@coasys/ad4m 0.13.0-test-6 → 0.13.0-test-7

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 (39) hide show
  1. package/lib/index.cjs +111 -36
  2. package/lib/index.js +111 -36
  3. package/lib/src/model/Ad4mModel.d.ts +15 -0
  4. package/lib/src/model/Ad4mModel.js +94 -28
  5. package/lib/src/model/Ad4mModel.test.js +1434 -688
  6. package/lib/src/model/ModelQueryBuilder.js +17 -8
  7. package/lib/src/model/Subject.js +6 -6
  8. package/lib/src/model/hydration-batch.d.ts +34 -0
  9. package/lib/src/model/hydration-batch.js +147 -0
  10. package/lib/src/model/hydration-batching.test.d.ts +7 -0
  11. package/lib/src/model/hydration-batching.test.js +456 -0
  12. package/lib/src/model/model-manifest.d.ts +41 -0
  13. package/lib/src/model/model-manifest.js +11 -0
  14. package/lib/src/model/query-cache.test.d.ts +1 -0
  15. package/lib/src/model/query-cache.test.js +43 -0
  16. package/lib/src/model/query-sparql-batch.d.ts +17 -0
  17. package/lib/src/model/query-sparql-batch.js +260 -0
  18. package/lib/src/model/query-sparql.test.d.ts +1 -0
  19. package/lib/src/model/query-sparql.test.js +312 -0
  20. package/lib/src/model/relation-filtering.test.js +15 -15
  21. package/lib/src/model/subscription-delta.test.d.ts +24 -0
  22. package/lib/src/model/subscription-delta.test.js +180 -0
  23. package/lib/src/model/subscription-pool.d.ts +39 -0
  24. package/lib/src/model/subscription-pool.js +165 -0
  25. package/lib/src/perspectives/PerspectiveClient.test.d.ts +1 -0
  26. package/lib/src/perspectives/PerspectiveClient.test.js +224 -0
  27. package/lib/src/perspectives/PerspectiveResolver.d.ts +0 -1
  28. package/lib/src/perspectives/PerspectiveResolver.js +0 -11
  29. package/lib/src/runtime/RuntimeResolver.d.ts +28 -1
  30. package/lib/src/runtime/RuntimeResolver.js +197 -4
  31. package/lib/src/schema.gql +27 -1
  32. package/lib/src/shacl/SHACLShape.test.js +82 -0
  33. package/package.json +8 -11
  34. package/src/model/Ad4mModel.ts +97 -26
  35. package/src/model/ModelQueryBuilder.ts +17 -7
  36. package/lib/src/model/query-surreal.d.ts +0 -44
  37. package/lib/src/model/query-surreal.js +0 -249
  38. package/lib/src/model/surreal-utils.d.ts +0 -42
  39. package/lib/src/model/surreal-utils.js +0 -128
