@_linked/core 2.35.0 → 2.36.1

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 (34) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +30 -0
  3. package/lib/esm/index.d.ts +3 -0
  4. package/lib/esm/index.js +4 -0
  5. package/lib/esm/index.js.map +1 -1
  6. package/lib/esm/live/LiveQueryStore.js +2 -1
  7. package/lib/esm/live/LiveQueryStore.js.map +1 -1
  8. package/lib/esm/queries/FieldSet.d.ts +7 -0
  9. package/lib/esm/queries/FieldSet.js +25 -4
  10. package/lib/esm/queries/FieldSet.js.map +1 -1
  11. package/lib/esm/queries/MutationQuery.js +3 -2
  12. package/lib/esm/queries/MutationQuery.js.map +1 -1
  13. package/lib/esm/queries/PropertyPath.js +2 -1
  14. package/lib/esm/queries/PropertyPath.js.map +1 -1
  15. package/lib/esm/queries/QueryBuilder.js +2 -1
  16. package/lib/esm/queries/QueryBuilder.js.map +1 -1
  17. package/lib/esm/queries/QueryContext.js +2 -0
  18. package/lib/esm/queries/QueryContext.js.map +1 -1
  19. package/lib/esm/queries/SelectQuery.js +6 -1
  20. package/lib/esm/queries/SelectQuery.js.map +1 -1
  21. package/lib/esm/queries/resolveShape.js +2 -1
  22. package/lib/esm/queries/resolveShape.js.map +1 -1
  23. package/lib/esm/shapes/validation.js +9 -4
  24. package/lib/esm/shapes/validation.js.map +1 -1
  25. package/lib/esm/utils/linkedError.d.ts +35 -0
  26. package/lib/esm/utils/linkedError.js +52 -0
  27. package/lib/esm/utils/linkedError.js.map +1 -0
  28. package/lib/esm/utils/sharedState.d.ts +25 -0
  29. package/lib/esm/utils/sharedState.js +34 -0
  30. package/lib/esm/utils/sharedState.js.map +1 -0
  31. package/lib/esm/utils/unresolvedShape.d.ts +44 -0
  32. package/lib/esm/utils/unresolvedShape.js +68 -0
  33. package/lib/esm/utils/unresolvedShape.js.map +1 -0
  34. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.36.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#353](https://github.com/linked-fw/core/pull/353) [`20a88f7`](https://github.com/linked-fw/core/commit/20a88f789a1f11054dca6907ba9e1d09cb0165b9) Thanks [@flyon](https://github.com/flyon)! - Errors for a shape that does not resolve name the scope only while a scoped `ShapeCatalog` is active (`withShapeCatalog`), as `Shape class not found for <Place> (property 'home' of '<Person>' points at it; not among the shapes in scope 'p1#main')`. Against the global registry the message ends after "points at it" (`… (property 'home' of '<Person>' points at it)`), and an error for a query's own shape is just its opening sentence. The opening of each message and the `shapeIri`, `property`, `propertyIri`, `ownerShapeIri` and `catalog` fields are unchanged.
