@_linked/core 2.35.0 → 2.36.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +30 -0
  3. package/lib/esm/index.d.ts +3 -0
  4. package/lib/esm/index.js +4 -0
  5. package/lib/esm/index.js.map +1 -1
  6. package/lib/esm/live/LiveQueryStore.js +2 -1
  7. package/lib/esm/live/LiveQueryStore.js.map +1 -1
  8. package/lib/esm/queries/FieldSet.d.ts +7 -0
  9. package/lib/esm/queries/FieldSet.js +25 -4
  10. package/lib/esm/queries/FieldSet.js.map +1 -1
  11. package/lib/esm/queries/MutationQuery.js +3 -2
  12. package/lib/esm/queries/MutationQuery.js.map +1 -1
  13. package/lib/esm/queries/PropertyPath.js +2 -1
  14. package/lib/esm/queries/PropertyPath.js.map +1 -1
  15. package/lib/esm/queries/QueryBuilder.js +2 -1
  16. package/lib/esm/queries/QueryBuilder.js.map +1 -1
  17. package/lib/esm/queries/QueryContext.js +2 -0
  18. package/lib/esm/queries/QueryContext.js.map +1 -1
  19. package/lib/esm/queries/SelectQuery.js +6 -1
  20. package/lib/esm/queries/SelectQuery.js.map +1 -1
  21. package/lib/esm/queries/resolveShape.js +2 -1
  22. package/lib/esm/queries/resolveShape.js.map +1 -1
  23. package/lib/esm/shapes/validation.js +9 -4
  24. package/lib/esm/shapes/validation.js.map +1 -1
  25. package/lib/esm/utils/linkedError.d.ts +35 -0
  26. package/lib/esm/utils/linkedError.js +52 -0
  27. package/lib/esm/utils/linkedError.js.map +1 -0
  28. package/lib/esm/utils/sharedState.d.ts +25 -0
  29. package/lib/esm/utils/sharedState.js +34 -0
  30. package/lib/esm/utils/sharedState.js.map +1 -0
  31. package/lib/esm/utils/unresolvedShape.d.ts +44 -0
  32. package/lib/esm/utils/unresolvedShape.js +68 -0
  33. package/lib/esm/utils/unresolvedShape.js.map +1 -0
  34. package/package.json +1 -1
