@gusto/baerly-storage 0.6.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 (218) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -512
  3. package/dist/CHANGELOG.md +1137 -378
  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-ypCm3zjt.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-wrVYf4bb.js → cloudflare-CKHYXccw.js} +61 -82
  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-Di_Q01qx.js → deploy-Obj4nE-Z.js} +10 -14
  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 +9 -14
  53. package/dist/dev-vite.js +11 -10
  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-Bx6xSNJj.d.ts → gcs-admin-Dso1HWQj.d.ts} +18 -14
  68. package/dist/gcs.d.ts +19 -7
  69. package/dist/gcs.js +1 -2
  70. package/dist/{goog4-signer-Z7KnJ1su.js → goog4-signer-CeLIABoE.js} +102 -92
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-7zT29K3P.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-DP3ClvcA.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 +119 -92
  103. package/dist/node.js +3 -3
  104. package/dist/{observability-Ch-VQJyE.js → observability-C-ISCCLE.js} +1247 -326
  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-C4qgiXSg.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--LykAdl1.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-DD5gDc7t.d.ts → s3-http-DBC_wiCL.d.ts} +14 -8
  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-CqcKTjw9.js → sha256-4FfGQNPw.js} +9 -9
  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/{aws4fetch.esm-CXE5ZbAa.js → sigv4-sign-5IUflUD_.js} +143 -96
  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-BMFfDUI2.js → src-Actga-bO.js} +949 -363
  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-BV68pqwJ.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-BMZR8o6U.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 +90 -69
  152. package/dist/aws4fetch.esm-CXE5ZbAa.js.map +0 -1
  153. package/dist/bytes-BXdamO3L.js +0 -11
  154. package/dist/bytes-BXdamO3L.js.map +0 -1
  155. package/dist/cloudflare-wrVYf4bb.js.map +0 -1
  156. package/dist/config-B6nTy8e2.js +0 -3095
  157. package/dist/config-B6nTy8e2.js.map +0 -1
  158. package/dist/constants-CfeMWQWk.js +0 -222
  159. package/dist/constants-CfeMWQWk.js.map +0 -1
  160. package/dist/context-DRZ3tZ5l.js.map +0 -1
  161. package/dist/cost-_SE_SVgZ.js +0 -203
  162. package/dist/cost-_SE_SVgZ.js.map +0 -1
  163. package/dist/current-json-C6nhPOm1.js.map +0 -1
  164. package/dist/db-DjjthkTi.d.ts +0 -254
  165. package/dist/deploy-Di_Q01qx.js.map +0 -1
  166. package/dist/doctor-RWVRpvat.js +0 -102
  167. package/dist/doctor-RWVRpvat.js.map +0 -1
  168. package/dist/dump-m2vEYDNY.js +0 -94
  169. package/dist/dump-m2vEYDNY.js.map +0 -1
  170. package/dist/errors-Dfa3p78c.js +0 -78
  171. package/dist/errors-Dfa3p78c.js.map +0 -1
  172. package/dist/export-DenKwEQu.js +0 -401
  173. package/dist/export-DenKwEQu.js.map +0 -1
  174. package/dist/fsck-2Vq-7-e2.js +0 -279
  175. package/dist/fsck-2Vq-7-e2.js.map +0 -1
  176. package/dist/goog4-signer-Z7KnJ1su.js.map +0 -1
  177. package/dist/http-7zT29K3P.js.map +0 -1
  178. package/dist/http-transport-BTgVCY5r.js +0 -1250
  179. package/dist/http-transport-BTgVCY5r.js.map +0 -1
  180. package/dist/index-BHz92Acj.d.ts +0 -162
  181. package/dist/index-CEZKQsKt.d.ts +0 -1113
  182. package/dist/index-uE-w2dgj.d.ts +0 -115
  183. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  184. package/dist/inspect-BpYbH1DM.js +0 -133
  185. package/dist/inspect-BpYbH1DM.js.map +0 -1
  186. package/dist/log-tail-QWU4wlu-.js +0 -514
  187. package/dist/log-tail-QWU4wlu-.js.map +0 -1
  188. package/dist/maintenance-BGHGt2Yg.d.ts +0 -537
  189. package/dist/maintenance-DULFcpd1.js +0 -2144
  190. package/dist/maintenance-DULFcpd1.js.map +0 -1
  191. package/dist/maintenance-fEi-UZ2o.js +0 -1412
  192. package/dist/maintenance-fEi-UZ2o.js.map +0 -1
  193. package/dist/normalize-rjnZLwS4.js +0 -133
  194. package/dist/normalize-rjnZLwS4.js.map +0 -1
  195. package/dist/observability-Ch-VQJyE.js.map +0 -1
  196. package/dist/plan-C4qgiXSg.js.map +0 -1
  197. package/dist/query-C43r-6ib.js +0 -1773
  198. package/dist/query-C43r-6ib.js.map +0 -1
  199. package/dist/rebuild-index-BH1dc1p6.js +0 -81
  200. package/dist/rebuild-index-BH1dc1p6.js.map +0 -1
  201. package/dist/request-u0M51mhJ.js +0 -72
  202. package/dist/request-u0M51mhJ.js.map +0 -1
  203. package/dist/restore-D0VYWzfP.js +0 -778
  204. package/dist/restore-D0VYWzfP.js.map +0 -1
  205. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  206. package/dist/runtime-spec--LykAdl1.js.map +0 -1
  207. package/dist/sha256-CqcKTjw9.js.map +0 -1
  208. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  209. package/dist/src-BMFfDUI2.js.map +0 -1
  210. package/dist/src-DYZ4H1aF.js +0 -392
  211. package/dist/src-DYZ4H1aF.js.map +0 -1
  212. package/dist/src-DvbTEya2.js +0 -536
  213. package/dist/src-DvbTEya2.js.map +0 -1
  214. package/dist/subcommand-BV68pqwJ.js.map +0 -1
  215. package/dist/time-DUqvFMHq.js.map +0 -1
  216. package/dist/usage-BMZR8o6U.js.map +0 -1
  217. package/dist/validate-DtljsCh1.js.map +0 -1
  218. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -1,41 +1,3 @@
1
- //#region packages/protocol/src/constants.d.ts
2
- /**
3
- * Current major version of the snapshot control-object schema
4
- * ({@link SnapshotBody}). Readers MUST reject unknown versions with
5
- * `BaerlyError{code:"InvalidResponse"}` rather than try to coerce.
6
- *
7
- * Bump only on a breaking change to `SnapshotBody` field semantics.
8
- * Adding a new optional field is NOT breaking; renaming or removing
9
- * a field IS breaking.
10
- *
11
- * @see packages/server/src/snapshot.ts
12
- */
13
- declare const SNAPSHOT_SCHEMA_VERSION: 1;
14
- type MaintenanceProfileShape = Readonly<{
15
- gcInterval: number;
16
- gcMaxMarks: number;
17
- gcMaxSweeps: number;
18
- maxFoldEntriesPerPass: number;
19
- maxFoldBytes: number;
20
- maxFoldRows: number;
21
- }>;
22
- /** CF-free profile; the absent-context default. */
23
- declare const MAINTENANCE_PROFILE_CF_FREE: MaintenanceProfileShape;
24
- /** Node profile; 10× CF-free caps. */
25
- declare const MAINTENANCE_PROFILE_NODE: MaintenanceProfileShape;
26
- /**
27
- * CF-paid profile — opt-in via `BAERLY_MAINTENANCE_PROFILE=cf-paid`. A paid
28
- * isolate keeps the CPU-killable single-phase shape but has the 10,000-
29
- * subrequest budget (vs free's 50), so it reuses the `NODE_MAINTENANCE_*`
30
- * per-pass caps. CRITICAL: snapshot ceilings `maxFoldBytes` (`C`) /
31
- * `maxFoldRows` (`E`) are UNCHANGED — a profile moves rate, never correctness
32
- * (the equivalence invariant); the memory wall is raised via
33
- * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`.
34
- *
35
- * @see packages/adapter-cloudflare/src/worker.ts
36
- * @see docs/about/graduation.md
37
- */
38
- declare const MAINTENANCE_PROFILE_CF_PAID: MaintenanceProfileShape;
39
1
  /**
40
2
  * Canonical auth posture identifiers consumed by `BaerlyAppConfig.auth`,
41
3
  * the adapter resolution path (`packages/adapter-cloudflare/src/worker.ts`,
@@ -52,8 +14,6 @@ declare const MAINTENANCE_PROFILE_CF_PAID: MaintenanceProfileShape;
52
14
  * option instead.
53
15
  */
