primitive-admin 1.1.0-alpha.9 → 1.2.0-alpha.0

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