@_linked/core 2.36.1 → 2.36.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +19 -0
  3. package/lib/esm/collections/CoreSet.js +2 -0
  4. package/lib/esm/collections/CoreSet.js.map +1 -1
  5. package/lib/esm/collections/ShapeSet.js +2 -0
  6. package/lib/esm/collections/ShapeSet.js.map +1 -1
  7. package/lib/esm/expressions/Expr.js +3 -2
  8. package/lib/esm/expressions/Expr.js.map +1 -1
  9. package/lib/esm/expressions/ExpressionNode.js +10 -7
  10. package/lib/esm/expressions/ExpressionNode.js.map +1 -1
  11. package/lib/esm/index.d.ts +1 -1
  12. package/lib/esm/index.js +1 -1
  13. package/lib/esm/index.js.map +1 -1
  14. package/lib/esm/queries/AskBuilder.js +5 -3
  15. package/lib/esm/queries/AskBuilder.js.map +1 -1
  16. package/lib/esm/queries/CountBuilder.js +4 -2
  17. package/lib/esm/queries/CountBuilder.js.map +1 -1
  18. package/lib/esm/queries/CreateBuilder.js +2 -0
  19. package/lib/esm/queries/CreateBuilder.js.map +1 -1
  20. package/lib/esm/queries/DeleteBuilder.js +3 -1
  21. package/lib/esm/queries/DeleteBuilder.js.map +1 -1
  22. package/lib/esm/queries/DslJsonExpression.js +7 -6
  23. package/lib/esm/queries/DslJsonExpression.js.map +1 -1
  24. package/lib/esm/queries/FieldSet.js +10 -8
  25. package/lib/esm/queries/FieldSet.js.map +1 -1
  26. package/lib/esm/queries/IRLower.js +2 -1
  27. package/lib/esm/queries/IRLower.js.map +1 -1
  28. package/lib/esm/queries/MutationSerialization.js +2 -1
  29. package/lib/esm/queries/MutationSerialization.js.map +1 -1
  30. package/lib/esm/queries/PropertyPath.js +2 -0
  31. package/lib/esm/queries/PropertyPath.js.map +1 -1
  32. package/lib/esm/queries/ProxiedPathBuilder.js +2 -1
  33. package/lib/esm/queries/ProxiedPathBuilder.js.map +1 -1
  34. package/lib/esm/queries/QueryBuilder.js +5 -4
  35. package/lib/esm/queries/QueryBuilder.js.map +1 -1
  36. package/lib/esm/queries/QueryContext.js +17 -6
  37. package/lib/esm/queries/QueryContext.js.map +1 -1
  38. package/lib/esm/queries/SelectQuery.js +18 -12
  39. package/lib/esm/queries/SelectQuery.js.map +1 -1
  40. package/lib/esm/queries/UpdateBuilder.js +3 -1
  41. package/lib/esm/queries/UpdateBuilder.js.map +1 -1
  42. package/lib/esm/queries/lower.js +5 -4
  43. package/lib/esm/queries/lower.js.map +1 -1
  44. package/lib/esm/shapes/SHACL.js +6 -3
  45. package/lib/esm/shapes/SHACL.js.map +1 -1
  46. package/lib/esm/shapes/Shape.d.ts +3 -1
  47. package/lib/esm/shapes/Shape.js +20 -2
  48. package/lib/esm/shapes/Shape.js.map +1 -1
  49. package/lib/esm/utils/LinkedErrorLogging.d.ts +2 -1
  50. package/lib/esm/utils/LinkedErrorLogging.js +11 -0
  51. package/lib/esm/utils/LinkedErrorLogging.js.map +1 -1
  52. package/lib/esm/utils/LinkedFileStorage.d.ts +6 -4
  53. package/lib/esm/utils/LinkedFileStorage.js +34 -4
  54. package/lib/esm/utils/LinkedFileStorage.js.map +1 -1
  55. package/lib/esm/utils/Package.d.ts +6 -0
  56. package/lib/esm/utils/Package.js +35 -7
  57. package/lib/esm/utils/Package.js.map +1 -1
  58. package/lib/esm/utils/Prefix.d.ts +4 -2
  59. package/lib/esm/utils/Prefix.js +18 -2
  60. package/lib/esm/utils/Prefix.js.map +1 -1
  61. package/lib/esm/utils/ShapeClass.js +11 -6
  62. package/lib/esm/utils/ShapeClass.js.map +1 -1
  63. package/lib/esm/utils/cached.js +2 -1
  64. package/lib/esm/utils/cached.js.map +1 -1
  65. package/lib/esm/utils/linkedError.d.ts +32 -0
  66. package/lib/esm/utils/linkedError.js +63 -0
  67. package/lib/esm/utils/linkedError.js.map +1 -1
  68. package/lib/esm/utils/unresolvedShape.d.ts +3 -1
  69. package/lib/esm/utils/unresolvedShape.js +5 -1
  70. package/lib/esm/utils/unresolvedShape.js.map +1 -1
  71. package/package.json +1 -1