54
16
  declare const AUTH_CONFIG_VALUES: readonly ["none", "shared-secret"];
55
- //#endregion
56
- //#region packages/protocol/src/json.d.ts
57
17
  /**
58
18
  * The shape constraint for documents stored in a {@link Collection}.
59
19
  *
@@ -79,16 +39,64 @@ type DocumentData = {
79
39
  * Arrays are valid values; they are replaced (not merged) on patch.
80
40
  */
81
41
  type DocumentValue = string | number | boolean | DocumentData | Array<DocumentValue>;
42
+ /**
43
+ * The patch an `update` takes for a row of type `T`: a JSON Merge Patch
44
+ * (RFC 7396), typed against the row.
45
+ *
46
+ * - Every key is optional; a key left out is left unchanged.
47
+ * - An optional key also accepts `null`, which deletes the field.
48
+ * A required key does not: remove it with `replace` instead.
49
+ * - A required object member with a single object type accepts a nested
50
+ * `MergePatch`, merged field by field. Union-valued members require a
51
+ * whole value because the current value may belong to another variant.
52
+ * - An optional plain-object member takes its whole value or `null`,
53
+ * never a nested patch: to change part of an optional object, pass
54
+ * the whole object or use `replace`.
55
+ * - Arrays and scalars replace the stored value whole; array elements
56
+ * are never merged.
57
+ *
58
+ * Supplying a whole object still merges its fields; use `replace` to
59
+ * discard existing fields. Values must be plain JSON at runtime; this
60
+ * structural type cannot distinguish data-only classes from interfaces.
61
+ *
62
+ * On an unbound collection (`T` is `DocumentData`) every key is
63
+ * optional, so any field accepts a value, a nested patch or `null`.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * type Ticket = {
68
+ * title: string;
69
+ * note?: string;
70
+ * meta: { owner: string; reviewer?: string };
71
+ * extra?: { flag?: boolean };
72
+ * };
73
+ *
74
+ * const patch: MergePatch<Ticket> = {
75
+ * note: null, // deletes `note`
76
+ * meta: { reviewer: null }, // merges into the required `meta`
77
+ * extra: { flag: true }, // supplies the whole optional object
78
+ * };
79
+ * // @ts-expect-error — `title` is required; use `replace` to remove it
80
+ * const bad: MergePatch<Ticket> = { title: null };
81
+ * ```
82
+ */
83
+ type MergePatch<T> = { [K in keyof T]?: string extends K ? MergePatchObjectValue<T[K]> | null : {} extends Pick<T, K> ? T[K] | null : MergePatchValue<T[K]>; };
84
+ /**
85
+ * Only a single object type guarantees that required nested fields
86
+ * already exist. A union may switch variants, so it takes a whole value.
87
+ */
88
+ type MergePatchValue<V> = true extends IsUnion<V> ? V : MergePatchObjectValue<V>;
89
+ type IsUnion<T, Whole = T> = T extends Whole ? ([Whole] extends [T] ? false : true) : never;
90
+ /** Index-signature values stay permissive, including nested patches. */
91
+ type MergePatchObjectValue<V> = V extends readonly unknown[] ? V : V extends object ? MergePatch<V> : V;
82
92
  type JSONObject = {
83
93
  [x: string]: JSONValue;
84
94
  };
85
95
  type JSONValue = string | number | boolean | null | JSONObject | Array<JSONValue>;
86
- //#endregion
87
- //#region packages/protocol/src/query/wire.d.ts
88
96
  /**
89
97
  * Runtime mirror of {@link PredicateOpName}. The type derives from this
90
98
  * tuple so the value is the single source of truth: the spec generator
91
- * and the drift gate enumerate `PREDICATE_OPS`, and tsgo rejects any
99
+ * and the drift gate enumerate `PREDICATE_OPS`, and tsc rejects any
92
100
  * member added to the type-union without a matching tuple entry.
93
101
  */
94
102
  declare const PREDICATE_OPS: readonly ["eq", "gt", "gte", "lt", "lte", "in"];
