cvx-kit 0.1.15 → 0.1.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +67 -40
- package/dist/querying/filters.d.mts +10 -1
- package/dist/querying/filters.mjs +1 -1
- package/dist/querying/filters.mjs.map +1 -1
- package/dist/querying/planner.d.mts +1 -0
- package/dist/querying/planner.mjs +1 -1
- package/dist/querying/planner.mjs.map +1 -1
- package/dist/querying/relationships.d.mts +1 -1
- package/dist/querying/relationships.mjs +1 -1
- package/dist/querying/relationships.mjs.map +1 -1
- package/dist/querying.d.mts +9 -8
- package/dist/querying.mjs.map +1 -1
- package/dist/relations-public.d.mts +2 -2
- package/dist/relations.d.mts +74 -25
- package/dist/relations.mjs +1 -1
- package/dist/relations.mjs.map +1 -1
- package/dist/zod-table.d.mts +59 -2
- package/dist/zod-table.mjs +1 -1
- package/dist/zod-table.mjs.map +1 -1
- package/package.json +12 -3
- package/AGENTS.md +0 -47
- package/CHANGELOG.md +0 -337
- package/ROADMAP.md +0 -126
- package/docs/agent-tools.md +0 -41
- package/docs/approvals.md +0 -201
- package/docs/architecture.md +0 -124
- package/docs/auth.md +0 -443
- package/docs/command-context.md +0 -150
- package/docs/commands-legacy.md +0 -513
- package/docs/commands.md +0 -173
- package/docs/conventions.md +0 -345
- package/docs/crud.md +0 -66
- package/docs/domain-contracts.md +0 -148
- package/docs/domain-operations.md +0 -615
- package/docs/effect.md +0 -403
- package/docs/llms.md +0 -324
- package/docs/maintainability.md +0 -124
- package/docs/migration.md +0 -351
- package/docs/oxlint.md +0 -260
- package/docs/querying.md +0 -329
- package/docs/tenancy.md +0 -176
- package/docs/triggers.md +0 -77
- package/docs/upgrading.md +0 -287
- package/docs/webhooks.md +0 -58
- package/docs/zod-table.md +0 -278
- package/scripts/convex-config-bridge.mjs +0 -44
- package/scripts/convex-smoke-env.mjs +0 -33
- package/scripts/extract-changelog.mjs +0 -29
- package/scripts/owned-process.mjs +0 -140
- package/scripts/owned-process.test.mjs +0 -107
- package/scripts/smoke-packed-components.mjs +0 -341
- package/scripts/smoke-packed-effect.mjs +0 -439
- package/scripts/smoke-packed-querying.mjs +0 -298
- package/scripts/test-packed-auth.mjs +0 -72
- package/scripts/test-packed-effect.mjs +0 -482
- package/scripts/test-packed-ids.mjs +0 -150
- package/scripts/test-packed-oxlint.mjs +0 -167
- package/scripts/test-packed-querying.mjs +0 -185
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"relationships.mjs","names":["RelationshipError","code","assertRelationshipDepth","nested","selection","depth","relationshipExecutor","metadata","planner","navigation","z","base","leg","edge","declared","table","name","lookup","index","field","i","relationIndex","indexes","length","size","key","plan","condition","conditions","c","chosen","candidates","b","a","relationPrefix","prefix","get","id","request","result","targets","value","target","iterator","q","next","permitted","traverse","parent","junction","one","match","matches","ast","scalarMatches","child","output","dto","selected","args","path","parents","pageRelation","prepare","input","constraints","from","to","through","sourceTable","targetIndex","binding","rootBinding","rootId","open","codec","token","CursorError","prepared","opened","lookupPlan","indexedTarget","executeStream","schema","row","raw","nativeSchema","fields","getIndexFields","source","reference","EmptyStream","stream","db","range","continuation","rootTable","declarations","declaration","final","start","end","ancestors","found","error","rethrowQueryError"],"sources":["../../src/querying/relationships.ts"],"sourcesContent":["import type { GenericSchema, SchemaDefinition, IndexRangeBuilder } from 'convex/server'\nimport type { GenericId, Value } from 'convex/values'\nimport type { RelationEdge } from '../relations'\nimport type { createPlanner, QueryInput, StoredConstraint } from './planner'\nimport { scalarMatches } from './planner'\nimport type {\n\tFilterAst,\n\tFilterScalar,\n\tIndexCondition,\n\tNativePagination,\n\tQueryIndex,\n} from './filters'\nimport { executeStream, rethrowQueryError, type ExecutionRequest } from './execution'\nimport type { createCursorCodec, CursorBinding } from './cursors'\nimport { CursorError } from './cursors'\nimport { z } from 'zod'\nimport { stream, EmptyStream, getIndexFields } from 'convex-helpers/server/stream'\n\nexport interface OutputSelection {\n\t[name: string]: true | OutputSelection\n}\ntype Edge = RelationEdge<string, string, 'one' | 'many'>\nexport type RelationDocument = Record<string, Value> & {\n\t_id: GenericId<string>\n\t_creationTime: number\n}\ntype Document = RelationDocument\ntype Planner = ReturnType<typeof createPlanner>\n\nexport class RelationshipError extends Error {\n\tconstructor(readonly code: 'AMBIGUOUS_RELATION' | 'INVALID_RELATION') {\n\t\tsuper(code)\n\t\tthis.name = 'RelationshipError'\n\t}\n}\n\n/** The selection has already passed the registry validator; count leaf edges too. */\nexport function assertRelationshipDepth(selection: OutputSelection, depth: number): void {\n\tfor (const nested of Object.values(selection)) {\n\t\tif (depth >= 4) throw new RelationshipError('INVALID_RELATION')\n\t\tif (nested !== true) assertRelationshipDepth(nested, depth + 1)\n\t}\n}\n\n/** One request owns all traversal and authorized ID memoization. No raw reader escapes. */\nexport function relationshipExecutor(\n\tschema: SchemaDefinition<GenericSchema, boolean>,\n\trequest: ExecutionRequest,\n\tplanner: Planner,\n\tcodec: ReturnType<typeof createCursorCodec>,\n\trootBinding: CursorBinding,\n) {\n\tconst metadata = planner.metadata\n\tconst navigation = z\n\t\t.object({ cursor: z.string(), ancestors: z.array(z.string()).max(3) })\n\t\t.strict()\n\tconst base = (leg: Edge['from']) => ('base' in leg ? leg.base : leg)\n\tfunction edge(table: string, name: string): Edge {\n\t\tplanner.assertUnchanged()\n\t\tconst declared = metadata.declarations[table]?.[name]\n\t\tif (!declared) throw new RelationshipError('INVALID_RELATION')\n\t\treturn declared\n\t}\n\tfunction lookup(table: string, field: string) {\n\t\tconst index =\n\t\t\tfield === '_id'\n\t\t\t\t? { name: 'by_id', fields: ['_id'] }\n\t\t\t\t: metadata.tables[table].indexes.find((i) => i.fields[0] === field)\n\t\tif (!index) throw new RelationshipError('INVALID_RELATION')\n\t\treturn index\n\t}\n\tfunction relationIndex(\n\t\ttable: string,\n\t\tfield: string,\n\t\tplan: ReturnType<Planner['plan']>,\n\t\tconditions: readonly IndexCondition[],\n\t): QueryIndex {\n\t\tconst indexes =\n\t\t\tfield === '_id' ? [{ name: 'by_id', fields: ['_id'] }] : metadata.tables[table].indexes\n\t\tconst length = (index: QueryIndex) => {\n\t\t\tlet size = 1\n\t\t\tfor (const key of index.fields.slice(1)) {\n\t\t\t\tif (!plan.bindings.has(key)) break\n\t\t\t\tsize++\n\t\t\t}\n\t\t\treturn size\n\t\t}\n\t\tconst condition = conditions.find((c) => c.value !== null && c.value !== undefined)\n\t\tif (condition) {\n\t\t\tconst chosen = indexes.find((i) => i.name === condition.index && i.fields[0] === field)\n\t\t\tif (!chosen)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Explicit index \"${condition.index}\" is incompatible with declared relationship lookup`,\n\t\t\t\t)\n\t\t\treturn chosen\n\t\t}\n\t\tconst candidates = indexes\n\t\t\t.filter((i) => i.fields[0] === field)\n\t\t\t.sort(\n\t\t\t\t(a, b) =>\n\t\t\t\t\tlength(b) - length(a) ||\n\t\t\t\t\ta.name.localeCompare(b.name) ||\n\t\t\t\t\ta.fields.join('\\0').localeCompare(b.fields.join('\\0')),\n\t\t\t)\n\t\tif (!candidates.length) throw new RelationshipError('INVALID_RELATION')\n\t\treturn candidates[0]\n\t}\n\tfunction relationPrefix(\n\t\tindex: QueryIndex,\n\t\tvalue: FilterScalar,\n\t\tplan: ReturnType<Planner['plan']>,\n\t) {\n\t\tconst prefix = [{ field: index.fields[0], value }]\n\t\tfor (const field of index.fields.slice(1)) {\n\t\t\tif (!plan.bindings.has(field)) break\n\t\t\tprefix.push({ field, value: plan.bindings.get(field)! })\n\t\t}\n\t\treturn prefix\n\t}\n\n\tasync function get(table: string, id: Value | undefined): Promise<Document | null> {\n\t\tplanner.beforeLeaf(table)\n\t\t// SAFETY: native normalization rejects non-string/non-table IDs before any read.\n\t\tif (id == null || !request.db.normalizeId(table, id as string)) return null\n\t\t// SAFETY: normalizeId verifies the declared native table before the authorized metered get.\n\t\tconst result = await request.db.get(table, id as GenericId<string>)\n\t\tplanner.assertUnchanged()\n\t\t// SAFETY: normalizeId checked the table; the authorized native get retains system fields.\n\t\treturn result as Document | null\n\t}\n\tasync function* targets(\n\t\ttable: string,\n\t\tfield: string,\n\t\tvalue: Value | undefined,\n\t\tdepth: number,\n\t): AsyncGenerator<Document> {\n\t\trequest.expand(depth, 0)\n\t\tif (value == null) return\n\t\tif (field === '_id') {\n\t\t\tconst target = await get(table, value)\n\t\t\tif (target) {\n\t\t\t\trequest.expand(depth)\n\t\t\t\tyield target\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tplanner.beforeLeaf(table)\n\t\tconst index = lookup(table, field)\n\t\t// SAFETY: registry validates the indexed native lookup prefix and compatible values.\n\t\tconst source = request.leafQuery(table).withIndex(index.name, (q) => q.eq(field, value))\n\t\tconst iterator = source[Symbol.asyncIterator]()\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tplanner.assertUnchanged()\n\t\t\t\tplanner.beforeLeaf(table)\n\t\t\t\tconst next = await iterator.next()\n\t\t\t\tplanner.assertUnchanged()\n\t\t\t\tif (next.done) return\n\t\t\t\tconst permitted = await request.authorize(table, next.value)\n\t\t\t\t// Denials are an await boundary too; never hide them inside an authorized iterator.\n\t\t\t\tplanner.assertUnchanged()\n\t\t\t\tif (!permitted) continue\n\t\t\t\trequest.expand(depth)\n\t\t\t\t// SAFETY: native rows include system fields and explicit authorization just completed.\n\t\t\t\tyield next.value as Document\n\t\t\t}\n\t\t} finally {\n\t\t\tawait iterator.return?.()\n\t\t}\n\t}\n\tasync function* traverse(\n\t\tdeclared: Edge,\n\t\tparent: Document,\n\t\tdepth: number,\n\t): AsyncGenerator<Document> {\n\t\trequest.expand(depth, 0)\n\t\tconst value = parent[base(declared.from).field]\n\t\tif (value == null) return\n\t\tif ('base' in declared.from && 'base' in declared.to) {\n\t\t\tfor await (const junction of targets(\n\t\t\t\tdeclared.from.junction.table,\n\t\t\t\tdeclared.from.junction.field,\n\t\t\t\tvalue,\n\t\t\t\tdepth,\n\t\t\t))\n\t\t\t\tyield* targets(\n\t\t\t\t\tdeclared.target,\n\t\t\t\t\tdeclared.to.base.field,\n\t\t\t\t\tjunction[declared.to.junction.field],\n\t\t\t\t\tdepth,\n\t\t\t\t)\n\t\t} else yield* targets(declared.target, base(declared.to).field, value, depth)\n\t}\n\tasync function one(declared: Edge, parent: Document, depth: number) {\n\t\tlet match: Document | null = null\n\t\tfor await (const target of traverse(declared, parent, depth)) {\n\t\t\tif (match) throw new RelationshipError('AMBIGUOUS_RELATION')\n\t\t\tmatch = target\n\t\t}\n\t\treturn match\n\t}\n\tasync function matches(\n\t\ttable: string,\n\t\tparent: Document,\n\t\tast: FilterAst,\n\t\tdepth = 0,\n\t): Promise<boolean> {\n\t\trequest.expand(depth, 0)\n\t\tplanner.assertUnchanged()\n\t\tif (ast.kind === 'scalar') return scalarMatches(ast, parent)\n\t\tif (ast.kind === 'not') return !(await matches(table, parent, ast.child, depth))\n\t\tif (ast.kind === 'and' || ast.kind === 'or') {\n\t\t\tfor (const child of ast.children) {\n\t\t\t\tconst result = await matches(table, parent, child, depth)\n\t\t\t\tif (ast.kind === 'and' && !result) return false\n\t\t\t\tif (ast.kind === 'or' && result) return true\n\t\t\t}\n\t\t\treturn ast.kind === 'and'\n\t\t}\n\t\tif (ast.kind !== 'relation') throw new RelationshipError('INVALID_RELATION')\n\t\tconst declared = edge(table, ast.name)\n\t\tif (ast.mode === 'one') {\n\t\t\tconst target = await one(declared, parent, depth + 1)\n\t\t\treturn ast.predicate === null\n\t\t\t\t? target === null\n\t\t\t\t: target !== null && (await matches(declared.target, target, ast.predicate, depth + 1))\n\t\t}\n\t\tfor await (const target of traverse(declared, parent, depth + 1))\n\t\t\tif (await matches(declared.target, target, ast.predicate!, depth + 1))\n\t\t\t\treturn ast.mode === 'some'\n\t\t// Only actual authorized traversal exhaustion proves none.\n\t\treturn ast.mode === 'none'\n\t}\n\tasync function output(\n\t\ttable: string,\n\t\tparent: Document,\n\t\tselection: OutputSelection,\n\t\targs: NativePagination & { order?: 'asc' | 'desc' },\n\t\tpath: readonly string[] = [],\n\t\tdepth = 0,\n\t\tparents: readonly string[] = [],\n\t): Promise<Record<string, Value>> {\n\t\trequest.expand(depth, 0)\n\t\t// SAFETY: the registry strictly validates this public native DTO projection.\n\t\tconst dto = planner.complete(table, parent, true, { kind: 'and', children: [] }) as Record<\n\t\t\tstring,\n\t\t\tValue\n\t\t>\n\t\tfor (const [name, selected] of Object.entries(selection)) {\n\t\t\tconst declared = edge(table, name),\n\t\t\t\tnested = selected === true ? {} : selected\n\t\t\tif (declared.cardinality === 'one') {\n\t\t\t\tconst target = await one(declared, parent, depth + 1)\n\t\t\t\tdto[name] = target\n\t\t\t\t\t? await output(declared.target, target, nested, args, [...path, name], depth + 1, [\n\t\t\t\t\t\t\t...parents,\n\t\t\t\t\t\t\tparent._id,\n\t\t\t\t\t\t])\n\t\t\t\t\t: null\n\t\t\t} else {\n\t\t\t\tconst page = await pageRelation(\n\t\t\t\t\ttable,\n\t\t\t\t\tparent,\n\t\t\t\t\tname,\n\t\t\t\t\tnested,\n\t\t\t\t\t{ numItems: args.numItems, cursor: null, order: args.order },\n\t\t\t\t\t[],\n\t\t\t\t\t[],\n\t\t\t\t\t[...path, name],\n\t\t\t\t\tdepth + 1,\n\t\t\t\t\t[...parents, parent._id],\n\t\t\t\t)\n\t\t\t\t// SAFETY: the declared page validator has parsed this nested DTO page.\n\t\t\t\tdto[name] = page as Value\n\t\t\t}\n\t\t}\n\t\treturn dto\n\t}\n\tfunction prepare(\n\t\ttable: string,\n\t\tname: string,\n\t\tselection: OutputSelection,\n\t\tinput: QueryInput,\n\t\tconditions: readonly IndexCondition[],\n\t\tconstraints: readonly StoredConstraint[],\n\t\tpath: readonly string[],\n\t\trootId: string,\n\t) {\n\t\tplanner.page(edge(table, name).target, selection)\n\t\tassertRelationshipDepth(selection, path.length)\n\t\tconst declared = edge(table, name)\n\t\tif (declared.cardinality !== 'many') throw new RelationshipError('INVALID_RELATION')\n\t\tconst plan = planner.plan(declared.target, input, [], constraints)\n\t\tconst from = declared.from,\n\t\t\tto = declared.to\n\t\tconst through =\n\t\t\t'base' in from && 'base' in to\n\t\t\t\t? {\n\t\t\t\t\t\ttable: from.junction.table,\n\t\t\t\t\t\tfield: from.junction.field,\n\t\t\t\t\t\ttargetField: to.base.field,\n\t\t\t\t\t\ttargetReference: to.junction.field,\n\t\t\t\t\t}\n\t\t\t\t: null\n\t\tconst sourceTable = through ? through.table : declared.target\n\t\tconst field = through ? through.field : base(to).field\n\t\tconst targetIndex = relationIndex(\n\t\t\tdeclared.target,\n\t\t\tthrough ? through.targetField : field,\n\t\t\tplan,\n\t\t\tconditions,\n\t\t)\n\t\tconst index = through ? lookup(sourceTable, field) : targetIndex\n\t\t// SAFETY: planner.page validated the complete output mask before cursor binding.\n\t\tconst binding: CursorBinding = {\n\t\t\t...rootBinding,\n\t\t\ttable: sourceTable,\n\t\t\tindex: index.name,\n\t\t\torder: plan.args.order ?? 'asc',\n\t\t\tclientFilters: plan.clientIdentity,\n\t\t\tserverFilters: {\n\t\t\t\tpredicates: plan.serverIdentity,\n\t\t\t\tselection: selection as Value,\n\t\t\t\tscope: { ...request.scope },\n\t\t\t\trootTable: rootBinding.table,\n\t\t\t\tlookupIndex: targetIndex.name,\n\t\t\t},\n\t\t\trelationPath: path,\n\t\t\tparent: rootId,\n\t\t}\n\t\tfunction open(token: string) {\n\t\t\ttry {\n\t\t\t\treturn navigation.parse(JSON.parse(codec.open(token, binding)))\n\t\t\t} catch {\n\t\t\t\tthrow new CursorError()\n\t\t\t}\n\t\t}\n\t\treturn { declared, plan, through, sourceTable, field, index, targetIndex, binding, open }\n\t}\n\tasync function pageRelation(\n\t\ttable: string,\n\t\tparent: Document | null,\n\t\tname: string,\n\t\tselection: OutputSelection,\n\t\tinput: QueryInput,\n\t\tconditions: readonly IndexCondition[] = [],\n\t\tconstraints: readonly StoredConstraint[] = [],\n\t\tpath: readonly string[] = [name],\n\t\tdepth = 1,\n\t\tparents: readonly string[] = [],\n\t\tprepared = prepare(\n\t\t\ttable,\n\t\t\tname,\n\t\t\tselection,\n\t\t\tinput,\n\t\t\tconditions,\n\t\t\tconstraints,\n\t\t\tpath,\n\t\t\tparents[0] ?? parent!._id,\n\t\t),\n\t\topened?: { cursor: string | null; endCursor?: string | null },\n\t) {\n\t\trequest.expand(depth, 0)\n\t\tconst { declared, plan, through, sourceTable, field, index, targetIndex, binding } = prepared\n\t\tconst value = parent?.[base(declared.from).field]\n\t\tconst args = { ...plan.args, ...(opened ?? { cursor: null }) }\n\t\t// SAFETY: declarations accept only native scalar lookup values; nullish references are absence.\n\t\tconst lookupPlan = {\n\t\t\t...plan,\n\t\t\tindex,\n\t\t\tprefix:\n\t\t\t\tvalue == null\n\t\t\t\t\t? []\n\t\t\t\t\t: through\n\t\t\t\t\t\t? [{ field, value: value as FilterScalar }]\n\t\t\t\t\t\t: relationPrefix(index, value as FilterScalar, plan),\n\t\t\tunsatisfiable: value == null || plan.unsatisfiable,\n\t\t}\n\t\tconst indexedTarget = through && through.targetField !== '_id'\n\t\tconst result = await executeStream(\n\t\t\tschema,\n\t\t\trequest,\n\t\t\tsourceTable,\n\t\t\tlookupPlan,\n\t\t\tplanner,\n\t\t\tcodec,\n\t\t\tbinding,\n\t\t\targs,\n\t\t\tasync (row, permitted) => {\n\t\t\t\tif (!permitted) return null\n\t\t\t\trequest.expand(depth)\n\t\t\t\tlet target: Document | null\n\t\t\t\tif (through && !indexedTarget)\n\t\t\t\t\ttarget = await get(declared.target, row[through.targetReference])\n\t\t\t\telse {\n\t\t\t\t\t// SAFETY: native direct/flattened target streams retain validated system fields.\n\t\t\t\t\ttarget = row as Document\n\t\t\t\t}\n\t\t\t\tif (!target || !(await matches(declared.target, target, plan.residual, depth))) return null\n\t\t\t\treturn output(declared.target, target, selection, plan.args, path, depth, parents)\n\t\t\t},\n\t\t\t(raw) => codec.seal(JSON.stringify({ cursor: raw, ancestors: parents.slice(1) }), binding),\n\t\t\tindexedTarget\n\t\t\t\t? (source, db) => {\n\t\t\t\t\t\t// SAFETY: the registry owns the native schema/index descriptors. Public\n\t\t\t\t\t\t// helper flatMap concatenates native outer/inner keys and paginates them.\n\t\t\t\t\t\tconst nativeSchema = schema as SchemaDefinition<\n\t\t\t\t\t\t\tRecord<\n\t\t\t\t\t\t\t\tstring,\n\t\t\t\t\t\t\t\timport('convex/server').TableDefinition<any, Record<string, string[]>>\n\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\tboolean\n\t\t\t\t\t\t>\n\t\t\t\t\t\tconst fields = getIndexFields(declared.target, targetIndex.name, nativeSchema)\n\t\t\t\t\t\treturn source.flatMap(async (junction) => {\n\t\t\t\t\t\t\trequest.expand(depth)\n\t\t\t\t\t\t\tconst permitted = await request.authorize(sourceTable, junction)\n\t\t\t\t\t\t\tplanner.assertUnchanged()\n\t\t\t\t\t\t\tconst reference = junction[through.targetReference]\n\t\t\t\t\t\t\tif (!permitted || reference == null)\n\t\t\t\t\t\t\t\treturn new EmptyStream(plan.args.order ?? 'asc', fields)\n\t\t\t\t\t\t\treturn stream(db, nativeSchema)\n\t\t\t\t\t\t\t\t.query(declared.target)\n\t\t\t\t\t\t\t\t.withIndex(targetIndex.name, (q) => {\n\t\t\t\t\t\t\t\t\t// SAFETY: registry validates the native leading lookup; validated filters supply each consecutive trailing binding.\n\t\t\t\t\t\t\t\t\tlet range = q as IndexRangeBuilder<any, string[], number>\n\t\t\t\t\t\t\t\t\t// SAFETY: junction references are native scalar Values validated by the declared lookup.\n\t\t\t\t\t\t\t\t\tconst prefix = relationPrefix(targetIndex, reference as FilterScalar, plan)\n\t\t\t\t\t\t\t\t\tfor (const binding of prefix) {\n\t\t\t\t\t\t\t\t\t\t// SAFETY: native eq advances the validated consecutive index prefix.\n\t\t\t\t\t\t\t\t\t\trange = range.eq(binding.field, binding.value) as IndexRangeBuilder<\n\t\t\t\t\t\t\t\t\t\t\tany,\n\t\t\t\t\t\t\t\t\t\t\tstring[],\n\t\t\t\t\t\t\t\t\t\t\tnumber\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\t\t\t\treturn range\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.order(plan.args.order ?? 'asc')\n\t\t\t\t\t\t}, fields)\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t\tindexedTarget ? declared.target : sourceTable,\n\t\t)\n\t\tplanner.assertUnchanged()\n\t\treturn planner.page(declared.target, selection).parse(result)\n\t}\n\tasync function continuation(\n\t\trootTable: string,\n\t\trootId: string,\n\t\tpath: readonly string[],\n\t\tselection: OutputSelection,\n\t\tinput: QueryInput,\n\t\tconditions: readonly IndexCondition[],\n\t\tconstraints: readonly StoredConstraint[],\n\t) {\n\t\tif (!path.length || path.length > 4 || !request.db.normalizeId(rootTable, rootId))\n\t\t\tthrow new RelationshipError('INVALID_RELATION')\n\t\tlet table = rootTable\n\t\tconst declarations = path.map((name) => {\n\t\t\tconst declaration = edge(table, name)\n\t\t\ttable = declaration.target\n\t\t\treturn declaration\n\t\t})\n\t\tconst final = declarations.at(-1)!\n\t\tconst prepared = prepare(\n\t\t\tfinal.source,\n\t\t\tpath.at(-1)!,\n\t\t\tselection,\n\t\t\tinput,\n\t\t\tconditions,\n\t\t\tconstraints,\n\t\t\tpath,\n\t\t\trootId,\n\t\t)\n\t\t// Authenticate both slots and native ancestor IDs before ANY parent/traversal read.\n\t\tconst start = input.cursor === null ? null : prepared.open(input.cursor)\n\t\tconst end = input.endCursor == null ? null : prepared.open(input.endCursor)\n\t\tconst ancestors = start?.ancestors ?? end?.ancestors ?? []\n\t\tif (\n\t\t\tancestors.length !== path.length - 1 ||\n\t\t\t(start && end && JSON.stringify(start.ancestors) !== JSON.stringify(end.ancestors)) ||\n\t\t\tancestors.some((id, i) => !request.db.normalizeId(declarations[i].target, id))\n\t\t)\n\t\t\tthrow new CursorError()\n\t\t// Declarative input/index/cursor validation above retains its pre-read errors,\n\t\t// just as on the root path. Every awaited read, ancestry proof and page is protected.\n\t\ttry {\n\t\t\tlet parent = await get(rootTable, rootId)\n\t\t\tfor (let i = 0; parent && i < ancestors.length; i++) {\n\t\t\t\tconst declared = declarations[i]\n\t\t\t\tlet found: Document | null = null\n\t\t\t\tif (declared.cardinality === 'one') {\n\t\t\t\t\tconst target = await one(declared, parent, i + 1)\n\t\t\t\t\tif (target?._id === ancestors[i]) found = target\n\t\t\t\t} else\n\t\t\t\t\tfor await (const target of traverse(declared, parent, i + 1)) {\n\t\t\t\t\t\tif (target._id === ancestors[i]) {\n\t\t\t\t\t\t\tfound = target\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tparent = found\n\t\t\t}\n\t\t\treturn await pageRelation(\n\t\t\t\tfinal.source,\n\t\t\t\tparent,\n\t\t\t\tpath.at(-1)!,\n\t\t\t\tselection,\n\t\t\t\tinput,\n\t\t\t\tconditions,\n\t\t\t\tconstraints,\n\t\t\t\tpath,\n\t\t\t\tpath.length,\n\t\t\t\t[rootId, ...ancestors],\n\t\t\t\tprepared,\n\t\t\t\t{ cursor: start?.cursor ?? null, endCursor: end?.cursor ?? input.endCursor },\n\t\t\t)\n\t\t} catch (error) {\n\t\t\trethrowQueryError(error)\n\t\t}\n\t}\n\treturn { matches, output, continuation, edge }\n}\n"],"mappings":"oRA6BA,IAAaA,EAAb,cAAuC,KAAM,CACvB,KAArB,YAAY,EAA0D,CACrE,MAAMC,CAAI,EADU,KAAA,KAAAA,EAEpB,KAAK,KAAO,mBACb,CACD,EAGA,SAAgBC,EAAwB,EAA4B,EAAqB,CACxF,IAAK,IAAMC,KAAU,OAAO,OAAOC,CAAS,EAAG,CAC9C,GAAIC,GAAS,EAAG,MAAM,IAAIL,EAAkB,kBAAkB,EAC1DG,IAAW,IAAMD,EAAwBC,EAAQE,EAAQ,CAAC,CAC/D,CACD,CAGA,SAAgBC,EACf,EACA,EACA,EACA,EACA,EACC,CACD,IAAMC,EAAWC,EAAQ,SACnBC,EAAaC,EACjB,OAAO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G,YAAY2D,EAAa7E,EAAE,CAAC,OAAQiB,CAAE,CAAC,EAE7E,MAAM,IAAIwC,EAGX,GAAI,CACH,IAAI7B,EAAS,MAAMZ,EAAI4D,EAAWvB,CAAM,EACxC,IAAK,IAAIrD,EAAI,EAAG4B,GAAU5B,EAAIkF,EAAU,OAAQ,IAAK,CACpD,IAAMxF,EAAWmF,EAAa7E,GAC1BmF,EAAyB,KAC7B,GAAIzF,EAAS,cAAgB,MAAO,CACnC,IAAM4B,EAAS,MAAMQ,EAAIpC,EAAUkC,EAAQ5B,EAAI,CAAC,EAC5CsB,GAAQ,MAAQ4D,EAAUlF,KAAI,EAAQsB,EAC3C,MACC,UAAW,IAAMA,KAAUK,EAASjC,EAAUkC,EAAQ5B,EAAI,CAAC,EAC1D,GAAIsB,EAAO,MAAQ4D,EAAUlF,GAAI,CAChC,EAAQsB,EACR,KACD,CAEF,EAAS6D,CACV,CACA,OAAO,MAAMzC,EACZqC,EAAM,OACNnD,EACAY,EAAK,GAAG,EAAE,EACVxD,EACA4D,EACApC,EACAqC,EACAL,EACAA,EAAK,OACL,CAACa,EAAQ,GAAG6B,CAAS,EACrBxB,EACA,CAAE,OAAQsB,GAAO,QAAU,KAAM,UAAWC,GAAK,QAAUrC,EAAM,SAAU,CAC5E,CACD,OAASwC,EAAO,CACfC,EAAkBD,CAAK,CACxB,CACD,CACA,MAAO,CAAE,UAAS,SAAQ,eAAc,MAAK,CAC9C"}
|
|
1
|
+
{"version":3,"file":"relationships.mjs","names":["RelationshipError","code","assertRelationshipDepth","nested","selection","depth","relationshipExecutor","metadata","planner","navigation","z","base","leg","edge","declared","table","name","guarded","guard","row","lookup","index","field","position","i","key","relationIndex","indexes","bound","plan","usable","length","size","condition","conditions","c","chosen","candidates","b","a","relationPrefix","prefix","get","id","request","result","targets","value","target","iterator","range","q","binding","next","permitted","traverse","parent","junction","one","match","matches","ast","scalarMatches","child","output","dto","selected","args","path","parents","pageRelation","prepare","guardConstraint","input","constraints","from","to","through","sourceTable","targetIndex","rootBinding","rootId","open","codec","token","CursorError","prepared","opened","lookupPlan","indexedTarget","executeStream","schema","raw","nativeSchema","fields","getIndexFields","source","reference","EmptyStream","stream","db","continuation","rootTable","declarations","declaration","final","start","end","ancestors","found","error","rethrowQueryError"],"sources":["../../src/querying/relationships.ts"],"sourcesContent":["import type { GenericSchema, SchemaDefinition, IndexRangeBuilder } from 'convex/server'\nimport type { GenericId, Value } from 'convex/values'\nimport type { RelationEdge, RelationGuard } from '../relations'\nimport type { createPlanner, QueryInput, StoredConstraint } from './planner'\nimport { scalarMatches } from './planner'\nimport type {\n\tFilterAst,\n\tFilterScalar,\n\tIndexCondition,\n\tNativePagination,\n\tQueryIndex,\n} from './filters'\nimport { executeStream, rethrowQueryError, type ExecutionRequest } from './execution'\nimport type { createCursorCodec, CursorBinding } from './cursors'\nimport { CursorError } from './cursors'\nimport { z } from 'zod'\nimport { stream, EmptyStream, getIndexFields } from 'convex-helpers/server/stream'\n\nexport interface OutputSelection {\n\t[name: string]: true | OutputSelection\n}\ntype Edge = RelationEdge<string, string, 'one' | 'many', any, any>\nexport type RelationDocument = Record<string, Value> & {\n\t_id: GenericId<string>\n\t_creationTime: number\n}\ntype Document = RelationDocument\ntype Planner = ReturnType<typeof createPlanner>\n\nexport class RelationshipError extends Error {\n\tconstructor(readonly code: 'AMBIGUOUS_RELATION' | 'INVALID_RELATION') {\n\t\tsuper(code)\n\t\tthis.name = 'RelationshipError'\n\t}\n}\n\n/** The selection has already passed the registry validator; count leaf edges too. */\nexport function assertRelationshipDepth(selection: OutputSelection, depth: number): void {\n\tfor (const nested of Object.values(selection)) {\n\t\tif (depth >= 4) throw new RelationshipError('INVALID_RELATION')\n\t\tif (nested !== true) assertRelationshipDepth(nested, depth + 1)\n\t}\n}\n\n/** One request owns all traversal and authorized ID memoization. No raw reader escapes. */\nexport function relationshipExecutor(\n\tschema: SchemaDefinition<GenericSchema, boolean>,\n\trequest: ExecutionRequest,\n\tplanner: Planner,\n\tcodec: ReturnType<typeof createCursorCodec>,\n\trootBinding: CursorBinding,\n) {\n\tconst metadata = planner.metadata\n\tconst navigation = z\n\t\t.object({ cursor: z.string(), ancestors: z.array(z.string()).max(3) })\n\t\t.strict()\n\tconst base = (leg: Edge['from']) => ('base' in leg ? leg.base : leg)\n\tfunction edge(table: string, name: string): Edge {\n\t\tplanner.assertUnchanged()\n\t\tconst declared = metadata.declarations[table]?.[name]\n\t\tif (!declared) throw new RelationshipError('INVALID_RELATION')\n\t\treturn declared\n\t}\n\tconst guarded = (row: Document | Record<string, Value>, guard?: RelationGuard) =>\n\t\t!guard || row[guard.discriminator] === guard.tag\n\tfunction lookup(table: string, field: string, guard?: RelationGuard) {\n\t\tconst index =\n\t\t\tfield === '_id'\n\t\t\t\t? { name: 'by_id', fields: ['_id'] }\n\t\t\t\t: metadata.tables[table].indexes.find((i) => {\n\t\t\t\t\t\tconst position = i.fields.indexOf(field)\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tposition >= 0 &&\n\t\t\t\t\t\t\ti.fields.slice(0, position).every((key) => key === guard?.discriminator)\n\t\t\t\t\t\t)\n\t\t\t\t\t})\n\t\tif (!index) throw new RelationshipError('INVALID_RELATION')\n\t\treturn index\n\t}\n\tfunction relationIndex(\n\t\ttable: string,\n\t\tfield: string,\n\t\tplan: ReturnType<Planner['plan']>,\n\t\tconditions: readonly IndexCondition[],\n\t\tguard?: RelationGuard,\n\t): QueryIndex {\n\t\tconst indexes =\n\t\t\tfield === '_id' ? [{ name: 'by_id', fields: ['_id'] }] : metadata.tables[table].indexes\n\t\tconst bound = (key: string) =>\n\t\t\tkey === field || key === guard?.discriminator || plan.bindings.has(key)\n\t\tconst usable = (index: QueryIndex) =>\n\t\t\tindex.fields.includes(field) &&\n\t\t\tindex.fields.slice(0, index.fields.indexOf(field)).every(bound)\n\t\tconst length = (index: QueryIndex) => {\n\t\t\tlet size = 0\n\t\t\tfor (const key of index.fields) {\n\t\t\t\tif (!bound(key)) break\n\t\t\t\tsize++\n\t\t\t}\n\t\t\treturn size\n\t\t}\n\t\tconst condition = conditions.find((c) => c.value !== null && c.value !== undefined)\n\t\tif (condition) {\n\t\t\tconst chosen = indexes.find((i) => i.name === condition.index && usable(i))\n\t\t\tif (!chosen)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Explicit index \"${condition.index}\" is incompatible with declared relationship lookup`,\n\t\t\t\t)\n\t\t\treturn chosen\n\t\t}\n\t\tconst candidates = indexes\n\t\t\t.filter(usable)\n\t\t\t.sort(\n\t\t\t\t(a, b) =>\n\t\t\t\t\tlength(b) - length(a) ||\n\t\t\t\t\ta.name.localeCompare(b.name) ||\n\t\t\t\t\ta.fields.join('\\0').localeCompare(b.fields.join('\\0')),\n\t\t\t)\n\t\tif (!candidates.length) throw new RelationshipError('INVALID_RELATION')\n\t\treturn candidates[0]\n\t}\n\tfunction relationPrefix(\n\t\tindex: QueryIndex,\n\t\tfield: string,\n\t\tvalue: FilterScalar,\n\t\tplan?: ReturnType<Planner['plan']>,\n\t\tguard?: RelationGuard,\n\t) {\n\t\tconst prefix: { field: string; value: FilterScalar }[] = []\n\t\tfor (const key of index.fields) {\n\t\t\tif (key === field) prefix.push({ field: key, value })\n\t\t\telse if (key === guard?.discriminator) prefix.push({ field: key, value: guard.tag })\n\t\t\telse if (plan?.bindings.has(key)) prefix.push({ field: key, value: plan.bindings.get(key)! })\n\t\t\telse break\n\t\t}\n\t\treturn prefix\n\t}\n\n\tasync function get(table: string, id: Value | undefined): Promise<Document | null> {\n\t\tplanner.beforeLeaf(table)\n\t\t// SAFETY: native normalization rejects non-string/non-table IDs before any read.\n\t\tif (id == null || !request.db.normalizeId(table, id as string)) return null\n\t\t// SAFETY: normalizeId verifies the declared native table before the authorized metered get.\n\t\tconst result = await request.db.get(table, id as GenericId<string>)\n\t\tplanner.assertUnchanged()\n\t\tif (result) planner.validateDocument(table, result)\n\t\t// SAFETY: normalizeId checked the table; the authorized native get retains system fields.\n\t\treturn result as Document | null\n\t}\n\tasync function* targets(\n\t\ttable: string,\n\t\tfield: string,\n\t\tvalue: Value | undefined,\n\t\tdepth: number,\n\t\tguard?: RelationGuard,\n\t): AsyncGenerator<Document> {\n\t\trequest.expand(depth, 0)\n\t\tif (value == null) return\n\t\tif (field === '_id') {\n\t\t\tconst target = await get(table, value)\n\t\t\tif (target && guarded(target, guard)) {\n\t\t\t\trequest.expand(depth)\n\t\t\t\tyield target\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tplanner.beforeLeaf(table)\n\t\tconst index = lookup(table, field, guard)\n\t\t// SAFETY: registry validates the indexed native lookup prefix and compatible values.\n\t\tconst source = request.leafQuery(table).withIndex(index.name, (q) => {\n\t\t\t// SAFETY: registration checks the mandatory join and every preceding guard equality.\n\t\t\tlet range = q as IndexRangeBuilder<any, string[], number>\n\t\t\t// SAFETY: registered relation fields are native scalars; each equality advances the consecutive checked prefix.\n\t\t\tfor (const binding of relationPrefix(index, field, value as FilterScalar, undefined, guard)) {\n\t\t\t\t// SAFETY: the prefix comes from the declared index and registry-owned guard.\n\t\t\t\trange = range.eq(binding.field, binding.value) as IndexRangeBuilder<any, string[], number>\n\t\t\t}\n\t\t\treturn range\n\t\t})\n\t\tconst iterator = source[Symbol.asyncIterator]()\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tplanner.assertUnchanged()\n\t\t\t\tplanner.beforeLeaf(table)\n\t\t\t\tconst next = await iterator.next()\n\t\t\t\tplanner.assertUnchanged()\n\t\t\t\tif (next.done) return\n\t\t\t\tconst permitted = await request.authorize(table, next.value)\n\t\t\t\t// Denials are an await boundary too; never hide them inside an authorized iterator.\n\t\t\t\tplanner.assertUnchanged()\n\t\t\t\tif (!permitted) continue\n\t\t\t\tplanner.validateDocument(table, next.value)\n\t\t\t\tif (!guarded(next.value, guard)) continue\n\t\t\t\trequest.expand(depth)\n\t\t\t\t// SAFETY: native rows include system fields and explicit authorization just completed.\n\t\t\t\tyield next.value as Document\n\t\t\t}\n\t\t} finally {\n\t\t\tawait iterator.return?.()\n\t\t}\n\t}\n\tasync function* traverse(\n\t\tdeclared: Edge,\n\t\tparent: Document,\n\t\tdepth: number,\n\t): AsyncGenerator<Document> {\n\t\trequest.expand(depth, 0)\n\t\tif (!guarded(parent, declared.sourceGuard)) return\n\t\tconst value = parent[base(declared.from).field]\n\t\tif (value == null) return\n\t\tif ('base' in declared.from && 'base' in declared.to) {\n\t\t\tfor await (const junction of targets(\n\t\t\t\tdeclared.from.junction.table,\n\t\t\t\tdeclared.from.junction.field,\n\t\t\t\tvalue,\n\t\t\t\tdepth,\n\t\t\t\tdeclared.junctionGuard,\n\t\t\t))\n\t\t\t\tyield* targets(\n\t\t\t\t\tdeclared.target,\n\t\t\t\t\tdeclared.to.base.field,\n\t\t\t\t\tjunction[declared.to.junction.field],\n\t\t\t\t\tdepth,\n\t\t\t\t\tdeclared.targetGuard,\n\t\t\t\t)\n\t\t} else\n\t\t\tyield* targets(declared.target, base(declared.to).field, value, depth, declared.targetGuard)\n\t}\n\tasync function one(declared: Edge, parent: Document, depth: number) {\n\t\tlet match: Document | null = null\n\t\tfor await (const target of traverse(declared, parent, depth)) {\n\t\t\tif (match) throw new RelationshipError('AMBIGUOUS_RELATION')\n\t\t\tmatch = target\n\t\t}\n\t\treturn match\n\t}\n\tasync function matches(\n\t\ttable: string,\n\t\tparent: Document,\n\t\tast: FilterAst,\n\t\tdepth = 0,\n\t): Promise<boolean> {\n\t\trequest.expand(depth, 0)\n\t\tplanner.assertUnchanged()\n\t\tplanner.validateDocument(table, parent)\n\t\tif (ast.kind === 'variant')\n\t\t\treturn parent[ast.discriminator] === ast.tag && matches(table, parent, ast.child, depth)\n\t\tif (ast.kind === 'scalar') return scalarMatches(ast, parent)\n\t\tif (ast.kind === 'not') return !(await matches(table, parent, ast.child, depth))\n\t\tif (ast.kind === 'and' || ast.kind === 'or') {\n\t\t\tfor (const child of ast.children) {\n\t\t\t\tconst result = await matches(table, parent, child, depth)\n\t\t\t\tif (ast.kind === 'and' && !result) return false\n\t\t\t\tif (ast.kind === 'or' && result) return true\n\t\t\t}\n\t\t\treturn ast.kind === 'and'\n\t\t}\n\t\tif (ast.kind !== 'relation') throw new RelationshipError('INVALID_RELATION')\n\t\tconst declared = edge(table, ast.name)\n\t\tif (ast.mode === 'one') {\n\t\t\tconst target = await one(declared, parent, depth + 1)\n\t\t\treturn ast.predicate === null\n\t\t\t\t? target === null\n\t\t\t\t: target !== null && (await matches(declared.target, target, ast.predicate, depth + 1))\n\t\t}\n\t\tfor await (const target of traverse(declared, parent, depth + 1))\n\t\t\tif (await matches(declared.target, target, ast.predicate!, depth + 1))\n\t\t\t\treturn ast.mode === 'some'\n\t\t// Only actual authorized traversal exhaustion proves none.\n\t\treturn ast.mode === 'none'\n\t}\n\tasync function output(\n\t\ttable: string,\n\t\tparent: Document,\n\t\tselection: OutputSelection,\n\t\targs: NativePagination & { order?: 'asc' | 'desc' },\n\t\tpath: readonly string[] = [],\n\t\tdepth = 0,\n\t\tparents: readonly string[] = [],\n\t): Promise<Record<string, Value>> {\n\t\trequest.expand(depth, 0)\n\t\t// SAFETY: the registry strictly validates this public native DTO projection.\n\t\tconst dto = planner.complete(table, parent, true, { kind: 'and', children: [] }) as Record<\n\t\t\tstring,\n\t\t\tValue\n\t\t>\n\t\tfor (const [name, selected] of Object.entries(selection)) {\n\t\t\tconst declared = edge(table, name),\n\t\t\t\tnested = selected === true ? {} : selected\n\t\t\tif (declared.cardinality === 'one') {\n\t\t\t\tconst target = await one(declared, parent, depth + 1)\n\t\t\t\tdto[name] = target\n\t\t\t\t\t? await output(declared.target, target, nested, args, [...path, name], depth + 1, [\n\t\t\t\t\t\t\t...parents,\n\t\t\t\t\t\t\tparent._id,\n\t\t\t\t\t\t])\n\t\t\t\t\t: null\n\t\t\t} else {\n\t\t\t\tconst page = await pageRelation(\n\t\t\t\t\ttable,\n\t\t\t\t\tparent,\n\t\t\t\t\tname,\n\t\t\t\t\tnested,\n\t\t\t\t\t{ numItems: args.numItems, cursor: null, order: args.order },\n\t\t\t\t\t[],\n\t\t\t\t\t[],\n\t\t\t\t\t[...path, name],\n\t\t\t\t\tdepth + 1,\n\t\t\t\t\t[...parents, parent._id],\n\t\t\t\t)\n\t\t\t\t// SAFETY: the declared page validator has parsed this nested DTO page.\n\t\t\t\tdto[name] = page as Value\n\t\t\t}\n\t\t}\n\t\treturn dto\n\t}\n\tfunction prepare(\n\t\ttable: string,\n\t\tname: string,\n\t\tselection: OutputSelection,\n\t\tinput: QueryInput,\n\t\tconditions: readonly IndexCondition[],\n\t\tconstraints: readonly StoredConstraint[],\n\t\tpath: readonly string[],\n\t\trootId: string,\n\t) {\n\t\tplanner.page(edge(table, name).target, selection)\n\t\tassertRelationshipDepth(selection, path.length)\n\t\tconst declared = edge(table, name)\n\t\tif (declared.cardinality !== 'many') throw new RelationshipError('INVALID_RELATION')\n\t\tconst guardConstraint = declared.targetGuard\n\t\t\t? { fields: { [declared.targetGuard.discriminator]: declared.targetGuard.tag } }\n\t\t\t: undefined\n\t\tconst plan = planner.plan(\n\t\t\tdeclared.target,\n\t\t\tinput,\n\t\t\t[],\n\t\t\tguardConstraint ? [...constraints, guardConstraint] : constraints,\n\t\t)\n\t\tconst from = declared.from,\n\t\t\tto = declared.to\n\t\tconst through =\n\t\t\t'base' in from && 'base' in to\n\t\t\t\t? {\n\t\t\t\t\t\ttable: from.junction.table,\n\t\t\t\t\t\tfield: from.junction.field,\n\t\t\t\t\t\ttargetField: to.base.field,\n\t\t\t\t\t\ttargetReference: to.junction.field,\n\t\t\t\t\t}\n\t\t\t\t: null\n\t\tconst sourceTable = through ? through.table : declared.target\n\t\tconst field = through ? through.field : base(to).field\n\t\tconst targetIndex = relationIndex(\n\t\t\tdeclared.target,\n\t\t\tthrough ? through.targetField : field,\n\t\t\tplan,\n\t\t\tconditions,\n\t\t\tdeclared.targetGuard,\n\t\t)\n\t\tconst index = through ? lookup(sourceTable, field, declared.junctionGuard) : targetIndex\n\t\t// SAFETY: planner.page validated the complete output mask before cursor binding.\n\t\tconst binding: CursorBinding = {\n\t\t\t...rootBinding,\n\t\t\ttable: sourceTable,\n\t\t\tindex: index.name,\n\t\t\torder: plan.args.order ?? 'asc',\n\t\t\tclientFilters: plan.clientIdentity,\n\t\t\tserverFilters: {\n\t\t\t\tpredicates: plan.serverIdentity,\n\t\t\t\tselection: selection as Value,\n\t\t\t\tscope: { ...request.scope },\n\t\t\t\trootTable: rootBinding.table,\n\t\t\t\tlookupIndex: targetIndex.name,\n\t\t\t\tguards: {\n\t\t\t\t\tsource: declared.sourceGuard ? { ...declared.sourceGuard } : null,\n\t\t\t\t\ttarget: declared.targetGuard ? { ...declared.targetGuard } : null,\n\t\t\t\t\tjunction: declared.junctionGuard ? { ...declared.junctionGuard } : null,\n\t\t\t\t},\n\t\t\t},\n\t\t\trelationPath: path,\n\t\t\tparent: rootId,\n\t\t}\n\t\tfunction open(token: string) {\n\t\t\ttry {\n\t\t\t\treturn navigation.parse(JSON.parse(codec.open(token, binding)))\n\t\t\t} catch {\n\t\t\t\tthrow new CursorError()\n\t\t\t}\n\t\t}\n\t\treturn { declared, plan, through, sourceTable, field, index, targetIndex, binding, open }\n\t}\n\tasync function pageRelation(\n\t\ttable: string,\n\t\tparent: Document | null,\n\t\tname: string,\n\t\tselection: OutputSelection,\n\t\tinput: QueryInput,\n\t\tconditions: readonly IndexCondition[] = [],\n\t\tconstraints: readonly StoredConstraint[] = [],\n\t\tpath: readonly string[] = [name],\n\t\tdepth = 1,\n\t\tparents: readonly string[] = [],\n\t\tprepared = prepare(\n\t\t\ttable,\n\t\t\tname,\n\t\t\tselection,\n\t\t\tinput,\n\t\t\tconditions,\n\t\t\tconstraints,\n\t\t\tpath,\n\t\t\tparents[0] ?? parent!._id,\n\t\t),\n\t\topened?: { cursor: string | null; endCursor?: string | null },\n\t) {\n\t\trequest.expand(depth, 0)\n\t\tconst { declared, plan, through, sourceTable, field, index, targetIndex, binding } = prepared\n\t\tconst value =\n\t\t\tparent && guarded(parent, declared.sourceGuard)\n\t\t\t\t? parent[base(declared.from).field]\n\t\t\t\t: undefined\n\t\tconst args = { ...plan.args, ...(opened ?? { cursor: null }) }\n\t\t// SAFETY: declarations accept only native scalar lookup values; nullish references are absence.\n\t\tconst lookupPlan = {\n\t\t\t...plan,\n\t\t\tindex,\n\t\t\tprefix:\n\t\t\t\tvalue == null\n\t\t\t\t\t? []\n\t\t\t\t\t: through\n\t\t\t\t\t\t? relationPrefix(index, field, value as FilterScalar, undefined, declared.junctionGuard)\n\t\t\t\t\t\t: relationPrefix(index, field, value as FilterScalar, plan, declared.targetGuard),\n\t\t\tunsatisfiable: value == null || plan.unsatisfiable,\n\t\t}\n\t\tconst indexedTarget = through && through.targetField !== '_id'\n\t\tconst result = await executeStream(\n\t\t\tschema,\n\t\t\trequest,\n\t\t\tsourceTable,\n\t\t\tlookupPlan,\n\t\t\tplanner,\n\t\t\tcodec,\n\t\t\tbinding,\n\t\t\targs,\n\t\t\tasync (row, permitted) => {\n\t\t\t\tif (permitted) planner.validateDocument(indexedTarget ? declared.target : sourceTable, row)\n\t\t\t\tif (!permitted || (through && !indexedTarget && !guarded(row, declared.junctionGuard)))\n\t\t\t\t\treturn null\n\t\t\t\trequest.expand(depth)\n\t\t\t\tlet target: Document | null\n\t\t\t\tif (through && !indexedTarget)\n\t\t\t\t\ttarget = await get(declared.target, row[through.targetReference])\n\t\t\t\telse {\n\t\t\t\t\t// SAFETY: native direct/flattened target streams retain validated system fields.\n\t\t\t\t\ttarget = row as Document\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\t!target ||\n\t\t\t\t\t!guarded(target, declared.targetGuard) ||\n\t\t\t\t\t!(await matches(declared.target, target, plan.residual, depth))\n\t\t\t\t)\n\t\t\t\t\treturn null\n\t\t\t\treturn output(declared.target, target, selection, plan.args, path, depth, parents)\n\t\t\t},\n\t\t\t(raw) => codec.seal(JSON.stringify({ cursor: raw, ancestors: parents.slice(1) }), binding),\n\t\t\tindexedTarget\n\t\t\t\t? (source, db) => {\n\t\t\t\t\t\t// SAFETY: the registry owns the native schema/index descriptors. Public\n\t\t\t\t\t\t// helper flatMap concatenates native outer/inner keys and paginates them.\n\t\t\t\t\t\tconst nativeSchema = schema as SchemaDefinition<\n\t\t\t\t\t\t\tRecord<\n\t\t\t\t\t\t\t\tstring,\n\t\t\t\t\t\t\t\timport('convex/server').TableDefinition<any, Record<string, string[]>>\n\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\tboolean\n\t\t\t\t\t\t>\n\t\t\t\t\t\tconst fields = getIndexFields(declared.target, targetIndex.name, nativeSchema)\n\t\t\t\t\t\treturn source.flatMap(async (junction) => {\n\t\t\t\t\t\t\trequest.expand(depth)\n\t\t\t\t\t\t\tconst permitted = await request.authorize(sourceTable, junction)\n\t\t\t\t\t\t\tplanner.assertUnchanged()\n\t\t\t\t\t\t\tif (permitted) planner.validateDocument(sourceTable, junction)\n\t\t\t\t\t\t\tconst reference = junction[through.targetReference]\n\t\t\t\t\t\t\tif (!permitted || !guarded(junction, declared.junctionGuard) || reference == null)\n\t\t\t\t\t\t\t\treturn new EmptyStream(plan.args.order ?? 'asc', fields)\n\t\t\t\t\t\t\treturn stream(db, nativeSchema)\n\t\t\t\t\t\t\t\t.query(declared.target)\n\t\t\t\t\t\t\t\t.withIndex(targetIndex.name, (q) => {\n\t\t\t\t\t\t\t\t\t// SAFETY: registry validates the native leading lookup; validated filters supply each consecutive trailing binding.\n\t\t\t\t\t\t\t\t\tlet range = q as IndexRangeBuilder<any, string[], number>\n\t\t\t\t\t\t\t\t\t// SAFETY: junction references are native scalar Values validated by the declared lookup.\n\t\t\t\t\t\t\t\t\tconst prefix = relationPrefix(\n\t\t\t\t\t\t\t\t\t\ttargetIndex,\n\t\t\t\t\t\t\t\t\t\tthrough.targetField,\n\t\t\t\t\t\t\t\t\t\treference as FilterScalar,\n\t\t\t\t\t\t\t\t\t\tplan,\n\t\t\t\t\t\t\t\t\t\tdeclared.targetGuard,\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tfor (const binding of prefix) {\n\t\t\t\t\t\t\t\t\t\t// SAFETY: native eq advances the validated consecutive index prefix.\n\t\t\t\t\t\t\t\t\t\trange = range.eq(binding.field, binding.value) as IndexRangeBuilder<\n\t\t\t\t\t\t\t\t\t\t\tany,\n\t\t\t\t\t\t\t\t\t\t\tstring[],\n\t\t\t\t\t\t\t\t\t\t\tnumber\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\t\t\t\treturn range\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.order(plan.args.order ?? 'asc')\n\t\t\t\t\t\t}, fields)\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t\tindexedTarget ? declared.target : sourceTable,\n\t\t)\n\t\tplanner.assertUnchanged()\n\t\treturn planner.page(declared.target, selection).parse(result)\n\t}\n\tasync function continuation(\n\t\trootTable: string,\n\t\trootId: string,\n\t\tpath: readonly string[],\n\t\tselection: OutputSelection,\n\t\tinput: QueryInput,\n\t\tconditions: readonly IndexCondition[],\n\t\tconstraints: readonly StoredConstraint[],\n\t) {\n\t\tif (!path.length || path.length > 4 || !request.db.normalizeId(rootTable, rootId))\n\t\t\tthrow new RelationshipError('INVALID_RELATION')\n\t\tlet table = rootTable\n\t\tconst declarations = path.map((name) => {\n\t\t\tconst declaration = edge(table, name)\n\t\t\ttable = declaration.target\n\t\t\treturn declaration\n\t\t})\n\t\tconst final = declarations.at(-1)!\n\t\tconst prepared = prepare(\n\t\t\tfinal.source,\n\t\t\tpath.at(-1)!,\n\t\t\tselection,\n\t\t\tinput,\n\t\t\tconditions,\n\t\t\tconstraints,\n\t\t\tpath,\n\t\t\trootId,\n\t\t)\n\t\t// Authenticate both slots and native ancestor IDs before ANY parent/traversal read.\n\t\tconst start = input.cursor === null ? null : prepared.open(input.cursor)\n\t\tconst end = input.endCursor == null ? null : prepared.open(input.endCursor)\n\t\tconst ancestors = start?.ancestors ?? end?.ancestors ?? []\n\t\tif (\n\t\t\tancestors.length !== path.length - 1 ||\n\t\t\t(start && end && JSON.stringify(start.ancestors) !== JSON.stringify(end.ancestors)) ||\n\t\t\tancestors.some((id, i) => !request.db.normalizeId(declarations[i].target, id))\n\t\t)\n\t\t\tthrow new CursorError()\n\t\t// Declarative input/index/cursor validation above retains its pre-read errors,\n\t\t// just as on the root path. Every awaited read, ancestry proof and page is protected.\n\t\ttry {\n\t\t\tlet parent = await get(rootTable, rootId)\n\t\t\tfor (let i = 0; parent && i < ancestors.length; i++) {\n\t\t\t\tconst declared = declarations[i]\n\t\t\t\tlet found: Document | null = null\n\t\t\t\tif (declared.cardinality === 'one') {\n\t\t\t\t\tconst target = await one(declared, parent, i + 1)\n\t\t\t\t\tif (target?._id === ancestors[i]) found = target\n\t\t\t\t} else\n\t\t\t\t\tfor await (const target of traverse(declared, parent, i + 1)) {\n\t\t\t\t\t\tif (target._id === ancestors[i]) {\n\t\t\t\t\t\t\tfound = target\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tparent = found\n\t\t\t}\n\t\t\treturn await pageRelation(\n\t\t\t\tfinal.source,\n\t\t\t\tparent,\n\t\t\t\tpath.at(-1)!,\n\t\t\t\tselection,\n\t\t\t\tinput,\n\t\t\t\tconditions,\n\t\t\t\tconstraints,\n\t\t\t\tpath,\n\t\t\t\tpath.length,\n\t\t\t\t[rootId, ...ancestors],\n\t\t\t\tprepared,\n\t\t\t\t{ cursor: start?.cursor ?? null, endCursor: end?.cursor ?? input.endCursor },\n\t\t\t)\n\t\t} catch (error) {\n\t\t\trethrowQueryError(error)\n\t\t}\n\t}\n\treturn { matches, output, continuation, edge }\n}\n"],"mappings":"oRA6BA,IAAaA,EAAb,cAAuC,KAAM,CACvB,KAArB,YAAY,EAA0D,CACrE,MAAMC,CAAI,EADU,KAAA,KAAAA,EAEpB,KAAK,KAAO,mBACb,CACD,EAGA,SAAgBC,EA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AAI,CAAC,EAC5CwB,GAAQ,MAAQ4D,EAAUpF,KAAI,EAAQwB,EAC3C,MACC,UAAW,IAAMA,KAAUO,EAASzC,EAAU0C,EAAQhC,EAAI,CAAC,EAC1D,GAAIwB,EAAO,MAAQ4D,EAAUpF,GAAI,CAChC,EAAQwB,EACR,KACD,CAEF,EAAS6D,CACV,CACA,OAAO,MAAMvC,EACZmC,EAAM,OACNjD,EACAY,EAAK,GAAG,EAAE,EACVhE,EACAqE,EACAvC,EACAwC,EACAN,EACAA,EAAK,OACL,CAACa,EAAQ,GAAG2B,CAAS,EACrBtB,EACA,CAAE,OAAQoB,GAAO,QAAU,KAAM,UAAWC,GAAK,QAAUlC,EAAM,SAAU,CAC5E,CACD,OAASqC,EAAO,CACfC,EAAkBD,CAAK,CACxB,CACD,CACA,MAAO,CAAE,UAAS,SAAQ,eAAc,MAAK,CAC9C"}
|
package/dist/querying.d.mts
CHANGED
|
@@ -1,25 +1,26 @@
|
|
|
1
1
|
import { ManagedBudgets, ManagedQueryContext, ManagedSecurityConfig } from "./querying/security.mjs";
|
|
2
2
|
import { IndexCondition, NativePagination } from "./querying/filters.mjs";
|
|
3
|
-
import { RelationDeclarations, RelationFilterSelection, RelationFilters,
|
|
3
|
+
import { RelationDeclarations, RelationFilterSelection, RelationFilters, RelationQueryRow, RelationRegistry, RelationSelection, RelationTables } from "./relations.mjs";
|
|
4
4
|
import { CursorCodecConfig } from "./querying/cursors.mjs";
|
|
5
5
|
import { DataModelFromSchemaDefinition, GenericSchema, PaginationResult, SchemaDefinition } from "convex/server";
|
|
6
6
|
import { GenericId } from "convex/values";
|
|
7
7
|
//#region src/querying.d.ts
|
|
8
|
-
type FullMask<S> = { [K in keyof S]-?: NonNullable<S[K]> extends true ? true : FullMask<NonNullable<S[K]>>; };
|
|
8
|
+
type FullMask<S> = { [K in keyof S]-?: NonNullable<S[K]> extends true ? true : FullMask<Exclude<NonNullable<S[K]>, true>>; };
|
|
9
9
|
type Paths<D extends RelationDeclarations, T extends string, L extends readonly 1[] = [1, 1, 1, 1]> = L extends readonly [1, ...infer Rest extends 1[]] ? { [K in keyof D[T] & string]: (D[T][K]['cardinality'] extends 'many' ? K : never) | `${K}.${Paths<D, D[T][K]['target'], Rest>}`; }[keyof D[T] & string] : never;
|
|
10
10
|
type PathTarget<D extends RelationDeclarations, T extends string, P extends string> = P extends `${infer Head}.${infer Rest}` ? PathTarget<D, D[T][Head]['target'], Rest> : D[T][P]['target'];
|
|
11
|
+
type PathScope<D extends RelationDeclarations, T extends string, P extends string> = P extends `${infer Head}.${infer Rest}` ? PathScope<D, D[T][Head]['target'], Rest> : Extract<NonNullable<D[T][P]['targetGuard']>['tag'], string>;
|
|
11
12
|
type RemainingDepth<P extends string, L extends readonly 1[]> = L extends readonly [1, ...infer Rest extends 1[]] ? P extends `${string}.${infer Tail}` ? RemainingDepth<Tail, Rest> : Rest : [];
|
|
12
13
|
type EngineArgs<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables> = NativePagination & {
|
|
13
14
|
filters?: RelationFilters<Tables, D, T, FullMask<RelationFilterSelection<Tables, D, T>>>;
|
|
14
15
|
order?: 'asc' | 'desc';
|
|
15
16
|
};
|
|
16
17
|
/** Typed declarative chain returned by the engine; named for consumer declaration emission. */
|
|
17
|
-
export interface TableQuery<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S = {}, L extends readonly 1[] = [1, 1, 1, 1]> {
|
|
18
|
-
when(value: IndexCondition['value'], index: string): TableQuery<Tables, D, T, S, L>;
|
|
19
|
-
where(spec: NonNullable<EngineArgs<Tables, D, T>['filters']>): TableQuery<Tables, D, T, S, L>;
|
|
20
|
-
with<const Selection extends RelationSelection<Tables, D, T, L>>(selection: Selection & { [K in keyof Selection]: K extends keyof RelationSelection<Tables, D, T, L> ? Selection[K] : never; }): TableQuery<Tables, D, T, Selection, L>;
|
|
21
|
-
relation<const P extends Paths<D, Extract<T, string>>>(parent: GenericId<Tables[T]['tableName']>, path: P): Omit<TableQuery<Tables, D, Extract<PathTarget<D, Extract<T, string>, P>, keyof Tables>, {}, RemainingDepth<P, L>>, 'relation'>;
|
|
22
|
-
paginate(args: EngineArgs<Tables, D, T>): Promise<PaginationResult<
|
|
18
|
+
export interface TableQuery<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S = {}, L extends readonly 1[] = [1, 1, 1, 1], Scope extends string = never> {
|
|
19
|
+
when(value: IndexCondition['value'], index: string): TableQuery<Tables, D, T, S, L, Scope>;
|
|
20
|
+
where(spec: NonNullable<EngineArgs<Tables, D, T>['filters']>): TableQuery<Tables, D, T, S, L, Scope>;
|
|
21
|
+
with<const Selection extends RelationSelection<Tables, D, T, L>>(selection: Selection & { [K in keyof Selection]: K extends keyof RelationSelection<Tables, D, T, L> ? Selection[K] : never; }): TableQuery<Tables, D, T, Selection, L, Scope>;
|
|
22
|
+
relation<const P extends Paths<D, Extract<T, string>>>(parent: GenericId<Tables[T]['tableName']>, path: P): Omit<TableQuery<Tables, D, Extract<PathTarget<D, Extract<T, string>, P>, keyof Tables>, {}, RemainingDepth<P, L>, PathScope<D, Extract<T, string>, P>>, 'relation'>;
|
|
23
|
+
paginate(args: EngineArgs<Tables, D, T>): Promise<PaginationResult<RelationQueryRow<Tables, D, T, S, Scope>>>;
|
|
23
24
|
}
|
|
24
25
|
export interface QueryEngineDeclaration<Schema extends SchemaDefinition<GenericSchema, boolean>, Tables extends RelationTables, D extends RelationDeclarations> {
|
|
25
26
|
schema: Schema;
|
package/dist/querying.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"querying.mjs","names":["executorRequest","createQueryEngine","config","settings","options","planner","createPlanner","schema","relations","cursorCodec","createCursorCodec","maxPageSize","engineVersion","policyVersion","registryDigest","security","createManagedSecurity","querying","request","ctx","tableQuery","table","conditions","constraints","selection","route","spec","selected","path","declaredPath","target","name","edge","codec","createEnvironmentCursorCodec","pageSchema","assertRelationshipDepth","plan","input","byte","binding","executor","relationshipExecutor","result","executeQuery","permitted","row"],"sources":["../src/querying.ts"],"sourcesContent":["import type {\n\tGenericSchema,\n\tSchemaDefinition,\n\tDataModelFromSchemaDefinition,\n\tPaginationResult,\n} from 'convex/server'\nimport type { GenericId } from 'convex/values'\nimport type {\n\tRelationTables,\n\tRelationDeclarations,\n\tRelationRegistry,\n\tRelationRow,\n\tRelationSelection,\n\tRelationFilters,\n\tRelationFilterSelection,\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} from './querying/relationships'\nimport {\n\tcreateCursorCodec,\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} from './querying/security'\nimport type { IndexCondition, NativePagination } from './querying/filters'\n\ntype FullMask<S> = {\n\t[K in keyof S]-?: NonNullable<S[K]> extends true ? true : FullMask<NonNullable<S[K]>>\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 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> {\n\twhen(value: IndexCondition['value'], index: string): TableQuery<Tables, D, T, S, L>\n\twhere(spec: NonNullable<EngineArgs<Tables, D, T>['filters']>): TableQuery<Tables, D, T, S, L>\n\twith<const Selection extends RelationSelection<Tables, D, T, L>>(\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): TableQuery<Tables, D, T, Selection, L>\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>,\n\t\t'relation'\n\t>\n\tpaginate(args: EngineArgs<Tables, D, T>): Promise<PaginationResult<RelationRow<Tables, D, T, S>>>\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<Schema extends SchemaDefinition<GenericSchema, boolean>> {\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}\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> {\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>\n\t}\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>,\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> & { 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>,\n\toptions?: QueryEngineOptions<Schema>,\n) {\n\tconst { schema, relations } = config\n\t// Retain released one-argument calls; a second argument overrides legacy fields.\n\tconst settings = { ...config, ...options }\n\tconst planner = createPlanner(schema, relations)\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. Live guards still\n\t// inspect current schemas; this caches only the immutable version identity.\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\tplanner.assertUnchanged()\n\t\tconst request = security(ctx)\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) {\n\t\t\treturn Object.freeze({\n\t\t\t\twhen: (value: IndexCondition['value'], index: string) =>\n\t\t\t\t\ttableQuery(table, [...conditions, { value, index }], constraints, selection, route),\n\t\t\t\twhere: (spec: StoredConstraint) =>\n\t\t\t\t\ttableQuery(table, conditions, [...constraints, spec], selection, route),\n\t\t\t\twith: (selected: OutputSelection) =>\n\t\t\t\t\ttableQuery(table, conditions, constraints, selected, route),\n\t\t\t\trelation: (parent: string, declaredPath: string) => {\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 })\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.assertUnchanged()\n\t\t\t\t\tconst pageSchema = planner.page(table, selection)\n\t\t\t\t\tassertRelationshipDepth(selection, route?.path.length ?? 0)\n\t\t\t\t\tconst plan = planner.plan(table, input, route ? [] : conditions, constraints)\n\t\t\t\t\tif (plan.args.numItems > maxPageSize) throw new Error('Page size exceeds central ceiling')\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\t// The digest await is a boundary too: mutation must be detected\n\t\t\t\t\t// before authenticated cursor validation or native query construction.\n\t\t\t\t\tplanner.assertUnchanged()\n\t\t\t\t\t// SAFETY: selection has passed the registry page validator before binding.\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: 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\t\tpredicates: plan.serverIdentity,\n\t\t\t\t\t\t\tselection: selection as import('convex/values').Value,\n\t\t\t\t\t\t\tscope: { ...request.scope },\n\t\t\t\t\t\t},\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 executor = relationshipExecutor(\n\t\t\t\t\t\tschema,\n\t\t\t\t\t\texecutorRequest as ExecutionRequest,\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)\n\t\t\t\t\tif (route)\n\t\t\t\t\t\treturn executor.continuation(\n\t\t\t\t\t\t\troute.table,\n\t\t\t\t\t\t\troute.parent,\n\t\t\t\t\t\t\troute.path,\n\t\t\t\t\t\t\tselection,\n\t\t\t\t\t\t\tplan.args,\n\t\t\t\t\t\t\tconditions,\n\t\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\t)\n\t\t\t\t\tconst result = await executeQuery(\n\t\t\t\t\t\tschema,\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tplan,\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\tasync (row, permitted) => {\n\t\t\t\t\t\t\t// SAFETY: metered native stream rows contain the validated system fields.\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!permitted ||\n\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)\n\t\t\t\t\t\t\t\treturn null\n\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\treturn executor.output(table, row as RelationDocument, selection, plan.args)\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t\tplanner.assertUnchanged()\n\t\t\t\t\treturn pageSchema.parse(result)\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> }\n\t}\n\treturn Object.assign(querying, { tables: relations.tables })\n}\n"],"mappings":"6WAqKA,SAAgBC,EAKf,EACA,EACC,CACD,GAAM,CAAE,SAAQ,aAAcC,EAExBC,EAAW,CAAE,GAAGD,EAAQ,GAAGE,CAAQ,EACnCC,EAAUC,EAAcC,EAAQC,CAAS,EAC3CC,EAAcN,EAAS,SAAW,IAAA,GAAY,IAAA,GAAYO,EAAkBP,EAAS,MAAM,EACzFQ,EAAcR,EAAS,aAAe,IAC5C,GAAI,CAAC,OAAO,cAAcQ,CAAW,GAAKA,GAAe,GAAKA,EAAc,IAC3E,MAAU,MAAM,2BAA2B,EAC5C,IAAMC,EAAgBT,EAAS,eAAiB,WAC1CU,EAAgBV,EAAS,eAAiB,IAI5CW,EACEC,EAAWC,EAA6D,CAC7E,OAAQ,OAAO,K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,gBAAgB,EACjB8B,EAAW,MAAMQ,CAAM,CAC/B,CACD,CAAC,CACF,CAGA,OAAO,OAAO,OACb,OAAO,YAAY,OAAO,KAAKnC,EAAU,MAAM,CAAC,CAAC,IAAK,GAAU,CAACa,EAAOD,EAAWC,CAAK,CAAC,CAAC,CAAC,CAC5F,CACD,CACA,OAAO,OAAO,OAAOJ,EAAU,CAAE,OAAQT,EAAU,MAAO,CAAC,CAC5D"}
|
|
1
|
+
{"version":3,"file":"querying.mjs","names":["executorRequest","createQueryEngine","config","settings","options","planner","createPlanner","schema","relations","cursorCodec","createCursorCodec","maxPageSize","engineVersion","policyVersion","registryDigest","security","createManagedSecurity","querying","request","ctx","tableQuery","table","conditions","constraints","selection","route","spec","selected","path","declaredPath","target","name","edge","codec","createEnvironmentCursorCodec","pageSchema","assertRelationshipDepth","plan","input","byte","binding","executor","relationshipExecutor","result","executeQuery","permitted","row"],"sources":["../src/querying.ts"],"sourcesContent":["import type {\n\tGenericSchema,\n\tSchemaDefinition,\n\tDataModelFromSchemaDefinition,\n\tPaginationResult,\n} from 'convex/server'\nimport type { GenericId } from 'convex/values'\nimport type {\n\tRelationTables,\n\tRelationDeclarations,\n\tRelationRegistry,\n\tRelationQueryRow,\n\tRelationSelection,\n\tRelationFilters,\n\tRelationFilterSelection,\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} from './querying/relationships'\nimport {\n\tcreateCursorCodec,\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} from './querying/security'\nimport type { IndexCondition, NativePagination } from './querying/filters'\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> {\n\twhen(value: IndexCondition['value'], index: string): TableQuery<Tables, D, T, S, L, Scope>\n\twhere(\n\t\tspec: NonNullable<EngineArgs<Tables, D, T>['filters']>,\n\t): TableQuery<Tables, D, T, S, L, Scope>\n\twith<const Selection extends RelationSelection<Tables, D, T, L>>(\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): TableQuery<Tables, D, T, Selection, L, Scope>\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>,\n\t\t'relation'\n\t>\n\tpaginate(\n\t\targs: EngineArgs<Tables, D, T>,\n\t): Promise<PaginationResult<RelationQueryRow<Tables, D, T, S, Scope>>>\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<Schema extends SchemaDefinition<GenericSchema, boolean>> {\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}\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> {\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>\n\t}\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>,\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> & { 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>,\n\toptions?: QueryEngineOptions<Schema>,\n) {\n\tconst { schema, relations } = config\n\t// Retain released one-argument calls; a second argument overrides legacy fields.\n\tconst settings = { ...config, ...options }\n\tconst planner = createPlanner(schema, relations)\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. Live guards still\n\t// inspect current schemas; this caches only the immutable version identity.\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\tplanner.assertUnchanged()\n\t\tconst request = security(ctx)\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) {\n\t\t\treturn Object.freeze({\n\t\t\t\twhen: (value: IndexCondition['value'], index: string) =>\n\t\t\t\t\ttableQuery(table, [...conditions, { value, index }], constraints, selection, route),\n\t\t\t\twhere: (spec: StoredConstraint) =>\n\t\t\t\t\ttableQuery(table, conditions, [...constraints, spec], selection, route),\n\t\t\t\twith: (selected: OutputSelection) =>\n\t\t\t\t\ttableQuery(table, conditions, constraints, selected, route),\n\t\t\t\trelation: (parent: string, declaredPath: string) => {\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 })\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.assertUnchanged()\n\t\t\t\t\tconst pageSchema = planner.page(table, selection)\n\t\t\t\t\tassertRelationshipDepth(selection, route?.path.length ?? 0)\n\t\t\t\t\tconst plan = planner.plan(table, input, route ? [] : conditions, constraints)\n\t\t\t\t\tif (plan.args.numItems > maxPageSize) throw new Error('Page size exceeds central ceiling')\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\t// The digest await is a boundary too: mutation must be detected\n\t\t\t\t\t// before authenticated cursor validation or native query construction.\n\t\t\t\t\tplanner.assertUnchanged()\n\t\t\t\t\t// SAFETY: selection has passed the registry page validator before binding.\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: 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\t\tpredicates: plan.serverIdentity,\n\t\t\t\t\t\t\tselection: selection as import('convex/values').Value,\n\t\t\t\t\t\t\tscope: { ...request.scope },\n\t\t\t\t\t\t},\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 executor = relationshipExecutor(\n\t\t\t\t\t\tschema,\n\t\t\t\t\t\texecutorRequest as ExecutionRequest,\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)\n\t\t\t\t\tif (route)\n\t\t\t\t\t\treturn executor.continuation(\n\t\t\t\t\t\t\troute.table,\n\t\t\t\t\t\t\troute.parent,\n\t\t\t\t\t\t\troute.path,\n\t\t\t\t\t\t\tselection,\n\t\t\t\t\t\t\tplan.args,\n\t\t\t\t\t\t\tconditions,\n\t\t\t\t\t\t\tconstraints,\n\t\t\t\t\t\t)\n\t\t\t\t\tconst result = await executeQuery(\n\t\t\t\t\t\tschema,\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tplan,\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\tasync (row, permitted) => {\n\t\t\t\t\t\t\t// SAFETY: metered native stream rows contain the validated system fields.\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!permitted ||\n\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)\n\t\t\t\t\t\t\t\treturn null\n\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\treturn executor.output(table, row as RelationDocument, selection, plan.args)\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t\tplanner.assertUnchanged()\n\t\t\t\t\treturn pageSchema.parse(result)\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> }\n\t}\n\treturn Object.assign(querying, { tables: relations.tables })\n}\n"],"mappings":"6WAoLA,SAAgBC,EAKf,EACA,EACC,CACD,GAAM,CAAE,SAAQ,aAAcC,EAExBC,EAAW,CAAE,GAAGD,EAAQ,GAAGE,CAAQ,EACnCC,EAAUC,EAAcC,EAAQC,CAAS,EAC3CC,EAAcN,EAAS,SAAW,IAAA,GAAY,IAAA,GAAYO,EAAkBP,EAAS,MAAM,EACzFQ,EAAcR,EAAS,aAAe,IAC5C,GAAI,CAAC,OAAO,cAAcQ,CAAW,GAAKA,GAAe,GAAKA,EAAc,IAC3E,MAAU,MAAM,2BAA2B,EAC5C,IAAMC,EAAgBT,EAAS,eAAiB,WAC1CU,EAAgBV,EAAS,eAAiB,IAI5CW,EACEC,EAAWC,EAA6D,CAC7E,OAAQ,OAAO,KAAKR,EAAU,MAAM,EACpC,gBACA,QAASL,EAAS,QAClB,eAAgBA,EAAS,cAC1B,CAAC,EACD,SAASc,EAAS,EAAiE,CAClFZ,EAAQ,gBAAgB,EACxB,IAAMa,EAAUH,EAASI,CAAG,EAC5B,SAASC,EACR,EACA,EAAwC,CAAC,EACzC,EAA2C,CAAC,EAC5C,EAA6B,CAAC,EAC9B,EACC,CACD,OAAO,OAAO,OAAO,CACpB,MAAO,EAAgC,IACtCA,EAAWC,EAAO,CAAC,GAAGC,EAAY,CAAE,QAAO,OAAM,CAAC,EAAGC,EAAaC,EAAWC,CAAK,EACnF,MAAQ,GACPL,EAAWC,EAAOC,E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,EAAG,GAAG,CAC5C,CAAC,CAAC,KAAK,EAAE,EAGTlC,EAAQ,gBAAgB,EAExB,IAAMmC,EAAyB,CAC9B,MAAOf,GAAO,OAASJ,EACvB,MAAOgB,EAAK,OAAO,MAAQ,mBAC3B,MAAOA,EAAK,KAAK,OAAS,MAC1B,cAAeA,EAAK,eAEpB,cAAe,CACd,WAAYA,EAAK,eACN,YACX,MAAO,CAAE,GAAGnB,EAAQ,KAAM,CAC3B,EACA,aAAc,CAAC,EACf,UAAW,KAAK,UAAUA,EAAQ,KAAK,EACvC,OAAQA,EAAQ,MAAM,OACtB,gBACA,gBACA,gBAAiBJ,CAClB,EAIM2B,EAAWC,EAChBnC,EACAP,EACAK,EACA4B,EACAO,CACD,EACA,GAAIf,EACH,OAAOgB,EAAS,aACfhB,EAAM,MACNA,EAAM,OACNA,EAAM,KACND,EACAa,EAAK,KACLf,EACAC,CACD,EACD,IAAMoB,EAAS,MAAMC,EACpBrC,EACAW,EACAG,EACAgB,EACAhC,EACA4B,EACAO,EACA,MAAO,EAAK,IAGV,CAACK,GACD,CAAE,MAAMJ,EAAS,QAAQpB,EAAOyB,EAAyBT,EAAK,QAAQ,EAE/D,KAEDI,EAAS,OAAOpB,EAAOyB,EAAyBtB,EAAWa,EAAK,IAAI,CAE7E,EAEA,OADAhC,EAAQ,gBAAgB,EACjB8B,EAAW,MAAMQ,CAAM,CAC/B,CACD,CAAC,CACF,CAGA,OAAO,OAAO,OACb,OAAO,YAAY,OAAO,KAAKnC,EAAU,MAAM,CAAC,CAAC,IAAK,GAAU,CAACa,EAAOD,EAAWC,CAAK,CAAC,CAAC,CAAC,CAC5F,CACD,CACA,OAAO,OAAO,OAAOJ,EAAU,CAAE,OAAQT,EAAU,MAAO,CAAC,CAC5D"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { FieldReference, RelationBuilder, RelationDeclarations, RelationEdge, RelationFilterSelection, RelationFilters, RelationRegistry, RelationRegistryIdentity, RelationRow, RelationSelection, RelationTable, RelationTableHelpers, RelationTables, ThroughReference, defineRelations } from "./relations.mjs";
|
|
2
|
-
export { type FieldReference, type RelationBuilder, type RelationDeclarations, type RelationEdge, type RelationFilterSelection, type RelationFilters, type RelationRegistry, type RelationRegistryIdentity, type RelationRow, type RelationSelection, type RelationTable, type RelationTableHelpers, type RelationTables, type ThroughReference, defineRelations };
|
|
1
|
+
import { BranchBuilder, FieldReference, RelationBuilder, RelationDeclarations, RelationEdge, RelationFilterSelection, RelationFilters, RelationRegistry, RelationRegistryIdentity, RelationRow, RelationSelection, RelationTable, RelationTableHelpers, RelationTables, ThroughReference, defineRelations } from "./relations.mjs";
|
|
2
|
+
export { type BranchBuilder, type FieldReference, type RelationBuilder, type RelationDeclarations, type RelationEdge, type RelationFilterSelection, type RelationFilters, type RelationRegistry, type RelationRegistryIdentity, type RelationRow, type RelationSelection, type RelationTable, type RelationTableHelpers, type RelationTables, type ThroughReference, defineRelations };
|
package/dist/relations.d.mts
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { PaginationOptionsSchema, ScalarPredicate, ScalarSelection } from "./querying/filters.mjs";
|
|
1
|
+
import { FieldSchemas, PaginationOptionsSchema, ScalarPredicate, ScalarSelection } from "./querying/filters.mjs";
|
|
2
2
|
import { ConvexValidatorFromZod } from "convex-helpers/server/zod4";
|
|
3
3
|
import { PaginationResult, TableDefinition } from "convex/server";
|
|
4
4
|
import { z } from "zod";
|
|
5
|
-
import { GenericId, ValidatorJSON } from "convex/values";
|
|
5
|
+
import { GenericId, GenericValidator, ValidatorJSON } from "convex/values";
|
|
6
6
|
//#region src/relations.d.ts
|
|
7
|
-
/**
|
|
7
|
+
/** Generated object or discriminated-union boundaries. */
|
|
8
8
|
export interface RelationTable {
|
|
9
9
|
tableName: string;
|
|
10
|
-
schema: z.ZodObject
|
|
11
|
-
publicDto: z.ZodObject
|
|
10
|
+
schema: z.ZodObject | z.ZodDiscriminatedUnion<any, string>;
|
|
11
|
+
publicDto: z.ZodObject | z.ZodDiscriminatedUnion<any, string>;
|
|
12
12
|
table: TableDefinition;
|
|
13
13
|
dto(includeId: true): z.ZodType;
|
|
14
14
|
}
|
|
@@ -17,29 +17,54 @@ export type RelationTables = Record<string, RelationTable>;
|
|
|
17
17
|
export interface SelectionMask {
|
|
18
18
|
[key: string]: true | SelectionMask;
|
|
19
19
|
}
|
|
20
|
-
type
|
|
20
|
+
type DocumentFields<S> = S extends z.ZodObject<infer F> ? F : S extends z.ZodDiscriminatedUnion<infer O, string> ? O[number] extends (infer B) ? B extends z.ZodObject<infer F> ? F : never : never : never;
|
|
21
|
+
type AllKeys<F> = F extends unknown ? keyof F : never;
|
|
22
|
+
type FieldAt<F, K extends PropertyKey> = F extends unknown ? K extends keyof F ? F[K] : never : never;
|
|
23
|
+
type NativeDomain<V> = V extends {
|
|
24
|
+
kind: 'union';
|
|
25
|
+
members: infer M extends GenericValidator[];
|
|
26
|
+
} ? NativeDomain<M[number]> : V extends {
|
|
27
|
+
kind: 'null';
|
|
28
|
+
} ? never : V extends {
|
|
29
|
+
kind: infer K;
|
|
30
|
+
type: infer Value;
|
|
31
|
+
} ? readonly [K, Exclude<Value, undefined>] : never;
|
|
32
|
+
type DomainAt<F, K extends PropertyKey> = F extends unknown ? K extends keyof F ? F[K] extends z.ZodType ? NativeDomain<ConvexValidatorFromZod<F[K], 'required'>> : never : never : never;
|
|
33
|
+
type CompatibleBranches<F, K extends keyof F, Domain = DomainAt<F, K>> = F extends unknown ? Same<DomainAt<F, K>, Domain> : never;
|
|
34
|
+
type Discriminator<T extends RelationTable> = T['schema'] extends z.ZodDiscriminatedUnion<any, string> ? T['schema']['_zod']['def']['discriminator'] : never;
|
|
35
|
+
type Fields<T extends RelationTable, F = DocumentFields<T['schema']>> = string extends T['tableName'] ? FieldSchemas : T['schema'] extends z.ZodObject<infer ObjectFields> ? { [K in keyof ObjectFields]: Extract<ObjectFields[K], z.ZodType>; } : { [K in Extract<keyof F, string> as K extends Discriminator<T> ? K : false extends CompatibleBranches<F, K> ? never : K]: Extract<FieldAt<F, K>, z.ZodType>; };
|
|
36
|
+
type BranchFields<T extends RelationTable, Tag extends string> = DocumentFields<T['schema']> extends (infer F) ? F extends Record<Discriminator<T>, z.ZodType> ? Tag extends z.output<F[Discriminator<T>]> ? F : never : never : never;
|
|
37
|
+
type Tags<T extends RelationTable> = T['schema'] extends z.ZodDiscriminatedUnion<any, string> ? Extract<z.output<T['schema']>[Discriminator<T>], string> : never;
|
|
21
38
|
type Native<T extends RelationTable, K extends keyof Fields<T>> = ConvexValidatorFromZod<Fields<T>[K], 'required'>['type'];
|
|
22
39
|
declare const fieldBrand: unique symbol;
|
|
23
40
|
declare const edgeBrand: unique symbol;
|
|
24
41
|
type Comparable<Value> = Exclude<Value, null | undefined>;
|
|
25
42
|
type Same<A, B> = [Comparable<A> | Comparable<B>] extends [never] ? false : [Comparable<A>] extends [Comparable<B>] ? [Comparable<B>] extends [Comparable<A>] ? true : false : false;
|
|
26
|
-
export interface FieldReference<Table extends string, Field extends string, Value> {
|
|
43
|
+
export interface FieldReference<Table extends string, Field extends string, Value, Scope extends string = never> {
|
|
44
|
+
readonly guard?: RelationGuard<Scope>;
|
|
27
45
|
readonly [fieldBrand]: Value;
|
|
28
46
|
readonly table: Table;
|
|
29
47
|
readonly field: Field;
|
|
30
|
-
through<J extends AnyField>(junction: J & (Same<Value, J[typeof fieldBrand]> extends true ? {} : never)): ThroughReference<Table, Field, Value, J>;
|
|
48
|
+
through<J extends AnyField>(junction: J & (Same<Value, J[typeof fieldBrand]> extends true ? {} : never)): ThroughReference<Table, Field, Value, J, Scope>;
|
|
31
49
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
readonly
|
|
50
|
+
export interface RelationGuard<Tag extends string = string> {
|
|
51
|
+
readonly discriminator: string;
|
|
52
|
+
readonly tag: Tag;
|
|
53
|
+
}
|
|
54
|
+
type AnyField = FieldReference<string, string, any, any>;
|
|
55
|
+
export interface ThroughReference<Table extends string, Field extends string, Value, Junction extends AnyField, Scope extends string = never> {
|
|
56
|
+
readonly base: FieldReference<Table, Field, Value, Scope>;
|
|
35
57
|
readonly junction: Junction;
|
|
36
58
|
}
|
|
37
|
-
type AnyThrough = ThroughReference<string, string, any, AnyField>;
|
|
59
|
+
type AnyThrough = ThroughReference<string, string, any, AnyField, any>;
|
|
38
60
|
type Leg = AnyField | AnyThrough;
|
|
39
61
|
type Base<L extends Leg> = L extends AnyThrough ? L['base'] : L;
|
|
40
62
|
type JunctionTable<L extends Leg> = L extends AnyThrough ? L['junction']['table'] : never;
|
|
41
63
|
type CompatibleLegs<F extends Leg, T extends Leg> = F extends AnyThrough ? T extends AnyThrough ? Same<JunctionTable<F>, JunctionTable<T>> extends true ? {} : never : never : T extends AnyThrough ? never : Same<Base<F>[typeof fieldBrand], Base<T>[typeof fieldBrand]> extends true ? {} : never;
|
|
42
|
-
export interface RelationEdge<Source extends string, Target extends string, Cardinality extends 'one' | 'many'> {
|
|
64
|
+
export interface RelationEdge<Source extends string, Target extends string, Cardinality extends 'one' | 'many', SourceScope extends string = never, TargetScope extends string = never> {
|
|
65
|
+
readonly sourceGuard?: RelationGuard<SourceScope>;
|
|
66
|
+
readonly targetGuard?: RelationGuard<TargetScope>;
|
|
67
|
+
readonly junctionGuard?: RelationGuard;
|
|
43
68
|
readonly [edgeBrand]: true;
|
|
44
69
|
readonly source: Source;
|
|
45
70
|
readonly target: Target;
|
|
@@ -47,43 +72,62 @@ export interface RelationEdge<Source extends string, Target extends string, Card
|
|
|
47
72
|
readonly from: Leg;
|
|
48
73
|
readonly to: Leg;
|
|
49
74
|
}
|
|
50
|
-
type AnyEdge = RelationEdge<string, string, 'one' | 'many'>;
|
|
75
|
+
type AnyEdge = RelationEdge<string, string, 'one' | 'many', any, any>;
|
|
51
76
|
type FieldReferences<Tables extends RelationTables> = { [T in keyof Tables]: { [K in Extract<keyof Fields<Tables[T]>, string>]: FieldReference<Extract<T, string>, K, Native<Tables[T], K>>; }; };
|
|
77
|
+
export type BranchBuilder<Tables extends RelationTables> = <const T extends keyof Tables & string, const Tag extends Tags<Tables[T]>>(table: T, tag: Tag) => { [K in keyof BranchFields<Tables[T], Tag> & string]: FieldReference<T, K, ConvexValidatorFromZod<Extract<BranchFields<Tables[T], Tag>[K], z.ZodType>, 'required'>['type'], Tag>; };
|
|
78
|
+
type Scope<L extends Leg> = NonNullable<Base<L>['guard']>['tag'];
|
|
52
79
|
type AllReferences<Tables extends RelationTables> = { [T in keyof Tables]: FieldReferences<Tables>[T][Extract<keyof FieldReferences<Tables>[T], string>]; }[keyof Tables];
|
|
53
|
-
type Builders<Tables extends RelationTables, C extends 'one' | 'many'> = { [T in keyof Tables]: <F extends AllReferences<Tables> | AnyThrough, To extends FieldReferences<Tables>[T][Extract<keyof FieldReferences<Tables>[T], string>] | AnyThrough>(spec: {
|
|
80
|
+
type Builders<Tables extends RelationTables, C extends 'one' | 'many'> = { [T in keyof Tables]: <F extends AllReferences<Tables> | AnyField | AnyThrough, To extends FieldReferences<Tables>[T][Extract<keyof FieldReferences<Tables>[T], string>] | AnyField | AnyThrough>(spec: {
|
|
54
81
|
from: F;
|
|
55
82
|
to: To;
|
|
56
|
-
} & CompatibleLegs<F, To> & (Base<To>['table'] extends T ? {} : never)) => RelationEdge<Base<F>['table'], Extract<T, string>, C
|
|
83
|
+
} & CompatibleLegs<F, To> & (Base<To>['table'] extends T ? {} : never)) => RelationEdge<Base<F>['table'], Extract<T, string>, C, Scope<F>, Scope<To>>; };
|
|
57
84
|
export type RelationBuilder<Tables extends RelationTables> = FieldReferences<Tables> & {
|
|
58
85
|
one: Builders<Tables, 'one'>;
|
|
59
86
|
many: Builders<Tables, 'many'>;
|
|
60
87
|
};
|
|
61
88
|
export type RelationDeclarations = Record<string, Record<string, AnyEdge>>;
|
|
62
|
-
type ExactDeclarations<Tables extends RelationTables, D extends RelationDeclarations> = { [T in keyof D]: T extends keyof Tables ? { [K in keyof D[T]]: K extends
|
|
89
|
+
type ExactDeclarations<Tables extends RelationTables, D extends RelationDeclarations> = { [T in keyof D]: T extends keyof Tables ? { [K in keyof D[T]]: K extends AllKeys<DocumentFields<Tables[T]['schema']>> | 'and' | 'or' | 'not' | 'fields' | 'then' | ([Tags<Tables[T]>] extends [never] ? never : 'variant' | 'variants') | '__proto__' | 'constructor' | 'prototype' ? never : D[T][K]['source'] extends T ? D[T][K] : never; } : never; };
|
|
63
90
|
type Depth = readonly [1, 1, 1, 1];
|
|
64
91
|
type Tail<D extends readonly 1[]> = D extends readonly [1, ...infer R extends 1[]] ? R : [];
|
|
65
92
|
type Edges<D, T> = T extends keyof D ? D[T] : {};
|
|
66
93
|
type Target<E> = E extends AnyEdge ? E['target'] : never;
|
|
67
94
|
export type RelationSelection<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, Level extends readonly 1[] = Depth> = Level extends readonly [] ? Record<string, never> : { [K in keyof Edges<D, T>]?: true | RelationSelection<Tables, D, Extract<Target<Edges<D, T>[K]>, keyof Tables>, Tail<Level>>; };
|
|
68
|
-
|
|
95
|
+
type BranchTables<Tables extends RelationTables, T extends keyof Tables, Tag extends string> = { [K in keyof Tables]: K extends T ? Omit<Tables[K], 'schema'> & {
|
|
96
|
+
schema: z.ZodObject<BranchFields<Tables[T], Tag>>;
|
|
97
|
+
} : Tables[K]; };
|
|
98
|
+
type VariantSelections<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, Level extends readonly 1[]> = { [Tag in Tags<Tables[T]>]?: RelationFilterSelection<BranchTables<Tables, T, Tag>, D, T, Level>; };
|
|
99
|
+
export type RelationFilterSelection<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, Level extends readonly 1[] = Depth> = ([Tags<Tables[T]>] extends [never] ? ScalarSelection<Fields<Tables[T]>> : Omit<ScalarSelection<Fields<Tables[T]>>, 'variants'> & {
|
|
100
|
+
variants?: ('variants' extends keyof ScalarSelection<Fields<Tables[T]>> ? true : never) | VariantSelections<Tables, D, T, Level>;
|
|
101
|
+
}) & (Level extends readonly [] ? {} : { [K in keyof Edges<D, T>]?: RelationFilterSelection<Tables, D, Extract<Target<Edges<D, T>[K]>, keyof Tables>, Tail<Level>>; });
|
|
69
102
|
type ExactOutputMask<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, L extends readonly 1[] = Depth> = S & { [K in keyof S]: L extends readonly [] ? never : K extends keyof Edges<D, T> ? S[K] extends true ? true : ExactOutputMask<Tables, D, Extract<Target<Edges<D, T>[K]>, keyof Tables>, S[K], Tail<L>> : never; };
|
|
70
|
-
type ExactFilterMask<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, L extends readonly 1[] = Depth> = S & { [K in keyof S]: K extends keyof ScalarSelection<Fields<Tables[T]>> ? S[K] extends true ? true : never : L extends readonly [] ? never : K extends keyof Edges<D, T> ? S[K] extends true ? never : ExactFilterMask<Tables, D, Extract<Target<Edges<D, T>[K]>, keyof Tables>, S[K], Tail<L>> : never; };
|
|
103
|
+
type ExactFilterMask<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, L extends readonly 1[] = Depth> = S & { [K in keyof S]: K extends ([Tags<Tables[T]>] extends [never] ? never : 'variants') ? S[K] extends true ? K extends keyof ScalarSelection<Fields<Tables[T]>> ? true : never : S[K] & { [Tag in keyof S[K]]: Tag extends Tags<Tables[T]> ? ExactFilterMask<BranchTables<Tables, T, Extract<Tag, string>>, D, T, S[K][Tag], Tail<L>> : never; } : K extends keyof ScalarSelection<Fields<Tables[T]>> ? S[K] extends true ? true : never : L extends readonly [] ? never : K extends keyof Edges<D, T> ? S[K] extends true ? never : ExactFilterMask<Tables, D, Extract<Target<Edges<D, T>[K]>, keyof Tables>, S[K], Tail<L>> : never; };
|
|
71
104
|
type ScalarValues<T extends RelationTable, S, Side extends 'input' | 'output'> = { [K in Extract<keyof S, keyof Fields<T>>]?: ScalarPredicate<Fields<T>[K], Side>; };
|
|
72
|
-
export type RelationFilters<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, Side extends 'input' | 'output' = 'output', Level extends readonly 1[] = Depth> = Omit<ScalarValues<Tables[T], S, Side>, 'and' | 'or' | 'not' | 'fields'> & {
|
|
105
|
+
export type RelationFilters<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, Side extends 'input' | 'output' = 'output', Level extends readonly 1[] = Depth> = Omit<ScalarValues<Tables[T], S, Side>, 'and' | 'or' | 'not' | 'fields' | ([Tags<Tables[T]>] extends [never] ? never : 'variant')> & {
|
|
73
106
|
fields?: ScalarValues<Tables[T], S, Side>;
|
|
74
|
-
} & (Level extends readonly [] ? {} : { [K in Extract<keyof S, keyof Edges<D, T>>]?: Edges<D, T>[K] extends RelationEdge<string, infer Target, infer C> ? C extends 'one' ? RelationFilters<Tables, D, Extract<Target, keyof Tables>, S[K], Side, Tail<Level>> | null : {
|
|
107
|
+
} & VariantFilters<Tables, D, T, S, Side, Level> & (Level extends readonly [] ? {} : { [K in Extract<keyof S, keyof Edges<D, T>>]?: Edges<D, T>[K] extends RelationEdge<string, infer Target, infer C, any, any> ? C extends 'one' ? RelationFilters<Tables, D, Extract<Target, keyof Tables>, S[K], Side, Tail<Level>> | null : {
|
|
75
108
|
some: RelationFilters<Tables, D, Extract<Target, keyof Tables>, S[K], Side, Tail<Level>>;
|
|
76
109
|
} | {
|
|
77
110
|
none: RelationFilters<Tables, D, Extract<Target, keyof Tables>, S[K], Side, Tail<Level>>;
|
|
78
111
|
} : never; } & {
|
|
79
|
-
and?: RelationFilters<Tables, D, T, S, Side, Tail<Level>>[];
|
|
80
|
-
or?: RelationFilters<Tables, D, T, S, Side, Tail<Level>>[];
|
|
112
|
+
and?: readonly RelationFilters<Tables, D, T, S, Side, Tail<Level>>[];
|
|
113
|
+
or?: readonly RelationFilters<Tables, D, T, S, Side, Tail<Level>>[];
|
|
81
114
|
not?: RelationFilters<Tables, D, T, S, Side, Tail<Level>>;
|
|
82
115
|
});
|
|
116
|
+
type VariantFilters<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, Side extends 'input' | 'output', L extends readonly 1[]> = L extends readonly [] ? {} : S extends {
|
|
117
|
+
variants: infer V;
|
|
118
|
+
} ? V extends true ? {} : {
|
|
119
|
+
variant?: { [Tag in keyof V]: Tag extends Tags<Tables[T]> ? {
|
|
120
|
+
tag: Tag;
|
|
121
|
+
filters: RelationFilters<BranchTables<Tables, T, Extract<Tag, string>>, D, T, V[Tag] & Omit<S, 'variants'>, Side, Tail<L>>;
|
|
122
|
+
} : never; }[keyof V];
|
|
123
|
+
} : {};
|
|
83
124
|
type PublicRow<T extends RelationTable> = z.output<T['publicDto']> & {
|
|
84
125
|
_id: GenericId<T['tableName']>;
|
|
85
126
|
};
|
|
86
|
-
export type
|
|
127
|
+
export type ScopedRelationRow<Row, Scope extends string, Key extends PropertyKey> = [Scope] extends [never] ? Row : Extract<Row, Record<Key, Scope>>;
|
|
128
|
+
type ComposeRelationRow<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, Level extends readonly 1[], Row> = Row extends unknown ? Row & (Level extends readonly [] ? {} : { [K in keyof S]: K extends keyof Edges<D, T> ? Edges<D, T>[K] extends RelationEdge<string, infer Target, infer C, infer SourceScope, infer TargetScope> ? C extends 'one' ? ([SourceScope] extends [never] ? true : Row extends ScopedRelationRow<Row, SourceScope, Discriminator<Tables[T]>> ? true : false) extends true ? ScopedRelationRow<RelationRow<Tables, D, Extract<Target, keyof Tables>, S[K] extends true ? {} : S[K], Tail<Level>>, TargetScope, Discriminator<Tables[Extract<Target, keyof Tables>]>> | null : null : PaginationResult<ScopedRelationRow<RelationRow<Tables, D, Extract<Target, keyof Tables>, S[K] extends true ? {} : S[K], Tail<Level>>, TargetScope, Discriminator<Tables[Extract<Target, keyof Tables>]>>> : never : never; }) : never;
|
|
129
|
+
export type RelationRow<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, Level extends readonly 1[] = Depth> = ComposeRelationRow<Tables, D, T, S, Level, PublicRow<Tables[T]>>;
|
|
130
|
+
export type RelationQueryRow<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables, S, Scope extends string = never> = ScopedRelationRow<RelationRow<Tables, D, T, S>, Scope, Discriminator<Tables[T]>>;
|
|
87
131
|
export interface RelationTableHelpers<Tables extends RelationTables, D extends RelationDeclarations, T extends keyof Tables> {
|
|
88
132
|
paginationOpts<const S extends RelationFilterSelection<Tables, D, T>>(selection: ExactFilterMask<Tables, D, T, S>): PaginationOptionsSchema<RelationFilters<Tables, D, T, S>, RelationFilters<Tables, D, T, S, 'input'>>;
|
|
89
133
|
pageDto<const S extends RelationSelection<Tables, D, T>>(selection: ExactOutputMask<Tables, D, T, S>): z.ZodType<PaginationResult<RelationRow<Tables, D, T, S>>>;
|
|
@@ -106,6 +150,10 @@ export interface RelationFieldMetadata {
|
|
|
106
150
|
}
|
|
107
151
|
export interface RelationTableMetadata {
|
|
108
152
|
readonly fields: Readonly<Record<string, RelationFieldMetadata>>;
|
|
153
|
+
readonly variant?: {
|
|
154
|
+
readonly discriminator: string;
|
|
155
|
+
readonly tags: readonly string[];
|
|
156
|
+
};
|
|
109
157
|
readonly indexes: readonly {
|
|
110
158
|
readonly name: string;
|
|
111
159
|
readonly fields: readonly string[];
|
|
@@ -116,12 +164,13 @@ export interface RelationMetadata {
|
|
|
116
164
|
readonly declarations: Readonly<Record<string, Readonly<Record<string, AnyEdge>>>>;
|
|
117
165
|
}
|
|
118
166
|
/** No ID-field inference and no readers: this registry owns declarations/schema helpers only. */
|
|
119
|
-
export declare function defineRelations<const Tables extends RelationTables, const D extends RelationDeclarations>(tables: Tables, declare: (r: RelationBuilder<Tables>) => D & ExactDeclarations<Tables, D>): RelationRegistry<Tables, D>;
|
|
167
|
+
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>;
|
|
120
168
|
/** Internal owned executor bridge. Not an advertised root API. Every operation
|
|
121
169
|
* rechecks the live registry, including cached plans and individual projections.
|
|
122
170
|
*/
|
|
123
171
|
export declare function getRelationExecutor(registry: RelationRegistryIdentity): Readonly<{
|
|
124
172
|
assertUnchanged: () => void;
|
|
173
|
+
validateDocument: (table: string, row: Record<string, import('convex/values').Value>) => void;
|
|
125
174
|
assertNativeTable: (table: string, definition: TableDefinition) => void;
|
|
126
175
|
assertSchema: (tables: Readonly<Record<string, TableDefinition>>) => void;
|
|
127
176
|
pagination(table: string): z.ZodObject<{
|
package/dist/relations.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{nativePagination as e,relationFilterSchema as t,scalarPredicateSchema as n}from"./querying/filters.mjs";import{paginated as r}from"./zod-table.mjs";import{zodToConvex as i}from"convex-helpers/server/zod4";import{z as a}from"zod";import{v as o}from"convex/values";const s=Symbol(`relationField`),c=Symbol(`relationEdge`),l=/* @__PURE__ */ new WeakMap,u=/* @__PURE__ */ new WeakMap,d=/* @__PURE__ */ new WeakMap,f=/* @__PURE__ */ new WeakSet,p=/* @__PURE__ */ new WeakSet,m=a.object({indexes:a.array(a.object({indexDescriptor:a.string(),fields:a.array(a.string())}))});function h(n,o){let c={},h=/* @__PURE__ */ new Set,g={},_={},v={};for(let[e,t]of Object.entries(n)){if(t.tableName!==e||[`one`,`many`,`__proto__`,`constructor`,`prototype`].includes(e))throw Error(`Invalid relation table "${e}"`);let n=t.dto(!0);if(!(n instanceof a.ZodObject))throw Error(`Expected object DTO`);let r=I(n),o=i(t.schema),l=k(t.table);M(l.documentType),N(e,o.fields,l.documentType);let u=m.parse(l).indexes.map(e=>({name:e.indexDescriptor,fields:[...e.fields]})).sort((e,t)=>e.name.localeCompare(t.name));M(A(i(n))),c[e]={fields:o.fields,indexes:u,dto:n,assertUnchanged:r};let p=Object.create(null);for(let[t,n]of Object.entries(o.fields)){let r={[s]:void 0,table:e,field:t,through(e){let t=d.get(e);if(!h.has(e)||!t||!S(n,t))throw Error(`Invalid junction field or registry`);let i=Object.freeze({base:r,junction:e});return f.add(i),i}};d.set(r,n),h.add(r),p[t]=Object.freeze(r)}g[e]=Object.freeze(p),_[e]=t=>x(e,`one`,t,h),v[e]=t=>x(e,`many`,t,h)}let C=o(Object.freeze({...g,one:Object.freeze(_),many:Object.freeze(v)})),T=Object.fromEntries(Object.entries(C).map(([e,t])=>[e,Object.freeze({...t})]));Object.freeze(T);for(let[e,t]of Object.entries(T)){if(!Object.hasOwn(n,e))throw Error(`Unknown source table "${e}"`);for(let[n,r]of Object.entries(t)){if(Object.hasOwn(c[e].fields,n)||[`and`,`or`,`not`,`fields`,`then`,`__proto__`,`constructor`,`prototype`].includes(n))throw Error(`Relation name collision "${n}"`);if(!p.has(r)||!h.has(b(r.from))||!h.has(b(r.to))||r.source!==e)throw Error(`Relation source bucket mismatch`);w(r,c)}}let P={metadata:c,declarations:T},F={};for(let i of Object.keys(n))F[i]={paginationOpts(n){return B(P),y(n),H(e.extend({filters:t(D(P,i,n)).optional(),order:a.enum([`asc`,`desc`]).optional()}),()=>B(P))},pageDto(e){return B(P),y(e),H(r(O(P,i,e)).result,()=>B(P))}};let L=JSON.stringify([1,Object.entries(c).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Object.entries(t.fields).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.isOptional,A(t)]),t.indexes,j(A(i(t.dto)))]),Object.entries(T).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Object.entries(t).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.cardinality,t.target,E(t.from),E(t.to)])])]),R=Object.freeze({identity:L,version:1,tables:Object.freeze(F)});l.set(R,U(P));let V=Object.freeze({...n}),W=Object.fromEntries(Object.entries(V).map(([e,t])=>{let n=z(t.schema,`stored`),r=JSON.stringify(k(t.table));return[e,()=>{if(n(),JSON.stringify(k(t.table))!==r)throw Error(`Native schema mutated after registry construction: ${e}`)}]}));return u.set(R,{internal:P,tables:V,assertStoredUnchanged:()=>{for(let e of Object.values(W))e()},assertNativeTable(e,t){if(!Object.hasOwn(V,e)||V[e].table!==t)throw Error(`Native schema/table ownership disagrees with relation registry`);W[e]()}}),R}function g(i){let o=u.get(i);if(!o)throw Error(`Unknown relation registry`);let s=()=>{B(o.internal),o.assertStoredUnchanged()},c=e=>{s();let t=Object.keys(o.tables);if(t.length!==Object.keys(e).length||t.some(t=>e[t]!==o.tables[t].table))throw Error(`Native schema/table ownership disagrees with relation registry`)};return s(),Object.freeze({assertUnchanged:s,assertNativeTable:o.assertNativeTable,assertSchema:c,pagination(r){s();let i=o.internal,c=/* @__PURE__ */ new Map;function l(e,t){let r=i.metadata[e];if(!r)throw Error(`Unknown query table`);let a=c.get(e);if(!a){a={};for(let[e,t]of Object.entries(r.fields))v(t)&&(a[e]=n(t).optional());c.set(e,a)}return{fields:a,relations:t>=4?{}:Object.fromEntries(Object.entries(i.declarations[e]??{}).map(([e,n])=>[e,{cardinality:n.cardinality,target:l(n.target,t+1)}]))}}return e.extend({filters:t(l(r,0)).optional(),order:a.enum([`asc`,`desc`]).optional()})},page(e,t){return s(),y(t),r(O(o.internal,e,t)).result},project(e,t,n,r){if(c(e),!r())return null;let i=o.internal.metadata[t]?.dto;if(!i)throw Error(`Unknown query table`);return i.parse(Object.fromEntries(Object.keys(i.shape).filter(e=>Object.hasOwn(n,e)).map(e=>[e,n[e]])))}})}function _(e){let t=l.get(e);if(!t)throw Error(`Unknown relation registry`);return t}function v(e){return[`id`,`string`,`float64`,`int64`,`boolean`,`null`,`literal`].includes(e.kind)||e.kind===`union`&&e.members.every(v)}function y(e){let t=[{value:e,depth:0,ancestors:[]}],n=0;for(;t.length;){let{value:e,depth:r,ancestors:i}=t.pop();if(++n>256||r>4||i.includes(e))throw Error(`Selection cycle or depth/node budget exceeded`);let a=Object.getPrototypeOf(e);if(a!==Object.prototype&&a!==null)throw Error(`Invalid selection`);let o=Reflect.ownKeys(e);if(o.length+n+t.length>256)throw Error(`Selection node budget exceeded`);for(let a of o){let o=Object.getOwnPropertyDescriptor(e,a);if(!o.enumerable||!(`value`in o)||String(a)!==a)throw Error(`Invalid selection property`);if(o.value!==!0)t.push({value:o.value,depth:r+1,ancestors:[...i,e]});else if(++n>256)throw Error(`Selection node budget exceeded`)}}}function b(e){return`base`in e?e.base:e}function x(e,t,n,r){for(let e of[n.from,n.to])if(!r.has(b(e))||`base`in e&&(!f.has(e)||!r.has(e.junction)))throw Error(`Foreign registry or invalid field reference`);if(b(n.to).table!==e)throw Error(`Wrong relation target table`);let i=Object.freeze({[c]:!0,source:b(n.from).table,target:e,cardinality:t,from:n.from,to:n.to});return p.add(i),i}function S(e,t){let n=C(e);return n.length>0&&JSON.stringify(n)===JSON.stringify(C(t))}function C(e){if(e.kind===`union`)return[...new Set(e.members.flatMap(C))].sort();if(e.kind===`null`)return[];if(![`id`,`string`,`float64`,`int64`,`boolean`,`literal`].includes(e.kind))throw Error(`Unsupported relation field kind`);return[JSON.stringify(A(e))]}function w(e,t){let n=e.from,r=e.to;if(`base`in n!=`base`in r)throw Error(`Both relation legs must use through`);if(`base`in n&&`base`in r){if(n.junction.table!==r.junction.table)throw Error(`Different junction tables`);T(t,n.junction.table,n.junction.field),T(t,e.target,r.base.field);return}if(!S(d.get(b(n)),d.get(b(r))))throw Error(`Incompatible relation field types`);T(t,e.target,b(r).field)}function T(e,t,n){if(n!==`_id`&&!e[t].indexes.some(e=>e.fields[0]===n))throw Error(`No active index begins with "${t}.${n}"`)}function E(e){return`base`in e?[e.base.table,e.base.field,e.junction.table,e.junction.field]:[e.table,e.field]}function D(e,t,r,i=0){let a={},o={};for(let[s,c]of Object.entries(r)){let r=e.metadata[t].fields[s],l=e.declarations[t]?.[s];if(c===!0&&r)a[s]=n(r).optional();else if(c!==!0&&l&&i<4)o[s]={cardinality:l.cardinality,target:D(e,l.target,c,i+1)};else throw Error(`Invalid relation filter selection "${t}.${s}"`)}return{fields:a,relations:o}}function O(e,t,n,i=0){let o={};for(let[a,s]of Object.entries(n)){let n=e.declarations[t]?.[a];if(!n||i>=4)throw Error(`Unknown or too deep relation "${t}.${a}"`);let c=s===!0?e.metadata[n.target].dto:O(e,n.target,s,i+1);o[a]=n.cardinality===`one`?c.nullable():r(c).result}let s=e.metadata[t].dto;if(!(s instanceof a.ZodObject))throw Error(`Expected object DTO`);return H(s.extend(o).strict(),()=>B(e))}function k(e){return e.export()}function A(e){return e.json}function j(e){if(Array.isArray(e))return`[${e.map(j).join(`,`)}]`;if(e!==null&&Object(e)===e){let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${j(t[e])}`).join(`,`)}}`}return JSON.stringify(e)}function M(e){if(e===null||Object(e)!==e)return;let t=e;if(t.type===`any`)throw Error(`Unsupported native validation form`);for(let e of Object.values(t))M(e)}function N(e,t,n){let{_id:r,_creationTime:i,...a}=t;if(!r||!i||j(A(r))!==j(A(o.id(e)))||j(A(i))!==j(A(o.number()))||r.isOptional!==`required`||i.isOptional!==`required`||j(n)!==j(A(o.object(a))))throw Error(`Native stored document disagrees with boundary "${e}"`)}const P=a.object({field:a.string()}),F=new Set([P,P.pick({field:!0}),P.omit({field:!0}),P.extend({other:a.string()}),P.safeExtend({other:a.string()}),P.merge(a.object({other:a.string()})),P.partial(),P.required()].flatMap(e=>{let t=Object.getOwnPropertyDescriptor(e._zod.def,`shape`)?.get;return t?[Function.prototype.toString.call(t)]:[]}));function I(e){return z(e,`dto`)}const L=Function.prototype.toString.call(Object.getOwnPropertyDescriptor(a.string().default(``)._zod.def,`defaultValue`).get),R=Function.prototype.toString.call(Object.getOwnPropertyDescriptor(a.string().prefault(``)._zod.def,`defaultValue`).get);function z(e,t){let n=[],r=/* @__PURE__ */ new Set,i=[],o=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new Set,c=[];function l(e,u){if(s.has(e))throw Error(`Unsupported cyclic DTO schema`);if(!o.has(e)){if(u>32||n.length>=4096)throw Error(`DTO schema graph budget exceeded`);o.add(e),s.add(e);try{if(e instanceof RegExp&&i.push({expression:e,source:e.source,flags:e.flags}),e instanceof a.core.$ZodCheck&&`check`in e._zod.def){if(t===`dto`&&e._zod.def.check===`overwrite`)throw Error(`Unsupported DTO overwrite check`);l(e._zod.def,u+1),n.push({object:e._zod,exactKeys:!1,keys:[`def`,`check`],values:[`def`,`check`].map(t=>Object.getOwnPropertyDescriptor(e._zod,t))});return}if(e instanceof a.core.$ZodType){let i=e._zod.def;if(t===`dto`&&(![`object`,`array`,`optional`,`nullable`,`nonoptional`,`union`,`intersection`,`tuple`,`record`,`string`,`number`,`boolean`,`bigint`,`null`,`never`,`literal`,`enum`].includes(i.type)||`coerce`in i&&i.coerce))throw Error(`Unsupported DTO schema "${i.type}"`);if(t===`stored`&&(i.type==="default"||i.type===`prefault`)){let e=Object.getOwnPropertyDescriptor(i,`defaultValue`);if(e?.get){if(e.set||Function.prototype.toString.call(e.get)!==(i.type==="default"?L:R))throw Error(`Unsupported stored schema accessor`);r.add(i)}}if(i.type===`object`){let t=Object.getOwnPropertyDescriptor(i,`shape`);if(t?.get){if(t.set||!F.has(Function.prototype.toString.call(t.get)))throw Error(`Unsupported DTO schema accessor`);let e=i.shape;l(e,u+1),Object.getOwnPropertyDescriptor(i,`shape`)?.get&&c.push({definition:i,fields:e})}if(e instanceof a.ZodObject){let t=Object.getOwnPropertyDescriptor(e,`shape`);if(t&&!(`value`in t))throw Error(`Unsupported DTO schema accessor`);l(e.shape,u+1)}}l(i,u+1),n.push({object:e._zod,exactKeys:!1,keys:[`def`],values:[Object.getOwnPropertyDescriptor(e._zod,`def`)]});return}let o=Reflect.ownKeys(e),s=o.map(t=>Object.getOwnPropertyDescriptor(e,t));if(s.some((t,n)=>!(`value`in t)&&!c.some(({definition:t})=>t===e&&o[n]===`shape`)&&!(r.has(e)&&o[n]===`defaultValue`)))throw Error(`Unsupported DTO schema accessor`);n.push({object:e,exactKeys:!0,keys:o,values:s});for(let e of s)e.value!==null&&Object(e.value)===e.value&&!(e.value instanceof Function)&&l(e.value,u+1)}finally{s.delete(e)}}}return l(e,0),()=>{for(let e of i)if(e.expression.source!==e.source||e.expression.flags!==e.flags)throw Error(`DTO schema mutated after registry construction`);for(let e of n){let t=e.keys;if(e.exactKeys&&Reflect.ownKeys(e.object).length!==t.length)throw Error(`DTO schema mutated after registry construction`);for(let n=0;n<t.length;n++){if(e.object instanceof RegExp&&t[n]===`lastIndex`)continue;let r=Object.getOwnPropertyDescriptor(e.object,t[n]),i=e.values[n];if(!r||r.value!==i.value||r.get!==i.get||r.set!==i.set||r.enumerable!==i.enumerable)throw Error(`DTO schema mutated after registry construction`)}}for(let{definition:e,fields:t}of c){let n=e.shape,r=Reflect.ownKeys(t);if(Reflect.ownKeys(n).length!==r.length||r.some(e=>Object.getOwnPropertyDescriptor(n,e)?.value!==Object.getOwnPropertyDescriptor(t,e)?.value))throw Error(`DTO schema mutated after registry construction`)}}}function B(e){for(let t of Object.values(e.metadata))t.assertUnchanged()}const V=a.core.$constructor(`GuardedDtoObject`,(e,t)=>{let n=t;a.ZodObject.init(e,t),e._zod.deferred??=[],e._zod.deferred.push(()=>{let t=e._zod.run;e._zod.run=(e,r)=>{try{n.assertUnchanged()}catch{return e.issues.push({code:`custom`,input:e.value,message:`DTO schema mutated after registry construction`}),e}return t(e,r)}})});function H(e,t){let n=e.shape,r={...e._zod.def,assertUnchanged:t};return Object.defineProperty(r,"shape",{enumerable:!0,configurable:!0,get:()=>(t(),n)}),new V(r)}function U(e){let t={};for(let[n,r]of Object.entries(e.metadata)){let e={};for(let[t,n]of Object.entries(r.fields))e[t]=Object.freeze({kind:n.kind,optional:n.isOptional===`optional`,nullable:W(n),idTables:Object.freeze(G(n)),native:K(A(n))});t[n]=Object.freeze({fields:Object.freeze(e),indexes:Object.freeze(r.indexes.map(e=>Object.freeze({name:e.name,fields:Object.freeze([...e.fields])})))})}return Object.freeze({tables:Object.freeze(t),declarations:e.declarations})}function W(e){return e.kind===`null`||e.kind===`union`&&e.members.some(W)}function G(e){return e.kind===`id`?[e.tableName]:e.kind===`union`?[...new Set(e.members.flatMap(G))].sort():[]}function K(e){let t=structuredClone(e),n=[t];for(;n.length;){let e=n.pop();if(Object(e)!==e)continue;let t=e;Object.freeze(t),n.push(...Object.values(t))}return t}export{h as defineRelations,g as getRelationExecutor,_ as getRelationMetadata};
|
|
1
|
+
import{nativePagination as e,relationFilterSchema as t,scalarPredicateSchema as n}from"./querying/filters.mjs";import{paginated as r}from"./zod-table.mjs";import{convexToZod as i,zodToConvex as a}from"convex-helpers/server/zod4";import{z as o}from"zod";import{v as s}from"convex/values";const c=Symbol(`relationField`),l=Symbol(`relationEdge`),u=/* @__PURE__ */ new WeakMap,d=/* @__PURE__ */ new WeakMap,f=/* @__PURE__ */ new WeakMap,p=/* @__PURE__ */ new WeakSet,m=/* @__PURE__ */ new WeakSet,h=o.object({indexes:o.array(o.object({indexDescriptor:o.string(),fields:o.array(o.string())}))});function g(n,i){let s={},l=/* @__PURE__ */ new Set,g=/* @__PURE__ */ new Map,_={},v={},y={};for(let[e,t]of Object.entries(n)){if(t.tableName!==e||[`one`,`many`,`__proto__`,`constructor`,`prototype`].includes(e))throw Error(`Invalid relation table "${e}"`);let n=t.dto(!0);if(!(n instanceof o.ZodObject)&&!(n instanceof o.ZodDiscriminatedUnion))throw Error(`Expected object or discriminated union DTO`);let r=B(n),i=N(t.table);I(i.documentType);let u=j(e,t.schema,n,i.documentType),d=h.parse(i).indexes.map(e=>({name:e.indexDescriptor,fields:[...e.fields]})).sort((e,t)=>e.name.localeCompare(t.name));I(P(a(n))),s[e]={...u,indexes:d,dto:n,assertUnchanged:r};let m=(t,n)=>{let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t={[c]:void 0,table:e,field:i,guard:n,through(e){let n=f.get(e);if(!l.has(e)||!n||!w(a,n))throw Error(`Invalid junction field or registry`);let r=Object.freeze({base:t,junction:e});return p.add(r),r}};f.set(t,a),l.add(t),r[i]=Object.freeze(t)}return Object.freeze(r)};if(_[e]=m(u.fields),u.branches)for(let[t,n]of Object.entries(u.branches.options))g.set(JSON.stringify([e,t]),m(n.fields,Object.freeze({discriminator:u.branches.discriminator,tag:t})));v[e]=t=>S(e,`one`,t,l),y[e]=t=>S(e,`many`,t,l)}let C=i(Object.freeze({..._,one:Object.freeze(v),many:Object.freeze(y)}),((e,t)=>{let n=g.get(JSON.stringify([e,t]));if(!n)throw Error(`Unknown variant scope "${e}.${t}"`);return n})),T=Object.fromEntries(Object.entries(C).map(([e,t])=>[e,Object.freeze({...t})]));Object.freeze(T);for(let[e,t]of Object.entries(T)){if(!Object.hasOwn(n,e))throw Error(`Unknown source table "${e}"`);for(let[n,r]of Object.entries(t)){if(s[e].allFields.has(n)||s[e].branches&&[`variant`,`variants`].includes(n)||[`and`,`or`,`not`,`fields`,`then`,`__proto__`,`constructor`,`prototype`].includes(n))throw Error(`Relation name collision "${n}"`);if(!m.has(r)||!l.has(x(r.from))||!l.has(x(r.to))||r.source!==e)throw Error(`Relation source bucket mismatch`);E(r,s)}}let D={metadata:s,declarations:T},M={};for(let i of Object.keys(n))M[i]={paginationOpts(n){return W(D),b(n),K(e.extend({filters:t(k(D,i,n)).optional(),order:o.enum([`asc`,`desc`]).optional()}),()=>W(D))},pageDto(e){return W(D),b(e),K(r(A(D,i,e)).result,()=>W(D))}};let L=JSON.stringify([2,Object.entries(s).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Object.entries(t.fields).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.isOptional,P(t)]),t.branches?[t.branches.discriminator,Object.entries(t.branches.options).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Object.entries(t.fields).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.isOptional,P(t)])])]:null,t.indexes,F(P(a(t.dto)))]),Object.entries(T).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Object.entries(t).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.cardinality,t.target,O(t.from),O(t.to)])])]),R=Object.freeze({identity:L,version:1,tables:Object.freeze(M)});u.set(R,Y(D));let z=Object.freeze({...n}),V=Object.fromEntries(Object.entries(z).map(([e,t])=>{let n=U(t.schema,`stored`),r=U(t.publicDto,`dto`),i=t.table.validator,a=i.isOptional,o=JSON.stringify(N(t.table));return[e,()=>{if(n(),r(),t.table.validator!==i||i.isOptional!==a||JSON.stringify(N(t.table))!==o)throw Error(`Native schema mutated after registry construction: ${e}`)}]}));for(let[e,t]of Object.entries(s)){if(!t.branches)continue;let n=t.assertUnchanged;t.assertUnchanged=()=>{n(),V[e]()}}return d.set(R,{internal:D,tables:z,assertStoredUnchanged:()=>{for(let e of Object.values(V))e()},assertNativeTable(e,t){if(!Object.hasOwn(z,e)||z[e].table!==t)throw Error(`Native schema/table ownership disagrees with relation registry`);V[e]()}}),R}function _(a){let c=d.get(a);if(!c)throw Error(`Unknown relation registry`);let l=()=>{W(c.internal),c.assertStoredUnchanged()},u=e=>{l();let t=Object.keys(c.tables);if(t.length!==Object.keys(e).length||t.some(t=>e[t]!==c.tables[t].table))throw Error(`Native schema/table ownership disagrees with relation registry`)};l();let f=/* @__PURE__ */ new WeakMap;function p(e,t){l();let n=c.internal.metadata[e];if(!n)throw Error(`Unknown query table`);if(!n.branches)return;let r=o.string().safeParse(t[n.branches.discriminator]),a=r.success&&Object.hasOwn(n.branches.options,r.data)?n.branches.options[r.data]:void 0;if(!a)throw Error(`Invalid variant document`);let u=Object.fromEntries(Object.keys(a.fields).filter(e=>Object.hasOwn(t,e)).map(e=>[e,t[e]])),d=f.get(a);d||(d=i(s.object(a.fields)),f.set(a,d)),d.parse(u)}return Object.freeze({assertUnchanged:l,validateDocument:p,assertNativeTable:c.assertNativeTable,assertSchema:u,pagination(r){l();let i=c.internal,a=/* @__PURE__ */ new Map;function s(e,t,r){let o=i.metadata[e];if(!o)throw Error(`Unknown query table`);let c=JSON.stringify([e,r??null]),l=a.get(c);if(!l){l={};for(let[e,t]of Object.entries(r===void 0?o.fields:o.branches.options[r].fields))y(t)&&(l[e]=n(t).optional());a.set(c,l)}return{fields:l,variants:o.branches&&r===void 0&&t<4?{discriminator:o.branches.discriminator,options:Object.fromEntries(Object.keys(o.branches.options).map(n=>[n,s(e,t+1,n)]))}:void 0,relations:t>=4?{}:Object.fromEntries(Object.entries(i.declarations[e]??{}).map(([e,n])=>[e,{cardinality:n.cardinality,target:s(n.target,t+1)}]))}}return e.extend({filters:t(s(r,0)).optional(),order:o.enum([`asc`,`desc`]).optional()})},page(e,t){return l(),b(t),r(A(c.internal,e,t)).result},project(e,t,n,r){if(u(e),!r())return null;let i=c.internal.metadata[t];if(!i)throw Error(`Unknown query table`);let a=i.branches?i.branches.options[String(n[i.branches.discriminator])]:void 0;if(i.branches&&!a)throw Error(`Invalid variant document`);let s=a?.dto??i.dto;if(!(s instanceof o.ZodObject))throw Error(`Invalid variant DTO`);return p(t,n),s.parse(Object.fromEntries(Object.keys(s.shape).filter(e=>Object.hasOwn(n,e)).map(e=>[e,n[e]])))}})}function v(e){let t=u.get(e);if(!t)throw Error(`Unknown relation registry`);return t}function y(e){return[`id`,`string`,`float64`,`int64`,`boolean`,`null`,`literal`].includes(e.kind)||e.kind===`union`&&e.members.every(y)}function b(e){let t=[{value:e,depth:0,ancestors:[]}],n=0;for(;t.length;){let{value:e,depth:r,ancestors:i}=t.pop();if(++n>256||r>4||i.includes(e))throw Error(`Selection cycle or depth/node budget exceeded`);let a=Object.getPrototypeOf(e);if(a!==Object.prototype&&a!==null)throw Error(`Invalid selection`);let o=Reflect.ownKeys(e);if(o.length+n+t.length>256)throw Error(`Selection node budget exceeded`);for(let a of o){let o=Object.getOwnPropertyDescriptor(e,a);if(!o.enumerable||!(`value`in o)||String(a)!==a)throw Error(`Invalid selection property`);if(o.value!==!0)t.push({value:o.value,depth:r+1,ancestors:[...i,e]});else if(++n>256)throw Error(`Selection node budget exceeded`)}}}function x(e){return`base`in e?e.base:e}function S(e,t,n,r){for(let e of[n.from,n.to])if(!r.has(x(e))||`base`in e&&(!p.has(e)||!r.has(e.junction)))throw Error(`Foreign registry or invalid field reference`);if(x(n.to).table!==e)throw Error(`Wrong relation target table`);let i=Object.freeze({[l]:!0,source:x(n.from).table,target:e,cardinality:t,from:n.from,to:n.to,sourceGuard:x(n.from).guard,targetGuard:x(n.to).guard,junctionGuard:C(n.from,n.to)});return m.add(i),i}function C(e,t){let n=`base`in e?e.junction.guard:void 0,r=`base`in t?t.junction.guard:void 0;if(n&&r&&(n.discriminator!==r.discriminator||n.tag!==r.tag))throw Error(`Contradictory junction scopes`);return n??r}function w(e,t){let n=T(e);return n.length>0&&JSON.stringify(n)===JSON.stringify(T(t))}function T(e){if(e.kind===`union`)return[...new Set(e.members.flatMap(T))].sort();if(e.kind===`null`)return[];if(![`id`,`string`,`float64`,`int64`,`boolean`,`literal`].includes(e.kind))throw Error(`Unsupported relation field kind`);return[JSON.stringify(P(e))]}function E(e,t){let n=e.from,r=e.to;if(`base`in n!=`base`in r)throw Error(`Both relation legs must use through`);if(`base`in n&&`base`in r){if(n.junction.table!==r.junction.table)throw Error(`Different junction tables`);D(t,n.junction.table,n.junction.field,e.junctionGuard),D(t,e.target,r.base.field,e.targetGuard);return}if(!w(f.get(x(n)),f.get(x(r))))throw Error(`Incompatible relation field types`);D(t,e.target,x(r).field,e.targetGuard)}function D(e,t,n,r){if(n!==`_id`&&!e[t].indexes.some(e=>{let t=e.fields.indexOf(n);return t>=0&&e.fields.slice(0,t).every(e=>e===r?.discriminator)}))throw Error(`No active index begins with or has a guarded prefix for "${t}.${n}"`)}function O(e){return`base`in e?[e.base.table,e.base.field,e.base.guard??null,e.junction.table,e.junction.field,e.junction.guard??null]:[e.table,e.field,e.guard??null]}function k(e,t,r,i=0,a){let o={},s={},c=e.metadata[t],l={};for(let[u,d]of Object.entries(r)){if(u===`variants`&&d!==!0&&c.branches&&a===void 0){if(i>=4)throw Error(`Invalid variant selection`);for(let[n,a]of Object.entries(d)){if(!Object.hasOwn(c.branches.options,n)||a===!0)throw Error(`Unknown variant filter selection`);l[n]=k(e,t,{...Object.fromEntries(Object.entries(r).filter(([e])=>e!==`variants`)),...a},i+1,n)}continue}let f=(a===void 0?c.fields:c.branches.options[a].fields)[u],p=e.declarations[t]?.[u];if(d===!0&&f)o[u]=n(f).optional();else if(d!==!0&&p&&i<4)s[u]={cardinality:p.cardinality,target:k(e,p.target,d,i+1)};else throw Error(`Invalid relation filter selection "${t}.${u}"`)}return{fields:o,relations:s,variants:c.branches&&a===void 0?{discriminator:c.branches.discriminator,options:l}:void 0}}function A(e,t,n,i=0){let a={};for(let[s,c]of Object.entries(n)){let n=e.declarations[t]?.[s];if(!n||i>=4)throw Error(`Unknown or too deep relation "${t}.${s}"`);let l=c===!0?e.metadata[n.target].dto:A(e,n.target,c,i+1);if(n.targetGuard){if(!(l instanceof o.ZodDiscriminatedUnion))throw Error(`Invalid target scope`);l=l.options.find(e=>e.shape[n.targetGuard.discriminator]instanceof o.ZodLiteral&&e.shape[n.targetGuard.discriminator].value===n.targetGuard.tag)}a[s]=n.cardinality===`one`?l.nullable():r(l).result}let s=e.metadata[t];function c(n,r){let i={...a};for(let n of Object.keys(i)){let a=e.declarations[t][n];a.sourceGuard&&r!==a.sourceGuard.tag&&a.cardinality===`one`&&(i[n]=o.null())}return K(n.extend(i).strict(),()=>W(e))}if(s.branches){let t=Object.entries(s.branches.options).map(([e,t])=>c(t.dto,e));return J(o.discriminatedUnion(s.branches.discriminator,[t[0],...t.slice(1)]),()=>W(e))}if(!(s.dto instanceof o.ZodObject))throw Error(`Expected object DTO`);return c(s.dto)}function j(e,t,n,r){if(t instanceof o.ZodObject&&n instanceof o.ZodObject){let n=a(t).fields;return L(e,n,r),{fields:n,allFields:new Set(Object.keys(n))}}if(!(t instanceof o.ZodDiscriminatedUnion)||!(n instanceof o.ZodDiscriminatedUnion))throw Error(`Expected matching discriminated union boundaries "${e}"`);let i=t._zod.def.discriminator;if(n._zod.def.discriminator!==i)throw Error(`DTO discriminator mismatch`);function c(e){let t=Object.create(null);for(let n of e.options){if(!(n instanceof o.ZodObject))throw Error(`Variant branches must be objects`);let e=n.shape[i];if(!(e instanceof o.ZodLiteral)||e.values.size!==1)throw Error(`Variant tags must be unique required string literals`);let r=o.string().safeParse(e.value);if(!r.success||Object.hasOwn(t,r.data))throw Error(`Variant tags must be unique required string literals`);t[r.data]=n}if(Object.keys(t).length===0)throw Error(`Expected at least one variant branch`);return t}let l=c(t),u=c(n);if(Object.keys(l).sort().join(`\0`)!==Object.keys(u).sort().join(`\0`))throw Error(`DTO variant tags mismatch`);let d={discriminator:i,options:Object.create(null)},f=[];for(let[t,n]of Object.entries(l)){let r=a(n).fields,{_id:i,_creationTime:o,...c}=r;L(e,r,P(s.object(c))),f.push(s.object(c)),d.options[t]={fields:r,dto:u[t]}}if(F(r)!==F(P(s.union(...f))))throw Error(`Native stored document disagrees with boundary "${e}"`);let p=Object.values(d.options).map(e=>e.fields),m={};for(let e of Object.keys(p[0])){if(!p.every(t=>Object.hasOwn(t,e))||e!==i&&!p.every(t=>M(t[e],p[0][e])))continue;let t=p.map(t=>t[e]),n=s.union(...t);m[e]=t.some(e=>e.isOptional===`optional`)?s.optional(n):n}return{fields:m,branches:d,allFields:new Set(p.flatMap(e=>Object.keys(e)))}}function M(e,t){try{return w(e,t)}catch{return F(P(e))===F(P(t))}}function N(e){return e.export()}function P(e){return e.json}function F(e){if(Array.isArray(e))return`[${e.map(F).join(`,`)}]`;if(e!==null&&Object(e)===e){let t=e;return`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${F(t[e])}`).join(`,`)}}`}return JSON.stringify(e)}function I(e){if(e===null||Object(e)!==e)return;let t=e;if(t.type===`any`)throw Error(`Unsupported native validation form`);for(let e of Object.values(t))I(e)}function L(e,t,n){let{_id:r,_creationTime:i,...a}=t;if(!r||!i||F(P(r))!==F(P(s.id(e)))||F(P(i))!==F(P(s.number()))||r.isOptional!==`required`||i.isOptional!==`required`||F(n)!==F(P(s.object(a))))throw Error(`Native stored document disagrees with boundary "${e}"`)}const R=o.object({field:o.string()}),z=new Set([R,R.pick({field:!0}),R.omit({field:!0}),R.extend({other:o.string()}),R.safeExtend({other:o.string()}),R.merge(o.object({other:o.string()})),R.partial(),R.required()].flatMap(e=>{let t=Object.getOwnPropertyDescriptor(e._zod.def,`shape`)?.get;return t?[Function.prototype.toString.call(t)]:[]}));function B(e){return U(e,`dto`)}const V=Function.prototype.toString.call(Object.getOwnPropertyDescriptor(o.string().default(``)._zod.def,`defaultValue`).get),H=Function.prototype.toString.call(Object.getOwnPropertyDescriptor(o.string().prefault(``)._zod.def,`defaultValue`).get);function U(e,t){let n=[],r=/* @__PURE__ */ new Set,i=[],a=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new Set,c=[];function l(e,u){if(s.has(e))throw Error(`Unsupported cyclic DTO schema`);if(!a.has(e)){if(u>32||n.length>=4096)throw Error(`DTO schema graph budget exceeded`);a.add(e),s.add(e);try{if(e instanceof RegExp&&i.push({expression:e,source:e.source,flags:e.flags}),e instanceof o.core.$ZodCheck&&`check`in e._zod.def){if(t===`dto`&&e._zod.def.check===`overwrite`)throw Error(`Unsupported DTO overwrite check`);l(e._zod.def,u+1),n.push({object:e._zod,exactKeys:!1,keys:[`def`,`check`],values:[`def`,`check`].map(t=>Object.getOwnPropertyDescriptor(e._zod,t))});return}if(e instanceof o.core.$ZodType){let i=e._zod.def;if(t===`dto`&&(![`object`,`array`,`optional`,`nullable`,`nonoptional`,`union`,`intersection`,`tuple`,`record`,`string`,`number`,`boolean`,`bigint`,`null`,`never`,`literal`,`enum`].includes(i.type)||`coerce`in i&&i.coerce))throw Error(`Unsupported DTO schema "${i.type}"`);if(t===`stored`&&(i.type==="default"||i.type===`prefault`)){let e=Object.getOwnPropertyDescriptor(i,`defaultValue`);if(e?.get){if(e.set||Function.prototype.toString.call(e.get)!==(i.type==="default"?V:H))throw Error(`Unsupported stored schema accessor`);r.add(i)}}if(e instanceof o.ZodUnion&&(l(e.options,u+1),n.push({object:e,exactKeys:!1,keys:[`options`],values:[Object.getOwnPropertyDescriptor(e,`options`)]})),i.type===`object`){let t=Object.getOwnPropertyDescriptor(i,`shape`);if(t?.get){if(t.set||!z.has(Function.prototype.toString.call(t.get)))throw Error(`Unsupported DTO schema accessor`);let e=i.shape;l(e,u+1),Object.getOwnPropertyDescriptor(i,`shape`)?.get&&c.push({definition:i,fields:e})}if(e instanceof o.ZodObject){let t=Object.getOwnPropertyDescriptor(e,`shape`);if(t&&!(`value`in t))throw Error(`Unsupported DTO schema accessor`);l(e.shape,u+1)}}l(i,u+1),n.push({object:e._zod,exactKeys:!1,keys:[`def`],values:[Object.getOwnPropertyDescriptor(e._zod,`def`)]});return}let a=Reflect.ownKeys(e),s=a.map(t=>Object.getOwnPropertyDescriptor(e,t));if(s.some((t,n)=>!(`value`in t)&&!c.some(({definition:t})=>t===e&&a[n]===`shape`)&&!(r.has(e)&&a[n]===`defaultValue`)))throw Error(`Unsupported DTO schema accessor`);n.push({object:e,exactKeys:!0,keys:a,values:s});for(let e of s)e.value!==null&&Object(e.value)===e.value&&!(e.value instanceof Function)&&l(e.value,u+1)}finally{s.delete(e)}}}return l(e,0),()=>{for(let e of i)if(e.expression.source!==e.source||e.expression.flags!==e.flags)throw Error(`DTO schema mutated after registry construction`);for(let e of n){let t=e.keys;if(e.exactKeys&&Reflect.ownKeys(e.object).length!==t.length)throw Error(`DTO schema mutated after registry construction`);for(let n=0;n<t.length;n++){if(e.object instanceof RegExp&&t[n]===`lastIndex`)continue;let r=Object.getOwnPropertyDescriptor(e.object,t[n]),i=e.values[n];if(!r||r.value!==i.value||r.get!==i.get||r.set!==i.set||r.enumerable!==i.enumerable)throw Error(`DTO schema mutated after registry construction`)}}for(let{definition:e,fields:t}of c){let n=e.shape,r=Reflect.ownKeys(t);if(Reflect.ownKeys(n).length!==r.length||r.some(e=>Object.getOwnPropertyDescriptor(n,e)?.value!==Object.getOwnPropertyDescriptor(t,e)?.value))throw Error(`DTO schema mutated after registry construction`)}}}function W(e){for(let t of Object.values(e.metadata))t.assertUnchanged()}const G=o.core.$constructor(`GuardedDtoObject`,(e,t)=>{let n=t;o.ZodObject.init(e,t),e._zod.deferred??=[],e._zod.deferred.push(()=>{let t=e._zod.run;e._zod.run=(e,r)=>{try{n.assertUnchanged()}catch{return e.issues.push({code:`custom`,input:e.value,message:`DTO schema mutated after registry construction`}),e}return t(e,r)}})});function K(e,t){let n=e.shape,r={...e._zod.def,assertUnchanged:t};return Object.defineProperty(r,"shape",{enumerable:!0,configurable:!0,get:()=>(t(),n)}),new G(r)}const q=o.core.$constructor(`GuardedDtoUnion`,(e,t)=>{let n=t;o.ZodDiscriminatedUnion.init(e,t),e._zod.deferred??=[],e._zod.deferred.push(()=>{let t=e._zod.run;e._zod.run=(e,r)=>{try{n.assertUnchanged()}catch{return e.issues.push({code:`custom`,input:e.value,message:`DTO schema mutated after registry construction`}),e}return t(e,r)}})});function J(e,t){let n=e.options,r={...e._zod.def,assertUnchanged:t};return Object.defineProperty(r,"options",{enumerable:!0,configurable:!0,get:()=>(t(),n)}),new q(r)}function Y(e){let t={};for(let[n,r]of Object.entries(e.metadata)){let e={};for(let[t,n]of Object.entries(r.fields))e[t]=Object.freeze({kind:n.kind,optional:n.isOptional===`optional`,nullable:X(n),idTables:Object.freeze(Z(n)),native:Q(P(n))});t[n]=Object.freeze({fields:Object.freeze(e),variant:r.branches?Object.freeze({discriminator:r.branches.discriminator,tags:Object.freeze(Object.keys(r.branches.options))}):void 0,indexes:Object.freeze(r.indexes.map(e=>Object.freeze({name:e.name,fields:Object.freeze([...e.fields])})))})}return Object.freeze({tables:Object.freeze(t),declarations:e.declarations})}function X(e){return e.kind===`null`||e.kind===`union`&&e.members.some(X)}function Z(e){return e.kind===`id`?[e.tableName]:e.kind===`union`?[...new Set(e.members.flatMap(Z))].sort():[]}function Q(e){let t=structuredClone(e),n=[t];for(;n.length;){let e=n.pop();if(Object(e)!==e)continue;let t=e;Object.freeze(t),n.push(...Object.values(t))}return t}export{g as defineRelations,_ as getRelationExecutor,v as getRelationMetadata};
|
|
2
2
|
//# sourceMappingURL=relations.mjs.map
|