primitive-admin 1.2.0-alpha.9 → 1.3.0-alpha.1

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 (590) hide show
  1. package/README.md +303 -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 +170 -50
  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 +42 -0
  40. package/dist/src/commands/db3-types.js +445 -0
  41. package/dist/src/commands/db3-types.js.map +1 -0
  42. package/dist/src/commands/db3.d.ts +38 -0
  43. package/dist/src/commands/db3.js +2053 -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 +1019 -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 +383 -32
  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 +509 -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 +55 -6
  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.d.ts +38 -0
  91. package/dist/src/commands/secrets.js +148 -6
  92. package/dist/src/commands/secrets.js.map +1 -1
  93. package/dist/src/commands/sessions.js +2 -0
  94. package/dist/src/commands/sessions.js.map +1 -1
  95. package/dist/src/commands/skill.js +2 -0
  96. package/dist/src/commands/skill.js.map +1 -1
  97. package/dist/src/commands/spent-tokens.d.ts +19 -0
  98. package/dist/src/commands/spent-tokens.js +79 -0
  99. package/dist/src/commands/spent-tokens.js.map +1 -0
  100. package/dist/src/commands/sync-app-settings.d.ts +58 -0
  101. package/dist/src/commands/sync-app-settings.js +119 -2
  102. package/dist/src/commands/sync-app-settings.js.map +1 -1
  103. package/dist/src/commands/sync-schemas.d.ts +202 -0
  104. package/dist/src/commands/sync-schemas.js +629 -0
  105. package/dist/src/commands/sync-schemas.js.map +1 -0
  106. package/dist/src/commands/sync-user-properties.d.ts +118 -0
  107. package/dist/src/commands/sync-user-properties.js +276 -0
  108. package/dist/src/commands/sync-user-properties.js.map +1 -0
  109. package/dist/src/commands/sync.d.ts +578 -546
  110. package/dist/src/commands/sync.js +3516 -5134
  111. package/dist/src/commands/sync.js.map +1 -1
  112. package/dist/src/commands/tokens.js +5 -3
  113. package/dist/src/commands/tokens.js.map +1 -1
  114. package/dist/src/commands/transitions.d.ts +54 -0
  115. package/dist/src/commands/transitions.js +418 -0
  116. package/dist/src/commands/transitions.js.map +1 -0
  117. package/dist/src/commands/usage.d.ts +42 -0
  118. package/dist/src/commands/usage.js +397 -0
  119. package/dist/src/commands/usage.js.map +1 -0
  120. package/dist/src/commands/user-properties.d.ts +14 -0
  121. package/dist/src/commands/user-properties.js +79 -0
  122. package/dist/src/commands/user-properties.js.map +1 -0
  123. package/dist/src/commands/users.js +951 -18
  124. package/dist/src/commands/users.js.map +1 -1
  125. package/dist/src/commands/vars.js +2 -0
  126. package/dist/src/commands/vars.js.map +1 -1
  127. package/dist/src/commands/waitlist.js +39 -4
  128. package/dist/src/commands/waitlist.js.map +1 -1
  129. package/dist/src/commands/workflows.d.ts +5 -83
  130. package/dist/src/commands/workflows.js +57 -2282
  131. package/dist/src/commands/workflows.js.map +1 -1
  132. package/dist/src/lib/analytics-query.d.ts +58 -0
  133. package/dist/src/lib/analytics-query.js +134 -0
  134. package/dist/src/lib/analytics-query.js.map +1 -0
  135. package/dist/src/lib/api-client.d.ts +1976 -431
  136. package/dist/src/lib/api-client.js +1095 -550
  137. package/dist/src/lib/api-client.js.map +1 -1
  138. package/dist/src/lib/app-settings-descriptor.d.ts +14 -2
  139. package/dist/src/lib/app-settings-descriptor.js +55 -1
  140. package/dist/src/lib/app-settings-descriptor.js.map +1 -1
  141. package/dist/src/lib/auth-fixtures.d.ts +44 -0
  142. package/dist/src/lib/auth-fixtures.js +61 -0
  143. package/dist/src/lib/auth-fixtures.js.map +1 -0
  144. package/dist/src/lib/auth-flow.d.ts +47 -1
  145. package/dist/src/lib/auth-flow.js +451 -14
  146. package/dist/src/lib/auth-flow.js.map +1 -1
  147. package/dist/src/lib/block-layout.d.ts +12 -23
  148. package/dist/src/lib/block-layout.js +26 -92
  149. package/dist/src/lib/block-layout.js.map +1 -1
  150. package/dist/src/lib/block-selector.d.ts +8 -14
  151. package/dist/src/lib/block-selector.js +8 -19
  152. package/dist/src/lib/block-selector.js.map +1 -1
  153. package/dist/src/lib/child-apps-local.d.ts +3 -1
  154. package/dist/src/lib/child-apps-local.js +9 -1
  155. package/dist/src/lib/child-apps-local.js.map +1 -1
  156. package/dist/src/lib/cli-manifest.d.ts +9 -0
  157. package/dist/src/lib/cli-manifest.js +10 -1
  158. package/dist/src/lib/cli-manifest.js.map +1 -1
  159. package/dist/src/lib/cli-version.d.ts +14 -0
  160. package/dist/src/lib/cli-version.js +38 -0
  161. package/dist/src/lib/cli-version.js.map +1 -0
  162. package/dist/src/lib/codegen-shared/prettierStable.d.ts +41 -0
  163. package/dist/src/lib/codegen-shared/prettierStable.js +146 -24
  164. package/dist/src/lib/codegen-shared/prettierStable.js.map +1 -1
  165. package/dist/src/lib/collection-export.d.ts +76 -15
  166. package/dist/src/lib/collection-export.js +116 -23
  167. package/dist/src/lib/collection-export.js.map +1 -1
  168. package/dist/src/lib/collection-principal.d.ts +22 -0
  169. package/dist/src/lib/collection-principal.js +35 -0
  170. package/dist/src/lib/collection-principal.js.map +1 -0
  171. package/dist/src/lib/command-groups.d.ts +30 -0
  172. package/dist/src/lib/command-groups.js +111 -0
  173. package/dist/src/lib/command-groups.js.map +1 -0
  174. package/dist/src/lib/command-status.d.ts +147 -0
  175. package/dist/src/lib/command-status.js +266 -0
  176. package/dist/src/lib/command-status.js.map +1 -0
  177. package/dist/src/lib/config-object-descriptor.d.ts +9 -22
  178. package/dist/src/lib/config-object-descriptor.js +113 -277
  179. package/dist/src/lib/config-object-descriptor.js.map +1 -1
  180. package/dist/src/lib/config-surface.d.ts +3 -7
  181. package/dist/src/lib/config-surface.js +9 -13
  182. package/dist/src/lib/config-surface.js.map +1 -1
  183. package/dist/src/lib/config-toml.d.ts +11 -2
  184. package/dist/src/lib/config-toml.js +25 -2
  185. package/dist/src/lib/config-toml.js.map +1 -1
  186. package/dist/src/lib/credentials-home.d.ts +7 -0
  187. package/dist/src/lib/credentials-home.js +45 -10
  188. package/dist/src/lib/credentials-home.js.map +1 -1
  189. package/dist/src/lib/credentials-lock.d.ts +14 -6
  190. package/dist/src/lib/credentials-lock.js +90 -10
  191. package/dist/src/lib/credentials-lock.js.map +1 -1
  192. package/dist/src/lib/credentials-store.d.ts +142 -70
  193. package/dist/src/lib/credentials-store.js +420 -111
  194. package/dist/src/lib/credentials-store.js.map +1 -1
  195. package/dist/src/lib/custodian.d.ts +8 -0
  196. package/dist/src/lib/custodian.js +18 -0
  197. package/dist/src/lib/custodian.js.map +1 -0
  198. package/dist/src/lib/data-input.d.ts +1 -1
  199. package/dist/src/lib/data-input.js +1 -1
  200. package/dist/src/lib/db-codegen/dbTsTypes.d.ts +1 -1
  201. package/dist/src/lib/db-codegen/dbTsTypes.js +3 -0
  202. package/dist/src/lib/db-codegen/dbTsTypes.js.map +1 -1
  203. package/dist/src/lib/db-codegen/dbTypeIR.d.ts +40 -1
  204. package/dist/src/lib/db-codegen/dbTypeIR.js +32 -8
  205. package/dist/src/lib/db-codegen/dbTypeIR.js.map +1 -1
  206. package/dist/src/lib/db-type-records.d.ts +125 -0
  207. package/dist/src/lib/db-type-records.js +237 -0
  208. package/dist/src/lib/db-type-records.js.map +1 -0
  209. package/dist/src/lib/db3-export.d.ts +322 -0
  210. package/dist/src/lib/db3-export.js +767 -0
  211. package/dist/src/lib/db3-export.js.map +1 -0
  212. package/dist/src/lib/db3-index-output.d.ts +116 -0
  213. package/dist/src/lib/db3-index-output.js +223 -0
  214. package/dist/src/lib/db3-index-output.js.map +1 -0
  215. package/dist/src/lib/db3-json-fields.d.ts +49 -0
  216. package/dist/src/lib/db3-json-fields.js +195 -0
  217. package/dist/src/lib/db3-json-fields.js.map +1 -0
  218. package/dist/src/lib/db3-type-archive.d.ts +59 -0
  219. package/dist/src/lib/db3-type-archive.js +95 -0
  220. package/dist/src/lib/db3-type-archive.js.map +1 -0
  221. package/dist/src/lib/db3-type-models.d.ts +148 -0
  222. package/dist/src/lib/db3-type-models.js +583 -0
  223. package/dist/src/lib/db3-type-models.js.map +1 -0
  224. package/dist/src/lib/deprecation.d.ts +2 -2
  225. package/dist/src/lib/deprecation.js +2 -2
  226. package/dist/src/lib/document-export-record-log.d.ts +7 -0
  227. package/dist/src/lib/document-export-record-log.js +9 -0
  228. package/dist/src/lib/document-export-record-log.js.map +1 -1
  229. package/dist/src/lib/document-ingest-artifact.d.ts +19 -0
  230. package/dist/src/lib/document-ingest-artifact.js +55 -6
  231. package/dist/src/lib/document-ingest-artifact.js.map +1 -1
  232. package/dist/src/lib/document-ingest-format2.d.ts +36 -0
  233. package/dist/src/lib/document-ingest-format2.js +78 -0
  234. package/dist/src/lib/document-ingest-format2.js.map +1 -0
  235. package/dist/src/lib/document-ingest-input.d.ts +9 -0
  236. package/dist/src/lib/document-ingest-input.js +28 -1
  237. package/dist/src/lib/document-ingest-input.js.map +1 -1
  238. package/dist/src/lib/document-ingest.d.ts +11 -1
  239. package/dist/src/lib/document-ingest.js +16 -0
  240. package/dist/src/lib/document-ingest.js.map +1 -1
  241. package/dist/src/lib/document-schema-rows.d.ts +42 -0
  242. package/dist/src/lib/document-schema-rows.js +53 -0
  243. package/dist/src/lib/document-schema-rows.js.map +1 -0
  244. package/dist/src/lib/experimental-apis.d.ts +36 -0
  245. package/dist/src/lib/experimental-apis.js +46 -0
  246. package/dist/src/lib/experimental-apis.js.map +1 -0
  247. package/dist/src/lib/file-attachment.d.ts +24 -0
  248. package/dist/src/lib/file-attachment.js +31 -0
  249. package/dist/src/lib/file-attachment.js.map +1 -0
  250. package/dist/src/lib/function-authorize-check.d.ts +142 -0
  251. package/dist/src/lib/function-authorize-check.js +311 -0
  252. package/dist/src/lib/function-authorize-check.js.map +1 -0
  253. package/dist/src/lib/function-authorize-view.d.ts +36 -0
  254. package/dist/src/lib/function-authorize-view.js +110 -0
  255. package/dist/src/lib/function-authorize-view.js.map +1 -0
  256. package/dist/src/lib/function-bundle.d.ts +27 -5
  257. package/dist/src/lib/function-bundle.js +142 -7
  258. package/dist/src/lib/function-bundle.js.map +1 -1
  259. package/dist/src/lib/function-collect.d.ts +112 -12
  260. package/dist/src/lib/function-collect.js +601 -12
  261. package/dist/src/lib/function-collect.js.map +1 -1
  262. package/dist/src/lib/function-db-types.d.ts +65 -11
  263. package/dist/src/lib/function-db-types.js +326 -157
  264. package/dist/src/lib/function-db-types.js.map +1 -1
  265. package/dist/src/lib/function-document-types.d.ts +19 -7
  266. package/dist/src/lib/function-document-types.js +24 -12
  267. package/dist/src/lib/function-document-types.js.map +1 -1
  268. package/dist/src/lib/function-grants-preflight.d.ts +99 -0
  269. package/dist/src/lib/function-grants-preflight.js +154 -2
  270. package/dist/src/lib/function-grants-preflight.js.map +1 -1
  271. package/dist/src/lib/function-lint.d.ts +85 -0
  272. package/dist/src/lib/function-lint.js +442 -0
  273. package/dist/src/lib/function-lint.js.map +1 -0
  274. package/dist/src/lib/function-log-row.js +21 -2
  275. package/dist/src/lib/function-log-row.js.map +1 -1
  276. package/dist/src/lib/function-run.d.ts +13 -21
  277. package/dist/src/lib/function-run.js +14 -27
  278. package/dist/src/lib/function-run.js.map +1 -1
  279. package/dist/src/lib/function-schema-codegen.d.ts +86 -22
  280. package/dist/src/lib/function-schema-codegen.js +194 -88
  281. package/dist/src/lib/function-schema-codegen.js.map +1 -1
  282. package/dist/src/lib/function-schema-refs.d.ts +98 -0
  283. package/dist/src/lib/function-schema-refs.js +177 -0
  284. package/dist/src/lib/function-schema-refs.js.map +1 -0
  285. package/dist/src/lib/function-sync.d.ts +120 -6
  286. package/dist/src/lib/function-sync.js +217 -26
  287. package/dist/src/lib/function-sync.js.map +1 -1
  288. package/dist/src/lib/function-trigger-listing.d.ts +11 -6
  289. package/dist/src/lib/function-trigger-listing.js +32 -11
  290. package/dist/src/lib/function-trigger-listing.js.map +1 -1
  291. package/dist/src/lib/function-typecheck.d.ts +52 -0
  292. package/dist/src/lib/function-typecheck.js +174 -54
  293. package/dist/src/lib/function-typecheck.js.map +1 -1
  294. package/dist/src/lib/function-versions.d.ts +2 -0
  295. package/dist/src/lib/function-versions.js +1 -0
  296. package/dist/src/lib/function-versions.js.map +1 -1
  297. package/dist/src/lib/generated-build-flags.d.ts +13 -0
  298. package/dist/src/lib/generated-build-flags.js +14 -0
  299. package/dist/src/lib/generated-build-flags.js.map +1 -0
  300. package/dist/src/lib/generated-command-status.d.ts +6 -0
  301. package/dist/src/lib/generated-command-status.js +502 -0
  302. package/dist/src/lib/generated-command-status.js.map +1 -0
  303. package/dist/src/lib/generated-config-surfaces.d.ts +804 -140
  304. package/dist/src/lib/generated-config-surfaces.js +2491 -1806
  305. package/dist/src/lib/generated-config-surfaces.js.map +1 -1
  306. package/dist/src/lib/generated-sdk-types.d.ts +1 -1
  307. package/dist/src/lib/generated-sdk-types.js +1 -1
  308. package/dist/src/lib/generated-sdk-types.js.map +1 -1
  309. package/dist/src/lib/hosting-build.d.ts +97 -0
  310. package/dist/src/lib/hosting-build.js +204 -0
  311. package/dist/src/lib/hosting-build.js.map +1 -0
  312. package/dist/src/lib/hosting-client.d.ts +167 -0
  313. package/dist/src/lib/hosting-client.js +340 -0
  314. package/dist/src/lib/hosting-client.js.map +1 -0
  315. package/dist/src/lib/hosting-environments.d.ts +32 -0
  316. package/dist/src/lib/hosting-environments.js +74 -0
  317. package/dist/src/lib/hosting-environments.js.map +1 -0
  318. package/dist/src/lib/hosting-errors.d.ts +30 -0
  319. package/dist/src/lib/hosting-errors.js +43 -0
  320. package/dist/src/lib/hosting-errors.js.map +1 -0
  321. package/dist/src/lib/hosting-token.d.ts +46 -0
  322. package/dist/src/lib/hosting-token.js +60 -0
  323. package/dist/src/lib/hosting-token.js.map +1 -0
  324. package/dist/src/lib/hosting-trust-step.d.ts +67 -0
  325. package/dist/src/lib/hosting-trust-step.js +279 -0
  326. package/dist/src/lib/hosting-trust-step.js.map +1 -0
  327. package/dist/src/lib/hosting-trust.d.ts +77 -0
  328. package/dist/src/lib/hosting-trust.js +194 -0
  329. package/dist/src/lib/hosting-trust.js.map +1 -0
  330. package/dist/src/lib/hosting-wait.d.ts +42 -0
  331. package/dist/src/lib/hosting-wait.js +84 -0
  332. package/dist/src/lib/hosting-wait.js.map +1 -0
  333. package/dist/src/lib/hosting-wfp-upload.d.ts +86 -0
  334. package/dist/src/lib/hosting-wfp-upload.js +149 -0
  335. package/dist/src/lib/hosting-wfp-upload.js.map +1 -0
  336. package/dist/src/lib/init-assets.d.ts +2 -6
  337. package/dist/src/lib/init-assets.js +11 -27
  338. package/dist/src/lib/init-assets.js.map +1 -1
  339. package/dist/src/lib/init-ios-links.d.ts +11 -7
  340. package/dist/src/lib/init-ios-links.js +28 -22
  341. package/dist/src/lib/init-ios-links.js.map +1 -1
  342. package/dist/src/lib/init-login-note.d.ts +13 -0
  343. package/dist/src/lib/init-login-note.js +22 -0
  344. package/dist/src/lib/init-login-note.js.map +1 -0
  345. package/dist/src/lib/init-schema.d.ts +15 -0
  346. package/dist/src/lib/init-schema.js +54 -0
  347. package/dist/src/lib/init-schema.js.map +1 -1
  348. package/dist/src/lib/integration-test-request.d.ts +54 -0
  349. package/dist/src/lib/integration-test-request.js +207 -0
  350. package/dist/src/lib/integration-test-request.js.map +1 -0
  351. package/dist/src/lib/invoker-shared-enums.d.ts +35 -0
  352. package/dist/src/lib/invoker-shared-enums.js +98 -0
  353. package/dist/src/lib/invoker-shared-enums.js.map +1 -0
  354. package/dist/src/lib/json-value.d.ts +6 -0
  355. package/dist/src/lib/json-value.js +13 -0
  356. package/dist/src/lib/json-value.js.map +1 -0
  357. package/dist/src/lib/load-routes.d.ts +33 -0
  358. package/dist/src/lib/load-routes.js +35 -0
  359. package/dist/src/lib/load-routes.js.map +1 -0
  360. package/dist/src/lib/log-inspection.d.ts +23 -4
  361. package/dist/src/lib/log-inspection.js +14 -5
  362. package/dist/src/lib/log-inspection.js.map +1 -1
  363. package/dist/src/lib/login-exchange-check.d.ts +18 -0
  364. package/dist/src/lib/login-exchange-check.js +27 -0
  365. package/dist/src/lib/login-exchange-check.js.map +1 -0
  366. package/dist/src/lib/login-scope-lines.d.ts +17 -7
  367. package/dist/src/lib/login-scope-lines.js +33 -10
  368. package/dist/src/lib/login-scope-lines.js.map +1 -1
  369. package/dist/src/lib/metadata-report.d.ts +85 -0
  370. package/dist/src/lib/metadata-report.js +81 -0
  371. package/dist/src/lib/metadata-report.js.map +1 -0
  372. package/dist/src/lib/object-status-filter.d.ts +9 -1
  373. package/dist/src/lib/object-status-filter.js +9 -1
  374. package/dist/src/lib/object-status-filter.js.map +1 -1
  375. package/dist/src/lib/output.d.ts +1 -1
  376. package/dist/src/lib/output.js +3 -1
  377. package/dist/src/lib/output.js.map +1 -1
  378. package/dist/src/lib/pin-refusal-hint.d.ts +12 -0
  379. package/dist/src/lib/pin-refusal-hint.js +35 -0
  380. package/dist/src/lib/pin-refusal-hint.js.map +1 -0
  381. package/dist/src/lib/platform-owned.js +5 -0
  382. package/dist/src/lib/platform-owned.js.map +1 -1
  383. package/dist/src/lib/primitive-declaration-names.d.ts +21 -0
  384. package/dist/src/lib/primitive-declaration-names.js +22 -0
  385. package/dist/src/lib/primitive-declaration-names.js.map +1 -0
  386. package/dist/src/lib/primitive-declaration.d.ts +174 -0
  387. package/dist/src/lib/primitive-declaration.js +871 -0
  388. package/dist/src/lib/primitive-declaration.js.map +1 -0
  389. package/dist/src/lib/primitive-env-plugin.d.ts +99 -0
  390. package/dist/src/lib/primitive-env-plugin.js +408 -0
  391. package/dist/src/lib/primitive-env-plugin.js.map +1 -0
  392. package/dist/src/lib/project-login-apps.d.ts +8 -0
  393. package/dist/src/lib/project-login-apps.js +27 -0
  394. package/dist/src/lib/project-login-apps.js.map +1 -0
  395. package/dist/src/lib/prompt-schema-codegen.d.ts +36 -12
  396. package/dist/src/lib/prompt-schema-codegen.js +96 -100
  397. package/dist/src/lib/prompt-schema-codegen.js.map +1 -1
  398. package/dist/src/lib/prompt-schema-document.d.ts +35 -0
  399. package/dist/src/lib/prompt-schema-document.js +92 -0
  400. package/dist/src/lib/prompt-schema-document.js.map +1 -0
  401. package/dist/src/lib/prompt-schema-refs.d.ts +173 -0
  402. package/dist/src/lib/prompt-schema-refs.js +478 -0
  403. package/dist/src/lib/prompt-schema-refs.js.map +1 -0
  404. package/dist/src/lib/records-verbs.d.ts +79 -0
  405. package/dist/src/lib/records-verbs.js +45 -0
  406. package/dist/src/lib/records-verbs.js.map +1 -0
  407. package/dist/src/lib/refresh-admin-credentials.d.ts +34 -4
  408. package/dist/src/lib/refresh-admin-credentials.js +85 -29
  409. package/dist/src/lib/refresh-admin-credentials.js.map +1 -1
  410. package/dist/src/lib/refresh-stored-login.d.ts +85 -0
  411. package/dist/src/lib/refresh-stored-login.js +233 -0
  412. package/dist/src/lib/refresh-stored-login.js.map +1 -0
  413. package/dist/src/lib/register-commands.d.ts +36 -0
  414. package/dist/src/lib/register-commands.js +37 -0
  415. package/dist/src/lib/register-commands.js.map +1 -0
  416. package/dist/src/lib/retired-imports.d.ts +53 -0
  417. package/dist/src/lib/retired-imports.js +120 -0
  418. package/dist/src/lib/retired-imports.js.map +1 -0
  419. package/dist/src/lib/row-field-rename.d.ts +18 -0
  420. package/dist/src/lib/row-field-rename.js +32 -0
  421. package/dist/src/lib/row-field-rename.js.map +1 -0
  422. package/dist/src/lib/run-status.d.ts +1 -1
  423. package/dist/src/lib/run-status.generated.d.ts +2 -2
  424. package/dist/src/lib/run-status.generated.js +3 -1
  425. package/dist/src/lib/run-status.generated.js.map +1 -1
  426. package/dist/src/lib/run-status.js +1 -1
  427. package/dist/src/lib/schema-codegen/compiledSpace.d.ts +62 -0
  428. package/dist/src/lib/schema-codegen/compiledSpace.js +103 -0
  429. package/dist/src/lib/schema-codegen/compiledSpace.js.map +1 -0
  430. package/dist/src/lib/schema-codegen/generated-db3-bridge.d.ts +86 -0
  431. package/dist/src/lib/schema-codegen/generated-db3-bridge.js +227 -0
  432. package/dist/src/lib/schema-codegen/generated-db3-bridge.js.map +1 -0
  433. package/dist/src/lib/schema-codegen/generated-db3-query-capabilities.d.ts +85 -0
  434. package/dist/src/lib/schema-codegen/generated-db3-query-capabilities.js +86 -0
  435. package/dist/src/lib/schema-codegen/generated-db3-query-capabilities.js.map +1 -0
  436. package/dist/src/lib/schema-codegen/generated-field-grammar.d.ts +229 -0
  437. package/dist/src/lib/schema-codegen/generated-field-grammar.js +420 -0
  438. package/dist/src/lib/schema-codegen/generated-field-grammar.js.map +1 -0
  439. package/dist/src/lib/schema-codegen/generated-field-table.d.ts +80 -0
  440. package/dist/src/lib/schema-codegen/generated-field-table.js +542 -0
  441. package/dist/src/lib/schema-codegen/generated-field-table.js.map +1 -0
  442. package/dist/src/lib/schema-codegen/generated-prompt-schemas.d.ts +195 -0
  443. package/dist/src/lib/schema-codegen/generated-prompt-schemas.js +503 -0
  444. package/dist/src/lib/schema-codegen/generated-prompt-schemas.js.map +1 -0
  445. package/dist/src/lib/schema-codegen/generated-schema-descriptor.d.ts +258 -0
  446. package/dist/src/lib/schema-codegen/generated-schema-descriptor.js +422 -0
  447. package/dist/src/lib/schema-codegen/generated-schema-descriptor.js.map +1 -0
  448. package/dist/src/lib/schema-codegen/generated-schema-file.d.ts +129 -0
  449. package/dist/src/lib/schema-codegen/generated-schema-file.js +475 -0
  450. package/dist/src/lib/schema-codegen/generated-schema-file.js.map +1 -0
  451. package/dist/src/lib/schema-codegen/generated-schema-provenance.d.ts +115 -0
  452. package/dist/src/lib/schema-codegen/generated-schema-provenance.js +274 -0
  453. package/dist/src/lib/schema-codegen/generated-schema-provenance.js.map +1 -0
  454. package/dist/src/lib/schema-codegen/generated-schema-refs.d.ts +366 -0
  455. package/dist/src/lib/schema-codegen/generated-schema-refs.js +1789 -0
  456. package/dist/src/lib/schema-codegen/generated-schema-refs.js.map +1 -0
  457. package/dist/src/lib/schema-codegen/generated-schema-shape.d.ts +27 -0
  458. package/dist/src/lib/schema-codegen/generated-schema-shape.js +126 -0
  459. package/dist/src/lib/schema-codegen/generated-schema-shape.js.map +1 -0
  460. package/dist/src/lib/schema-codegen/namedRefs.d.ts +56 -0
  461. package/dist/src/lib/schema-codegen/namedRefs.js +143 -0
  462. package/dist/src/lib/schema-codegen/namedRefs.js.map +1 -0
  463. package/dist/src/lib/schema-codegen/naming.d.ts +35 -0
  464. package/dist/src/lib/schema-codegen/naming.js +83 -0
  465. package/dist/src/lib/schema-codegen/naming.js.map +1 -0
  466. package/dist/src/lib/schema-codegen/schemaChanges.d.ts +74 -0
  467. package/dist/src/lib/schema-codegen/schemaChanges.js +277 -0
  468. package/dist/src/lib/schema-codegen/schemaChanges.js.map +1 -0
  469. package/dist/src/lib/schema-codegen/schemaDocs.d.ts +69 -0
  470. package/dist/src/lib/schema-codegen/schemaDocs.js +219 -0
  471. package/dist/src/lib/schema-codegen/schemaDocs.js.map +1 -0
  472. package/dist/src/lib/schema-codegen/schemaIR.d.ts +158 -0
  473. package/dist/src/lib/schema-codegen/schemaIR.js +279 -0
  474. package/dist/src/lib/schema-codegen/schemaIR.js.map +1 -0
  475. package/dist/src/lib/schema-codegen/schemaToTs.d.ts +109 -0
  476. package/dist/src/lib/schema-codegen/schemaToTs.js +269 -0
  477. package/dist/src/lib/schema-codegen/schemaToTs.js.map +1 -0
  478. package/dist/src/lib/schema-codegen/valuesLists.d.ts +48 -0
  479. package/dist/src/lib/schema-codegen/valuesLists.js +144 -0
  480. package/dist/src/lib/schema-codegen/valuesLists.js.map +1 -0
  481. package/dist/src/lib/schema-defs-module.d.ts +29 -0
  482. package/dist/src/lib/schema-defs-module.js +103 -0
  483. package/dist/src/lib/schema-defs-module.js.map +1 -0
  484. package/dist/src/lib/schema-family-index.d.ts +228 -0
  485. package/dist/src/lib/schema-family-index.js +813 -0
  486. package/dist/src/lib/schema-family-index.js.map +1 -0
  487. package/dist/src/lib/schema-pins.d.ts +82 -0
  488. package/dist/src/lib/schema-pins.js +198 -0
  489. package/dist/src/lib/schema-pins.js.map +1 -0
  490. package/dist/src/lib/schema-preview.d.ts +244 -0
  491. package/dist/src/lib/schema-preview.js +498 -0
  492. package/dist/src/lib/schema-preview.js.map +1 -0
  493. package/dist/src/lib/scope-request.d.ts +23 -11
  494. package/dist/src/lib/scope-request.js +69 -31
  495. package/dist/src/lib/scope-request.js.map +1 -1
  496. package/dist/src/lib/session-scope.d.ts +26 -0
  497. package/dist/src/lib/session-scope.js +58 -0
  498. package/dist/src/lib/session-scope.js.map +1 -0
  499. package/dist/src/lib/skill-installer.d.ts +2 -2
  500. package/dist/src/lib/skill-installer.js +2 -21
  501. package/dist/src/lib/skill-installer.js.map +1 -1
  502. package/dist/src/lib/step-run-table.d.ts +1 -2
  503. package/dist/src/lib/step-run-table.js +1 -2
  504. package/dist/src/lib/step-run-table.js.map +1 -1
  505. package/dist/src/lib/swift-codegen/agentGenerator.d.ts +2 -1
  506. package/dist/src/lib/swift-codegen/agentGenerator.js +25 -23
  507. package/dist/src/lib/swift-codegen/agentGenerator.js.map +1 -1
  508. package/dist/src/lib/swift-codegen/banners.d.ts +12 -0
  509. package/dist/src/lib/swift-codegen/banners.js +12 -0
  510. package/dist/src/lib/swift-codegen/banners.js.map +1 -1
  511. package/dist/src/lib/swift-codegen/functionGenerator.d.ts +36 -1
  512. package/dist/src/lib/swift-codegen/functionGenerator.js +169 -51
  513. package/dist/src/lib/swift-codegen/functionGenerator.js.map +1 -1
  514. package/dist/src/lib/swift-codegen/schemaToSwift.d.ts +33 -9
  515. package/dist/src/lib/swift-codegen/schemaToSwift.js +215 -179
  516. package/dist/src/lib/swift-codegen/schemaToSwift.js.map +1 -1
  517. package/dist/src/lib/swift-codegen/sharedGenerator.d.ts +51 -0
  518. package/dist/src/lib/swift-codegen/sharedGenerator.js +239 -0
  519. package/dist/src/lib/swift-codegen/sharedGenerator.js.map +1 -0
  520. package/dist/src/lib/swift-codegen/swiftKeys.d.ts +19 -0
  521. package/dist/src/lib/swift-codegen/swiftKeys.js +31 -0
  522. package/dist/src/lib/swift-codegen/swiftKeys.js.map +1 -0
  523. package/dist/src/lib/swift-codegen/userPropertiesGenerator.d.ts +30 -0
  524. package/dist/src/lib/swift-codegen/userPropertiesGenerator.js +69 -0
  525. package/dist/src/lib/swift-codegen/userPropertiesGenerator.js.map +1 -0
  526. package/dist/src/lib/sync-resource-types.d.ts +117 -31
  527. package/dist/src/lib/sync-resource-types.js +197 -189
  528. package/dist/src/lib/sync-resource-types.js.map +1 -1
  529. package/dist/src/lib/sync-selectors.d.ts +7 -0
  530. package/dist/src/lib/sync-selectors.js +22 -2
  531. package/dist/src/lib/sync-selectors.js.map +1 -1
  532. package/dist/src/lib/template.d.ts +39 -3
  533. package/dist/src/lib/template.js +103 -14
  534. package/dist/src/lib/template.js.map +1 -1
  535. package/dist/src/lib/test-case-file-names.d.ts +3 -5
  536. package/dist/src/lib/test-case-file-names.js +3 -5
  537. package/dist/src/lib/test-case-file-names.js.map +1 -1
  538. package/dist/src/lib/test-runs.d.ts +45 -0
  539. package/dist/src/lib/test-runs.js +150 -0
  540. package/dist/src/lib/test-runs.js.map +1 -0
  541. package/dist/src/lib/test-users.d.ts +25 -0
  542. package/dist/src/lib/test-users.js +36 -0
  543. package/dist/src/lib/test-users.js.map +1 -0
  544. package/dist/src/lib/toml-database-config.d.ts +4 -2
  545. package/dist/src/lib/toml-database-config.js +11 -6
  546. package/dist/src/lib/toml-database-config.js.map +1 -1
  547. package/dist/src/lib/toml-list-edit.d.ts +33 -0
  548. package/dist/src/lib/toml-list-edit.js +481 -0
  549. package/dist/src/lib/toml-list-edit.js.map +1 -0
  550. package/dist/src/lib/toml-scalar-edit.d.ts +9 -0
  551. package/dist/src/lib/toml-scalar-edit.js +73 -5
  552. package/dist/src/lib/toml-scalar-edit.js.map +1 -1
  553. package/dist/src/lib/transition-warnings.d.ts +21 -0
  554. package/dist/src/lib/transition-warnings.js +49 -0
  555. package/dist/src/lib/transition-warnings.js.map +1 -0
  556. package/dist/src/lib/usage-meters.d.ts +16 -0
  557. package/dist/src/lib/usage-meters.js +52 -0
  558. package/dist/src/lib/usage-meters.js.map +1 -0
  559. package/dist/src/lib/user-index.d.ts +80 -0
  560. package/dist/src/lib/user-index.js +166 -0
  561. package/dist/src/lib/user-index.js.map +1 -0
  562. package/dist/src/lib/user-properties/generated-properties-schema.d.ts +159 -0
  563. package/dist/src/lib/user-properties/generated-properties-schema.js +471 -0
  564. package/dist/src/lib/user-properties/generated-properties-schema.js.map +1 -0
  565. package/dist/src/lib/user-properties/user-properties-codegen.d.ts +55 -0
  566. package/dist/src/lib/user-properties/user-properties-codegen.js +129 -0
  567. package/dist/src/lib/user-properties/user-properties-codegen.js.map +1 -0
  568. package/dist/src/lib/user-walk.d.ts +31 -0
  569. package/dist/src/lib/user-walk.js +102 -0
  570. package/dist/src/lib/user-walk.js.map +1 -0
  571. package/dist/src/lib/webhook-capture.d.ts +43 -0
  572. package/dist/src/lib/webhook-capture.js +91 -0
  573. package/dist/src/lib/webhook-capture.js.map +1 -0
  574. package/dist/src/lib/webhook-deliver.d.ts +18 -20
  575. package/dist/src/lib/webhook-deliver.js +34 -89
  576. package/dist/src/lib/webhook-deliver.js.map +1 -1
  577. package/dist/src/lib/webhook-test-run.d.ts +32 -0
  578. package/dist/src/lib/webhook-test-run.js +108 -0
  579. package/dist/src/lib/webhook-test-run.js.map +1 -0
  580. package/dist/src/lib/worker-perf-format.d.ts +22 -0
  581. package/dist/src/lib/worker-perf-format.js +27 -0
  582. package/dist/src/lib/worker-perf-format.js.map +1 -0
  583. package/dist/src/types/index.d.ts +20 -65
  584. package/dist/src/validators.d.ts +7 -55
  585. package/dist/src/validators.js +7 -53
  586. package/dist/src/validators.js.map +1 -1
  587. package/dist/src/vite.d.ts +17 -0
  588. package/dist/src/vite.js +18 -0
  589. package/dist/src/vite.js.map +1 -0
  590. package/package.json +20 -9
