cvx-kit 0.1.29 → 0.1.30

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 CHANGED
@@ -72,6 +72,26 @@ Guides:
72
72
  - [`migration.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/migration.md) — restructuring an existing raw Convex project into this architecture
73
73
  - [`llms.md`](https://github.com/ImRLopezAG/cvx-kit/blob/main/skills/cvx-kit/references/llms.md) — optional condensed reference for coding agents
74
74
 
75
+ ## Per-request import cost
76
+
77
+ Convex evaluates a function's whole static import graph on every request, and queries and mutations cannot use dynamic `import()`. Whatever a module builds at import is paid on every call. The kit builders do not convert validators at registration. Convex reads them when it exports function metadata at push, and the handler builds its parse state on first call. To keep a module from building schemas for functions it is not serving, declare them lazily:
78
+
79
+ ```ts
80
+ export const listPayments = authQuery({
81
+ get args() {
82
+ return financeContract.queries.listPayments.input
83
+ },
84
+ get returns() {
85
+ return financeContract.queries.listPayments.result
86
+ },
87
+ handler: (ctx, args) => ctx.queries.finance.exec('listPayments', args),
88
+ })
89
+ ```
90
+
91
+ With `args: contract.queries.x.input`, the property read builds the schema at import. A getter defers it. Declare contract operations as getters too (see the [domain contracts guide](./skills/cvx-kit/references/domain-contracts.md)), so that reading or executing one operation builds and binds only that operation. Keep the trigger registry out of query modules with `createAuthReaders` (see `cvx-kit/auth` below). Validation is identical in every form.
92
+
93
+ Two more things keep the deferral intact. First, a `paginationOpts(...)` or `pageDto(...)` call at module scope outside a contract still builds at import, so put it behind a getter or inside the operation that uses it. Second, pass Convex's generated builders (`query`, `mutation`, ...) to the kit constructors. A wrapper that spreads or copies the definition reads its getters at registration.
94
+
75
95
  ## Modules
76
96
 
77
97
  ### `cvx-kit/zod-table`
@@ -392,6 +412,38 @@ registry structurally; `include()` bounds every read (default 100 rows).
392
412
  `resolveOrganization` derives org and role from your own tables, enabling
393
413
  identity providers whose tokens carry no org claims.
394
414
 
415
+ Convex evaluates a function's whole static import graph on every request, and
416
+ queries and mutations cannot use dynamic `import()`. Passing `triggers` here
417
+ makes every module that imports these constructors, queries included, load
418
+ every domain the trigger registry imports. Split the constructors:
419
+
420
+ ```ts
421
+ // convex/functions/base.ts — no trigger import
422
+ export const base = {
423
+ query,
424
+ action,
425
+ internalQuery,
426
+ internalAction,
427
+ getAuthUser,
428
+ mapRole,
429
+ adminRoles,
430
+ }
431
+ // convex/functions/read.ts — never imports the trigger registry
432
+ export const { authQuery, adminQuery, authAction, include } = createAuthReaders<DataModel>(base)
433
+ // convex/functions/write.ts
434
+ export const { authMutation, systemMutation } = createAuthFunctions<DataModel>({
435
+ ...base,
436
+ mutation,
437
+ internalMutation,
438
+ triggers,
439
+ })
440
+ ```
441
+
442
+ Query and action modules import only from `read.ts`. `createAuthReaders`
443
+ shares the implementation, so identity, tenancy, rules, and role gates match;
444
+ it has no mutation constructors. `createEffectAuthFunctions` has no reader
445
+ variant yet.
446
+
395
447
  ### `cvx-kit/effect` — commands and queries
396
448
 
397
449
  Use the Effect API for new commands. Install Effect `>=4.0.1 <5`, bind host
package/dist/auth.d.mts CHANGED
@@ -71,13 +71,16 @@ export type SecurityConfig<DataModel extends GenericDataModel, Role extends stri
71
71
  defaultPolicy?: RLSConfig['defaultPolicy'];
72
72
  };
73
73
  type AnyAuthContext<DataModel extends GenericDataModel> = GenericQueryCtx<DataModel> | GenericMutationCtx<DataModel> | GenericActionCtx<DataModel>;
74
- export type AuthFunctionsConfig<DataModel extends GenericDataModel, Role extends string> = {
74
+ /**
75
+ * Configuration for createAuthReaders: everything createAuthFunctions takes
76
+ * except the mutation builders and trigger wrapping, so a module built from
77
+ * it never has to import the trigger registry.
78
+ */
79
+ export type AuthReadersConfig<DataModel extends GenericDataModel, Role extends string> = {
75
80
  /** The consumer's generated function builders (from ./_generated/server). */
76
81
  query: QueryBuilder<DataModel, 'public'>;
77
- mutation: MutationBuilder<DataModel, 'public'>;
78
82
  action: ActionBuilder<DataModel, 'public'>;
79
83
  internalQuery: QueryBuilder<DataModel, 'internal'>;
80
- internalMutation: MutationBuilder<DataModel, 'internal'>;
81
84
  internalAction: ActionBuilder<DataModel, 'internal'>;
82
85
  /**
83
86
  * Resolves the synchronized principal, e.g. (ctx) => authKit.getAuthUser(ctx).
@@ -124,14 +127,6 @@ export type AuthFunctionsConfig<DataModel extends GenericDataModel, Role extends
124
127
  } | null>;
125
128
  /** Host error policy; defaults to throwing KitError. */
126
129
  errors?: ErrorFactory;
127
- /**
128
- * Application trigger registry. When set, every authMutation,
129
- * roleMutation, and systemMutation write runs through triggers.wrapDB —
130
- * evaluations registered on tables fire structurally.
131
- */
132
- triggers?: Triggers<DataModel>;
133
- /** Lower-level alternative to `triggers`: a custom ctx wrapper. */
134
- wrapDB?: (ctx: GenericMutationCtx<DataModel>) => GenericMutationCtx<DataModel>;
135
130
  /** Upper bound for include() reads. */
136
131
  maxIncludedQueryRows?: number;
137
132
  /**
@@ -142,6 +137,19 @@ export type AuthFunctionsConfig<DataModel extends GenericDataModel, Role extends
142
137
  */
143
138
  security?: SecurityConfig<DataModel, Role>;
144
139
  };
140
+ /** A reader config plus the mutation builders and trigger wrapping. */
141
+ export type AuthFunctionsConfig<DataModel extends GenericDataModel, Role extends string> = AuthReadersConfig<DataModel, Role> & {
142
+ mutation: MutationBuilder<DataModel, 'public'>;
143
+ internalMutation: MutationBuilder<DataModel, 'internal'>;
144
+ /**
145
+ * Application trigger registry. When set, every authMutation,
146
+ * roleMutation, and systemMutation write runs through triggers.wrapDB —
147
+ * evaluations registered on tables fire structurally.
148
+ */
149
+ triggers?: Triggers<DataModel>;
150
+ /** Lower-level alternative to `triggers`: a custom ctx wrapper. */
151
+ wrapDB?: (ctx: GenericMutationCtx<DataModel>) => GenericMutationCtx<DataModel>;
152
+ };
145
153
  /** WorkOS-style default: `member` writes; reader/writer/admin pass through. */
146
154
  export declare function defaultRoleMap(roleSlug?: string): DefaultRole | null;
147
155
  export type IncludedQuery<Table extends GenericTableInfo> = {
@@ -198,6 +206,8 @@ export type AuthFunctions<DataModel extends GenericDataModel, Role extends strin
198
206
  }, {}, GenericMutationCtx<DataModel>, 'internal', object>;
199
207
  systemAction: CustomBuilder<'action', {}, GenericActionCtx<DataModel>, {}, GenericActionCtx<DataModel>, 'internal', object>;
200
208
  };
209
+ /** The read-only constructors: everything AuthFunctions has except mutations. */
210
+ export type AuthReaders<DataModel extends GenericDataModel, Role extends string = DefaultRole> = Omit<AuthFunctions<DataModel, Role>, `${string}Mutation`>;
201
211
  export type ServiceQuery<DataModel extends GenericDataModel, Role extends string, Extra extends Record<string, unknown> = {}> = CustomBuilder<'query', {}, GenericQueryCtx<DataModel> & AuthBundle<Role> & Extra & {
202
212
  include: Include;
203
213
  }, {}, GenericQueryCtx<DataModel>, 'internal', object>;
@@ -218,6 +228,14 @@ export declare function createInclude(options?: {
218
228
  * admin* constructors are just that gate applied to config.adminRoles.
219
229
  */
220
230
  export declare function createAuthFunctions<DataModel extends GenericDataModel, const Role extends string = DefaultRole>(config: AuthFunctionsConfig<DataModel, Role>): AuthFunctions<DataModel, Role>;
231
+ /**
232
+ * Builds the read-only constructors (queries and actions) from the same
233
+ * policy as createAuthFunctions, without mutation builders or triggers.
234
+ * Identity, tenancy, rules, role gates, membership checks and errors are the
235
+ * same implementation, so a module built from these never imports the
236
+ * trigger registry or the domains it pulls in.
237
+ */
238
+ export declare function createAuthReaders<DataModel extends GenericDataModel, const Role extends string = DefaultRole>(config: AuthReadersConfig<DataModel, Role>): AuthReaders<DataModel, Role>;
221
239
  //#endregion
222
240
  export type { SecurityPolicyContext };
223
241
  //# sourceMappingURL=auth.d.mts.map
package/dist/auth.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{rawFunctionArgs as e,zCustomAction as t,zCustomMutation as n,zCustomQuery as r}from"./zod-registration.mjs";import{defaultErrors as i}from"./errors.mjs";import{registerQueryReader as a,suppliedPolicyRules as o}from"./querying/security.mjs";import{composeRules as s,createTenantRules as c,wrapDatabaseReader as l,wrapDatabaseWriter as u}from"./tenancy.mjs";import{z as d}from"zod";function f(e){let t=e?.trim().toLowerCase();return t===`member`?`writer`:t===`reader`||t===`writer`||t===`admin`?t:null}function p(e){let t=e?.errors??i,n=e?.maxRows??100;function r(e,i){async function a(r,a){if(!Number.isSafeInteger(r)||r<1||r>n)return t.throw({code:`INVALID_REQUEST_BOUNDARY`,message:`A bounded query limit must be from 1 to ${n}`});let o=await(i??e.fullTableScan()).take(r);return a?a(o):o}async function o(r,a){if(!Number.isSafeInteger(r.numItems)||r.numItems<1||r.numItems>n)return t.throw({code:`INVALID_REQUEST_BOUNDARY`,message:`A page size must be from 1 to ${n}`});let o=await(i??e.fullTableScan()).paginate(r);return a?{...o,page:await a(o.page)}:o}return{when:(t,n)=>i||t==null?r(e,i):r(e,n(e,t)),matching:(t,n,a=!0)=>i||!a?r(e,i):r(e,e.withIndex(t,n)),otherwise:t=>i??t(e),resolve:()=>i??e.fullTableScan(),execute:a,paginate:o}}return e=>r(e)}function m(d){let f=d.errors??i,m=d.triggers,_=m?e=>m.wrapDB(e):d.wrapDB??(e=>e),v=p({errors:f,maxRows:d.maxIncludedQueryRows});async function y(e){let t=await e.auth.getUserIdentity(),n=t?await d.getAuthUser(e,t):null;if(!t||!n)return f.throw({code:`UNAUTHENTICATED`});let r,i;if(d.resolveOrganization){let a=null;try{a=await d.resolveOrganization({ctx:e,identity:t,user:n})}catch{}if(!a)return f.throw({code:`FORBIDDEN`});r=a.organizationId,i=a.roleSlug}else{let e=g.parse(t),n=e.organization?.organizationId??e.org_id;if(!n)return f.throw({code:`UNAUTHENTICATED`});r=n,i=e.organization?.role??e.role}let a=d.mapRole(i);if(!a)return f.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:d.security?.tenancy?.resolve?.(o)??r})}let b=d.security?{defaultPolicy:d.security.defaultPolicy??(d.security.tenancy?`deny`:`allow`)}:void 0;function x(e){let t=d.security;if(!t)return;let n=[];return t.tenancy&&n.push(c(e.tenant,t.tenancy.tables)),t.rules&&n.push(t.rules(e)),n.length===1?n[0]:s(...n)}function S(e,t,n=`authenticated`){let r=x(t),i=b?.defaultPolicy??`allow`,s=r?l({db:e.db},e.db,o(e.db,r,i),b):e.db;return{...e,db:a(e.db,s,{scope:{mode:n,principal:t.user.id,organization:t.org.organizationId,tenant:t.tenant,role:t.role},rules:r??{},defaultPolicy:i})}}function C(e,t){let n=x(t);return n?{...e,db:u({db:e.db},e.db,o(e.db,n,b?.defaultPolicy??`allow`),b)}:e}async function w(e,t){if(!d.verifyMembership)return null;try{let n=await d.verifyMembership({userId:e,organizationId:t});if(n&&n.organizationId===t)return n}catch{}return f.throw({code:`FORBIDDEN`})}function T(e,t){if(!t.includes(e))return f.throw({code:`FORBIDDEN`})}async function E(e){let t=await y(e);return{ctx:{...S(e,t),include:v,...t},args:{}}}async function D(e){let t=await y(e);return{ctx:{...C(_(e),t),include:v,...t},args:{}}}async function O(e){let t=await y(e),n=await w(t.user.id,t.org.organizationId);if(!n)return{ctx:{...e,...t},args:{}};let r=d.mapRole(n.roleSlug);if(!r)return f.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:d.security?.tenancy?.resolve?.(i)??n.organizationId},args:{}}}async function k(t,n){let r=await t(n,e(n));if(!h.safeParse(r).success)throw Error(`A service principal must be an AuthBundle with user.id and tenant`);let i=Object.keys(r).filter(e=>e in n);if(i.length>0)throw Error(`A service principal cannot override native context fields: ${i.join(`, `)}`);return r}function A(e){return r(d.internalQuery,{args:{},input:async t=>{let n=await k(e,t);return{ctx:{...S(t,n,`trusted`),...n,include:v},args:{}}}})}function j(e){return n(d.internalMutation,{args:{},input:async t=>{let n=await k(e,t);return{ctx:{...C(_(t),n),...n,include:v},args:{}}}})}function M(...e){return r(d.query,{args:{},input:async t=>{let n=await E(t);return T(n.ctx.actor.role,e),n}})}function N(...e){return n(d.mutation,{args:{},input:async t=>{let n=await D(t);return T(n.ctx.actor.role,e),n}})}function P(...e){return t(d.action,{args:{},input:async t=>{let n=await O(t);return T(n.ctx.actor.role,e),n}})}return{include:v,authenticatedUser:y,roleQuery:M,roleMutation:N,roleAction:P,authQuery:r(d.query,{args:{},input:E}),authMutation:n(d.mutation,{args:{},input:D}),authAction:t(d.action,{args:{},input:O}),adminQuery:M(...d.adminRoles),adminMutation:N(...d.adminRoles),adminAction:P(...d.adminRoles),serviceQuery:A,serviceMutation:j,systemQuery:r(d.internalQuery,{args:{},input:async e=>({ctx:{...e,include:v,db:a(e.db,e.db,{scope:{mode:`system`,principal:null,organization:null,tenant:null,role:null},rules:{},defaultPolicy:`allow`})},args:{}})}),systemMutation:n(d.internalMutation,{args:{},input:async e=>({ctx:{..._(e),include:v},args:{}})}),systemAction:t(d.internalAction,{args:{},input:async e=>({ctx:e,args:{}})})}}const h=d.object({user:d.object({id:d.string()}),tenant:d.string()}),g=d.object({organization:d.object({organizationId:d.string().optional().catch(void 0),role:d.string().optional().catch(void 0)}).optional().catch(void 0),org_id:d.string().optional().catch(void 0),role:d.string().optional().catch(void 0)});export{m as createAuthFunctions,p as createInclude,f as defaultRoleMap};
1
+ import{rawFunctionArgs as e,zCustomAction as t,zCustomMutation as n,zCustomQuery as r}from"./zod-registration.mjs";import{defaultErrors as i}from"./errors.mjs";import{registerQueryReader as a,suppliedPolicyRules as o}from"./querying/security.mjs";import{composeRules as s,createTenantRules as c,wrapDatabaseReader as l,wrapDatabaseWriter as u}from"./tenancy.mjs";import{z as d}from"zod";function f(e){let t=e?.trim().toLowerCase();return t===`member`?`writer`:t===`reader`||t===`writer`||t===`admin`?t:null}function p(e){let t=e?.errors??i,n=e?.maxRows??100;function r(e,i){async function a(r,a){if(!Number.isSafeInteger(r)||r<1||r>n)return t.throw({code:`INVALID_REQUEST_BOUNDARY`,message:`A bounded query limit must be from 1 to ${n}`});let o=await(i??e.fullTableScan()).take(r);return a?a(o):o}async function o(r,a){if(!Number.isSafeInteger(r.numItems)||r.numItems<1||r.numItems>n)return t.throw({code:`INVALID_REQUEST_BOUNDARY`,message:`A page size must be from 1 to ${n}`});let o=await(i??e.fullTableScan()).paginate(r);return a?{...o,page:await a(o.page)}:o}return{when:(t,n)=>i||t==null?r(e,i):r(e,n(e,t)),matching:(t,n,a=!0)=>i||!a?r(e,i):r(e,e.withIndex(t,n)),otherwise:t=>i??t(e),resolve:()=>i??e.fullTableScan(),execute:a,paginate:o}}return e=>r(e)}function m(e){let t=g(e),{include:r,secureWriter:i,servicePrincipal:a,requireRole:o}=t,s=e.triggers,c=s?e=>s.wrapDB(e):e.wrapDB??(e=>e);async function l(e){let n=await t.authenticatedUser(e);return{ctx:{...i(c(e),n),include:r,...n},args:{}}}function u(t){return n(e.internalMutation,{args:{},input:async e=>{let n=await a(t,e);return{ctx:{...i(c(e),n),...n,include:r},args:{}}}})}function d(...t){return n(e.mutation,{args:{},input:async e=>{let n=await l(e);return o(n.ctx.actor.role,t),n}})}return{...t.readers,roleMutation:d,authMutation:n(e.mutation,{args:{},input:l}),adminMutation:d(...e.adminRoles),serviceMutation:u,systemMutation:n(e.internalMutation,{args:{},input:async e=>({ctx:{...c(e),include:r},args:{}})})}}function h(e){return g(e).readers}function g(n){let d=n.errors??i,f=p({errors:d,maxRows:n.maxIncludedQueryRows});async function m(e){let t=await e.auth.getUserIdentity(),r=t?await n.getAuthUser(e,t):null;if(!t||!r)return d.throw({code:`UNAUTHENTICATED`});let i,a;if(n.resolveOrganization){let o=null;try{o=await n.resolveOrganization({ctx:e,identity:t,user:r})}catch{}if(!o)return d.throw({code:`FORBIDDEN`});i=o.organizationId,a=o.roleSlug}else{let e=v.parse(t),n=e.organization?.organizationId??e.org_id;if(!n)return d.throw({code:`UNAUTHENTICATED`});i=n,a=e.organization?.role??e.role}let o=n.mapRole(a);if(!o)return d.throw({code:`FORBIDDEN`});let s={identity:t,user:Object.freeze({id:r.id}),org:Object.freeze({organizationId:i,role:o}),role:o,actor:Object.freeze({userId:r.id,organizationId:i,role:o})};return Object.freeze({...s,tenant:n.security?.tenancy?.resolve?.(s)??i})}let h=n.security?{defaultPolicy:n.security.defaultPolicy??(n.security.tenancy?`deny`:`allow`)}:void 0;function g(e){let t=n.security;if(!t)return;let r=[];return t.tenancy&&r.push(c(e.tenant,t.tenancy.tables)),t.rules&&r.push(t.rules(e)),r.length===1?r[0]:s(...r)}function y(e,t,n=`authenticated`){let r=g(t),i=h?.defaultPolicy??`allow`,s=r?l({db:e.db},e.db,o(e.db,r,i),h):e.db;return{...e,db:a(e.db,s,{scope:{mode:n,principal:t.user.id,organization:t.org.organizationId,tenant:t.tenant,role:t.role},rules:r??{},defaultPolicy:i})}}function b(e,t){let n=g(t);return n?{...e,db:u({db:e.db},e.db,o(e.db,n,h?.defaultPolicy??`allow`),h)}:e}async function x(e,t){if(!n.verifyMembership)return null;try{let r=await n.verifyMembership({userId:e,organizationId:t});if(r&&r.organizationId===t)return r}catch{}return d.throw({code:`FORBIDDEN`})}function S(e,t){if(!t.includes(e))return d.throw({code:`FORBIDDEN`})}async function C(e){let t=await m(e);return{ctx:{...y(e,t),include:f,...t},args:{}}}async function w(e){let t=await m(e),r=await x(t.user.id,t.org.organizationId);if(!r)return{ctx:{...e,...t},args:{}};let i=n.mapRole(r.roleSlug);if(!i)return d.throw({code:`FORBIDDEN`});let a={identity:t.identity,user:t.user,org:Object.freeze({organizationId:r.organizationId,role:i}),role:i,actor:Object.freeze({userId:t.user.id,organizationId:r.organizationId,role:i})};return{ctx:{...e,...a,tenant:n.security?.tenancy?.resolve?.(a)??r.organizationId},args:{}}}async function T(t,n){let r=await t(n,e(n));if(!_.safeParse(r).success)throw Error(`A service principal must be an AuthBundle with user.id and tenant`);let i=Object.keys(r).filter(e=>e in n);if(i.length>0)throw Error(`A service principal cannot override native context fields: ${i.join(`, `)}`);return r}function E(e){return r(n.internalQuery,{args:{},input:async t=>{let n=await T(e,t);return{ctx:{...y(t,n,`trusted`),...n,include:f},args:{}}}})}function D(...e){return r(n.query,{args:{},input:async t=>{let n=await C(t);return S(n.ctx.actor.role,e),n}})}function O(...e){return t(n.action,{args:{},input:async t=>{let n=await w(t);return S(n.ctx.actor.role,e),n}})}return{readers:{include:f,authenticatedUser:m,roleQuery:D,roleAction:O,authQuery:r(n.query,{args:{},input:C}),authAction:t(n.action,{args:{},input:w}),adminQuery:D(...n.adminRoles),adminAction:O(...n.adminRoles),serviceQuery:E,systemQuery:r(n.internalQuery,{args:{},input:async e=>({ctx:{...e,include:f,db:a(e.db,e.db,{scope:{mode:`system`,principal:null,organization:null,tenant:null,role:null},rules:{},defaultPolicy:`allow`})},args:{}})}),systemAction:t(n.internalAction,{args:{},input:async e=>({ctx:e,args:{}})})},include:f,authenticatedUser:m,secureWriter:b,servicePrincipal:T,requireRole:S}}const _=d.object({user:d.object({id:d.string()}),tenant:d.string()}),v=d.object({organization:d.object({organizationId:d.string().optional().catch(void 0),role:d.string().optional().catch(void 0)}).optional().catch(void 0),org_id:d.string().optional().catch(void 0),role:d.string().optional().catch(void 0)});export{m as createAuthFunctions,h as createAuthReaders,p as createInclude,f 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","servicePrincipal","principal","rawFunctionArgs","servicePrincipalContract","reserved","key","serviceQuery","zCustomQuery","serviceMutation","zCustomMutation","roleQuery","roleMutation","roleAction","zCustomAction","z"],"sources":["../src/auth.ts"],"sourcesContent":["import { z } from 'zod'\nimport { rawFunctionArgs, zCustomAction, zCustomMutation, zCustomQuery } from './zod-registration'\nimport type { CustomBuilder } from 'convex-helpers/server/zod4'\nimport type {\n\tActionBuilder,\n\tDefaultFunctionArgs,\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 * The bundle handed to security rules. Service principals (serviceQuery /\n * serviceMutation) may carry extra host-supplied fields beside the standard\n * bundle; rules read them as unknown and narrow as needed.\n */\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- Host extras are open by design; rules narrow the fields they own.\nexport type SecurityBundle<Role extends string> = AuthBundle<Role> & ServiceExtras\n\n/** Extra fields a host factory attaches to a service principal. */\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- Host extras are open by design; rules narrow the fields they own.\nexport type ServiceExtras = Readonly<Record<string, unknown>>\n\n/**\n * A trusted host factory producing the principal a service function runs as.\n * `args` are the raw (unparsed) arguments of the invocation, so the host can\n * derive the scope (e.g. a client id) from them. Never accept the principal\n * itself from the caller — only derive it.\n */\nexport type ServicePrincipal<Ctx, Role extends string, Extra extends Record<string, unknown>> = (\n\tctx: Ctx,\n\targs: DefaultFunctionArgs,\n) => (AuthBundle<Role> & Extra) | Promise<AuthBundle<Role> & Extra>\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: SecurityBundle<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*,\n\t * admin*, and service* constructor. system* constructors stay unwrapped\n\t * (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\t/**\n\t * Internal query running as a host-supplied service principal with the\n\t * app's security rules fully applied. No identity lookup; the trusted\n\t * host's factory is the only principal source.\n\t */\n\tserviceQuery: <Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>,\n\t) => ServiceQuery<DataModel, Role, Extra>\n\t/** Internal mutation running as a service principal: triggers first, then the secured writer. */\n\tserviceMutation: <Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>,\n\t) => ServiceMutation<DataModel, Role, Extra>\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\nexport type ServiceQuery<\n\tDataModel extends GenericDataModel,\n\tRole extends string,\n\tExtra extends Record<string, unknown> = {},\n> = CustomBuilder<\n\t'query',\n\t{},\n\tGenericQueryCtx<DataModel> & AuthBundle<Role> & Extra & { include: Include },\n\t{},\n\tGenericQueryCtx<DataModel>,\n\t'internal',\n\tobject\n>\n\nexport type ServiceMutation<\n\tDataModel extends GenericDataModel,\n\tRole extends string,\n\tExtra extends Record<string, unknown> = {},\n> = CustomBuilder<\n\t'mutation',\n\t{},\n\tGenericMutationCtx<DataModel> & AuthBundle<Role> & Extra & { include: Include },\n\t{},\n\tGenericMutationCtx<DataModel>,\n\t'internal',\n\tobject\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\tmode: 'authenticated' | 'trusted' = 'authenticated',\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,\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\tasync function servicePrincipal<\n\t\tCtx extends GenericQueryCtx<DataModel> | GenericMutationCtx<DataModel>,\n\t\tExtra extends Record<string, unknown>,\n\t>(principal: ServicePrincipal<Ctx, Role, Extra>, ctx: Ctx) {\n\t\tconst bundle = await principal(ctx, rawFunctionArgs(ctx))\n\t\tif (!servicePrincipalContract.safeParse(bundle).success) {\n\t\t\tthrow new Error('A service principal must be an AuthBundle with user.id and tenant')\n\t\t}\n\t\t// Extras are spread onto the secured ctx; a host field named like a native\n\t\t// handle (db, auth, scheduler, ...) would silently replace the secured one.\n\t\tconst reserved = Object.keys(bundle).filter((key) => key in ctx)\n\t\tif (reserved.length > 0) {\n\t\t\tthrow new Error(`A service principal cannot override native context fields: ${reserved.join(', ')}`)\n\t\t}\n\t\treturn bundle\n\t}\n\n\t/** Internal query running as the host-derived service principal, rules applied. */\n\tfunction serviceQuery<Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>,\n\t): ServiceQuery<DataModel, Role, Extra> {\n\t\treturn zCustomQuery(config.internalQuery, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst bundle = await servicePrincipal(principal, ctx)\n\t\t\t\treturn {\n\t\t\t\t\tctx: { ...secureReader(ctx, bundle, 'trusted'), ...bundle, include },\n\t\t\t\t\targs: {},\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\t}\n\n\t/** Internal mutation running as the host-derived service principal: triggers, then rules. */\n\tfunction serviceMutation<Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>,\n\t): ServiceMutation<DataModel, Role, Extra> {\n\t\treturn zCustomMutation(config.internalMutation, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst bundle = await servicePrincipal(principal, ctx)\n\t\t\t\treturn {\n\t\t\t\t\tctx: { ...secureWriter(wrapDB(ctx), bundle), ...bundle, include },\n\t\t\t\t\targs: {},\n\t\t\t\t}\n\t\t\t},\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\tserviceQuery,\n\t\tserviceMutation,\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\n/** The minimum a host factory must return; the rest of the bundle is the host's contract. */\nconst servicePrincipalContract = z.object({\n\tuser: z.object({ id: z.string() }),\n\ttenant: z.string(),\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})\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U,EAC5C,eACA,kBACA,YAAagD,EAAahD,EAAO,cAAe,CAC/C,KAAM,CAAC,EACP,MAAO,KAAO,KAAS,CACtB,IAAK,CACJ,GAAGG,EACH,UACA,GAAI0B,EAAoB1B,EAAI,GAAIA,EAAI,GAAI,CACvC,MAAO,CACN,KAAM,SACN,UAAW,KACX,aAAc,KACd,OAAQ,KACR,KAAM,IACP,EACA,MAAO,CAAC,EACR,cAAe,OAChB,CAAC,CACF,EACA,KAAM,CAAC,CACR,EACD,CAAC,EACD,eAAgB+C,EAAgBlD,EAAO,iBAAkB,CACxD,KAAM,CAAC,EACP,MAAO,KAAO,KAAS,CAAE,IAAK,CAAE,GAAGE,EAAOC,CAAG,EAAG,SAAQ,EAAG,KAAM,CAAC,CAAE,EACrE,CAAC,EACD,aAAcmD,EAActD,EAAO,eAAgB,CAClD,KAAM,CAAC,EACP,MAAO,KAAO,KAAS,CAAE,MAAK,KAAM,CAAC,CAAE,EACxC,CAAC,CACF,CACD,CAGA,MAAM4C,EAA2BW,EAAE,OAAO,CACzC,KAAMA,EAAE,OAAO,CAAE,GAAIA,EAAE,OAAO,CAAE,CAAC,EACjC,OAAQA,EAAE,OAAO,CAClB,CAAC,EAEK3C,EAAqB2C,EAAE,OAAO,CACnC,aAAcA,EACZ,OAAO,CACP,eAAgBA,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,IAAA,EAAS,EACrD,KAAMA,EAAE,OAAO,CAAC,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","core","createAuthCore","config","triggers","wrapDB","ctx","mutationInput","bundle","secureWriter","serviceMutation","zCustomMutation","servicePrincipal","principal","roleMutation","allowed","authenticated","requireRole","createAuthReaders","include","authenticatedUser","identity","user","organizationId","organizationRole","resolved","claims","organizationClaims","claimedOrganizationId","role","base","securityConfig","securityRules","security","sets","createTenantRules","composeRules","secureReader","rules","defaultPolicy","ordinary","wrapDatabaseReader","suppliedPolicyRules","registerQueryReader","wrapDatabaseWriter","verifiedMembership","membership","queryInput","actionInput","verified","rawFunctionArgs","servicePrincipalContract","reserved","key","serviceQuery","zCustomQuery","roleQuery","roleAction","zCustomAction","z"],"sources":["../src/auth.ts"],"sourcesContent":["import { z } from 'zod'\nimport { rawFunctionArgs, zCustomAction, zCustomMutation, zCustomQuery } from './zod-registration'\nimport type { CustomBuilder } from 'convex-helpers/server/zod4'\nimport type {\n\tActionBuilder,\n\tDefaultFunctionArgs,\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 * The bundle handed to security rules. Service principals (serviceQuery /\n * serviceMutation) may carry extra host-supplied fields beside the standard\n * bundle; rules read them as unknown and narrow as needed.\n */\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- Host extras are open by design; rules narrow the fields they own.\nexport type SecurityBundle<Role extends string> = AuthBundle<Role> & ServiceExtras\n\n/** Extra fields a host factory attaches to a service principal. */\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- Host extras are open by design; rules narrow the fields they own.\nexport type ServiceExtras = Readonly<Record<string, unknown>>\n\n/**\n * A trusted host factory producing the principal a service function runs as.\n * `args` are the raw (unparsed) arguments of the invocation, so the host can\n * derive the scope (e.g. a client id) from them. Never accept the principal\n * itself from the caller — only derive it.\n */\nexport type ServicePrincipal<Ctx, Role extends string, Extra extends Record<string, unknown>> = (\n\tctx: Ctx,\n\targs: DefaultFunctionArgs,\n) => (AuthBundle<Role> & Extra) | Promise<AuthBundle<Role> & Extra>\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: SecurityBundle<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\n/**\n * Configuration for createAuthReaders: everything createAuthFunctions takes\n * except the mutation builders and trigger wrapping, so a module built from\n * it never has to import the trigger registry.\n */\nexport type AuthReadersConfig<DataModel extends GenericDataModel, Role extends string> = {\n\t/** The consumer's generated function builders (from ./_generated/server). */\n\tquery: QueryBuilder<DataModel, 'public'>\n\taction: ActionBuilder<DataModel, 'public'>\n\tinternalQuery: QueryBuilder<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/** 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*,\n\t * admin*, and service* constructor. system* constructors stay unwrapped\n\t * (trusted).\n\t */\n\tsecurity?: SecurityConfig<DataModel, Role>\n}\n\n/** A reader config plus the mutation builders and trigger wrapping. */\nexport type AuthFunctionsConfig<\n\tDataModel extends GenericDataModel,\n\tRole extends string,\n> = AuthReadersConfig<DataModel, Role> & {\n\tmutation: MutationBuilder<DataModel, 'public'>\n\tinternalMutation: MutationBuilder<DataModel, 'internal'>\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}\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\t/**\n\t * Internal query running as a host-supplied service principal with the\n\t * app's security rules fully applied. No identity lookup; the trusted\n\t * host's factory is the only principal source.\n\t */\n\tserviceQuery: <Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>,\n\t) => ServiceQuery<DataModel, Role, Extra>\n\t/** Internal mutation running as a service principal: triggers first, then the secured writer. */\n\tserviceMutation: <Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>,\n\t) => ServiceMutation<DataModel, Role, Extra>\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/** The read-only constructors: everything AuthFunctions has except mutations. */\nexport type AuthReaders<\n\tDataModel extends GenericDataModel,\n\tRole extends string = DefaultRole,\n> = Omit<AuthFunctions<DataModel, Role>, `${string}Mutation`>\n\nexport type ServiceQuery<\n\tDataModel extends GenericDataModel,\n\tRole extends string,\n\tExtra extends Record<string, unknown> = {},\n> = CustomBuilder<\n\t'query',\n\t{},\n\tGenericQueryCtx<DataModel> & AuthBundle<Role> & Extra & { include: Include },\n\t{},\n\tGenericQueryCtx<DataModel>,\n\t'internal',\n\tobject\n>\n\nexport type ServiceMutation<\n\tDataModel extends GenericDataModel,\n\tRole extends string,\n\tExtra extends Record<string, unknown> = {},\n> = CustomBuilder<\n\t'mutation',\n\t{},\n\tGenericMutationCtx<DataModel> & AuthBundle<Role> & Extra & { include: Include },\n\t{},\n\tGenericMutationCtx<DataModel>,\n\t'internal',\n\tobject\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 core = createAuthCore(config)\n\tconst { include, secureWriter, servicePrincipal, requireRole } = core\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\n\tasync function mutationInput(ctx: GenericMutationCtx<DataModel>) {\n\t\tconst bundle = await core.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\t/** Internal mutation running as the host-derived service principal: triggers, then rules. */\n\tfunction serviceMutation<Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>,\n\t): ServiceMutation<DataModel, Role, Extra> {\n\t\treturn zCustomMutation(config.internalMutation, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst bundle = await servicePrincipal(principal, ctx)\n\t\t\t\treturn {\n\t\t\t\t\tctx: { ...secureWriter(wrapDB(ctx), bundle), ...bundle, include },\n\t\t\t\t\targs: {},\n\t\t\t\t}\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\treturn {\n\t\t...core.readers,\n\t\troleMutation,\n\t\tauthMutation: zCustomMutation(config.mutation, {\n\t\t\targs: {},\n\t\t\tinput: mutationInput,\n\t\t}),\n\t\tadminMutation: roleMutation(...config.adminRoles),\n\t\tserviceMutation,\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}\n}\n\n/**\n * Builds the read-only constructors (queries and actions) from the same\n * policy as createAuthFunctions, without mutation builders or triggers.\n * Identity, tenancy, rules, role gates, membership checks and errors are the\n * same implementation, so a module built from these never imports the\n * trigger registry or the domains it pulls in.\n */\nexport function createAuthReaders<\n\tDataModel extends GenericDataModel,\n\tconst Role extends string = DefaultRole,\n>(config: AuthReadersConfig<DataModel, Role>): AuthReaders<DataModel, Role> {\n\treturn createAuthCore(config).readers\n}\n\n/** Shared implementation behind createAuthFunctions and createAuthReaders. */\nfunction createAuthCore<DataModel extends GenericDataModel, Role extends string>(\n\tconfig: AuthReadersConfig<DataModel, Role>,\n) {\n\tconst errors = config.errors ?? defaultErrors\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\tmode: 'authenticated' | 'trusted' = 'authenticated',\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,\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 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\tasync function servicePrincipal<\n\t\tCtx extends GenericQueryCtx<DataModel> | GenericMutationCtx<DataModel>,\n\t\tExtra extends Record<string, unknown>,\n\t>(principal: ServicePrincipal<Ctx, Role, Extra>, ctx: Ctx) {\n\t\tconst bundle = await principal(ctx, rawFunctionArgs(ctx))\n\t\tif (!servicePrincipalContract.safeParse(bundle).success) {\n\t\t\tthrow new Error('A service principal must be an AuthBundle with user.id and tenant')\n\t\t}\n\t\t// Extras are spread onto the secured ctx; a host field named like a native\n\t\t// handle (db, auth, scheduler, ...) would silently replace the secured one.\n\t\tconst reserved = Object.keys(bundle).filter((key) => key in ctx)\n\t\tif (reserved.length > 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`A service principal cannot override native context fields: ${reserved.join(', ')}`,\n\t\t\t)\n\t\t}\n\t\treturn bundle\n\t}\n\n\t/** Internal query running as the host-derived service principal, rules applied. */\n\tfunction serviceQuery<Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>,\n\t): ServiceQuery<DataModel, Role, Extra> {\n\t\treturn zCustomQuery(config.internalQuery, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst bundle = await servicePrincipal(principal, ctx)\n\t\t\t\treturn {\n\t\t\t\t\tctx: { ...secureReader(ctx, bundle, 'trusted'), ...bundle, include },\n\t\t\t\t\targs: {},\n\t\t\t\t}\n\t\t\t},\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/** 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\tconst readers: AuthReaders<DataModel, Role> = {\n\t\tinclude,\n\t\tauthenticatedUser,\n\t\troleQuery,\n\t\troleAction,\n\t\tauthQuery: zCustomQuery(config.query, { args: {}, input: queryInput }),\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\tadminAction: roleAction(...config.adminRoles),\n\t\tserviceQuery,\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\tsystemAction: zCustomAction(config.internalAction, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => ({ ctx, args: {} }),\n\t\t}),\n\t}\n\treturn { readers, include, authenticatedUser, secureWriter, servicePrincipal, requireRole }\n}\n\n/** The minimum a host factory must return; the rest of the bundle is the host's contract. */\nconst servicePrincipalContract = z.object({\n\tuser: z.object({ id: z.string() }),\n\ttenant: z.string(),\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"],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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"}
@@ -19,8 +19,6 @@ export declare function domainHelpers(entries: Readonly<Record<string, object>>)
19
19
  /** Bind only opaque schema references; never invoke user callbacks at construction. */
20
20
  export declare function bindDomainImplementation(key: string, declaration: object, implementation: object): {};
21
21
  /** Snapshot records and verify key ownership before the executor closes over them. */
22
- export declare function snapshotOperations(operations: Readonly<Record<string, object>>, contract: DomainContract | undefined, section: 'commands' | 'queries', audit?: (resolution: never, context: never) => unknown): Readonly<{
23
- [k: string]: Readonly<Record<string, unknown>>;
24
- }>;
22
+ export declare function snapshotOperations(operations: Readonly<Record<string, object>>, contract: DomainContract | undefined, section: 'commands' | 'queries', audit?: (resolution: never, context: never) => unknown): Readonly<Record<string, Readonly<Record<string, unknown>>>>;
25
23
  //#endregion
26
24
  //# sourceMappingURL=binding.d.mts.map
@@ -1,2 +1,2 @@
1
- const e=[`input`,`result`,`classification`,`replayResult`,`wire`],t=/* @__PURE__ */ new WeakMap,n=/* @__PURE__ */ new WeakMap;function r(e){let t=Object.fromEntries(Object.keys(e).map(t=>[t,n=>i(t,e[t],n)])),r=t.handler;return t.handler=(t,i)=>{if(typeof t!=`function`&&r)return r(t);if(typeof t!=`function`)throw Error(`Invalid operation handler`);let a={...i,handler:t};return n.set(a,e),a},t}function i(n,r,i){for(let e of[`handler`,`audit`,`prepare`,`guard`,`middleware`,`context`])if(Object.prototype.hasOwnProperty.call(r,e))throw Error(`Domain contract ${n} cannot contain ${e}`);for(let t of e)if(Object.prototype.hasOwnProperty.call(i,t))throw Error(`Contracted operation ${n} cannot override ${t}`);let a={...i,...r};return t.set(a,{key:n,declaration:r}),a}function a(r,a,o,s){if(s!==void 0&&typeof s!=`function`)throw Error(`Invalid registry audit callback`);let c=a?.[o];if(a&&!c)throw Error(`Domain contract has no ${o} section`);let l=Object.keys(r);if(c&&(l.length!==Object.keys(c).length||l.some(e=>!Object.prototype.hasOwnProperty.call(c,e))))throw Error(`Contract operation keys must match exactly`);let u=l.map(a=>{let l=r[a];if(c){if(n.has(l)){if(n.get(l)!==c)throw Error(`Operation ${a} must use its own contract helper`);l=i(a,c[a],l)}let r=t.get(l);if(!r||r.key!==a||r.declaration!==c[a]||e.some(e=>l[e]!==c[a][e]))throw Error(`Operation ${a} must use its own contract helper`)}let u={...l};if(u.wire&&=Object.freeze({...u.wire}),o===`commands`){let e=u.audit;if(e!==void 0&&typeof e!=`function`)throw Error(`Invalid audit for ${a}`);if(e===void 0){if(!s)throw Error(`Command ${a} requires an audit callback`);u.audit=(e,t)=>s({operation:a,input:e.command,result:e.result},t)}}return[a,Object.freeze(u)]});return Object.freeze(Object.fromEntries(u))}export{i as bindDomainImplementation,r as domainHelpers,a as snapshotOperations};
1
+ import{memoize as e}from"./lazy.mjs";const t=[`input`,`result`,`classification`,`replayResult`,`wire`],n=/* @__PURE__ */ new WeakMap,r=/* @__PURE__ */ new WeakMap,i=/* @__PURE__ */ new WeakMap;function a(e){let t=Object.fromEntries(Object.keys(e).map(t=>[t,n=>{if(!c(e,t))return o(t,e[t],n);let r={...n};return i.set(r,{key:t,entries:e}),r}])),n=t.handler;return t.handler=(t,i)=>{if(typeof t!=`function`&&n)return n(t);if(typeof t!=`function`)throw Error(`Invalid operation handler`);let a={...i,handler:t};return r.set(a,e),a},t}function o(e,r,i){for(let t of[`handler`,`audit`,`prepare`,`guard`,`middleware`,`context`])if(Object.prototype.hasOwnProperty.call(r,t))throw Error(`Domain contract ${e} cannot contain ${t}`);for(let n of t)if(Object.prototype.hasOwnProperty.call(i,n))throw Error(`Contracted operation ${e} cannot override ${n}`);let a={...i,...r};return n.set(a,{key:e,declaration:r}),a}function s(a,s,l,u){if(u!==void 0&&typeof u!=`function`)throw Error(`Invalid registry audit callback`);let d=s?.[l];if(s&&!d)throw Error(`Domain contract has no ${l} section`);let f=Object.keys(a);if(d&&(f.length!==Object.keys(d).length||f.some(e=>!Object.prototype.hasOwnProperty.call(d,e))))throw Error(`Contract operation keys must match exactly`);let p=e=>{let s=a[e],c=i.get(s);if(c&&(s=o(c.key,c.entries[c.key],s)),d){if(r.has(s)){if(r.get(s)!==d)throw Error(`Operation ${e} must use its own contract helper`);s=o(e,d[e],s)}let i=n.get(s);if(!i||i.key!==e||i.declaration!==d[e]||t.some(t=>s[t]!==d[e][t]))throw Error(`Operation ${e} must use its own contract helper`)}let f={...s};if(f.wire&&=Object.freeze({...f.wire}),l===`commands`){let t=f.audit;if(t!==void 0&&typeof t!=`function`)throw Error(`Invalid audit for ${e}`);if(t===void 0){if(!u)throw Error(`Command ${e} requires an audit callback`);f.audit=(t,n)=>u({operation:e,input:t.command,result:t.result},n)}}return Object.freeze(f)},m={};for(let t of f)d&&c(d,t)?Object.defineProperty(m,t,{enumerable:!0,get:e(()=>p(t))}):m[t]=p(t);return Object.freeze(m)}function c(e,n){let r=Object.getOwnPropertyDescriptor(e,n);if(!r)return!1;if(r.get)return!0;let i=r.value;return!!i&&typeof i==`object`&&t.some(e=>!!Object.getOwnPropertyDescriptor(i,e)?.get)}export{o as bindDomainImplementation,a as domainHelpers,s as snapshotOperations};
2
2
  //# sourceMappingURL=binding.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"binding.mjs","names":["protectedFields","bindings","pending","domainHelpers","helpers","entries","key","bindDomainImplementation","implementation","namedHandler","handler","options","field","declaration","definition","snapshotOperations","audit","declarations","contract","section","keys","operations","original","binding","override","resolution","context"],"sources":["../../../src/modules/contracts/binding.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-object-parameters, anti-slop/no-unsafe-dictionary-type, anti-slop/no-known-value-widening, anti-slop/no-runtime-typeof, anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns -- Configuration boundary validates heterogeneous own-key records and callback presence; validators remain opaque identities. */\nimport type { DomainContract, DomainOperationContract } from './domain'\n\ndeclare const declaredSchemas: unique symbol\n/** Private evidence for contextual inference; schemas are installed only at registration. */\nexport type DeclaredSchemas<Entry> = { readonly [declaredSchemas]: Entry }\nexport type BoundOperations<\n\tOperations extends Readonly<\n\t\tRecord<keyof Entries, { handler: (...arguments_: never[]) => unknown }>\n\t>,\n\tEntries extends Readonly<Record<string, DomainOperationContract>>,\n> = {\n\t[Key in keyof Entries]: Entries[Key] &\n\t\tOperations[Key] & {\n\t\t\tinput: Entries[Key]['input']\n\t\t\tresult: Entries[Key]['result']\n\t\t\thandler: Operations[Key]['handler']\n\t\t}\n}\n\n// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\nconst protectedFields = ['input', 'result', 'classification', 'replayResult', 'wire'] as const\nconst bindings = new WeakMap<object, { key: string; declaration: object }>()\nconst pending = new WeakMap<object, Readonly<Record<string, object>>>()\n\n/** Both adapters bind declarations through the same configuration boundary. */\nexport function domainHelpers(entries: Readonly<Record<string, object>>) {\n\tconst helpers = Object.fromEntries(\n\t\tObject.keys(entries).map((key) => [\n\t\t\tkey,\n\t\t\t(implementation: object) => bindDomainImplementation(key, entries[key], implementation),\n\t\t]),\n\t)\n\tconst namedHandler = helpers.handler\n\thelpers.handler = (handler: Function | object, options?: object) => {\n\t\tif (typeof handler !== 'function' && namedHandler) return namedHandler(handler)\n\t\tif (typeof handler !== 'function') throw Error('Invalid operation handler')\n\t\tconst implementation = { ...options, handler }\n\t\tpending.set(implementation, entries)\n\t\treturn implementation\n\t}\n\treturn helpers\n}\n\n/** Bind only opaque schema references; never invoke user callbacks at construction. */\nexport function bindDomainImplementation(key: string, declaration: object, implementation: object) {\n\tfor (const field of ['handler', 'audit', 'prepare', 'guard', 'middleware', 'context']) {\n\t\tif (Object.prototype.hasOwnProperty.call(declaration, field))\n\t\t\tthrow Error(`Domain contract ${key} cannot contain ${field}`)\n\t}\n\tfor (const field of protectedFields) {\n\t\tif (Object.prototype.hasOwnProperty.call(implementation, field))\n\t\t\tthrow Error(`Contracted operation ${key} cannot override ${field}`)\n\t}\n\tconst definition = { ...implementation, ...declaration }\n\tbindings.set(definition, { key, declaration })\n\treturn definition\n}\n\n/** Snapshot records and verify key ownership before the executor closes over them. */\nexport function snapshotOperations(\n\toperations: Readonly<Record<string, object>>,\n\tcontract: DomainContract | undefined,\n\tsection: 'commands' | 'queries',\n\taudit?: (resolution: never, context: never) => unknown,\n) {\n\tif (audit !== undefined && typeof audit !== 'function')\n\t\tthrow Error('Invalid registry audit callback')\n\tconst declarations = contract?.[section]\n\tif (contract && !declarations) throw Error(`Domain contract has no ${section} section`)\n\tconst keys = Object.keys(operations)\n\tif (\n\t\tdeclarations &&\n\t\t(keys.length !== Object.keys(declarations).length ||\n\t\t\tkeys.some((key) => !Object.prototype.hasOwnProperty.call(declarations, key)))\n\t)\n\t\tthrow Error('Contract operation keys must match exactly')\n\tconst entries = keys.map((key) => {\n\t\tlet original = operations[key]\n\t\tif (declarations) {\n\t\t\tif (pending.has(original)) {\n\t\t\t\tif (pending.get(original) !== declarations)\n\t\t\t\t\tthrow Error(`Operation ${key} must use its own contract helper`)\n\t\t\t\toriginal = bindDomainImplementation(key, declarations[key], original)\n\t\t\t}\n\t\t\tconst binding = bindings.get(original)\n\t\t\tif (\n\t\t\t\t!binding ||\n\t\t\t\tbinding.key !== key ||\n\t\t\t\tbinding.declaration !== declarations[key] ||\n\t\t\t\tprotectedFields.some(\n\t\t\t\t\t(field) =>\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\t(original as Record<string, unknown>)[field] !==\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\t(declarations[key] as Record<string, unknown>)[field],\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow Error(`Operation ${key} must use its own contract helper`)\n\t\t}\n\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\tconst definition = { ...original } as Record<string, unknown>\n\t\tif (definition.wire) {\n\t\t\t// SAFETY: wire is configuration, while its schema stays an opaque reference.\n\t\t\tdefinition.wire = Object.freeze({ ...(definition.wire as object) })\n\t\t}\n\t\tif (section === 'commands') {\n\t\t\tconst override = definition.audit\n\t\t\tif (override !== undefined && typeof override !== 'function')\n\t\t\t\tthrow Error(`Invalid audit for ${key}`)\n\t\t\tif (override === undefined) {\n\t\t\t\tif (!audit) throw Error(`Command ${key} requires an audit callback`)\n\t\t\t\tdefinition.audit = (resolution: { command: unknown; result: unknown }, context: unknown) =>\n\t\t\t\t\taudit(\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\t{ operation: key, input: resolution.command, result: resolution.result } as never,\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\tcontext as never,\n\t\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\treturn [key, Object.freeze(definition)] as const\n\t})\n\treturn Object.freeze(Object.fromEntries(entries))\n}\n"],"mappings":"AAqBA,MAAMA,EAAkB,CAAC,QAAS,SAAU,iBAAkB,eAAgB,MAAM,EAC9EC,kBAAW,IAAI,QACfC,kBAAU,IAAI,QAGpB,SAAgBC,EAAc,EAA2C,CACxE,IAAMC,EAAU,OAAO,YACtB,OAAO,KAAKC,CAAO,CAAC,CAAC,IAAK,GAAQ,CACjCC,EACC,GAA2BC,EAAyBD,EAAKD,EAAQC,GAAME,CAAc,CACvF,CAAC,CACF,EACMC,EAAeL,EAAQ,QAQ7B,MAPA,GAAQ,SAAW,EAA4B,IAAqB,CACnE,GAAI,OAAOM,GAAY,YAAcD,EAAc,OAAOA,EAAaC,CAAO,EAC9E,GAAI,OAAOA,GAAY,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EAChE,EAAWC,EAAyBD,EAAKW,EAAaX,GAAMgB,CAAQ,CACrE,CACA,IAAMC,EAAUtB,EAAS,IAAIqB,CAAQ,EACrC,GACC,CAACC,GACDA,EAAQ,MAAQjB,GAChBiB,EAAQ,cAAgBN,EAAaX,IACrCN,EAAgB,KACd,GAECsB,EAAqCV,KAErCK,EAAaX,EAAI,CAA6BM,EACjD,EAEA,MAAM,MAAM,aAAaN,EAAI,kCAAkC,CACjE,CAEA,IAAMQ,EAAa,CAAE,GAAGQ,CAAS,EAKjC,GAJA,AAECR,EAAW,OAAO,OAAO,OAAO,CAAE,GAAIA,EAAW,IAAgB,CAAC,EAE/DK,IAAY,WAAY,CAC3B,IAAMK,EAAWV,EAAW,MAC5B,GAAIU,IAAa,IAAA,IAAa,OAAOA,GAAa,WACjD,MAAM,MAAM,qBAAqBlB,GAAK,EACvC,GAAIkB,IAAa,IAAA,GAAW,CAC3B,GAAI,CAACR,EAAO,MAAM,MAAM,WAAWV,EAAI,4BAA4B,EACnE,EAAW,OAAS,EAAmD,IACtEU,EAEC,CAAE,UAAWV,EAAK,MAAOmB,EAAW,QAAS,OAAQA,EAAW,MAAO,EAEvEC,CACD,CACF,CACD,CAEA,MAAO,CAACpB,EAAK,OAAO,OAAOQ,CAAU,CAAC,CACvC,CAAC,EACD,OAAO,OAAO,OAAO,OAAO,YAAYT,CAAO,CAAC,CACjD"}
1
+ {"version":3,"file":"binding.mjs","names":["protectedFields","bindings","pending","deferred","domainHelpers","helpers","entries","key","isLazyOperation","bindDomainImplementation","implementation","draft","namedHandler","handler","options","field","declaration","definition","snapshotOperations","audit","declarations","contract","section","keys","operations","bind","original","binding","override","resolution","context","snapshot","memoize","descriptor","value"],"sources":["../../../src/modules/contracts/binding.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-object-parameters, anti-slop/no-unsafe-dictionary-type, anti-slop/no-known-value-widening, anti-slop/no-runtime-typeof, anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns -- Configuration boundary validates heterogeneous own-key records and callback presence; validators remain opaque identities. */\nimport { memoize } from './lazy'\nimport type { DomainContract, DomainOperationContract } from './domain'\n\ndeclare const declaredSchemas: unique symbol\n/** Private evidence for contextual inference; schemas are installed only at registration. */\nexport type DeclaredSchemas<Entry> = { readonly [declaredSchemas]: Entry }\nexport type BoundOperations<\n\tOperations extends Readonly<\n\t\tRecord<keyof Entries, { handler: (...arguments_: never[]) => unknown }>\n\t>,\n\tEntries extends Readonly<Record<string, DomainOperationContract>>,\n> = {\n\t[Key in keyof Entries]: Entries[Key] &\n\t\tOperations[Key] & {\n\t\t\tinput: Entries[Key]['input']\n\t\t\tresult: Entries[Key]['result']\n\t\t\thandler: Operations[Key]['handler']\n\t\t}\n}\n\n// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\nconst protectedFields = ['input', 'result', 'classification', 'replayResult', 'wire'] as const\nconst bindings = new WeakMap<object, { key: string; declaration: object }>()\nconst pending = new WeakMap<object, Readonly<Record<string, object>>>()\nconst deferred = new WeakMap<object, { key: string; entries: Readonly<Record<string, object>> }>()\n\n/** Both adapters bind declarations through the same configuration boundary. */\nexport function domainHelpers(entries: Readonly<Record<string, object>>) {\n\tconst helpers = Object.fromEntries(\n\t\tObject.keys(entries).map((key) => [\n\t\t\tkey,\n\t\t\t(implementation: object) => {\n\t\t\t\tif (!isLazyOperation(entries, key))\n\t\t\t\t\treturn bindDomainImplementation(key, entries[key], implementation)\n\t\t\t\tconst draft = { ...implementation }\n\t\t\t\tdeferred.set(draft, { key, entries })\n\t\t\t\treturn draft\n\t\t\t},\n\t\t]),\n\t)\n\tconst namedHandler = helpers.handler\n\thelpers.handler = (handler: Function | object, options?: object) => {\n\t\tif (typeof handler !== 'function' && namedHandler) return namedHandler(handler)\n\t\tif (typeof handler !== 'function') throw Error('Invalid operation handler')\n\t\tconst implementation = { ...options, handler }\n\t\tpending.set(implementation, entries)\n\t\treturn implementation\n\t}\n\treturn helpers\n}\n\n/** Bind only opaque schema references; never invoke user callbacks at construction. */\nexport function bindDomainImplementation(key: string, declaration: object, implementation: object) {\n\tfor (const field of ['handler', 'audit', 'prepare', 'guard', 'middleware', 'context']) {\n\t\tif (Object.prototype.hasOwnProperty.call(declaration, field))\n\t\t\tthrow Error(`Domain contract ${key} cannot contain ${field}`)\n\t}\n\tfor (const field of protectedFields) {\n\t\tif (Object.prototype.hasOwnProperty.call(implementation, field))\n\t\t\tthrow Error(`Contracted operation ${key} cannot override ${field}`)\n\t}\n\tconst definition = { ...implementation, ...declaration }\n\tbindings.set(definition, { key, declaration })\n\treturn definition\n}\n\n/** Snapshot records and verify key ownership before the executor closes over them. */\nexport function snapshotOperations(\n\toperations: Readonly<Record<string, object>>,\n\tcontract: DomainContract | undefined,\n\tsection: 'commands' | 'queries',\n\taudit?: (resolution: never, context: never) => unknown,\n) {\n\tif (audit !== undefined && typeof audit !== 'function')\n\t\tthrow Error('Invalid registry audit callback')\n\tconst declarations = contract?.[section]\n\tif (contract && !declarations) throw Error(`Domain contract has no ${section} section`)\n\tconst keys = Object.keys(operations)\n\tif (\n\t\tdeclarations &&\n\t\t(keys.length !== Object.keys(declarations).length ||\n\t\t\tkeys.some((key) => !Object.prototype.hasOwnProperty.call(declarations, key)))\n\t)\n\t\tthrow Error('Contract operation keys must match exactly')\n\tconst bind = (key: string) => {\n\t\tlet original = operations[key]\n\t\t// A deferred helper result binds to its own declaration wherever it is registered.\n\t\tconst draft = deferred.get(original)\n\t\tif (draft) original = bindDomainImplementation(draft.key, draft.entries[draft.key], original)\n\t\tif (declarations) {\n\t\t\tif (pending.has(original)) {\n\t\t\t\tif (pending.get(original) !== declarations)\n\t\t\t\t\tthrow Error(`Operation ${key} must use its own contract helper`)\n\t\t\t\toriginal = bindDomainImplementation(key, declarations[key], original)\n\t\t\t}\n\t\t\tconst binding = bindings.get(original)\n\t\t\tif (\n\t\t\t\t!binding ||\n\t\t\t\tbinding.key !== key ||\n\t\t\t\tbinding.declaration !== declarations[key] ||\n\t\t\t\tprotectedFields.some(\n\t\t\t\t\t(field) =>\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\t(original as Record<string, unknown>)[field] !==\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\t(declarations[key] as Record<string, unknown>)[field],\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow Error(`Operation ${key} must use its own contract helper`)\n\t\t}\n\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\tconst definition = { ...original } as Record<string, unknown>\n\t\tif (definition.wire) {\n\t\t\t// SAFETY: wire is configuration, while its schema stays an opaque reference.\n\t\t\tdefinition.wire = Object.freeze({ ...(definition.wire as object) })\n\t\t}\n\t\tif (section === 'commands') {\n\t\t\tconst override = definition.audit\n\t\t\tif (override !== undefined && typeof override !== 'function')\n\t\t\t\tthrow Error(`Invalid audit for ${key}`)\n\t\t\tif (override === undefined) {\n\t\t\t\tif (!audit) throw Error(`Command ${key} requires an audit callback`)\n\t\t\t\tdefinition.audit = (resolution: { command: unknown; result: unknown }, context: unknown) =>\n\t\t\t\t\taudit(\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\t{ operation: key, input: resolution.command, result: resolution.result } as never,\n\t\t\t\t\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\t\t\t\t\tcontext as never,\n\t\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\t// SAFETY: this configuration boundary compares opaque fields or restores callback slots checked by the public helpers.\n\t\treturn Object.freeze(definition)\n\t}\n\tconst snapshot: Record<string, Readonly<Record<string, unknown>>> = {}\n\tfor (const key of keys) {\n\t\tif (declarations && isLazyOperation(declarations, key))\n\t\t\tObject.defineProperty(snapshot, key, { enumerable: true, get: memoize(() => bind(key)) })\n\t\telse snapshot[key] = bind(key)\n\t}\n\treturn Object.freeze(snapshot)\n}\n\n/** Getter-declared operations, or operations with getter-declared protected fields, bind on first access. */\nfunction isLazyOperation(entries: Readonly<Record<string, object>>, key: string) {\n\tconst descriptor = Object.getOwnPropertyDescriptor(entries, key)\n\tif (!descriptor) return false\n\tif (descriptor.get) return true\n\tconst value: unknown = descriptor.value\n\treturn (\n\t\t!!value &&\n\t\ttypeof value === 'object' &&\n\t\tprotectedFields.some((field) => !!Object.getOwnPropertyDescriptor(value, field)?.get)\n\t)\n}\n"],"mappings":"qCAsBA,MAAMA,EAAkB,CAAC,QAAS,SAAU,iBAAkB,eAAgB,MAAM,EAC9EC,kBAAW,IAAI,QACfC,kBAAU,IAAI,QACdC,kBAAW,IAAI,QAGrB,SAAgBC,EAAc,EAA2C,CACxE,IAAMC,EAAU,OAAO,YACtB,OAAO,KAAKC,CAAO,CAAC,CAAC,IAAK,GAAQ,CACjCC,EACC,GAA2B,CAC3B,GAAI,CAACC,EAAgBF,EAASC,CAAG,EAChC,OAAOE,EAAyBF,EAAKD,EAAQC,GAAMG,CAAc,EAClE,IAAMC,EAAQ,CAAE,GAAGD,CAAe,EAElC,OADAP,EAAS,IAAIQ,EAAO,CAAE,MAAK,SAAQ,CAAC,EAC7BA,CACR,CACD,CAAC,CACF,EACMC,EAAeP,EAAQ,QAQ7B,MAPA,GAAQ,SAAW,EAA4B,IAAqB,CACnE,GAAI,OAAOQ,GAAY,YAAcD,EAAc,OAAOA,EAAaC,CAAO,EAC9E,GAAI,OAAOA,GAAY,WAAY,MAAM,MAAM,2BAA2B,EAC1E,IAAMH,EAAiB,CAAE,GAAGI,EAAS,SAAQ,EAE7C,OADAZ,EAAQ,IAAIQ,EAAgBJ,CAAO,EAC5BI,CACR,EACOL,CACR,CAGA,SAAgBI,EAAyB,EAAa,EAAqB,EAAwB,CAClG,IAAK,IAAMM,IAAS,CAAC,UAAW,QAAS,UAAW,QAAS,aAAc,SAAS,EACnF,GAAI,OAAO,UAAU,eAAe,KAAKC,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!=`function`)return t;let n={},r=e(()=>{let e=t();return Object.defineProperties(n,Object.getOwnPropertyDescriptors(e)),Object.setPrototypeOf(n,Object.getPrototypeOf(e)),n});return new Proxy(n,{get:(e,t,n)=>Reflect.get(r(),t,n),has:(e,t)=>Reflect.has(r(),t),ownKeys:()=>Reflect.ownKeys(r()),getOwnPropertyDescriptor:(e,t)=>Reflect.getOwnPropertyDescriptor(r(),t),set:(e,t,n)=>Reflect.set(r(),t,n),defineProperty:(e,t,n)=>Reflect.defineProperty(r(),t,n),deleteProperty:(e,t)=>Reflect.deleteProperty(r(),t),getPrototypeOf:()=>Reflect.getPrototypeOf(r()),setPrototypeOf:(e,t)=>Reflect.setPrototypeOf(r(),t),preventExtensions:()=>Reflect.preventExtensions(r()),isExtensible:()=>Reflect.isExtensible(r())})}export{t as defineDomainContract};
1
+ import{memoize as e}from"./lazy.mjs";function t(t){if(typeof t!=`function`)return a(t);let n={},r=e(()=>{let e=a(t());return Object.defineProperties(n,Object.getOwnPropertyDescriptors(e)),Object.setPrototypeOf(n,Object.getPrototypeOf(e)),n});return new Proxy(n,{get:(e,t,n)=>Reflect.get(r(),t,n),has:(e,t)=>Reflect.has(r(),t),ownKeys:()=>Reflect.ownKeys(r()),getOwnPropertyDescriptor:(e,t)=>Reflect.getOwnPropertyDescriptor(r(),t),set:(e,t,n)=>Reflect.set(r(),t,n),defineProperty:(e,t,n)=>Reflect.defineProperty(r(),t,n),deleteProperty:(e,t)=>Reflect.deleteProperty(r(),t),getPrototypeOf:()=>Reflect.getPrototypeOf(r()),setPrototypeOf:(e,t)=>Reflect.setPrototypeOf(r(),t),preventExtensions:()=>Reflect.preventExtensions(r()),isExtensible:()=>Reflect.isExtensible(r())})}const n=[`input`,`result`,`replayResult`,`wire`];function r(t,n,r){for(let i of n){let n=Object.getOwnPropertyDescriptor(t,i);if(!n?.get||!n.configurable)continue;let a=n.get;Object.defineProperty(t,i,{configurable:!0,enumerable:n.enumerable,get:e(()=>r(a.call(t)))})}}function i(e){return e&&typeof e==`object`&&r(e,n,e=>e),e}function a(e){for(let t of[`commands`,`queries`]){let n=e?.[t];if(n&&typeof n==`object`){for(let e of Object.keys(n)){let t=Object.getOwnPropertyDescriptor(n,e);t&&`value`in t&&i(t.value)}r(n,Object.keys(n),i)}}return e}export{t as defineDomainContract};
2
2
  //# sourceMappingURL=domain.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"domain.mjs","names":["defineDomainContract","definition","target","read","memoize","value","key","receiver","descriptor","prototype"],"sources":["../../../src/modules/contracts/domain.ts"],"sourcesContent":["import { memoize } from './lazy'\nimport type { ContractSchema, ContractInput, ContractOutput } from './contract'\nimport type { ErrorContract, ErrorDefinitions } from './errors'\n\n/** Schema-only domain vocabulary; implementations and host policies live in registries. */\nexport type DomainOperationContract = {\n\treadonly input: ContractSchema\n\treadonly result: ContractSchema\n\treadonly classification?: string\n\treadonly wire?: { readonly schema: ContractSchema; readonly project: Function }\n}\nexport type DomainCommandContract = DomainOperationContract & {\n\treadonly classification: string\n\treadonly replayResult?: ContractSchema\n}\nexport type DomainQueryContract = DomainOperationContract & { readonly replayResult?: never }\nexport type DomainContract = {\n\treadonly errors?: Pick<ErrorContract<ErrorDefinitions>, 'project'>\n\treadonly commands?: Readonly<Record<string, DomainCommandContract>>\n\treadonly queries?: Readonly<Record<string, DomainQueryContract>>\n}\n\ntype CheckedEntry<Entry extends DomainOperationContract> = {\n\treadonly handler?: never\n\treadonly audit?: never\n\treadonly prepare?: never\n\treadonly guard?: never\n\treadonly middleware?: never\n\treadonly context?: never\n\treadonly wire?: Entry extends { wire: { schema: infer Wire } }\n\t\t? {\n\t\t\t\treadonly schema: Wire\n\t\t\t\treadonly project: (value: ContractOutput<Entry['result']>) => ContractInput<Wire>\n\t\t\t}\n\t\t: never\n} & (Entry extends { replayResult: infer Replay }\n\t? {\n\t\t\treadonly replayResult: ContractOutput<Replay> extends ContractOutput<Entry['result']>\n\t\t\t\t? Replay\n\t\t\t\t: never\n\t\t}\n\t: {})\ntype CheckedSection<Section> = {\n\treadonly [Key in keyof Section]: Section[Key] extends DomainOperationContract\n\t\t? CheckedEntry<Section[Key]>\n\t\t: never\n}\ntype CheckedDomain<Definition> = {\n\treadonly [Section in Extract<keyof Definition, 'commands' | 'queries'>]: CheckedSection<\n\t\tDefinition[Section]\n\t>\n}\n\n/** Preserve the declaration's literal keys and opaque validator/error-contract identities. */\nexport function defineDomainContract<const Definition extends DomainContract>(\n\tdefinition:\n\t\t| (Definition & NoInfer<CheckedDomain<Definition>>)\n\t\t| (() => Definition & NoInfer<CheckedDomain<Definition>>),\n): Definition {\n\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- The public input is a checked declaration or its explicitly supported thunk.\n\tif (typeof definition !== 'function') return definition\n\t// SAFETY: the first read installs the inferred declaration's own descriptors on this target.\n\tconst target = {} as Definition\n\tconst read = memoize(() => {\n\t\tconst value = definition()\n\t\tObject.defineProperties(target, Object.getOwnPropertyDescriptors(value))\n\t\tObject.setPrototypeOf(target, Object.getPrototypeOf(value))\n\t\treturn target\n\t})\n\treturn new Proxy(target, {\n\t\t// oxlint-disable-next-line anti-slop/no-reflect-get -- Preserve accessor receiver semantics for the forwarded declaration.\n\t\tget: (_target, key, receiver) => Reflect.get(read(), key, receiver),\n\t\thas: (_target, key) => Reflect.has(read(), key),\n\t\townKeys: () => Reflect.ownKeys(read()),\n\t\tgetOwnPropertyDescriptor: (_target, key) => Reflect.getOwnPropertyDescriptor(read(), key),\n\t\tset: (_target, key, value) => Reflect.set(read(), key, value),\n\t\tdefineProperty: (_target, key, descriptor) => Reflect.defineProperty(read(), key, descriptor),\n\t\tdeleteProperty: (_target, key) => Reflect.deleteProperty(read(), key),\n\t\tgetPrototypeOf: () => Reflect.getPrototypeOf(read()),\n\t\tsetPrototypeOf: (_target, prototype) => Reflect.setPrototypeOf(read(), prototype),\n\t\tpreventExtensions: () => Reflect.preventExtensions(read()),\n\t\tisExtensible: () => Reflect.isExtensible(read()),\n\t})\n}\n\n/** Exactness applies to variables as well as fresh object literals. */\nexport type ExactOperationKeys<Operations, Contracts> =\n\tExclude<keyof Operations, keyof Contracts> extends never\n\t\t? Exclude<keyof Contracts, keyof Operations> extends never\n\t\t\t? string extends keyof Contracts\n\t\t\t\t? never\n\t\t\t\t: unknown\n\t\t\t: never\n\t\t: never\n\n/** Correlated callback envelope for registry-level command audit. */\nexport type DomainAuditInput<Commands> = {\n\t[Key in Extract<keyof Commands, string>]: Commands[Key] extends DomainOperationContract\n\t\t? {\n\t\t\t\toperation: Key\n\t\t\t\tinput: ContractOutput<Commands[Key]['input']>\n\t\t\t\tresult: ContractOutput<Commands[Key]['result']>\n\t\t\t}\n\t\t: never\n}[Extract<keyof Commands, string>]\n"],"mappings":"qCAsDA,SAAgBA,EACf,EAGa,CAEb,GAAI,OAAOC,GAAe,WAAY,OAAOA,EAE7C,IAAMC,EAAS,CAAC,EACVC,EAAOC,MAAc,CAC1B,IAAMC,EAAQJ,EAAW,EAGzB,OAFA,OAAO,iBAAiBC,EAAQ,OAAO,0BAA0BG,CAAK,CAAC,EACvE,OAAO,eAAeH,EAAQ,OAAO,eAAeG,CAAK,CAAC,EACnDH,CACR,CAAC,EACD,OAAO,IAAI,MAAMA,EAAQ,CAExB,KAAM,EAAS,EAAK,IAAa,QAAQ,IAAIC,EAAK,EAAGG,EAAKC,CAAQ,EAClE,KAAM,EAAS,IAAQ,QAAQ,IAAIJ,EAAK,EAAGG,CAAG,EAC9C,YAAe,QAAQ,QAAQH,EAAK,CAAC,EACrC,0BAA2B,EAAS,IAAQ,QAAQ,yBAAyBA,EAAK,EAAGG,CAAG,EACxF,KAAM,EAAS,EAAK,IAAU,QAAQ,IAAIH,EAAK,EAAGG,EAAKD,CAAK,EAC5D,gBAAiB,EAAS,EAAK,IAAe,QAAQ,eAAeF,EAAK,EAAGG,EAAKE,CAAU,EAC5F,gBAAiB,EAAS,IAAQ,QAAQ,eAAeL,EAAK,EAAGG,CAAG,EACpE,mBAAsB,QAAQ,eAAeH,EAAK,CAAC,EACnD,gBAAiB,EAAS,IAAc,QAAQ,eAAeA,EAAK,EAAGM,CAAS,EAChF,sBAAyB,QAAQ,kBAAkBN,EAAK,CAAC,EACzD,iBAAoB,QAAQ,aAAaA,EAAK,CAAC,CAChD,CAAC,CACF"}
1
+ {"version":3,"file":"domain.mjs","names":["defineDomainContract","definition","memoizeAccessors","target","read","memoize","value","key","receiver","descriptor","prototype","lazyFields","memoizeGetters","keys","get","wrap","memoizeOperation","operation","name","section"],"sources":["../../../src/modules/contracts/domain.ts"],"sourcesContent":["import { memoize } from './lazy'\nimport type { ContractSchema, ContractInput, ContractOutput } from './contract'\nimport type { ErrorContract, ErrorDefinitions } from './errors'\n\n/** Schema-only domain vocabulary; implementations and host policies live in registries. */\nexport type DomainOperationContract = {\n\treadonly input: ContractSchema\n\treadonly result: ContractSchema\n\treadonly classification?: string\n\treadonly wire?: { readonly schema: ContractSchema; readonly project: Function }\n}\nexport type DomainCommandContract = DomainOperationContract & {\n\treadonly classification: string\n\treadonly replayResult?: ContractSchema\n}\nexport type DomainQueryContract = DomainOperationContract & { readonly replayResult?: never }\nexport type DomainContract = {\n\treadonly errors?: Pick<ErrorContract<ErrorDefinitions>, 'project'>\n\treadonly commands?: Readonly<Record<string, DomainCommandContract>>\n\treadonly queries?: Readonly<Record<string, DomainQueryContract>>\n}\n\ntype CheckedEntry<Entry extends DomainOperationContract> = {\n\treadonly handler?: never\n\treadonly audit?: never\n\treadonly prepare?: never\n\treadonly guard?: never\n\treadonly middleware?: never\n\treadonly context?: never\n\treadonly wire?: Entry extends { wire: { schema: infer Wire } }\n\t\t? {\n\t\t\t\treadonly schema: Wire\n\t\t\t\treadonly project: (value: ContractOutput<Entry['result']>) => ContractInput<Wire>\n\t\t\t}\n\t\t: never\n} & (Entry extends { replayResult: infer Replay }\n\t? {\n\t\t\treadonly replayResult: ContractOutput<Replay> extends ContractOutput<Entry['result']>\n\t\t\t\t? Replay\n\t\t\t\t: never\n\t\t}\n\t: {})\ntype CheckedSection<Section> = {\n\treadonly [Key in keyof Section]: Section[Key] extends DomainOperationContract\n\t\t? CheckedEntry<Section[Key]>\n\t\t: never\n}\ntype CheckedDomain<Definition> = {\n\treadonly [Section in Extract<keyof Definition, 'commands' | 'queries'>]: CheckedSection<\n\t\tDefinition[Section]\n\t>\n}\n\n/** Preserve the declaration's literal keys and opaque validator/error-contract identities. */\nexport function defineDomainContract<const Definition extends DomainContract>(\n\tdefinition:\n\t\t| (Definition & NoInfer<CheckedDomain<Definition>>)\n\t\t| (() => Definition & NoInfer<CheckedDomain<Definition>>),\n): Definition {\n\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- The public input is a checked declaration or its explicitly supported thunk.\n\tif (typeof definition !== 'function') return memoizeAccessors(definition)\n\t// SAFETY: the first read installs the inferred declaration's own descriptors on this target.\n\tconst target = {} as Definition\n\tconst read = memoize(() => {\n\t\tconst value = memoizeAccessors(definition())\n\t\tObject.defineProperties(target, Object.getOwnPropertyDescriptors(value))\n\t\tObject.setPrototypeOf(target, Object.getPrototypeOf(value))\n\t\treturn target\n\t})\n\treturn new Proxy(target, {\n\t\t// oxlint-disable-next-line anti-slop/no-reflect-get -- Preserve accessor receiver semantics for the forwarded declaration.\n\t\tget: (_target, key, receiver) => Reflect.get(read(), key, receiver),\n\t\thas: (_target, key) => Reflect.has(read(), key),\n\t\townKeys: () => Reflect.ownKeys(read()),\n\t\tgetOwnPropertyDescriptor: (_target, key) => Reflect.getOwnPropertyDescriptor(read(), key),\n\t\tset: (_target, key, value) => Reflect.set(read(), key, value),\n\t\tdefineProperty: (_target, key, descriptor) => Reflect.defineProperty(read(), key, descriptor),\n\t\tdeleteProperty: (_target, key) => Reflect.deleteProperty(read(), key),\n\t\tgetPrototypeOf: () => Reflect.getPrototypeOf(read()),\n\t\tsetPrototypeOf: (_target, prototype) => Reflect.setPrototypeOf(read(), prototype),\n\t\tpreventExtensions: () => Reflect.preventExtensions(read()),\n\t\tisExtensible: () => Reflect.isExtensible(read()),\n\t})\n}\n\n/** Exactness applies to variables as well as fresh object literals. */\nexport type ExactOperationKeys<Operations, Contracts> =\n\tExclude<keyof Operations, keyof Contracts> extends never\n\t\t? Exclude<keyof Contracts, keyof Operations> extends never\n\t\t\t? string extends keyof Contracts\n\t\t\t\t? never\n\t\t\t\t: unknown\n\t\t\t: never\n\t\t: never\n\n/** Correlated callback envelope for registry-level command audit. */\nexport type DomainAuditInput<Commands> = {\n\t[Key in Extract<keyof Commands, string>]: Commands[Key] extends DomainOperationContract\n\t\t? {\n\t\t\t\toperation: Key\n\t\t\t\tinput: ContractOutput<Commands[Key]['input']>\n\t\t\t\tresult: ContractOutput<Commands[Key]['result']>\n\t\t\t}\n\t\t: never\n}[Extract<keyof Commands, string>]\n\n/* oxlint-disable anti-slop/no-object-parameters, anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns, anti-slop/no-unsafe-dictionary-type, anti-slop/no-runtime-typeof -- Wrapping walks checked declarations by descriptor and keeps schemas as opaque identities. */\nconst lazyFields = ['input', 'result', 'replayResult', 'wire'] as const\n\n/** Replace configurable getters with memoized ones in place, without invoking any of them. */\nfunction memoizeGetters(\n\ttarget: object,\n\tkeys: readonly PropertyKey[],\n\twrap: (value: unknown) => unknown,\n) {\n\tfor (const key of keys) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(target, key)\n\t\tif (!descriptor?.get || !descriptor.configurable) continue\n\t\tconst get = descriptor.get\n\t\tObject.defineProperty(target, key, {\n\t\t\tconfigurable: true,\n\t\t\tenumerable: descriptor.enumerable,\n\t\t\tget: memoize(() => wrap(get.call(target))),\n\t\t})\n\t}\n}\n\nfunction memoizeOperation(operation: unknown) {\n\tif (operation && typeof operation === 'object') memoizeGetters(operation, lazyFields, (value) => value)\n\treturn operation\n}\n\n/** Getter-declared operations and fields build at most once and keep a stable identity. */\nfunction memoizeAccessors<Definition>(definition: Definition): Definition {\n\tfor (const name of ['commands', 'queries'] as const) {\n\t\t// SAFETY: the checked declaration's sections are plain records of operation declarations.\n\t\tconst section = (definition as Record<string, unknown> | undefined)?.[name]\n\t\tif (!section || typeof section !== 'object') continue\n\t\tfor (const key of Object.keys(section)) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(section, key)\n\t\t\tif (descriptor && 'value' in descriptor) memoizeOperation(descriptor.value)\n\t\t}\n\t\tmemoizeGetters(section, Object.keys(section), memoizeOperation)\n\t}\n\treturn definition\n}\n/* oxlint-enable anti-slop/no-object-parameters, anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns, anti-slop/no-unsafe-dictionary-type, anti-slop/no-runtime-typeof */\n"],"mappings":"qCAsDA,SAAgBA,EACf,EAGa,CAEb,GAAI,OAAOC,GAAe,WAAY,OAAOC,EAAiBD,CAAU,EAExE,IAAME,EAAS,CAAC,EACVC,EAAOC,MAAc,CAC1B,IAAMC,EAAQJ,EAAiBD,EAAW,CAAC,EAG3C,OAFA,OAAO,iBAAiBE,EAAQ,OAAO,0BAA0BG,CAAK,CAAC,EACvE,OAAO,eAAeH,EAAQ,OAAO,eAAeG,CAAK,CAAC,EACnDH,CACR,CAAC,EACD,OAAO,IAAI,MAAMA,EAAQ,CAExB,KAAM,EAAS,EAAK,IAAa,QAAQ,IAAIC,EAAK,EAAGG,EAAKC,CAAQ,EAClE,KAAM,EAAS,IAAQ,QAAQ,IAAIJ,EAAK,EAAGG,CAAG,EAC9C,YAAe,QAAQ,QAAQH,EAAK,CAAC,EACrC,0BAA2B,EAAS,IAAQ,QAAQ,yBAAyBA,EAAK,EAAGG,CAAG,EACxF,KAAM,EAAS,EAAK,IAAU,QAAQ,IAAIH,EAAK,EAAGG,EAAKD,CAAK,EAC5D,gBAAiB,EAAS,EAAK,IAAe,QAAQ,eAAeF,EAAK,EAAGG,EAAKE,CAAU,EAC5F,gBAAiB,EAAS,IAAQ,QAAQ,eAAeL,EAAK,EAAGG,CAAG,EACpE,mBAAsB,QAAQ,eAAeH,EAAK,CAAC,EACnD,gBAAiB,EAAS,IAAc,QAAQ,eAAeA,EAAK,EAAGM,CAAS,EAChF,sBAAyB,QAAQ,kBAAkBN,EAAK,CAAC,EACzD,iBAAoB,QAAQ,aAAaA,EAAK,CAAC,CAChD,CAAC,CACF,CAwBA,MAAMO,EAAa,CAAC,QAAS,SAAU,eAAgB,MAAM,EAG7D,SAASC,EACR,EACA,EACA,EACC,CACD,IAAK,IAAML,KAAOM,EAAM,CACvB,IAAMJ,EAAa,OAAO,yBAAyBN,EAAQI,CAAG,EAC9D,GAAI,CAACE,GAAY,KAAO,CAACA,EAAW,aAAc,SAClD,IAAMK,EAAML,EAAW,IACvB,OAAO,eAAeN,EAAQI,EAAK,CAClC,aAAc,GACd,WAAYE,EAAW,WACvB,IAAKJ,MAAcU,EAAKD,EAAI,KAAKX,CAAM,CAAC,CAAC,CAC1C,CAAC,CACF,CACD,CAEA,SAASa,EAAiB,EAAoB,CAE7C,OADIC,GAAa,OAAOA,GAAc,UAAUL,EAAeK,EAAWN,EAAa,GAAUL,CAAK,EAC/FW,CACR,CAGA,SAASf,EAA6B,EAAoC,CACzE,IAAK,IAAMgB,IAAQ,CAAC,WAAY,SAAS,EAAY,CAEpD,IAAMC,EAAWlB,IAAqDiB,GACtE,GAAKC,GAAW,OAAOA,GAAY,SACnC,KAAK,IAAMZ,KAAO,OAAO,KAAKY,CAAO,EAAG,CACvC,IAAMV,EAAa,OAAO,yBAAyBU,EAASZ,CAAG,EAC3DE,GAAc,UAAWA,GAAYO,EAAiBP,EAAW,KAAK,CAC3E,CACAG,EAAeO,EAAS,OAAO,KAAKA,CAAO,EAAGH,CAAgB,CAD9D,CAED,CACA,OAAOf,CACR"}
@@ -1,2 +1,2 @@
1
- function e(e){let t=`pending`,n,r;return()=>{if(t===`ready`)return n;if(t===`failed`)throw r;if(t===`building`)throw Error(`Recursive lazy declaration`);t=`building`;try{return n=e(),t=`ready`,n}catch(e){throw r=e,t=`failed`,e}}}const t=/* @__PURE__ */ new WeakMap;function n(e,n){return t.set(e,n),e}function r(e){let n=t.get(e);if(!n)throw Error(`Expected a kit Effect registry`);n()}export{r as forceRegistry,e as memoize,n as registerLazyRegistry};
1
+ function e(e){let t=`pending`,n,r;return()=>{if(t===`ready`)return n;if(t===`failed`)throw r;if(t===`building`)throw Error(`Recursive lazy declaration`);t=`building`;try{return n=e(),t=`ready`,n}catch(e){throw r=e,t=`failed`,e}}}const t=/* @__PURE__ */ new WeakMap;function n(e,n){return t.set(e,n),e}function r(e){let n=t.get(e);if(!n)throw Error(`Expected a kit Effect registry`);Object.values(n())}export{r as forceRegistry,e as memoize,n as registerLazyRegistry};
2
2
  //# sourceMappingURL=lazy.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"lazy.mjs","names":["memoize","state","value","failure","build","cause","registryBuilders","registerLazyRegistry","registry","forceRegistry"],"sources":["../../../src/modules/contracts/lazy.ts"],"sourcesContent":["/** Retain both successful builds and configuration failures; never repeat declaration effects. */\nexport function memoize<Value>(build: () => Value): () => Value {\n\tlet state: 'pending' | 'building' | 'ready' | 'failed' = 'pending'\n\tlet value: Value\n\tlet failure: unknown\n\treturn () => {\n\t\tif (state === 'ready') return value\n\t\tif (state === 'failed') throw failure\n\t\tif (state === 'building') throw new Error('Recursive lazy declaration')\n\t\tstate = 'building'\n\t\ttry {\n\t\t\tvalue = build()\n\t\t\tstate = 'ready'\n\t\t\treturn value\n\t\t} catch (cause) {\n\t\t\tfailure = cause\n\t\t\tstate = 'failed'\n\t\t\tthrow cause\n\t\t}\n\t}\n}\n\nconst registryBuilders = new WeakMap<object, () => object>()\n\n/** Internal bridge lets the architecture test path validate explicitly supplied registries. */\nexport function registerLazyRegistry<Registry extends object>(\n\tregistry: Registry,\n\tbuild: () => object,\n): Registry {\n\tregistryBuilders.set(registry, build)\n\treturn registry\n}\n\nexport function forceRegistry<Registry extends object>(registry: Registry): void {\n\tconst build = registryBuilders.get(registry)\n\tif (!build) throw new Error('Expected a kit Effect registry')\n\tbuild()\n}\n"],"mappings":"AACA,SAAgBA,EAAe,EAAiC,CAC/D,IAAIC,EAAqD,UACrDC,EACAC,EACJ,UAAa,CACZ,GAAIF,IAAU,QAAS,OAAOC,EAC9B,GAAID,IAAU,SAAU,MAAME,EAC9B,GAAIF,IAAU,WAAY,MAAU,MAAM,4BAA4B,EACtE,EAAQ,WACR,GAAI,CAGH,MAFA,GAAQG,EAAM,EACd,EAAQ,QACDF,CACR,OAASG,EAAO,CAGf,KAFA,GAAUA,EACV,EAAQ,SACFA,CACP,CACD,CACD,CAEA,MAAMC,kBAAmB,IAAI,QAG7B,SAAgBC,EACf,EACA,EACW,CAEX,OADAD,EAAiB,IAAIE,EAAUJ,CAAK,EAC7BI,CACR,CAEA,SAAgBC,EAAuC,EAA0B,CAChF,IAAML,EAAQE,EAAiB,IAAIE,CAAQ,EAC3C,GAAI,CAACJ,EAAO,MAAU,MAAM,gCAAgC,EAC5DA,EAAM,CACP"}
1
+ {"version":3,"file":"lazy.mjs","names":["memoize","state","value","failure","build","cause","registryBuilders","registerLazyRegistry","registry","forceRegistry"],"sources":["../../../src/modules/contracts/lazy.ts"],"sourcesContent":["/** Retain both successful builds and configuration failures; never repeat declaration effects. */\nexport function memoize<Value>(build: () => Value): () => Value {\n\tlet state: 'pending' | 'building' | 'ready' | 'failed' = 'pending'\n\tlet value: Value\n\tlet failure: unknown\n\treturn () => {\n\t\tif (state === 'ready') return value\n\t\tif (state === 'failed') throw failure\n\t\tif (state === 'building') throw new Error('Recursive lazy declaration')\n\t\tstate = 'building'\n\t\ttry {\n\t\t\tvalue = build()\n\t\t\tstate = 'ready'\n\t\t\treturn value\n\t\t} catch (cause) {\n\t\t\tfailure = cause\n\t\t\tstate = 'failed'\n\t\t\tthrow cause\n\t\t}\n\t}\n}\n\nconst registryBuilders = new WeakMap<object, () => object>()\n\n/** Internal bridge lets the architecture test path validate explicitly supplied registries. */\nexport function registerLazyRegistry<Registry extends object>(\n\tregistry: Registry,\n\tbuild: () => object,\n): Registry {\n\tregistryBuilders.set(registry, build)\n\treturn registry\n}\n\nexport function forceRegistry<Registry extends object>(registry: Registry): void {\n\tconst build = registryBuilders.get(registry)\n\tif (!build) throw new Error('Expected a kit Effect registry')\n\t// Getter-declared operations bind on first access; reading every value validates them here too.\n\tvoid Object.values(build())\n}\n"],"mappings":"AACA,SAAgBA,EAAe,EAAiC,CAC/D,IAAIC,EAAqD,UACrDC,EACAC,EACJ,UAAa,CACZ,GAAIF,IAAU,QAAS,OAAOC,EAC9B,GAAID,IAAU,SAAU,MAAME,EAC9B,GAAIF,IAAU,WAAY,MAAU,MAAM,4BAA4B,EACtE,EAAQ,WACR,GAAI,CAGH,MAFA,GAAQG,EAAM,EACd,EAAQ,QACDF,CACR,OAASG,EAAO,CAGf,KAFA,GAAUA,EACV,EAAQ,SACFA,CACP,CACD,CACD,CAEA,MAAMC,kBAAmB,IAAI,QAG7B,SAAgBC,EACf,EACA,EACW,CAEX,OADAD,EAAiB,IAAIE,EAAUJ,CAAK,EAC7BI,CACR,CAEA,SAAgBC,EAAuC,EAA0B,CAChF,IAAML,EAAQE,EAAiB,IAAIE,CAAQ,EAC3C,GAAI,CAACJ,EAAO,MAAU,MAAM,gCAAgC,EAE5D,OAAY,OAAOA,EAAM,CAAC,CAC3B"}
@@ -1,2 +1,2 @@
1
- import{projectErrorCause as e}from"./errors.mjs";import{normalizeEffect as t}from"./normalize.mjs";import{ConvexError as n}from"convex/values";import{Cause as r,Context as i,Effect as a,Exit as o}from"effect";function s(s,c){return l=>{let u=typeof l==`function`?l:l.handler,d=async(s,...l)=>{let d=t(()=>c.services?c.services(s):i.empty()).pipe(a.flatMap(e=>t(()=>c.context?c.context(s):{}).pipe(a.flatMap(e=>a.sync(()=>{if(typeof e!=`object`||!e)throw Error(`Effect API context must be an object`);let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw Error(`Effect API context additions must be a plain record`);let n=s;for(let t of Reflect.ownKeys(e))if(t in n)throw Error(`Effect API context cannot replace ${String(t)}`);return c.context?Object.create(Object.getPrototypeOf(n),{...Object.getOwnPropertyDescriptors(n),...Object.getOwnPropertyDescriptors(e)}):s})),a.flatMap(e=>t(()=>u(e,...l))),a.provideContext(e)))),f=await a.runPromiseExit(a.scoped(d));if(o.isSuccess(f))return f.value;if(c.errors)throw new n(e(c.errors,f.cause));let p=f.cause.reasons.length===1?f.cause.reasons[0]:void 0;throw p&&r.isFailReason(p)?c.mapError?c.mapError(p.error):p.error:p&&r.isDieReason(p)?p.defect:Error(`Effect API execution failed`,{cause:f.cause})};return s(typeof l==`function`?d:{...l,handler:d})}}export{s as wrapEffectBuilder};
1
+ import{memoize as e}from"../contracts/lazy.mjs";import{projectErrorCause as t}from"./errors.mjs";import{normalizeEffect as n}from"./normalize.mjs";import{ConvexError as r}from"convex/values";import{Cause as i,Context as a,Effect as o,Exit as s}from"effect";function c(e,c){return u=>{let d=typeof u==`function`?u:u.handler,f=async(e,...l)=>{let u=n(()=>c.services?c.services(e):a.empty()).pipe(o.flatMap(t=>n(()=>c.context?c.context(e):{}).pipe(o.flatMap(t=>o.sync(()=>{if(typeof t!=`object`||!t)throw Error(`Effect API context must be an object`);let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw Error(`Effect API context additions must be a plain record`);let r=e;for(let e of Reflect.ownKeys(t))if(e in r)throw Error(`Effect API context cannot replace ${String(e)}`);return c.context?Object.create(Object.getPrototypeOf(r),{...Object.getOwnPropertyDescriptors(r),...Object.getOwnPropertyDescriptors(t)}):e})),o.flatMap(e=>n(()=>d(e,...l))),o.provideContext(t)))),f=await o.runPromiseExit(o.scoped(u));if(s.isSuccess(f))return f.value;if(c.errors)throw new r(t(c.errors,f.cause));let p=f.cause.reasons.length===1?f.cause.reasons[0]:void 0;throw p&&i.isFailReason(p)?c.mapError?c.mapError(p.error):p.error:p&&i.isDieReason(p)?p.defect:Error(`Effect API execution failed`,{cause:f.cause})};return e(typeof u==`function`?f:l(u,f))}}function l(t,n){let r={handler:n};for(let n of Reflect.ownKeys(t)){let i=Object.getOwnPropertyDescriptor(t,n);n!==`handler`&&i?.enumerable&&Object.defineProperty(r,n,{configurable:!0,enumerable:!0,...i.get?{get:e(()=>i.get.call(t))}:{value:i.value,writable:!0}})}return r}export{c as wrapEffectBuilder};
2
2
  //# sourceMappingURL=api-runtime.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"api-runtime.mjs","names":["wrapEffectBuilder","original","definition","handler","args","program","normalizeEffect","options","ctx","Context","Effect","added","additionsPrototype","originalContext","key","context","services","exit","Exit","ConvexError","projectErrorCause","reason","Cause","builder"],"sources":["../../../src/modules/effect/api-runtime.ts"],"sourcesContent":["import { Cause, Context, Effect, Exit } from 'effect'\nimport type { Scope } from 'effect'\nimport { ConvexError, type Value } from 'convex/values'\nimport type { ErrorContract, ErrorDefinitions } from '../contracts/errors'\nimport { projectErrorCause } from './errors'\nimport { normalizeEffect } from './normalize'\nimport type { CallbackRequirements, EffectValue } from './operation'\n\n// oxlint-disable-next-line anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns -- Projection receives any expected failure and its result is always thrown, never returned as public data.\nexport type EffectApiErrorProjection = (error: unknown) => unknown\nexport type EffectApiErrorContract = Pick<ErrorContract<ErrorDefinitions>, 'project'>\n\nexport type EffectApiHandlerValue<Value> =\n\t| Value\n\t| PromiseLike<Value>\n\t| Effect.Effect<Value, unknown, unknown>\n\nexport type EffectApiServices =\n\t| Context.Context<never>\n\t| PromiseLike<Context.Context<never>>\n\t| Effect.Effect<Context.Context<never>, unknown, Scope.Scope>\nexport type ProvidedServices<Provider> =\n\tEffectValue<Provider> extends Context.Context<infer Services> ? Services : never\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- This inference constraint requires record-shaped additions; each adapter preserves its concrete inferred fields and runtime checks the record boundary.\nexport type EffectApiContext = EffectApiHandlerValue<Record<string, unknown>>\ntype KeysOfUnion<Value> = Value extends object ? keyof Value : never\nexport type CheckedContext<Ctx, Added> =\n\tExtract<KeysOfUnion<EffectValue<Added>>, keyof Ctx> extends never ? unknown : never\nexport type EffectApiOptions<Ctx, Provider extends EffectApiServices, Added = {}> = (\n\t[ProvidedServices<Provider>] extends [never]\n\t\t? { services?: (ctx: Ctx) => Provider }\n\t\t: { services: (ctx: Ctx) => Provider }\n) & (\n\t[KeysOfUnion<EffectValue<Added>>] extends [never]\n\t\t? { context?: (ctx: Ctx) => Added & CheckedContext<Ctx, Added> }\n\t\t: { context: (ctx: Ctx) => Added & CheckedContext<Ctx, Added> }\n) & (\n\t| { errors: EffectApiErrorContract; mapError?: never }\n\t| { errors?: never; mapError?: EffectApiErrorProjection }\n)\nexport type CheckedApiRequirements<Returned, Provider> = [\n\tExclude<CallbackRequirements<NoInfer<Returned>>, ProvidedServices<Provider> | Scope.Scope>,\n] extends [never]\n\t? unknown\n\t: never\n\n/** Internal erasure is limited to the registration boundary; public adapters check A/E/R. */\nexport function wrapEffectBuilder(\n\tbuilder: Function,\n\toptions: {\n\t\tservices?: Function\n\t\tcontext?: Function\n\t\tmapError?: EffectApiErrorProjection\n\t\terrors?: EffectApiErrorContract\n\t},\n): Function {\n\treturn (definition: Function | { handler: Function }) => {\n\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Native registration explicitly accepts a callable or an object with a handler.\n\t\tconst original = typeof definition === 'function' ? definition : definition.handler\n\t\t// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Private erased callback receives the context already constructed by the checked native/custom builder.\n\t\tconst handler = async (ctx: unknown, ...args: unknown[]) => {\n\t\t\tconst program = normalizeEffect(() =>\n\t\t\t\toptions.services ? options.services(ctx) : Context.empty(),\n\t\t\t).pipe(\n\t\t\t\tEffect.flatMap((services) =>\n\t\t\t\t\tnormalizeEffect(() => (options.context ? options.context(ctx) : {})).pipe(\n\t\t\t\t\t\tEffect.flatMap((added) =>\n\t\t\t\t\t\t\tEffect.sync(() => {\n\t\t\t\t\t\t\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Validate erased context additions before enumerating or merging their fields.\n\t\t\t\t\t\t\t\tif (added === null || typeof added !== 'object')\n\t\t\t\t\t\t\t\t\tthrow Error('Effect API context must be an object')\n\t\t\t\t\t\t\t\tconst additionsPrototype = Object.getPrototypeOf(added)\n\t\t\t\t\t\t\t\tif (additionsPrototype !== Object.prototype && additionsPrototype !== null)\n\t\t\t\t\t\t\t\t\tthrow Error('Effect API context additions must be a plain record')\n\t\t\t\t\t\t\t\t// SAFETY: native and custom builders construct an object context before invoking this private handler.\n\t\t\t\t\t\t\t\tconst originalContext = ctx as object\n\t\t\t\t\t\t\t\tfor (const key of Reflect.ownKeys(added)) {\n\t\t\t\t\t\t\t\t\tif (key in originalContext)\n\t\t\t\t\t\t\t\t\t\tthrow Error(`Effect API context cannot replace ${String(key)}`)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn options.context\n\t\t\t\t\t\t\t\t\t? Object.create(Object.getPrototypeOf(originalContext), {\n\t\t\t\t\t\t\t\t\t\t\t...Object.getOwnPropertyDescriptors(originalContext),\n\t\t\t\t\t\t\t\t\t\t\t...Object.getOwnPropertyDescriptors(added),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t: ctx\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tEffect.flatMap((context) => normalizeEffect(() => original(context, ...args))),\n\t\t\t\t\t\tEffect.provideContext(services),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t)\n\t\t\t// SAFETY: checked public signatures prohibit unprovided handler requirements and\n\t\t\t// permit only Scope in providers; services are constructed within this same scope.\n\t\t\tconst exit = await Effect.runPromiseExit(\n\t\t\t\tEffect.scoped(program) as Effect.Effect<unknown, unknown>,\n\t\t\t)\n\t\t\tif (Exit.isSuccess(exit)) return exit.value\n\t\t\tif (options.errors) {\n\t\t\t\t// SAFETY: declared projection copies validated JSON-safe fields; all other Causes have a fixed safe envelope.\n\t\t\t\tthrow new ConvexError(projectErrorCause(options.errors, exit.cause) as Value)\n\t\t\t}\n\t\t\tconst reason = exit.cause.reasons.length === 1 ? exit.cause.reasons[0] : undefined\n\t\t\tif (reason && Cause.isFailReason(reason)) {\n\t\t\t\tthrow options.mapError ? options.mapError(reason.error) : reason.error\n\t\t\t}\n\t\t\tif (reason && Cause.isDieReason(reason)) throw reason.defect\n\t\t\tthrow new Error('Effect API execution failed', { cause: exit.cause })\n\t\t}\n\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Preserve the original native callable or object registration form.\n\t\treturn builder(typeof definition === 'function' ? handler : { ...definition, handler })\n\t}\n}\n"],"mappings":"iNA+CA,SAAgBA,EACf,EACA,EAMW,CACX,MAAQ,IAAiD,CAExD,IAAMC,EAAW,OAAOC,GAAe,WAAaA,EAAaA,EAAW,QAEtEC,EAAU,MAAO,EAAc,GAAGC,IAAoB,CAC3D,IAAMC,EAAUC,MACfC,EAAQ,SAAWA,EAAQ,SAASC,CAAG,EAAIC,EAAQ,MAAM,CAC1D,CAAC,CAAC,KACDC,EAAO,QAAS,GACfJ,MAAuBC,EAAQ,QAAUA,EAAQ,QAAQC,CAAG,EAAI,CAAC,CAAE,CAAC,CAAC,KACpEE,EAAO,QAAS,GACfA,EAAO,SAAW,CAEjB,GAAsB,OAAOC,GAAU,WAAnCA,EACH,MAAM,MAAM,sCAAsC,EACnD,IAAMC,EAAqB,OAAO,eAAeD,CAAK,EACtD,GAAIC,IAAuB,OAAO,WAAaA,IAAuB,KACrE,MAAM,MAAM,qDAAqD,EAElE,IAAMC,EAAkBL,EACxB,IAAK,IAAMM,KAAO,QAAQ,QAAQH,CAAK,EACtC,GAAIG,KAAOD,EACV,MAAM,MAAM,qCAAqC,OAAOC,CAAG,GAAG,EAEhE,OAAOP,EAAQ,QACZ,OAAO,OAAO,OAAO,eAAeM,CAAe,EAAG,CACtD,GAAG,OAAO,0BAA0BA,CAAe,EACnD,GAAG,OAAO,0BAA0BF,CAAK,CAC1C,CAAC,EACAH,CACJ,CAAC,CACF,EACAE,EAAO,QAAS,GAAYJ,MAAsBL,EAASc,EAAS,GAAGX,CAAI,CAAC,CAAC,EAC7EM,EAAO,eAAeM,CAAQ,CAC/B,CACD,CACD,EAGMC,EAAO,MAAMP,EAAO,eACzBA,EAAO,OAAOL,CAAO,CACtB,EACA,GAAIa,EAAK,UAAUD,CAAI,EAAG,OAAOA,EAAK,MACtC,GAAIV,EAAQ,OAEX,MAAM,IAAIY,EAAYC,EAAkBb,EAAQ,OAAQU,EAAK,KAAK,CAAU,EAE7E,IAAMI,EAASJ,EAAK,MAAM,QAAQ,SAAW,EAAIA,EAAK,MAAM,QAAQ,GAAK,IAAA,GAKzE,MAJII,GAAUC,EAAM,aAAaD,CAAM,EAChCd,EAAQ,SAAWA,EAAQ,SAASc,EAAO,KAAK,EAAIA,EAAO,MAE9DA,GAAUC,EAAM,YAAYD,CAAM,EAASA,EAAO,OAC5C,MAAM,8BAA+B,CAAE,MAAOJ,EAAK,KAAM,CAAC,CACrE,EAEA,OAAOM,EAAQ,OAAOrB,GAAe,WAAaC,EAAU,CAAE,GAAGD,EAAY,SAAQ,CAAC,CACvF,CACD"}
1
+ {"version":3,"file":"api-runtime.mjs","names":["wrapEffectBuilder","original","definition","handler","args","program","normalizeEffect","options","ctx","Context","Effect","added","additionsPrototype","originalContext","key","context","services","exit","Exit","ConvexError","projectErrorCause","reason","Cause","builder","withHandler","copy","descriptor","memoize"],"sources":["../../../src/modules/effect/api-runtime.ts"],"sourcesContent":["import { Cause, Context, Effect, Exit } from 'effect'\nimport type { Scope } from 'effect'\nimport { ConvexError, type Value } from 'convex/values'\nimport type { ErrorContract, ErrorDefinitions } from '../contracts/errors'\nimport { memoize } from '../contracts/lazy'\nimport { projectErrorCause } from './errors'\nimport { normalizeEffect } from './normalize'\nimport type { CallbackRequirements, EffectValue } from './operation'\n\n// oxlint-disable-next-line anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns -- Projection receives any expected failure and its result is always thrown, never returned as public data.\nexport type EffectApiErrorProjection = (error: unknown) => unknown\nexport type EffectApiErrorContract = Pick<ErrorContract<ErrorDefinitions>, 'project'>\n\nexport type EffectApiHandlerValue<Value> =\n\t| Value\n\t| PromiseLike<Value>\n\t| Effect.Effect<Value, unknown, unknown>\n\nexport type EffectApiServices =\n\t| Context.Context<never>\n\t| PromiseLike<Context.Context<never>>\n\t| Effect.Effect<Context.Context<never>, unknown, Scope.Scope>\nexport type ProvidedServices<Provider> =\n\tEffectValue<Provider> extends Context.Context<infer Services> ? Services : never\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- This inference constraint requires record-shaped additions; each adapter preserves its concrete inferred fields and runtime checks the record boundary.\nexport type EffectApiContext = EffectApiHandlerValue<Record<string, unknown>>\ntype KeysOfUnion<Value> = Value extends object ? keyof Value : never\nexport type CheckedContext<Ctx, Added> =\n\tExtract<KeysOfUnion<EffectValue<Added>>, keyof Ctx> extends never ? unknown : never\nexport type EffectApiOptions<Ctx, Provider extends EffectApiServices, Added = {}> = (\n\t[ProvidedServices<Provider>] extends [never]\n\t\t? { services?: (ctx: Ctx) => Provider }\n\t\t: { services: (ctx: Ctx) => Provider }\n) & (\n\t[KeysOfUnion<EffectValue<Added>>] extends [never]\n\t\t? { context?: (ctx: Ctx) => Added & CheckedContext<Ctx, Added> }\n\t\t: { context: (ctx: Ctx) => Added & CheckedContext<Ctx, Added> }\n) & (\n\t| { errors: EffectApiErrorContract; mapError?: never }\n\t| { errors?: never; mapError?: EffectApiErrorProjection }\n)\nexport type CheckedApiRequirements<Returned, Provider> = [\n\tExclude<CallbackRequirements<NoInfer<Returned>>, ProvidedServices<Provider> | Scope.Scope>,\n] extends [never]\n\t? unknown\n\t: never\n\n/** Internal erasure is limited to the registration boundary; public adapters check A/E/R. */\nexport function wrapEffectBuilder(\n\tbuilder: Function,\n\toptions: {\n\t\tservices?: Function\n\t\tcontext?: Function\n\t\tmapError?: EffectApiErrorProjection\n\t\terrors?: EffectApiErrorContract\n\t},\n): Function {\n\treturn (definition: Function | { handler: Function }) => {\n\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Native registration explicitly accepts a callable or an object with a handler.\n\t\tconst original = typeof definition === 'function' ? definition : definition.handler\n\t\t// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Private erased callback receives the context already constructed by the checked native/custom builder.\n\t\tconst handler = async (ctx: unknown, ...args: unknown[]) => {\n\t\t\tconst program = normalizeEffect(() =>\n\t\t\t\toptions.services ? options.services(ctx) : Context.empty(),\n\t\t\t).pipe(\n\t\t\t\tEffect.flatMap((services) =>\n\t\t\t\t\tnormalizeEffect(() => (options.context ? options.context(ctx) : {})).pipe(\n\t\t\t\t\t\tEffect.flatMap((added) =>\n\t\t\t\t\t\t\tEffect.sync(() => {\n\t\t\t\t\t\t\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Validate erased context additions before enumerating or merging their fields.\n\t\t\t\t\t\t\t\tif (added === null || typeof added !== 'object')\n\t\t\t\t\t\t\t\t\tthrow Error('Effect API context must be an object')\n\t\t\t\t\t\t\t\tconst additionsPrototype = Object.getPrototypeOf(added)\n\t\t\t\t\t\t\t\tif (additionsPrototype !== Object.prototype && additionsPrototype !== null)\n\t\t\t\t\t\t\t\t\tthrow Error('Effect API context additions must be a plain record')\n\t\t\t\t\t\t\t\t// SAFETY: native and custom builders construct an object context before invoking this private handler.\n\t\t\t\t\t\t\t\tconst originalContext = ctx as object\n\t\t\t\t\t\t\t\tfor (const key of Reflect.ownKeys(added)) {\n\t\t\t\t\t\t\t\t\tif (key in originalContext)\n\t\t\t\t\t\t\t\t\t\tthrow Error(`Effect API context cannot replace ${String(key)}`)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn options.context\n\t\t\t\t\t\t\t\t\t? Object.create(Object.getPrototypeOf(originalContext), {\n\t\t\t\t\t\t\t\t\t\t\t...Object.getOwnPropertyDescriptors(originalContext),\n\t\t\t\t\t\t\t\t\t\t\t...Object.getOwnPropertyDescriptors(added),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t: ctx\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tEffect.flatMap((context) => normalizeEffect(() => original(context, ...args))),\n\t\t\t\t\t\tEffect.provideContext(services),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t)\n\t\t\t// SAFETY: checked public signatures prohibit unprovided handler requirements and\n\t\t\t// permit only Scope in providers; services are constructed within this same scope.\n\t\t\tconst exit = await Effect.runPromiseExit(\n\t\t\t\tEffect.scoped(program) as Effect.Effect<unknown, unknown>,\n\t\t\t)\n\t\t\tif (Exit.isSuccess(exit)) return exit.value\n\t\t\tif (options.errors) {\n\t\t\t\t// SAFETY: declared projection copies validated JSON-safe fields; all other Causes have a fixed safe envelope.\n\t\t\t\tthrow new ConvexError(projectErrorCause(options.errors, exit.cause) as Value)\n\t\t\t}\n\t\t\tconst reason = exit.cause.reasons.length === 1 ? exit.cause.reasons[0] : undefined\n\t\t\tif (reason && Cause.isFailReason(reason)) {\n\t\t\t\tthrow options.mapError ? options.mapError(reason.error) : reason.error\n\t\t\t}\n\t\t\tif (reason && Cause.isDieReason(reason)) throw reason.defect\n\t\t\tthrow new Error('Effect API execution failed', { cause: exit.cause })\n\t\t}\n\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Preserve the original native callable or object registration form.\n\t\treturn builder(typeof definition === 'function' ? handler : withHandler(definition, handler))\n\t}\n}\n\n/**\n * Object-spread equivalent that forwards accessors instead of reading them, so\n * getter-declared args and returns stay unread until the builder needs them.\n */\nfunction withHandler(definition: { handler: Function }, handler: Function) {\n\tconst copy = { handler }\n\tfor (const key of Reflect.ownKeys(definition)) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(definition, key)\n\t\tif (key === 'handler' || !descriptor?.enumerable) continue\n\t\tObject.defineProperty(copy, key, {\n\t\t\tconfigurable: true,\n\t\t\tenumerable: true,\n\t\t\t...(descriptor.get\n\t\t\t\t? { get: memoize(() => descriptor.get!.call(definition)) }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