@@ -20,7 +20,7 @@ var __metadata = (this && this.__metadata) || function (k, v) {
20
20
  import { Ad4mModel } from "./Ad4mModel";
21
21
  import { Model, Property, Flag, HasMany, Optional, buildConformanceFilter, } from "./decorators";
22
22
  import { SHACLShape, } from "../shacl/SHACLShape";
23
- import { compileWhereClause } from "./surreal-utils";
23
+ import { compileWhereClause } from "./query-utils";
24
24
  // ============================================================================
25
25
  // Test models
26
26
  // ============================================================================
@@ -88,7 +88,7 @@ __decorate([
88
88
  ], ParentWithRelations.prototype, "unfilteredItems", void 0);
89
89
  __decorate([
90
90
  HasMany({
91
- getter: "(<-link[WHERE predicate = 'test://custom'].in.uri)",
91
+ getter: "SELECT ?target WHERE { ?target <test://custom> ?source . }",
92
92
  }),
93
93
  __metadata("design:type", Array)
94
94
  ], ParentWithRelations.prototype, "customItems", void 0);
@@ -113,8 +113,8 @@ describe("buildConformanceFilter()", () => {
113
113
  expect(reqCond).toBeDefined();
114
114
  expect(reqCond.predicate).toBe("test://name");
115
115
  expect(reqCond.value).toBeUndefined();
116
- // Getter string should be a SurrealQL expression
117
- expect(result.getter).toContain("->link[WHERE predicate =");
116
+ // Getter string should be a SPARQL expression
117
+ expect(result.getter).toContain("SELECT ?target WHERE");
118
118
  expect(result.getter).toContain("test://has_flagged");
119
119
  expect(result.getter).toContain("test://type");
120
120
  expect(result.getter).toContain("test://flagged_type");
@@ -161,7 +161,7 @@ describe("buildConformanceFilter()", () => {
161
161
  Property({
162
162
  through: "test://computed",
163
163
  required: true,
164
- getter: "(<-link[WHERE predicate = 'test://custom'].in.uri)[0]",
164
+ getter: "SELECT ?target WHERE { ?target <test://custom> ?source . } LIMIT 1",
165
165
  }),
166
166
  __metadata("design:type", String)
167
167
  ], CustomGetterTarget.prototype, "computed", void 0);
@@ -179,7 +179,7 @@ describe("buildConformanceFilter()", () => {
179
179
  // SHACL serialization round-trip tests
180
180
  // ============================================================================
181
181
  describe("SHACL shape getter serialization", () => {
182
- const testGetter = "(->link[WHERE predicate = 'test://pred'].out[WHERE count(->link[WHERE predicate = 'test://type' AND out.uri = 'test://flag']) > 0].uri)";
182
+ const testGetter = "SELECT ?target WHERE { <Base> <test://pred> ?target . ?target <test://type> <test://flag> . }";
183
183
  const testConditions = [
184
184
  { type: "flag", predicate: "test://type", value: "test://flag" },
185
185
  { type: "required", predicate: "test://name" },
@@ -198,7 +198,7 @@ describe("SHACL shape getter serialization", () => {
198
198
  // Verify getter link exists
199
199
  const getterLink = links.find(l => l.predicate === "ad4m://getter");
200
200
  expect(getterLink).toBeDefined();
201
- expect(getterLink.target).toBe(`literal://string:${testGetter}`);
201
+ expect(getterLink.target).toBe(`literal:string:${testGetter}`);
202
202
  // Verify conditions link exists
203
203
  const conditionsLink = links.find(l => l.predicate === "ad4m://conformanceConditions");
204
204
  expect(conditionsLink).toBeDefined();
@@ -321,7 +321,7 @@ describe("Ad4mModel.getModelMetadata() relation filtering fields", () => {
321
321
  it("should expose explicit getter on relations with custom getter", () => {
322
322
  const metadata = ParentWithRelations.getModelMetadata();
323
323
  // Explicit getter provided via decorator (getter-only, no predicate)
324
- expect(metadata.relations.customItems.getter).toBe("(<-link[WHERE predicate = 'test://custom'].in.uri)");
324
+ expect(metadata.relations.customItems.getter).toBe("SELECT ?target WHERE { ?target <test://custom> ?source . }");
325
325
  expect(metadata.relations.customItems.predicate).toBe("");
326
326
  // Auto-generated getter is NOT in decorator metadata (it's in the SHACL shape)
327
327
  expect(metadata.relations.flaggedItems.getter).toBeUndefined();
@@ -364,7 +364,7 @@ describe("Relation decorator validation", () => {
364
364
  };
365
365
  __decorate([
366
366
  HasMany({
367
- getter: "(<-link.in.uri)",
367
+ getter: "SELECT ?target WHERE { ?target ?p ?source . }",
368
368
  target: () => FlaggedTarget,
369
369
  }),
370
370
  __metadata("design:type", Array)
@@ -384,7 +384,7 @@ describe("Relation decorator validation", () => {
384
384
  };
385
385
  __decorate([
386
386
  HasMany({
387
- getter: "(<-link.in.uri)",
387
+ getter: "SELECT ?target WHERE { ?target ?p ?source . }",
388
388
  through: "test://pred",
389
389
  }),
390
390
  __metadata("design:type", Array)
@@ -404,7 +404,7 @@ describe("Relation decorator validation", () => {
404
404
  };
405
405
  __decorate([
406
406
  HasMany({
407
- getter: "(<-link.in.uri)",
407
+ getter: "SELECT ?target WHERE { ?target ?p ?source . }",
408
408
  }),
409
409
  __metadata("design:type", Array)
410
410
  ], _Valid.prototype, "items", void 0);
@@ -541,7 +541,7 @@ describe("where clause validation", () => {
541
541
  __decorate([
542
542
  HasMany({
543
543
  where: { status: "active" },
544
- getter: "(<-link.in.uri)",
544
+ getter: "SELECT ?target WHERE { ?target ?p ?source . }",
545
545
  }),
546
546
  __metadata("design:type", Array)
547
547
  ], _Invalid.prototype, "items", void 0);
@@ -573,7 +573,7 @@ describe("where clause validation", () => {
573
573
  });
574
574
  });
575
575
  describe("where clause compilation", () => {
576
- it("should compile where clause to SurrealQL getter", () => {
576
+ it("should compile where clause to SPARQL getter", () => {
577
577
  let WhereTarget = class WhereTarget extends Ad4mModel {
578
578
  constructor() {
579
579
  super(...arguments);
@@ -810,7 +810,7 @@ describe("where clause compilation", () => {
810
810
  // compileWhereClause() unit tests
811
811
  // ============================================================================
812
812
  describe("compileWhereClause()", () => {
813
- it("should compile simple equality to SurrealQL condition", () => {
813
+ it("should compile simple equality to SPARQL condition", () => {
814
814
  const conditions = compileWhereClause({ status: "active" }, { properties: { status: { name: "status", predicate: "test://status", required: false, readOnly: false } }, relations: {}, className: "Test" });
815
815
  expect(conditions).toHaveLength(1);
816
816
  expect(conditions[0]).toContain("test://status");
@@ -819,7 +819,7 @@ describe("compileWhereClause()", () => {
819
819
  it("should compile not operator", () => {
820
820
  const conditions = compileWhereClause({ status: { not: "archived" } }, { properties: { status: { name: "status", predicate: "test://status", required: false, readOnly: false } }, relations: {}, className: "Test" });
821
821
  expect(conditions).toHaveLength(1);
822
- expect(conditions[0]).toContain("= 0"); // negation
822
+ expect(conditions[0]).toContain("NOT EXISTS"); // negation
823
823
  expect(conditions[0]).toContain("archived");
824
824
  });
825
825
  it("should compile array values to IN clause", () => {
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Tests for the delta fast-path logic used in subscription-pool.ts.
3
+ *
4
+ * The delta optimisation in pooledSubscribe's onResult handler:
5
+ * 1. Checks if new rows are a strict superset of previous rows
6
+ * 2. Extracts added rows (new triples not in prev set)
7
+ * 3. Verifies ALL added rows have source URIs not already in previous results
8
+ * 4. If condition 3 fails (existing source got new links), falls back to full rehydration
9
+ *
10
+ * These tests validate the detection logic in isolation.
11
+ */
12
+ type Row = {
13
+ source: string;
14
+ predicate: string;
15
+ target: string;
16
+ };
17
+ /**
18
+ * Replicates the delta-path eligibility check from subscription-pool.ts
19
+ */
20
+ declare function detectDeltaPath(prevArr: Row[], newArr: Row[]): {
21
+ useDelta: boolean;
22
+ addedRows: Row[];
23
+ reason?: string;
24
+ };
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Tests for the delta fast-path logic used in subscription-pool.ts.
3
+ *
4
+ * The delta optimisation in pooledSubscribe's onResult handler:
5
+ * 1. Checks if new rows are a strict superset of previous rows
6
+ * 2. Extracts added rows (new triples not in prev set)
7
+ * 3. Verifies ALL added rows have source URIs not already in previous results
8
+ * 4. If condition 3 fails (existing source got new links), falls back to full rehydration
9
+ *
10
+ * These tests validate the detection logic in isolation.
11
+ */
12
+ /**
13
+ * Replicates the delta-path eligibility check from subscription-pool.ts
14
+ */
15
+ function detectDeltaPath(prevArr, newArr) {
16
+ if (newArr.length <= prevArr.length) {
17
+ return { useDelta: false, addedRows: [], reason: 'no growth' };
18
+ }
19
+ if (newArr.length - prevArr.length > 5) {
20
+ return { useDelta: false, addedRows: [], reason: 'delta too large' };
21
+ }
22
+ const prevSources = new Set(prevArr.map(r => `${r.source}|${r.predicate}|${r.target}`));
23
+ const addedRows = newArr.filter(r => !prevSources.has(`${r.source}|${r.predicate}|${r.target}`));
24
+ const newSources = new Set(newArr.map(r => `${r.source}|${r.predicate}|${r.target}`));
25
+ const removedRows = prevArr.filter(r => !newSources.has(`${r.source}|${r.predicate}|${r.target}`));
26
+ if (removedRows.length > 0) {
27
+ return { useDelta: false, addedRows, reason: 'rows removed' };
28
+ }
29
+ // Key check: all added rows must have NEW source URIs
30
+ const prevSourceIds = new Set(prevArr.map(r => r.source));
31
+ const allNewSources = addedRows.every(r => !prevSourceIds.has(r.source));
32
+ if (!allNewSources) {
33
+ return { useDelta: false, addedRows, reason: 'existing source got new links' };
34
+ }
35
+ return { useDelta: true, addedRows };
36
+ }
37
+ describe('delta fast-path detection', () => {
38
+ const prev = [
39
+ { source: 'a', predicate: 'p1', target: 't1' },
40
+ { source: 'a', predicate: 'p2', target: 't2' },
41
+ { source: 'b', predicate: 'p1', target: 't3' },
42
+ ];
43
+ it('appends genuinely new items via delta path', () => {
44
+ const next = [
45
+ ...prev,
46
+ { source: 'c', predicate: 'p1', target: 't4' },
47
+ ];
48
+ const result = detectDeltaPath(prev, next);
49
+ expect(result.useDelta).toBe(true);
50
+ expect(result.addedRows).toHaveLength(1);
51
+ expect(result.addedRows[0].source).toBe('c');
52
+ });
53
+ it('falls back when existing source gets new links', () => {
54
+ const next = [
55
+ ...prev,
56
+ { source: 'a', predicate: 'p3', target: 't5' }, // source 'a' already exists
57
+ ];
58
+ const result = detectDeltaPath(prev, next);
59
+ expect(result.useDelta).toBe(false);
60
+ expect(result.reason).toBe('existing source got new links');
61
+ });
62
+ it('falls back when rows are removed (even if new ones added)', () => {
63
+ const next = [
64
+ { source: 'a', predicate: 'p1', target: 't1' },
65
+ { source: 'a', predicate: 'p2', target: 't2' },
66
+ // source 'b' row removed, two new sources added so length grows
67
+ { source: 'c', predicate: 'p1', target: 't4' },
68
+ { source: 'd', predicate: 'p1', target: 't5' },
69
+ ];
70
+ const result = detectDeltaPath(prev, next);
71
+ expect(result.useDelta).toBe(false);
72
+ expect(result.reason).toBe('rows removed');
73
+ });
74
+ it('falls back when delta is too large (>5 new rows)', () => {
75
+ const next = [
76
+ ...prev,
77
+ ...Array.from({ length: 6 }, (_, i) => ({
78
+ source: `new${i}`, predicate: 'p1', target: `t${10 + i}`,
79
+ })),
80
+ ];
81
+ const result = detectDeltaPath(prev, next);
82
+ expect(result.useDelta).toBe(false);
83
+ expect(result.reason).toBe('delta too large');
84
+ });
85
+ it('falls back when no growth', () => {
86
+ const result = detectDeltaPath(prev, prev);
87
+ expect(result.useDelta).toBe(false);
88
+ expect(result.reason).toBe('no growth');
89
+ });
90
+ it('handles multiple new sources in one delta', () => {
91
+ const next = [
92
+ ...prev,
93
+ { source: 'c', predicate: 'p1', target: 't4' },
94
+ { source: 'd', predicate: 'p1', target: 't5' },
95
+ ];
96
+ const result = detectDeltaPath(prev, next);
97
+ expect(result.useDelta).toBe(true);
98
+ expect(result.addedRows).toHaveLength(2);
99
+ });
100
+ // ── Test #8: Rapid successive additions ──
101
+ it('handles 10 items added in quick succession without duplicates', () => {
102
+ let current = [...prev];
103
+ for (let i = 0; i < 10; i++) {
104
+ const next = [...current, { source: `rapid-${i}`, predicate: 'p1', target: `t-rapid-${i}` }];
105
+ const result = detectDeltaPath(current, next);
106
+ // Each individual addition should be eligible for delta
107
+ expect(result.useDelta).toBe(true);
108
+ expect(result.addedRows).toHaveLength(1);
109
+ expect(result.addedRows[0].source).toBe(`rapid-${i}`);
110
+ current = next;
111
+ }
112
+ });
113
+ // ── Test #9: Addition + removal in same batch ──
114
+ it('falls back when one item added and another removed simultaneously', () => {
115
+ const next = [
116
+ { source: 'a', predicate: 'p1', target: 't1' },
117
+ { source: 'a', predicate: 'p2', target: 't2' },
118
+ // source 'b' removed, source 'c' added
119
+ { source: 'c', predicate: 'p1', target: 't4' },
120
+ { source: 'd', predicate: 'p1', target: 't5' },
121
+ ];
122
+ const result = detectDeltaPath(prev, next);
123
+ expect(result.useDelta).toBe(false);
124
+ expect(result.reason).toBe('rows removed');
125
+ });
126
+ // ── Test #10: Delta with nested relations (detection only) ──
127
+ it('delta path detects new items correctly even when sources have complex URIs', () => {
128
+ const next = [
129
+ ...prev,
130
+ { source: 'flux://post/123/comment/456', predicate: 'flux://belongs_to', target: 'flux://post/123' },
131
+ ];
132
+ const result = detectDeltaPath(prev, next);
133
+ expect(result.useDelta).toBe(true);
134
+ expect(result.addedRows).toHaveLength(1);
135
+ expect(result.addedRows[0].source).toBe('flux://post/123/comment/456');
136
+ });
137
+ // ── Test #11: Empty previous result + new items ──
138
+ it('handles empty previous array with new items arriving', () => {
139
+ const empty = [];
140
+ const next = [
141
+ { source: 'x', predicate: 'p1', target: 't1' },
142
+ ];
143
+ const result = detectDeltaPath(empty, next);
144
+ expect(result.useDelta).toBe(true);
145
+ expect(result.addedRows).toHaveLength(1);
146
+ });
147
+ it('handles empty previous with no new items', () => {
148
+ const result = detectDeltaPath([], []);
149
+ expect(result.useDelta).toBe(false);
150
+ expect(result.reason).toBe('no growth');
151
+ });
152
+ // ── Test #12: Source URI with special characters ──
153
+ it('handles URIs with encoded characters, fragments, and query params', () => {
154
+ const specialPrev = [
155
+ { source: 'flux://item%20one', predicate: 'p1', target: 't1' },
156
+ { source: 'flux://item#section', predicate: 'p2', target: 't2' },
157
+ { source: 'flux://item?key=val&foo=bar', predicate: 'p3', target: 't3' },
158
+ ];
159
+ const specialNext = [
160
+ ...specialPrev,
161
+ { source: 'flux://new%C3%A9item', predicate: 'p1', target: 't4' },
162
+ ];
163
+ const result = detectDeltaPath(specialPrev, specialNext);
164
+ expect(result.useDelta).toBe(true);
165
+ expect(result.addedRows).toHaveLength(1);
166
+ expect(result.addedRows[0].source).toBe('flux://new%C3%A9item');
167
+ });
168
+ it('correctly identifies existing source with special chars getting new links', () => {
169
+ const specialPrev = [
170
+ { source: 'flux://item#section', predicate: 'p1', target: 't1' },
171
+ ];
172
+ const specialNext = [
173
+ ...specialPrev,
174
+ { source: 'flux://item#section', predicate: 'p2', target: 't2' },
175
+ ];
176
+ const result = detectDeltaPath(specialPrev, specialNext);
177
+ expect(result.useDelta).toBe(false);
178
+ expect(result.reason).toBe('existing source got new links');
179
+ });
180
+ });
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Subscription Pool — deduplicates identical SPARQL subscriptions.
3
+ *
4
+ * When multiple UI components subscribe to the same SPARQL query on the same
5
+ * perspective, the pool shares a single `subscribeQuery()` call and distributes
6
+ * results to all registered callbacks. Hydration happens once per result set,
7
+ * then is shared across all subscribers.
8
+ *
9
+ * Key: `perspectiveUUID + sparqlQuery`
10
+ */
11
+ import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
12
+ type HydrateCallback = (rawResult: any) => Promise<any>;
13
+ type ResultCallback = (hydratedResult: any) => void;
14
+ export interface PooledSubscription {
15
+ /** The initial (hydrated) result */
16
+ initialResult: any;
17
+ /** Unsubscribe this particular callback from the pool */
18
+ dispose: () => void;
19
+ }
20
+ /**
21
+ * Subscribe to a SPARQL query, sharing the underlying subscription
22
+ * with any other subscribers using the same perspective + query.
23
+ *
24
+ * @param perspective - The perspective proxy
25
+ * @param sparqlQuery - The SPARQL query text
26
+ * @param hydrate - Async function that takes raw SPARQL results and returns hydrated results
27
+ * @param onResult - Callback for subsequent result updates (hydrated)
28
+ * @returns PooledSubscription with initial result and dispose function
29
+ */
30
+ export declare function pooledSubscribe(perspective: PerspectiveProxy, sparqlQuery: string, hydrate: HydrateCallback, onResult: ResultCallback): Promise<PooledSubscription>;
31
+ /**
32
+ * Clear the entire pool (for testing).
33
+ */
34
+ export declare function clearSubscriptionPool(): void;
35
+ /**
36
+ * Get the current pool size (for testing).
37
+ */
38
+ export declare function subscriptionPoolSize(): number;
39
+ export {};
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Subscription Pool — deduplicates identical SPARQL subscriptions.
3
+ *
4
+ * When multiple UI components subscribe to the same SPARQL query on the same
5
+ * perspective, the pool shares a single `subscribeQuery()` call and distributes
6
+ * results to all registered callbacks. Hydration happens once per result set,
7
+ * then is shared across all subscribers.
8
+ *
9
+ * Key: `perspectiveUUID + sparqlQuery`
10
+ */
11
+ const pool = new Map();
12
+ function makeKey(perspectiveUUID, sparqlQuery) {
13
+ return `${perspectiveUUID}::${sparqlQuery}`;
14
+ }
15
+ /**
16
+ * Subscribe to a SPARQL query, sharing the underlying subscription
17
+ * with any other subscribers using the same perspective + query.
18
+ *
19
+ * @param perspective - The perspective proxy
20
+ * @param sparqlQuery - The SPARQL query text
21
+ * @param hydrate - Async function that takes raw SPARQL results and returns hydrated results
22
+ * @param onResult - Callback for subsequent result updates (hydrated)
23
+ * @returns PooledSubscription with initial result and dispose function
24
+ */
25
+ export async function pooledSubscribe(perspective, sparqlQuery, hydrate, onResult) {
26
+ const uuid = perspective.uuid || perspective.handle?.uuid || '';
27
+ const key = makeKey(uuid, sparqlQuery);
28
+ const entry = pool.get(key);
29
+ const subscriber = { onResult, hydrate };
30
+ if (entry) {
31
+ // Join existing subscription
32
+ entry.callbacks.add(subscriber);
33
+ entry.refCount++;
34
+ // Hydrate latest result for this new subscriber
35
+ let initialResult;
36
+ if (entry.latestHydrated !== undefined) {
37
+ initialResult = entry.latestHydrated;
38
+ }
39
+ else if (entry.latestRaw !== undefined) {
40
+ initialResult = await hydrate(entry.latestRaw);
41
+ }
42
+ return {
43
+ initialResult,
44
+ dispose: () => disposeSubscriber(key, subscriber),
45
+ };
46
+ }
47
+ // Create new subscription
48
+ const subscription = await perspective.subscribeQuery(sparqlQuery);
49
+ const newEntry = {
50
+ subscription,
51
+ callbacks: new Set([subscriber]),
52
+ latestRaw: subscription.result,
53
+ latestHydrated: undefined,
54
+ hydrating: false,
55
+ refCount: 1,
56
+ };
57
+ pool.set(key, newEntry);
58
+ // Set up shared result handler with delta optimization
59
+ subscription.onResult(async (rawResult) => {
60
+ const prevRaw = newEntry.latestRaw;
61
+ newEntry.latestRaw = rawResult;
62
+ newEntry.hydrating = true;
63
+ try {
64
+ const firstSub = newEntry.callbacks.values().next().value;
65
+ if (firstSub) {
66
+ // Delta optimization: if the new result is strictly an addition
67
+ // (all previous rows still present + new rows), only hydrate the
68
+ // new rows and append them to the cached hydrated result.
69
+ const prevArr = Array.isArray(prevRaw) ? prevRaw : [];
70
+ const newArr = Array.isArray(rawResult) ? rawResult : [];
71
+ const prevHydrated = newEntry.latestHydrated;
72
+ if (prevHydrated &&
73
+ Array.isArray(prevHydrated) &&
74
+ newArr.length > prevArr.length &&
75
+ newArr.length - prevArr.length <= 5 // small delta — worth optimizing
76
+ ) {
77
+ // Build a set of source URIs from previous results for quick lookup
78
+ const prevSources = new Set(prevArr.map((r) => `${r.source}|${r.predicate}|${r.target}`));
79
+ const addedRows = newArr.filter((r) => !prevSources.has(`${r.source}|${r.predicate}|${r.target}`));
80
+ // Check that no rows were removed (pure addition)
81
+ const newSources = new Set(newArr.map((r) => `${r.source}|${r.predicate}|${r.target}`));
82
+ const removedRows = prevArr.filter((r) => !newSources.has(`${r.source}|${r.predicate}|${r.target}`));
83
+ if (removedRows.length === 0 && addedRows.length > 0) {
84
+ // Verify ALL added rows have sources not in previous results.
85
+ // If any added row's source matches an existing source, it means
86
+ // an existing instance got new links — we need full rehydration.
87
+ const prevSourceIds = new Set(prevArr.map((r) => r.source));
88
+ const allNewSources = addedRows.every((r) => !prevSourceIds.has(r.source));
89
+ if (allNewSources) {
90
+ // Pure addition of new instances — hydrate only the new rows
91
+ try {
92
+ const deltaHydrated = await firstSub.hydrate(addedRows);
93
+ if (Array.isArray(deltaHydrated)) {
94
+ const merged = [...prevHydrated, ...deltaHydrated];
95
+ newEntry.latestHydrated = merged;
96
+ for (const cb of newEntry.callbacks) {
97
+ try {
98
+ cb.onResult(merged);
99
+ }
100
+ catch (e) { /* subscriber error */ }
101
+ }
102
+ return; // Delta path succeeded
103
+ }
104
+ }
105
+ catch {
106
+ // Delta hydration failed — fall through to full hydration
107
+ }
108
+ }
109
+ }
110
+ }
111
+ // Full hydration fallback
112
+ const hydrated = await firstSub.hydrate(rawResult);
113
+ newEntry.latestHydrated = hydrated;
114
+ // Distribute to all callbacks
115
+ for (const cb of newEntry.callbacks) {
116
+ try {
117
+ cb.onResult(hydrated);
118
+ }
119
+ catch (e) { /* subscriber error */ }
120
+ }
121
+ }
122
+ }
123
+ finally {
124
+ newEntry.hydrating = false;
125
+ }
126
+ });
127
+ // Hydrate initial result
128
+ const initialResult = await hydrate(subscription.result);
129
+ newEntry.latestHydrated = initialResult;
130
+ return {
131
+ initialResult,
132
+ dispose: () => disposeSubscriber(key, subscriber),
133
+ };
134
+ }
135
+ function disposeSubscriber(key, subscriber) {
136
+ const entry = pool.get(key);
137
+ if (!entry)
138
+ return;
139
+ entry.callbacks.delete(subscriber);
140
+ entry.refCount--;
141
+ if (entry.refCount <= 0) {
142
+ // Last subscriber — tear down the underlying subscription
143
+ if (entry.subscription?.dispose) {
144
+ entry.subscription.dispose();
145
+ }
146
+ pool.delete(key);
147
+ }
148
+ }
149
+ /**
150
+ * Clear the entire pool (for testing).
151
+ */
152
+ export function clearSubscriptionPool() {
153
+ for (const entry of pool.values()) {
154
+ if (entry.subscription?.dispose) {
155
+ entry.subscription.dispose();
156
+ }
157
+ }
158
+ pool.clear();
159
+ }
160
+ /**
161
+ * Get the current pool size (for testing).
162
+ */
163
+ export function subscriptionPoolSize() {
164
+ return pool.size;
165
+ }
@@ -0,0 +1 @@
1
+ export {};