@_linked/core 2.33.0 → 2.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/README.md +26 -0
- package/lib/esm/index.d.ts +2 -1
- package/lib/esm/index.js +2 -0
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/live/LiveQueryStore.d.ts +22 -0
- package/lib/esm/live/LiveQueryStore.js +86 -19
- package/lib/esm/live/LiveQueryStore.js.map +1 -1
- package/lib/esm/live/changes.d.ts +9 -1
- package/lib/esm/live/changes.js +7 -2
- package/lib/esm/live/changes.js.map +1 -1
- package/lib/esm/live/keys.d.ts +6 -0
- package/lib/esm/live/keys.js +10 -1
- package/lib/esm/live/keys.js.map +1 -1
- package/lib/esm/live/matcher.d.ts +4 -1
- package/lib/esm/live/matcher.js +10 -5
- package/lib/esm/live/matcher.js.map +1 -1
- package/lib/esm/queries/AskBuilder.d.ts +6 -0
- package/lib/esm/queries/AskBuilder.js +14 -0
- package/lib/esm/queries/AskBuilder.js.map +1 -1
- package/lib/esm/queries/CountBuilder.d.ts +6 -0
- package/lib/esm/queries/CountBuilder.js +14 -0
- package/lib/esm/queries/CountBuilder.js.map +1 -1
- package/lib/esm/queries/CreateBuilder.d.ts +4 -0
- package/lib/esm/queries/CreateBuilder.js +15 -1
- package/lib/esm/queries/CreateBuilder.js.map +1 -1
- package/lib/esm/queries/DeleteBuilder.d.ts +4 -0
- package/lib/esm/queries/DeleteBuilder.js +15 -1
- package/lib/esm/queries/DeleteBuilder.js.map +1 -1
- package/lib/esm/queries/FieldSet.d.ts +10 -0
- package/lib/esm/queries/FieldSet.js +85 -18
- package/lib/esm/queries/FieldSet.js.map +1 -1
- package/lib/esm/queries/IRLower.js +3 -2
- package/lib/esm/queries/IRLower.js.map +1 -1
- package/lib/esm/queries/IRMutation.js +15 -14
- package/lib/esm/queries/IRMutation.js.map +1 -1
- package/lib/esm/queries/MutationSerialization.js +2 -2
- package/lib/esm/queries/MutationSerialization.js.map +1 -1
- package/lib/esm/queries/PropertyPath.js +2 -2
- package/lib/esm/queries/PropertyPath.js.map +1 -1
- package/lib/esm/queries/QueryBuilder.d.ts +7 -0
- package/lib/esm/queries/QueryBuilder.js +40 -3
- package/lib/esm/queries/QueryBuilder.js.map +1 -1
- package/lib/esm/queries/SelectQuery.js +2 -2
- package/lib/esm/queries/SelectQuery.js.map +1 -1
- package/lib/esm/queries/UpdateBuilder.d.ts +4 -0
- package/lib/esm/queries/UpdateBuilder.js +15 -1
- package/lib/esm/queries/UpdateBuilder.js.map +1 -1
- package/lib/esm/queries/fromJSON.d.ts +12 -1
- package/lib/esm/queries/fromJSON.js +5 -1
- package/lib/esm/queries/fromJSON.js.map +1 -1
- package/lib/esm/queries/lower.js +12 -5
- package/lib/esm/queries/lower.js.map +1 -1
- package/lib/esm/queries/queryDependencies.js +14 -10
- package/lib/esm/queries/queryDependencies.js.map +1 -1
- package/lib/esm/queries/resolveShape.js +14 -2
- package/lib/esm/queries/resolveShape.js.map +1 -1
- package/lib/esm/shapes/Shape.js +2 -1
- package/lib/esm/shapes/Shape.js.map +1 -1
- package/lib/esm/shapes/nodeShapeData.js +7 -10
- package/lib/esm/shapes/nodeShapeData.js.map +1 -1
- package/lib/esm/shapes/registerRuntimeShape.js +3 -1
- package/lib/esm/shapes/registerRuntimeShape.js.map +1 -1
- package/lib/esm/shapes/syncShapes.d.ts +6 -2
- package/lib/esm/shapes/syncShapes.js +16 -9
- package/lib/esm/shapes/syncShapes.js.map +1 -1
- package/lib/esm/shapes/validation.js +2 -2
- package/lib/esm/shapes/validation.js.map +1 -1
- package/lib/esm/sparql/irToAlgebra.js +117 -52
- package/lib/esm/sparql/irToAlgebra.js.map +1 -1
- package/lib/esm/sparql/ownedLinkCheck.js +6 -1
- package/lib/esm/sparql/ownedLinkCheck.js.map +1 -1
- package/lib/esm/utils/LinkedStorage.d.ts +7 -0
- package/lib/esm/utils/LinkedStorage.js +39 -12
- package/lib/esm/utils/LinkedStorage.js.map +1 -1
- package/lib/esm/utils/ShapeCatalog.d.ts +57 -0
- package/lib/esm/utils/ShapeCatalog.js +86 -0
- package/lib/esm/utils/ShapeCatalog.js.map +1 -0
- package/lib/esm/utils/ShapeClass.d.ts +73 -8
- package/lib/esm/utils/ShapeClass.js +245 -66
- package/lib/esm/utils/ShapeClass.js.map +1 -1
- package/lib/esm/utils/loadStores.d.ts +4 -0
- package/lib/esm/utils/loadStores.js +24 -1
- package/lib/esm/utils/loadStores.js.map +1 -1
- package/lib/esm/utils/registryCache.d.ts +15 -0
- package/lib/esm/utils/registryCache.js +50 -0
- package/lib/esm/utils/registryCache.js.map +1 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UpdateBuilder.js","sourceRoot":"","sources":["../../../src/queries/UpdateBuilder.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,EAAC,YAAY,EAAC,MAAM,mBAAmB,CAAC;AAE/C,OAAO,EAAC,oBAAoB,EAAC,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAC,gBAAgB,EAAC,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAC,uBAAuB,EAAC,MAAM,oBAAoB,CAAC;AAE3D,OAAO,EAAC,YAAY,EAAE,iBAAiB,EAAC,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAC,mBAAmB,EAAE,eAAe,EAAE,sBAAsB,EAAC,MAAM,mBAAmB,CAAC;AAC/F,OAAO,EAAC,gBAAgB,EAAE,gBAAgB,EAAC,MAAM,iBAAiB,CAAC;AAEnE,OAAO,EAAmC,kBAAkB,EAAC,MAAM,kBAAkB,CAAC;AAEtF,OAAO,EACL,cAAc,EACd,mBAAmB,GAGpB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAC,kBAAkB,EAAE,oBAAoB,EAAC,MAAM,gCAAgC,CAAC;AA0BxF;;;;;;;;;;;;GAYG;AACH,MAAM,OAAO,aACX,SAAQ,gBAAmB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AAE,CAAC;gBACf,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;YAC1E,CAAC;YACD,mFAAmF;YACnF,wDAAwD;YACvD,IAA2B,CAAC,KAAK,GAAG,kBAAkB,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACxF,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;;;;;OAMG;IACG,IAAI,CAAC,MAAiB;;YAC1B,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;YAChE,MAAM,MAAM,GAAG,uBAAuB,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;YAC3E,+EAA+E;YAC/E,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;gBAC1C,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,CAAe,CAAC;YACpD,CAAC;YACD,OAAO,MAAoB,CAAC;QAC9B,CAAC;KAAA;CAEF","sourcesContent":["import {Shape, type ShapeConstructor} from '../shapes/Shape.js';\nimport {resolveShape} from './resolveShape.js';\nimport {type AddId, type UpdatePartial, NodeReferenceValue} from './QueryFactory.js';\nimport {MutationQueryFactory} from './MutationQuery.js';\nimport {MutationThenable} from './MutationThenable.js';\nimport {resolveMutationDispatch} from './queryDispatch.js';\nimport type {IDataset} from '../interfaces/IDataset.js';\nimport {WIRE_VERSION, assertWireVersion} from './wireVersion.js';\nimport {PendingQueryContext, getQueryContext, UnresolvedContextError} from './QueryContext.js';\nimport {encodeContextRef, isContextRefJSON} from './ContextRef.js';\nimport type {NodeShapeData} from '../shapes/SHACL.js';\nimport {type WhereClause, type WherePath, processWhereClause} from './SelectQuery.js';\nimport type {ExpressionUpdateProxy, ExpressionUpdateResult} from '../expressions/ExpressionMethods.js';\nimport {\n encodeNodeData,\n decodeNodeDataToRaw,\n type UpdateMutationJSON,\n type UpsertMutationJSON,\n} from './MutationSerialization.js';\nimport {serializeWherePath, deserializeWherePath} from './QueryBuilderSerialization.js';\nimport type {UpdateLowerSpec} from './mutationLowerSpec.js';\n\ntype UpdateMode = 'for' | 'forAll' | 'where';\n\n/**\n * Internal state bag for UpdateBuilder.\n */\ninterface UpdateBuilderInit<S extends Shape> {\n shape: ShapeConstructor<S>;\n data?: UpdatePartial<S>;\n targetId?: string;\n mode?: UpdateMode;\n whereFn?: WhereClause<S>;\n /** A pre-resolved where path (used by fromJSON; no live callback). */\n where?: WherePath;\n /** A query-context name used as the target subject (resolved at lowering). */\n targetContextName?: string;\n /**\n * Upsert mode — create-or-replace against a known id. Set by `Shape.upsert()`.\n * The builder is otherwise identical to an update, which is why it reuses this class;\n * only the lowered IR kind and the `.where()`/`.forAll()` guards differ.\n */\n upsert?: boolean;\n}\n\n/**\n * An immutable, fluent builder for update mutations.\n *\n * Every mutation method returns a new UpdateBuilder — the original is never modified.\n *\n * Implements PromiseLike so mutations execute on `await`:\n * ```ts\n * const result = await UpdateBuilder.from(Person).for({id: '...'}).set({name: 'Bob'});\n * await UpdateBuilder.from(Person).set({hobby: 'x'}).forAll(); // returns void\n * ```\n *\n * R is the resolved type: AddId<U> for ID-based, void for bulk operations.\n */\nexport class UpdateBuilder<S extends Shape = Shape, U extends UpdatePartial<S> = UpdatePartial<S>, R = AddId<U>>\n extends MutationThenable<R>\n{\n protected readonly _tag = 'UpdateBuilder';\n private readonly _shape: ShapeConstructor<S>;\n private readonly _data?: UpdatePartial<S>;\n private readonly _targetId?: string;\n private readonly _mode?: UpdateMode;\n private readonly _whereFn?: WhereClause<S>;\n private readonly _where?: WherePath;\n private readonly _targetContextName?: string;\n private readonly _upsert: boolean;\n\n private constructor(init: UpdateBuilderInit<S>) {\n super();\n this._shape = init.shape;\n this._data = init.data;\n this._targetId = init.targetId;\n this._mode = init.mode;\n this._whereFn = init.whereFn;\n this._where = init.where;\n this._targetContextName = init.targetContextName;\n this._upsert = init.upsert ?? false;\n }\n\n private clone(overrides: Partial<UpdateBuilderInit<S>> = {}): UpdateBuilder<S, any, any> {\n return new UpdateBuilder<S, any>({\n shape: this._shape,\n data: this._data,\n targetId: this._targetId,\n mode: this._mode,\n whereFn: this._whereFn,\n where: this._where,\n targetContextName: this._targetContextName,\n upsert: this._upsert,\n ...overrides,\n });\n }\n\n // ---------------------------------------------------------------------------\n // Static constructors\n // ---------------------------------------------------------------------------\n\n static from<S extends Shape>(shape: ShapeConstructor<S> | string): UpdateBuilder<S> {\n const resolved = resolveShape<S>(shape);\n return new UpdateBuilder<S>({shape: resolved});\n }\n\n /** Builder for a create-or-replace against a known id. See `Shape.upsert()`. */\n static upsertFrom<S extends Shape>(shape: ShapeConstructor<S> | string): UpdateBuilder<S> {\n const resolved = resolveShape<S>(shape);\n return new UpdateBuilder<S>({shape: resolved, upsert: true});\n }\n\n /** Reconstruct an UpdateBuilder from its DSL-JSON (inverse of `toJSON`). */\n static fromJSON(json: UpdateMutationJSON | UpsertMutationJSON): UpdateBuilder {\n assertWireVersion(json.v);\n const resolved = resolveShape(json.shape);\n const data = decodeNodeDataToRaw(json.data, resolved.shape) as any;\n\n // Branch on `op` first so each envelope keeps its own narrowed type; an upsert has\n // only the `for` form, so its modes are not the update modes.\n if (json.op === 'upsert') {\n // The type says `mode: 'for'`, but an inbound envelope is untrusted data — the\n // cast keeps the runtime check that the type alone cannot enforce.\n if ((json.mode as string) !== 'for') {\n throw new Error(\n `upsert mode \"${String(json.mode)}\" is invalid — an upsert targets one known id.`,\n );\n }\n if (isContextRefJSON(json.targetId)) {\n return new UpdateBuilder({\n shape: resolved, data, targetContextName: json.targetId['@ctx'], mode: 'for', upsert: true,\n });\n }\n return new UpdateBuilder({shape: resolved, data, targetId: json.targetId, mode: 'for', upsert: true});\n }\n\n if (json.mode === 'for') {\n if (isContextRefJSON(json.targetId)) {\n return new UpdateBuilder({shape: resolved, data, targetContextName: json.targetId['@ctx'], mode: 'for'});\n }\n return new UpdateBuilder({shape: resolved, data, targetId: json.targetId, mode: 'for'});\n }\n if (json.mode === 'forAll') {\n return new UpdateBuilder({shape: resolved, data, mode: 'forAll'});\n }\n const where = deserializeWherePath(resolved.shape, json.where!);\n return new UpdateBuilder({shape: resolved, data, mode: 'where', where});\n }\n\n // ---------------------------------------------------------------------------\n // Fluent API\n // ---------------------------------------------------------------------------\n\n /** Target a specific entity by ID. */\n for(id: string | NodeReferenceValue | PendingQueryContext): UpdateBuilder<S, U, AddId<U>> {\n if (id instanceof PendingQueryContext) {\n return this.clone({targetContextName: id.contextName, targetId: undefined, mode: 'for'}) as unknown as UpdateBuilder<S, U, AddId<U>>;\n }\n const resolvedId = typeof id === 'string' ? id : id.id;\n return this.clone({targetId: resolvedId, targetContextName: undefined, mode: 'for'}) as unknown as UpdateBuilder<S, U, AddId<U>>;\n }\n\n /** Update all instances of this shape type. Returns void. */\n forAll(): UpdateBuilder<S, U, void> {\n this._assertNotUpsert('forAll()');\n return this.clone({mode: 'forAll', targetId: undefined, whereFn: undefined}) as unknown as UpdateBuilder<S, U, void>;\n }\n\n /** Update instances matching a condition. Returns void. */\n where(fn: WhereClause<S>): UpdateBuilder<S, U, void> {\n this._assertNotUpsert('where()');\n return this.clone({mode: 'where', whereFn: fn, targetId: undefined}) as unknown as UpdateBuilder<S, U, void>;\n }\n\n /**\n * An upsert has to know which node to create, so it only makes sense against a single\n * known id. `forAll()` and `where()` select existing nodes — there is nothing to create\n * when they match nothing, and no single id to create it under.\n */\n private _assertNotUpsert(method: string): void {\n if (this._upsert) {\n throw new Error(\n `upsert does not support .${method} — an upsert targets one known id, ` +\n `so use .for(id). (.${method} selects existing nodes, which is what update does.)`,\n );\n }\n }\n\n /** Replace the update data. */\n set(fn: (p: ExpressionUpdateProxy<S>) => ExpressionUpdateResult<S>): UpdateBuilder<S, any, R>;\n set<NewU extends UpdatePartial<S>>(data: NewU): UpdateBuilder<S, NewU, R>;\n set(data: any): any {\n return this.clone({data}) as any;\n }\n\n // ---------------------------------------------------------------------------\n // Build & execute\n // ---------------------------------------------------------------------------\n\n /** Discriminator for the free `lower()` function and dataset routing. */\n readonly __queryKind = 'update' as const;\n\n /** The shape this query targets — the routing key datasets/`LinkedStorage` use. */\n get shape(): NodeShapeData {\n return this._shape.shape;\n }\n\n /** @internal The IR-free lowering spec consumed by `lower()`. Validates inputs. */\n _lowerSpec(): UpdateLowerSpec<S> {\n if (!this._data) {\n throw new Error(\n 'UpdateBuilder requires .set(data) before it can be lowered. Specify what to update.',\n );\n }\n\n const mode = this._mode || (this._targetId ? 'for' : undefined);\n\n if (mode === 'forAll') {\n return {shapeClass: this._shape, data: this._data, mode: 'forAll'};\n }\n\n if (mode === 'where') {\n if (!this._whereFn && !this._where) {\n throw new Error('UpdateBuilder.where() requires a condition callback.');\n }\n const wherePath =\n this._where ?? processWhereClause(this._whereFn!, this._shape);\n return {shapeClass: this._shape, data: this._data, mode: 'where', wherePath};\n }\n\n // Default: ID-based update (target id may come from a query context)\n const targetId = this._resolveTargetId();\n if (!targetId) {\n if (this._targetContextName) {\n throw new UnresolvedContextError(this._targetContextName);\n }\n // A caller arriving from `create({__id: id, ...values})` — which upsert is meant to\n // replace — naturally writes the id into the data object. That form is rejected\n // further down (\"cannot use id in the top level\"), but only once a target exists;\n // without one they would otherwise get a bare \"requires .for(id)\" that never\n // mentions the id they did pass. Name it here instead.\n const strayId = this._strayTopLevelId();\n if (strayId) {\n throw new Error(\n `${this._upsert ? 'upsert' : 'update'} takes the target id in .for(id), not in the data: ` +\n `move \"${strayId}\" out of the data object — ` +\n `${this._upsert ? 'upsert' : 'update'}(values).for({id}). ` +\n `(create() is the one that takes an id in its data, because there it names the node being created.)`,\n );\n }\n throw new Error(\n this._upsert\n ? 'upsert requires .for(id) before it can be lowered — an upsert targets one known id.'\n : 'UpdateBuilder requires .for(id), .forAll(), or .where() before it can be lowered.',\n );\n }\n return {\n shapeClass: this._shape,\n data: this._data,\n mode: 'for',\n targetId,\n ...(this._upsert ? {upsert: true} : {}),\n };\n }\n\n /**\n * The key name of a top-level `id`/`__id` in the update data, if present. Used only to\n * improve the missing-target error; the data object itself is validated downstream.\n */\n private _strayTopLevelId(): string | undefined {\n const data = this._data as Record<string, unknown> | undefined;\n if (!data || typeof data !== 'object') return undefined;\n return ['id', '__id'].find((k) => k in data);\n }\n\n /** Resolve the target id from an explicit id or a query-context reference. */\n private _resolveTargetId(): string | undefined {\n if (this._targetId) return this._targetId;\n if (this._targetContextName) return getQueryContext(this._targetContextName)?.id;\n return undefined;\n }\n\n /**\n * Serialize this update mutation to lightweight DSL-JSON. Normalizes the update\n * data through the IR-free factory base (handles the expression-callback form\n * of `.set()`), and serializes the where clause for `where`-mode updates.\n */\n toJSON(): UpdateMutationJSON | UpsertMutationJSON {\n if (!this._data) {\n throw new Error('UpdateBuilder requires .set(data) before .toJSON().');\n }\n const mode = this._mode || (this._targetId ? 'for' : undefined);\n if (!mode) {\n throw new Error(\n 'UpdateBuilder requires .for(id), .forAll(), or .where() before .toJSON().',\n );\n }\n const fields = new MutationQueryFactory().describe(\n this._shape.shape,\n this._data,\n {validate: 'partial'},\n );\n if (this._upsert && mode !== 'for') {\n throw new Error('upsert requires .for(id) before it can be serialized.');\n }\n const json = {\n v: WIRE_VERSION,\n op: this._upsert ? 'upsert' : 'update',\n shape: this._shape.shape.id,\n mode,\n data: encodeNodeData(fields, this._shape.shape),\n } as UpdateMutationJSON | UpsertMutationJSON;\n if (mode === 'for') {\n if (this._targetContextName) json.targetId = encodeContextRef(this._targetContextName);\n else json.targetId = this._targetId;\n }\n if (mode === 'where') {\n const wherePath = this._where ?? (this._whereFn ? processWhereClause(this._whereFn, this._shape) : undefined);\n if (!wherePath) {\n throw new Error('UpdateBuilder.where() requires a condition callback.');\n }\n // `mode === 'where'` is unreachable for an upsert (guarded in `.where()` and again\n // above), so this branch is always the update envelope.\n (json as UpdateMutationJSON).where = serializeWherePath(wherePath, this._shape.shape);\n }\n return json;\n }\n\n /**\n * Execute the mutation.\n *\n * @param target Optional explicit dataset (a store or a router) to run against. Omitted →\n * the global query dispatch. A `target` runs on that dataset only; the global router is\n * untouched. Rejects if the target dataset doesn't implement update.\n */\n async exec(target?: IDataset): Promise<R> {\n const mode = this._mode || (this._targetId ? 'for' : undefined);\n const result = resolveMutationDispatch('update', target).updateQuery(this);\n // Bulk (forAll/where) resolves to void; id-based resolves to the updated node.\n if (mode === 'forAll' || mode === 'where') {\n return result.then(() => undefined) as Promise<R>;\n }\n return result as Promise<R>;\n }\n\n}\n"]}
|
|
1
|
+
{"version":3,"file":"UpdateBuilder.js","sourceRoot":"","sources":["../../../src/queries/UpdateBuilder.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,EAAC,cAAc,EAAE,qBAAqB,EAAE,gBAAgB,EAAC,MAAM,wBAAwB,CAAC;AAE/F,OAAO,EAAC,YAAY,EAAC,MAAM,mBAAmB,CAAC;AAE/C,OAAO,EAAC,oBAAoB,EAAC,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAC,gBAAgB,EAAC,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAC,uBAAuB,EAAC,MAAM,oBAAoB,CAAC;AAE3D,OAAO,EAAC,YAAY,EAAE,iBAAiB,EAAC,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAC,mBAAmB,EAAE,eAAe,EAAE,sBAAsB,EAAC,MAAM,mBAAmB,CAAC;AAC/F,OAAO,EAAC,gBAAgB,EAAE,gBAAgB,EAAC,MAAM,iBAAiB,CAAC;AAEnE,OAAO,EAAmC,kBAAkB,EAAC,MAAM,kBAAkB,CAAC;AAEtF,OAAO,EACL,cAAc,EACd,mBAAmB,GAGpB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAC,kBAAkB,EAAE,oBAAoB,EAAC,MAAM,gCAAgC,CAAC;AA4BxF;;;;;;;;;;;;GAYG;AACH,MAAM,OAAO,aACX,SAAQ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AI,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;gBAC1C,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,CAAe,CAAC;YACpD,CAAC;YACD,OAAO,MAAoB,CAAC;QAC9B,CAAC;KAAA;CAEF","sourcesContent":["import {Shape, type ShapeConstructor} from '../shapes/Shape.js';\nimport {captureCatalog, getActiveShapeCatalog, withShapeCatalog} from '../utils/ShapeClass.js';\nimport type {ShapeCatalog} from '../utils/ShapeCatalog.js';\nimport {resolveShape} from './resolveShape.js';\nimport {type AddId, type UpdatePartial, NodeReferenceValue} from './QueryFactory.js';\nimport {MutationQueryFactory} from './MutationQuery.js';\nimport {MutationThenable} from './MutationThenable.js';\nimport {resolveMutationDispatch} from './queryDispatch.js';\nimport type {IDataset} from '../interfaces/IDataset.js';\nimport {WIRE_VERSION, assertWireVersion} from './wireVersion.js';\nimport {PendingQueryContext, getQueryContext, UnresolvedContextError} from './QueryContext.js';\nimport {encodeContextRef, isContextRefJSON} from './ContextRef.js';\nimport type {NodeShapeData} from '../shapes/SHACL.js';\nimport {type WhereClause, type WherePath, processWhereClause} from './SelectQuery.js';\nimport type {ExpressionUpdateProxy, ExpressionUpdateResult} from '../expressions/ExpressionMethods.js';\nimport {\n encodeNodeData,\n decodeNodeDataToRaw,\n type UpdateMutationJSON,\n type UpsertMutationJSON,\n} from './MutationSerialization.js';\nimport {serializeWherePath, deserializeWherePath} from './QueryBuilderSerialization.js';\nimport type {UpdateLowerSpec} from './mutationLowerSpec.js';\n\ntype UpdateMode = 'for' | 'forAll' | 'where';\n\n/**\n * Internal state bag for UpdateBuilder.\n */\ninterface UpdateBuilderInit<S extends Shape> {\n shape: ShapeConstructor<S>;\n /** The catalog the builder resolves in; absent = captured from the active one. */\n catalog?: ShapeCatalog;\n data?: UpdatePartial<S>;\n targetId?: string;\n mode?: UpdateMode;\n whereFn?: WhereClause<S>;\n /** A pre-resolved where path (used by fromJSON; no live callback). */\n where?: WherePath;\n /** A query-context name used as the target subject (resolved at lowering). */\n targetContextName?: string;\n /**\n * Upsert mode — create-or-replace against a known id. Set by `Shape.upsert()`.\n * The builder is otherwise identical to an update, which is why it reuses this class;\n * only the lowered IR kind and the `.where()`/`.forAll()` guards differ.\n */\n upsert?: boolean;\n}\n\n/**\n * An immutable, fluent builder for update mutations.\n *\n * Every mutation method returns a new UpdateBuilder — the original is never modified.\n *\n * Implements PromiseLike so mutations execute on `await`:\n * ```ts\n * const result = await UpdateBuilder.from(Person).for({id: '...'}).set({name: 'Bob'});\n * await UpdateBuilder.from(Person).set({hobby: 'x'}).forAll(); // returns void\n * ```\n *\n * R is the resolved type: AddId<U> for ID-based, void for bulk operations.\n */\nexport class UpdateBuilder<S extends Shape = Shape, U extends UpdatePartial<S> = UpdatePartial<S>, R = AddId<U>>\n extends MutationThenable<R>\n{\n protected readonly _tag = 'UpdateBuilder';\n private readonly _shape: ShapeConstructor<S>;\n private readonly _data?: UpdatePartial<S>;\n private readonly _targetId?: string;\n private readonly _mode?: UpdateMode;\n private readonly _whereFn?: WhereClause<S>;\n private readonly _where?: WherePath;\n private readonly _targetContextName?: string;\n private readonly _upsert: boolean;\n\n private readonly _catalog: ShapeCatalog | undefined;\n\n private constructor(init: UpdateBuilderInit<S>) {\n super();\n this._shape = init.shape;\n this._catalog = 'catalog' in init ? init.catalog : captureCatalog(init.shape);\n this._data = init.data;\n this._targetId = init.targetId;\n this._mode = init.mode;\n this._whereFn = init.whereFn;\n this._where = init.where;\n this._targetContextName = init.targetContextName;\n this._upsert = init.upsert ?? false;\n }\n\n private clone(overrides: Partial<UpdateBuilderInit<S>> = {}): UpdateBuilder<S, any, any> {\n return new UpdateBuilder<S, any>({\n shape: this._shape,\n data: this._data,\n targetId: this._targetId,\n mode: this._mode,\n whereFn: this._whereFn,\n where: this._where,\n targetContextName: this._targetContextName,\n upsert: this._upsert,\n catalog: this._catalog,\n ...overrides,\n });\n }\n\n // ---------------------------------------------------------------------------\n // Static constructors\n // ---------------------------------------------------------------------------\n\n static from<S extends Shape>(shape: ShapeConstructor<S> | string): UpdateBuilder<S> {\n const resolved = resolveShape<S>(shape);\n return new UpdateBuilder<S>({shape: resolved});\n }\n\n /** Builder for a create-or-replace against a known id. See `Shape.upsert()`. */\n static upsertFrom<S extends Shape>(shape: ShapeConstructor<S> | string): UpdateBuilder<S> {\n const resolved = resolveShape<S>(shape);\n return new UpdateBuilder<S>({shape: resolved, upsert: true});\n }\n\n /** Reconstruct an UpdateBuilder from its DSL-JSON (inverse of `toJSON`). */\n static fromJSON(json: UpdateMutationJSON | UpsertMutationJSON): UpdateBuilder {\n assertWireVersion(json.v);\n const resolved = resolveShape(json.shape);\n const data = decodeNodeDataToRaw(json.data, resolved.shape) as any;\n\n // Branch on `op` first so each envelope keeps its own narrowed type; an upsert has\n // only the `for` form, so its modes are not the update modes.\n if (json.op === 'upsert') {\n // The type says `mode: 'for'`, but an inbound envelope is untrusted data — the\n // cast keeps the runtime check that the type alone cannot enforce.\n if ((json.mode as string) !== 'for') {\n throw new Error(\n `upsert mode \"${String(json.mode)}\" is invalid — an upsert targets one known id.`,\n );\n }\n if (isContextRefJSON(json.targetId)) {\n return new UpdateBuilder({\n shape: resolved, data, targetContextName: json.targetId['@ctx'], mode: 'for', upsert: true,\n });\n }\n return new UpdateBuilder({shape: resolved, data, targetId: json.targetId, mode: 'for', upsert: true});\n }\n\n if (json.mode === 'for') {\n if (isContextRefJSON(json.targetId)) {\n return new UpdateBuilder({shape: resolved, data, targetContextName: json.targetId['@ctx'], mode: 'for'});\n }\n return new UpdateBuilder({shape: resolved, data, targetId: json.targetId, mode: 'for'});\n }\n if (json.mode === 'forAll') {\n return new UpdateBuilder({shape: resolved, data, mode: 'forAll'});\n }\n const where = deserializeWherePath(resolved.shape, json.where!);\n return new UpdateBuilder({shape: resolved, data, mode: 'where', where});\n }\n\n // ---------------------------------------------------------------------------\n // Fluent API\n // ---------------------------------------------------------------------------\n\n /** Target a specific entity by ID. */\n for(id: string | NodeReferenceValue | PendingQueryContext): UpdateBuilder<S, U, AddId<U>> {\n if (id instanceof PendingQueryContext) {\n return this.clone({targetContextName: id.contextName, targetId: undefined, mode: 'for'}) as unknown as UpdateBuilder<S, U, AddId<U>>;\n }\n const resolvedId = typeof id === 'string' ? id : id.id;\n return this.clone({targetId: resolvedId, targetContextName: undefined, mode: 'for'}) as unknown as UpdateBuilder<S, U, AddId<U>>;\n }\n\n /** Update all instances of this shape type. Returns void. */\n forAll(): UpdateBuilder<S, U, void> {\n this._assertNotUpsert('forAll()');\n return this.clone({mode: 'forAll', targetId: undefined, whereFn: undefined}) as unknown as UpdateBuilder<S, U, void>;\n }\n\n /** Update instances matching a condition. Returns void. */\n where(fn: WhereClause<S>): UpdateBuilder<S, U, void> {\n this._assertNotUpsert('where()');\n return this.clone({mode: 'where', whereFn: fn, targetId: undefined}) as unknown as UpdateBuilder<S, U, void>;\n }\n\n /**\n * An upsert has to know which node to create, so it only makes sense against a single\n * known id. `forAll()` and `where()` select existing nodes — there is nothing to create\n * when they match nothing, and no single id to create it under.\n */\n private _assertNotUpsert(method: string): void {\n if (this._upsert) {\n throw new Error(\n `upsert does not support .${method} — an upsert targets one known id, ` +\n `so use .for(id). (.${method} selects existing nodes, which is what update does.)`,\n );\n }\n }\n\n /** Replace the update data. */\n set(fn: (p: ExpressionUpdateProxy<S>) => ExpressionUpdateResult<S>): UpdateBuilder<S, any, R>;\n set<NewU extends UpdatePartial<S>>(data: NewU): UpdateBuilder<S, NewU, R>;\n set(data: any): any {\n return this.clone({data}) as any;\n }\n\n // ---------------------------------------------------------------------------\n // Build & execute\n // ---------------------------------------------------------------------------\n\n /** Discriminator for the free `lower()` function and dataset routing. */\n readonly __queryKind = 'update' as const;\n\n /** The shape this query targets — the routing key datasets/`LinkedStorage` use. */\n get shape(): NodeShapeData {\n return this._shape.shape;\n }\n\n /** The catalog this builder resolves shapes in (undefined = the global registry). */\n get catalog(): ShapeCatalog | undefined {\n return this._catalog;\n }\n\n /** @internal The IR-free lowering spec consumed by `lower()`. Validates inputs. */\n _lowerSpec(): UpdateLowerSpec<S> {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this._lowerSpec());\n }\n if (!this._data) {\n throw new Error(\n 'UpdateBuilder requires .set(data) before it can be lowered. Specify what to update.',\n );\n }\n\n const mode = this._mode || (this._targetId ? 'for' : undefined);\n\n if (mode === 'forAll') {\n return {shapeClass: this._shape, data: this._data, mode: 'forAll'};\n }\n\n if (mode === 'where') {\n if (!this._whereFn && !this._where) {\n throw new Error('UpdateBuilder.where() requires a condition callback.');\n }\n const wherePath =\n this._where ?? processWhereClause(this._whereFn!, this._shape);\n return {shapeClass: this._shape, data: this._data, mode: 'where', wherePath};\n }\n\n // Default: ID-based update (target id may come from a query context)\n const targetId = this._resolveTargetId();\n if (!targetId) {\n if (this._targetContextName) {\n throw new UnresolvedContextError(this._targetContextName);\n }\n // A caller arriving from `create({__id: id, ...values})` — which upsert is meant to\n // replace — naturally writes the id into the data object. That form is rejected\n // further down (\"cannot use id in the top level\"), but only once a target exists;\n // without one they would otherwise get a bare \"requires .for(id)\" that never\n // mentions the id they did pass. Name it here instead.\n const strayId = this._strayTopLevelId();\n if (strayId) {\n throw new Error(\n `${this._upsert ? 'upsert' : 'update'} takes the target id in .for(id), not in the data: ` +\n `move \"${strayId}\" out of the data object — ` +\n `${this._upsert ? 'upsert' : 'update'}(values).for({id}). ` +\n `(create() is the one that takes an id in its data, because there it names the node being created.)`,\n );\n }\n throw new Error(\n this._upsert\n ? 'upsert requires .for(id) before it can be lowered — an upsert targets one known id.'\n : 'UpdateBuilder requires .for(id), .forAll(), or .where() before it can be lowered.',\n );\n }\n return {\n shapeClass: this._shape,\n data: this._data,\n mode: 'for',\n targetId,\n ...(this._upsert ? {upsert: true} : {}),\n };\n }\n\n /**\n * The key name of a top-level `id`/`__id` in the update data, if present. Used only to\n * improve the missing-target error; the data object itself is validated downstream.\n */\n private _strayTopLevelId(): string | undefined {\n const data = this._data as Record<string, unknown> | undefined;\n if (!data || typeof data !== 'object') return undefined;\n return ['id', '__id'].find((k) => k in data);\n }\n\n /** Resolve the target id from an explicit id or a query-context reference. */\n private _resolveTargetId(): string | undefined {\n if (this._targetId) return this._targetId;\n if (this._targetContextName) return getQueryContext(this._targetContextName)?.id;\n return undefined;\n }\n\n /**\n * Serialize this update mutation to lightweight DSL-JSON. Normalizes the update\n * data through the IR-free factory base (handles the expression-callback form\n * of `.set()`), and serializes the where clause for `where`-mode updates.\n */\n toJSON(): UpdateMutationJSON | UpsertMutationJSON {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.toJSON());\n }\n if (!this._data) {\n throw new Error('UpdateBuilder requires .set(data) before .toJSON().');\n }\n const mode = this._mode || (this._targetId ? 'for' : undefined);\n if (!mode) {\n throw new Error(\n 'UpdateBuilder requires .for(id), .forAll(), or .where() before .toJSON().',\n );\n }\n const fields = new MutationQueryFactory().describe(\n this._shape.shape,\n this._data,\n {validate: 'partial'},\n );\n if (this._upsert && mode !== 'for') {\n throw new Error('upsert requires .for(id) before it can be serialized.');\n }\n const json = {\n v: WIRE_VERSION,\n op: this._upsert ? 'upsert' : 'update',\n shape: this._shape.shape.id,\n mode,\n data: encodeNodeData(fields, this._shape.shape),\n } as UpdateMutationJSON | UpsertMutationJSON;\n if (mode === 'for') {\n if (this._targetContextName) json.targetId = encodeContextRef(this._targetContextName);\n else json.targetId = this._targetId;\n }\n if (mode === 'where') {\n const wherePath = this._where ?? (this._whereFn ? processWhereClause(this._whereFn, this._shape) : undefined);\n if (!wherePath) {\n throw new Error('UpdateBuilder.where() requires a condition callback.');\n }\n // `mode === 'where'` is unreachable for an upsert (guarded in `.where()` and again\n // above), so this branch is always the update envelope.\n (json as UpdateMutationJSON).where = serializeWherePath(wherePath, this._shape.shape);\n }\n return json;\n }\n\n /**\n * Execute the mutation.\n *\n * @param target Optional explicit dataset (a store or a router) to run against. Omitted →\n * the global query dispatch. A `target` runs on that dataset only; the global router is\n * untouched. Rejects if the target dataset doesn't implement update.\n */\n async exec(target?: IDataset): Promise<R> {\n const mode = this._mode || (this._targetId ? 'for' : undefined);\n const result = resolveMutationDispatch('update', target).updateQuery(this);\n // Bulk (forAll/where) resolves to void; id-based resolves to the updated node.\n if (mode === 'forAll' || mode === 'where') {\n return result.then(() => undefined) as Promise<R>;\n }\n return result as Promise<R>;\n }\n\n}\n"]}
|
|
@@ -15,6 +15,17 @@ import { CountBuilder } from './CountBuilder.js';
|
|
|
15
15
|
import type { AskQueryJSON } from './AskQuery.js';
|
|
16
16
|
import type { CountQueryJSON } from './CountQuery.js';
|
|
17
17
|
import type { MutationJSON } from './MutationSerialization.js';
|
|
18
|
+
import type { ShapeCatalog } from '../utils/ShapeCatalog.js';
|
|
19
|
+
/** Options for {@link fromJSON}. */
|
|
20
|
+
export type FromJSONOptions = {
|
|
21
|
+
/**
|
|
22
|
+
* Decode against this catalog — even `undefined`, which means the global registry.
|
|
23
|
+
* Without the key, the active catalog (`withShapeCatalog`) is used. The builder keeps
|
|
24
|
+
* the catalog it was decoded with. The wire never carries a catalog: each side
|
|
25
|
+
* supplies its own.
|
|
26
|
+
*/
|
|
27
|
+
catalog?: ShapeCatalog;
|
|
28
|
+
};
|
|
18
29
|
/** Any query in its wire (DSL-JSON) form. */
|
|
19
30
|
export type QueryJSON = QueryBuilderJSON | AskQueryJSON | CountQueryJSON | MutationJSON;
|
|
20
|
-
export declare function fromJSON(json: QueryJSON): SelectBuilder | AskBuilder | CountBuilder | CreateBuilder | UpdateBuilder | DeleteBuilder;
|
|
31
|
+
export declare function fromJSON(json: QueryJSON, options?: FromJSONOptions): SelectBuilder | AskBuilder | CountBuilder | CreateBuilder | UpdateBuilder | DeleteBuilder;
|
|
@@ -18,7 +18,11 @@ import { DeleteBuilder } from './DeleteBuilder.js';
|
|
|
18
18
|
import { AskBuilder } from './AskBuilder.js';
|
|
19
19
|
import { CountBuilder } from './CountBuilder.js';
|
|
20
20
|
import { assertWireVersion } from './wireVersion.js';
|
|
21
|
-
|
|
21
|
+
import { getActiveShapeCatalog, withShapeCatalog } from '../utils/ShapeClass.js';
|
|
22
|
+
export function fromJSON(json, options) {
|
|
23
|
+
if (options && 'catalog' in options && options.catalog !== getActiveShapeCatalog()) {
|
|
24
|
+
return withShapeCatalog(options.catalog, () => fromJSON(json));
|
|
25
|
+
}
|
|
22
26
|
assertWireVersion(json === null || json === void 0 ? void 0 : json.v);
|
|
23
27
|
if (json && typeof json === 'object' && 'op' in json) {
|
|
24
28
|
switch (json.op) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fromJSON.js","sourceRoot":"","sources":["../../../src/queries/fromJSON.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;;;;GAOG;AACH,OAAO,EAAC,aAAa,EAAwB,MAAM,mBAAmB,CAAC;AACvE,OAAO,EAAC,aAAa,EAAC,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAC,aAAa,EAAC,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAC,aAAa,EAAC,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAC,UAAU,EAAC,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAC,YAAY,EAAC,MAAM,mBAAmB,CAAC;AAI/C,OAAO,EAAC,iBAAiB,EAAC,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"fromJSON.js","sourceRoot":"","sources":["../../../src/queries/fromJSON.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;;;;GAOG;AACH,OAAO,EAAC,aAAa,EAAwB,MAAM,mBAAmB,CAAC;AACvE,OAAO,EAAC,aAAa,EAAC,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAC,aAAa,EAAC,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAC,aAAa,EAAC,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAC,UAA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jF,CAAC;QACN,CAAC;IACH,CAAC;IACD,OAAO,aAAa,CAAC,QAAQ,CAAC,IAAwB,CAAC,CAAC;AAC1D,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 * Kind-detecting `fromJSON` — rehydrate any query DSL-JSON back into its builder.\n *\n * Ask, count and mutation envelopes carry an `op` discriminator; select envelopes\n * (`QueryBuilderJSON`) do not. This is the inbound boundary helper: a receiving\n * process turns wire JSON into a live query with `fromJSON(json).exec()` (the\n * existing generic dispatch), no per-op routing needed.\n */\nimport {SelectBuilder, type QueryBuilderJSON} from './QueryBuilder.js';\nimport {CreateBuilder} from './CreateBuilder.js';\nimport {UpdateBuilder} from './UpdateBuilder.js';\nimport {DeleteBuilder} from './DeleteBuilder.js';\nimport {AskBuilder} from './AskBuilder.js';\nimport {CountBuilder} from './CountBuilder.js';\nimport type {AskQueryJSON} from './AskQuery.js';\nimport type {CountQueryJSON} from './CountQuery.js';\nimport type {MutationJSON} from './MutationSerialization.js';\nimport {assertWireVersion} from './wireVersion.js';\nimport {getActiveShapeCatalog, withShapeCatalog} from '../utils/ShapeClass.js';\nimport type {ShapeCatalog} from '../utils/ShapeCatalog.js';\n\n/** Options for {@link fromJSON}. */\nexport type FromJSONOptions = {\n /**\n * Decode against this catalog — even `undefined`, which means the global registry.\n * Without the key, the active catalog (`withShapeCatalog`) is used. The builder keeps\n * the catalog it was decoded with. The wire never carries a catalog: each side\n * supplies its own.\n */\n catalog?: ShapeCatalog;\n};\n\n/** Any query in its wire (DSL-JSON) form. */\nexport type QueryJSON =\n | QueryBuilderJSON\n | AskQueryJSON\n | CountQueryJSON\n | MutationJSON;\n\nexport function fromJSON(\n json: QueryJSON,\n options?: FromJSONOptions,\n):\n | SelectBuilder\n | AskBuilder\n | CountBuilder\n | CreateBuilder\n | UpdateBuilder\n | DeleteBuilder {\n if (options && 'catalog' in options && options.catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(options.catalog, () => fromJSON(json));\n }\n assertWireVersion((json as {v?: unknown})?.v);\n if (json && typeof json === 'object' && 'op' in json) {\n switch (json.op) {\n case 'ask':\n return AskBuilder.fromJSON(json as AskQueryJSON);\n case 'count':\n return CountBuilder.fromJSON(json as CountQueryJSON);\n case 'create':\n return CreateBuilder.fromJSON(json);\n case 'update':\n case 'upsert':\n // Both reconstruct an UpdateBuilder; the op selects upsert mode inside.\n return UpdateBuilder.fromJSON(json);\n case 'delete':\n return DeleteBuilder.fromJSON(json);\n default:\n // An `op` is present but not one we know — a malformed/corrupted or\n // future-versioned mutation envelope. Fail loud rather than silently\n // reinterpreting it as a select query.\n throw new Error(\n `Unknown query op \"${String((json as {op: unknown}).op)}\" in DSL-JSON envelope.`,\n );\n }\n }\n return SelectBuilder.fromJSON(json as QueryBuilderJSON);\n}\n"]}
|
package/lib/esm/queries/lower.js
CHANGED
|
@@ -23,6 +23,7 @@ import { resolveContextId } from './ContextRef.js';
|
|
|
23
23
|
import { buildCanonicalCreateMutationIR, buildCanonicalUpdateMutationIR, buildCanonicalUpsertMutationIR, buildCanonicalUpdateWhereMutationIR, buildCanonicalDeleteMutationIR, buildCanonicalDeleteAllMutationIR, buildCanonicalDeleteWhereMutationIR, } from './IRMutation.js';
|
|
24
24
|
import { toWhere } from './IRDesugar.js';
|
|
25
25
|
import { lowerWhereToIR } from './IRLower.js';
|
|
26
|
+
import { attachCatalog, catalogOf, getActiveShapeCatalog, withShapeCatalog, } from '../utils/ShapeClass.js';
|
|
26
27
|
/** Lower a pre-evaluated where path to its canonical IR fragment. */
|
|
27
28
|
function lowerWherePath(where) {
|
|
28
29
|
return lowerWhereToIR(toWhere(where));
|
|
@@ -124,7 +125,7 @@ function lowerAsk(input) {
|
|
|
124
125
|
const id = subject instanceof PendingQueryContext
|
|
125
126
|
? resolveContextId(subject.contextName, true)
|
|
126
127
|
: subject === null || subject === void 0 ? void 0 : subject.id;
|
|
127
|
-
return { kind: 'ask', patterns: [], subjectId: id };
|
|
128
|
+
return attachCatalog({ kind: 'ask', patterns: [], subjectId: id });
|
|
128
129
|
}
|
|
129
130
|
const selected = buildSelectQuery({
|
|
130
131
|
entries: [],
|
|
@@ -134,14 +135,14 @@ function lowerAsk(input) {
|
|
|
134
135
|
where: input.where,
|
|
135
136
|
minusEntries: input.minusEntries,
|
|
136
137
|
});
|
|
137
|
-
return {
|
|
138
|
+
return attachCatalog({
|
|
138
139
|
kind: 'ask',
|
|
139
140
|
root: selected.root,
|
|
140
141
|
patterns: selected.patterns,
|
|
141
142
|
where: selected.where,
|
|
142
143
|
subjectId: selected.subjectId,
|
|
143
144
|
subjectIds: selected.subjectIds,
|
|
144
|
-
};
|
|
145
|
+
});
|
|
145
146
|
}
|
|
146
147
|
/**
|
|
147
148
|
* The variable a root count binds its `COUNT` to.
|
|
@@ -192,7 +193,7 @@ function lowerCount(input) {
|
|
|
192
193
|
where: input.where,
|
|
193
194
|
minusEntries: input.minusEntries,
|
|
194
195
|
});
|
|
195
|
-
return {
|
|
196
|
+
return attachCatalog({
|
|
196
197
|
kind: 'count',
|
|
197
198
|
root: selected.root,
|
|
198
199
|
patterns: selected.patterns,
|
|
@@ -200,9 +201,15 @@ function lowerCount(input) {
|
|
|
200
201
|
subjectId: selected.subjectId,
|
|
201
202
|
subjectIds: selected.subjectIds,
|
|
202
203
|
alias: COUNT_ALIAS,
|
|
203
|
-
};
|
|
204
|
+
});
|
|
204
205
|
}
|
|
205
206
|
export function lower(query) {
|
|
207
|
+
// Lower in the catalog the query captured; the IR it returns records it (non-enumerable
|
|
208
|
+
// `catalog`) for the compile that may run after an await.
|
|
209
|
+
const catalog = catalogOf(query);
|
|
210
|
+
if (catalog !== getActiveShapeCatalog()) {
|
|
211
|
+
return withShapeCatalog(catalog, () => lower(query));
|
|
212
|
+
}
|
|
206
213
|
switch (query.__queryKind) {
|
|
207
214
|
case 'select':
|
|
208
215
|
return buildSelectQuery(query.toRawInput());
|
|
@@ -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;AAoC5C,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,GAAG,CAAC,WAAW,EAAE,IAAI,CAAE,EAAC,CAAC;IACxD,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QACvB,OAAO,GAAG,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;IACvC,CAAC;IACD,IAAI,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;QACnC,IAAI,sBAAsB,CAAC,GAAG,CAAC,EAAE,CAAC;YAChC,MAA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K,CAAC,KAAK;QAClB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,OAAO;QACL,IAAI,EAAE,OAAO;QACb,IAAI,EAAE,QAAQ,CAAC,IAAI;QACnB,QAAQ,EAAE,QAAQ,CAAC,QAAQ;QAC3B,KAAK,EAAE,QAAQ,CAAC,KAAK;QACrB,SAAS,EAAE,QAAQ,CAAC,SAAS;QAC7B,UAAU,EAAE,QAAQ,CAAC,UAAU;QAC/B,KAAK,EAAE,WAAW;KACnB,CAAC;AACJ,CAAC;AAQD,MAAM,UAAU,KAAK,CACnB,KAAqB;IAQrB,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 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 {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 {\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 {\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 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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,UAAU;QAC/B,KAAK,EAAE,WAAW;KACnB,CAAC,CAAC;AACL,CAAC;AAQD,MAAM,UAAU,KAAK,CACnB,KAAqB;IAQrB,wFAAwF;IACxF,0DAA0D;IAC1D,MAAM,OAAO,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;IACjC,IAAI,OAAO,KAAK,qBAAqB,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';\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"]}
|
|
@@ -19,10 +19,11 @@
|
|
|
19
19
|
* (`^member`, `knows/name`) contributes every predicate it touches.
|
|
20
20
|
*/
|
|
21
21
|
import { lower } from './lower.js';
|
|
22
|
+
import { RegistryCache } from '../utils/registryCache.js';
|
|
22
23
|
import { getSimplePathId } from '../paths/normalizePropertyPath.js';
|
|
23
24
|
import { collectPathUris } from '../paths/pathExprToSparql.js';
|
|
24
25
|
import { findPropertyShapeById, getPropertyShapes, } from '../shapes/nodeShapeData.js';
|
|
25
|
-
import { getAllNodeShapes, getNodeShape,
|
|
26
|
+
import { getAllNodeShapes, getNodeShape, catalogOf, getActiveShapeCatalog, withShapeCatalog, getShapeClass, } from '../utils/ShapeClass.js';
|
|
26
27
|
// ---------------------------------------------------------------------------
|
|
27
28
|
// Predicate resolution
|
|
28
29
|
// ---------------------------------------------------------------------------
|
|
@@ -55,8 +56,7 @@ function valueShapeOf(propertyShapeId) {
|
|
|
55
56
|
}
|
|
56
57
|
// Owner lookups, cached on the same terms as `findPropertyShapeById`: successful
|
|
57
58
|
// resolutions only, invalidated by the registry version.
|
|
58
|
-
const declaringShapeCache = new
|
|
59
|
-
let declaringShapeCacheVersion = -1;
|
|
59
|
+
const declaringShapeCache = new RegistryCache();
|
|
60
60
|
/**
|
|
61
61
|
* The node shape that declares a property shape as its own.
|
|
62
62
|
*
|
|
@@ -66,17 +66,13 @@ let declaringShapeCacheVersion = -1;
|
|
|
66
66
|
* trace of `Employee` left is that `employeeId` is declared there.
|
|
67
67
|
*/
|
|
68
68
|
function declaringShapeOf(propertyShapeId) {
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
declaringShapeCache.clear();
|
|
72
|
-
declaringShapeCacheVersion = version;
|
|
73
|
-
}
|
|
74
|
-
const cached = declaringShapeCache.get(propertyShapeId);
|
|
69
|
+
const cache = declaringShapeCache.get();
|
|
70
|
+
const cached = cache.get(propertyShapeId);
|
|
75
71
|
if (cached)
|
|
76
72
|
return cached;
|
|
77
73
|
for (const nodeShape of getAllNodeShapes().values()) {
|
|
78
74
|
if (getPropertyShapes(nodeShape, false).some((ps) => ps.id === propertyShapeId)) {
|
|
79
|
-
|
|
75
|
+
cache.set(propertyShapeId, nodeShape.id);
|
|
80
76
|
return nodeShape.id;
|
|
81
77
|
}
|
|
82
78
|
}
|
|
@@ -298,6 +294,10 @@ function isBound(ir) {
|
|
|
298
294
|
*/
|
|
299
295
|
export function queryDependencies(query) {
|
|
300
296
|
var _a;
|
|
297
|
+
const catalog = catalogOf(query);
|
|
298
|
+
if (catalog !== getActiveShapeCatalog()) {
|
|
299
|
+
return withShapeCatalog(catalog, () => queryDependencies(query));
|
|
300
|
+
}
|
|
301
301
|
const ir = lowerQuery(query);
|
|
302
302
|
const collector = new DependencyCollector();
|
|
303
303
|
const deps = collector.deps;
|
|
@@ -424,6 +424,10 @@ function resolveShapeData(shapeId) {
|
|
|
424
424
|
* (`update_where`, `delete_all`, `delete_where`), where `ids` stays `undefined`.
|
|
425
425
|
*/
|
|
426
426
|
export function mutationEffects(mutation, result) {
|
|
427
|
+
const catalog = catalogOf(mutation);
|
|
428
|
+
if (catalog !== getActiveShapeCatalog()) {
|
|
429
|
+
return withShapeCatalog(catalog, () => mutationEffects(mutation, result));
|
|
430
|
+
}
|
|
427
431
|
const ir = lowerMutation(mutation);
|
|
428
432
|
const collector = new EffectCollector();
|
|
429
433
|
switch (ir.kind) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queryDependencies.js","sourceRoot":"","sources":["../../../src/queries/queryDependencies.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAC,KAAK,EAAC,MAAM,YAAY,CAAC;AAwBjC,OAAO,EAAC,eAAe,EAAC,MAAM,mCAAmC,CAAC;AAClE,OAAO,EAAC,eAAe,EAAC,MAAM,8BAA8B,CAAC;AAC7D,OAAO,EACL,qBAAqB,EACrB,iBAAiB,GAElB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,gBAAgB,EAChB,YAAY,EACZ,kBAAkB,EAClB,aAAa,GACd,MAAM,wBAAwB,CAAC;AA0ChC,8EAA8E;AAC9E,uBAAuB;AACvB,8EAA8E;AAE9E;;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S,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;YAC/B,CAAC;YACD,OAAO;gBACL,EAAE,EAAE,QAAQ;gBACZ,KAAK,EAAE,EAAE,CAAC,KAAK;gBACf,KAAK,EAAE,SAAS,CAAC,KAAK;gBACtB,GAAG,EAAE,EAAE,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS;gBACrD,UAAU,EAAE,SAAS,CAAC,UAAU;aACjC,CAAC;QACJ,CAAC;IACH,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 * Dependency helpers for live queries.\n *\n * Two pure functions that describe, in terms of **predicate IRIs**, what a query\n * reads ({@link queryDependencies}) and what a mutation writes\n * ({@link mutationEffects}). A live-query store feeds both into its change matcher:\n * a query is re-run when a mutation writes a predicate the query depends on, on a\n * node the query can see.\n *\n * Both work on the canonical IR (`lower(query)`), where every property is a\n * property-SHAPE id. Each one is resolved to the predicate(s) it is declared with\n * (`sh:path`), so two shapes that share a predicate — `Person.name` and `Team.name`\n * both on `schema:name` — describe the same dependency, and a structured path\n * (`^member`, `knows/name`) contributes every predicate it touches.\n */\nimport {lower} from './lower.js';\nimport type {\n LowerableAsk,\n LowerableCount,\n LowerableCreate,\n LowerableDelete,\n LowerableSelect,\n LowerableUpdate,\n} from './lower.js';\nimport type {\n IRAskQuery,\n IRCountQuery,\n IRExpression,\n IRFieldValue,\n IRGraphPattern,\n IRNodeData,\n IRPropertyExpression,\n IRSelectQuery,\n IRTraversePattern,\n} from './IntermediateRepresentation.js';\nimport type {IRCreateQuery} from './CreateQuery.js';\nimport type {IRUpdateQuery} from './UpdateQuery.js';\nimport type {IRDeleteQuery} from './DeleteQuery.js';\nimport type {PathExpr} from '../paths/PropertyPathExpr.js';\nimport {getSimplePathId} from '../paths/normalizePropertyPath.js';\nimport {collectPathUris} from '../paths/pathExprToSparql.js';\nimport {\n findPropertyShapeById,\n getPropertyShapes,\n type NodeShapeData,\n} from '../shapes/nodeShapeData.js';\nimport {\n getAllNodeShapes,\n getNodeShape,\n getRegistryVersion,\n getShapeClass,\n} from '../utils/ShapeClass.js';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport type QueryDependencies = {\n /** Predicates read on nodes whose ids appear in the result (root row + projected relation rows). */\n narrow: Set<string>;\n /** Predicates deciding membership/order: where, scoped where, minus, exists, sortBy, inner orderBy. */\n filter: Set<string>;\n /**\n * Predicates read on nodes whose ids are NOT projected: `size()` / aggregates over\n * relations, computed values over traversals, traversals with no projected id.\n */\n hidden: Set<string>;\n /**\n * Shape IRIs the query is pinned to: the root scan, nested shape scans (minus by\n * shape), and — for every property read — the shape declaring it and the value\n * shape it points at.\n */\n shapes: Set<string>;\n /** `false` when the query is bound to subjects (`.for` / `.forAll` / a resolved context). */\n unbound: boolean;\n};\n\nexport type MutationEffects = {\n op: 'create' | 'update' | 'upsert' | 'delete';\n /** Routing shape IRI. */\n shape: string;\n /** Predicates written (nested node descriptions and add/remove relations included); for delete: every predicate of the shape. */\n props: Set<string>;\n /**\n * Affected node ids: the target id(s), nested created nodes, removed references, and every\n * `id` found anywhere in `result` (conservative: a reference echoed in the result counts).\n * `undefined` = unknown (`update_where`, `delete_all`, `delete_where`).\n */\n ids?: Set<string>;\n /** Shapes whose instance set may have changed: the target shape for create/upsert/delete + shapes of nested created nodes; empty for a plain update. */\n membership: Set<string>;\n};\n\n// ---------------------------------------------------------------------------\n// Predicate resolution\n// ---------------------------------------------------------------------------\n\n/**\n * The predicate IRI(s) a property-shape id reads or writes.\n *\n * An inline `pathExpr` wins (it IS the path). Otherwise the registered property\n * shape's `sh:path`: a simple path is one predicate, a structured path every IRI\n * it mentions. An unknown id falls back to the id itself — never empty, so a\n * dependency is never silently dropped.\n */\nfunction predicatesOf(propertyShapeId: string, pathExpr?: PathExpr): string[] {\n if (pathExpr) {\n const uris = collectPathUris(pathExpr);\n return uris.length ? uris : [propertyShapeId];\n }\n const propertyShape = findPropertyShapeById(propertyShapeId);\n if (!propertyShape) return [propertyShapeId];\n const simple = getSimplePathId(propertyShape.path);\n if (simple !== null) return [simple];\n const uris = collectPathUris(propertyShape.path);\n return uris.length ? uris : [propertyShapeId];\n}\n\n/** The value shape a property-shape id points at, if it is an object property. */\nfunction valueShapeOf(propertyShapeId: string): string | undefined {\n return findPropertyShapeById(propertyShapeId)?.valueShape?.id;\n}\n\n// Owner lookups, cached on the same terms as `findPropertyShapeById`: successful\n// resolutions only, invalidated by the registry version.\nconst declaringShapeCache = new Map<string, string>();\nlet declaringShapeCacheVersion = -1;\n\n/**\n * The node shape that declares a property shape as its own.\n *\n * Reading a property pins the query to the shape it is declared on, even when the\n * IR carries no scan for it: `p.friends.as(Employee).employeeId` lowers to a plain\n * traversal plus a property read — the cast is type-level only — and the only\n * trace of `Employee` left is that `employeeId` is declared there.\n */\nfunction declaringShapeOf(propertyShapeId: string): string | undefined {\n const version = getRegistryVersion();\n if (version !== declaringShapeCacheVersion) {\n declaringShapeCache.clear();\n declaringShapeCacheVersion = version;\n }\n const cached = declaringShapeCache.get(propertyShapeId);\n if (cached) return cached;\n for (const nodeShape of getAllNodeShapes().values()) {\n if (getPropertyShapes(nodeShape, false).some((ps) => ps.id === propertyShapeId)) {\n declaringShapeCache.set(propertyShapeId, nodeShape.id);\n return nodeShape.id;\n }\n }\n return undefined;\n}\n\nconst addAll = (target: Set<string>, values: Iterable<string>): void => {\n for (const v of values) target.add(v);\n};\n\n// ---------------------------------------------------------------------------\n// queryDependencies\n// ---------------------------------------------------------------------------\n\ntype TraverseInfo = {\n pattern: IRTraversePattern;\n /** Sits under a `minus` / `exists` pattern: its predicates decide membership. */\n inFilter: boolean;\n};\n\nclass DependencyCollector {\n readonly deps: QueryDependencies = {\n narrow: new Set(),\n filter: new Set(),\n hidden: new Set(),\n shapes: new Set(),\n unbound: true,\n };\n /** Every traverse, keyed by the alias it binds. */\n private readonly traverseByTo = new Map<string, TraverseInfo>();\n /** Traverses whose predicates were attributed to a set by a projection or a filter. */\n private readonly reached = new Set<IRTraversePattern>();\n /** Filter expressions found while walking patterns, with the alias their scope starts at. */\n private readonly scopedFilters: {expr: IRExpression; scope?: string}[] = [];\n\n // --- pass 1: patterns -------------------------------------------------------\n\n walkPattern(pattern: IRGraphPattern, inFilter: boolean): void {\n switch (pattern.kind) {\n case 'shape_scan':\n this.deps.shapes.add(pattern.shape);\n return;\n case 'traverse': {\n this.traverseByTo.set(pattern.to, {pattern, inFilter});\n this.recordShapesOf(pattern.property);\n if (pattern.filter) {\n // A scoped where (`t.members.where(m => …)`) decides which related rows\n // take part; its chain stops at the traversal it scopes, whose own\n // predicate is attributed wherever that traversal lands.\n this.scopedFilters.push({expr: pattern.filter, scope: pattern.to});\n }\n for (const order of pattern.innerOrderBy ?? []) {\n addAll(this.deps.filter, predicatesOf(order.property));\n }\n return;\n }\n case 'join':\n for (const p of pattern.patterns) this.walkPattern(p, inFilter);\n return;\n case 'optional':\n this.walkPattern(pattern.pattern, inFilter);\n return;\n case 'union':\n for (const p of pattern.branches) this.walkPattern(p, inFilter);\n return;\n case 'exists':\n this.walkPattern(pattern.pattern, true);\n return;\n case 'minus':\n this.walkPattern(pattern.pattern, true);\n if (pattern.filter) this.scopedFilters.push({expr: pattern.filter});\n return;\n }\n }\n\n // --- pass 2: attribution -----------------------------------------------------\n\n /**\n * The predicates of every traversal from `alias` back towards the root, stopping\n * before `stopAt` when given. Marks each traversal as reached.\n */\n chain(alias: string, stopAt?: string): string[] {\n const preds: string[] = [];\n const visited = new Set<string>();\n let current = alias;\n while (current !== stopAt && !visited.has(current)) {\n visited.add(current);\n const info = this.traverseByTo.get(current);\n if (!info) break;\n this.reached.add(info.pattern);\n preds.push(...predicatesOf(info.pattern.property, info.pattern.pathExpr));\n current = info.pattern.from;\n }\n return preds;\n }\n\n /** The shapes a property read pins the query to: its declaring shape and its value shape. */\n private recordShapesOf(propertyShapeId: string): void {\n const declaring = declaringShapeOf(propertyShapeId);\n if (declaring) this.deps.shapes.add(declaring);\n const valueShape = valueShapeOf(propertyShapeId);\n if (valueShape) this.deps.shapes.add(valueShape);\n }\n\n private propertyExprPredicates(expr: IRPropertyExpression, scope?: string): string[] {\n this.recordShapesOf(expr.property);\n return [...predicatesOf(expr.property, expr.pathExpr), ...this.chain(expr.sourceAlias, scope)];\n }\n\n /** Every predicate an expression decides membership or order by. */\n collectFilter(expr: IRExpression, scope?: string): void {\n switch (expr.kind) {\n case 'property_expr':\n addAll(this.deps.filter, this.propertyExprPredicates(expr, scope));\n return;\n case 'context_property_expr':\n addAll(this.deps.filter, predicatesOf(expr.property));\n return;\n case 'alias_expr':\n addAll(this.deps.filter, this.chain(expr.alias, scope));\n return;\n case 'exists_expr':\n this.walkPattern(expr.pattern, true);\n if (expr.filter) this.collectFilter(expr.filter, scope);\n return;\n default:\n for (const child of childExpressions(expr)) this.collectFilter(child, scope);\n }\n }\n\n /** A projected expression: plain paths are narrow, computed values hidden. */\n collectProjection(expr: IRExpression): void {\n switch (expr.kind) {\n case 'property_expr':\n addAll(this.deps.narrow, this.propertyExprPredicates(expr));\n return;\n case 'alias_expr':\n addAll(this.deps.narrow, this.chain(expr.alias));\n return;\n default:\n this.collectHidden(expr);\n }\n }\n\n private collectHidden(expr: IRExpression): void {\n switch (expr.kind) {\n case 'property_expr':\n addAll(this.deps.hidden, this.propertyExprPredicates(expr));\n return;\n case 'alias_expr':\n addAll(this.deps.hidden, this.chain(expr.alias));\n return;\n case 'context_property_expr':\n addAll(this.deps.filter, predicatesOf(expr.property));\n return;\n case 'exists_expr':\n this.collectFilter(expr);\n return;\n default:\n for (const child of childExpressions(expr)) this.collectHidden(child);\n }\n }\n\n /** Filters gathered while walking patterns (scoped where, minus filter). */\n flushScopedFilters(): void {\n // `collectFilter` on an exists expression may walk new patterns and push new\n // scoped filters, so drain until stable.\n while (this.scopedFilters.length) {\n const {expr, scope} = this.scopedFilters.shift()!;\n this.collectFilter(expr, scope);\n }\n }\n\n /** Traversals no projection or filter attributed: read, but their ids never surface. */\n attributeUnreached(): void {\n for (const {pattern, inFilter} of this.traverseByTo.values()) {\n if (this.reached.has(pattern)) continue;\n const target = inFilter ? this.deps.filter : this.deps.hidden;\n addAll(target, predicatesOf(pattern.property, pattern.pathExpr));\n // The traversal leading up to it is read on the same terms.\n addAll(target, this.chain(pattern.from));\n }\n }\n}\n\n/** The immediate sub-expressions of a compound expression (none for leaves). */\nfunction childExpressions(expr: IRExpression): IRExpression[] {\n switch (expr.kind) {\n case 'binary_expr':\n return [expr.left, expr.right];\n case 'logical_expr':\n return expr.expressions;\n case 'not_expr':\n return [expr.expression];\n case 'function_expr':\n case 'aggregate_expr':\n return expr.args;\n case 'in_expr':\n return [expr.value, ...expr.source.list];\n default:\n return [];\n }\n}\n\n/** `lower()` is overloaded per builder kind; dispatch on the discriminator. */\nfunction lowerQuery(\n query: LowerableSelect | LowerableCount | LowerableAsk,\n): IRSelectQuery | IRCountQuery | IRAskQuery {\n switch (query.__queryKind) {\n case 'select':\n return lower(query);\n case 'count':\n return lower(query);\n case 'ask':\n return lower(query);\n }\n}\n\nfunction isBound(ir: {subjectId?: string; subjectIds?: string[]}): boolean {\n return !!(ir.subjectId || (ir.subjectIds && ir.subjectIds.length));\n}\n\n/**\n * What a query reads, as predicate IRIs and shape IRIs.\n *\n * - `narrow`: read on nodes whose ids are in the result (root rows and projected\n * relation rows) — a change to one of these on a visible node changes the result.\n * - `filter`: decide which nodes are in the result and in what order.\n * - `hidden`: read on nodes the result does not identify (counted relations,\n * computed values over traversals), so a change there can only be matched by\n * predicate, not by id.\n * - `shapes`: every shape whose instance set the query scans or traverses into.\n * - `unbound`: `true` unless the query is pinned to known subjects.\n */\nexport function queryDependencies(\n query: LowerableSelect | LowerableCount | LowerableAsk,\n): QueryDependencies {\n const ir = lowerQuery(query);\n const collector = new DependencyCollector();\n const deps = collector.deps;\n\n if (!ir.root) {\n // Shapeless ask: no rdf:type constraint, no properties — nothing is read but\n // the subject itself.\n deps.unbound = !ir.subjectId;\n return deps;\n }\n\n collector.walkPattern(ir.root, false);\n for (const pattern of ir.patterns) collector.walkPattern(pattern, false);\n\n if (ir.kind === 'select') {\n for (const item of ir.projection) collector.collectProjection(item.expression);\n }\n if (ir.where) collector.collectFilter(ir.where);\n if (ir.kind === 'select') {\n for (const order of ir.orderBy ?? []) collector.collectFilter(order.expression);\n }\n collector.flushScopedFilters();\n collector.attributeUnreached();\n\n deps.unbound = !isBound(ir);\n return deps;\n}\n\n// ---------------------------------------------------------------------------\n// mutationEffects\n// ---------------------------------------------------------------------------\n\nconst isNodeData = (value: unknown): value is IRNodeData =>\n !!value && typeof value === 'object' && 'fields' in value && 'shape' in value;\n\nconst isSetModification = (value: unknown): value is {add?: IRFieldValue[]; remove?: {id: string}[]} =>\n !!value && typeof value === 'object' && ('add' in value || 'remove' in value) && !('kind' in value);\n\nclass EffectCollector {\n readonly props = new Set<string>();\n readonly ids = new Set<string>();\n readonly membership = new Set<string>();\n\n /** Every field at every depth writes its predicate; nested nodes may be created. */\n walkNodeData(data: IRNodeData, nested: boolean): void {\n if (nested) {\n this.membership.add(data.shape);\n if (data.id) this.ids.add(data.id);\n } else if (data.id) {\n this.ids.add(data.id);\n }\n for (const field of data.fields) {\n addAll(this.props, predicatesOf(field.property));\n this.walkValue(field.value);\n }\n }\n\n private walkValue(value: IRFieldValue): void {\n if (value === null || value === undefined) return;\n if (Array.isArray(value)) {\n for (const item of value) this.walkValue(item);\n return;\n }\n if (typeof value !== 'object' || value instanceof Date) return;\n if (isNodeData(value)) {\n this.walkNodeData(value, true);\n return;\n }\n if (isSetModification(value)) {\n for (const item of value.add ?? []) this.walkValue(item);\n for (const ref of value.remove ?? []) {\n if (ref?.id) this.ids.add(ref.id);\n }\n return;\n }\n // A `{id}` reference or an expression: neither writes a predicate of its own,\n // and a referenced node is not itself modified.\n }\n\n /** Every string under a key named `id`, anywhere in a store result. */\n walkResult(value: unknown, seen = new Set<object>()): void {\n if (!value || typeof value !== 'object' || value instanceof Date) return;\n if (seen.has(value)) return;\n seen.add(value);\n if (Array.isArray(value)) {\n for (const item of value) this.walkResult(item, seen);\n return;\n }\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n if (key === 'id' && typeof child === 'string') this.ids.add(child);\n else this.walkResult(child, seen);\n }\n }\n}\n\n/** `lower()` is overloaded per builder kind; dispatch on the discriminator. */\nfunction lowerMutation(\n mutation: LowerableCreate | LowerableUpdate | LowerableDelete,\n): IRCreateQuery | IRUpdateQuery | IRDeleteQuery {\n switch (mutation.__queryKind) {\n case 'create':\n return lower(mutation);\n case 'update':\n return lower(mutation);\n case 'delete':\n return lower(mutation);\n }\n}\n\n/** The shape metadata for a shape IRI, class-backed or data-only. */\nfunction resolveShapeData(shapeId: string): NodeShapeData | undefined {\n return getShapeClass(shapeId)?.shape ?? getNodeShape(shapeId);\n}\n\n/**\n * What a mutation writes, as predicate IRIs, affected node ids and the shapes\n * whose instance sets may have changed.\n *\n * `result` — what the store returned — is optional and only widens `ids`: a create\n * learns its generated id from it, and an add/remove learns the ids of nested\n * creates. It is never consulted for an op whose target set is unknown\n * (`update_where`, `delete_all`, `delete_where`), where `ids` stays `undefined`.\n */\nexport function mutationEffects(\n mutation: LowerableCreate | LowerableUpdate | LowerableDelete,\n result?: unknown,\n): MutationEffects {\n const ir = lowerMutation(mutation);\n const collector = new EffectCollector();\n\n switch (ir.kind) {\n case 'create': {\n collector.membership.add(ir.shape);\n collector.walkNodeData(ir.data, false);\n collector.walkResult(result);\n return {\n op: 'create',\n shape: ir.shape,\n props: collector.props,\n ids: collector.ids,\n membership: collector.membership,\n };\n }\n case 'update':\n case 'upsert': {\n if (ir.kind === 'upsert') collector.membership.add(ir.shape);\n collector.ids.add(ir.id);\n collector.walkNodeData(ir.data, false);\n collector.walkResult(result);\n return {\n op: ir.kind,\n shape: ir.shape,\n props: collector.props,\n ids: collector.ids,\n membership: collector.membership,\n };\n }\n case 'update_where': {\n collector.walkNodeData(ir.data, false);\n return {\n op: 'update',\n shape: ir.shape,\n props: collector.props,\n ids: undefined,\n membership: collector.membership,\n };\n }\n case 'delete':\n case 'delete_all':\n case 'delete_where': {\n collector.membership.add(ir.shape);\n const shapeData = resolveShapeData(ir.shape);\n if (shapeData) {\n for (const ps of getPropertyShapes(shapeData, true)) {\n addAll(collector.props, predicatesOf(ps.id));\n }\n }\n if (ir.kind === 'delete') {\n for (const ref of ir.ids) {\n if (ref?.id) collector.ids.add(ref.id);\n }\n collector.walkResult(result);\n }\n return {\n op: 'delete',\n shape: ir.shape,\n props: collector.props,\n ids: ir.kind === 'delete' ? collector.ids : undefined,\n membership: collector.membership,\n };\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"queryDependencies.js","sourceRoot":"","sources":["../../../src/queries/queryDependencies.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAC,KAAK,EAAC,MAAM,YAAY,CAAC;AACjC,OAAO,EAAC,aAAa,EAAC,MAAM,2BAA2B,CAAC;AAwBxD,OAAO,EAAC,eAAe,EAAC,MAAM,mCAAmC,CAAC;AAClE,OAAO,EAAC,eAAe,EAAC,MAAM,8BAA8B,CAAC;AAC7D,OAAO,EACL,qBAAqB,EACrB,iBAAiB,GAElB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,gBAAgB,EAChB,YAAY,EACZ,SAAS,EACT,qBAAqB,EACrB,gBAAgB,EAChB,aAAa,GACd,MAAM,wBAAwB,CAAC;AA0ChC,8EAA8E;AAC9E,uBAAuB;AACvB,8EAA8E;AAE9E;;;;;;;GAOG;AACH,SAAS,YAAY,CAAC,eAAuB,EAAE,QAAmB;IAChE,IAAI,QAAQ,EAAE,CAAC;QACb,MAAM,IAAI,GAAG,eAAe,CAAC,QAAQ,CAAC,CAAC;QACvC,OAA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AAH,GAAG,CAAE,EAAE;wBAAE,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;gBACzC,CAAC;gBACD,SAAS,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;YAC/B,CAAC;YACD,OAAO;gBACL,EAAE,EAAE,QAAQ;gBACZ,KAAK,EAAE,EAAE,CAAC,KAAK;gBACf,KAAK,EAAE,SAAS,CAAC,KAAK;gBACtB,GAAG,EAAE,EAAE,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS;gBACrD,UAAU,EAAE,SAAS,CAAC,UAAU;aACjC,CAAC;QACJ,CAAC;IACH,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 * Dependency helpers for live queries.\n *\n * Two pure functions that describe, in terms of **predicate IRIs**, what a query\n * reads ({@link queryDependencies}) and what a mutation writes\n * ({@link mutationEffects}). A live-query store feeds both into its change matcher:\n * a query is re-run when a mutation writes a predicate the query depends on, on a\n * node the query can see.\n *\n * Both work on the canonical IR (`lower(query)`), where every property is a\n * property-SHAPE id. Each one is resolved to the predicate(s) it is declared with\n * (`sh:path`), so two shapes that share a predicate — `Person.name` and `Team.name`\n * both on `schema:name` — describe the same dependency, and a structured path\n * (`^member`, `knows/name`) contributes every predicate it touches.\n */\nimport {lower} from './lower.js';\nimport {RegistryCache} from '../utils/registryCache.js';\nimport type {\n LowerableAsk,\n LowerableCount,\n LowerableCreate,\n LowerableDelete,\n LowerableSelect,\n LowerableUpdate,\n} from './lower.js';\nimport type {\n IRAskQuery,\n IRCountQuery,\n IRExpression,\n IRFieldValue,\n IRGraphPattern,\n IRNodeData,\n IRPropertyExpression,\n IRSelectQuery,\n IRTraversePattern,\n} from './IntermediateRepresentation.js';\nimport type {IRCreateQuery} from './CreateQuery.js';\nimport type {IRUpdateQuery} from './UpdateQuery.js';\nimport type {IRDeleteQuery} from './DeleteQuery.js';\nimport type {PathExpr} from '../paths/PropertyPathExpr.js';\nimport {getSimplePathId} from '../paths/normalizePropertyPath.js';\nimport {collectPathUris} from '../paths/pathExprToSparql.js';\nimport {\n findPropertyShapeById,\n getPropertyShapes,\n type NodeShapeData,\n} from '../shapes/nodeShapeData.js';\nimport {\n getAllNodeShapes,\n getNodeShape,\n catalogOf,\n getActiveShapeCatalog,\n withShapeCatalog,\n getShapeClass,\n} from '../utils/ShapeClass.js';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport type QueryDependencies = {\n /** Predicates read on nodes whose ids appear in the result (root row + projected relation rows). */\n narrow: Set<string>;\n /** Predicates deciding membership/order: where, scoped where, minus, exists, sortBy, inner orderBy. */\n filter: Set<string>;\n /**\n * Predicates read on nodes whose ids are NOT projected: `size()` / aggregates over\n * relations, computed values over traversals, traversals with no projected id.\n */\n hidden: Set<string>;\n /**\n * Shape IRIs the query is pinned to: the root scan, nested shape scans (minus by\n * shape), and — for every property read — the shape declaring it and the value\n * shape it points at.\n */\n shapes: Set<string>;\n /** `false` when the query is bound to subjects (`.for` / `.forAll` / a resolved context). */\n unbound: boolean;\n};\n\nexport type MutationEffects = {\n op: 'create' | 'update' | 'upsert' | 'delete';\n /** Routing shape IRI. */\n shape: string;\n /** Predicates written (nested node descriptions and add/remove relations included); for delete: every predicate of the shape. */\n props: Set<string>;\n /**\n * Affected node ids: the target id(s), nested created nodes, removed references, and every\n * `id` found anywhere in `result` (conservative: a reference echoed in the result counts).\n * `undefined` = unknown (`update_where`, `delete_all`, `delete_where`).\n */\n ids?: Set<string>;\n /** Shapes whose instance set may have changed: the target shape for create/upsert/delete + shapes of nested created nodes; empty for a plain update. */\n membership: Set<string>;\n};\n\n// ---------------------------------------------------------------------------\n// Predicate resolution\n// ---------------------------------------------------------------------------\n\n/**\n * The predicate IRI(s) a property-shape id reads or writes.\n *\n * An inline `pathExpr` wins (it IS the path). Otherwise the registered property\n * shape's `sh:path`: a simple path is one predicate, a structured path every IRI\n * it mentions. An unknown id falls back to the id itself — never empty, so a\n * dependency is never silently dropped.\n */\nfunction predicatesOf(propertyShapeId: string, pathExpr?: PathExpr): string[] {\n if (pathExpr) {\n const uris = collectPathUris(pathExpr);\n return uris.length ? uris : [propertyShapeId];\n }\n const propertyShape = findPropertyShapeById(propertyShapeId);\n if (!propertyShape) return [propertyShapeId];\n const simple = getSimplePathId(propertyShape.path);\n if (simple !== null) return [simple];\n const uris = collectPathUris(propertyShape.path);\n return uris.length ? uris : [propertyShapeId];\n}\n\n/** The value shape a property-shape id points at, if it is an object property. */\nfunction valueShapeOf(propertyShapeId: string): string | undefined {\n return findPropertyShapeById(propertyShapeId)?.valueShape?.id;\n}\n\n// Owner lookups, cached on the same terms as `findPropertyShapeById`: successful\n// resolutions only, invalidated by the registry version.\nconst declaringShapeCache = new RegistryCache<string, string>();\n\n/**\n * The node shape that declares a property shape as its own.\n *\n * Reading a property pins the query to the shape it is declared on, even when the\n * IR carries no scan for it: `p.friends.as(Employee).employeeId` lowers to a plain\n * traversal plus a property read — the cast is type-level only — and the only\n * trace of `Employee` left is that `employeeId` is declared there.\n */\nfunction declaringShapeOf(propertyShapeId: string): string | undefined {\n const cache = declaringShapeCache.get();\n const cached = cache.get(propertyShapeId);\n if (cached) return cached;\n for (const nodeShape of getAllNodeShapes().values()) {\n if (getPropertyShapes(nodeShape, false).some((ps) => ps.id === propertyShapeId)) {\n cache.set(propertyShapeId, nodeShape.id);\n return nodeShape.id;\n }\n }\n return undefined;\n}\n\nconst addAll = (target: Set<string>, values: Iterable<string>): void => {\n for (const v of values) target.add(v);\n};\n\n// ---------------------------------------------------------------------------\n// queryDependencies\n// ---------------------------------------------------------------------------\n\ntype TraverseInfo = {\n pattern: IRTraversePattern;\n /** Sits under a `minus` / `exists` pattern: its predicates decide membership. */\n inFilter: boolean;\n};\n\nclass DependencyCollector {\n readonly deps: QueryDependencies = {\n narrow: new Set(),\n filter: new Set(),\n hidden: new Set(),\n shapes: new Set(),\n unbound: true,\n };\n /** Every traverse, keyed by the alias it binds. */\n private readonly traverseByTo = new Map<string, TraverseInfo>();\n /** Traverses whose predicates were attributed to a set by a projection or a filter. */\n private readonly reached = new Set<IRTraversePattern>();\n /** Filter expressions found while walking patterns, with the alias their scope starts at. */\n private readonly scopedFilters: {expr: IRExpression; scope?: string}[] = [];\n\n // --- pass 1: patterns -------------------------------------------------------\n\n walkPattern(pattern: IRGraphPattern, inFilter: boolean): void {\n switch (pattern.kind) {\n case 'shape_scan':\n this.deps.shapes.add(pattern.shape);\n return;\n case 'traverse': {\n this.traverseByTo.set(pattern.to, {pattern, inFilter});\n this.recordShapesOf(pattern.property);\n if (pattern.filter) {\n // A scoped where (`t.members.where(m => …)`) decides which related rows\n // take part; its chain stops at the traversal it scopes, whose own\n // predicate is attributed wherever that traversal lands.\n this.scopedFilters.push({expr: pattern.filter, scope: pattern.to});\n }\n for (const order of pattern.innerOrderBy ?? []) {\n addAll(this.deps.filter, predicatesOf(order.property));\n }\n return;\n }\n case 'join':\n for (const p of pattern.patterns) this.walkPattern(p, inFilter);\n return;\n case 'optional':\n this.walkPattern(pattern.pattern, inFilter);\n return;\n case 'union':\n for (const p of pattern.branches) this.walkPattern(p, inFilter);\n return;\n case 'exists':\n this.walkPattern(pattern.pattern, true);\n return;\n case 'minus':\n this.walkPattern(pattern.pattern, true);\n if (pattern.filter) this.scopedFilters.push({expr: pattern.filter});\n return;\n }\n }\n\n // --- pass 2: attribution -----------------------------------------------------\n\n /**\n * The predicates of every traversal from `alias` back towards the root, stopping\n * before `stopAt` when given. Marks each traversal as reached.\n */\n chain(alias: string, stopAt?: string): string[] {\n const preds: string[] = [];\n const visited = new Set<string>();\n let current = alias;\n while (current !== stopAt && !visited.has(current)) {\n visited.add(current);\n const info = this.traverseByTo.get(current);\n if (!info) break;\n this.reached.add(info.pattern);\n preds.push(...predicatesOf(info.pattern.property, info.pattern.pathExpr));\n current = info.pattern.from;\n }\n return preds;\n }\n\n /** The shapes a property read pins the query to: its declaring shape and its value shape. */\n private recordShapesOf(propertyShapeId: string): void {\n const declaring = declaringShapeOf(propertyShapeId);\n if (declaring) this.deps.shapes.add(declaring);\n const valueShape = valueShapeOf(propertyShapeId);\n if (valueShape) this.deps.shapes.add(valueShape);\n }\n\n private propertyExprPredicates(expr: IRPropertyExpression, scope?: string): string[] {\n this.recordShapesOf(expr.property);\n return [...predicatesOf(expr.property, expr.pathExpr), ...this.chain(expr.sourceAlias, scope)];\n }\n\n /** Every predicate an expression decides membership or order by. */\n collectFilter(expr: IRExpression, scope?: string): void {\n switch (expr.kind) {\n case 'property_expr':\n addAll(this.deps.filter, this.propertyExprPredicates(expr, scope));\n return;\n case 'context_property_expr':\n addAll(this.deps.filter, predicatesOf(expr.property));\n return;\n case 'alias_expr':\n addAll(this.deps.filter, this.chain(expr.alias, scope));\n return;\n case 'exists_expr':\n this.walkPattern(expr.pattern, true);\n if (expr.filter) this.collectFilter(expr.filter, scope);\n return;\n default:\n for (const child of childExpressions(expr)) this.collectFilter(child, scope);\n }\n }\n\n /** A projected expression: plain paths are narrow, computed values hidden. */\n collectProjection(expr: IRExpression): void {\n switch (expr.kind) {\n case 'property_expr':\n addAll(this.deps.narrow, this.propertyExprPredicates(expr));\n return;\n case 'alias_expr':\n addAll(this.deps.narrow, this.chain(expr.alias));\n return;\n default:\n this.collectHidden(expr);\n }\n }\n\n private collectHidden(expr: IRExpression): void {\n switch (expr.kind) {\n case 'property_expr':\n addAll(this.deps.hidden, this.propertyExprPredicates(expr));\n return;\n case 'alias_expr':\n addAll(this.deps.hidden, this.chain(expr.alias));\n return;\n case 'context_property_expr':\n addAll(this.deps.filter, predicatesOf(expr.property));\n return;\n case 'exists_expr':\n this.collectFilter(expr);\n return;\n default:\n for (const child of childExpressions(expr)) this.collectHidden(child);\n }\n }\n\n /** Filters gathered while walking patterns (scoped where, minus filter). */\n flushScopedFilters(): void {\n // `collectFilter` on an exists expression may walk new patterns and push new\n // scoped filters, so drain until stable.\n while (this.scopedFilters.length) {\n const {expr, scope} = this.scopedFilters.shift()!;\n this.collectFilter(expr, scope);\n }\n }\n\n /** Traversals no projection or filter attributed: read, but their ids never surface. */\n attributeUnreached(): void {\n for (const {pattern, inFilter} of this.traverseByTo.values()) {\n if (this.reached.has(pattern)) continue;\n const target = inFilter ? this.deps.filter : this.deps.hidden;\n addAll(target, predicatesOf(pattern.property, pattern.pathExpr));\n // The traversal leading up to it is read on the same terms.\n addAll(target, this.chain(pattern.from));\n }\n }\n}\n\n/** The immediate sub-expressions of a compound expression (none for leaves). */\nfunction childExpressions(expr: IRExpression): IRExpression[] {\n switch (expr.kind) {\n case 'binary_expr':\n return [expr.left, expr.right];\n case 'logical_expr':\n return expr.expressions;\n case 'not_expr':\n return [expr.expression];\n case 'function_expr':\n case 'aggregate_expr':\n return expr.args;\n case 'in_expr':\n return [expr.value, ...expr.source.list];\n default:\n return [];\n }\n}\n\n/** `lower()` is overloaded per builder kind; dispatch on the discriminator. */\nfunction lowerQuery(\n query: LowerableSelect | LowerableCount | LowerableAsk,\n): IRSelectQuery | IRCountQuery | IRAskQuery {\n switch (query.__queryKind) {\n case 'select':\n return lower(query);\n case 'count':\n return lower(query);\n case 'ask':\n return lower(query);\n }\n}\n\nfunction isBound(ir: {subjectId?: string; subjectIds?: string[]}): boolean {\n return !!(ir.subjectId || (ir.subjectIds && ir.subjectIds.length));\n}\n\n/**\n * What a query reads, as predicate IRIs and shape IRIs.\n *\n * - `narrow`: read on nodes whose ids are in the result (root rows and projected\n * relation rows) — a change to one of these on a visible node changes the result.\n * - `filter`: decide which nodes are in the result and in what order.\n * - `hidden`: read on nodes the result does not identify (counted relations,\n * computed values over traversals), so a change there can only be matched by\n * predicate, not by id.\n * - `shapes`: every shape whose instance set the query scans or traverses into.\n * - `unbound`: `true` unless the query is pinned to known subjects.\n */\nexport function queryDependencies(\n query: LowerableSelect | LowerableCount | LowerableAsk,\n): QueryDependencies {\n const catalog = catalogOf(query);\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => queryDependencies(query));\n }\n const ir = lowerQuery(query);\n const collector = new DependencyCollector();\n const deps = collector.deps;\n\n if (!ir.root) {\n // Shapeless ask: no rdf:type constraint, no properties — nothing is read but\n // the subject itself.\n deps.unbound = !ir.subjectId;\n return deps;\n }\n\n collector.walkPattern(ir.root, false);\n for (const pattern of ir.patterns) collector.walkPattern(pattern, false);\n\n if (ir.kind === 'select') {\n for (const item of ir.projection) collector.collectProjection(item.expression);\n }\n if (ir.where) collector.collectFilter(ir.where);\n if (ir.kind === 'select') {\n for (const order of ir.orderBy ?? []) collector.collectFilter(order.expression);\n }\n collector.flushScopedFilters();\n collector.attributeUnreached();\n\n deps.unbound = !isBound(ir);\n return deps;\n}\n\n// ---------------------------------------------------------------------------\n// mutationEffects\n// ---------------------------------------------------------------------------\n\nconst isNodeData = (value: unknown): value is IRNodeData =>\n !!value && typeof value === 'object' && 'fields' in value && 'shape' in value;\n\nconst isSetModification = (value: unknown): value is {add?: IRFieldValue[]; remove?: {id: string}[]} =>\n !!value && typeof value === 'object' && ('add' in value || 'remove' in value) && !('kind' in value);\n\nclass EffectCollector {\n readonly props = new Set<string>();\n readonly ids = new Set<string>();\n readonly membership = new Set<string>();\n\n /** Every field at every depth writes its predicate; nested nodes may be created. */\n walkNodeData(data: IRNodeData, nested: boolean): void {\n if (nested) {\n this.membership.add(data.shape);\n if (data.id) this.ids.add(data.id);\n } else if (data.id) {\n this.ids.add(data.id);\n }\n for (const field of data.fields) {\n addAll(this.props, predicatesOf(field.property));\n this.walkValue(field.value);\n }\n }\n\n private walkValue(value: IRFieldValue): void {\n if (value === null || value === undefined) return;\n if (Array.isArray(value)) {\n for (const item of value) this.walkValue(item);\n return;\n }\n if (typeof value !== 'object' || value instanceof Date) return;\n if (isNodeData(value)) {\n this.walkNodeData(value, true);\n return;\n }\n if (isSetModification(value)) {\n for (const item of value.add ?? []) this.walkValue(item);\n for (const ref of value.remove ?? []) {\n if (ref?.id) this.ids.add(ref.id);\n }\n return;\n }\n // A `{id}` reference or an expression: neither writes a predicate of its own,\n // and a referenced node is not itself modified.\n }\n\n /** Every string under a key named `id`, anywhere in a store result. */\n walkResult(value: unknown, seen = new Set<object>()): void {\n if (!value || typeof value !== 'object' || value instanceof Date) return;\n if (seen.has(value)) return;\n seen.add(value);\n if (Array.isArray(value)) {\n for (const item of value) this.walkResult(item, seen);\n return;\n }\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n if (key === 'id' && typeof child === 'string') this.ids.add(child);\n else this.walkResult(child, seen);\n }\n }\n}\n\n/** `lower()` is overloaded per builder kind; dispatch on the discriminator. */\nfunction lowerMutation(\n mutation: LowerableCreate | LowerableUpdate | LowerableDelete,\n): IRCreateQuery | IRUpdateQuery | IRDeleteQuery {\n switch (mutation.__queryKind) {\n case 'create':\n return lower(mutation);\n case 'update':\n return lower(mutation);\n case 'delete':\n return lower(mutation);\n }\n}\n\n/** The shape metadata for a shape IRI, class-backed or data-only. */\nfunction resolveShapeData(shapeId: string): NodeShapeData | undefined {\n return getShapeClass(shapeId)?.shape ?? getNodeShape(shapeId);\n}\n\n/**\n * What a mutation writes, as predicate IRIs, affected node ids and the shapes\n * whose instance sets may have changed.\n *\n * `result` — what the store returned — is optional and only widens `ids`: a create\n * learns its generated id from it, and an add/remove learns the ids of nested\n * creates. It is never consulted for an op whose target set is unknown\n * (`update_where`, `delete_all`, `delete_where`), where `ids` stays `undefined`.\n */\nexport function mutationEffects(\n mutation: LowerableCreate | LowerableUpdate | LowerableDelete,\n result?: unknown,\n): MutationEffects {\n const catalog = catalogOf(mutation);\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => mutationEffects(mutation, result));\n }\n const ir = lowerMutation(mutation);\n const collector = new EffectCollector();\n\n switch (ir.kind) {\n case 'create': {\n collector.membership.add(ir.shape);\n collector.walkNodeData(ir.data, false);\n collector.walkResult(result);\n return {\n op: 'create',\n shape: ir.shape,\n props: collector.props,\n ids: collector.ids,\n membership: collector.membership,\n };\n }\n case 'update':\n case 'upsert': {\n if (ir.kind === 'upsert') collector.membership.add(ir.shape);\n collector.ids.add(ir.id);\n collector.walkNodeData(ir.data, false);\n collector.walkResult(result);\n return {\n op: ir.kind,\n shape: ir.shape,\n props: collector.props,\n ids: collector.ids,\n membership: collector.membership,\n };\n }\n case 'update_where': {\n collector.walkNodeData(ir.data, false);\n return {\n op: 'update',\n shape: ir.shape,\n props: collector.props,\n ids: undefined,\n membership: collector.membership,\n };\n }\n case 'delete':\n case 'delete_all':\n case 'delete_where': {\n collector.membership.add(ir.shape);\n const shapeData = resolveShapeData(ir.shape);\n if (shapeData) {\n for (const ps of getPropertyShapes(shapeData, true)) {\n addAll(collector.props, predicatesOf(ps.id));\n }\n }\n if (ir.kind === 'delete') {\n for (const ref of ir.ids) {\n if (ref?.id) collector.ids.add(ref.id);\n }\n collector.walkResult(result);\n }\n return {\n op: 'delete',\n shape: ir.shape,\n props: collector.props,\n ids: ir.kind === 'delete' ? collector.ids : undefined,\n membership: collector.membership,\n };\n }\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getOrCreateShapeAdapter, getShapeClass } from '../utils/ShapeClass.js';
|
|
1
|
+
import { getActiveShapeCatalog, getOrCreateShapeAdapter, getShapeClass } from '../utils/ShapeClass.js';
|
|
2
2
|
/**
|
|
3
3
|
* Resolve a shape class or IRI string to a ShapeConstructor.
|
|
4
4
|
*
|
|
@@ -8,7 +8,7 @@ import { getOrCreateShapeAdapter, getShapeClass } from '../utils/ShapeClass.js';
|
|
|
8
8
|
* @throws If a string IRI cannot be resolved via the shape registry.
|
|
9
9
|
*/
|
|
10
10
|
export function resolveShape(shape) {
|
|
11
|
-
var _a;
|
|
11
|
+
var _a, _b;
|
|
12
12
|
if (typeof shape === 'string') {
|
|
13
13
|
// An authored class first; otherwise a constructor derived from the registered
|
|
14
14
|
// metadata, so a project-authored shape that exists only as data resolves too.
|
|
@@ -18,6 +18,18 @@ export function resolveShape(shape) {
|
|
|
18
18
|
}
|
|
19
19
|
return shapeClass;
|
|
20
20
|
}
|
|
21
|
+
// Inside a catalog the catalog's data is the authority for every IRI it holds, so an
|
|
22
|
+
// authored class for one of them (CN's compiled `Person` for a project's `Person`)
|
|
23
|
+
// resolves to the catalog's shape. A class the catalog does not hold is kept as is.
|
|
24
|
+
const catalog = getActiveShapeCatalog();
|
|
25
|
+
if (catalog !== undefined) {
|
|
26
|
+
const id = (_b = shape === null || shape === void 0 ? void 0 : shape.shape) === null || _b === void 0 ? void 0 : _b.id;
|
|
27
|
+
if (id && catalog.has(id)) {
|
|
28
|
+
const own = getOrCreateShapeAdapter(id);
|
|
29
|
+
if (own)
|
|
30
|
+
return own;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
21
33
|
return shape;
|
|
22
34
|
}
|
|
23
35
|
//# sourceMappingURL=resolveShape.js.map
|