@gusto/baerly-storage 0.1.2 → 0.3.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 (123) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.md +108 -44
  4. package/dist/API.md +192 -121
  5. package/dist/CHANGELOG.md +144 -0
  6. package/dist/THIRD-PARTY-LICENSES.txt +312 -0
  7. package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-BIzyAKzy.d.ts} +14 -2
  8. package/dist/app-config.d.ts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.js +288 -288
  11. package/dist/auth.js.map +1 -1
  12. package/dist/baerly.js +10 -10
  13. package/dist/baerly.js.map +1 -1
  14. package/dist/bytes-BXdamO3L.js.map +1 -1
  15. package/dist/{client-DYZfoZb9.d.ts → client-BJXF3XJA.d.ts} +10 -10
  16. package/dist/client-react.d.ts +76 -85
  17. package/dist/client-react.js +95 -53
  18. package/dist/client-react.js.map +1 -1
  19. package/dist/client.d.ts +3 -3
  20. package/dist/client.js.map +1 -1
  21. package/dist/{cloudflare-CINJPKCW.js → cloudflare-Cn2ibODt.js} +178 -2
  22. package/dist/cloudflare-Cn2ibODt.js.map +1 -0
  23. package/dist/cloudflare.d.ts +4 -4
  24. package/dist/cloudflare.js +10 -11
  25. package/dist/cloudflare.js.map +1 -1
  26. package/dist/{subcommand-DZcHcsYp.js → config-CGyBopy3.js} +643 -439
  27. package/dist/config-CGyBopy3.js.map +1 -0
  28. package/dist/context-DRZ3tZ5l.js.map +1 -1
  29. package/dist/{cost-CQt1YRkA.js → cost-BZ_MDBmn.js} +6 -4
  30. package/dist/cost-BZ_MDBmn.js.map +1 -0
  31. package/dist/{current-json-C-EyJqs0.js → current-json-DsN7FNY1.js} +47 -13
  32. package/dist/current-json-DsN7FNY1.js.map +1 -0
  33. package/dist/{db-BM3y2JQw.d.ts → db-CCT6tDfY.d.ts} +26 -108
  34. package/dist/{deploy-CrAbfgCq.js → deploy-BKKyGlSJ.js} +11 -4
  35. package/dist/deploy-BKKyGlSJ.js.map +1 -0
  36. package/dist/dev-vite.d.ts +5 -5
  37. package/dist/dev-vite.js +5 -5
  38. package/dist/dev-vite.js.map +1 -1
  39. package/dist/dev.d.ts +1 -1
  40. package/dist/dev.js +1 -1
  41. package/dist/{doctor-Db-hzPmE.js → doctor-BVU4GNXN.js} +13 -132
  42. package/dist/doctor-BVU4GNXN.js.map +1 -0
  43. package/dist/{dump-BYA55NLP.js → dump-DPEAKub6.js} +5 -3
  44. package/dist/dump-DPEAKub6.js.map +1 -0
  45. package/dist/errors-DOdL95kK.js.map +1 -1
  46. package/dist/{export-Bhbz90-z.js → export-BcuCLFFe.js} +6 -4
  47. package/dist/{export-Bhbz90-z.js.map → export-BcuCLFFe.js.map} +1 -1
  48. package/dist/{fsck-CPPZWt9p.js → fsck-RXgLOaJG.js} +23 -11
  49. package/dist/fsck-RXgLOaJG.js.map +1 -0
  50. package/dist/{http-Cw8p6y5b.js → http-Bd4byR4n.js} +45 -61
  51. package/dist/http-Bd4byR4n.js.map +1 -0
  52. package/dist/http.d.ts +15 -15
  53. package/dist/http.js +1 -1
  54. package/dist/{index-cUY-36AN.d.ts → index-BDceQQi-.d.ts} +20 -4
  55. package/dist/{index-C3JAH1Yo.d.ts → index-Cmsxx-ZN.d.ts} +9 -9
  56. package/dist/{index-DSvwEUeF.d.ts → index-DW7GT6M2.d.ts} +50 -42
  57. package/dist/{index-DwDTWPSU.d.ts → index-DnBGSeuU.d.ts} +10 -7
  58. package/dist/index.d.ts +6 -6
  59. package/dist/index.js +4 -4
  60. package/dist/{indexes-DAu2AkTW.d.ts → indexes-Cx7uMXm0.d.ts} +2 -2
  61. package/dist/{inspect-Bdbzvi-_.js → inspect-DhI49PSi.js} +16 -8
  62. package/dist/inspect-DhI49PSi.js.map +1 -0
  63. package/dist/{snapshot-SS8USDUF.js → log-tail-DXeDkWEp.js} +154 -83
  64. package/dist/log-tail-DXeDkWEp.js.map +1 -0
  65. package/dist/{maintenance-BRrThz8V.d.ts → maintenance-BkhUr72A.d.ts} +91 -26
  66. package/dist/{maintenance-ClzBC1Vv.js → maintenance-CWBQpZ2y.js} +368 -161
  67. package/dist/maintenance-CWBQpZ2y.js.map +1 -0
  68. package/dist/{maintenance-BvOv6BMM.js → maintenance-C_KSkVjd.js} +204 -82
  69. package/dist/maintenance-C_KSkVjd.js.map +1 -0
  70. package/dist/maintenance.d.ts +3 -2
  71. package/dist/maintenance.js +3 -2
  72. package/dist/node.d.ts +13 -8
  73. package/dist/node.js +1 -1
  74. package/dist/normalize-XWY25_sG.js.map +1 -1
  75. package/dist/{observability-CpOiEN0k.js → observability-BYd-RzEx.js} +63 -55
  76. package/dist/observability-BYd-RzEx.js.map +1 -0
  77. package/dist/observability.d.ts +3 -3
  78. package/dist/observability.js +1 -1
  79. package/dist/{plan-DOTl21vq.js → plan-DIu_B6fy.js} +7 -4
  80. package/dist/plan-DIu_B6fy.js.map +1 -0
  81. package/dist/{query-BmiQy328.js → query-sQNO5vU_.js} +1071 -1099
  82. package/dist/query-sQNO5vU_.js.map +1 -0
  83. package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-DP4CqSSs.js} +5 -4
  84. package/dist/rebuild-index-DP4CqSSs.js.map +1 -0
  85. package/dist/{restore-C6IcmLeA.js → restore-DpQYef6r.js} +362 -328
  86. package/dist/restore-DpQYef6r.js.map +1 -0
  87. package/dist/shared-secret-BJdSwpgw.js.map +1 -1
  88. package/dist/{src-QQ7jDeL2.js → src-CWpkSbvJ.js} +40 -20
  89. package/dist/src-CWpkSbvJ.js.map +1 -0
  90. package/dist/{src-DU1sCMlr.js → src-D24wDpzR.js} +269 -258
  91. package/dist/src-D24wDpzR.js.map +1 -0
  92. package/dist/{src-zhEAmmF7.js → src-Db4-qVtM.js} +36 -96
  93. package/dist/src-Db4-qVtM.js.map +1 -0
  94. package/dist/subcommand-CP9NY2J4.js +159 -0
  95. package/dist/subcommand-CP9NY2J4.js.map +1 -0
  96. package/dist/{usage-CLjirdD-.js → usage-CTfDq9HR.js} +3 -3
  97. package/dist/{usage-CLjirdD-.js.map → usage-CTfDq9HR.js.map} +1 -1
  98. package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
  99. package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
  100. package/package.json +42 -31
  101. package/dist/cloudflare-CINJPKCW.js.map +0 -1
  102. package/dist/config-DVfDGyw1.js +0 -278
  103. package/dist/config-DVfDGyw1.js.map +0 -1
  104. package/dist/cost-CQt1YRkA.js.map +0 -1
  105. package/dist/current-json-C-EyJqs0.js.map +0 -1
  106. package/dist/deploy-CrAbfgCq.js.map +0 -1
  107. package/dist/doctor-Db-hzPmE.js.map +0 -1
  108. package/dist/dump-BYA55NLP.js.map +0 -1
  109. package/dist/fsck-CPPZWt9p.js.map +0 -1
  110. package/dist/http-Cw8p6y5b.js.map +0 -1
  111. package/dist/inspect-Bdbzvi-_.js.map +0 -1
  112. package/dist/maintenance-BvOv6BMM.js.map +0 -1
  113. package/dist/maintenance-ClzBC1Vv.js.map +0 -1
  114. package/dist/observability-CpOiEN0k.js.map +0 -1
  115. package/dist/plan-DOTl21vq.js.map +0 -1
  116. package/dist/query-BmiQy328.js.map +0 -1
  117. package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
  118. package/dist/restore-C6IcmLeA.js.map +0 -1
  119. package/dist/snapshot-SS8USDUF.js.map +0 -1
  120. package/dist/src-DU1sCMlr.js.map +0 -1
  121. package/dist/src-QQ7jDeL2.js.map +0 -1
  122. package/dist/src-zhEAmmF7.js.map +0 -1
  123. package/dist/subcommand-DZcHcsYp.js.map +0 -1
