primitive-admin 1.2.0-alpha.9 → 1.3.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 (546) hide show
  1. package/README.md +258 -186
  2. package/assets/skill/skills/primitive-platform/SKILL.md +93 -27
  3. package/dist/bin/primitive.js +15 -89
  4. package/dist/bin/primitive.js.map +1 -1
  5. package/dist/src/commands/admins.js +80 -17
  6. package/dist/src/commands/admins.js.map +1 -1
  7. package/dist/src/commands/agent-sessions.d.ts +129 -0
  8. package/dist/src/commands/agent-sessions.js +532 -20
  9. package/dist/src/commands/agent-sessions.js.map +1 -1
  10. package/dist/src/commands/analytics.js +207 -155
  11. package/dist/src/commands/analytics.js.map +1 -1
  12. package/dist/src/commands/apps-children.js +3 -0
  13. package/dist/src/commands/apps-children.js.map +1 -1
  14. package/dist/src/commands/apps-transitions.d.ts +39 -0
  15. package/dist/src/commands/apps-transitions.js +198 -0
  16. package/dist/src/commands/apps-transitions.js.map +1 -0
  17. package/dist/src/commands/apps.d.ts +17 -0
  18. package/dist/src/commands/apps.js +108 -3
  19. package/dist/src/commands/apps.js.map +1 -1
  20. package/dist/src/commands/auth-sessions.js +2 -0
  21. package/dist/src/commands/auth-sessions.js.map +1 -1
  22. package/dist/src/commands/auth.js +138 -44
  23. package/dist/src/commands/auth.js.map +1 -1
  24. package/dist/src/commands/blob-buckets.js +2 -0
  25. package/dist/src/commands/blob-buckets.js.map +1 -1
  26. package/dist/src/commands/collections.js +318 -256
  27. package/dist/src/commands/collections.js.map +1 -1
  28. package/dist/src/commands/comparisons.js +2 -0
  29. package/dist/src/commands/comparisons.js.map +1 -1
  30. package/dist/src/commands/config.d.ts +2 -2
  31. package/dist/src/commands/config.js +59 -33
  32. package/dist/src/commands/config.js.map +1 -1
  33. package/dist/src/commands/connections.js +2 -0
  34. package/dist/src/commands/connections.js.map +1 -1
  35. package/dist/src/commands/database-type-configs.js +5 -3
  36. package/dist/src/commands/database-type-configs.js.map +1 -1
  37. package/dist/src/commands/databases.js +6 -4
  38. package/dist/src/commands/databases.js.map +1 -1
  39. package/dist/src/commands/db3-types.d.ts +15 -0
  40. package/dist/src/commands/db3-types.js +159 -0
  41. package/dist/src/commands/db3-types.js.map +1 -0
  42. package/dist/src/commands/db3.d.ts +24 -0
  43. package/dist/src/commands/db3.js +1444 -0
  44. package/dist/src/commands/db3.js.map +1 -0
  45. package/dist/src/commands/documents.d.ts +110 -10
  46. package/dist/src/commands/documents.js +1012 -748
  47. package/dist/src/commands/documents.js.map +1 -1
  48. package/dist/src/commands/email-templates.js +74 -0
  49. package/dist/src/commands/email-templates.js.map +1 -1
  50. package/dist/src/commands/env.js +8 -4
  51. package/dist/src/commands/env.js.map +1 -1
  52. package/dist/src/commands/function-trigger-commands.d.ts +28 -0
  53. package/dist/src/commands/function-trigger-commands.js +341 -0
  54. package/dist/src/commands/function-trigger-commands.js.map +1 -0
  55. package/dist/src/commands/functions.js +376 -30
  56. package/dist/src/commands/functions.js.map +1 -1
  57. package/dist/src/commands/groups.js +168 -50
  58. package/dist/src/commands/groups.js.map +1 -1
  59. package/dist/src/commands/guides.js +7 -5
  60. package/dist/src/commands/guides.js.map +1 -1
  61. package/dist/src/commands/hosting.d.ts +8 -0
  62. package/dist/src/commands/hosting.js +346 -0
  63. package/dist/src/commands/hosting.js.map +1 -0
  64. package/dist/src/commands/init.js +129 -38
  65. package/dist/src/commands/init.js.map +1 -1
  66. package/dist/src/commands/integrations.js +82 -53
  67. package/dist/src/commands/integrations.js.map +1 -1
  68. package/dist/src/commands/locks.d.ts +5 -3
  69. package/dist/src/commands/locks.js +19 -61
  70. package/dist/src/commands/locks.js.map +1 -1
  71. package/dist/src/commands/metadata-category-configs.d.ts +2 -2
  72. package/dist/src/commands/metadata-category-configs.js +4 -2
  73. package/dist/src/commands/metadata-category-configs.js.map +1 -1
  74. package/dist/src/commands/metadata.js +41 -0
  75. package/dist/src/commands/metadata.js.map +1 -1
  76. package/dist/src/commands/prompts.js +75 -52
  77. package/dist/src/commands/prompts.js.map +1 -1
  78. package/dist/src/commands/rate-counters.d.ts +19 -0
  79. package/dist/src/commands/rate-counters.js +104 -0
  80. package/dist/src/commands/rate-counters.js.map +1 -0
  81. package/dist/src/commands/rule-sets.d.ts +1 -1
  82. package/dist/src/commands/rule-sets.js +2 -1
  83. package/dist/src/commands/rule-sets.js.map +1 -1
  84. package/dist/src/commands/schemas.d.ts +15 -0
  85. package/dist/src/commands/schemas.js +122 -0
  86. package/dist/src/commands/schemas.js.map +1 -0
  87. package/dist/src/commands/scripts.d.ts +9 -17
  88. package/dist/src/commands/scripts.js +24 -479
  89. package/dist/src/commands/scripts.js.map +1 -1
  90. package/dist/src/commands/secrets.js +47 -3
  91. package/dist/src/commands/secrets.js.map +1 -1
  92. package/dist/src/commands/sessions.js +2 -0
  93. package/dist/src/commands/sessions.js.map +1 -1
  94. package/dist/src/commands/skill.js +2 -0
  95. package/dist/src/commands/skill.js.map +1 -1
  96. package/dist/src/commands/sync-schemas.d.ts +202 -0
  97. package/dist/src/commands/sync-schemas.js +629 -0
  98. package/dist/src/commands/sync-schemas.js.map +1 -0
  99. package/dist/src/commands/sync-user-properties.d.ts +118 -0
  100. package/dist/src/commands/sync-user-properties.js +276 -0
  101. package/dist/src/commands/sync-user-properties.js.map +1 -0
  102. package/dist/src/commands/sync.d.ts +518 -546
  103. package/dist/src/commands/sync.js +3010 -4877
  104. package/dist/src/commands/sync.js.map +1 -1
  105. package/dist/src/commands/tokens.js +5 -3
  106. package/dist/src/commands/tokens.js.map +1 -1
  107. package/dist/src/commands/transitions.d.ts +54 -0
  108. package/dist/src/commands/transitions.js +418 -0
  109. package/dist/src/commands/transitions.js.map +1 -0
  110. package/dist/src/commands/usage.d.ts +18 -0
  111. package/dist/src/commands/usage.js +343 -0
  112. package/dist/src/commands/usage.js.map +1 -0
  113. package/dist/src/commands/user-properties.d.ts +14 -0
  114. package/dist/src/commands/user-properties.js +79 -0
  115. package/dist/src/commands/user-properties.js.map +1 -0
  116. package/dist/src/commands/users.js +911 -18
  117. package/dist/src/commands/users.js.map +1 -1
  118. package/dist/src/commands/vars.js +2 -0
  119. package/dist/src/commands/vars.js.map +1 -1
  120. package/dist/src/commands/waitlist.js +39 -4
  121. package/dist/src/commands/waitlist.js.map +1 -1
  122. package/dist/src/commands/workflows.d.ts +5 -83
  123. package/dist/src/commands/workflows.js +57 -2282
  124. package/dist/src/commands/workflows.js.map +1 -1
  125. package/dist/src/lib/analytics-query.d.ts +58 -0
  126. package/dist/src/lib/analytics-query.js +134 -0
  127. package/dist/src/lib/analytics-query.js.map +1 -0
  128. package/dist/src/lib/api-client.d.ts +1818 -438
  129. package/dist/src/lib/api-client.js +965 -544
  130. package/dist/src/lib/api-client.js.map +1 -1
  131. package/dist/src/lib/app-settings-descriptor.d.ts +1 -1
  132. package/dist/src/lib/app-settings-descriptor.js +6 -0
  133. package/dist/src/lib/app-settings-descriptor.js.map +1 -1
  134. package/dist/src/lib/auth-fixtures.d.ts +44 -0
  135. package/dist/src/lib/auth-fixtures.js +61 -0
  136. package/dist/src/lib/auth-fixtures.js.map +1 -0
  137. package/dist/src/lib/auth-flow.d.ts +34 -1
  138. package/dist/src/lib/auth-flow.js +429 -13
  139. package/dist/src/lib/auth-flow.js.map +1 -1
  140. package/dist/src/lib/block-layout.d.ts +12 -23
  141. package/dist/src/lib/block-layout.js +26 -92
  142. package/dist/src/lib/block-layout.js.map +1 -1
  143. package/dist/src/lib/block-selector.d.ts +8 -14
  144. package/dist/src/lib/block-selector.js +8 -19
  145. package/dist/src/lib/block-selector.js.map +1 -1
  146. package/dist/src/lib/child-apps-local.d.ts +3 -1
  147. package/dist/src/lib/child-apps-local.js +9 -1
  148. package/dist/src/lib/child-apps-local.js.map +1 -1
  149. package/dist/src/lib/cli-manifest.d.ts +9 -0
  150. package/dist/src/lib/cli-manifest.js +10 -1
  151. package/dist/src/lib/cli-manifest.js.map +1 -1
  152. package/dist/src/lib/cli-version.d.ts +14 -0
  153. package/dist/src/lib/cli-version.js +38 -0
  154. package/dist/src/lib/cli-version.js.map +1 -0
  155. package/dist/src/lib/codegen-shared/prettierStable.d.ts +41 -0
  156. package/dist/src/lib/codegen-shared/prettierStable.js +146 -24
  157. package/dist/src/lib/codegen-shared/prettierStable.js.map +1 -1
  158. package/dist/src/lib/collection-export.d.ts +76 -15
  159. package/dist/src/lib/collection-export.js +116 -23
  160. package/dist/src/lib/collection-export.js.map +1 -1
  161. package/dist/src/lib/collection-principal.d.ts +22 -0
  162. package/dist/src/lib/collection-principal.js +35 -0
  163. package/dist/src/lib/collection-principal.js.map +1 -0
  164. package/dist/src/lib/command-groups.d.ts +30 -0
  165. package/dist/src/lib/command-groups.js +109 -0
  166. package/dist/src/lib/command-groups.js.map +1 -0
  167. package/dist/src/lib/command-status.d.ts +147 -0
  168. package/dist/src/lib/command-status.js +266 -0
  169. package/dist/src/lib/command-status.js.map +1 -0
  170. package/dist/src/lib/config-object-descriptor.d.ts +9 -22
  171. package/dist/src/lib/config-object-descriptor.js +107 -276
  172. package/dist/src/lib/config-object-descriptor.js.map +1 -1
  173. package/dist/src/lib/config-surface.d.ts +3 -7
  174. package/dist/src/lib/config-surface.js +9 -13
  175. package/dist/src/lib/config-surface.js.map +1 -1
  176. package/dist/src/lib/config-toml.d.ts +11 -2
  177. package/dist/src/lib/config-toml.js +25 -2
  178. package/dist/src/lib/config-toml.js.map +1 -1
  179. package/dist/src/lib/credentials-home.d.ts +7 -0
  180. package/dist/src/lib/credentials-home.js +45 -10
  181. package/dist/src/lib/credentials-home.js.map +1 -1
  182. package/dist/src/lib/credentials-lock.d.ts +14 -6
  183. package/dist/src/lib/credentials-lock.js +90 -10
  184. package/dist/src/lib/credentials-lock.js.map +1 -1
  185. package/dist/src/lib/credentials-store.d.ts +123 -70
  186. package/dist/src/lib/credentials-store.js +358 -113
  187. package/dist/src/lib/credentials-store.js.map +1 -1
  188. package/dist/src/lib/custodian.d.ts +8 -0
  189. package/dist/src/lib/custodian.js +18 -0
  190. package/dist/src/lib/custodian.js.map +1 -0
  191. package/dist/src/lib/data-input.d.ts +1 -1
  192. package/dist/src/lib/data-input.js +1 -1
  193. package/dist/src/lib/db-codegen/dbTsTypes.d.ts +1 -1
  194. package/dist/src/lib/db-codegen/dbTsTypes.js +3 -0
  195. package/dist/src/lib/db-codegen/dbTsTypes.js.map +1 -1
  196. package/dist/src/lib/db-codegen/dbTypeIR.d.ts +38 -1
  197. package/dist/src/lib/db-codegen/dbTypeIR.js +29 -7
  198. package/dist/src/lib/db-codegen/dbTypeIR.js.map +1 -1
  199. package/dist/src/lib/db-type-records.d.ts +106 -0
  200. package/dist/src/lib/db-type-records.js +224 -0
  201. package/dist/src/lib/db-type-records.js.map +1 -0
  202. package/dist/src/lib/db3-export.d.ts +287 -0
  203. package/dist/src/lib/db3-export.js +647 -0
  204. package/dist/src/lib/db3-export.js.map +1 -0
  205. package/dist/src/lib/db3-index-output.d.ts +116 -0
  206. package/dist/src/lib/db3-index-output.js +223 -0
  207. package/dist/src/lib/db3-index-output.js.map +1 -0
  208. package/dist/src/lib/db3-type-models.d.ts +134 -0
  209. package/dist/src/lib/db3-type-models.js +452 -0
  210. package/dist/src/lib/db3-type-models.js.map +1 -0
  211. package/dist/src/lib/deprecation.d.ts +2 -2
  212. package/dist/src/lib/deprecation.js +2 -2
  213. package/dist/src/lib/document-ingest-artifact.d.ts +13 -0
  214. package/dist/src/lib/document-ingest-artifact.js +36 -6
  215. package/dist/src/lib/document-ingest-artifact.js.map +1 -1
  216. package/dist/src/lib/document-ingest-format2.d.ts +36 -0
  217. package/dist/src/lib/document-ingest-format2.js +78 -0
  218. package/dist/src/lib/document-ingest-format2.js.map +1 -0
  219. package/dist/src/lib/document-ingest-input.d.ts +9 -0
  220. package/dist/src/lib/document-ingest-input.js +28 -1
  221. package/dist/src/lib/document-ingest-input.js.map +1 -1
  222. package/dist/src/lib/document-ingest.d.ts +11 -1
  223. package/dist/src/lib/document-ingest.js +16 -0
  224. package/dist/src/lib/document-ingest.js.map +1 -1
  225. package/dist/src/lib/document-schema-rows.d.ts +42 -0
  226. package/dist/src/lib/document-schema-rows.js +53 -0
  227. package/dist/src/lib/document-schema-rows.js.map +1 -0
  228. package/dist/src/lib/experimental-apis.d.ts +36 -0
  229. package/dist/src/lib/experimental-apis.js +46 -0
  230. package/dist/src/lib/experimental-apis.js.map +1 -0
  231. package/dist/src/lib/file-attachment.d.ts +24 -0
  232. package/dist/src/lib/file-attachment.js +31 -0
  233. package/dist/src/lib/file-attachment.js.map +1 -0
  234. package/dist/src/lib/function-authorize-check.d.ts +142 -0
  235. package/dist/src/lib/function-authorize-check.js +311 -0
  236. package/dist/src/lib/function-authorize-check.js.map +1 -0
  237. package/dist/src/lib/function-authorize-view.d.ts +27 -0
  238. package/dist/src/lib/function-authorize-view.js +88 -0
  239. package/dist/src/lib/function-authorize-view.js.map +1 -0
  240. package/dist/src/lib/function-bundle.d.ts +27 -5
  241. package/dist/src/lib/function-bundle.js +142 -7
  242. package/dist/src/lib/function-bundle.js.map +1 -1
  243. package/dist/src/lib/function-collect.d.ts +90 -12
  244. package/dist/src/lib/function-collect.js +482 -12
  245. package/dist/src/lib/function-collect.js.map +1 -1
  246. package/dist/src/lib/function-db-types.d.ts +65 -11
  247. package/dist/src/lib/function-db-types.js +297 -157
  248. package/dist/src/lib/function-db-types.js.map +1 -1
  249. package/dist/src/lib/function-document-types.d.ts +19 -7
  250. package/dist/src/lib/function-document-types.js +24 -12
  251. package/dist/src/lib/function-document-types.js.map +1 -1
  252. package/dist/src/lib/function-lint.d.ts +57 -0
  253. package/dist/src/lib/function-lint.js +234 -0
  254. package/dist/src/lib/function-lint.js.map +1 -0
  255. package/dist/src/lib/function-log-row.js +21 -2
  256. package/dist/src/lib/function-log-row.js.map +1 -1
  257. package/dist/src/lib/function-run.d.ts +13 -21
  258. package/dist/src/lib/function-run.js +14 -27
  259. package/dist/src/lib/function-run.js.map +1 -1
  260. package/dist/src/lib/function-schema-codegen.d.ts +86 -22
  261. package/dist/src/lib/function-schema-codegen.js +194 -88
  262. package/dist/src/lib/function-schema-codegen.js.map +1 -1
  263. package/dist/src/lib/function-schema-refs.d.ts +98 -0
  264. package/dist/src/lib/function-schema-refs.js +177 -0
  265. package/dist/src/lib/function-schema-refs.js.map +1 -0
  266. package/dist/src/lib/function-sync.d.ts +109 -6
  267. package/dist/src/lib/function-sync.js +179 -26
  268. package/dist/src/lib/function-sync.js.map +1 -1
  269. package/dist/src/lib/function-trigger-listing.d.ts +11 -6
  270. package/dist/src/lib/function-trigger-listing.js +32 -11
  271. package/dist/src/lib/function-trigger-listing.js.map +1 -1
  272. package/dist/src/lib/function-typecheck.d.ts +52 -0
  273. package/dist/src/lib/function-typecheck.js +174 -54
  274. package/dist/src/lib/function-typecheck.js.map +1 -1
  275. package/dist/src/lib/function-versions.d.ts +2 -0
  276. package/dist/src/lib/function-versions.js +1 -0
  277. package/dist/src/lib/function-versions.js.map +1 -1
  278. package/dist/src/lib/generated-build-flags.d.ts +13 -0
  279. package/dist/src/lib/generated-build-flags.js +14 -0
  280. package/dist/src/lib/generated-build-flags.js.map +1 -0
  281. package/dist/src/lib/generated-command-status.d.ts +6 -0
  282. package/dist/src/lib/generated-command-status.js +469 -0
  283. package/dist/src/lib/generated-command-status.js.map +1 -0
  284. package/dist/src/lib/generated-config-surfaces.d.ts +538 -141
  285. package/dist/src/lib/generated-config-surfaces.js +1772 -1854
  286. package/dist/src/lib/generated-config-surfaces.js.map +1 -1
  287. package/dist/src/lib/generated-sdk-types.d.ts +1 -1
  288. package/dist/src/lib/generated-sdk-types.js +1 -1
  289. package/dist/src/lib/generated-sdk-types.js.map +1 -1
  290. package/dist/src/lib/hosting-build.d.ts +97 -0
  291. package/dist/src/lib/hosting-build.js +204 -0
  292. package/dist/src/lib/hosting-build.js.map +1 -0
  293. package/dist/src/lib/hosting-client.d.ts +167 -0
  294. package/dist/src/lib/hosting-client.js +340 -0
  295. package/dist/src/lib/hosting-client.js.map +1 -0
  296. package/dist/src/lib/hosting-environments.d.ts +32 -0
  297. package/dist/src/lib/hosting-environments.js +74 -0
  298. package/dist/src/lib/hosting-environments.js.map +1 -0
  299. package/dist/src/lib/hosting-errors.d.ts +30 -0
  300. package/dist/src/lib/hosting-errors.js +43 -0
  301. package/dist/src/lib/hosting-errors.js.map +1 -0
  302. package/dist/src/lib/hosting-token.d.ts +46 -0
  303. package/dist/src/lib/hosting-token.js +60 -0
  304. package/dist/src/lib/hosting-token.js.map +1 -0
  305. package/dist/src/lib/hosting-wait.d.ts +42 -0
  306. package/dist/src/lib/hosting-wait.js +84 -0
  307. package/dist/src/lib/hosting-wait.js.map +1 -0
  308. package/dist/src/lib/hosting-wfp-upload.d.ts +86 -0
  309. package/dist/src/lib/hosting-wfp-upload.js +149 -0
  310. package/dist/src/lib/hosting-wfp-upload.js.map +1 -0
  311. package/dist/src/lib/init-assets.d.ts +2 -6
  312. package/dist/src/lib/init-assets.js +11 -27
  313. package/dist/src/lib/init-assets.js.map +1 -1
  314. package/dist/src/lib/init-ios-links.d.ts +11 -7
  315. package/dist/src/lib/init-ios-links.js +28 -22
  316. package/dist/src/lib/init-ios-links.js.map +1 -1
  317. package/dist/src/lib/init-login-note.d.ts +13 -0
  318. package/dist/src/lib/init-login-note.js +22 -0
  319. package/dist/src/lib/init-login-note.js.map +1 -0
  320. package/dist/src/lib/init-schema.d.ts +15 -0
  321. package/dist/src/lib/init-schema.js +54 -0
  322. package/dist/src/lib/init-schema.js.map +1 -1
  323. package/dist/src/lib/integration-test-request.d.ts +54 -0
  324. package/dist/src/lib/integration-test-request.js +207 -0
  325. package/dist/src/lib/integration-test-request.js.map +1 -0
  326. package/dist/src/lib/invoker-shared-enums.d.ts +35 -0
  327. package/dist/src/lib/invoker-shared-enums.js +98 -0
  328. package/dist/src/lib/invoker-shared-enums.js.map +1 -0
  329. package/dist/src/lib/json-value.d.ts +6 -0
  330. package/dist/src/lib/json-value.js +13 -0
  331. package/dist/src/lib/json-value.js.map +1 -0
  332. package/dist/src/lib/load-routes.d.ts +33 -0
  333. package/dist/src/lib/load-routes.js +35 -0
  334. package/dist/src/lib/load-routes.js.map +1 -0
  335. package/dist/src/lib/log-inspection.d.ts +23 -4
  336. package/dist/src/lib/log-inspection.js +14 -5
  337. package/dist/src/lib/log-inspection.js.map +1 -1
  338. package/dist/src/lib/login-exchange-check.d.ts +18 -0
  339. package/dist/src/lib/login-exchange-check.js +27 -0
  340. package/dist/src/lib/login-exchange-check.js.map +1 -0
  341. package/dist/src/lib/login-scope-lines.d.ts +17 -7
  342. package/dist/src/lib/login-scope-lines.js +33 -10
  343. package/dist/src/lib/login-scope-lines.js.map +1 -1
  344. package/dist/src/lib/metadata-report.d.ts +85 -0
  345. package/dist/src/lib/metadata-report.js +81 -0
  346. package/dist/src/lib/metadata-report.js.map +1 -0
  347. package/dist/src/lib/object-status-filter.d.ts +9 -1
  348. package/dist/src/lib/object-status-filter.js +9 -1
  349. package/dist/src/lib/object-status-filter.js.map +1 -1
  350. package/dist/src/lib/output.d.ts +1 -1
  351. package/dist/src/lib/output.js +3 -1
  352. package/dist/src/lib/output.js.map +1 -1
  353. package/dist/src/lib/pin-refusal-hint.d.ts +12 -0
  354. package/dist/src/lib/pin-refusal-hint.js +35 -0
  355. package/dist/src/lib/pin-refusal-hint.js.map +1 -0
  356. package/dist/src/lib/platform-owned.js +5 -0
  357. package/dist/src/lib/platform-owned.js.map +1 -1
  358. package/dist/src/lib/primitive-declaration-names.d.ts +21 -0
  359. package/dist/src/lib/primitive-declaration-names.js +22 -0
  360. package/dist/src/lib/primitive-declaration-names.js.map +1 -0
  361. package/dist/src/lib/primitive-declaration.d.ts +174 -0
  362. package/dist/src/lib/primitive-declaration.js +792 -0
  363. package/dist/src/lib/primitive-declaration.js.map +1 -0
  364. package/dist/src/lib/primitive-env-plugin.d.ts +99 -0
  365. package/dist/src/lib/primitive-env-plugin.js +408 -0
  366. package/dist/src/lib/primitive-env-plugin.js.map +1 -0
  367. package/dist/src/lib/project-login-apps.d.ts +8 -0
  368. package/dist/src/lib/project-login-apps.js +27 -0
  369. package/dist/src/lib/project-login-apps.js.map +1 -0
  370. package/dist/src/lib/prompt-schema-codegen.d.ts +36 -12
  371. package/dist/src/lib/prompt-schema-codegen.js +96 -100
  372. package/dist/src/lib/prompt-schema-codegen.js.map +1 -1
  373. package/dist/src/lib/prompt-schema-document.d.ts +35 -0
  374. package/dist/src/lib/prompt-schema-document.js +92 -0
  375. package/dist/src/lib/prompt-schema-document.js.map +1 -0
  376. package/dist/src/lib/prompt-schema-refs.d.ts +173 -0
  377. package/dist/src/lib/prompt-schema-refs.js +478 -0
  378. package/dist/src/lib/prompt-schema-refs.js.map +1 -0
  379. package/dist/src/lib/records-verbs.d.ts +79 -0
  380. package/dist/src/lib/records-verbs.js +45 -0
  381. package/dist/src/lib/records-verbs.js.map +1 -0
  382. package/dist/src/lib/register-commands.d.ts +36 -0
  383. package/dist/src/lib/register-commands.js +37 -0
  384. package/dist/src/lib/register-commands.js.map +1 -0
  385. package/dist/src/lib/retired-imports.d.ts +53 -0
  386. package/dist/src/lib/retired-imports.js +120 -0
  387. package/dist/src/lib/retired-imports.js.map +1 -0
  388. package/dist/src/lib/run-status.d.ts +1 -1
  389. package/dist/src/lib/run-status.generated.d.ts +2 -2
  390. package/dist/src/lib/run-status.generated.js +3 -1
  391. package/dist/src/lib/run-status.generated.js.map +1 -1
  392. package/dist/src/lib/run-status.js +1 -1
  393. package/dist/src/lib/schema-codegen/compiledSpace.d.ts +62 -0
  394. package/dist/src/lib/schema-codegen/compiledSpace.js +103 -0
  395. package/dist/src/lib/schema-codegen/compiledSpace.js.map +1 -0
  396. package/dist/src/lib/schema-codegen/generated-db3-bridge.d.ts +86 -0
  397. package/dist/src/lib/schema-codegen/generated-db3-bridge.js +227 -0
  398. package/dist/src/lib/schema-codegen/generated-db3-bridge.js.map +1 -0
  399. package/dist/src/lib/schema-codegen/generated-db3-query-capabilities.d.ts +85 -0
  400. package/dist/src/lib/schema-codegen/generated-db3-query-capabilities.js +86 -0
  401. package/dist/src/lib/schema-codegen/generated-db3-query-capabilities.js.map +1 -0
  402. package/dist/src/lib/schema-codegen/generated-field-grammar.d.ts +218 -0
  403. package/dist/src/lib/schema-codegen/generated-field-grammar.js +397 -0
  404. package/dist/src/lib/schema-codegen/generated-field-grammar.js.map +1 -0
  405. package/dist/src/lib/schema-codegen/generated-field-table.d.ts +80 -0
  406. package/dist/src/lib/schema-codegen/generated-field-table.js +542 -0
  407. package/dist/src/lib/schema-codegen/generated-field-table.js.map +1 -0
  408. package/dist/src/lib/schema-codegen/generated-prompt-schemas.d.ts +195 -0
  409. package/dist/src/lib/schema-codegen/generated-prompt-schemas.js +503 -0
  410. package/dist/src/lib/schema-codegen/generated-prompt-schemas.js.map +1 -0
  411. package/dist/src/lib/schema-codegen/generated-schema-descriptor.d.ts +258 -0
  412. package/dist/src/lib/schema-codegen/generated-schema-descriptor.js +422 -0
  413. package/dist/src/lib/schema-codegen/generated-schema-descriptor.js.map +1 -0
  414. package/dist/src/lib/schema-codegen/generated-schema-file.d.ts +129 -0
  415. package/dist/src/lib/schema-codegen/generated-schema-file.js +475 -0
  416. package/dist/src/lib/schema-codegen/generated-schema-file.js.map +1 -0
  417. package/dist/src/lib/schema-codegen/generated-schema-provenance.d.ts +115 -0
  418. package/dist/src/lib/schema-codegen/generated-schema-provenance.js +274 -0
  419. package/dist/src/lib/schema-codegen/generated-schema-provenance.js.map +1 -0
  420. package/dist/src/lib/schema-codegen/generated-schema-refs.d.ts +366 -0
  421. package/dist/src/lib/schema-codegen/generated-schema-refs.js +1789 -0
  422. package/dist/src/lib/schema-codegen/generated-schema-refs.js.map +1 -0
  423. package/dist/src/lib/schema-codegen/generated-schema-shape.d.ts +27 -0
  424. package/dist/src/lib/schema-codegen/generated-schema-shape.js +126 -0
  425. package/dist/src/lib/schema-codegen/generated-schema-shape.js.map +1 -0
  426. package/dist/src/lib/schema-codegen/namedRefs.d.ts +56 -0
  427. package/dist/src/lib/schema-codegen/namedRefs.js +143 -0
  428. package/dist/src/lib/schema-codegen/namedRefs.js.map +1 -0
  429. package/dist/src/lib/schema-codegen/naming.d.ts +35 -0
  430. package/dist/src/lib/schema-codegen/naming.js +83 -0
  431. package/dist/src/lib/schema-codegen/naming.js.map +1 -0
  432. package/dist/src/lib/schema-codegen/schemaChanges.d.ts +74 -0
  433. package/dist/src/lib/schema-codegen/schemaChanges.js +277 -0
  434. package/dist/src/lib/schema-codegen/schemaChanges.js.map +1 -0
  435. package/dist/src/lib/schema-codegen/schemaDocs.d.ts +69 -0
  436. package/dist/src/lib/schema-codegen/schemaDocs.js +219 -0
  437. package/dist/src/lib/schema-codegen/schemaDocs.js.map +1 -0
  438. package/dist/src/lib/schema-codegen/schemaIR.d.ts +158 -0
  439. package/dist/src/lib/schema-codegen/schemaIR.js +279 -0
  440. package/dist/src/lib/schema-codegen/schemaIR.js.map +1 -0
  441. package/dist/src/lib/schema-codegen/schemaToTs.d.ts +109 -0
  442. package/dist/src/lib/schema-codegen/schemaToTs.js +269 -0
  443. package/dist/src/lib/schema-codegen/schemaToTs.js.map +1 -0
  444. package/dist/src/lib/schema-codegen/valuesLists.d.ts +48 -0
  445. package/dist/src/lib/schema-codegen/valuesLists.js +144 -0
  446. package/dist/src/lib/schema-codegen/valuesLists.js.map +1 -0
  447. package/dist/src/lib/schema-family-index.d.ts +228 -0
  448. package/dist/src/lib/schema-family-index.js +813 -0
  449. package/dist/src/lib/schema-family-index.js.map +1 -0
  450. package/dist/src/lib/schema-pins.d.ts +82 -0
  451. package/dist/src/lib/schema-pins.js +198 -0
  452. package/dist/src/lib/schema-pins.js.map +1 -0
  453. package/dist/src/lib/schema-preview.d.ts +244 -0
  454. package/dist/src/lib/schema-preview.js +498 -0
  455. package/dist/src/lib/schema-preview.js.map +1 -0
  456. package/dist/src/lib/scope-request.d.ts +23 -11
  457. package/dist/src/lib/scope-request.js +69 -31
  458. package/dist/src/lib/scope-request.js.map +1 -1
  459. package/dist/src/lib/session-scope.d.ts +26 -0
  460. package/dist/src/lib/session-scope.js +58 -0
  461. package/dist/src/lib/session-scope.js.map +1 -0
  462. package/dist/src/lib/skill-installer.d.ts +2 -2
  463. package/dist/src/lib/skill-installer.js +2 -21
  464. package/dist/src/lib/skill-installer.js.map +1 -1
  465. package/dist/src/lib/step-run-table.d.ts +1 -2
  466. package/dist/src/lib/step-run-table.js +1 -2
  467. package/dist/src/lib/step-run-table.js.map +1 -1
  468. package/dist/src/lib/swift-codegen/agentGenerator.d.ts +2 -1
  469. package/dist/src/lib/swift-codegen/agentGenerator.js +25 -23
  470. package/dist/src/lib/swift-codegen/agentGenerator.js.map +1 -1
  471. package/dist/src/lib/swift-codegen/banners.d.ts +12 -0
  472. package/dist/src/lib/swift-codegen/banners.js +12 -0
  473. package/dist/src/lib/swift-codegen/banners.js.map +1 -1
  474. package/dist/src/lib/swift-codegen/functionGenerator.d.ts +36 -1
  475. package/dist/src/lib/swift-codegen/functionGenerator.js +169 -51
  476. package/dist/src/lib/swift-codegen/functionGenerator.js.map +1 -1
  477. package/dist/src/lib/swift-codegen/schemaToSwift.d.ts +33 -9
  478. package/dist/src/lib/swift-codegen/schemaToSwift.js +215 -179
  479. package/dist/src/lib/swift-codegen/schemaToSwift.js.map +1 -1
  480. package/dist/src/lib/swift-codegen/sharedGenerator.d.ts +45 -0
  481. package/dist/src/lib/swift-codegen/sharedGenerator.js +165 -0
  482. package/dist/src/lib/swift-codegen/sharedGenerator.js.map +1 -0
  483. package/dist/src/lib/swift-codegen/swiftKeys.d.ts +19 -0
  484. package/dist/src/lib/swift-codegen/swiftKeys.js +31 -0
  485. package/dist/src/lib/swift-codegen/swiftKeys.js.map +1 -0
  486. package/dist/src/lib/swift-codegen/userPropertiesGenerator.d.ts +30 -0
  487. package/dist/src/lib/swift-codegen/userPropertiesGenerator.js +69 -0
  488. package/dist/src/lib/swift-codegen/userPropertiesGenerator.js.map +1 -0
  489. package/dist/src/lib/sync-resource-types.d.ts +117 -31
  490. package/dist/src/lib/sync-resource-types.js +197 -189
  491. package/dist/src/lib/sync-resource-types.js.map +1 -1
  492. package/dist/src/lib/sync-selectors.d.ts +7 -0
  493. package/dist/src/lib/sync-selectors.js +22 -2
  494. package/dist/src/lib/sync-selectors.js.map +1 -1
  495. package/dist/src/lib/template.d.ts +39 -3
  496. package/dist/src/lib/template.js +103 -14
  497. package/dist/src/lib/template.js.map +1 -1
  498. package/dist/src/lib/test-case-file-names.d.ts +3 -5
  499. package/dist/src/lib/test-case-file-names.js +3 -5
  500. package/dist/src/lib/test-case-file-names.js.map +1 -1
  501. package/dist/src/lib/test-runs.d.ts +45 -0
  502. package/dist/src/lib/test-runs.js +150 -0
  503. package/dist/src/lib/test-runs.js.map +1 -0
  504. package/dist/src/lib/test-users.d.ts +25 -0
  505. package/dist/src/lib/test-users.js +36 -0
  506. package/dist/src/lib/test-users.js.map +1 -0
  507. package/dist/src/lib/toml-database-config.d.ts +4 -2
  508. package/dist/src/lib/toml-database-config.js +11 -6
  509. package/dist/src/lib/toml-database-config.js.map +1 -1
  510. package/dist/src/lib/toml-scalar-edit.js +6 -4
  511. package/dist/src/lib/toml-scalar-edit.js.map +1 -1
  512. package/dist/src/lib/transition-warnings.d.ts +21 -0
  513. package/dist/src/lib/transition-warnings.js +49 -0
  514. package/dist/src/lib/transition-warnings.js.map +1 -0
  515. package/dist/src/lib/user-index.d.ts +80 -0
  516. package/dist/src/lib/user-index.js +166 -0
  517. package/dist/src/lib/user-index.js.map +1 -0
  518. package/dist/src/lib/user-properties/generated-properties-schema.d.ts +159 -0
  519. package/dist/src/lib/user-properties/generated-properties-schema.js +471 -0
  520. package/dist/src/lib/user-properties/generated-properties-schema.js.map +1 -0
  521. package/dist/src/lib/user-properties/user-properties-codegen.d.ts +55 -0
  522. package/dist/src/lib/user-properties/user-properties-codegen.js +129 -0
  523. package/dist/src/lib/user-properties/user-properties-codegen.js.map +1 -0
  524. package/dist/src/lib/user-walk.d.ts +31 -0
  525. package/dist/src/lib/user-walk.js +102 -0
  526. package/dist/src/lib/user-walk.js.map +1 -0
  527. package/dist/src/lib/webhook-capture.d.ts +43 -0
  528. package/dist/src/lib/webhook-capture.js +91 -0
  529. package/dist/src/lib/webhook-capture.js.map +1 -0
  530. package/dist/src/lib/webhook-deliver.d.ts +18 -20
  531. package/dist/src/lib/webhook-deliver.js +34 -89
  532. package/dist/src/lib/webhook-deliver.js.map +1 -1
  533. package/dist/src/lib/webhook-test-run.d.ts +32 -0
  534. package/dist/src/lib/webhook-test-run.js +108 -0
  535. package/dist/src/lib/webhook-test-run.js.map +1 -0
  536. package/dist/src/lib/worker-perf-format.d.ts +22 -0
  537. package/dist/src/lib/worker-perf-format.js +27 -0
  538. package/dist/src/lib/worker-perf-format.js.map +1 -0
  539. package/dist/src/types/index.d.ts +20 -65
  540. package/dist/src/validators.d.ts +7 -55
  541. package/dist/src/validators.js +7 -53
  542. package/dist/src/validators.js.map +1 -1
  543. package/dist/src/vite.d.ts +17 -0
  544. package/dist/src/vite.js +18 -0
  545. package/dist/src/vite.js.map +1 -0
  546. package/package.json +20 -9
