@happyvertical/smrt-tenancy 0.68.0 → 0.70.0

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/AGENTS.md CHANGED
@@ -72,9 +72,9 @@ It requires `enableTenancy()` and refuses nesting. See README "Authorized hierar
72
72
  read scopes" for bootstrap, RLS composition and the direct-database boundary.
73
73
 
74
74
 
75
- **Optional-mode reads with no context pass through UNFILTERED at the interceptor.** That is intentional for trusted/admin call paths, but it means the interceptor alone does not protect a tenant-scoped model exposed as `@smrt({ api: { public } })`: an anonymous HTTP read has no context, so the interceptor would return every tenant's rows. The generated REST + SvelteKit read routes close this by forcing a `{ <ownership field>: null }` filter on list, count and point reads (runtime REST refuses such a caller every custom collection action), and emitted custom GET actions get the same keys in their options with every caller-sent ownership key (`tenantId` included) removed — the configured `field` (`@TenantScoped({ field: 'organizationId' })`), never a literal `tenantId` that may be an ordinary column, resolved at request time from the live registry so `registerTenantScopedClass()` at runtime is honoured (core's `applyWhereScope()`, which first drops every client filter on the ownership column under any spelling) when tenancy is enabled but no context is active, so public/anonymous reads fail closed to **global (NULL-tenant) rows only** — mirroring the dispatch resolver's *enforced, no active tenant → global rows only* rule (#1782). Authenticated reads still scope to the caller's tenant via the interceptor. `enableTenancy()` also installs core's request tenant context hooks (`setRequestTenantContextHooks`), through which emitted routes of a runtime-registered model enter the caller's tenant (`enterRequestTenantContext` refuses a context without a tenant) and read the super-admin bypass per class (`allowSuperAdminBypass`, outside hierarchy read scopes, as the interceptor decides).
75
+ **Optional-mode reads with no context pass through UNFILTERED at the interceptor**, outside a request. That is intentional for trusted/admin call paths. Request paths (runtime REST, emitted routes, both sync apply paths, both MCP surfaces) resolve the request's tenancy in core (`src/request-tenancy.ts`, #5375) and bind it (runtime REST also refuses a caller with no tenant every custom collection action of a tenant-scoped model): core's `smrt-request-tenancy` interceptor (priority 110, before this one) holds every collection call of the request to rows without an owner (`{ <ownership field>: null }`, the configured `field`, never a literal `tenantId`) for a caller with no tenant, refuses a write by a caller with no tenant (rows without an owner included) or under a cross-tenant read grant, restricts the STI family table to the admitted types, decides every save and delete under the policy of the row's stored type and instance `_meta_type` (another policy than the class written through is refused, since this interceptor stamps and checks the owner under that class's policy) and, in an STI family with members, against the stored owner as well as the one the instance carries, and refuses a member whose policy changed after admission. A model the request did not resolve is held to the same rules under its live policy. Code that enters `withSystemContext()` inside a request acts as the system (and code that enters `withTenant()` in a request with no tenant acts in that tenant), except in a request admitted under a cross-tenant read grant, which writes no tenant-scoped row whatever context its code enters. This interceptor reads the bound policy for every member (`boundMemberTenancy`) instead of a fresh lookup, the member's `autoPopulate` included, and treats a bound member that is not `scoped` with a mode and field (a failed lookup) as an isolation error, never as unscoped.
76
76
 
