@happyvertical/smrt-app-runtime 0.54.2 → 0.54.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -1
- package/dist/manifest.json +3 -2
- package/dist/smrt-knowledge.json +3 -3
- package/dist/sveltekit/runtime.d.ts.map +1 -1
- package/dist/sveltekit.js +13 -5
- package/dist/sveltekit.js.map +1 -1
- package/package.json +9 -9
package/README.md
CHANGED
|
@@ -75,7 +75,10 @@ checked against its canonical path before descendants or secret bytes are
|
|
|
75
75
|
written. The runtime then acquires SQLite through `@happyvertical/sql`'s
|
|
76
76
|
explicit `node:sqlite` trusted-parent custody boundary, rooted at the mode-0700
|
|
77
77
|
application data directory. Unsupported runtimes or platforms and unsafe
|
|
78
|
-
ownership, permissions, ACLs, or path components fail closed.
|
|
78
|
+
ownership, permissions, ACLs, or path components fail closed. The local
|
|
79
|
+
`runtime.databaseConfig()` and default `runtime.classOptions()` retain that
|
|
80
|
+
same driver, custody, and root configuration when application collections open
|
|
81
|
+
another connection; an explicit per-class database override still wins.
|
|
79
82
|
|
|
80
83
|
The application secret is published by atomically linking a fully written,
|
|
81
84
|
synced mode-0600 temporary file into place. Concurrent installers validate and
|
package/dist/manifest.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"version": "1.0.0",
|
|
3
3
|
"timestamp": 0,
|
|
4
4
|
"packageName": "@happyvertical/smrt-app-runtime",
|
|
5
|
-
"packageVersion": "0.54.
|
|
5
|
+
"packageVersion": "0.54.4",
|
|
6
6
|
"objects": {},
|
|
7
7
|
"moduleType": "smrt",
|
|
8
8
|
"smrtDependencies": [
|
|
@@ -11,5 +11,6 @@
|
|
|
11
11
|
"@happyvertical/smrt-profiles",
|
|
12
12
|
"@happyvertical/smrt-tenancy",
|
|
13
13
|
"@happyvertical/smrt-users"
|
|
14
|
-
]
|
|
14
|
+
],
|
|
15
|
+
"stampsConstructors": true
|
|
15
16
|
}
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,12 +3,12 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-app-runtime",
|
|
6
|
-
"packageVersion": "0.54.
|
|
6
|
+
"packageVersion": "0.54.4",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
10
|
+
"manifest": "169b9de229773ca62235035d8227db7517333adea749a3e14d1912a0b251b6b6",
|
|
11
|
+
"packageJson": "ffe81dbb429d4ce97f11271b00f2f19040c6614b4318c53b73df3b97b68c2820",
|
|
12
12
|
"agents": "f5b360b498cc5c914a13958ebf462791c4793409b98e09ce325a68514bdc1d37"
|
|
13
13
|
},
|
|
14
14
|
"exports": [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../src/sveltekit/runtime.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAEL,KAAK,0BAA0B,EAEhC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAEL,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACnB,KAAK,UAAU,EAChB,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAIL,KAAK,oBAAoB,EAE1B,MAAM,6BAA6B,CAAC;AAarC,OAAO,KAAK,EACV,qBAAqB,EACrB,aAAa,EACd,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,KAAK,iBAAiB,EAAe,MAAM,oBAAoB,CAAC;AACzE,OAAO,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAKxD,OAAO,EACL,KAAK,0BAA0B,EAE/B,oCAAoC,EAGrC,MAAM,wBAAwB,CAAC;AAChC,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;;GAKG;AACH,wBAAgB,cAAc,CAAC,GAAG,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAiBpE"}
|
package/dist/sveltekit.js
CHANGED
|
@@ -296,15 +296,23 @@ function composeSmrtSvelteKitRuntime(options, seams) {
|
|
|
296
296
|
};
|
|
297
297
|
const baseDatabaseConfig = () => {
|
|
298
298
|
const runtime = requireResolved();
|
|
299
|
-
if (runtime.profile === "local")
|
|
300
|
-
|
|
301
|
-
url: resolveLocalRuntimePaths({
|
|
299
|
+
if (runtime.profile === "local") {
|
|
300
|
+
const paths = resolveLocalRuntimePaths({
|
|
302
301
|
appId: applicationId(),
|
|
303
302
|
dataDirectory,
|
|
304
303
|
sourceRoot,
|
|
305
304
|
env
|
|
306
|
-
})
|
|
307
|
-
|
|
305
|
+
});
|
|
306
|
+
return {
|
|
307
|
+
type: "sqlite",
|
|
308
|
+
url: paths.database,
|
|
309
|
+
secureFile: {
|
|
310
|
+
driver: "node:sqlite",
|
|
311
|
+
custody: "trusted-parent",
|
|
312
|
+
root: paths.root
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
}
|
|
308
316
|
const databaseUrl = env.DATABASE_URL;
|
|
309
317
|
if (!databaseUrl) throw new Error(`${runtime.profile} requires DATABASE_URL.`);
|
|
310
318
|
return {
|
package/dist/sveltekit.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sveltekit.js","names":["name","resolved","tenantId"],"sources":["../src/sveltekit/handlers.ts","../src/sveltekit/owner-setup.ts","../src/sveltekit/tenancy.ts","../src/sveltekit/runtime.ts"],"sourcesContent":["/**\n * Mountable runtime routes: liveness health, authorized diagnostics, and the\n * server-owned session summary for the root layout.\n */\n\nimport {\n getRequestScopedDatabase,\n RoleCollection,\n} from '@happyvertical/smrt-users';\nimport { json, type RequestHandler } from '@sveltejs/kit';\nimport type { RuntimeDiagnostics } from '../runtime-diagnostics.js';\nimport type {\n ApplicationRuntimeDiagnosticsOptions,\n SmrtSvelteKitRuntime,\n} from './runtime.js';\n\n/** Explicit permission that grants diagnostics read without the owner role. */\nexport const RUNTIME_DIAGNOSTICS_READ_PERMISSION = 'runtime_diagnostics.read';\n\n/**\n * Mount as `src/routes/api/_runtime/health/+server.ts`:\n * `export const GET = createRuntimeHealthHandler(runtime);`\n *\n * Local responses add the application ID, managed process instance, and the\n * secret-free configuration fingerprint that process managers compare.\n * Deployed responses expose only schema version, status, and profile.\n */\nexport function createRuntimeHealthHandler(\n runtime: Pick<SmrtSvelteKitRuntime, 'health'>,\n): RequestHandler {\n return async () => json(await runtime.health());\n}\n\n/** The locals the diagnostics route authorizes against. */\nexport interface DiagnosticsPrincipalLocals {\n readonly user?: { readonly id?: unknown } | null;\n readonly membership?: {\n readonly userId?: unknown;\n readonly tenantId?: unknown;\n readonly roleId?: unknown;\n isActive?: () => boolean;\n } | null;\n readonly permissions?: readonly string[];\n readonly tenantId?: unknown;\n readonly sessionId?: unknown;\n}\n\ntype DiagnosticsInputValue<T> = T | (() => T);\n\nexport interface RuntimeDiagnosticsHandlerOptions {\n /** Supplies default diagnostics reading and owner-role lookup. */\n readonly runtime?: Pick<\n SmrtSvelteKitRuntime,\n 'readDiagnostics' | 'classOptions'\n >;\n /** Replace the runtime projection (must already be the public allowlist). */\n readonly readDiagnostics?: () => Promise<RuntimeDiagnostics>;\n /** Replace the owner-role lookup. Thrown errors deny. */\n readonly resolveRoleSlug?: (roleId: string) => Promise<string | null>;\n /** Override where the principal comes from. Defaults to `event.locals`. */\n readonly resolveLocals?: (event: {\n readonly locals: unknown;\n }) => DiagnosticsPrincipalLocals;\n /** Public tool inventory (sorted/capped by the projector). */\n readonly toolNames?: DiagnosticsInputValue<readonly string[]>;\n readonly schemaStatus?: DiagnosticsInputValue<\n ApplicationRuntimeDiagnosticsOptions['schemaStatus']\n >;\n readonly migrationStatus?: DiagnosticsInputValue<\n ApplicationRuntimeDiagnosticsOptions['migrationStatus']\n >;\n readonly workerHeartbeatAt?: () => Date | string | null | undefined;\n readonly recentErrors?: () => ApplicationRuntimeDiagnosticsOptions['recentErrors'];\n /** Testable clock. */\n readonly now?: () => Date;\n}\n\nfunction resolveInputValue<T>(\n value: DiagnosticsInputValue<T> | undefined,\n): T | undefined {\n return typeof value === 'function' ? (value as () => T)() : value;\n}\n\n/**\n * Mount as `src/routes/api/_runtime/diagnostics/+server.ts`:\n * `export const GET = createRuntimeDiagnosticsHandler({ runtime });`\n *\n * Authentication and authorization always complete before the private runtime\n * is read. Authorized callers hold `runtime_diagnostics.read` or the `owner`\n * role of their active, session-matching membership. Every failure is a\n * stable `{ schemaVersion: 1, error: { code } }` body.\n */\nexport function createRuntimeDiagnosticsHandler(\n options: RuntimeDiagnosticsHandlerOptions,\n): RequestHandler {\n const runtime = options.runtime;\n const readDiagnostics =\n options.readDiagnostics ??\n (runtime\n ? () =>\n runtime.readDiagnostics({\n toolNames: resolveInputValue(options.toolNames) ?? [],\n observedAt: options.now?.() ?? new Date(),\n schemaStatus: resolveInputValue(options.schemaStatus) ?? 'unknown',\n migrationStatus:\n resolveInputValue(options.migrationStatus) ?? 'unknown',\n workerHeartbeatAt: options.workerHeartbeatAt?.() ?? null,\n recentErrors: options.recentErrors?.() ?? [],\n })\n : undefined);\n const resolveRoleSlug =\n options.resolveRoleSlug ??\n (runtime\n ? async (roleId: string) => {\n const config = runtime.classOptions('Role');\n const requestDb = getRequestScopedDatabase();\n const roles = await RoleCollection.create(\n requestDb\n ? { ...config, db: requestDb as typeof config.db }\n : config,\n );\n return (await roles.findById(roleId))?.slug ?? null;\n }\n : undefined);\n if (!readDiagnostics || !resolveRoleSlug) {\n throw new TypeError(\n 'createRuntimeDiagnosticsHandler requires `runtime`, or both `readDiagnostics` and `resolveRoleSlug`.',\n );\n }\n const resolveLocals =\n options.resolveLocals ??\n ((event: { readonly locals: unknown }) =>\n event.locals as DiagnosticsPrincipalLocals);\n\n return async (event) => {\n const locals = resolveLocals(event);\n const principal = authenticatedPrincipal(locals);\n if (!principal) return stableError(401, 'authentication_required');\n\n let authorized =\n locals.permissions?.includes(RUNTIME_DIAGNOSTICS_READ_PERMISSION) ===\n true;\n if (!authorized) {\n try {\n authorized = (await resolveRoleSlug(principal.roleId)) === 'owner';\n } catch {\n authorized = false;\n }\n }\n if (!authorized) return stableError(403, 'authorization_denied');\n\n try {\n return json(await readDiagnostics());\n } catch {\n return stableError(503, 'diagnostics_unavailable');\n }\n };\n}\n\nfunction authenticatedPrincipal(\n locals: DiagnosticsPrincipalLocals | null | undefined,\n): { roleId: string } | null {\n const userId = locals?.user?.id;\n const tenantId = locals?.tenantId;\n const sessionId = locals?.sessionId;\n const membership = locals?.membership;\n if (\n typeof userId !== 'string' ||\n !userId ||\n typeof tenantId !== 'string' ||\n !tenantId ||\n typeof sessionId !== 'string' ||\n !sessionId ||\n !membership ||\n membership.userId !== userId ||\n membership.tenantId !== tenantId ||\n typeof membership.roleId !== 'string' ||\n !membership.roleId\n ) {\n return null;\n }\n try {\n if (membership.isActive?.() !== true) return null;\n } catch {\n return null;\n }\n return { roleId: membership.roleId };\n}\n\nfunction stableError(status: number, code: string): Response {\n return json({ schemaVersion: 1, error: { code } }, { status });\n}\n\n/** Server-owned session summary for the root layout. */\nexport interface SessionLayoutData {\n readonly session: {\n readonly authenticated: boolean;\n /** Tenant authorized by the active session. */\n readonly activeTenantId: string | null;\n /** URL-selected tenant candidate; display only, never authorization. */\n readonly selectedTenantSlug: string | null;\n };\n}\n\n/**\n * Mount as `src/routes/+layout.server.ts`:\n * `export const load = createSessionLayoutLoad();`\n */\nexport function createSessionLayoutLoad(): (event: {\n readonly locals: unknown;\n}) => SessionLayoutData {\n return ({ locals }) => {\n const value = locals as {\n user?: unknown;\n tenantId?: string | null;\n selectedTenantSlug?: string | null;\n };\n return {\n session: {\n authenticated: Boolean(value.user),\n activeTenantId: value.tenantId ?? null,\n selectedTenantSlug: value.selectedTenantSlug ?? null,\n },\n };\n };\n}\n","/**\n * Server half of the local owner-setup page (`src/routes/setup/+page.server.ts`).\n *\n * Owner bootstrap is local-profile only, loopback-only, and single-use. The\n * runtime stores only an HMAC of the short-lived token; this module never\n * stores, logs, or returns claim errors, and it re-checks loopback custody on\n * every request instead of trusting the bind host alone.\n */\n\nimport type { Cookies } from '@sveltejs/kit';\nimport { type ActionFailure, fail, redirect } from '@sveltejs/kit';\nimport type { LocalOwnerClaimResult } from '../index.js';\nimport { removeOnboardingHandoff } from '../state-root.js';\nimport type { SmrtSvelteKitRuntime } from './runtime.js';\n\n/** Data returned by the setup page `load`. */\nexport interface OwnerSetupPageData {\n /** False when setup is claimed, disabled (deployed), or not loopback. */\n readonly available: boolean;\n /** One-time token from `?token=` (empty unless available). */\n readonly token: string;\n}\n\n/** Stable failure codes returned by the setup action. */\nexport type OwnerSetupErrorCode =\n /** Not the local profile (HTTP 404). */\n | 'setup_disabled'\n /** Request is not from a loopback client on a loopback host (HTTP 403). */\n | 'setup_unavailable'\n /** Missing token, blank name, or email without `@` (HTTP 400). */\n | 'setup_invalid_input'\n /** Token wrong, expired, or already used; owner already claimed (HTTP 400). */\n | 'setup_invalid';\n\n/** `form` data returned with `fail(status, …)`. */\nexport interface OwnerSetupFailure {\n readonly code: OwnerSetupErrorCode;\n /** Fixed, secret-free message; never claim error text. */\n readonly message: string;\n}\n\n/** Form field names posted to the setup action. */\nexport const OWNER_SETUP_FIELDS = Object.freeze({\n token: 'token',\n name: 'name',\n email: 'email',\n tenantName: 'tenantName',\n} as const);\n\nexport const DEFAULT_OWNER_SETUP_MESSAGES: Readonly<\n Record<OwnerSetupErrorCode, string>\n> = Object.freeze({\n setup_disabled: 'Local owner setup is disabled.',\n setup_unavailable: 'Local owner setup is available only from this device.',\n setup_invalid_input: 'Name, email, and a valid setup token are required.',\n setup_invalid:\n 'The setup invitation is invalid, expired, or already used. Run pnpm app:stop, pnpm app:recover, pnpm app:start, then pnpm app:open.',\n});\n\n/** The request fields the setup page reads. */\nexport interface OwnerSetupEvent {\n readonly url: URL;\n readonly locals: unknown;\n getClientAddress(): string;\n}\n\nexport interface OwnerSetupActionEvent extends OwnerSetupEvent {\n readonly request: Request;\n readonly cookies: Pick<Cookies, 'set'>;\n}\n\nexport interface OwnerSetupPageOptions {\n /** Where a signed-in visitor or a successful claim is sent. Default `/`. */\n readonly redirectTo?: string;\n /** Replace fixed failure messages (for example app-specific recovery steps). */\n readonly messages?: Partial<Record<OwnerSetupErrorCode, string>>;\n /** Override where the signed-in user comes from. Defaults to `locals.user`. */\n readonly resolveUser?: (event: OwnerSetupEvent) => unknown;\n /**\n * Set false to keep the `smrt app` onboarding hand-off files after a claim.\n * By default the runtime removes `onboarding.json` and\n * `onboarding-launch.html` from the private state root once the claim has\n * committed, so `pnpm app:open` stops offering the spent invitation.\n */\n readonly removeOnboardingHandoff?: boolean;\n /**\n * Best-effort extra cleanup after a successful claim (the hand-off files are\n * already removed by default). Errors are ignored: the owner and session are\n * already authoritative and a stale token now fails closed.\n */\n readonly onOwnerClaimed?: (\n result: LocalOwnerClaimResult,\n event: OwnerSetupActionEvent,\n ) => void | Promise<void>;\n}\n\nexport interface OwnerSetupPage {\n readonly load: (event: OwnerSetupEvent) => Promise<OwnerSetupPageData>;\n readonly actions: {\n readonly default: (\n event: OwnerSetupActionEvent,\n ) => Promise<ActionFailure<OwnerSetupFailure>>;\n };\n}\n\n/**\n * Mount as `src/routes/setup/+page.server.ts`:\n *\n * ```ts\n * import { createOwnerSetupPage } from '@happyvertical/smrt-app-runtime/sveltekit';\n * import { runtime } from '../../hooks.server';\n *\n * export const { load, actions } = createOwnerSetupPage(runtime);\n * ```\n *\n * The form posts to the `default` action with fields `token` (hidden),\n * `name`, `email`, and optional `tenantName`. Success sets the session cookie\n * and redirects 303; failures return `fail(status, { code, message })`.\n */\nexport function createOwnerSetupPage(\n runtime: Pick<\n SmrtSvelteKitRuntime,\n 'resolvedRuntime' | 'localRuntime' | 'sessionCookie'\n > &\n Partial<Pick<SmrtSvelteKitRuntime, 'applicationStateRoot'>>,\n options: OwnerSetupPageOptions = {},\n): OwnerSetupPage {\n const redirectTo = options.redirectTo ?? '/';\n const messages = { ...DEFAULT_OWNER_SETUP_MESSAGES, ...options.messages };\n const failure = (status: number, code: OwnerSetupErrorCode) =>\n fail(status, { code, message: messages[code] } as OwnerSetupFailure);\n const resolveUser =\n options.resolveUser ??\n ((event: OwnerSetupEvent) => (event.locals as { user?: unknown }).user);\n\n const load = async (event: OwnerSetupEvent): Promise<OwnerSetupPageData> => {\n if (resolveUser(event)) redirect(303, redirectTo);\n const resolved = await runtime.resolvedRuntime();\n if (resolved.profile !== 'local' || !isLoopbackRequest(event)) {\n return { available: false, token: '' };\n }\n const local = await runtime.localRuntime();\n const diagnostics = await local.diagnostics();\n const available = diagnostics.bootstrap.status !== 'claimed';\n return {\n available,\n token: available\n ? event.url.searchParams.get(OWNER_SETUP_FIELDS.token) || ''\n : '',\n };\n };\n\n const claim = async (\n event: OwnerSetupActionEvent,\n ): Promise<ActionFailure<OwnerSetupFailure>> => {\n const resolved = await runtime.resolvedRuntime();\n if (resolved.profile !== 'local') return failure(404, 'setup_disabled');\n if (!isLoopbackRequest(event)) return failure(403, 'setup_unavailable');\n\n let form: FormData;\n try {\n form = await event.request.formData();\n } catch {\n return failure(400, 'setup_invalid_input');\n }\n const field = (name: string) => {\n const value = form.get(name);\n return typeof value === 'string' ? value : '';\n };\n const token = field(OWNER_SETUP_FIELDS.token);\n const name = field(OWNER_SETUP_FIELDS.name);\n const email = field(OWNER_SETUP_FIELDS.email);\n const tenantName = field(OWNER_SETUP_FIELDS.tenantName).trim();\n if (!token || !name.trim() || !email.includes('@')) {\n return failure(400, 'setup_invalid_input');\n }\n\n const local = await runtime.localRuntime();\n let result: LocalOwnerClaimResult;\n try {\n result = await local.claimOwner({\n token,\n name,\n email,\n ...(tenantName ? { tenantName } : {}),\n userAgent: event.request.headers.get('user-agent') || undefined,\n ipAddress: event.getClientAddress(),\n });\n } catch {\n return failure(400, 'setup_invalid');\n }\n\n // claimOwner resolved, so the claim transaction has committed. Clean up\n // before cookie serialization, which can throw on a malformed config.\n if (\n options.removeOnboardingHandoff !== false &&\n runtime.applicationStateRoot\n ) {\n try {\n removeOnboardingHandoff(runtime.applicationStateRoot());\n } catch {\n // Best effort: the spent token already fails closed.\n }\n }\n const cookie = runtime.sessionCookie;\n event.cookies.set(cookie.name, result.sessionId, {\n path: cookie.path,\n ...(cookie.domain ? { domain: cookie.domain } : {}),\n httpOnly: true,\n secure: cookie.secure ?? event.url.protocol === 'https:',\n sameSite: cookie.sameSite,\n maxAge: cookie.maxAgeSeconds,\n });\n try {\n await options.onOwnerClaimed?.(result, event);\n } catch {\n // Best effort only; see OwnerSetupPageOptions.onOwnerClaimed.\n }\n redirect(303, redirectTo);\n };\n\n return Object.freeze({\n load,\n actions: Object.freeze({ default: claim }),\n });\n}\n\n/**\n * True only when both the peer address and the addressed host are loopback.\n * The host check rejects tunnels and DNS-rebinding hosts that forward to a\n * loopback listener; a throwing `getClientAddress` is treated as remote.\n */\nexport function isLoopbackRequest(event: {\n readonly url: URL;\n getClientAddress(): string;\n}): boolean {\n let address: string;\n try {\n address = event.getClientAddress();\n } catch {\n return false;\n }\n return isLoopbackAddress(address) && isLoopbackHostname(event.url.hostname);\n}\n\n/** Loopback IP literal: `127.0.0.0/8`, `::1`, or IPv4-mapped `127/8`. */\nexport function isLoopbackAddress(value: string | null | undefined): boolean {\n if (typeof value !== 'string') return false;\n let host = value\n .trim()\n .toLowerCase()\n .replace(/^\\[|\\]$/g, '');\n if (host === '::1' || host === '0:0:0:0:0:0:0:1') return true;\n if (host.startsWith('::ffff:')) host = host.slice('::ffff:'.length);\n const octets = host.split('.');\n return (\n octets.length === 4 &&\n octets.every((part) => /^\\d{1,3}$/.test(part) && Number(part) <= 255) &&\n Number(octets[0]) === 127\n );\n}\n\n/** Loopback host name as SvelteKit reports it in `url.hostname`. */\nexport function isLoopbackHostname(hostname: string): boolean {\n const host = hostname.trim().toLowerCase().replace(/\\.$/, '');\n return host === 'localhost' || isLoopbackAddress(host);\n}\n","/**\n * Tenant *selection* for SvelteKit requests.\n *\n * Selection and authorization are deliberately separate:\n *\n * - a selector maps a trusted URL shape (by default the leading subdomain) to\n * an active tenant record and publishes it as `locals.selectedTenant*`;\n * - the signed session (`createSessionHandler({ enterTenantContext: true })`)\n * authorizes the signed-in user's membership and establishes the request\n * tenant context.\n *\n * A selected tenant is useful for login and membership-gated switch flows, but\n * it never becomes ambient query authority by itself. The default selector\n * ignores client-provided tenant headers.\n */\n\nimport type { SmrtClassOptions } from '@happyvertical/smrt-core';\nimport { TenantCollection, TenantStatus } from '@happyvertical/smrt-users';\n\n/** The request fields a tenant selector may read. */\nexport interface TenantSelectionEvent {\n readonly url: URL;\n readonly request: { readonly headers: Headers };\n}\n\n/** URL-derived tenant candidate. Never authorization. */\nexport interface TenantSelection {\n /** Database ID for an active tenant, or null when none resolves. */\n readonly tenantId: string | null;\n /** URL-derived slug. Informational until membership authorizes a switch. */\n readonly tenantSlug: string | null;\n}\n\n/**\n * Replaceable selection extension point. Implementations must preserve the\n * rule that selection alone never establishes authorization context.\n */\nexport type TenantSelector = (\n event: TenantSelectionEvent,\n) => TenantSelection | Promise<TenantSelection>;\n\nconst ROOT_LIKE_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);\nconst RESERVED_SUBDOMAINS = new Set(['www', 'api', 'app', 'admin']);\nconst NO_SELECTION: TenantSelection = Object.freeze({\n tenantId: null,\n tenantSlug: null,\n});\n\n/**\n * Pure URL parser used by the default selector.\n *\n * Set `TENANT_BASE_DOMAIN` (or pass `baseDomain`) in production so\n * multi-label public suffixes are never guessed. Without it, the fallback is\n * intended only for local domains such as `acme.demo.local`.\n */\nexport function selectTenantSlug(\n url: URL,\n baseDomain: string | undefined = process.env.TENANT_BASE_DOMAIN,\n): string | null {\n const hostname = url.hostname.toLowerCase();\n if (\n ROOT_LIKE_HOSTS.has(hostname) ||\n hostname.startsWith('[') ||\n /^\\d{1,3}(\\.\\d{1,3}){3}$/.test(hostname)\n ) {\n return null;\n }\n\n const normalizedBase = baseDomain\n ?.trim()\n .toLowerCase()\n .replace(/^\\.+|\\.+$/g, '');\n\n let candidate: string | undefined;\n if (normalizedBase) {\n if (hostname === normalizedBase) return null;\n const suffix = `.${normalizedBase}`;\n if (!hostname.endsWith(suffix)) return null;\n candidate = hostname.slice(0, -suffix.length).split('.')[0];\n } else {\n const labels = hostname.split('.');\n if (labels.length < 3) return null;\n candidate = labels[0];\n }\n\n return candidate && !RESERVED_SUBDOMAINS.has(candidate) ? candidate : null;\n}\n\nfunction isMissingTenantTable(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n const code = (error as Error & { code?: string }).code;\n return (\n code === '42P01' ||\n error.message.includes('relation \"tenants\" does not exist') ||\n error.message.includes('no such table: tenants')\n );\n}\n\nexport interface SubdomainTenantSelectorOptions {\n /** Explicit public base domain. Defaults to `TENANT_BASE_DOMAIN`. */\n readonly baseDomain?: string;\n /** Collection options for the `Tenant` lookup. */\n readonly classOptions: () => SmrtClassOptions;\n}\n\n/**\n * Default selector: the leading subdomain names an ACTIVE tenant.\n *\n * A missing `tenants` table (a fresh project before its first migration)\n * yields no selection; the runtime never creates that table.\n */\nexport function createSubdomainTenantSelector(\n options: SubdomainTenantSelectorOptions,\n): TenantSelector {\n return async (event) => {\n const tenantSlug = selectTenantSlug(event.url, options.baseDomain);\n if (!tenantSlug) return NO_SELECTION;\n let tenantId: string | null;\n try {\n const tenants = await TenantCollection.create(options.classOptions());\n const tenant = await tenants.findBySlug(tenantSlug);\n tenantId =\n tenant?.status === TenantStatus.ACTIVE ? (tenant.id ?? null) : null;\n } catch (error) {\n if (!isMissingTenantTable(error)) throw error;\n tenantId = null;\n }\n return { tenantId, tenantSlug };\n };\n}\n\n/** Coerce an application selector's result into the published shape. */\nexport function normalizeTenantSelection(\n selection: TenantSelection | null | undefined,\n): TenantSelection {\n const tenantId =\n typeof selection?.tenantId === 'string' && selection.tenantId\n ? selection.tenantId\n : null;\n const tenantSlug =\n typeof selection?.tenantSlug === 'string' && selection.tenantSlug\n ? selection.tenantSlug\n : null;\n return { tenantId, tenantSlug };\n}\n","/**\n * SvelteKit server composition for the validated runtime profiles.\n *\n * Request foundation, in order:\n *\n * 0. Wait for the fail-closed runtime startup gate (`init`).\n * 1. Resolve a URL tenant candidate into `locals.selectedTenant*`. This is\n * selection only and never enters AsyncLocalStorage tenant context.\n * 2. Load the signed session. Its tenant is accepted only for a verified\n * active direct or legitimately inherited membership\n * ({@link isSessionTenantAuthorized}, the deployed runtime's rule);\n * otherwise the request is unauthenticated. An accepted session enters the\n * tenant context and permission set for downstream code, inside the\n * request RLS transaction when the profile selects `database-rls`.\n * 3. Publish the authorized context on `locals.tenantContext` only when it\n * matches the verified session tenant.\n *\n * This ordering prevents a spoofed header or hostname from becoming query\n * authority. Membership-gated tenant switching belongs in an explicit action\n * using `switchSessionTenant()` from `@happyvertical/smrt-users/sveltekit`.\n */\n\nimport {\n loadConfig,\n type ResolvedApplicationRuntime,\n resolveEffectiveApplicationRuntime,\n} from '@happyvertical/smrt-config';\nimport {\n ObjectRegistry,\n type SmrtClassOptions,\n type SmrtCollection,\n type SmrtObject,\n} from '@happyvertical/smrt-core';\nimport { OidcIdentityCollection } from '@happyvertical/smrt-profiles';\nimport {\n enableTenancy,\n getCurrentTenant,\n isTenancyEnabled,\n type MinimalTenantContext,\n withSystemContext,\n} from '@happyvertical/smrt-tenancy';\nimport {\n getCurrentSessionPermissionContext,\n getRequestScopedDatabase,\n MembershipCollection,\n PermissionResolver,\n SessionService,\n type SessionServiceOptions,\n UserCollection,\n UserStatus,\n withPrincipalPermissionContext,\n withSessionPermissionContext,\n} from '@happyvertical/smrt-users';\nimport type {\n SessionHandlerOptions,\n SessionLocals,\n} from '@happyvertical/smrt-users/sveltekit';\nimport { type DatabaseInterface, getDatabase } from '@happyvertical/sql';\nimport type { Handle, ServerInit } from '@sveltejs/kit';\nimport {\n resolveApplicationId,\n runtimeConfigurationFingerprint,\n} from '../application-identity.js';\nimport {\n type DeployedApplicationRuntime,\n type DeployedApplicationRuntimeProfile,\n initializeDeployedApplicationRuntime,\n isSessionTenantAuthorized,\n type PublicAuthenticationProvider,\n} from '../deployed-runtime.js';\nimport {\n resolveBoundMembershipPermissions,\n type TenantBindingMode,\n} from '../direct-membership.js';\nimport {\n initializeLocalApplicationRuntime,\n isLocalMcpTokenPrincipal,\n type LocalApplicationRuntime,\n type LocalMcpTokenPrincipal,\n type LocalOwnerBootstrapInvitation,\n resolveLocalRuntimePaths,\n validateApplicationId,\n} from '../index.js';\nimport {\n deepFrozenPlainCopy,\n ownValue,\n PlainDataError,\n} from '../plain-data.js';\nimport {\n projectRuntimeDiagnostics,\n type RuntimeDiagnostics,\n type RuntimeDiagnosticsProjectionInput,\n} from '../runtime-diagnostics.js';\nimport {\n prepareApplicationStateRoot,\n resolveApplicationStateRoot,\n} from '../state-root.js';\nimport { acquireWriterLease, type WriterLease } from '../writer-lease.js';\nimport {\n createSubdomainTenantSelector,\n normalizeTenantSelection,\n type TenantSelector,\n} from './tenancy.js';\n\n/** `App.Locals` fields populated by the SMRT runtime `handle`. */\nexport interface SmrtRuntimeLocals extends SessionLocals {\n /**\n * URL-selected tenant candidate. Never use this as authorization; the\n * session-authorized tenant remains `tenantId` from {@link SessionLocals}.\n */\n selectedTenantId: string | null;\n selectedTenantSlug: string | null;\n /** Full context for the authorized session tenant, when present. */\n tenantContext?: MinimalTenantContext;\n}\n\n/** Provider component whose readiness a deployed web process must prove. */\nexport type ProviderReadinessComponent =\n | 'authentication'\n | 'assets'\n | 'secrets';\n\n/**\n * Build a provider-owned readiness probe. The probe must check the real\n * backing service and must never return or log credentials.\n */\nexport type ProviderReadinessFactory = (\n component: ProviderReadinessComponent,\n context: { readonly profile: string; readonly provider: string },\n) => () => Promise<void>;\n\n/** Context handed to an application-owned writer lease. */\nexport interface WriterLeaseContext {\n readonly appId: string;\n readonly dataDirectory: string | undefined;\n readonly sourceRoot: string;\n}\n\n/**\n * Held for the life of the local web process; released on failed startup.\n * The root entry's `acquireWriterLease()` returns one.\n */\nexport type { WriterLease } from '../writer-lease.js';\n\n/** Inputs to the public diagnostics projection that only the app can supply. */\nexport interface ApplicationRuntimeDiagnosticsOptions {\n readonly toolNames: readonly string[];\n readonly observedAt: Date;\n /** Application-owned schema verification seam; runtime liveness is not proof. */\n readonly schemaStatus?: 'not-ready' | 'ready' | 'unknown';\n /** Application-owned migration tracker seam; database liveness is not proof. */\n readonly migrationStatus?: 'current' | 'failed' | 'pending' | 'unknown';\n /** Bounded worker seam supplied by the deployment's lease/heartbeat adapter. */\n readonly workerHeartbeatAt?: Date | string | null;\n /** Stable code/timestamp pairs only; raw errors never cross this seam. */\n readonly recentErrors?: readonly {\n readonly code?: unknown;\n readonly at?: unknown;\n }[];\n}\n\n/** Liveness body served by the mounted health route. */\nexport interface RuntimeHealthBody {\n readonly schemaVersion: 1;\n readonly status: 'ready';\n readonly profile: ResolvedApplicationRuntime['profile'];\n /** Local profile only: canonical application ID. */\n readonly application?: string;\n /** Local profile only: managed process instance (`SMRT_PROCESS_INSTANCE`). */\n readonly instance?: string | null;\n /** Local profile only: {@link runtimeConfigurationFingerprint}. */\n readonly configuration?: string;\n}\n\n/** Session-handler options the application may tune. */\nexport type SmrtRuntimeSessionOptions = Omit<\n SessionHandlerOptions,\n 'enterTenantContext'\n>;\n\n/** App-specific options for {@link createSmrtSvelteKitRuntime}. */\nexport interface SmrtSvelteKitRuntimeOptions {\n /**\n * Explicit application ID. Defaults to `SMRT_APP_ID` (strictly validated)\n * or the encoded `package.json` name under `sourceRoot`.\n */\n readonly appId?: string;\n /** Application source checkout. Defaults to `process.cwd()`. */\n readonly sourceRoot?: string;\n /** Local data root. Defaults to `SMRT_DATA_DIR`, then the OS data directory. */\n readonly dataDirectory?: string;\n /** Environment to read. Defaults to `process.env`. */\n readonly env?: NodeJS.ProcessEnv;\n /**\n * Resolved runtime profile. Defaults to `smrt.config` `runtime` when\n * present, otherwise the `local` profile; a present value that is not a\n * runtime block (`null`, `false`, `0`, `''`) fails closed.\n */\n readonly runtime?:\n | ResolvedApplicationRuntime\n | (() => ResolvedApplicationRuntime | Promise<ResolvedApplicationRuntime>);\n /**\n * Explicit, idempotent application migration hook, run during `init`.\n * The runtime never synthesizes application tables itself.\n */\n readonly prepareDatabase?: (db: DatabaseInterface) => Promise<void>;\n /**\n * Local HTTP bind host. Defaults to `HOST`, or `127.0.0.1` when\n * `NODE_ENV=development`. Local production startup without one fails.\n */\n readonly bindHost?: string;\n /** Opt in to persisted local background jobs. Default `SMRT_BACKGROUND_JOBS === 'true'`. */\n readonly backgroundJobs?: boolean;\n /** Opt in to application-defined paid capabilities. Default false. */\n readonly paidCapabilities?: boolean;\n /** Owner-bootstrap token lifetime (1..900 seconds). */\n readonly bootstrapTtlSeconds?: number;\n /** Session lifetime for the owner-bootstrap session cookie. Default 7 days. */\n readonly sessionTtlSeconds?: number;\n /**\n * Local single-writer lease held for the web process, released when local\n * startup fails. Defaults to the state-root writer lease shared with\n * `smrt app` operations ({@link defaultWriterLease}: `writer.lease` under\n * `prepareApplicationStateRoot()`, presenting `SMRT_OPERATION_INSTANCE`).\n * Pass a factory to replace it, or `false` to hold no lease. Deployed\n * profiles never take it.\n */\n readonly acquireWriterLease?:\n | ((context: WriterLeaseContext) => WriterLease)\n | false;\n /**\n * Deployed provider readiness probes. Required by `self-hosted` and `cloud`;\n * deployed startup fails closed without them.\n */\n readonly providerReadiness?: ProviderReadinessFactory;\n /** Replace the default subdomain tenant selector. Selection only. */\n readonly selectTenant?: TenantSelector;\n /** Base domain for the default selector. Defaults to `TENANT_BASE_DOMAIN`. */\n readonly tenantBaseDomain?: string;\n /** Session handler tuning. `enterTenantContext` is always `true`. */\n readonly session?: SmrtRuntimeSessionOptions;\n /** Per-class overrides layered over the runtime database config. */\n readonly classOverrides?: Readonly<Record<string, Partial<SmrtClassOptions>>>;\n /** Call `enableTenancy()` if it is not already enabled. Default true. */\n readonly enableTenancy?: boolean;\n /**\n * Receives an owner-bootstrap invitation that this process's startup newly\n * issued (the plaintext is returned exactly once; only its HMAC is stored).\n * Use it to show a loopback `/setup?token=` URL. Errors are ignored so a\n * failing presenter never blocks startup. Default: not presented.\n */\n readonly onBootstrapInvitation?: (\n invitation: LocalOwnerBootstrapInvitation,\n context: { readonly bindHost: string },\n ) => void;\n /** Testable clock for the local runtime. */\n readonly now?: () => Date;\n}\n\n/** Cookie attributes for a session established outside the session handler. */\nexport interface SmrtRuntimeSessionCookie {\n readonly name: string;\n readonly path: string;\n readonly domain?: string;\n readonly sameSite: 'strict' | 'lax' | 'none';\n /** `undefined` means \"secure when the request is HTTPS\". */\n readonly secure?: boolean;\n readonly maxAgeSeconds: number;\n}\n\nexport type { TenantBindingMode } from '../direct-membership.js';\n\n/** The composed runtime; `handle` and `init` are bound and destructurable. */\n/** A principal a route authenticated itself, for {@link SmrtSvelteKitRuntime.runAsPrincipal}. */\nexport interface SmrtRuntimeBoundPrincipal {\n readonly id: string;\n readonly tenantId?: string | null;\n /** Granted scopes that cap the live permission set (e.g. token scopes). */\n readonly scopes?: readonly string[];\n /**\n * How tenant authority may be established, set by the authenticating\n * adapter (never request input). `direct` (local owner tokens, the default\n * hosted resolver) needs an active direct membership in exactly\n * `tenantId`. `direct-or-inherited` (the default; hosted application-owned\n * mappings) applies the session step's rule: that direct row, or with no\n * direct row, authority inherited from an active inheritable ancestor.\n */\n readonly tenantBinding?: TenantBindingMode;\n}\n\n/** A verified hosted access-token identity (see `McpVerifiedIdentity`). */\nexport interface SmrtRuntimeMcpIdentity {\n /** Exact issuer the token was verified against. */\n readonly issuer: string;\n /** Verified `sub` claim. */\n readonly subject: string;\n}\n\n/** The current account and tenant a hosted MCP identity maps to. */\nexport interface SmrtRuntimeMcpPrincipalMapping {\n readonly id: string;\n readonly tenantId: string;\n readonly kind: 'human';\n /** The default resolver maps only direct memberships. */\n readonly tenantBinding: 'direct';\n}\n\n/** `T` with every nested array and object field readonly. */\nexport type SmrtRuntimeDeepReadonly<T> = T extends readonly (infer U)[]\n ? readonly SmrtRuntimeDeepReadonly<U>[]\n : T extends object\n ? { readonly [K in keyof T]: SmrtRuntimeDeepReadonly<T[K]> }\n : T;\n\n/**\n * The frozen principal `runAsPrincipal` hands its callback: a deep, frozen\n * snapshot of the caller's principal taken before any await, with the\n * effective `tenantBinding` and effective (frozen) `scopes`.\n */\nexport type SmrtRuntimeBoundPrincipalSnapshot<P> = SmrtRuntimeDeepReadonly<\n Omit<P, 'scopes' | 'tenantBinding'>\n> & {\n readonly scopes: readonly string[];\n readonly tenantBinding: TenantBindingMode;\n};\n\nexport interface SmrtSvelteKitRuntime {\n /** `hooks.server.ts` `handle`. */\n readonly handle: Handle;\n /** `hooks.server.ts` `init`: the fail-closed startup gate. */\n readonly init: ServerInit;\n /** Session cookie attributes shared with owner setup. */\n readonly sessionCookie: SmrtRuntimeSessionCookie;\n /** Resolve the runtime profile (memoized; retried after failure). */\n resolvedRuntime(): Promise<ResolvedApplicationRuntime>;\n /** Await profile-specific startup (same promise as `init`). */\n ready(): Promise<void>;\n /** Canonical application ID. */\n applicationId(): string;\n /**\n * Private state root shared with the `smrt app` operator commands (writer\n * lease, operation lock, onboarding hand-off files). Resolves the path only;\n * it does not create it.\n */\n applicationStateRoot(): string;\n /** Secret-free configuration fingerprint. Requires a resolved runtime. */\n configurationFingerprint(): string;\n /**\n * Database for SMRT collections. Requires a resolved runtime. Inside a\n * request running in the RLS transaction (`database-rls` isolation, or\n * `session.postgresRls`) this is the transaction-bound request database;\n * otherwise the base configuration. Call it per request and never retain\n * the result (or collections built from it) beyond that request.\n */\n databaseConfig(): SmrtClassOptions['db'];\n /**\n * Collection options for a class: {@link databaseConfig} plus\n * `classOverrides`. A class whose override sets `db` keeps that database.\n * Same per-request rule as {@link databaseConfig}.\n */\n classOptions(className: string): SmrtClassOptions;\n /**\n * The registered collection for a class, built from {@link classOptions}\n * evaluated on this call: inside an RLS request it is bound to the request\n * transaction. Generated API routes resolve collections through it. Call it\n * per request and never retain the result beyond that request.\n */\n getCollection<T extends SmrtObject = SmrtObject>(\n className: string,\n ): Promise<SmrtCollection<T>>;\n /**\n * Run `fn` as a principal the route verified itself (for example a bearer\n * token mapped by an MCP route), replacing the cookie session's permission\n * context for that call. The principal's permissions are resolved live from\n * its membership in `tenantId` and, when `scopes` is given, capped to it;\n * under the RLS transaction rule of {@link databaseConfig} a fresh\n * transaction publishes that user, tenant and permission set, and\n * `databaseConfig()`/`classOptions()` return it inside `fn`. Rejects (before\n * `fn` runs) without a user id, a tenant, or a membership its\n * `tenantBinding` accepts: `direct` needs an active direct membership in\n * exactly that tenant; `direct-or-inherited` (default) also accepts\n * authority inherited from an active inheritable ancestor when no direct\n * row exists. A suspended or pending direct row is always authoritative.\n *\n * `principal` is read once, before any await: `fn` receives a frozen copy\n * of that snapshot (its effective `tenantBinding`, and `scopes` replaced by\n * the effective, frozen permission set: live permissions capped by the\n * given scopes), never the caller's object. Callers\n * that authorize in code (rather than through database policy, as under\n * `application` isolation) must authorize with these effective scopes so a\n * revoked permission takes effect even while a token still carries it.\n */\n runAsPrincipal<\n T,\n P extends SmrtRuntimeBoundPrincipal = SmrtRuntimeBoundPrincipal,\n >(\n principal: P,\n fn: (bound: SmrtRuntimeBoundPrincipalSnapshot<P>) => Promise<T>,\n ): Promise<T>;\n /**\n * Verify an owner-minted local MCP token (`smrt app token`). Resolves the\n * token's owner principal with its scopes capped to the owner's live\n * permissions, or `null` for anything else: a malformed, unknown, revoked\n * or expired token, an inactive owner or membership, or any non-`local`\n * profile. Pass the runtime as `createHostedMcpResourceAuth({ runtime })`\n * so `/mcp` accepts these tokens in the local profile.\n */\n verifyLocalMcpToken(token: string): Promise<LocalMcpTokenPrincipal | null>;\n /**\n * Default membership-backed hosted MCP principal mapping: the verified\n * issuer/subject must be linked (`oidc_identities`) to exactly one active\n * user with exactly one active direct tenant membership. Anything else\n * (unlinked, ambiguous, inactive, several tenants, the `local` profile)\n * resolves `null`, which denies the request. Token claims never select the\n * tenant. Applications with multi-tenant users pass their own\n * `resolvePrincipal`, which takes precedence.\n */\n resolveMcpPrincipal(\n identity: SmrtRuntimeMcpIdentity,\n ): Promise<SmrtRuntimeMcpPrincipalMapping | null>;\n /** The local runtime. Rejects outside the `local` profile. */\n localRuntime(): Promise<LocalApplicationRuntime>;\n /** The deployed runtime. Rejects in the `local` profile. */\n deployedRuntime(): Promise<DeployedApplicationRuntime>;\n /** Liveness body for the health route (awaits startup). */\n health(): Promise<RuntimeHealthBody>;\n /**\n * Read private runtime state and project it onto the public allowlist.\n * Call only after the route has authenticated and authorized its caller.\n */\n readDiagnostics(\n options: ApplicationRuntimeDiagnosticsOptions,\n ): Promise<RuntimeDiagnostics>;\n}\n\n/** @internal Test and composition seams; not part of the public entry. */\nexport interface SmrtSvelteKitRuntimeSeams {\n readonly initializeLocal?: typeof initializeLocalApplicationRuntime;\n readonly initializeDeployed?: typeof initializeDeployedApplicationRuntime;\n readonly loadRuntime?: () => Promise<ResolvedApplicationRuntime>;\n}\n\nconst DEFAULT_SESSION_TTL_SECONDS = 7 * 24 * 60 * 60;\n\n/**\n * Compose runtime startup, tenant selection, the signed session, and\n * authorized-tenant locals into a SvelteKit `{ handle, init }` pair.\n *\n * @example\n * ```ts\n * // src/hooks.server.ts\n * import { createSmrtSvelteKitRuntime } from '@happyvertical/smrt-app-runtime/sveltekit';\n *\n * export const runtime = createSmrtSvelteKitRuntime();\n * export const { handle, init } = runtime;\n * ```\n */\nexport function createSmrtSvelteKitRuntime(\n options: SmrtSvelteKitRuntimeOptions = {},\n): SmrtSvelteKitRuntime {\n return composeSmrtSvelteKitRuntime(options, {});\n}\n\n/** @internal */\nexport function composeSmrtSvelteKitRuntime(\n options: SmrtSvelteKitRuntimeOptions,\n seams: SmrtSvelteKitRuntimeSeams,\n): SmrtSvelteKitRuntime {\n const env = options.env ?? process.env;\n const sourceRoot = options.sourceRoot ?? process.cwd();\n const dataDirectory = options.dataDirectory ?? env.SMRT_DATA_DIR;\n const initializeLocal =\n seams.initializeLocal ?? initializeLocalApplicationRuntime;\n const initializeDeployed =\n seams.initializeDeployed ?? initializeDeployedApplicationRuntime;\n\n if (options.enableTenancy !== false && !isTenancyEnabled()) {\n enableTenancy();\n }\n\n let appId: string | undefined;\n const applicationId = (): string => {\n appId ??= options.appId\n ? validateApplicationId(options.appId)\n : resolveApplicationId({ sourceRoot, explicitId: env.SMRT_APP_ID });\n return appId;\n };\n\n let resolved: ResolvedApplicationRuntime | undefined;\n let resolvedPromise: Promise<ResolvedApplicationRuntime> | undefined;\n const resolvedRuntime = (): Promise<ResolvedApplicationRuntime> => {\n resolvedPromise ??= (async () => {\n const value =\n typeof options.runtime === 'function'\n ? await options.runtime()\n : (options.runtime ??\n (await (seams.loadRuntime ?? loadConfiguredRuntime)()));\n resolved = value;\n return value;\n })().catch((error: unknown) => {\n resolvedPromise = undefined;\n throw error;\n });\n return resolvedPromise;\n };\n\n const requireResolved = (): ResolvedApplicationRuntime => {\n if (!resolved) {\n throw new Error(\n 'The SMRT application runtime is not resolved yet; await init() first.',\n );\n }\n return resolved;\n };\n\n /** Base (connection-level) database config; never request-scoped. */\n const baseDatabaseConfig = (): SmrtClassOptions['db'] => {\n const runtime = requireResolved();\n if (runtime.profile === 'local') {\n const paths = resolveLocalRuntimePaths({\n appId: applicationId(),\n dataDirectory,\n sourceRoot,\n env,\n });\n return { type: 'sqlite', url: paths.database };\n }\n const databaseUrl = env.DATABASE_URL;\n if (!databaseUrl) {\n throw new Error(`${runtime.profile} requires DATABASE_URL.`);\n }\n return { type: 'postgres', url: databaseUrl };\n };\n\n /** Base collection options; used for anything that outlives a request. */\n const baseClassOptions = (className: string): SmrtClassOptions => {\n const defaults: SmrtClassOptions = { db: baseDatabaseConfig() };\n const override = options.classOverrides?.[className];\n return override ? { ...defaults, ...override } : defaults;\n };\n\n /**\n * Inside a request running in the RLS transaction, the transaction-bound\n * request database (it carries the `smrt.*` session variables); otherwise\n * undefined. Never cache the returned handle beyond the request.\n */\n const rlsRequestDatabase = (): SmrtClassOptions['db'] | undefined => {\n const context = getCurrentSessionPermissionContext();\n if (context?.postgresRls !== true) return undefined;\n return (getRequestScopedDatabase() ?? undefined) as\n | SmrtClassOptions['db']\n | undefined;\n };\n\n const databaseConfig = (): SmrtClassOptions['db'] =>\n rlsRequestDatabase() ?? baseDatabaseConfig();\n\n const classOptions = (className: string): SmrtClassOptions => {\n const base = baseClassOptions(className);\n if (options.classOverrides?.[className]?.db !== undefined) return base;\n const requestDb = rlsRequestDatabase();\n return requestDb ? { ...base, db: requestDb } : base;\n };\n\n const getCollection = <T extends SmrtObject = SmrtObject>(\n className: string,\n ): Promise<SmrtCollection<T>> =>\n ObjectRegistry.getCollection<T>(className, classOptions(className));\n\n const writerLease =\n options.acquireWriterLease === false\n ? undefined\n : (options.acquireWriterLease ??\n ((context: WriterLeaseContext) => defaultWriterLease(context, env)));\n\n let localPromise: Promise<LocalApplicationRuntime> | undefined;\n let localLease: WriterLease | undefined;\n const localRuntime = async (): Promise<LocalApplicationRuntime> => {\n const runtime = await resolvedRuntime();\n if (runtime.profile !== 'local') {\n throw new Error(\n 'Owner bootstrap is available only in the local profile.',\n );\n }\n if (localPromise) return localPromise;\n const bindHost =\n options.bindHost ||\n env.HOST ||\n (env.NODE_ENV === 'development' ? '127.0.0.1' : null);\n if (!bindHost) {\n throw new Error(\n 'Local production startup requires an explicit loopback HOST; use pnpm app:start.',\n );\n }\n const id = applicationId();\n localLease ??= writerLease?.({\n appId: id,\n dataDirectory,\n sourceRoot,\n });\n localPromise = initializeLocal({\n appId: id,\n dataDirectory,\n sourceRoot,\n env,\n bindHost,\n providers: {\n database: runtime.providers.database,\n authentication: runtime.providers.authentication,\n tenancy: runtime.providers.tenancy,\n assets: runtime.providers.assets,\n secrets: runtime.providers.secrets,\n jobs: runtime.providers.jobs,\n network: runtime.providers.network,\n },\n backgroundJobs:\n options.backgroundJobs ?? env.SMRT_BACKGROUND_JOBS === 'true',\n paidCapabilities: options.paidCapabilities,\n bootstrapTtlSeconds: options.bootstrapTtlSeconds,\n sessionTtlSeconds: options.sessionTtlSeconds,\n prepareDatabase: options.prepareDatabase,\n now: options.now,\n })\n .then(({ runtime: initialized, bootstrap }) => {\n if (bootstrap) {\n try {\n options.onBootstrapInvitation?.(bootstrap, { bindHost });\n } catch {\n // Presentation is best effort; the invitation stays claimable.\n }\n }\n return initialized;\n })\n .catch((error: unknown) => {\n localLease?.release();\n localLease = undefined;\n localPromise = undefined;\n throw error;\n });\n return localPromise;\n };\n\n let deployedPromise: Promise<DeployedApplicationRuntime> | undefined;\n const deployedRuntime = async (): Promise<DeployedApplicationRuntime> => {\n const runtime = await resolvedRuntime();\n if (runtime.profile === 'local') {\n throw new Error('deployed_runtime_unavailable');\n }\n const profile = runtime.profile as DeployedApplicationRuntimeProfile;\n const databaseUrl = env.DATABASE_URL;\n if (!databaseUrl) {\n throw new Error(`${profile} requires DATABASE_URL.`);\n }\n const authenticationProvider = runtime.providers.authentication.provider;\n if (authenticationProvider === 'owner-bootstrap') {\n throw new Error('Deployed profiles require public authentication.');\n }\n const readiness = options.providerReadiness;\n if (!readiness) {\n throw new Error(\n `${profile} requires providerReadiness probes for authentication, assets, and secrets.`,\n );\n }\n deployedPromise ??= initializeDeployed({\n profile,\n providers: {\n database: runtime.providers.database,\n authentication: runtime.providers.authentication,\n tenancy: runtime.providers.tenancy,\n assets: runtime.providers.assets,\n secrets: runtime.providers.secrets,\n jobs: runtime.providers.jobs,\n network: runtime.providers.network,\n },\n database: {\n engine: 'postgres',\n connect: () => getDatabase({ type: 'postgres', url: databaseUrl }),\n close: async (db) => {\n await db.close?.();\n },\n },\n authentication: {\n provider: authenticationProvider as PublicAuthenticationProvider,\n readiness: readiness('authentication', {\n profile,\n provider: authenticationProvider,\n }),\n },\n assets: {\n provider: runtime.providers.assets.provider,\n readiness: readiness('assets', {\n profile,\n provider: runtime.providers.assets.provider,\n }),\n },\n secrets: {\n provider: runtime.providers.secrets.provider,\n readiness: readiness('secrets', {\n profile,\n provider: runtime.providers.secrets.provider,\n }),\n },\n prepareDatabase: options.prepareDatabase,\n });\n return deployedPromise;\n };\n\n const ready = async (): Promise<void> => {\n const runtime = await resolvedRuntime();\n if (runtime.profile === 'local') {\n await localRuntime();\n return;\n }\n await deployedRuntime();\n };\n\n const configurationFingerprint = (): string =>\n runtimeConfigurationFingerprint(requireResolved(), env);\n\n const health = async (): Promise<RuntimeHealthBody> => {\n await ready();\n const runtime = requireResolved();\n const publicHealth = {\n schemaVersion: 1 as const,\n status: 'ready' as const,\n profile: runtime.profile,\n };\n return runtime.profile === 'local'\n ? {\n ...publicHealth,\n application: applicationId(),\n instance: env.SMRT_PROCESS_INSTANCE || null,\n configuration: configurationFingerprint(),\n }\n : publicHealth;\n };\n\n const readDiagnostics = async (\n diagnosticsOptions: ApplicationRuntimeDiagnosticsOptions,\n ): Promise<RuntimeDiagnostics> => {\n await ready();\n const runtime = requireResolved();\n const schema = {\n status: diagnosticsOptions.schemaStatus ?? 'unknown',\n migrations: diagnosticsOptions.migrationStatus ?? 'unknown',\n } as const;\n\n if (runtime.profile === 'local') {\n const local = await localRuntime();\n const diagnostics = await local.diagnostics();\n return projectRuntimeDiagnostics({\n profile: 'local',\n health: 'healthy',\n schema,\n capabilities: {\n 'asset-storage': 'available',\n authentication: 'available',\n 'background-jobs': diagnostics.jobs.backgroundEnabled\n ? 'available'\n : 'disabled',\n database: 'available',\n 'paid-capabilities': diagnostics.paidCapabilitiesEnabled\n ? 'available'\n : 'disabled',\n 'secret-storage': 'available',\n },\n toolNames: diagnosticsOptions.toolNames,\n worker: {\n topology: diagnostics.jobs.topology,\n required: diagnostics.jobs.backgroundEnabled,\n heartbeatAt: diagnosticsOptions.workerHeartbeatAt,\n },\n recentErrors: diagnosticsOptions.recentErrors,\n observedAt: diagnosticsOptions.observedAt,\n });\n }\n\n const deployed = await deployedPromise;\n if (!deployed) throw new Error('deployed_runtime_unavailable');\n const readiness = await deployed.readiness();\n const componentStatus = (\n component: keyof typeof readiness.components,\n ): 'available' | 'unavailable' =>\n readiness.components[component].status === 'ready'\n ? 'available'\n : 'unavailable';\n const input: RuntimeDiagnosticsProjectionInput = {\n profile: runtime.profile,\n health:\n deployed.health().status === 'healthy'\n ? readiness.status === 'ready'\n ? 'healthy'\n : 'degraded'\n : 'stopped',\n schema,\n capabilities: {\n 'asset-storage': componentStatus('assets'),\n authentication: componentStatus('authentication'),\n 'background-jobs': 'available',\n database: componentStatus('database'),\n 'paid-capabilities': 'unknown',\n 'secret-storage': componentStatus('secrets'),\n },\n toolNames: diagnosticsOptions.toolNames,\n worker: {\n topology: deployed.resolvedRuntime.providers.jobs.topology,\n required: true,\n heartbeatAt: diagnosticsOptions.workerHeartbeatAt,\n },\n recentErrors: diagnosticsOptions.recentErrors,\n observedAt: diagnosticsOptions.observedAt,\n };\n return projectRuntimeDiagnostics(input);\n };\n\n const selectTenant: TenantSelector =\n options.selectTenant ??\n createSubdomainTenantSelector({\n baseDomain: options.tenantBaseDomain ?? env.TENANT_BASE_DOMAIN,\n classOptions: () => baseClassOptions('Tenant'),\n });\n\n const readinessHandle: Handle = async ({ event, resolve }) => {\n await ready();\n return resolve(event);\n };\n\n const tenantSelectionHandle: Handle = async ({ event, resolve }) => {\n const locals = runtimeLocals(event.locals);\n const selection = normalizeTenantSelection(\n await selectTenant({ url: event.url, request: event.request }),\n );\n locals.selectedTenantId = selection.tenantId;\n locals.selectedTenantSlug = selection.tenantSlug;\n return resolve(event);\n };\n\n const sessionCookieName = options.session?.cookieName ?? 'sid';\n const sessionSkipPaths = options.session?.skipPaths ?? [];\n const sessionServiceOptions = (): SessionServiceOptions => ({\n ...baseClassOptions('Session'),\n ...options.session,\n defaultTTL: options.session?.ttl ?? DEFAULT_SESSION_TTL_SECONDS,\n autoExtend: options.session?.autoExtend ?? false,\n });\n /** `database-rls` isolation always runs the request RLS transaction. */\n const postgresRls = (): boolean | undefined =>\n requireResolved().providers.tenancy.isolation === 'database-rls'\n ? true\n : options.session?.postgresRls;\n let permissionResolverPromise: Promise<PermissionResolver> | undefined;\n const permissionResolver = (): Promise<PermissionResolver> => {\n permissionResolverPromise ??= PermissionResolver.create(\n baseClassOptions('Permission'),\n ).catch((error: unknown) => {\n permissionResolverPromise = undefined;\n throw error;\n });\n return permissionResolverPromise;\n };\n\n const runAsPrincipal = async <\n T,\n P extends SmrtRuntimeBoundPrincipal = SmrtRuntimeBoundPrincipal,\n >(\n principal: P,\n fn: (bound: SmrtRuntimeBoundPrincipalSnapshot<P>) => Promise<T>,\n ): Promise<T> => {\n // One complete snapshot before the first await: authorization, the\n // permission/RLS context and the principal handed to `fn` all come from\n // it, and the caller's object is never read again (a caller mutating it\n // mid-flight cannot change the bound identity, tenant, binding or scopes).\n if (!principal || typeof principal !== 'object') {\n throw new Error('A bound principal is required.');\n }\n const snapshot = snapshotBoundPrincipal(principal) as P;\n // The snapshot has a null prototype: every read below is own data.\n const tokenDerived = isLocalMcpTokenPrincipal(snapshot);\n const userId = ownValue(snapshot, 'id') as P['id'];\n const tenantId = ownValue(snapshot, 'tenantId') as P['tenantId'];\n const snapshotScopes = ownValue(snapshot, 'scopes') as\n | readonly string[]\n | undefined;\n const requestedTenantBinding = ownValue(snapshot, 'tenantBinding') as\n | TenantBindingMode\n | undefined;\n const requestedScopes =\n snapshotScopes === undefined\n ? undefined\n : Object.freeze([...snapshotScopes]);\n if (\n requestedScopes !== undefined &&\n !requestedScopes.every((scope) => typeof scope === 'string')\n ) {\n throw new Error('A bound principal has malformed scopes.');\n }\n if (typeof userId !== 'string' || userId.length === 0) {\n throw new Error('A bound principal requires a user id.');\n }\n if (typeof tenantId !== 'string' || tenantId.length === 0) {\n throw new Error('A bound principal requires a tenant.');\n }\n // Resolution reads the base connection, before any RLS transaction opens.\n // A token-derived principal is direct-only. A copy that tries to widen\n // its binding is refused rather than silently narrowed.\n if (\n tokenDerived &&\n requestedTenantBinding !== undefined &&\n requestedTenantBinding !== 'direct'\n ) {\n throw new Error(\n 'A local MCP token principal binds only through its direct membership.',\n );\n }\n const binding: TenantBindingMode = tokenDerived\n ? 'direct'\n : (requestedTenantBinding ?? 'direct-or-inherited');\n if (binding !== 'direct' && binding !== 'direct-or-inherited') {\n throw new Error('Unknown tenant binding mode for a bound principal.');\n }\n const resolved = await resolveBoundMembershipPermissions({\n memberships: await MembershipCollection.create(\n baseClassOptions('Membership'),\n ),\n resolver: await permissionResolver(),\n userId,\n tenantId,\n binding,\n });\n if (!resolved) {\n throw new Error(\n binding === 'direct'\n ? 'The bound principal has no active direct membership in its tenant.'\n : 'The bound principal has no authorized membership in its tenant.',\n );\n }\n const cap = requestedScopes ? new Set(requestedScopes) : undefined;\n const permissions = [...resolved.permissions].filter(\n (permission) => !cap || cap.has(permission),\n );\n return withPrincipalPermissionContext(\n {\n ...baseClassOptions('Session'),\n userId,\n tenantId,\n permissions,\n enterTenantContext: true,\n postgresRls: postgresRls(),\n },\n () =>\n fn(\n // Null prototype like the snapshot: a field the principal lacks\n // (say `allowCrossTenant`) never resolves to an inherited value.\n Object.freeze(\n Object.assign(Object.create(null), snapshot, {\n id: userId,\n tenantId,\n tenantBinding: binding,\n scopes: Object.freeze([...permissions]),\n }),\n ) as SmrtRuntimeBoundPrincipalSnapshot<P>,\n ),\n );\n };\n\n const verifyLocalMcpToken = async (\n token: string,\n ): Promise<LocalMcpTokenPrincipal | null> => {\n if ((await resolvedRuntime()).profile !== 'local') return null;\n const local = await localRuntime();\n // A runtime without a token store has no tokens: fail closed.\n return (await local.mcpTokens?.verify(token)) ?? null;\n };\n\n const resolveMcpPrincipal = async (\n identity: SmrtRuntimeMcpIdentity,\n ): Promise<SmrtRuntimeMcpPrincipalMapping | null> => {\n if ((await resolvedRuntime()).profile === 'local') return null;\n if (!identity || typeof identity !== 'object') return null;\n const issuer = ownValue(identity, 'issuer');\n const subject = ownValue(identity, 'subject');\n if (\n typeof issuer !== 'string' ||\n issuer.length === 0 ||\n typeof subject !== 'string' ||\n subject.length === 0\n ) {\n return null;\n }\n // Every read is keyed by the verified issuer/subject and the ids derived\n // from it, and only ids leave this block (the PermissionResolver rule).\n return withSystemContext(async () => {\n const identities = await OidcIdentityCollection.create(\n baseClassOptions('OidcIdentity'),\n );\n let linked: Awaited<ReturnType<typeof identities.findBySubject>>;\n try {\n linked = await identities.findBySubject(issuer, subject);\n } catch {\n return null; // Ambiguous identity: deny.\n }\n if (!linked?.profileId) return null;\n const users = await UserCollection.create(baseClassOptions('User'));\n const owners = await users.list({\n where: { profileId: linked.profileId },\n limit: 2,\n });\n const user = owners.length === 1 ? owners[0] : undefined;\n if (\n typeof user?.id !== 'string' ||\n user.id.length === 0 ||\n user.status !== UserStatus.ACTIVE\n ) {\n return null;\n }\n const memberships = await MembershipCollection.create(\n baseClassOptions('Membership'),\n );\n const tenants = new Set(\n (await memberships.findActiveByUser(user.id))\n .map((membership) => membership.tenantId)\n .filter(\n (tenantId): tenantId is string =>\n typeof tenantId === 'string' && tenantId.length > 0,\n ),\n );\n if (tenants.size !== 1) return null;\n const [tenantId] = tenants;\n return Object.freeze({\n id: user.id,\n tenantId,\n kind: 'human' as const,\n tenantBinding: 'direct' as const,\n });\n });\n };\n\n let sessionServicePromise: Promise<SessionService> | undefined;\n const sessionService = (): Promise<SessionService> => {\n sessionServicePromise ??= (async () => {\n const service = new TenantAuthorizingSessionService(\n sessionServiceOptions(),\n requireResolved().providers.tenancy.context === 'required',\n );\n await service.initialize();\n return service;\n })().catch((error: unknown) => {\n sessionServicePromise = undefined;\n throw error;\n });\n return sessionServicePromise;\n };\n\n /**\n * Step 2. Downstream code runs at most once: a downstream throw (or a\n * failure after `resolve` was entered, such as an RLS commit) propagates\n * unchanged and `resolve` is never re-entered. A session-layer failure\n * before `resolve` fails closed with 500 and no authenticated locals, for\n * both RLS and non-RLS isolation.\n */\n const sessionStep: Handle = async ({ event, resolve }) => {\n const locals = runtimeLocals(event.locals);\n clearSessionLocals(locals);\n const rls = postgresRls();\n // A skipped path skips session loading only. Under RLS it still runs in\n // the request transaction, as an anonymous principal.\n const skipped = sessionSkipPaths.some((path) =>\n event.url.pathname.startsWith(path),\n );\n if (skipped && !rls) return resolve(event);\n const sessionId = skipped\n ? undefined\n : event.cookies.get(sessionCookieName);\n if (!sessionId && !rls) return resolve(event);\n\n let resolveEntered = false;\n let downstream: { error: unknown } | undefined;\n try {\n const service = await sessionService();\n return await withSessionPermissionContext(\n {\n ...sessionServiceOptions(),\n enterTenantContext: true,\n postgresRls: rls,\n sessionId: sessionId ?? null,\n sessionService: service,\n },\n async (context) => {\n if (context.session) {\n locals.user = context.user;\n locals.membership = context.membership ?? null;\n locals.permissions = context.permissions;\n locals.tenantId = context.tenantId;\n locals.sessionId = context.sessionId;\n if (context.tenantId) {\n verifiedSessionTenants.set(locals, context.tenantId);\n }\n }\n resolveEntered = true;\n try {\n return await resolve(event);\n } catch (error) {\n downstream = { error };\n throw error;\n }\n },\n );\n } catch (error) {\n if (downstream) throw downstream.error;\n if (resolveEntered) throw error;\n clearSessionLocals(locals);\n return new Response('Internal Server Error', { status: 500 });\n }\n };\n\n const sessionCookie: SmrtRuntimeSessionCookie = Object.freeze({\n name: options.session?.cookieName ?? 'sid',\n path: options.session?.cookiePath ?? '/',\n ...(options.session?.cookieDomain\n ? { domain: options.session.cookieDomain }\n : {}),\n sameSite: options.session?.cookieSameSite ?? 'lax',\n ...(options.session?.cookieSecure !== undefined\n ? { secure: options.session.cookieSecure }\n : {}),\n maxAgeSeconds: options.sessionTtlSeconds ?? DEFAULT_SESSION_TTL_SECONDS,\n });\n\n const init: ServerInit = () => ready();\n\n return Object.freeze({\n handle: composeHandles(\n readinessHandle,\n tenantSelectionHandle,\n sessionStep,\n authorizedTenantLocalsHandle,\n ),\n init,\n sessionCookie,\n resolvedRuntime,\n ready,\n applicationId,\n applicationStateRoot: () =>\n resolveApplicationStateRoot({\n appId: applicationId(),\n dataDirectory,\n sourceRoot,\n }),\n configurationFingerprint,\n databaseConfig,\n classOptions,\n getCollection,\n runAsPrincipal,\n verifyLocalMcpToken,\n resolveMcpPrincipal,\n localRuntime,\n deployedRuntime,\n health,\n readDiagnostics,\n });\n}\n\n/**\n * The default local writer lease: the state-root `writer.lease` shared with\n * `smrt app` operations, presenting the managed operation instance\n * (`SMRT_OPERATION_INSTANCE`) that `smrt app start` passes to its writer.\n */\nexport function defaultWriterLease(\n context: WriterLeaseContext,\n env: NodeJS.ProcessEnv = process.env,\n): WriterLease {\n return acquireWriterLease(\n prepareApplicationStateRoot({\n appId: context.appId,\n dataDirectory: context.dataDirectory,\n sourceRoot: context.sourceRoot,\n }),\n { operationInstance: env.SMRT_OPERATION_INSTANCE },\n );\n}\n\n/** Locals whose session tenant passed {@link isSessionTenantAuthorized}. */\nconst verifiedSessionTenants = new WeakMap<object, string>();\n\n/**\n * Session service whose loaded context carries a tenant only when that\n * tenant passed {@link isSessionTenantAuthorized}. A session bound to an\n * unauthorized tenant (or missing a required tenant) loads as no session, so\n * no identity, permissions, or tenant context is established for it.\n */\nclass TenantAuthorizingSessionService extends SessionService {\n private readonly tenantRequired: boolean;\n\n constructor(options: SessionServiceOptions, tenantRequired: boolean) {\n super(options);\n this.tenantRequired = tenantRequired;\n }\n\n override async loadSessionContext(\n sessionId: string,\n ): ReturnType<SessionService['loadSessionContext']> {\n const context = await super.loadSessionContext(sessionId);\n if (!context) return null;\n if (typeof context.tenantId === 'string' && context.tenantId.length > 0) {\n return isSessionTenantAuthorized(context) ? context : null;\n }\n return this.tenantRequired ? null : context;\n }\n}\n\nfunction clearSessionLocals(locals: SmrtRuntimeLocals): void {\n locals.user = null;\n locals.membership = null;\n locals.permissions = [];\n locals.tenantId = null;\n locals.sessionId = null;\n locals.tenantContext = undefined;\n verifiedSessionTenants.delete(locals);\n}\n\n/**\n * Step 3: publish the authorized tenant context only when this runtime's\n * session step verified the session tenant and it matches the active\n * AsyncLocalStorage context. Locals populated by any other session layer are\n * never published.\n */\nexport const authorizedTenantLocalsHandle: Handle = async ({\n event,\n resolve,\n}) => {\n const locals = runtimeLocals(event.locals);\n const activeContext = getCurrentTenant();\n if (\n locals.user &&\n locals.tenantId &&\n verifiedSessionTenants.get(locals) === locals.tenantId &&\n activeContext?.tenantId === locals.tenantId\n ) {\n locals.tenantContext = activeContext;\n }\n return resolve(event);\n};\n\n/**\n * Run handles in order. Unlike `sequence()` from `@sveltejs/kit/hooks`, this\n * needs no SvelteKit request store, so the composed handle is usable (and\n * testable) outside the Kit server runtime. The runtime's own handles never\n * pass resolve options; any options a handle passes are forwarded unchanged.\n */\nexport function composeHandles(...handles: readonly Handle[]): Handle {\n return ({ event, resolve }) => {\n const run: (\n index: number,\n current: Parameters<Handle>[0]['event'],\n resolveOptions?: Parameters<Parameters<Handle>[0]['resolve']>[1],\n ) => ReturnType<Handle> = (index, current, resolveOptions) => {\n const next = handles[index];\n if (!next) return resolve(current, resolveOptions);\n return next({\n event: current,\n resolve: (nextEvent, nextOptions) =>\n run(index + 1, nextEvent, nextOptions ?? resolveOptions),\n });\n };\n return run(0, event);\n };\n}\n\nfunction runtimeLocals(locals: unknown): SmrtRuntimeLocals {\n return locals as SmrtRuntimeLocals;\n}\n\n/**\n * No `runtime` block selects `local`; a present non-block value fails closed.\n * Shared with `smrt app` through smrt-config (#3446).\n */\nasync function loadConfiguredRuntime(): Promise<ResolvedApplicationRuntime> {\n return resolveEffectiveApplicationRuntime(await loadConfig());\n}\n\n/**\n * Deep, frozen, validated copy of a bound principal, taken before any await\n * (see `plain-data.ts` for what is rejected: poison keys, accessors,\n * inherited or non-plain data, sparse arrays, functions, deep nesting).\n * Known fields are type-checked from own data (`id`, `tenantId`, `kind`,\n * `tenantBinding`: strings; `scopes`, `roles`: string arrays;\n * `allowCrossTenant`: boolean). Other own enumerable fields (string or\n * symbol keys) are kept as deep-frozen copies.\n */\nfunction snapshotBoundPrincipal(\n principal: unknown,\n): Record<PropertyKey, unknown> {\n if (!principal || typeof principal !== 'object' || Array.isArray(principal)) {\n throw new Error('A bound principal is required.');\n }\n let snapshot: Record<PropertyKey, unknown>;\n try {\n snapshot = deepFrozenPlainCopy(principal) as Record<PropertyKey, unknown>;\n } catch (error) {\n if (error instanceof PlainDataError) {\n throw new Error(`A bound principal ${error.message}.`);\n }\n throw error;\n }\n for (const key of ['id', 'tenantId', 'kind', 'tenantBinding']) {\n const value = ownValue(snapshot, key);\n if (value !== undefined && typeof value !== 'string') {\n throw new Error(`A bound principal has a malformed ${key}.`);\n }\n }\n for (const key of ['scopes', 'roles']) {\n const value = ownValue(snapshot, key);\n if (\n value !== undefined &&\n (!Array.isArray(value) ||\n !value.every((entry) => typeof entry === 'string'))\n ) {\n throw new Error(`A bound principal has malformed ${key}.`);\n }\n }\n const allowCrossTenant = ownValue(snapshot, 'allowCrossTenant');\n if (allowCrossTenant !== undefined && typeof allowCrossTenant !== 'boolean') {\n throw new Error('A bound principal has a malformed allowCrossTenant.');\n }\n return snapshot;\n}\n"],"mappings":";;;;;;;;;AAiBO,IAAM,sCAAsC;AAU5C,SAAS,2BACd,SACgB;CAChB,OAAO,YAAY,KAAK,MAAM,QAAQ,OAAO,CAAC;AAChD;AA8CA,SAAS,kBACP,OACe;CACf,OAAO,OAAO,UAAU,aAAc,MAAkB,IAAI;AAC9D;AAWO,SAAS,gCACd,SACgB;CAChB,MAAM,UAAU,QAAQ;CACxB,MAAM,kBACJ,QAAQ,oBACP,gBAEK,QAAQ,gBAAgB;EACtB,WAAW,kBAAkB,QAAQ,SAAS,KAAK,CAAC;EACpD,YAAY,QAAQ,MAAM,qBAAK,IAAI,KAAK;EACxC,cAAc,kBAAkB,QAAQ,YAAY,KAAK;EACzD,iBACE,kBAAkB,QAAQ,eAAe,KAAK;EAChD,mBAAmB,QAAQ,oBAAoB,KAAK;EACpD,cAAc,QAAQ,eAAe,KAAK,CAAC;CAC7C,CAAC,IACH,KAAA;CACN,MAAM,kBACJ,QAAQ,oBACP,UACG,OAAO,WAAmB;EACxB,MAAM,SAAS,QAAQ,aAAa,MAAM;EAC1C,MAAM,YAAY,yBAAyB;EAM3C,QAAQ,OAAM,MALM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OAAO,CAAC,UAAU,OAAO,GAAG;EACrC,MAAM,QAAQ,SAAS,UAAU,GAAG;EACpC,IACE,UAAU,KAAA,MACT,CAAC,MAAM,QAAQ,KAAK,KACnB,CAAC,MAAM,OAAO,UAAU,OAAO,UAAU,QAAQ,IAEnD,MAAM,IAAI,MAAM,mCAAmC,IAAG,EAAG;CAE7D;CACA,MAAM,mBAAmB,SAAS,UAAU,kBAAkB;CAC9D,IAAI,qBAAqB,KAAA,KAAa,OAAO,qBAAqB,WAChE,MAAM,IAAI,MAAM,qDAAqD;CAEvE,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"sveltekit.js","names":["name","resolved","tenantId"],"sources":["../src/sveltekit/handlers.ts","../src/sveltekit/owner-setup.ts","../src/sveltekit/tenancy.ts","../src/sveltekit/runtime.ts"],"sourcesContent":["/**\n * Mountable runtime routes: liveness health, authorized diagnostics, and the\n * server-owned session summary for the root layout.\n */\n\nimport {\n getRequestScopedDatabase,\n RoleCollection,\n} from '@happyvertical/smrt-users';\nimport { json, type RequestHandler } from '@sveltejs/kit';\nimport type { RuntimeDiagnostics } from '../runtime-diagnostics.js';\nimport type {\n ApplicationRuntimeDiagnosticsOptions,\n SmrtSvelteKitRuntime,\n} from './runtime.js';\n\n/** Explicit permission that grants diagnostics read without the owner role. */\nexport const RUNTIME_DIAGNOSTICS_READ_PERMISSION = 'runtime_diagnostics.read';\n\n/**\n * Mount as `src/routes/api/_runtime/health/+server.ts`:\n * `export const GET = createRuntimeHealthHandler(runtime);`\n *\n * Local responses add the application ID, managed process instance, and the\n * secret-free configuration fingerprint that process managers compare.\n * Deployed responses expose only schema version, status, and profile.\n */\nexport function createRuntimeHealthHandler(\n runtime: Pick<SmrtSvelteKitRuntime, 'health'>,\n): RequestHandler {\n return async () => json(await runtime.health());\n}\n\n/** The locals the diagnostics route authorizes against. */\nexport interface DiagnosticsPrincipalLocals {\n readonly user?: { readonly id?: unknown } | null;\n readonly membership?: {\n readonly userId?: unknown;\n readonly tenantId?: unknown;\n readonly roleId?: unknown;\n isActive?: () => boolean;\n } | null;\n readonly permissions?: readonly string[];\n readonly tenantId?: unknown;\n readonly sessionId?: unknown;\n}\n\ntype DiagnosticsInputValue<T> = T | (() => T);\n\nexport interface RuntimeDiagnosticsHandlerOptions {\n /** Supplies default diagnostics reading and owner-role lookup. */\n readonly runtime?: Pick<\n SmrtSvelteKitRuntime,\n 'readDiagnostics' | 'classOptions'\n >;\n /** Replace the runtime projection (must already be the public allowlist). */\n readonly readDiagnostics?: () => Promise<RuntimeDiagnostics>;\n /** Replace the owner-role lookup. Thrown errors deny. */\n readonly resolveRoleSlug?: (roleId: string) => Promise<string | null>;\n /** Override where the principal comes from. Defaults to `event.locals`. */\n readonly resolveLocals?: (event: {\n readonly locals: unknown;\n }) => DiagnosticsPrincipalLocals;\n /** Public tool inventory (sorted/capped by the projector). */\n readonly toolNames?: DiagnosticsInputValue<readonly string[]>;\n readonly schemaStatus?: DiagnosticsInputValue<\n ApplicationRuntimeDiagnosticsOptions['schemaStatus']\n >;\n readonly migrationStatus?: DiagnosticsInputValue<\n ApplicationRuntimeDiagnosticsOptions['migrationStatus']\n >;\n readonly workerHeartbeatAt?: () => Date | string | null | undefined;\n readonly recentErrors?: () => ApplicationRuntimeDiagnosticsOptions['recentErrors'];\n /** Testable clock. */\n readonly now?: () => Date;\n}\n\nfunction resolveInputValue<T>(\n value: DiagnosticsInputValue<T> | undefined,\n): T | undefined {\n return typeof value === 'function' ? (value as () => T)() : value;\n}\n\n/**\n * Mount as `src/routes/api/_runtime/diagnostics/+server.ts`:\n * `export const GET = createRuntimeDiagnosticsHandler({ runtime });`\n *\n * Authentication and authorization always complete before the private runtime\n * is read. Authorized callers hold `runtime_diagnostics.read` or the `owner`\n * role of their active, session-matching membership. Every failure is a\n * stable `{ schemaVersion: 1, error: { code } }` body.\n */\nexport function createRuntimeDiagnosticsHandler(\n options: RuntimeDiagnosticsHandlerOptions,\n): RequestHandler {\n const runtime = options.runtime;\n const readDiagnostics =\n options.readDiagnostics ??\n (runtime\n ? () =>\n runtime.readDiagnostics({\n toolNames: resolveInputValue(options.toolNames) ?? [],\n observedAt: options.now?.() ?? new Date(),\n schemaStatus: resolveInputValue(options.schemaStatus) ?? 'unknown',\n migrationStatus:\n resolveInputValue(options.migrationStatus) ?? 'unknown',\n workerHeartbeatAt: options.workerHeartbeatAt?.() ?? null,\n recentErrors: options.recentErrors?.() ?? [],\n })\n : undefined);\n const resolveRoleSlug =\n options.resolveRoleSlug ??\n (runtime\n ? async (roleId: string) => {\n const config = runtime.classOptions('Role');\n const requestDb = getRequestScopedDatabase();\n const roles = await RoleCollection.create(\n requestDb\n ? { ...config, db: requestDb as typeof config.db }\n : config,\n );\n return (await roles.findById(roleId))?.slug ?? null;\n }\n : undefined);\n if (!readDiagnostics || !resolveRoleSlug) {\n throw new TypeError(\n 'createRuntimeDiagnosticsHandler requires `runtime`, or both `readDiagnostics` and `resolveRoleSlug`.',\n );\n }\n const resolveLocals =\n options.resolveLocals ??\n ((event: { readonly locals: unknown }) =>\n event.locals as DiagnosticsPrincipalLocals);\n\n return async (event) => {\n const locals = resolveLocals(event);\n const principal = authenticatedPrincipal(locals);\n if (!principal) return stableError(401, 'authentication_required');\n\n let authorized =\n locals.permissions?.includes(RUNTIME_DIAGNOSTICS_READ_PERMISSION) ===\n true;\n if (!authorized) {\n try {\n authorized = (await resolveRoleSlug(principal.roleId)) === 'owner';\n } catch {\n authorized = false;\n }\n }\n if (!authorized) return stableError(403, 'authorization_denied');\n\n try {\n return json(await readDiagnostics());\n } catch {\n return stableError(503, 'diagnostics_unavailable');\n }\n };\n}\n\nfunction authenticatedPrincipal(\n locals: DiagnosticsPrincipalLocals | null | undefined,\n): { roleId: string } | null {\n const userId = locals?.user?.id;\n const tenantId = locals?.tenantId;\n const sessionId = locals?.sessionId;\n const membership = locals?.membership;\n if (\n typeof userId !== 'string' ||\n !userId ||\n typeof tenantId !== 'string' ||\n !tenantId ||\n typeof sessionId !== 'string' ||\n !sessionId ||\n !membership ||\n membership.userId !== userId ||\n membership.tenantId !== tenantId ||\n typeof membership.roleId !== 'string' ||\n !membership.roleId\n ) {\n return null;\n }\n try {\n if (membership.isActive?.() !== true) return null;\n } catch {\n return null;\n }\n return { roleId: membership.roleId };\n}\n\nfunction stableError(status: number, code: string): Response {\n return json({ schemaVersion: 1, error: { code } }, { status });\n}\n\n/** Server-owned session summary for the root layout. */\nexport interface SessionLayoutData {\n readonly session: {\n readonly authenticated: boolean;\n /** Tenant authorized by the active session. */\n readonly activeTenantId: string | null;\n /** URL-selected tenant candidate; display only, never authorization. */\n readonly selectedTenantSlug: string | null;\n };\n}\n\n/**\n * Mount as `src/routes/+layout.server.ts`:\n * `export const load = createSessionLayoutLoad();`\n */\nexport function createSessionLayoutLoad(): (event: {\n readonly locals: unknown;\n}) => SessionLayoutData {\n return ({ locals }) => {\n const value = locals as {\n user?: unknown;\n tenantId?: string | null;\n selectedTenantSlug?: string | null;\n };\n return {\n session: {\n authenticated: Boolean(value.user),\n activeTenantId: value.tenantId ?? null,\n selectedTenantSlug: value.selectedTenantSlug ?? null,\n },\n };\n };\n}\n","/**\n * Server half of the local owner-setup page (`src/routes/setup/+page.server.ts`).\n *\n * Owner bootstrap is local-profile only, loopback-only, and single-use. The\n * runtime stores only an HMAC of the short-lived token; this module never\n * stores, logs, or returns claim errors, and it re-checks loopback custody on\n * every request instead of trusting the bind host alone.\n */\n\nimport type { Cookies } from '@sveltejs/kit';\nimport { type ActionFailure, fail, redirect } from '@sveltejs/kit';\nimport type { LocalOwnerClaimResult } from '../index.js';\nimport { removeOnboardingHandoff } from '../state-root.js';\nimport type { SmrtSvelteKitRuntime } from './runtime.js';\n\n/** Data returned by the setup page `load`. */\nexport interface OwnerSetupPageData {\n /** False when setup is claimed, disabled (deployed), or not loopback. */\n readonly available: boolean;\n /** One-time token from `?token=` (empty unless available). */\n readonly token: string;\n}\n\n/** Stable failure codes returned by the setup action. */\nexport type OwnerSetupErrorCode =\n /** Not the local profile (HTTP 404). */\n | 'setup_disabled'\n /** Request is not from a loopback client on a loopback host (HTTP 403). */\n | 'setup_unavailable'\n /** Missing token, blank name, or email without `@` (HTTP 400). */\n | 'setup_invalid_input'\n /** Token wrong, expired, or already used; owner already claimed (HTTP 400). */\n | 'setup_invalid';\n\n/** `form` data returned with `fail(status, …)`. */\nexport interface OwnerSetupFailure {\n readonly code: OwnerSetupErrorCode;\n /** Fixed, secret-free message; never claim error text. */\n readonly message: string;\n}\n\n/** Form field names posted to the setup action. */\nexport const OWNER_SETUP_FIELDS = Object.freeze({\n token: 'token',\n name: 'name',\n email: 'email',\n tenantName: 'tenantName',\n} as const);\n\nexport const DEFAULT_OWNER_SETUP_MESSAGES: Readonly<\n Record<OwnerSetupErrorCode, string>\n> = Object.freeze({\n setup_disabled: 'Local owner setup is disabled.',\n setup_unavailable: 'Local owner setup is available only from this device.',\n setup_invalid_input: 'Name, email, and a valid setup token are required.',\n setup_invalid:\n 'The setup invitation is invalid, expired, or already used. Run pnpm app:stop, pnpm app:recover, pnpm app:start, then pnpm app:open.',\n});\n\n/** The request fields the setup page reads. */\nexport interface OwnerSetupEvent {\n readonly url: URL;\n readonly locals: unknown;\n getClientAddress(): string;\n}\n\nexport interface OwnerSetupActionEvent extends OwnerSetupEvent {\n readonly request: Request;\n readonly cookies: Pick<Cookies, 'set'>;\n}\n\nexport interface OwnerSetupPageOptions {\n /** Where a signed-in visitor or a successful claim is sent. Default `/`. */\n readonly redirectTo?: string;\n /** Replace fixed failure messages (for example app-specific recovery steps). */\n readonly messages?: Partial<Record<OwnerSetupErrorCode, string>>;\n /** Override where the signed-in user comes from. Defaults to `locals.user`. */\n readonly resolveUser?: (event: OwnerSetupEvent) => unknown;\n /**\n * Set false to keep the `smrt app` onboarding hand-off files after a claim.\n * By default the runtime removes `onboarding.json` and\n * `onboarding-launch.html` from the private state root once the claim has\n * committed, so `pnpm app:open` stops offering the spent invitation.\n */\n readonly removeOnboardingHandoff?: boolean;\n /**\n * Best-effort extra cleanup after a successful claim (the hand-off files are\n * already removed by default). Errors are ignored: the owner and session are\n * already authoritative and a stale token now fails closed.\n */\n readonly onOwnerClaimed?: (\n result: LocalOwnerClaimResult,\n event: OwnerSetupActionEvent,\n ) => void | Promise<void>;\n}\n\nexport interface OwnerSetupPage {\n readonly load: (event: OwnerSetupEvent) => Promise<OwnerSetupPageData>;\n readonly actions: {\n readonly default: (\n event: OwnerSetupActionEvent,\n ) => Promise<ActionFailure<OwnerSetupFailure>>;\n };\n}\n\n/**\n * Mount as `src/routes/setup/+page.server.ts`:\n *\n * ```ts\n * import { createOwnerSetupPage } from '@happyvertical/smrt-app-runtime/sveltekit';\n * import { runtime } from '../../hooks.server';\n *\n * export const { load, actions } = createOwnerSetupPage(runtime);\n * ```\n *\n * The form posts to the `default` action with fields `token` (hidden),\n * `name`, `email`, and optional `tenantName`. Success sets the session cookie\n * and redirects 303; failures return `fail(status, { code, message })`.\n */\nexport function createOwnerSetupPage(\n runtime: Pick<\n SmrtSvelteKitRuntime,\n 'resolvedRuntime' | 'localRuntime' | 'sessionCookie'\n > &\n Partial<Pick<SmrtSvelteKitRuntime, 'applicationStateRoot'>>,\n options: OwnerSetupPageOptions = {},\n): OwnerSetupPage {\n const redirectTo = options.redirectTo ?? '/';\n const messages = { ...DEFAULT_OWNER_SETUP_MESSAGES, ...options.messages };\n const failure = (status: number, code: OwnerSetupErrorCode) =>\n fail(status, { code, message: messages[code] } as OwnerSetupFailure);\n const resolveUser =\n options.resolveUser ??\n ((event: OwnerSetupEvent) => (event.locals as { user?: unknown }).user);\n\n const load = async (event: OwnerSetupEvent): Promise<OwnerSetupPageData> => {\n if (resolveUser(event)) redirect(303, redirectTo);\n const resolved = await runtime.resolvedRuntime();\n if (resolved.profile !== 'local' || !isLoopbackRequest(event)) {\n return { available: false, token: '' };\n }\n const local = await runtime.localRuntime();\n const diagnostics = await local.diagnostics();\n const available = diagnostics.bootstrap.status !== 'claimed';\n return {\n available,\n token: available\n ? event.url.searchParams.get(OWNER_SETUP_FIELDS.token) || ''\n : '',\n };\n };\n\n const claim = async (\n event: OwnerSetupActionEvent,\n ): Promise<ActionFailure<OwnerSetupFailure>> => {\n const resolved = await runtime.resolvedRuntime();\n if (resolved.profile !== 'local') return failure(404, 'setup_disabled');\n if (!isLoopbackRequest(event)) return failure(403, 'setup_unavailable');\n\n let form: FormData;\n try {\n form = await event.request.formData();\n } catch {\n return failure(400, 'setup_invalid_input');\n }\n const field = (name: string) => {\n const value = form.get(name);\n return typeof value === 'string' ? value : '';\n };\n const token = field(OWNER_SETUP_FIELDS.token);\n const name = field(OWNER_SETUP_FIELDS.name);\n const email = field(OWNER_SETUP_FIELDS.email);\n const tenantName = field(OWNER_SETUP_FIELDS.tenantName).trim();\n if (!token || !name.trim() || !email.includes('@')) {\n return failure(400, 'setup_invalid_input');\n }\n\n const local = await runtime.localRuntime();\n let result: LocalOwnerClaimResult;\n try {\n result = await local.claimOwner({\n token,\n name,\n email,\n ...(tenantName ? { tenantName } : {}),\n userAgent: event.request.headers.get('user-agent') || undefined,\n ipAddress: event.getClientAddress(),\n });\n } catch {\n return failure(400, 'setup_invalid');\n }\n\n // claimOwner resolved, so the claim transaction has committed. Clean up\n // before cookie serialization, which can throw on a malformed config.\n if (\n options.removeOnboardingHandoff !== false &&\n runtime.applicationStateRoot\n ) {\n try {\n removeOnboardingHandoff(runtime.applicationStateRoot());\n } catch {\n // Best effort: the spent token already fails closed.\n }\n }\n const cookie = runtime.sessionCookie;\n event.cookies.set(cookie.name, result.sessionId, {\n path: cookie.path,\n ...(cookie.domain ? { domain: cookie.domain } : {}),\n httpOnly: true,\n secure: cookie.secure ?? event.url.protocol === 'https:',\n sameSite: cookie.sameSite,\n maxAge: cookie.maxAgeSeconds,\n });\n try {\n await options.onOwnerClaimed?.(result, event);\n } catch {\n // Best effort only; see OwnerSetupPageOptions.onOwnerClaimed.\n }\n redirect(303, redirectTo);\n };\n\n return Object.freeze({\n load,\n actions: Object.freeze({ default: claim }),\n });\n}\n\n/**\n * True only when both the peer address and the addressed host are loopback.\n * The host check rejects tunnels and DNS-rebinding hosts that forward to a\n * loopback listener; a throwing `getClientAddress` is treated as remote.\n */\nexport function isLoopbackRequest(event: {\n readonly url: URL;\n getClientAddress(): string;\n}): boolean {\n let address: string;\n try {\n address = event.getClientAddress();\n } catch {\n return false;\n }\n return isLoopbackAddress(address) && isLoopbackHostname(event.url.hostname);\n}\n\n/** Loopback IP literal: `127.0.0.0/8`, `::1`, or IPv4-mapped `127/8`. */\nexport function isLoopbackAddress(value: string | null | undefined): boolean {\n if (typeof value !== 'string') return false;\n let host = value\n .trim()\n .toLowerCase()\n .replace(/^\\[|\\]$/g, '');\n if (host === '::1' || host === '0:0:0:0:0:0:0:1') return true;\n if (host.startsWith('::ffff:')) host = host.slice('::ffff:'.length);\n const octets = host.split('.');\n return (\n octets.length === 4 &&\n octets.every((part) => /^\\d{1,3}$/.test(part) && Number(part) <= 255) &&\n Number(octets[0]) === 127\n );\n}\n\n/** Loopback host name as SvelteKit reports it in `url.hostname`. */\nexport function isLoopbackHostname(hostname: string): boolean {\n const host = hostname.trim().toLowerCase().replace(/\\.$/, '');\n return host === 'localhost' || isLoopbackAddress(host);\n}\n","/**\n * Tenant *selection* for SvelteKit requests.\n *\n * Selection and authorization are deliberately separate:\n *\n * - a selector maps a trusted URL shape (by default the leading subdomain) to\n * an active tenant record and publishes it as `locals.selectedTenant*`;\n * - the signed session (`createSessionHandler({ enterTenantContext: true })`)\n * authorizes the signed-in user's membership and establishes the request\n * tenant context.\n *\n * A selected tenant is useful for login and membership-gated switch flows, but\n * it never becomes ambient query authority by itself. The default selector\n * ignores client-provided tenant headers.\n */\n\nimport type { SmrtClassOptions } from '@happyvertical/smrt-core';\nimport { TenantCollection, TenantStatus } from '@happyvertical/smrt-users';\n\n/** The request fields a tenant selector may read. */\nexport interface TenantSelectionEvent {\n readonly url: URL;\n readonly request: { readonly headers: Headers };\n}\n\n/** URL-derived tenant candidate. Never authorization. */\nexport interface TenantSelection {\n /** Database ID for an active tenant, or null when none resolves. */\n readonly tenantId: string | null;\n /** URL-derived slug. Informational until membership authorizes a switch. */\n readonly tenantSlug: string | null;\n}\n\n/**\n * Replaceable selection extension point. Implementations must preserve the\n * rule that selection alone never establishes authorization context.\n */\nexport type TenantSelector = (\n event: TenantSelectionEvent,\n) => TenantSelection | Promise<TenantSelection>;\n\nconst ROOT_LIKE_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);\nconst RESERVED_SUBDOMAINS = new Set(['www', 'api', 'app', 'admin']);\nconst NO_SELECTION: TenantSelection = Object.freeze({\n tenantId: null,\n tenantSlug: null,\n});\n\n/**\n * Pure URL parser used by the default selector.\n *\n * Set `TENANT_BASE_DOMAIN` (or pass `baseDomain`) in production so\n * multi-label public suffixes are never guessed. Without it, the fallback is\n * intended only for local domains such as `acme.demo.local`.\n */\nexport function selectTenantSlug(\n url: URL,\n baseDomain: string | undefined = process.env.TENANT_BASE_DOMAIN,\n): string | null {\n const hostname = url.hostname.toLowerCase();\n if (\n ROOT_LIKE_HOSTS.has(hostname) ||\n hostname.startsWith('[') ||\n /^\\d{1,3}(\\.\\d{1,3}){3}$/.test(hostname)\n ) {\n return null;\n }\n\n const normalizedBase = baseDomain\n ?.trim()\n .toLowerCase()\n .replace(/^\\.+|\\.+$/g, '');\n\n let candidate: string | undefined;\n if (normalizedBase) {\n if (hostname === normalizedBase) return null;\n const suffix = `.${normalizedBase}`;\n if (!hostname.endsWith(suffix)) return null;\n candidate = hostname.slice(0, -suffix.length).split('.')[0];\n } else {\n const labels = hostname.split('.');\n if (labels.length < 3) return null;\n candidate = labels[0];\n }\n\n return candidate && !RESERVED_SUBDOMAINS.has(candidate) ? candidate : null;\n}\n\nfunction isMissingTenantTable(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n const code = (error as Error & { code?: string }).code;\n return (\n code === '42P01' ||\n error.message.includes('relation \"tenants\" does not exist') ||\n error.message.includes('no such table: tenants')\n );\n}\n\nexport interface SubdomainTenantSelectorOptions {\n /** Explicit public base domain. Defaults to `TENANT_BASE_DOMAIN`. */\n readonly baseDomain?: string;\n /** Collection options for the `Tenant` lookup. */\n readonly classOptions: () => SmrtClassOptions;\n}\n\n/**\n * Default selector: the leading subdomain names an ACTIVE tenant.\n *\n * A missing `tenants` table (a fresh project before its first migration)\n * yields no selection; the runtime never creates that table.\n */\nexport function createSubdomainTenantSelector(\n options: SubdomainTenantSelectorOptions,\n): TenantSelector {\n return async (event) => {\n const tenantSlug = selectTenantSlug(event.url, options.baseDomain);\n if (!tenantSlug) return NO_SELECTION;\n let tenantId: string | null;\n try {\n const tenants = await TenantCollection.create(options.classOptions());\n const tenant = await tenants.findBySlug(tenantSlug);\n tenantId =\n tenant?.status === TenantStatus.ACTIVE ? (tenant.id ?? null) : null;\n } catch (error) {\n if (!isMissingTenantTable(error)) throw error;\n tenantId = null;\n }\n return { tenantId, tenantSlug };\n };\n}\n\n/** Coerce an application selector's result into the published shape. */\nexport function normalizeTenantSelection(\n selection: TenantSelection | null | undefined,\n): TenantSelection {\n const tenantId =\n typeof selection?.tenantId === 'string' && selection.tenantId\n ? selection.tenantId\n : null;\n const tenantSlug =\n typeof selection?.tenantSlug === 'string' && selection.tenantSlug\n ? selection.tenantSlug\n : null;\n return { tenantId, tenantSlug };\n}\n","/**\n * SvelteKit server composition for the validated runtime profiles.\n *\n * Request foundation, in order:\n *\n * 0. Wait for the fail-closed runtime startup gate (`init`).\n * 1. Resolve a URL tenant candidate into `locals.selectedTenant*`. This is\n * selection only and never enters AsyncLocalStorage tenant context.\n * 2. Load the signed session. Its tenant is accepted only for a verified\n * active direct or legitimately inherited membership\n * ({@link isSessionTenantAuthorized}, the deployed runtime's rule);\n * otherwise the request is unauthenticated. An accepted session enters the\n * tenant context and permission set for downstream code, inside the\n * request RLS transaction when the profile selects `database-rls`.\n * 3. Publish the authorized context on `locals.tenantContext` only when it\n * matches the verified session tenant.\n *\n * This ordering prevents a spoofed header or hostname from becoming query\n * authority. Membership-gated tenant switching belongs in an explicit action\n * using `switchSessionTenant()` from `@happyvertical/smrt-users/sveltekit`.\n */\n\nimport {\n loadConfig,\n type ResolvedApplicationRuntime,\n resolveEffectiveApplicationRuntime,\n} from '@happyvertical/smrt-config';\nimport {\n ObjectRegistry,\n type SmrtClassOptions,\n type SmrtCollection,\n type SmrtObject,\n} from '@happyvertical/smrt-core';\nimport { OidcIdentityCollection } from '@happyvertical/smrt-profiles';\nimport {\n enableTenancy,\n getCurrentTenant,\n isTenancyEnabled,\n type MinimalTenantContext,\n withSystemContext,\n} from '@happyvertical/smrt-tenancy';\nimport {\n getCurrentSessionPermissionContext,\n getRequestScopedDatabase,\n MembershipCollection,\n PermissionResolver,\n SessionService,\n type SessionServiceOptions,\n UserCollection,\n UserStatus,\n withPrincipalPermissionContext,\n withSessionPermissionContext,\n} from '@happyvertical/smrt-users';\nimport type {\n SessionHandlerOptions,\n SessionLocals,\n} from '@happyvertical/smrt-users/sveltekit';\nimport { type DatabaseInterface, getDatabase } from '@happyvertical/sql';\nimport type { Handle, ServerInit } from '@sveltejs/kit';\nimport {\n resolveApplicationId,\n runtimeConfigurationFingerprint,\n} from '../application-identity.js';\nimport {\n type DeployedApplicationRuntime,\n type DeployedApplicationRuntimeProfile,\n initializeDeployedApplicationRuntime,\n isSessionTenantAuthorized,\n type PublicAuthenticationProvider,\n} from '../deployed-runtime.js';\nimport {\n resolveBoundMembershipPermissions,\n type TenantBindingMode,\n} from '../direct-membership.js';\nimport {\n initializeLocalApplicationRuntime,\n isLocalMcpTokenPrincipal,\n type LocalApplicationRuntime,\n type LocalMcpTokenPrincipal,\n type LocalOwnerBootstrapInvitation,\n resolveLocalRuntimePaths,\n validateApplicationId,\n} from '../index.js';\nimport {\n deepFrozenPlainCopy,\n ownValue,\n PlainDataError,\n} from '../plain-data.js';\nimport {\n projectRuntimeDiagnostics,\n type RuntimeDiagnostics,\n type RuntimeDiagnosticsProjectionInput,\n} from '../runtime-diagnostics.js';\nimport {\n prepareApplicationStateRoot,\n resolveApplicationStateRoot,\n} from '../state-root.js';\nimport { acquireWriterLease, type WriterLease } from '../writer-lease.js';\nimport {\n createSubdomainTenantSelector,\n normalizeTenantSelection,\n type TenantSelector,\n} from './tenancy.js';\n\n/** `App.Locals` fields populated by the SMRT runtime `handle`. */\nexport interface SmrtRuntimeLocals extends SessionLocals {\n /**\n * URL-selected tenant candidate. Never use this as authorization; the\n * session-authorized tenant remains `tenantId` from {@link SessionLocals}.\n */\n selectedTenantId: string | null;\n selectedTenantSlug: string | null;\n /** Full context for the authorized session tenant, when present. */\n tenantContext?: MinimalTenantContext;\n}\n\n/** Provider component whose readiness a deployed web process must prove. */\nexport type ProviderReadinessComponent =\n | 'authentication'\n | 'assets'\n | 'secrets';\n\n/**\n * Build a provider-owned readiness probe. The probe must check the real\n * backing service and must never return or log credentials.\n */\nexport type ProviderReadinessFactory = (\n component: ProviderReadinessComponent,\n context: { readonly profile: string; readonly provider: string },\n) => () => Promise<void>;\n\n/** Context handed to an application-owned writer lease. */\nexport interface WriterLeaseContext {\n readonly appId: string;\n readonly dataDirectory: string | undefined;\n readonly sourceRoot: string;\n}\n\n/**\n * Held for the life of the local web process; released on failed startup.\n * The root entry's `acquireWriterLease()` returns one.\n */\nexport type { WriterLease } from '../writer-lease.js';\n\n/** Inputs to the public diagnostics projection that only the app can supply. */\nexport interface ApplicationRuntimeDiagnosticsOptions {\n readonly toolNames: readonly string[];\n readonly observedAt: Date;\n /** Application-owned schema verification seam; runtime liveness is not proof. */\n readonly schemaStatus?: 'not-ready' | 'ready' | 'unknown';\n /** Application-owned migration tracker seam; database liveness is not proof. */\n readonly migrationStatus?: 'current' | 'failed' | 'pending' | 'unknown';\n /** Bounded worker seam supplied by the deployment's lease/heartbeat adapter. */\n readonly workerHeartbeatAt?: Date | string | null;\n /** Stable code/timestamp pairs only; raw errors never cross this seam. */\n readonly recentErrors?: readonly {\n readonly code?: unknown;\n readonly at?: unknown;\n }[];\n}\n\n/** Liveness body served by the mounted health route. */\nexport interface RuntimeHealthBody {\n readonly schemaVersion: 1;\n readonly status: 'ready';\n readonly profile: ResolvedApplicationRuntime['profile'];\n /** Local profile only: canonical application ID. */\n readonly application?: string;\n /** Local profile only: managed process instance (`SMRT_PROCESS_INSTANCE`). */\n readonly instance?: string | null;\n /** Local profile only: {@link runtimeConfigurationFingerprint}. */\n readonly configuration?: string;\n}\n\n/** Session-handler options the application may tune. */\nexport type SmrtRuntimeSessionOptions = Omit<\n SessionHandlerOptions,\n 'enterTenantContext'\n>;\n\n/** App-specific options for {@link createSmrtSvelteKitRuntime}. */\nexport interface SmrtSvelteKitRuntimeOptions {\n /**\n * Explicit application ID. Defaults to `SMRT_APP_ID` (strictly validated)\n * or the encoded `package.json` name under `sourceRoot`.\n */\n readonly appId?: string;\n /** Application source checkout. Defaults to `process.cwd()`. */\n readonly sourceRoot?: string;\n /** Local data root. Defaults to `SMRT_DATA_DIR`, then the OS data directory. */\n readonly dataDirectory?: string;\n /** Environment to read. Defaults to `process.env`. */\n readonly env?: NodeJS.ProcessEnv;\n /**\n * Resolved runtime profile. Defaults to `smrt.config` `runtime` when\n * present, otherwise the `local` profile; a present value that is not a\n * runtime block (`null`, `false`, `0`, `''`) fails closed.\n */\n readonly runtime?:\n | ResolvedApplicationRuntime\n | (() => ResolvedApplicationRuntime | Promise<ResolvedApplicationRuntime>);\n /**\n * Explicit, idempotent application migration hook, run during `init`.\n * The runtime never synthesizes application tables itself.\n */\n readonly prepareDatabase?: (db: DatabaseInterface) => Promise<void>;\n /**\n * Local HTTP bind host. Defaults to `HOST`, or `127.0.0.1` when\n * `NODE_ENV=development`. Local production startup without one fails.\n */\n readonly bindHost?: string;\n /** Opt in to persisted local background jobs. Default `SMRT_BACKGROUND_JOBS === 'true'`. */\n readonly backgroundJobs?: boolean;\n /** Opt in to application-defined paid capabilities. Default false. */\n readonly paidCapabilities?: boolean;\n /** Owner-bootstrap token lifetime (1..900 seconds). */\n readonly bootstrapTtlSeconds?: number;\n /** Session lifetime for the owner-bootstrap session cookie. Default 7 days. */\n readonly sessionTtlSeconds?: number;\n /**\n * Local single-writer lease held for the web process, released when local\n * startup fails. Defaults to the state-root writer lease shared with\n * `smrt app` operations ({@link defaultWriterLease}: `writer.lease` under\n * `prepareApplicationStateRoot()`, presenting `SMRT_OPERATION_INSTANCE`).\n * Pass a factory to replace it, or `false` to hold no lease. Deployed\n * profiles never take it.\n */\n readonly acquireWriterLease?:\n | ((context: WriterLeaseContext) => WriterLease)\n | false;\n /**\n * Deployed provider readiness probes. Required by `self-hosted` and `cloud`;\n * deployed startup fails closed without them.\n */\n readonly providerReadiness?: ProviderReadinessFactory;\n /** Replace the default subdomain tenant selector. Selection only. */\n readonly selectTenant?: TenantSelector;\n /** Base domain for the default selector. Defaults to `TENANT_BASE_DOMAIN`. */\n readonly tenantBaseDomain?: string;\n /** Session handler tuning. `enterTenantContext` is always `true`. */\n readonly session?: SmrtRuntimeSessionOptions;\n /** Per-class overrides layered over the runtime database config. */\n readonly classOverrides?: Readonly<Record<string, Partial<SmrtClassOptions>>>;\n /** Call `enableTenancy()` if it is not already enabled. Default true. */\n readonly enableTenancy?: boolean;\n /**\n * Receives an owner-bootstrap invitation that this process's startup newly\n * issued (the plaintext is returned exactly once; only its HMAC is stored).\n * Use it to show a loopback `/setup?token=` URL. Errors are ignored so a\n * failing presenter never blocks startup. Default: not presented.\n */\n readonly onBootstrapInvitation?: (\n invitation: LocalOwnerBootstrapInvitation,\n context: { readonly bindHost: string },\n ) => void;\n /** Testable clock for the local runtime. */\n readonly now?: () => Date;\n}\n\n/** Cookie attributes for a session established outside the session handler. */\nexport interface SmrtRuntimeSessionCookie {\n readonly name: string;\n readonly path: string;\n readonly domain?: string;\n readonly sameSite: 'strict' | 'lax' | 'none';\n /** `undefined` means \"secure when the request is HTTPS\". */\n readonly secure?: boolean;\n readonly maxAgeSeconds: number;\n}\n\nexport type { TenantBindingMode } from '../direct-membership.js';\n\n/** The composed runtime; `handle` and `init` are bound and destructurable. */\n/** A principal a route authenticated itself, for {@link SmrtSvelteKitRuntime.runAsPrincipal}. */\nexport interface SmrtRuntimeBoundPrincipal {\n readonly id: string;\n readonly tenantId?: string | null;\n /** Granted scopes that cap the live permission set (e.g. token scopes). */\n readonly scopes?: readonly string[];\n /**\n * How tenant authority may be established, set by the authenticating\n * adapter (never request input). `direct` (local owner tokens, the default\n * hosted resolver) needs an active direct membership in exactly\n * `tenantId`. `direct-or-inherited` (the default; hosted application-owned\n * mappings) applies the session step's rule: that direct row, or with no\n * direct row, authority inherited from an active inheritable ancestor.\n */\n readonly tenantBinding?: TenantBindingMode;\n}\n\n/** A verified hosted access-token identity (see `McpVerifiedIdentity`). */\nexport interface SmrtRuntimeMcpIdentity {\n /** Exact issuer the token was verified against. */\n readonly issuer: string;\n /** Verified `sub` claim. */\n readonly subject: string;\n}\n\n/** The current account and tenant a hosted MCP identity maps to. */\nexport interface SmrtRuntimeMcpPrincipalMapping {\n readonly id: string;\n readonly tenantId: string;\n readonly kind: 'human';\n /** The default resolver maps only direct memberships. */\n readonly tenantBinding: 'direct';\n}\n\n/** `T` with every nested array and object field readonly. */\nexport type SmrtRuntimeDeepReadonly<T> = T extends readonly (infer U)[]\n ? readonly SmrtRuntimeDeepReadonly<U>[]\n : T extends object\n ? { readonly [K in keyof T]: SmrtRuntimeDeepReadonly<T[K]> }\n : T;\n\n/**\n * The frozen principal `runAsPrincipal` hands its callback: a deep, frozen\n * snapshot of the caller's principal taken before any await, with the\n * effective `tenantBinding` and effective (frozen) `scopes`.\n */\nexport type SmrtRuntimeBoundPrincipalSnapshot<P> = SmrtRuntimeDeepReadonly<\n Omit<P, 'scopes' | 'tenantBinding'>\n> & {\n readonly scopes: readonly string[];\n readonly tenantBinding: TenantBindingMode;\n};\n\nexport interface SmrtSvelteKitRuntime {\n /** `hooks.server.ts` `handle`. */\n readonly handle: Handle;\n /** `hooks.server.ts` `init`: the fail-closed startup gate. */\n readonly init: ServerInit;\n /** Session cookie attributes shared with owner setup. */\n readonly sessionCookie: SmrtRuntimeSessionCookie;\n /** Resolve the runtime profile (memoized; retried after failure). */\n resolvedRuntime(): Promise<ResolvedApplicationRuntime>;\n /** Await profile-specific startup (same promise as `init`). */\n ready(): Promise<void>;\n /** Canonical application ID. */\n applicationId(): string;\n /**\n * Private state root shared with the `smrt app` operator commands (writer\n * lease, operation lock, onboarding hand-off files). Resolves the path only;\n * it does not create it.\n */\n applicationStateRoot(): string;\n /** Secret-free configuration fingerprint. Requires a resolved runtime. */\n configurationFingerprint(): string;\n /**\n * Database for SMRT collections. Requires a resolved runtime. Inside a\n * request running in the RLS transaction (`database-rls` isolation, or\n * `session.postgresRls`) this is the transaction-bound request database;\n * otherwise the base configuration. Call it per request and never retain\n * the result (or collections built from it) beyond that request.\n */\n databaseConfig(): SmrtClassOptions['db'];\n /**\n * Collection options for a class: {@link databaseConfig} plus\n * `classOverrides`. A class whose override sets `db` keeps that database.\n * Same per-request rule as {@link databaseConfig}.\n */\n classOptions(className: string): SmrtClassOptions;\n /**\n * The registered collection for a class, built from {@link classOptions}\n * evaluated on this call: inside an RLS request it is bound to the request\n * transaction. Generated API routes resolve collections through it. Call it\n * per request and never retain the result beyond that request.\n */\n getCollection<T extends SmrtObject = SmrtObject>(\n className: string,\n ): Promise<SmrtCollection<T>>;\n /**\n * Run `fn` as a principal the route verified itself (for example a bearer\n * token mapped by an MCP route), replacing the cookie session's permission\n * context for that call. The principal's permissions are resolved live from\n * its membership in `tenantId` and, when `scopes` is given, capped to it;\n * under the RLS transaction rule of {@link databaseConfig} a fresh\n * transaction publishes that user, tenant and permission set, and\n * `databaseConfig()`/`classOptions()` return it inside `fn`. Rejects (before\n * `fn` runs) without a user id, a tenant, or a membership its\n * `tenantBinding` accepts: `direct` needs an active direct membership in\n * exactly that tenant; `direct-or-inherited` (default) also accepts\n * authority inherited from an active inheritable ancestor when no direct\n * row exists. A suspended or pending direct row is always authoritative.\n *\n * `principal` is read once, before any await: `fn` receives a frozen copy\n * of that snapshot (its effective `tenantBinding`, and `scopes` replaced by\n * the effective, frozen permission set: live permissions capped by the\n * given scopes), never the caller's object. Callers\n * that authorize in code (rather than through database policy, as under\n * `application` isolation) must authorize with these effective scopes so a\n * revoked permission takes effect even while a token still carries it.\n */\n runAsPrincipal<\n T,\n P extends SmrtRuntimeBoundPrincipal = SmrtRuntimeBoundPrincipal,\n >(\n principal: P,\n fn: (bound: SmrtRuntimeBoundPrincipalSnapshot<P>) => Promise<T>,\n ): Promise<T>;\n /**\n * Verify an owner-minted local MCP token (`smrt app token`). Resolves the\n * token's owner principal with its scopes capped to the owner's live\n * permissions, or `null` for anything else: a malformed, unknown, revoked\n * or expired token, an inactive owner or membership, or any non-`local`\n * profile. Pass the runtime as `createHostedMcpResourceAuth({ runtime })`\n * so `/mcp` accepts these tokens in the local profile.\n */\n verifyLocalMcpToken(token: string): Promise<LocalMcpTokenPrincipal | null>;\n /**\n * Default membership-backed hosted MCP principal mapping: the verified\n * issuer/subject must be linked (`oidc_identities`) to exactly one active\n * user with exactly one active direct tenant membership. Anything else\n * (unlinked, ambiguous, inactive, several tenants, the `local` profile)\n * resolves `null`, which denies the request. Token claims never select the\n * tenant. Applications with multi-tenant users pass their own\n * `resolvePrincipal`, which takes precedence.\n */\n resolveMcpPrincipal(\n identity: SmrtRuntimeMcpIdentity,\n ): Promise<SmrtRuntimeMcpPrincipalMapping | null>;\n /** The local runtime. Rejects outside the `local` profile. */\n localRuntime(): Promise<LocalApplicationRuntime>;\n /** The deployed runtime. Rejects in the `local` profile. */\n deployedRuntime(): Promise<DeployedApplicationRuntime>;\n /** Liveness body for the health route (awaits startup). */\n health(): Promise<RuntimeHealthBody>;\n /**\n * Read private runtime state and project it onto the public allowlist.\n * Call only after the route has authenticated and authorized its caller.\n */\n readDiagnostics(\n options: ApplicationRuntimeDiagnosticsOptions,\n ): Promise<RuntimeDiagnostics>;\n}\n\n/** @internal Test and composition seams; not part of the public entry. */\nexport interface SmrtSvelteKitRuntimeSeams {\n readonly initializeLocal?: typeof initializeLocalApplicationRuntime;\n readonly initializeDeployed?: typeof initializeDeployedApplicationRuntime;\n readonly loadRuntime?: () => Promise<ResolvedApplicationRuntime>;\n}\n\nconst DEFAULT_SESSION_TTL_SECONDS = 7 * 24 * 60 * 60;\n\n/**\n * Compose runtime startup, tenant selection, the signed session, and\n * authorized-tenant locals into a SvelteKit `{ handle, init }` pair.\n *\n * @example\n * ```ts\n * // src/hooks.server.ts\n * import { createSmrtSvelteKitRuntime } from '@happyvertical/smrt-app-runtime/sveltekit';\n *\n * export const runtime = createSmrtSvelteKitRuntime();\n * export const { handle, init } = runtime;\n * ```\n */\nexport function createSmrtSvelteKitRuntime(\n options: SmrtSvelteKitRuntimeOptions = {},\n): SmrtSvelteKitRuntime {\n return composeSmrtSvelteKitRuntime(options, {});\n}\n\n/** @internal */\nexport function composeSmrtSvelteKitRuntime(\n options: SmrtSvelteKitRuntimeOptions,\n seams: SmrtSvelteKitRuntimeSeams,\n): SmrtSvelteKitRuntime {\n const env = options.env ?? process.env;\n const sourceRoot = options.sourceRoot ?? process.cwd();\n const dataDirectory = options.dataDirectory ?? env.SMRT_DATA_DIR;\n const initializeLocal =\n seams.initializeLocal ?? initializeLocalApplicationRuntime;\n const initializeDeployed =\n seams.initializeDeployed ?? initializeDeployedApplicationRuntime;\n\n if (options.enableTenancy !== false && !isTenancyEnabled()) {\n enableTenancy();\n }\n\n let appId: string | undefined;\n const applicationId = (): string => {\n appId ??= options.appId\n ? validateApplicationId(options.appId)\n : resolveApplicationId({ sourceRoot, explicitId: env.SMRT_APP_ID });\n return appId;\n };\n\n let resolved: ResolvedApplicationRuntime | undefined;\n let resolvedPromise: Promise<ResolvedApplicationRuntime> | undefined;\n const resolvedRuntime = (): Promise<ResolvedApplicationRuntime> => {\n resolvedPromise ??= (async () => {\n const value =\n typeof options.runtime === 'function'\n ? await options.runtime()\n : (options.runtime ??\n (await (seams.loadRuntime ?? loadConfiguredRuntime)()));\n resolved = value;\n return value;\n })().catch((error: unknown) => {\n resolvedPromise = undefined;\n throw error;\n });\n return resolvedPromise;\n };\n\n const requireResolved = (): ResolvedApplicationRuntime => {\n if (!resolved) {\n throw new Error(\n 'The SMRT application runtime is not resolved yet; await init() first.',\n );\n }\n return resolved;\n };\n\n /** Base (connection-level) database config; never request-scoped. */\n const baseDatabaseConfig = (): SmrtClassOptions['db'] => {\n const runtime = requireResolved();\n if (runtime.profile === 'local') {\n const paths = resolveLocalRuntimePaths({\n appId: applicationId(),\n dataDirectory,\n sourceRoot,\n env,\n });\n return {\n type: 'sqlite',\n url: paths.database,\n secureFile: {\n driver: 'node:sqlite',\n custody: 'trusted-parent',\n root: paths.root,\n },\n };\n }\n const databaseUrl = env.DATABASE_URL;\n if (!databaseUrl) {\n throw new Error(`${runtime.profile} requires DATABASE_URL.`);\n }\n return { type: 'postgres', url: databaseUrl };\n };\n\n /** Base collection options; used for anything that outlives a request. */\n const baseClassOptions = (className: string): SmrtClassOptions => {\n const defaults: SmrtClassOptions = { db: baseDatabaseConfig() };\n const override = options.classOverrides?.[className];\n return override ? { ...defaults, ...override } : defaults;\n };\n\n /**\n * Inside a request running in the RLS transaction, the transaction-bound\n * request database (it carries the `smrt.*` session variables); otherwise\n * undefined. Never cache the returned handle beyond the request.\n */\n const rlsRequestDatabase = (): SmrtClassOptions['db'] | undefined => {\n const context = getCurrentSessionPermissionContext();\n if (context?.postgresRls !== true) return undefined;\n return (getRequestScopedDatabase() ?? undefined) as\n | SmrtClassOptions['db']\n | undefined;\n };\n\n const databaseConfig = (): SmrtClassOptions['db'] =>\n rlsRequestDatabase() ?? baseDatabaseConfig();\n\n const classOptions = (className: string): SmrtClassOptions => {\n const base = baseClassOptions(className);\n if (options.classOverrides?.[className]?.db !== undefined) return base;\n const requestDb = rlsRequestDatabase();\n return requestDb ? { ...base, db: requestDb } : base;\n };\n\n const getCollection = <T extends SmrtObject = SmrtObject>(\n className: string,\n ): Promise<SmrtCollection<T>> =>\n ObjectRegistry.getCollection<T>(className, classOptions(className));\n\n const writerLease =\n options.acquireWriterLease === false\n ? undefined\n : (options.acquireWriterLease ??\n ((context: WriterLeaseContext) => defaultWriterLease(context, env)));\n\n let localPromise: Promise<LocalApplicationRuntime> | undefined;\n let localLease: WriterLease | undefined;\n const localRuntime = async (): Promise<LocalApplicationRuntime> => {\n const runtime = await resolvedRuntime();\n if (runtime.profile !== 'local') {\n throw new Error(\n 'Owner bootstrap is available only in the local profile.',\n );\n }\n if (localPromise) return localPromise;\n const bindHost =\n options.bindHost ||\n env.HOST ||\n (env.NODE_ENV === 'development' ? '127.0.0.1' : null);\n if (!bindHost) {\n throw new Error(\n 'Local production startup requires an explicit loopback HOST; use pnpm app:start.',\n );\n }\n const id = applicationId();\n localLease ??= writerLease?.({\n appId: id,\n dataDirectory,\n sourceRoot,\n });\n localPromise = initializeLocal({\n appId: id,\n dataDirectory,\n sourceRoot,\n env,\n bindHost,\n providers: {\n database: runtime.providers.database,\n authentication: runtime.providers.authentication,\n tenancy: runtime.providers.tenancy,\n assets: runtime.providers.assets,\n secrets: runtime.providers.secrets,\n jobs: runtime.providers.jobs,\n network: runtime.providers.network,\n },\n backgroundJobs:\n options.backgroundJobs ?? env.SMRT_BACKGROUND_JOBS === 'true',\n paidCapabilities: options.paidCapabilities,\n bootstrapTtlSeconds: options.bootstrapTtlSeconds,\n sessionTtlSeconds: options.sessionTtlSeconds,\n prepareDatabase: options.prepareDatabase,\n now: options.now,\n })\n .then(({ runtime: initialized, bootstrap }) => {\n if (bootstrap) {\n try {\n options.onBootstrapInvitation?.(bootstrap, { bindHost });\n } catch {\n // Presentation is best effort; the invitation stays claimable.\n }\n }\n return initialized;\n })\n .catch((error: unknown) => {\n localLease?.release();\n localLease = undefined;\n localPromise = undefined;\n throw error;\n });\n return localPromise;\n };\n\n let deployedPromise: Promise<DeployedApplicationRuntime> | undefined;\n const deployedRuntime = async (): Promise<DeployedApplicationRuntime> => {\n const runtime = await resolvedRuntime();\n if (runtime.profile === 'local') {\n throw new Error('deployed_runtime_unavailable');\n }\n const profile = runtime.profile as DeployedApplicationRuntimeProfile;\n const databaseUrl = env.DATABASE_URL;\n if (!databaseUrl) {\n throw new Error(`${profile} requires DATABASE_URL.`);\n }\n const authenticationProvider = runtime.providers.authentication.provider;\n if (authenticationProvider === 'owner-bootstrap') {\n throw new Error('Deployed profiles require public authentication.');\n }\n const readiness = options.providerReadiness;\n if (!readiness) {\n throw new Error(\n `${profile} requires providerReadiness probes for authentication, assets, and secrets.`,\n );\n }\n deployedPromise ??= initializeDeployed({\n profile,\n providers: {\n database: runtime.providers.database,\n authentication: runtime.providers.authentication,\n tenancy: runtime.providers.tenancy,\n assets: runtime.providers.assets,\n secrets: runtime.providers.secrets,\n jobs: runtime.providers.jobs,\n network: runtime.providers.network,\n },\n database: {\n engine: 'postgres',\n connect: () => getDatabase({ type: 'postgres', url: databaseUrl }),\n close: async (db) => {\n await db.close?.();\n },\n },\n authentication: {\n provider: authenticationProvider as PublicAuthenticationProvider,\n readiness: readiness('authentication', {\n profile,\n provider: authenticationProvider,\n }),\n },\n assets: {\n provider: runtime.providers.assets.provider,\n readiness: readiness('assets', {\n profile,\n provider: runtime.providers.assets.provider,\n }),\n },\n secrets: {\n provider: runtime.providers.secrets.provider,\n readiness: readiness('secrets', {\n profile,\n provider: runtime.providers.secrets.provider,\n }),\n },\n prepareDatabase: options.prepareDatabase,\n });\n return deployedPromise;\n };\n\n const ready = async (): Promise<void> => {\n const runtime = await resolvedRuntime();\n if (runtime.profile === 'local') {\n await localRuntime();\n return;\n }\n await deployedRuntime();\n };\n\n const configurationFingerprint = (): string =>\n runtimeConfigurationFingerprint(requireResolved(), env);\n\n const health = async (): Promise<RuntimeHealthBody> => {\n await ready();\n const runtime = requireResolved();\n const publicHealth = {\n schemaVersion: 1 as const,\n status: 'ready' as const,\n profile: runtime.profile,\n };\n return runtime.profile === 'local'\n ? {\n ...publicHealth,\n application: applicationId(),\n instance: env.SMRT_PROCESS_INSTANCE || null,\n configuration: configurationFingerprint(),\n }\n : publicHealth;\n };\n\n const readDiagnostics = async (\n diagnosticsOptions: ApplicationRuntimeDiagnosticsOptions,\n ): Promise<RuntimeDiagnostics> => {\n await ready();\n const runtime = requireResolved();\n const schema = {\n status: diagnosticsOptions.schemaStatus ?? 'unknown',\n migrations: diagnosticsOptions.migrationStatus ?? 'unknown',\n } as const;\n\n if (runtime.profile === 'local') {\n const local = await localRuntime();\n const diagnostics = await local.diagnostics();\n return projectRuntimeDiagnostics({\n profile: 'local',\n health: 'healthy',\n schema,\n capabilities: {\n 'asset-storage': 'available',\n authentication: 'available',\n 'background-jobs': diagnostics.jobs.backgroundEnabled\n ? 'available'\n : 'disabled',\n database: 'available',\n 'paid-capabilities': diagnostics.paidCapabilitiesEnabled\n ? 'available'\n : 'disabled',\n 'secret-storage': 'available',\n },\n toolNames: diagnosticsOptions.toolNames,\n worker: {\n topology: diagnostics.jobs.topology,\n required: diagnostics.jobs.backgroundEnabled,\n heartbeatAt: diagnosticsOptions.workerHeartbeatAt,\n },\n recentErrors: diagnosticsOptions.recentErrors,\n observedAt: diagnosticsOptions.observedAt,\n });\n }\n\n const deployed = await deployedPromise;\n if (!deployed) throw new Error('deployed_runtime_unavailable');\n const readiness = await deployed.readiness();\n const componentStatus = (\n component: keyof typeof readiness.components,\n ): 'available' | 'unavailable' =>\n readiness.components[component].status === 'ready'\n ? 'available'\n : 'unavailable';\n const input: RuntimeDiagnosticsProjectionInput = {\n profile: runtime.profile,\n health:\n deployed.health().status === 'healthy'\n ? readiness.status === 'ready'\n ? 'healthy'\n : 'degraded'\n : 'stopped',\n schema,\n capabilities: {\n 'asset-storage': componentStatus('assets'),\n authentication: componentStatus('authentication'),\n 'background-jobs': 'available',\n database: componentStatus('database'),\n 'paid-capabilities': 'unknown',\n 'secret-storage': componentStatus('secrets'),\n },\n toolNames: diagnosticsOptions.toolNames,\n worker: {\n topology: deployed.resolvedRuntime.providers.jobs.topology,\n required: true,\n heartbeatAt: diagnosticsOptions.workerHeartbeatAt,\n },\n recentErrors: diagnosticsOptions.recentErrors,\n observedAt: diagnosticsOptions.observedAt,\n };\n return projectRuntimeDiagnostics(input);\n };\n\n const selectTenant: TenantSelector =\n options.selectTenant ??\n createSubdomainTenantSelector({\n baseDomain: options.tenantBaseDomain ?? env.TENANT_BASE_DOMAIN,\n classOptions: () => baseClassOptions('Tenant'),\n });\n\n const readinessHandle: Handle = async ({ event, resolve }) => {\n await ready();\n return resolve(event);\n };\n\n const tenantSelectionHandle: Handle = async ({ event, resolve }) => {\n const locals = runtimeLocals(event.locals);\n const selection = normalizeTenantSelection(\n await selectTenant({ url: event.url, request: event.request }),\n );\n locals.selectedTenantId = selection.tenantId;\n locals.selectedTenantSlug = selection.tenantSlug;\n return resolve(event);\n };\n\n const sessionCookieName = options.session?.cookieName ?? 'sid';\n const sessionSkipPaths = options.session?.skipPaths ?? [];\n const sessionServiceOptions = (): SessionServiceOptions => ({\n ...baseClassOptions('Session'),\n ...options.session,\n defaultTTL: options.session?.ttl ?? DEFAULT_SESSION_TTL_SECONDS,\n autoExtend: options.session?.autoExtend ?? false,\n });\n /** `database-rls` isolation always runs the request RLS transaction. */\n const postgresRls = (): boolean | undefined =>\n requireResolved().providers.tenancy.isolation === 'database-rls'\n ? true\n : options.session?.postgresRls;\n let permissionResolverPromise: Promise<PermissionResolver> | undefined;\n const permissionResolver = (): Promise<PermissionResolver> => {\n permissionResolverPromise ??= PermissionResolver.create(\n baseClassOptions('Permission'),\n ).catch((error: unknown) => {\n permissionResolverPromise = undefined;\n throw error;\n });\n return permissionResolverPromise;\n };\n\n const runAsPrincipal = async <\n T,\n P extends SmrtRuntimeBoundPrincipal = SmrtRuntimeBoundPrincipal,\n >(\n principal: P,\n fn: (bound: SmrtRuntimeBoundPrincipalSnapshot<P>) => Promise<T>,\n ): Promise<T> => {\n // One complete snapshot before the first await: authorization, the\n // permission/RLS context and the principal handed to `fn` all come from\n // it, and the caller's object is never read again (a caller mutating it\n // mid-flight cannot change the bound identity, tenant, binding or scopes).\n if (!principal || typeof principal !== 'object') {\n throw new Error('A bound principal is required.');\n }\n const snapshot = snapshotBoundPrincipal(principal) as P;\n // The snapshot has a null prototype: every read below is own data.\n const tokenDerived = isLocalMcpTokenPrincipal(snapshot);\n const userId = ownValue(snapshot, 'id') as P['id'];\n const tenantId = ownValue(snapshot, 'tenantId') as P['tenantId'];\n const snapshotScopes = ownValue(snapshot, 'scopes') as\n | readonly string[]\n | undefined;\n const requestedTenantBinding = ownValue(snapshot, 'tenantBinding') as\n | TenantBindingMode\n | undefined;\n const requestedScopes =\n snapshotScopes === undefined\n ? undefined\n : Object.freeze([...snapshotScopes]);\n if (\n requestedScopes !== undefined &&\n !requestedScopes.every((scope) => typeof scope === 'string')\n ) {\n throw new Error('A bound principal has malformed scopes.');\n }\n if (typeof userId !== 'string' || userId.length === 0) {\n throw new Error('A bound principal requires a user id.');\n }\n if (typeof tenantId !== 'string' || tenantId.length === 0) {\n throw new Error('A bound principal requires a tenant.');\n }\n // Resolution reads the base connection, before any RLS transaction opens.\n // A token-derived principal is direct-only. A copy that tries to widen\n // its binding is refused rather than silently narrowed.\n if (\n tokenDerived &&\n requestedTenantBinding !== undefined &&\n requestedTenantBinding !== 'direct'\n ) {\n throw new Error(\n 'A local MCP token principal binds only through its direct membership.',\n );\n }\n const binding: TenantBindingMode = tokenDerived\n ? 'direct'\n : (requestedTenantBinding ?? 'direct-or-inherited');\n if (binding !== 'direct' && binding !== 'direct-or-inherited') {\n throw new Error('Unknown tenant binding mode for a bound principal.');\n }\n const resolved = await resolveBoundMembershipPermissions({\n memberships: await MembershipCollection.create(\n baseClassOptions('Membership'),\n ),\n resolver: await permissionResolver(),\n userId,\n tenantId,\n binding,\n });\n if (!resolved) {\n throw new Error(\n binding === 'direct'\n ? 'The bound principal has no active direct membership in its tenant.'\n : 'The bound principal has no authorized membership in its tenant.',\n );\n }\n const cap = requestedScopes ? new Set(requestedScopes) : undefined;\n const permissions = [...resolved.permissions].filter(\n (permission) => !cap || cap.has(permission),\n );\n return withPrincipalPermissionContext(\n {\n ...baseClassOptions('Session'),\n userId,\n tenantId,\n permissions,\n enterTenantContext: true,\n postgresRls: postgresRls(),\n },\n () =>\n fn(\n // Null prototype like the snapshot: a field the principal lacks\n // (say `allowCrossTenant`) never resolves to an inherited value.\n Object.freeze(\n Object.assign(Object.create(null), snapshot, {\n id: userId,\n tenantId,\n tenantBinding: binding,\n scopes: Object.freeze([...permissions]),\n }),\n ) as SmrtRuntimeBoundPrincipalSnapshot<P>,\n ),\n );\n };\n\n const verifyLocalMcpToken = async (\n token: string,\n ): Promise<LocalMcpTokenPrincipal | null> => {\n if ((await resolvedRuntime()).profile !== 'local') return null;\n const local = await localRuntime();\n // A runtime without a token store has no tokens: fail closed.\n return (await local.mcpTokens?.verify(token)) ?? null;\n };\n\n const resolveMcpPrincipal = async (\n identity: SmrtRuntimeMcpIdentity,\n ): Promise<SmrtRuntimeMcpPrincipalMapping | null> => {\n if ((await resolvedRuntime()).profile === 'local') return null;\n if (!identity || typeof identity !== 'object') return null;\n const issuer = ownValue(identity, 'issuer');\n const subject = ownValue(identity, 'subject');\n if (\n typeof issuer !== 'string' ||\n issuer.length === 0 ||\n typeof subject !== 'string' ||\n subject.length === 0\n ) {\n return null;\n }\n // Every read is keyed by the verified issuer/subject and the ids derived\n // from it, and only ids leave this block (the PermissionResolver rule).\n return withSystemContext(async () => {\n const identities = await OidcIdentityCollection.create(\n baseClassOptions('OidcIdentity'),\n );\n let linked: Awaited<ReturnType<typeof identities.findBySubject>>;\n try {\n linked = await identities.findBySubject(issuer, subject);\n } catch {\n return null; // Ambiguous identity: deny.\n }\n if (!linked?.profileId) return null;\n const users = await UserCollection.create(baseClassOptions('User'));\n const owners = await users.list({\n where: { profileId: linked.profileId },\n limit: 2,\n });\n const user = owners.length === 1 ? owners[0] : undefined;\n if (\n typeof user?.id !== 'string' ||\n user.id.length === 0 ||\n user.status !== UserStatus.ACTIVE\n ) {\n return null;\n }\n const memberships = await MembershipCollection.create(\n baseClassOptions('Membership'),\n );\n const tenants = new Set(\n (await memberships.findActiveByUser(user.id))\n .map((membership) => membership.tenantId)\n .filter(\n (tenantId): tenantId is string =>\n typeof tenantId === 'string' && tenantId.length > 0,\n ),\n );\n if (tenants.size !== 1) return null;\n const [tenantId] = tenants;\n return Object.freeze({\n id: user.id,\n tenantId,\n kind: 'human' as const,\n tenantBinding: 'direct' as const,\n });\n });\n };\n\n let sessionServicePromise: Promise<SessionService> | undefined;\n const sessionService = (): Promise<SessionService> => {\n sessionServicePromise ??= (async () => {\n const service = new TenantAuthorizingSessionService(\n sessionServiceOptions(),\n requireResolved().providers.tenancy.context === 'required',\n );\n await service.initialize();\n return service;\n })().catch((error: unknown) => {\n sessionServicePromise = undefined;\n throw error;\n });\n return sessionServicePromise;\n };\n\n /**\n * Step 2. Downstream code runs at most once: a downstream throw (or a\n * failure after `resolve` was entered, such as an RLS commit) propagates\n * unchanged and `resolve` is never re-entered. A session-layer failure\n * before `resolve` fails closed with 500 and no authenticated locals, for\n * both RLS and non-RLS isolation.\n */\n const sessionStep: Handle = async ({ event, resolve }) => {\n const locals = runtimeLocals(event.locals);\n clearSessionLocals(locals);\n const rls = postgresRls();\n // A skipped path skips session loading only. Under RLS it still runs in\n // the request transaction, as an anonymous principal.\n const skipped = sessionSkipPaths.some((path) =>\n event.url.pathname.startsWith(path),\n );\n if (skipped && !rls) return resolve(event);\n const sessionId = skipped\n ? undefined\n : event.cookies.get(sessionCookieName);\n if (!sessionId && !rls) return resolve(event);\n\n let resolveEntered = false;\n let downstream: { error: unknown } | undefined;\n try {\n const service = await sessionService();\n return await withSessionPermissionContext(\n {\n ...sessionServiceOptions(),\n enterTenantContext: true,\n postgresRls: rls,\n sessionId: sessionId ?? null,\n sessionService: service,\n },\n async (context) => {\n if (context.session) {\n locals.user = context.user;\n locals.membership = context.membership ?? null;\n locals.permissions = context.permissions;\n locals.tenantId = context.tenantId;\n locals.sessionId = context.sessionId;\n if (context.tenantId) {\n verifiedSessionTenants.set(locals, context.tenantId);\n }\n }\n resolveEntered = true;\n try {\n return await resolve(event);\n } catch (error) {\n downstream = { error };\n throw error;\n }\n },\n );\n } catch (error) {\n if (downstream) throw downstream.error;\n if (resolveEntered) throw error;\n clearSessionLocals(locals);\n return new Response('Internal Server Error', { status: 500 });\n }\n };\n\n const sessionCookie: SmrtRuntimeSessionCookie = Object.freeze({\n name: options.session?.cookieName ?? 'sid',\n path: options.session?.cookiePath ?? '/',\n ...(options.session?.cookieDomain\n ? { domain: options.session.cookieDomain }\n : {}),\n sameSite: options.session?.cookieSameSite ?? 'lax',\n ...(options.session?.cookieSecure !== undefined\n ? { secure: options.session.cookieSecure }\n : {}),\n maxAgeSeconds: options.sessionTtlSeconds ?? DEFAULT_SESSION_TTL_SECONDS,\n });\n\n const init: ServerInit = () => ready();\n\n return Object.freeze({\n handle: composeHandles(\n readinessHandle,\n tenantSelectionHandle,\n sessionStep,\n authorizedTenantLocalsHandle,\n ),\n init,\n sessionCookie,\n resolvedRuntime,\n ready,\n applicationId,\n applicationStateRoot: () =>\n resolveApplicationStateRoot({\n appId: applicationId(),\n dataDirectory,\n sourceRoot,\n }),\n configurationFingerprint,\n databaseConfig,\n classOptions,\n getCollection,\n runAsPrincipal,\n verifyLocalMcpToken,\n resolveMcpPrincipal,\n localRuntime,\n deployedRuntime,\n health,\n readDiagnostics,\n });\n}\n\n/**\n * The default local writer lease: the state-root `writer.lease` shared with\n * `smrt app` operations, presenting the managed operation instance\n * (`SMRT_OPERATION_INSTANCE`) that `smrt app start` passes to its writer.\n */\nexport function defaultWriterLease(\n context: WriterLeaseContext,\n env: NodeJS.ProcessEnv = process.env,\n): WriterLease {\n return acquireWriterLease(\n prepareApplicationStateRoot({\n appId: context.appId,\n dataDirectory: context.dataDirectory,\n sourceRoot: context.sourceRoot,\n }),\n { operationInstance: env.SMRT_OPERATION_INSTANCE },\n );\n}\n\n/** Locals whose session tenant passed {@link isSessionTenantAuthorized}. */\nconst verifiedSessionTenants = new WeakMap<object, string>();\n\n/**\n * Session service whose loaded context carries a tenant only when that\n * tenant passed {@link isSessionTenantAuthorized}. A session bound to an\n * unauthorized tenant (or missing a required tenant) loads as no session, so\n * no identity, permissions, or tenant context is established for it.\n */\nclass TenantAuthorizingSessionService extends SessionService {\n private readonly tenantRequired: boolean;\n\n constructor(options: SessionServiceOptions, tenantRequired: boolean) {\n super(options);\n this.tenantRequired = tenantRequired;\n }\n\n override async loadSessionContext(\n sessionId: string,\n ): ReturnType<SessionService['loadSessionContext']> {\n const context = await super.loadSessionContext(sessionId);\n if (!context) return null;\n if (typeof context.tenantId === 'string' && context.tenantId.length > 0) {\n return isSessionTenantAuthorized(context) ? context : null;\n }\n return this.tenantRequired ? null : context;\n }\n}\n\nfunction clearSessionLocals(locals: SmrtRuntimeLocals): void {\n locals.user = null;\n locals.membership = null;\n locals.permissions = [];\n locals.tenantId = null;\n locals.sessionId = null;\n locals.tenantContext = undefined;\n verifiedSessionTenants.delete(locals);\n}\n\n/**\n * Step 3: publish the authorized tenant context only when this runtime's\n * session step verified the session tenant and it matches the active\n * AsyncLocalStorage context. Locals populated by any other session layer are\n * never published.\n */\nexport const authorizedTenantLocalsHandle: Handle = async ({\n event,\n resolve,\n}) => {\n const locals = runtimeLocals(event.locals);\n const activeContext = getCurrentTenant();\n if (\n locals.user &&\n locals.tenantId &&\n verifiedSessionTenants.get(locals) === locals.tenantId &&\n activeContext?.tenantId === locals.tenantId\n ) {\n locals.tenantContext = activeContext;\n }\n return resolve(event);\n};\n\n/**\n * Run handles in order. Unlike `sequence()` from `@sveltejs/kit/hooks`, this\n * needs no SvelteKit request store, so the composed handle is usable (and\n * testable) outside the Kit server runtime. The runtime's own handles never\n * pass resolve options; any options a handle passes are forwarded unchanged.\n */\nexport function composeHandles(...handles: readonly Handle[]): Handle {\n return ({ event, resolve }) => {\n const run: (\n index: number,\n current: Parameters<Handle>[0]['event'],\n resolveOptions?: Parameters<Parameters<Handle>[0]['resolve']>[1],\n ) => ReturnType<Handle> = (index, current, resolveOptions) => {\n const next = handles[index];\n if (!next) return resolve(current, resolveOptions);\n return next({\n event: current,\n resolve: (nextEvent, nextOptions) =>\n run(index + 1, nextEvent, nextOptions ?? resolveOptions),\n });\n };\n return run(0, event);\n };\n}\n\nfunction runtimeLocals(locals: unknown): SmrtRuntimeLocals {\n return locals as SmrtRuntimeLocals;\n}\n\n/**\n * No `runtime` block selects `local`; a present non-block value fails closed.\n * Shared with `smrt app` through smrt-config (#3446).\n */\nasync function loadConfiguredRuntime(): Promise<ResolvedApplicationRuntime> {\n return resolveEffectiveApplicationRuntime(await loadConfig());\n}\n\n/**\n * Deep, frozen, validated copy of a bound principal, taken before any await\n * (see `plain-data.ts` for what is rejected: poison keys, accessors,\n * inherited or non-plain data, sparse arrays, functions, deep nesting).\n * Known fields are type-checked from own data (`id`, `tenantId`, `kind`,\n * `tenantBinding`: strings; `scopes`, `roles`: string arrays;\n * `allowCrossTenant`: boolean). Other own enumerable fields (string or\n * symbol keys) are kept as deep-frozen copies.\n */\nfunction snapshotBoundPrincipal(\n principal: unknown,\n): Record<PropertyKey, unknown> {\n if (!principal || typeof principal !== 'object' || Array.isArray(principal)) {\n throw new Error('A bound principal is required.');\n }\n let snapshot: Record<PropertyKey, unknown>;\n try {\n snapshot = deepFrozenPlainCopy(principal) as Record<PropertyKey, unknown>;\n } catch (error) {\n if (error instanceof PlainDataError) {\n throw new Error(`A bound principal ${error.message}.`);\n }\n throw error;\n }\n for (const key of ['id', 'tenantId', 'kind', 'tenantBinding']) {\n const value = ownValue(snapshot, key);\n if (value !== undefined && typeof value !== 'string') {\n throw new Error(`A bound principal has a malformed ${key}.`);\n }\n }\n for (const key of ['scopes', 'roles']) {\n const value = ownValue(snapshot, key);\n if (\n value !== undefined &&\n (!Array.isArray(value) ||\n !value.every((entry) => typeof entry === 'string'))\n ) {\n throw new Error(`A bound principal has malformed ${key}.`);\n }\n }\n const allowCrossTenant = ownValue(snapshot, 'allowCrossTenant');\n if (allowCrossTenant !== undefined && typeof allowCrossTenant !== 'boolean') {\n throw new Error('A bound principal has a malformed allowCrossTenant.');\n }\n return snapshot;\n}\n"],"mappings":";;;;;;;;;AAiBO,IAAM,sCAAsC;AAU5C,SAAS,2BACd,SACgB;CAChB,OAAO,YAAY,KAAK,MAAM,QAAQ,OAAO,CAAC;AAChD;AA8CA,SAAS,kBACP,OACe;CACf,OAAO,OAAO,UAAU,aAAc,MAAkB,IAAI;AAC9D;AAWO,SAAS,gCACd,SACgB;CAChB,MAAM,UAAU,QAAQ;CACxB,MAAM,kBACJ,QAAQ,oBACP,gBAEK,QAAQ,gBAAgB;EACtB,WAAW,kBAAkB,QAAQ,SAAS,KAAK,CAAC;EACpD,YAAY,QAAQ,MAAM,qBAAK,IAAI,KAAK;EACxC,cAAc,kBAAkB,QAAQ,YAAY,KAAK;EACzD,iBACE,kBAAkB,QAAQ,eAAe,KAAK;EAChD,mBAAmB,QAAQ,oBAAoB,KAAK;EACpD,cAAc,QAAQ,eAAe,KAAK,CAAC;CAC7C,CAAC,IACH,KAAA;CACN,MAAM,kBACJ,QAAQ,oBACP,UACG,OAAO,WAAmB;EACxB,MAAM,SAAS,QAAQ,aAAa,MAAM;EAC1C,MAAM,YAAY,yBAAyB;EAM3C,QAAQ,OAAM,MALM,eAAe,OACjC,YACI;GAAE,GAAG;GAAQ,IAAI;EAA8B,IAC/C,MACN,EAAA,CACoB,SAAS,MAAM,EAAA,EAAI,QAAQ;CACjD,IACA,KAAA;CACN,IAAI,CAAC,mBAAmB,CAAC,iBACvB,MAAM,IAAI,UACR,sGACF;CAEF,MAAM,gBACJ,QAAQ,mBACN,UACA,MAAM;CAEV,OAAO,OAAO,UAAU;EACtB,MAAM,SAAS,cAAc,KAAK;EAClC,MAAM,YAAY,uBAAuB,MAAM;EAC/C,IAAI,CAAC,WAAW,OAAO,YAAY,KAAK,yBAAyB;EAEjE,IAAI,aACF,OAAO,aAAa,SAAS,mCAAmC,MAChE;EACF,IAAI,C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AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@happyvertical/smrt-app-runtime",
|
|
3
|
-
"version": "0.54.
|
|
3
|
+
"version": "0.54.4",
|
|
4
4
|
"description": "Validated local, self-hosted, and cloud runtime composition for s-m-r-t applications",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -29,16 +29,16 @@
|
|
|
29
29
|
}
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@happyvertical/smrt-config": "0.54.
|
|
33
|
-
"@happyvertical/smrt-core": "0.54.
|
|
34
|
-
"@happyvertical/smrt-jobs": "0.54.
|
|
35
|
-
"@happyvertical/smrt-profiles": "0.54.
|
|
36
|
-
"@happyvertical/smrt-tenancy": "0.54.
|
|
37
|
-
"@happyvertical/smrt-users": "0.54.
|
|
38
|
-
"@happyvertical/sql": "^0.
|
|
32
|
+
"@happyvertical/smrt-config": "0.54.4",
|
|
33
|
+
"@happyvertical/smrt-core": "0.54.4",
|
|
34
|
+
"@happyvertical/smrt-jobs": "0.54.4",
|
|
35
|
+
"@happyvertical/smrt-profiles": "0.54.4",
|
|
36
|
+
"@happyvertical/smrt-tenancy": "0.54.4",
|
|
37
|
+
"@happyvertical/smrt-users": "0.54.4",
|
|
38
|
+
"@happyvertical/sql": "^0.102.1"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
|
-
"@happyvertical/smrt-vitest": "0.54.
|
|
41
|
+
"@happyvertical/smrt-vitest": "0.54.4",
|
|
42
42
|
"@sveltejs/kit": "2.70.3",
|
|
43
43
|
"@types/node": "24.13.6",
|
|
44
44
|
"tsx": "^4.23.13",
|