@@ -132,66 +140,49 @@ interface PredicateClause {
132
140
  interface PredicateWire {
133
141
  readonly clauses: ReadonlyArray<PredicateClause>;
134
142
  }
135
- //#endregion
136
- //#region packages/protocol/src/indexes.d.ts
137
143
  /**
138
- * A secondary index declaration. Lives in `baerly.config.ts` under
139
- * `collections.<name>.indexes[]` and is threaded through
140
- * `Writer` via `WriterOptions.indexes`.
144
+ * A secondary index declaration, under `collections.<name>.indexes[]`
145
+ * in `baerly.config.ts`.
146
+ *
147
+ * **An index does not speed up reads, change which rows a read
148
+ * returns, or cost a write anything.** Every read folds the
149
+ * collection's snapshot and log in full, and no storage call depends on
150
+ * the declaration. The declaration is validated and
151
+ * reserved for a future index-aware storage format; omit it unless an
152
+ * existing config already declares one.
141
153
  *
142
- * Validated synchronously by `validateIndexDefinition` (in
143
- * `@baerly/server`) at writer construction — see `name` below.
154
+ * `Db.create` validates every declaration and throws on a malformed
155
+ * one; see each field for the rule.
156
+ *
157
+ * @example
158
+ * ```ts
159
+ * { name: "by_status", on: "status" }
160
+ * ```
144
161
  */
145
162
  interface IndexDefinition {
146
163
  /**
147
- * Stable path-safe identifier, used directly as a key segment under
148
- * `<logPrefix>/index/<name>/...`. Must match `/^[a-z][a-z0-9_]*$/`.
149
- * A reserved leading-`_` name throws `InvalidConfig`; a malformed
150
- * name throws `SchemaError`. See docs/adr/003-layout-versioning-cordon.md.
164
+ * Stable identifier. Must match `/^[a-z][a-z0-9_]*$/`. A reserved
165
+ * leading-`_` name throws `InvalidConfig`; any other malformed name
166
+ * throws `SchemaError`.
151
167
  */
152
168
  readonly name: string;
153
169
  /**
154
- * Field name(s) to index on. `string` is a single-field index.
155
- * `readonly string[]` is composite; the read path can route a
156
- * left-anchored equality prefix and, when present, a range / `$in`
157
- * clause on the final indexed field beyond that equality prefix.
158
- *
159
- * Top-level fields only — dotted-path `on` values throw
160
- * `SchemaError` from `projectIndexValues`. A future change widens
161
- * the projector to dotted paths (mirroring what
162
- * `packages/server/src/query.ts` already does on the predicate
163
- * side).
170
+ * Field name(s) the index covers: a `string` for one field, a
171
+ * non-empty `readonly string[]` for a composite. Top-level fields
172
+ * only: an empty value throws `SchemaError` and a dotted path
173
+ * (`"meta.owner"`) throws `InvalidConfig`, both at `Db.create`.
174
+ * A row may hold any value, arrays included, in a declared field.
164
175
  */
165
176
  readonly on: string | readonly string[];
166
177
  /**
167
- * Optional sparse-projection filter (wire-form). When present, the
168
- * writer emits index keys ONLY for docs that satisfy `predicate`
169
- * under `matchesWire(predicate, body)`. Sparse indexes shrink the
170
- * on-storage key set proportionally to filter selectivity — an
171
- * index that matches ~1% of writes pays ~1% of the dense Class-A
172
- * PUT cost.
173
- *
174
- * Operators allowed: `eq`, `gt`, `gte`, `lt`, `lte`, `in` — the
175
- * locked {@link PredicateOpName} vocabulary. Range-shaped and
176
- * `in`-shaped filters compose with the planner's cost-bias step
177
- * via the implication checker, which proves whether a query
178
- * predicate is contained in the filter's value range. A query
179
- * that the filter's range / set strictly contains will route
180
- * through the filtered index in preference to an unfiltered
181
- * alternative.
182
- *
183
- * Wire shape example:
178
+ * Optional filter in wire form, for example
184
179
  * `{ clauses: [{ op: "eq", field: "status", value: "open" }] }`.
185
- *
186
- * Planner cost-bias: a filtered index whose predicate is implied
187
- * by the query predicate outranks an unfiltered alternative; an
188
- * unfiltered index outranks a filtered one whose predicate is NOT
189
- * implied (walking the smaller key set would miss matching docs).
180
+ * Operators: `eq`, `gt`, `gte`, `lt`, `lte`, `in` (the
181
+ * {@link PredicateOpName} vocabulary). An invalid predicate throws
182
+ * `SchemaError`. It never restricts what a query returns.
190
183
  */
191
184
  readonly predicate?: PredicateWire;
192
185
  }
193
- //#endregion
194
- //#region packages/protocol/src/schema.d.ts
195
186
  /**
196
187
  * Schema-validator adapter type for `Db.insert` / `Query.update` /
197
188
  * `Collection.replace` boundary checks.
@@ -273,19 +264,21 @@ interface SchemaIssue {
273
264
  readonly key: PropertyKey;
274
265
  }> | undefined;
275
266
  }
276
- //#endregion
277
- //#region packages/protocol/src/app-config.d.ts
278
267
  /**
279
- * One collection's declarative config. Today `indexes` and `schema`
280
- * are consumed; future tickets add `replica_identity` and lifecycle
281
- * hooks.
268
+ * One collection's declarative config: an optional `schema`, and
269
+ * optional `indexes`, which are validated but do not affect reads.
282
270
  */
283
271
  interface CollectionDefinition {
284
272
  /**
285
- * Secondary indexes declared for this collection. Each declared
286
- * index produces one zero-byte PUT per commit (when the indexed
287
- * field is set on the doc) inside the same fence as the log
288
- * entry and content body. See `./indexes.ts` for the key shape.
273
+ * Reserved secondary-index declarations. **They do not speed up
274
+ * reads or change which rows a read returns**: every read folds the
275
+ * collection's snapshot and log in full. Omit this field unless an
276
+ * existing config already declares indexes.
277
+ *
278
+ * `Db.create` validates each entry and throws on a malformed one
279
+ * (see {@link IndexDefinition}), so names and shapes stay reserved
280
+ * for a future index-aware storage format. A declared index changes
281
+ * no storage call: writes cost what they cost without it.
289
282
  */
290
283
  readonly indexes?: ReadonlyArray<IndexDefinition>;
291
284
  /**
@@ -317,7 +310,20 @@ interface CollectionDefinition {
317
310
  /**
318
311
  * The full `baerly.config.ts` runtime shape. Re-exported from
319
312
  * `baerly-storage` and consumed by the day-1 `npm create baerly`
320
- * scaffold + the `baerly admin rebuild-index` CLI.
313
+ * scaffold and the `baerly` CLI.
314
+ *
315
+ * The two-tier shape — collections namespaced under `collections`,
316
+ * reserved keys at the top level — is deliberate. Flattening collection
317
+ * names to the top level was evaluated and rejected: it needs a
318
+ * discriminator separating a user-chosen collection name from a reserved
319
+ * key, and both candidates fail. A reserved-key allowlist
320
+ * (`Exclude<keyof C, ReservedKeys>`) breaks every time a config key is
321
+ * added — that set has already grown twice — turning each future
322
+ * addition into a breaking change or a forced rename for whoever named a
323
+ * collection after it. A structural sentinel keyed on `schema:` presence
324
+ * fails because {@link CollectionDefinition.schema} is optional, and
325
+ * `{ notes: {} }` is the hello-world shape the `examples/minimal-*`
326
+ * scaffolds ship. The namespace is what keeps config growth additive.
321
327
  */
322
328
  interface BaerlyConfig {
323
329
  /**
@@ -348,14 +354,18 @@ interface BaerlyConfig {
348
354
  * are set — this is the "dev default in config, prod override via
349
355
  * env" recipe.
350
356
  *
351
- * **`auth` only gates the kernel's HTTP router.** It's consumed by
352
- * `baerlyWorker` / `baerlyNode` / `createRouter` to decide who can
353
- * hit `/v1/*`. If you use `Db` directly without mounting any of
354
- * those (server-internal jobs, your own Hono/Express router, a CLI
355
- * embedding the kernel), this field is inert — each `Db.create` call
356
- * already carries an explicit `tenant:`, and your handler's own
357
- * auth layer decides who reaches the call. Set `auth: "none"` to
358
- * silence the typecheck requirement in that case.
357
+ * **`auth` is enforced only by `baerlyWorker` / `baerlyNode`** (the
358
+ * dev Vite plugin and `baerly doctor` also read it). The adapters
359
+ * resolve a `Verifier` from it (unless `verifier:` overrides it) and
360
+ * run it before building the per-request `Db` and router, deciding
361
+ * who can hit `/v1/*`. `createRouter` has no auth seam: it serves
362
+ * every request it receives as its `Db`'s tenant. If you call `Db` or
363
+ * `createRouter` yourself (server-internal jobs, your own
364
+ * Hono/Express router, a CLI embedding the kernel), this field is
365
+ * inert — each `Db.create` call carries an explicit `tenant:`, and
366
+ * your own auth layer decides who reaches the call and which tenant
367
+ * it gets. Set `auth: "none"` to satisfy the required field in that
368
+ * case.
359
369
  *
360
370
  * Field is required on `BaerlyAppConfig`. Omitting it causes both a
361
371
  * TypeScript error at `defineConfig({...})` and (defensively) an
@@ -372,7 +382,7 @@ type AuthConfig = (typeof AUTH_CONFIG_VALUES)[number];
372
382
  *
373
383
  * Exposed at `@gusto/baerly-storage/config`. Imported by the
374
384
  * `baerly.config.ts` that `npm create baerly` emits, and by anyone
375
- * who wants IDE/`tsgo` type inference on the full scaffold-aware
385
+ * who wants IDE/`tsc` type inference on the full scaffold-aware
376
386
  * config shape on top of the runtime `BaerlyConfig.collections` map.
377
387
  *
378
388
  * One `baerly.config.ts` carries both scaffold metadata (consumed by
@@ -449,7 +459,7 @@ interface BaerlyAppConfig extends BaerlyConfig {
449
459
  }
450
460
  /**
451
461
  * Identity helper that pins the config's TypeScript shape so IDEs
452
- * surface autocomplete and `tsgo --noEmit` catches typos at write
462
+ * surface autocomplete and `tsc --noEmit` catches typos at write
453
463
  * time. Returns its input verbatim — no runtime transformation.
454
464
  *
455
465
  * Two overloads: one for the scaffold-flavoured `BaerlyAppConfig`
@@ -528,6 +538,4 @@ type RowOf<C extends BaerlyConfig, N extends CollectionNames<C>> = C extends {
528
538
  } ? N extends keyof Cs ? Cs[N] extends {
529
539
  readonly schema: infer S;
530
540
  } ? S extends SchemaValidator<unknown, infer Out> ? Out : Record<string, unknown> : Record<string, unknown> : Record<string, unknown> : Record<string, unknown>;
531
- //#endregion
532
- export { MAINTENANCE_PROFILE_NODE as _, CollectionNames as a, defineConfig as c, IndexDefinition as d, DocumentData as f, MAINTENANCE_PROFILE_CF_PAID as g, MAINTENANCE_PROFILE_CF_FREE as h, CollectionDefinition as i, SchemaIssue as l, JSONValue as m, BaerlyAppConfig as n, RowOf as o, DocumentValue as p, BaerlyConfig as r, UnboundConfig as s, AuthConfig as t, SchemaValidator as u, SNAPSHOT_SCHEMA_VERSION as v };
533
- //# sourceMappingURL=app-config-DyiFK3_k.d.ts.map
541
+ export { CollectionNames as a, defineConfig as c, IndexDefinition as d, DocumentData as f, MergePatch as h, CollectionDefinition as i, SchemaIssue as l, JSONValue as m, BaerlyAppConfig as n, RowOf as o, DocumentValue as p, BaerlyConfig as r, UnboundConfig as s, AuthConfig as t, SchemaValidator as u };
@@ -1,2 +1,32 @@
1
- import { a as CollectionNames, c as defineConfig, f as DocumentData, i as CollectionDefinition, n as BaerlyAppConfig, o as RowOf, p as DocumentValue, r as BaerlyConfig, s as UnboundConfig, t as AuthConfig } from "./app-config-DyiFK3_k.js";
1
+ /**
2
+ * Collection-config schema types + `defineConfig` identity helper.
3
+ *
4
+ * Lives in `@baerly/protocol` (the cross-platform package) so the
5
+ * scaffold's `baerly.config.ts` and the client can reference these
6
+ * types without transitively dragging Node-only server modules
7
+ * (`AsyncLocalStorage` etc.) into their import graph.
8
+ *
9
+ * Runtime helpers that operate on these shapes —
10
+ * `collectionsToMaps`, `validateIndexDefinition`, `validateOrThrow`
11
+ * — stay in `@baerly/server`; they have impl detail that's allowed
12
+ * to depend on Node-only modules.
13
+ *
14
+ * @see ./indexes.ts — `IndexDefinition` type.
15
+ * @see ./schema.ts — `SchemaValidator` / `SchemaIssue` types.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * import { defineConfig } from "@gusto/baerly-storage/config";
20
+ *
21
+ * export default defineConfig({
22
+ * app: "tickets",
23
+ * tenant: "acme",
24
+ * target: "cloudflare",
25
+ * collections: {
26
+ * tickets: {},
27
+ * },
28
+ * });
29
+ * ```
30
+ */
31
+ import { a as CollectionNames, c as defineConfig, f as DocumentData, i as CollectionDefinition, n as BaerlyAppConfig, o as RowOf, p as DocumentValue, r as BaerlyConfig, s as UnboundConfig, t as AuthConfig } from "./app-config-C6qW7m8S.js";
2
32
  export { AuthConfig, BaerlyAppConfig, BaerlyConfig, CollectionDefinition, CollectionNames, type DocumentData, type DocumentValue, RowOf, UnboundConfig, defineConfig };
@@ -1,8 +1,7 @@
1
- //#region packages/protocol/src/app-config.ts
1
+ // packages/protocol/src/app-config.ts
2
2
  function defineConfig(cfg) {
3
3
  return cfg;
4
4
  }
5
- //#endregion
6
5
  export { defineConfig };
7
6
 
8
7
  //# sourceMappingURL=app-config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"app-config.js","names":[],"sources":["../packages/protocol/src/app-config.ts"],"sourcesContent":["/**\n * Collection-config schema types + `defineConfig` identity helper.\n *\n * Lives in `@baerly/protocol` (the cross-platform package) so the\n * scaffold's `baerly.config.ts` and the client can reference these\n * types without transitively dragging Node-only server modules\n * (`AsyncLocalStorage` etc.) into their import graph.\n *\n * Runtime helpers that operate on these shapes —\n * `collectionsToMaps`, `validateIndexDefinition`, `validateOrThrow`\n * — stay in `@baerly/server`; they have impl detail that's allowed\n * to depend on Node-only modules.\n *\n * @see ./indexes.ts — `IndexDefinition` type.\n * @see ./schema.ts — `SchemaValidator` / `SchemaIssue` types.\n *\n * @example\n * ```ts\n * import { defineConfig } from \"@gusto/baerly-storage/config\";\n *\n * export default defineConfig({\n * app: \"tickets\",\n * tenant: \"acme\",\n * target: \"cloudflare\",\n * collections: {\n * tickets: {\n * indexes: [\n * { name: \"by_status\", on: \"status\" },\n * { name: \"by_assignee\", on: \"assignee\" },\n * ],\n * },\n * },\n * });\n * ```\n */\n\nimport type { AUTH_CONFIG_VALUES } from \"./constants.ts\";\nimport type { IndexDefinition } from \"./indexes.ts\";\nimport type { SchemaValidator } from \"./schema.ts\";\n\n// Cross-platform protocol types re-exported from `@gusto/baerly-storage/config`\n// so the scaffold's `baerly.config.ts` and its sibling `types.ts` can\n// pull every shape they need from one DOM-pure entry. `DocumentData`\n// is the row-shape constraint that scaffolded `interface Note extends\n// DocumentData {...}` declarations target; re-exporting here keeps the\n// example's typecheck graph from reaching into the server barrel.\nexport type { DocumentData, DocumentValue } from \"./json.ts\";\n\n/**\n * One collection's declarative config. Today `indexes` and `schema`\n * are consumed; future tickets add `replica_identity` and lifecycle\n * hooks.\n */\nexport interface CollectionDefinition {\n /**\n * Secondary indexes declared for this collection. Each declared\n * index produces one zero-byte PUT per commit (when the indexed\n * field is set on the doc) inside the same fence as the log\n * entry and content body. See `./indexes.ts` for the key shape.\n */\n readonly indexes?: ReadonlyArray<IndexDefinition>;\n /**\n * Optional schema for this collection. When set, every server-side\n * `insert` / `update` / `replace` validates the resulting post-image\n * before committing — invalid input throws\n * `BaerlyError{code:\"SchemaError\"}` carrying a `.issues` array of\n * `{ path, message }` entries.\n *\n * Adapter: StandardSchemaV1 (see `./schema.ts`). Compatible with\n * Zod 3.24+, Valibot 0.36+, ArkType 2.0+ today; any future library\n * implementing the spec works without a code change here.\n *\n * `undefined` means no validation — every write proceeds as today\n * (zero overhead, today's tests untouched).\n *\n * @remarks\n * **`.nullable()` is not supported.** baerly's `DocumentValue` excludes\n * `null` by design (see `packages/protocol/src/json.ts`). `null` is\n * reserved as the JSON-merge-patch (RFC 7386) field-deletion sentinel\n * in `update` patches. Use `.optional()` for absent values.\n *\n * Validation runs on the post-image: `update` and `replace` see the\n * full doc, not just the patch. Failures throw\n * `BaerlyError{ code: \"SchemaError\", issues: [...] }`.\n */\n readonly schema?: SchemaValidator;\n}\n\n/**\n * The full `baerly.config.ts` runtime shape. Re-exported from\n * `baerly-storage` and consumed by the day-1 `npm create baerly`\n * scaffold + the `baerly admin rebuild-index` CLI.\n */\nexport interface BaerlyConfig {\n /**\n * Per-collection declarations, keyed by collection name. Required\n * (declare `{}` when you have no collections yet) — this keeps the\n * config interface from being structurally empty, which would\n * trigger TypeScript's weak-type check when the adapter accepts\n * the literal as `BaerlyWorkerOptions.config` / `BaerlyNodeOptions.config`.\n */\n readonly collections: Readonly<Record<string, CollectionDefinition>>;\n}\n\n/**\n * Auth posture for the deployed app. REQUIRED on `BaerlyAppConfig`.\n *\n * - `\"none\"`: no header check; every request resolves to\n * `config.tenant`. Use for local dev, intranet deployments, CLI\n * tools — contexts where the network seam itself is the trust\n * boundary. The adapter logs one startup line so the state is not\n * silent.\n * - `\"shared-secret\"`: bearer-token check; the adapter reads\n * `SHARED_SECRET` from the runtime env and pins every request to\n * `config.tenant`. Module init throws `BaerlyError(\"InvalidConfig\", ...)`\n * on first `fetch` if the env var is missing/empty.\n *\n * For custom verifiers (Cloudflare Access, JWT, SigV4, …), pass a\n * `Verifier` directly to the adapter factory's `verifier:` option.\n * The factory `verifier:` silently overrides `config.auth` when both\n * are set — this is the \"dev default in config, prod override via\n * env\" recipe.\n *\n * **`auth` only gates the kernel's HTTP router.** It's consumed by\n * `baerlyWorker` / `baerlyNode` / `createRouter` to decide who can\n * hit `/v1/*`. If you use `Db` directly without mounting any of\n * those (server-internal jobs, your own Hono/Express router, a CLI\n * embedding the kernel), this field is inert — each `Db.create` call\n * already carries an explicit `tenant:`, and your handler's own\n * auth layer decides who reaches the call. Set `auth: \"none\"` to\n * silence the typecheck requirement in that case.\n *\n * Field is required on `BaerlyAppConfig`. Omitting it causes both a\n * TypeScript error at `defineConfig({...})` and (defensively) an\n * `InvalidConfig` error at adapter module init.\n *\n * The literal values come from\n * {@link AUTH_CONFIG_VALUES} so the runtime-only consumers (doctor,\n * adapter) share the same source of truth.\n */\nexport type AuthConfig = (typeof AUTH_CONFIG_VALUES)[number];\n\n/**\n * `BaerlyAppConfig` extends `BaerlyConfig` with scaffold-flavoured\n * deploy metadata (`target`, `domain`, `cloudflareAccess`, etc.).\n *\n * Exposed at `@gusto/baerly-storage/config`. Imported by the\n * `baerly.config.ts` that `npm create baerly` emits, and by anyone\n * who wants IDE/`tsgo` type inference on the full scaffold-aware\n * config shape on top of the runtime `BaerlyConfig.collections` map.\n *\n * One `baerly.config.ts` carries both scaffold metadata (consumed by\n * `baerly deploy` / `baerly doctor`) and the runtime schema\n * (consumed by `Db.create`). The literal-pinned return type of\n * {@link defineConfig} makes `collections` flow through to\n * `Db.create<TConfig>` and `createBaerlyClient<TConfig>`.\n */\nexport interface BaerlyAppConfig extends BaerlyConfig {\n /** Bucket-prefix for this baerly app. One bucket per app. */\n readonly app: string;\n /**\n * Default tenant pin for `Verifier`s that don't derive a tenant\n * from a claim. Production `Verifier`s (`bearerJwt`,\n * `cloudflareAccess`) ignore this and derive `tenantPrefix` from\n * the request.\n */\n readonly tenant: string;\n /**\n * Deploy target — `\"cloudflare\"` or `\"node\"`.\n * Read by `baerly deploy` to dispatch the correct deploy command.\n */\n readonly target: \"cloudflare\" | \"node\";\n /**\n * Optional. Custom domain for the deployed service. Cloudflare:\n * wired to the Worker as a route. Node: rendered into the\n * Dockerfile's `EXPOSE` and the emitted readme.\n */\n readonly domain?: string | undefined;\n /**\n * Names of secrets the deployed runtime needs. `baerly deploy`\n * and `baerly doctor` check each against the platform's secret\n * store and warn (deploy) / report (doctor) when missing.\n * Default treatment (when unset) is `[\"SHARED_SECRET\"]` — matches\n * the scaffolder's emitted Verifier wiring.\n */\n readonly requiredSecrets?: readonly string[];\n /**\n * Optional Cloudflare Access app config. When set, the production\n * CF template prefers `cloudflareAccess()` as the `Verifier` and\n * `baerly doctor --target=cloudflare` walks the CF Access app\n * config to confirm the audience tag matches.\n *\n * - `teamDomain` — CF Access team domain, e.g. `\"acme\"`.\n * - `audienceTag` — Application Audience (AUD) tag from the CF\n * Access app, 64 lowercase-hex characters.\n */\n readonly cloudflareAccess?: {\n readonly teamDomain: string;\n readonly audienceTag: string;\n };\n /**\n * Optional observability overrides. The templates already\n * read `LOG_LEVEL` from the runtime env; this field is a\n * typed-config alternative for deployments that prefer to pin\n * defaults in source. See `docs/guide/observability.md` for the\n * canonical-line shape and `docs/contributing/conventions/observability.md` for\n * the one-canonical-line-per-unit-of-work rule.\n *\n * - `level` — lowest record level reaching the sink. Falls back\n * to the `LOG_LEVEL` env var, then to `\"info\"`.\n */\n readonly observability?: {\n readonly level?: \"debug\" | \"info\" | \"warn\" | \"error\";\n };\n /**\n * Auth posture. See {@link AuthConfig} for the full per-value\n * semantics, the failure modes, and the \"dev default, prod override\"\n * recipe. Field is required — omission fails typecheck and (for\n * adapters that didn't supply a `verifier:` override) throws\n * `BaerlyError(\"InvalidConfig\", ...)` at first request.\n */\n readonly auth: AuthConfig;\n}\n\n/**\n * Identity helper that pins the config's TypeScript shape so IDEs\n * surface autocomplete and `tsgo --noEmit` catches typos at write\n * time. Returns its input verbatim — no runtime transformation.\n *\n * Two overloads: one for the scaffold-flavoured `BaerlyAppConfig`\n * (the shape `npm create baerly` emits, which carries `app`,\n * `tenant`, `target` deploy metadata) and one for the runtime\n * `BaerlyConfig` shape (just `collections`, used by tests and by\n * apps that wire deploy metadata in some other way). Both preserve\n * the literal shape of `cfg` via `<const C>` so `CollectionNames<C>`\n * and `RowOf<C, N>` resolve to literal unions.\n */\nexport function defineConfig<const C extends BaerlyAppConfig>(cfg: C): C;\nexport function defineConfig<const C extends BaerlyConfig>(cfg: C): C;\nexport function defineConfig<const C extends BaerlyConfig>(cfg: C): C {\n return cfg;\n}\n\n/**\n * Sentinel `BaerlyConfig` used as the default `TConfig` parameter\n * by consumers (`Db<TConfig>`, `BaerlyClient<TConfig>`). Setting\n * `collections` to `Record<string, CollectionDefinition>` makes\n * `CollectionNames<UnboundConfig>` widen to `string`, so the single\n * typed accessor `db.collection<N extends CollectionNames<TConfig>>(name: N)`\n * still resolves for kernel-internal paths (which carry no bound\n * config) — those callers see `name: string` and the row type\n * defaults to `DocumentData` via {@link RowOf}'s `Record<string, unknown>`\n * fallback. Consumers who bind a config via {@link defineConfig}\n * narrow `CollectionNames<TConfig>` to a literal union and lose the\n * string-typo accepting behaviour, which is the design intent.\n */\nexport type UnboundConfig = { readonly collections: Record<string, CollectionDefinition> };\n\n/**\n * Set of declared collection names on a `BaerlyConfig`, as a string\n * union. Resolves to `never` when no `collections` are declared\n * (notably for `UnboundConfig`), which the typed `Db` / client\n * overloads use to disable narrowing for unbound consumers.\n *\n * @example\n * ```ts\n * const config = defineConfig({\n * collections: {\n * tickets: { schema: TicketSchema },\n * audits: {},\n * },\n * });\n * type Names = CollectionNames<typeof config>; // \"tickets\" | \"audits\"\n * ```\n */\nexport type CollectionNames<C extends BaerlyConfig> = C extends {\n readonly collections: infer Cs;\n}\n ? Extract<keyof Cs, string>\n : never;\n\n/**\n * Row type for collection `N` on config `C`. Resolves to the\n * `StandardSchemaV1` output type of `C[\"collections\"][N][\"schema\"]`\n * when one is declared; otherwise falls back to\n * `Record<string, unknown>`.\n *\n * The fallback is intentionally wider than the protocol's\n * `DocumentData`. Downstream call sites that need\n * `DocumentData` (e.g. `Collection<T extends DocumentData>`)\n * apply the intersection at their own seam — keeping that\n * constraint local to the consumer keeps THIS file independent of\n * `@baerly/protocol/src/json.ts`.\n *\n * @example\n * ```ts\n * const config = defineConfig({\n * collections: {\n * tickets: { schema: TicketSchema },\n * audits: {},\n * },\n * });\n * type Ticket = RowOf<typeof config, \"tickets\">; // z.infer<typeof TicketSchema>\n * type Audit = RowOf<typeof config, \"audits\">; // Record<string, unknown>\n * ```\n */\nexport type RowOf<C extends BaerlyConfig, N extends CollectionNames<C>> = C extends {\n readonly collections: infer Cs;\n}\n ? N extends keyof Cs\n ? Cs[N] extends { readonly schema: infer S }\n ? S extends SchemaValidator<unknown, infer Out>\n ? Out\n : Record<string, unknown>\n : Record<string, unknown>\n : Record<string, unknown>\n : Record<string, unknown>;\n"],"mappings":";AA+OA,SAAgB,aAA2C,KAAW;CACpE,OAAO;AACT"}
1
+ {"version":3,"file":"app-config.js","names":[],"sources":["../packages/protocol/src/app-config.ts"],"sourcesContent":["/**\n * Collection-config schema types + `defineConfig` identity helper.\n *\n * Lives in `@baerly/protocol` (the cross-platform package) so the\n * scaffold's `baerly.config.ts` and the client can reference these\n * types without transitively dragging Node-only server modules\n * (`AsyncLocalStorage` etc.) into their import graph.\n *\n * Runtime helpers that operate on these shapes —\n * `collectionsToMaps`, `validateIndexDefinition`, `validateOrThrow`\n * — stay in `@baerly/server`; they have impl detail that's allowed\n * to depend on Node-only modules.\n *\n * @see ./indexes.ts — `IndexDefinition` type.\n * @see ./schema.ts — `SchemaValidator` / `SchemaIssue` types.\n *\n * @example\n * ```ts\n * import { defineConfig } from \"@gusto/baerly-storage/config\";\n *\n * export default defineConfig({\n * app: \"tickets\",\n * tenant: \"acme\",\n * target: \"cloudflare\",\n * collections: {\n * tickets: {},\n * },\n * });\n * ```\n */\n\nimport type { AUTH_CONFIG_VALUES } from \"./constants.ts\";\nimport type { IndexDefinition } from \"./indexes.ts\";\nimport type { SchemaValidator } from \"./schema.ts\";\n\n// Cross-platform protocol types re-exported from `@gusto/baerly-storage/config`\n// so the scaffold's `baerly.config.ts` and its sibling `types.ts` can\n// pull every shape they need from one DOM-pure entry. `DocumentData`\n// is the row-shape constraint that scaffolded `interface Note extends\n// DocumentData {...}` declarations target; re-exporting here keeps the\n// example's typecheck graph from reaching into the server barrel.\nexport type { DocumentData, DocumentValue } from \"./json.ts\";\n\n/**\n * One collection's declarative config: an optional `schema`, and\n * optional `indexes`, which are validated but do not affect reads.\n */\nexport interface CollectionDefinition {\n /**\n * Reserved secondary-index declarations. **They do not speed up\n * reads or change which rows a read returns**: every read folds the\n * collection's snapshot and log in full. Omit this field unless an\n * existing config already declares indexes.\n *\n * `Db.create` validates each entry and throws on a malformed one\n * (see {@link IndexDefinition}), so names and shapes stay reserved\n * for a future index-aware storage format. A declared index changes\n * no storage call: writes cost what they cost without it.\n */\n readonly indexes?: ReadonlyArray<IndexDefinition>;\n /**\n * Optional schema for this collection. When set, every server-side\n * `insert` / `update` / `replace` validates the resulting post-image\n * before committing — invalid input throws\n * `BaerlyError{code:\"SchemaError\"}` carrying a `.issues` array of\n * `{ path, message }` entries.\n *\n * Adapter: StandardSchemaV1 (see `./schema.ts`). Compatible with\n * Zod 3.24+, Valibot 0.36+, ArkType 2.0+ today; any future library\n * implementing the spec works without a code change here.\n *\n * `undefined` means no validation — every write proceeds as today\n * (zero overhead, today's tests untouched).\n *\n * @remarks\n * **`.nullable()` is not supported.** baerly's `DocumentValue` excludes\n * `null` by design (see `packages/protocol/src/json.ts`). `null` is\n * reserved as the JSON-merge-patch (RFC 7386) field-deletion sentinel\n * in `update` patches. Use `.optional()` for absent values.\n *\n * Validation runs on the post-image: `update` and `replace` see the\n * full doc, not just the patch. Failures throw\n * `BaerlyError{ code: \"SchemaError\", issues: [...] }`.\n */\n readonly schema?: SchemaValidator;\n}\n\n/**\n * The full `baerly.config.ts` runtime shape. Re-exported from\n * `baerly-storage` and consumed by the day-1 `npm create baerly`\n * scaffold and the `baerly` CLI.\n *\n * The two-tier shape — collections namespaced under `collections`,\n * reserved keys at the top level — is deliberate. Flattening collection\n * names to the top level was evaluated and rejected: it needs a\n * discriminator separating a user-chosen collection name from a reserved\n * key, and both candidates fail. A reserved-key allowlist\n * (`Exclude<keyof C, ReservedKeys>`) breaks every time a config key is\n * added — that set has already grown twice — turning each future\n * addition into a breaking change or a forced rename for whoever named a\n * collection after it. A structural sentinel keyed on `schema:` presence\n * fails because {@link CollectionDefinition.schema} is optional, and\n * `{ notes: {} }` is the hello-world shape the `examples/minimal-*`\n * scaffolds ship. The namespace is what keeps config growth additive.\n */\nexport interface BaerlyConfig {\n /**\n * Per-collection declarations, keyed by collection name. Required\n * (declare `{}` when you have no collections yet) — this keeps the\n * config interface from being structurally empty, which would\n * trigger TypeScript's weak-type check when the adapter accepts\n * the literal as `BaerlyWorkerOptions.config` / `BaerlyNodeOptions.config`.\n */\n readonly collections: Readonly<Record<string, CollectionDefinition>>;\n}\n\n/**\n * Auth posture for the deployed app. REQUIRED on `BaerlyAppConfig`.\n *\n * - `\"none\"`: no header check; every request resolves to\n * `config.tenant`. Use for local dev, intranet deployments, CLI\n * tools — contexts where the network seam itself is the trust\n * boundary. The adapter logs one startup line so the state is not\n * silent.\n * - `\"shared-secret\"`: bearer-token check; the adapter reads\n * `SHARED_SECRET` from the runtime env and pins every request to\n * `config.tenant`. Module init throws `BaerlyError(\"InvalidConfig\", ...)`\n * on first `fetch` if the env var is missing/empty.\n *\n * For custom verifiers (Cloudflare Access, JWT, SigV4, …), pass a\n * `Verifier` directly to the adapter factory's `verifier:` option.\n * The factory `verifier:` silently overrides `config.auth` when both\n * are set — this is the \"dev default in config, prod override via\n * env\" recipe.\n *\n * **`auth` is enforced only by `baerlyWorker` / `baerlyNode`** (the\n * dev Vite plugin and `baerly doctor` also read it). The adapters\n * resolve a `Verifier` from it (unless `verifier:` overrides it) and\n * run it before building the per-request `Db` and router, deciding\n * who can hit `/v1/*`. `createRouter` has no auth seam: it serves\n * every request it receives as its `Db`'s tenant. If you call `Db` or\n * `createRouter` yourself (server-internal jobs, your own\n * Hono/Express router, a CLI embedding the kernel), this field is\n * inert — each `Db.create` call carries an explicit `tenant:`, and\n * your own auth layer decides who reaches the call and which tenant\n * it gets. Set `auth: \"none\"` to satisfy the required field in that\n * case.\n *\n * Field is required on `BaerlyAppConfig`. Omitting it causes both a\n * TypeScript error at `defineConfig({...})` and (defensively) an\n * `InvalidConfig` error at adapter module init.\n *\n * The literal values come from\n * {@link AUTH_CONFIG_VALUES} so the runtime-only consumers (doctor,\n * adapter) share the same source of truth.\n */\nexport type AuthConfig = (typeof AUTH_CONFIG_VALUES)[number];\n\n/**\n * `BaerlyAppConfig` extends `BaerlyConfig` with scaffold-flavoured\n * deploy metadata (`target`, `domain`, `cloudflareAccess`, etc.).\n *\n * Exposed at `@gusto/baerly-storage/config`. Imported by the\n * `baerly.config.ts` that `npm create baerly` emits, and by anyone\n * who wants IDE/`tsc` type inference on the full scaffold-aware\n * config shape on top of the runtime `BaerlyConfig.collections` map.\n *\n * One `baerly.config.ts` carries both scaffold metadata (consumed by\n * `baerly deploy` / `baerly doctor`) and the runtime schema\n * (consumed by `Db.create`). The literal-pinned return type of\n * {@link defineConfig} makes `collections` flow through to\n * `Db.create<TConfig>` and `createBaerlyClient<TConfig>`.\n */\nexport interface BaerlyAppConfig extends BaerlyConfig {\n /** Bucket-prefix for this baerly app. One bucket per app. */\n readonly app: string;\n /**\n * Default tenant pin for `Verifier`s that don't derive a tenant\n * from a claim. Production `Verifier`s (`bearerJwt`,\n * `cloudflareAccess`) ignore this and derive `tenantPrefix` from\n * the request.\n */\n readonly tenant: string;\n /**\n * Deploy target — `\"cloudflare\"` or `\"node\"`.\n * Read by `baerly deploy` to dispatch the correct deploy command.\n */\n readonly target: \"cloudflare\" | \"node\";\n /**\n * Optional. Custom domain for the deployed service. Cloudflare:\n * wired to the Worker as a route. Node: rendered into the\n * Dockerfile's `EXPOSE` and the emitted readme.\n */\n readonly domain?: string | undefined;\n /**\n * Names of secrets the deployed runtime needs. `baerly deploy`\n * and `baerly doctor` check each against the platform's secret\n * store and warn (deploy) / report (doctor) when missing.\n * Default treatment (when unset) is `[\"SHARED_SECRET\"]` — matches\n * the scaffolder's emitted Verifier wiring.\n */\n readonly requiredSecrets?: readonly string[];\n /**\n * Optional Cloudflare Access app config. When set, the production\n * CF template prefers `cloudflareAccess()` as the `Verifier` and\n * `baerly doctor --target=cloudflare` walks the CF Access app\n * config to confirm the audience tag matches.\n *\n * - `teamDomain` — CF Access team domain, e.g. `\"acme\"`.\n * - `audienceTag` — Application Audience (AUD) tag from the CF\n * Access app, 64 lowercase-hex characters.\n */\n readonly cloudflareAccess?: {\n readonly teamDomain: string;\n readonly audienceTag: string;\n };\n /**\n * Optional observability overrides. The templates already\n * read `LOG_LEVEL` from the runtime env; this field is a\n * typed-config alternative for deployments that prefer to pin\n * defaults in source. See `docs/guide/observability.md` for the\n * canonical-line shape and `docs/contributing/conventions/observability.md` for\n * the one-canonical-line-per-unit-of-work rule.\n *\n * - `level` — lowest record level reaching the sink. Falls back\n * to the `LOG_LEVEL` env var, then to `\"info\"`.\n */\n readonly observability?: {\n readonly level?: \"debug\" | \"info\" | \"warn\" | \"error\";\n };\n /**\n * Auth posture. See {@link AuthConfig} for the full per-value\n * semantics, the failure modes, and the \"dev default, prod override\"\n * recipe. Field is required — omission fails typecheck and (for\n * adapters that didn't supply a `verifier:` override) throws\n * `BaerlyError(\"InvalidConfig\", ...)` at first request.\n */\n readonly auth: AuthConfig;\n}\n\n/**\n * Identity helper that pins the config's TypeScript shape so IDEs\n * surface autocomplete and `tsc --noEmit` catches typos at write\n * time. Returns its input verbatim — no runtime transformation.\n *\n * Two overloads: one for the scaffold-flavoured `BaerlyAppConfig`\n * (the shape `npm create baerly` emits, which carries `app`,\n * `tenant`, `target` deploy metadata) and one for the runtime\n * `BaerlyConfig` shape (just `collections`, used by tests and by\n * apps that wire deploy metadata in some other way). Both preserve\n * the literal shape of `cfg` via `<const C>` so `CollectionNames<C>`\n * and `RowOf<C, N>` resolve to literal unions.\n */\nexport function defineConfig<const C extends BaerlyAppConfig>(cfg: C): C;\nexport function defineConfig<const C extends BaerlyConfig>(cfg: C): C;\nexport function defineConfig<const C extends BaerlyConfig>(cfg: C): C {\n return cfg;\n}\n\n/**\n * Sentinel `BaerlyConfig` used as the default `TConfig` parameter\n * by consumers (`Db<TConfig>`, `BaerlyClient<TConfig>`). Setting\n * `collections` to `Record<string, CollectionDefinition>` makes\n * `CollectionNames<UnboundConfig>` widen to `string`, so the single\n * typed accessor `db.collection<N extends CollectionNames<TConfig>>(name: N)`\n * still resolves for kernel-internal paths (which carry no bound\n * config) — those callers see `name: string` and the row type\n * defaults to `DocumentData` via {@link RowOf}'s `Record<string, unknown>`\n * fallback. Consumers who bind a config via {@link defineConfig}\n * narrow `CollectionNames<TConfig>` to a literal union and lose the\n * string-typo accepting behaviour, which is the design intent.\n */\nexport type UnboundConfig = { readonly collections: Record<string, CollectionDefinition> };\n\n/**\n * Set of declared collection names on a `BaerlyConfig`, as a string\n * union. Resolves to `never` when no `collections` are declared\n * (notably for `UnboundConfig`), which the typed `Db` / client\n * overloads use to disable narrowing for unbound consumers.\n *\n * @example\n * ```ts\n * const config = defineConfig({\n * collections: {\n * tickets: { schema: TicketSchema },\n * audits: {},\n * },\n * });\n * type Names = CollectionNames<typeof config>; // \"tickets\" | \"audits\"\n * ```\n */\nexport type CollectionNames<C extends BaerlyConfig> = C extends {\n readonly collections: infer Cs;\n}\n ? Extract<keyof Cs, string>\n : never;\n\n/**\n * Row type for collection `N` on config `C`. Resolves to the\n * `StandardSchemaV1` output type of `C[\"collections\"][N][\"schema\"]`\n * when one is declared; otherwise falls back to\n * `Record<string, unknown>`.\n *\n * The fallback is intentionally wider than the protocol's\n * `DocumentData`. Downstream call sites that need\n * `DocumentData` (e.g. `Collection<T extends DocumentData>`)\n * apply the intersection at their own seam — keeping that\n * constraint local to the consumer keeps THIS file independent of\n * `@baerly/protocol/src/json.ts`.\n *\n * @example\n * ```ts\n * const config = defineConfig({\n * collections: {\n * tickets: { schema: TicketSchema },\n * audits: {},\n * },\n * });\n * type Ticket = RowOf<typeof config, \"tickets\">; // z.infer<typeof TicketSchema>\n * type Audit = RowOf<typeof config, \"audits\">; // Record<string, unknown>\n * ```\n */\nexport type RowOf<C extends BaerlyConfig, N extends CollectionNames<C>> = C extends {\n readonly collections: infer Cs;\n}\n ? N extends keyof Cs\n ? Cs[N] extends { readonly schema: infer S }\n ? S extends SchemaValidator<unknown, infer Out>\n ? Out\n : Record<string, unknown>\n : Record<string, unknown>\n : Record<string, unknown>\n : Record<string, unknown>;\n"],"mappings":";AA+PA,SAAgB,aAA2C,KAAW;CACpE,OAAO;AACT"}
package/dist/auth.d.ts CHANGED
@@ -1,6 +1,4 @@
1
- import { r as Verifier } from "./index-CEZKQsKt.js";
2
-
3
- //#region packages/server/src/auth/presets/shared-secret.d.ts
1
+ import { t as Verifier } from "./verifier-Bmlmndzo.js";
4
2
  /**
5
3
  * Options for {@link sharedSecret}.
6
4
  *
@@ -50,9 +48,7 @@ interface SharedSecretOptions {
50
48
  * });
51
49
  * ```
52
50
  */
53
- declare const sharedSecret: (opts: SharedSecretOptions) => Verifier;
54
- //#endregion
55
- //#region packages/server/src/auth/presets/bearer-jwt.d.ts
51
+ export declare const sharedSecret: (opts: SharedSecretOptions) => Verifier;
56
52
  /**
57
53
  * Options for {@link bearerJwt}.
58
54
  *
@@ -68,7 +64,10 @@ declare const sharedSecret: (opts: SharedSecretOptions) => Verifier;
68
64
  * - `tenantClaim` — name of the claim that carries the tenant
69
65
  * identifier. Defaults to `"tenant"`. Custom IdPs may use a
70
66
  * namespaced claim (`"https://example.com/tenant"`); set to that
71
- * string. Mutually exclusive with `tenantPrefix`.
67
+ * string. The claim picks the tenant a request reads and writes, so
68
+ * it must be one only an IdP admin can set; a claim the user can
69
+ * edit (profile metadata, a self-service attribute) lets them pick
70
+ * their own tenant. Mutually exclusive with `tenantPrefix`.
72
71
  * - `tenantPrefix` — pin every verified token to a fixed tenant
73
72
  * string, bypassing claim lookup. Use for single-tenant
74
73
  * deployments where the IdP doesn't ship a tenant claim (the
@@ -80,10 +79,10 @@ declare const sharedSecret: (opts: SharedSecretOptions) => Verifier;
80
79
  * `["RS256", "ES256", "EdDSA"]`. `none`, `HS256`, anything else
81
80
  * is rejected without consulting the JWKS.
82
81
  * - `clockSkewMs` — tolerance for `exp` / `nbf` checks. Defaults to
83
- * 60 000 (60 s).
82
+ * 60 000 (60 s). Must be a finite number `>= 0`.
84
83
  * - `jwksCacheTtlMs` — JWKS HTTP cache TTL. Defaults to 600 000
85
- * (10 min). The cache is per-factory-call; a fresh `bearerJwt()`
86
- * call starts cold.
84
+ * (10 min). Must be `>= 0`. The cache is per-factory-call; a fresh
85
+ * `bearerJwt()` call starts cold.
87
86
  * - `fetch` — `fetch` override. Defaults to `globalThis.fetch`.
88
87
  * Tests inject a stub.
89
88
  */
@@ -136,11 +135,14 @@ interface Jwk {
136
135
  * `groups`, …) pass through verbatim. The kernel types it as
137
136
  * `unknown` to keep `Verifier` plain; cast at the call site with the
138
137
  * payload shape your IdP emits, e.g. `const id = result.identity as
139
- * { sub: string }`. Token-level failures (bad signature, expired,
140
- * wrong audience, missing/non-string tenant claim) return `null`.
138
+ * { sub: string }`. Token-level failures (bad signature, missing or
139
+ * past `exp`, wrong audience, missing/non-string tenant claim) return
140
+ * `null`. Every token must carry `exp` (RFC 9068 §2.2); a token without
141
+ * one is rejected, not accepted forever.
141
142
  *
142
143
  * @throws BaerlyError code="InvalidConfig" — required option
143
- * missing, `issuer`/`audience` empty, `algorithms` empty.
144
+ * missing, `issuer`/`audience` empty, `algorithms` empty,
145
+ * `clockSkewMs` negative or non-finite, `jwksCacheTtlMs` negative.
144
146
  * @throws BaerlyError code="NetworkError" — JWKS fetch failed AND
145
147
  * the cache is cold. A stale cache hit on a network failure is
146
148
  * preferred over throwing (jose serves the stale JWKS until the
@@ -157,14 +159,14 @@ interface Jwk {
157
159
  * });
158
160
  * ```
159
161
  */
160
- declare const bearerJwt: (opts: BearerJwtOptions) => Verifier;
161
- //#endregion
162
- //#region packages/server/src/auth/presets/cloudflare-access.d.ts
162
+ export declare const bearerJwt: (opts: BearerJwtOptions) => Verifier;
163
163
  /**
164
164
  * Options for {@link cloudflareAccess}.
165
165
  *
166
- * - `teamDomain` — your CF Access team domain, e.g. `acme`. The
167
- * factory derives the JWKS URL from this:
166
+ * - `teamDomain` — your CF Access team name, e.g. `acme`: lowercase
167
+ * letters, digits and `-` only, not the full
168
+ * `acme.cloudflareaccess.com` host. The factory derives the JWKS URL
169
+ * from this:
168
170
  * `https://<teamDomain>.cloudflareaccess.com/cdn-cgi/access/certs`
169
171
  * and the issuer as
170
172
  * `https://<teamDomain>.cloudflareaccess.com`.
@@ -173,7 +175,10 @@ declare const bearerJwt: (opts: BearerJwtOptions) => Verifier;
173
175
  * - `tenantClaim` — same as `BearerJwtOptions.tenantClaim`.
174
176
  * Defaults to `"tenant"`. Set to a custom claim if you've wired
175
177
  * CF Access to a SAML / OIDC provider that ships a tenant in a
176
- * namespaced claim. Mutually exclusive with `tenantPrefix`.
178
+ * namespaced claim. The claim picks the tenant a request reads and
179
+ * writes, so it must be one only an IdP admin can set; a claim the
180
+ * user can edit lets them pick their own tenant. Mutually exclusive
181
+ * with `tenantPrefix`.
177
182
  * - `tenantPrefix` — pin every verified token to a fixed tenant
178
183
  * string. Use for single-tenant CF Access deployments: vanilla
179
184
  * CF Access JWTs ship `sub`/`email` but no `tenant` claim, so
@@ -199,9 +204,10 @@ interface CloudflareAccessOptions {
199
204
  * Cloudflare-side scaffold (`examples/minimal-cloudflare/`) defaults
200
205
  * to this factory.
201
206
  *
202
- * Internally a thin shim over `bearerJwt` — pulls the JWT from the
203
- * CF-specific header, points at CF Access's JWKS, and pins
204
- * issuer/audience to the CF-Access shape.
207
+ * Internally shares `bearerJwt`'s token verifier — pulls the JWT from
208
+ * the CF-specific header, points at CF Access's JWKS, and pins
209
+ * issuer/audience to the CF-Access shape. An `Authorization` header
210
+ * the app sent itself is never read.
205
211
  *
206
212
  * **Identity shape.** Same as {@link bearerJwt}: the returned
207
213
  * `identity` is the verified JWT payload CF Access mints (after IdP
@@ -209,8 +215,9 @@ interface CloudflareAccessOptions {
209
215
  * `identity.identity_nonce` — see Cloudflare's "Application Token"
210
216
  * reference. The kernel types it as `unknown`; cast at the call site.
211
217
  *
212
- * @throws BaerlyError code="InvalidConfig" — `teamDomain` or
213
- * `audienceTag` empty, or `audienceTag` not 64 lowercase-hex chars.
218
+ * @throws BaerlyError code="InvalidConfig" — `teamDomain` not a bare
219
+ * team name (`^[a-z0-9-]+$`), or `audienceTag` not 64 lowercase-hex
220
+ * chars.
214
221
  *
215
222
  * @example
216
223
  * ```ts
@@ -231,7 +238,5 @@ interface CloudflareAccessOptions {
231
238
  * });
232
239
  * ```
233
240
  */
234
- declare const cloudflareAccess: (opts: CloudflareAccessOptions) => Verifier;
235
- //#endregion
236
- export { type BearerJwtOptions, type CloudflareAccessOptions, type Jwk, type JwksDocument, type JwtAlgorithm, type SharedSecretOptions, bearerJwt, cloudflareAccess, sharedSecret };
237
- //# sourceMappingURL=auth.d.ts.map
241
+ export declare const cloudflareAccess: (opts: CloudflareAccessOptions) => Verifier;
242
+ export type { BearerJwtOptions, CloudflareAccessOptions, Jwk, JwksDocument, JwtAlgorithm, SharedSecretOptions };