@gusto/baerly-storage 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -511
  3. package/dist/CHANGELOG.md +1148 -307
  4. package/dist/RECIPES.md +398 -80
  5. package/dist/THIRD-PARTY-LICENSES.txt +5 -26
  6. package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
  7. package/dist/app-config.d.ts +31 -1
  8. package/dist/app-config.js +1 -2
  9. package/dist/app-config.js.map +1 -1
  10. package/dist/auth.d.ts +33 -28
  11. package/dist/auth.js +549 -985
  12. package/dist/auth.js.map +1 -1
  13. package/dist/baerly.js +130 -138
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +97 -22
  16. package/dist/capacity-warning-header-BlVopyiI.js +16 -0
  17. package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
  18. package/dist/{client-Fe8CwB73.d.ts → client-CHQTXpef.d.ts} +121 -36
  19. package/dist/client-react.d.ts +67 -20
  20. package/dist/client-react.js +240 -54
  21. package/dist/client-react.js.map +1 -1
  22. package/dist/client.d.ts +5 -4
  23. package/dist/client.js +51 -16
  24. package/dist/client.js.map +1 -1
  25. package/dist/{cloudflare-DzKBrUlg.js → cloudflare-CKHYXccw.js} +504 -124
  26. package/dist/cloudflare-CKHYXccw.js.map +1 -0
  27. package/dist/cloudflare.d.ts +106 -71
  28. package/dist/cloudflare.js +334 -271
  29. package/dist/cloudflare.js.map +1 -1
  30. package/dist/code-resolution-CL_7L0wS.js +22 -0
  31. package/dist/code-resolution-CL_7L0wS.js.map +1 -0
  32. package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
  33. package/dist/config-DEzInG6M.js +4035 -0
  34. package/dist/config-DEzInG6M.js.map +1 -0
  35. package/dist/constants-D3GSH3tc.js +469 -0
  36. package/dist/constants-D3GSH3tc.js.map +1 -0
  37. package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
  38. package/dist/context-rlpSnHFA.js.map +1 -0
  39. package/dist/cost-B52llVDx.js +330 -0
  40. package/dist/cost-B52llVDx.js.map +1 -0
  41. package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
  42. package/dist/current-json-CC6lE4Aj.js.map +1 -0
  43. package/dist/db-plFUNTSF.d.ts +130 -0
  44. package/dist/db-read-seams-BSs0m1z1.js +3261 -0
  45. package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
  46. package/dist/{deploy-DonTr-CV.js → deploy-Obj4nE-Z.js} +12 -16
  47. package/dist/deploy-Obj4nE-Z.js.map +1 -0
  48. package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
  49. package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
  50. package/dist/dev-landing-CD-si4dW.js +50 -0
  51. package/dist/dev-landing-CD-si4dW.js.map +1 -0
  52. package/dist/dev-vite.d.ts +38 -39
  53. package/dist/dev-vite.js +67 -36
  54. package/dist/dev-vite.js.map +1 -1
  55. package/dist/dev.d.ts +3 -2
  56. package/dist/dev.js +2 -1
  57. package/dist/doctor-BA0i-YAN.js +270 -0
  58. package/dist/doctor-BA0i-YAN.js.map +1 -0
  59. package/dist/dump-D1vX8ozg.js +133 -0
  60. package/dist/dump-D1vX8ozg.js.map +1 -0
  61. package/dist/errors-7Rk1HGCE.js +160 -0
  62. package/dist/errors-7Rk1HGCE.js.map +1 -0
  63. package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
  64. package/dist/export-BVL2EvYE.js.map +1 -0
  65. package/dist/fsck-BWkPgov4.js +145 -0
  66. package/dist/fsck-BWkPgov4.js.map +1 -0
  67. package/dist/gcs-admin-Dso1HWQj.d.ts +127 -0
  68. package/dist/gcs.d.ts +30 -0
  69. package/dist/gcs.js +1 -0
  70. package/dist/goog4-signer-CeLIABoE.js +331 -0
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-DGd5tbNs.js → http-Z5rZyYMX.js} +898 -271
  73. package/dist/http-Z5rZyYMX.js.map +1 -0
  74. package/dist/http-transport-DNUM8kU-.js +1299 -0
  75. package/dist/http-transport-DNUM8kU-.js.map +1 -0
  76. package/dist/http.d.ts +366 -294
  77. package/dist/http.js +2 -2
  78. package/dist/index-JJrIu1pO.d.ts +135 -0
  79. package/dist/index-LEgHN0qJ.d.ts +50 -0
  80. package/dist/{index-CuA9Mi3K.d.ts → index-RiEYj8t0.d.ts} +291 -78
  81. package/dist/index.d.ts +27 -6
  82. package/dist/index.js +3 -5
  83. package/dist/inspect-BTsVYZKd.js +196 -0
  84. package/dist/inspect-BTsVYZKd.js.map +1 -0
  85. package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
  86. package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
  87. package/dist/ledger-Dj_bGgo0.js +192 -0
  88. package/dist/ledger-Dj_bGgo0.js.map +1 -0
  89. package/dist/legacy-names-DgZBtgOh.js +47 -0
  90. package/dist/legacy-names-DgZBtgOh.js.map +1 -0
  91. package/dist/log-C9W15Dfo.d.ts +94 -0
  92. package/dist/log-tail-DWJbneBF.js +142 -0
  93. package/dist/log-tail-DWJbneBF.js.map +1 -0
  94. package/dist/log-walk-C-vA-WGJ.js +111 -0
  95. package/dist/log-walk-C-vA-WGJ.js.map +1 -0
  96. package/dist/maintenance-Dd-Yakqj.js +1709 -0
  97. package/dist/maintenance-Dd-Yakqj.js.map +1 -0
  98. package/dist/maintenance-DevB6z4e.js +2237 -0
  99. package/dist/maintenance-DevB6z4e.js.map +1 -0
  100. package/dist/maintenance.d.ts +100 -3
  101. package/dist/maintenance.js +1 -3
  102. package/dist/node.d.ts +130 -142
  103. package/dist/node.js +4 -3
  104. package/dist/{observability-BmflLCdF.js → observability-C-ISCCLE.js} +1275 -332
  105. package/dist/observability-C-ISCCLE.js.map +1 -0
  106. package/dist/observability.d.ts +27 -3
  107. package/dist/observability.js +3 -3
  108. package/dist/path-segment-DBXG26PW.js +363 -0
  109. package/dist/path-segment-DBXG26PW.js.map +1 -0
  110. package/dist/{plan-a7PJHBCy.js → plan-BvQbaNMe.js} +19 -11
  111. package/dist/plan-BvQbaNMe.js.map +1 -0
  112. package/dist/request-CRWiTrza.js +272 -0
  113. package/dist/request-CRWiTrza.js.map +1 -0
  114. package/dist/restore-U6Im8V1V.js +1467 -0
  115. package/dist/restore-U6Im8V1V.js.map +1 -0
  116. package/dist/retry-OBtLB2GC.js +126 -0
  117. package/dist/retry-OBtLB2GC.js.map +1 -0
  118. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  119. package/dist/{runtime-spec-Dsw2-n8S.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DBC_wiCL.d.ts} +18 -10
  122. package/dist/s3.d.ts +20 -7
  123. package/dist/s3.js +4 -5
  124. package/dist/s3.js.map +1 -1
  125. package/dist/sha256-4FfGQNPw.js +22 -0
  126. package/dist/sha256-4FfGQNPw.js.map +1 -0
  127. package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
  128. package/dist/shared-secret-Vkur-8r0.js.map +1 -0
  129. package/dist/sigv4-sign-5IUflUD_.js +507 -0
  130. package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
  131. package/dist/snapshot-CknzkDM0.js +148 -0
  132. package/dist/snapshot-CknzkDM0.js.map +1 -0
  133. package/dist/{src-BL_JoPTn.js → src-Actga-bO.js} +1004 -378
  134. package/dist/src-Actga-bO.js.map +1 -0
  135. package/dist/src-D0MQfvOp.js +812 -0
  136. package/dist/src-D0MQfvOp.js.map +1 -0
  137. package/dist/src-Dr9uo3dc.js +501 -0
  138. package/dist/src-Dr9uo3dc.js.map +1 -0
  139. package/dist/{subcommand-DoDA-K7d.js → subcommand-BLoF66dG.js} +89 -16
  140. package/dist/subcommand-BLoF66dG.js.map +1 -0
  141. package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
  142. package/dist/time-DRxTP9iv.js.map +1 -0
  143. package/dist/types-suVbsEWS.d.ts +116 -0
  144. package/dist/{usage-DBV1eQHC.js → usage-CPzVhrQr.js} +40 -45
  145. package/dist/usage-CPzVhrQr.js.map +1 -0
  146. package/dist/uuid-BuT_c404.js +333 -0
  147. package/dist/uuid-BuT_c404.js.map +1 -0
  148. package/dist/verifier-Bmlmndzo.d.ts +95 -0
  149. package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
  150. package/dist/wire-DndvKU-K.js.map +1 -0
  151. package/package.json +96 -69
  152. package/dist/aws4fetch.esm-p7eEzLCs.js +0 -1702
  153. package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
  154. package/dist/bytes-BXdamO3L.js +0 -11
  155. package/dist/bytes-BXdamO3L.js.map +0 -1
  156. package/dist/cloudflare-DzKBrUlg.js.map +0 -1
  157. package/dist/config-1tv0-Yzm.js +0 -2693
  158. package/dist/config-1tv0-Yzm.js.map +0 -1
  159. package/dist/constants-CfeMWQWk.js +0 -222
  160. package/dist/constants-CfeMWQWk.js.map +0 -1
  161. package/dist/context-DRZ3tZ5l.js.map +0 -1
  162. package/dist/cost-DSMIVqzL.js +0 -203
  163. package/dist/cost-DSMIVqzL.js.map +0 -1
  164. package/dist/current-json-C6nhPOm1.js.map +0 -1
  165. package/dist/db-DsPkOVEH.d.ts +0 -254
  166. package/dist/deploy-DonTr-CV.js.map +0 -1
  167. package/dist/doctor-DSIyCDg_.js +0 -346
  168. package/dist/doctor-DSIyCDg_.js.map +0 -1
  169. package/dist/dump-Bh5k26VQ.js +0 -94
  170. package/dist/dump-Bh5k26VQ.js.map +0 -1
  171. package/dist/errors-Dfa3p78c.js +0 -78
  172. package/dist/errors-Dfa3p78c.js.map +0 -1
  173. package/dist/export-DtF5tDIM.js +0 -401
  174. package/dist/export-DtF5tDIM.js.map +0 -1
  175. package/dist/fsck-D_djMO5D.js +0 -279
  176. package/dist/fsck-D_djMO5D.js.map +0 -1
  177. package/dist/http-DGd5tbNs.js.map +0 -1
  178. package/dist/index-0rZcMBwy.d.ts +0 -115
  179. package/dist/index-BNRh23K9.d.ts +0 -162
  180. package/dist/index-BYk9oCNf.d.ts +0 -1112
  181. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  182. package/dist/inspect-6WZ-pC7-.js +0 -133
  183. package/dist/inspect-6WZ-pC7-.js.map +0 -1
  184. package/dist/log-tail-D98U1JBo.js +0 -522
  185. package/dist/log-tail-D98U1JBo.js.map +0 -1
  186. package/dist/maintenance-B4Dki6Ig.js +0 -2157
  187. package/dist/maintenance-B4Dki6Ig.js.map +0 -1
  188. package/dist/maintenance-B_e0T99L.d.ts +0 -537
  189. package/dist/maintenance-C7coQp4c.js +0 -1418
  190. package/dist/maintenance-C7coQp4c.js.map +0 -1
  191. package/dist/normalize-rjnZLwS4.js +0 -133
  192. package/dist/normalize-rjnZLwS4.js.map +0 -1
  193. package/dist/observability-BmflLCdF.js.map +0 -1
  194. package/dist/plan-a7PJHBCy.js.map +0 -1
  195. package/dist/query-rAtXNQQB.js +0 -1773
  196. package/dist/query-rAtXNQQB.js.map +0 -1
  197. package/dist/rebuild-index-BVzQSZlm.js +0 -81
  198. package/dist/rebuild-index-BVzQSZlm.js.map +0 -1
  199. package/dist/request-u0M51mhJ.js +0 -72
  200. package/dist/request-u0M51mhJ.js.map +0 -1
  201. package/dist/restore-R-4rbciV.js +0 -778
  202. package/dist/restore-R-4rbciV.js.map +0 -1
  203. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  204. package/dist/runtime-spec-Dsw2-n8S.js.map +0 -1
  205. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  206. package/dist/src-BL_JoPTn.js.map +0 -1
  207. package/dist/src-CYHFDrKz.js +0 -536
  208. package/dist/src-CYHFDrKz.js.map +0 -1
  209. package/dist/src-DYZ4H1aF.js +0 -392
  210. package/dist/src-DYZ4H1aF.js.map +0 -1
  211. package/dist/subcommand-DoDA-K7d.js.map +0 -1
  212. package/dist/time-DUqvFMHq.js.map +0 -1
  213. package/dist/usage-DBV1eQHC.js.map +0 -1
  214. package/dist/validate-DtljsCh1.js.map +0 -1
  215. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-Dr9uo3dc.js","names":[],"sources":["../packages/protocol/src/env.ts","../packages/protocol/src/storage/memory.ts","../packages/server/src/indexes.ts","../packages/server/src/config.ts","../packages/server/src/collection.ts","../packages/server/src/db.ts"],"sourcesContent":["// Deployment detection shared by the in-memory storage guard and the\n// Node resolveStorageFromEnv resolver. Pure (env passed in) so it stays\n// Workerd-loadable. Markers are vars each platform sets unconditionally:\n// Cloud Run, Heroku, Kubernetes, ECS, Railway, Render, Fly.\n//\n// The list is deliberately conservative: every marker here is set ONLY by\n// the platform at runtime, never by that platform's local dev emulator, so\n// detection cannot false-positive a developer's machine. Serverless markers\n// like VERCEL / NETLIFY / AWS_LAMBDA_FUNCTION_NAME are intentionally omitted\n// — their local emulators (`vercel dev`, `netlify dev`, SAM local) set the\n// same vars, so adding them would break local development. Before adding a\n// marker, confirm it is never set by that platform's dev tooling. An\n// unmarked host should set NODE_ENV=production to opt into the guard.\nexport const PAAS_MARKERS = [\n \"RAILWAY_ENVIRONMENT\",\n \"RENDER\",\n \"FLY_APP_NAME\",\n \"K_SERVICE\",\n \"DYNO\",\n \"KUBERNETES_SERVICE_HOST\",\n \"ECS_CONTAINER_METADATA_URI_V4\",\n] as const;\n\n/**\n * True when `env` looks like a deployed environment: `NODE_ENV=production`\n * or any {@link PAAS_MARKERS} set to a non-empty value. Decides whether a\n * non-durable store (in-memory, local-fs) should fail loud instead of\n * silently serving a production workload. A CI runner (`CI` set to a\n * non-empty, non-`false` value) is never treated as deployed, so PaaS\n * markers from an in-cluster CI agent do not trip it.\n */\nexport const isDeployedEnv = (env: Record<string, string | undefined>): boolean => {\n // A CI runner is never a deployment — even in a k8s pod that sets a PaaS\n // marker (e.g. KUBERNETES_SERVICE_HOST) — so it must not trip the markers.\n const inCi = (env[\"CI\"] ?? \"\") !== \"\" && env[\"CI\"] !== \"false\";\n return (\n env[\"NODE_ENV\"] === \"production\" || (!inCi && PAAS_MARKERS.some((m) => (env[m] ?? \"\") !== \"\"))\n );\n};\n","import { isDeployedEnv } from \"../env.ts\";\nimport { BaerlyError } from \"../errors.ts\";\nimport { assertValidStorageKey } from \"./key.ts\";\nimport type {\n Storage,\n StorageGetOptions,\n StorageGetResult,\n StorageListEntry,\n StoragePutOptions,\n StoragePutResult,\n} from \"./types.ts\";\n\ninterface StoredObject {\n body: Uint8Array;\n etag: string;\n contentType?: string;\n}\n\nconst utf8Encoder = new TextEncoder();\n\nconst EPHEMERAL_ENV_OPT_IN = \"BAERLY_ALLOW_EPHEMERAL_STORAGE\";\n\n// Read process env without a `node:` import so protocol stays Workerd-\n// loadable. With `nodejs_compat`, Workerd populates `process.env` from text\n// bindings, so the deployed-environment guard also applies on Workers.\nconst readProcessEnv = (): Record<string, string | undefined> =>\n (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n\nlet warnedEphemeralInDeployment = false;\n\n// Fail closed when in-memory storage would silently back a deployed\n// workload (writes \"succeed\" into RAM, vanish on restart). No-op in\n// dev/test; bypass in a deployment only via an explicit acknowledgement.\nconst assertEphemeralAllowed = (explicitOptIn: boolean): void => {\n const env = readProcessEnv();\n if (!isDeployedEnv(env)) {\n return;\n }\n if (!explicitOptIn && env[EPHEMERAL_ENV_OPT_IN] !== \"true\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"Refusing to use in-memory storage in a deployed environment — all data is lost on restart. \" +\n \"MemoryStorage is for tests/local dev only; configure a durable bucket (AWS S3 / Cloudflare R2). \" +\n `To intentionally opt in: new MemoryStorage({ ephemeral: true }) or ${EPHEMERAL_ENV_OPT_IN}=true.`,\n );\n }\n if (!warnedEphemeralInDeployment) {\n warnedEphemeralInDeployment = true;\n console.warn(\n \"[baerly] in-memory storage in a deployed environment — ALL DATA IS LOST ON RESTART.\",\n );\n }\n};\n\n/** Options for {@link MemoryStorage}. */\nexport interface MemoryStorageOptions {\n /**\n * Acknowledge the store is intentionally ephemeral — required to\n * construct in a detected deployment ({@link isDeployedEnv}); ignored in\n * dev/test. Env equivalent: `BAERLY_ALLOW_EPHEMERAL_STORAGE=true`.\n */\n ephemeral?: boolean;\n}\n\n/**\n * Compare two keys by their UTF-8 byte sequences — the order S3 and\n * R2 use for `list`. JavaScript's default string sort compares UTF-16\n * code units, which diverges from UTF-8 byte order for supplementary-\n * plane characters (e.g. emoji sort before high-BMP characters under\n * UTF-16 but after them in UTF-8). Using this keeps the in-memory\n * reference backend faithful to the real adapters. (All kernel keys\n * are ASCII base-32, where the two orders coincide — this only\n * matters for adversarial / non-ASCII keys.)\n */\nconst compareKeysUtf8 = (a: string, b: string): number => {\n const ba = utf8Encoder.encode(a);\n const bb = utf8Encoder.encode(b);\n const n = Math.min(ba.length, bb.length);\n for (let i = 0; i < n; i++) {\n if (ba[i] !== bb[i]) {\n return ba[i]! - bb[i]!;\n }\n }\n return ba.length - bb.length;\n};\n\n/**\n * In-memory `Storage`. The randomized property test runs against\n * this; it must be deterministic — no clocks beyond the caller's,\n * no randomness, no I/O.\n *\n * ETags are a monotonically increasing hex counter formatted in the\n * `\"<hex>\"` shape S3 returns (the surrounding double-quotes are part\n * of the ETag header value). Keys are stored verbatim.\n *\n * **Test-confidence caveat:** every method resolves on the microtask\n * queue with no real concurrency, so `put` reads `existing` and writes\n * back with no interleaving. MemoryStorage therefore CANNOT exercise the\n * compare-and-swap race the writer-fence model depends on — two writers\n * contending on one `current.json` always serialize here, so a green run\n * is necessary but not sufficient. That race is covered only by the\n * randomized integration tests against real S3 / Minio\n * (`tests/integration/randomized.test.ts`, `node-minio` variant).\n * Relatedly, `serverDate` returns the local clock, not an independent\n * server clock (see the `put` return below).\n */\nexport class MemoryStorage implements Storage {\n readonly #objects = new Map<string, StoredObject>();\n #etagCounter = 0;\n\n constructor(opts?: MemoryStorageOptions) {\n assertEphemeralAllowed(opts?.ephemeral === true);\n }\n\n #nextEtag(): string {\n this.#etagCounter += 1;\n return `\"${this.#etagCounter.toString(16)}\"`;\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n const stored = this.#objects.get(key);\n if (stored === undefined) {\n return null;\n }\n return { body: stored.body, etag: stored.etag };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n const existing = this.#objects.get(key);\n\n if (opts?.ifNoneMatch === \"*\" && existing !== undefined) {\n throw new BaerlyError(\n \"WriteConflict\",\n `PUT ${key}: precondition failed (ifNoneMatch=\"*\" but key exists)`,\n );\n }\n if (opts?.ifMatch !== undefined) {\n if (existing === undefined) {\n throw new BaerlyError(\n \"WriteConflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`,\n );\n }\n if (existing.etag !== opts.ifMatch) {\n throw new BaerlyError(\n \"WriteConflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${existing.etag})`,\n );\n }\n }\n\n const etag = this.#nextEtag();\n this.#objects.set(key, {\n body,\n etag,\n // Stryker disable next-line ObjectLiteral,ConditionalExpression: contentType is stored in the internal StoredObject but never returned by get() — the Storage interface has no contentType on StorageGetResult, so any mutation of this spread is observable-equivalent\n ...(opts?.contentType !== undefined && { contentType: opts.contentType }),\n });\n // `serverDate` is intentionally returned — the kernel's adaptive\n // clock-skew loop consumes the write-time server clock. `list()`\n // needs no such clock: `StorageListEntry` is `key` + `etag` only.\n return { etag, serverDate: new Date() };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n this.#objects.delete(key);\n }\n\n async *list(\n prefix: string,\n opts?: { startAfter?: string; maxKeys?: number; signal?: AbortSignal },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n const startAfter = opts?.startAfter ?? \"\";\n const maxKeys = opts?.maxKeys ?? Infinity;\n const sorted = [...this.#objects.keys()]\n .filter((k) => k.startsWith(prefix) && compareKeysUtf8(k, startAfter) > 0)\n .toSorted(compareKeysUtf8);\n let yielded = 0;\n for (const key of sorted) {\n if (yielded >= maxKeys) {\n return;\n }\n opts?.signal?.throwIfAborted();\n const stored = this.#objects.get(key);\n // Stryker disable next-line ConditionalExpression,BlockStatement: unreachable guard — keys come from Map.keys() so the corresponding value is always present; this branch exists only to satisfy noUncheckedIndexedAccess\n if (stored === undefined) {\n continue;\n }\n yield { key, etag: stored.etag };\n yielded += 1;\n }\n }\n\n /**\n * Test-only: drop all objects.\n * @internal\n */\n _clear(): void {\n this.#objects.clear();\n this.#etagCounter = 0;\n }\n}\n\n// Process-singleton MemoryStorage map keyed by bucket. Tests that need\n// multiple `Db` / `Writer` instances to see each other's writes\n// against an in-memory backend reach for this via\n// {@link getOrCreateMemoryStorageForBucket}; {@link resetMemoryStorage}\n// drops every bucket between test cases.\nconst sharedPerBucket = new Map<string, MemoryStorage>();\n\n/**\n * Test isolation: drop every bucket's contents from the shared\n * memory storage used by {@link getOrCreateMemoryStorageForBucket}.\n * Direct `MemoryStorage` instances built via `new MemoryStorage()`\n * are unaffected — those are isolated by construction.\n */\nexport const resetMemoryStorage = (): void => {\n sharedPerBucket.clear();\n};\n\n/**\n * Get the process-singleton {@link MemoryStorage} for the named\n * bucket, creating one on first access. Use this when constructing\n * a `Storage` directly so multiple consumers in the same process\n * see each other's writes for the same bucket name.\n */\nexport const getOrCreateMemoryStorageForBucket = (bucket: string): MemoryStorage => {\n return sharedPerBucket.getOrInsertComputed(bucket, () => new MemoryStorage());\n};\n","/**\n * Secondary index declarations: the runtime check on the\n * {@link IndexDefinition} shape, whose type lives in `@baerly/protocol`.\n *\n * A declaration changes no storage call and no read result. Reads and\n * insert uniqueness take membership from the snapshot plus the committed\n * log, and the writer maintains no index objects. Validation keeps the\n * declared names and shapes reserved for an index-aware format;\n * {@link validateIndexDefinition} runs at `Db.create` (`./config.ts`).\n *\n * Buckets written before 0.7 may hold inert marker objects under\n * `<collection>/index/`. Nothing reads, writes or reclaims them.\n */\n\nimport { BaerlyError, type IndexDefinition, validateWire } from \"@baerly/protocol\";\nimport { assertNameNotReserved } from \"./names.ts\";\n\nexport type { IndexDefinition };\n\n/** Path-safe segment name. */\nconst INDEX_NAME_RE = /^[a-z][a-z0-9_]*$/;\n\n/**\n * Reject malformed {@link IndexDefinition} shapes synchronously, at\n * `Db.create`. See docs/adr/003-layout-versioning-cordon.md.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — reserved leading-`_` `name`,\n * or an `on` field is a dotted path (only top-level fields are accepted).\n * @throws BaerlyError code=\"SchemaError\" — `name` fails the regex, or `on` is empty.\n */\nexport const validateIndexDefinition = (def: IndexDefinition): void => {\n assertNameNotReserved(def.name, \"index.name\");\n if (!INDEX_NAME_RE.test(def.name)) {\n throw new BaerlyError(\n \"SchemaError\",\n `index.name must match /^[a-z][a-z0-9_]*$/; got ${JSON.stringify(def.name)}`,\n );\n }\n if (typeof def.on === \"string\") {\n if (def.on.length === 0) {\n throw new BaerlyError(\"SchemaError\", `index ${def.name}.on must be non-empty`);\n }\n } else if (def.on.length === 0) {\n throw new BaerlyError(\"SchemaError\", `index ${def.name}.on must be non-empty array`);\n }\n for (const field of typeof def.on === \"string\" ? [def.on] : def.on) {\n if (field.includes(\".\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `index ${def.name}.on must name top-level fields; dotted paths are not supported (got ${JSON.stringify(field)})`,\n );\n }\n }\n if (def.predicate !== undefined) {\n try {\n validateWire(def.predicate);\n } catch (error) {\n // Surface as SchemaError so the failure mode matches the rest\n // of validateIndexDefinition (a `Db.create`-time bail-out).\n if (error instanceof BaerlyError) {\n throw new BaerlyError(\n \"SchemaError\",\n `index ${def.name}.predicate is invalid: ${error.message}`,\n { cause: error },\n );\n }\n throw error;\n }\n }\n};\n","/**\n * Runtime helpers for the `BaerlyConfig` shape.\n *\n * The type declarations (`BaerlyConfig`, `BaerlyAppConfig`,\n * `CollectionDefinition`, `CollectionNames`, `RowOf`, `UnboundConfig`,\n * `defineConfig`) live in `@baerly/protocol` — the cross-platform\n * package — so cross-platform consumers (client, scaffold\n * `baerly.config.ts`) can reference them without dragging the\n * Node-only server modules (`AsyncLocalStorage` etc.) into their\n * typecheck graph.\n *\n * This file keeps only the runtime helper `collectionsToMaps`, which\n * the Cloudflare and Node adapters call to flatten\n * `BaerlyConfig.collections` into the per-collection maps that\n * `Db.create` consumes.\n *\n * @see @baerly/protocol app-config.ts — type declarations.\n */\n\nimport type { BaerlyConfig, IndexDefinition, SchemaValidator } from \"@baerly/protocol\";\nimport { validateIndexDefinition } from \"./indexes.ts\";\n\n/**\n * Flatten `BaerlyConfig.collections` into the per-collection\n * `schemas` and `indexes` maps that {@link Db.create} consumes at\n * runtime. Used by the Cloudflare and Node adapters to pipe a\n * single `config` object through to the writer.\n *\n * Both adapters import this helper rather than inlining the loop\n * so the projection rule (drop empty index arrays; omit absent\n * schemas) stays in one place. Future `CollectionDefinition`\n * fields (lifecycle hooks, replica_identity) land here too.\n *\n * Every declared index is validated here, so a malformed declaration\n * fails at {@link Db.create} rather than at the first write. Indexes\n * change no read result, so validation is all a declaration buys:\n * it keeps the names and shapes reserved.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — an index `name` uses the\n * reserved leading `_`, or an `on` field is a dotted path.\n * @throws BaerlyError code=\"SchemaError\" — an index `name` fails\n * `/^[a-z][a-z0-9_]*$/`, `on` is empty, or `predicate` is invalid.\n */\nexport const collectionsToMaps = (\n collections: BaerlyConfig[\"collections\"] | undefined,\n): {\n schemas: ReadonlyMap<string, SchemaValidator>;\n indexes: ReadonlyMap<string, ReadonlyArray<IndexDefinition>>;\n} => {\n const schemas = new Map<string, SchemaValidator>();\n const indexes = new Map<string, ReadonlyArray<IndexDefinition>>();\n if (collections === undefined) {\n return { schemas, indexes };\n }\n for (const [name, def] of Object.entries(collections)) {\n if (def.schema !== undefined) {\n schemas.set(name, def.schema);\n }\n if (def.indexes !== undefined && def.indexes.length > 0) {\n for (const index of def.indexes) {\n validateIndexDefinition(index);\n }\n indexes.set(name, def.indexes);\n }\n }\n return { schemas, indexes };\n};\n","/**\n * `Collection<T>` factory. `Db.collection(name)` returns the result of\n * `makeCollection(ctx)` — a cheap, no-I/O handle. By-id mutations route\n * through dedicated runners: `insert` → `runInsert`,\n * `replace(id, doc)` → `runReplaceById`. `update(id, patch)` and\n * `delete(id)` forward to the predicate-form runners via a `byId`\n * wire — those Query verbs are genuinely bulk, so the by-id case is\n * just a one-row predicate.\n *\n * `Collection.insert(doc)` is the public insert path. The locked\n * `Query<T>` interface (`@baerly/protocol/src/collection-api.ts`) intentionally\n * does NOT declare `insert` — chainable inserts are out of scope.\n * For an inserted doc whose predicate-bound shape matters,\n * `db.collection(...).insert(...)` is the path; predicates are a read-\n * side concern.\n */\n\nimport {\n type Collection,\n type DocumentData,\n type OrderSpec,\n type PredicateWire,\n} from \"@baerly/protocol\";\nimport { assertReadDocId } from \"./doc-id.ts\";\nimport { makeQuery, runInsert, runReplaceById, type CollectionReadContext } from \"./query.ts\";\n\n/**\n * Build a `Collection<T>` bound to one `(tenant, collection)` read context.\n * Cheap: zero I/O, allocates one closure. Each modifier call returns\n * a FRESH `Query<T>` — calling `.where(p1)` and `.where(p2)` on the\n * same `Collection<T>` produces two independent chains.\n *\n * `.count()` shorthand defers to the empty-state `Query<T>.count()`\n * so the fold logic lives in one place.\n *\n * @example\n * ```ts\n * const collection = makeCollection<Ticket>({\n * storage,\n * collectionPrefix: \"app/tickets/tenant/acme/manifests/tickets\",\n * collectionName: \"tickets\",\n * });\n * const open = await collection.where({ status: \"open\" }).all();\n * ```\n *\n * @internal\n */\nexport const makeCollection = <T extends DocumentData>(\n ctx: CollectionReadContext,\n): Collection<T> => {\n // Empty seed state. Every modifier merges into a frozen copy.\n const seed = {\n wire: undefined as PredicateWire | undefined,\n order: undefined as OrderSpec<T> | undefined,\n limit: undefined as number | undefined,\n };\n // Kernel-internal `_id`-shaped wire. Bypasses `validateWire`\n // (which rejects top-level `_id`) by construction — the wire is\n // never wire-submitted; it short-circuits to `Map.get` via\n // `singleIdFromPredicate` inside `runRead`.\n const byId = (id: string) => ({\n ...seed,\n wire: { clauses: [{ op: \"eq\" as const, field: \"_id\", value: id }] } as PredicateWire,\n });\n return {\n name: ctx.collectionName,\n first: () => makeQuery<T>(ctx, seed).first(),\n all: () => makeQuery<T>(ctx, seed).all(),\n count: () => makeQuery<T>(ctx, seed).count(),\n /**\n * Read the row at `id`. `id` is checked by the stored-id rule (not the\n * NFC write rule) before any I/O, so a row an earlier release stored\n * under a non-NFC id stays readable.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `id` breaks the key-segment\n * rule; no row can be stored under it. Nothing was read.\n */\n get: async (id) => {\n assertReadDocId(id);\n return await makeQuery<T>(ctx, byId(id)).first();\n },\n where: (p) => makeQuery<T>(ctx, seed).where(p),\n order: (s) => makeQuery<T>(ctx, { ...seed, order: s }),\n limit: (n) => makeQuery<T>(ctx, { ...seed, limit: n }),\n /**\n * Insert one document. UUIDv7 auto-id when `_id` is absent,\n * `undefined` or `\"\"`; otherwise the caller-supplied `_id` is honoured. The first\n * insert of an `_id` wins: a pre-commit existence check surfaces\n * `AlreadyExists` for a row already committed, and the writer's insert\n * guard surfaces it for one a concurrent insert committed after that\n * check — matches the locked `Collection.insert` throws contract\n * (`@baerly/protocol/src/collection-api.ts`).\n *\n * Single-attempt per call: log-create contention is resolved inside\n * `Writer.commit()`, and its errors surface unchanged.\n *\n * @throws BaerlyError code=\"AlreadyExists\" — a live row holds `_id`,\n * committed before or concurrently with this call; of concurrent\n * inserts of one `_id`, at most one commits. Nothing was committed.\n * Not retriable.\n * @throws BaerlyError code=\"WriteConflict\" — a rejected storage precondition\n * the writer does not resolve; the write was not committed. The writer\n * makes one attempt (log-create races are resolved inside it), so\n * re-run the call to retry. Retriable.\n * @throws BaerlyError code=\"AmbiguousCommit\" — a committing create may be\n * durable, but its outcome could not be resolved, so the row may or may\n * not have been inserted. Re-read by a stable `_id`; absence is not proof\n * of failure. Not retriable-by-default; see `Writer.commit`.\n * @throws BaerlyError code=\"SchemaError\" — from the per-collection\n * `SchemaValidator` threaded via `collectionReadContext`.\n * @throws BaerlyError code=\"InvalidConfig\" — the supplied `_id` is not a\n * string (`null` included), or breaks the key-segment rule, holds an\n * unpaired UTF-16 surrogate, or is not NFC. Nothing was written.\n */\n insert: (doc) => runInsert<T>(ctx, doc),\n /**\n * Update the row at `id` by JSON-merge-patch. Forwards to the\n * predicate-form `runUpdate` through a `byId` wire, so at most one row\n * is matched. A write to the row that commits after the read is not\n * lost: the patch is re-applied to it, and a row deleted there is left\n * deleted with `modified: 0` (see `runUpdate`).\n *\n * @throws BaerlyError code=\"WriteConflict\" — a rejected storage precondition\n * the writer does not resolve, or log retention retired part of the\n * commit window; the write was not committed. The writer makes one\n * attempt (log-create races are resolved inside it), so re-run the\n * call to retry. Retriable.\n * @throws BaerlyError code=\"AmbiguousCommit\" — a committing create may be\n * durable, but its outcome could not be resolved, so the update may or\n * may not have been applied. Re-read by `id`; absence is not proof of\n * failure. Not retriable-by-default; see `Writer.commit`.\n * @throws BaerlyError code=\"SchemaError\" — merged post-image rejected by the\n * collection's bound validator, or `applyMergePatch(prev, patch)` produced\n * `undefined`.\n * @throws BaerlyError code=\"InvalidConfig\" — the patch's top-level `_id`\n * is present and is not `id` (`null` included), or `id` holds an\n * unpaired UTF-16 surrogate or is not NFC.\n * @throws BaerlyError code=\"InvalidResponse\" — the stored row's `_id` is\n * not the string `id`; repair it with `replace(id, doc)`.\n */\n update: (id, patch) => makeQuery<T>(ctx, byId(id)).update(patch),\n /**\n * Replace the row at `id` wholesale, preserving doc identity. Last\n * writer wins against a concurrent update; a concurrent delete is not\n * undone (see `runReplaceById`).\n *\n * @throws BaerlyError code=\"NotFound\" — no row exists at `id`, including\n * one a concurrent delete removed after the read.\n * @throws BaerlyError code=\"WriteConflict\" — a rejected storage precondition\n * the writer does not resolve; the write was not committed. The writer\n * makes one attempt (log-create races are resolved inside it), so\n * re-run the call to retry. Retriable.\n * @throws BaerlyError code=\"AmbiguousCommit\" — a committing create may be\n * durable, but its outcome could not be resolved, so the replace may or\n * may not have been applied. Re-read by `id`; absence is not proof of\n * failure. Not retriable-by-default; see `Writer.commit`.\n * @throws BaerlyError code=\"SchemaError\" — post-image rejected by the\n * collection's bound validator.\n * @throws BaerlyError code=\"InvalidConfig\" — `id` breaks the key-segment\n * rule, holds an unpaired UTF-16 surrogate, or is not NFC. Nothing\n * was written.\n */\n replace: (id, doc) => runReplaceById<T>(ctx, id, doc),\n /**\n * Tombstone the row at `id`. Forwards to the predicate-form `runDelete`\n * through a `byId` wire, so at most one row is matched. A missing row is\n * not an error — `deleted` is `0`. `id` need not be NFC, so a row an\n * earlier release stored under a non-NFC id stays deletable. A row a\n * concurrent delete removed after the read is not deleted again (nor a\n * re-insert of its `_id`): `deleted` is `0` (see `runDelete`).\n *\n * @throws BaerlyError code=\"WriteConflict\" — a rejected storage precondition\n * the writer does not resolve; the write was not committed. The writer\n * makes one attempt (log-create races are resolved inside it), so\n * re-run the call to retry. Retriable.\n * @throws BaerlyError code=\"AmbiguousCommit\" — a committing create may be\n * durable, but its outcome could not be resolved, so the tombstone may or\n * may not have been applied. Re-read by `id`; absence is not proof of\n * failure. Not retriable-by-default; see `Writer.commit`.\n * @throws BaerlyError code=\"InvalidResponse\" — the stored row's `_id` is\n * not the string `id`; repair it with `replace(id, doc)`.\n */\n delete: (id) => makeQuery<T>(ctx, byId(id)).delete(),\n };\n};\n","import {\n type BaerlyConfig,\n type Collection,\n type CollectionNames,\n type DocumentData,\n type RowOf,\n type SchemaValidator,\n type Storage,\n type UnboundConfig,\n} from \"@baerly/protocol\";\nimport { collectionsToMaps } from \"./config.ts\";\nimport { makeCollection } from \"./collection.ts\";\nimport { assertKeySegment, collectionReadContext, registerDbInternals } from \"./db-read-seams.ts\";\n\n/**\n * Runtime entry point. One `Db` per `(app, tenant)` request.\n *\n * Construct via {@link Db.create} — the constructor is private so\n * callers don't accidentally bypass validation.\n *\n * **Collection provisioning.** `Db` provisions collections implicitly on\n * the first commit — the writer auto-creates the per-collection\n * `current.json` manifest with a zero-state seed, costing one extra\n * Class A PUT on the very first write per collection and zero\n * thereafter. There is no `ensureCollection` method on this class. For\n * eager pre-warm (seed scripts, deploy-time provisioning, CI fixtures\n * that want the manifest in place before the first request), use\n * {@link \"@gusto/baerly-storage/dev\".ensureTable}. The two seeds are\n * equivalent, not byte-identical: each mints its own `generation`\n * nonce. Harmless — `If-None-Match` means exactly one lands.\n *\n * @example\n * ```ts\n * import { Db } from \"@gusto/baerly-storage\";\n * import { MemoryStorage } from \"@gusto/baerly-storage\";\n *\n * const db = Db.create({\n * storage: new MemoryStorage(),\n * app: \"tickets\",\n * tenant: \"acme-co\",\n * });\n *\n * await db.collection(\"tickets\").insert({ title: \"first ticket\", status: \"open\" });\n * const open = await db.collection(\"tickets\").where({ status: \"open\" }).all();\n * ```\n *\n * @remarks\n * **Anti-patterns** (TS compile errors, not runtime rejections):\n * - `db.collection(name).insertOne({...})` / `.insert({...})` —\n * the Mongo verb. Use `.insert(row)` (returns `{ _id }`).\n * - `db.collection(name).findOne({...})` / `.find({...})` —\n * the Mongo read verbs. Use `.get(id)` for by-id reads and\n * `.where({...}).first()` / `.all()` for predicate reads.\n * - `db.collection(name).aggregate([...])` — no pipeline stage\n * model. Compose via `.where().order().limit()` modifiers.\n * - Raw SQL strings of any shape. The kernel has no SQL parser.\n */\nexport class Db<TConfig extends BaerlyConfig = UnboundConfig> {\n readonly app: string;\n readonly tenant: string;\n /**\n * Underlying `Storage`, captured so the collection API can issue reads\n * using physical keys directly.\n */\n readonly #storage: Storage;\n /**\n * Per-collection {@link SchemaValidator}s threaded onto every\n * {@link CollectionReadContext} this `Db` mints. Empty map means \"no\n * validation declared\" — every write proceeds at zero overhead.\n *\n * Derived from `config.collections[*].schema` via\n * {@link collectionsToMaps} at {@link Db.create} time.\n */\n readonly #schemas: ReadonlyMap<string, SchemaValidator>;\n\n private constructor(\n app: string,\n tenant: string,\n storage: Storage,\n schemas: ReadonlyMap<string, SchemaValidator>,\n ) {\n this.app = app;\n this.tenant = tenant;\n this.#storage = storage;\n this.#schemas = schemas;\n }\n\n /**\n * Build a tenant-scoped `Db`. Throws\n * `BaerlyError{code:\"InvalidConfig\"}` if either `app` or `tenant`\n * is empty, contains `/`, is `\".\"` or `\"..\"`, contains control\n * characters, starts with the reserved `\"_\"` prefix, exceeds\n * 256 bytes, contains an unpaired UTF-16 surrogate\n * (`!name.isWellFormed()`), or is not in Unicode Normalization Form C\n * (`name !== name.normalize(\"NFC\")`). Names are never normalized for\n * you: pass `name.normalize(\"NFC\")`.\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `app`, `tenant`, or a\n * `config.collections` key is empty, contains `/`, is `\".\"` or\n * `\"..\"`, contains control characters, starts with the reserved\n * `\"_\"` prefix, exceeds 256 bytes, contains an unpaired surrogate,\n * or is not NFC.\n *\n * @example\n * ```ts\n * const db = Db.create({ storage, app: \"tickets\", tenant: \"acme\" });\n * await db.collection(\"tickets\").insert({ title: \"hi\" });\n * ```\n */\n static create<TConfig extends BaerlyConfig = UnboundConfig>(config: {\n storage: Storage;\n app: string;\n tenant: string;\n /**\n * Optional. Pass the value returned by {@link defineConfig} from\n * your `baerly.config.ts`. Two things happen:\n *\n * 1. **Types.** `db.collection(name)` narrows `name` to declared\n * collection names and infers the row type from\n * `collections[name].schema` via {@link RowOf}.\n * 2. **Runtime.** Schemas are wired from `config.collections`\n * via {@link collectionsToMaps} — no second hand-off step.\n * Declared `indexes` are validated here (a malformed one throws\n * `SchemaError` or `InvalidConfig`) but do not speed up reads\n * or change their results or costs.\n *\n * @example\n * ```ts\n * import config from \"../baerly.config.ts\";\n * const db = Db.create({\n * storage: new MemoryStorage(),\n * app: \"helpdesk\",\n * tenant: \"test\",\n * config,\n * });\n * // db.collection(\"tickets\") is typed AND validates writes against\n * // the schema declared in baerly.config.ts.\n * ```\n */\n config?: TConfig;\n }): Db<TConfig> {\n const { storage, app, tenant } = config;\n assertKeySegment(app, \"app\", \"Db.create\");\n assertKeySegment(tenant, \"tenant\", \"Db.create\");\n // Config collection keys fail here, not at first use.\n for (const name of Object.keys(config.config?.collections ?? {})) {\n assertKeySegment(name, \"collection\", \"Db.create\");\n }\n // Always derive runtime maps from `config.collections` (which also\n // validates every index declaration). Absent config ⇒ no schemas;\n // the kernel behaves the same as a config with `collections: {}`.\n const derived =\n config.config !== undefined ? collectionsToMaps(config.config.collections) : undefined;\n return new Db<TConfig>(app, tenant, storage, derived?.schemas ?? new Map());\n }\n\n /**\n * Typed handle for a single collection. Cheap; creates no I/O. Same\n * `name` returns a FRESH `Collection<T>` object on each call (chain\n * identity is intentional — modifiers return new objects).\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `name` is empty,\n * contains `/`, is `\".\"` or `\"..\"`, contains control characters,\n * starts with the reserved `\"_\"` prefix, exceeds 256 bytes, or is\n * not in Unicode Normalization Form C.\n *\n * @example\n * ```ts\n * // With a baerly.config.ts bound via Db.create({..., config}),\n * // db.collection(name) infers the row type from the declared schema —\n * // no <Ticket> generic needed.\n * const open = await db.collection(\"tickets\")\n * .where({ status: \"open\" })\n * .order({ commit_ts: \"desc\" })\n * .limit(50)\n * .all();\n * ```\n */\n // One signature. When `TConfig` extends `UnboundConfig`,\n // `CollectionNames<UnboundConfig>` widens to `string` so kernel-internal\n // paths against `Db<UnboundConfig>` still resolve without a separate\n // untyped overload. The impl signature stays widened (`Collection<any>`)\n // — the runtime never narrows; `makeCollection<DocumentData>` builds a\n // single row-agnostic handle and TypeScript handles the rest at the\n // call site.\n collection<N extends CollectionNames<TConfig>>(\n name: N,\n ): Collection<RowOf<TConfig, N> & DocumentData>;\n collection(name: string): Collection<any> {\n return makeCollection<DocumentData>(collectionReadContext(this, name));\n }\n\n static {\n // Grants the read seams in `./db-read-seams.ts` access to the private\n // fields without putting them on the public class.\n registerDbInternals((db) => ({ storage: db.#storage, schemas: db.#schemas }));\n }\n}\n"],"mappings":";;;;;AAaA,MAAa,eAAe;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AAUA,MAAa,iBAAiB,QAAqD;CAGjF,MAAM,QAAQ,IAAI,SAAS,QAAQ,MAAM,IAAI,UAAU;CACvD,OACE,IAAI,gBAAgB,gBAAiB,CAAC,QAAQ,aAAa,MAAM,OAAO,IAAI,MAAM,QAAQ,EAAE;AAEhG;;ACpBA,MAAM,cAAc,IAAI,YAAY;AAEpC,MAAM,uBAAuB;AAK7B,MAAM,uBACH,WAA0E,SAAS,OAAO,CAAC;AAE9F,IAAI,8BAA8B;AAKlC,MAAM,0BAA0B,kBAAiC;CAC/D,MAAM,MAAM,eAAe;CAC3B,IAAI,CAAC,cAAc,GAAG,GACpB;CAEF,IAAI,CAAC,iBAAiB,IAAI,0BAA0B,QAClD,MAAM,IAAI,YACR,iBACA,iQAEwE,qBAAqB,OAC/F;CAEF,IAAI,CAAC,6BAA6B;EAChC,8BAA8B;EAC9B,QAAQ,KACN,qFACF;CACF;AACF;;;;;;;;;;;AAsBA,MAAM,mBAAmB,GAAW,MAAsB;CACxD,MAAM,KAAK,YAAY,OAAO,CAAC;CAC/B,MAAM,KAAK,YAAY,OAAO,CAAC;CAC/B,MAAM,IAAI,KAAK,IAAI,GAAG,QAAQ,GAAG,MAAM;CACvC,KAAK,IAAI,IAAI,GAAG,IAAI,GAAG,KACrB,IAAI,GAAG,OAAO,GAAG,IACf,OAAO,GAAG,KAAM,GAAG;CAGvB,OAAO,GAAG,SAA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S,2BAAW,IAAI,IAAI,CAAC;CAC5E;CAkCA,WAAW,MAA+B;EACxC,OAAO,eAA6B,sBAAsB,MAAM,IAAI,CAAC;CACvE;CAEA;EAGE,qBAAqB,QAAQ;GAAE,SAAS,GAAG;GAAU,SAAS,GAAG;EAAS,EAAE;CAC9E;AACF"}
