@wazootech/sparql-engine 0.0.0-stage → 0.5.8

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,365 @@
1
+ import { a as SparqlRequest, c as SparqlValue, i as SparqlEngineInterface, n as SparqlBinding, o as SparqlResponse, r as SparqlConstructResults, s as SparqlSelectResults, t as SparqlAskResults } from "./sparql-engine-interface-Bies9KjE.js";
2
+ import { i as RdfQuad, l as RdfTerm, o as RdfSource, s as RdfStore } from "./rdf-terms-DGpxNnyn.js";
3
+ import { B as Triple, z as Term } from "./ast-CIKmrXH9.js";
4
+ import { n as SparqlSyntaxError, t as parseTurtleQuads } from "./turtle-parser-CzWF7KXf.js";
5
+ import { n as MemoryStream, t as MemoryStore } from "./memory-store-DhAGI-j6.js";
6
+ import { A as canonicalizeRdfTerm, C as XSD_INTEGER, I as sameRdfTerm, L as termKey, M as rdfTermToSparqlValue, N as sparqlTermToRdfTerm, O as numericValue, S as XSD_FLOAT, T as compareNumericValues, _ as XSD_BOOLEAN, b as XSD_DECIMAL, g as XSD, h as NUMERIC_DATATYPES, i as compareRdfTerms, j as canonicalizeSparqlValue, k as CanonicalTerm, m as formatNumber, r as dataFactory, t as DataFactory, w as XSD_STRING, x as XSD_DOUBLE } from "./public-BNHiaGho.js";
7
+ import { a as serializeJsonResults, i as serializeXmlResults, n as TurtleWriterOptions, r as serializeTurtle, t as TurtleFormat } from "./mod-C4GFefO7.js";
8
+ /** LoadHttpResponse is the fetch reply surface the guarded LOAD path reads. */
9
+ interface LoadHttpResponse {
10
+ readonly ok: boolean;
11
+ readonly status: number;
12
+ readonly headers: {
13
+ get(name: string): string | null;
14
+ };
15
+ readonly body?: {
16
+ getReader(): {
17
+ read(): Promise<{
18
+ done: boolean;
19
+ value?: Uint8Array;
20
+ }>;
21
+ cancel(): Promise<void>;
22
+ };
23
+ } | null;
24
+ text(): Promise<string>;
25
+ }
26
+ /** LoadFetch is the fetch signature the guarded LOAD path calls. */
27
+ type LoadFetch = (url: string, init: {
28
+ redirect: "manual";
29
+ signal: AbortSignal;
30
+ }) => Promise<LoadHttpResponse>;
31
+ /**
32
+ * LoadPolicy governs `LOAD <http(s)://...>`. Remote LOAD is denied unless
33
+ * allowedHosts names the host, so a multi-tenant host never fetches an
34
+ * arbitrary caller-chosen URL. File LOAD is unaffected (it needs the
35
+ * readTextFile option outside Deno and Bun).
36
+ */
37
+ interface LoadPolicy {
38
+ /** allowedHosts lists exact hostnames LOAD may fetch. Empty or absent denies all remote LOAD. */
39
+ allowedHosts?: readonly string[];
40
+ /** allowHttp permits plain http for allowed hosts. Defaults to https only. */
41
+ allowHttp?: boolean;
42
+ /** maxBytes caps the response body. Defaults to 5 MiB. */
43
+ maxBytes?: number;
44
+ /** maxQuads caps the parsed document. Defaults to 10000. */
45
+ maxQuads?: number;
46
+ /** timeoutMs bounds each fetch including body reads. Defaults to 5000. */
47
+ timeoutMs?: number;
48
+ /** maxRedirects bounds followed redirects; each hop is re-validated. Defaults to 3. */
49
+ maxRedirects?: number;
50
+ /**
51
+ * resolveHost resolves a hostname to IP addresses so they can be checked
52
+ * against private ranges (DNS-rebinding defense). Optional because the
53
+ * package graph stays free of `node:` imports; pass one on Node, Deno or Bun.
54
+ */
55
+ resolveHost?: (hostname: string) => Promise<string[]>;
56
+ /** fetch overrides globalThis.fetch (tests, proxies). */
57
+ fetch?: LoadFetch;
58
+ }
59
+ /**
60
+ * PatternStats are the per-pattern statistics that feed the join-cost
61
+ * estimator (planner piece 2, issue #129):
62
+ *
63
+ * - candidates — how many quads the pattern matches in the store (the
64
+ * pattern's cardinality). For the default-graph scope this agrees with
65
+ * ScanEntry.candidates, which the join actually materializes;
66
+ * - distinctByVar — for each variable position of the pattern, how many
67
+ * distinct values that variable takes across the matched quads. This is
68
+ * the per-variable value-frequency that lets the estimator see true
69
+ * index bucket sizes, so two medium-selectivity patterns that share a
70
+ * variable are recognized as cheaper than unrelated patterns.
71
+ *
72
+ * Stats only ever influence join order — never results (SPARQL 1.1 §18.2.2).
73
+ */
74
+ interface PatternStats {
75
+ candidates: number;
76
+ distinctByVar: Partial<Record<string, number>>;
77
+ }
78
+ /**
79
+ * StoreStatisticsHook is the optional store capability that feeds the
80
+ * statistics source (mirroring the countQuads precedent, decision #12): a
81
+ * store that can answer pattern-cardinality questions efficiently exposes
82
+ * estimateStats, and the engine uses it when present, falling back to a
83
+ * bounded derivation from the pattern's own candidate scan otherwise.
84
+ *
85
+ * The hook returns the statistics for the given triple pattern over the same
86
+ * universe the store's match() exposes. A store whose data lives in the
87
+ * default graph (the typical case) thus returns numbers that agree exactly
88
+ * with the engine's fallback on identical data; a store with named-graph
89
+ * data should scope its own answer accordingly. Returning undefined (or not
90
+ * implementing the hook at all) selects the fallback for that pattern.
91
+ */
92
+ type StoreStatisticsHook = {
93
+ estimateStats?(pattern: Triple): PatternStats | undefined | Promise<PatternStats | undefined>;
94
+ };
95
+ /** DISTINCT_SAMPLE_CAP bounds the fallback distinct-value pass. */
96
+ export declare const DISTINCT_SAMPLE_CAP = 1024;
97
+ /**
98
+ * ScanEntry is a triple pattern with its resolved terms and pre-fetched
99
+ * candidate quads, so join ordering can use true store cardinalities without
100
+ * issuing extra scans.
101
+ */
102
+ interface ScanEntry {
103
+ subject: Term;
104
+ predicate: Term;
105
+ object: Term;
106
+ candidates: RdfQuad[];
107
+ /**
108
+ * reifies marks a `?r rdf:reifies <<( s p o )>>` pattern, which joins by
109
+ * decomposing each candidate's quoted-triple-term object instead of
110
+ * matching the object position directly.
111
+ */
112
+ reifies?: boolean;
113
+ /**
114
+ * tripleTermObject marks a pattern whose object is a triple-term pattern
115
+ * `?s ?p <<( ?st ?pt ?ot )>>`, which joins by decomposing each candidate's
116
+ * triple-term object instead of probing the object position directly.
117
+ */
118
+ tripleTermObject?: boolean;
119
+ }
120
+ /**
121
+ * PatternStatistics is the statistics source for one query evaluation. It
122
+ * resolves PatternStats for a BGP pattern once per query, keyed by pattern
123
+ * signature, so the greedy join-order loop in evaluateWithReordering never
124
+ * re-derives them per step.
125
+ *
126
+ * Resolution order:
127
+ * 1. A store exposing estimateStats supplies its own numbers (cached).
128
+ * 2. Named-graph scopes (GRAPH) always derive from the pattern's scoped
129
+ * candidate scan — the store hook cannot see the scope, and the scoped
130
+ * candidates are exact for that graph.
131
+ * 3. Otherwise the bounded fallback derives the same shape from the
132
+ * pattern's already-scanned candidates: the exact cardinality plus a
133
+ * distinct-value pass capped at DISTINCT_SAMPLE_CAP candidates (exact
134
+ * below the cap, a deterministic evenly-spaced sample above it), so
135
+ * large stores never pay an unbounded counting pass.
136
+ */
137
+ export declare class PatternStatistics {
138
+ private readonly cache;
139
+ private readonly hook;
140
+ constructor(store: RdfSource<RdfQuad>);
141
+ /** hasHook reports whether the store exposes estimateStats. */
142
+ get hasHook(): boolean;
143
+ /**
144
+ * statsFor resolves the statistics for one scanned pattern within the
145
+ * given store scope (see class doc for the resolution order). The scope is
146
+ * the store view the pattern was scanned against; the result is cached by
147
+ * pattern signature per scope kind.
148
+ */
149
+ statsFor(storeView: RdfSource<RdfQuad>, entry: ScanEntry): Promise<PatternStats>;
150
+ private resolve;
151
+ }
152
+ /**
153
+ * JoinCostEstimator estimates the cost of joining one BGP triple pattern
154
+ * against the current solution bindings. The estimate drives the greedy
155
+ * join-order selection in BgpEvaluator.evaluateWithReordering — it must
156
+ * never change results, only the order in which patterns are joined
157
+ * (SPARQL 1.1 §18.2.2: joins commute, so every order yields the same
158
+ * solution multiset).
159
+ *
160
+ * Contract: an estimator receives the pattern's ScanEntry — whose
161
+ * candidates array holds the pattern's true store cardinality from the
162
+ * up-front scan in evaluateWithReordering — plus the current bindings and
163
+ * the pattern's statistics (planner piece 2, issue #129). Stats are
164
+ * optional: they carry the store's per-variable distinct-value counts (see
165
+ * PatternStats), and the estimator must degrade gracefully when absent (or
166
+ * when a variable's distinct count is unknown). It may assume nothing else:
167
+ * no store access. The estimator must be pure and deterministic: the same
168
+ * entry, bindings, and stats always produce the same cost, and calling it
169
+ * must have no side effects. The default baseline's costs are exactly the
170
+ * model the DP join-order search (planner piece 3, issue #130) optimizes
171
+ * over for small BGPs, so the two stay in agreement.
172
+ */
173
+ interface JoinCostEstimator {
174
+ /**
175
+ * estimatorKind optionally tags built-in estimators ("baseline" for
176
+ * BaselineJoinCostEstimator) so the evaluator dispatches without
177
+ * instanceof. Custom estimators omit it.
178
+ */
179
+ readonly estimatorKind?: string;
180
+ /**
181
+ * estimateJoinCost returns the estimated number of quad iterations
182
+ * joining the given pattern against the current bindings will perform.
183
+ * Lower is cheaper. A cost of 0 (for example, no bindings left to join)
184
+ * is valid. stats, when supplied, carries the pattern's store statistics
185
+ * (candidates and per-variable distinct counts); pass undefined when the
186
+ * caller has none.
187
+ */
188
+ estimateJoinCost(subjectVar: string | undefined, predicateVar: string | undefined, objectVar: string | undefined, candidateCount: number, bindingCount: number, stats?: PatternStats): number;
189
+ }
190
+ /**
191
+ * BaselineJoinCostEstimator is the default JoinCostEstimator: the greedy
192
+ * formula the engine shipped before the estimator seam existed, extended to
193
+ * use the piece-2 statistics when available. Bindings that bind no pattern
194
+ * variable iterate every candidate quad; bindings that bind a pattern
195
+ * variable probe the positional index, costing roughly the average bucket
196
+ * size for the bound variable with the fewest distinct bound values.
197
+ *
198
+ * The average bucket is candidate count divided by that variable's distinct
199
+ * count. The statistics source (PatternStatistics) supplies the store's
200
+ * distinct-value count for the pattern's variables, which is the true bucket
201
+ * average across the whole store; without stats (or for a variable the store
202
+ * has no count for), the estimator falls back to the distinct count of the
203
+ * values actually bound in the current bindings — the piece-1 behavior,
204
+ * which adapts to the join's current state but overestimates when few
205
+ * bindings remain. Either way the cost is a conservative per-binding bound.
206
+ */
207
+ export declare class BaselineJoinCostEstimator implements JoinCostEstimator {
208
+ /** estimatorKind marks this as the default baseline estimator. */
209
+ readonly estimatorKind = "baseline";
210
+ /**
211
+ * estimateJoinCost estimates join cost from binding count only. Greedy BGP
212
+ * reordering calls estimateBaselineJoinCost with full bindings instead.
213
+ */
214
+ estimateJoinCost(subjectVar: string | undefined, predicateVar: string | undefined, objectVar: string | undefined, candidateCount: number, bindingCount: number, stats?: PatternStats): number;
215
+ }
216
+ /**
217
+ * IriFunction evaluates a custom SPARQL 1.1 extension function (§17.4.3.1)
218
+ * registered under a function IRI. It receives the function's evaluated
219
+ * arguments (undefined for unbound variables and runtime type errors) and
220
+ * returns a result term, or undefined to signal an error — the same
221
+ * contract as the builtin expression surface: FILTER drops the binding,
222
+ * ORDER BY sorts it lowest.
223
+ */
224
+ type IriFunction = (args: ReadonlyArray<RdfTerm | undefined>) => RdfTerm | undefined;
225
+ /**
226
+ * IriFunctionMap maps function IRIs to their evaluators. Injected through
227
+ * WazooSparqlEngineOptions.functions; unregistered IRIs keep raising the
228
+ * "Unsupported SPARQL expression: functionCall <iri>" error.
229
+ */
230
+ type IriFunctionMap = Readonly<Record<string, IriFunction>>;
231
+ /**
232
+ * WazooSparqlTransaction is the minimal write contract the engine uses for updates.
233
+ * It mirrors the structural shape of @worlds/sdk's Transaction so durable
234
+ * backends can pass their existing transaction objects.
235
+ */
236
+ interface WazooSparqlTransaction {
237
+ /** add buffers a single quad for insertion on the next commit. */
238
+ add(quad: RdfQuad): unknown;
239
+ /** delete buffers a single quad for deletion on the next commit. */
240
+ delete(quad: RdfQuad): unknown;
241
+ /** commit persists the buffered patch. */
242
+ commit(): Promise<void>;
243
+ /** rollback discards any uncommitted insertions and deletions. */
244
+ rollback(): void;
245
+ }
246
+ /**
247
+ * WazooSparqlEngineOptions configures WazooSparqlEngine.
248
+ */
249
+ interface WazooSparqlEngineOptions {
250
+ /** store is the RDFJS store to execute queries on. */
251
+ store: RdfStore;
252
+ /**
253
+ * createTransaction is an optional factory to create a transaction for SPARQL
254
+ * UPDATEs. When provided, every update runs through one atomic transaction.
255
+ * When omitted, updates are applied directly to the store, which must then
256
+ * implement addQuad/removeQuad (as MemoryStore does).
257
+ */
258
+ createTransaction?: () => WazooSparqlTransaction;
259
+ /**
260
+ * reorderPatterns statically sorts BGP triple patterns by selectivity
261
+ * (constant count) before joining, so the most selective pattern runs
262
+ * first. Defaults to true. Disabling it preserves written order exactly.
263
+ */
264
+ reorderPatterns?: boolean;
265
+ /**
266
+ * functions registers custom IRI functions (SPARQL 1.1 §17.4.3.1): a map
267
+ * from function IRI to evaluator, injected like Comunica's function
268
+ * factory. A registered function receives its evaluated arguments and
269
+ * returns a term, or undefined for a type error (FILTER drops the row,
270
+ * ORDER BY sorts it lowest). Unregistered IRIs keep raising
271
+ * "Unsupported SPARQL expression: functionCall".
272
+ */
273
+ functions?: IriFunctionMap;
274
+ /**
275
+ * estimator supplies the BGP join-cost estimator (see JoinCostEstimator);
276
+ * defaults to the baseline formula, whose costs match the DP join-order
277
+ * search (issue #130) — small BGPs get the globally optimal order, larger
278
+ * ones the greedy stepwise choice. An injected custom estimator keeps the
279
+ * greedy loop. Only affects join order, never results.
280
+ */
281
+ estimator?: JoinCostEstimator;
282
+ /**
283
+ * readTextFile reads a local file for `LOAD <file://...>`. Defaults to
284
+ * Deno's reader under Deno; elsewhere (Node, Bun, native builds) pass
285
+ * one, e.g. `(path) => readFile(path, "utf8")` from `node:fs/promises`.
286
+ */
287
+ readTextFile?: (path: string) => Promise<string>;
288
+ /**
289
+ * loadPolicy governs `LOAD <http(s)://...>`. Absent, remote LOAD is
290
+ * denied; pass allowedHosts to opt in (see LoadPolicy).
291
+ */
292
+ loadPolicy?: LoadPolicy;
293
+ }
294
+ /**
295
+ * WazooSparqlEngine is the Wazoo SPARQL 1.1 & 1.2 engine over RDFJS Store sources.
296
+ */
297
+ export declare class WazooSparqlEngine implements SparqlEngineInterface {
298
+ private readonly options;
299
+ private readonly parser;
300
+ private readonly evaluator;
301
+ private readonly updateEvaluator;
302
+ /**
303
+ * Bounded cache of parsed queries keyed by the exact request string.
304
+ * Parsing measured ~40% of a sub-millisecond execute, and the AST is only
305
+ * ever read by the evaluators (never mutated), so repeated queries reuse
306
+ * the parse. Map preserves insertion order, giving cheap FIFO eviction.
307
+ */
308
+ private readonly queryCache;
309
+ private static readonly QUERY_CACHE_MAX;
310
+ constructor(options: WazooSparqlEngineOptions);
311
+ /**
312
+ * execute runs a SPARQL query/update against the configured store,
313
+ * enforcing timeoutMs and signal (issue #122): the request promise
314
+ * rejects on timeout or abort (Comunica's end-of-request shape), and the
315
+ * composed signal is threaded through the evaluator so cancellation also
316
+ * lands at the next pattern/join boundary.
317
+ */
318
+ execute(request: SparqlRequest): Promise<SparqlResponse>;
319
+ }
320
+ /**
321
+ * DP_MAX_PATTERNS is the largest BGP the DP join-order search explores.
322
+ * The subset DP costs 2^n states, each with up to n transitions, so 8
323
+ * patterns means at most 256 states and ~1,024 transitions of pure
324
+ * arithmetic — well under a millisecond, never a measurable fraction of the
325
+ * joins it plans. Real-world BGPs (and the entire W3C suite) stay at or
326
+ * below this; beyond it the greedy stepwise planner (planner pieces 1–2)
327
+ * takes over, where its per-step choice is within noise of optimal for the
328
+ * large shapes that hit the fallback.
329
+ */
330
+ export declare const DP_MAX_PATTERNS = 8;
331
+ /**
332
+ * EstimatedJoinState is the search's model of the solutions a partial plan
333
+ * has produced, without materializing them:
334
+ *
335
+ * - card — the estimated number of solution bindings the partial plan
336
+ * outputs (the next join's bindings count);
337
+ * - bound — the variables bound in at least one output binding (the next
338
+ * join's probeable pattern variables).
339
+ *
340
+ * The model is exact for the join semantics this engine uses: joining a
341
+ * pattern probes the positional index once per (binding, candidate) pair, so
342
+ * the estimated output cardinality equals the estimated join cost — no extra
343
+ * state beyond card and bound is needed to score the next join.
344
+ */
345
+ interface EstimatedJoinState {
346
+ card: number;
347
+ bound: ReadonlySet<string>;
348
+ }
349
+ /**
350
+ * searchBestJoinOrder returns the join order (indices into the entries
351
+ * array) minimizing the estimated total join work, or null when the BGP is
352
+ * too large for the DP (see DP_MAX_PATTERNS) — the caller then falls back to
353
+ * the greedy planner. The search is a subset DP over 2^n states: the state
354
+ * for a set S of joined patterns carries the cheapest plan's estimated cost
355
+ * (total work) and output state (card + bound), and the transition appends
356
+ * each remaining pattern at its estimated marginal cost. Ties keep the
357
+ * lowest-index pattern first, so the order is deterministic.
358
+ *
359
+ * The search is a plan search only — it never materializes bindings. The
360
+ * winning order is then executed by the normal eager join loop, so the DP
361
+ * changes only which order joins run in, never the result multiset
362
+ * (SPARQL 1.1 §18.2.2: joins commute).
363
+ */
364
+ export declare function searchBestJoinOrder(entries: ScanEntry[], statsList: PatternStats[], initialState: EstimatedJoinState): number[] | null;
365
+ export { type CanonicalTerm, DataFactory, type EstimatedJoinState, type IriFunction, type IriFunctionMap, type JoinCostEstimator, type LoadPolicy, MemoryStore, MemoryStream, NUMERIC_DATATYPES, type PatternStats, type SparqlAskResults, type SparqlBinding, type SparqlConstructResults, type SparqlEngineInterface, type SparqlRequest, type SparqlResponse, type SparqlSelectResults, SparqlSyntaxError, type SparqlValue, type StoreStatisticsHook, type TurtleFormat, type TurtleWriterOptions, type WazooSparqlEngineOptions, type WazooSparqlTransaction, XSD, XSD_BOOLEAN, XSD_DECIMAL, XSD_DOUBLE, XSD_FLOAT, XSD_INTEGER, XSD_STRING, canonicalizeRdfTerm, canonicalizeSparqlValue, compareNumericValues, compareRdfTerms, dataFactory, formatNumber, numericValue, parseTurtleQuads, rdfTermToSparqlValue, sameRdfTerm, serializeJsonResults, serializeTurtle, serializeXmlResults, sparqlTermToRdfTerm, termKey };