primitive-admin 1.1.0-alpha.6 → 1.1.0-alpha.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (387) hide show
  1. package/README.md +389 -71
  2. package/assets/skill/skills/primitive-platform/SKILL.md +670 -0
  3. package/dist/bin/primitive.d.ts +2 -0
  4. package/dist/bin/primitive.js +287 -17
  5. package/dist/bin/primitive.js.map +1 -1
  6. package/dist/src/commands/admins.d.ts +2 -0
  7. package/dist/src/commands/admins.js +138 -19
  8. package/dist/src/commands/admins.js.map +1 -1
  9. package/dist/src/commands/analytics.d.ts +2 -0
  10. package/dist/src/commands/analytics.js +554 -55
  11. package/dist/src/commands/analytics.js.map +1 -1
  12. package/dist/src/commands/apps.d.ts +2 -0
  13. package/dist/src/commands/apps.js +27 -80
  14. package/dist/src/commands/apps.js.map +1 -1
  15. package/dist/src/commands/auth.d.ts +2 -0
  16. package/dist/src/commands/auth.js +177 -7
  17. package/dist/src/commands/auth.js.map +1 -1
  18. package/dist/src/commands/blob-buckets.d.ts +2 -0
  19. package/dist/src/commands/blob-buckets.js +330 -0
  20. package/dist/src/commands/blob-buckets.js.map +1 -0
  21. package/dist/src/commands/catalog.d.ts +2 -0
  22. package/dist/src/commands/catalog.js +37 -38
  23. package/dist/src/commands/catalog.js.map +1 -1
  24. package/dist/src/commands/collection-type-configs.d.ts +2 -0
  25. package/dist/src/commands/collection-type-configs.js +92 -0
  26. package/dist/src/commands/collection-type-configs.js.map +1 -0
  27. package/dist/src/commands/collections.d.ts +2 -0
  28. package/dist/src/commands/collections.js +526 -0
  29. package/dist/src/commands/collections.js.map +1 -0
  30. package/dist/src/commands/comparisons.d.ts +2 -0
  31. package/dist/src/commands/comparisons.js +6 -6
  32. package/dist/src/commands/comparisons.js.map +1 -1
  33. package/dist/src/commands/config.d.ts +35 -0
  34. package/dist/src/commands/config.js +437 -0
  35. package/dist/src/commands/config.js.map +1 -0
  36. package/dist/src/commands/connections.d.ts +2 -0
  37. package/dist/src/commands/connections.js +100 -0
  38. package/dist/src/commands/connections.js.map +1 -0
  39. package/dist/src/commands/cron-triggers.d.ts +2 -0
  40. package/dist/src/commands/cron-triggers.js +204 -0
  41. package/dist/src/commands/cron-triggers.js.map +1 -0
  42. package/dist/src/commands/database-types.d.ts +2 -0
  43. package/dist/src/commands/database-types.js +171 -0
  44. package/dist/src/commands/database-types.js.map +1 -0
  45. package/dist/src/commands/databases.d.ts +65 -0
  46. package/dist/src/commands/databases.js +2153 -96
  47. package/dist/src/commands/databases.js.map +1 -1
  48. package/dist/src/commands/documents.d.ts +2 -0
  49. package/dist/src/commands/documents.js +1230 -19
  50. package/dist/src/commands/documents.js.map +1 -1
  51. package/dist/src/commands/email-templates.d.ts +2 -0
  52. package/dist/src/commands/email-templates.js +174 -0
  53. package/dist/src/commands/email-templates.js.map +1 -0
  54. package/dist/src/commands/env.d.ts +12 -0
  55. package/dist/src/commands/env.js +260 -0
  56. package/dist/src/commands/env.js.map +1 -0
  57. package/dist/src/commands/group-type-configs.d.ts +2 -0
  58. package/dist/src/commands/group-type-configs.js +86 -0
  59. package/dist/src/commands/group-type-configs.js.map +1 -0
  60. package/dist/src/commands/groups.d.ts +2 -0
  61. package/dist/src/commands/groups.js +38 -99
  62. package/dist/src/commands/groups.js.map +1 -1
  63. package/dist/src/commands/guides.d.ts +223 -0
  64. package/dist/src/commands/guides.js +617 -65
  65. package/dist/src/commands/guides.js.map +1 -1
  66. package/dist/src/commands/init.d.ts +17 -0
  67. package/dist/src/commands/init.js +964 -202
  68. package/dist/src/commands/init.js.map +1 -1
  69. package/dist/src/commands/integrations.d.ts +2 -0
  70. package/dist/src/commands/integrations.js +484 -205
  71. package/dist/src/commands/integrations.js.map +1 -1
  72. package/dist/src/commands/llm.d.ts +2 -0
  73. package/dist/src/commands/llm.js +13 -8
  74. package/dist/src/commands/llm.js.map +1 -1
  75. package/dist/src/commands/locks.d.ts +8 -0
  76. package/dist/src/commands/locks.js +160 -0
  77. package/dist/src/commands/locks.js.map +1 -0
  78. package/dist/src/commands/metadata.d.ts +2 -0
  79. package/dist/src/commands/metadata.js +406 -0
  80. package/dist/src/commands/metadata.js.map +1 -0
  81. package/dist/src/commands/prompts.d.ts +2 -0
  82. package/dist/src/commands/prompts.js +135 -355
  83. package/dist/src/commands/prompts.js.map +1 -1
  84. package/dist/src/commands/rule-sets.d.ts +3 -0
  85. package/dist/src/commands/rule-sets.js +271 -0
  86. package/dist/src/commands/rule-sets.js.map +1 -0
  87. package/dist/src/commands/scripts.d.ts +20 -0
  88. package/dist/src/commands/scripts.js +739 -0
  89. package/dist/src/commands/scripts.js.map +1 -0
  90. package/dist/src/commands/secrets.d.ts +2 -0
  91. package/dist/src/commands/secrets.js +108 -0
  92. package/dist/src/commands/secrets.js.map +1 -0
  93. package/dist/src/commands/sessions.d.ts +2 -0
  94. package/dist/src/commands/sessions.js +75 -0
  95. package/dist/src/commands/sessions.js.map +1 -0
  96. package/dist/src/commands/settings.d.ts +18 -0
  97. package/dist/src/commands/settings.js +54 -0
  98. package/dist/src/commands/settings.js.map +1 -0
  99. package/dist/src/commands/skill.d.ts +2 -0
  100. package/dist/src/commands/skill.js +29 -0
  101. package/dist/src/commands/skill.js.map +1 -0
  102. package/dist/src/commands/sync-app-settings.d.ts +125 -0
  103. package/dist/src/commands/sync-app-settings.js +380 -0
  104. package/dist/src/commands/sync-app-settings.js.map +1 -0
  105. package/dist/src/commands/sync.d.ts +958 -0
  106. package/dist/src/commands/sync.js +8954 -812
  107. package/dist/src/commands/sync.js.map +1 -1
  108. package/dist/src/commands/tokens.d.ts +2 -0
  109. package/dist/src/commands/tokens.js +130 -21
  110. package/dist/src/commands/tokens.js.map +1 -1
  111. package/dist/src/commands/users.d.ts +2 -0
  112. package/dist/src/commands/users.js +440 -22
  113. package/dist/src/commands/users.js.map +1 -1
  114. package/dist/src/commands/vars.d.ts +8 -0
  115. package/dist/src/commands/vars.js +96 -0
  116. package/dist/src/commands/vars.js.map +1 -0
  117. package/dist/src/commands/waitlist.d.ts +2 -0
  118. package/dist/src/commands/waitlist.js +10 -10
  119. package/dist/src/commands/waitlist.js.map +1 -1
  120. package/dist/src/commands/webhooks.d.ts +2 -0
  121. package/dist/src/commands/webhooks.js +442 -0
  122. package/dist/src/commands/webhooks.js.map +1 -0
  123. package/dist/src/commands/workflows.d.ts +94 -0
  124. package/dist/src/commands/workflows.js +1581 -448
  125. package/dist/src/commands/workflows.js.map +1 -1
  126. package/dist/src/lib/api-client.d.ts +1814 -0
  127. package/dist/src/lib/api-client.js +1655 -103
  128. package/dist/src/lib/api-client.js.map +1 -1
  129. package/dist/src/lib/app-settings-descriptor.d.ts +130 -0
  130. package/dist/src/lib/app-settings-descriptor.js +262 -0
  131. package/dist/src/lib/app-settings-descriptor.js.map +1 -0
  132. package/dist/src/lib/auth-flow.d.ts +8 -0
  133. package/dist/src/lib/batch.d.ts +26 -0
  134. package/dist/src/lib/batch.js +32 -0
  135. package/dist/src/lib/batch.js.map +1 -0
  136. package/dist/src/lib/block-layout.d.ts +160 -0
  137. package/dist/src/lib/block-layout.js +451 -0
  138. package/dist/src/lib/block-layout.js.map +1 -0
  139. package/dist/src/lib/canonical-json.d.ts +12 -0
  140. package/dist/src/lib/canonical-json.js +35 -0
  141. package/dist/src/lib/canonical-json.js.map +1 -0
  142. package/dist/src/lib/channel.d.ts +30 -0
  143. package/dist/src/lib/channel.js +68 -0
  144. package/dist/src/lib/channel.js.map +1 -0
  145. package/dist/src/lib/cli-manifest.d.ts +68 -0
  146. package/dist/src/lib/cli-manifest.js +71 -0
  147. package/dist/src/lib/cli-manifest.js.map +1 -0
  148. package/dist/src/lib/codegen-shared/generatedFiles.d.ts +97 -0
  149. package/dist/src/lib/codegen-shared/generatedFiles.js +184 -0
  150. package/dist/src/lib/codegen-shared/generatedFiles.js.map +1 -0
  151. package/dist/src/lib/codegen-shared/prettierStable.d.ts +262 -0
  152. package/dist/src/lib/codegen-shared/prettierStable.js +610 -0
  153. package/dist/src/lib/codegen-shared/prettierStable.js.map +1 -0
  154. package/dist/src/lib/codegen-shared/resolveCodegenSourceDir.d.ts +68 -0
  155. package/dist/src/lib/codegen-shared/resolveCodegenSourceDir.js +168 -0
  156. package/dist/src/lib/codegen-shared/resolveCodegenSourceDir.js.map +1 -0
  157. package/dist/src/lib/config-object-descriptor.d.ts +108 -0
  158. package/dist/src/lib/config-object-descriptor.js +607 -0
  159. package/dist/src/lib/config-object-descriptor.js.map +1 -0
  160. package/dist/src/lib/config-payload.d.ts +85 -0
  161. package/dist/src/lib/config-payload.js +105 -0
  162. package/dist/src/lib/config-payload.js.map +1 -0
  163. package/dist/src/lib/config-surface.d.ts +93 -0
  164. package/dist/src/lib/config-surface.js +178 -0
  165. package/dist/src/lib/config-surface.js.map +1 -0
  166. package/dist/src/lib/config-toml.d.ts +10 -0
  167. package/dist/src/lib/config-toml.js +42 -0
  168. package/dist/src/lib/config-toml.js.map +1 -0
  169. package/dist/src/lib/config.d.ts +53 -0
  170. package/dist/src/lib/config.js +92 -53
  171. package/dist/src/lib/config.js.map +1 -1
  172. package/dist/src/lib/confirm-prompt.d.ts +83 -0
  173. package/dist/src/lib/confirm-prompt.js +110 -0
  174. package/dist/src/lib/confirm-prompt.js.map +1 -0
  175. package/dist/src/lib/constants.d.ts +11 -0
  176. package/dist/src/lib/constants.js +12 -0
  177. package/dist/src/lib/constants.js.map +1 -0
  178. package/dist/src/lib/crash-handlers.d.ts +20 -0
  179. package/dist/src/lib/crash-handlers.js +49 -0
  180. package/dist/src/lib/crash-handlers.js.map +1 -0
  181. package/dist/src/lib/credentials-store.d.ts +89 -0
  182. package/dist/src/lib/credentials-store.js +330 -0
  183. package/dist/src/lib/credentials-store.js.map +1 -0
  184. package/dist/src/lib/csv.d.ts +47 -0
  185. package/dist/src/lib/csv.js +172 -0
  186. package/dist/src/lib/csv.js.map +1 -0
  187. package/dist/src/lib/data-input.d.ts +23 -0
  188. package/dist/src/lib/data-input.js +50 -0
  189. package/dist/src/lib/data-input.js.map +1 -0
  190. package/dist/src/lib/db-codegen/dbFingerprint.d.ts +10 -0
  191. package/dist/src/lib/db-codegen/dbFingerprint.js +17 -0
  192. package/dist/src/lib/db-codegen/dbFingerprint.js.map +1 -0
  193. package/dist/src/lib/db-codegen/dbGenerator.d.ts +67 -0
  194. package/dist/src/lib/db-codegen/dbGenerator.js +170 -0
  195. package/dist/src/lib/db-codegen/dbGenerator.js.map +1 -0
  196. package/dist/src/lib/db-codegen/dbNaming.d.ts +87 -0
  197. package/dist/src/lib/db-codegen/dbNaming.js +180 -0
  198. package/dist/src/lib/db-codegen/dbNaming.js.map +1 -0
  199. package/dist/src/lib/db-codegen/dbTemplates.d.ts +272 -0
  200. package/dist/src/lib/db-codegen/dbTemplates.js +480 -0
  201. package/dist/src/lib/db-codegen/dbTemplates.js.map +1 -0
  202. package/dist/src/lib/db-codegen/dbTsTypes.d.ts +73 -0
  203. package/dist/src/lib/db-codegen/dbTsTypes.js +139 -0
  204. package/dist/src/lib/db-codegen/dbTsTypes.js.map +1 -0
  205. package/dist/src/lib/db-codegen/dbTypeIR.d.ts +146 -0
  206. package/dist/src/lib/db-codegen/dbTypeIR.js +517 -0
  207. package/dist/src/lib/db-codegen/dbTypeIR.js.map +1 -0
  208. package/dist/src/lib/db-codegen/generated-operation-def-descriptor.d.ts +112 -0
  209. package/dist/src/lib/db-codegen/generated-operation-def-descriptor.js +211 -0
  210. package/dist/src/lib/db-codegen/generated-operation-def-descriptor.js.map +1 -0
  211. package/dist/src/lib/env-resolver.d.ts +62 -0
  212. package/dist/src/lib/env-resolver.js +121 -0
  213. package/dist/src/lib/env-resolver.js.map +1 -0
  214. package/dist/src/lib/fetch.d.ts +5 -0
  215. package/dist/src/lib/generated-allowlist.d.ts +28 -0
  216. package/dist/src/lib/generated-allowlist.js +266 -0
  217. package/dist/src/lib/generated-allowlist.js.map +1 -0
  218. package/dist/src/lib/generated-config-surfaces.d.ts +578 -0
  219. package/dist/src/lib/generated-config-surfaces.js +3630 -0
  220. package/dist/src/lib/generated-config-surfaces.js.map +1 -0
  221. package/dist/src/lib/generated-template-lint.d.ts +206 -0
  222. package/dist/src/lib/generated-template-lint.js +589 -0
  223. package/dist/src/lib/generated-template-lint.js.map +1 -0
  224. package/dist/src/lib/generated-workflow-model-fields.d.ts +20 -0
  225. package/dist/src/lib/generated-workflow-model-fields.js +53 -0
  226. package/dist/src/lib/generated-workflow-model-fields.js.map +1 -0
  227. package/dist/src/lib/google-client-secret-status.d.ts +35 -0
  228. package/dist/src/lib/google-client-secret-status.js +56 -0
  229. package/dist/src/lib/google-client-secret-status.js.map +1 -0
  230. package/dist/src/lib/init-config.d.ts +81 -0
  231. package/dist/src/lib/init-config.js +149 -0
  232. package/dist/src/lib/init-config.js.map +1 -0
  233. package/dist/src/lib/log-inspection.d.ts +568 -0
  234. package/dist/src/lib/log-inspection.js +639 -0
  235. package/dist/src/lib/log-inspection.js.map +1 -0
  236. package/dist/src/lib/migration-nag.d.ts +49 -0
  237. package/dist/src/lib/migration-nag.js +163 -0
  238. package/dist/src/lib/migration-nag.js.map +1 -0
  239. package/dist/src/lib/output.d.ts +109 -0
  240. package/dist/src/lib/output.js +191 -8
  241. package/dist/src/lib/output.js.map +1 -1
  242. package/dist/src/lib/package-manager.d.ts +140 -0
  243. package/dist/src/lib/package-manager.js +305 -0
  244. package/dist/src/lib/package-manager.js.map +1 -0
  245. package/dist/src/lib/paginate.d.ts +83 -0
  246. package/dist/src/lib/paginate.js +95 -0
  247. package/dist/src/lib/paginate.js.map +1 -0
  248. package/dist/src/lib/platform-owned.d.ts +51 -0
  249. package/dist/src/lib/platform-owned.js +64 -0
  250. package/dist/src/lib/platform-owned.js.map +1 -0
  251. package/dist/src/lib/project-config.d.ts +97 -0
  252. package/dist/src/lib/project-config.js +219 -0
  253. package/dist/src/lib/project-config.js.map +1 -0
  254. package/dist/src/lib/query-operators.d.ts +43 -0
  255. package/dist/src/lib/query-operators.js +80 -0
  256. package/dist/src/lib/query-operators.js.map +1 -0
  257. package/dist/src/lib/record-filter.d.ts +18 -0
  258. package/dist/src/lib/record-filter.js +55 -0
  259. package/dist/src/lib/record-filter.js.map +1 -0
  260. package/dist/src/lib/refresh-admin-credentials.d.ts +65 -0
  261. package/dist/src/lib/refresh-admin-credentials.js +103 -0
  262. package/dist/src/lib/refresh-admin-credentials.js.map +1 -0
  263. package/dist/src/lib/resolve-init-dev-port.d.ts +56 -0
  264. package/dist/src/lib/resolve-init-dev-port.js +55 -0
  265. package/dist/src/lib/resolve-init-dev-port.js.map +1 -0
  266. package/dist/src/lib/resolve-init-server.d.ts +71 -0
  267. package/dist/src/lib/resolve-init-server.js +94 -0
  268. package/dist/src/lib/resolve-init-server.js.map +1 -0
  269. package/dist/src/lib/resolve-platform.d.ts +45 -0
  270. package/dist/src/lib/resolve-platform.js +43 -0
  271. package/dist/src/lib/resolve-platform.js.map +1 -0
  272. package/dist/src/lib/run-status.d.ts +19 -0
  273. package/dist/src/lib/run-status.generated.d.ts +39 -0
  274. package/dist/src/lib/run-status.generated.js +66 -0
  275. package/dist/src/lib/run-status.generated.js.map +1 -0
  276. package/dist/src/lib/run-status.js +19 -0
  277. package/dist/src/lib/run-status.js.map +1 -0
  278. package/dist/src/lib/signing-secret-status.d.ts +81 -0
  279. package/dist/src/lib/signing-secret-status.js +116 -0
  280. package/dist/src/lib/signing-secret-status.js.map +1 -0
  281. package/dist/src/lib/skill-installer.d.ts +25 -0
  282. package/dist/src/lib/skill-installer.js +266 -0
  283. package/dist/src/lib/skill-installer.js.map +1 -0
  284. package/dist/src/lib/snapshots.d.ts +99 -0
  285. package/dist/src/lib/snapshots.js +357 -0
  286. package/dist/src/lib/snapshots.js.map +1 -0
  287. package/dist/src/lib/swift-codegen/dbGenerator.d.ts +100 -0
  288. package/dist/src/lib/swift-codegen/dbGenerator.js +682 -0
  289. package/dist/src/lib/swift-codegen/dbGenerator.js.map +1 -0
  290. package/dist/src/lib/swift-codegen/dbSwiftTypes.d.ts +42 -0
  291. package/dist/src/lib/swift-codegen/dbSwiftTypes.js +100 -0
  292. package/dist/src/lib/swift-codegen/dbSwiftTypes.js.map +1 -0
  293. package/dist/src/lib/swift-codegen/generator.d.ts +85 -0
  294. package/dist/src/lib/swift-codegen/generator.js +266 -0
  295. package/dist/src/lib/swift-codegen/generator.js.map +1 -0
  296. package/dist/src/lib/swift-codegen/schemaToSwift.d.ts +72 -0
  297. package/dist/src/lib/swift-codegen/schemaToSwift.js +644 -0
  298. package/dist/src/lib/swift-codegen/schemaToSwift.js.map +1 -0
  299. package/dist/src/lib/swift-codegen/siblingSymbols.d.ts +90 -0
  300. package/dist/src/lib/swift-codegen/siblingSymbols.js +152 -0
  301. package/dist/src/lib/swift-codegen/siblingSymbols.js.map +1 -0
  302. package/dist/src/lib/swift-codegen/swiftNaming.d.ts +85 -0
  303. package/dist/src/lib/swift-codegen/swiftNaming.js +198 -0
  304. package/dist/src/lib/swift-codegen/swiftNaming.js.map +1 -0
  305. package/dist/src/lib/sync-paths.d.ts +72 -0
  306. package/dist/src/lib/sync-paths.js +130 -0
  307. package/dist/src/lib/sync-paths.js.map +1 -0
  308. package/dist/src/lib/sync-resource-types.d.ts +445 -0
  309. package/dist/src/lib/sync-resource-types.js +812 -0
  310. package/dist/src/lib/sync-resource-types.js.map +1 -0
  311. package/dist/src/lib/sync-selectors.d.ts +95 -0
  312. package/dist/src/lib/sync-selectors.js +228 -0
  313. package/dist/src/lib/sync-selectors.js.map +1 -0
  314. package/dist/src/lib/template.d.ts +121 -0
  315. package/dist/src/lib/template.js +447 -67
  316. package/dist/src/lib/template.js.map +1 -1
  317. package/dist/src/lib/token-inject.d.ts +56 -0
  318. package/dist/src/lib/token-inject.js +204 -0
  319. package/dist/src/lib/token-inject.js.map +1 -0
  320. package/dist/src/lib/toml-database-config.d.ts +123 -0
  321. package/dist/src/lib/toml-database-config.js +527 -0
  322. package/dist/src/lib/toml-database-config.js.map +1 -0
  323. package/dist/src/lib/toml-metadata-config.d.ts +151 -0
  324. package/dist/src/lib/toml-metadata-config.js +476 -0
  325. package/dist/src/lib/toml-metadata-config.js.map +1 -0
  326. package/dist/src/lib/toml-native-form.d.ts +46 -0
  327. package/dist/src/lib/toml-native-form.js +78 -0
  328. package/dist/src/lib/toml-native-form.js.map +1 -0
  329. package/dist/src/lib/toml-params-validator.d.ts +129 -0
  330. package/dist/src/lib/toml-params-validator.js +298 -0
  331. package/dist/src/lib/toml-params-validator.js.map +1 -0
  332. package/dist/src/lib/toml-scalar-edit.d.ts +43 -0
  333. package/dist/src/lib/toml-scalar-edit.js +283 -0
  334. package/dist/src/lib/toml-scalar-edit.js.map +1 -0
  335. package/dist/src/lib/user-selector.d.ts +24 -0
  336. package/dist/src/lib/user-selector.js +33 -0
  337. package/dist/src/lib/user-selector.js.map +1 -0
  338. package/dist/src/lib/version-check.d.ts +35 -0
  339. package/dist/src/lib/version-check.js +241 -0
  340. package/dist/src/lib/version-check.js.map +1 -0
  341. package/dist/src/lib/watch.d.ts +121 -0
  342. package/dist/src/lib/watch.js +169 -0
  343. package/dist/src/lib/watch.js.map +1 -0
  344. package/dist/src/lib/workflow-apply.d.ts +51 -0
  345. package/dist/src/lib/workflow-apply.js +89 -0
  346. package/dist/src/lib/workflow-apply.js.map +1 -0
  347. package/dist/src/lib/workflow-codegen/generated-schema-descriptor.d.ts +129 -0
  348. package/dist/src/lib/workflow-codegen/generated-schema-descriptor.js +269 -0
  349. package/dist/src/lib/workflow-codegen/generated-schema-descriptor.js.map +1 -0
  350. package/dist/src/lib/workflow-codegen/generator.d.ts +96 -0
  351. package/dist/src/lib/workflow-codegen/generator.js +361 -0
  352. package/dist/src/lib/workflow-codegen/generator.js.map +1 -0
  353. package/dist/src/lib/workflow-codegen/invokerIR.d.ts +83 -0
  354. package/dist/src/lib/workflow-codegen/invokerIR.js +71 -0
  355. package/dist/src/lib/workflow-codegen/invokerIR.js.map +1 -0
  356. package/dist/src/lib/workflow-codegen/naming.d.ts +33 -0
  357. package/dist/src/lib/workflow-codegen/naming.js +81 -0
  358. package/dist/src/lib/workflow-codegen/naming.js.map +1 -0
  359. package/dist/src/lib/workflow-codegen/schemaToTs.d.ts +80 -0
  360. package/dist/src/lib/workflow-codegen/schemaToTs.js +303 -0
  361. package/dist/src/lib/workflow-codegen/schemaToTs.js.map +1 -0
  362. package/dist/src/lib/workflow-config-apply.d.ts +70 -0
  363. package/dist/src/lib/workflow-config-apply.js +137 -0
  364. package/dist/src/lib/workflow-config-apply.js.map +1 -0
  365. package/dist/src/lib/workflow-config-sidecar.d.ts +63 -0
  366. package/dist/src/lib/workflow-config-sidecar.js +96 -0
  367. package/dist/src/lib/workflow-config-sidecar.js.map +1 -0
  368. package/dist/src/lib/workflow-field-descriptor.d.ts +91 -0
  369. package/dist/src/lib/workflow-field-descriptor.js +153 -0
  370. package/dist/src/lib/workflow-field-descriptor.js.map +1 -0
  371. package/dist/src/lib/workflow-fragments.d.ts +64 -0
  372. package/dist/src/lib/workflow-fragments.js +342 -0
  373. package/dist/src/lib/workflow-fragments.js.map +1 -0
  374. package/dist/src/lib/workflow-include-preserve.d.ts +71 -0
  375. package/dist/src/lib/workflow-include-preserve.js +153 -0
  376. package/dist/src/lib/workflow-include-preserve.js.map +1 -0
  377. package/dist/src/lib/workflow-payload.d.ts +86 -0
  378. package/dist/src/lib/workflow-payload.js +168 -0
  379. package/dist/src/lib/workflow-payload.js.map +1 -0
  380. package/dist/src/lib/workflow-toml-validator.d.ts +199 -0
  381. package/dist/src/lib/workflow-toml-validator.js +754 -0
  382. package/dist/src/lib/workflow-toml-validator.js.map +1 -0
  383. package/dist/src/types/index.d.ts +533 -0
  384. package/dist/src/validators.d.ts +65 -0
  385. package/dist/src/validators.js +64 -0
  386. package/dist/src/validators.js.map +1 -0
  387. package/package.json +32 -6
