@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,335 @@
1
+ // src/serialize/json-results.ts
2
+ /**
3
+ * serializeJsonResults serializes a SELECT or ASK SparqlResponse into the
4
+ * SPARQL 1.1 Query Results JSON format ("application/sparql-results+json",
5
+ * the .srj serialization), extended with the SPARQL 1.2 direction and
6
+ * triple-term members the engine's wire format already carries.
7
+ *
8
+ * The response is already in the wire shape (src/sparql-engine-interface.ts):
9
+ * every SparqlValue is emitted as-is — uri/bnode as {type, value}; literals
10
+ * with their "xml:lang", "its:dir" (RDF 1.2 base direction), and datatype
11
+ * members; RDF 1.2 triple terms as the nested {type: "triple", value:
12
+ * {subject, predicate, object}} object — so this is a document builder, not a
13
+ * term re-encoder.
14
+ *
15
+ * Coverage: SELECT (head.vars + results.bindings) and ASK (boolean). The
16
+ * format does not cover CONSTRUCT/DESCRIBE (RDF graph results, serialized as
17
+ * RDF) or updates (void responses carry no result body) — those kinds throw
18
+ * a clear error.
19
+ *
20
+ * Output is deterministic: members are emitted in a fixed order (head, then
21
+ * results/boolean; for literals type, value, xml:lang, its:dir, datatype), so
22
+ * equal responses produce byte-identical documents.
23
+ */
24
+ function serializeJsonResults(response) {
25
+ switch (response.kind) {
26
+ case "select": {
27
+ const head = response.data.head;
28
+ return JSON.stringify({
29
+ head: head.link?.length ? {
30
+ vars: head.vars,
31
+ link: head.link
32
+ } : { vars: head.vars },
33
+ results: { bindings: response.data.results.bindings }
34
+ });
35
+ }
36
+ case "ask": {
37
+ const head = response.data.head;
38
+ if (head.link?.length) return JSON.stringify({
39
+ head: { link: head.link },
40
+ boolean: response.data.boolean
41
+ });
42
+ return JSON.stringify({
43
+ head: {},
44
+ boolean: response.data.boolean
45
+ });
46
+ }
47
+ case "construct":
48
+ case "void": throw new Error(`serializeJsonResults: cannot serialize a ${response.kind} response — the SPARQL results JSON format covers SELECT and ASK only (CONSTRUCT/DESCRIBE results are RDF graphs; updates have no result body)`);
49
+ }
50
+ }
51
+ // src/serialize/xml-results.ts
52
+ /**
53
+ * serializeXmlResults serializes a SELECT or ASK SparqlResponse into the
54
+ * SPARQL 1.1 Query Results XML format ("application/sparql-results+xml", the
55
+ * .srx serialization), extended with the SPARQL 1.2 surface the engine's wire
56
+ * format carries: RDF 1.2 triple terms as nested <subject>/<predicate>/<object>
57
+ * elements, and the base direction of a directional language-tagged literal
58
+ * as the its:dir attribute (ITS 2.0 namespace, mirroring how the SPARQL 1.2
59
+ * results JSON format carries it) — matching the shape of the vendored
60
+ * sparql12 .srx fixtures.
61
+ *
62
+ * Coverage: SELECT (head variables + one <result> per binding) and ASK
63
+ * (<boolean>). The format does not cover CONSTRUCT/DESCRIBE (RDF graph
64
+ * results, serialized as RDF) or updates (void responses carry no result
65
+ * body) — those kinds throw a clear error.
66
+ *
67
+ * Output is deterministic: elements are emitted in a fixed order with
68
+ * two-space indentation, and every text/attribute value is XML-escaped
69
+ * (&, <, >, ", '), so equal responses produce byte-identical documents.
70
+ */
71
+ function serializeXmlResults(response) {
72
+ const out = [];
73
+ out.push("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
74
+ out.push("<sparql xmlns=\"http://www.w3.org/2005/sparql-results#\" xmlns:its=\"http://www.w3.org/2005/11/its\" its:version=\"2.0\">");
75
+ switch (response.kind) {
76
+ case "select":
77
+ out.push(" <head>");
78
+ for (const variable of response.data.head.vars) out.push(` <variable name="${escapeAttr(variable)}"/>`);
79
+ for (const link of response.data.head.link ?? []) out.push(` <link href="${escapeAttr(link)}"/>`);
80
+ out.push(" </head>");
81
+ out.push(" <results>");
82
+ for (const binding of response.data.results.bindings) {
83
+ out.push(" <result>");
84
+ for (const name of Object.keys(binding)) {
85
+ out.push(` <binding name="${escapeAttr(name)}">`);
86
+ pushTerm(out, binding[name], 8);
87
+ out.push(" </binding>");
88
+ }
89
+ out.push(" </result>");
90
+ }
91
+ out.push(" </results>");
92
+ break;
93
+ case "ask":
94
+ out.push(" <head>");
95
+ for (const link of response.data.head.link ?? []) out.push(` <link href="${escapeAttr(link)}"/>`);
96
+ out.push(" </head>");
97
+ out.push(` <boolean>${response.data.boolean}</boolean>`);
98
+ break;
99
+ case "construct":
100
+ case "void": throw new Error(`serializeXmlResults: cannot serialize a ${response.kind} response — the SPARQL results XML format covers SELECT and ASK only (CONSTRUCT/DESCRIBE results are RDF graphs; updates have no result body)`);
101
+ }
102
+ out.push("</sparql>");
103
+ return out.join("\n") + "\n";
104
+ }
105
+ /**
106
+ * pushTerm appends one SparqlValue as its XML term element. Literals carry
107
+ * their xml:lang (plus the RDF 1.2 its:dir attribute when directional) or
108
+ * their datatype; triple terms nest a subject/predicate/object wrapper, each
109
+ * holding a term element — the SPARQL 1.2 triple-term results encoding.
110
+ */
111
+ function pushTerm(out, value, indent) {
112
+ const pad = " ".repeat(indent);
113
+ switch (value.type) {
114
+ case "uri":
115
+ out.push(`${pad}<uri>${escapeText(value.value)}</uri>`);
116
+ break;
117
+ case "bnode":
118
+ out.push(`${pad}<bnode>${escapeText(value.value)}</bnode>`);
119
+ break;
120
+ case "literal": {
121
+ const attributes = [];
122
+ if (value["xml:lang"]) {
123
+ attributes.push(`xml:lang="${escapeAttr(value["xml:lang"])}"`);
124
+ if (value["its:dir"]) attributes.push(`its:dir="${escapeAttr(value["its:dir"])}"`);
125
+ } else if (value.datatype) attributes.push(`datatype="${escapeAttr(value.datatype)}"`);
126
+ out.push(`${pad}<literal${attributes.length > 0 ? " " + attributes.join(" ") : ""}>${escapeText(value.value)}</literal>`);
127
+ break;
128
+ }
129
+ case "triple":
130
+ out.push(`${pad}<triple>`);
131
+ pushTriplePart(out, "subject", value.value.subject, indent + 2);
132
+ pushTriplePart(out, "predicate", value.value.predicate, indent + 2);
133
+ pushTriplePart(out, "object", value.value.object, indent + 2);
134
+ out.push(`${pad}</triple>`);
135
+ }
136
+ }
137
+ /** pushTriplePart wraps one triple-term position in its role element. */
138
+ function pushTriplePart(out, role, value, indent) {
139
+ const pad = " ".repeat(indent);
140
+ out.push(`${pad}<${role}>`);
141
+ pushTerm(out, value, indent + 2);
142
+ out.push(`${pad}</${role}>`);
143
+ }
144
+ /**
145
+ * UNREPRESENTABLE matches a character no XML 1.0 document may contain, even as a
146
+ * reference: C0 controls other than tab, line feed and carriage return, lone
147
+ * surrogates, U+FFFE and U+FFFF.
148
+ */
149
+ const UNREPRESENTABLE = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uD800-\uDFFF￾￿]/u;
150
+ /**
151
+ * escapeText XML-escapes text content. A carriage return is written as a
152
+ * reference, because a parser would otherwise read it as a line feed. It throws
153
+ * for a character XML cannot carry rather than writing a malformed document.
154
+ */
155
+ function escapeText(text) {
156
+ if (UNREPRESENTABLE.test(text)) throw new Error("serializeXmlResults: a term contains a character XML 1.0 cannot represent");
157
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\r/g, "&#xD;");
158
+ }
159
+ /**
160
+ * escapeAttr XML-escapes an attribute value. Tabs and line feeds are written as
161
+ * references so a parser does not turn them into spaces.
162
+ */
163
+ function escapeAttr(text) {
164
+ return escapeText(text).replace(/"/g, "&quot;").replace(/'/g, "&apos;").replace(/\t/g, "&#x9;").replace(/\n/g, "&#xA;");
165
+ }
166
+ // src/serialize/turtle-escape.ts
167
+ /**
168
+ * escapeIri escapes a value for use inside `<...>` (IRIREF grammar). The
169
+ * grammar only permits `\u`/`\U` escapes inside an IRI (a literal backslash
170
+ * is excluded), so every forbidden character is emitted as a UCHAR rather
171
+ * than a backslash-escaped form.
172
+ */
173
+ function escapeIri(value) {
174
+ let out = "";
175
+ for (const ch of value) {
176
+ const code = ch.codePointAt(0);
177
+ if (ch === "\\" || ch === ">" || ch === "<" || ch === "\"" || ch === "{" || ch === "}" || ch === "|" || ch === "^" || ch === "`" || code <= 32) out += `\\u${code.toString(16).padStart(4, "0")}`;
178
+ else out += ch;
179
+ }
180
+ return out;
181
+ }
182
+ /** escapeLiteral escapes a literal value for use inside `"..."` (STRING_LITERAL_QUOTE grammar). */
183
+ function escapeLiteral(value) {
184
+ let out = "";
185
+ for (const ch of value) switch (ch) {
186
+ case "\\":
187
+ out += "\\\\";
188
+ break;
189
+ case "\"":
190
+ out += "\\\"";
191
+ break;
192
+ case "\n":
193
+ out += "\\n";
194
+ break;
195
+ case "\r":
196
+ out += "\\r";
197
+ break;
198
+ case " ":
199
+ out += "\\t";
200
+ break;
201
+ default: {
202
+ const code = ch.codePointAt(0);
203
+ out += code <= 31 ? `\\u${code.toString(16).padStart(4, "0")}` : ch;
204
+ }
205
+ }
206
+ return out;
207
+ }
208
+ /** LABEL_START matches a character a blank node label may begin with: PN_CHARS_U or a digit. */
209
+ const LABEL_START = /^[A-Za-z0-9_\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}]$/u;
210
+ /** LABEL_TAIL_ONLY matches the PN_CHARS a label may contain but not begin with. */
211
+ const LABEL_TAIL_ONLY = /^[\u0300-\u036F\u203F\u2040-]$/u;
212
+ /**
213
+ * escapeBlankNodeLabel escapes a blank node label for the BLANK_NODE_LABEL
214
+ * grammar, hex-encoding a character the grammar does not allow at that position
215
+ * the same way the reference implementations do (`_xHH_`). A label may not start
216
+ * with "-" or ".", nor end with ".". A dot right after a dot is encoded too:
217
+ * the grammar allows it, but n3 does not read it.
218
+ */
219
+ function escapeBlankNodeLabel(value) {
220
+ let out = "";
221
+ let offset = 0;
222
+ let afterDot = false;
223
+ for (const ch of value) {
224
+ const first = offset === 0;
225
+ offset += ch.length;
226
+ const safe = LABEL_START.test(ch) || !first && LABEL_TAIL_ONLY.test(ch) || !first && !afterDot && offset < value.length && ch === ".";
227
+ afterDot = safe && ch === ".";
228
+ const code = ch.codePointAt(0);
229
+ out += safe ? ch : `_x${code.toString(16).toUpperCase().padStart(2, "0")}_`;
230
+ }
231
+ return out;
232
+ }
233
+ // src/serialize/turtle-term.ts
234
+ const XSD_STRING = "http://www.w3.org/2001/XMLSchema#string";
235
+ const RDF_LANG_STRING = "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString";
236
+ /** term serializes a single RDF/JS term (Turtle term grammar). */
237
+ function term(t, prefixes = {}) {
238
+ switch (t.termType) {
239
+ case "NamedNode": return iriTerm(t.value, prefixes);
240
+ case "BlankNode": return `_:${escapeBlankNodeLabel(t.value)}`;
241
+ case "Literal": return literalTerm(t, prefixes);
242
+ case "Quad": return `<<( ${term(t.subject, prefixes)} ${term(t.predicate, prefixes)} ${term(t.object, prefixes)} )>>`;
243
+ default: throw new Error(`Cannot serialize ${t.termType} term in Turtle: ${t.value}`);
244
+ }
245
+ }
246
+ /** iriTerm renders an IRI as a prefixed name when a registered namespace matches. */
247
+ function iriTerm(value, prefixes) {
248
+ for (const [prefix, namespace] of Object.entries(prefixes)) if (prefix.length > 0 && namespace.length > 0 && value.startsWith(namespace)) {
249
+ const local = value.slice(namespace.length);
250
+ if (/^[A-Za-z0-9_](?:[A-Za-z0-9_.-]*[A-Za-z0-9_-])?$/.test(local)) return `${prefix}:${local}`;
251
+ }
252
+ return `<${escapeIri(value)}>`;
253
+ }
254
+ /** literalTerm renders a literal with language/direction or datatype suffix. */
255
+ function literalTerm(term, prefixes) {
256
+ const value = `"${escapeLiteral(term.value)}"`;
257
+ if (term.language) {
258
+ const direction = term.direction ? `--${term.direction}` : "";
259
+ return `${value}@${term.language}${direction}`;
260
+ }
261
+ if (term.datatype.value !== XSD_STRING && term.datatype.value !== RDF_LANG_STRING) return `${value}^^${iriTerm(term.datatype.value, prefixes)}`;
262
+ return value;
263
+ }
264
+ // src/serialize/turtle-writer.ts
265
+ /**
266
+ * serializeTurtle serializes RDF/JS quads into a Turtle-family document.
267
+ *
268
+ * It is the writer counterpart to `parseTurtleQuads`: the two round-trip
269
+ * losslessly over Turtle, TriG, N-Quads, and N-Triples, including RDF 1.2
270
+ * triple terms (`<<( s p o )>>`), directional language literals
271
+ * (`"v"@en--ltr`), and named graphs. Output preserves input order and groups
272
+ * statements by subject and predicate (`,` and `;` shorthand) in Turtle mode.
273
+ *
274
+ * @param quads quads to serialize
275
+ * @param options format and prefix configuration
276
+ * @returns the serialized document (trailing newline, empty string for no quads)
277
+ */
278
+ function serializeTurtle(quads, options = {}) {
279
+ const format = options.format ?? "turtle";
280
+ const quadArray = quads;
281
+ if (quadArray.length === 0) return "";
282
+ if (format === "n-quads") return quadArray.map((q) => `${term(q.subject)} ${term(q.predicate)} ${term(q.object)}${q.graph.termType === "DefaultGraph" ? "" : ` ${term(q.graph)}`} .`).join("\n") + "\n";
283
+ if (format === "n-triples") return quadArray.map((q) => {
284
+ if (q.graph.termType !== "DefaultGraph") throw new Error(`N-Triples cannot serialize quads with a named graph (${term(q.graph)}); use Turtle or N-Quads for graph data.`);
285
+ return `${term(q.subject)} ${term(q.predicate)} ${term(q.object)} .`;
286
+ }).join("\n") + "\n";
287
+ const prefixes = options.prefixes ?? {};
288
+ const prefixLines = Object.entries(prefixes).map(([prefix, iri]) => `@prefix ${prefix}: <${escapeIri(iri)}> .`);
289
+ const defaultGraph = [];
290
+ const byGraph = /* @__PURE__ */ new Map();
291
+ for (const q of quadArray) if (q.graph.termType === "DefaultGraph") defaultGraph.push(q);
292
+ else {
293
+ const key = term(q.graph);
294
+ const bucket = byGraph.get(key);
295
+ if (bucket) bucket.push(q);
296
+ else byGraph.set(key, [q]);
297
+ }
298
+ const lines = [...prefixLines];
299
+ const defaultStatements = statementLines(defaultGraph, prefixes);
300
+ lines.push(...defaultStatements);
301
+ for (const [graphKey, graphQuads] of byGraph) {
302
+ lines.push(`${graphKey} {`);
303
+ lines.push(...statementLines(graphQuads, prefixes).map((l) => ` ${l}`));
304
+ lines.push("}");
305
+ }
306
+ return lines.filter((line) => line.length > 0).join("\n") + "\n";
307
+ }
308
+ /**
309
+ * statementLines renders quads grouped by subject, with `;` between predicate
310
+ * groups and `,` between objects of the same predicate.
311
+ */
312
+ function statementLines(quads, prefixes) {
313
+ const bySubject = /* @__PURE__ */ new Map();
314
+ for (const q of quads) {
315
+ const key = term(q.subject, prefixes);
316
+ const bucket = bySubject.get(key);
317
+ if (bucket) bucket.push(q);
318
+ else bySubject.set(key, [q]);
319
+ }
320
+ const lines = [];
321
+ for (const [subjectKey, subjectQuads] of bySubject) {
322
+ const byPredicate = /* @__PURE__ */ new Map();
323
+ for (const q of subjectQuads) {
324
+ const key = term(q.predicate, prefixes);
325
+ const bucket = byPredicate.get(key);
326
+ if (bucket) bucket.push(q);
327
+ else byPredicate.set(key, [q]);
328
+ }
329
+ const predicateGroups = [];
330
+ for (const [predicateKey, predicateQuads] of byPredicate) predicateGroups.push(predicateKey + " " + predicateQuads.map((q) => term(q.object, prefixes)).join(", "));
331
+ lines.push(subjectKey + " " + predicateGroups.join(" ;\n ") + " .");
332
+ }
333
+ return lines;
334
+ }
335
+ export { serializeXmlResults as n, serializeJsonResults as r, serializeTurtle as t };
@@ -0,0 +1,2 @@
1
+ import { a as serializeJsonResults, i as serializeXmlResults, n as TurtleWriterOptions, r as serializeTurtle, t as TurtleFormat } from "./mod-C4GFefO7.js";
2
+ export { type TurtleFormat, type TurtleWriterOptions, serializeJsonResults, serializeTurtle, serializeXmlResults };
@@ -0,0 +1 @@
1
+ export { r as serializeJsonResults, t as serializeTurtle, n as serializeXmlResults } from "./serialize-BSkHhuBp.js";
@@ -0,0 +1,102 @@
1
+ import { i as RdfQuad } from "./rdf-terms-DGpxNnyn.js";
2
+ /**
3
+ * SparqlEngineInterface executes raw SPARQL queries/updates against a data adapter.
4
+ */
5
+ interface SparqlEngineInterface {
6
+ /**
7
+ * execute fires a SPARQL request and returns a strongly typed response.
8
+ *
9
+ * @param request contains the raw query string and execution settings.
10
+ */
11
+ execute(request: SparqlRequest): Promise<SparqlResponse>;
12
+ }
13
+ /**
14
+ * SparqlRequest is the request type for evaluating SPARQL operations.
15
+ */
16
+ interface SparqlRequest {
17
+ /** The raw SPARQL query string. */
18
+ query: string;
19
+ /** Base IRI for the query execution. */
20
+ baseIri?: string;
21
+ /** Query timeout in milliseconds (defaults to 30 seconds). */
22
+ timeoutMs?: number;
23
+ /**
24
+ * signal aborts the request: the execute promise rejects (with the
25
+ * signal's reason when it is an Error, else a generic abort error) and
26
+ * the evaluation is cancelled at the next pattern/join boundary. The
27
+ * engine composes it with the timeout — whichever fires first wins.
28
+ */
29
+ signal?: AbortSignal;
30
+ }
31
+ /**
32
+ * SparqlResponse is the encapsulated response wrapping typed result packets.
33
+ */
34
+ type SparqlResponse = {
35
+ kind: "select";
36
+ data: SparqlSelectResults;
37
+ } | {
38
+ kind: "ask";
39
+ data: SparqlAskResults;
40
+ } | {
41
+ kind: "construct";
42
+ data: SparqlConstructResults;
43
+ } | {
44
+ kind: "void";
45
+ };
46
+ /**
47
+ * SparqlAskResults is the specific format for an ASK boolean query.
48
+ */
49
+ interface SparqlAskResults {
50
+ head: {
51
+ link?: Array<string> | null;
52
+ };
53
+ boolean: boolean;
54
+ }
55
+ /**
56
+ * SparqlSelectResults is the tabular format returned by SELECT queries.
57
+ */
58
+ interface SparqlSelectResults {
59
+ head: {
60
+ vars: Array<string>;
61
+ link?: Array<string> | null;
62
+ };
63
+ results: {
64
+ bindings: Array<SparqlBinding>;
65
+ };
66
+ }
67
+ /**
68
+ * SparqlConstructResults is the quad stream returned by CONSTRUCT/DESCRIBE queries.
69
+ */
70
+ interface SparqlConstructResults {
71
+ quads: Array<RdfQuad>;
72
+ }
73
+ /**
74
+ * SparqlValue is a specific value bound to a variable within a SPARQL result
75
+ * binding.
76
+ */
77
+ type SparqlValue = {
78
+ type: "uri";
79
+ value: string;
80
+ } | {
81
+ type: "bnode";
82
+ value: string;
83
+ } | {
84
+ type: "literal";
85
+ value: string;
86
+ "xml:lang"?: string;
87
+ /** Base direction ("ltr"/"rtl") of an RDF 1.2 directional language-tagged literal, per the SPARQL 1.2 results JSON/XML formats. */
88
+ "its:dir"?: "ltr" | "rtl";
89
+ datatype?: string;
90
+ } | {
91
+ type: "triple";
92
+ value: {
93
+ subject: SparqlValue;
94
+ predicate: SparqlValue;
95
+ object: SparqlValue;
96
+ };
97
+ };
98
+ /**
99
+ * SparqlBinding is a map associating specific variable identifiers to resolved values.
100
+ */
101
+ type SparqlBinding = Record<string, SparqlValue>;
102
+ export { SparqlRequest as a, SparqlValue as c, SparqlEngineInterface as i, SparqlBinding as n, SparqlResponse as o, SparqlConstructResults as r, SparqlSelectResults as s, SparqlAskResults as t };
@@ -0,0 +1,2 @@
1
+ import { n as MemoryStream, t as MemoryStore } from "./memory-store-DhAGI-j6.js";
2
+ export { MemoryStore, MemoryStream };
package/dist/store.js ADDED
@@ -0,0 +1 @@
1
+ export { t as MemoryStore, n as MemoryStream } from "./memory-store-Mq4x2Ya1.js";