@wazootech/worlds-cloudflare 0.0.0-stage → 0.15.6

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,166 @@
1
+ import { _ as effectiveLookupChunkSize, a as buildSelectAssertedQuadsPage, c as buildDeleteDerivedQuadsByQuadIds, f as buildInsertRow, i as buildMatchQuadsQuery, l as buildDeleteQuadsByQuadIds, o as buildSelectExistingQuadIds, p as quadFromD1Row, t as buildBulkInsertQuads, u as buildWipeAllGraphDataStatements } from "./d1-quad-insert-sql-B4ZiZZe8.js";
2
+ import { buildChunkFtsValue } from "@wazootech/worlds-sqlite/sql-core";
3
+ import { filterQuads } from "@wazootech/worlds-sdk/quad-store";
4
+ // src/cloudflare/commit/d1-commit-dialect.ts
5
+ /** chunked slices `ids` into IN-clause sized groups and builds one statement per group. */
6
+ function chunked(ids, size, build) {
7
+ const statements = [];
8
+ for (let index = 0; index < ids.length; index += size) statements.push(build(ids.slice(index, index + size)));
9
+ return statements;
10
+ }
11
+ /**
12
+ * createD1CommitDialect builds one commit's statements. Create one per commit:
13
+ * the inference change set rides the first `buildDeletions` call, which the
14
+ * core makes whenever the patch deletes or writes anything, and every quad
15
+ * delete in that call precedes the derived writes, as inference requires.
16
+ *
17
+ * `buildDeletions` removes quad rows only. A deleted quad's chunk rows stay
18
+ * until an unscoped reindex or the hosted API's orphan cleanup: they are the only record
19
+ * of the vector ids to remove from the outside-D1 vector index.
20
+ */
21
+ function createD1CommitDialect(options) {
22
+ const { worldId, lookupChunkSize, searchQueryBuilder, derived } = options;
23
+ let derivedPending = derived;
24
+ const deleteChunks = (ids) => chunked(ids, lookupChunkSize, (chunk) => searchQueryBuilder.buildDeleteByQuadIds(chunk));
25
+ const takeDerivedStatements = () => {
26
+ const changes = derivedPending;
27
+ derivedPending = void 0;
28
+ if (!changes) return [];
29
+ return [...chunked(changes.removeIds, lookupChunkSize, (chunk) => buildDeleteDerivedQuadsByQuadIds(chunk, worldId)), ...buildBulkInsertQuads(changes.addRows, { orIgnore: true })];
30
+ };
31
+ return {
32
+ keyOf: (_quad, hash) => hash,
33
+ buildWipe: () => buildWipeAllGraphDataStatements(worldId),
34
+ buildClearChunks: () => [searchQueryBuilder.buildClearChunks()],
35
+ buildDeleteChunks: deleteChunks,
36
+ buildDeletions: (keys) => [...chunked(keys, lookupChunkSize, (chunk) => buildDeleteQuadsByQuadIds(chunk, worldId)), ...takeDerivedStatements()],
37
+ buildInserts: (quads, _keys, hashes) => buildBulkInsertQuads(quads.map((quad, index) => ({
38
+ ...buildInsertRow(quad, hashes[index]),
39
+ world_id: worldId,
40
+ ...derived && { derived: 0 }
41
+ }))),
42
+ buildChunkRows: (rows) => {
43
+ options.onChunkRows?.(rows);
44
+ return [...deleteChunks([...new Set(rows.map((row) => row.chunk.quad_id))]), ...rows.map(({ chunk, ftsValue, vector }) => searchQueryBuilder.buildInsertChunk({
45
+ quad_id: chunk.quad_id,
46
+ subject: chunk.subject,
47
+ predicate: chunk.predicate,
48
+ graph: chunk.graph,
49
+ value: chunk.value,
50
+ fts_value: ftsValue,
51
+ vector: vector ? new Float32Array(vector) : void 0,
52
+ world_id: worldId
53
+ }))];
54
+ },
55
+ buildCleanup: (keys) => [...chunked(keys, lookupChunkSize, (chunk) => buildDeleteQuadsByQuadIds(chunk, worldId)), ...deleteChunks(keys)]
56
+ };
57
+ }
58
+ // src/cloudflare/d1/d1-statement-weight.ts
59
+ /**
60
+ * DEFAULT_D1_MAX_BATCH_WEIGHT is the estimated serialized bytes one D1
61
+ * `batch()` call may carry (16 MiB). The Worker-to-D1 RPC rejects a batch whose
62
+ * serialized arguments exceed 32 MiB (measured on a real D1, 2026-11-22, see
63
+ * README), so this leaves 2x headroom for the estimator's error.
64
+ */
65
+ const DEFAULT_D1_MAX_BATCH_WEIGHT = 16777216;
66
+ /** paramWeight estimates one bound parameter's serialized bytes. */
67
+ function paramWeight(value) {
68
+ if (typeof value === "string") return value.length + 2;
69
+ if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) return value.byteLength * 4;
70
+ if (Array.isArray(value)) return value.reduce((sum, item) => sum + paramWeight(item), 0);
71
+ return 8;
72
+ }
73
+ /**
74
+ * d1StatementWeight ESTIMATES the serialized bytes of one D1 statement: the SQL
75
+ * text length, a fixed overhead, and each bound parameter (strings by UTF-16
76
+ * code units, BLOBs at `BLOB_BYTE_WEIGHT` per byte, scalars a few bytes). It is
77
+ * calibrated from measured real-D1 points, not a contract, and errs high.
78
+ */
79
+ function d1StatementWeight(statement) {
80
+ let weight = statement.sql.length + 64;
81
+ for (const arg of statement.args ?? []) weight += paramWeight(arg);
82
+ return weight;
83
+ }
84
+ // src/cloudflare/commit/d1-commit-driver.ts
85
+ /**
86
+ * createD1CommitDriver adapts a D1 connection to the shared core's driver. D1's
87
+ * atomic unit is one `batch()` call. Cloudflare documents no statement cap for
88
+ * it, so the atomic limit is the chosen write batch size plus a byte budget
89
+ * (the binding rejects a batch over 32 MiB serialized): a commit that fits both
90
+ * is atomic, a larger one takes the core's chunked fallback with cleanup.
91
+ */
92
+ function createD1CommitDriver(options) {
93
+ const { connection, worldId } = options;
94
+ const batchSize = options.maxWriteBatchSize ?? 2e3;
95
+ const lookupChunkSize = effectiveLookupChunkSize(options.maxLookupChunkSize, Boolean(worldId));
96
+ const matches = filterQuads(options);
97
+ const driver = {
98
+ maxAtomicStatements: batchSize,
99
+ writeBatchSize: batchSize,
100
+ statementWeight: d1StatementWeight,
101
+ maxBatchWeight: options.maxBatchWeight ?? 16777216,
102
+ processedQuadCount: 0,
103
+ executeBatch: (statements) => connection.batch(statements),
104
+ async lookupExisting(keys) {
105
+ const existing = /* @__PURE__ */ new Set();
106
+ for (let index = 0; index < keys.length; index += lookupChunkSize) {
107
+ const { rows } = await connection.execute(buildSelectExistingQuadIds(keys.slice(index, index + lookupChunkSize), worldId, { assertedOnly: options.inferenceEnabled === true }));
108
+ for (const row of rows) if (row.id) existing.add(String(row.id));
109
+ }
110
+ return existing;
111
+ },
112
+ async streamQuads({ after, pageSize }) {
113
+ const afterQuadId = after;
114
+ const { rows } = await connection.execute(options.inferenceEnabled ? buildSelectAssertedQuadsPage({
115
+ afterQuadId,
116
+ limit: pageSize
117
+ }, worldId) : buildMatchQuadsQuery({
118
+ subject: null,
119
+ predicate: null,
120
+ object: null,
121
+ graph: null
122
+ }, {
123
+ afterQuadId,
124
+ limit: pageSize
125
+ }, worldId));
126
+ const quads = [];
127
+ for (const row of rows) try {
128
+ const quad = quadFromD1Row(row);
129
+ if (matches(quad)) quads.push(quad);
130
+ driver.processedQuadCount++;
131
+ } catch (error) {
132
+ console.warn(`D1 rebuild: skipping corrupt row s="${row.s}"`, error);
133
+ }
134
+ if (quads.length > 0) await options.beforePage?.(quads);
135
+ const last = rows[rows.length - 1];
136
+ return {
137
+ quads,
138
+ next: rows.length >= pageSize && last ? String(last.id) : void 0
139
+ };
140
+ }
141
+ };
142
+ return driver;
143
+ }
144
+ // src/cloudflare/search-index/project-search-chunks-options.ts
145
+ function vectorSyncEnabled(options) {
146
+ return Boolean(options.embeddingService && options.vectorSearch);
147
+ }
148
+ /**
149
+ * toProjectionOptions maps D1's options to the shared core's chunking and
150
+ * embedding options. Embedding runs only when both an embedding service and a
151
+ * vector index are wired; an embedding failure throws, as on every backend.
152
+ */
153
+ function toProjectionOptions(options) {
154
+ return {
155
+ textSplitter: options.textSplitter,
156
+ embeddingService: vectorSyncEnabled(options) ? options.embeddingService : void 0,
157
+ ftsValueOf: buildChunkFtsValue,
158
+ vectorDimensions: options.vectorDimensions ?? options.searchQueryBuilder.vectorDimensions
159
+ };
160
+ }
161
+ /** isFullRebuild is true when no include/exclude filter narrows a search-index rebuild. */
162
+ function isFullRebuild(filter) {
163
+ const narrows = (criteria) => Boolean(criteria?.subjects?.length || criteria?.predicates?.length || criteria?.graphs?.length);
164
+ return !narrows(filter.include) && !narrows(filter.exclude);
165
+ }
166
+ export { DEFAULT_D1_MAX_BATCH_WEIGHT as a, createD1CommitDriver as i, toProjectionOptions as n, d1StatementWeight as o, vectorSyncEnabled as r, createD1CommitDialect as s, isFullRebuild as t };
@@ -0,0 +1,398 @@
1
+ import { InMemoryProvenanceStore, Transaction, exportFromRdfjsStore, hashQuads, importViaTransaction, isReplaceImportCommit, preparePatch } 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 buildSelectProvenance, c as chunk, n as buildDeleteWriteRecords, o as buildSelectProvenanceChains, r as buildInsertProvenance, s as buildSelectQuadRecords, t as PROVENANCE_IDS_PER_STATEMENT } from "./d1-provenance-sql-jn_cwWxX.js";
6
+ import { i as createD1CommitDriver, s as createD1CommitDialect, t as isFullRebuild } from "./project-search-chunks-options-qI9m5FWz.js";
7
+ import { Reasoner } from "@wazootech/reasoner";
8
+ import { r as matchD1Pages } from "./d1-rdfjs-store-read-2QTEEe_a.js";
9
+ // src/cloudflare/provenance/read-stored-quads.ts
10
+ /** selectStored runs one read; it names `derived` only when inference guarantees the column. */
11
+ async function selectStored(condition, arg, options) {
12
+ const { rows } = await options.connection.execute({
13
+ sql: `SELECT quad_id AS id, s, p, g FROM quads WHERE ${condition}${options.worldId ? " AND world_id = ?" : ""}${options.inferenceEnabled ? " AND derived = 0" : ""} ORDER BY quad_id LIMIT ${PROVENANCE_IDS_PER_STATEMENT}`,
14
+ args: [arg, ...options.worldId ? [options.worldId] : []]
15
+ });
16
+ return rows;
17
+ }
18
+ /** lookupStoredQuads yields the quads among `ids` that the world holds. */
19
+ async function* lookupStoredQuads(ids, options) {
20
+ for (const group of chunk([...new Set(ids)])) yield* await selectStored("quad_id IN (SELECT value FROM json_each(?))", JSON.stringify(group), options);
21
+ }
22
+ /** streamStoredQuads yields every quad of the world, a page at a time. */
23
+ async function* streamStoredQuads(options) {
24
+ let after = "";
25
+ for (;;) {
26
+ const rows = await selectStored("quad_id > ?", after, options);
27
+ yield* rows;
28
+ if (rows.length < 5e3) return;
29
+ after = rows[rows.length - 1].id;
30
+ }
31
+ }
32
+ // src/cloudflare/provenance/plan-d1-provenance.ts
33
+ /** positionKey identifies the statement a quad makes; a correction changes only the object. */
34
+ function positionKey(s, p, g) {
35
+ return JSON.stringify([
36
+ s,
37
+ p,
38
+ g
39
+ ]);
40
+ }
41
+ function positionOf(quad) {
42
+ return positionKey(quad.subject.value, quad.predicate.value, quad.graph.value);
43
+ }
44
+ /**
45
+ * planD1Provenance works out, before anything is written, which quads a commit
46
+ * really adds and removes. A quad the world already holds gets no new record, so
47
+ * importing the same data again neither grows the table nor makes an old quad
48
+ * look newly written. The SDK's in-memory store records every insertion instead.
49
+ */
50
+ async function planD1Provenance(patch, context, options) {
51
+ const { worldId } = options;
52
+ const replacing = isReplaceImportCommit(context);
53
+ const prepared = preparePatch(patch, options);
54
+ const inserted = new Map(prepared.insertionIds.map((id, i) => [id, prepared.insertions[i]]));
55
+ const insertedPositions = new Set([...inserted.values()].map(positionOf));
56
+ const kept = [];
57
+ const removed = [];
58
+ const supersededAt = /* @__PURE__ */ new Map();
59
+ const stored = replacing ? streamStoredQuads(options) : lookupStoredQuads([...inserted.keys(), ...prepared.deletionIds], options);
60
+ for await (const row of stored) {
61
+ if (inserted.has(row.id)) {
62
+ kept.push(row.id);
63
+ continue;
64
+ }
65
+ removed.push([row.id]);
66
+ const position = positionKey(row.s, row.p, row.g);
67
+ if (insertedPositions.has(position)) supersededAt.set(position, row.id);
68
+ }
69
+ const keptIds = new Set(kept);
70
+ const written = [];
71
+ for (const [id, quad] of inserted) if (!keptIds.has(id)) written.push([id, supersededAt.get(positionOf(quad))]);
72
+ const lostByCleanup = replacing ? kept : [];
73
+ const stamp = {
74
+ ...context?.provenance,
75
+ recordedAt: (/* @__PURE__ */ new Date()).toISOString()
76
+ };
77
+ return {
78
+ removals: buildInsertProvenance("remove", removed, stamp, worldId),
79
+ writes: buildInsertProvenance("write", written, stamp, worldId),
80
+ cleanup: [...buildDeleteWriteRecords(written.map(([id]) => id), stamp.recordedAt, worldId), ...buildInsertProvenance("remove", lostByCleanup.map((id) => [id]), stamp, worldId)]
81
+ };
82
+ }
83
+ // src/cloudflare/provenance/with-provenance.ts
84
+ /**
85
+ * withProvenance adds a plan's statements to a commit dialect, so they join the
86
+ * commit's own batch: removals before the first delete or wipe, writes after the
87
+ * quads they describe. Create one per commit, like the dialect itself.
88
+ */
89
+ function withProvenance(dialect, plan) {
90
+ const pendingRemovals = [...plan.removals];
91
+ const takeRemovals = () => pendingRemovals.splice(0);
92
+ return {
93
+ ...dialect,
94
+ buildWipe: () => [...takeRemovals(), ...dialect.buildWipe()],
95
+ buildDeletions: (keys, hashes) => [...takeRemovals(), ...dialect.buildDeletions(keys, hashes)],
96
+ buildInserts: (quads, keys, hashes) => [...dialect.buildInserts(quads, keys, hashes), ...plan.writes],
97
+ buildCleanup: (keys, hashes) => [...dialect.buildCleanup(keys, hashes), ...plan.cleanup]
98
+ };
99
+ }
100
+ // src/cloudflare/inference/inference-planner.ts
101
+ /** quadKey identifies a quad by term type and value, datatype and language included. */
102
+ function quadKey(quad) {
103
+ return [
104
+ quad.subject,
105
+ quad.predicate,
106
+ quad.object,
107
+ quad.graph
108
+ ].map((term) => {
109
+ if (term.termType === "Literal") return `L|${term.value}|${term.datatype.value}|${term.language}`;
110
+ return `${term.termType}|${term.value}`;
111
+ }).join("\0");
112
+ }
113
+ /**
114
+ * planInference reasons about one patch.
115
+ *
116
+ * It rebuilds a Reasoner from the asserted quads (the reasoner has no
117
+ * serialize/restore, so there is no persisted state to resume), runs it, then
118
+ * uses `retract` and `extend` to get exactly the inferred quads the patch
119
+ * removes and adds instead of diffing two closures. The result is correct only
120
+ * if the stored inferred rows equal the closure of `assertedBefore`; a world
121
+ * that had data before inference was enabled needs a one-time rebuild.
122
+ */
123
+ function planInference(input) {
124
+ const reasoner = new Reasoner({ graphs: input.graphs ?? "per-graph" });
125
+ const asserted = /* @__PURE__ */ new Map();
126
+ for (const quad of input.assertedBefore) asserted.set(quadKey(quad), quad);
127
+ reasoner.add(asserted.values());
128
+ reasoner.run();
129
+ const deletions = dedupe(input.deletions);
130
+ const derivedToRemove = reasoner.retract(deletions.filter((quad) => asserted.has(quadKey(quad))), "application");
131
+ for (const quad of deletions) asserted.delete(quadKey(quad));
132
+ const fresh = dedupe(input.insertions).filter((quad) => !asserted.has(quadKey(quad)));
133
+ return {
134
+ derivedToAdd: reasoner.extend(fresh, "application"),
135
+ derivedToRemove,
136
+ entailedDeletions: deletions.filter((quad) => !asserted.has(quadKey(quad)) && quad.predicate.termType === "NamedNode" && reasoner.has(quad.subject, quad.predicate, quad.object, quad.graph)),
137
+ inconsistencies: reasoner.inconsistencies()
138
+ };
139
+ }
140
+ function dedupe(quads) {
141
+ const seen = /* @__PURE__ */ new Map();
142
+ for (const quad of quads) seen.set(quadKey(quad), quad);
143
+ return [...seen.values()];
144
+ }
145
+ // src/cloudflare/inference/load-asserted-quads.ts
146
+ /** DEFAULT_MAX_ASSERTED_QUADS is the default inference size guard. */
147
+ const DEFAULT_MAX_ASSERTED_QUADS = 1e5;
148
+ const PAGE_SIZE = 1e3;
149
+ /** InferenceSizeGuardError is thrown, before any write, when a world is too big to reason over. */
150
+ var InferenceSizeGuardError = class extends Error {
151
+ assertedQuads;
152
+ maxAssertedQuads;
153
+ constructor(assertedQuads, maxAssertedQuads) {
154
+ 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.`);
155
+ this.assertedQuads = assertedQuads;
156
+ this.maxAssertedQuads = maxAssertedQuads;
157
+ this.name = "InferenceSizeGuardError";
158
+ }
159
+ };
160
+ /**
161
+ * loadAssertedQuads reads every asserted (derived = 0) quad of the world,
162
+ * failing with InferenceSizeGuardError when `pendingInsertions` more would
163
+ * exceed `maxAssertedQuads`.
164
+ */
165
+ async function loadAssertedQuads(connection, options) {
166
+ const count = await connection.execute(buildCountAssertedQuads(options.worldId));
167
+ const total = Number(count.rows[0]?.count ?? 0);
168
+ if (total + options.pendingInsertions > options.maxAssertedQuads) throw new InferenceSizeGuardError(total + options.pendingInsertions, options.maxAssertedQuads);
169
+ const quads = [];
170
+ let afterQuadId;
171
+ for (;;) {
172
+ const page = await connection.execute(buildSelectAssertedQuadsPage({
173
+ afterQuadId,
174
+ limit: PAGE_SIZE
175
+ }, options.worldId));
176
+ for (const row of page.rows) quads.push(quadFromD1Row(row));
177
+ if (page.rows.length < PAGE_SIZE) return quads;
178
+ afterQuadId = String(page.rows[page.rows.length - 1].id);
179
+ }
180
+ }
181
+ // src/cloudflare/commit/d1-derived-changes.ts
182
+ /**
183
+ * planD1DerivedChanges reasons over the world's asserted quads before the
184
+ * commit writes anything, so a size-guard failure leaves the world untouched.
185
+ * A replace import wipes the world first, so nothing existing counts.
186
+ */
187
+ async function planD1DerivedChanges(patch, context, inference, driverOptions) {
188
+ const prepared = preparePatch(patch, driverOptions);
189
+ const maxAssertedQuads = inference.maxAssertedQuads ?? 1e5;
190
+ const replacing = isReplaceImportCommit(context);
191
+ if (replacing && prepared.insertions.length > maxAssertedQuads) throw new InferenceSizeGuardError(prepared.insertions.length, maxAssertedQuads);
192
+ const plan = planInference({
193
+ assertedBefore: replacing ? [] : await loadAssertedQuads(driverOptions.connection, {
194
+ worldId: driverOptions.worldId,
195
+ maxAssertedQuads,
196
+ pendingInsertions: prepared.insertions.length
197
+ }),
198
+ deletions: prepared.deletions,
199
+ insertions: prepared.insertions,
200
+ graphs: inference.graphs
201
+ });
202
+ const addRows = /* @__PURE__ */ new Map();
203
+ const derived = [...plan.derivedToAdd, ...plan.entailedDeletions];
204
+ const derivedIds = hashQuads(derived);
205
+ derived.forEach((quad, index) => {
206
+ const id = derivedIds[index];
207
+ if (!addRows.has(id)) addRows.set(id, {
208
+ ...buildInsertRow(quad, id),
209
+ world_id: driverOptions.worldId,
210
+ derived: 1
211
+ });
212
+ });
213
+ return {
214
+ removeIds: hashQuads(plan.derivedToRemove),
215
+ addRows: [...addRows.values()]
216
+ };
217
+ }
218
+ // src/cloudflare/commit/commit-d1-patch.ts
219
+ /**
220
+ * commitD1Patch runs one D1 commit through the shared SQL commit core
221
+ * (`commitSqlPatch`). D1 batches are not atomic with the outside-D1 Vectorize
222
+ * index, which the platform forces: vectors sync after the D1 write lands, and
223
+ * a failure there is logged drift that a reindex repairs. An embedding failure
224
+ * throws before anything is written, so the caller can retry. Imports project
225
+ * chunks during the commit (`searchIndexOnImport` defaults to the shared
226
+ * `"incremental"`); `"deferred"` stays available as an option.
227
+ */
228
+ async function commitD1Patch(patch, context, options) {
229
+ const { connection, worldId, searchIndexProjector: projector } = options;
230
+ const sync = projector?.createVectorSync();
231
+ const driverOptions = {
232
+ ...options,
233
+ connection,
234
+ inferenceEnabled: options.inference?.enabled === true,
235
+ beforePage: sync?.beforePage
236
+ };
237
+ const derived = options.inference?.enabled ? await planD1DerivedChanges(patch, context, options.inference, driverOptions) : void 0;
238
+ const provenance = options.provenance?.enabled ? await planD1Provenance(patch, context, driverOptions) : void 0;
239
+ const indexing = planSearchIndexing(options.searchIndexOnImport, context);
240
+ const dialect = createD1CommitDialect({
241
+ searchQueryBuilder: options.searchQueryBuilder,
242
+ worldId,
243
+ lookupChunkSize: effectiveLookupChunkSize(options.maxLookupChunkSize, Boolean(worldId)),
244
+ derived,
245
+ onChunkRows: sync?.collect
246
+ });
247
+ await commitSqlPatch(patch, context, createD1CommitDriver(driverOptions), provenance ? withProvenance(dialect, provenance) : dialect, {
248
+ filter: options,
249
+ searchIndexOnImport: options.searchIndexOnImport,
250
+ projection: projector?.projection,
251
+ rebuildPageSize: DEFAULT_D1_MATCH_PAGE_SIZE,
252
+ afterWrite: async () => {
253
+ if (indexing.reindexAfterCommit ? isFullRebuild(options) : isReplaceImportCommit(context) && indexing.projectDuringCommit) await sync?.purgeWorld();
254
+ await sync?.flush();
255
+ }
256
+ });
257
+ await sync?.flush();
258
+ sync?.logDrift(indexing.reindexAfterCommit ? "reindex" : "import");
259
+ }
260
+ // src/cloudflare/provenance/d1-provenance-store.ts
261
+ /** recordFromRow maps a `provenance` row to the SDK's record, omitting empty fields. */
262
+ function recordFromRow(row) {
263
+ return {
264
+ quadId: String(row.quad_id),
265
+ recordedAt: String(row.recorded_at),
266
+ type: row.type,
267
+ ...row.writer != null && { writer: String(row.writer) },
268
+ ...row.source != null && { source: String(row.source) },
269
+ ...row.supersedes_quad_id != null && { supersedesQuadId: String(row.supersedes_quad_id) }
270
+ };
271
+ }
272
+ /**
273
+ * D1ProvenanceStore is the durable ProvenanceStore over the `provenance` table.
274
+ * Commits do not go through `record`: they write their records in the same batch
275
+ * as the quads (see `planD1Provenance`).
276
+ */
277
+ var D1ProvenanceStore = class {
278
+ options;
279
+ constructor(options) {
280
+ this.options = options;
281
+ }
282
+ /** record appends one record on its own, outside any commit. */
283
+ async record(input) {
284
+ const recordedAt = input.recordedAt ?? (/* @__PURE__ */ new Date()).toISOString();
285
+ const type = input.type ?? "write";
286
+ await this.options.connection.batch(buildInsertProvenance(type, [[input.quadId, input.supersedesQuadId]], {
287
+ recordedAt,
288
+ writer: input.writer,
289
+ source: input.source
290
+ }, this.options.worldId));
291
+ return {
292
+ ...input,
293
+ recordedAt,
294
+ type
295
+ };
296
+ }
297
+ /** list returns matching records, oldest first. */
298
+ async list(query) {
299
+ const { rows } = await this.options.connection.execute(buildSelectProvenance(query ?? {}, this.options.worldId));
300
+ return rows.map(recordFromRow);
301
+ }
302
+ /** history walks what the quad replaced and what replaced it. */
303
+ async history(quadId) {
304
+ return await (await this.load([quadId])).history(quadId);
305
+ }
306
+ /**
307
+ * load reads the records of `quadIds` in one query, with their full correction
308
+ * chains unless `chains` is false, into the SDK's in-memory store, so walks
309
+ * behave exactly as they do there.
310
+ */
311
+ async load(quadIds, chains = true) {
312
+ const build = chains ? buildSelectProvenanceChains : buildSelectQuadRecords;
313
+ const { rows } = await this.options.connection.execute(build(quadIds, this.options.worldId));
314
+ const loaded = new InMemoryProvenanceStore();
315
+ for (const row of rows) await loaded.record(recordFromRow(row));
316
+ return loaded;
317
+ }
318
+ };
319
+ // src/cloudflare/provenance/query-d1-provenance.ts
320
+ /** matchQuads reads the quads matching the pattern, fetching no page past the limit. */
321
+ async function matchQuads(request, options) {
322
+ const limit = request.limit ?? 1e400;
323
+ const pageSize = options.matchPageSize ?? 1e3;
324
+ const quads = [];
325
+ for await (const quad of matchD1Pages(options.connection, Math.min(pageSize, limit), options.worldId, request.subject, request.predicate, request.object)) {
326
+ quads.push(quad);
327
+ if (quads.length >= limit) break;
328
+ }
329
+ return quads;
330
+ }
331
+ /**
332
+ * queryD1Provenance pairs each quad matching the pattern, up to the request's
333
+ * limit, with its records and history. Quads written before the world opted in come back with none.
334
+ */
335
+ async function queryD1Provenance(request, options) {
336
+ const chains = options.provenance?.history !== false;
337
+ const provenance = new D1ProvenanceStore(options);
338
+ const quads = await matchQuads(request, options);
339
+ const ids = quads.length > 0 ? hashQuads(quads) : [];
340
+ const results = [];
341
+ for (const group of chunk(ids)) {
342
+ const loaded = await provenance.load(group, chains);
343
+ for (const quadId of group) results.push({
344
+ quadId,
345
+ quad: quads[results.length],
346
+ records: await loaded.list({ quadId }),
347
+ history: chains ? await loaded.history(quadId) : {
348
+ quadId,
349
+ supersedes: [],
350
+ supersededBy: []
351
+ }
352
+ });
353
+ }
354
+ return { results };
355
+ }
356
+ // src/cloudflare/quad-store/d1-quad-store.ts
357
+ /**
358
+ * D1QuadStore implements the QuadStoreInterface for D1 backed durable persistence.
359
+ * It encapsulates transaction routing, commits, and indexing synchronization.
360
+ */
361
+ var D1QuadStore = class {
362
+ options;
363
+ constructor(options) {
364
+ this.options = options;
365
+ }
366
+ /**
367
+ * import merges or replaces the underlying store with provided RDF source data.
368
+ *
369
+ * @param request The payload defining the ingestion source and overwrite mode.
370
+ */
371
+ async import(request) {
372
+ await importViaTransaction(request, { createTransaction: () => this.createTransaction() });
373
+ }
374
+ /**
375
+ * export extracts the graph contents in raw quads or serialized formats.
376
+ *
377
+ * @param request The desired format specifications.
378
+ */
379
+ async export(request) {
380
+ return await exportFromRdfjsStore(this.options.store, request);
381
+ }
382
+ /**
383
+ * provenanceQuery returns the records and correction history of the quads
384
+ * matching the pattern. It rejects when the world has not opted in.
385
+ */
386
+ async provenanceQuery(request) {
387
+ if (!this.options.provenance?.enabled) throw new Error("Provenance is not configured.");
388
+ return await queryD1Provenance(request, this.options);
389
+ }
390
+ /**
391
+ * createTransaction returns a pre-configured Transaction bound to internal commit hooks.
392
+ * Its commit uses `defaults` when it is given no context of its own.
393
+ */
394
+ createTransaction(defaults) {
395
+ return new Transaction({ commit: (patch, context) => commitD1Patch(patch, context ?? defaults, this.options) });
396
+ }
397
+ };
398
+ export { loadAssertedQuads as a, InferenceSizeGuardError as i, D1ProvenanceStore as n, planInference as o, DEFAULT_MAX_ASSERTED_QUADS as r, D1QuadStore as t };
@@ -0,0 +1,2 @@
1
+ import { n as D1QuadStoreOptions, t as D1QuadStore } from "./mod-BRtbH8pa.js";
2
+ export { D1QuadStore, type D1QuadStoreOptions };
@@ -0,0 +1 @@
1
+ export { t as D1QuadStore } from "./quad-store-DX7Nqyjw.js";