@@ -1,15 +1,748 @@
1
1
  import { ApiClient } from "../lib/api-client.js";
2
2
  import { resolveAppId } from "../lib/config.js";
3
- import { success, error, info, formatTable, formatDate, json, } from "../lib/output.js";
3
+ import { success, error, info, formatTable, formatId, formatDate, json, keyValue, result as printResult, warn, } from "../lib/output.js";
4
+ import { confirmPrompt } from "../lib/confirm-prompt.js";
5
+ import { parseDataOption } from "../lib/data-input.js";
6
+ import { parseFilterOptions } from "../lib/record-filter.js";
7
+ import { ulid } from "ulid";
8
+ import * as fs from "fs";
9
+ import * as path from "path";
4
10
  export function registerDocumentsCommands(program) {
5
11
  const documents = program
6
12
  .command("documents")
7
13
  .description("Manage documents within an app")
8
14
  .addHelpText("after", `
9
15
  Examples:
16
+ $ primitive documents list --user-id <user-id>
17
+ $ primitive documents get <document-id>
18
+ $ primitive documents permissions list <document-id>
19
+ $ primitive documents permissions grant <document-id> --user-id <user-id> --permission reader
20
+ $ primitive documents permissions revoke <document-id> <user-id>
21
+ $ primitive documents records models <document-id>
22
+ $ primitive documents records describe <document-id> <model-name>
23
+ $ primitive documents records query <document-id> <model-name> --filter '{"status":"open"}'
24
+ $ primitive documents records count <document-id> <model-name>
25
+ $ primitive documents records save <document-id> <model-name> --data '{"qty":10}'
26
+ $ primitive documents records patch <document-id> <model-name> <record-id> --data '{"qty":11}'
27
+ $ primitive documents records delete <document-id> <model-name> <record-id> -y
28
+ $ primitive documents records aggregate <document-id> <model-name> --op avg --field price
29
+ $ primitive documents records bulk <document-id> --data-file ops.json -y
30
+ $ primitive documents dump <document-id>
31
+ $ primitive documents stats <document-id>
10
32
  $ primitive documents transfer-owner <document-id> <new-owner-id>
11
33
  $ primitive documents group-permissions list <document-id>
12
34
  `);
35
+ // ---- List a user's documents ----
36
+ // No app-wide enumeration: `--user-id` is required (the admin token has no
37
+ // "self"). Reads the per-user permission partition via the admin endpoint.
38
+ documents
39
+ .command("list")
40
+ .description("List a user's documents")
41
+ .requiredOption("--user-id <id>", "User ID whose documents to list")
42
+ .option("--app <app-id>", "App ID")
43
+ .option("--json", "Output as JSON")
44
+ .action(async (options) => {
45
+ const resolvedAppId = resolveAppId(undefined, options);
46
+ const client = new ApiClient();
47
+ try {
48
+ const list = await client.listAdminDocuments(resolvedAppId, options.userId);
49
+ if (options.json) {
50
+ json(list);
51
+ return;
52
+ }
53
+ if (list.length === 0) {
54
+ info("No documents found.");
55
+ return;
56
+ }
57
+ console.log(formatTable(list, [
58
+ { header: "DOCUMENT_ID", key: "documentId", format: formatId },
59
+ { header: "TITLE", key: "title", flex: true },
60
+ { header: "PERMISSION", key: "permission" },
61
+ { header: "GRANTED", key: "grantedAt", format: formatDate },
62
+ ]));
63
+ }
64
+ catch (err) {
65
+ error(err.message);
66
+ process.exit(1);
67
+ }
68
+ });
69
+ // ---- Get a single document's metadata ----
70
+ documents
71
+ .command("get")
72
+ .description("Show a document's metadata and the caller's access to it")
73
+ .argument("<document-id>", "Document ID")
74
+ .option("--app <app-id>", "App ID")
75
+ .option("--json", "Output as JSON")
76
+ .action(async (documentId, options) => {
77
+ const resolvedAppId = resolveAppId(undefined, options);
78
+ const client = new ApiClient();
79
+ try {
80
+ const doc = await client.getDocument(resolvedAppId, documentId);
81
+ if (options.json) {
82
+ json(doc);
83
+ return;
84
+ }
85
+ keyValue("Document ID", doc.documentId);
86
+ keyValue("Title", doc.title);
87
+ keyValue("Created By", doc.createdBy);
88
+ keyValue("Created", formatDate(doc.createdAt));
89
+ keyValue("Modified", formatDate(doc.modifiedAt ?? doc.lastModified));
90
+ // `GET documents/:id` reports the caller's own access, not the
91
+ // document's grant/alias/collection inventory — printing counts for
92
+ // fields the endpoint never returns read as a definitive "0" for
93
+ // documents that demonstrably have them. Use
94
+ // `documents permissions list` for the grant list.
95
+ if (doc.permission)
96
+ keyValue("Your Permission", doc.permission);
97
+ if (doc.accessSource)
98
+ keyValue("Access Source", doc.accessSource);
99
+ if (doc.linkAccess)
100
+ keyValue("Link Access", doc.linkAccess);
101
+ }
102
+ catch (err) {
103
+ error(err.message);
104
+ process.exit(1);
105
+ }
106
+ });
107
+ // ---- User-level permissions subcommand group ----
108
+ const permissions = documents
109
+ .command("permissions")
110
+ .description("Manage user-level permissions on a document");
111
+ // List user-level permissions
112
+ permissions
113
+ .command("list")
114
+ .description("List user-level permissions for a document")
115
+ .argument("<document-id>", "Document ID")
116
+ .option("--app <app-id>", "App ID")
117
+ .option("--json", "Output as JSON")
118
+ .action(async (documentId, options) => {
119
+ const resolvedAppId = resolveAppId(undefined, options);
120
+ const client = new ApiClient();
121
+ try {
122
+ const result = await client.listDocumentPermissions(resolvedAppId, documentId);
123
+ const list = Array.isArray(result) ? result : result?.permissions ?? [];
124
+ if (options.json) {
125
+ json(list);
126
+ return;
127
+ }
128
+ if (list.length === 0) {
129
+ info("No permissions found.");
130
+ return;
131
+ }
132
+ console.log(formatTable(list, [
133
+ { header: "USER_ID", key: "userId", format: formatId },
134
+ { header: "EMAIL", key: "email", flex: true },
135
+ { header: "PERMISSION", key: "permission" },
136
+ { header: "GRANTED", key: "grantedAt", format: formatDate },
137
+ ]));
138
+ }
139
+ catch (err) {
140
+ error(err.message);
141
+ process.exit(1);
142
+ }
143
+ });
144
+ // Grant (or update) a user-level permission
145
+ permissions
146
+ .command("grant")
147
+ .description("Grant or update a user's permission on a document")
148
+ .argument("<document-id>", "Document ID")
149
+ .option("--user-id <id>", "User ID to grant the permission to")
150
+ .option("--email <email>", "Email of the user to grant the permission to")
151
+ .requiredOption("--permission <permission>", "Permission level: reader or read-write")
152
+ .option("--app <app-id>", "App ID")
153
+ .option("--json", "Output as JSON")
154
+ .action(async (documentId, options) => {
155
+ if (!options.userId && !options.email) {
156
+ error("Either --user-id or --email is required.");
157
+ process.exit(1);
158
+ }
159
+ if (options.userId && options.email) {
160
+ error("Provide only one of --user-id or --email, not both.");
161
+ process.exit(1);
162
+ }
163
+ if (!["reader", "read-write"].includes(options.permission)) {
164
+ error("Invalid --permission. Must be 'reader' or 'read-write'.");
165
+ process.exit(1);
166
+ }
167
+ const resolvedAppId = resolveAppId(undefined, options);
168
+ const client = new ApiClient();
169
+ try {
170
+ const entry = options.userId
171
+ ? { userId: options.userId, permission: options.permission }
172
+ : { email: options.email, permission: options.permission };
173
+ const result = await client.grantDocumentPermission(resolvedAppId, documentId, [entry]);
174
+ if (options.json) {
175
+ json(result);
176
+ return;
177
+ }
178
+ const target = options.userId ? options.userId : options.email;
179
+ success(`Permission '${options.permission}' granted to ${target}.`);
180
+ }
181
+ catch (err) {
182
+ error(err.message);
183
+ process.exit(1);
184
+ }
185
+ });
186
+ // Revoke a user-level permission
187
+ permissions
188
+ .command("revoke")
189
+ .description("Revoke a user's permission on a document")
190
+ .argument("<document-id>", "Document ID")
191
+ .argument("[user-id]", "User ID to revoke (or use --email)")
192
+ .option("--email <email>", "Email of the user to revoke (alternative to <user-id>)")
193
+ .option("--app <app-id>", "App ID")
194
+ .option("-y, --yes", "Skip confirmation prompt")
195
+ .action(async (documentId, userId, options) => {
196
+ if (!userId && !options.email) {
197
+ error("Either a <user-id> argument or --email is required.");
198
+ process.exit(1);
199
+ }
200
+ if (userId && options.email) {
201
+ error("Provide only one of <user-id> or --email, not both.");
202
+ process.exit(1);
203
+ }
204
+ const target = userId ?? options.email;
205
+ const resolvedAppId = resolveAppId(undefined, options);
206
+ if (!options.yes) {
207
+ let confirm;
208
+ try {
209
+ confirm = await confirmPrompt(`Revoke permission for ${target} on document ${documentId}?`);
210
+ }
211
+ catch (err) {
212
+ error(err.message);
213
+ process.exit(1);
214
+ }
215
+ if (!confirm) {
216
+ info("Cancelled.");
217
+ return;
218
+ }
219
+ }
220
+ const client = new ApiClient();
221
+ try {
222
+ await client.revokeDocumentPermission(resolvedAppId, documentId, {
223
+ userId,
224
+ email: options.email,
225
+ });
226
+ success(`Permission revoked for ${target}.`);
227
+ }
228
+ catch (err) {
229
+ error(err.message);
230
+ process.exit(1);
231
+ }
232
+ });
233
+ // ---- Records introspection subcommand group ----
234
+ const records = documents
235
+ .command("records")
236
+ .description("Inspect a document's models and records");
237
+ // List model names
238
+ records
239
+ .command("models")
240
+ .description("List model names in a document")
241
+ .argument("<document-id>", "Document ID")
242
+ .option("--app <app-id>", "App ID")
243
+ .option("--json", "Output as JSON")
244
+ .action(async (documentId, options) => {
245
+ const resolvedAppId = resolveAppId(undefined, options);
246
+ const client = new ApiClient();
247
+ try {
248
+ const result = await client.getDocumentSchema(resolvedAppId, documentId);
249
+ const models = result?.modelNames ?? Object.keys(result?.schema?.models ?? {});
250
+ if (options.json) {
251
+ json(models);
252
+ return;
253
+ }
254
+ if (models.length === 0) {
255
+ info("No models found.");
256
+ return;
257
+ }
258
+ for (const m of models) {
259
+ console.log(` ${m}`);
260
+ }
261
+ }
262
+ catch (err) {
263
+ error(err.message);
264
+ process.exit(1);
265
+ }
266
+ });
267
+ // Describe a model's fields and indexes
268
+ records
269
+ .command("describe")
270
+ .description("Show a model's fields and indexes")
271
+ .argument("<document-id>", "Document ID")
272
+ .argument("<model-name>", "Model name")
273
+ .option("--app <app-id>", "App ID")
274
+ .option("--json", "Output as JSON")
275
+ .action(async (documentId, modelName, options) => {
276
+ const resolvedAppId = resolveAppId(undefined, options);
277
+ const client = new ApiClient();
278
+ try {
279
+ const result = await client.getDocumentSchema(resolvedAppId, documentId);
280
+ const model = result?.schema?.models?.[modelName];
281
+ if (!model) {
282
+ if (options.json) {
283
+ json(null);
284
+ return;
285
+ }
286
+ info(`Model '${modelName}' not found in this document.`);
287
+ return;
288
+ }
289
+ const fieldsObj = model.fields ?? {};
290
+ const rows = Object.entries(fieldsObj).map(([name, meta]) => ({
291
+ field: name,
292
+ type: meta?.type ?? "unknown",
293
+ indexed: meta?.indexed ? "yes" : "",
294
+ unique: meta?.unique ? "yes" : "",
295
+ required: meta?.required ? "yes" : "",
296
+ }));
297
+ if (options.json) {
298
+ json({ fields: fieldsObj, constraints: model.constraints ?? {} });
299
+ return;
300
+ }
301
+ if (rows.length === 0) {
302
+ info("No fields detected for this model.");
303
+ return;
304
+ }
305
+ console.log(formatTable(rows, [
306
+ { header: "FIELD", key: "field", flex: true },
307
+ { header: "TYPE", key: "type" },
308
+ { header: "INDEXED", key: "indexed" },
309
+ { header: "UNIQUE", key: "unique" },
310
+ { header: "REQUIRED", key: "required" },
311
+ ]));
312
+ }
313
+ catch (err) {
314
+ error(err.message);
315
+ process.exit(1);
316
+ }
317
+ });
318
+ // Query records in a document model
319
+ records
320
+ .command("query")
321
+ .description("Query records in a document model")
322
+ .argument("<document-id>", "Document ID")
323
+ .argument("<model-name>", "Model name to query")
324
+ .option("--app <app-id>", "App ID")
325
+ .option("--filter <json>", "Filter as JSON (e.g. '{\"status\":\"open\"}')")
326
+ .option("--filter-file <path>", "Read filter from a JSON or TOML file")
327
+ .option("--limit <n>", "Maximum number of records to return (max 100)", parseInt)
328
+ .option("--cursor <cursor>", "Pagination cursor from a previous query")
329
+ .option("--json", "Output as JSON")
330
+ .action(async (documentId, modelName, options) => {
331
+ const resolvedAppId = resolveAppId(undefined, options);
332
+ const filter = parseFilterOptions(options);
333
+ const client = new ApiClient();
334
+ try {
335
+ const result = await client.queryDocumentRecords(resolvedAppId, documentId, modelName, { filter, limit: options.limit, cursor: options.cursor });
336
+ if (options.json) {
337
+ json(result);
338
+ return;
339
+ }
340
+ const items = result.items;
341
+ if (items.length === 0) {
342
+ info("No records found.");
343
+ return;
344
+ }
345
+ const allKeys = new Set();
346
+ for (const rec of items) {
347
+ for (const key of Object.keys(rec))
348
+ allKeys.add(key);
349
+ }
350
+ const orderedKeys = [];
351
+ if (allKeys.has("id")) {
352
+ orderedKeys.push("id");
353
+ allKeys.delete("id");
354
+ }
355
+ orderedKeys.push(...[...allKeys].sort());
356
+ const columns = orderedKeys.map((key) => ({
357
+ header: key.toUpperCase(),
358
+ key,
359
+ format: (v) => {
360
+ if (v === null || v === undefined)
361
+ return "—";
362
+ if (typeof v === "object")
363
+ return JSON.stringify(v);
364
+ return String(v);
365
+ },
366
+ }));
367
+ console.log(formatTable(items, columns));
368
+ if (result.nextCursor) {
369
+ info(`More results available. Use --cursor ${result.nextCursor}`);
370
+ }
371
+ }
372
+ catch (err) {
373
+ error(err.message);
374
+ process.exit(1);
375
+ }
376
+ });
377
+ // Get a single record by id (mirrors `databases records get`, issue #2357).
378
+ records
379
+ .command("get")
380
+ .description("Get a single record by id from a document model")
381
+ .argument("<document-id>", "Document ID")
382
+ .argument("<model-name>", "Model name")
383
+ .argument("<record-id>", "Record ID")
384
+ .option("--app <app-id>", "App ID")
385
+ .option("--json", "Output as JSON")
386
+ .action(async (documentId, modelName, recordId, options) => {
387
+ const resolvedAppId = resolveAppId(undefined, options);
388
+ const client = new ApiClient();
389
+ try {
390
+ // A single-record fetch is a query filtered by primary-key id (there is
391
+ // no dedicated get endpoint — reuse queryDocumentRecords, exactly as
392
+ // the `databases records get` twin reuses queryDatabaseRecords).
393
+ const result = await client.queryDocumentRecords(resolvedAppId, documentId, modelName, { filter: { id: recordId }, limit: 1 });
394
+ const record = result.items[0];
395
+ if (options.json) {
396
+ json(record ?? null);
397
+ return;
398
+ }
399
+ if (!record) {
400
+ info(`No record found with id ${recordId} in ${modelName}.`);
401
+ return;
402
+ }
403
+ // `get` is a data command, so its fields go to stdout via `result()`
404
+ // — the #711 split (`result()` = the data the caller asked for,
405
+ // `keyValue()` = a post-action diagnostic summary). Issue #2437; the
406
+ // databases twin renders identically.
407
+ for (const [key, value] of Object.entries(record)) {
408
+ const rendered = value === null || value === undefined
409
+ ? "—"
410
+ : typeof value === "object"
411
+ ? JSON.stringify(value)
412
+ : String(value);
413
+ printResult(key, rendered);
414
+ }
415
+ }
416
+ catch (err) {
417
+ error(err.message);
418
+ process.exit(1);
419
+ }
420
+ });
421
+ // Count records in a document model
422
+ records
423
+ .command("count")
424
+ .description("Count records in a document model")
425
+ .argument("<document-id>", "Document ID")
426
+ .argument("<model-name>", "Model name to count")
427
+ .option("--app <app-id>", "App ID")
428
+ .option("--filter <json>", "Filter as JSON (e.g. '{\"status\":\"open\"}')")
429
+ .option("--filter-file <path>", "Read filter from a JSON or TOML file")
430
+ .option("--json", "Output as JSON")
431
+ .action(async (documentId, modelName, options) => {
432
+ const resolvedAppId = resolveAppId(undefined, options);
433
+ const filter = parseFilterOptions(options);
434
+ const client = new ApiClient();
435
+ try {
436
+ const result = await client.countDocumentRecords(resolvedAppId, documentId, modelName, { filter });
437
+ if (options.json) {
438
+ json(result);
439
+ return;
440
+ }
441
+ console.log(` ${result.count}`);
442
+ }
443
+ catch (err) {
444
+ error(err.message);
445
+ process.exit(1);
446
+ }
447
+ });
448
+ // Aggregate records in a document model (issue #2437). Mirrors
449
+ // `databases records aggregate` flag for flag and rendering for rendering —
450
+ // including the deliberate `keyValue()` for the ungrouped scalar, so the two
451
+ // twins keep printing the same thing.
452
+ const AGGREGATE_OPS = ["count", "sum", "avg", "min", "max"];
453
+ records
454
+ .command("aggregate")
455
+ .description("Aggregate records in a document model (count/sum/avg/min/max, optional group-by)")
456
+ .argument("<document-id>", "Document ID")
457
+ .argument("<model-name>", "Model name")
458
+ .option("--app <app-id>", "App ID")
459
+ .requiredOption("--op <operation>", `Aggregate operation: ${AGGREGATE_OPS.join("|")}`)
460
+ .option("--field <field>", "Field to aggregate (required for sum/avg/min/max)")
461
+ .option("--group-by <field>", "Group results by this plain field (repeatable; StringSet fields are not supported)", (value, previous = []) => previous.concat(value), [])
462
+ .option("--filter <json>", "Filter as JSON")
463
+ .option("--filter-file <path>", "Read filter from a JSON or TOML file")
464
+ .option("--json", "Output as JSON")
465
+ .action(async (documentId, modelName, options) => {
466
+ const resolvedAppId = resolveAppId(undefined, options);
467
+ if (!AGGREGATE_OPS.includes(options.op)) {
468
+ error(`Invalid --op "${options.op}". Expected one of: ${AGGREGATE_OPS.join(", ")}.`);
469
+ process.exit(1);
470
+ }
471
+ const operation = { type: options.op };
472
+ if (options.op === "count") {
473
+ if (options.field) {
474
+ error("--field is not valid for --op count.");
475
+ process.exit(1);
476
+ }
477
+ }
478
+ else {
479
+ if (!options.field) {
480
+ error(`--op ${options.op} requires --field.`);
481
+ process.exit(1);
482
+ }
483
+ operation.field = options.field;
484
+ }
485
+ const filter = parseFilterOptions(options);
486
+ const groupBy = options.groupBy || [];
487
+ const client = new ApiClient();
488
+ try {
489
+ const response = await client.aggregateDocumentRecords(resolvedAppId, documentId, modelName, { operations: [operation], groupBy, filter });
490
+ if (options.json) {
491
+ json(response);
492
+ return;
493
+ }
494
+ const aggregated = response?.result;
495
+ // Same labelling rule as the databases twin: the field name is
496
+ // reproduced verbatim, never case-folded (issue #2357).
497
+ const valueLabel = options.op === "count"
498
+ ? "COUNT"
499
+ : `${options.op.toUpperCase()}(${options.field})`;
500
+ const scalarLabel = options.op === "count"
501
+ ? "count"
502
+ : `${options.op.toLowerCase()}(${options.field})`;
503
+ if (groupBy.length === 0) {
504
+ const value = (aggregated ?? {})[options.op === "count" ? "count" : `${options.op}_${options.field}`];
505
+ keyValue(scalarLabel, value === null || value === undefined ? "—" : String(value));
506
+ return;
507
+ }
508
+ if (aggregated &&
509
+ typeof aggregated === "object" &&
510
+ !Array.isArray(aggregated) &&
511
+ Object.values(aggregated).every((v) => typeof v !== "object" || v === null)) {
512
+ const rows = Object.entries(aggregated).map(([group, value]) => ({
513
+ group,
514
+ value: value === null || value === undefined ? "—" : String(value),
515
+ }));
516
+ console.log(formatTable(rows, [
517
+ { header: "GROUP", key: "group" },
518
+ { header: valueLabel, key: "value" },
519
+ ]));
520
+ }
521
+ else {
522
+ console.log(JSON.stringify(aggregated ?? {}, null, 2));
523
+ }
524
+ }
525
+ catch (err) {
526
+ error(err.message);
527
+ process.exit(1);
528
+ }
529
+ });
530
+ // ---- Record writes (#1964 Phase 4) ----
531
+ // Server-side writes through the document facade: Yjs-first, CRDT-safe,
532
+ // broadcast to connected clients. Requires read-write or higher on the
533
+ // document (or an admin token). `--data` / `--data-file` are validated
534
+ // CLI-side before any request is sent.
535
+ // `--data`/`--data-file` parsing (including the object-shape check and the
536
+ // both-flags rule) is the shared `parseDataOption` helper, so these verbs
537
+ // behave and diagnose identically to `metadata` and `databases records`.
538
+ // Create or replace a record
539
+ records
540
+ .command("save")
541
+ .description("Create or replace a record in a document model")
542
+ .argument("<document-id>", "Document ID")
543
+ .argument("<model-name>", "Model name to write to")
544
+ .option("--app <app-id>", "App ID")
545
+ .option("--id <record-id>", "Record ID (a ULID is generated when omitted)")
546
+ .option("--data <json>", "Record fields as JSON (e.g. '{\"qty\":10}')")
547
+ .option("--data-file <file>", "Read record fields from a JSON file")
548
+ .option("--upsert-on <field>", "Update the record whose <field> matches instead of creating")
549
+ .option("--json", "Output as JSON")
550
+ .action(async (documentId, modelName, options) => {
551
+ const data = parseDataOption(options, "record fields");
552
+ const resolvedAppId = resolveAppId(undefined, options);
553
+ const recordId = options.id || ulid();
554
+ const writeOptions = options.upsertOn ? { upsertOn: options.upsertOn } : undefined;
555
+ const client = new ApiClient();
556
+ try {
557
+ const result = await client.saveDocumentRecord(resolvedAppId, documentId, modelName, { id: recordId, data, ...(writeOptions ? { options: writeOptions } : {}) });
558
+ if (options.json) {
559
+ json(result);
560
+ return;
561
+ }
562
+ success(`Record saved: ${result.record?.id ?? recordId}`);
563
+ }
564
+ catch (err) {
565
+ error(err.message);
566
+ process.exit(1);
567
+ }
568
+ });
569
+ // Merge fields into an existing record
570
+ records
571
+ .command("patch")
572
+ .description("Merge fields into an existing record in a document model")
573
+ .argument("<document-id>", "Document ID")
574
+ .argument("<model-name>", "Model name")
575
+ .argument("<record-id>", "Record ID to patch")
576
+ .option("--app <app-id>", "App ID")
577
+ .option("--data <json>", "Fields to merge as JSON (e.g. '{\"status\":\"closed\"}')")
578
+ .option("--data-file <file>", "Read fields from a JSON file")
579
+ .option("--json", "Output as JSON")
580
+ .action(async (documentId, modelName, recordId, options) => {
581
+ const data = parseDataOption(options, "fields to merge");
582
+ const resolvedAppId = resolveAppId(undefined, options);
583
+ const client = new ApiClient();
584
+ try {
585
+ const result = await client.patchDocumentRecord(resolvedAppId, documentId, modelName, recordId, { data });
586
+ if (options.json) {
587
+ json(result);
588
+ return;
589
+ }
590
+ success(`Record patched: ${recordId}`);
591
+ }
592
+ catch (err) {
593
+ error(err.message);
594
+ process.exit(1);
595
+ }
596
+ });
597
+ // Delete a record
598
+ records
599
+ .command("delete")
600
+ .description("Delete a record from a document model")
601
+ .argument("<document-id>", "Document ID")
602
+ .argument("<model-name>", "Model name")
603
+ .argument("<record-id>", "Record ID to delete")
604
+ .option("--app <app-id>", "App ID")
605
+ .option("-y, --yes", "Skip confirmation prompt")
606
+ .option("--json", "Output as JSON")
607
+ .action(async (documentId, modelName, recordId, options) => {
608
+ const resolvedAppId = resolveAppId(undefined, options);
609
+ if (!options.yes) {
610
+ const confirmed = await confirmPrompt(`Delete record ${recordId} from ${modelName} in document ${documentId}?`);
611
+ if (!confirmed) {
612
+ info("Cancelled.");
613
+ return;
614
+ }
615
+ }
616
+ const client = new ApiClient();
617
+ try {
618
+ const result = await client.deleteDocumentRecord(resolvedAppId, documentId, modelName, recordId);
619
+ if (options.json) {
620
+ json(result);
621
+ return;
622
+ }
623
+ // A delete of a missing record is a silent no-op server-side, so
624
+ // this reports the request outcome, not record existence.
625
+ success(`Record deleted: ${recordId}`);
626
+ }
627
+ catch (err) {
628
+ error(err.message);
629
+ process.exit(1);
630
+ }
631
+ });
632
+ // Apply an atomic multi-model operations blob
633
+ records
634
+ .command("bulk")
635
+ .description("Apply an atomic create/patch/delete operations blob to a document")
636
+ .argument("<document-id>", "Document ID")
637
+ .requiredOption("--data-file <file>", "JSON file with { operations: [...] } or a bare operations array. " +
638
+ "Each op is { model, action: create|patch|delete, id, data, precondition? } " +
639
+ "— `data` holds the record fields and is required (non-empty) on " +
640
+ "create/patch, not allowed on delete; a create `id` must be a 26-char " +
641
+ "uppercase Crockford ULID")
642
+ .option("--app <app-id>", "App ID")
643
+ .option("-y, --yes", "Skip confirmation prompt")
644
+ .option("--json", "Output as JSON")
645
+ .action(async (documentId, options) => {
646
+ const parsed = parseDataOption(options, "operations blob", {
647
+ allowArray: true,
648
+ });
649
+ const operations = Array.isArray(parsed) ? parsed : parsed?.operations;
650
+ if (!Array.isArray(operations) || operations.length === 0) {
651
+ error("--data-file must contain { operations: [...] } or a non-empty operations array.");
652
+ process.exit(1);
653
+ }
654
+ const resolvedAppId = resolveAppId(undefined, options);
655
+ if (!options.yes) {
656
+ const confirmed = await confirmPrompt(`Apply ${operations.length} operation(s) atomically to document ${documentId}?`);
657
+ if (!confirmed) {
658
+ info("Cancelled.");
659
+ return;
660
+ }
661
+ }
662
+ const client = new ApiClient();
663
+ try {
664
+ const result = await client.bulkDocumentRecords(resolvedAppId, documentId, operations);
665
+ if (options.json) {
666
+ json(result);
667
+ return;
668
+ }
669
+ success(`Applied ${result.applied} operation(s): ` +
670
+ `${result.added.length} added, ${result.updated.length} updated, ${result.deleted} deleted.`);
671
+ }
672
+ catch (err) {
673
+ error(err.message);
674
+ process.exit(1);
675
+ }
676
+ });
677
+ // Dump a document's records grouped by model (CLI-side composition)
678
+ documents
679
+ .command("dump")
680
+ .description("Dump a document's records grouped by model as JSON")
681
+ .argument("<document-id>", "Document ID")
682
+ .option("--app <app-id>", "App ID")
683
+ .option("--output <file>", "Write the JSON dump to a file instead of stdout")
684
+ .option("--json", "Output as JSON (default)")
685
+ .action(async (documentId, options) => {
686
+ const resolvedAppId = resolveAppId(undefined, options);
687
+ const client = new ApiClient();
688
+ try {
689
+ // Model names come from the schema; records are assembled from paged
690
+ // reads per model (not a single atomic snapshot — the paged path is
691
+ // the contract, same pattern as `databases export`).
692
+ const schema = await client.getDocumentSchema(resolvedAppId, documentId);
693
+ const modelNames = schema?.modelNames ?? Object.keys(schema?.schema?.models ?? {});
694
+ const grouped = {};
695
+ for (const modelName of modelNames) {
696
+ const records = [];
697
+ let cursor;
698
+ do {
699
+ const page = await client.queryDocumentRecords(resolvedAppId, documentId, modelName, { limit: 100, cursor });
700
+ records.push(...page.items);
701
+ cursor = page.nextCursor;
702
+ } while (cursor);
703
+ grouped[modelName] = records;
704
+ }
705
+ const output = JSON.stringify(grouped, null, 2);
706
+ if (options.output) {
707
+ fs.writeFileSync(options.output, output);
708
+ success(`Document dump written to ${options.output}`);
709
+ return;
710
+ }
711
+ console.log(output);
712
+ }
713
+ catch (err) {
714
+ error(err.message);
715
+ process.exit(1);
716
+ }
717
+ });
718
+ // Document statistics (platform-vocabulary projection)
719
+ documents
720
+ .command("stats")
721
+ .description("Show a document's record/model/blob counts and approximate size")
722
+ .argument("<document-id>", "Document ID")
723
+ .option("--app <app-id>", "App ID")
724
+ .option("--json", "Output as JSON")
725
+ .action(async (documentId, options) => {
726
+ const resolvedAppId = resolveAppId(undefined, options);
727
+ const client = new ApiClient();
728
+ try {
729
+ const result = await client.getDocumentStats(resolvedAppId, documentId);
730
+ if (options.json) {
731
+ json(result);
732
+ return;
733
+ }
734
+ keyValue("Document ID", result.documentId);
735
+ keyValue("Records", result.recordCount);
736
+ keyValue("Models", result.modelCount);
737
+ keyValue("Blobs", result.blobCount);
738
+ keyValue("Size (bytes, approx)", result.sizeBytes);
739
+ keyValue("Last modified", result.lastModifiedAt ? formatDate(result.lastModifiedAt) : "—");
740
+ }
741
+ catch (err) {
742
+ error(err.message);
743
+ process.exit(1);
744
+ }
745
+ });
13
746
  // Transfer document ownership
14
747
  documents
15
748
  .command("transfer-owner")
@@ -43,15 +776,14 @@ Examples:
43
776
  process.exit(1);
44
777
  }