@@ -0,0 +1,1444 @@
1
+ import { Option } from "commander";
2
+ import { commandStatus } from "../lib/command-status.js";
3
+ import { ApiClient } from "../lib/api-client.js";
4
+ import { resolveAppId } from "../lib/config.js";
5
+ import { error, flushOutput, formatDate, formatTable, info, json, result as printResult, success, warn } from "../lib/output.js";
6
+ import { confirmPrompt } from "../lib/confirm-prompt.js";
7
+ import { normalizeCliListEnvelope, wholeListEnvelope } from "../lib/paginate.js";
8
+ import { parseDataOption } from "../lib/data-input.js";
9
+ import { parseFilterOptions } from "../lib/record-filter.js";
10
+ import { DB3_BATCH_OPERATION_CAP, DB3_ROUTES } from "../lib/records-verbs.js";
11
+ import { DB3_LOAD_ROUTES } from "../lib/load-routes.js";
12
+ import { declarationOfSchemaAnswer, declaredModelNames, exportDb3, loadDb3Rows, pendingRegistrations, planDb3Import, readDb3Manifest, readExportedBlobs, resolvedTypeName, } from "../lib/db3-export.js";
13
+ import fs from "fs";
14
+ import path from "path";
15
+ import { DB3_INDEX_KINDS, DB3_INDEX_PLACEMENTS, VECTOR_DISTANCES, VECTOR_INDEX_MODES, VECTOR_QUANTIZERS, db3IndexKindOnTheWire, db3IndexRefusalLines, db3IndexRefusalSentence, db3IndexTableRows, listsVectorIndex, db3TextOptionsOf, vectorIndexOptions, } from "../lib/db3-index-output.js";
16
+ import { parseCustodianOrExit } from "../lib/custodian.js";
17
+ import { pageCursorOption, pageLimitOption, parsePageLimit, printEmptyPage, printPageHint } from "../lib/list-options.js";
18
+ import { aggregateReadOf, aggregateRecordsAction, batchReadRecordsAction, batchRecordsAction, countRecordsAction, deleteRecordAction, describeAction, describeRecordsFailure, displayTags, inspectAction, modelsAction, patchRecordAction, queryReadOf, queryRecordsAction, saveRecordAction, schemaAction, statsAction, ingestAction, listIngestsAction, getIngestAction, abortIngestAction, listSnapshotsAction, getSnapshotAction, buildSnapshotAction, } from "./documents.js";
19
+ /**
20
+ * The `--data-file` help of `db3 records batch`: the db3 operation shapes,
21
+ * reads among them (#5243), the cap, and the command for a larger load.
22
+ */
23
+ export const DB3_BATCH_DATA_FILE_HELP = "JSON file with { operations: [...] } or a bare operations array, " +
24
+ `at most ${DB3_BATCH_OPERATION_CAP} operations per call (atomic): all apply or none do, in order. ` +
25
+ "Each write is one of { model, action: create, data, id? } (the database assigns " +
26
+ "the id when none is given), { model, action: patch, id, data }, " +
27
+ "{ model, action: increment, id, fields } (each field's delta), " +
28
+ "{ model, action: delete, id } or { model, action: upsert, constraint, data, id? } " +
29
+ "(merged into the record holding that unique constraint's key, or created). " +
30
+ "Any write takes a condition, a query filter the record must match or the batch is refused. " +
31
+ "A read { model, action: query, filter?, sort?, limit?, cursor?, include? }, " +
32
+ "{ model, action: count, filter? } or { model, action: aggregate, options } is answered " +
33
+ "against the writes before it. For larger loads use `primitive db3 ingest`";
34
+ /** The `--data-file` help of `db3 records batch-read` (#5243): the read shapes and the cap. */
35
+ export const DB3_BATCH_READ_DATA_FILE_HELP = "JSON file with { operations: [...] } or a bare array of reads, " +
36
+ `at most ${DB3_BATCH_OPERATION_CAP} per call, all answered from one state of the db3. ` +
37
+ "Each read is { model, action: query, filter?, sort?, limit?, cursor?, include? }, " +
38
+ "{ model, action: count, filter? } or { model, action: aggregate, options }";
39
+ /**
40
+ * A refused index call: the server's sentence, its code and status, then one
41
+ * line per detail the code names (the duplicate keys, the origins keeping
42
+ * the index, the index a name belongs to, the stored format). The sentence
43
+ * is printed in the CLI's words (#5890): a set-element index, and `spelling`
44
+ * for the set-element flag the user typed.
45
+ */
46
+ function refuse(err, spelling = "--set-elements") {
47
+ const reworded = typeof err?.message === "string"
48
+ ? { message: db3IndexRefusalSentence(err.message, err.code, spelling), code: err.code, statusCode: err.statusCode, status: err.status }
49
+ : err;
50
+ error(describeRecordsFailure(reworded));
51
+ for (const line of db3IndexRefusalLines(err))
52
+ console.error(` ${line}`);
53
+ process.exit(1);
54
+ }
55
+ /** A refused db3 call: the server's sentence, its code and its status, then exit 1. */
56
+ function fail(err) {
57
+ error(describeRecordsFailure(err));
58
+ process.exit(1);
59
+ }
60
+ /** `--explain` on a records read verb (#5240). */
61
+ const EXPLAIN_FLAG = "Explain the read on the server instead of answering it: the indexes it used, what it scanned and the rows it read";
62
+ /** `--index` on a records read verb (#5240). */
63
+ const INDEX_FLAG = "Explain the read forced onto this index of the model, or 'none' to read with no index (implies --explain)";
64
+ /** Whether a records read verb was asked to explain: `--explain`, or `--index`, which implies it. */
65
+ const explaining = (options) => options.explain === true || options.index !== undefined;
66
+ /**
67
+ * A records read explained (#5240): sends `read` through `client`, with
68
+ * `--index` as its force, to `POST db3/:id/records/:model/explain` and prints the answer,
69
+ * or `--json` it. A refusal prints the server's sentence, code and status,
70
+ * and a force's reason.
71
+ */
72
+ async function explainReadAction(client, appId, db3Id, modelName, options, read) {
73
+ try {
74
+ const answer = await client.explainDb3Read(appId, db3Id, modelName, {
75
+ ...read,
76
+ ...(options.index !== undefined ? { index: options.index } : {}),
77
+ });
78
+ if (options.json) {
79
+ json(answer);
80
+ return;
81
+ }
82
+ printExplain(answer);
83
+ }
84
+ catch (err) {
85
+ refuse(err);
86
+ }
87
+ }
88
+ /** An explain's answer: the read and its force, what it used, scanned, read and answered, then each statement's plan. */
89
+ function printExplain(answer) {
90
+ const forced = answer.index === null ? "no" : answer.index === "none" ? "none (no index)" : answer.index;
91
+ printResult("Read", `${answer.op} ${answer.model}`);
92
+ printResult("Forced", forced);
93
+ printResult("Indexes", answer.indexes.length > 0 ? answer.indexes.join(", ") : "none");
94
+ printResult("Scanned", answer.scanned.length > 0 ? answer.scanned.join(", ") : "none");
95
+ printResult("Rows read", answer.cost?.rowsRead ?? "not reported");
96
+ printResult("Answered", answer.answered);
97
+ for (const statement of answer.statements) {
98
+ console.log("");
99
+ console.log(statement.runs > 1 ? `${statement.model} (${statement.runs} runs)` : statement.model);
100
+ if (statement.plan === null)
101
+ console.log(` (no plan: ${statement.planError ?? "refused"})`);
102
+ else
103
+ for (const line of statement.plan)
104
+ console.log(` ${line}`);
105
+ }
106
+ }
107
+ /** Print `message` and exit 1, before any request. */
108
+ function refuseList(message) {
109
+ error(message);
110
+ process.exit(1);
111
+ }
112
+ /** The ways `db3 list --user-id` reads, in listing order. */
113
+ const DB3_VIAS = ["held", "shared", "app"];
114
+ /**
115
+ * The columns of `db3 list --user-id`, in order: each a field of the client's
116
+ * `Db3Row` or `Db3ListEntry` (`src/client/api/db3Api.ts`).
117
+ */
118
+ export const USER_DB3_TABLE_FIELDS = ["id", "title", "via", "permission", "custodian", "sync", "type", "grantedAt"];
119
+ const USER_DB3_TABLE_HEADERS = {
120
+ id: "ID",
121
+ title: "TITLE",
122
+ via: "VIA",
123
+ permission: "PERMISSION",
124
+ custodian: "CUSTODIAN",
125
+ sync: "SYNC",
126
+ type: "TYPE",
127
+ grantedAt: "GRANTED",
128
+ };
129
+ /** `--via` as a list of ways, or exit 1 before any request when it names anything else. */
130
+ function parseVia(value) {
131
+ const ways = value.split(",");
132
+ if (!value || ways.some((way) => !DB3_VIAS.includes(way))) {
133
+ refuseList("--via lists some of held, shared and app, comma-separated.");
134
+ }
135
+ return ways;
136
+ }
137
+ /** `on` or `off` as a boolean, or exit 1 naming `label` before any request. */
138
+ function parseOnOff(value, label) {
139
+ if (value === "on")
140
+ return true;
141
+ if (value === "off")
142
+ return false;
143
+ error(`${label} must be "on" or "off".`);
144
+ process.exit(1);
145
+ }
146
+ /** The lines a db3 is printed as: its id, title, custodian, sync and type. */
147
+ function printDb3(row) {
148
+ printResult("ID", row.id);
149
+ printResult("Title", row.title);
150
+ printResult("Custodian", row.custodian ?? "none");
151
+ printResult("Sync", row.sync === false ? "off" : "on");
152
+ printResult("Type", row.type ?? "none");
153
+ }
154
+ /**
155
+ * `primitive db3` (#4696, #4804): a db3's lifecycle (`create`, `get`,
156
+ * `list`, `delete`, `stats`), its sync, app access and custody, its indexes,
157
+ * and its records, schema and room through the `db3/:id/*` routes.
158
+ *
159
+ * The records, schema and inspect verbs are the `documents` verbs' twins:
160
+ * they share their action code (`./documents.ts`) through the db3 routes
161
+ * (`DB3_ROUTES`), take the same arguments and flags but `--document-format`
162
+ * (a db3 is format 3), and print what their twins print.
163
+ */
164
+ export function registerDb3Commands(program) {
165
+ const db3 = program
166
+ .command("db3")
167
+ .description("Work with db3s: create, read, list and delete them, their sync, app access and custody, indexes, records, schema and room");
168
+ commandStatus(db3, { stability: "beta" });
169
+ // ---- Indexes ----
170
+ const indexes = db3.command("indexes").description("List, register and drop a db3's indexes");
171
+ indexes
172
+ .command("list")
173
+ .description("List a db3's indexes: declared and registered")
174
+ .argument("<db3-id>", "db3 ID")
175
+ .option("--app <app-id>", "App ID")
176
+ .option("--json", "Output as JSON")
177
+ .action(async (db3Id, options) => {
178
+ const resolvedAppId = resolveAppId(undefined, options);
179
+ const client = new ApiClient();
180
+ try {
181
+ const { indexes: list } = await client.listDb3Indexes(resolvedAppId, db3Id);
182
+ if (options.json) {
183
+ json(wholeListEnvelope(list));
184
+ return;
185
+ }
186
+ if (list.length === 0) {
187
+ info("No indexes on this db3.");
188
+ return;
189
+ }
190
+ console.log(formatTable(db3IndexTableRows(list), [
191
+ { header: "NAME", key: "name", flex: true },
192
+ { header: "MODEL", key: "model" },
193
+ { header: "FIELDS", key: "fields" },
194
+ { header: "UNIQUE", key: "unique" },
195
+ { header: "ORIGINS", key: "origins" },
196
+ { header: "KIND", key: "kind" },
197
+ { header: "ON", key: "on" },
198
+ // #5229 — a vector index's shared model; a list with no vector index prints as before.
199
+ ...(listsVectorIndex(list) ? [{ header: "ANN MODEL", key: "annModel" }] : []),
200
+ ]));
201
+ }
202
+ catch (err) {
203
+ refuse(err);
204
+ }
205
+ });
206
+ indexes
207
+ .command("register")
208
+ .description("Register an index on a db3 model's field, or a named composite over several fields")
209
+ .argument("<db3-id>", "db3 ID")
210
+ .requiredOption("--model <model>", "Model name")
211
+ .requiredOption("--field <field>", "Field to index (repeat it for a composite unique index, which also needs --unique and --name)", (value, previous = []) => previous.concat(value))
212
+ .option("--unique", "Enforce that no two records share the key")
213
+ .option("--name <name>", "Name the index (idx_named_<model>_<name>)")
214
+ .option("--set-elements", "Index a string-set field's elements (idx_members_<model>_<field>) for $contains, any-of and facets; one --field, no --unique or --name (the same as --kind set-elements)")
215
+ // #5890 — the old spelling of --set-elements, kept outside the documented surface.
216
+ .addOption(new Option("--members", "Deprecated: use --set-elements").hideHelp())
217
+ .option("--kind <kind>", `What the index is: ${DB3_INDEX_KINDS.join(", ")} (default scalar, set-elements with --set-elements)`)
218
+ .option("--on <placement>", `Where the index lives: ${DB3_INDEX_PLACEMENTS.join(", ")} (default both, server for a set-element index, device for a vector index); change it by dropping and registering again`)
219
+ .option("--distance <distance>", `A vector index's distance: ${VECTOR_DISTANCES.join(", ")} (with --kind vector)`)
220
+ .option("--index <mode>", `A vector index's search: ${VECTOR_INDEX_MODES.join(", ")} (with --kind vector; default exact)`)
221
+ .option("--nbucket <n>", "An ann vector index's bucket count (with --index ann)")
222
+ .option("--codesize <n>", "An ann vector index's bytes per quantized vector (with --index ann)")
223
+ .option("--quantizer <quantizer>", `An ann vector index's quantizer: ${VECTOR_QUANTIZERS.join(", ")} (with --index ann)`)
224
+ .option("--tokenizer <tokenizer>", "A text index's tokenizer: unicode61 (the default, diacritics folded) or porter (English stems)")
225
+ .option("--prefix <lengths>", "A text index's prefix lengths to index, comma-separated (e.g. 2,3)")
226
+ .option("--weight <field=weight>", "A text index's weight for one of its fields (repeatable; 1 by default)", (value, previous = []) => previous.concat(value))
227
+ .option("--app <app-id>", "App ID")
228
+ .option("--json", "Output as JSON")
229
+ .action(async (db3Id, options) => {
230
+ const resolvedAppId = resolveAppId(undefined, options);
231
+ const fields = options.field;
232
+ const kind = options.kind;
233
+ const vector = vectorIndexOptions(options, kind);
234
+ if ("problem" in vector) {
235
+ error(vector.problem);
236
+ process.exit(1);
237
+ }
238
+ if (options.members && options.setElements) {
239
+ error("--members is the old spelling of --set-elements: give --set-elements alone");
240
+ process.exit(1);
241
+ }
242
+ // #5890 — the old spellings still register the same index, saying so once each.
243
+ if (options.members)
244
+ warn("--members is deprecated: use --set-elements");
245
+ if (kind === "members")
246
+ warn("--kind members is deprecated: use --kind set-elements");
247
+ const setFlag = options.setElements === true || options.members === true;
248
+ const setFlagSpelling = options.members ? "--members" : "--set-elements";
249
+ const members = setFlag || kind === "members" || kind === "set-elements";
250
+ // The set-element spelling the user typed: the flag, else the kind.
251
+ const flag = setFlag
252
+ ? setFlagSpelling
253
+ : kind === "members"
254
+ ? "--kind members"
255
+ : kind === "set-elements"
256
+ ? "--kind set-elements"
257
+ : "--set-elements";
258
+ const textOptions = options.tokenizer !== undefined || options.prefix !== undefined || options.weight !== undefined;
259
+ const text = kind === "text" ? db3TextOptionsOf(options) : null;
260
+ const conflict = kind !== undefined && kind !== "members" && !DB3_INDEX_KINDS.includes(kind)
261
+ ? `--kind must be one of ${DB3_INDEX_KINDS.join(", ")}`
262
+ : options.on !== undefined && !DB3_INDEX_PLACEMENTS.includes(options.on)
263
+ ? `--on must be one of ${DB3_INDEX_PLACEMENTS.join(", ")}`
264
+ : setFlag && kind !== undefined && kind !== "members" && kind !== "set-elements"
265
+ ? `${setFlagSpelling} is --kind set-elements: give --kind ${kind} without ${setFlagSpelling}, or --kind set-elements`
266
+ : textOptions && kind !== "text"
267
+ ? `--tokenizer, --prefix and --weight apply to --kind text`
268
+ : text && "refusal" in text
269
+ ? text.refusal
270
+ : kind === "text" && options.unique
271
+ ? `--kind text takes no --unique: a text index enforces nothing`
272
+ : kind === "text" && options.name !== undefined
273
+ ? `--kind text takes no --name: a model's text index is named idx_text_<model>`
274
+ : !members
275
+ ? null
276
+ : fields.length > 1
277
+ ? `${flag} takes one --field: a set-element index covers one string-set field`
278
+ : options.unique
279
+ ? `${flag} takes no --unique: a set-element index enforces nothing`
280
+ : options.name !== undefined
281
+ ? `${flag} takes no --name: a set-element index is named idx_members_<model>_<field>`
282
+ : null;
283
+ if (conflict) {
284
+ error(conflict);
285
+ process.exit(1);
286
+ }
287
+ const textBody = text && "text" in text && Object.keys(text.text).length > 0 ? { text: text.text } : {};
288
+ const body = {
289
+ model: options.model,
290
+ ...(fields.length === 1 ? { field: fields[0] } : { fields }),
291
+ ...(options.unique ? { unique: true } : {}),
292
+ ...(options.name !== undefined ? { name: options.name } : {}),
293
+ ...(setFlag ? { members: true } : {}),
294
+ ...(kind !== undefined ? { kind: db3IndexKindOnTheWire(kind) } : {}),
295
+ ...(options.on !== undefined ? { on: options.on } : {}),
296
+ ...(vector.options ? { vector: vector.options } : {}),
297
+ ...textBody,
298
+ };
299
+ const client = new ApiClient();
300
+ try {
301
+ const { index } = await client.registerDb3Index(resolvedAppId, db3Id, body);
302
+ if (options.json) {
303
+ json(index);
304
+ return;
305
+ }
306
+ success(`Registered ${index.name} on ${index.model} (${index.fields.join(", ")}${index.unique ? ", unique" : ""}${index.members ? ", set-element index" : ""}${index.kind === "text" ? ", text" : ""}).`);
307
+ }
308
+ catch (err) {
309
+ refuse(err, flag);
310
+ }
311
+ });
312
+ indexes
313
+ .command("drop")
314
+ .description("Drop a db3 index you registered (one a declaration keeps stays)")
315
+ .argument("<db3-id>", "db3 ID")
316
+ .argument("<name>", "Index name, as `db3 indexes list` prints it")
317
+ .option("--app <app-id>", "App ID")
318
+ .option("-y, --yes", "Skip confirmation prompt")
319
+ .option("--json", "Output as JSON")
320
+ .action(async (db3Id, name, options) => {
321
+ const resolvedAppId = resolveAppId(undefined, options);
322
+ if (!options.yes) {
323
+ let confirmed;
324
+ try {
325
+ confirmed = await confirmPrompt(`Drop index ${name} from db3 ${db3Id}?`);
326
+ }
327
+ catch (err) {
328
+ error(err.message);
329
+ process.exit(1);
330
+ }
331
+ if (!confirmed) {
332
+ info("Cancelled.");
333
+ return;
334
+ }
335
+ }
336
+ const client = new ApiClient();
337
+ try {
338
+ const answer = await client.dropDb3Index(resolvedAppId, db3Id, name);
339
+ if (options.json) {
340
+ json(answer);
341
+ return;
342
+ }
343
+ success(`Dropped ${answer.name}.`);
344
+ }
345
+ catch (err) {
346
+ refuse(err);
347
+ }
348
+ });
349
+ // ---- A vector index's shared ANN model (#5229) ----
350
+ const model = indexes.command("model").description("Fetch or delete an ann vector index's shared model");
351
+ model
352
+ .command("get")
353
+ .description("Write an ann vector index's shared model to a file, as a device uploaded it")
354
+ .argument("<db3-id>", "db3 ID")
355
+ .argument("<name>", "Vector index name, as `db3 indexes list` prints it")
356
+ .option("--out <file>", "Where to write the model (default <name>-<generation>-<revision>.pvm1)")
357
+ .option("--app <app-id>", "App ID")
358
+ .option("--json", "Output as JSON")
359
+ .action(async (db3Id, name, options) => {
360
+ const resolvedAppId = resolveAppId(undefined, options);
361
+ const client = new ApiClient();
362
+ try {
363
+ const fetched = await client.fetchDb3IndexModel(resolvedAppId, db3Id, name);
364
+ const out = path.resolve(options.out ?? `${name}-${fetched.generation}-${fetched.revision}.pvm1`);
365
+ fs.writeFileSync(out, fetched.data);
366
+ const summary = {
367
+ name,
368
+ file: out,
369
+ bytes: fetched.data.byteLength,
370
+ generation: fetched.generation,
371
+ revision: fetched.revision,
372
+ rows: fetched.rows,
373
+ trainedAt: fetched.trainedAt,
374
+ format: fetched.format,
375
+ };
376
+ if (options.json) {
377
+ json(summary);
378
+ return;
379
+ }
380
+ success(`Wrote ${name}'s model (revision ${fetched.revision}, ${fetched.rows} rows, trained ${fetched.trainedAt}) to ${out}: ${fetched.data.byteLength} bytes.`);
381
+ }
382
+ catch (err) {
383
+ refuse(err);
384
+ }
385
+ });
386
+ model
387
+ .command("delete")
388
+ .description("Delete an ann vector index's shared model so a device trains it again (the db3's owner)")
389
+ .argument("<db3-id>", "db3 ID")
390
+ .argument("<name>", "Vector index name, as `db3 indexes list` prints it")
391
+ .option("--app <app-id>", "App ID")
392
+ .option("-y, --yes", "Skip confirmation prompt")
393
+ .option("--json", "Output as JSON")
394
+ .action(async (db3Id, name, options) => {
395
+ const resolvedAppId = resolveAppId(undefined, options);
396
+ if (!options.yes) {
397
+ let confirmed;
398
+ try {
399
+ confirmed = await confirmPrompt(`Delete ${name}'s shared model on db3 ${db3Id}? Every device answers exactly until one trains it again.`);
400
+ }
401
+ catch (err) {
402
+ error(err.message);
403
+ process.exit(1);
404
+ }
405
+ if (!confirmed) {
406
+ info("Cancelled.");
407
+ return;
408
+ }
409
+ }
410
+ const client = new ApiClient();
411
+ try {
412
+ const answer = await client.deleteDb3IndexModel(resolvedAppId, db3Id, name);
413
+ if (options.json) {
414
+ json(answer);
415
+ return;
416
+ }
417
+ success(`Deleted ${answer.name}'s model; its revision is now ${answer.revision}.`);
418
+ }
419
+ catch (err) {
420
+ refuse(err);
421
+ }
422
+ });
423
+ // ---- Records: the `documents records` verbs' twins ----
424
+ const records = db3.command("records").description("Query and write a db3's records");
425
+ records
426
+ .command("query")
427
+ .description("Query records in a db3 model")
428
+ .argument("<db3-id>", "db3 ID")
429
+ .argument("<model-name>", "Model name to query")
430
+ .option("--app <app-id>", "App ID")
431
+ .option("--filter <json>", "Filter as JSON (e.g. '{\"status\":\"open\"}')")
432
+ .option("--filter-file <path>", "Read filter from a JSON or TOML file")
433
+ .option("--sort <json>", "Sort as JSON, e.g. '{\"createdAt\":-1}'; 1 ascending, -1 descending, key order is precedence; repeat it with --cursor")
434
+ .option("--limit <n>", "Records per page (default 100, max 10000)")
435
+ .option("--cursor <cursor>", "Pagination cursor from a previous query (valid only with the same --sort)")
436
+ .option("--include <json>", "Related records as a JSON array of include specs, e.g. '[{\"model\":\"customer\",\"type\":\"refersTo\",\"sourceField\":\"customerId\"}]'; answered as _related")
437
+ .option("--explain", EXPLAIN_FLAG)
438
+ .option("--index <name>", INDEX_FLAG)
439
+ .option("--json", "Output as JSON")
440
+ .action(async (db3Id, modelName, options) => {
441
+ const resolvedAppId = resolveAppId(undefined, options);
442
+ if (explaining(options)) {
443
+ const { filter, sort, include } = queryReadOf(options);
444
+ const limit = options.limit === undefined ? undefined : /^\d+$/.test(options.limit) ? Number(options.limit) : options.limit;
445
+ await explainReadAction(new ApiClient(), resolvedAppId, db3Id, modelName, options, {
446
+ op: "query",
447
+ ...(filter ? { filter } : {}),
448
+ options: {
449
+ ...(sort !== undefined ? { sort } : {}),
450
+ ...(limit !== undefined ? { limit } : {}),
451
+ ...(options.cursor !== undefined ? { cursor: options.cursor } : {}),
452
+ ...(include !== undefined ? { include } : {}),
453
+ },
454
+ });
455
+ return;
456
+ }
457
+ await queryRecordsAction(DB3_ROUTES, resolvedAppId, db3Id, modelName, options);
458
+ });
459
+ records
460
+ .command("count")
461
+ .description("Count records in a db3 model")
462
+ .argument("<db3-id>", "db3 ID")
463
+ .argument("<model-name>", "Model name to count")
464
+ .option("--app <app-id>", "App ID")
465
+ .option("--filter <json>", "Filter as JSON (e.g. '{\"status\":\"open\"}')")
466
+ .option("--filter-file <path>", "Read filter from a JSON or TOML file")
467
+ .option("--explain", EXPLAIN_FLAG)
468
+ .option("--index <name>", INDEX_FLAG)
469
+ .option("--json", "Output as JSON")
470
+ .action(async (db3Id, modelName, options) => {
471
+ const resolvedAppId = resolveAppId(undefined, options);
472
+ if (explaining(options)) {
473
+ const filter = parseFilterOptions(options);
474
+ await explainReadAction(new ApiClient(), resolvedAppId, db3Id, modelName, options, { op: "count", ...(filter ? { filter } : {}) });
475
+ return;
476
+ }
477
+ await countRecordsAction(DB3_ROUTES, resolvedAppId, db3Id, modelName, options);
478
+ });
479
+ records
480
+ .command("aggregate")
481
+ .description("Aggregate records in a db3 model (count/sum/avg/min/max, optional group-by)")
482
+ .argument("<db3-id>", "db3 ID")
483
+ .argument("<model-name>", "Model name")
484
+ .option("--app <app-id>", "App ID")
485
+ .requiredOption("--op <operation>", "Aggregate operation: count|sum|avg|min|max")
486
+ .option("--field <field>", "Field to aggregate (required for sum/avg/min/max)")
487
+ .option("--group-by <field>", "Group results by this field (repeatable)", (value, previous = []) => previous.concat(value), [])
488
+ .option("--filter <json>", "Filter as JSON")
489
+ .option("--filter-file <path>", "Read filter from a JSON or TOML file")
490
+ .option("--explain", EXPLAIN_FLAG)
491
+ .option("--index <name>", INDEX_FLAG)
492
+ .option("--json", "Output as JSON")
493
+ .action(async (db3Id, modelName, options) => {
494
+ const resolvedAppId = resolveAppId(undefined, options);
495
+ if (explaining(options)) {
496
+ const { operations, groupBy, filter } = aggregateReadOf(options);
497
+ await explainReadAction(new ApiClient(), resolvedAppId, db3Id, modelName, options, {
498
+ op: "aggregate",
499
+ aggregate: { operations, groupBy, ...(filter ? { filter } : {}) },
500
+ });
501
+ return;
502
+ }
503
+ await aggregateRecordsAction(DB3_ROUTES, resolvedAppId, db3Id, modelName, options);
504
+ });
505
+ records
506
+ .command("save")
507
+ .description("Create or replace a record in a db3 model")
508
+ .argument("<db3-id>", "db3 ID")
509
+ .argument("<model-name>", "Model name to write to")
510
+ .option("--app <app-id>", "App ID")
511
+ .option("--id <record-id>", "Record ID (a ULID is generated when omitted)")
512
+ .option("--data <json>", "Record fields as JSON (e.g. '{\"qty\":10}')")
513
+ .option("--data-file <file>", "Read record fields from a JSON file")
514
+ .option("--upsert-on <field>", "Update the record whose <field> matches instead of creating")
515
+ .option("--json", "Output as JSON")
516
+ .action(async (db3Id, modelName, options) => {
517
+ const data = parseDataOption(options, "record fields");
518
+ const resolvedAppId = resolveAppId(undefined, options);
519
+ await saveRecordAction(DB3_ROUTES, resolvedAppId, db3Id, modelName, data, options);
520
+ });
521
+ records
522
+ .command("patch")
523
+ .description("Merge fields into an existing record in a db3 model")
524
+ .argument("<db3-id>", "db3 ID")
525
+ .argument("<model-name>", "Model name")
526
+ .argument("<record-id>", "Record ID to patch")
527
+ .option("--app <app-id>", "App ID")
528
+ .option("--data <json>", "Fields to merge as JSON (e.g. '{\"status\":\"closed\"}')")
529
+ .option("--data-file <file>", "Read fields from a JSON file")
530
+ .option("--json", "Output as JSON")
531
+ .action(async (db3Id, modelName, recordId, options) => {
532
+ const data = parseDataOption(options, "fields to merge");
533
+ const resolvedAppId = resolveAppId(undefined, options);
534
+ await patchRecordAction(DB3_ROUTES, resolvedAppId, db3Id, modelName, recordId, data, options);
535
+ });
536
+ records
537
+ .command("delete")
538
+ .description("Delete a record from a db3 model")
539
+ .argument("<db3-id>", "db3 ID")
540
+ .argument("<model-name>", "Model name")
541
+ .argument("<record-id>", "Record ID to delete")
542
+ .option("--app <app-id>", "App ID")
543
+ .option("-y, --yes", "Skip confirmation prompt")
544
+ .option("--json", "Output as JSON")
545
+ .action(async (db3Id, modelName, recordId, options) => {
546
+ const resolvedAppId = resolveAppId(undefined, options);
547
+ await deleteRecordAction(DB3_ROUTES, resolvedAppId, db3Id, modelName, recordId, options);
548
+ });
549
+ records
550
+ .command("batch")
551
+ .description(`Apply create/patch/increment/delete/upsert operations to a db3, with reads among them, at most ${DB3_BATCH_OPERATION_CAP} ` +
552
+ "operations per call (atomic); use `primitive db3 ingest` for larger loads")
553
+ .argument("<db3-id>", "db3 ID")
554
+ .requiredOption("--data-file <file>", DB3_BATCH_DATA_FILE_HELP)
555
+ .option("--app <app-id>", "App ID")
556
+ .option("-y, --yes", "Skip confirmation prompt")
557
+ .option("--json", "Output as JSON")
558
+ .action(async (db3Id, options) => {
559
+ await batchRecordsAction(DB3_ROUTES, db3Id, options);
560
+ });
561
+ records
562
+ .command("batch-read")
563
+ .description(`Run several queries, counts and aggregates on a db3 in one request, at most ${DB3_BATCH_OPERATION_CAP} ` +
564
+ "per call, answered from one state of the db3")
565
+ .argument("<db3-id>", "db3 ID")
566
+ .requiredOption("--data-file <file>", DB3_BATCH_READ_DATA_FILE_HELP)
567
+ .option("--partial", "Answer a refused read in its place instead of refusing the request")
568
+ .option("--app <app-id>", "App ID")
569
+ .option("--json", "Output as JSON")
570
+ .action(async (db3Id, options) => {
571
+ const client = new ApiClient();
572
+ await batchReadRecordsAction(client, db3Id, options);
573
+ });
574
+ records
575
+ .command("models")
576
+ .description("List model names in a db3")
577
+ .argument("<db3-id>", "db3 ID")
578
+ .option("--app <app-id>", "App ID")
579
+ .option("--json", "Output as JSON")
580
+ .action(async (db3Id, options) => {
581
+ await modelsAction(DB3_ROUTES, db3Id, options);
582
+ });
583
+ records
584
+ .command("describe")
585
+ .description("Show a db3 model's fields and indexes")
586
+ .argument("<db3-id>", "db3 ID")
587
+ .argument("<model-name>", "Model name")
588
+ .option("--app <app-id>", "App ID")
589
+ .option("--json", "Output as JSON")
590
+ .action(async (db3Id, modelName, options) => {
591
+ await describeAction(DB3_ROUTES, db3Id, modelName, options);
592
+ });
593
+ records
594
+ .command("increment")
595
+ .description("Add to numeric fields of a record in a db3 model (a missing or non-numeric field starts at 0)")
596
+ .argument("<db3-id>", "db3 ID")
597
+ .argument("<model-name>", "Model name")
598
+ .argument("<record-id>", "Record ID")
599
+ .option("--app <app-id>", "App ID")
600
+ .option("--data <json>", "Each field's delta as JSON (e.g. '{\"qty\":2}')")
601
+ .option("--data-file <file>", "Read the deltas from a JSON file")
602
+ .option("--json", "Output as JSON")
603
+ .action(async (db3Id, modelName, recordId, options) => {
604
+ const fields = parseDataOption(options, "field deltas");
605
+ const resolvedAppId = resolveAppId(undefined, options);
606
+ try {
607
+ const answer = await new ApiClient().incrementDb3Record(resolvedAppId, db3Id, modelName, recordId, { fields });
608
+ if (options.json) {
609
+ json(answer);
610
+ return;
611
+ }
612
+ for (const [field, value] of Object.entries(answer.values ?? {}))
613
+ printResult(field, value);
614
+ }
615
+ catch (err) {
616
+ fail(err);
617
+ }
618
+ });
619
+ // ---- Schema and room: the `documents schema` and `documents inspect` twins ----
620
+ db3
621
+ .command("schema")
622
+ .description("Show a db3's models and fields as declared and observed, or export them as a schema.toml")
623
+ .argument("<db3-id>", "db3 ID")
624
+ .option("--app <app-id>", "App ID")
625
+ .option("--toml", "Print a schema.toml the client's schemaToml option and js-bao-codegen-v2 accept")
626
+ .option("--output <file>", "With --toml: write the TOML to this file (overwriting it) instead of stdout")
627
+ .option("--json", "Output the /schema answer as JSON")
628
+ .action(async (db3Id, options) => {
629
+ await schemaAction(DB3_ROUTES, db3Id, options);
630
+ });
631
+ // ---- Type (#4802): attach a db3 type, or read the one it has ----
632
+ const type = db3.command("type").description("Attach a db3 type to a db3, or show the one it has");
633
+ type
634
+ .command("attach")
635
+ .description("Install a type's current revision in a db3, whole or not at all (a type is never detached)")
636
+ .argument("<db3-id>", "db3 ID")
637
+ .argument("<name>", "Type name")
638
+ .option("--app <app-id>", "App ID")
639
+ .option("--json", "Output as JSON")
640
+ .action(async (db3Id, name, options) => {
641
+ const resolvedAppId = resolveAppId(undefined, options);
642
+ try {
643
+ const answer = await new ApiClient().attachDb3Type(resolvedAppId, db3Id, name);
644
+ if (options.json) {
645
+ json(answer);
646
+ return;
647
+ }
648
+ success(`${db3Id} is of type ${answer.type}: ${answer.outcome} (revision ${new Date(answer.revision.generation).toISOString()})`);
649
+ }
650
+ catch (err) {
651
+ if (options.json) {
652
+ json({ ok: false, code: err?.code ?? null, message: err?.message ?? String(err), details: err?.details ?? null });
653
+ process.exit(1);
654
+ }
655
+ error(describeRecordsFailure(err));
656
+ for (const reason of err?.details?.reasons ?? [])
657
+ console.error(` ${reason.path}: ${reason.reason}`);
658
+ if (err?.details?.installed)
659
+ console.error(` installed: ${err.details.installed}`);
660
+ process.exit(1);
661
+ }
662
+ });
663
+ type
664
+ .command("get")
665
+ .description("Show the type a db3's row names, its revision, and what the db3's room holds")
666
+ .argument("<db3-id>", "db3 ID")
667
+ .option("--app <app-id>", "App ID")
668
+ .option("--json", "Output as JSON")
669
+ .action(async (db3Id, options) => {
670
+ const resolvedAppId = resolveAppId(undefined, options);
671
+ try {
672
+ const answer = await new ApiClient().getDb3Type(resolvedAppId, db3Id);
673
+ if (options.json) {
674
+ json(answer);
675
+ return;
676
+ }
677
+ const revision = (r) => (r ? `${new Date(r.generation).toISOString()} (${String(r.hash).slice(0, 12)})` : "—");
678
+ console.log(`Type: ${answer.type ?? "none"}`);
679
+ console.log(`Revision: ${revision(answer.revision)}`);
680
+ console.log(`Installed: ${answer.installed ? `${answer.installed.name} ${revision(answer.installed.revision)}` : "none"}`);
681
+ }
682
+ catch (err) {
683
+ error(describeRecordsFailure(err));
684
+ process.exit(1);
685
+ }
686
+ });
687
+ db3
688
+ .command("inspect")
689
+ .description("Show a db3's room: epochs, log number, floors, writers, the bulk load in progress and checkpoint")
690
+ .argument("<db3-id>", "db3 ID")
691
+ .option("--app <app-id>", "App ID")
692
+ .option("--refused <session-id>", "Print every row that bulk load refused, with its code, instead")
693
+ .option("--limit <n>", "With --refused: rows per page read (1–100)", "100")
694
+ .option("--json", "Output as JSON")
695
+ .action(async (db3Id, options) => {
696
+ await inspectAction(DB3_ROUTES, db3Id, options);
697
+ });
698
+ // ---- Bulk loads, snapshots, export and import (#4889) ----
699
+ // The `documents ingest|ingests|snapshots` verbs' twins over `db3/:id/*`:
700
+ // the same action code (`./documents.ts`), arguments and flags.
701
+ db3
702
+ .command("ingest")
703
+ .description("Bulk-load records into a db3 from a directory")
704
+ .argument("<db3-id>", "db3 ID")
705
+ .requiredOption("--input <dir>", "Directory of <model>.ndjson[.gz] files, or a `db3 export` or `documents export` output")
706
+ .option("--app <app-id>", "App ID")
707
+ .option("--reserve-epoch <when>", "Reserve the load's epoch at session open (open, the default) or at commit")
708
+ .option("--mode <mode>", "Merge the rows (merge, the default), or refresh: also delete every record of the input's models that no row names")
709
+ .option("-y, --yes", "Skip the confirmation prompt")
710
+ .option("--no-wait", "Exit once the session is committed")
711
+ .option("--timeout <seconds>", "Give up waiting after this many seconds")
712
+ .option("--json", "Output as JSON")
713
+ .addHelpText("after", `
714
+ Rows a load refuses are listed by \`primitive db3 inspect <db3-id> --refused <session-id>\`.
715
+ `)
716
+ .action(async (db3Id, options) => {
717
+ await ingestAction(DB3_LOAD_ROUTES, db3Id, options);
718
+ });
719
+ const ingests = db3.command("ingests").description("Inspect or abort a db3's bulk-load sessions");
720
+ ingests
721
+ .command("list")
722
+ .description("List a db3's bulk-load sessions, newest first")
723
+ .argument("<db3-id>", "db3 ID")
724
+ .option("--app <app-id>", "App ID")
725
+ .option("--limit <n>", "Page size (1–100)", "20")
726
+ .option("--cursor <cursor>", "Continue from a previous page's nextCursor")
727
+ .option("--json", "Output as JSON")
728
+ .action(async (db3Id, options) => {
729
+ await listIngestsAction(DB3_LOAD_ROUTES, db3Id, options);
730
+ });
731
+ ingests
732
+ .command("get")
733
+ .description("Show one bulk-load session, its progress and why it stopped")
734
+ .argument("<db3-id>", "db3 ID")
735
+ .argument("<session-id>", "Session ID")
736
+ .option("--app <app-id>", "App ID")
737
+ .option("--json", "Output as JSON")
738
+ .action(async (db3Id, sessionId, options) => {
739
+ await getIngestAction(DB3_LOAD_ROUTES, db3Id, sessionId, options);
740
+ });
741
+ ingests
742
+ .command("abort")
743
+ .description("Abort a bulk-load session and discard what it uploaded")
744
+ .argument("<db3-id>", "db3 ID")
745
+ .argument("<session-id>", "Session ID")
746
+ .option("--app <app-id>", "App ID")
747
+ .option("-y, --yes", "Skip the confirmation prompt")
748
+ .option("--json", "Output as JSON")
749
+ .action(async (db3Id, sessionId, options) => {
750
+ await abortIngestAction(DB3_LOAD_ROUTES, db3Id, sessionId, options);
751
+ });
752
+ const snapshots = db3.command("snapshots").description("Inspect or start a db3's segment exports");
753
+ snapshots
754
+ .command("list")
755
+ .description("List a db3's segment exports, newest first")
756
+ .argument("<db3-id>", "db3 ID")
757
+ .option("--app <app-id>", "App ID")
758
+ .option("--limit <n>", "Page size (1–100)", "20")
759
+ .option("--cursor <cursor>", "Continue from a previous page's nextCursor")
760
+ .option("--json", "Output as JSON")
761
+ .action(async (db3Id, options) => {
762
+ await listSnapshotsAction(DB3_LOAD_ROUTES, db3Id, options);
763
+ });
764
+ snapshots
765
+ .command("get")
766
+ .description("Show one segment export: its state, log number, rows and chunks")
767
+ .argument("<db3-id>", "db3 ID")
768
+ .argument("<segment-id>", "Segment ID")
769
+ .option("--app <app-id>", "App ID")
770
+ .option("--json", "Output as JSON")
771
+ .action(async (db3Id, segmentId, options) => {
772
+ await getSnapshotAction(DB3_LOAD_ROUTES, db3Id, segmentId, options);
773
+ });
774
+ snapshots
775
+ .command("build")
776
+ .description("Start a segment export of a db3's records now")
777
+ .argument("<db3-id>", "db3 ID")
778
+ .option("--app <app-id>", "App ID")
779
+ .option("--wait", "Poll until the segment is complete or failed")
780
+ .option("--timeout <seconds>", "Give up waiting after this many seconds")
781
+ .option("--json", "Output as JSON")
782
+ .action(async (db3Id, options) => {
783
+ await buildSnapshotAction(DB3_LOAD_ROUTES, db3Id, options);
784
+ });
785
+ db3
786
+ .command("export")
787
+ .description("Export a db3 to a directory: its rows, type, declaration and blobs")
788
+ .argument("<db3-id>", "db3 ID")
789
+ .option("--app <app-id>", "App ID")
790
+ .option("--output <dir>", "Directory to write (default ./primitive-export/db3/<db3-id>)")
791
+ .option("--no-blobs", "Leave the blobs out")
792
+ .option("--json", "Output as JSON")
793
+ .addHelpText("after", `
794
+ The directory holds db3.json (the db3's id, title, tags, type and revision,
795
+ its declaration and registered indexes, and the log number the rows are at),
796
+ the rows under snapshot/, chain.json and the blobs under blobs/. It holds no
797
+ grant, custody, sync state or alias. \`primitive db3 import\` loads it.
798
+ `)
799
+ .action(async (db3Id, options) => {
800
+ const resolvedAppId = resolveAppId(undefined, options);
801
+ const dir = path.resolve(options.output ?? path.join("primitive-export", "db3", db3Id));
802
+ let code = 0;
803
+ try {
804
+ const exported = await exportDb3(new ApiClient(), resolvedAppId, db3Id, dir, {
805
+ blobs: options.blobs !== false,
806
+ onProgress: (line) => info(line),
807
+ });
808
+ if (options.json) {
809
+ json({ id: db3Id, exportPath: dir, rows: exported.rows, blobs: exported.blobs, type: exported.manifest.type, lsn: exported.manifest.lsn });
810
+ }
811
+ else {
812
+ success(`Exported db3 ${db3Id} (${exported.manifest.title || "untitled"}) to ${dir}`);
813
+ printResult("Rows", exported.rows);
814
+ printResult("Blobs", options.blobs === false ? "left out" : exported.blobs);
815
+ printResult("Type", exported.manifest.type?.name ?? "none");
816
+ printResult("Log number", exported.manifest.lsn);
817
+ }
818
+ }
819
+ catch (err) {
820
+ error(err?.statusCode ? describeRecordsFailure(err) : err?.message ?? String(err));
821
+ code = 1;
822
+ }
823
+ await flushOutput();
824
+ process.exit(code);
825
+ });
826
+ db3
827
+ .command("import")
828
+ .description("Import a `db3 export` directory: a new db3 of its type, or --into an existing one")
829
+ .argument("<path>", "The export's directory")
830
+ .option("--app <app-id>", "App ID")
831
+ .option("--into <db3-id>", "Load into this db3 instead of creating one (of the same type and declaration)")
832
+ .option("--keep-id", "Create the db3 under the export's id (an app owner or admin; the id must be free in this app)")
833
+ .option("--title <title>", "The new db3's title (default: the export's)")
834
+ .option("--type <name>", "The db3 type to create it with (default: the export's)")
835
+ .option("--untyped", "Load into an untyped db3, registering the export's indexes and uniques first")
836
+ .option("--no-blobs", "Leave the blobs out")
837
+ .option("-y, --yes", "Skip the confirmation prompt (--into)")
838
+ .option("--json", "Output as JSON")
839
+ .addHelpText("after", `
840
+ Every check runs before anything is written: the type must be one the app
841
+ has (primitive db3-types push), with the export's declaration; an --into
842
+ target must be of the export's type and declare its models alike; and the
843
+ blobs keep their ids, so the exported db3 must be gone from the app (or
844
+ import into another app, or pass --no-blobs). A load that refuses a row exits
845
+ 1 naming \`primitive db3 inspect <db3-id> --refused <session-id>\`.
846
+
847
+ --keep-id creates the db3 under the export's id, so what stored that id still
848
+ finds it: the id must be free in this app (delete the exported db3 first, or
849
+ import into another app). Without it the import gets a new id.
850
+ `)
851
+ .action(async (dir, options) => {
852
+ const code = await importAction(dir, options);
853
+ await flushOutput();
854
+ process.exit(code);
855
+ });
856
+ // ---- Lifecycle (#4804) ----
857
+ db3
858
+ .command("create")
859
+ .description("Create a db3")
860
+ .argument("<title>", "db3 title")
861
+ .option("--type <name>", "A db3 type of the app: its current revision is installed before the db3 answers")
862
+ .option("--sync <on|off>", "off: no client ever opens the db3 over a socket (app owners and admins only)")
863
+ .option("--custodian <custodian>", '"app" or "user:<user-id>" (a member of the app)')
864
+ .option("--app <app-id>", "App ID")
865
+ .option("--json", "Output as JSON")
866
+ .addHelpText("after", `
867
+ Custody:
868
+ A member's token creates a db3 the member holds. An admin token's create is
869
+ held by the app, which no member owns, unless --custodian names a member.
870
+ `)
871
+ .action(async (title, options) => {
872
+ const sync = options.sync === undefined ? undefined : parseOnOff(options.sync, "--sync");
873
+ const custodian = options.custodian === undefined ? undefined : parseCustodianOrExit(options.custodian, "--custodian");
874
+ const resolvedAppId = resolveAppId(undefined, options);
875
+ try {
876
+ const created = await new ApiClient().createDb3(resolvedAppId, {
877
+ title,
878
+ ...(options.type !== undefined ? { type: options.type } : {}),
879
+ ...(sync !== undefined ? { sync } : {}),
880
+ ...(custodian !== undefined ? { custodian } : {}),
881
+ });
882
+ if (options.json) {
883
+ json(created);
884
+ return;
885
+ }
886
+ success("db3 created.");
887
+ printDb3(created);
888
+ }
889
+ catch (err) {
890
+ fail(err);
891
+ }
892
+ });
893
+ db3
894
+ .command("get")
895
+ .description("Show a db3, and the caller's access to it")
896
+ .argument("<db3-id>", "db3 ID")
897
+ .option("--app <app-id>", "App ID")
898
+ .option("--json", "Output as JSON")
899
+ .action(async (db3Id, options) => {
900
+ const resolvedAppId = resolveAppId(undefined, options);
901
+ try {
902
+ const row = await new ApiClient().getDb3(resolvedAppId, db3Id);
903
+ if (options.json) {
904
+ json(row);
905
+ return;
906
+ }
907
+ printDb3(row);
908
+ printResult("Created By", row.createdBy);
909
+ printResult("Created", formatDate(row.createdAt));
910
+ printResult("Modified", formatDate(row.modifiedAt));
911
+ const tags = displayTags(row.tags);
912
+ if (tags.length > 0)
913
+ printResult("Tags", tags.join(", "));
914
+ if (row.permission)
915
+ printResult("Your Permission", row.permission);
916
+ if (row.accessSource)
917
+ printResult("Access Source", row.accessSource);
918
+ }
919
+ catch (err) {
920
+ fail(err);
921
+ }
922
+ });
923
+ db3
924
+ .command("update")
925
+ .description("Rename a db3")
926
+ .argument("<db3-id>", "db3 ID")
927
+ .requiredOption("--title <title>", "The db3's new title (at most 255 characters; stored trimmed)")
928
+ .option("--app <app-id>", "App ID")
929
+ .option("--json", "Output as JSON")
930
+ .action(async (db3Id, options) => {
931
+ const resolvedAppId = resolveAppId(undefined, options);
932
+ try {
933
+ const updated = await new ApiClient().updateDb3(resolvedAppId, db3Id, { title: options.title });
934
+ if (options.json) {
935
+ json(updated);
936
+ return;
937
+ }
938
+ success("db3 updated.");
939
+ printDb3(updated);
940
+ }
941
+ catch (err) {
942
+ fail(err);
943
+ }
944
+ });
945
+ db3
946
+ .command("list")
947
+ .description("List one custodian's db3s, oldest first, or every db3 a user reaches: held, shared with them, then app access")
948
+ .option("--custodian <custodian>", '"app" or "user:<user-id>"')
949
+ .option("--user-id <user-id>", "List every db3 this user reaches, one row per way, sync-off db3s included")
950
+ .option("--via <ways>", "With --user-id: some of held, shared and app, comma-separated")
951
+ .option("--app <app-id>", "App ID")
952
+ .addOption(pageLimitOption())
953
+ .addOption(pageCursorOption())
954
+ .option("--json", "Output as JSON")
955
+ .allowExcessArguments(false)
956
+ .action(async (options) => {
957
+ if ((options.custodian === undefined) === (options.userId === undefined)) {
958
+ refuseList("db3 list takes exactly one of --custodian and --user-id.");
959
+ }
960
+ if (options.userId === undefined) {
961
+ if (options.via !== undefined)
962
+ refuseList("--via is valid only with --user-id.");
963
+ return listByCustodian(options);
964
+ }
965
+ const userId = options.userId;
966
+ if (!userId.trim() || userId.startsWith("user:"))
967
+ refuseList("--user-id needs a bare user id.");
968
+ const via = options.via === undefined ? undefined : parseVia(options.via);
969
+ const limit = parsePageLimit(options.limit);
970
+ const resolvedAppId = resolveAppId(undefined, options);
971
+ try {
972
+ const page = normalizeCliListEnvelope(await new ApiClient().listDb3ForUser(resolvedAppId, userId, {
973
+ ...(via ? { via } : {}),
974
+ ...(limit !== undefined ? { limit } : {}),
975
+ ...(options.cursor ? { cursor: options.cursor } : {}),
976
+ }));
977
+ if (options.json) {
978
+ json(page);
979
+ return;
980
+ }
981
+ if (page.items.length === 0) {
982
+ printEmptyPage(page, "db3s");
983
+ return;
984
+ }
985
+ const rows = page.items.map((row) => ({
986
+ id: row.id,
987
+ title: row.title ?? "",
988
+ via: row.via,
989
+ permission: row.permission ?? "none",
990
+ custodian: row.custodian ?? "none",
991
+ sync: row.sync === false ? "off" : "on",
992
+ type: row.type ?? "none",
993
+ grantedAt: row.grantedAt,
994
+ }));
995
+ console.log(formatTable(rows, USER_DB3_TABLE_FIELDS.map((key) => ({
996
+ header: USER_DB3_TABLE_HEADERS[key],
997
+ key,
998
+ ...(key === "title" ? { flex: true } : {}),
999
+ ...(key === "grantedAt" ? { format: (value) => (value ? formatDate(value) : "—") } : {}),
1000
+ }))));
1001
+ printPageHint(page);
1002
+ }
1003
+ catch (err) {
1004
+ fail(err);
1005
+ }
1006
+ });
1007
+ /** `db3 list --custodian`: one custodian's db3s from the admin API (#4800). */
1008
+ async function listByCustodian(options) {
1009
+ const limit = parsePageLimit(options.limit);
1010
+ const custodian = parseCustodianOrExit(options.custodian, "--custodian");
1011
+ const resolvedAppId = resolveAppId(undefined, options);
1012
+ try {
1013
+ const page = normalizeCliListEnvelope(await new ApiClient().listDb3ByCustodian(resolvedAppId, custodian, {
1014
+ ...(limit !== undefined ? { limit } : {}),
1015
+ ...(options.cursor ? { cursor: options.cursor } : {}),
1016
+ }));
1017
+ if (options.json) {
1018
+ json(page);
1019
+ return;
1020
+ }
1021
+ if (page.items.length === 0) {
1022
+ printEmptyPage(page, "db3s");
1023
+ return;
1024
+ }
1025
+ const rows = page.items.map((row) => ({
1026
+ id: row.id,
1027
+ title: row.title ?? "",
1028
+ custodian: row.custodian ?? "none",
1029
+ sync: row.sync === false ? "off" : "on",
1030
+ type: row.type ?? "none",
1031
+ createdAt: row.createdAt,
1032
+ }));
1033
+ console.log(formatTable(rows, [
1034
+ { header: "ID", key: "id" },
1035
+ { header: "TITLE", key: "title", flex: true },
1036
+ { header: "CUSTODIAN", key: "custodian" },
1037
+ { header: "SYNC", key: "sync" },
1038
+ { header: "TYPE", key: "type" },
1039
+ { header: "CREATED", key: "createdAt", format: formatDate },
1040
+ ]));
1041
+ printPageHint(page);
1042
+ }
1043
+ catch (err) {
1044
+ fail(err);
1045
+ }
1046
+ }
1047
+ db3
1048
+ .command("delete")
1049
+ .description("Delete a db3 and all its data (records, blobs, aliases, permissions)")
1050
+ .argument("<db3-id>", "db3 ID")
1051
+ .option("--app <app-id>", "App ID")
1052
+ .option("-y, --yes", "Skip confirmation prompt")
1053
+ .option("--json", "Output as JSON")
1054
+ .action(async (db3Id, options) => {
1055
+ const resolvedAppId = resolveAppId(undefined, options);
1056
+ if (!options.yes) {
1057
+ let confirmed;
1058
+ try {
1059
+ confirmed = await confirmPrompt(`Delete db3 ${db3Id}? This permanently deletes its records, blobs, aliases and permissions.`);
1060
+ }
1061
+ catch (err) {
1062
+ error(err.message);
1063
+ process.exit(1);
1064
+ }
1065
+ if (!confirmed) {
1066
+ info("Cancelled.");
1067
+ return;
1068
+ }
1069
+ }
1070
+ try {
1071
+ const answer = await new ApiClient().deleteDb3(resolvedAppId, db3Id);
1072
+ if (options.json) {
1073
+ json(answer);
1074
+ return;
1075
+ }
1076
+ success(`db3 ${db3Id} deleted.`);
1077
+ }
1078
+ catch (err) {
1079
+ fail(err);
1080
+ }
1081
+ });
1082
+ db3
1083
+ .command("stats")
1084
+ .description("Show a db3's record/model/blob counts and size")
1085
+ .argument("<db3-id>", "db3 ID")
1086
+ .option("--app <app-id>", "App ID")
1087
+ .option("--json", "Output as JSON")
1088
+ .action(async (db3Id, options) => {
1089
+ await statsAction(DB3_ROUTES, db3Id, options);
1090
+ });
1091
+ // ---- Sync (#4799, #4804) ----
1092
+ const sync = db3.command("sync").description("Show or change whether a db3 is synced");
1093
+ sync
1094
+ .command("get")
1095
+ .description("Print on or off: whether clients open the db3 over a socket")
1096
+ .argument("<db3-id>", "db3 ID")
1097
+ .option("--app <app-id>", "App ID")
1098
+ .option("--json", "Output as JSON")
1099
+ .action(async (db3Id, options) => {
1100
+ const resolvedAppId = resolveAppId(undefined, options);
1101
+ try {
1102
+ const answer = await new ApiClient().getDb3Sync(resolvedAppId, db3Id);
1103
+ if (options.json) {
1104
+ json(answer);
1105
+ return;
1106
+ }
1107
+ console.log(answer.sync ? "on" : "off");
1108
+ }
1109
+ catch (err) {
1110
+ fail(err);
1111
+ }
1112
+ });
1113
+ sync
1114
+ .command("set")
1115
+ .description("Turn a db3's sync on or off (app owners and admins only)")
1116
+ .argument("<db3-id>", "db3 ID")
1117
+ .argument("<on|off>", "on or off")
1118
+ .option("--app <app-id>", "App ID")
1119
+ .option("--json", "Output as JSON")
1120
+ .action(async (db3Id, state, options) => {
1121
+ const on = parseOnOff(state, "The sync state");
1122
+ const resolvedAppId = resolveAppId(undefined, options);
1123
+ try {
1124
+ const answer = await new ApiClient().setDb3Sync(resolvedAppId, db3Id, on);
1125
+ if (options.json) {
1126
+ json(answer);
1127
+ return;
1128
+ }
1129
+ success(answer.changed ? `Sync is ${on ? "on" : "off"} for ${db3Id}.` : `Sync was already ${on ? "on" : "off"} for ${db3Id}.`);
1130
+ }
1131
+ catch (err) {
1132
+ fail(err);
1133
+ }
1134
+ });
1135
+ // ---- App access (#4801, #4804) ----
1136
+ const appAccess = db3.command("app-access").description("Show or change the access every user of the app holds on a db3");
1137
+ appAccess
1138
+ .command("get")
1139
+ .description("Print reader, read-write or none")
1140
+ .argument("<db3-id>", "db3 ID")
1141
+ .option("--app <app-id>", "App ID")
1142
+ .option("--json", "Output as JSON")
1143
+ .action(async (db3Id, options) => {
1144
+ const resolvedAppId = resolveAppId(undefined, options);
1145
+ try {
1146
+ const answer = await new ApiClient().getDb3AppAccess(resolvedAppId, db3Id);
1147
+ if (options.json) {
1148
+ json(answer);
1149
+ return;
1150
+ }
1151
+ console.log(answer.level ?? "none");
1152
+ }
1153
+ catch (err) {
1154
+ fail(err);
1155
+ }
1156
+ });
1157
+ appAccess
1158
+ .command("set")
1159
+ .description("Grant the db3 to every user of the app, or remove the grant with none (app owners and admins only)")
1160
+ .argument("<db3-id>", "db3 ID")
1161
+ .argument("<level>", "reader, read-write or none")
1162
+ .option("--app <app-id>", "App ID")
1163
+ .option("--json", "Output as JSON")
1164
+ .action(async (db3Id, level, options) => {
1165
+ if (!["reader", "read-write", "none"].includes(level)) {
1166
+ error('The level must be "reader", "read-write" or "none".');
1167
+ process.exit(1);
1168
+ }
1169
+ const resolvedAppId = resolveAppId(undefined, options);
1170
+ try {
1171
+ const answer = await new ApiClient().setDb3AppAccess(resolvedAppId, db3Id, level === "none" ? null : level);
1172
+ if (options.json) {
1173
+ json(answer);
1174
+ return;
1175
+ }
1176
+ success(`App access on ${db3Id}: ${answer.level ?? "none"}${answer.changed ? "" : " (unchanged)"}.`);
1177
+ }
1178
+ catch (err) {
1179
+ fail(err);
1180
+ }
1181
+ });
1182
+ // ---- Custody (#4800, #4804): through the admin API ----
1183
+ db3
1184
+ .command("transfer")
1185
+ .description("Transfer a db3 to another user or to the app")
1186
+ .argument("<db3-id>", "db3 ID")
1187
+ .argument("<custodian>", '"user:<user-id>" (a member of the app) or "app"')
1188
+ .option("--app <app-id>", "App ID")
1189
+ .option("--json", "Output as JSON")
1190
+ .allowExcessArguments(false)
1191
+ .addHelpText("after", `
1192
+ The custodian and the owner row move together: a user custodian holds the
1193
+ owner row and the previous owner keeps read-write; moving to the app deletes
1194
+ every owner row. No other grant changes.
1195
+ `)
1196
+ .action(async (db3Id, custodianArg, options) => {
1197
+ const to = parseCustodianOrExit(custodianArg, "custodian");
1198
+ const resolvedAppId = resolveAppId(undefined, options);
1199
+ try {
1200
+ const answer = await new ApiClient().transferDb3(resolvedAppId, db3Id, to);
1201
+ if (options.json) {
1202
+ json(answer);
1203
+ return;
1204
+ }
1205
+ success(`db3 ${db3Id} transferred.`);
1206
+ printResult("Custodian", answer.custodian);
1207
+ }
1208
+ catch (err) {
1209
+ fail(err);
1210
+ }
1211
+ });
1212
+ const ownerRow = db3.command("owner-row").description("Remove or restore the owner row of the user who holds a db3");
1213
+ ownerRow
1214
+ .command("set")
1215
+ .description("present restores the custodian user's owner row, absent removes it; the custodian stays")
1216
+ .argument("<db3-id>", "db3 ID")
1217
+ .argument("<present|absent>", "present or absent")
1218
+ .option("--app <app-id>", "App ID")
1219
+ .option("--json", "Output as JSON")
1220
+ .action(async (db3Id, state, options) => {
1221
+ if (state !== "present" && state !== "absent") {
1222
+ error('The owner row must be "present" or "absent".');
1223
+ process.exit(1);
1224
+ }
1225
+ const resolvedAppId = resolveAppId(undefined, options);
1226
+ try {
1227
+ const answer = await new ApiClient().setDb3OwnerRow(resolvedAppId, db3Id, state === "present");
1228
+ if (options.json) {
1229
+ json(answer);
1230
+ return;
1231
+ }
1232
+ printResult("Custodian", answer.custodian);
1233
+ printResult("Owner row", answer.ownerRow ? "present" : "absent");
1234
+ printResult("Changed", answer.changed ? "yes" : "no");
1235
+ }
1236
+ catch (err) {
1237
+ fail(err);
1238
+ }
1239
+ });
1240
+ }
1241
+ /** What to do about a refused create of the import's db3 (#4921), after the refusal itself. */
1242
+ function createRefusalAdvice(code) {
1243
+ switch (code) {
1244
+ case "DB3_ID_EXISTS":
1245
+ return " This app holds the export's id: delete that db3 first, import into another app, or import without --keep-id.";
1246
+ case "DB3_CREATE_IN_PROGRESS":
1247
+ return " Another create of this id is running: try again shortly.";
1248
+ case "DB3_ID_INVALID":
1249
+ return " The manifest's id is not a ULID this server accepts: import without --keep-id.";
1250
+ case "DB3_ID_NOT_ALLOWED":
1251
+ return " Keeping an id needs an app owner or admin: log in as one, or import without --keep-id.";
1252
+ default:
1253
+ return "";
1254
+ }
1255
+ }
1256
+ /** `db3 import`: the reads, the plan, then the writes; answers the exit code. */
1257
+ async function importAction(dir, options) {
1258
+ const resolvedAppId = resolveAppId(undefined, options);
1259
+ const client = new ApiClient();
1260
+ const root = path.resolve(dir);
1261
+ try {
1262
+ const manifest = readDb3Manifest(root);
1263
+ if (!manifest) {
1264
+ error(`${root} holds no db3.json, so it is not a \`db3 export\` directory. ` +
1265
+ "Load a directory of rows into an existing db3 with `primitive db3 ingest <db3-id> --input <dir>`.");
1266
+ return 1;
1267
+ }
1268
+ const flags = {
1269
+ ...(options.into ? { into: String(options.into) } : {}),
1270
+ ...(options.title !== undefined ? { title: String(options.title) } : {}),
1271
+ ...(options.type !== undefined ? { type: String(options.type) } : {}),
1272
+ untyped: Boolean(options.untyped),
1273
+ noBlobs: options.blobs === false,
1274
+ keepId: Boolean(options.keepId),
1275
+ };
1276
+ if (flags.keepId && flags.into) {
1277
+ const refused = planDb3Import(manifest, flags, { blobCount: 0 });
1278
+ if ("refusal" in refused)
1279
+ error(refused.refusal);
1280
+ return 1;
1281
+ }
1282
+ // Every read before any write.
1283
+ const blobs = flags.noBlobs ? [] : readExportedBlobs(root);
1284
+ const facts = { blobCount: blobs.length };
1285
+ const named = resolvedTypeName(manifest, flags);
1286
+ if (named && !flags.untyped) {
1287
+ try {
1288
+ facts.type = await client.getDb3TypeConfig(resolvedAppId, named);
1289
+ }
1290
+ catch (err) {
1291
+ if (err?.statusCode !== 404)
1292
+ throw err;
1293
+ facts.type = null;
1294
+ }
1295
+ }
1296
+ if (flags.into) {
1297
+ const row = await client.getDb3(resolvedAppId, flags.into);
1298
+ let declaredModels = [];
1299
+ if (row?.type) {
1300
+ const targetType = facts.type?.name === row.type ? facts.type : await client.getDb3TypeConfig(resolvedAppId, String(row.type));
1301
+ declaredModels = declaredModelNames(targetType?.schema);
1302
+ }
1303
+ const declaration = declarationOfSchemaAnswer(await client.getDb3Schema(resolvedAppId, flags.into), { declaredModels });
1304
+ const listed = await client.listDb3Indexes(resolvedAppId, flags.into);
1305
+ facts.target = { row, declaration, indexes: listed?.indexes ?? [] };
1306
+ }
1307
+ // One read of the source's id, for the blobs and for --keep-id alike.
1308
+ if (blobs.length > 0 || flags.keepId) {
1309
+ try {
1310
+ await client.getDb3(resolvedAppId, manifest.id);
1311
+ facts.sourceExists = true;
1312
+ }
1313
+ catch (err) {
1314
+ if (err?.statusCode !== 404)
1315
+ throw err;
1316
+ facts.sourceExists = false;
1317
+ }
1318
+ }
1319
+ const plan = planDb3Import(manifest, flags, facts);
1320
+ if ("refusal" in plan) {
1321
+ error(plan.refusal);
1322
+ for (const line of plan.lines ?? [])
1323
+ console.error(` ${line}`);
1324
+ return 1;
1325
+ }
1326
+ for (const note of plan.notes)
1327
+ info(note);
1328
+ let db3Id;
1329
+ let created = false;
1330
+ if (plan.into) {
1331
+ if (!options.yes) {
1332
+ let confirmed;
1333
+ try {
1334
+ confirmed = await confirmPrompt(`Load the export's rows into db3 ${plan.into}? Rows with an id it already holds are replaced.`);
1335
+ }
1336
+ catch (err) {
1337
+ error(err.message);
1338
+ return 1;
1339
+ }
1340
+ if (!confirmed) {
1341
+ info("Nothing was written.");
1342
+ return 1;
1343
+ }
1344
+ }
1345
+ db3Id = plan.into;
1346
+ }
1347
+ else {
1348
+ let row;
1349
+ try {
1350
+ row = await client.createDb3(resolvedAppId, plan.create);
1351
+ }
1352
+ catch (err) {
1353
+ error(`${describeRecordsFailure(err)}${createRefusalAdvice(err?.code)} Nothing was written.`);
1354
+ return 1;
1355
+ }
1356
+ db3Id = row.id;
1357
+ created = true;
1358
+ if (!options.json)
1359
+ success(`Created db3 ${db3Id}${plan.typeName ? ` of type ${plan.typeName}` : ""}.`);
1360
+ }
1361
+ let register = plan.register;
1362
+ if (created && plan.typeName && register.length > 0) {
1363
+ // A typed db3 has its type's indexes from the create: register only what they leave out.
1364
+ const pending = pendingRegistrations(register, (await client.listDb3Indexes(resolvedAppId, db3Id))?.indexes ?? []);
1365
+ if (pending.conflicts.length) {
1366
+ error(`The export's indexes clash with type ${plan.typeName}'s by name; db3 ${db3Id} was created and holds no rows.`);
1367
+ for (const line of pending.conflicts)
1368
+ console.error(` ${line}`);
1369
+ return 1;
1370
+ }
1371
+ register = pending.register;
1372
+ }
1373
+ for (const registration of register) {
1374
+ try {
1375
+ await client.registerDb3Index(resolvedAppId, db3Id, registration);
1376
+ }
1377
+ catch (err) {
1378
+ // A refused registration prints in the CLI's words (#5890), as `indexes register` prints it.
1379
+ if (!err?.statusCode || typeof err?.message !== "string")
1380
+ throw err;
1381
+ const reworded = { message: db3IndexRefusalSentence(err.message, err.code, "--set-elements"), code: err.code, statusCode: err.statusCode, status: err.status };
1382
+ error(describeRecordsFailure(reworded));
1383
+ return 1;
1384
+ }
1385
+ }
1386
+ const outcome = await loadDb3Rows(client, resolvedAppId, db3Id, root, (line) => info(line));
1387
+ const session = outcome?.session ?? null;
1388
+ if (outcome && outcome.exitCode !== 0) {
1389
+ if (outcome.message)
1390
+ error(outcome.message);
1391
+ if (options.json)
1392
+ json({ id: db3Id, created, keptId: flags.keepId, session, exitCode: outcome.exitCode });
1393
+ return 1;
1394
+ }
1395
+ const refusedRows = Number(session?.refusedRows ?? 0);
1396
+ let blobsUploaded = 0;
1397
+ if (plan.blobs) {
1398
+ for (const blob of blobs) {
1399
+ const data = fs.readFileSync(path.join(root, "blobs", `${blob.blobId}.bin`));
1400
+ try {
1401
+ await client.uploadDb3Blob(resolvedAppId, db3Id, blob.blobId, data, {
1402
+ filename: blob.filename,
1403
+ contentType: blob.contentType,
1404
+ sha256: blob.sha256,
1405
+ });
1406
+ }
1407
+ catch (err) {
1408
+ error(`Blob ${blob.blobId} could not be uploaded under its id: ${describeRecordsFailure(err)}. The rows are loaded into db3 ${db3Id}.`);
1409
+ return 1;
1410
+ }
1411
+ blobsUploaded++;
1412
+ }
1413
+ }
1414
+ if (options.json) {
1415
+ json({
1416
+ id: db3Id,
1417
+ created,
1418
+ keptId: flags.keepId,
1419
+ type: plan.typeName,
1420
+ registered: register.length,
1421
+ rows: session?.rows ?? 0,
1422
+ refusedRows,
1423
+ session,
1424
+ blobs: blobsUploaded,
1425
+ });
1426
+ }
1427
+ else {
1428
+ printResult("db3", db3Id);
1429
+ printResult("Rows", session?.rows ?? 0);
1430
+ printResult("Indexes registered", register.length);
1431
+ printResult("Blobs", plan.blobs ? blobsUploaded : "none");
1432
+ }
1433
+ if (refusedRows > 0) {
1434
+ error(`The load refused ${refusedRows} row(s). List them with \`primitive db3 inspect ${db3Id} --refused ${session?.sessionId}\`.`);
1435
+ return 1;
1436
+ }
1437
+ return 0;
1438
+ }
1439
+ catch (err) {
1440
+ error(err?.statusCode ? describeRecordsFailure(err) : err?.message ?? String(err));
1441
+ return 1;
1442
+ }
1443
+ }
1444
+ //# sourceMappingURL=db3.js.map