8
+
9
+ ## 2.36.0
10
+
11
+ ### Minor Changes
12
+
13
+ - [#349](https://github.com/linked-fw/core/pull/349) [`c68a46a`](https://github.com/linked-fw/core/commit/c68a46acab79aa36ba0d5282f01af535ac5253b6) Thanks [@flyon](https://github.com/flyon)! - Add `sharedState(pkg, name, init)`, which keeps module state on `globalThis` under `Symbol.for('<pkg>:<name>')` so two copies of a module share it, and `brandLinkedError(Cls, pkg, name)` with `isLinkedError(err, Cls)`, which recognises an error thrown by another copy of its defining module, where `instanceof` does not.
14
+
15
+ ## 2.35.1
16
+
17
+ ### Patch Changes
18
+
19
+ - [#350](https://github.com/linked-fw/core/pull/350) [`77a7b77`](https://github.com/linked-fw/core/commit/77a7b778fba33e91413e6037221b8db65544c405) Thanks [@flyon](https://github.com/flyon)! - Errors for a shape that does not resolve name the property that points at it, the shape that declares that property, and the active catalog: `Shape class not found for <Place> (property 'home' of '<Person>' points at it; catalog 'p1#main' does not hold it)`. The errors stay plain `Error`s (and `ShapeValidationError` for `validate`), now thrown as `UnresolvedShapeError` with `shapeIri`, `property`, `propertyIri`, `ownerShapeIri` and `catalog` fields. `fromJSON` no longer reads a relation's sub-fields against the parent shape when the relation's value shape does not resolve; it throws the same error.
20
+
3
21
  ## 2.35.0
4
22
 
5
23
  ### Minor Changes
package/README.md CHANGED
@@ -1368,6 +1368,36 @@ await Team.update({members: {add: [{id: personId}]}}).for({id: teamId});
1368
1368
  - A dataset can report changes made elsewhere through the optional `IDataset.subscribeChanges(listener)`;
1369
1369
  `publishChange(event)` does the same from application code; `invalidate(Shape | {id} | query)` is the manual lever.
1370
1370
 
1371
+ ## Shared state and error brands
1372
+
1373
+ A framework module can be evaluated twice in one process (under `linked start`, once by Vite's SSR
1374
+ module runner and once by Node) or twice in a browser. Two conventions make that second copy harmless:
1375
+
1376
+ - **Module state lives on `globalThis`.** A module-level value that more than one caller reads or writes
1377
+ (a registry, a configured singleton, a static that callers assign) is kept with `sharedState`, under
1378
+ `Symbol.for('<pkg>:<name>')`, so every copy reads and writes the same container:
1379
+
1380
+ ```ts
1381
+ import {sharedState} from '@_linked/core';
1382
+ const state = sharedState('@_linked/my-pkg', 'Mailer.state', () => ({provider: null as Provider | null}));
1383
+ export function setProvider(p: Provider) { state.provider = p; }
1384
+ ```
1385
+
1386
+ - **Errors are matched by brand, not `instanceof`.** A framework error class is branded once with
1387
+ `brandLinkedError(Cls, '<pkg>', '<ClassName>')`, and code that catches an error from another package
1388
+ checks it with `isLinkedError(err, Cls)`. That matches an instance thrown by any copy of the defining
1389
+ module, and a subclass instance against its base.
1390
+
1391
+ ```ts
1392
+ export class StoreError extends Error {}
1393
+ brandLinkedError(StoreError, '@_linked/my-pkg', 'StoreError');
1394
+ // elsewhere
1395
+ if (isLinkedError(err, StoreError)) { /* … */ }
1396
+ ```
1397
+
1398
+ The full convention, including what stays per copy and how React contexts are handled, is in
1399
+ [shared state and error brands](https://github.com/linked-fw/cli/blob/main/docs/architecture/shared-state-and-error-brands.md).
1400
+
1371
1401
  ## TODO
1372
1402
 
1373
1403
  - Allow `preloadFor` to accept another query (not just a component).
@@ -7,8 +7,11 @@ export { rdfList } from './shapes/List.js';
7
7
  export { serializePathToNodeData } from './shapes/serializePathToNodeData.js';
8
8
  export { Shape } from './shapes/Shape.js';
9
9
  export { validate, assertValid, ShapeValidationError } from './shapes/validation.js';
10
+ export { UnresolvedShapeError, type UnresolvedShapeDetails } from './utils/unresolvedShape.js';
10
11
  export type { ValidationReport, ValidationResult, ValidationMode, ValidateOptions, ValidatableShape, } from './shapes/validation.js';
11
12
  export { LinkedStorage } from './utils/LinkedStorage.js';
13
+ export { sharedState, sharedStateKey } from './utils/sharedState.js';
14
+ export { brandLinkedError, isLinkedError, linkedErrorBrand } from './utils/linkedError.js';
12
15
  export { SelectBuilder, QueryBuilder } from './queries/QueryBuilder.js';
13
16
  export { lower } from './queries/lower.js';
14
17
  export type { LowerableQuery } from './queries/lower.js';
package/lib/esm/index.js CHANGED
@@ -15,7 +15,11 @@ export { serializePathToNodeData } from './shapes/serializePathToNodeData.js';
15
15
  export { Shape } from './shapes/Shape.js';
16
16
  // SHACL-aligned validation of plain data objects against a shape.
17
17
  export { validate, assertValid, ShapeValidationError } from './shapes/validation.js';
18
+ export { UnresolvedShapeError } from './utils/unresolvedShape.js';
18
19
  export { LinkedStorage } from './utils/LinkedStorage.js';
20
+ // Conventions that make a second copy of a framework module harmless.
21
+ export { sharedState, sharedStateKey } from './utils/sharedState.js';
22
+ export { brandLinkedError, isLinkedError, linkedErrorBrand } from './utils/linkedError.js';
19
23
  // New dynamic query building API (Phase 2)
20
24
  export { SelectBuilder, QueryBuilder } from './queries/QueryBuilder.js';
21
25
  export { lower } from './queries/lower.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,0DAA0D;AAC1D,OAAO,mBAAmB,CAAC;AAC3B,8EAA8E;AAC9E,OAAO,WAAW,CAAC;AACnB,OAAO,EAAC,UAAU,EAAE,SAAS,EAAC,MAAM,wBAAwB,CAAC;AAE7D,OAAO,EACL,mBAAmB,EACnB,qBAAqB,EACrB,2BAA2B,GAC5B,MAAM,mCAAmC,CAAC;AAC3C,OAAO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,OAAO,EAAC,aAAa,EAAC,MAAM,4BAA4B,CAAC;AAGzD,8CAA8C;AAC9C,OAAO,EAAC,cAAc,EAAC,MAAM,iCAAiC,CAAC;AAE/D,OAAO,EAAC,IAAI,EAAC,MAAM,uBAAuB,CAAC;AAe3C,sEAAsE;AACtE,OAAO,EACL,cAAc,EACd,WAAW,GACZ,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,cAAc,EACd,iBAAiB,GAClB,MAAM,gCAAgC,CAAC;AAWxC,0FAA0F;AAC1F,OAAO,EAAC,iBAAiB,EAAE,eAAe,EAAC,MAAM,gCAAgC,CAAC;AAElF,OAAO,EAAC,qBAAqB,EAAC,MAAM,2BAA2B,CAAC;AAEhE,mDAAmD;AACnD,OAAO,EAAC,cAAc,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,aAAa,EAAE,UAAU,EAAC,MAAM,0BAA0B,CAAC","sourcesContent":["/*\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\n// Registers every shape core defines (side effects only).\nimport './shapes/index.js';\n// Registers the live-query store so `query.live()` works (side effects only).\nimport './live.js';\nexport {syncShapes, syncShape} from './shapes/syncShapes.js';\nexport type {SyncShapesOptions, SyncShapeOptions} from './shapes/syncShapes.js';\nexport {\n singleOwnerShapeIri,\n singleOwnerProperties,\n buildSingleOwnerConstraints,\n} from './shapes/singleOwnerConstraint.js';\nexport {rdfList} from './shapes/List.js';\nexport {serializePathToNodeData} from './shapes/serializePathToNodeData.js';\n// Core public API surface (documented as root imports in the README).\nexport {Shape} from './shapes/Shape.js';\n// SHACL-aligned validation of plain data objects against a shape.\nexport {validate, assertValid, ShapeValidationError} from './shapes/validation.js';\nexport type {\n ValidationReport,\n ValidationResult,\n ValidationMode,\n ValidateOptions,\n ValidatableShape,\n} from './shapes/validation.js';\nexport {LinkedStorage} from './utils/LinkedStorage.js';\n// New dynamic query building API (Phase 2)\nexport {SelectBuilder, QueryBuilder} from './queries/QueryBuilder.js';\nexport {lower} from './queries/lower.js';\nexport type {LowerableQuery} from './queries/lower.js';\nexport {fromJSON} from './queries/fromJSON.js';\nexport type {QueryJSON, FromJSONOptions} from './queries/fromJSON.js';\n// Shape catalogs: resolve queries against a set of shapes without registering them.\nexport {\n ShapeCatalog,\n withShapeCatalog,\n getActiveShapeCatalog,\n catalogOf,\n shapeCatalogKey,\n} from './utils/ShapeCatalog.js';\nexport {\n getQueryContext,\n setQueryContext,\n subscribeQueryContext,\n PendingQueryContext,\n UnresolvedContextError,\n} from './queries/QueryContext.js';\nexport {subscribeQueryDispatch} from './queries/queryDispatch.js';\nexport type {QueryDispatchEvent, QueryDispatchListener} from './queries/queryDispatch.js';\nexport {\n CONTEXT_REF_KEY,\n encodeContextRef,\n isContextRefJSON,\n resolveContextId,\n} from './queries/ContextRef.js';\nexport type {ContextRefJSON} from './queries/ContextRef.js';\nexport {PropertyPath, walkPropertyPath} from './queries/PropertyPath.js';\n\n// Phase 3a — FieldSet\nexport {FieldSet} from './queries/FieldSet.js';\nexport type {FieldSetEntry, FieldSetInput, FieldSetJSON, FieldSetFieldJSON} from './queries/FieldSet.js';\n\n// Phase 4 — Serialization types\nexport type {QueryBuilderJSON} from './queries/QueryBuilder.js';\n\n// Phase 3b — Mutation builders\nexport {AskBuilder, isAskQuery} from './queries/AskBuilder.js';\nexport type {AskSpec} from './queries/AskBuilder.js';\nexport type {AskQuery, AskQueryJSON, RawAskInput} from './queries/AskQuery.js';\nexport {CountBuilder, isCountQuery} from './queries/CountBuilder.js';\nexport type {CountSpec} from './queries/CountBuilder.js';\nexport type {CountQuery, CountQueryJSON, RawCountInput} from './queries/CountQuery.js';\nexport {CreateBuilder} from './queries/CreateBuilder.js';\nexport {UpdateBuilder} from './queries/UpdateBuilder.js';\nexport {DeleteBuilder} from './queries/DeleteBuilder.js';\nexport type {DeleteId} from './queries/DeleteBuilder.js';\n\n// Expressions — computed fields and functions\nexport {ExpressionNode} from './expressions/ExpressionNode.js';\nexport type {ExpressionInput, PropertyRefMap} from './expressions/ExpressionNode.js';\nexport {Expr} from './expressions/Expr.js';\nexport type {\n ExpressionUpdateProxy,\n ExpressionUpdateResult,\n BaseExpressionMethods,\n NumericExpressionMethods,\n StringExpressionMethods,\n DateExpressionMethods,\n BooleanExpressionMethods,\n} from './expressions/ExpressionMethods.js';\n\n// Phase 5 — Component query integration\nexport type {LinkedComponentInterface, QueryComponentLike} from './queries/SelectQuery.js';\n\n\n// Mutation DSL-JSON serialization (create/update/delete to/from JSON)\nexport {\n encodeNodeData,\n encodeValue,\n} from './queries/MutationSerialization.js';\nexport {\n decodeNodeData,\n lowerMutationJSON,\n} from './queries/lowerMutationJSON.js';\nexport type {\n MutationJSON,\n CreateMutationJSON,\n UpdateMutationJSON,\n DeleteMutationJSON,\n MutationValueJSON,\n MutationNodeDataJSON,\n} from './queries/MutationSerialization.js';\n\n\n// Live-query dependency helpers — what a query reads and a mutation writes, as predicates\nexport {queryDependencies, mutationEffects} from './queries/queryDependencies.js';\nexport type {QueryDependencies, MutationEffects} from './queries/queryDependencies.js';\nexport {findPropertyShapeById} from './shapes/nodeShapeData.js';\n\n// Live queries — see documentation/live-queries.md\nexport {LiveQueryStore, getLiveQueryStore, resetLiveQueryStore, publishChange, invalidate} from './live/LiveQueryStore.js';\nexport type {ChangeEvent} from './live/changes.js';\nexport type {\n LiveQuery,\n LiveState,\n LiveStatus,\n LiveListener,\n LiveQueryOptions,\n LiveQueryStoreOptions,\n} from './live/LiveQueryStore.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,0DAA0D;AAC1D,OAAO,mBAAmB,CAAC;AAC3B,8EAA8E;AAC9E,OAAO,WAAW,CAAC;AACnB,OAAO,EAAC,UAAU,EAAE,SAAS,EAAC,MAAM,wBAAwB,CAAC;AAE7D,OAAO,EACL,mBAAmB,EACnB,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AC,MAAM,uBAAuB,CAAC;AAM/C,+BAA+B;AAC/B,OAAO,EAAC,UAAU,EAAE,UAAU,EAAC,MAAM,yBAAyB,CAAC;AAG/D,OAAO,EAAC,YAAY,EAAE,YAAY,EAAC,MAAM,2BAA2B,CAAC;AAGrE,OAAO,EAAC,aAAa,EAAC,MAAM,4BAA4B,CAAC;AACzD,OAAO,EAAC,aAAa,EAAC,MAAM,4BAA4B,CAAC;AACzD,OAAO,EAAC,aAAa,EAAC,MAAM,4BAA4B,CAAC;AAGzD,8CAA8C;AAC9C,OAAO,EAAC,cAAc,EAAC,MAAM,iCAAiC,CAAC;AAE/D,OAAO,EAAC,IAAI,EAAC,MAAM,uBAAuB,CAAC;AAe3C,sEAAsE;AACtE,OAAO,EACL,cAAc,EACd,WAAW,GACZ,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,cAAc,EACd,iBAAiB,GAClB,MAAM,gCAAgC,CAAC;AAWxC,0FAA0F;AAC1F,OAAO,EAAC,iBAAiB,EAAE,eAAe,EAAC,MAAM,gCAAgC,CAAC;AAElF,OAAO,EAAC,qBAAqB,EAAC,MAAM,2BAA2B,CAAC;AAEhE,mDAAmD;AACnD,OAAO,EAAC,cAAc,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,aAAa,EAAE,UAAU,EAAC,MAAM,0BAA0B,CAAC","sourcesContent":["/*\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\n// Registers every shape core defines (side effects only).\nimport './shapes/index.js';\n// Registers the live-query store so `query.live()` works (side effects only).\nimport './live.js';\nexport {syncShapes, syncShape} from './shapes/syncShapes.js';\nexport type {SyncShapesOptions, SyncShapeOptions} from './shapes/syncShapes.js';\nexport {\n singleOwnerShapeIri,\n singleOwnerProperties,\n buildSingleOwnerConstraints,\n} from './shapes/singleOwnerConstraint.js';\nexport {rdfList} from './shapes/List.js';\nexport {serializePathToNodeData} from './shapes/serializePathToNodeData.js';\n// Core public API surface (documented as root imports in the README).\nexport {Shape} from './shapes/Shape.js';\n// SHACL-aligned validation of plain data objects against a shape.\nexport {validate, assertValid, ShapeValidationError} from './shapes/validation.js';\nexport {UnresolvedShapeError, type UnresolvedShapeDetails} from './utils/unresolvedShape.js';\nexport type {\n ValidationReport,\n ValidationResult,\n ValidationMode,\n ValidateOptions,\n ValidatableShape,\n} from './shapes/validation.js';\nexport {LinkedStorage} from './utils/LinkedStorage.js';\n// Conventions that make a second copy of a framework module harmless.\nexport {sharedState, sharedStateKey} from './utils/sharedState.js';\nexport {brandLinkedError, isLinkedError, linkedErrorBrand} from './utils/linkedError.js';\n// New dynamic query building API (Phase 2)\nexport {SelectBuilder, QueryBuilder} from './queries/QueryBuilder.js';\nexport {lower} from './queries/lower.js';\nexport type {LowerableQuery} from './queries/lower.js';\nexport {fromJSON} from './queries/fromJSON.js';\nexport type {QueryJSON, FromJSONOptions} from './queries/fromJSON.js';\n// Shape catalogs: resolve queries against a set of shapes without registering them.\nexport {\n ShapeCatalog,\n withShapeCatalog,\n getActiveShapeCatalog,\n catalogOf,\n shapeCatalogKey,\n} from './utils/ShapeCatalog.js';\nexport {\n getQueryContext,\n setQueryContext,\n subscribeQueryContext,\n PendingQueryContext,\n UnresolvedContextError,\n} from './queries/QueryContext.js';\nexport {subscribeQueryDispatch} from './queries/queryDispatch.js';\nexport type {QueryDispatchEvent, QueryDispatchListener} from './queries/queryDispatch.js';\nexport {\n CONTEXT_REF_KEY,\n encodeContextRef,\n isContextRefJSON,\n resolveContextId,\n} from './queries/ContextRef.js';\nexport type {ContextRefJSON} from './queries/ContextRef.js';\nexport {PropertyPath, walkPropertyPath} from './queries/PropertyPath.js';\n\n// Phase 3a — FieldSet\nexport {FieldSet} from './queries/FieldSet.js';\nexport type {FieldSetEntry, FieldSetInput, FieldSetJSON, FieldSetFieldJSON} from './queries/FieldSet.js';\n\n// Phase 4 — Serialization types\nexport type {QueryBuilderJSON} from './queries/QueryBuilder.js';\n\n// Phase 3b — Mutation builders\nexport {AskBuilder, isAskQuery} from './queries/AskBuilder.js';\nexport type {AskSpec} from './queries/AskBuilder.js';\nexport type {AskQuery, AskQueryJSON, RawAskInput} from './queries/AskQuery.js';\nexport {CountBuilder, isCountQuery} from './queries/CountBuilder.js';\nexport type {CountSpec} from './queries/CountBuilder.js';\nexport type {CountQuery, CountQueryJSON, RawCountInput} from './queries/CountQuery.js';\nexport {CreateBuilder} from './queries/CreateBuilder.js';\nexport {UpdateBuilder} from './queries/UpdateBuilder.js';\nexport {DeleteBuilder} from './queries/DeleteBuilder.js';\nexport type {DeleteId} from './queries/DeleteBuilder.js';\n\n// Expressions — computed fields and functions\nexport {ExpressionNode} from './expressions/ExpressionNode.js';\nexport type {ExpressionInput, PropertyRefMap} from './expressions/ExpressionNode.js';\nexport {Expr} from './expressions/Expr.js';\nexport type {\n ExpressionUpdateProxy,\n ExpressionUpdateResult,\n BaseExpressionMethods,\n NumericExpressionMethods,\n StringExpressionMethods,\n DateExpressionMethods,\n BooleanExpressionMethods,\n} from './expressions/ExpressionMethods.js';\n\n// Phase 5 — Component query integration\nexport type {LinkedComponentInterface, QueryComponentLike} from './queries/SelectQuery.js';\n\n\n// Mutation DSL-JSON serialization (create/update/delete to/from JSON)\nexport {\n encodeNodeData,\n encodeValue,\n} from './queries/MutationSerialization.js';\nexport {\n decodeNodeData,\n lowerMutationJSON,\n} from './queries/lowerMutationJSON.js';\nexport type {\n MutationJSON,\n CreateMutationJSON,\n UpdateMutationJSON,\n DeleteMutationJSON,\n MutationValueJSON,\n MutationNodeDataJSON,\n} from './queries/MutationSerialization.js';\n\n\n// Live-query dependency helpers — what a query reads and a mutation writes, as predicates\nexport {queryDependencies, mutationEffects} from './queries/queryDependencies.js';\nexport type {QueryDependencies, MutationEffects} from './queries/queryDependencies.js';\nexport {findPropertyShapeById} from './shapes/nodeShapeData.js';\n\n// Live queries — see documentation/live-queries.md\nexport {LiveQueryStore, getLiveQueryStore, resetLiveQueryStore, publishChange, invalidate} from './live/LiveQueryStore.js';\nexport type {ChangeEvent} from './live/changes.js';\nexport type {\n LiveQuery,\n LiveState,\n LiveStatus,\n LiveListener,\n LiveQueryOptions,\n LiveQueryStoreOptions,\n} from './live/LiveQueryStore.js';\n"]}
@@ -22,6 +22,7 @@ import { effectsHash, normalizeChange } from './changes.js';
22
22
  import { selectInstances } from './matcher.js';
23
23
  import { kindOf, paramsKey, splitQuery, stripSubjects, templateKeyFor, } from './keys.js';
24
24
  import { setLiveQueryStore, peekLiveQueryStore } from './registry.js';
25
+ import { isLinkedError } from '../utils/linkedError.js';
25
26
  const IDLE = Object.freeze({ status: 'pending', notFound: false, refreshing: false });
26
27
  // ---------------------------------------------------------------------------
27
28
  // Store
@@ -105,7 +106,7 @@ export class LiveQueryStore {
105
106
  template.depsProvisional = false;
106
107
  }
107
108
  catch (err) {
108
- if (!(err instanceof UnresolvedContextError))
109
+ if (!isLinkedError(err, UnresolvedContextError))
109
110
  throw err;
110
111
  if (template.deps)
111
112
  return template.deps; // still provisional
@@ -1 +1 @@
1
- {"version":3,"file":"LiveQueryStore.js","sourceRoot":"","sources":["../../../src/live/LiveQueryStore.ts"],"names":[],"mappings":";;;;;;;;;AAAA;;;;GAIG;AACH,OAAO,EAAC,aAAa,EAAC,MAAM,2BAA2B,CAAC;AAExD,OAAO,EAAC,qBAAqB,EAAE,sBAAsB,EAAC,MAAM,4BAA4B,CAAC;AACzF,OAAO,EAAC,gBAAgB,EAAC,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAC,sBAAsB,EAA0B,MAAM,6BAA6B,CAAC;AAC5F,OAAO,EACL,eAAe,EACf,iBAAiB,GAGlB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,SAAS,EACT,qBAAqB,EACrB,aAAa,EACb,gBAAgB,GACjB,MAAM,wBAAwB,CAAC;AAGhC,OAAO,EAAC,WAAW,EAAE,eAAe,EAAsC,MAAM,cAAc,CAAC;AAC/F,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iBAAiB;IAC/B,IAAI,KAAK,GAAG,kBAAkB,EAAE,CAAC;IACjC,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,KAAK,GAAG,IAAI,cAAc,EAAE,CAAC;QAC7B,iBAAiB,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,aAAa,CAAC,KAAkB;IAC9C,iBAAiB,EAAE,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AAC5C,CAAC;AAED,uGAAuG;AACvG,MAAM,UAAU,UAAU,CAAC,MAA8E;IACvG,iBAAiB,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;AACzC,CAAC;AAID,kDAAkD;AAClD,MAAM,UAAU,mBAAmB;;IACjC,MAAA,kBAAkB,EAAE,0CAAE,OAAO,EAAE,CAAC;IAChC,MAAM,KAAK,GAAG,IAAI,cAAc,EAAE,CAAC;IACnC,iBAAiB,CAAC,KAAK,CAAC,CAAC;IACzB,OAAO,KAAK,CAAC;AACf,CAAC;AAED,wEAAwE;AACxE,IAAI,CAAC,kBAAkB,EAAE;IAAE,iBAAiB,CAAC,IAAI,cAAc,EAAE,CAAC,CAAC","sourcesContent":["/*\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport {LinkedStorage} from '../utils/LinkedStorage.js';\nimport type {IDataset} from '../interfaces/IDataset.js';\nimport {subscribeQueryContext, UnresolvedContextError} from '../queries/QueryContext.js';\nimport {resolveContextId} from '../queries/ContextRef.js';\nimport {subscribeQueryDispatch, type QueryDispatchEvent} from '../queries/queryDispatch.js';\nimport {\n mutationEffects,\n queryDependencies,\n type MutationEffects,\n type QueryDependencies,\n} from '../queries/queryDependencies.js';\nimport {\n catalogOf,\n getActiveShapeCatalog,\n getShapeClass,\n withShapeCatalog,\n} from '../utils/ShapeClass.js';\nimport type {ShapeCatalog} from '../utils/ShapeCatalog.js';\nimport type {ShapeConstructor} from '../shapes/Shape.js';\nimport {effectsHash, normalizeChange, type ChangeEvent, type ChangeOrigin} from './changes.js';\nimport {selectInstances} from './matcher.js';\nimport {\n kindOf,\n paramsKey,\n splitQuery,\n stripSubjects,\n templateKeyFor,\n type InstanceParams,\n type LiveBuilder,\n type LiveQueryKind,\n} from './keys.js';\nimport {setLiveQueryStore, peekLiveQueryStore} from './registry.js';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport type LiveStatus = 'pending' | 'loading' | 'success' | 'error';\n\n/**\n * What a live query currently knows.\n *\n * - `pending`: nothing requested yet (no storage configured, or the subject is\n * a query context that has not been set).\n * - `loading`: first request in flight, no data yet.\n * - `success` / `error`: last request settled. On error the previous `data`,\n * if any, is kept so a screen does not go blank over a transient failure.\n * - `refreshing`: a request is in flight while `data` is present.\n * - `notFound`: a single-subject query answered `null`.\n *\n * The object is replaced (never mutated) on every change, so it is safe as a\n * `useSyncExternalStore` snapshot.\n */\nexport type LiveState<R = unknown> = {\n status: LiveStatus;\n data?: R;\n error?: Error;\n notFound: boolean;\n refreshing: boolean;\n};\n\nexport type LiveListener<R = unknown> = (state: LiveState<R>) => void;\n\nexport type LiveQueryOptions = {\n /** Metadata for the template registry (`prepare()`), not identity. */\n name?: string;\n /** `false` opts this template — every query with this exact template — out of automatic invalidation. Default `true`. */\n reactive?: boolean;\n /** A pinned template survives having no instances (component definitions, `prepare()`). */\n pinned?: boolean;\n};\n\n/**\n * The handle returned by `query.live()`.\n *\n * It is `PromiseLike`: `await live` resolves with the first successful `data`\n * (or rejects with the first error) and the handle stays live afterwards. It\n * waits for as long as storage is not configured or a pending query context is\n * not set. Because the handle is thenable, do not `return` it from an `async`\n * function — the promise machinery would unwrap it. `subscribe(cb)` follows\n * the Svelte store contract (returns the unsubscribe function). `close()`\n * detaches every listener added through this handle; the handle can be used\n * again afterwards, which is what React's StrictMode needs.\n */\nexport interface LiveQuery<R = unknown> extends PromiseLike<R> {\n readonly state: LiveState<R>;\n /** Identity of the underlying instance (template key + params). */\n readonly key: string;\n subscribe(listener: LiveListener<R>): () => void;\n /** Refetch now, keeping the current data until the response lands. */\n refresh(): Promise<void>;\n /**\n * Local edit of the cached data, no request; overwritten by the next refetch\n * and visible to every subscriber of the same query. An object merges into\n * object data; an array or a function replaces.\n */\n patch(partial: Partial<R> | ((current: R) => R)): void;\n /** Detach every listener added through this handle. */\n close(): void;\n}\n\nexport type Template = {\n key: string;\n kind: LiveQueryKind;\n /**\n * The catalog the template's queries resolve in (undefined = the global registry). Part\n * of its identity: the same JSON in two catalogs is two templates.\n */\n catalog?: ShapeCatalog;\n name?: string;\n json: Record<string, unknown>;\n /** Subject-stripped builder, used for dependency analysis only. */\n builder: LiveBuilder;\n shapeIri?: string;\n reactive: boolean;\n pinned: boolean;\n deps?: QueryDependencies;\n /** `deps` could not be computed (a query context in `where` is unset); recomputed on the next use. */\n depsProvisional?: boolean;\n instances: Map<string, Instance>;\n};\n\nexport type Instance = {\n key: string;\n template: Template;\n params: InstanceParams;\n /** The bound builder this instance executes (what `.live()` was called on). */\n builder: LiveBuilder;\n state: LiveState;\n /** Sequence of the latest issued request; a response carrying an older sequence is dropped. */\n seq: number;\n inflight: boolean;\n /** Invalidated while a request was in flight: run one more request when it settles. */\n staleWhileInflight: boolean;\n /** Every node id the last result mentions, plus the subject(s). */\n ids: Set<string>;\n listeners: Set<LiveListener>;\n /** Removed from its template (GC, routing change); a handle that still holds it re-resolves on use. */\n dropped: boolean;\n /** Set when a query context re-keyed this instance: handles follow it to the new one. */\n movedTo?: Instance;\n gcTimer?: ReturnType<typeof setTimeout>;\n};\n\nexport type LiveQueryStoreOptions = {\n /** Grace period before an instance with no listeners is dropped. */\n gcMs: number;\n /** Window in which a remote echo of a local change (or the reverse) folds into one refetch. */\n echoMs: number;\n};\n\nconst IDLE: LiveState = Object.freeze({status: 'pending', notFound: false, refreshing: false}) as LiveState;\n\n// ---------------------------------------------------------------------------\n// Store\n// ---------------------------------------------------------------------------\n\n/**\n * Holds every live query in the runtime: templates (what is read) and\n * instances (what it is applied to, and the data). Framework-free; UI layers\n * subscribe to instances. One store per runtime, registered on `globalThis`\n * (see `registry.ts`).\n */\nexport class LiveQueryStore {\n readonly options: LiveQueryStoreOptions = {gcMs: 30_000, echoMs: 50};\n\n /** @internal */\n readonly _templates = new Map<string, Template>();\n /** @internal Indexes read by the change matcher. */\n readonly templatesByProp = new Map<string, Set<Template>>();\n /** @internal */\n readonly templatesByShape = new Map<string, Set<Template>>();\n /** @internal */\n readonly instancesById = new Map<string, Set<Instance>>();\n\n private readonly _disposers: Array<() => void> = [];\n private readonly _feeds = new Map<IDataset, () => void>();\n private readonly _recentChanges = new Map<string, {at: number; origin: ChangeOrigin}>();\n private _pendingRefetch = new Set<Instance>();\n private _flushScheduled = false;\n /** How many templates each catalog has; a change is decoded once per catalog listed here. */\n private readonly _catalogTemplates = new Map<ShapeCatalog, number>();\n\n constructor() {\n this._disposers.push(subscribeQueryContext((name) => this._onContextChange(name)));\n this._disposers.push(subscribeQueryDispatch((e) => this._onDispatch(e)));\n this._disposers.push(LinkedStorage.onRoutingChanged(() => this._onRoutingChanged()));\n this._scanDatasets();\n }\n\n // -------------------------------------------------------------------------\n // Templates\n // -------------------------------------------------------------------------\n\n /** Register (or find) the template of `query`. Options merge into an existing template. */\n template(query: LiveBuilder, opts: LiveQueryOptions = {}): Template {\n return this._template(splitQuery(query).templateJson, query, opts);\n }\n\n private _template(templateJson: Record<string, unknown>, query: LiveBuilder, opts: LiveQueryOptions): Template {\n const catalog = catalogOf(query);\n const key = templateKeyFor(templateJson, catalog);\n let t = this._templates.get(key);\n if (!t) {\n t = {\n key,\n kind: kindOf(query),\n ...(catalog !== undefined ? {catalog} : {}),\n json: templateJson,\n builder: stripSubjects(query),\n shapeIri: typeof templateJson.shape === 'string' ? (templateJson.shape as string) : undefined,\n reactive: true,\n pinned: false,\n instances: new Map(),\n };\n this._templates.set(key, t);\n if (catalog !== undefined) {\n this._catalogTemplates.set(catalog, (this._catalogTemplates.get(catalog) ?? 0) + 1);\n }\n }\n if (opts.name !== undefined) t.name = opts.name;\n if (opts.reactive !== undefined) t.reactive = opts.reactive;\n if (opts.pinned) t.pinned = true;\n return t;\n }\n\n /** The registered templates (for database tuning, devtools). */\n templates(): ReadonlyArray<{key: string; kind: LiveQueryKind; name?: string; json: Record<string, unknown>}> {\n return [...this._templates.values()].map((t) => ({key: t.key, kind: t.kind, name: t.name, json: t.json}));\n }\n\n /** Compute the dependencies of every template now (they are otherwise computed on first use). */\n prepare(): void {\n for (const t of this._templates.values()) this.depsOf(t);\n }\n\n /**\n * The watch set of a template, computed once. When a query context used in\n * `where` is not set yet, lowering throws; the template then gets provisional\n * dependencies (its shape only) and is recomputed on its next use, which the\n * context change triggers.\n */\n depsOf(template: Template): QueryDependencies {\n if (template.deps && !template.depsProvisional) return template.deps;\n try {\n template.deps = queryDependencies(template.builder as any);\n template.depsProvisional = false;\n } catch (err) {\n if (!(err instanceof UnresolvedContextError)) throw err;\n if (template.deps) return template.deps; // still provisional\n template.deps = {\n narrow: new Set(),\n filter: new Set(),\n hidden: new Set(),\n shapes: new Set(template.shapeIri ? [template.shapeIri] : []),\n unbound: false,\n };\n template.depsProvisional = true;\n }\n this._index(template);\n return template.deps;\n }\n\n private _index(t: Template): void {\n const deps = t.deps!;\n for (const set of [deps.narrow, deps.filter, deps.hidden]) {\n for (const p of set) addToIndex(this.templatesByProp, p, t);\n }\n for (const s of deps.shapes) addToIndex(this.templatesByShape, s, t);\n }\n\n private _unindexTemplate(t: Template): void {\n for (const set of this.templatesByProp.values()) set.delete(t);\n for (const set of this.templatesByShape.values()) set.delete(t);\n }\n\n // -------------------------------------------------------------------------\n // Instances and handles\n // -------------------------------------------------------------------------\n\n /** @internal Get or create the instance of `template` for `params`, executing `builder`. */\n instance(template: Template, params: InstanceParams, builder: LiveBuilder): Instance {\n const pk = paramsKey(params);\n let inst = template.instances.get(pk);\n if (!inst) {\n this.depsOf(template); // index the template before its first instance exists\n inst = {\n key: `${template.key}|${pk}`,\n template,\n params,\n builder,\n state: IDLE,\n seq: 0,\n inflight: false,\n staleWhileInflight: false,\n ids: new Set(),\n listeners: new Set(),\n dropped: false,\n };\n template.instances.set(pk, inst);\n }\n return inst;\n }\n\n /**\n * Subscribe to `query`. The first listener on an instance starts its fetch;\n * identical queries share one instance and one request. A handle created\n * without a listener holds nothing: its instance is released after the grace\n * period unless something subscribes.\n */\n subscribe<R = unknown>(query: LiveBuilder, listener?: LiveListener<R>, opts: LiveQueryOptions = {}): LiveQuery<R> {\n const {templateJson, params} = splitQuery(query);\n const template = this._template(templateJson, query, opts);\n const inst = this.instance(template, params, query);\n if (inst.listeners.size === 0) this._scheduleGc(inst);\n const handle = new LiveQueryHandle<R>(this, inst);\n if (listener) handle.subscribe(listener);\n return handle;\n }\n\n /** @internal The live instance for a possibly dropped one (same template, params and builder). */\n _resolve(inst: Instance): Instance {\n if (!inst.dropped) return inst;\n if (inst.movedTo) return this._resolve(inst.movedTo);\n const t = this._templates.get(inst.template.key) ?? this._template(inst.template.json, inst.builder, {});\n return this.instance(t, inst.params, inst.builder);\n }\n\n /** @internal */\n _attach(inst: Instance, listener: LiveListener): void {\n this._cancelGc(inst);\n inst.listeners.add(listener);\n if (inst.state.status === 'pending' && !inst.inflight) {\n void this._fetch(inst);\n }\n }\n\n /** @internal */\n _detach(inst: Instance, listener: LiveListener): void {\n inst.listeners.delete(listener);\n if (inst.listeners.size === 0 && !inst.dropped) this._scheduleGc(inst);\n }\n\n /** Refetch an instance, keeping its data on screen. Resolves when that request settles. */\n refresh(inst: Instance): Promise<void> {\n return this._fetch(inst);\n }\n\n /**\n * Local edit of an instance's data. Never touches the store. A patched\n * instance counts as loaded (`success`), so `await live` resolves with it.\n */\n patch(inst: Instance, partial: unknown): void {\n const current = inst.state.data;\n const mergeable = (v: unknown) => !!v && typeof v === 'object' && !Array.isArray(v);\n const next =\n typeof partial === 'function'\n ? (partial as (c: unknown) => unknown)(current)\n : mergeable(current) && mergeable(partial)\n ? {...(current as object), ...(partial as object)}\n : partial;\n const status = inst.state.status === 'error' ? 'error' : 'success';\n this._setState(inst, {...inst.state, status, data: next, notFound: next === null});\n this._collectIds(inst, next);\n }\n\n /**\n * Refetch every instance matching `target`: a shape class or shape IRI\n * (everything that scans or traverses it, as after a delete), a node\n * reference (`{id}`), a query (its template), or a template. Never folded\n * with other change events.\n */\n invalidate(target: ShapeConstructor<any> | string | {id: string} | LiveBuilder | Template): void {\n if (typeof target === 'function' || typeof target === 'string') {\n const shape = typeof target === 'string' ? target : (target as {shape?: {id?: string}}).shape?.id;\n if (!shape) throw new Error('invalidate(): the shape class has no registered shape.');\n this.publish({effects: {op: 'delete', shape, props: new Set(), ids: undefined, membership: new Set([shape])}}, 'manual');\n return;\n }\n const instances = new Set<Instance>();\n if (isTemplate(target)) {\n for (const i of target.instances.values()) instances.add(i);\n } else if (typeof (target as {__queryKind?: string}).__queryKind === 'string') {\n const t = this._templates.get(\n templateKeyFor(splitQuery(target as LiveBuilder).templateJson, catalogOf(target)),\n );\n if (t) for (const i of t.instances.values()) instances.add(i);\n } else if (typeof (target as {id?: unknown}).id === 'string') {\n for (const i of this.instancesById.get((target as {id: string}).id) ?? []) instances.add(i);\n }\n this._refetchAll(instances);\n }\n\n /** @internal Refetch a set of instances, folding in-flight ones into one follow-up request. */\n _refetchAll(instances: Iterable<Instance>): void {\n for (const inst of instances) {\n if (inst.listeners.size === 0 || inst.dropped) continue; // nobody is watching; it refetches when subscribed again\n if (inst.inflight) inst.staleWhileInflight = true;\n else void this._fetch(inst);\n }\n }\n\n // -------------------------------------------------------------------------\n // Change sources\n // -------------------------------------------------------------------------\n\n /**\n * Tell the store that data changed. Every source ends here: local mutations\n * (automatically, origin `local`), dataset change feeds (`feed`), application\n * code via `publishChange()` (`app`) and `invalidate()` (`manual`).\n *\n * A local change and its remote confirmation carry identical effects; when\n * they arrive within `options.echoMs` of each other they refetch once. Two\n * events of the same origin are never folded — two writes to the same node\n * in quick succession are two changes — and manual invalidations never are.\n */\n publish(event: ChangeEvent, origin: ChangeOrigin = 'app'): void {\n this._publish(event, origin);\n }\n\n /**\n * `within` limits the change to one catalog's templates (undefined = the global registry's):\n * a local mutation changes the data of the catalog it was made in, and only that one.\n */\n private _publish(\n event: ChangeEvent,\n origin: ChangeOrigin,\n within?: {catalog: ShapeCatalog | undefined},\n ): void {\n const decoded: Array<[ShapeCatalog | undefined, MutationEffects]> = within\n ? [[within.catalog, normalizeChange(event, {catalog: within.catalog})]]\n : this._decodePerCatalog(event);\n const effects = decoded[0][1];\n if (origin !== 'manual') {\n const hash = effectsHash(effects);\n const now = Date.now();\n const prev = this._recentChanges.get(hash);\n if (prev && prev.origin !== 'manual' && prev.origin !== origin && now - prev.at < this.options.echoMs) {\n return; // the echo of a change already applied\n }\n this._recentChanges.set(hash, {at: now, origin});\n if (this._recentChanges.size > 256) {\n // Bounded: anything older than the echo window can no longer fold with a newcomer.\n for (const [h, r] of this._recentChanges) if (now - r.at >= this.options.echoMs) this._recentChanges.delete(h);\n }\n }\n if (decoded.length === 1 && decoded[0][0] === undefined && this._catalogTemplates.size === 0) {\n for (const inst of selectInstances(this, effects)) this._pendingRefetch.add(inst);\n } else {\n for (const [catalog, e] of decoded) {\n for (const inst of selectInstances(this, e, {catalog})) this._pendingRefetch.add(inst);\n }\n }\n this._scheduleFlush();\n }\n\n /**\n * The effects of a change in the global registry and in each catalog that has\n * templates. A mutation is decoded once per catalog; one that does not resolve in a\n * catalog (its shape is not there) leaves that catalog's templates alone, and effects\n * given as data apply to a catalog only when it holds their shape. Throws only when\n * the change resolves nowhere, as a change that cannot be decoded did before catalogs.\n */\n private _decodePerCatalog(\n event: ChangeEvent,\n ): Array<[ShapeCatalog | undefined, MutationEffects]> {\n if (this._catalogTemplates.size === 0) {\n return [[undefined, normalizeChange(event, {catalog: undefined})]];\n }\n const out: Array<[ShapeCatalog | undefined, MutationEffects]> = [];\n let globalError: unknown;\n try {\n out.push([undefined, normalizeChange(event, {catalog: undefined})]);\n } catch (err) {\n globalError = err;\n }\n for (const catalog of this._catalogTemplates.keys()) {\n try {\n const effects = normalizeChange(event, {catalog});\n if ('effects' in event && !catalog.has(effects.shape)) continue;\n out.push([catalog, effects]);\n } catch {\n // Not a change to this catalog's shapes.\n }\n }\n if (out.length === 0) throw globalError;\n return out;\n }\n\n private _scheduleFlush(): void {\n if (this._flushScheduled) return;\n this._flushScheduled = true;\n queueMicrotask(() => {\n this._flushScheduled = false;\n const batch = this._pendingRefetch;\n this._pendingRefetch = new Set();\n this._refetchAll(batch);\n });\n }\n\n /**\n * Local mutations. Select and ask events are ignored: the store's own fetches\n * run through the same dispatch and must not feed back into it.\n */\n private _onDispatch(e: QueryDispatchEvent): void {\n if (e.kind !== 'create' && e.kind !== 'update' && e.kind !== 'delete') return;\n const query = e.query as {shape?: {id?: string}};\n // The routing lookup reads the registry, so it runs in the mutation's catalog.\n const catalog = catalogOf(query);\n const shapeClassOf = (id: string) =>\n catalog === getActiveShapeCatalog()\n ? getShapeClass(id)\n : withShapeCatalog(catalog, () => getShapeClass(id));\n const dataset =\n e.target ??\n LinkedStorage.getDatasetForShapeClass(\n (query.shape?.id ? shapeClassOf(query.shape.id) : undefined) as Function | undefined,\n );\n if (dataset?.authoritativeChanges) return; // the dataset's own feed will report it\n e.result.then(\n (result) => {\n let effects: MutationEffects;\n try {\n effects = mutationEffects(e.query as any, result);\n } catch (err) {\n console.error('[linked] could not derive the effects of a mutation; live queries were not refetched', err);\n return;\n }\n this._publish({effects}, 'local', {catalog});\n },\n () => {}, // a failed mutation changed nothing\n );\n }\n\n /** Subscribe to the change feeds of the datasets currently routed; drop feeds of datasets that left. */\n private _scanDatasets(): void {\n const current = new Set<IDataset>(LinkedStorage.getDatasets());\n for (const [dataset, off] of [...this._feeds]) {\n if (!current.has(dataset)) {\n off();\n this._feeds.delete(dataset);\n }\n }\n for (const dataset of current) {\n if (typeof dataset.subscribeChanges !== 'function' || this._feeds.has(dataset)) continue;\n const off = dataset.subscribeChanges((event) => {\n try {\n this.publish(event, 'feed');\n } catch (err) {\n console.error('[linked] a dataset change event could not be applied', err);\n }\n });\n this._feeds.set(dataset, off);\n }\n }\n\n /**\n * Storage changed (a dataset was set, pinned or unpinned): what is cached may\n * come from a store that no longer answers, so instances nobody watches are\n * dropped and watched ones fetch again. Also refreshes the feed subscriptions.\n */\n private _onRoutingChanged(): void {\n this._scanDatasets();\n this._recentChanges.clear();\n for (const t of [...this._templates.values()]) {\n for (const inst of [...t.instances.values()]) {\n if (inst.listeners.size === 0) this._dropInstance(inst);\n else this._refetchAll([inst]);\n }\n }\n }\n\n /** Drop every template and instance (tests). Subscriptions to sources stay. */\n reset(): void {\n for (const t of [...this._templates.values()]) {\n for (const i of [...t.instances.values()]) this._dropInstance(i, true);\n }\n this._templates.clear();\n this._catalogTemplates.clear();\n this.templatesByProp.clear();\n this.templatesByShape.clear();\n this.instancesById.clear();\n this._recentChanges.clear();\n this._pendingRefetch.clear();\n }\n\n /** @internal */\n dispose(): void {\n this.reset();\n for (const off of this._disposers) off();\n for (const off of this._feeds.values()) off();\n this._feeds.clear();\n }\n\n // -------------------------------------------------------------------------\n // Fetching\n // -------------------------------------------------------------------------\n\n private async _fetch(inst: Instance): Promise<void> {\n const unresolvedSubject = !!inst.params.contextName && !inst.params.subject;\n if (!LinkedStorage.isInitialised() || unresolvedSubject) {\n // Nothing to request yet. Stay quiet if that is already what listeners know.\n if (inst.state.status !== 'pending' || inst.state.refreshing) {\n this._setState(inst, {...inst.state, status: 'pending', refreshing: false});\n }\n return;\n }\n if (inst.template.depsProvisional) this.depsOf(inst.template); // a context may have landed\n const seq = ++inst.seq;\n inst.inflight = true;\n const hasData = inst.state.data !== undefined;\n this._setState(inst, {\n ...inst.state,\n status: hasData ? inst.state.status : 'loading',\n refreshing: hasData,\n });\n try {\n // `exec()` is the same path `await query` takes: dispatch, count/ask\n // contracts, error wrapping. The store adds nothing of its own to it.\n const data = await (inst.builder as {exec(): Promise<unknown>}).exec();\n if (seq !== inst.seq) return;\n this._applyResult(inst, data);\n } catch (err) {\n if (seq !== inst.seq) return;\n this._setState(inst, {\n ...inst.state,\n status: 'error',\n error: err instanceof Error ? err : new Error(String(err)),\n refreshing: false,\n });\n } finally {\n if (seq === inst.seq) {\n inst.inflight = false;\n if (inst.staleWhileInflight) {\n inst.staleWhileInflight = false;\n void this._fetch(inst);\n }\n }\n }\n }\n\n private _applyResult(inst: Instance, data: unknown): void {\n const notFound = data === null && inst.template.kind === 'select' && !!(inst.params.subject || inst.params.one);\n if (inst.state.status === 'success' && deepEqual(inst.state.data, data)) {\n // Structural sharing: same data, keep the reference and stay quiet.\n if (inst.state.refreshing) this._setState(inst, {...inst.state, refreshing: false, error: undefined});\n return;\n }\n this._collectIds(inst, data);\n this._setState(inst, {status: 'success', data, error: undefined, notFound, refreshing: false});\n }\n\n private _collectIds(inst: Instance, data: unknown): void {\n const ids = new Set<string>();\n if (inst.params.subject) ids.add(inst.params.subject);\n for (const s of inst.params.subjects ?? []) ids.add(s);\n collectIds(data, ids);\n for (const old of inst.ids) if (!ids.has(old)) removeFromIndex(this.instancesById, old, inst);\n for (const id of ids) if (!inst.ids.has(id)) addToIndex(this.instancesById, id, inst);\n inst.ids = ids;\n }\n\n private _setState(inst: Instance, state: LiveState): void {\n inst.state = state;\n for (const l of [...inst.listeners]) {\n try {\n l(state);\n } catch (err) {\n console.error('[linked] live query listener failed', err);\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // Query context\n // -------------------------------------------------------------------------\n\n /**\n * A query context changed. An instance whose *subject* is that context is\n * re-keyed to the new id (the builder resolves the context lazily, so it is\n * reused); an instance that references it in `where` just fetches again.\n */\n private _onContextChange(name: string): void {\n const resolved = resolveContextId(name, false);\n for (const t of [...this._templates.values()]) {\n for (const inst of [...t.instances.values()]) {\n if (inst.params.contextNames?.includes(name)) {\n if (t.depsProvisional) {\n this._unindexTemplate(t);\n this.depsOf(t);\n }\n if (inst.listeners.size > 0) this._refetchAll([inst]);\n }\n if (inst.params.contextName !== name) continue;\n const params: InstanceParams = {...inst.params};\n if (resolved) params.subject = resolved;\n else delete params.subject;\n if (paramsKey(params) === paramsKey(inst.params)) continue;\n // Move the listeners to the instance for the new subject and drop the old one.\n const next = this.instance(t, params, inst.builder);\n this._cancelGc(next);\n const listeners = [...inst.listeners];\n inst.listeners.clear();\n inst.seq++; // any in-flight response for the old subject is now stale\n inst.movedTo = next;\n this._dropInstance(inst, true);\n for (const l of listeners) next.listeners.add(l);\n if (next.listeners.size > 0) {\n if (!resolved) this._setState(next, {...IDLE});\n else if (next.state.status === 'pending' && !next.inflight) void this._fetch(next);\n else this._setState(next, next.state); // publish the cached state to the moved listeners\n } else {\n this._scheduleGc(next);\n }\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // GC\n // -------------------------------------------------------------------------\n\n /** Remove an instance from its template (and the template when it is empty and not pinned). */\n private _dropInstance(inst: Instance, keepTemplate = false): void {\n this._cancelGc(inst);\n inst.dropped = true;\n const t = inst.template;\n if (t.instances.get(paramsKey(inst.params)) === inst) t.instances.delete(paramsKey(inst.params));\n for (const id of inst.ids) removeFromIndex(this.instancesById, id, inst);\n if (!keepTemplate && t.instances.size === 0 && !t.pinned) {\n this._templates.delete(t.key);\n this._unindexTemplate(t);\n this._forgetCatalogTemplate(t);\n }\n }\n\n private _forgetCatalogTemplate(t: Template): void {\n if (t.catalog === undefined) return;\n const left = (this._catalogTemplates.get(t.catalog) ?? 1) - 1;\n if (left > 0) this._catalogTemplates.set(t.catalog, left);\n else this._catalogTemplates.delete(t.catalog);\n }\n\n private _scheduleGc(inst: Instance): void {\n this._cancelGc(inst);\n // `unref` so a pending grace period never keeps a Node process (or a test\n // runner) alive.\n const timer = setTimeout(() => {\n inst.gcTimer = undefined;\n if (inst.listeners.size > 0) return;\n this._dropInstance(inst);\n }, this.options.gcMs);\n (timer as {unref?: () => void}).unref?.();\n inst.gcTimer = timer;\n }\n\n private _cancelGc(inst: Instance): void {\n if (inst.gcTimer) {\n clearTimeout(inst.gcTimer);\n inst.gcTimer = undefined;\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Handle\n// ---------------------------------------------------------------------------\n\nclass LiveQueryHandle<R> implements LiveQuery<R> {\n private _inst: Instance;\n private readonly _mine = new Set<LiveListener>();\n\n constructor(\n private readonly store: LiveQueryStore,\n inst: Instance,\n ) {\n this._inst = inst;\n }\n\n /** The current instance, re-resolved if the store dropped the one this handle held. */\n private get inst(): Instance {\n if (this._inst.dropped) this._inst = this.store._resolve(this._inst);\n return this._inst;\n }\n\n get state(): LiveState<R> {\n return this.inst.state as LiveState<R>;\n }\n\n get key(): string {\n return this.inst.key;\n }\n\n subscribe(listener: LiveListener<R>): () => void {\n const l = listener as LiveListener;\n const inst = this.inst;\n this._mine.add(l);\n this.store._attach(inst, l);\n return () => {\n if (this._mine.delete(l)) this.store._detach(inst, l);\n };\n }\n\n refresh(): Promise<void> {\n return this.store.refresh(this.inst);\n }\n\n patch(partial: Partial<R> | ((current: R) => R)): void {\n this.store.patch(this.inst, partial);\n }\n\n close(): void {\n const inst = this._inst;\n for (const l of this._mine) this.store._detach(inst, l);\n this._mine.clear();\n }\n\n then<T1 = R, T2 = never>(\n onfulfilled?: ((value: R) => T1 | PromiseLike<T1>) | null,\n onrejected?: ((reason: unknown) => T2 | PromiseLike<T2>) | null,\n ): Promise<T1 | T2> {\n return this._firstResult().then(onfulfilled, onrejected);\n }\n\n /** Resolves with the first successful data; the subscription it needs is released afterwards. */\n private _firstResult(): Promise<R> {\n const s = this.state;\n if (s.status === 'success') return Promise.resolve(s.data as R);\n if (s.status === 'error') return Promise.reject(s.error);\n return new Promise<R>((resolve, reject) => {\n const off = this.subscribe((st) => {\n if (st.status === 'success') {\n off();\n resolve(st.data as R);\n } else if (st.status === 'error') {\n off();\n reject(st.error);\n }\n });\n });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction addToIndex<K, V>(index: Map<K, Set<V>>, key: K, value: V): void {\n let set = index.get(key);\n if (!set) index.set(key, (set = new Set()));\n set.add(value);\n}\n\nfunction removeFromIndex<K, V>(index: Map<K, Set<V>>, key: K, value: V): void {\n const set = index.get(key);\n if (!set) return;\n set.delete(value);\n if (set.size === 0) index.delete(key);\n}\n\nfunction isTemplate(v: unknown): v is Template {\n return !!v && typeof v === 'object' && 'instances' in (v as object) && 'builder' in (v as object);\n}\n\n/** Every string value under an `id` key, at any depth. */\nexport function collectIds(value: unknown, into: Set<string>): Set<string> {\n if (Array.isArray(value)) {\n for (const v of value) collectIds(v, into);\n } else if (value && typeof value === 'object' && !(value instanceof Date)) {\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (k === 'id' && typeof v === 'string') into.add(v);\n else if (v && typeof v === 'object') collectIds(v, into);\n }\n }\n return into;\n}\n\n/** Deep equality over the plain-data results the store holds (objects, arrays, dates, primitives). */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a instanceof Date || b instanceof Date) {\n return a instanceof Date && b instanceof Date && a.getTime() === b.getTime();\n }\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n return a.every((v, i) => deepEqual(v, b[i]));\n }\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n const ka = Object.keys(a as object);\n const kb = Object.keys(b as object);\n if (ka.length !== kb.length) return false;\n return ka.every((k) => deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]));\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Registration\n// ---------------------------------------------------------------------------\n\n/** The runtime's live-query store (registered on `globalThis` when this module loads). */\nexport function getLiveQueryStore(): LiveQueryStore {\n let store = peekLiveQueryStore();\n if (!store) {\n store = new LiveQueryStore();\n setLiveQueryStore(store);\n }\n return store;\n}\n\n/** Publish a change from application code (your own transport, a server push). */\nexport function publishChange(event: ChangeEvent): void {\n getLiveQueryStore().publish(event, 'app');\n}\n\n/** Refetch every live query that `target` can have affected. See {@link LiveQueryStore.invalidate}. */\nexport function invalidate(target: ShapeConstructor<any> | string | {id: string} | LiveBuilder | Template): void {\n getLiveQueryStore().invalidate(target);\n}\n\nexport type {ChangeEvent, ChangeOrigin, MutationEffects};\n\n/** Replace the store with a fresh one (tests). */\nexport function resetLiveQueryStore(): LiveQueryStore {\n peekLiveQueryStore()?.dispose();\n const store = new LiveQueryStore();\n setLiveQueryStore(store);\n return store;\n}\n\n// Register on load: importing this module is what makes `.live()` work.\nif (!peekLiveQueryStore()) setLiveQueryStore(new LiveQueryStore());\n"]}
1
+ {"version":3,"file":"LiveQueryStore.js","sourceRoot":"","sources":["../../../src/live/LiveQueryStore.ts"],"names":[],"mappings":";;;;;;;;;AAAA;;;;GAIG;AACH,OAAO,EAAC,aAAa,EAAC,MAAM,2BAA2B,CAAC;AAExD,OAAO,EAAC,qBAAqB,EAAE,sBAAsB,EAAC,MAAM,4BAA4B,CAAC;AACzF,OAAO,EAAC,gBAAgB,EAAC,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAC,sBAAsB,EAA0B,MAAM,6BAA6B,CAAC;AAC5F,OAAO,EACL,eAAe,EACf,iBAAiB,GAGlB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,SAAS,EACT,qBAAqB,EACrB,aAAa,EACb,gBAAgB,GACjB,MAAM,wBAAwB,CAAC;AAGhC,OAAO,EAAC,WAAW,EAAE,eAAe,EAAsC,MAAM,cAAc,CAAC;AAC/F,OAAO,EAAC,eAAe,EAAC,MAAM,cAAc,CAAC;AAC7C,OAAO,EACL,MAAM,EACN,SAAS,EACT,UAAU,EACV,aAAa,EACb,cAAc,GAIf,MAAM,WAAW,CAAC;AACnB,OAAO,EAAC,iBAAiB,EAAE,kBAAkB,EAAC,MAAM,eAAe,CAAC;AACpE,OAAO,EAAC,aAAa,EAAC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;IAC3B,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,aAAa,CAAC,KAAkB;IAC9C,iBAAiB,EAAE,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AAC5C,CAAC;AAED,uGAAuG;AACvG,MAAM,UAAU,UAAU,CAAC,MAA8E;IACvG,iBAAiB,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;AACzC,CAAC;AAID,kDAAkD;AAClD,MAAM,UAAU,mBAAmB;;IACjC,MAAA,kBAAkB,EAAE,0CAAE,OAAO,EAAE,CAAC;IAChC,MAAM,KAAK,GAAG,IAAI,cAAc,EAAE,CAAC;IACnC,iBAAiB,CAAC,KAAK,CAAC,CAAC;IACzB,OAAO,KAAK,CAAC;AACf,CAAC;AAED,wEAAwE;AACxE,IAAI,CAAC,kBAAkB,EAAE;IAAE,iBAAiB,CAAC,IAAI,cAAc,EAAE,CAAC,CAAC","sourcesContent":["/*\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/.\n */\nimport {LinkedStorage} from '../utils/LinkedStorage.js';\nimport type {IDataset} from '../interfaces/IDataset.js';\nimport {subscribeQueryContext, UnresolvedContextError} from '../queries/QueryContext.js';\nimport {resolveContextId} from '../queries/ContextRef.js';\nimport {subscribeQueryDispatch, type QueryDispatchEvent} from '../queries/queryDispatch.js';\nimport {\n mutationEffects,\n queryDependencies,\n type MutationEffects,\n type QueryDependencies,\n} from '../queries/queryDependencies.js';\nimport {\n catalogOf,\n getActiveShapeCatalog,\n getShapeClass,\n withShapeCatalog,\n} from '../utils/ShapeClass.js';\nimport type {ShapeCatalog} from '../utils/ShapeCatalog.js';\nimport type {ShapeConstructor} from '../shapes/Shape.js';\nimport {effectsHash, normalizeChange, type ChangeEvent, type ChangeOrigin} from './changes.js';\nimport {selectInstances} from './matcher.js';\nimport {\n kindOf,\n paramsKey,\n splitQuery,\n stripSubjects,\n templateKeyFor,\n type InstanceParams,\n type LiveBuilder,\n type LiveQueryKind,\n} from './keys.js';\nimport {setLiveQueryStore, peekLiveQueryStore} from './registry.js';\nimport {isLinkedError} from '../utils/linkedError.js';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport type LiveStatus = 'pending' | 'loading' | 'success' | 'error';\n\n/**\n * What a live query currently knows.\n *\n * - `pending`: nothing requested yet (no storage configured, or the subject is\n * a query context that has not been set).\n * - `loading`: first request in flight, no data yet.\n * - `success` / `error`: last request settled. On error the previous `data`,\n * if any, is kept so a screen does not go blank over a transient failure.\n * - `refreshing`: a request is in flight while `data` is present.\n * - `notFound`: a single-subject query answered `null`.\n *\n * The object is replaced (never mutated) on every change, so it is safe as a\n * `useSyncExternalStore` snapshot.\n */\nexport type LiveState<R = unknown> = {\n status: LiveStatus;\n data?: R;\n error?: Error;\n notFound: boolean;\n refreshing: boolean;\n};\n\nexport type LiveListener<R = unknown> = (state: LiveState<R>) => void;\n\nexport type LiveQueryOptions = {\n /** Metadata for the template registry (`prepare()`), not identity. */\n name?: string;\n /** `false` opts this template — every query with this exact template — out of automatic invalidation. Default `true`. */\n reactive?: boolean;\n /** A pinned template survives having no instances (component definitions, `prepare()`). */\n pinned?: boolean;\n};\n\n/**\n * The handle returned by `query.live()`.\n *\n * It is `PromiseLike`: `await live` resolves with the first successful `data`\n * (or rejects with the first error) and the handle stays live afterwards. It\n * waits for as long as storage is not configured or a pending query context is\n * not set. Because the handle is thenable, do not `return` it from an `async`\n * function — the promise machinery would unwrap it. `subscribe(cb)` follows\n * the Svelte store contract (returns the unsubscribe function). `close()`\n * detaches every listener added through this handle; the handle can be used\n * again afterwards, which is what React's StrictMode needs.\n */\nexport interface LiveQuery<R = unknown> extends PromiseLike<R> {\n readonly state: LiveState<R>;\n /** Identity of the underlying instance (template key + params). */\n readonly key: string;\n subscribe(listener: LiveListener<R>): () => void;\n /** Refetch now, keeping the current data until the response lands. */\n refresh(): Promise<void>;\n /**\n * Local edit of the cached data, no request; overwritten by the next refetch\n * and visible to every subscriber of the same query. An object merges into\n * object data; an array or a function replaces.\n */\n patch(partial: Partial<R> | ((current: R) => R)): void;\n /** Detach every listener added through this handle. */\n close(): void;\n}\n\nexport type Template = {\n key: string;\n kind: LiveQueryKind;\n /**\n * The catalog the template's queries resolve in (undefined = the global registry). Part\n * of its identity: the same JSON in two catalogs is two templates.\n */\n catalog?: ShapeCatalog;\n name?: string;\n json: Record<string, unknown>;\n /** Subject-stripped builder, used for dependency analysis only. */\n builder: LiveBuilder;\n shapeIri?: string;\n reactive: boolean;\n pinned: boolean;\n deps?: QueryDependencies;\n /** `deps` could not be computed (a query context in `where` is unset); recomputed on the next use. */\n depsProvisional?: boolean;\n instances: Map<string, Instance>;\n};\n\nexport type Instance = {\n key: string;\n template: Template;\n params: InstanceParams;\n /** The bound builder this instance executes (what `.live()` was called on). */\n builder: LiveBuilder;\n state: LiveState;\n /** Sequence of the latest issued request; a response carrying an older sequence is dropped. */\n seq: number;\n inflight: boolean;\n /** Invalidated while a request was in flight: run one more request when it settles. */\n staleWhileInflight: boolean;\n /** Every node id the last result mentions, plus the subject(s). */\n ids: Set<string>;\n listeners: Set<LiveListener>;\n /** Removed from its template (GC, routing change); a handle that still holds it re-resolves on use. */\n dropped: boolean;\n /** Set when a query context re-keyed this instance: handles follow it to the new one. */\n movedTo?: Instance;\n gcTimer?: ReturnType<typeof setTimeout>;\n};\n\nexport type LiveQueryStoreOptions = {\n /** Grace period before an instance with no listeners is dropped. */\n gcMs: number;\n /** Window in which a remote echo of a local change (or the reverse) folds into one refetch. */\n echoMs: number;\n};\n\nconst IDLE: LiveState = Object.freeze({status: 'pending', notFound: false, refreshing: false}) as LiveState;\n\n// ---------------------------------------------------------------------------\n// Store\n// ---------------------------------------------------------------------------\n\n/**\n * Holds every live query in the runtime: templates (what is read) and\n * instances (what it is applied to, and the data). Framework-free; UI layers\n * subscribe to instances. One store per runtime, registered on `globalThis`\n * (see `registry.ts`).\n */\nexport class LiveQueryStore {\n readonly options: LiveQueryStoreOptions = {gcMs: 30_000, echoMs: 50};\n\n /** @internal */\n readonly _templates = new Map<string, Template>();\n /** @internal Indexes read by the change matcher. */\n readonly templatesByProp = new Map<string, Set<Template>>();\n /** @internal */\n readonly templatesByShape = new Map<string, Set<Template>>();\n /** @internal */\n readonly instancesById = new Map<string, Set<Instance>>();\n\n private readonly _disposers: Array<() => void> = [];\n private readonly _feeds = new Map<IDataset, () => void>();\n private readonly _recentChanges = new Map<string, {at: number; origin: ChangeOrigin}>();\n private _pendingRefetch = new Set<Instance>();\n private _flushScheduled = false;\n /** How many templates each catalog has; a change is decoded once per catalog listed here. */\n private readonly _catalogTemplates = new Map<ShapeCatalog, number>();\n\n constructor() {\n this._disposers.push(subscribeQueryContext((name) => this._onContextChange(name)));\n this._disposers.push(subscribeQueryDispatch((e) => this._onDispatch(e)));\n this._disposers.push(LinkedStorage.onRoutingChanged(() => this._onRoutingChanged()));\n this._scanDatasets();\n }\n\n // -------------------------------------------------------------------------\n // Templates\n // -------------------------------------------------------------------------\n\n /** Register (or find) the template of `query`. Options merge into an existing template. */\n template(query: LiveBuilder, opts: LiveQueryOptions = {}): Template {\n return this._template(splitQuery(query).templateJson, query, opts);\n }\n\n private _template(templateJson: Record<string, unknown>, query: LiveBuilder, opts: LiveQueryOptions): Template {\n const catalog = catalogOf(query);\n const key = templateKeyFor(templateJson, catalog);\n let t = this._templates.get(key);\n if (!t) {\n t = {\n key,\n kind: kindOf(query),\n ...(catalog !== undefined ? {catalog} : {}),\n json: templateJson,\n builder: stripSubjects(query),\n shapeIri: typeof templateJson.shape === 'string' ? (templateJson.shape as string) : undefined,\n reactive: true,\n pinned: false,\n instances: new Map(),\n };\n this._templates.set(key, t);\n if (catalog !== undefined) {\n this._catalogTemplates.set(catalog, (this._catalogTemplates.get(catalog) ?? 0) + 1);\n }\n }\n if (opts.name !== undefined) t.name = opts.name;\n if (opts.reactive !== undefined) t.reactive = opts.reactive;\n if (opts.pinned) t.pinned = true;\n return t;\n }\n\n /** The registered templates (for database tuning, devtools). */\n templates(): ReadonlyArray<{key: string; kind: LiveQueryKind; name?: string; json: Record<string, unknown>}> {\n return [...this._templates.values()].map((t) => ({key: t.key, kind: t.kind, name: t.name, json: t.json}));\n }\n\n /** Compute the dependencies of every template now (they are otherwise computed on first use). */\n prepare(): void {\n for (const t of this._templates.values()) this.depsOf(t);\n }\n\n /**\n * The watch set of a template, computed once. When a query context used in\n * `where` is not set yet, lowering throws; the template then gets provisional\n * dependencies (its shape only) and is recomputed on its next use, which the\n * context change triggers.\n */\n depsOf(template: Template): QueryDependencies {\n if (template.deps && !template.depsProvisional) return template.deps;\n try {\n template.deps = queryDependencies(template.builder as any);\n template.depsProvisional = false;\n } catch (err) {\n if (!isLinkedError(err, UnresolvedContextError)) throw err;\n if (template.deps) return template.deps; // still provisional\n template.deps = {\n narrow: new Set(),\n filter: new Set(),\n hidden: new Set(),\n shapes: new Set(template.shapeIri ? [template.shapeIri] : []),\n unbound: false,\n };\n template.depsProvisional = true;\n }\n this._index(template);\n return template.deps;\n }\n\n private _index(t: Template): void {\n const deps = t.deps!;\n for (const set of [deps.narrow, deps.filter, deps.hidden]) {\n for (const p of set) addToIndex(this.templatesByProp, p, t);\n }\n for (const s of deps.shapes) addToIndex(this.templatesByShape, s, t);\n }\n\n private _unindexTemplate(t: Template): void {\n for (const set of this.templatesByProp.values()) set.delete(t);\n for (const set of this.templatesByShape.values()) set.delete(t);\n }\n\n // -------------------------------------------------------------------------\n // Instances and handles\n // -------------------------------------------------------------------------\n\n /** @internal Get or create the instance of `template` for `params`, executing `builder`. */\n instance(template: Template, params: InstanceParams, builder: LiveBuilder): Instance {\n const pk = paramsKey(params);\n let inst = template.instances.get(pk);\n if (!inst) {\n this.depsOf(template); // index the template before its first instance exists\n inst = {\n key: `${template.key}|${pk}`,\n template,\n params,\n builder,\n state: IDLE,\n seq: 0,\n inflight: false,\n staleWhileInflight: false,\n ids: new Set(),\n listeners: new Set(),\n dropped: false,\n };\n template.instances.set(pk, inst);\n }\n return inst;\n }\n\n /**\n * Subscribe to `query`. The first listener on an instance starts its fetch;\n * identical queries share one instance and one request. A handle created\n * without a listener holds nothing: its instance is released after the grace\n * period unless something subscribes.\n */\n subscribe<R = unknown>(query: LiveBuilder, listener?: LiveListener<R>, opts: LiveQueryOptions = {}): LiveQuery<R> {\n const {templateJson, params} = splitQuery(query);\n const template = this._template(templateJson, query, opts);\n const inst = this.instance(template, params, query);\n if (inst.listeners.size === 0) this._scheduleGc(inst);\n const handle = new LiveQueryHandle<R>(this, inst);\n if (listener) handle.subscribe(listener);\n return handle;\n }\n\n /** @internal The live instance for a possibly dropped one (same template, params and builder). */\n _resolve(inst: Instance): Instance {\n if (!inst.dropped) return inst;\n if (inst.movedTo) return this._resolve(inst.movedTo);\n const t = this._templates.get(inst.template.key) ?? this._template(inst.template.json, inst.builder, {});\n return this.instance(t, inst.params, inst.builder);\n }\n\n /** @internal */\n _attach(inst: Instance, listener: LiveListener): void {\n this._cancelGc(inst);\n inst.listeners.add(listener);\n if (inst.state.status === 'pending' && !inst.inflight) {\n void this._fetch(inst);\n }\n }\n\n /** @internal */\n _detach(inst: Instance, listener: LiveListener): void {\n inst.listeners.delete(listener);\n if (inst.listeners.size === 0 && !inst.dropped) this._scheduleGc(inst);\n }\n\n /** Refetch an instance, keeping its data on screen. Resolves when that request settles. */\n refresh(inst: Instance): Promise<void> {\n return this._fetch(inst);\n }\n\n /**\n * Local edit of an instance's data. Never touches the store. A patched\n * instance counts as loaded (`success`), so `await live` resolves with it.\n */\n patch(inst: Instance, partial: unknown): void {\n const current = inst.state.data;\n const mergeable = (v: unknown) => !!v && typeof v === 'object' && !Array.isArray(v);\n const next =\n typeof partial === 'function'\n ? (partial as (c: unknown) => unknown)(current)\n : mergeable(current) && mergeable(partial)\n ? {...(current as object), ...(partial as object)}\n : partial;\n const status = inst.state.status === 'error' ? 'error' : 'success';\n this._setState(inst, {...inst.state, status, data: next, notFound: next === null});\n this._collectIds(inst, next);\n }\n\n /**\n * Refetch every instance matching `target`: a shape class or shape IRI\n * (everything that scans or traverses it, as after a delete), a node\n * reference (`{id}`), a query (its template), or a template. Never folded\n * with other change events.\n */\n invalidate(target: ShapeConstructor<any> | string | {id: string} | LiveBuilder | Template): void {\n if (typeof target === 'function' || typeof target === 'string') {\n const shape = typeof target === 'string' ? target : (target as {shape?: {id?: string}}).shape?.id;\n if (!shape) throw new Error('invalidate(): the shape class has no registered shape.');\n this.publish({effects: {op: 'delete', shape, props: new Set(), ids: undefined, membership: new Set([shape])}}, 'manual');\n return;\n }\n const instances = new Set<Instance>();\n if (isTemplate(target)) {\n for (const i of target.instances.values()) instances.add(i);\n } else if (typeof (target as {__queryKind?: string}).__queryKind === 'string') {\n const t = this._templates.get(\n templateKeyFor(splitQuery(target as LiveBuilder).templateJson, catalogOf(target)),\n );\n if (t) for (const i of t.instances.values()) instances.add(i);\n } else if (typeof (target as {id?: unknown}).id === 'string') {\n for (const i of this.instancesById.get((target as {id: string}).id) ?? []) instances.add(i);\n }\n this._refetchAll(instances);\n }\n\n /** @internal Refetch a set of instances, folding in-flight ones into one follow-up request. */\n _refetchAll(instances: Iterable<Instance>): void {\n for (const inst of instances) {\n if (inst.listeners.size === 0 || inst.dropped) continue; // nobody is watching; it refetches when subscribed again\n if (inst.inflight) inst.staleWhileInflight = true;\n else void this._fetch(inst);\n }\n }\n\n // -------------------------------------------------------------------------\n // Change sources\n // -------------------------------------------------------------------------\n\n /**\n * Tell the store that data changed. Every source ends here: local mutations\n * (automatically, origin `local`), dataset change feeds (`feed`), application\n * code via `publishChange()` (`app`) and `invalidate()` (`manual`).\n *\n * A local change and its remote confirmation carry identical effects; when\n * they arrive within `options.echoMs` of each other they refetch once. Two\n * events of the same origin are never folded — two writes to the same node\n * in quick succession are two changes — and manual invalidations never are.\n */\n publish(event: ChangeEvent, origin: ChangeOrigin = 'app'): void {\n this._publish(event, origin);\n }\n\n /**\n * `within` limits the change to one catalog's templates (undefined = the global registry's):\n * a local mutation changes the data of the catalog it was made in, and only that one.\n */\n private _publish(\n event: ChangeEvent,\n origin: ChangeOrigin,\n within?: {catalog: ShapeCatalog | undefined},\n ): void {\n const decoded: Array<[ShapeCatalog | undefined, MutationEffects]> = within\n ? [[within.catalog, normalizeChange(event, {catalog: within.catalog})]]\n : this._decodePerCatalog(event);\n const effects = decoded[0][1];\n if (origin !== 'manual') {\n const hash = effectsHash(effects);\n const now = Date.now();\n const prev = this._recentChanges.get(hash);\n if (prev && prev.origin !== 'manual' && prev.origin !== origin && now - prev.at < this.options.echoMs) {\n return; // the echo of a change already applied\n }\n this._recentChanges.set(hash, {at: now, origin});\n if (this._recentChanges.size > 256) {\n // Bounded: anything older than the echo window can no longer fold with a newcomer.\n for (const [h, r] of this._recentChanges) if (now - r.at >= this.options.echoMs) this._recentChanges.delete(h);\n }\n }\n if (decoded.length === 1 && decoded[0][0] === undefined && this._catalogTemplates.size === 0) {\n for (const inst of selectInstances(this, effects)) this._pendingRefetch.add(inst);\n } else {\n for (const [catalog, e] of decoded) {\n for (const inst of selectInstances(this, e, {catalog})) this._pendingRefetch.add(inst);\n }\n }\n this._scheduleFlush();\n }\n\n /**\n * The effects of a change in the global registry and in each catalog that has\n * templates. A mutation is decoded once per catalog; one that does not resolve in a\n * catalog (its shape is not there) leaves that catalog's templates alone, and effects\n * given as data apply to a catalog only when it holds their shape. Throws only when\n * the change resolves nowhere, as a change that cannot be decoded did before catalogs.\n */\n private _decodePerCatalog(\n event: ChangeEvent,\n ): Array<[ShapeCatalog | undefined, MutationEffects]> {\n if (this._catalogTemplates.size === 0) {\n return [[undefined, normalizeChange(event, {catalog: undefined})]];\n }\n const out: Array<[ShapeCatalog | undefined, MutationEffects]> = [];\n let globalError: unknown;\n try {\n out.push([undefined, normalizeChange(event, {catalog: undefined})]);\n } catch (err) {\n globalError = err;\n }\n for (const catalog of this._catalogTemplates.keys()) {\n try {\n const effects = normalizeChange(event, {catalog});\n if ('effects' in event && !catalog.has(effects.shape)) continue;\n out.push([catalog, effects]);\n } catch {\n // Not a change to this catalog's shapes.\n }\n }\n if (out.length === 0) throw globalError;\n return out;\n }\n\n private _scheduleFlush(): void {\n if (this._flushScheduled) return;\n this._flushScheduled = true;\n queueMicrotask(() => {\n this._flushScheduled = false;\n const batch = this._pendingRefetch;\n this._pendingRefetch = new Set();\n this._refetchAll(batch);\n });\n }\n\n /**\n * Local mutations. Select and ask events are ignored: the store's own fetches\n * run through the same dispatch and must not feed back into it.\n */\n private _onDispatch(e: QueryDispatchEvent): void {\n if (e.kind !== 'create' && e.kind !== 'update' && e.kind !== 'delete') return;\n const query = e.query as {shape?: {id?: string}};\n // The routing lookup reads the registry, so it runs in the mutation's catalog.\n const catalog = catalogOf(query);\n const shapeClassOf = (id: string) =>\n catalog === getActiveShapeCatalog()\n ? getShapeClass(id)\n : withShapeCatalog(catalog, () => getShapeClass(id));\n const dataset =\n e.target ??\n LinkedStorage.getDatasetForShapeClass(\n (query.shape?.id ? shapeClassOf(query.shape.id) : undefined) as Function | undefined,\n );\n if (dataset?.authoritativeChanges) return; // the dataset's own feed will report it\n e.result.then(\n (result) => {\n let effects: MutationEffects;\n try {\n effects = mutationEffects(e.query as any, result);\n } catch (err) {\n console.error('[linked] could not derive the effects of a mutation; live queries were not refetched', err);\n return;\n }\n this._publish({effects}, 'local', {catalog});\n },\n () => {}, // a failed mutation changed nothing\n );\n }\n\n /** Subscribe to the change feeds of the datasets currently routed; drop feeds of datasets that left. */\n private _scanDatasets(): void {\n const current = new Set<IDataset>(LinkedStorage.getDatasets());\n for (const [dataset, off] of [...this._feeds]) {\n if (!current.has(dataset)) {\n off();\n this._feeds.delete(dataset);\n }\n }\n for (const dataset of current) {\n if (typeof dataset.subscribeChanges !== 'function' || this._feeds.has(dataset)) continue;\n const off = dataset.subscribeChanges((event) => {\n try {\n this.publish(event, 'feed');\n } catch (err) {\n console.error('[linked] a dataset change event could not be applied', err);\n }\n });\n this._feeds.set(dataset, off);\n }\n }\n\n /**\n * Storage changed (a dataset was set, pinned or unpinned): what is cached may\n * come from a store that no longer answers, so instances nobody watches are\n * dropped and watched ones fetch again. Also refreshes the feed subscriptions.\n */\n private _onRoutingChanged(): void {\n this._scanDatasets();\n this._recentChanges.clear();\n for (const t of [...this._templates.values()]) {\n for (const inst of [...t.instances.values()]) {\n if (inst.listeners.size === 0) this._dropInstance(inst);\n else this._refetchAll([inst]);\n }\n }\n }\n\n /** Drop every template and instance (tests). Subscriptions to sources stay. */\n reset(): void {\n for (const t of [...this._templates.values()]) {\n for (const i of [...t.instances.values()]) this._dropInstance(i, true);\n }\n this._templates.clear();\n this._catalogTemplates.clear();\n this.templatesByProp.clear();\n this.templatesByShape.clear();\n this.instancesById.clear();\n this._recentChanges.clear();\n this._pendingRefetch.clear();\n }\n\n /** @internal */\n dispose(): void {\n this.reset();\n for (const off of this._disposers) off();\n for (const off of this._feeds.values()) off();\n this._feeds.clear();\n }\n\n // -------------------------------------------------------------------------\n // Fetching\n // -------------------------------------------------------------------------\n\n private async _fetch(inst: Instance): Promise<void> {\n const unresolvedSubject = !!inst.params.contextName && !inst.params.subject;\n if (!LinkedStorage.isInitialised() || unresolvedSubject) {\n // Nothing to request yet. Stay quiet if that is already what listeners know.\n if (inst.state.status !== 'pending' || inst.state.refreshing) {\n this._setState(inst, {...inst.state, status: 'pending', refreshing: false});\n }\n return;\n }\n if (inst.template.depsProvisional) this.depsOf(inst.template); // a context may have landed\n const seq = ++inst.seq;\n inst.inflight = true;\n const hasData = inst.state.data !== undefined;\n this._setState(inst, {\n ...inst.state,\n status: hasData ? inst.state.status : 'loading',\n refreshing: hasData,\n });\n try {\n // `exec()` is the same path `await query` takes: dispatch, count/ask\n // contracts, error wrapping. The store adds nothing of its own to it.\n const data = await (inst.builder as {exec(): Promise<unknown>}).exec();\n if (seq !== inst.seq) return;\n this._applyResult(inst, data);\n } catch (err) {\n if (seq !== inst.seq) return;\n this._setState(inst, {\n ...inst.state,\n status: 'error',\n error: err instanceof Error ? err : new Error(String(err)),\n refreshing: false,\n });\n } finally {\n if (seq === inst.seq) {\n inst.inflight = false;\n if (inst.staleWhileInflight) {\n inst.staleWhileInflight = false;\n void this._fetch(inst);\n }\n }\n }\n }\n\n private _applyResult(inst: Instance, data: unknown): void {\n const notFound = data === null && inst.template.kind === 'select' && !!(inst.params.subject || inst.params.one);\n if (inst.state.status === 'success' && deepEqual(inst.state.data, data)) {\n // Structural sharing: same data, keep the reference and stay quiet.\n if (inst.state.refreshing) this._setState(inst, {...inst.state, refreshing: false, error: undefined});\n return;\n }\n this._collectIds(inst, data);\n this._setState(inst, {status: 'success', data, error: undefined, notFound, refreshing: false});\n }\n\n private _collectIds(inst: Instance, data: unknown): void {\n const ids = new Set<string>();\n if (inst.params.subject) ids.add(inst.params.subject);\n for (const s of inst.params.subjects ?? []) ids.add(s);\n collectIds(data, ids);\n for (const old of inst.ids) if (!ids.has(old)) removeFromIndex(this.instancesById, old, inst);\n for (const id of ids) if (!inst.ids.has(id)) addToIndex(this.instancesById, id, inst);\n inst.ids = ids;\n }\n\n private _setState(inst: Instance, state: LiveState): void {\n inst.state = state;\n for (const l of [...inst.listeners]) {\n try {\n l(state);\n } catch (err) {\n console.error('[linked] live query listener failed', err);\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // Query context\n // -------------------------------------------------------------------------\n\n /**\n * A query context changed. An instance whose *subject* is that context is\n * re-keyed to the new id (the builder resolves the context lazily, so it is\n * reused); an instance that references it in `where` just fetches again.\n */\n private _onContextChange(name: string): void {\n const resolved = resolveContextId(name, false);\n for (const t of [...this._templates.values()]) {\n for (const inst of [...t.instances.values()]) {\n if (inst.params.contextNames?.includes(name)) {\n if (t.depsProvisional) {\n this._unindexTemplate(t);\n this.depsOf(t);\n }\n if (inst.listeners.size > 0) this._refetchAll([inst]);\n }\n if (inst.params.contextName !== name) continue;\n const params: InstanceParams = {...inst.params};\n if (resolved) params.subject = resolved;\n else delete params.subject;\n if (paramsKey(params) === paramsKey(inst.params)) continue;\n // Move the listeners to the instance for the new subject and drop the old one.\n const next = this.instance(t, params, inst.builder);\n this._cancelGc(next);\n const listeners = [...inst.listeners];\n inst.listeners.clear();\n inst.seq++; // any in-flight response for the old subject is now stale\n inst.movedTo = next;\n this._dropInstance(inst, true);\n for (const l of listeners) next.listeners.add(l);\n if (next.listeners.size > 0) {\n if (!resolved) this._setState(next, {...IDLE});\n else if (next.state.status === 'pending' && !next.inflight) void this._fetch(next);\n else this._setState(next, next.state); // publish the cached state to the moved listeners\n } else {\n this._scheduleGc(next);\n }\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // GC\n // -------------------------------------------------------------------------\n\n /** Remove an instance from its template (and the template when it is empty and not pinned). */\n private _dropInstance(inst: Instance, keepTemplate = false): void {\n this._cancelGc(inst);\n inst.dropped = true;\n const t = inst.template;\n if (t.instances.get(paramsKey(inst.params)) === inst) t.instances.delete(paramsKey(inst.params));\n for (const id of inst.ids) removeFromIndex(this.instancesById, id, inst);\n if (!keepTemplate && t.instances.size === 0 && !t.pinned) {\n this._templates.delete(t.key);\n this._unindexTemplate(t);\n this._forgetCatalogTemplate(t);\n }\n }\n\n private _forgetCatalogTemplate(t: Template): void {\n if (t.catalog === undefined) return;\n const left = (this._catalogTemplates.get(t.catalog) ?? 1) - 1;\n if (left > 0) this._catalogTemplates.set(t.catalog, left);\n else this._catalogTemplates.delete(t.catalog);\n }\n\n private _scheduleGc(inst: Instance): void {\n this._cancelGc(inst);\n // `unref` so a pending grace period never keeps a Node process (or a test\n // runner) alive.\n const timer = setTimeout(() => {\n inst.gcTimer = undefined;\n if (inst.listeners.size > 0) return;\n this._dropInstance(inst);\n }, this.options.gcMs);\n (timer as {unref?: () => void}).unref?.();\n inst.gcTimer = timer;\n }\n\n private _cancelGc(inst: Instance): void {\n if (inst.gcTimer) {\n clearTimeout(inst.gcTimer);\n inst.gcTimer = undefined;\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Handle\n// ---------------------------------------------------------------------------\n\nclass LiveQueryHandle<R> implements LiveQuery<R> {\n private _inst: Instance;\n private readonly _mine = new Set<LiveListener>();\n\n constructor(\n private readonly store: LiveQueryStore,\n inst: Instance,\n ) {\n this._inst = inst;\n }\n\n /** The current instance, re-resolved if the store dropped the one this handle held. */\n private get inst(): Instance {\n if (this._inst.dropped) this._inst = this.store._resolve(this._inst);\n return this._inst;\n }\n\n get state(): LiveState<R> {\n return this.inst.state as LiveState<R>;\n }\n\n get key(): string {\n return this.inst.key;\n }\n\n subscribe(listener: LiveListener<R>): () => void {\n const l = listener as LiveListener;\n const inst = this.inst;\n this._mine.add(l);\n this.store._attach(inst, l);\n return () => {\n if (this._mine.delete(l)) this.store._detach(inst, l);\n };\n }\n\n refresh(): Promise<void> {\n return this.store.refresh(this.inst);\n }\n\n patch(partial: Partial<R> | ((current: R) => R)): void {\n this.store.patch(this.inst, partial);\n }\n\n close(): void {\n const inst = this._inst;\n for (const l of this._mine) this.store._detach(inst, l);\n this._mine.clear();\n }\n\n then<T1 = R, T2 = never>(\n onfulfilled?: ((value: R) => T1 | PromiseLike<T1>) | null,\n onrejected?: ((reason: unknown) => T2 | PromiseLike<T2>) | null,\n ): Promise<T1 | T2> {\n return this._firstResult().then(onfulfilled, onrejected);\n }\n\n /** Resolves with the first successful data; the subscription it needs is released afterwards. */\n private _firstResult(): Promise<R> {\n const s = this.state;\n if (s.status === 'success') return Promise.resolve(s.data as R);\n if (s.status === 'error') return Promise.reject(s.error);\n return new Promise<R>((resolve, reject) => {\n const off = this.subscribe((st) => {\n if (st.status === 'success') {\n off();\n resolve(st.data as R);\n } else if (st.status === 'error') {\n off();\n reject(st.error);\n }\n });\n });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction addToIndex<K, V>(index: Map<K, Set<V>>, key: K, value: V): void {\n let set = index.get(key);\n if (!set) index.set(key, (set = new Set()));\n set.add(value);\n}\n\nfunction removeFromIndex<K, V>(index: Map<K, Set<V>>, key: K, value: V): void {\n const set = index.get(key);\n if (!set) return;\n set.delete(value);\n if (set.size === 0) index.delete(key);\n}\n\nfunction isTemplate(v: unknown): v is Template {\n return !!v && typeof v === 'object' && 'instances' in (v as object) && 'builder' in (v as object);\n}\n\n/** Every string value under an `id` key, at any depth. */\nexport function collectIds(value: unknown, into: Set<string>): Set<string> {\n if (Array.isArray(value)) {\n for (const v of value) collectIds(v, into);\n } else if (value && typeof value === 'object' && !(value instanceof Date)) {\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (k === 'id' && typeof v === 'string') into.add(v);\n else if (v && typeof v === 'object') collectIds(v, into);\n }\n }\n return into;\n}\n\n/** Deep equality over the plain-data results the store holds (objects, arrays, dates, primitives). */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a instanceof Date || b instanceof Date) {\n return a instanceof Date && b instanceof Date && a.getTime() === b.getTime();\n }\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n return a.every((v, i) => deepEqual(v, b[i]));\n }\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n const ka = Object.keys(a as object);\n const kb = Object.keys(b as object);\n if (ka.length !== kb.length) return false;\n return ka.every((k) => deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]));\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Registration\n// ---------------------------------------------------------------------------\n\n/** The runtime's live-query store (registered on `globalThis` when this module loads). */\nexport function getLiveQueryStore(): LiveQueryStore {\n let store = peekLiveQueryStore();\n if (!store) {\n store = new LiveQueryStore();\n setLiveQueryStore(store);\n }\n return store;\n}\n\n/** Publish a change from application code (your own transport, a server push). */\nexport function publishChange(event: ChangeEvent): void {\n getLiveQueryStore().publish(event, 'app');\n}\n\n/** Refetch every live query that `target` can have affected. See {@link LiveQueryStore.invalidate}. */\nexport function invalidate(target: ShapeConstructor<any> | string | {id: string} | LiveBuilder | Template): void {\n getLiveQueryStore().invalidate(target);\n}\n\nexport type {ChangeEvent, ChangeOrigin, MutationEffects};\n\n/** Replace the store with a fresh one (tests). */\nexport function resetLiveQueryStore(): LiveQueryStore {\n peekLiveQueryStore()?.dispose();\n const store = new LiveQueryStore();\n setLiveQueryStore(store);\n return store;\n}\n\n// Register on load: importing this module is what makes `.live()` work.\nif (!peekLiveQueryStore()) setLiveQueryStore(new LiveQueryStore());\n"]}
@@ -254,6 +254,13 @@ export declare class FieldSet<R = any, Source = any> {
254
254
  private static fromFields;
255
255
  /** Parse one field entry (string leaf / computed / relation-keyed) against `shape`. */
256
256
  private static parseField;
257
+ /**
258
+ * The shape sub-fields of `path` are read against: its terminal segment's value shape, or
259
+ * `shape` when that segment declares none. A declared value shape that does not resolve is
260
+ * an error: reading the sub-fields against `shape` instead would resolve them on the wrong
261
+ * shape (or fail with a message about the wrong property).
262
+ */
263
+ private static requireNestedShapeOf;
257
264
  /** The shape reached at the end of a relation path (its terminal segment's value shape). */
258
265
  private static nestedShapeOf;
259
266
  /**
@@ -5,6 +5,7 @@ import { createProxiedPathBuilder } from './ProxiedPathBuilder.js';
5
5
  import { isExpressionNode, ExpressionNode } from '../expressions/ExpressionNode.js';
6
6
  import { encodeValueExpr, decodeValueExpr } from './DslJsonExpression.js';
7
7
  import { serializeWherePath, deserializeWherePath, } from './QueryBuilderSerialization.js';
8
+ import { topLevelDetails, unresolvedShapeError, unresolvedValueShapeError } from '../utils/unresolvedShape.js';
8
9
  const isQueryBuilderObject = (obj) => obj !== null &&
9
10
  typeof obj === 'object' &&
10
11
  'property' in obj &&
@@ -398,7 +399,7 @@ export class FieldSet {
398
399
  }
399
400
  /** Parse one field entry (string leaf / computed / relation-keyed) against `shape`. */
400
401
  static parseField(shape, raw) {
401
- var _a, _b, _c, _d, _e;
402
+ var _a, _b, _c, _d;
402
403
  // Leaf path (may carry inline `as(Shape)` casts).
403
404
  if (typeof raw === 'string') {
404
405
  return { path: FieldSet.walkPathWithCasts(shape, raw) };
@@ -459,11 +460,31 @@ export class FieldSet {
459
460
  if (subFields) {
460
461
  const nested = opts.shape
461
462
  ? FieldSet.resolveShape(opts.shape)
462
- : (_e = FieldSet.nestedShapeOf(path)) !== null && _e !== void 0 ? _e : shape;
463
+ : FieldSet.requireNestedShapeOf(path, shape);
463
464
  entry.subSelect = FieldSet.fromFields(nested, subFields);
464
465
  }
465
466
  return entry;
466
467
  }
468
+ /**
469
+ * The shape sub-fields of `path` are read against: its terminal segment's value shape, or
470
+ * `shape` when that segment declares none. A declared value shape that does not resolve is
471
+ * an error: reading the sub-fields against `shape` instead would resolve them on the wrong
472
+ * shape (or fail with a message about the wrong property).
473
+ */
474
+ static requireNestedShapeOf(path, shape) {
475
+ var _a;
476
+ const nested = FieldSet.nestedShapeOf(path);
477
+ if (nested)
478
+ return nested;
479
+ const seg = path.segments[path.segments.length - 1];
480
+ if ((_a = seg === null || seg === void 0 ? void 0 : seg.valueShape) === null || _a === void 0 ? void 0 : _a.id) {
481
+ const owner = path.segments.length > 1
482
+ ? FieldSet.nestedShapeOf(new PropertyPath(path.rootShape, path.segments.slice(0, -1)))
483
+ : path.rootShape;
484
+ throw unresolvedValueShapeError(`Cannot resolve valueShape '${seg.valueShape.id}' for property '${seg.label}' in path '${path.toString()}'`, seg, owner);
485
+ }
486
+ return shape;
487
+ }
467
488
  /** The shape reached at the end of a relation path (its terminal segment's value shape). */
468
489
  static nestedShapeOf(path) {
469
490
  var _a, _b;
@@ -501,7 +522,7 @@ export class FieldSet {
501
522
  // below is already supported, it just was not reachable from an IRI.
502
523
  const nodeShape = getNodeShape(shape);
503
524
  if (!nodeShape) {
504
- throw new Error(`Cannot resolve shape for '${shape}'`);
525
+ throw unresolvedShapeError(`Cannot resolve shape for '${shape}'`, topLevelDetails(shape));
505
526
  }
506
527
  return { nodeShape };
507
528
  }
@@ -554,7 +575,7 @@ export class FieldSet {
554
575
  }
555
576
  const nestedShapeClass = getQueryShapeClass(basePropertyShape.valueShape);
556
577
  if (!nestedShapeClass || !nestedShapeClass.shape) {
557
- throw new Error(`Cannot resolve valueShape for property '${key}'`);
578
+ throw unresolvedValueShapeError(`Cannot resolve valueShape '${basePropertyShape.valueShape.id}' for property '${key}'`, basePropertyShape);
558
579
  }
559
580
  for (const nestedField of value) {
560
581
  const nestedPath = walkPropertyPath(nestedShapeClass.shape, nestedField);