@wazootech/worlds-cloudflare 0.15.9 → 0.15.11

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.
@@ -0,0 +1,794 @@
1
+ import { InMemoryProvenanceStore, Transaction, exportFromRdfjsStore, filterQuads, hashQuads, importViaTransaction, isReplaceImportCommit, preparePatch, selectNovelQuads } from "@wazootech/worlds-sdk/quad-store";
2
+ import { planSearchIndexing } from "@wazootech/worlds-sdk/search-index";
3
+ import { commitSqlPatch } from "@wazootech/worlds-sqlite/sql-core";
4
+ import { _ as effectiveLookupChunkSize, a as buildSelectAssertedQuadsPage, d as DEFAULT_D1_MATCH_PAGE_SIZE, f as buildInsertRow, n as buildCountAssertedQuads, p as quadFromD1Row } from "./d1-quad-insert-sql-B4ZiZZe8.js";
5
+ import { a as buildSelectQuadRecords, d as selectWorldVersion, f as SHAPES_GRAPH, i as buildSelectProvenanceChains, l as isVersionConflict, o as chunk, r as buildSelectProvenance, s as buildRaiseVersion, t as buildInsertProvenance, u as readWorldVersion } from "./d1-provenance-sql-CV6Mly6b.js";
6
+ import { Reasoner } from "@wazootech/reasoner";
7
+ import { i as createD1CommitDriver, o as d1StatementWeight, s as createD1CommitDialect, t as isFullRebuild } from "./project-search-chunks-options-qI9m5FWz.js";
8
+ import { r as matchD1Pages } from "./d1-rdfjs-store-read-2QTEEe_a.js";
9
+ /** LISTS_PER_STATEMENT keeps a statement inside D1's 100 parameters and a batch's byte budget. */
10
+ const LISTS_PER_STATEMENT = 16;
11
+ /** packLists splits items over as many JSON lists as D1's value size needs, and at least one. */
12
+ function packLists(items) {
13
+ const lists = [];
14
+ let list = "";
15
+ for (const item of items) {
16
+ const json = JSON.stringify(item);
17
+ if (list && list.length + json.length > 5e5) {
18
+ lists.push(`[${list}]`);
19
+ list = "";
20
+ }
21
+ list += list ? `,${json}` : json;
22
+ }
23
+ return [...lists, `[${list}]`];
24
+ }
25
+ /** groupLists splits items over statements; no items need no statement. */
26
+ function groupLists(items) {
27
+ if (items.length === 0) return [];
28
+ const lists = packLists(items);
29
+ const groups = [];
30
+ for (let i = 0; i < lists.length; i += LISTS_PER_STATEMENT) groups.push(lists.slice(i, i + LISTS_PER_STATEMENT));
31
+ return groups;
32
+ }
33
+ /** fromLists reads the items of several lists as rows of `item`. */
34
+ function fromLists(lists) {
35
+ return {
36
+ sql: `(VALUES ${lists.map(() => "(?)").join(", ")}) lists CROSS JOIN json_each(lists.column1) item`,
37
+ args: [...lists]
38
+ };
39
+ }
40
+ /** insertRecords starts an INSERT of one record per row, with these values for its quad and the one it replaced. */
41
+ function insertRecords(type, values, scope) {
42
+ const { worldId, recordedAt, writer, source } = scope;
43
+ return {
44
+ sql: `INSERT INTO provenance (quad_id, supersedes_quad_id, type, recorded_at, writer, source${worldId ? ", world_id" : ""}) SELECT ${values}, '${type}', ?, ?, ?${worldId ? ", ?" : ""} FROM`,
45
+ args: [
46
+ recordedAt,
47
+ writer ?? null,
48
+ source ?? null,
49
+ ...worldId ? [worldId] : []
50
+ ]
51
+ };
52
+ }
53
+ /** latestRecord reads a value from the newest record `r` of a quad; it is NULL if there is none. */
54
+ function latestRecord(value, quadId, { worldId }) {
55
+ return {
56
+ sql: `(SELECT ${value.sql} FROM provenance r WHERE r.quad_id = ${quadId}${worldId ? " AND r.world_id = ?" : ""} ORDER BY r.record_id DESC LIMIT 1)`,
57
+ args: [...value.args, ...worldId ? [worldId] : []]
58
+ };
59
+ }
60
+ /** asserted limits the quads `q` to the world's asserted ones; it names `derived` only when inference guarantees the column. */
61
+ function asserted({ worldId, inferenceEnabled }) {
62
+ return {
63
+ sql: `${worldId ? " AND q.world_id = ?" : ""}${inferenceEnabled ? " AND q.derived = 0" : ""}`,
64
+ args: worldId ? [worldId] : []
65
+ };
66
+ }
67
+ /** fromStored reads, as rows of `q`, the listed quads that the world holds at that moment, or all of them. */
68
+ function fromStored(lists, scope) {
69
+ const held = asserted(scope);
70
+ if (lists === "world") return {
71
+ sql: `quads q WHERE TRUE${held.sql}`,
72
+ args: held.args
73
+ };
74
+ const ids = fromLists(lists);
75
+ return {
76
+ sql: `${ids.sql} CROSS JOIN quads q WHERE q.quad_id = item.value${held.sql}`,
77
+ args: [...ids.args, ...held.args]
78
+ };
79
+ }
80
+ // src/cloudflare/provenance/commit-records-sql.ts
81
+ /** buildRemoveRecords records the stored quads a commit takes out. It has to run before anything is deleted. */
82
+ function buildRemoveRecords(leaving, addedIds, scope) {
83
+ const insert = insertRecords("remove", "q.quad_id, NULL", scope);
84
+ if (leaving !== "world") return groupLists(leaving).map((lists) => {
85
+ const stored = fromStored(lists, scope);
86
+ return {
87
+ sql: `${insert.sql} ${stored.sql}`,
88
+ args: [...insert.args, ...stored.args]
89
+ };
90
+ });
91
+ const stored = fromStored("world", scope);
92
+ const kept = fromLists(packLists(addedIds));
93
+ return [{
94
+ sql: `${insert.sql} ${stored.sql} AND q.quad_id NOT IN (SELECT item.value FROM ${kept.sql})`,
95
+ args: [
96
+ ...insert.args,
97
+ ...stored.args,
98
+ ...kept.args
99
+ ]
100
+ }];
101
+ }
102
+ /**
103
+ * buildWriteRecords records the added quads that the world does not hold yet,
104
+ * each linked to the quad it replaces: one at the same position that has just
105
+ * got this commit's remove record. It has to run between those and the first
106
+ * delete. The `+` keeps SQLite off the index by subject, which worlds share.
107
+ */
108
+ function buildWriteRecords(added, leaving, scope) {
109
+ const old = fromStored(leaving === "world" ? leaving : packLists(leaving), scope);
110
+ const justRemoved = latestRecord({
111
+ sql: "r.type = 'remove' AND r.recorded_at = ?",
112
+ args: [scope.recordedAt]
113
+ }, "q.quad_id", scope);
114
+ const held = asserted(scope);
115
+ const insert = insertRecords("write", "added.id, replaced.id", scope);
116
+ return groupLists(added).map((lists) => {
117
+ const items = fromLists(lists);
118
+ return {
119
+ sql: `WITH added(id, s, p, g) AS MATERIALIZED (
120
+ SELECT json_extract(item.value, '$[0]'), json_extract(item.value, '$[1]'),
121
+ json_extract(item.value, '$[2]'), json_extract(item.value, '$[3]')
122
+ FROM ${items.sql}
123
+ ), replaced(id, s, p, g) AS MATERIALIZED (
124
+ SELECT MAX(q.quad_id), q.s, q.p, q.g FROM ${old.sql}
125
+ AND (+q.s, +q.p, +q.g) IN (SELECT s, p, g FROM added)
126
+ AND ${justRemoved.sql}
127
+ GROUP BY q.s, q.p, q.g
128
+ ) ${insert.sql} added LEFT JOIN replaced
129
+ ON replaced.s = added.s AND replaced.p = added.p AND replaced.g = added.g
130
+ WHERE NOT EXISTS (SELECT 1 FROM quads q WHERE q.quad_id = added.id${held.sql})`,
131
+ args: [
132
+ ...items.args,
133
+ ...old.args,
134
+ ...justRemoved.args,
135
+ ...insert.args,
136
+ ...held.args
137
+ ]
138
+ };
139
+ });
140
+ }
141
+ // src/cloudflare/provenance/undo-records-sql.ts
142
+ /**
143
+ * buildUndoRecords makes the records true again after a commit that was too
144
+ * large for one batch failed partway. It has to run before the commit's cleanup,
145
+ * which deletes every added quad, even one that was stored before. `recorded`
146
+ * says that all the commit's records were written; before that, it deleted nothing.
147
+ */
148
+ function buildUndoRecords(leaving, addedIds, recorded, scope) {
149
+ const added = groupLists(addedIds).map(fromLists);
150
+ return [
151
+ ...(leaving === "world" ? [leaving] : groupLists(leaving)).map((lists) => takeBackRemoves(lists, scope)),
152
+ ...added.map((ids) => {
153
+ const insert = insertRecords("remove", "item.value, NULL", scope);
154
+ const lost = wasStored(recorded, scope);
155
+ return {
156
+ sql: `${insert.sql} ${ids.sql} WHERE ${lost.sql}`,
157
+ args: [
158
+ ...insert.args,
159
+ ...ids.args,
160
+ ...lost.args
161
+ ]
162
+ };
163
+ }),
164
+ ...added.map((ids) => ({
165
+ sql: `DELETE FROM provenance WHERE type = 'write' AND recorded_at = ? AND quad_id IN (SELECT item.value FROM ${ids.sql})${scope.worldId ? " AND world_id = ?" : ""}`,
166
+ args: [
167
+ scope.recordedAt,
168
+ ...ids.args,
169
+ ...scope.worldId ? [scope.worldId] : []
170
+ ]
171
+ }))
172
+ ];
173
+ }
174
+ /** takeBackRemoves deletes the commit's remove records of quads that are still stored. */
175
+ function takeBackRemoves(lists, scope) {
176
+ const stored = fromStored(lists, scope);
177
+ const own = latestRecord({
178
+ sql: "CASE WHEN r.type = 'remove' AND r.recorded_at = ? THEN r.record_id END",
179
+ args: [scope.recordedAt]
180
+ }, "q.quad_id", scope);
181
+ return {
182
+ sql: `DELETE FROM provenance WHERE record_id IN (SELECT ${own.sql} FROM ${stored.sql})`,
183
+ args: [...own.args, ...stored.args]
184
+ };
185
+ }
186
+ /**
187
+ * wasStored is true for an added quad `item` that another commit wrote, so that
188
+ * the cleanup loses it. A quad from before the world had provenance has no
189
+ * record: it was stored if this commit didn't record a write, or if it still is.
190
+ */
191
+ function wasStored(recorded, scope) {
192
+ const written = latestRecord({
193
+ sql: "r.type = 'write' AND r.recorded_at <> ?",
194
+ args: [scope.recordedAt]
195
+ }, "item.value", scope);
196
+ const held = asserted(scope);
197
+ return {
198
+ sql: `COALESCE(${written.sql}, ${recorded ? "TRUE" : `EXISTS (SELECT 1 FROM quads q WHERE q.quad_id = item.value${held.sql})`})`,
199
+ args: [...written.args, ...recorded ? [] : held.args]
200
+ };
201
+ }
202
+ // src/cloudflare/provenance/plan-d1-provenance.ts
203
+ /** positionOf names the statement a quad makes; a correction changes only the object. */
204
+ function positionOf({ subject, predicate, graph }) {
205
+ return [
206
+ subject.value,
207
+ predicate.value,
208
+ graph.value
209
+ ];
210
+ }
211
+ /**
212
+ * planD1Provenance builds the statements that record a commit. They decide what
213
+ * the commit really adds and removes when its batch runs, not now, because
214
+ * another commit may get in between. A quad the world already holds gets no new
215
+ * record, so importing the same data again neither grows the table nor makes an
216
+ * old quad look newly written. The SDK's in-memory store records every insertion
217
+ * instead.
218
+ */
219
+ async function planD1Provenance(patch, context, driver, options) {
220
+ const replacing = isReplaceImportCommit(context);
221
+ const prepared = preparePatch(patch, options);
222
+ let existing;
223
+ const lookupExisting = (ids) => existing ??= driver.lookupExisting(ids);
224
+ const novel = await selectNovelQuads(prepared, {
225
+ replacing,
226
+ lookupExisting
227
+ });
228
+ const inserted = new Map(novel.novelQuadIds.map((id, i) => [id, novel.novelInsertions[i]]));
229
+ const deleted = new Map(prepared.deletionIds.map((id, i) => [id, prepared.deletions[i]]).filter(([id]) => !inserted.has(id)));
230
+ const key = (quad) => JSON.stringify(positionOf(quad));
231
+ const freed = new Set([...deleted.values()].map(key));
232
+ const filled = new Set([...inserted.values()].map(key));
233
+ const added = [...inserted].map(([id, quad]) => replacing || freed.has(key(quad)) ? [id, ...positionOf(quad)] : [id]);
234
+ const replaceable = [...deleted].filter(([, quad]) => filled.has(key(quad))).map(([id]) => id);
235
+ const scope = {
236
+ ...context?.provenance,
237
+ recordedAt: (/* @__PURE__ */ new Date()).toISOString(),
238
+ worldId: options.worldId,
239
+ inferenceEnabled: options.inferenceEnabled
240
+ };
241
+ const ids = [...inserted.keys()];
242
+ const leaving = replacing ? "world" : [...deleted.keys()];
243
+ return {
244
+ records: [...buildRemoveRecords(leaving, ids, scope), ...buildWriteRecords(added, replacing ? "world" : replaceable, scope)],
245
+ lookupExisting,
246
+ undo: (recorded) => buildUndoRecords(leaving, ids, recorded, scope)
247
+ };
248
+ }
249
+ // src/cloudflare/provenance/with-provenance.ts
250
+ /**
251
+ * withProvenance adds a plan's statements to a commit's driver and dialect, so
252
+ * they join the commit's own batch, before its first delete or wipe. Create one
253
+ * per commit, like the dialect itself.
254
+ */
255
+ function withProvenance(driver, dialect, plan) {
256
+ const pending = [...plan.records];
257
+ const takeRecords = () => pending.splice(0);
258
+ const last = plan.records.at(-1);
259
+ let recorded = false;
260
+ return {
261
+ driver: {
262
+ ...driver,
263
+ lookupExisting: plan.lookupExisting,
264
+ executeBatch: async (statements) => {
265
+ await driver.executeBatch(statements);
266
+ recorded ||= last !== void 0 && statements.includes(last);
267
+ }
268
+ },
269
+ dialect: {
270
+ ...dialect,
271
+ buildWipe: () => [...takeRecords(), ...dialect.buildWipe()],
272
+ buildDeletions: (keys, hashes) => [...takeRecords(), ...dialect.buildDeletions(keys, hashes)],
273
+ buildCleanup: (keys, hashes) => [...plan.undo(recorded), ...dialect.buildCleanup(keys, hashes)]
274
+ }
275
+ };
276
+ }
277
+ // src/cloudflare/inference/inference-planner.ts
278
+ /** quadKey identifies a quad by term type and value, datatype and language included. */
279
+ function quadKey(quad) {
280
+ return [
281
+ quad.subject,
282
+ quad.predicate,
283
+ quad.object,
284
+ quad.graph
285
+ ].map((term) => {
286
+ if (term.termType === "Literal") return `L|${term.value}|${term.datatype.value}|${term.language}`;
287
+ return `${term.termType}|${term.value}`;
288
+ }).join("\0");
289
+ }
290
+ /**
291
+ * planInference reasons about one patch.
292
+ *
293
+ * It rebuilds a Reasoner from the asserted quads (the reasoner has no
294
+ * serialize/restore, so there is no persisted state to resume), runs it, then
295
+ * uses `retract` and `extend` to get exactly the inferred quads the patch
296
+ * removes and adds instead of diffing two closures. The result is correct only
297
+ * if the stored inferred rows equal the closure of `assertedBefore`; a world
298
+ * that had data before inference was enabled needs a one-time rebuild.
299
+ */
300
+ function planInference(input) {
301
+ const reasoner = new Reasoner({ graphs: input.graphs ?? "per-graph" });
302
+ const asserted = /* @__PURE__ */ new Map();
303
+ for (const quad of input.assertedBefore) asserted.set(quadKey(quad), quad);
304
+ reasoner.add(asserted.values());
305
+ reasoner.run();
306
+ const deletions = dedupe(input.deletions);
307
+ const derivedToRemove = reasoner.retract(deletions.filter((quad) => asserted.has(quadKey(quad))), "application");
308
+ for (const quad of deletions) asserted.delete(quadKey(quad));
309
+ const fresh = dedupe(input.insertions).filter((quad) => !asserted.has(quadKey(quad)));
310
+ return {
311
+ derivedToAdd: reasoner.extend(fresh, "application"),
312
+ derivedToRemove,
313
+ entailedDeletions: deletions.filter((quad) => !asserted.has(quadKey(quad)) && quad.predicate.termType === "NamedNode" && reasoner.has(quad.subject, quad.predicate, quad.object, quad.graph)),
314
+ inconsistencies: reasoner.inconsistencies()
315
+ };
316
+ }
317
+ function dedupe(quads) {
318
+ const seen = /* @__PURE__ */ new Map();
319
+ for (const quad of quads) seen.set(quadKey(quad), quad);
320
+ return [...seen.values()];
321
+ }
322
+ // src/cloudflare/shacl/create-d1-shacl-source.ts
323
+ /** MAX_SHAPE_QUADS is how large a world's shapes graph may be. */
324
+ const MAX_SHAPE_QUADS = 1e4;
325
+ const VALUES_PER_STATEMENT = 2e3;
326
+ const CHARACTERS_PER_STATEMENT = 4e5;
327
+ const COLUMNS = "s, s_type, p, o, o_type, o_datatype, o_lang, g, g_type";
328
+ /**
329
+ * readShapes reads a world's shapes, and the version the world had then. Without
330
+ * shapes there is no version, because no row carries it.
331
+ */
332
+ async function readShapes(options) {
333
+ const { connection, worldId, inferenceEnabled } = options;
334
+ const version = selectWorldVersion(options);
335
+ const { rows } = await connection.execute({
336
+ sql: `SELECT ${COLUMNS}, ${version.sql} FROM quads WHERE g = '${SHAPES_GRAPH}'${inferenceEnabled ? " AND derived = 0" : ""}${worldId ? " AND world_id = ?" : ""} LIMIT 10001`,
337
+ args: [...version.args, ...worldId ? [worldId] : []]
338
+ });
339
+ return {
340
+ shapes: rows.map(quadFromD1Row),
341
+ version: rows[0] && Number(rows[0].world_version)
342
+ };
343
+ }
344
+ /** createD1ShaclSource reads the facts that a SHACL check asks for from D1. */
345
+ function createD1ShaclSource(options) {
346
+ const { connection, worldId } = options;
347
+ async function select(condition, args, limit) {
348
+ const { rows } = await connection.execute({
349
+ sql: `SELECT ${COLUMNS} FROM quads WHERE ${condition}${worldId ? " AND +world_id = ?" : ""} LIMIT ${Math.min(Math.floor(limit), Number.MAX_SAFE_INTEGER)}`,
350
+ args: worldId ? [...args, worldId] : args
351
+ });
352
+ return rows.map(quadFromD1Row);
353
+ }
354
+ /** selectAmong runs one statement per group of values, up to one row over the limit. */
355
+ async function selectAmong(column, terms, predicates, limit) {
356
+ const found = [];
357
+ const among = (name) => `${name} IN (SELECT value FROM json_each(?))`;
358
+ for (const values of groupValues(terms)) {
359
+ const rows = await select(`${predicates ? `${among("p")} AND ` : ""}${among(column)} AND g <> '${SHAPES_GRAPH}'`, [...predicates ? [JSON.stringify(predicates)] : [], values], limit + 1 - found.length);
360
+ for (const row of rows) found.push(row);
361
+ if (found.length > limit) break;
362
+ }
363
+ return found;
364
+ }
365
+ return {
366
+ shapes: async () => (await readShapes(options)).shapes,
367
+ outgoing: ({ subjects, predicates, limit }) => selectAmong("s", subjects, predicates, limit),
368
+ incoming: ({ objects, predicate, limit }) => selectAmong("o", objects, [predicate], limit)
369
+ };
370
+ }
371
+ /** groupValues packs the terms' values into JSON lists that fit a D1 parameter. */
372
+ function* groupValues(terms) {
373
+ let group = [];
374
+ let characters = 0;
375
+ for (const value of new Set(terms.map((term) => term.value))) {
376
+ if ((group.length >= VALUES_PER_STATEMENT || characters + value.length > CHARACTERS_PER_STATEMENT) && group.length > 0) {
377
+ yield JSON.stringify(group);
378
+ group = [];
379
+ characters = 0;
380
+ }
381
+ group.push(value);
382
+ characters += value.length;
383
+ }
384
+ if (group.length > 0) yield JSON.stringify(group);
385
+ }
386
+ // src/cloudflare/shacl/check-d1-patch.ts
387
+ /**
388
+ * checkD1Patch rejects when a commit would add violations of the world's SHACL
389
+ * shapes, counting the inferred quads it adds and removes. Call it before
390
+ * anything is written. A world without shapes costs one indexed read, and never
391
+ * loads the validator.
392
+ *
393
+ * It returns what must still be true when the commit is written for the check to
394
+ * count. A replace import relies on nothing that is stored.
395
+ */
396
+ async function checkD1Patch(patch, context, options, derived) {
397
+ if (options.shacl?.enabled === false) return void 0;
398
+ const matches = filterQuads(options);
399
+ const insertions = patch.insertions.filter(matches);
400
+ const deletions = patch.deletions.filter(matches);
401
+ const sourceOptions = {
402
+ connection: options.connection,
403
+ worldId: options.worldId,
404
+ inferenceEnabled: options.inference?.enabled === true
405
+ };
406
+ const source = createD1ShaclSource(sourceOptions);
407
+ const replacing = isReplaceImportCommit(context);
408
+ const addsShapes = insertions.some(isShape);
409
+ const before = addsShapes && !replacing ? await readWorldVersion(options.connection, options) : void 0;
410
+ const { shapes, version = before } = replacing ? { shapes: [] } : await readShapes(sourceOptions);
411
+ if (shapes.length === 0 && !addsShapes) return replacing ? void 0 : "no shapes";
412
+ const { InvalidShapesError, validateWrite } = await import("@wazootech/worlds-sdk/shacl");
413
+ if (countShapesAfter(shapes, insertions, deletions) > 1e4) throw new InvalidShapesError([`A world can have at most ${MAX_SHAPE_QUADS} quads of shapes.`]);
414
+ await validateWrite({
415
+ patch: {
416
+ insertions: [...insertions, ...(derived?.added ?? []).filter((quad) => !isShape(quad))],
417
+ deletions: [...deletions, ...(derived?.removed ?? []).filter((quad) => !isShape(quad))]
418
+ },
419
+ context,
420
+ source: {
421
+ ...source,
422
+ shapes: () => Promise.resolve(shapes)
423
+ },
424
+ maxCheckedFacts: options.shacl?.maxCheckedFacts
425
+ });
426
+ return version === void 0 ? void 0 : { version };
427
+ }
428
+ function isShape(quad) {
429
+ return quad.graph.value === SHAPES_GRAPH;
430
+ }
431
+ function countShapesAfter(stored, insertions, deletions) {
432
+ const keys = new Set(stored.map(quadKey));
433
+ for (const quad of deletions) keys.delete(quadKey(quad));
434
+ for (const quad of insertions) if (isShape(quad)) keys.add(quadKey(quad));
435
+ return keys.size;
436
+ }
437
+ // src/cloudflare/inference/load-asserted-quads.ts
438
+ /** DEFAULT_MAX_ASSERTED_QUADS is the default inference size guard. */
439
+ const DEFAULT_MAX_ASSERTED_QUADS = 1e5;
440
+ const PAGE_SIZE = 1e3;
441
+ /** InferenceSizeGuardError is thrown, before any write, when a world is too big to reason over. */
442
+ var InferenceSizeGuardError = class extends Error {
443
+ assertedQuads;
444
+ maxAssertedQuads;
445
+ constructor(assertedQuads, maxAssertedQuads) {
446
+ super(`inference size guard: ${assertedQuads} asserted quads exceed maxAssertedQuads (${maxAssertedQuads}); each commit rebuilds the reasoner from all asserted quads. Disable inference for this world or raise the limit.`);
447
+ this.assertedQuads = assertedQuads;
448
+ this.maxAssertedQuads = maxAssertedQuads;
449
+ this.name = "InferenceSizeGuardError";
450
+ }
451
+ };
452
+ /**
453
+ * loadAssertedQuads reads every asserted (derived = 0) quad of the world,
454
+ * failing with InferenceSizeGuardError when `pendingInsertions` more would
455
+ * exceed `maxAssertedQuads`.
456
+ */
457
+ async function loadAssertedQuads(connection, options) {
458
+ const count = await connection.execute(buildCountAssertedQuads(options.worldId));
459
+ const total = Number(count.rows[0]?.count ?? 0);
460
+ if (total + options.pendingInsertions > options.maxAssertedQuads) throw new InferenceSizeGuardError(total + options.pendingInsertions, options.maxAssertedQuads);
461
+ const quads = [];
462
+ let afterQuadId;
463
+ for (;;) {
464
+ const page = await connection.execute(buildSelectAssertedQuadsPage({
465
+ afterQuadId,
466
+ limit: PAGE_SIZE
467
+ }, options.worldId));
468
+ for (const row of page.rows) quads.push(quadFromD1Row(row));
469
+ if (page.rows.length < PAGE_SIZE) return quads;
470
+ afterQuadId = String(page.rows[page.rows.length - 1].id);
471
+ }
472
+ }
473
+ // src/cloudflare/commit/d1-derived-changes.ts
474
+ /**
475
+ * planD1DerivedChanges reasons over the world's asserted quads before the
476
+ * commit writes anything, so a size-guard failure leaves the world untouched.
477
+ * A replace import wipes the world first, so nothing existing counts.
478
+ */
479
+ async function planD1DerivedChanges(patch, context, inference, driverOptions) {
480
+ const prepared = preparePatch(patch, driverOptions);
481
+ const maxAssertedQuads = inference.maxAssertedQuads ?? 1e5;
482
+ const replacing = isReplaceImportCommit(context);
483
+ if (replacing && prepared.insertions.length > maxAssertedQuads) throw new InferenceSizeGuardError(prepared.insertions.length, maxAssertedQuads);
484
+ const plan = planInference({
485
+ assertedBefore: replacing ? [] : await loadAssertedQuads(driverOptions.connection, {
486
+ worldId: driverOptions.worldId,
487
+ maxAssertedQuads,
488
+ pendingInsertions: prepared.insertions.length
489
+ }),
490
+ deletions: prepared.deletions,
491
+ insertions: prepared.insertions,
492
+ graphs: inference.graphs
493
+ });
494
+ const addRows = /* @__PURE__ */ new Map();
495
+ const derived = [...plan.derivedToAdd, ...plan.entailedDeletions];
496
+ const derivedIds = hashQuads(derived);
497
+ derived.forEach((quad, index) => {
498
+ const id = derivedIds[index];
499
+ if (!addRows.has(id)) addRows.set(id, {
500
+ ...buildInsertRow(quad, id),
501
+ world_id: driverOptions.worldId,
502
+ derived: 1
503
+ });
504
+ });
505
+ return {
506
+ removeIds: hashQuads(plan.derivedToRemove),
507
+ addRows: [...addRows.values()],
508
+ removed: plan.derivedToRemove,
509
+ added: derived
510
+ };
511
+ }
512
+ // src/cloudflare/commit/remember-embeddings.ts
513
+ /**
514
+ * rememberEmbeddings embeds each text once, however often a commit is planned.
515
+ * Embedding is the slow and paid part, and the longer an attempt takes, the likelier
516
+ * another write gets in between.
517
+ */
518
+ function rememberEmbeddings(service) {
519
+ const known = /* @__PURE__ */ new Map();
520
+ return { async embed(texts) {
521
+ const unknown = texts.filter((text) => !known.has(text));
522
+ if (unknown.length > 0) (await service.embed(unknown)).forEach((vector, i) => known.set(unknown[i], vector));
523
+ return texts.map((text) => known.get(text));
524
+ } };
525
+ }
526
+ /** No single wait is longer than this, in milliseconds. */
527
+ const LONGEST_WAIT = 5e3;
528
+ /**
529
+ * ConcurrentWriteError is thrown when other writes changed the world during every
530
+ * attempt to commit. Nothing was written, so the same write can be sent again.
531
+ */
532
+ var ConcurrentWriteError = class extends Error {
533
+ constructor(options) {
534
+ super(`Other writes changed this world during all 8 attempts to commit. Nothing was written. Try again.`, options);
535
+ this.name = "ConcurrentWriteError";
536
+ }
537
+ };
538
+ /**
539
+ * retryOnConflict runs `attempt` again when another write got in between its reads
540
+ * and its batch. Any other error would come back the same, so it is thrown.
541
+ *
542
+ * Writes that collide need random waits that are long compared with an attempt, or
543
+ * they collide again. So a wait is at most twice as long as the attempt before it
544
+ * took, and that factor doubles each time.
545
+ */
546
+ async function retryOnConflict(attempt) {
547
+ for (let tried = 1;; tried++) {
548
+ const start = performance.now();
549
+ try {
550
+ return await attempt();
551
+ } catch (error) {
552
+ if (!isVersionConflict(error)) throw error;
553
+ if (tried === 8) throw new ConcurrentWriteError({ cause: error });
554
+ }
555
+ const took = performance.now() - start;
556
+ const longest = Math.min(took * 2 ** tried, LONGEST_WAIT);
557
+ const wait = Math.random() * longest;
558
+ await new Promise((resolve) => setTimeout(resolve, wait));
559
+ }
560
+ }
561
+ // src/cloudflare/commit/with-world-version.ts
562
+ /**
563
+ * withWorldVersion makes a commit's first statement the one that counts it and
564
+ * checks `condition`, so a commit that can't go ahead writes nothing. Apply it last,
565
+ * and create one per commit.
566
+ *
567
+ * A commit too large for one batch checks the condition in its first batch only. Its
568
+ * other batches count as writes too, so a commit that read a half-written world
569
+ * plans again. Call `finish` when the last one is written.
570
+ */
571
+ function withWorldVersion(driver, dialect, scope, condition) {
572
+ const first = buildRaiseVersion(scope, condition);
573
+ const counting = buildRaiseVersion(scope);
574
+ const pending = [first];
575
+ let writing = true;
576
+ return {
577
+ driver: {
578
+ ...driver,
579
+ maxBatchWeight: driver.maxBatchWeight && Math.max(0, driver.maxBatchWeight - d1StatementWeight(counting)),
580
+ executeBatch: (statements) => driver.executeBatch(!writing || statements.includes(first) ? statements : [...statements, counting])
581
+ },
582
+ dialect: {
583
+ ...dialect,
584
+ buildWipe: () => [...pending.splice(0), ...dialect.buildWipe()],
585
+ buildDeletions: (keys, hashes) => [...pending.splice(0), ...dialect.buildDeletions(keys, hashes)]
586
+ },
587
+ finish: () => {
588
+ writing = false;
589
+ }
590
+ };
591
+ }
592
+ // src/cloudflare/commit/commit-d1-patch.ts
593
+ /**
594
+ * commitD1Patch runs one D1 commit through the shared SQL commit core
595
+ * (`commitSqlPatch`). D1 batches are not atomic with the outside-D1 Vectorize
596
+ * index, which the platform forces: vectors sync after the D1 write lands, and
597
+ * a failure there is logged drift that a reindex repairs. An embedding failure
598
+ * throws before anything is written, so the caller can retry. So does a SHACL
599
+ * violation. Imports project
600
+ * chunks during the commit (`searchIndexOnImport` defaults to the shared
601
+ * `"incremental"`); `"deferred"` stays available as an option.
602
+ *
603
+ * Inference and SHACL checks read the world before the batch. When another write
604
+ * gets in between, the batch fails and the commit is planned again.
605
+ */
606
+ async function commitD1Patch(patch, context, options) {
607
+ const projection = options.searchIndexProjector?.projection;
608
+ const embeddingService = projection?.embeddingService && rememberEmbeddings(projection.embeddingService);
609
+ await retryOnConflict(() => tryCommit(patch, context, options, projection && {
610
+ ...projection,
611
+ embeddingService
612
+ }));
613
+ }
614
+ /** tryCommit plans and writes the commit once. */
615
+ async function tryCommit(patch, context, options, projection) {
616
+ const { connection, worldId, searchIndexProjector: projector } = options;
617
+ const sync = projector?.createVectorSync();
618
+ const driverOptions = {
619
+ ...options,
620
+ connection,
621
+ inferenceEnabled: options.inference?.enabled === true,
622
+ beforePage: sync?.beforePage
623
+ };
624
+ const version = options.inference?.enabled && !isReplaceImportCommit(context) ? await readWorldVersion(connection, options) : void 0;
625
+ const derived = options.inference?.enabled ? await planD1DerivedChanges(patch, context, options.inference, driverOptions) : void 0;
626
+ const checked = await checkD1Patch(patch, context, options, derived);
627
+ const driver = createD1CommitDriver(driverOptions);
628
+ const provenance = options.provenance?.enabled ? await planD1Provenance(patch, context, driver, driverOptions) : void 0;
629
+ const indexing = planSearchIndexing(options.searchIndexOnImport, context);
630
+ const dialect = createD1CommitDialect({
631
+ searchQueryBuilder: options.searchQueryBuilder,
632
+ worldId,
633
+ lookupChunkSize: effectiveLookupChunkSize(options.maxLookupChunkSize, Boolean(worldId)),
634
+ derived,
635
+ onChunkRows: sync?.collect
636
+ });
637
+ const recorded = provenance ? withProvenance(driver, dialect, provenance) : {
638
+ driver,
639
+ dialect
640
+ };
641
+ const commit = withWorldVersion(recorded.driver, recorded.dialect, options, version === void 0 ? checked : { version });
642
+ await commitSqlPatch(patch, context, commit.driver, commit.dialect, {
643
+ filter: options,
644
+ searchIndexOnImport: options.searchIndexOnImport,
645
+ projection,
646
+ rebuildPageSize: DEFAULT_D1_MATCH_PAGE_SIZE,
647
+ afterWrite: async () => {
648
+ commit.finish();
649
+ if (indexing.reindexAfterCommit ? isFullRebuild(options) : isReplaceImportCommit(context) && indexing.projectDuringCommit) await sync?.purgeWorld();
650
+ await sync?.flush();
651
+ }
652
+ });
653
+ await sync?.flush();
654
+ sync?.logDrift(indexing.reindexAfterCommit ? "reindex" : "import");
655
+ }
656
+ // src/cloudflare/provenance/d1-provenance-store.ts
657
+ /** recordFromRow maps a `provenance` row to the SDK's record, omitting empty fields. */
658
+ function recordFromRow(row) {
659
+ return {
660
+ quadId: String(row.quad_id),
661
+ recordedAt: String(row.recorded_at),
662
+ type: row.type,
663
+ ...row.writer != null && { writer: String(row.writer) },
664
+ ...row.source != null && { source: String(row.source) },
665
+ ...row.supersedes_quad_id != null && { supersedesQuadId: String(row.supersedes_quad_id) }
666
+ };
667
+ }
668
+ /**
669
+ * D1ProvenanceStore is the durable ProvenanceStore over the `provenance` table.
670
+ * Commits do not go through `record`: they write their records in the same batch
671
+ * as the quads (see `planD1Provenance`).
672
+ */
673
+ var D1ProvenanceStore = class {
674
+ options;
675
+ constructor(options) {
676
+ this.options = options;
677
+ }
678
+ /** record appends one record on its own, outside any commit. */
679
+ async record(input) {
680
+ const recordedAt = input.recordedAt ?? (/* @__PURE__ */ new Date()).toISOString();
681
+ const type = input.type ?? "write";
682
+ await this.options.connection.batch(buildInsertProvenance(type, [[input.quadId, input.supersedesQuadId]], {
683
+ recordedAt,
684
+ writer: input.writer,
685
+ source: input.source
686
+ }, this.options.worldId));
687
+ return {
688
+ ...input,
689
+ recordedAt,
690
+ type
691
+ };
692
+ }
693
+ /** list returns matching records, oldest first. */
694
+ async list(query) {
695
+ const { rows } = await this.options.connection.execute(buildSelectProvenance(query ?? {}, this.options.worldId));
696
+ return rows.map(recordFromRow);
697
+ }
698
+ /** history walks what the quad replaced and what replaced it. */
699
+ async history(quadId) {
700
+ return await (await this.load([quadId])).history(quadId);
701
+ }
702
+ /**
703
+ * load reads the records of `quadIds` in one query, with their full correction
704
+ * chains unless `chains` is false, into the SDK's in-memory store, so walks
705
+ * behave exactly as they do there.
706
+ */
707
+ async load(quadIds, chains = true) {
708
+ const build = chains ? buildSelectProvenanceChains : buildSelectQuadRecords;
709
+ const { rows } = await this.options.connection.execute(build(quadIds, this.options.worldId));
710
+ const loaded = new InMemoryProvenanceStore();
711
+ for (const row of rows) await loaded.record(recordFromRow(row));
712
+ return loaded;
713
+ }
714
+ };
715
+ // src/cloudflare/provenance/query-d1-provenance.ts
716
+ /** matchQuads reads the quads matching the pattern, fetching no page past the limit. */
717
+ async function matchQuads(request, options) {
718
+ const limit = request.limit ?? 1e400;
719
+ const pageSize = options.matchPageSize ?? 1e3;
720
+ const quads = [];
721
+ for await (const quad of matchD1Pages(options.connection, Math.min(pageSize, limit), options.worldId, request.subject, request.predicate, request.object)) {
722
+ quads.push(quad);
723
+ if (quads.length >= limit) break;
724
+ }
725
+ return quads;
726
+ }
727
+ /**
728
+ * queryD1Provenance pairs each quad matching the pattern, up to the request's
729
+ * limit, with its records and history. Quads written before the world opted in come back with none.
730
+ */
731
+ async function queryD1Provenance(request, options) {
732
+ const chains = options.provenance?.history !== false;
733
+ const provenance = new D1ProvenanceStore(options);
734
+ const quads = await matchQuads(request, options);
735
+ const ids = quads.length > 0 ? hashQuads(quads) : [];
736
+ const results = [];
737
+ for (const group of chunk(ids)) {
738
+ const loaded = await provenance.load(group, chains);
739
+ for (const quadId of group) results.push({
740
+ quadId,
741
+ quad: quads[results.length],
742
+ records: await loaded.list({ quadId }),
743
+ history: chains ? await loaded.history(quadId) : {
744
+ quadId,
745
+ supersedes: [],
746
+ supersededBy: []
747
+ }
748
+ });
749
+ }
750
+ return { results };
751
+ }
752
+ // src/cloudflare/quad-store/d1-quad-store.ts
753
+ /**
754
+ * D1QuadStore implements the QuadStoreInterface for D1 backed durable persistence.
755
+ * It encapsulates transaction routing, commits, and indexing synchronization.
756
+ */
757
+ var D1QuadStore = class {
758
+ options;
759
+ constructor(options) {
760
+ this.options = options;
761
+ }
762
+ /**
763
+ * import merges or replaces the underlying store with provided RDF source data.
764
+ *
765
+ * @param request The payload defining the ingestion source and overwrite mode.
766
+ */
767
+ async import(request) {
768
+ await importViaTransaction(request, { createTransaction: () => this.createTransaction() });
769
+ }
770
+ /**
771
+ * export extracts the graph contents in raw quads or serialized formats.
772
+ *
773
+ * @param request The desired format specifications.
774
+ */
775
+ async export(request) {
776
+ return await exportFromRdfjsStore(this.options.store, request);
777
+ }
778
+ /**
779
+ * provenanceQuery returns the records and correction history of the quads
780
+ * matching the pattern. It rejects when the world has not opted in.
781
+ */
782
+ async provenanceQuery(request) {
783
+ if (!this.options.provenance?.enabled) throw new Error("Provenance is not configured.");
784
+ return await queryD1Provenance(request, this.options);
785
+ }
786
+ /**
787
+ * createTransaction returns a pre-configured Transaction bound to internal commit hooks.
788
+ * Its commit uses `defaults` when it is given no context of its own.
789
+ */
790
+ createTransaction(defaults) {
791
+ return new Transaction({ commit: (patch, context) => commitD1Patch(patch, context ?? defaults, this.options) });
792
+ }
793
+ };
794
+ export { InferenceSizeGuardError as a, DEFAULT_MAX_ASSERTED_QUADS as i, D1ProvenanceStore as n, loadAssertedQuads as o, ConcurrentWriteError as r, planInference as s, D1QuadStore as t };