@@ -1 +1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AAI,CACF,WAA0E,EAC1E,UAAuE;QAEvE,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;IACnD,CAAC;IAED,2EAA2E;IAC3E,KAAK,CACH,UAAqE;QAErE,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACvC,CAAC;IAED,+EAA+E;IAC/E,OAAO,CAAC,SAA+B;QACrC,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACxC,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC;QACtB,OAAO,eAAe,CAAC;IACzB,CAAC;CACF;AAED,4FAA4F;AAC5F,OAAO,EAAC,aAAa,IAAI,YAAY,EAAC,CAAC","sourcesContent":["import {Shape, type ShapeConstructor} from '../shapes/Shape.js';\nimport {getUniquePropertyShapes} from '../shapes/nodeShapeData.js';\nimport {resolveShape} from './resolveShape.js';\nimport {\n type QueryBuildFn,\n type WhereClause,\n type QResult,\n type QueryResponseToResultType,\n type SelectAllQueryResponse,\n type QueryComponentLike,\n processWhereClause,\n evaluateSortCallback,\n} from './SelectQuery.js';\nimport type {SortByPath, WherePath} from './SelectQuery.js';\nimport type {PropertyPathSegment, RawMinusEntry, RawSelectInput} from './IRDesugar.js';\nimport {WIRE_VERSION, assertWireVersion} from './wireVersion.js';\nimport {getQueryDispatch} from './queryDispatch.js';\nimport {AskBuilder} from './AskBuilder.js';\nimport {CountBuilder} from './CountBuilder.js';\nimport type {IDataset} from '../interfaces/IDataset.js';\nimport type {NodeShapeData} from '../shapes/SHACL.js';\nimport type {NodeReferenceValue} from './QueryFactory.js';\nimport {resolveUriOrThrow} from '../utils/NodeReference.js';\nimport {FieldSet, type FieldSetFieldJSON, type FieldSetEntry} from './FieldSet.js';\nimport {PendingQueryContext, UnresolvedContextError} from './QueryContext.js';\nimport {encodeContextRef, isContextRefJSON, type ContextRefJSON} from './ContextRef.js';\nimport {createProxiedPathBuilder} from './ProxiedPathBuilder.js';\nimport {\n serializeWherePath,\n serializeSortByPath,\n serializeRawMinusEntry,\n deserializeWherePath,\n deserializeSortByPath,\n deserializeRawMinusEntry,\n type WherePathJSON,\n type SortByPathJSON,\n type RawMinusEntryJSON,\n} from './QueryBuilderSerialization.js';\nimport {requireLiveQueryStore} from '../live/registry.js';\nimport {captureCatalog, getActiveShapeCatalog, withShapeCatalog} from '../utils/ShapeClass.js';\nimport type {ShapeCatalog} from '../utils/ShapeCatalog.js';\nimport type {LiveListener, LiveQuery, LiveQueryOptions} from '../live/LiveQueryStore.js';\n\n/** JSON representation of a SelectBuilder. */\nexport type QueryBuilderJSON = {\n /** DSL-JSON wire-format version. */\n v?: string;\n shape: string;\n fields?: FieldSetFieldJSON[];\n limit?: number;\n offset?: number;\n /** A node id, or a `{@ctx: name}` context reference resolved at lowering. */\n subject?: string | ContextRefJSON;\n subjects?: string[];\n /** `.one()` — unwrap a single result. */\n one?: boolean;\n where?: WherePathJSON;\n sortBy?: SortByPathJSON;\n minusEntries?: RawMinusEntryJSON[];\n nullSubject?: boolean;\n};\n\n/** A preload entry binding a property path to a component's query. */\ninterface PreloadEntry {\n path: string;\n component: QueryComponentLike<any, any>;\n}\n\n/** A MINUS entry — either a shape type exclusion or a WHERE-clause condition. */\ninterface MinusEntry<S extends Shape> {\n shapeId?: string;\n whereFn?: WhereClause<S>;\n}\n\n/** Internal state bag for SelectBuilder. */\ninterface QueryBuilderInit<S extends Shape, R> {\n shape: ShapeConstructor<S>;\n /** The catalog the builder resolves in; absent = captured from the active one. */\n catalog?: ShapeCatalog;\n selectFn?: QueryBuildFn<S, R>;\n whereFn?: WhereClause<S>;\n sortByFn?: QueryBuildFn<S, any>;\n sortDirection?: 'ASC' | 'DESC';\n limit?: number;\n offset?: number;\n subject?: S | QResult<S> | NodeReferenceValue;\n subjects?: NodeReferenceValue[];\n singleResult?: boolean;\n selectAllLabels?: string[];\n fieldSet?: FieldSet;\n preloads?: PreloadEntry[];\n minusEntries?: MinusEntry<S>[];\n _nullSubject?: boolean;\n _pendingContextName?: string;\n // Pre-evaluated data (restored from JSON; used when callbacks are not available)\n _where?: WherePath;\n _sortBy?: SortByPath;\n _rawMinusEntries?: RawMinusEntry[];\n}\n\n/**\n * An immutable, fluent query builder for select queries.\n *\n * Every mutation method (`.select()`, `.where()`, `.limit()`, etc.) returns\n * a **new** SelectBuilder instance — the original is never modified.\n *\n * Implements `PromiseLike` so queries execute on `await`:\n * ```ts\n * const results = await SelectBuilder.from(Person).select(p => p.name);\n * ```\n *\n * Produces a raw select input (`toRawInput()`) that the free `lower()` function\n * turns into IR; the builder itself carries no dependency on the IR pipeline.\n */\nexport class SelectBuilder<S extends Shape = Shape, R = any, Result = any>\n implements PromiseLike<Result>, Promise<Result>\n{\n private readonly _shape: ShapeConstructor<S>;\n private readonly _selectFn?: QueryBuildFn<S, R>;\n private readonly _whereFn?: WhereClause<S>;\n private readonly _sortByFn?: QueryBuildFn<S, any>;\n private readonly _sortDirection?: 'ASC' | 'DESC';\n private readonly _limit?: number;\n private readonly _offset?: number;\n private readonly _subject?: S | QResult<S> | NodeReferenceValue;\n private readonly _subjects?: NodeReferenceValue[];\n private readonly _singleResult?: boolean;\n private readonly _selectAllLabels?: string[];\n private readonly _fieldSet?: FieldSet;\n private readonly _preloads?: PreloadEntry[];\n private readonly _minusEntries?: MinusEntry<S>[];\n private readonly _nullSubject?: boolean;\n private readonly _pendingContextName?: string;\n // Pre-evaluated data (restored from JSON; used when callbacks are not available)\n private readonly _where?: WherePath;\n private readonly _sortBy?: SortByPath;\n private readonly _rawMinusEntries?: RawMinusEntry[];\n private readonly _catalog: ShapeCatalog | undefined;\n\n private constructor(init: QueryBuilderInit<S, R>) {\n this._shape = init.shape;\n this._catalog = 'catalog' in init ? init.catalog : captureCatalog(init.shape);\n this._selectFn = init.selectFn;\n this._whereFn = init.whereFn;\n this._sortByFn = init.sortByFn;\n this._sortDirection = init.sortDirection;\n this._limit = init.limit;\n this._offset = init.offset;\n this._subject = init.subject;\n this._subjects = init.subjects;\n this._singleResult = init.singleResult;\n this._selectAllLabels = init.selectAllLabels;\n this._fieldSet = init.fieldSet;\n this._preloads = init.preloads;\n this._minusEntries = init.minusEntries;\n this._nullSubject = init._nullSubject;\n this._pendingContextName = init._pendingContextName;\n this._where = init._where;\n this._sortBy = init._sortBy;\n this._rawMinusEntries = init._rawMinusEntries;\n }\n\n /** Create a shallow clone with overrides. */\n private clone<NR = R, NResult = Result>(overrides: Partial<QueryBuilderInit<S, any>> = {}): SelectBuilder<S, NR, NResult> {\n return new SelectBuilder<S, NR, NResult>({\n shape: this._shape,\n selectFn: this._selectFn as any,\n whereFn: this._whereFn,\n sortByFn: this._sortByFn,\n sortDirection: this._sortDirection,\n limit: this._limit,\n offset: this._offset,\n subject: this._subject,\n subjects: this._subjects,\n singleResult: this._singleResult,\n selectAllLabels: this._selectAllLabels,\n fieldSet: this._fieldSet,\n preloads: this._preloads,\n minusEntries: this._minusEntries,\n _nullSubject: this._nullSubject,\n _pendingContextName: this._pendingContextName,\n _where: this._where,\n _sortBy: this._sortBy,\n _rawMinusEntries: this._rawMinusEntries,\n catalog: this._catalog,\n ...overrides,\n });\n }\n\n // ---------------------------------------------------------------------------\n // Static constructors\n // ---------------------------------------------------------------------------\n\n /**\n * Create a SelectBuilder for the given shape.\n *\n * Accepts a shape class (e.g. `Person`), a NodeShapeData instance,\n * or a shape IRI string (resolved via the shape registry).\n */\n static from<S extends Shape>(\n shape: ShapeConstructor<S> | string,\n ): SelectBuilder<S> {\n const resolved = resolveShape<S>(shape);\n return new SelectBuilder<S>({shape: resolved});\n }\n\n // ---------------------------------------------------------------------------\n // Fluent API — each returns a new instance\n // ---------------------------------------------------------------------------\n\n /** Set the select projection via a callback, labels, or FieldSet. */\n select<NewR>(fn: QueryBuildFn<S, NewR>): SelectBuilder<S, NewR, QueryResponseToResultType<NewR, S>[]>;\n select(labels: string[]): SelectBuilder<S>;\n select<NewR>(fieldSet: FieldSet<NewR>): SelectBuilder<S, NewR, QueryResponseToResultType<NewR, S>[]>;\n select<NewR = R>(fnOrLabelsOrFieldSet: QueryBuildFn<S, NewR> | string[] | FieldSet<any>): SelectBuilder<S, NewR, any> {\n if (fnOrLabelsOrFieldSet instanceof FieldSet) {\n const labels = fnOrLabelsOrFieldSet.labels();\n const selectFn = ((p: any) =>\n labels.map((label) => p[label])) as unknown as QueryBuildFn<S, any>;\n return this.clone<NewR, any>({selectFn, selectAllLabels: undefined, fieldSet: fnOrLabelsOrFieldSet});\n }\n if (Array.isArray(fnOrLabelsOrFieldSet)) {\n const labels = fnOrLabelsOrFieldSet;\n const selectFn = ((p: any) =>\n labels.map((label) => p[label])) as unknown as QueryBuildFn<S, any>;\n return this.clone<NewR, any>({selectFn, selectAllLabels: undefined, fieldSet: undefined});\n }\n return this.clone<NewR, any>({selectFn: fnOrLabelsOrFieldSet as any, selectAllLabels: undefined, fieldSet: undefined});\n }\n\n /** Select all decorated properties of the shape. */\n selectAll(): SelectBuilder<S, any, QueryResponseToResultType<SelectAllQueryResponse<S>, S>[]> {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.selectAll());\n }\n const propertyLabels = getUniquePropertyShapes(this._shape.shape)\n .map((ps) => ps.label);\n const selectFn = ((p: any) =>\n propertyLabels.map((label) => p[label])) as unknown as QueryBuildFn<S, any>;\n return this.clone({selectFn, selectAllLabels: propertyLabels});\n }\n\n /** Add a where clause. */\n where(fn: WhereClause<S>): SelectBuilder<S, R, Result> {\n return this.clone({whereFn: fn});\n }\n\n /**\n * Exclude results matching a MINUS pattern.\n *\n * Accepts:\n * - A shape constructor to exclude by type: `.minus(Employee)`\n * - A WHERE callback to exclude by condition: `.minus(p => p.hobby.equals('Chess'))`\n * - A callback returning a property or array of properties for existence exclusion:\n * `.minus(p => p.hobby)` or `.minus(p => [p.hobby, p.bestFriend.name])`\n *\n * Chainable: `.minus(A).minus(B)` produces two separate `MINUS { }` blocks.\n */\n minus(shapeOrFn: ShapeConstructor<any> | WhereClause<S> | ((s: any) => any)): SelectBuilder<S, R, Result> {\n const entry: MinusEntry<S> = {};\n if (typeof shapeOrFn === 'function' && 'shape' in shapeOrFn) {\n // ShapeConstructor — has a static .shape property\n entry.shapeId = (shapeOrFn as ShapeConstructor<any>).shape?.id;\n } else {\n // WhereClause callback\n entry.whereFn = shapeOrFn as WhereClause<S>;\n }\n const existing = this._minusEntries || [];\n return this.clone({minusEntries: [...existing, entry]});\n }\n\n /** Set sort order. */\n orderBy<OR>(fn: QueryBuildFn<S, OR>, direction: 'ASC' | 'DESC' = 'ASC'): SelectBuilder<S, R, Result> {\n return this.clone({sortByFn: fn as any, sortDirection: direction});\n }\n\n /**\n * @deprecated Use `orderBy()` instead.\n */\n sortBy<OR>(fn: QueryBuildFn<S, OR>, direction: 'ASC' | 'DESC' = 'ASC'): SelectBuilder<S, R, Result> {\n return this.orderBy(fn, direction);\n }\n\n /** Set result limit. */\n limit(n: number): SelectBuilder<S, R, Result> {\n return this.clone({limit: n});\n }\n\n /** Set result offset. */\n offset(n: number): SelectBuilder<S, R, Result> {\n return this.clone({offset: n});\n }\n\n /** Target a single entity by ID. Implies singleResult; unwraps array Result type. */\n for(id: string | NodeReferenceValue | PendingQueryContext | null | undefined): SelectBuilder<S, R, Result extends (infer E)[] ? E : Result> {\n if (id instanceof PendingQueryContext) {\n // Store the pending context as subject — its .id getter resolves lazily\n // from the global context map when the query is lowered/serialized.\n return this.clone({subject: id as any, subjects: undefined, singleResult: true, _nullSubject: false, _pendingContextName: id.contextName}) as any;\n }\n if (id == null) {\n // Return a builder that resolves to null when executed (no subject = no query).\n // This commonly happens when getQueryContext() returns null before the user is authenticated.\n return this.clone({subject: undefined, subjects: undefined, singleResult: true, _nullSubject: true, _pendingContextName: undefined}) as any;\n }\n const subject: NodeReferenceValue = typeof id === 'string' ? {id: resolveUriOrThrow(id)} : id;\n return this.clone({subject, subjects: undefined, singleResult: true, _pendingContextName: undefined}) as any;\n }\n\n /**\n * Whether the query has a pending (lazy) context that hasn't resolved yet.\n * Returns true when .for() received a PendingQueryContext whose value isn't available yet.\n */\n hasPendingContext(): boolean {\n return !!(this._pendingContextName && !this._subject?.id);\n }\n\n /** Target multiple entities by ID, or all if no ids given. */\n forAll(ids?: (string | NodeReferenceValue)[]): SelectBuilder<S, R, Result> {\n if (!ids) {\n return this.clone({subject: undefined, subjects: undefined, singleResult: false, _pendingContextName: undefined});\n }\n const subjects = ids.map((id) => typeof id === 'string' ? {id: resolveUriOrThrow(id)} : id);\n return this.clone({subject: undefined, subjects, singleResult: false, _pendingContextName: undefined});\n }\n\n /** Limit to one result. Unwraps array Result type to single element. */\n one(): SelectBuilder<S, R, Result extends (infer E)[] ? E : Result> {\n return this.clone<R, Result extends (infer E)[] ? E : Result>({limit: 1, singleResult: true});\n }\n\n /**\n * Whether **any** row matches this query. Executes immediately and resolves to a\n * real `boolean` — never a row, never `null`, never an array the caller has to\n * interpret.\n *\n * ```ts\n * await Person.select().where(p => p.name.equals('Semmy')).exists(); // boolean\n * await Person.exists({id}); // the common case\n * ```\n *\n * ### The query is normalised to its cheapest correct form first\n *\n * **Dropped** — the projection, preloads, sorting *and pagination* (`limit`/`offset`).\n * **Kept** — filters, `minus` entries and the subject: those decide whether a match\n * exists. `LIMIT 1` is then applied.\n *\n * So `.select(…).orderBy(…).offset(10).exists()` costs, and answers, exactly the\n * same as a bare `.exists()`. Against a SPARQL store that goes out as:\n *\n * ```sparql\n * ASK WHERE { ?a0 rdf:type <…> . FILTER(?a0 = <…>) }\n * ```\n *\n * Pagination does not survive, and cannot: `OFFSET` skips rows of a *solution\n * sequence*, and an ask has none. (Nor is it merely dropped — an\n * {@link AskBuilder} has nowhere to hold it.) `exists()` answers a question about\n * the **match set**, not about a page of it.\n *\n * ### Errors are not swallowed\n *\n * A store, transport or lowering failure rejects the returned promise; it is never\n * reported as `false`. That includes an unresolved query-context reference in a\n * where clause, which `exec()` deliberately reports as `null` (\"not ready\") but\n * which `exists()` must not flatten into a boolean — and a store whose `askQuery`\n * resolves to something that is not a boolean, which rejects rather than being\n * coerced into one.\n *\n * The one case that does resolve `false` without querying is a query with **no\n * subject to ask about** — `.for(null)`, `.for(undefined)`, or an unresolved\n * `PendingQueryContext` *as the subject*. \"Does the node with no id exist?\" has a\n * correct total answer, and it is `false`.\n *\n * @param target Optional explicit dataset, as for {@link exec}.\n */\n async exists(target?: IDataset): Promise<boolean> {\n return this._toAsk().exec(target);\n }\n\n /**\n * **How many** rows match this query — the total of the match set, as a real\n * `number`.\n *\n * ```ts\n * await Person.select().where(p => p.name.equals('Semmy')).count(); // number\n * await SelectBuilder.from(shapeIri).where(…).count(); // from an IRI alone\n * ```\n *\n * ### The query is normalised to its cheapest correct form first\n *\n * **Dropped** — the projection, preloads, sorting *and pagination*\n * (`limit`/`offset`). **Kept** — filters, `minus` entries and the subject: those\n * decide membership of the match set. Against a SPARQL store that goes out as:\n *\n * ```sparql\n * SELECT (COUNT(DISTINCT ?a0) AS ?count)\n * WHERE { ?a0 rdf:type <…> . ?a0 <…name> ?a0_name . FILTER(?a0_name = \"Semmy\") }\n * ```\n *\n * ### `limit`/`offset` are dropped, not rejected\n *\n * A count of a windowed query is meaningless — `OFFSET` skips rows of a *solution\n * sequence*, and the number a count answers is a property of the whole match set,\n * not of a page of it. So `.limit(20).offset(40).count()` costs, and answers,\n * exactly the same as a bare `.count()`.\n *\n * Dropping rather than throwing is deliberate: the paging caller holds **one**\n * builder and wants the page *and* its total from the same filter, so rejecting\n * the combination would force it to rebuild the builder by hand for no\n * correctness gain. There is exactly one sensible reading, and it is this one.\n * `.exists()` already made the same call, so the DSL has one rule — *a\n * scalar-answering query drops the solution-sequence modifiers* — not two.\n *\n * Nor is the drop merely a convention: a {@link CountBuilder} has nowhere to hold\n * a window, so it cannot be forgotten or half-applied downstream.\n *\n * `DISTINCT` is likewise not optional. A filter on a multi-valued property yields\n * several rows per subject, so the count is of distinct subjects — \"how many\n * instances match\", which is the question asked.\n *\n * ### Errors are not swallowed\n *\n * A store, transport or lowering failure **rejects**; it is never reported as `0`.\n * `0` is a plausible count: it renders an empty table and looks like data. Do not\n * wrap this in `.catch(() => 0)`.\n *\n * The one case that resolves `0` without querying is a query with no subject to\n * count — `.for(null)`, `.for(undefined)`, or an unresolved `PendingQueryContext`\n * *as the subject*.\n *\n * @param target Optional explicit dataset, as for {@link exec}.\n */\n async count(target?: IDataset): Promise<number> {\n return this.toCount().exec(target);\n }\n\n /**\n * Reduce this select to the count query that answers \"how many match?\".\n *\n * Public, unlike the ask equivalent, because a caller may want to **forward**\n * rather than execute: `builder.toCount().toJSON()` is the `{op: 'count'}` wire\n * envelope a router or RPC boundary sends on, and `fromJSON` turns it back into a\n * `CountBuilder` on the other side.\n *\n * Only the pattern survives — shape, subject(s), filters, `minus`. The projection,\n * preloads, sorting and pagination are not so much \"dropped\" as unrepresentable:\n * {@link CountBuilder} has nowhere to put them. That is the point of it being a\n * separate builder rather than a mode of this one.\n */\n toCount(): CountBuilder {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.toCount());\n }\n return CountBuilder.of({\n shapeClass: this._shape,\n catalog: this._catalog,\n // `.for(null)` rides along in the spec. An unresolved pending context is\n // handled by CountBuilder.exec, which answers `0` without querying.\n ...this._patternSpec(),\n });\n }\n\n /**\n * The pattern-bearing part of this select: shape-membership, subject(s), filters\n * and `minus` — everything that decides which nodes are in the match set, and\n * nothing that shapes or windows the rows describing them.\n *\n * Shared by {@link _toAsk} and {@link toCount} rather than written twice. That is\n * not only about duplication: if the two normalisations drifted, `.exists()` and\n * `.count()` would disagree about what the match set *is* — a count of 0 next to\n * an `exists` of `true`, from the same builder.\n */\n private _patternSpec(): {\n subject?: NodeReferenceValue | PendingQueryContext;\n subjects?: NodeReferenceValue[];\n where?: WherePath;\n minusEntries?: RawMinusEntry[];\n nullSubject?: boolean;\n } {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this._patternSpec());\n }\n let where: WherePath | undefined;\n if (this._whereFn) {\n where = processWhereClause(this._whereFn, this._shape);\n } else if (this._where) {\n where = this._where;\n }\n\n let minusEntries: RawMinusEntry[] | undefined;\n if (this._minusEntries && this._minusEntries.length > 0) {\n minusEntries = this._evaluateMinusEntries();\n } else if (this._rawMinusEntries && this._rawMinusEntries.length > 0) {\n minusEntries = this._rawMinusEntries;\n }\n\n // A PendingQueryContext must survive as itself. It has an `id` *getter*, so\n // narrowing it to `{id}` here would silently resolve it against THIS process's\n // context map — and the query would then travel as a concrete IRI where the\n // equivalent select travels as `{\"@ctx\": name}` for the receiver to resolve.\n const subject =\n this._subject instanceof PendingQueryContext\n ? this._subject\n : this._subject && typeof this._subject === 'object' && 'id' in this._subject\n ? {id: (this._subject as NodeReferenceValue).id}\n : undefined;\n\n return {\n subject,\n subjects: this._subjects,\n where,\n minusEntries,\n nullSubject: this._nullSubject,\n };\n }\n\n /**\n * Reduce this select to the ask query that answers the same existence question.\n *\n * Only the pattern survives — shape, subject(s), filters, `minus`. The\n * projection, preloads, sorting and pagination are not \"dropped\" so much as\n * unrepresentable: {@link AskBuilder} has nowhere to put them. That is the point\n * of it being a separate builder rather than a mode of this one — the\n * normalisation cannot be forgotten or half-applied.\n */\n private _toAsk(): AskBuilder {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this._toAsk());\n }\n return AskBuilder.of({\n shapeClass: this._shape,\n catalog: this._catalog,\n // `.for(null)` rides along in the spec. An unresolved pending context is\n // handled by AskBuilder.exec, which sees the live context and answers `false`\n // without querying.\n ...this._patternSpec(),\n });\n }\n\n /**\n * Preload a component's query fields at the given property path.\n *\n * This merges the component's query paths into this query's selection,\n * wrapping them in an OPTIONAL block (handled by the IR pipeline).\n *\n * Equivalent to the DSL's `.preloadFor()`:\n * ```ts\n * // DSL style\n * Person.select(p => p.bestFriend.preloadFor(PersonCard))\n * // SelectBuilder style\n * SelectBuilder.from(Person).select(p => [p.name]).preload('bestFriend', PersonCard)\n * ```\n *\n * NOTE: Preloads hold live component references and are not serializable.\n * They are merged into the selection when the field set is evaluated\n * (`_fieldsWithPreloads()`), so changes to preload handling must account for\n * the selectFn wrapping logic.\n */\n preload<CS extends Shape, CR>(\n path: string,\n component: QueryComponentLike<CS, CR>,\n ): SelectBuilder<S, R, Result> {\n const newPreloads = [...(this._preloads || []), {path, component}];\n return this.clone({preloads: newPreloads});\n }\n\n /**\n * Returns the current selection as a FieldSet.\n * If the selection was set via a FieldSet, returns that directly.\n * If set via selectAll labels, constructs a FieldSet from them.\n * If set via a callback, eagerly evaluates it through the proxy to produce a FieldSet.\n */\n fields(): FieldSet | undefined {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.fields());\n }\n if (this._fieldSet) {\n return this._fieldSet;\n }\n if (this._selectAllLabels) {\n return FieldSet.for(this._shape.shape, this._selectAllLabels);\n }\n if (this._selectFn) {\n // Eagerly evaluate the callback through FieldSet.for(ShapeClass, callback)\n // The callback is pure — same proxy always produces same paths.\n return FieldSet.for(this._shape, this._selectFn as unknown as (p: any) => any[]);\n }\n return undefined;\n }\n\n // ---------------------------------------------------------------------------\n // Internal helpers\n // ---------------------------------------------------------------------------\n\n /** Return the FieldSet with preload entries merged in (if any). */\n private _fieldsWithPreloads(): FieldSet | undefined {\n let fs = this.fields();\n if (this._preloads && this._preloads.length > 0) {\n const preloadFn = (p: any) => {\n return this._preloads!.map((entry) => p[entry.path].preloadFor(entry.component));\n };\n const preloadFs = FieldSet.for(this._shape, preloadFn);\n if (fs) {\n fs = FieldSet.createFromEntries(fs.shape, [\n ...(fs.entries as FieldSetEntry[]),\n ...(preloadFs.entries as FieldSetEntry[]),\n ]);\n } else {\n fs = preloadFs;\n }\n }\n return fs;\n }\n\n /** Evaluate minus entry callbacks into RawMinusEntry[] (plain data). */\n private _evaluateMinusEntries(): RawMinusEntry[] {\n const proxy = createProxiedPathBuilder(this._shape);\n return this._minusEntries!.map((entry) => {\n if (entry.shapeId) {\n return {shapeId: entry.shapeId};\n }\n if (entry.whereFn) {\n const result = (entry.whereFn as Function)(proxy);\n\n if (Array.isArray(result)) {\n const propertyPaths = result.map((item: any) => {\n const segments = FieldSet.collectPropertySegments(item);\n return segments.map((seg): PropertyPathSegment => ({propertyShapeId: seg.id}));\n });\n return {propertyPaths};\n }\n\n if (result && typeof result === 'object' && 'property' in result && 'subject' in result) {\n const segments = FieldSet.collectPropertySegments(result);\n return {propertyPaths: [segments.map((seg): PropertyPathSegment => ({propertyShapeId: seg.id}))]};\n }\n\n // WHERE-based exclusion\n return {where: processWhereClause(entry.whereFn, this._shape)};\n }\n return {};\n });\n }\n\n // ---------------------------------------------------------------------------\n // Serialization\n // ---------------------------------------------------------------------------\n\n /**\n * Serialize this SelectBuilder to a plain JSON object.\n *\n * Selections are serializable regardless of how they were set (FieldSet,\n * string[], selectAll, or callback). Callback-based selections are eagerly\n * evaluated through the proxy to produce a FieldSet.\n *\n * Where, orderBy, and minus clauses are evaluated through the proxy and\n * serialized as plain data structures. Preloads are merged into the FieldSet\n * as subSelect entries, producing identical IR on deserialization.\n */\n toJSON(): QueryBuilderJSON {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.toJSON());\n }\n const shapeId = this._shape.shape?.id || '';\n const json: QueryBuilderJSON = {\n v: WIRE_VERSION,\n shape: shapeId,\n };\n\n const fs = this._fieldsWithPreloads();\n if (fs) {\n json.fields = fs.toJSON().fields;\n }\n\n if (this._limit !== undefined) {\n json.limit = this._limit;\n }\n if (this._offset !== undefined) {\n json.offset = this._offset;\n }\n if (this._pendingContextName) {\n // Carry the context reference, not its (possibly unresolved) id, so the\n // receiver resolves it against its own context map at lowering time.\n json.subject = encodeContextRef(this._pendingContextName);\n } else if (this._subject && typeof this._subject === 'object' && 'id' in this._subject) {\n json.subject = (this._subject as NodeReferenceValue).id;\n }\n if (this._subjects && this._subjects.length > 0) {\n json.subjects = this._subjects.map((s) => s.id);\n }\n if (this._singleResult) {\n json.one = true;\n }\n\n if (this._whereFn) {\n json.where = serializeWherePath(processWhereClause(this._whereFn, this._shape), this._shape.shape);\n } else if (this._where) {\n json.where = serializeWherePath(this._where, this._shape.shape);\n }\n\n if (this._sortByFn) {\n json.sortBy = serializeSortByPath(\n evaluateSortCallback(this._shape, this._sortByFn as unknown as (p: any) => any, this._sortDirection || 'ASC'),\n );\n } else if (this._sortBy) {\n json.sortBy = serializeSortByPath(this._sortBy);\n }\n\n if (this._minusEntries && this._minusEntries.length > 0) {\n json.minusEntries = this._evaluateMinusEntries().map((e) =>\n serializeRawMinusEntry(e, this._shape.shape),\n );\n } else if (this._rawMinusEntries && this._rawMinusEntries.length > 0) {\n json.minusEntries = this._rawMinusEntries.map((e) =>\n serializeRawMinusEntry(e, this._shape.shape),\n );\n }\n\n if (this._nullSubject) {\n json.nullSubject = true;\n }\n\n return json;\n }\n\n /**\n * Reconstruct a SelectBuilder from a JSON object.\n * Resolves shape IRI via getShapeClass() and field paths as label selections.\n */\n static fromJSON<S extends Shape = Shape>(json: QueryBuilderJSON): SelectBuilder<S> {\n assertWireVersion(json.v);\n let builder = SelectBuilder.from<S>(json.shape as any);\n\n if (json.fields && json.fields.length > 0) {\n const fieldSet = FieldSet.fromJSON({\n shape: json.shape,\n fields: json.fields,\n });\n builder = builder.select(fieldSet) as SelectBuilder<S>;\n }\n\n if (json.limit !== undefined) {\n builder = builder.limit(json.limit) as SelectBuilder<S>;\n }\n if (json.offset !== undefined) {\n builder = builder.offset(json.offset) as SelectBuilder<S>;\n }\n if (json.subject) {\n // A `{@ctx}` subject rehydrates as a pending context (preserving the name\n // so it re-serializes as a context reference and resolves live).\n const subject = isContextRefJSON(json.subject)\n ? new PendingQueryContext(json.subject['@ctx'])\n : json.subject;\n builder = builder.for(subject) as SelectBuilder<S>;\n }\n if (json.subjects && json.subjects.length > 0) {\n builder = builder.forAll(json.subjects) as SelectBuilder<S>;\n }\n if (json.one && !json.subject) {\n builder = builder.one() as SelectBuilder<S>;\n }\n\n // Restore pre-evaluated data via clone — safe because fromJSON is in the same class.\n const overrides: Partial<QueryBuilderInit<S, any>> = {};\n const nodeShape = builder._shape.shape;\n\n // Restore where clause\n if (json.where && nodeShape) {\n overrides._where = deserializeWherePath(nodeShape, json.where);\n }\n\n // Restore sort key + direction (direction rides on the ordered sortBy array)\n if (json.sortBy && json.sortBy.length > 0 && nodeShape) {\n const sortBy = deserializeSortByPath(nodeShape, json.sortBy);\n overrides._sortBy = sortBy;\n overrides.sortDirection = sortBy.directions[0];\n }\n\n // Restore minus entries\n if (json.minusEntries && json.minusEntries.length > 0 && nodeShape) {\n overrides._rawMinusEntries = json.minusEntries.map((e) =>\n deserializeRawMinusEntry(nodeShape, e),\n );\n }\n\n // Restore nullSubject flag\n if (json.nullSubject) {\n overrides._nullSubject = true;\n }\n\n if (Object.keys(overrides).length > 0) {\n builder = (builder as any).clone(overrides) as SelectBuilder<S>;\n }\n\n return builder;\n }\n\n // ---------------------------------------------------------------------------\n // Build & execute\n // ---------------------------------------------------------------------------\n\n /**\n * Get the raw pipeline input.\n *\n * Constructs RawSelectInput directly from FieldSet entries.\n */\n toRawInput(): RawSelectInput {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.toRawInput());\n }\n return this._buildDirectRawInput();\n }\n\n /** Build RawSelectInput directly from FieldSet entries. */\n private _buildDirectRawInput(): RawSelectInput {\n const fs = this._fieldsWithPreloads();\n const entries = fs ? fs.entries : [];\n\n let where: WherePath | undefined;\n if (this._whereFn) {\n where = processWhereClause(this._whereFn, this._shape);\n } else if (this._where) {\n where = this._where;\n }\n\n let sortBy: SortByPath | undefined;\n if (this._sortByFn) {\n sortBy = evaluateSortCallback(\n this._shape,\n this._sortByFn as unknown as (p: any) => any,\n this._sortDirection || 'ASC',\n );\n } else if (this._sortBy) {\n sortBy = this._sortBy;\n }\n\n const input: RawSelectInput = {\n entries,\n subject: this._subject,\n limit: this._limit,\n offset: this._offset,\n shape: this._shape,\n sortBy,\n singleResult:\n this._singleResult ||\n !!(\n this._subject &&\n typeof this._subject === 'object' &&\n 'id' in this._subject\n ),\n };\n\n if (where) {\n input.where = where;\n }\n if (this._subjects && this._subjects.length > 0) {\n input.subjects = this._subjects;\n }\n if (this._minusEntries && this._minusEntries.length > 0) {\n input.minusEntries = this._evaluateMinusEntries();\n } else if (this._rawMinusEntries && this._rawMinusEntries.length > 0) {\n input.minusEntries = this._rawMinusEntries;\n }\n\n return input;\n }\n\n /** Discriminator for the free `lower()` function and dataset routing. */\n readonly __queryKind = 'select' 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 /**\n * The catalog this builder resolves shapes in — captured when it was built, kept by\n * every derived builder. Undefined = the global registry. Never serialized.\n */\n get catalog(): ShapeCatalog | undefined {\n return this._catalog;\n }\n\n /**\n * Execute the query and return results.\n *\n * @param target Optional explicit dataset (a store or a router — a router *is* an\n * `IDataset`) to run against. Omitted → the global query dispatch (the router's\n * shape-based default). A `target` runs on that dataset only; the global router is\n * untouched. `await`ing the builder (the PromiseLike path) always uses the global\n * dispatch — only `.exec(target)` overrides.\n */\n async exec(target?: IDataset): Promise<Result> {\n return this._run(target, true) as Promise<Result>;\n }\n\n /**\n * Shared execution path for {@link exec} and {@link exists}.\n *\n * @param swallowUnresolvedContext When true (the `exec` path), a where-clause\n * context reference that has not resolved yet surfaces as `null` — \"not ready\",\n * which a reactive layer re-runs once the context lands. `exists()` passes\n * false: it must not turn \"could not ask\" into a boolean.\n */\n private async _run(\n target: IDataset | undefined,\n swallowUnresolvedContext: boolean,\n ): Promise<unknown> {\n if (this._nullSubject) {\n // .for(null/undefined) was called — return null instead of executing a broken query.\n return null;\n }\n if (this._pendingContextName && !this._subject?.id) {\n // Pending context hasn't resolved yet — return null rather than querying without a subject.\n return null;\n }\n // Dispatch the live (closed) query; the dataset decides whether to lower it.\n // `async` ensures a missing global dispatch surfaces as a rejected promise, not a sync throw.\n const dispatch = target ?? getQueryDispatch();\n try {\n return await dispatch.selectQuery(this);\n } catch (err) {\n // A where-clause context reference that hasn't resolved yet surfaces as\n // UnresolvedContextError when the dataset lowers the query. For SELECT this\n // means \"not ready\" — return null (a reactive layer re-runs once it lands),\n // mirroring the pending-subject behavior. Mutations still throw.\n if (swallowUnresolvedContext && err instanceof UnresolvedContextError) {\n return null;\n }\n // The message names the query, which is what a human needs. `cause` keeps\n // the ORIGINAL error reachable as an object, which is what code needs: a\n // store error's status/endpoint/class is how a caller tells \"this dataset\n // does not exist\" from \"this query is wrong\", and without the chain the\n // only way left is to pattern-match this string. Written with\n // defineProperty rather than `new Error(msg, {cause})` because this\n // package targets es6, where that overload is not typed; the property\n // shape (own, non-enumerable) is identical.\n const wrapped = Error(`Error while executing query: ${(err as Error).stack}.\\n\\nQuery related to this error: ${JSON.stringify(this.toJSON())}`);\n Object.defineProperty(wrapped, 'cause', {\n value: err,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n throw wrapped;\n }\n }\n\n\n /**\n * Go live: subscribe to this query and keep its result current.\n *\n * Returns a {@link LiveQuery} handle. `await` it for the first result,\n * `subscribe()` for every later one, `close()` when done. A listener may be\n * passed directly as the first argument. Requires the live-query store to be\n * loaded, which importing `@_linked/core` (the package root) does.\n */\n live<R = Result>(listenerOrOptions?: LiveListener<R> | LiveQueryOptions, options?: LiveQueryOptions): LiveQuery<R> {\n const listener = typeof listenerOrOptions === 'function' ? listenerOrOptions : undefined;\n const opts = typeof listenerOrOptions === 'function' ? options : listenerOrOptions;\n return requireLiveQueryStore().subscribe<R>(this as any, listener, opts);\n }\n\n // ---------------------------------------------------------------------------\n // Promise-compatible interface\n // ---------------------------------------------------------------------------\n\n /** `await` triggers execution. */\n then<TResult1 = Result, TResult2 = never>(\n onfulfilled?: ((value: Result) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.exec().then(onfulfilled, onrejected);\n }\n\n /** Catch errors from execution. Chain off then() to avoid re-executing. */\n catch<TResult = never>(\n onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null,\n ): Promise<Result | TResult> {\n return this.then().catch(onrejected);\n }\n\n /** Finally handler after execution. Chain off then() to avoid re-executing. */\n finally(onfinally?: (() => void) | null): Promise<Result> {\n return this.then().finally(onfinally);\n }\n\n get [Symbol.toStringTag](): string {\n return 'SelectBuilder';\n }\n}\n\n/** @deprecated Renamed to `SelectBuilder`. This alias will be removed in a future major. */\nexport {SelectBuilder as QueryBuilder};\n"]}
1
+ {"version":3,"file":"QueryBuilder.js","sourceRoot":"","sources":["../../../src/queries/QueryBuilder.ts"],"names":[],"mappings":";;;;;;;;;AACA,OAAO,EAAC,uBAAuB,EAAC,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAC,YAAY,EAAC,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAOL,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EAAC,YAAY,EAAE,iBAAiB,EAAC,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAC,gBAAgB,EAAC,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAC,UAAU,EAAC,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAC,YAAY,EAAC,MAAM,mBAAmB,CAAC;AAI/C,OAAO,EAAC,iBAAiB,EAAC,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAC,QAAQ,EAA6C,MAAM,eAAe,CAAC;AACnF,OAAO,EAAC,mBAAmB,EAAE,sBAAsB,EAAC,MAAM,mBAAmB,CAAC;AAC9E,OAAO,EAAC,gBAAgB,EAAE,gBAAgB,EAAsB,MAAM,iBAAiB,CAAC;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AE,IAAI;oBACd,YAAY,EAAE,IAAI;oBAClB,UAAU,EAAE,KAAK;iBAClB,CAAC,CAAC;gBACH,MAAM,OAAO,CAAC;YAChB,CAAC;QACH,CAAC;KAAA;IAGD;;;;;;;OAOG;IACH,IAAI,CAAa,iBAAsD,EAAE,OAA0B;QACjG,MAAM,QAAQ,GAAG,OAAO,iBAAiB,KAAK,UAAU,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,SAAS,CAAC;QACzF,MAAM,IAAI,GAAG,OAAO,iBAAiB,KAAK,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,iBAAiB,CAAC;QACnF,OAAO,qBAAqB,EAAE,CAAC,SAAS,CAAI,IAAW,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC;IAC3E,CAAC;IAED,8EAA8E;IAC9E,+BAA+B;IAC/B,8EAA8E;IAE9E,kCAAkC;IAClC,IAAI,CACF,WAA0E,EAC1E,UAAuE;QAEvE,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;IACnD,CAAC;IAED,2EAA2E;IAC3E,KAAK,CACH,UAAqE;QAErE,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACvC,CAAC;IAED,+EAA+E;IAC/E,OAAO,CAAC,SAA+B;QACrC,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACxC,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC;QACtB,OAAO,eAAe,CAAC;IACzB,CAAC;CACF;AAED,4FAA4F;AAC5F,OAAO,EAAC,aAAa,IAAI,YAAY,EAAC,CAAC","sourcesContent":["import {Shape, type ShapeConstructor} from '../shapes/Shape.js';\nimport {getUniquePropertyShapes} from '../shapes/nodeShapeData.js';\nimport {resolveShape} from './resolveShape.js';\nimport {\n type QueryBuildFn,\n type WhereClause,\n type QResult,\n type QueryResponseToResultType,\n type SelectAllQueryResponse,\n type QueryComponentLike,\n processWhereClause,\n evaluateSortCallback,\n} from './SelectQuery.js';\nimport type {SortByPath, WherePath} from './SelectQuery.js';\nimport type {PropertyPathSegment, RawMinusEntry, RawSelectInput} from './IRDesugar.js';\nimport {WIRE_VERSION, assertWireVersion} from './wireVersion.js';\nimport {getQueryDispatch} from './queryDispatch.js';\nimport {AskBuilder} from './AskBuilder.js';\nimport {CountBuilder} from './CountBuilder.js';\nimport type {IDataset} from '../interfaces/IDataset.js';\nimport type {NodeShapeData} from '../shapes/SHACL.js';\nimport type {NodeReferenceValue} from './QueryFactory.js';\nimport {resolveUriOrThrow} from '../utils/NodeReference.js';\nimport {FieldSet, type FieldSetFieldJSON, type FieldSetEntry} from './FieldSet.js';\nimport {PendingQueryContext, UnresolvedContextError} from './QueryContext.js';\nimport {encodeContextRef, isContextRefJSON, type ContextRefJSON} from './ContextRef.js';\nimport {createProxiedPathBuilder} from './ProxiedPathBuilder.js';\nimport {\n serializeWherePath,\n serializeSortByPath,\n serializeRawMinusEntry,\n deserializeWherePath,\n deserializeSortByPath,\n deserializeRawMinusEntry,\n type WherePathJSON,\n type SortByPathJSON,\n type RawMinusEntryJSON,\n} from './QueryBuilderSerialization.js';\nimport {requireLiveQueryStore} from '../live/registry.js';\nimport {captureCatalog, getActiveShapeCatalog, withShapeCatalog} from '../utils/ShapeClass.js';\nimport type {ShapeCatalog} from '../utils/ShapeCatalog.js';\nimport {isLinkedError} from '../utils/linkedError.js';\nimport type {LiveListener, LiveQuery, LiveQueryOptions} from '../live/LiveQueryStore.js';\n\n/** JSON representation of a SelectBuilder. */\nexport type QueryBuilderJSON = {\n /** DSL-JSON wire-format version. */\n v?: string;\n shape: string;\n fields?: FieldSetFieldJSON[];\n limit?: number;\n offset?: number;\n /** A node id, or a `{@ctx: name}` context reference resolved at lowering. */\n subject?: string | ContextRefJSON;\n subjects?: string[];\n /** `.one()` — unwrap a single result. */\n one?: boolean;\n where?: WherePathJSON;\n sortBy?: SortByPathJSON;\n minusEntries?: RawMinusEntryJSON[];\n nullSubject?: boolean;\n};\n\n/** A preload entry binding a property path to a component's query. */\ninterface PreloadEntry {\n path: string;\n component: QueryComponentLike<any, any>;\n}\n\n/** A MINUS entry — either a shape type exclusion or a WHERE-clause condition. */\ninterface MinusEntry<S extends Shape> {\n shapeId?: string;\n whereFn?: WhereClause<S>;\n}\n\n/** Internal state bag for SelectBuilder. */\ninterface QueryBuilderInit<S extends Shape, R> {\n shape: ShapeConstructor<S>;\n /** The catalog the builder resolves in; absent = captured from the active one. */\n catalog?: ShapeCatalog;\n selectFn?: QueryBuildFn<S, R>;\n whereFn?: WhereClause<S>;\n sortByFn?: QueryBuildFn<S, any>;\n sortDirection?: 'ASC' | 'DESC';\n limit?: number;\n offset?: number;\n subject?: S | QResult<S> | NodeReferenceValue;\n subjects?: NodeReferenceValue[];\n singleResult?: boolean;\n selectAllLabels?: string[];\n fieldSet?: FieldSet;\n preloads?: PreloadEntry[];\n minusEntries?: MinusEntry<S>[];\n _nullSubject?: boolean;\n _pendingContextName?: string;\n // Pre-evaluated data (restored from JSON; used when callbacks are not available)\n _where?: WherePath;\n _sortBy?: SortByPath;\n _rawMinusEntries?: RawMinusEntry[];\n}\n\n/**\n * An immutable, fluent query builder for select queries.\n *\n * Every mutation method (`.select()`, `.where()`, `.limit()`, etc.) returns\n * a **new** SelectBuilder instance — the original is never modified.\n *\n * Implements `PromiseLike` so queries execute on `await`:\n * ```ts\n * const results = await SelectBuilder.from(Person).select(p => p.name);\n * ```\n *\n * Produces a raw select input (`toRawInput()`) that the free `lower()` function\n * turns into IR; the builder itself carries no dependency on the IR pipeline.\n */\nexport class SelectBuilder<S extends Shape = Shape, R = any, Result = any>\n implements PromiseLike<Result>, Promise<Result>\n{\n private readonly _shape: ShapeConstructor<S>;\n private readonly _selectFn?: QueryBuildFn<S, R>;\n private readonly _whereFn?: WhereClause<S>;\n private readonly _sortByFn?: QueryBuildFn<S, any>;\n private readonly _sortDirection?: 'ASC' | 'DESC';\n private readonly _limit?: number;\n private readonly _offset?: number;\n private readonly _subject?: S | QResult<S> | NodeReferenceValue;\n private readonly _subjects?: NodeReferenceValue[];\n private readonly _singleResult?: boolean;\n private readonly _selectAllLabels?: string[];\n private readonly _fieldSet?: FieldSet;\n private readonly _preloads?: PreloadEntry[];\n private readonly _minusEntries?: MinusEntry<S>[];\n private readonly _nullSubject?: boolean;\n private readonly _pendingContextName?: string;\n // Pre-evaluated data (restored from JSON; used when callbacks are not available)\n private readonly _where?: WherePath;\n private readonly _sortBy?: SortByPath;\n private readonly _rawMinusEntries?: RawMinusEntry[];\n private readonly _catalog: ShapeCatalog | undefined;\n\n private constructor(init: QueryBuilderInit<S, R>) {\n this._shape = init.shape;\n this._catalog = 'catalog' in init ? init.catalog : captureCatalog(init.shape);\n this._selectFn = init.selectFn;\n this._whereFn = init.whereFn;\n this._sortByFn = init.sortByFn;\n this._sortDirection = init.sortDirection;\n this._limit = init.limit;\n this._offset = init.offset;\n this._subject = init.subject;\n this._subjects = init.subjects;\n this._singleResult = init.singleResult;\n this._selectAllLabels = init.selectAllLabels;\n this._fieldSet = init.fieldSet;\n this._preloads = init.preloads;\n this._minusEntries = init.minusEntries;\n this._nullSubject = init._nullSubject;\n this._pendingContextName = init._pendingContextName;\n this._where = init._where;\n this._sortBy = init._sortBy;\n this._rawMinusEntries = init._rawMinusEntries;\n }\n\n /** Create a shallow clone with overrides. */\n private clone<NR = R, NResult = Result>(overrides: Partial<QueryBuilderInit<S, any>> = {}): SelectBuilder<S, NR, NResult> {\n return new SelectBuilder<S, NR, NResult>({\n shape: this._shape,\n selectFn: this._selectFn as any,\n whereFn: this._whereFn,\n sortByFn: this._sortByFn,\n sortDirection: this._sortDirection,\n limit: this._limit,\n offset: this._offset,\n subject: this._subject,\n subjects: this._subjects,\n singleResult: this._singleResult,\n selectAllLabels: this._selectAllLabels,\n fieldSet: this._fieldSet,\n preloads: this._preloads,\n minusEntries: this._minusEntries,\n _nullSubject: this._nullSubject,\n _pendingContextName: this._pendingContextName,\n _where: this._where,\n _sortBy: this._sortBy,\n _rawMinusEntries: this._rawMinusEntries,\n catalog: this._catalog,\n ...overrides,\n });\n }\n\n // ---------------------------------------------------------------------------\n // Static constructors\n // ---------------------------------------------------------------------------\n\n /**\n * Create a SelectBuilder for the given shape.\n *\n * Accepts a shape class (e.g. `Person`), a NodeShapeData instance,\n * or a shape IRI string (resolved via the shape registry).\n */\n static from<S extends Shape>(\n shape: ShapeConstructor<S> | string,\n ): SelectBuilder<S> {\n const resolved = resolveShape<S>(shape);\n return new SelectBuilder<S>({shape: resolved});\n }\n\n // ---------------------------------------------------------------------------\n // Fluent API — each returns a new instance\n // ---------------------------------------------------------------------------\n\n /** Set the select projection via a callback, labels, or FieldSet. */\n select<NewR>(fn: QueryBuildFn<S, NewR>): SelectBuilder<S, NewR, QueryResponseToResultType<NewR, S>[]>;\n select(labels: string[]): SelectBuilder<S>;\n select<NewR>(fieldSet: FieldSet<NewR>): SelectBuilder<S, NewR, QueryResponseToResultType<NewR, S>[]>;\n select<NewR = R>(fnOrLabelsOrFieldSet: QueryBuildFn<S, NewR> | string[] | FieldSet<any>): SelectBuilder<S, NewR, any> {\n if (fnOrLabelsOrFieldSet instanceof FieldSet) {\n const labels = fnOrLabelsOrFieldSet.labels();\n const selectFn = ((p: any) =>\n labels.map((label) => p[label])) as unknown as QueryBuildFn<S, any>;\n return this.clone<NewR, any>({selectFn, selectAllLabels: undefined, fieldSet: fnOrLabelsOrFieldSet});\n }\n if (Array.isArray(fnOrLabelsOrFieldSet)) {\n const labels = fnOrLabelsOrFieldSet;\n const selectFn = ((p: any) =>\n labels.map((label) => p[label])) as unknown as QueryBuildFn<S, any>;\n return this.clone<NewR, any>({selectFn, selectAllLabels: undefined, fieldSet: undefined});\n }\n return this.clone<NewR, any>({selectFn: fnOrLabelsOrFieldSet as any, selectAllLabels: undefined, fieldSet: undefined});\n }\n\n /** Select all decorated properties of the shape. */\n selectAll(): SelectBuilder<S, any, QueryResponseToResultType<SelectAllQueryResponse<S>, S>[]> {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.selectAll());\n }\n const propertyLabels = getUniquePropertyShapes(this._shape.shape)\n .map((ps) => ps.label);\n const selectFn = ((p: any) =>\n propertyLabels.map((label) => p[label])) as unknown as QueryBuildFn<S, any>;\n return this.clone({selectFn, selectAllLabels: propertyLabels});\n }\n\n /** Add a where clause. */\n where(fn: WhereClause<S>): SelectBuilder<S, R, Result> {\n return this.clone({whereFn: fn});\n }\n\n /**\n * Exclude results matching a MINUS pattern.\n *\n * Accepts:\n * - A shape constructor to exclude by type: `.minus(Employee)`\n * - A WHERE callback to exclude by condition: `.minus(p => p.hobby.equals('Chess'))`\n * - A callback returning a property or array of properties for existence exclusion:\n * `.minus(p => p.hobby)` or `.minus(p => [p.hobby, p.bestFriend.name])`\n *\n * Chainable: `.minus(A).minus(B)` produces two separate `MINUS { }` blocks.\n */\n minus(shapeOrFn: ShapeConstructor<any> | WhereClause<S> | ((s: any) => any)): SelectBuilder<S, R, Result> {\n const entry: MinusEntry<S> = {};\n if (typeof shapeOrFn === 'function' && 'shape' in shapeOrFn) {\n // ShapeConstructor — has a static .shape property\n entry.shapeId = (shapeOrFn as ShapeConstructor<any>).shape?.id;\n } else {\n // WhereClause callback\n entry.whereFn = shapeOrFn as WhereClause<S>;\n }\n const existing = this._minusEntries || [];\n return this.clone({minusEntries: [...existing, entry]});\n }\n\n /** Set sort order. */\n orderBy<OR>(fn: QueryBuildFn<S, OR>, direction: 'ASC' | 'DESC' = 'ASC'): SelectBuilder<S, R, Result> {\n return this.clone({sortByFn: fn as any, sortDirection: direction});\n }\n\n /**\n * @deprecated Use `orderBy()` instead.\n */\n sortBy<OR>(fn: QueryBuildFn<S, OR>, direction: 'ASC' | 'DESC' = 'ASC'): SelectBuilder<S, R, Result> {\n return this.orderBy(fn, direction);\n }\n\n /** Set result limit. */\n limit(n: number): SelectBuilder<S, R, Result> {\n return this.clone({limit: n});\n }\n\n /** Set result offset. */\n offset(n: number): SelectBuilder<S, R, Result> {\n return this.clone({offset: n});\n }\n\n /** Target a single entity by ID. Implies singleResult; unwraps array Result type. */\n for(id: string | NodeReferenceValue | PendingQueryContext | null | undefined): SelectBuilder<S, R, Result extends (infer E)[] ? E : Result> {\n if (id instanceof PendingQueryContext) {\n // Store the pending context as subject — its .id getter resolves lazily\n // from the global context map when the query is lowered/serialized.\n return this.clone({subject: id as any, subjects: undefined, singleResult: true, _nullSubject: false, _pendingContextName: id.contextName}) as any;\n }\n if (id == null) {\n // Return a builder that resolves to null when executed (no subject = no query).\n // This commonly happens when getQueryContext() returns null before the user is authenticated.\n return this.clone({subject: undefined, subjects: undefined, singleResult: true, _nullSubject: true, _pendingContextName: undefined}) as any;\n }\n const subject: NodeReferenceValue = typeof id === 'string' ? {id: resolveUriOrThrow(id)} : id;\n return this.clone({subject, subjects: undefined, singleResult: true, _pendingContextName: undefined}) as any;\n }\n\n /**\n * Whether the query has a pending (lazy) context that hasn't resolved yet.\n * Returns true when .for() received a PendingQueryContext whose value isn't available yet.\n */\n hasPendingContext(): boolean {\n return !!(this._pendingContextName && !this._subject?.id);\n }\n\n /** Target multiple entities by ID, or all if no ids given. */\n forAll(ids?: (string | NodeReferenceValue)[]): SelectBuilder<S, R, Result> {\n if (!ids) {\n return this.clone({subject: undefined, subjects: undefined, singleResult: false, _pendingContextName: undefined});\n }\n const subjects = ids.map((id) => typeof id === 'string' ? {id: resolveUriOrThrow(id)} : id);\n return this.clone({subject: undefined, subjects, singleResult: false, _pendingContextName: undefined});\n }\n\n /** Limit to one result. Unwraps array Result type to single element. */\n one(): SelectBuilder<S, R, Result extends (infer E)[] ? E : Result> {\n return this.clone<R, Result extends (infer E)[] ? E : Result>({limit: 1, singleResult: true});\n }\n\n /**\n * Whether **any** row matches this query. Executes immediately and resolves to a\n * real `boolean` — never a row, never `null`, never an array the caller has to\n * interpret.\n *\n * ```ts\n * await Person.select().where(p => p.name.equals('Semmy')).exists(); // boolean\n * await Person.exists({id}); // the common case\n * ```\n *\n * ### The query is normalised to its cheapest correct form first\n *\n * **Dropped** — the projection, preloads, sorting *and pagination* (`limit`/`offset`).\n * **Kept** — filters, `minus` entries and the subject: those decide whether a match\n * exists. `LIMIT 1` is then applied.\n *\n * So `.select(…).orderBy(…).offset(10).exists()` costs, and answers, exactly the\n * same as a bare `.exists()`. Against a SPARQL store that goes out as:\n *\n * ```sparql\n * ASK WHERE { ?a0 rdf:type <…> . FILTER(?a0 = <…>) }\n * ```\n *\n * Pagination does not survive, and cannot: `OFFSET` skips rows of a *solution\n * sequence*, and an ask has none. (Nor is it merely dropped — an\n * {@link AskBuilder} has nowhere to hold it.) `exists()` answers a question about\n * the **match set**, not about a page of it.\n *\n * ### Errors are not swallowed\n *\n * A store, transport or lowering failure rejects the returned promise; it is never\n * reported as `false`. That includes an unresolved query-context reference in a\n * where clause, which `exec()` deliberately reports as `null` (\"not ready\") but\n * which `exists()` must not flatten into a boolean — and a store whose `askQuery`\n * resolves to something that is not a boolean, which rejects rather than being\n * coerced into one.\n *\n * The one case that does resolve `false` without querying is a query with **no\n * subject to ask about** — `.for(null)`, `.for(undefined)`, or an unresolved\n * `PendingQueryContext` *as the subject*. \"Does the node with no id exist?\" has a\n * correct total answer, and it is `false`.\n *\n * @param target Optional explicit dataset, as for {@link exec}.\n */\n async exists(target?: IDataset): Promise<boolean> {\n return this._toAsk().exec(target);\n }\n\n /**\n * **How many** rows match this query — the total of the match set, as a real\n * `number`.\n *\n * ```ts\n * await Person.select().where(p => p.name.equals('Semmy')).count(); // number\n * await SelectBuilder.from(shapeIri).where(…).count(); // from an IRI alone\n * ```\n *\n * ### The query is normalised to its cheapest correct form first\n *\n * **Dropped** — the projection, preloads, sorting *and pagination*\n * (`limit`/`offset`). **Kept** — filters, `minus` entries and the subject: those\n * decide membership of the match set. Against a SPARQL store that goes out as:\n *\n * ```sparql\n * SELECT (COUNT(DISTINCT ?a0) AS ?count)\n * WHERE { ?a0 rdf:type <…> . ?a0 <…name> ?a0_name . FILTER(?a0_name = \"Semmy\") }\n * ```\n *\n * ### `limit`/`offset` are dropped, not rejected\n *\n * A count of a windowed query is meaningless — `OFFSET` skips rows of a *solution\n * sequence*, and the number a count answers is a property of the whole match set,\n * not of a page of it. So `.limit(20).offset(40).count()` costs, and answers,\n * exactly the same as a bare `.count()`.\n *\n * Dropping rather than throwing is deliberate: the paging caller holds **one**\n * builder and wants the page *and* its total from the same filter, so rejecting\n * the combination would force it to rebuild the builder by hand for no\n * correctness gain. There is exactly one sensible reading, and it is this one.\n * `.exists()` already made the same call, so the DSL has one rule — *a\n * scalar-answering query drops the solution-sequence modifiers* — not two.\n *\n * Nor is the drop merely a convention: a {@link CountBuilder} has nowhere to hold\n * a window, so it cannot be forgotten or half-applied downstream.\n *\n * `DISTINCT` is likewise not optional. A filter on a multi-valued property yields\n * several rows per subject, so the count is of distinct subjects — \"how many\n * instances match\", which is the question asked.\n *\n * ### Errors are not swallowed\n *\n * A store, transport or lowering failure **rejects**; it is never reported as `0`.\n * `0` is a plausible count: it renders an empty table and looks like data. Do not\n * wrap this in `.catch(() => 0)`.\n *\n * The one case that resolves `0` without querying is a query with no subject to\n * count — `.for(null)`, `.for(undefined)`, or an unresolved `PendingQueryContext`\n * *as the subject*.\n *\n * @param target Optional explicit dataset, as for {@link exec}.\n */\n async count(target?: IDataset): Promise<number> {\n return this.toCount().exec(target);\n }\n\n /**\n * Reduce this select to the count query that answers \"how many match?\".\n *\n * Public, unlike the ask equivalent, because a caller may want to **forward**\n * rather than execute: `builder.toCount().toJSON()` is the `{op: 'count'}` wire\n * envelope a router or RPC boundary sends on, and `fromJSON` turns it back into a\n * `CountBuilder` on the other side.\n *\n * Only the pattern survives — shape, subject(s), filters, `minus`. The projection,\n * preloads, sorting and pagination are not so much \"dropped\" as unrepresentable:\n * {@link CountBuilder} has nowhere to put them. That is the point of it being a\n * separate builder rather than a mode of this one.\n */\n toCount(): CountBuilder {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.toCount());\n }\n return CountBuilder.of({\n shapeClass: this._shape,\n catalog: this._catalog,\n // `.for(null)` rides along in the spec. An unresolved pending context is\n // handled by CountBuilder.exec, which answers `0` without querying.\n ...this._patternSpec(),\n });\n }\n\n /**\n * The pattern-bearing part of this select: shape-membership, subject(s), filters\n * and `minus` — everything that decides which nodes are in the match set, and\n * nothing that shapes or windows the rows describing them.\n *\n * Shared by {@link _toAsk} and {@link toCount} rather than written twice. That is\n * not only about duplication: if the two normalisations drifted, `.exists()` and\n * `.count()` would disagree about what the match set *is* — a count of 0 next to\n * an `exists` of `true`, from the same builder.\n */\n private _patternSpec(): {\n subject?: NodeReferenceValue | PendingQueryContext;\n subjects?: NodeReferenceValue[];\n where?: WherePath;\n minusEntries?: RawMinusEntry[];\n nullSubject?: boolean;\n } {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this._patternSpec());\n }\n let where: WherePath | undefined;\n if (this._whereFn) {\n where = processWhereClause(this._whereFn, this._shape);\n } else if (this._where) {\n where = this._where;\n }\n\n let minusEntries: RawMinusEntry[] | undefined;\n if (this._minusEntries && this._minusEntries.length > 0) {\n minusEntries = this._evaluateMinusEntries();\n } else if (this._rawMinusEntries && this._rawMinusEntries.length > 0) {\n minusEntries = this._rawMinusEntries;\n }\n\n // A PendingQueryContext must survive as itself. It has an `id` *getter*, so\n // narrowing it to `{id}` here would silently resolve it against THIS process's\n // context map — and the query would then travel as a concrete IRI where the\n // equivalent select travels as `{\"@ctx\": name}` for the receiver to resolve.\n const subject =\n this._subject instanceof PendingQueryContext\n ? this._subject\n : this._subject && typeof this._subject === 'object' && 'id' in this._subject\n ? {id: (this._subject as NodeReferenceValue).id}\n : undefined;\n\n return {\n subject,\n subjects: this._subjects,\n where,\n minusEntries,\n nullSubject: this._nullSubject,\n };\n }\n\n /**\n * Reduce this select to the ask query that answers the same existence question.\n *\n * Only the pattern survives — shape, subject(s), filters, `minus`. The\n * projection, preloads, sorting and pagination are not \"dropped\" so much as\n * unrepresentable: {@link AskBuilder} has nowhere to put them. That is the point\n * of it being a separate builder rather than a mode of this one — the\n * normalisation cannot be forgotten or half-applied.\n */\n private _toAsk(): AskBuilder {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this._toAsk());\n }\n return AskBuilder.of({\n shapeClass: this._shape,\n catalog: this._catalog,\n // `.for(null)` rides along in the spec. An unresolved pending context is\n // handled by AskBuilder.exec, which sees the live context and answers `false`\n // without querying.\n ...this._patternSpec(),\n });\n }\n\n /**\n * Preload a component's query fields at the given property path.\n *\n * This merges the component's query paths into this query's selection,\n * wrapping them in an OPTIONAL block (handled by the IR pipeline).\n *\n * Equivalent to the DSL's `.preloadFor()`:\n * ```ts\n * // DSL style\n * Person.select(p => p.bestFriend.preloadFor(PersonCard))\n * // SelectBuilder style\n * SelectBuilder.from(Person).select(p => [p.name]).preload('bestFriend', PersonCard)\n * ```\n *\n * NOTE: Preloads hold live component references and are not serializable.\n * They are merged into the selection when the field set is evaluated\n * (`_fieldsWithPreloads()`), so changes to preload handling must account for\n * the selectFn wrapping logic.\n */\n preload<CS extends Shape, CR>(\n path: string,\n component: QueryComponentLike<CS, CR>,\n ): SelectBuilder<S, R, Result> {\n const newPreloads = [...(this._preloads || []), {path, component}];\n return this.clone({preloads: newPreloads});\n }\n\n /**\n * Returns the current selection as a FieldSet.\n * If the selection was set via a FieldSet, returns that directly.\n * If set via selectAll labels, constructs a FieldSet from them.\n * If set via a callback, eagerly evaluates it through the proxy to produce a FieldSet.\n */\n fields(): FieldSet | undefined {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.fields());\n }\n if (this._fieldSet) {\n return this._fieldSet;\n }\n if (this._selectAllLabels) {\n return FieldSet.for(this._shape.shape, this._selectAllLabels);\n }\n if (this._selectFn) {\n // Eagerly evaluate the callback through FieldSet.for(ShapeClass, callback)\n // The callback is pure — same proxy always produces same paths.\n return FieldSet.for(this._shape, this._selectFn as unknown as (p: any) => any[]);\n }\n return undefined;\n }\n\n // ---------------------------------------------------------------------------\n // Internal helpers\n // ---------------------------------------------------------------------------\n\n /** Return the FieldSet with preload entries merged in (if any). */\n private _fieldsWithPreloads(): FieldSet | undefined {\n let fs = this.fields();\n if (this._preloads && this._preloads.length > 0) {\n const preloadFn = (p: any) => {\n return this._preloads!.map((entry) => p[entry.path].preloadFor(entry.component));\n };\n const preloadFs = FieldSet.for(this._shape, preloadFn);\n if (fs) {\n fs = FieldSet.createFromEntries(fs.shape, [\n ...(fs.entries as FieldSetEntry[]),\n ...(preloadFs.entries as FieldSetEntry[]),\n ]);\n } else {\n fs = preloadFs;\n }\n }\n return fs;\n }\n\n /** Evaluate minus entry callbacks into RawMinusEntry[] (plain data). */\n private _evaluateMinusEntries(): RawMinusEntry[] {\n const proxy = createProxiedPathBuilder(this._shape);\n return this._minusEntries!.map((entry) => {\n if (entry.shapeId) {\n return {shapeId: entry.shapeId};\n }\n if (entry.whereFn) {\n const result = (entry.whereFn as Function)(proxy);\n\n if (Array.isArray(result)) {\n const propertyPaths = result.map((item: any) => {\n const segments = FieldSet.collectPropertySegments(item);\n return segments.map((seg): PropertyPathSegment => ({propertyShapeId: seg.id}));\n });\n return {propertyPaths};\n }\n\n if (result && typeof result === 'object' && 'property' in result && 'subject' in result) {\n const segments = FieldSet.collectPropertySegments(result);\n return {propertyPaths: [segments.map((seg): PropertyPathSegment => ({propertyShapeId: seg.id}))]};\n }\n\n // WHERE-based exclusion\n return {where: processWhereClause(entry.whereFn, this._shape)};\n }\n return {};\n });\n }\n\n // ---------------------------------------------------------------------------\n // Serialization\n // ---------------------------------------------------------------------------\n\n /**\n * Serialize this SelectBuilder to a plain JSON object.\n *\n * Selections are serializable regardless of how they were set (FieldSet,\n * string[], selectAll, or callback). Callback-based selections are eagerly\n * evaluated through the proxy to produce a FieldSet.\n *\n * Where, orderBy, and minus clauses are evaluated through the proxy and\n * serialized as plain data structures. Preloads are merged into the FieldSet\n * as subSelect entries, producing identical IR on deserialization.\n */\n toJSON(): QueryBuilderJSON {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.toJSON());\n }\n const shapeId = this._shape.shape?.id || '';\n const json: QueryBuilderJSON = {\n v: WIRE_VERSION,\n shape: shapeId,\n };\n\n const fs = this._fieldsWithPreloads();\n if (fs) {\n json.fields = fs.toJSON().fields;\n }\n\n if (this._limit !== undefined) {\n json.limit = this._limit;\n }\n if (this._offset !== undefined) {\n json.offset = this._offset;\n }\n if (this._pendingContextName) {\n // Carry the context reference, not its (possibly unresolved) id, so the\n // receiver resolves it against its own context map at lowering time.\n json.subject = encodeContextRef(this._pendingContextName);\n } else if (this._subject && typeof this._subject === 'object' && 'id' in this._subject) {\n json.subject = (this._subject as NodeReferenceValue).id;\n }\n if (this._subjects && this._subjects.length > 0) {\n json.subjects = this._subjects.map((s) => s.id);\n }\n if (this._singleResult) {\n json.one = true;\n }\n\n if (this._whereFn) {\n json.where = serializeWherePath(processWhereClause(this._whereFn, this._shape), this._shape.shape);\n } else if (this._where) {\n json.where = serializeWherePath(this._where, this._shape.shape);\n }\n\n if (this._sortByFn) {\n json.sortBy = serializeSortByPath(\n evaluateSortCallback(this._shape, this._sortByFn as unknown as (p: any) => any, this._sortDirection || 'ASC'),\n );\n } else if (this._sortBy) {\n json.sortBy = serializeSortByPath(this._sortBy);\n }\n\n if (this._minusEntries && this._minusEntries.length > 0) {\n json.minusEntries = this._evaluateMinusEntries().map((e) =>\n serializeRawMinusEntry(e, this._shape.shape),\n );\n } else if (this._rawMinusEntries && this._rawMinusEntries.length > 0) {\n json.minusEntries = this._rawMinusEntries.map((e) =>\n serializeRawMinusEntry(e, this._shape.shape),\n );\n }\n\n if (this._nullSubject) {\n json.nullSubject = true;\n }\n\n return json;\n }\n\n /**\n * Reconstruct a SelectBuilder from a JSON object.\n * Resolves shape IRI via getShapeClass() and field paths as label selections.\n */\n static fromJSON<S extends Shape = Shape>(json: QueryBuilderJSON): SelectBuilder<S> {\n assertWireVersion(json.v);\n let builder = SelectBuilder.from<S>(json.shape as any);\n\n if (json.fields && json.fields.length > 0) {\n const fieldSet = FieldSet.fromJSON({\n shape: json.shape,\n fields: json.fields,\n });\n builder = builder.select(fieldSet) as SelectBuilder<S>;\n }\n\n if (json.limit !== undefined) {\n builder = builder.limit(json.limit) as SelectBuilder<S>;\n }\n if (json.offset !== undefined) {\n builder = builder.offset(json.offset) as SelectBuilder<S>;\n }\n if (json.subject) {\n // A `{@ctx}` subject rehydrates as a pending context (preserving the name\n // so it re-serializes as a context reference and resolves live).\n const subject = isContextRefJSON(json.subject)\n ? new PendingQueryContext(json.subject['@ctx'])\n : json.subject;\n builder = builder.for(subject) as SelectBuilder<S>;\n }\n if (json.subjects && json.subjects.length > 0) {\n builder = builder.forAll(json.subjects) as SelectBuilder<S>;\n }\n if (json.one && !json.subject) {\n builder = builder.one() as SelectBuilder<S>;\n }\n\n // Restore pre-evaluated data via clone — safe because fromJSON is in the same class.\n const overrides: Partial<QueryBuilderInit<S, any>> = {};\n const nodeShape = builder._shape.shape;\n\n // Restore where clause\n if (json.where && nodeShape) {\n overrides._where = deserializeWherePath(nodeShape, json.where);\n }\n\n // Restore sort key + direction (direction rides on the ordered sortBy array)\n if (json.sortBy && json.sortBy.length > 0 && nodeShape) {\n const sortBy = deserializeSortByPath(nodeShape, json.sortBy);\n overrides._sortBy = sortBy;\n overrides.sortDirection = sortBy.directions[0];\n }\n\n // Restore minus entries\n if (json.minusEntries && json.minusEntries.length > 0 && nodeShape) {\n overrides._rawMinusEntries = json.minusEntries.map((e) =>\n deserializeRawMinusEntry(nodeShape, e),\n );\n }\n\n // Restore nullSubject flag\n if (json.nullSubject) {\n overrides._nullSubject = true;\n }\n\n if (Object.keys(overrides).length > 0) {\n builder = (builder as any).clone(overrides) as SelectBuilder<S>;\n }\n\n return builder;\n }\n\n // ---------------------------------------------------------------------------\n // Build & execute\n // ---------------------------------------------------------------------------\n\n /**\n * Get the raw pipeline input.\n *\n * Constructs RawSelectInput directly from FieldSet entries.\n */\n toRawInput(): RawSelectInput {\n const catalog = this._catalog;\n if (catalog !== getActiveShapeCatalog()) {\n return withShapeCatalog(catalog, () => this.toRawInput());\n }\n return this._buildDirectRawInput();\n }\n\n /** Build RawSelectInput directly from FieldSet entries. */\n private _buildDirectRawInput(): RawSelectInput {\n const fs = this._fieldsWithPreloads();\n const entries = fs ? fs.entries : [];\n\n let where: WherePath | undefined;\n if (this._whereFn) {\n where = processWhereClause(this._whereFn, this._shape);\n } else if (this._where) {\n where = this._where;\n }\n\n let sortBy: SortByPath | undefined;\n if (this._sortByFn) {\n sortBy = evaluateSortCallback(\n this._shape,\n this._sortByFn as unknown as (p: any) => any,\n this._sortDirection || 'ASC',\n );\n } else if (this._sortBy) {\n sortBy = this._sortBy;\n }\n\n const input: RawSelectInput = {\n entries,\n subject: this._subject,\n limit: this._limit,\n offset: this._offset,\n shape: this._shape,\n sortBy,\n singleResult:\n this._singleResult ||\n !!(\n this._subject &&\n typeof this._subject === 'object' &&\n 'id' in this._subject\n ),\n };\n\n if (where) {\n input.where = where;\n }\n if (this._subjects && this._subjects.length > 0) {\n input.subjects = this._subjects;\n }\n if (this._minusEntries && this._minusEntries.length > 0) {\n input.minusEntries = this._evaluateMinusEntries();\n } else if (this._rawMinusEntries && this._rawMinusEntries.length > 0) {\n input.minusEntries = this._rawMinusEntries;\n }\n\n return input;\n }\n\n /** Discriminator for the free `lower()` function and dataset routing. */\n readonly __queryKind = 'select' 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 /**\n * The catalog this builder resolves shapes in — captured when it was built, kept by\n * every derived builder. Undefined = the global registry. Never serialized.\n */\n get catalog(): ShapeCatalog | undefined {\n return this._catalog;\n }\n\n /**\n * Execute the query and return results.\n *\n * @param target Optional explicit dataset (a store or a router — a router *is* an\n * `IDataset`) to run against. Omitted → the global query dispatch (the router's\n * shape-based default). A `target` runs on that dataset only; the global router is\n * untouched. `await`ing the builder (the PromiseLike path) always uses the global\n * dispatch — only `.exec(target)` overrides.\n */\n async exec(target?: IDataset): Promise<Result> {\n return this._run(target, true) as Promise<Result>;\n }\n\n /**\n * Shared execution path for {@link exec} and {@link exists}.\n *\n * @param swallowUnresolvedContext When true (the `exec` path), a where-clause\n * context reference that has not resolved yet surfaces as `null` — \"not ready\",\n * which a reactive layer re-runs once the context lands. `exists()` passes\n * false: it must not turn \"could not ask\" into a boolean.\n */\n private async _run(\n target: IDataset | undefined,\n swallowUnresolvedContext: boolean,\n ): Promise<unknown> {\n if (this._nullSubject) {\n // .for(null/undefined) was called — return null instead of executing a broken query.\n return null;\n }\n if (this._pendingContextName && !this._subject?.id) {\n // Pending context hasn't resolved yet — return null rather than querying without a subject.\n return null;\n }\n // Dispatch the live (closed) query; the dataset decides whether to lower it.\n // `async` ensures a missing global dispatch surfaces as a rejected promise, not a sync throw.\n const dispatch = target ?? getQueryDispatch();\n try {\n return await dispatch.selectQuery(this);\n } catch (err) {\n // A where-clause context reference that hasn't resolved yet surfaces as\n // UnresolvedContextError when the dataset lowers the query. For SELECT this\n // means \"not ready\" — return null (a reactive layer re-runs once it lands),\n // mirroring the pending-subject behavior. Mutations still throw.\n if (swallowUnresolvedContext && isLinkedError(err, UnresolvedContextError)) {\n return null;\n }\n // The message names the query, which is what a human needs. `cause` keeps\n // the ORIGINAL error reachable as an object, which is what code needs: a\n // store error's status/endpoint/class is how a caller tells \"this dataset\n // does not exist\" from \"this query is wrong\", and without the chain the\n // only way left is to pattern-match this string. Written with\n // defineProperty rather than `new Error(msg, {cause})` because this\n // package targets es6, where that overload is not typed; the property\n // shape (own, non-enumerable) is identical.\n const wrapped = Error(`Error while executing query: ${(err as Error).stack}.\\n\\nQuery related to this error: ${JSON.stringify(this.toJSON())}`);\n Object.defineProperty(wrapped, 'cause', {\n value: err,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n throw wrapped;\n }\n }\n\n\n /**\n * Go live: subscribe to this query and keep its result current.\n *\n * Returns a {@link LiveQuery} handle. `await` it for the first result,\n * `subscribe()` for every later one, `close()` when done. A listener may be\n * passed directly as the first argument. Requires the live-query store to be\n * loaded, which importing `@_linked/core` (the package root) does.\n */\n live<R = Result>(listenerOrOptions?: LiveListener<R> | LiveQueryOptions, options?: LiveQueryOptions): LiveQuery<R> {\n const listener = typeof listenerOrOptions === 'function' ? listenerOrOptions : undefined;\n const opts = typeof listenerOrOptions === 'function' ? options : listenerOrOptions;\n return requireLiveQueryStore().subscribe<R>(this as any, listener, opts);\n }\n\n // ---------------------------------------------------------------------------\n // Promise-compatible interface\n // ---------------------------------------------------------------------------\n\n /** `await` triggers execution. */\n then<TResult1 = Result, TResult2 = never>(\n onfulfilled?: ((value: Result) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.exec().then(onfulfilled, onrejected);\n }\n\n /** Catch errors from execution. Chain off then() to avoid re-executing. */\n catch<TResult = never>(\n onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null,\n ): Promise<Result | TResult> {\n return this.then().catch(onrejected);\n }\n\n /** Finally handler after execution. Chain off then() to avoid re-executing. */\n finally(onfinally?: (() => void) | null): Promise<Result> {\n return this.then().finally(onfinally);\n }\n\n get [Symbol.toStringTag](): string {\n return 'SelectBuilder';\n }\n}\n\n/** @deprecated Renamed to `SelectBuilder`. This alias will be removed in a future major. */\nexport {SelectBuilder as QueryBuilder};\n"]}
@@ -1,5 +1,6 @@
1
1
  import { QueryShape } from './SelectQuery.js';
2
2
  import { Shape, createShapeTarget } from '../shapes/Shape.js';
3
+ import { brandLinkedError } from '../utils/linkedError.js';
3
4
  const queryContext = new Map();
4
5
  /**
5
6
  * A live reference returned by getQueryContext when the context hasn't been set yet.
@@ -29,6 +30,7 @@ export class UnresolvedContextError extends Error {
29
30
  this.name = 'UnresolvedContextError';
30
31
  }
31
32
  }
33
+ brandLinkedError(UnresolvedContextError, '@_linked/core', 'UnresolvedContextError');
32
34
  const contextListeners = new Set();
33
35
  /**
34
36
  * Subscribe to query-context changes. Returns an unsubscribe function.
@@ -1 +1 @@
1
- {"version":3,"file":"QueryContext.js","sourceRoot":"","sources":["../../../src/queries/QueryContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAC,KAAK,EAAE,iBAAiB,EAAC,MAAM,oBAAoB,CAAC;AAE5D,MAAM,YAAY,GAAG,IAAI,GAAG,EAAiC,CAAC;AAE9D;;;;GAIG;AACH,MAAM,OAAO,mBAAmB;IAC9B,YAA4B,WAAmB;QAAnB,gBAAW,GAAX,WAAW,CAAQ;IAAG,CAAC;IAEnD,IAAI,EAAE;;QACJ,OAAO,MAAA,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,0CAAE,EAAE,CAAC;IAChD,CAAC;CACF;AAED;;;;;;GAMG;AACH,MAAM,OAAO,sBAAuB,SAAQ,KAAK;IAC/C,YAA4B,WAAmB;QAC7C,KAAK,CACH,kBAAkB,WAAW,0DAA0D,CACxF,CAAC;QAHwB,gBAAW,GAAX,WAAW,CAAQ;QAI7C,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAC;IACvC,CAAC;CACF;AAID,MAAM,gBAAgB,GAAG,IAAI,GAAG,EAAwB,CAAC;AAEzD;;;;;;;;;GASG;AACH,MAAM,UAAU,qBAAqB,CAAC,QAA8B;IAClE,gBAAgB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC/B,OAAO,GAAG,EAAE,CAAC,gBAAgB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACj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AAgB,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;QAC5D,KAAK,CAAC,gBAAgB,GAAG,KAAK,CAAC,EAAE,CAAC;QAClC,KAAK,CAAC,kBAAkB,GAAG,IAAI,CAAC;QAChC,YAAY,CAAC,GAAG,CAAC,IAAI,EAAE,UAAU,CAAC,MAAM,CAAC,KAAK,CAAQ,CAAC,CAAC;QACxD,mBAAmB,CAAC,IAAI,CAAC,CAAC;QAC1B,OAAO;IACT,CAAC;IAED,MAAM,IAAI,KAAK,CACb,oBAAoB,IAAI,6DAA6D,OAAO,KAAK,wFAAwF,CAC1L,CAAC;AACJ,CAAC","sourcesContent":["import {type QShape, QueryShape} from './SelectQuery.js';\nimport {Shape, createShapeTarget} from '../shapes/Shape.js';\n\nconst queryContext = new Map<string, QShape<any, any, any>>();\n\n/**\n * A live reference returned by getQueryContext when the context hasn't been set yet.\n * Its `id` getter resolves lazily from the global context map, so queries built with\n * a PendingQueryContext will pick up the value once it's set (e.g. after auth completes).\n */\nexport class PendingQueryContext {\n constructor(public readonly contextName: string) {}\n\n get id(): string | undefined {\n return queryContext.get(this.contextName)?.id;\n }\n}\n\n/**\n * Thrown when a query carrying a context reference is lowered but the context\n * isn't set in the current process. A context ref is carried in DSL-JSON and\n * resolves at lowering time against whatever context map is available (e.g.\n * server-side auth); if it can't resolve, lowering throws this rather than\n * silently producing a subject-less query.\n */\nexport class UnresolvedContextError extends Error {\n constructor(public readonly contextName: string) {\n super(\n `Query context \"${contextName}\" is not set and could not be resolved at lowering time.`,\n );\n this.name = 'UnresolvedContextError';\n }\n}\n\n/** Listener notified (with the changed context name) whenever a context is set or cleared. */\nexport type QueryContextListener = (name: string) => void;\nconst contextListeners = new Set<QueryContextListener>();\n\n/**\n * Subscribe to query-context changes. Returns an unsubscribe function.\n *\n * This is the primitive that makes context resolution reactive: a consuming layer\n * (e.g. React components) subscribes and re-runs affected queries when the context\n * lands — so a query that resolved to `null` while the context was unset simply\n * re-runs and resolves once it's available (\"waiting\"), and re-runs again on any\n * later change (\"auto re-resolve\"). Core only emits the change; re-execution is the\n * consumer's responsibility.\n */\nexport function subscribeQueryContext(listener: QueryContextListener): () => void {\n contextListeners.add(listener);\n return () => contextListeners.delete(listener);\n}\n\nfunction notifyContextChange(name: string): void {\n // Snapshot so a listener that (un)subscribes or re-sets a context during\n // notification can't mutate the set mid-iteration.\n for (const listener of [...contextListeners]) {\n try {\n listener(name);\n } catch (err) {\n // A listener must never break setQueryContext for the others.\n console.error('[linked] query context listener failed', err);\n }\n }\n}\n\n/**\n * Normalize any query-context value to a {@link PendingQueryContext} carrying its name,\n * or return `undefined` if the value is not a context reference.\n *\n * A context appears in two runtime forms: a `PendingQueryContext` (the context was unset\n * when `getQueryContext()` was called) or a resolved `QueryShape` stamped with\n * `__queryContextName` (it was already set). Both must be treated as the same `{@ctx}`\n * reference wherever a node value/id is accepted (mutation field values, delete ids), so\n * that context-bound mutations behave identically whether the context is set or unset at\n * build time — resolution always happens at lowering.\n */\nexport function asContextRef(value: unknown): PendingQueryContext | undefined {\n if (value instanceof PendingQueryContext) return value;\n if (!value || typeof value !== 'object') return undefined;\n // A resolved context is a QueryShape proxy wrapping a Shape stamped with\n // `__queryContextName`. Read it via `originalValue` (a known QueryShape field)\n // so we don't trip the proxy's \"undecorated property\" guard (it now throws);\n // a bare Shape\n // carries the stamp directly.\n const v = value as {originalValue?: {__queryContextName?: unknown}; __queryContextName?: unknown};\n const source = v.originalValue ?? v;\n const name = (source as {__queryContextName?: unknown}).__queryContextName;\n if (typeof name === 'string') return new PendingQueryContext(name);\n return undefined;\n}\n\nexport function getQueryContext<T extends Shape>(name: string): QShape<T> {\n if (queryContext.has(name)) {\n return queryContext.get(name);\n }\n // Return a live reference that resolves lazily when the context is set.\n // This avoids the timing issue where module-level queries capture null\n // because the context hasn't been set yet (e.g. useEffect hasn't fired).\n return new PendingQueryContext(name) as any;\n}\n\nexport function setQueryContext(name: string, value: any, shapeType?) {\n // Clearing a context entry\n if (!value) {\n queryContext.delete(name);\n notifyContextChange(name);\n return;\n }\n\n // Already a QShape — stamp the underlying shape and store as-is. (Checked before\n // the plain-`{id}` branch below: a QueryShape's `.id` getter is also a string, so\n // testing for `{id}` first would wrongly require a shapeType and no-op.)\n if (value instanceof QueryShape) {\n const orig = (value as any).originalValue;\n if (orig) {\n orig.__queryContextName = name;\n if (typeof orig.id === 'string') orig.__queryContextId = orig.id;\n }\n queryContext.set(name, value as any);\n notifyContextChange(name);\n return;\n }\n\n // A Shape-shaped value (e.g. a `createShapeTarget` proxy target) — stamp it and\n // wrap as a QShape. Needs no shapeType (it already carries its shape class).\n if (value instanceof Shape) {\n value.__queryContextName = name;\n if (typeof value.id === 'string') value.__queryContextId = value.id;\n queryContext.set(name, new QueryShape(value) as any);\n notifyContextChange(name);\n return;\n }\n\n // A plain QResult `{id}` — materialize a shape (requires shapeType).\n if (typeof value.id === 'string') {\n if (!shapeType) {\n // A silent no-op here is a trap: the context never sets and the caller\n // gets no signal. A `{id}` value cannot be materialized without its shape.\n throw new Error(\n `setQueryContext('${name}'): a {id} value requires a shapeType so the shape can be materialized. Pass the Shape class as the third argument.`,\n );\n }\n const shape = createShapeTarget(shapeType as any, value.id);\n shape.__queryContextId = value.id;\n shape.__queryContextName = name;\n queryContext.set(name, QueryShape.create(shape) as any);\n notifyContextChange(name);\n return;\n }\n\n throw new Error(\n `setQueryContext('${name}'): value is not a QueryShape, Shape, or {id} result. Got ${typeof value}. Pass a Shape instance, a query-context shape, or a {id} result (with its shapeType).`,\n );\n}\n"]}
1
+ {"version":3,"file":"QueryContext.js","sourceRoot":"","sources":["../../../src/queries/QueryContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAC,KAAK,EAAE,iBAAiB,EAAC,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAC,gBAAgB,EAAC,MAAM,yBAAyB,CAAC;AAEzD,MAAM,YAAY,GAAG,IAAI,GAAG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eTarget} from '../shapes/Shape.js';\nimport {brandLinkedError} from '../utils/linkedError.js';\n\nconst queryContext = new Map<string, QShape<any, any, any>>();\n\n/**\n * A live reference returned by getQueryContext when the context hasn't been set yet.\n * Its `id` getter resolves lazily from the global context map, so queries built with\n * a PendingQueryContext will pick up the value once it's set (e.g. after auth completes).\n */\nexport class PendingQueryContext {\n constructor(public readonly contextName: string) {}\n\n get id(): string | undefined {\n return queryContext.get(this.contextName)?.id;\n }\n}\n\n/**\n * Thrown when a query carrying a context reference is lowered but the context\n * isn't set in the current process. A context ref is carried in DSL-JSON and\n * resolves at lowering time against whatever context map is available (e.g.\n * server-side auth); if it can't resolve, lowering throws this rather than\n * silently producing a subject-less query.\n */\nexport class UnresolvedContextError extends Error {\n constructor(public readonly contextName: string) {\n super(\n `Query context \"${contextName}\" is not set and could not be resolved at lowering time.`,\n );\n this.name = 'UnresolvedContextError';\n }\n}\nbrandLinkedError(UnresolvedContextError, '@_linked/core', 'UnresolvedContextError');\n\n/** Listener notified (with the changed context name) whenever a context is set or cleared. */\nexport type QueryContextListener = (name: string) => void;\nconst contextListeners = new Set<QueryContextListener>();\n\n/**\n * Subscribe to query-context changes. Returns an unsubscribe function.\n *\n * This is the primitive that makes context resolution reactive: a consuming layer\n * (e.g. React components) subscribes and re-runs affected queries when the context\n * lands — so a query that resolved to `null` while the context was unset simply\n * re-runs and resolves once it's available (\"waiting\"), and re-runs again on any\n * later change (\"auto re-resolve\"). Core only emits the change; re-execution is the\n * consumer's responsibility.\n */\nexport function subscribeQueryContext(listener: QueryContextListener): () => void {\n contextListeners.add(listener);\n return () => contextListeners.delete(listener);\n}\n\nfunction notifyContextChange(name: string): void {\n // Snapshot so a listener that (un)subscribes or re-sets a context during\n // notification can't mutate the set mid-iteration.\n for (const listener of [...contextListeners]) {\n try {\n listener(name);\n } catch (err) {\n // A listener must never break setQueryContext for the others.\n console.error('[linked] query context listener failed', err);\n }\n }\n}\n\n/**\n * Normalize any query-context value to a {@link PendingQueryContext} carrying its name,\n * or return `undefined` if the value is not a context reference.\n *\n * A context appears in two runtime forms: a `PendingQueryContext` (the context was unset\n * when `getQueryContext()` was called) or a resolved `QueryShape` stamped with\n * `__queryContextName` (it was already set). Both must be treated as the same `{@ctx}`\n * reference wherever a node value/id is accepted (mutation field values, delete ids), so\n * that context-bound mutations behave identically whether the context is set or unset at\n * build time — resolution always happens at lowering.\n */\nexport function asContextRef(value: unknown): PendingQueryContext | undefined {\n if (value instanceof PendingQueryContext) return value;\n if (!value || typeof value !== 'object') return undefined;\n // A resolved context is a QueryShape proxy wrapping a Shape stamped with\n // `__queryContextName`. Read it via `originalValue` (a known QueryShape field)\n // so we don't trip the proxy's \"undecorated property\" guard (it now throws);\n // a bare Shape\n // carries the stamp directly.\n const v = value as {originalValue?: {__queryContextName?: unknown}; __queryContextName?: unknown};\n const source = v.originalValue ?? v;\n const name = (source as {__queryContextName?: unknown}).__queryContextName;\n if (typeof name === 'string') return new PendingQueryContext(name);\n return undefined;\n}\n\nexport function getQueryContext<T extends Shape>(name: string): QShape<T> {\n if (queryContext.has(name)) {\n return queryContext.get(name);\n }\n // Return a live reference that resolves lazily when the context is set.\n // This avoids the timing issue where module-level queries capture null\n // because the context hasn't been set yet (e.g. useEffect hasn't fired).\n return new PendingQueryContext(name) as any;\n}\n\nexport function setQueryContext(name: string, value: any, shapeType?) {\n // Clearing a context entry\n if (!value) {\n queryContext.delete(name);\n notifyContextChange(name);\n return;\n }\n\n // Already a QShape — stamp the underlying shape and store as-is. (Checked before\n // the plain-`{id}` branch below: a QueryShape's `.id` getter is also a string, so\n // testing for `{id}` first would wrongly require a shapeType and no-op.)\n if (value instanceof QueryShape) {\n const orig = (value as any).originalValue;\n if (orig) {\n orig.__queryContextName = name;\n if (typeof orig.id === 'string') orig.__queryContextId = orig.id;\n }\n queryContext.set(name, value as any);\n notifyContextChange(name);\n return;\n }\n\n // A Shape-shaped value (e.g. a `createShapeTarget` proxy target) — stamp it and\n // wrap as a QShape. Needs no shapeType (it already carries its shape class).\n if (value instanceof Shape) {\n value.__queryContextName = name;\n if (typeof value.id === 'string') value.__queryContextId = value.id;\n queryContext.set(name, new QueryShape(value) as any);\n notifyContextChange(name);\n return;\n }\n\n // A plain QResult `{id}` — materialize a shape (requires shapeType).\n if (typeof value.id === 'string') {\n if (!shapeType) {\n // A silent no-op here is a trap: the context never sets and the caller\n // gets no signal. A `{id}` value cannot be materialized without its shape.\n throw new Error(\n `setQueryContext('${name}'): a {id} value requires a shapeType so the shape can be materialized. Pass the Shape class as the third argument.`,\n );\n }\n const shape = createShapeTarget(shapeType as any, value.id);\n shape.__queryContextId = value.id;\n shape.__queryContextName = name;\n queryContext.set(name, QueryShape.create(shape) as any);\n notifyContextChange(name);\n return;\n }\n\n throw new Error(\n `setQueryContext('${name}'): value is not a QueryShape, Shape, or {id} result. Got ${typeof value}. Pass a Shape instance, a query-context shape, or a {id} result (with its shapeType).`,\n );\n}\n"]}
@@ -10,6 +10,7 @@ import { FieldSet } from './FieldSet.js';
10
10
  import { PropertyPath } from './PropertyPath.js';
11
11
  import { ExpressionNode, ExistsCondition, isExpressionNode, isExistsCondition, tracedPropertyExpression, tracedAliasExpression } from '../expressions/ExpressionNode.js';
12
12
  import { PendingQueryContext } from './QueryContext.js';
13
+ import { unresolvedValueShapeError } from '../utils/unresolvedShape.js';
13
14
  /**
14
15
  * String keys the query-shape proxy must let through *without* treating them as
15
16
  * a property access — promise-awaiting (`then`), React (`$$typeof`), and common
@@ -78,7 +79,7 @@ export class QueryBuilderObject {
78
79
  // but Im not sure if that's even possible with dynamic import paths, that are only known at runtime
79
80
  //UPDATE: we should not need to load shapeclasses. We just need to be able to access shapes.
80
81
  // but the problem remains that the ImageObject shape needs to be available, but thats easier, as its data
81
- throw new Error(`Shape class not found for ${valueShape.id}`);
82
+ throw unresolvedValueShapeError(`Shape class not found for ${valueShape.id}`, property);
82
83
  }
83
84
  const shapeValue = createShapeTarget(shapeClass);
84
85
  if (singleValue) {
@@ -375,6 +376,10 @@ export class QueryShapeSet extends QueryBuilderObject {
375
376
  if (!valueShape && ((_a = queryShapeSet.property) === null || _a === void 0 ? void 0 : _a.valueShape)) {
376
377
  const shapeClass = getQueryShapeClass(queryShapeSet.property.valueShape);
377
378
  valueShape = shapeClass === null || shapeClass === void 0 ? void 0 : shapeClass.shape;
379
+ if (!valueShape) {
380
+ // Not an undecorated key: the set's shape itself is missing.
381
+ throw unresolvedValueShapeError(`Shape class not found for ${queryShapeSet.property.valueShape.id}`, queryShapeSet.property);
382
+ }
378
383
  }
379
384
  let propertyShape = valueShape
380
385
  ? getPropertyShapes(valueShape, true).find((propertyShape) => propertyShape.label === key)