@@ -1,7 +1,7 @@
1
- import { _ as SHARED_SECRET_MISSING_MESSAGE, h as NO_AUTH_CONFIGURED_MESSAGE, i as readCurrentJson, v as decodeJsonBytes } from "./current-json-C-EyJqs0.js";
1
+ import { _ as NO_AUTH_CONFIGURED_MESSAGE, b as decodeJsonBytes, i as readCurrentJson, y as SHARED_SECRET_MISSING_MESSAGE } from "./current-json-DsN7FNY1.js";
2
2
  import { t as BaerlyError } from "./errors-DOdL95kK.js";
3
- import { y as assertNameNotReserved } from "./maintenance-ClzBC1Vv.js";
4
- import { a as runReplaceById, i as runInsert, s as Writer, t as makeQuery } from "./query-BmiQy328.js";
3
+ import { C as logObjectKey, S as probeTailFrom } from "./maintenance-CWBQpZ2y.js";
4
+ import { a as runReplaceById, i as runInsert, s as assertPathSegment, t as makeQuery } from "./query-sQNO5vU_.js";
5
5
  import { t as sharedSecret } from "./shared-secret-BJdSwpgw.js";
6
6
  //#region packages/protocol/src/storage/memory.ts
7
7
  const utf8Encoder = new TextEncoder();
