cvx-kit 0.1.23 → 0.1.25

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.
@@ -1 +1 @@
1
- {"version":3,"file":"filters.mjs","names":["MAX_FILTER_DEPTH","MAX_FILTER_NODES","MAX_FILTER_IN_VALUES","relationPredicates","variantPredicates","filterGrammars","compactFilters","compactFilterMetadata","entry","schema","relationFilterSchema","options","captured","captureGrammar","grammar","error","UnsupportedFilterCapture","boundedObject","filterNodeSchema","cache","semantic","paginationGrammar","z","filters","root","cached","name","predicate","relation","normalizeFilters","children","value","expression","child","scoped","field","scalar","normalizeScalar","target","scalarPredicateFromSchema","equality","ranged","range","existence","optional","boundedFilterSchema","predicates","depth","direct","key","relations","tag","branch","node","result","depths","withinFilterBudget","pending","nodes","object","array","prototype","keys","consumed","descriptor","context","operator","expected","definition","expectedCatchall","inst","def","metadata","parse","payload","ctx","seen","source","schemas","copy","k","v","checks","check","copied"],"sources":["../../../src/querying/shared/filters.ts"],"sourcesContent":["import { z } from 'zod'\nimport type { FilterAst, FilterScalar, FilterOperator } from './ast'\nexport const MAX_FILTER_DEPTH = 4\nexport const MAX_FILTER_NODES = 256\nexport const MAX_FILTER_IN_VALUES = 100\nexport type FieldSchemas = Record<string, z.ZodType>\nexport type FilterTree =\n\t| string\n\t| number\n\t| bigint\n\t| boolean\n\t| null\n\t| undefined\n\t| FilterTree[]\n\t| { [key: string]: FilterTree }\n\n// Compose Zod's exported core constructor with its ordinary object initializer.\n// Clones use this constructor again, preserving preflight without replacing the\n// converter-recognized object definition or any native scalar/ID validators.\nconst relationPredicates = new WeakMap<\n\tz.core.$ZodType,\n\t{ cardinality: 'one' | 'many'; target: FilterGrammar }\n>()\nconst variantPredicates = new WeakMap<z.core.$ZodType, NonNullable<FilterGrammar['variants']>>()\nconst filterGrammars = new WeakMap<z.core.$ZodType, FilterGrammar>()\n\nexport interface PaginationValidatorOptions {\n\tvalidator: 'compact'\n}\n\nexport interface FilterBoundaryMetadata {\n\treadonly grammar: FilterGrammar\n\treadonly semantic: z.ZodType\n}\nconst compactFilters = new WeakMap<\n\tz.core.$ZodType,\n\t{\n\t\tmetadata: FilterBoundaryMetadata\n\t\tmatches(): boolean\n\t}\n>()\n\n/** Only constructors created here can carry permission to project a filter. */\nexport function compactFilterMetadata(schema: z.core.$ZodType): FilterBoundaryMetadata | undefined {\n\tconst entry = compactFilters.get(schema)\n\treturn entry?.matches() ? entry.metadata : undefined\n}\n\n/** Each boolean child and relation target expression consumes one of four edges.\n * some/none wrappers and fields namespaces consume nodes, but no extra depth.\n */\nexport interface FilterGrammar {\n\tfields: FieldSchemas\n\tvariants?: { discriminator: string; options: Record<string, FilterGrammar> }\n\trelations: Record<string, { cardinality: 'one' | 'many'; target: FilterGrammar }>\n}\n\nexport function relationFilterSchema(\n\tgrammar: FilterGrammar,\n\tcache = new WeakMap<FilterGrammar, Map<number, z.ZodObject>>(),\n\toptions?: PaginationValidatorOptions,\n): z.ZodType {\n\tif (options?.validator === 'compact') {\n\t\tlet captured: FilterGrammar\n\t\ttry {\n\t\t\tcaptured = captureGrammar(grammar)\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof UnsupportedFilterCapture)) throw error\n\t\t\treturn boundedObject(filterNodeSchema(grammar, 0, cache)._zod.def, grammar)\n\t\t}\n\t\tconst semantic = boundedObject(filterNodeSchema(captured, 0)._zod.def, captured)\n\t\treturn boundedObject(\n\t\t\tfilterNodeSchema(grammar, 0, cache)._zod.def,\n\t\t\tcaptured,\n\t\t\tObject.freeze({ grammar: captured, semantic }),\n\t\t)\n\t}\n\treturn boundedObject(filterNodeSchema(grammar, 0, cache)._zod.def, grammar)\n}\n\nexport function paginationGrammar(schema: z.ZodType): FilterGrammar | undefined {\n\tif (!(schema instanceof z.ZodObject)) return undefined\n\tconst filters = schema.shape.filters\n\tif (!(filters instanceof z.ZodOptional)) return undefined\n\tconst root = filters.unwrap()\n\tconst cached = filterGrammars.get(root)\n\tif (cached) return cached\n\tif (!(root instanceof z.ZodObject)) return undefined\n\treturn {\n\t\tfields: root.shape,\n\t\tvariants: variantPredicates.get(root.shape.variant),\n\t\trelations: Object.fromEntries(\n\t\t\tObject.entries(root.shape).flatMap(([name, predicate]) => {\n\t\t\t\t// SAFETY: object shapes contain Zod schemas; metadata only recognizes predicates created by our grammar.\n\t\t\t\tconst relation = relationPredicates.get(predicate as z.core.$ZodType)\n\t\t\t\treturn relation ? [[name, relation]] : []\n\t\t\t}),\n\t\t),\n\t}\n}\nexport function normalizeFilters(value: FilterTree, grammar?: FilterGrammar): FilterAst {\n\tconst children: FilterAst[] = []\n\tif (!value) return { kind: 'and', children }\n\t// SAFETY: the caller parsed a strict filter object; its grammar has no array/primitive expression.\n\tconst expression = value as Record<string, FilterTree>\n\tfor (const [name, predicate] of Object.entries(expression)) {\n\t\tif (predicate === undefined) continue\n\t\tif (name === 'and' || name === 'or') {\n\t\t\t// SAFETY: boolean composition is validated as an array of expressions.\n\t\t\tchildren.push({\n\t\t\t\tkind: name,\n\t\t\t\tchildren: (predicate as FilterTree[]).map((child) => normalizeFilters(child, grammar)),\n\t\t\t})\n\t\t} else if (name === 'variant' && grammar?.variants) {\n\t\t\t// SAFETY: strict branch grammar validates the literal tag and its selected target filters.\n\t\t\tconst scoped = predicate as { tag: string; filters: FilterTree }\n\t\t\tchildren.push({\n\t\t\t\tkind: 'variant',\n\t\t\t\tdiscriminator: grammar.variants.discriminator,\n\t\t\t\ttag: scoped.tag,\n\t\t\t\tchild: normalizeFilters(scoped.filters, grammar.variants.options[scoped.tag]),\n\t\t\t})\n\t\t} else if (name === 'not')\n\t\t\tchildren.push({ kind: 'not', child: normalizeFilters(predicate, grammar) })\n\t\telse if (name === 'fields') {\n\t\t\t// SAFETY: fields is a strict selected scalar namespace.\n\t\t\tfor (const [field, scalar] of Object.entries(predicate as Record<string, FilterTree>))\n\t\t\t\tchildren.push(...normalizeScalar(field, scalar))\n\t\t} else if (grammar?.relations[name]) {\n\t\t\tconst relation = grammar.relations[name]\n\t\t\tif (relation.cardinality === 'one')\n\t\t\t\tchildren.push({\n\t\t\t\t\tkind: 'relation',\n\t\t\t\t\tname,\n\t\t\t\t\tmode: 'one',\n\t\t\t\t\tpredicate: predicate === null ? null : normalizeFilters(predicate, relation.target),\n\t\t\t\t})\n\t\t\telse {\n\t\t\t\t// SAFETY: many predicates validate as exactly one some/none target expression.\n\t\t\t\tconst target = predicate as { some?: FilterTree; none?: FilterTree }\n\t\t\t\tchildren.push({\n\t\t\t\t\tkind: 'relation',\n\t\t\t\t\tname,\n\t\t\t\t\tmode: target.some === undefined ? 'none' : 'some',\n\t\t\t\t\tpredicate: normalizeFilters(target.some ?? target.none, relation.target),\n\t\t\t\t})\n\t\t\t}\n\t\t} else children.push(...normalizeScalar(name, predicate))\n\t}\n\treturn { kind: 'and', children }\n}\nexport function scalarPredicateFromSchema(\n\tscalar: z.ZodType,\n\trange: boolean,\n\toptional: boolean,\n): z.ZodType {\n\tconst equality = z.object({\n\t\teq: scalar.optional(),\n\t\tin: z.array(scalar).max(MAX_FILTER_IN_VALUES).optional(),\n\t})\n\tconst ranged = range\n\t\t? equality.extend({\n\t\t\t\tgt: scalar.optional(),\n\t\t\t\tgte: scalar.optional(),\n\t\t\t\tlt: scalar.optional(),\n\t\t\t\tlte: scalar.optional(),\n\t\t\t})\n\t\t: equality\n\tconst existence = optional ? ranged.extend({ exists: z.boolean().optional() }) : ranged\n\treturn z.union([\n\t\tscalar,\n\t\texistence\n\t\t\t.strict()\n\t\t\t.refine(\n\t\t\t\t(value) => Object.values(value).some((entry) => entry !== undefined),\n\t\t\t\t'At least one operator is required',\n\t\t\t),\n\t])\n}\n\nexport function boundedFilterSchema(\n\tpredicates: FieldSchemas,\n\toptions?: PaginationValidatorOptions,\n): z.ZodType {\n\treturn relationFilterSchema({ fields: predicates, relations: {} }, undefined, options)\n}\n\nfunction filterNodeSchema(\n\tgrammar: FilterGrammar,\n\tdepth: number,\n\tcache = new WeakMap<FilterGrammar, Map<number, z.ZodObject>>(),\n): z.ZodObject {\n\tconst cached = cache.get(grammar)?.get(depth)\n\tif (cached) return cached\n\tconst predicates = grammar.fields\n\tconst direct = Object.fromEntries(\n\t\tObject.entries(predicates).filter(\n\t\t\t([key]) =>\n\t\t\t\t!['and', 'or', 'not', 'fields', ...(grammar.variants ? ['variant'] : [])].includes(key),\n\t\t),\n\t)\n\tconst relations: FieldSchemas = {}\n\tfor (const [name, relation] of Object.entries(grammar.relations)) {\n\t\tif (depth === MAX_FILTER_DEPTH) continue\n\t\tconst target = filterNodeSchema(relation.target, depth + 1, cache)\n\t\trelations[name] = (\n\t\t\trelation.cardinality === 'one'\n\t\t\t\t? target.nullable()\n\t\t\t\t: z.union([z.object({ some: target }).strict(), z.object({ none: target }).strict()])\n\t\t).optional()\n\t\trelationPredicates.set(relations[name], relation)\n\t}\n\tif (grammar.variants && depth < MAX_FILTER_DEPTH) {\n\t\tconst options = Object.entries(grammar.variants.options).map(([tag, branch]) =>\n\t\t\tz.strictObject({ tag: z.literal(tag), filters: filterNodeSchema(branch, depth + 1, cache) }),\n\t\t)\n\t\tif (options.length) {\n\t\t\trelations.variant = z.union(options).optional()\n\t\t\tvariantPredicates.set(relations.variant, grammar.variants)\n\t\t}\n\t}\n\tconst node = z\n\t\t.object({ ...direct, ...relations, fields: z.object(predicates).strict().optional() })\n\t\t.strict()\n\tconst child = depth === MAX_FILTER_DEPTH ? undefined : filterNodeSchema(grammar, depth + 1, cache)\n\tconst result = child\n\t\t? node.extend({\n\t\t\t\tand: z.array(child).min(1).max(MAX_FILTER_NODES).optional(),\n\t\t\t\tor: z.array(child).min(1).max(MAX_FILTER_NODES).optional(),\n\t\t\t\tnot: child.optional(),\n\t\t\t})\n\t\t: node\n\tlet depths = cache.get(grammar)\n\tif (!depths) {\n\t\tdepths = new Map()\n\t\tcache.set(grammar, depths)\n\t}\n\tdepths.set(depth, result)\n\treturn result\n}\n\nfunction withinFilterBudget(value: FilterTree, grammar: FilterGrammar): boolean {\n\ttype Context =\n\t\t| 'expression'\n\t\t| 'fields'\n\t\t| 'predicate'\n\t\t| 'composition'\n\t\t| 'many'\n\t\t| 'variant'\n\t\t| 'value'\n\tinterface Entry {\n\t\tvalue: FilterTree\n\t\tdepth: number\n\t\tcontext: Context\n\t\tgrammar: FilterGrammar\n\t}\n\tconst pending: Entry[] = [{ value, depth: 0, context: 'expression', grammar }]\n\tlet nodes = 0\n\twhile (pending.length) {\n\t\tconst entry = pending.pop()!\n\t\tif (++nodes > MAX_FILTER_NODES || entry.depth > MAX_FILTER_DEPTH) return false\n\t\tif (Object(entry.value) !== entry.value) continue\n\t\t// SAFETY: boxing excludes null and primitives; descriptors below avoid invoking getters.\n\t\tconst object = entry.value as FilterTree[] | Record<string, FilterTree>\n\t\tconst array = Array.isArray(object) ? object : undefined\n\t\tconst prototype = Object.getPrototypeOf(object)\n\t\tif (\n\t\t\tarray ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null\n\t\t)\n\t\t\treturn false\n\t\tif (array && array.length + nodes + pending.length > MAX_FILTER_NODES) return false\n\t\tconst keys = Reflect.ownKeys(object)\n\t\tif (\n\t\t\tkeys.length - (array ? 1 : 0) + nodes + pending.length > MAX_FILTER_NODES ||\n\t\t\t(array && keys.length !== array.length + 1)\n\t\t)\n\t\t\treturn false\n\t\tlet consumed: string[]\n\t\tswitch (entry.context) {\n\t\t\tcase 'expression':\n\t\t\t\tconsumed = [\n\t\t\t\t\t...Object.keys(entry.grammar.fields),\n\t\t\t\t\t...Object.keys(entry.grammar.relations),\n\t\t\t\t\t'and',\n\t\t\t\t\t'or',\n\t\t\t\t\t'not',\n\t\t\t\t\t'fields',\n\t\t\t\t\t...(entry.grammar.variants ? ['variant'] : []),\n\t\t\t\t]\n\t\t\t\tbreak\n\t\t\tcase 'variant':\n\t\t\t\tconsumed = ['tag', 'filters']\n\t\t\t\tbreak\n\t\t\tcase 'fields':\n\t\t\t\tconsumed = Object.keys(entry.grammar.fields)\n\t\t\t\tbreak\n\t\t\tcase 'predicate':\n\t\t\t\tconsumed = ['eq', 'in', 'gt', 'gte', 'lt', 'lte', 'exists']\n\t\t\t\tbreak\n\t\t\tcase 'many':\n\t\t\t\tconsumed = ['some', 'none']\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tconsumed = []\n\t\t}\n\t\tfor (const key of consumed) if (!Object.hasOwn(object, key) && key in object) return false\n\t\tfor (const key of keys) {\n\t\t\tif (array && key === 'length') continue\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(object, key)!\n\t\t\tconst name = String(key)\n\t\t\tif (!descriptor.enumerable || !('value' in descriptor) || name !== key) return false\n\t\t\tif (array && (!/^(0|[1-9]\\d*)$/.test(name) || Number(name) >= array.length)) return false\n\t\t\tlet context: Context = 'value'\n\t\t\tlet depth = entry.depth\n\t\t\tlet target = entry.grammar\n\t\t\tif (entry.context === 'expression') {\n\t\t\t\tcontext = 'predicate'\n\t\t\t\tif (name === 'variant' && entry.grammar.variants) {\n\t\t\t\t\tcontext = 'variant'\n\t\t\t\t\tdepth++\n\t\t\t\t} else if (name === 'fields') context = 'fields'\n\t\t\t\telse if (name === 'and' || name === 'or') {\n\t\t\t\t\tcontext = 'composition'\n\t\t\t\t\tdepth++\n\t\t\t\t} else if (name === 'not') {\n\t\t\t\t\tcontext = 'expression'\n\t\t\t\t\tdepth++\n\t\t\t\t} else if (entry.grammar.relations[name]) {\n\t\t\t\t\tconst relation = entry.grammar.relations[name]\n\t\t\t\t\tcontext = relation.cardinality === 'one' ? 'expression' : 'many'\n\t\t\t\t\ttarget = relation.target\n\t\t\t\t\tdepth++\n\t\t\t\t}\n\t\t\t} else if (entry.context === 'variant' && name === 'filters') {\n\t\t\t\tconst tag = Object.getOwnPropertyDescriptor(object, 'tag')\n\t\t\t\tif (\n\t\t\t\t\t!tag ||\n\t\t\t\t\t!('value' in tag) ||\n\t\t\t\t\t!z.string().safeParse(tag.value).success ||\n\t\t\t\t\t!Object.hasOwn(entry.grammar.variants?.options ?? {}, tag.value)\n\t\t\t\t)\n\t\t\t\t\treturn false\n\t\t\t\tcontext = 'expression'\n\t\t\t\ttarget = entry.grammar.variants!.options[String(tag.value)]\n\t\t\t} else if (entry.context === 'fields') context = 'predicate'\n\t\t\telse if (entry.context === 'composition' || entry.context === 'many') context = 'expression'\n\t\t\tpending.push({ value: descriptor.value, depth, context, grammar: target })\n\t\t}\n\t}\n\treturn true\n}\nfunction normalizeScalar(field: string, predicate: FilterTree): FilterAst[] {\n\tif (predicate === undefined) return []\n\tif (Object(predicate) !== predicate) {\n\t\t// SAFETY: native scalar grammar excludes object/array values and preserves branded ID strings.\n\t\treturn [{ kind: 'scalar', field, operator: 'eq', value: predicate as FilterScalar }]\n\t}\n\t// SAFETY: only selected supported scalar operator objects survive validation.\n\treturn Object.entries(predicate as Record<FilterOperator, FilterScalar | FilterScalar[]>)\n\t\t.filter(([, value]) => value !== undefined)\n\t\t.map(([operator, value]) => ({\n\t\t\tkind: 'scalar',\n\t\t\tfield,\n\t\t\toperator: operator as FilterOperator,\n\t\t\tvalue,\n\t\t}))\n}\n\nfunction boundedObject(\n\tdefinition: z.ZodObject['_zod']['def'],\n\tgrammar: FilterGrammar,\n\tmetadata?: FilterBoundaryMetadata,\n): z.ZodObject {\n\tconst expected = Object.entries(definition.shape)\n\tconst expectedCatchall = definition.catchall\n\tconst BoundedFilterObject = z.core.$constructor<z.ZodObject>(\n\t\t'BoundedFilterObject',\n\t\t(inst, def) => {\n\t\t\tz.ZodObject.init(inst, def)\n\t\t\tfilterGrammars.set(inst, grammar)\n\t\t\t// Clones/refinements retain the generated fields. Shape edits use full conversion.\n\t\t\tif (\n\t\t\t\tmetadata &&\n\t\t\t\tdef.catchall === expectedCatchall &&\n\t\t\t\tObject.keys(def.shape).length === expected.length &&\n\t\t\t\texpected.every(([key, value]) => def.shape[key] === value)\n\t\t\t)\n\t\t\t\tcompactFilters.set(inst, {\n\t\t\t\t\tmetadata,\n\t\t\t\t\tmatches: () =>\n\t\t\t\t\t\tinst._zod.def.catchall === expectedCatchall &&\n\t\t\t\t\t\tObject.keys(inst._zod.def.shape).length === expected.length &&\n\t\t\t\t\t\texpected.every(([key, value]) => inst._zod.def.shape[key] === value),\n\t\t\t\t})\n\t\t\tconst parse = inst._zod.parse\n\t\t\tinst._zod.parse = (payload, ctx) => {\n\t\t\t\t// SAFETY: layout preflight precedes Zod's value traversal.\n\t\t\t\tif (!withinFilterBudget(payload.value as FilterTree, grammar)) {\n\t\t\t\t\tpayload.issues.push({\n\t\t\t\t\t\tcode: 'custom',\n\t\t\t\t\t\tinput: payload.value,\n\t\t\t\t\t\tmessage: 'Unsupported filter layout or depth/node budget exceeded',\n\t\t\t\t\t})\n\t\t\t\t\treturn payload\n\t\t\t\t}\n\t\t\t\treturn parse(payload, ctx)\n\t\t\t}\n\t\t},\n\t)\n\treturn new BoundedFilterObject(definition)\n}\n\nclass UnsupportedFilterCapture extends Error {}\n\n// Copy the generated schema graph before exposing the public filter. These are\n// generated scalar predicates, not arbitrary storage schemas or consumer hooks.\nfunction captureGrammar(\n\tsource: FilterGrammar,\n\tseen = new WeakMap<FilterGrammar, FilterGrammar>(),\n): FilterGrammar {\n\tconst cached = seen.get(source)\n\tif (cached) return cached\n\tconst schemas = new WeakMap<z.ZodType, z.ZodType>()\n\tfunction copy(schema: z.core.$ZodType): z.ZodType {\n\t\tif (!(schema instanceof z.ZodType)) throw new Error('Expected generated classic filter schema')\n\t\tconst cached = schemas.get(schema)\n\t\tif (cached) return cached\n\t\tlet result: z.ZodType\n\t\tif (schema instanceof z.ZodObject)\n\t\t\tresult = schema.clone({\n\t\t\t\t...schema._zod.def,\n\t\t\t\t// oxlint-disable-next-line anti-slop/no-shape-in-symbol-names -- Installed Zod object definition property.\n\t\t\t\tshape: Object.fromEntries(Object.entries(schema.shape).map(([k, v]) => [k, copy(v)])),\n\t\t\t\tcatchall: schema._zod.def.catchall ? copy(schema._zod.def.catchall) : undefined,\n\t\t\t})\n\t\telse if (schema instanceof z.ZodUnion)\n\t\t\tresult = schema.clone({ ...schema._zod.def, options: schema.options.map(copy) })\n\t\telse if (schema instanceof z.ZodArray)\n\t\t\tresult = schema.clone({ ...schema._zod.def, element: copy(schema.element) })\n\t\telse if (schema instanceof z.ZodOptional)\n\t\t\tresult = schema.clone({ ...schema._zod.def, innerType: copy(schema._zod.def.innerType) })\n\t\telse if (schema instanceof z.ZodNonOptional)\n\t\t\tresult = schema.clone({ ...schema._zod.def, innerType: copy(schema._zod.def.innerType) })\n\t\telse if (schema instanceof z.ZodNullable)\n\t\t\tresult = schema.clone({ ...schema._zod.def, innerType: copy(schema._zod.def.innerType) })\n\t\telse if (schema instanceof z.ZodEnum)\n\t\t\tresult = schema.clone({ ...schema._zod.def, entries: { ...schema._zod.def.entries } })\n\t\telse if (schema instanceof z.ZodLiteral)\n\t\t\tresult = schema.clone({ ...schema._zod.def, values: [...schema._zod.def.values] })\n\t\telse if (\n\t\t\tschema instanceof z.ZodString ||\n\t\t\tschema instanceof z.ZodNumber ||\n\t\t\tschema instanceof z.ZodBigInt ||\n\t\t\tschema instanceof z.ZodBoolean ||\n\t\t\tschema instanceof z.ZodNull ||\n\t\t\tschema instanceof z.ZodNever ||\n\t\t\tschema instanceof z.ZodCustom\n\t\t)\n\t\t\tresult = z.core.clone(schema, { ...schema._zod.def }, { parent: true })\n\t\telse throw new UnsupportedFilterCapture()\n\t\t// Generated membership limits and nonempty-operator refinements must not\n\t\t// share mutable check definitions with the public graph.\n\t\tif (schema._zod.def.checks) {\n\t\t\tconst checks = schema._zod.def.checks.map((check) => {\n\t\t\t\tif (check instanceof z.ZodCustom) {\n\t\t\t\t\tconst copied = copy(check)\n\t\t\t\t\tif (!(copied instanceof z.ZodCustom)) throw new UnsupportedFilterCapture()\n\t\t\t\t\treturn copied\n\t\t\t\t}\n\t\t\t\tif (check instanceof z.core.$ZodCheckMaxLength)\n\t\t\t\t\treturn new z.core.$ZodCheckMaxLength({ ...check._zod.def })\n\t\t\t\tif (check instanceof z.core.$ZodCheckMinLength)\n\t\t\t\t\treturn new z.core.$ZodCheckMinLength({ ...check._zod.def })\n\t\t\t\tthrow new UnsupportedFilterCapture()\n\t\t\t})\n\t\t\tresult = result.clone({ ...result._zod.def, checks })\n\t\t}\n\t\tschemas.set(schema, result)\n\t\treturn result\n\t}\n\tconst result: FilterGrammar = {\n\t\tfields: Object.freeze(\n\t\t\tObject.fromEntries(Object.entries(source.fields).map(([k, v]) => [k, copy(v)])),\n\t\t),\n\t\trelations: {},\n\t}\n\tseen.set(source, result)\n\tresult.relations = Object.freeze(\n\t\tObject.fromEntries(\n\t\t\tObject.entries(source.relations).map(([k, v]) => [\n\t\t\t\tk,\n\t\t\t\tObject.freeze({ cardinality: v.cardinality, target: captureGrammar(v.target, seen) }),\n\t\t\t]),\n\t\t),\n\t)\n\tif (source.variants)\n\t\tresult.variants = Object.freeze({\n\t\t\tdiscriminator: source.variants.discriminator,\n\t\t\toptions: Object.freeze(\n\t\t\t\tObject.fromEntries(\n\t\t\t\t\tObject.entries(source.variants.options).map(([k, v]) => [k, captureGrammar(v, seen)]),\n\t\t\t\t),\n\t\t\t),\n\t\t})\n\treturn Object.freeze(result)\n}\n"],"mappings":"wBAEA,MAAaA,EAAmB,EACnBC,EAAmB,IACnBC,EAAuB,IAe9BC,kBAAqB,IAAI,QAIzBC,kBAAoB,IAAI,QACxBC,kBAAiB,IAAI,QAUrBC,kBAAiB,IAAI,QAS3B,SAAgBC,EAAsB,EAA6D,CAClG,IAAMC,EAAQF,EAAe,IAAIG,CAAM,EACvC,OAAOD,GAAO,QAAQ,EAAIA,EAAM,SAAW,IAAA,EAC5C,CAWA,SAAgBE,EACf,EACA,kBAAQ,IAAI,QACZ,EACY,CACZ,GAAIC,GAAS,YAAc,UAAW,CACrC,IAAIC,EACJ,GAAI,CACH,EAAWC,EAAeC,CAAO,CAClC,OAASC,EAAO,CACf,GAAI,EAAEA,aAAiBC,GAA2B,MAAMD,EACxD,OAAOE,EAAcC,EA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,CACrD,CAEA,OADAwB,EAAQ,IAAIrE,EAAQ6C,CAAM,EACnBA,CACR,CACA,IAAMA,EAAwB,CAC7B,OAAQ,OAAO,OACd,OAAO,YAAY,OAAO,QAAQuB,EAAO,MAAM,CAAC,CAAC,KAAK,CAACG,EAAGC,KAAO,CAACD,EAAGD,EAAKE,CAAC,CAAC,CAAC,CAAC,CAC/E,EACA,UAAW,CAAC,CACb,EAmBA,OAlBAL,EAAK,IAAIC,EAAQvB,CAAM,EACvB,EAAO,UAAY,OAAO,OACzB,OAAO,YACN,OAAO,QAAQuB,EAAO,SAAS,CAAC,CAAC,KAAK,CAACG,EAAGC,KAAO,CAChDD,EACA,OAAO,OAAO,CAAE,YAAaC,EAAE,YAAa,OAAQpE,EAAeoE,EAAE,OAAQL,CAAI,CAAE,CAAC,CACrF,CAAC,CACF,CACD,EACIC,EAAO,WACV,EAAO,SAAW,OAAO,OAAO,CAC/B,cAAeA,EAAO,SAAS,cAC/B,QAAS,OAAO,OACf,OAAO,YACN,OAAO,QAAQA,EAAO,SAAS,OAAO,CAAC,CAAC,KAAK,CAACG,EAAGC,KAAO,CAACD,EAAGnE,EAAeoE,EAAGL,CAAI,CAAC,CAAC,CACrF,CACD,CACD,CAAC,GACK,OAAO,OAAOtB,CAAM,CAC5B"}
1
+ {"version":3,"file":"filters.mjs","names":["MAX_FILTER_DEPTH","MAX_FILTER_NODES","MAX_FILTER_IN_VALUES","relationPredicates","variantPredicates","filterGrammars","compactFilters","compactFilterMetadata","entry","schema","relationFilterSchema","options","captured","captureGrammar","grammar","error","UnsupportedFilterCapture","boundedObject","filterNodeSchema","cache","semantic","lazyRelationFilterSchema","restricted","ids","nextId","idOf","id","source","restrict","key","used","names","a","b","result","build","state","depth","existing","states","name","relation","tag","option","paginationGrammar","z","filters","root","cached","predicate","normalizeFilters","children","value","expression","child","scoped","field","scalar","normalizeScalar","target","scalarPredicateFromSchema","equality","ranged","range","existence","optional","boundedFilterSchema","predicates","direct","relations","branch","node","depths","withinFilterBudget","pending","nodes","object","array","prototype","keys","consumed","descriptor","context","operator","expected","definition","expectedCatchall","inst","def","metadata","parse","resolve","payload","ctx","seen","schemas","copy","k","v","checks","check","copied"],"sources":["../../../src/querying/shared/filters.ts"],"sourcesContent":["import { z } from 'zod'\nimport type { FilterAst, FilterScalar, FilterOperator } from './ast'\nexport const MAX_FILTER_DEPTH = 4\nexport const MAX_FILTER_NODES = 256\nexport const MAX_FILTER_IN_VALUES = 100\nexport type FieldSchemas = Record<string, z.ZodType>\nexport type FilterTree =\n\t| string\n\t| number\n\t| bigint\n\t| boolean\n\t| null\n\t| undefined\n\t| FilterTree[]\n\t| { [key: string]: FilterTree }\n\n// Compose Zod's exported core constructor with its ordinary object initializer.\n// Clones use this constructor again, preserving preflight without replacing the\n// converter-recognized object definition or any native scalar/ID validators.\nconst relationPredicates = new WeakMap<\n\tz.core.$ZodType,\n\t{ cardinality: 'one' | 'many'; target: FilterGrammar }\n>()\nconst variantPredicates = new WeakMap<z.core.$ZodType, NonNullable<FilterGrammar['variants']>>()\nconst filterGrammars = new WeakMap<z.core.$ZodType, FilterGrammar>()\n\nexport interface PaginationValidatorOptions {\n\tvalidator: 'compact'\n}\n\nexport interface FilterBoundaryMetadata {\n\treadonly grammar: FilterGrammar\n\treadonly semantic: z.ZodType\n}\nconst compactFilters = new WeakMap<\n\tz.core.$ZodType,\n\t{\n\t\tmetadata: FilterBoundaryMetadata\n\t\tmatches(): boolean\n\t}\n>()\n\n/** Only constructors created here can carry permission to project a filter. */\nexport function compactFilterMetadata(schema: z.core.$ZodType): FilterBoundaryMetadata | undefined {\n\tconst entry = compactFilters.get(schema)\n\treturn entry?.matches() ? entry.metadata : undefined\n}\n\n/** Each boolean child and relation target expression consumes one of four edges.\n * some/none wrappers and fields namespaces consume nodes, but no extra depth.\n */\nexport interface FilterGrammar {\n\tfields: FieldSchemas\n\tvariants?: { discriminator: string; options: Record<string, FilterGrammar> }\n\trelations: Record<string, { cardinality: 'one' | 'many'; target: FilterGrammar }>\n}\n\nexport function relationFilterSchema(\n\tgrammar: FilterGrammar,\n\tcache = new WeakMap<FilterGrammar, Map<number, z.ZodObject>>(),\n\toptions?: PaginationValidatorOptions,\n): z.ZodType {\n\tif (options?.validator === 'compact') {\n\t\tlet captured: FilterGrammar\n\t\ttry {\n\t\t\tcaptured = captureGrammar(grammar)\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof UnsupportedFilterCapture)) throw error\n\t\t\treturn boundedObject(filterNodeSchema(grammar, 0, cache)._zod.def, grammar)\n\t\t}\n\t\tconst semantic = boundedObject(filterNodeSchema(captured, 0)._zod.def, captured)\n\t\treturn boundedObject(\n\t\t\tfilterNodeSchema(grammar, 0, cache)._zod.def,\n\t\t\tcaptured,\n\t\t\tObject.freeze({ grammar: captured, semantic }),\n\t\t)\n\t}\n\treturn boundedObject(filterNodeSchema(grammar, 0, cache)._zod.def, grammar)\n}\n\n/**\n * The engine's private filter boundary. It accepts exactly what\n * relationFilterSchema(grammar) accepts, but builds relation predicates only for\n * the relations an input names: absent optional relations validate nothing. So\n * a query never reads relation grammars, or their tables, that it does not use.\n */\nexport function lazyRelationFilterSchema(\n\tgrammar: FilterGrammar,\n\tcache = new WeakMap<FilterGrammar, Map<number, z.ZodObject>>(),\n): z.ZodType {\n\tconst restricted = new Map<string, FilterGrammar>()\n\tconst ids = new WeakMap<FilterGrammar, number>()\n\tlet nextId = 0\n\tconst idOf = (source: FilterGrammar) => {\n\t\tlet id = ids.get(source)\n\t\tif (id === undefined) ids.set(source, (id = nextId++))\n\t\treturn id\n\t}\n\t// A restriction is a function of the root grammar and the relation names used\n\t// per grammar, so that flat set is its key: no larger than the input.\n\tfunction restrict(used: Map<FilterGrammar, Set<string>>): FilterGrammar {\n\t\tconst key = JSON.stringify(\n\t\t\t[...used]\n\t\t\t\t.map(([source, names]) => [idOf(source), [...names].sort()] as const)\n\t\t\t\t.sort(([a], [b]) => a - b),\n\t\t)\n\t\tlet result = restricted.get(key)\n\t\tif (!result) {\n\t\t\tresult = build(used, grammar, 0, new Map())\n\t\t\tif (restricted.size >= 256) restricted.clear()\n\t\t\trestricted.set(key, result)\n\t\t}\n\t\treturn result\n\t}\n\t// One restricted grammar per source grammar and depth. filterNodeSchema builds\n\t// no relations at MAX_FILTER_DEPTH, so neither does a restriction; this also\n\t// bounds the walk over a cyclic grammar.\n\tfunction build(\n\t\tused: Map<FilterGrammar, Set<string>>,\n\t\tsource: FilterGrammar,\n\t\tdepth: number,\n\t\tstates: Map<string, FilterGrammar>,\n\t): FilterGrammar {\n\t\tconst state = `${idOf(source)}:${depth}`\n\t\tconst existing = states.get(state)\n\t\tif (existing) return existing\n\t\tconst result: FilterGrammar = { fields: source.fields, relations: {} }\n\t\tstates.set(state, result)\n\t\tif (depth < MAX_FILTER_DEPTH)\n\t\t\tfor (const name of [...(used.get(source) ?? [])].sort()) {\n\t\t\t\tconst relation = source.relations[name]\n\t\t\t\tresult.relations[name] = {\n\t\t\t\t\tcardinality: relation.cardinality,\n\t\t\t\t\ttarget: build(used, relation.target, depth + 1, states),\n\t\t\t\t}\n\t\t\t}\n\t\tif (source.variants)\n\t\t\tresult.variants = {\n\t\t\t\tdiscriminator: source.variants.discriminator,\n\t\t\t\toptions: Object.fromEntries(\n\t\t\t\t\tObject.entries(source.variants.options).map(([tag, option]) => [\n\t\t\t\t\t\ttag,\n\t\t\t\t\t\tbuild(used, option, depth + 1, states),\n\t\t\t\t\t]),\n\t\t\t\t),\n\t\t\t}\n\t\treturn result\n\t}\n\tconst scalar = restrict(new Map())\n\treturn boundedObject(filterNodeSchema(scalar, 0, cache)._zod.def, grammar, undefined, (used) =>\n\t\tfilterNodeSchema(restrict(used), 0, cache),\n\t)\n}\n\nexport function paginationGrammar(schema: z.ZodType): FilterGrammar | undefined {\n\tif (!(schema instanceof z.ZodObject)) return undefined\n\tconst filters = schema.shape.filters\n\tif (!(filters instanceof z.ZodOptional)) return undefined\n\tconst root = filters.unwrap()\n\tconst cached = filterGrammars.get(root)\n\tif (cached) return cached\n\tif (!(root instanceof z.ZodObject)) return undefined\n\treturn {\n\t\tfields: root.shape,\n\t\tvariants: variantPredicates.get(root.shape.variant),\n\t\trelations: Object.fromEntries(\n\t\t\tObject.entries(root.shape).flatMap(([name, predicate]) => {\n\t\t\t\t// SAFETY: object shapes contain Zod schemas; metadata only recognizes predicates created by our grammar.\n\t\t\t\tconst relation = relationPredicates.get(predicate as z.core.$ZodType)\n\t\t\t\treturn relation ? [[name, relation]] : []\n\t\t\t}),\n\t\t),\n\t}\n}\nexport function normalizeFilters(value: FilterTree, grammar?: FilterGrammar): FilterAst {\n\tconst children: FilterAst[] = []\n\tif (!value) return { kind: 'and', children }\n\t// SAFETY: the caller parsed a strict filter object; its grammar has no array/primitive expression.\n\tconst expression = value as Record<string, FilterTree>\n\tfor (const [name, predicate] of Object.entries(expression)) {\n\t\tif (predicate === undefined) continue\n\t\tif (name === 'and' || name === 'or') {\n\t\t\t// SAFETY: boolean composition is validated as an array of expressions.\n\t\t\tchildren.push({\n\t\t\t\tkind: name,\n\t\t\t\tchildren: (predicate as FilterTree[]).map((child) => normalizeFilters(child, grammar)),\n\t\t\t})\n\t\t} else if (name === 'variant' && grammar?.variants) {\n\t\t\t// SAFETY: strict branch grammar validates the literal tag and its selected target filters.\n\t\t\tconst scoped = predicate as { tag: string; filters: FilterTree }\n\t\t\tchildren.push({\n\t\t\t\tkind: 'variant',\n\t\t\t\tdiscriminator: grammar.variants.discriminator,\n\t\t\t\ttag: scoped.tag,\n\t\t\t\tchild: normalizeFilters(scoped.filters, grammar.variants.options[scoped.tag]),\n\t\t\t})\n\t\t} else if (name === 'not')\n\t\t\tchildren.push({ kind: 'not', child: normalizeFilters(predicate, grammar) })\n\t\telse if (name === 'fields') {\n\t\t\t// SAFETY: fields is a strict selected scalar namespace.\n\t\t\tfor (const [field, scalar] of Object.entries(predicate as Record<string, FilterTree>))\n\t\t\t\tchildren.push(...normalizeScalar(field, scalar))\n\t\t} else if (grammar?.relations[name]) {\n\t\t\tconst relation = grammar.relations[name]\n\t\t\tif (relation.cardinality === 'one')\n\t\t\t\tchildren.push({\n\t\t\t\t\tkind: 'relation',\n\t\t\t\t\tname,\n\t\t\t\t\tmode: 'one',\n\t\t\t\t\tpredicate: predicate === null ? null : normalizeFilters(predicate, relation.target),\n\t\t\t\t})\n\t\t\telse {\n\t\t\t\t// SAFETY: many predicates validate as exactly one some/none target expression.\n\t\t\t\tconst target = predicate as { some?: FilterTree; none?: FilterTree }\n\t\t\t\tchildren.push({\n\t\t\t\t\tkind: 'relation',\n\t\t\t\t\tname,\n\t\t\t\t\tmode: target.some === undefined ? 'none' : 'some',\n\t\t\t\t\tpredicate: normalizeFilters(target.some ?? target.none, relation.target),\n\t\t\t\t})\n\t\t\t}\n\t\t} else children.push(...normalizeScalar(name, predicate))\n\t}\n\treturn { kind: 'and', children }\n}\nexport function scalarPredicateFromSchema(\n\tscalar: z.ZodType,\n\trange: boolean,\n\toptional: boolean,\n): z.ZodType {\n\tconst equality = z.object({\n\t\teq: scalar.optional(),\n\t\tin: z.array(scalar).max(MAX_FILTER_IN_VALUES).optional(),\n\t})\n\tconst ranged = range\n\t\t? equality.extend({\n\t\t\t\tgt: scalar.optional(),\n\t\t\t\tgte: scalar.optional(),\n\t\t\t\tlt: scalar.optional(),\n\t\t\t\tlte: scalar.optional(),\n\t\t\t})\n\t\t: equality\n\tconst existence = optional ? ranged.extend({ exists: z.boolean().optional() }) : ranged\n\treturn z.union([\n\t\tscalar,\n\t\texistence\n\t\t\t.strict()\n\t\t\t.refine(\n\t\t\t\t(value) => Object.values(value).some((entry) => entry !== undefined),\n\t\t\t\t'At least one operator is required',\n\t\t\t),\n\t])\n}\n\nexport function boundedFilterSchema(\n\tpredicates: FieldSchemas,\n\toptions?: PaginationValidatorOptions,\n): z.ZodType {\n\treturn relationFilterSchema({ fields: predicates, relations: {} }, undefined, options)\n}\n\nfunction filterNodeSchema(\n\tgrammar: FilterGrammar,\n\tdepth: number,\n\tcache = new WeakMap<FilterGrammar, Map<number, z.ZodObject>>(),\n): z.ZodObject {\n\tconst cached = cache.get(grammar)?.get(depth)\n\tif (cached) return cached\n\tconst predicates = grammar.fields\n\tconst direct = Object.fromEntries(\n\t\tObject.entries(predicates).filter(\n\t\t\t([key]) =>\n\t\t\t\t!['and', 'or', 'not', 'fields', ...(grammar.variants ? ['variant'] : [])].includes(key),\n\t\t),\n\t)\n\tconst relations: FieldSchemas = {}\n\tfor (const [name, relation] of Object.entries(grammar.relations)) {\n\t\tif (depth === MAX_FILTER_DEPTH) continue\n\t\tconst target = filterNodeSchema(relation.target, depth + 1, cache)\n\t\trelations[name] = (\n\t\t\trelation.cardinality === 'one'\n\t\t\t\t? target.nullable()\n\t\t\t\t: z.union([z.object({ some: target }).strict(), z.object({ none: target }).strict()])\n\t\t).optional()\n\t\trelationPredicates.set(relations[name], relation)\n\t}\n\tif (grammar.variants && depth < MAX_FILTER_DEPTH) {\n\t\tconst options = Object.entries(grammar.variants.options).map(([tag, branch]) =>\n\t\t\tz.strictObject({ tag: z.literal(tag), filters: filterNodeSchema(branch, depth + 1, cache) }),\n\t\t)\n\t\tif (options.length) {\n\t\t\trelations.variant = z.union(options).optional()\n\t\t\tvariantPredicates.set(relations.variant, grammar.variants)\n\t\t}\n\t}\n\tconst node = z\n\t\t.object({ ...direct, ...relations, fields: z.object(predicates).strict().optional() })\n\t\t.strict()\n\tconst child = depth === MAX_FILTER_DEPTH ? undefined : filterNodeSchema(grammar, depth + 1, cache)\n\tconst result = child\n\t\t? node.extend({\n\t\t\t\tand: z.array(child).min(1).max(MAX_FILTER_NODES).optional(),\n\t\t\t\tor: z.array(child).min(1).max(MAX_FILTER_NODES).optional(),\n\t\t\t\tnot: child.optional(),\n\t\t\t})\n\t\t: node\n\tlet depths = cache.get(grammar)\n\tif (!depths) {\n\t\tdepths = new Map()\n\t\tcache.set(grammar, depths)\n\t}\n\tdepths.set(depth, result)\n\treturn result\n}\n\nfunction withinFilterBudget(\n\tvalue: FilterTree,\n\tgrammar: FilterGrammar,\n\tused?: Map<FilterGrammar, Set<string>>,\n): boolean {\n\ttype Context =\n\t\t| 'expression'\n\t\t| 'fields'\n\t\t| 'predicate'\n\t\t| 'composition'\n\t\t| 'many'\n\t\t| 'variant'\n\t\t| 'value'\n\tinterface Entry {\n\t\tvalue: FilterTree\n\t\tdepth: number\n\t\tcontext: Context\n\t\tgrammar: FilterGrammar\n\t}\n\tconst pending: Entry[] = [{ value, depth: 0, context: 'expression', grammar }]\n\tlet nodes = 0\n\twhile (pending.length) {\n\t\tconst entry = pending.pop()!\n\t\tif (++nodes > MAX_FILTER_NODES || entry.depth > MAX_FILTER_DEPTH) return false\n\t\tif (Object(entry.value) !== entry.value) continue\n\t\t// SAFETY: boxing excludes null and primitives; descriptors below avoid invoking getters.\n\t\tconst object = entry.value as FilterTree[] | Record<string, FilterTree>\n\t\tconst array = Array.isArray(object) ? object : undefined\n\t\tconst prototype = Object.getPrototypeOf(object)\n\t\tif (\n\t\t\tarray ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null\n\t\t)\n\t\t\treturn false\n\t\tif (array && array.length + nodes + pending.length > MAX_FILTER_NODES) return false\n\t\tconst keys = Reflect.ownKeys(object)\n\t\tif (\n\t\t\tkeys.length - (array ? 1 : 0) + nodes + pending.length > MAX_FILTER_NODES ||\n\t\t\t(array && keys.length !== array.length + 1)\n\t\t)\n\t\t\treturn false\n\t\tlet consumed: string[]\n\t\tswitch (entry.context) {\n\t\t\tcase 'expression':\n\t\t\t\tconsumed = [\n\t\t\t\t\t...Object.keys(entry.grammar.fields),\n\t\t\t\t\t...Object.keys(entry.grammar.relations),\n\t\t\t\t\t'and',\n\t\t\t\t\t'or',\n\t\t\t\t\t'not',\n\t\t\t\t\t'fields',\n\t\t\t\t\t...(entry.grammar.variants ? ['variant'] : []),\n\t\t\t\t]\n\t\t\t\tbreak\n\t\t\tcase 'variant':\n\t\t\t\tconsumed = ['tag', 'filters']\n\t\t\t\tbreak\n\t\t\tcase 'fields':\n\t\t\t\tconsumed = Object.keys(entry.grammar.fields)\n\t\t\t\tbreak\n\t\t\tcase 'predicate':\n\t\t\t\tconsumed = ['eq', 'in', 'gt', 'gte', 'lt', 'lte', 'exists']\n\t\t\t\tbreak\n\t\t\tcase 'many':\n\t\t\t\tconsumed = ['some', 'none']\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tconsumed = []\n\t\t}\n\t\tfor (const key of consumed) if (!Object.hasOwn(object, key) && key in object) return false\n\t\tfor (const key of keys) {\n\t\t\tif (array && key === 'length') continue\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(object, key)!\n\t\t\tconst name = String(key)\n\t\t\tif (!descriptor.enumerable || !('value' in descriptor) || name !== key) return false\n\t\t\tif (array && (!/^(0|[1-9]\\d*)$/.test(name) || Number(name) >= array.length)) return false\n\t\t\tlet context: Context = 'value'\n\t\t\tlet depth = entry.depth\n\t\t\tlet target = entry.grammar\n\t\t\tif (entry.context === 'expression') {\n\t\t\t\tcontext = 'predicate'\n\t\t\t\tif (name === 'variant' && entry.grammar.variants) {\n\t\t\t\t\tcontext = 'variant'\n\t\t\t\t\tdepth++\n\t\t\t\t} else if (name === 'fields') context = 'fields'\n\t\t\t\telse if (name === 'and' || name === 'or') {\n\t\t\t\t\tcontext = 'composition'\n\t\t\t\t\tdepth++\n\t\t\t\t} else if (name === 'not') {\n\t\t\t\t\tcontext = 'expression'\n\t\t\t\t\tdepth++\n\t\t\t\t} else if (Object.hasOwn(entry.grammar.relations, name)) {\n\t\t\t\t\tconst relation = entry.grammar.relations[name]\n\t\t\t\t\tcontext = relation.cardinality === 'one' ? 'expression' : 'many'\n\t\t\t\t\ttarget = relation.target\n\t\t\t\t\tdepth++\n\t\t\t\t\tif (used) {\n\t\t\t\t\t\tconst names = used.get(entry.grammar) ?? new Set<string>()\n\t\t\t\t\t\tused.set(entry.grammar, names.add(name))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (entry.context === 'variant' && name === 'filters') {\n\t\t\t\tconst tag = Object.getOwnPropertyDescriptor(object, 'tag')\n\t\t\t\tif (\n\t\t\t\t\t!tag ||\n\t\t\t\t\t!('value' in tag) ||\n\t\t\t\t\t!z.string().safeParse(tag.value).success ||\n\t\t\t\t\t!Object.hasOwn(entry.grammar.variants?.options ?? {}, tag.value)\n\t\t\t\t)\n\t\t\t\t\treturn false\n\t\t\t\tcontext = 'expression'\n\t\t\t\ttarget = entry.grammar.variants!.options[String(tag.value)]\n\t\t\t} else if (entry.context === 'fields') context = 'predicate'\n\t\t\telse if (entry.context === 'composition' || entry.context === 'many') context = 'expression'\n\t\t\tpending.push({ value: descriptor.value, depth, context, grammar: target })\n\t\t}\n\t}\n\treturn true\n}\nfunction normalizeScalar(field: string, predicate: FilterTree): FilterAst[] {\n\tif (predicate === undefined) return []\n\tif (Object(predicate) !== predicate) {\n\t\t// SAFETY: native scalar grammar excludes object/array values and preserves branded ID strings.\n\t\treturn [{ kind: 'scalar', field, operator: 'eq', value: predicate as FilterScalar }]\n\t}\n\t// SAFETY: only selected supported scalar operator objects survive validation.\n\treturn Object.entries(predicate as Record<FilterOperator, FilterScalar | FilterScalar[]>)\n\t\t.filter(([, value]) => value !== undefined)\n\t\t.map(([operator, value]) => ({\n\t\t\tkind: 'scalar',\n\t\t\tfield,\n\t\t\toperator: operator as FilterOperator,\n\t\t\tvalue,\n\t\t}))\n}\n\nfunction boundedObject(\n\tdefinition: z.ZodObject['_zod']['def'],\n\tgrammar: FilterGrammar,\n\tmetadata?: FilterBoundaryMetadata,\n\tresolve?: (used: Map<FilterGrammar, Set<string>>) => z.ZodObject,\n): z.ZodObject {\n\tconst expected = Object.entries(definition.shape)\n\tconst expectedCatchall = definition.catchall\n\tconst BoundedFilterObject = z.core.$constructor<z.ZodObject>(\n\t\t'BoundedFilterObject',\n\t\t(inst, def) => {\n\t\t\tz.ZodObject.init(inst, def)\n\t\t\tfilterGrammars.set(inst, grammar)\n\t\t\t// Clones/refinements retain the generated fields. Shape edits use full conversion.\n\t\t\tif (\n\t\t\t\tmetadata &&\n\t\t\t\tdef.catchall === expectedCatchall &&\n\t\t\t\tObject.keys(def.shape).length === expected.length &&\n\t\t\t\texpected.every(([key, value]) => def.shape[key] === value)\n\t\t\t)\n\t\t\t\tcompactFilters.set(inst, {\n\t\t\t\t\tmetadata,\n\t\t\t\t\tmatches: () =>\n\t\t\t\t\t\tinst._zod.def.catchall === expectedCatchall &&\n\t\t\t\t\t\tObject.keys(inst._zod.def.shape).length === expected.length &&\n\t\t\t\t\t\texpected.every(([key, value]) => inst._zod.def.shape[key] === value),\n\t\t\t\t})\n\t\t\tconst parse = inst._zod.parse\n\t\t\tinst._zod.parse = (payload, ctx) => {\n\t\t\t\tconst used = resolve && new Map<FilterGrammar, Set<string>>()\n\t\t\t\t// SAFETY: layout preflight precedes Zod's value traversal.\n\t\t\t\tif (!withinFilterBudget(payload.value as FilterTree, grammar, used)) {\n\t\t\t\t\tpayload.issues.push({\n\t\t\t\t\t\tcode: 'custom',\n\t\t\t\t\t\tinput: payload.value,\n\t\t\t\t\t\tmessage: 'Unsupported filter layout or depth/node budget exceeded',\n\t\t\t\t\t})\n\t\t\t\t\treturn payload\n\t\t\t\t}\n\t\t\t\t// Validate against the relations this input names; the rest are absent.\n\t\t\t\treturn used ? resolve(used)._zod.run(payload, ctx) : parse(payload, ctx)\n\t\t\t}\n\t\t},\n\t)\n\treturn new BoundedFilterObject(definition)\n}\n\nclass UnsupportedFilterCapture extends Error {}\n\n// Copy the generated schema graph before exposing the public filter. These are\n// generated scalar predicates, not arbitrary storage schemas or consumer hooks.\nfunction captureGrammar(\n\tsource: FilterGrammar,\n\tseen = new WeakMap<FilterGrammar, FilterGrammar>(),\n): FilterGrammar {\n\tconst cached = seen.get(source)\n\tif (cached) return cached\n\tconst schemas = new WeakMap<z.ZodType, z.ZodType>()\n\tfunction copy(schema: z.core.$ZodType): z.ZodType {\n\t\tif (!(schema instanceof z.ZodType)) throw new Error('Expected generated classic filter schema')\n\t\tconst cached = schemas.get(schema)\n\t\tif (cached) return cached\n\t\tlet result: z.ZodType\n\t\tif (schema instanceof z.ZodObject)\n\t\t\tresult = schema.clone({\n\t\t\t\t...schema._zod.def,\n\t\t\t\t// oxlint-disable-next-line anti-slop/no-shape-in-symbol-names -- Installed Zod object definition property.\n\t\t\t\tshape: Object.fromEntries(Object.entries(schema.shape).map(([k, v]) => [k, copy(v)])),\n\t\t\t\tcatchall: schema._zod.def.catchall ? copy(schema._zod.def.catchall) : undefined,\n\t\t\t})\n\t\telse if (schema instanceof z.ZodUnion)\n\t\t\tresult = schema.clone({ ...schema._zod.def, options: schema.options.map(copy) })\n\t\telse if (schema instanceof z.ZodArray)\n\t\t\tresult = schema.clone({ ...schema._zod.def, element: copy(schema.element) })\n\t\telse if (schema instanceof z.ZodOptional)\n\t\t\tresult = schema.clone({ ...schema._zod.def, innerType: copy(schema._zod.def.innerType) })\n\t\telse if (schema instanceof z.ZodNonOptional)\n\t\t\tresult = schema.clone({ ...schema._zod.def, innerType: copy(schema._zod.def.innerType) })\n\t\telse if (schema instanceof z.ZodNullable)\n\t\t\tresult = schema.clone({ ...schema._zod.def, innerType: copy(schema._zod.def.innerType) })\n\t\telse if (schema instanceof z.ZodEnum)\n\t\t\tresult = schema.clone({ ...schema._zod.def, entries: { ...schema._zod.def.entries } })\n\t\telse if (schema instanceof z.ZodLiteral)\n\t\t\tresult = schema.clone({ ...schema._zod.def, values: [...schema._zod.def.values] })\n\t\telse if (\n\t\t\tschema instanceof z.ZodString ||\n\t\t\tschema instanceof z.ZodNumber ||\n\t\t\tschema instanceof z.ZodBigInt ||\n\t\t\tschema instanceof z.ZodBoolean ||\n\t\t\tschema instanceof z.ZodNull ||\n\t\t\tschema instanceof z.ZodNever ||\n\t\t\tschema instanceof z.ZodCustom\n\t\t)\n\t\t\tresult = z.core.clone(schema, { ...schema._zod.def }, { parent: true })\n\t\telse throw new UnsupportedFilterCapture()\n\t\t// Generated membership limits and nonempty-operator refinements must not\n\t\t// share mutable check definitions with the public graph.\n\t\tif (schema._zod.def.checks) {\n\t\t\tconst checks = schema._zod.def.checks.map((check) => {\n\t\t\t\tif (check instanceof z.ZodCustom) {\n\t\t\t\t\tconst copied = copy(check)\n\t\t\t\t\tif (!(copied instanceof z.ZodCustom)) throw new UnsupportedFilterCapture()\n\t\t\t\t\treturn copied\n\t\t\t\t}\n\t\t\t\tif (check instanceof z.core.$ZodCheckMaxLength)\n\t\t\t\t\treturn new z.core.$ZodCheckMaxLength({ ...check._zod.def })\n\t\t\t\tif (check instanceof z.core.$ZodCheckMinLength)\n\t\t\t\t\treturn new z.core.$ZodCheckMinLength({ ...check._zod.def })\n\t\t\t\tthrow new UnsupportedFilterCapture()\n\t\t\t})\n\t\t\tresult = result.clone({ ...result._zod.def, checks })\n\t\t}\n\t\tschemas.set(schema, result)\n\t\treturn result\n\t}\n\tconst result: FilterGrammar = {\n\t\tfields: Object.freeze(\n\t\t\tObject.fromEntries(Object.entries(source.fields).map(([k, v]) => [k, copy(v)])),\n\t\t),\n\t\trelations: {},\n\t}\n\tseen.set(source, result)\n\tresult.relations = Object.freeze(\n\t\tObject.fromEntries(\n\t\t\tObject.entries(source.relations).map(([k, v]) => [\n\t\t\t\tk,\n\t\t\t\tObject.freeze({ cardinality: v.cardinality, target: captureGrammar(v.target, seen) }),\n\t\t\t]),\n\t\t),\n\t)\n\tif (source.variants)\n\t\tresult.variants = Object.freeze({\n\t\t\tdiscriminator: source.variants.discriminator,\n\t\t\toptions: Object.freeze(\n\t\t\t\tObject.fromEntries(\n\t\t\t\t\tObject.entries(source.variants.options).map(([k, v]) => [k, captureGrammar(v, seen)]),\n\t\t\t\t),\n\t\t\t),\n\t\t})\n\treturn Object.freeze(result)\n}\n"],"mappings":"wBAEA,MAAaA,EAAmB,EACnBC,EAAmB,IACnBC,EAAuB,IAe9BC,kBAAqB,IAAI,QAIzBC,kBAAoB,IAAI,QACxBC,kBAAiB,IAAI,QAUrBC,kBAAiB,IAAI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O,MAAM,CAAC,CAAC,KAAK,CAACsE,EAAGC,KAAO,CAACD,EAAGD,EAAKE,CAAC,CAAC,CAAC,CAAC,CAC/E,EACA,UAAW,CAAC,CACb,EAmBA,OAlBAJ,EAAK,IAAInE,EAAQO,CAAM,EACvB,EAAO,UAAY,OAAO,OACzB,OAAO,YACN,OAAO,QAAQP,EAAO,SAAS,CAAC,CAAC,KAAK,CAACsE,EAAGC,KAAO,CAChDD,EACA,OAAO,OAAO,CAAE,YAAaC,EAAE,YAAa,OAAQrF,EAAeqF,EAAE,OAAQJ,CAAI,CAAE,CAAC,CACrF,CAAC,CACF,CACD,EACInE,EAAO,WACV,EAAO,SAAW,OAAO,OAAO,CAC/B,cAAeA,EAAO,SAAS,cAC/B,QAAS,OAAO,OACf,OAAO,YACN,OAAO,QAAQA,EAAO,SAAS,OAAO,CAAC,CAAC,KAAK,CAACsE,EAAGC,KAAO,CAACD,EAAGpF,EAAeqF,EAAGJ,CAAI,CAAC,CAAC,CACrF,CACD,CACD,CAAC,GACK,OAAO,OAAO5D,CAAM,CAC5B"}
package/dist/querying.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{ManagedReadError as e,createManagedSecurity as t}from"./querying/security.mjs";import{createPlanner as n}from"./querying/planner.mjs";import{CursorError as r,createCursorCodec as i,createEnvironmentCursorCodec as a,createScopedCursorCodec as o}from"./querying/cursors.mjs";import{SearchError as s,executeSearch as c,planSearch as l}from"./querying/search.mjs";import{assertRelationshipDepth as u,relationshipExecutor as d}from"./querying/relationships.mjs";import{executeQuery as f}from"./querying/execution.mjs";import{queryFailureContract as p}from"./querying/failures.mjs";import{z as m}from"zod";const h={fieldGroups:{},relations:{}};var g=class extends Error{code=`FIELD_GROUP_DENIED`;constructor(){super(`FIELD_GROUP_DENIED`),this.name=`FieldGroupError`}};function _(r,p){let{relations:_}=r,y={...r,...p},b=n(r.schema,_),x=b.streamSchema,S=/* @__PURE__ */ new Map;for(let[e,t]of Object.entries(y.fieldGroups??{})){if(!Object.hasOwn(b.metadata.tables,e))throw Error(`Unknown field group policy table`);for(let[n,r]of Object.entries(t??{})){if(!Object.hasOwn(b.metadata.tables[e].fieldGroups,n)||!(r instanceof Function))throw Error(`Unknown field group policy`);S.set(JSON.stringify([e,n]),r)}}let C=y.cursor===void 0?void 0:i(y.cursor),w=y.maxPageSize??100;if(!Number.isSafeInteger(w)||w<=0||w>100)throw Error(`Invalid central page size`);let T=y.engineVersion??`scalar-1`,E=y.policyVersion??`1`,D,O=t({tables:Object.keys(_.tables),policyVersion:E,budgets:y.budgets,trustedAdapter:y.trustedAdapter});function k(t){let n=O(t),r=/* @__PURE__ */ new Map;async function i(t,a){let o={};for(let[i,s]of Object.entries(a.fieldGroups??{})){let a=JSON.stringify([t,i]),c=r.get(a);if(c||(c=Promise.resolve().then(async()=>{try{return await S.get(a)?.(Object.freeze({db:n.db,scope:n.scope}))===!0}catch(t){throw t instanceof e?t:new g}}),r.set(a,c)),o[i]={mode:s,allowed:await c},s===`required`&&!o[i].allowed)throw new g}let s={};for(let[e,n]of Object.entries(a.relations??{}))s[e]=await i(b.metadata.declarations[t][e].target,n);return{fieldGroups:o,relations:s}}function o(e,t=[],r=[],p={},y,S,O={},k){return Object.freeze({include:n=>o(e,t,r,p,y,S,b.groups(e,{...O,fieldGroups:n}),k),orderBy:n=>{if(k)throw new s(`SEARCH_ORDER_UNSUPPORTED`);if(!m.string().safeParse(n).success)throw Error(`Unknown ordering index`);return o(e,t,r,p,y,n,O,k)},when:(n,i)=>{if(k&&n!=null)throw new s(`SEARCH_ORDER_UNSUPPORTED`);return o(e,[...t,{value:n,index:i}],r,p,y,S,O,k)},where:n=>o(e,t,[...r,n],p,y,S,O,k),with:(n,i={})=>o(e,t,r,n,y,S,b.groups(e,{...O,...i}),k),search:(n,i)=>{if(y)throw new s(`SEARCH_RELATION_UNSUPPORTED`);if(S!==void 0||t.some(({value:e})=>e!=null))throw new s(`SEARCH_ORDER_UNSUPPORTED`);if(k)throw new s(`SEARCH_OPTIONS_UNSUPPORTED`);return o(e,t,r,p,y,S,O,{index:n,text:i})},relation:(n,i)=>{if(k)throw new s(`SEARCH_RELATION_UNSUPPORTED`);let a=i.split(`.`);if(!a.length||a.length>4)throw Error(`INVALID_RELATION`);let c=e;for(let e of a){let t=b.metadata.declarations[c]?.[e];if(!t)throw Error(`INVALID_RELATION`);c=t.target}return o(c,t,r,{},{table:e,parent:n,path:a},S)},async paginate(o){let s=C??=a();b.select(e,p),u(p,y?.path.length??0);let m=k?l(b,e,k.index,k.text,o,r):void 0,A=m?.plan??b.plan(e,o,y?[]:t,r,S,y?`relation`:`root`);if(!m&&A.args.numItems>w)throw Error(`Page size exceeds central ceiling`);let j=await i(e,b.groups(e,O)),M={at(e){return e.slice(y?.path.length??0).reduce((e,t)=>e.relations[t]??h,j)},allowed(e){return Object.entries(this.at(e).fieldGroups).filter(([,e])=>e.allowed).map(([e])=>e)},checkOrder(e,t,n){for(let r of t)N(e,r,n?this.at(n):h)}};function N(e,t,n){for(let[r,i]of Object.entries(b.metadata.tables[e].fieldGroups))if(i.includes(t.split(`.`)[0])&&n.fieldGroups[r]?.allowed!==!0)throw new g}function P(e,t,n){if(t.kind===`scalar`)N(e,t.field,n);else if(t.kind===`variant`)N(e,t.discriminator,n),P(e,t.child,n);else if(t.kind===`not`)P(e,t.child,n);else if(t.kind===`and`||t.kind===`or`)for(let r of t.children)P(e,r,n);else t.kind===`relation`&&t.predicate&&P(b.metadata.declarations[e][t.name].target,t.predicate,n.relations[t.name]??h)}if(A.residual.kind!==`and`)throw Error(`Invalid compiled filter root`);P(e,A.residual.children[0],j),m&&N(e,m.metadata.searchField,j);let F=S??t.find(e=>e.value!=null)?.index;if(!m&&F!==void 0)for(let t of b.metadata.tables[e].indexes.find(e=>e.name===F)?.fields??[])N(e,t,j);else if(!m&&!y&&A.index)for(let t of A.index.fields.slice(A.prefix.length))N(e,t,j);A.args.maximumRowsRead=Math.min(A.args.maximumRowsRead??n.budgets.rawCandidates,n.budgets.rawCandidates),A.args.maximumBytesRead=Math.min(A.args.maximumBytesRead??n.budgets.documentBytes,n.budgets.documentBytes),D??=Array.from(new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(_.identity))),e=>e.toString(16).padStart(2,`0`)).join(``);let I={};v(j)&&(I.fieldGroups=j);let L={predicates:A.serverIdentity,selection:p,...I,scope:{...n.scope}};m&&(L.search={mode:`search`,text:m.text,index:{...m.metadata,filterFields:[...m.metadata.filterFields]},equalities:m.equalities,scanLimit:m.scanLimit??null});let R={table:y?.table??e,index:m?.metadata.name??A.index?.name??`by_creation_time`,order:A.args.order??`asc`,clientFilters:A.clientIdentity,serverFilters:L,relationPath:[],principal:JSON.stringify(n.scope),tenant:n.scope.tenant,policyVersion:E,engineVersion:T,registryVersion:D},z=n,B=d(x,z,b,s,R,M);return B.preflight(e,p,A.args,y?.path??[]),m?await c(z,e,m,s,R,w,async t=>{let r=t;return!await n.authorize(e,t)||!await B.matches(e,r,A.residual)?null:B.output(e,r,p,A.args)}):y?await B.continuation(y.table,y.parent,y.path,p,A.args,t,r,S):await f(x,n,e,A,b,s,R,async(t,n)=>!n||!await B.matches(e,t,A.residual)?null:B.output(e,t,p,A.args))}})}return Object.freeze(Object.fromEntries(Object.keys(_.tables).map(e=>[e,o(e)])))}return Object.assign(k,{tables:_.tables,cursorCodec(e,t){let n=O.cursorScope(e);return C??=a(),o(C.custom,n,t)}})}function v(e){return Object.keys(e.fieldGroups).length>0||Object.values(e.relations).some(v)}export{r as CursorError,g as FieldGroupError,s as SearchError,_ as createQueryEngine,p as queryFailureContract};
1
+ import{ManagedReadError as e,createManagedSecurity as t}from"./querying/security.mjs";import{createPlanner as n,digest as r}from"./querying/planner.mjs";import{CursorError as i,createCursorCodec as a,createEnvironmentCursorCodec as o,createScopedCursorCodec as s}from"./querying/cursors.mjs";import{SearchError as c,executeSearch as l,planSearch as u}from"./querying/search.mjs";import{assertRelationshipDepth as d,relationshipExecutor as f}from"./querying/relationships.mjs";import{executeQuery as p}from"./querying/execution.mjs";import{queryFailureContract as m}from"./querying/failures.mjs";import{z as h}from"zod";const g={fieldGroups:{},relations:{}};var _=class extends Error{code=`FIELD_GROUP_DENIED`;constructor(){super(`FIELD_GROUP_DENIED`),this.name=`FieldGroupError`}};function v(i,m){let{relations:v}=i,b={...i,...m},x=n(i.schema,v),S=x.streamSchema,C=/* @__PURE__ */ new Map;for(let[e,t]of Object.entries(b.fieldGroups??{})){if(!Object.hasOwn(x.metadata.tables,e))throw Error(`Unknown field group policy table`);for(let[n,r]of Object.entries(t??{})){if(!Object.hasOwn(x.metadata.tables[e].fieldGroups,n)||!(r instanceof Function))throw Error(`Unknown field group policy`);C.set(JSON.stringify([e,n]),r)}}let w=b.cursor===void 0?void 0:a(b.cursor),T=b.maxPageSize??100;if(!Number.isSafeInteger(T)||T<=0||T>100)throw Error(`Invalid central page size`);let E=b.engineVersion??`scalar-1`,D=b.policyVersion??`1`,O,k=t({tables:Object.keys(v.tables),policyVersion:D,budgets:b.budgets,trustedAdapter:b.trustedAdapter});function A(t){let n=k(t),i=/* @__PURE__ */ new Map;async function a(t,r){let o={};for(let[a,s]of Object.entries(r.fieldGroups??{})){let r=JSON.stringify([t,a]),c=i.get(r);if(c||(c=Promise.resolve().then(async()=>{try{return await C.get(r)?.(Object.freeze({db:n.db,scope:n.scope}))===!0}catch(t){throw t instanceof e?t:new _}}),i.set(r,c)),o[a]={mode:s,allowed:await c},s===`required`&&!o[a].allowed)throw new _}let s={};for(let[e,n]of Object.entries(r.relations??{}))s[e]=await a(x.metadata.declarations[t][e].target,n);return{fieldGroups:o,relations:s}}function s(e,t=[],i=[],m={},b,C,k={},A){return Object.freeze({include:n=>s(e,t,i,m,b,C,x.groups(e,{...k,fieldGroups:n}),A),orderBy:n=>{if(A)throw new c(`SEARCH_ORDER_UNSUPPORTED`);if(!h.string().safeParse(n).success)throw Error(`Unknown ordering index`);return s(e,t,i,m,b,n,k,A)},when:(n,r)=>{if(A&&n!=null)throw new c(`SEARCH_ORDER_UNSUPPORTED`);return s(e,[...t,{value:n,index:r}],i,m,b,C,k,A)},where:n=>s(e,t,[...i,n],m,b,C,k,A),with:(n,r={})=>s(e,t,i,n,b,C,x.groups(e,{...k,...r}),A),search:(n,r)=>{if(b)throw new c(`SEARCH_RELATION_UNSUPPORTED`);if(C!==void 0||t.some(({value:e})=>e!=null))throw new c(`SEARCH_ORDER_UNSUPPORTED`);if(A)throw new c(`SEARCH_OPTIONS_UNSUPPORTED`);return s(e,t,i,m,b,C,k,{index:n,text:r})},relation:(n,r)=>{if(A)throw new c(`SEARCH_RELATION_UNSUPPORTED`);let a=r.split(`.`);if(!a.length||a.length>4)throw Error(`INVALID_RELATION`);let o=e;for(let e of a){let t=x.metadata.declarations[o]?.[e];if(!t)throw Error(`INVALID_RELATION`);o=t.target}return s(o,t,i,{},{table:e,parent:n,path:a},C)},async paginate(s){let c=w??=o();x.select(e,m),d(m,b?.path.length??0);let h=A?u(x,e,A.index,A.text,s,i):void 0,j=h?.plan??x.plan(e,s,b?[]:t,i,C,b?`relation`:`root`);if(!h&&j.args.numItems>T)throw Error(`Page size exceeds central ceiling`);let M=await a(e,x.groups(e,k)),N={at(e){return e.slice(b?.path.length??0).reduce((e,t)=>e.relations[t]??g,M)},allowed(e){return Object.entries(this.at(e).fieldGroups).filter(([,e])=>e.allowed).map(([e])=>e)},checkOrder(e,t,n){for(let r of t)P(e,r,n?this.at(n):g)}};function P(e,t,n){for(let[r,i]of Object.entries(x.metadata.tables[e].fieldGroups))if(i.includes(t.split(`.`)[0])&&n.fieldGroups[r]?.allowed!==!0)throw new _}function F(e,t,n){if(t.kind===`scalar`)P(e,t.field,n);else if(t.kind===`variant`)P(e,t.discriminator,n),F(e,t.child,n);else if(t.kind===`not`)F(e,t.child,n);else if(t.kind===`and`||t.kind===`or`)for(let r of t.children)F(e,r,n);else t.kind===`relation`&&t.predicate&&F(x.metadata.declarations[e][t.name].target,t.predicate,n.relations[t.name]??g)}if(j.residual.kind!==`and`)throw Error(`Invalid compiled filter root`);F(e,j.residual.children[0],M),h&&P(e,h.metadata.searchField,M);let I=C??t.find(e=>e.value!=null)?.index;if(!h&&I!==void 0)for(let t of x.metadata.tables[e].indexes.find(e=>e.name===I)?.fields??[])P(e,t,M);else if(!h&&!b&&j.index)for(let t of j.index.fields.slice(j.prefix.length))P(e,t,M);j.args.maximumRowsRead=Math.min(j.args.maximumRowsRead??n.budgets.rawCandidates,n.budgets.rawCandidates),j.args.maximumBytesRead=Math.min(j.args.maximumBytesRead??n.budgets.documentBytes,n.budgets.documentBytes);let L=await x.registryVersion(b?{root:b.table,path:[],selection:{},groups:g,filters:[]}:{root:e,path:[],selection:m,groups:M,filters:[j.residual]}),R={};y(M)&&(R.fieldGroups=M);let z={predicates:j.serverIdentity,selection:m,...R,scope:{...n.scope}};h&&(z.search={mode:`search`,text:h.text,index:{...h.metadata,filterFields:[...h.metadata.filterFields]},equalities:h.equalities,scanLimit:h.scanLimit??null});let B={table:b?.table??e,index:h?.metadata.name??j.index?.name??`by_creation_time`,order:j.args.order??`asc`,clientFilters:j.clientIdentity,serverFilters:z,relationPath:[],principal:JSON.stringify(n.scope),tenant:n.scope.tenant,policyVersion:D,engineVersion:E,registryVersion:L},V=n,H=!1,U=Object.freeze({...c,open(e,t){try{return c.open(e,t)}catch(n){if(O===void 0)throw H=!0,n;return c.open(e,{...t,registryVersion:O})}}}),W=async()=>{let r=f(S,V,x,U,B,N);return r.preflight(e,m,j.args,b?.path??[]),h?await l(V,e,h,U,B,T,async t=>{let i=t;return!await n.authorize(e,t)||!await r.matches(e,i,j.residual)?null:r.output(e,i,m,j.args)}):b?await r.continuation(b.table,b.parent,b.path,m,j.args,t,i,C):await p(S,n,e,j,x,U,B,async(t,n)=>!n||!await r.matches(e,t,j.residual)?null:r.output(e,t,m,j.args))},G;try{G=await W()}catch(e){if(!H)throw e;O??=await r(v.identity),G=await W()}return G}})}return Object.freeze(Object.fromEntries(Object.keys(v.tables).map(e=>[e,s(e)])))}return Object.assign(A,{tables:v.tables,cursorCodec(e,t){let n=k.cursorScope(e);return w??=o(),s(w.custom,n,t)}})}function y(e){return Object.keys(e.fieldGroups).length>0||Object.values(e.relations).some(y)}export{i as CursorError,_ as FieldGroupError,c as SearchError,v as createQueryEngine,m as queryFailureContract};
2
2
  //# sourceMappingURL=querying.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"querying.mjs","names":["executorRequest","emptyGroups","FieldGroupError","createQueryEngine","config","settings","options","planner","createPlanner","relations","schema","policies","table","definitions","name","policy","cursorCodec","createCursorCodec","maxPageSize","engineVersion","policyVersion","registryDigest","security","createManagedSecurity","querying","request","ctx","decisions","resolveGroups","fieldGroups","mode","groups","key","decision","error","ManagedReadError","nested","selection","tableQuery","conditions","constraints","route","ordering","search","SearchError","z","index","value","spec","selected","requested","path","declaredPath","target","edge","codec","createEnvironmentCursorCodec","assertRelationshipDepth","searchPlan","planSearch","input","plan","resolved","groupAccess","node","field","fields","checkField","checkClient","ast","child","sortIndex","condition","byte","groupBinding","hasGroups","serverFilters","binding","executionRequest","executor","relationshipExecutor","executeSearch","document","row","executeQuery","permitted","scope","createScopedCursorCodec","CursorError","queryFailureContract"],"sources":["../src/querying.ts"],"sourcesContent":["import type { GenericSchema, SchemaDefinition, DataModelFromSchemaDefinition } from 'convex/server'\nimport type { GenericId } from 'convex/values'\nimport type { EnginePaginationResult } from './zod-table'\nimport { z } from 'zod'\nimport type {\n\tRelationTables,\n\tRelationDeclarations,\n\tRelationRegistry,\n\tRelationQueryRow,\n\tRelationSelection,\n\tRelationFilters,\n\tRelationFilterSelection,\n\tFieldGroupRequest,\n\tRelationGroupSelection,\n\tGroupSelection,\n\tExactGroupSelection,\n} from './relations'\nimport { createPlanner, type QueryInput, type StoredConstraint } from './querying/planner'\nimport { executeQuery, type ExecutionRequest } from './querying/execution'\nimport {\n\trelationshipExecutor,\n\tassertRelationshipDepth,\n\ttype OutputSelection,\n\ttype RelationDocument,\n\ttype GroupAccess,\n\ttype ResolvedGroups,\n} from './querying/relationships'\nimport {\n\tcreateCursorCodec,\n\tcreateScopedCursorCodec,\n\ttype ScopedCursorOptions,\n\ttype ScopedCursorCodec,\n\tcreateEnvironmentCursorCodec,\n\ttype CursorCodecConfig,\n\ttype CursorBinding,\n} from './querying/cursors'\nimport {\n\tcreateManagedSecurity,\n\ttype ManagedSecurityConfig,\n\ttype ManagedQueryContext,\n\ttype ManagedBudgets,\n\ttype ManagedScope,\n\tManagedReadError,\n} from './querying/security'\nimport type { FilterAst, IndexCondition, NativePagination } from './querying/filters'\nimport type { GenericDatabaseReader } from 'convex/server'\nimport type { Value } from 'convex/values'\n\nimport { planSearch, executeSearch, SearchError } from './querying/search'\nexport { SearchError } from './querying/search'\nexport type { SearchPaginationResult } from './querying/search'\nexport { queryFailureContract } from './querying/failures'\nexport { CursorError } from './querying/cursors'\nexport type { ScopedCursorOptions, ScopedCursorCodec } from './querying/cursors'\n\nconst emptyGroups: ResolvedGroups = { fieldGroups: {}, relations: {} }\n\ntype FullMask<S> = {\n\t[K in keyof S]-?: NonNullable<S[K]> extends true\n\t\t? true\n\t\t: FullMask<Exclude<NonNullable<S[K]>, true>>\n}\ntype Paths<\n\tD extends RelationDeclarations,\n\tT extends string,\n\tL extends readonly 1[] = [1, 1, 1, 1],\n> = L extends readonly [1, ...infer Rest extends 1[]]\n\t? {\n\t\t\t[K in keyof D[T] & string]:\n\t\t\t\t| (D[T][K]['cardinality'] extends 'many' ? K : never)\n\t\t\t\t| `${K}.${Paths<D, D[T][K]['target'], Rest>}`\n\t\t}[keyof D[T] & string]\n\t: never\ntype PathTarget<\n\tD extends RelationDeclarations,\n\tT extends string,\n\tP extends string,\n> = P extends `${infer Head}.${infer Rest}`\n\t? PathTarget<D, D[T][Head]['target'], Rest>\n\t: D[T][P]['target']\ntype PathScope<\n\tD extends RelationDeclarations,\n\tT extends string,\n\tP extends string,\n> = P extends `${infer Head}.${infer Rest}`\n\t? PathScope<D, D[T][Head]['target'], Rest>\n\t: Extract<NonNullable<D[T][P]['targetGuard']>['tag'], string>\ntype RemainingDepth<P extends string, L extends readonly 1[]> = L extends readonly [\n\t1,\n\t...infer Rest extends 1[],\n]\n\t? P extends `${string}.${infer Tail}`\n\t\t? RemainingDepth<Tail, Rest>\n\t\t: Rest\n\t: []\ntype EngineArgs<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n> = NativePagination & {\n\tfilters?: RelationFilters<Tables, D, T, FullMask<RelationFilterSelection<Tables, D, T>>>\n\torder?: 'asc' | 'desc'\n}\n/** Typed declarative chain returned by the engine; named for consumer declaration emission. */\nexport interface TableQuery<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tS = {},\n\tL extends readonly 1[] = [1, 1, 1, 1],\n\tScope extends string = never,\n\tSchema extends SchemaDefinition<GenericSchema, boolean> = SchemaDefinition<\n\t\tGenericSchema,\n\t\tboolean\n\t>,\n\tG = {},\n\tRoot extends boolean = true,\n> {\n\tsearch: Root extends true\n\t\t? (\n\t\t\t\tindex: Extract<\n\t\t\t\t\tkeyof DataModelFromSchemaDefinition<Schema>[Extract<T, string>]['searchIndexes'],\n\t\t\t\t\tstring\n\t\t\t\t>,\n\t\t\t\ttext: string,\n\t\t\t) => SearchQuery<Tables, D, T, S, L, Scope, Schema, G>\n\t\t: never\n\tinclude<const Groups extends FieldGroupRequest<Tables[T]>>(\n\t\tgroups: Groups & Record<Exclude<keyof Groups, keyof FieldGroupRequest<Tables[T]>>, never>,\n\t): TableQuery<\n\t\tTables,\n\t\tD,\n\t\tT,\n\t\tS,\n\t\tL,\n\t\tScope,\n\t\tSchema,\n\t\tOmit<G, 'fieldGroups'> & { fieldGroups: Groups },\n\t\tRoot\n\t>\n\torderBy(\n\t\tindex: Exclude<\n\t\t\tExtract<keyof DataModelFromSchemaDefinition<Schema>[Extract<T, string>]['indexes'], string>,\n\t\t\t'by_id' | 'by_creation_time'\n\t\t>,\n\t): TableQuery<Tables, D, T, S, L, Scope, Schema, G, Root>\n\twhen(\n\t\tvalue: IndexCondition['value'],\n\t\tindex: string,\n\t): TableQuery<Tables, D, T, S, L, Scope, Schema, G, Root>\n\twhere(\n\t\tspec: NonNullable<EngineArgs<Tables, D, T>['filters']>,\n\t): TableQuery<Tables, D, T, S, L, Scope, Schema, G, Root>\n\twith<\n\t\tconst Selection extends RelationSelection<Tables, D, T, L>,\n\t\tconst Groups extends RelationGroupSelection<Tables, D, T, L> = {},\n\t>(\n\t\tselection: Selection & {\n\t\t\t[K in keyof Selection]: K extends keyof RelationSelection<Tables, D, T, L>\n\t\t\t\t? Selection[K]\n\t\t\t\t: never\n\t\t},\n\t\tgroups?: ExactGroupSelection<Tables, D, T, Groups>,\n\t): TableQuery<Tables, D, T, Selection, L, Scope, Schema, Omit<G, keyof Groups> & Groups, Root>\n\trelation<const P extends Paths<D, Extract<T, string>>>(\n\t\tparent: GenericId<Tables[T]['tableName']>,\n\t\tpath: P,\n\t): Omit<\n\t\tTableQuery<\n\t\t\tTables,\n\t\t\tD,\n\t\t\tExtract<PathTarget<D, Extract<T, string>, P>, keyof Tables>,\n\t\t\t{},\n\t\t\tRemainingDepth<P, L>,\n\t\t\tPathScope<D, Extract<T, string>, P>,\n\t\t\tSchema,\n\t\t\t{},\n\t\t\tfalse\n\t\t>,\n\t\t'relation'\n\t>\n\tpaginate(\n\t\targs: EngineArgs<Tables, D, T>,\n\t): Promise<EnginePaginationResult<RelationQueryRow<Tables, D, T, S, Scope, G>>>\n}\n\nexport interface SearchQuery<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tS = {},\n\tL extends readonly 1[] = [1, 1, 1, 1],\n\tScope extends string = never,\n\tSchema extends SchemaDefinition<GenericSchema, boolean> = SchemaDefinition<\n\t\tGenericSchema,\n\t\tboolean\n\t>,\n\tG = {},\n> {\n\tinclude<const Groups extends FieldGroupRequest<Tables[T]>>(\n\t\tgroups: Groups & Record<Exclude<keyof Groups, keyof FieldGroupRequest<Tables[T]>>, never>,\n\t): SearchQuery<\n\t\tTables,\n\t\tD,\n\t\tT,\n\t\tS,\n\t\tL,\n\t\tScope,\n\t\tSchema,\n\t\tOmit<G, 'fieldGroups'> & { fieldGroups: Groups }\n\t>\n\twhere(\n\t\tspec: NonNullable<EngineArgs<Tables, D, T>['filters']>,\n\t): SearchQuery<Tables, D, T, S, L, Scope, Schema, G>\n\twith<\n\t\tconst Selection extends RelationSelection<Tables, D, T, L>,\n\t\tconst Groups extends RelationGroupSelection<Tables, D, T, L> = {},\n\t>(\n\t\tselection: Selection & {\n\t\t\t[K in keyof Selection]: K extends keyof RelationSelection<Tables, D, T, L>\n\t\t\t\t? Selection[K]\n\t\t\t\t: never\n\t\t},\n\t\tgroups?: ExactGroupSelection<Tables, D, T, Groups>,\n\t): SearchQuery<Tables, D, T, Selection, L, Scope, Schema, Omit<G, keyof Groups> & Groups>\n\tpaginate(\n\t\targs: Omit<\n\t\t\tEngineArgs<Tables, D, T>,\n\t\t\t'order' | 'endCursor' | 'maximumRowsRead' | 'maximumBytesRead' | 'onEmptyBudget'\n\t\t> & { scanLimit?: number },\n\t): Promise<\n\t\timport('./querying/search').SearchPaginationResult<RelationQueryRow<Tables, D, T, S, Scope, G>>\n\t>\n}\nexport interface QueryEngineDeclaration<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n> {\n\tschema: Schema\n\trelations: RelationRegistry<Tables, D>\n}\n/** Advanced server configuration, separate from the normal schema/relations declaration. */\nexport interface QueryEngineOptions<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tTables extends RelationTables = RelationTables,\n> {\n\t/** Explicit codecs validate at creation. Otherwise environment keys load at first paginate. */\n\tcursor?: CursorCodecConfig\n\tbudgets?: Partial<ManagedBudgets>\n\tmaxPageSize?: number\n\tpolicyVersion?: string\n\tengineVersion?: string\n\ttrustedAdapter?: ManagedSecurityConfig<DataModelFromSchemaDefinition<Schema>>['trustedAdapter']\n\tfieldGroups?: {\n\t\t[T in keyof Tables]?: {\n\t\t\t[G in keyof NonNullable<Tables[T]['fieldGroups']>]?: (\n\t\t\t\tctx: FieldGroupPolicyContext<Schema>,\n\t\t\t) => boolean | Promise<boolean>\n\t\t}\n\t}\n}\nexport interface FieldGroupPolicyContext<Schema extends SchemaDefinition<GenericSchema, boolean>> {\n\treadonly db: GenericDatabaseReader<DataModelFromSchemaDefinition<Schema>>\n\treadonly scope: ManagedScope\n}\nexport class FieldGroupError extends Error {\n\treadonly code = 'FIELD_GROUP_DENIED'\n\tconstructor() {\n\t\tsuper('FIELD_GROUP_DENIED')\n\t\tthis.name = 'FieldGroupError'\n\t}\n}\n\n/** @deprecated Use QueryEngineDeclaration and optional QueryEngineOptions separately. */\nexport interface QueryEngineConfig<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n>\n\textends QueryEngineDeclaration<Schema, Tables, D>, QueryEngineOptions<Schema, Tables> {\n\tcursor: CursorCodecConfig\n}\n\ntype QueryEngine<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n> = {\n\t(ctx: ManagedQueryContext<DataModelFromSchemaDefinition<Schema>>): {\n\t\t[T in keyof Tables]: TableQuery<Tables, D, T, {}, [1, 1, 1, 1], never, Schema>\n\t}\n\t/** Opens prove integrity only; native consumers must enforce current row authorization. */\n\tcursorCodec<S extends z.ZodType<Value>>(\n\t\tctx: ManagedQueryContext<DataModelFromSchemaDefinition<Schema>>,\n\t\toptions: ScopedCursorOptions<S>,\n\t): ScopedCursorCodec<S>\n\ttables: RelationRegistry<Tables, D>['tables']\n}\n\n/** Central facade. Endpoint chains carry declarative constraints and explicit relationships. */\nexport function createQueryEngine<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tconst Tables extends RelationTables,\n\tconst D extends RelationDeclarations,\n>(\n\tconfig: QueryEngineDeclaration<Schema, Tables, D>,\n\toptions?: QueryEngineOptions<Schema, Tables>,\n): QueryEngine<Schema, Tables, D>\n/** @deprecated Pass advanced fields in the optional second argument. */\nexport function createQueryEngine<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tconst Tables extends RelationTables,\n\tconst D extends RelationDeclarations,\n>(\n\tconfig: QueryEngineDeclaration<Schema, Tables, D> &\n\t\tQueryEngineOptions<Schema, Tables> & { cursor: CursorCodecConfig },\n): QueryEngine<Schema, Tables, D>\nexport function createQueryEngine<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tconst Tables extends RelationTables,\n\tconst D extends RelationDeclarations,\n>(\n\tconfig: QueryEngineDeclaration<Schema, Tables, D> & QueryEngineOptions<Schema, Tables>,\n\toptions?: QueryEngineOptions<Schema, Tables>,\n) {\n\tconst { relations } = config\n\t// Retain released one-argument calls; a second argument overrides legacy fields.\n\tconst settings = { ...config, ...options }\n\tconst planner = createPlanner(config.schema, relations)\n\tconst schema = planner.streamSchema\n\t// Copy callback references once: later option mutation cannot replace engine authority.\n\tconst policies = new Map<\n\t\tstring,\n\t\t(ctx: FieldGroupPolicyContext<Schema>) => boolean | Promise<boolean>\n\t>()\n\tfor (const [table, definitions] of Object.entries(settings.fieldGroups ?? {})) {\n\t\tif (!Object.hasOwn(planner.metadata.tables, table))\n\t\t\tthrow new Error('Unknown field group policy table')\n\t\tfor (const [name, policy] of Object.entries(definitions ?? {})) {\n\t\t\tif (\n\t\t\t\t!Object.hasOwn(planner.metadata.tables[table].fieldGroups, name) ||\n\t\t\t\t!(policy instanceof Function)\n\t\t\t)\n\t\t\t\tthrow new Error('Unknown field group policy')\n\t\t\t// SAFETY: the public mapped options require this policy signature; the function check also rejects malformed JS callers.\n\t\t\tpolicies.set(\n\t\t\t\tJSON.stringify([table, name]),\n\t\t\t\tpolicy as (ctx: FieldGroupPolicyContext<Schema>) => boolean | Promise<boolean>,\n\t\t\t)\n\t\t}\n\t}\n\tlet cursorCodec = settings.cursor === undefined ? undefined : createCursorCodec(settings.cursor)\n\tconst maxPageSize = settings.maxPageSize ?? 100\n\tif (!Number.isSafeInteger(maxPageSize) || maxPageSize <= 0 || maxPageSize > 100)\n\t\tthrow new Error('Invalid central page size')\n\tconst engineVersion = settings.engineVersion ?? 'scalar-1'\n\tconst policyVersion = settings.policyVersion ?? '1'\n\t// Bind the full immutable identity through a collision-resistant digest so\n\t// real application registries fit the codec's bounded AAD.\n\tlet registryDigest: string | undefined\n\tconst security = createManagedSecurity<DataModelFromSchemaDefinition<Schema>>({\n\t\ttables: Object.keys(relations.tables),\n\t\tpolicyVersion,\n\t\tbudgets: settings.budgets,\n\t\ttrustedAdapter: settings.trustedAdapter,\n\t})\n\tfunction querying(ctx: ManagedQueryContext<DataModelFromSchemaDefinition<Schema>>) {\n\t\tconst request = security(ctx)\n\t\tconst decisions = new Map<string, Promise<boolean>>()\n\t\tasync function resolveGroups(table: string, groups: GroupSelection): Promise<ResolvedGroups> {\n\t\t\tconst fieldGroups: ResolvedGroups['fieldGroups'] = {}\n\t\t\tfor (const [name, mode] of Object.entries(groups.fieldGroups ?? {})) {\n\t\t\t\tconst key = JSON.stringify([table, name])\n\t\t\t\tlet decision = decisions.get(key)\n\t\t\t\tif (!decision) {\n\t\t\t\t\tdecision = Promise.resolve().then(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t(await policies.get(key)?.(\n\t\t\t\t\t\t\t\t\tObject.freeze({ db: request.db, scope: request.scope }),\n\t\t\t\t\t\t\t\t)) === true\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif (error instanceof ManagedReadError) throw error\n\t\t\t\t\t\t\tthrow new FieldGroupError()\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\tdecisions.set(key, decision)\n\t\t\t\t}\n\t\t\t\tfieldGroups[name] = { mode, allowed: await decision }\n\t\t\t\tif (mode === 'required' && !fieldGroups[name].allowed) throw new FieldGroupError()\n\t\t\t}\n\t\t\tconst nested: ResolvedGroups['relations'] = {}\n\t\t\tfor (const [name, selection] of Object.entries(groups.relations ?? {}))\n\t\t\t\tnested[name] = await resolveGroups(\n\t\t\t\t\tplanner.metadata.declarations[table][name].target,\n\t\t\t\t\tselection,\n\t\t\t\t)\n\t\t\treturn { fieldGroups, relations: nested }\n\t\t}\n\t\tfunction tableQuery(\n\t\t\ttable: string,\n\t\t\tconditions: readonly IndexCondition[] = [],\n\t\t\tconstraints: readonly StoredConstraint[] = [],\n\t\t\tselection: OutputSelection = {},\n\t\t\troute?: { table: string; parent: string; path: string[] },\n\t\t\tordering?: string,\n\t\t\tgroups: GroupSelection = {},\n\t\t\tsearch?: { index: string; text: string },\n\t\t) {\n\t\t\treturn Object.freeze({\n\t\t\t\tinclude: (fieldGroups: GroupSelection['fieldGroups']) =>\n\t\t\t\t\ttableQuery(\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tconditions,\n\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\tselection,\n\t\t\t\t\t\troute,\n\t\t\t\t\t\tordering,\n\t\t\t\t\t\tplanner.groups(table, { ...groups, fieldGroups }),\n\t\t\t\t\t\tsearch,\n\t\t\t\t\t),\n\t\t\t\torderBy: (index: string) => {\n\t\t\t\t\tif (search) throw new SearchError('SEARCH_ORDER_UNSUPPORTED')\n\t\t\t\t\tif (!z.string().safeParse(index).success) throw new Error('Unknown ordering index')\n\t\t\t\t\treturn tableQuery(table, conditions, constraints, selection, route, index, groups, search)\n\t\t\t\t},\n\t\t\t\twhen: (value: IndexCondition['value'], index: string) => {\n\t\t\t\t\tif (search && value != null) throw new SearchError('SEARCH_ORDER_UNSUPPORTED')\n\t\t\t\t\treturn tableQuery(\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\t[...conditions, { value, index }],\n\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\tselection,\n\t\t\t\t\t\troute,\n\t\t\t\t\t\tordering,\n\t\t\t\t\t\tgroups,\n\t\t\t\t\t\tsearch,\n\t\t\t\t\t)\n\t\t\t\t},\n\t\t\t\twhere: (spec: StoredConstraint) =>\n\t\t\t\t\ttableQuery(\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tconditions,\n\t\t\t\t\t\t[...constraints, spec],\n\t\t\t\t\t\tselection,\n\t\t\t\t\t\troute,\n\t\t\t\t\t\tordering,\n\t\t\t\t\t\tgroups,\n\t\t\t\t\t\tsearch,\n\t\t\t\t\t),\n\t\t\t\twith: (selected: OutputSelection, requested: GroupSelection = {}) =>\n\t\t\t\t\ttableQuery(\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tconditions,\n\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\tselected,\n\t\t\t\t\t\troute,\n\t\t\t\t\t\tordering,\n\t\t\t\t\t\tplanner.groups(table, { ...groups, ...requested }),\n\t\t\t\t\t\tsearch,\n\t\t\t\t\t),\n\t\t\t\tsearch: (index: string, text: string) => {\n\t\t\t\t\tif (route) throw new SearchError('SEARCH_RELATION_UNSUPPORTED')\n\t\t\t\t\tif (ordering !== undefined || conditions.some(({ value }) => value != null))\n\t\t\t\t\t\tthrow new SearchError('SEARCH_ORDER_UNSUPPORTED')\n\t\t\t\t\tif (search) throw new SearchError('SEARCH_OPTIONS_UNSUPPORTED')\n\t\t\t\t\treturn tableQuery(table, conditions, constraints, selection, route, ordering, groups, {\n\t\t\t\t\t\tindex,\n\t\t\t\t\t\ttext,\n\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t\trelation: (parent: string, declaredPath: string) => {\n\t\t\t\t\tif (search) throw new SearchError('SEARCH_RELATION_UNSUPPORTED')\n\t\t\t\t\tconst path = declaredPath.split('.')\n\t\t\t\t\tif (!path.length || path.length > 4) throw new Error('INVALID_RELATION')\n\t\t\t\t\tlet target = table\n\t\t\t\t\tfor (const name of path) {\n\t\t\t\t\t\tconst edge = planner.metadata.declarations[target]?.[name]\n\t\t\t\t\t\tif (!edge) throw new Error('INVALID_RELATION')\n\t\t\t\t\t\ttarget = edge.target\n\t\t\t\t\t}\n\t\t\t\t\treturn tableQuery(target, conditions, constraints, {}, { table, parent, path }, ordering)\n\t\t\t\t},\n\t\t\t\tasync paginate(input: QueryInput) {\n\t\t\t\t\t// Resolve once per global engine, before any native query or policy reads.\n\t\t\t\t\tconst codec = (cursorCodec ??= createEnvironmentCursorCodec())\n\t\t\t\t\tplanner.select(table, selection)\n\t\t\t\t\tassertRelationshipDepth(selection, route?.path.length ?? 0)\n\t\t\t\t\tconst searchPlan = search\n\t\t\t\t\t\t? planSearch(\n\t\t\t\t\t\t\t\tplanner,\n\t\t\t\t\t\t\t\ttable,\n\t\t\t\t\t\t\t\tsearch.index,\n\t\t\t\t\t\t\t\tsearch.text,\n\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: undefined\n\t\t\t\t\tconst plan =\n\t\t\t\t\t\tsearchPlan?.plan ??\n\t\t\t\t\t\tplanner.plan(\n\t\t\t\t\t\t\ttable,\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\troute ? [] : conditions,\n\t\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\t\tordering,\n\t\t\t\t\t\t\troute ? 'relation' : 'root',\n\t\t\t\t\t\t)\n\t\t\t\t\tif (!searchPlan && plan.args.numItems > maxPageSize)\n\t\t\t\t\t\tthrow new Error('Page size exceeds central ceiling')\n\t\t\t\t\tconst resolved = await resolveGroups(table, planner.groups(table, groups))\n\t\t\t\t\tconst groupAccess: GroupAccess = {\n\t\t\t\t\t\tat(path) {\n\t\t\t\t\t\t\treturn path\n\t\t\t\t\t\t\t\t.slice(route?.path.length ?? 0)\n\t\t\t\t\t\t\t\t.reduce((node, name) => node.relations[name] ?? emptyGroups, resolved)\n\t\t\t\t\t\t},\n\t\t\t\t\t\tallowed(path) {\n\t\t\t\t\t\t\treturn Object.entries(this.at(path).fieldGroups)\n\t\t\t\t\t\t\t\t.filter(([, decision]) => decision.allowed)\n\t\t\t\t\t\t\t\t.map(([name]) => name)\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcheckOrder(table, fields, path) {\n\t\t\t\t\t\t\tfor (const field of fields)\n\t\t\t\t\t\t\t\tcheckField(table, field, path ? this.at(path) : emptyGroups)\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t\tfunction checkField(table: string, field: string, groups: ResolvedGroups) {\n\t\t\t\t\t\tfor (const [name, fields] of Object.entries(planner.metadata.tables[table].fieldGroups))\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tfields.includes(field.split('.')[0]) &&\n\t\t\t\t\t\t\t\tgroups.fieldGroups[name]?.allowed !== true\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tthrow new FieldGroupError()\n\t\t\t\t\t}\n\t\t\t\t\tfunction checkClient(table: string, ast: FilterAst, groups: ResolvedGroups): void {\n\t\t\t\t\t\tif (ast.kind === 'scalar') checkField(table, ast.field, groups)\n\t\t\t\t\t\telse if (ast.kind === 'variant') {\n\t\t\t\t\t\t\tcheckField(table, ast.discriminator, groups)\n\t\t\t\t\t\t\tcheckClient(table, ast.child, groups)\n\t\t\t\t\t\t} else if (ast.kind === 'not') checkClient(table, ast.child, groups)\n\t\t\t\t\t\telse if (ast.kind === 'and' || ast.kind === 'or')\n\t\t\t\t\t\t\tfor (const child of ast.children) checkClient(table, child, groups)\n\t\t\t\t\t\telse if (ast.kind === 'relation' && ast.predicate)\n\t\t\t\t\t\t\tcheckClient(\n\t\t\t\t\t\t\t\tplanner.metadata.declarations[table][ast.name].target,\n\t\t\t\t\t\t\t\tast.predicate,\n\t\t\t\t\t\t\t\tgroups.relations[ast.name] ?? emptyGroups,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\t// Inspect the whole client tree independently of execution/contradiction short circuits.\n\t\t\t\t\tif (plan.residual.kind !== 'and') throw new Error('Invalid compiled filter root')\n\t\t\t\t\tcheckClient(table, plan.residual.children[0], resolved)\n\t\t\t\t\tif (searchPlan) checkField(table, searchPlan.metadata.searchField, resolved)\n\t\t\t\t\tconst sortIndex =\n\t\t\t\t\t\tordering ?? conditions.find((condition) => condition.value != null)?.index\n\t\t\t\t\tif (!searchPlan && sortIndex !== undefined)\n\t\t\t\t\t\tfor (const field of planner.metadata.tables[table].indexes.find(\n\t\t\t\t\t\t\t(index) => index.name === sortIndex,\n\t\t\t\t\t\t)?.fields ?? [])\n\t\t\t\t\t\t\tcheckField(table, field, resolved)\n\t\t\t\t\telse if (!searchPlan && !route && plan.index)\n\t\t\t\t\t\tfor (const field of plan.index.fields.slice(plan.prefix.length))\n\t\t\t\t\t\t\tcheckField(table, field, resolved)\n\t\t\t\t\t// Native root limits stay native; lowering those limits cannot raise\n\t\t\t\t\t// the independent shared request meter.\n\t\t\t\t\tplan.args.maximumRowsRead = Math.min(\n\t\t\t\t\t\tplan.args.maximumRowsRead ?? request.budgets.rawCandidates,\n\t\t\t\t\t\trequest.budgets.rawCandidates,\n\t\t\t\t\t)\n\t\t\t\t\tplan.args.maximumBytesRead = Math.min(\n\t\t\t\t\t\tplan.args.maximumBytesRead ?? request.budgets.documentBytes,\n\t\t\t\t\t\trequest.budgets.documentBytes,\n\t\t\t\t\t)\n\t\t\t\t\tregistryDigest ??= Array.from(\n\t\t\t\t\t\tnew Uint8Array(\n\t\t\t\t\t\t\tawait crypto.subtle.digest('SHA-256', new TextEncoder().encode(relations.identity)),\n\t\t\t\t\t\t),\n\t\t\t\t\t\t(byte) => byte.toString(16).padStart(2, '0'),\n\t\t\t\t\t).join('')\n\t\t\t\t\tconst groupBinding: Record<string, Value> = {}\n\t\t\t\t\tif (hasGroups(resolved)) groupBinding.fieldGroups = resolved\n\t\t\t\t\t// SAFETY: selection has passed registry admission before cursor binding.\n\t\t\t\t\tconst serverFilters: CursorBinding['serverFilters'] = {\n\t\t\t\t\t\tpredicates: plan.serverIdentity,\n\t\t\t\t\t\tselection: selection as import('convex/values').Value,\n\t\t\t\t\t\t...groupBinding,\n\t\t\t\t\t\tscope: { ...request.scope },\n\t\t\t\t\t}\n\t\t\t\t\tif (searchPlan) serverFilters.search = {\n\t\t\t\t\t\tmode: 'search', text: searchPlan.text,\n\t\t\t\t\t\tindex: {...searchPlan.metadata, filterFields: [...searchPlan.metadata.filterFields]},\n\t\t\t\t\t\tequalities: searchPlan.equalities, scanLimit: searchPlan.scanLimit ?? null,\n\t\t\t\t\t}\n\t\t\t\t\tconst binding: CursorBinding = {\n\t\t\t\t\t\ttable: route?.table ?? table,\n\t\t\t\t\t\tindex: searchPlan?.metadata.name ?? plan.index?.name ?? 'by_creation_time',\n\t\t\t\t\t\torder: plan.args.order ?? 'asc',\n\t\t\t\t\t\tclientFilters: plan.clientIdentity,\n\t\t\t\t\t\t// Include output selection and the complete immutable scope in trusted identity.\n\t\t\t\t\t\tserverFilters,\n\t\t\t\t\t\trelationPath: [],\n\t\t\t\t\t\tprincipal: JSON.stringify(request.scope),\n\t\t\t\t\t\ttenant: request.scope.tenant,\n\t\t\t\t\t\tpolicyVersion,\n\t\t\t\t\t\tengineVersion,\n\t\t\t\t\t\tregistryVersion: registryDigest,\n\t\t\t\t\t}\n\t\t\t\t\t// The executor accepts registry-selected native tables, rather than a static DM key.\n\t\t\t\t\tconst executorRequest: unknown = request\n\t\t\t\t\t// SAFETY: only native DM types are erased at this private executor boundary.\n\t\t\t\t\tconst executionRequest = executorRequest as ExecutionRequest\n\t\t\t\t\tconst executor = relationshipExecutor(\n\t\t\t\t\t\tschema,\n\t\t\t\t\t\texecutionRequest,\n\t\t\t\t\t\tplanner,\n\t\t\t\t\t\tcodec,\n\t\t\t\t\t\tbinding,\n\t\t\t\t\t\tgroupAccess,\n\t\t\t\t\t)\n\t\t\t\t\texecutor.preflight(table, selection, plan.args, route?.path ?? [])\n\t\t\t\t\tconst result = searchPlan\n\t\t\t\t\t\t? await executeSearch(\n\t\t\t\t\t\t\t\texecutionRequest,\n\t\t\t\t\t\t\t\ttable,\n\t\t\t\t\t\t\t\tsearchPlan,\n\t\t\t\t\t\t\t\tcodec,\n\t\t\t\t\t\t\t\tbinding,\n\t\t\t\t\t\t\t\tmaxPageSize,\n\t\t\t\t\t\t\t\tasync (row) => {\n\t\t\t\t\t\t\t\t\t// SAFETY: native search returns system fields from the admitted registry table.\n\t\t\t\t\t\t\t\t\tconst document = row as RelationDocument\n\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t!(await request.authorize(table, row)) ||\n\t\t\t\t\t\t\t\t\t\t!(await executor.matches(table, document, plan.residual))\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\treturn null\n\t\t\t\t\t\t\t\t\treturn executor.output(table, document, selection, plan.args)\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: route\n\t\t\t\t\t\t\t? await executor.continuation(\n\t\t\t\t\t\t\t\t\troute.table,\n\t\t\t\t\t\t\t\t\troute.parent,\n\t\t\t\t\t\t\t\t\troute.path,\n\t\t\t\t\t\t\t\t\tselection,\n\t\t\t\t\t\t\t\t\tplan.args,\n\t\t\t\t\t\t\t\t\tconditions,\n\t\t\t\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\t\t\t\tordering,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: await executeQuery(\n\t\t\t\t\t\t\t\t\tschema,\n\t\t\t\t\t\t\t\t\trequest,\n\t\t\t\t\t\t\t\t\ttable,\n\t\t\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t\t\tplanner,\n\t\t\t\t\t\t\t\t\tcodec,\n\t\t\t\t\t\t\t\t\tbinding,\n\t\t\t\t\t\t\t\t\tasync (row, permitted) => {\n\t\t\t\t\t\t\t\t\t\t// SAFETY: metered native stream rows contain the validated system fields.\n\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t!permitted ||\n\t\t\t\t\t\t\t\t\t\t\t!(await executor.matches(table, row as RelationDocument, plan.residual))\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\treturn null\n\t\t\t\t\t\t\t\t\t\t// SAFETY: the same native row is authorized and matches the declared predicates.\n\t\t\t\t\t\t\t\t\t\treturn executor.output(table, row as RelationDocument, selection, plan.args)\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t// SAFETY: the private executor validated and projected every row against\n\t\t\t\t\t// this registry's DTO and selected edges before assembling the page.\n\t\t\t\t\treturn result as EnginePaginationResult<\n\t\t\t\t\t\tRelationQueryRow<Tables, D, keyof Tables, OutputSelection>\n\t\t\t\t\t>\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\t// SAFETY: each key comes from the exact validated registry; the planner\n\t\t// validates all input and projection while mapped types retain table brands.\n\t\treturn Object.freeze(\n\t\t\tObject.fromEntries(Object.keys(relations.tables).map((table) => [table, tableQuery(table)])),\n\t\t) as { [T in keyof Tables]: TableQuery<Tables, D, T, {}, [1, 1, 1, 1], never, Schema> }\n\t}\n\treturn Object.assign(querying, {\n\t\ttables: relations.tables,\n\t\tcursorCodec<S extends z.ZodType<Value>>(\n\t\t\tctx: ManagedQueryContext<DataModelFromSchemaDefinition<Schema>>,\n\t\t\toptions: ScopedCursorOptions<S>,\n\t\t): ScopedCursorCodec<S> {\n\t\t\t// Admission precedes lazy key loading and all schema/codec operations.\n\t\t\tconst scope = security.cursorScope(ctx)\n\t\t\tcursorCodec ??= createEnvironmentCursorCodec()\n\t\t\treturn createScopedCursorCodec(cursorCodec.custom, scope, options)\n\t\t},\n\t})\n}\n\nfunction hasGroups(groups: ResolvedGroups): boolean {\n\treturn (\n\t\tObject.keys(groups.fieldGroups).length > 0 || Object.values(groups.relations).some(hasGroups)\n\t)\n}\n"],"mappings":"+lBAuDA,MAAMC,EAA8B,CAAE,YAAa,CAAC,EAAG,UAAW,CAAC,CAAE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OACC,OAAO,KAAK5C,EAAO,WAAW,CAAC,CAAC,OAAS,GAAK,OAAO,OAAOA,EAAO,SAAS,CAAC,CAAC,KAAK4C,CAAS,CAE9F"}
