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,6 +1,17 @@
1
+ import { readFileSync, writeFileSync, appendFileSync, mkdirSync, existsSync, readdirSync } from "fs";
2
+ import * as path from "path";
1
3
  import { ApiClient } from "../lib/api-client.js";
2
4
  import { getCurrentAppId } from "../lib/config.js";
3
- import { success, error, info, keyValue, formatTable, formatId, formatDate, json, } from "../lib/output.js";
5
+ import { resolveCodegenSourceDir } from "../lib/codegen-shared/resolveCodegenSourceDir.js";
6
+ import { parseCsv, applyColumnMap, buildRows } from "../lib/csv.js";
7
+ import { chunk, parseBatchSize } from "../lib/batch.js";
8
+ import { generateDbTypes, } from "../lib/db-codegen/dbGenerator.js";
9
+ import { generateDbSwiftTypes } from "../lib/swift-codegen/dbGenerator.js";
10
+ import { success, error, info, warn, keyValue, result as printResult, formatTable, formatId, formatDate, json, } from "../lib/output.js";
11
+ import { confirmPrompt } from "../lib/confirm-prompt.js";
12
+ import { parseFilterOptions } from "../lib/record-filter.js";
13
+ import { parseDataOption } from "../lib/data-input.js";
14
+ import { ulid } from "ulid";
4
15
  function resolveAppId(appId, options) {
5
16
  const resolved = appId || options.app || getCurrentAppId();
6
17
  if (!resolved) {
@@ -9,6 +20,175 @@ function resolveAppId(appId, options) {
9
20
  }
10
21
  return resolved;
11
22
  }
23
+ /**
24
+ * Render the flat `{ success, id, appliedFields }` response that
25
+ * `records/save` and `records/patch` return — these endpoints answer with a
26
+ * write receipt, not the stored record, so the human view shows the resolved id
27
+ * plus any server-applied fields (autoStamps / trigger-computed values).
28
+ */
29
+ function renderRecordWriteResult(result, fallbackId, message) {
30
+ success(message);
31
+ keyValue("id", String(result?.id ?? fallbackId));
32
+ const applied = result?.appliedFields;
33
+ if (applied && typeof applied === "object" && Object.keys(applied).length > 0) {
34
+ for (const [key, value] of Object.entries(applied)) {
35
+ keyValue(`applied.${key}`, value === null || value === undefined ? "—" : String(value));
36
+ }
37
+ }
38
+ }
39
+ /**
40
+ * Refuse a write whose `--data` carries an `id` that is not the record being
41
+ * written. The server strips `id` from the record body on both the save and the
42
+ * patch path, so such an `id` would be dropped silently and the write would
43
+ * land on the id from the argument — somewhere the caller did not intend.
44
+ *
45
+ * `recordId` is the id the caller passed as an argument (absent on a `save`
46
+ * that mints one); `writtenId` is the id actually being written. Exits non-zero
47
+ * when they disagree with `--data` (#1965 review).
48
+ */
49
+ function assertDataIdMatches(data, recordId, writtenId, commandPath) {
50
+ if (!data || typeof data !== "object")
51
+ return;
52
+ const dataId = data.id;
53
+ if (dataId === undefined || dataId === writtenId)
54
+ return;
55
+ error(recordId
56
+ ? `The "id" in --data ("${dataId}") does not match the record id "${recordId}". Remove it, or pass the id you mean as the argument.`
57
+ : `Pass the record id as the argument, not inside --data: ${commandPath} ${dataId} --data ...`);
58
+ process.exit(1);
59
+ }
60
+ /**
61
+ * Validate that the named operation is an import-compatible, save-like
62
+ * mutation before importing (issue #145, Codex finding (a)).
63
+ *
64
+ * The importer always builds `params: { modelName, id, data }`, and the batch
65
+ * endpoint rejects undeclared params per item. So we require the op to be a
66
+ * `mutation` whose declared `params` cover `modelName`, `id`, and `data`. This
67
+ * surfaces a clear up-front error instead of letting every row fail
68
+ * server-side. Exits non-zero on any mismatch.
69
+ */
70
+ async function validateImportOperation(client, appId, databaseId, operationName) {
71
+ let ops;
72
+ try {
73
+ ops = await client.listDatabaseOperations(appId, databaseId);
74
+ }
75
+ catch (err) {
76
+ error(`Could not list operations for this database: ${err?.message || err}`);
77
+ process.exit(1);
78
+ return;
79
+ }
80
+ const op = (ops || []).find((o) => o?.name === operationName);
81
+ if (!op) {
82
+ error(`Operation "${operationName}" not found — create a mutation op (e.g. ` +
83
+ `\`seed_save\`) on this database type first.`);
84
+ process.exit(1);
85
+ return;
86
+ }
87
+ if (op.type !== "mutation") {
88
+ error(`Operation "${operationName}" is a "${op.type}" op, not an import-compatible ` +
89
+ `mutation. CSV import needs a save-like mutation taking {modelName, id, data}.`);
90
+ process.exit(1);
91
+ return;
92
+ }
93
+ const params = op.params || {};
94
+ const missing = ["modelName", "id", "data"].filter((p) => !(p in params));
95
+ if (missing.length > 0) {
96
+ error(`Operation "${operationName}" is not import-compatible: its params are missing ` +
97
+ `${missing.join(", ")}. CSV import builds {modelName, id, data} per item, so the ` +
98
+ `op must declare those params (like \`seed_save\`).`);
99
+ process.exit(1);
100
+ return;
101
+ }
102
+ }
103
+ /**
104
+ * The full `databases records bulk` precondition value space, audited in one
105
+ * pass (issue #2437, Codex cycle 3). A precondition is field-equality only, so
106
+ * a value is one of: `null`, a boolean, a number, or a string. For each, what
107
+ * the DatabaseDO `condition` grammar can express, compared against the
108
+ * documents twin's strict JS equality (`evaluatePrecondition`):
109
+ *
110
+ * | Value | Disposition | Why |
111
+ * |-------------------|-------------|----------------------------------------------------------------------|
112
+ * | string | round-trips | bound as TEXT; SQLite never equates TEXT with a number or a JSON bool |
113
+ * | number ≠ 0 and ≠1 | round-trips | bound as-is; no other JSON type extracts to that value |
114
+ * | `null` | rewritten | paired with `$exists: true` so an absent key fails (cycle-2 fix) |
115
+ * | `true` / `false` | REJECTED | bound as 1/0, and `json_extract` yields 1/0 for JSON booleans too |
116
+ * | number 0 or 1 | REJECTED | same collision seen from the other side: matches a stored `false`/`true` |
117
+ * | `{}` (no fields) | see #2511 | sent as an empty `condition`, which the DO reads as "record must exist" |
118
+ * | object / array | rejected | not field-equality; rejected by the bulk validator before reaching here |
119
+ *
120
+ * The two REJECTED rows are the boolean/number collision: `JsonQueryTranslator`
121
+ * binds `true`/`false` as `1`/`0`, and SQLite's `json_extract` also returns a
122
+ * stored JSON boolean as `1`/`0`, so `{ enabled: true }` matches a record
123
+ * holding the number `1` and `{ retries: 1 }` matches a record holding `true`.
124
+ * The documents twin compares with `!==` and fails both. The `condition`
125
+ * grammar has no type predicate (`$exists` only distinguishes present from
126
+ * absent), so this cannot be translated exactly — the CLI rejects those values
127
+ * at the boundary instead, so the databases twin fails loudly rather than
128
+ * running with a weaker guard than the caller wrote. Issue #2507 tracks giving
129
+ * the grammar a type-aware equality, which would let these values be accepted.
130
+ *
131
+ * Returns an explanation when the value cannot be translated exactly, or
132
+ * `null` when it round-trips or is rewritten.
133
+ */
134
+ export function untranslatablePreconditionValue(value) {
135
+ if (typeof value === "boolean") {
136
+ return (`a boolean precondition cannot be checked exactly on a database — the ` +
137
+ `record store compares JSON booleans as 1/0, so \`${value}\` would also ` +
138
+ `match a record holding the number ${value ? 1 : 0}`);
139
+ }
140
+ if (value === 0 || value === 1) {
141
+ return (`the number ${value} cannot be checked exactly on a database — the ` +
142
+ `record store compares JSON booleans as 1/0, so ${value} would also ` +
143
+ `match a record holding \`${value === 1}\``);
144
+ }
145
+ return null;
146
+ }
147
+ /**
148
+ * Translate a `databases records bulk` op's documents-surface `precondition`
149
+ * into the DatabaseDO's per-op `condition` (issue #2437). See
150
+ * {@link untranslatablePreconditionValue} for the audit of the whole value
151
+ * space; this function handles the one value that is REWRITTEN rather than
152
+ * passed through or rejected.
153
+ *
154
+ * The two are NOT the same grammar, and a straight hand-off silently weakens
155
+ * the guard for one value: `null`. A `condition` is a query filter, so
156
+ * `{ approvedAt: null }` translates to
157
+ * `json_extract(_data, '$.approvedAt') IS NULL` — which is also true when the
158
+ * key is ABSENT. A guarded patch/delete would then execute against a record
159
+ * that never had the field. The documents surface evaluates the same
160
+ * precondition in JS (`evaluatePrecondition` in `src/document-models.ts`): an
161
+ * absent field reads `undefined`, and `undefined !== null`, so the guard fails
162
+ * closed there.
163
+ *
164
+ * Pin the database side to the documents meaning — "the key is present AND
165
+ * holds null" — by pairing each null check with an existence constraint.
166
+ * `$exists: true` translates to `json_type(_data, '$.<field>') IS NOT NULL`,
167
+ * true for a key holding JSON null and false for an absent key, so the pair
168
+ * emits `json_extract(...) IS NULL AND json_type(...) IS NOT NULL`.
169
+ *
170
+ * Non-null scalars need no rewrite: `= ?` against `json_extract` already fails
171
+ * for an absent field, because NULL never equals a bound value.
172
+ *
173
+ * Assumes the caller has already rejected `$`-prefixed keys, non-scalar values,
174
+ * and the values {@link untranslatablePreconditionValue} names — which is what
175
+ * leaves `$and` free to use here and what makes a pass-through exact.
176
+ */
177
+ export function preconditionToCondition(precondition) {
178
+ const nullFields = Object.keys(precondition).filter((f) => precondition[f] === null);
179
+ if (nullFields.length === 0)
180
+ return { ...precondition };
181
+ const condition = {};
182
+ for (const [field, expected] of Object.entries(precondition)) {
183
+ if (expected !== null)
184
+ condition[field] = expected;
185
+ }
186
+ condition.$and = nullFields.flatMap((field) => [
187
+ { [field]: null },
188
+ { [field]: { $exists: true } },
189
+ ]);
190
+ return condition;
191
+ }
12
192
  export function registerDatabasesCommands(program) {
13
193
  const databases = program
14
194
  .command("databases")
@@ -16,10 +196,32 @@ export function registerDatabasesCommands(program) {
16
196
  .addHelpText("after", `
17
197
  Examples:
18
198
  $ primitive databases list
199
+ $ primitive databases list --owner <user-id>
19
200
  $ primitive databases create "My Database"
20
201
  $ primitive databases get <database-id>
202
+ $ primitive databases records models <database-id>
203
+ $ primitive databases records describe <database-id> <model-name>
204
+ $ primitive databases records query <database-id> <model-name> --filter '{"name":"Alice"}'
205
+ $ primitive databases records get <database-id> <model-name> <record-id>
206
+ $ primitive databases records count <database-id> <model-name> --filter '{"status":"open"}'
207
+ $ primitive databases records aggregate <database-id> <model-name> --op avg --field price
208
+ $ primitive databases records save <database-id> <model-name> [record-id] --data '{"name":"Alice"}'
209
+ $ primitive databases records patch <database-id> <model-name> <record-id> --data '{"name":"Alice"}'
210
+ $ primitive databases operations list <database-id>
211
+ $ primitive databases operations execute <database-id> <operation-name> --params '{"key":"value"}'
212
+ $ primitive databases indexes list <database-id>
213
+ $ primitive databases indexes create <database-id> --model contacts --field email
214
+ $ primitive databases records delete <database-id> <model-name> <record-id> --yes
215
+ $ primitive databases records delete-all <database-id> <model-name> --yes
216
+ $ primitive databases records delete-all <database-id> <model-name> --filter '{"status":"draft"}' --yes
217
+ $ primitive databases records bulk <database-id> --data-file ops.json --yes
21
218
  $ primitive databases permissions list <database-id>
22
- $ primitive databases group-permissions list <database-id>
219
+
220
+ Note: this group manages database *instances*. Database *type* configurations
221
+ (schemas, rules, operations) are authored in TOML — see 'primitive config fields
222
+ database-type' and the 'database-types' group for inspection:
223
+ $ primitive database-types list
224
+ $ rm database-types/<database-type>.toml && primitive sync push --prune
23
225
  `);
24
226
  // List databases
25
227
  databases
@@ -27,12 +229,15 @@ Examples:
27
229
  .description("List databases in an app")
28
230
  .argument("[app-id]", "App ID (uses current app if not specified)")
29
231
  .option("--app <app-id>", "App ID")
232
+ .option("--owner <user-id>", "Only list databases created by this user")
30
233
  .option("--json", "Output as JSON")
31
234
  .action(async (appId, options) => {
32
235
  const resolvedAppId = resolveAppId(appId, options);
33
236
  const client = new ApiClient();
34
237
  try {
35
- const result = await client.listDatabases(resolvedAppId);
238
+ const result = await client.listDatabases(resolvedAppId, {
239
+ owner: options.owner,
240
+ });
36
241
  const list = Array.isArray(result) ? result : result?.databases ?? [];
37
242
  if (options.json) {
38
243
  json(list);
@@ -45,7 +250,20 @@ Examples:
45
250
  console.log(formatTable(list, [
46
251
  { header: "ID", key: "databaseId", format: formatId },
47
252
  { header: "TITLE", key: "title" },
253
+ { header: "TYPE", key: "databaseType", format: (v) => v || "—" },
48
254
  { header: "PERMISSION", key: "permission" },
255
+ // `permission` reads "owner" on every row for an app admin, so it
256
+ // cannot confirm --owner narrowed anything. Show who created each
257
+ // database when the filter is in play.
258
+ ...(options.owner
259
+ ? [
260
+ {
261
+ header: "CREATED BY",
262
+ key: "createdBy",
263
+ format: (v) => (v ? formatId(v) : "—"),
264
+ },
265
+ ]
266
+ : []),
49
267
  { header: "CREATED", key: "createdAt", format: formatDate },
50
268
  ]));
51
269
  }
@@ -60,12 +278,41 @@ Examples:
60
278
  .description("Create a new database")
61
279
  .argument("<title>", "Database title")
62
280
  .option("--app <app-id>", "App ID")
281
+ .requiredOption("--type <database-type>", "Database type (required)")
282
+ .option("--cel-context <json>", "[deprecated] Initial CEL context as JSON (read from rules as database.celContext.*). Prefer --initial-metadata (resource metadata categories, separate readRule/writeRule).")
283
+ .option("--metadata <json>", "[deprecated] Initial CEL context as JSON (legacy alias for --cel-context); prefer --initial-metadata")
284
+ .option("--initial-metadata <json>", "Create-time resource metadata as JSON, keyed by category name (issue #1420). The recommended replacement for --cel-context: read from rules as md.self.<category>.<key>.")
63
285
  .option("--json", "Output as JSON")
64
286
  .action(async (title, options) => {
65
287
  const resolvedAppId = resolveAppId(undefined, options);
66
288
  const client = new ApiClient();
67
289
  try {
68
- const result = await client.createDatabase(resolvedAppId, { title });
290
+ const params = { title, databaseType: options.type };
291
+ // `--cel-context` is the new user-facing name; `--metadata` remains
292
+ // supported for backwards compatibility. When both are provided,
293
+ // --cel-context wins.
294
+ const contextSource = options.celContext ?? options.metadata;
295
+ if (contextSource) {
296
+ try {
297
+ params.metadata = JSON.parse(contextSource);
298
+ }
299
+ catch {
300
+ error(`Invalid ${options.celContext ? "--cel-context" : "--metadata"} JSON.`);
301
+ process.exit(1);
302
+ }
303
+ }
304
+ // `--initial-metadata` is a separate concept: create-time per-category
305
+ // ResourceMetadata rows (issue #1420), not the database CEL context.
306
+ if (options.initialMetadata) {
307
+ try {
308
+ params.initialMetadata = JSON.parse(options.initialMetadata);
309
+ }
310
+ catch {
311
+ error("Invalid --initial-metadata JSON.");
312
+ process.exit(1);
313
+ }
314
+ }
315
+ const result = await client.createDatabase(resolvedAppId, params);
69
316
  if (options.json) {
70
317
  json(result);
71
318
  return;
@@ -73,6 +320,9 @@ Examples:
73
320
  success("Database created.");
74
321
  keyValue("Database ID", result.databaseId);
75
322
  keyValue("Title", result.title);
323
+ if (result.databaseType) {
324
+ keyValue("Database Type", result.databaseType);
325
+ }
76
326
  }
77
327
  catch (err) {
78
328
  error(err.message);
@@ -95,10 +345,53 @@ Examples:
95
345
  json(result);
96
346
  return;
97
347
  }
348
+ printResult("Database ID", result.databaseId);
349
+ printResult("Title", result.title);
350
+ printResult("Database Type", result.databaseType || "none");
351
+ printResult("Permission", result.permission || "none");
352
+ printResult("Created", formatDate(result.createdAt));
353
+ }
354
+ catch (err) {
355
+ error(err.message);
356
+ process.exit(1);
357
+ }
358
+ });
359
+ // Update database
360
+ databases
361
+ .command("update")
362
+ .description("Update a database (title, type)")
363
+ .argument("<database-id>", "Database ID")
364
+ .option("--app <app-id>", "App ID")
365
+ .option("--title <title>", "New title")
366
+ .option("--type <database-type>", "Database type (use 'none' to clear)")
367
+ .option("--json", "Output as JSON")
368
+ .action(async (databaseId, options) => {
369
+ const resolvedAppId = resolveAppId(undefined, options);
370
+ const client = new ApiClient();
371
+ const params = {};
372
+ if (options.title) {
373
+ params.title = options.title;
374
+ }
375
+ if (options.type !== undefined) {
376
+ params.databaseType =
377
+ options.type === "none"
378
+ ? null
379
+ : options.type;
380
+ }
381
+ if (Object.keys(params).length === 0) {
382
+ error("Provide at least one of --title or --type.");
383
+ process.exit(1);
384
+ }
385
+ try {
386
+ const result = await client.updateDatabase(resolvedAppId, databaseId, params);
387
+ if (options.json) {
388
+ json(result);
389
+ return;
390
+ }
391
+ success("Database updated.");
98
392
  keyValue("Database ID", result.databaseId);
99
393
  keyValue("Title", result.title);
100
- keyValue("Permission", result.permission);
101
- keyValue("Created", formatDate(result.createdAt));
394
+ keyValue("Database Type", result.databaseType || "none");
102
395
  }
103
396
  catch (err) {
104
397
  error(err.message);
@@ -115,15 +408,14 @@ Examples:
115
408
  .action(async (databaseId, options) => {
116
409
  const resolvedAppId = resolveAppId(undefined, options);
117
410
  if (!options.yes) {
118
- const inquirer = await import("inquirer");
119
- const { confirm } = await inquirer.default.prompt([
120
- {
121
- type: "confirm",
122
- name: "confirm",
123
- message: `Delete database ${databaseId}? This cannot be undone.`,
124
- default: false,
125
- },
126
- ]);
411
+ let confirm;
412
+ try {
413
+ confirm = await confirmPrompt(`Delete database ${databaseId}? This cannot be undone.`);
414
+ }
415
+ catch (err) {
416
+ error(err.message);
417
+ process.exit(1);
418
+ }
127
419
  if (!confirm) {
128
420
  info("Cancelled.");
129
421
  return;
@@ -176,157 +468,462 @@ Examples:
176
468
  process.exit(1);
177
469
  }
178
470
  });
179
- // Grant permission
471
+ // Add manager action handler
472
+ const addManagerAction = async (databaseId, options) => {
473
+ const resolvedAppId = resolveAppId(undefined, options);
474
+ const client = new ApiClient();
475
+ try {
476
+ const result = await client.addDatabaseManager(resolvedAppId, databaseId, options.userId);
477
+ if (options.json) {
478
+ json(result);
479
+ return;
480
+ }
481
+ success(`Manager added: user ${options.userId}.`);
482
+ }
483
+ catch (err) {
484
+ error(err.message);
485
+ process.exit(1);
486
+ }
487
+ };
488
+ // Remove manager action handler
489
+ const removeManagerAction = async (databaseId, userId, options) => {
490
+ const resolvedAppId = resolveAppId(undefined, options);
491
+ if (!options.yes) {
492
+ let confirm;
493
+ try {
494
+ confirm = await confirmPrompt(`Remove manager ${userId} from database ${databaseId}?`);
495
+ }
496
+ catch (err) {
497
+ error(err.message);
498
+ process.exit(1);
499
+ }
500
+ if (!confirm) {
501
+ info("Cancelled.");
502
+ return;
503
+ }
504
+ }
505
+ const client = new ApiClient();
506
+ try {
507
+ await client.removeDatabaseManager(resolvedAppId, databaseId, userId);
508
+ success(`Manager removed: user ${userId}.`);
509
+ }
510
+ catch (err) {
511
+ error(err.message);
512
+ process.exit(1);
513
+ }
514
+ };
515
+ // Add manager (primary command)
516
+ permissions
517
+ .command("add-manager")
518
+ .description("Add a user as a manager of a database")
519
+ .argument("<database-id>", "Database ID")
520
+ .requiredOption("--user-id <user-id>", "User ID to add as manager")
521
+ .option("--app <app-id>", "App ID")
522
+ .option("--json", "Output as JSON")
523
+ .action(addManagerAction);
524
+ // Remove manager (primary command)
525
+ permissions
526
+ .command("remove-manager")
527
+ .description("Remove a manager from a database")
528
+ .argument("<database-id>", "Database ID")
529
+ .argument("<user-id>", "User ID to remove")
530
+ .option("--app <app-id>", "App ID")
531
+ .option("-y, --yes", "Skip confirmation prompt")
532
+ .action(removeManagerAction);
533
+ // Grant permission (deprecated alias for add-manager)
180
534
  permissions
181
535
  .command("grant")
182
- .description("Grant a user permission on a database")
536
+ .description("(deprecated: use add-manager) Grant a user permission on a database")
183
537
  .argument("<database-id>", "Database ID")
184
538
  .requiredOption("--user-id <user-id>", "User ID to grant permission to")
185
- .requiredOption("--permission <permission>", "Permission level: owner, read-write, or reader")
539
+ .option("--permission <permission>", "Permission level (ignored, always 'manager')")
540
+ .option("--app <app-id>", "App ID")
541
+ .option("--json", "Output as JSON")
542
+ .action(addManagerAction);
543
+ // Revoke permission (deprecated alias for remove-manager)
544
+ permissions
545
+ .command("revoke")
546
+ .description("(deprecated: use remove-manager) Revoke a user's permission on a database")
547
+ .argument("<database-id>", "Database ID")
548
+ .argument("<user-id>", "User ID to revoke")
549
+ .option("--app <app-id>", "App ID")
550
+ .option("-y, --yes", "Skip confirmation prompt")
551
+ .action(removeManagerAction);
552
+ // ---- Records subcommand group ----
553
+ const records = databases
554
+ .command("records")
555
+ .description("Inspect and query records in a database");
556
+ // List models
557
+ records
558
+ .command("models")
559
+ .description("List model names in a database")
560
+ .argument("<database-id>", "Database ID")
186
561
  .option("--app <app-id>", "App ID")
187
562
  .option("--json", "Output as JSON")
188
563
  .action(async (databaseId, options) => {
189
564
  const resolvedAppId = resolveAppId(undefined, options);
190
565
  const client = new ApiClient();
191
566
  try {
192
- const result = await client.grantDatabasePermission(resolvedAppId, databaseId, {
193
- userId: options.userId,
194
- permission: options.permission,
195
- });
567
+ const result = await client.listDatabaseModels(resolvedAppId, databaseId);
568
+ const models = result.models || [];
196
569
  if (options.json) {
197
- json(result);
570
+ json(models);
571
+ return;
572
+ }
573
+ if (models.length === 0) {
574
+ info("No models found.");
198
575
  return;
199
576
  }
200
- success(`Permission '${options.permission}' granted to user ${options.userId}.`);
577
+ for (const m of models) {
578
+ console.log(` ${m}`);
579
+ }
201
580
  }
202
581
  catch (err) {
203
582
  error(err.message);
204
583
  process.exit(1);
205
584
  }
206
585
  });
207
- // Revoke permission
208
- permissions
209
- .command("revoke")
210
- .description("Revoke a user's permission on a database")
586
+ // Describe model
587
+ records
588
+ .command("describe")
589
+ .description("Show inferred schema for a model")
211
590
  .argument("<database-id>", "Database ID")
212
- .argument("<user-id>", "User ID to revoke")
591
+ .argument("<model-name>", "Model name")
213
592
  .option("--app <app-id>", "App ID")
214
- .option("-y, --yes", "Skip confirmation prompt")
215
- .action(async (databaseId, userId, options) => {
593
+ .option("--json", "Output as JSON")
594
+ .action(async (databaseId, modelName, options) => {
216
595
  const resolvedAppId = resolveAppId(undefined, options);
217
- if (!options.yes) {
218
- const inquirer = await import("inquirer");
219
- const { confirm } = await inquirer.default.prompt([
220
- {
221
- type: "confirm",
222
- name: "confirm",
223
- message: `Revoke permission for user ${userId} on database ${databaseId}?`,
224
- default: false,
596
+ const client = new ApiClient();
597
+ try {
598
+ const result = await client.describeDatabaseModel(resolvedAppId, databaseId, modelName);
599
+ const fields = result.fields || [];
600
+ if (options.json) {
601
+ json(fields);
602
+ return;
603
+ }
604
+ if (fields.length === 0) {
605
+ info("No fields detected.");
606
+ return;
607
+ }
608
+ console.log(formatTable(fields, [
609
+ { header: "FIELD", key: "field_name" },
610
+ { header: "TYPE", key: "inferred_type" },
611
+ ]));
612
+ }
613
+ catch (err) {
614
+ error(err.message);
615
+ process.exit(1);
616
+ }
617
+ });
618
+ // Query records (direct introspection via the records route)
619
+ records
620
+ .command("query")
621
+ .description("Query records in a database model (admin only)")
622
+ .argument("<database-id>", "Database ID")
623
+ .argument("<model-name>", "Model name to query")
624
+ .option("--app <app-id>", "App ID")
625
+ .option("--filter <json>", "Filter as JSON (e.g. '{\"name\":\"Alice\"}')")
626
+ .option("--filter-file <path>", "Read filter from a JSON or TOML file")
627
+ .option("--limit <n>", "Maximum number of records to return", parseInt)
628
+ .option("--cursor <cursor>", "Pagination cursor from previous query")
629
+ .option("--json", "Output as JSON")
630
+ .action(async (databaseId, modelName, options) => {
631
+ const resolvedAppId = resolveAppId(undefined, options);
632
+ const client = new ApiClient();
633
+ const filter = parseFilterOptions(options);
634
+ try {
635
+ const result = await client.queryDatabaseRecords(resolvedAppId, databaseId, modelName, { filter, limit: options.limit, cursor: options.cursor });
636
+ if (options.json) {
637
+ json(result);
638
+ return;
639
+ }
640
+ const records = result.items;
641
+ if (records.length === 0) {
642
+ info("No records found.");
643
+ return;
644
+ }
645
+ // Auto-detect columns from record keys
646
+ const allKeys = new Set();
647
+ for (const rec of records) {
648
+ for (const key of Object.keys(rec)) {
649
+ allKeys.add(key);
650
+ }
651
+ }
652
+ // Put id first, then type, then the rest sorted
653
+ const orderedKeys = [];
654
+ if (allKeys.has("id")) {
655
+ orderedKeys.push("id");
656
+ allKeys.delete("id");
657
+ }
658
+ if (allKeys.has("type")) {
659
+ orderedKeys.push("type");
660
+ allKeys.delete("type");
661
+ }
662
+ orderedKeys.push(...[...allKeys].sort());
663
+ const columns = orderedKeys.map((key) => ({
664
+ header: key.toUpperCase(),
665
+ key,
666
+ format: (v) => {
667
+ if (v === null || v === undefined)
668
+ return "—";
669
+ if (typeof v === "object")
670
+ return JSON.stringify(v);
671
+ return String(v);
225
672
  },
226
- ]);
227
- if (!confirm) {
228
- info("Cancelled.");
673
+ }));
674
+ console.log(formatTable(records, columns));
675
+ if (result.nextCursor) {
676
+ info(`More results available. Use --cursor ${result.nextCursor}`);
677
+ }
678
+ }
679
+ catch (err) {
680
+ error(err.message);
681
+ process.exit(1);
682
+ }
683
+ });
684
+ // Get a single record by id
685
+ records
686
+ .command("get")
687
+ .description("Get a single record by id (admin only)")
688
+ .argument("<database-id>", "Database ID")
689
+ .argument("<model-name>", "Model name")
690
+ .argument("<record-id>", "Record ID")
691
+ .option("--app <app-id>", "App ID")
692
+ .option("--json", "Output as JSON")
693
+ .action(async (databaseId, modelName, recordId, options) => {
694
+ const resolvedAppId = resolveAppId(undefined, options);
695
+ const client = new ApiClient();
696
+ try {
697
+ // A single-record fetch is a query filtered by primary-key id (there is
698
+ // no dedicated get endpoint — reuse queryDatabaseRecords).
699
+ const result = await client.queryDatabaseRecords(resolvedAppId, databaseId, modelName, { filter: { id: recordId }, limit: 1 });
700
+ const record = result.items[0];
701
+ if (options.json) {
702
+ json(record ?? null);
703
+ return;
704
+ }
705
+ if (!record) {
706
+ info(`No record found with id ${recordId} in ${modelName}.`);
229
707
  return;
230
708
  }
709
+ // `get` is a data command, so its fields go to stdout via `result()`
710
+ // — the #711 split (`result()` = the data the caller asked for,
711
+ // `keyValue()` = a post-action diagnostic summary). Issue #2437; the
712
+ // documents twin renders identically.
713
+ for (const [key, value] of Object.entries(record)) {
714
+ const rendered = value === null || value === undefined
715
+ ? "—"
716
+ : typeof value === "object"
717
+ ? JSON.stringify(value)
718
+ : String(value);
719
+ printResult(key, rendered);
720
+ }
721
+ }
722
+ catch (err) {
723
+ error(err.message);
724
+ process.exit(1);
231
725
  }
726
+ });
727
+ // Count records
728
+ records
729
+ .command("count")
730
+ .description("Count records in a database model (admin only)")
731
+ .argument("<database-id>", "Database ID")
732
+ .argument("<model-name>", "Model name")
733
+ .option("--app <app-id>", "App ID")
734
+ .option("--filter <json>", "Filter as JSON (e.g. '{\"name\":\"Alice\"}')")
735
+ .option("--filter-file <path>", "Read filter from a JSON or TOML file")
736
+ .option("--json", "Output as JSON")
737
+ .action(async (databaseId, modelName, options) => {
738
+ const resolvedAppId = resolveAppId(undefined, options);
739
+ const filter = parseFilterOptions(options);
232
740
  const client = new ApiClient();
233
741
  try {
234
- await client.revokeDatabasePermission(resolvedAppId, databaseId, userId);
235
- success(`Permission revoked for user ${userId}.`);
742
+ const result = await client.countDatabaseRecords(resolvedAppId, databaseId, modelName, filter);
743
+ if (options.json) {
744
+ json(result);
745
+ return;
746
+ }
747
+ keyValue("count", String(result?.count ?? 0));
236
748
  }
237
749
  catch (err) {
238
750
  error(err.message);
239
751
  process.exit(1);
240
752
  }
241
753
  });
242
- // ---- Group Permissions subcommand group ----
243
- const groupPermissions = databases
244
- .command("group-permissions")
245
- .description("Manage group permissions on a database");
246
- // List group permissions
247
- groupPermissions
248
- .command("list")
249
- .description("List group permissions for a database")
754
+ // Aggregate records
755
+ const AGGREGATE_OPS = ["count", "sum", "avg", "min", "max"];
756
+ records
757
+ .command("aggregate")
758
+ .description("Aggregate records in a database model (count/sum/avg/min/max, optional group-by; admin only)")
250
759
  .argument("<database-id>", "Database ID")
760
+ .argument("<model-name>", "Model name")
251
761
  .option("--app <app-id>", "App ID")
762
+ .requiredOption("--op <operation>", `Aggregate operation: ${AGGREGATE_OPS.join("|")}`)
763
+ .option("--field <field>", "Field to aggregate (required for sum/avg/min/max)")
764
+ .option("--group-by <field>", "Group results by this field (repeatable)", (value, previous = []) => previous.concat(value), [])
765
+ .option("--filter <json>", "Filter as JSON")
766
+ .option("--filter-file <path>", "Read filter from a JSON or TOML file")
252
767
  .option("--json", "Output as JSON")
253
- .action(async (databaseId, options) => {
768
+ .action(async (databaseId, modelName, options) => {
254
769
  const resolvedAppId = resolveAppId(undefined, options);
770
+ if (!AGGREGATE_OPS.includes(options.op)) {
771
+ error(`Invalid --op "${options.op}". Expected one of: ${AGGREGATE_OPS.join(", ")}.`);
772
+ process.exit(1);
773
+ }
774
+ const operation = { type: options.op };
775
+ if (options.op === "count") {
776
+ if (options.field) {
777
+ error("--field is not valid for --op count.");
778
+ process.exit(1);
779
+ }
780
+ }
781
+ else {
782
+ if (!options.field) {
783
+ error(`--op ${options.op} requires --field.`);
784
+ process.exit(1);
785
+ }
786
+ operation.field = options.field;
787
+ }
788
+ const filter = parseFilterOptions(options);
789
+ const groupBy = options.groupBy || [];
255
790
  const client = new ApiClient();
256
791
  try {
257
- const result = await client.listDatabaseGroupPermissions(resolvedAppId, databaseId);
258
- const list = Array.isArray(result) ? result : result?.permissions ?? [];
792
+ const result = await client.aggregateDatabaseRecords(resolvedAppId, databaseId, modelName, { operations: [operation], groupBy, filter });
259
793
  if (options.json) {
260
- json(list);
794
+ json(result);
261
795
  return;
262
796
  }
263
- if (list.length === 0) {
264
- info("No group permissions found.");
797
+ const aggregated = result?.result;
798
+ // Label the value column after the operation, including the field it
799
+ // ran over: `SUM` alone does not say what was summed. The field name is
800
+ // reproduced verbatim in both labels — it is a user-supplied
801
+ // identifier, and case-folding it produced `avg(lastvalue)` for
802
+ // `--field lastValue` (issue #2357).
803
+ const valueLabel = options.op === "count"
804
+ ? "COUNT"
805
+ : `${options.op.toUpperCase()}(${options.field})`;
806
+ const scalarLabel = options.op === "count"
807
+ ? "count"
808
+ : `${options.op.toLowerCase()}(${options.field})`;
809
+ if (groupBy.length === 0) {
810
+ // Ungrouped: one scalar per operation, keyed by the endpoint's
811
+ // operation name (`count`, `sum_<field>`, …). Render it as a
812
+ // key/value line — there is no group column to table.
813
+ const value = (aggregated ?? {})[options.op === "count" ? "count" : `${options.op}_${options.field}`];
814
+ keyValue(scalarLabel, value === null || value === undefined ? "—" : String(value));
265
815
  return;
266
816
  }
267
- console.log(formatTable(list, [
268
- { header: "GROUP_TYPE", key: "groupType" },
269
- { header: "GROUP_ID", key: "groupId" },
270
- { header: "PERMISSION", key: "permission" },
271
- { header: "GRANTED", key: "grantedAt", format: formatDate },
272
- ]));
817
+ if (aggregated &&
818
+ typeof aggregated === "object" &&
819
+ !Array.isArray(aggregated) &&
820
+ Object.values(aggregated).every((v) => typeof v !== "object" || v === null)) {
821
+ // Flat { group -> value } shape (single operation, single group-by): render a table.
822
+ const rows = Object.entries(aggregated).map(([group, value]) => ({
823
+ group,
824
+ value: value === null || value === undefined ? "—" : String(value),
825
+ }));
826
+ console.log(formatTable(rows, [
827
+ { header: "GROUP", key: "group" },
828
+ { header: valueLabel, key: "value" },
829
+ ]));
830
+ }
831
+ else {
832
+ // Grouped/nested or multi-operation shape: print the structured result.
833
+ console.log(JSON.stringify(aggregated ?? {}, null, 2));
834
+ }
273
835
  }
274
836
  catch (err) {
275
837
  error(err.message);
276
838
  process.exit(1);
277
839
  }
278
840
  });
279
- // Grant group permission
280
- groupPermissions
281
- .command("grant")
282
- .description("Grant a group permission on a database")
841
+ // Upsert a record (create, or merge into an existing one)
842
+ records
843
+ .command("save")
844
+ .description("Create a record, or merge fields into an existing one (admin only)")
283
845
  .argument("<database-id>", "Database ID")
284
- .requiredOption("--group-type <type>", "Group type")
285
- .requiredOption("--group-id <id>", "Group ID")
286
- .requiredOption("--permission <permission>", "Permission level: read-write or reader")
846
+ .argument("<model-name>", "Model name")
847
+ .argument("[record-id]", "Record ID (generated when omitted)")
287
848
  .option("--app <app-id>", "App ID")
849
+ .option("--data <json>", "Record fields as inline JSON")
850
+ .option("--data-file <path>", "Read the record fields from a JSON file")
288
851
  .option("--json", "Output as JSON")
289
- .action(async (databaseId, options) => {
852
+ .action(async (databaseId, modelName, recordId, options) => {
290
853
  const resolvedAppId = resolveAppId(undefined, options);
854
+ const data = parseDataOption(options, "record");
291
855
  const client = new ApiClient();
856
+ // The DatabaseDO requires an id on the plain save path (it only generates
857
+ // one for `upsertOn` writes). Mint the id client-side for a create so
858
+ // `save` works without an id, the same way CSV import does
859
+ // (`lib/csv.ts`).
860
+ const id = recordId || ulid();
861
+ assertDataIdMatches(data, recordId, id, "primitive databases records save <database-id> <model-name>");
292
862
  try {
293
- const result = await client.grantDatabaseGroupPermission(resolvedAppId, databaseId, {
294
- groupType: options.groupType,
295
- groupId: options.groupId,
296
- permission: options.permission,
297
- });
863
+ const result = await client.saveDatabaseRecord(resolvedAppId, databaseId, modelName, id, data);
298
864
  if (options.json) {
299
865
  json(result);
300
866
  return;
301
867
  }
302
- success(`Permission '${options.permission}' granted to group ${options.groupType}/${options.groupId}.`);
868
+ renderRecordWriteResult(result, id, `Record saved to ${modelName}.`);
303
869
  }
304
870
  catch (err) {
305
871
  error(err.message);
306
872
  process.exit(1);
307
873
  }
308
874
  });
309
- // Revoke group permission
310
- groupPermissions
311
- .command("revoke")
312
- .description("Revoke a group's permission on a database")
875
+ // Patch a record (partial merge)
876
+ records
877
+ .command("patch")
878
+ .description("Merge fields into an existing record (admin only)")
879
+ .argument("<database-id>", "Database ID")
880
+ .argument("<model-name>", "Model name")
881
+ .argument("<record-id>", "Record ID")
882
+ .option("--app <app-id>", "App ID")
883
+ .option("--data <json>", "Fields to merge as inline JSON")
884
+ .option("--data-file <path>", "Read the fields to merge from a JSON file")
885
+ .option("--json", "Output as JSON")
886
+ .action(async (databaseId, modelName, recordId, options) => {
887
+ const resolvedAppId = resolveAppId(undefined, options);
888
+ const data = parseDataOption(options, "fields to merge");
889
+ const client = new ApiClient();
890
+ // Same guard as `save` — on this path `recordId` is required, so the
891
+ // "pass it as the argument" branch is unreachable here.
892
+ assertDataIdMatches(data, recordId, recordId, "primitive databases records patch <database-id> <model-name>");
893
+ try {
894
+ const result = await client.patchDatabaseRecord(resolvedAppId, databaseId, modelName, recordId, data);
895
+ if (options.json) {
896
+ json(result);
897
+ return;
898
+ }
899
+ renderRecordWriteResult(result, recordId, `Record ${recordId} patched in ${modelName}.`);
900
+ }
901
+ catch (err) {
902
+ error(err.message);
903
+ process.exit(1);
904
+ }
905
+ });
906
+ // Delete a single record
907
+ records
908
+ .command("delete")
909
+ .description("Delete a single record from a database model (admin only)")
313
910
  .argument("<database-id>", "Database ID")
314
- .argument("<group-type>", "Group type")
315
- .argument("<group-id>", "Group ID")
911
+ .argument("<model-name>", "Model name")
912
+ .argument("<record-id>", "Record ID to delete")
316
913
  .option("--app <app-id>", "App ID")
317
914
  .option("-y, --yes", "Skip confirmation prompt")
318
- .action(async (databaseId, groupType, groupId, options) => {
915
+ .option("--json", "Output as JSON")
916
+ .action(async (databaseId, modelName, recordId, options) => {
319
917
  const resolvedAppId = resolveAppId(undefined, options);
320
918
  if (!options.yes) {
321
- const inquirer = await import("inquirer");
322
- const { confirm } = await inquirer.default.prompt([
323
- {
324
- type: "confirm",
325
- name: "confirm",
326
- message: `Revoke permission for group ${groupType}/${groupId} on database ${databaseId}?`,
327
- default: false,
328
- },
329
- ]);
919
+ let confirm;
920
+ try {
921
+ confirm = await confirmPrompt(`Delete record ${recordId} from ${modelName}? This cannot be undone.`);
922
+ }
923
+ catch (err) {
924
+ error(err.message);
925
+ process.exit(1);
926
+ }
330
927
  if (!confirm) {
331
928
  info("Cancelled.");
332
929
  return;
@@ -334,13 +931,1473 @@ Examples:
334
931
  }
335
932
  const client = new ApiClient();
336
933
  try {
337
- await client.revokeDatabaseGroupPermission(resolvedAppId, databaseId, groupType, groupId);
338
- success(`Permission revoked for group ${groupType}/${groupId}.`);
934
+ const result = await client.deleteDatabaseRecord(resolvedAppId, databaseId, modelName, recordId);
935
+ if (options.json) {
936
+ json(result);
937
+ return;
938
+ }
939
+ success(`Record ${recordId} deleted from ${modelName}.`);
940
+ }
941
+ catch (err) {
942
+ error(err.message);
943
+ process.exit(1);
944
+ }
945
+ });
946
+ // Delete all records for a model
947
+ records
948
+ .command("delete-all")
949
+ .description("Delete all records for a model (queries then batch deletes, admin only)")
950
+ .argument("<database-id>", "Database ID")
951
+ .argument("<model-name>", "Model name")
952
+ .option("--app <app-id>", "App ID")
953
+ .option("--filter <json>", "Filter as JSON to select which records to delete")
954
+ .option("--filter-file <path>", "Read filter from a JSON or TOML file")
955
+ .option("-y, --yes", "Skip confirmation prompt")
956
+ .option("--json", "Output as JSON")
957
+ .action(async (databaseId, modelName, options) => {
958
+ const resolvedAppId = resolveAppId(undefined, options);
959
+ const client = new ApiClient();
960
+ const filter = parseFilterOptions(options);
961
+ try {
962
+ // First, query to find all matching records
963
+ let allRecords = [];
964
+ let cursor;
965
+ let hasMore = true;
966
+ while (hasMore) {
967
+ const result = await client.queryDatabaseRecords(resolvedAppId, databaseId, modelName, { filter, limit: 100, cursor });
968
+ const records = result.items;
969
+ allRecords = allRecords.concat(records);
970
+ cursor = result.nextCursor;
971
+ hasMore = !!cursor && records.length > 0;
972
+ }
973
+ if (allRecords.length === 0) {
974
+ if (options.json) {
975
+ json({ deleted: 0, modelName });
976
+ return;
977
+ }
978
+ info("No matching records found.");
979
+ return;
980
+ }
981
+ if (!options.yes) {
982
+ let confirm;
983
+ try {
984
+ confirm = await confirmPrompt(`Delete ${allRecords.length} record(s) from ${modelName}? This cannot be undone.`);
985
+ }
986
+ catch (err) {
987
+ error(err.message);
988
+ process.exit(1);
989
+ }
990
+ if (!confirm) {
991
+ info("Cancelled.");
992
+ return;
993
+ }
994
+ }
995
+ // Batch delete in chunks of 50
996
+ const BATCH_SIZE = 50;
997
+ let deleted = 0;
998
+ for (let i = 0; i < allRecords.length; i += BATCH_SIZE) {
999
+ const chunk = allRecords.slice(i, i + BATCH_SIZE);
1000
+ const operations = chunk.map((r) => ({
1001
+ op: "delete",
1002
+ modelName,
1003
+ id: r.id,
1004
+ }));
1005
+ await client.batchDeleteDatabaseRecords(resolvedAppId, databaseId, operations);
1006
+ deleted += chunk.length;
1007
+ }
1008
+ if (options.json) {
1009
+ json({ deleted, modelName });
1010
+ return;
1011
+ }
1012
+ success(`Deleted ${deleted} record(s) from ${modelName}.`);
339
1013
  }
340
1014
  catch (err) {
341
1015
  error(err.message);
342
1016
  process.exit(1);
343
1017
  }
344
1018
  });
1019
+ // Apply an atomic multi-model operations blob (issue #2437).
1020
+ //
1021
+ // Takes the SAME `--data-file` blob as `documents records bulk` — one file
1022
+ // works against either surface — and translates it to the DatabaseDO's
1023
+ // `records/batch` wire shape (`{ op, modelName, id, data }`) with
1024
+ // `atomic: true`, so the whole blob is all-or-nothing like the documents
1025
+ // twin. Both guards the documents blob can carry survive the translation:
1026
+ // `action: create` maps to `save` with `ifNotExists: true` (the DatabaseDO's
1027
+ // strict-create flag, a 409 `ALREADY_EXISTS` inside the transaction), and an
1028
+ // op's `precondition` maps to the DO's per-op `condition` (a 409
1029
+ // `CONDITION_NOT_MET`). Both abort the whole batch, matching the documents
1030
+ // twin.
1031
+ const BULK_ACTIONS = ["create", "patch", "delete"];
1032
+ const BULK_ACTION_TO_OP = {
1033
+ create: "save",
1034
+ patch: "patch",
1035
+ delete: "delete",
1036
+ };
1037
+ // Mirrors the documents surface's `BULK_WRITE_OP_KEYS` / `BULK_DELETE_OP_KEYS`
1038
+ // (`src/document-models.ts`). Unknown keys are an error rather than ignored:
1039
+ // a guard the author asked for must never be dropped silently.
1040
+ const BULK_OP_KEYS = ["model", "action", "id", "data", "precondition"];
1041
+ const BULK_DELETE_OP_KEYS = ["model", "action", "id", "precondition"];
1042
+ records
1043
+ .command("bulk")
1044
+ .description("Apply an atomic create/patch/delete operations blob to a database (admin only)")
1045
+ .argument("<database-id>", "Database ID")
1046
+ .requiredOption("--data-file <file>", "JSON file with { operations: [...] } or a bare operations array. " +
1047
+ "Each op is { model, action: create|patch|delete, id, data, precondition? } " +
1048
+ "— the same shape `documents records bulk` takes. `data` holds the " +
1049
+ "record fields and is required on create/patch, not allowed on delete. " +
1050
+ "A `create` against an id that already exists fails the whole batch, " +
1051
+ "and a `precondition` that does not hold rolls the whole batch back")
1052
+ .option("--app <app-id>", "App ID")
1053
+ .option("-y, --yes", "Skip confirmation prompt")
1054
+ .option("--json", "Output as JSON")
1055
+ .action(async (databaseId, options) => {
1056
+ const parsed = parseDataOption(options, "operations blob", {
1057
+ allowArray: true,
1058
+ });
1059
+ const rawOperations = Array.isArray(parsed) ? parsed : parsed?.operations;
1060
+ if (!Array.isArray(rawOperations) || rawOperations.length === 0) {
1061
+ error("--data-file must contain { operations: [...] } or a non-empty operations array.");
1062
+ process.exit(1);
1063
+ }
1064
+ // Translate to the batch wire shape, rejecting a malformed op before any
1065
+ // request goes out so the caller sees which entry is wrong.
1066
+ const operations = [];
1067
+ for (let i = 0; i < rawOperations.length; i++) {
1068
+ const op = rawOperations[i];
1069
+ if (!op || typeof op !== "object" || Array.isArray(op)) {
1070
+ error(`Operation ${i}: each operation must be a JSON object.`);
1071
+ process.exit(1);
1072
+ }
1073
+ const action = op.action;
1074
+ if (!BULK_ACTIONS.includes(action)) {
1075
+ error(`Operation ${i}: invalid action "${action}". Expected one of: ${BULK_ACTIONS.join(", ")}.`);
1076
+ process.exit(1);
1077
+ }
1078
+ if (!op.model || typeof op.model !== "string") {
1079
+ error(`Operation ${i}: "model" is required and must be a model name.`);
1080
+ process.exit(1);
1081
+ }
1082
+ if (!op.id || typeof op.id !== "string") {
1083
+ error(`Operation ${i}: "id" is required.`);
1084
+ process.exit(1);
1085
+ }
1086
+ // `data` on a delete gets its own message before the allowlist runs, so
1087
+ // the caller is not told a first-class key is "unknown".
1088
+ if (action === "delete" && op.data !== undefined) {
1089
+ error(`Operation ${i}: "data" is not allowed on a delete.`);
1090
+ process.exit(1);
1091
+ }
1092
+ const allowedKeys = action === "delete" ? BULK_DELETE_OP_KEYS : BULK_OP_KEYS;
1093
+ const unknownKey = Object.keys(op).find((k) => !allowedKeys.includes(k));
1094
+ if (unknownKey) {
1095
+ error(`Operation ${i}: unknown key "${unknownKey}". Expected one of: ${allowedKeys.join(", ")}.`);
1096
+ process.exit(1);
1097
+ }
1098
+ // A `precondition` is field-equality only, the same grammar the
1099
+ // documents surface enforces (`validatePrecondition` in
1100
+ // `src/document-models.ts`), so one blob means the same thing on both.
1101
+ // `preconditionToCondition` translates it to the DO's per-op
1102
+ // `condition`, checked inside the transaction: a mismatch is a 409 that
1103
+ // rolls the whole batch back.
1104
+ let condition;
1105
+ if (op.precondition !== undefined && op.precondition !== null) {
1106
+ if (typeof op.precondition !== "object" || Array.isArray(op.precondition)) {
1107
+ error(`Operation ${i}: "precondition" must be a field-equality object ({ field: scalar, … }).`);
1108
+ process.exit(1);
1109
+ }
1110
+ for (const [field, expected] of Object.entries(op.precondition)) {
1111
+ if (field.startsWith("$")) {
1112
+ error(`Operation ${i}: precondition operator "${field}" is not supported — preconditions are field-equality only ({ field: scalar, … }).`);
1113
+ process.exit(1);
1114
+ }
1115
+ if (expected !== null && typeof expected === "object") {
1116
+ error(`Operation ${i}: precondition on field "${field}" must be a scalar equality value — operators and nested objects/arrays are not supported.`);
1117
+ process.exit(1);
1118
+ }
1119
+ // Fail loudly on the values the `condition` grammar cannot check
1120
+ // exactly, rather than running with a weaker guard than the caller
1121
+ // wrote (issue #2437; the grammar fix is tracked in #2507).
1122
+ const untranslatable = untranslatablePreconditionValue(expected);
1123
+ if (untranslatable) {
1124
+ error(`Operation ${i}: precondition on field "${field}" is not supported — ${untranslatable}. ` +
1125
+ `Guard on a field whose value is a string or a number other than 0/1, or read the record ` +
1126
+ `first and gate the write on that.`);
1127
+ process.exit(1);
1128
+ }
1129
+ }
1130
+ condition = preconditionToCondition(op.precondition);
1131
+ }
1132
+ if (action === "delete") {
1133
+ if (op.data !== undefined) {
1134
+ error(`Operation ${i}: "data" is not allowed on a delete.`);
1135
+ process.exit(1);
1136
+ }
1137
+ operations.push({
1138
+ op: "delete",
1139
+ modelName: op.model,
1140
+ id: op.id,
1141
+ ...(condition ? { condition } : {}),
1142
+ });
1143
+ continue;
1144
+ }
1145
+ if (!op.data ||
1146
+ typeof op.data !== "object" ||
1147
+ Array.isArray(op.data) ||
1148
+ Object.keys(op.data).length === 0) {
1149
+ error(`Operation ${i}: "data" is required and must be a non-empty object on a ${action}.`);
1150
+ process.exit(1);
1151
+ }
1152
+ operations.push({
1153
+ op: BULK_ACTION_TO_OP[action],
1154
+ modelName: op.model,
1155
+ id: op.id,
1156
+ data: op.data,
1157
+ // `create` is a STRICT create on both twins: `ifNotExists` is the
1158
+ // DatabaseDO batch's strict-create flag (409 `ALREADY_EXISTS`), so a
1159
+ // create against a live id fails the batch instead of merging.
1160
+ ...(action === "create" ? { ifNotExists: true } : {}),
1161
+ ...(condition ? { condition } : {}),
1162
+ });
1163
+ }
1164
+ const resolvedAppId = resolveAppId(undefined, options);
1165
+ if (!options.yes) {
1166
+ let confirm;
1167
+ try {
1168
+ confirm = await confirmPrompt(`Apply ${operations.length} operation(s) atomically to database ${databaseId}?`);
1169
+ }
1170
+ catch (err) {
1171
+ error(err.message);
1172
+ process.exit(1);
1173
+ }
1174
+ if (!confirm) {
1175
+ info("Cancelled.");
1176
+ return;
1177
+ }
1178
+ }
1179
+ const client = new ApiClient();
1180
+ try {
1181
+ await client.batchDatabaseRecords(resolvedAppId, databaseId, operations, {
1182
+ atomic: true,
1183
+ });
1184
+ // The batch endpoint answers with a per-operation `results` array; the
1185
+ // documents twin answers with a rolled-up summary. Report the twin's
1186
+ // summary so one blob produces one contract on both surfaces — the
1187
+ // batch is atomic, so a 2xx means every op in the input applied.
1188
+ //
1189
+ // One reporting difference, documented alongside the verb: the
1190
+ // documents twin's `deleted` counts records actually removed, because
1191
+ // its DO reports that. The database batch issues a plain DELETE and
1192
+ // reports no rows-affected, so `deleted` here counts delete operations
1193
+ // applied — deleting an id that was not there still counts 1.
1194
+ const added = rawOperations
1195
+ .filter((op) => op.action === "create")
1196
+ .map((op) => ({ model: op.model, id: op.id }));
1197
+ const updated = rawOperations
1198
+ .filter((op) => op.action === "patch")
1199
+ .map((op) => ({ model: op.model, id: op.id }));
1200
+ const deleted = rawOperations.filter((op) => op.action === "delete").length;
1201
+ const summary = {
1202
+ applied: added.length + updated.length + deleted,
1203
+ added,
1204
+ updated,
1205
+ deleted,
1206
+ };
1207
+ if (options.json) {
1208
+ json(summary);
1209
+ return;
1210
+ }
1211
+ success(`Applied ${summary.applied} operation(s): ` +
1212
+ `${added.length} added, ${updated.length} updated, ${deleted} deleted.`);
1213
+ }
1214
+ catch (err) {
1215
+ error(err.message);
1216
+ process.exit(1);
1217
+ }
1218
+ });
1219
+ // ---- CEL context subcommand group ----
1220
+ // `cel-context` is the user-facing name for the dict that feeds CEL
1221
+ // access rules and filter placeholders. `metadata` is kept as a hidden
1222
+ // alias for backwards compatibility with existing scripts.
1223
+ const registerCelContextGroup = (name, hidden) => {
1224
+ const group = databases
1225
+ .command(name, { hidden })
1226
+ .description(hidden
1227
+ ? "Manage database CEL context (alias of 'cel-context')"
1228
+ : "Manage database CEL context (the dict referenced by access rules and filters)");
1229
+ group
1230
+ .command("get")
1231
+ .description("Read database CEL context")
1232
+ .argument("<database-id>", "Database ID")
1233
+ .option("--app <app-id>", "App ID")
1234
+ .option("--json", "Output as JSON")
1235
+ .action(async (databaseId, options) => {
1236
+ const resolvedAppId = resolveAppId(undefined, options);
1237
+ const client = new ApiClient();
1238
+ try {
1239
+ const result = await client.getDatabaseCelContext(resolvedAppId, databaseId);
1240
+ if (options.json) {
1241
+ json(result);
1242
+ return;
1243
+ }
1244
+ printResult("Database ID", result.databaseId);
1245
+ const ctx = result.celContext ?? result.metadata;
1246
+ if (ctx && Object.keys(ctx).length > 0) {
1247
+ printResult("CEL Context", JSON.stringify(ctx, null, 2));
1248
+ }
1249
+ else {
1250
+ info("No CEL context set.");
1251
+ }
1252
+ }
1253
+ catch (err) {
1254
+ error(err.message);
1255
+ process.exit(1);
1256
+ }
1257
+ });
1258
+ group
1259
+ .command("update")
1260
+ .description("Update database CEL context (merge with existing)")
1261
+ .argument("<database-id>", "Database ID")
1262
+ .requiredOption("--data <json>", "CEL context fields as JSON (merged with existing)")
1263
+ .option("--app <app-id>", "App ID")
1264
+ .option("--json", "Output as JSON")
1265
+ .action(async (databaseId, options) => {
1266
+ const resolvedAppId = resolveAppId(undefined, options);
1267
+ const client = new ApiClient();
1268
+ let data;
1269
+ try {
1270
+ data = JSON.parse(options.data);
1271
+ }
1272
+ catch {
1273
+ error("Invalid --data JSON.");
1274
+ process.exit(1);
1275
+ return;
1276
+ }
1277
+ try {
1278
+ const result = await client.updateDatabaseCelContext(resolvedAppId, databaseId, data);
1279
+ if (options.json) {
1280
+ json(result);
1281
+ return;
1282
+ }
1283
+ success("CEL context updated.");
1284
+ const ctx = result.celContext ?? result.metadata;
1285
+ if (ctx) {
1286
+ keyValue("CEL Context", JSON.stringify(ctx));
1287
+ }
1288
+ }
1289
+ catch (err) {
1290
+ error(err.message);
1291
+ process.exit(1);
1292
+ }
1293
+ });
1294
+ };
1295
+ registerCelContextGroup("cel-context", false);
1296
+ // Hidden legacy alias — `primitive databases metadata get/update` still works.
1297
+ registerCelContextGroup("metadata", true);
1298
+ // ---- Operations subcommand group ----
1299
+ const operations = databases
1300
+ .command("operations")
1301
+ .description("List and execute registered operations on a database");
1302
+ // List operations
1303
+ operations
1304
+ .command("list")
1305
+ .description("List registered operations available on a database")
1306
+ .argument("<database-id>", "Database ID")
1307
+ .option("--app <app-id>", "App ID")
1308
+ .option("--json", "Output as JSON")
1309
+ .action(async (databaseId, options) => {
1310
+ const resolvedAppId = resolveAppId(undefined, options);
1311
+ const client = new ApiClient();
1312
+ try {
1313
+ const result = await client.listDatabaseOperations(resolvedAppId, databaseId);
1314
+ const list = Array.isArray(result) ? result : [];
1315
+ if (options.json) {
1316
+ json(list);
1317
+ return;
1318
+ }
1319
+ if (list.length === 0) {
1320
+ info("No operations found.");
1321
+ return;
1322
+ }
1323
+ console.log(formatTable(list, [
1324
+ { header: "NAME", key: "name" },
1325
+ { header: "TYPE", key: "type" },
1326
+ { header: "MODEL", key: "modelName" },
1327
+ { header: "ACCESS", key: "access" },
1328
+ ]));
1329
+ }
1330
+ catch (err) {
1331
+ error(err.message);
1332
+ process.exit(1);
1333
+ }
1334
+ });
1335
+ // Execute operation
1336
+ operations
1337
+ .command("execute")
1338
+ .description("Execute a registered operation on a database")
1339
+ .argument("<database-id>", "Database ID")
1340
+ .argument("<operation-name>", "Operation name")
1341
+ .option("--params <json>", "Operation parameters as JSON")
1342
+ .option("--limit <n>", "Max records to return (for queries)")
1343
+ .option("--cursor <cursor>", "Pagination cursor")
1344
+ .option("--token <jwt>", "Execute as a specific user (dev/test — JWT visible in process args)")
1345
+ .option("--app <app-id>", "App ID")
1346
+ .option("--json", "Output as JSON")
1347
+ .option("--timing", "Show server-side timing breakdown")
1348
+ .action(async (databaseId, operationName, options) => {
1349
+ const resolvedAppId = resolveAppId(undefined, options);
1350
+ const client = new ApiClient();
1351
+ let params;
1352
+ if (options.params) {
1353
+ try {
1354
+ params = JSON.parse(options.params);
1355
+ }
1356
+ catch {
1357
+ error("Invalid --params JSON.");
1358
+ process.exit(1);
1359
+ return;
1360
+ }
1361
+ }
1362
+ const body = {};
1363
+ if (params)
1364
+ body.params = params;
1365
+ if (options.limit)
1366
+ body.limit = parseInt(options.limit, 10);
1367
+ if (options.cursor)
1368
+ body.cursor = options.cursor;
1369
+ try {
1370
+ const result = await client.executeDatabaseOperation(resolvedAppId, databaseId, operationName, body, options.token, { timing: !!options.timing });
1371
+ if (options.json) {
1372
+ json(result);
1373
+ return;
1374
+ }
1375
+ // Smart display based on result shape. `executeDatabaseOperation()`
1376
+ // has already normalized a query page to `{ items, hasMore,
1377
+ // nextCursor? }` (#2440), so `items` is exactly "this result was a
1378
+ // list" — the two branches cannot disagree about it.
1379
+ if (Array.isArray(result.items)) {
1380
+ if (result.items.length === 0) {
1381
+ info("No records found.");
1382
+ }
1383
+ else {
1384
+ const cols = Object.keys(result.items[0]).filter((k) => k !== "type");
1385
+ console.log(formatTable(result.items, cols.map((c) => ({
1386
+ header: c.toUpperCase(),
1387
+ key: c,
1388
+ format: (v) => {
1389
+ if (v === null || v === undefined)
1390
+ return "—";
1391
+ if (typeof v === "object") {
1392
+ const s = JSON.stringify(v);
1393
+ return s.length > 50 ? s.slice(0, 47) + "..." : s;
1394
+ }
1395
+ const s = String(v);
1396
+ return s.length > 50 ? s.slice(0, 47) + "..." : s;
1397
+ },
1398
+ }))));
1399
+ }
1400
+ // Gate on the cursor itself, the way `records query` does: `hasMore`
1401
+ // without a cursor used to print the literal `undefined` (#2440).
1402
+ if (result.nextCursor) {
1403
+ info(`More records available. Use --cursor ${result.nextCursor} to continue.`);
1404
+ }
1405
+ }
1406
+ else if (result.count !== undefined) {
1407
+ console.log(`Count: ${result.count}`);
1408
+ }
1409
+ else if (result.result !== undefined) {
1410
+ // Aggregate result
1411
+ json(result);
1412
+ }
1413
+ else if (result.results && Array.isArray(result.results)) {
1414
+ // Batch/mutation results
1415
+ success(`Operation executed (${result.results.length} result${result.results.length === 1 ? "" : "s"}).`);
1416
+ }
1417
+ else if (result.success !== undefined) {
1418
+ success("Operation executed.");
1419
+ }
1420
+ else {
1421
+ json(result);
1422
+ }
1423
+ // Display timing if present
1424
+ if (result._timing) {
1425
+ console.log("");
1426
+ console.log("Timing:");
1427
+ for (const [key, value] of Object.entries(result._timing)) {
1428
+ console.log(` ${key}: ${value}ms`);
1429
+ }
1430
+ }
1431
+ }
1432
+ catch (err) {
1433
+ error(err.message);
1434
+ process.exit(1);
1435
+ }
1436
+ });
1437
+ // ---- Indexes subcommand group ----
1438
+ const indexes = databases
1439
+ .command("indexes")
1440
+ .description("Manage indexes on a database");
1441
+ // List indexes
1442
+ indexes
1443
+ .command("list")
1444
+ .description("List indexes for a database or model")
1445
+ .argument("<database-id>", "Database ID")
1446
+ .option("--model <model-name>", "Filter by model name")
1447
+ .option("--app <app-id>", "App ID")
1448
+ .option("--json", "Output as JSON")
1449
+ .action(async (databaseId, options) => {
1450
+ const resolvedAppId = resolveAppId(undefined, options);
1451
+ const client = new ApiClient();
1452
+ try {
1453
+ const result = await client.listDatabaseIndexes(resolvedAppId, databaseId, options.model);
1454
+ const list = result.indexes || [];
1455
+ if (options.json) {
1456
+ json(list);
1457
+ return;
1458
+ }
1459
+ if (list.length === 0) {
1460
+ info("No indexes found.");
1461
+ return;
1462
+ }
1463
+ console.log(formatTable(list, [
1464
+ { header: "MODEL", key: "model_name" },
1465
+ { header: "FIELD", key: "field_name" },
1466
+ { header: "TYPE", key: "field_type" },
1467
+ { header: "UNIQUE", key: "is_unique", format: (v) => (v ? "Yes" : "No") },
1468
+ ]));
1469
+ }
1470
+ catch (err) {
1471
+ error(err.message);
1472
+ process.exit(1);
1473
+ }
1474
+ });
1475
+ // Register index
1476
+ indexes
1477
+ .command("create")
1478
+ .description("Create an index on a model field")
1479
+ .argument("<database-id>", "Database ID")
1480
+ .requiredOption("--model <model-name>", "Model name")
1481
+ .requiredOption("--field <field-name>", "Field name to index")
1482
+ .option("--type <field-type>", "Field type: string, number, or boolean", "string")
1483
+ .option("--unique", "Make this a unique index")
1484
+ .option("--app <app-id>", "App ID")
1485
+ .option("--json", "Output as JSON")
1486
+ .action(async (databaseId, options) => {
1487
+ const resolvedAppId = resolveAppId(undefined, options);
1488
+ const client = new ApiClient();
1489
+ try {
1490
+ const result = await client.registerDatabaseIndex(resolvedAppId, databaseId, {
1491
+ modelName: options.model,
1492
+ fieldName: options.field,
1493
+ fieldType: options.type,
1494
+ unique: !!options.unique,
1495
+ });
1496
+ if (options.json) {
1497
+ json(result);
1498
+ return;
1499
+ }
1500
+ success(`Index created on ${options.model}.${options.field} (${options.type}${options.unique ? ", unique" : ""}).`);
1501
+ }
1502
+ catch (err) {
1503
+ error(err.message);
1504
+ process.exit(1);
1505
+ }
1506
+ });
1507
+ // Drop index
1508
+ indexes
1509
+ .command("drop")
1510
+ .description("Drop an index from a model field")
1511
+ .argument("<database-id>", "Database ID")
1512
+ .requiredOption("--model <model-name>", "Model name")
1513
+ .requiredOption("--field <field-name>", "Field name")
1514
+ .option("--app <app-id>", "App ID")
1515
+ .option("-y, --yes", "Skip confirmation prompt")
1516
+ .action(async (databaseId, options) => {
1517
+ const resolvedAppId = resolveAppId(undefined, options);
1518
+ if (!options.yes) {
1519
+ let confirm;
1520
+ try {
1521
+ confirm = await confirmPrompt(`Drop index on ${options.model}.${options.field}?`);
1522
+ }
1523
+ catch (err) {
1524
+ error(err.message);
1525
+ process.exit(1);
1526
+ }
1527
+ if (!confirm) {
1528
+ info("Cancelled.");
1529
+ return;
1530
+ }
1531
+ }
1532
+ const client = new ApiClient();
1533
+ try {
1534
+ await client.dropDatabaseIndex(resolvedAppId, databaseId, {
1535
+ modelName: options.model,
1536
+ fieldName: options.field,
1537
+ });
1538
+ success(`Index dropped on ${options.model}.${options.field}.`);
1539
+ }
1540
+ catch (err) {
1541
+ error(err.message);
1542
+ process.exit(1);
1543
+ }
1544
+ });
1545
+ // Reindex an existing instance from its type schema (issue #974). The
1546
+ // on-demand remedy that brings a pre-existing database into compliance after
1547
+ // a schema declares a field `unique = true` — registers any declared-but-
1548
+ // missing unique index so `upsertOn` ops resolve. Idempotent.
1549
+ databases
1550
+ .command("reindex")
1551
+ .description("Reprovision a database's unique indexes from its type schema")
1552
+ .argument("<database-id>", "Database ID")
1553
+ .requiredOption("--from-schema", "Reprovision unique indexes declared in the type schema")
1554
+ .option("--app <app-id>", "App ID")
1555
+ .option("--json", "Output as JSON")
1556
+ .action(async (databaseId, options) => {
1557
+ const resolvedAppId = resolveAppId(undefined, options);
1558
+ const client = new ApiClient();
1559
+ try {
1560
+ const res = await client.reindexDatabaseFromSchema(resolvedAppId, databaseId);
1561
+ if (options.json) {
1562
+ json(res);
1563
+ return;
1564
+ }
1565
+ if (res.skipped) {
1566
+ info(`Nothing to reindex (${res.reason}).`);
1567
+ return;
1568
+ }
1569
+ success(`Reindexed from schema: ${res.registered} unique index${res.registered === 1 ? "" : "es"} provisioned.`);
1570
+ }
1571
+ catch (err) {
1572
+ error(err.message);
1573
+ process.exit(1);
1574
+ }
1575
+ });
1576
+ // ---- Export / Import commands ----
1577
+ databases
1578
+ .command("export")
1579
+ .description("Export a database (records, indexes, constraints)")
1580
+ .argument("[app-id]", "App ID (uses current app if not specified)")
1581
+ .argument("<database-id>", "Database ID to export")
1582
+ .option("--app <app-id>", "App ID")
1583
+ .option("--output <dir>", "Output directory", "./primitive-export")
1584
+ .option("--json", "Output as JSON")
1585
+ .action(async (first, second, options) => {
1586
+ let resolvedAppId;
1587
+ let databaseId;
1588
+ if (second && !second.startsWith("-")) {
1589
+ resolvedAppId = resolveAppId(first, options);
1590
+ databaseId = second;
1591
+ }
1592
+ else {
1593
+ resolvedAppId = resolveAppId(undefined, options);
1594
+ databaseId = first;
1595
+ }
1596
+ if (!databaseId) {
1597
+ error("Database ID is required.");
1598
+ process.exit(1);
1599
+ }
1600
+ const client = new ApiClient();
1601
+ try {
1602
+ await exportSingleDatabase(client, resolvedAppId, databaseId, options.output, options.json);
1603
+ }
1604
+ catch (err) {
1605
+ error(err.message);
1606
+ process.exit(1);
1607
+ }
1608
+ });
1609
+ databases
1610
+ .command("import")
1611
+ .description("Import a database from an export directory")
1612
+ .argument("[app-id]", "App ID (uses current app if not specified)")
1613
+ .argument("<path>", "Path to database export directory")
1614
+ .option("--app <app-id>", "App ID")
1615
+ .option("--overwrite", "Replace existing database if ID collides")
1616
+ .option("--dry-run", "Show what would be imported without making changes")
1617
+ .option("--batch-size <n>", "Records per batch write request (default: 5000)", "5000")
1618
+ .option("--stop-on-error", "Abort the whole run on the first failing chunk (default: continue and report)")
1619
+ .option("--json", "Output as JSON")
1620
+ .action(async (first, second, options) => {
1621
+ let resolvedAppId;
1622
+ let importPath;
1623
+ if (second && !second.startsWith("-")) {
1624
+ resolvedAppId = resolveAppId(first, options);
1625
+ importPath = second;
1626
+ }
1627
+ else {
1628
+ resolvedAppId = resolveAppId(undefined, options);
1629
+ importPath = first;
1630
+ }
1631
+ if (!importPath) {
1632
+ error("Import path is required.");
1633
+ process.exit(1);
1634
+ }
1635
+ // Validate --batch-size up front so a bad value fails before any write.
1636
+ // Unlike `import-csv` (registered-batch path, hard 100k server cap),
1637
+ // `records/batch` has no fixed server item cap — bound it with a
1638
+ // conservative client-side ceiling to keep each request within
1639
+ // Cloudflare body-size and Durable Object memory limits.
1640
+ const parsedBatchSize = parseBatchSize(options.batchSize, {
1641
+ max: IMPORT_BATCH_SIZE_CEILING,
1642
+ overMaxMessage: `--batch-size cannot exceed ${IMPORT_BATCH_SIZE_CEILING} (a conservative client-side limit for batch write requests).`,
1643
+ });
1644
+ if ("error" in parsedBatchSize) {
1645
+ error(parsedBatchSize.error);
1646
+ process.exit(1);
1647
+ return;
1648
+ }
1649
+ const batchSize = parsedBatchSize.value;
1650
+ const client = new ApiClient();
1651
+ try {
1652
+ // Determine if this is a manifest-based export or a single database
1653
+ let dbDirs = [];
1654
+ const manifestPath = path.join(importPath, "manifest.json");
1655
+ if (existsSync(path.join(importPath, "metadata.json"))) {
1656
+ // Single database directory
1657
+ dbDirs = [importPath];
1658
+ }
1659
+ else if (existsSync(manifestPath)) {
1660
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf-8"));
1661
+ for (const dbId of manifest.databases || []) {
1662
+ const dbDir = path.join(importPath, "databases", dbId);
1663
+ if (existsSync(dbDir)) {
1664
+ dbDirs.push(dbDir);
1665
+ }
1666
+ }
1667
+ }
1668
+ else if (existsSync(path.join(importPath, "databases"))) {
1669
+ const entries = readdirSync(path.join(importPath, "databases"), { withFileTypes: true });
1670
+ for (const entry of entries) {
1671
+ if (entry.isDirectory()) {
1672
+ dbDirs.push(path.join(importPath, "databases", entry.name));
1673
+ }
1674
+ }
1675
+ }
1676
+ else {
1677
+ error("No valid database export data found at the specified path.");
1678
+ process.exit(1);
1679
+ }
1680
+ if (dbDirs.length === 0) {
1681
+ info("No databases to import.");
1682
+ return;
1683
+ }
1684
+ const summary = {
1685
+ created: 0,
1686
+ updated: 0,
1687
+ skipped: 0,
1688
+ recordsImported: 0,
1689
+ recordsFailed: 0,
1690
+ batches: 0,
1691
+ aborted: false,
1692
+ indexesRegistered: 0,
1693
+ batchErrors: [],
1694
+ };
1695
+ for (const dbDir of dbDirs) {
1696
+ await importSingleDatabase(client, resolvedAppId, dbDir, {
1697
+ overwrite: options.overwrite || false,
1698
+ dryRun: options.dryRun || false,
1699
+ batchSize,
1700
+ stopOnError: options.stopOnError || false,
1701
+ json: options.json || false,
1702
+ summary,
1703
+ });
1704
+ // Fork 3: --stop-on-error stops the whole run across a multi-DB dir.
1705
+ if (summary.aborted)
1706
+ break;
1707
+ }
1708
+ if (options.json) {
1709
+ json({ ...summary, dryRun: options.dryRun || false });
1710
+ }
1711
+ else {
1712
+ success("Database import complete:");
1713
+ keyValue(" Databases created", String(summary.created));
1714
+ if (summary.updated > 0)
1715
+ keyValue(" Databases updated", String(summary.updated));
1716
+ if (summary.skipped > 0)
1717
+ keyValue(" Databases skipped", String(summary.skipped));
1718
+ keyValue(" Records imported", String(summary.recordsImported));
1719
+ if (summary.recordsFailed > 0)
1720
+ keyValue(" Records failed", String(summary.recordsFailed));
1721
+ keyValue(" Batches", String(summary.batches));
1722
+ if (summary.indexesRegistered > 0)
1723
+ keyValue(" Indexes registered", String(summary.indexesRegistered));
1724
+ if (summary.aborted)
1725
+ warn("Aborted after a failing chunk (--stop-on-error).");
1726
+ if (summary.batchErrors.length > 0) {
1727
+ error(`${summary.batchErrors.length} chunk(s) errored:`);
1728
+ for (const e of summary.batchErrors) {
1729
+ error(` ${e.database} batch ${e.batch + 1}: ${e.error}`);
1730
+ }
1731
+ }
1732
+ }
1733
+ // Non-zero exit if any chunk errored (default continue-and-report or
1734
+ // --stop-on-error both surface failures this way).
1735
+ if (summary.batchErrors.length > 0) {
1736
+ process.exit(1);
1737
+ }
1738
+ }
1739
+ catch (err) {
1740
+ error(err.message);
1741
+ process.exit(1);
1742
+ }
1743
+ });
1744
+ // ============================================
1745
+ // CSV import (issue #145, Phase 1)
1746
+ // ============================================
1747
+ databases
1748
+ .command("import-csv")
1749
+ .description("Import rows from a CSV file into a database via a registered batch (bulk) save operation")
1750
+ .argument("<database-id>", "Database ID")
1751
+ .argument("<file>", "Path to the CSV file")
1752
+ .requiredOption("--model <name>", "Model name passed in each item's params")
1753
+ .option("--operation <op>", "Registered mutation operation to use (must be a {modelName,id,data} save-like op)", "seed_save")
1754
+ .option("--column-map <json>", 'Map CSV headers to field names, e.g. \'{"CSV Header":"fieldName"}\'')
1755
+ .option("--types <json>", 'Coerce fields by type, e.g. \'{"price":"number","active":"boolean"}\'')
1756
+ .option("--id-column <col>", "Use this CSV column for record ids (else a ULID is generated)")
1757
+ .option("--batch-size <n>", "Records per batch request (default: 5000)", "5000")
1758
+ .option("--delimiter <char>", "CSV field delimiter (default: ',')", ",")
1759
+ .option("--app <app-id>", "App ID")
1760
+ .option("--dry-run", "Parse + report row/batch counts without writing")
1761
+ .option("--stop-on-error", "Abort the whole import on the first chunk error (default: best-effort continue)")
1762
+ .option("--json", "Output a machine-readable result")
1763
+ .action(async (databaseId, file, options) => {
1764
+ const resolvedAppId = resolveAppId(undefined, options);
1765
+ const client = new ApiClient();
1766
+ // Parse JSON flags up front for clear errors.
1767
+ let columnMap;
1768
+ if (options.columnMap) {
1769
+ try {
1770
+ columnMap = JSON.parse(options.columnMap);
1771
+ }
1772
+ catch {
1773
+ error("Invalid --column-map JSON.");
1774
+ process.exit(1);
1775
+ return;
1776
+ }
1777
+ }
1778
+ let types;
1779
+ if (options.types) {
1780
+ try {
1781
+ types = JSON.parse(options.types);
1782
+ }
1783
+ catch {
1784
+ error("Invalid --types JSON.");
1785
+ process.exit(1);
1786
+ return;
1787
+ }
1788
+ }
1789
+ // The registered-batch (`executeBatch`) path rejects requests over
1790
+ // 100000 items server-side; keep chunks under it.
1791
+ const parsedBatchSize = parseBatchSize(options.batchSize, {
1792
+ max: 100000,
1793
+ overMaxMessage: "--batch-size cannot exceed 100000 (the server's per-request cap).",
1794
+ });
1795
+ if ("error" in parsedBatchSize) {
1796
+ error(parsedBatchSize.error);
1797
+ process.exit(1);
1798
+ return;
1799
+ }
1800
+ const batchSize = parsedBatchSize.value;
1801
+ if (!existsSync(file)) {
1802
+ error(`CSV file not found: ${file}`);
1803
+ process.exit(1);
1804
+ return;
1805
+ }
1806
+ try {
1807
+ // 1. Read + parse the CSV.
1808
+ const raw = readFileSync(file, "utf-8");
1809
+ let rows = parseCsv(raw, options.delimiter);
1810
+ // 2. Apply column map.
1811
+ rows = applyColumnMap(rows, columnMap);
1812
+ // 3. Coerce types, assign ids, shape into batch items.
1813
+ const { batch, rowCount } = buildRows(rows, {
1814
+ modelName: options.model,
1815
+ types,
1816
+ idColumn: options.idColumn,
1817
+ });
1818
+ const chunks = chunk(batch, batchSize);
1819
+ // 4. Validate the chosen op is an import-compatible save-like mutation
1820
+ // BEFORE writing (op-not-found / incompatible → clear up-front error
1821
+ // rather than per-row server-side failure). Skip the round-trip only
1822
+ // when there is genuinely nothing to import in a dry run.
1823
+ if (!options.dryRun || rowCount > 0) {
1824
+ await validateImportOperation(client, resolvedAppId, databaseId, options.operation);
1825
+ }
1826
+ // 5. Empty / headers-only CSV: no request, report 0/0.
1827
+ if (rowCount === 0) {
1828
+ if (options.json) {
1829
+ json({ imported: 0, failed: 0, rows: 0, batches: 0, errors: [], dryRun: !!options.dryRun });
1830
+ }
1831
+ else {
1832
+ info("No data rows found in CSV — nothing to import.");
1833
+ success("Imported: 0, Failed: 0");
1834
+ }
1835
+ return;
1836
+ }
1837
+ // 6. Dry run: report counts, no writes.
1838
+ if (options.dryRun) {
1839
+ if (options.json) {
1840
+ json({ dryRun: true, rows: rowCount, batches: chunks.length, batchSize });
1841
+ }
1842
+ else {
1843
+ info(`Dry run — no records written.`);
1844
+ keyValue(" Rows", String(rowCount));
1845
+ keyValue(" Batches", String(chunks.length));
1846
+ keyValue(" Batch size", String(batchSize));
1847
+ }
1848
+ return;
1849
+ }
1850
+ // 7. Import chunk by chunk; accumulate imported/failed + per-chunk errors.
1851
+ let imported = 0;
1852
+ let failed = 0;
1853
+ const errors = [];
1854
+ let aborted = false;
1855
+ for (let i = 0; i < chunks.length; i++) {
1856
+ const piece = chunks[i];
1857
+ try {
1858
+ const res = await client.executeBatch(resolvedAppId, databaseId, options.operation, piece);
1859
+ imported += res.imported ?? 0;
1860
+ failed += res.failed ?? 0;
1861
+ if (!options.json) {
1862
+ info(`Batch ${i + 1}/${chunks.length}: imported ${res.imported ?? 0}, failed ${res.failed ?? 0}`);
1863
+ }
1864
+ }
1865
+ catch (err) {
1866
+ const msg = err?.message || String(err);
1867
+ errors.push({ batch: i, error: msg });
1868
+ failed += piece.length;
1869
+ if (!options.json) {
1870
+ warn(`Batch ${i + 1}/${chunks.length} failed: ${msg}`);
1871
+ }
1872
+ if (options.stopOnError) {
1873
+ aborted = true;
1874
+ break;
1875
+ }
1876
+ }
1877
+ }
1878
+ if (options.json) {
1879
+ json({ imported, failed, rows: rowCount, batches: chunks.length, errors, aborted });
1880
+ }
1881
+ else {
1882
+ if (aborted) {
1883
+ warn(`Aborted after a chunk error (--stop-on-error).`);
1884
+ }
1885
+ success(`Imported: ${imported}, Failed: ${failed}`);
1886
+ if (errors.length > 0) {
1887
+ error(`${errors.length} batch(es) errored:`);
1888
+ for (const e of errors) {
1889
+ error(` Batch ${e.batch + 1}: ${e.error}`);
1890
+ }
1891
+ }
1892
+ }
1893
+ // Non-zero exit if any chunk errored.
1894
+ if (errors.length > 0) {
1895
+ process.exit(1);
1896
+ }
1897
+ }
1898
+ catch (err) {
1899
+ error(err.message);
1900
+ process.exit(1);
1901
+ }
1902
+ });
1903
+ // ============================================
1904
+ // Schema commands (issue #666)
1905
+ // ============================================
1906
+ const schema = databases
1907
+ .command("schema")
1908
+ .description("Manage the TOML schema attached to a database type");
1909
+ schema
1910
+ .command("generate")
1911
+ .description("Scaffold a starting TOML schema for <database-type> from existing operations + DO introspection, and insert it into the local database-types/<type>.toml file.")
1912
+ .argument("<database-type>", "Database type name")
1913
+ .option("--app <app-id>", "App ID")
1914
+ .option("--sync-dir <path>", "Override path to the sync directory (defaults to ./.primitive/sync/<env>/<appId>/)")
1915
+ .option("-f, --force", "Overwrite an existing [models.*] block in the local file")
1916
+ .option("--json", "Output the generated TOML as JSON")
1917
+ .action(async (databaseType, options) => {
1918
+ const resolvedAppId = resolveAppId(undefined, options);
1919
+ const client = new ApiClient();
1920
+ try {
1921
+ // 1. Call the server's :scaffold endpoint.
1922
+ const result = await client.scaffoldDatabaseTypeSchema(resolvedAppId, databaseType);
1923
+ const scaffoldedToml = result?.schema ?? "";
1924
+ if (options.json) {
1925
+ json({ schema: scaffoldedToml });
1926
+ return;
1927
+ }
1928
+ // 2. Locate the local `database-types/<type>.toml` file. Per the
1929
+ // plan-of-record CLI sync layout, the file lives at
1930
+ // `<sync-dir>/database-types/<type>.toml`. We don't need to know the
1931
+ // exact sync dir for the happy path — just look for an existing
1932
+ // file relative to the CWD's `.primitive/sync/` directory tree.
1933
+ const candidateFiles = [];
1934
+ if (options.syncDir) {
1935
+ candidateFiles.push(path.join(options.syncDir, "database-types", `${databaseType}.toml`));
1936
+ }
1937
+ else {
1938
+ // Search any env/appId subtree under .primitive/sync that matches.
1939
+ const root = path.join(process.cwd(), ".primitive", "sync");
1940
+ if (existsSync(root)) {
1941
+ for (const env of readdirSync(root)) {
1942
+ const envDir = path.join(root, env);
1943
+ try {
1944
+ for (const app of readdirSync(envDir)) {
1945
+ const candidate = path.join(envDir, app, "database-types", `${databaseType}.toml`);
1946
+ if (existsSync(candidate)) {
1947
+ candidateFiles.push(candidate);
1948
+ }
1949
+ }
1950
+ }
1951
+ catch {
1952
+ // skip non-dirs
1953
+ }
1954
+ }
1955
+ }
1956
+ }
1957
+ if (candidateFiles.length === 0) {
1958
+ // No local file found — print the scaffold to stdout and tell
1959
+ // the user where to put it.
1960
+ info(`No local database-types/${databaseType}.toml found under .primitive/sync/. Generated TOML:`);
1961
+ console.log("");
1962
+ console.log(scaffoldedToml);
1963
+ return;
1964
+ }
1965
+ // 3. For each candidate, splice the scaffolded TOML at a stable
1966
+ // anchor (before the first `[[operations]]` block, or at EOF). Per
1967
+ // the plan-of-record, textual insertion is deliberate — smol-toml
1968
+ // parse/stringify drops comments, so we splice as a raw string.
1969
+ for (const targetPath of candidateFiles) {
1970
+ const original = readFileSync(targetPath, "utf-8");
1971
+ // Detect existing [models.*] block. If present, refuse unless --force.
1972
+ const hasModelsBlock = /\n\[models\./.test("\n" + original);
1973
+ if (hasModelsBlock && !options.force) {
1974
+ error(`${targetPath} already has [models.*] blocks. Re-run with --force to overwrite.`);
1975
+ process.exit(1);
1976
+ }
1977
+ // Strip existing [models.*] blocks if --force.
1978
+ let cleaned = original;
1979
+ if (hasModelsBlock && options.force) {
1980
+ cleaned = stripModelsBlocks(original);
1981
+ }
1982
+ // Splice: insert before the first [[operations]] block, otherwise
1983
+ // at the end of file.
1984
+ let merged;
1985
+ const opsAnchor = cleaned.indexOf("\n[[operations]]");
1986
+ if (opsAnchor >= 0) {
1987
+ merged =
1988
+ cleaned.slice(0, opsAnchor + 1) +
1989
+ scaffoldedToml +
1990
+ "\n" +
1991
+ cleaned.slice(opsAnchor + 1);
1992
+ }
1993
+ else {
1994
+ const sep = cleaned.endsWith("\n") ? "" : "\n";
1995
+ merged = cleaned + sep + scaffoldedToml + "\n";
1996
+ }
1997
+ writeFileSync(targetPath, merged);
1998
+ success(`Inserted schema into ${targetPath}`);
1999
+ }
2000
+ info("Review the generated schema, fix types the generator guessed wrong, then run `primitive sync push` (or `primitive sync push --dry-run`).");
2001
+ }
2002
+ catch (err) {
2003
+ error(err.message);
2004
+ process.exit(1);
2005
+ }
2006
+ });
2007
+ // ============================================
2008
+ // Codegen command (issue #814)
2009
+ // ============================================
2010
+ databases
2011
+ .command("codegen")
2012
+ .description("Generate record + operation types from the local database-types/*.toml schema. TypeScript (default): a <type>.generated.ts per database type (record interfaces, per-op input-params interfaces, per-op result aliases, and a typed <type>Ops factory). Swift (--lang swift): a <type>.generated.swift per database type (record structs, per-op params structs, per-op result typealiases, and a typed <Type>Ops factory).\n\nFormatting: the emitted TypeScript is already formatted the way Prettier's DEFAULT config formats it, so a `codegen` -> `prettier --write` -> `codegen --check` pipeline stays green. If your project uses a NON-default Prettier config (a different printWidth, trailingComma, or quote style), Prettier will reformat the generated files and `--check` will then fail: add the generated directory to `.prettierignore` and commit the raw emission instead.")
2013
+ .argument("[database-type]", "Generate for a single database type (defaults to every database-types/*.toml found)")
2014
+ .option("--app <app-id>", "App ID")
2015
+ .option("--sync-dir <path>", "Override path to the sync directory (defaults to ./.primitive/sync/<env>/<appId>/)")
2016
+ .option("-o, --output <dir>", "Output directory for the generated files (defaults to <sync-dir>/database-types/generated/)")
2017
+ .option("--lang <lang>", "Target language for the generated types: 'ts' (default) or 'swift'.", "ts")
2018
+ .option("--check", "Exit non-zero if generated output is out of date (CI guard); does not write. Compares byte-for-byte, so the file on disk must match the emission exactly.")
2019
+ .option("--json", "Output the result summary as JSON")
2020
+ .action(async (databaseType, options) => {
2021
+ try {
2022
+ // 0. Validate --lang up front so an unknown value fails clearly rather
2023
+ // than silently defaulting to the TS emitter.
2024
+ const lang = String(options.lang ?? "ts").toLowerCase();
2025
+ if (lang !== "ts" && lang !== "swift") {
2026
+ error(`Unknown --lang "${options.lang}". Use "ts" or "swift".`);
2027
+ process.exit(1);
2028
+ }
2029
+ // 1. Resolve the single source database-types/ directory via the
2030
+ // shared active-environment resolver (issue #1510). Honors
2031
+ // --sync-dir / --app overrides and resolves the active env
2032
+ // (--env → PRIMITIVE_ENV → defaultEnvironment → single-env) instead
2033
+ // of silently merging types across every synced env.
2034
+ const dbTypesSourceDir = resolveCodegenSourceDir({
2035
+ subdir: "database-types",
2036
+ options: { app: options.app, syncDir: options.syncDir },
2037
+ });
2038
+ // 2. Collect the source .toml files (one per database type), filtered
2039
+ // to a single type when an argument is given.
2040
+ const inputs = [];
2041
+ for (const fileName of readdirSync(dbTypesSourceDir)) {
2042
+ if (!fileName.endsWith(".toml"))
2043
+ continue;
2044
+ const typeName = fileName.slice(0, -".toml".length);
2045
+ if (databaseType && typeName !== databaseType)
2046
+ continue;
2047
+ const tomlPath = path.join(dbTypesSourceDir, fileName);
2048
+ inputs.push({
2049
+ databaseType: typeName,
2050
+ tomlPath,
2051
+ tomlContent: readFileSync(tomlPath, "utf-8"),
2052
+ });
2053
+ }
2054
+ if (inputs.length === 0) {
2055
+ error(databaseType
2056
+ ? `No database-types/${databaseType}.toml found under .primitive/sync/.`
2057
+ : "No database-types/*.toml files found to generate from.");
2058
+ process.exit(1);
2059
+ }
2060
+ // 3. Resolve the output directory. Default: a `generated/` subdir of
2061
+ // the first source dir (keeps generated output beside the schema).
2062
+ const outputDir = options.output
2063
+ ? path.resolve(options.output)
2064
+ : path.join(path.dirname(inputs[0].tomlPath), "generated");
2065
+ // 4. Run codegen (or --check) with the selected emitter. Both the TS
2066
+ // and Swift generators return the same WriteOrCheckResult shape, so
2067
+ // the reporting below is emitter-agnostic; only the emitter (and the
2068
+ // regenerate hint) differs. When a single database-type filter
2069
+ // argument is given, the input set is partial — flag it so stale
2070
+ // cleanup is scoped to that type and sibling types' generated files
2071
+ // are left intact.
2072
+ const codegenResult = lang === "swift"
2073
+ ? await generateDbSwiftTypes({
2074
+ inputs,
2075
+ outputDir,
2076
+ check: !!options.check,
2077
+ singleType: !!databaseType,
2078
+ })
2079
+ : await generateDbTypes({
2080
+ inputs,
2081
+ outputDir,
2082
+ check: !!options.check,
2083
+ singleType: !!databaseType,
2084
+ });
2085
+ if (options.check) {
2086
+ if (codegenResult.mismatches.length > 0) {
2087
+ if (options.json) {
2088
+ json({ ok: false, mismatches: codegenResult.mismatches });
2089
+ }
2090
+ else {
2091
+ error(`Check failed: ${codegenResult.mismatches.length} file(s) out of date.`);
2092
+ for (const m of codegenResult.mismatches) {
2093
+ error(` ${m.reason}: ${path.relative(process.cwd(), m.filePath)}`);
2094
+ }
2095
+ info(lang === "swift"
2096
+ ? "Run `primitive databases codegen --lang swift` to regenerate."
2097
+ : "Run `primitive databases codegen` to regenerate.");
2098
+ }
2099
+ process.exit(1);
2100
+ }
2101
+ if (options.json) {
2102
+ json({ ok: true, checked: codegenResult.writtenFiles.length });
2103
+ }
2104
+ else {
2105
+ success(`Check passed: ${codegenResult.writtenFiles.length} file(s) up to date.`);
2106
+ }
2107
+ return;
2108
+ }
2109
+ if (options.json) {
2110
+ json({
2111
+ written: codegenResult.writtenFiles,
2112
+ deleted: codegenResult.deletedFiles,
2113
+ });
2114
+ return;
2115
+ }
2116
+ success(`Generated ${codegenResult.writtenFiles.length} file(s)` +
2117
+ (codegenResult.deletedFiles.length > 0
2118
+ ? `, deleted ${codegenResult.deletedFiles.length} stale file(s).`
2119
+ : "."));
2120
+ for (const f of codegenResult.writtenFiles) {
2121
+ keyValue(" wrote", path.relative(process.cwd(), f));
2122
+ }
2123
+ for (const f of codegenResult.deletedFiles) {
2124
+ keyValue(" deleted", path.relative(process.cwd(), f));
2125
+ }
2126
+ }
2127
+ catch (err) {
2128
+ error(err.message);
2129
+ process.exit(1);
2130
+ }
2131
+ });
2132
+ }
2133
+ /** Remove every existing `[models.*]` block from a TOML file body. */
2134
+ function stripModelsBlocks(text) {
2135
+ const lines = text.split("\n");
2136
+ const result = [];
2137
+ let skipping = false;
2138
+ for (const line of lines) {
2139
+ const isModelsHeader = /^\s*\[models\b/.test(line);
2140
+ const isOtherHeader = /^\s*\[(?!models\b)/.test(line);
2141
+ if (isModelsHeader) {
2142
+ skipping = true;
2143
+ continue;
2144
+ }
2145
+ if (skipping && isOtherHeader) {
2146
+ skipping = false;
2147
+ }
2148
+ if (!skipping)
2149
+ result.push(line);
2150
+ }
2151
+ return result.join("\n");
2152
+ }
2153
+ // ============================================
2154
+ // Database export/import helpers
2155
+ // ============================================
2156
+ async function exportSingleDatabase(client, appId, databaseId, outputDir, jsonOutput) {
2157
+ const dbDir = path.join(outputDir, "databases", databaseId);
2158
+ mkdirSync(dbDir, { recursive: true });
2159
+ // 1. Fetch database metadata
2160
+ const dbMeta = await client.getDatabase(appId, databaseId);
2161
+ // Warn about databaseType sync
2162
+ if (dbMeta.databaseType) {
2163
+ warn(`This database uses type "${dbMeta.databaseType}". Make sure to \`primitive sync push\` the type config before importing into a new app.`);
2164
+ }
2165
+ // 2. Write metadata
2166
+ const metadata = {
2167
+ databaseId: dbMeta.databaseId || databaseId,
2168
+ title: dbMeta.title,
2169
+ databaseType: dbMeta.databaseType || null,
2170
+ metadata: dbMeta.metadata || null,
2171
+ };
2172
+ writeFileSync(path.join(dbDir, "metadata.json"), JSON.stringify(metadata, null, 2));
2173
+ // 3. Export records: list models, then query each.
2174
+ // listDatabaseModels() resolves to `{ models: string[] }`, not a bare array,
2175
+ // so unwrap it before iterating (mirrors the `databases records models`
2176
+ // consumer above). Without this, `for (const modelName of models)` throws
2177
+ // "models is not iterable" and records.jsonl is left empty (#1396).
2178
+ const models = (await client.listDatabaseModels(appId, databaseId)).models || [];
2179
+ let totalRecords = 0;
2180
+ const recordsFile = path.join(dbDir, "records.jsonl");
2181
+ // Clear file
2182
+ writeFileSync(recordsFile, "");
2183
+ for (const modelName of models) {
2184
+ let cursor;
2185
+ let hasMore = true;
2186
+ while (hasMore) {
2187
+ const result = await client.queryDatabaseRecords(appId, databaseId, modelName, {
2188
+ limit: 100,
2189
+ cursor,
2190
+ });
2191
+ const records = result.items;
2192
+ for (const record of records) {
2193
+ const line = JSON.stringify({ _type: modelName, _id: record.id, _data: record });
2194
+ appendFileSync(recordsFile, line + "\n");
2195
+ totalRecords++;
2196
+ }
2197
+ cursor = result.nextCursor;
2198
+ hasMore = !!cursor && records.length > 0;
2199
+ }
2200
+ }
2201
+ // 4. Export indexes
2202
+ const indexes = await client.listDatabaseIndexes(appId, databaseId);
2203
+ writeFileSync(path.join(dbDir, "indexes.json"), JSON.stringify(indexes, null, 2));
2204
+ // 5. Export unique constraints
2205
+ const constraints = await client.listDatabaseUniqueConstraints(appId, databaseId);
2206
+ writeFileSync(path.join(dbDir, "constraints.json"), JSON.stringify(constraints, null, 2));
2207
+ if (jsonOutput) {
2208
+ json({
2209
+ databaseId,
2210
+ title: metadata.title,
2211
+ databaseType: metadata.databaseType,
2212
+ models: models.length,
2213
+ records: totalRecords,
2214
+ indexes: indexes.length,
2215
+ constraints: constraints.length,
2216
+ exportPath: dbDir,
2217
+ });
2218
+ }
2219
+ else {
2220
+ success(`Exported database ${databaseId} (${metadata.title || "untitled"}) to ${dbDir}`);
2221
+ keyValue(" Models", String(models.length));
2222
+ keyValue(" Records", String(totalRecords));
2223
+ keyValue(" Indexes", String(indexes.length));
2224
+ }
2225
+ }
2226
+ /**
2227
+ * Conservative client-side ceiling for `databases import --batch-size`.
2228
+ * `records/batch` has no fixed server-side item cap (unlike the
2229
+ * registered-batch path used by `import-csv`), so this bounds each request to
2230
+ * keep it within Cloudflare body-size and Durable Object memory limits.
2231
+ */
2232
+ const IMPORT_BATCH_SIZE_CEILING = 25000;
2233
+ async function importSingleDatabase(client, appId, dbDir, options) {
2234
+ const { overwrite, dryRun, batchSize, stopOnError, json: jsonOutput, summary } = options;
2235
+ const metadataPath = path.join(dbDir, "metadata.json");
2236
+ if (!existsSync(metadataPath)) {
2237
+ warn(`Skipping ${dbDir}: no metadata.json found`);
2238
+ summary.skipped++;
2239
+ return;
2240
+ }
2241
+ const metadata = JSON.parse(readFileSync(metadataPath, "utf-8"));
2242
+ const databaseId = metadata.databaseId;
2243
+ if (dryRun) {
2244
+ // Report record/batch counts without writing anything (no DB creation,
2245
+ // no index registration, no batch write).
2246
+ const recordCount = countRecordLines(dbDir);
2247
+ const batchCount = chunk(new Array(recordCount), batchSize).length;
2248
+ summary.created++;
2249
+ summary.recordsImported += recordCount;
2250
+ summary.batches += batchCount;
2251
+ info(`[dry-run] Would import database ${databaseId} (${metadata.title || "untitled"}) — ${recordCount} record(s), ${batchCount} batch(es)`);
2252
+ return;
2253
+ }
2254
+ // Check if database type exists — warn if not
2255
+ if (metadata.databaseType) {
2256
+ warn(`Database uses type "${metadata.databaseType}". Ensure the type config exists in the target app (use \`primitive sync push\`).`);
2257
+ }
2258
+ // Check if database exists — use the original ID for overwrite scenarios
2259
+ let targetDatabaseId = databaseId;
2260
+ let exists = false;
2261
+ try {
2262
+ await client.getDatabase(appId, databaseId);
2263
+ exists = true;
2264
+ }
2265
+ catch {
2266
+ exists = false;
2267
+ }
2268
+ if (exists && !overwrite) {
2269
+ warn(`Skipping ${databaseId}: already exists (use --overwrite to replace)`);
2270
+ summary.skipped++;
2271
+ return;
2272
+ }
2273
+ // Create database if it doesn't exist
2274
+ // Note: server auto-generates the ID, so we capture it for subsequent operations
2275
+ if (!exists) {
2276
+ const createData = {
2277
+ title: metadata.title || "Imported Database",
2278
+ };
2279
+ if (metadata.databaseType) {
2280
+ createData.databaseType = metadata.databaseType;
2281
+ }
2282
+ if (metadata.metadata) {
2283
+ createData.metadata = metadata.metadata;
2284
+ }
2285
+ const created = await client.createDatabase(appId, createData);
2286
+ targetDatabaseId = created.databaseId || created.id || databaseId;
2287
+ summary.created++;
2288
+ }
2289
+ else {
2290
+ summary.updated++;
2291
+ }
2292
+ // Register indexes
2293
+ const indexesPath = path.join(dbDir, "indexes.json");
2294
+ if (existsSync(indexesPath)) {
2295
+ const indexes = JSON.parse(readFileSync(indexesPath, "utf-8"));
2296
+ for (const idx of indexes) {
2297
+ try {
2298
+ await client.registerDatabaseIndex(appId, targetDatabaseId, {
2299
+ modelName: idx.modelName || idx.model_name,
2300
+ fieldName: idx.fieldName || idx.field_name,
2301
+ fieldType: idx.fieldType || idx.field_type || "string",
2302
+ unique: idx.isUnique || idx.is_unique || false,
2303
+ });
2304
+ summary.indexesRegistered++;
2305
+ }
2306
+ catch {
2307
+ // Index may already exist
2308
+ }
2309
+ }
2310
+ }
2311
+ // Register unique constraints
2312
+ const constraintsPath = path.join(dbDir, "constraints.json");
2313
+ if (existsSync(constraintsPath)) {
2314
+ const constraints = JSON.parse(readFileSync(constraintsPath, "utf-8"));
2315
+ for (const c of constraints) {
2316
+ try {
2317
+ await client.registerDatabaseUniqueConstraint(appId, targetDatabaseId, {
2318
+ modelName: c.modelName || c.model_name,
2319
+ constraintName: c.constraintName || c.constraint_name,
2320
+ fields: c.fields ? (typeof c.fields === "string" ? JSON.parse(c.fields) : c.fields) : [],
2321
+ });
2322
+ }
2323
+ catch {
2324
+ // Constraint may already exist
2325
+ }
2326
+ }
2327
+ }
2328
+ // Import records via chunked batch writes (was one save per record).
2329
+ const recordsPath = path.join(dbDir, "records.jsonl");
2330
+ if (existsSync(recordsPath)) {
2331
+ const lines = readFileSync(recordsPath, "utf-8").split("\n").filter(Boolean);
2332
+ // Map each records.jsonl line to a batch save op. Preserve the explicit
2333
+ // `_type`/`_id`; strip the redundant id/type keys out of `_data` (the
2334
+ // per-record loop did the same) so they don't duplicate into stored data.
2335
+ const ops = lines.map((line) => {
2336
+ const record = JSON.parse(line);
2337
+ const { _type, _id, _data } = record;
2338
+ const { id: _ignoredId, type: _ignoredType, ...data } = _data;
2339
+ return { op: "save", modelName: _type, id: _id, data };
2340
+ });
2341
+ const chunks = chunk(ops, batchSize);
2342
+ summary.batches += chunks.length;
2343
+ for (let i = 0; i < chunks.length; i++) {
2344
+ const piece = chunks[i];
2345
+ let chunkFailed = false;
2346
+ try {
2347
+ const res = await client.batchDatabaseRecords(appId, targetDatabaseId, piece);
2348
+ const results = res?.results ?? [];
2349
+ let imported = 0;
2350
+ let failed = 0;
2351
+ const firstErrors = [];
2352
+ for (let j = 0; j < piece.length; j++) {
2353
+ const r = results[j];
2354
+ if (r && r.success) {
2355
+ imported++;
2356
+ }
2357
+ else {
2358
+ failed++;
2359
+ if (r?.error && firstErrors.length < 3)
2360
+ firstErrors.push(r.error);
2361
+ }
2362
+ }
2363
+ summary.recordsImported += imported;
2364
+ summary.recordsFailed += failed;
2365
+ if (failed > 0) {
2366
+ chunkFailed = true;
2367
+ summary.batchErrors.push({
2368
+ database: databaseId,
2369
+ batch: i,
2370
+ error: `${failed} record(s) failed${firstErrors.length ? `: ${firstErrors.join("; ")}` : ""}`,
2371
+ });
2372
+ }
2373
+ if (!jsonOutput) {
2374
+ info(` ${databaseId} batch ${i + 1}/${chunks.length}: imported ${imported}, failed ${failed}`);
2375
+ }
2376
+ }
2377
+ catch (err) {
2378
+ // Chunk-level failure (e.g. a 400 for a malformed op): the whole chunk
2379
+ // is rejected, so every item in it counts as failed.
2380
+ const msg = err?.message || String(err);
2381
+ chunkFailed = true;
2382
+ summary.recordsFailed += piece.length;
2383
+ summary.batchErrors.push({ database: databaseId, batch: i, error: msg });
2384
+ if (!jsonOutput) {
2385
+ warn(` ${databaseId} batch ${i + 1}/${chunks.length} failed: ${msg}`);
2386
+ }
2387
+ }
2388
+ if (chunkFailed && stopOnError) {
2389
+ summary.aborted = true;
2390
+ return;
2391
+ }
2392
+ }
2393
+ }
2394
+ info(`Imported database ${databaseId} (${metadata.title || "untitled"})`);
2395
+ }
2396
+ /** Count non-empty lines in a database export's records.jsonl (0 if absent). */
2397
+ function countRecordLines(dbDir) {
2398
+ const recordsPath = path.join(dbDir, "records.jsonl");
2399
+ if (!existsSync(recordsPath))
2400
+ return 0;
2401
+ return readFileSync(recordsPath, "utf-8").split("\n").filter(Boolean).length;
345
2402
  }
346
2403
  //# sourceMappingURL=databases.js.map