@@ -24,6 +24,7 @@ import { buildCanonicalCreateMutationIR, buildCanonicalUpdateMutationIR, buildCa
24
24
  import { toWhere } from './IRDesugar.js';
25
25
  import { lowerWhereToIR } from './IRLower.js';
26
26
  import { attachCatalog, catalogOf, getActiveShapeCatalog, withShapeCatalog, } from '../utils/ShapeClass.js';
27
+ import { isLinkedInstance } from '../utils/linkedError.js';
27
28
  /** Lower a pre-evaluated where path to its canonical IR fragment. */
28
29
  function lowerWherePath(where) {
29
30
  return lowerWhereToIR(toWhere(where));
@@ -35,7 +36,7 @@ function lowerWherePath(where) {
35
36
  * context is resolved here and an unset one throws `UnresolvedContextError`.
36
37
  */
37
38
  function resolveValueContexts(val) {
38
- if (val instanceof PendingQueryContext) {
39
+ if (isLinkedInstance(val, PendingQueryContext)) {
39
40
  return { id: resolveContextId(val.contextName, true) };
40
41
  }
41
42
  if (Array.isArray(val)) {
@@ -96,7 +97,7 @@ function lowerDelete(spec) {
96
97
  }
97
98
  // Resolve any context-ref ids ({@ctx}) against the live map — a delete must hit
98
99
  // a concrete node, so an unresolved one throws (never a silent `{id: undefined}`).
99
- const resolvedIds = spec.ids.map((id) => id instanceof PendingQueryContext
100
+ const resolvedIds = spec.ids.map((id) => isLinkedInstance(id, PendingQueryContext)
100
101
  ? { id: resolveContextId(id.contextName, true) }
101
102
  : id);
102
103
  const ids = new MutationQueryFactory().normalizeNodeRefs(resolvedIds);
@@ -122,7 +123,7 @@ function lowerAsk(input) {
122
123
  const subject = input.subject;
123
124
  if (!input.shape) {
124
125
  // Shapeless: no rdf:type constraint, so no shape scan and no property refs.
125
- const id = subject instanceof PendingQueryContext
126
+ const id = isLinkedInstance(subject, PendingQueryContext)
126
127
  ? resolveContextId(subject.contextName, true)
127
128
  : subject === null || subject === void 0 ? void 0 : subject.id;
128
129
  return attachCatalog({ kind: 'ask', patterns: [], subjectId: id });
@@ -182,7 +183,7 @@ function lowerCount(input) {
182
183
  // straight to a store. Resolve it here, which throws `UnresolvedContextError` when
183
184
  // the context is unset — the same "not ready" a where-clause reference raises, and
184
185
  // never a plausible number.
185
- const subject = input.subject instanceof PendingQueryContext
186
+ const subject = isLinkedInstance(input.subject, PendingQueryContext)
186
187
  ? { id: resolveContextId(input.subject.contextName, true) }
187
188
  : input.subject;
188
189
  const selected = buildSelectQuery({
@@ -1 +1 @@
1
- {"version":3,"file":"lower.js","sourceRoot":"","sources":["../../../src/queries/lower.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;;;;;;;;GAWG;AACH,OAAO,EAAC,gBAAgB,EAAC,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAC,oBAAoB,EAAC,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAC,sBAAsB,EAA4B,MAAM,mBAAmB,CAAC;AACpF,OAAO,EAAC,mBAAmB,EAAC,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAC,gBAAgB,EAAC,MAAM,iBAAiB,CAAC;AACjD,OAAO,EACL,8BAA8B,EAC9B,8BAA8B,EAC9B,8BAA8B,EAC9B,mCAAmC,EACnC,8BAA8B,EAC9B,iCAAiC,EACjC,mCAAmC,GACpC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAC,OAAO,EAAC,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAAC,cAAc,EAAC,MAAM,cAAc,CAAC;AAC5C,OAAO,EACL,aAAa,EACb,SAAS,EACT,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,wBAAwB,CAAC;AAoChC,qEAAqE;AACrE,SAAS,cAAc,CAAC,KAAgB;IACtC,OAAO,cAAc,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;AACxC,CAAC;AAED;;;;;GAKG;AACH,SAAS,oBAAoB,CAAC,GAAY;IACxC,IAAI,GAAG,YAAY,mBAAmB,EAAE,CAAC;QACvC,OAAO,EAAC,EAAE,EAAE,gBAAgB,CAAC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KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;QACxC,KAAK,QAAQ;YACX,OAAO,WAAW,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;QACzC,KAAK,QAAQ;YACX,OAAO,WAAW,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;QACzC,KAAK,QAAQ;YACX,OAAO,WAAW,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;IAC3C,CAAC;AACH,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\n/**\n * `lower(query)` — turn a live query (builder) into its canonical IR algebra.\n *\n * This is the single, **free** lowering entry point, and the *only* place the\n * canonical-IR pipeline (`IRPipeline` / `IRMutation` / `IRLower` / …) is reached\n * from. The builders are deliberately IR-free: they hand `lower()` a plain\n * \"lowering spec\" (`mutationLowerSpec`) or raw select input, and all IR\n * construction happens here. A client that authors/serializes/forwards queries\n * but never calls `lower()` therefore tree-shakes the entire IR pipeline away.\n * The IR is an implementation detail of stores that want it (e.g. SPARQL) — not\n * the contract.\n */\nimport {buildSelectQuery} from './IRPipeline.js';\nimport {MutationQueryFactory} from './MutationQuery.js';\nimport {isSetModificationValue, type NodeDescriptionValue} from './QueryFactory.js';\nimport {PendingQueryContext} from './QueryContext.js';\nimport {resolveContextId} from './ContextRef.js';\nimport {\n buildCanonicalCreateMutationIR,\n buildCanonicalUpdateMutationIR,\n buildCanonicalUpsertMutationIR,\n buildCanonicalUpdateWhereMutationIR,\n buildCanonicalDeleteMutationIR,\n buildCanonicalDeleteAllMutationIR,\n buildCanonicalDeleteWhereMutationIR,\n} from './IRMutation.js';\nimport {toWhere} from './IRDesugar.js';\nimport {lowerWhereToIR} from './IRLower.js';\nimport {\n attachCatalog,\n catalogOf,\n getActiveShapeCatalog,\n withShapeCatalog,\n} from '../utils/ShapeClass.js';\nimport type {WherePath} from './SelectQuery.js';\nimport type {\n IRAskQuery,\n IRCountQuery,\n IRSelectQuery,\n} from './IntermediateRepresentation.js';\nimport type {RawAskInput} from './AskQuery.js';\nimport type {RawCountInput} from './CountQuery.js';\nimport type {IRCreateQuery} from './CreateQuery.js';\nimport type {IRUpdateQuery} from './UpdateQuery.js';\nimport type {IRDeleteQuery} from './DeleteQuery.js';\nimport type {\n CreateLowerSpec,\n UpdateLowerSpec,\n DeleteLowerSpec,\n} from './mutationLowerSpec.js';\n\n/** A select query that can be lowered (the select builder). */\nexport type LowerableSelect = {readonly __queryKind: 'select'; toRawInput(): any};\n/** An ask query that can be lowered (the ask builder). */\nexport type LowerableAsk = {readonly __queryKind: 'ask'; toRawInput(): RawAskInput};\n/** A count query that can be lowered (the count builder). */\nexport type LowerableCount = {readonly __queryKind: 'count'; toRawInput(): RawCountInput};\n/** A mutation query that can be lowered (the mutation builders). */\nexport type LowerableCreate = {readonly __queryKind: 'create'; _lowerSpec(): CreateLowerSpec};\nexport type LowerableUpdate = {readonly __queryKind: 'update'; _lowerSpec(): UpdateLowerSpec};\nexport type LowerableDelete = {readonly __queryKind: 'delete'; _lowerSpec(): DeleteLowerSpec};\nexport type LowerableQuery =\n | LowerableSelect\n | LowerableAsk\n | LowerableCount\n | LowerableCreate\n | LowerableUpdate\n | LowerableDelete;\n\n/** Lower a pre-evaluated where path to its canonical IR fragment. */\nfunction lowerWherePath(where: WherePath) {\n return lowerWhereToIR(toWhere(where));\n}\n\n/**\n * Resolve any query-context reference carried as a mutation field value. The\n * builder preserves a live `PendingQueryContext` through normalization (so it can\n * serialize as `{@ctx}`); at lowering a mutation must hit a concrete node, so the\n * context is resolved here and an unset one throws `UnresolvedContextError`.\n */\nfunction resolveValueContexts(val: unknown): unknown {\n if (val instanceof PendingQueryContext) {\n return {id: resolveContextId(val.contextName, true)!};\n }\n if (Array.isArray(val)) {\n return val.map(resolveValueContexts);\n }\n if (val && typeof val === 'object') {\n if (isSetModificationValue(val)) {\n const mod = val as {$add?: unknown[]; $remove?: unknown[]};\n const out: {$add?: unknown[]; $remove?: unknown[]} = {};\n if (mod.$add) out.$add = mod.$add.map(resolveValueContexts);\n if (mod.$remove) out.$remove = mod.$remove.map(resolveValueContexts);\n return out;\n }\n if ('fields' in val) {\n return resolveDescriptionContexts(val as NodeDescriptionValue);\n }\n }\n return val;\n}\n\n/** Deep-resolve context references in a normalized node description (returns a new copy). */\nfunction resolveDescriptionContexts(desc: NodeDescriptionValue): NodeDescriptionValue {\n return {\n ...desc,\n fields: desc.fields.map((f) => ({...f, val: resolveValueContexts(f.val) as typeof f.val})),\n };\n}\n\nfunction lowerCreate(spec: CreateLowerSpec): IRCreateQuery {\n const description = resolveDescriptionContexts(\n new MutationQueryFactory().describe(spec.shapeClass.shape, spec.data, {\n allowTopLevelId: true,\n validate: 'complete',\n }),\n );\n return buildCanonicalCreateMutationIR({shape: spec.shapeClass.shape, description});\n}\n\nfunction lowerUpdate(spec: UpdateLowerSpec): IRUpdateQuery {\n const shape = spec.shapeClass.shape;\n const updates = resolveDescriptionContexts(\n new MutationQueryFactory().describe(shape, spec.data, {validate: 'partial'}),\n );\n if (spec.mode === 'for') {\n return spec.upsert\n ? buildCanonicalUpsertMutationIR({id: spec.targetId!, shape, updates})\n : buildCanonicalUpdateMutationIR({id: spec.targetId!, shape, updates});\n }\n // forAll / where\n const lowered = spec.wherePath ? lowerWherePath(spec.wherePath) : undefined;\n return buildCanonicalUpdateWhereMutationIR({\n shape,\n updates,\n where: lowered?.where,\n wherePatterns: lowered?.wherePatterns,\n });\n}\n\nfunction lowerDelete(spec: DeleteLowerSpec): IRDeleteQuery {\n const shape = spec.shapeClass.shape;\n if (spec.mode === 'all') {\n return buildCanonicalDeleteAllMutationIR({shape});\n }\n if (spec.mode === 'where') {\n const {where, wherePatterns} = lowerWherePath(spec.wherePath!);\n return buildCanonicalDeleteWhereMutationIR({shape, where, wherePatterns});\n }\n // Resolve any context-ref ids ({@ctx}) against the live map — a delete must hit\n // a concrete node, so an unresolved one throws (never a silent `{id: undefined}`).\n const resolvedIds = spec.ids!.map((id) =>\n id instanceof PendingQueryContext\n ? {id: resolveContextId(id.contextName, true)!}\n : id,\n );\n const ids = new MutationQueryFactory().normalizeNodeRefs(resolvedIds);\n return buildCanonicalDeleteMutationIR({shape, ids});\n}\n\n/**\n * Lower an ask to its canonical IR.\n *\n * The shaped case reuses the select pipeline to build the pattern — one\n * implementation of shape scans, traversals, filters and minus — and then keeps\n * only the pattern-bearing part. The rootless (shapeless) case has no pattern to\n * build: it is a bare subject.\n */\nfunction lowerAsk(input: RawAskInput): IRAskQuery {\n if (input.nullSubject) {\n // \"Does the node with no id exist?\" is answered `false` without querying —\n // `AskBuilder.exec` does that before dispatching. Reaching lowering means a\n // store took the builder off the normal path; a subject-less pattern would\n // match every instance of the shape and answer `true`, so refuse it loudly.\n throw new Error(\n 'Cannot lower an ask query with no subject (`.for(null)`). It resolves to ' +\n '`false` without querying — execute it through `exec()` rather than lowering it.',\n );\n }\n const subject = input.subject;\n if (!input.shape) {\n // Shapeless: no rdf:type constraint, so no shape scan and no property refs.\n const id =\n subject instanceof PendingQueryContext\n ? resolveContextId(subject.contextName, true)!\n : (subject as {id?: string} | undefined)?.id;\n return attachCatalog<IRAskQuery>({kind: 'ask', patterns: [], subjectId: id});\n }\n const selected = buildSelectQuery({\n entries: [],\n shape: input.shape,\n subject,\n subjects: input.subjects,\n where: input.where,\n minusEntries: input.minusEntries,\n });\n return attachCatalog<IRAskQuery>({\n kind: 'ask',\n root: selected.root,\n patterns: selected.patterns,\n where: selected.where,\n subjectId: selected.subjectId,\n subjectIds: selected.subjectIds,\n });\n}\n\n/**\n * The variable a root count binds its `COUNT` to.\n *\n * Chosen not to collide with the `a<N>` alias scheme the pipeline generates for\n * the root and every traversal, so it never needs the collision rename\n * `selectToAlgebra` applies to aggregate aliases.\n */\nexport const COUNT_ALIAS = 'count';\n\n/**\n * Lower a count to its canonical IR.\n *\n * Reuses the select pipeline to build the pattern — one implementation of shape\n * scans, traversals, filters and minus — and then keeps only the pattern-bearing\n * part, exactly as {@link lowerAsk} does. The `entries: []` is why nothing is\n * projected: a count has no projection to build.\n */\nfunction lowerCount(input: RawCountInput): IRCountQuery {\n if (input.nullSubject) {\n // \"How many nodes with no id match?\" is answered `0` without querying —\n // `CountBuilder.exec` does that before dispatching. Reaching lowering means a\n // store took the builder off the normal path; a subject-less pattern would\n // count every instance of the shape and report it as the count of one node.\n throw new Error(\n 'Cannot lower a count query with no subject (`.for(null)`). It resolves to ' +\n '`0` without querying — execute it through `exec()` rather than lowering it.',\n );\n }\n if (!input.shape) {\n throw new Error(\n 'Cannot lower a count query with no shape. A shapeless count would count ' +\n 'every node in the store, under any type or none.',\n );\n }\n // A `{\"@ctx\": name}` subject arrives here as a live PendingQueryContext, and\n // `buildSelectQuery` narrows a subject with `'id' in subject` — so an UNRESOLVED\n // one would quietly yield `subjectId: undefined` and the count would be of every\n // instance of the shape, reported as the count of one node. `CountBuilder.exec`\n // answers `0` for that case before dispatching, but this path is reached without\n // it: a receiver that rehydrates an envelope with `fromJSON` and hands the builder\n // straight to a store. Resolve it here, which throws `UnresolvedContextError` when\n // the context is unset — the same \"not ready\" a where-clause reference raises, and\n // never a plausible number.\n const subject =\n input.subject instanceof PendingQueryContext\n ? {id: resolveContextId(input.subject.contextName, true)!}\n : input.subject;\n const selected = buildSelectQuery({\n entries: [],\n shape: input.shape,\n subject,\n subjects: input.subjects,\n where: input.where,\n minusEntries: input.minusEntries,\n });\n return attachCatalog<IRCountQuery>({\n kind: 'count',\n root: selected.root,\n patterns: selected.patterns,\n where: selected.where,\n subjectId: selected.subjectId,\n subjectIds: selected.subjectIds,\n alias: COUNT_ALIAS,\n });\n}\n\nexport function lower(query: LowerableSelect): IRSelectQuery;\nexport function lower(query: LowerableAsk): IRAskQuery;\nexport function lower(query: LowerableCount): IRCountQuery;\nexport function lower(query: LowerableCreate): IRCreateQuery;\nexport function lower(query: LowerableUpdate): IRUpdateQuery;\nexport function lower(query: LowerableDelete): IRDeleteQuery;\nexport function lower(\n query: LowerableQuery,\n):\n | IRSelectQuery\n | IRAskQuery\n | IRCountQuery\n | IRCreateQuery\n | IRUpdateQuery\n | IRDeleteQuery {\n // Lower in the catalog the query captured; the IR it returns records it (non-enumerable\n // `catalog`) for the compile that may run after an await.\n const catalog = catalogOf(query);\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => lower(query as LowerableSelect));\n }\n switch (query.__queryKind) {\n case 'select':\n return buildSelectQuery(query.toRawInput());\n case 'ask':\n return lowerAsk(query.toRawInput());\n case 'count':\n return lowerCount(query.toRawInput());\n case 'create':\n return lowerCreate(query._lowerSpec());\n case 'update':\n return lowerUpdate(query._lowerSpec());\n case 'delete':\n return lowerDelete(query._lowerSpec());\n }\n}\n"]}
1
+ {"version":3,"file":"lower.js","sourceRoot":"","sources":["../../../src/queries/lower.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;;;;;;;;GAWG;AACH,OAAO,EAAC,gBAAgB,EAAC,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAC,oBAAoB,EAAC,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAC,sBAAsB,EAA4B,MAAM,mBAAmB,CAAC;AACpF,OAAO,EAAC,mBAAmB,EAAC,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAC,gBAAgB,EAAC,MAAM,iBAAiB,CAAC;AACjD,OAAO,EACL,8BAA8B,EAC9B,8BAA8B,EAC9B,8BAA8B,EAC9B,mCAAmC,EACnC,8BAA8B,EAC9B,iCAAiC,EACjC,mCAAmC,GACpC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAC,OAAO,EAAC,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAAC,cAAc,EAAC,MAAM,cAAc,CAAC;AAC5C,OAAO,EACL,aAAa,EACb,SAAS,EACT,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,wBAAwB,CAAC;AAiBhC,OAAO,EAAC,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B,EAAE,EAAE,CAAC;QACxC,OAAO,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,KAAwB,CAAC,CAAC,CAAC;IAC1E,CAAC;IACD,QAAQ,KAAK,CAAC,WAAW,EAAE,CAAC;QAC1B,KAAK,QAAQ;YACX,OAAO,gBAAgB,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;QAC9C,KAAK,KAAK;YACR,OAAO,QAAQ,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;QACtC,KAAK,OAAO;YACV,OAAO,UAAU,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;QACxC,KAAK,QAAQ;YACX,OAAO,WAAW,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;QACzC,KAAK,QAAQ;YACX,OAAO,WAAW,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;QACzC,KAAK,QAAQ;YACX,OAAO,WAAW,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;IAC3C,CAAC;AACH,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\n/**\n * `lower(query)` — turn a live query (builder) into its canonical IR algebra.\n *\n * This is the single, **free** lowering entry point, and the *only* place the\n * canonical-IR pipeline (`IRPipeline` / `IRMutation` / `IRLower` / …) is reached\n * from. The builders are deliberately IR-free: they hand `lower()` a plain\n * \"lowering spec\" (`mutationLowerSpec`) or raw select input, and all IR\n * construction happens here. A client that authors/serializes/forwards queries\n * but never calls `lower()` therefore tree-shakes the entire IR pipeline away.\n * The IR is an implementation detail of stores that want it (e.g. SPARQL) — not\n * the contract.\n */\nimport {buildSelectQuery} from './IRPipeline.js';\nimport {MutationQueryFactory} from './MutationQuery.js';\nimport {isSetModificationValue, type NodeDescriptionValue} from './QueryFactory.js';\nimport {PendingQueryContext} from './QueryContext.js';\nimport {resolveContextId} from './ContextRef.js';\nimport {\n buildCanonicalCreateMutationIR,\n buildCanonicalUpdateMutationIR,\n buildCanonicalUpsertMutationIR,\n buildCanonicalUpdateWhereMutationIR,\n buildCanonicalDeleteMutationIR,\n buildCanonicalDeleteAllMutationIR,\n buildCanonicalDeleteWhereMutationIR,\n} from './IRMutation.js';\nimport {toWhere} from './IRDesugar.js';\nimport {lowerWhereToIR} from './IRLower.js';\nimport {\n attachCatalog,\n catalogOf,\n getActiveShapeCatalog,\n withShapeCatalog,\n} from '../utils/ShapeClass.js';\nimport type {WherePath} from './SelectQuery.js';\nimport type {\n IRAskQuery,\n IRCountQuery,\n IRSelectQuery,\n} from './IntermediateRepresentation.js';\nimport type {RawAskInput} from './AskQuery.js';\nimport type {RawCountInput} from './CountQuery.js';\nimport type {IRCreateQuery} from './CreateQuery.js';\nimport type {IRUpdateQuery} from './UpdateQuery.js';\nimport type {IRDeleteQuery} from './DeleteQuery.js';\nimport type {\n CreateLowerSpec,\n UpdateLowerSpec,\n DeleteLowerSpec,\n} from './mutationLowerSpec.js';\nimport {isLinkedInstance} from '../utils/linkedError.js';\n\n/** A select query that can be lowered (the select builder). */\nexport type LowerableSelect = {readonly __queryKind: 'select'; toRawInput(): any};\n/** An ask query that can be lowered (the ask builder). */\nexport type LowerableAsk = {readonly __queryKind: 'ask'; toRawInput(): RawAskInput};\n/** A count query that can be lowered (the count builder). */\nexport type LowerableCount = {readonly __queryKind: 'count'; toRawInput(): RawCountInput};\n/** A mutation query that can be lowered (the mutation builders). */\nexport type LowerableCreate = {readonly __queryKind: 'create'; _lowerSpec(): CreateLowerSpec};\nexport type LowerableUpdate = {readonly __queryKind: 'update'; _lowerSpec(): UpdateLowerSpec};\nexport type LowerableDelete = {readonly __queryKind: 'delete'; _lowerSpec(): DeleteLowerSpec};\nexport type LowerableQuery =\n | LowerableSelect\n | LowerableAsk\n | LowerableCount\n | LowerableCreate\n | LowerableUpdate\n | LowerableDelete;\n\n/** Lower a pre-evaluated where path to its canonical IR fragment. */\nfunction lowerWherePath(where: WherePath) {\n return lowerWhereToIR(toWhere(where));\n}\n\n/**\n * Resolve any query-context reference carried as a mutation field value. The\n * builder preserves a live `PendingQueryContext` through normalization (so it can\n * serialize as `{@ctx}`); at lowering a mutation must hit a concrete node, so the\n * context is resolved here and an unset one throws `UnresolvedContextError`.\n */\nfunction resolveValueContexts(val: unknown): unknown {\n if (isLinkedInstance(val, PendingQueryContext)) {\n return {id: resolveContextId(val.contextName, true)!};\n }\n if (Array.isArray(val)) {\n return val.map(resolveValueContexts);\n }\n if (val && typeof val === 'object') {\n if (isSetModificationValue(val)) {\n const mod = val as {$add?: unknown[]; $remove?: unknown[]};\n const out: {$add?: unknown[]; $remove?: unknown[]} = {};\n if (mod.$add) out.$add = mod.$add.map(resolveValueContexts);\n if (mod.$remove) out.$remove = mod.$remove.map(resolveValueContexts);\n return out;\n }\n if ('fields' in val) {\n return resolveDescriptionContexts(val as NodeDescriptionValue);\n }\n }\n return val;\n}\n\n/** Deep-resolve context references in a normalized node description (returns a new copy). */\nfunction resolveDescriptionContexts(desc: NodeDescriptionValue): NodeDescriptionValue {\n return {\n ...desc,\n fields: desc.fields.map((f) => ({...f, val: resolveValueContexts(f.val) as typeof f.val})),\n };\n}\n\nfunction lowerCreate(spec: CreateLowerSpec): IRCreateQuery {\n const description = resolveDescriptionContexts(\n new MutationQueryFactory().describe(spec.shapeClass.shape, spec.data, {\n allowTopLevelId: true,\n validate: 'complete',\n }),\n );\n return buildCanonicalCreateMutationIR({shape: spec.shapeClass.shape, description});\n}\n\nfunction lowerUpdate(spec: UpdateLowerSpec): IRUpdateQuery {\n const shape = spec.shapeClass.shape;\n const updates = resolveDescriptionContexts(\n new MutationQueryFactory().describe(shape, spec.data, {validate: 'partial'}),\n );\n if (spec.mode === 'for') {\n return spec.upsert\n ? buildCanonicalUpsertMutationIR({id: spec.targetId!, shape, updates})\n : buildCanonicalUpdateMutationIR({id: spec.targetId!, shape, updates});\n }\n // forAll / where\n const lowered = spec.wherePath ? lowerWherePath(spec.wherePath) : undefined;\n return buildCanonicalUpdateWhereMutationIR({\n shape,\n updates,\n where: lowered?.where,\n wherePatterns: lowered?.wherePatterns,\n });\n}\n\nfunction lowerDelete(spec: DeleteLowerSpec): IRDeleteQuery {\n const shape = spec.shapeClass.shape;\n if (spec.mode === 'all') {\n return buildCanonicalDeleteAllMutationIR({shape});\n }\n if (spec.mode === 'where') {\n const {where, wherePatterns} = lowerWherePath(spec.wherePath!);\n return buildCanonicalDeleteWhereMutationIR({shape, where, wherePatterns});\n }\n // Resolve any context-ref ids ({@ctx}) against the live map — a delete must hit\n // a concrete node, so an unresolved one throws (never a silent `{id: undefined}`).\n const resolvedIds = spec.ids!.map((id) =>\n isLinkedInstance(id, PendingQueryContext)\n ? {id: resolveContextId(id.contextName, true)!}\n : id,\n );\n const ids = new MutationQueryFactory().normalizeNodeRefs(resolvedIds);\n return buildCanonicalDeleteMutationIR({shape, ids});\n}\n\n/**\n * Lower an ask to its canonical IR.\n *\n * The shaped case reuses the select pipeline to build the pattern — one\n * implementation of shape scans, traversals, filters and minus — and then keeps\n * only the pattern-bearing part. The rootless (shapeless) case has no pattern to\n * build: it is a bare subject.\n */\nfunction lowerAsk(input: RawAskInput): IRAskQuery {\n if (input.nullSubject) {\n // \"Does the node with no id exist?\" is answered `false` without querying —\n // `AskBuilder.exec` does that before dispatching. Reaching lowering means a\n // store took the builder off the normal path; a subject-less pattern would\n // match every instance of the shape and answer `true`, so refuse it loudly.\n throw new Error(\n 'Cannot lower an ask query with no subject (`.for(null)`). It resolves to ' +\n '`false` without querying — execute it through `exec()` rather than lowering it.',\n );\n }\n const subject = input.subject;\n if (!input.shape) {\n // Shapeless: no rdf:type constraint, so no shape scan and no property refs.\n const id =\n isLinkedInstance(subject, PendingQueryContext)\n ? resolveContextId(subject.contextName, true)!\n : (subject as {id?: string} | undefined)?.id;\n return attachCatalog<IRAskQuery>({kind: 'ask', patterns: [], subjectId: id});\n }\n const selected = buildSelectQuery({\n entries: [],\n shape: input.shape,\n subject,\n subjects: input.subjects,\n where: input.where,\n minusEntries: input.minusEntries,\n });\n return attachCatalog<IRAskQuery>({\n kind: 'ask',\n root: selected.root,\n patterns: selected.patterns,\n where: selected.where,\n subjectId: selected.subjectId,\n subjectIds: selected.subjectIds,\n });\n}\n\n/**\n * The variable a root count binds its `COUNT` to.\n *\n * Chosen not to collide with the `a<N>` alias scheme the pipeline generates for\n * the root and every traversal, so it never needs the collision rename\n * `selectToAlgebra` applies to aggregate aliases.\n */\nexport const COUNT_ALIAS = 'count';\n\n/**\n * Lower a count to its canonical IR.\n *\n * Reuses the select pipeline to build the pattern — one implementation of shape\n * scans, traversals, filters and minus — and then keeps only the pattern-bearing\n * part, exactly as {@link lowerAsk} does. The `entries: []` is why nothing is\n * projected: a count has no projection to build.\n */\nfunction lowerCount(input: RawCountInput): IRCountQuery {\n if (input.nullSubject) {\n // \"How many nodes with no id match?\" is answered `0` without querying —\n // `CountBuilder.exec` does that before dispatching. Reaching lowering means a\n // store took the builder off the normal path; a subject-less pattern would\n // count every instance of the shape and report it as the count of one node.\n throw new Error(\n 'Cannot lower a count query with no subject (`.for(null)`). It resolves to ' +\n '`0` without querying — execute it through `exec()` rather than lowering it.',\n );\n }\n if (!input.shape) {\n throw new Error(\n 'Cannot lower a count query with no shape. A shapeless count would count ' +\n 'every node in the store, under any type or none.',\n );\n }\n // A `{\"@ctx\": name}` subject arrives here as a live PendingQueryContext, and\n // `buildSelectQuery` narrows a subject with `'id' in subject` — so an UNRESOLVED\n // one would quietly yield `subjectId: undefined` and the count would be of every\n // instance of the shape, reported as the count of one node. `CountBuilder.exec`\n // answers `0` for that case before dispatching, but this path is reached without\n // it: a receiver that rehydrates an envelope with `fromJSON` and hands the builder\n // straight to a store. Resolve it here, which throws `UnresolvedContextError` when\n // the context is unset — the same \"not ready\" a where-clause reference raises, and\n // never a plausible number.\n const subject =\n isLinkedInstance(input.subject, PendingQueryContext)\n ? {id: resolveContextId(input.subject.contextName, true)!}\n : input.subject;\n const selected = buildSelectQuery({\n entries: [],\n shape: input.shape,\n subject,\n subjects: input.subjects,\n where: input.where,\n minusEntries: input.minusEntries,\n });\n return attachCatalog<IRCountQuery>({\n kind: 'count',\n root: selected.root,\n patterns: selected.patterns,\n where: selected.where,\n subjectId: selected.subjectId,\n subjectIds: selected.subjectIds,\n alias: COUNT_ALIAS,\n });\n}\n\nexport function lower(query: LowerableSelect): IRSelectQuery;\nexport function lower(query: LowerableAsk): IRAskQuery;\nexport function lower(query: LowerableCount): IRCountQuery;\nexport function lower(query: LowerableCreate): IRCreateQuery;\nexport function lower(query: LowerableUpdate): IRUpdateQuery;\nexport function lower(query: LowerableDelete): IRDeleteQuery;\nexport function lower(\n query: LowerableQuery,\n):\n | IRSelectQuery\n | IRAskQuery\n | IRCountQuery\n | IRCreateQuery\n | IRUpdateQuery\n | IRDeleteQuery {\n // Lower in the catalog the query captured; the IR it returns records it (non-enumerable\n // `catalog`) for the compile that may run after an await.\n const catalog = catalogOf(query);\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => lower(query as LowerableSelect));\n }\n switch (query.__queryKind) {\n case 'select':\n return buildSelectQuery(query.toRawInput());\n case 'ask':\n return lowerAsk(query.toRawInput());\n case 'count':\n return lowerCount(query.toRawInput());\n case 'create':\n return lowerCreate(query._lowerSpec());\n case 'update':\n return lowerUpdate(query._lowerSpec());\n case 'delete':\n return lowerDelete(query._lowerSpec());\n }\n}\n"]}
@@ -8,6 +8,7 @@ import { Shape } from './Shape.js';
8
8
  import { shacl } from '../ontologies/shacl.js';
9
9
  import { warnOnReservedPropertyLabel } from '../queries/reservedQueryNames.js';
10
10
  import { getShapeClass } from '../utils/ShapeClass.js';
11
+ import { sharedState } from '../utils/sharedState.js';
11
12
  import { normalizePropertyPath } from '../paths/normalizePropertyPath.js';
12
13
  import { createPropertyShapeData, getPropertyShape as getPropertyShapeData, addPropertyShape as addPropertyShapeData, clonePropertyShape, } from './nodeShapeData.js';
13
14
  // Metadata operations (formerly NodeShape/PropertyShape instance methods).
@@ -41,9 +42,10 @@ export function packageNameToSlug(packageName) {
41
42
  * Where each package publishes its IRIs (the identity root). The slug is always
42
43
  * derived from the package name; only the root is configurable — `linkedPackage`
43
44
  * defaults it to `LINKED_DATA_ROOT` (linked.cm), and CN injects a workspace-scoped
44
- * root (`{workspaceSlug}.id.create.now`) for private packages.
45
+ * root (`{workspaceSlug}.id.create.now`) for private packages. Shared by every copy of core,
46
+ * so a private package's root holds whichever copy derives its IRIs.
45
47
  */
46
- const packageBaseUri = new Map();
48
+ const packageBaseUri = sharedState('@_linked/core', 'SHACL.packageBaseUri', () => new Map());
47
49
  /** Record a package's publish root. Called by `linkedPackage()`. */
48
50
  export function setPackagePublishConfig(packageName, config) {
49
51
  var _a;
@@ -398,7 +400,8 @@ export function getNodeShapeUri(packageName, shapeName) {
398
400
  // (it is a class name, already URI-safe), packageSlug derived from the name.
399
401
  return `${resolveBaseUri(packageName)}shape/${packageNameToSlug(packageName)}/${shapeName}`;
400
402
  }
401
- const nodeShapeCallbacks = new Map();
403
+ /** Callbacks waiting for a node shape to register, shared so a registration through any copy of core fires them. */
404
+ const nodeShapeCallbacks = sharedState('@_linked/core', 'SHACL.nodeShapeCallbacks', () => new Map());
402
405
  export function getAndClearCallbacks(nodeShapeId) {
403
406
  const callbacks = nodeShapeCallbacks.get(nodeShapeId);
404
407
  nodeShapeCallbacks.delete(nodeShapeId);
@@ -1 +1 @@
1
- {"version":3,"file":"SHACL.js","sourceRoot":"","sources":["../../../src/shapes/SHACL.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAA0B,eAAe,EAAC,MAAM,2BAA2B,CAAC;AACnF,OAAO,EAAC,KAAK,EAAwB,MAAM,YAAY,CAAC;AACxD,OAAO,EAAC,KAAK,EAAC,MAAM,wBAAwB,CAAC;AAC7C,OAAO,EAAC,2BAA2B,EAAC,MAAM,kCAAkC,CA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,GAAG,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;IAC1C,CAAC;IACD,kBAAkB,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AACrD,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 {type NodeReferenceValue, toNodeReference} from '../utils/NodeReference.js';\nimport {Shape, type ShapeConstructor} from './Shape.js';\nimport {shacl} from '../ontologies/shacl.js';\nimport {warnOnReservedPropertyLabel} from '../queries/reservedQueryNames.js';\nimport {getShapeClass} from '../utils/ShapeClass.js';\nimport type {PathExpr} from '../paths/PropertyPathExpr.js';\nimport {normalizePropertyPath, type PropertyPathDecoratorInput} from '../paths/normalizePropertyPath.js';\nimport {\n createPropertyShapeData,\n getPropertyShape as getPropertyShapeData,\n addPropertyShape as addPropertyShapeData,\n clonePropertyShape,\n type NodeShapeData,\n type PropertyShapeData,\n} from './nodeShapeData.js';\n\n// Metadata types now live in nodeShapeData.js (plain objects); re-exported here for\n// existing importers of `NodeShape`/`PropertyShape`-adjacent types.\nexport type {NodeShapeData, PropertyShapeData, PropertyShapeResult} from './nodeShapeData.js';\n// Metadata operations (formerly NodeShape/PropertyShape instance methods).\nexport {\n getPropertyShapes,\n getUniquePropertyShapes,\n getPropertyShape,\n addPropertyShape,\n clonePropertyShape,\n propertyShapeToResult,\n nodeShapeEquals,\n createNodeShapeData,\n createPropertyShapeData,\n} from './nodeShapeData.js';\n\n/**\n * Default identity root for shape & package IRIs. Public/first-party packages\n * publish under `linked.cm` (arch-02 §Domains). Packages may override per-package\n * via `linkedPackage(name, { baseUri })` — CN injects a workspace-scoped root\n * (`{workspaceSlug}.id.create.now`) for private packages; first-party packages\n * keep this default.\n */\nexport const LINKED_DATA_ROOT: string = 'https://linked.cm/';\n\n/**\n * Derive the public package slug — the npm package **basename** with the\n * `@scope/` dropped, kebab-cased (arch-02 §Slug rules: `^[a-z0-9]+(?:-[a-z0-9]+)*$`).\n * The package name is the single source of truth; there is no separate slug.\n * `@_linked/core` → `core`, `@linked.cm/blog` → `blog`, `mypkg` → `mypkg`.\n *\n * Both first-party (`@_linked`) and community (`@linked.cm`) packages publish into\n * the one `linked.cm/{shape,pkg}` space, so the basename must be globally unique —\n * enforced by the registry, which reserves the (handful of) first-party names.\n */\nexport function packageNameToSlug(packageName: string): string {\n return packageName\n .replace(/^@[^/]+\\//, '') // drop the npm scope (@scope/), keep the basename\n .replace(/[^a-zA-Z0-9]+/g, '-') // any run of non-alphanumerics → single hyphen\n .replace(/^-+|-+$/g, '') // trim stray hyphens\n .toLowerCase();\n}\n\n/**\n * Where each package publishes its IRIs (the identity root). The slug is always\n * derived from the package name; only the root is configurable — `linkedPackage`\n * defaults it to `LINKED_DATA_ROOT` (linked.cm), and CN injects a workspace-scoped\n * root (`{workspaceSlug}.id.create.now`) for private packages.\n */\nconst packageBaseUri = new Map<string, string>();\n\n/** Record a package's publish root. Called by `linkedPackage()`. */\nexport function setPackagePublishConfig(\n packageName: string,\n config?: {baseUri?: string},\n): void {\n packageBaseUri.set(packageName, config?.baseUri ?? LINKED_DATA_ROOT);\n}\n\n/** Resolve a package's publish root, defaulting to linked.cm if undeclared. */\nfunction resolveBaseUri(packageName: string): string {\n return packageBaseUri.get(packageName) ?? LINKED_DATA_ROOT;\n}\n\n/** Public/first-party package IRI — arch-02: `{baseUri}pkg/{slug}`. */\nexport function getPackageUri(packageName: string): string {\n return `${resolveBaseUri(packageName)}pkg/${packageNameToSlug(packageName)}`;\n}\n\ntype NodeKindConfig = NodeReferenceValue | NodeReferenceValue[];\n\nexport type PropertyPathInput = PropertyPathDecoratorInput;\nexport type PropertyPathInputList = PropertyPathDecoratorInput;\n\nconst normalizeNodeKind = (\n nodeKind?: NodeKindConfig,\n defaultNodeKind?: NodeReferenceValue,\n): NodeReferenceValue | undefined => {\n if (!nodeKind) {\n return defaultNodeKind;\n }\n if (Array.isArray(nodeKind)) {\n const ids = nodeKind.map((entry) => entry?.id);\n const includesBlank = ids.includes(shacl.BlankNode.id);\n const includesNamed = ids.includes(shacl.IRI.id);\n const includesLiteral = ids.includes(shacl.Literal.id);\n if (includesBlank && includesNamed) {\n return shacl.BlankNodeOrIRI;\n }\n if (includesLiteral && includesNamed) {\n return shacl.IRIOrLiteral;\n }\n if (includesLiteral && includesBlank) {\n return shacl.BlankNodeOrLiteral;\n }\n return nodeKind[0];\n }\n return nodeKind;\n};\n\nexport interface NodeShapeConfig {\n /**\n * Set to true to close the shape. This means any target node of this shape\n * that has properties outside the defined properties of this shape is invalid.\n */\n closed?: boolean;\n /**\n * Optional list of properties that are also permitted in addition to those explicitly listed by this shape.\n */\n ignoredProperties?: NodeReferenceValue[];\n}\n\nexport interface LiteralPropertyShapeConfig extends PropertyShapeConfig {\n nodeKind?: NodeReferenceValue;\n /**\n * Values of the configured property must be less than the values of this 'lessThan' property.\n * Value is always a property IRI (pair constraint).\n */\n lessThan?: NodeReferenceValue;\n /**\n * Values of the configured property must be less than or equal the values of this 'lessThanOrEquals' property.\n * Value is always a property IRI (pair constraint).\n */\n lessThanOrEquals?: NodeReferenceValue;\n /**\n * All values of this property must be higher than this number\n */\n minExclusive?: number | string;\n /**\n * All values of this property must be higher than or equal this number\n */\n minInclusive?: number;\n /**\n * All values of this property must be lower than this number\n */\n maxExclusive?: number;\n /**\n * All values of this property must be lower than or equal this number\n */\n maxInclusive?: number;\n /**\n * All literal values of this property must at least be this long\n */\n minLength?: number;\n /**\n * All literal values of this property must at most be this long\n */\n maxLength?: number;\n /**\n * All literal values of this property must match this regular expression\n */\n pattern?: RegExp;\n /**\n * All literal values of this property must have one of these languages as their language tag\n */\n languageIn?: string[];\n /**\n * No pair of values may use the same language tag.\n */\n uniqueLang?: boolean;\n /**\n * Each literal value of this property must use this datatype\n */\n datatype?: NodeReferenceValue;\n /**\n * Each value of the property must occur in this set.\n * Use {id: '...'} for IRI nodes, or plain strings/numbers/booleans for literal values.\n */\n in?: (NodeReferenceValue | string | number | boolean)[];\n}\n\nexport interface ObjectPropertyShapeConfig extends PropertyShapeConfig {\n nodeKind?: NodeReferenceValue;\n /**\n * Each value of this property must have this class as its rdf:type\n */\n class?: NodeReferenceValue;\n /**\n * The shape that values of this property path need to confirm to.\n * You need to provide a class that extends Shape.\n */\n shape?: typeof Shape | [string, string];\n /**\n * Marks this property as *containment* (composition): the value(s) are owned by the subject\n * through this property. Ownership is per property: a plain property of another shape on the\n * same predicate is a reference and owns nothing. Requires `shape` (throws otherwise).\n *\n * - Replacing, unsetting or set-removing a value deletes the old node's own triples and blank\n * values, and its owned subtree; re-sent `{id}`s are kept.\n * - Deleting the subject (by id or in bulk) deletes its owned subtree (recursion other than a\n * shape owning its own kind stops after `MAX_OWNED_RECURSION` re-entries): the values\n * of its `contains` properties, the values their shapes own in turn, and the extra `contains`\n * values of registered sub-shapes (followed only from nodes of the sub-shape's class).\n * - Linking an existing node by `{id}` is class-checked: it is refused when the node is typed\n * and none of its types is the shape's class, a registered sub-shape's, or `sh:class`.\n *\n * Shape sync also persists a generated SHACL shape for this property (at its property shape's\n * IRI plus `.singleOwner`, written by the declaring class only) that limits each value of the\n * predicate to one owner of the declaring class or a registered sub-shape's class. It is not\n * enforced on write.\n */\n contains?: boolean;\n}\n\nexport interface PropertyShapeConfig {\n /**\n * The property path of this property shape.\n *\n * Four accepted forms, all equivalent where they overlap:\n *\n * - **An ontology term** — `documents.confidence`. The idiom for real shapes: it reuses the\n * ontology, so a namespace changes in one place. `createNameSpace` returns a `{id}` ref, so\n * the term IS the second form and is passed DIRECTLY — never `documents.confidence.id`,\n * which unwraps it back to a bare string.\n * - **A node reference** — `{id: 'https://example.org/vocab#startsAt'}`. What the first form\n * produces. Convenient in tests, or wherever an ontology module would be overkill.\n * - **A bare IRI or prefixed name** — `'https://example.org/vocab#startsAt'`, `'ex:startsAt'`.\n * - **A path expression** — `'ex:a/ex:b'`, `{seq: [...]}`, `{inv: ...}`, and the other\n * operators. An array is read as a sequence.\n *\n * A string is parsed as an expression only when it is not a bare absolute IRI: `ex:a/ex:b` is\n * a sequence, while the `/` inside `https://example.org/vocab#x` belongs to the IRI.\n */\n path: PropertyPathInputList;\n /**\n * Indicates that this property must exist.\n * Shorthand for minCount=1\n */\n required?: boolean;\n /**\n * Each value must be of this node type.\n */\n nodeKind?: NodeKindConfig;\n /**\n * Minimum number of values required\n */\n minCount?: number;\n /**\n * Maximum number of values allowed\n */\n maxCount?: number;\n /**\n * Values of the configured property must equal the values of this 'equals' property.\n * Value is always a property IRI (pair constraint).\n */\n equals?: NodeReferenceValue;\n /**\n * Values of the configured property must differ from the values of this 'disjoint' property.\n * Value is always a property IRI (pair constraint).\n */\n disjoint?: NodeReferenceValue;\n /**\n * At least one value of this property must equal the given value.\n * Use {id: '...'} for IRI nodes, or a plain string for literal values.\n */\n hasValue?: NodeReferenceValue | string | number | boolean;\n name?: string;\n description?: string;\n order?: number;\n group?: string;\n /**\n * Display importance, lower = more important (`core:displayRank`).\n * A renderer that can show only N properties shows the N lowest ranks.\n */\n displayRank?: number;\n /** Omit this property from generic rendering (`core:displayHidden`). */\n displayHidden?: boolean;\n /**\n * should correlate to the given datatype or class\n */\n defaultValue?: unknown;\n /**\n * Each value of the property must occur in this set.\n * Use {id: '...'} for IRI nodes, or plain strings for literal values.\n *\n * @example\n * in: ['ACTIVE', 'PENDING', 'CLOSED']\n * in: [{id: 'http://example.org/StatusA'}, {id: 'http://example.org/StatusB'}]\n */\n in?: (NodeReferenceValue | string | number | boolean)[];\n /**\n * Values of the configured property path are sorted by the values of this property path.\n */\n sortBy?: PropertyPathInputList;\n}\n\nconst EXPLICIT_NODE_KIND_SYMBOL = Symbol('explicitNodeKind');\nconst EXPLICIT_MIN_COUNT_SYMBOL = Symbol('explicitMinCount');\nconst EXPLICIT_MAX_COUNT_SYMBOL = Symbol('explicitMaxCount');\n\n/** Internal symbol-keyed flags on a PropertyShapeData object to track which fields were explicitly configured. */\ninterface ExplicitFlags {\n [EXPLICIT_NODE_KIND_SYMBOL]?: boolean;\n [EXPLICIT_MIN_COUNT_SYMBOL]?: boolean;\n [EXPLICIT_MAX_COUNT_SYMBOL]?: boolean;\n}\n\nexport interface ParameterConfig {\n optional?: number;\n}\n\n/**\n * Static-only DSL handle for the SHACL `sh:NodeShape` meta-shape.\n *\n * Never instantiated — a shape's metadata is a plain {@link NodeShapeData} object\n * (see nodeShapeData.js), and the instance methods that used to live here are now\n * free functions in that module. This class exists only to carry the meta-shape's\n * static `.shape` self-description and to serve as the DSL entry point for reading\n * and writing node-shape SHACL data (`NodeShape.create/select/delete`).\n */\nexport class NodeShape extends Shape {\n static targetClass = shacl.NodeShape;\n}\n\n/**\n * Static-only DSL handle for the SHACL `sh:PropertyShape` meta-shape.\n *\n * Never instantiated — property-shape metadata is a plain {@link PropertyShapeData}\n * object (see nodeShapeData.js). Exists only for its static `.shape` self-description\n * and as a DSL entry point (`PropertyShape.create/select`).\n */\nexport class PropertyShape extends Shape {\n static targetClass = shacl.PropertyShape;\n}\n\nconst connectValueShape = <\n Config extends LiteralPropertyShapeConfig | ObjectPropertyShapeConfig,\n>(\n config: Config,\n propertyKey: string,\n property: PropertyShapeData,\n) => {\n if ((config as ObjectPropertyShapeConfig).shape) {\n const shapeConfig = (config as ObjectPropertyShapeConfig).shape;\n\n if (Array.isArray(shapeConfig)) {\n const [packageName, shapeName] = shapeConfig;\n const nodeShapeUri = getNodeShapeUri(packageName, shapeName);\n property.valueShape = {id: nodeShapeUri};\n } else {\n const shapeClass = shapeConfig as typeof Shape;\n if (shapeClass.shape) {\n property.valueShape = {id: shapeClass.shape.id};\n } else {\n onShapeSetup(\n shapeConfig,\n (nodeShape: NodeShapeData) => {\n property.valueShape = {id: nodeShape.id};\n },\n propertyKey,\n );\n }\n }\n }\n};\n\n/**\n * The DSL-JSON where-clause combinators. A property may not be named after one,\n * because a condition key in those positions has no `{path}` escape (the key is a\n * bare string). See documentation/dsl-json.md (Reserved words).\n */\nconst RESERVED_PROPERTY_LABELS = new Set(['and', 'or', 'not']);\n\nexport function registerPropertyShape(\n shape: NodeShapeData,\n propertyShape: PropertyShapeData,\n) {\n if (RESERVED_PROPERTY_LABELS.has(propertyShape.label)) {\n throw new Error(\n `Property label '${propertyShape.label}' is reserved (a DSL-JSON boolean combinator) ` +\n `and cannot be used as a property name. See documentation/dsl-json.md (Reserved words).`,\n );\n }\n // Not fatal, but the author needs to hear it here rather than from the field tracer.\n warnOnReservedPropertyLabel(propertyShape.label, shape.label, shape.id);\n const inherited = getPropertyShapeData(shape, propertyShape.label, true);\n const existing = getPropertyShapeData(shape, propertyShape.label, false);\n if (!existing && inherited) {\n if (!(propertyShape as unknown as ExplicitFlags)[EXPLICIT_MIN_COUNT_SYMBOL]) {\n propertyShape.minCount = inherited.minCount;\n }\n if (!(propertyShape as unknown as ExplicitFlags)[EXPLICIT_MAX_COUNT_SYMBOL]) {\n propertyShape.maxCount = inherited.maxCount;\n }\n if (!(propertyShape as unknown as ExplicitFlags)[EXPLICIT_NODE_KIND_SYMBOL]) {\n propertyShape.nodeKind = inherited.nodeKind;\n }\n validateOverrideTightening(shape, inherited, propertyShape);\n }\n if (existing) {\n Object.assign(existing, propertyShape);\n return existing;\n }\n propertyShape.id = `${shape.id}/${propertyShape.label}`;\n addPropertyShapeData(shape, propertyShape);\n return propertyShape;\n}\n\nconst ATOMIC_NODE_KINDS = [\n shacl.BlankNode.id,\n shacl.IRI.id,\n shacl.Literal.id,\n];\n\nconst nodeKindToAtomics = (nodeKind?: NodeReferenceValue): Set<string> => {\n if (!nodeKind?.id) {\n return new Set();\n }\n switch (nodeKind.id) {\n case shacl.BlankNode.id:\n case shacl.IRI.id:\n case shacl.Literal.id:\n return new Set([nodeKind.id]);\n case shacl.BlankNodeOrIRI.id:\n return new Set([shacl.BlankNode.id, shacl.IRI.id]);\n case shacl.IRIOrLiteral.id:\n return new Set([shacl.IRI.id, shacl.Literal.id]);\n case shacl.BlankNodeOrLiteral.id:\n return new Set([shacl.BlankNode.id, shacl.Literal.id]);\n default:\n return new Set(ATOMIC_NODE_KINDS);\n }\n};\n\nconst throwOverrideError = (\n shape: NodeShapeData,\n propertyShape: PropertyShapeData,\n message: string,\n) => {\n throw new Error(\n `Invalid override for ${shape.label}.${propertyShape.label}: ${message}`,\n );\n};\n\nconst validateOverrideTightening = (\n shape: NodeShapeData,\n base: PropertyShapeData,\n override: PropertyShapeData,\n) => {\n if (\n typeof base.minCount === 'number' &&\n typeof override.minCount === 'number' &&\n override.minCount < base.minCount\n ) {\n throwOverrideError(\n shape,\n override,\n `minCount cannot be lowered (${base.minCount} -> ${override.minCount}).`,\n );\n }\n\n if (\n typeof base.maxCount === 'number' &&\n typeof override.maxCount === 'number' &&\n override.maxCount > base.maxCount\n ) {\n throwOverrideError(\n shape,\n override,\n `maxCount cannot be increased (${base.maxCount} -> ${override.maxCount}).`,\n );\n }\n\n if (base.nodeKind && override.nodeKind) {\n const baseKinds = nodeKindToAtomics(base.nodeKind);\n const overrideKinds = nodeKindToAtomics(override.nodeKind);\n const widensNodeKind = [...overrideKinds].some((kind) => !baseKinds.has(kind));\n if (widensNodeKind) {\n throwOverrideError(\n shape,\n override,\n `nodeKind cannot be widened (${base.nodeKind.id} -> ${override.nodeKind.id}).`,\n );\n }\n }\n};\n\nexport function createPropertyShape<\n Config extends LiteralPropertyShapeConfig | ObjectPropertyShapeConfig,\n>(\n config: Config,\n propertyKey: string,\n defaultNodeKind: NodeReferenceValue = null,\n shapeClass: typeof Shape | [string, string] = null,\n) {\n const propertyShape = createPropertyShapeData();\n propertyShape.path = normalizePropertyPath(config.path);\n propertyShape.label = propertyKey;\n\n if (config.name) {\n propertyShape.name = config.name;\n }\n if (config.description) {\n propertyShape.description = config.description;\n }\n\n if (config.required) {\n propertyShape.minCount = 1;\n } else if (config.minCount !== undefined) {\n propertyShape.minCount = config.minCount;\n }\n (propertyShape as unknown as ExplicitFlags)[EXPLICIT_MIN_COUNT_SYMBOL] =\n config.required === true || config.minCount !== undefined;\n\n if (config.maxCount !== undefined) {\n propertyShape.maxCount = config.maxCount;\n }\n (propertyShape as unknown as ExplicitFlags)[EXPLICIT_MAX_COUNT_SYMBOL] =\n config.maxCount !== undefined;\n if ((config as LiteralPropertyShapeConfig).datatype) {\n propertyShape.datatype = toNodeReference(\n (config as LiteralPropertyShapeConfig).datatype,\n );\n }\n\n if ((config as ObjectPropertyShapeConfig).class) {\n propertyShape.class = toNodeReference(\n (config as ObjectPropertyShapeConfig).class,\n );\n }\n\n if ((config as ObjectPropertyShapeConfig).contains) {\n // Ownership is walked shape by shape, so an owned value needs a shape to walk into. A\n // polymorphic slot holding blank structure needs no `contains`: blank values are deleted\n // through their blank-capable `nodeKind`.\n if (!(config as ObjectPropertyShapeConfig).shape) {\n throw new Error(\n `The contains property \"${propertyKey}\" needs a \\`shape\\`: ownership follows the value ` +\n `shape to what it owns in turn. Declare the value's shape, or drop \\`contains\\` (a blank ` +\n `value is deleted through a blank-capable \\`nodeKind\\` without it).`,\n );\n }\n propertyShape.contains = true;\n }\n\n if (config.equals) {\n propertyShape.equalsConstraint = toNodeReference(config.equals);\n }\n if (config.disjoint) {\n propertyShape.disjoint = toNodeReference(config.disjoint);\n }\n if ((config as LiteralPropertyShapeConfig).lessThan) {\n propertyShape.lessThan = toNodeReference((config as LiteralPropertyShapeConfig).lessThan);\n }\n if ((config as LiteralPropertyShapeConfig).lessThanOrEquals) {\n propertyShape.lessThanOrEquals = toNodeReference((config as LiteralPropertyShapeConfig).lessThanOrEquals);\n }\n // Value-range / string-length / pattern constraints (report 021 §3, G5). These are\n // recorded on the shape and serialized to SHACL; there is no DSL-side runtime\n // enforcement — they describe the shape for validators / introspection.\n {\n const lit = config as LiteralPropertyShapeConfig;\n if (lit.minInclusive !== undefined) propertyShape.minInclusive = lit.minInclusive;\n if (lit.maxInclusive !== undefined) propertyShape.maxInclusive = lit.maxInclusive;\n if (lit.minExclusive !== undefined) propertyShape.minExclusive = lit.minExclusive;\n if (lit.maxExclusive !== undefined) propertyShape.maxExclusive = lit.maxExclusive;\n if (lit.minLength !== undefined) propertyShape.minLength = lit.minLength;\n if (lit.maxLength !== undefined) propertyShape.maxLength = lit.maxLength;\n if (lit.pattern !== undefined) propertyShape.pattern = lit.pattern;\n }\n if (config.hasValue !== undefined) {\n const v = config.hasValue;\n propertyShape.hasValueConstraint = typeof v === 'object' && v !== null ? toNodeReference(v) : v;\n }\n if (config.defaultValue !== undefined) {\n propertyShape.defaultValue = config.defaultValue;\n }\n if (config.in) {\n propertyShape.in = config.in.map((entry) =>\n typeof entry === 'object' && entry !== null ? toNodeReference(entry) : entry,\n );\n }\n if (config.sortBy) {\n propertyShape.sortBy = normalizePropertyPath(config.sortBy);\n }\n // Arrangement + display metadata. `order` and `group` were declared on the config\n // but never copied onto the property shape, so a declared `sh:order` was silently\n // dropped and every renderer fell back to array position. Carried now, alongside\n // the two display terms.\n if (config.order !== undefined) propertyShape.order = config.order;\n if (config.group !== undefined) propertyShape.group = config.group;\n if (config.displayRank !== undefined) propertyShape.displayRank = config.displayRank;\n if (config.displayHidden !== undefined)\n propertyShape.displayHidden = config.displayHidden;\n\n propertyShape.nodeKind = normalizeNodeKind(config.nodeKind, defaultNodeKind);\n (propertyShape as unknown as ExplicitFlags)[EXPLICIT_NODE_KIND_SYMBOL] =\n config.nodeKind !== undefined;\n\n if (shapeClass) {\n onShapeSetup(shapeClass, (shape: NodeShapeData) => {\n connectValueShape(config, propertyKey, propertyShape);\n registerPropertyShape(shape, propertyShape);\n });\n }\n\n return propertyShape;\n}\n\nexport function onShapeSetup(\n shapeClass: typeof Shape | [string, string],\n callback: (shape: NodeShapeData) => void,\n propertyName?: string,\n waitForSuperShapes?: boolean,\n) {\n const cb = waitForSuperShapes\n ? (shape: NodeShapeData) => {\n const superClass = Object.getPrototypeOf(shapeClass) as typeof Shape;\n if (superClass.name === 'Shape') {\n callback(shape);\n return;\n }\n if (superClass.name === '') {\n console.error(\n `Shape ${shape.label} does not extend base class lincd/shapes/Shape. Make sure it extends Shape.`,\n );\n return;\n }\n onShapeSetup(\n superClass,\n () => {\n callback(shape);\n },\n propertyName,\n waitForSuperShapes,\n );\n }\n : callback;\n\n const safeCallback = (\n targetShapeClass: typeof Shape,\n innerCallback: (shape: NodeShapeData) => void,\n ) => {\n if (targetShapeClass.hasOwnProperty('shape')) {\n innerCallback((targetShapeClass as typeof Shape).shape);\n } else {\n if (!targetShapeClass['shapeCallbacks']) {\n targetShapeClass['shapeCallbacks'] = [];\n }\n targetShapeClass['shapeCallbacks'].push(innerCallback);\n }\n };\n\n if (Array.isArray(shapeClass)) {\n const [packageName, shapeName] = shapeClass;\n const nodeShapeId = getNodeShapeUri(packageName, shapeName);\n if (typeof document !== 'undefined') {\n window.addEventListener('load', () => {\n const resolved = getShapeClass(nodeShapeId);\n if (!resolved) {\n console.warn(\n `Could not find value shape (${packageName}/${shapeName}) for accessor get ${propertyName}(). Likely because it is not bundled.`,\n );\n return;\n }\n safeCallback(resolved as unknown as typeof Shape, cb);\n });\n } else {\n addNodeShapeCallback(nodeShapeId, cb);\n }\n } else {\n safeCallback(shapeClass, cb);\n }\n}\n\nconst _linkedProperty = <\n Config extends ObjectPropertyShapeConfig | LiteralPropertyShapeConfig,\n>(\n config: Config,\n defaultNodeKind: NodeReferenceValue = null,\n) => {\n return function (\n target: any,\n propertyKey: string,\n _descriptor: PropertyDescriptor,\n ) {\n createPropertyShape(config, propertyKey, defaultNodeKind, target.constructor);\n };\n};\n\nexport const literalProperty = (config: LiteralPropertyShapeConfig) => {\n return _linkedProperty<LiteralPropertyShapeConfig>(config, shacl.Literal);\n};\n\nexport const objectProperty = (config: ObjectPropertyShapeConfig) => {\n return _linkedProperty<ObjectPropertyShapeConfig>(config, shacl.IRI);\n};\n\nexport const linkedProperty = (\n config: ObjectPropertyShapeConfig | LiteralPropertyShapeConfig,\n) => {\n return _linkedProperty(config);\n};\n\nexport function disallowProperty(\n target: any,\n propertyKey: string,\n _descriptor: PropertyDescriptor,\n) {\n onShapeSetup(\n target.constructor,\n (shape: NodeShapeData) => {\n const superClass = Object.getPrototypeOf(target.constructor) as typeof Shape;\n const superNodeShape = superClass.shape;\n const superPropertyShape = getPropertyShapeData(\n superNodeShape,\n propertyKey,\n true,\n );\n if (!superPropertyShape) {\n console.warn(\n `Property ${propertyKey} not found in super class ${superClass.name} or any of its super classes. Does it have a property decorator? Cannot disallow property ${target.constructor.name}.${propertyKey}`,\n );\n return;\n }\n const clonedPropertyShape = clonePropertyShape(superPropertyShape);\n clonedPropertyShape.maxCount = 0;\n registerPropertyShape(shape, clonedPropertyShape);\n },\n '',\n true,\n );\n}\n\nexport function getNodeShapeUri(packageName: string, shapeName: string): string {\n // arch-02: `{baseUri}shape/{packageSlug}/{ShapeName}` — ShapeName kept PascalCase\n // (it is a class name, already URI-safe), packageSlug derived from the name.\n return `${resolveBaseUri(packageName)}shape/${packageNameToSlug(packageName)}/${shapeName}`;\n}\n\nconst nodeShapeCallbacks = new Map<string, ((shape: NodeShapeData) => void)[]>();\nexport function getAndClearCallbacks(\n nodeShapeId: string,\n): ((shape: NodeShapeData) => void)[] {\n const callbacks = nodeShapeCallbacks.get(nodeShapeId);\n nodeShapeCallbacks.delete(nodeShapeId);\n return callbacks;\n}\nexport const addNodeShapeCallback = (\n nodeShapeId: string,\n callback: (shape: NodeShapeData) => void,\n) => {\n if (!nodeShapeCallbacks.has(nodeShapeId)) {\n nodeShapeCallbacks.set(nodeShapeId, []);\n }\n nodeShapeCallbacks.get(nodeShapeId).push(callback);\n};\n"]}
1
+ {"version":3,"file":"SHACL.js","sourceRoot":"","sources":["../../../src/shapes/SHACL.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAA0B,eAAe,EAAC,MAAM,2BAA2B,CAAC;AACnF,OAAO,EAAC,KAAK,EAAwB,MAAM,YAAY,CAAC;AACxD,OAAO,EAAC,KAAK,EAAC,MAAM,wBAAwB,CAAC;AAC7C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B,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IACvC,OAAO,SAAS,CAAC;AACnB,CAAC;AACD,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAClC,WAAmB,EACnB,QAAwC,EACxC,EAAE;IACF,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;QACzC,kBAAkB,CAAC,GAAG,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;IAC1C,CAAC;IACD,kBAAkB,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AACrD,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 {type NodeReferenceValue, toNodeReference} from '../utils/NodeReference.js';\nimport {Shape, type ShapeConstructor} from './Shape.js';\nimport {shacl} from '../ontologies/shacl.js';\nimport {warnOnReservedPropertyLabel} from '../queries/reservedQueryNames.js';\nimport {getShapeClass} from '../utils/ShapeClass.js';\nimport {sharedState} from '../utils/sharedState.js';\nimport type {PathExpr} from '../paths/PropertyPathExpr.js';\nimport {normalizePropertyPath, type PropertyPathDecoratorInput} from '../paths/normalizePropertyPath.js';\nimport {\n createPropertyShapeData,\n getPropertyShape as getPropertyShapeData,\n addPropertyShape as addPropertyShapeData,\n clonePropertyShape,\n type NodeShapeData,\n type PropertyShapeData,\n} from './nodeShapeData.js';\n\n// Metadata types now live in nodeShapeData.js (plain objects); re-exported here for\n// existing importers of `NodeShape`/`PropertyShape`-adjacent types.\nexport type {NodeShapeData, PropertyShapeData, PropertyShapeResult} from './nodeShapeData.js';\n// Metadata operations (formerly NodeShape/PropertyShape instance methods).\nexport {\n getPropertyShapes,\n getUniquePropertyShapes,\n getPropertyShape,\n addPropertyShape,\n clonePropertyShape,\n propertyShapeToResult,\n nodeShapeEquals,\n createNodeShapeData,\n createPropertyShapeData,\n} from './nodeShapeData.js';\n\n/**\n * Default identity root for shape & package IRIs. Public/first-party packages\n * publish under `linked.cm` (arch-02 §Domains). Packages may override per-package\n * via `linkedPackage(name, { baseUri })` — CN injects a workspace-scoped root\n * (`{workspaceSlug}.id.create.now`) for private packages; first-party packages\n * keep this default.\n */\nexport const LINKED_DATA_ROOT: string = 'https://linked.cm/';\n\n/**\n * Derive the public package slug — the npm package **basename** with the\n * `@scope/` dropped, kebab-cased (arch-02 §Slug rules: `^[a-z0-9]+(?:-[a-z0-9]+)*$`).\n * The package name is the single source of truth; there is no separate slug.\n * `@_linked/core` → `core`, `@linked.cm/blog` → `blog`, `mypkg` → `mypkg`.\n *\n * Both first-party (`@_linked`) and community (`@linked.cm`) packages publish into\n * the one `linked.cm/{shape,pkg}` space, so the basename must be globally unique —\n * enforced by the registry, which reserves the (handful of) first-party names.\n */\nexport function packageNameToSlug(packageName: string): string {\n return packageName\n .replace(/^@[^/]+\\//, '') // drop the npm scope (@scope/), keep the basename\n .replace(/[^a-zA-Z0-9]+/g, '-') // any run of non-alphanumerics → single hyphen\n .replace(/^-+|-+$/g, '') // trim stray hyphens\n .toLowerCase();\n}\n\n/**\n * Where each package publishes its IRIs (the identity root). The slug is always\n * derived from the package name; only the root is configurable — `linkedPackage`\n * defaults it to `LINKED_DATA_ROOT` (linked.cm), and CN injects a workspace-scoped\n * root (`{workspaceSlug}.id.create.now`) for private packages. Shared by every copy of core,\n * so a private package's root holds whichever copy derives its IRIs.\n */\nconst packageBaseUri = sharedState('@_linked/core', 'SHACL.packageBaseUri', () => new Map<string, string>());\n\n/** Record a package's publish root. Called by `linkedPackage()`. */\nexport function setPackagePublishConfig(\n packageName: string,\n config?: {baseUri?: string},\n): void {\n packageBaseUri.set(packageName, config?.baseUri ?? LINKED_DATA_ROOT);\n}\n\n/** Resolve a package's publish root, defaulting to linked.cm if undeclared. */\nfunction resolveBaseUri(packageName: string): string {\n return packageBaseUri.get(packageName) ?? LINKED_DATA_ROOT;\n}\n\n/** Public/first-party package IRI — arch-02: `{baseUri}pkg/{slug}`. */\nexport function getPackageUri(packageName: string): string {\n return `${resolveBaseUri(packageName)}pkg/${packageNameToSlug(packageName)}`;\n}\n\ntype NodeKindConfig = NodeReferenceValue | NodeReferenceValue[];\n\nexport type PropertyPathInput = PropertyPathDecoratorInput;\nexport type PropertyPathInputList = PropertyPathDecoratorInput;\n\nconst normalizeNodeKind = (\n nodeKind?: NodeKindConfig,\n defaultNodeKind?: NodeReferenceValue,\n): NodeReferenceValue | undefined => {\n if (!nodeKind) {\n return defaultNodeKind;\n }\n if (Array.isArray(nodeKind)) {\n const ids = nodeKind.map((entry) => entry?.id);\n const includesBlank = ids.includes(shacl.BlankNode.id);\n const includesNamed = ids.includes(shacl.IRI.id);\n const includesLiteral = ids.includes(shacl.Literal.id);\n if (includesBlank && includesNamed) {\n return shacl.BlankNodeOrIRI;\n }\n if (includesLiteral && includesNamed) {\n return shacl.IRIOrLiteral;\n }\n if (includesLiteral && includesBlank) {\n return shacl.BlankNodeOrLiteral;\n }\n return nodeKind[0];\n }\n return nodeKind;\n};\n\nexport interface NodeShapeConfig {\n /**\n * Set to true to close the shape. This means any target node of this shape\n * that has properties outside the defined properties of this shape is invalid.\n */\n closed?: boolean;\n /**\n * Optional list of properties that are also permitted in addition to those explicitly listed by this shape.\n */\n ignoredProperties?: NodeReferenceValue[];\n}\n\nexport interface LiteralPropertyShapeConfig extends PropertyShapeConfig {\n nodeKind?: NodeReferenceValue;\n /**\n * Values of the configured property must be less than the values of this 'lessThan' property.\n * Value is always a property IRI (pair constraint).\n */\n lessThan?: NodeReferenceValue;\n /**\n * Values of the configured property must be less than or equal the values of this 'lessThanOrEquals' property.\n * Value is always a property IRI (pair constraint).\n */\n lessThanOrEquals?: NodeReferenceValue;\n /**\n * All values of this property must be higher than this number\n */\n minExclusive?: number | string;\n /**\n * All values of this property must be higher than or equal this number\n */\n minInclusive?: number;\n /**\n * All values of this property must be lower than this number\n */\n maxExclusive?: number;\n /**\n * All values of this property must be lower than or equal this number\n */\n maxInclusive?: number;\n /**\n * All literal values of this property must at least be this long\n */\n minLength?: number;\n /**\n * All literal values of this property must at most be this long\n */\n maxLength?: number;\n /**\n * All literal values of this property must match this regular expression\n */\n pattern?: RegExp;\n /**\n * All literal values of this property must have one of these languages as their language tag\n */\n languageIn?: string[];\n /**\n * No pair of values may use the same language tag.\n */\n uniqueLang?: boolean;\n /**\n * Each literal value of this property must use this datatype\n */\n datatype?: NodeReferenceValue;\n /**\n * Each value of the property must occur in this set.\n * Use {id: '...'} for IRI nodes, or plain strings/numbers/booleans for literal values.\n */\n in?: (NodeReferenceValue | string | number | boolean)[];\n}\n\nexport interface ObjectPropertyShapeConfig extends PropertyShapeConfig {\n nodeKind?: NodeReferenceValue;\n /**\n * Each value of this property must have this class as its rdf:type\n */\n class?: NodeReferenceValue;\n /**\n * The shape that values of this property path need to confirm to.\n * You need to provide a class that extends Shape.\n */\n shape?: typeof Shape | [string, string];\n /**\n * Marks this property as *containment* (composition): the value(s) are owned by the subject\n * through this property. Ownership is per property: a plain property of another shape on the\n * same predicate is a reference and owns nothing. Requires `shape` (throws otherwise).\n *\n * - Replacing, unsetting or set-removing a value deletes the old node's own triples and blank\n * values, and its owned subtree; re-sent `{id}`s are kept.\n * - Deleting the subject (by id or in bulk) deletes its owned subtree (recursion other than a\n * shape owning its own kind stops after `MAX_OWNED_RECURSION` re-entries): the values\n * of its `contains` properties, the values their shapes own in turn, and the extra `contains`\n * values of registered sub-shapes (followed only from nodes of the sub-shape's class).\n * - Linking an existing node by `{id}` is class-checked: it is refused when the node is typed\n * and none of its types is the shape's class, a registered sub-shape's, or `sh:class`.\n *\n * Shape sync also persists a generated SHACL shape for this property (at its property shape's\n * IRI plus `.singleOwner`, written by the declaring class only) that limits each value of the\n * predicate to one owner of the declaring class or a registered sub-shape's class. It is not\n * enforced on write.\n */\n contains?: boolean;\n}\n\nexport interface PropertyShapeConfig {\n /**\n * The property path of this property shape.\n *\n * Four accepted forms, all equivalent where they overlap:\n *\n * - **An ontology term** — `documents.confidence`. The idiom for real shapes: it reuses the\n * ontology, so a namespace changes in one place. `createNameSpace` returns a `{id}` ref, so\n * the term IS the second form and is passed DIRECTLY — never `documents.confidence.id`,\n * which unwraps it back to a bare string.\n * - **A node reference** — `{id: 'https://example.org/vocab#startsAt'}`. What the first form\n * produces. Convenient in tests, or wherever an ontology module would be overkill.\n * - **A bare IRI or prefixed name** — `'https://example.org/vocab#startsAt'`, `'ex:startsAt'`.\n * - **A path expression** — `'ex:a/ex:b'`, `{seq: [...]}`, `{inv: ...}`, and the other\n * operators. An array is read as a sequence.\n *\n * A string is parsed as an expression only when it is not a bare absolute IRI: `ex:a/ex:b` is\n * a sequence, while the `/` inside `https://example.org/vocab#x` belongs to the IRI.\n */\n path: PropertyPathInputList;\n /**\n * Indicates that this property must exist.\n * Shorthand for minCount=1\n */\n required?: boolean;\n /**\n * Each value must be of this node type.\n */\n nodeKind?: NodeKindConfig;\n /**\n * Minimum number of values required\n */\n minCount?: number;\n /**\n * Maximum number of values allowed\n */\n maxCount?: number;\n /**\n * Values of the configured property must equal the values of this 'equals' property.\n * Value is always a property IRI (pair constraint).\n */\n equals?: NodeReferenceValue;\n /**\n * Values of the configured property must differ from the values of this 'disjoint' property.\n * Value is always a property IRI (pair constraint).\n */\n disjoint?: NodeReferenceValue;\n /**\n * At least one value of this property must equal the given value.\n * Use {id: '...'} for IRI nodes, or a plain string for literal values.\n */\n hasValue?: NodeReferenceValue | string | number | boolean;\n name?: string;\n description?: string;\n order?: number;\n group?: string;\n /**\n * Display importance, lower = more important (`core:displayRank`).\n * A renderer that can show only N properties shows the N lowest ranks.\n */\n displayRank?: number;\n /** Omit this property from generic rendering (`core:displayHidden`). */\n displayHidden?: boolean;\n /**\n * should correlate to the given datatype or class\n */\n defaultValue?: unknown;\n /**\n * Each value of the property must occur in this set.\n * Use {id: '...'} for IRI nodes, or plain strings for literal values.\n *\n * @example\n * in: ['ACTIVE', 'PENDING', 'CLOSED']\n * in: [{id: 'http://example.org/StatusA'}, {id: 'http://example.org/StatusB'}]\n */\n in?: (NodeReferenceValue | string | number | boolean)[];\n /**\n * Values of the configured property path are sorted by the values of this property path.\n */\n sortBy?: PropertyPathInputList;\n}\n\nconst EXPLICIT_NODE_KIND_SYMBOL = Symbol('explicitNodeKind');\nconst EXPLICIT_MIN_COUNT_SYMBOL = Symbol('explicitMinCount');\nconst EXPLICIT_MAX_COUNT_SYMBOL = Symbol('explicitMaxCount');\n\n/** Internal symbol-keyed flags on a PropertyShapeData object to track which fields were explicitly configured. */\ninterface ExplicitFlags {\n [EXPLICIT_NODE_KIND_SYMBOL]?: boolean;\n [EXPLICIT_MIN_COUNT_SYMBOL]?: boolean;\n [EXPLICIT_MAX_COUNT_SYMBOL]?: boolean;\n}\n\nexport interface ParameterConfig {\n optional?: number;\n}\n\n/**\n * Static-only DSL handle for the SHACL `sh:NodeShape` meta-shape.\n *\n * Never instantiated — a shape's metadata is a plain {@link NodeShapeData} object\n * (see nodeShapeData.js), and the instance methods that used to live here are now\n * free functions in that module. This class exists only to carry the meta-shape's\n * static `.shape` self-description and to serve as the DSL entry point for reading\n * and writing node-shape SHACL data (`NodeShape.create/select/delete`).\n */\nexport class NodeShape extends Shape {\n static targetClass = shacl.NodeShape;\n}\n\n/**\n * Static-only DSL handle for the SHACL `sh:PropertyShape` meta-shape.\n *\n * Never instantiated — property-shape metadata is a plain {@link PropertyShapeData}\n * object (see nodeShapeData.js). Exists only for its static `.shape` self-description\n * and as a DSL entry point (`PropertyShape.create/select`).\n */\nexport class PropertyShape extends Shape {\n static targetClass = shacl.PropertyShape;\n}\n\nconst connectValueShape = <\n Config extends LiteralPropertyShapeConfig | ObjectPropertyShapeConfig,\n>(\n config: Config,\n propertyKey: string,\n property: PropertyShapeData,\n) => {\n if ((config as ObjectPropertyShapeConfig).shape) {\n const shapeConfig = (config as ObjectPropertyShapeConfig).shape;\n\n if (Array.isArray(shapeConfig)) {\n const [packageName, shapeName] = shapeConfig;\n const nodeShapeUri = getNodeShapeUri(packageName, shapeName);\n property.valueShape = {id: nodeShapeUri};\n } else {\n const shapeClass = shapeConfig as typeof Shape;\n if (shapeClass.shape) {\n property.valueShape = {id: shapeClass.shape.id};\n } else {\n onShapeSetup(\n shapeConfig,\n (nodeShape: NodeShapeData) => {\n property.valueShape = {id: nodeShape.id};\n },\n propertyKey,\n );\n }\n }\n }\n};\n\n/**\n * The DSL-JSON where-clause combinators. A property may not be named after one,\n * because a condition key in those positions has no `{path}` escape (the key is a\n * bare string). See documentation/dsl-json.md (Reserved words).\n */\nconst RESERVED_PROPERTY_LABELS = new Set(['and', 'or', 'not']);\n\nexport function registerPropertyShape(\n shape: NodeShapeData,\n propertyShape: PropertyShapeData,\n) {\n if (RESERVED_PROPERTY_LABELS.has(propertyShape.label)) {\n throw new Error(\n `Property label '${propertyShape.label}' is reserved (a DSL-JSON boolean combinator) ` +\n `and cannot be used as a property name. See documentation/dsl-json.md (Reserved words).`,\n );\n }\n // Not fatal, but the author needs to hear it here rather than from the field tracer.\n warnOnReservedPropertyLabel(propertyShape.label, shape.label, shape.id);\n const inherited = getPropertyShapeData(shape, propertyShape.label, true);\n const existing = getPropertyShapeData(shape, propertyShape.label, false);\n if (!existing && inherited) {\n if (!(propertyShape as unknown as ExplicitFlags)[EXPLICIT_MIN_COUNT_SYMBOL]) {\n propertyShape.minCount = inherited.minCount;\n }\n if (!(propertyShape as unknown as ExplicitFlags)[EXPLICIT_MAX_COUNT_SYMBOL]) {\n propertyShape.maxCount = inherited.maxCount;\n }\n if (!(propertyShape as unknown as ExplicitFlags)[EXPLICIT_NODE_KIND_SYMBOL]) {\n propertyShape.nodeKind = inherited.nodeKind;\n }\n validateOverrideTightening(shape, inherited, propertyShape);\n }\n if (existing) {\n Object.assign(existing, propertyShape);\n return existing;\n }\n propertyShape.id = `${shape.id}/${propertyShape.label}`;\n addPropertyShapeData(shape, propertyShape);\n return propertyShape;\n}\n\nconst ATOMIC_NODE_KINDS = [\n shacl.BlankNode.id,\n shacl.IRI.id,\n shacl.Literal.id,\n];\n\nconst nodeKindToAtomics = (nodeKind?: NodeReferenceValue): Set<string> => {\n if (!nodeKind?.id) {\n return new Set();\n }\n switch (nodeKind.id) {\n case shacl.BlankNode.id:\n case shacl.IRI.id:\n case shacl.Literal.id:\n return new Set([nodeKind.id]);\n case shacl.BlankNodeOrIRI.id:\n return new Set([shacl.BlankNode.id, shacl.IRI.id]);\n case shacl.IRIOrLiteral.id:\n return new Set([shacl.IRI.id, shacl.Literal.id]);\n case shacl.BlankNodeOrLiteral.id:\n return new Set([shacl.BlankNode.id, shacl.Literal.id]);\n default:\n return new Set(ATOMIC_NODE_KINDS);\n }\n};\n\nconst throwOverrideError = (\n shape: NodeShapeData,\n propertyShape: PropertyShapeData,\n message: string,\n) => {\n throw new Error(\n `Invalid override for ${shape.label}.${propertyShape.label}: ${message}`,\n );\n};\n\nconst validateOverrideTightening = (\n shape: NodeShapeData,\n base: PropertyShapeData,\n override: PropertyShapeData,\n) => {\n if (\n typeof base.minCount === 'number' &&\n typeof override.minCount === 'number' &&\n override.minCount < base.minCount\n ) {\n throwOverrideError(\n shape,\n override,\n `minCount cannot be lowered (${base.minCount} -> ${override.minCount}).`,\n );\n }\n\n if (\n typeof base.maxCount === 'number' &&\n typeof override.maxCount === 'number' &&\n override.maxCount > base.maxCount\n ) {\n throwOverrideError(\n shape,\n override,\n `maxCount cannot be increased (${base.maxCount} -> ${override.maxCount}).`,\n );\n }\n\n if (base.nodeKind && override.nodeKind) {\n const baseKinds = nodeKindToAtomics(base.nodeKind);\n const overrideKinds = nodeKindToAtomics(override.nodeKind);\n const widensNodeKind = [...overrideKinds].some((kind) => !baseKinds.has(kind));\n if (widensNodeKind) {\n throwOverrideError(\n shape,\n override,\n `nodeKind cannot be widened (${base.nodeKind.id} -> ${override.nodeKind.id}).`,\n );\n }\n }\n};\n\nexport function createPropertyShape<\n Config extends LiteralPropertyShapeConfig | ObjectPropertyShapeConfig,\n>(\n config: Config,\n propertyKey: string,\n defaultNodeKind: NodeReferenceValue = null,\n shapeClass: typeof Shape | [string, string] = null,\n) {\n const propertyShape = createPropertyShapeData();\n propertyShape.path = normalizePropertyPath(config.path);\n propertyShape.label = propertyKey;\n\n if (config.name) {\n propertyShape.name = config.name;\n }\n if (config.description) {\n propertyShape.description = config.description;\n }\n\n if (config.required) {\n propertyShape.minCount = 1;\n } else if (config.minCount !== undefined) {\n propertyShape.minCount = config.minCount;\n }\n (propertyShape as unknown as ExplicitFlags)[EXPLICIT_MIN_COUNT_SYMBOL] =\n config.required === true || config.minCount !== undefined;\n\n if (config.maxCount !== undefined) {\n propertyShape.maxCount = config.maxCount;\n }\n (propertyShape as unknown as ExplicitFlags)[EXPLICIT_MAX_COUNT_SYMBOL] =\n config.maxCount !== undefined;\n if ((config as LiteralPropertyShapeConfig).datatype) {\n propertyShape.datatype = toNodeReference(\n (config as LiteralPropertyShapeConfig).datatype,\n );\n }\n\n if ((config as ObjectPropertyShapeConfig).class) {\n propertyShape.class = toNodeReference(\n (config as ObjectPropertyShapeConfig).class,\n );\n }\n\n if ((config as ObjectPropertyShapeConfig).contains) {\n // Ownership is walked shape by shape, so an owned value needs a shape to walk into. A\n // polymorphic slot holding blank structure needs no `contains`: blank values are deleted\n // through their blank-capable `nodeKind`.\n if (!(config as ObjectPropertyShapeConfig).shape) {\n throw new Error(\n `The contains property \"${propertyKey}\" needs a \\`shape\\`: ownership follows the value ` +\n `shape to what it owns in turn. Declare the value's shape, or drop \\`contains\\` (a blank ` +\n `value is deleted through a blank-capable \\`nodeKind\\` without it).`,\n );\n }\n propertyShape.contains = true;\n }\n\n if (config.equals) {\n propertyShape.equalsConstraint = toNodeReference(config.equals);\n }\n if (config.disjoint) {\n propertyShape.disjoint = toNodeReference(config.disjoint);\n }\n if ((config as LiteralPropertyShapeConfig).lessThan) {\n propertyShape.lessThan = toNodeReference((config as LiteralPropertyShapeConfig).lessThan);\n }\n if ((config as LiteralPropertyShapeConfig).lessThanOrEquals) {\n propertyShape.lessThanOrEquals = toNodeReference((config as LiteralPropertyShapeConfig).lessThanOrEquals);\n }\n // Value-range / string-length / pattern constraints (report 021 §3, G5). These are\n // recorded on the shape and serialized to SHACL; there is no DSL-side runtime\n // enforcement — they describe the shape for validators / introspection.\n {\n const lit = config as LiteralPropertyShapeConfig;\n if (lit.minInclusive !== undefined) propertyShape.minInclusive = lit.minInclusive;\n if (lit.maxInclusive !== undefined) propertyShape.maxInclusive = lit.maxInclusive;\n if (lit.minExclusive !== undefined) propertyShape.minExclusive = lit.minExclusive;\n if (lit.maxExclusive !== undefined) propertyShape.maxExclusive = lit.maxExclusive;\n if (lit.minLength !== undefined) propertyShape.minLength = lit.minLength;\n if (lit.maxLength !== undefined) propertyShape.maxLength = lit.maxLength;\n if (lit.pattern !== undefined) propertyShape.pattern = lit.pattern;\n }\n if (config.hasValue !== undefined) {\n const v = config.hasValue;\n propertyShape.hasValueConstraint = typeof v === 'object' && v !== null ? toNodeReference(v) : v;\n }\n if (config.defaultValue !== undefined) {\n propertyShape.defaultValue = config.defaultValue;\n }\n if (config.in) {\n propertyShape.in = config.in.map((entry) =>\n typeof entry === 'object' && entry !== null ? toNodeReference(entry) : entry,\n );\n }\n if (config.sortBy) {\n propertyShape.sortBy = normalizePropertyPath(config.sortBy);\n }\n // Arrangement + display metadata. `order` and `group` were declared on the config\n // but never copied onto the property shape, so a declared `sh:order` was silently\n // dropped and every renderer fell back to array position. Carried now, alongside\n // the two display terms.\n if (config.order !== undefined) propertyShape.order = config.order;\n if (config.group !== undefined) propertyShape.group = config.group;\n if (config.displayRank !== undefined) propertyShape.displayRank = config.displayRank;\n if (config.displayHidden !== undefined)\n propertyShape.displayHidden = config.displayHidden;\n\n propertyShape.nodeKind = normalizeNodeKind(config.nodeKind, defaultNodeKind);\n (propertyShape as unknown as ExplicitFlags)[EXPLICIT_NODE_KIND_SYMBOL] =\n config.nodeKind !== undefined;\n\n if (shapeClass) {\n onShapeSetup(shapeClass, (shape: NodeShapeData) => {\n connectValueShape(config, propertyKey, propertyShape);\n registerPropertyShape(shape, propertyShape);\n });\n }\n\n return propertyShape;\n}\n\nexport function onShapeSetup(\n shapeClass: typeof Shape | [string, string],\n callback: (shape: NodeShapeData) => void,\n propertyName?: string,\n waitForSuperShapes?: boolean,\n) {\n const cb = waitForSuperShapes\n ? (shape: NodeShapeData) => {\n const superClass = Object.getPrototypeOf(shapeClass) as typeof Shape;\n if (superClass.name === 'Shape') {\n callback(shape);\n return;\n }\n if (superClass.name === '') {\n console.error(\n `Shape ${shape.label} does not extend base class lincd/shapes/Shape. Make sure it extends Shape.`,\n );\n return;\n }\n onShapeSetup(\n superClass,\n () => {\n callback(shape);\n },\n propertyName,\n waitForSuperShapes,\n );\n }\n : callback;\n\n const safeCallback = (\n targetShapeClass: typeof Shape,\n innerCallback: (shape: NodeShapeData) => void,\n ) => {\n if (targetShapeClass.hasOwnProperty('shape')) {\n innerCallback((targetShapeClass as typeof Shape).shape);\n } else {\n if (!targetShapeClass['shapeCallbacks']) {\n targetShapeClass['shapeCallbacks'] = [];\n }\n targetShapeClass['shapeCallbacks'].push(innerCallback);\n }\n };\n\n if (Array.isArray(shapeClass)) {\n const [packageName, shapeName] = shapeClass;\n const nodeShapeId = getNodeShapeUri(packageName, shapeName);\n if (typeof document !== 'undefined') {\n window.addEventListener('load', () => {\n const resolved = getShapeClass(nodeShapeId);\n if (!resolved) {\n console.warn(\n `Could not find value shape (${packageName}/${shapeName}) for accessor get ${propertyName}(). Likely because it is not bundled.`,\n );\n return;\n }\n safeCallback(resolved as unknown as typeof Shape, cb);\n });\n } else {\n addNodeShapeCallback(nodeShapeId, cb);\n }\n } else {\n safeCallback(shapeClass, cb);\n }\n}\n\nconst _linkedProperty = <\n Config extends ObjectPropertyShapeConfig | LiteralPropertyShapeConfig,\n>(\n config: Config,\n defaultNodeKind: NodeReferenceValue = null,\n) => {\n return function (\n target: any,\n propertyKey: string,\n _descriptor: PropertyDescriptor,\n ) {\n createPropertyShape(config, propertyKey, defaultNodeKind, target.constructor);\n };\n};\n\nexport const literalProperty = (config: LiteralPropertyShapeConfig) => {\n return _linkedProperty<LiteralPropertyShapeConfig>(config, shacl.Literal);\n};\n\nexport const objectProperty = (config: ObjectPropertyShapeConfig) => {\n return _linkedProperty<ObjectPropertyShapeConfig>(config, shacl.IRI);\n};\n\nexport const linkedProperty = (\n config: ObjectPropertyShapeConfig | LiteralPropertyShapeConfig,\n) => {\n return _linkedProperty(config);\n};\n\nexport function disallowProperty(\n target: any,\n propertyKey: string,\n _descriptor: PropertyDescriptor,\n) {\n onShapeSetup(\n target.constructor,\n (shape: NodeShapeData) => {\n const superClass = Object.getPrototypeOf(target.constructor) as typeof Shape;\n const superNodeShape = superClass.shape;\n const superPropertyShape = getPropertyShapeData(\n superNodeShape,\n propertyKey,\n true,\n );\n if (!superPropertyShape) {\n console.warn(\n `Property ${propertyKey} not found in super class ${superClass.name} or any of its super classes. Does it have a property decorator? Cannot disallow property ${target.constructor.name}.${propertyKey}`,\n );\n return;\n }\n const clonedPropertyShape = clonePropertyShape(superPropertyShape);\n clonedPropertyShape.maxCount = 0;\n registerPropertyShape(shape, clonedPropertyShape);\n },\n '',\n true,\n );\n}\n\nexport function getNodeShapeUri(packageName: string, shapeName: string): string {\n // arch-02: `{baseUri}shape/{packageSlug}/{ShapeName}` — ShapeName kept PascalCase\n // (it is a class name, already URI-safe), packageSlug derived from the name.\n return `${resolveBaseUri(packageName)}shape/${packageNameToSlug(packageName)}/${shapeName}`;\n}\n\n/** Callbacks waiting for a node shape to register, shared so a registration through any copy of core fires them. */\nconst nodeShapeCallbacks = sharedState(\n '@_linked/core',\n 'SHACL.nodeShapeCallbacks',\n () => new Map<string, ((shape: NodeShapeData) => void)[]>(),\n);\nexport function getAndClearCallbacks(\n nodeShapeId: string,\n): ((shape: NodeShapeData) => void)[] {\n const callbacks = nodeShapeCallbacks.get(nodeShapeId);\n nodeShapeCallbacks.delete(nodeShapeId);\n return callbacks;\n}\nexport const addNodeShapeCallback = (\n nodeShapeId: string,\n callback: (shape: NodeShapeData) => void,\n) => {\n if (!nodeShapeCallbacks.has(nodeShapeId)) {\n nodeShapeCallbacks.set(nodeShapeId, []);\n }\n nodeShapeCallbacks.get(nodeShapeId).push(callback);\n};\n"]}
@@ -40,7 +40,9 @@ export declare function createShapeTarget<S extends Shape>(shapeClass: ShapeCons
40
40
  export declare abstract class Shape {
41
41
  static targetClass: NodeReferenceValue;
42
42
  static shape: NodeShapeData;
43
- static typesToShapes: Map<string, Set<typeof Shape>>;
43
+ static get typesToShapes(): Map<string, Set<typeof Shape>>;
44
+ /** Replaces the shared map, for every copy of core (e.g. a test reset). */
45
+ static set typesToShapes(map: Map<string, Set<typeof Shape>>);
44
46
  __queryContextId?: string;
45
47
  /** The query-context name this shape was registered under (for `{@ctx}` refs). */
46
48
  __queryContextName?: string;
@@ -16,6 +16,17 @@ import { UpdateBuilder } from '../queries/UpdateBuilder.js';
16
16
  import { DeleteBuilder } from '../queries/DeleteBuilder.js';
17
17
  import { getPropertyShapeByLabel } from '../utils/ShapeClass.js';
18
18
  import { ShapeSet } from '../collections/ShapeSet.js';
19
+ import { sharedState } from '../utils/sharedState.js';
20
+ import { brandLinkedClass, isLinkedInstance } from '../utils/linkedError.js';
21
+ /**
22
+ * Shape classes by target class, shared so a class registered through any copy of core is listed.
23
+ * Named `Shape.typesToShapes`, not `Shape`: `Symbol.for('@_linked/core:Shape')` is Shape's class
24
+ * brand, and a container under that key on `globalThis` would make anything inheriting from
25
+ * `globalThis` pass `isLinkedInstance(x, Shape)`.
26
+ */
27
+ const shapeTypeState = sharedState('@_linked/core', 'Shape.typesToShapes', () => ({
28
+ typesToShapes: new Map(),
29
+ }));
19
30
  /**
20
31
  * @internal
21
32
  * Build a constructor-less, prototype-linked Shape used ONLY as a proxy /
@@ -33,6 +44,13 @@ export function createShapeTarget(shapeClass, id) {
33
44
  return target;
34
45
  }
35
46
  export class Shape {
47
+ static get typesToShapes() {
48
+ return shapeTypeState.typesToShapes;
49
+ }
50
+ /** Replaces the shared map, for every copy of core (e.g. a test reset). */
51
+ static set typesToShapes(map) {
52
+ shapeTypeState.typesToShapes = map;
53
+ }
36
54
  // Instantiation guard DEFERRED on the `lego-demo` branch (per René): some
37
55
  // framework shapes (e.g. server `LocalFileStore`) legitimately `extends Shape`
38
56
  // and are constructed as runtime service objects, which the upstream guard
@@ -287,7 +305,7 @@ export class Shape {
287
305
  static getSetOf(values) {
288
306
  const set = new ShapeSet();
289
307
  for (const value of values) {
290
- if (value instanceof Shape) {
308
+ if (isLinkedInstance(value, Shape)) {
291
309
  set.add(value);
292
310
  }
293
311
  else {
@@ -299,5 +317,5 @@ export class Shape {
299
317
  }
300
318
  }
301
319
  Shape.targetClass = null;
302
- Shape.typesToShapes = new Map();
320
+ brandLinkedClass(Shape, '@_linked/core', 'Shape');
303
321
  //# sourceMappingURL=Shape.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Shape.js","sourceRoot":"","sources":["../../../src/shapes/Shape.ts"],"names":[],"mappings":";;;;;;;;;AAcA,OAAO,EAAC,YAAY,EAAC,MAAM,4BAA4B,CAAC;AACxD,OAAO,EAAC,UAAU,EAAC,MAAM,0BAA0B,CAAC;AACpD,OAAO,EAAC,YAAY,EAAC,MAAM,4BAA4B,CAAC;AACxD,OAAO,EAAC,YAAY,EAAC,MAAM,4BAA4B,CAAC;AAGxD,OAAO,EAAC,aAAa,EAAC,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAC,aAAa,EAAC,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAC,aAAa,EAAgB,MAAM,6BAA6B,CAAC;AAEzE,OAAO,EAAC,uBAAuB,EAAC,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EAAC,QAAQ,EAAC,MAAM,4BAA4B,CAAC;AA2BpD;;;;;;;;GAQG;AACH,MAAM,UAAU,iBAAiB,CAC/B,UAA8C,EAC9C,EAAW;IAEX,MAAM,MAAM,GAA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AC7C,CAAC;gBACF,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACpB,CAAC;QACH,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC;;AAtYM,iBAAW,GAAuB,IAAI,CAAC;AAEvC,mBAAa,GAAmC,IAAI,GAAG,EAAE,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 type {NodeShapeData, PropertyShapeData} from './nodeShapeData.js';\nimport type {\n QueryBuildFn,\n QueryResponseToResultType,\n SelectAllQueryResponse,\n WhereClause,\n} from '../queries/SelectQuery.js';\nimport type {NodeReferenceValue, UpdatePartial} from '../queries/QueryFactory.js';\nimport type {NodeId} from '../queries/MutationQuery.js';\nimport {QueryBuilder} from '../queries/QueryBuilder.js';\nimport {AskBuilder} from '../queries/AskBuilder.js';\nimport {CountBuilder} from '../queries/CountBuilder.js';\nimport {resolveShape} from '../queries/resolveShape.js';\nimport type {PendingQueryContext} from '../queries/QueryContext.js';\nimport type {IDataset} from '../interfaces/IDataset.js';\nimport {CreateBuilder} from '../queries/CreateBuilder.js';\nimport {UpdateBuilder} from '../queries/UpdateBuilder.js';\nimport {DeleteBuilder, type DeleteId} from '../queries/DeleteBuilder.js';\nimport type {ExpressionUpdateProxy, ExpressionUpdateResult} from '../expressions/ExpressionMethods.js';\nimport {getPropertyShapeByLabel} from '../utils/ShapeClass.js';\nimport {ShapeSet} from '../collections/ShapeSet.js';\n\n//shape that returns property shapes for its keys\ntype AccessPropertiesShape<T extends Shape> = {\n [P in keyof T]: PropertyShapeData;\n};\ntype PropertyShapeMapFunction<T extends Shape, ResponseType> = (\n p: AccessPropertiesShape<T>,\n) => ResponseType;\n\n/**\n * Concrete constructor type for Shape subclasses — used at runtime boundaries\n * (Builder `from()` methods, Shape static `this` parameters, mutation factories).\n *\n * Uses concrete `new` (not `abstract new`) so TypeScript accepts the class as a\n * value and reads its static `.shape`/`.targetClass` without casts. NOTE: `new\n * shape()` is only a *type-level* capability — at runtime the `Shape` constructor\n * throws (shapes are metadata, not data). The framework builds proxy targets via\n * `createShapeTarget()` (Object.create), never `new`.\n */\nexport type ShapeConstructor<S extends Shape = Shape> = (new (\n ...args: any[]\n) => S) & {\n shape: NodeShapeData;\n targetClass?: NodeReferenceValue;\n};\n\n/**\n * @internal\n * Build a constructor-less, prototype-linked Shape used ONLY as a proxy /\n * metadata-carrier target inside the query DSL (never handed to consumers and\n * never persisted). It is a genuine `Shape` on the prototype chain — so\n * `.constructor`, the `nodeShape` getter, `ShapeSet`, and `getLeastSpecificShape`\n * all work — but it deliberately bypasses the `Shape` constructor, which is\n * guarded to reject direct instantiation. Not exported from the package index.\n */\nexport function createShapeTarget<S extends Shape>(\n shapeClass: ShapeConstructor<S> | typeof Shape,\n id?: string,\n): S {\n const target = Object.create(shapeClass.prototype) as S;\n if (id !== undefined) {\n target.id = id;\n }\n return target;\n}\n\nexport abstract class Shape {\n static targetClass: NodeReferenceValue = null;\n static shape: NodeShapeData;\n static typesToShapes: Map<string, Set<typeof Shape>> = new Map();\n\n __queryContextId?: string;\n /** The query-context name this shape was registered under (for `{@ctx}` refs). */\n __queryContextName?: string;\n id?: string;\n\n // Instantiation guard DEFERRED on the `lego-demo` branch (per René): some\n // framework shapes (e.g. server `LocalFileStore`) legitimately `extends Shape`\n // and are constructed as runtime service objects, which the upstream guard\n // (core report 026) rejects at backend boot. The `validate()`/`assertValid()`\n // work from the same dev merge is KEPT; only the constructor throw is relaxed —\n // restoring pre-guard behaviour: accept an optional node ref and set `id`\n // (mirrors `createShapeTarget`). Re-enable the guard once those shapes migrate.\n constructor(node?: string | {id?: string}) {\n if (node !== undefined) {\n this.id = typeof node === 'string' ? node : node.id;\n }\n }\n\n get nodeShape(): NodeShapeData {\n return (this.constructor as typeof Shape).shape;\n }\n\n get uri(): string {\n return this.id;\n }\n\n set uri(value: string) {\n this.id = value;\n }\n\n /**\n * @internal\n * @param shapeClass\n * @param type\n */\n static registerByType(shapeClass: typeof Shape, type?: NodeReferenceValue) {\n if (!type) {\n if (shapeClass === Shape) {\n return;\n }\n const shapeType = shapeClass.targetClass;\n if (shapeType) {\n type = shapeType;\n }\n }\n if (!type) {\n return;\n }\n const typeId = type.id;\n if (!this.typesToShapes.has(typeId)) {\n this.typesToShapes.set(typeId, new Set());\n }\n this.typesToShapes.get(typeId).add(shapeClass);\n }\n\n /**\n * Select properties of instances of this shape.\n * Chain `.for(id)` to target a single entity, or `.forAll(ids)` for multiple.\n * The select callback receives a proxy of the shape for type-safe property access.\n */\n static select<\n S extends Shape,\n R = unknown,\n ResultType = QueryResponseToResultType<R, S>[],\n >(\n this: ShapeConstructor<S>,\n selectFn: QueryBuildFn<S, R>,\n ): QueryBuilder<S, R, ResultType>;\n static select<\n S extends Shape,\n R = unknown,\n ResultType = QueryResponseToResultType<R, S>[],\n >(\n this: ShapeConstructor<S>,\n ): QueryBuilder<S, R, ResultType>;\n static select<\n S extends Shape,\n R = unknown,\n ResultType = QueryResponseToResultType<R, S>[],\n >(\n this: ShapeConstructor<S>,\n selectFn?: QueryBuildFn<S, R>,\n ): QueryBuilder<S, R, ResultType> {\n let builder = QueryBuilder.from(this) as QueryBuilder<S, any, any>;\n if (selectFn) {\n builder = builder.select(selectFn as any);\n }\n return builder as QueryBuilder<S, R, ResultType>;\n }\n\n /**\n * Select all decorated properties of this shape.\n * Chain `.for(id)` to target a single entity.\n */\n static selectAll<\n S extends Shape,\n ResultType = QueryResponseToResultType<\n SelectAllQueryResponse<S>,\n S\n >[],\n >(\n this: ShapeConstructor<S>,\n ): QueryBuilder<S, any, ResultType> {\n return QueryBuilder.from(this).selectAll() as QueryBuilder<S, any, ResultType>;\n }\n\n /**\n * Whether a node with this id exists as an instance of this shape.\n *\n * On the base class — `Shape.exists(uri)` — it means something different and\n * weaker: does a node with this IRI exist **at all**, under any type or none.\n * There is no shape to constrain by, so no `rdf:type` triple is emitted and the\n * query is `ASK { <uri> ?p ?o }`. (`Shape` is free to mean this because the\n * shapes themselves are described by `NodeShape` and `PropertyShape`, so\n * `Shape.exists` is not needed for \"is this a shape?\".) Because a shapeless ask\n * has no shape to route on, a router asks every dataset it knows — see\n * `LinkedStorage.askQuery`.\n *\n * ```typescript\n * if (await SourceDocument.exists({id})) {\n * await SourceDocument.update(values).for({id});\n * } else {\n * await SourceDocument.create({id, ...values});\n * }\n * ```\n *\n * Resolves to a real `boolean` — unlike `select().where(…).one()`, which resolves\n * to a row or `null` and leaves the conversion (and the failure modes) to the\n * caller. Runs the cheapest correct query: against a SPARQL store, an\n * `ASK WHERE { ?a0 rdf:type <ShapeClass> . FILTER(?a0 = <id>) }` — the shape's\n * type triple and an equality filter on the subject, nothing else.\n *\n * Note the type triple: this asks whether the node exists **as an instance of\n * this shape**. A node with that IRI and a different type answers `false`.\n *\n * A `null`/`undefined` id resolves to `false` without touching the store — as does\n * a `PendingQueryContext` whose value has not landed yet, since there is no subject\n * to ask about. (An unresolved context inside a *where clause* rejects instead; see\n * {@link QueryBuilder.exists}.)\n *\n * **Errors reject — they are never reported as `false`.** Do not wrap this in a\n * `.catch(() => false)`: that is exactly how a broken existence check hides,\n * turning every `exists ? update : create` into an unconditional `create`.\n *\n * For \"does *anything* match?\", compose on the builder instead:\n * `await Person.select().where(p => p.name.equals('Semmy')).exists()`.\n *\n * @param id The node id: a string IRI, a `{id}` reference, or a `PendingQueryContext`.\n * A malformed string IRI rejects (it does not throw synchronously).\n * @param target Optional explicit dataset to run against; omitted uses the\n * global query dispatch.\n */\n static async exists<S extends Shape>(\n this: ShapeConstructor<S> | typeof Shape,\n id: string | NodeReferenceValue | PendingQueryContext | null | undefined,\n target?: IDataset,\n ): Promise<boolean> {\n // `async`, so that a bad string IRI (resolveUriOrThrow) rejects rather than\n // throwing synchronously past the caller's .catch().\n if ((this as unknown) === Shape) {\n // Called on the base class: no shape to constrain by, so no rdf:type triple.\n // `ASK { <iri> ?p ?o }` — does this node exist at all?\n return AskBuilder.forNode(id).exec(target);\n }\n return QueryBuilder.from(this as ShapeConstructor<S>).for(id).exists(target);\n }\n\n /**\n * How many instances of this shape exist — a real `number`.\n *\n * ```typescript\n * const total = await Person.count();\n * ```\n *\n * This is the unfiltered total. For a filtered one, compose on the builder, which\n * is the form a paging table wants:\n *\n * ```typescript\n * await Person.select().where(p => p.name.equals('Semmy')).count();\n * ```\n *\n * Runs the cheapest correct query: against a SPARQL store,\n * `SELECT (COUNT(DISTINCT ?a0) AS ?count) WHERE { ?a0 rdf:type <ShapeClass> }` —\n * the shape's type triple and nothing else. Note the type triple: this counts\n * instances **of this shape**, not nodes in general.\n *\n * **On the base class — `Shape.count()` — this throws.** Unlike\n * {@link Shape.exists}, whose shapeless reading (\"does this node exist at all?\")\n * is useful and cheap, a shapeless count would count every node in every dataset\n * the router knows. No caller means that, so it is refused rather than answered.\n *\n * **Errors reject — they are never reported as `0`.** Do not wrap this in a\n * `.catch(() => 0)`: `0` is a plausible count, so a broken one renders an empty\n * table that looks exactly like real data.\n *\n * @param target Optional explicit dataset to run against; omitted uses the\n * global query dispatch.\n */\n static async count<S extends Shape>(\n this: ShapeConstructor<S> | typeof Shape,\n target?: IDataset,\n ): Promise<number> {\n // `async`, so the base-class refusal rejects rather than throwing synchronously\n // past the caller's `.catch()`.\n if ((this as unknown) === Shape) {\n throw new Error(\n 'Shape.count() has no meaning on the base class: there is no shape to ' +\n 'constrain by, so it would count every node in the store, under any type or ' +\n 'none. Call it on a shape subclass (`Person.count()`), or compose a filter ' +\n 'on the builder (`Person.select().where(…).count()`).',\n );\n }\n return CountBuilder.of({\n shapeClass: resolveShape(this as ShapeConstructor<S>),\n }).exec(target);\n }\n\n /**\n * Update properties of an instance of this shape.\n * Chain `.for(id)` to target a specific entity.\n *\n * ```typescript\n * await Person.update({name: 'Alice'}).for({id: '...'});\n * ```\n *\n * **`__id` is for *new* nodes only** — a fixed id for a nested node being\n * created (here, when **adding** to a relation: `update({friends: {add: {__id, name}}})`).\n * Do NOT put `__id` on a plain single-valued *replace* (`update({image: {__id, contentUrl}})`):\n * it re-targets that same node and *adds* another value instead of replacing\n * (breaks `sh:maxCount 1`). For a replace, **omit `__id`** — the engine drops the\n * old edge and writes a fresh node, so the value replaces cleanly. (Use `Shape.create`\n * for `__id` at creation; use `.delete()` or `{remove: […]}` for full owned-node cleanup.)\n *\n * **On a node that does not exist, this still writes — untyped.** `update`'s WHERE is a\n * bare `OPTIONAL`, so it matches whether or not the subject exists, and the INSERT fires\n * either way. What it never writes is `rdf:type`, so the result is an id carrying\n * properties that no shape-scoped select can find, and the call reports success. If the\n * node may be absent, use {@link Shape.upsert} instead, which asserts the type. (Whether\n * `update` should instead no-op on an absent node is an open semantic question — core\n * backlog 039.)\n */\n static update<S extends Shape>(\n this: ShapeConstructor<S>,\n data: (p: ExpressionUpdateProxy<S>) => ExpressionUpdateResult<S>,\n ): UpdateBuilder<S, any>;\n static update<S extends Shape, U extends UpdatePartial<S>>(\n this: ShapeConstructor<S>,\n data: U,\n ): UpdateBuilder<S, U>;\n static update<S extends Shape>(\n this: ShapeConstructor<S>,\n data: any,\n ): UpdateBuilder<S, any> {\n return UpdateBuilder.from(this).set(data) as unknown as UpdateBuilder<S, any>;\n }\n\n /**\n * Create the node if it is absent, replace the named properties if it is present —\n * in one request.\n *\n * ```ts\n * await SourceDocument.upsert(values).for({id});\n * ```\n *\n * This replaces the branch callers otherwise hand-roll:\n *\n * ```ts\n * if (await S.exists({id})) await S.update(values).for({id});\n * else await S.create({id, ...values});\n * ```\n *\n * which costs two round-trips, races between them, and — if the check is wrong in the\n * `false` direction — takes the `create` branch silently, duplicating single-valued\n * properties rather than erroring.\n *\n * Semantics:\n * - Replaces **only the properties named**; others on an existing node are untouched.\n * It is not a whole-node replace.\n * - Always asserts the node's type, which `update().for({id})` does not — an update\n * against an absent id writes its properties onto an untyped node.\n * - Returns what `update` returns. It deliberately does **not** report whether it\n * created or replaced: knowing that needs the extra read this avoids.\n * - `.where()` / `.forAll()` are rejected — an upsert targets one known id.\n * - **The id goes in `.for(id)`, not in the data object** — unlike `create`, where an\n * `id`/`__id` in the data names the node being created. Here the data object is\n * properties only; an `id` in it is rejected.\n * - Expression-valued fields are rejected: an expression reads the node's current\n * value, which does not exist when upsert creates it, and the property would be\n * silently skipped.\n */\n static upsert<S extends Shape, U extends UpdatePartial<S>>(\n this: ShapeConstructor<S>,\n data: U,\n ): UpdateBuilder<S, U> {\n return UpdateBuilder.upsertFrom(this).set(data) as unknown as UpdateBuilder<S, U>;\n }\n\n static create<S extends Shape, U extends UpdatePartial<S>>(\n this: ShapeConstructor<S>,\n updateObjectOrFn?: U,\n ): CreateBuilder<S, U> {\n let builder = CreateBuilder.from(this) as CreateBuilder<S, any>;\n if (updateObjectOrFn) {\n builder = builder.set(updateObjectOrFn);\n }\n return builder as unknown as CreateBuilder<S, U>;\n }\n\n static delete<S extends Shape>(\n this: ShapeConstructor<S>,\n id: DeleteId | DeleteId[] | NodeReferenceValue[],\n ): DeleteBuilder<S> {\n return DeleteBuilder.from(this, id) as DeleteBuilder<S>;\n }\n\n /** Delete all instances of this shape type. Returns void. */\n static deleteAll<S extends Shape>(\n this: ShapeConstructor<S>,\n ): DeleteBuilder<S, void> {\n return (DeleteBuilder.from(this) as DeleteBuilder<S>).all();\n }\n\n /** Delete instances matching a condition. Sugar for `.delete().where(fn)`. Returns void. */\n static deleteWhere<S extends Shape>(\n this: ShapeConstructor<S>,\n fn: WhereClause<S>,\n ): DeleteBuilder<S, void> {\n return (DeleteBuilder.from(this) as DeleteBuilder<S>).where(fn);\n }\n\n /**\n * @deprecated Unused; the DSL reads property shapes via `nodeShapeData` free\n * functions and static metadata. Scheduled for removal.\n */\n static mapPropertyShapes<S extends Shape, ResponseType = unknown>(\n this: ShapeConstructor<S>,\n mapFunction?: PropertyShapeMapFunction<S, ResponseType>,\n ): ResponseType {\n // SAFETY: dummyShape is used as a dynamic proxy target — we assign .proxy and\n // access arbitrary property names on it, which S doesn't declare.\n let dummyShape: any = createShapeTarget(this);\n dummyShape.proxy = new Proxy(dummyShape, {\n get(target, key, receiver) {\n if (typeof key === 'string') {\n if (key in dummyShape) {\n if (typeof dummyShape[key] === 'function') {\n return target[key].bind(target);\n }\n let propertyShape = getPropertyShapeByLabel(\n dummyShape.constructor,\n key.toString(),\n );\n if (propertyShape) {\n return propertyShape;\n }\n throw new Error(\n `${this.name}.${key.toString()} is missing a @linkedProperty decorator. This method can only access decorated get/set methods.`,\n );\n }\n }\n },\n });\n return mapFunction(dummyShape.proxy);\n }\n\n /**\n * @deprecated Unused; shapes are metadata and no longer materialized into\n * `ShapeSet`s of instances. Scheduled for removal.\n */\n static getSetOf<T extends Shape>(\n this: ShapeConstructor<T>,\n values: Iterable<T | NodeReferenceValue | string>,\n ): ShapeSet<T> {\n const set = new ShapeSet<T>();\n for (const value of values) {\n if (value instanceof Shape) {\n set.add(value as T);\n } else {\n const instance = createShapeTarget(\n this,\n typeof value === 'string' ? value : value.id,\n );\n set.add(instance);\n }\n }\n return set;\n }\n}\n"]}
1
+ {"version":3,"file":"Shape.js","sourceRoot":"","sources":["../../../src/shapes/Shape.ts"],"names":[],"mappings":";;;;;;;;;AAcA,OAAO,EAAC,YAAY,EAAC,MAAM,4BAA4B,CAAC;AACxD,OAAO,EAAC,UAAU,EAAC,MAAM,0BAA0B,CAAC;AACpD,OAAO,EAAC,YAAY,EAAC,MAAM,4BAA4B,CAAC;AACxD,OAAO,EAAC,YAAY,EAAC,MAAM,4BAA4B,CAAC;AAGxD,OAAO,EAAC,aAAa,EAAC,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAC,aAAa,EAAC,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAC,aAAa,EAAgB,MAAM,6BAA6B,CAAC;AAEzE,OAAO,EAAC,uBAAuB,EAAC,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EAAC,QAAQ,EAAC,MAAM,4BAA4B,CAAC;AACpD,OAAO,EAAC,WAAW,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ChI,CAAC;oBACJ,CAAC;gBACH,CAAC;YACH,CAAC;SACF,CAAC,CAAC;QACH,OAAO,WAAW,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;IACvC,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,QAAQ,CAEb,MAAiD;QAEjD,MAAM,GAAG,GAAG,IAAI,QAAQ,EAAK,CAAC;QAC9B,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;YAC3B,IAAI,gBAAgB,CAAC,KAAK,EAAE,KAAK,CAAC,EAAE,CAAC;gBACnC,GAAG,CAAC,GAAG,CAAC,KAAU,CAAC,CAAC;YACtB,CAAC;iBAAM,CAAC;gBACN,MAAM,QAAQ,GAAG,iBAAiB,CAChC,IAAI,EACJ,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAC7C,CAAC;gBACF,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACpB,CAAC;QACH,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC;;AA5YM,iBAAW,GAAuB,IAAI,CAAC;AA8YhD,gBAAgB,CAAC,KAAK,EAAE,eAAe,EAAE,OAAO,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 type {NodeShapeData, PropertyShapeData} from './nodeShapeData.js';\nimport type {\n QueryBuildFn,\n QueryResponseToResultType,\n SelectAllQueryResponse,\n WhereClause,\n} from '../queries/SelectQuery.js';\nimport type {NodeReferenceValue, UpdatePartial} from '../queries/QueryFactory.js';\nimport type {NodeId} from '../queries/MutationQuery.js';\nimport {QueryBuilder} from '../queries/QueryBuilder.js';\nimport {AskBuilder} from '../queries/AskBuilder.js';\nimport {CountBuilder} from '../queries/CountBuilder.js';\nimport {resolveShape} from '../queries/resolveShape.js';\nimport type {PendingQueryContext} from '../queries/QueryContext.js';\nimport type {IDataset} from '../interfaces/IDataset.js';\nimport {CreateBuilder} from '../queries/CreateBuilder.js';\nimport {UpdateBuilder} from '../queries/UpdateBuilder.js';\nimport {DeleteBuilder, type DeleteId} from '../queries/DeleteBuilder.js';\nimport type {ExpressionUpdateProxy, ExpressionUpdateResult} from '../expressions/ExpressionMethods.js';\nimport {getPropertyShapeByLabel} from '../utils/ShapeClass.js';\nimport {ShapeSet} from '../collections/ShapeSet.js';\nimport {sharedState} from '../utils/sharedState.js';\nimport {brandLinkedClass, isLinkedInstance} from '../utils/linkedError.js';\n\n/**\n * Shape classes by target class, shared so a class registered through any copy of core is listed.\n * Named `Shape.typesToShapes`, not `Shape`: `Symbol.for('@_linked/core:Shape')` is Shape's class\n * brand, and a container under that key on `globalThis` would make anything inheriting from\n * `globalThis` pass `isLinkedInstance(x, Shape)`.\n */\nconst shapeTypeState = sharedState('@_linked/core', 'Shape.typesToShapes', () => ({\n typesToShapes: new Map<string, Set<typeof Shape>>(),\n}));\n\n//shape that returns property shapes for its keys\ntype AccessPropertiesShape<T extends Shape> = {\n [P in keyof T]: PropertyShapeData;\n};\ntype PropertyShapeMapFunction<T extends Shape, ResponseType> = (\n p: AccessPropertiesShape<T>,\n) => ResponseType;\n\n/**\n * Concrete constructor type for Shape subclasses — used at runtime boundaries\n * (Builder `from()` methods, Shape static `this` parameters, mutation factories).\n *\n * Uses concrete `new` (not `abstract new`) so TypeScript accepts the class as a\n * value and reads its static `.shape`/`.targetClass` without casts. NOTE: `new\n * shape()` is only a *type-level* capability — at runtime the `Shape` constructor\n * throws (shapes are metadata, not data). The framework builds proxy targets via\n * `createShapeTarget()` (Object.create), never `new`.\n */\nexport type ShapeConstructor<S extends Shape = Shape> = (new (\n ...args: any[]\n) => S) & {\n shape: NodeShapeData;\n targetClass?: NodeReferenceValue;\n};\n\n/**\n * @internal\n * Build a constructor-less, prototype-linked Shape used ONLY as a proxy /\n * metadata-carrier target inside the query DSL (never handed to consumers and\n * never persisted). It is a genuine `Shape` on the prototype chain — so\n * `.constructor`, the `nodeShape` getter, `ShapeSet`, and `getLeastSpecificShape`\n * all work — but it deliberately bypasses the `Shape` constructor, which is\n * guarded to reject direct instantiation. Not exported from the package index.\n */\nexport function createShapeTarget<S extends Shape>(\n shapeClass: ShapeConstructor<S> | typeof Shape,\n id?: string,\n): S {\n const target = Object.create(shapeClass.prototype) as S;\n if (id !== undefined) {\n target.id = id;\n }\n return target;\n}\n\nexport abstract class Shape {\n static targetClass: NodeReferenceValue = null;\n static shape: NodeShapeData;\n static get typesToShapes(): Map<string, Set<typeof Shape>> {\n return shapeTypeState.typesToShapes;\n }\n /** Replaces the shared map, for every copy of core (e.g. a test reset). */\n static set typesToShapes(map: Map<string, Set<typeof Shape>>) {\n shapeTypeState.typesToShapes = map;\n }\n\n __queryContextId?: string;\n /** The query-context name this shape was registered under (for `{@ctx}` refs). */\n __queryContextName?: string;\n id?: string;\n\n // Instantiation guard DEFERRED on the `lego-demo` branch (per René): some\n // framework shapes (e.g. server `LocalFileStore`) legitimately `extends Shape`\n // and are constructed as runtime service objects, which the upstream guard\n // (core report 026) rejects at backend boot. The `validate()`/`assertValid()`\n // work from the same dev merge is KEPT; only the constructor throw is relaxed —\n // restoring pre-guard behaviour: accept an optional node ref and set `id`\n // (mirrors `createShapeTarget`). Re-enable the guard once those shapes migrate.\n constructor(node?: string | {id?: string}) {\n if (node !== undefined) {\n this.id = typeof node === 'string' ? node : node.id;\n }\n }\n\n get nodeShape(): NodeShapeData {\n return (this.constructor as typeof Shape).shape;\n }\n\n get uri(): string {\n return this.id;\n }\n\n set uri(value: string) {\n this.id = value;\n }\n\n /**\n * @internal\n * @param shapeClass\n * @param type\n */\n static registerByType(shapeClass: typeof Shape, type?: NodeReferenceValue) {\n if (!type) {\n if (shapeClass === Shape) {\n return;\n }\n const shapeType = shapeClass.targetClass;\n if (shapeType) {\n type = shapeType;\n }\n }\n if (!type) {\n return;\n }\n const typeId = type.id;\n if (!this.typesToShapes.has(typeId)) {\n this.typesToShapes.set(typeId, new Set());\n }\n this.typesToShapes.get(typeId).add(shapeClass);\n }\n\n /**\n * Select properties of instances of this shape.\n * Chain `.for(id)` to target a single entity, or `.forAll(ids)` for multiple.\n * The select callback receives a proxy of the shape for type-safe property access.\n */\n static select<\n S extends Shape,\n R = unknown,\n ResultType = QueryResponseToResultType<R, S>[],\n >(\n this: ShapeConstructor<S>,\n selectFn: QueryBuildFn<S, R>,\n ): QueryBuilder<S, R, ResultType>;\n static select<\n S extends Shape,\n R = unknown,\n ResultType = QueryResponseToResultType<R, S>[],\n >(\n this: ShapeConstructor<S>,\n ): QueryBuilder<S, R, ResultType>;\n static select<\n S extends Shape,\n R = unknown,\n ResultType = QueryResponseToResultType<R, S>[],\n >(\n this: ShapeConstructor<S>,\n selectFn?: QueryBuildFn<S, R>,\n ): QueryBuilder<S, R, ResultType> {\n let builder = QueryBuilder.from(this) as QueryBuilder<S, any, any>;\n if (selectFn) {\n builder = builder.select(selectFn as any);\n }\n return builder as QueryBuilder<S, R, ResultType>;\n }\n\n /**\n * Select all decorated properties of this shape.\n * Chain `.for(id)` to target a single entity.\n */\n static selectAll<\n S extends Shape,\n ResultType = QueryResponseToResultType<\n SelectAllQueryResponse<S>,\n S\n >[],\n >(\n this: ShapeConstructor<S>,\n ): QueryBuilder<S, any, ResultType> {\n return QueryBuilder.from(this).selectAll() as QueryBuilder<S, any, ResultType>;\n }\n\n /**\n * Whether a node with this id exists as an instance of this shape.\n *\n * On the base class — `Shape.exists(uri)` — it means something different and\n * weaker: does a node with this IRI exist **at all**, under any type or none.\n * There is no shape to constrain by, so no `rdf:type` triple is emitted and the\n * query is `ASK { <uri> ?p ?o }`. (`Shape` is free to mean this because the\n * shapes themselves are described by `NodeShape` and `PropertyShape`, so\n * `Shape.exists` is not needed for \"is this a shape?\".) Because a shapeless ask\n * has no shape to route on, a router asks every dataset it knows — see\n * `LinkedStorage.askQuery`.\n *\n * ```typescript\n * if (await SourceDocument.exists({id})) {\n * await SourceDocument.update(values).for({id});\n * } else {\n * await SourceDocument.create({id, ...values});\n * }\n * ```\n *\n * Resolves to a real `boolean` — unlike `select().where(…).one()`, which resolves\n * to a row or `null` and leaves the conversion (and the failure modes) to the\n * caller. Runs the cheapest correct query: against a SPARQL store, an\n * `ASK WHERE { ?a0 rdf:type <ShapeClass> . FILTER(?a0 = <id>) }` — the shape's\n * type triple and an equality filter on the subject, nothing else.\n *\n * Note the type triple: this asks whether the node exists **as an instance of\n * this shape**. A node with that IRI and a different type answers `false`.\n *\n * A `null`/`undefined` id resolves to `false` without touching the store — as does\n * a `PendingQueryContext` whose value has not landed yet, since there is no subject\n * to ask about. (An unresolved context inside a *where clause* rejects instead; see\n * {@link QueryBuilder.exists}.)\n *\n * **Errors reject — they are never reported as `false`.** Do not wrap this in a\n * `.catch(() => false)`: that is exactly how a broken existence check hides,\n * turning every `exists ? update : create` into an unconditional `create`.\n *\n * For \"does *anything* match?\", compose on the builder instead:\n * `await Person.select().where(p => p.name.equals('Semmy')).exists()`.\n *\n * @param id The node id: a string IRI, a `{id}` reference, or a `PendingQueryContext`.\n * A malformed string IRI rejects (it does not throw synchronously).\n * @param target Optional explicit dataset to run against; omitted uses the\n * global query dispatch.\n */\n static async exists<S extends Shape>(\n this: ShapeConstructor<S> | typeof Shape,\n id: string | NodeReferenceValue | PendingQueryContext | null | undefined,\n target?: IDataset,\n ): Promise<boolean> {\n // `async`, so that a bad string IRI (resolveUriOrThrow) rejects rather than\n // throwing synchronously past the caller's .catch().\n if ((this as unknown) === Shape) {\n // Called on the base class: no shape to constrain by, so no rdf:type triple.\n // `ASK { <iri> ?p ?o }` — does this node exist at all?\n return AskBuilder.forNode(id).exec(target);\n }\n return QueryBuilder.from(this as ShapeConstructor<S>).for(id).exists(target);\n }\n\n /**\n * How many instances of this shape exist — a real `number`.\n *\n * ```typescript\n * const total = await Person.count();\n * ```\n *\n * This is the unfiltered total. For a filtered one, compose on the builder, which\n * is the form a paging table wants:\n *\n * ```typescript\n * await Person.select().where(p => p.name.equals('Semmy')).count();\n * ```\n *\n * Runs the cheapest correct query: against a SPARQL store,\n * `SELECT (COUNT(DISTINCT ?a0) AS ?count) WHERE { ?a0 rdf:type <ShapeClass> }` —\n * the shape's type triple and nothing else. Note the type triple: this counts\n * instances **of this shape**, not nodes in general.\n *\n * **On the base class — `Shape.count()` — this throws.** Unlike\n * {@link Shape.exists}, whose shapeless reading (\"does this node exist at all?\")\n * is useful and cheap, a shapeless count would count every node in every dataset\n * the router knows. No caller means that, so it is refused rather than answered.\n *\n * **Errors reject — they are never reported as `0`.** Do not wrap this in a\n * `.catch(() => 0)`: `0` is a plausible count, so a broken one renders an empty\n * table that looks exactly like real data.\n *\n * @param target Optional explicit dataset to run against; omitted uses the\n * global query dispatch.\n */\n static async count<S extends Shape>(\n this: ShapeConstructor<S> | typeof Shape,\n target?: IDataset,\n ): Promise<number> {\n // `async`, so the base-class refusal rejects rather than throwing synchronously\n // past the caller's `.catch()`.\n if ((this as unknown) === Shape) {\n throw new Error(\n 'Shape.count() has no meaning on the base class: there is no shape to ' +\n 'constrain by, so it would count every node in the store, under any type or ' +\n 'none. Call it on a shape subclass (`Person.count()`), or compose a filter ' +\n 'on the builder (`Person.select().where(…).count()`).',\n );\n }\n return CountBuilder.of({\n shapeClass: resolveShape(this as ShapeConstructor<S>),\n }).exec(target);\n }\n\n /**\n * Update properties of an instance of this shape.\n * Chain `.for(id)` to target a specific entity.\n *\n * ```typescript\n * await Person.update({name: 'Alice'}).for({id: '...'});\n * ```\n *\n * **`__id` is for *new* nodes only** — a fixed id for a nested node being\n * created (here, when **adding** to a relation: `update({friends: {add: {__id, name}}})`).\n * Do NOT put `__id` on a plain single-valued *replace* (`update({image: {__id, contentUrl}})`):\n * it re-targets that same node and *adds* another value instead of replacing\n * (breaks `sh:maxCount 1`). For a replace, **omit `__id`** — the engine drops the\n * old edge and writes a fresh node, so the value replaces cleanly. (Use `Shape.create`\n * for `__id` at creation; use `.delete()` or `{remove: […]}` for full owned-node cleanup.)\n *\n * **On a node that does not exist, this still writes — untyped.** `update`'s WHERE is a\n * bare `OPTIONAL`, so it matches whether or not the subject exists, and the INSERT fires\n * either way. What it never writes is `rdf:type`, so the result is an id carrying\n * properties that no shape-scoped select can find, and the call reports success. If the\n * node may be absent, use {@link Shape.upsert} instead, which asserts the type. (Whether\n * `update` should instead no-op on an absent node is an open semantic question — core\n * backlog 039.)\n */\n static update<S extends Shape>(\n this: ShapeConstructor<S>,\n data: (p: ExpressionUpdateProxy<S>) => ExpressionUpdateResult<S>,\n ): UpdateBuilder<S, any>;\n static update<S extends Shape, U extends UpdatePartial<S>>(\n this: ShapeConstructor<S>,\n data: U,\n ): UpdateBuilder<S, U>;\n static update<S extends Shape>(\n this: ShapeConstructor<S>,\n data: any,\n ): UpdateBuilder<S, any> {\n return UpdateBuilder.from(this).set(data) as unknown as UpdateBuilder<S, any>;\n }\n\n /**\n * Create the node if it is absent, replace the named properties if it is present —\n * in one request.\n *\n * ```ts\n * await SourceDocument.upsert(values).for({id});\n * ```\n *\n * This replaces the branch callers otherwise hand-roll:\n *\n * ```ts\n * if (await S.exists({id})) await S.update(values).for({id});\n * else await S.create({id, ...values});\n * ```\n *\n * which costs two round-trips, races between them, and — if the check is wrong in the\n * `false` direction — takes the `create` branch silently, duplicating single-valued\n * properties rather than erroring.\n *\n * Semantics:\n * - Replaces **only the properties named**; others on an existing node are untouched.\n * It is not a whole-node replace.\n * - Always asserts the node's type, which `update().for({id})` does not — an update\n * against an absent id writes its properties onto an untyped node.\n * - Returns what `update` returns. It deliberately does **not** report whether it\n * created or replaced: knowing that needs the extra read this avoids.\n * - `.where()` / `.forAll()` are rejected — an upsert targets one known id.\n * - **The id goes in `.for(id)`, not in the data object** — unlike `create`, where an\n * `id`/`__id` in the data names the node being created. Here the data object is\n * properties only; an `id` in it is rejected.\n * - Expression-valued fields are rejected: an expression reads the node's current\n * value, which does not exist when upsert creates it, and the property would be\n * silently skipped.\n */\n static upsert<S extends Shape, U extends UpdatePartial<S>>(\n this: ShapeConstructor<S>,\n data: U,\n ): UpdateBuilder<S, U> {\n return UpdateBuilder.upsertFrom(this).set(data) as unknown as UpdateBuilder<S, U>;\n }\n\n static create<S extends Shape, U extends UpdatePartial<S>>(\n this: ShapeConstructor<S>,\n updateObjectOrFn?: U,\n ): CreateBuilder<S, U> {\n let builder = CreateBuilder.from(this) as CreateBuilder<S, any>;\n if (updateObjectOrFn) {\n builder = builder.set(updateObjectOrFn);\n }\n return builder as unknown as CreateBuilder<S, U>;\n }\n\n static delete<S extends Shape>(\n this: ShapeConstructor<S>,\n id: DeleteId | DeleteId[] | NodeReferenceValue[],\n ): DeleteBuilder<S> {\n return DeleteBuilder.from(this, id) as DeleteBuilder<S>;\n }\n\n /** Delete all instances of this shape type. Returns void. */\n static deleteAll<S extends Shape>(\n this: ShapeConstructor<S>,\n ): DeleteBuilder<S, void> {\n return (DeleteBuilder.from(this) as DeleteBuilder<S>).all();\n }\n\n /** Delete instances matching a condition. Sugar for `.delete().where(fn)`. Returns void. */\n static deleteWhere<S extends Shape>(\n this: ShapeConstructor<S>,\n fn: WhereClause<S>,\n ): DeleteBuilder<S, void> {\n return (DeleteBuilder.from(this) as DeleteBuilder<S>).where(fn);\n }\n\n /**\n * @deprecated Unused; the DSL reads property shapes via `nodeShapeData` free\n * functions and static metadata. Scheduled for removal.\n */\n static mapPropertyShapes<S extends Shape, ResponseType = unknown>(\n this: ShapeConstructor<S>,\n mapFunction?: PropertyShapeMapFunction<S, ResponseType>,\n ): ResponseType {\n // SAFETY: dummyShape is used as a dynamic proxy target — we assign .proxy and\n // access arbitrary property names on it, which S doesn't declare.\n let dummyShape: any = createShapeTarget(this);\n dummyShape.proxy = new Proxy(dummyShape, {\n get(target, key, receiver) {\n if (typeof key === 'string') {\n if (key in dummyShape) {\n if (typeof dummyShape[key] === 'function') {\n return target[key].bind(target);\n }\n let propertyShape = getPropertyShapeByLabel(\n dummyShape.constructor,\n key.toString(),\n );\n if (propertyShape) {\n return propertyShape;\n }\n throw new Error(\n `${this.name}.${key.toString()} is missing a @linkedProperty decorator. This method can only access decorated get/set methods.`,\n );\n }\n }\n },\n });\n return mapFunction(dummyShape.proxy);\n }\n\n /**\n * @deprecated Unused; shapes are metadata and no longer materialized into\n * `ShapeSet`s of instances. Scheduled for removal.\n */\n static getSetOf<T extends Shape>(\n this: ShapeConstructor<T>,\n values: Iterable<T | NodeReferenceValue | string>,\n ): ShapeSet<T> {\n const set = new ShapeSet<T>();\n for (const value of values) {\n if (isLinkedInstance(value, Shape)) {\n set.add(value as T);\n } else {\n const instance = createShapeTarget(\n this,\n typeof value === 'string' ? value : value.id,\n );\n set.add(instance);\n }\n }\n return set;\n }\n}\nbrandLinkedClass(Shape, '@_linked/core', 'Shape');\n\n"]}
@@ -6,7 +6,8 @@ export interface IErrorLogger {
6
6
  * Install any error client package like lincd-sentry in your app to log errors.
7
7
  */
8
8
  export declare class LinkedErrorLogging {
9
- private static logger;
9
+ private static get logger();
10
+ private static set logger(value);
10
11
  static setDefaultLogger(logger: IErrorLogger): void;
11
12
  static hasDefaultLogger(): boolean;
12
13
  static log(error: Error): Promise<void>;
@@ -1,8 +1,19 @@
1
+ import { sharedState } from './sharedState.js';
2
+ /** The logger, shared so one set through any copy of core (e.g. by `@_linked/sentry`) logs for all. */
3
+ const loggingState = sharedState('@_linked/core', 'LinkedErrorLogging', () => ({
4
+ logger: undefined,
5
+ }));
1
6
  /**
2
7
  * Utility class to log errors.
3
8
  * Install any error client package like lincd-sentry in your app to log errors.
4
9
  */
5
10
  export class LinkedErrorLogging {
11
+ static get logger() {
12
+ return loggingState.logger;
13
+ }
14
+ static set logger(logger) {
15
+ loggingState.logger = logger;
16
+ }
6
17
  static setDefaultLogger(logger) {
7
18
  this.logger = logger;
8
19
  }
@@ -1 +1 @@
1
- {"version":3,"file":"LinkedErrorLogging.js","sourceRoot":"","sources":["../../../src/utils/LinkedErrorLogging.ts"],"names":[],"mappings":"AAIA;;;GAGG;AACH,MAAM,OAAO,kBAAkB;IAG7B,MAAM,CAAC,gBAAgB,CAAC,MAAoB;QAC1C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED,MAAM,CAAC,gBAAgB;QACrB,OAAO,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC;IAC7B,CAAC;IAED,MAAM,CAAC,GAAG,CAAC,KAAY;QACrB,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;CACF","sourcesContent":["export interface IErrorLogger {\n log?(error: any): Promise<void>;\n}\n\n/**\n * Utility class to log errors.\n * Install any error client package like lincd-sentry in your app to log errors.\n */\nexport class LinkedErrorLogging {\n private static logger: IErrorLogger;\n\n static setDefaultLogger(logger: IErrorLogger) {\n this.logger = logger;\n }\n\n static hasDefaultLogger() {\n return this.logger && true;\n }\n\n static log(error: Error) {\n if (this.logger) {\n return this.logger.log(error);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"LinkedErrorLogging.js","sourceRoot":"","sources":["../../../src/utils/LinkedErrorLogging.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,WAAW,EAAC,MAAM,kBAAkB,CAAC;AAM7C,uGAAuG;AACvG,MAAM,YAAY,GAAG,WAAW,CAAC,eAAe,EAAE,oBAAoB,EAAE,GAAG,EAAE,CAAC,CAAC;IAC7E,MAAM,EAAE,SAAqC;CAC9C,CAAC,CAAC,CAAC;AAEJ;;;GAGG;AACH,MAAM,OAAO,kBAAkB;IACrB,MAAM,KAAK,MAAM;QACvB,OAAO,YAAY,CAAC,MAAM,CAAC;IAC7B,CAAC;IACO,MAAM,KAAK,MAAM,CAAC,MAAgC;QACxD,YAAY,CAAC,MAAM,GAAG,MAAM,CAAC;IAC/B,CAAC;IAED,MAAM,CAAC,gBAAgB,CAAC,MAAoB;QAC1C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED,MAAM,CAAC,gBAAgB;QACrB,OAAO,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC;IAC7B,CAAC;IAED,MAAM,CAAC,GAAG,CAAC,KAAY;QACrB,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;CACF","sourcesContent":["import {sharedState} from './sharedState.js';\n\nexport interface IErrorLogger {\n log?(error: any): Promise<void>;\n}\n\n/** The logger, shared so one set through any copy of core (e.g. by `@_linked/sentry`) logs for all. */\nconst loggingState = sharedState('@_linked/core', 'LinkedErrorLogging', () => ({\n logger: undefined as IErrorLogger | undefined,\n}));\n\n/**\n * Utility class to log errors.\n * Install any error client package like lincd-sentry in your app to log errors.\n */\nexport class LinkedErrorLogging {\n private static get logger(): IErrorLogger | undefined {\n return loggingState.logger;\n }\n private static set logger(logger: IErrorLogger | undefined) {\n loggingState.logger = logger;\n }\n\n static setDefaultLogger(logger: IErrorLogger) {\n this.logger = logger;\n }\n\n static hasDefaultLogger() {\n return this.logger && true;\n }\n\n static log(error: Error) {\n if (this.logger) {\n return this.logger.log(error);\n }\n }\n}\n"]}