1
+ {"version":3,"file":"querying.mjs","names":["executorRequest","emptyGroups","FieldGroupError","createQueryEngine","config","settings","options","planner","createPlanner","relations","schema","policies","table","definitions","name","policy","cursorCodec","createCursorCodec","maxPageSize","engineVersion","policyVersion","legacyDigest","security","createManagedSecurity","querying","request","ctx","decisions","resolveGroups","fieldGroups","mode","groups","key","decision","error","ManagedReadError","nested","selection","tableQuery","conditions","constraints","route","ordering","search","SearchError","z","index","value","spec","selected","requested","path","declaredPath","target","edge","codec","createEnvironmentCursorCodec","assertRelationshipDepth","searchPlan","planSearch","input","plan","resolved","groupAccess","node","field","fields","checkField","checkClient","ast","child","sortIndex","condition","registryVersion","groupBinding","hasGroups","serverFilters","binding","executionRequest","legacy","opener","token","cursorBinding","execute","executor","relationshipExecutor","executeSearch","document","row","executeQuery","permitted","result","digest","scope","createScopedCursorCodec","CursorError","queryFailureContract"],"sources":["../src/querying.ts"],"sourcesContent":["import type { GenericSchema, SchemaDefinition, DataModelFromSchemaDefinition } from 'convex/server'\nimport type { GenericId } from 'convex/values'\nimport type { EnginePaginationResult } from './zod-table'\nimport { z } from 'zod'\nimport type {\n\tRelationTables,\n\tRelationDeclarations,\n\tRelationRegistry,\n\tRelationQueryRow,\n\tRelationSelection,\n\tRelationFilters,\n\tRelationFilterSelection,\n\tFieldGroupRequest,\n\tRelationGroupSelection,\n\tGroupSelection,\n\tExactGroupSelection,\n} from './relations'\nimport {\n\tcreatePlanner,\n\tdigest,\n\ttype QueryInput,\n\ttype StoredConstraint,\n} from './querying/planner'\nimport { executeQuery, type ExecutionRequest } from './querying/execution'\nimport {\n\trelationshipExecutor,\n\tassertRelationshipDepth,\n\ttype OutputSelection,\n\ttype RelationDocument,\n\ttype GroupAccess,\n\ttype ResolvedGroups,\n} from './querying/relationships'\nimport {\n\tcreateCursorCodec,\n\tcreateScopedCursorCodec,\n\ttype ScopedCursorOptions,\n\ttype ScopedCursorCodec,\n\tcreateEnvironmentCursorCodec,\n\ttype CursorCodecConfig,\n\ttype CursorBinding,\n} from './querying/cursors'\nimport {\n\tcreateManagedSecurity,\n\ttype ManagedSecurityConfig,\n\ttype ManagedQueryContext,\n\ttype ManagedBudgets,\n\ttype ManagedScope,\n\tManagedReadError,\n} from './querying/security'\nimport type { FilterAst, IndexCondition, NativePagination } from './querying/filters'\nimport type { GenericDatabaseReader } from 'convex/server'\nimport type { Value } from 'convex/values'\n\nimport { planSearch, executeSearch, SearchError } from './querying/search'\nexport { SearchError } from './querying/search'\nexport type { SearchPaginationResult } from './querying/search'\nexport { queryFailureContract } from './querying/failures'\nexport { CursorError } from './querying/cursors'\nexport type { ScopedCursorOptions, ScopedCursorCodec } from './querying/cursors'\n\nconst emptyGroups: ResolvedGroups = { fieldGroups: {}, relations: {} }\n\ntype FullMask<S> = {\n\t[K in keyof S]-?: NonNullable<S[K]> extends true\n\t\t? true\n\t\t: FullMask<Exclude<NonNullable<S[K]>, true>>\n}\ntype Paths<\n\tD extends RelationDeclarations,\n\tT extends string,\n\tL extends readonly 1[] = [1, 1, 1, 1],\n> = L extends readonly [1, ...infer Rest extends 1[]]\n\t? {\n\t\t\t[K in keyof D[T] & string]:\n\t\t\t\t| (D[T][K]['cardinality'] extends 'many' ? K : never)\n\t\t\t\t| `${K}.${Paths<D, D[T][K]['target'], Rest>}`\n\t\t}[keyof D[T] & string]\n\t: never\ntype PathTarget<\n\tD extends RelationDeclarations,\n\tT extends string,\n\tP extends string,\n> = P extends `${infer Head}.${infer Rest}`\n\t? PathTarget<D, D[T][Head]['target'], Rest>\n\t: D[T][P]['target']\ntype PathScope<\n\tD extends RelationDeclarations,\n\tT extends string,\n\tP extends string,\n> = P extends `${infer Head}.${infer Rest}`\n\t? PathScope<D, D[T][Head]['target'], Rest>\n\t: Extract<NonNullable<D[T][P]['targetGuard']>['tag'], string>\ntype RemainingDepth<P extends string, L extends readonly 1[]> = L extends readonly [\n\t1,\n\t...infer Rest extends 1[],\n]\n\t? P extends `${string}.${infer Tail}`\n\t\t? RemainingDepth<Tail, Rest>\n\t\t: Rest\n\t: []\ntype EngineArgs<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n> = NativePagination & {\n\tfilters?: RelationFilters<Tables, D, T, FullMask<RelationFilterSelection<Tables, D, T>>>\n\torder?: 'asc' | 'desc'\n}\n/** Typed declarative chain returned by the engine; named for consumer declaration emission. */\nexport interface TableQuery<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tS = {},\n\tL extends readonly 1[] = [1, 1, 1, 1],\n\tScope extends string = never,\n\tSchema extends SchemaDefinition<GenericSchema, boolean> = SchemaDefinition<\n\t\tGenericSchema,\n\t\tboolean\n\t>,\n\tG = {},\n\tRoot extends boolean = true,\n> {\n\tsearch: Root extends true\n\t\t? (\n\t\t\t\tindex: Extract<\n\t\t\t\t\tkeyof DataModelFromSchemaDefinition<Schema>[Extract<T, string>]['searchIndexes'],\n\t\t\t\t\tstring\n\t\t\t\t>,\n\t\t\t\ttext: string,\n\t\t\t) => SearchQuery<Tables, D, T, S, L, Scope, Schema, G>\n\t\t: never\n\tinclude<const Groups extends FieldGroupRequest<Tables[T]>>(\n\t\tgroups: Groups & Record<Exclude<keyof Groups, keyof FieldGroupRequest<Tables[T]>>, never>,\n\t): TableQuery<\n\t\tTables,\n\t\tD,\n\t\tT,\n\t\tS,\n\t\tL,\n\t\tScope,\n\t\tSchema,\n\t\tOmit<G, 'fieldGroups'> & { fieldGroups: Groups },\n\t\tRoot\n\t>\n\torderBy(\n\t\tindex: Exclude<\n\t\t\tExtract<keyof DataModelFromSchemaDefinition<Schema>[Extract<T, string>]['indexes'], string>,\n\t\t\t'by_id' | 'by_creation_time'\n\t\t>,\n\t): TableQuery<Tables, D, T, S, L, Scope, Schema, G, Root>\n\twhen(\n\t\tvalue: IndexCondition['value'],\n\t\tindex: string,\n\t): TableQuery<Tables, D, T, S, L, Scope, Schema, G, Root>\n\twhere(\n\t\tspec: NonNullable<EngineArgs<Tables, D, T>['filters']>,\n\t): TableQuery<Tables, D, T, S, L, Scope, Schema, G, Root>\n\twith<\n\t\tconst Selection extends RelationSelection<Tables, D, T, L>,\n\t\tconst Groups extends RelationGroupSelection<Tables, D, T, L> = {},\n\t>(\n\t\tselection: Selection & {\n\t\t\t[K in keyof Selection]: K extends keyof RelationSelection<Tables, D, T, L>\n\t\t\t\t? Selection[K]\n\t\t\t\t: never\n\t\t},\n\t\tgroups?: ExactGroupSelection<Tables, D, T, Groups>,\n\t): TableQuery<Tables, D, T, Selection, L, Scope, Schema, Omit<G, keyof Groups> & Groups, Root>\n\trelation<const P extends Paths<D, Extract<T, string>>>(\n\t\tparent: GenericId<Tables[T]['tableName']>,\n\t\tpath: P,\n\t): Omit<\n\t\tTableQuery<\n\t\t\tTables,\n\t\t\tD,\n\t\t\tExtract<PathTarget<D, Extract<T, string>, P>, keyof Tables>,\n\t\t\t{},\n\t\t\tRemainingDepth<P, L>,\n\t\t\tPathScope<D, Extract<T, string>, P>,\n\t\t\tSchema,\n\t\t\t{},\n\t\t\tfalse\n\t\t>,\n\t\t'relation'\n\t>\n\tpaginate(\n\t\targs: EngineArgs<Tables, D, T>,\n\t): Promise<EnginePaginationResult<RelationQueryRow<Tables, D, T, S, Scope, G>>>\n}\n\nexport interface SearchQuery<\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n\tT extends keyof Tables,\n\tS = {},\n\tL extends readonly 1[] = [1, 1, 1, 1],\n\tScope extends string = never,\n\tSchema extends SchemaDefinition<GenericSchema, boolean> = SchemaDefinition<\n\t\tGenericSchema,\n\t\tboolean\n\t>,\n\tG = {},\n> {\n\tinclude<const Groups extends FieldGroupRequest<Tables[T]>>(\n\t\tgroups: Groups & Record<Exclude<keyof Groups, keyof FieldGroupRequest<Tables[T]>>, never>,\n\t): SearchQuery<\n\t\tTables,\n\t\tD,\n\t\tT,\n\t\tS,\n\t\tL,\n\t\tScope,\n\t\tSchema,\n\t\tOmit<G, 'fieldGroups'> & { fieldGroups: Groups }\n\t>\n\twhere(\n\t\tspec: NonNullable<EngineArgs<Tables, D, T>['filters']>,\n\t): SearchQuery<Tables, D, T, S, L, Scope, Schema, G>\n\twith<\n\t\tconst Selection extends RelationSelection<Tables, D, T, L>,\n\t\tconst Groups extends RelationGroupSelection<Tables, D, T, L> = {},\n\t>(\n\t\tselection: Selection & {\n\t\t\t[K in keyof Selection]: K extends keyof RelationSelection<Tables, D, T, L>\n\t\t\t\t? Selection[K]\n\t\t\t\t: never\n\t\t},\n\t\tgroups?: ExactGroupSelection<Tables, D, T, Groups>,\n\t): SearchQuery<Tables, D, T, Selection, L, Scope, Schema, Omit<G, keyof Groups> & Groups>\n\tpaginate(\n\t\targs: Omit<\n\t\t\tEngineArgs<Tables, D, T>,\n\t\t\t'order' | 'endCursor' | 'maximumRowsRead' | 'maximumBytesRead' | 'onEmptyBudget'\n\t\t> & { scanLimit?: number },\n\t): Promise<\n\t\timport('./querying/search').SearchPaginationResult<RelationQueryRow<Tables, D, T, S, Scope, G>>\n\t>\n}\nexport interface QueryEngineDeclaration<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n> {\n\tschema: Schema\n\trelations: RelationRegistry<Tables, D>\n}\n/** Advanced server configuration, separate from the normal schema/relations declaration. */\nexport interface QueryEngineOptions<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tTables extends RelationTables = RelationTables,\n> {\n\t/** Explicit codecs validate at creation. Otherwise environment keys load at first paginate. */\n\tcursor?: CursorCodecConfig\n\tbudgets?: Partial<ManagedBudgets>\n\tmaxPageSize?: number\n\tpolicyVersion?: string\n\tengineVersion?: string\n\ttrustedAdapter?: ManagedSecurityConfig<DataModelFromSchemaDefinition<Schema>>['trustedAdapter']\n\tfieldGroups?: {\n\t\t[T in keyof Tables]?: {\n\t\t\t[G in keyof NonNullable<Tables[T]['fieldGroups']>]?: (\n\t\t\t\tctx: FieldGroupPolicyContext<Schema>,\n\t\t\t) => boolean | Promise<boolean>\n\t\t}\n\t}\n}\nexport interface FieldGroupPolicyContext<Schema extends SchemaDefinition<GenericSchema, boolean>> {\n\treadonly db: GenericDatabaseReader<DataModelFromSchemaDefinition<Schema>>\n\treadonly scope: ManagedScope\n}\nexport class FieldGroupError extends Error {\n\treadonly code = 'FIELD_GROUP_DENIED'\n\tconstructor() {\n\t\tsuper('FIELD_GROUP_DENIED')\n\t\tthis.name = 'FieldGroupError'\n\t}\n}\n\n/** @deprecated Use QueryEngineDeclaration and optional QueryEngineOptions separately. */\nexport interface QueryEngineConfig<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n>\n\textends QueryEngineDeclaration<Schema, Tables, D>, QueryEngineOptions<Schema, Tables> {\n\tcursor: CursorCodecConfig\n}\n\ntype QueryEngine<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tTables extends RelationTables,\n\tD extends RelationDeclarations,\n> = {\n\t(ctx: ManagedQueryContext<DataModelFromSchemaDefinition<Schema>>): {\n\t\t[T in keyof Tables]: TableQuery<Tables, D, T, {}, [1, 1, 1, 1], never, Schema>\n\t}\n\t/** Opens prove integrity only; native consumers must enforce current row authorization. */\n\tcursorCodec<S extends z.ZodType<Value>>(\n\t\tctx: ManagedQueryContext<DataModelFromSchemaDefinition<Schema>>,\n\t\toptions: ScopedCursorOptions<S>,\n\t): ScopedCursorCodec<S>\n\ttables: RelationRegistry<Tables, D>['tables']\n}\n\n/** Central facade. Endpoint chains carry declarative constraints and explicit relationships. */\nexport function createQueryEngine<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tconst Tables extends RelationTables,\n\tconst D extends RelationDeclarations,\n>(\n\tconfig: QueryEngineDeclaration<Schema, Tables, D>,\n\toptions?: QueryEngineOptions<Schema, Tables>,\n): QueryEngine<Schema, Tables, D>\n/** @deprecated Pass advanced fields in the optional second argument. */\nexport function createQueryEngine<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tconst Tables extends RelationTables,\n\tconst D extends RelationDeclarations,\n>(\n\tconfig: QueryEngineDeclaration<Schema, Tables, D> &\n\t\tQueryEngineOptions<Schema, Tables> & { cursor: CursorCodecConfig },\n): QueryEngine<Schema, Tables, D>\nexport function createQueryEngine<\n\tSchema extends SchemaDefinition<GenericSchema, boolean>,\n\tconst Tables extends RelationTables,\n\tconst D extends RelationDeclarations,\n>(\n\tconfig: QueryEngineDeclaration<Schema, Tables, D> & QueryEngineOptions<Schema, Tables>,\n\toptions?: QueryEngineOptions<Schema, Tables>,\n) {\n\tconst { relations } = config\n\t// Retain released one-argument calls; a second argument overrides legacy fields.\n\tconst settings = { ...config, ...options }\n\tconst planner = createPlanner(config.schema, relations)\n\tconst schema = planner.streamSchema\n\t// Copy callback references once: later option mutation cannot replace engine authority.\n\tconst policies = new Map<\n\t\tstring,\n\t\t(ctx: FieldGroupPolicyContext<Schema>) => boolean | Promise<boolean>\n\t>()\n\tfor (const [table, definitions] of Object.entries(settings.fieldGroups ?? {})) {\n\t\tif (!Object.hasOwn(planner.metadata.tables, table))\n\t\t\tthrow new Error('Unknown field group policy table')\n\t\tfor (const [name, policy] of Object.entries(definitions ?? {})) {\n\t\t\tif (\n\t\t\t\t!Object.hasOwn(planner.metadata.tables[table].fieldGroups, name) ||\n\t\t\t\t!(policy instanceof Function)\n\t\t\t)\n\t\t\t\tthrow new Error('Unknown field group policy')\n\t\t\t// SAFETY: the public mapped options require this policy signature; the function check also rejects malformed JS callers.\n\t\t\tpolicies.set(\n\t\t\t\tJSON.stringify([table, name]),\n\t\t\t\tpolicy as (ctx: FieldGroupPolicyContext<Schema>) => boolean | Promise<boolean>,\n\t\t\t)\n\t\t}\n\t}\n\tlet cursorCodec = settings.cursor === undefined ? undefined : createCursorCodec(settings.cursor)\n\tconst maxPageSize = settings.maxPageSize ?? 100\n\tif (!Number.isSafeInteger(maxPageSize) || maxPageSize <= 0 || maxPageSize > 100)\n\t\tthrow new Error('Invalid central page size')\n\tconst engineVersion = settings.engineVersion ?? 'scalar-1'\n\tconst policyVersion = settings.policyVersion ?? '1'\n\t// Cursors from 0.1.24 and earlier bound the full registry identity, not the\n\t// scope of their query. They still open: the first one in an engine pays for\n\t// the full digest once, and every continuation reseals under its scope.\n\tlet legacyDigest: string | undefined\n\tconst security = createManagedSecurity<DataModelFromSchemaDefinition<Schema>>({\n\t\ttables: Object.keys(relations.tables),\n\t\tpolicyVersion,\n\t\tbudgets: settings.budgets,\n\t\ttrustedAdapter: settings.trustedAdapter,\n\t})\n\tfunction querying(ctx: ManagedQueryContext<DataModelFromSchemaDefinition<Schema>>) {\n\t\tconst request = security(ctx)\n\t\tconst decisions = new Map<string, Promise<boolean>>()\n\t\tasync function resolveGroups(table: string, groups: GroupSelection): Promise<ResolvedGroups> {\n\t\t\tconst fieldGroups: ResolvedGroups['fieldGroups'] = {}\n\t\t\tfor (const [name, mode] of Object.entries(groups.fieldGroups ?? {})) {\n\t\t\t\tconst key = JSON.stringify([table, name])\n\t\t\t\tlet decision = decisions.get(key)\n\t\t\t\tif (!decision) {\n\t\t\t\t\tdecision = Promise.resolve().then(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t(await policies.get(key)?.(\n\t\t\t\t\t\t\t\t\tObject.freeze({ db: request.db, scope: request.scope }),\n\t\t\t\t\t\t\t\t)) === true\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif (error instanceof ManagedReadError) throw error\n\t\t\t\t\t\t\tthrow new FieldGroupError()\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\tdecisions.set(key, decision)\n\t\t\t\t}\n\t\t\t\tfieldGroups[name] = { mode, allowed: await decision }\n\t\t\t\tif (mode === 'required' && !fieldGroups[name].allowed) throw new FieldGroupError()\n\t\t\t}\n\t\t\tconst nested: ResolvedGroups['relations'] = {}\n\t\t\tfor (const [name, selection] of Object.entries(groups.relations ?? {}))\n\t\t\t\tnested[name] = await resolveGroups(\n\t\t\t\t\tplanner.metadata.declarations[table][name].target,\n\t\t\t\t\tselection,\n\t\t\t\t)\n\t\t\treturn { fieldGroups, relations: nested }\n\t\t}\n\t\tfunction tableQuery(\n\t\t\ttable: string,\n\t\t\tconditions: readonly IndexCondition[] = [],\n\t\t\tconstraints: readonly StoredConstraint[] = [],\n\t\t\tselection: OutputSelection = {},\n\t\t\troute?: { table: string; parent: string; path: string[] },\n\t\t\tordering?: string,\n\t\t\tgroups: GroupSelection = {},\n\t\t\tsearch?: { index: string; text: string },\n\t\t) {\n\t\t\treturn Object.freeze({\n\t\t\t\tinclude: (fieldGroups: GroupSelection['fieldGroups']) =>\n\t\t\t\t\ttableQuery(\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tconditions,\n\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\tselection,\n\t\t\t\t\t\troute,\n\t\t\t\t\t\tordering,\n\t\t\t\t\t\tplanner.groups(table, { ...groups, fieldGroups }),\n\t\t\t\t\t\tsearch,\n\t\t\t\t\t),\n\t\t\t\torderBy: (index: string) => {\n\t\t\t\t\tif (search) throw new SearchError('SEARCH_ORDER_UNSUPPORTED')\n\t\t\t\t\tif (!z.string().safeParse(index).success) throw new Error('Unknown ordering index')\n\t\t\t\t\treturn tableQuery(table, conditions, constraints, selection, route, index, groups, search)\n\t\t\t\t},\n\t\t\t\twhen: (value: IndexCondition['value'], index: string) => {\n\t\t\t\t\tif (search && value != null) throw new SearchError('SEARCH_ORDER_UNSUPPORTED')\n\t\t\t\t\treturn tableQuery(\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\t[...conditions, { value, index }],\n\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\tselection,\n\t\t\t\t\t\troute,\n\t\t\t\t\t\tordering,\n\t\t\t\t\t\tgroups,\n\t\t\t\t\t\tsearch,\n\t\t\t\t\t)\n\t\t\t\t},\n\t\t\t\twhere: (spec: StoredConstraint) =>\n\t\t\t\t\ttableQuery(\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tconditions,\n\t\t\t\t\t\t[...constraints, spec],\n\t\t\t\t\t\tselection,\n\t\t\t\t\t\troute,\n\t\t\t\t\t\tordering,\n\t\t\t\t\t\tgroups,\n\t\t\t\t\t\tsearch,\n\t\t\t\t\t),\n\t\t\t\twith: (selected: OutputSelection, requested: GroupSelection = {}) =>\n\t\t\t\t\ttableQuery(\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tconditions,\n\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\tselected,\n\t\t\t\t\t\troute,\n\t\t\t\t\t\tordering,\n\t\t\t\t\t\tplanner.groups(table, { ...groups, ...requested }),\n\t\t\t\t\t\tsearch,\n\t\t\t\t\t),\n\t\t\t\tsearch: (index: string, text: string) => {\n\t\t\t\t\tif (route) throw new SearchError('SEARCH_RELATION_UNSUPPORTED')\n\t\t\t\t\tif (ordering !== undefined || conditions.some(({ value }) => value != null))\n\t\t\t\t\t\tthrow new SearchError('SEARCH_ORDER_UNSUPPORTED')\n\t\t\t\t\tif (search) throw new SearchError('SEARCH_OPTIONS_UNSUPPORTED')\n\t\t\t\t\treturn tableQuery(table, conditions, constraints, selection, route, ordering, groups, {\n\t\t\t\t\t\tindex,\n\t\t\t\t\t\ttext,\n\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t\trelation: (parent: string, declaredPath: string) => {\n\t\t\t\t\tif (search) throw new SearchError('SEARCH_RELATION_UNSUPPORTED')\n\t\t\t\t\tconst path = declaredPath.split('.')\n\t\t\t\t\tif (!path.length || path.length > 4) throw new Error('INVALID_RELATION')\n\t\t\t\t\tlet target = table\n\t\t\t\t\tfor (const name of path) {\n\t\t\t\t\t\tconst edge = planner.metadata.declarations[target]?.[name]\n\t\t\t\t\t\tif (!edge) throw new Error('INVALID_RELATION')\n\t\t\t\t\t\ttarget = edge.target\n\t\t\t\t\t}\n\t\t\t\t\treturn tableQuery(target, conditions, constraints, {}, { table, parent, path }, ordering)\n\t\t\t\t},\n\t\t\t\tasync paginate(input: QueryInput) {\n\t\t\t\t\t// Resolve once per global engine, before any native query or policy reads.\n\t\t\t\t\tconst codec = (cursorCodec ??= createEnvironmentCursorCodec())\n\t\t\t\t\tplanner.select(table, selection)\n\t\t\t\t\tassertRelationshipDepth(selection, route?.path.length ?? 0)\n\t\t\t\t\tconst searchPlan = search\n\t\t\t\t\t\t? planSearch(\n\t\t\t\t\t\t\t\tplanner,\n\t\t\t\t\t\t\t\ttable,\n\t\t\t\t\t\t\t\tsearch.index,\n\t\t\t\t\t\t\t\tsearch.text,\n\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: undefined\n\t\t\t\t\tconst plan =\n\t\t\t\t\t\tsearchPlan?.plan ??\n\t\t\t\t\t\tplanner.plan(\n\t\t\t\t\t\t\ttable,\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\troute ? [] : conditions,\n\t\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\t\tordering,\n\t\t\t\t\t\t\troute ? 'relation' : 'root',\n\t\t\t\t\t\t)\n\t\t\t\t\tif (!searchPlan && plan.args.numItems > maxPageSize)\n\t\t\t\t\t\tthrow new Error('Page size exceeds central ceiling')\n\t\t\t\t\tconst resolved = await resolveGroups(table, planner.groups(table, groups))\n\t\t\t\t\tconst groupAccess: GroupAccess = {\n\t\t\t\t\t\tat(path) {\n\t\t\t\t\t\t\treturn path\n\t\t\t\t\t\t\t\t.slice(route?.path.length ?? 0)\n\t\t\t\t\t\t\t\t.reduce((node, name) => node.relations[name] ?? emptyGroups, resolved)\n\t\t\t\t\t\t},\n\t\t\t\t\t\tallowed(path) {\n\t\t\t\t\t\t\treturn Object.entries(this.at(path).fieldGroups)\n\t\t\t\t\t\t\t\t.filter(([, decision]) => decision.allowed)\n\t\t\t\t\t\t\t\t.map(([name]) => name)\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcheckOrder(table, fields, path) {\n\t\t\t\t\t\t\tfor (const field of fields)\n\t\t\t\t\t\t\t\tcheckField(table, field, path ? this.at(path) : emptyGroups)\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t\tfunction checkField(table: string, field: string, groups: ResolvedGroups) {\n\t\t\t\t\t\tfor (const [name, fields] of Object.entries(planner.metadata.tables[table].fieldGroups))\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tfields.includes(field.split('.')[0]) &&\n\t\t\t\t\t\t\t\tgroups.fieldGroups[name]?.allowed !== true\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tthrow new FieldGroupError()\n\t\t\t\t\t}\n\t\t\t\t\tfunction checkClient(table: string, ast: FilterAst, groups: ResolvedGroups): void {\n\t\t\t\t\t\tif (ast.kind === 'scalar') checkField(table, ast.field, groups)\n\t\t\t\t\t\telse if (ast.kind === 'variant') {\n\t\t\t\t\t\t\tcheckField(table, ast.discriminator, groups)\n\t\t\t\t\t\t\tcheckClient(table, ast.child, groups)\n\t\t\t\t\t\t} else if (ast.kind === 'not') checkClient(table, ast.child, groups)\n\t\t\t\t\t\telse if (ast.kind === 'and' || ast.kind === 'or')\n\t\t\t\t\t\t\tfor (const child of ast.children) checkClient(table, child, groups)\n\t\t\t\t\t\telse if (ast.kind === 'relation' && ast.predicate)\n\t\t\t\t\t\t\tcheckClient(\n\t\t\t\t\t\t\t\tplanner.metadata.declarations[table][ast.name].target,\n\t\t\t\t\t\t\t\tast.predicate,\n\t\t\t\t\t\t\t\tgroups.relations[ast.name] ?? emptyGroups,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\t// Inspect the whole client tree independently of execution/contradiction short circuits.\n\t\t\t\t\tif (plan.residual.kind !== 'and') throw new Error('Invalid compiled filter root')\n\t\t\t\t\tcheckClient(table, plan.residual.children[0], resolved)\n\t\t\t\t\tif (searchPlan) checkField(table, searchPlan.metadata.searchField, resolved)\n\t\t\t\t\tconst sortIndex =\n\t\t\t\t\t\tordering ?? conditions.find((condition) => condition.value != null)?.index\n\t\t\t\t\tif (!searchPlan && sortIndex !== undefined)\n\t\t\t\t\t\tfor (const field of planner.metadata.tables[table].indexes.find(\n\t\t\t\t\t\t\t(index) => index.name === sortIndex,\n\t\t\t\t\t\t)?.fields ?? [])\n\t\t\t\t\t\t\tcheckField(table, field, resolved)\n\t\t\t\t\telse if (!searchPlan && !route && plan.index)\n\t\t\t\t\t\tfor (const field of plan.index.fields.slice(plan.prefix.length))\n\t\t\t\t\t\t\tcheckField(table, field, resolved)\n\t\t\t\t\t// Native root limits stay native; lowering those limits cannot raise\n\t\t\t\t\t// the independent shared request meter.\n\t\t\t\t\tplan.args.maximumRowsRead = Math.min(\n\t\t\t\t\t\tplan.args.maximumRowsRead ?? request.budgets.rawCandidates,\n\t\t\t\t\t\trequest.budgets.rawCandidates,\n\t\t\t\t\t)\n\t\t\t\t\tplan.args.maximumBytesRead = Math.min(\n\t\t\t\t\t\tplan.args.maximumBytesRead ?? request.budgets.documentBytes,\n\t\t\t\t\t\trequest.budgets.documentBytes,\n\t\t\t\t\t)\n\t\t\t\t\t// A relation route binds its cursors per child path, in the executor.\n\t\t\t\t\tconst registryVersion = await planner.registryVersion(\n\t\t\t\t\t\troute\n\t\t\t\t\t\t\t? { root: route.table, path: [], selection: {}, groups: emptyGroups, filters: [] }\n\t\t\t\t\t\t\t: { root: table, path: [], selection, groups: resolved, filters: [plan.residual] },\n\t\t\t\t\t)\n\t\t\t\t\tconst groupBinding: Record<string, Value> = {}\n\t\t\t\t\tif (hasGroups(resolved)) groupBinding.fieldGroups = resolved\n\t\t\t\t\t// SAFETY: selection has passed registry admission before cursor binding.\n\t\t\t\t\tconst serverFilters: CursorBinding['serverFilters'] = {\n\t\t\t\t\t\tpredicates: plan.serverIdentity,\n\t\t\t\t\t\tselection: selection as import('convex/values').Value,\n\t\t\t\t\t\t...groupBinding,\n\t\t\t\t\t\tscope: { ...request.scope },\n\t\t\t\t\t}\n\t\t\t\t\tif (searchPlan) serverFilters.search = {\n\t\t\t\t\t\tmode: 'search', text: searchPlan.text,\n\t\t\t\t\t\tindex: {...searchPlan.metadata, filterFields: [...searchPlan.metadata.filterFields]},\n\t\t\t\t\t\tequalities: searchPlan.equalities, scanLimit: searchPlan.scanLimit ?? null,\n\t\t\t\t\t}\n\t\t\t\t\tconst binding: CursorBinding = {\n\t\t\t\t\t\ttable: route?.table ?? table,\n\t\t\t\t\t\tindex: searchPlan?.metadata.name ?? plan.index?.name ?? 'by_creation_time',\n\t\t\t\t\t\torder: plan.args.order ?? 'asc',\n\t\t\t\t\t\tclientFilters: plan.clientIdentity,\n\t\t\t\t\t\t// Include output selection and the complete immutable scope in trusted identity.\n\t\t\t\t\t\tserverFilters,\n\t\t\t\t\t\trelationPath: [],\n\t\t\t\t\t\tprincipal: JSON.stringify(request.scope),\n\t\t\t\t\t\ttenant: request.scope.tenant,\n\t\t\t\t\t\tpolicyVersion,\n\t\t\t\t\t\tengineVersion,\n\t\t\t\t\t\tregistryVersion,\n\t\t\t\t\t}\n\t\t\t\t\t// The executor accepts registry-selected native tables, rather than a static DM key.\n\t\t\t\t\tconst executorRequest: unknown = request\n\t\t\t\t\t// SAFETY: only native DM types are erased at this private executor boundary.\n\t\t\t\t\tconst executionRequest = executorRequest as ExecutionRequest\n\t\t\t\t\tlet legacy = false\n\t\t\t\t\tconst opener: typeof codec = Object.freeze({\n\t\t\t\t\t\t...codec,\n\t\t\t\t\t\topen(token: string, cursorBinding: CursorBinding) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\treturn codec.open(token, cursorBinding)\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tif (legacyDigest === undefined) {\n\t\t\t\t\t\t\t\t\tlegacy = true\n\t\t\t\t\t\t\t\t\tthrow error\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn codec.open(token, { ...cursorBinding, registryVersion: legacyDigest })\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t\tconst execute = async () => {\n\t\t\t\t\t\tconst executor = relationshipExecutor(\n\t\t\t\t\t\t\tschema,\n\t\t\t\t\t\t\texecutionRequest,\n\t\t\t\t\t\t\tplanner,\n\t\t\t\t\t\t\topener,\n\t\t\t\t\t\t\tbinding,\n\t\t\t\t\t\t\tgroupAccess,\n\t\t\t\t\t\t)\n\t\t\t\t\t\texecutor.preflight(table, selection, plan.args, route?.path ?? [])\n\t\t\t\t\t\treturn searchPlan\n\t\t\t\t\t\t\t? await executeSearch(\n\t\t\t\t\t\t\t\t\texecutionRequest,\n\t\t\t\t\t\t\t\t\ttable,\n\t\t\t\t\t\t\t\t\tsearchPlan,\n\t\t\t\t\t\t\t\t\topener,\n\t\t\t\t\t\t\t\t\tbinding,\n\t\t\t\t\t\t\t\t\tmaxPageSize,\n\t\t\t\t\t\t\t\t\tasync (row) => {\n\t\t\t\t\t\t\t\t\t\t// SAFETY: native search returns system fields from the admitted registry table.\n\t\t\t\t\t\t\t\t\t\tconst document = row as RelationDocument\n\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t!(await request.authorize(table, row)) ||\n\t\t\t\t\t\t\t\t\t\t\t!(await executor.matches(table, document, plan.residual))\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\treturn null\n\t\t\t\t\t\t\t\t\t\treturn executor.output(table, document, selection, plan.args)\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: route\n\t\t\t\t\t\t\t\t? await executor.continuation(\n\t\t\t\t\t\t\t\t\t\troute.table,\n\t\t\t\t\t\t\t\t\t\troute.parent,\n\t\t\t\t\t\t\t\t\t\troute.path,\n\t\t\t\t\t\t\t\t\t\tselection,\n\t\t\t\t\t\t\t\t\t\tplan.args,\n\t\t\t\t\t\t\t\t\t\tconditions,\n\t\t\t\t\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\t\t\t\t\tordering,\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t: await executeQuery(\n\t\t\t\t\t\t\t\t\t\tschema,\n\t\t\t\t\t\t\t\t\t\trequest,\n\t\t\t\t\t\t\t\t\t\ttable,\n\t\t\t\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t\t\t\tplanner,\n\t\t\t\t\t\t\t\t\t\topener,\n\t\t\t\t\t\t\t\t\t\tbinding,\n\t\t\t\t\t\t\t\t\t\tasync (row, permitted) => {\n\t\t\t\t\t\t\t\t\t\t\t// SAFETY: metered native stream rows contain the validated system fields.\n\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\t!permitted ||\n\t\t\t\t\t\t\t\t\t\t\t\t!(await executor.matches(table, row as RelationDocument, plan.residual))\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\treturn null\n\t\t\t\t\t\t\t\t\t\t\t// SAFETY: the same native row is authorized and matches the declared predicates.\n\t\t\t\t\t\t\t\t\t\t\treturn executor.output(table, row as RelationDocument, selection, plan.args)\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tlet result: Awaited<ReturnType<typeof execute>>\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresult = await execute()\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!legacy) throw error\n\t\t\t\t\t\t// Every cursor opens before the first read, so the retry repeats no reads.\n\t\t\t\t\t\tlegacyDigest ??= await digest(relations.identity)\n\t\t\t\t\t\tresult = await execute()\n\t\t\t\t\t}\n\t\t\t\t\t// SAFETY: the private executor validated and projected every row against\n\t\t\t\t\t// this registry's DTO and selected edges before assembling the page.\n\t\t\t\t\treturn result as EnginePaginationResult<\n\t\t\t\t\t\tRelationQueryRow<Tables, D, keyof Tables, OutputSelection>\n\t\t\t\t\t>\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\t// SAFETY: each key comes from the exact validated registry; the planner\n\t\t// validates all input and projection while mapped types retain table brands.\n\t\treturn Object.freeze(\n\t\t\tObject.fromEntries(Object.keys(relations.tables).map((table) => [table, tableQuery(table)])),\n\t\t) as { [T in keyof Tables]: TableQuery<Tables, D, T, {}, [1, 1, 1, 1], never, Schema> }\n\t}\n\treturn Object.assign(querying, {\n\t\ttables: relations.tables,\n\t\tcursorCodec<S extends z.ZodType<Value>>(\n\t\t\tctx: ManagedQueryContext<DataModelFromSchemaDefinition<Schema>>,\n\t\t\toptions: ScopedCursorOptions<S>,\n\t\t): ScopedCursorCodec<S> {\n\t\t\t// Admission precedes lazy key loading and all schema/codec operations.\n\t\t\tconst scope = security.cursorScope(ctx)\n\t\t\tcursorCodec ??= createEnvironmentCursorCodec()\n\t\t\treturn createScopedCursorCodec(cursorCodec.custom, scope, options)\n\t\t},\n\t})\n}\n\nfunction hasGroups(groups: ResolvedGroups): boolean {\n\treturn (\n\t\tObject.keys(groups.fieldGroups).length > 0 || Object.values(groups.relations).some(hasGroups)\n\t)\n}\n"],"mappings":"2mBA4DA,MAAMC,EAA8B,CAAE,YAAa,CAAC,EAAG,UAAW,CAAC,CAAE,EAmNrE,IAAaC,EAAb,cAAqC,KAAM,CAC1C,KAAgB,qBAChB,aAAc,CACb,MAAM,oBAAoB,EAC1B,KAAK,KAAO,iBACb,CACD,EA8CA,SAAgBC,EAKf,EACA,EACC,CACD,GAAM,CAAE,aAAcC,EAEhBC,EAAW,CAAE,GAAGD,EAAQ,GAAGE,CAAQ,EACnCC,EAAUC,EAAcJ,EAAO,OAAQK,CAAS,EAChDC,EAASH,EAAQ,aAEjBI,kBAAW,IAAI,IAIrB,IAAK,GAAM,CAACC,EAAOC,KAAg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OAClB,YACC,EACA,EACuB,CAEvB,IAAMoF,EAAQvE,EAAS,YAAYI,CAAG,EAEtC,MADA,KAAgB8B,EAA6B,EACtCsC,EAAwB9E,EAAY,OAAQ6E,EAAOvF,CAAO,CAClE,CACD,CAAC,CACF,CAEA,SAASqE,EAAU,EAAiC,CACnD,OACC,OAAO,KAAK5C,EAAO,WAAW,CAAC,CAAC,OAAS,GAAK,OAAO,OAAOA,EAAO,SAAS,CAAC,CAAC,KAAK4C,CAAS,CAE9F"}
@@ -1,2 +1,2 @@
1
- import { BranchBuilder, FieldGroupMode, FieldGroupRequest, FieldReference, PaginationFiltersInput, RelationBuilder, RelationDeclarations, RelationEdge, RelationFilterSelection, RelationFilters, RelationGroupSelection, RelationRegistry, RelationRegistryIdentity, RelationRow, RelationSelection, RelationTable, RelationTableHelpers, RelationTables, ThroughReference, defineRelations } from "./relations.mjs";
2
- export { type BranchBuilder, type FieldGroupMode, type FieldGroupRequest, type FieldReference, type PaginationFiltersInput, type RelationBuilder, type RelationDeclarations, type RelationEdge, type RelationFilterSelection, type RelationFilters, type RelationGroupSelection, type RelationRegistry, type RelationRegistryIdentity, type RelationRow, type RelationSelection, type RelationTable, type RelationTableHelpers, type RelationTables, type ThroughReference, defineRelations };
1
+ import { BranchBuilder, FieldGroupMode, FieldGroupRequest, FieldReference, PaginationFiltersInput, RelationBuilder, RelationDeclarations, RelationEdge, RelationFilterSelection, RelationFilters, RelationGroupSelection, RelationRegistry, RelationRegistryIdentity, RelationRow, RelationSelection, RelationTable, RelationTableHelpers, RelationTables, ThroughReference, defineRelations, verifyRelations } from "./relations.mjs";
2
+ export { type BranchBuilder, type FieldGroupMode, type FieldGroupRequest, type FieldReference, type PaginationFiltersInput, type RelationBuilder, type RelationDeclarations, type RelationEdge, type RelationFilterSelection, type RelationFilters, type RelationGroupSelection, type RelationRegistry, type RelationRegistryIdentity, type RelationRow, type RelationSelection, type RelationTable, type RelationTableHelpers, type RelationTables, type ThroughReference, defineRelations, verifyRelations };
@@ -1 +1 @@
1
- import{defineRelations as e}from"./relations.mjs";export{e as defineRelations};
1
+ import{defineRelations as e,verifyRelations as t}from"./relations.mjs";export{e as defineRelations,t as verifyRelations};
@@ -227,11 +227,18 @@ export interface RelationMetadata {
227
227
  readonly tables: Readonly<Record<string, RelationTableMetadata>>;
228
228
  readonly declarations: Readonly<Record<string, Readonly<Record<string, AnyEdge>>>>;
229
229
  }