@@ -363,10 +363,14 @@ var Db = class Db {
363
363
  /**
364
364
  * Build a tenant-scoped `Db`. Throws
365
365
  * `BaerlyError{code:"InvalidConfig"}` if either `app` or `tenant`
366
- * is empty or contains `/` (the segment separator).
366
+ * is empty, contains `/`, is `"."` or `".."`, contains control
367
+ * characters, starts with the reserved `"_"` prefix, or exceeds
368
+ * 256 bytes.
367
369
  *
368
370
  * @throws BaerlyError code="InvalidConfig" when `app` or `tenant` is
369
- * empty or contains `/`.
371
+ * empty, contains `/`, is `"."` or `".."`, contains control
372
+ * characters, starts with the reserved `"_"` prefix, or exceeds
373
+ * 256 bytes.
370
374
  *
371
375
  * @example
372
376
  * ```ts
@@ -395,8 +399,9 @@ var Db = class Db {
395
399
  *
396
400
  * Runs the same `name`-validation guard as {@link Db.collection}.
397
401
  *
398
- * @throws BaerlyError code="InvalidConfig" when `name` is empty or
399
- * contains `/`.
402
+ * @throws BaerlyError code="InvalidConfig" when `name` is empty,
403
+ * contains `/`, is `"."` or `".."`, contains control characters,
404
+ * starts with the reserved `"_"` prefix, or exceeds 256 bytes.
400
405
  * @internal
401
406
  */
402
407
  collectionReadContext(name) {
@@ -411,83 +416,6 @@ var Db = class Db {
411
416
  };
412
417
  }
413
418
  /**
414
- * Atomic mutation over a single collection. The callback receives a
415
- * `Collection<T>` (not a `Db`) so cross-collection writes inside a
416
- * transaction are a TypeScript error at compile time — not a
417
- * runtime trap. Mutation verbs (`insert`, `update`, `replace`,
418
- * `delete`) buffer; reads (`first`, `all`, `count`) go through
419
- * `Storage` live (no MVCC snapshot, no read-your-writes).
420
- *
421
- * Single-attempt: on CAS conflict throws
422
- * `BaerlyError{code:"Conflict"}`. The body MAY have already run its
423
- * read side-effects (no rollback of in-memory state); the write
424
- * side-effects either all landed or none did. Wrap in a retry
425
- * loop you wrote if you want one.
426
- *
427
- * Empty body (or a body that buffers nothing) resolves without
428
- * touching `current.json`.
429
- *
430
- * @throws BaerlyError code="Conflict" — CAS lost on the collection's
431
- * `current.json`. Caller decides whether to re-run the body.
432
- * @throws Whatever the body throws — re-thrown as-is. The commit
433
- * is skipped when the body throws.
434
- * @throws BaerlyError code="InvalidConfig" — `collection` is empty or
435
- * contains `/`.
436
- *
437
- * @remarks
438
- * Single-collection by design. Cross-collection 2PC was rejected on
439
- * cost grounds — multiple round-trips per commit, no native fencing
440
- * primitive on S3-compatible storage, no rollback to undo a
441
- * successful PUT — and because in-doubt-transaction recovery state
442
- * would contradict the stateless-writer model. Applications that
443
- * need cross-collection atomicity re-express it at the app layer: an
444
- * idempotent move keyed off source-row state, or a single
445
- * denormalized collection with a `status` column.
446
- *
447
- * @example
448
- * ```ts
449
- * await db.transaction("tickets", async (tx) => {
450
- * const open = await tx.where({ status: "open" }).count();
451
- * if (open < 100) await tx.insert({ title: "another", status: "open" });
452
- * });
453
- * ```
454
- */
455
- async transaction(collection, body) {
456
- assertKeySegment(collection, "collection", "Db.transaction");
457
- const txCtx = {
458
- collection,
459
- mutations: []
460
- };
461
- const collectionPrefix = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}`;
462
- const schema = this.#schemas.get(collection);
463
- const indexes = this.#indexes.get(collection) ?? [];
464
- await body(makeCollection({
465
- storage: this.#storage,
466
- collectionPrefix,
467
- collectionName: collection,
468
- txCtx,
469
- indexes,
470
- ...schema !== void 0 ? { schema } : {}
471
- }));
472
- if (txCtx.mutations.length === 0) return;
473
- const inputs = [];
474
- for (const m of txCtx.mutations) {
475
- const input = {
476
- op: m.op,
477
- collection,
478
- docId: m.docId,
479
- ...m.body !== void 0 ? { body: m.body } : {},
480
- ...m.origin !== void 0 ? { origin: m.origin } : {}
481
- };
482
- inputs.push(input);
483
- }
484
- await new Writer({
485
- storage: this.#storage,
486
- currentJsonKey: `${collectionPrefix}/current.json`,
487
- options: { indexes }
488
- }).commitBatch(inputs);
489
- }
490
- /**
491
419
  * Read + parse this `Db`'s `manifests/<collection>/current.json`. Returns
492
420
  * `null` when the collection has not been provisioned yet (no
493
421
  * `current.json` exists). Throws `BaerlyError{code:"InvalidResponse"}`
@@ -502,12 +430,13 @@ var Db = class Db {
502
430
  * the collection API.
503
431
  */
504
432
  async getCurrentJson(collection, opts) {
433
+ assertPathSegment(collection, "collection");
505
434
  const key = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}/current.json`;
506
435
  return readCurrentJson(this.#storage, key, opts);
507
436
  }
508
437
  /**
509
438
  * Read + parse one `LogEntry` by `seq` from
510
- * `manifests/<collection>/${LOG_KEY_PREFIX}/<seq>.json`. Returns `null`
439
+ * `manifests/<collection>/log/<seq>.json`. Returns `null`
511
440
  * when the entry is missing — this typically means the GC sweeper
512
441
  * deleted the entry between a `readCurrentJson` and this GET (the
513
442
  * `/v1/since` handler treats the race as silent and skips the
@@ -518,7 +447,8 @@ var Db = class Db {
518
447
  * the collection API.
519
448
  */
520
449
  async getLogEntry(collection, seq, opts) {
521
- const key = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}/log/${seq}.json`;
450
+ assertPathSegment(collection, "collection");
451
+ const key = logObjectKey(`${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}`, seq);
522
452
  const got = await this.#storage.get(key, opts);
523
453
  if (got === null) return null;
524
454
  let parsed;
@@ -529,25 +459,35 @@ var Db = class Db {
529
459
  }
530
460
  return parsed;
531
461
  }
462
+ /**
463
+ * Forward-probe the TRUE committed log tail from `hint` (a lower
464
+ * bound, typically `tail_hint`). Backs the `/v1/since` end-bound.
465
+ *
466
+ * @internal — typed seam for the HTTP handler.
467
+ */
468
+ async probeLogTail(collection, hint, opts) {
469
+ assertPathSegment(collection, "collection");
470
+ const logPrefix = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}`;
471
+ const { tail } = await probeTailFrom(this.#storage, logPrefix, hint, opts);
472
+ return tail;
473
+ }
532
474
  };
