@manta-eu/datalog-parser 0.1.0

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/dist/index.js ADDED
@@ -0,0 +1,2871 @@
1
+ var br = Object.defineProperty;
2
+ var Or = (e, t, r) => t in e ? br(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r;
3
+ var d = (e, t, r) => Or(e, typeof t != "symbol" ? t + "" : t, r);
4
+ import { match as p, P as u } from "ts-pattern";
5
+ import Ie from "decimal.js";
6
+ import { GeneratorBuilder as xr, ParserBuilder as P } from "@traqula/core";
7
+ import { sparql11GeneratorBuilder as Mt } from "@traqula/generator-sparql-1-1";
8
+ import { AstFactory as vr, lex as ze, completeGeneratorContext as Cr, gram as n, MinimalSparqlParser as Ir, sparqlCodepointEscape as Mr } from "@traqula/rules-sparql-1-1";
9
+ import { createToken as c, Lexer as Bt, CstParser as Br, EOF as Fr } from "chevrotain";
10
+ import { z as q } from "zod";
11
+ const Mn = (e) => p(e).with({ type: "triple" }, () => !0).otherwise(() => !1), Bn = (e) => p(e).with({ type: "property" }, () => !0).otherwise(() => !1), Fn = (e) => p(e).with({ type: "class" }, () => !0).otherwise(() => !1), Pn = (e) => p(e).with({ type: "general" }, () => !0).otherwise(() => !1), I = (e) => p(e).with({ type: "variable" }, () => !0).otherwise(() => !1), kn = (e) => p(e).with({ type: "iri" }, () => !0).otherwise(() => !1), tt = (e) => p(e).with({ type: "literal" }, () => !0).otherwise(() => !1), Dn = (e) => p(e).with({ type: "blank" }, () => !0).otherwise(() => !1), $n = (e) => p(e).with({ type: "negation" }, () => !0).otherwise(() => !1), Gn = (e) => p(e).with({ type: "filter" }, () => !0).otherwise(() => !1), _n = (e) => p(e).with({ type: "bind" }, () => !0).otherwise(() => !1), Vn = (e) => p(e).with({ type: "aggregate" }, () => !0).otherwise(() => !1), jn = (e) => p(e).with({ type: "skolem" }, () => !0).otherwise(() => !1), qn = (e) => p(e).with({ type: "binary" }, () => !0).otherwise(() => !1), Xn = (e) => p(e).with({ type: "unary" }, () => !0).otherwise(() => !1), Hn = (e) => p(e).with({ type: "term" }, () => !0).otherwise(() => !1), Qn = (e) => p(e).with({ type: "function" }, () => !0).otherwise(() => !1), zn = (e) => p(e).with({ type: "triple" }, () => "triple").with({ type: "property" }, () => "property").with({ type: "class" }, () => "class").with({ type: "general" }, () => "general").exhaustive(), Kn = (e) => p(e).with({ type: "variable" }, () => "variable").with({ type: "iri" }, () => "iri").with({ type: "literal" }, () => "literal").with({ type: "blank" }, () => "blank").exhaustive(), Wn = (e) => p(e).with({ type: "binary" }, () => "binary").with({ type: "unary" }, () => "unary").with({ type: "term" }, () => "term").with({ type: "function" }, () => "function").with({ type: "in" }, () => "in").exhaustive(), Pr = (e) => p(e).with({ type: "triple" }, (t) => [t.subject, t.predicate, t.object].filter(I)).with({ type: "property" }, (t) => [t.subject, t.object].filter(I)).with({ type: "class" }, (t) => [t.instance].filter(I)).with({ type: "general" }, (t) => t.terms.filter(I)).exhaustive(), kr = (e) => {
12
+ const t = Pr(e), r = "graph" in e ? e.graph : void 0;
13
+ return r && I(r) ? [...t, r] : t;
14
+ }, Yn = (e) => e.function, Zn = (e) => p(e).with(u.union("+", "-", "*", "/", "<", ">", "<=", ">="), () => !0).with(u.union("=", "!=", "||", "&&"), () => !1).exhaustive(), Jn = (e) => p(e).with(u.union("||", "&&", "=", "!=", "<", ">", "<=", ">="), () => !0).with(u.union("+", "-", "*", "/"), () => !1).exhaustive(), Ke = '[^\\s<>"{}|^`\\\\]', Dr = new RegExp(`^[a-z][a-z0-9+.-]*:${Ke}*$`, "i");
15
+ function ts(e) {
16
+ return Dr.test(e);
17
+ }
18
+ function We(e) {
19
+ return e.includes("://");
20
+ }
21
+ const $r = /^(true|false)$/i, Gr = /^"(true|false)"\^\^<?\S*boolean>?$/i, St = "[eE][+-]?\\d+", _r = new RegExp(
22
+ `^[+-]?(?:\\d+\\.\\d*(?:${St})|\\d+\\.\\d+|\\.\\d+(?:${St})?|\\d+(?:${St})?)$`
23
+ );
24
+ function Rt(e) {
25
+ return _r.test(e);
26
+ }
27
+ const Vr = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/, jr = 21;
28
+ function qr(e, t) {
29
+ return t <= 0 ? { integer: "0", fraction: "0".repeat(-t) + e } : t >= e.length ? { integer: e + "0".repeat(t - e.length), fraction: "" } : { integer: e.slice(0, t), fraction: e.slice(t) };
30
+ }
31
+ function Xr(e) {
32
+ const t = Rt(e) ? e.match(Vr) : null;
33
+ if (!t) return e;
34
+ const [, r = "", i = "", s = "", a] = t, o = i + s, l = i.length + Number(a ?? 0);
35
+ if (o.length + Math.abs(l) > jr) return e;
36
+ const E = qr(o, l), y = E.integer.replace(/^0+(?=\d)/, ""), S = E.fraction.replace(/0+$/, ""), h = S ? `${y}.${S}` : y;
37
+ return h === "0" || r === "+" ? h : `${r}${h}`;
38
+ }
39
+ function es(e) {
40
+ if ($r.test(e)) return e.toLowerCase() === "true";
41
+ const t = e.match(Gr);
42
+ if (t != null && t[1]) return t[1].toLowerCase() === "true";
43
+ }
44
+ const bt = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", Ot = "http://www.w3.org/2001/XMLSchema#", j = {
45
+ integer: "xsd:integer",
46
+ decimal: "xsd:decimal",
47
+ double: "xsd:double",
48
+ boolean: "xsd:boolean",
49
+ string: "xsd:string",
50
+ date: "xsd:date",
51
+ dateTime: "xsd:dateTime"
52
+ }, Hr = ["integer", "decimal", "double"], Me = {
53
+ "||": 1,
54
+ "&&": 2,
55
+ "=": 3,
56
+ "!=": 3,
57
+ "<": 3,
58
+ ">": 3,
59
+ "<=": 3,
60
+ ">=": 3,
61
+ "+": 4,
62
+ "-": 4,
63
+ "*": 5,
64
+ "/": 5
65
+ }, Ft = {
66
+ "=": "=",
67
+ "!=": "!=",
68
+ "<": ">",
69
+ "<=": ">=",
70
+ ">": "<",
71
+ ">=": "<="
72
+ };
73
+ function Be(e) {
74
+ return p(e).with({ type: u.union("triple", "property", "class", "general") }, () => !0).otherwise(() => !1);
75
+ }
76
+ function B(e) {
77
+ return p(e).with({ type: "binary" }, ({ left: t, right: r }) => B(t) || B(r)).with({ type: "unary" }, ({ operand: t }) => B(t)).with({ type: "term" }, () => !1).with(
78
+ { type: "function" },
79
+ ({ name: t, args: r }) => t.toUpperCase() === "SKOLEM" || r.some(B)
80
+ ).with(
81
+ { type: "in" },
82
+ ({ expression: t, list: r }) => B(t) || r.some(B)
83
+ ).exhaustive();
84
+ }
85
+ function xt(e) {
86
+ return p(e).with({ type: "skolem" }, () => !0).with({ type: u.union("filter", "bind") }, ({ expression: t }) => B(t)).with({ type: "negation" }, ({ formulas: t }) => t.some(xt)).with(
87
+ { type: "aggregate" },
88
+ ({ atoms: t, bindings: r }) => t.some(xt) || ((r == null ? void 0 : r.some(
89
+ ({ expression: i, secondExpression: s }) => i !== "*" && B(i) || s !== void 0 && B(s)
90
+ )) ?? !1)
91
+ ).with({ type: u.union("triple", "property", "class", "general") }, () => !1).exhaustive();
92
+ }
93
+ function Ye(e) {
94
+ return e.some((t) => t.type !== "negation" && xt(t));
95
+ }
96
+ function Ze(e) {
97
+ return p(e).with({ type: "class" }, (t) => ({
98
+ className: t.className,
99
+ instance: t.instance,
100
+ graph: t.graph
101
+ })).with(
102
+ {
103
+ type: "property",
104
+ predicate: u.union("a", "rdf:type", bt),
105
+ object: { type: "iri" }
106
+ },
107
+ (t) => ({
108
+ className: t.object.value,
109
+ instance: t.subject,
110
+ graph: t.graph
111
+ })
112
+ ).with(
113
+ {
114
+ type: "triple",
115
+ predicate: { type: "iri", value: u.union("a", "rdf:type", bt) },
116
+ object: { type: "iri" }
117
+ },
118
+ (t) => ({
119
+ className: t.object.value,
120
+ instance: t.subject,
121
+ graph: t.graph
122
+ })
123
+ ).otherwise(() => null);
124
+ }
125
+ function Je(e) {
126
+ return p(e).with({ type: "property" }, (t) => ({
127
+ predicate: t.predicate,
128
+ subject: t.subject,
129
+ object: t.object,
130
+ graph: t.graph
131
+ })).with(
132
+ { type: "triple", predicate: { type: "iri", value: u.not(u.union("a", "rdf:type", bt)) } },
133
+ (t) => ({
134
+ predicate: t.predicate.value,
135
+ subject: t.subject,
136
+ object: t.object,
137
+ graph: t.graph
138
+ })
139
+ ).otherwise(() => null);
140
+ }
141
+ function rs(e) {
142
+ return e in Ft;
143
+ }
144
+ function is(e) {
145
+ return Ft[e];
146
+ }
147
+ function it(e, t) {
148
+ return e === j[t] || e === `${Ot}${t}`;
149
+ }
150
+ function Fe(e) {
151
+ const { datatype: t } = e;
152
+ if (!(!t || it(t, "string")))
153
+ return t.startsWith(Ot) ? `xsd:${t.slice(Ot.length)}` : t;
154
+ }
155
+ function tr(e, t) {
156
+ return p([e, t]).with([{ type: "literal" }, { type: "literal" }], ([r, i]) => Q(r) && Q(i) && Rt(r.value) && Rt(i.value) ? new Ie(r.value).equals(new Ie(i.value)) : r.value === i.value && r.language === i.language && Fe(r) === Fe(i)).with([{ type: "iri" }, { type: "iri" }], ([r, i]) => r.value === i.value).with([{ type: "blank" }, { type: "blank" }], ([r, i]) => r.label === i.label).with([{ type: "variable" }, { type: "variable" }], ([r, i]) => r.name === i.name).otherwise(() => !1);
157
+ }
158
+ function Q(e) {
159
+ return Hr.some((t) => it(e.datatype, t));
160
+ }
161
+ function ns(e) {
162
+ return !Q(e) || !e.termSpan || !e.valueSpan ? !1 : e.termSpan.start === e.valueSpan.start && e.termSpan.end === e.valueSpan.end;
163
+ }
164
+ function ss(e) {
165
+ return tt(e) && Q(e);
166
+ }
167
+ function er(e) {
168
+ return it(e.datatype, "boolean");
169
+ }
170
+ function Qr(e) {
171
+ return it(e.datatype, "date");
172
+ }
173
+ function zr(e) {
174
+ return it(e.datatype, "dateTime");
175
+ }
176
+ function as(e) {
177
+ return Q(e) ? Xr(e.value) : er(e) || Qr(e) ? e.value : zr(e) ? e.value.replace("T", " ") : JSON.stringify(e.value);
178
+ }
179
+ function os(e) {
180
+ return Kr(e.expression);
181
+ }
182
+ function Kr(e) {
183
+ return p(e).with(
184
+ { type: "binary", operator: u.union("=", "!=", "<", ">", "<=", ">=") },
185
+ (t) => {
186
+ const r = G(t.left), i = G(t.right);
187
+ return !r || !i ? null : I(r) && tt(i) ? { variableName: r.name, operator: t.operator, literal: i } : tt(r) && I(i) ? {
188
+ variableName: i.name,
189
+ operator: Ft[t.operator],
190
+ literal: r
191
+ } : null;
192
+ }
193
+ ).otherwise(() => null);
194
+ }
195
+ function Wr(e) {
196
+ return p(e).returnType().with(
197
+ { type: "binary", operator: "=" },
198
+ (t) => p([G(t.left), G(t.right)]).returnType().with([u.not(u.nullish), { type: "literal" }], ([r, i]) => ({ subject: r, literal: i })).with([{ type: "literal" }, u.not(u.nullish)], ([r, i]) => ({ subject: i, literal: r })).otherwise(() => null)
199
+ ).otherwise(() => null);
200
+ }
201
+ function ls(e) {
202
+ var s;
203
+ if (e.type === "in") {
204
+ const a = G(e.expression), o = e.list.flatMap((l) => {
205
+ const E = ti(l);
206
+ return E ? [E] : [];
207
+ });
208
+ return a && o.length > 0 && o.length === e.list.length ? { subject: a, literals: o, negated: e.negated } : null;
209
+ }
210
+ const t = vt(e, "||");
211
+ if (t.length < 2) return null;
212
+ const r = t.flatMap((a) => {
213
+ const o = Wr(a);
214
+ return o ? [o] : [];
215
+ });
216
+ if (r.length !== t.length) return null;
217
+ const i = (s = r[0]) == null ? void 0 : s.subject;
218
+ return !i || !r.every((a) => tr(a.subject, i)) ? null : {
219
+ subject: i,
220
+ literals: r.map((a) => a.literal),
221
+ negated: !1
222
+ };
223
+ }
224
+ function Yr(e) {
225
+ const t = G(e);
226
+ return t && I(t) ? t.name : null;
227
+ }
228
+ function Zr(e) {
229
+ return p(e).with({ type: "skolem" }, (t) => {
230
+ const r = t.args.at(-1);
231
+ return r ? Yr(r) : null;
232
+ }).with({ type: "bind", expression: { type: "function", name: "SKOLEM" } }, (t) => t.variable).otherwise(() => null);
233
+ }
234
+ function us(e) {
235
+ const t = /* @__PURE__ */ new Set(), r = (a) => {
236
+ T(a).forEach((o) => t.add(o));
237
+ }, i = (a) => {
238
+ nt(a).forEach((o) => t.add(o));
239
+ }, s = (a) => {
240
+ p(a).with({ type: u.union("triple", "property", "class", "general") }, i).with({ type: "negation" }, (o) => o.formulas.forEach(s)).with({ type: "filter" }, (o) => r(o.expression)).with({ type: "bind" }, (o) => {
241
+ r(o.expression), t.add(o.variable);
242
+ }).with({ type: "aggregate" }, (o) => {
243
+ var l, E;
244
+ o.atoms.forEach(s), (l = o.onVars) == null || l.forEach((y) => t.add(y)), (E = o.bindings) == null || E.forEach((y) => {
245
+ t.add(y.variable), y.expression !== "*" && r(y.expression), y.secondExpression && r(y.secondExpression);
246
+ });
247
+ }).with({ type: "skolem" }, (o) => o.args.forEach(r)).exhaustive();
248
+ };
249
+ return e.head.forEach(i), e.body.forEach(s), Array.from(t);
250
+ }
251
+ function cs(e, t) {
252
+ const r = /* @__PURE__ */ new Set(), i = (o) => {
253
+ o.includes(t) && o.forEach((l) => r.add(l));
254
+ }, s = (o) => {
255
+ i(nt(o));
256
+ }, a = (o) => {
257
+ p(o).with({ type: u.union("triple", "property", "class", "general") }, s).with({ type: "negation" }, (l) => l.formulas.forEach(a)).with({ type: "filter" }, (l) => i(T(l.expression))).with(
258
+ { type: "bind" },
259
+ (l) => i([...T(l.expression), l.variable])
260
+ ).with({ type: "aggregate" }, (l) => {
261
+ l.atoms.forEach(a);
262
+ const E = [
263
+ ...l.onVars ?? [],
264
+ ...(l.bindings ?? []).flatMap((y) => [
265
+ y.variable,
266
+ ...y.expression === "*" ? [] : T(y.expression),
267
+ ...y.secondExpression ? T(y.secondExpression) : []
268
+ ])
269
+ ];
270
+ i(E);
271
+ }).with(
272
+ { type: "skolem" },
273
+ (l) => i(l.args.flatMap((E) => T(E)))
274
+ ).exhaustive();
275
+ };
276
+ return e.head.forEach(s), e.body.forEach(a), r;
277
+ }
278
+ function nt(e) {
279
+ return kr(e).map((t) => t.name);
280
+ }
281
+ function Jr(e) {
282
+ return e && I(e) ? [e.name] : [];
283
+ }
284
+ function T(e) {
285
+ return p(e).with({ type: "binary" }, (t) => [
286
+ ...T(t.left),
287
+ ...T(t.right)
288
+ ]).with({ type: "unary" }, (t) => T(t.operand)).with({ type: "term" }, (t) => Jr(t.term)).with({ type: "function" }, (t) => t.args.flatMap(T)).with({ type: "in" }, (t) => [
289
+ ...T(t.expression),
290
+ ...t.list.flatMap(T)
291
+ ]).exhaustive();
292
+ }
293
+ function ti(e) {
294
+ const t = G(e);
295
+ return t && tt(t) ? t : null;
296
+ }
297
+ function vt(e, t) {
298
+ return e.type !== "binary" || e.operator !== t ? [e] : [
299
+ ...vt(e.left, t),
300
+ ...vt(e.right, t)
301
+ ];
302
+ }
303
+ function rr(e) {
304
+ return We(e) ? `<${e}>` : e;
305
+ }
306
+ function x(e, t = {}) {
307
+ return p(e).with({ type: "variable" }, (r) => `?${r.name}`).with({ type: "iri" }, (r) => r.prefixed ? r.value : `<${r.value}>`).with({ type: "literal" }, (r) => {
308
+ const i = t.stripSimpleLiteralDatatypes && Pe(r) ? r.value : JSON.stringify(r.value);
309
+ return r.language ? `${i}@${r.language}` : r.datatype ? t.stripSimpleLiteralDatatypes && Pe(r) ? i : `${i}^^${rr(r.datatype)}` : i;
310
+ }).with({ type: "blank" }, (r) => `_:${r.label}`).exhaustive();
311
+ }
312
+ function ps(e, t = {}) {
313
+ const r = "graph" in e && e.graph ? ` ${x(e.graph, t)}` : "";
314
+ return p(e).with(
315
+ { type: "property" },
316
+ (i) => `${i.predicate}[${x(i.subject, t)}, ${x(i.object, t)}]${r}`
317
+ ).with(
318
+ { type: "triple" },
319
+ (i) => `[${x(i.subject, t)}, ${x(i.predicate, t)}, ${x(i.object, t)}]${r}`
320
+ ).with(
321
+ { type: "class" },
322
+ (i) => `${i.className}[${x(i.instance, t)}]${r}`
323
+ ).with(
324
+ { type: "general" },
325
+ (i) => `${i.tableName}(${i.terms.map((s) => x(s, t)).join(", ")})`
326
+ ).exhaustive();
327
+ }
328
+ function Pe(e) {
329
+ return Q(e) || er(e);
330
+ }
331
+ function hs(e, t = {}) {
332
+ return si(H(e, t));
333
+ }
334
+ function H(e, t = {}) {
335
+ return p(e).with({ type: "binary" }, (r) => [
336
+ ...ke(r.left, r.operator, "left", t),
337
+ C(` ${r.operator} `),
338
+ ...ke(r.right, r.operator, "right", t)
339
+ ]).with({ type: "unary" }, (r) => [C(r.operator), ...ii(r.operand, t)]).with({ type: "term" }, (r) => ni(r.term, t)).with({ type: "function" }, (r) => [
340
+ C(`${r.name}(`),
341
+ ...De(
342
+ r.args.map((i) => H(i, t)),
343
+ ", "
344
+ ),
345
+ C(")")
346
+ ]).with({ type: "in" }, (r) => [
347
+ ...H(r.expression, t),
348
+ C(` ${r.negated ? "NOT IN" : "IN"} (`),
349
+ ...De(
350
+ r.list.map((i) => H(i, t)),
351
+ ", "
352
+ ),
353
+ C(")")
354
+ ]).exhaustive();
355
+ }
356
+ function ei(e, t, r) {
357
+ if (e.type !== "binary") return !1;
358
+ const i = Me[e.operator], s = Me[t];
359
+ return i < s || r === "right" && i === s && (t === "-" || t === "/");
360
+ }
361
+ function ri(e) {
362
+ return e.type === "binary" || e.type === "in";
363
+ }
364
+ function ke(e, t, r, i) {
365
+ const s = H(e, i);
366
+ return ei(e, t, r) ? ir(s) : s;
367
+ }
368
+ function ii(e, t) {
369
+ const r = H(e, t);
370
+ return ri(e) ? ir(r) : r;
371
+ }
372
+ function ni(e, t) {
373
+ return I(e) ? [ai(e.name)] : tt(e) ? [oi(e, t)] : [C(x(e, t))];
374
+ }
375
+ function ir(e) {
376
+ return [C("("), ...e, C(")")];
377
+ }
378
+ function De(e, t) {
379
+ return e.flatMap((r, i) => i === 0 ? r : [C(t), ...r]);
380
+ }
381
+ function si(e) {
382
+ return e.map((t) => t.type === "variable" ? `?${t.name}` : t.text).join("");
383
+ }
384
+ function C(e) {
385
+ return { type: "text", text: e };
386
+ }
387
+ function ai(e) {
388
+ return { type: "variable", name: e };
389
+ }
390
+ function oi(e, t) {
391
+ return { type: "literal", literal: e, text: x(e, t) };
392
+ }
393
+ function G(e) {
394
+ return e.type === "term" ? e.term : null;
395
+ }
396
+ const li = "Cannot translate grounded Datalog rules to SPARQL.";
397
+ function nr(e) {
398
+ if (e.some(Ct)) throw new Error(li);
399
+ }
400
+ function Ct(e) {
401
+ return p(e).with({ type: "bind" }, ({ groundedTarget: t }) => t !== void 0).with(
402
+ { type: "aggregate" },
403
+ ({ groundedOnTargets: t, bindings: r, atoms: i }) => t !== void 0 || ((r == null ? void 0 : r.some((s) => s.groundedTarget !== void 0)) ?? !1) || i.some(Ct)
404
+ ).with({ type: "negation" }, ({ formulas: t }) => t.some(Ct)).with({ type: u.union("triple", "property", "class", "general", "filter", "skolem") }, () => !1).exhaustive();
405
+ }
406
+ const g = new vr(), m = g.gen(), $e = Mt.getRule("aggregate"), Ge = Mt.getRule("expression"), ui = {
407
+ ...$e,
408
+ gImpl: (e) => (t, r) => {
409
+ const i = t.secondExpression;
410
+ if (!i)
411
+ return $e.gImpl(e)(t, r);
412
+ const { PRINT_WORD: s, SUBRULE: a } = e, o = t.expression[0], l = r.astFactory;
413
+ if (l.isWildcard(o))
414
+ throw new Error(
415
+ `RDFox aggregate ${t.aggregation.toUpperCase()} cannot combine * with a second expression.`
416
+ );
417
+ l.printFilter(t, () => {
418
+ s(t.aggregation.toUpperCase(), "("), t.distinct && s("DISTINCT");
419
+ }), a(Ge, o), l.printFilter(t, () => s(",")), a(Ge, i), l.printFilter(t, () => s(")"));
420
+ }
421
+ }, ci = xr.create(Mt).patchRule(ui).build(), pi = /* @__PURE__ */ new Set(["MIN_ARGMIN", "MAX_ARGMIN", "MIN_ARGMAX", "MAX_ARGMAX"]), hi = new Map(
422
+ Object.entries(ze.builtIn).filter(([e]) => e !== "BuiltInCalls" && e !== "allBuiltInCalls").filter(([, e]) => e && typeof e == "object" && "LABEL" in e).map(([, e]) => {
423
+ const t = e;
424
+ return [t.LABEL.toLowerCase(), t.LABEL];
425
+ })
426
+ );
427
+ function $(e) {
428
+ if (e.includes("://") || e.startsWith("urn:") || e.startsWith("mailto:") || e.startsWith("tel:") || e.startsWith("data:"))
429
+ return g.termNamed(m, e);
430
+ const r = e.indexOf(":");
431
+ return r >= 0 ? g.termNamed(m, e.slice(r + 1), e.slice(0, r)) : g.termNamed(m, e);
432
+ }
433
+ function ot(e, t) {
434
+ return g.expressionOperation(e, t, m);
435
+ }
436
+ function di(e, t) {
437
+ const { function: r, expression: i, secondExpression: s } = e, a = pi.has(r), o = s !== void 0;
438
+ if (a && s == null)
439
+ throw new Error(`RDFox aggregate ${r} requires two expressions.`);
440
+ if (a && i === "*")
441
+ throw new Error(`RDFox aggregate ${r} cannot use * as an expression.`);
442
+ if (!a && o)
443
+ throw new Error(`RDFox aggregate ${r} accepts only one expression.`);
444
+ const l = i === "*" ? g.wildcard(m) : O(i, t), E = g.aggregate(
445
+ r.toLowerCase(),
446
+ e.distinct || !1,
447
+ l,
448
+ void 0,
449
+ m
450
+ );
451
+ return o ? {
452
+ ...E,
453
+ secondExpression: O(s, t)
454
+ } : E;
455
+ }
456
+ function D(e, t, r = void 0) {
457
+ return p(r).with("predicate", () => {
458
+ if (e.type !== "variable" && e.type !== "iri")
459
+ throw new Error(`Invalid predicate term: ${e.type}. RDF predicates cannot be ${e.type} nodes.`);
460
+ }).with("expression", () => {
461
+ if (e.type === "blank")
462
+ throw new Error(`Invalid expression term: ${e.type}. Expressions cannot use ${e.type} nodes.`);
463
+ }).with("graph", () => {
464
+ if (e.type !== "variable" && e.type !== "iri")
465
+ throw new Error(`Invalid graph name term: ${e.type}. Graph names can only be variables or IRIs.`);
466
+ }).with(u.nullish, () => {
467
+ }).exhaustive(), r === "predicate" && e.type === "iri" && e.value === "a" ? $("rdf:type") : p(e).with({ type: "variable" }, (i) => (t.add(i.name), g.termVariable(i.name, m))).with({ type: "iri", prefixed: !0 }, (i) => $(i.value)).with({ type: "iri", prefixed: !1 }, (i) => g.termNamed(m, i.value)).with(
468
+ { type: "literal", language: u.string },
469
+ (i) => g.termLiteral(m, i.value, i.language)
470
+ ).with({ type: "literal", datatype: u.string }, (i) => {
471
+ const s = $(i.datatype);
472
+ return g.termLiteral(m, i.value, s);
473
+ }).with({ type: "literal" }, (i) => g.termLiteral(m, i.value)).with({ type: "blank" }, (i) => g.termBlank(i.label, m)).exhaustive();
474
+ }
475
+ function Ei(e, t) {
476
+ const r = e.args.map((a) => O(a, t)), i = hi.get(e.name.toLowerCase());
477
+ if (i)
478
+ return ot(i.toLowerCase(), r);
479
+ const s = $(e.name);
480
+ return g.expressionFunctionCall(s, r, !1, m);
481
+ }
482
+ function O(e, t) {
483
+ return p(e).with(
484
+ { type: "binary" },
485
+ (r) => ot(r.operator, [
486
+ O(r.left, t),
487
+ O(r.right, t)
488
+ ])
489
+ ).with(
490
+ { type: "unary" },
491
+ (r) => ot(r.operator, [O(r.operand, t)])
492
+ ).with({ type: "term" }, (r) => D(r.term, t, "expression")).with({ type: "function" }, (r) => Ei(r, t)).with(
493
+ { type: "in" },
494
+ (r) => ot(r.negated ? "notin" : "in", [
495
+ O(r.expression, t),
496
+ ...r.list.map((i) => O(i, t))
497
+ ])
498
+ ).exhaustive();
499
+ }
500
+ function Pt(e, t) {
501
+ const r = p(e).with(
502
+ { type: "triple" },
503
+ (i) => g.triple(
504
+ D(i.subject, t),
505
+ D(i.predicate, t, "predicate"),
506
+ D(i.object, t)
507
+ )
508
+ ).with({ type: "property" }, (i) => {
509
+ const s = $(i.predicate);
510
+ return g.triple(D(i.subject, t), s, D(i.object, t));
511
+ }).with({ type: "class" }, (i) => {
512
+ const s = $("rdf:type"), a = $(i.className);
513
+ return g.triple(D(i.instance, t), s, a);
514
+ }).with({ type: "general" }, () => {
515
+ throw new Error("General formulas are not supported as triple patterns.");
516
+ }).exhaustive();
517
+ if (!r) return { triples: [] };
518
+ if ("graph" in e && e.graph) {
519
+ const i = g.patternBgp([r], m);
520
+ return { graph: g.patternGraph(
521
+ D(e.graph, t, "graph"),
522
+ [i],
523
+ m
524
+ ) };
525
+ }
526
+ return { triples: [r] };
527
+ }
528
+ function fi(e, t) {
529
+ return e.formulas.filter((r) => "type" in r).flatMap(
530
+ (r) => p(r).with({ type: u.union("triple", "property", "class") }, (i) => Pt(i, t).triples || []).with({ type: "general" }, () => {
531
+ throw new Error("General formulas are not supported in negation patterns.");
532
+ }).exhaustive()
533
+ );
534
+ }
535
+ function gi(e, t) {
536
+ return e.reduce(
537
+ (r, i) => "type" in i ? p(i).with({ type: u.union("triple", "property", "class") }, (s) => {
538
+ const a = Pt(s, t);
539
+ return a.graph ? { ...r, graphPatterns: [...r.graphPatterns, a.graph] } : a.triples ? { ...r, triples: [...r.triples, ...a.triples] } : r;
540
+ }).with({ type: "filter" }, (s) => {
541
+ const a = O(s.expression, t), o = g.patternFilter(a, m);
542
+ return { ...r, filters: [...r.filters, o] };
543
+ }).with({ type: "bind" }, (s) => {
544
+ t.add(s.variable);
545
+ const a = O(s.expression, t), o = g.termVariable(s.variable, m), l = g.patternBind(a, o, m);
546
+ return { ...r, binds: [...r.binds, l] };
547
+ }).with({ type: "general" }, () => {
548
+ throw new Error("General formulas are not supported in atom processing.");
549
+ }).exhaustive() : r,
550
+ { triples: [], filters: [], binds: [], graphPatterns: [] }
551
+ );
552
+ }
553
+ function mi(e, t) {
554
+ var S;
555
+ const { triples: r, filters: i, binds: s, graphPatterns: a } = gi(e.atoms, t), o = e.onVars || [], l = o.map((h) => (t.add(h), g.termVariable(h, m))), E = [], y = [];
556
+ return (S = e.bindings) == null || S.forEach((h) => {
557
+ if (t.add(h.variable), h.expression === void 0) {
558
+ const W = h.function !== void 0 ? `RDFox aggregate ${h.function}` : "Expression-only aggregate binding";
559
+ throw new Error(`${W} requires an expression.`);
560
+ }
561
+ if (h.function === void 0 && h.secondExpression !== void 0)
562
+ throw new Error("Expression-only aggregate bindings cannot have a second expression.");
563
+ const R = h.function !== void 0, L = R ? di(h, t) : O(h.expression, t), A = g.termVariable(h.variable, m), k = g.patternBind(L, A, m);
564
+ R ? E.push(k) : y.push(k);
565
+ }), {
566
+ triples: r,
567
+ filters: i,
568
+ binds: [...s, ...y],
569
+ graphPatterns: a,
570
+ selectVars: [...l, ...E],
571
+ groupBy: o
572
+ };
573
+ }
574
+ function yi(e, t) {
575
+ nr(e);
576
+ const r = /* @__PURE__ */ new Set(), i = e.reduce(
577
+ (h, R) => p(R).with({ type: u.union("triple", "property", "class", "general") }, (L) => {
578
+ const A = Pt(L, r);
579
+ return A.graph ? { ...h, graphPatterns: [...h.graphPatterns, A.graph] } : A.triples ? { ...h, triples: [...h.triples, ...A.triples] } : h;
580
+ }).with({ type: "filter" }, (L) => {
581
+ const A = O(L.expression, r), k = g.patternFilter(A, m);
582
+ return { ...h, filters: [...h.filters, k] };
583
+ }).with({ type: "bind" }, (L) => {
584
+ const A = O(L.expression, r);
585
+ r.add(L.variable);
586
+ const k = g.termVariable(L.variable, m), W = g.patternBind(A, k, m);
587
+ return { ...h, binds: [...h.binds, W] };
588
+ }).with({ type: "negation" }, (L) => {
589
+ const A = fi(L, r);
590
+ if (A.length > 0) {
591
+ const k = g.patternBgp(A, m), W = g.patternGroup([k], m), Nr = g.expressionPatternOperation("notexists", W, m), Rr = g.patternFilter(Nr, m);
592
+ return { ...h, filters: [...h.filters, Rr] };
593
+ }
594
+ return h;
595
+ }).with({ type: "aggregate" }, (L) => {
596
+ const A = mi(L, r);
597
+ return {
598
+ triples: [...h.triples, ...A.triples],
599
+ filters: [...h.filters, ...A.filters],
600
+ binds: [...h.binds, ...A.binds],
601
+ graphPatterns: [...h.graphPatterns, ...A.graphPatterns],
602
+ groupByVars: A.groupBy,
603
+ aggregateSelectVars: A.selectVars
604
+ };
605
+ }).with({ type: "skolem" }, () => {
606
+ throw new Error("Skolem formulas are not supported in SPARQL translation.");
607
+ }).exhaustive(),
608
+ {
609
+ triples: [],
610
+ filters: [],
611
+ graphPatterns: [],
612
+ binds: [],
613
+ groupByVars: [],
614
+ aggregateSelectVars: []
615
+ }
616
+ ), s = [
617
+ ...i.triples.length > 0 ? [g.patternBgp(i.triples, m)] : [],
618
+ ...i.graphPatterns,
619
+ ...i.filters,
620
+ ...i.binds
621
+ ], a = i.aggregateSelectVars.length > 0 ? i.aggregateSelectVars : r.size > 0 ? Array.from(r).map((h) => g.termVariable(h, m)) : [g.wildcard(m)], o = i.groupByVars.length > 0 ? {
622
+ group: g.solutionModifierGroup(
623
+ i.groupByVars.map((h) => g.termVariable(h, m)),
624
+ m
625
+ )
626
+ } : {}, l = t ? Object.entries(t).map(([h, R]) => {
627
+ const L = g.termNamed(m, R);
628
+ return g.contextDefinitionPrefix(m, h, L);
629
+ }) : [], E = g.querySelect(
630
+ {
631
+ context: l,
632
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-ts-comment
633
+ variables: a,
634
+ // @ts-ignore - Fails in CI for some reason
635
+ where: g.patternGroup(s, m),
636
+ datasets: g.datasetClauses([], m),
637
+ solutionModifiers: o
638
+ },
639
+ m
640
+ ), y = ci.queryOrUpdate(E, Cr({ indentInc: 2 })).trim(), S = i.aggregateSelectVars.length > 0 ? i.aggregateSelectVars.map((h) => "value" in h && typeof h.value == "string" ? h.value : "variable" in h && h.variable && "value" in h.variable ? h.variable.value : null).filter((h) => h !== null) : Array.from(r);
641
+ return {
642
+ query: y,
643
+ variables: S
644
+ };
645
+ }
646
+ const kt = c({ name: "RULE_ARROW", pattern: /:-/ }), lt = c({ name: "NOT", pattern: /NOT/ }), Dt = c({ name: "EXISTS", pattern: /EXISTS?/ }), Z = c({ name: "IN", pattern: /IN/ }), $t = c({ name: "FILTER", pattern: /FILTER/ }), z = c({ name: "BIND", pattern: /BIND/ }), K = c({ name: "AS", pattern: /AS/ }), wt = c({ name: "AGGREGATE", pattern: /AGGREGATE/ }), At = c({ name: "ON", pattern: /ON/ }), Gt = c({ name: "COUNT", pattern: /COUNT/ }), _t = c({ name: "MIN", pattern: /MIN/ }), Vt = c({ name: "MAX", pattern: /MAX/ }), jt = c({ name: "SUM", pattern: /SUM/ }), qt = c({ name: "MUL", pattern: /MUL/ }), Xt = c({ name: "AVG", pattern: /AVG/ }), Ht = c({ name: "COUNT_MIN", pattern: /COUNT_MIN/ }), Qt = c({ name: "COUNT_MAX", pattern: /COUNT_MAX/ }), zt = c({ name: "MIN_ARGMIN", pattern: /MIN_ARGMIN/ }), Kt = c({ name: "MAX_ARGMIN", pattern: /MAX_ARGMIN/ }), Wt = c({ name: "MIN_ARGMAX", pattern: /MIN_ARGMAX/ }), Yt = c({ name: "MAX_ARGMAX", pattern: /MAX_ARGMAX/ }), ut = c({ name: "DISTINCT", pattern: /DISTINCT/ }), Zt = c({ name: "CONCAT", pattern: /CONCAT/ }), Jt = c({ name: "STR", pattern: /STR/ }), te = c({ name: "IF", pattern: /IF/ }), ee = c({ name: "IRI", pattern: /IRI/ }), ct = c({ name: "SKOLEM", pattern: /SKOLEM/ }), re = c({ name: "ROUND", pattern: /ROUND/ }), ie = c({ name: "REGEX", pattern: /REGEX/ }), ne = c({ name: "TRUE", pattern: /true/ }), se = c({ name: "FALSE", pattern: /false/ }), ae = c({ name: "EQUALS", pattern: /=/ }), oe = c({ name: "NOT_EQUALS", pattern: /!=/ }), le = c({ name: "LESS_THAN", pattern: /</ }), ue = c({ name: "LESS_THAN_OR_EQUAL", pattern: /<=/ }), ce = c({ name: "GREATER_THAN", pattern: />/ }), pe = c({ name: "GREATER_THAN_OR_EQUAL", pattern: />=/ }), he = c({ name: "AND", pattern: /&&/ }), de = c({ name: "OR", pattern: /\|\|/ }), pt = c({ name: "PLUS", pattern: /\+/ }), ht = c({ name: "MINUS", pattern: /-/ }), dt = c({ name: "STAR", pattern: /\*/ }), Ee = c({ name: "SLASH", pattern: /\// }), fe = c({ name: "EXCLAMATION", pattern: /!/ }), ge = c({ name: "DOT", pattern: /\./ }), N = c({ name: "COMMA", pattern: /,/ }), U = c({ name: "LPAREN", pattern: /\(/ }), w = c({ name: "RPAREN", pattern: /\)/ }), Et = c({ name: "LBRACKET", pattern: /\[/ }), ft = c({ name: "RBRACKET", pattern: /\]/ }), sr = c({ name: "AT", pattern: /@/ }), gt = c({ name: "HAT", pattern: /\^/ }), ar = c({ name: "COLON", pattern: /:/ }), b = c({ name: "VARIABLE", pattern: /\?[a-zA-Z_][a-zA-Z0-9_]*/ }), me = c({ name: "IRI_REF", pattern: new RegExp(`<${Ke}*>`) }), ye = c({ name: "INTERNAL_FUNCTION", pattern: /<internal:[^>]+>/ }), et = c({ name: "BLANK_NODE", pattern: /_:[\w](?:[\w.-]*[\w-])?/ }), Le = "%[0-9a-fA-F]{2}|\\\\[-_~.!$&'()*+,;=/?#@%]", Li = `(?:[\\w:]|${Le})`, Ui = `(?:[\\w:.-]|${Le})`, wi = `(?:[\\w:-]|${Le})`, or = `${Li}(?:${Ui}*${wi})?`, st = c({
647
+ name: "PREFIXED_NAME",
648
+ pattern: new RegExp(`[a-zA-Z_][\\w]*:${or}`)
649
+ }), Tt = c({ name: "PREFIX_ONLY", pattern: /[a-zA-Z_][\w]*:/ }), Ue = c({
650
+ name: "DEFAULT_NS_IRI",
651
+ pattern: new RegExp(`:${or}`)
652
+ }), we = c({ name: "INTEGER", pattern: /[+-]?\d+/ }), Ae = c({ name: "DECIMAL", pattern: /[+-]?\d*\.\d+/ }), Te = c({
653
+ name: "DOUBLE",
654
+ pattern: /[+-]?(\d+\.\d*[eE][+-]?\d+|\.\d+[eE][+-]?\d+|\d+[eE][+-]?\d+)/
655
+ }), Se = c({
656
+ name: "STRING_LITERAL_LONG",
657
+ pattern: /"""(?:[^"\\]|\\.|"(?!""))*"""|'''(?:[^'\\]|\\.|'(?!''))*'''/
658
+ }), mt = c({
659
+ name: "STRING_LITERAL",
660
+ pattern: /"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/
661
+ }), Ne = c({ name: "LANGTAG", pattern: /@[a-zA-Z]+(-[a-zA-Z0-9]+)*/ }), rt = c({
662
+ name: "IDENTIFIER",
663
+ pattern: /[a-zA-Z_][a-zA-Z0-9_]*/,
664
+ longer_alt: st
665
+ }), Ai = c({
666
+ name: "COMMENT",
667
+ pattern: /#[^\r\n]*/,
668
+ group: Bt.SKIPPED
669
+ }), Ti = c({
670
+ name: "WHITESPACE",
671
+ pattern: /\s+/,
672
+ group: Bt.SKIPPED
673
+ }), lr = [
674
+ // Whitespace and comments (skipped)
675
+ Ti,
676
+ Ai,
677
+ // Multi-character operators (before single-char)
678
+ kt,
679
+ oe,
680
+ ue,
681
+ pe,
682
+ he,
683
+ de,
684
+ gt,
685
+ // Keywords (before identifiers)
686
+ lt,
687
+ Dt,
688
+ Z,
689
+ $t,
690
+ z,
691
+ K,
692
+ wt,
693
+ At,
694
+ zt,
695
+ Kt,
696
+ Wt,
697
+ Yt,
698
+ Ht,
699
+ Qt,
700
+ Gt,
701
+ _t,
702
+ Vt,
703
+ jt,
704
+ qt,
705
+ Xt,
706
+ ut,
707
+ Zt,
708
+ Jt,
709
+ te,
710
+ ee,
711
+ ct,
712
+ re,
713
+ ie,
714
+ ne,
715
+ se,
716
+ // Literals (specific patterns before generic)
717
+ Se,
718
+ mt,
719
+ Te,
720
+ Ae,
721
+ we,
722
+ Ne,
723
+ // Identifiers and names
724
+ b,
725
+ ye,
726
+ me,
727
+ et,
728
+ st,
729
+ Ue,
730
+ Tt,
731
+ rt,
732
+ // Single character tokens
733
+ ae,
734
+ le,
735
+ ce,
736
+ pt,
737
+ ht,
738
+ dt,
739
+ Ee,
740
+ fe,
741
+ ge,
742
+ N,
743
+ U,
744
+ w,
745
+ Et,
746
+ ft,
747
+ sr,
748
+ ar
749
+ ], Si = /* @__PURE__ */ new Set([lt, Dt, Z, $t, z, K, wt, At, ut]), Ni = /* @__PURE__ */ new Set([
750
+ Gt,
751
+ _t,
752
+ Vt,
753
+ jt,
754
+ qt,
755
+ Xt,
756
+ Ht,
757
+ Qt,
758
+ zt,
759
+ Kt,
760
+ Wt,
761
+ Yt,
762
+ Zt,
763
+ Jt,
764
+ te,
765
+ ee,
766
+ ct,
767
+ re,
768
+ ie
769
+ ]), Ri = /* @__PURE__ */ new Set([ne, se]), ds = /* @__PURE__ */ new Set([we, Ae, Te]), bi = /* @__PURE__ */ new Set([mt, Se]), Es = /* @__PURE__ */ new Set([me, ye, st, Tt, Ue]), fs = /* @__PURE__ */ new Set([
770
+ kt,
771
+ ae,
772
+ oe,
773
+ le,
774
+ ue,
775
+ ce,
776
+ pe,
777
+ he,
778
+ de,
779
+ pt,
780
+ ht,
781
+ dt,
782
+ Ee,
783
+ fe
784
+ ]), gs = /* @__PURE__ */ new Set([ge, N, U, w, Et, ft, sr, gt, ar]), ms = /* @__PURE__ */ new Set([b, et, Ne, rt]);
785
+ for (const e of [...Si, ...Ni, ...Ri])
786
+ e.LONGER_ALT = [st, Tt, rt];
787
+ let Oi;
788
+ function Re(e) {
789
+ return (Oi ?? (Oi = new Bt(lr))).tokenize(e);
790
+ }
791
+ function J(e, t, r, i) {
792
+ var o;
793
+ const a = e.slice(0, t).split(/\r\n|\r|\n/);
794
+ return {
795
+ message: i,
796
+ line: a.length,
797
+ column: (((o = a.at(-1)) == null ? void 0 : o.length) ?? 0) + 1,
798
+ offset: t,
799
+ endOffset: t + r
800
+ };
801
+ }
802
+ function be(e) {
803
+ for (let t = 0; t < e.length; t++) {
804
+ const r = e.charCodeAt(t);
805
+ if (r >= 55296 && r <= 56319) {
806
+ const i = e.charCodeAt(t + 1);
807
+ if (i >= 56320 && i <= 57343) {
808
+ t++;
809
+ continue;
810
+ }
811
+ return J(e, t, 1, "Unpaired high surrogate is not a valid Unicode scalar value");
812
+ }
813
+ if (r >= 56320 && r <= 57343)
814
+ return J(e, t, 1, "Unpaired low surrogate is not a valid Unicode scalar value");
815
+ }
816
+ }
817
+ function Oe(e, t) {
818
+ for (const r of t)
819
+ if (bi.has(r.tokenType))
820
+ for (let i = 0; i < r.image.length; i++) {
821
+ if (r.image[i] !== "\\") continue;
822
+ const s = r.image[i + 1];
823
+ if (s !== "u" && s !== "U") {
824
+ i++;
825
+ continue;
826
+ }
827
+ const a = s === "u" ? 4 : 8, o = a + 2, l = r.image.slice(i, i + o), E = r.image.slice(i + 2, i + o), y = r.startOffset + i;
828
+ if (E.length !== a || !/^[0-9a-fA-F]+$/.test(E))
829
+ return J(
830
+ e,
831
+ y,
832
+ l.length,
833
+ `Unicode escape \\${s} must contain ${a} hexadecimal digits`
834
+ );
835
+ const S = Number.parseInt(E, 16);
836
+ if (S >= 55296 && S <= 57343)
837
+ return J(e, y, o, `Unicode escape ${l} denotes a surrogate code point`);
838
+ if (S > 1114111)
839
+ return J(e, y, o, `Unicode escape ${l} is outside the Unicode range`);
840
+ i += o - 1;
841
+ }
842
+ }
843
+ class xe extends Br {
844
+ constructor(r = {}) {
845
+ super(lr);
846
+ // Rule := RuleHead ':-' RuleBody '.'
847
+ d(this, "rule", this.RULE("rule", () => {
848
+ this.SUBRULE(this.ruleHead), this.CONSUME(kt), this.OPTION(() => {
849
+ this.SUBRULE(this.ruleBody);
850
+ }), this.CONSUME(ge);
851
+ }));
852
+ // RuleHead := TupleTableAtom (',' TupleTableAtom)*
853
+ d(this, "ruleHead", this.RULE("ruleHead", () => {
854
+ this.SUBRULE(this.tupleTableAtom), this.MANY(() => {
855
+ this.CONSUME(N), this.SUBRULE2(this.tupleTableAtom);
856
+ });
857
+ }));
858
+ // RuleBody := BodyFormula (',' BodyFormula)*
859
+ d(this, "ruleBody", this.RULE("ruleBody", () => {
860
+ this.SUBRULE(this.bodyFormula), this.MANY(() => {
861
+ this.CONSUME(N), this.SUBRULE2(this.bodyFormula);
862
+ });
863
+ }));
864
+ // BodyFormula := Negation | FilterAtom | BindAtom | Aggregate | SkolemAtom | TupleTableAtom
865
+ d(this, "bodyFormula", this.RULE("bodyFormula", () => {
866
+ this.OR([
867
+ { ALT: () => this.SUBRULE(this.negation) },
868
+ { ALT: () => this.SUBRULE(this.filterAtom) },
869
+ { ALT: () => this.SUBRULE(this.bindAtom) },
870
+ { ALT: () => this.SUBRULE(this.aggregate) },
871
+ { ALT: () => this.SUBRULE(this.skolemAtom) },
872
+ { ALT: () => this.SUBRULE(this.tupleTableAtom) }
873
+ ]);
874
+ }));
875
+ // TupleTableAtom := (DefaultGraphAtom Graph?) | GeneralAtom
876
+ // NamedGraphAtom := DefaultGraphAtom Graph
877
+ // Graph := Term (IRI or Variable)
878
+ d(this, "tupleTableAtom", this.RULE("tupleTableAtom", () => {
879
+ this.OR([{ ALT: () => this.SUBRULE(this.defaultGraphAtom) }, { ALT: () => this.SUBRULE(this.generalAtom) }]), this.OPTION(() => {
880
+ this.SUBRULE(this.graphName, { LABEL: "graph" });
881
+ });
882
+ }));
883
+ // Graph name for named graph atoms - can be IRI or Variable
884
+ d(this, "graphName", this.RULE("graphName", () => {
885
+ this.OR([{ ALT: () => this.CONSUME(b) }, { ALT: () => this.SUBRULE(this.iri) }]);
886
+ }));
887
+ // DefaultGraphAtom := TripleAtom | PropertyAtom | ClassAtom
888
+ d(this, "defaultGraphAtom", this.RULE("defaultGraphAtom", () => {
889
+ this.OR([
890
+ // TripleAtom: [term, term, term]
891
+ {
892
+ ALT: () => {
893
+ this.CONSUME(Et), this.SUBRULE(this.term, { LABEL: "subject" }), this.CONSUME(N), this.SUBRULE2(this.term, { LABEL: "predicate" }), this.CONSUME2(N), this.SUBRULE3(this.term, { LABEL: "object" }), this.CONSUME(ft);
894
+ }
895
+ },
896
+ // PropertyAtom: predicate[term, term] or ClassAtom: class[term]
897
+ {
898
+ ALT: () => {
899
+ this.SUBRULE(this.iri, { LABEL: "predicateOrClass" }), this.CONSUME2(Et), this.SUBRULE4(this.term, { LABEL: "firstTerm" }), this.OPTION(() => {
900
+ this.CONSUME3(N), this.SUBRULE5(this.term, { LABEL: "secondTerm" });
901
+ }), this.CONSUME2(ft);
902
+ }
903
+ }
904
+ ]);
905
+ }));
906
+ // GeneralAtom := tableName(term, ...)
907
+ d(this, "generalAtom", this.RULE("generalAtom", () => {
908
+ this.OR([{ ALT: () => this.CONSUME(rt) }, { ALT: () => this.CONSUME(mt) }]), this.CONSUME(U), this.SUBRULE(this.term), this.MANY(() => {
909
+ this.CONSUME(N), this.SUBRULE2(this.term);
910
+ }), this.CONSUME(w);
911
+ }));
912
+ // Term := Variable | IRI | Literal | BlankNode
913
+ d(this, "term", this.RULE("term", () => {
914
+ this.OR([
915
+ { ALT: () => this.CONSUME(b) },
916
+ { ALT: () => this.SUBRULE(this.iri) },
917
+ { ALT: () => this.SUBRULE(this.literal) },
918
+ { ALT: () => this.CONSUME(et) }
919
+ ]);
920
+ }));
921
+ // IRI := IRI_REF | PrefixedName | DefaultNsIRI | InternalFunction
922
+ d(this, "iri", this.RULE("iri", () => {
923
+ this.OR([
924
+ { ALT: () => this.CONSUME(me) },
925
+ { ALT: () => this.CONSUME(ye) },
926
+ { ALT: () => this.CONSUME(st) },
927
+ { ALT: () => this.CONSUME(Ue) },
928
+ { ALT: () => this.CONSUME(Tt) },
929
+ { ALT: () => this.CONSUME(rt) }
930
+ ]);
931
+ }));
932
+ // Literal := NumericLiteral | BooleanLiteral | StringLiteral
933
+ d(this, "literal", this.RULE("literal", () => {
934
+ this.OR([
935
+ { ALT: () => this.SUBRULE(this.numericLiteral) },
936
+ { ALT: () => this.SUBRULE(this.booleanLiteral) },
937
+ { ALT: () => this.SUBRULE(this.stringLiteral) }
938
+ ]);
939
+ }));
940
+ d(this, "numericLiteral", this.RULE("numericLiteral", () => {
941
+ this.OR([
942
+ { ALT: () => this.CONSUME(Te) },
943
+ { ALT: () => this.CONSUME(Ae) },
944
+ { ALT: () => this.CONSUME(we) }
945
+ ]);
946
+ }));
947
+ d(this, "booleanLiteral", this.RULE("booleanLiteral", () => {
948
+ this.OR([{ ALT: () => this.CONSUME(ne) }, { ALT: () => this.CONSUME(se) }]);
949
+ }));
950
+ d(this, "stringLiteral", this.RULE("stringLiteral", () => {
951
+ this.OR([
952
+ { ALT: () => this.CONSUME(Se) },
953
+ { ALT: () => this.CONSUME(mt) }
954
+ ]), this.OPTION(() => {
955
+ this.OR2([
956
+ { ALT: () => this.CONSUME(Ne) },
957
+ {
958
+ ALT: () => {
959
+ this.CONSUME(gt), this.CONSUME2(gt), this.SUBRULE(this.iri);
960
+ }
961
+ }
962
+ ]);
963
+ });
964
+ }));
965
+ // Negation := 'NOT' ExistsClause? (Atom | '(' BodyFormulaList ')')
966
+ d(this, "negation", this.RULE("negation", () => {
967
+ this.CONSUME(lt), this.OPTION(() => {
968
+ this.SUBRULE(this.existsClause);
969
+ }), this.OR([
970
+ {
971
+ ALT: () => {
972
+ this.CONSUME(U), this.SUBRULE(this.bodyFormulaList), this.CONSUME(w);
973
+ }
974
+ },
975
+ { ALT: () => this.SUBRULE(this.tupleTableAtom) }
976
+ ]);
977
+ }));
978
+ // ExistsClause := 'EXISTS' variable (',' variable)* 'IN'
979
+ d(this, "existsClause", this.RULE("existsClause", () => {
980
+ this.CONSUME(Dt), this.CONSUME(b), this.MANY(() => {
981
+ this.CONSUME(N), this.CONSUME2(b);
982
+ }), this.CONSUME(Z);
983
+ }));
984
+ // AtomList := Atom (',' Atom)*
985
+ d(this, "atomList", this.RULE("atomList", () => {
986
+ this.SUBRULE(this.atom), this.MANY(() => {
987
+ this.CONSUME(N), this.SUBRULE2(this.atom);
988
+ });
989
+ }));
990
+ // Atom := TupleTableAtom | FilterAtom | BindAtom
991
+ d(this, "atom", this.RULE("atom", () => {
992
+ this.OR([
993
+ { ALT: () => this.SUBRULE(this.tupleTableAtom) },
994
+ { ALT: () => this.SUBRULE(this.filterAtom) },
995
+ { ALT: () => this.SUBRULE(this.bindAtom) }
996
+ ]);
997
+ }));
998
+ // BodyFormulaList := BodyFormula (',' BodyFormula)*
999
+ d(this, "bodyFormulaList", this.RULE("bodyFormulaList", () => {
1000
+ this.SUBRULE(this.bodyFormula), this.MANY(() => {
1001
+ this.CONSUME(N), this.SUBRULE2(this.bodyFormula);
1002
+ });
1003
+ }));
1004
+ // FilterAtom := 'FILTER' '(' Expression ')'
1005
+ d(this, "filterAtom", this.RULE("filterAtom", () => {
1006
+ this.CONSUME($t), this.CONSUME(U), this.SUBRULE(this.expression), this.CONSUME(w);
1007
+ }));
1008
+ // BindAtom := 'BIND' '(' Expression 'AS' variable ')'
1009
+ d(this, "bindAtom", this.RULE("bindAtom", () => {
1010
+ this.CONSUME(z), this.CONSUME(U), this.SUBRULE(this.expression), this.CONSUME(K), this.CONSUME(b), this.CONSUME(w);
1011
+ }));
1012
+ // SkolemAtom := 'SKOLEM' '(' ArgumentList ')'
1013
+ d(this, "skolemAtom", this.RULE("skolemAtom", () => {
1014
+ this.CONSUME(ct), this.CONSUME(U), this.SUBRULE(this.argumentList), this.CONSUME(w);
1015
+ }));
1016
+ // Aggregate := 'AGGREGATE' '(' AtomList OnClause? AggregateBind* ')'
1017
+ d(this, "aggregate", this.RULE("aggregate", () => {
1018
+ this.CONSUME(wt), this.CONSUME(U), this.SUBRULE(this.atomList), this.OPTION(() => {
1019
+ this.SUBRULE(this.onClause);
1020
+ }), this.MANY(() => {
1021
+ this.SUBRULE(this.aggregateBind);
1022
+ }), this.CONSUME(w);
1023
+ }));
1024
+ // OnClause := 'ON' variable+
1025
+ d(this, "onClause", this.RULE("onClause", () => {
1026
+ this.CONSUME(At), this.CONSUME(b), this.MANY(() => {
1027
+ this.CONSUME2(b);
1028
+ });
1029
+ }));
1030
+ // AggregateBind := ('BIND' AggregateFunction | AggregateFunction) 'AS' variable
1031
+ d(this, "aggregateBind", this.RULE("aggregateBind", () => {
1032
+ this.OPTION(() => {
1033
+ this.CONSUME(z);
1034
+ }), this.SUBRULE(this.aggregateFunction), this.CONSUME(K), this.CONSUME(b);
1035
+ }));
1036
+ // AggregateFunction := AggregateFunction1 | AggregateFunction2
1037
+ d(this, "aggregateFunction", this.RULE("aggregateFunction", () => {
1038
+ this.OR([
1039
+ { ALT: () => this.SUBRULE(this.aggregateFunction1) },
1040
+ { ALT: () => this.SUBRULE(this.aggregateFunction2) }
1041
+ ]);
1042
+ }));
1043
+ // AggregateFunction1 := (SUM | MUL | AVG | MIN | COUNT_MIN | MAX | COUNT_MAX | COUNT) '(' DISTINCT? (STAR | Expression) ')'
1044
+ d(this, "aggregateFunction1", this.RULE("aggregateFunction1", () => {
1045
+ this.OR([
1046
+ { ALT: () => this.CONSUME(Ht) },
1047
+ { ALT: () => this.CONSUME(Qt) },
1048
+ { ALT: () => this.CONSUME(Gt) },
1049
+ { ALT: () => this.CONSUME(_t) },
1050
+ { ALT: () => this.CONSUME(Vt) },
1051
+ { ALT: () => this.CONSUME(jt) },
1052
+ { ALT: () => this.CONSUME(qt) },
1053
+ { ALT: () => this.CONSUME(Xt) }
1054
+ ]), this.CONSUME(U), this.OPTION(() => {
1055
+ this.CONSUME(ut);
1056
+ }), this.OR2([{ ALT: () => this.CONSUME(dt) }, { ALT: () => this.SUBRULE(this.expression) }]), this.CONSUME(w);
1057
+ }));
1058
+ // AggregateFunction2 := (MIN_ARGMIN | MAX_ARGMIN | MIN_ARGMAX | MAX_ARGMAX) '(' DISTINCT? Expression ',' Expression ')'
1059
+ d(this, "aggregateFunction2", this.RULE("aggregateFunction2", () => {
1060
+ this.OR([
1061
+ { ALT: () => this.CONSUME(zt) },
1062
+ { ALT: () => this.CONSUME(Kt) },
1063
+ { ALT: () => this.CONSUME(Wt) },
1064
+ { ALT: () => this.CONSUME(Yt) }
1065
+ ]), this.CONSUME(U), this.OPTION(() => {
1066
+ this.CONSUME(ut);
1067
+ }), this.SUBRULE(this.expression, { LABEL: "firstExpr" }), this.CONSUME(N), this.SUBRULE2(this.expression, { LABEL: "secondExpr" }), this.CONSUME(w);
1068
+ }));
1069
+ // Expression (simplified for now)
1070
+ d(this, "expression", this.RULE("expression", () => {
1071
+ this.SUBRULE(this.conditionalOrExpression);
1072
+ }));
1073
+ d(this, "conditionalOrExpression", this.RULE("conditionalOrExpression", () => {
1074
+ this.SUBRULE(this.conditionalAndExpression), this.MANY(() => {
1075
+ this.CONSUME(de), this.SUBRULE2(this.conditionalAndExpression);
1076
+ });
1077
+ }));
1078
+ d(this, "conditionalAndExpression", this.RULE("conditionalAndExpression", () => {
1079
+ this.SUBRULE(this.relationalExpression), this.MANY(() => {
1080
+ this.CONSUME(he), this.SUBRULE2(this.relationalExpression);
1081
+ });
1082
+ }));
1083
+ d(this, "relationalExpression", this.RULE("relationalExpression", () => {
1084
+ this.SUBRULE(this.additiveExpression), this.OPTION(() => {
1085
+ this.OR([
1086
+ {
1087
+ ALT: () => {
1088
+ this.OR2([
1089
+ { ALT: () => this.CONSUME(ae) },
1090
+ { ALT: () => this.CONSUME(oe) },
1091
+ { ALT: () => this.CONSUME(le) },
1092
+ { ALT: () => this.CONSUME(ce) },
1093
+ { ALT: () => this.CONSUME(ue) },
1094
+ { ALT: () => this.CONSUME(pe) }
1095
+ ]), this.SUBRULE2(this.additiveExpression);
1096
+ }
1097
+ },
1098
+ // Handle IN
1099
+ {
1100
+ ALT: () => {
1101
+ this.CONSUME(Z), this.CONSUME2(U), this.SUBRULE(this.argumentList), this.CONSUME3(w);
1102
+ }
1103
+ },
1104
+ // Handle NOT IN
1105
+ {
1106
+ ALT: () => {
1107
+ this.CONSUME(lt), this.CONSUME2(Z), this.CONSUME4(U), this.SUBRULE2(this.argumentList), this.CONSUME5(w);
1108
+ }
1109
+ }
1110
+ ]);
1111
+ });
1112
+ }));
1113
+ d(this, "additiveExpression", this.RULE("additiveExpression", () => {
1114
+ this.SUBRULE(this.multiplicativeExpression), this.MANY(() => {
1115
+ this.OR([{ ALT: () => this.CONSUME(pt) }, { ALT: () => this.CONSUME(ht) }]), this.SUBRULE2(this.multiplicativeExpression);
1116
+ });
1117
+ }));
1118
+ d(this, "multiplicativeExpression", this.RULE("multiplicativeExpression", () => {
1119
+ this.SUBRULE(this.unaryExpression), this.MANY(() => {
1120
+ this.OR([{ ALT: () => this.CONSUME(dt) }, { ALT: () => this.CONSUME(Ee) }]), this.SUBRULE2(this.unaryExpression);
1121
+ });
1122
+ }));
1123
+ d(this, "unaryExpression", this.RULE("unaryExpression", () => {
1124
+ this.OPTION(() => {
1125
+ this.OR([
1126
+ { ALT: () => this.CONSUME(fe) },
1127
+ { ALT: () => this.CONSUME(pt) },
1128
+ { ALT: () => this.CONSUME(ht) }
1129
+ ]);
1130
+ }), this.SUBRULE(this.primaryExpression);
1131
+ }));
1132
+ // Function calls
1133
+ d(this, "functionCall", this.RULE("functionCall", () => {
1134
+ this.OR([
1135
+ // Built-in functions
1136
+ { ALT: () => this.SUBRULE(this.concatFunction) },
1137
+ { ALT: () => this.SUBRULE(this.strFunction) },
1138
+ { ALT: () => this.SUBRULE(this.ifFunction) },
1139
+ { ALT: () => this.SUBRULE(this.iriFunction) },
1140
+ { ALT: () => this.SUBRULE(this.skolemFunction) },
1141
+ { ALT: () => this.SUBRULE(this.roundFunction) },
1142
+ { ALT: () => this.SUBRULE(this.regexFunction) },
1143
+ // Generic function call (IRI followed by arguments)
1144
+ {
1145
+ ALT: () => {
1146
+ this.SUBRULE(this.iri), this.CONSUME(U), this.OPTION(() => {
1147
+ this.SUBRULE(this.argumentList);
1148
+ }), this.CONSUME(w);
1149
+ }
1150
+ }
1151
+ ]);
1152
+ }));
1153
+ // CONCAT function
1154
+ d(this, "concatFunction", this.RULE("concatFunction", () => {
1155
+ this.CONSUME(Zt), this.CONSUME(U), this.SUBRULE(this.argumentList), this.CONSUME(w);
1156
+ }));
1157
+ // STR function
1158
+ d(this, "strFunction", this.RULE("strFunction", () => {
1159
+ this.CONSUME(Jt), this.CONSUME(U), this.SUBRULE(this.expression), this.CONSUME(w);
1160
+ }));
1161
+ // IF function
1162
+ d(this, "ifFunction", this.RULE("ifFunction", () => {
1163
+ this.CONSUME(te), this.CONSUME(U), this.SUBRULE(this.expression, { LABEL: "condition" }), this.CONSUME(N), this.SUBRULE2(this.expression, { LABEL: "thenExpr" }), this.CONSUME2(N), this.SUBRULE3(this.expression, { LABEL: "elseExpr" }), this.CONSUME(w);
1164
+ }));
1165
+ // IRI function
1166
+ d(this, "iriFunction", this.RULE("iriFunction", () => {
1167
+ this.CONSUME(ee), this.CONSUME(U), this.SUBRULE(this.expression, { LABEL: "iriExpr" }), this.OPTION(() => {
1168
+ this.CONSUME(N), this.SUBRULE2(this.expression, { LABEL: "baseIri" });
1169
+ }), this.CONSUME(w);
1170
+ }));
1171
+ // SKOLEM function
1172
+ d(this, "skolemFunction", this.RULE("skolemFunction", () => {
1173
+ this.CONSUME(ct), this.CONSUME(U), this.SUBRULE(this.argumentList), this.CONSUME(w);
1174
+ }));
1175
+ // ROUND function
1176
+ d(this, "roundFunction", this.RULE("roundFunction", () => {
1177
+ this.CONSUME(re), this.CONSUME(U), this.SUBRULE(this.expression), this.CONSUME(w);
1178
+ }));
1179
+ // REGEX function
1180
+ d(this, "regexFunction", this.RULE("regexFunction", () => {
1181
+ this.CONSUME(ie), this.CONSUME(U), this.SUBRULE(this.expression, { LABEL: "textExpr" }), this.CONSUME(N), this.SUBRULE2(this.expression, { LABEL: "patternExpr" }), this.OPTION(() => {
1182
+ this.CONSUME2(N), this.SUBRULE3(this.expression, { LABEL: "flagsExpr" });
1183
+ }), this.CONSUME(w);
1184
+ }));
1185
+ // Argument list
1186
+ d(this, "argumentList", this.RULE("argumentList", () => {
1187
+ this.SUBRULE(this.expression), this.MANY(() => {
1188
+ this.CONSUME(N), this.SUBRULE2(this.expression);
1189
+ });
1190
+ }));
1191
+ d(this, "primaryExpression", this.RULE("primaryExpression", () => {
1192
+ this.OR([
1193
+ {
1194
+ ALT: () => {
1195
+ this.CONSUME(U), this.SUBRULE(this.expression), this.CONSUME(w);
1196
+ }
1197
+ },
1198
+ { ALT: () => this.SUBRULE(this.functionCall) },
1199
+ { ALT: () => this.SUBRULE(this.literal) },
1200
+ { ALT: () => this.CONSUME(b) },
1201
+ { ALT: () => this.SUBRULE(this.iri) }
1202
+ ]);
1203
+ }));
1204
+ const { selfAnalysis: i = !0 } = r;
1205
+ i && this.performSelfAnalysis();
1206
+ }
1207
+ // Chevrotain only reports leftover input for the rule it was entered on, so
1208
+ // callers entering on a nested rule have to reject trailing tokens themselves.
1209
+ get atEndOfInput() {
1210
+ return this.LA(1).tokenType === Fr;
1211
+ }
1212
+ }
1213
+ let xi;
1214
+ function ve() {
1215
+ return xi ?? (xi = new xe());
1216
+ }
1217
+ function ur(e, t) {
1218
+ const r = be(t);
1219
+ if (r) throw new Error(r.message);
1220
+ const i = Re(t);
1221
+ if (i.errors.length > 0)
1222
+ throw new Error(`Lexer errors: ${i.errors.map((o) => o.message).join(", ")}`);
1223
+ const s = Oe(t, i.tokens);
1224
+ if (s) throw new Error(s.message);
1225
+ e.input = i.tokens;
1226
+ const a = e.rule();
1227
+ if (e.errors.length > 0)
1228
+ throw new Error(`Parser errors: ${e.errors.map((o) => o.message).join(", ")}`);
1229
+ return a;
1230
+ }
1231
+ function cr(e) {
1232
+ return ur(ve(), e);
1233
+ }
1234
+ function ys(e) {
1235
+ try {
1236
+ return cr(e), { valid: !0 };
1237
+ } catch (t) {
1238
+ return {
1239
+ valid: !1,
1240
+ error: t instanceof Error ? t.message : "Unknown parsing error"
1241
+ };
1242
+ }
1243
+ }
1244
+ class vi extends xe {
1245
+ constructor() {
1246
+ super({ selfAnalysis: !1 });
1247
+ // `term` cannot be used directly as the alternative to a variable: its own
1248
+ // first alternative is VARIABLE, which would make the enclosing OR ambiguous.
1249
+ d(this, "groundedAsTarget", this.RULE("groundedAsTarget", () => {
1250
+ this.OR([
1251
+ { ALT: () => this.SUBRULE(this.iri) },
1252
+ { ALT: () => this.SUBRULE(this.literal) },
1253
+ { ALT: () => this.CONSUME(et) }
1254
+ ]);
1255
+ }));
1256
+ // OnClause := 'ON' (variable | GroundedAsTarget)*
1257
+ // Grounding substitutes the grouping variables as well, and an aggregate
1258
+ // over the whole store comes back with a bare 'ON', so both are accepted.
1259
+ d(this, "expandedOnClause", this.OVERRIDE_RULE("onClause", () => {
1260
+ this.CONSUME(At), this.MANY(() => {
1261
+ this.variableOrGroundedTarget();
1262
+ });
1263
+ }));
1264
+ // BindAtom := 'BIND' '(' Expression 'AS' (variable | GroundedAsTarget) ')'
1265
+ d(this, "expandedBindAtom", this.OVERRIDE_RULE("bindAtom", () => {
1266
+ this.CONSUME(z), this.CONSUME(U), this.SUBRULE(this.expression), this.CONSUME(K), this.variableOrGroundedTarget(), this.CONSUME(w);
1267
+ }));
1268
+ // Aggregate := 'AGGREGATE' '(' AtomList? OnClause? AggregateBind* ')'
1269
+ // atomList is optional so RDFox-emitted atom-free forms parse; empty
1270
+ // `AGGREGATE()` / `AGGREGATE(ON ?x)` are rejected after parse (visitor).
1271
+ d(this, "expandedAggregate", this.OVERRIDE_RULE("aggregate", () => {
1272
+ this.CONSUME(wt), this.CONSUME(U), this.OPTION(() => {
1273
+ this.SUBRULE(this.atomList);
1274
+ }), this.OPTION2(() => {
1275
+ this.SUBRULE(this.onClause);
1276
+ }), this.MANY(() => {
1277
+ this.SUBRULE(this.aggregateBind);
1278
+ }), this.CONSUME(w);
1279
+ }));
1280
+ // AggregateBind := 'BIND'? (AggregateFunction | Expression) 'AS' (variable | GroundedAsTarget)
1281
+ d(this, "expandedAggregateBind", this.OVERRIDE_RULE("aggregateBind", () => {
1282
+ this.OPTION(() => {
1283
+ this.CONSUME(z);
1284
+ }), this.OR2([{ ALT: () => this.SUBRULE(this.aggregateFunction) }, { ALT: () => this.SUBRULE(this.expression) }]), this.CONSUME(K), this.variableOrGroundedTarget();
1285
+ }));
1286
+ // Grounding substitutes SKOLEM outputs into expression positions as blank
1287
+ // nodes, so the expanded grammar accepts them as primary expressions.
1288
+ d(this, "expandedPrimaryExpression", this.OVERRIDE_RULE("primaryExpression", () => {
1289
+ this.OR([
1290
+ {
1291
+ ALT: () => {
1292
+ this.CONSUME(U), this.SUBRULE(this.expression), this.CONSUME(w);
1293
+ }
1294
+ },
1295
+ { ALT: () => this.SUBRULE(this.functionCall) },
1296
+ { ALT: () => this.SUBRULE(this.literal) },
1297
+ { ALT: () => this.CONSUME(b) },
1298
+ { ALT: () => this.CONSUME(et) },
1299
+ { ALT: () => this.SUBRULE(this.iri) }
1300
+ ]);
1301
+ }));
1302
+ this.performSelfAnalysis();
1303
+ }
1304
+ // Each rule below records this once, so the default occurrence index is unambiguous.
1305
+ variableOrGroundedTarget() {
1306
+ this.OR([{ ALT: () => this.CONSUME(b) }, { ALT: () => this.SUBRULE(this.groundedAsTarget) }]);
1307
+ }
1308
+ }
1309
+ let Ci;
1310
+ function Ii() {
1311
+ return Ci ?? (Ci = new vi());
1312
+ }
1313
+ function Mi(e) {
1314
+ return ur(Ii(), e);
1315
+ }
1316
+ function Bi(e) {
1317
+ nr(e.body);
1318
+ const t = e.body.filter((s) => s.type !== "negation"), r = Ye(e.body) ? t.filter(
1319
+ (s) => p(s).with({ type: u.union("triple", "property", "class") }, () => !0).otherwise(() => !1)
1320
+ ) : t, { query: i } = yi(r);
1321
+ return `${i}
1322
+ LIMIT 1`;
1323
+ }
1324
+ function Ls(e) {
1325
+ return p(e).with({ type: "variable" }, (t) => `?${t.name}`).with({ type: "iri", value: "a" }, () => "rdf:type").with({ type: "iri", prefixed: !0 }, (t) => t.value).with({ type: "iri", prefixed: !1 }, (t) => `<${t.value}>`).with({ type: "literal", language: u.string }, (t) => `"${t.value}"@${t.language}`).with({ type: "literal", datatype: u.string }, (t) => `"${t.value}"^^${rr(t.datatype)}`).with({ type: "literal" }, (t) => `"${t.value}"`).with({ type: "blank" }, (t) => `_:${t.label}`).exhaustive();
1326
+ }
1327
+ function Fi(e) {
1328
+ const t = e.head[0];
1329
+ return t ? p(t).with({ type: "triple" }, (r) => ({
1330
+ subject: _(r.subject),
1331
+ predicate: _(r.predicate),
1332
+ object: _(r.object)
1333
+ })).with({ type: "property" }, (r) => ({
1334
+ subject: _(r.subject),
1335
+ predicate: r.predicate,
1336
+ object: _(r.object)
1337
+ })).with({ type: "class" }, (r) => ({
1338
+ subject: _(r.instance),
1339
+ predicate: "rdf:type",
1340
+ object: r.className
1341
+ })).with({ type: "general" }, () => null).exhaustive() : null;
1342
+ }
1343
+ function _(e) {
1344
+ return p(e).with({ type: "variable" }, (t) => `:test_${t.name}`).with({ type: "iri", prefixed: !0 }, (t) => t.value).with({ type: "iri", prefixed: !1 }, (t) => `<${t.value}>`).with({ type: "literal", datatype: u.string }, (t) => `"${t.value}"^^${t.datatype}`).with({ type: "literal" }, (t) => `"${t.value}"`).with({ type: "blank" }, (t) => `_:${t.label}`).exhaustive();
1345
+ }
1346
+ const Pi = q.object({
1347
+ results: q.object({
1348
+ bindings: q.array(q.unknown())
1349
+ })
1350
+ }), ki = q.object({
1351
+ boolean: q.boolean()
1352
+ });
1353
+ async function Us(e, t, r, i, s) {
1354
+ if (Ye(e.body) && !s)
1355
+ return {
1356
+ verified: !1,
1357
+ error: "Rules containing SKOLEM require a concrete test triple for inference verification"
1358
+ };
1359
+ try {
1360
+ const o = s || Fi(e);
1361
+ if (!o)
1362
+ return {
1363
+ verified: !1,
1364
+ error: "Could not generate test triple from rule head"
1365
+ };
1366
+ const l = Bi(e), E = await Di(l, t, r, i);
1367
+ if (E)
1368
+ return {
1369
+ verified: !1,
1370
+ testTriple: o,
1371
+ candidateQuery: l,
1372
+ error: E
1373
+ };
1374
+ const y = $i(o), S = new URL(`datastores/${r}/sparql`, t), h = await fetch(S.toString(), {
1375
+ method: "POST",
1376
+ headers: {
1377
+ Authorization: i,
1378
+ "Content-Type": "application/sparql-query",
1379
+ Accept: "application/sparql-results+json"
1380
+ },
1381
+ body: y
1382
+ });
1383
+ if (!h.ok)
1384
+ throw new Error(`SPARQL query failed: ${h.status} - ${await h.text()}`);
1385
+ return {
1386
+ verified: ki.parse(await h.json()).boolean,
1387
+ testTriple: o,
1388
+ sparqlQuery: y,
1389
+ candidateQuery: l
1390
+ };
1391
+ } catch (o) {
1392
+ return {
1393
+ verified: !1,
1394
+ testTriple: s,
1395
+ error: o instanceof Error ? o.message : "Unknown error during inference verification"
1396
+ };
1397
+ }
1398
+ }
1399
+ async function Di(e, t, r, i) {
1400
+ try {
1401
+ const s = new URL(`datastores/${r}/sparql`, t), a = await fetch(s.toString(), {
1402
+ method: "POST",
1403
+ headers: {
1404
+ Authorization: i,
1405
+ "Content-Type": "application/sparql-query",
1406
+ Accept: "application/sparql-results+json"
1407
+ },
1408
+ body: e
1409
+ });
1410
+ if (!a.ok) {
1411
+ let l = "";
1412
+ try {
1413
+ l = await a.text();
1414
+ } catch {
1415
+ }
1416
+ const E = l || a.statusText;
1417
+ return `Candidate query failed: ${a.status}${E ? ` - ${E}` : ""}`;
1418
+ }
1419
+ return Pi.parse(await a.json()).results.bindings.length > 0 ? void 0 : "No candidate variable bindings found for rule body - rule cannot fire";
1420
+ } catch (s) {
1421
+ return `Candidate query failed: ${s instanceof Error ? s.message : "Unknown error"}`;
1422
+ }
1423
+ }
1424
+ function $i(e) {
1425
+ return `
1426
+ ASK WHERE {
1427
+ ${e.subject} ${e.predicate} ${e.object} .
1428
+ FILTER(NOT EXISTS {
1429
+ ${e.subject} ${e.predicate} ${e.object} EXPLICIT true
1430
+ })
1431
+ }
1432
+ `.trim();
1433
+ }
1434
+ function ws(e) {
1435
+ return p(e).with({ verified: !0 }, () => "Inference verification succeeded").with({ error: u.string }, (t) => t.error).with({ testTriple: u.nullish }, () => "Could not determine what triple should be inferred by this rule").with({ testTriple: u.not(u.nullish) }, (t) => {
1436
+ const { subject: r, predicate: i, object: s } = t.testTriple;
1437
+ return `Expected inference was not produced:
1438
+
1439
+ Expected triple: ${r} ${i} ${s}
1440
+
1441
+ This could indicate:
1442
+ 1. The rule syntax is correct but the rule conditions are not met
1443
+ 2. Required facts are missing from the knowledge base
1444
+ 3. Variable bindings in the rule body don't match existing data
1445
+ 4. The rule head atom format doesn't match the expected pattern
1446
+
1447
+ To debug:
1448
+ 1. Check if the rule body conditions can be satisfied with current facts
1449
+ 2. Verify variable names are consistent between head and body
1450
+ 3. Ensure IRIs and predicates use correct prefixes
1451
+ 4. Test rule components individually`;
1452
+ }).exhaustive();
1453
+ }
1454
+ const Gi = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
1455
+ function pr() {
1456
+ return { classes: [], predicates: [] };
1457
+ }
1458
+ function yt(e) {
1459
+ return {
1460
+ classes: e.flatMap(({ classes: t }) => t),
1461
+ predicates: e.flatMap(({ predicates: t }) => t)
1462
+ };
1463
+ }
1464
+ function _i(e) {
1465
+ return e === "a" || e === "rdf:type" || e === Gi;
1466
+ }
1467
+ function hr(e) {
1468
+ const t = Ze(e);
1469
+ if (t)
1470
+ return {
1471
+ classes: [{ term: t.className, graph: t.graph }],
1472
+ predicates: []
1473
+ };
1474
+ const r = Je(e);
1475
+ return r && !_i(r.predicate) ? {
1476
+ classes: [],
1477
+ predicates: [{ term: r.predicate, graph: r.graph }]
1478
+ } : pr();
1479
+ }
1480
+ function It(e) {
1481
+ return p(e).with({ type: u.union("triple", "property", "class", "general") }, hr).with(
1482
+ { type: "negation" },
1483
+ ({ formulas: t }) => yt(t.map(It))
1484
+ ).with(
1485
+ { type: "aggregate" },
1486
+ ({ atoms: t }) => yt(t.map(It))
1487
+ ).with({ type: u.union("filter", "bind", "skolem") }, pr).exhaustive();
1488
+ }
1489
+ function Vi(e) {
1490
+ return {
1491
+ head: yt(e.head.map(hr)),
1492
+ body: yt(e.body.map(It))
1493
+ };
1494
+ }
1495
+ const ji = [
1496
+ n.expression,
1497
+ n.conditionalOrExpression,
1498
+ n.conditionalAndExpression,
1499
+ n.valueLogical,
1500
+ n.relationalExpression,
1501
+ n.numericExpression,
1502
+ n.expressionList,
1503
+ n.additiveExpression,
1504
+ n.multiplicativeExpression,
1505
+ n.unaryExpression,
1506
+ n.primaryExpression,
1507
+ n.brackettedExpression,
1508
+ // BuiltInCall,
1509
+ n.iriOrFunction,
1510
+ n.rdfLiteral,
1511
+ n.numericLiteral,
1512
+ n.numericLiteralUnsigned,
1513
+ n.numericLiteralPositive,
1514
+ n.numericLiteralNegative,
1515
+ n.booleanLiteral,
1516
+ n.var_,
1517
+ n.builtInStr,
1518
+ n.builtInLang,
1519
+ n.builtInLangmatches,
1520
+ n.builtInDatatype,
1521
+ n.builtInBound,
1522
+ n.builtInIri,
1523
+ n.builtInUri,
1524
+ n.builtInBnodeSparqlJs,
1525
+ n.builtInRand,
1526
+ n.builtInAbs,
1527
+ n.builtInCeil,
1528
+ n.builtInFloor,
1529
+ n.builtInRound,
1530
+ n.builtInConcat,
1531
+ n.builtInStrlen,
1532
+ n.builtInUcase,
1533
+ n.builtInLcase,
1534
+ n.builtInEncode_for_uri
1535
+ ], qi = {
1536
+ name: "builtInCall",
1537
+ impl: ({ OR: e, SUBRULE: t }) => () => e(n.builtInCallList(t).slice(0, -2))
1538
+ }, Xi = P.create(ji).addMany(n.builtInContains, n.builtInStrstarts, n.builtInStrends, n.builtInStrbefore, n.builtInStrafter, n.builtInYear, n.builtInMonth, n.builtInDay, n.builtInHours, n.builtInMinutes, n.builtInSeconds, n.builtInTimezone, n.builtInTz, n.builtInNow, n.builtInUuid, n.builtInStruuid, n.builtInMd5, n.builtInSha1, n.builtInSha256, n.builtInSha384, n.builtInSha512, n.builtInCoalesce, n.builtInIf, n.builtInStrlang, n.builtInStrdt, n.builtInSameterm, n.builtInIsiri, n.builtInIsuri, n.builtInIsblank, n.builtInIsliteral, n.builtInIsnumeric, n.regexExpression, n.substringExpression, n.strReplaceExpression, n.aggregateCount, n.aggregateSum, n.aggregateMin, n.aggregateMax, n.aggregateAvg, n.aggregateSample, n.aggregateGroup_concat, n.aggregate, n.iri, n.prefixedName, n.argList, n.string).addRule(qi), Hi = [
1539
+ n.objectList,
1540
+ n.object,
1541
+ n.graphNode,
1542
+ n.varOrTerm,
1543
+ n.triplesNode,
1544
+ n.collection,
1545
+ n.blankNodePropertyList,
1546
+ n.propertyListNotEmpty,
1547
+ // PropertyListNotEmpty
1548
+ n.verb,
1549
+ n.verbA,
1550
+ n.varOrIri,
1551
+ n.var_,
1552
+ n.iri,
1553
+ n.iriFull,
1554
+ n.prefixedName,
1555
+ n.graphTerm,
1556
+ n.rdfLiteral,
1557
+ n.numericLiteral,
1558
+ n.booleanLiteral,
1559
+ n.blankNode,
1560
+ n.string,
1561
+ n.numericLiteralUnsigned,
1562
+ n.numericLiteralPositive,
1563
+ n.numericLiteralNegative
1564
+ ], dr = P.create(Hi), Qi = P.create([
1565
+ n.triplesBlock,
1566
+ n.triplesSameSubjectPath,
1567
+ // VarOrTerm is included in the required ObjectList rule
1568
+ n.propertyListPathNotEmpty,
1569
+ n.triplesNodePath,
1570
+ n.propertyListPath,
1571
+ // PropertyListNotEmpty
1572
+ n.verbPath,
1573
+ n.verbSimple,
1574
+ n.objectListPath
1575
+ ]).merge(dr, []).addMany(
1576
+ n.path,
1577
+ n.pathAlternative,
1578
+ n.pathSequence,
1579
+ n.pathEltOrInverse,
1580
+ n.pathElt,
1581
+ n.pathPrimary,
1582
+ n.pathMod,
1583
+ n.pathNegatedPropertySet,
1584
+ n.pathOneInPropertySet,
1585
+ // ObjectListPath
1586
+ n.objectPath,
1587
+ n.graphNodePath,
1588
+ n.collectionPath,
1589
+ n.blankNodePropertyListPath
1590
+ ), zi = [
1591
+ n.subSelect,
1592
+ n.selectClause,
1593
+ n.whereClause,
1594
+ n.solutionModifier,
1595
+ n.valuesClause
1596
+ ], Er = P.create(zi).merge(Xi, []).patchRule(n.builtInCall).addMany(n.existsFunc, n.notExistsFunc, n.groupGraphPattern, n.groupGraphPatternSub).merge(Qi, []).addMany(
1597
+ n.graphPatternNotTriples,
1598
+ n.groupOrUnionGraphPattern,
1599
+ n.optionalGraphPattern,
1600
+ n.minusGraphPattern,
1601
+ n.graphGraphPattern,
1602
+ n.serviceGraphPattern,
1603
+ n.filter,
1604
+ n.bind,
1605
+ n.inlineData,
1606
+ n.constraint,
1607
+ n.functionCall,
1608
+ n.dataBlock,
1609
+ n.inlineDataOneVar,
1610
+ n.inlineDataFull,
1611
+ n.dataBlockValue,
1612
+ // Solution modifier
1613
+ n.groupClause,
1614
+ n.havingClause,
1615
+ n.orderClause,
1616
+ n.limitOffsetClauses,
1617
+ n.groupCondition,
1618
+ n.havingCondition,
1619
+ n.orderCondition,
1620
+ n.limitClause,
1621
+ n.offsetClause
1622
+ ), Ki = [
1623
+ n.triplesTemplate,
1624
+ n.triplesSameSubject,
1625
+ n.varOrTerm,
1626
+ n.propertyListNotEmpty,
1627
+ n.triplesNode,
1628
+ n.propertyList,
1629
+ n.var_,
1630
+ n.graphTerm,
1631
+ n.iri,
1632
+ n.iriFull,
1633
+ n.prefixedName,
1634
+ n.rdfLiteral,
1635
+ n.string,
1636
+ n.numericLiteral,
1637
+ n.numericLiteralUnsigned,
1638
+ n.numericLiteralPositive,
1639
+ n.numericLiteralNegative,
1640
+ n.booleanLiteral,
1641
+ n.blankNode,
1642
+ n.verb,
1643
+ n.verbA,
1644
+ n.varOrIri,
1645
+ n.objectList,
1646
+ n.object,
1647
+ n.collection,
1648
+ n.blankNodePropertyList,
1649
+ n.graphNode
1650
+ ], fr = P.create(Ki), Wi = [
1651
+ n.queryUnit,
1652
+ n.query,
1653
+ n.prologue,
1654
+ n.selectQuery,
1655
+ n.constructQuery,
1656
+ n.describeQuery,
1657
+ n.askQuery,
1658
+ n.valuesClause,
1659
+ n.baseDecl,
1660
+ n.prefixDecl
1661
+ ], Yi = P.create(Wi).merge(Er, []).addRule(n.datasetClause).addRule(n.datasetClauseStar).addRule(n.defaultGraphClause).addRule(n.namedGraphClause).addRule(n.sourceSelector).addRule(n.constructTemplate).merge(fr, []).addRule(n.constructTriples), Zi = {
1662
+ name: "update1",
1663
+ impl: ({ SUBRULE: e, OR: t }) => () => t([
1664
+ { ALT: () => e(n.load) },
1665
+ { ALT: () => e(n.clear) },
1666
+ { ALT: () => e(n.drop) },
1667
+ { ALT: () => e(n.add) },
1668
+ { ALT: () => e(n.move) },
1669
+ { ALT: () => e(n.copy) },
1670
+ { ALT: () => e(n.create) },
1671
+ { ALT: () => e(n.insertData) },
1672
+ { ALT: () => e(n.deleteData) },
1673
+ { ALT: () => e(n.deleteWhere) }
1674
+ ]),
1675
+ gImpl: n.update1.gImpl
1676
+ }, Ji = [
1677
+ n.updateUnit,
1678
+ n.update,
1679
+ n.prologue,
1680
+ // Update1,
1681
+ n.baseDecl,
1682
+ n.prefixDecl,
1683
+ n.load,
1684
+ n.clear,
1685
+ n.drop,
1686
+ n.add,
1687
+ n.move,
1688
+ n.copy,
1689
+ n.create,
1690
+ n.insertData,
1691
+ n.deleteData,
1692
+ n.deleteWhere,
1693
+ n.iri,
1694
+ n.prefixedName,
1695
+ n.graphRef,
1696
+ n.graphRefAll,
1697
+ n.graphOrDefault,
1698
+ n.quadData,
1699
+ n.quads
1700
+ ], tn = P.create(Ji).addRule(Zi).merge(fr, []).addRule(n.quadPattern).addRule(n.quadsNotTriples), en = P.create(tn).patchRule(n.update1).addMany(n.modify, n.deleteClause, n.insertClause, n.usingClause, n.defaultGraphClause, n.namedGraphClause, n.sourceSelector, n.usingClauseStar, n.groupGraphPattern).merge(dr, []).merge(Er, []), rn = P.create(Yi).merge(en, []).addRule(n.queryOrUpdate);
1701
+ class gr extends Ir {
1702
+ constructor(t = {}) {
1703
+ const r = rn.build({
1704
+ ...t,
1705
+ tokenVocabulary: ze.sparql11LexerBuilder.tokenVocabulary,
1706
+ queryPreProcessor: Mr
1707
+ });
1708
+ super(r, t.defaultContext);
1709
+ }
1710
+ }
1711
+ let Lt;
1712
+ function nn(e) {
1713
+ return e.type === "query";
1714
+ }
1715
+ function mr(e) {
1716
+ return e.type === "update";
1717
+ }
1718
+ function yr(e) {
1719
+ return e.replace(/\s+EXPLICIT\s+(TRUE|FALSE)\b/gi, "");
1720
+ }
1721
+ function sn(e) {
1722
+ Lt ?? (Lt = new gr());
1723
+ try {
1724
+ const t = Lt.parse(yr(e));
1725
+ return mr(t) ? {
1726
+ valid: !0,
1727
+ queryType: "update",
1728
+ isReadOnly: !1
1729
+ } : nn(t) ? {
1730
+ valid: !0,
1731
+ queryType: t.subType,
1732
+ isReadOnly: !0
1733
+ } : {
1734
+ valid: !1,
1735
+ error: "Unknown query type"
1736
+ };
1737
+ } catch (t) {
1738
+ return {
1739
+ valid: !1,
1740
+ error: t instanceof Error ? t.message : "Failed to parse SPARQL query"
1741
+ };
1742
+ }
1743
+ }
1744
+ function As(e) {
1745
+ const t = sn(e);
1746
+ return t.valid ? t.isReadOnly ? { allowed: !0, queryType: t.queryType } : {
1747
+ allowed: !1,
1748
+ error: "UPDATE operations not allowed. Only SELECT, CONSTRUCT, DESCRIBE, and ASK queries are permitted.",
1749
+ queryType: t.queryType
1750
+ } : { allowed: !1, error: t.error };
1751
+ }
1752
+ const an = /* @__PURE__ */ new Set([
1753
+ "insertdata",
1754
+ "deletedata",
1755
+ "modify"
1756
+ ]), on = {
1757
+ insertdata: "INSERT DATA",
1758
+ deletedata: "DELETE DATA",
1759
+ deletewhere: "DELETE WHERE",
1760
+ modify: "DELETE/INSERT WHERE",
1761
+ load: "LOAD",
1762
+ clear: "CLEAR",
1763
+ drop: "DROP",
1764
+ create: "CREATE",
1765
+ add: "ADD",
1766
+ move: "MOVE",
1767
+ copy: "COPY"
1768
+ };
1769
+ function _e(e) {
1770
+ return an.has(e);
1771
+ }
1772
+ function Ve(e) {
1773
+ return e.type === "term" && e.subType === "variable";
1774
+ }
1775
+ function ln(e) {
1776
+ return Ve(e.subject) && e.predicate.subType === "variable" && Ve(e.object);
1777
+ }
1778
+ function un(e) {
1779
+ for (const t of e) {
1780
+ const r = t.type === "graph" ? t.triples.triples : t.triples;
1781
+ for (const i of r)
1782
+ if (i.type === "triple" && ln(i)) return !0;
1783
+ }
1784
+ return !1;
1785
+ }
1786
+ function cn(e) {
1787
+ return e.delete.length > 0 && un(e.delete);
1788
+ }
1789
+ function Ts(e) {
1790
+ Lt ?? (Lt = new gr());
1791
+ let t;
1792
+ try {
1793
+ t = Lt.parse(yr(e));
1794
+ } catch (o) {
1795
+ return {
1796
+ allowed: !1,
1797
+ error: o instanceof Error ? o.message : "Failed to parse SPARQL update"
1798
+ };
1799
+ }
1800
+ if (!mr(t))
1801
+ return {
1802
+ allowed: !1,
1803
+ error: "Expected a SPARQL UPDATE statement, not a query."
1804
+ };
1805
+ const r = [];
1806
+ for (const o of t.updates)
1807
+ o.operation && r.push(o.operation);
1808
+ if (r.length === 0)
1809
+ return { allowed: !1, error: "Empty SPARQL update -- no operations found." };
1810
+ const i = r.filter((o) => !_e(o.subType));
1811
+ if (i.length > 0) {
1812
+ const o = i.map((E) => E.subType);
1813
+ return {
1814
+ allowed: !1,
1815
+ error: `Blocked operations: ${i.map((E) => on[E.subType]).join(", ")}. Only INSERT DATA, DELETE DATA, and DELETE/INSERT WHERE are permitted.`,
1816
+ blockedOperations: o
1817
+ };
1818
+ }
1819
+ return r.filter(
1820
+ (o) => o.subType === "modify" && cn(o)
1821
+ ).length > 0 ? {
1822
+ allowed: !1,
1823
+ error: "Unscoped DELETE patterns (all-variable triples) are not permitted.",
1824
+ blockedOperations: ["modify"]
1825
+ } : { allowed: !0, operationTypes: r.map((o) => o.subType).filter(_e) };
1826
+ }
1827
+ async function pn(e) {
1828
+ const { rdfoxUrl: t, datastoreName: r, authorization: i } = e, s = new URL(`datastores/${r}/connections`, t), a = await fetch(s.toString(), {
1829
+ method: "POST",
1830
+ headers: {
1831
+ Authorization: i
1832
+ }
1833
+ });
1834
+ if (!a.ok) {
1835
+ const l = await a.text();
1836
+ throw new Error(`Failed to create connection: ${a.status} - ${l}`);
1837
+ }
1838
+ const o = a.headers.get("Location");
1839
+ if (!o)
1840
+ throw new Error("Connection creation response missing Location header");
1841
+ return o.split("/").pop();
1842
+ }
1843
+ async function hn(e) {
1844
+ const { rdfoxUrl: t, datastoreName: r, connectionId: i, authorization: s } = e, a = new URL(`datastores/${r}/connections/${i}/transaction`, t);
1845
+ a.searchParams.set("operation", "begin-read-write-transaction");
1846
+ const o = await fetch(a.toString(), {
1847
+ method: "PATCH",
1848
+ headers: {
1849
+ Authorization: s
1850
+ }
1851
+ });
1852
+ if (!o.ok) {
1853
+ const l = await o.text();
1854
+ throw new Error(`Failed to begin transaction: ${o.status} - ${l}`);
1855
+ }
1856
+ }
1857
+ async function dn(e) {
1858
+ const { rdfoxUrl: t, datastoreName: r, connectionId: i, authorization: s } = e, a = new URL(`datastores/${r}/connections/${i}/transaction`, t);
1859
+ a.searchParams.set("operation", "commit-transaction");
1860
+ const o = await fetch(a.toString(), {
1861
+ method: "PATCH",
1862
+ headers: {
1863
+ Authorization: s
1864
+ }
1865
+ });
1866
+ if (!o.ok) {
1867
+ const l = await o.text();
1868
+ throw new Error(`Failed to commit transaction: ${o.status} - ${l}`);
1869
+ }
1870
+ }
1871
+ async function En(e) {
1872
+ const { rdfoxUrl: t, datastoreName: r, connectionId: i, authorization: s } = e, a = new URL(`datastores/${r}/connections/${i}/transaction`, t);
1873
+ a.searchParams.set("operation", "rollback-transaction");
1874
+ const o = await fetch(a.toString(), {
1875
+ method: "PATCH",
1876
+ headers: {
1877
+ Authorization: s
1878
+ }
1879
+ });
1880
+ if (!o.ok) {
1881
+ const l = await o.text();
1882
+ throw new Error(`Failed to rollback transaction: ${o.status} - ${l}`);
1883
+ }
1884
+ }
1885
+ async function fn(e) {
1886
+ const { rdfoxUrl: t, datastoreName: r, connectionId: i, authorization: s } = e, a = new URL(`datastores/${r}/connections/${i}`, t), o = await fetch(a.toString(), {
1887
+ method: "DELETE",
1888
+ headers: {
1889
+ Authorization: s
1890
+ }
1891
+ });
1892
+ if (!o.ok) {
1893
+ const l = await o.text();
1894
+ throw new Error(`Failed to delete connection: ${o.status} - ${l}`);
1895
+ }
1896
+ }
1897
+ async function Ss(e, t) {
1898
+ const r = await pn(e);
1899
+ try {
1900
+ await hn({ ...e, connectionId: r });
1901
+ const i = await t(r);
1902
+ return await dn({ ...e, connectionId: r }), i;
1903
+ } catch (i) {
1904
+ try {
1905
+ await En({ ...e, connectionId: r });
1906
+ } catch (s) {
1907
+ console.error("Failed to rollback transaction:", s);
1908
+ }
1909
+ throw i;
1910
+ } finally {
1911
+ try {
1912
+ await fn({ ...e, connectionId: r });
1913
+ } catch (i) {
1914
+ console.error("Failed to delete connection:", i);
1915
+ }
1916
+ }
1917
+ }
1918
+ function Nt(e) {
1919
+ return e.type === "variable" ? `?${e.name}` : void 0;
1920
+ }
1921
+ function Ns(e) {
1922
+ const t = /* @__PURE__ */ new Map();
1923
+ function r(a) {
1924
+ let o = t.get(a);
1925
+ return o || (o = { variable: a, predicateEvidence: [] }, t.set(a, o)), o;
1926
+ }
1927
+ function i(a) {
1928
+ const { atom: o, fromBody: l = !1 } = a, E = Ze(o);
1929
+ if (E) {
1930
+ const R = Nt(E.instance);
1931
+ if (R) {
1932
+ const L = r(R);
1933
+ L.classTerm ?? (L.classTerm = E.className), l && (L.bodyClassTerm ?? (L.bodyClassTerm = E.className));
1934
+ }
1935
+ return;
1936
+ }
1937
+ const y = Je(o);
1938
+ if (!y) return;
1939
+ const S = Nt(y.subject), h = Nt(y.object);
1940
+ S && r(S).predicateEvidence.push({ term: y.predicate, position: "domain" }), h && r(h).predicateEvidence.push({ term: y.predicate, position: "range" });
1941
+ }
1942
+ function s(a) {
1943
+ if (Be(a)) {
1944
+ i({ atom: a, fromBody: !0 });
1945
+ return;
1946
+ }
1947
+ a.type === "aggregate" && a.atoms.filter(Be).forEach((o) => i({ atom: o, fromBody: !0 }));
1948
+ }
1949
+ return e.head.forEach((a) => i({ atom: a })), e.body.forEach(s), [...t.values()];
1950
+ }
1951
+ function Rs(e, t) {
1952
+ const r = [];
1953
+ for (const i of e) {
1954
+ const s = i.bodyClassTerm ?? i.classTerm;
1955
+ if (s) {
1956
+ r.push({ variable: i.variable, typeTerm: s, source: "class" });
1957
+ continue;
1958
+ }
1959
+ const a = gn(i.predicateEvidence, t);
1960
+ a && r.push({ variable: i.variable, ...a });
1961
+ }
1962
+ return r;
1963
+ }
1964
+ function gn(e, t) {
1965
+ for (const { term: r, position: i } of e) {
1966
+ const s = t(r), a = i === "domain" ? s == null ? void 0 : s.domainIncludes[0] : s == null ? void 0 : s.rangeIncludes[0];
1967
+ if (a) return { typeTerm: a, source: i };
1968
+ }
1969
+ }
1970
+ const mn = new xe({ selfAnalysis: !1 }).getBaseCstVisitorConstructor();
1971
+ function v(e, t) {
1972
+ if (e === void 0)
1973
+ throw new Error(t);
1974
+ return e;
1975
+ }
1976
+ function at(e, t, ...r) {
1977
+ var s;
1978
+ if (!e)
1979
+ throw new Error(`Children is undefined when looking for keys: [${r.join(", ")}]`);
1980
+ for (const a of r)
1981
+ if ((s = e[a]) != null && s[0]) return t(e[a][0]);
1982
+ const i = Object.keys(e);
1983
+ throw new Error(`None of [${r.join(", ")}] found. Available keys: [${i.join(", ")}]`);
1984
+ }
1985
+ const f = (e) => e != null && e.length > 0;
1986
+ function je(e) {
1987
+ return e.flatMap(({ arr: t, op: r }) => (t ?? []).map((i) => ({ offset: i.startOffset, op: r }))).sort((t, r) => t.offset - r.offset).map(({ op: t }) => t);
1988
+ }
1989
+ function Y(e) {
1990
+ const t = e.startOffset ?? 0, r = e.endOffset ?? t + e.image.length - 1;
1991
+ return { start: t, end: r + 1 };
1992
+ }
1993
+ function V(e, t, r = e.image) {
1994
+ return {
1995
+ token: e,
1996
+ term: { type: "iri", value: r, prefixed: t }
1997
+ };
1998
+ }
1999
+ function qe(e) {
2000
+ return p(e).returnType().with(
2001
+ { IRI_REF: u.when(f) },
2002
+ ({ IRI_REF: t }) => V(t[0], !1, t[0].image.slice(1, -1))
2003
+ ).with({ PREFIXED_NAME: u.when(f) }, ({ PREFIXED_NAME: t }) => V(t[0], !0)).with({ PREFIX_ONLY: u.when(f) }, ({ PREFIX_ONLY: t }) => V(t[0], !0)).with({ IDENTIFIER: u.when(f) }, ({ IDENTIFIER: t }) => V(t[0], !1)).with({ DEFAULT_NS_IRI: u.when(f) }, ({ DEFAULT_NS_IRI: t }) => V(t[0], !0)).with(
2004
+ { INTERNAL_FUNCTION: u.when(f) },
2005
+ ({ INTERNAL_FUNCTION: t }) => V(t[0], !1)
2006
+ ).otherwise(() => {
2007
+ throw new Error("Unknown IRI type");
2008
+ });
2009
+ }
2010
+ function yn(e, t) {
2011
+ const r = Y(e);
2012
+ return {
2013
+ start: r.start + t,
2014
+ end: r.end - t
2015
+ };
2016
+ }
2017
+ class Ln extends mn {
2018
+ rule(t) {
2019
+ var s;
2020
+ const r = this.visit(v(t.ruleHead, "Rule missing head")), i = (s = t.ruleBody) != null && s[0] ? this.visit(t.ruleBody) : [];
2021
+ return { head: r, body: i };
2022
+ }
2023
+ ruleHead(t) {
2024
+ return t.tupleTableAtom.map((r) => this.visit(r));
2025
+ }
2026
+ ruleBody(t) {
2027
+ return t.bodyFormula.map((r) => this.visit(r));
2028
+ }
2029
+ bodyFormula(t) {
2030
+ return at(
2031
+ t,
2032
+ this.visit.bind(this),
2033
+ "negation",
2034
+ "filterAtom",
2035
+ "bindAtom",
2036
+ "aggregate",
2037
+ "skolemAtom",
2038
+ "tupleTableAtom"
2039
+ );
2040
+ }
2041
+ tupleTableAtom(t) {
2042
+ const r = at(t, this.visit.bind(this), "defaultGraphAtom", "generalAtom");
2043
+ if (f(t.graph)) {
2044
+ const i = this.visit(t.graph[0]);
2045
+ if (r.type === "triple" || r.type === "property" || r.type === "class")
2046
+ return { ...r, graph: i };
2047
+ throw new Error(`Graph annotation not supported on atom type '${r.type}'`);
2048
+ }
2049
+ return r;
2050
+ }
2051
+ graphName(t) {
2052
+ if (f(t.VARIABLE))
2053
+ return { type: "variable", name: t.VARIABLE[0].image.substring(1) };
2054
+ if (f(t.iri))
2055
+ return this.visit(t.iri[0]);
2056
+ throw new Error("Unknown graph name type");
2057
+ }
2058
+ defaultGraphAtom(t) {
2059
+ const r = t;
2060
+ if (f(r.subject) && f(r.predicate) && f(r.object))
2061
+ return {
2062
+ type: "triple",
2063
+ subject: this.visit(r.subject[0]),
2064
+ predicate: this.visit(r.predicate[0]),
2065
+ object: this.visit(r.object[0])
2066
+ };
2067
+ if (f(r.predicateOrClass) && f(r.firstTerm)) {
2068
+ const i = this.extractIriValue(r.predicateOrClass[0]), s = this.visit(r.firstTerm[0]);
2069
+ return f(r.secondTerm) ? {
2070
+ type: "property",
2071
+ predicate: i,
2072
+ subject: s,
2073
+ object: this.visit(r.secondTerm[0])
2074
+ } : {
2075
+ type: "class",
2076
+ className: i,
2077
+ instance: s
2078
+ };
2079
+ }
2080
+ throw new Error("Unknown default graph atom format");
2081
+ }
2082
+ generalAtom(t) {
2083
+ const r = t;
2084
+ return {
2085
+ type: "general",
2086
+ tableName: f(r.IDENTIFIER) ? r.IDENTIFIER[0].image : f(r.STRING_LITERAL) ? this.unquoteString(r.STRING_LITERAL[0].image) : (() => {
2087
+ throw new Error("Missing table name");
2088
+ })(),
2089
+ terms: r.term.map((s) => this.visit(s))
2090
+ };
2091
+ }
2092
+ term(t) {
2093
+ const r = t;
2094
+ if (f(r.VARIABLE)) return { type: "variable", name: r.VARIABLE[0].image.substring(1) };
2095
+ if (f(r.iri)) return this.visit(r.iri[0]);
2096
+ if (f(r.literal)) return this.visit(r.literal[0]);
2097
+ if (f(r.BLANK_NODE)) return { type: "blank", label: r.BLANK_NODE[0].image.substring(2) };
2098
+ throw new Error("Unknown term type");
2099
+ }
2100
+ iri(t) {
2101
+ return qe(t).term;
2102
+ }
2103
+ literal(t) {
2104
+ return at(
2105
+ t,
2106
+ this.visit.bind(this),
2107
+ "numericLiteral",
2108
+ "booleanLiteral",
2109
+ "stringLiteral"
2110
+ );
2111
+ }
2112
+ numericLiteral(t) {
2113
+ const r = t;
2114
+ if (f(r.INTEGER)) return this.numericTokenLiteral(r.INTEGER[0], j.integer);
2115
+ if (f(r.DECIMAL)) return this.numericTokenLiteral(r.DECIMAL[0], j.decimal);
2116
+ if (f(r.DOUBLE)) return this.numericTokenLiteral(r.DOUBLE[0], j.double);
2117
+ throw new Error("Unknown numeric literal type");
2118
+ }
2119
+ booleanLiteral(t) {
2120
+ const r = t;
2121
+ if (f(r.TRUE)) return { type: "literal", value: "true", datatype: j.boolean };
2122
+ if (f(r.FALSE)) return { type: "literal", value: "false", datatype: j.boolean };
2123
+ throw new Error("Unknown boolean literal type");
2124
+ }
2125
+ stringLiteral(t) {
2126
+ var h, R, L, A;
2127
+ const r = (h = t.STRING_LITERAL_LONG) == null ? void 0 : h[0], i = (R = t.STRING_LITERAL) == null ? void 0 : R[0], s = r ?? i;
2128
+ if (!s) throw new Error("Unknown string literal format");
2129
+ const a = r ? this.unquoteTripleString(s.image) : this.unquoteString(s.image), o = Y(s), l = (L = t.LANGTAG) == null ? void 0 : L[0], E = (A = t.iri) != null && A[0] ? qe(t.iri[0].children) : void 0, y = l ? Y(l).end : E ? Y(E.token).end : o.end, S = {
2130
+ type: "literal",
2131
+ value: a,
2132
+ termSpan: { start: o.start, end: y },
2133
+ valueSpan: yn(s, r ? 3 : 1)
2134
+ };
2135
+ return l ? S.language = l.image.substring(1) : E && (S.datatype = E.term.value), S;
2136
+ }
2137
+ negation(t) {
2138
+ var s, a, o;
2139
+ const r = [];
2140
+ if ((s = t.existsClause) != null && s[0]) {
2141
+ const l = this.visit(t.existsClause);
2142
+ r.push(...l);
2143
+ }
2144
+ const i = [];
2145
+ return (a = t.bodyFormulaList) != null && a[0] ? i.push(...this.visit(t.bodyFormulaList)) : (o = t.tupleTableAtom) != null && o[0] && i.push(this.visit(t.tupleTableAtom)), {
2146
+ type: "negation",
2147
+ formulas: i,
2148
+ existentialVars: r.length > 0 ? r : void 0
2149
+ };
2150
+ }
2151
+ existsClause(t) {
2152
+ return t.VARIABLE.map((r) => r.image.substring(1));
2153
+ }
2154
+ atomList(t) {
2155
+ return t.atom ? t.atom.map((r) => this.visit(r)) : [];
2156
+ }
2157
+ atom(t) {
2158
+ return at(
2159
+ t,
2160
+ (r) => this.visit(r),
2161
+ "tupleTableAtom",
2162
+ "filterAtom",
2163
+ "bindAtom"
2164
+ );
2165
+ }
2166
+ bodyFormulaList(t) {
2167
+ return t.bodyFormula.map((r) => this.visit(r));
2168
+ }
2169
+ filterAtom(t) {
2170
+ return {
2171
+ type: "filter",
2172
+ expression: this.visit(v(t.expression, "Filter missing expression"))
2173
+ };
2174
+ }
2175
+ bindAtom(t) {
2176
+ return {
2177
+ type: "bind",
2178
+ expression: this.visit(v(t.expression, "Bind missing expression")),
2179
+ ...this.asTarget(t, "Bind missing variable")
2180
+ };
2181
+ }
2182
+ // The expanded grammar accepts a value where a variable belongs, because RDFox
2183
+ // substitutes the `AS` target when it grounds a rule.
2184
+ asTarget(t, r) {
2185
+ var a;
2186
+ const i = (a = t.VARIABLE) == null ? void 0 : a[0];
2187
+ if (i) return { variable: i.image.substring(1) };
2188
+ const s = this.visit(v(t.groundedAsTarget, r));
2189
+ return { variable: x(s, { stripSimpleLiteralDatatypes: !0 }), groundedTarget: s };
2190
+ }
2191
+ // A variable-free `term`, so it visits identically.
2192
+ groundedAsTarget(t) {
2193
+ return this.term(t);
2194
+ }
2195
+ skolemAtom(t) {
2196
+ return {
2197
+ type: "skolem",
2198
+ args: this.visit(v(t.argumentList, "Skolem missing argument list"))
2199
+ };
2200
+ }
2201
+ aggregate(t) {
2202
+ var a;
2203
+ const r = (a = t.atomList) != null && a[0] ? this.visit(t.atomList) : [], i = t.onClause ? this.visit(t.onClause) : void 0, s = t.aggregateBind ? t.aggregateBind.map((o) => this.visit(o)) : void 0;
2204
+ if (r.length === 0 && !(s != null && s.length))
2205
+ throw new Error("AGGREGATE requires at least one atom or binding");
2206
+ return {
2207
+ type: "aggregate",
2208
+ atoms: r,
2209
+ onVars: i == null ? void 0 : i.onVars,
2210
+ groundedOnTargets: i == null ? void 0 : i.groundedOnTargets,
2211
+ bindings: s
2212
+ };
2213
+ }
2214
+ // RDFox grounds every grouping variable or none of them, so listing the
2215
+ // variables ahead of any substituted values preserves source order in practice.
2216
+ onClause(t) {
2217
+ var a, o;
2218
+ const r = ((a = t.VARIABLE) == null ? void 0 : a.map((l) => l.image.substring(1))) ?? [], i = ((o = t.groundedAsTarget) == null ? void 0 : o.map((l) => this.visit(l))) ?? [], s = i.map(
2219
+ (l) => x(l, { stripSimpleLiteralDatatypes: !0 })
2220
+ );
2221
+ return {
2222
+ onVars: [...r, ...s],
2223
+ groundedOnTargets: i.length > 0 ? i : void 0
2224
+ };
2225
+ }
2226
+ aggregateBind(t) {
2227
+ var i;
2228
+ const r = this.asTarget(t, "AggregateBind missing variable");
2229
+ return (i = t.aggregateFunction) != null && i[0] ? { ...this.visit(t.aggregateFunction), ...r } : {
2230
+ expression: this.visit(v(t.expression, "AggregateBind missing expression")),
2231
+ ...r
2232
+ };
2233
+ }
2234
+ aggregateFunction(t) {
2235
+ return p(t).with({ aggregateFunction1: u.when(f) }, (r) => this.visit(r.aggregateFunction1[0])).with({ aggregateFunction2: u.when(f) }, (r) => this.visit(r.aggregateFunction2[0])).otherwise(() => {
2236
+ throw new Error("Unknown aggregate function arity");
2237
+ });
2238
+ }
2239
+ aggregateFunction1(t) {
2240
+ var i;
2241
+ return {
2242
+ function: p(t).when(
2243
+ (s) => !!s.COUNT_MIN,
2244
+ () => "COUNT_MIN"
2245
+ ).when(
2246
+ (s) => !!s.COUNT_MAX,
2247
+ () => "COUNT_MAX"
2248
+ ).when(
2249
+ (s) => !!s.COUNT,
2250
+ () => "COUNT"
2251
+ ).when(
2252
+ (s) => !!s.MIN,
2253
+ () => "MIN"
2254
+ ).when(
2255
+ (s) => !!s.MAX,
2256
+ () => "MAX"
2257
+ ).when(
2258
+ (s) => !!s.SUM,
2259
+ () => "SUM"
2260
+ ).when(
2261
+ (s) => !!s.MUL,
2262
+ () => "MUL"
2263
+ ).when(
2264
+ (s) => !!s.AVG,
2265
+ () => "AVG"
2266
+ ).otherwise(() => {
2267
+ throw new Error("Unknown aggregate function");
2268
+ }),
2269
+ expression: t.STAR ? "*" : (i = t.expression) != null && i[0] ? this.visit(t.expression[0]) : { type: "term", term: { type: "literal", value: "", datatype: "xsd:string" } },
2270
+ ...t.DISTINCT && { distinct: !0 }
2271
+ };
2272
+ }
2273
+ aggregateFunction2(t) {
2274
+ var i, s;
2275
+ return {
2276
+ function: p(t).when(
2277
+ (a) => !!a.MIN_ARGMIN,
2278
+ () => "MIN_ARGMIN"
2279
+ ).when(
2280
+ (a) => !!a.MAX_ARGMIN,
2281
+ () => "MAX_ARGMIN"
2282
+ ).when(
2283
+ (a) => !!a.MIN_ARGMAX,
2284
+ () => "MIN_ARGMAX"
2285
+ ).when(
2286
+ (a) => !!a.MAX_ARGMAX,
2287
+ () => "MAX_ARGMAX"
2288
+ ).otherwise(() => {
2289
+ throw new Error("Unknown aggregate function");
2290
+ }),
2291
+ expression: this.visit(v((i = t.firstExpr) == null ? void 0 : i[0], "AggregateFunction2 missing first expression")),
2292
+ secondExpression: this.visit(
2293
+ v((s = t.secondExpr) == null ? void 0 : s[0], "AggregateFunction2 missing second expression")
2294
+ ),
2295
+ ...t.DISTINCT && { distinct: !0 }
2296
+ };
2297
+ }
2298
+ expression(t) {
2299
+ return this.visit(t.conditionalOrExpression);
2300
+ }
2301
+ conditionalOrExpression(t) {
2302
+ return t.conditionalAndExpression.slice(1).reduce(
2303
+ (r, i) => ({
2304
+ type: "binary",
2305
+ operator: "||",
2306
+ left: r,
2307
+ right: this.visit(i)
2308
+ }),
2309
+ this.visit(t.conditionalAndExpression[0])
2310
+ );
2311
+ }
2312
+ conditionalAndExpression(t) {
2313
+ return t.relationalExpression.slice(1).reduce(
2314
+ (r, i) => ({
2315
+ type: "binary",
2316
+ operator: "&&",
2317
+ left: r,
2318
+ right: this.visit(i)
2319
+ }),
2320
+ this.visit(t.relationalExpression[0])
2321
+ );
2322
+ }
2323
+ relationalExpression(t) {
2324
+ var i;
2325
+ const r = this.visit(t.additiveExpression);
2326
+ if (t.IN) {
2327
+ const s = !!t.NOT, a = (i = t.argumentList) == null ? void 0 : i[0], o = a ? this.visit(a) : [];
2328
+ return {
2329
+ type: "in",
2330
+ negated: s,
2331
+ expression: r,
2332
+ list: o
2333
+ };
2334
+ }
2335
+ return t.additiveExpression.length > 1 ? {
2336
+ type: "binary",
2337
+ operator: p(t).with({ EQUALS: u.when(Boolean) }, () => "=").with({ NOT_EQUALS: u.when(Boolean) }, () => "!=").with({ LESS_THAN: u.when(Boolean) }, () => "<").with({ GREATER_THAN: u.when(Boolean) }, () => ">").with({ LESS_THAN_OR_EQUAL: u.when(Boolean) }, () => "<=").with({ GREATER_THAN_OR_EQUAL: u.when(Boolean) }, () => ">=").otherwise(() => "="),
2338
+ left: r,
2339
+ right: t.additiveExpression[1] ? this.visit(t.additiveExpression[1]) : r
2340
+ } : r;
2341
+ }
2342
+ additiveExpression(t) {
2343
+ const r = je([
2344
+ { arr: t.PLUS, op: "+" },
2345
+ { arr: t.MINUS, op: "-" }
2346
+ ]);
2347
+ return t.multiplicativeExpression.slice(1).reduce(
2348
+ (i, s, a) => ({
2349
+ type: "binary",
2350
+ operator: r[a] ?? "+",
2351
+ left: i,
2352
+ right: this.visit(s)
2353
+ }),
2354
+ this.visit(t.multiplicativeExpression[0])
2355
+ );
2356
+ }
2357
+ multiplicativeExpression(t) {
2358
+ const r = je([
2359
+ { arr: t.STAR, op: "*" },
2360
+ { arr: t.SLASH, op: "/" }
2361
+ ]);
2362
+ return t.unaryExpression.slice(1).reduce(
2363
+ (i, s, a) => ({
2364
+ type: "binary",
2365
+ operator: r[a] ?? "*",
2366
+ left: i,
2367
+ right: this.visit(s)
2368
+ }),
2369
+ this.visit(t.unaryExpression[0])
2370
+ );
2371
+ }
2372
+ unaryExpression(t) {
2373
+ return p(t).with(
2374
+ { EXCLAMATION: u.when(Boolean) },
2375
+ () => ({
2376
+ type: "unary",
2377
+ operator: "!",
2378
+ operand: this.visit(t.primaryExpression)
2379
+ })
2380
+ ).with(
2381
+ { PLUS: u.when(Boolean) },
2382
+ () => ({
2383
+ type: "unary",
2384
+ operator: "+",
2385
+ operand: this.visit(t.primaryExpression)
2386
+ })
2387
+ ).with(
2388
+ { MINUS: u.when(Boolean) },
2389
+ () => ({
2390
+ type: "unary",
2391
+ operator: "-",
2392
+ operand: this.visit(t.primaryExpression)
2393
+ })
2394
+ ).otherwise(() => this.visit(t.primaryExpression));
2395
+ }
2396
+ functionCall(t) {
2397
+ return p(t).with({ concatFunction: u.when(f) }, (r) => this.visit(r.concatFunction[0])).with({ strFunction: u.when(f) }, (r) => this.visit(r.strFunction[0])).with({ ifFunction: u.when(f) }, (r) => this.visit(r.ifFunction[0])).with({ iriFunction: u.when(f) }, (r) => this.visit(r.iriFunction[0])).with({ skolemFunction: u.when(f) }, (r) => this.visit(r.skolemFunction[0])).with({ roundFunction: u.when(f) }, (r) => this.visit(r.roundFunction[0])).with({ regexFunction: u.when(f) }, (r) => this.visit(r.regexFunction[0])).with({ iri: u.when(f), LPAREN: u.when(f) }, (r) => {
2398
+ var o;
2399
+ const i = r.iri[0] ? this.visit(r.iri[0]) : null, s = i && typeof i == "object" && "type" in i && i.type === "iri" && "value" in i ? String(i.value) : "unknown", a = (o = r.argumentList) != null && o[0] ? this.visit(r.argumentList[0]) : [];
2400
+ return { type: "function", name: s, args: a };
2401
+ }).otherwise(() => {
2402
+ throw new Error("Unknown function call type");
2403
+ });
2404
+ }
2405
+ concatFunction(t) {
2406
+ return {
2407
+ type: "function",
2408
+ name: "CONCAT",
2409
+ args: this.visit(t.argumentList)
2410
+ };
2411
+ }
2412
+ strFunction(t) {
2413
+ return {
2414
+ type: "function",
2415
+ name: "STR",
2416
+ args: [this.visit(t.expression)]
2417
+ };
2418
+ }
2419
+ ifFunction(t) {
2420
+ return {
2421
+ type: "function",
2422
+ name: "IF",
2423
+ args: [this.visit(t.condition), this.visit(t.thenExpr), this.visit(t.elseExpr)]
2424
+ };
2425
+ }
2426
+ iriFunction(t) {
2427
+ const r = [this.visit(t.iriExpr)];
2428
+ return t.baseIri && r.push(this.visit(t.baseIri)), {
2429
+ type: "function",
2430
+ name: "IRI",
2431
+ args: r
2432
+ };
2433
+ }
2434
+ skolemFunction(t) {
2435
+ return {
2436
+ type: "function",
2437
+ name: "SKOLEM",
2438
+ args: this.visit(t.argumentList)
2439
+ };
2440
+ }
2441
+ roundFunction(t) {
2442
+ return {
2443
+ type: "function",
2444
+ name: "ROUND",
2445
+ args: [this.visit(t.expression)]
2446
+ };
2447
+ }
2448
+ regexFunction(t) {
2449
+ var i;
2450
+ const r = [
2451
+ this.visit(v(t.textExpr, "REGEX missing text expression")),
2452
+ this.visit(v(t.patternExpr, "REGEX missing pattern expression"))
2453
+ ];
2454
+ return (i = t.flagsExpr) != null && i[0] && r.push(this.visit(t.flagsExpr)), {
2455
+ type: "function",
2456
+ name: "REGEX",
2457
+ args: r
2458
+ };
2459
+ }
2460
+ argumentList(t) {
2461
+ return t.expression.map((r) => this.visit(r));
2462
+ }
2463
+ primaryExpression(t) {
2464
+ return p(t).with({ expression: u.when(f) }, (r) => this.visit(r.expression[0])).with({ functionCall: u.when(f) }, (r) => this.visit(r.functionCall[0])).with({ literal: u.when(f) }, (r) => ({ type: "term", term: this.visit(r.literal[0]) })).with({ VARIABLE: u.when(f) }, (r) => ({
2465
+ type: "term",
2466
+ term: { type: "variable", name: r.VARIABLE[0].image.substring(1) }
2467
+ })).with({ BLANK_NODE: u.when(f) }, (r) => ({
2468
+ type: "term",
2469
+ term: { type: "blank", label: r.BLANK_NODE[0].image.substring(2) }
2470
+ })).with({ iri: u.when(f) }, (r) => ({ type: "term", term: this.visit(r.iri[0]) })).otherwise(() => {
2471
+ throw new Error("Unknown primary expression type");
2472
+ });
2473
+ }
2474
+ extractIriValue(t) {
2475
+ return this.visit(t).value;
2476
+ }
2477
+ numericTokenLiteral(t, r) {
2478
+ const i = Y(t);
2479
+ return {
2480
+ type: "literal",
2481
+ value: t.image,
2482
+ datatype: r,
2483
+ termSpan: i,
2484
+ valueSpan: i
2485
+ };
2486
+ }
2487
+ unquoteString(t) {
2488
+ return t.substring(1, t.length - 1).replace(/\\(.)/g, "$1");
2489
+ }
2490
+ unquoteTripleString(t) {
2491
+ return t.substring(3, t.length - 3).replace(/\\(.)/g, "$1");
2492
+ }
2493
+ }
2494
+ let Un;
2495
+ function Ce() {
2496
+ return Un ?? (Un = new Ln());
2497
+ }
2498
+ function M(e, t) {
2499
+ t.forEach((r) => e.add(r));
2500
+ }
2501
+ function F(e, t, r) {
2502
+ t.forEach((i) => {
2503
+ e.has(i) || r.add(i);
2504
+ });
2505
+ }
2506
+ function Ut(e, t) {
2507
+ p(e).with({ type: u.union("triple", "property", "class", "general") }, (r) => {
2508
+ M(t, nt(r));
2509
+ }).with({ type: "filter" }, (r) => {
2510
+ M(t, T(r.expression));
2511
+ }).with({ type: "bind" }, (r) => {
2512
+ M(t, T(r.expression)), t.add(r.variable);
2513
+ }).with({ type: "skolem" }, (r) => {
2514
+ r.args.forEach((i) => M(t, T(i)));
2515
+ }).with({ type: "negation" }, (r) => {
2516
+ var s;
2517
+ const i = /* @__PURE__ */ new Set();
2518
+ r.formulas.forEach((a) => Ut(a, i)), (s = r.existentialVars) == null || s.forEach((a) => i.delete(a)), M(t, [...i]);
2519
+ }).with({ type: "aggregate" }, (r) => {
2520
+ var i, s;
2521
+ r.atoms.forEach((a) => Ut(a, t)), (i = r.onVars) == null || i.forEach((a) => t.add(a)), (s = r.bindings) == null || s.forEach((a) => {
2522
+ t.add(a.variable), a.expression !== "*" && M(t, T(a.expression)), a.secondExpression && M(t, T(a.secondExpression));
2523
+ });
2524
+ }).exhaustive();
2525
+ }
2526
+ function Lr(e, t) {
2527
+ p(e).with({ type: u.union("triple", "property", "class", "general") }, (r) => {
2528
+ M(t, nt(r));
2529
+ }).with({ type: "skolem" }, (r) => {
2530
+ const i = Zr(r);
2531
+ i && t.add(i);
2532
+ }).with({ type: u.union("bind", "filter", "negation", "aggregate") }, () => {
2533
+ }).exhaustive();
2534
+ }
2535
+ function wn(e, t, r, i) {
2536
+ F(r, T(t), i), r.add(e);
2537
+ }
2538
+ function Ur(e, t, r) {
2539
+ var o;
2540
+ const i = /* @__PURE__ */ new Set();
2541
+ e.atoms.forEach((l) => Lr(l, i));
2542
+ const s = e.onVars ?? [];
2543
+ s.forEach((l) => {
2544
+ t.has(l) && i.add(l);
2545
+ }), e.atoms.forEach((l) => Ar(l, i, r));
2546
+ const a = /* @__PURE__ */ new Set();
2547
+ e.atoms.forEach((l) => Ut(l, a)), s.forEach((l) => {
2548
+ a.has(l) && i.has(l) ? t.add(l) : r.add(l);
2549
+ }), (o = e.bindings) == null || o.forEach((l) => {
2550
+ l.expression !== "*" && F(i, T(l.expression), r), l.secondExpression && F(i, T(l.secondExpression), r), t.add(l.variable);
2551
+ });
2552
+ }
2553
+ function wr(e, t, r) {
2554
+ const i = new Set(t);
2555
+ M(i, e.existentialVars ?? []), e.formulas.forEach((s) => {
2556
+ p(s).with({ type: "aggregate" }, (a) => {
2557
+ var o;
2558
+ F(i, a.onVars ?? [], r), F(i, ((o = a.bindings) == null ? void 0 : o.map(({ variable: l }) => l)) ?? [], r), Ur(a, i, r);
2559
+ }).with({ type: "negation" }, (a) => {
2560
+ wr(a, i, r);
2561
+ }).otherwise((a) => {
2562
+ const o = /* @__PURE__ */ new Set();
2563
+ Ut(a, o), F(i, [...o], r);
2564
+ });
2565
+ });
2566
+ }
2567
+ function Ar(e, t, r) {
2568
+ p(e).with({ type: u.union("triple", "property", "class", "general") }, () => {
2569
+ }).with({ type: "filter" }, (i) => {
2570
+ F(t, T(i.expression), r);
2571
+ }).with({ type: "bind" }, (i) => {
2572
+ wn(i.variable, i.expression, t, r);
2573
+ }).with({ type: "skolem" }, (i) => {
2574
+ i.args.slice(0, -1).forEach((s) => F(t, T(s), r));
2575
+ }).with({ type: "negation" }, (i) => {
2576
+ wr(i, t, r);
2577
+ }).with({ type: "aggregate" }, (i) => {
2578
+ Ur(i, t, r);
2579
+ }).exhaustive();
2580
+ }
2581
+ function An(e) {
2582
+ const t = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Set();
2583
+ return e.body.forEach((i) => Lr(i, t)), e.body.forEach((i) => Ar(i, t, r)), e.head.forEach((i) => F(t, nt(i), r)), [...r].sort();
2584
+ }
2585
+ function Tr(e, t) {
2586
+ const r = t(e);
2587
+ return { ...Ce().visit(r), raw: e };
2588
+ }
2589
+ function Xe(e) {
2590
+ return Tr(e, cr);
2591
+ }
2592
+ function bs(e) {
2593
+ return { ...Tr(e, Mi), grounded: !0 };
2594
+ }
2595
+ function X(e) {
2596
+ return e !== void 0 && Number.isFinite(e) ? e : void 0;
2597
+ }
2598
+ function Tn(e) {
2599
+ const t = X(e.startOffset), r = X(e.endOffset);
2600
+ return { offset: t, endOffset: r === void 0 ? void 0 : r + 1 };
2601
+ }
2602
+ function Sr(e) {
2603
+ const t = be(e);
2604
+ if (t) return { ok: !1, issues: [t] };
2605
+ const r = Re(e);
2606
+ if (r.errors.length > 0)
2607
+ return {
2608
+ ok: !1,
2609
+ issues: r.errors.map((o) => ({
2610
+ message: o.message,
2611
+ line: X(o.line),
2612
+ column: X(o.column),
2613
+ offset: o.offset,
2614
+ endOffset: o.offset + o.length
2615
+ }))
2616
+ };
2617
+ const i = Oe(e, r.tokens);
2618
+ if (i) return { ok: !1, issues: [i] };
2619
+ const s = ve();
2620
+ s.input = r.tokens;
2621
+ const a = s.rule();
2622
+ if (s.errors.length > 0)
2623
+ return {
2624
+ ok: !1,
2625
+ issues: s.errors.map((o) => ({
2626
+ message: o.message,
2627
+ line: X(o.token.startLine),
2628
+ column: X(o.token.startColumn),
2629
+ ...Tn(o.token)
2630
+ }))
2631
+ };
2632
+ try {
2633
+ return { ok: !0, rule: { ...Ce().visit(a), raw: e } };
2634
+ } catch (o) {
2635
+ return {
2636
+ ok: !1,
2637
+ issues: [{ message: o instanceof Error ? o.message : "Invalid Datalog rule" }]
2638
+ };
2639
+ }
2640
+ }
2641
+ function Os(e) {
2642
+ const t = Sr(e);
2643
+ return t.ok ? { ok: !0, vocabulary: Vi(t.rule) } : t;
2644
+ }
2645
+ function Sn(e) {
2646
+ if (be(e)) return;
2647
+ const t = Re(e);
2648
+ if (t.errors.length > 0 || Oe(e, t.tokens)) return;
2649
+ const r = ve();
2650
+ r.input = t.tokens;
2651
+ const i = r.term();
2652
+ if (!(r.errors.length > 0 || !r.atEndOfInput))
2653
+ return Ce().visit(i);
2654
+ }
2655
+ function He(e) {
2656
+ const t = Sn(e), r = (t == null ? void 0 : t.type) === "iri" && !t.prefixed && !We(t.value);
2657
+ return t && !r ? t : void 0;
2658
+ }
2659
+ function xs(e, t) {
2660
+ const r = He(e), i = He(t);
2661
+ if (!(!r || !i))
2662
+ return tr(r, i);
2663
+ }
2664
+ function vs(e) {
2665
+ const t = Sr(e);
2666
+ if (!t.ok)
2667
+ return {
2668
+ valid: !1,
2669
+ error: t.issues.map(({ message: s }) => s).join("; ") || "Invalid Datalog rule"
2670
+ };
2671
+ const r = An(t.rule);
2672
+ return r.length === 0 ? { valid: !0 } : {
2673
+ valid: !1,
2674
+ error: `Unbound variables ${r.map((s) => `?${s}`).join(", ")}. Bind each variable with a body atom, BIND, AGGREGATE, or SKOLEM, or declare negation-local variables with NOT EXIST ?variable IN (...). AGGREGATE ON variables must also occur in the aggregate body.`
2675
+ };
2676
+ }
2677
+ function Cs(e, t) {
2678
+ try {
2679
+ const r = Xe(e), i = Xe(t);
2680
+ return r.head.length !== i.head.length ? !1 : Qe(e) === Qe(t);
2681
+ } catch {
2682
+ return !1;
2683
+ }
2684
+ }
2685
+ function Qe(e) {
2686
+ return e.replace(/\s+/g, " ").replace(/\s*([(),[\]])\s*/g, "$1").replace(/\s*:-\s*/g, ":-").trim();
2687
+ }
2688
+ export {
2689
+ wt as AGGREGATE,
2690
+ he as AND,
2691
+ K as AS,
2692
+ sr as AT,
2693
+ Xt as AVG,
2694
+ z as BIND,
2695
+ et as BLANK_NODE,
2696
+ mn as BaseDatalogVisitor,
2697
+ ar as COLON,
2698
+ N as COMMA,
2699
+ Ai as COMMENT,
2700
+ Zt as CONCAT,
2701
+ Gt as COUNT,
2702
+ Qt as COUNT_MAX,
2703
+ Ht as COUNT_MIN,
2704
+ Ae as DECIMAL,
2705
+ Ue as DEFAULT_NS_IRI,
2706
+ ut as DISTINCT,
2707
+ ge as DOT,
2708
+ Te as DOUBLE,
2709
+ Ln as DatalogAstBuilder,
2710
+ xe as DatalogParser,
2711
+ ae as EQUALS,
2712
+ fe as EXCLAMATION,
2713
+ Dt as EXISTS,
2714
+ vi as ExpandedDatalogParser,
2715
+ se as FALSE,
2716
+ $t as FILTER,
2717
+ ce as GREATER_THAN,
2718
+ pe as GREATER_THAN_OR_EQUAL,
2719
+ gt as HAT,
2720
+ rt as IDENTIFIER,
2721
+ te as IF,
2722
+ Z as IN,
2723
+ we as INTEGER,
2724
+ ye as INTERNAL_FUNCTION,
2725
+ ee as IRI,
2726
+ me as IRI_REF,
2727
+ Ne as LANGTAG,
2728
+ Et as LBRACKET,
2729
+ le as LESS_THAN,
2730
+ ue as LESS_THAN_OR_EQUAL,
2731
+ U as LPAREN,
2732
+ Vt as MAX,
2733
+ Yt as MAX_ARGMAX,
2734
+ Kt as MAX_ARGMIN,
2735
+ _t as MIN,
2736
+ ht as MINUS,
2737
+ Wt as MIN_ARGMAX,
2738
+ zt as MIN_ARGMIN,
2739
+ qt as MUL,
2740
+ lt as NOT,
2741
+ oe as NOT_EQUALS,
2742
+ At as ON,
2743
+ de as OR,
2744
+ pt as PLUS,
2745
+ st as PREFIXED_NAME,
2746
+ Tt as PREFIX_ONLY,
2747
+ ft as RBRACKET,
2748
+ ie as REGEX,
2749
+ re as ROUND,
2750
+ w as RPAREN,
2751
+ kt as RULE_ARROW,
2752
+ ct as SKOLEM,
2753
+ Ee as SLASH,
2754
+ dt as STAR,
2755
+ Jt as STR,
2756
+ mt as STRING_LITERAL,
2757
+ Se as STRING_LITERAL_LONG,
2758
+ jt as SUM,
2759
+ ne as TRUE,
2760
+ b as VARIABLE,
2761
+ Ti as WHITESPACE,
2762
+ lr as allTokens,
2763
+ Cs as areRulesEquivalent,
2764
+ nr as assertNoGroundedTargets,
2765
+ Ce as astBuilder,
2766
+ ps as atomToDatalogText,
2767
+ hn as beginTransaction,
2768
+ ei as binaryOperandNeedsParentheses,
2769
+ Ri as booleanLiteralTokenTypes,
2770
+ Ni as builtinFunctionTokenTypes,
2771
+ Ze as classAssertionFromAtom,
2772
+ Ns as collectVariableTypeEvidence,
2773
+ dn as commitTransaction,
2774
+ pn as createConnection,
2775
+ yi as datalogBodyToSparqlSelect,
2776
+ rr as datatypeToTermText,
2777
+ fn as deleteConnection,
2778
+ gs as delimiterTokenTypes,
2779
+ Ii as expandedParserInstance,
2780
+ ws as explainInferenceFailure,
2781
+ H as expressionToDatalogParts,
2782
+ hs as expressionToDatalogText,
2783
+ Os as extractRuleVocabulary,
2784
+ Vi as extractRuleVocabularyFromAst,
2785
+ hr as extractRuleVocabularyFromAtom,
2786
+ us as extractVariables,
2787
+ xt as formulaContainsSkolem,
2788
+ Yn as getAggregateFunction,
2789
+ zn as getAtomType,
2790
+ Wn as getExpressionType,
2791
+ cs as getRelatedVariables,
2792
+ Kn as getTermType,
2793
+ Pr as getVariablesFromAtom,
2794
+ kr as getVariablesFromAtomIncludingGraph,
2795
+ is as invertComparisonOperator,
2796
+ Ke as iriBodyCharClass,
2797
+ Es as iriTokenTypes,
2798
+ Vn as isAggregateFormula,
2799
+ ns as isBareNumericLiteral,
2800
+ qn as isBinaryExpression,
2801
+ _n as isBindFormula,
2802
+ Dn as isBlankNodeTerm,
2803
+ er as isBooleanLiteral,
2804
+ Fn as isClassAtom,
2805
+ rs as isComparisonOperator,
2806
+ Be as isDatalogAtom,
2807
+ Qr as isDateLiteral,
2808
+ zr as isDateTimeLiteral,
2809
+ Gn as isFilterFormula,
2810
+ We as isFullIri,
2811
+ Qn as isFunctionCallExpression,
2812
+ Pn as isGeneralAtom,
2813
+ kn as isIriTerm,
2814
+ tt as isLiteralTerm,
2815
+ Jn as isLogicalOperator,
2816
+ $n as isNegationFormula,
2817
+ Q as isNumericLiteral,
2818
+ ss as isNumericLiteralTerm,
2819
+ Zn as isNumericOperator,
2820
+ Rt as isNumericRdfValue,
2821
+ Bn as isPropertyAtom,
2822
+ ts as isQueryableTermIri,
2823
+ As as isReadOnlySparqlQuery,
2824
+ jn as isSkolemFormula,
2825
+ Hn as isTermExpression,
2826
+ Mn as isTripleAtom,
2827
+ Xn as isUnaryExpression,
2828
+ I as isVariableTerm,
2829
+ it as isXsdDatatype,
2830
+ Si as keywordTokenTypes,
2831
+ ls as literalSetComparisonFromExpression,
2832
+ as as literalToDisplayText,
2833
+ ds as numericLiteralTokenTypes,
2834
+ fs as operatorTokenTypes,
2835
+ es as parseBooleanLiteral,
2836
+ Xe as parseDatalogRule,
2837
+ Sr as parseDatalogRuleWithIssues,
2838
+ Sn as parseDatalogTermText,
2839
+ bs as parseGroundedDatalogRule,
2840
+ Mi as parseGroundedRule,
2841
+ cr as parseRule,
2842
+ ur as parseRuleWith,
2843
+ ve as parserInstance,
2844
+ Xr as plainDecimalText,
2845
+ Ye as positiveBodyContainsSkolem,
2846
+ Je as propertyAssertionFromAtom,
2847
+ Rs as resolveVariableTypes,
2848
+ En as rollbackTransaction,
2849
+ Kr as simpleComparisonFromExpression,
2850
+ os as simpleComparisonFromFilter,
2851
+ Zr as skolemMintedVariable,
2852
+ bi as stringLiteralTokenTypes,
2853
+ xs as termTextsEqual,
2854
+ x as termToDatalogText,
2855
+ Ls as termToSparql,
2856
+ ms as termTokenTypes,
2857
+ tr as termsEqual,
2858
+ Re as tokenizeDatalog,
2859
+ ri as unaryOperandNeedsParentheses,
2860
+ G as unwrapTermExpression,
2861
+ Ts as validateDataManipulationUpdate,
2862
+ vs as validateDatalogRule,
2863
+ ys as validateRuleSyntax,
2864
+ sn as validateSparqlQuery,
2865
+ Yr as variableNameFromTermExpression,
2866
+ nt as variableNamesFromAtom,
2867
+ T as variableNamesFromExpression,
2868
+ Us as verifyRuleInference,
2869
+ Ss as withTransaction,
2870
+ j as xsdDatatypes
2871
+ };