230
- /** No ID-field inference and no readers: this registry owns declarations/schema helpers only. */
230
+ /** No ID-field inference and no readers: this registry owns declarations/schema helpers only.
231
+ * Registration checks table names, native table identity and edge structure. Every other
232
+ * per-table check (preflight, schema capture, indexes, field groups, edge field types and
233
+ * indexes) runs once, on the table's first use. `verifyRelations` runs all of them eagerly.
234
+ */
231
235
  export declare function defineRelations<const Tables extends RelationTables, const D extends RelationDeclarations>(tables: Tables, declare: (r: RelationBuilder<Tables>, branch: BranchBuilder<Tables>) => D & ExactDeclarations<Tables, D>): RelationRegistry<Tables, D>;
236
+ /** Runs every deferred registration check now, for example in a test that should fail CI. */
237
+ export declare function verifyRelations(registry: RelationRegistryIdentity): void;
232
238
  /** Internal owned executor bridge. Source ownership is checked once by each engine. */
233
239
  export declare function getRelationExecutor(registry: RelationRegistryIdentity): Readonly<{
234
240
  streamSchema: import("convex/server").SchemaDefinition<import("convex/server").GenericSchema, boolean>;
241
+ scopedIdentity: (tables: readonly string[], edges: readonly (readonly [source: string, name: string])[]) => string;
235
242
  groups(table: string, groups: GroupSelection): GroupSelection;
236
243
  validateDocument: (table: string, row: Record<string, import('convex/values').Value>) => void;
237
244
  assertSchema: (tables: Readonly<Record<string, TableDefinition>>) => void;
@@ -250,7 +257,7 @@ export declare function getRelationExecutor(registry: RelationRegistryIdentity):
250
257
  }>>;
251
258
  }, z.core.$strict>;
252
259
  select(table: string, selection: SelectionMask): void;
253
- project(table: string, row: Record<string, import('convex/values').Value>, eligible: () => boolean, groups?: readonly string[]): Record<string, unknown> | null;
260
+ project(table: string, row: Record<string, import('convex/values').Value>, eligible: () => boolean, groups?: readonly string[]): any;
254
261
  }>;
255
262
  /** Internal compiler/engine adapter. Registry identity alone cannot forge a registry. */
256
263
  export declare function getRelationMetadata(registry: RelationRegistryIdentity): RelationMetadata;