@gusto/baerly-storage 0.1.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.
- package/README.md +97 -0
- package/dist/API.md +850 -0
- package/dist/app-config-Cb5dO2s9.d.ts +480 -0
- package/dist/app-config.d.ts +2 -0
- package/dist/app-config.js +8 -0
- package/dist/app-config.js.map +1 -0
- package/dist/auth.d.ts +237 -0
- package/dist/auth.js +1335 -0
- package/dist/auth.js.map +1 -0
- package/dist/baerly.js +761 -0
- package/dist/baerly.js.map +1 -0
- package/dist/bucket-uri-BrDEYvzy.js +4922 -0
- package/dist/bucket-uri-BrDEYvzy.js.map +1 -0
- package/dist/chunk-EAsCxrDo.js +14 -0
- package/dist/client-BLf3Ae5s.d.ts +233 -0
- package/dist/client-react.d.ts +131 -0
- package/dist/client-react.js +559 -0
- package/dist/client-react.js.map +1 -0
- package/dist/client.d.ts +4 -0
- package/dist/client.js +160 -0
- package/dist/client.js.map +1 -0
- package/dist/cloudflare-CINJPKCW.js +911 -0
- package/dist/cloudflare-CINJPKCW.js.map +1 -0
- package/dist/cloudflare.d.ts +211 -0
- package/dist/cloudflare.js +445 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/config-Bsg8wgwo.js +198 -0
- package/dist/config-Bsg8wgwo.js.map +1 -0
- package/dist/context-Oj7ffwD-.js +187 -0
- package/dist/context-Oj7ffwD-.js.map +1 -0
- package/dist/cost-B1WiZxlf.js +203 -0
- package/dist/cost-B1WiZxlf.js.map +1 -0
- package/dist/current-json-BkatBzF7.js +252 -0
- package/dist/current-json-BkatBzF7.js.map +1 -0
- package/dist/db-D62JguBc.d.ts +336 -0
- package/dist/deploy-BB-wqbhf.js +83 -0
- package/dist/deploy-BB-wqbhf.js.map +1 -0
- package/dist/dev-banner-CWHIk8tH.d.ts +26 -0
- package/dist/dev-vite.d.ts +146 -0
- package/dist/dev-vite.js +223 -0
- package/dist/dev-vite.js.map +1 -0
- package/dist/dev.d.ts +3 -0
- package/dist/dev.js +2 -0
- package/dist/doctor-B8h9GCN9.js +331 -0
- package/dist/doctor-B8h9GCN9.js.map +1 -0
- package/dist/dump-BHo_sIMZ.js +116 -0
- package/dist/dump-BHo_sIMZ.js.map +1 -0
- package/dist/errors-DOdL95kK.js +58 -0
- package/dist/errors-DOdL95kK.js.map +1 -0
- package/dist/export-Dz2PZKSR.js +423 -0
- package/dist/export-Dz2PZKSR.js.map +1 -0
- package/dist/fsck-DEz9lyCy.js +293 -0
- package/dist/fsck-DEz9lyCy.js.map +1 -0
- package/dist/http-CjUO1Bec.js +1756 -0
- package/dist/http-CjUO1Bec.js.map +1 -0
- package/dist/http.d.ts +1619 -0
- package/dist/http.js +2 -0
- package/dist/index-BGC-ENnj.d.ts +1065 -0
- package/dist/index-BYv0hb8M.d.ts +1457 -0
- package/dist/index-BquQkhJi.d.ts +112 -0
- package/dist/index-COsQ-Mlz.d.ts +146 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/indexes-BXn7a06a.js +297 -0
- package/dist/indexes-BXn7a06a.js.map +1 -0
- package/dist/indexes-DwOXkn1Y.d.ts +22 -0
- package/dist/inspect-x02aFWnh.js +149 -0
- package/dist/inspect-x02aFWnh.js.map +1 -0
- package/dist/log-walk-DIru96UT.js +260 -0
- package/dist/log-walk-DIru96UT.js.map +1 -0
- package/dist/maintenance-Bn6ul9aV.js +758 -0
- package/dist/maintenance-Bn6ul9aV.js.map +1 -0
- package/dist/maintenance.d.ts +323 -0
- package/dist/maintenance.js +2 -0
- package/dist/node.d.ts +422 -0
- package/dist/node.js +2 -0
- package/dist/normalize-XWY25_sG.js +133 -0
- package/dist/normalize-XWY25_sG.js.map +1 -0
- package/dist/observability-2IDYRuZK.js +2333 -0
- package/dist/observability-2IDYRuZK.js.map +1 -0
- package/dist/observability.d.ts +3 -0
- package/dist/observability.js +3 -0
- package/dist/plan-Cs17VqjU.js +224 -0
- package/dist/plan-Cs17VqjU.js.map +1 -0
- package/dist/query-DcSbFLJt.js +1880 -0
- package/dist/query-DcSbFLJt.js.map +1 -0
- package/dist/rebuild-index-C5gTXryd.js +119 -0
- package/dist/rebuild-index-C5gTXryd.js.map +1 -0
- package/dist/rebuild-index-DwXM0WfA.js +104 -0
- package/dist/rebuild-index-DwXM0WfA.js.map +1 -0
- package/dist/request-BEF_OvMh.js +72 -0
- package/dist/request-BEF_OvMh.js.map +1 -0
- package/dist/restore-CbKVMMpm.js +847 -0
- package/dist/restore-CbKVMMpm.js.map +1 -0
- package/dist/shared-secret-BJdSwpgw.js +71 -0
- package/dist/shared-secret-BJdSwpgw.js.map +1 -0
- package/dist/snapshot-D7C4_FSl.js +71 -0
- package/dist/snapshot-D7C4_FSl.js.map +1 -0
- package/dist/snapshot-z_N9hpTe.js +917 -0
- package/dist/snapshot-z_N9hpTe.js.map +1 -0
- package/dist/src-Chafbw8r.js +522 -0
- package/dist/src-Chafbw8r.js.map +1 -0
- package/dist/src-DyET_VPP.js +6199 -0
- package/dist/src-DyET_VPP.js.map +1 -0
- package/dist/src-n0Te1r98.js +352 -0
- package/dist/src-n0Te1r98.js.map +1 -0
- package/dist/subcommand-BWs6K7zb.js +110 -0
- package/dist/subcommand-BWs6K7zb.js.map +1 -0
- package/dist/usage-RVUQMLop.js +339 -0
- package/dist/usage-RVUQMLop.js.map +1 -0
- package/dist/validate-DhH1lO8I.js +377 -0
- package/dist/validate-DhH1lO8I.js.map +1 -0
- package/dist/wire-izfGZDvr.js +7 -0
- package/dist/wire-izfGZDvr.js.map +1 -0
- package/package.json +189 -0
|
@@ -0,0 +1,522 @@
|
|
|
1
|
+
import { d as SHARED_SECRET_MISSING_MESSAGE, f as decodeJsonBytes, l as NO_AUTH_CONFIGURED_MESSAGE, r as readCurrentJson } from "./current-json-BkatBzF7.js";
|
|
2
|
+
import { t as BaerlyError } from "./errors-DOdL95kK.js";
|
|
3
|
+
import { a as runReplaceById, i as runInsert, s as Writer, t as makeQuery } from "./query-DcSbFLJt.js";
|
|
4
|
+
import { t as sharedSecret } from "./shared-secret-BJdSwpgw.js";
|
|
5
|
+
//#region packages/protocol/src/storage/memory.ts
|
|
6
|
+
/**
|
|
7
|
+
* In-memory `Storage`. The randomized property test runs against
|
|
8
|
+
* this; it must be deterministic — no clocks beyond the caller's,
|
|
9
|
+
* no randomness, no I/O.
|
|
10
|
+
*
|
|
11
|
+
* ETags are a monotonically increasing hex counter formatted in the
|
|
12
|
+
* `"<hex>"` shape S3 returns (the surrounding double-quotes are part
|
|
13
|
+
* of the ETag header value). Keys are stored verbatim.
|
|
14
|
+
*/
|
|
15
|
+
var MemoryStorage = class {
|
|
16
|
+
#objects = /* @__PURE__ */ new Map();
|
|
17
|
+
#etagCounter = 0;
|
|
18
|
+
#nextEtag() {
|
|
19
|
+
this.#etagCounter += 1;
|
|
20
|
+
return `"${this.#etagCounter.toString(16)}"`;
|
|
21
|
+
}
|
|
22
|
+
async get(key, opts) {
|
|
23
|
+
opts?.signal?.throwIfAborted();
|
|
24
|
+
const stored = this.#objects.get(key);
|
|
25
|
+
if (stored === void 0) return null;
|
|
26
|
+
if (opts?.ifNoneMatch !== void 0 && opts.ifNoneMatch === stored.etag) return null;
|
|
27
|
+
return {
|
|
28
|
+
body: stored.body,
|
|
29
|
+
etag: stored.etag
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
async put(key, body, opts) {
|
|
33
|
+
opts?.signal?.throwIfAborted();
|
|
34
|
+
const existing = this.#objects.get(key);
|
|
35
|
+
if (opts?.ifNoneMatch === "*" && existing !== void 0) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifNoneMatch="*" but key exists)`);
|
|
36
|
+
if (opts?.ifMatch !== void 0) {
|
|
37
|
+
if (existing === void 0) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`);
|
|
38
|
+
if (existing.etag !== opts.ifMatch) throw new BaerlyError("Conflict", `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${existing.etag})`);
|
|
39
|
+
}
|
|
40
|
+
const etag = this.#nextEtag();
|
|
41
|
+
this.#objects.set(key, {
|
|
42
|
+
body,
|
|
43
|
+
etag,
|
|
44
|
+
...opts?.contentType !== void 0 && { contentType: opts.contentType }
|
|
45
|
+
});
|
|
46
|
+
return {
|
|
47
|
+
etag,
|
|
48
|
+
serverDate: /* @__PURE__ */ new Date()
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
async delete(key, opts) {
|
|
52
|
+
opts?.signal?.throwIfAborted();
|
|
53
|
+
this.#objects.delete(key);
|
|
54
|
+
}
|
|
55
|
+
async *list(prefix, opts) {
|
|
56
|
+
opts?.signal?.throwIfAborted();
|
|
57
|
+
const startAfter = opts?.startAfter ?? "";
|
|
58
|
+
const maxKeys = opts?.maxKeys ?? Infinity;
|
|
59
|
+
const sorted = [...this.#objects.keys()].filter((k) => k.startsWith(prefix) && k > startAfter).toSorted();
|
|
60
|
+
let yielded = 0;
|
|
61
|
+
for (const key of sorted) {
|
|
62
|
+
if (yielded >= maxKeys) return;
|
|
63
|
+
opts?.signal?.throwIfAborted();
|
|
64
|
+
const stored = this.#objects.get(key);
|
|
65
|
+
if (stored === void 0) continue;
|
|
66
|
+
yield {
|
|
67
|
+
key,
|
|
68
|
+
etag: stored.etag
|
|
69
|
+
};
|
|
70
|
+
yielded += 1;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Test-only: drop all objects.
|
|
75
|
+
* @internal
|
|
76
|
+
*/
|
|
77
|
+
_clear() {
|
|
78
|
+
this.#objects.clear();
|
|
79
|
+
this.#etagCounter = 0;
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
//#endregion
|
|
83
|
+
//#region packages/server/src/config.ts
|
|
84
|
+
/**
|
|
85
|
+
* Flatten `BaerlyConfig.collections` into the per-collection
|
|
86
|
+
* `schemas` and `indexes` maps that {@link Db.create} consumes at
|
|
87
|
+
* runtime. Used by the Cloudflare and Node adapters to pipe a
|
|
88
|
+
* single `config` object through to the writer/planner.
|
|
89
|
+
*
|
|
90
|
+
* Both adapters import this helper rather than inlining the loop
|
|
91
|
+
* so the projection rule (drop empty index arrays; omit absent
|
|
92
|
+
* schemas) stays in one place. Future `CollectionDefinition`
|
|
93
|
+
* fields (lifecycle hooks, replica_identity) land here too.
|
|
94
|
+
*/
|
|
95
|
+
const collectionsToMaps = (collections) => {
|
|
96
|
+
const schemas = /* @__PURE__ */ new Map();
|
|
97
|
+
const indexes = /* @__PURE__ */ new Map();
|
|
98
|
+
if (collections === void 0) return {
|
|
99
|
+
schemas,
|
|
100
|
+
indexes
|
|
101
|
+
};
|
|
102
|
+
for (const [name, def] of Object.entries(collections)) {
|
|
103
|
+
if (def.schema !== void 0) schemas.set(name, def.schema);
|
|
104
|
+
if (def.indexes !== void 0 && def.indexes.length > 0) indexes.set(name, def.indexes);
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
schemas,
|
|
108
|
+
indexes
|
|
109
|
+
};
|
|
110
|
+
};
|
|
111
|
+
//#endregion
|
|
112
|
+
//#region packages/server/src/auth/internal/none-verifier.ts
|
|
113
|
+
/**
|
|
114
|
+
* Internal helper backing `config.auth === "none"`. Returns a
|
|
115
|
+
* `Verifier` that resolves every request to the supplied
|
|
116
|
+
* `tenantPrefix` with `identity: { kind: "none" }`. The kernel
|
|
117
|
+
* NEVER reads the `Authorization` header in this mode — the network
|
|
118
|
+
* seam itself is the trust boundary.
|
|
119
|
+
*
|
|
120
|
+
* Discriminant note: `identity.kind === "none"` distinguishes the
|
|
121
|
+
* "operator opted into auth=none in baerly.config.ts" branch from the
|
|
122
|
+
* bearer-token paths (`kind: "shared-secret"`, `kind: "jwt"`, etc).
|
|
123
|
+
*
|
|
124
|
+
* Not part of the public surface. Consumed by `baerlyWorker` /
|
|
125
|
+
* `baerlyNode` resolution; the operator-facing API is the typed
|
|
126
|
+
* `auth: "none"` field on `BaerlyAppConfig`.
|
|
127
|
+
*
|
|
128
|
+
* @internal
|
|
129
|
+
*/
|
|
130
|
+
const noAuthVerifier = (tenantPrefix) => {
|
|
131
|
+
return async () => ({
|
|
132
|
+
tenantPrefix,
|
|
133
|
+
identity: { kind: "none" }
|
|
134
|
+
});
|
|
135
|
+
};
|
|
136
|
+
//#endregion
|
|
137
|
+
//#region packages/server/src/auth/internal/resolve-verifier.ts
|
|
138
|
+
/**
|
|
139
|
+
* Resolve the per-request `Verifier` for an adapter factory using the
|
|
140
|
+
* fixed order:
|
|
141
|
+
*
|
|
142
|
+
* 1. `factoryVerifier` set → use as-is (highest precedence; enables
|
|
143
|
+
* env-aware construction via `cloudflareAccess(env)` etc).
|
|
144
|
+
* 2. else `config.auth === "shared-secret"` → read `SHARED_SECRET`
|
|
145
|
+
* via `readEnv`; throw `BaerlyError("InvalidConfig",
|
|
146
|
+
* SHARED_SECRET_MISSING_MESSAGE)` when unset/empty; else build
|
|
147
|
+
* `sharedSecret({ secret, tenantPrefix: config.tenant })`.
|
|
148
|
+
* 3. else `config.auth === "none"` → `noAuthVerifier(config.tenant)`.
|
|
149
|
+
* 4. else → throw `BaerlyError("InvalidConfig",
|
|
150
|
+
* NO_AUTH_CONFIGURED_MESSAGE)`.
|
|
151
|
+
*
|
|
152
|
+
* Pure function — no I/O, no side effects beyond `sharedSecret`'s
|
|
153
|
+
* own validation. Caller invokes once at adapter init time (or on
|
|
154
|
+
* first fetch, depending on platform `await`-at-top-level
|
|
155
|
+
* constraints).
|
|
156
|
+
*
|
|
157
|
+
* @throws BaerlyError code="InvalidConfig" — branches 2 and 4 above.
|
|
158
|
+
*
|
|
159
|
+
* @internal
|
|
160
|
+
*/
|
|
161
|
+
const resolveVerifier = (input) => {
|
|
162
|
+
if (input.factoryVerifier !== void 0) return input.factoryVerifier;
|
|
163
|
+
if (input.config.auth === "shared-secret") {
|
|
164
|
+
const secret = input.readEnv("SHARED_SECRET");
|
|
165
|
+
if (secret === void 0 || secret.length === 0) throw new BaerlyError("InvalidConfig", SHARED_SECRET_MISSING_MESSAGE);
|
|
166
|
+
return sharedSecret({
|
|
167
|
+
secret,
|
|
168
|
+
tenantPrefix: input.config.tenant
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
if (input.config.auth === "none") return noAuthVerifier(input.config.tenant);
|
|
172
|
+
throw new BaerlyError("InvalidConfig", NO_AUTH_CONFIGURED_MESSAGE);
|
|
173
|
+
};
|
|
174
|
+
//#endregion
|
|
175
|
+
//#region packages/server/src/collection.ts
|
|
176
|
+
/**
|
|
177
|
+
* Build a `Collection<T>` bound to one `(tenant, collection)` read context.
|
|
178
|
+
* Cheap: zero I/O, allocates one closure. Each modifier call returns
|
|
179
|
+
* a FRESH `Query<T>` — calling `.where(p1)` and `.where(p2)` on the
|
|
180
|
+
* same `Collection<T>` produces two independent chains.
|
|
181
|
+
*
|
|
182
|
+
* `.count()` shorthand defers to the empty-state `Query<T>.count()`
|
|
183
|
+
* so the fold logic lives in one place.
|
|
184
|
+
*
|
|
185
|
+
* @example
|
|
186
|
+
* ```ts
|
|
187
|
+
* const collection = makeCollection<Ticket>({
|
|
188
|
+
* storage,
|
|
189
|
+
* collectionPrefix: "app/tickets/tenant/acme/manifests/tickets",
|
|
190
|
+
* collectionName: "tickets",
|
|
191
|
+
* });
|
|
192
|
+
* const open = await collection.where({ status: "open" }).all();
|
|
193
|
+
* ```
|
|
194
|
+
*
|
|
195
|
+
* @internal
|
|
196
|
+
*/
|
|
197
|
+
const makeCollection = (ctx) => {
|
|
198
|
+
const seed = {
|
|
199
|
+
wire: void 0,
|
|
200
|
+
order: void 0,
|
|
201
|
+
limit: void 0
|
|
202
|
+
};
|
|
203
|
+
const byId = (id) => ({
|
|
204
|
+
...seed,
|
|
205
|
+
wire: { clauses: [{
|
|
206
|
+
op: "eq",
|
|
207
|
+
field: "_id",
|
|
208
|
+
value: id
|
|
209
|
+
}] }
|
|
210
|
+
});
|
|
211
|
+
return {
|
|
212
|
+
name: ctx.collectionName,
|
|
213
|
+
first: () => makeQuery(ctx, seed).first(),
|
|
214
|
+
all: () => makeQuery(ctx, seed).all(),
|
|
215
|
+
count: () => makeQuery(ctx, seed).count(),
|
|
216
|
+
get: (id) => makeQuery(ctx, byId(id)).first(),
|
|
217
|
+
where: (p) => makeQuery(ctx, seed).where(p),
|
|
218
|
+
order: (s) => makeQuery(ctx, {
|
|
219
|
+
...seed,
|
|
220
|
+
order: s
|
|
221
|
+
}),
|
|
222
|
+
limit: (n) => makeQuery(ctx, {
|
|
223
|
+
...seed,
|
|
224
|
+
limit: n
|
|
225
|
+
}),
|
|
226
|
+
/**
|
|
227
|
+
* Insert one document. UUIDv7 auto-id when `_id` is absent or
|
|
228
|
+
* empty; otherwise the caller-supplied `_id` is honoured. A
|
|
229
|
+
* pre-commit existence check against the materialised collection
|
|
230
|
+
* surfaces `Conflict` on duplicate `_id` without round-tripping
|
|
231
|
+
* to the writer — matches the locked `Collection.insert` throws
|
|
232
|
+
* contract (`@baerly/protocol/src/collection-api.ts`).
|
|
233
|
+
*
|
|
234
|
+
* Single-attempt per call: CAS retries (up to 8 attempts) live
|
|
235
|
+
* inside `Writer.commit()`. On retry-budget exhaustion the
|
|
236
|
+
* writer throws `Conflict` and we surface unchanged.
|
|
237
|
+
*
|
|
238
|
+
* @throws BaerlyError code="Conflict" — `_id` collision (pre-commit
|
|
239
|
+
* check) or CAS retry budget exhausted.
|
|
240
|
+
* @throws BaerlyError code="SchemaError" — from the per-collection
|
|
241
|
+
* `SchemaValidator` threaded via {@link Db.collectionReadContext}.
|
|
242
|
+
*/
|
|
243
|
+
insert: (doc) => runInsert(ctx, doc),
|
|
244
|
+
update: (id, patch) => makeQuery(ctx, byId(id)).update(patch),
|
|
245
|
+
replace: (id, doc) => runReplaceById(ctx, id, doc),
|
|
246
|
+
delete: (id) => makeQuery(ctx, byId(id)).delete()
|
|
247
|
+
};
|
|
248
|
+
};
|
|
249
|
+
//#endregion
|
|
250
|
+
//#region packages/server/src/db.ts
|
|
251
|
+
/**
|
|
252
|
+
* Physical-key prefix for a `(app, tenant)` pair. Trailing slash is
|
|
253
|
+
* part of the prefix so a caller's `list("")` resolves to
|
|
254
|
+
* `list("app/<app>/tenant/<tenant>/")` and cannot enumerate a sibling
|
|
255
|
+
* tenant whose name shares a prefix.
|
|
256
|
+
*/
|
|
257
|
+
const physicalPrefixFor = (app, tenant) => `app/${app}/tenant/${tenant}/`;
|
|
258
|
+
/**
|
|
259
|
+
* Runtime entry point. One `Db` per `(app, tenant)` request.
|
|
260
|
+
*
|
|
261
|
+
* Construct via {@link Db.create} — the constructor is private so
|
|
262
|
+
* callers don't accidentally bypass validation.
|
|
263
|
+
*
|
|
264
|
+
* **Collection provisioning.** `Db` provisions collections implicitly on
|
|
265
|
+
* the first commit — the writer auto-creates the per-collection
|
|
266
|
+
* `current.json` manifest with a zero-state seed, costing one extra
|
|
267
|
+
* Class A PUT on the very first write per collection and zero
|
|
268
|
+
* thereafter. There is no `ensureCollection` method on this class. For
|
|
269
|
+
* eager pre-warm (seed scripts, deploy-time provisioning, CI fixtures
|
|
270
|
+
* that want byte-identical bytes before the first request), use
|
|
271
|
+
* {@link "@gusto/baerly-storage/dev".ensureTable}.
|
|
272
|
+
*
|
|
273
|
+
* @example
|
|
274
|
+
* ```ts
|
|
275
|
+
* import { Db } from "@gusto/baerly-storage";
|
|
276
|
+
* import { MemoryStorage } from "@gusto/baerly-storage";
|
|
277
|
+
*
|
|
278
|
+
* const db = Db.create({
|
|
279
|
+
* storage: new MemoryStorage(),
|
|
280
|
+
* app: "tickets",
|
|
281
|
+
* tenant: "acme-co",
|
|
282
|
+
* });
|
|
283
|
+
*
|
|
284
|
+
* await db.collection("tickets").insert({ title: "first ticket", status: "open" });
|
|
285
|
+
* const open = await db.collection("tickets").where({ status: "open" }).all();
|
|
286
|
+
* ```
|
|
287
|
+
*
|
|
288
|
+
* @remarks
|
|
289
|
+
* **Anti-patterns** (TS compile errors, not runtime rejections):
|
|
290
|
+
* - `db.collection(name).insertOne({...})` / `.insert({...})` —
|
|
291
|
+
* the Mongo verb. Use `.insert(row)` (returns `{ _id }`).
|
|
292
|
+
* - `db.collection(name).findOne({...})` / `.find({...})` —
|
|
293
|
+
* the Mongo read verbs. Use `.get(id)` for by-id reads and
|
|
294
|
+
* `.where({...}).first()` / `.all()` for predicate reads.
|
|
295
|
+
* - `db.collection(name).aggregate([...])` — no pipeline stage
|
|
296
|
+
* model. Compose via `.where().order().limit()` modifiers.
|
|
297
|
+
* - Raw SQL strings of any shape. The kernel has no SQL parser.
|
|
298
|
+
*/
|
|
299
|
+
var Db = class Db {
|
|
300
|
+
app;
|
|
301
|
+
tenant;
|
|
302
|
+
/**
|
|
303
|
+
* Underlying `Storage`, captured so the collection API can issue reads
|
|
304
|
+
* using physical keys directly.
|
|
305
|
+
*/
|
|
306
|
+
#storage;
|
|
307
|
+
/**
|
|
308
|
+
* Per-collection {@link SchemaValidator}s threaded onto every
|
|
309
|
+
* {@link CollectionReadContext} this `Db` mints. Empty map means "no
|
|
310
|
+
* validation declared" — every write proceeds at zero overhead.
|
|
311
|
+
*
|
|
312
|
+
* Derived from `config.collections[*].schema` via
|
|
313
|
+
* {@link collectionsToMaps} at {@link Db.create} time.
|
|
314
|
+
*/
|
|
315
|
+
#schemas;
|
|
316
|
+
/**
|
|
317
|
+
* Per-collection {@link IndexDefinition}s threaded onto every
|
|
318
|
+
* {@link CollectionReadContext} this `Db` mints. Empty map means "no
|
|
319
|
+
* indexes declared" — every read falls through to the snapshot +
|
|
320
|
+
* log fold path.
|
|
321
|
+
*
|
|
322
|
+
* Derived from `config.collections[*].indexes` via
|
|
323
|
+
* {@link collectionsToMaps} at {@link Db.create} time.
|
|
324
|
+
*/
|
|
325
|
+
#indexes;
|
|
326
|
+
constructor(app, tenant, storage, schemas, indexes) {
|
|
327
|
+
this.app = app;
|
|
328
|
+
this.tenant = tenant;
|
|
329
|
+
this.#storage = storage;
|
|
330
|
+
this.#schemas = schemas;
|
|
331
|
+
this.#indexes = indexes;
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Build a tenant-scoped `Db`. Throws
|
|
335
|
+
* `BaerlyError{code:"InvalidConfig"}` if either `app` or `tenant`
|
|
336
|
+
* is empty or contains `/` (the segment separator).
|
|
337
|
+
*
|
|
338
|
+
* @throws BaerlyError code="InvalidConfig" when `app` or `tenant` is
|
|
339
|
+
* empty or contains `/`.
|
|
340
|
+
*
|
|
341
|
+
* @example
|
|
342
|
+
* ```ts
|
|
343
|
+
* const db = Db.create({ storage, app: "tickets", tenant: "acme" });
|
|
344
|
+
* await db.collection("tickets").insert({ title: "hi" });
|
|
345
|
+
* ```
|
|
346
|
+
*/
|
|
347
|
+
static create(config) {
|
|
348
|
+
const { storage, app, tenant } = config;
|
|
349
|
+
assertKeySegment(app, "app", "Db.create");
|
|
350
|
+
assertKeySegment(tenant, "tenant", "Db.create");
|
|
351
|
+
const derived = config.config !== void 0 ? collectionsToMaps(config.config.collections) : void 0;
|
|
352
|
+
return new Db(app, tenant, storage, derived?.schemas ?? /* @__PURE__ */ new Map(), derived?.indexes ?? /* @__PURE__ */ new Map());
|
|
353
|
+
}
|
|
354
|
+
collection(name) {
|
|
355
|
+
return makeCollection(this.collectionReadContext(name));
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Build a freshly-seeded {@link CollectionReadContext} for `name`. The
|
|
359
|
+
* HTTP router uses this so it can drive `runAllWithMeta` directly
|
|
360
|
+
* (the return shape carries the manifest-pointer cursor used to
|
|
361
|
+
* pack `_meta` onto the read response envelope). Application
|
|
362
|
+
* callers should keep using
|
|
363
|
+
* {@link Db.collection}; the chainable terminals destructure the cursor
|
|
364
|
+
* out and discard it to keep the locked `Query<T>` signature.
|
|
365
|
+
*
|
|
366
|
+
* Runs the same `name`-validation guard as {@link Db.collection}.
|
|
367
|
+
*
|
|
368
|
+
* @throws BaerlyError code="InvalidConfig" when `name` is empty or
|
|
369
|
+
* contains `/`.
|
|
370
|
+
* @internal
|
|
371
|
+
*/
|
|
372
|
+
collectionReadContext(name) {
|
|
373
|
+
assertKeySegment(name, "collection", "Db.collection");
|
|
374
|
+
const schema = this.#schemas.get(name);
|
|
375
|
+
return {
|
|
376
|
+
storage: this.#storage,
|
|
377
|
+
collectionPrefix: `${physicalPrefixFor(this.app, this.tenant)}manifests/${name}`,
|
|
378
|
+
collectionName: name,
|
|
379
|
+
indexes: this.#indexes.get(name) ?? [],
|
|
380
|
+
...schema !== void 0 ? { schema } : {}
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Atomic mutation over a single collection. The callback receives a
|
|
385
|
+
* `Collection<T>` (not a `Db`) so cross-collection writes inside a
|
|
386
|
+
* transaction are a TypeScript error at compile time — not a
|
|
387
|
+
* runtime trap. Mutation verbs (`insert`, `update`, `replace`,
|
|
388
|
+
* `delete`) buffer; reads (`first`, `all`, `count`) go through
|
|
389
|
+
* `Storage` live (no MVCC snapshot, no read-your-writes).
|
|
390
|
+
*
|
|
391
|
+
* Single-attempt: on CAS conflict throws
|
|
392
|
+
* `BaerlyError{code:"Conflict"}`. The body MAY have already run its
|
|
393
|
+
* read side-effects (no rollback of in-memory state); the write
|
|
394
|
+
* side-effects either all landed or none did. Wrap in a retry
|
|
395
|
+
* loop you wrote if you want one.
|
|
396
|
+
*
|
|
397
|
+
* Empty body (or a body that buffers nothing) resolves without
|
|
398
|
+
* touching `current.json`.
|
|
399
|
+
*
|
|
400
|
+
* @throws BaerlyError code="Conflict" — CAS lost on the collection's
|
|
401
|
+
* `current.json`. Caller decides whether to re-run the body.
|
|
402
|
+
* @throws Whatever the body throws — re-thrown as-is. The commit
|
|
403
|
+
* is skipped when the body throws.
|
|
404
|
+
* @throws BaerlyError code="InvalidConfig" — `collection` is empty or
|
|
405
|
+
* contains `/`.
|
|
406
|
+
*
|
|
407
|
+
* @remarks
|
|
408
|
+
* Single-collection by design. Cross-collection 2PC was rejected on
|
|
409
|
+
* cost grounds — multiple round-trips per commit, no native fencing
|
|
410
|
+
* primitive on S3-compatible storage, no rollback to undo a
|
|
411
|
+
* successful PUT — and because in-doubt-transaction recovery state
|
|
412
|
+
* would contradict the stateless-writer model. Applications that
|
|
413
|
+
* need cross-collection atomicity re-express it at the app layer: an
|
|
414
|
+
* idempotent move keyed off source-row state, or a single
|
|
415
|
+
* denormalized collection with a `status` column.
|
|
416
|
+
*
|
|
417
|
+
* @example
|
|
418
|
+
* ```ts
|
|
419
|
+
* await db.transaction("tickets", async (tx) => {
|
|
420
|
+
* const open = await tx.where({ status: "open" }).count();
|
|
421
|
+
* if (open < 100) await tx.insert({ title: "another", status: "open" });
|
|
422
|
+
* });
|
|
423
|
+
* ```
|
|
424
|
+
*/
|
|
425
|
+
async transaction(collection, body) {
|
|
426
|
+
assertKeySegment(collection, "collection", "Db.transaction");
|
|
427
|
+
const txCtx = {
|
|
428
|
+
collection,
|
|
429
|
+
mutations: []
|
|
430
|
+
};
|
|
431
|
+
const collectionPrefix = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}`;
|
|
432
|
+
const schema = this.#schemas.get(collection);
|
|
433
|
+
const indexes = this.#indexes.get(collection) ?? [];
|
|
434
|
+
await body(makeCollection({
|
|
435
|
+
storage: this.#storage,
|
|
436
|
+
collectionPrefix,
|
|
437
|
+
collectionName: collection,
|
|
438
|
+
txCtx,
|
|
439
|
+
indexes,
|
|
440
|
+
...schema !== void 0 ? { schema } : {}
|
|
441
|
+
}));
|
|
442
|
+
if (txCtx.mutations.length === 0) return;
|
|
443
|
+
const inputs = [];
|
|
444
|
+
for (const m of txCtx.mutations) {
|
|
445
|
+
const input = {
|
|
446
|
+
op: m.op,
|
|
447
|
+
collection,
|
|
448
|
+
docId: m.docId,
|
|
449
|
+
...m.body !== void 0 ? { body: m.body } : {},
|
|
450
|
+
...m.origin !== void 0 ? { origin: m.origin } : {}
|
|
451
|
+
};
|
|
452
|
+
inputs.push(input);
|
|
453
|
+
}
|
|
454
|
+
await new Writer({
|
|
455
|
+
storage: this.#storage,
|
|
456
|
+
currentJsonKey: `${collectionPrefix}/current.json`,
|
|
457
|
+
options: { indexes }
|
|
458
|
+
}).commitBatch(inputs);
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Read + parse this `Db`'s `manifests/<collection>/current.json`. Returns
|
|
462
|
+
* `null` when the collection has not been provisioned yet (no
|
|
463
|
+
* `current.json` exists). Throws `BaerlyError{code:"InvalidResponse"}`
|
|
464
|
+
* on a malformed body — same contract as the underlying
|
|
465
|
+
* {@link readCurrentJson} helper in `@baerly/protocol`.
|
|
466
|
+
*
|
|
467
|
+
* Backs the `/v1/since` long-poll handler in
|
|
468
|
+
* `packages/server/src/http/since.ts`; that handler needs the parsed
|
|
469
|
+
* `CurrentJson` plus an ETag for the follow-up reads.
|
|
470
|
+
*
|
|
471
|
+
* @internal — typed seam for the HTTP handler; app code should use
|
|
472
|
+
* the collection API.
|
|
473
|
+
*/
|
|
474
|
+
async getCurrentJson(collection, opts) {
|
|
475
|
+
const key = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}/current.json`;
|
|
476
|
+
return readCurrentJson(this.#storage, key, opts);
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Read + parse one `LogEntry` by `seq` from
|
|
480
|
+
* `manifests/<collection>/${LOG_KEY_PREFIX}/<seq>.json`. Returns `null`
|
|
481
|
+
* when the entry is missing — this typically means the GC sweeper
|
|
482
|
+
* deleted the entry between a `readCurrentJson` and this GET (the
|
|
483
|
+
* `/v1/since` handler treats the race as silent and skips the
|
|
484
|
+
* entry). Throws `BaerlyError{code:"InvalidResponse"}` on a body
|
|
485
|
+
* that isn't valid JSON.
|
|
486
|
+
*
|
|
487
|
+
* @internal — typed seam for the HTTP handler; app code should use
|
|
488
|
+
* the collection API.
|
|
489
|
+
*/
|
|
490
|
+
async getLogEntry(collection, seq, opts) {
|
|
491
|
+
const key = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}/log/${seq}.json`;
|
|
492
|
+
const got = await this.#storage.get(key, opts);
|
|
493
|
+
if (got === null) return null;
|
|
494
|
+
let parsed;
|
|
495
|
+
try {
|
|
496
|
+
parsed = decodeJsonBytes(got.body);
|
|
497
|
+
} catch (error) {
|
|
498
|
+
throw new BaerlyError("InvalidResponse", `log entry at ${key}: body is not valid JSON`, error);
|
|
499
|
+
}
|
|
500
|
+
return parsed;
|
|
501
|
+
}
|
|
502
|
+
};
|
|
503
|
+
/**
|
|
504
|
+
* Guard a string used as a path-segment in the bucket-key encoding.
|
|
505
|
+
* Rejects empty and `/`-containing values with
|
|
506
|
+
* `BaerlyError{code:"InvalidConfig"}`. `role` and `verb` are baked
|
|
507
|
+
* into the message so the caller doesn't need to format their own.
|
|
508
|
+
*
|
|
509
|
+
* Used by {@link Db.create} (twice — `app`, `tenant`),
|
|
510
|
+
* {@link Db.collectionReadContext} (once — `name`), and
|
|
511
|
+
* {@link Db.transaction} (once — `collection`).
|
|
512
|
+
*
|
|
513
|
+
* @internal
|
|
514
|
+
*/
|
|
515
|
+
const assertKeySegment = (value, role, verb) => {
|
|
516
|
+
if (value.length === 0) throw new BaerlyError("InvalidConfig", `${verb}: ${role} must be non-empty (got ${JSON.stringify(value)})`);
|
|
517
|
+
if (value.includes("/")) throw new BaerlyError("InvalidConfig", `${verb}: "/" is reserved as the key-segment separator (got ${role}=${JSON.stringify(value)})`);
|
|
518
|
+
};
|
|
519
|
+
//#endregion
|
|
520
|
+
export { MemoryStorage as i, resolveVerifier as n, collectionsToMaps as r, Db as t };
|
|
521
|
+
|
|
522
|
+
//# sourceMappingURL=src-Chafbw8r.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-Chafbw8r.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\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 */\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 ...(opts?.contentType !== undefined && { contentType: opts.contentType }),\n });\n // `serverDate` is intentionally returned (callers like the kernel's\n // adaptive-clock loop need a value); `lastModified` is intentionally\n // *not* surfaced on `list()` — the in-memory impl has no\n // independent server clock, and pretending it does would force the\n // kernel's wall-clock cross-check against an artificially injected\n // `clockOffset`, breaking the property-based randomized tests.\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) && k > startAfter)\n .toSorted();\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 if (stored === undefined) {\n continue;\n } // unreachable; satisfies noUncheckedIndexedAccess\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 LOG_KEY_PREFIX,\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 type { CollectionReadContext } from \"./query.ts\";\nimport { Writer, type CommitInput } from \"./writer.ts\";\nimport { makeCollection } from \"./collection.ts\";\n\n/**\n * In-memory buffer for a single in-flight {@link Db.transaction}\n * call. The `Collection<T>` instance passed to the transaction body holds\n * a reference to this object; every mutation verb appends to\n * `mutations` instead of calling `Writer.commit` directly.\n *\n * After the body resolves, `Db.transaction` performs ONE\n * `Writer.commitBatch(...)` to commit every buffered mutation\n * in a single CAS attempt.\n *\n * @internal — referenced by `collection.ts` and `query.ts`; not part of\n * the public API surface for app code.\n */\nexport interface TxContext {\n /**\n * The collection name the transaction is scoped to. Mutation verbs\n * runtime-assert that their `Collection<T>`'s `name` matches this\n * field before appending — the type system already prevents the\n * legitimate path, this catches the bug path (a stale `Query<T>`\n * re-attached to a different collection's transaction).\n */\n readonly collection: string;\n\n /**\n * Mutations buffered in order of issuance. The commit converts\n * each into one `CommitInput` (`Writer`'s single-mutation\n * shape) and passes the array to `Writer.commitBatch`.\n */\n readonly mutations: BufferedMutation[];\n}\n\n/**\n * One buffered mutation. Mirrors {@link CommitInput} minus\n * `collection` (which is constant per transaction and lives on\n * `TxContext.collection`).\n *\n * @internal — only used inside the `Db.transaction` path.\n */\nexport interface BufferedMutation {\n readonly op: \"I\" | \"U\" | \"D\";\n readonly docId: string;\n readonly body?: DocumentData;\n readonly origin?: string;\n}\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 or contains `/` (the segment separator).\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `app` or `tenant` is\n * empty or contains `/`.\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 or\n * contains `/`.\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 or\n * contains `/`.\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 * Atomic mutation over a single collection. The callback receives a\n * `Collection<T>` (not a `Db`) so cross-collection writes inside a\n * transaction are a TypeScript error at compile time — not a\n * runtime trap. Mutation verbs (`insert`, `update`, `replace`,\n * `delete`) buffer; reads (`first`, `all`, `count`) go through\n * `Storage` live (no MVCC snapshot, no read-your-writes).\n *\n * Single-attempt: on CAS conflict throws\n * `BaerlyError{code:\"Conflict\"}`. The body MAY have already run its\n * read side-effects (no rollback of in-memory state); the write\n * side-effects either all landed or none did. Wrap in a retry\n * loop you wrote if you want one.\n *\n * Empty body (or a body that buffers nothing) resolves without\n * touching `current.json`.\n *\n * @throws BaerlyError code=\"Conflict\" — CAS lost on the collection's\n * `current.json`. Caller decides whether to re-run the body.\n * @throws Whatever the body throws — re-thrown as-is. The commit\n * is skipped when the body throws.\n * @throws BaerlyError code=\"InvalidConfig\" — `collection` is empty or\n * contains `/`.\n *\n * @remarks\n * Single-collection by design. Cross-collection 2PC was rejected on\n * cost grounds — multiple round-trips per commit, no native fencing\n * primitive on S3-compatible storage, no rollback to undo a\n * successful PUT — and because in-doubt-transaction recovery state\n * would contradict the stateless-writer model. Applications that\n * need cross-collection atomicity re-express it at the app layer: an\n * idempotent move keyed off source-row state, or a single\n * denormalized collection with a `status` column.\n *\n * @example\n * ```ts\n * await db.transaction(\"tickets\", async (tx) => {\n * const open = await tx.where({ status: \"open\" }).count();\n * if (open < 100) await tx.insert({ title: \"another\", status: \"open\" });\n * });\n * ```\n */\n async transaction<T extends DocumentData = DocumentData>(\n collection: string,\n body: (tx: Collection<T>) => Promise<void>,\n ): Promise<void> {\n assertKeySegment(collection, \"collection\", \"Db.transaction\");\n\n const txCtx: TxContext = { collection, mutations: [] };\n const collectionPrefix = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}`;\n\n // Build a Collection<T> whose mutation verbs buffer onto `txCtx`. The\n // read path ignores `txCtx` entirely (locked: no MVCC, no\n // read-your-writes inside a transaction).\n const schema = this.#schemas.get(collection);\n const indexes = this.#indexes.get(collection) ?? [];\n const tx = makeCollection<T>({\n storage: this.#storage,\n collectionPrefix,\n collectionName: collection,\n txCtx,\n indexes,\n ...(schema !== undefined ? { schema } : {}),\n });\n\n // Run the body. Reads go through Storage live; mutations append\n // to txCtx.mutations. A throw here propagates AS-IS and skips\n // the commit (txCtx.mutations is discarded).\n await body(tx);\n\n // Empty buffer — nothing to commit, nothing to throw.\n if (txCtx.mutations.length === 0) {\n return;\n }\n\n // Map BufferedMutations -> CommitInputs and fire one\n // single-attempt commitBatch. On CAS loss commitBatch throws\n // `Conflict` and we surface it unchanged.\n const inputs: CommitInput[] = [];\n for (const m of txCtx.mutations) {\n const input: CommitInput = {\n op: m.op,\n collection,\n docId: m.docId,\n ...(m.body !== undefined ? { body: m.body } : {}),\n ...(m.origin !== undefined ? { origin: m.origin } : {}),\n };\n inputs.push(input);\n }\n\n const writer = new Writer({\n storage: this.#storage,\n currentJsonKey: `${collectionPrefix}/current.json`,\n options: { indexes },\n });\n await writer.commitBatch(inputs);\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 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_KEY_PREFIX}/<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 const key = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}/${LOG_KEY_PREFIX}/${seq}.json`;\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/**\n * Guard a string used as a path-segment in the bucket-key encoding.\n * Rejects empty and `/`-containing values with\n * `BaerlyError{code:\"InvalidConfig\"}`. `role` and `verb` are baked\n * into the message so the caller doesn't need to format their own.\n *\n * Used by {@link Db.create} (twice — `app`, `tenant`),\n * {@link Db.collectionReadContext} (once — `name`), and\n * {@link Db.transaction} (once — `collection`).\n *\n * @internal\n */\nconst assertKeySegment = (value: string, role: string, verb: string): void => {\n if (value.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${verb}: ${role} must be non-empty (got ${JSON.stringify(value)})`,\n );\n }\n if (value.includes(\"/\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${verb}: \"/\" is reserved as the key-segment separator (got ${role}=${JSON.stringify(value)})`,\n );\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAyBA,IAAa,gBAAb,MAA8C;CAC5C,2BAAoB,IAAI,IAA0B;CAClD,eAAe;CAEf,YAAoB;EAClB,KAAKC,gBAAgB;EACrB,OAAO,IAAI,KAAKA,aAAa,SAAS,EAAE,EAAE;CAC5C;CAEA,MAAM,IAAI,KAAa,MAA4D;EACjF,MAAM,QAAQ,eAAe;EAC7B,MAAM,SAAS,KAAKD,SAAS,IAAI,GAAG;EACpC,IAAI,WAAW,KAAA,GACb,OAAO;EAET,IAAI,MAAM,gBAAgB,KAAA,KAAa,KAAK,gBAAgB,OAAO,MAEjE,OAAO;EAET,OAAO;GAAE,MAAM,OAAO;GAAM,MAAM,OAAO;EAAK;CAChD;CAEA,MAAM,IAAI,KAAa,MAAkB,MAAqD;EAC5F,MAAM,QAAQ,eAAe;EAC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