533
475
  /**
534
476
  * Guard a string used as a path-segment in the bucket-key encoding.
535
- * Rejects empty and `/`-containing values with
536
- * `BaerlyError{code:"InvalidConfig"}`. `role` and `verb` are baked
537
- * into the message so the caller doesn't need to format their own.
477
+ * Routes through the single shared {@link assertPathSegment} rule
478
+ * (empty / `"/"` / `"."`|`".."` / C0-C1 control / leading `"_"` (ADR-007) /
479
+ * overlong), all as `BaerlyError{code:"InvalidConfig"}`. `role` and `verb`
480
+ * are baked into the message so the caller doesn't need to format their own.
538
481
  *
539
- * Used by {@link Db.create} (twice — `app`, `tenant`),
540
- * {@link Db.collectionReadContext} (once — `name`), and
541
- * {@link Db.transaction} (once — `collection`).
482
+ * Used by {@link Db.create} (twice — `app`, `tenant`) and
483
+ * {@link Db.collectionReadContext} (once — `name`).
542
484
  *
543
485
  * @internal
544
486
  */
545
487
  const assertKeySegment = (value, role, verb) => {
546
- if (value.length === 0) throw new BaerlyError("InvalidConfig", `${verb}: ${role} must be non-empty (got ${JSON.stringify(value)})`);
547
- if (value.includes("/")) throw new BaerlyError("InvalidConfig", `${verb}: "/" is reserved as the key-segment separator (got ${role}=${JSON.stringify(value)})`);
548
- assertNameNotReserved(value, verb);
488
+ assertPathSegment(value, role, verb);
549
489
  };
550
490
  //#endregion
551
491
  export { MemoryStorage as i, resolveVerifier as n, collectionsToMaps as r, Db as t };
552
492
 
