cvx-kit 0.1.23 → 0.1.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -5
- package/dist/auth.d.mts +6 -2
- package/dist/auth.mjs +1 -1
- package/dist/auth.mjs.map +1 -1
- package/dist/querying/planner.d.mts +18 -1
- package/dist/querying/planner.mjs +1 -1
- package/dist/querying/planner.mjs.map +1 -1
- package/dist/querying/relationships.mjs +1 -1
- package/dist/querying/relationships.mjs.map +1 -1
- package/dist/querying/schema-snapshot.d.mts +18 -0
- package/dist/querying/schema-snapshot.mjs +1 -1
- package/dist/querying/schema-snapshot.mjs.map +1 -1
- package/dist/querying/shared/filters.d.mts +7 -0
- package/dist/querying/shared/filters.mjs +1 -1
- package/dist/querying/shared/filters.mjs.map +1 -1
- package/dist/querying.mjs +1 -1
- package/dist/querying.mjs.map +1 -1
- package/dist/relations-public.d.mts +2 -2
- package/dist/relations-public.mjs +1 -1
- package/dist/relations.d.mts +9 -2
- package/dist/relations.mjs +1 -1
- package/dist/relations.mjs.map +1 -1
- package/dist/zod-registration.mjs +1 -1
- package/dist/zod-registration.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -156,11 +156,26 @@ public DTO or `null`. A many edge returns a bounded native page. Junction output
|
|
|
156
156
|
preserves duplicate edge occurrences, even when target reads are memoized.
|
|
157
157
|
Missing and unreadable targets have the same public result.
|
|
158
158
|
|
|
159
|
-
`defineRelations`
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
159
|
+
`defineRelations` checks table names, native table ownership and the structure
|
|
160
|
+
of relation declarations. Variant tables also run their native table preflight
|
|
161
|
+
then, to expose common-field references. It captures each table's stored field semantics,
|
|
162
|
+
public DTO validation, variants and active indexes on that table's first use:
|
|
163
|
+
its schema helpers, an engine read, or a selected relation that reaches it. Each
|
|
164
|
+
edge's field types and indexes are checked when the edge is first read. Invalid
|
|
165
|
+
tables and edges throw on first use instead of at registration. Complete schema
|
|
166
|
+
and index configuration before calling `defineRelations`. Later changes to
|
|
167
|
+
source declarations do not affect a table after its first use. Create a new
|
|
168
|
+
registry to adopt changes. Caller-owned declarations remain mutable.
|
|
169
|
+
|
|
170
|
+
Call `verifyRelations(relations)` from a test to run every deferred check, so CI
|
|
171
|
+
fails on an invalid registry:
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
import { verifyRelations } from 'cvx-kit/relations'
|
|
175
|
+
import { relations } from '../convex/relations'
|
|
176
|
+
|
|
177
|
+
test('relation registry is valid', () => verifyRelations(relations))
|
|
178
|
+
```
|
|
164
179
|
|
|
165
180
|
Relation DTOs support `.refine()`. They reject opaque `.superRefine()` and
|
|
166
181
|
`.check()` callbacks; express those validations with `.refine()` instead.
|
|
@@ -192,6 +207,11 @@ output, index, order, relation ancestry, principal/tenant/security scope, and
|
|
|
192
207
|
registry/policy/engine versions. Page-size changes alone remain valid. Retain
|
|
193
208
|
old keys during rotation when existing cursors should continue working.
|
|
194
209
|
|
|
210
|
+
Relation registration captures and validates schemas eagerly; eligible private
|
|
211
|
+
DTO schemas reconstruct on first projection. Public helper schemas stay fresh.
|
|
212
|
+
See [registry capture and compatibility](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/querying.md#registry-capture-and-private-dtos)
|
|
213
|
+
for eager fallback and the unsupported side-effecting internal Proxy boundary.
|
|
214
|
+
|
|
195
215
|
Use the registry's validators in domain contracts and an authenticated Query
|
|
196
216
|
registry handler:
|
|
197
217
|
|
package/dist/auth.d.mts
CHANGED
|
@@ -64,8 +64,12 @@ export type AuthFunctionsConfig<DataModel extends GenericDataModel, Role extends
|
|
|
64
64
|
internalQuery: QueryBuilder<DataModel, 'internal'>;
|
|
65
65
|
internalMutation: MutationBuilder<DataModel, 'internal'>;
|
|
66
66
|
internalAction: ActionBuilder<DataModel, 'internal'>;
|
|
67
|
-
/**
|
|
68
|
-
|
|
67
|
+
/**
|
|
68
|
+
* Resolves the synchronized principal, e.g. (ctx) => authKit.getAuthUser(ctx).
|
|
69
|
+
* The already-resolved, non-null identity is supplied as a second argument.
|
|
70
|
+
* Callbacks may ignore it; using it can avoid a redundant identity lookup.
|
|
71
|
+
*/
|
|
72
|
+
getAuthUser: (ctx: AnyAuthContext<DataModel>, identity: UserIdentity) => Promise<{
|
|
69
73
|
id: string;
|
|
70
74
|
} | null>;
|
|
71
75
|
/**
|
package/dist/auth.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{zCustomAction as e,zCustomMutation as t,zCustomQuery as n}from"./zod-registration.mjs";import{defaultErrors as r}from"./errors.mjs";import{registerQueryReader as i,suppliedPolicyRules as a}from"./querying/security.mjs";import{composeRules as o,createTenantRules as s,wrapDatabaseReader as c,wrapDatabaseWriter as l}from"./tenancy.mjs";import{z as u}from"zod";function d(e){let t=e?.trim().toLowerCase();return t===`member`?`writer`:t===`reader`||t===`writer`||t===`admin`?t:null}function f(e){let t=e?.errors??r,n=e?.maxRows??100;function i(e,r){async function a(i,a){if(!Number.isSafeInteger(i)||i<1||i>n)return t.throw({code:`INVALID_REQUEST_BOUNDARY`,message:`A bounded query limit must be from 1 to ${n}`});let o=await(r??e.fullTableScan()).take(i);return a?a(o):o}async function o(i,a){if(!Number.isSafeInteger(i.numItems)||i.numItems<1||i.numItems>n)return t.throw({code:`INVALID_REQUEST_BOUNDARY`,message:`A page size must be from 1 to ${n}`});let o=await(r??e.fullTableScan()).paginate(i);return a?{...o,page:await a(o.page)}:o}return{when:(t,n)=>r||t==null?i(e,r):i(e,n(e,t)),matching:(t,n,a=!0)=>r||!a?i(e,r):i(e,e.withIndex(t,n)),otherwise:t=>r??t(e),resolve:()=>r??e.fullTableScan(),execute:a,paginate:o}}return e=>i(e)}function p(u){let d=u.errors??r,p=u.triggers,h=p?e=>p.wrapDB(e):u.wrapDB??(e=>e),g=f({errors:d,maxRows:u.maxIncludedQueryRows});async function _(e){let t=await e.auth.getUserIdentity(),n=t?await u.getAuthUser(e):null;if(!t||!n)return d.throw({code:`UNAUTHENTICATED`});let r,i;if(u.resolveOrganization){let a=null;try{a=await u.resolveOrganization({ctx:e,identity:t,user:n})}catch{}if(!a)return d.throw({code:`FORBIDDEN`});r=a.organizationId,i=a.roleSlug}else{let e=m.parse(t),n=e.organization?.organizationId??e.org_id;if(!n)return d.throw({code:`UNAUTHENTICATED`});r=n,i=e.organization?.role??e.role}let a=u.mapRole(i);if(!a)return d.throw({code:`FORBIDDEN`});let o={identity:t,user:Object.freeze({id:n.id}),org:Object.freeze({organizationId:r,role:a}),role:a,actor:Object.freeze({userId:n.id,organizationId:r,role:a})};return Object.freeze({...o,tenant:u.security?.tenancy?.resolve?.(o)??r})}let v=u.security?{defaultPolicy:u.security.defaultPolicy??(u.security.tenancy?`deny`:`allow`)}:void 0;function y(e){let t=u.security;if(!t)return;let n=[];return t.tenancy&&n.push(s(e.tenant,t.tenancy.tables)),t.rules&&n.push(t.rules(e)),n.length===1?n[0]:o(...n)}function b(e,t){let n=y(t),r=v?.defaultPolicy??`allow`,o=n?c({db:e.db},e.db,a(e.db,n,r),v):e.db;return{...e,db:i(e.db,o,{scope:{mode:`authenticated`,principal:t.user.id,organization:t.org.organizationId,tenant:t.tenant,role:t.role},rules:n??{},defaultPolicy:r})}}function x(e,t){let n=y(t);return n?{...e,db:l({db:e.db},e.db,a(e.db,n,v?.defaultPolicy??`allow`),v)}:e}async function S(e,t){if(!u.verifyMembership)return null;try{let n=await u.verifyMembership({userId:e,organizationId:t});if(n&&n.organizationId===t)return n}catch{}return d.throw({code:`FORBIDDEN`})}function C(e,t){if(!t.includes(e))return d.throw({code:`FORBIDDEN`})}async function w(e){let t=await _(e);return{ctx:{...b(e,t),include:g,...t},args:{}}}async function T(e){let t=await _(e);return{ctx:{...x(h(e),t),include:g,...t},args:{}}}async function E(e){let t=await _(e),n=await S(t.user.id,t.org.organizationId);if(!n)return{ctx:{...e,...t},args:{}};let r=u.mapRole(n.roleSlug);if(!r)return d.throw({code:`FORBIDDEN`});let i={identity:t.identity,user:t.user,org:Object.freeze({organizationId:n.organizationId,role:r}),role:r,actor:Object.freeze({userId:t.user.id,organizationId:n.organizationId,role:r})};return{ctx:{...e,...i,tenant:u.security?.tenancy?.resolve?.(i)??n.organizationId},args:{}}}function D(...e){return n(u.query,{args:{},input:async t=>{let n=await w(t);return C(n.ctx.actor.role,e),n}})}function O(...e){return t(u.mutation,{args:{},input:async t=>{let n=await T(t);return C(n.ctx.actor.role,e),n}})}function k(...t){return e(u.action,{args:{},input:async e=>{let n=await E(e);return C(n.ctx.actor.role,t),n}})}return{include:g,authenticatedUser:_,roleQuery:D,roleMutation:O,roleAction:k,authQuery:n(u.query,{args:{},input:w}),authMutation:t(u.mutation,{args:{},input:T}),authAction:e(u.action,{args:{},input:E}),adminQuery:D(...u.adminRoles),adminMutation:O(...u.adminRoles),adminAction:k(...u.adminRoles),systemQuery:n(u.internalQuery,{args:{},input:async e=>({ctx:{...e,include:g,db:i(e.db,e.db,{scope:{mode:`system`,principal:null,organization:null,tenant:null,role:null},rules:{},defaultPolicy:`allow`})},args:{}})}),systemMutation:t(u.internalMutation,{args:{},input:async e=>({ctx:{...h(e),include:g},args:{}})}),systemAction:e(u.internalAction,{args:{},input:async e=>({ctx:e,args:{}})})}}const m=u.object({organization:u.object({organizationId:u.string().optional().catch(void 0),role:u.string().optional().catch(void 0)}).optional().catch(void 0),org_id:u.string().optional().catch(void 0),role:u.string().optional().catch(void 0)});export{p as createAuthFunctions,f as createInclude,d as defaultRoleMap};
|
|
1
|
+
import{zCustomAction as e,zCustomMutation as t,zCustomQuery as n}from"./zod-registration.mjs";import{defaultErrors as r}from"./errors.mjs";import{registerQueryReader as i,suppliedPolicyRules as a}from"./querying/security.mjs";import{composeRules as o,createTenantRules as s,wrapDatabaseReader as c,wrapDatabaseWriter as l}from"./tenancy.mjs";import{z as u}from"zod";function d(e){let t=e?.trim().toLowerCase();return t===`member`?`writer`:t===`reader`||t===`writer`||t===`admin`?t:null}function f(e){let t=e?.errors??r,n=e?.maxRows??100;function i(e,r){async function a(i,a){if(!Number.isSafeInteger(i)||i<1||i>n)return t.throw({code:`INVALID_REQUEST_BOUNDARY`,message:`A bounded query limit must be from 1 to ${n}`});let o=await(r??e.fullTableScan()).take(i);return a?a(o):o}async function o(i,a){if(!Number.isSafeInteger(i.numItems)||i.numItems<1||i.numItems>n)return t.throw({code:`INVALID_REQUEST_BOUNDARY`,message:`A page size must be from 1 to ${n}`});let o=await(r??e.fullTableScan()).paginate(i);return a?{...o,page:await a(o.page)}:o}return{when:(t,n)=>r||t==null?i(e,r):i(e,n(e,t)),matching:(t,n,a=!0)=>r||!a?i(e,r):i(e,e.withIndex(t,n)),otherwise:t=>r??t(e),resolve:()=>r??e.fullTableScan(),execute:a,paginate:o}}return e=>i(e)}function p(u){let d=u.errors??r,p=u.triggers,h=p?e=>p.wrapDB(e):u.wrapDB??(e=>e),g=f({errors:d,maxRows:u.maxIncludedQueryRows});async function _(e){let t=await e.auth.getUserIdentity(),n=t?await u.getAuthUser(e,t):null;if(!t||!n)return d.throw({code:`UNAUTHENTICATED`});let r,i;if(u.resolveOrganization){let a=null;try{a=await u.resolveOrganization({ctx:e,identity:t,user:n})}catch{}if(!a)return d.throw({code:`FORBIDDEN`});r=a.organizationId,i=a.roleSlug}else{let e=m.parse(t),n=e.organization?.organizationId??e.org_id;if(!n)return d.throw({code:`UNAUTHENTICATED`});r=n,i=e.organization?.role??e.role}let a=u.mapRole(i);if(!a)return d.throw({code:`FORBIDDEN`});let o={identity:t,user:Object.freeze({id:n.id}),org:Object.freeze({organizationId:r,role:a}),role:a,actor:Object.freeze({userId:n.id,organizationId:r,role:a})};return Object.freeze({...o,tenant:u.security?.tenancy?.resolve?.(o)??r})}let v=u.security?{defaultPolicy:u.security.defaultPolicy??(u.security.tenancy?`deny`:`allow`)}:void 0;function y(e){let t=u.security;if(!t)return;let n=[];return t.tenancy&&n.push(s(e.tenant,t.tenancy.tables)),t.rules&&n.push(t.rules(e)),n.length===1?n[0]:o(...n)}function b(e,t){let n=y(t),r=v?.defaultPolicy??`allow`,o=n?c({db:e.db},e.db,a(e.db,n,r),v):e.db;return{...e,db:i(e.db,o,{scope:{mode:`authenticated`,principal:t.user.id,organization:t.org.organizationId,tenant:t.tenant,role:t.role},rules:n??{},defaultPolicy:r})}}function x(e,t){let n=y(t);return n?{...e,db:l({db:e.db},e.db,a(e.db,n,v?.defaultPolicy??`allow`),v)}:e}async function S(e,t){if(!u.verifyMembership)return null;try{let n=await u.verifyMembership({userId:e,organizationId:t});if(n&&n.organizationId===t)return n}catch{}return d.throw({code:`FORBIDDEN`})}function C(e,t){if(!t.includes(e))return d.throw({code:`FORBIDDEN`})}async function w(e){let t=await _(e);return{ctx:{...b(e,t),include:g,...t},args:{}}}async function T(e){let t=await _(e);return{ctx:{...x(h(e),t),include:g,...t},args:{}}}async function E(e){let t=await _(e),n=await S(t.user.id,t.org.organizationId);if(!n)return{ctx:{...e,...t},args:{}};let r=u.mapRole(n.roleSlug);if(!r)return d.throw({code:`FORBIDDEN`});let i={identity:t.identity,user:t.user,org:Object.freeze({organizationId:n.organizationId,role:r}),role:r,actor:Object.freeze({userId:t.user.id,organizationId:n.organizationId,role:r})};return{ctx:{...e,...i,tenant:u.security?.tenancy?.resolve?.(i)??n.organizationId},args:{}}}function D(...e){return n(u.query,{args:{},input:async t=>{let n=await w(t);return C(n.ctx.actor.role,e),n}})}function O(...e){return t(u.mutation,{args:{},input:async t=>{let n=await T(t);return C(n.ctx.actor.role,e),n}})}function k(...t){return e(u.action,{args:{},input:async e=>{let n=await E(e);return C(n.ctx.actor.role,t),n}})}return{include:g,authenticatedUser:_,roleQuery:D,roleMutation:O,roleAction:k,authQuery:n(u.query,{args:{},input:w}),authMutation:t(u.mutation,{args:{},input:T}),authAction:e(u.action,{args:{},input:E}),adminQuery:D(...u.adminRoles),adminMutation:O(...u.adminRoles),adminAction:k(...u.adminRoles),systemQuery:n(u.internalQuery,{args:{},input:async e=>({ctx:{...e,include:g,db:i(e.db,e.db,{scope:{mode:`system`,principal:null,organization:null,tenant:null,role:null},rules:{},defaultPolicy:`allow`})},args:{}})}),systemMutation:t(u.internalMutation,{args:{},input:async e=>({ctx:{...h(e),include:g},args:{}})}),systemAction:e(u.internalAction,{args:{},input:async e=>({ctx:e,args:{}})})}}const m=u.object({organization:u.object({organizationId:u.string().optional().catch(void 0),role:u.string().optional().catch(void 0)}).optional().catch(void 0),org_id:u.string().optional().catch(void 0),role:u.string().optional().catch(void 0)});export{p as createAuthFunctions,f as createInclude,d as defaultRoleMap};
|
|
2
2
|
//# sourceMappingURL=auth.mjs.map
|
package/dist/auth.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.mjs","names":["defaultRoleMap","normalized","roleSlug","createInclude","errors","options","defaultErrors","maxRows","attach","execute","limit","data","selected","query","transform","paginate","opts","result","value","select","shouldMatch","indexName","indexRange","createAuthFunctions","config","triggers","wrapDB","ctx","include","authenticatedUser","identity","user","organizationId","organizationRole","resolved","claims","organizationClaims","claimedOrganizationId","role","base","securityConfig","securityRules","security","sets","createTenantRules","bundle","composeRules","secureReader","rules","defaultPolicy","ordinary","wrapDatabaseReader","suppliedPolicyRules","registerQueryReader","secureWriter","wrapDatabaseWriter","verifiedMembership","membership","requireRole","allowed","queryInput","mutationInput","actionInput","authenticated","verified","roleQuery","zCustomQuery","roleMutation","zCustomMutation","roleAction","zCustomAction","z"],"sources":["../src/auth.ts"],"sourcesContent":["import { z } from 'zod'\nimport { zCustomAction, zCustomMutation, zCustomQuery } from './zod-registration'\nimport type { CustomBuilder } from 'convex-helpers/server/zod4'\nimport type {\n\tActionBuilder,\n\tDocumentByInfo,\n\tPaginationOptions,\n\tPaginationResult,\n\tGenericActionCtx,\n\tGenericDataModel,\n\tGenericMutationCtx,\n\tGenericQueryCtx,\n\tGenericTableInfo,\n\tIndexNames,\n\tIndexRange,\n\tIndexRangeBuilder,\n\tMutationBuilder,\n\tNamedIndex,\n\tQuery,\n\tQueryBuilder,\n\tQueryInitializer,\n\tUserIdentity,\n} from 'convex/server'\nimport type { Triggers } from 'convex-helpers/server/triggers'\nimport type { TableNamesInDataModel } from 'convex/server'\nimport { defaultErrors, type ErrorFactory } from './errors'\nimport {\n\tregisterQueryReader,\n\tsuppliedPolicyRules,\n\ttype SecurityPolicyContext,\n} from './querying/security'\nexport type { SecurityPolicyContext } from './querying/security'\nimport {\n\tcomposeRules,\n\tcreateTenantRules,\n\twrapDatabaseReader,\n\twrapDatabaseWriter,\n\ttype RLSConfig,\n\ttype Rules,\n} from './tenancy'\n\n/** The default vocabulary; every app can supply its own via the Role generic. */\nexport type DefaultRole = 'reader' | 'writer' | 'admin'\n\nexport type Actor<Role extends string> = Readonly<{\n\tuserId: string\n\torganizationId: string\n\trole: Role\n}>\n\nexport type AuthBundle<Role extends string> = Readonly<{\n\tidentity: UserIdentity\n\tuser: Readonly<{ id: string }>\n\torg: Readonly<{ organizationId: string; role: Role }>\n\trole: Role\n\tactor: Actor<Role>\n\t/** The resolved tenant — security.tenancy.resolve, or the organization id. */\n\ttenant: string\n}>\n\n/**\n * Row-level security configuration. Tenant isolation and role-level rules\n * compose (AND) onto the same wrapped database: queries get a wrapped\n * reader, mutations get triggers first, then a wrapped writer.\n */\nexport type SecurityConfig<DataModel extends GenericDataModel, Role extends string> = {\n\t/**\n\t * Tenant isolation. `tables` is THE registry: every listed table gets\n\t * read/insert/modify gated on row.tenant === ctx.tenant. Pair with\n\t * tenantTable (schema) and tenantOwnership (triggers) on the same list.\n\t */\n\ttenancy?: {\n\t\ttables: readonly TableNamesInDataModel<DataModel>[]\n\t\t/** Maps the auth bundle to the tenant; defaults to org.organizationId. */\n\t\tresolve?: (bundle: Omit<AuthBundle<Role>, 'tenant'>) => string\n\t}\n\t/**\n\t * Role-level (or any policy) rules derived from the authenticated bundle,\n\t * composed AND-wise with tenant isolation. E.g. gate `modify` on a table\n\t * to admin roles.\n\t */\n\trules?: (bundle: AuthBundle<Role>) => Rules<SecurityPolicyContext<DataModel>, DataModel>\n\t/**\n\t * Policy for tables with no rule. Defaults to 'deny' when tenancy is\n\t * configured (unlisted tables are unreachable — fail closed), 'allow'\n\t * otherwise.\n\t */\n\tdefaultPolicy?: RLSConfig['defaultPolicy']\n}\n\ntype AnyAuthContext<DataModel extends GenericDataModel> =\n\t| GenericQueryCtx<DataModel>\n\t| GenericMutationCtx<DataModel>\n\t| GenericActionCtx<DataModel>\n\nexport type AuthFunctionsConfig<DataModel extends GenericDataModel, Role extends string> = {\n\t/** The consumer's generated function builders (from ./_generated/server). */\n\tquery: QueryBuilder<DataModel, 'public'>\n\tmutation: MutationBuilder<DataModel, 'public'>\n\taction: ActionBuilder<DataModel, 'public'>\n\tinternalQuery: QueryBuilder<DataModel, 'internal'>\n\tinternalMutation: MutationBuilder<DataModel, 'internal'>\n\tinternalAction: ActionBuilder<DataModel, 'internal'>\n\t/** Resolves the synchronized principal, e.g. (ctx) => authKit.getAuthUser(ctx). */\n\tgetAuthUser: (ctx: AnyAuthContext<DataModel>) => Promise<{ id: string } | null>\n\t/**\n\t * Maps an identity role slug onto the app's role vocabulary. Returning\n\t * null rejects the caller with FORBIDDEN — unknown roles never pass.\n\t */\n\tmapRole: (roleSlug?: string) => Role | null\n\t/** Roles allowed through the admin* constructors. */\n\tadminRoles: readonly NoInfer<Role>[]\n\t/**\n\t * Live membership check for actions (queries/mutations trust the JWT).\n\t * Authentication fails closed with FORBIDDEN when verification errors.\n\t * Omit to let actions trust the JWT like queries do.\n\t */\n\tverifyMembership?: (input: {\n\t\tuserId: string\n\t\torganizationId: string\n\t}) => Promise<{ organizationId: string; roleSlug: string } | null>\n\t/**\n\t * Resolves organization authority from the app's own data for identity\n\t * providers whose tokens carry no org claims. When configured, its result\n\t * overrides claim-based resolution; null or an error rejects with FORBIDDEN\n\t * (fail closed). In actions the ctx has no db — resolve via ctx.runQuery.\n\t */\n\tresolveOrganization?: (input: {\n\t\tctx: AnyAuthContext<DataModel>\n\t\tidentity: UserIdentity\n\t\tuser: { id: string }\n\t}) => Promise<{ organizationId: string; roleSlug: string } | null>\n\t/** Host error policy; defaults to throwing KitError. */\n\terrors?: ErrorFactory\n\t/**\n\t * Application trigger registry. When set, every authMutation,\n\t * roleMutation, and systemMutation write runs through triggers.wrapDB —\n\t * evaluations registered on tables fire structurally.\n\t */\n\ttriggers?: Triggers<DataModel>\n\t/** Lower-level alternative to `triggers`: a custom ctx wrapper. */\n\twrapDB?: (ctx: GenericMutationCtx<DataModel>) => GenericMutationCtx<DataModel>\n\t/** Upper bound for include() reads. */\n\tmaxIncludedQueryRows?: number\n\t/**\n\t * Row-level security: tenant isolation (from a table registry) and\n\t * role-level rules, applied structurally inside every auth*, role*, and\n\t * admin* constructor. system* constructors stay unwrapped (trusted).\n\t */\n\tsecurity?: SecurityConfig<DataModel, Role>\n}\n\n/** WorkOS-style default: `member` writes; reader/writer/admin pass through. */\nexport function defaultRoleMap(roleSlug?: string): DefaultRole | null {\n\tconst normalized = roleSlug?.trim().toLowerCase()\n\tif (normalized === 'member') return 'writer'\n\treturn normalized === 'reader' || normalized === 'writer' || normalized === 'admin'\n\t\t? normalized\n\t\t: null\n}\n\nexport type IncludedQuery<Table extends GenericTableInfo> = {\n\twhen<Value>(\n\t\tvalue: Value | null | undefined,\n\t\tselect: (query: QueryInitializer<Table>, value: Value) => Query<Table>,\n\t): IncludedQuery<Table>\n\tmatching<IndexName extends IndexNames<Table>>(\n\t\tindexName: IndexName,\n\t\tindexRange?: (\n\t\t\tquery: IndexRangeBuilder<DocumentByInfo<Table>, NamedIndex<Table, IndexName>>,\n\t\t) => IndexRange,\n\t\tshouldMatch?: boolean,\n\t): IncludedQuery<Table>\n\totherwise(select: (query: QueryInitializer<Table>) => Query<Table>): Query<Table>\n\tresolve(): Query<Table>\n\texecute(limit: number): Promise<DocumentByInfo<Table>[]>\n\texecute<Result>(\n\t\tlimit: number,\n\t\ttransform: (data: Awaited<ReturnType<Query<Table>['take']>>) => Result | Promise<Result>,\n\t): Promise<Result>\n\t/**\n\t * Cursor pagination over the selected indexed query. numItems is bounded\n\t * by the same maxRows policy as execute(). Under row-level security a\n\t * page may be shorter than numItems (rejected rows are filtered after\n\t * pagination); cursors remain correct. Pair with paginated(dto) from\n\t * cvx-kit/zod-table for the boundary schemas.\n\t */\n\tpaginate(opts: PaginationOptions): Promise<PaginationResult<DocumentByInfo<Table>>>\n\tpaginate<Item>(\n\t\topts: PaginationOptions,\n\t\ttransform: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t): Promise<PaginationResult<Item>>\n}\n\nexport type Include = <Table extends GenericTableInfo>(\n\tquery: QueryInitializer<Table>,\n) => IncludedQuery<Table>\n\n/**\n * Keep native contexts symbolic in published declarations. Inferred spreads\n * copy build-time Convex methods and override the consumer's native context.\n */\nexport type AuthFunctions<DataModel extends GenericDataModel, Role extends string = DefaultRole> = {\n\tinclude: Include\n\tauthenticatedUser: (ctx: AnyAuthContext<DataModel>) => Promise<AuthBundle<Role>>\n\tauthQuery: CustomBuilder<\n\t\t'query',\n\t\t{},\n\t\tGenericQueryCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t{},\n\t\tGenericQueryCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\tauthMutation: CustomBuilder<\n\t\t'mutation',\n\t\t{},\n\t\tGenericMutationCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t{},\n\t\tGenericMutationCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\tauthAction: CustomBuilder<\n\t\t'action',\n\t\t{},\n\t\tGenericActionCtx<DataModel> & AuthBundle<Role>,\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\troleQuery: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authQuery']\n\troleMutation: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authMutation']\n\troleAction: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authAction']\n\tadminQuery: AuthFunctions<DataModel, Role>['authQuery']\n\tadminMutation: AuthFunctions<DataModel, Role>['authMutation']\n\tadminAction: AuthFunctions<DataModel, Role>['authAction']\n\tsystemQuery: CustomBuilder<\n\t\t'query',\n\t\t{},\n\t\tGenericQueryCtx<DataModel> & { include: Include },\n\t\t{},\n\t\tGenericQueryCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n\tsystemMutation: CustomBuilder<\n\t\t'mutation',\n\t\t{},\n\t\tGenericMutationCtx<DataModel> & { include: Include },\n\t\t{},\n\t\tGenericMutationCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n\tsystemAction: CustomBuilder<\n\t\t'action',\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n}\n\n/** Builds an include() that selects the first matching indexed query and bounds the read. */\nexport function createInclude(options?: { errors?: ErrorFactory; maxRows?: number }): Include {\n\tconst errors = options?.errors ?? defaultErrors\n\tconst maxRows = options?.maxRows ?? 100\n\n\tfunction attach<Table extends GenericTableInfo>(\n\t\tquery: QueryInitializer<Table>,\n\t\tselected?: Query<Table>,\n\t): IncludedQuery<Table> {\n\t\tfunction execute(limit: number): Promise<DocumentByInfo<Table>[]>\n\t\tfunction execute<Result>(\n\t\t\tlimit: number,\n\t\t\ttransform: (data: DocumentByInfo<Table>[]) => Result | Promise<Result>,\n\t\t): Promise<Result>\n\t\tasync function execute<Result>(\n\t\t\tlimit: number,\n\t\t\ttransform?: (data: DocumentByInfo<Table>[]) => Result | Promise<Result>,\n\t\t) {\n\t\t\tif (!Number.isSafeInteger(limit) || limit < 1 || limit > maxRows) {\n\t\t\t\treturn errors.throw({\n\t\t\t\t\tcode: 'INVALID_REQUEST_BOUNDARY',\n\t\t\t\t\tmessage: `A bounded query limit must be from 1 to ${maxRows}`,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst data = await (selected ?? query.fullTableScan()).take(limit)\n\t\t\treturn transform ? transform(data) : data\n\t\t}\n\t\tfunction paginate(opts: PaginationOptions): Promise<PaginationResult<DocumentByInfo<Table>>>\n\t\tfunction paginate<Item>(\n\t\t\topts: PaginationOptions,\n\t\t\ttransform: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t\t): Promise<PaginationResult<Item>>\n\t\tasync function paginate<Item>(\n\t\t\topts: PaginationOptions,\n\t\t\ttransform?: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t\t) {\n\t\t\tif (!Number.isSafeInteger(opts.numItems) || opts.numItems < 1 || opts.numItems > maxRows) {\n\t\t\t\treturn errors.throw({\n\t\t\t\t\tcode: 'INVALID_REQUEST_BOUNDARY',\n\t\t\t\t\tmessage: `A page size must be from 1 to ${maxRows}`,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst result = await (selected ?? query.fullTableScan()).paginate(opts)\n\t\t\treturn transform ? { ...result, page: await transform(result.page) } : result\n\t\t}\n\t\treturn {\n\t\t\twhen: (value, select) =>\n\t\t\t\tselected || value === undefined || value === null\n\t\t\t\t\t? attach(query, selected)\n\t\t\t\t\t: attach(query, select(query, value)),\n\t\t\tmatching: (indexName, indexRange, shouldMatch = true) =>\n\t\t\t\tselected || !shouldMatch\n\t\t\t\t\t? attach(query, selected)\n\t\t\t\t\t: attach(query, query.withIndex(indexName, indexRange)),\n\t\t\totherwise: (select) => selected ?? select(query),\n\t\t\tresolve: () => selected ?? query.fullTableScan(),\n\t\t\texecute,\n\t\t\tpaginate,\n\t\t}\n\t}\n\n\treturn (query) => attach(query)\n}\n\n/**\n * Builds the auth-aware function constructors from the host's injected\n * policy: identity resolution, the app's own role vocabulary, live\n * membership verification for actions, trigger wrapping for mutations,\n * and errors. Role-based access is first-class — every constructor family\n * has a role-gated variant (roleQuery/roleMutation/roleAction), and the\n * admin* constructors are just that gate applied to config.adminRoles.\n */\nexport function createAuthFunctions<\n\tDataModel extends GenericDataModel,\n\tconst Role extends string = DefaultRole,\n>(config: AuthFunctionsConfig<DataModel, Role>): AuthFunctions<DataModel, Role> {\n\tconst errors = config.errors ?? defaultErrors\n\tconst triggers = config.triggers\n\tconst wrapDB = triggers\n\t\t? (ctx: GenericMutationCtx<DataModel>) => triggers.wrapDB(ctx)\n\t\t: (config.wrapDB ?? ((ctx) => ctx))\n\tconst include = createInclude({\n\t\terrors,\n\t\tmaxRows: config.maxIncludedQueryRows,\n\t})\n\n\tasync function authenticatedUser(ctx: AnyAuthContext<DataModel>): Promise<AuthBundle<Role>> {\n\t\tconst identity = await ctx.auth.getUserIdentity()\n\t\tconst user = identity ? await config.getAuthUser(ctx) : null\n\t\tif (!identity || !user) return errors.throw({ code: 'UNAUTHENTICATED' })\n\t\tlet organizationId: string\n\t\tlet organizationRole: string | undefined\n\t\tif (config.resolveOrganization) {\n\t\t\t// The hook is the organization authority — claims are skipped\n\t\t\t// entirely. Authentication fails closed when it errors or abstains.\n\t\t\tlet resolved: { organizationId: string; roleSlug: string } | null = null\n\t\t\ttry {\n\t\t\t\tresolved = await config.resolveOrganization({ ctx, identity, user })\n\t\t\t} catch {\n\t\t\t\t// Authentication fails closed when the hook cannot resolve.\n\t\t\t}\n\t\t\tif (!resolved) return errors.throw({ code: 'FORBIDDEN' })\n\t\t\torganizationId = resolved.organizationId\n\t\t\torganizationRole = resolved.roleSlug\n\t\t} else {\n\t\t\tconst claims = organizationClaims.parse(identity)\n\t\t\tconst claimedOrganizationId = claims.organization?.organizationId ?? claims.org_id\n\t\t\tif (!claimedOrganizationId) return errors.throw({ code: 'UNAUTHENTICATED' })\n\t\t\torganizationId = claimedOrganizationId\n\t\t\torganizationRole = claims.organization?.role ?? claims.role\n\t\t}\n\t\tconst role = config.mapRole(organizationRole)\n\t\tif (!role) return errors.throw({ code: 'FORBIDDEN' })\n\t\tconst base = {\n\t\t\tidentity,\n\t\t\tuser: Object.freeze({ id: user.id }),\n\t\t\torg: Object.freeze({ organizationId, role }),\n\t\t\trole,\n\t\t\tactor: Object.freeze({ userId: user.id, organizationId, role }),\n\t\t}\n\t\treturn Object.freeze({\n\t\t\t...base,\n\t\t\ttenant: config.security?.tenancy?.resolve?.(base) ?? organizationId,\n\t\t})\n\t}\n\n\tconst securityConfig: RLSConfig | undefined = config.security\n\t\t? {\n\t\t\t\tdefaultPolicy:\n\t\t\t\t\tconfig.security.defaultPolicy ?? (config.security.tenancy ? 'deny' : 'allow'),\n\t\t\t}\n\t\t: undefined\n\n\tfunction securityRules(\n\t\tbundle: AuthBundle<Role>,\n\t): Rules<SecurityPolicyContext<DataModel>, DataModel> | undefined {\n\t\tconst security = config.security\n\t\tif (!security) return undefined\n\t\tconst sets: Rules<SecurityPolicyContext<DataModel>, DataModel>[] = []\n\t\tif (security.tenancy) {\n\t\t\tsets.push(createTenantRules<DataModel>(bundle.tenant, security.tenancy.tables))\n\t\t}\n\t\tif (security.rules) sets.push(security.rules(bundle))\n\t\treturn sets.length === 1 ? sets[0] : composeRules(...sets)\n\t}\n\n\tfunction secureReader(\n\t\tctx: GenericQueryCtx<DataModel>,\n\t\tbundle: AuthBundle<Role>,\n\t): GenericQueryCtx<DataModel> {\n\t\tconst rules = securityRules(bundle)\n\t\tconst defaultPolicy = securityConfig?.defaultPolicy ?? 'allow'\n\t\tconst ordinary = rules\n\t\t\t? wrapDatabaseReader(\n\t\t\t\t\t{ db: ctx.db },\n\t\t\t\t\tctx.db,\n\t\t\t\t\tsuppliedPolicyRules(ctx.db, rules, defaultPolicy),\n\t\t\t\t\tsecurityConfig,\n\t\t\t\t)\n\t\t\t: ctx.db\n\t\treturn {\n\t\t\t...ctx,\n\t\t\tdb: registerQueryReader(ctx.db, ordinary, {\n\t\t\t\tscope: {\n\t\t\t\t\tmode: 'authenticated',\n\t\t\t\t\tprincipal: bundle.user.id,\n\t\t\t\t\torganization: bundle.org.organizationId,\n\t\t\t\t\ttenant: bundle.tenant,\n\t\t\t\t\trole: bundle.role,\n\t\t\t\t},\n\t\t\t\trules: rules ?? {},\n\t\t\t\tdefaultPolicy,\n\t\t\t}),\n\t\t}\n\t}\n\n\tfunction secureWriter(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\tbundle: AuthBundle<Role>,\n\t): GenericMutationCtx<DataModel> {\n\t\tconst rules = securityRules(bundle)\n\t\tif (!rules) return ctx\n\t\t// Triggers wrap first (ctx already trigger-wrapped by the caller),\n\t\t// then row-level security wraps the triggered db — order matters.\n\t\treturn {\n\t\t\t...ctx,\n\t\t\tdb: wrapDatabaseWriter(\n\t\t\t\t{ db: ctx.db },\n\t\t\t\tctx.db,\n\t\t\t\tsuppliedPolicyRules(ctx.db, rules, securityConfig?.defaultPolicy ?? 'allow'),\n\t\t\t\tsecurityConfig,\n\t\t\t),\n\t\t}\n\t}\n\n\tasync function verifiedMembership(userId: string, organizationId: string) {\n\t\tif (!config.verifyMembership) return null\n\t\ttry {\n\t\t\tconst membership = await config.verifyMembership({\n\t\t\t\tuserId,\n\t\t\t\torganizationId,\n\t\t\t})\n\t\t\tif (membership && membership.organizationId === organizationId) {\n\t\t\t\treturn membership\n\t\t\t}\n\t\t} catch {\n\t\t\t// Authentication fails closed when membership cannot be verified.\n\t\t}\n\t\treturn errors.throw({ code: 'FORBIDDEN' })\n\t}\n\n\tfunction requireRole(role: Role, allowed: readonly Role[]) {\n\t\tif (!allowed.includes(role)) return errors.throw({ code: 'FORBIDDEN' })\n\t}\n\n\tasync function queryInput(ctx: GenericQueryCtx<DataModel>) {\n\t\tconst bundle = await authenticatedUser(ctx)\n\t\treturn {\n\t\t\tctx: { ...secureReader(ctx, bundle), include, ...bundle },\n\t\t\targs: {},\n\t\t}\n\t}\n\n\tasync function mutationInput(ctx: GenericMutationCtx<DataModel>) {\n\t\tconst bundle = await authenticatedUser(ctx)\n\t\treturn {\n\t\t\tctx: { ...secureWriter(wrapDB(ctx), bundle), include, ...bundle },\n\t\t\targs: {},\n\t\t}\n\t}\n\n\tasync function actionInput(ctx: GenericActionCtx<DataModel>) {\n\t\tconst authenticated = await authenticatedUser(ctx)\n\t\tconst membership = await verifiedMembership(\n\t\t\tauthenticated.user.id,\n\t\t\tauthenticated.org.organizationId,\n\t\t)\n\t\tif (!membership) return { ctx: { ...ctx, ...authenticated }, args: {} }\n\t\tconst role = config.mapRole(membership.roleSlug)\n\t\tif (!role) return errors.throw({ code: 'FORBIDDEN' })\n\t\tconst verified = {\n\t\t\tidentity: authenticated.identity,\n\t\t\tuser: authenticated.user,\n\t\t\torg: Object.freeze({\n\t\t\t\torganizationId: membership.organizationId,\n\t\t\t\trole,\n\t\t\t}),\n\t\t\trole,\n\t\t\tactor: Object.freeze({\n\t\t\t\tuserId: authenticated.user.id,\n\t\t\t\torganizationId: membership.organizationId,\n\t\t\t\trole,\n\t\t\t}),\n\t\t}\n\t\treturn {\n\t\t\tctx: {\n\t\t\t\t...ctx,\n\t\t\t\t...verified,\n\t\t\t\t// Tenant re-derives from the live-verified organization.\n\t\t\t\ttenant: config.security?.tenancy?.resolve?.(verified) ?? membership.organizationId,\n\t\t\t},\n\t\t\targs: {},\n\t\t}\n\t}\n\n\t/** Query constructor allowing only the given roles. */\n\tfunction roleQuery(...allowed: readonly Role[]) {\n\t\treturn zCustomQuery(config.query, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst authenticated = await queryInput(ctx)\n\t\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\t\treturn authenticated\n\t\t\t},\n\t\t})\n\t}\n\n\t/** Mutation constructor allowing only the given roles. */\n\tfunction roleMutation(...allowed: readonly Role[]) {\n\t\treturn zCustomMutation(config.mutation, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst authenticated = await mutationInput(ctx)\n\t\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\t\treturn authenticated\n\t\t\t},\n\t\t})\n\t}\n\n\t/** Action constructor allowing only the given roles (post live verification). */\n\tfunction roleAction(...allowed: readonly Role[]) {\n\t\treturn zCustomAction(config.action, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst authenticated = await actionInput(ctx)\n\t\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\t\treturn authenticated\n\t\t\t},\n\t\t})\n\t}\n\n\treturn {\n\t\tinclude,\n\t\tauthenticatedUser,\n\t\troleQuery,\n\t\troleMutation,\n\t\troleAction,\n\t\tauthQuery: zCustomQuery(config.query, { args: {}, input: queryInput }),\n\t\tauthMutation: zCustomMutation(config.mutation, {\n\t\t\targs: {},\n\t\t\tinput: mutationInput,\n\t\t}),\n\t\tauthAction: zCustomAction(config.action, {\n\t\t\targs: {},\n\t\t\tinput: actionInput,\n\t\t}),\n\t\tadminQuery: roleQuery(...config.adminRoles),\n\t\tadminMutation: roleMutation(...config.adminRoles),\n\t\tadminAction: roleAction(...config.adminRoles),\n\t\tsystemQuery: zCustomQuery(config.internalQuery, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => ({\n\t\t\t\tctx: {\n\t\t\t\t\t...ctx,\n\t\t\t\t\tinclude,\n\t\t\t\t\tdb: registerQueryReader(ctx.db, ctx.db, {\n\t\t\t\t\t\tscope: {\n\t\t\t\t\t\t\tmode: 'system',\n\t\t\t\t\t\t\tprincipal: null,\n\t\t\t\t\t\t\torganization: null,\n\t\t\t\t\t\t\ttenant: null,\n\t\t\t\t\t\t\trole: null,\n\t\t\t\t\t\t},\n\t\t\t\t\t\trules: {},\n\t\t\t\t\t\tdefaultPolicy: 'allow',\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t\targs: {},\n\t\t\t}),\n\t\t}),\n\t\tsystemMutation: zCustomMutation(config.internalMutation, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => ({ ctx: { ...wrapDB(ctx), include }, args: {} }),\n\t\t}),\n\t\tsystemAction: zCustomAction(config.internalAction, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => ({ ctx, args: {} }),\n\t\t}),\n\t}\n}\n\nconst organizationClaims = z.object({\n\torganization: z\n\t\t.object({\n\t\t\torganizationId: z.string().optional().catch(undefined),\n\t\t\trole: z.string().optional().catch(undefined),\n\t\t})\n\t\t.optional()\n\t\t.catch(undefined),\n\torg_id: z.string().optional().catch(undefined),\n\trole: z.string().optional().catch(undefined),\n})\n"],"mappings":"8WAyJA,SAAgBA,EAAe,EAAuC,CACrE,IAAMC,EAAaC,GAAU,KAAK,CAAC,CAAC,YAAY,EAEhD,OADID,IAAe,SAAiB,SAC7BA,IAAe,UAAYA,IAAe,UAAYA,IAAe,QACzEA,EACA,IACJ,CA6GA,SAAgBE,EAAc,EAAgE,CAC7F,IAAMC,EAASC,GAAS,QAAUC,EAC5BC,EAAUF,GAAS,SAAW,IAEpC,SAASG,EACR,EACA,EACuB,CAMvB,eAAeC,EACd,EACA,EACC,CACD,GAAI,CAAC,OAAO,cAAcC,CAAK,GAAKA,EAAQ,GAAKA,EAAQH,EACxD,OAAOH,EAAO,MAAM,CACnB,KAAM,2BACN,QAAS,2CAA2CG,GACrD,CAAC,EAEF,IAAMI,EAAO,MAAOC,GAAYC,EAAM,cAAc,EAAA,CAAG,KAAKH,CAAK,EACjE,OAAOI,EAAYA,EAAUH,CAAI,EAAIA,CACtC,CAMA,eAAeI,EACd,EACA,EACC,CACD,GAAI,CAAC,OAAO,cAAcC,EAAK,QAAQ,GAAKA,EAAK,SAAW,GAAKA,EAAK,SAAWT,EAChF,OAAOH,EAAO,MAAM,CACnB,KAAM,2BACN,QAAS,iCAAiCG,GAC3C,CAAC,EAEF,IAAMU,EAAS,MAAOL,GAAYC,EAAM,cAAc,EAAA,CAAG,SAASG,CAAI,EACtE,OAAOF,EAAY,CAAE,GAAGG,EAAQ,KAAM,MAAMH,EAAUG,EAAO,IAAI,CAAE,EAAIA,CACxE,CACA,MAAO,CACN,MAAO,EAAO,IACbL,GAAYM,GAAiC,KAC1CV,EAAOK,EAAOD,CAAQ,EACtBJ,EAAOK,EAAOM,EAAON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CAAC,SAAS,CAAC,CAAC,MAAM,IAAA,EAAS,CAC5C,CAAC,CAAC,CACD,SAAS,CAAC,CACV,MAAM,IAAA,EAAS,EACjB,OAAQA,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,IAAA,EAAS,EAC7C,KAAMA,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,IAAA,EAAS,CAC5C,CAAC"}
|
|
1
|
+
{"version":3,"file":"auth.mjs","names":["defaultRoleMap","normalized","roleSlug","createInclude","errors","options","defaultErrors","maxRows","attach","execute","limit","data","selected","query","transform","paginate","opts","result","value","select","shouldMatch","indexName","indexRange","createAuthFunctions","config","triggers","wrapDB","ctx","include","authenticatedUser","identity","user","organizationId","organizationRole","resolved","claims","organizationClaims","claimedOrganizationId","role","base","securityConfig","securityRules","security","sets","createTenantRules","bundle","composeRules","secureReader","rules","defaultPolicy","ordinary","wrapDatabaseReader","suppliedPolicyRules","registerQueryReader","secureWriter","wrapDatabaseWriter","verifiedMembership","membership","requireRole","allowed","queryInput","mutationInput","actionInput","authenticated","verified","roleQuery","zCustomQuery","roleMutation","zCustomMutation","roleAction","zCustomAction","z"],"sources":["../src/auth.ts"],"sourcesContent":["import { z } from 'zod'\nimport { zCustomAction, zCustomMutation, zCustomQuery } from './zod-registration'\nimport type { CustomBuilder } from 'convex-helpers/server/zod4'\nimport type {\n\tActionBuilder,\n\tDocumentByInfo,\n\tPaginationOptions,\n\tPaginationResult,\n\tGenericActionCtx,\n\tGenericDataModel,\n\tGenericMutationCtx,\n\tGenericQueryCtx,\n\tGenericTableInfo,\n\tIndexNames,\n\tIndexRange,\n\tIndexRangeBuilder,\n\tMutationBuilder,\n\tNamedIndex,\n\tQuery,\n\tQueryBuilder,\n\tQueryInitializer,\n\tUserIdentity,\n} from 'convex/server'\nimport type { Triggers } from 'convex-helpers/server/triggers'\nimport type { TableNamesInDataModel } from 'convex/server'\nimport { defaultErrors, type ErrorFactory } from './errors'\nimport {\n\tregisterQueryReader,\n\tsuppliedPolicyRules,\n\ttype SecurityPolicyContext,\n} from './querying/security'\nexport type { SecurityPolicyContext } from './querying/security'\nimport {\n\tcomposeRules,\n\tcreateTenantRules,\n\twrapDatabaseReader,\n\twrapDatabaseWriter,\n\ttype RLSConfig,\n\ttype Rules,\n} from './tenancy'\n\n/** The default vocabulary; every app can supply its own via the Role generic. */\nexport type DefaultRole = 'reader' | 'writer' | 'admin'\n\nexport type Actor<Role extends string> = Readonly<{\n\tuserId: string\n\torganizationId: string\n\trole: Role\n}>\n\nexport type AuthBundle<Role extends string> = Readonly<{\n\tidentity: UserIdentity\n\tuser: Readonly<{ id: string }>\n\torg: Readonly<{ organizationId: string; role: Role }>\n\trole: Role\n\tactor: Actor<Role>\n\t/** The resolved tenant — security.tenancy.resolve, or the organization id. */\n\ttenant: string\n}>\n\n/**\n * Row-level security configuration. Tenant isolation and role-level rules\n * compose (AND) onto the same wrapped database: queries get a wrapped\n * reader, mutations get triggers first, then a wrapped writer.\n */\nexport type SecurityConfig<DataModel extends GenericDataModel, Role extends string> = {\n\t/**\n\t * Tenant isolation. `tables` is THE registry: every listed table gets\n\t * read/insert/modify gated on row.tenant === ctx.tenant. Pair with\n\t * tenantTable (schema) and tenantOwnership (triggers) on the same list.\n\t */\n\ttenancy?: {\n\t\ttables: readonly TableNamesInDataModel<DataModel>[]\n\t\t/** Maps the auth bundle to the tenant; defaults to org.organizationId. */\n\t\tresolve?: (bundle: Omit<AuthBundle<Role>, 'tenant'>) => string\n\t}\n\t/**\n\t * Role-level (or any policy) rules derived from the authenticated bundle,\n\t * composed AND-wise with tenant isolation. E.g. gate `modify` on a table\n\t * to admin roles.\n\t */\n\trules?: (bundle: AuthBundle<Role>) => Rules<SecurityPolicyContext<DataModel>, DataModel>\n\t/**\n\t * Policy for tables with no rule. Defaults to 'deny' when tenancy is\n\t * configured (unlisted tables are unreachable — fail closed), 'allow'\n\t * otherwise.\n\t */\n\tdefaultPolicy?: RLSConfig['defaultPolicy']\n}\n\ntype AnyAuthContext<DataModel extends GenericDataModel> =\n\t| GenericQueryCtx<DataModel>\n\t| GenericMutationCtx<DataModel>\n\t| GenericActionCtx<DataModel>\n\nexport type AuthFunctionsConfig<DataModel extends GenericDataModel, Role extends string> = {\n\t/** The consumer's generated function builders (from ./_generated/server). */\n\tquery: QueryBuilder<DataModel, 'public'>\n\tmutation: MutationBuilder<DataModel, 'public'>\n\taction: ActionBuilder<DataModel, 'public'>\n\tinternalQuery: QueryBuilder<DataModel, 'internal'>\n\tinternalMutation: MutationBuilder<DataModel, 'internal'>\n\tinternalAction: ActionBuilder<DataModel, 'internal'>\n\t/**\n\t * Resolves the synchronized principal, e.g. (ctx) => authKit.getAuthUser(ctx).\n\t * The already-resolved, non-null identity is supplied as a second argument.\n\t * Callbacks may ignore it; using it can avoid a redundant identity lookup.\n\t */\n\tgetAuthUser: (\n\t\tctx: AnyAuthContext<DataModel>,\n\t\tidentity: UserIdentity,\n\t) => Promise<{ id: string } | null>\n\t/**\n\t * Maps an identity role slug onto the app's role vocabulary. Returning\n\t * null rejects the caller with FORBIDDEN — unknown roles never pass.\n\t */\n\tmapRole: (roleSlug?: string) => Role | null\n\t/** Roles allowed through the admin* constructors. */\n\tadminRoles: readonly NoInfer<Role>[]\n\t/**\n\t * Live membership check for actions (queries/mutations trust the JWT).\n\t * Authentication fails closed with FORBIDDEN when verification errors.\n\t * Omit to let actions trust the JWT like queries do.\n\t */\n\tverifyMembership?: (input: {\n\t\tuserId: string\n\t\torganizationId: string\n\t}) => Promise<{ organizationId: string; roleSlug: string } | null>\n\t/**\n\t * Resolves organization authority from the app's own data for identity\n\t * providers whose tokens carry no org claims. When configured, its result\n\t * overrides claim-based resolution; null or an error rejects with FORBIDDEN\n\t * (fail closed). In actions the ctx has no db — resolve via ctx.runQuery.\n\t */\n\tresolveOrganization?: (input: {\n\t\tctx: AnyAuthContext<DataModel>\n\t\tidentity: UserIdentity\n\t\tuser: { id: string }\n\t}) => Promise<{ organizationId: string; roleSlug: string } | null>\n\t/** Host error policy; defaults to throwing KitError. */\n\terrors?: ErrorFactory\n\t/**\n\t * Application trigger registry. When set, every authMutation,\n\t * roleMutation, and systemMutation write runs through triggers.wrapDB —\n\t * evaluations registered on tables fire structurally.\n\t */\n\ttriggers?: Triggers<DataModel>\n\t/** Lower-level alternative to `triggers`: a custom ctx wrapper. */\n\twrapDB?: (ctx: GenericMutationCtx<DataModel>) => GenericMutationCtx<DataModel>\n\t/** Upper bound for include() reads. */\n\tmaxIncludedQueryRows?: number\n\t/**\n\t * Row-level security: tenant isolation (from a table registry) and\n\t * role-level rules, applied structurally inside every auth*, role*, and\n\t * admin* constructor. system* constructors stay unwrapped (trusted).\n\t */\n\tsecurity?: SecurityConfig<DataModel, Role>\n}\n\n/** WorkOS-style default: `member` writes; reader/writer/admin pass through. */\nexport function defaultRoleMap(roleSlug?: string): DefaultRole | null {\n\tconst normalized = roleSlug?.trim().toLowerCase()\n\tif (normalized === 'member') return 'writer'\n\treturn normalized === 'reader' || normalized === 'writer' || normalized === 'admin'\n\t\t? normalized\n\t\t: null\n}\n\nexport type IncludedQuery<Table extends GenericTableInfo> = {\n\twhen<Value>(\n\t\tvalue: Value | null | undefined,\n\t\tselect: (query: QueryInitializer<Table>, value: Value) => Query<Table>,\n\t): IncludedQuery<Table>\n\tmatching<IndexName extends IndexNames<Table>>(\n\t\tindexName: IndexName,\n\t\tindexRange?: (\n\t\t\tquery: IndexRangeBuilder<DocumentByInfo<Table>, NamedIndex<Table, IndexName>>,\n\t\t) => IndexRange,\n\t\tshouldMatch?: boolean,\n\t): IncludedQuery<Table>\n\totherwise(select: (query: QueryInitializer<Table>) => Query<Table>): Query<Table>\n\tresolve(): Query<Table>\n\texecute(limit: number): Promise<DocumentByInfo<Table>[]>\n\texecute<Result>(\n\t\tlimit: number,\n\t\ttransform: (data: Awaited<ReturnType<Query<Table>['take']>>) => Result | Promise<Result>,\n\t): Promise<Result>\n\t/**\n\t * Cursor pagination over the selected indexed query. numItems is bounded\n\t * by the same maxRows policy as execute(). Under row-level security a\n\t * page may be shorter than numItems (rejected rows are filtered after\n\t * pagination); cursors remain correct. Pair with paginated(dto) from\n\t * cvx-kit/zod-table for the boundary schemas.\n\t */\n\tpaginate(opts: PaginationOptions): Promise<PaginationResult<DocumentByInfo<Table>>>\n\tpaginate<Item>(\n\t\topts: PaginationOptions,\n\t\ttransform: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t): Promise<PaginationResult<Item>>\n}\n\nexport type Include = <Table extends GenericTableInfo>(\n\tquery: QueryInitializer<Table>,\n) => IncludedQuery<Table>\n\n/**\n * Keep native contexts symbolic in published declarations. Inferred spreads\n * copy build-time Convex methods and override the consumer's native context.\n */\nexport type AuthFunctions<DataModel extends GenericDataModel, Role extends string = DefaultRole> = {\n\tinclude: Include\n\tauthenticatedUser: (ctx: AnyAuthContext<DataModel>) => Promise<AuthBundle<Role>>\n\tauthQuery: CustomBuilder<\n\t\t'query',\n\t\t{},\n\t\tGenericQueryCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t{},\n\t\tGenericQueryCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\tauthMutation: CustomBuilder<\n\t\t'mutation',\n\t\t{},\n\t\tGenericMutationCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t{},\n\t\tGenericMutationCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\tauthAction: CustomBuilder<\n\t\t'action',\n\t\t{},\n\t\tGenericActionCtx<DataModel> & AuthBundle<Role>,\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\troleQuery: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authQuery']\n\troleMutation: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authMutation']\n\troleAction: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authAction']\n\tadminQuery: AuthFunctions<DataModel, Role>['authQuery']\n\tadminMutation: AuthFunctions<DataModel, Role>['authMutation']\n\tadminAction: AuthFunctions<DataModel, Role>['authAction']\n\tsystemQuery: CustomBuilder<\n\t\t'query',\n\t\t{},\n\t\tGenericQueryCtx<DataModel> & { include: Include },\n\t\t{},\n\t\tGenericQueryCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n\tsystemMutation: CustomBuilder<\n\t\t'mutation',\n\t\t{},\n\t\tGenericMutationCtx<DataModel> & { include: Include },\n\t\t{},\n\t\tGenericMutationCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n\tsystemAction: CustomBuilder<\n\t\t'action',\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n}\n\n/** Builds an include() that selects the first matching indexed query and bounds the read. */\nexport function createInclude(options?: { errors?: ErrorFactory; maxRows?: number }): Include {\n\tconst errors = options?.errors ?? defaultErrors\n\tconst maxRows = options?.maxRows ?? 100\n\n\tfunction attach<Table extends GenericTableInfo>(\n\t\tquery: QueryInitializer<Table>,\n\t\tselected?: Query<Table>,\n\t): IncludedQuery<Table> {\n\t\tfunction execute(limit: number): Promise<DocumentByInfo<Table>[]>\n\t\tfunction execute<Result>(\n\t\t\tlimit: number,\n\t\t\ttransform: (data: DocumentByInfo<Table>[]) => Result | Promise<Result>,\n\t\t): Promise<Result>\n\t\tasync function execute<Result>(\n\t\t\tlimit: number,\n\t\t\ttransform?: (data: DocumentByInfo<Table>[]) => Result | Promise<Result>,\n\t\t) {\n\t\t\tif (!Number.isSafeInteger(limit) || limit < 1 || limit > maxRows) {\n\t\t\t\treturn errors.throw({\n\t\t\t\t\tcode: 'INVALID_REQUEST_BOUNDARY',\n\t\t\t\t\tmessage: `A bounded query limit must be from 1 to ${maxRows}`,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst data = await (selected ?? query.fullTableScan()).take(limit)\n\t\t\treturn transform ? transform(data) : data\n\t\t}\n\t\tfunction paginate(opts: PaginationOptions): Promise<PaginationResult<DocumentByInfo<Table>>>\n\t\tfunction paginate<Item>(\n\t\t\topts: PaginationOptions,\n\t\t\ttransform: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t\t): Promise<PaginationResult<Item>>\n\t\tasync function paginate<Item>(\n\t\t\topts: PaginationOptions,\n\t\t\ttransform?: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t\t) {\n\t\t\tif (!Number.isSafeInteger(opts.numItems) || opts.numItems < 1 || opts.numItems > maxRows) {\n\t\t\t\treturn errors.throw({\n\t\t\t\t\tcode: 'INVALID_REQUEST_BOUNDARY',\n\t\t\t\t\tmessage: `A page size must be from 1 to ${maxRows}`,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst result = await (selected ?? query.fullTableScan()).paginate(opts)\n\t\t\treturn transform ? { ...result, page: await transform(result.page) } : result\n\t\t}\n\t\treturn {\n\t\t\twhen: (value, select) =>\n\t\t\t\tselected || value === undefined || value === null\n\t\t\t\t\t? attach(query, selected)\n\t\t\t\t\t: attach(query, select(query, value)),\n\t\t\tmatching: (indexName, indexRange, shouldMatch = true) =>\n\t\t\t\tselected || !shouldMatch\n\t\t\t\t\t? attach(query, selected)\n\t\t\t\t\t: attach(query, query.withIndex(indexName, indexRange)),\n\t\t\totherwise: (select) => selected ?? select(query),\n\t\t\tresolve: () => selected ?? query.fullTableScan(),\n\t\t\texecute,\n\t\t\tpaginate,\n\t\t}\n\t}\n\n\treturn (query) => attach(query)\n}\n\n/**\n * Builds the auth-aware function constructors from the host's injected\n * policy: identity resolution, the app's own role vocabulary, live\n * membership verification for actions, trigger wrapping for mutations,\n * and errors. Role-based access is first-class — every constructor family\n * has a role-gated variant (roleQuery/roleMutation/roleAction), and the\n * admin* constructors are just that gate applied to config.adminRoles.\n */\nexport function createAuthFunctions<\n\tDataModel extends GenericDataModel,\n\tconst Role extends string = DefaultRole,\n>(config: AuthFunctionsConfig<DataModel, Role>): AuthFunctions<DataModel, Role> {\n\tconst errors = config.errors ?? defaultErrors\n\tconst triggers = config.triggers\n\tconst wrapDB = triggers\n\t\t? (ctx: GenericMutationCtx<DataModel>) => triggers.wrapDB(ctx)\n\t\t: (config.wrapDB ?? ((ctx) => ctx))\n\tconst include = createInclude({\n\t\terrors,\n\t\tmaxRows: config.maxIncludedQueryRows,\n\t})\n\n\tasync function authenticatedUser(ctx: AnyAuthContext<DataModel>): Promise<AuthBundle<Role>> {\n\t\tconst identity = await ctx.auth.getUserIdentity()\n\t\tconst user = identity ? await config.getAuthUser(ctx, identity) : null\n\t\tif (!identity || !user) return errors.throw({ code: 'UNAUTHENTICATED' })\n\t\tlet organizationId: string\n\t\tlet organizationRole: string | undefined\n\t\tif (config.resolveOrganization) {\n\t\t\t// The hook is the organization authority — claims are skipped\n\t\t\t// entirely. Authentication fails closed when it errors or abstains.\n\t\t\tlet resolved: { organizationId: string; roleSlug: string } | null = null\n\t\t\ttry {\n\t\t\t\tresolved = await config.resolveOrganization({ ctx, identity, user })\n\t\t\t} catch {\n\t\t\t\t// Authentication fails closed when the hook cannot resolve.\n\t\t\t}\n\t\t\tif (!resolved) return errors.throw({ code: 'FORBIDDEN' })\n\t\t\torganizationId = resolved.organizationId\n\t\t\torganizationRole = resolved.roleSlug\n\t\t} else {\n\t\t\tconst claims = organizationClaims.parse(identity)\n\t\t\tconst claimedOrganizationId = claims.organization?.organizationId ?? claims.org_id\n\t\t\tif (!claimedOrganizationId) return errors.throw({ code: 'UNAUTHENTICATED' })\n\t\t\torganizationId = claimedOrganizationId\n\t\t\torganizationRole = claims.organization?.role ?? claims.role\n\t\t}\n\t\tconst role = config.mapRole(organizationRole)\n\t\tif (!role) return errors.throw({ code: 'FORBIDDEN' })\n\t\tconst base = {\n\t\t\tidentity,\n\t\t\tuser: Object.freeze({ id: user.id }),\n\t\t\torg: Object.freeze({ organizationId, role }),\n\t\t\trole,\n\t\t\tactor: Object.freeze({ userId: user.id, organizationId, role }),\n\t\t}\n\t\treturn Object.freeze({\n\t\t\t...base,\n\t\t\ttenant: config.security?.tenancy?.resolve?.(base) ?? organizationId,\n\t\t})\n\t}\n\n\tconst securityConfig: RLSConfig | undefined = config.security\n\t\t? {\n\t\t\t\tdefaultPolicy:\n\t\t\t\t\tconfig.security.defaultPolicy ?? (config.security.tenancy ? 'deny' : 'allow'),\n\t\t\t}\n\t\t: undefined\n\n\tfunction securityRules(\n\t\tbundle: AuthBundle<Role>,\n\t): Rules<SecurityPolicyContext<DataModel>, DataModel> | undefined {\n\t\tconst security = config.security\n\t\tif (!security) return undefined\n\t\tconst sets: Rules<SecurityPolicyContext<DataModel>, DataModel>[] = []\n\t\tif (security.tenancy) {\n\t\t\tsets.push(createTenantRules<DataModel>(bundle.tenant, security.tenancy.tables))\n\t\t}\n\t\tif (security.rules) sets.push(security.rules(bundle))\n\t\treturn sets.length === 1 ? sets[0] : composeRules(...sets)\n\t}\n\n\tfunction secureReader(\n\t\tctx: GenericQueryCtx<DataModel>,\n\t\tbundle: AuthBundle<Role>,\n\t): GenericQueryCtx<DataModel> {\n\t\tconst rules = securityRules(bundle)\n\t\tconst defaultPolicy = securityConfig?.defaultPolicy ?? 'allow'\n\t\tconst ordinary = rules\n\t\t\t? wrapDatabaseReader(\n\t\t\t\t\t{ db: ctx.db },\n\t\t\t\t\tctx.db,\n\t\t\t\t\tsuppliedPolicyRules(ctx.db, rules, defaultPolicy),\n\t\t\t\t\tsecurityConfig,\n\t\t\t\t)\n\t\t\t: ctx.db\n\t\treturn {\n\t\t\t...ctx,\n\t\t\tdb: registerQueryReader(ctx.db, ordinary, {\n\t\t\t\tscope: {\n\t\t\t\t\tmode: 'authenticated',\n\t\t\t\t\tprincipal: bundle.user.id,\n\t\t\t\t\torganization: bundle.org.organizationId,\n\t\t\t\t\ttenant: bundle.tenant,\n\t\t\t\t\trole: bundle.role,\n\t\t\t\t},\n\t\t\t\trules: rules ?? {},\n\t\t\t\tdefaultPolicy,\n\t\t\t}),\n\t\t}\n\t}\n\n\tfunction secureWriter(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\tbundle: AuthBundle<Role>,\n\t): GenericMutationCtx<DataModel> {\n\t\tconst rules = securityRules(bundle)\n\t\tif (!rules) return ctx\n\t\t// Triggers wrap first (ctx already trigger-wrapped by the caller),\n\t\t// then row-level security wraps the triggered db — order matters.\n\t\treturn {\n\t\t\t...ctx,\n\t\t\tdb: wrapDatabaseWriter(\n\t\t\t\t{ db: ctx.db },\n\t\t\t\tctx.db,\n\t\t\t\tsuppliedPolicyRules(ctx.db, rules, securityConfig?.defaultPolicy ?? 'allow'),\n\t\t\t\tsecurityConfig,\n\t\t\t),\n\t\t}\n\t}\n\n\tasync function verifiedMembership(userId: string, organizationId: string) {\n\t\tif (!config.verifyMembership) return null\n\t\ttry {\n\t\t\tconst membership = await config.verifyMembership({\n\t\t\t\tuserId,\n\t\t\t\torganizationId,\n\t\t\t})\n\t\t\tif (membership && membership.organizationId === organizationId) {\n\t\t\t\treturn membership\n\t\t\t}\n\t\t} catch {\n\t\t\t// Authentication fails closed when membership cannot be verified.\n\t\t}\n\t\treturn errors.throw({ code: 'FORBIDDEN' })\n\t}\n\n\tfunction requireRole(role: Role, allowed: readonly Role[]) {\n\t\tif (!allowed.includes(role)) return errors.throw({ code: 'FORBIDDEN' })\n\t}\n\n\tasync function queryInput(ctx: GenericQueryCtx<DataModel>) {\n\t\tconst bundle = await authenticatedUser(ctx)\n\t\treturn {\n\t\t\tctx: { ...secureReader(ctx, bundle), include, ...bundle },\n\t\t\targs: {},\n\t\t}\n\t}\n\n\tasync function mutationInput(ctx: GenericMutationCtx<DataModel>) {\n\t\tconst bundle = await authenticatedUser(ctx)\n\t\treturn {\n\t\t\tctx: { ...secureWriter(wrapDB(ctx), bundle), include, ...bundle },\n\t\t\targs: {},\n\t\t}\n\t}\n\n\tasync function actionInput(ctx: GenericActionCtx<DataModel>) {\n\t\tconst authenticated = await authenticatedUser(ctx)\n\t\tconst membership = await verifiedMembership(\n\t\t\tauthenticated.user.id,\n\t\t\tauthenticated.org.organizationId,\n\t\t)\n\t\tif (!membership) return { ctx: { ...ctx, ...authenticated }, args: {} }\n\t\tconst role = config.mapRole(membership.roleSlug)\n\t\tif (!role) return errors.throw({ code: 'FORBIDDEN' })\n\t\tconst verified = {\n\t\t\tidentity: authenticated.identity,\n\t\t\tuser: authenticated.user,\n\t\t\torg: Object.freeze({\n\t\t\t\torganizationId: membership.organizationId,\n\t\t\t\trole,\n\t\t\t}),\n\t\t\trole,\n\t\t\tactor: Object.freeze({\n\t\t\t\tuserId: authenticated.user.id,\n\t\t\t\torganizationId: membership.organizationId,\n\t\t\t\trole,\n\t\t\t}),\n\t\t}\n\t\treturn {\n\t\t\tctx: {\n\t\t\t\t...ctx,\n\t\t\t\t...verified,\n\t\t\t\t// Tenant re-derives from the live-verified organization.\n\t\t\t\ttenant: config.security?.tenancy?.resolve?.(verified) ?? membership.organizationId,\n\t\t\t},\n\t\t\targs: {},\n\t\t}\n\t}\n\n\t/** Query constructor allowing only the given roles. */\n\tfunction roleQuery(...allowed: readonly Role[]) {\n\t\treturn zCustomQuery(config.query, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst authenticated = await queryInput(ctx)\n\t\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\t\treturn authenticated\n\t\t\t},\n\t\t})\n\t}\n\n\t/** Mutation constructor allowing only the given roles. */\n\tfunction roleMutation(...allowed: readonly Role[]) {\n\t\treturn zCustomMutation(config.mutation, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst authenticated = await mutationInput(ctx)\n\t\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\t\treturn authenticated\n\t\t\t},\n\t\t})\n\t}\n\n\t/** Action constructor allowing only the given roles (post live verification). */\n\tfunction roleAction(...allowed: readonly Role[]) {\n\t\treturn zCustomAction(config.action, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst authenticated = await actionInput(ctx)\n\t\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\t\treturn authenticated\n\t\t\t},\n\t\t})\n\t}\n\n\treturn {\n\t\tinclude,\n\t\tauthenticatedUser,\n\t\troleQuery,\n\t\troleMutation,\n\t\troleAction,\n\t\tauthQuery: zCustomQuery(config.query, { args: {}, input: queryInput }),\n\t\tauthMutation: zCustomMutation(config.mutation, {\n\t\t\targs: {},\n\t\t\tinput: mutationInput,\n\t\t}),\n\t\tauthAction: zCustomAction(config.action, {\n\t\t\targs: {},\n\t\t\tinput: actionInput,\n\t\t}),\n\t\tadminQuery: roleQuery(...config.adminRoles),\n\t\tadminMutation: roleMutation(...config.adminRoles),\n\t\tadminAction: roleAction(...config.adminRoles),\n\t\tsystemQuery: zCustomQuery(config.internalQuery, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => ({\n\t\t\t\tctx: {\n\t\t\t\t\t...ctx,\n\t\t\t\t\tinclude,\n\t\t\t\t\tdb: registerQueryReader(ctx.db, ctx.db, {\n\t\t\t\t\t\tscope: {\n\t\t\t\t\t\t\tmode: 'system',\n\t\t\t\t\t\t\tprincipal: null,\n\t\t\t\t\t\t\torganization: null,\n\t\t\t\t\t\t\ttenant: null,\n\t\t\t\t\t\t\trole: null,\n\t\t\t\t\t\t},\n\t\t\t\t\t\trules: {},\n\t\t\t\t\t\tdefaultPolicy: 'allow',\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t\targs: {},\n\t\t\t}),\n\t\t}),\n\t\tsystemMutation: zCustomMutation(config.internalMutation, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => ({ ctx: { ...wrapDB(ctx), include }, args: {} }),\n\t\t}),\n\t\tsystemAction: zCustomAction(config.internalAction, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => ({ ctx, args: {} }),\n\t\t}),\n\t}\n}\n\nconst organizationClaims = z.object({\n\torganization: z\n\t\t.object({\n\t\t\torganizationId: z.string().optional().catch(undefined),\n\t\t\trole: z.string().optional().catch(undefined),\n\t\t})\n\t\t.optional()\n\t\t.catch(undefined),\n\torg_id: z.string().optional().catch(undefined),\n\trole: z.string().optional().catch(undefined),\n})\n"],"mappings":"8WAgKA,SAAgBA,EAAe,EAAuC,CACrE,IAAMC,EAAaC,GAAU,KAAK,CAAC,CAAC,YAAY,EAEhD,OADID,IAAe,SAAiB,SAC7BA,IAAe,UAAYA,IAAe,UAAYA,IAAe,QACzEA,EACA,IACJ,CA6GA,SAAgBE,EAAc,EAAgE,CAC7F,IAAMC,EAASC,GAAS,QAAUC,EAC5BC,EAAUF,GAAS,SAAW,IAEpC,SAASG,EACR,EACA,EACuB,CAMvB,eAAeC,EACd,EACA,EACC,CACD,GAAI,CAAC,OAAO,cAAcC,CAAK,GAAKA,EAAQ,GAAKA,EAAQH,EACxD,OAAOH,EAAO,MAAM,CACnB,KAAM,2BACN,QAAS,2CAA2CG,GACrD,CAAC,EAEF,IAAMI,EAAO,MAAOC,GAAYC,EAAM,cAAc,EAAA,CAAG,KAAKH,CAAK,EACjE,OAAOI,EAAYA,EAAUH,CAAI,EAAIA,CACtC,CAMA,eAAeI,EACd,EACA,EACC,CACD,GAAI,CAAC,OAAO,cAAcC,EAAK,QAAQ,GAAKA,EAAK,SAAW,GAAKA,EAAK,SAAWT,EAChF,OAAOH,EAAO,MAAM,CACnB,KAAM,2BACN,QAAS,iCAAiCG,GAC3C,CAAC,EAEF,IAAMU,EAAS,MAAOL,GAAYC,EAAM,cAAc,EAAA,CAAG,SAASG,CAAI,EACtE,OAAOF,EAAY,CAAE,GAAGG,EAAQ,KAAM,MAAMH,EAAUG,EAAO,IAAI,CAAE,EAAIA,CACxE,CACA,MAAO,CACN,MAAO,EAAO,IACbL,GAAYM,GAAiC,KAC1CV,EAAOK,EAAOD,CAAQ,EACtBJ,EAAOK,EAAOM,EAAON,EAAOK,CAAK,CAAC,EACtC,UAAW,EAAW,EAAY,EAAc,KAC/CN,GAAY,CAAC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,CACD,SAAS,CAAC,CACV,MAAM,IAAA,EAAS,EACjB,OAAQA,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,IAAA,EAAS,EAC7C,KAAMA,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,IAAA,EAAS,CAC5C,CAAC"}
|
|
@@ -5,6 +5,20 @@ import { GenericSchema, SchemaDefinition } from "convex/server";
|
|
|
5
5
|
import { z } from "zod";
|
|
6
6
|
import { Value } from "convex/values";
|
|
7
7
|
//#region src/querying/planner.d.ts
|
|
8
|
+
interface SelectionTree {
|
|
9
|
+
[name: string]: true | SelectionTree;
|
|
10
|
+
}
|
|
11
|
+
interface GroupTree {
|
|
12
|
+
relations: Record<string, GroupTree>;
|
|
13
|
+
}
|
|
14
|
+
/** What one cursor binding can depend on: a root, the path to its table and what it reads there. */
|
|
15
|
+
export interface RegistryScope {
|
|
16
|
+
readonly root: string;
|
|
17
|
+
readonly path: readonly string[];
|
|
18
|
+
readonly selection: SelectionTree;
|
|
19
|
+
readonly groups: GroupTree;
|
|
20
|
+
readonly filters: readonly FilterAst[];
|
|
21
|
+
}
|
|
8
22
|
export type QueryInput = z.input<ReturnType<ReturnType<typeof getRelationExecutor>['pagination']>>;
|
|
9
23
|
export type StoredConstraint = NonNullable<QueryInput['filters']>;
|
|
10
24
|
export declare function createPlanner(schema: SchemaDefinition<GenericSchema, boolean>, relations: RelationRegistryIdentity): {
|
|
@@ -13,8 +27,9 @@ export declare function createPlanner(schema: SchemaDefinition<GenericSchema, bo
|
|
|
13
27
|
groups: (table: string, groups: GroupSelection) => GroupSelection;
|
|
14
28
|
validateDocument: (table: string, row: Record<string, import('convex/values').Value>) => void;
|
|
15
29
|
streamSchema: SchemaDefinition<GenericSchema, boolean>;
|
|
30
|
+
registryVersion: (scope: RegistryScope) => Promise<string>;
|
|
16
31
|
beforeLeaf(table: string): void;
|
|
17
|
-
complete(table: string, document: Record<string, Value>, permitted: boolean, residual: FilterAst, groups?: readonly string[]):
|
|
32
|
+
complete(table: string, document: Record<string, Value>, permitted: boolean, residual: FilterAst, groups?: readonly string[]): any;
|
|
18
33
|
plan(table: string, input: QueryInput, conditions: readonly IndexCondition[], constraints: readonly StoredConstraint[], ordering?: string, traversal?: 'root' | 'relation'): {
|
|
19
34
|
expansion: IndexExpansion | null;
|
|
20
35
|
sets: ReadonlyMap<string, FilterScalar[]>;
|
|
@@ -44,5 +59,7 @@ export declare function createPlanner(schema: SchemaDefinition<GenericSchema, bo
|
|
|
44
59
|
};
|
|
45
60
|
};
|
|
46
61
|
export declare function scalarMatches(ast: FilterAst, document: Record<string, Value | undefined>): boolean;
|
|
62
|
+
/** Lowercase hex SHA-256 of the UTF-8 text. */
|
|
63
|
+
export declare function digest(text: string): Promise<string>;
|
|
47
64
|
//#endregion
|
|
48
65
|
//# sourceMappingURL=planner.d.mts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{evaluateFilter as e}from"./shared/evaluate.mjs";import{parseFilterPlan as t}from"./filters.mjs";import{getRelationExecutor as n,getRelationMetadata as r}from"../relations.mjs";import"convex/values";function i(e,i){let
|
|
1
|
+
import{evaluateFilter as e}from"./shared/evaluate.mjs";import{parseFilterPlan as t}from"./filters.mjs";import{getRelationExecutor as n,getRelationMetadata as r}from"../relations.mjs";import"convex/values";function i(e,i){let s=n(i);s.assertSchema(e.tables);let c=r(i),l=/* @__PURE__ */ new Map,u=/* @__PURE__ */ new Map;function d(e){let t=/* @__PURE__ */ new Set([e.root]),n=/* @__PURE__ */ new Map;function r(e,t){let r=c.declarations[e]?.[t];if(!r)throw Error(`INVALID_RELATION`);return n.set(JSON.stringify([e,t]),[e,t]),r.target}function i(e,t){for(let[n,a]of Object.entries(t)){let t=r(e,n);a!==!0&&i(t,a)}}function a(e,t){for(let[n,i]of Object.entries(t.relations))a(r(e,n),i)}function l(e,t){if(t.kind===`and`||t.kind===`or`)for(let n of t.children)l(e,n);else if(t.kind===`not`||t.kind===`variant`)l(e,t.child);else if(t.kind===`relation`){let n=r(e,t.name);t.predicate&&l(n,t.predicate)}}let d=e.root;for(let t of e.path)d=r(d,t);t.add(d),i(d,e.selection),a(d,e.groups);for(let t of e.filters)l(d,t);let f=JSON.stringify([[...t].sort(),[...n.keys()].sort()]),p=u.get(f);return p||(p=o(s.scopedIdentity([...t],[...n.values()])),u.size>=256&&u.clear(),u.set(f,p)),p}return{metadata:c,select:s.select,groups:s.groups,validateDocument:s.validateDocument,streamSchema:s.streamSchema,registryVersion:d,beforeLeaf(e){if(!Object.hasOwn(c.tables,e))throw Error(`Unknown query table`)},complete(e,t,n,r,i=[]){return s.project(e,t,()=>n&&a(r,t),i)},plan(e,n,r,i,a,o=`root`){if(!Object.hasOwn(c.tables,e))throw Error(`Unknown query table`);let u=l.get(e);u||(u=s.pagination(e),l.set(e,u));let d=i.length===1?i[0]:i.length?{and:i}:void 0,{args:f,compiled:p}=t(u,n,o===`relation`&&a===void 0?[]:c.tables[e].indexes,r,d,a);if(p.residual.kind!==`and`)throw Error(`Invalid compiled filter root`);let[m,h]=p.residual.children,g={kind:`and`,children:[]},_={kind:`and`,children:[m,g]},v=p.sets.size?{kind:`and`,children:[h,g],traversal:{version:2,expansion:p.expansion}}:{kind:`and`,children:[h,g]};return{...p,args:f,clientIdentity:_,serverIdentity:v}}}}function a(t,n){return e(t,n)===!0}async function o(e){return Array.from(new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e))),e=>e.toString(16).padStart(2,`0`)).join(``)}export{i as createPlanner,o as digest,a as scalarMatches};
|
|
2
2
|
//# sourceMappingURL=planner.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"planner.mjs","names":["createPlanner","owned","getRelationExecutor","relations","schema","metadata","getRelationMetadata","inputs","table","document","permitted","scalarMatches","residual","groups","validator","where","constraints","parseFilterPlan","input","traversal","ordering","conditions","compiled","client","server","empty","clientIdentity","serverIdentity","evaluateFilter","ast"],"sources":["../../src/querying/planner.ts"],"sourcesContent":["import { evaluateFilter } from './shared/evaluate'\nimport type { z } from 'zod'\nimport type { SchemaDefinition, GenericSchema } from 'convex/server'\nimport { type Value } from 'convex/values'\nimport {\n\tgetRelationExecutor,\n\tgetRelationMetadata,\n\ttype RelationRegistryIdentity,\n} from '../relations'\nimport { parseFilterPlan, type FilterAst, type IndexCondition } from './filters'\n\nexport type QueryInput = z.input<ReturnType<ReturnType<typeof getRelationExecutor>['pagination']>>\nexport type StoredConstraint = NonNullable<QueryInput['filters']>\n\nexport function createPlanner(\n\tschema: SchemaDefinition<GenericSchema, boolean>,\n\trelations: RelationRegistryIdentity,\n) {\n\tconst owned = getRelationExecutor(relations)\n\towned.assertSchema(schema.tables)\n\tconst metadata = getRelationMetadata(relations)\n\t// Build each immutable filter grammar only when that table is queried. Engine\n\t// declarations also load in mutations, which never need pagination validators.\n\tconst inputs = new Map<string, ReturnType<typeof owned.pagination>>()\n\treturn {\n\t\tmetadata,\n\t\tselect: owned.select,\n\t\tgroups: owned.groups,\n\t\tvalidateDocument: owned.validateDocument,\n\t\tstreamSchema: owned.streamSchema,\n\t\tbeforeLeaf(table: string) {\n\t\t\tif (!Object.hasOwn(metadata.tables, table)) throw new Error('Unknown query table')\n\t\t},\n\t\tcomplete(\n\t\t\ttable: string,\n\t\t\tdocument: Record<string, Value>,\n\t\t\tpermitted: boolean,\n\t\t\tresidual: FilterAst,\n\t\t\tgroups: readonly string[] = [],\n\t\t) {\n\t\t\treturn owned.project(\n\t\t\t\ttable,\n\t\t\t\tdocument,\n\t\t\t\t() => permitted && scalarMatches(residual, document),\n\t\t\t\tgroups,\n\t\t\t)\n\t\t},\n\t\tplan(\n\t\t\ttable: string,\n\t\t\tinput: QueryInput,\n\t\t\tconditions: readonly IndexCondition[],\n\t\t\tconstraints: readonly StoredConstraint[],\n\t\t\tordering?: string,\n\t\t\ttraversal: 'root' | 'relation' = 'root',\n\t\t) {\n\t\t\tif (!Object.hasOwn(metadata.tables, table)) throw new Error('Unknown query table')\n\t\t\tlet validator = inputs.get(table)\n\t\t\tif (!validator) {\n\t\t\t\tvalidator = owned.pagination(table)\n\t\t\t\tinputs.set(table, validator)\n\t\t\t}\n\t\t\t// Server constraints are independently validated against stored fields,\n\t\t\t// not the endpoint's public input/filter mask. Client values cannot replace them.\n\t\t\tconst where =\n\t\t\t\tconstraints.length === 1\n\t\t\t\t\t? constraints[0]\n\t\t\t\t\t: constraints.length\n\t\t\t\t\t\t? { and: constraints }\n\t\t\t\t\t\t: undefined\n\t\t\tconst { args, compiled } = parseFilterPlan(\n\t\t\t\tvalidator,\n\t\t\t\tinput,\n\t\t\t\ttraversal === 'relation' && ordering === undefined ? [] : metadata.tables[table].indexes,\n\t\t\t\tconditions,\n\t\t\t\twhere,\n\t\t\t\tordering,\n\t\t\t)\n\t\t\tif (compiled.residual.kind !== 'and') throw new Error('Invalid compiled filter root')\n\t\t\tconst [client, server] = compiled.residual.children\n\t\t\tconst empty: FilterAst = { kind: 'and', children: [] }\n\t\t\tconst clientIdentity = { kind: 'and', children: [client, empty] }\n\t\t\tconst serverIdentity = compiled.sets.size\n\t\t\t\t? {\n\t\t\t\t\t\tkind: 'and',\n\t\t\t\t\t\tchildren: [server, empty],\n\t\t\t\t\t\ttraversal: { version: 2, expansion: compiled.expansion },\n\t\t\t\t\t}\n\t\t\t\t: { kind: 'and', children: [server, empty] }\n\t\t\t// SAFETY: normalized AST nodes contain only validated native scalar Values.\n\t\t\treturn {\n\t\t\t\t...compiled,\n\t\t\t\targs,\n\t\t\t\tclientIdentity: clientIdentity as Value,\n\t\t\t\tserverIdentity: serverIdentity as Value,\n\t\t\t}\n\t\t},\n\t}\n}\n\nexport function scalarMatches(\n\tast: FilterAst,\n\tdocument: Record<string, Value | undefined>,\n): boolean {\n\treturn evaluateFilter(ast, document) === true\n}\n"],"mappings":"6MAcA,SAAgBA,EACf,EACA,EACC,CACD,IAAMC,EAAQC,EAAoBC,CAAS,EAC3CF,EAAM,aAAaG,EAAO,MAAM,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E,EAAQC,CAAK,CAAE,EAE5C,MAAO,CACN,GAAGH,EACH,OACgB,iBACA,gBACjB,CACD,CACD,CACD,CAEA,SAAgBX,EACf,EACA,EACU,CACV,OAAOiB,EAAeC,EAAKpB,CAAQ,IAAM,EAC1C"}
|
|
1
|
+
{"version":3,"file":"planner.mjs","names":["createPlanner","owned","getRelationExecutor","relations","schema","metadata","getRelationMetadata","inputs","versions","registryVersion","tables","scope","edges","walk","edge","table","name","select","nested","selection","target","group","groups","filter","ast","child","key","version","digest","document","permitted","scalarMatches","residual","validator","where","constraints","parseFilterPlan","input","traversal","ordering","conditions","compiled","client","server","empty","clientIdentity","serverIdentity","evaluateFilter","text","byte"],"sources":["../../src/querying/planner.ts"],"sourcesContent":["import { evaluateFilter } from './shared/evaluate'\nimport type { z } from 'zod'\nimport type { SchemaDefinition, GenericSchema } from 'convex/server'\nimport { type Value } from 'convex/values'\nimport {\n\tgetRelationExecutor,\n\tgetRelationMetadata,\n\ttype RelationRegistryIdentity,\n} from '../relations'\nimport { parseFilterPlan, type FilterAst, type IndexCondition } from './filters'\n\ninterface SelectionTree {\n\t[name: string]: true | SelectionTree\n}\ninterface GroupTree {\n\trelations: Record<string, GroupTree>\n}\n/** What one cursor binding can depend on: a root, the path to its table and what it reads there. */\nexport interface RegistryScope {\n\treadonly root: string\n\treadonly path: readonly string[]\n\treadonly selection: SelectionTree\n\treadonly groups: GroupTree\n\treadonly filters: readonly FilterAst[]\n}\n\nexport type QueryInput = z.input<ReturnType<ReturnType<typeof getRelationExecutor>['pagination']>>\nexport type StoredConstraint = NonNullable<QueryInput['filters']>\n\nexport function createPlanner(\n\tschema: SchemaDefinition<GenericSchema, boolean>,\n\trelations: RelationRegistryIdentity,\n) {\n\tconst owned = getRelationExecutor(relations)\n\towned.assertSchema(schema.tables)\n\tconst metadata = getRelationMetadata(relations)\n\t// Build each immutable filter grammar only when that table is queried. Engine\n\t// declarations also load in mutations, which never need pagination validators.\n\tconst inputs = new Map<string, ReturnType<typeof owned.pagination>>()\n\t// Digests per used scope; a scope is a few sorted names, so the cap only bounds abuse.\n\tconst versions = new Map<string, Promise<string>>()\n\t/**\n\t * The registry version a cursor binds: a digest of the identity of every table\n\t * and edge the query can read. That is its table, the path edges to it, and\n\t * every edge its selection, field groups and relation filters walk, with the\n\t * tables those edges touch. Nothing else can change what such a cursor means.\n\t */\n\tfunction registryVersion(scope: RegistryScope): Promise<string> {\n\t\tconst tables = new Set([scope.root])\n\t\tconst edges = new Map<string, readonly [string, string]>()\n\t\tfunction walk(table: string, name: string): string {\n\t\t\tconst edge = metadata.declarations[table]?.[name]\n\t\t\tif (!edge) throw new Error('INVALID_RELATION')\n\t\t\tedges.set(JSON.stringify([table, name]), [table, name])\n\t\t\treturn edge.target\n\t\t}\n\t\tfunction select(table: string, selection: SelectionTree): void {\n\t\t\tfor (const [name, nested] of Object.entries(selection)) {\n\t\t\t\tconst target = walk(table, name)\n\t\t\t\tif (nested !== true) select(target, nested)\n\t\t\t}\n\t\t}\n\t\tfunction group(table: string, groups: GroupTree): void {\n\t\t\tfor (const [name, nested] of Object.entries(groups.relations))\n\t\t\t\tgroup(walk(table, name), nested)\n\t\t}\n\t\tfunction filter(table: string, ast: FilterAst): void {\n\t\t\tif (ast.kind === 'and' || ast.kind === 'or')\n\t\t\t\tfor (const child of ast.children) filter(table, child)\n\t\t\telse if (ast.kind === 'not' || ast.kind === 'variant') filter(table, ast.child)\n\t\t\telse if (ast.kind === 'relation') {\n\t\t\t\tconst target = walk(table, ast.name)\n\t\t\t\tif (ast.predicate) filter(target, ast.predicate)\n\t\t\t}\n\t\t}\n\t\tlet table = scope.root\n\t\tfor (const name of scope.path) table = walk(table, name)\n\t\ttables.add(table)\n\t\tselect(table, scope.selection)\n\t\tgroup(table, scope.groups)\n\t\tfor (const ast of scope.filters) filter(table, ast)\n\t\tconst key = JSON.stringify([[...tables].sort(), [...edges.keys()].sort()])\n\t\tlet version = versions.get(key)\n\t\tif (!version) {\n\t\t\tversion = digest(owned.scopedIdentity([...tables], [...edges.values()]))\n\t\t\tif (versions.size >= 256) versions.clear()\n\t\t\tversions.set(key, version)\n\t\t}\n\t\treturn version\n\t}\n\treturn {\n\t\tmetadata,\n\t\tselect: owned.select,\n\t\tgroups: owned.groups,\n\t\tvalidateDocument: owned.validateDocument,\n\t\tstreamSchema: owned.streamSchema,\n\t\tregistryVersion,\n\t\tbeforeLeaf(table: string) {\n\t\t\tif (!Object.hasOwn(metadata.tables, table)) throw new Error('Unknown query table')\n\t\t},\n\t\tcomplete(\n\t\t\ttable: string,\n\t\t\tdocument: Record<string, Value>,\n\t\t\tpermitted: boolean,\n\t\t\tresidual: FilterAst,\n\t\t\tgroups: readonly string[] = [],\n\t\t) {\n\t\t\treturn owned.project(\n\t\t\t\ttable,\n\t\t\t\tdocument,\n\t\t\t\t() => permitted && scalarMatches(residual, document),\n\t\t\t\tgroups,\n\t\t\t)\n\t\t},\n\t\tplan(\n\t\t\ttable: string,\n\t\t\tinput: QueryInput,\n\t\t\tconditions: readonly IndexCondition[],\n\t\t\tconstraints: readonly StoredConstraint[],\n\t\t\tordering?: string,\n\t\t\ttraversal: 'root' | 'relation' = 'root',\n\t\t) {\n\t\t\tif (!Object.hasOwn(metadata.tables, table)) throw new Error('Unknown query table')\n\t\t\tlet validator = inputs.get(table)\n\t\t\tif (!validator) {\n\t\t\t\tvalidator = owned.pagination(table)\n\t\t\t\tinputs.set(table, validator)\n\t\t\t}\n\t\t\t// Server constraints are independently validated against stored fields,\n\t\t\t// not the endpoint's public input/filter mask. Client values cannot replace them.\n\t\t\tconst where =\n\t\t\t\tconstraints.length === 1\n\t\t\t\t\t? constraints[0]\n\t\t\t\t\t: constraints.length\n\t\t\t\t\t\t? { and: constraints }\n\t\t\t\t\t\t: undefined\n\t\t\tconst { args, compiled } = parseFilterPlan(\n\t\t\t\tvalidator,\n\t\t\t\tinput,\n\t\t\t\ttraversal === 'relation' && ordering === undefined ? [] : metadata.tables[table].indexes,\n\t\t\t\tconditions,\n\t\t\t\twhere,\n\t\t\t\tordering,\n\t\t\t)\n\t\t\tif (compiled.residual.kind !== 'and') throw new Error('Invalid compiled filter root')\n\t\t\tconst [client, server] = compiled.residual.children\n\t\t\tconst empty: FilterAst = { kind: 'and', children: [] }\n\t\t\tconst clientIdentity = { kind: 'and', children: [client, empty] }\n\t\t\tconst serverIdentity = compiled.sets.size\n\t\t\t\t? {\n\t\t\t\t\t\tkind: 'and',\n\t\t\t\t\t\tchildren: [server, empty],\n\t\t\t\t\t\ttraversal: { version: 2, expansion: compiled.expansion },\n\t\t\t\t\t}\n\t\t\t\t: { kind: 'and', children: [server, empty] }\n\t\t\t// SAFETY: normalized AST nodes contain only validated native scalar Values.\n\t\t\treturn {\n\t\t\t\t...compiled,\n\t\t\t\targs,\n\t\t\t\tclientIdentity: clientIdentity as Value,\n\t\t\t\tserverIdentity: serverIdentity as Value,\n\t\t\t}\n\t\t},\n\t}\n}\n\nexport function scalarMatches(\n\tast: FilterAst,\n\tdocument: Record<string, Value | undefined>,\n): boolean {\n\treturn evaluateFilter(ast, document) === true\n}\n\n/** Lowercase hex SHA-256 of the UTF-8 text. */\nexport async function digest(text: string): Promise<string> {\n\treturn Array.from(\n\t\tnew Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))),\n\t\t(byte) => byte.toString(16).padStart(2, '0'),\n\t).join('')\n}\n"],"mappings":"6MA6BA,SAAgBA,EACf,EACA,EACC,CACD,IAAMC,EAAQC,EAAoBC,CAAS,EAC3CF,EAAM,aAAaG,EAAO,MAAM,EAChC,IAAMC,EAAWC,EAAoBH,CAAS,EAGxCI,kBAAS,IAAI,IAEbC,kBAAW,IAAI,IAOrB,SAASC,EAAgB,EAAuC,CAC/D,IAAMC,kBAAS,IAAI,IAAI,CAACC,EAAM,IAAI,CAAC,EAC7BC,kBAAQ,IAAI,IAClB,SAASC,EAAK,EAAe,EAAsB,CAClD,IAAMC,EAAOT,EAAS,aAAaU,EAAM,GAAGC,GAC5C,GAAI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AACH,EAAQE,CAAK,CAAE,EAC1DE,EAAiBL,EAAS,KAAK,KAClC,CACA,KAAM,MACN,SAAU,CAACE,EAAQC,CAAK,EACxB,UAAW,CAAE,QAAS,EAAG,UAAWH,EAAS,SAAU,CACxD,EACC,CAAE,KAAM,MAAO,SAAU,CAACE,EAAQC,CAAK,CAAE,EAE5C,MAAO,CACN,GAAGH,EACH,OACgB,iBACA,gBACjB,CACD,CACD,CACD,CAEA,SAAgBV,EACf,EACA,EACU,CACV,OAAOgB,EAAevB,EAAKK,CAAQ,IAAM,EAC1C,CAGA,eAAsBD,EAAO,EAA+B,CAC3D,OAAO,MAAM,KACZ,IAAI,WAAW,MAAM,OAAO,OAAO,OAAO,UAAW,IAAI,YAAY,CAAC,CAAC,OAAOoB,CAAI,CAAC,CAAC,EACnF,GAASC,EAAK,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAC5C,CAAC,CAAC,KAAK,EAAE,CACV"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{expansionForIndex as e,rangeForIndex as t,withinRange as n}from"./filters.mjs";import{scalarMatches as r}from"./planner.mjs";import{CursorError as i}from"./cursors.mjs";import{executeStream as a,nativeIndexRange as o,rethrowQueryError as s}from"./execution.mjs";import{z as c}from"zod";import{compareValues as l}from"convex/values";import{EmptyStream as u,getIndexFields as d,stream as f}from"convex-helpers/server/stream";const p=c.object({cursor:c.string(),ancestors:c.array(c.string()).max(3)}).strict();var m=class extends Error{code;constructor(e){super(e),this.code=e,this.name=`RelationshipError`}};function h(e,t){for(let n of Object.values(e)){if(t>=4)throw new m(`INVALID_RELATION`);n!==!0&&h(n,t+1)}}function g(g,v,y,b,x,S){let C=y.metadata,w=e=>`base`in e?e.base:e;function T(e,t){let n=C.declarations[e]?.[t];if(!n)throw new m(`INVALID_RELATION`);return n}let E=(e,t)=>!t||e[t.discriminator]===t.tag,D=c.string();function O(e,t){if(!t)return!0;let n=D.safeParse(e);return n.success&&v.db.normalizeId(t.table,n.data)!==null}function k(e,t){if(!t||!E(t,e.sourceGuard))return;let n=t[w(e.from).field];return O(n,e.sourceMember)&&O(n,e.targetMember)?n:void 0}function A(e,t,n){let r=t===`_id`?{name:`by_id`,fields:[`_id`]}:C.tables[e].indexes.find(e=>{let r=e.fields.indexOf(t);return r>=0&&e.fields.slice(0,r).every(e=>e===n?.discriminator)});if(!r)throw new m(`INVALID_RELATION`);return r}function j(e,t){function n(e,t,n,r){S?.checkOrder(e,A(e,t,n).fields.filter(e=>e!==t&&e!==n?.discriminator),r)}`base`in e.from&&`base`in e.to?(n(e.from.junction.table,e.from.junction.field,e.junctionGuard),n(e.target,e.to.base.field,e.targetGuard,t)):n(e.target,w(e.to).field,e.targetGuard,t)}function M(e,t,n,r,i){let a=t===`_id`?[{name:`by_id`,fields:[`_id`]}]:C.tables[e].indexes,o=e=>e===t||e===i?.discriminator||n.bindings.has(e),s=e=>e.fields.includes(t)&&e.fields.slice(0,e.fields.indexOf(t)).every(o),c=e=>{let t=0;for(let n of e.fields){if(!o(n))break;t++}return t},l=r.find(e=>e.value!==null&&e.value!==void 0);if(l){let e=a.find(e=>e.name===l.index&&s(e));if(!e)throw Error(`Explicit index "${l.index}" is incompatible with declared relationship lookup`);return e}let u=a.filter(s).sort((e,t)=>c(t)-c(e)||Number(n.sets.has(t.fields[c(t)]))-Number(n.sets.has(e.fields[c(e)]))||Number(n.ranges.has(t.fields[c(t)]))-Number(n.ranges.has(e.fields[c(e)]))||e.name.localeCompare(t.name)||e.fields.join(`\0`).localeCompare(t.fields.join(`\0`)));if(!u.length)throw new m(`INVALID_RELATION`);return u[0]}function N(e,t,n,r,i){let a=[];for(let o of e.fields)if(o===t)a.push({field:o,value:n});else if(o===i?.discriminator)a.push({field:o,value:i.tag});else if(r?.bindings.has(o))a.push({field:o,value:r.bindings.get(o)});else break;return a}async function P(e,t){if(y.beforeLeaf(e),t==null||!v.db.normalizeId(e,t))return null;let n=await v.db.get(e,t);return n&&y.validateDocument(e,n),n}async function*F(e,t,n,r,i,a){if(v.expand(r,0),n==null||!O(n,a))return;if(t===`_id`){let o=await P(e,n);o&&E(o,i)&&O(o[t],a)&&(v.expand(r),yield o);return}y.beforeLeaf(e);let o=A(e,t,i),s=v.leafQuery(e).withIndex(o.name,e=>{let r=e;for(let e of N(o,t,n,void 0,i))r=r.eq(e.field,e.value);return r})[Symbol.asyncIterator]();try{for(;;){y.beforeLeaf(e);let n=await s.next();if(n.done)return;await v.authorize(e,n.value)&&(y.validateDocument(e,n.value),E(n.value,i)&&O(n.value[t],a)&&(v.expand(r),yield n.value))}}finally{await s.return?.()}}async function*I(e,t,n){v.expand(n,0);let r=k(e,t);if(r!=null){if(`base`in e.from&&`base`in e.to)for await(let t of F(e.from.junction.table,e.from.junction.field,r,n,e.junctionGuard))yield*F(e.target,e.to.base.field,t[e.to.junction.field],n,e.targetGuard);else yield*F(e.target,w(e.to).field,r,n,e.targetGuard,e.targetMember)}}async function L(e,t,n){let r=null;for await(let i of I(e,t,n)){if(r)throw new m(`AMBIGUOUS_RELATION`);r=i}return r}async function R(e,t,n,i=0){if(v.expand(i,0),C.tables[e].variant&&y.validateDocument(e,t),_(n))return r(n,t);if(n.kind===`variant`)return t[n.discriminator]===n.tag&&R(e,t,n.child,i);if(n.kind===`scalar`)return r(n,t);if(n.kind===`not`)return!await R(e,t,n.child,i);if(n.kind===`and`||n.kind===`or`){for(let r of n.children){let a=await R(e,t,r,i);if(n.kind===`and`&&!a)return!1;if(n.kind===`or`&&a)return!0}return n.kind===`and`}if(n.kind!==`relation`)throw new m(`INVALID_RELATION`);let a=T(e,n.name);if(n.mode===`one`){let e=await L(a,t,i+1);return n.predicate===null?e===null:e!==null&&await R(a.target,e,n.predicate,i+1)}for await(let e of I(a,t,i+1))if(await R(a.target,e,n.predicate,i+1))return n.mode===`some`;return n.mode===`none`}async function z(e,t,n,r,i=[],a=0,o=[]){v.expand(a,0);let s=y.complete(e,t,!0,{kind:`and`,children:[]},S?.allowed(i));for(let[c,l]of Object.entries(n)){let n=T(e,c),u=l===!0?{}:l;if(n.cardinality===`one`){let e=await L(n,t,a+1);s[c]=e?await z(n.target,e,u,r,[...i,c],a+1,[...o,t._id]):null}else s[c]=await V(e,t,c,u,{numItems:r.numItems,cursor:null,order:r.order},[],[],[...i,c],a+1,[...o,t._id])}return s}function B(t,n,r,a,o,s,c,l,u){if(u!==void 0&&o.some(e=>e.value!==null&&e.value!==void 0))throw Error(`orderBy cannot be combined with an active when selector`);y.select(T(t,n).target,r),h(r,c.length);let d=T(t,n);if(d.cardinality!==`many`)throw new m(`INVALID_RELATION`);let f=d.targetGuard?{fields:{[d.targetGuard.discriminator]:d.targetGuard.tag}}:void 0,g=y.plan(d.target,a,[],f?[...s,f]:s,u,`relation`),_=d.from,C=d.to,E=`base`in _&&`base`in C?{table:_.junction.table,field:_.junction.field,targetField:C.base.field,targetReference:C.junction.field}:null;if(u!==void 0&&E)throw Error(`orderBy is unsupported for junction relationships`);let D=E?E.table:d.target,O=E?E.field:w(C).field,k=M(d.target,E?E.targetField:O,g,u===void 0?o:[{value:!0,index:u}],d.targetGuard);S?.checkOrder(d.target,k.fields.filter(e=>e!==(E?E.targetField:O)&&e!==d.targetGuard?.discriminator&&!g.bindings.has(e)),c);let j=E?A(D,O,d.junctionGuard):k;E&&S?.checkOrder(D,j.fields.filter(e=>e!==O&&e!==d.junctionGuard?.discriminator));let P=E||g.unsatisfiable?null:e(j,N(j,O,null,g,d.targetGuard),g.sets,u!==void 0||o.some(e=>e.value!==null&&e.value!==void 0)),F={},I=S?.at(c);I&&(Object.keys(I.fieldGroups).length||Object.keys(I.relations).length)&&(F.fieldGroups=I);let L={...x,table:D,index:j.name,order:g.args.order??`asc`,clientFilters:g.clientIdentity,serverFilters:{predicates:g.sets.size?{predicates:g.serverIdentity,traversal:{version:2,expansion:P?{...P}:null}}:g.serverIdentity,selection:r,...F,scope:{...v.scope},rootTable:x.table,lookupIndex:k.name,guards:{source:d.sourceGuard?{...d.sourceGuard}:null,target:d.targetGuard?{...d.targetGuard}:null,junction:d.junctionGuard?{...d.junctionGuard}:null},...(d.sourceMember||d.targetMember)&&{members:{source:d.sourceMember?{...d.sourceMember}:null,target:d.targetMember?{...d.targetMember}:null}}},relationPath:c,parent:l};function R(e){try{return p.parse(JSON.parse(b.open(e,L)))}catch{throw new i}}return{declared:d,plan:g,through:E,sourceTable:D,field:O,index:j,targetIndex:k,binding:L,open:R,expansion:P}}async function V(e,r,i,s,c,p=[],m=[],h=[i],_=1,x=[],S=B(e,i,s,c,p,m,h,x[0]??r._id),C){v.expand(_,0);let{declared:T,plan:D,through:A,sourceTable:j,field:M,index:F,targetIndex:I,binding:L,expansion:V}=S,H=k(T,r),U={...D.args,...C??{cursor:null}},W={...D,expansion:V,index:F,prefix:H==null?[]:A?N(F,M,H,void 0,T.junctionGuard):N(F,M,H,D,T.targetGuard),unsatisfiable:H==null||D.unsatisfiable};if(W.range=A?null:t(F,W.prefix,D.ranges),!A)for(let e of W.prefix){let t=D.ranges.get(e.field);D.bindings.has(e.field)&&l(e.value,D.bindings.get(e.field))!==0&&(W.unsatisfiable=!0),t&&!n(e.value,t)&&(W.unsatisfiable=!0)}let G=A&&A.targetField!==`_id`;return await a(g,v,j,W,y,b,L,U,async(e,t)=>{if(t&&y.validateDocument(G?T.target:j,e),!t||A&&!G&&!E(e,T.junctionGuard))return null;v.expand(_);let n;return n=A&&!G?await P(T.target,e[A.targetReference]):e,!n||!E(n,T.targetGuard)||!O(n[w(T.to).field],T.targetMember)||!await R(T.target,n,D.residual,_)?null:z(T.target,n,s,D.args,h,_,x)},e=>b.seal(JSON.stringify({cursor:e,ancestors:x.slice(1)}),L),G?(e,n)=>{let r=g,i=d(T.target,I.name,r);return e.flatMap(async e=>{v.expand(_);let a=await v.authorize(j,e);a&&y.validateDocument(j,e);let s=e[A.targetReference];return!a||!E(e,T.junctionGuard)||s==null?new u(D.args.order??`asc`,i):f(n,r).query(T.target).withIndex(I.name,e=>{let n=N(I,A.targetField,s,D,T.targetGuard);return o(e,n,t(I,n,D.ranges))}).order(D.args.order??`asc`)},i)}:void 0,G?T.target:j)}async function H(e,t,n,r,a,o,c,u){if(!n.length||n.length>4||!v.db.normalizeId(e,t))throw new m(`INVALID_RELATION`);let d=e,f=n.map(e=>{let t=T(d,e);return d=t.target,t});if(u!==void 0&&f.some(e=>`base`in e.from||`base`in e.to))throw Error(`orderBy is unsupported for junction relationships`);let p=f.at(-1);for(let e of f.slice(0,-1))(e.cardinality===`one`||`base`in e.from||`base`in e.to)&&j(e);let h=B(p.source,n.at(-1),r,a,o,c,n,t,u),g=a.cursor===null?null:h.open(a.cursor),_=a.endCursor==null?null:h.open(a.endCursor),y=g?.ancestors??_?.ancestors??[];if(y.length!==n.length-1||g&&_&&JSON.stringify(g.ancestors)!==JSON.stringify(_.ancestors)||y.some((e,t)=>!v.db.normalizeId(f[t].target,e)))throw new i;try{let i=await P(e,t);for(let e=0;i&&e<y.length;e++){let t=f[e],n=null;if(t.cardinality===`many`&&!(`base`in t.from)&&!(`base`in t.to)){v.expand(e+1,0);let r=k(t,i),a=r==null?null:await P(t.target,y[e]),o=t.to.field;r!=null&&a&&E(a,t.targetGuard)&&O(a[o],t.targetMember)&&a[o]!==void 0&&l(r,a[o])===0&&(v.expand(e+1),n=a)}else if(t.cardinality===`one`){let r=await L(t,i,e+1);r?._id===y[e]&&(n=r)}else for await(let r of I(t,i,e+1))if(r._id===y[e]){n=r;break}i=n}return await V(p.source,i,n.at(-1),r,a,o,c,n,n.length,[t,...y],h,{cursor:g?.cursor??null,endCursor:_?.cursor??a.endCursor})}catch(e){s(e)}}function U(e,t,n,r=[]){for(let[i,a]of Object.entries(t)){let t=T(e,i),o=a===!0?{}:a,s=[...r,i];t.cardinality===`many`?B(e,i,o,{numItems:n.numItems,cursor:null,order:n.order},[],[],s,``):j(t,s),U(t.target,o,n,s)}}return{matches:R,output:z,continuation:H,edge:T,preflight:U}}function _(e){return e.kind===`relation`?!1:e.kind===`and`||e.kind===`or`?e.children.every(_):e.kind===`not`||e.kind===`variant`?_(e.child):!0}export{m as RelationshipError,h as assertRelationshipDepth,g as relationshipExecutor};
|
|
1
|
+
import{expansionForIndex as e,rangeForIndex as t,withinRange as n}from"./filters.mjs";import{scalarMatches as r}from"./planner.mjs";import{CursorError as i}from"./cursors.mjs";import{executeStream as a,nativeIndexRange as o,rethrowQueryError as s}from"./execution.mjs";import{z as c}from"zod";import{compareValues as l}from"convex/values";import{EmptyStream as u,getIndexFields as d,stream as f}from"convex-helpers/server/stream";const p={fieldGroups:{},relations:{}},m=c.object({cursor:c.string(),ancestors:c.array(c.string()).max(3)}).strict();var h=class extends Error{code;constructor(e){super(e),this.code=e,this.name=`RelationshipError`}};function g(e,t){for(let n of Object.values(e)){if(t>=4)throw new h(`INVALID_RELATION`);n!==!0&&g(n,t+1)}}function _(_,y,b,x,S,C){let w=b.metadata,T=e=>`base`in e?e.base:e;function E(e,t){let n=w.declarations[e]?.[t];if(!n)throw new h(`INVALID_RELATION`);return n}let D=(e,t)=>!t||e[t.discriminator]===t.tag,O=c.string();function k(e,t){if(!t)return!0;let n=O.safeParse(e);return n.success&&y.db.normalizeId(t.table,n.data)!==null}function A(e,t){if(!t||!D(t,e.sourceGuard))return;let n=t[T(e.from).field];return k(n,e.sourceMember)&&k(n,e.targetMember)?n:void 0}function j(e,t,n){let r=t===`_id`?{name:`by_id`,fields:[`_id`]}:w.tables[e].indexes.find(e=>{let r=e.fields.indexOf(t);return r>=0&&e.fields.slice(0,r).every(e=>e===n?.discriminator)});if(!r)throw new h(`INVALID_RELATION`);return r}function M(e,t){function n(e,t,n,r){C?.checkOrder(e,j(e,t,n).fields.filter(e=>e!==t&&e!==n?.discriminator),r)}`base`in e.from&&`base`in e.to?(n(e.from.junction.table,e.from.junction.field,e.junctionGuard),n(e.target,e.to.base.field,e.targetGuard,t)):n(e.target,T(e.to).field,e.targetGuard,t)}function N(e,t,n,r,i){let a=t===`_id`?[{name:`by_id`,fields:[`_id`]}]:w.tables[e].indexes,o=e=>e===t||e===i?.discriminator||n.bindings.has(e),s=e=>e.fields.includes(t)&&e.fields.slice(0,e.fields.indexOf(t)).every(o),c=e=>{let t=0;for(let n of e.fields){if(!o(n))break;t++}return t},l=r.find(e=>e.value!==null&&e.value!==void 0);if(l){let e=a.find(e=>e.name===l.index&&s(e));if(!e)throw Error(`Explicit index "${l.index}" is incompatible with declared relationship lookup`);return e}let u=a.filter(s).sort((e,t)=>c(t)-c(e)||Number(n.sets.has(t.fields[c(t)]))-Number(n.sets.has(e.fields[c(e)]))||Number(n.ranges.has(t.fields[c(t)]))-Number(n.ranges.has(e.fields[c(e)]))||e.name.localeCompare(t.name)||e.fields.join(`\0`).localeCompare(t.fields.join(`\0`)));if(!u.length)throw new h(`INVALID_RELATION`);return u[0]}function P(e,t,n,r,i){let a=[];for(let o of e.fields)if(o===t)a.push({field:o,value:n});else if(o===i?.discriminator)a.push({field:o,value:i.tag});else if(r?.bindings.has(o))a.push({field:o,value:r.bindings.get(o)});else break;return a}async function F(e,t){if(b.beforeLeaf(e),t==null||!y.db.normalizeId(e,t))return null;let n=await y.db.get(e,t);return n&&b.validateDocument(e,n),n}async function*I(e,t,n,r,i,a){if(y.expand(r,0),n==null||!k(n,a))return;if(t===`_id`){let o=await F(e,n);o&&D(o,i)&&k(o[t],a)&&(y.expand(r),yield o);return}b.beforeLeaf(e);let o=j(e,t,i),s=y.leafQuery(e).withIndex(o.name,e=>{let r=e;for(let e of P(o,t,n,void 0,i))r=r.eq(e.field,e.value);return r})[Symbol.asyncIterator]();try{for(;;){b.beforeLeaf(e);let n=await s.next();if(n.done)return;await y.authorize(e,n.value)&&(b.validateDocument(e,n.value),D(n.value,i)&&k(n.value[t],a)&&(y.expand(r),yield n.value))}}finally{await s.return?.()}}async function*L(e,t,n){y.expand(n,0);let r=A(e,t);if(r!=null){if(`base`in e.from&&`base`in e.to)for await(let t of I(e.from.junction.table,e.from.junction.field,r,n,e.junctionGuard))yield*I(e.target,e.to.base.field,t[e.to.junction.field],n,e.targetGuard);else yield*I(e.target,T(e.to).field,r,n,e.targetGuard,e.targetMember)}}async function R(e,t,n){let r=null;for await(let i of L(e,t,n)){if(r)throw new h(`AMBIGUOUS_RELATION`);r=i}return r}async function z(e,t,n,i=0){if(y.expand(i,0),w.tables[e].variant&&b.validateDocument(e,t),v(n))return r(n,t);if(n.kind===`variant`)return t[n.discriminator]===n.tag&&z(e,t,n.child,i);if(n.kind===`scalar`)return r(n,t);if(n.kind===`not`)return!await z(e,t,n.child,i);if(n.kind===`and`||n.kind===`or`){for(let r of n.children){let a=await z(e,t,r,i);if(n.kind===`and`&&!a)return!1;if(n.kind===`or`&&a)return!0}return n.kind===`and`}if(n.kind!==`relation`)throw new h(`INVALID_RELATION`);let a=E(e,n.name);if(n.mode===`one`){let e=await R(a,t,i+1);return n.predicate===null?e===null:e!==null&&await z(a.target,e,n.predicate,i+1)}for await(let e of L(a,t,i+1))if(await z(a.target,e,n.predicate,i+1))return n.mode===`some`;return n.mode===`none`}async function B(e,t,n,r,i=[],a=0,o=[]){y.expand(a,0);let s=b.complete(e,t,!0,{kind:`and`,children:[]},C?.allowed(i));for(let[c,l]of Object.entries(n)){let n=E(e,c),u=l===!0?{}:l;if(n.cardinality===`one`){let e=await R(n,t,a+1);s[c]=e?await B(n.target,e,u,r,[...i,c],a+1,[...o,t._id]):null}else s[c]=await H(e,t,c,u,{numItems:r.numItems,cursor:null,order:r.order},[],[],[...i,c],a+1,[...o,t._id])}return s}function V(t,n,r,a,o,s,c,l,u){if(u!==void 0&&o.some(e=>e.value!==null&&e.value!==void 0))throw Error(`orderBy cannot be combined with an active when selector`);b.select(E(t,n).target,r),g(r,c.length);let d=E(t,n);if(d.cardinality!==`many`)throw new h(`INVALID_RELATION`);let f=d.targetGuard?{fields:{[d.targetGuard.discriminator]:d.targetGuard.tag}}:void 0,_=b.plan(d.target,a,[],f?[...s,f]:s,u,`relation`),v=d.from,w=d.to,D=`base`in v&&`base`in w?{table:v.junction.table,field:v.junction.field,targetField:w.base.field,targetReference:w.junction.field}:null;if(u!==void 0&&D)throw Error(`orderBy is unsupported for junction relationships`);let O=D?D.table:d.target,k=D?D.field:T(w).field,A=N(d.target,D?D.targetField:k,_,u===void 0?o:[{value:!0,index:u}],d.targetGuard);C?.checkOrder(d.target,A.fields.filter(e=>e!==(D?D.targetField:k)&&e!==d.targetGuard?.discriminator&&!_.bindings.has(e)),c);let M=D?j(O,k,d.junctionGuard):A;D&&C?.checkOrder(O,M.fields.filter(e=>e!==k&&e!==d.junctionGuard?.discriminator));let F=D||_.unsatisfiable?null:e(M,P(M,k,null,_,d.targetGuard),_.sets,u!==void 0||o.some(e=>e.value!==null&&e.value!==void 0)),I={},L=C?.at(c);L&&(Object.keys(L.fieldGroups).length||Object.keys(L.relations).length)&&(I.fieldGroups=L);let R={...S,table:O,index:M.name,order:_.args.order??`asc`,clientFilters:_.clientIdentity,serverFilters:{predicates:_.sets.size?{predicates:_.serverIdentity,traversal:{version:2,expansion:F?{...F}:null}}:_.serverIdentity,selection:r,...I,scope:{...y.scope},rootTable:S.table,lookupIndex:A.name,guards:{source:d.sourceGuard?{...d.sourceGuard}:null,target:d.targetGuard?{...d.targetGuard}:null,junction:d.junctionGuard?{...d.junctionGuard}:null},...(d.sourceMember||d.targetMember)&&{members:{source:d.sourceMember?{...d.sourceMember}:null,target:d.targetMember?{...d.targetMember}:null}}},relationPath:c,parent:l},z;function B(){return z??=b.registryVersion({root:S.table,path:c,selection:r,groups:L??p,filters:[_.residual]}).then(e=>({...R,registryVersion:e})),z}async function V(e){try{return m.parse(JSON.parse(x.open(e,await B())))}catch{throw new i}}return{declared:d,plan:_,through:D,sourceTable:O,field:k,index:M,targetIndex:A,bind:B,open:V,expansion:F}}async function H(e,r,i,s,c,p=[],m=[],h=[i],g=1,v=[],S=V(e,i,s,c,p,m,h,v[0]??r._id),C){y.expand(g,0);let{declared:w,plan:E,through:O,sourceTable:j,field:M,index:N,targetIndex:I,expansion:L}=S,R=await S.bind(),H=A(w,r),U={...E.args,...C??{cursor:null}},W={...E,expansion:L,index:N,prefix:H==null?[]:O?P(N,M,H,void 0,w.junctionGuard):P(N,M,H,E,w.targetGuard),unsatisfiable:H==null||E.unsatisfiable};if(W.range=O?null:t(N,W.prefix,E.ranges),!O)for(let e of W.prefix){let t=E.ranges.get(e.field);E.bindings.has(e.field)&&l(e.value,E.bindings.get(e.field))!==0&&(W.unsatisfiable=!0),t&&!n(e.value,t)&&(W.unsatisfiable=!0)}let G=O&&O.targetField!==`_id`;return await a(_,y,j,W,b,x,R,U,async(e,t)=>{if(t&&b.validateDocument(G?w.target:j,e),!t||O&&!G&&!D(e,w.junctionGuard))return null;y.expand(g);let n;return n=O&&!G?await F(w.target,e[O.targetReference]):e,!n||!D(n,w.targetGuard)||!k(n[T(w.to).field],w.targetMember)||!await z(w.target,n,E.residual,g)?null:B(w.target,n,s,E.args,h,g,v)},e=>x.seal(JSON.stringify({cursor:e,ancestors:v.slice(1)}),R),G?(e,n)=>{let r=_,i=d(w.target,I.name,r);return e.flatMap(async e=>{y.expand(g);let a=await y.authorize(j,e);a&&b.validateDocument(j,e);let s=e[O.targetReference];return!a||!D(e,w.junctionGuard)||s==null?new u(E.args.order??`asc`,i):f(n,r).query(w.target).withIndex(I.name,e=>{let n=P(I,O.targetField,s,E,w.targetGuard);return o(e,n,t(I,n,E.ranges))}).order(E.args.order??`asc`)},i)}:void 0,G?w.target:j)}async function U(e,t,n,r,a,o,c,u){if(!n.length||n.length>4||!y.db.normalizeId(e,t))throw new h(`INVALID_RELATION`);let d=e,f=n.map(e=>{let t=E(d,e);return d=t.target,t});if(u!==void 0&&f.some(e=>`base`in e.from||`base`in e.to))throw Error(`orderBy is unsupported for junction relationships`);let p=f.at(-1);for(let e of f.slice(0,-1))(e.cardinality===`one`||`base`in e.from||`base`in e.to)&&M(e);let m=V(p.source,n.at(-1),r,a,o,c,n,t,u),g=a.cursor===null?null:await m.open(a.cursor),_=a.endCursor==null?null:await m.open(a.endCursor),v=g?.ancestors??_?.ancestors??[];if(v.length!==n.length-1||g&&_&&JSON.stringify(g.ancestors)!==JSON.stringify(_.ancestors)||v.some((e,t)=>!y.db.normalizeId(f[t].target,e)))throw new i;try{let i=await F(e,t);for(let e=0;i&&e<v.length;e++){let t=f[e],n=null;if(t.cardinality===`many`&&!(`base`in t.from)&&!(`base`in t.to)){y.expand(e+1,0);let r=A(t,i),a=r==null?null:await F(t.target,v[e]),o=t.to.field;r!=null&&a&&D(a,t.targetGuard)&&k(a[o],t.targetMember)&&a[o]!==void 0&&l(r,a[o])===0&&(y.expand(e+1),n=a)}else if(t.cardinality===`one`){let r=await R(t,i,e+1);r?._id===v[e]&&(n=r)}else for await(let r of L(t,i,e+1))if(r._id===v[e]){n=r;break}i=n}return await H(p.source,i,n.at(-1),r,a,o,c,n,n.length,[t,...v],m,{cursor:g?.cursor??null,endCursor:_?.cursor??a.endCursor})}catch(e){s(e)}}function W(e,t,n,r=[]){for(let[i,a]of Object.entries(t)){let t=E(e,i),o=a===!0?{}:a,s=[...r,i];t.cardinality===`many`?V(e,i,o,{numItems:n.numItems,cursor:null,order:n.order},[],[],s,``):M(t,s),W(t.target,o,n,s)}}return{matches:z,output:B,continuation:U,edge:E,preflight:W}}function v(e){return e.kind===`relation`?!1:e.kind===`and`||e.kind===`or`?e.children.every(v):e.kind===`not`||e.kind===`variant`?v(e.child):!0}export{h as RelationshipError,g as assertRelationshipDepth,_ as relationshipExecutor};
|
|
2
2
|
//# sourceMappingURL=relationships.mjs.map
|