@typicalday/firegraph 0.9.0 → 0.10.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 (45) hide show
  1. package/dist/backend-73p5Blx7.d.cts +97 -0
  2. package/dist/backend-BrqFkbid.d.ts +97 -0
  3. package/dist/backend.cjs.map +1 -1
  4. package/dist/backend.d.cts +7 -6
  5. package/dist/backend.d.ts +7 -6
  6. package/dist/backend.js +1 -1
  7. package/dist/backend.js.map +1 -1
  8. package/dist/{chunk-EVUM6ORB.js → chunk-LZOIQHYN.js} +57 -2
  9. package/dist/chunk-LZOIQHYN.js.map +1 -0
  10. package/dist/{chunk-GLOVWKQH.js → chunk-R7CRGYY4.js} +1 -1
  11. package/dist/{chunk-GLOVWKQH.js.map → chunk-R7CRGYY4.js.map} +1 -1
  12. package/dist/{do-sqlite.cjs → cloudflare/index.cjs} +1533 -1420
  13. package/dist/cloudflare/index.cjs.map +1 -0
  14. package/dist/cloudflare/index.d.cts +454 -0
  15. package/dist/cloudflare/index.d.ts +454 -0
  16. package/dist/cloudflare/index.js +822 -0
  17. package/dist/cloudflare/index.js.map +1 -0
  18. package/dist/codegen/index.d.cts +1 -1
  19. package/dist/codegen/index.d.ts +1 -1
  20. package/dist/editor/server/index.mjs +55 -0
  21. package/dist/index.cjs +55 -0
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +13 -9
  24. package/dist/index.d.ts +13 -9
  25. package/dist/index.js +8 -8
  26. package/dist/index.js.map +1 -1
  27. package/dist/{scope-path-BtajqNK5.d.ts → scope-path-B1G3YiA7.d.cts} +5 -100
  28. package/dist/{scope-path-D2mNENJ-.d.cts → scope-path-B1G3YiA7.d.ts} +5 -100
  29. package/dist/{types-DfWVTsMn.d.cts → types-DOemdlVA.d.cts} +18 -1
  30. package/dist/{types-DfWVTsMn.d.ts → types-DOemdlVA.d.ts} +18 -1
  31. package/package.json +33 -45
  32. package/dist/chunk-EVUM6ORB.js.map +0 -1
  33. package/dist/chunk-SZ6W4VAS.js +0 -701
  34. package/dist/chunk-SZ6W4VAS.js.map +0 -1
  35. package/dist/d1.cjs +0 -2421
  36. package/dist/d1.cjs.map +0 -1
  37. package/dist/d1.d.cts +0 -54
  38. package/dist/d1.d.ts +0 -54
  39. package/dist/d1.js +0 -76
  40. package/dist/d1.js.map +0 -1
  41. package/dist/do-sqlite.cjs.map +0 -1
  42. package/dist/do-sqlite.d.cts +0 -41
  43. package/dist/do-sqlite.d.ts +0 -41
  44. package/dist/do-sqlite.js +0 -79
  45. package/dist/do-sqlite.js.map +0 -1
@@ -154,101 +154,15 @@ var init_serialization = __esm({
154
154
  }
155
155
  });
156
156
 
