@dxos/echo-memory 0.0.0-stage → 0.0.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.
Files changed (147) hide show
  1. package/LICENSE +105 -0
  2. package/dist/lib/Fact.mjs +1 -0
  3. package/dist/lib/FactFeed.mjs +1 -0
  4. package/dist/lib/Graph.mjs +1 -0
  5. package/dist/lib/Hash.mjs +1 -0
  6. package/dist/lib/Mapping.mjs +1 -0
  7. package/dist/lib/MemoryError.mjs +1 -0
  8. package/dist/lib/MemoryQuery.mjs +1 -0
  9. package/dist/lib/MemoryService.mjs +1 -0
  10. package/dist/lib/Ontology.mjs +1 -0
  11. package/dist/lib/Pipeline.mjs +1 -0
  12. package/dist/lib/Predicate.mjs +1 -0
  13. package/dist/lib/Rdf.mjs +1 -0
  14. package/dist/lib/RdfStore.mjs +1 -0
  15. package/dist/lib/Sparql.mjs +1 -0
  16. package/dist/lib/Subscription.mjs +1 -0
  17. package/dist/lib/Trig.mjs +1 -0
  18. package/dist/lib/Vocab.mjs +1 -0
  19. package/dist/lib/Vocabularies.mjs +1 -0
  20. package/dist/lib/chunk-Fact.mjs +245 -0
  21. package/dist/lib/chunk-Fact.mjs.map +1 -0
  22. package/dist/lib/chunk-FactFeed.mjs +29 -0
  23. package/dist/lib/chunk-FactFeed.mjs.map +1 -0
  24. package/dist/lib/chunk-Graph.mjs +147 -0
  25. package/dist/lib/chunk-Graph.mjs.map +1 -0
  26. package/dist/lib/chunk-Hash.mjs +16 -0
  27. package/dist/lib/chunk-Hash.mjs.map +1 -0
  28. package/dist/lib/chunk-Mapping.mjs +226 -0
  29. package/dist/lib/chunk-Mapping.mjs.map +1 -0
  30. package/dist/lib/chunk-MemoryError.mjs +10 -0
  31. package/dist/lib/chunk-MemoryError.mjs.map +1 -0
  32. package/dist/lib/chunk-MemoryQuery.mjs +99 -0
  33. package/dist/lib/chunk-MemoryQuery.mjs.map +1 -0
  34. package/dist/lib/chunk-MemoryService.mjs +31 -0
  35. package/dist/lib/chunk-MemoryService.mjs.map +1 -0
  36. package/dist/lib/chunk-Ontology.mjs +529 -0
  37. package/dist/lib/chunk-Ontology.mjs.map +1 -0
  38. package/dist/lib/chunk-Pipeline.mjs +84 -0
  39. package/dist/lib/chunk-Pipeline.mjs.map +1 -0
  40. package/dist/lib/chunk-Predicate.mjs +66 -0
  41. package/dist/lib/chunk-Predicate.mjs.map +1 -0
  42. package/dist/lib/chunk-Rdf.mjs +120 -0
  43. package/dist/lib/chunk-Rdf.mjs.map +1 -0
  44. package/dist/lib/chunk-RdfStore.mjs +60 -0
  45. package/dist/lib/chunk-RdfStore.mjs.map +1 -0
  46. package/dist/lib/chunk-Sparql.mjs +153 -0
  47. package/dist/lib/chunk-Sparql.mjs.map +1 -0
  48. package/dist/lib/chunk-Subscription.mjs +44 -0
  49. package/dist/lib/chunk-Subscription.mjs.map +1 -0
  50. package/dist/lib/chunk-Trig.mjs +106 -0
  51. package/dist/lib/chunk-Trig.mjs.map +1 -0
  52. package/dist/lib/chunk-Vocab.mjs +164 -0
  53. package/dist/lib/chunk-Vocab.mjs.map +1 -0
  54. package/dist/lib/chunk-Vocabularies.mjs +343 -0
  55. package/dist/lib/chunk-Vocabularies.mjs.map +1 -0
  56. package/dist/lib/chunk-rolldown-runtime.mjs +13 -0
  57. package/dist/lib/index.mjs +19 -0
  58. package/dist/types/src/Fact.d.ts +339 -0
  59. package/dist/types/src/Fact.d.ts.map +1 -0
  60. package/dist/types/src/Fact.test.d.ts +2 -0
  61. package/dist/types/src/Fact.test.d.ts.map +1 -0
  62. package/dist/types/src/FactFeed.d.ts +11 -0
  63. package/dist/types/src/FactFeed.d.ts.map +1 -0
  64. package/dist/types/src/FactFeed.test.d.ts +2 -0
  65. package/dist/types/src/FactFeed.test.d.ts.map +1 -0
  66. package/dist/types/src/Graph.d.ts +31 -0
  67. package/dist/types/src/Graph.d.ts.map +1 -0
  68. package/dist/types/src/Graph.test.d.ts +2 -0
  69. package/dist/types/src/Graph.test.d.ts.map +1 -0
  70. package/dist/types/src/Hash.d.ts +3 -0
  71. package/dist/types/src/Hash.d.ts.map +1 -0
  72. package/dist/types/src/Mapping.d.ts +18 -0
  73. package/dist/types/src/Mapping.d.ts.map +1 -0
  74. package/dist/types/src/Mapping.test.d.ts +2 -0
  75. package/dist/types/src/Mapping.test.d.ts.map +1 -0
  76. package/dist/types/src/MemoryError.d.ts +33 -0
  77. package/dist/types/src/MemoryError.d.ts.map +1 -0
  78. package/dist/types/src/MemoryQuery.d.ts +136 -0
  79. package/dist/types/src/MemoryQuery.d.ts.map +1 -0
  80. package/dist/types/src/MemoryQuery.test.d.ts +2 -0
  81. package/dist/types/src/MemoryQuery.test.d.ts.map +1 -0
  82. package/dist/types/src/MemoryService.d.ts +72 -0
  83. package/dist/types/src/MemoryService.d.ts.map +1 -0
  84. package/dist/types/src/Ontology.d.ts +115 -0
  85. package/dist/types/src/Ontology.d.ts.map +1 -0
  86. package/dist/types/src/Ontology.test.d.ts +2 -0
  87. package/dist/types/src/Ontology.test.d.ts.map +1 -0
  88. package/dist/types/src/Pipeline.d.ts +103 -0
  89. package/dist/types/src/Pipeline.d.ts.map +1 -0
  90. package/dist/types/src/Predicate.d.ts +17 -0
  91. package/dist/types/src/Predicate.d.ts.map +1 -0
  92. package/dist/types/src/Predicate.test.d.ts +2 -0
  93. package/dist/types/src/Predicate.test.d.ts.map +1 -0
  94. package/dist/types/src/Rdf.d.ts +33 -0
  95. package/dist/types/src/Rdf.d.ts.map +1 -0
  96. package/dist/types/src/Rdf.test.d.ts +2 -0
  97. package/dist/types/src/Rdf.test.d.ts.map +1 -0
  98. package/dist/types/src/RdfStore.d.ts +471 -0
  99. package/dist/types/src/RdfStore.d.ts.map +1 -0
  100. package/dist/types/src/Sparql.d.ts +58 -0
  101. package/dist/types/src/Sparql.d.ts.map +1 -0
  102. package/dist/types/src/Sparql.test.d.ts +2 -0
  103. package/dist/types/src/Sparql.test.d.ts.map +1 -0
  104. package/dist/types/src/Subscription.d.ts +100 -0
  105. package/dist/types/src/Subscription.d.ts.map +1 -0
  106. package/dist/types/src/Trig.d.ts +8 -0
  107. package/dist/types/src/Trig.d.ts.map +1 -0
  108. package/dist/types/src/Trig.test.d.ts +2 -0
  109. package/dist/types/src/Trig.test.d.ts.map +1 -0
  110. package/dist/types/src/Vocab.d.ts +90 -0
  111. package/dist/types/src/Vocab.d.ts.map +1 -0
  112. package/dist/types/src/Vocabularies.d.ts +45 -0
  113. package/dist/types/src/Vocabularies.d.ts.map +1 -0
  114. package/dist/types/src/index.d.ts +19 -0
  115. package/dist/types/src/index.d.ts.map +1 -0
  116. package/dist/types/tsconfig.tsbuildinfo +1 -0
  117. package/package.json +133 -3
  118. package/src/Fact.test.ts +74 -0
  119. package/src/Fact.ts +269 -0
  120. package/src/FactFeed.test.ts +40 -0
  121. package/src/FactFeed.ts +38 -0
  122. package/src/Graph.test.ts +106 -0
  123. package/src/Graph.ts +158 -0
  124. package/src/Hash.ts +15 -0
  125. package/src/Mapping.test.ts +197 -0
  126. package/src/Mapping.ts +320 -0
  127. package/src/MemoryError.ts +10 -0
  128. package/src/MemoryQuery.test.ts +67 -0
  129. package/src/MemoryQuery.ts +114 -0
  130. package/src/MemoryService.ts +89 -0
  131. package/src/Ontology.test.ts +94 -0
  132. package/src/Ontology.ts +571 -0
  133. package/src/Pipeline.ts +97 -0
  134. package/src/Predicate.test.ts +47 -0
  135. package/src/Predicate.ts +89 -0
  136. package/src/Rdf.test.ts +104 -0
  137. package/src/Rdf.ts +158 -0
  138. package/src/RdfStore.ts +111 -0
  139. package/src/Sparql.test.ts +72 -0
  140. package/src/Sparql.ts +237 -0
  141. package/src/Subscription.ts +47 -0
  142. package/src/Trig.test.ts +199 -0
  143. package/src/Trig.ts +170 -0
  144. package/src/Vocab.ts +134 -0
  145. package/src/Vocabularies.ts +204 -0
  146. package/src/index.ts +22 -0
  147. package/README.md +0 -3