@@ -1,7 +1,7 @@
1
- import { t as loadAppConfig } from "./config-1tv0-Yzm.js";
2
- import { a as setJsonMode, c as parseArgs, n as emitError, o as BaerlyError, s as defineCommand } from "./baerly.js";
1
+ import { i as errorToExitCode, l as defineCommand, n as emitError, o as setJsonMode, s as BaerlyError, u as parseArgs } from "./baerly.js";
2
+ import { t as loadAppConfig } from "./config-DEzInG6M.js";
3
3
  import "node:stream";
4
- //#region ../server/src/names.ts
4
+ // ../server/src/names.ts
5
5
  /** Reject names in the system-reserved leading-"_" namespace. See docs/adr/003-layout-versioning-cordon.md. */
6
6
  const assertNameNotReserved = (name, context) => {
7
7
  if (name.startsWith("_")) throw new BaerlyError("InvalidConfig", `${context}: "${name}" is reserved — names beginning with "_" are reserved for system use. See docs/adr/003-layout-versioning-cordon.md.`);
@@ -27,8 +27,71 @@ const assertPathSegment = (value, role, verb = "") => {
27
27
  if (utf8.encode(value).length > 256) throw new BaerlyError("InvalidConfig", `${where} is too long (> 256 bytes)`);
28
28
  assertNameNotReserved(value, where);
29
29
  };
30
- //#endregion
31
- //#region src/subcommand.ts
30
+ /**
31
+ * Resolution for a non-NFC app, tenant, or collection name. Data an
32
+ * earlier release stored under one stays readable through the operator
33
+ * CLI, and is migrated by export and restore under a new name.
34
+ */
35
+ const NAME_NFC_RESOLUTION = "Pass name.normalize(\"NFC\") for a new app, tenant, or collection name. The SDK refuses non-NFC names. Export legacy data with `baerly admin dump` and restore it with `baerly admin restore` under an NFC name that is not canonically equivalent to the original. The normalized original name is not a safe target, because R2 stores canonically-equivalent keys as one object.";
36
+ /**
37
+ * Require `value` to be in Unicode Normalization Form C
38
+ * (`value === value.normalize("NFC")`). R2 stores canonically-equivalent
39
+ * keys (NFC `é` and NFD `e` + U+0301) as one object, so two segments that
40
+ * differ only by normalization would address the same objects there. NFC
41
+ * gives each equivalence class one spelling. Case and compatibility
42
+ * variants (`A` / `a`, `fi` / `fi`) are distinct NFC strings and stay
43
+ * distinct. Shared by the `_id` write guard and {@link assertNameSegment}.
44
+ *
45
+ * @param resolution the `BaerlyError.resolution` for this segment's role.
46
+ * @throws BaerlyError code="InvalidConfig" — `value` is not NFC.
47
+ */
48
+ const assertNfcSegment = (value, role, verb, resolution) => {
49
+ if (value !== value.normalize("NFC")) {
50
+ const where = verb === "" ? role : `${verb}: ${role}`;
51
+ throw new BaerlyError("InvalidConfig", `${where} must be in Unicode Normalization Form C: ${JSON.stringify(value)}`, { resolution });
52
+ }
53
+ };
54
+ /**
55
+ * Resolution for an app, tenant, or collection name with an unpaired
56
+ * surrogate.
57
+ */
58
+ const NAME_WELL_FORMED_RESOLUTION = "Pass a name with no unpaired UTF-16 surrogate (name.isWellFormed() is true). One usually comes from slicing a string between the two halves of an emoji or other astral character; slice by code point instead.";
59
+ /**
60
+ * Require `value` to be well-formed UTF-16 (`value.isWellFormed()`): no
61
+ * unpaired surrogate. `encodeURIComponent` throws on one and UTF-8 has no
62
+ * encoding for one, so such a segment can be neither addressed over HTTP
63
+ * nor stored as an S3, GCS, or local-fs key. Shared by the `_id` write
64
+ * guard and {@link assertNameSegment}.
65
+ *
66
+ * @param resolution the `BaerlyError.resolution` for this segment's role.
67
+ * @throws BaerlyError code="InvalidConfig" — `value` holds an unpaired
68
+ * surrogate.
69
+ */
70
+ const assertWellFormedSegment = (value, role, verb, resolution) => {
71
+ if (!value.isWellFormed()) {
72
+ const where = verb === "" ? role : `${verb}: ${role}`;
73
+ throw new BaerlyError("InvalidConfig", `${where} may not contain an unpaired UTF-16 surrogate: ${JSON.stringify(value)}`, { resolution });
74
+ }
75
+ };
76
+ /**
77
+ * Guard an app, tenant, or collection name that the SDK, the HTTP
78
+ * router, or a writing CLI verb addresses: {@link assertPathSegment},
79
+ * then {@link assertWellFormedSegment}, then {@link assertNfcSegment}. Names are never normalized on the
80
+ * caller's behalf, so two canonically-equivalent names are never merged
81
+ * into one. The read-only CLI verbs (`inspect`, `export`, `cost`,
82
+ * `admin dump`, `admin fsck`, `admin usage`) apply only
83
+ * {@link assertPathSegment}, which keeps a legacy non-NFC name readable
84
+ * and exportable.
85
+ *
86
+ * @throws BaerlyError code="InvalidConfig" — the name breaks the
87
+ * key-segment rule, holds an unpaired surrogate, or is not NFC.
88
+ */
89
+ const assertNameSegment = (value, role, verb = "") => {
90
+ assertPathSegment(value, role, verb);
91
+ assertWellFormedSegment(value, role, verb, NAME_WELL_FORMED_RESOLUTION);
92
+ assertNfcSegment(value, role, verb, NAME_NFC_RESOLUTION);
93
+ };
94
+ // src/subcommand.ts
32
95
  /**
33
96
  * Shared citty arg fragments for the flags every operator command
34
97
  * takes with identical wording. Each subcommand spreads the ones it
@@ -36,7 +99,7 @@ const assertPathSegment = (value, role, verb = "") => {
36
99
  * `--bucket` / `--app` / `--tenant` / `--collection` / `--json`
37
100
  * descriptions can't drift copy-to-copy (they did: `--collection` had
38
101
  * both "Collection name" and "Collection name." variants). Bespoke
39
- * flags (`--config`, `--indexes`, `--provider`, `--verbose`, …) stay
102
+ * flags (`--config`, `--provider`, `--verbose`, …) stay
40
103
  * inline in the command that owns them.
41
104
  */
42
105
  const BUCKET_ARG = {
@@ -67,12 +130,6 @@ const JSON_ARG = {
67
130
  type: "boolean",
68
131
  description: "Emit a structured JSON envelope to stdout (success) or stderr (error)"
69
132
  };
70
- /** Shared exit-code mapping for caught `BaerlyError`s. */
71
- const errorToExitCode = (code) => {
72
- if (code === "InvalidConfig") return 1;
73
- if (code === "Conflict" || code === "Internal" || code === "InvalidResponse") return 3;
74
- return 2;
75
- };
76
133
  /**
77
134
  * Validate a `--collection` arg through the same shared rule the
78
135
  * server uses for every caller-controlled key segment, before it is
@@ -88,6 +145,22 @@ const assertCollectionArg = (collection, verb) => {
88
145
  assertPathSegment(collection, "collection", verb);
89
146
  };
90
147
  /**
148
+ * Guard the names a WRITING verb (`admin restore`) is about to write
149
+ * under: the server's
150
+ * SDK name rule, which adds Unicode Normalization Form C to the
151
+ * key-segment rule. Read-only verbs keep the bare key-segment rule
152
+ * ({@link assertCollectionArg} plus `resolveAppTenant`), so a legacy
153
+ * non-NFC name stays readable and exportable but is never a write
154
+ * target.
155
+ *
156
+ * @throws BaerlyError code="InvalidConfig" — a name is not NFC.
157
+ */
158
+ const assertWritableNames = (names, verb) => {
159
+ assertNameSegment(names.app, "app", verb);
160
+ assertNameSegment(names.tenant, "tenant", verb);
161
+ assertNameSegment(names.collection, "collection", verb);
162
+ };
163
+ /**
91
164
  * Build the app/tenant resolver. Captures `name` to surface the
92
165
  * calling subcommand in the InvalidConfig hint.
93
166
  */
@@ -105,7 +178,8 @@ const makeResolveAppTenant = (name) => {
105
178
  try {
106
179
  cfg = await loadAppConfig();
107
180
  } catch (error) {
108
- throw new BaerlyError("InvalidConfig", `baerly ${name}: --app / --tenant not supplied and no baerly.config.{ts,js,mjs,json} in cwd (${error instanceof BaerlyError ? error.message : error.message})`, error);
181
+ const inner = error instanceof BaerlyError ? error.message : error.message;
182
+ throw new BaerlyError("InvalidConfig", `baerly ${name}: --app / --tenant not supplied and no baerly.config.{ts,js,mjs,json} in cwd (${inner})`, { cause: error });
109
183
  }
110
184
  app = flagApp ?? cfg.app;
111
185
  tenant = flagTenant ?? cfg.tenant;
@@ -191,7 +265,6 @@ const defineBaerlySubcommand = (def) => {
191
265
  run
192
266
  };
193
267
  };
194
- //#endregion
195
- export { TENANT_ARG as a, assertPathSegment as c, JSON_ARG as i, assertNameNotReserved as l, BUCKET_ARG as n, assertCollectionArg as o, COLLECTION_ARG as r, defineBaerlySubcommand as s, APP_ARG as t };
268
+ export { TENANT_ARG as a, defineBaerlySubcommand as c, assertWellFormedSegment as d, JSON_ARG as i, assertNfcSegment as l, BUCKET_ARG as n, assertCollectionArg as o, COLLECTION_ARG as r, assertWritableNames as s, APP_ARG as t, assertPathSegment as u };
196
269
 
197
- //# sourceMappingURL=subcommand-DoDA-K7d.js.map
270
+ //# sourceMappingURL=subcommand-BLoF66dG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subcommand-BLoF66dG.js","names":[],"sources":["../packages/server/src/names.ts","../packages/server/src/path-segment.ts","../packages/cli/src/subcommand.ts"],"sourcesContent":["import { BaerlyError } from \"@baerly/protocol\";\n\n/** Reject names in the system-reserved leading-\"_\" namespace. See docs/adr/003-layout-versioning-cordon.md. */\nexport const assertNameNotReserved = (name: string, context: string): void => {\n if (name.startsWith(\"_\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${context}: \"${name}\" is reserved — names beginning with \"_\" are reserved for system use. See docs/adr/003-layout-versioning-cordon.md.`,\n );\n }\n};\n","import { BaerlyError } from \"@baerly/protocol\";\nimport { assertNameNotReserved } from \"./names.ts\";\n\n/**\n * Per-segment byte ceiling. S3 and R2 cap a full object key at 1024\n * UTF-8 bytes; a key is several segments, so this 256 leaves real prefix\n * headroom. The assembled multi-segment key sum is bounded separately on\n * the write path, not here. This is an intentional server-local *policy*\n * value (not the protocol-level S3/R2 fact `MAX_KEY_BYTES = 1024` in\n * `@baerly/protocol`'s `constants.ts`); it lives here, co-located with the\n * one rule that uses it, to keep `protocol/constants.ts` out of the\n * validator's bundle closure.\n */\nexport const MAX_SEGMENT_BYTES = 256;\nconst utf8 = new TextEncoder();\n// C0 (U+0000-U+001F) + DEL/C1 (U+007F-U+009F).\n// eslint-disable-next-line no-control-regex -- intentional control-char class\nconst CONTROL_CHARS = /[\\u0000-\\u001f\\u007f-\\u009f]/;\n\n/**\n * The single validation rule for every caller-controlled key segment\n * (`_id`, `collection`, `app`, `tenant`) before it becomes a written\n * key segment or `LocalFsStorage` path. Rejects empty / `\"/\"` /\n * `\".\"`|`\"..\"` / C0-C1 control / leading `\"_\"` (ADR-003) / `> MAX_SEGMENT_BYTES`,\n * all as `BaerlyError{code:\"InvalidConfig\"}`.\n *\n * @param role human label for the segment (\"_id\" | \"collection\" | \"app\" | \"tenant\").\n * @param verb optional calling-context label for the message.\n */\nexport const assertPathSegment = (value: string, role: string, verb = \"\"): void => {\n const where = verb === \"\" ? role : `${verb}: ${role}`;\n if (value.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", `${where} must be a non-empty string`);\n }\n if (value.includes(\"/\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${where} may not contain \"/\": ${JSON.stringify(value)}`,\n );\n }\n if (value === \".\" || value === \"..\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${where} may not be \".\" or \"..\": ${JSON.stringify(value)}`,\n );\n }\n if (CONTROL_CHARS.test(value)) {\n throw new BaerlyError(\"InvalidConfig\", `${where} may not contain control characters`);\n }\n if (utf8.encode(value).length > MAX_SEGMENT_BYTES) {\n throw new BaerlyError(\"InvalidConfig\", `${where} is too long (> ${MAX_SEGMENT_BYTES} bytes)`);\n }\n // Leading `_` is the ADR-003 reserved namespace.\n assertNameNotReserved(value, where);\n};\n\n/**\n * Resolution for a non-NFC app, tenant, or collection name. Data an\n * earlier release stored under one stays readable through the operator\n * CLI, and is migrated by export and restore under a new name.\n */\nconst NAME_NFC_RESOLUTION =\n 'Pass name.normalize(\"NFC\") for a new app, tenant, or collection name. The SDK refuses non-NFC names. Export legacy data with `baerly admin dump` and restore it with `baerly admin restore` under an NFC name that is not canonically equivalent to the original. The normalized original name is not a safe target, because R2 stores canonically-equivalent keys as one object.';\n\n/**\n * Require `value` to be in Unicode Normalization Form C\n * (`value === value.normalize(\"NFC\")`). R2 stores canonically-equivalent\n * keys (NFC `é` and NFD `e` + U+0301) as one object, so two segments that\n * differ only by normalization would address the same objects there. NFC\n * gives each equivalence class one spelling. Case and compatibility\n * variants (`A` / `a`, `fi` / `fi`) are distinct NFC strings and stay\n * distinct. Shared by the `_id` write guard and {@link assertNameSegment}.\n *\n * @param resolution the `BaerlyError.resolution` for this segment's role.\n * @throws BaerlyError code=\"InvalidConfig\" — `value` is not NFC.\n */\nexport const assertNfcSegment = (\n value: string,\n role: string,\n verb: string,\n resolution: string,\n): void => {\n if (value !== value.normalize(\"NFC\")) {\n const where = verb === \"\" ? role : `${verb}: ${role}`;\n throw new BaerlyError(\n \"InvalidConfig\",\n `${where} must be in Unicode Normalization Form C: ${JSON.stringify(value)}`,\n { resolution },\n );\n }\n};\n\n/**\n * Resolution for an app, tenant, or collection name with an unpaired\n * surrogate.\n */\nconst NAME_WELL_FORMED_RESOLUTION =\n \"Pass a name with no unpaired UTF-16 surrogate (name.isWellFormed() is true). One usually comes from slicing a string between the two halves of an emoji or other astral character; slice by code point instead.\";\n\n/**\n * Require `value` to be well-formed UTF-16 (`value.isWellFormed()`): no\n * unpaired surrogate. `encodeURIComponent` throws on one and UTF-8 has no\n * encoding for one, so such a segment can be neither addressed over HTTP\n * nor stored as an S3, GCS, or local-fs key. Shared by the `_id` write\n * guard and {@link assertNameSegment}.\n *\n * @param resolution the `BaerlyError.resolution` for this segment's role.\n * @throws BaerlyError code=\"InvalidConfig\" — `value` holds an unpaired\n * surrogate.\n */\nexport const assertWellFormedSegment = (\n value: string,\n role: string,\n verb: string,\n resolution: string,\n): void => {\n if (!value.isWellFormed()) {\n const where = verb === \"\" ? role : `${verb}: ${role}`;\n throw new BaerlyError(\n \"InvalidConfig\",\n `${where} may not contain an unpaired UTF-16 surrogate: ${JSON.stringify(value)}`,\n { resolution },\n );\n }\n};\n\n/**\n * Guard an app, tenant, or collection name that the SDK, the HTTP\n * router, or a writing CLI verb addresses: {@link assertPathSegment},\n * then {@link assertWellFormedSegment}, then {@link assertNfcSegment}. Names are never normalized on the\n * caller's behalf, so two canonically-equivalent names are never merged\n * into one. The read-only CLI verbs (`inspect`, `export`, `cost`,\n * `admin dump`, `admin fsck`, `admin usage`) apply only\n * {@link assertPathSegment}, which keeps a legacy non-NFC name readable\n * and exportable.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — the name breaks the\n * key-segment rule, holds an unpaired surrogate, or is not NFC.\n */\nexport const assertNameSegment = (value: string, role: string, verb = \"\"): void => {\n assertPathSegment(value, role, verb);\n assertWellFormedSegment(value, role, verb, NAME_WELL_FORMED_RESOLUTION);\n assertNfcSegment(value, role, verb, NAME_NFC_RESOLUTION);\n};\n","/**\n * Shared subcommand scaffolding for `baerly`.\n *\n * Every operator-facing subcommand (`inspect`, `export`, `doctor`, and\n * every `admin/*` command) was independently re-implementing the same\n * five pieces of boilerplate:\n *\n * 1. `setJsonMode(args.json === true)` before any emission.\n * 2. A `KNOWN_KEYS` whitelist asserting unknown `--flag` rejection.\n * 3. An `errorToExitCode(code)` mapping —\n * `InvalidConfig → 1`,\n * `WriteConflict|AlreadyExists|Internal|InvalidResponse|AmbiguousCommit → 3`,\n * else `2`.\n * 4. `resolveAppTenant(args)` falling back through `baerly.config.*`\n * to either real values or hard-coded `\"app\"` / `\"tenant\"`\n * literals.\n * 5. Two parallel entry points: a citty `defineCommand` block that\n * calls `process.exit(code)` on failure, and a `runXxx(argv)`\n * function for in-process tests that returns the exit code.\n *\n * The five copies drifted: some commands suppressed protocol-level\n * errors (no protocol-invariant `→ 3` arm), and the\n * config-fallback silently produced `\"app\"` / `\"tenant\"` literals\n * (confidently-wrong output when no config is present).\n *\n * {@link defineBaerlySubcommand} centralizes the five pieces:\n * - Computes the known-keys set from `Object.keys(args)` itself, so\n * a new flag is picked up automatically.\n * - Applies the full 3-bucket exit-code mapping uniformly.\n * - {@link SubcommandContext.resolveAppTenant} throws\n * `BaerlyError(\"InvalidConfig\", …)` with a `--app` / `--tenant`\n * hint when neither flags nor a loadable `baerly.config.*` supply\n * the values.\n * - Returns a bundle of {@link SubcommandBundle.cmd} (citty wiring)\n * and {@link SubcommandBundle.run} (test entry) sharing one\n * wrapped handler.\n */\n\nimport { type Readable, type Writable } from \"node:stream\";\nimport { defineCommand, parseArgs, type ArgsDef, type ParsedArgs, type CommandDef } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { assertNameSegment, assertPathSegment } from \"@baerly/server/_internal/testing\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { emitError, setJsonMode, errorToExitCode } from \"./output.ts\";\n\n/**\n * Shared citty arg fragments for the flags every operator command\n * takes with identical wording. Each subcommand spreads the ones it\n * needs into its own `... as const satisfies ArgsDef` literal, so the\n * `--bucket` / `--app` / `--tenant` / `--collection` / `--json`\n * descriptions can't drift copy-to-copy (they did: `--collection` had\n * both \"Collection name\" and \"Collection name.\" variants). Bespoke\n * flags (`--config`, `--provider`, `--verbose`, …) stay\n * inline in the command that owns them.\n */\nexport const BUCKET_ARG = {\n type: \"string\",\n required: true,\n description: \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n} as const;\n\nexport const APP_ARG = {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n} as const;\n\nexport const TENANT_ARG = {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n} as const;\n\nexport const COLLECTION_ARG = {\n type: \"string\",\n required: true,\n description: \"Collection name.\",\n valueHint: \"name\",\n} as const;\n\nexport const JSON_ARG = {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n} as const;\n\n/**\n * Optional stdin / stdout streams that a programmatic caller (today:\n * `runDump` / `runRestore` tests, and the export round-trip\n * integration test) can divert in place of `process.stdin` /\n * `process.stdout`. The citty entry point always uses the process\n * streams; only {@link SubcommandBundle.run} accepts these overrides.\n */\nexport interface SubcommandStreams {\n readonly stdin?: Readable;\n readonly stdout?: Writable;\n}\n\n/**\n * Capabilities the subcommand handler receives. Today: app/tenant\n * resolution. Kept narrow so the handler signature stays load-bearing\n * (the helper isn't a god object).\n */\ninterface SubcommandContext {\n /**\n * Returns `{ app, tenant }` resolved from explicit flags or\n * `baerly.config.{ts,js,mjs,json}` in the cwd.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — neither flag was\n * supplied AND no loadable config was found. The error message\n * includes a hint mentioning `--app` / `--tenant`.\n */\n readonly resolveAppTenant: (args: {\n readonly app?: string;\n readonly tenant?: string;\n }) => Promise<{ app: string; tenant: string }>;\n /**\n * Programmatic stdin / stdout overrides. `undefined` (or any\n * missing field) means \"use the process stream\". Only\n * `admin dump` / `admin restore` consume this; other commands\n * ignore the field.\n */\n readonly streams?: SubcommandStreams;\n}\n\n/**\n * Definition fed to {@link defineBaerlySubcommand}. `name` is the JSON\n * envelope tag (`\"inspect\"`, `\"admin.compact\"`, etc.); `args` is the\n * citty ArgsDef; `handler` returns the integer exit code.\n */\nexport interface SubcommandDef<TArgs extends ArgsDef> {\n /** JSON envelope `command` tag and the prefix of every emitted error. */\n readonly name: string;\n readonly meta: { readonly description: string };\n readonly args: TArgs;\n readonly handler: (args: ParsedArgs<TArgs>, ctx: SubcommandContext) => Promise<number>;\n}\n\n/**\n * Output of {@link defineBaerlySubcommand}. `cmd` plugs into\n * `subCommands` in `baerly.ts`; `run` is the in-process entry for\n * unit tests.\n */\nexport interface SubcommandBundle<TArgs extends ArgsDef> {\n readonly cmd: CommandDef<TArgs>;\n readonly run: (\n argv: readonly string[],\n options?: { readonly streams?: SubcommandStreams },\n ) => Promise<number>;\n}\n\n/**\n * Validate a `--collection` arg through the same shared rule the\n * server uses for every caller-controlled key segment, before it is\n * interpolated into a bucket key. Throws `BaerlyError(\"InvalidConfig\",\n * …)` on a traversal / empty / control-char / reserved value. `verb`\n * is the operator-facing command name (e.g. `\"baerly admin restore\"`,\n * `\"baerly inspect\"`) so the message names the exact command.\n *\n * (app/tenant are validated at their own chokepoint inside\n * `resolveAppTenant`; this guards the per-command `collection` arg.)\n */\nexport const assertCollectionArg = (collection: string, verb: string): void => {\n assertPathSegment(collection, \"collection\", verb);\n};\n\n/**\n * Guard the names a WRITING verb (`admin restore`) is about to write\n * under: the server's\n * SDK name rule, which adds Unicode Normalization Form C to the\n * key-segment rule. Read-only verbs keep the bare key-segment rule\n * ({@link assertCollectionArg} plus `resolveAppTenant`), so a legacy\n * non-NFC name stays readable and exportable but is never a write\n * target.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — a name is not NFC.\n */\nexport const assertWritableNames = (\n names: { readonly app: string; readonly tenant: string; readonly collection: string },\n verb: string,\n): void => {\n assertNameSegment(names.app, \"app\", verb);\n assertNameSegment(names.tenant, \"tenant\", verb);\n assertNameSegment(names.collection, \"collection\", verb);\n};\n\n/**\n * Build the app/tenant resolver. Captures `name` to surface the\n * calling subcommand in the InvalidConfig hint.\n */\nconst makeResolveAppTenant = (name: string): SubcommandContext[\"resolveAppTenant\"] => {\n return async (args) => {\n const flagApp = typeof args.app === \"string\" && args.app.length > 0 ? args.app : undefined;\n const flagTenant =\n typeof args.tenant === \"string\" && args.tenant.length > 0 ? args.tenant : undefined;\n let app: string;\n let tenant: string;\n if (flagApp !== undefined && flagTenant !== undefined) {\n app = flagApp;\n tenant = flagTenant;\n } else {\n let cfg: { app: string; tenant: string };\n try {\n cfg = await loadAppConfig();\n } catch (error) {\n // Re-throw with our own wording so the operator sees the\n // calling-command name and the hint to pass --app / --tenant\n // explicitly. The underlying loadAppConfig error is preserved\n // as the cause. (Only wraps a config-LOAD failure — the\n // segment validation below is intentionally outside this catch\n // so its own InvalidConfig message survives.)\n const inner = error instanceof BaerlyError ? error.message : (error as Error).message;\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly ${name}: --app / --tenant not supplied and no baerly.config.{ts,js,mjs,json} in cwd (${inner})`,\n { cause: error },\n );\n }\n app = flagApp ?? cfg.app;\n tenant = flagTenant ?? cfg.tenant;\n }\n // Single chokepoint covering every command that calls\n // resolveAppTenant: whatever the source (flags or config), the\n // resolved segments must pass the same shared rule before they\n // become bucket-key segments. A bad-but-supplied value throws\n // InvalidConfig, consistent with the \"not supplied\" case above.\n assertPathSegment(app, \"app\", `baerly ${name}`);\n assertPathSegment(tenant, \"tenant\", `baerly ${name}`);\n return { app, tenant };\n };\n};\n\n/**\n * Wrap `def.handler` with the standard JSON-mode toggle, unknown-key\n * rejection, and error-to-exit-code mapping. Shared by both the citty\n * `run({ args })` path and the test `run(argv)` path. The caller\n * supplies the {@link SubcommandContext}; this lets each `run(argv)`\n * invocation attach its own `streams` override without leaking across\n * invocations.\n */\nconst kebabToCamel = (s: string): string => s.replace(/-(\\w)/g, (_, c: string) => c.toUpperCase());\n\nconst wrapHandler = <TArgs extends ArgsDef>(\n def: SubcommandDef<TArgs>,\n): ((args: ParsedArgs<TArgs>, ctx: SubcommandContext) => Promise<number>) => {\n // Compute the allow-list once from the ArgsDef. citty injects `_`\n // for positional captures, so it must stay allowed. citty 0.2.2\n // also auto-injects a camelCase alias for every kebab-case flag\n // (e.g. `--where-comment` produces both `whereComment` and\n // `where-comment` on the parsed args), so each kebab key is\n // expanded to its camelCase variant in the allow-list too.\n const allowedKeys: ReadonlySet<string> = new Set(\n Object.keys(def.args)\n .flatMap((k) => (k.includes(\"-\") ? [k, kebabToCamel(k)] : [k]))\n .concat([\"_\"]),\n );\n return async (args, ctx) => {\n // `json` is conventional but not required — only toggle when it's\n // both declared in the ArgsDef and truthy on the parsed args.\n if (\"json\" in def.args) {\n setJsonMode((args as ParsedArgs<TArgs> & { json?: boolean }).json === true);\n }\n try {\n for (const k of Object.keys(args)) {\n if (!allowedKeys.has(k)) {\n throw new BaerlyError(\"InvalidConfig\", `baerly ${def.name}: unknown flag --${k}`);\n }\n }\n return await def.handler(args, ctx);\n } catch (error) {\n if (error instanceof BaerlyError) {\n emitError(def.name, error.code, error.message);\n return errorToExitCode(error.code);\n }\n emitError(def.name, \"Unknown\", (error as Error).message);\n return 2;\n }\n };\n};\n\n/**\n * Wrap a baerly subcommand. Returns `{ cmd, run }` —\n * - `cmd` is a citty `defineCommand` block; mount it in\n * `baerly.ts`'s `subCommands`. It calls `process.exit(code)` on a\n * non-zero exit so the parent process surfaces the failure.\n * - `run(argv)` is the in-process test entry. It parses `argv` with\n * citty's `parseArgs`, dispatches through the same wrapped\n * handler, and returns the integer exit code (does NOT call\n * `process.exit`).\n *\n * The two paths share `wrapHandler` so JSON-mode toggling,\n * unknown-flag rejection, and error-to-exit-code mapping behave\n * identically.\n */\nexport const defineBaerlySubcommand = <TArgs extends ArgsDef>(\n def: SubcommandDef<TArgs>,\n): SubcommandBundle<TArgs> => {\n const resolveAppTenant = makeResolveAppTenant(def.name);\n const wrapped = wrapHandler(def);\n\n const cmd = defineCommand({\n meta: { name: def.name, description: def.meta.description },\n args: def.args,\n run: async ({ args }) => {\n const code = await wrapped(args as ParsedArgs<TArgs>, { resolveAppTenant });\n if (code !== 0) {\n process.exit(code);\n }\n },\n });\n\n const run = async (\n argv: readonly string[],\n options?: { readonly streams?: SubcommandStreams },\n ): Promise<number> => {\n let parsed: ParsedArgs<TArgs>;\n try {\n parsed = parseArgs<TArgs>(argv as string[], def.args);\n } catch (error) {\n // Parse-time error from citty (missing required flag,\n // malformed value). Toggle JSON mode by sniffing argv since\n // we never reached the handler.\n setJsonMode(argv.includes(\"--json\"));\n emitError(def.name, \"InvalidConfig\", (error as Error).message);\n return 1;\n }\n return wrapped(parsed, { resolveAppTenant, streams: options?.streams });\n };\n\n return { cmd, run };\n};\n"],"mappings":";;;;;AAGA,MAAa,yBAAyB,MAAc,YAA0B;CAC5E,IAAI,KAAK,WAAW,GAAG,GACrB,MAAM,IAAI,YACR,iBACA,GAAG,QAAQ,KAAK,KAAK,oHACvB;AAEJ;ACIA,MAAM,OAAO,IAAI,YAAY;AAG7B,MAAM,gBAAgB;;;;;;;;;;;AAYtB,MAAa,qBAAqB,OAAe,MAAc,OAAO,OAAa;CACjF,MAAM,QAAQ,SAAS,KAAK,OAAO,GAAG,KAAK,IAAI;CAC/C,IAAI,MAAM,WAAW,GACnB,MAAM,IAAI,YAAY,iBAAiB,GAAG,MAAM,4BAA4B;CAE9E,IAAI,MAAM,SAAS,GAAG,GACpB,MAAM,IAAI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YAAY,KAAK,SAAS,QAAQ,CAAC;GACnC,UAAU,IAAI,MAAM,iBAAkB,MAAgB,OAAO;GAC7D,OAAO;EACT;EACA,OAAO,QAAQ,QAAQ;GAAE;GAAkB,SAAS,SAAS;EAAQ,CAAC;CACxE;CAEA,OAAO;EAAE;EAAK;CAAI;AACpB"}
@@ -1,35 +1,17 @@
1
- import { t as BaerlyError } from "./errors-Dfa3p78c.js";
2
- //#region packages/protocol/src/types.ts
1
+ import { t as BaerlyError } from "./errors-7Rk1HGCE.js";
2
+ // packages/protocol/src/types.ts
3
3
  /**
4
4
  * Mint a fresh {@link UUID}. The cast lives here so callers don't sprinkle
5
5
  * `<UUID>crypto.randomUUID()` throughout the codebase.
6
6
  */
7
7
  const uuid = () => crypto.randomUUID();
8
+ const UUID_V7_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
8
9
  /**
9
- * Mint a UUIDv7 — 48-bit Unix-millis prefix + 74 bits of randomness,
10
- * formatted as a standard 8-4-4-4-12 UUID string per RFC 9562 §5.7.
11
- * Lex-sortable by mint time, so it pairs well with object-storage
12
- * list semantics. Returns a branded {@link UUID}.
13
- *
14
- * Uses `crypto.getRandomValues` which is universally available
15
- * (Node 19+, Workerd, Bun, browsers).
16
- *
17
- * @example
18
- * ```ts
19
- * const id = uuidv7();
20
- * // e.g. "01956cad-4cc8-7abc-9def-0123456789ab"
21
- * ```
10
+ * True iff `s` has exactly the shape {@link uuidv7} produces: canonical
11
+ * lowercase 8-4-4-4-12 hex, version nibble `7`, variant nibble in
12
+ * `[89ab]`.
22
13
  */
23
- const uuidv7 = () => {
24
- const millis = Date.now();
25
- const rand = /* @__PURE__ */ new Uint8Array(10);
26
- crypto.getRandomValues(rand);
27
- rand[0] = rand[0] & 15 | 112;
28
- rand[2] = rand[2] & 63 | 128;
29
- const millisHex = millis.toString(16).padStart(12, "0");
30
- const b = Array.from(rand, (n) => n.toString(16).padStart(2, "0")).join("");
31
- return `${millisHex.slice(0, 8)}-${millisHex.slice(8, 12)}-${b.slice(0, 4)}-${b.slice(4, 8)}-${b.slice(8, 20)}`;
32
- };
14
+ const isUuidV7 = (s) => UUID_V7_RE.test(s);
33
15
  /**
34
16
  * Mint the trailing seq segment of an LSN (`<base32-time>_<sess>_<seq>`).
35
17
  * Uses `COUNT_BIT_WIDTH` (see `packages/protocol/src/constants.ts`) to
@@ -71,13 +53,13 @@ const uint2str = (num, bits) => {
71
53
  * consumers".
72
54
  */
73
55
  const uint2strDesc = (num, bits) => {
74
- return uint2str(Math.pow(2, bits) - 1 - num, bits);
56
+ const maxValue = Math.pow(2, bits) - 1;
57
+ return uint2str(maxValue - num, bits);
75
58
  };
76
59
  const str2uintDesc = (str, bits) => {
77
60
  return Math.pow(2, bits) - 1 - parseInt(str, 32);
78
61
  };
79
- //#endregion
80
- //#region packages/protocol/src/time.ts
62
+ // packages/protocol/src/time.ts
81
63
  /**
82
64
  * Encode an epoch-millis instant as a lexicographically-DEScending
83
65
  * base-32 key (newer sorts first). The load-bearing LSN ordering
@@ -98,9 +80,9 @@ const timestamp = (epoch) => {
98
80
  /**
99
81
  * Delay for `ms` milliseconds, with optional cancellation. If
100
82
  * `signal` aborts before the delay elapses, the returned promise
101
- * rejects with `signal.reason`. Used by `S3HttpStorage`'s retry
102
- * loop so shutdown can interrupt an in-flight backoff instead of
103
- * waiting for it to complete.
83
+ * rejects with `signal.reason`. `retryStorageCall` uses it for its
84
+ * backoff without a signal, so a backoff it has started always runs
85
+ * to completion.
104
86
  */
105
87
  const delay = (ms, signal) => new Promise((resolve, reject) => {
106
88
  if (signal?.aborted) {
@@ -113,7 +95,6 @@ const delay = (ms, signal) => new Promise((resolve, reject) => {
113
95
  reject(signal.reason);
114
96
  }, { once: true });
115
97
  });
116
- //#endregion
117
- export { uuid as a, str2uintDesc as i, timestamp as n, uuidv7 as o, countKey as r, delay as t };
98
+ export { str2uintDesc as a, isUuidV7 as i, timestamp as n, uuid as o, countKey as r, delay as t };
118
99
 
119
- //# sourceMappingURL=time-DUqvFMHq.js.map
100
+ //# sourceMappingURL=time-DRxTP9iv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"time-DRxTP9iv.js","names":[],"sources":["../packages/protocol/src/types.ts","../packages/protocol/src/time.ts"],"sourcesContent":["import { COUNT_BIT_WIDTH } from \"./constants.ts\";\n\n// Re-exported so existing `./types.ts` importers keep working; the\n// implementations live in `./uuid.ts` so a consumer that needs only\n// `uuidv7` (the client) does not pull in this module's base-32 helpers.\nexport { uuidv7 } from \"./uuid.ts\";\n\ndeclare const brand: unique symbol;\ntype Brand<B> = { [brand]: B };\n\n/**\n * Nominal-typing helper. `Branded<string, \"UUID\">` is a `string` at\n * runtime but the type system rejects mixing it with a plain `string` or\n * a string branded as something else. Used to prevent confusion bugs at\n * protocol boundaries (UUIDs vs. legacy content versions are both\n * strings, but using the wrong one corrupts the per-collection log).\n *\n * Construct branded values via the helpers in this file (e.g. {@link uuid})\n * or with a tagged cast at a single, deliberate boundary — never `as string`\n * to widen one back. See `docs/contributing/conventions/src.md`.\n */\nexport type Branded<T, B> = T & Brand<B>;\n\n/**\n * A UUID minted by this client. {@link uuid} returns v4 values used for\n * writer-session entropy and storage probe keys; {@link uuidv7} returns\n * time-sortable v7 values for caller-facing identifiers. Content side\n * objects use the separate legacy {@link ContentVersionId} hash brand.\n */\nexport type UUID = Branded<string, \"UUID\">;\n\n/**\n * Legacy content-key digest: lowercase SHA-256 hex truncated to 32\n * characters (128 bits), minted by `versionFromContent`. v0.6.0 writers\n * used it to name `content/<hash>.json` side objects; the current kernel\n * retains the brand only for legacy inspection or direct-bucket tooling.\n * Current writers do not mint content side objects, and current GC never\n * touches `content/`.\n */\nexport type ContentVersionId = Branded<string, \"ContentVersionId\">;\n\n/**\n * Mint a fresh {@link UUID}. The cast lives here so callers don't sprinkle\n * `<UUID>crypto.randomUUID()` throughout the codebase.\n */\nexport const uuid = (): UUID => crypto.randomUUID() as UUID;\n\nconst UUID_V7_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;\n\n/**\n * True iff `s` has exactly the shape {@link uuidv7} produces: canonical\n * lowercase 8-4-4-4-12 hex, version nibble `7`, variant nibble in\n * `[89ab]`.\n */\nexport const isUuidV7 = (s: string): s is UUID => UUID_V7_RE.test(s);\n\n/**\n * Mint the trailing seq segment of an LSN (`<base32-time>_<sess>_<seq>`).\n * Uses `COUNT_BIT_WIDTH` (see `packages/protocol/src/constants.ts`) to\n * produce an 11-char descending base-32 string with a domain of\n * 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1).\n *\n * Used together with {@link timestamp} (the descending base-32\n * encoding of millis-since-epoch). See {@link uint2strDesc} for the\n * lex-reversal property both rely on.\n */\nexport const countKey = (number: number): string => uint2strDesc(number, COUNT_BIT_WIDTH);\n\nexport const uint2str = (num: number, bits: number) => {\n const maxBase32Length = Math.ceil(bits / 5); // Change from 4 to 5 because log2(32) is roughly 5.\n const base32Representation = num.toString(32);\n return base32Representation.padStart(maxBase32Length, \"0\");\n};\n\nexport const str2uint = (str: string) => {\n return parseInt(str, 32); // Parse the string as base 32.\n};\n\n/**\n * Lex-reversed base-32 encoder for an unsigned integer in `[0, 2^bits)`.\n * Pads to `Math.ceil(bits/5)` chars so all values in the domain compare\n * lex against each other.\n *\n * **Order-reversal property:** for any pair of integers `a < b` (with\n * `a, b ∈ [0, 2^bits)`), `uint2strDesc(a, bits) > uint2strDesc(b, bits)`\n * lexicographically. Composed into an LSN of shape\n * `<base32-time>_<session>_<seq>` (where both `<base32-time>` and\n * `<seq>` use this encoder), a forward `Storage.list(prefix)`\n * returns log entries in reverse-causal order — newer entries first.\n *\n * This is the structural property the read path leans on:\n * `ListObjectsV2` is forward-only on S3, but the descending encoding\n * makes \"fetch the K newest entries\" a single bounded LIST with\n * `maxKeys=K` instead of a full-population LIST + in-memory reverse.\n *\n * Behaviourally verified across randomized populations in\n * `packages/protocol/src/lsn-reverse-list.test.ts`. Quantified\n * bytes-listed reduction is in\n * `docs/spec/attachments/lsn-reverse-walk-baseline.json`\n * (run `pnpm bench:lsn-reverse-walk` to reproduce). Spec rationale:\n * `docs/spec/sync-protocol.md` §\"LSNs, wall clocks, and downstream\n * consumers\".\n */\nexport const uint2strDesc = (num: number, bits: number): string => {\n const maxValue = Math.pow(2, bits) - 1;\n return uint2str(maxValue - num, bits);\n};\n\nexport const str2uintDesc = (str: string, bits: number): number => {\n const maxValue = Math.pow(2, bits) - 1;\n const num = parseInt(str, 32); // Convert base32 string to number\n return maxValue - num;\n};\n","import { TIMESTAMP_BIT_WIDTH } from \"./constants.ts\";\nimport { BaerlyError } from \"./errors.ts\";\nimport { uint2strDesc } from \"./types.ts\";\n\n/**\n * Encode an epoch-millis instant as a lexicographically-DEScending\n * base-32 key (newer sorts first). The load-bearing LSN ordering\n * primitive — see {@link uint2strDesc}.\n *\n * `epoch` is REQUIRED and validated. There is no default: an argless\n * call used to encode `0`, which descending-sorts as the most-ancient\n * instant and would silently invert ordering. A non-finite, negative,\n * or out-of-range `epoch` (e.g. a broken `Date.now()` returning `NaN`)\n * would corrupt the key silently rather than fail loud, so it throws\n * `Internal` instead — this is an invariant violation, not caller config\n * (the only legitimate argument is `Date.now()`).\n */\nexport const timestamp = (epoch: number): string => {\n if (!Number.isInteger(epoch) || epoch < 0 || epoch >= 2 ** TIMESTAMP_BIT_WIDTH) {\n throw new BaerlyError(\n \"Internal\",\n `timestamp(): epoch must be a non-negative integer < 2^${TIMESTAMP_BIT_WIDTH} (got ${epoch})`,\n );\n }\n return uint2strDesc(epoch, TIMESTAMP_BIT_WIDTH);\n};\n\n/**\n * Delay for `ms` milliseconds, with optional cancellation. If\n * `signal` aborts before the delay elapses, the returned promise\n * rejects with `signal.reason`. `retryStorageCall` uses it for its\n * backoff without a signal, so a backoff it has started always runs\n * to completion.\n */\nexport const delay = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(signal.reason);\n },\n // Stryker disable next-line BooleanLiteral,ObjectLiteral: `{ once: true }` removes the\n // listener after the first fire. AbortController fires `abort` only once per signal, so\n // `once: false` / `{}` produce identical observable behaviour — the listener stays attached\n // to an already-fired signal, but calling reject on a settled Promise is a no-op. The\n // BooleanLiteral (once:false) and ObjectLiteral ({}) mutations are genuine equivalences.\n { once: true },\n );\n });\n"],"mappings":";;;;;;AA6CA,MAAa,aAAmB,OAAO,WAAW;AAElD,MAAM,aAAa;;;;;;AAOnB,MAAa,YAAY,MAAyB,WAAW,KAAK,CAAC;;;;;;;;;;;AAYnE,MAAa,YAAY,WAA2B,aAAa,QAAA,EAAuB;AAExF,MAAa,YAAY,KAAa,SAAiB;CACrD,MAAM,kBAAkB,KAAK,KAAK,OAAO,CAAC;CAE1C,OAD6B,IAAI,SAAS,EAChB,CAAC,CAAC,SAAS,iBAAiB,GAAG;AAC3D;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,gBAAgB,KAAa,SAAyB;CACjE,MAAM,WAAW,KAAK,IAAI,GAAG,IAAI,IAAI;CACrC,OAAO,SAAS,WAAW,KAAK,IAAI;AACtC;AAEA,MAAa,gBAAgB,KAAa,SAAyB;CAGjE,OAFiB,KAAK,IAAI,GAAG,IAAI,IAAI,IACzB,SAAS,KAAK,EACN;AACtB;;;;;;;;;;;;;;;AC/FA,MAAa,aAAa,UAA0B;CAClD,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,KAAK,SAAS,KAAA,IACpD,MAAM,IAAI,YACR,YACA,iEAAqF,MAAM,EAC7F;CAEF,OAAO,aAAa,OAAA,EAA0B;AAChD;;;;;;;;AASA,MAAa,SAAS,IAAY,WAChC,IAAI,SAAe,SAAS,WAAW;CACrC,IAAI,QAAQ,SAAS;EACnB,OAAO,OAAO,MAAM;EACpB;CACF;CACA,MAAM,QAAQ,WAAW,SAAS,EAAE;CACpC,QAAQ,iBACN,eACM;EACJ,aAAa,KAAK;EAClB,OAAO,OAAO,MAAM;CACtB,GAMA,EAAE,MAAM,KAAK,CACf;AACF,CAAC"}
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Object-storage abstraction. The protocol kernel writes through
3
+ * this and only this. Implementations: in-memory (testing), S3 HTTP
4
+ * and native GCS HTTP (production), R2 binding (production), local-fs
5
+ * (dev).
6
+ *
7
+ * Cancellation: every method accepts an optional AbortSignal.
8
+ * Implementations should respect it where feasible; consumers may
9
+ * ignore it. We thread it through from the start so we don't have
10
+ * to retrofit cancellation later.
11
+ *
12
+ * Encoding: bodies are `Uint8Array` (works in Workers + Node 26+),
13
+ * not `Buffer`. Result types are `readonly` — the kernel doesn't
14
+ * mutate what storage returns.
15
+ *
16
+ * Not-found is signalled by `null` (single discriminator), not by
17
+ * throwing. Other failure modes throw `BaerlyError`.
18
+ */
19
+ interface Storage {
20
+ /**
21
+ * Fetch a single object. Returns `null` on not-found (404
22
+ * semantics). Every read is unconditional and returns the current
23
+ * version. Other failure modes throw `BaerlyError`.
24
+ */
25
+ get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null>;
26
+ /**
27
+ * Write a single object. Returns the new ETag and, when the
28
+ * underlying transport surfaces it, the server's response time
29
+ * as `serverDate` (S3's `Date` header). The kernel uses
30
+ * `serverDate` to track adaptive clock-skew; impls may return
31
+ * `undefined` if no server clock is available. Use `ifMatch` for
32
+ * compare-and-swap (write only if the current ETag matches), or
33
+ * `ifNoneMatch: "*"` for create-only (write only if no object
34
+ * exists). A rejected precondition throws
35
+ * `BaerlyError{code:"WriteConflict"}` (HTTP 412 semantics).
36
+ *
37
+ * A create-only put that rejects with `AccessDenied` or `InvalidConfig`
38
+ * must guarantee that no attempt of that call can still land. An
39
+ * implementation that retries internally reports a rejection that
40
+ * follows an attempt of unknown outcome as `NetworkError` instead; the
41
+ * writer resolves `NetworkError` by reading the slot back. A create-only
42
+ * put's `NetworkError` whose `cause.notApplied` is `true` must guarantee
43
+ * that no attempt of that call was applied or can still apply (for example,
44
+ * every attempt was definitively throttled before applying). The writer
45
+ * still reads the slot back to resolve an occupant, but an empty or failed readback
46
+ * preserves the original retriable `NetworkError`. Build it with
47
+ * `new BaerlyError("NetworkError", msg, { cause: { notApplied: true } })`:
48
+ * the detail object goes under `cause`, never as the options object.
49
+ */
50
+ put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult>;
51
+ /**
52
+ * Delete a single object. Idempotent: deleting a missing key is
53
+ * not an error.
54
+ */
55
+ delete(key: string, opts?: {
56
+ signal?: AbortSignal;
57
+ }): Promise<void>;
58
+ /**
59
+ * Lex-asc enumeration of keys with the given prefix. Pagination is
60
+ * implementation-internal; consumers iterate until exhaustion or
61
+ * `maxKeys`. `startAfter` (exclusive) is a strict-greater cursor.
62
+ */
63
+ list(prefix: string, opts?: {
64
+ startAfter?: string;
65
+ maxKeys?: number;
66
+ signal?: AbortSignal;
67
+ }): AsyncIterable<StorageListEntry>;
68
+ }
69
+ interface StorageGetOptions {
70
+ readonly signal?: AbortSignal;
71
+ }
72
+ interface StorageGetResult {
73
+ readonly body: Uint8Array;
74
+ readonly etag: string;
75
+ }
76
+ interface StoragePutResult {
77
+ readonly etag: string;
78
+ /**
79
+ * Server-reported response time, used by the kernel's adaptive
80
+ * clock-skew loop. Set by HTTP-backed impls from the response
81
+ * `Date` header; in-memory impls fill in the local wall clock.
82
+ * `undefined` if no clock signal is available.
83
+ */
84
+ readonly serverDate?: Date;
85
+ }
86
+ interface StoragePutOptions {
87
+ /** CAS guard: write only if ETag matches. */
88
+ readonly ifMatch?: string;
89
+ /** Create-only guard: write only if no object exists. */
90
+ readonly ifNoneMatch?: "*";
91
+ readonly contentType?: string;
92
+ /** Cancel mid-flight; impls should respect when feasible. */
93
+ readonly signal?: AbortSignal;
94
+ }
95
+ /**
96
+ * A listed object. `key` + `etag` only — deliberately not a mirror of
97
+ * whatever the backend's LIST response happens to carry.
98
+ *
99
+ * There is no `lastModified`. One existed, populated from server-side
100
+ * headers by the S3/GCS/R2 adapters and omitted by the clock-less
101
+ * impls. Its only consumer anchored GC's `due_at` on it, which made
102
+ * the grace period `max(0, grace − object age)` on exactly the
103
+ * adapters that populated it — see `computeDueAt` in `gc.ts`. With
104
+ * that anchor corrected the field had no reader, and a server clock
105
+ * per listed entry is not something the protocol should carry
106
+ * speculatively. Wall-clock needs are served by
107
+ * {@link StoragePutResult.serverDate} (the write-time server clock,
108
+ * which drives the adaptive clock-skew loop) or by reading
109
+ * `LogEntry.commit_ts`, which is what `baerly admin usage` does and
110
+ * documents as the cross-backend-uniform choice.
111
+ */
112
+ interface StorageListEntry {
113
+ readonly key: string;
114
+ readonly etag: string;
115
+ }
116
+ export { StoragePutOptions as a, StorageListEntry as i, StorageGetOptions as n, StoragePutResult as o, StorageGetResult as r, Storage as t };