157
- // src/do-sqlite.ts
158
- var do_sqlite_exports = {};
159
- __export(do_sqlite_exports, {
160
- createDOSqliteGraphClient: () => createDOSqliteGraphClient
157
+ // src/cloudflare/index.ts
158
+ var cloudflare_exports = {};
159
+ __export(cloudflare_exports, {
160
+ DORPCBackend: () => DORPCBackend,
161
+ FiregraphDO: () => FiregraphDO,
162
+ createDOClient: () => createDOClient,
163
+ createSiblingClient: () => createSiblingClient
161
164
  });
162
- module.exports = __toCommonJS(do_sqlite_exports);
163
-
164
- // src/docid.ts
165
- var import_node_crypto = require("crypto");
166
-
167
- // src/internal/constants.ts
168
- var NODE_RELATION = "is";
169
- var DEFAULT_QUERY_LIMIT = 500;
170
- var BUILTIN_FIELDS = /* @__PURE__ */ new Set([
171
- "aType",
172
- "aUid",
173
- "axbType",
174
- "bType",
175
- "bUid",
176
- "createdAt",
177
- "updatedAt"
178
- ]);
179
- var SHARD_SEPARATOR = ":";
180
-
181
- // src/docid.ts
182
- function computeNodeDocId(uid) {
183
- return uid;
184
- }
185
- function computeEdgeDocId(aUid, axbType, bUid) {
186
- const composite = `${aUid}${SHARD_SEPARATOR}${axbType}${SHARD_SEPARATOR}${bUid}`;
187
- const hash = (0, import_node_crypto.createHash)("sha256").update(composite).digest("hex");
188
- const shard = hash[0];
189
- return `${shard}${SHARD_SEPARATOR}${aUid}${SHARD_SEPARATOR}${axbType}${SHARD_SEPARATOR}${bUid}`;
190
- }
191
-
192
- // src/batch.ts
193
- function buildWritableNodeRecord(aType, uid, data) {
194
- return { aType, aUid: uid, axbType: NODE_RELATION, bType: aType, bUid: uid, data };
195
- }
196
- function buildWritableEdgeRecord(aType, aUid, axbType, bType, bUid, data) {
197
- return { aType, aUid, axbType, bType, bUid, data };
198
- }
199
- var GraphBatchImpl = class {
200
- constructor(backend, registry, scopePath = "") {
201
- this.backend = backend;
202
- this.registry = registry;
203
- this.scopePath = scopePath;
204
- }
205
- async putNode(aType, uid, data) {
206
- if (this.registry) {
207
- this.registry.validate(aType, NODE_RELATION, aType, data, this.scopePath);
208
- }
209
- const docId = computeNodeDocId(uid);
210
- const record = buildWritableNodeRecord(aType, uid, data);
211
- if (this.registry) {
212
- const entry = this.registry.lookup(aType, NODE_RELATION, aType);
213
- if (entry?.schemaVersion && entry.schemaVersion > 0) {
214
- record.v = entry.schemaVersion;
215
- }
216
- }
217
- this.backend.setDoc(docId, record);
218
- }
219
- async putEdge(aType, aUid, axbType, bType, bUid, data) {
220
- if (this.registry) {
221
- this.registry.validate(aType, axbType, bType, data, this.scopePath);
222
- }
223
- const docId = computeEdgeDocId(aUid, axbType, bUid);
224
- const record = buildWritableEdgeRecord(aType, aUid, axbType, bType, bUid, data);
225
- if (this.registry) {
226
- const entry = this.registry.lookup(aType, axbType, bType);
227
- if (entry?.schemaVersion && entry.schemaVersion > 0) {
228
- record.v = entry.schemaVersion;
229
- }
230
- }
231
- this.backend.setDoc(docId, record);
232
- }
233
- async updateNode(uid, data) {
234
- const docId = computeNodeDocId(uid);
235
- this.backend.updateDoc(docId, { dataFields: data });
236
- }
237
- async removeNode(uid) {
238
- const docId = computeNodeDocId(uid);
239
- this.backend.deleteDoc(docId);
240
- }
241
- async removeEdge(aUid, axbType, bUid) {
242
- const docId = computeEdgeDocId(aUid, axbType, bUid);
243
- this.backend.deleteDoc(docId);
244
- }
245
- async commit() {
246
- await this.backend.commit();
247
- }
248
- };
249
-
250
- // src/dynamic-registry.ts
251
- var import_node_crypto3 = require("crypto");
165
+ module.exports = __toCommonJS(cloudflare_exports);
252
166
 
253
167
  // src/errors.ts
254
168
  var FiregraphError = class extends Error {
@@ -305,243 +219,858 @@ var MigrationError = class extends FiregraphError {
305
219
  }
306
220
  };
307
221
 
308
- // src/json-schema.ts
309
- var import_ajv = __toESM(require("ajv"), 1);
310
- var import_ajv_formats = __toESM(require("ajv-formats"), 1);
311
- var ajv = new import_ajv.default({ allErrors: true, strict: false });
312
- (0, import_ajv_formats.default)(ajv);
313
- function compileSchema(schema, label) {
314
- const validate = ajv.compile(schema);
315
- return (data) => {
316
- if (!validate(data)) {
317
- const errors = validate.errors ?? [];
318
- const messages = errors.map((err) => `${err.instancePath || "/"}${err.message ? ": " + err.message : ""}`).join("; ");
319
- throw new ValidationError(
320
- `Data validation failed${label ? " for " + label : ""}: ${messages}`,
321
- errors
322
- );
323
- }
324
- };
325
- }
222
+ // src/internal/constants.ts
223
+ var NODE_RELATION = "is";
224
+ var DEFAULT_QUERY_LIMIT = 500;
225
+ var BUILTIN_FIELDS = /* @__PURE__ */ new Set([
226
+ "aType",
227
+ "aUid",
228
+ "axbType",
229
+ "bType",
230
+ "bUid",
231
+ "createdAt",
232
+ "updatedAt"
233
+ ]);
234
+ var SHARD_SEPARATOR = ":";
326
235
 
327
- // src/migration.ts
328
- async function applyMigrationChain(data, currentVersion, targetVersion, migrations) {
329
- const sorted = [...migrations].sort((a, b) => a.fromVersion - b.fromVersion);
330
- let result = { ...data };
331
- let version = currentVersion;
332
- for (const step of sorted) {
333
- if (step.fromVersion === version) {
334
- try {
335
- result = await step.up(result);
336
- } catch (err) {
337
- if (err instanceof MigrationError) throw err;
338
- throw new MigrationError(
339
- `Migration from v${step.fromVersion} to v${step.toVersion} failed: ${err.message}`
340
- );
341
- }
342
- if (!result || typeof result !== "object") {
343
- throw new MigrationError(
344
- `Migration from v${step.fromVersion} to v${step.toVersion} returned invalid data (expected object)`
345
- );
346
- }
347
- version = step.toVersion;
348
- }
236
+ // src/timestamp.ts
237
+ var GraphTimestampImpl = class _GraphTimestampImpl {
238
+ constructor(seconds, nanoseconds) {
239
+ this.seconds = seconds;
240
+ this.nanoseconds = nanoseconds;
349
241
  }
350
- if (version !== targetVersion) {
351
- throw new MigrationError(
352
- `Incomplete migration chain: reached v${version} but target is v${targetVersion}`
353
- );
242
+ toDate() {
243
+ return new Date(this.toMillis());
354
244
  }
355
- return result;
356
- }
357
- function validateMigrationChain(migrations, label) {
358
- if (migrations.length === 0) return;
359
- const seen = /* @__PURE__ */ new Set();
360
- for (const step of migrations) {
361
- if (step.toVersion <= step.fromVersion) {
362
- throw new MigrationError(
363
- `${label}: migration step has toVersion (${step.toVersion}) <= fromVersion (${step.fromVersion})`
364
- );
365
- }
366
- if (seen.has(step.fromVersion)) {
367
- throw new MigrationError(
368
- `${label}: duplicate migration step for fromVersion ${step.fromVersion}`
369
- );
370
- }
371
- seen.add(step.fromVersion);
245
+ toMillis() {
246
+ return this.seconds * 1e3 + Math.floor(this.nanoseconds / 1e6);
372
247
  }
373
- const sorted = [...migrations].sort((a, b) => a.fromVersion - b.fromVersion);
374
- const targetVersion = Math.max(...migrations.map((m) => m.toVersion));
375
- let version = 0;
376
- for (const step of sorted) {
377
- if (step.fromVersion === version) {
378
- version = step.toVersion;
379
- } else if (step.fromVersion > version) {
380
- throw new MigrationError(
381
- `${label}: migration chain has a gap \u2014 no step covers v${version} \u2192 v${step.fromVersion}`
382
- );
383
- }
248
+ toJSON() {
249
+ return { seconds: this.seconds, nanoseconds: this.nanoseconds };
384
250
  }
385
- if (version !== targetVersion) {
386
- throw new MigrationError(
387
- `${label}: migration chain does not reach v${targetVersion} (stuck at v${version})`
388
- );
251
+ static fromMillis(ms) {
252
+ const seconds = Math.floor(ms / 1e3);
253
+ const nanoseconds = (ms - seconds * 1e3) * 1e6;
254
+ return new _GraphTimestampImpl(seconds, nanoseconds);
389
255
  }
390
- }
391
- async function migrateRecord(record, registry, globalWriteBack = "off") {
392
- const entry = registry.lookup(record.aType, record.axbType, record.bType);
393
- if (!entry?.migrations?.length || !entry.schemaVersion) {
394
- return { record, migrated: false, writeBack: "off" };
256
+ static now() {
257
+ return _GraphTimestampImpl.fromMillis(Date.now());
395
258
  }
396
- const currentVersion = record.v ?? 0;
397
- if (currentVersion >= entry.schemaVersion) {
398
- return { record, migrated: false, writeBack: "off" };
259
+ };
260
+
261
+ // src/cloudflare/schema.ts
262
+ var DO_FIELD_TO_COLUMN = {
263
+ aType: "a_type",
264
+ aUid: "a_uid",
265
+ axbType: "axb_type",
266
+ bType: "b_type",
267
+ bUid: "b_uid",
268
+ v: "v",
269
+ createdAt: "created_at",
270
+ updatedAt: "updated_at"
271
+ };
272
+ var IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
273
+ function validateDOTableName(name) {
274
+ if (!IDENT_RE.test(name)) {
275
+ throw new Error(`Invalid SQL identifier: ${name}. Must match /^[A-Za-z_][A-Za-z0-9_]*$/.`);
399
276
  }
400
- const migratedData = await applyMigrationChain(
401
- record.data,
402
- currentVersion,
403
- entry.schemaVersion,
404
- entry.migrations
405
- );
406
- const writeBack = entry.migrationWriteBack ?? globalWriteBack ?? "off";
407
- return {
408
- record: { ...record, data: migratedData, v: entry.schemaVersion },
409
- migrated: true,
410
- writeBack
411
- };
412
- }
413
- async function migrateRecords(records, registry, globalWriteBack = "off") {
414
- return Promise.all(
415
- records.map((r) => migrateRecord(r, registry, globalWriteBack))
416
- );
417
277
  }
418
-
419
- // src/scope.ts
420
- function matchScope(scopePath, pattern) {
421
- if (pattern === "root") return scopePath === "";
422
- if (pattern === "**") return true;
423
- const pathSegments = scopePath === "" ? [] : scopePath.split("/");
424
- const patternSegments = pattern.split("/");
425
- return matchSegments(pathSegments, 0, patternSegments, 0);
278
+ function quoteDOIdent(name) {
279
+ validateDOTableName(name);
280
+ return `"${name}"`;
426
281
  }
427
- function matchScopeAny(scopePath, patterns) {
428
- if (!patterns || patterns.length === 0) return true;
429
- return patterns.some((p) => matchScope(scopePath, p));
282
+ function buildDOSchemaStatements(table) {
283
+ const t = quoteDOIdent(table);
284
+ return [
285
+ `CREATE TABLE IF NOT EXISTS ${t} (
286
+ doc_id TEXT NOT NULL PRIMARY KEY,
287
+ a_type TEXT NOT NULL,
288
+ a_uid TEXT NOT NULL,
289
+ axb_type TEXT NOT NULL,
290
+ b_type TEXT NOT NULL,
291
+ b_uid TEXT NOT NULL,
292
+ data TEXT NOT NULL,
293
+ v INTEGER,
294
+ created_at INTEGER NOT NULL,
295
+ updated_at INTEGER NOT NULL
296
+ )`,
297
+ `CREATE INDEX IF NOT EXISTS ${quoteDOIdent(`${table}_idx_a_uid`)} ON ${t}(a_uid)`,
298
+ `CREATE INDEX IF NOT EXISTS ${quoteDOIdent(`${table}_idx_b_uid`)} ON ${t}(b_uid)`,
299
+ `CREATE INDEX IF NOT EXISTS ${quoteDOIdent(`${table}_idx_axb_type_b_uid`)} ON ${t}(axb_type, b_uid)`,
300
+ `CREATE INDEX IF NOT EXISTS ${quoteDOIdent(`${table}_idx_a_type`)} ON ${t}(a_type)`,
301
+ `CREATE INDEX IF NOT EXISTS ${quoteDOIdent(`${table}_idx_b_type`)} ON ${t}(b_type)`
302
+ ];
430
303
  }
431
- function matchSegments(path, pi, pattern, qi) {
432
- if (pi === path.length && qi === pattern.length) return true;
433
- if (qi === pattern.length) return false;
434
- const seg = pattern[qi];
435
- if (seg === "**") {
436
- if (qi === pattern.length - 1) return true;
437
- for (let skip = 0; skip <= path.length - pi; skip++) {
438
- if (matchSegments(path, pi + skip, pattern, qi + 1)) return true;
439
- }
440
- return false;
304
+
305
+ // src/cloudflare/sql.ts
306
+ function compileFieldRef(field) {
307
+ const column = DO_FIELD_TO_COLUMN[field];
308
+ if (column) {
309
+ return { expr: quoteDOIdent(column) };
441
310
  }
442
- if (pi === path.length) return false;
443
- if (seg === "*") {
444
- return matchSegments(path, pi + 1, pattern, qi + 1);
311
+ if (field.startsWith("data.")) {
312
+ const key = field.slice(5);
313
+ validateJsonPathKey(key);
314
+ return { expr: 'json_extract("data", ?)', pathParam: `$.${key}` };
445
315
  }
446
- if (path[pi] === seg) {
447
- return matchSegments(path, pi + 1, pattern, qi + 1);
316
+ if (field === "data") {
317
+ return { expr: 'json_extract("data", ?)', pathParam: "$" };
448
318
  }
449
- return false;
450
- }
451
-
452
- // src/registry.ts
453
- function tripleKey(aType, axbType, bType) {
454
- return `${aType}:${axbType}:${bType}`;
319
+ throw new FiregraphError(
320
+ `DO SQLite backend cannot resolve filter field: ${field}`,
321
+ "INVALID_QUERY"
322
+ );
455
323
  }
456
- function tripleKeyFor(e) {
457
- return tripleKey(e.aType, e.axbType, e.bType);
324
+ var FIRESTORE_TYPE_NAMES = /* @__PURE__ */ new Set([
325
+ "Timestamp",
326
+ "GeoPoint",
327
+ "VectorValue",
328
+ "DocumentReference",
329
+ "FieldValue"
330
+ ]);
331
+ function isFirestoreSpecialType(value) {
332
+ const ctorName = value.constructor?.name;
333
+ if (ctorName && FIRESTORE_TYPE_NAMES.has(ctorName)) return ctorName;
334
+ return null;
458
335
  }
459
- function createRegistry(input) {
460
- const map = /* @__PURE__ */ new Map();
461
- let entries;
462
- if (Array.isArray(input)) {
463
- entries = input;
464
- } else {
465
- entries = discoveryToEntries(input);
336
+ function bindValue(value) {
337
+ if (value === null || value === void 0) return null;
338
+ if (typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") {
339
+ return value;
466
340
  }
467
- const entryList = Object.freeze([...entries]);
468
- for (const entry of entries) {
469
- if (entry.targetGraph && entry.targetGraph.includes("/")) {
470
- throw new ValidationError(
471
- `Entry (${entry.aType}) -[${entry.axbType}]-> (${entry.bType}) has invalid targetGraph "${entry.targetGraph}" \u2014 must be a single segment (no "/")`
341
+ if (value instanceof Date) return value.getTime();
342
+ if (typeof value === "object") {
343
+ const firestoreType = isFirestoreSpecialType(value);
344
+ if (firestoreType) {
345
+ throw new FiregraphError(
346
+ `DO SQLite backend cannot bind a Firestore ${firestoreType} value \u2014 JSON serialization would silently drop fields and the resulting bind would never match a stored row. Convert to a primitive (e.g. \`ts.toMillis()\` for Timestamp) before filtering or updating.`,
347
+ "INVALID_QUERY"
472
348
  );
473
349
  }
474
- if (entry.migrations?.length) {
475
- const label = `Entry (${entry.aType}) -[${entry.axbType}]-> (${entry.bType})`;
476
- validateMigrationChain(entry.migrations, label);
477
- entry.schemaVersion = Math.max(...entry.migrations.map((m) => m.toVersion));
478
- } else {
479
- entry.schemaVersion = void 0;
480
- }
481
- const key = tripleKey(entry.aType, entry.axbType, entry.bType);
482
- const validator = entry.jsonSchema ? compileSchema(entry.jsonSchema, `(${entry.aType}) -[${entry.axbType}]-> (${entry.bType})`) : void 0;
483
- map.set(key, { entry, validate: validator });
350
+ return JSON.stringify(value);
484
351
  }
485
- const axbIndex = /* @__PURE__ */ new Map();
486
- const axbBuild = /* @__PURE__ */ new Map();
487
- for (const entry of entries) {
488
- const existing = axbBuild.get(entry.axbType);
489
- if (existing) {
490
- existing.push(entry);
491
- } else {
492
- axbBuild.set(entry.axbType, [entry]);
352
+ return String(value);
353
+ }
354
+ var JSON_PATH_KEY_RE = /^[A-Za-z_][A-Za-z0-9_-]*$/;
355
+ function validateJsonPathKey(key) {
356
+ if (key.length === 0) {
357
+ throw new FiregraphError(
358
+ "DO SQLite backend: empty JSON path component is not allowed",
359
+ "INVALID_QUERY"
360
+ );
361
+ }
362
+ if (!JSON_PATH_KEY_RE.test(key)) {
363
+ throw new FiregraphError(
364
+ `DO SQLite backend: data field path component "${key}" is not a safe JSON-path identifier. Allowed pattern: /^[A-Za-z_][A-Za-z0-9_-]*$/. Use replaceData (full-data overwrite) for keys with reserved characters (whitespace, dots, brackets, quotes, etc.).`,
365
+ "INVALID_QUERY"
366
+ );
367
+ }
368
+ }
369
+ function compileFilter(filter, params) {
370
+ const { expr, pathParam } = compileFieldRef(filter.field);
371
+ if (pathParam !== void 0) params.push(pathParam);
372
+ switch (filter.op) {
373
+ case "==":
374
+ params.push(bindValue(filter.value));
375
+ return `${expr} = ?`;
376
+ case "!=":
377
+ params.push(bindValue(filter.value));
378
+ return `${expr} != ?`;
379
+ case "<":
380
+ params.push(bindValue(filter.value));
381
+ return `${expr} < ?`;
382
+ case "<=":
383
+ params.push(bindValue(filter.value));
384
+ return `${expr} <= ?`;
385
+ case ">":
386
+ params.push(bindValue(filter.value));
387
+ return `${expr} > ?`;
388
+ case ">=":
389
+ params.push(bindValue(filter.value));
390
+ return `${expr} >= ?`;
391
+ case "in": {
392
+ const values = asArray(filter.value, "in");
393
+ const placeholders = values.map(() => "?").join(", ");
394
+ for (const v of values) params.push(bindValue(v));
395
+ return `${expr} IN (${placeholders})`;
396
+ }
397
+ case "not-in": {
398
+ const values = asArray(filter.value, "not-in");
399
+ const placeholders = values.map(() => "?").join(", ");
400
+ for (const v of values) params.push(bindValue(v));
401
+ return `${expr} NOT IN (${placeholders})`;
402
+ }
403
+ case "array-contains": {
404
+ params.push(bindValue(filter.value));
405
+ return `EXISTS (SELECT 1 FROM json_each(${expr}) WHERE value = ?)`;
406
+ }
407
+ case "array-contains-any": {
408
+ const values = asArray(filter.value, "array-contains-any");
409
+ const placeholders = values.map(() => "?").join(", ");
410
+ for (const v of values) params.push(bindValue(v));
411
+ return `EXISTS (SELECT 1 FROM json_each(${expr}) WHERE value IN (${placeholders}))`;
493
412
  }
413
+ default:
414
+ throw new FiregraphError(
415
+ `DO SQLite backend does not support filter operator: ${String(filter.op)}`,
416
+ "INVALID_QUERY"
417
+ );
494
418
  }
495
- for (const [key, arr] of axbBuild) {
496
- axbIndex.set(key, Object.freeze(arr));
419
+ }
420
+ function asArray(value, op) {
421
+ if (!Array.isArray(value) || value.length === 0) {
422
+ throw new FiregraphError(`Operator "${op}" requires a non-empty array value`, "INVALID_QUERY");
423
+ }
424
+ return value;
425
+ }
426
+ function compileOrderBy(options, params) {
427
+ if (!options?.orderBy) return "";
428
+ const { field, direction } = options.orderBy;
429
+ const { expr, pathParam } = compileFieldRef(field);
430
+ if (pathParam !== void 0) params.push(pathParam);
431
+ const dir = direction === "desc" ? "DESC" : "ASC";
432
+ return ` ORDER BY ${expr} ${dir}`;
433
+ }
434
+ function compileLimit(options, params) {
435
+ if (options?.limit === void 0) return "";
436
+ params.push(options.limit);
437
+ return ` LIMIT ?`;
438
+ }
439
+ function compileDOSelect(table, filters, options) {
440
+ const params = [];
441
+ const conditions = [];
442
+ for (const f of filters) {
443
+ conditions.push(compileFilter(f, params));
497
444
  }
445
+ const where = conditions.length > 0 ? ` WHERE ${conditions.join(" AND ")}` : "";
446
+ let sql = `SELECT * FROM ${quoteDOIdent(table)}${where}`;
447
+ sql += compileOrderBy(options, params);
448
+ sql += compileLimit(options, params);
449
+ return { sql, params };
450
+ }
451
+ function compileDOSelectByDocId(table, docId) {
498
452
  return {
499
- lookup(aType, axbType, bType) {
500
- return map.get(tripleKey(aType, axbType, bType))?.entry;
501
- },
502
- lookupByAxbType(axbType) {
503
- return axbIndex.get(axbType) ?? [];
504
- },
505
- validate(aType, axbType, bType, data, scopePath) {
506
- const rec = map.get(tripleKey(aType, axbType, bType));
507
- if (!rec) {
508
- throw new RegistryViolationError(aType, axbType, bType);
509
- }
510
- if (scopePath !== void 0 && rec.entry.allowedIn && rec.entry.allowedIn.length > 0) {
511
- if (!matchScopeAny(scopePath, rec.entry.allowedIn)) {
512
- throw new RegistryScopeError(aType, axbType, bType, scopePath, rec.entry.allowedIn);
513
- }
514
- }
515
- if (rec.validate) {
516
- try {
517
- rec.validate(data);
518
- } catch (err) {
519
- if (err instanceof ValidationError) throw err;
520
- throw new ValidationError(
521
- `Data validation failed for (${aType}) -[${axbType}]-> (${bType})`,
522
- err
523
- );
524
- }
525
- }
526
- },
527
- entries() {
528
- return entryList;
453
+ sql: `SELECT * FROM ${quoteDOIdent(table)} WHERE "doc_id" = ? LIMIT 1`,
454
+ params: [docId]
455
+ };
456
+ }
457
+ function compileDOSet(table, docId, record, nowMillis) {
458
+ const sql = `INSERT OR REPLACE INTO ${quoteDOIdent(table)} (
459
+ doc_id, a_type, a_uid, axb_type, b_type, b_uid, data, v, created_at, updated_at
460
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
461
+ const params = [
462
+ docId,
463
+ record.aType,
464
+ record.aUid,
465
+ record.axbType,
466
+ record.bType,
467
+ record.bUid,
468
+ JSON.stringify(record.data ?? {}),
469
+ record.v ?? null,
470
+ nowMillis,
471
+ nowMillis
472
+ ];
473
+ return { sql, params };
474
+ }
475
+ function compileDOUpdate(table, docId, update, nowMillis) {
476
+ const setClauses = [];
477
+ const params = [];
478
+ if (update.replaceData) {
479
+ setClauses.push(`"data" = ?`);
480
+ params.push(JSON.stringify(update.replaceData));
481
+ } else if (update.dataFields && Object.keys(update.dataFields).length > 0) {
482
+ const entries = Object.entries(update.dataFields);
483
+ const pathArgs = entries.map(() => `?, ?`).join(", ");
484
+ setClauses.push(`"data" = json_set(COALESCE("data", '{}'), ${pathArgs})`);
485
+ for (const [k, v] of entries) {
486
+ validateJsonPathKey(k);
487
+ params.push(`$.${k}`);
488
+ params.push(bindValue(v));
529
489
  }
490
+ }
491
+ if (update.v !== void 0) {
492
+ setClauses.push(`"v" = ?`);
493
+ params.push(update.v);
494
+ }
495
+ setClauses.push(`"updated_at" = ?`);
496
+ params.push(nowMillis);
497
+ params.push(docId);
498
+ return {
499
+ sql: `UPDATE ${quoteDOIdent(table)} SET ${setClauses.join(", ")} WHERE "doc_id" = ?`,
500
+ params
530
501
  };
531
502
  }
532
- function createMergedRegistry(base, extension) {
533
- const baseKeys = new Set(base.entries().map(tripleKeyFor));
503
+ function compileDODelete(table, docId) {
534
504
  return {
535
- lookup(aType, axbType, bType) {
536
- return base.lookup(aType, axbType, bType) ?? extension.lookup(aType, axbType, bType);
537
- },
538
- lookupByAxbType(axbType) {
539
- const baseResults = base.lookupByAxbType(axbType);
540
- const extResults = extension.lookupByAxbType(axbType);
541
- if (extResults.length === 0) return baseResults;
542
- if (baseResults.length === 0) return extResults;
543
- const seen = new Set(baseResults.map(tripleKeyFor));
544
- const merged = [...baseResults];
505
+ sql: `DELETE FROM ${quoteDOIdent(table)} WHERE "doc_id" = ?`,
506
+ params: [docId]
507
+ };
508
+ }
509
+ function compileDODeleteAll(table) {
510
+ return {
511
+ sql: `DELETE FROM ${quoteDOIdent(table)}`,
512
+ params: []
513
+ };
514
+ }
515
+ function rowToDORecord(row) {
516
+ const dataString = row.data;
517
+ const data = dataString ? JSON.parse(dataString) : {};
518
+ const createdAtMs = toMillis(row.created_at);
519
+ const updatedAtMs = toMillis(row.updated_at);
520
+ const record = {
521
+ aType: row.a_type,
522
+ aUid: row.a_uid,
523
+ axbType: row.axb_type,
524
+ bType: row.b_type,
525
+ bUid: row.b_uid,
526
+ data,
527
+ createdAtMs,
528
+ updatedAtMs
529
+ };
530
+ if (row.v !== null && row.v !== void 0) {
531
+ record.v = Number(row.v);
532
+ }
533
+ return record;
534
+ }
535
+ function hydrateDORecord(wire) {
536
+ const record = {
537
+ aType: wire.aType,
538
+ aUid: wire.aUid,
539
+ axbType: wire.axbType,
540
+ bType: wire.bType,
541
+ bUid: wire.bUid,
542
+ data: wire.data,
543
+ createdAt: GraphTimestampImpl.fromMillis(wire.createdAtMs),
544
+ updatedAt: GraphTimestampImpl.fromMillis(wire.updatedAtMs)
545
+ };
546
+ if (wire.v !== void 0) {
547
+ record.v = wire.v;
548
+ }
549
+ return record;
550
+ }
551
+ function toMillis(value) {
552
+ if (typeof value === "number") return value;
553
+ if (typeof value === "bigint") return Number(value);
554
+ if (typeof value === "string") {
555
+ const n = Number(value);
556
+ if (Number.isFinite(n)) return n;
557
+ }
558
+ throw new FiregraphError(
559
+ `DO SQLite row has non-numeric timestamp column: ${typeof value} (${String(value)})`,
560
+ "INVALID_QUERY"
561
+ );
562
+ }
563
+
564
+ // src/cloudflare/backend.ts
565
+ function validateSegment(value, label) {
566
+ if (!value || value.includes("/")) {
567
+ throw new FiregraphError(
568
+ `Invalid ${label} for subgraph: "${value}". Must be non-empty and not contain "/".`,
569
+ "INVALID_SUBGRAPH"
570
+ );
571
+ }
572
+ }
573
+ function transactionsUnsupported() {
574
+ return new FiregraphError(
575
+ "Interactive transactions are not supported by the Cloudflare DO backend. Use `batch()` for atomic multi-write commits, or restructure the read-then-conditional-write as an explicit read \u2192 decide \u2192 batch sequence.",
576
+ "UNSUPPORTED_OPERATION"
577
+ );
578
+ }
579
+ var DORPCBatchBackend = class {
580
+ constructor(getStub) {
581
+ this.getStub = getStub;
582
+ }
583
+ ops = [];
584
+ setDoc(docId, record) {
585
+ this.ops.push({ kind: "set", docId, record });
586
+ }
587
+ updateDoc(docId, update) {
588
+ this.ops.push({ kind: "update", docId, update });
589
+ }
590
+ deleteDoc(docId) {
591
+ this.ops.push({ kind: "delete", docId });
592
+ }
593
+ async commit() {
594
+ if (this.ops.length === 0) return;
595
+ const ops = this.ops.slice();
596
+ this.ops.length = 0;
597
+ await this.getStub()._fgBatch(ops);
598
+ }
599
+ };
600
+ var DORPCBackend = class _DORPCBackend {
601
+ collectionPath = "firegraph";
602
+ scopePath;
603
+ /** @internal */
604
+ storageKey;
605
+ /** @internal */
606
+ namespace;
607
+ registryAccessor;
608
+ /** @internal — see `DORPCBackendOptions.makeSiblingClient` for the union-type rationale. */
609
+ makeSiblingClient;
610
+ cachedStub = null;
611
+ constructor(namespace, options) {
612
+ this.namespace = namespace;
613
+ this.scopePath = options.scopePath ?? "";
614
+ this.storageKey = options.storageKey;
615
+ this.registryAccessor = options.registryAccessor;
616
+ this.makeSiblingClient = options.makeSiblingClient;
617
+ }
618
+ get stub() {
619
+ if (!this.cachedStub) {
620
+ const id = this.namespace.idFromName(this.storageKey);
621
+ this.cachedStub = this.namespace.get(id);
622
+ }
623
+ return this.cachedStub;
624
+ }
625
+ // --- Reads ---
626
+ async getDoc(docId) {
627
+ const wire = await this.stub._fgGetDoc(docId);
628
+ return wire ? hydrateDORecord(wire) : null;
629
+ }
630
+ async query(filters, options) {
631
+ const wires = await this.stub._fgQuery(filters, options);
632
+ return wires.map(hydrateDORecord);
633
+ }
634
+ // --- Writes ---
635
+ async setDoc(docId, record) {
636
+ return this.stub._fgSetDoc(docId, record);
637
+ }
638
+ async updateDoc(docId, update) {
639
+ return this.stub._fgUpdateDoc(docId, update);
640
+ }
641
+ async deleteDoc(docId) {
642
+ return this.stub._fgDeleteDoc(docId);
643
+ }
644
+ // --- Transactions / batches ---
645
+ async runTransaction(_fn) {
646
+ void _fn;
647
+ throw transactionsUnsupported();
648
+ }
649
+ createBatch() {
650
+ return new DORPCBatchBackend(() => this.stub);
651
+ }
652
+ // --- Subgraphs ---
653
+ subgraph(parentNodeUid, name) {
654
+ validateSegment(parentNodeUid, "parentNodeUid");
655
+ validateSegment(name, "subgraph name");
656
+ const newStorageKey = `${this.storageKey}/${parentNodeUid}/${name}`;
657
+ const newScopePath = this.scopePath ? `${this.scopePath}/${name}` : name;
658
+ return new _DORPCBackend(this.namespace, {
659
+ scopePath: newScopePath,
660
+ storageKey: newStorageKey,
661
+ // Subgraph backends share the same live registry accessor so a cascade
662
+ // invoked on a subgraph client still fans out correctly. The sibling
663
+ // factory is also carried forward so `createSiblingClient` works from
664
+ // any subgraph client in the chain.
665
+ registryAccessor: this.registryAccessor,
666
+ makeSiblingClient: this.makeSiblingClient
667
+ });
668
+ }
669
+ // --- Cascade & bulk ---
670
+ async removeNodeCascade(uid, reader, options) {
671
+ const shouldDeleteSubgraphs = options?.deleteSubcollections !== false;
672
+ const registry = this.registryAccessor?.();
673
+ if (shouldDeleteSubgraphs && registry) {
674
+ const node = await reader.getNode(uid);
675
+ if (node) {
676
+ const topology = registry.getSubgraphTopology(node.aType);
677
+ for (const entry of topology) {
678
+ const target = entry.targetGraph;
679
+ const childBackend = this.subgraph(uid, target);
680
+ await childBackend.destroyRecursively(registry);
681
+ }
682
+ }
683
+ }
684
+ return this.stub._fgRemoveNodeCascade(uid);
685
+ }
686
+ async bulkRemoveEdges(params, _reader, options) {
687
+ void _reader;
688
+ return this.stub._fgBulkRemoveEdges(params, options);
689
+ }
690
+ // --- Cross-scope queries ---
691
+ //
692
+ // `findEdgesGlobal` is deliberately NOT defined on this class. The
693
+ // GraphClient checks for its presence before running query planning and
694
+ // throws `UNSUPPORTED_OPERATION` when absent, giving the caller an
695
+ // immediate, accurate error. Defining the method with a throwing body
696
+ // would only surface the same error AFTER `checkQuerySafety` had already
697
+ // fired — and for scan-unsafe calls that results in a misleading
698
+ // `QuerySafetyError` ("add filters like aUid+axbType") when no filter
699
+ // combination would actually make the call work on this backend. See the
700
+ // "What's not supported" section in `createDOClient` for the design
701
+ // rationale (no collection-group index across DOs).
702
+ // --- Destroy helpers ---
703
+ /**
704
+ * Wipe this DO's storage. The DO itself can't be deleted — its ID
705
+ * persists forever — but its rows can be emptied, which is what the
706
+ * cascade walk does on every descendant subgraph DO.
707
+ *
708
+ * Exposed on the concrete class (not `StorageBackend`) so generic
709
+ * backend code doesn't reach for it.
710
+ */
711
+ async destroy() {
712
+ await this.stub._fgDestroy();
713
+ }
714
+ /**
715
+ * Tear down every descendant subgraph DO, then wipe this DO's own rows.
716
+ *
717
+ * Invoked by cross-DO cascade: for each node in this DO we enumerate the
718
+ * subgraph topology and recurse into child DOs depth-first before
719
+ * wiping the current DO. The current DO's own rows are destroyed last so
720
+ * that a partial failure mid-recursion leaves the caller's reader able
721
+ * to discover what's still present.
722
+ *
723
+ * @internal
724
+ */
725
+ async destroyRecursively(registry) {
726
+ const nodes = await this.query([{ field: "axbType", op: "==", value: NODE_RELATION }]);
727
+ for (const node of nodes) {
728
+ const topology = registry.getSubgraphTopology(node.aType);
729
+ for (const entry of topology) {
730
+ const target = entry.targetGraph;
731
+ const childBackend = this.subgraph(node.aUid, target);
732
+ await childBackend.destroyRecursively(registry);
733
+ }
734
+ }
735
+ await this.destroy();
736
+ }
737
+ };
738
+
739
+ // src/docid.ts
740
+ var import_node_crypto = require("crypto");
741
+ function computeNodeDocId(uid) {
742
+ return uid;
743
+ }
744
+ function computeEdgeDocId(aUid, axbType, bUid) {
745
+ const composite = `${aUid}${SHARD_SEPARATOR}${axbType}${SHARD_SEPARATOR}${bUid}`;
746
+ const hash = (0, import_node_crypto.createHash)("sha256").update(composite).digest("hex");
747
+ const shard = hash[0];
748
+ return `${shard}${SHARD_SEPARATOR}${aUid}${SHARD_SEPARATOR}${axbType}${SHARD_SEPARATOR}${bUid}`;
749
+ }
750
+
751
+ // src/batch.ts
752
+ function buildWritableNodeRecord(aType, uid, data) {
753
+ return { aType, aUid: uid, axbType: NODE_RELATION, bType: aType, bUid: uid, data };
754
+ }
755
+ function buildWritableEdgeRecord(aType, aUid, axbType, bType, bUid, data) {
756
+ return { aType, aUid, axbType, bType, bUid, data };
757
+ }
758
+ var GraphBatchImpl = class {
759
+ constructor(backend, registry, scopePath = "") {
760
+ this.backend = backend;
761
+ this.registry = registry;
762
+ this.scopePath = scopePath;
763
+ }
764
+ async putNode(aType, uid, data) {
765
+ if (this.registry) {
766
+ this.registry.validate(aType, NODE_RELATION, aType, data, this.scopePath);
767
+ }
768
+ const docId = computeNodeDocId(uid);
769
+ const record = buildWritableNodeRecord(aType, uid, data);
770
+ if (this.registry) {
771
+ const entry = this.registry.lookup(aType, NODE_RELATION, aType);
772
+ if (entry?.schemaVersion && entry.schemaVersion > 0) {
773
+ record.v = entry.schemaVersion;
774
+ }
775
+ }
776
+ this.backend.setDoc(docId, record);
777
+ }
778
+ async putEdge(aType, aUid, axbType, bType, bUid, data) {
779
+ if (this.registry) {
780
+ this.registry.validate(aType, axbType, bType, data, this.scopePath);
781
+ }
782
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
783
+ const record = buildWritableEdgeRecord(aType, aUid, axbType, bType, bUid, data);
784
+ if (this.registry) {
785
+ const entry = this.registry.lookup(aType, axbType, bType);
786
+ if (entry?.schemaVersion && entry.schemaVersion > 0) {
787
+ record.v = entry.schemaVersion;
788
+ }
789
+ }
790
+ this.backend.setDoc(docId, record);
791
+ }
792
+ async updateNode(uid, data) {
793
+ const docId = computeNodeDocId(uid);
794
+ this.backend.updateDoc(docId, { dataFields: data });
795
+ }
796
+ async removeNode(uid) {
797
+ const docId = computeNodeDocId(uid);
798
+ this.backend.deleteDoc(docId);
799
+ }
800
+ async removeEdge(aUid, axbType, bUid) {
801
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
802
+ this.backend.deleteDoc(docId);
803
+ }
804
+ async commit() {
805
+ await this.backend.commit();
806
+ }
807
+ };
808
+
809
+ // src/dynamic-registry.ts
810
+ var import_node_crypto3 = require("crypto");
811
+
812
+ // src/json-schema.ts
813
+ var import_ajv = __toESM(require("ajv"), 1);
814
+ var import_ajv_formats = __toESM(require("ajv-formats"), 1);
815
+ var ajv = new import_ajv.default({ allErrors: true, strict: false });
816
+ (0, import_ajv_formats.default)(ajv);
817
+ function compileSchema(schema, label) {
818
+ const validate = ajv.compile(schema);
819
+ return (data) => {
820
+ if (!validate(data)) {
821
+ const errors = validate.errors ?? [];
822
+ const messages = errors.map((err) => `${err.instancePath || "/"}${err.message ? ": " + err.message : ""}`).join("; ");
823
+ throw new ValidationError(
824
+ `Data validation failed${label ? " for " + label : ""}: ${messages}`,
825
+ errors
826
+ );
827
+ }
828
+ };
829
+ }
830
+
831
+ // src/migration.ts
832
+ async function applyMigrationChain(data, currentVersion, targetVersion, migrations) {
833
+ const sorted = [...migrations].sort((a, b) => a.fromVersion - b.fromVersion);
834
+ let result = { ...data };
835
+ let version = currentVersion;
836
+ for (const step of sorted) {
837
+ if (step.fromVersion === version) {
838
+ try {
839
+ result = await step.up(result);
840
+ } catch (err) {
841
+ if (err instanceof MigrationError) throw err;
842
+ throw new MigrationError(
843
+ `Migration from v${step.fromVersion} to v${step.toVersion} failed: ${err.message}`
844
+ );
845
+ }
846
+ if (!result || typeof result !== "object") {
847
+ throw new MigrationError(
848
+ `Migration from v${step.fromVersion} to v${step.toVersion} returned invalid data (expected object)`
849
+ );
850
+ }
851
+ version = step.toVersion;
852
+ }
853
+ }
854
+ if (version !== targetVersion) {
855
+ throw new MigrationError(
856
+ `Incomplete migration chain: reached v${version} but target is v${targetVersion}`
857
+ );
858
+ }
859
+ return result;
860
+ }
861
+ function validateMigrationChain(migrations, label) {
862
+ if (migrations.length === 0) return;
863
+ const seen = /* @__PURE__ */ new Set();
864
+ for (const step of migrations) {
865
+ if (step.toVersion <= step.fromVersion) {
866
+ throw new MigrationError(
867
+ `${label}: migration step has toVersion (${step.toVersion}) <= fromVersion (${step.fromVersion})`
868
+ );
869
+ }
870
+ if (seen.has(step.fromVersion)) {
871
+ throw new MigrationError(
872
+ `${label}: duplicate migration step for fromVersion ${step.fromVersion}`
873
+ );
874
+ }
875
+ seen.add(step.fromVersion);
876
+ }
877
+ const sorted = [...migrations].sort((a, b) => a.fromVersion - b.fromVersion);
878
+ const targetVersion = Math.max(...migrations.map((m) => m.toVersion));
879
+ let version = 0;
880
+ for (const step of sorted) {
881
+ if (step.fromVersion === version) {
882
+ version = step.toVersion;
883
+ } else if (step.fromVersion > version) {
884
+ throw new MigrationError(
885
+ `${label}: migration chain has a gap \u2014 no step covers v${version} \u2192 v${step.fromVersion}`
886
+ );
887
+ }
888
+ }
889
+ if (version !== targetVersion) {
890
+ throw new MigrationError(
891
+ `${label}: migration chain does not reach v${targetVersion} (stuck at v${version})`
892
+ );
893
+ }
894
+ }
895
+ async function migrateRecord(record, registry, globalWriteBack = "off") {
896
+ const entry = registry.lookup(record.aType, record.axbType, record.bType);
897
+ if (!entry?.migrations?.length || !entry.schemaVersion) {
898
+ return { record, migrated: false, writeBack: "off" };
899
+ }
900
+ const currentVersion = record.v ?? 0;
901
+ if (currentVersion >= entry.schemaVersion) {
902
+ return { record, migrated: false, writeBack: "off" };
903
+ }
904
+ const migratedData = await applyMigrationChain(
905
+ record.data,
906
+ currentVersion,
907
+ entry.schemaVersion,
908
+ entry.migrations
909
+ );
910
+ const writeBack = entry.migrationWriteBack ?? globalWriteBack ?? "off";
911
+ return {
912
+ record: { ...record, data: migratedData, v: entry.schemaVersion },
913
+ migrated: true,
914
+ writeBack
915
+ };
916
+ }
917
+ async function migrateRecords(records, registry, globalWriteBack = "off") {
918
+ return Promise.all(
919
+ records.map((r) => migrateRecord(r, registry, globalWriteBack))
920
+ );
921
+ }
922
+
923
+ // src/scope.ts
924
+ function matchScope(scopePath, pattern) {
925
+ if (pattern === "root") return scopePath === "";
926
+ if (pattern === "**") return true;
927
+ const pathSegments = scopePath === "" ? [] : scopePath.split("/");
928
+ const patternSegments = pattern.split("/");
929
+ return matchSegments(pathSegments, 0, patternSegments, 0);
930
+ }
931
+ function matchScopeAny(scopePath, patterns) {
932
+ if (!patterns || patterns.length === 0) return true;
933
+ return patterns.some((p) => matchScope(scopePath, p));
934
+ }
935
+ function matchSegments(path, pi, pattern, qi) {
936
+ if (pi === path.length && qi === pattern.length) return true;
937
+ if (qi === pattern.length) return false;
938
+ const seg = pattern[qi];
939
+ if (seg === "**") {
940
+ if (qi === pattern.length - 1) return true;
941
+ for (let skip = 0; skip <= path.length - pi; skip++) {
942
+ if (matchSegments(path, pi + skip, pattern, qi + 1)) return true;
943
+ }
944
+ return false;
945
+ }
946
+ if (pi === path.length) return false;
947
+ if (seg === "*") {
948
+ return matchSegments(path, pi + 1, pattern, qi + 1);
949
+ }
950
+ if (path[pi] === seg) {
951
+ return matchSegments(path, pi + 1, pattern, qi + 1);
952
+ }
953
+ return false;
954
+ }
955
+
956
+ // src/registry.ts
957
+ function tripleKey(aType, axbType, bType) {
958
+ return `${aType}:${axbType}:${bType}`;
959
+ }
960
+ function tripleKeyFor(e) {
961
+ return tripleKey(e.aType, e.axbType, e.bType);
962
+ }
963
+ function createRegistry(input) {
964
+ const map = /* @__PURE__ */ new Map();
965
+ let entries;
966
+ if (Array.isArray(input)) {
967
+ entries = input;
968
+ } else {
969
+ entries = discoveryToEntries(input);
970
+ }
971
+ const entryList = Object.freeze([...entries]);
972
+ for (const entry of entries) {
973
+ if (entry.targetGraph && entry.targetGraph.includes("/")) {
974
+ throw new ValidationError(
975
+ `Entry (${entry.aType}) -[${entry.axbType}]-> (${entry.bType}) has invalid targetGraph "${entry.targetGraph}" \u2014 must be a single segment (no "/")`
976
+ );
977
+ }
978
+ if (entry.migrations?.length) {
979
+ const label = `Entry (${entry.aType}) -[${entry.axbType}]-> (${entry.bType})`;
980
+ validateMigrationChain(entry.migrations, label);
981
+ entry.schemaVersion = Math.max(...entry.migrations.map((m) => m.toVersion));
982
+ } else {
983
+ entry.schemaVersion = void 0;
984
+ }
985
+ const key = tripleKey(entry.aType, entry.axbType, entry.bType);
986
+ const validator = entry.jsonSchema ? compileSchema(entry.jsonSchema, `(${entry.aType}) -[${entry.axbType}]-> (${entry.bType})`) : void 0;
987
+ map.set(key, { entry, validate: validator });
988
+ }
989
+ const axbIndex = /* @__PURE__ */ new Map();
990
+ const axbBuild = /* @__PURE__ */ new Map();
991
+ for (const entry of entries) {
992
+ const existing = axbBuild.get(entry.axbType);
993
+ if (existing) {
994
+ existing.push(entry);
995
+ } else {
996
+ axbBuild.set(entry.axbType, [entry]);
997
+ }
998
+ }
999
+ for (const [key, arr] of axbBuild) {
1000
+ axbIndex.set(key, Object.freeze(arr));
1001
+ }
1002
+ const topologyIndex = /* @__PURE__ */ new Map();
1003
+ const topologyBuild = /* @__PURE__ */ new Map();
1004
+ const topologySeen = /* @__PURE__ */ new Map();
1005
+ for (const entry of entries) {
1006
+ if (!entry.targetGraph) continue;
1007
+ let seen = topologySeen.get(entry.aType);
1008
+ if (!seen) {
1009
+ seen = /* @__PURE__ */ new Set();
1010
+ topologySeen.set(entry.aType, seen);
1011
+ }
1012
+ if (seen.has(entry.targetGraph)) continue;
1013
+ seen.add(entry.targetGraph);
1014
+ const existing = topologyBuild.get(entry.aType);
1015
+ if (existing) {
1016
+ existing.push(entry);
1017
+ } else {
1018
+ topologyBuild.set(entry.aType, [entry]);
1019
+ }
1020
+ }
1021
+ for (const [key, arr] of topologyBuild) {
1022
+ topologyIndex.set(key, Object.freeze(arr));
1023
+ }
1024
+ return {
1025
+ lookup(aType, axbType, bType) {
1026
+ return map.get(tripleKey(aType, axbType, bType))?.entry;
1027
+ },
1028
+ lookupByAxbType(axbType) {
1029
+ return axbIndex.get(axbType) ?? [];
1030
+ },
1031
+ getSubgraphTopology(aType) {
1032
+ return topologyIndex.get(aType) ?? [];
1033
+ },
1034
+ validate(aType, axbType, bType, data, scopePath) {
1035
+ const rec = map.get(tripleKey(aType, axbType, bType));
1036
+ if (!rec) {
1037
+ throw new RegistryViolationError(aType, axbType, bType);
1038
+ }
1039
+ if (scopePath !== void 0 && rec.entry.allowedIn && rec.entry.allowedIn.length > 0) {
1040
+ if (!matchScopeAny(scopePath, rec.entry.allowedIn)) {
1041
+ throw new RegistryScopeError(aType, axbType, bType, scopePath, rec.entry.allowedIn);
1042
+ }
1043
+ }
1044
+ if (rec.validate) {
1045
+ try {
1046
+ rec.validate(data);
1047
+ } catch (err) {
1048
+ if (err instanceof ValidationError) throw err;
1049
+ throw new ValidationError(
1050
+ `Data validation failed for (${aType}) -[${axbType}]-> (${bType})`,
1051
+ err
1052
+ );
1053
+ }
1054
+ }
1055
+ },
1056
+ entries() {
1057
+ return entryList;
1058
+ }
1059
+ };
1060
+ }
1061
+ function createMergedRegistry(base, extension) {
1062
+ const baseKeys = new Set(base.entries().map(tripleKeyFor));
1063
+ return {
1064
+ lookup(aType, axbType, bType) {
1065
+ return base.lookup(aType, axbType, bType) ?? extension.lookup(aType, axbType, bType);
1066
+ },
1067
+ lookupByAxbType(axbType) {
1068
+ const baseResults = base.lookupByAxbType(axbType);
1069
+ const extResults = extension.lookupByAxbType(axbType);
1070
+ if (extResults.length === 0) return baseResults;
1071
+ if (baseResults.length === 0) return extResults;
1072
+ const seen = new Set(baseResults.map(tripleKeyFor));
1073
+ const merged = [...baseResults];
545
1074
  for (const entry of extResults) {
546
1075
  if (!seen.has(tripleKeyFor(entry))) {
547
1076
  merged.push(entry);
@@ -549,6 +1078,21 @@ function createMergedRegistry(base, extension) {
549
1078
  }
550
1079
  return Object.freeze(merged);
551
1080
  },
1081
+ getSubgraphTopology(aType) {
1082
+ const baseResults = base.getSubgraphTopology(aType);
1083
+ const extResults = extension.getSubgraphTopology(aType);
1084
+ if (extResults.length === 0) return baseResults;
1085
+ if (baseResults.length === 0) return extResults;
1086
+ const seen = new Set(baseResults.map((e) => e.targetGraph));
1087
+ const merged = [...baseResults];
1088
+ for (const entry of extResults) {
1089
+ if (!seen.has(entry.targetGraph)) {
1090
+ seen.add(entry.targetGraph);
1091
+ merged.push(entry);
1092
+ }
1093
+ }
1094
+ return Object.freeze(merged);
1095
+ },
552
1096
  validate(aType, axbType, bType, data, scopePath) {
553
1097
  if (baseKeys.has(tripleKey(aType, axbType, bType))) {
554
1098
  return base.validate(aType, axbType, bType, data, scopePath);
@@ -1173,263 +1717,46 @@ var GraphTransactionImpl = class {
1173
1717
  return this.applyMigrations(records);
1174
1718
  }
1175
1719
  async applyMigrations(records) {
1176
- if (!this.registry || records.length === 0) return records;
1177
- const results = await migrateRecords(records, this.registry, this.globalWriteBack);
1178
- for (const result of results) {
1179
- if (result.migrated && result.writeBack !== "off") {
1180
- const docId = result.record.axbType === NODE_RELATION ? computeNodeDocId(result.record.aUid) : computeEdgeDocId(result.record.aUid, result.record.axbType, result.record.bUid);
1181
- await this.backend.updateDoc(docId, {
1182
- replaceData: result.record.data,
1183
- v: result.record.v
1184
- });
1185
- }
1186
- }
1187
- return results.map((r) => r.record);
1188
- }
1189
- async putNode(aType, uid, data) {
1190
- if (this.registry) {
1191
- this.registry.validate(aType, NODE_RELATION, aType, data, this.scopePath);
1192
- }
1193
- const docId = computeNodeDocId(uid);
1194
- const record = buildWritableNodeRecord2(aType, uid, data);
1195
- if (this.registry) {
1196
- const entry = this.registry.lookup(aType, NODE_RELATION, aType);
1197
- if (entry?.schemaVersion && entry.schemaVersion > 0) {
1198
- record.v = entry.schemaVersion;
1199
- }
1200
- }
1201
- await this.backend.setDoc(docId, record);
1202
- }
1203
- async putEdge(aType, aUid, axbType, bType, bUid, data) {
1204
- if (this.registry) {
1205
- this.registry.validate(aType, axbType, bType, data, this.scopePath);
1206
- }
1207
- const docId = computeEdgeDocId(aUid, axbType, bUid);
1208
- const record = buildWritableEdgeRecord2(aType, aUid, axbType, bType, bUid, data);
1209
- if (this.registry) {
1210
- const entry = this.registry.lookup(aType, axbType, bType);
1211
- if (entry?.schemaVersion && entry.schemaVersion > 0) {
1212
- record.v = entry.schemaVersion;
1213
- }
1214
- }
1215
- await this.backend.setDoc(docId, record);
1216
- }
1217
- async updateNode(uid, data) {
1218
- const docId = computeNodeDocId(uid);
1219
- await this.backend.updateDoc(docId, { dataFields: data });
1220
- }
1221
- async removeNode(uid) {
1222
- const docId = computeNodeDocId(uid);
1223
- await this.backend.deleteDoc(docId);
1224
- }
1225
- async removeEdge(aUid, axbType, bUid) {
1226
- const docId = computeEdgeDocId(aUid, axbType, bUid);
1227
- await this.backend.deleteDoc(docId);
1228
- }
1229
- };
1230
-
1231
- // src/client.ts
1232
- var RESERVED_TYPE_NAMES = /* @__PURE__ */ new Set([META_NODE_TYPE, META_EDGE_TYPE]);
1233
- function buildWritableNodeRecord3(aType, uid, data) {
1234
- return { aType, aUid: uid, axbType: NODE_RELATION, bType: aType, bUid: uid, data };
1235
- }
1236
- function buildWritableEdgeRecord3(aType, aUid, axbType, bType, bUid, data) {
1237
- return { aType, aUid, axbType, bType, bUid, data };
1238
- }
1239
- var GraphClientImpl = class _GraphClientImpl {
1240
- constructor(backend, options, metaBackend) {
1241
- this.backend = backend;
1242
- this.globalWriteBack = options?.migrationWriteBack ?? "off";
1243
- this.migrationSandbox = options?.migrationSandbox;
1244
- if (options?.registryMode) {
1245
- this.dynamicConfig = options.registryMode;
1246
- this.bootstrapRegistry = createBootstrapRegistry();
1247
- if (options.registry) {
1248
- this.staticRegistry = options.registry;
1249
- }
1250
- this.metaBackend = metaBackend;
1251
- } else {
1252
- this.staticRegistry = options?.registry;
1253
- }
1254
- this.scanProtection = options?.scanProtection ?? "error";
1255
- }
1256
- scanProtection;
1257
- // Static mode
1258
- staticRegistry;
1259
- // Dynamic mode
1260
- dynamicConfig;
1261
- bootstrapRegistry;
1262
- dynamicRegistry;
1263
- metaBackend;
1264
- // Migration settings
1265
- globalWriteBack;
1266
- migrationSandbox;
1267
- // ---------------------------------------------------------------------------
1268
- // Backend access (exposed for traversal helpers and subgraph cloning)
1269
- // ---------------------------------------------------------------------------
1270
- /** @internal */
1271
- getBackend() {
1272
- return this.backend;
1273
- }
1274
- // ---------------------------------------------------------------------------
1275
- // Registry routing
1276
- // ---------------------------------------------------------------------------
1277
- getRegistryForType(aType) {
1278
- if (!this.dynamicConfig) return this.staticRegistry;
1279
- if (aType === META_NODE_TYPE || aType === META_EDGE_TYPE) {
1280
- return this.bootstrapRegistry;
1281
- }
1282
- return this.dynamicRegistry ?? this.staticRegistry ?? this.bootstrapRegistry;
1283
- }
1284
- getBackendForType(aType) {
1285
- if (this.metaBackend && (aType === META_NODE_TYPE || aType === META_EDGE_TYPE)) {
1286
- return this.metaBackend;
1287
- }
1288
- return this.backend;
1289
- }
1290
- getCombinedRegistry() {
1291
- if (!this.dynamicConfig) return this.staticRegistry;
1292
- return this.dynamicRegistry ?? this.staticRegistry ?? this.bootstrapRegistry;
1293
- }
1294
- // ---------------------------------------------------------------------------
1295
- // Query safety
1296
- // ---------------------------------------------------------------------------
1297
- checkQuerySafety(filters, allowCollectionScan) {
1298
- if (allowCollectionScan || this.scanProtection === "off") return;
1299
- const result = analyzeQuerySafety(filters);
1300
- if (result.safe) return;
1301
- if (this.scanProtection === "error") {
1302
- throw new QuerySafetyError(result.reason);
1303
- }
1304
- console.warn(`[firegraph] Query safety warning: ${result.reason}`);
1305
- }
1306
- // ---------------------------------------------------------------------------
1307
- // Migration helpers
1308
- // ---------------------------------------------------------------------------
1309
- async applyMigration(record, docId) {
1310
- const registry = this.getCombinedRegistry();
1311
- if (!registry) return record;
1312
- const result = await migrateRecord(record, registry, this.globalWriteBack);
1313
- if (result.migrated) {
1314
- this.handleWriteBack(result, docId);
1315
- }
1316
- return result.record;
1317
- }
1318
- async applyMigrations(records) {
1319
- const registry = this.getCombinedRegistry();
1320
- if (!registry || records.length === 0) return records;
1321
- const results = await migrateRecords(records, registry, this.globalWriteBack);
1322
- for (const result of results) {
1323
- if (result.migrated) {
1324
- const docId = result.record.axbType === NODE_RELATION ? computeNodeDocId(result.record.aUid) : computeEdgeDocId(result.record.aUid, result.record.axbType, result.record.bUid);
1325
- this.handleWriteBack(result, docId);
1326
- }
1327
- }
1328
- return results.map((r) => r.record);
1329
- }
1330
- /**
1331
- * Fire-and-forget write-back for a migrated record. Both `'eager'` and
1332
- * `'background'` are non-blocking; the difference is the log level on
1333
- * failure. For synchronous write-back, use a transaction — see
1334
- * `GraphTransactionImpl`.
1335
- */
1336
- handleWriteBack(result, docId) {
1337
- if (result.writeBack === "off") return;
1338
- const doWriteBack = async () => {
1339
- try {
1340
- await this.backend.updateDoc(docId, {
1341
- replaceData: result.record.data,
1342
- v: result.record.v
1343
- });
1344
- } catch (err) {
1345
- const msg = `[firegraph] Migration write-back failed for ${docId}: ${err.message}`;
1346
- if (result.writeBack === "eager") {
1347
- console.error(msg);
1348
- } else {
1349
- console.warn(msg);
1350
- }
1351
- }
1352
- };
1353
- void doWriteBack();
1354
- }
1355
- // ---------------------------------------------------------------------------
1356
- // GraphReader
1357
- // ---------------------------------------------------------------------------
1358
- async getNode(uid) {
1359
- const docId = computeNodeDocId(uid);
1360
- const record = await this.backend.getDoc(docId);
1361
- if (!record) return null;
1362
- return this.applyMigration(record, docId);
1363
- }
1364
- async getEdge(aUid, axbType, bUid) {
1365
- const docId = computeEdgeDocId(aUid, axbType, bUid);
1366
- const record = await this.backend.getDoc(docId);
1367
- if (!record) return null;
1368
- return this.applyMigration(record, docId);
1369
- }
1370
- async edgeExists(aUid, axbType, bUid) {
1371
- const docId = computeEdgeDocId(aUid, axbType, bUid);
1372
- const record = await this.backend.getDoc(docId);
1373
- return record !== null;
1374
- }
1375
- async findEdges(params) {
1376
- const plan = buildEdgeQueryPlan(params);
1377
- let records;
1378
- if (plan.strategy === "get") {
1379
- const record = await this.backend.getDoc(plan.docId);
1380
- records = record ? [record] : [];
1381
- } else {
1382
- this.checkQuerySafety(plan.filters, params.allowCollectionScan);
1383
- records = await this.backend.query(plan.filters, plan.options);
1384
- }
1385
- return this.applyMigrations(records);
1386
- }
1387
- async findNodes(params) {
1388
- const plan = buildNodeQueryPlan(params);
1389
- let records;
1390
- if (plan.strategy === "get") {
1391
- const record = await this.backend.getDoc(plan.docId);
1392
- records = record ? [record] : [];
1393
- } else {
1394
- this.checkQuerySafety(plan.filters, params.allowCollectionScan);
1395
- records = await this.backend.query(plan.filters, plan.options);
1720
+ if (!this.registry || records.length === 0) return records;
1721
+ const results = await migrateRecords(records, this.registry, this.globalWriteBack);
1722
+ for (const result of results) {
1723
+ if (result.migrated && result.writeBack !== "off") {
1724
+ const docId = result.record.axbType === NODE_RELATION ? computeNodeDocId(result.record.aUid) : computeEdgeDocId(result.record.aUid, result.record.axbType, result.record.bUid);
1725
+ await this.backend.updateDoc(docId, {
1726
+ replaceData: result.record.data,
1727
+ v: result.record.v
1728
+ });
1729
+ }
1396
1730
  }
1397
- return this.applyMigrations(records);
1731
+ return results.map((r) => r.record);
1398
1732
  }
1399
- // ---------------------------------------------------------------------------
1400
- // GraphWriter
1401
- // ---------------------------------------------------------------------------
1402
1733
  async putNode(aType, uid, data) {
1403
- const registry = this.getRegistryForType(aType);
1404
- if (registry) {
1405
- registry.validate(aType, NODE_RELATION, aType, data, this.backend.scopePath);
1734
+ if (this.registry) {
1735
+ this.registry.validate(aType, NODE_RELATION, aType, data, this.scopePath);
1406
1736
  }
1407
- const backend = this.getBackendForType(aType);
1408
1737
  const docId = computeNodeDocId(uid);
1409
- const record = buildWritableNodeRecord3(aType, uid, data);
1410
- if (registry) {
1411
- const entry = registry.lookup(aType, NODE_RELATION, aType);
1738
+ const record = buildWritableNodeRecord2(aType, uid, data);
1739
+ if (this.registry) {
1740
+ const entry = this.registry.lookup(aType, NODE_RELATION, aType);
1412
1741
  if (entry?.schemaVersion && entry.schemaVersion > 0) {
1413
1742
  record.v = entry.schemaVersion;
1414
1743
  }
1415
1744
  }
1416
- await backend.setDoc(docId, record);
1745
+ await this.backend.setDoc(docId, record);
1417
1746
  }
1418
1747
  async putEdge(aType, aUid, axbType, bType, bUid, data) {
1419
- const registry = this.getRegistryForType(aType);
1420
- if (registry) {
1421
- registry.validate(aType, axbType, bType, data, this.backend.scopePath);
1748
+ if (this.registry) {
1749
+ this.registry.validate(aType, axbType, bType, data, this.scopePath);
1422
1750
  }
1423
- const backend = this.getBackendForType(aType);
1424
1751
  const docId = computeEdgeDocId(aUid, axbType, bUid);
1425
- const record = buildWritableEdgeRecord3(aType, aUid, axbType, bType, bUid, data);
1426
- if (registry) {
1427
- const entry = registry.lookup(aType, axbType, bType);
1752
+ const record = buildWritableEdgeRecord2(aType, aUid, axbType, bType, bUid, data);
1753
+ if (this.registry) {
1754
+ const entry = this.registry.lookup(aType, axbType, bType);
1428
1755
  if (entry?.schemaVersion && entry.schemaVersion > 0) {
1429
1756
  record.v = entry.schemaVersion;
1430
1757
  }
1431
1758
  }
1432
- await backend.setDoc(docId, record);
1759
+ await this.backend.setDoc(docId, record);
1433
1760
  }
1434
1761
  async updateNode(uid, data) {
1435
1762
  const docId = computeNodeDocId(uid);
@@ -1443,982 +1770,768 @@ var GraphClientImpl = class _GraphClientImpl {
1443
1770
  const docId = computeEdgeDocId(aUid, axbType, bUid);
1444
1771
  await this.backend.deleteDoc(docId);
1445
1772
  }
1446
- // ---------------------------------------------------------------------------
1447
- // Transactions & Batches
1448
- // ---------------------------------------------------------------------------
1449
- async runTransaction(fn) {
1450
- return this.backend.runTransaction(async (txBackend) => {
1451
- const graphTx = new GraphTransactionImpl(
1452
- txBackend,
1453
- this.getCombinedRegistry(),
1454
- this.scanProtection,
1455
- this.backend.scopePath,
1456
- this.globalWriteBack
1457
- );
1458
- return fn(graphTx);
1459
- });
1460
- }
1461
- batch() {
1462
- return new GraphBatchImpl(
1463
- this.backend.createBatch(),
1464
- this.getCombinedRegistry(),
1465
- this.backend.scopePath
1466
- );
1467
- }
1468
- // ---------------------------------------------------------------------------
1469
- // Subgraph
1470
- // ---------------------------------------------------------------------------
1471
- subgraph(parentNodeUid, name = "graph") {
1472
- if (!parentNodeUid || parentNodeUid.includes("/")) {
1473
- throw new FiregraphError(
1474
- `Invalid parentNodeUid for subgraph: "${parentNodeUid}". Must be a non-empty string without "/".`,
1475
- "INVALID_SUBGRAPH"
1476
- );
1477
- }
1478
- if (name.includes("/")) {
1479
- throw new FiregraphError(
1480
- `Subgraph name must not contain "/": got "${name}". Use chained .subgraph() calls for nested subgraphs.`,
1481
- "INVALID_SUBGRAPH"
1482
- );
1483
- }
1484
- const childBackend = this.backend.subgraph(parentNodeUid, name);
1485
- return new _GraphClientImpl(
1486
- childBackend,
1487
- {
1488
- registry: this.getCombinedRegistry(),
1489
- scanProtection: this.scanProtection,
1490
- migrationWriteBack: this.globalWriteBack,
1491
- migrationSandbox: this.migrationSandbox
1773
+ };
1774
+
1775
+ // src/client.ts
1776
+ var RESERVED_TYPE_NAMES = /* @__PURE__ */ new Set([META_NODE_TYPE, META_EDGE_TYPE]);
1777
+ function buildWritableNodeRecord3(aType, uid, data) {
1778
+ return { aType, aUid: uid, axbType: NODE_RELATION, bType: aType, bUid: uid, data };
1779
+ }
1780
+ function buildWritableEdgeRecord3(aType, aUid, axbType, bType, bUid, data) {
1781
+ return { aType, aUid, axbType, bType, bUid, data };
1782
+ }
1783
+ var GraphClientImpl = class _GraphClientImpl {
1784
+ constructor(backend, options, metaBackend) {
1785
+ this.backend = backend;
1786
+ this.globalWriteBack = options?.migrationWriteBack ?? "off";
1787
+ this.migrationSandbox = options?.migrationSandbox;
1788
+ if (options?.registryMode) {
1789
+ this.dynamicConfig = options.registryMode;
1790
+ this.bootstrapRegistry = createBootstrapRegistry();
1791
+ if (options.registry) {
1792
+ this.staticRegistry = options.registry;
1492
1793
  }
1493
- // Subgraphs do not have meta-backends; meta lives only at the root.
1494
- );
1495
- }
1496
- // ---------------------------------------------------------------------------
1497
- // Collection group query
1498
- // ---------------------------------------------------------------------------
1499
- async findEdgesGlobal(params, collectionName) {
1500
- if (!this.backend.findEdgesGlobal) {
1501
- throw new FiregraphError(
1502
- "findEdgesGlobal() is not supported by the current storage backend.",
1503
- "UNSUPPORTED_OPERATION"
1504
- );
1505
- }
1506
- const plan = buildEdgeQueryPlan(params);
1507
- if (plan.strategy === "get") {
1508
- throw new FiregraphError(
1509
- "findEdgesGlobal() requires a query, not a direct document lookup. Omit one of aUid/axbType/bUid to force a query strategy.",
1510
- "INVALID_QUERY"
1511
- );
1794
+ this.metaBackend = metaBackend;
1795
+ } else {
1796
+ this.staticRegistry = options?.registry;
1512
1797
  }
1513
- this.checkQuerySafety(plan.filters, params.allowCollectionScan);
1514
- const records = await this.backend.findEdgesGlobal(params, collectionName);
1515
- return this.applyMigrations(records);
1798
+ this.scanProtection = options?.scanProtection ?? "error";
1516
1799
  }
1800
+ scanProtection;
1801
+ // Static mode
1802
+ staticRegistry;
1803
+ // Dynamic mode
1804
+ dynamicConfig;
1805
+ bootstrapRegistry;
1806
+ dynamicRegistry;
1807
+ metaBackend;
1808
+ // Migration settings
1809
+ globalWriteBack;
1810
+ migrationSandbox;
1517
1811
  // ---------------------------------------------------------------------------
1518
- // Bulk operations
1812
+ // Backend access (exposed for traversal helpers and subgraph cloning)
1519
1813
  // ---------------------------------------------------------------------------
1520
- async removeNodeCascade(uid, options) {
1521
- return this.backend.removeNodeCascade(uid, this, options);
1814
+ /** @internal */
1815
+ getBackend() {
1816
+ return this.backend;
1522
1817
  }
1523
- async bulkRemoveEdges(params, options) {
1524
- return this.backend.bulkRemoveEdges(params, this, options);
1818
+ /**
1819
+ * Snapshot of the currently-effective registry. Returns the merged view
1820
+ * used for domain-type validation and migration — in dynamic mode this is
1821
+ * `dynamicRegistry ?? staticRegistry ?? bootstrapRegistry`, so callers see
1822
+ * updates after `reloadRegistry()` without having to re-resolve anything.
1823
+ *
1824
+ * Exposed for backends that need topology access during bulk operations
1825
+ * (e.g. the Cloudflare DO backend's cross-DO cascade). Not part of the
1826
+ * public `GraphClient` surface.
1827
+ *
1828
+ * @internal
1829
+ */
1830
+ getRegistrySnapshot() {
1831
+ return this.getCombinedRegistry();
1525
1832
  }
1526
1833
  // ---------------------------------------------------------------------------
1527
- // Dynamic registry methods
1834
+ // Registry routing
1528
1835
  // ---------------------------------------------------------------------------
1529
- async defineNodeType(name, jsonSchema, description, options) {
1530
- if (!this.dynamicConfig) {
1531
- throw new DynamicRegistryError(
1532
- 'defineNodeType() is only available in dynamic registry mode. Pass registryMode: { mode: "dynamic" } to createGraphClient().'
1533
- );
1534
- }
1535
- if (RESERVED_TYPE_NAMES.has(name)) {
1536
- throw new DynamicRegistryError(
1537
- `Cannot define type "${name}": this name is reserved for the meta-registry.`
1538
- );
1539
- }
1540
- if (this.staticRegistry?.lookup(name, NODE_RELATION, name)) {
1541
- throw new DynamicRegistryError(
1542
- `Cannot define node type "${name}": already defined in the static registry.`
1543
- );
1544
- }
1545
- const uid = generateDeterministicUid(META_NODE_TYPE, name);
1546
- const data = { name, jsonSchema };
1547
- if (description !== void 0) data.description = description;
1548
- if (options?.titleField !== void 0) data.titleField = options.titleField;
1549
- if (options?.subtitleField !== void 0) data.subtitleField = options.subtitleField;
1550
- if (options?.viewTemplate !== void 0) data.viewTemplate = options.viewTemplate;
1551
- if (options?.viewCss !== void 0) data.viewCss = options.viewCss;
1552
- if (options?.allowedIn !== void 0) data.allowedIn = options.allowedIn;
1553
- if (options?.migrationWriteBack !== void 0)
1554
- data.migrationWriteBack = options.migrationWriteBack;
1555
- if (options?.migrations !== void 0) {
1556
- data.migrations = await this.serializeMigrations(options.migrations);
1836
+ getRegistryForType(aType) {
1837
+ if (!this.dynamicConfig) return this.staticRegistry;
1838
+ if (aType === META_NODE_TYPE || aType === META_EDGE_TYPE) {
1839
+ return this.bootstrapRegistry;
1557
1840
  }
1558
- await this.putNode(META_NODE_TYPE, uid, data);
1841
+ return this.dynamicRegistry ?? this.staticRegistry ?? this.bootstrapRegistry;
1559
1842
  }
1560
- async defineEdgeType(name, topology, jsonSchema, description, options) {
1561
- if (!this.dynamicConfig) {
1562
- throw new DynamicRegistryError(
1563
- 'defineEdgeType() is only available in dynamic registry mode. Pass registryMode: { mode: "dynamic" } to createGraphClient().'
1564
- );
1565
- }
1566
- if (RESERVED_TYPE_NAMES.has(name)) {
1567
- throw new DynamicRegistryError(
1568
- `Cannot define type "${name}": this name is reserved for the meta-registry.`
1569
- );
1570
- }
1571
- if (this.staticRegistry) {
1572
- const fromTypes = Array.isArray(topology.from) ? topology.from : [topology.from];
1573
- const toTypes = Array.isArray(topology.to) ? topology.to : [topology.to];
1574
- for (const aType of fromTypes) {
1575
- for (const bType of toTypes) {
1576
- if (this.staticRegistry.lookup(aType, name, bType)) {
1577
- throw new DynamicRegistryError(
1578
- `Cannot define edge type "${name}" for (${aType}) -> (${bType}): already defined in the static registry.`
1579
- );
1580
- }
1581
- }
1582
- }
1583
- }
1584
- const uid = generateDeterministicUid(META_EDGE_TYPE, name);
1585
- const data = {
1586
- name,
1587
- from: topology.from,
1588
- to: topology.to
1589
- };
1590
- if (jsonSchema !== void 0) data.jsonSchema = jsonSchema;
1591
- if (topology.inverseLabel !== void 0) data.inverseLabel = topology.inverseLabel;
1592
- if (topology.targetGraph !== void 0) data.targetGraph = topology.targetGraph;
1593
- if (description !== void 0) data.description = description;
1594
- if (options?.titleField !== void 0) data.titleField = options.titleField;
1595
- if (options?.subtitleField !== void 0) data.subtitleField = options.subtitleField;
1596
- if (options?.viewTemplate !== void 0) data.viewTemplate = options.viewTemplate;
1597
- if (options?.viewCss !== void 0) data.viewCss = options.viewCss;
1598
- if (options?.allowedIn !== void 0) data.allowedIn = options.allowedIn;
1599
- if (options?.migrationWriteBack !== void 0)
1600
- data.migrationWriteBack = options.migrationWriteBack;
1601
- if (options?.migrations !== void 0) {
1602
- data.migrations = await this.serializeMigrations(options.migrations);
1843
+ getBackendForType(aType) {
1844
+ if (this.metaBackend && (aType === META_NODE_TYPE || aType === META_EDGE_TYPE)) {
1845
+ return this.metaBackend;
1603
1846
  }
1604
- await this.putNode(META_EDGE_TYPE, uid, data);
1847
+ return this.backend;
1605
1848
  }
1606
- async reloadRegistry() {
1607
- if (!this.dynamicConfig) {
1608
- throw new DynamicRegistryError(
1609
- 'reloadRegistry() is only available in dynamic registry mode. Pass registryMode: { mode: "dynamic" } to createGraphClient().'
1610
- );
1849
+ getCombinedRegistry() {
1850
+ if (!this.dynamicConfig) return this.staticRegistry;
1851
+ return this.dynamicRegistry ?? this.staticRegistry ?? this.bootstrapRegistry;
1852
+ }
1853
+ // ---------------------------------------------------------------------------
1854
+ // Query safety
1855
+ // ---------------------------------------------------------------------------
1856
+ checkQuerySafety(filters, allowCollectionScan) {
1857
+ if (allowCollectionScan || this.scanProtection === "off") return;
1858
+ const result = analyzeQuerySafety(filters);
1859
+ if (result.safe) return;
1860
+ if (this.scanProtection === "error") {
1861
+ throw new QuerySafetyError(result.reason);
1611
1862
  }
1612
- const reader = this.createMetaReader();
1613
- const dynamicOnly = await createRegistryFromGraph(reader, this.migrationSandbox);
1614
- if (this.staticRegistry) {
1615
- this.dynamicRegistry = createMergedRegistry(this.staticRegistry, dynamicOnly);
1616
- } else {
1617
- this.dynamicRegistry = dynamicOnly;
1863
+ console.warn(`[firegraph] Query safety warning: ${result.reason}`);
1864
+ }
1865
+ // ---------------------------------------------------------------------------
1866
+ // Migration helpers
1867
+ // ---------------------------------------------------------------------------
1868
+ async applyMigration(record, docId) {
1869
+ const registry = this.getCombinedRegistry();
1870
+ if (!registry) return record;
1871
+ const result = await migrateRecord(record, registry, this.globalWriteBack);
1872
+ if (result.migrated) {
1873
+ this.handleWriteBack(result, docId);
1618
1874
  }
1875
+ return result.record;
1619
1876
  }
1620
- async serializeMigrations(migrations) {
1621
- const result = migrations.map((m) => {
1622
- const source = typeof m.up === "function" ? m.up.toString() : m.up;
1623
- return { fromVersion: m.fromVersion, toVersion: m.toVersion, up: source };
1624
- });
1625
- await Promise.all(result.map((m) => precompileSource(m.up, this.migrationSandbox)));
1626
- return result;
1877
+ async applyMigrations(records) {
1878
+ const registry = this.getCombinedRegistry();
1879
+ if (!registry || records.length === 0) return records;
1880
+ const results = await migrateRecords(records, registry, this.globalWriteBack);
1881
+ for (const result of results) {
1882
+ if (result.migrated) {
1883
+ const docId = result.record.axbType === NODE_RELATION ? computeNodeDocId(result.record.aUid) : computeEdgeDocId(result.record.aUid, result.record.axbType, result.record.bUid);
1884
+ this.handleWriteBack(result, docId);
1885
+ }
1886
+ }
1887
+ return results.map((r) => r.record);
1627
1888
  }
1628
1889
  /**
1629
- * Build a `GraphReader` over the meta-backend. If meta lives in the same
1630
- * collection as the main backend, `this` is returned directly.
1890
+ * Fire-and-forget write-back for a migrated record. Both `'eager'` and
1891
+ * `'background'` are non-blocking; the difference is the log level on
1892
+ * failure. For synchronous write-back, use a transaction — see
1893
+ * `GraphTransactionImpl`.
1631
1894
  */
1632
- createMetaReader() {
1633
- if (!this.metaBackend) return this;
1634
- const backend = this.metaBackend;
1635
- const executeMetaQuery = (filters, options) => backend.query(filters, options);
1636
- return {
1637
- async getNode(uid) {
1638
- return backend.getDoc(computeNodeDocId(uid));
1639
- },
1640
- async getEdge(aUid, axbType, bUid) {
1641
- return backend.getDoc(computeEdgeDocId(aUid, axbType, bUid));
1642
- },
1643
- async edgeExists(aUid, axbType, bUid) {
1644
- const record = await backend.getDoc(computeEdgeDocId(aUid, axbType, bUid));
1645
- return record !== null;
1646
- },
1647
- async findEdges(params) {
1648
- const plan = buildEdgeQueryPlan(params);
1649
- if (plan.strategy === "get") {
1650
- const record = await backend.getDoc(plan.docId);
1651
- return record ? [record] : [];
1652
- }
1653
- return executeMetaQuery(plan.filters, plan.options);
1654
- },
1655
- async findNodes(params) {
1656
- const plan = buildNodeQueryPlan(params);
1657
- if (plan.strategy === "get") {
1658
- const record = await backend.getDoc(plan.docId);
1659
- return record ? [record] : [];
1895
+ handleWriteBack(result, docId) {
1896
+ if (result.writeBack === "off") return;
1897
+ const doWriteBack = async () => {
1898
+ try {
1899
+ await this.backend.updateDoc(docId, {
1900
+ replaceData: result.record.data,
1901
+ v: result.record.v
1902
+ });
1903
+ } catch (err) {
1904
+ const msg = `[firegraph] Migration write-back failed for ${docId}: ${err.message}`;
1905
+ if (result.writeBack === "eager") {
1906
+ console.error(msg);
1907
+ } else {
1908
+ console.warn(msg);
1660
1909
  }
1661
- return executeMetaQuery(plan.filters, plan.options);
1662
1910
  }
1663
1911
  };
1912
+ void doWriteBack();
1664
1913
  }
1665
- };
1666
- function createGraphClientFromBackend(backend, options, metaBackend) {
1667
- return new GraphClientImpl(backend, options, metaBackend);
1668
- }
1669
-
1670
- // src/timestamp.ts
1671
- var GraphTimestampImpl = class _GraphTimestampImpl {
1672
- constructor(seconds, nanoseconds) {
1673
- this.seconds = seconds;
1674
- this.nanoseconds = nanoseconds;
1675
- }
1676
- toDate() {
1677
- return new Date(this.toMillis());
1678
- }
1679
- toMillis() {
1680
- return this.seconds * 1e3 + Math.floor(this.nanoseconds / 1e6);
1914
+ // ---------------------------------------------------------------------------
1915
+ // GraphReader
1916
+ // ---------------------------------------------------------------------------
1917
+ async getNode(uid) {
1918
+ const docId = computeNodeDocId(uid);
1919
+ const record = await this.backend.getDoc(docId);
1920
+ if (!record) return null;
1921
+ return this.applyMigration(record, docId);
1681
1922
  }
1682
- toJSON() {
1683
- return { seconds: this.seconds, nanoseconds: this.nanoseconds };
1923
+ async getEdge(aUid, axbType, bUid) {
1924
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
1925
+ const record = await this.backend.getDoc(docId);
1926
+ if (!record) return null;
1927
+ return this.applyMigration(record, docId);
1684
1928
  }
1685
- static fromMillis(ms) {
1686
- const seconds = Math.floor(ms / 1e3);
1687
- const nanoseconds = (ms - seconds * 1e3) * 1e6;
1688
- return new _GraphTimestampImpl(seconds, nanoseconds);
1929
+ async edgeExists(aUid, axbType, bUid) {
1930
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
1931
+ const record = await this.backend.getDoc(docId);
1932
+ return record !== null;
1689
1933
  }
1690
- static now() {
1691
- return _GraphTimestampImpl.fromMillis(Date.now());
1934
+ async findEdges(params) {
1935
+ const plan = buildEdgeQueryPlan(params);
1936
+ let records;
1937
+ if (plan.strategy === "get") {
1938
+ const record = await this.backend.getDoc(plan.docId);
1939
+ records = record ? [record] : [];
1940
+ } else {
1941
+ this.checkQuerySafety(plan.filters, params.allowCollectionScan);
1942
+ records = await this.backend.query(plan.filters, plan.options);
1943
+ }
1944
+ return this.applyMigrations(records);
1692
1945
  }
1693
- };
1694
-
1695
- // src/internal/sqlite-schema.ts
1696
- var FIELD_TO_COLUMN = {
1697
- aType: "a_type",
1698
- aUid: "a_uid",
1699
- axbType: "axb_type",
1700
- bType: "b_type",
1701
- bUid: "b_uid",
1702
- v: "v",
1703
- createdAt: "created_at",
1704
- updatedAt: "updated_at"
1705
- };
1706
- function buildSchemaStatements(table) {
1707
- const t = quoteIdent(table);
1708
- return [
1709
- `CREATE TABLE IF NOT EXISTS ${t} (
1710
- doc_id TEXT NOT NULL,
1711
- scope TEXT NOT NULL DEFAULT '',
1712
- a_type TEXT NOT NULL,
1713
- a_uid TEXT NOT NULL,
1714
- axb_type TEXT NOT NULL,
1715
- b_type TEXT NOT NULL,
1716
- b_uid TEXT NOT NULL,
1717
- data TEXT NOT NULL,
1718
- v INTEGER,
1719
- created_at INTEGER NOT NULL,
1720
- updated_at INTEGER NOT NULL,
1721
- PRIMARY KEY (scope, doc_id)
1722
- )`,
1723
- `CREATE INDEX IF NOT EXISTS ${quoteIdent(`${table}_idx_scope_a_uid`)} ON ${t}(scope, a_uid)`,
1724
- `CREATE INDEX IF NOT EXISTS ${quoteIdent(`${table}_idx_scope_b_uid`)} ON ${t}(scope, b_uid)`,
1725
- `CREATE INDEX IF NOT EXISTS ${quoteIdent(`${table}_idx_scope_axb_type_b_uid`)} ON ${t}(scope, axb_type, b_uid)`,
1726
- `CREATE INDEX IF NOT EXISTS ${quoteIdent(`${table}_idx_scope_a_type`)} ON ${t}(scope, a_type)`,
1727
- `CREATE INDEX IF NOT EXISTS ${quoteIdent(`${table}_idx_scope_b_type`)} ON ${t}(scope, b_type)`,
1728
- `CREATE INDEX IF NOT EXISTS ${quoteIdent(`${table}_idx_doc_id`)} ON ${t}(doc_id)`
1729
- ];
1730
- }
1731
- function quoteIdent(name) {
1732
- validateTableName(name);
1733
- return `"${name}"`;
1734
- }
1735
- function validateTableName(name) {
1736
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
1737
- throw new Error(`Invalid SQL identifier: ${name}. Must match /^[A-Za-z_][A-Za-z0-9_]*$/.`);
1946
+ async findNodes(params) {
1947
+ const plan = buildNodeQueryPlan(params);
1948
+ let records;
1949
+ if (plan.strategy === "get") {
1950
+ const record = await this.backend.getDoc(plan.docId);
1951
+ records = record ? [record] : [];
1952
+ } else {
1953
+ this.checkQuerySafety(plan.filters, params.allowCollectionScan);
1954
+ records = await this.backend.query(plan.filters, plan.options);
1955
+ }
1956
+ return this.applyMigrations(records);
1738
1957
  }
1739
- }
1740
-
1741
- // src/internal/sqlite-sql.ts
1742
- function compileFieldRef(field) {
1743
- const column = FIELD_TO_COLUMN[field];
1744
- if (column) {
1745
- return { expr: quoteIdent(column) };
1958
+ // ---------------------------------------------------------------------------
1959
+ // GraphWriter
1960
+ // ---------------------------------------------------------------------------
1961
+ async putNode(aType, uid, data) {
1962
+ const registry = this.getRegistryForType(aType);
1963
+ if (registry) {
1964
+ registry.validate(aType, NODE_RELATION, aType, data, this.backend.scopePath);
1965
+ }
1966
+ const backend = this.getBackendForType(aType);
1967
+ const docId = computeNodeDocId(uid);
1968
+ const record = buildWritableNodeRecord3(aType, uid, data);
1969
+ if (registry) {
1970
+ const entry = registry.lookup(aType, NODE_RELATION, aType);
1971
+ if (entry?.schemaVersion && entry.schemaVersion > 0) {
1972
+ record.v = entry.schemaVersion;
1973
+ }
1974
+ }
1975
+ await backend.setDoc(docId, record);
1746
1976
  }
1747
- if (field.startsWith("data.")) {
1748
- const key = field.slice(5);
1749
- validateJsonPathKey(key);
1750
- return { expr: 'json_extract("data", ?)', pathParam: `$.${key}` };
1977
+ async putEdge(aType, aUid, axbType, bType, bUid, data) {
1978
+ const registry = this.getRegistryForType(aType);
1979
+ if (registry) {
1980
+ registry.validate(aType, axbType, bType, data, this.backend.scopePath);
1981
+ }
1982
+ const backend = this.getBackendForType(aType);
1983
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
1984
+ const record = buildWritableEdgeRecord3(aType, aUid, axbType, bType, bUid, data);
1985
+ if (registry) {
1986
+ const entry = registry.lookup(aType, axbType, bType);
1987
+ if (entry?.schemaVersion && entry.schemaVersion > 0) {
1988
+ record.v = entry.schemaVersion;
1989
+ }
1990
+ }
1991
+ await backend.setDoc(docId, record);
1751
1992
  }
1752
- if (field === "data") {
1753
- return { expr: 'json_extract("data", ?)', pathParam: "$" };
1993
+ async updateNode(uid, data) {
1994
+ const docId = computeNodeDocId(uid);
1995
+ await this.backend.updateDoc(docId, { dataFields: data });
1754
1996
  }
1755
- throw new FiregraphError(`SQLite backend cannot resolve filter field: ${field}`, "INVALID_QUERY");
1756
- }
1757
- var FIRESTORE_TYPE_NAMES = /* @__PURE__ */ new Set([
1758
- "Timestamp",
1759
- "GeoPoint",
1760
- "VectorValue",
1761
- "DocumentReference",
1762
- "FieldValue"
1763
- ]);
1764
- function isFirestoreSpecialType(value) {
1765
- const ctorName = value.constructor?.name;
1766
- if (ctorName && FIRESTORE_TYPE_NAMES.has(ctorName)) return ctorName;
1767
- return null;
1768
- }
1769
- function bindValue(value) {
1770
- if (value === null || value === void 0) return null;
1771
- if (typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") {
1772
- return value;
1997
+ async removeNode(uid) {
1998
+ const docId = computeNodeDocId(uid);
1999
+ await this.backend.deleteDoc(docId);
1773
2000
  }
1774
- if (value instanceof Date) return value.getTime();
1775
- if (typeof value === "object") {
1776
- const firestoreType = isFirestoreSpecialType(value);
1777
- if (firestoreType) {
1778
- throw new FiregraphError(
1779
- `SQLite backend cannot bind a Firestore ${firestoreType} value \u2014 JSON serialization would silently drop fields and the resulting bind would never match a stored row. Convert to a primitive (e.g. \`ts.toMillis()\` for Timestamp) before filtering or updating.`,
1780
- "INVALID_QUERY"
1781
- );
1782
- }
1783
- return JSON.stringify(value);
2001
+ async removeEdge(aUid, axbType, bUid) {
2002
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
2003
+ await this.backend.deleteDoc(docId);
1784
2004
  }
1785
- return String(value);
1786
- }
1787
- var JSON_PATH_KEY_RE = /^[A-Za-z_][A-Za-z0-9_-]*$/;
1788
- function validateJsonPathKey(key) {
1789
- if (key.length === 0) {
1790
- throw new FiregraphError(
1791
- "SQLite backend: empty JSON path component is not allowed",
1792
- "INVALID_QUERY"
1793
- );
2005
+ // ---------------------------------------------------------------------------
2006
+ // Transactions & Batches
2007
+ // ---------------------------------------------------------------------------
2008
+ async runTransaction(fn) {
2009
+ return this.backend.runTransaction(async (txBackend) => {
2010
+ const graphTx = new GraphTransactionImpl(
2011
+ txBackend,
2012
+ this.getCombinedRegistry(),
2013
+ this.scanProtection,
2014
+ this.backend.scopePath,
2015
+ this.globalWriteBack
2016
+ );
2017
+ return fn(graphTx);
2018
+ });
1794
2019
  }
1795
- if (!JSON_PATH_KEY_RE.test(key)) {
1796
- throw new FiregraphError(
1797
- `SQLite backend: data field path component "${key}" is not a safe JSON-path identifier. Allowed pattern: /^[A-Za-z_][A-Za-z0-9_-]*$/. Use replaceData (full-data overwrite) for keys with reserved characters (whitespace, dots, brackets, quotes, etc.).`,
1798
- "INVALID_QUERY"
2020
+ batch() {
2021
+ return new GraphBatchImpl(
2022
+ this.backend.createBatch(),
2023
+ this.getCombinedRegistry(),
2024
+ this.backend.scopePath
1799
2025
  );
1800
2026
  }
1801
- }
1802
- function compileFilter(filter, params) {
1803
- const { expr, pathParam } = compileFieldRef(filter.field);
1804
- if (pathParam !== void 0) params.push(pathParam);
1805
- switch (filter.op) {
1806
- case "==":
1807
- params.push(bindValue(filter.value));
1808
- return `${expr} = ?`;
1809
- case "!=":
1810
- params.push(bindValue(filter.value));
1811
- return `${expr} != ?`;
1812
- case "<":
1813
- params.push(bindValue(filter.value));
1814
- return `${expr} < ?`;
1815
- case "<=":
1816
- params.push(bindValue(filter.value));
1817
- return `${expr} <= ?`;
1818
- case ">":
1819
- params.push(bindValue(filter.value));
1820
- return `${expr} > ?`;
1821
- case ">=":
1822
- params.push(bindValue(filter.value));
1823
- return `${expr} >= ?`;
1824
- case "in": {
1825
- const values = asArray(filter.value, "in");
1826
- const placeholders = values.map(() => "?").join(", ");
1827
- for (const v of values) params.push(bindValue(v));
1828
- return `${expr} IN (${placeholders})`;
1829
- }
1830
- case "not-in": {
1831
- const values = asArray(filter.value, "not-in");
1832
- const placeholders = values.map(() => "?").join(", ");
1833
- for (const v of values) params.push(bindValue(v));
1834
- return `${expr} NOT IN (${placeholders})`;
2027
+ // ---------------------------------------------------------------------------
2028
+ // Subgraph
2029
+ // ---------------------------------------------------------------------------
2030
+ subgraph(parentNodeUid, name = "graph") {
2031
+ if (!parentNodeUid || parentNodeUid.includes("/")) {
2032
+ throw new FiregraphError(
2033
+ `Invalid parentNodeUid for subgraph: "${parentNodeUid}". Must be a non-empty string without "/".`,
2034
+ "INVALID_SUBGRAPH"
2035
+ );
1835
2036
  }
1836
- case "array-contains": {
1837
- params.push(bindValue(filter.value));
1838
- return `EXISTS (SELECT 1 FROM json_each(${expr}) WHERE value = ?)`;
2037
+ if (name.includes("/")) {
2038
+ throw new FiregraphError(
2039
+ `Subgraph name must not contain "/": got "${name}". Use chained .subgraph() calls for nested subgraphs.`,
2040
+ "INVALID_SUBGRAPH"
2041
+ );
1839
2042
  }
1840
- case "array-contains-any": {
1841
- const values = asArray(filter.value, "array-contains-any");
1842
- const placeholders = values.map(() => "?").join(", ");
1843
- for (const v of values) params.push(bindValue(v));
1844
- return `EXISTS (SELECT 1 FROM json_each(${expr}) WHERE value IN (${placeholders}))`;
2043
+ const childBackend = this.backend.subgraph(parentNodeUid, name);
2044
+ return new _GraphClientImpl(
2045
+ childBackend,
2046
+ {
2047
+ registry: this.getCombinedRegistry(),
2048
+ scanProtection: this.scanProtection,
2049
+ migrationWriteBack: this.globalWriteBack,
2050
+ migrationSandbox: this.migrationSandbox
2051
+ }
2052
+ // Subgraphs do not have meta-backends; meta lives only at the root.
2053
+ );
2054
+ }
2055
+ // ---------------------------------------------------------------------------
2056
+ // Collection group query
2057
+ // ---------------------------------------------------------------------------
2058
+ async findEdgesGlobal(params, collectionName) {
2059
+ if (!this.backend.findEdgesGlobal) {
2060
+ throw new FiregraphError(
2061
+ "findEdgesGlobal() is not supported by the current storage backend.",
2062
+ "UNSUPPORTED_OPERATION"
2063
+ );
1845
2064
  }
1846
- default:
2065
+ const plan = buildEdgeQueryPlan(params);
2066
+ if (plan.strategy === "get") {
1847
2067
  throw new FiregraphError(
1848
- `SQLite backend does not support filter operator: ${String(filter.op)}`,
2068
+ "findEdgesGlobal() requires a query, not a direct document lookup. Omit one of aUid/axbType/bUid to force a query strategy.",
1849
2069
  "INVALID_QUERY"
1850
2070
  );
2071
+ }
2072
+ this.checkQuerySafety(plan.filters, params.allowCollectionScan);
2073
+ const records = await this.backend.findEdgesGlobal(params, collectionName);
2074
+ return this.applyMigrations(records);
1851
2075
  }
1852
- }
1853
- function asArray(value, op) {
1854
- if (!Array.isArray(value) || value.length === 0) {
1855
- throw new FiregraphError(`Operator "${op}" requires a non-empty array value`, "INVALID_QUERY");
1856
- }
1857
- return value;
1858
- }
1859
- function compileOrderBy(options, params) {
1860
- if (!options?.orderBy) return "";
1861
- const { field, direction } = options.orderBy;
1862
- const { expr, pathParam } = compileFieldRef(field);
1863
- if (pathParam !== void 0) params.push(pathParam);
1864
- const dir = direction === "desc" ? "DESC" : "ASC";
1865
- return ` ORDER BY ${expr} ${dir}`;
1866
- }
1867
- function compileLimit(options, params) {
1868
- if (options?.limit === void 0) return "";
1869
- params.push(options.limit);
1870
- return ` LIMIT ?`;
1871
- }
1872
- function compileSelect(table, scope, filters, options) {
1873
- const params = [];
1874
- const conditions = ['"scope" = ?'];
1875
- params.push(scope);
1876
- for (const f of filters) {
1877
- conditions.push(compileFilter(f, params));
2076
+ // ---------------------------------------------------------------------------
2077
+ // Bulk operations
2078
+ // ---------------------------------------------------------------------------
2079
+ async removeNodeCascade(uid, options) {
2080
+ return this.backend.removeNodeCascade(uid, this, options);
1878
2081
  }
1879
- let sql = `SELECT * FROM ${quoteIdent(table)} WHERE ${conditions.join(" AND ")}`;
1880
- const orderClause = compileOrderBy(options, params);
1881
- sql += orderClause;
1882
- sql += compileLimit(options, params);
1883
- return { sql, params };
1884
- }
1885
- function compileSelectGlobal(table, filters, options, scopeNameFilter) {
1886
- if (filters.length === 0) {
1887
- throw new FiregraphError(
1888
- "compileSelectGlobal requires at least one filter \u2014 refusing to issue an unbounded SELECT.",
1889
- "INVALID_QUERY"
1890
- );
2082
+ async bulkRemoveEdges(params, options) {
2083
+ return this.backend.bulkRemoveEdges(params, this, options);
1891
2084
  }
1892
- const params = [];
1893
- const conditions = [];
1894
- if (scopeNameFilter) {
1895
- if (scopeNameFilter.isRoot) {
1896
- conditions.push(`"scope" = ?`);
1897
- params.push("");
1898
- } else {
1899
- conditions.push(`"scope" LIKE ? ESCAPE '\\'`);
1900
- params.push(`%/${escapeLike(scopeNameFilter.name)}`);
2085
+ // ---------------------------------------------------------------------------
2086
+ // Dynamic registry methods
2087
+ // ---------------------------------------------------------------------------
2088
+ async defineNodeType(name, jsonSchema, description, options) {
2089
+ if (!this.dynamicConfig) {
2090
+ throw new DynamicRegistryError(
2091
+ 'defineNodeType() is only available in dynamic registry mode. Pass registryMode: { mode: "dynamic" } to createGraphClient().'
2092
+ );
1901
2093
  }
2094
+ if (RESERVED_TYPE_NAMES.has(name)) {
2095
+ throw new DynamicRegistryError(
2096
+ `Cannot define type "${name}": this name is reserved for the meta-registry.`
2097
+ );
2098
+ }
2099
+ if (this.staticRegistry?.lookup(name, NODE_RELATION, name)) {
2100
+ throw new DynamicRegistryError(
2101
+ `Cannot define node type "${name}": already defined in the static registry.`
2102
+ );
2103
+ }
2104
+ const uid = generateDeterministicUid(META_NODE_TYPE, name);
2105
+ const data = { name, jsonSchema };
2106
+ if (description !== void 0) data.description = description;
2107
+ if (options?.titleField !== void 0) data.titleField = options.titleField;
2108
+ if (options?.subtitleField !== void 0) data.subtitleField = options.subtitleField;
2109
+ if (options?.viewTemplate !== void 0) data.viewTemplate = options.viewTemplate;
2110
+ if (options?.viewCss !== void 0) data.viewCss = options.viewCss;
2111
+ if (options?.allowedIn !== void 0) data.allowedIn = options.allowedIn;
2112
+ if (options?.migrationWriteBack !== void 0)
2113
+ data.migrationWriteBack = options.migrationWriteBack;
2114
+ if (options?.migrations !== void 0) {
2115
+ data.migrations = await this.serializeMigrations(options.migrations);
2116
+ }
2117
+ await this.putNode(META_NODE_TYPE, uid, data);
1902
2118
  }
1903
- for (const f of filters) {
1904
- conditions.push(compileFilter(f, params));
1905
- }
1906
- const sql = `SELECT * FROM ${quoteIdent(table)} WHERE ${conditions.join(" AND ")}` + compileOrderBy(options, params) + compileLimit(options, params);
1907
- return { sql, params };
1908
- }
1909
- function compileSelectByDocId(table, scope, docId) {
1910
- return {
1911
- sql: `SELECT * FROM ${quoteIdent(table)} WHERE "scope" = ? AND "doc_id" = ? LIMIT 1`,
1912
- params: [scope, docId]
1913
- };
1914
- }
1915
- function compileSet(table, scope, docId, record, nowMillis) {
1916
- const sql = `INSERT OR REPLACE INTO ${quoteIdent(table)} (
1917
- doc_id, scope, a_type, a_uid, axb_type, b_type, b_uid, data, v, created_at, updated_at
1918
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
1919
- const params = [
1920
- docId,
1921
- scope,
1922
- record.aType,
1923
- record.aUid,
1924
- record.axbType,
1925
- record.bType,
1926
- record.bUid,
1927
- JSON.stringify(record.data ?? {}),
1928
- record.v ?? null,
1929
- nowMillis,
1930
- nowMillis
1931
- ];
1932
- return { sql, params };
1933
- }
1934
- function compileUpdate(table, scope, docId, update, nowMillis) {
1935
- const setClauses = [];
1936
- const params = [];
1937
- if (update.replaceData) {
1938
- setClauses.push(`"data" = ?`);
1939
- params.push(JSON.stringify(update.replaceData));
1940
- } else if (update.dataFields && Object.keys(update.dataFields).length > 0) {
1941
- const entries = Object.entries(update.dataFields);
1942
- const pathArgs = entries.map(() => `?, ?`).join(", ");
1943
- setClauses.push(`"data" = json_set(COALESCE("data", '{}'), ${pathArgs})`);
1944
- for (const [k, v] of entries) {
1945
- validateJsonPathKey(k);
1946
- params.push(`$.${k}`);
1947
- params.push(bindValue(v));
2119
+ async defineEdgeType(name, topology, jsonSchema, description, options) {
2120
+ if (!this.dynamicConfig) {
2121
+ throw new DynamicRegistryError(
2122
+ 'defineEdgeType() is only available in dynamic registry mode. Pass registryMode: { mode: "dynamic" } to createGraphClient().'
2123
+ );
2124
+ }
2125
+ if (RESERVED_TYPE_NAMES.has(name)) {
2126
+ throw new DynamicRegistryError(
2127
+ `Cannot define type "${name}": this name is reserved for the meta-registry.`
2128
+ );
2129
+ }
2130
+ if (this.staticRegistry) {
2131
+ const fromTypes = Array.isArray(topology.from) ? topology.from : [topology.from];
2132
+ const toTypes = Array.isArray(topology.to) ? topology.to : [topology.to];
2133
+ for (const aType of fromTypes) {
2134
+ for (const bType of toTypes) {
2135
+ if (this.staticRegistry.lookup(aType, name, bType)) {
2136
+ throw new DynamicRegistryError(
2137
+ `Cannot define edge type "${name}" for (${aType}) -> (${bType}): already defined in the static registry.`
2138
+ );
2139
+ }
2140
+ }
2141
+ }
2142
+ }
2143
+ const uid = generateDeterministicUid(META_EDGE_TYPE, name);
2144
+ const data = {
2145
+ name,
2146
+ from: topology.from,
2147
+ to: topology.to
2148
+ };
2149
+ if (jsonSchema !== void 0) data.jsonSchema = jsonSchema;
2150
+ if (topology.inverseLabel !== void 0) data.inverseLabel = topology.inverseLabel;
2151
+ if (topology.targetGraph !== void 0) data.targetGraph = topology.targetGraph;
2152
+ if (description !== void 0) data.description = description;
2153
+ if (options?.titleField !== void 0) data.titleField = options.titleField;
2154
+ if (options?.subtitleField !== void 0) data.subtitleField = options.subtitleField;
2155
+ if (options?.viewTemplate !== void 0) data.viewTemplate = options.viewTemplate;
2156
+ if (options?.viewCss !== void 0) data.viewCss = options.viewCss;
2157
+ if (options?.allowedIn !== void 0) data.allowedIn = options.allowedIn;
2158
+ if (options?.migrationWriteBack !== void 0)
2159
+ data.migrationWriteBack = options.migrationWriteBack;
2160
+ if (options?.migrations !== void 0) {
2161
+ data.migrations = await this.serializeMigrations(options.migrations);
1948
2162
  }
2163
+ await this.putNode(META_EDGE_TYPE, uid, data);
1949
2164
  }
1950
- if (update.v !== void 0) {
1951
- setClauses.push(`"v" = ?`);
1952
- params.push(update.v);
2165
+ async reloadRegistry() {
2166
+ if (!this.dynamicConfig) {
2167
+ throw new DynamicRegistryError(
2168
+ 'reloadRegistry() is only available in dynamic registry mode. Pass registryMode: { mode: "dynamic" } to createGraphClient().'
2169
+ );
2170
+ }
2171
+ const reader = this.createMetaReader();
2172
+ const dynamicOnly = await createRegistryFromGraph(reader, this.migrationSandbox);
2173
+ if (this.staticRegistry) {
2174
+ this.dynamicRegistry = createMergedRegistry(this.staticRegistry, dynamicOnly);
2175
+ } else {
2176
+ this.dynamicRegistry = dynamicOnly;
2177
+ }
1953
2178
  }
1954
- setClauses.push(`"updated_at" = ?`);
1955
- params.push(nowMillis);
1956
- params.push(scope, docId);
1957
- return {
1958
- sql: `UPDATE ${quoteIdent(table)} SET ${setClauses.join(", ")} WHERE "scope" = ? AND "doc_id" = ?`,
1959
- params
1960
- };
1961
- }
1962
- function compileDelete(table, scope, docId) {
1963
- return {
1964
- sql: `DELETE FROM ${quoteIdent(table)} WHERE "scope" = ? AND "doc_id" = ?`,
1965
- params: [scope, docId]
1966
- };
1967
- }
1968
- function compileDeleteScopePrefix(table, scopePrefix) {
1969
- const escaped = escapeLike(scopePrefix);
1970
- return {
1971
- sql: `DELETE FROM ${quoteIdent(table)} WHERE "scope" LIKE ? ESCAPE '\\'`,
1972
- params: [`${escaped}/%`]
1973
- };
1974
- }
1975
- function compileCountScopePrefix(table, scopePrefix) {
1976
- const escaped = escapeLike(scopePrefix);
1977
- return {
1978
- sql: `SELECT COUNT(*) AS n FROM ${quoteIdent(table)} WHERE "scope" LIKE ? ESCAPE '\\'`,
1979
- params: [`${escaped}/%`]
1980
- };
1981
- }
1982
- function escapeLike(value) {
1983
- return value.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
1984
- }
1985
- function rowToRecord(row) {
1986
- const dataString = row.data;
1987
- const data = dataString ? JSON.parse(dataString) : {};
1988
- const createdMs = toMillis(row.created_at);
1989
- const updatedMs = toMillis(row.updated_at);
1990
- const record = {
1991
- aType: row.a_type,
1992
- aUid: row.a_uid,
1993
- axbType: row.axb_type,
1994
- bType: row.b_type,
1995
- bUid: row.b_uid,
1996
- data,
1997
- createdAt: GraphTimestampImpl.fromMillis(createdMs),
1998
- updatedAt: GraphTimestampImpl.fromMillis(updatedMs)
1999
- };
2000
- if (row.v !== null && row.v !== void 0) {
2001
- record.v = Number(row.v);
2179
+ async serializeMigrations(migrations) {
2180
+ const result = migrations.map((m) => {
2181
+ const source = typeof m.up === "function" ? m.up.toString() : m.up;
2182
+ return { fromVersion: m.fromVersion, toVersion: m.toVersion, up: source };
2183
+ });
2184
+ await Promise.all(result.map((m) => precompileSource(m.up, this.migrationSandbox)));
2185
+ return result;
2002
2186
  }
2003
- return record;
2004
- }
2005
- function toMillis(value) {
2006
- if (typeof value === "number") return value;
2007
- if (typeof value === "bigint") return Number(value);
2008
- if (typeof value === "string") return Number(value);
2009
- return 0;
2187
+ /**
2188
+ * Build a `GraphReader` over the meta-backend. If meta lives in the same
2189
+ * collection as the main backend, `this` is returned directly.
2190
+ */
2191
+ createMetaReader() {
2192
+ if (!this.metaBackend) return this;
2193
+ const backend = this.metaBackend;
2194
+ const executeMetaQuery = (filters, options) => backend.query(filters, options);
2195
+ return {
2196
+ async getNode(uid) {
2197
+ return backend.getDoc(computeNodeDocId(uid));
2198
+ },
2199
+ async getEdge(aUid, axbType, bUid) {
2200
+ return backend.getDoc(computeEdgeDocId(aUid, axbType, bUid));
2201
+ },
2202
+ async edgeExists(aUid, axbType, bUid) {
2203
+ const record = await backend.getDoc(computeEdgeDocId(aUid, axbType, bUid));
2204
+ return record !== null;
2205
+ },
2206
+ async findEdges(params) {
2207
+ const plan = buildEdgeQueryPlan(params);
2208
+ if (plan.strategy === "get") {
2209
+ const record = await backend.getDoc(plan.docId);
2210
+ return record ? [record] : [];
2211
+ }
2212
+ return executeMetaQuery(plan.filters, plan.options);
2213
+ },
2214
+ async findNodes(params) {
2215
+ const plan = buildNodeQueryPlan(params);
2216
+ if (plan.strategy === "get") {
2217
+ const record = await backend.getDoc(plan.docId);
2218
+ return record ? [record] : [];
2219
+ }
2220
+ return executeMetaQuery(plan.filters, plan.options);
2221
+ }
2222
+ };
2223
+ }
2224
+ };
2225
+ function createGraphClientFromBackend(backend, options, metaBackend) {
2226
+ return new GraphClientImpl(backend, options, metaBackend);
2010
2227
  }
2011
2228
 
2012
- // src/internal/sqlite-backend.ts
2013
- var DEFAULT_MAX_RETRIES = 3;
2014
- var BASE_RETRY_DELAY_MS = 200;
2015
- var MAX_RETRY_DELAY_MS = 5e3;
2016
- function sleep(ms) {
2017
- return new Promise((resolve) => setTimeout(resolve, ms));
2018
- }
2019
- function minDefined(a, b) {
2020
- if (a === void 0) return b;
2021
- if (b === void 0) return a;
2022
- return Math.min(a, b);
2023
- }
2024
- function chunkStatements(statements, maxStatements, maxParams) {
2025
- const stmtCap = maxStatements && maxStatements > 0 && Number.isFinite(maxStatements) ? Math.floor(maxStatements) : Infinity;
2026
- const paramCap = maxParams && maxParams > 0 && Number.isFinite(maxParams) ? Math.floor(maxParams) : Infinity;
2027
- if (stmtCap === Infinity && paramCap === Infinity) {
2028
- return [statements];
2029
- }
2030
- const chunks = [];
2031
- let current = [];
2032
- let currentParamCount = 0;
2033
- for (const stmt of statements) {
2034
- const stmtParams = stmt.params.length;
2035
- const wouldExceedStmt = current.length + 1 > stmtCap;
2036
- const wouldExceedParam = currentParamCount + stmtParams > paramCap;
2037
- if (current.length > 0 && (wouldExceedStmt || wouldExceedParam)) {
2038
- chunks.push(current);
2039
- current = [];
2040
- currentParamCount = 0;
2041
- }
2042
- current.push(stmt);
2043
- currentParamCount += stmtParams;
2044
- }
2045
- if (current.length > 0) chunks.push(current);
2046
- return chunks;
2047
- }
2048
- var SqliteTransactionBackendImpl = class {
2049
- constructor(tx, tableName, storageScope) {
2050
- this.tx = tx;
2051
- this.tableName = tableName;
2052
- this.storageScope = storageScope;
2053
- }
2054
- async getDoc(docId) {
2055
- const stmt = compileSelectByDocId(this.tableName, this.storageScope, docId);
2056
- const rows = await this.tx.all(stmt.sql, stmt.params);
2057
- return rows.length === 0 ? null : rowToRecord(rows[0]);
2058
- }
2059
- async query(filters, options) {
2060
- const stmt = compileSelect(this.tableName, this.storageScope, filters, options);
2061
- const rows = await this.tx.all(stmt.sql, stmt.params);
2062
- return rows.map(rowToRecord);
2229
+ // src/cloudflare/client.ts
2230
+ function createDOClient(namespace, rootKey, options = {}) {
2231
+ if (!rootKey || typeof rootKey !== "string") {
2232
+ throw new FiregraphError(
2233
+ `createDOClient: rootKey must be a non-empty string, got ${JSON.stringify(rootKey)}.`,
2234
+ "INVALID_ARGUMENT"
2235
+ );
2063
2236
  }
2064
- async setDoc(docId, record) {
2065
- const stmt = compileSet(this.tableName, this.storageScope, docId, record, Date.now());
2066
- await this.tx.run(stmt.sql, stmt.params);
2237
+ if (rootKey.includes("/")) {
2238
+ throw new FiregraphError(
2239
+ `createDOClient: rootKey must not contain "/". Got: "${rootKey}".`,
2240
+ "INVALID_ARGUMENT"
2241
+ );
2067
2242
  }
2068
- async updateDoc(docId, update) {
2069
- const stmt = compileUpdate(this.tableName, this.storageScope, docId, update, Date.now());
2070
- const sqlWithReturning = `${stmt.sql} RETURNING "doc_id"`;
2071
- const rows = await this.tx.all(sqlWithReturning, stmt.params);
2072
- if (rows.length === 0) {
2243
+ let client;
2244
+ const registryAccessor = () => {
2245
+ if (!client) {
2073
2246
  throw new FiregraphError(
2074
- `updateDoc: no document found for doc_id=${docId} (scope=${this.storageScope})`,
2075
- "NOT_FOUND"
2247
+ "createDOClient: registryAccessor fired before the client was assigned. This indicates a programming error in the DO backend \u2014 the accessor must only be invoked lazily from `removeNodeCascade`, never synchronously from the `DORPCBackend` constructor.",
2248
+ "INTERNAL"
2076
2249
  );
2077
2250
  }
2251
+ return client.getRegistrySnapshot();
2252
+ };
2253
+ const siblingOptions = { ...options };
2254
+ const makeSiblingClient = (siblingRootKey) => createDOClient(namespace, siblingRootKey, siblingOptions);
2255
+ const backend = new DORPCBackend(namespace, {
2256
+ scopePath: "",
2257
+ storageKey: rootKey,
2258
+ registryAccessor,
2259
+ makeSiblingClient
2260
+ });
2261
+ let metaBackend;
2262
+ if (options.registryMode?.collection) {
2263
+ const metaKey = options.registryMode.collection;
2264
+ if (metaKey.includes("/")) {
2265
+ throw new FiregraphError(
2266
+ `createDOClient: registryMode.collection must not contain "/". Got: "${metaKey}".`,
2267
+ "INVALID_ARGUMENT"
2268
+ );
2269
+ }
2270
+ if (metaKey !== rootKey) {
2271
+ metaBackend = new DORPCBackend(namespace, {
2272
+ scopePath: "",
2273
+ storageKey: metaKey,
2274
+ // Meta backend shares the accessor so its own `removeNodeCascade`
2275
+ // (unlikely, but safe) would also see the live registry. Sibling
2276
+ // factory is carried for consistency; there's no user-facing path
2277
+ // that creates a sibling from the meta backend, but it costs
2278
+ // nothing to keep the two backends in sync.
2279
+ registryAccessor,
2280
+ makeSiblingClient
2281
+ });
2282
+ }
2078
2283
  }
2079
- async deleteDoc(docId) {
2080
- const stmt = compileDelete(this.tableName, this.storageScope, docId);
2081
- await this.tx.run(stmt.sql, stmt.params);
2082
- }
2083
- };
2084
- var SqliteBatchBackendImpl = class {
2085
- constructor(executor, tableName, storageScope) {
2086
- this.executor = executor;
2087
- this.tableName = tableName;
2088
- this.storageScope = storageScope;
2089
- }
2090
- statements = [];
2091
- setDoc(docId, record) {
2092
- this.statements.push(compileSet(this.tableName, this.storageScope, docId, record, Date.now()));
2093
- }
2094
- updateDoc(docId, update) {
2095
- this.statements.push(
2096
- compileUpdate(this.tableName, this.storageScope, docId, update, Date.now())
2284
+ client = createGraphClientFromBackend(backend, options, metaBackend);
2285
+ return client;
2286
+ }
2287
+ function createSiblingClient(client, siblingRootKey) {
2288
+ if (!siblingRootKey || typeof siblingRootKey !== "string") {
2289
+ throw new FiregraphError(
2290
+ `createSiblingClient: siblingRootKey must be a non-empty string, got ${JSON.stringify(siblingRootKey)}.`,
2291
+ "INVALID_ARGUMENT"
2097
2292
  );
2098
2293
  }
2099
- deleteDoc(docId) {
2100
- this.statements.push(compileDelete(this.tableName, this.storageScope, docId));
2294
+ if (siblingRootKey.includes("/")) {
2295
+ throw new FiregraphError(
2296
+ `createSiblingClient: siblingRootKey must not contain "/". Got: "${siblingRootKey}".`,
2297
+ "INVALID_ARGUMENT"
2298
+ );
2101
2299
  }
2102
- async commit() {
2103
- if (this.statements.length === 0) return;
2104
- await this.executor.batch(this.statements);
2105
- this.statements.length = 0;
2300
+ const impl = client;
2301
+ const backend = typeof impl.getBackend === "function" ? impl.getBackend() : void 0;
2302
+ const maker = backend && backend.makeSiblingClient;
2303
+ if (typeof maker !== "function") {
2304
+ throw new FiregraphError(
2305
+ "createSiblingClient: the provided client is not backed by a DO client produced by `createDOClient`. Sibling construction is only available for DO-backed clients.",
2306
+ "UNSUPPORTED_OPERATION"
2307
+ );
2106
2308
  }
2309
+ return maker(siblingRootKey);
2310
+ }
2311
+
2312
+ // src/cloudflare/do.ts
2313
+ var DEFAULT_OPTIONS = {
2314
+ table: "firegraph",
2315
+ autoMigrate: true
2107
2316
  };
2108
- var SqliteBackendImpl = class _SqliteBackendImpl {
2109
- constructor(executor, tableName, storageScope, scopePath) {
2110
- this.executor = executor;
2111
- this.collectionPath = tableName;
2112
- this.storageScope = storageScope;
2113
- this.scopePath = scopePath;
2317
+ var FiregraphDO = class {
2318
+ /** @internal — exposed for subclass access, not part of the public RPC. */
2319
+ ctx;
2320
+ /** @internal — exposed for subclass access; opaque to this class. */
2321
+ env;
2322
+ /** @internal — table name used by every compiled statement. */
2323
+ table;
2324
+ constructor(ctx, env, options = {}) {
2325
+ this.ctx = ctx;
2326
+ this.env = env;
2327
+ const table = options.table ?? DEFAULT_OPTIONS.table;
2328
+ validateDOTableName(table);
2329
+ this.table = table;
2330
+ const autoMigrate = options.autoMigrate ?? DEFAULT_OPTIONS.autoMigrate;
2331
+ if (autoMigrate) {
2332
+ void this.ctx.blockConcurrencyWhile(async () => {
2333
+ this.runSchema();
2334
+ });
2335
+ }
2114
2336
  }
2115
- /** Logical table name (returned through `collectionPath` for parity with Firestore). */
2116
- collectionPath;
2117
- scopePath;
2118
- /** Materialized storage scope (interleaved parent UIDs + subgraph names). */
2119
- storageScope;
2120
- // --- Reads ---
2121
- async getDoc(docId) {
2122
- const stmt = compileSelectByDocId(this.collectionPath, this.storageScope, docId);
2123
- const rows = await this.executor.all(stmt.sql, stmt.params);
2124
- return rows.length === 0 ? null : rowToRecord(rows[0]);
2337
+ // ---------------------------------------------------------------------------
2338
+ // RPC: reads
2339
+ //
2340
+ // Method names are prefixed `_fg` so user subclasses can add their own RPC
2341
+ // methods without name collisions. The client-side backend in
2342
+ // `src/cloudflare/backend.ts` calls these directly on the DO stub.
2343
+ // ---------------------------------------------------------------------------
2344
+ async _fgGetDoc(docId) {
2345
+ const stmt = compileDOSelectByDocId(this.table, docId);
2346
+ const rows = this.execAll(stmt);
2347
+ return rows.length === 0 ? null : rowToDORecord(rows[0]);
2125
2348
  }
2126
- async query(filters, options) {
2127
- const stmt = compileSelect(this.collectionPath, this.storageScope, filters, options);
2128
- const rows = await this.executor.all(stmt.sql, stmt.params);
2129
- return rows.map(rowToRecord);
2349
+ async _fgQuery(filters, options) {
2350
+ const stmt = compileDOSelect(this.table, filters, options);
2351
+ const rows = this.execAll(stmt);
2352
+ return rows.map(rowToDORecord);
2130
2353
  }
2131
- // --- Writes ---
2132
- async setDoc(docId, record) {
2133
- const stmt = compileSet(this.collectionPath, this.storageScope, docId, record, Date.now());
2134
- await this.executor.run(stmt.sql, stmt.params);
2354
+ // ---------------------------------------------------------------------------
2355
+ // RPC: writes
2356
+ // ---------------------------------------------------------------------------
2357
+ async _fgSetDoc(docId, record) {
2358
+ const stmt = compileDOSet(this.table, docId, record, Date.now());
2359
+ this.execRun(stmt);
2135
2360
  }
2136
- async updateDoc(docId, update) {
2137
- const stmt = compileUpdate(this.collectionPath, this.storageScope, docId, update, Date.now());
2361
+ async _fgUpdateDoc(docId, update) {
2362
+ const stmt = compileDOUpdate(this.table, docId, update, Date.now());
2138
2363
  const sqlWithReturning = `${stmt.sql} RETURNING "doc_id"`;
2139
- const rows = await this.executor.all(sqlWithReturning, stmt.params);
2364
+ const rows = this.ctx.storage.sql.exec(sqlWithReturning, ...stmt.params).toArray();
2140
2365
  if (rows.length === 0) {
2141
- throw new FiregraphError(
2142
- `updateDoc: no document found for doc_id=${docId} (scope=${this.storageScope})`,
2143
- "NOT_FOUND"
2144
- );
2366
+ throw new FiregraphError(`updateDoc: no document found for doc_id=${docId}`, "NOT_FOUND");
2145
2367
  }
2146
2368
  }
2147
- async deleteDoc(docId) {
2148
- const stmt = compileDelete(this.collectionPath, this.storageScope, docId);
2149
- await this.executor.run(stmt.sql, stmt.params);
2369
+ async _fgDeleteDoc(docId) {
2370
+ const stmt = compileDODelete(this.table, docId);
2371
+ this.execRun(stmt);
2150
2372
  }
2151
- // --- Transactions / Batches ---
2152
- async runTransaction(fn) {
2153
- if (!this.executor.transaction) {
2154
- throw new FiregraphError(
2155
- "Interactive transactions are not supported by this SQLite driver. D1 in particular has no read-then-conditional-write transactions; use a Durable Object SQLite client instead, or rewrite the code path as a batch().",
2156
- "UNSUPPORTED_OPERATION"
2157
- );
2158
- }
2159
- return this.executor.transaction(async (tx) => {
2160
- const txBackend = new SqliteTransactionBackendImpl(
2161
- tx,
2162
- this.collectionPath,
2163
- this.storageScope
2164
- );
2165
- return fn(txBackend);
2373
+ // ---------------------------------------------------------------------------
2374
+ // RPC: batch
2375
+ // ---------------------------------------------------------------------------
2376
+ /**
2377
+ * Execute a list of write ops atomically. DO SQLite's `transactionSync`
2378
+ * provides real atomicity — either every statement commits or none do.
2379
+ * No statement-count cap applies (contrast with D1's ~100-statement batch
2380
+ * limit), so the caller can submit as many ops as they like in one call.
2381
+ */
2382
+ async _fgBatch(ops) {
2383
+ if (ops.length === 0) return;
2384
+ const now = Date.now();
2385
+ const statements = ops.map((op) => {
2386
+ switch (op.kind) {
2387
+ case "set":
2388
+ return compileDOSet(this.table, op.docId, op.record, now);
2389
+ case "update":
2390
+ return compileDOUpdate(this.table, op.docId, op.update, now);
2391
+ case "delete":
2392
+ return compileDODelete(this.table, op.docId);
2393
+ }
2394
+ });
2395
+ this.ctx.storage.transactionSync(() => {
2396
+ for (const stmt of statements) {
2397
+ this.ctx.storage.sql.exec(stmt.sql, ...stmt.params).toArray();
2398
+ }
2166
2399
  });
2167
2400
  }
2168
- createBatch() {
2169
- return new SqliteBatchBackendImpl(this.executor, this.collectionPath, this.storageScope);
2170
- }
2171
- // --- Subgraphs ---
2172
- subgraph(parentNodeUid, name) {
2173
- if (!parentNodeUid || parentNodeUid.includes("/")) {
2174
- throw new FiregraphError(
2175
- `Invalid parentNodeUid for subgraph: "${parentNodeUid}". Must be a non-empty string without "/".`,
2176
- "INVALID_SUBGRAPH"
2177
- );
2178
- }
2179
- if (!name || name.includes("/")) {
2180
- throw new FiregraphError(
2181
- `Subgraph name must not contain "/" and must be non-empty: got "${name}". Use chained .subgraph() calls for nested subgraphs.`,
2182
- "INVALID_SUBGRAPH"
2183
- );
2184
- }
2185
- const newStorageScope = this.storageScope ? `${this.storageScope}/${parentNodeUid}/${name}` : `${parentNodeUid}/${name}`;
2186
- const newScope = this.scopePath ? `${this.scopePath}/${name}` : name;
2187
- return new _SqliteBackendImpl(this.executor, this.collectionPath, newStorageScope, newScope);
2188
- }
2189
- // --- Cascade & bulk ---
2190
- async removeNodeCascade(uid, reader, options) {
2191
- const [outgoingRaw, incomingRaw] = await Promise.all([
2192
- reader.findEdges({ aUid: uid, allowCollectionScan: true, limit: 0 }),
2193
- reader.findEdges({ bUid: uid, allowCollectionScan: true, limit: 0 })
2194
- ]);
2401
+ // ---------------------------------------------------------------------------
2402
+ // RPC: cascade + bulk (local DO only)
2403
+ //
2404
+ // These cascade *within this DO*. Subgraph DOs (nested under this node) are
2405
+ // not reachable from here — the client-side `DORPCBackend.removeNodeCascade`
2406
+ // consults the registry topology to discover descendant subgraph DOs and
2407
+ // fans out explicit `_fgDestroy` calls to each before invoking this method.
2408
+ // Without that topology the DO has no way to enumerate its children.
2409
+ // ---------------------------------------------------------------------------
2410
+ async _fgRemoveNodeCascade(uid) {
2411
+ const outgoingStmt = compileDOSelect(this.table, [{ field: "aUid", op: "==", value: uid }]);
2412
+ const incomingStmt = compileDOSelect(this.table, [{ field: "bUid", op: "==", value: uid }]);
2413
+ const outgoingRows = this.execAll(outgoingStmt);
2414
+ const incomingRows = this.execAll(incomingStmt);
2195
2415
  const seen = /* @__PURE__ */ new Set();
2196
2416
  const edgeDocIds = [];
2197
- for (const edge of [...outgoingRaw, ...incomingRaw]) {
2198
- if (edge.axbType === NODE_RELATION) continue;
2199
- const docId = computeEdgeDocId(edge.aUid, edge.axbType, edge.bUid);
2417
+ let nodeExists = false;
2418
+ for (const row of [...outgoingRows, ...incomingRows]) {
2419
+ const axbType = row.axb_type;
2420
+ const aUid = row.a_uid;
2421
+ const bUid = row.b_uid;
2422
+ if (axbType === NODE_RELATION && aUid === bUid) {
2423
+ nodeExists = true;
2424
+ continue;
2425
+ }
2426
+ const docId = computeEdgeDocId(aUid, axbType, bUid);
2200
2427
  if (!seen.has(docId)) {
2201
2428
  seen.add(docId);
2202
2429
  edgeDocIds.push(docId);
2203
2430
  }
2204
2431
  }
2205
- const nodeDocId = computeNodeDocId(uid);
2206
- const shouldDeleteSubgraphs = options?.deleteSubcollections !== false;
2207
- let subgraphRowCount = 0;
2208
- if (shouldDeleteSubgraphs) {
2209
- const prefix = this.storageScope ? `${this.storageScope}/${uid}` : uid;
2210
- const countStmt = compileCountScopePrefix(this.collectionPath, prefix);
2211
- const countRows = await this.executor.all(countStmt.sql, countStmt.params);
2212
- const first = countRows[0];
2213
- const n = first?.n;
2214
- subgraphRowCount = typeof n === "bigint" ? Number(n) : Number(n ?? 0);
2215
- }
2216
- const writeStatements = edgeDocIds.map(
2217
- (id) => compileDelete(this.collectionPath, this.storageScope, id)
2218
- );
2219
- writeStatements.push(compileDelete(this.collectionPath, this.storageScope, nodeDocId));
2220
- if (shouldDeleteSubgraphs) {
2221
- const prefix = this.storageScope ? `${this.storageScope}/${uid}` : uid;
2222
- writeStatements.push(compileDeleteScopePrefix(this.collectionPath, prefix));
2223
- }
2224
- const {
2225
- deleted: stmtDeleted,
2226
- batches,
2227
- errors
2228
- } = await this.executeChunkedBatches(writeStatements, options);
2229
- const allOk = errors.length === 0;
2230
- const edgesDeleted = allOk ? edgeDocIds.length : 0;
2231
- const nodeDeleted = allOk;
2232
- const prefixStatementContribution = shouldDeleteSubgraphs && allOk ? 1 : 0;
2233
- const deleted = stmtDeleted - prefixStatementContribution + (allOk ? subgraphRowCount : 0);
2234
- return { deleted, batches, errors, edgesDeleted, nodeDeleted };
2235
- }
2236
- async bulkRemoveEdges(params, reader, options) {
2237
- const effectiveParams = params.limit !== void 0 ? { ...params, allowCollectionScan: params.allowCollectionScan ?? true } : { ...params, limit: 0, allowCollectionScan: params.allowCollectionScan ?? true };
2238
- const edges = await reader.findEdges(effectiveParams);
2239
- const docIds = edges.map((e) => computeEdgeDocId(e.aUid, e.axbType, e.bUid));
2240
- if (docIds.length === 0) {
2241
- return { deleted: 0, batches: 0, errors: [] };
2432
+ const statements = edgeDocIds.map((id) => compileDODelete(this.table, id));
2433
+ if (nodeExists) {
2434
+ statements.push(compileDODelete(this.table, computeNodeDocId(uid)));
2242
2435
  }
2243
- const statements = docIds.map(
2244
- (id) => compileDelete(this.collectionPath, this.storageScope, id)
2245
- );
2246
- return this.executeChunkedBatches(statements, options);
2247
- }
2248
- /**
2249
- * Submit `statements` to the executor as one or more `batch()` calls,
2250
- * chunking by `executor.maxBatchSize` (e.g. D1's ~100-statement cap).
2251
- * Drivers that don't advertise a cap submit everything in one batch,
2252
- * preserving cross-batch atomicity.
2253
- *
2254
- * Each chunk is retried with exponential backoff up to `maxRetries`
2255
- * (default 3) before being recorded in `errors`. The loop continues past
2256
- * a permanently failed chunk so the caller still gets partial progress
2257
- * visibility — to halt on first failure, set `maxRetries: 0` and check
2258
- * `result.errors.length` after the call.
2259
- *
2260
- * Returns `BulkResult`-shaped fields. `deleted` reflects only the
2261
- * statement count of *successfully committed* batches — a prefix-delete
2262
- * statement contributes 1 to that total even though it may match many
2263
- * rows; `removeNodeCascade` patches that up with a pre-counted row total.
2264
- *
2265
- * **Atomicity caveat (D1):** when chunking kicks in, atomicity is lost
2266
- * across chunk boundaries — one chunk may commit while a later one fails.
2267
- * `removeNodeCascade` is idempotent (deleting the same docs again is a
2268
- * no-op) so a caller can simply retry on partial failure. `bulkRemoveEdges`
2269
- * is also idempotent for the same reason. DO SQLite leaves `maxBatchSize`
2270
- * unset, so everything funnels through one atomic `transactionSync` and
2271
- * this caveat does not apply.
2272
- */
2273
- async executeChunkedBatches(statements, options) {
2274
2436
  if (statements.length === 0) {
2275
- return { deleted: 0, batches: 0, errors: [] };
2437
+ return {
2438
+ deleted: 0,
2439
+ batches: 0,
2440
+ errors: [],
2441
+ edgesDeleted: 0,
2442
+ nodeDeleted: false
2443
+ };
2276
2444
  }
2277
- const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES;
2278
- const callerBatchSize = options?.batchSize;
2279
- const stmtCap = minDefined(callerBatchSize, this.executor.maxBatchSize);
2280
- const chunks = chunkStatements(statements, stmtCap, this.executor.maxBatchParams);
2281
- const errors = [];
2282
- let deleted = 0;
2283
- let batches = 0;
2284
- const totalBatches = chunks.length;
2285
- const driverParamCap = this.executor.maxBatchParams;
2286
- for (let batchIndex = 0; batchIndex < chunks.length; batchIndex++) {
2287
- const chunk = chunks[batchIndex];
2288
- const isUnretriableOversize = chunk.length === 1 && driverParamCap !== void 0 && chunk[0].params.length > driverParamCap;
2289
- let committed = false;
2290
- let lastError = null;
2291
- const effectiveRetries = isUnretriableOversize ? 0 : maxRetries;
2292
- for (let attempt = 0; attempt <= effectiveRetries; attempt++) {
2293
- try {
2294
- await this.executor.batch(chunk);
2295
- committed = true;
2296
- break;
2297
- } catch (err) {
2298
- lastError = err instanceof Error ? err : new Error(String(err));
2299
- if (attempt < effectiveRetries) {
2300
- const delay = Math.min(BASE_RETRY_DELAY_MS * Math.pow(2, attempt), MAX_RETRY_DELAY_MS);
2301
- await sleep(delay);
2302
- }
2445
+ try {
2446
+ this.ctx.storage.transactionSync(() => {
2447
+ for (const stmt of statements) {
2448
+ this.ctx.storage.sql.exec(stmt.sql, ...stmt.params).toArray();
2303
2449
  }
2304
- }
2305
- if (committed) {
2306
- deleted += chunk.length;
2307
- batches += 1;
2308
- } else if (lastError) {
2309
- errors.push({
2310
- batchIndex,
2311
- error: lastError,
2312
- operationCount: chunk.length
2313
- });
2314
- }
2315
- if (options?.onProgress) {
2316
- options.onProgress({
2317
- completedBatches: batches,
2318
- totalBatches,
2319
- deletedSoFar: deleted
2320
- });
2321
- }
2450
+ });
2451
+ return {
2452
+ deleted: statements.length,
2453
+ batches: 1,
2454
+ errors: [],
2455
+ edgesDeleted: edgeDocIds.length,
2456
+ nodeDeleted: nodeExists
2457
+ };
2458
+ } catch (err) {
2459
+ const error = err instanceof Error ? err : new Error(String(err));
2460
+ return {
2461
+ deleted: 0,
2462
+ batches: 0,
2463
+ errors: [{ batchIndex: 0, error, operationCount: statements.length }],
2464
+ edgesDeleted: 0,
2465
+ nodeDeleted: false
2466
+ };
2322
2467
  }
2323
- return { deleted, batches, errors };
2324
2468
  }
2325
- // --- Cross-scope (collection group) ---
2326
- async findEdgesGlobal(params, collectionName) {
2469
+ async _fgBulkRemoveEdges(params, _options) {
2327
2470
  const plan = buildEdgeQueryPlan(params);
2471
+ let docIds;
2328
2472
  if (plan.strategy === "get") {
2329
- throw new FiregraphError(
2330
- "findEdgesGlobal() requires a query, not a direct document lookup. Omit one of aUid/axbType/bUid to force a query strategy.",
2331
- "INVALID_QUERY"
2473
+ const existsStmt = compileDOSelectByDocId(this.table, plan.docId);
2474
+ const rows = this.execAll(existsStmt);
2475
+ docIds = rows.length > 0 ? [plan.docId] : [];
2476
+ } else {
2477
+ const selectStmt = compileDOSelect(this.table, plan.filters, plan.options);
2478
+ const rows = this.execAll(selectStmt);
2479
+ docIds = rows.map(
2480
+ (row) => computeEdgeDocId(row.a_uid, row.axb_type, row.b_uid)
2332
2481
  );
2333
2482
  }
2334
- const name = collectionName ?? this.collectionPath;
2335
- const scopeNameFilter = {
2336
- name,
2337
- isRoot: name === this.collectionPath
2338
- };
2339
- const stmt = compileSelectGlobal(
2340
- this.collectionPath,
2341
- plan.filters,
2342
- plan.options,
2343
- scopeNameFilter
2344
- );
2345
- const rows = await this.executor.all(stmt.sql, stmt.params);
2346
- return rows.map(rowToRecord);
2347
- }
2348
- };
2349
- function createSqliteBackend(executor, tableName, options = {}) {
2350
- const storageScope = options.storageScope ?? "";
2351
- const scopePath = options.scopePath ?? "";
2352
- return new SqliteBackendImpl(executor, tableName, storageScope, scopePath);
2353
- }
2354
-
2355
- // src/do-sqlite.ts
2356
- var DOSqliteExecutor = class {
2357
- constructor(storage) {
2358
- this.storage = storage;
2359
- }
2360
- async all(sql, params) {
2361
- return this.storage.sql.exec(sql, ...params).toArray();
2362
- }
2363
- async run(sql, params) {
2364
- this.storage.sql.exec(sql, ...params).toArray();
2365
- }
2366
- async batch(statements) {
2367
- if (statements.length === 0) return;
2368
- this.storage.transactionSync(() => {
2369
- for (const s of statements) {
2370
- this.storage.sql.exec(s.sql, ...s.params).toArray();
2371
- }
2372
- });
2373
- }
2374
- async transaction(fn) {
2375
- this.storage.sql.exec("BEGIN IMMEDIATE").toArray();
2483
+ if (docIds.length === 0) {
2484
+ return { deleted: 0, batches: 0, errors: [] };
2485
+ }
2486
+ const deleteStmts = docIds.map((id) => compileDODelete(this.table, id));
2376
2487
  try {
2377
- const txExec = {
2378
- all: async (sql, params) => this.storage.sql.exec(sql, ...params).toArray(),
2379
- run: async (sql, params) => {
2380
- this.storage.sql.exec(sql, ...params).toArray();
2488
+ this.ctx.storage.transactionSync(() => {
2489
+ for (const stmt of deleteStmts) {
2490
+ this.ctx.storage.sql.exec(stmt.sql, ...stmt.params).toArray();
2381
2491
  }
2382
- };
2383
- const result = await fn(txExec);
2384
- this.storage.sql.exec("COMMIT").toArray();
2385
- return result;
2492
+ });
2493
+ return { deleted: deleteStmts.length, batches: 1, errors: [] };
2386
2494
  } catch (err) {
2387
- this.storage.sql.exec("ROLLBACK").toArray();
2388
- throw err;
2495
+ const error = err instanceof Error ? err : new Error(String(err));
2496
+ return {
2497
+ deleted: 0,
2498
+ batches: 0,
2499
+ errors: [{ batchIndex: 0, error, operationCount: deleteStmts.length }]
2500
+ };
2389
2501
  }
2390
2502
  }
2391
- };
2392
- function ensureSchema(storage, table) {
2393
- const statements = buildSchemaStatements(table);
2394
- for (const sql of statements) {
2395
- storage.sql.exec(sql).toArray();
2396
- }
2397
- }
2398
- function createDOSqliteGraphClient(storage, options = {}) {
2399
- const table = options.table ?? "firegraph";
2400
- validateTableName(table);
2401
- if (options.autoMigrate !== false) {
2402
- ensureSchema(storage, table);
2403
- }
2404
- const executor = new DOSqliteExecutor(storage);
2405
- const backend = createSqliteBackend(executor, table);
2406
- const { table: _t, autoMigrate: _m, ...clientOptions } = options;
2407
- void _t;
2408
- void _m;
2409
- let metaBackend;
2410
- if (clientOptions.registryMode && typeof clientOptions.registryMode === "object" && clientOptions.registryMode.collection && clientOptions.registryMode.collection !== table) {
2411
- const metaTable = clientOptions.registryMode.collection;
2412
- validateTableName(metaTable);
2413
- if (options.autoMigrate !== false) {
2414
- ensureSchema(storage, metaTable);
2503
+ // ---------------------------------------------------------------------------
2504
+ // RPC: admin
2505
+ // ---------------------------------------------------------------------------
2506
+ /**
2507
+ * Wipe every row. Called by the client when tearing down a subgraph DO as
2508
+ * part of cascade — the DO itself can't be destroyed (DO IDs persist
2509
+ * forever), but its storage can be emptied.
2510
+ */
2511
+ async _fgDestroy() {
2512
+ const stmt = compileDODeleteAll(this.table);
2513
+ this.execRun(stmt);
2514
+ }
2515
+ // ---------------------------------------------------------------------------
2516
+ // Internals
2517
+ // ---------------------------------------------------------------------------
2518
+ runSchema() {
2519
+ for (const sql of buildDOSchemaStatements(this.table)) {
2520
+ this.ctx.storage.sql.exec(sql).toArray();
2415
2521
  }
2416
- metaBackend = createSqliteBackend(executor, metaTable);
2417
2522
  }
2418
- return createGraphClientFromBackend(backend, clientOptions, metaBackend);
2419
- }
2523
+ execAll(stmt) {
2524
+ return this.ctx.storage.sql.exec(stmt.sql, ...stmt.params).toArray();
2525
+ }
2526
+ execRun(stmt) {
2527
+ this.ctx.storage.sql.exec(stmt.sql, ...stmt.params).toArray();
2528
+ }
2529
+ };
2420
2530
  // Annotate the CommonJS export names for ESM import in node:
2421
2531
  0 && (module.exports = {
2422
- createDOSqliteGraphClient
2532
+ DORPCBackend,
2533
+ FiregraphDO,
2534
+ createDOClient,
2535
+ createSiblingClient
2423
2536
  });
2424
- //# sourceMappingURL=do-sqlite.cjs.map
2537
+ //# sourceMappingURL=index.cjs.map