77
- **Optional-mode writes with no context pass through too, so generated routes refuse them.** The runtime REST server runs every operation on a tenant-scoped model through `runTenantScopedEntryPoint()` with the tenant its host supplies per request (`APIConfig.resolveTenant`); the generated SvelteKit CRUD, action and sync routes call `requireTenantWriteContext()` after reading the tenant from `locals`. A caller with no tenant gets 403 (401 if anonymous) for create, update, delete, a mutating action or a sync item, global rows included, unless the principal is explicitly cross-tenant (a system context, `allowCrossTenant`, or a verified super-admin bypass). Inside an active tenant context, `runTenantScopedEntryPoint()` refuses a caller that names a different tenant with `TenantIsolationError` (403, sync `forbidden`) and keeps the context for a caller that names none. Tests: `src/__tests__/rest-write-tenant-gate.test.ts`, `src/__tests__/rest-request-tenant.test.ts`.
77
+ **`enableTenancy()` installs the policy source core decides with** (`setTenantPolicySource`): `policyOf(key)` is `getTenantScopedConfig()` by qualified key, reported as absent, resolved, or failed (an ambiguous or stale selector is `failed`, never "not scoped"; a failure always carries a reason), plus the system, bypass and hierarchy probes (`hierarchyReadScopeKey` keys read validators on the active hierarchy scope) and the context runners (a refreshed context keeps its other fields). For a principal the REST host resolves (#5195) it also lends `runForPrincipal(context | null, fn)` (`runInPrincipalContext`, internal: a frozen projection of the principal on this package's storage, its read-only permissions, never the bypass flag; `null` runs with no tenant and no system context) and `generation()`, a process-wide counter (`Symbol.for('smrt:tenant-policy-generation')`) bumped by every registration, removal, `clearTenantScopedRegistry()`, enable and disable. The request tenant context hooks (`setRequestTenantContextHooks`: enter, current, run, and the super-admin bypass, which answers only while tenancy is enabled) are installed when this package is loaded, enabled or not, so a route carrying a complete principal (`api.principalContext`) enters it for a model with no tenancy and an active context of another tenant refuses the request. `disableTenancy()` removes the policy source and keeps the context hooks. Enabled tenancy without a policy source refuses every scoped request. `runTenantScopedEntryPoint()` remains for direct callers; no generated surface uses it. Tests: `src/__tests__/effective-tenancy-*.test.ts`, `src/__tests__/rest-write-tenant-gate.test.ts`, `src/__tests__/rest-request-tenant.test.ts`.
78
78
 
79
79
  ## Read-Path Coverage (#2365)
80
80
 
@@ -1,2 +1,2 @@
1
- import { n as createExpressMiddleware, r as createCliContext, t as createSvelteKitHandle } from "../chunks/adapters-B4hMNcuw.js";
1
+ import { n as createExpressMiddleware, r as createCliContext, t as createSvelteKitHandle } from "../chunks/adapters-D3XAWSIV.js";
2
2
  export { createCliContext, createExpressMiddleware, createSvelteKitHandle };
@@ -1,4 +1,4 @@
1
- import { i as enterTenantContext, m as withTenant, p as withSystemContext } from "./context-CwbLwyIV.js";
1
+ import { h as withTenant, i as enterTenantContext, m as withSystemContext } from "./context-BNwgjIhk.js";
2
2
  //#region src/adapters/cli.ts
3
3
  function createCliContext(options = {}) {
4
4
  const { resolveTenantId, resolveUserId, defaultPermissions = /* @__PURE__ */ new Set(), superAdminByDefault = false } = options;
@@ -118,4 +118,4 @@ function matchPath(path, pattern) {
118
118
  //#endregion
119
119
  export { createExpressMiddleware as n, createCliContext as r, createSvelteKitHandle as t };
120
120
 
121
- //# sourceMappingURL=adapters-B4hMNcuw.js.map
121
+ //# sourceMappingURL=adapters-D3XAWSIV.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"adapters-B4hMNcuw.js","names":[],"sources":["../../src/adapters/cli.ts","../../src/adapters/express.ts","../../src/adapters/sveltekit.ts"],"sourcesContent":["/**\n * CLI Adapter for smrt-tenancy\n *\n * Provides utilities for setting up tenant context in CLI tools.\n *\n * @example\n * ```typescript\n * import { createCliContext } from '@happyvertical/smrt-tenancy/adapters';\n *\n * // Create context helper for CLI\n * const cliContext = createCliContext({\n * resolveTenantId: () => process.env.TENANT_ID,\n * });\n *\n * // Run command in tenant context\n * await cliContext.run(async () => {\n * await documentCollection.list({});\n * });\n * ```\n */\n\nimport {\n type TenantContextData,\n withSystemContext,\n withTenant,\n} from '../context.js';\n\n/**\n * Configuration for the CLI context runner created by `createCliContext()`.\n *\n * `resolveTenantId` is optional — when omitted (or when it returns\n * `null`/`undefined`) the `run()` method falls back to `withSystemContext()`.\n *\n * @see createCliContext\n * @see CliContextRunner\n */\nexport interface CliContextOptions {\n /**\n * Resolve tenant ID\n *\n * Common sources:\n * - Environment variable: () => process.env.TENANT_ID\n * - Command line argument: () => argv.tenant\n * - Config file: () => config.tenantId\n */\n resolveTenantId?: () =>\n | Promise<string | null | undefined>\n | string\n | null\n | undefined;\n\n /**\n * Resolve user ID (optional)\n */\n resolveUserId?: () =>\n | Promise<string | null | undefined>\n | string\n | null\n | undefined;\n\n /**\n * Default permissions for CLI operations\n */\n defaultPermissions?: Set<string>;\n\n /**\n * Run CLI as super admin by default\n * @default false\n */\n superAdminByDefault?: boolean;\n}\n\n/**\n * Context runner returned by `createCliContext()`.\n *\n * Provides four execution modes suitable for different CLI scenarios:\n * - `run()` — resolves the tenant from the configured options and runs code in\n * that context; falls back to system context if no tenant is available.\n * - `runWithTenant()` — explicitly specify a tenant ID for this invocation.\n * - `runAsSystem()` — bypass all tenant checks (migration scripts, admin tools).\n * - `runAsSuperAdmin()` — tenant context with bypass flag enabled.\n *\n * @see createCliContext\n */\nexport interface CliContextRunner {\n /**\n * Run `fn` inside the tenant context resolved from the `CliContextOptions`.\n *\n * Falls back to `withSystemContext()` when no tenant ID is available.\n *\n * @param fn - Async function to execute.\n * @returns Promise resolving to the return value of `fn`.\n */\n run<T>(fn: () => Promise<T>): Promise<T>;\n\n /**\n * Run `fn` inside the context of the specified tenant.\n *\n * @param tenantId - Tenant ID to set as context.\n * @param fn - Async function to execute.\n * @returns Promise resolving to the return value of `fn`.\n */\n runWithTenant<T>(tenantId: string, fn: () => Promise<T>): Promise<T>;\n\n /**\n * Run `fn` in system context, bypassing all tenant checks.\n *\n * @param fn - Async function to execute.\n * @returns Promise resolving to the return value of `fn`.\n */\n runAsSystem<T>(fn: () => Promise<T>): Promise<T>;\n\n /**\n * Run `fn` with a tenant context and super admin bypass enabled.\n *\n * @param tenantId - Tenant ID to set as context.\n * @param fn - Async function to execute.\n * @returns Promise resolving to the return value of `fn`.\n */\n runAsSuperAdmin<T>(tenantId: string, fn: () => Promise<T>): Promise<T>;\n}\n\n/**\n * Create a CLI context runner\n *\n * @param options - Configuration options\n * @returns CLI context runner with various execution modes\n *\n * @example\n * ```typescript\n * const cli = createCliContext({\n * resolveTenantId: () => process.env.TENANT_ID,\n * superAdminByDefault: true,\n * });\n *\n * // Use resolved tenant\n * await cli.run(async () => {\n * const docs = await collection.list({});\n * console.log(`Found ${docs.length} documents`);\n * });\n *\n * // Override tenant\n * await cli.runWithTenant('other-tenant', async () => {\n * // Operations in other-tenant context\n * });\n *\n * // System operations (no tenant)\n * await cli.runAsSystem(async () => {\n * // Can access all data\n * const allDocs = await collection.list({});\n * });\n * ```\n */\nexport function createCliContext(\n options: CliContextOptions = {},\n): CliContextRunner {\n const {\n resolveTenantId,\n resolveUserId,\n defaultPermissions = new Set<string>(),\n superAdminByDefault = false,\n } = options;\n\n return {\n async run<T>(fn: () => Promise<T>): Promise<T> {\n const tenantId = resolveTenantId ? await resolveTenantId() : null;\n\n if (!tenantId) {\n // No tenant configured - run in system context\n return withSystemContext(fn);\n }\n\n const userId = resolveUserId ? await resolveUserId() : undefined;\n\n const context: TenantContextData = {\n tenantId,\n userId: userId ?? undefined,\n permissions: defaultPermissions,\n superAdminBypass: superAdminByDefault,\n };\n\n return withTenant(context, fn);\n },\n\n async runWithTenant<T>(tenantId: string, fn: () => Promise<T>): Promise<T> {\n const userId = resolveUserId ? await resolveUserId() : undefined;\n\n const context: TenantContextData = {\n tenantId,\n userId: userId ?? undefined,\n permissions: defaultPermissions,\n superAdminBypass: superAdminByDefault,\n };\n\n return withTenant(context, fn);\n },\n\n async runAsSystem<T>(fn: () => Promise<T>): Promise<T> {\n return withSystemContext(fn);\n },\n\n async runAsSuperAdmin<T>(\n tenantId: string,\n fn: () => Promise<T>,\n ): Promise<T> {\n const userId = resolveUserId ? await resolveUserId() : undefined;\n\n const context: TenantContextData = {\n tenantId,\n userId: userId ?? undefined,\n permissions: defaultPermissions,\n superAdminBypass: true,\n };\n\n return withTenant(context, fn);\n },\n };\n}\n\n/**\n * Run an async function with a specific tenant ID set as context.\n *\n * Convenience wrapper around `withTenant()` for one-off CLI operations where\n * a full `CliContextRunner` is not needed.\n *\n * @param tenantId - Tenant ID to set as the active context.\n * @param fn - Async function to execute in the tenant context.\n * @returns Promise resolving to the return value of `fn`.\n *\n * @example\n * ```typescript\n * import { runWithTenant } from '@happyvertical/smrt-tenancy/adapters';\n *\n * await runWithTenant('tenant-123', async () => {\n * await collection.list({});\n * });\n * ```\n *\n * @see createCliContext\n * @see runAsSystem\n */\nexport async function runWithTenant<T>(\n tenantId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n return withTenant({ tenantId }, fn);\n}\n\n/**\n * Run an async function in system context, bypassing all tenant checks.\n *\n * Convenience wrapper around `withSystemContext()` for one-off CLI operations\n * such as migration scripts or admin tooling that needs cross-tenant access.\n *\n * @param fn - Async function to execute in system context.\n * @returns Promise resolving to the return value of `fn`.\n *\n * @example\n * ```typescript\n * import { runAsSystem } from '@happyvertical/smrt-tenancy/adapters';\n *\n * await runAsSystem(async () => {\n * const all = await collection.list({});\n * console.log(`Total records: ${all.length}`);\n * });\n * ```\n *\n * @see runWithTenant\n * @see createCliContext\n */\nexport async function runAsSystem<T>(fn: () => Promise<T>): Promise<T> {\n return withSystemContext(fn);\n}\n","/**\n * Express Adapter for smrt-tenancy\n *\n * Provides Express middleware that sets up tenant context for each request.\n *\n * @example\n * ```typescript\n * import express from 'express';\n * import { createExpressMiddleware } from '@happyvertical/smrt-tenancy/adapters';\n *\n * const app = express();\n *\n * app.use(createExpressMiddleware({\n * resolveTenantId: (req) => req.headers['x-tenant-id'] as string,\n * }));\n * ```\n */\n\nimport { enterTenantContext, type TenantContextData } from '../context.js';\n\n/**\n * Express Request interface (minimal to avoid direct dependency)\n */\ninterface ExpressRequest {\n headers: Record<string, string | string[] | undefined>;\n url: string;\n path: string;\n query: Record<string, unknown>;\n cookies?: Record<string, string>;\n}\n\n/**\n * Request object after the tenancy middleware has attached the resolved tenant\n * context. The middleware sets these properties so downstream route handlers can\n * read the tenant directly off the request.\n */\ninterface TenantAwareExpressRequest extends ExpressRequest {\n tenantContext?: TenantContextData;\n tenantId?: string;\n}\n\n/**\n * Express Response interface\n */\ninterface ExpressResponse {\n status(code: number): ExpressResponse;\n json(data: unknown): ExpressResponse;\n send(data: unknown): ExpressResponse;\n}\n\n/**\n * Express NextFunction\n */\ntype ExpressNext = (error?: unknown) => void;\n\n/**\n * Configuration options for the Express tenancy middleware created by\n * `createExpressMiddleware()`.\n *\n * Only `resolveTenantId` is required. All callback options receive the raw\n * Express `Request` object so you can extract tenant information from headers,\n * subdomains, cookies, or any other request property.\n *\n * @see createExpressMiddleware\n */\nexport interface ExpressMiddlewareOptions {\n /**\n * Resolve tenant ID from the request\n */\n resolveTenantId: (\n req: ExpressRequest,\n ) => Promise<string | null | undefined> | string | null | undefined;\n\n /**\n * Resolve user ID from the request (optional)\n */\n resolveUserId?: (\n req: ExpressRequest,\n ) => Promise<string | null | undefined> | string | null | undefined;\n\n /**\n * Resolve permissions (optional)\n */\n resolvePermissions?: (\n req: ExpressRequest,\n tenantId: string,\n userId?: string,\n ) => Promise<Set<string>> | Set<string>;\n\n /**\n * Check if user is super admin (optional)\n */\n isSuperAdmin?: (\n req: ExpressRequest,\n tenantId: string,\n userId?: string,\n ) => Promise<boolean> | boolean;\n\n /**\n * Called when no tenant ID could be resolved\n * Return true to continue, false to stop with 400 error.\n */\n onNoTenant?: (\n req: ExpressRequest,\n res: ExpressResponse,\n ) => Promise<boolean> | boolean;\n\n /**\n * Paths to exclude from tenant context\n */\n excludePaths?: string[];\n}\n\n/**\n * Create an Express middleware function that establishes tenant context for\n * every incoming request.\n *\n * Uses `enterTenantContext()` (rather than `withTenant()`) because Express\n * middleware returns before route handlers execute. `enterWith()` sets the\n * context on the current async resource so it propagates to handlers that run\n * after `next()` is called.\n *\n * The resolved context is also attached directly to the request object for\n * convenience:\n * - `req.tenantContext` — full `TenantContextData`\n * - `req.tenantId` — string tenant ID shortcut\n *\n * When no tenant ID can be resolved, the default behaviour returns a `400`\n * JSON response. Customise this with the `onNoTenant` option.\n *\n * @param options - Middleware configuration including the required\n * `resolveTenantId` callback.\n * @returns An Express-compatible middleware function `(req, res, next) => void`.\n *\n * @example\n * ```typescript\n * import express from 'express';\n * import { createExpressMiddleware } from '@happyvertical/smrt-tenancy/adapters';\n *\n * const app = express();\n * app.use(createExpressMiddleware({\n * resolveTenantId: (req) => req.headers['x-tenant-id'] as string,\n * excludePaths: ['/health', '/public/*'],\n * }));\n * ```\n *\n * @see ExpressMiddlewareOptions\n * @see createSvelteKitHandle\n */\nexport function createExpressMiddleware(options: ExpressMiddlewareOptions) {\n const {\n resolveTenantId,\n resolveUserId,\n resolvePermissions,\n isSuperAdmin,\n onNoTenant,\n excludePaths = [],\n } = options;\n\n return async function tenancyMiddleware(\n req: ExpressRequest,\n res: ExpressResponse,\n next: ExpressNext,\n ): Promise<void> {\n try {\n // Check excluded paths\n if (excludePaths.some((pattern) => matchPath(req.path, pattern))) {\n next();\n return;\n }\n\n // Resolve tenant ID\n const tenantId = await resolveTenantId(req);\n\n if (!tenantId) {\n if (onNoTenant) {\n const shouldContinue = await onNoTenant(req, res);\n if (shouldContinue) {\n next();\n return;\n }\n } else {\n res.status(400).json({\n error: 'Tenant ID required',\n message:\n 'Please provide a tenant ID via header, subdomain, or query parameter.',\n });\n return;\n }\n return;\n }\n\n // Resolve optional context\n const userId = resolveUserId ? await resolveUserId(req) : undefined;\n const permissions = resolvePermissions\n ? await resolvePermissions(req, tenantId, userId ?? undefined)\n : new Set<string>();\n const superAdminBypass = isSuperAdmin\n ? await isSuperAdmin(req, tenantId, userId ?? undefined)\n : false;\n\n // Build context\n const context: TenantContextData = {\n tenantId,\n userId: userId ?? undefined,\n permissions,\n superAdminBypass,\n };\n\n // Attach to request for access in route handlers\n (req as TenantAwareExpressRequest).tenantContext = context;\n (req as TenantAwareExpressRequest).tenantId = tenantId;\n\n // Use enterWith() to establish context that persists for the entire\n // request lifecycle. This ensures route handlers have access to\n // tenant context via AsyncLocalStorage.\n enterTenantContext(context);\n next();\n } catch (error) {\n next(error);\n }\n };\n}\n\n/**\n * Simple glob pattern matching for paths\n */\nfunction matchPath(path: string, pattern: string): boolean {\n const regexPattern = pattern\n .replace(/\\*/g, '.*')\n .replace(/\\//g, '\\\\/')\n .replace(/\\?/g, '.');\n\n return new RegExp(`^${regexPattern}$`).test(path);\n}\n","/**\n * SvelteKit Adapter for smrt-tenancy\n *\n * Provides a SvelteKit Handle that sets up tenant context for each request.\n *\n * @example\n * ```typescript\n * // hooks.server.ts\n * import { createSvelteKitHandle } from '@happyvertical/smrt-tenancy/adapters';\n *\n * export const handle = createSvelteKitHandle({\n * resolveTenantId: async (event) => {\n * // From subdomain\n * const host = event.request.headers.get('host');\n * const subdomain = host?.split('.')[0];\n * return subdomain;\n *\n * // Or from header\n * // return event.request.headers.get('x-tenant-id');\n *\n * // Or from cookie\n * // return event.cookies.get('tenant_id');\n * }\n * });\n * ```\n */\n\nimport { type TenantContextData, withTenant } from '../context.js';\n\n/**\n * SvelteKit RequestEvent (minimal interface to avoid direct dependency)\n */\ninterface SvelteKitEvent {\n request: Request;\n url: URL;\n cookies: {\n get(name: string): string | undefined;\n set(name: string, value: string, opts?: unknown): void;\n };\n locals: Record<string, unknown>;\n}\n\n/**\n * SvelteKit resolve function\n */\ntype SvelteKitResolve = (event: SvelteKitEvent) => Promise<Response>;\n\n/**\n * Configuration options for the SvelteKit tenancy handle created by\n * `createSvelteKitHandle()`.\n *\n * Only `resolveTenantId` is required; all other fields are optional callbacks\n * used to enrich the context or customise missing-tenant behaviour.\n *\n * @see createSvelteKitHandle\n */\nexport interface SvelteKitHandleOptions {\n /**\n * Resolve tenant ID from the request\n *\n * Return the tenant ID string, or null/undefined if no tenant context should be set.\n */\n resolveTenantId: (\n event: SvelteKitEvent,\n ) => Promise<string | null | undefined> | string | null | undefined;\n\n /**\n * Resolve user ID from the request (optional)\n */\n resolveUserId?: (\n event: SvelteKitEvent,\n ) => Promise<string | null | undefined> | string | null | undefined;\n\n /**\n * Resolve permissions for the user in this tenant (optional)\n */\n resolvePermissions?: (\n event: SvelteKitEvent,\n tenantId: string,\n userId?: string,\n ) => Promise<Set<string>> | Set<string>;\n\n /**\n * Check if user is a super admin (optional)\n * If true and super admin bypass is enabled on the class, tenant filtering is skipped.\n */\n isSuperAdmin?: (\n event: SvelteKitEvent,\n tenantId: string,\n userId?: string,\n ) => Promise<boolean> | boolean;\n\n /**\n * Called when no tenant ID could be resolved\n * Return a Response to short-circuit, or undefined to continue without tenant context.\n */\n onNoTenant?: (\n event: SvelteKitEvent,\n ) => Promise<Response | undefined> | Response | undefined;\n\n /**\n * Paths to exclude from tenant context (e.g., public APIs, health checks)\n * Supports glob patterns.\n */\n excludePaths?: string[];\n}\n\n/**\n * Create a SvelteKit `Handle` function that establishes tenant context for\n * every server-side request.\n *\n * The returned handle wraps the `resolve` call in `withTenant()` so that all\n * server-side load functions, API routes, and `+server.ts` handlers within the\n * request share the same tenant context via `AsyncLocalStorage`.\n *\n * The resolved context is also stored in `event.locals` under two keys:\n * - `event.locals.tenantContext` — full `TenantContextData`\n * - `event.locals.tenantId` — string tenant ID shortcut\n *\n * When no tenant ID can be resolved (and no custom `onNoTenant` handler\n * returns a `Response`), the request continues without any tenant context.\n *\n * @param options - Configuration options including the required\n * `resolveTenantId` callback.\n * @returns A SvelteKit `Handle` function suitable for use in `hooks.server.ts`.\n *\n * @example\n * ```typescript\n * // src/hooks.server.ts\n * import { createSvelteKitHandle } from '@happyvertical/smrt-tenancy/adapters';\n *\n * export const handle = createSvelteKitHandle({\n * resolveTenantId: (event) =>\n * event.request.headers.get('x-tenant-id'),\n * onNoTenant: () =>\n * new Response('Tenant required', { status: 400 }),\n * });\n * ```\n *\n * @see SvelteKitHandleOptions\n * @see createExpressMiddleware\n */\nexport function createSvelteKitHandle(options: SvelteKitHandleOptions) {\n const {\n resolveTenantId,\n resolveUserId,\n resolvePermissions,\n isSuperAdmin,\n onNoTenant,\n excludePaths = [],\n } = options;\n\n return async function handle({\n event,\n resolve,\n }: {\n event: SvelteKitEvent;\n resolve: SvelteKitResolve;\n }): Promise<Response> {\n // Check excluded paths\n const path = event.url.pathname;\n if (excludePaths.some((pattern) => matchPath(path, pattern))) {\n return resolve(event);\n }\n\n // Resolve tenant ID\n const tenantId = await resolveTenantId(event);\n\n if (!tenantId) {\n // No tenant ID - call handler or continue without context\n if (onNoTenant) {\n const response = await onNoTenant(event);\n if (response) {\n return response;\n }\n }\n return resolve(event);\n }\n\n // Resolve optional context data\n const userId = resolveUserId ? await resolveUserId(event) : undefined;\n const permissions = resolvePermissions\n ? await resolvePermissions(event, tenantId, userId ?? undefined)\n : new Set<string>();\n const superAdminBypass = isSuperAdmin\n ? await isSuperAdmin(event, tenantId, userId ?? undefined)\n : false;\n\n // Build context\n const context: TenantContextData = {\n tenantId,\n userId: userId ?? undefined,\n permissions,\n superAdminBypass,\n };\n\n // Store in locals for access in load functions\n event.locals.tenantContext = context;\n event.locals.tenantId = tenantId;\n\n // Run request in tenant context\n return withTenant(context, () => resolve(event));\n };\n}\n\n/**\n * Simple glob pattern matching for paths\n */\nfunction matchPath(path: string, pattern: string): boolean {\n // Convert glob to regex\n const regexPattern = pattern\n .replace(/\\*/g, '.*')\n .replace(/\\//g, '\\\\/')\n .replace(/\\?/g, '.');\n\n return new RegExp(`^${regexPattern}$`).test(path);\n}\n"],"mappings":";;AAyJO,SAAS,iBACd,UAA6B,CAAC,GACZ;CAClB,MAAM,EACJ,iBACA,eACA,qCAAqB,IAAI,IAAY,GACrC,sBAAsB,UACpB;CAEJ,OAAO;EACL,MAAM,IAAO,IAAkC;GAC7C,MAAM,WAAW,kBAAkB,MAAM,gBAAgB,IAAI;GAE7D,IAAI,CAAC,UAEH,OAAO,kBAAkB,EAAE;GAY7B,OAAO,WAAW;IANhB;IACA,SAJa,gBAAgB,MAAM,cAAc,IAAI,KAAA,MAInC,KAAA;IAClB,aAAa;IACb,kBAAkB;GAGF,GAAS,EAAE;EAC/B;EAEA,MAAM,cAAiB,UAAkB,IAAkC;GAUzE,OAAO,WAAW;IANhB;IACA,SAJa,gBAAgB,MAAM,cAAc,IAAI,KAAA,MAInC,KAAA;IAClB,aAAa;IACb,kBAAkB;GAGF,GAAS,EAAE;EAC/B;EAEA,MAAM,YAAe,IAAkC;GACrD,OAAO,kBAAkB,EAAE;EAC7B;EAEA,MAAM,gBACJ,UACA,IACY;GAUZ,OAAO,WAAW;IANhB;IACA,SAJa,gBAAgB,MAAM,cAAc,IAAI,KAAA,MAInC,KAAA;IAClB,aAAa;IACb,kBAAkB;GAGF,GAAS,EAAE;EAC/B;CACF;AACF;;;ACpEO,SAAS,wBAAwB,SAAmC;CACzE,MAAM,EACJ,iBACA,eACA,oBACA,cACA,YACA,eAAe,CAAC,MACd;CAEJ,OAAO,eAAe,kBACpB,KACA,KACA,MACe;EACf,IAAI;GAEF,IAAI,aAAa,MAAM,YAAY,YAAU,IAAI,MAAM,OAAO,CAAC,GAAG;IAChE,KAAK;IACL;GACF;GAGA,MAAM,WAAW,MAAM,gBAAgB,GAAG;GAE1C,IAAI,CAAC,UAAU;IACb,IAAI;SAEE,MADyB,WAAW,KAAK,GAAG,GAC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D,MAAM,cAAc,qBAChB,MAAM,mBAAmB,OAAO,UAAU,UAAU,KAAA,CAAS,oBAC7D,IAAI,IAAY;EACpB,MAAM,mBAAmB,eACrB,MAAM,aAAa,OAAO,UAAU,UAAU,KAAA,CAAS,IACvD;EAGJ,MAAM,UAA6B;GACjC;GACA,QAAQ,UAAU,KAAA;GAClB;GACA;EACF;EAGA,MAAM,OAAO,gBAAgB;EAC7B,MAAM,OAAO,WAAW;EAGxB,OAAO,WAAW,eAAe,QAAQ,KAAK,CAAC;CACjD;AACF;AAKA,SAAS,UAAU,MAAc,SAA0B;CAEzD,MAAM,eAAe,QAClB,QAAQ,OAAO,IAAI,CAAA,CACnB,QAAQ,OAAO,KAAK,CAAA,CACpB,QAAQ,OAAO,GAAG;CAErB,OAAO,IAAI,OAAO,IAAI,aAAY,EAAG,CAAA,CAAE,KAAK,IAAI;AAClD"}
1
+ {"version":3,"file":"adapters-D3XAWSIV.js","names":[],"sources":["../../src/adapters/cli.ts","../../src/adapters/express.ts","../../src/adapters/sveltekit.ts"],"sourcesContent":["/**\n * CLI Adapter for smrt-tenancy\n *\n * Provides utilities for setting up tenant context in CLI tools.\n *\n * @example\n * ```typescript\n * import { createCliContext } from '@happyvertical/smrt-tenancy/adapters';\n *\n * // Create context helper for CLI\n * const cliContext = createCliContext({\n * resolveTenantId: () => process.env.TENANT_ID,\n * });\n *\n * // Run command in tenant context\n * await cliContext.run(async () => {\n * await documentCollection.list({});\n * });\n * ```\n */\n\nimport {\n type TenantContextData,\n withSystemContext,\n withTenant,\n} from '../context.js';\n\n/**\n * Configuration for the CLI context runner created by `createCliContext()`.\n *\n * `resolveTenantId` is optional — when omitted (or when it returns\n * `null`/`undefined`) the `run()` method falls back to `withSystemContext()`.\n *\n * @see createCliContext\n * @see CliContextRunner\n */\nexport interface CliContextOptions {\n /**\n * Resolve tenant ID\n *\n * Common sources:\n * - Environment variable: () => process.env.TENANT_ID\n * - Command line argument: () => argv.tenant\n * - Config file: () => config.tenantId\n */\n resolveTenantId?: () =>\n | Promise<string | null | undefined>\n | string\n | null\n | undefined;\n\n /**\n * Resolve user ID (optional)\n */\n resolveUserId?: () =>\n | Promise<string | null | undefined>\n | string\n | null\n | undefined;\n\n /**\n * Default permissions for CLI operations\n */\n defaultPermissions?: Set<string>;\n\n /**\n * Run CLI as super admin by default\n * @default false\n */\n superAdminByDefault?: boolean;\n}\n\n/**\n * Context runner returned by `createCliContext()`.\n *\n * Provides four execution modes suitable for different CLI scenarios:\n * - `run()` — resolves the tenant from the configured options and runs code in\n * that context; falls back to system context if no tenant is available.\n * - `runWithTenant()` — explicitly specify a tenant ID for this invocation.\n * - `runAsSystem()` — bypass all tenant checks (migration scripts, admin tools).\n * - `runAsSuperAdmin()` — tenant context with bypass flag enabled.\n *\n * @see createCliContext\n */\nexport interface CliContextRunner {\n /**\n * Run `fn` inside the tenant context resolved from the `CliContextOptions`.\n *\n * Falls back to `withSystemContext()` when no tenant ID is available.\n *\n * @param fn - Async function to execute.\n * @returns Promise resolving to the return value of `fn`.\n */\n run<T>(fn: () => Promise<T>): Promise<T>;\n\n /**\n * Run `fn` inside the context of the specified tenant.\n *\n * @param tenantId - Tenant ID to set as context.\n * @param fn - Async function to execute.\n * @returns Promise resolving to the return value of `fn`.\n */\n runWithTenant<T>(tenantId: string, fn: () => Promise<T>): Promise<T>;\n\n /**\n * Run `fn` in system context, bypassing all tenant checks.\n *\n * @param fn - Async function to execute.\n * @returns Promise resolving to the return value of `fn`.\n */\n runAsSystem<T>(fn: () => Promise<T>): Promise<T>;\n\n /**\n * Run `fn` with a tenant context and super admin bypass enabled.\n *\n * @param tenantId - Tenant ID to set as context.\n * @param fn - Async function to execute.\n * @returns Promise resolving to the return value of `fn`.\n */\n runAsSuperAdmin<T>(tenantId: string, fn: () => Promise<T>): Promise<T>;\n}\n\n/**\n * Create a CLI context runner\n *\n * @param options - Configuration options\n * @returns CLI context runner with various execution modes\n *\n * @example\n * ```typescript\n * const cli = createCliContext({\n * resolveTenantId: () => process.env.TENANT_ID,\n * superAdminByDefault: true,\n * });\n *\n * // Use resolved tenant\n * await cli.run(async () => {\n * const docs = await collection.list({});\n * console.log(`Found ${docs.length} documents`);\n * });\n *\n * // Override tenant\n * await cli.runWithTenant('other-tenant', async () => {\n * // Operations in other-tenant context\n * });\n *\n * // System operations (no tenant)\n * await cli.runAsSystem(async () => {\n * // Can access all data\n * const allDocs = await collection.list({});\n * });\n * ```\n */\nexport function createCliContext(\n options: CliContextOptions = {},\n): CliContextRunner {\n const {\n resolveTenantId,\n resolveUserId,\n defaultPermissions = new Set<string>(),\n superAdminByDefault = false,\n } = options;\n\n return {\n async run<T>(fn: () => Promise<T>): Promise<T> {\n const tenantId = resolveTenantId ? await resolveTenantId() : null;\n\n if (!tenantId) {\n // No tenant configured - run in system context\n return withSystemContext(fn);\n }\n\n const userId = resolveUserId ? await resolveUserId() : undefined;\n\n const context: TenantContextData = {\n tenantId,\n userId: userId ?? undefined,\n permissions: defaultPermissions,\n superAdminBypass: superAdminByDefault,\n };\n\n return withTenant(context, fn);\n },\n\n async runWithTenant<T>(tenantId: string, fn: () => Promise<T>): Promise<T> {\n const userId = resolveUserId ? await resolveUserId() : undefined;\n\n const context: TenantContextData = {\n tenantId,\n userId: userId ?? undefined,\n permissions: defaultPermissions,\n superAdminBypass: superAdminByDefault,\n };\n\n return withTenant(context, fn);\n },\n\n async runAsSystem<T>(fn: () => Promise<T>): Promise<T> {\n return withSystemContext(fn);\n },\n\n async runAsSuperAdmin<T>(\n tenantId: string,\n fn: () => Promise<T>,\n ): Promise<T> {\n const userId = resolveUserId ? await resolveUserId() : undefined;\n\n const context: TenantContextData = {\n tenantId,\n userId: userId ?? undefined,\n permissions: defaultPermissions,\n superAdminBypass: true,\n };\n\n return withTenant(context, fn);\n },\n };\n}\n\n/**\n * Run an async function with a specific tenant ID set as context.\n *\n * Convenience wrapper around `withTenant()` for one-off CLI operations where\n * a full `CliContextRunner` is not needed.\n *\n * @param tenantId - Tenant ID to set as the active context.\n * @param fn - Async function to execute in the tenant context.\n * @returns Promise resolving to the return value of `fn`.\n *\n * @example\n * ```typescript\n * import { runWithTenant } from '@happyvertical/smrt-tenancy/adapters';\n *\n * await runWithTenant('tenant-123', async () => {\n * await collection.list({});\n * });\n * ```\n *\n * @see createCliContext\n * @see runAsSystem\n */\nexport async function runWithTenant<T>(\n tenantId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n return withTenant({ tenantId }, fn);\n}\n\n/**\n * Run an async function in system context, bypassing all tenant checks.\n *\n * Convenience wrapper around `withSystemContext()` for one-off CLI operations\n * such as migration scripts or admin tooling that needs cross-tenant access.\n *\n * @param fn - Async function to execute in system context.\n * @returns Promise resolving to the return value of `fn`.\n *\n * @example\n * ```typescript\n * import { runAsSystem } from '@happyvertical/smrt-tenancy/adapters';\n *\n * await runAsSystem(async () => {\n * const all = await collection.list({});\n * console.log(`Total records: ${all.length}`);\n * });\n * ```\n *\n * @see runWithTenant\n * @see createCliContext\n */\nexport async function runAsSystem<T>(fn: () => Promise<T>): Promise<T> {\n return withSystemContext(fn);\n}\n","/**\n * Express Adapter for smrt-tenancy\n *\n * Provides Express middleware that sets up tenant context for each request.\n *\n * @example\n * ```typescript\n * import express from 'express';\n * import { createExpressMiddleware } from '@happyvertical/smrt-tenancy/adapters';\n *\n * const app = express();\n *\n * app.use(createExpressMiddleware({\n * resolveTenantId: (req) => req.headers['x-tenant-id'] as string,\n * }));\n * ```\n */\n\nimport { enterTenantContext, type TenantContextData } from '../context.js';\n\n/**\n * Express Request interface (minimal to avoid direct dependency)\n */\ninterface ExpressRequest {\n headers: Record<string, string | string[] | undefined>;\n url: string;\n path: string;\n query: Record<string, unknown>;\n cookies?: Record<string, string>;\n}\n\n/**\n * Request object after the tenancy middleware has attached the resolved tenant\n * context. The middleware sets these properties so downstream route handlers can\n * read the tenant directly off the request.\n */\ninterface TenantAwareExpressRequest extends ExpressRequest {\n tenantContext?: TenantContextData;\n tenantId?: string;\n}\n\n/**\n * Express Response interface\n */\ninterface ExpressResponse {\n status(code: number): ExpressResponse;\n json(data: unknown): ExpressResponse;\n send(data: unknown): ExpressResponse;\n}\n\n/**\n * Express NextFunction\n */\ntype ExpressNext = (error?: unknown) => void;\n\n/**\n * Configuration options for the Express tenancy middleware created by\n * `createExpressMiddleware()`.\n *\n * Only `resolveTenantId` is required. All callback options receive the raw\n * Express `Request` object so you can extract tenant information from headers,\n * subdomains, cookies, or any other request property.\n *\n * @see createExpressMiddleware\n */\nexport interface ExpressMiddlewareOptions {\n /**\n * Resolve tenant ID from the request\n */\n resolveTenantId: (\n req: ExpressRequest,\n ) => Promise<string | null | undefined> | string | null | undefined;\n\n /**\n * Resolve user ID from the request (optional)\n */\n resolveUserId?: (\n req: ExpressRequest,\n ) => Promise<string | null | undefined> | string | null | undefined;\n\n /**\n * Resolve permissions (optional)\n */\n resolvePermissions?: (\n req: ExpressRequest,\n tenantId: string,\n userId?: string,\n ) => Promise<Set<string>> | Set<string>;\n\n /**\n * Check if user is super admin (optional)\n */\n isSuperAdmin?: (\n req: ExpressRequest,\n tenantId: string,\n userId?: string,\n ) => Promise<boolean> | boolean;\n\n /**\n * Called when no tenant ID could be resolved\n * Return true to continue, false to stop with 400 error.\n */\n onNoTenant?: (\n req: ExpressRequest,\n res: ExpressResponse,\n ) => Promise<boolean> | boolean;\n\n /**\n * Paths to exclude from tenant context\n */\n excludePaths?: string[];\n}\n\n/**\n * Create an Express middleware function that establishes tenant context for\n * every incoming request.\n *\n * Uses `enterTenantContext()` (rather than `withTenant()`) because Express\n * middleware returns before route handlers execute. `enterWith()` sets the\n * context on the current async resource so it propagates to handlers that run\n * after `next()` is called.\n *\n * The resolved context is also attached directly to the request object for\n * convenience:\n * - `req.tenantContext` — full `TenantContextData`\n * - `req.tenantId` — string tenant ID shortcut\n *\n * When no tenant ID can be resolved, the default behaviour returns a `400`\n * JSON response. Customise this with the `onNoTenant` option.\n *\n * @param options - Middleware configuration including the required\n * `resolveTenantId` callback.\n * @returns An Express-compatible middleware function `(req, res, next) => void`.\n *\n * @example\n * ```typescript\n * import express from 'express';\n * import { createExpressMiddleware } from '@happyvertical/smrt-tenancy/adapters';\n *\n * const app = express();\n * app.use(createExpressMiddleware({\n * resolveTenantId: (req) => req.headers['x-tenant-id'] as string,\n * excludePaths: ['/health', '/public/*'],\n * }));\n * ```\n *\n * @see ExpressMiddlewareOptions\n * @see createSvelteKitHandle\n */\nexport function createExpressMiddleware(options: ExpressMiddlewareOptions) {\n const {\n resolveTenantId,\n resolveUserId,\n resolvePermissions,\n isSuperAdmin,\n onNoTenant,\n excludePaths = [],\n } = options;\n\n return async function tenancyMiddleware(\n req: ExpressRequest,\n res: ExpressResponse,\n next: ExpressNext,\n ): Promise<void> {\n try {\n // Check excluded paths\n if (excludePaths.some((pattern) => matchPath(req.path, pattern))) {\n next();\n return;\n }\n\n // Resolve tenant ID\n const tenantId = await resolveTenantId(req);\n\n if (!tenantId) {\n if (onNoTenant) {\n const shouldContinue = await onNoTenant(req, res);\n if (shouldContinue) {\n next();\n return;\n }\n } else {\n res.status(400).json({\n error: 'Tenant ID required',\n message:\n 'Please provide a tenant ID via header, subdomain, or query parameter.',\n });\n return;\n }\n return;\n }\n\n // Resolve optional context\n const userId = resolveUserId ? await resolveUserId(req) : undefined;\n const permissions = resolvePermissions\n ? await resolvePermissions(req, tenantId, userId ?? undefined)\n : new Set<string>();\n const superAdminBypass = isSuperAdmin\n ? await isSuperAdmin(req, tenantId, userId ?? undefined)\n : false;\n\n // Build context\n const context: TenantContextData = {\n tenantId,\n userId: userId ?? undefined,\n permissions,\n superAdminBypass,\n };\n\n // Attach to request for access in route handlers\n (req as TenantAwareExpressRequest).tenantContext = context;\n (req as TenantAwareExpressRequest).tenantId = tenantId;\n\n // Use enterWith() to establish context that persists for the entire\n // request lifecycle. This ensures route handlers have access to\n // tenant context via AsyncLocalStorage.\n enterTenantContext(context);\n next();\n } catch (error) {\n next(error);\n }\n };\n}\n\n/**\n * Simple glob pattern matching for paths\n */\nfunction matchPath(path: string, pattern: string): boolean {\n const regexPattern = pattern\n .replace(/\\*/g, '.*')\n .replace(/\\//g, '\\\\/')\n .replace(/\\?/g, '.');\n\n return new RegExp(`^${regexPattern}$`).test(path);\n}\n","/**\n * SvelteKit Adapter for smrt-tenancy\n *\n * Provides a SvelteKit Handle that sets up tenant context for each request.\n *\n * @example\n * ```typescript\n * // hooks.server.ts\n * import { createSvelteKitHandle } from '@happyvertical/smrt-tenancy/adapters';\n *\n * export const handle = createSvelteKitHandle({\n * resolveTenantId: async (event) => {\n * // From subdomain\n * const host = event.request.headers.get('host');\n * const subdomain = host?.split('.')[0];\n * return subdomain;\n *\n * // Or from header\n * // return event.request.headers.get('x-tenant-id');\n *\n * // Or from cookie\n * // return event.cookies.get('tenant_id');\n * }\n * });\n * ```\n */\n\nimport { type TenantContextData, withTenant } from '../context.js';\n\n/**\n * SvelteKit RequestEvent (minimal interface to avoid direct dependency)\n */\ninterface SvelteKitEvent {\n request: Request;\n url: URL;\n cookies: {\n get(name: string): string | undefined;\n set(name: string, value: string, opts?: unknown): void;\n };\n locals: Record<string, unknown>;\n}\n\n/**\n * SvelteKit resolve function\n */\ntype SvelteKitResolve = (event: SvelteKitEvent) => Promise<Response>;\n\n/**\n * Configuration options for the SvelteKit tenancy handle created by\n * `createSvelteKitHandle()`.\n *\n * Only `resolveTenantId` is required; all other fields are optional callbacks\n * used to enrich the context or customise missing-tenant behaviour.\n *\n * @see createSvelteKitHandle\n */\nexport interface SvelteKitHandleOptions {\n /**\n * Resolve tenant ID from the request\n *\n * Return the tenant ID string, or null/undefined if no tenant context should be set.\n */\n resolveTenantId: (\n event: SvelteKitEvent,\n ) => Promise<string | null | undefined> | string | null | undefined;\n\n /**\n * Resolve user ID from the request (optional)\n */\n resolveUserId?: (\n event: SvelteKitEvent,\n ) => Promise<string | null | undefined> | string | null | undefined;\n\n /**\n * Resolve permissions for the user in this tenant (optional)\n */\n resolvePermissions?: (\n event: SvelteKitEvent,\n tenantId: string,\n userId?: string,\n ) => Promise<Set<string>> | Set<string>;\n\n /**\n * Check if user is a super admin (optional)\n * If true and super admin bypass is enabled on the class, tenant filtering is skipped.\n */\n isSuperAdmin?: (\n event: SvelteKitEvent,\n tenantId: string,\n userId?: string,\n ) => Promise<boolean> | boolean;\n\n /**\n * Called when no tenant ID could be resolved\n * Return a Response to short-circuit, or undefined to continue without tenant context.\n */\n onNoTenant?: (\n event: SvelteKitEvent,\n ) => Promise<Response | undefined> | Response | undefined;\n\n /**\n * Paths to exclude from tenant context (e.g., public APIs, health checks)\n * Supports glob patterns.\n */\n excludePaths?: string[];\n}\n\n/**\n * Create a SvelteKit `Handle` function that establishes tenant context for\n * every server-side request.\n *\n * The returned handle wraps the `resolve` call in `withTenant()` so that all\n * server-side load functions, API routes, and `+server.ts` handlers within the\n * request share the same tenant context via `AsyncLocalStorage`.\n *\n * The resolved context is also stored in `event.locals` under two keys:\n * - `event.locals.tenantContext` — full `TenantContextData`\n * - `event.locals.tenantId` — string tenant ID shortcut\n *\n * When no tenant ID can be resolved (and no custom `onNoTenant` handler\n * returns a `Response`), the request continues without any tenant context.\n *\n * @param options - Configuration options including the required\n * `resolveTenantId` callback.\n * @returns A SvelteKit `Handle` function suitable for use in `hooks.server.ts`.\n *\n * @example\n * ```typescript\n * // src/hooks.server.ts\n * import { createSvelteKitHandle } from '@happyvertical/smrt-tenancy/adapters';\n *\n * export const handle = createSvelteKitHandle({\n * resolveTenantId: (event) =>\n * event.request.headers.get('x-tenant-id'),\n * onNoTenant: () =>\n * new Response('Tenant required', { status: 400 }),\n * });\n * ```\n *\n * @see SvelteKitHandleOptions\n * @see createExpressMiddleware\n */\nexport function createSvelteKitHandle(options: SvelteKitHandleOptions) {\n const {\n resolveTenantId,\n resolveUserId,\n resolvePermissions,\n isSuperAdmin,\n onNoTenant,\n excludePaths = [],\n } = options;\n\n return async function handle({\n event,\n resolve,\n }: {\n event: SvelteKitEvent;\n resolve: SvelteKitResolve;\n }): Promise<Response> {\n // Check excluded paths\n const path = event.url.pathname;\n if (excludePaths.some((pattern) => matchPath(path, pattern))) {\n return resolve(event);\n }\n\n // Resolve tenant ID\n const tenantId = await resolveTenantId(event);\n\n if (!tenantId) {\n // No tenant ID - call handler or continue without context\n if (onNoTenant) {\n const response = await onNoTenant(event);\n if (response) {\n return response;\n }\n }\n return resolve(event);\n }\n\n // Resolve optional context data\n const userId = resolveUserId ? await resolveUserId(event) : undefined;\n const permissions = resolvePermissions\n ? await resolvePermissions(event, tenantId, userId ?? undefined)\n : new Set<string>();\n const superAdminBypass = isSuperAdmin\n ? await isSuperAdmin(event, tenantId, userId ?? undefined)\n : false;\n\n // Build context\n const context: TenantContextData = {\n tenantId,\n userId: userId ?? undefined,\n permissions,\n superAdminBypass,\n };\n\n // Store in locals for access in load functions\n event.locals.tenantContext = context;\n event.locals.tenantId = tenantId;\n\n // Run request in tenant context\n return withTenant(context, () => resolve(event));\n };\n}\n\n/**\n * Simple glob pattern matching for paths\n */\nfunction matchPath(path: string, pattern: string): boolean {\n // Convert glob to regex\n const regexPattern = pattern\n .replace(/\\*/g, '.*')\n .replace(/\\//g, '\\\\/')\n .replace(/\\?/g, '.');\n\n return new RegExp(`^${regexPattern}$`).test(path);\n}\n"],"mappings":";;AAyJO,SAAS,iBACd,UAA6B,CAAC,GACZ;CAClB,MAAM,EACJ,iBACA,eACA,qCAAqB,IAAI,IAAY,GACrC,sBAAsB,UACpB;CAEJ,OAAO;EACL,MAAM,IAAO,IAAkC;GAC7C,MAAM,WAAW,kBAAkB,MAAM,gBAAgB,IAAI;GAE7D,IAAI,CAAC,UAEH,OAAO,kBAAkB,EAAE;GAY7B,OAAO,WAAW;IANhB;IACA,SAJa,gBAAgB,MAAM,cAAc,IAAI,KAAA,MAInC,KAAA;IAClB,aAAa;IACb,kBAAkB;GAGF,GAAS,EAAE;EAC/B;EAEA,MAAM,cAAiB,UAAkB,IAAkC;GAUzE,OAAO,WAAW;IANhB;IACA,SAJa,gBAAgB,MAAM,cAAc,I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
60
60
  tenantStorage.enterWith(fullContext);
61
61
  }
62
+ function runInPrincipalContext(context, fn) {
63
+ if (!context) return tenantStorage.run(void 0, fn);
64
+ const projected = Object.freeze({
65
+ tenantId: context.tenantId,
66
+ ...context.userId ? { userId: context.userId } : {},
67
+ permissions: context.permissions ?? /* @__PURE__ */ new Set(),
68
+ superAdminBypass: false
69
+ });
70
+ return tenantStorage.run(projected, fn);
71
+ }
62
72
  async function withSystemContext(fn) {
63
73
  return tenantStorage.run(SYSTEM_CONTEXT_MARKER, fn);
64
74
  }
@@ -158,6 +168,6 @@ var TenantIsolationError = class extends Error {
158
168
  }
159
169
  };
160
170
  //#endregion
161
- export { getCurrentTenant as a, isSuperAdminBypass as c, requireTenantId as d, withSuperAdminBypass as f, withTenantSync as h, enterTenantContext as i, isSystemContext as l, withTenant as m, TenantContextError as n, getTenantId as o, withSystemContext as p, TenantIsolationError as r, hasTenantContext as s, TenantContext as t, requireTenant as u };
171
+ export { getCurrentTenant as a, isSuperAdminBypass as c, requireTenantId as d, runInPrincipalContext as f, withTenantSync as g, withTenant as h, enterTenantContext as i, isSystemContext as l, withSystemContext as m, TenantContextError as n, getTenantId as o, withSuperAdminBypass as p, TenantIsolationError as r, hasTenantContext as s, TenantContext as t, requireTenant as u };
162
172
 
163
- //# sourceMappingURL=context-CwbLwyIV.js.map
173
+ //# sourceMappingURL=context-BNwgjIhk.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"context-CwbLwyIV.js","names":[],"sources":["../../src/context.ts"],"sourcesContent":["/**\n * TenantContext - AsyncLocalStorage-based tenant context propagation\n *\n * Provides request-scoped tenant context that flows through async operations.\n * This is the core of the tenancy system - all tenant isolation depends on\n * having a valid context.\n *\n * @example Basic usage with middleware\n * ```typescript\n * import { withTenant, requireTenantId } from '@happyvertical/smrt-tenancy';\n *\n * // In middleware (SvelteKit, Express, etc.)\n * await withTenant({ tenantId: 'tenant-123' }, async () => {\n * // All code in this async tree has access to tenant context\n * const id = requireTenantId(); // 'tenant-123'\n * });\n * ```\n *\n * @example Background job binding\n * ```typescript\n * import { TenantContext } from '@happyvertical/smrt-tenancy';\n *\n * // Bind a callback to preserve context across async boundaries\n * setTimeout(TenantContext.bind(() => {\n * console.log(requireTenantId()); // Works!\n * }), 1000);\n * ```\n *\n * @see https://github.com/happyvertical/smrt/issues/675\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { DatabaseInterface } from '@happyvertical/sql';\n\n/**\n * Full data stored in tenant context for the current async execution scope.\n *\n * Created by `withTenant()` / `enterTenantContext()` and read by `getCurrentTenant()`,\n * `getTenantId()`, and the interceptor hooks. All fields except `tenantId` and\n * `permissions` are optional and may be populated lazily by higher-level packages\n * (e.g., `smrt-users`).\n *\n * @see withTenant\n * @see MinimalTenantContext\n */\nexport interface TenantContextData {\n /** Current tenant ID (required) */\n tenantId: string;\n\n /** Current tenant object (lazy-loaded if smrt-users is available) */\n tenant?: unknown;\n\n /** Current user ID (optional) */\n userId?: string;\n\n /** Current user object (lazy-loaded if smrt-users is available) */\n user?: unknown;\n\n /** Resolved permissions for this user in this tenant */\n permissions: Set<string>;\n\n /** Database connection for this tenant (if database-per-tenant strategy) */\n database?: DatabaseInterface;\n\n /** Super admin bypass enabled - allows cross-tenant operations */\n superAdminBypass?: boolean;\n\n /** Custom metadata for application-specific data */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Minimal context accepted by `withTenant()` and `withTenantSync()` when only a\n * tenant ID is known.\n *\n * `permissions` defaults to an empty `Set` when omitted. Use `TenantContextData`\n * when you also need to carry user info, database handles, or resolved permissions.\n *\n * @see TenantContextData\n * @see withTenant\n */\nexport interface MinimalTenantContext {\n /** Tenant identifier. */\n tenantId: string;\n /** Resolved permissions; defaults to an empty Set when omitted. */\n permissions?: Set<string>;\n /** When `true`, tenant auto-filtering is skipped for classes that allow super admin bypass. */\n superAdminBypass?: boolean;\n /** Arbitrary application-specific metadata to carry through the context. */\n metadata?: Record<string, unknown>;\n}\n\n// Sentinel symbol to mark system context (distinct from \"no context\")\nconst SYSTEM_CONTEXT_MARKER = Symbol.for('smrt:system-context');\n\n// Storage type includes the marker for system context\ntype ContextStoreValue = TenantContextData | typeof SYSTEM_CONTEXT_MARKER;\n\n// globalThis key for the shared AsyncLocalStorage. Vite/vitest/SvelteKit\n// server pipelines can evaluate this module more than once from a single copy\n// on disk (separate SSR/node module graphs, CJS/ESM interop); a module-local\n// storage would make context entered through one instance invisible to guards\n// reading from another (e.g. smrt-profiles' isSystemContext() check missing an\n// app's withSystemContext()). Symbol.for() resolves to the same symbol in\n// every instance, so all of them share the one storage below.\nconst TENANT_STORAGE_KEY = Symbol.for('smrt:tenant-context-storage');\n\n// AsyncLocalStorage instance for tenant context, shared across module instances\nfunction resolveTenantStorage(): AsyncLocalStorage<ContextStoreValue> {\n const root = globalThis as typeof globalThis & {\n [TENANT_STORAGE_KEY]?: AsyncLocalStorage<ContextStoreValue>;\n };\n root[TENANT_STORAGE_KEY] ??= new AsyncLocalStorage<ContextStoreValue>();\n return root[TENANT_STORAGE_KEY];\n}\n\nconst tenantStorage = resolveTenantStorage();\n\n/**\n * Get the current tenant context for this async execution scope.\n *\n * Returns `undefined` when called outside any tenant scope or inside a\n * `withSystemContext()` block (the system context marker is treated as \"no\n * tenant data\"). Prefer `requireTenant()` when a context is mandatory.\n *\n * @returns The active `TenantContextData`, or `undefined` if none is set.\n *\n * @example\n * ```typescript\n * const ctx = getCurrentTenant();\n * if (ctx) {\n * console.log('Current tenant:', ctx.tenantId);\n * }\n * ```\n *\n * @see requireTenant\n * @see hasTenantContext\n */\nexport function getCurrentTenant(): TenantContextData | undefined {\n const store = tenantStorage.getStore();\n // Return undefined for system context marker (no tenant data available)\n if (store === SYSTEM_CONTEXT_MARKER) {\n return undefined;\n }\n return store;\n}\n\n/**\n * Get the current tenant context or throw if one is not available.\n *\n * Use this in business-logic code that must run inside a tenant scope.\n * For a non-throwing alternative use `getCurrentTenant()`.\n *\n * @returns The active `TenantContextData`.\n * @throws {TenantContextError} When no tenant context is set (code is outside\n * any `withTenant()` call or the enclosing middleware has not run).\n *\n * @example\n * ```typescript\n * const { tenantId, permissions } = requireTenant();\n * ```\n *\n * @see getCurrentTenant\n * @see requireTenantId\n */\nexport function requireTenant(): TenantContextData {\n const ctx = tenantStorage.getStore();\n if (!ctx || ctx === SYSTEM_CONTEXT_MARKER) {\n throw new TenantContextError(\n 'No tenant context available. ' +\n 'Ensure request is wrapped in withTenant() or middleware is configured.',\n );\n }\n return ctx;\n}\n\n/**\n * Get the current tenant ID or throw if no tenant context is available.\n *\n * Shorthand for `requireTenant().tenantId`.\n *\n * @returns The active tenant ID string.\n * @throws {TenantContextError} When no tenant context is set.\n *\n * @example\n * ```typescript\n * const tenantId = requireTenantId();\n * const rows = await db.query(`SELECT * FROM docs WHERE tenant_id = ?`, [tenantId]);\n * ```\n *\n * @see getTenantId\n * @see requireTenant\n */\nexport function requireTenantId(): string {\n return requireTenant().tenantId;\n}\n\n/**\n * Get the current tenant ID without throwing.\n *\n * Returns `undefined` when called outside any tenant scope or inside a\n * `withSystemContext()` block. Use `requireTenantId()` when a missing context\n * should be treated as an error.\n *\n * @returns The active tenant ID, or `undefined` if none is set.\n *\n * @example\n * ```typescript\n * const tenantId = getTenantId();\n * if (tenantId) {\n * // Optional tenant-scoped logic\n * }\n * ```\n *\n * @see requireTenantId\n * @see hasTenantContext\n */\nexport function getTenantId(): string | undefined {\n const store = tenantStorage.getStore();\n if (store === SYSTEM_CONTEXT_MARKER) {\n return undefined;\n }\n return store?.tenantId;\n}\n\n/**\n * Check whether the current async execution scope has an active tenant context.\n *\n * Returns `false` both when there is no context at all and when code is running\n * inside `withSystemContext()` (the system marker is not a tenant context).\n *\n * @returns `true` if a `TenantContextData` is active, `false` otherwise.\n *\n * @example\n * ```typescript\n * if (hasTenantContext()) {\n * console.log('Tenant:', getTenantId());\n * }\n * ```\n *\n * @see getTenantId\n * @see isSystemContext\n */\nexport function hasTenantContext(): boolean {\n const store = tenantStorage.getStore();\n // System context marker means no tenant context (even though storage is set)\n return store !== undefined && store !== SYSTEM_CONTEXT_MARKER;\n}\n\n/**\n * Check whether the current async execution scope was entered via `withSystemContext()`.\n *\n * A system context is explicitly set to bypass all tenant checks; it is distinct\n * from \"no context\" (undefined store). When the store is undefined the\n * interceptor enforces tenant requirements; when it holds the system marker the\n * interceptor skips all checks.\n *\n * @returns `true` if inside a `withSystemContext()` call, `false` otherwise.\n *\n * @see withSystemContext\n * @see hasTenantContext\n */\nexport function isSystemContext(): boolean {\n return tenantStorage.getStore() === SYSTEM_CONTEXT_MARKER;\n}\n\n/**\n * Check whether the super admin bypass flag is set in the current tenant context.\n *\n * When `true`, the interceptor skips tenant auto-filtering for classes that have\n * `allowSuperAdminBypass: true` in their `@TenantScoped()` config. Returns\n * `false` inside a system context (no tenant data is available).\n *\n * @returns `true` if super admin bypass is active, `false` otherwise.\n *\n * @see withSuperAdminBypass\n * @see TenantScopedOptions.allowSuperAdminBypass\n */\nexport function isSuperAdminBypass(): boolean {\n const store = tenantStorage.getStore();\n if (store === SYSTEM_CONTEXT_MARKER) {\n return false;\n }\n return store?.superAdminBypass === true;\n}\n\n/**\n * Run code within a tenant context (async version)\n *\n * @param context - Tenant context data (at minimum, tenantId)\n * @param fn - Async function to run within the tenant context\n * @returns Promise resolving to the function's return value\n *\n * @example\n * ```typescript\n * await withTenant({ tenantId: 'tenant-123' }, async () => {\n * const id = requireTenantId(); // 'tenant-123'\n * await doSomething();\n * });\n * ```\n */\nexport async function withTenant<T>(\n context: TenantContextData | MinimalTenantContext,\n fn: () => Promise<T>,\n): Promise<T> {\n const fullContext: TenantContextData = {\n permissions: new Set(),\n ...context,\n };\n return tenantStorage.run(fullContext, fn);\n}\n\n/**\n * Run synchronous code within a tenant context.\n *\n * Prefer `withTenant()` for async code. Use this variant only when the\n * callback must be synchronous (e.g., initializing a module-level value that\n * is consumed synchronously downstream).\n *\n * @param context - Tenant context data (at minimum, `tenantId`).\n * @param fn - Synchronous function to run within the tenant context.\n * @returns The return value of `fn`.\n *\n * @example\n * ```typescript\n * const result = withTenantSync({ tenantId: 'tenant-123' }, () => {\n * return computeSomethingSync();\n * });\n * ```\n *\n * @see withTenant\n */\nexport function withTenantSync<T>(\n context: TenantContextData | MinimalTenantContext,\n fn: () => T,\n): T {\n const fullContext: TenantContextData = {\n permissions: new Set(),\n ...context,\n };\n return tenantStorage.run(fullContext, fn);\n}\n\n/**\n * Enter tenant context for the remainder of the current async execution\n *\n * This uses AsyncLocalStorage.enterWith() to establish context that persists\n * until the async resource completes. Useful for Express middleware where\n * the route handler executes after the middleware returns.\n *\n * @param context - Tenant context data\n *\n * @example Express middleware\n * ```typescript\n * app.use((req, res, next) => {\n * const tenantId = req.headers['x-tenant-id'] as string;\n * enterTenantContext({ tenantId });\n * next(); // Route handlers now have tenant context\n * });\n * ```\n */\nexport function enterTenantContext(\n context: TenantContextData | MinimalTenantContext,\n): void {\n const fullContext: TenantContextData = {\n permissions: new Set(),\n ...context,\n };\n tenantStorage.enterWith(fullContext);\n}\n\n/**\n * Run code in system context (bypasses tenant checks)\n *\n * Use this for:\n * - Migration scripts\n * - Admin tools that need cross-tenant access\n * - Background jobs that process multiple tenants\n *\n * System context is explicitly different from \"no context\" - it signals\n * that tenant checks should be bypassed, while no context means the\n * interceptor should enforce tenant requirements.\n *\n * @param fn - Async function to run without tenant context\n *\n * @example\n * ```typescript\n * await withSystemContext(async () => {\n * // No tenant context - can access all data\n * const allDocuments = await documentCollection.list({});\n * });\n * ```\n */\nexport async function withSystemContext<T>(fn: () => Promise<T>): Promise<T> {\n // Run with system context marker (distinct from undefined/no context)\n return tenantStorage.run(SYSTEM_CONTEXT_MARKER, fn);\n}\n\n/**\n * Run async code with the super admin bypass flag enabled on the current\n * tenant context.\n *\n * Unlike `withSystemContext()`, this does **not** remove the tenant context —\n * the caller's `tenantId` remains intact. The interceptor skips\n * auto-filtering only for classes that have `allowSuperAdminBypass: true` in\n * their `@TenantScoped()` config.\n *\n * A tenant context must already be active (i.e., this must be called from\n * within a `withTenant()` scope). Use `withSystemContext()` if no tenant\n * context is available at all.\n *\n * @param fn - Async function to run with super admin bypass enabled.\n * @returns Promise resolving to the return value of `fn`.\n * @throws {TenantContextError} If called outside any tenant context.\n *\n * @example\n * ```typescript\n * await withTenant({ tenantId: 'admin-tenant' }, async () => {\n * await withSuperAdminBypass(async () => {\n * // Can read any tenant's AuditLog (if allowSuperAdminBypass: true)\n * const logs = await auditLogCollection.list({});\n * });\n * });\n * ```\n *\n * @see withSystemContext\n * @see isSuperAdminBypass\n */\nexport async function withSuperAdminBypass<T>(\n fn: () => Promise<T>,\n): Promise<T> {\n const current = tenantStorage.getStore();\n if (!current || current === SYSTEM_CONTEXT_MARKER) {\n throw new TenantContextError(\n 'Cannot enable super admin bypass without a tenant context. ' +\n 'Use withTenant() first or withSystemContext() instead.',\n );\n }\n\n const bypassContext: TenantContextData = {\n ...current,\n superAdminBypass: true,\n };\n\n return tenantStorage.run(bypassContext, fn);\n}\n\n/**\n * Namespace object providing advanced tenant context utilities.\n *\n * Contains helpers for binding callbacks, inspecting context state, and\n * running code with the context stored in a queued job payload. These\n * utilities supplement the standalone exported functions for situations where\n * async context might otherwise be lost (e.g., `setTimeout`, event emitters,\n * message queue consumers).\n *\n * @example\n * ```typescript\n * import { TenantContext } from '@happyvertical/smrt-tenancy';\n *\n * // Preserve context across a setTimeout\n * setTimeout(TenantContext.bind(() => {\n * console.log(getTenantId()); // context is intact\n * }), 500);\n *\n * // Process a queued job\n * await TenantContext.runWithJobContext(job, async () => {\n * await processJob(job);\n * });\n * ```\n */\nexport const TenantContext = {\n /**\n * Bind a callback to the current tenant context\n *\n * Use this when passing callbacks to setTimeout, event emitters,\n * or other APIs that might lose the async context.\n *\n * @param fn - Function to bind to current context\n * @returns Wrapped function that will run in the original context\n *\n * @example\n * ```typescript\n * // Without bind - context is lost\n * setTimeout(() => {\n * console.log(getTenantId()); // undefined!\n * }, 1000);\n *\n * // With bind - context is preserved\n * setTimeout(TenantContext.bind(() => {\n * console.log(getTenantId()); // 'tenant-123'\n * }), 1000);\n * ```\n */\n bind<T extends (...args: unknown[]) => unknown>(fn: T): T {\n const store = tenantStorage.getStore();\n if (!store) {\n // No context to bind, return function as-is\n return fn;\n }\n\n // Preserve the context (including system context marker)\n return ((...args: unknown[]) => {\n return tenantStorage.run(store, () => fn(...args));\n }) as T;\n },\n\n /**\n * Get the current context data (or undefined for system/no context)\n */\n get current(): TenantContextData | undefined {\n return getCurrentTenant();\n },\n\n /**\n * Check if we're in system context\n */\n get isSystem(): boolean {\n return isSystemContext();\n },\n\n /**\n * Run code with context from a job/message payload\n *\n * Useful for processing queued jobs that include tenant metadata.\n *\n * @param job - Job object with tenantId in metadata\n * @param fn - Function to run in the job's tenant context\n *\n * @example\n * ```typescript\n * const job = await queue.pop();\n * await TenantContext.runWithJobContext(job, async () => {\n * await processJob(job);\n * });\n * ```\n */\n async runWithJobContext<T>(\n job: { metadata?: { tenantId?: string }; tenantId?: string },\n fn: () => Promise<T>,\n ): Promise<T> {\n const tenantId = job.metadata?.tenantId ?? job.tenantId;\n if (!tenantId) {\n throw new TenantContextError(\n 'Job does not contain tenant information. ' +\n 'Ensure jobs include tenantId in metadata or as a top-level field.',\n );\n }\n\n return withTenant({ tenantId }, fn);\n },\n};\n\n/**\n * Error thrown when a tenant context is required but not available.\n *\n * Raised by `requireTenant()`, `requireTenantId()`, and the tenant interceptor\n * when a `@TenantScoped({ mode: 'required' })` operation is attempted outside\n * any `withTenant()` scope.\n *\n * The `code` property is always `'TENANT_CONTEXT_REQUIRED'` and can be used for\n * programmatic error handling.\n *\n * @example\n * ```typescript\n * try {\n * const tenantId = requireTenantId();\n * } catch (err) {\n * if (err instanceof TenantContextError) {\n * // err.code === 'TENANT_CONTEXT_REQUIRED'\n * }\n * }\n * ```\n *\n * @see requireTenant\n * @see requireTenantId\n * @see TenantIsolationError\n */\nexport class TenantContextError extends Error {\n /** Stable error code; always `'TENANT_CONTEXT_REQUIRED'`. */\n readonly code = 'TENANT_CONTEXT_REQUIRED';\n\n constructor(message: string) {\n super(message);\n this.name = 'TenantContextError';\n }\n}\n\n/**\n * Error thrown when a tenant isolation boundary is crossed.\n *\n * Raised by the tenant interceptor when:\n * - A `list()` or `get()` query explicitly filters by a tenant ID that does not\n * match the current context tenant.\n * - A `save()` or `delete()` is attempted on an object whose `tenantId` field\n * belongs to a different tenant than the current context.\n * - A raw SQL query is executed against a tenant-scoped class without an\n * explicit bypass (when `rawQueryPolicy` is `'throw'`).\n *\n * The `code` property is always `'TENANT_ISOLATION_VIOLATION'`.\n *\n * @example\n * ```typescript\n * try {\n * await collection.list({ where: { tenantId: 'other-tenant' } });\n * } catch (err) {\n * if (err instanceof TenantIsolationError) {\n * // err.tenantId — context tenant\n * // err.attemptedTenantId — tenant that was attempted\n * }\n * }\n * ```\n *\n * @see TenantContextError\n * @see createTenantInterceptor\n */\nexport class TenantIsolationError extends Error {\n /** Stable error code; always `'TENANT_ISOLATION_VIOLATION'`. */\n readonly code = 'TENANT_ISOLATION_VIOLATION';\n /** The tenant ID that is active in the current context. */\n readonly tenantId?: string;\n /** The tenant ID that was attempted (and rejected). */\n readonly attemptedTenantId?: string;\n\n constructor(\n message: string,\n details?: { tenantId?: string; attemptedTenantId?: string },\n ) {\n super(message);\n this.name = 'TenantIsolationError';\n this.tenantId = details?.tenantId;\n this.attemptedTenantId = details?.attemptedTenantId;\n }\n}\n"],"mappings":";;AA6FA,IAAM,wBAAwB,uBAAO,IAAI,qBAAqB;AAY9D,IAAM,qBAAqB,uBAAO,IAAI,6BAA6B;AAGnE,SAAS,uBAA6D;CACpE,MAAM,OAAO;CAGb,KAAK,wBAAwB,IAAI,kBAAqC;CACtE,OAAO,KAAK;AACd;AAEA,IAAM,gBAAgB,qBAAqB;AAsBpC,SAAS,mBAAkD;CAChE,MAAM,QAAQ,cAAc,SAAS;CAErC,IAAI,UAAU,uBACZ;CAEF,OAAO;AACT;AAoBO,SAAS,gBAAmC;CACjD,MAA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;;;;;;;;;;;CAuB3B,KAAgD,IAAU;EACxD,MAAM,QAAQ,cAAc,SAAS;EACrC,IAAI,CAAC,OAEH,OAAO;EAIT,SAAQ,GAAI,SAAoB;GAC9B,OAAO,cAAc,IAAI,aAAa,GAAG,GAAG,IAAI,CAAC;EACnD;CACF;;;;CAKA,IAAI,UAAyC;EAC3C,OAAO,iBAAiB;CAC1B;;;;CAKA,IAAI,WAAoB;EACtB,OAAO,gBAAgB;CACzB;;;;;;;;;;;;;;;;;CAkBA,MAAM,kBACJ,KACA,IACY;EACZ,MAAM,WAAW,IAAI,UAAU,YAAY,IAAI;EAC/C,IAAI,CAAC,UACH,MAAM,IAAI,mBACR,4GAEF;EAGF,OAAO,WAAW,EAAE,SAAS,GAAG,EAAE;CACpC;AACF;AA2BO,IAAM,qBAAN,cAAiC,MAAM;;CAEnC,OAAO;CAEhB,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AA8BO,IAAM,uBAAN,cAAmC,MAAM;;CAErC,OAAO;;CAEP;;CAEA;CAET,YACE,SACA,SACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,WAAW,SAAS;EACzB,KAAK,oBAAoB,SAAS;CACpC;AACF"}
1
+ {"version":3,"file":"context-BNwgjIhk.js","names":[],"sources":["../../src/context.ts"],"sourcesContent":["/**\n * TenantContext - AsyncLocalStorage-based tenant context propagation\n *\n * Provides request-scoped tenant context that flows through async operations.\n * This is the core of the tenancy system - all tenant isolation depends on\n * having a valid context.\n *\n * @example Basic usage with middleware\n * ```typescript\n * import { withTenant, requireTenantId } from '@happyvertical/smrt-tenancy';\n *\n * // In middleware (SvelteKit, Express, etc.)\n * await withTenant({ tenantId: 'tenant-123' }, async () => {\n * // All code in this async tree has access to tenant context\n * const id = requireTenantId(); // 'tenant-123'\n * });\n * ```\n *\n * @example Background job binding\n * ```typescript\n * import { TenantContext } from '@happyvertical/smrt-tenancy';\n *\n * // Bind a callback to preserve context across async boundaries\n * setTimeout(TenantContext.bind(() => {\n * console.log(requireTenantId()); // Works!\n * }), 1000);\n * ```\n *\n * @see https://github.com/happyvertical/smrt/issues/675\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { DatabaseInterface } from '@happyvertical/sql';\n\n/**\n * Full data stored in tenant context for the current async execution scope.\n *\n * Created by `withTenant()` / `enterTenantContext()` and read by `getCurrentTenant()`,\n * `getTenantId()`, and the interceptor hooks. All fields except `tenantId` and\n * `permissions` are optional and may be populated lazily by higher-level packages\n * (e.g., `smrt-users`).\n *\n * @see withTenant\n * @see MinimalTenantContext\n */\nexport interface TenantContextData {\n /** Current tenant ID (required) */\n tenantId: string;\n\n /** Current tenant object (lazy-loaded if smrt-users is available) */\n tenant?: unknown;\n\n /** Current user ID (optional) */\n userId?: string;\n\n /** Current user object (lazy-loaded if smrt-users is available) */\n user?: unknown;\n\n /** Resolved permissions for this user in this tenant */\n permissions: Set<string>;\n\n /** Database connection for this tenant (if database-per-tenant strategy) */\n database?: DatabaseInterface;\n\n /** Super admin bypass enabled - allows cross-tenant operations */\n superAdminBypass?: boolean;\n\n /** Custom metadata for application-specific data */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Minimal context accepted by `withTenant()` and `withTenantSync()` when only a\n * tenant ID is known.\n *\n * `permissions` defaults to an empty `Set` when omitted. Use `TenantContextData`\n * when you also need to carry user info, database handles, or resolved permissions.\n *\n * @see TenantContextData\n * @see withTenant\n */\nexport interface MinimalTenantContext {\n /** Tenant identifier. */\n tenantId: string;\n /** Resolved permissions; defaults to an empty Set when omitted. */\n permissions?: Set<string>;\n /** When `true`, tenant auto-filtering is skipped for classes that allow super admin bypass. */\n superAdminBypass?: boolean;\n /** Arbitrary application-specific metadata to carry through the context. */\n metadata?: Record<string, unknown>;\n}\n\n// Sentinel symbol to mark system context (distinct from \"no context\")\nconst SYSTEM_CONTEXT_MARKER = Symbol.for('smrt:system-context');\n\n// Storage type includes the marker for system context\ntype ContextStoreValue = TenantContextData | typeof SYSTEM_CONTEXT_MARKER;\n\n// globalThis key for the shared AsyncLocalStorage. Vite/vitest/SvelteKit\n// server pipelines can evaluate this module more than once from a single copy\n// on disk (separate SSR/node module graphs, CJS/ESM interop); a module-local\n// storage would make context entered through one instance invisible to guards\n// reading from another (e.g. smrt-profiles' isSystemContext() check missing an\n// app's withSystemContext()). Symbol.for() resolves to the same symbol in\n// every instance, so all of them share the one storage below.\nconst TENANT_STORAGE_KEY = Symbol.for('smrt:tenant-context-storage');\n\n// AsyncLocalStorage instance for tenant context, shared across module instances\nfunction resolveTenantStorage(): AsyncLocalStorage<ContextStoreValue> {\n const root = globalThis as typeof globalThis & {\n [TENANT_STORAGE_KEY]?: AsyncLocalStorage<ContextStoreValue>;\n };\n root[TENANT_STORAGE_KEY] ??= new AsyncLocalStorage<ContextStoreValue>();\n return root[TENANT_STORAGE_KEY];\n}\n\nconst tenantStorage = resolveTenantStorage();\n\n/**\n * Get the current tenant context for this async execution scope.\n *\n * Returns `undefined` when called outside any tenant scope or inside a\n * `withSystemContext()` block (the system context marker is treated as \"no\n * tenant data\"). Prefer `requireTenant()` when a context is mandatory.\n *\n * @returns The active `TenantContextData`, or `undefined` if none is set.\n *\n * @example\n * ```typescript\n * const ctx = getCurrentTenant();\n * if (ctx) {\n * console.log('Current tenant:', ctx.tenantId);\n * }\n * ```\n *\n * @see requireTenant\n * @see hasTenantContext\n */\nexport function getCurrentTenant(): TenantContextData | undefined {\n const store = tenantStorage.getStore();\n // Return undefined for system context marker (no tenant data available)\n if (store === SYSTEM_CONTEXT_MARKER) {\n return undefined;\n }\n return store;\n}\n\n/**\n * Get the current tenant context or throw if one is not available.\n *\n * Use this in business-logic code that must run inside a tenant scope.\n * For a non-throwing alternative use `getCurrentTenant()`.\n *\n * @returns The active `TenantContextData`.\n * @throws {TenantContextError} When no tenant context is set (code is outside\n * any `withTenant()` call or the enclosing middleware has not run).\n *\n * @example\n * ```typescript\n * const { tenantId, permissions } = requireTenant();\n * ```\n *\n * @see getCurrentTenant\n * @see requireTenantId\n */\nexport function requireTenant(): TenantContextData {\n const ctx = tenantStorage.getStore();\n if (!ctx || ctx === SYSTEM_CONTEXT_MARKER) {\n throw new TenantContextError(\n 'No tenant context available. ' +\n 'Ensure request is wrapped in withTenant() or middleware is configured.',\n );\n }\n return ctx;\n}\n\n/**\n * Get the current tenant ID or throw if no tenant context is available.\n *\n * Shorthand for `requireTenant().tenantId`.\n *\n * @returns The active tenant ID string.\n * @throws {TenantContextError} When no tenant context is set.\n *\n * @example\n * ```typescript\n * const tenantId = requireTenantId();\n * const rows = await db.query(`SELECT * FROM docs WHERE tenant_id = ?`, [tenantId]);\n * ```\n *\n * @see getTenantId\n * @see requireTenant\n */\nexport function requireTenantId(): string {\n return requireTenant().tenantId;\n}\n\n/**\n * Get the current tenant ID without throwing.\n *\n * Returns `undefined` when called outside any tenant scope or inside a\n * `withSystemContext()` block. Use `requireTenantId()` when a missing context\n * should be treated as an error.\n *\n * @returns The active tenant ID, or `undefined` if none is set.\n *\n * @example\n * ```typescript\n * const tenantId = getTenantId();\n * if (tenantId) {\n * // Optional tenant-scoped logic\n * }\n * ```\n *\n * @see requireTenantId\n * @see hasTenantContext\n */\nexport function getTenantId(): string | undefined {\n const store = tenantStorage.getStore();\n if (store === SYSTEM_CONTEXT_MARKER) {\n return undefined;\n }\n return store?.tenantId;\n}\n\n/**\n * Check whether the current async execution scope has an active tenant context.\n *\n * Returns `false` both when there is no context at all and when code is running\n * inside `withSystemContext()` (the system marker is not a tenant context).\n *\n * @returns `true` if a `TenantContextData` is active, `false` otherwise.\n *\n * @example\n * ```typescript\n * if (hasTenantContext()) {\n * console.log('Tenant:', getTenantId());\n * }\n * ```\n *\n * @see getTenantId\n * @see isSystemContext\n */\nexport function hasTenantContext(): boolean {\n const store = tenantStorage.getStore();\n // System context marker means no tenant context (even though storage is set)\n return store !== undefined && store !== SYSTEM_CONTEXT_MARKER;\n}\n\n/**\n * Check whether the current async execution scope was entered via `withSystemContext()`.\n *\n * A system context is explicitly set to bypass all tenant checks; it is distinct\n * from \"no context\" (undefined store). When the store is undefined the\n * interceptor enforces tenant requirements; when it holds the system marker the\n * interceptor skips all checks.\n *\n * @returns `true` if inside a `withSystemContext()` call, `false` otherwise.\n *\n * @see withSystemContext\n * @see hasTenantContext\n */\nexport function isSystemContext(): boolean {\n return tenantStorage.getStore() === SYSTEM_CONTEXT_MARKER;\n}\n\n/**\n * Check whether the super admin bypass flag is set in the current tenant context.\n *\n * When `true`, the interceptor skips tenant auto-filtering for classes that have\n * `allowSuperAdminBypass: true` in their `@TenantScoped()` config. Returns\n * `false` inside a system context (no tenant data is available).\n *\n * @returns `true` if super admin bypass is active, `false` otherwise.\n *\n * @see withSuperAdminBypass\n * @see TenantScopedOptions.allowSuperAdminBypass\n */\nexport function isSuperAdminBypass(): boolean {\n const store = tenantStorage.getStore();\n if (store === SYSTEM_CONTEXT_MARKER) {\n return false;\n }\n return store?.superAdminBypass === true;\n}\n\n/**\n * Run code within a tenant context (async version)\n *\n * @param context - Tenant context data (at minimum, tenantId)\n * @param fn - Async function to run within the tenant context\n * @returns Promise resolving to the function's return value\n *\n * @example\n * ```typescript\n * await withTenant({ tenantId: 'tenant-123' }, async () => {\n * const id = requireTenantId(); // 'tenant-123'\n * await doSomething();\n * });\n * ```\n */\nexport async function withTenant<T>(\n context: TenantContextData | MinimalTenantContext,\n fn: () => Promise<T>,\n): Promise<T> {\n const fullContext: TenantContextData = {\n permissions: new Set(),\n ...context,\n };\n return tenantStorage.run(fullContext, fn);\n}\n\n/**\n * Run synchronous code within a tenant context.\n *\n * Prefer `withTenant()` for async code. Use this variant only when the\n * callback must be synchronous (e.g., initializing a module-level value that\n * is consumed synchronously downstream).\n *\n * @param context - Tenant context data (at minimum, `tenantId`).\n * @param fn - Synchronous function to run within the tenant context.\n * @returns The return value of `fn`.\n *\n * @example\n * ```typescript\n * const result = withTenantSync({ tenantId: 'tenant-123' }, () => {\n * return computeSomethingSync();\n * });\n * ```\n *\n * @see withTenant\n */\nexport function withTenantSync<T>(\n context: TenantContextData | MinimalTenantContext,\n fn: () => T,\n): T {\n const fullContext: TenantContextData = {\n permissions: new Set(),\n ...context,\n };\n return tenantStorage.run(fullContext, fn);\n}\n\n/**\n * Enter tenant context for the remainder of the current async execution\n *\n * This uses AsyncLocalStorage.enterWith() to establish context that persists\n * until the async resource completes. Useful for Express middleware where\n * the route handler executes after the middleware returns.\n *\n * @param context - Tenant context data\n *\n * @example Express middleware\n * ```typescript\n * app.use((req, res, next) => {\n * const tenantId = req.headers['x-tenant-id'] as string;\n * enterTenantContext({ tenantId });\n * next(); // Route handlers now have tenant context\n * });\n * ```\n */\nexport function enterTenantContext(\n context: TenantContextData | MinimalTenantContext,\n): void {\n const fullContext: TenantContextData = {\n permissions: new Set(),\n ...context,\n };\n tenantStorage.enterWith(fullContext);\n}\n\n/**\n * Run `fn` as a host-resolved request principal (#5195). Internal: lent to\n * core as the policy source's `runForPrincipal`, never exported.\n *\n * Replaces whatever context is active with a frozen projection of the\n * principal (its tenant, user and read-only permissions, and never the\n * super-admin bypass flag), or, for `null`, with no tenant and no system\n * context.\n *\n * @internal\n */\nexport function runInPrincipalContext<T>(\n context: {\n tenantId: string;\n userId?: string;\n permissions?: ReadonlySet<string>;\n } | null,\n fn: () => Promise<T>,\n): Promise<T> {\n if (!context) {\n return tenantStorage.run(undefined as unknown as ContextStoreValue, fn);\n }\n const projected = Object.freeze({\n tenantId: context.tenantId,\n ...(context.userId ? { userId: context.userId } : {}),\n // A read-only view from core; declared as a `Set` for consumers, whose\n // mutators throw inside a principal request.\n permissions: (context.permissions ?? new Set<string>()) as Set<string>,\n superAdminBypass: false,\n }) as TenantContextData;\n return tenantStorage.run(projected, fn);\n}\n\n/**\n * Run code in system context (bypasses tenant checks)\n *\n * Use this for:\n * - Migration scripts\n * - Admin tools that need cross-tenant access\n * - Background jobs that process multiple tenants\n *\n * System context is explicitly different from \"no context\" - it signals\n * that tenant checks should be bypassed, while no context means the\n * interceptor should enforce tenant requirements.\n *\n * @param fn - Async function to run without tenant context\n *\n * @example\n * ```typescript\n * await withSystemContext(async () => {\n * // No tenant context - can access all data\n * const allDocuments = await documentCollection.list({});\n * });\n * ```\n */\nexport async function withSystemContext<T>(fn: () => Promise<T>): Promise<T> {\n // Run with system context marker (distinct from undefined/no context)\n return tenantStorage.run(SYSTEM_CONTEXT_MARKER, fn);\n}\n\n/**\n * Run async code with the super admin bypass flag enabled on the current\n * tenant context.\n *\n * Unlike `withSystemContext()`, this does **not** remove the tenant context —\n * the caller's `tenantId` remains intact. The interceptor skips\n * auto-filtering only for classes that have `allowSuperAdminBypass: true` in\n * their `@TenantScoped()` config.\n *\n * A tenant context must already be active (i.e., this must be called from\n * within a `withTenant()` scope). Use `withSystemContext()` if no tenant\n * context is available at all.\n *\n * @param fn - Async function to run with super admin bypass enabled.\n * @returns Promise resolving to the return value of `fn`.\n * @throws {TenantContextError} If called outside any tenant context.\n *\n * @example\n * ```typescript\n * await withTenant({ tenantId: 'admin-tenant' }, async () => {\n * await withSuperAdminBypass(async () => {\n * // Can read any tenant's AuditLog (if allowSuperAdminBypass: true)\n * const logs = await auditLogCollection.list({});\n * });\n * });\n * ```\n *\n * @see withSystemContext\n * @see isSuperAdminBypass\n */\nexport async function withSuperAdminBypass<T>(\n fn: () => Promise<T>,\n): Promise<T> {\n const current = tenantStorage.getStore();\n if (!current || current === SYSTEM_CONTEXT_MARKER) {\n throw new TenantContextError(\n 'Cannot enable super admin bypass without a tenant context. ' +\n 'Use withTenant() first or withSystemContext() instead.',\n );\n }\n\n const bypassContext: TenantContextData = {\n ...current,\n superAdminBypass: true,\n };\n\n return tenantStorage.run(bypassContext, fn);\n}\n\n/**\n * Namespace object providing advanced tenant context utilities.\n *\n * Contains helpers for binding callbacks, inspecting context state, and\n * running code with the context stored in a queued job payload. These\n * utilities supplement the standalone exported functions for situations where\n * async context might otherwise be lost (e.g., `setTimeout`, event emitters,\n * message queue consumers).\n *\n * @example\n * ```typescript\n * import { TenantContext } from '@happyvertical/smrt-tenancy';\n *\n * // Preserve context across a setTimeout\n * setTimeout(TenantContext.bind(() => {\n * console.log(getTenantId()); // context is intact\n * }), 500);\n *\n * // Process a queued job\n * await TenantContext.runWithJobContext(job, async () => {\n * await processJob(job);\n * });\n * ```\n */\nexport const TenantContext = {\n /**\n * Bind a callback to the current tenant context\n *\n * Use this when passing callbacks to setTimeout, event emitters,\n * or other APIs that might lose the async context.\n *\n * @param fn - Function to bind to current context\n * @returns Wrapped function that will run in the original context\n *\n * @example\n * ```typescript\n * // Without bind - context is lost\n * setTimeout(() => {\n * console.log(getTenantId()); // undefined!\n * }, 1000);\n *\n * // With bind - context is preserved\n * setTimeout(TenantContext.bind(() => {\n * console.log(getTenantId()); // 'tenant-123'\n * }), 1000);\n * ```\n */\n bind<T extends (...args: unknown[]) => unknown>(fn: T): T {\n const store = tenantStorage.getStore();\n if (!store) {\n // No context to bind, return function as-is\n return fn;\n }\n\n // Preserve the context (including system context marker)\n return ((...args: unknown[]) => {\n return tenantStorage.run(store, () => fn(...args));\n }) as T;\n },\n\n /**\n * Get the current context data (or undefined for system/no context)\n */\n get current(): TenantContextData | undefined {\n return getCurrentTenant();\n },\n\n /**\n * Check if we're in system context\n */\n get isSystem(): boolean {\n return isSystemContext();\n },\n\n /**\n * Run code with context from a job/message payload\n *\n * Useful for processing queued jobs that include tenant metadata.\n *\n * @param job - Job object with tenantId in metadata\n * @param fn - Function to run in the job's tenant context\n *\n * @example\n * ```typescript\n * const job = await queue.pop();\n * await TenantContext.runWithJobContext(job, async () => {\n * await processJob(job);\n * });\n * ```\n */\n async runWithJobContext<T>(\n job: { metadata?: { tenantId?: string }; tenantId?: string },\n fn: () => Promise<T>,\n ): Promise<T> {\n const tenantId = job.metadata?.tenantId ?? job.tenantId;\n if (!tenantId) {\n throw new TenantContextError(\n 'Job does not contain tenant information. ' +\n 'Ensure jobs include tenantId in metadata or as a top-level field.',\n );\n }\n\n return withTenant({ tenantId }, fn);\n },\n};\n\n/**\n * Error thrown when a tenant context is required but not available.\n *\n * Raised by `requireTenant()`, `requireTenantId()`, and the tenant interceptor\n * when a `@TenantScoped({ mode: 'required' })` operation is attempted outside\n * any `withTenant()` scope.\n *\n * The `code` property is always `'TENANT_CONTEXT_REQUIRED'` and can be used for\n * programmatic error handling.\n *\n * @example\n * ```typescript\n * try {\n * const tenantId = requireTenantId();\n * } catch (err) {\n * if (err instanceof TenantContextError) {\n * // err.code === 'TENANT_CONTEXT_REQUIRED'\n * }\n * }\n * ```\n *\n * @see requireTenant\n * @see requireTenantId\n * @see TenantIsolationError\n */\nexport class TenantContextError extends Error {\n /** Stable error code; always `'TENANT_CONTEXT_REQUIRED'`. */\n readonly code = 'TENANT_CONTEXT_REQUIRED';\n\n constructor(message: string) {\n super(message);\n this.name = 'TenantContextError';\n }\n}\n\n/**\n * Error thrown when a tenant isolation boundary is crossed.\n *\n * Raised by the tenant interceptor when:\n * - A `list()` or `get()` query explicitly filters by a tenant ID that does not\n * match the current context tenant.\n * - A `save()` or `delete()` is attempted on an object whose `tenantId` field\n * belongs to a different tenant than the current context.\n * - A raw SQL query is executed against a tenant-scoped class without an\n * explicit bypass (when `rawQueryPolicy` is `'throw'`).\n *\n * The `code` property is always `'TENANT_ISOLATION_VIOLATION'`.\n *\n * @example\n * ```typescript\n * try {\n * await collection.list({ where: { tenantId: 'other-tenant' } });\n * } catch (err) {\n * if (err instanceof TenantIsolationError) {\n * // err.tenantId — context tenant\n * // err.attemptedTenantId — tenant that was attempted\n * }\n * }\n * ```\n *\n * @see TenantContextError\n * @see createTenantInterceptor\n */\nexport class TenantIsolationError extends Error {\n /** Stable error code; always `'TENANT_ISOLATION_VIOLATION'`. */\n readonly code = 'TENANT_ISOLATION_VIOLATION';\n /** The tenant ID that is active in the current context. */\n readonly tenantId?: string;\n /** The tenant ID that was attempted (and rejected). */\n readonly attemptedTenantId?: string;\n\n constructor(\n message: string,\n details?: { tenantId?: string; attemptedTenantId?: string },\n ) {\n super(message);\n this.name = 'TenantIsolationError';\n this.tenantId = details?.tenantId;\n this.attemptedTenantId = details?.attemptedTenantId;\n }\n}\n"],"mappings":";;AA6FA,IAAM,wBAAwB,uBAAO,IAAI,qBAAqB;AAY9D,IAAM,qBAAqB,uBAAO,IAAI,6BAA6B;AAGnE,SAAS,uBAA6D;CACpE,MAAM,OAAO;CAGb,KAAK,wBAAwB,IAAI,kBAAqC;CACtE,OAAO,KAAK;AACd;AAEA,IAAM,gBAAgB,qBAAqB;AAsBpC,SAAS,mBAAkD;CAChE,MAAM,QAAQ,cAAc,SAAS;CAErC,IAAI,UAAU,uBACZ;CAEF,OAAO;AACT;AAoBO,SAAS,gBAAmC;CACjD,MAAM,MAAM,cAAc,SAAS;CACnC,IAAI,CAAC,OAAO,QAAQ,uBAClB,MAAM,IAAI,mBACR,qGAEF;CAEF,OAAO;AACT;AAmBO,SAAS,kBAA0B;CACxC,OAAO,cAAc,CAAA,CAAE;AACzB;AAsBO,SAAS,cAAkC;CAChD,MAAM,QAAQ,cAAc,SAAS;CACrC,IAAI,UAAU,uBACZ;CAEF,OAAO,OAAO;AAChB;AAoBO,SAAS,mBAA4B;CAC1C,MAAM,QAAQ,cAAc,SAAS;CAErC,OAAO,UAAU,KAAA,KAAa,UAAU;AAC1C;AAeO,SAAS,kBAA2B;CACzC,OAAO,cAAc,SAAS,MAAM;AACtC;AAcO,SAAS,qBAA8B;CAC5C,MAAM,QAAQ,cAAc,SAAS;CACrC,IAAI,UAAU,uBACZ,OAAO;CAET,OAAO,OAAO,qBAAqB;AACrC;AAiBA,eAAsB,WACpB,SACA,IACY;CACZ,MAAM,cAAiC;EACrC,6BAAa,IAAI,IAAI;EACrB,GAAG;CACL;CACA,OAAO,cAAc,IAAI,aAAa,EAAE;AAC1C;AAsBO,SAAS,eACd,SACA,IACG;CACH,MAAM,cAAiC;EACrC,6BAAa,IAAI,IAAI;EACrB,GAAG;CACL;CACA,OAAO,cAAc,IAAI,aAAa,EAAE;AAC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AACF;AA2BO,IAAM,qBAAN,cAAiC,MAAM;;CAEnC,OAAO;CAEhB,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AA8BO,IAAM,uBAAN,cAAmC,MAAM;;CAErC,OAAO;;CAEP;;CAEA;CAET,YACE,SACA,SACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,WAAW,SAAS;EACzB,KAAK,oBAAoB,SAAS;CACpC;AACF"}
@@ -1,5 +1,23 @@
1
1
  import { ObjectRegistry, toSnakeCase } from "@happyvertical/smrt-core";
2
2
  import { createLogger } from "@happyvertical/logger";
3
+ //#region src/enabled-state.ts
4
+ var enabled = false;
5
+ function setTenancyEnabled(value) {
6
+ enabled = value;
7
+ bumpTenantPolicyGeneration();
8
+ }
9
+ function isTenancyEnabled() {
10
+ return enabled;
11
+ }
12
+ var GENERATION_KEY = /* @__PURE__ */ Symbol.for("smrt:tenant-policy-generation");
13
+ function bumpTenantPolicyGeneration() {
14
+ const root = globalThis;
15
+ root[GENERATION_KEY] = (root[GENERATION_KEY] ?? 0) + 1;
16
+ }
17
+ function tenantPolicyGeneration() {
18
+ return globalThis[GENERATION_KEY] ?? 0;
19
+ }
20
+ //#endregion
3
21
  //#region src/registry.ts
4
22
  var logger = createLogger({ level: "info" });
5
23
  var DEFAULT_CONFIG = {
@@ -46,6 +64,7 @@ function registerTenantScopedConstructor(target, config = {}) {
46
64
  };
47
65
  unregisteredDecoratorRegistrations.set(target.name, resolved);
48
66
  tenantScopedClasses.set(target.name, resolved);
67
+ bumpTenantPolicyGeneration();
49
68
  }
50
69
  function registerTenantScopedClass(className, config = {}) {
51
70
  const resolved = {
@@ -53,6 +72,7 @@ function registerTenantScopedClass(className, config = {}) {
53
72
  ...config
54
73
  };
55
74
  tenantScopedClasses.set(className, resolved);
75
+ bumpTenantPolicyGeneration();
56
76
  auditedSelectors.delete(className);
57
77
  if (isQualifiedClassName(className)) {
58
78
  directQualifiedRegistrations.set(className, resolved);
@@ -66,6 +86,7 @@ function registerTenantScopedClass(className, config = {}) {
66
86
  warnOnRegistrationMismatch(className);
67
87
  }
68
88
  function unregisterTenantScopedClass(className) {
89
+ bumpTenantPolicyGeneration();
69
90
  auditedSelectors.delete(className);
70
91
  tenantScopedClasses.delete(className);
71
92
  if (isQualifiedClassName(className)) {
@@ -151,6 +172,7 @@ function getAllTenantScopedClasses() {
151
172
  return new Map(tenantScopedClasses);
152
173
  }
153
174
  function clearTenantScopedRegistry() {
175
+ bumpTenantPolicyGeneration();
154
176
  auditedSelectors.clear();
155
177
  tenantScopedClasses.clear();
156
178
  directSimpleRegistrations.clear();
@@ -234,6 +256,6 @@ function warnOnRegistrationMismatch(selector) {
234
256
  }
235
257
  }
236
258
  //#endregion
237
- export { isTenantScopedClass as a, unregisterTenantScopedClass as c, getTenantScopedConfig as i, clearTenantScopedRegistry as n, registerTenantScopedClass as o, getAllTenantScopedClasses as r, registerTenantScopedConstructor as s, auditTenantScopedRegistrations as t };
259
+ export { isTenantScopedClass as a, unregisterTenantScopedClass as c, tenantPolicyGeneration as d, getTenantScopedConfig as i, isTenancyEnabled as l, clearTenantScopedRegistry as n, registerTenantScopedClass as o, getAllTenantScopedClasses as r, registerTenantScopedConstructor as s, auditTenantScopedRegistrations as t, setTenancyEnabled as u };
238
260
 
239
- //# sourceMappingURL=registry-DH0v5Efm.js.map
261
+ //# sourceMappingURL=registry-DtRl8Jm2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry-DtRl8Jm2.js","names":[],"sources":["../../src/enabled-state.ts","../../src/registry.ts"],"sourcesContent":["/**\n * Shared tenancy-enabled flag.\n *\n * Holds the single boolean toggled by `enableTenancy()` / `disableTenancy()`.\n * It lives in its own leaf module (importing nothing from the package) so that\n * both `interceptor.ts` and `entry-point.ts` can read it without forming a\n * circular import: `interceptor.ts` imports `runTenantScopedEntryPoint` from\n * `entry-point.ts`, and `entry-point.ts` needs the enabled flag — routing the\n * flag through here keeps that dependency one-directional.\n */\n\nlet enabled = false;\n\n/**\n * Set the global tenancy-enabled flag. Internal — called by `enableTenancy()` /\n * `disableTenancy()` in `interceptor.ts`.\n *\n * @param value - `true` to mark tenancy enabled, `false` to clear it.\n */\nexport function setTenancyEnabled(value: boolean): void {\n enabled = value;\n bumpTenantPolicyGeneration();\n}\n\n/**\n * Return `true` if tenant enforcement is currently active.\n *\n * @returns Whether `enableTenancy()` has been called without a later\n * `disableTenancy()`.\n */\nexport function isTenancyEnabled(): boolean {\n return enabled;\n}\n\n// The policy generation (#5195): a counter core reads through the policy\n// source's `generation()` to know that the policies it resolved may be\n// stale. Shared by every copy of this package in the process, like the\n// context storage, through a registered symbol.\nconst GENERATION_KEY = Symbol.for('smrt:tenant-policy-generation');\n\ntype GenerationRoot = typeof globalThis & { [GENERATION_KEY]?: number };\n\n/**\n * Advance the policy generation. Internal: called on every registration or\n * removal of a tenancy policy and on enable and disable.\n */\nexport function bumpTenantPolicyGeneration(): void {\n const root = globalThis as GenerationRoot;\n root[GENERATION_KEY] = (root[GENERATION_KEY] ?? 0) + 1;\n}\n\n/** The current policy generation. Never throws. */\nexport function tenantPolicyGeneration(): number {\n return (globalThis as GenerationRoot)[GENERATION_KEY] ?? 0;\n}\n","/**\n * Tenant-Scoped Class Registry\n *\n * Tracks which classes are tenant-scoped and their configuration.\n * Used by the interceptor to determine how to handle operations.\n *\n * This registry supports two patterns:\n * 1. @TenantScoped() decorator + tenantId field (original pattern)\n * 2. @smrt({ tenantScoped: true }) in smrt-core (Issue #688 pattern)\n *\n * Both patterns are automatically recognized by the interceptor.\n *\n * @see https://github.com/happyvertical/smrt/issues/675\n * @see https://github.com/happyvertical/smrt/issues/688\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport { ObjectRegistry, toSnakeCase } from '@happyvertical/smrt-core';\nimport { bumpTenantPolicyGeneration } from './enabled-state.js';\n\nconst logger = createLogger({ level: 'info' });\n\n/**\n * Resolved tenancy configuration for a single class, as stored in the registry.\n *\n * Every field has a concrete (non-optional) value — defaults are applied by\n * `registerTenantScopedClass()` when the class is registered via `@TenantScoped()`.\n *\n * @see TenantScopedOptions\n * @see registerTenantScopedClass\n */\nexport interface TenantScopedConfig {\n /**\n * Tenancy mode for this class\n * - 'required': Must have tenant context for all operations\n * - 'optional': Works with or without tenant context\n * @default 'required'\n */\n mode: 'required' | 'optional';\n\n /**\n * Field name containing tenant ID\n * @default 'tenantId'\n */\n field: string;\n\n /**\n * Auto-filter all queries by tenant\n * @default true\n */\n autoFilter: boolean;\n\n /**\n * Auto-populate tenant ID from context on create\n * @default true\n */\n autoPopulate: boolean;\n\n /**\n * Allow super admin bypass for this class\n * @default false\n */\n allowSuperAdminBypass: boolean;\n}\n\nconst DEFAULT_CONFIG: TenantScopedConfig = {\n mode: 'required',\n field: 'tenantId',\n autoFilter: true,\n autoPopulate: true,\n allowSuperAdminBypass: false,\n};\n\n// Registry snapshot exposed by getAllTenantScopedClasses().\nconst tenantScopedClasses = new Map<string, TenantScopedConfig>();\n\n// Direct callers select a class by string. Keep simple and qualified selectors\n// separate: a simple selector may be bound only after core proves that exactly\n// one constructor owns that name.\nconst directSimpleRegistrations = new Map<string, TenantScopedConfig>();\nconst directQualifiedRegistrations = new Map<string, TenantScopedConfig>();\nconst directSimpleBindings = new Map<\n string,\n { qualifiedName: string; constructor: Function }\n>();\n\n// Decorators retain a simple mirror only until core has registered their\n// authoritative qualified policy. Qualified runtime resolution always defers\n// to core, preserving manifest and explicit-@smrt precedence.\nconst unregisteredDecoratorRegistrations = new Map<\n string,\n TenantScopedConfig\n>();\n\n// Selectors already audited (and warned about) since their last registration.\nconst auditedSelectors = new Set<string>();\n\nfunction isQualifiedClassName(className: string): boolean {\n return className.includes(':');\n}\n\nfunction isCurrentDirectSimpleBinding(binding: {\n qualifiedName: string;\n constructor: Function;\n}): boolean {\n return (\n ObjectRegistry.getClassByQualifiedName(binding.qualifiedName)\n ?.constructor === binding.constructor\n );\n}\n\nfunction bindDirectSimpleRegistration(className: string): void {\n const config = directSimpleRegistrations.get(className);\n if (!config || directSimpleBindings.has(className)) return;\n\n const matches = ObjectRegistry.findClassesByName(className);\n if (matches.length !== 1 || !matches[0].qualifiedName) return;\n\n directSimpleBindings.set(className, {\n qualifiedName: matches[0].qualifiedName,\n constructor: matches[0].constructor,\n });\n warnOnRegistrationMismatch(className);\n}\n\nfunction getDirectSimpleRegistration(\n className: string,\n): TenantScopedConfig | undefined {\n const config = directSimpleRegistrations.get(className);\n if (!config) return undefined;\n\n const binding = directSimpleBindings.get(className);\n if (binding && !isCurrentDirectSimpleBinding(binding)) {\n throw new Error(\n `Stale tenant-scoped class registration '${className}'; ` +\n 'unregister and register it again for the current constructor.',\n );\n }\n\n const matches = ObjectRegistry.findClassesByName(className);\n if (matches.length > 1) {\n throw new Error(\n `Ambiguous tenant-scoped class registration '${className}'; ` +\n 'register an explicit qualified class name instead.',\n );\n }\n\n return config;\n}\n\n/** @internal Used by TenantScoped; direct callers must use the string API. */\nexport function registerTenantScopedConstructor(\n target: Function,\n config: Partial<TenantScopedConfig> = {},\n): void {\n const resolved = { ...DEFAULT_CONFIG, ...config };\n unregisteredDecoratorRegistrations.set(target.name, resolved);\n tenantScopedClasses.set(target.name, resolved);\n bumpTenantPolicyGeneration();\n}\n\n/**\n * Register a class as tenant-scoped with the given configuration.\n *\n * Call this directly when you cannot use decorators (e.g., third-party classes\n * or plain objects in tests). Defaults from `DEFAULT_CONFIG` are merged over\n * any omitted options. `@TenantScoped()` has its own constructor-aware mirror\n * and reconciles its authoritative policy in core.\n *\n * A simple selector binds to its exact core constructor when one owner is\n * uniquely resolvable, including when registration happens before core. Once\n * bound it remains attached to that constructor if a same-name peer appears.\n * If core clears that constructor and reuses its qualified name, the selector\n * fails closed until the caller explicitly unregisters and re-registers it.\n * If ownership is ambiguous before binding, interception fails closed until a\n * caller registers an explicit qualified selector. Calling this again for the\n * same selector overwrites that selector's previous entry.\n *\n * @param className - A simple class name (e.g., `'Document'`) or exact core\n * qualified name (e.g., `'@package/name:Document'`).\n * @param config - Partial tenancy configuration; omitted fields receive defaults.\n *\n * @example\n * ```typescript\n * // Manually register a class (e.g., for testing)\n * registerTenantScopedClass('Document', { mode: 'optional' });\n * ```\n *\n * @see TenantScoped\n * @see unregisterTenantScopedClass\n */\nexport function registerTenantScopedClass(\n className: string,\n config: Partial<TenantScopedConfig> = {},\n): void {\n const resolved = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n tenantScopedClasses.set(className, resolved);\n bumpTenantPolicyGeneration();\n\n auditedSelectors.delete(className);\n if (isQualifiedClassName(className)) {\n directQualifiedRegistrations.set(className, resolved);\n warnOnRegistrationMismatch(className);\n return;\n }\n\n directSimpleRegistrations.set(className, resolved);\n const existingBinding = directSimpleBindings.get(className);\n if (existingBinding && !isCurrentDirectSimpleBinding(existingBinding)) {\n directSimpleBindings.delete(className);\n }\n bindDirectSimpleRegistration(className);\n warnOnRegistrationMismatch(className);\n}\n\n/**\n * Remove a class from the tenant-scoped registry.\n *\n * Primarily intended for test teardown — use `clearTenantScopedRegistry()` to\n * reset the entire registry at once.\n *\n * @param className - The class name to remove (e.g., `'Document'`).\n *\n * @see clearTenantScopedRegistry\n * @see registerTenantScopedClass\n */\nexport function unregisterTenantScopedClass(className: string): void {\n bumpTenantPolicyGeneration();\n auditedSelectors.delete(className);\n tenantScopedClasses.delete(className);\n if (isQualifiedClassName(className)) {\n directQualifiedRegistrations.delete(className);\n return;\n }\n\n directSimpleRegistrations.delete(className);\n directSimpleBindings.delete(className);\n unregisteredDecoratorRegistrations.delete(className);\n}\n\n/**\n * Return a shallow copy of a config so callers can never mutate the stored\n * registration. The same backing object is shared by the base and every\n * inheriting descendant, so handing out the reference would let an accidental\n * caller mutation silently corrupt the base (and all children). (#1598 review)\n */\nfunction cloneConfig(config: TenantScopedConfig): TenantScopedConfig {\n return { ...config };\n}\n\n/**\n * Resolve a class's OWN tenancy configuration — no STI inheritance, EXACT name\n * match only.\n *\n * Checks the registration mechanisms in order: an explicit direct selector,\n * then core's declared policy. `@TenantScoped()` reconciles its policy in core;\n * its simple-name mirror is used only for unregistered test doubles.\n *\n * Lookups are by exact name only — no simple-name fallback — so a qualified\n * lookup (e.g. `@happyvertical/smrt-affiliates:Payout`, explicitly not scoped)\n * can never strip its namespace and match a same-simple-name scoped class in\n * another package (e.g. `@happyvertical/smrt-commerce:Payout`). (#1598 review)\n */\nfunction getDirectTenantScopedConfig(\n className: string,\n): TenantScopedConfig | undefined {\n const direct = getDeclaredTenantScopedConfig(className);\n const qualifiedName = ObjectRegistry.getClass(className)?.qualifiedName;\n if (\n direct &&\n qualifiedName &&\n ObjectRegistry.getRuntimeOverride(qualifiedName)?.tenancy\n ) {\n return { ...direct, mode: 'required' };\n }\n return direct;\n}\n\nfunction getDeclaredTenantScopedConfig(\n className: string,\n): TenantScopedConfig | undefined {\n // Core marks caught silent-manifest/runtime-decorator conflicts invalid.\n // Check before the simple-name decorator mirror so every identity path\n // fails closed rather than falling through to an unscoped operation.\n ObjectRegistry.assertTenantScopedRegistrationValid(className);\n // 1. Explicit direct qualified selector.\n const directQualified = directQualifiedRegistrations.get(className);\n if (directQualified) {\n // A qualified selector registered before core learned the class is\n // audited on first use instead.\n if (!auditedSelectors.has(className)) warnOnRegistrationMismatch(className);\n return cloneConfig(directQualified);\n }\n\n const registered = isQualifiedClassName(className)\n ? ObjectRegistry.getClassByQualifiedName(className)\n : ObjectRegistry.getClass(className);\n\n // A direct simple selector can bind lazily after registration-before-core.\n // It is never inferred from a qualified name when more than one core class\n // owns that simple name.\n if (registered) {\n const simple = registered.name;\n const bound = directSimpleBindings.get(simple);\n if (bound) {\n if (\n bound.qualifiedName === className &&\n bound.constructor === registered.constructor\n ) {\n return cloneConfig(directSimpleRegistrations.get(simple)!);\n }\n // Core can clear and re-register a qualified name with a different\n // constructor. Never transfer the old selector binding to it: the caller\n // must explicitly unregister/re-register after that lifecycle reset.\n if (!isCurrentDirectSimpleBinding(bound)) {\n throw new Error(\n `Stale tenant-scoped class registration '${simple}'; ` +\n 'unregister and register it again for the current constructor.',\n );\n }\n }\n if (!bound && directSimpleRegistrations.has(simple)) {\n const matches = ObjectRegistry.findClassesByName(simple);\n if (matches.length > 1) {\n throw new Error(\n `Ambiguous tenant-scoped class registration '${simple}'; ` +\n 'register an explicit qualified class name instead.',\n );\n }\n bindDirectSimpleRegistration(simple);\n const rebound = directSimpleBindings.get(simple);\n if (\n rebound?.qualifiedName === className &&\n rebound.constructor === registered.constructor\n ) {\n return cloneConfig(directSimpleRegistrations.get(simple)!);\n }\n }\n }\n\n if (!isQualifiedClassName(className)) {\n // Explicit direct selectors retain their established precedence. For\n // plain-object/test-double paths this is the historical simple-selector\n // fallback, subject to the existing ambiguity checks.\n const directSimple = getDirectSimpleRegistration(className);\n if (directSimple) return cloneConfig(directSimple);\n }\n\n // 2. Core registry (@smrt({ tenantScoped: true }) pattern - Issue #688).\n // findClass() resolves qualified names package-safely, so this branch is\n // already disambiguated.\n const coreConfig = ObjectRegistry.getTenantScopedConfig(className);\n if (coreConfig) {\n // Convert core config to TenantScopedConfig format\n return {\n mode: coreConfig.mode,\n field: coreConfig.field,\n autoFilter: coreConfig.autoFilter,\n autoPopulate: coreConfig.autoPopulate,\n allowSuperAdminBypass: coreConfig.allowSuperAdminBypass,\n };\n }\n\n // A decorator mirror is only authoritative when core has no registration.\n // A registered unqualified consumer still has a canonical simple identity.\n if (!registered && !isQualifiedClassName(className)) {\n const decoratorConfig = unregisteredDecoratorRegistrations.get(className);\n if (decoratorConfig) return cloneConfig(decoratorConfig);\n }\n\n return undefined;\n}\n\n/**\n * Resolve tenancy configuration inherited from an STI/ancestor class.\n *\n * `@TenantScoped` (and `@smrt({ tenantScoped })`) register ONLY the exact class\n * decorated — recognition does NOT propagate to subclasses. Before #1596 this\n * meant an STI child with its own collection (the child is the collection's\n * `_itemClass`) was treated as non-tenant-scoped at runtime: the interceptor\n * skipped tenant filtering on its `list()`/`get()` (cross-tenant reads), skipped\n * tenant population in `beforeSave`, and skipped the raw-SQL policy. Manual\n * re-declaration on every child was the fragile pattern that already bit images\n * (#1407) and messages.\n *\n * We now walk the STI inheritance chain so any descendant of a tenant-scoped\n * base is recognized automatically and inherits the base's config. A subclass\n * of a tenant-scoped class is always itself tenant-scoped — there is no safe\n * reason for it to opt out — so the walk intentionally covers any inheritance\n * (the motivating leak is STI child collections, but this is correct for CTI\n * hierarchies too).\n *\n * Ancestors are walked from nearest-to-self toward the root, returning the\n * first tenant-scoped ancestor's config so a closer ancestor wins. The class's\n * OWN declaration is resolved by the direct lookup in `getTenantScopedConfig`\n * and always takes precedence over anything inherited here.\n */\nfunction getInheritedTenantScopedConfig(\n className: string,\n): TenantScopedConfig | undefined {\n // getInheritanceChain returns [root, ..., self] (qualified names where the\n // class has package context). It is cached by core and only reached here when\n // the direct lookup misses, so the per-call cost on non-tenant classes is a\n // cache hit plus this short loop. Returns [] for unregistered classes.\n const chain = ObjectRegistry.getInheritanceChain(className);\n // chain[length - 1] is the class itself (already covered by the direct\n // lookup); walk its ancestors from nearest to root.\n for (let i = chain.length - 2; i >= 0; i--) {\n const ancestor = chain[i];\n\n // Exact, package-safe match first — covers `@smrt({ tenantScoped })` bases\n // (resolved through the core registry by qualified name) and any class\n // whose @TenantScoped key matches the chain entry verbatim.\n const direct = getDirectTenantScopedConfig(ancestor);\n if (direct) {\n return direct;\n }\n\n // Do not bridge a qualified ancestor back to a simple registration here.\n // The exact lookup above reaches the core declaration reconciled by the\n // decorator. Stripping would let an unrelated same-name peer lend its\n // direct or decorator policy to this inheritance chain.\n }\n return undefined;\n}\n\n/**\n * Retrieve the resolved tenancy configuration for a class.\n *\n * Resolution order:\n * 1. The class's OWN declaration — local `@TenantScoped()` registry first, then\n * the core `@smrt({ tenantScoped: true })` registry.\n * 2. STI inheritance — the nearest tenant-scoped ancestor's config (#1596).\n *\n * A class that declares its own tenancy never reaches step 2, so an explicit\n * child `@TenantScoped` always overrides the inherited base config.\n *\n * @param className - The class name to look up.\n * @returns The `TenantScopedConfig` if the class is tenant-scoped directly or\n * by inheritance, or `undefined` if it is not.\n *\n * @see isTenantScopedClass\n * @see getAllTenantScopedClasses\n */\nexport function getTenantScopedConfig(\n className: string,\n): TenantScopedConfig | undefined {\n // A class's own @TenantScoped / @smrt({ tenantScoped }) declaration wins.\n const direct = getDirectTenantScopedConfig(className);\n if (direct) return direct;\n // Otherwise inherit recognition from a tenant-scoped STI ancestor (#1596).\n return getInheritedTenantScopedConfig(className);\n}\n\n/**\n * Tell core which column records a row's owner for every tenant-scoped class,\n * including runtime registrations on a custom field\n * (`registerTenantScopedClass('Team', { field: 'organizationId' })`) that the\n * manifest knows nothing about. Core's natural-key save guard compares these\n * columns, so a save whose key collides with another organization's row is\n * refused (`TENANT_ISOLATION_VIOLATION`) instead of adopting it. Resolved on\n * every lookup, so selectors that bind later or are unregistered are honoured.\n */\nObjectRegistry.registerOwnershipColumnSource((qualifiedName) => {\n const config = getTenantScopedConfig(qualifiedName);\n return config ? [toSnakeCase(config.field)] : undefined;\n});\n\n/**\n * Return `true` if the named class is tenant-scoped — directly (via\n * `@TenantScoped()` / `@smrt({ tenantScoped: true })`) or by inheriting from a\n * tenant-scoped STI ancestor (#1596).\n *\n * @param className - The class name to look up (e.g., `'Document'`).\n * @returns `true` if the class is tenant-scoped by any mechanism.\n *\n * @see getTenantScopedConfig\n * @see registerTenantScopedClass\n */\nexport function isTenantScopedClass(className: string): boolean {\n return getTenantScopedConfig(className) !== undefined;\n}\n\n/**\n * Return a snapshot of all classes registered via `@TenantScoped()`.\n *\n * Returns a new `Map` so mutations to the returned value do not affect the\n * internal registry. Note that classes registered only through the core\n * `ObjectRegistry` (`@smrt({ tenantScoped: true })`) are **not** included in\n * this map.\n *\n * @returns A copy of the local tenant-scoped class registry, keyed by class name.\n *\n * @see isTenantScopedClass\n * @see getTenantScopedConfig\n */\nexport function getAllTenantScopedClasses(): Map<string, TenantScopedConfig> {\n return new Map(tenantScopedClasses);\n}\n\n/**\n * Remove all entries from the local tenant-scoped class registry.\n *\n * Intended for test teardown via `resetTenancy()`. Does not affect\n * registrations held by the core `ObjectRegistry`.\n *\n * @see resetTenancy\n * @see unregisterTenantScopedClass\n */\nexport function clearTenantScopedRegistry(): void {\n bumpTenantPolicyGeneration();\n auditedSelectors.clear();\n tenantScopedClasses.clear();\n directSimpleRegistrations.clear();\n directQualifiedRegistrations.clear();\n directSimpleBindings.clear();\n unregisteredDecoratorRegistrations.clear();\n}\n\n/**\n * One finding from {@link auditTenantScopedRegistrations}.\n *\n * - `missing_tenant_field` (`error`): the class has no field named by the\n * registration, so the interceptor filters and populates a column that does\n * not exist in the model's manifest/schema.\n * - `natural_key_not_tenant_scoped` (`warning`): the class's upsert conflict\n * target (and so its unique index) omits the tenant column — its natural key\n * is unique ACROSS tenants. The interceptor hides other tenants' rows from\n * lookups, so a second tenant's same-key save collides with a row it cannot\n * see; core refuses that save (`TENANT_ISOLATION_VIOLATION`) instead of\n * overwriting the other tenant's row, but the second tenant still cannot\n * store the key.\n * - `undeclared_tenant_scope` (`info`): tenant scope exists only as this\n * runtime registration; the model's manifest declares no tenancy. Its\n * default natural key is still tenant-led when it has a `tenantId` field,\n * but generated surfaces, knowledge, and schema contracts cannot see the\n * read policy. Declaring `@smrt({ tenantScoped })` makes it visible.\n */\nexport interface TenantRegistrationFinding {\n /** The selector passed to `registerTenantScopedClass()`. */\n selector: string;\n /** The core class it resolved to (qualified name when known). */\n className: string;\n kind:\n | 'missing_tenant_field'\n | 'natural_key_not_tenant_scoped'\n | 'undeclared_tenant_scope';\n severity: 'error' | 'warning' | 'info';\n message: string;\n}\n\nfunction resolveSelectorClass(selector: string) {\n if (isQualifiedClassName(selector)) {\n return ObjectRegistry.getClassByQualifiedName(selector);\n }\n const bound = directSimpleBindings.get(selector);\n if (bound) return ObjectRegistry.getClassByQualifiedName(bound.qualifiedName);\n const matches = ObjectRegistry.findClassesByName(selector);\n return matches.length === 1 ? matches[0] : undefined;\n}\n\ntype RegisteredSmrtClass = NonNullable<ReturnType<typeof resolveSelectorClass>>;\n\n/**\n * Whether the class or one of its registered ancestors declares `fieldName`.\n *\n * A class's own field map holds only its own decorator fields until its\n * manifest entry loads; an STI child registered first (a bundled server) has\n * its inherited tenant field on the registered parent only (#3623). Walk the\n * constructor's prototype chain through public registry lookups — read-only,\n * unlike `getInheritanceChain()`, which caches whatever partial chain exists\n * at registration time.\n */\nfunction declaresFieldInChain(\n registered: RegisteredSmrtClass,\n fieldName: string,\n): boolean {\n if (registered.fields.has(fieldName)) return true;\n if (registered.inheritedFields?.has(fieldName)) return true;\n const visited = new Set<unknown>([registered.constructor]);\n let ctor: unknown = Object.getPrototypeOf(registered.constructor);\n while (typeof ctor === 'function' && !visited.has(ctor)) {\n visited.add(ctor);\n const ancestor = ObjectRegistry.getClassByConstructor(\n ctor as RegisteredSmrtClass['constructor'],\n );\n if (ancestor?.fields.has(fieldName)) return true;\n ctor = Object.getPrototypeOf(ctor);\n }\n return false;\n}\n\nfunction auditSelector(\n selector: string,\n config: TenantScopedConfig,\n): TenantRegistrationFinding[] {\n const registered = resolveSelectorClass(selector);\n if (!registered) return [];\n const className = registered.qualifiedName || registered.name;\n const findings: TenantRegistrationFinding[] = [];\n\n if (!declaresFieldInChain(registered, config.field)) {\n findings.push({\n selector,\n className,\n kind: 'missing_tenant_field',\n severity: 'error',\n message:\n `${className} is registered tenant-scoped on field '${config.field}', ` +\n 'but the model declares no such field. Tenant filtering and population ' +\n 'target a column its manifest and schema do not have. Add the field ' +\n '(or declare `@smrt({ tenantScoped })`) and regenerate the manifest.',\n });\n return findings;\n }\n\n if (!ObjectRegistry.getTenantScopedConfig(className)) {\n findings.push({\n selector,\n className,\n kind: 'undeclared_tenant_scope',\n severity: 'info',\n message:\n `${className} is tenant-scoped only by runtime registration; its ` +\n 'manifest declares no tenancy. Declare `@smrt({ tenantScoped })` so ' +\n 'schema, generated surfaces and knowledge agree with the read policy.',\n });\n }\n\n const tenantColumn = toSnakeCase(config.field);\n const conflictColumns = ObjectRegistry.getConflictColumns(className);\n const keyedOnPrimaryKey =\n conflictColumns.length === 1 && conflictColumns[0] === 'id';\n if (!keyedOnPrimaryKey && !conflictColumns.includes(tenantColumn)) {\n findings.push({\n selector,\n className,\n kind: 'natural_key_not_tenant_scoped',\n severity: 'warning',\n message:\n `${className} is registered tenant-scoped, but its natural key ` +\n `(${conflictColumns.join(', ')}) omits '${tenantColumn}', so it is ` +\n 'unique across tenants: a second tenant cannot store a key another ' +\n 'tenant already uses. A new object saved on such a key is refused ' +\n '(TENANT_ISOLATION_VIOLATION) when the row it collides with has a ' +\n `different '${tenantColumn}'; one whose slug was derived from its ` +\n 'name moves to a free slug instead. ' +\n `Include '${tenantColumn}' in the conflict columns (or drop the ` +\n 'explicit conflictColumns) and run `smrt db:migrate`.',\n });\n }\n return findings;\n}\n\n/**\n * Audit every string-selector registration (`registerTenantScopedClass()`)\n * against the core model it resolves to. Selectors whose class core has not\n * registered yet are skipped (they are audited when they bind).\n *\n * Registration also runs this per selector and logs `error`/`warning`\n * findings once, so a mismatch surfaces at startup; call this directly for a\n * complete report (for example from a health check or a test).\n */\nexport function auditTenantScopedRegistrations(): TenantRegistrationFinding[] {\n const findings: TenantRegistrationFinding[] = [];\n for (const [selector, config] of directQualifiedRegistrations) {\n findings.push(...auditSelector(selector, config));\n }\n for (const [selector, config] of directSimpleRegistrations) {\n findings.push(...auditSelector(selector, config));\n }\n return findings;\n}\n\nfunction warnOnRegistrationMismatch(selector: string): void {\n if (auditedSelectors.has(selector)) return;\n const config =\n directQualifiedRegistrations.get(selector) ??\n directSimpleRegistrations.get(selector);\n if (!config) return;\n let findings: TenantRegistrationFinding[];\n try {\n findings = auditSelector(selector, config);\n } catch {\n // Ambiguous or stale identities fail closed on use; the audit stays quiet.\n return;\n }\n if (!resolveSelectorClass(selector)) return; // not in core yet; retry later\n auditedSelectors.add(selector);\n for (const finding of findings) {\n if (finding.severity === 'info') continue;\n logger.warn(`[smrt-tenancy] ${finding.message}`);\n }\n}\n"],"mappings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