45
778
  if (!options.yes) {
46
- const inquirer = await import("inquirer");
47
- const { confirm } = await inquirer.default.prompt([
48
- {
49
- type: "confirm",
50
- name: "confirm",
51
- message: `Transfer ownership of document ${documentId} to user ${newOwnerId}? This cannot be undone.`,
52
- default: false,
53
- },
54
- ]);
779
+ let confirm;
780
+ try {
781
+ confirm = await confirmPrompt(`Transfer ownership of document ${documentId} to user ${newOwnerId}? This cannot be undone.`);
782
+ }
783
+ catch (err) {
784
+ error(err.message);
785
+ process.exit(1);
786
+ }
55
787
  if (!confirm) {
56
788
  info("Cancelled.");
57
789
  return;
@@ -138,6 +870,287 @@ Examples:
138
870
  process.exit(1);
139
871
  }
140
872
  });
873
+ // ---- Link access ("anyone with the link") ----
874
+ const linkAccess = documents
875
+ .command("link-access")
876
+ .description('Manage "anyone with the link" access on a document');
877
+ linkAccess
878
+ .command("get")
879
+ .description("Show the current link-access level for a document")
880
+ .argument("<document-id>", "Document ID")
881
+ .option("--app <app-id>", "App ID")
882
+ .option("--json", "Output as JSON")
883
+ .action(async (documentId, options) => {
884
+ const resolvedAppId = resolveAppId(undefined, options);
885
+ const client = new ApiClient();
886
+ try {
887
+ const state = await client.getDocumentLinkAccess(resolvedAppId, documentId);
888
+ const level = state?.linkAccess ?? null;
889
+ if (options.json) {
890
+ json({ documentId, linkAccess: level });
891
+ return;
892
+ }
893
+ if (!level) {
894
+ info("Link access is off for this document.");
895
+ return;
896
+ }
897
+ keyValue("Document", documentId);
898
+ keyValue("Link access", level);
899
+ }
900
+ catch (err) {
901
+ error(err.message);
902
+ process.exit(1);
903
+ }
904
+ });
905
+ linkAccess
906
+ .command("set")
907
+ .description("Turn on link access at a given level")
908
+ .argument("<document-id>", "Document ID")
909
+ .requiredOption("--level <level>", "Link access level: reader or read-write")
910
+ .option("--app <app-id>", "App ID")
911
+ .option("--json", "Output as JSON")
912
+ .action(async (documentId, options) => {
913
+ const resolvedAppId = resolveAppId(undefined, options);
914
+ const client = new ApiClient();
915
+ try {
916
+ const result = await client.setDocumentLinkAccess(resolvedAppId, documentId, options.level);
917
+ if (options.json) {
918
+ json(result);
919
+ return;
920
+ }
921
+ success(`Link access set to '${options.level}' for document ${documentId}.`);
922
+ }
923
+ catch (err) {
924
+ error(err.message);
925
+ process.exit(1);
926
+ }
927
+ });
928
+ linkAccess
929
+ .command("clear")
930
+ .description("Turn off link access")
931
+ .argument("<document-id>", "Document ID")
932
+ .option("--app <app-id>", "App ID")
933
+ .option("--json", "Output as JSON")
934
+ .action(async (documentId, options) => {
935
+ const resolvedAppId = resolveAppId(undefined, options);
936
+ const client = new ApiClient();
937
+ try {
938
+ const result = await client.clearDocumentLinkAccess(resolvedAppId, documentId);
939
+ if (options.json) {
940
+ json(result);
941
+ return;
942
+ }
943
+ success(`Link access turned off for document ${documentId}.`);
944
+ }
945
+ catch (err) {
946
+ error(err.message);
947
+ process.exit(1);
948
+ }
949
+ });
950
+ // ---- Export / Import commands ----
951
+ documents
952
+ .command("export")
953
+ .description("Export a document (Yjs state, blobs, permissions, aliases)")
954
+ .argument("[app-id]", "App ID (uses current app if not specified)")
955
+ .argument("<document-id>", "Document ID to export")
956
+ .option("--app <app-id>", "App ID")
957
+ .option("--output <dir>", "Output directory", "./primitive-export")
958
+ .option("--no-blobs", "Skip blob data")
959
+ .option("--json", "Output as JSON")
960
+ .action(async (first, second, options) => {
961
+ let resolvedAppId;
962
+ let documentId;
963
+ if (second && !second.startsWith("-")) {
964
+ resolvedAppId = resolveAppId(first, options);
965
+ documentId = second;
966
+ }
967
+ else {
968
+ resolvedAppId = resolveAppId(undefined, options);
969
+ documentId = first;
970
+ }
971
+ if (!documentId) {
972
+ error("Document ID is required.");
973
+ process.exit(1);
974
+ }
975
+ const client = new ApiClient();
976
+ try {
977
+ await exportSingleDocument(client, resolvedAppId, documentId, options.output, options.blobs !== false ? true : false, options.json);
978
+ }
979
+ catch (err) {
980
+ error(err.message);
981
+ process.exit(1);
982
+ }
983
+ });
984
+ documents
985
+ .command("export-all")
986
+ .description("Export all documents for a user")
987
+ .argument("[app-id]", "App ID (uses current app if not specified)")
988
+ .requiredOption("--user-id <id>", "User ID to export documents for")
989
+ .option("--app <app-id>", "App ID")
990
+ .option("--owned-only", "Only export documents owned by the user")
991
+ .option("--output <dir>", "Output directory", "./primitive-export")
992
+ .option("--no-blobs", "Skip blob data")
993
+ .option("--json", "Output as JSON")
994
+ .action(async (appIdArg, options) => {
995
+ const resolvedAppId = resolveAppId(appIdArg, options);
996
+ const client = new ApiClient();
997
+ const includeBlobs = options.blobs !== false;
998
+ try {
999
+ const documents = await client.listAdminDocuments(resolvedAppId, options.userId);
1000
+ let docList = Array.isArray(documents) ? documents : [];
1001
+ if (options.ownedOnly) {
1002
+ docList = docList.filter((d) => d.permission === "owner");
1003
+ }
1004
+ if (docList.length === 0) {
1005
+ info("No documents found.");
1006
+ return;
1007
+ }
1008
+ info(`Exporting ${docList.length} document(s)...`);
1009
+ const exportedIds = [];
1010
+ for (const doc of docList) {
1011
+ const docId = doc.documentId || doc.id;
1012
+ try {
1013
+ await exportSingleDocument(client, resolvedAppId, docId, options.output, includeBlobs, false);
1014
+ exportedIds.push(docId);
1015
+ }
1016
+ catch (err) {
1017
+ warn(`Failed to export ${docId}: ${err.message}`);
1018
+ }
1019
+ }
1020
+ // Write manifest
1021
+ const manifestPath = path.join(options.output, "manifest.json");
1022
+ const manifest = {
1023
+ version: 1,
1024
+ exportedAt: new Date().toISOString(),
1025
+ sourceAppId: resolvedAppId,
1026
+ documentCount: exportedIds.length,
1027
+ documents: exportedIds,
1028
+ };
1029
+ fs.mkdirSync(path.dirname(manifestPath), { recursive: true });
1030
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
1031
+ if (options.json) {
1032
+ json(manifest);
1033
+ }
1034
+ else {
1035
+ success(`Exported ${exportedIds.length} document(s) to ${options.output}`);
1036
+ }
1037
+ }
1038
+ catch (err) {
1039
+ error(err.message);
1040
+ process.exit(1);
1041
+ }
1042
+ });
1043
+ documents
1044
+ .command("import")
1045
+ .description("Import documents from an export directory")
1046
+ .argument("[app-id]", "App ID (uses current app if not specified)")
1047
+ .argument("<path>", "Path to export directory or single document directory")
1048
+ .option("--app <app-id>", "App ID")
1049
+ .option("--aliases <mode>", "Alias conflict handling: overwrite or skip", "skip")
1050
+ .option("--overwrite", "Replace existing documents if IDs collide")
1051
+ .option("--dry-run", "Show what would be imported without making changes")
1052
+ .option("--owner <userId-or-email>", "User ID or email to set as document owner (admin only)")
1053
+ .option("--json", "Output as JSON")
1054
+ .action(async (first, second, options) => {
1055
+ let resolvedAppId;
1056
+ let importPath;
1057
+ if (second && !second.startsWith("-")) {
1058
+ resolvedAppId = resolveAppId(first, options);
1059
+ importPath = second;
1060
+ }
1061
+ else {
1062
+ resolvedAppId = resolveAppId(undefined, options);
1063
+ importPath = first;
1064
+ }
1065
+ if (!importPath) {
1066
+ error("Import path is required.");
1067
+ process.exit(1);
1068
+ }
1069
+ const client = new ApiClient();
1070
+ // Resolve --owner to a userId
1071
+ let ownerUserId;
1072
+ if (options.owner) {
1073
+ if (options.owner.includes("@")) {
1074
+ const user = await client.findUserByEmail(resolvedAppId, options.owner);
1075
+ if (!user) {
1076
+ error(`No user found with email "${options.owner}" in app ${resolvedAppId}.`);
1077
+ process.exit(1);
1078
+ }
1079
+ ownerUserId = user.userId || user.id;
1080
+ info(`Resolved owner email to userId: ${ownerUserId}`);
1081
+ }
1082
+ else {
1083
+ ownerUserId = options.owner;
1084
+ }
1085
+ }
1086
+ try {
1087
+ // Determine if this is a manifest-based export or a single document
1088
+ const manifestPath = path.join(importPath, "manifest.json");
1089
+ let docDirs = [];
1090
+ if (fs.existsSync(manifestPath)) {
1091
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
1092
+ for (const docId of manifest.documents) {
1093
+ const docDir = path.join(importPath, "documents", docId);
1094
+ if (fs.existsSync(docDir)) {
1095
+ docDirs.push(docDir);
1096
+ }
1097
+ }
1098
+ }
1099
+ else if (fs.existsSync(path.join(importPath, "metadata.json"))) {
1100
+ // Single document directory
1101
+ docDirs = [importPath];
1102
+ }
1103
+ else if (fs.existsSync(path.join(importPath, "documents"))) {
1104
+ // Export directory without manifest — discover documents
1105
+ const entries = fs.readdirSync(path.join(importPath, "documents"), { withFileTypes: true });
1106
+ for (const entry of entries) {
1107
+ if (entry.isDirectory()) {
1108
+ docDirs.push(path.join(importPath, "documents", entry.name));
1109
+ }
1110
+ }
1111
+ }
1112
+ else {
1113
+ error("No valid export data found at the specified path.");
1114
+ process.exit(1);
1115
+ }
1116
+ if (docDirs.length === 0) {
1117
+ info("No documents to import.");
1118
+ return;
1119
+ }
1120
+ const summary = {
1121
+ created: 0,
1122
+ updated: 0,
1123
+ skipped: 0,
1124
+ blobsUploaded: 0,
1125
+ aliasesSet: 0,
1126
+ aliasesSkipped: 0,
1127
+ };
1128
+ for (const docDir of docDirs) {
1129
+ await importSingleDocument(client, resolvedAppId, docDir, options.overwrite || false, options.aliases || "skip", options.dryRun || false, summary, ownerUserId);
1130
+ }
1131
+ if (options.json) {
1132
+ json(summary);
1133
+ }
1134
+ else {
1135
+ success(`Import complete:`);
1136
+ keyValue(" Documents created", String(summary.created));
1137
+ if (summary.updated > 0)
1138
+ keyValue(" Documents updated", String(summary.updated));
1139
+ if (summary.skipped > 0)
1140
+ keyValue(" Documents skipped", String(summary.skipped));
1141
+ if (summary.blobsUploaded > 0)
1142
+ keyValue(" Blobs uploaded", String(summary.blobsUploaded));
1143
+ if (summary.aliasesSet > 0)
1144
+ keyValue(" Aliases set", String(summary.aliasesSet));
1145
+ if (summary.aliasesSkipped > 0)
1146
+ keyValue(" Aliases skipped", String(summary.aliasesSkipped));
1147
+ }
1148
+ }
1149
+ catch (err) {
1150
+ error(err.message);
1151
+ process.exit(1);
1152
+ }
1153
+ });
141
1154
  // Revoke group permission