553
- //# sourceMappingURL=src-zhEAmmF7.js.map
493
+ //# sourceMappingURL=src-Db4-qVtM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-Db4-qVtM.js","names":["#objects","#etagCounter","#nextEtag","#storage","#schemas","#indexes"],"sources":["../packages/protocol/src/storage/memory.ts","../packages/server/src/config.ts","../packages/server/src/auth/internal/none-verifier.ts","../packages/server/src/auth/internal/resolve-verifier.ts","../packages/server/src/collection.ts","../packages/server/src/db.ts"],"sourcesContent":["import { BaerlyError } from \"../errors.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\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 #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 opts?.signal?.throwIfAborted();\n const stored = this.#objects.get(key);\n if (stored === undefined) {\n return null;\n }\n if (opts?.ifNoneMatch !== undefined && opts.ifNoneMatch === stored.etag) {\n // 304 Not Modified — caller's cached copy is current.\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 opts?.signal?.throwIfAborted();\n const existing = this.#objects.get(key);\n\n if (opts?.ifNoneMatch === \"*\" && existing !== undefined) {\n throw new BaerlyError(\n \"Conflict\",\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 \"Conflict\",\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 \"Conflict\",\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 // deliberately omits `lastModified`: the in-memory impl has no\n // independent server clock, and its only consumer (GC's `due_at`\n // anchor) falls back to `now()` when it is absent, so omitting it\n // changes nothing.\n return { etag, serverDate: new Date() };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\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 let s = sharedPerBucket.get(bucket);\n if (s === undefined) {\n s = new MemoryStorage();\n sharedPerBucket.set(bucket, s);\n }\n return s;\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\";\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/planner.\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 */\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 indexes.set(name, def.indexes);\n }\n }\n return { schemas, indexes };\n};\n","import type { Verifier } from \"@baerly/protocol\";\n\n/**\n * Internal helper backing `config.auth === \"none\"`. Returns a\n * `Verifier` that resolves every request to the supplied\n * `tenantPrefix` with `identity: { kind: \"none\" }`. The kernel\n * NEVER reads the `Authorization` header in this mode — the network\n * seam itself is the trust boundary.\n *\n * Discriminant note: `identity.kind === \"none\"` distinguishes the\n * \"operator opted into auth=none in baerly.config.ts\" branch from the\n * bearer-token paths (`kind: \"shared-secret\"`, `kind: \"jwt\"`, etc).\n *\n * Not part of the public surface. Consumed by `baerlyWorker` /\n * `baerlyNode` resolution; the operator-facing API is the typed\n * `auth: \"none\"` field on `BaerlyAppConfig`.\n *\n * @internal\n */\nexport const noAuthVerifier = (tenantPrefix: string): Verifier => {\n return async () => ({ tenantPrefix, identity: { kind: \"none\" } });\n};\n","import {\n type BaerlyAppConfig,\n BaerlyError,\n NO_AUTH_CONFIGURED_MESSAGE,\n SHARED_SECRET_MISSING_MESSAGE,\n type Verifier,\n} from \"@baerly/protocol\";\nimport { sharedSecret } from \"../presets/shared-secret.ts\";\nimport { noAuthVerifier } from \"./none-verifier.ts\";\n\n/**\n * Read env var lazily via a host-supplied accessor so the same\n * resolver works in CF Workers (env binding) and Node\n * (`process.env`). Returns `undefined` for an unset OR empty string —\n * both branches mean \"operator forgot to set it\".\n */\nexport type EnvAccessor = (name: string) => string | undefined;\n\n/**\n * Inputs to {@link resolveVerifier}. `factoryVerifier` is the\n * adapter-factory `verifier:` option (may be undefined). `config`\n * carries the typed `auth` posture + the `tenant` pin. `readEnv`\n * is the per-host env accessor.\n */\nexport interface ResolveVerifierInput {\n readonly factoryVerifier: Verifier | undefined;\n readonly config: BaerlyAppConfig;\n readonly readEnv: EnvAccessor;\n}\n\n/**\n * Resolve the per-request `Verifier` for an adapter factory using the\n * fixed order:\n *\n * 1. `factoryVerifier` set → use as-is (highest precedence; enables\n * env-aware construction via `cloudflareAccess(env)` etc).\n * 2. else `config.auth === \"shared-secret\"` → read `SHARED_SECRET`\n * via `readEnv`; throw `BaerlyError(\"InvalidConfig\",\n * SHARED_SECRET_MISSING_MESSAGE)` when unset/empty; else build\n * `sharedSecret({ secret, tenantPrefix: config.tenant })`.\n * 3. else `config.auth === \"none\"` → `noAuthVerifier(config.tenant)`.\n * 4. else → throw `BaerlyError(\"InvalidConfig\",\n * NO_AUTH_CONFIGURED_MESSAGE)`.\n *\n * Pure function — no I/O, no side effects beyond `sharedSecret`'s\n * own validation. Caller invokes once at adapter init time (or on\n * first fetch, depending on platform `await`-at-top-level\n * constraints).\n *\n * @throws BaerlyError code=\"InvalidConfig\" — branches 2 and 4 above.\n *\n * @internal\n */\nexport const resolveVerifier = (input: ResolveVerifierInput): Verifier => {\n if (input.factoryVerifier !== undefined) {\n return input.factoryVerifier;\n }\n if (input.config.auth === \"shared-secret\") {\n const secret = input.readEnv(\"SHARED_SECRET\");\n if (secret === undefined || secret.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", SHARED_SECRET_MISSING_MESSAGE);\n }\n return sharedSecret({ secret, tenantPrefix: input.config.tenant });\n }\n if (input.config.auth === \"none\") {\n return noAuthVerifier(input.config.tenant);\n }\n // Exhaustiveness backstop. The AuthConfig union is locked to\n // [\"none\", \"shared-secret\"]; reaching this branch means the caller\n // passed a config that has neither the typed field nor a factory\n // override. Same operator remediation as the type-level error.\n throw new BaerlyError(\"InvalidConfig\", NO_AUTH_CONFIGURED_MESSAGE);\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 { 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 get: (id) => makeQuery<T>(ctx, byId(id)).first(),\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 or\n * empty; otherwise the caller-supplied `_id` is honoured. A\n * pre-commit existence check against the materialised collection\n * surfaces `Conflict` on duplicate `_id` without round-tripping\n * to the writer — matches the locked `Collection.insert` throws\n * contract (`@baerly/protocol/src/collection-api.ts`).\n *\n * Single-attempt per call: CAS retries (up to 8 attempts) live\n * inside `Writer.commit()`. On retry-budget exhaustion the\n * writer throws `Conflict` and we surface unchanged.\n *\n * @throws BaerlyError code=\"Conflict\" — `_id` collision (pre-commit\n * check) or CAS retry budget exhausted.\n * @throws BaerlyError code=\"SchemaError\" — from the per-collection\n * `SchemaValidator` threaded via {@link Db.collectionReadContext}.\n */\n insert: (doc) => runInsert<T>(ctx, doc),\n update: (id, patch) => makeQuery<T>(ctx, byId(id)).update(patch),\n replace: (id, doc) => runReplaceById<T>(ctx, id, doc),\n delete: (id) => makeQuery<T>(ctx, byId(id)).delete(),\n };\n};\n","import {\n type BaerlyConfig,\n BaerlyError,\n type Collection,\n type CollectionNames,\n type CurrentJsonRead,\n decodeJsonBytes,\n type DocumentData,\n type IndexDefinition,\n logObjectKey,\n type LogEntry,\n readCurrentJson,\n type RowOf,\n type SchemaValidator,\n type Storage,\n type UnboundConfig,\n} from \"@baerly/protocol\";\nimport { collectionsToMaps } from \"./config.ts\";\nimport { probeTailFrom } from \"./log-tail.ts\";\nimport { assertPathSegment } from \"./path-segment.ts\";\nimport type { CollectionReadContext } from \"./query.ts\";\nimport { makeCollection } from \"./collection.ts\";\n\n/**\n * Physical-key prefix for a `(app, tenant)` pair. Trailing slash is\n * part of the prefix so a caller's `list(\"\")` resolves to\n * `list(\"app/<app>/tenant/<tenant>/\")` and cannot enumerate a sibling\n * tenant whose name shares a prefix.\n */\nconst physicalPrefixFor = (app: string, tenant: string): string => `app/${app}/tenant/${tenant}/`;\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 byte-identical bytes before the first request), use\n * {@link \"@gusto/baerly-storage/dev\".ensureTable}.\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 * Per-collection {@link IndexDefinition}s threaded onto every\n * {@link CollectionReadContext} this `Db` mints. Empty map means \"no\n * indexes declared\" — every read falls through to the snapshot +\n * log fold path.\n *\n * Derived from `config.collections[*].indexes` via\n * {@link collectionsToMaps} at {@link Db.create} time.\n */\n readonly #indexes: ReadonlyMap<string, ReadonlyArray<IndexDefinition>>;\n\n private constructor(\n app: string,\n tenant: string,\n storage: Storage,\n schemas: ReadonlyMap<string, SchemaValidator>,\n indexes: ReadonlyMap<string, ReadonlyArray<IndexDefinition>>,\n ) {\n this.app = app;\n this.tenant = tenant;\n this.#storage = storage;\n this.#schemas = schemas;\n this.#indexes = indexes;\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, or exceeds\n * 256 bytes.\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `app` or `tenant` is\n * empty, contains `/`, is `\".\"` or `\"..\"`, contains control\n * characters, starts with the reserved `\"_\"` prefix, or exceeds\n * 256 bytes.\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 and indexes are derived from\n * `config.collections` via {@link collectionsToMaps}. Schema\n * validation and index routing are wired automatically — no\n * second hand-off step.\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 // Always derive runtime maps from `config.collections`. Absent\n // config ⇒ empty maps (no schemas, no indexes); the kernel\n // 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>(\n app,\n tenant,\n storage,\n derived?.schemas ?? new Map(),\n derived?.indexes ?? new Map(),\n );\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, or exceeds 256 bytes.\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any -- impl signature must be wider than the public overload; with Predicate<T> typed, Collection<DocumentData> is no longer assignable to Collection<RowOf<...>&DocumentData> due to contravariance on where(). `any` widens correctly.\n collection(name: string): Collection<any> {\n return makeCollection<DocumentData>(this.collectionReadContext(name));\n }\n\n /**\n * Build a freshly-seeded {@link CollectionReadContext} for `name`. The\n * HTTP router uses this so it can drive `runAllWithMeta` directly\n * (the return shape carries the manifest-pointer cursor used to\n * pack `_meta` onto the read response envelope). Application\n * callers should keep using\n * {@link Db.collection}; the chainable terminals destructure the cursor\n * out and discard it to keep the locked `Query<T>` signature.\n *\n * Runs the same `name`-validation guard as {@link Db.collection}.\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `name` is empty,\n * contains `/`, is `\".\"` or `\"..\"`, contains control characters,\n * starts with the reserved `\"_\"` prefix, or exceeds 256 bytes.\n * @internal\n */\n collectionReadContext(name: string): CollectionReadContext {\n assertKeySegment(name, \"collection\", \"Db.collection\");\n const schema = this.#schemas.get(name);\n return {\n storage: this.#storage,\n collectionPrefix: `${physicalPrefixFor(this.app, this.tenant)}manifests/${name}`,\n collectionName: name,\n indexes: this.#indexes.get(name) ?? [],\n ...(schema !== undefined ? { schema } : {}),\n };\n }\n\n /**\n * Read + parse this `Db`'s `manifests/<collection>/current.json`. Returns\n * `null` when the collection has not been provisioned yet (no\n * `current.json` exists). Throws `BaerlyError{code:\"InvalidResponse\"}`\n * on a malformed body — same contract as the underlying\n * {@link readCurrentJson} helper in `@baerly/protocol`.\n *\n * Backs the `/v1/since` long-poll handler in\n * `packages/server/src/http/since.ts`; that handler needs the parsed\n * `CurrentJson` plus an ETag for the follow-up reads.\n *\n * @internal — typed seam for the HTTP handler; app code should use\n * the collection API.\n */\n async getCurrentJson(\n collection: string,\n opts?: { signal?: AbortSignal },\n ): Promise<CurrentJsonRead | null> {\n // Defensive at the db layer so ALL callers are covered — including\n // the `/v1/since` handler, whose only inline screen catches empty /\n // `/` and lets `..` / control bytes through into this key.\n assertPathSegment(collection, \"collection\");\n const key = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}/current.json`;\n return readCurrentJson(this.#storage, key, opts);\n }\n\n /**\n * Read + parse one `LogEntry` by `seq` from\n * `manifests/<collection>/log/<seq>.json`. Returns `null`\n * when the entry is missing — this typically means the GC sweeper\n * deleted the entry between a `readCurrentJson` and this GET (the\n * `/v1/since` handler treats the race as silent and skips the\n * entry). Throws `BaerlyError{code:\"InvalidResponse\"}` on a body\n * that isn't valid JSON.\n *\n * @internal — typed seam for the HTTP handler; app code should use\n * the collection API.\n */\n async getLogEntry(\n collection: string,\n seq: number,\n opts?: { signal?: AbortSignal },\n ): Promise<LogEntry | null> {\n // Defensive at the db layer so ALL callers are covered — same\n // rationale as `getCurrentJson`; the `/v1/since` poll reaches here.\n assertPathSegment(collection, \"collection\");\n const key = logObjectKey(\n `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}`,\n seq,\n );\n const got = await this.#storage.get(key, opts);\n if (got === null) {\n return null;\n }\n let parsed: unknown;\n try {\n parsed = decodeJsonBytes(got.body);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `log entry at ${key}: body is not valid JSON`,\n error,\n );\n }\n return parsed as LogEntry;\n }\n\n /**\n * Forward-probe the TRUE committed log tail from `hint` (a lower\n * bound, typically `tail_hint`). Backs the `/v1/since` end-bound.\n *\n * @internal — typed seam for the HTTP handler.\n */\n async probeLogTail(\n collection: string,\n hint: number,\n opts?: { signal?: AbortSignal },\n ): Promise<number> {\n assertPathSegment(collection, \"collection\");\n const logPrefix = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}`;\n const { tail } = await probeTailFrom(this.#storage, logPrefix, hint, opts);\n return tail;\n }\n}\n\n/**\n * Guard a string used as a path-segment in the bucket-key encoding.\n * Routes through the single shared {@link assertPathSegment} rule\n * (empty / `\"/\"` / `\".\"`|`\"..\"` / C0-C1 control / leading `\"_\"` (ADR-007) /\n * overlong), all as `BaerlyError{code:\"InvalidConfig\"}`. `role` and `verb`\n * are baked into the message so the caller doesn't need to format their own.\n *\n * Used by {@link Db.create} (twice — `app`, `tenant`) and\n * {@link Db.collectionReadContext} (once — `name`).\n *\n * @internal\n */\nconst assertKeySegment = (value: string, role: string, verb: string): void => {\n assertPathSegment(value, role, verb);\n};\n"],"mappings":";;;;;;AAgBA,MAAM,cAAc,IAAI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as setJsonMode, c as parseArgs, n as emitError, o as BaerlyError, s as defineCommand } from "./baerly.js";
3
+ import "node:stream";
4
+ //#region ../server/src/names.ts
5
+ /** Reject names in the system-reserved leading-"_" namespace. See docs/adr/007-layout-versioning-cordon.md. */
6
+ const assertNameNotReserved = (name, context) => {
7
+ if (name.startsWith("_")) throw new BaerlyError("InvalidConfig", `${context}: "${name}" is reserved — names beginning with "_" are reserved for system use. See docs/adr/007-layout-versioning-cordon.md.`);
8
+ };
9
+ const utf8 = new TextEncoder();
10
+ const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/;
11
+ /**
12
+ * The single validation rule for every caller-controlled key segment
13
+ * (`_id`, `collection`, `app`, `tenant`) before it becomes a written
14
+ * key segment or `LocalFsStorage` path. Rejects empty / `"/"` /
15
+ * `"."`|`".."` / C0-C1 control / leading `"_"` (ADR-007) / `> MAX_SEGMENT_BYTES`,
16
+ * all as `BaerlyError{code:"InvalidConfig"}`.
17
+ *
18
+ * @param role human label for the segment ("_id" | "collection" | "app" | "tenant").
19
+ * @param verb optional calling-context label for the message.
20
+ */
21
+ const assertPathSegment = (value, role, verb = "") => {
22
+ const where = verb === "" ? role : `${verb}: ${role}`;
23
+ if (value.length === 0) throw new BaerlyError("InvalidConfig", `${where} must be a non-empty string`);
24
+ if (value.includes("/")) throw new BaerlyError("InvalidConfig", `${where} may not contain "/": ${JSON.stringify(value)}`);
25
+ if (value === "." || value === "..") throw new BaerlyError("InvalidConfig", `${where} may not be "." or "..": ${JSON.stringify(value)}`);
26
+ if (CONTROL_CHARS.test(value)) throw new BaerlyError("InvalidConfig", `${where} may not contain control characters`);
27
+ if (utf8.encode(value).length > 256) throw new BaerlyError("InvalidConfig", `${where} is too long (> 256 bytes)`);
28
+ assertNameNotReserved(value, where);
29
+ };
30
+ //#endregion
31
+ //#region src/subcommand.ts
32
+ /** Shared exit-code mapping for caught `BaerlyError`s. */
33
+ const errorToExitCode = (code) => {
34
+ if (code === "InvalidConfig") return 1;
35
+ if (code === "Conflict" || code === "Internal" || code === "InvalidResponse") return 3;
36
+ return 2;
37
+ };
38
+ /**
39
+ * Validate a `--collection` arg through the same shared rule the
40
+ * server uses for every caller-controlled key segment, before it is
41
+ * interpolated into a bucket key. Throws `BaerlyError("InvalidConfig",
42
+ * …)` on a traversal / empty / control-char / reserved value. `verb`
43
+ * is the operator-facing command name (e.g. `"baerly admin restore"`,
44
+ * `"baerly inspect"`) so the message names the exact command.
45
+ *
46
+ * (app/tenant are validated at their own chokepoint inside
47
+ * `resolveAppTenant`; this guards the per-command `collection` arg.)
48
+ */
49
+ const assertCollectionArg = (collection, verb) => {
50
+ assertPathSegment(collection, "collection", verb);
51
+ };
52
+ /**
53
+ * Build the app/tenant resolver. Captures `name` to surface the
54
+ * calling subcommand in the InvalidConfig hint.
55
+ */
56
+ const makeResolveAppTenant = (name) => {
57
+ return async (args) => {
58
+ const flagApp = typeof args.app === "string" && args.app.length > 0 ? args.app : void 0;
59
+ const flagTenant = typeof args.tenant === "string" && args.tenant.length > 0 ? args.tenant : void 0;
60
+ let app;
61
+ let tenant;
62
+ if (flagApp !== void 0 && flagTenant !== void 0) {
63
+ app = flagApp;
64
+ tenant = flagTenant;
65
+ } else {
66
+ let cfg;
67
+ try {
68
+ cfg = await loadAppConfig();
69
+ } catch (error) {
70
+ 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);
71
+ }
72
+ app = flagApp ?? cfg.app;
73
+ tenant = flagTenant ?? cfg.tenant;
74
+ }
75
+ assertPathSegment(app, "app", `baerly ${name}`);
76
+ assertPathSegment(tenant, "tenant", `baerly ${name}`);
77
+ return {
78
+ app,
79
+ tenant
80
+ };
81
+ };
82
+ };
83
+ /**
84
+ * Wrap `def.handler` with the standard JSON-mode toggle, unknown-key
85
+ * rejection, and error-to-exit-code mapping. Shared by both the citty
86
+ * `run({ args })` path and the test `run(argv)` path. The caller
87
+ * supplies the {@link SubcommandContext}; this lets each `run(argv)`
88
+ * invocation attach its own `streams` override without leaking across
89
+ * invocations.
90
+ */
91
+ const kebabToCamel = (s) => s.replace(/-(\w)/g, (_, c) => c.toUpperCase());
92
+ const wrapHandler = (def) => {
93
+ const allowedKeys = new Set(Object.keys(def.args).flatMap((k) => k.includes("-") ? [k, kebabToCamel(k)] : [k]).concat(["_"]));
94
+ return async (args, ctx) => {
95
+ if ("json" in def.args) setJsonMode(args.json === true);
96
+ try {
97
+ for (const k of Object.keys(args)) if (!allowedKeys.has(k)) throw new BaerlyError("InvalidConfig", `baerly ${def.name}: unknown flag --${k}`);
98
+ return await def.handler(args, ctx);
99
+ } catch (error) {
100
+ if (error instanceof BaerlyError) {
101
+ emitError(def.name, error.code, error.message);
102
+ return errorToExitCode(error.code);
103
+ }
104
+ emitError(def.name, "Unknown", error.message);
105
+ return 2;
106
+ }
107
+ };
108
+ };
109
+ /**
110
+ * Wrap a baerly subcommand. Returns `{ cmd, run }` —
111
+ * - `cmd` is a citty `defineCommand` block; mount it in
112
+ * `baerly.ts`'s `subCommands`. It calls `process.exit(code)` on a
113
+ * non-zero exit so the parent process surfaces the failure.
114
+ * - `run(argv)` is the in-process test entry. It parses `argv` with
115
+ * citty's `parseArgs`, dispatches through the same wrapped
116
+ * handler, and returns the integer exit code (does NOT call
117
+ * `process.exit`).
118
+ *
119
+ * The two paths share `wrapHandler` so JSON-mode toggling,
120
+ * unknown-flag rejection, and error-to-exit-code mapping behave
121
+ * identically.
122
+ */
123
+ const defineBaerlySubcommand = (def) => {
124
+ const resolveAppTenant = makeResolveAppTenant(def.name);
125
+ const wrapped = wrapHandler(def);
126
+ const cmd = defineCommand({
127
+ meta: {
128
+ name: def.name,
129
+ description: def.meta.description
130
+ },
131
+ args: def.args,
132
+ run: async ({ args }) => {
133
+ const code = await wrapped(args, { resolveAppTenant });
134
+ if (code !== 0) process.exit(code);
135
+ }
136
+ });
137
+ const run = async (argv, options) => {
138
+ let parsed;
139
+ try {
140
+ parsed = parseArgs(argv, def.args);
141
+ } catch (error) {
142
+ setJsonMode(argv.includes("--json"));
143
+ emitError(def.name, "InvalidConfig", error.message);
144
+ return 1;
145
+ }
146
+ return wrapped(parsed, {
147
+ resolveAppTenant,
148
+ streams: options?.streams
149
+ });
150
+ };
151
+ return {
152
+ cmd,
153
+ run
154
+ };
155
+ };
156
+ //#endregion
157
+ export { assertNameNotReserved as i, defineBaerlySubcommand as n, assertPathSegment as r, assertCollectionArg as t };
158
+
159
+ //# sourceMappingURL=subcommand-CP9NY2J4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subcommand-CP9NY2J4.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/007-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/007-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-007) / `> 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-007 reserved namespace.\n assertNameNotReserved(value, where);\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`, `Conflict|Internal|InvalidResponse → 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 `Conflict|Internal|InvalidResponse → 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 { assertPathSegment } from \"@baerly/server/_internal/testing\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { emitError, setJsonMode } from \"./output.ts\";\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 */\nexport interface 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/** Shared exit-code mapping for caught `BaerlyError`s. */\nconst errorToExitCode = (code: string): number => {\n if (code === \"InvalidConfig\") {\n return 1;\n }\n if (code === \"Conflict\" || code === \"Internal\" || code === \"InvalidResponse\") {\n return 3;\n }\n return 2;\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 * 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 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,YACR,iBACA,GAAG,MAAM,wBAAwB,KAAK,UAAU,KAAK,GACvD;CAEF,IAAI,UAAU,OAAO,UAAU,MAC7B,MAAM,IAAI,YACR,iBACA,GAAG,MAAM,2BAA2B,KAAK,UAAU,KAAK,GAC1D;CAEF,IAAI,cAAc,KAAK,KAAK,GAC1B,MAAM,IAAI,YAAY,iBAAiB,GAAG,MAAM,oCAAoC;CAEtF,IAAI,KAAK,OAAO,KAAK,CAAC,CAAC,SAAA,KACrB,M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B"}
@@ -1,7 +1,7 @@
1
1
  import { t as decodeJsonBytes } from "./bytes-BXdamO3L.js";
2
- import { t as loadAppConfig } from "./config-DVfDGyw1.js";
3
- import { n as parseBucketUri, t as defineBaerlySubcommand } from "./subcommand-DZcHcsYp.js";
2
+ import { r as parseBucketUri, t as loadAppConfig } from "./config-CGyBopy3.js";
4
3
  import { i as isJsonMode, o as BaerlyError, r as emitSuccess } from "./baerly.js";
4
+ import { n as defineBaerlySubcommand } from "./subcommand-CP9NY2J4.js";
5
5
  /** Number of trailing log entries the estimator reads per collection. */
6
6
  const SAMPLE_SIZE = 120;
7
7
  /** Build the canonical `current.json` key for one collection. */
@@ -336,4 +336,4 @@ bundle.run;
336
336
  //#endregion
337
337
  export { estimateWritesPerMin, usageCmd };
338
338
 
339
- //# sourceMappingURL=usage-CLjirdD-.js.map
339
+ //# sourceMappingURL=usage-CTfDq9HR.js.map