cvx-kit 0.1.27 → 0.1.29
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/dist/auth.d.mts +34 -4
- package/dist/auth.mjs +1 -1
- package/dist/auth.mjs.map +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/modules/effect/auth.d.mts +5 -1
- package/dist/modules/effect/auth.mjs +1 -1
- package/dist/modules/effect/auth.mjs.map +1 -1
- package/dist/oxlint/architecture.d.mts +3 -1
- package/dist/oxlint/architecture.mjs +1 -1
- package/dist/oxlint/architecture.mjs.map +1 -1
- package/dist/oxlint/ast.d.mts +2 -0
- package/dist/oxlint/ast.mjs +1 -1
- package/dist/oxlint/ast.mjs.map +1 -1
- package/dist/oxlint/components.d.mts +6 -0
- package/dist/oxlint/components.mjs +2 -0
- package/dist/oxlint/components.mjs.map +1 -0
- package/dist/oxlint/ownership.mjs +1 -1
- package/dist/oxlint/ownership.mjs.map +1 -1
- package/dist/oxlint.mjs +1 -1
- package/dist/oxlint.mjs.map +1 -1
- package/dist/relations.mjs +1 -1
- package/dist/relations.mjs.map +1 -1
- package/dist/triggers.d.mts +5 -1
- package/dist/triggers.mjs +1 -1
- package/dist/triggers.mjs.map +1 -1
- package/dist/zod-registration.d.mts +6 -1
- package/dist/zod-registration.mjs +1 -1
- package/dist/zod-registration.mjs.map +1 -1
- package/package.json +1 -1
package/dist/auth.d.mts
CHANGED
|
@@ -2,7 +2,7 @@ import { ErrorFactory } from "./errors.mjs";
|
|
|
2
2
|
import { RLSConfig, Rules } from "./tenancy.mjs";
|
|
3
3
|
import { SecurityPolicyContext } from "./querying/security.mjs";
|
|
4
4
|
import { CustomBuilder } from "convex-helpers/server/zod4";
|
|
5
|
-
import { ActionBuilder, DocumentByInfo, GenericActionCtx, GenericDataModel, GenericMutationCtx, GenericQueryCtx, GenericTableInfo, IndexNames, IndexRange, IndexRangeBuilder, MutationBuilder, NamedIndex, PaginationOptions, PaginationResult, Query, QueryBuilder, QueryInitializer, TableNamesInDataModel, UserIdentity } from "convex/server";
|
|
5
|
+
import { ActionBuilder, DefaultFunctionArgs, DocumentByInfo, GenericActionCtx, GenericDataModel, GenericMutationCtx, GenericQueryCtx, GenericTableInfo, IndexNames, IndexRange, IndexRangeBuilder, MutationBuilder, NamedIndex, PaginationOptions, PaginationResult, Query, QueryBuilder, QueryInitializer, TableNamesInDataModel, UserIdentity } from "convex/server";
|
|
6
6
|
import { Triggers } from "convex-helpers/server/triggers";
|
|
7
7
|
//#region src/auth.d.ts
|
|
8
8
|
/** The default vocabulary; every app can supply its own via the Role generic. */
|
|
@@ -26,6 +26,21 @@ export type AuthBundle<Role extends string> = Readonly<{
|
|
|
26
26
|
/** The resolved tenant — security.tenancy.resolve, or the organization id. */
|
|
27
27
|
tenant: string;
|
|
28
28
|
}>;
|
|
29
|
+
/**
|
|
30
|
+
* The bundle handed to security rules. Service principals (serviceQuery /
|
|
31
|
+
* serviceMutation) may carry extra host-supplied fields beside the standard
|
|
32
|
+
* bundle; rules read them as unknown and narrow as needed.
|
|
33
|
+
*/
|
|
34
|
+
export type SecurityBundle<Role extends string> = AuthBundle<Role> & ServiceExtras;
|
|
35
|
+
/** Extra fields a host factory attaches to a service principal. */
|
|
36
|
+
export type ServiceExtras = Readonly<Record<string, unknown>>;
|
|
37
|
+
/**
|
|
38
|
+
* A trusted host factory producing the principal a service function runs as.
|
|
39
|
+
* `args` are the raw (unparsed) arguments of the invocation, so the host can
|
|
40
|
+
* derive the scope (e.g. a client id) from them. Never accept the principal
|
|
41
|
+
* itself from the caller — only derive it.
|
|
42
|
+
*/
|
|
43
|
+
export type ServicePrincipal<Ctx, Role extends string, Extra extends Record<string, unknown>> = (ctx: Ctx, args: DefaultFunctionArgs) => (AuthBundle<Role> & Extra) | Promise<AuthBundle<Role> & Extra>;
|
|
29
44
|
/**
|
|
30
45
|
* Row-level security configuration. Tenant isolation and role-level rules
|
|
31
46
|
* compose (AND) onto the same wrapped database: queries get a wrapped
|
|
@@ -47,7 +62,7 @@ export type SecurityConfig<DataModel extends GenericDataModel, Role extends stri
|
|
|
47
62
|
* composed AND-wise with tenant isolation. E.g. gate `modify` on a table
|
|
48
63
|
* to admin roles.
|
|
49
64
|
*/
|
|
50
|
-
rules?: (bundle:
|
|
65
|
+
rules?: (bundle: SecurityBundle<Role>) => Rules<SecurityPolicyContext<DataModel>, DataModel>;
|
|
51
66
|
/**
|
|
52
67
|
* Policy for tables with no rule. Defaults to 'deny' when tenancy is
|
|
53
68
|
* configured (unlisted tables are unreachable — fail closed), 'allow'
|
|
@@ -121,8 +136,9 @@ export type AuthFunctionsConfig<DataModel extends GenericDataModel, Role extends
|
|
|
121
136
|
maxIncludedQueryRows?: number;
|
|
122
137
|
/**
|
|
123
138
|
* Row-level security: tenant isolation (from a table registry) and
|
|
124
|
-
* role-level rules, applied structurally inside every auth*, role*,
|
|
125
|
-
* admin* constructor. system* constructors stay unwrapped
|
|
139
|
+
* role-level rules, applied structurally inside every auth*, role*,
|
|
140
|
+
* admin*, and service* constructor. system* constructors stay unwrapped
|
|
141
|
+
* (trusted).
|
|
126
142
|
*/
|
|
127
143
|
security?: SecurityConfig<DataModel, Role>;
|
|
128
144
|
};
|
|
@@ -166,6 +182,14 @@ export type AuthFunctions<DataModel extends GenericDataModel, Role extends strin
|
|
|
166
182
|
adminQuery: AuthFunctions<DataModel, Role>['authQuery'];
|
|
167
183
|
adminMutation: AuthFunctions<DataModel, Role>['authMutation'];
|
|
168
184
|
adminAction: AuthFunctions<DataModel, Role>['authAction'];
|
|
185
|
+
/**
|
|
186
|
+
* Internal query running as a host-supplied service principal with the
|
|
187
|
+
* app's security rules fully applied. No identity lookup; the trusted
|
|
188
|
+
* host's factory is the only principal source.
|
|
189
|
+
*/
|
|
190
|
+
serviceQuery: <Extra extends Record<string, unknown> = {}>(principal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>) => ServiceQuery<DataModel, Role, Extra>;
|
|
191
|
+
/** Internal mutation running as a service principal: triggers first, then the secured writer. */
|
|
192
|
+
serviceMutation: <Extra extends Record<string, unknown> = {}>(principal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>) => ServiceMutation<DataModel, Role, Extra>;
|
|
169
193
|
systemQuery: CustomBuilder<'query', {}, GenericQueryCtx<DataModel> & {
|
|
170
194
|
include: Include;
|
|
171
195
|
}, {}, GenericQueryCtx<DataModel>, 'internal', object>;
|
|
@@ -174,6 +198,12 @@ export type AuthFunctions<DataModel extends GenericDataModel, Role extends strin
|
|
|
174
198
|
}, {}, GenericMutationCtx<DataModel>, 'internal', object>;
|
|
175
199
|
systemAction: CustomBuilder<'action', {}, GenericActionCtx<DataModel>, {}, GenericActionCtx<DataModel>, 'internal', object>;
|
|
176
200
|
};
|
|
201
|
+
export type ServiceQuery<DataModel extends GenericDataModel, Role extends string, Extra extends Record<string, unknown> = {}> = CustomBuilder<'query', {}, GenericQueryCtx<DataModel> & AuthBundle<Role> & Extra & {
|
|
202
|
+
include: Include;
|
|
203
|
+
}, {}, GenericQueryCtx<DataModel>, 'internal', object>;
|
|
204
|
+
export type ServiceMutation<DataModel extends GenericDataModel, Role extends string, Extra extends Record<string, unknown> = {}> = CustomBuilder<'mutation', {}, GenericMutationCtx<DataModel> & AuthBundle<Role> & Extra & {
|
|
205
|
+
include: Include;
|
|
206
|
+
}, {}, GenericMutationCtx<DataModel>, 'internal', object>;
|
|
177
207
|
/** Builds an include() that selects the first matching indexed query and bounds the read. */
|
|
178
208
|
export declare function createInclude(options?: {
|
|
179
209
|
errors?: ErrorFactory;
|
package/dist/auth.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
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};
|
|
2
2
|
//# sourceMappingURL=auth.mjs.map
|
package/dist/auth.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.mjs","names":["defaultRoleMap","normalized","roleSlug","createInclude","errors","options","defaultErrors","maxRows","attach","execute","limit","data","selected","query","transform","paginate","opts","result","value","select","shouldMatch","indexName","indexRange","createAuthFunctions","config","triggers","wrapDB","ctx","include","authenticatedUser","identity","user","organizationId","organizationRole","resolved","claims","organizationClaims","claimedOrganizationId","role","base","securityConfig","securityRules","security","sets","createTenantRules","bundle","composeRules","secureReader","rules","defaultPolicy","ordinary","wrapDatabaseReader","suppliedPolicyRules","registerQueryReader","secureWriter","wrapDatabaseWriter","verifiedMembership","membership","requireRole","allowed","queryInput","mutationInput","actionInput","authenticated","verified","roleQuery","zCustomQuery","roleMutation","zCustomMutation","roleAction","zCustomAction","z"],"sources":["../src/auth.ts"],"sourcesContent":["import { z } from 'zod'\nimport { zCustomAction, zCustomMutation, zCustomQuery } from './zod-registration'\nimport type { CustomBuilder } from 'convex-helpers/server/zod4'\nimport type {\n\tActionBuilder,\n\tDocumentByInfo,\n\tPaginationOptions,\n\tPaginationResult,\n\tGenericActionCtx,\n\tGenericDataModel,\n\tGenericMutationCtx,\n\tGenericQueryCtx,\n\tGenericTableInfo,\n\tIndexNames,\n\tIndexRange,\n\tIndexRangeBuilder,\n\tMutationBuilder,\n\tNamedIndex,\n\tQuery,\n\tQueryBuilder,\n\tQueryInitializer,\n\tUserIdentity,\n} from 'convex/server'\nimport type { Triggers } from 'convex-helpers/server/triggers'\nimport type { TableNamesInDataModel } from 'convex/server'\nimport { defaultErrors, type ErrorFactory } from './errors'\nimport {\n\tregisterQueryReader,\n\tsuppliedPolicyRules,\n\ttype SecurityPolicyContext,\n} from './querying/security'\nexport type { SecurityPolicyContext } from './querying/security'\nimport {\n\tcomposeRules,\n\tcreateTenantRules,\n\twrapDatabaseReader,\n\twrapDatabaseWriter,\n\ttype RLSConfig,\n\ttype Rules,\n} from './tenancy'\n\n/** The default vocabulary; every app can supply its own via the Role generic. */\nexport type DefaultRole = 'reader' | 'writer' | 'admin'\n\nexport type Actor<Role extends string> = Readonly<{\n\tuserId: string\n\torganizationId: string\n\trole: Role\n}>\n\nexport type AuthBundle<Role extends string> = Readonly<{\n\tidentity: UserIdentity\n\tuser: Readonly<{ id: string }>\n\torg: Readonly<{ organizationId: string; role: Role }>\n\trole: Role\n\tactor: Actor<Role>\n\t/** The resolved tenant — security.tenancy.resolve, or the organization id. */\n\ttenant: string\n}>\n\n/**\n * Row-level security configuration. Tenant isolation and role-level rules\n * compose (AND) onto the same wrapped database: queries get a wrapped\n * reader, mutations get triggers first, then a wrapped writer.\n */\nexport type SecurityConfig<DataModel extends GenericDataModel, Role extends string> = {\n\t/**\n\t * Tenant isolation. `tables` is THE registry: every listed table gets\n\t * read/insert/modify gated on row.tenant === ctx.tenant. Pair with\n\t * tenantTable (schema) and tenantOwnership (triggers) on the same list.\n\t */\n\ttenancy?: {\n\t\ttables: readonly TableNamesInDataModel<DataModel>[]\n\t\t/** Maps the auth bundle to the tenant; defaults to org.organizationId. */\n\t\tresolve?: (bundle: Omit<AuthBundle<Role>, 'tenant'>) => string\n\t}\n\t/**\n\t * Role-level (or any policy) rules derived from the authenticated bundle,\n\t * composed AND-wise with tenant isolation. E.g. gate `modify` on a table\n\t * to admin roles.\n\t */\n\trules?: (bundle: AuthBundle<Role>) => Rules<SecurityPolicyContext<DataModel>, DataModel>\n\t/**\n\t * Policy for tables with no rule. Defaults to 'deny' when tenancy is\n\t * configured (unlisted tables are unreachable — fail closed), 'allow'\n\t * otherwise.\n\t */\n\tdefaultPolicy?: RLSConfig['defaultPolicy']\n}\n\ntype AnyAuthContext<DataModel extends GenericDataModel> =\n\t| GenericQueryCtx<DataModel>\n\t| GenericMutationCtx<DataModel>\n\t| GenericActionCtx<DataModel>\n\nexport type AuthFunctionsConfig<DataModel extends GenericDataModel, Role extends string> = {\n\t/** The consumer's generated function builders (from ./_generated/server). */\n\tquery: QueryBuilder<DataModel, 'public'>\n\tmutation: MutationBuilder<DataModel, 'public'>\n\taction: ActionBuilder<DataModel, 'public'>\n\tinternalQuery: QueryBuilder<DataModel, 'internal'>\n\tinternalMutation: MutationBuilder<DataModel, 'internal'>\n\tinternalAction: ActionBuilder<DataModel, 'internal'>\n\t/**\n\t * Resolves the synchronized principal, e.g. (ctx) => authKit.getAuthUser(ctx).\n\t * The already-resolved, non-null identity is supplied as a second argument.\n\t * Callbacks may ignore it; using it can avoid a redundant identity lookup.\n\t */\n\tgetAuthUser: (\n\t\tctx: AnyAuthContext<DataModel>,\n\t\tidentity: UserIdentity,\n\t) => Promise<{ id: string } | null>\n\t/**\n\t * Maps an identity role slug onto the app's role vocabulary. Returning\n\t * null rejects the caller with FORBIDDEN — unknown roles never pass.\n\t */\n\tmapRole: (roleSlug?: string) => Role | null\n\t/** Roles allowed through the admin* constructors. */\n\tadminRoles: readonly NoInfer<Role>[]\n\t/**\n\t * Live membership check for actions (queries/mutations trust the JWT).\n\t * Authentication fails closed with FORBIDDEN when verification errors.\n\t * Omit to let actions trust the JWT like queries do.\n\t */\n\tverifyMembership?: (input: {\n\t\tuserId: string\n\t\torganizationId: string\n\t}) => Promise<{ organizationId: string; roleSlug: string } | null>\n\t/**\n\t * Resolves organization authority from the app's own data for identity\n\t * providers whose tokens carry no org claims. When configured, its result\n\t * overrides claim-based resolution; null or an error rejects with FORBIDDEN\n\t * (fail closed). In actions the ctx has no db — resolve via ctx.runQuery.\n\t */\n\tresolveOrganization?: (input: {\n\t\tctx: AnyAuthContext<DataModel>\n\t\tidentity: UserIdentity\n\t\tuser: { id: string }\n\t}) => Promise<{ organizationId: string; roleSlug: string } | null>\n\t/** Host error policy; defaults to throwing KitError. */\n\terrors?: ErrorFactory\n\t/**\n\t * Application trigger registry. When set, every authMutation,\n\t * roleMutation, and systemMutation write runs through triggers.wrapDB —\n\t * evaluations registered on tables fire structurally.\n\t */\n\ttriggers?: Triggers<DataModel>\n\t/** Lower-level alternative to `triggers`: a custom ctx wrapper. */\n\twrapDB?: (ctx: GenericMutationCtx<DataModel>) => GenericMutationCtx<DataModel>\n\t/** Upper bound for include() reads. */\n\tmaxIncludedQueryRows?: number\n\t/**\n\t * Row-level security: tenant isolation (from a table registry) and\n\t * role-level rules, applied structurally inside every auth*, role*, and\n\t * admin* constructor. system* constructors stay unwrapped (trusted).\n\t */\n\tsecurity?: SecurityConfig<DataModel, Role>\n}\n\n/** WorkOS-style default: `member` writes; reader/writer/admin pass through. */\nexport function defaultRoleMap(roleSlug?: string): DefaultRole | null {\n\tconst normalized = roleSlug?.trim().toLowerCase()\n\tif (normalized === 'member') return 'writer'\n\treturn normalized === 'reader' || normalized === 'writer' || normalized === 'admin'\n\t\t? normalized\n\t\t: null\n}\n\nexport type IncludedQuery<Table extends GenericTableInfo> = {\n\twhen<Value>(\n\t\tvalue: Value | null | undefined,\n\t\tselect: (query: QueryInitializer<Table>, value: Value) => Query<Table>,\n\t): IncludedQuery<Table>\n\tmatching<IndexName extends IndexNames<Table>>(\n\t\tindexName: IndexName,\n\t\tindexRange?: (\n\t\t\tquery: IndexRangeBuilder<DocumentByInfo<Table>, NamedIndex<Table, IndexName>>,\n\t\t) => IndexRange,\n\t\tshouldMatch?: boolean,\n\t): IncludedQuery<Table>\n\totherwise(select: (query: QueryInitializer<Table>) => Query<Table>): Query<Table>\n\tresolve(): Query<Table>\n\texecute(limit: number): Promise<DocumentByInfo<Table>[]>\n\texecute<Result>(\n\t\tlimit: number,\n\t\ttransform: (data: Awaited<ReturnType<Query<Table>['take']>>) => Result | Promise<Result>,\n\t): Promise<Result>\n\t/**\n\t * Cursor pagination over the selected indexed query. numItems is bounded\n\t * by the same maxRows policy as execute(). Under row-level security a\n\t * page may be shorter than numItems (rejected rows are filtered after\n\t * pagination); cursors remain correct. Pair with paginated(dto) from\n\t * cvx-kit/zod-table for the boundary schemas.\n\t */\n\tpaginate(opts: PaginationOptions): Promise<PaginationResult<DocumentByInfo<Table>>>\n\tpaginate<Item>(\n\t\topts: PaginationOptions,\n\t\ttransform: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t): Promise<PaginationResult<Item>>\n}\n\nexport type Include = <Table extends GenericTableInfo>(\n\tquery: QueryInitializer<Table>,\n) => IncludedQuery<Table>\n\n/**\n * Keep native contexts symbolic in published declarations. Inferred spreads\n * copy build-time Convex methods and override the consumer's native context.\n */\nexport type AuthFunctions<DataModel extends GenericDataModel, Role extends string = DefaultRole> = {\n\tinclude: Include\n\tauthenticatedUser: (ctx: AnyAuthContext<DataModel>) => Promise<AuthBundle<Role>>\n\tauthQuery: CustomBuilder<\n\t\t'query',\n\t\t{},\n\t\tGenericQueryCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t{},\n\t\tGenericQueryCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\tauthMutation: CustomBuilder<\n\t\t'mutation',\n\t\t{},\n\t\tGenericMutationCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t{},\n\t\tGenericMutationCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\tauthAction: CustomBuilder<\n\t\t'action',\n\t\t{},\n\t\tGenericActionCtx<DataModel> & AuthBundle<Role>,\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\troleQuery: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authQuery']\n\troleMutation: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authMutation']\n\troleAction: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authAction']\n\tadminQuery: AuthFunctions<DataModel, Role>['authQuery']\n\tadminMutation: AuthFunctions<DataModel, Role>['authMutation']\n\tadminAction: AuthFunctions<DataModel, Role>['authAction']\n\tsystemQuery: CustomBuilder<\n\t\t'query',\n\t\t{},\n\t\tGenericQueryCtx<DataModel> & { include: Include },\n\t\t{},\n\t\tGenericQueryCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n\tsystemMutation: CustomBuilder<\n\t\t'mutation',\n\t\t{},\n\t\tGenericMutationCtx<DataModel> & { include: Include },\n\t\t{},\n\t\tGenericMutationCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n\tsystemAction: CustomBuilder<\n\t\t'action',\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n}\n\n/** Builds an include() that selects the first matching indexed query and bounds the read. */\nexport function createInclude(options?: { errors?: ErrorFactory; maxRows?: number }): Include {\n\tconst errors = options?.errors ?? defaultErrors\n\tconst maxRows = options?.maxRows ?? 100\n\n\tfunction attach<Table extends GenericTableInfo>(\n\t\tquery: QueryInitializer<Table>,\n\t\tselected?: Query<Table>,\n\t): IncludedQuery<Table> {\n\t\tfunction execute(limit: number): Promise<DocumentByInfo<Table>[]>\n\t\tfunction execute<Result>(\n\t\t\tlimit: number,\n\t\t\ttransform: (data: DocumentByInfo<Table>[]) => Result | Promise<Result>,\n\t\t): Promise<Result>\n\t\tasync function execute<Result>(\n\t\t\tlimit: number,\n\t\t\ttransform?: (data: DocumentByInfo<Table>[]) => Result | Promise<Result>,\n\t\t) {\n\t\t\tif (!Number.isSafeInteger(limit) || limit < 1 || limit > maxRows) {\n\t\t\t\treturn errors.throw({\n\t\t\t\t\tcode: 'INVALID_REQUEST_BOUNDARY',\n\t\t\t\t\tmessage: `A bounded query limit must be from 1 to ${maxRows}`,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst data = await (selected ?? query.fullTableScan()).take(limit)\n\t\t\treturn transform ? transform(data) : data\n\t\t}\n\t\tfunction paginate(opts: PaginationOptions): Promise<PaginationResult<DocumentByInfo<Table>>>\n\t\tfunction paginate<Item>(\n\t\t\topts: PaginationOptions,\n\t\t\ttransform: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t\t): Promise<PaginationResult<Item>>\n\t\tasync function paginate<Item>(\n\t\t\topts: PaginationOptions,\n\t\t\ttransform?: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t\t) {\n\t\t\tif (!Number.isSafeInteger(opts.numItems) || opts.numItems < 1 || opts.numItems > maxRows) {\n\t\t\t\treturn errors.throw({\n\t\t\t\t\tcode: 'INVALID_REQUEST_BOUNDARY',\n\t\t\t\t\tmessage: `A page size must be from 1 to ${maxRows}`,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst result = await (selected ?? query.fullTableScan()).paginate(opts)\n\t\t\treturn transform ? { ...result, page: await transform(result.page) } : result\n\t\t}\n\t\treturn {\n\t\t\twhen: (value, select) =>\n\t\t\t\tselected || value === undefined || value === null\n\t\t\t\t\t? attach(query, selected)\n\t\t\t\t\t: attach(query, select(query, value)),\n\t\t\tmatching: (indexName, indexRange, shouldMatch = true) =>\n\t\t\t\tselected || !shouldMatch\n\t\t\t\t\t? attach(query, selected)\n\t\t\t\t\t: attach(query, query.withIndex(indexName, indexRange)),\n\t\t\totherwise: (select) => selected ?? select(query),\n\t\t\tresolve: () => selected ?? query.fullTableScan(),\n\t\t\texecute,\n\t\t\tpaginate,\n\t\t}\n\t}\n\n\treturn (query) => attach(query)\n}\n\n/**\n * Builds the auth-aware function constructors from the host's injected\n * policy: identity resolution, the app's own role vocabulary, live\n * membership verification for actions, trigger wrapping for mutations,\n * and errors. Role-based access is first-class — every constructor family\n * has a role-gated variant (roleQuery/roleMutation/roleAction), and the\n * admin* constructors are just that gate applied to config.adminRoles.\n */\nexport function createAuthFunctions<\n\tDataModel extends GenericDataModel,\n\tconst Role extends string = DefaultRole,\n>(config: AuthFunctionsConfig<DataModel, Role>): AuthFunctions<DataModel, Role> {\n\tconst errors = config.errors ?? defaultErrors\n\tconst triggers = config.triggers\n\tconst wrapDB = triggers\n\t\t? (ctx: GenericMutationCtx<DataModel>) => triggers.wrapDB(ctx)\n\t\t: (config.wrapDB ?? ((ctx) => ctx))\n\tconst include = createInclude({\n\t\terrors,\n\t\tmaxRows: config.maxIncludedQueryRows,\n\t})\n\n\tasync function authenticatedUser(ctx: AnyAuthContext<DataModel>): Promise<AuthBundle<Role>> {\n\t\tconst identity = await ctx.auth.getUserIdentity()\n\t\tconst user = identity ? await config.getAuthUser(ctx, identity) : null\n\t\tif (!identity || !user) return errors.throw({ code: 'UNAUTHENTICATED' })\n\t\tlet organizationId: string\n\t\tlet organizationRole: string | undefined\n\t\tif (config.resolveOrganization) {\n\t\t\t// The hook is the organization authority — claims are skipped\n\t\t\t// entirely. Authentication fails closed when it errors or abstains.\n\t\t\tlet resolved: { organizationId: string; roleSlug: string } | null = null\n\t\t\ttry {\n\t\t\t\tresolved = await config.resolveOrganization({ ctx, identity, user })\n\t\t\t} catch {\n\t\t\t\t// Authentication fails closed when the hook cannot resolve.\n\t\t\t}\n\t\t\tif (!resolved) return errors.throw({ code: 'FORBIDDEN' })\n\t\t\torganizationId = resolved.organizationId\n\t\t\torganizationRole = resolved.roleSlug\n\t\t} else {\n\t\t\tconst claims = organizationClaims.parse(identity)\n\t\t\tconst claimedOrganizationId = claims.organization?.organizationId ?? claims.org_id\n\t\t\tif (!claimedOrganizationId) return errors.throw({ code: 'UNAUTHENTICATED' })\n\t\t\torganizationId = claimedOrganizationId\n\t\t\torganizationRole = claims.organization?.role ?? claims.role\n\t\t}\n\t\tconst role = config.mapRole(organizationRole)\n\t\tif (!role) return errors.throw({ code: 'FORBIDDEN' })\n\t\tconst base = {\n\t\t\tidentity,\n\t\t\tuser: Object.freeze({ id: user.id }),\n\t\t\torg: Object.freeze({ organizationId, role }),\n\t\t\trole,\n\t\t\tactor: Object.freeze({ userId: user.id, organizationId, role }),\n\t\t}\n\t\treturn Object.freeze({\n\t\t\t...base,\n\t\t\ttenant: config.security?.tenancy?.resolve?.(base) ?? organizationId,\n\t\t})\n\t}\n\n\tconst securityConfig: RLSConfig | undefined = config.security\n\t\t? {\n\t\t\t\tdefaultPolicy:\n\t\t\t\t\tconfig.security.defaultPolicy ?? (config.security.tenancy ? 'deny' : 'allow'),\n\t\t\t}\n\t\t: undefined\n\n\tfunction securityRules(\n\t\tbundle: AuthBundle<Role>,\n\t): Rules<SecurityPolicyContext<DataModel>, DataModel> | undefined {\n\t\tconst security = config.security\n\t\tif (!security) return undefined\n\t\tconst sets: Rules<SecurityPolicyContext<DataModel>, DataModel>[] = []\n\t\tif (security.tenancy) {\n\t\t\tsets.push(createTenantRules<DataModel>(bundle.tenant, security.tenancy.tables))\n\t\t}\n\t\tif (security.rules) sets.push(security.rules(bundle))\n\t\treturn sets.length === 1 ? sets[0] : composeRules(...sets)\n\t}\n\n\tfunction secureReader(\n\t\tctx: GenericQueryCtx<DataModel>,\n\t\tbundle: AuthBundle<Role>,\n\t): GenericQueryCtx<DataModel> {\n\t\tconst rules = securityRules(bundle)\n\t\tconst defaultPolicy = securityConfig?.defaultPolicy ?? 'allow'\n\t\tconst ordinary = rules\n\t\t\t? wrapDatabaseReader(\n\t\t\t\t\t{ db: ctx.db },\n\t\t\t\t\tctx.db,\n\t\t\t\t\tsuppliedPolicyRules(ctx.db, rules, defaultPolicy),\n\t\t\t\t\tsecurityConfig,\n\t\t\t\t)\n\t\t\t: ctx.db\n\t\treturn {\n\t\t\t...ctx,\n\t\t\tdb: registerQueryReader(ctx.db, ordinary, {\n\t\t\t\tscope: {\n\t\t\t\t\tmode: 'authenticated',\n\t\t\t\t\tprincipal: bundle.user.id,\n\t\t\t\t\torganization: bundle.org.organizationId,\n\t\t\t\t\ttenant: bundle.tenant,\n\t\t\t\t\trole: bundle.role,\n\t\t\t\t},\n\t\t\t\trules: rules ?? {},\n\t\t\t\tdefaultPolicy,\n\t\t\t}),\n\t\t}\n\t}\n\n\tfunction secureWriter(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\tbundle: AuthBundle<Role>,\n\t): GenericMutationCtx<DataModel> {\n\t\tconst rules = securityRules(bundle)\n\t\tif (!rules) return ctx\n\t\t// Triggers wrap first (ctx already trigger-wrapped by the caller),\n\t\t// then row-level security wraps the triggered db — order matters.\n\t\treturn {\n\t\t\t...ctx,\n\t\t\tdb: wrapDatabaseWriter(\n\t\t\t\t{ db: ctx.db },\n\t\t\t\tctx.db,\n\t\t\t\tsuppliedPolicyRules(ctx.db, rules, securityConfig?.defaultPolicy ?? 'allow'),\n\t\t\t\tsecurityConfig,\n\t\t\t),\n\t\t}\n\t}\n\n\tasync function verifiedMembership(userId: string, organizationId: string) {\n\t\tif (!config.verifyMembership) return null\n\t\ttry {\n\t\t\tconst membership = await config.verifyMembership({\n\t\t\t\tuserId,\n\t\t\t\torganizationId,\n\t\t\t})\n\t\t\tif (membership && membership.organizationId === organizationId) {\n\t\t\t\treturn membership\n\t\t\t}\n\t\t} catch {\n\t\t\t// Authentication fails closed when membership cannot be verified.\n\t\t}\n\t\treturn errors.throw({ code: 'FORBIDDEN' })\n\t}\n\n\tfunction requireRole(role: Role, allowed: readonly Role[]) {\n\t\tif (!allowed.includes(role)) return errors.throw({ code: 'FORBIDDEN' })\n\t}\n\n\tasync function queryInput(ctx: GenericQueryCtx<DataModel>) {\n\t\tconst bundle = await authenticatedUser(ctx)\n\t\treturn {\n\t\t\tctx: { ...secureReader(ctx, bundle), include, ...bundle },\n\t\t\targs: {},\n\t\t}\n\t}\n\n\tasync function mutationInput(ctx: GenericMutationCtx<DataModel>) {\n\t\tconst bundle = await authenticatedUser(ctx)\n\t\treturn {\n\t\t\tctx: { ...secureWriter(wrapDB(ctx), bundle), include, ...bundle },\n\t\t\targs: {},\n\t\t}\n\t}\n\n\tasync function actionInput(ctx: GenericActionCtx<DataModel>) {\n\t\tconst authenticated = await authenticatedUser(ctx)\n\t\tconst membership = await verifiedMembership(\n\t\t\tauthenticated.user.id,\n\t\t\tauthenticated.org.organizationId,\n\t\t)\n\t\tif (!membership) return { ctx: { ...ctx, ...authenticated }, args: {} }\n\t\tconst role = config.mapRole(membership.roleSlug)\n\t\tif (!role) return errors.throw({ code: 'FORBIDDEN' })\n\t\tconst verified = {\n\t\t\tidentity: authenticated.identity,\n\t\t\tuser: authenticated.user,\n\t\t\torg: Object.freeze({\n\t\t\t\torganizationId: membership.organizationId,\n\t\t\t\trole,\n\t\t\t}),\n\t\t\trole,\n\t\t\tactor: Object.freeze({\n\t\t\t\tuserId: authenticated.user.id,\n\t\t\t\torganizationId: membership.organizationId,\n\t\t\t\trole,\n\t\t\t}),\n\t\t}\n\t\treturn {\n\t\t\tctx: {\n\t\t\t\t...ctx,\n\t\t\t\t...verified,\n\t\t\t\t// Tenant re-derives from the live-verified organization.\n\t\t\t\ttenant: config.security?.tenancy?.resolve?.(verified) ?? membership.organizationId,\n\t\t\t},\n\t\t\targs: {},\n\t\t}\n\t}\n\n\t/** Query constructor allowing only the given roles. */\n\tfunction roleQuery(...allowed: readonly Role[]) {\n\t\treturn zCustomQuery(config.query, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst authenticated = await queryInput(ctx)\n\t\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\t\treturn authenticated\n\t\t\t},\n\t\t})\n\t}\n\n\t/** Mutation constructor allowing only the given roles. */\n\tfunction roleMutation(...allowed: readonly Role[]) {\n\t\treturn zCustomMutation(config.mutation, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst authenticated = await mutationInput(ctx)\n\t\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\t\treturn authenticated\n\t\t\t},\n\t\t})\n\t}\n\n\t/** Action constructor allowing only the given roles (post live verification). */\n\tfunction roleAction(...allowed: readonly Role[]) {\n\t\treturn zCustomAction(config.action, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst authenticated = await actionInput(ctx)\n\t\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\t\treturn authenticated\n\t\t\t},\n\t\t})\n\t}\n\n\treturn {\n\t\tinclude,\n\t\tauthenticatedUser,\n\t\troleQuery,\n\t\troleMutation,\n\t\troleAction,\n\t\tauthQuery: zCustomQuery(config.query, { args: {}, input: queryInput }),\n\t\tauthMutation: zCustomMutation(config.mutation, {\n\t\t\targs: {},\n\t\t\tinput: mutationInput,\n\t\t}),\n\t\tauthAction: zCustomAction(config.action, {\n\t\t\targs: {},\n\t\t\tinput: actionInput,\n\t\t}),\n\t\tadminQuery: roleQuery(...config.adminRoles),\n\t\tadminMutation: roleMutation(...config.adminRoles),\n\t\tadminAction: roleAction(...config.adminRoles),\n\t\tsystemQuery: zCustomQuery(config.internalQuery, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => ({\n\t\t\t\tctx: {\n\t\t\t\t\t...ctx,\n\t\t\t\t\tinclude,\n\t\t\t\t\tdb: registerQueryReader(ctx.db, ctx.db, {\n\t\t\t\t\t\tscope: {\n\t\t\t\t\t\t\tmode: 'system',\n\t\t\t\t\t\t\tprincipal: null,\n\t\t\t\t\t\t\torganization: null,\n\t\t\t\t\t\t\ttenant: null,\n\t\t\t\t\t\t\trole: null,\n\t\t\t\t\t\t},\n\t\t\t\t\t\trules: {},\n\t\t\t\t\t\tdefaultPolicy: 'allow',\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t\targs: {},\n\t\t\t}),\n\t\t}),\n\t\tsystemMutation: zCustomMutation(config.internalMutation, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => ({ ctx: { ...wrapDB(ctx), include }, args: {} }),\n\t\t}),\n\t\tsystemAction: zCustomAction(config.internalAction, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => ({ ctx, args: {} }),\n\t\t}),\n\t}\n}\n\nconst organizationClaims = z.object({\n\torganization: z\n\t\t.object({\n\t\t\torganizationId: z.string().optional().catch(undefined),\n\t\t\trole: z.string().optional().catch(undefined),\n\t\t})\n\t\t.optional()\n\t\t.catch(undefined),\n\torg_id: z.string().optional().catch(undefined),\n\trole: z.string().optional().catch(undefined),\n})\n"],"mappings":"8WAgKA,SAAgBA,EAAe,EAAuC,CACrE,IAAMC,EAAaC,GAAU,KAAK,CAAC,CAAC,YAAY,EAEhD,OADID,IAAe,SAAiB,SAC7BA,IAAe,UAAYA,IAAe,UAAYA,IAAe,QACzEA,EACA,IACJ,CA6GA,SAAgBE,EAAc,EAAgE,CAC7F,IAAMC,EAASC,GAAS,QAAUC,EAC5BC,EAAUF,GAAS,SAAW,IAEpC,SAASG,EACR,EACA,EACuB,CAMvB,eAAeC,EACd,EACA,EACC,CACD,GAAI,CAAC,OAAO,cAAcC,CAAK,GAAKA,EAAQ,GAAKA,EAAQH,EACxD,OAAOH,EAAO,MAA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AIA,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,eAAgByC,EAAgB5C,EAAO,iBAAkB,CACxD,KAAM,CAAC,EACP,MAAO,KAAO,KAAS,CAAE,IAAK,CAAE,GAAGE,EAAOC,CAAG,EAAG,SAAQ,EAAG,KAAM,CAAC,CAAE,EACrE,CAAC,EACD,aAAc2C,EAAc9C,EAAO,eAAgB,CAClD,KAAM,CAAC,EACP,MAAO,KAAO,KAAS,CAAE,MAAK,KAAM,CAAC,CAAE,EACxC,CAAC,CACF,CACD,CAEA,MAAMY,EAAqBmC,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","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().cat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arFilters, ScalarSelection, ServerFilter } from "./querying/filters
|
|
|
4
4
|
import { DtoOptions, TIMESTAMP_FIELDS, TableBoundaryOptions, createModule, createTable, jsonSafeZid, paginated, tenantTable, zodTable, zodVariantTable } from "./zod-table.mjs";
|
|
5
5
|
import { FieldReference, RelationBuilder, RelationDeclarations, RelationEdge, RelationFilterSelection, RelationFilters, RelationRegistry, RelationRegistryIdentity, RelationRow, RelationSelection, RelationTable, RelationTableHelpers, RelationTables, ThroughReference, defineRelations } from "./relations.mjs";
|
|
6
6
|
import { RLSConfig, Rules, TENANT_FIELD, assertTenantOwned, composeRules, createTenantRules, requireTenantReference } from "./tenancy.mjs";
|
|
7
|
-
import { Actor, AuthBundle, AuthFunctions, AuthFunctionsConfig, DefaultRole, Include, IncludedQuery, SecurityConfig, createAuthFunctions, createInclude, defaultRoleMap } from "./auth.mjs";
|
|
7
|
+
import { Actor, AuthBundle, AuthFunctions, AuthFunctionsConfig, DefaultRole, Include, IncludedQuery, SecurityBundle, SecurityConfig, ServiceMutation, ServicePrincipal, ServiceQuery, createAuthFunctions, createInclude, defaultRoleMap } from "./auth.mjs";
|
|
8
8
|
import { AnyQueryMiddleware, QueryMiddleware } from "./components/foundation/modules/query/query.mjs";
|
|
9
9
|
import { AnyCommandMiddleware, ApplicationCommand, AuditEntryInput, AuditWriter, AuditedOperation, AuditedRegistry, CommandConstructor, CommandDefaults, CommandMiddleware, Foundation, FoundationOptions, PermissionChecker } from "./components/foundation/client.mjs";
|
|
10
10
|
import { CrudConfig, createCrudCommands } from "./crud.mjs";
|
|
11
11
|
import { RateLimiterLike, rateLimit } from "./middleware.mjs";
|
|
12
12
|
import { WebhookBoundaryConfig, createWebhookBoundary, recordWebhookEvent, webhookEventsTable } from "./webhooks.mjs";
|
|
13
13
|
import { createStateMachine } from "./state-machine.mjs";
|
|
14
|
-
import { Change, Trigger, Triggers, appendOnly, createTriggers, noDelete, tenantOwnership, timestamps } from "./triggers.mjs";
|
|
14
|
+
import { Change, Trigger, Triggers, appendOnly, createTriggers, noDelete, tenantOwnership, timestamps, triggerContext } from "./triggers.mjs";
|
|
15
15
|
import { FoundationRegistry, FoundationRegistryOptions, createFoundation } from "./modules/foundation/foundation.mjs";
|
|
16
16
|
import { QueryEngineConfig, createQueryEngine } from "./querying.mjs";
|
|
17
|
-
export { type Actor, type AgentToolHandlers, type AgentToolRecord, type AnyCommandMiddleware, type AnyQueryMiddleware, type ApplicationCommand, type AuditEntryInput, type AuditWriter, type AuditedOperation, type AuditedRegistry, type AuthBundle, type AuthFunctions, type AuthFunctionsConfig, type Change, type CommandConstructor, type CommandDefaults, type CommandMiddleware, type CrudConfig, type DefaultRole, type DtoOptions, type ErrorFactory, type FieldReference, Foundation, type FoundationOptions, type FoundationRegistry, type FoundationRegistryOptions, type Include, type IncludedQuery, KitError, type PermissionChecker, type QueryEngineConfig, type QueryMiddleware, type RLSConfig, type RateLimiterLike, type RelationBuilder, type RelationDeclarations, type RelationEdge, type RelationFilterSelection, type RelationFilters, type RelationRegistry, type RelationRegistryIdentity, type RelationRow, type RelationSelection, type RelationTable, type RelationTableHelpers, type RelationTables, type Rules, type ScalarFilters, type ScalarSelection, type SecurityConfig, type ServerFilter, TENANT_FIELD, TIMESTAMP_FIELDS, type TableBoundaryOptions, type ThroughReference, type Trigger, Triggers, type WebhookBoundaryConfig, appendOnly, assertTenantOwned, composeRules, createAgentTools, createAuthFunctions, createCrudCommands, createFoundation, createInclude, createModule, createQueryEngine, createStateMachine, createTable, createTenantRules, createTriggers, createWebhookBoundary, defaultErrors, defaultRoleMap, defineRelations, jsonSafeZid, noDelete, paginated, rateLimit, recordWebhookEvent, requireTenantReference, tenantOwnership, tenantTable, timestamps, webhookEventsTable, zodTable, zodVariantTable };
|
|
17
|
+
export { type Actor, type AgentToolHandlers, type AgentToolRecord, type AnyCommandMiddleware, type AnyQueryMiddleware, type ApplicationCommand, type AuditEntryInput, type AuditWriter, type AuditedOperation, type AuditedRegistry, type AuthBundle, type AuthFunctions, type AuthFunctionsConfig, type Change, type CommandConstructor, type CommandDefaults, type CommandMiddleware, type CrudConfig, type DefaultRole, type DtoOptions, type ErrorFactory, type FieldReference, Foundation, type FoundationOptions, type FoundationRegistry, type FoundationRegistryOptions, type Include, type IncludedQuery, KitError, type PermissionChecker, type QueryEngineConfig, type QueryMiddleware, type RLSConfig, type RateLimiterLike, type RelationBuilder, type RelationDeclarations, type RelationEdge, type RelationFilterSelection, type RelationFilters, type RelationRegistry, type RelationRegistryIdentity, type RelationRow, type RelationSelection, type RelationTable, type RelationTableHelpers, type RelationTables, type Rules, type ScalarFilters, type ScalarSelection, type SecurityBundle, type SecurityConfig, type ServerFilter, type ServiceMutation, type ServicePrincipal, type ServiceQuery, TENANT_FIELD, TIMESTAMP_FIELDS, type TableBoundaryOptions, type ThroughReference, type Trigger, Triggers, type WebhookBoundaryConfig, appendOnly, assertTenantOwned, composeRules, createAgentTools, createAuthFunctions, createCrudCommands, createFoundation, createInclude, createModule, createQueryEngine, createStateMachine, createTable, createTenantRules, createTriggers, createWebhookBoundary, defaultErrors, defaultRoleMap, defineRelations, jsonSafeZid, noDelete, paginated, rateLimit, recordWebhookEvent, requireTenantReference, tenantOwnership, tenantTable, timestamps, triggerContext, webhookEventsTable, zodTable, zodVariantTable };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createAgentTools as e}from"./agent-tools.mjs";import{KitError as t,defaultErrors as n}from"./errors.mjs";import{TENANT_FIELD as r,assertTenantOwned as i,composeRules as a,createTenantRules as o,requireTenantReference as s}from"./tenancy.mjs";import{createAuthFunctions as c,createInclude as l,defaultRoleMap as u}from"./auth.mjs";import{createCrudCommands as d}from"./crud.mjs";import{TIMESTAMP_FIELDS as f,createModule as p,createTable as m,jsonSafeZid as h,paginated as g,tenantTable as _,zodTable as v,zodVariantTable as y}from"./zod-table.mjs";import{rateLimit as b}from"./middleware.mjs";import{createWebhookBoundary as x,recordWebhookEvent as S,webhookEventsTable as C}from"./webhooks.mjs";import{createStateMachine as w}from"./state-machine.mjs";import{Triggers as T,appendOnly as E,createTriggers as D,noDelete as O,tenantOwnership as k,timestamps as A}from"./triggers.mjs";import{Foundation as
|
|
1
|
+
import{createAgentTools as e}from"./agent-tools.mjs";import{KitError as t,defaultErrors as n}from"./errors.mjs";import{TENANT_FIELD as r,assertTenantOwned as i,composeRules as a,createTenantRules as o,requireTenantReference as s}from"./tenancy.mjs";import{createAuthFunctions as c,createInclude as l,defaultRoleMap as u}from"./auth.mjs";import{createCrudCommands as d}from"./crud.mjs";import{TIMESTAMP_FIELDS as f,createModule as p,createTable as m,jsonSafeZid as h,paginated as g,tenantTable as _,zodTable as v,zodVariantTable as y}from"./zod-table.mjs";import{rateLimit as b}from"./middleware.mjs";import{createWebhookBoundary as x,recordWebhookEvent as S,webhookEventsTable as C}from"./webhooks.mjs";import{createStateMachine as w}from"./state-machine.mjs";import{Triggers as T,appendOnly as E,createTriggers as D,noDelete as O,tenantOwnership as k,timestamps as A,triggerContext as j}from"./triggers.mjs";import{Foundation as M}from"./components/foundation/client.mjs";import{createFoundation as N}from"./modules/foundation/foundation.mjs";import{defineRelations as P}from"./relations.mjs";import{createQueryEngine as F}from"./querying.mjs";export{M as Foundation,t as KitError,r as TENANT_FIELD,f as TIMESTAMP_FIELDS,T as Triggers,E as appendOnly,i as assertTenantOwned,a as composeRules,e as createAgentTools,c as createAuthFunctions,d as createCrudCommands,N as createFoundation,l as createInclude,p as createModule,F as createQueryEngine,w as createStateMachine,m as createTable,o as createTenantRules,D as createTriggers,x as createWebhookBoundary,n as defaultErrors,u as defaultRoleMap,P as defineRelations,h as jsonSafeZid,O as noDelete,g as paginated,b as rateLimit,S as recordWebhookEvent,s as requireTenantReference,k as tenantOwnership,_ as tenantTable,A as timestamps,j as triggerContext,C as webhookEventsTable,v as zodTable,y as zodVariantTable};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AuthBundle, AuthFunctions, AuthFunctionsConfig, DefaultRole, Include } from "../../auth.mjs";
|
|
1
|
+
import { AuthBundle, AuthFunctions, AuthFunctionsConfig, DefaultRole, Include, ServiceMutation, ServicePrincipal, ServiceQuery } from "../../auth.mjs";
|
|
2
2
|
import { EffectValue } from "./operation.mjs";
|
|
3
3
|
import { EffectApiContext, EffectApiOptions, EffectApiServices, ProvidedServices } from "./api-runtime.mjs";
|
|
4
4
|
import { EffectZodApiBuilder } from "./api-zod.mjs";
|
|
@@ -18,6 +18,10 @@ export type EffectAuthFunctions<DataModel extends GenericDataModel, Role extends
|
|
|
18
18
|
authAction: Adapted<AuthFunctions<DataModel, Role>['authAction'], ActionServices, ActionAdded>;
|
|
19
19
|
roleAction: (...allowed: readonly Role[]) => Adapted<AuthFunctions<DataModel, Role>['authAction'], ActionServices, ActionAdded>;
|
|
20
20
|
adminAction: Adapted<AuthFunctions<DataModel, Role>['authAction'], ActionServices, ActionAdded>;
|
|
21
|
+
/** Service principals share the `query` policy; the host factory is the only principal source. */
|
|
22
|
+
serviceQuery: <Extra extends Record<string, unknown> = {}>(principal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>) => Adapted<ServiceQuery<DataModel, Role, Extra>, QueryServices, QueryAdded>;
|
|
23
|
+
/** Service principals share the `mutation` policy. */
|
|
24
|
+
serviceMutation: <Extra extends Record<string, unknown> = {}>(principal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>) => Adapted<ServiceMutation<DataModel, Role, Extra>, MutationServices, MutationAdded>;
|
|
21
25
|
systemQuery: Adapted<AuthFunctions<DataModel, Role>['systemQuery'], SystemQueryServices, SystemQueryAdded>;
|
|
22
26
|
systemMutation: Adapted<AuthFunctions<DataModel, Role>['systemMutation'], SystemMutationServices, SystemMutationAdded>;
|
|
23
27
|
systemAction: Adapted<AuthFunctions<DataModel, Role>['systemAction'], SystemActionServices, SystemActionAdded>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createAuthFunctions as e}from"../../auth.mjs";import{
|
|
1
|
+
import{createAuthFunctions as e}from"../../auth.mjs";import{wrapEffectBuilder as t}from"./api-runtime.mjs";import{effectZodApiBuilder as n}from"./api-zod.mjs";function r(t,r){let a=e(t);return{include:a.include,authenticatedUser:a.authenticatedUser,authQuery:n(a.authQuery,r.query),roleQuery:(...e)=>n(a.roleQuery(...e),r.query),adminQuery:n(a.adminQuery,r.query),authMutation:n(a.authMutation,r.mutation),roleMutation:(...e)=>n(a.roleMutation(...e),r.mutation),adminMutation:n(a.adminMutation,r.mutation),authAction:n(a.authAction,r.action),roleAction:(...e)=>n(a.roleAction(...e),r.action),adminAction:n(a.adminAction,r.action),serviceQuery:e=>i(a.serviceQuery(e),r.query),serviceMutation:e=>i(a.serviceMutation(e),r.mutation),systemQuery:n(a.systemQuery,r.systemQuery),systemMutation:n(a.systemMutation,r.systemMutation),systemAction:n(a.systemAction,r.systemAction)}}function i(e,n){return t(e,n)}export{r as createEffectAuthFunctions};
|
|
2
2
|
//# sourceMappingURL=auth.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.mjs","names":["createEffectAuthFunctions","auth","createAuthFunctions","config","effectZodApiBuilder","options","allowed"],"sources":["../../../src/modules/effect/auth.ts"],"sourcesContent":["import type { Context } from 'effect'\nimport type {\n\tGenericDataModel,\n\tGenericQueryCtx,\n\tGenericMutationCtx,\n\tGenericActionCtx,\n} from 'convex/server'\nimport type { CustomBuilder } from 'convex-helpers/server/zod4'\nimport {\n\tcreateAuthFunctions,\n\ttype AuthFunctions,\n\ttype AuthFunctionsConfig,\n\ttype AuthBundle,\n\ttype DefaultRole,\n\ttype Include,\n} from '../../auth'\nimport { effectZodApiBuilder, type EffectZodApiBuilder } from './api-zod'\nimport type {\n\tEffectApiOptions,\n\tEffectApiServices,\n\tEffectApiContext,\n\tProvidedServices,\n} from './api-runtime'\nimport type { EffectValue } from './operation'\n\n// Derive the adapter from the symbolic auth contract, never from inferred native spreads.\ntype Adapted<Builder, Services, Added> =\n\tBuilder extends CustomBuilder<\n\t\tinfer Kind,\n\t\tinfer Args,\n\t\tinfer Ctx,\n\t\tinfer Made,\n\t\tinfer Input,\n\t\tinfer Visibility,\n\t\tinfer Extra\n\t>\n\t\t? EffectZodApiBuilder<\n\t\t\t\tKind,\n\t\t\t\tArgs,\n\t\t\t\tCtx,\n\t\t\t\tMade,\n\t\t\t\tInput,\n\t\t\t\tVisibility,\n\t\t\t\tExtra,\n\t\t\t\tProvidedServices<Services>,\n\t\t\t\tEffectValue<Added>,\n\t\t\t\tAdded\n\t\t\t>\n\t\t: never\n\n/** Shared post-auth composition; internal/system policies are configured separately. */\nexport type EffectAuthFunctions<\n\tDataModel extends GenericDataModel,\n\tRole extends string = DefaultRole,\n\tQueryServices extends EffectApiServices = Context.Context<never>,\n\tQueryAdded extends EffectApiContext = {},\n\tMutationServices extends EffectApiServices = Context.Context<never>,\n\tMutationAdded extends EffectApiContext = {},\n\tActionServices extends EffectApiServices = Context.Context<never>,\n\tActionAdded extends EffectApiContext = {},\n\tSystemQueryServices extends EffectApiServices = Context.Context<never>,\n\tSystemQueryAdded extends EffectApiContext = {},\n\tSystemMutationServices extends EffectApiServices = Context.Context<never>,\n\tSystemMutationAdded extends EffectApiContext = {},\n\tSystemActionServices extends EffectApiServices = Context.Context<never>,\n\tSystemActionAdded extends EffectApiContext = {},\n> = Pick<AuthFunctions<DataModel, Role>, 'include' | 'authenticatedUser'> & {\n\tauthQuery: Adapted<AuthFunctions<DataModel, Role>['authQuery'], QueryServices, QueryAdded>\n\troleQuery: (\n\t\t...allowed: readonly Role[]\n\t) => Adapted<AuthFunctions<DataModel, Role>['authQuery'], QueryServices, QueryAdded>\n\tadminQuery: Adapted<AuthFunctions<DataModel, Role>['authQuery'], QueryServices, QueryAdded>\n\tauthMutation: Adapted<\n\t\tAuthFunctions<DataModel, Role>['authMutation'],\n\t\tMutationServices,\n\t\tMutationAdded\n\t>\n\troleMutation: (\n\t\t...allowed: readonly Role[]\n\t) => Adapted<AuthFunctions<DataModel, Role>['authMutation'], MutationServices, MutationAdded>\n\tadminMutation: Adapted<\n\t\tAuthFunctions<DataModel, Role>['authMutation'],\n\t\tMutationServices,\n\t\tMutationAdded\n\t>\n\tauthAction: Adapted<AuthFunctions<DataModel, Role>['authAction'], ActionServices, ActionAdded>\n\troleAction: (\n\t\t...allowed: readonly Role[]\n\t) => Adapted<AuthFunctions<DataModel, Role>['authAction'], ActionServices, ActionAdded>\n\tadminAction: Adapted<AuthFunctions<DataModel, Role>['authAction'], ActionServices, ActionAdded>\n\tsystemQuery: Adapted<\n\t\tAuthFunctions<DataModel, Role>['systemQuery'],\n\t\tSystemQueryServices,\n\t\tSystemQueryAdded\n\t>\n\tsystemMutation: Adapted<\n\t\tAuthFunctions<DataModel, Role>['systemMutation'],\n\t\tSystemMutationServices,\n\t\tSystemMutationAdded\n\t>\n\tsystemAction: Adapted<\n\t\tAuthFunctions<DataModel, Role>['systemAction'],\n\t\tSystemActionServices,\n\t\tSystemActionAdded\n\t>\n}\n\n/** Providers and handles run once per invocation after security and live role checks. */\nexport function createEffectAuthFunctions<\n\tDataModel extends GenericDataModel,\n\tconst Role extends string = DefaultRole,\n\tQueryServices extends EffectApiServices = Context.Context<never>,\n\tQueryAdded extends EffectApiContext = {},\n\tMutationServices extends EffectApiServices = Context.Context<never>,\n\tMutationAdded extends EffectApiContext = {},\n\tActionServices extends EffectApiServices = Context.Context<never>,\n\tActionAdded extends EffectApiContext = {},\n\tSystemQueryServices extends EffectApiServices = Context.Context<never>,\n\tSystemQueryAdded extends EffectApiContext = {},\n\tSystemMutationServices extends EffectApiServices = Context.Context<never>,\n\tSystemMutationAdded extends EffectApiContext = {},\n\tSystemActionServices extends EffectApiServices = Context.Context<never>,\n\tSystemActionAdded extends EffectApiContext = {},\n>(\n\tconfig: AuthFunctionsConfig<DataModel, Role>,\n\toptions: {\n\t\tquery: EffectApiOptions<\n\t\t\tGenericQueryCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t\tQueryServices,\n\t\t\tQueryAdded\n\t\t>\n\t\tmutation: EffectApiOptions<\n\t\t\tGenericMutationCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t\tMutationServices,\n\t\t\tMutationAdded\n\t\t>\n\t\taction: EffectApiOptions<\n\t\t\tGenericActionCtx<DataModel> & AuthBundle<Role>,\n\t\t\tActionServices,\n\t\t\tActionAdded\n\t\t>\n\t\tsystemQuery: EffectApiOptions<\n\t\t\tGenericQueryCtx<DataModel> & { include: Include },\n\t\t\tSystemQueryServices,\n\t\t\tSystemQueryAdded\n\t\t>\n\t\tsystemMutation: EffectApiOptions<\n\t\t\tGenericMutationCtx<DataModel> & { include: Include },\n\t\t\tSystemMutationServices,\n\t\t\tSystemMutationAdded\n\t\t>\n\t\tsystemAction: EffectApiOptions<\n\t\t\tGenericActionCtx<DataModel>,\n\t\t\tSystemActionServices,\n\t\t\tSystemActionAdded\n\t\t>\n\t},\n): EffectAuthFunctions<\n\tDataModel,\n\tRole,\n\tQueryServices,\n\tQueryAdded,\n\tMutationServices,\n\tMutationAdded,\n\tActionServices,\n\tActionAdded,\n\tSystemQueryServices,\n\tSystemQueryAdded,\n\tSystemMutationServices,\n\tSystemMutationAdded,\n\tSystemActionServices,\n\tSystemActionAdded\n> {\n\tconst auth = createAuthFunctions(config)\n\treturn {\n\t\tinclude: auth.include,\n\t\tauthenticatedUser: auth.authenticatedUser,\n\t\tauthQuery: effectZodApiBuilder(auth.authQuery, options.query),\n\t\troleQuery: (...allowed) => effectZodApiBuilder(auth.roleQuery(...allowed), options.query),\n\t\tadminQuery: effectZodApiBuilder(auth.adminQuery, options.query),\n\t\tauthMutation: effectZodApiBuilder(auth.authMutation, options.mutation),\n\t\troleMutation: (...allowed) =>\n\t\t\teffectZodApiBuilder(auth.roleMutation(...allowed), options.mutation),\n\t\tadminMutation: effectZodApiBuilder(auth.adminMutation, options.mutation),\n\t\tauthAction: effectZodApiBuilder(auth.authAction, options.action),\n\t\troleAction: (...allowed) => effectZodApiBuilder(auth.roleAction(...allowed), options.action),\n\t\tadminAction: effectZodApiBuilder(auth.adminAction, options.action),\n\t\tsystemQuery: effectZodApiBuilder(auth.systemQuery, options.systemQuery),\n\t\tsystemMutation: effectZodApiBuilder(auth.systemMutation, options.systemMutation),\n\t\tsystemAction: effectZodApiBuilder(auth.systemAction, options.systemAction),\n\t}\n}\n"],"mappings":"yGA4GA,SAAgBA,EAgBf,EACA,EA+CC,CACD,IAAMC,EAAOC,EAAoBC,CAAM,EACvC,MAAO,CACN,QAASF,EAAK,QACd,kBAAmBA,EAAK,kBACxB,UAAWG,EAAoBH,EAAK,UAAWI,EAAQ,KAAK,EAC5D,WAAY,GAAGC,IAAYF,EAAoBH,EAAK,UAAU,GAAGK,CAAO,EAAGD,EAAQ,KAAK,EACxF,WAAYD,EAAoBH,EAAK,WAAYI,EAAQ,KAAK,EAC9D,aAAcD,EAAoBH,EAAK,aAAcI,EAAQ,QAAQ,EACrE,cAAe,GAAGC,IACjBF,EAAoBH,EAAK,aAAa,GAAGK,CAAO,EAAGD,EAAQ,QAAQ,EACpE,cAAeD,EAAoBH,EAAK,cAAeI,EAAQ,QAAQ,EACvE,WAAYD,EAAoBH,EAAK,WAAYI,EAAQ,MAAM,EAC/D,YAAa,GAAGC,IAAYF,EAAoBH,EAAK,WAAW,GAAGK,CAAO,EAAGD,EAAQ,MAAM,EAC3F,YAAaD,EAAoBH,EAAK,YAAaI,EAAQ,MAAM,EACjE,YAAaD,EAAoBH,EAAK,YAAaI,EAAQ,WAAW,EACtE,eAAgBD,EAAoBH,EAAK,eAAgBI,EAAQ,cAAc,EAC/E,aAAcD,EAAoBH,EAAK,aAAcI,EAAQ,YAAY,CAC1E,CACD"}
|
|
1
|
+
{"version":3,"file":"auth.mjs","names":["createEffectAuthFunctions","auth","createAuthFunctions","config","effectZodApiBuilder","options","allowed","adaptService","principal","wrapEffectBuilder","builder"],"sources":["../../../src/modules/effect/auth.ts"],"sourcesContent":["import type { Context } from 'effect'\nimport type {\n\tGenericDataModel,\n\tGenericQueryCtx,\n\tGenericMutationCtx,\n\tGenericActionCtx,\n} from 'convex/server'\nimport type { CustomBuilder } from 'convex-helpers/server/zod4'\nimport {\n\tcreateAuthFunctions,\n\ttype AuthFunctions,\n\ttype AuthFunctionsConfig,\n\ttype AuthBundle,\n\ttype DefaultRole,\n\ttype Include,\n\ttype ServicePrincipal,\n\ttype ServiceQuery,\n\ttype ServiceMutation,\n} from '../../auth'\nimport { effectZodApiBuilder, type EffectZodApiBuilder } from './api-zod'\nimport {\n\twrapEffectBuilder,\n\ttype EffectApiOptions,\n\ttype EffectApiServices,\n\ttype EffectApiContext,\n\ttype ProvidedServices,\n} from './api-runtime'\nimport type { EffectValue } from './operation'\n\n// Derive the adapter from the symbolic auth contract, never from inferred native spreads.\ntype Adapted<Builder, Services, Added> =\n\tBuilder extends CustomBuilder<\n\t\tinfer Kind,\n\t\tinfer Args,\n\t\tinfer Ctx,\n\t\tinfer Made,\n\t\tinfer Input,\n\t\tinfer Visibility,\n\t\tinfer Extra\n\t>\n\t\t? EffectZodApiBuilder<\n\t\t\t\tKind,\n\t\t\t\tArgs,\n\t\t\t\tCtx,\n\t\t\t\tMade,\n\t\t\t\tInput,\n\t\t\t\tVisibility,\n\t\t\t\tExtra,\n\t\t\t\tProvidedServices<Services>,\n\t\t\t\tEffectValue<Added>,\n\t\t\t\tAdded\n\t\t\t>\n\t\t: never\n\n/** Shared post-auth composition; internal/system policies are configured separately. */\nexport type EffectAuthFunctions<\n\tDataModel extends GenericDataModel,\n\tRole extends string = DefaultRole,\n\tQueryServices extends EffectApiServices = Context.Context<never>,\n\tQueryAdded extends EffectApiContext = {},\n\tMutationServices extends EffectApiServices = Context.Context<never>,\n\tMutationAdded extends EffectApiContext = {},\n\tActionServices extends EffectApiServices = Context.Context<never>,\n\tActionAdded extends EffectApiContext = {},\n\tSystemQueryServices extends EffectApiServices = Context.Context<never>,\n\tSystemQueryAdded extends EffectApiContext = {},\n\tSystemMutationServices extends EffectApiServices = Context.Context<never>,\n\tSystemMutationAdded extends EffectApiContext = {},\n\tSystemActionServices extends EffectApiServices = Context.Context<never>,\n\tSystemActionAdded extends EffectApiContext = {},\n> = Pick<AuthFunctions<DataModel, Role>, 'include' | 'authenticatedUser'> & {\n\tauthQuery: Adapted<AuthFunctions<DataModel, Role>['authQuery'], QueryServices, QueryAdded>\n\troleQuery: (\n\t\t...allowed: readonly Role[]\n\t) => Adapted<AuthFunctions<DataModel, Role>['authQuery'], QueryServices, QueryAdded>\n\tadminQuery: Adapted<AuthFunctions<DataModel, Role>['authQuery'], QueryServices, QueryAdded>\n\tauthMutation: Adapted<\n\t\tAuthFunctions<DataModel, Role>['authMutation'],\n\t\tMutationServices,\n\t\tMutationAdded\n\t>\n\troleMutation: (\n\t\t...allowed: readonly Role[]\n\t) => Adapted<AuthFunctions<DataModel, Role>['authMutation'], MutationServices, MutationAdded>\n\tadminMutation: Adapted<\n\t\tAuthFunctions<DataModel, Role>['authMutation'],\n\t\tMutationServices,\n\t\tMutationAdded\n\t>\n\tauthAction: Adapted<AuthFunctions<DataModel, Role>['authAction'], ActionServices, ActionAdded>\n\troleAction: (\n\t\t...allowed: readonly Role[]\n\t) => Adapted<AuthFunctions<DataModel, Role>['authAction'], ActionServices, ActionAdded>\n\tadminAction: Adapted<AuthFunctions<DataModel, Role>['authAction'], ActionServices, ActionAdded>\n\t/** Service principals share the `query` policy; the host factory is the only principal source. */\n\tserviceQuery: <Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>,\n\t) => Adapted<ServiceQuery<DataModel, Role, Extra>, QueryServices, QueryAdded>\n\t/** Service principals share the `mutation` policy. */\n\tserviceMutation: <Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>,\n\t) => Adapted<ServiceMutation<DataModel, Role, Extra>, MutationServices, MutationAdded>\n\tsystemQuery: Adapted<\n\t\tAuthFunctions<DataModel, Role>['systemQuery'],\n\t\tSystemQueryServices,\n\t\tSystemQueryAdded\n\t>\n\tsystemMutation: Adapted<\n\t\tAuthFunctions<DataModel, Role>['systemMutation'],\n\t\tSystemMutationServices,\n\t\tSystemMutationAdded\n\t>\n\tsystemAction: Adapted<\n\t\tAuthFunctions<DataModel, Role>['systemAction'],\n\t\tSystemActionServices,\n\t\tSystemActionAdded\n\t>\n}\n\n/** Providers and handles run once per invocation after security and live role checks. */\nexport function createEffectAuthFunctions<\n\tDataModel extends GenericDataModel,\n\tconst Role extends string = DefaultRole,\n\tQueryServices extends EffectApiServices = Context.Context<never>,\n\tQueryAdded extends EffectApiContext = {},\n\tMutationServices extends EffectApiServices = Context.Context<never>,\n\tMutationAdded extends EffectApiContext = {},\n\tActionServices extends EffectApiServices = Context.Context<never>,\n\tActionAdded extends EffectApiContext = {},\n\tSystemQueryServices extends EffectApiServices = Context.Context<never>,\n\tSystemQueryAdded extends EffectApiContext = {},\n\tSystemMutationServices extends EffectApiServices = Context.Context<never>,\n\tSystemMutationAdded extends EffectApiContext = {},\n\tSystemActionServices extends EffectApiServices = Context.Context<never>,\n\tSystemActionAdded extends EffectApiContext = {},\n>(\n\tconfig: AuthFunctionsConfig<DataModel, Role>,\n\toptions: {\n\t\tquery: EffectApiOptions<\n\t\t\tGenericQueryCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t\tQueryServices,\n\t\t\tQueryAdded\n\t\t>\n\t\tmutation: EffectApiOptions<\n\t\t\tGenericMutationCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t\tMutationServices,\n\t\t\tMutationAdded\n\t\t>\n\t\taction: EffectApiOptions<\n\t\t\tGenericActionCtx<DataModel> & AuthBundle<Role>,\n\t\t\tActionServices,\n\t\t\tActionAdded\n\t\t>\n\t\tsystemQuery: EffectApiOptions<\n\t\t\tGenericQueryCtx<DataModel> & { include: Include },\n\t\t\tSystemQueryServices,\n\t\t\tSystemQueryAdded\n\t\t>\n\t\tsystemMutation: EffectApiOptions<\n\t\t\tGenericMutationCtx<DataModel> & { include: Include },\n\t\t\tSystemMutationServices,\n\t\t\tSystemMutationAdded\n\t\t>\n\t\tsystemAction: EffectApiOptions<\n\t\t\tGenericActionCtx<DataModel>,\n\t\t\tSystemActionServices,\n\t\t\tSystemActionAdded\n\t\t>\n\t},\n): EffectAuthFunctions<\n\tDataModel,\n\tRole,\n\tQueryServices,\n\tQueryAdded,\n\tMutationServices,\n\tMutationAdded,\n\tActionServices,\n\tActionAdded,\n\tSystemQueryServices,\n\tSystemQueryAdded,\n\tSystemMutationServices,\n\tSystemMutationAdded,\n\tSystemActionServices,\n\tSystemActionAdded\n> {\n\tconst auth = createAuthFunctions(config)\n\treturn {\n\t\tinclude: auth.include,\n\t\tauthenticatedUser: auth.authenticatedUser,\n\t\tauthQuery: effectZodApiBuilder(auth.authQuery, options.query),\n\t\troleQuery: (...allowed) => effectZodApiBuilder(auth.roleQuery(...allowed), options.query),\n\t\tadminQuery: effectZodApiBuilder(auth.adminQuery, options.query),\n\t\tauthMutation: effectZodApiBuilder(auth.authMutation, options.mutation),\n\t\troleMutation: (...allowed) =>\n\t\t\teffectZodApiBuilder(auth.roleMutation(...allowed), options.mutation),\n\t\tadminMutation: effectZodApiBuilder(auth.adminMutation, options.mutation),\n\t\tauthAction: effectZodApiBuilder(auth.authAction, options.action),\n\t\troleAction: (...allowed) => effectZodApiBuilder(auth.roleAction(...allowed), options.action),\n\t\tadminAction: effectZodApiBuilder(auth.adminAction, options.action),\n\t\tserviceQuery: <Extra extends Record<string, unknown> = {}>(\n\t\t\tprincipal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>,\n\t\t) =>\n\t\t\tadaptService<ServiceQuery<DataModel, Role, Extra>, QueryServices, QueryAdded>(\n\t\t\t\tauth.serviceQuery(principal),\n\t\t\t\toptions.query,\n\t\t\t),\n\t\tserviceMutation: <Extra extends Record<string, unknown> = {}>(\n\t\t\tprincipal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>,\n\t\t) =>\n\t\t\tadaptService<ServiceMutation<DataModel, Role, Extra>, MutationServices, MutationAdded>(\n\t\t\t\tauth.serviceMutation(principal),\n\t\t\t\toptions.mutation,\n\t\t\t),\n\t\tsystemQuery: effectZodApiBuilder(auth.systemQuery, options.systemQuery),\n\t\tsystemMutation: effectZodApiBuilder(auth.systemMutation, options.systemMutation),\n\t\tsystemAction: effectZodApiBuilder(auth.systemAction, options.systemAction),\n\t}\n}\n\n/** Service builders reuse the query/mutation policy; the ctx adds only host extras. */\nfunction adaptService<Builder extends Function, Services extends EffectApiServices, Added>(\n\tbuilder: Builder,\n\toptions: Parameters<typeof wrapEffectBuilder>[1],\n): Adapted<Builder, Services, Added> {\n\t// SAFETY: the shared policy callbacks read only the standard auth bundle, which every\n\t// service ctx carries; wrapEffectBuilder swaps the handler and keeps the builder's\n\t// registration kind, validation and visibility, as effectZodApiBuilder does.\n\treturn wrapEffectBuilder(builder, options) as Adapted<Builder, Services, Added>\n}\n"],"mappings":"+JAwHA,SAAgBA,EAgBf,EACA,EA+CC,CACD,IAAMC,EAAOC,EAAoBC,CAAM,EACvC,MAAO,CACN,QAASF,EAAK,QACd,kBAAmBA,EAAK,kBACxB,UAAWG,EAAoBH,EAAK,UAAWI,EAAQ,KAAK,EAC5D,WAAY,GAAGC,IAAYF,EAAoBH,EAAK,UAAU,GAAGK,CAAO,EAAGD,EAAQ,KAAK,EACxF,WAAYD,EAAoBH,EAAK,WAAYI,EAAQ,KAAK,EAC9D,aAAcD,EAAoBH,EAAK,aAAcI,EAAQ,QAAQ,EACrE,cAAe,GAAGC,IACjBF,EAAoBH,EAAK,aAAa,GAAGK,CAAO,EAAGD,EAAQ,QAAQ,EACpE,cAAeD,EAAoBH,EAAK,cAAeI,EAAQ,QAAQ,EACvE,WAAYD,EAAoBH,EAAK,WAAYI,EAAQ,MAAM,EAC/D,YAAa,GAAGC,IAAYF,EAAoBH,EAAK,WAAW,GAAGK,CAAO,EAAGD,EAAQ,MAAM,EAC3F,YAAaD,EAAoBH,EAAK,YAAaI,EAAQ,MAAM,EACjE,aACC,GAEAE,EACCN,EAAK,aAAaO,CAAS,EAC3BH,EAAQ,KACT,EACD,gBACC,GAEAE,EACCN,EAAK,gBAAgBO,CAAS,EAC9BH,EAAQ,QACT,EACD,YAAaD,EAAoBH,EAAK,YAAaI,EAAQ,WAAW,EACtE,eAAgBD,EAAoBH,EAAK,eAAgBI,EAAQ,cAAc,EAC/E,aAAcD,EAAoBH,EAAK,aAAcI,EAAQ,YAAY,CAC1E,CACD,CAGA,SAASE,EACR,EACA,EACoC,CAIpC,OAAOE,EAAkBC,EAASL,CAAO,CAC1C"}
|
|
@@ -3,6 +3,8 @@ import { ResolverFactory } from "oxc-resolver";
|
|
|
3
3
|
export interface ArchitectureOptions {
|
|
4
4
|
cwd?: string;
|
|
5
5
|
convexDir?: string;
|
|
6
|
+
/** Additional component roots, relative to convexDir. */
|
|
7
|
+
componentDirs?: readonly string[];
|
|
6
8
|
/** Build these registries to surface deferred configuration errors in tests. */
|
|
7
9
|
registries?: readonly object[];
|
|
8
10
|
}
|
|
@@ -13,7 +15,7 @@ export interface ArchitectureDiagnostic {
|
|
|
13
15
|
}
|
|
14
16
|
/** Full-project checks, independent of the consumer's test runner. No persistent cache. */
|
|
15
17
|
export declare function inspectArchitecture(options?: ArchitectureOptions): ArchitectureDiagnostic[];
|
|
16
|
-
export declare function createResolver(): ResolverFactory;
|
|
18
|
+
export declare function createResolver(symlinks?: boolean): ResolverFactory;
|
|
17
19
|
export declare function resolveImport(resolver: ResolverFactory, filename: string, source: string): string | null;
|
|
18
20
|
/** The lint rule runs the project scan on one deterministic source file. */
|
|
19
21
|
export declare function architectureAnchor(root: string): string | null;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{dirname as e,relative as t,resolve as n,sep as r}from"node:path";import{existsSync as i,readFileSync as a,readdirSync as o,realpathSync as s}from"node:fs";import{Visitor as c,parseSync as l}from"oxc-parser";import{ResolverFactory as u}from"oxc-resolver";function d(o={}){let c=n(o.cwd??process.cwd(),o.convexDir??`convex`),u=i(c)?s(c):c,d=[];if(!i(u))return[{code:`missing-root`,file:`.`,message:`Convex directory does not exist: ${u}`}];let m=g(u,d),b=/* @__PURE__ */ new Set,T=/* @__PURE__ */ new Set,E=/* @__PURE__ */ new Map,D=/* @__PURE__ */ new Map,O=f();for(let i of m){let o=n(u,i),s=l(o,a(o,`utf8`));if(s.errors.length){d.push({code:`parse`,file:i,message:`Cannot validate ${i}: ${s.errors[0].message}`});continue}if(_(i)){i.includes(`__tests__/`)?e(i).endsWith(`__tests__`)&&y(s.program)&&T.add(e(e(i))):d.push({code:`test-location`,file:i,message:`Place tests in a sibling __tests__/ directory.`});continue}if(i.split(`/`).includes(`__tests__`))continue;/^domain\/[^/]+$/.test(i)&&i!==`domain/table.ts`&&d.push({code:`domain-entry`,file:i,message:`Domain source belongs in domain/<module>/ or domain/shared/. Only domain/table.ts assembles module tables.`}),v(s.program)&&i!==`domain/table.ts`&&!h(i,a(o,`utf8`))&&b.add(e(i));let c=S(i)??``,f=/* @__PURE__ */ new Set;D.set(i,f);for(let e of x(s.program)){let n=p(O,o,e);if(!n)continue;let i=t(u,n).split(r).join(`/`);f.add(i);let a=S(i);if(c&&a&&c!==a){let e=E.get(c)??/* @__PURE__ */ new Set;E.set(c,e),e.add(a)}}}for(let e of b)T.has(e)||d.push({code:`tests`,file:e,message:`${e}/__tests__/ must contain a .test or .spec file with a nonempty, non-skipped test. Parent or child suites do not count.`});d.push(...w(D));for(let e of C(E))d.push({code:`cycle`,file:e[0],message:`Module dependency cycle: ${e.join(` → `)}.`});return d.sort((e,t)=>e.file.localeCompare(t.file)||e.code.localeCompare(t.code))}function f(){return new u({tsconfig:`auto`,extensions:[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`],extensionAlias:{".js":[`.ts`,`.tsx`,`.js`],".mjs":[`.mts`,`.mjs`],".cjs":[`.cts`,`.cjs`]},conditionNames:[`types`,`import`,`node`,`default`],symlinks:!0})}function p(t,r,i){return t.resolveFileSync(r,i).path||(i.startsWith(`.`)?n(e(r),i):null)}function m(e){if(!i(e))return null;if(i(n(e,`convex.config.ts`)))return s(n(e,`convex.config.ts`));e=s(e);for(let t of g(e,[]))if(!t.includes(`__tests__/`)&&!_(t))return n(e,t);return null}function h(e,t){let n=e===`relations.ts`?`defineRelations`:e===`querying.ts`?`createQueryEngine`:null;if(!n)return!1;let r=l(e,t);if(r.errors.length)return!1;let i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=0,s=!1;function c(e,t=/* @__PURE__ */ new Set){if(e.type===`Identifier`){if(t.has(e.name))return null;let n=a.get(e.name);return n?c(n,new Set(t).add(e.name)):i.get(e.name)??null}return e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&c(e.object,t)===`*`?e.property.name:null}function u(e,t,n=!1){if(e.type===`Identifier`||e.type===`Literal`)return!0;if(e.type===`TSAsExpression`||e.type===`TSSatisfiesExpression`||e.type===`ParenthesizedExpression`)return u(e.expression,t,n);if(e.type===`MemberExpression`)return!e.computed&&u(e.object,t);if(e.type===`ArrayExpression`)return e.elements.every(e=>e!==null&&u(e,t));if(e.type===`ObjectExpression`)return e.properties.every(e=>e.type===`Property`&&!e.computed&&e.kind===`init`&&!e.method&&u(e.value,t));if(e.type===`ArrowFunctionExpression`&&n&&!t&&e.params.length===1&&e.params[0].type===`Identifier`&&!e.async){let t=e.body.type===`ParenthesizedExpression`?e.body.expression:e.body;return t.type===`ObjectExpression`&&u(t,e.params[0].name)}if(e.type===`CallExpression`&&t){let n=e.callee,r=[];for(;n.type===`MemberExpression`&&!n.computed&&n.property.type===`Identifier`;)r.unshift(n.property.name),n=n.object;return n.type===`Identifier`&&n.name===t&&(r.length===2&&[`one`,`many`].includes(r[0])||r.length===3&&r[2]===`through`)&&e.arguments.every(e=>u(e,t))}return!1}for(let t of r.program.body){if(t.type===`ImportDeclaration`){if(t.importKind===`type`)continue;for(let n of t.specifiers)(n.type!==`ImportSpecifier`||n.importKind!==`type`)&&[`cvx-kit`,`cvx-kit/${e.slice(0,-3)}`].includes(t.source.value)&&i.set(n.local.name,n.type===`ImportSpecifier`?n.imported.type===`Identifier`?n.imported.name:``:n.type===`ImportNamespaceSpecifier`?`*`:``);continue}if(t.type===`EmptyStatement`||t.type===`TSTypeAliasDeclaration`||t.type===`TSInterfaceDeclaration`)continue;let r=t.type===`ExportNamedDeclaration`?t.declaration:t;if(r?.type!==`VariableDeclaration`||r.kind!==`const`)return!1;for(let e of r.declarations){if(e.id.type!==`Identifier`||!e.init)return!1;if(e.init.type===`CallExpression`&&c(e.init.callee)===n){if(!e.init.arguments.every((e,t)=>u(e,void 0,n===`defineRelations`&&t===1)))return!1;o++,s||=t.type===`ExportNamedDeclaration`}else if(t.type===`ExportNamedDeclaration`||!u(e.init))return!1;a.set(e.id.name,e.init)}}return o===1&&s}function*g(e,i){let a=/* @__PURE__ */ new Set([`_generated`,`__tests__`,`api`,`domain`,`application`,`migrations`,`components`]);function*s(c){for(let l of o(c,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let o=n(c,l.name),u=t(e,o).split(r).join(`/`);if(l.isSymbolicLink()){i.push({code:`symlink`,file:u,message:`Keep application source inside its owning directory; symlinked files and folders are not allowed.`});continue}l.isDirectory()?(c===e&&!a.has(l.name)&&i.push({code:`root-directory`,file:u,message:`Root folder ${l.name}/ is not allowed. Use api/, domain/, application/, migrations/, components/, __tests__/, or _generated/.`}),l.name!==`_generated`&&l.name!==`node_modules`&&!l.name.startsWith(`.`)&&(yield*s(o))):/\.[cm]?[jt]sx?$/.test(l.name)&&!/\.d\.[cm]?ts$/.test(l.name)&&(yield u)}}yield*s(e)}function _(e){return/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(e)}function v(e){return e.body.some(e=>{let t=e.type===`ExportNamedDeclaration`?e.declaration:e;return t&&`declare`in t&&t.declare||e.type===`ImportDeclaration`||e.type===`EmptyStatement`?!1:e.type===`ExportNamedDeclaration`?e.exportKind===`type`||!e.declaration?!1:![`TSInterfaceDeclaration`,`TSTypeAliasDeclaration`,`TSDeclareFunction`].includes(e.declaration.type):![`TSInterfaceDeclaration`,`TSTypeAliasDeclaration`,`TSDeclareFunction`,`ExportAllDeclaration`].includes(e.type)})}function y(e){let t=/* @__PURE__ */ new Map([[`test`,`test`],[`it`,`it`],[`describe`,`describe`],[`suite`,`suite`]]);for(let n of e.body){let e=n.type===`ExportNamedDeclaration`?n.declaration:n;if(e?.type===`FunctionDeclaration`&&e.id&&t.delete(e.id.name),e?.type===`VariableDeclaration`)for(let n of e.declarations)n.id.type===`Identifier`&&t.delete(n.id.name);if(n.type===`ImportDeclaration`)for(let e of n.specifiers)t.delete(e.local.name),[`vitest`,`vite-plus/test`,`bun:test`,`node:test`,`@jest/globals`].includes(n.source.value)&&(e.type===`ImportNamespaceSpecifier`?t.set(e.local.name,`*`):e.type===`ImportDefaultSpecifier`?t.set(e.local.name,`test`):e.imported.type===`Identifier`&&t.set(e.local.name,e.imported.name))}let n=[];new c({CallExpression(e){n.push(e)}}).visit(e);let r=n.filter(e=>{let n=b(e.callee,t);return[`test`,`it`,`describe`,`suite`].includes(n[0])&&(n.some(e=>[`skip`,`todo`,`skipIf`,`runIf`].includes(e))||e.arguments.some(e=>e.type===`ObjectExpression`&&e.properties.some(e=>e.type===`Property`&&[`skip`,`todo`].includes(e.key.type===`Identifier`?e.key.name:e.key.type===`Literal`?String(e.key.value):``)&&(e.value.type!==`Literal`||e.value.value!==!1))))});return n.some(e=>{let n=b(e.callee,t);return![`test`,`it`].includes(n[0])||r.some(t=>e.start>=t.start&&e.end<=t.end)?!1:e.arguments.some(e=>(e.type===`ArrowFunctionExpression`||e.type===`FunctionExpression`)&&e.body&&(e.body.type!==`BlockStatement`||e.body.body.some(e=>e.type!==`EmptyStatement`)))})}function b(e,t){if(e.type===`Identifier`){let n=t.get(e.name);return n?[n]:[]}if(e.type===`CallExpression`)return b(e.callee,t);if(e.type===`MemberExpression`){let n=b(e.object,t),r=!e.computed&&e.property.type===`Identifier`?e.property.name:e.property.type===`Literal`?String(e.property.value):``;return!n.length||!r?[]:n[0]===`*`?[r]:[...n,r]}return[]}function x(e){let t=[];return new c({ImportDeclaration(e){e.importKind!==`type`&&(e.specifiers.length===0||e.specifiers.some(e=>e.type!==`ImportSpecifier`||e.importKind!==`type`))&&t.push(e.source.value)},ExportNamedDeclaration(e){e.source&&e.exportKind!==`type`&&e.specifiers.some(e=>e.exportKind!==`type`)&&t.push(e.source.value)},ExportAllDeclaration(e){e.exportKind!==`type`&&t.push(e.source.value)},ImportExpression(e){e.source.type===`Literal`&&String(e.source.value)===e.source.value&&t.push(String(e.source.value))}}).visit(e),t}function S(e){let t=e.split(`/`);return t[0]===`domain`&&t.length>=3&&t[1]!==`__tests__`?`domain/${t[1]}`:null}function C(e){let t=/* @__PURE__ */ new Set,n=[],r=[];function i(a){let o=n.indexOf(a);if(o>=0){r.push([...n.slice(o),a]);return}if(!t.has(a)){n.push(a);for(let t of e.get(a)??[])i(t);n.pop(),t.add(a)}}for(let t of e.keys())i(t);return r}function w(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of e){let i=S(n)??``;if(!i||i===`domain/shared`)continue;let a=/* @__PURE__ */ new Set;function o(n){if(!n.startsWith(`domain/shared/`)||a.has(n))return;a.add(n);let r=t.get(n)??/* @__PURE__ */ new Set;r.add(i),t.set(n,r);for(let t of e.get(n)??[])o(t)}for(let e of r)o(e)}let n=[];for(let[e,r]of t)r.size===1&&n.push({code:`shared-owner`,file:e,message:`This shared implementation is used only by ${[...r][0]}. Move it into that module until another module needs it.`});return n}export{m as architectureAnchor,f as createResolver,d as inspectArchitecture,h as narrowRootDeclaration,p as resolveImport};
|
|
1
|
+
import{conventionalComponentRoot as e,findComponentRoot as t}from"./components.mjs";import{dirname as n,relative as r,resolve as i,sep as a}from"node:path";import{existsSync as o,readFileSync as s,readdirSync as c,realpathSync as l}from"node:fs";import{Visitor as u,parseSync as d}from"oxc-parser";import{ResolverFactory as f}from"oxc-resolver";function p(c={}){let u=i(c.cwd??process.cwd(),c.convexDir??`convex`),f=o(u)?l(u):u,p=[];if(!o(f))return[{code:`missing-root`,file:`.`,message:`Convex directory does not exist: ${f}`}];let g=(c.componentDirs??[]).map(e=>i(f,e)),S=[...v(f,p)],D=/* @__PURE__ */ new Map;for(let n of S){let o=t(i(f,n),g)??e(i(f,n),f);o&&(o===f||o.startsWith(f+a))&&D.set(n,r(f,o).split(a).join(`/`))}let O=new Set(D.values());for(let e=p.length-1;e>=0;e--){let t=p[e];t.code===`root-directory`&&[...O].some(e=>!e||e===t.file||e.startsWith(t.file+`/`))&&!S.some(e=>e.startsWith(t.file+`/`)&&!D.has(e))&&p.splice(e,1)}let k=/* @__PURE__ */ new Set,A=/* @__PURE__ */ new Set,j=/* @__PURE__ */ new Map,M=/* @__PURE__ */ new Map,N=/* @__PURE__ */ new Map,P=m();for(let e of S){let t=i(f,e),o=d(t,s(t,`utf8`));if(o.errors.length){p.push({code:`parse`,file:e,message:`Cannot validate ${e}: ${o.errors[0].message}`});continue}if(y(e)){e.includes(`__tests__/`)?n(e).endsWith(`__tests__`)&&x(o.program)&&A.add(n(n(e))):p.push({code:`test-location`,file:e,message:`Place tests in a sibling __tests__/ directory.`});continue}if(e.split(`/`).includes(`__tests__`))continue;let c=D.get(e),l=c===void 0?e:r(i(f,c),t).split(a).join(`/`);c===void 0&&/^domain\/[^/]+$/.test(e)&&e!==`domain/table.ts`&&p.push({code:`domain-entry`,file:e,message:`Domain source belongs in domain/<module>/ or domain/shared/. Only domain/table.ts assembles module tables.`}),b(o.program)&&e!==`domain/table.ts`&&!_(l,s(t,`utf8`))&&k.add(n(e));let u=w(e)??``,m=/* @__PURE__ */ new Set;N.set(e,m);for(let n of C(o.program)){let i=h(P,t,n);if(!i)continue;let o=r(f,i).split(a).join(`/`);if(m.add(o),c!==void 0&&D.get(o)===c){let t=M.get(e)??/* @__PURE__ */ new Set;M.set(e,t),t.add(o)}let s=w(o);if(u&&s&&u!==s){let e=j.get(u)??/* @__PURE__ */ new Set;j.set(u,e),e.add(s)}}}for(let e of k)A.has(e)||p.push({code:`tests`,file:e,message:`${e}/__tests__/ must contain a .test or .spec file with a nonempty, non-skipped test. Parent or child suites do not count.`});p.push(...E(N));for(let e of[...T(j),...T(M)])p.push({code:`cycle`,file:e[0],message:`Module dependency cycle: ${e.join(` → `)}.`});return p.sort((e,t)=>e.file.localeCompare(t.file)||e.code.localeCompare(t.code))}function m(e=!0){return new f({tsconfig:`auto`,extensions:[`.ts`,`.tsx`,`.mts`,`.cts`,`.js`,`.jsx`,`.mjs`,`.cjs`,`.json`],extensionAlias:{".js":[`.ts`,`.tsx`,`.js`],".mjs":[`.mts`,`.mjs`],".cjs":[`.cts`,`.cjs`]},conditionNames:[`types`,`import`,`node`,`default`],symlinks:e})}function h(e,t,r){return e.resolveFileSync(t,r).path||(r.startsWith(`.`)?i(n(t),r):null)}function g(e){if(!o(e))return null;if(o(i(e,`convex.config.ts`)))return l(i(e,`convex.config.ts`));e=l(e);for(let t of v(e,[]))if(!t.includes(`__tests__/`)&&!y(t))return i(e,t);return null}function _(e,t){let n=e===`relations.ts`?`defineRelations`:e===`querying.ts`?`createQueryEngine`:null;if(!n)return!1;let r=d(e,t);if(r.errors.length)return!1;let i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=0,s=!1;function c(e,t=/* @__PURE__ */ new Set){if(e.type===`Identifier`){if(t.has(e.name))return null;let n=a.get(e.name);return n?c(n,new Set(t).add(e.name)):i.get(e.name)??null}return e.type===`MemberExpression`&&!e.computed&&e.property.type===`Identifier`&&c(e.object,t)===`*`?e.property.name:null}function l(e,t,n=!1){if(e.type===`Identifier`||e.type===`Literal`)return!0;if(e.type===`TSAsExpression`||e.type===`TSSatisfiesExpression`||e.type===`ParenthesizedExpression`)return l(e.expression,t,n);if(e.type===`MemberExpression`)return!e.computed&&l(e.object,t);if(e.type===`ArrayExpression`)return e.elements.every(e=>e!==null&&l(e,t));if(e.type===`ObjectExpression`)return e.properties.every(e=>e.type===`Property`&&!e.computed&&e.kind===`init`&&!e.method&&l(e.value,t));if(e.type===`ArrowFunctionExpression`&&n&&!t&&e.params.length===1&&e.params[0].type===`Identifier`&&!e.async){let t=e.body.type===`ParenthesizedExpression`?e.body.expression:e.body;return t.type===`ObjectExpression`&&l(t,e.params[0].name)}if(e.type===`CallExpression`&&t){let n=e.callee,r=[];for(;n.type===`MemberExpression`&&!n.computed&&n.property.type===`Identifier`;)r.unshift(n.property.name),n=n.object;return n.type===`Identifier`&&n.name===t&&(r.length===2&&[`one`,`many`].includes(r[0])||r.length===3&&r[2]===`through`)&&e.arguments.every(e=>l(e,t))}return!1}for(let t of r.program.body){if(t.type===`ImportDeclaration`){if(t.importKind===`type`)continue;for(let n of t.specifiers)(n.type!==`ImportSpecifier`||n.importKind!==`type`)&&[`cvx-kit`,`cvx-kit/${e.slice(0,-3)}`].includes(t.source.value)&&i.set(n.local.name,n.type===`ImportSpecifier`?n.imported.type===`Identifier`?n.imported.name:``:n.type===`ImportNamespaceSpecifier`?`*`:``);continue}if(t.type===`EmptyStatement`||t.type===`TSTypeAliasDeclaration`||t.type===`TSInterfaceDeclaration`)continue;let r=t.type===`ExportNamedDeclaration`?t.declaration:t;if(r?.type!==`VariableDeclaration`||r.kind!==`const`)return!1;for(let e of r.declarations){if(e.id.type!==`Identifier`||!e.init)return!1;if(e.init.type===`CallExpression`&&c(e.init.callee)===n){if(!e.init.arguments.every((e,t)=>l(e,void 0,n===`defineRelations`&&t===1)))return!1;o++,s||=t.type===`ExportNamedDeclaration`}else if(t.type===`ExportNamedDeclaration`||!l(e.init))return!1;a.set(e.id.name,e.init)}}return o===1&&s}function*v(e,t){let n=/* @__PURE__ */ new Set([`_generated`,`__tests__`,`api`,`domain`,`application`,`migrations`,`components`]);function*o(s){for(let l of c(s,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let c=i(s,l.name),u=r(e,c).split(a).join(`/`);if(l.isSymbolicLink()){t.push({code:`symlink`,file:u,message:`Keep application source inside its owning directory; symlinked files and folders are not allowed.`});continue}l.isDirectory()?(s===e&&!n.has(l.name)&&t.push({code:`root-directory`,file:u,message:`Root folder ${l.name}/ is not allowed. Use api/, domain/, application/, migrations/, components/, __tests__/, or _generated/.`}),l.name!==`_generated`&&l.name!==`node_modules`&&!l.name.startsWith(`.`)&&(yield*o(c))):/\.[cm]?[jt]sx?$/.test(l.name)&&!/\.d\.[cm]?ts$/.test(l.name)&&(yield u)}}yield*o(e)}function y(e){return/\.(?:test|spec)\.[cm]?[jt]sx?$/.test(e)}function b(e){return e.body.some(e=>{let t=e.type===`ExportNamedDeclaration`?e.declaration:e;return t&&`declare`in t&&t.declare||e.type===`ImportDeclaration`||e.type===`EmptyStatement`?!1:e.type===`ExportNamedDeclaration`?e.exportKind===`type`||!e.declaration?!1:![`TSInterfaceDeclaration`,`TSTypeAliasDeclaration`,`TSDeclareFunction`].includes(e.declaration.type):![`TSInterfaceDeclaration`,`TSTypeAliasDeclaration`,`TSDeclareFunction`,`ExportAllDeclaration`].includes(e.type)})}function x(e){let t=/* @__PURE__ */ new Map([[`test`,`test`],[`it`,`it`],[`describe`,`describe`],[`suite`,`suite`]]);for(let n of e.body){let e=n.type===`ExportNamedDeclaration`?n.declaration:n;if(e?.type===`FunctionDeclaration`&&e.id&&t.delete(e.id.name),e?.type===`VariableDeclaration`)for(let n of e.declarations)n.id.type===`Identifier`&&t.delete(n.id.name);if(n.type===`ImportDeclaration`)for(let e of n.specifiers)t.delete(e.local.name),[`vitest`,`vite-plus/test`,`bun:test`,`node:test`,`@jest/globals`].includes(n.source.value)&&(e.type===`ImportNamespaceSpecifier`?t.set(e.local.name,`*`):e.type===`ImportDefaultSpecifier`?t.set(e.local.name,`test`):e.imported.type===`Identifier`&&t.set(e.local.name,e.imported.name))}let n=[];new u({CallExpression(e){n.push(e)}}).visit(e);let r=n.filter(e=>{let n=S(e.callee,t);return[`test`,`it`,`describe`,`suite`].includes(n[0])&&(n.some(e=>[`skip`,`todo`,`skipIf`,`runIf`].includes(e))||e.arguments.some(e=>e.type===`ObjectExpression`&&e.properties.some(e=>e.type===`Property`&&[`skip`,`todo`].includes(e.key.type===`Identifier`?e.key.name:e.key.type===`Literal`?String(e.key.value):``)&&(e.value.type!==`Literal`||e.value.value!==!1))))});return n.some(e=>{let n=S(e.callee,t);return![`test`,`it`].includes(n[0])||r.some(t=>e.start>=t.start&&e.end<=t.end)?!1:e.arguments.some(e=>(e.type===`ArrowFunctionExpression`||e.type===`FunctionExpression`)&&e.body&&(e.body.type!==`BlockStatement`||e.body.body.some(e=>e.type!==`EmptyStatement`)))})}function S(e,t){if(e.type===`Identifier`){let n=t.get(e.name);return n?[n]:[]}if(e.type===`CallExpression`)return S(e.callee,t);if(e.type===`MemberExpression`){let n=S(e.object,t),r=!e.computed&&e.property.type===`Identifier`?e.property.name:e.property.type===`Literal`?String(e.property.value):``;return!n.length||!r?[]:n[0]===`*`?[r]:[...n,r]}return[]}function C(e){let t=[];return new u({ImportDeclaration(e){e.importKind!==`type`&&(e.specifiers.length===0||e.specifiers.some(e=>e.type!==`ImportSpecifier`||e.importKind!==`type`))&&t.push(e.source.value)},ExportNamedDeclaration(e){e.source&&e.exportKind!==`type`&&e.specifiers.some(e=>e.exportKind!==`type`)&&t.push(e.source.value)},ExportAllDeclaration(e){e.exportKind!==`type`&&t.push(e.source.value)},ImportExpression(e){e.source.type===`Literal`&&String(e.source.value)===e.source.value&&t.push(String(e.source.value))}}).visit(e),t}function w(e){let t=e.split(`/`);return t[0]===`domain`&&t.length>=3&&t[1]!==`__tests__`?`domain/${t[1]}`:null}function T(e){let t=/* @__PURE__ */ new Set,n=[],r=[];function i(a){let o=n.indexOf(a);if(o>=0){r.push([...n.slice(o),a]);return}if(!t.has(a)){n.push(a);for(let t of e.get(a)??[])i(t);n.pop(),t.add(a)}}for(let t of e.keys())i(t);return r}function E(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of e){let i=w(n)??``;if(!i||i===`domain/shared`)continue;let a=/* @__PURE__ */ new Set;function o(n){if(!n.startsWith(`domain/shared/`)||a.has(n))return;a.add(n);let r=t.get(n)??/* @__PURE__ */ new Set;r.add(i),t.set(n,r);for(let t of e.get(n)??[])o(t)}for(let e of r)o(e)}let n=[];for(let[e,r]of t)r.size===1&&n.push({code:`shared-owner`,file:e,message:`This shared implementation is used only by ${[...r][0]}. Move it into that module until another module needs it.`});return n}export{g as architectureAnchor,m as createResolver,p as inspectArchitecture,_ as narrowRootDeclaration,h as resolveImport};
|
|
2
2
|
//# sourceMappingURL=architecture.mjs.map
|