@@ -0,0 +1,47 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { describe, test } from 'vitest';
6
+
7
+ import * as Predicate from './Predicate.ts';
8
+
9
+ describe('Predicate.normalize', () => {
10
+ test('collapses case, whitespace, and inflection of the head verb', ({ expect }) => {
11
+ const key = Predicate.normalize('works at');
12
+ expect(Predicate.normalize('Works At')).toBe(key);
13
+ expect(Predicate.normalize(' works at ')).toBe(key);
14
+ expect(Predicate.normalize('worked at')).toBe(key);
15
+ expect(Predicate.normalize('is working at')).toBe(key);
16
+ });
17
+
18
+ test('drops leading copula/article so "is a man" keys as "man"', ({ expect }) => {
19
+ expect(Predicate.normalize('is a man')).toBe('man');
20
+ expect(Predicate.normalize('man')).toBe('man');
21
+ });
22
+
23
+ test('does NOT merge true synonyms / different particles', ({ expect }) => {
24
+ expect(Predicate.normalize('works for')).not.toBe(Predicate.normalize('works at'));
25
+ expect(Predicate.normalize('employed by')).not.toBe(Predicate.normalize('works at'));
26
+ });
27
+
28
+ test('is idempotent', ({ expect }) => {
29
+ const once = Predicate.normalize('is leading');
30
+ expect(Predicate.normalize(once)).toBe(once);
31
+ });
32
+ });
33
+
34
+ describe('Predicate.label', () => {
35
+ test('writes lowercase kebab-case, keeping the words as said', ({ expect }) => {
36
+ expect(Predicate.label('Works at')).toBe('works-at');
37
+ expect(Predicate.label('Known by')).toBe('known-by');
38
+ expect(Predicate.label('is a')).toBe('is-a');
39
+ expect(Predicate.label('hasRole')).toBe('has-role');
40
+ expect(Predicate.label(' member of ')).toBe('member-of');
41
+ });
42
+
43
+ test('is idempotent', ({ expect }) => {
44
+ const once = Predicate.label('is member of');
45
+ expect(Predicate.label(once)).toBe(once);
46
+ });
47
+ });
@@ -0,0 +1,89 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ // Leading auxiliary / copula / article words dropped from a predicate so "is a man" keys as "man"
8
+ // and "is working at" keys the same as "works at".
9
+ const LEADING_NOISE = new Set([
10
+ 'is',
11
+ 'are',
12
+ 'was',
13
+ 'were',
14
+ 'be',
15
+ 'been',
16
+ 'being',
17
+ 'am',
18
+ 'has',
19
+ 'have',
20
+ 'had',
21
+ 'does',
22
+ 'do',
23
+ 'did',
24
+ 'can',
25
+ 'could',
26
+ 'will',
27
+ 'would',
28
+ 'shall',
29
+ 'should',
30
+ 'may',
31
+ 'might',
32
+ 'must',
33
+ 'a',
34
+ 'an',
35
+ 'the',
36
+ 'to',
37
+ ]);
38
+
39
+ /** Light inflectional stem of a single word (consistency over linguistic correctness). */
40
+ const stem = (word: string): string => {
41
+ if (word.length > 4 && word.endsWith('ing')) {
42
+ return word.slice(0, -3);
43
+ }
44
+ if (word.length > 3 && word.endsWith('ed')) {
45
+ return word.slice(0, -2);
46
+ }
47
+ if (word.length > 4 && word.endsWith('ies')) {
48
+ return `${word.slice(0, -3)}y`;
49
+ }
50
+ if (word.length > 3 && word.endsWith('s') && !word.endsWith('ss')) {
51
+ return word.slice(0, -1);
52
+ }
53
+ return word;
54
+ };
55
+
56
+ /**
57
+ * Normalize a predicate to a relation key for matching: lowercase, collapse whitespace, drop leading
58
+ * auxiliary/copula/article words, and light-stem the head verb. Inflection / case / auxiliary variants
59
+ * collapse (e.g. `Works at` / `is working at` / `worked at` → `work at`). True synonyms (`at` vs `for`,
60
+ * `works` vs `employed by`) are NOT merged — that needs a controlled vocabulary (deferred). Idempotent.
61
+ */
62
+ export const normalize = (predicate: string, { stem: stemHead = true }: { stem?: boolean } = {}): string => {
63
+ const tokens = predicate
64
+ .toLowerCase()
65
+ .trim()
66
+ .split(/\s+/)
67
+ .filter((token) => token.length > 0);
68
+ while (tokens.length > 1 && LEADING_NOISE.has(tokens[0])) {
69
+ tokens.shift();
70
+ }
71
+ if (stemHead && tokens.length > 0) {
72
+ tokens[0] = stem(tokens[0]);
73
+ }
74
+ return tokens.join(' ');
75
+ };
76
+
77
+ /**
78
+ * The display form of a predicate or an inverse: lowercase kebab-case (`Works at` → `works-at`, `Known by` →
79
+ * `known-by`), so labels the extractor, the ontology and a UI author each write read as one vocabulary. Unlike
80
+ * {@link normalize} it keeps the words as said (no stemming, no dropped copula), since it is shown, not matched.
81
+ * Idempotent.
82
+ */
83
+ export const label = (predicate: string): string =>
84
+ predicate
85
+ .trim()
86
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
87
+ .toLowerCase()
88
+ .replace(/[^a-z0-9]+/g, '-')
89
+ .replace(/^-+|-+$/g, '');
@@ -0,0 +1,104 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { DataFactory } from 'n3';
6
+ import { describe, test } from 'vitest';
7
+
8
+ import * as Rdf from './Rdf.ts';
9
+
10
+ const IRI = 'https://example.org/a';
11
+
12
+ describe('Rdf', () => {
13
+ test('a named node equals another with the same IRI, and nothing else', ({ expect }) => {
14
+ const node = Rdf.namedNode(IRI);
15
+ expect(node.termType).toBe('NamedNode');
16
+ expect(node.value).toBe(IRI);
17
+ expect(node.equals(Rdf.namedNode(IRI))).toBe(true);
18
+ expect(node.equals(Rdf.namedNode(`${IRI}b`))).toBe(false);
19
+ expect(node.equals(Rdf.blankNode(IRI))).toBe(false);
20
+ expect(node.equals(Rdf.literal(IRI))).toBe(false);
21
+ expect(node.equals(null)).toBe(false);
22
+ expect(node.equals(undefined)).toBe(false);
23
+ });
24
+
25
+ test('blank nodes compare by label; an unlabelled one is fresh', ({ expect }) => {
26
+ expect(Rdf.blankNode('x').equals(Rdf.blankNode('x'))).toBe(true);
27
+ expect(Rdf.blankNode('x').equals(Rdf.blankNode('y'))).toBe(false);
28
+ expect(Rdf.blankNode().equals(Rdf.blankNode())).toBe(false);
29
+ });
30
+
31
+ test('a plain literal is an xsd:string with no language', ({ expect }) => {
32
+ const plain = Rdf.literal('hi');
33
+ expect(plain.language).toBe('');
34
+ expect(plain.datatype.value).toBe(Rdf.XSD_STRING);
35
+ expect(plain.equals(Rdf.literal('hi'))).toBe(true);
36
+ expect(plain.equals(Rdf.literal('hi', Rdf.namedNode(Rdf.XSD_STRING)))).toBe(true);
37
+ expect(plain.equals(Rdf.literal('ho'))).toBe(false);
38
+ });
39
+
40
+ test('a language tag makes an rdf:langString, compared case-insensitively', ({ expect }) => {
41
+ const tagged = Rdf.literal('chat', 'FR');
42
+ expect(tagged.language).toBe('fr');
43
+ expect(tagged.datatype.value).toBe(Rdf.RDF_LANG_STRING);
44
+ expect(tagged.equals(Rdf.literal('chat', 'fr'))).toBe(true);
45
+ expect(tagged.equals(Rdf.literal('chat', 'en'))).toBe(false);
46
+ expect(tagged.equals(Rdf.literal('chat'))).toBe(false);
47
+ });
48
+
49
+ test('a datatype distinguishes otherwise equal literals', ({ expect }) => {
50
+ const integer = Rdf.literal('1', Rdf.namedNode('http://www.w3.org/2001/XMLSchema#integer'));
51
+ expect(integer.datatype.value).toBe('http://www.w3.org/2001/XMLSchema#integer');
52
+ expect(integer.equals(Rdf.literal('1'))).toBe(false);
53
+ });
54
+
55
+ test('the default graph is one term, equal only to a default graph', ({ expect }) => {
56
+ expect(Rdf.defaultGraph()).toBe(Rdf.defaultGraph());
57
+ expect(Rdf.defaultGraph().value).toBe('');
58
+ expect(Rdf.defaultGraph().equals(Rdf.namedNode(''))).toBe(false);
59
+ });
60
+
61
+ test('a quad equals another with equal terms, in the default graph unless given one', ({ expect }) => {
62
+ const triple = Rdf.quad(Rdf.namedNode(IRI), Rdf.namedNode(`${IRI}/p`), Rdf.literal('o'));
63
+ expect(triple.graph.termType).toBe('DefaultGraph');
64
+ expect(triple.equals(Rdf.quad(Rdf.namedNode(IRI), Rdf.namedNode(`${IRI}/p`), Rdf.literal('o')))).toBe(true);
65
+ expect(
66
+ triple.equals(Rdf.quad(Rdf.namedNode(IRI), Rdf.namedNode(`${IRI}/p`), Rdf.literal('o'), Rdf.namedNode(IRI))),
67
+ ).toBe(false);
68
+ expect(triple.equals(Rdf.quad(Rdf.namedNode(IRI), Rdf.namedNode(`${IRI}/p`), Rdf.literal('x')))).toBe(false);
69
+ });
70
+
71
+ test('terms are interchangeable with another RDF/JS implementation', ({ expect }) => {
72
+ expect(Rdf.namedNode(IRI).equals(DataFactory.namedNode(IRI))).toBe(true);
73
+ expect(DataFactory.namedNode(IRI).equals(Rdf.namedNode(IRI))).toBe(true);
74
+ expect(Rdf.literal('chat', 'fr').equals(DataFactory.literal('chat', 'fr'))).toBe(true);
75
+ expect(DataFactory.literal('chat', 'fr').equals(Rdf.literal('chat', 'fr'))).toBe(true);
76
+ expect(Rdf.literal('hi').equals(DataFactory.literal('hi'))).toBe(true);
77
+ expect(Rdf.defaultGraph().equals(DataFactory.defaultGraph())).toBe(true);
78
+ const ours = Rdf.quad(Rdf.namedNode(IRI), Rdf.namedNode(IRI), Rdf.literal('o'), Rdf.namedNode(IRI));
79
+ const theirs = DataFactory.quad(
80
+ DataFactory.namedNode(IRI),
81
+ DataFactory.namedNode(IRI),
82
+ DataFactory.literal('o'),
83
+ DataFactory.namedNode(IRI),
84
+ );
85
+ expect(ours.equals(theirs)).toBe(true);
86
+ expect(theirs.equals(ours)).toBe(true);
87
+ });
88
+ test('a null graph is the default graph, as RDF/JS requires', ({ expect }) => {
89
+ const subject = Rdf.namedNode('https://example.com/s');
90
+ expect(Rdf.quad(subject, subject, subject, null).graph.equals(Rdf.defaultGraph())).toBe(true);
91
+ expect(Rdf.quad(subject, subject, subject, null).equals(Rdf.quad(subject, subject, subject))).toBe(true);
92
+ });
93
+ test('a directional literal is an rdf:dirLangString, distinct by direction', ({ expect }) => {
94
+ const rtl = Rdf.literal('x', { language: 'AR', direction: 'rtl' });
95
+ expect(rtl.language).toBe('ar');
96
+ expect(rtl.direction).toBe('rtl');
97
+ expect(rtl.datatype.value).toBe(Rdf.RDF_DIR_LANG_STRING);
98
+ expect(rtl.equals(Rdf.literal('x', { language: 'ar', direction: 'rtl' }))).toBe(true);
99
+ expect(rtl.equals(Rdf.literal('x', { language: 'ar', direction: 'ltr' }))).toBe(false);
100
+ expect(rtl.equals(Rdf.literal('x', 'ar'))).toBe(false);
101
+ expect(Rdf.literal('x', { language: 'ar' }).equals(Rdf.literal('x', 'ar'))).toBe(true);
102
+ expect(Rdf.literal('x', { language: '', direction: '' }).equals(Rdf.literal('x'))).toBe(true);
103
+ });
104
+ });
package/src/Rdf.ts ADDED
@@ -0,0 +1,158 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import type * as RdfJs from '@rdfjs/types';
8
+
9
+ //
10
+ // RDF/JS terms and quads (https://rdf.js.org/data-model-spec/), so the memory core builds and compares RDF without a
11
+ // parser library: n3 pulls in `readable-stream`, which does not load under workerd's `nodejs_compat`.
12
+ //
13
+
14
+ export type Term = RdfJs.Term;
15
+ export type NamedNode<Iri extends string = string> = RdfJs.NamedNode<Iri>;
16
+ export type BlankNode = RdfJs.BlankNode;
17
+ export type Literal = RdfJs.Literal;
18
+ export type Variable = RdfJs.Variable;
19
+ export type DefaultGraph = RdfJs.DefaultGraph;
20
+ export type Quad = RdfJs.Quad;
21
+ export type QuadSubject = RdfJs.Quad_Subject;
22
+ export type QuadPredicate = RdfJs.Quad_Predicate;
23
+ export type QuadObject = RdfJs.Quad_Object;
24
+ export type QuadGraph = RdfJs.Quad_Graph;
25
+
26
+ export const XSD_STRING = 'http://www.w3.org/2001/XMLSchema#string';
27
+ export const RDF_LANG_STRING = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#langString';
28
+ export const RDF_DIR_LANG_STRING = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#dirLangString';
29
+ export const RDF_TYPE = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';
30
+
31
+ class NamedNodeTerm<Iri extends string = string> implements RdfJs.NamedNode<Iri> {
32
+ readonly termType = 'NamedNode';
33
+ constructor(readonly value: Iri) {}
34
+ equals(other: RdfJs.Term | null | undefined): boolean {
35
+ return !!other && other.termType === this.termType && other.value === this.value;
36
+ }
37
+ }
38
+
39
+ class BlankNodeTerm implements RdfJs.BlankNode {
40
+ readonly termType = 'BlankNode';
41
+ constructor(readonly value: string) {}
42
+ equals(other: RdfJs.Term | null | undefined): boolean {
43
+ return !!other && other.termType === this.termType && other.value === this.value;
44
+ }
45
+ }
46
+
47
+ class LiteralTerm implements RdfJs.Literal {
48
+ readonly termType = 'Literal';
49
+ constructor(
50
+ readonly value: string,
51
+ readonly language: string,
52
+ readonly datatype: RdfJs.NamedNode,
53
+ readonly direction: '' | 'ltr' | 'rtl' = '',
54
+ ) {}
55
+ equals(other: RdfJs.Term | null | undefined): boolean {
56
+ return (
57
+ !!other &&
58
+ other.termType === this.termType &&
59
+ other.value === this.value &&
60
+ other.language === this.language &&
61
+ (other.direction ?? '') === this.direction &&
62
+ other.datatype.equals(this.datatype)
63
+ );
64
+ }
65
+ }
66
+
67
+ class VariableTerm implements RdfJs.Variable {
68
+ readonly termType = 'Variable';
69
+ constructor(readonly value: string) {}
70
+ equals(other: RdfJs.Term | null | undefined): boolean {
71
+ return !!other && other.termType === this.termType && other.value === this.value;
72
+ }
73
+ }
74
+
75
+ class DefaultGraphTerm implements RdfJs.DefaultGraph {
76
+ readonly termType = 'DefaultGraph';
77
+ readonly value = '';
78
+ equals(other: RdfJs.Term | null | undefined): boolean {
79
+ return !!other && other.termType === this.termType;
80
+ }
81
+ }
82
+
83
+ class QuadTerm implements RdfJs.Quad {
84
+ readonly termType = 'Quad';
85
+ readonly value = '';
86
+ constructor(
87
+ readonly subject: RdfJs.Quad_Subject,
88
+ readonly predicate: RdfJs.Quad_Predicate,
89
+ readonly object: RdfJs.Quad_Object,
90
+ readonly graph: RdfJs.Quad_Graph,
91
+ ) {}
92
+ equals(other: RdfJs.Term | null | undefined): boolean {
93
+ return (
94
+ !!other &&
95
+ other.termType === this.termType &&
96
+ this.subject.equals(other.subject) &&
97
+ this.predicate.equals(other.predicate) &&
98
+ this.object.equals(other.object) &&
99
+ this.graph.equals(other.graph)
100
+ );
101
+ }
102
+ }
103
+
104
+ const DEFAULT_GRAPH = new DefaultGraphTerm();
105
+ const STRING_DATATYPE = new NamedNodeTerm(XSD_STRING);
106
+ const LANG_STRING_DATATYPE = new NamedNodeTerm(RDF_LANG_STRING);
107
+ const DIR_LANG_STRING_DATATYPE = new NamedNodeTerm(RDF_DIR_LANG_STRING);
108
+
109
+ /** A named node for an IRI. */
110
+ export const namedNode = <Iri extends string = string>(value: Iri): RdfJs.NamedNode<Iri> => new NamedNodeTerm(value);
111
+
112
+ let nextBlankNode = 0;
113
+
114
+ /** A blank node; without a label, one unique within this process. */
115
+ export const blankNode = (value?: string): RdfJs.BlankNode => new BlankNodeTerm(value ?? `b${nextBlankNode++}`);
116
+
117
+ /**
118
+ * A literal: a string is a language tag (`rdf:langString`), a language with a direction a directional one
119
+ * (`rdf:dirLangString`), a named node a datatype; none makes an `xsd:string`. Language tags are compared lower-case,
120
+ * as RDF 1.1 requires.
121
+ */
122
+ export const literal = (
123
+ value: string,
124
+ languageOrDatatype?: string | RdfJs.NamedNode | RdfJs.DirectionalLanguage,
125
+ ): RdfJs.Literal => {
126
+ if (typeof languageOrDatatype === 'string') {
127
+ return languageOrDatatype.length > 0
128
+ ? new LiteralTerm(value, languageOrDatatype.toLowerCase(), LANG_STRING_DATATYPE)
129
+ : new LiteralTerm(value, '', STRING_DATATYPE);
130
+ }
131
+ if (languageOrDatatype === undefined) {
132
+ return new LiteralTerm(value, '', STRING_DATATYPE);
133
+ }
134
+ if ('termType' in languageOrDatatype) {
135
+ return new LiteralTerm(value, '', namedNode(languageOrDatatype.value));
136
+ }
137
+ const { language, direction } = languageOrDatatype;
138
+ if (language.length === 0) {
139
+ return new LiteralTerm(value, '', STRING_DATATYPE);
140
+ }
141
+ return direction
142
+ ? new LiteralTerm(value, language.toLowerCase(), DIR_LANG_STRING_DATATYPE, direction)
143
+ : new LiteralTerm(value, language.toLowerCase(), LANG_STRING_DATATYPE);
144
+ };
145
+
146
+ /** A SPARQL variable; `value` is its name without the leading `?`. */
147
+ export const variable = (value: string): RdfJs.Variable => new VariableTerm(value);
148
+
149
+ /** The default graph; every call returns the same term. */
150
+ export const defaultGraph = (): RdfJs.DefaultGraph => DEFAULT_GRAPH;
151
+
152
+ /** A quad; a missing or `null` graph is the default graph, as RDF/JS requires. */
153
+ export const quad = (
154
+ subject: RdfJs.Quad_Subject,
155
+ predicate: RdfJs.Quad_Predicate,
156
+ object: RdfJs.Quad_Object,
157
+ graph?: RdfJs.Quad_Graph | null,
158
+ ): RdfJs.Quad => new QuadTerm(subject, predicate, object, graph ?? DEFAULT_GRAPH);
@@ -0,0 +1,111 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import * as Context from 'effect/Context';
8
+ import type * as Effect from 'effect/Effect';
9
+ import * as Schema from 'effect/Schema';
10
+ import type * as Scope from 'effect/Scope';
11
+
12
+ import { BaseError } from '@dxos/errors';
13
+
14
+ import * as MemoryQuery from './MemoryQuery.ts';
15
+
16
+ //
17
+ // The store a memory runs on: a space's quads, read with SPARQL and changed by batches of writes. A memory turns its
18
+ // operations into these calls, so the same memory runs over a store in the page, in a worker, or across RPC.
19
+ //
20
+
21
+ /** A triple in the default graph, or a quad in the named graph `g`. */
22
+ export const Quad = Schema.Struct({
23
+ s: MemoryQuery.SparqlTerm,
24
+ p: MemoryQuery.SparqlTerm,
25
+ o: MemoryQuery.SparqlTerm,
26
+ g: Schema.optional(MemoryQuery.SparqlTerm),
27
+ });
28
+ export interface Quad extends Schema.Schema.Type<typeof Quad> {}
29
+
30
+ /** Adds quads; one already stored is kept once. */
31
+ export const Insert = Schema.TaggedStruct('insert', { quads: Schema.Array(Quad) });
32
+ export interface Insert extends Schema.Schema.Type<typeof Insert> {}
33
+
34
+ /** Removes quads; one not stored is ignored. */
35
+ export const Delete = Schema.TaggedStruct('delete', { quads: Schema.Array(Quad) });
36
+ export interface Delete extends Schema.Schema.Type<typeof Delete> {}
37
+
38
+ /** Removes every quad of the part written to. */
39
+ export const Clear = Schema.TaggedStruct('clear', {});
40
+ export interface Clear extends Schema.Schema.Type<typeof Clear> {}
41
+
42
+ /** One change to the store. */
43
+ export const Write = Schema.Union([Insert, Delete, Clear]);
44
+ export type Write = Schema.Schema.Type<typeof Write>;
45
+
46
+ /** Writes recorded together and applied together, in order. */
47
+ export const Batch = Schema.Struct({ id: Schema.String, writes: Schema.Array(Write) });
48
+ export interface Batch extends Schema.Schema.Type<typeof Batch> {}
49
+
50
+ /**
51
+ * How quads move in and out in bulk. `trig`: the Turtle family's text syntax with named graphs, which every fact is
52
+ * stored in and plain Turtle cannot express. `binary`: a term dictionary and the quads as indexes into it, several
53
+ * times smaller and faster to read, for copies between stores.
54
+ */
55
+ export const Format = Schema.Literals(['trig', 'binary']);
56
+ export type Format = Schema.Schema.Type<typeof Format>;
57
+
58
+ /** The store refused, could not be reached, or the input does not parse; the message says which. */
59
+ export class RdfStoreError extends BaseError.extend('RdfStoreError', 'RDF store operation failed.') {}
60
+
61
+ export type ExportOptions = {
62
+ /** Namespace prefixes a TriG export abbreviates IRIs with, by prefix. */
63
+ readonly prefixes?: Readonly<Record<string, string>>;
64
+ };
65
+
66
+ /** What an import added: the batch it wrote, and how many quads it read. */
67
+ export const ImportResult = Schema.Struct({ batch: Schema.String, quads: Schema.Number });
68
+ export interface ImportResult extends Schema.Schema.Type<typeof ImportResult> {}
69
+
70
+ export type QueryOptions = {
71
+ /** Reads the store's local part instead of its shared part. */
72
+ readonly local?: boolean;
73
+ };
74
+
75
+ export type WriteOptions = {
76
+ /**
77
+ * Writes the store's local part: kept on this device only, never replicated, and untouched by a `clear` of the
78
+ * shared part. A memory keeps its subscriptions and their undelivered events there.
79
+ */
80
+ readonly local?: boolean;
81
+ };
82
+
83
+ /**
84
+ * A space's quads in two parts. The shared part is replicated: a write is recorded durably before it is applied, and
85
+ * every replica applies the same batches in the same order. The local part is this device's own.
86
+ */
87
+ export interface Service {
88
+ /** Runs a SPARQL read (SELECT, ASK or CONSTRUCT); an update fails, since changes go through {@link write}. */
89
+ readonly query: (
90
+ sparql: string,
91
+ options?: QueryOptions,
92
+ ) => Effect.Effect<readonly MemoryQuery.SparqlRow[], RdfStoreError>;
93
+
94
+ /** Applies the writes as one batch and returns its id, once it is durable (shared) or written (local). */
95
+ readonly write: (writes: readonly Write[], options?: WriteOptions) => Effect.Effect<string, RdfStoreError>;
96
+
97
+ /** Every quad of the shared part, serialized where the store is, so a large store crosses a boundary once. */
98
+ readonly export: (format: Format, options?: ExportOptions) => Effect.Effect<Uint8Array, RdfStoreError>;
99
+
100
+ /** Parses the data where the store is and inserts its quads into the shared part as one batch. */
101
+ readonly import: (data: Uint8Array, format: Format) => Effect.Effect<ImportResult, RdfStoreError>;
102
+
103
+ /**
104
+ * Calls `onApplied` with each batch of the shared part once it is applied, this replica's and other replicas' alike,
105
+ * in the order applied, until the scope closes. The listener is registered before this returns, so a reader that
106
+ * listens and then reads misses nothing.
107
+ */
108
+ readonly listen: (onApplied: (batch: Batch) => void) => Effect.Effect<void, never, Scope.Scope>;
109
+ }
110
+
111
+ export class RdfStore extends Context.Service<RdfStore, Service>()('@dxos/echo-memory/RdfStore') {}
@@ -0,0 +1,72 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { describe, test } from 'vitest';
6
+
7
+ import * as Ontology from './Ontology.ts';
8
+ import * as Rdf from './Rdf.ts';
9
+ import * as Sparql from './Sparql.ts';
10
+
11
+ const IS_A = Ontology.DEFAULT.resolve('is a').iri;
12
+ const WORKS_AT = Ontology.DEFAULT.resolve('works at').iri;
13
+ const STORED = new Map([
14
+ [IS_A, 'is a'],
15
+ [WORKS_AT, 'works at'],
16
+ ]);
17
+
18
+ describe('matchingPredicates', () => {
19
+ test('matches whole words of the relation key, not characters', ({ expect }) => {
20
+ // `is a` keys as `a`, which is a substring of `work_at` but not one of its words.
21
+ expect(Sparql.matchingPredicates('work at', STORED)).toEqual(new Set([WORKS_AT]));
22
+ expect(Sparql.matchingPredicates('is working at', STORED)).toEqual(new Set([WORKS_AT]));
23
+ });
24
+
25
+ test('a query that names part of a relation still finds it', ({ expect }) => {
26
+ expect(Sparql.matchingPredicates('works', STORED).has(WORKS_AT)).toBe(true);
27
+ });
28
+ });
29
+
30
+ const { defaultGraph, literal, namedNode, quad } = Rdf;
31
+
32
+ const XSD_DECIMAL = 'http://www.w3.org/2001/XMLSchema#decimal';
33
+ const GRAPH = 'https://example.com/graph/1';
34
+
35
+ describe('terms', () => {
36
+ test('toQuad keeps literal datatypes and languages, and drops the default graph', ({ expect }) => {
37
+ const typed = Sparql.toQuad(
38
+ quad(namedNode('urn:s'), namedNode('urn:p'), literal('0.6', namedNode(XSD_DECIMAL)), defaultGraph()),
39
+ );
40
+ expect(typed).toEqual({
41
+ s: { termType: 'NamedNode', value: 'urn:s' },
42
+ p: { termType: 'NamedNode', value: 'urn:p' },
43
+ o: { termType: 'Literal', value: '0.6', datatype: XSD_DECIMAL },
44
+ });
45
+ const tagged = Sparql.toQuad(
46
+ quad(namedNode('urn:s'), namedNode('urn:p'), literal('bonjour', 'fr'), namedNode(GRAPH)),
47
+ );
48
+ expect(tagged.o).toEqual({ termType: 'Literal', value: 'bonjour', language: 'fr' });
49
+ expect(tagged.g).toEqual({ termType: 'NamedNode', value: GRAPH });
50
+ });
51
+
52
+ test('rowsToQuads restores literal datatypes and languages in graph and provenance rows', ({ expect }) => {
53
+ const [statement, provenance] = Sparql.rowsToQuads([
54
+ {
55
+ g: { termType: 'NamedNode', value: GRAPH },
56
+ s: { termType: 'NamedNode', value: 'urn:s' },
57
+ p: { termType: 'NamedNode', value: 'urn:p' },
58
+ o: { termType: 'Literal', value: 'bonjour', language: 'fr' },
59
+ },
60
+ {
61
+ g: { termType: 'NamedNode', value: GRAPH },
62
+ p: { termType: 'NamedNode', value: 'urn:confidence' },
63
+ o: { termType: 'Literal', value: '0.6', datatype: XSD_DECIMAL },
64
+ },
65
+ ]);
66
+ expect(statement.object.equals(literal('bonjour', 'fr'))).toBe(true);
67
+ expect(statement.graph.equals(namedNode(GRAPH))).toBe(true);
68
+ expect(provenance.subject.equals(namedNode(GRAPH))).toBe(true);
69
+ expect(provenance.object.equals(literal('0.6', namedNode(XSD_DECIMAL)))).toBe(true);
70
+ expect(provenance.graph.termType).toBe('DefaultGraph');
71
+ });
72
+ });