142
1155
  groupPermissions
143
1156
  .command("revoke")
@@ -150,15 +1163,14 @@ Examples:
150
1163
  .action(async (documentId, groupType, groupId, options) => {
151
1164
  const resolvedAppId = resolveAppId(undefined, options);
152
1165
  if (!options.yes) {
153
- const inquirer = await import("inquirer");
154
- const { confirm } = await inquirer.default.prompt([
155
- {
156
- type: "confirm",
157
- name: "confirm",
158
- message: `Revoke permission for group ${groupType}/${groupId} on document ${documentId}?`,
159
- default: false,
160
- },
161
- ]);
1166
+ let confirm;
1167
+ try {
1168
+ confirm = await confirmPrompt(`Revoke permission for group ${groupType}/${groupId} on document ${documentId}?`);
1169
+ }
1170
+ catch (err) {
1171
+ error(err.message);
1172
+ process.exit(1);
1173
+ }
162
1174
  if (!confirm) {
163
1175
  info("Cancelled.");
164
1176
  return;
@@ -175,4 +1187,203 @@ Examples:
175
1187
  }
176
1188
  });
177
1189
  }
1190
+ // ============================================
1191
+ // Helper functions for export/import
1192
+ // ============================================
1193
+ async function exportSingleDocument(client, appId, documentId, outputDir, includeBlobs, jsonOutput) {
1194
+ const docDir = path.join(outputDir, "documents", documentId);
1195
+ fs.mkdirSync(docDir, { recursive: true });
1196
+ // 1. Fetch document metadata
1197
+ const docMeta = await client.getDocument(appId, documentId);
1198
+ // 2. Export Yjs state
1199
+ const stateResult = await client.exportDocumentState(appId, documentId);
1200
+ fs.writeFileSync(path.join(docDir, "document.yjs"), Buffer.from(stateResult.state, "base64"));
1201
+ // 3. Fetch permissions
1202
+ let permissions = [];
1203
+ try {
1204
+ const permResult = await client.listDocumentPermissions(appId, documentId);
1205
+ permissions = Array.isArray(permResult) ? permResult : permResult?.permissions || [];
1206
+ }
1207
+ catch {
1208
+ // Permissions endpoint might not return data for all docs
1209
+ }
1210
+ // 4. Fetch invitations
1211
+ let invitations = [];
1212
+ try {
1213
+ const invResult = await client.listDocumentInvitations(appId, documentId);
1214
+ invitations = Array.isArray(invResult) ? invResult : invResult?.invitations || [];
1215
+ }
1216
+ catch {
1217
+ // May not have invitations
1218
+ }
1219
+ // Merge permissions and invitations into a single list with email identifiers
1220
+ const permissionsExport = [
1221
+ ...permissions.map((p) => ({
1222
+ email: p.email,
1223
+ permission: p.permission,
1224
+ grantedAt: p.grantedAt,
1225
+ })),
1226
+ ...invitations
1227
+ .filter((i) => !i.accepted && new Date(i.expiresAt) > new Date())
1228
+ .map((i) => ({
1229
+ email: i.email,
1230
+ permission: i.permission,
1231
+ source: "invitation",
1232
+ status: "pending",
1233
+ })),
1234
+ ];
1235
+ fs.writeFileSync(path.join(docDir, "permissions.json"), JSON.stringify(permissionsExport, null, 2));
1236
+ // 5. Fetch aliases (user-scoped only)
1237
+ let aliases = [];
1238
+ try {
1239
+ const aliasResult = await client.listDocumentAliases(appId, documentId);
1240
+ aliases = (Array.isArray(aliasResult) ? aliasResult : aliasResult?.aliases || [])
1241
+ .filter((a) => (a.scope || a.aliasScope) === "user");
1242
+ }
1243
+ catch {
1244
+ // May not have aliases
1245
+ }
1246
+ // 6. Write metadata
1247
+ const metadata = {
1248
+ documentId: docMeta.documentId || documentId,
1249
+ title: docMeta.title,
1250
+ tags: docMeta.tags || [],
1251
+ createdAt: docMeta.createdAt,
1252
+ createdBy: docMeta.createdByEmail || docMeta.createdBy,
1253
+ aliases: aliases.map((a) => ({
1254
+ aliasScope: a.scope || a.aliasScope,
1255
+ aliasKey: a.aliasKey,
1256
+ })),
1257
+ };
1258
+ fs.writeFileSync(path.join(docDir, "metadata.json"), JSON.stringify(metadata, null, 2));
1259
+ // 7. Blobs
1260
+ if (includeBlobs) {
1261
+ let blobs = [];
1262
+ try {
1263
+ const blobResult = await client.listDocumentBlobs(appId, documentId);
1264
+ blobs = Array.isArray(blobResult) ? blobResult : blobResult?.items || blobResult?.blobs || [];
1265
+ }
1266
+ catch {
1267
+ // May not have blobs
1268
+ }
1269
+ if (blobs.length > 0) {
1270
+ const blobsDir = path.join(docDir, "blobs");
1271
+ fs.mkdirSync(blobsDir, { recursive: true });
1272
+ const blobIndex = blobs.map((b) => ({
1273
+ blobId: b.blobId,
1274
+ filename: b.filename,
1275
+ contentType: b.contentType,
1276
+ sha256: b.sha256,
1277
+ numBytes: b.numBytes,
1278
+ }));
1279
+ fs.writeFileSync(path.join(blobsDir, "index.json"), JSON.stringify(blobIndex, null, 2));
1280
+ // Download blobs (sequentially to avoid overwhelming the server)
1281
+ for (const blob of blobs) {
1282
+ const data = await client.downloadBlob(appId, documentId, blob.blobId);
1283
+ fs.writeFileSync(path.join(blobsDir, `${blob.blobId}.bin`), data);
1284
+ }
1285
+ }
1286
+ }
1287
+ if (jsonOutput) {
1288
+ json({
1289
+ documentId,
1290
+ title: metadata.title,
1291
+ stateBytes: stateResult.byteLength,
1292
+ permissions: permissionsExport.length,
1293
+ aliases: aliases.length,
1294
+ exportPath: docDir,
1295
+ });
1296
+ }
1297
+ else {
1298
+ success(`Exported document ${documentId} (${metadata.title || "untitled"}) to ${docDir}`);
1299
+ }
1300
+ }
1301
+ async function importSingleDocument(client, appId, docDir, overwrite, aliasMode, dryRun, summary, ownerUserId) {
1302
+ const metadataPath = path.join(docDir, "metadata.json");
1303
+ if (!fs.existsSync(metadataPath)) {
1304
+ warn(`Skipping ${docDir}: no metadata.json found`);
1305
+ summary.skipped++;
1306
+ return;
1307
+ }
1308
+ const metadata = JSON.parse(fs.readFileSync(metadataPath, "utf-8"));
1309
+ const documentId = metadata.documentId;
1310
+ if (dryRun) {
1311
+ info(`[dry-run] Would import document ${documentId} (${metadata.title || "untitled"})`);
1312
+ summary.created++;
1313
+ return;
1314
+ }
1315
+ // Check if document exists
1316
+ let exists = false;
1317
+ try {
1318
+ await client.getDocument(appId, documentId);
1319
+ exists = true;
1320
+ }
1321
+ catch {
1322
+ exists = false;
1323
+ }
1324
+ if (exists && !overwrite) {
1325
+ warn(`Skipping ${documentId}: already exists (use --overwrite to replace)`);
1326
+ summary.skipped++;
1327
+ return;
1328
+ }
1329
+ // Create document if it doesn't exist
1330
+ if (!exists) {
1331
+ await client.createDocument(appId, {
1332
+ title: metadata.title || "Imported Document",
1333
+ documentId,
1334
+ tags: metadata.tags,
1335
+ ...(ownerUserId ? { createdBy: ownerUserId } : {}),
1336
+ });
1337
+ summary.created++;
1338
+ }
1339
+ else {
1340
+ summary.updated++;
1341
+ }
1342
+ // Import Yjs state
1343
+ const yjsPath = path.join(docDir, "document.yjs");
1344
+ if (fs.existsSync(yjsPath)) {
1345
+ const stateBuffer = fs.readFileSync(yjsPath);
1346
+ const stateBase64 = stateBuffer.toString("base64");
1347
+ await client.importDocumentState(appId, documentId, stateBase64);
1348
+ }
1349
+ // Upload blobs
1350
+ const blobIndexPath = path.join(docDir, "blobs", "index.json");
1351
+ if (fs.existsSync(blobIndexPath)) {
1352
+ const blobIndex = JSON.parse(fs.readFileSync(blobIndexPath, "utf-8"));
1353
+ for (const blob of blobIndex) {
1354
+ const blobPath = path.join(docDir, "blobs", `${blob.blobId}.bin`);
1355
+ if (fs.existsSync(blobPath)) {
1356
+ const data = fs.readFileSync(blobPath);
1357
+ await client.uploadBlob(appId, documentId, blob.blobId, data, {
1358
+ filename: blob.filename,
1359
+ contentType: blob.contentType,
1360
+ sha256: blob.sha256,
1361
+ });
1362
+ summary.blobsUploaded++;
1363
+ }
1364
+ }
1365
+ }
1366
+ // Permissions are exported for reference but not restored during import.
1367
+ // The importing admin is the new owner; sharing is managed in the target app.
1368
+ // Restore aliases
1369
+ if (metadata.aliases && Array.isArray(metadata.aliases)) {
1370
+ for (const alias of metadata.aliases) {
1371
+ if (alias.aliasScope !== "user")
1372
+ continue;
1373
+ if (!ownerUserId) {
1374
+ summary.aliasesSkipped++;
1375
+ continue;
1376
+ }
1377
+ try {
1378
+ await client.setDocumentAlias(appId, alias.aliasScope, alias.aliasKey, documentId, ownerUserId, aliasMode === "skip" // mustNotExist: true for skip mode, false for overwrite
1379
+ );
1380
+ summary.aliasesSet++;
1381
+ }
1382
+ catch {
1383
+ summary.aliasesSkipped++;
1384
+ }
1385
+ }
1386
+ }
1387
+ info(`Imported document ${documentId} (${metadata.title || "untitled"})`);
1388
+ }
178
1389
  //# sourceMappingURL=documents.js.map