eyemind 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,808 @@
1
+ /**
2
+ * eyemind: RDF terms and shared utilities
3
+ *
4
+ * Core data model and shared utilities: Term/Triple/Formula types, namespaces,
5
+ * and prefix environment helpers used throughout the project.
6
+ */
7
+
8
+
9
+ // ===========================================================================
10
+ // Namespace constants
11
+ // ===========================================================================
12
+
13
+ const RDF_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
14
+ const RDFS_NS = 'http://www.w3.org/2000/01/rdf-schema#';
15
+ const OWL_NS = 'http://www.w3.org/2002/07/owl#';
16
+ const XSD_NS = 'http://www.w3.org/2001/XMLSchema#';
17
+ const CRYPTO_NS = 'http://www.w3.org/2000/10/swap/crypto#';
18
+ const MATH_NS = 'http://www.w3.org/2000/10/swap/math#';
19
+ const TIME_NS = 'http://www.w3.org/2000/10/swap/time#';
20
+ const LIST_NS = 'http://www.w3.org/2000/10/swap/list#';
21
+ const LOG_NS = 'http://www.w3.org/2000/10/swap/log#';
22
+ const STRING_NS = 'http://www.w3.org/2000/10/swap/string#';
23
+ const DT_NS = 'https://eyereasoner.github.io/eyeling/datatype#';
24
+ const SKOLEM_NS = 'https://eyereasoner.github.io/.well-known/genid/';
25
+ const RDF_JSON_DT = RDF_NS + 'JSON';
26
+
27
+ // Private rule-lifting variable prefix used for blank nodes that appear in
28
+ // rule-body patterns. The prefix is intentionally not spellable in N3 input,
29
+ // but public extension APIs should present these variables with stable,
30
+ // ordinary names and translate them back internally.
31
+ const INTERNAL_BLANK_VAR_PREFIX = '\uE000eyeling_b';
32
+
33
+ function isInternalBlankVarName(name) {
34
+ return typeof name === 'string' && name.startsWith(INTERNAL_BLANK_VAR_PREFIX);
35
+ }
36
+
37
+ function internalBlankVarSuffix(name) {
38
+ if (!isInternalBlankVarName(name)) return '';
39
+ return name.slice(INTERNAL_BLANK_VAR_PREFIX.length);
40
+ }
41
+
42
+ function parseUriReferenceForResolution(uri) {
43
+ // RFC 3986 Appendix B-style component parser, with the scheme tightened to
44
+ // the RFC scheme grammar. Capturing delimiter presence matters: `?` with an
45
+ // empty query is defined, while no `?` means undefined.
46
+ const m = /^(([A-Za-z][A-Za-z0-9+.-]*):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/u.exec(String(uri));
47
+ if (!m) return null;
48
+ return {
49
+ scheme: m[2] !== undefined ? m[2] : undefined,
50
+ authority: m[4] !== undefined ? m[4] : undefined,
51
+ path: m[5] || '',
52
+ query: m[6] !== undefined ? (m[7] || '') : undefined,
53
+ fragment: m[8] !== undefined ? (m[9] || '') : undefined,
54
+ };
55
+ }
56
+
57
+ function recomposeUriReference(parts) {
58
+ let out = '';
59
+ if (parts.scheme !== undefined) out += `${parts.scheme}:`;
60
+ if (parts.authority !== undefined) out += `//${parts.authority}`;
61
+ out += parts.path || '';
62
+ if (parts.query !== undefined) out += `?${parts.query}`;
63
+ if (parts.fragment !== undefined) out += `#${parts.fragment}`;
64
+ return out;
65
+ }
66
+
67
+ function removeLastPathSegment(path) {
68
+ if (!path) return '';
69
+ const i = path.lastIndexOf('/');
70
+ if (i < 0) return '';
71
+ if (i === 0) return '';
72
+ return path.slice(0, i);
73
+ }
74
+
75
+ function removeDotSegments(path) {
76
+ // eyemind: use RFC 3986 section 5.2.4 instead of WHATWG URL parsing to
77
+ // preserve IRI spelling (for example, do not add a trailing
78
+ // slash to `http://example.org`) while still normalizing `.` and `..` path
79
+ // segments as required by section 5.2.2.
80
+ let input = String(path || '');
81
+ let output = '';
82
+
83
+ while (input.length > 0) {
84
+ if (input.startsWith('../')) {
85
+ input = input.slice(3);
86
+ } else if (input.startsWith('./')) {
87
+ input = input.slice(2);
88
+ } else if (input.startsWith('/./')) {
89
+ input = `/${input.slice(3)}`;
90
+ } else if (input === '/.') {
91
+ input = '/';
92
+ } else if (input.startsWith('/../')) {
93
+ input = `/${input.slice(4)}`;
94
+ output = removeLastPathSegment(output);
95
+ } else if (input === '/..') {
96
+ input = '/';
97
+ output = removeLastPathSegment(output);
98
+ } else if (input === '.' || input === '..') {
99
+ input = '';
100
+ } else {
101
+ let segmentEnd;
102
+ if (input[0] === '/') {
103
+ segmentEnd = input.indexOf('/', 1);
104
+ } else {
105
+ segmentEnd = input.indexOf('/');
106
+ }
107
+
108
+ if (segmentEnd < 0) {
109
+ output += input;
110
+ input = '';
111
+ } else {
112
+ output += input.slice(0, segmentEnd);
113
+ input = input.slice(segmentEnd);
114
+ }
115
+ }
116
+ }
117
+
118
+ return output;
119
+ }
120
+
121
+ function mergePaths(base, refPath) {
122
+ if (base.authority !== undefined && base.path === '') {
123
+ return `/${refPath}`;
124
+ }
125
+ const i = base.path.lastIndexOf('/');
126
+ if (i < 0) return refPath;
127
+ return `${base.path.slice(0, i + 1)}${refPath}`;
128
+ }
129
+
130
+ function resolveIriRef(ref, base) {
131
+ const r = parseUriReferenceForResolution(ref);
132
+ if (!r) return ref;
133
+
134
+ const baseParts = base ? parseUriReferenceForResolution(base) : null;
135
+
136
+ // Absolute references do not need a base, but RFC 3986 section 5.2.2 still
137
+ // applies remove_dot_segments(R.path) when R.scheme is defined.
138
+ if (r.scheme !== undefined) {
139
+ return recomposeUriReference({
140
+ scheme: r.scheme,
141
+ authority: r.authority,
142
+ path: removeDotSegments(r.path),
143
+ query: r.query,
144
+ fragment: r.fragment,
145
+ });
146
+ }
147
+
148
+ // Without a usable base, preserve relative references as written.
149
+ if (!baseParts || baseParts.scheme === undefined) return ref;
150
+
151
+ const t = {
152
+ scheme: baseParts.scheme,
153
+ authority: undefined,
154
+ path: '',
155
+ query: undefined,
156
+ fragment: r.fragment,
157
+ };
158
+
159
+ if (r.authority !== undefined) {
160
+ t.authority = r.authority;
161
+ t.path = removeDotSegments(r.path);
162
+ t.query = r.query;
163
+ } else if (r.path === '') {
164
+ t.authority = baseParts.authority;
165
+ t.path = baseParts.path;
166
+ t.query = r.query !== undefined ? r.query : baseParts.query;
167
+ } else {
168
+ t.authority = baseParts.authority;
169
+ if (r.path.startsWith('/')) {
170
+ t.path = removeDotSegments(r.path);
171
+ } else {
172
+ t.path = removeDotSegments(mergePaths(baseParts, r.path));
173
+ }
174
+ t.query = r.query;
175
+ }
176
+
177
+ return recomposeUriReference(t);
178
+ }
179
+
180
+ // -----------------------------------------------------------------------------
181
+ // Literal helpers
182
+ // -----------------------------------------------------------------------------
183
+
184
+ // Hot cache used by literalParts().
185
+ const MAX_LITERAL_PARTS_CACHE_LEN = 1024;
186
+
187
+ const __literalPartsCache = new Map(); // lit string -> [lex, dt]
188
+
189
+ function quotedLiteralEndIndex(str) {
190
+ if (typeof str !== 'string' || str.length < 2) return -1;
191
+
192
+ const quote = str[0];
193
+ if (quote !== '"' && quote !== "'") return -1;
194
+
195
+ const delimLen = str.startsWith(quote.repeat(3)) ? 3 : 1;
196
+ const delim = quote.repeat(delimLen);
197
+
198
+ let i = delimLen;
199
+ while (i < str.length) {
200
+ // Stored literals may contain escaped quotes, e.g. \"...\"^^xsd:dateTime
201
+ // inside a plain string. Those must not terminate the outer lexical form.
202
+ if (str[i] === '\\') {
203
+ i += 2;
204
+ continue;
205
+ }
206
+
207
+ if (delimLen === 1) {
208
+ if (str[i] === quote) return i + 1;
209
+ i += 1;
210
+ continue;
211
+ }
212
+
213
+ if (str.startsWith(delim, i)) return i + delimLen;
214
+ i += 1;
215
+ }
216
+
217
+ return -1;
218
+ }
219
+
220
+ function literalParts(lit) {
221
+ // Avoid caching extremely large literals (notably huge numeric intermediates)
222
+ // to prevent unbounded memory growth.
223
+ const useCache = typeof lit === 'string' && lit.length <= MAX_LITERAL_PARTS_CACHE_LEN;
224
+
225
+ if (useCache) {
226
+ const cached = __literalPartsCache.get(lit);
227
+ if (cached) return cached;
228
+ }
229
+
230
+ // Split a literal into lexical form and datatype IRI (if any).
231
+ // Also strip an optional language tag from the lexical form:
232
+ // "\"hello\"@en" -> "\"hello\""
233
+ // "\"hello\"@en^^<...>" is rejected earlier in the parser.
234
+ let lex = lit;
235
+ let dt = null;
236
+
237
+ const lexEnd = quotedLiteralEndIndex(lit);
238
+ if (lexEnd > 0 && lit.startsWith('^^', lexEnd)) {
239
+ lex = lit.slice(0, lexEnd);
240
+ dt = lit.slice(lexEnd + 2);
241
+ if (dt.startsWith('<') && dt.endsWith('>')) {
242
+ dt = dt.slice(1, -1);
243
+ }
244
+ }
245
+
246
+ // Strip LANGTAG from the lexical form when present.
247
+ const langLexEnd = quotedLiteralEndIndex(lex);
248
+ if (langLexEnd > 0 && lex[0] === '"' && langLexEnd < lex.length && lex[langLexEnd] === '@') {
249
+ const lang = lex.slice(langLexEnd + 1);
250
+ if (/^[A-Za-z]+(?:-[A-Za-z0-9]+)*$/.test(lang)) {
251
+ lex = lex.slice(0, langLexEnd);
252
+ }
253
+ }
254
+
255
+ const res = [lex, dt];
256
+ if (useCache) __literalPartsCache.set(lit, res);
257
+ return res;
258
+ }
259
+
260
+ // -----------------------------------------------------------------------------
261
+ // Global stable term IDs (performance)
262
+ // -----------------------------------------------------------------------------
263
+ // A small integer ID is assigned per *value-based* key, and stored on each term
264
+ // as non-enumerable property `__tid`. This enables cheaper indexing and
265
+ // equality fast-paths than repeated string key construction.
266
+
267
+ let __nextTid = 1;
268
+ const __tidIntern = new Map(); // legacy generic key -> number
269
+ const __iriTidIntern = new Map(); // IRI value -> number
270
+ const __blankTidIntern = new Map(); // blank label -> number
271
+ const __literalTidIntern = new Map(); // normalized literal lexical form -> number
272
+
273
+ // Avoid storing extremely large literal keys in the global term-id intern map.
274
+ // For huge literals we still assign a unique __tid, but we do not intern the key.
275
+ const MAX_LITERAL_TID_LEN = 1024;
276
+
277
+ function __getTidFromMap(map, key) {
278
+ let id = map.get(key);
279
+ if (!id) {
280
+ id = __nextTid++;
281
+ map.set(key, id);
282
+ }
283
+ return id;
284
+ }
285
+
286
+ function __getTid(key) {
287
+ return __getTidFromMap(__tidIntern, key);
288
+ }
289
+
290
+ function __getIriTid(value) {
291
+ return __getTidFromMap(__iriTidIntern, value);
292
+ }
293
+
294
+ function __getBlankTid(label) {
295
+ return __getTidFromMap(__blankTidIntern, label);
296
+ }
297
+
298
+ function __getLiteralTid(norm) {
299
+ return __getTidFromMap(__literalTidIntern, norm);
300
+ }
301
+
302
+ function __isQuotedLexical(lit) {
303
+ if (typeof lit !== 'string') return false;
304
+ if (lit.length >= 6) {
305
+ if (lit.startsWith('"""') && lit.endsWith('"""')) return true;
306
+ if (lit.startsWith("'''") && lit.endsWith("'''")) return true;
307
+ }
308
+ if (lit.length >= 2) {
309
+ const a = lit[0];
310
+ const b = lit[lit.length - 1];
311
+ if ((a === '"' && b === '"') || (a === "'" && b === "'")) return true;
312
+ }
313
+ return false;
314
+ }
315
+
316
+ function __literalHasLangTag(lit) {
317
+ if (typeof lit !== 'string' || !__isQuotedLexical(lit)) return false;
318
+ let end = -1;
319
+ let qlen = 1;
320
+ if (lit.startsWith('"""')) {
321
+ end = lit.lastIndexOf('"""');
322
+ qlen = 3;
323
+ } else if (lit.startsWith("'''")) {
324
+ end = lit.lastIndexOf("'''");
325
+ qlen = 3;
326
+ } else {
327
+ end = lit.lastIndexOf(lit[0]);
328
+ qlen = 1;
329
+ }
330
+ if (end < 0) return false;
331
+ const after = lit.slice(end + qlen);
332
+ if (!after.startsWith('@')) return false;
333
+ const lang = after.slice(1);
334
+ return /^[A-Za-z]+(?:-[A-Za-z0-9]+)*$/.test(lang);
335
+ }
336
+
337
+ function __isPlainStringLiteralValue(lit) {
338
+ if (typeof lit !== 'string') return false;
339
+ if (lit.indexOf('^^') >= 0) return false;
340
+ if (!__isQuotedLexical(lit)) return false;
341
+ return !__literalHasLangTag(lit);
342
+ }
343
+
344
+ function normalizeLiteralForTid(lit) {
345
+ // Canonicalize so that plain string and explicit xsd:string share the same id.
346
+ if (typeof lit !== 'string') return lit;
347
+
348
+ // Fast path for the overwhelmingly common lexer output for plain string
349
+ // literals: a canonical JSON-style quoted lexical form with no suffix.
350
+ // This avoids literalParts()/language-tag parsing for large fact tables.
351
+ if (lit.length >= 2 && lit.charCodeAt(0) === 34 && lit.charCodeAt(lit.length - 1) === 34 && lit.indexOf('^^') < 0) {
352
+ return `${lit}^^<${XSD_NS}string>`;
353
+ }
354
+
355
+ const [lex, dt] = literalParts(lit);
356
+ if (dt === XSD_NS + 'string') return `${lex}^^<${XSD_NS}string>`;
357
+ if (dt === null && __isPlainStringLiteralValue(lit)) return `${lex}^^<${XSD_NS}string>`;
358
+ return lit;
359
+ }
360
+
361
+ // ===========================================================================
362
+ // AST (Abstract Syntax Tree)
363
+ // ===========================================================================
364
+
365
+ class Term {}
366
+
367
+ class Iri extends Term {
368
+ constructor(value) {
369
+ super();
370
+ this.value = value;
371
+ Object.defineProperty(this, '__tid', {
372
+ value: __getIriTid(value),
373
+ enumerable: false,
374
+ });
375
+ }
376
+ }
377
+
378
+ class Literal extends Term {
379
+ constructor(value) {
380
+ super();
381
+ this.value = value; // raw lexical form, e.g. "foo", 12, true, or "\"1944-08-21\"^^..."
382
+ const norm = normalizeLiteralForTid(value);
383
+ const useIntern = typeof norm === 'string' && norm.length <= MAX_LITERAL_TID_LEN;
384
+ const tid = useIntern ? __getLiteralTid(norm) : __nextTid++;
385
+ Object.defineProperty(this, '__tid', {
386
+ value: tid,
387
+ enumerable: false,
388
+ });
389
+ }
390
+ }
391
+
392
+ class Var extends Term {
393
+ constructor(name) {
394
+ super();
395
+ this.name = name; // without leading '?'
396
+ }
397
+ }
398
+
399
+ class Blank extends Term {
400
+ constructor(label, blankNodeKind = 'labeled') {
401
+ super();
402
+ this.label = label; // _:b1, etc.
403
+ // eyemind: log:rawType distinguishes source-labeled blank nodes (_:name)
404
+ // from unlabeled blank nodes introduced by N3 syntax such as [] / [...].
405
+ this.blankNodeKind = blankNodeKind === 'unlabeled' ? 'unlabeled' : 'labeled';
406
+ Object.defineProperty(this, '__tid', {
407
+ value: __getBlankTid(label),
408
+ enumerable: false,
409
+ });
410
+ }
411
+ }
412
+
413
+ class ListTerm extends Term {
414
+ constructor(elems) {
415
+ super();
416
+ this.elems = elems; // Term[]
417
+ }
418
+ }
419
+
420
+ class OpenListTerm extends Term {
421
+ constructor(prefix, tailVar) {
422
+ super();
423
+ this.prefix = prefix; // Term[]
424
+ this.tailVar = tailVar; // string
425
+ }
426
+ }
427
+
428
+ class GraphTerm extends Term {
429
+ constructor(triples) {
430
+ super();
431
+ this.triples = triples; // Triple[]
432
+ }
433
+ }
434
+
435
+ class Triple {
436
+ constructor(s, p, o) {
437
+ this.s = s;
438
+ this.p = p;
439
+ this.o = o;
440
+ }
441
+ }
442
+
443
+ class Rule {
444
+ constructor(premise, conclusion, isForward, isFuse, headBlankLabels) {
445
+ this.premise = premise; // Triple[]
446
+ this.conclusion = conclusion; // Triple[]
447
+ this.isForward = isForward; // boolean
448
+ this.isFuse = isFuse; // boolean
449
+ // Set<string> of blank-node labels that occur explicitly in the rule head
450
+ this.headBlankLabels = headBlankLabels || new Set();
451
+ }
452
+ }
453
+
454
+ class DerivedFact {
455
+ constructor(fact, rule, premises, subst) {
456
+ this.fact = fact; // Triple
457
+ this.rule = rule; // Rule
458
+ this.premises = premises; // Triple[]
459
+ this.subst = subst; // { varName: Term }
460
+ }
461
+ }
462
+
463
+ // ===========================================================================
464
+ // Term interning
465
+ // ===========================================================================
466
+
467
+ // Intern IRIs and literals by their raw lexical string.
468
+ // This reduces allocations when the same terms repeat and can improve performance.
469
+ //
470
+ // NOTE: Terms are treated as immutable. Do NOT mutate .value on interned objects.
471
+ const __iriIntern = new Map();
472
+ const __literalIntern = new Map();
473
+
474
+ // Do not intern extremely large literal strings (e.g., huge numeric intermediates).
475
+ // Interning them creates global strong references that prevent GC.
476
+ const MAX_LITERAL_INTERN_LEN = 1024;
477
+
478
+ /** @param {string} value */
479
+ function internIri(value) {
480
+ let t = __iriIntern.get(value);
481
+ if (!t) {
482
+ t = new Iri(value);
483
+ __iriIntern.set(value, t);
484
+ }
485
+ return t;
486
+ }
487
+
488
+ /** @param {string} value */
489
+ function internLiteral(value) {
490
+ if (typeof value === 'string' && value.length > MAX_LITERAL_INTERN_LEN) {
491
+ // Skip global interning for huge literals to avoid retaining them forever.
492
+ return new Literal(value);
493
+ }
494
+ let t = __literalIntern.get(value);
495
+ if (!t) {
496
+ t = new Literal(value);
497
+ __literalIntern.set(value, t);
498
+ }
499
+ return t;
500
+ }
501
+
502
+ // ===========================================================================
503
+ // Special predicate helpers (kept here because PrefixEnv needs them)
504
+ // ===========================================================================
505
+
506
+ function isRdfTypePred(p) {
507
+ return p instanceof Iri && p.value === RDF_NS + 'type';
508
+ }
509
+
510
+ function isOwlSameAsPred(p) {
511
+ return p instanceof Iri && p.value === OWL_NS + 'sameAs';
512
+ }
513
+
514
+ function isLogImplies(p) {
515
+ return p instanceof Iri && p.value === LOG_NS + 'implies';
516
+ }
517
+
518
+ function isLogImpliedBy(p) {
519
+ return p instanceof Iri && p.value === LOG_NS + 'impliedBy';
520
+ }
521
+
522
+ function isLogQuery(p) {
523
+ return p instanceof Iri && p.value === LOG_NS + 'query';
524
+ }
525
+
526
+ // ===========================================================================
527
+ // PREFIX ENVIRONMENT
528
+ // ===========================================================================
529
+
530
+ // Conservative check for whether a candidate local part can be safely serialized as a prefixed name.
531
+ // If false, we fall back to <IRI> to guarantee syntactically valid N3/Turtle output.
532
+ function isValidQNameLocal(local) {
533
+ if (typeof local !== 'string' || local.length === 0) return false;
534
+ // Disallow characters that would break PN_LOCAL unless escaped (we keep this conservative).
535
+ if (/[#:/?\s]/.test(local)) return false;
536
+ // Allow a safe ASCII subset.
537
+ if (/[^A-Za-z0-9._-]/.test(local)) return false;
538
+ // Avoid edge cases that typically require escaping.
539
+ if (local.endsWith('.')) return false;
540
+ if (/^[.-]/.test(local)) return false;
541
+ return true;
542
+ }
543
+
544
+ class PrefixEnv {
545
+ constructor(map, baseIri) {
546
+ this.map = map || {}; // prefix -> IRI (including "" for @prefix :)
547
+ this.baseIri = baseIri || ''; // base IRI for resolving <relative>
548
+ }
549
+
550
+ static newDefault() {
551
+ const m = {};
552
+ m['rdf'] = RDF_NS;
553
+ m['rdfs'] = RDFS_NS;
554
+ m['xsd'] = XSD_NS;
555
+ m['log'] = LOG_NS;
556
+ m['math'] = MATH_NS;
557
+ m['string'] = STRING_NS;
558
+ m['list'] = LIST_NS;
559
+ m['time'] = TIME_NS;
560
+ m['dt'] = DT_NS;
561
+ m['genid'] = SKOLEM_NS;
562
+ m[''] = ''; // empty prefix default namespace
563
+ return new PrefixEnv(m, ''); // base IRI starts empty
564
+ }
565
+
566
+ // shrinkIri and prefixesUsedForOutput run once per IRI of output, and both used
567
+ // to rebuild Object.entries(this.map) on every call. These caches hold the
568
+ // entry list and the per-IRI answer instead; every write to the map goes
569
+ // through set(), so invalidating there is enough.
570
+ __invalidatePrefixCaches() {
571
+ this.__entries = null;
572
+ this.__shrinkCache = null;
573
+ }
574
+
575
+ __nonEmptyEntries() {
576
+ if (!this.__entries) this.__entries = Object.entries(this.map).filter(([, base]) => !!base);
577
+ return this.__entries;
578
+ }
579
+
580
+ set(pref, base) {
581
+ this.map[pref] = base;
582
+ this.__invalidatePrefixCaches();
583
+ }
584
+
585
+ setBase(baseIri) {
586
+ this.baseIri = baseIri || '';
587
+ }
588
+
589
+ expandQName(q) {
590
+ const sep = typeof q === 'string' ? q.indexOf(':') : -1;
591
+ if (sep >= 0) {
592
+ const p = q.slice(0, sep);
593
+ const local = q.slice(sep + 1);
594
+ const base = this.map[p] || '';
595
+ if (base) return base + local;
596
+ return q;
597
+ }
598
+ return q;
599
+ }
600
+
601
+ shrinkIri(iri) {
602
+ if (!this.__shrinkCache) this.__shrinkCache = new Map();
603
+ const cached = this.__shrinkCache.get(iri);
604
+ if (cached !== undefined) return cached;
605
+ const out = this.__shrinkIriUncached(iri);
606
+ this.__shrinkCache.set(iri, out);
607
+ return out;
608
+ }
609
+
610
+ __shrinkIriUncached(iri) {
611
+ let best = null; // [prefix, local]
612
+ for (const [p, base] of this.__nonEmptyEntries()) {
613
+ if (iri.startsWith(base)) {
614
+ const local = iri.slice(base.length);
615
+ if (!local) continue;
616
+ // Only emit a QName when the local part is safe to serialize without escaping.
617
+ if (!isValidQNameLocal(local)) continue;
618
+ const cand = [p, local];
619
+ if (best === null || cand[1].length < best[1].length) best = cand;
620
+ }
621
+ }
622
+ if (best === null) return null;
623
+ const [p, local] = best;
624
+ if (p === '') return `:${local}`;
625
+ return `${p}:${local}`;
626
+ }
627
+
628
+ prefixesUsedForOutput(triples) {
629
+ const used = new Set();
630
+ const entries = this.__nonEmptyEntries();
631
+ // One accumulator reused across every term, and stop the moment every prefix
632
+ // is accounted for: the answer cannot grow after that.
633
+ const iris = [];
634
+ for (const t of triples) {
635
+ if (used.size === entries.length) break;
636
+ iris.length = 0;
637
+ collectIrisInTerm(t.s, iris);
638
+ if (!isRdfTypePred(t.p)) {
639
+ collectIrisInTerm(t.p, iris);
640
+ }
641
+ collectIrisInTerm(t.o, iris);
642
+ for (const iri of iris) {
643
+ for (const [p, base] of entries) {
644
+ if (iri.startsWith(base)) used.add(p);
645
+ }
646
+ }
647
+ }
648
+ const v = [];
649
+ for (const p of used) {
650
+ if (Object.prototype.hasOwnProperty.call(this.map, p)) v.push([p, this.map[p]]);
651
+ }
652
+ v.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
653
+ return v;
654
+ }
655
+ }
656
+
657
+ // out is optional so the old "returns a fresh array" contract still holds, but
658
+ // callers in a loop can pass one accumulator instead of allocating per term.
659
+ function collectIrisInTerm(t, out = []) {
660
+ if (t instanceof Iri) {
661
+ out.push(t.value);
662
+ } else if (t instanceof Literal) {
663
+ const [, dt] = literalParts(t.value);
664
+ if (dt) out.push(dt); // so rdf/xsd prefixes are emitted when only used in ^^...
665
+ } else if (t instanceof ListTerm) {
666
+ for (const x of t.elems) collectIrisInTerm(x, out);
667
+ } else if (t instanceof OpenListTerm) {
668
+ for (const x of t.prefix) collectIrisInTerm(x, out);
669
+ } else if (t instanceof GraphTerm) {
670
+ for (const tr of t.triples) {
671
+ collectIrisInTerm(tr.s, out);
672
+ collectIrisInTerm(tr.p, out);
673
+ collectIrisInTerm(tr.o, out);
674
+ }
675
+ }
676
+ return out;
677
+ }
678
+
679
+ function collectVarsInTerm(t, acc) {
680
+ if (t instanceof Var) {
681
+ acc.add(t.name);
682
+ } else if (t instanceof ListTerm) {
683
+ for (const x of t.elems) collectVarsInTerm(x, acc);
684
+ } else if (t instanceof OpenListTerm) {
685
+ for (const x of t.prefix) collectVarsInTerm(x, acc);
686
+ acc.add(t.tailVar);
687
+ } else if (t instanceof GraphTerm) {
688
+ for (const tr of t.triples) {
689
+ collectVarsInTerm(tr.s, acc);
690
+ collectVarsInTerm(tr.p, acc);
691
+ collectVarsInTerm(tr.o, acc);
692
+ }
693
+ }
694
+ }
695
+
696
+ function varsInRule(rule) {
697
+ const acc = new Set();
698
+ for (const tr of rule.premise) {
699
+ collectVarsInTerm(tr.s, acc);
700
+ collectVarsInTerm(tr.p, acc);
701
+ collectVarsInTerm(tr.o, acc);
702
+ }
703
+ for (const tr of rule.conclusion) {
704
+ collectVarsInTerm(tr.s, acc);
705
+ collectVarsInTerm(tr.p, acc);
706
+ collectVarsInTerm(tr.o, acc);
707
+ }
708
+ return acc;
709
+ }
710
+
711
+ function collectBlankLabelsInTerm(t, acc) {
712
+ if (t instanceof Blank) {
713
+ acc.add(t.label);
714
+ } else if (t instanceof ListTerm) {
715
+ for (const x of t.elems) collectBlankLabelsInTerm(x, acc);
716
+ } else if (t instanceof OpenListTerm) {
717
+ for (const x of t.prefix) collectBlankLabelsInTerm(x, acc);
718
+ } else if (t instanceof GraphTerm) {
719
+ for (const tr of t.triples) {
720
+ collectBlankLabelsInTerm(tr.s, acc);
721
+ collectBlankLabelsInTerm(tr.p, acc);
722
+ collectBlankLabelsInTerm(tr.o, acc);
723
+ }
724
+ }
725
+ }
726
+
727
+ function collectBlankLabelsInTriples(triples) {
728
+ const acc = new Set();
729
+ for (const tr of triples) {
730
+ collectBlankLabelsInTerm(tr.s, acc);
731
+ collectBlankLabelsInTerm(tr.p, acc);
732
+ collectBlankLabelsInTerm(tr.o, acc);
733
+ }
734
+ return acc;
735
+ }
736
+
737
+ function annotateQuotedGraphTerm(graph) {
738
+ if (!(graph instanceof GraphTerm)) return graph;
739
+ const labels = collectBlankLabelsInTriples(graph.triples);
740
+ Object.defineProperty(graph, '__quotedLocalBlankLabels', {
741
+ value: labels,
742
+ enumerable: false,
743
+ writable: true,
744
+ configurable: true,
745
+ });
746
+ return graph;
747
+ }
748
+
749
+ function copyQuotedGraphMetadata(src, dst) {
750
+ if (!(src instanceof GraphTerm) || !(dst instanceof GraphTerm)) return dst;
751
+ if (!Object.prototype.hasOwnProperty.call(src, '__quotedLocalBlankLabels')) return dst;
752
+
753
+ const labels = src.__quotedLocalBlankLabels;
754
+ Object.defineProperty(dst, '__quotedLocalBlankLabels', {
755
+ value: labels instanceof Set ? new Set(labels) : labels,
756
+ enumerable: false,
757
+ writable: true,
758
+ configurable: true,
759
+ });
760
+ return dst;
761
+ }
762
+
763
+ export {
764
+ RDF_NS,
765
+ RDFS_NS,
766
+ OWL_NS,
767
+ XSD_NS,
768
+ CRYPTO_NS,
769
+ MATH_NS,
770
+ TIME_NS,
771
+ LIST_NS,
772
+ LOG_NS,
773
+ STRING_NS,
774
+ DT_NS,
775
+ SKOLEM_NS,
776
+ RDF_JSON_DT,
777
+ INTERNAL_BLANK_VAR_PREFIX,
778
+ isInternalBlankVarName,
779
+ internalBlankVarSuffix,
780
+ resolveIriRef,
781
+ literalParts,
782
+ normalizeLiteralForTid,
783
+ MAX_LITERAL_TID_LEN,
784
+ Term,
785
+ Iri,
786
+ Literal,
787
+ Var,
788
+ Blank,
789
+ ListTerm,
790
+ OpenListTerm,
791
+ GraphTerm,
792
+ Triple,
793
+ Rule,
794
+ DerivedFact,
795
+ internIri,
796
+ internLiteral,
797
+ isRdfTypePred,
798
+ isOwlSameAsPred,
799
+ isLogImplies,
800
+ isLogImpliedBy,
801
+ isLogQuery,
802
+ PrefixEnv,
803
+ collectIrisInTerm,
804
+ varsInRule,
805
+ collectBlankLabelsInTriples,
806
+ annotateQuotedGraphTerm,
807
+ copyQuotedGraphMetadata,
808
+ };