@@ -0,0 +1,2053 @@
1
+ import { Option } from "commander";
2
+ import { commandStatus } from "../lib/command-status.js";
3
+ import { ApiClient } from "../lib/api-client.js";
4
+ import { getServerUrl, 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
+ /** The levels a db3 grant, link or request names. */
155
+ const SHARING_LEVELS = ["reader", "read-write"];
156
+ /** `value` as a sharing level, or exit 1 naming `flag` before any request. */
157
+ function parseSharingLevel(value, flag) {
158
+ if (SHARING_LEVELS.includes(value))
159
+ return value;
160
+ refuseList(`${flag} must be "reader" or "read-write".`);
161
+ }
162
+ /** Exactly one of `--user-id` and `--email`, or exit 1 before any request. */
163
+ function parseUserTarget(options) {
164
+ if (options.userId !== undefined && options.email === undefined)
165
+ return { userId: options.userId };
166
+ if (options.email !== undefined && options.userId === undefined)
167
+ return { email: options.email };
168
+ refuseList("Name the user with exactly one of --user-id <id> and --email <email>.");
169
+ }
170
+ /** Ask `question` unless `-y`: false when the operator cancels; exit 1 when stdin cannot ask. */
171
+ async function confirmed(options, question) {
172
+ if (options.yes)
173
+ return true;
174
+ try {
175
+ if (await confirmPrompt(question))
176
+ return true;
177
+ }
178
+ catch (err) {
179
+ error(err.message);
180
+ process.exit(1);
181
+ }
182
+ info("Cancelled.");
183
+ return false;
184
+ }
185
+ /** A sharing list's rows printed as a table, or its "No … found." line. */
186
+ function printSharingTable(rows, columns, empty) {
187
+ if (rows.length === 0) {
188
+ info(empty);
189
+ return;
190
+ }
191
+ console.log(formatTable(rows, columns));
192
+ }
193
+ /**
194
+ * `primitive db3` (#4696, #4804): a db3's lifecycle (`create`, `get`,
195
+ * `list`, `delete`, `stats`), its sync, app access and custody, its sharing
196
+ * (#5922: link access, user and group grants, pending invitations, access
197
+ * requests and a user's effective access), its indexes, and its records,
198
+ * schema and room through the `db3/:id/*` routes.
199
+ *
200
+ * The records, schema and inspect verbs are the `documents` verbs' twins:
201
+ * they share their action code (`./documents.ts`) through the db3 routes
202
+ * (`DB3_ROUTES`), take the same arguments and flags but `--document-format`
203
+ * (a db3 is format 3), and print what their twins print.
204
+ */
205
+ export function registerDb3Commands(program) {
206
+ const db3 = program
207
+ .command("db3")
208
+ .description("Work with db3s: create, read, list and delete them, their sync, sharing, app access and custody, indexes, records, schema and room");
209
+ commandStatus(db3, { stability: "beta" });
210
+ // ---- Indexes ----
211
+ const indexes = db3.command("indexes").description("List, register and drop a db3's indexes");
212
+ indexes
213
+ .command("list")
214
+ .description("List a db3's indexes: declared and registered")
215
+ .argument("<db3-id>", "db3 ID")
216
+ .option("--app <app-id>", "App ID")
217
+ .option("--json", "Output as JSON")
218
+ .action(async (db3Id, options) => {
219
+ const resolvedAppId = resolveAppId(undefined, options);
220
+ const client = new ApiClient();
221
+ try {
222
+ const { indexes: list } = await client.listDb3Indexes(resolvedAppId, db3Id);
223
+ if (options.json) {
224
+ json(wholeListEnvelope(list));
225
+ return;
226
+ }
227
+ if (list.length === 0) {
228
+ info("No indexes on this db3.");
229
+ return;
230
+ }
231
+ console.log(formatTable(db3IndexTableRows(list), [
232
+ { header: "NAME", key: "name", flex: true },
233
+ { header: "MODEL", key: "model" },
234
+ { header: "FIELDS", key: "fields" },
235
+ { header: "UNIQUE", key: "unique" },
236
+ { header: "ORIGINS", key: "origins" },
237
+ { header: "KIND", key: "kind" },
238
+ { header: "ON", key: "on" },
239
+ // #5229 — a vector index's shared model; a list with no vector index prints as before.
240
+ ...(listsVectorIndex(list) ? [{ header: "ANN MODEL", key: "annModel" }] : []),
241
+ ]));
242
+ }
243
+ catch (err) {
244
+ refuse(err);
245
+ }
246
+ });
247
+ indexes
248
+ .command("register")
249
+ .description("Register an index on a db3 model's field, or a named composite over several fields")
250
+ .argument("<db3-id>", "db3 ID")
251
+ .requiredOption("--model <model>", "Model name")
252
+ .requiredOption("--field <field>", "Field to index (repeat it for a composite unique index, which also needs --unique and --name)", (value, previous = []) => previous.concat(value))
253
+ .option("--unique", "Enforce that no two records share the key")
254
+ .option("--name <name>", "Name the index (idx_named_<model>_<name>)")
255
+ .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)")
256
+ // #5890 — the old spelling of --set-elements, kept outside the documented surface.
257
+ .addOption(new Option("--members", "Deprecated: use --set-elements").hideHelp())
258
+ .option("--kind <kind>", `What the index is: ${DB3_INDEX_KINDS.join(", ")} (default scalar, set-elements with --set-elements)`)
259
+ .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`)
260
+ .option("--distance <distance>", `A vector index's distance: ${VECTOR_DISTANCES.join(", ")} (with --kind vector)`)
261
+ .option("--index <mode>", `A vector index's search: ${VECTOR_INDEX_MODES.join(", ")} (with --kind vector; default exact)`)
262
+ .option("--nbucket <n>", "An ann vector index's bucket count (with --index ann)")
263
+ .option("--codesize <n>", "An ann vector index's bytes per quantized vector (with --index ann)")
264
+ .option("--quantizer <quantizer>", `An ann vector index's quantizer: ${VECTOR_QUANTIZERS.join(", ")} (with --index ann)`)
265
+ .option("--tokenizer <tokenizer>", "A text index's tokenizer: unicode61 (the default, diacritics folded) or porter (English stems)")
266
+ .option("--prefix <lengths>", "A text index's prefix lengths to index, comma-separated (e.g. 2,3)")
267
+ .option("--weight <field=weight>", "A text index's weight for one of its fields (repeatable; 1 by default)", (value, previous = []) => previous.concat(value))
268
+ .option("--app <app-id>", "App ID")
269
+ .option("--json", "Output as JSON")
270
+ .action(async (db3Id, options) => {
271
+ const resolvedAppId = resolveAppId(undefined, options);
272
+ const fields = options.field;
273
+ const kind = options.kind;
274
+ const vector = vectorIndexOptions(options, kind);
275
+ if ("problem" in vector) {
276
+ error(vector.problem);
277
+ process.exit(1);
278
+ }
279
+ if (options.members && options.setElements) {
280
+ error("--members is the old spelling of --set-elements: give --set-elements alone");
281
+ process.exit(1);
282
+ }
283
+ // #5890 — the old spellings still register the same index, saying so once each.
284
+ if (options.members)
285
+ warn("--members is deprecated: use --set-elements");
286
+ if (kind === "members")
287
+ warn("--kind members is deprecated: use --kind set-elements");
288
+ const setFlag = options.setElements === true || options.members === true;
289
+ const setFlagSpelling = options.members ? "--members" : "--set-elements";
290
+ const members = setFlag || kind === "members" || kind === "set-elements";
291
+ // The set-element spelling the user typed: the flag, else the kind.
292
+ const flag = setFlag
293
+ ? setFlagSpelling
294
+ : kind === "members"
295
+ ? "--kind members"
296
+ : kind === "set-elements"
297
+ ? "--kind set-elements"
298
+ : "--set-elements";
299
+ const textOptions = options.tokenizer !== undefined || options.prefix !== undefined || options.weight !== undefined;
300
+ const text = kind === "text" ? db3TextOptionsOf(options) : null;
301
+ const conflict = kind !== undefined && kind !== "members" && !DB3_INDEX_KINDS.includes(kind)
302
+ ? `--kind must be one of ${DB3_INDEX_KINDS.join(", ")}`
303
+ : options.on !== undefined && !DB3_INDEX_PLACEMENTS.includes(options.on)
304
+ ? `--on must be one of ${DB3_INDEX_PLACEMENTS.join(", ")}`
305
+ : setFlag && kind !== undefined && kind !== "members" && kind !== "set-elements"
306
+ ? `${setFlagSpelling} is --kind set-elements: give --kind ${kind} without ${setFlagSpelling}, or --kind set-elements`
307
+ : textOptions && kind !== "text"
308
+ ? `--tokenizer, --prefix and --weight apply to --kind text`
309
+ : text && "refusal" in text
310
+ ? text.refusal
311
+ : kind === "text" && options.unique
312
+ ? `--kind text takes no --unique: a text index enforces nothing`
313
+ : kind === "text" && options.name !== undefined
314
+ ? `--kind text takes no --name: a model's text index is named idx_text_<model>`
315
+ : !members
316
+ ? null
317
+ : fields.length > 1
318
+ ? `${flag} takes one --field: a set-element index covers one string-set field`
319
+ : options.unique
320
+ ? `${flag} takes no --unique: a set-element index enforces nothing`
321
+ : options.name !== undefined
322
+ ? `${flag} takes no --name: a set-element index is named idx_members_<model>_<field>`
323
+ : null;
324
+ if (conflict) {
325
+ error(conflict);
326
+ process.exit(1);
327
+ }
328
+ const textBody = text && "text" in text && Object.keys(text.text).length > 0 ? { text: text.text } : {};
329
+ const body = {
330
+ model: options.model,
331
+ ...(fields.length === 1 ? { field: fields[0] } : { fields }),
332
+ ...(options.unique ? { unique: true } : {}),
333
+ ...(options.name !== undefined ? { name: options.name } : {}),
334
+ ...(setFlag ? { members: true } : {}),
335
+ ...(kind !== undefined ? { kind: db3IndexKindOnTheWire(kind) } : {}),
336
+ ...(options.on !== undefined ? { on: options.on } : {}),
337
+ ...(vector.options ? { vector: vector.options } : {}),
338
+ ...textBody,
339
+ };
340
+ const client = new ApiClient();
341
+ try {
342
+ const { index } = await client.registerDb3Index(resolvedAppId, db3Id, body);
343
+ if (options.json) {
344
+ json(index);
345
+ return;
346
+ }
347
+ success(`Registered ${index.name} on ${index.model} (${index.fields.join(", ")}${index.unique ? ", unique" : ""}${index.members ? ", set-element index" : ""}${index.kind === "text" ? ", text" : ""}).`);
348
+ }
349
+ catch (err) {
350
+ refuse(err, flag);
351
+ }
352
+ });
353
+ indexes
354
+ .command("drop")
355
+ .description("Drop a db3 index you registered (one a declaration keeps stays)")
356
+ .argument("<db3-id>", "db3 ID")
357
+ .argument("<name>", "Index name, as `db3 indexes list` prints it")
358
+ .option("--app <app-id>", "App ID")
359
+ .option("-y, --yes", "Skip confirmation prompt")
360
+ .option("--json", "Output as JSON")
361
+ .action(async (db3Id, name, options) => {
362
+ const resolvedAppId = resolveAppId(undefined, options);
363
+ if (!options.yes) {
364
+ let confirmed;
365
+ try {
366
+ confirmed = await confirmPrompt(`Drop index ${name} from db3 ${db3Id}?`);
367
+ }
368
+ catch (err) {
369
+ error(err.message);
370
+ process.exit(1);
371
+ }
372
+ if (!confirmed) {
373
+ info("Cancelled.");
374
+ return;
375
+ }
376
+ }
377
+ const client = new ApiClient();
378
+ try {
379
+ const answer = await client.dropDb3Index(resolvedAppId, db3Id, name);
380
+ if (options.json) {
381
+ json(answer);
382
+ return;
383
+ }
384
+ success(`Dropped ${answer.name}.`);
385
+ }
386
+ catch (err) {
387
+ refuse(err);
388
+ }
389
+ });
390
+ // ---- A vector index's shared ANN model (#5229) ----
391
+ const model = indexes.command("model").description("Fetch or delete an ann vector index's shared model");
392
+ model
393
+ .command("get")
394
+ .description("Write an ann vector index's shared model to a file, as a device uploaded it")
395
+ .argument("<db3-id>", "db3 ID")
396
+ .argument("<name>", "Vector index name, as `db3 indexes list` prints it")
397
+ .option("--out <file>", "Where to write the model (default <name>-<generation>-<revision>.pvm1)")
398
+ .option("--app <app-id>", "App ID")
399
+ .option("--json", "Output as JSON")
400
+ .action(async (db3Id, name, options) => {
401
+ const resolvedAppId = resolveAppId(undefined, options);
402
+ const client = new ApiClient();
403
+ try {
404
+ const fetched = await client.fetchDb3IndexModel(resolvedAppId, db3Id, name);
405
+ const out = path.resolve(options.out ?? `${name}-${fetched.generation}-${fetched.revision}.pvm1`);
406
+ fs.writeFileSync(out, fetched.data);
407
+ const summary = {
408
+ name,
409
+ file: out,
410
+ bytes: fetched.data.byteLength,
411
+ generation: fetched.generation,
412
+ revision: fetched.revision,
413
+ rows: fetched.rows,
414
+ trainedAt: fetched.trainedAt,
415
+ format: fetched.format,
416
+ };
417
+ if (options.json) {
418
+ json(summary);
419
+ return;
420
+ }
421
+ success(`Wrote ${name}'s model (revision ${fetched.revision}, ${fetched.rows} rows, trained ${fetched.trainedAt}) to ${out}: ${fetched.data.byteLength} bytes.`);
422
+ }
423
+ catch (err) {
424
+ refuse(err);
425
+ }
426
+ });
427
+ model
428
+ .command("delete")
429
+ .description("Delete an ann vector index's shared model so a device trains it again (the db3's owner)")
430
+ .argument("<db3-id>", "db3 ID")
431
+ .argument("<name>", "Vector index name, as `db3 indexes list` prints it")
432
+ .option("--app <app-id>", "App ID")
433
+ .option("-y, --yes", "Skip confirmation prompt")
434
+ .option("--json", "Output as JSON")
435
+ .action(async (db3Id, name, options) => {
436
+ const resolvedAppId = resolveAppId(undefined, options);
437
+ if (!options.yes) {
438
+ let confirmed;
439
+ try {
440
+ confirmed = await confirmPrompt(`Delete ${name}'s shared model on db3 ${db3Id}? Every device answers exactly until one trains it again.`);
441
+ }
442
+ catch (err) {
443
+ error(err.message);
444
+ process.exit(1);
445
+ }
446
+ if (!confirmed) {
447
+ info("Cancelled.");
448
+ return;
449
+ }
450
+ }
451
+ const client = new ApiClient();
452
+ try {
453
+ const answer = await client.deleteDb3IndexModel(resolvedAppId, db3Id, name);
454
+ if (options.json) {
455
+ json(answer);
456
+ return;
457
+ }
458
+ success(`Deleted ${answer.name}'s model; its revision is now ${answer.revision}.`);
459
+ }
460
+ catch (err) {
461
+ refuse(err);
462
+ }
463
+ });
464
+ // ---- Records: the `documents records` verbs' twins ----
465
+ const records = db3.command("records").description("Query and write a db3's records");
466
+ records
467
+ .command("query")
468
+ .description("Query records in a db3 model")
469
+ .argument("<db3-id>", "db3 ID")
470
+ .argument("<model-name>", "Model name to query")
471
+ .option("--app <app-id>", "App ID")
472
+ .option("--filter <json>", "Filter as JSON (e.g. '{\"status\":\"open\"}')")
473
+ .option("--filter-file <path>", "Read filter from a JSON or TOML file")
474
+ .option("--sort <json>", "Sort as JSON, e.g. '{\"createdAt\":-1}'; 1 ascending, -1 descending, key order is precedence; repeat it with --cursor")
475
+ .option("--limit <n>", "Records per page (default 100, max 10000)")
476
+ .option("--cursor <cursor>", "Pagination cursor from a previous query (valid only with the same --sort)")
477
+ .option("--include <json>", "Related records as a JSON array of include specs, e.g. '[{\"model\":\"customer\",\"type\":\"refersTo\",\"sourceField\":\"customerId\"}]'; answered as _related")
478
+ .option("--explain", EXPLAIN_FLAG)
479
+ .option("--index <name>", INDEX_FLAG)
480
+ .option("--json", "Output as JSON")
481
+ .action(async (db3Id, modelName, options) => {
482
+ const resolvedAppId = resolveAppId(undefined, options);
483
+ if (explaining(options)) {
484
+ const { filter, sort, include } = queryReadOf(options);
485
+ const limit = options.limit === undefined ? undefined : /^\d+$/.test(options.limit) ? Number(options.limit) : options.limit;
486
+ await explainReadAction(new ApiClient(), resolvedAppId, db3Id, modelName, options, {
487
+ op: "query",
488
+ ...(filter ? { filter } : {}),
489
+ options: {
490
+ ...(sort !== undefined ? { sort } : {}),
491
+ ...(limit !== undefined ? { limit } : {}),
492
+ ...(options.cursor !== undefined ? { cursor: options.cursor } : {}),
493
+ ...(include !== undefined ? { include } : {}),
494
+ },
495
+ });
496
+ return;
497
+ }
498
+ await queryRecordsAction(DB3_ROUTES, resolvedAppId, db3Id, modelName, options);
499
+ });
500
+ records
501
+ .command("count")
502
+ .description("Count records in a db3 model")
503
+ .argument("<db3-id>", "db3 ID")
504
+ .argument("<model-name>", "Model name to count")
505
+ .option("--app <app-id>", "App ID")
506
+ .option("--filter <json>", "Filter as JSON (e.g. '{\"status\":\"open\"}')")
507
+ .option("--filter-file <path>", "Read filter from a JSON or TOML file")
508
+ .option("--explain", EXPLAIN_FLAG)
509
+ .option("--index <name>", INDEX_FLAG)
510
+ .option("--json", "Output as JSON")
511
+ .action(async (db3Id, modelName, options) => {
512
+ const resolvedAppId = resolveAppId(undefined, options);
513
+ if (explaining(options)) {
514
+ const filter = parseFilterOptions(options);
515
+ await explainReadAction(new ApiClient(), resolvedAppId, db3Id, modelName, options, { op: "count", ...(filter ? { filter } : {}) });
516
+ return;
517
+ }
518
+ await countRecordsAction(DB3_ROUTES, resolvedAppId, db3Id, modelName, options);
519
+ });
520
+ records
521
+ .command("aggregate")
522
+ .description("Aggregate records in a db3 model (count/sum/avg/min/max, optional group-by)")
523
+ .argument("<db3-id>", "db3 ID")
524
+ .argument("<model-name>", "Model name")
525
+ .option("--app <app-id>", "App ID")
526
+ .requiredOption("--op <operation>", "Aggregate operation: count|sum|avg|min|max")
527
+ .option("--field <field>", "Field to aggregate (required for sum/avg/min/max)")
528
+ .option("--group-by <field>", "Group results by this field (repeatable)", (value, previous = []) => previous.concat(value), [])
529
+ .option("--filter <json>", "Filter as JSON")
530
+ .option("--filter-file <path>", "Read filter from a JSON or TOML file")
531
+ .option("--explain", EXPLAIN_FLAG)
532
+ .option("--index <name>", INDEX_FLAG)
533
+ .option("--json", "Output as JSON")
534
+ .action(async (db3Id, modelName, options) => {
535
+ const resolvedAppId = resolveAppId(undefined, options);
536
+ if (explaining(options)) {
537
+ const { operations, groupBy, filter } = aggregateReadOf(options);
538
+ await explainReadAction(new ApiClient(), resolvedAppId, db3Id, modelName, options, {
539
+ op: "aggregate",
540
+ aggregate: { operations, groupBy, ...(filter ? { filter } : {}) },
541
+ });
542
+ return;
543
+ }
544
+ await aggregateRecordsAction(DB3_ROUTES, resolvedAppId, db3Id, modelName, options);
545
+ });
546
+ records
547
+ .command("save")
548
+ .description("Create or replace a record in a db3 model")
549
+ .argument("<db3-id>", "db3 ID")
550
+ .argument("<model-name>", "Model name to write to")
551
+ .option("--app <app-id>", "App ID")
552
+ .option("--id <record-id>", "Record ID (a ULID is generated when omitted)")
553
+ .option("--data <json>", "Record fields as JSON (e.g. '{\"qty\":10}')")
554
+ .option("--data-file <file>", "Read record fields from a JSON file")
555
+ .option("--upsert-on <field>", "Update the record whose <field> matches instead of creating")
556
+ .option("--json", "Output as JSON")
557
+ .action(async (db3Id, modelName, options) => {
558
+ const data = parseDataOption(options, "record fields");
559
+ const resolvedAppId = resolveAppId(undefined, options);
560
+ await saveRecordAction(DB3_ROUTES, resolvedAppId, db3Id, modelName, data, options);
561
+ });
562
+ records
563
+ .command("patch")
564
+ .description("Merge fields into an existing record in a db3 model")
565
+ .argument("<db3-id>", "db3 ID")
566
+ .argument("<model-name>", "Model name")
567
+ .argument("<record-id>", "Record ID to patch")
568
+ .option("--app <app-id>", "App ID")
569
+ .option("--data <json>", "Fields to merge as JSON (e.g. '{\"status\":\"closed\"}')")
570
+ .option("--data-file <file>", "Read fields from a JSON file")
571
+ .option("--json", "Output as JSON")
572
+ .action(async (db3Id, modelName, recordId, options) => {
573
+ const data = parseDataOption(options, "fields to merge");
574
+ const resolvedAppId = resolveAppId(undefined, options);
575
+ await patchRecordAction(DB3_ROUTES, resolvedAppId, db3Id, modelName, recordId, data, options);
576
+ });
577
+ records
578
+ .command("delete")
579
+ .description("Delete a record from a db3 model")
580
+ .argument("<db3-id>", "db3 ID")
581
+ .argument("<model-name>", "Model name")
582
+ .argument("<record-id>", "Record ID to delete")
583
+ .option("--app <app-id>", "App ID")
584
+ .option("-y, --yes", "Skip confirmation prompt")
585
+ .option("--json", "Output as JSON")
586
+ .action(async (db3Id, modelName, recordId, options) => {
587
+ const resolvedAppId = resolveAppId(undefined, options);
588
+ await deleteRecordAction(DB3_ROUTES, resolvedAppId, db3Id, modelName, recordId, options);
589
+ });
590
+ records
591
+ .command("batch")
592
+ .description(`Apply create/patch/increment/delete/upsert operations to a db3, with reads among them, at most ${DB3_BATCH_OPERATION_CAP} ` +
593
+ "operations per call (atomic); use `primitive db3 ingest` for larger loads")
594
+ .argument("<db3-id>", "db3 ID")
595
+ .requiredOption("--data-file <file>", DB3_BATCH_DATA_FILE_HELP)
596
+ .option("--app <app-id>", "App ID")
597
+ .option("-y, --yes", "Skip confirmation prompt")
598
+ .option("--json", "Output as JSON")
599
+ .action(async (db3Id, options) => {
600
+ await batchRecordsAction(DB3_ROUTES, db3Id, options);
601
+ });
602
+ records
603
+ .command("batch-read")
604
+ .description(`Run several queries, counts and aggregates on a db3 in one request, at most ${DB3_BATCH_OPERATION_CAP} ` +
605
+ "per call, answered from one state of the db3")
606
+ .argument("<db3-id>", "db3 ID")
607
+ .requiredOption("--data-file <file>", DB3_BATCH_READ_DATA_FILE_HELP)
608
+ .option("--partial", "Answer a refused read in its place instead of refusing the request")
609
+ .option("--app <app-id>", "App ID")
610
+ .option("--json", "Output as JSON")
611
+ .action(async (db3Id, options) => {
612
+ const client = new ApiClient();
613
+ await batchReadRecordsAction(client, db3Id, options);
614
+ });
615
+ records
616
+ .command("models")
617
+ .description("List model names in a db3")
618
+ .argument("<db3-id>", "db3 ID")
619
+ .option("--app <app-id>", "App ID")
620
+ .option("--json", "Output as JSON")
621
+ .action(async (db3Id, options) => {
622
+ await modelsAction(DB3_ROUTES, db3Id, options);
623
+ });
624
+ records
625
+ .command("describe")
626
+ .description("Show a db3 model's fields and indexes")
627
+ .argument("<db3-id>", "db3 ID")
628
+ .argument("<model-name>", "Model name")
629
+ .option("--app <app-id>", "App ID")
630
+ .option("--json", "Output as JSON")
631
+ .action(async (db3Id, modelName, options) => {
632
+ await describeAction(DB3_ROUTES, db3Id, modelName, options);
633
+ });
634
+ records
635
+ .command("increment")
636
+ .description("Add to numeric fields of a record in a db3 model (a missing or non-numeric field starts at 0)")
637
+ .argument("<db3-id>", "db3 ID")
638
+ .argument("<model-name>", "Model name")
639
+ .argument("<record-id>", "Record ID")
640
+ .option("--app <app-id>", "App ID")
641
+ .option("--data <json>", "Each field's delta as JSON (e.g. '{\"qty\":2}')")
642
+ .option("--data-file <file>", "Read the deltas from a JSON file")
643
+ .option("--json", "Output as JSON")
644
+ .action(async (db3Id, modelName, recordId, options) => {
645
+ const fields = parseDataOption(options, "field deltas");
646
+ const resolvedAppId = resolveAppId(undefined, options);
647
+ try {
648
+ const answer = await new ApiClient().incrementDb3Record(resolvedAppId, db3Id, modelName, recordId, { fields });
649
+ if (options.json) {
650
+ json(answer);
651
+ return;
652
+ }
653
+ for (const [field, value] of Object.entries(answer.values ?? {}))
654
+ printResult(field, value);
655
+ }
656
+ catch (err) {
657
+ fail(err);
658
+ }
659
+ });
660
+ records
661
+ .command("clear")
662
+ .description("Remove every record of a db3 model in one operation (experimental)")
663
+ .argument("<db3-id>", "db3 ID")
664
+ .argument("<model-name>", "Model name")
665
+ .option("--app <app-id>", "App ID")
666
+ .option("--drop", "Also remove the model itself from an untyped db3 (its declaration, observed fields and indexes)")
667
+ .option("-y, --yes", "Skip confirmation prompt")
668
+ .option("--json", "Output as JSON")
669
+ .action(async (db3Id, modelName, options) => {
670
+ const resolvedAppId = resolveAppId(undefined, options);
671
+ if (!options.yes) {
672
+ let confirmed;
673
+ try {
674
+ confirmed = await confirmPrompt(`Remove every record of ${modelName} from db3 ${db3Id}${options.drop ? ", and the model itself" : ""}? This cannot be undone.`);
675
+ }
676
+ catch (err) {
677
+ error(err.message);
678
+ process.exit(1);
679
+ }
680
+ if (!confirmed) {
681
+ info("Cancelled.");
682
+ return;
683
+ }
684
+ }
685
+ try {
686
+ const answer = await new ApiClient().clearDb3Model(resolvedAppId, db3Id, modelName, options.drop ? { drop: true } : {});
687
+ if (options.json) {
688
+ json(answer);
689
+ return;
690
+ }
691
+ if (answer.lsn === null)
692
+ success(`${modelName} held no records; nothing was written`);
693
+ else
694
+ success(`Cleared ${answer.rows} records of ${modelName} from db3 ${db3Id} (log number ${answer.lsn}, epoch ${answer.epoch})` +
695
+ (answer.dropped ? "; the model was dropped" : ""));
696
+ }
697
+ catch (err) {
698
+ fail(err);
699
+ }
700
+ });
701
+ // ---- Schema and room: the `documents schema` and `documents inspect` twins ----
702
+ db3
703
+ .command("schema")
704
+ .description("Show a db3's models and fields as declared and observed, or export them as a schema.toml")
705
+ .argument("<db3-id>", "db3 ID")
706
+ .option("--app <app-id>", "App ID")
707
+ .option("--toml", "Print a schema.toml the client's schemaToml option and js-bao-codegen-v2 accept")
708
+ .option("--output <file>", "With --toml: write the TOML to this file (overwriting it) instead of stdout")
709
+ .option("--json", "Output the /schema answer as JSON")
710
+ .action(async (db3Id, options) => {
711
+ await schemaAction(DB3_ROUTES, db3Id, options);
712
+ });
713
+ // ---- Type (#4802): attach a db3 type, or read the one it has ----
714
+ const type = db3.command("type").description("Attach a db3 type to a db3, or show the one it has");
715
+ type
716
+ .command("attach")
717
+ .description("Install a type's current revision in a db3, whole or not at all (a type is never detached)")
718
+ .argument("<db3-id>", "db3 ID")
719
+ .argument("<name>", "Type name")
720
+ .option("--app <app-id>", "App ID")
721
+ .option("--json", "Output as JSON")
722
+ .action(async (db3Id, name, options) => {
723
+ const resolvedAppId = resolveAppId(undefined, options);
724
+ try {
725
+ const answer = await new ApiClient().attachDb3Type(resolvedAppId, db3Id, name);
726
+ if (options.json) {
727
+ json(answer);
728
+ return;
729
+ }
730
+ success(`${db3Id} is of type ${answer.type}: ${answer.outcome} (revision ${new Date(answer.revision.generation).toISOString()})`);
731
+ }
732
+ catch (err) {
733
+ if (options.json) {
734
+ json({ ok: false, code: err?.code ?? null, message: err?.message ?? String(err), details: err?.details ?? null });
735
+ process.exit(1);
736
+ }
737
+ error(describeRecordsFailure(err));
738
+ for (const reason of err?.details?.reasons ?? [])
739
+ console.error(` ${reason.path}: ${reason.reason}`);
740
+ if (err?.details?.installed)
741
+ console.error(` installed: ${err.details.installed}`);
742
+ process.exit(1);
743
+ }
744
+ });
745
+ type
746
+ .command("get")
747
+ .description("Show the type a db3's row names, its revision, and what the db3's room holds")
748
+ .argument("<db3-id>", "db3 ID")
749
+ .option("--app <app-id>", "App ID")
750
+ .option("--json", "Output as JSON")
751
+ .action(async (db3Id, options) => {
752
+ const resolvedAppId = resolveAppId(undefined, options);
753
+ try {
754
+ const answer = await new ApiClient().getDb3Type(resolvedAppId, db3Id);
755
+ if (options.json) {
756
+ json(answer);
757
+ return;
758
+ }
759
+ const revision = (r) => (r ? `${new Date(r.generation).toISOString()} (${String(r.hash).slice(0, 12)})` : "—");
760
+ console.log(`Type: ${answer.type ?? "none"}`);
761
+ console.log(`Revision: ${revision(answer.revision)}`);
762
+ console.log(`Installed: ${answer.installed ? `${answer.installed.name} ${revision(answer.installed.revision)}` : "none"}`);
763
+ }
764
+ catch (err) {
765
+ error(describeRecordsFailure(err));
766
+ process.exit(1);
767
+ }
768
+ });
769
+ db3
770
+ .command("inspect")
771
+ .description("Show a db3's room: epochs, log number, floors, writers, the bulk load in progress and checkpoint")
772
+ .argument("<db3-id>", "db3 ID")
773
+ .option("--app <app-id>", "App ID")
774
+ .option("--refused <session-id>", "Print every row that bulk load refused, with its code, instead")
775
+ .option("--limit <n>", "With --refused: rows per page read (1–100)", "100")
776
+ .option("--json", "Output as JSON")
777
+ .action(async (db3Id, options) => {
778
+ await inspectAction(DB3_ROUTES, db3Id, options);
779
+ });
780
+ // ---- Bulk loads, snapshots, export and import (#4889) ----
781
+ // The `documents ingest|ingests|snapshots` verbs' twins over `db3/:id/*`:
782
+ // the same action code (`./documents.ts`), arguments and flags.
783
+ db3
784
+ .command("ingest")
785
+ .description("Bulk-load records into a db3 from a directory")
786
+ .argument("<db3-id>", "db3 ID")
787
+ .requiredOption("--input <dir>", "Directory of <model>.ndjson[.gz] files, or a `db3 export` or `documents export` output")
788
+ .option("--app <app-id>", "App ID")
789
+ .option("--reserve-epoch <when>", "Reserve the load's epoch at session open (open, the default) or at commit")
790
+ .option("--mode <mode>", "Merge the rows (merge, the default), or refresh: also delete every record of the input's models that no row names")
791
+ .option("-y, --yes", "Skip the confirmation prompt")
792
+ .option("--no-wait", "Exit once the session is committed")
793
+ .option("--timeout <seconds>", "Give up waiting after this many seconds")
794
+ .option("--json", "Output as JSON")
795
+ .addHelpText("after", `
796
+ Rows a load refuses are listed by \`primitive db3 inspect <db3-id> --refused <session-id>\`.
797
+ `)
798
+ .action(async (db3Id, options) => {
799
+ await ingestAction(DB3_LOAD_ROUTES, db3Id, options);
800
+ });
801
+ const ingests = db3.command("ingests").description("Inspect or abort a db3's bulk-load sessions");
802
+ ingests
803
+ .command("list")
804
+ .description("List a db3's bulk-load sessions, newest first")
805
+ .argument("<db3-id>", "db3 ID")
806
+ .option("--app <app-id>", "App ID")
807
+ .option("--limit <n>", "Page size (1–100)", "20")
808
+ .option("--cursor <cursor>", "Continue from a previous page's nextCursor")
809
+ .option("--json", "Output as JSON")
810
+ .action(async (db3Id, options) => {
811
+ await listIngestsAction(DB3_LOAD_ROUTES, db3Id, options);
812
+ });
813
+ ingests
814
+ .command("get")
815
+ .description("Show one bulk-load session, its progress and why it stopped")
816
+ .argument("<db3-id>", "db3 ID")
817
+ .argument("<session-id>", "Session ID")
818
+ .option("--app <app-id>", "App ID")
819
+ .option("--json", "Output as JSON")
820
+ .action(async (db3Id, sessionId, options) => {
821
+ await getIngestAction(DB3_LOAD_ROUTES, db3Id, sessionId, options);
822
+ });
823
+ ingests
824
+ .command("abort")
825
+ .description("Abort a bulk-load session and discard what it uploaded")
826
+ .argument("<db3-id>", "db3 ID")
827
+ .argument("<session-id>", "Session ID")
828
+ .option("--app <app-id>", "App ID")
829
+ .option("-y, --yes", "Skip the confirmation prompt")
830
+ .option("--json", "Output as JSON")
831
+ .action(async (db3Id, sessionId, options) => {
832
+ await abortIngestAction(DB3_LOAD_ROUTES, db3Id, sessionId, options);
833
+ });
834
+ const snapshots = db3.command("snapshots").description("Inspect or start a db3's segment exports");
835
+ snapshots
836
+ .command("list")
837
+ .description("List a db3's segment exports, newest first")
838
+ .argument("<db3-id>", "db3 ID")
839
+ .option("--app <app-id>", "App ID")
840
+ .option("--limit <n>", "Page size (1–100)", "20")
841
+ .option("--cursor <cursor>", "Continue from a previous page's nextCursor")
842
+ .option("--json", "Output as JSON")
843
+ .action(async (db3Id, options) => {
844
+ await listSnapshotsAction(DB3_LOAD_ROUTES, db3Id, options);
845
+ });
846
+ snapshots
847
+ .command("get")
848
+ .description("Show one segment export: its state, log number, rows and chunks")
849
+ .argument("<db3-id>", "db3 ID")
850
+ .argument("<segment-id>", "Segment ID")
851
+ .option("--app <app-id>", "App ID")
852
+ .option("--json", "Output as JSON")
853
+ .action(async (db3Id, segmentId, options) => {
854
+ await getSnapshotAction(DB3_LOAD_ROUTES, db3Id, segmentId, options);
855
+ });
856
+ snapshots
857
+ .command("build")
858
+ .description("Start a segment export of a db3's records now")
859
+ .argument("<db3-id>", "db3 ID")
860
+ .option("--app <app-id>", "App ID")
861
+ .option("--wait", "Poll until the segment is complete or failed")
862
+ .option("--timeout <seconds>", "Give up waiting after this many seconds")
863
+ .option("--json", "Output as JSON")
864
+ .action(async (db3Id, options) => {
865
+ await buildSnapshotAction(DB3_LOAD_ROUTES, db3Id, options);
866
+ });
867
+ db3
868
+ .command("export")
869
+ .description("Export a db3 to a directory: its rows, type, declaration and blobs")
870
+ .argument("<db3-id>", "db3 ID")
871
+ .option("--app <app-id>", "App ID")
872
+ .option("--output <dir>", "Directory to write (default ./primitive-export/db3/<db3-id>)")
873
+ .option("--no-blobs", "Leave the blobs out")
874
+ .option("--json", "Output as JSON")
875
+ .addHelpText("after", `
876
+ The directory holds db3.json (the db3's id, title, tags, type and revision,
877
+ its declaration and registered indexes, and the log number the rows are at),
878
+ the rows under snapshot/, chain.json and the blobs under blobs/. It holds no
879
+ grant, custody, sync state or alias. \`primitive db3 import\` loads it.
880
+ `)
881
+ .action(async (db3Id, options) => {
882
+ const resolvedAppId = resolveAppId(undefined, options);
883
+ const dir = path.resolve(options.output ?? path.join("primitive-export", "db3", db3Id));
884
+ let code = 0;
885
+ try {
886
+ const exported = await exportDb3(new ApiClient(), resolvedAppId, db3Id, dir, {
887
+ blobs: options.blobs !== false,
888
+ onProgress: (line) => info(line),
889
+ });
890
+ if (options.json) {
891
+ json({ id: db3Id, exportPath: dir, rows: exported.rows, blobs: exported.blobs, type: exported.manifest.type, lsn: exported.manifest.lsn });
892
+ }
893
+ else {
894
+ success(`Exported db3 ${db3Id} (${exported.manifest.title || "untitled"}) to ${dir}`);
895
+ printResult("Rows", exported.rows);
896
+ printResult("Blobs", options.blobs === false ? "left out" : exported.blobs);
897
+ printResult("Type", exported.manifest.type?.name ?? "none");
898
+ printResult("Log number", exported.manifest.lsn);
899
+ }
900
+ }
901
+ catch (err) {
902
+ error(err?.statusCode ? describeRecordsFailure(err) : err?.message ?? String(err));
903
+ code = 1;
904
+ }
905
+ await flushOutput();
906
+ process.exit(code);
907
+ });
908
+ db3
909
+ .command("import")
910
+ .description("Import a `db3 export` directory: a new db3 of its type, or --into an existing one")
911
+ .argument("<path>", "The export's directory")
912
+ .option("--app <app-id>", "App ID")
913
+ .option("--into <db3-id>", "Load into this db3 instead of creating one (of the same type and declaration)")
914
+ .option("--keep-id", "Create the db3 under the export's id (an app owner or admin; the id must be free in this app)")
915
+ .option("--title <title>", "The new db3's title (default: the export's)")
916
+ .option("--type <name>", "The db3 type to create it with (default: the export's)")
917
+ .option("--untyped", "Load into an untyped db3, registering the export's indexes and uniques first")
918
+ .option("--no-blobs", "Leave the blobs out")
919
+ .option("-y, --yes", "Skip the confirmation prompt (--into)")
920
+ .option("--json", "Output as JSON")
921
+ .addHelpText("after", `
922
+ Every check runs before anything is written: the type must be one the app
923
+ has (primitive db3-types push), with the export's declaration; an --into
924
+ target must be of the export's type and declare its models alike; and the
925
+ blobs keep their ids, so the exported db3 must be gone from the app (or
926
+ import into another app, or pass --no-blobs). A load that refuses a row exits
927
+ 1 naming \`primitive db3 inspect <db3-id> --refused <session-id>\`.
928
+
929
+ --keep-id creates the db3 under the export's id, so what stored that id still
930
+ finds it: the id must be free in this app (delete the exported db3 first, or
931
+ import into another app). Without it the import gets a new id.
932
+ `)
933
+ .action(async (dir, options) => {
934
+ const code = await importAction(dir, options);
935
+ await flushOutput();
936
+ process.exit(code);
937
+ });
938
+ // ---- Lifecycle (#4804) ----
939
+ db3
940
+ .command("create")
941
+ .description("Create a db3")
942
+ .argument("<title>", "db3 title")
943
+ .option("--type <name>", "A db3 type of the app: its current revision is installed before the db3 answers")
944
+ .option("--sync <on|off>", "off: no client ever opens the db3 over a socket (app owners and admins only)")
945
+ .option("--custodian <custodian>", '"app" or "user:<user-id>" (a member of the app)')
946
+ .option("--app <app-id>", "App ID")
947
+ .option("--json", "Output as JSON")
948
+ .addHelpText("after", `
949
+ Custody:
950
+ A member's token creates a db3 the member holds. An admin token's create is
951
+ held by the app, which no member owns, unless --custodian names a member.
952
+ `)
953
+ .action(async (title, options) => {
954
+ const sync = options.sync === undefined ? undefined : parseOnOff(options.sync, "--sync");
955
+ const custodian = options.custodian === undefined ? undefined : parseCustodianOrExit(options.custodian, "--custodian");
956
+ const resolvedAppId = resolveAppId(undefined, options);
957
+ try {
958
+ const created = await new ApiClient().createDb3(resolvedAppId, {
959
+ title,
960
+ ...(options.type !== undefined ? { type: options.type } : {}),
961
+ ...(sync !== undefined ? { sync } : {}),
962
+ ...(custodian !== undefined ? { custodian } : {}),
963
+ });
964
+ if (options.json) {
965
+ json(created);
966
+ return;
967
+ }
968
+ success("db3 created.");
969
+ printDb3(created);
970
+ }
971
+ catch (err) {
972
+ fail(err);
973
+ }
974
+ });
975
+ db3
976
+ .command("get")
977
+ .description("Show a db3, and the caller's access to it")
978
+ .argument("<db3-id>", "db3 ID")
979
+ .option("--app <app-id>", "App ID")
980
+ .option("--json", "Output as JSON")
981
+ .action(async (db3Id, options) => {
982
+ const resolvedAppId = resolveAppId(undefined, options);
983
+ try {
984
+ const row = await new ApiClient().getDb3(resolvedAppId, db3Id);
985
+ if (options.json) {
986
+ json(row);
987
+ return;
988
+ }
989
+ printDb3(row);
990
+ printResult("Created By", row.createdBy);
991
+ printResult("Created", formatDate(row.createdAt));
992
+ printResult("Modified", formatDate(row.modifiedAt));
993
+ const tags = displayTags(row.tags);
994
+ if (tags.length > 0)
995
+ printResult("Tags", tags.join(", "));
996
+ if (row.permission)
997
+ printResult("Your Permission", row.permission);
998
+ if (row.accessSource)
999
+ printResult("Access Source", row.accessSource);
1000
+ if (row.publicAccess) {
1001
+ printResult("Public Access", row.publicAccess);
1002
+ if (row.publicAccessUpdatedBy)
1003
+ printResult("Public Access Set By", row.publicAccessUpdatedBy);
1004
+ if (row.publicAccessUpdatedAt)
1005
+ printResult("Public Access Set", formatDate(row.publicAccessUpdatedAt));
1006
+ }
1007
+ }
1008
+ catch (err) {
1009
+ fail(err);
1010
+ }
1011
+ });
1012
+ db3
1013
+ .command("update")
1014
+ .description("Rename a db3")
1015
+ .argument("<db3-id>", "db3 ID")
1016
+ .requiredOption("--title <title>", "The db3's new title (at most 255 characters; stored trimmed)")
1017
+ .option("--app <app-id>", "App ID")
1018
+ .option("--json", "Output as JSON")
1019
+ .action(async (db3Id, options) => {
1020
+ const resolvedAppId = resolveAppId(undefined, options);
1021
+ try {
1022
+ const updated = await new ApiClient().updateDb3(resolvedAppId, db3Id, { title: options.title });
1023
+ if (options.json) {
1024
+ json(updated);
1025
+ return;
1026
+ }
1027
+ success("db3 updated.");
1028
+ printDb3(updated);
1029
+ }
1030
+ catch (err) {
1031
+ fail(err);
1032
+ }
1033
+ });
1034
+ db3
1035
+ .command("list")
1036
+ .description("List one custodian's db3s, oldest first, or every db3 a user reaches: held, shared with them, then app access")
1037
+ .option("--custodian <custodian>", '"app" or "user:<user-id>"')
1038
+ .option("--user-id <user-id>", "List every db3 this user reaches, one row per way, sync-off db3s included")
1039
+ .option("--via <ways>", "With --user-id: some of held, shared and app, comma-separated")
1040
+ .option("--app <app-id>", "App ID")
1041
+ .addOption(pageLimitOption())
1042
+ .addOption(pageCursorOption())
1043
+ .option("--json", "Output as JSON")
1044
+ .allowExcessArguments(false)
1045
+ .action(async (options) => {
1046
+ if ((options.custodian === undefined) === (options.userId === undefined)) {
1047
+ refuseList("db3 list takes exactly one of --custodian and --user-id.");
1048
+ }
1049
+ if (options.userId === undefined) {
1050
+ if (options.via !== undefined)
1051
+ refuseList("--via is valid only with --user-id.");
1052
+ return listByCustodian(options);
1053
+ }
1054
+ const userId = options.userId;
1055
+ if (!userId.trim() || userId.startsWith("user:"))
1056
+ refuseList("--user-id needs a bare user id.");
1057
+ const via = options.via === undefined ? undefined : parseVia(options.via);
1058
+ const limit = parsePageLimit(options.limit);
1059
+ const resolvedAppId = resolveAppId(undefined, options);
1060
+ try {
1061
+ const page = normalizeCliListEnvelope(await new ApiClient().listDb3ForUser(resolvedAppId, userId, {
1062
+ ...(via ? { via } : {}),
1063
+ ...(limit !== undefined ? { limit } : {}),
1064
+ ...(options.cursor ? { cursor: options.cursor } : {}),
1065
+ }));
1066
+ if (options.json) {
1067
+ json(page);
1068
+ return;
1069
+ }
1070
+ if (page.items.length === 0) {
1071
+ printEmptyPage(page, "db3s");
1072
+ return;
1073
+ }
1074
+ const rows = page.items.map((row) => ({
1075
+ id: row.id,
1076
+ title: row.title ?? "",
1077
+ via: row.via,
1078
+ permission: row.permission ?? "none",
1079
+ custodian: row.custodian ?? "none",
1080
+ sync: row.sync === false ? "off" : "on",
1081
+ type: row.type ?? "none",
1082
+ grantedAt: row.grantedAt,
1083
+ }));
1084
+ console.log(formatTable(rows, USER_DB3_TABLE_FIELDS.map((key) => ({
1085
+ header: USER_DB3_TABLE_HEADERS[key],
1086
+ key,
1087
+ ...(key === "title" ? { flex: true } : {}),
1088
+ ...(key === "grantedAt" ? { format: (value) => (value ? formatDate(value) : "—") } : {}),
1089
+ }))));
1090
+ printPageHint(page);
1091
+ }
1092
+ catch (err) {
1093
+ fail(err);
1094
+ }
1095
+ });
1096
+ /** `db3 list --custodian`: one custodian's db3s from the admin API (#4800). */
1097
+ async function listByCustodian(options) {
1098
+ const limit = parsePageLimit(options.limit);
1099
+ const custodian = parseCustodianOrExit(options.custodian, "--custodian");
1100
+ const resolvedAppId = resolveAppId(undefined, options);
1101
+ try {
1102
+ const page = normalizeCliListEnvelope(await new ApiClient().listDb3ByCustodian(resolvedAppId, custodian, {
1103
+ ...(limit !== undefined ? { limit } : {}),
1104
+ ...(options.cursor ? { cursor: options.cursor } : {}),
1105
+ }));
1106
+ if (options.json) {
1107
+ json(page);
1108
+ return;
1109
+ }
1110
+ if (page.items.length === 0) {
1111
+ printEmptyPage(page, "db3s");
1112
+ return;
1113
+ }
1114
+ const rows = page.items.map((row) => ({
1115
+ id: row.id,
1116
+ title: row.title ?? "",
1117
+ custodian: row.custodian ?? "none",
1118
+ sync: row.sync === false ? "off" : "on",
1119
+ type: row.type ?? "none",
1120
+ createdAt: row.createdAt,
1121
+ }));
1122
+ console.log(formatTable(rows, [
1123
+ { header: "ID", key: "id" },
1124
+ { header: "TITLE", key: "title", flex: true },
1125
+ { header: "CUSTODIAN", key: "custodian" },
1126
+ { header: "SYNC", key: "sync" },
1127
+ { header: "TYPE", key: "type" },
1128
+ { header: "CREATED", key: "createdAt", format: formatDate },
1129
+ ]));
1130
+ printPageHint(page);
1131
+ }
1132
+ catch (err) {
1133
+ fail(err);
1134
+ }
1135
+ }
1136
+ db3
1137
+ .command("delete")
1138
+ .description("Delete a db3 and all its data (records, blobs, aliases, permissions)")
1139
+ .argument("<db3-id>", "db3 ID")
1140
+ .option("--app <app-id>", "App ID")
1141
+ .option("-y, --yes", "Skip confirmation prompt")
1142
+ .option("--json", "Output as JSON")
1143
+ .action(async (db3Id, options) => {
1144
+ const resolvedAppId = resolveAppId(undefined, options);
1145
+ if (!options.yes) {
1146
+ let confirmed;
1147
+ try {
1148
+ confirmed = await confirmPrompt(`Delete db3 ${db3Id}? This permanently deletes its records, blobs, aliases and permissions.`);
1149
+ }
1150
+ catch (err) {
1151
+ error(err.message);
1152
+ process.exit(1);
1153
+ }
1154
+ if (!confirmed) {
1155
+ info("Cancelled.");
1156
+ return;
1157
+ }
1158
+ }
1159
+ try {
1160
+ const answer = await new ApiClient().deleteDb3(resolvedAppId, db3Id);
1161
+ if (options.json) {
1162
+ json(answer);
1163
+ return;
1164
+ }
1165
+ success(`db3 ${db3Id} deleted.`);
1166
+ }
1167
+ catch (err) {
1168
+ fail(err);
1169
+ }
1170
+ });
1171
+ db3
1172
+ .command("stats")
1173
+ .description("Show a db3's record/model/blob counts and size")
1174
+ .argument("<db3-id>", "db3 ID")
1175
+ .option("--app <app-id>", "App ID")
1176
+ .option("--json", "Output as JSON")
1177
+ .action(async (db3Id, options) => {
1178
+ await statsAction(DB3_ROUTES, db3Id, options);
1179
+ });
1180
+ // ---- Sync (#4799, #4804) ----
1181
+ const sync = db3.command("sync").description("Show or change whether a db3 is synced");
1182
+ sync
1183
+ .command("get")
1184
+ .description("Print on or off: whether clients open the db3 over a socket")
1185
+ .argument("<db3-id>", "db3 ID")
1186
+ .option("--app <app-id>", "App ID")
1187
+ .option("--json", "Output as JSON")
1188
+ .action(async (db3Id, options) => {
1189
+ const resolvedAppId = resolveAppId(undefined, options);
1190
+ try {
1191
+ const answer = await new ApiClient().getDb3Sync(resolvedAppId, db3Id);
1192
+ if (options.json) {
1193
+ json(answer);
1194
+ return;
1195
+ }
1196
+ console.log(answer.sync ? "on" : "off");
1197
+ }
1198
+ catch (err) {
1199
+ fail(err);
1200
+ }
1201
+ });
1202
+ sync
1203
+ .command("set")
1204
+ .description("Turn a db3's sync on or off (app owners and admins only)")
1205
+ .argument("<db3-id>", "db3 ID")
1206
+ .argument("<on|off>", "on or off")
1207
+ .option("--app <app-id>", "App ID")
1208
+ .option("--json", "Output as JSON")
1209
+ .action(async (db3Id, state, options) => {
1210
+ const on = parseOnOff(state, "The sync state");
1211
+ const resolvedAppId = resolveAppId(undefined, options);
1212
+ try {
1213
+ const answer = await new ApiClient().setDb3Sync(resolvedAppId, db3Id, on);
1214
+ if (options.json) {
1215
+ json(answer);
1216
+ return;
1217
+ }
1218
+ success(answer.changed ? `Sync is ${on ? "on" : "off"} for ${db3Id}.` : `Sync was already ${on ? "on" : "off"} for ${db3Id}.`);
1219
+ }
1220
+ catch (err) {
1221
+ fail(err);
1222
+ }
1223
+ });
1224
+ // ---- App access (#4801, #4804) ----
1225
+ const appAccess = db3.command("app-access").description("Show or change the access every user of the app holds on a db3");
1226
+ appAccess
1227
+ .command("get")
1228
+ .description("Print reader, read-write or none")
1229
+ .argument("<db3-id>", "db3 ID")
1230
+ .option("--app <app-id>", "App ID")
1231
+ .option("--json", "Output as JSON")
1232
+ .action(async (db3Id, options) => {
1233
+ const resolvedAppId = resolveAppId(undefined, options);
1234
+ try {
1235
+ const answer = await new ApiClient().getDb3AppAccess(resolvedAppId, db3Id);
1236
+ if (options.json) {
1237
+ json(answer);
1238
+ return;
1239
+ }
1240
+ console.log(answer.level ?? "none");
1241
+ }
1242
+ catch (err) {
1243
+ fail(err);
1244
+ }
1245
+ });
1246
+ appAccess
1247
+ .command("set")
1248
+ .description("Grant the db3 to every user of the app, or remove the grant with none (app owners and admins only)")
1249
+ .argument("<db3-id>", "db3 ID")
1250
+ .argument("<level>", "reader, read-write or none")
1251
+ .option("--app <app-id>", "App ID")
1252
+ .option("--json", "Output as JSON")
1253
+ .action(async (db3Id, level, options) => {
1254
+ if (!["reader", "read-write", "none"].includes(level)) {
1255
+ error('The level must be "reader", "read-write" or "none".');
1256
+ process.exit(1);
1257
+ }
1258
+ const resolvedAppId = resolveAppId(undefined, options);
1259
+ try {
1260
+ const answer = await new ApiClient().setDb3AppAccess(resolvedAppId, db3Id, level === "none" ? null : level);
1261
+ if (options.json) {
1262
+ json(answer);
1263
+ return;
1264
+ }
1265
+ success(`App access on ${db3Id}: ${answer.level ?? "none"}${answer.changed ? "" : " (unchanged)"}.`);
1266
+ }
1267
+ catch (err) {
1268
+ fail(err);
1269
+ }
1270
+ });
1271
+ // ---- Public access (#5842) ----
1272
+ const publicAccess = db3
1273
+ .command("public-access")
1274
+ .description("Change whether a db3 may be served to callers with no sharing level (app owners and admins only)");
1275
+ publicAccess
1276
+ .command("set")
1277
+ .description("Mark the db3 public with reader, or clear it with none (app owners and admins only)")
1278
+ .argument("<db3-id>", "db3 ID")
1279
+ .argument("<level>", "reader or none")
1280
+ .option("--app <app-id>", "App ID")
1281
+ .option("--json", "Output as JSON")
1282
+ .addHelpText("after", `
1283
+ Public access is not a sharing level: it lets nobody open, sync, list or read
1284
+ the db3 through a db3 route. While the app's signedOutAccess setting is on, a
1285
+ server function may serve a public db3 to any caller, signed out included.
1286
+ \`primitive db3 get\` prints the stored value.
1287
+ `)
1288
+ .action(async (db3Id, level, options) => {
1289
+ if (level !== "reader" && level !== "none") {
1290
+ error('The level must be "reader" or "none".');
1291
+ process.exit(1);
1292
+ }
1293
+ const resolvedAppId = resolveAppId(undefined, options);
1294
+ try {
1295
+ const answer = await new ApiClient().setDb3PublicAccess(resolvedAppId, db3Id, level === "none" ? null : "reader");
1296
+ if (options.json) {
1297
+ json(answer);
1298
+ return;
1299
+ }
1300
+ success(`Public access on ${db3Id}: ${answer.level ?? "none"}${answer.changed ? "" : " (unchanged)"}.`);
1301
+ if (answer.level === "reader" && answer.signedOutAccess === false) {
1302
+ info("It takes effect once the app's signedOutAccess setting is on ([app] signedOutAccess = true in app.toml).");
1303
+ }
1304
+ }
1305
+ catch (err) {
1306
+ fail(err);
1307
+ }
1308
+ });
1309
+ publicAccess
1310
+ .command("blob-url")
1311
+ .description("Print the stable public URL of a blob in a public db3 (makes no request)")
1312
+ .argument("<db3-id>", "db3 ID")
1313
+ .argument("<blob-id>", "Blob ID")
1314
+ .option("--app <app-id>", "App ID")
1315
+ .option("--json", "Output as JSON")
1316
+ .addHelpText("after", `
1317
+ Anyone can load the URL, signed in or not, while the db3 is public and the
1318
+ app's signedOutAccess setting is on; every other case answers 404. The URL
1319
+ never changes, and its answer may be cached for five minutes. In a web app,
1320
+ client.db3.publicBlobUrl(db3Id, blobId) builds the same URL.
1321
+ `)
1322
+ .action((db3Id, blobId, options) => {
1323
+ const resolvedAppId = resolveAppId(undefined, options);
1324
+ const url = publicBlobUrl(getServerUrl(), resolvedAppId, db3Id, blobId);
1325
+ if (options.json) {
1326
+ json({ url });
1327
+ return;
1328
+ }
1329
+ console.log(url);
1330
+ });
1331
+ // ---- Sharing (#5922): link access, grants, invitations, requests, effective access ----
1332
+ const linkAccess = db3.command("link-access").description("Show or change who in the app may open a db3 by its id alone");
1333
+ linkAccess
1334
+ .command("get")
1335
+ .description("Print reader, read-write or none")
1336
+ .argument("<db3-id>", "db3 ID")
1337
+ .option("--app <app-id>", "App ID")
1338
+ .option("--json", "Output as JSON")
1339
+ .action(async (db3Id, options) => {
1340
+ const resolvedAppId = resolveAppId(undefined, options);
1341
+ try {
1342
+ const answer = await new ApiClient().getDb3LinkAccess(resolvedAppId, db3Id);
1343
+ if (options.json) {
1344
+ json(answer);
1345
+ return;
1346
+ }
1347
+ console.log(answer.linkAccess ?? "none");
1348
+ }
1349
+ catch (err) {
1350
+ fail(err);
1351
+ }
1352
+ });
1353
+ linkAccess
1354
+ .command("set")
1355
+ .description("Let any member of the app with the db3's id open it at a level")
1356
+ .argument("<db3-id>", "db3 ID")
1357
+ .requiredOption("--level <level>", "reader or read-write")
1358
+ .option("--app <app-id>", "App ID")
1359
+ .option("--json", "Output as JSON")
1360
+ .action(async (db3Id, options) => {
1361
+ const level = parseSharingLevel(options.level, "--level");
1362
+ const resolvedAppId = resolveAppId(undefined, options);
1363
+ try {
1364
+ const answer = await new ApiClient().setDb3LinkAccess(resolvedAppId, db3Id, level);
1365
+ if (options.json) {
1366
+ json(answer);
1367
+ return;
1368
+ }
1369
+ success(`Link access on ${db3Id}: ${answer?.linkAccess ?? level}.`);
1370
+ }
1371
+ catch (err) {
1372
+ fail(err);
1373
+ }
1374
+ });
1375
+ linkAccess
1376
+ .command("clear")
1377
+ .description("Turn link access off; grants are untouched")
1378
+ .argument("<db3-id>", "db3 ID")
1379
+ .option("--app <app-id>", "App ID")
1380
+ .option("--json", "Output as JSON")
1381
+ .action(async (db3Id, options) => {
1382
+ const resolvedAppId = resolveAppId(undefined, options);
1383
+ try {
1384
+ const answer = await new ApiClient().clearDb3LinkAccess(resolvedAppId, db3Id);
1385
+ if (options.json) {
1386
+ json(answer);
1387
+ return;
1388
+ }
1389
+ success(`Link access on ${db3Id} cleared.`);
1390
+ }
1391
+ catch (err) {
1392
+ fail(err);
1393
+ }
1394
+ });
1395
+ const permissions = db3.command("permissions").description("List, grant and revoke users' grants on a db3");
1396
+ permissions
1397
+ .command("list")
1398
+ .description("List the users granted the db3 and their levels")
1399
+ .argument("<db3-id>", "db3 ID")
1400
+ .option("--app <app-id>", "App ID")
1401
+ .option("--json", "Output as JSON")
1402
+ .action(async (db3Id, options) => {
1403
+ const resolvedAppId = resolveAppId(undefined, options);
1404
+ try {
1405
+ const page = wholeListEnvelope(await new ApiClient().listDb3Permissions(resolvedAppId, db3Id));
1406
+ if (options.json) {
1407
+ json(page);
1408
+ return;
1409
+ }
1410
+ printSharingTable(page.items, [
1411
+ { header: "USER_ID", key: "userId" },
1412
+ { header: "EMAIL", key: "email" },
1413
+ { header: "PERMISSION", key: "permission" },
1414
+ { header: "GRANTED", key: "grantedAt", format: formatDate },
1415
+ ], "No permissions found.");
1416
+ }
1417
+ catch (err) {
1418
+ fail(err);
1419
+ }
1420
+ });
1421
+ permissions
1422
+ .command("grant")
1423
+ .description("Grant one user a level, by user ID or by email (an address not yet in the app gets a pending invitation)")
1424
+ .argument("<db3-id>", "db3 ID")
1425
+ .option("--user-id <id>", "The user's ID")
1426
+ .option("--email <email>", "The user's email address")
1427
+ .requiredOption("--permission <level>", "reader or read-write")
1428
+ .option("--send-email", "Email the user about the grant")
1429
+ .option("--url <url>", "The link the email carries (needs --send-email; defaults to the app's base URL)")
1430
+ .option("--note <text>", "A note the email carries (needs --send-email)")
1431
+ .option("--app <app-id>", "App ID")
1432
+ .option("--json", "Output as JSON")
1433
+ .action(async (db3Id, options) => {
1434
+ const target = parseUserTarget(options);
1435
+ const permission = parseSharingLevel(options.permission, "--permission");
1436
+ if (!options.sendEmail && (options.url !== undefined || options.note !== undefined)) {
1437
+ refuseList("--url and --note go in the grant's email: pass --send-email with them.");
1438
+ }
1439
+ const resolvedAppId = resolveAppId(undefined, options);
1440
+ try {
1441
+ const answer = await new ApiClient().grantDb3Permission(resolvedAppId, db3Id, { ...target, permission }, options.sendEmail
1442
+ ? {
1443
+ sendEmail: true,
1444
+ ...(options.url !== undefined ? { documentUrl: options.url } : {}),
1445
+ ...(options.note !== undefined ? { note: options.note } : {}),
1446
+ }
1447
+ : undefined);
1448
+ if (options.json) {
1449
+ json(answer);
1450
+ return;
1451
+ }
1452
+ const who = "userId" in target ? target.userId : target.email;
1453
+ const pending = (answer?.results ?? []).filter((r) => r?.status === "pending_signup");
1454
+ if (pending.length === 0) {
1455
+ success(`Granted ${permission} on ${db3Id} to ${who}.`);
1456
+ return;
1457
+ }
1458
+ for (const row of pending) {
1459
+ info(`${row.email} has not joined the app yet: the ${row.permission ?? permission} grant is pending until they sign up.`);
1460
+ printResult("Invitation", row.invitationId);
1461
+ }
1462
+ }
1463
+ catch (err) {
1464
+ fail(err);
1465
+ }
1466
+ });
1467
+ permissions
1468
+ .command("revoke")
1469
+ .description("Revoke one user's grant, by user ID or by email")
1470
+ .argument("<db3-id>", "db3 ID")
1471
+ .option("--user-id <id>", "The user's ID")
1472
+ .option("--email <email>", "The user's email address")
1473
+ .option("--app <app-id>", "App ID")
1474
+ .option("-y, --yes", "Skip confirmation prompt")
1475
+ .option("--json", "Output as JSON")
1476
+ .action(async (db3Id, options) => {
1477
+ const target = parseUserTarget(options);
1478
+ const who = "userId" in target ? target.userId : target.email;
1479
+ const resolvedAppId = resolveAppId(undefined, options);
1480
+ if (!(await confirmed(options, `Revoke ${who}'s grant on db3 ${db3Id}?`)))
1481
+ return;
1482
+ try {
1483
+ const answer = await new ApiClient().revokeDb3Permission(resolvedAppId, db3Id, target);
1484
+ if (options.json) {
1485
+ json(answer);
1486
+ return;
1487
+ }
1488
+ success(`Revoked ${who}'s grant on ${db3Id}.`);
1489
+ }
1490
+ catch (err) {
1491
+ fail(err);
1492
+ }
1493
+ });
1494
+ const groupPermissions = db3.command("group-permissions").description("List, grant and revoke groups' grants on a db3");
1495
+ groupPermissions
1496
+ .command("list")
1497
+ .description("List the groups granted the db3 and their levels")
1498
+ .argument("<db3-id>", "db3 ID")
1499
+ .option("--include-system", "Also list the grants of the platform's system groups")
1500
+ .option("--app <app-id>", "App ID")
1501
+ .option("--json", "Output as JSON")
1502
+ .action(async (db3Id, options) => {
1503
+ const resolvedAppId = resolveAppId(undefined, options);
1504
+ try {
1505
+ const page = wholeListEnvelope(await new ApiClient().listDb3GroupPermissions(resolvedAppId, db3Id, { includeSystem: options.includeSystem === true }));
1506
+ if (options.json) {
1507
+ json(page);
1508
+ return;
1509
+ }
1510
+ const rows = page.items.map((row) => ({
1511
+ ...row,
1512
+ system: typeof row.groupType === "string" && row.groupType.startsWith("_") ? "yes" : "no",
1513
+ }));
1514
+ printSharingTable(rows, [
1515
+ { header: "GROUP_ID", key: "groupId" },
1516
+ { header: "PERMISSION", key: "permission" },
1517
+ { header: "GRANTED", key: "grantedAt", format: formatDate },
1518
+ ...(options.includeSystem ? [{ header: "SYSTEM", key: "system" }] : []),
1519
+ ], "No group permissions found.");
1520
+ }
1521
+ catch (err) {
1522
+ fail(err);
1523
+ }
1524
+ });
1525
+ groupPermissions
1526
+ .command("grant")
1527
+ .description("Grant a group, by its ID, a level: every current and future member holds it")
1528
+ .argument("<db3-id>", "db3 ID")
1529
+ .requiredOption("--group-id <id>", "The group's ID")
1530
+ .requiredOption("--permission <level>", "reader or read-write")
1531
+ .option("--app <app-id>", "App ID")
1532
+ .option("--json", "Output as JSON")
1533
+ .action(async (db3Id, options) => {
1534
+ const permission = parseSharingLevel(options.permission, "--permission");
1535
+ const resolvedAppId = resolveAppId(undefined, options);
1536
+ try {
1537
+ const answer = await new ApiClient().grantDb3GroupPermission(resolvedAppId, db3Id, options.groupId, permission);
1538
+ if (options.json) {
1539
+ json(answer);
1540
+ return;
1541
+ }
1542
+ success(`Granted ${permission} on ${db3Id} to group ${options.groupId}.`);
1543
+ }
1544
+ catch (err) {
1545
+ fail(err);
1546
+ }
1547
+ });
1548
+ groupPermissions
1549
+ .command("revoke")
1550
+ .description("Revoke a group's grant")
1551
+ .argument("<db3-id>", "db3 ID")
1552
+ .argument("<group-id>", "The group's ID")
1553
+ .option("--app <app-id>", "App ID")
1554
+ .option("-y, --yes", "Skip confirmation prompt")
1555
+ .option("--json", "Output as JSON")
1556
+ .action(async (db3Id, groupId, options) => {
1557
+ const resolvedAppId = resolveAppId(undefined, options);
1558
+ if (!(await confirmed(options, `Revoke group ${groupId}'s grant on db3 ${db3Id}?`)))
1559
+ return;
1560
+ try {
1561
+ const answer = await new ApiClient().revokeDb3GroupPermission(resolvedAppId, db3Id, groupId);
1562
+ if (options.json) {
1563
+ json(answer);
1564
+ return;
1565
+ }
1566
+ success(`Revoked group ${groupId}'s grant on ${db3Id}.`);
1567
+ }
1568
+ catch (err) {
1569
+ fail(err);
1570
+ }
1571
+ });
1572
+ const pendingInvitations = db3
1573
+ .command("pending-invitations")
1574
+ .description("List and revoke grants waiting for an email address to join the app");
1575
+ pendingInvitations
1576
+ .command("list")
1577
+ .description("List the db3's pending invitations")
1578
+ .argument("<db3-id>", "db3 ID")
1579
+ .option("--app <app-id>", "App ID")
1580
+ .option("--json", "Output as JSON")
1581
+ .action(async (db3Id, options) => {
1582
+ const resolvedAppId = resolveAppId(undefined, options);
1583
+ try {
1584
+ const answer = await new ApiClient().listDb3PendingInvitations(resolvedAppId, db3Id);
1585
+ const page = wholeListEnvelope(answer?.items);
1586
+ if (options.json) {
1587
+ json(page);
1588
+ return;
1589
+ }
1590
+ printSharingTable(page.items, [
1591
+ { header: "INVITATION_ID", key: "invitationId" },
1592
+ { header: "EMAIL", key: "email" },
1593
+ { header: "PERMISSION", key: "permission" },
1594
+ { header: "INVITED", key: "createdAt", format: formatDate },
1595
+ { header: "EXPIRES", key: "expiresAt", format: formatDate },
1596
+ ], "No pending invitations found.");
1597
+ }
1598
+ catch (err) {
1599
+ fail(err);
1600
+ }
1601
+ });
1602
+ pendingInvitations
1603
+ .command("revoke")
1604
+ .description("Cancel a pending invitation's grants on this db3; the app invitation and its other shares stay")
1605
+ .argument("<db3-id>", "db3 ID")
1606
+ .argument("<invitation-id>", "The invitation's ID, from pending-invitations list")
1607
+ .option("--app <app-id>", "App ID")
1608
+ .option("-y, --yes", "Skip confirmation prompt")
1609
+ .option("--json", "Output as JSON")
1610
+ .action(async (db3Id, invitationId, options) => {
1611
+ const resolvedAppId = resolveAppId(undefined, options);
1612
+ if (!(await confirmed(options, `Revoke pending invitation ${invitationId} on db3 ${db3Id}?`)))
1613
+ return;
1614
+ try {
1615
+ const answer = await new ApiClient().revokeDb3PendingInvitation(resolvedAppId, db3Id, invitationId);
1616
+ if (options.json) {
1617
+ json(answer);
1618
+ return;
1619
+ }
1620
+ success(`Revoked the pending invitation for ${answer?.email ?? invitationId} on ${db3Id}.`);
1621
+ }
1622
+ catch (err) {
1623
+ fail(err);
1624
+ }
1625
+ });
1626
+ const accessRequests = db3.command("access-requests").description("List, file and resolve requests for access to a db3");
1627
+ accessRequests
1628
+ .command("list")
1629
+ .description("List the db3's pending access requests")
1630
+ .argument("<db3-id>", "db3 ID")
1631
+ .option("--app <app-id>", "App ID")
1632
+ .option("--json", "Output as JSON")
1633
+ .action(async (db3Id, options) => {
1634
+ const resolvedAppId = resolveAppId(undefined, options);
1635
+ try {
1636
+ const page = wholeListEnvelope(await new ApiClient().listDb3AccessRequests(resolvedAppId, db3Id));
1637
+ if (options.json) {
1638
+ json(page);
1639
+ return;
1640
+ }
1641
+ printSharingTable(page.items.map((row) => ({ ...row, message: row.message ?? "" })), [
1642
+ { header: "REQUEST_ID", key: "requestId" },
1643
+ { header: "REQUESTER", key: "requesterId" },
1644
+ { header: "PERMISSION", key: "requestedPermission" },
1645
+ { header: "MESSAGE", key: "message" },
1646
+ { header: "CREATED", key: "createdAt", format: formatDate },
1647
+ ], "No access requests found.");
1648
+ }
1649
+ catch (err) {
1650
+ fail(err);
1651
+ }
1652
+ });
1653
+ accessRequests
1654
+ .command("create")
1655
+ .description("Ask the db3's owners for access as the signed-in user (a member's login; an admin already has access)")
1656
+ .argument("<db3-id>", "db3 ID")
1657
+ .requiredOption("--permission <level>", "reader or read-write")
1658
+ .option("--message <text>", "A message to the owners")
1659
+ .option("--url <url>", "The link the owners' email carries")
1660
+ .option("--review-url <url>", "The link to review the request (defaults to --url)")
1661
+ .option("--no-send-email", "Do not email the owners")
1662
+ .option("--app <app-id>", "App ID")
1663
+ .option("--json", "Output as JSON")
1664
+ .action(async (db3Id, options) => {
1665
+ const permission = parseSharingLevel(options.permission, "--permission");
1666
+ const resolvedAppId = resolveAppId(undefined, options);
1667
+ try {
1668
+ const { answer, created } = await new ApiClient().createDb3AccessRequest(resolvedAppId, db3Id, {
1669
+ permission,
1670
+ ...(options.message !== undefined ? { message: options.message } : {}),
1671
+ ...(options.url !== undefined ? { documentUrl: options.url } : {}),
1672
+ ...(options.reviewUrl !== undefined ? { reviewUrl: options.reviewUrl } : {}),
1673
+ ...(options.sendEmail === false ? { sendEmail: false } : {}),
1674
+ });
1675
+ if (options.json) {
1676
+ json(answer);
1677
+ return;
1678
+ }
1679
+ success(created
1680
+ ? `Access request created for ${permission} on ${db3Id}.`
1681
+ : `Your pending access request on ${db3Id} was updated to ${permission}.`);
1682
+ printResult("Request", answer?.request?.requestId);
1683
+ }
1684
+ catch (err) {
1685
+ fail(err);
1686
+ }
1687
+ });
1688
+ accessRequests
1689
+ .command("approve")
1690
+ .description("Approve a request: grants the requested level, or --permission")
1691
+ .argument("<db3-id>", "db3 ID")
1692
+ .argument("<request-id>", "The request's ID, from access-requests list")
1693
+ .option("--permission <level>", "reader or read-write, in place of the requested level")
1694
+ .option("--url <url>", "The link the requester's email carries")
1695
+ .option("--app <app-id>", "App ID")
1696
+ .option("--json", "Output as JSON")
1697
+ .action(async (db3Id, requestId, options) => {
1698
+ const permission = options.permission !== undefined ? parseSharingLevel(options.permission, "--permission") : undefined;
1699
+ const resolvedAppId = resolveAppId(undefined, options);
1700
+ try {
1701
+ const answer = await new ApiClient().approveDb3AccessRequest(resolvedAppId, db3Id, requestId, {
1702
+ ...(permission !== undefined ? { permission } : {}),
1703
+ ...(options.url !== undefined ? { documentUrl: options.url } : {}),
1704
+ });
1705
+ if (options.json) {
1706
+ json(answer);
1707
+ return;
1708
+ }
1709
+ success(`Approved request ${requestId}: granted ${answer?.request?.grantedPermission ?? permission ?? "the requested level"} on ${db3Id}.`);
1710
+ }
1711
+ catch (err) {
1712
+ fail(err);
1713
+ }
1714
+ });
1715
+ accessRequests
1716
+ .command("deny")
1717
+ .description("Deny a request; the requester may ask again")
1718
+ .argument("<db3-id>", "db3 ID")
1719
+ .argument("<request-id>", "The request's ID, from access-requests list")
1720
+ .option("--url <url>", "The link the requester's email carries")
1721
+ .option("--app <app-id>", "App ID")
1722
+ .option("--json", "Output as JSON")
1723
+ .action(async (db3Id, requestId, options) => {
1724
+ const resolvedAppId = resolveAppId(undefined, options);
1725
+ try {
1726
+ const answer = await new ApiClient().denyDb3AccessRequest(resolvedAppId, db3Id, requestId, options.url !== undefined ? { documentUrl: options.url } : {});
1727
+ if (options.json) {
1728
+ json(answer);
1729
+ return;
1730
+ }
1731
+ success(`Denied request ${requestId} on ${db3Id}.`);
1732
+ }
1733
+ catch (err) {
1734
+ fail(err);
1735
+ }
1736
+ });
1737
+ const access = db3.command("access").description("Show a user's effective access to a db3");
1738
+ access
1739
+ .command("get")
1740
+ .description("Show a user's level on the db3 and where it comes from: a grant, a group, the link, app access or ownership")
1741
+ .argument("<db3-id>", "db3 ID")
1742
+ .requiredOption("--user-id <id>", "The user's ID")
1743
+ .option("--app <app-id>", "App ID")
1744
+ .option("--json", "Output as JSON")
1745
+ .action(async (db3Id, options) => {
1746
+ const resolvedAppId = resolveAppId(undefined, options);
1747
+ try {
1748
+ const answer = await new ApiClient().validateDb3AccessForUser(resolvedAppId, db3Id, options.userId);
1749
+ const row = {
1750
+ db3Id,
1751
+ userId: options.userId,
1752
+ hasAccess: answer?.hasAccess === true,
1753
+ permission: answer?.permission ?? null,
1754
+ accessSource: answer?.accessSource ?? null,
1755
+ appRole: answer?.appRole ?? null,
1756
+ };
1757
+ if (options.json) {
1758
+ json(row);
1759
+ return;
1760
+ }
1761
+ console.log(formatTable([{ ...row, hasAccess: String(row.hasAccess), permission: row.permission ?? "-", accessSource: row.accessSource ?? "-", appRole: row.appRole ?? "-" }], [
1762
+ { header: "DB3", key: "db3Id" },
1763
+ { header: "USER", key: "userId" },
1764
+ { header: "ACCESS", key: "hasAccess" },
1765
+ { header: "PERMISSION", key: "permission" },
1766
+ { header: "SOURCE", key: "accessSource" },
1767
+ { header: "APP_ROLE", key: "appRole" },
1768
+ ]));
1769
+ if (!row.hasAccess)
1770
+ info(`${row.userId} has no access to ${db3Id}.`);
1771
+ }
1772
+ catch (err) {
1773
+ fail(err);
1774
+ }
1775
+ });
1776
+ // ---- Custody (#4800, #4804): through the admin API ----
1777
+ db3
1778
+ .command("transfer")
1779
+ .description("Transfer a db3 to another user or to the app")
1780
+ .argument("<db3-id>", "db3 ID")
1781
+ .argument("<custodian>", '"user:<user-id>" (a member of the app) or "app"')
1782
+ .option("--app <app-id>", "App ID")
1783
+ .option("--json", "Output as JSON")
1784
+ .allowExcessArguments(false)
1785
+ .addHelpText("after", `
1786
+ The custodian and the owner row move together: a user custodian holds the
1787
+ owner row and the previous owner keeps read-write; moving to the app deletes
1788
+ every owner row. No other grant changes.
1789
+ `)
1790
+ .action(async (db3Id, custodianArg, options) => {
1791
+ const to = parseCustodianOrExit(custodianArg, "custodian");
1792
+ const resolvedAppId = resolveAppId(undefined, options);
1793
+ try {
1794
+ const answer = await new ApiClient().transferDb3(resolvedAppId, db3Id, to);
1795
+ if (options.json) {
1796
+ json(answer);
1797
+ return;
1798
+ }
1799
+ success(`db3 ${db3Id} transferred.`);
1800
+ printResult("Custodian", answer.custodian);
1801
+ }
1802
+ catch (err) {
1803
+ fail(err);
1804
+ }
1805
+ });
1806
+ const ownerRow = db3.command("owner-row").description("Remove or restore the owner row of the user who holds a db3");
1807
+ ownerRow
1808
+ .command("set")
1809
+ .description("present restores the custodian user's owner row, absent removes it; the custodian stays")
1810
+ .argument("<db3-id>", "db3 ID")
1811
+ .argument("<present|absent>", "present or absent")
1812
+ .option("--app <app-id>", "App ID")
1813
+ .option("--json", "Output as JSON")
1814
+ .action(async (db3Id, state, options) => {
1815
+ if (state !== "present" && state !== "absent") {
1816
+ error('The owner row must be "present" or "absent".');
1817
+ process.exit(1);
1818
+ }
1819
+ const resolvedAppId = resolveAppId(undefined, options);
1820
+ try {
1821
+ const answer = await new ApiClient().setDb3OwnerRow(resolvedAppId, db3Id, state === "present");
1822
+ if (options.json) {
1823
+ json(answer);
1824
+ return;
1825
+ }
1826
+ printResult("Custodian", answer.custodian);
1827
+ printResult("Owner row", answer.ownerRow ? "present" : "absent");
1828
+ printResult("Changed", answer.changed ? "yes" : "no");
1829
+ }
1830
+ catch (err) {
1831
+ fail(err);
1832
+ }
1833
+ });
1834
+ }
1835
+ /** What to do about a refused create of the import's db3 (#4921), after the refusal itself. */
1836
+ function createRefusalAdvice(code) {
1837
+ switch (code) {
1838
+ case "DB3_ID_EXISTS":
1839
+ return " This app holds the export's id: delete that db3 first, import into another app, or import without --keep-id.";
1840
+ case "DB3_CREATE_IN_PROGRESS":
1841
+ return " Another create of this id is running: try again shortly.";
1842
+ case "DB3_ID_INVALID":
1843
+ return " The manifest's id is not a ULID this server accepts: import without --keep-id.";
1844
+ case "DB3_ID_NOT_ALLOWED":
1845
+ return " Keeping an id needs an app owner or admin: log in as one, or import without --keep-id.";
1846
+ default:
1847
+ return "";
1848
+ }
1849
+ }
1850
+ /** `db3 import`: the reads, the plan, then the writes; answers the exit code. */
1851
+ async function importAction(dir, options) {
1852
+ const resolvedAppId = resolveAppId(undefined, options);
1853
+ const client = new ApiClient();
1854
+ const root = path.resolve(dir);
1855
+ try {
1856
+ const manifest = readDb3Manifest(root);
1857
+ if (!manifest) {
1858
+ error(`${root} holds no db3.json, so it is not a \`db3 export\` directory. ` +
1859
+ "Load a directory of rows into an existing db3 with `primitive db3 ingest <db3-id> --input <dir>`.");
1860
+ return 1;
1861
+ }
1862
+ const flags = {
1863
+ ...(options.into ? { into: String(options.into) } : {}),
1864
+ ...(options.title !== undefined ? { title: String(options.title) } : {}),
1865
+ ...(options.type !== undefined ? { type: String(options.type) } : {}),
1866
+ untyped: Boolean(options.untyped),
1867
+ noBlobs: options.blobs === false,
1868
+ keepId: Boolean(options.keepId),
1869
+ };
1870
+ if (flags.keepId && flags.into) {
1871
+ const refused = planDb3Import(manifest, flags, { blobCount: 0 });
1872
+ if ("refusal" in refused)
1873
+ error(refused.refusal);
1874
+ return 1;
1875
+ }
1876
+ // Every read before any write.
1877
+ const blobs = flags.noBlobs ? [] : readExportedBlobs(root);
1878
+ const facts = { blobCount: blobs.length };
1879
+ const named = resolvedTypeName(manifest, flags);
1880
+ if (named && !flags.untyped) {
1881
+ try {
1882
+ facts.type = await client.getDb3TypeConfig(resolvedAppId, named);
1883
+ }
1884
+ catch (err) {
1885
+ if (err?.statusCode !== 404)
1886
+ throw err;
1887
+ facts.type = null;
1888
+ }
1889
+ }
1890
+ if (flags.into) {
1891
+ const row = await client.getDb3(resolvedAppId, flags.into);
1892
+ let declaredModels = [];
1893
+ if (row?.type) {
1894
+ const targetType = facts.type?.name === row.type ? facts.type : await client.getDb3TypeConfig(resolvedAppId, String(row.type));
1895
+ declaredModels = declaredModelNames(targetType?.schema);
1896
+ }
1897
+ const declaration = declarationOfSchemaAnswer(await client.getDb3Schema(resolvedAppId, flags.into), { declaredModels });
1898
+ const listed = await client.listDb3Indexes(resolvedAppId, flags.into);
1899
+ facts.target = { row, declaration, indexes: listed?.indexes ?? [] };
1900
+ }
1901
+ // One read of the source's id, for the blobs and for --keep-id alike.
1902
+ if (blobs.length > 0 || flags.keepId) {
1903
+ try {
1904
+ await client.getDb3(resolvedAppId, manifest.id);
1905
+ facts.sourceExists = true;
1906
+ }
1907
+ catch (err) {
1908
+ if (err?.statusCode !== 404)
1909
+ throw err;
1910
+ facts.sourceExists = false;
1911
+ }
1912
+ }
1913
+ const plan = planDb3Import(manifest, flags, facts);
1914
+ if ("refusal" in plan) {
1915
+ error(plan.refusal);
1916
+ for (const line of plan.lines ?? [])
1917
+ console.error(` ${line}`);
1918
+ return 1;
1919
+ }
1920
+ for (const note of plan.notes)
1921
+ info(note);
1922
+ let db3Id;
1923
+ let created = false;
1924
+ if (plan.into) {
1925
+ if (!options.yes) {
1926
+ let confirmed;
1927
+ try {
1928
+ confirmed = await confirmPrompt(`Load the export's rows into db3 ${plan.into}? Rows with an id it already holds are replaced.`);
1929
+ }
1930
+ catch (err) {
1931
+ error(err.message);
1932
+ return 1;
1933
+ }
1934
+ if (!confirmed) {
1935
+ info("Nothing was written.");
1936
+ return 1;
1937
+ }
1938
+ }
1939
+ db3Id = plan.into;
1940
+ }
1941
+ else {
1942
+ let row;
1943
+ try {
1944
+ row = await client.createDb3(resolvedAppId, plan.create);
1945
+ }
1946
+ catch (err) {
1947
+ error(`${describeRecordsFailure(err)}${createRefusalAdvice(err?.code)} Nothing was written.`);
1948
+ return 1;
1949
+ }
1950
+ db3Id = row.id;
1951
+ created = true;
1952
+ if (!options.json)
1953
+ success(`Created db3 ${db3Id}${plan.typeName ? ` of type ${plan.typeName}` : ""}.`);
1954
+ }
1955
+ let register = plan.register;
1956
+ if (created && plan.typeName && register.length > 0) {
1957
+ // A typed db3 has its type's indexes from the create: register only what they leave out.
1958
+ const pending = pendingRegistrations(register, (await client.listDb3Indexes(resolvedAppId, db3Id))?.indexes ?? []);
1959
+ if (pending.conflicts.length) {
1960
+ error(`The export's indexes clash with type ${plan.typeName}'s by name; db3 ${db3Id} was created and holds no rows.`);
1961
+ for (const line of pending.conflicts)
1962
+ console.error(` ${line}`);
1963
+ return 1;
1964
+ }
1965
+ register = pending.register;
1966
+ }
1967
+ for (const registration of register) {
1968
+ try {
1969
+ await client.registerDb3Index(resolvedAppId, db3Id, registration);
1970
+ }
1971
+ catch (err) {
1972
+ // A refused registration prints in the CLI's words (#5890), as `indexes register` prints it.
1973
+ if (!err?.statusCode || typeof err?.message !== "string")
1974
+ throw err;
1975
+ const reworded = { message: db3IndexRefusalSentence(err.message, err.code, "--set-elements"), code: err.code, statusCode: err.statusCode, status: err.status };
1976
+ error(describeRecordsFailure(reworded));
1977
+ return 1;
1978
+ }
1979
+ }
1980
+ const outcome = await loadDb3Rows(client, resolvedAppId, db3Id, root, (line) => info(line), manifest.declaration);
1981
+ const session = outcome?.session ?? null;
1982
+ if (outcome && outcome.exitCode !== 0) {
1983
+ if (outcome.message)
1984
+ error(outcome.message);
1985
+ if (options.json)
1986
+ json({ id: db3Id, created, keptId: flags.keepId, session, exitCode: outcome.exitCode });
1987
+ return 1;
1988
+ }
1989
+ const refusedRows = Number(session?.refusedRows ?? 0);
1990
+ let blobsUploaded = 0;
1991
+ if (plan.blobs) {
1992
+ for (const blob of blobs) {
1993
+ const data = fs.readFileSync(path.join(root, "blobs", `${blob.blobId}.bin`));
1994
+ try {
1995
+ await client.uploadDb3Blob(resolvedAppId, db3Id, blob.blobId, data, {
1996
+ filename: blob.filename,
1997
+ contentType: blob.contentType,
1998
+ sha256: blob.sha256,
1999
+ });
2000
+ }
2001
+ catch (err) {
2002
+ error(`Blob ${blob.blobId} could not be uploaded under its id: ${describeRecordsFailure(err)}. The rows are loaded into db3 ${db3Id}.`);
2003
+ return 1;
2004
+ }
2005
+ blobsUploaded++;
2006
+ }
2007
+ }
2008
+ if (options.json) {
2009
+ json({
2010
+ id: db3Id,
2011
+ created,
2012
+ keptId: flags.keepId,
2013
+ type: plan.typeName,
2014
+ registered: register.length,
2015
+ rows: session?.rows ?? 0,
2016
+ refusedRows,
2017
+ session,
2018
+ blobs: blobsUploaded,
2019
+ });
2020
+ }
2021
+ else {
2022
+ printResult("db3", db3Id);
2023
+ printResult("Rows", session?.rows ?? 0);
2024
+ printResult("Indexes registered", register.length);
2025
+ printResult("Blobs", plan.blobs ? blobsUploaded : "none");
2026
+ }
2027
+ if (refusedRows > 0) {
2028
+ error(`The load refused ${refusedRows} row(s). List them with \`primitive db3 inspect ${db3Id} --refused ${session?.sessionId}\`.`);
2029
+ return 1;
2030
+ }
2031
+ return 0;
2032
+ }
2033
+ catch (err) {
2034
+ error(err?.statusCode ? describeRecordsFailure(err) : err?.message ?? String(err));
2035
+ return 1;
2036
+ }
2037
+ }
2038
+ /**
2039
+ * The public blob route's URL, as `client.db3.publicBlobUrl` builds it: the
2040
+ * API host, then `/app/<appId>/api/public/db3/<db3Id>/blobs/<blobId>` with
2041
+ * every id percent-encoded.
2042
+ *
2043
+ * @param apiUrl - The environment's API host.
2044
+ * @param appId - The app.
2045
+ * @param db3Id - The public db3.
2046
+ * @param blobId - The blob.
2047
+ * @returns The URL.
2048
+ */
2049
+ export function publicBlobUrl(apiUrl, appId, db3Id, blobId) {
2050
+ const base = apiUrl.replace(/\/+$/, "");
2051
+ return `${base}/app/${encodeURIComponent(appId)}/api/public/db3/${encodeURIComponent(db3Id)}/blobs/${encodeURIComponent(blobId)}`;
2052
+ }
2053
+ //# sourceMappingURL=db3.js.map