@wazootech/worlds-sdk 0.0.0-stage → 0.11.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +288 -2
- package/THIRD_PARTY_NOTICES.md +279 -0
- package/dist/ai-sdk.d.ts +27 -0
- package/dist/ai-sdk.js +28 -0
- package/dist/build-search-result-id-qxdmXp0V.js +12 -0
- package/dist/chunk-and-embed-0crm0xLl.js +75 -0
- package/dist/client-BJ45zmXU.d.ts +74 -0
- package/dist/client-BWh0UAM0.js +45 -0
- package/dist/embedding-service-DebRMVmn.d.ts +15 -0
- package/dist/embedding-service.d.ts +3 -0
- package/dist/embedding-service.js +19 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +9 -0
- package/dist/memory.d.ts +26 -0
- package/dist/memory.js +29 -0
- package/dist/mod-8Zh1f9vW.d.ts +24 -0
- package/dist/mod-BuF_B_xU.d.ts +362 -0
- package/dist/mod-CHiiyEER.d.ts +79 -0
- package/dist/mod-ClDFMN-C.d.ts +625 -0
- package/dist/mod-Dmrdrb03.d.ts +13 -0
- package/dist/quad-chunker.d.ts +2 -0
- package/dist/quad-chunker.js +1 -0
- package/dist/quad-store-BGCOUBxK.js +851 -0
- package/dist/quad-store.d.ts +2 -0
- package/dist/quad-store.js +3 -0
- package/dist/rdf-formats-BkGt5RDB.js +93 -0
- package/dist/rdfjs-BNVjLSNL.js +190 -0
- package/dist/rdfjs.d.ts +79 -0
- package/dist/rdfjs.js +1 -0
- package/dist/search-index.d.ts +2 -0
- package/dist/search-index.js +219 -0
- package/dist/sparql-engine.d.ts +2 -0
- package/dist/sparql-engine.js +0 -0
- package/dist/testing.d.ts +301 -0
- package/dist/testing.js +786 -0
- package/dist/tfjs-use.d.ts +42 -0
- package/dist/tfjs-use.js +315 -0
- package/dist/wazoo.d.ts +86 -0
- package/dist/wazoo.js +347 -0
- package/package.json +119 -4
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { $ as ImportRequest, A as fromRdfjsTerm, B as QuadFilter, C as getFormat, D as fromRdfjsQuad, E as Quad, F as HexastoreIndexDescriptor, G as isImportCommit, H as PatchableStore, I as hashQuad, J as RdfjsStoreLike, K as isReplaceImportCommit, L as hashQuads, M as QuadRowReader, N as quadFromRow, O as toRdfjsQuad, P as HEXASTORE_INDEXES, Q as ImportMode, R as isTextualLiteral, S as exportQuadsResponse, T as parseQuads, U as TransactionContext, V as filterQuads, W as deduplicateBuffers, X as ExportRequest, Y as Patch, Z as ExportResponse, _ as createRdfjsStoreCommitHandler, a as preparePatch, at as ProvenanceListQuery, b as awaitDrainRemoveMatches, c as TransactionalRdfjsStore, ct as ProvenanceQueryResponse, d as RdfjsExportSource, dt as ProvenanceRecordInput, et as ImportSource, f as exportFromRdfjsStore, ft as ProvenanceRecordType, g as TransactionOptions, h as Transaction, i as computeNovelQuads, it as ProvenanceHistory, j as toRdfjsTerm, k as Term, l as TransactionalRdfjsStoreOptions, lt as ProvenanceQueryResult, m as MatchFunction, n as PreparedPatch, nt as InMemoryProvenanceStore, o as selectNovelQuads, ot as ProvenanceQueryHandler, p as importViaTransaction, pt as ProvenanceStore, q as RdfjsEventSource, r as SelectNovelQuadsOptions, rt as ImportProvenance, s as ReadonlyStore, st as ProvenanceQueryRequest, t as NovelQuads, tt as QuadStoreInterface, u as ImportViaTransactionOptions, ut as ProvenanceRecord, v as FORMATS, w as materializeImportQuads, x as collectQuadsFromStream, y as RdfFormat, z as QuadCriteria } from "./mod-ClDFMN-C.js";
|
|
2
|
+
export { ExportRequest, ExportResponse, FORMATS, HEXASTORE_INDEXES, HexastoreIndexDescriptor, ImportMode, ImportProvenance, ImportRequest, ImportSource, ImportViaTransactionOptions, InMemoryProvenanceStore, MatchFunction, NovelQuads, Patch, PatchableStore, PreparedPatch, ProvenanceHistory, ProvenanceListQuery, ProvenanceQueryHandler, ProvenanceQueryRequest, ProvenanceQueryResponse, ProvenanceQueryResult, ProvenanceRecord, ProvenanceRecordInput, ProvenanceRecordType, ProvenanceStore, Quad, QuadCriteria, QuadFilter, QuadRowReader, QuadStoreInterface, RdfFormat, RdfjsEventSource, RdfjsExportSource, RdfjsStoreLike, ReadonlyStore, SelectNovelQuadsOptions, Term, Transaction, TransactionContext, TransactionOptions, TransactionalRdfjsStore, TransactionalRdfjsStoreOptions, awaitDrainRemoveMatches, collectQuadsFromStream, computeNovelQuads, createRdfjsStoreCommitHandler, deduplicateBuffers, exportFromRdfjsStore, exportQuadsResponse, filterQuads, fromRdfjsQuad, fromRdfjsTerm, getFormat, hashQuad, hashQuads, importViaTransaction, isImportCommit, isReplaceImportCommit, isTextualLiteral, materializeImportQuads, parseQuads, preparePatch, quadFromRow, selectNovelQuads, toRdfjsQuad, toRdfjsTerm };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { S as InMemoryProvenanceStore, _ as isTextualLiteral, a as Transaction, b as isImportCommit, c as importViaTransaction, d as quadFromRow, f as fromRdfjsTerm, g as hashQuads, h as hashQuad, i as TransactionalRdfjsStore, l as fromRdfjsQuad, m as HEXASTORE_INDEXES, n as preparePatch, o as createRdfjsStoreCommitHandler, p as toRdfjsTerm, r as selectNovelQuads, s as exportFromRdfjsStore, t as computeNovelQuads, u as toRdfjsQuad, v as filterQuads, x as isReplaceImportCommit, y as deduplicateBuffers } from "./quad-store-BGCOUBxK.js";
|
|
2
|
+
import { a as getFormat, i as exportQuadsResponse, n as awaitDrainRemoveMatches, o as materializeImportQuads, r as collectQuadsFromStream, s as parseQuads, t as FORMATS } from "./rdf-formats-BkGt5RDB.js";
|
|
3
|
+
export { FORMATS, HEXASTORE_INDEXES, InMemoryProvenanceStore, Transaction, TransactionalRdfjsStore, awaitDrainRemoveMatches, collectQuadsFromStream, computeNovelQuads, createRdfjsStoreCommitHandler, deduplicateBuffers, exportFromRdfjsStore, exportQuadsResponse, filterQuads, fromRdfjsQuad, fromRdfjsTerm, getFormat, hashQuad, hashQuads, importViaTransaction, isImportCommit, isReplaceImportCommit, isTextualLiteral, materializeImportQuads, parseQuads, preparePatch, quadFromRow, selectNovelQuads, toRdfjsQuad, toRdfjsTerm };
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { MemoryStream, parseTurtleQuads, serializeTurtle } from "@wazootech/sparql-engine";
|
|
2
|
+
// src/client/quad-store/rdf-formats.ts
|
|
3
|
+
/**
|
|
4
|
+
* FORMATS is a map of content types to supported RdfFormats. The engine's
|
|
5
|
+
* TriG grammar is a Turtle/N-Triples/N-Quads superset, so parsing is uniform
|
|
6
|
+
* across formats; the dialect only constrains serialization. `text/n3` maps
|
|
7
|
+
* to the Turtle writer (the engine covers the N3 subset that is valid
|
|
8
|
+
* Turtle/TriG).
|
|
9
|
+
*/
|
|
10
|
+
const FORMATS = {
|
|
11
|
+
"text/turtle": {
|
|
12
|
+
contentType: "text/turtle",
|
|
13
|
+
engineFormat: "turtle"
|
|
14
|
+
},
|
|
15
|
+
"application/n-quads": {
|
|
16
|
+
contentType: "application/n-quads",
|
|
17
|
+
engineFormat: "n-quads"
|
|
18
|
+
},
|
|
19
|
+
"application/n-triples": {
|
|
20
|
+
contentType: "application/n-triples",
|
|
21
|
+
engineFormat: "n-triples"
|
|
22
|
+
},
|
|
23
|
+
"text/n3": {
|
|
24
|
+
contentType: "text/n3",
|
|
25
|
+
engineFormat: "turtle"
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* getFormat resolves the appropriate RdfFormat mapping for the given content type, defaulting to N-Quads.
|
|
30
|
+
*/
|
|
31
|
+
function getFormat(contentType) {
|
|
32
|
+
const format = contentType?.toLowerCase() || "application/n-quads";
|
|
33
|
+
return FORMATS[format] || FORMATS["application/n-quads"];
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* parseQuads parses serialized RDF into a quad stream for the given content type.
|
|
37
|
+
*/
|
|
38
|
+
function parseQuads(data, contentType) {
|
|
39
|
+
getFormat(contentType);
|
|
40
|
+
return new MemoryStream(parseTurtleQuads(data));
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* collectQuadsFromStream drains an RDF/JS quad stream into an array.
|
|
44
|
+
*/
|
|
45
|
+
function collectQuadsFromStream(stream) {
|
|
46
|
+
const quads = [];
|
|
47
|
+
return new Promise((resolve, reject) => {
|
|
48
|
+
stream.on("data", (quad) => quads.push(quad));
|
|
49
|
+
stream.on("end", () => resolve(quads));
|
|
50
|
+
stream.on("error", reject);
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* materializeImportQuads collects quads from an import source into an array.
|
|
55
|
+
*/
|
|
56
|
+
async function materializeImportQuads(source) {
|
|
57
|
+
if (source.kind === "quads") return Array.from(source.quads);
|
|
58
|
+
if (source.kind === "dataset") return Array.from(source.dataset);
|
|
59
|
+
if (source.kind === "serialized") return await collectQuadsFromStream(parseQuads(source.data, source.contentType));
|
|
60
|
+
throw new Error("Unsupported import source kind");
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* exportQuadsResponse formats collected quads according to an export request.
|
|
64
|
+
*/
|
|
65
|
+
function exportQuadsResponse(quads, request) {
|
|
66
|
+
if (request.format.kind === "quads") return {
|
|
67
|
+
kind: "quads",
|
|
68
|
+
quads
|
|
69
|
+
};
|
|
70
|
+
if (request.format.kind === "serialized") {
|
|
71
|
+
const contentType = request.format.contentType ?? "application/n-quads";
|
|
72
|
+
const { engineFormat } = getFormat(contentType);
|
|
73
|
+
return {
|
|
74
|
+
kind: "serialized",
|
|
75
|
+
data: serializeTurtle(quads, { format: engineFormat }),
|
|
76
|
+
contentType
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
throw new Error("Invalid format requested");
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* awaitDrainRemoveMatches waits for removeMatches(null, null, null, null) to finish.
|
|
83
|
+
* Used by createRdfjsStoreCommitHandler for replace import commits; durable backends
|
|
84
|
+
* honor isReplaceImportCommit in their commit patch handlers.
|
|
85
|
+
*/
|
|
86
|
+
function awaitDrainRemoveMatches(store) {
|
|
87
|
+
return new Promise((resolve, reject) => {
|
|
88
|
+
const removalStream = store.removeMatches(null, null, null, null);
|
|
89
|
+
removalStream.on("end", () => resolve());
|
|
90
|
+
removalStream.on("error", (error) => reject(error));
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
export { getFormat as a, exportQuadsResponse as i, awaitDrainRemoveMatches as n, materializeImportQuads as o, collectQuadsFromStream as r, parseQuads as s, FORMATS as t };
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { t as buildSearchResultId } from "./build-search-result-id-qxdmXp0V.js";
|
|
2
|
+
import { r as collectQuadsFromStream } from "./rdf-formats-BkGt5RDB.js";
|
|
3
|
+
import { S as InMemoryProvenanceStore, _ as isTextualLiteral, a as Transaction, c as importViaTransaction, h as hashQuad, o as createRdfjsStoreCommitHandler, s as exportFromRdfjsStore, v as filterQuads } from "./quad-store-BGCOUBxK.js";
|
|
4
|
+
import { MemoryStore } from "@wazootech/sparql-engine";
|
|
5
|
+
// src/rdfjs/rdfjs-search-index.ts
|
|
6
|
+
/**
|
|
7
|
+
* RdfjsSearchIndex is the implementation of SearchIndexInterface that uses an RDF/JS store.
|
|
8
|
+
*/
|
|
9
|
+
var RdfjsSearchIndex = class {
|
|
10
|
+
store;
|
|
11
|
+
/**
|
|
12
|
+
* The search index only reads via match() and size, so any RDF/JS store
|
|
13
|
+
* exposing those (N3.Store, @wazootech/sparql-engine MemoryStore,
|
|
14
|
+
* @wazootech/worlds-sqlite SqliteStore, LibsqlStore) is interchangeable here — no
|
|
15
|
+
* N3-specific surface needed.
|
|
16
|
+
*/
|
|
17
|
+
constructor(store) {
|
|
18
|
+
this.store = store;
|
|
19
|
+
}
|
|
20
|
+
async search(request) {
|
|
21
|
+
const query = request.query.toLowerCase();
|
|
22
|
+
const stream = this.store.match(null, null, null, null);
|
|
23
|
+
const results = [];
|
|
24
|
+
const pendingSearchResultPromises = [];
|
|
25
|
+
const matcher = filterQuads(request);
|
|
26
|
+
await new Promise((resolve, reject) => {
|
|
27
|
+
stream.on("data", (quad) => {
|
|
28
|
+
if (!matcher(quad)) return;
|
|
29
|
+
if (isTextualLiteral(quad.object)) {
|
|
30
|
+
const value = quad.object.value;
|
|
31
|
+
if (value.toLowerCase().includes(query)) pendingSearchResultPromises.push((async () => {
|
|
32
|
+
const searchResultBase = {
|
|
33
|
+
subject: quad.subject.value,
|
|
34
|
+
predicate: quad.predicate.value,
|
|
35
|
+
graph: quad.graph.value,
|
|
36
|
+
text: value
|
|
37
|
+
};
|
|
38
|
+
results.push({
|
|
39
|
+
id: await buildSearchResultId(searchResultBase),
|
|
40
|
+
...searchResultBase,
|
|
41
|
+
score: 1
|
|
42
|
+
});
|
|
43
|
+
})());
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
stream.on("end", resolve);
|
|
47
|
+
stream.on("error", reject);
|
|
48
|
+
});
|
|
49
|
+
await Promise.all(pendingSearchResultPromises);
|
|
50
|
+
return { results };
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* reindex is a no-op for in-memory RDF/JS search, which scans the live store on each query.
|
|
54
|
+
*/
|
|
55
|
+
reindex(_request) {
|
|
56
|
+
return Promise.resolve({
|
|
57
|
+
processedQuadCount: this.store.size,
|
|
58
|
+
chunkRowCount: 0
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
// src/rdfjs/rdfjs-quad-store-provenance.ts
|
|
63
|
+
/**
|
|
64
|
+
* recordPatchProvenance records sidecar provenance for one applied patch:
|
|
65
|
+
* removal tombstones for deletions and prior quads, write records for
|
|
66
|
+
* insertions, and supersedesQuadId links when an inserted quad occupies the
|
|
67
|
+
* same subject/predicate/object/graph position as a removed one. Durable
|
|
68
|
+
* backends and custom commit handlers (for example SPARQL update commits) can
|
|
69
|
+
* call this directly so patch-driven removals are recorded too.
|
|
70
|
+
*/
|
|
71
|
+
async function recordPatchProvenance(options) {
|
|
72
|
+
const { provenanceStore, patch, context, priorQuads = [] } = options;
|
|
73
|
+
const meta = context?.provenance;
|
|
74
|
+
const insertionIds = /* @__PURE__ */ new Set();
|
|
75
|
+
for (const quad of patch.insertions) {
|
|
76
|
+
const quadId = safeHashQuad(quad);
|
|
77
|
+
if (quadId !== null) insertionIds.add(quadId);
|
|
78
|
+
}
|
|
79
|
+
const removedQuads = [...patch.deletions, ...priorQuads].filter((quad) => {
|
|
80
|
+
const quadId = safeHashQuad(quad);
|
|
81
|
+
return quadId !== null && !insertionIds.has(quadId);
|
|
82
|
+
});
|
|
83
|
+
const supersededBySpog = new Map(removedQuads.map((quad) => [spogKey(quad), hashQuad(quad)]));
|
|
84
|
+
const recordedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
85
|
+
for (const removedQuad of removedQuads) await provenanceStore.record({
|
|
86
|
+
quadId: hashQuad(removedQuad),
|
|
87
|
+
type: "remove",
|
|
88
|
+
recordedAt,
|
|
89
|
+
...meta
|
|
90
|
+
});
|
|
91
|
+
for (const quad of patch.insertions) {
|
|
92
|
+
const quadId = safeHashQuad(quad);
|
|
93
|
+
if (quadId === null) continue;
|
|
94
|
+
await provenanceStore.record({
|
|
95
|
+
quadId,
|
|
96
|
+
type: "write",
|
|
97
|
+
recordedAt,
|
|
98
|
+
supersedesQuadId: supersededBySpog.get(spogKey(quad)),
|
|
99
|
+
...meta
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* safeHashQuad returns null instead of throwing for quads the q2 scheme
|
|
105
|
+
* cannot content-address (for example RDF-star triple terms); those quads
|
|
106
|
+
* simply carry no provenance record rather than failing the import.
|
|
107
|
+
*/
|
|
108
|
+
function safeHashQuad(quad) {
|
|
109
|
+
try {
|
|
110
|
+
return hashQuad(quad);
|
|
111
|
+
} catch {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* spogKey keys a quad by subject, predicate, and graph value so a removed
|
|
117
|
+
* quad can be linked as superseded by an inserted quad in the same statement
|
|
118
|
+
* position. The object is deliberately excluded: a correction keeps its
|
|
119
|
+
* subject and predicate and changes the object, which is exactly the
|
|
120
|
+
* supersession relationship provenance should capture.
|
|
121
|
+
*/
|
|
122
|
+
function spogKey(quad) {
|
|
123
|
+
return [
|
|
124
|
+
quad.subject.value,
|
|
125
|
+
quad.predicate.value,
|
|
126
|
+
quad.graph.value
|
|
127
|
+
].join("\0");
|
|
128
|
+
}
|
|
129
|
+
// src/rdfjs/rdfjs-quad-store.ts
|
|
130
|
+
/**
|
|
131
|
+
* RdfjsQuadStore is the standard implementation of the QuadStoreInterface that uses
|
|
132
|
+
* an underlying in-memory or compatible RDFJS Store. Every commit records
|
|
133
|
+
* sidecar provenance: write records for insertions, removal tombstones for
|
|
134
|
+
* deletions and replace-mode wipes, and supersedesQuadId links when a commit
|
|
135
|
+
* replaces a quad sharing subject, predicate, and graph.
|
|
136
|
+
*/
|
|
137
|
+
var RdfjsQuadStore = class {
|
|
138
|
+
options;
|
|
139
|
+
provenanceStore;
|
|
140
|
+
store;
|
|
141
|
+
constructor(options) {
|
|
142
|
+
this.options = options;
|
|
143
|
+
this.store = options?.store ?? new MemoryStore();
|
|
144
|
+
this.provenanceStore = options?.provenanceStore ?? new InMemoryProvenanceStore();
|
|
145
|
+
}
|
|
146
|
+
async import(request) {
|
|
147
|
+
const commitHandler = this.options?.commit ?? createRdfjsStoreCommitHandler(this.store);
|
|
148
|
+
await importViaTransaction(request, { createTransaction: () => new Transaction({ commit: async (patch, context) => {
|
|
149
|
+
const priorQuads = context?.importMode === "replace" ? await collectAllQuads(this.store) : [];
|
|
150
|
+
await commitHandler(patch, context);
|
|
151
|
+
await this.recordProvenance(patch, context, priorQuads);
|
|
152
|
+
} }) });
|
|
153
|
+
}
|
|
154
|
+
async export(request) {
|
|
155
|
+
return await exportFromRdfjsStore(this.store, request);
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* provenanceQuery resolves quads matching the RDF pattern and pairs each
|
|
159
|
+
* with its sidecar records and supersedes chain. Quads written before
|
|
160
|
+
* provenance recording return with empty records rather than failing.
|
|
161
|
+
*/
|
|
162
|
+
async provenanceQuery(request) {
|
|
163
|
+
const stream = this.store.match(request.subject ?? null, request.predicate ?? null, request.object ?? null);
|
|
164
|
+
const quads = (await collectQuadsFromStream(stream)).slice(0, request.limit);
|
|
165
|
+
return { results: await Promise.all(quads.map(async (quad) => {
|
|
166
|
+
const quadId = hashQuad(quad);
|
|
167
|
+
return {
|
|
168
|
+
quadId,
|
|
169
|
+
quad,
|
|
170
|
+
records: await this.provenanceStore.list({ quadId }),
|
|
171
|
+
history: await this.provenanceStore.history(quadId)
|
|
172
|
+
};
|
|
173
|
+
})) };
|
|
174
|
+
}
|
|
175
|
+
recordProvenance(patch, context, priorQuads = []) {
|
|
176
|
+
return recordPatchProvenance({
|
|
177
|
+
provenanceStore: this.provenanceStore,
|
|
178
|
+
patch,
|
|
179
|
+
context,
|
|
180
|
+
priorQuads
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
/**
|
|
185
|
+
* collectAllQuads drains every quad currently in the store.
|
|
186
|
+
*/
|
|
187
|
+
async function collectAllQuads(store) {
|
|
188
|
+
return await collectQuadsFromStream(store.match(null, null, null, null));
|
|
189
|
+
}
|
|
190
|
+
export { recordPatchProvenance as n, RdfjsSearchIndex as r, RdfjsQuadStore as t };
|
package/dist/rdfjs.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { C as ReindexResponse, D as SearchRequest, O as SearchResponse, S as ReindexRequest, w as SearchIndexInterface } from "./mod-BuF_B_xU.js";
|
|
2
|
+
import { $ as ImportRequest, J as RdfjsStoreLike, U as TransactionContext, X as ExportRequest, Y as Patch, Z as ExportResponse, ct as ProvenanceQueryResponse, pt as ProvenanceStore, st as ProvenanceQueryRequest, tt as QuadStoreInterface } from "./mod-ClDFMN-C.js";
|
|
3
|
+
import * as rdfjs from "@rdfjs/types";
|
|
4
|
+
/**
|
|
5
|
+
* RdfjsSearchIndex is the implementation of SearchIndexInterface that uses an RDF/JS store.
|
|
6
|
+
*/
|
|
7
|
+
export declare class RdfjsSearchIndex implements SearchIndexInterface {
|
|
8
|
+
private readonly store;
|
|
9
|
+
/**
|
|
10
|
+
* The search index only reads via match() and size, so any RDF/JS store
|
|
11
|
+
* exposing those (N3.Store, @wazootech/sparql-engine MemoryStore,
|
|
12
|
+
* @wazootech/worlds-sqlite SqliteStore, LibsqlStore) is interchangeable here — no
|
|
13
|
+
* N3-specific surface needed.
|
|
14
|
+
*/
|
|
15
|
+
constructor(store: RdfjsStoreLike & {
|
|
16
|
+
size: number;
|
|
17
|
+
});
|
|
18
|
+
search(request: SearchRequest): Promise<SearchResponse>;
|
|
19
|
+
/**
|
|
20
|
+
* reindex is a no-op for in-memory RDF/JS search, which scans the live store on each query.
|
|
21
|
+
*/
|
|
22
|
+
reindex(_request?: ReindexRequest): Promise<ReindexResponse>;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* recordPatchProvenance records sidecar provenance for one applied patch:
|
|
26
|
+
* removal tombstones for deletions and prior quads, write records for
|
|
27
|
+
* insertions, and supersedesQuadId links when an inserted quad occupies the
|
|
28
|
+
* same subject/predicate/object/graph position as a removed one. Durable
|
|
29
|
+
* backends and custom commit handlers (for example SPARQL update commits) can
|
|
30
|
+
* call this directly so patch-driven removals are recorded too.
|
|
31
|
+
*/
|
|
32
|
+
export declare function recordPatchProvenance(options: RecordPatchProvenanceOptions): Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* RecordPatchProvenanceOptions bundles the inputs to recordPatchProvenance.
|
|
35
|
+
*/
|
|
36
|
+
interface RecordPatchProvenanceOptions {
|
|
37
|
+
provenanceStore: ProvenanceStore;
|
|
38
|
+
patch: Patch;
|
|
39
|
+
context?: TransactionContext;
|
|
40
|
+
/** priorQuads are the quads that existed before a replace-mode wipe. */
|
|
41
|
+
priorQuads?: rdfjs.Quad[];
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* RdfjsQuadStoreOptions configures RdfjsQuadStore dependencies.
|
|
45
|
+
*/
|
|
46
|
+
export interface RdfjsQuadStoreOptions {
|
|
47
|
+
/** store is the active in-memory quad backend. */
|
|
48
|
+
store?: RdfjsStoreLike;
|
|
49
|
+
/** commit optionally overrides how transactions are persisted. */
|
|
50
|
+
commit?: (patch: Patch, context?: TransactionContext) => Promise<void>;
|
|
51
|
+
/**
|
|
52
|
+
* provenanceStore optionally overrides the sidecar provenance store.
|
|
53
|
+
* Defaults to an InMemoryProvenanceStore scoped to this store instance.
|
|
54
|
+
*/
|
|
55
|
+
provenanceStore?: ProvenanceStore;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* RdfjsQuadStore is the standard implementation of the QuadStoreInterface that uses
|
|
59
|
+
* an underlying in-memory or compatible RDFJS Store. Every commit records
|
|
60
|
+
* sidecar provenance: write records for insertions, removal tombstones for
|
|
61
|
+
* deletions and replace-mode wipes, and supersedesQuadId links when a commit
|
|
62
|
+
* replaces a quad sharing subject, predicate, and graph.
|
|
63
|
+
*/
|
|
64
|
+
export declare class RdfjsQuadStore implements QuadStoreInterface {
|
|
65
|
+
private readonly options?;
|
|
66
|
+
readonly provenanceStore: ProvenanceStore;
|
|
67
|
+
private readonly store;
|
|
68
|
+
constructor(options?: RdfjsQuadStoreOptions | undefined);
|
|
69
|
+
import(request: ImportRequest): Promise<void>;
|
|
70
|
+
export(request: ExportRequest): Promise<ExportResponse>;
|
|
71
|
+
/**
|
|
72
|
+
* provenanceQuery resolves quads matching the RDF pattern and pairs each
|
|
73
|
+
* with its sidecar records and supersedes chain. Quads written before
|
|
74
|
+
* provenance recording return with empty records rather than failing.
|
|
75
|
+
*/
|
|
76
|
+
provenanceQuery(request: ProvenanceQueryRequest): Promise<ProvenanceQueryResponse>;
|
|
77
|
+
private recordProvenance;
|
|
78
|
+
}
|
|
79
|
+
export type { RecordPatchProvenanceOptions };
|
package/dist/rdfjs.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as RdfjsQuadStore, r as RdfjsSearchIndex, n as recordPatchProvenance } from "./rdfjs-BNVjLSNL.js";
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { A as DEFAULT_RRF_K, C as ReindexResponse, D as SearchRequest, E as SearchMode, M as normalizeRrfScore, O as SearchResponse, S as ReindexRequest, T as SearchIndexOnImport, _ as extractRdfLocalLabel, a as RebuildSearchIndexResult, b as BuildSearchResultIdOptions, c as PreparedCommit, d as PlanSearchIndexingOptions, f as SearchIndexPlan, g as buildChunkFtsValue, h as DEFAULT_LABEL_PREDICATES, i as RebuildSearchIndexOptions, j as SearchScoreType, k as SearchResult, l as prepareCommit, m as BuildChunkFtsValueOptions, n as RebuildPage, o as rebuildSearchIndex, p as planSearchIndexing, r as RebuildScope, s as PrepareCommitOptions, t as ChunkRebuildDriver, u as DEFAULT_SEARCH_INDEX_ON_IMPORT, v as formatPredicatePhrase, w as SearchIndexInterface, x as buildSearchResultId, y as resolveLabelPredicates } from "./mod-BuF_B_xU.js";
|
|
2
|
+
export { BuildChunkFtsValueOptions, BuildSearchResultIdOptions, ChunkRebuildDriver, DEFAULT_LABEL_PREDICATES, DEFAULT_RRF_K, DEFAULT_SEARCH_INDEX_ON_IMPORT, PlanSearchIndexingOptions, PrepareCommitOptions, PreparedCommit, RebuildPage, RebuildScope, RebuildSearchIndexOptions, RebuildSearchIndexResult, ReindexRequest, ReindexResponse, SearchIndexInterface, SearchIndexOnImport, SearchIndexPlan, SearchMode, SearchRequest, SearchResponse, SearchResult, SearchScoreType, buildChunkFtsValue, buildSearchResultId, extractRdfLocalLabel, formatPredicatePhrase, normalizeRrfScore, planSearchIndexing, prepareCommit, rebuildSearchIndex, resolveLabelPredicates };
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { t as buildSearchResultId } from "./build-search-result-id-qxdmXp0V.js";
|
|
2
|
+
import { b as isImportCommit, g as hashQuads, n as preparePatch, r as selectNovelQuads, v as filterQuads, x as isReplaceImportCommit } from "./quad-store-BGCOUBxK.js";
|
|
3
|
+
import { t as chunkAndEmbedQuads } from "./chunk-and-embed-0crm0xLl.js";
|
|
4
|
+
// src/client/search-index/search-chunk-fts.ts
|
|
5
|
+
/**
|
|
6
|
+
* buildChunkFtsValue composes space-separated discovery tokens for FTS and semantic indexing.
|
|
7
|
+
*/
|
|
8
|
+
function buildChunkFtsValue(chunk, options) {
|
|
9
|
+
return [
|
|
10
|
+
extractRdfLocalLabel(chunk.subject),
|
|
11
|
+
formatPredicatePhrase(chunk.predicate),
|
|
12
|
+
chunk.value,
|
|
13
|
+
...options.labelLiteralsForSubject
|
|
14
|
+
].filter((token) => token.length > 0).join(" ");
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* extractRdfLocalLabel returns a short human-readable label from an IRI or term value.
|
|
18
|
+
*/
|
|
19
|
+
function extractRdfLocalLabel(iri) {
|
|
20
|
+
const trimmed = iri.trim();
|
|
21
|
+
if (trimmed.length === 0) return "unknown entity";
|
|
22
|
+
const hashIndex = trimmed.lastIndexOf("#");
|
|
23
|
+
if (hashIndex >= 0 && hashIndex < trimmed.length - 1) return humanizeToken(trimmed.slice(hashIndex + 1));
|
|
24
|
+
const slashIndex = trimmed.lastIndexOf("/");
|
|
25
|
+
if (slashIndex >= 0 && slashIndex < trimmed.length - 1) return humanizeToken(trimmed.slice(slashIndex + 1));
|
|
26
|
+
return humanizeToken(trimmed);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* formatPredicatePhrase converts a predicate IRI into a short verb phrase.
|
|
30
|
+
*/
|
|
31
|
+
function formatPredicatePhrase(predicateIri) {
|
|
32
|
+
return extractRdfLocalLabel(predicateIri).toLowerCase();
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* humanizeToken decodes common IRI local-name separators into spaced words.
|
|
36
|
+
*/
|
|
37
|
+
function humanizeToken(token) {
|
|
38
|
+
const withSpaces = token.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").trim();
|
|
39
|
+
if (withSpaces.length === 0) return token;
|
|
40
|
+
return withSpaces;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* DEFAULT_LABEL_PREDICATES lists built-in predicate IRIs used for subject alias discovery at index time.
|
|
44
|
+
*/
|
|
45
|
+
const DEFAULT_LABEL_PREDICATES = [
|
|
46
|
+
"http://www.w3.org/2000/01/rdf-schema#label",
|
|
47
|
+
"http://www.w3.org/2004/02/skos/core#prefLabel",
|
|
48
|
+
"http://schema.org/name"
|
|
49
|
+
];
|
|
50
|
+
/**
|
|
51
|
+
* resolveLabelPredicates merges caller extensions with built-in label IRIs (union, deduped, stable order).
|
|
52
|
+
*/
|
|
53
|
+
function resolveLabelPredicates(labelPredicates) {
|
|
54
|
+
const seen = /* @__PURE__ */ new Set();
|
|
55
|
+
const resolved = [];
|
|
56
|
+
for (const predicate of [...DEFAULT_LABEL_PREDICATES, ...labelPredicates ?? []]) if (!seen.has(predicate)) {
|
|
57
|
+
seen.add(predicate);
|
|
58
|
+
resolved.push(predicate);
|
|
59
|
+
}
|
|
60
|
+
return resolved;
|
|
61
|
+
}
|
|
62
|
+
// src/client/search-index/rrf-score.ts
|
|
63
|
+
/**
|
|
64
|
+
* DEFAULT_RRF_K is the reciprocal rank fusion constant used by all search
|
|
65
|
+
* backends (RRF, $k = 60$). See the hosted search contract (worlds-api#30)
|
|
66
|
+
* decision D7 for the score-scale requirements this module implements.
|
|
67
|
+
*/
|
|
68
|
+
const DEFAULT_RRF_K = 60;
|
|
69
|
+
/**
|
|
70
|
+
* normalizeRrfScore normalizes a raw reciprocal rank to the hosted search
|
|
71
|
+
* contract scale (worlds-api#30 D7): `score = k / (k + rank)`.
|
|
72
|
+
*
|
|
73
|
+
* The raw RRF formula `1 / (k + rank)` tops out near 0.017 for realistic
|
|
74
|
+
* result pools (k = 60, rank 0), which makes any caller-side `minScore` floor
|
|
75
|
+
* meaningless. This mapper is the single normalization point for all backends
|
|
76
|
+
* (sqlite, libsql, indexeddb, cloudflare) so that:
|
|
77
|
+
*
|
|
78
|
+
* - rank 0 → 1.0 (best possible score)
|
|
79
|
+
* - scores are strictly decreasing in rank
|
|
80
|
+
* - scores are always > 0 for any finite rank, approaching 0 asymptotically
|
|
81
|
+
* - the transform is rank-monotone: result ordering is unchanged
|
|
82
|
+
*
|
|
83
|
+
* The hybrid fused-list factor for multi-list RRF is deliberately deferred
|
|
84
|
+
* (Phase C, worlds-cloudflare#30) — no hybrid backend exists on the hosted
|
|
85
|
+
* path yet, so single-list normalization is all the contract needs today.
|
|
86
|
+
*
|
|
87
|
+
* @param rank zero-based result rank (0 = best hit).
|
|
88
|
+
* @param k reciprocal rank fusion constant; must be a finite number > 0.
|
|
89
|
+
* Defaults to {@link DEFAULT_RRF_K} (60).
|
|
90
|
+
* @returns the normalized score in (0, 1], with 1.0 at rank 0.
|
|
91
|
+
* @throws RangeError when rank is negative or non-finite, or k is not a
|
|
92
|
+
* finite number > 0.
|
|
93
|
+
*/
|
|
94
|
+
function normalizeRrfScore(rank, k = 60) {
|
|
95
|
+
if (!Number.isFinite(rank) || rank < 0) throw new RangeError(`normalizeRrfScore: rank must be a finite number >= 0, got ${rank}`);
|
|
96
|
+
if (!Number.isFinite(k) || k <= 0) throw new RangeError(`normalizeRrfScore: k must be a finite number > 0, got ${k}`);
|
|
97
|
+
return k / (k + rank);
|
|
98
|
+
}
|
|
99
|
+
// src/client/search-index/search-index-policy.ts
|
|
100
|
+
/**
|
|
101
|
+
* DEFAULT_SEARCH_INDEX_ON_IMPORT is the mode a backend uses when the option is
|
|
102
|
+
* unset: project chunks as quads are written. Every backend, `@wazootech/worlds-cloudflare`
|
|
103
|
+
* included, takes it.
|
|
104
|
+
*/
|
|
105
|
+
const DEFAULT_SEARCH_INDEX_ON_IMPORT = "incremental";
|
|
106
|
+
/**
|
|
107
|
+
* planSearchIndexing decides, from the configured `searchIndexOnImport` and the
|
|
108
|
+
* commit's context, whether to project during the commit and whether to
|
|
109
|
+
* rebuild afterwards:
|
|
110
|
+
*
|
|
111
|
+
* - "disabled": never project, never rebuild.
|
|
112
|
+
* - "incremental": project during every commit, never rebuild.
|
|
113
|
+
* - "deferred": project during ordinary commits; an import (merge or replace)
|
|
114
|
+
* skips projection and rebuilds once afterwards.
|
|
115
|
+
*
|
|
116
|
+
* It is the rule `@wazootech/worlds-libsql`, `@wazootech/worlds-sqlite`, and `@wazootech/worlds-cloudflare`
|
|
117
|
+
* each implement today, differing only in the default mode.
|
|
118
|
+
*/
|
|
119
|
+
function planSearchIndexing(mode, context, options) {
|
|
120
|
+
const effective = mode ?? options?.defaultMode ?? "incremental";
|
|
121
|
+
const deferredImport = effective === "deferred" && isImportCommit(context);
|
|
122
|
+
return {
|
|
123
|
+
projectDuringCommit: effective !== "disabled" && !deferredImport,
|
|
124
|
+
reindexAfterCommit: deferredImport
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
// src/client/search-index/prepare-commit.ts
|
|
128
|
+
/**
|
|
129
|
+
* prepareCommit is the pure, fallible half of every durable commit, in the one
|
|
130
|
+
* order all backends share, entirely before any write:
|
|
131
|
+
*
|
|
132
|
+
* 1. `preparePatch` applies the include/exclude filter to both sides, so a
|
|
133
|
+
* filtered-out quad is neither stored nor projected, and hashes the rest.
|
|
134
|
+
* 2. `planSearchIndexing` decides whether to project now and whether a full
|
|
135
|
+
* rebuild must follow (a deferred import projects nothing: `rows` is empty
|
|
136
|
+
* and the caller reindexes after its write).
|
|
137
|
+
* 3. `selectNovelQuads` finds the insertions to write (see `selectNovel`).
|
|
138
|
+
* 4. `chunkAndEmbedQuads` builds the chunk rows for the novel quads. A chunking
|
|
139
|
+
* or embedding failure rejects here, so the store is never touched.
|
|
140
|
+
*
|
|
141
|
+
* The caller writes `prepared` deletions, `novel` insertions, and `rows`, wipes
|
|
142
|
+
* first when `replacing`, then reindexes when `plan.reindexAfterCommit`.
|
|
143
|
+
*/
|
|
144
|
+
async function prepareCommit(patch, options) {
|
|
145
|
+
const { context, projection } = options;
|
|
146
|
+
const replacing = isReplaceImportCommit(context);
|
|
147
|
+
const prepared = preparePatch(patch, {
|
|
148
|
+
include: options.include,
|
|
149
|
+
exclude: options.exclude
|
|
150
|
+
});
|
|
151
|
+
const plan = planSearchIndexing(options.searchIndexOnImport, context, { defaultMode: options.defaultMode });
|
|
152
|
+
const projecting = plan.projectDuringCommit ? projection : void 0;
|
|
153
|
+
const novel = options.selectNovel === "when-projecting" && !projecting ? {
|
|
154
|
+
novelInsertions: [],
|
|
155
|
+
novelQuadIds: []
|
|
156
|
+
} : await selectNovelQuads(prepared, {
|
|
157
|
+
replacing,
|
|
158
|
+
keyOf: options.keyOf,
|
|
159
|
+
lookupExisting: options.lookupExisting
|
|
160
|
+
});
|
|
161
|
+
return {
|
|
162
|
+
prepared,
|
|
163
|
+
plan,
|
|
164
|
+
novel,
|
|
165
|
+
rows: projecting && novel.novelQuadIds.length > 0 ? (await chunkAndEmbedQuads(novel.novelInsertions, novel.novelQuadIds, projecting)).rows : [],
|
|
166
|
+
replacing
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
// src/client/search-index/rebuild-search-index.ts
|
|
170
|
+
/** hasCriteria is true when one side of a QuadFilter names anything to match. */
|
|
171
|
+
function hasCriteria(side) {
|
|
172
|
+
return side !== void 0 && Object.values(side).some((v) => v?.length);
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* rebuildSearchIndex is the page loop every durable backend shares. It pages
|
|
176
|
+
* stored quads through `driver.pageQuads`, keeps the in-scope ones, chunks and
|
|
177
|
+
* embeds each page BEFORE `driver.writePage` (an embedding failure rejects and
|
|
178
|
+
* that page writes nothing), and counts what it scanned and wrote.
|
|
179
|
+
*
|
|
180
|
+
* Unscoped, the first `writePage` clears every old row, so an embedding
|
|
181
|
+
* failure on page 1 changes nothing; a store with no quads still clears once.
|
|
182
|
+
* Scoped (an include or exclude with any criteria), nothing is cleared: each
|
|
183
|
+
* page replaces only the rows of its in-scope quads, by hash. A failure on a
|
|
184
|
+
* later page leaves the earlier pages written; `finish` is for a driver that
|
|
185
|
+
* buffers instead and wants all-or-nothing.
|
|
186
|
+
*/
|
|
187
|
+
async function rebuildSearchIndex(driver, projection, options) {
|
|
188
|
+
const { scope } = options;
|
|
189
|
+
const scoped = scope !== void 0 && (hasCriteria(scope.include) || hasCriteria(scope.exclude));
|
|
190
|
+
const inScope = scoped ? filterQuads(scope) : () => true;
|
|
191
|
+
const pageSize = Math.max(1, options.pageSize);
|
|
192
|
+
const result = {
|
|
193
|
+
processedQuadCount: 0,
|
|
194
|
+
chunkRowCount: 0
|
|
195
|
+
};
|
|
196
|
+
let first = true;
|
|
197
|
+
let after;
|
|
198
|
+
for (;;) {
|
|
199
|
+
const page = await driver.pageQuads({
|
|
200
|
+
after,
|
|
201
|
+
pageSize
|
|
202
|
+
});
|
|
203
|
+
result.processedQuadCount += page.quads.length;
|
|
204
|
+
const quads = page.quads.filter(inScope);
|
|
205
|
+
if (quads.length > 0) {
|
|
206
|
+
const hashes = hashQuads(quads);
|
|
207
|
+
const { rows } = await chunkAndEmbedQuads(quads, hashes, projection);
|
|
208
|
+
await driver.writePage(scoped ? { hashes } : { all: true }, rows, first);
|
|
209
|
+
first = false;
|
|
210
|
+
result.chunkRowCount += rows.length;
|
|
211
|
+
}
|
|
212
|
+
if (page.next === void 0) break;
|
|
213
|
+
after = page.next;
|
|
214
|
+
}
|
|
215
|
+
if (first && !scoped) await driver.writePage({ all: true }, [], true);
|
|
216
|
+
await driver.finish?.();
|
|
217
|
+
return result;
|
|
218
|
+
}
|
|
219
|
+
export { DEFAULT_LABEL_PREDICATES, DEFAULT_RRF_K, DEFAULT_SEARCH_INDEX_ON_IMPORT, buildChunkFtsValue, buildSearchResultId, extractRdfLocalLabel, formatPredicatePhrase, normalizeRrfScore, planSearchIndexing, prepareCommit, rebuildSearchIndex, resolveLabelPredicates };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as SparqlSelectResults, c as SparqlRequest, i as SparqlResponse, n as SparqlBinding, o as SparqlValue, r as SparqlConstructResults, s as SparqlEngineInterface, t as SparqlAskResults } from "./mod-8Zh1f9vW.js";
|
|
2
|
+
export type { SparqlAskResults, SparqlBinding, SparqlConstructResults, SparqlEngineInterface, SparqlRequest, SparqlResponse, SparqlSelectResults, SparqlValue };
|
|
File without changes
|