@luckystack/core 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/bootUuid.d.ts +16 -0
  3. package/dist/{chunk-PN2FPJXI.js → chunk-55YXIACQ.js} +1 -1
  4. package/dist/chunk-55YXIACQ.js.map +1 -0
  5. package/dist/{chunk-RC7ZQBO6.js → chunk-EZIBIQXO.js} +3 -3
  6. package/dist/{chunk-C4AK6P5D.js → chunk-NJULJZ3N.js} +29 -17
  7. package/dist/chunk-NJULJZ3N.js.map +1 -0
  8. package/dist/{chunk-6UPWMV6L.js → chunk-YKVBUWB6.js} +2 -2
  9. package/dist/chunk-YKVBUWB6.js.map +1 -0
  10. package/dist/client.d.ts +1 -1
  11. package/dist/client.js +74 -12
  12. package/dist/client.js.map +1 -1
  13. package/dist/config.js +2 -2
  14. package/dist/deployConfigRegistry.d.ts +3 -1
  15. package/dist/emailRegistry.d.ts +2 -1
  16. package/dist/errorTrackerIdentity.d.ts +2 -0
  17. package/dist/index.d.ts +3 -3
  18. package/dist/index.js +134 -31
  19. package/dist/index.js.map +1 -1
  20. package/dist/localSocketEnumerationGuard.d.ts +2 -1
  21. package/dist/middlewareRegistry.d.ts +13 -1
  22. package/dist/{projectConfig-EOJRMH36.js → projectConfig-6QNMG5GZ.js} +2 -2
  23. package/dist/projectConfig.d.ts +13 -9
  24. package/dist/react/languageOverride.d.ts +8 -0
  25. package/dist/redactedLogKeys.d.ts +2 -0
  26. package/dist/roomNameFormatterRegistry.d.ts +7 -5
  27. package/dist/{sentrySetup-T7535RYZ.js → sentrySetup-MZTUOMHL.js} +3 -3
  28. package/dist/sessionProviderRegistry.d.ts +14 -6
  29. package/package.json +1 -1
  30. package/dist/chunk-6UPWMV6L.js.map +0 -1
  31. package/dist/chunk-C4AK6P5D.js.map +0 -1
  32. package/dist/chunk-PN2FPJXI.js.map +0 -1
  33. /package/dist/{chunk-RC7ZQBO6.js.map → chunk-EZIBIQXO.js.map} +0 -0
  34. /package/dist/{projectConfig-EOJRMH36.js.map → projectConfig-6QNMG5GZ.js.map} +0 -0
  35. /package/dist/{sentrySetup-T7535RYZ.js.map → sentrySetup-MZTUOMHL.js.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -5,6 +5,39 @@ All notable changes to `@luckystack/core` are documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.15.0] - 2026-10-19
9
+
10
+ ### Added
11
+
12
+ - **`resolvePageMiddleware(path)`** on `@luckystack/core/client` finds the per-page guard for a URL by route pattern. It ignores letter case, a trailing slash, the query and the hash, fills `:param` segments and supports a trailing `*`.
13
+ - **`registerPageRoute(pattern)`** on `@luckystack/core/client` declares a page route whether or not it has a guard. `resolvePageMiddleware` picks the best-matching route first and returns that route's guard, so a page without a guard (`/about`) never gets the guard of a less specific page that loaded earlier (`/:slug`). The scaffold's `src/main.tsx` registers every page; without it only guarded pages are candidates.
14
+ - **`SessionSaveOptions.onlyIfExists`.** A save with this option updates an existing session only: when the session was deleted in the meantime, the provider must not recreate it and returns `{ ok: false, errorCode: 'session.notFound' }`. Custom providers registered with `registerSessionProvider` should honour it (ADR 0077).
15
+ - **`hasErrorTrackerIdentityScope()`** tells whether a request identity scope is active, also for an anonymous request. Error-tracker adapters use it to keep anonymous requests anonymous (ADR 0085).
16
+
17
+ ### Changed
18
+
19
+ - **Breaking:** a real environment variable (shell, Docker, Kubernetes, CI) now beats every env file, including `.env.local` and later `LUCKYSTACK_ENV_FILES` entries, as documented. Before, `.env.local` silently replaced the orchestrator's value. Between files the later file still wins (ADR 0076). Upgrade: if you relied on `.env.local` overriding an exported or container variable, unset that variable or change it at the source.
20
+ - **Breaking:** `registerEmailSenders({...})` replaces the whole registry; without a `default` slot there is no default sender any more. Before, the sender `@luckystack/email/register` picked at boot (often the ConsoleSender) stayed as a hidden default, so mail without a hint was written in full to the server log and reported as sent. Upgrade: add a `default` slot if you call `registerEmailSenders` and send mail without `adapter`, or with an `adapterHint` whose slot is not registered.
21
+ - **Breaking:** the boot UUID Redis key includes the project name (`luckystack:boot:<project>:<env>`), so projects that share one Redis no longer overwrite each other's boot UUID and health signature. New export `bootUuidKey(envKey)` (ADR 0074). The project part reads `PROJECT_NAME` only (default `luckystack`), never `session.projectName`, because the router CLI does not load `config.ts`. Upgrade: upgrade `@luckystack/router` and every backend together, and give them the same `PROJECT_NAME`.
22
+ - The `socket.activityHeartbeatThrottleMs` JSDoc names its actual reader, the client activity tracker; `@luckystack/presence` does not read it.
23
+
24
+ ### Fixed
25
+
26
+ - **Per-page route guards run for every URL that renders the page:** another letter case (`/ADMIN`), a trailing slash, filled-in dynamic segments (`/orders/123`), percent-encoded segments, and `useRouter().navigate()` targets with a `?query` or `#hash`. Before, these URLs skipped the page guard and fell back to the global handler, which allows by default. A page whose guard should block may now redirect or deny where it used to render.
27
+ - **Removing a hook handler during a dispatch no longer makes the dispatch skip the next handler.** Hot reload, a tenant toggle or a handler that removes itself could skip, for example, an authorization hook that should have stopped the request. This applies to async and sync hooks.
28
+ - **Route inputs typed as an intersection of object types** (`BaseInput & { extra: string }`) no longer reject every valid payload, in development and production. An intersection inside an object type, or an `&` inside a string literal, no longer causes a false "input nesting exceeds the maximum depth" error.
29
+ - **Route inputs with a quote or backslash in a string literal type** (`"it's"`) accept the matching value.
30
+ - **Route inputs typed with Prisma JSON types** (`JsonValue`, `InputJsonValue`, `JsonObject`, `JsonArray`) are validated as JSON data instead of being rejected as an unresolved type. Non-JSON values (Dates, `NaN`, class instances) and the keys `__proto__`, `constructor` and `prototype` are rejected, and nesting depth is bounded.
31
+ - **Log and error-tracker redaction ignores `-` and `_` in key names** (`api_key`, `x-api-key`, `set_cookie`, `recovery_codes`) and also masks `secretKey`- and `privateKey`-style keys. This holds for context objects and for `key=value`/`key: value` text in error messages and stacks (`GET /x?api_key=…`, `x-api-key: …`, `stripe_secret_key=…`).
32
+ - **`sanitizeForLog`, which runs on every error-tracker context, copies an object that appears twice** (`{ actor: user, target: user }`) instead of replacing the second one with `'[circular]'`. Only real loops are marked.
33
+ - **The error-tracker scrubber also removes** `Authorization: Bearer …`/`Basic …` values, JSON-style `"password":"…"`, quoted values (`token: 'abc'`) and spaced assignments (`password = x`) from error messages, stacks and captured messages. Before, only `key=value` and `key: value` up to the first space were removed.
34
+ - **`extractTokenFromRequest` and `extractTokenFromSocket` read the session cookie under its prefixed name** when `http.sessionCookiePrefix` is set (see `@luckystack/server` 0.15.0).
35
+ - **The development guard against per-instance socket enumeration also covers namespaces reached through `io.of(...)`.** Production is unchanged.
36
+ - **The development `console.log` replacement** no longer turns objects after a leading string into `[object Object]`, and keeps an error's stack.
37
+ - **`useUpdateLanguage()` previews** (such as the settings page's language dropdown) are no longer reverted to the session language within 250 ms. The preview holds until the language source itself changes, for example after saving.
38
+ - **The client `preLogin` hook fires only on a real login** (no session → session, or a different user), not on same-user session updates such as a room join or an avatar change. A veto on such an update used to log the UI out while the server session stayed active.
39
+ - **With `transport.invocation: 'routed-http'`, repeated identical GET requests keep cancelling the previous one.** A superseded request removed its replacement's abort controller, so from the third call on a stale response could overwrite a newer one.
40
+
8
41
  ## [0.14.0] - 2026-10-16
9
42
 
10
43
  ### Added
@@ -1,4 +1,20 @@
1
1
  export declare const BOOT_KEY_PREFIX = "luckystack:boot:";
2
+ /**
3
+ * The Redis key holding an environment's boot UUID. Single source of truth —
4
+ * also used by `@luckystack/router`'s `bootHandshake.ts`, so writer and reader
5
+ * can never drift.
6
+ *
7
+ * The project name is part of the key for the same reason it is part of the
8
+ * Socket.io adapter key: two projects with the same environment name on one
9
+ * Redis would otherwise overwrite each other's UUID, rotating the other
10
+ * project's health HMAC and faking a handshake mismatch. Router and backends
11
+ * must therefore resolve the same project name (`PROJECT_NAME`).
12
+ *
13
+ * The name comes from `PROJECT_NAME` only, never `session.projectName`: the
14
+ * standalone router CLI does not load `config.ts`, so a config-only name would
15
+ * give the backend a different key than the router reads.
16
+ */
17
+ export declare const bootUuidKey: (envKey: string) => string;
2
18
  export declare const resolveEnvKey: () => string;
3
19
  export declare const writeBootUuid: (envKey?: string) => Promise<string>;
4
20
  export declare const readBootUuid: (envKey?: string) => Promise<string | null>;
@@ -280,4 +280,4 @@ export {
280
280
  getProjectName,
281
281
  isProjectConfigRegistered
282
282
  };
283
- //# sourceMappingURL=chunk-PN2FPJXI.js.map
283
+ //# sourceMappingURL=chunk-55YXIACQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/configUtils.ts","../src/createRegistry.ts","../src/projectConfig.ts"],"sourcesContent":["//? Shared config-merge utilities. Every `@luckystack/*` config registry\n//? (projectConfig, avatarConfig, and — after this lands — email/presence/\n//? error-tracking) deep-merges a consumer's deep-partial override over a\n//? built-in default. This module is the single implementation so a merge\n//? bug is fixed once for everyone.\n//?\n//? Behaviour contract (must match the historical hand-rolled copies exactly):\n//? - `override === undefined` → return `base` untouched.\n//? - When either side is not a plain object (arrays, primitives, class\n//? instances, null) → the override replaces the base wholesale\n//? (`override ?? base`). Arrays are therefore replaced, never merged.\n//? - Otherwise merge key-by-key: `undefined` override values are skipped\n//? (the base value wins), nested plain objects recurse, everything else\n//? replaces.\n//?\n//? Added over the historical copies: a depth + circular-reference guard so a\n//? pathological override (self-referential object or absurd nesting) degrades\n//? to a wholesale replace instead of overflowing the stack. Real config trees\n//? are a handful of levels deep, so the guard never triggers in practice and\n//? behaviour is identical to the old implementations.\n\n/** Maximum recursion depth before the merge stops descending and replaces wholesale. */\nconst MAX_MERGE_DEPTH = 100;\n\nexport type DeepPartial<T> = {\n [K in keyof T]?: T[K] extends object | undefined ? DeepPartial<NonNullable<T[K]>> : T[K];\n};\n\n/**\n * True when `value` is a plain object literal (prototype is `Object.prototype`\n * or `null`). Arrays, class instances, Maps, Dates, and `null` are rejected so\n * they are treated as opaque replacement values during a merge.\n */\nexport const isPlainObject = (value: unknown): value is Record<string, unknown> => {\n if (value === null || typeof value !== 'object') return false;\n const proto = Object.getPrototypeOf(value) as object | null;\n return proto === Object.prototype || proto === null;\n};\n\nconst deepMergeInternal = <T>(\n base: T,\n override: DeepPartial<T> | undefined,\n depth: number,\n seen: WeakSet<object>,\n): T => {\n if (override === undefined) return base;\n if (!isPlainObject(base) || !isPlainObject(override)) {\n return (override as T) ?? base;\n }\n\n //? Depth / circular guard: if we have descended too far, or the override\n //? object has already been visited on this branch (self-reference), stop\n //? recursing and replace wholesale. Normal config trees never reach this.\n if (depth >= MAX_MERGE_DEPTH || seen.has(override)) {\n return (override as T) ?? base;\n }\n seen.add(override);\n try {\n const result: Record<string, unknown> = { ...(base as Record<string, unknown>) };\n for (const [key, overrideValue] of Object.entries(override as Record<string, unknown>)) {\n if (overrideValue === undefined) continue;\n //? Prototype-pollution guard: only `__proto__` can silently mutate the\n //? prototype chain via object spread/assign. `constructor` and `prototype`\n //? are valid config key names (e.g. a config section named `prototype` or a\n //? field called `constructor`) and must be allowed through; blocking them\n //? silently dropped legitimate consumer config keys (CORE-N5).\n if (key === '__proto__') continue;\n const baseValue = (base as Record<string, unknown>)[key];\n result[key] =\n isPlainObject(baseValue) && isPlainObject(overrideValue)\n ? deepMergeInternal(baseValue, overrideValue as DeepPartial<unknown>, depth + 1, seen)\n : overrideValue;\n }\n return result as T;\n } finally {\n //? Remove on the way back UP so the visited-set tracks only the ACTIVE branch\n //? (ancestor cycle), not the whole tree. Without this, a shared (DAG) object\n //? reference reused at two sibling config positions hit `seen.has()` on its\n //? 2nd occurrence and was replaced wholesale — silently dropping that\n //? sub-tree's base defaults (could relax a security default). Per-branch\n //? tracking still catches a genuine self-reference (object on the live path).\n seen.delete(override);\n }\n};\n\n/**\n * Deep-merge a deep-partial `override` over a fully-populated `base`,\n * returning a new object. See the module header for the exact behaviour\n * contract. Arrays and non-plain-object values are replaced wholesale; nested\n * plain objects merge recursively; `undefined` override values are ignored.\n */\nexport const deepMerge = <T>(base: T, override: DeepPartial<T> | undefined): T =>\n deepMergeInternal(base, override, 0, new WeakSet<object>());\n","//? Generic single-slot DI-registry factory. LuckyStack's `register* / get* /\n//? is*Registered / reset*ForTests` triad is hand-rolled a dozen-plus times in\n//? this package (and again downstream in `@luckystack/server`). Each copy is\n//? the same shape: a module-level mutable slot, a setter that flips a\n//? \"registered\" flag, a call-time getter, a boolean guard, and an optional\n//? test-reset. This factory centralises that boilerplate while staying\n//? flexible enough for the variants that exist in the wild:\n//?\n//? - registers that return the stored value (deployConfig, servicesConfig)\n//? vs. return void (projectConfig, logger, notifier).\n//? - getters that fall back to a default vs. throw when nothing is\n//? registered (servicesConfig).\n//? - a debug-log line on each register (rateLimiter strategy).\n//? - an optional input → stored transform (projectConfig deep-merges the\n//? consumer's deep-partial over the defaults before storing).\n//?\n//? Registries with genuinely bespoke storage (keyed slots like the\n//? prisma/redis client map, additive Set-based registries, multi-handler\n//? arrays) are intentionally NOT a fit for this single-slot factory and stay\n//? hand-rolled.\n\n//? When no `transform` is supplied, `TInput` must equal `TStored` so the\n//? identity store is type-safe (no cast). When they differ, a `transform` is\n//? mandatory — `RequireTransform` makes that a compile error rather than a\n//? runtime surprise.\ntype RequireTransform<TInput, TStored> = [TInput] extends [TStored]\n ? { transform?: (input: TInput, current: TStored) => TStored }\n : { transform: (input: TInput, current: TStored) => TStored };\n\ninterface RegistryOptionsBase<TStored> {\n /**\n * Called once per `register` with the freshly-stored value — used for the\n * rate-limiter's `[RateLimiter] active strategy → …` debug line. Runs after\n * the slot is updated so a logger registry can log through itself.\n */\n onRegister?: (stored: TStored) => void;\n /**\n * Resolve the value `get` returns when nothing has been registered yet.\n * Defaults to returning `defaultValue`. `servicesConfig` throws here.\n */\n resolveDefault?: () => TStored;\n}\n\nexport type RegistryOptions<TInput, TStored> = RegistryOptionsBase<TStored> &\n RequireTransform<TInput, TStored>;\n\nexport interface Registry<TInput, TStored> {\n /** Store a value (after the optional `transform`) and mark the slot registered. */\n register: (input: TInput) => TStored;\n /** Read the active value at call time (registered value, else the default). */\n get: () => TStored;\n /** True once `register` has been called at least once. */\n isRegistered: () => boolean;\n /** Restore the unregistered state (test-only). */\n reset: () => void;\n}\n\n/**\n * Create a single-slot registry. `defaultValue` is returned by `get` until\n * `register` is called (unless `resolveDefault` overrides that). When\n * `TInput` differs from `TStored`, the `transform` option is mandatory (the\n * `RequireTransform` constraint enforces it); when they match it is optional\n * and defaults to identity. The second positional argument is likewise\n * optional only in the identity case.\n */\nexport function createRegistry<TStored, TInput = TStored>(\n defaultValue: TStored,\n ...optionsArg: [TInput] extends [TStored]\n ? [options?: RegistryOptions<TInput, TStored>]\n : [options: RegistryOptions<TInput, TStored>]\n): Registry<TInput, TStored> {\n //? Implementation body uses a single erased `unknown` boundary so the\n //? identity fallback needs no per-instantiation cast. The public overload\n //? above keeps every call site fully typed; this boundary is internal only.\n const options = (optionsArg[0] ?? {}) as {\n transform?: (input: unknown, current: unknown) => unknown;\n onRegister?: (stored: unknown) => void;\n resolveDefault?: () => unknown;\n };\n const { transform, onRegister, resolveDefault } = options;\n\n let active: unknown = defaultValue;\n let registered = false;\n\n const register = (input: TInput): TStored => {\n active = transform ? transform(input, active) : input;\n registered = true;\n if (onRegister) onRegister(active);\n return active as TStored;\n };\n\n const get = (): TStored => {\n if (registered) return active as TStored;\n return (resolveDefault ? resolveDefault() : defaultValue) as TStored;\n };\n\n const isRegistered = (): boolean => registered;\n\n const reset = (): void => {\n active = defaultValue;\n registered = false;\n };\n\n return { register, get, isRegistered, reset };\n}\n","//? Project-level runtime configuration, consumed by framework packages via\n//? `getProjectConfig()`. The project's entrypoint calls\n//? `registerProjectConfig({...})` once at boot — before any framework code\n//? issues API/sync requests — mirroring the pattern we use for the localized\n//? normalizer.\n//?\n//? Everything here is runtime-settable. Type-level project shapes\n//? (`SessionLayout`, etc.) stay in the project's `config.ts` so TypeScript\n//? inference keeps working at call sites.\n//?\n//? Framework code reads values through `getProjectConfig()` (call-time) so\n//? `registerProjectConfig` can be invoked after this module is imported.\n//? Never read at module load — that captures whatever was registered at\n//? import time, which is fragile.\n//?\n//? `registerProjectConfig` accepts a deep-partial of `ProjectConfig`; missing\n//? fields fall back to the defaults defined here. This means a project's\n//? `config.ts` only has to specify the values it wants to override.\n\nimport { deepMerge, type DeepPartial } from './configUtils';\nimport { createRegistry } from './createRegistry';\n\nexport interface LoggingConfig {\n devLogs: boolean;\n devNotifications: boolean;\n socketStatus: boolean;\n socketStartup: boolean;\n stream: boolean;\n /**\n * Prefix every line from the framework's built-in loggers (the default\n * `console.*` logger and `createDevLogger`) with an ISO-8601 UTC timestamp,\n * e.g. `[2026-07-13T15:20:01.123Z] Connected to Redis`. DEFAULT `true`. Set\n * `false` under a log aggregator that stamps its own time (journald, Docker,\n * Datadog) to avoid double timestamps. A registered custom logger\n * (`registerLogger(...)`) is responsible for its own timestamps — this flag\n * only governs the built-in loggers.\n */\n timestamps: boolean;\n}\n\nexport interface RateLimitingConfig {\n /**\n * Global kill-switch for all rate limiting. When `false`, every\n * `checkRateLimit` call short-circuits to \"allowed\" and counters are not\n * touched. Useful for local dev, load tests, or trusted internal tooling.\n * Defaults to `true`.\n */\n enabled: boolean;\n store: 'memory' | 'redis';\n redisKeyPrefix: string;\n defaultApiLimit: number | false;\n defaultIpLimit: number | false;\n windowMs: number;\n /** How often the in-memory store evicts expired entries. */\n cleanupIntervalMs: number;\n /**\n * What the default strategy does when `store: 'redis'` is active but a Redis\n * operation fails (disconnect, eval error). DEFAULT `'memory'` — degrade to\n * the process-local in-memory store (fail-open, backwards-compatible) and log\n * a one-shot warning. In a multi-instance deployment this silently relaxes the\n * global limit to per-instance (N×). Set `'deny'` to instead reject the\n * request (fail-closed) so a Redis outage can't bypass rate limiting.\n */\n onStoreError: 'memory' | 'deny';\n /**\n * Skip rate limiting for requests that resolve to a loopback client IP\n * (`127.0.0.1`, `::1`, the `UNKNOWN_CLIENT_IP` sentinel) when running in\n * development (`NODE_ENV !== 'production'`). Lets a dev machine hammer its own\n * server (HMR reload storms, local load tests) without tripping limits, while\n * staying fully enforced in production. DEFAULT `false` (enforce everywhere) —\n * a missing key keeps today's behavior. The api/sync transport handlers read\n * this when building the per-IP key; core only owns the flag + the\n * {@link isLoopbackIp} helper.\n */\n skipLoopbackInDev: boolean;\n /**\n * Identity callback that decides the BASIS of a rate-limit key for a given\n * request — i.e. whether to key per-user, per-IP, or some custom dimension.\n * The api/sync handlers call this (when set) to derive the `{ scope, id }`\n * used to build the bucket key, instead of the built-in user-then-IP default.\n * Returning `null` falls back to the framework default. Synchronous by design\n * (it runs on the hot request path). DEFAULT unset.\n */\n identity?: (params: RateLimitIdentityParams) => RateLimitIdentity | null;\n /**\n * Per-account brute-force lockout slot, keyed independently from the general\n * api/ip limits so credential endpoints (login, password-reset) can apply a\n * stricter window without affecting normal traffic.\n *\n * NOTE — DD-CORE-D3: **core does NOT consume this slot**. The core package\n * only declares and stores the config; the `@luckystack/login` package reads\n * `rateLimiting.auth` when keying a per-account attempt counter\n * (`auth:<accountKey>`). If you search the core source for usages of this\n * field and find none, that is expected — it is not dead config; it is login-\n * owned config that lives here for a single source of truth.\n *\n * DEFAULT `{ enabled: false }` — a missing/disabled slot keeps today's\n * behavior (no per-account lockout; only the per-IP throttle applies).\n */\n auth: AuthRateLimitConfig;\n}\n\n/** Inputs handed to the {@link RateLimitingConfig.identity} callback. */\nexport interface RateLimitIdentityParams {\n /** Resolved route name (`api/billing/getInvoice/v1`, `sync/...`). */\n routeName: string;\n /** Session user id when the request is authenticated, else null. */\n userId: string | null;\n /** Resolved client IP (already honours `http.trustProxy`). */\n ip: string;\n /** Transport the request arrived on. */\n transport: 'socket' | 'http';\n}\n\n/** Result of a {@link RateLimitingConfig.identity} callback. */\nexport interface RateLimitIdentity {\n /** Which dimension the key is built from. */\n scope: 'user' | 'ip' | 'custom';\n /** The identity value (user id, ip, or a custom string). Never a raw token. */\n id: string;\n}\n\nexport interface AuthRateLimitConfig {\n /** When false (default), no per-account lockout is applied. */\n enabled: boolean;\n /** Max failed attempts per account FROM ONE IP within `windowMs` before that\n * IP+account bucket locks (per-IP cap; also bounds a single IP and protects other\n * IPs from a victim-lock DoS). Default 5. */\n maxAttempts: number;\n /**\n * Cross-IP cap: max failed attempts against a SINGLE account from ALL IPs\n * combined within `windowMs` before the account locks. This is the\n * distributed-credential-stuffing defense — `maxAttempts` alone is per-IP, so N\n * attacker IPs would otherwise each get a fresh `maxAttempts` budget. Should be\n * HIGHER than `maxAttempts` (it counts every IP). Default 50.\n */\n maxAttemptsPerAccount: number;\n /** Rolling window in ms over which both caps are counted. Default 900000 (15 min). */\n windowMs: number;\n}\n\nexport interface SessionConfig {\n basedToken: boolean;\n expiryDays: number;\n /**\n * Whether a single user can hold multiple active sessions across devices.\n * `'single'` (default): logging in on a new device kicks the previous one.\n * `'multiple'`: device A and device B can both be logged in concurrently.\n */\n perUser: 'single' | 'multiple';\n /**\n * Optional cap on concurrent sessions when `perUser === 'multiple'`. Null\n * = unlimited. When the cap is reached, the policy from `onConflict`\n * decides whether the new login is accepted (kicking oldest) or rejected.\n */\n maxConcurrentPerUser: number | null;\n /**\n * What to do when a session limit is exceeded.\n * `'revokeOld'` (default): kick the oldest session, accept the new login.\n * `'rejectNew'`: refuse the new login, leave existing sessions intact.\n */\n onConflict: 'revokeOld' | 'rejectNew';\n /**\n * When `onConflict === 'revokeOld'`, whether to broadcast a short UI\n * notification (\"logged in elsewhere\") to the kicked device before\n * disconnecting it. Default true.\n */\n notifyOldDeviceOnRevoke: boolean;\n /**\n * Prefix used for Redis session/activeUsers keys (e.g. `${projectName}-session:<token>`).\n * Falls back to `process.env.PROJECT_NAME` then this default at config build time.\n */\n projectName: string;\n}\n\nexport interface AppConfig {\n /**\n * Public URL of the app — used by OAuth callback redirects, transactional\n * email links (when `@luckystack/email` is installed), and any other\n * framework code that needs to render an absolute link to your app.\n * Empty default — consumers should set this to the public origin of their\n * deployment (e.g. `https://app.example.com`).\n */\n publicUrl: string;\n}\n\nexport interface HttpStreamConfig {\n /** Query-string flag clients pass to opt into SSE streaming. */\n queryParam: string;\n /** Value the query-string flag must have. */\n enabledValue: string;\n /** Initial comment line written when an SSE stream opens (keeps proxies happy). */\n connectedComment: string;\n}\n\nexport interface SecurityHeadersConfig {\n frameOptions: string;\n referrerPolicy: string;\n xssProtection: string;\n contentTypeOptions: string;\n}\n\nexport interface CorsConfig {\n allowedMethods: string;\n allowedHeaders: string;\n exposedHeaders: string;\n /** Send `Access-Control-Allow-Credentials: true`. */\n credentials: boolean;\n /**\n * Origins permitted to make cross-origin requests. The framework always\n * permits the registered bind address. Set `allowLocalhost`\n * to true to also accept any `localhost` origin (useful for dev).\n * Origins are normalized (scheme + host + port) before comparison.\n *\n * Static list mode: pass a `string[]`. Origins are matched exactly.\n * Dynamic mode: pass a synchronous function `(origin) => boolean` for\n * per-tenant / per-time-window allow-listing. Async resolvers are NOT\n * supported here because Socket.io's CORS check is synchronous; use a\n * pre-computed in-memory cache that the function can read from.\n */\n allowedOrigins: string[] | ((origin: string) => boolean);\n /**\n * Accept any origin matching `localhost` (any port). Convenient for local\n * development; should be `false` in production. Defaults to `false` so\n * production deployments fail closed.\n */\n allowLocalhost: boolean;\n /**\n * Historical opt-in kept for symmetry. Origin-less requests are ALWAYS\n * admitted at the CORS layer now (see `loadSocket.ts`): browsers omit the\n * `Origin` header on same-origin GETs, which is exactly the initial Socket.io\n * polling handshake in both dev (Vite proxy) and prod-with-router (single\n * origin) topologies — rejecting it broke every connection with\n * `400 code:3 MIDDLEWARE_FAILURE`. The real auth gate is the session token\n * in the handshake, not the Origin header. This flag no longer gates\n * anything and is retained only so existing configs that set it keep\n * type-checking; it may be removed in a future major version.\n */\n allowOriginless?: boolean;\n /**\n * Optional per-route override hook. When a `_api/*` file exports\n * `export const cors = { allowedOrigins, allowedHeaders, ... }` the\n * framework merges that on top of the global config for THAT route only.\n * Implemented in the api handler — this field is documentation-only.\n */\n // Note: per-route override is wired in `packages/api/src/handleHttpApiRequest.ts`.\n}\n\nexport interface HttpConfig {\n sessionCookieName: string;\n sessionCookieSameSite: 'Strict' | 'Lax' | 'None';\n sessionCookiePath: string;\n /**\n * Optional `Domain` attribute for the session cookie (CORE-39). Leave unset\n * (DEFAULT) for a host-only cookie (most secure). Set to a parent domain\n * (`.example.com`) only when the cookie must be shared across subdomains.\n * IGNORED when `sessionCookiePrefix === '__Host-'` (that prefix forbids\n * `Domain`). A missing key keeps today's host-only behavior.\n */\n sessionCookieDomain?: string;\n /**\n * Optional cookie name prefix enforcing browser-level guarantees (CORE-10/39):\n *\n * - `'__Host-'` — forces `Secure`, `Path=/`, and NO `Domain` (blocks\n * subdomain cookie-tossing). The strongest option for a host-only session.\n * - `'__Secure-'` — forces `Secure` (cookie only sent over HTTPS).\n * - unset (DEFAULT) — no prefix; today's behavior. A missing key changes\n * nothing.\n *\n * The server's session cookie builder (`@luckystack/server`\n * `httpRoutes/sessionCookie.ts`) applies the prefix to `sessionCookieName`\n * plus the forced attributes on every set, refresh and clear, and the token\n * extractors read the prefixed name. Changing this renames the cookie, so\n * existing sessions are logged out once. Use\n * {@link applyCookiePrefixConstraints} to compute the effective attributes.\n */\n sessionCookiePrefix?: '__Host-' | '__Secure-';\n /**\n * Per-cookie `Secure` override (CORE-39). When unset (DEFAULT) the server\n * derives `Secure` from `process.env.SECURE` as today. Set explicitly to\n * force on/off independently of the env flag. A `__Host-`/`__Secure-` prefix\n * forces `Secure: true` regardless.\n */\n sessionCookieSecure?: boolean;\n /**\n * Maximum body size (bytes) accepted on the HTTP transport for `/api/*` and\n * `/sync/*` POSTs. DEFAULT 1 MiB (1024 * 1024). This is the HTTP-body cap; the\n * SOCKET transport has a SEPARATE, independently-configurable frame cap\n * (`socket.maxHttpBufferSize`, default 5 MiB) — the two are deliberately distinct\n * knobs (HTTP body parser vs Socket.io whole-frame buffer). Set both to the same\n * value if you want a uniform per-call payload ceiling across transports.\n */\n requestBodyMaxBytes: number;\n /** Path of the router boot-handshake endpoint. */\n healthEndpoint: string;\n /**\n * Liveness endpoint. Always returns 200 if the process is up and\n * responsive — does NOT check dependencies. Suitable for K8s `livenessProbe`.\n */\n liveEndpoint: string;\n /**\n * Readiness endpoint. Returns 200 only when Redis + Prisma are reachable\n * AND boot UUID is set. Suitable for K8s `readinessProbe`.\n */\n readyEndpoint: string;\n /** Path of the dev-only state-reset endpoint (gated by NODE_ENV + token). */\n testResetEndpoint: string;\n /**\n * Whether a known reverse proxy sits in front of this server. DEFAULT false.\n * When false, per-IP rate-limit keys derive from the raw transport peer\n * address (historical behaviour). When true, the framework resolves the real\n * client IP from `X-Forwarded-For` / `X-Real-IP` before keying — so per-IP\n * limits stay meaningful behind nginx/HAProxy. Only enable when a trusted\n * proxy populates those headers, otherwise clients can spoof their IP.\n */\n trustProxy?: boolean;\n /**\n * How many proxy hops to skip from the RIGHT of `X-Forwarded-For` when\n * `trustProxy` is on (CORE-O3). The rightmost entries are the ones appended by\n * YOUR trusted proxies, so the resolved client IP is the entry that many hops\n * in from the end. The LEFTMOST hop is client-controlled and must never be\n * trusted (it enables per-IP rate-limit evasion + audit-IP spoofing).\n *\n * DEFAULT 1 — with the standard single-trusted-proxy topology this selects the\n * immediate upstream peer (the rightmost real hop), i.e. the IP the proxy saw\n * the connection arrive from. Raise it to match the number of trusted proxies\n * in the chain. Clamped to the list length so an over-large count falls back\n * to the leftmost available trusted hop rather than the spoofable client entry.\n * IGNORED when `trustProxy` is false (raw peer address is used verbatim).\n */\n trustedProxyHopCount?: number;\n /**\n * Whether cookie-mode sessions (`session.basedToken === false`) also accept a\n * token supplied via `Authorization: Bearer` / `handshake.auth.token` as a\n * fallback (CORE-O10). DEFAULT false — in cookie-mode the framework reads ONLY\n * the session cookie and ignores any bearer/handshake-auth token, so a stolen\n * token replayed through a header can no longer defeat the cookie/CSRF model.\n * Set true to restore the legacy behaviour (cookie-then-bearer fallback).\n * IGNORED in token-mode (`session.basedToken === true`), which is unaffected:\n * it always reads the bearer/handshake token first, cookie as fallback.\n */\n acceptBearerInCookieMode?: boolean;\n /**\n * Controls how `/_health` exposes synchronized-env-var hashes (SEC-13).\n * Previously `/_health` returned an UNSALTED `sha256(value)` of each\n * synchronized secret, unauthenticated — enabling offline dictionary attacks\n * on low-entropy secrets + key-name disclosure. This config + the shared\n * {@link hashSynchronizedValue} helper let both the server (`/_health`) and the\n * router (boot handshake) salt/HMAC consistently so the compare still works.\n * DEFAULTS keep today's wire behavior (`mode: 'plain'`) so a missing key does\n * not break an existing router handshake — opt into `'salted'`/`'hmac'`\n * explicitly (and bump server + router together).\n */\n healthHash: HealthHashConfig;\n stream: HttpStreamConfig;\n securityHeaders: SecurityHeadersConfig;\n cors: CorsConfig;\n}\n\nexport interface HealthHashConfig {\n /**\n * - `'plain'` — unsalted `sha256(value)`; the pre-0.2.0 behavior, kept so an\n * existing router boot handshake keeps comparing successfully. Opt in with\n * `mode:'plain'` to restore the legacy wire output.\n * - `'salted'` — `sha256(salt + value)` using `salt` below (or the boot UUID\n * when `salt` is the literal `'@bootUuid'`). Stable across a boot, rotates on\n * restart when bound to the boot UUID.\n * - `'hmac'` (DEFAULT in 0.2.0) — `HMAC-SHA256(key=salt, value)`. The default\n * `salt:'@bootUuid'` keys it on the per-boot UUID server + router already\n * share, so `/_health` no longer exposes a stable, offline-attackable\n * `sha256(secret)`. Collapses to `'plain'` when no boot UUID is available so\n * the boot handshake never silently diverges.\n */\n mode: 'plain' | 'salted' | 'hmac';\n /**\n * Shared salt / HMAC key. Both the backend `/_health` and the router's\n * compare MUST use the same value. The literal `'@bootUuid'` is a sentinel\n * meaning \"use the current boot UUID as the salt\" (valid with `'salted'` or\n * `'hmac'`). DEFAULTS to `'@bootUuid'` in 0.2.0 (only consulted when\n * `mode !== 'plain'`); set a non-empty static value to pin a stable key.\n */\n salt: string;\n}\n\nexport interface PasswordPolicyConfig {\n /** Minimum total length. Default 8. */\n minLength: number;\n /** Maximum total length. Default 191 (DB column-friendly). */\n maxLength: number;\n /** Require at least one uppercase letter (A-Z). Default false. */\n requireUppercase: boolean;\n /** Require at least one lowercase letter (a-z). Default false. */\n requireLowercase: boolean;\n /** Require at least one digit (0-9). Default false. */\n requireNumber: boolean;\n /** Require at least one non-alphanumeric character. Default false. */\n requireSpecial: boolean;\n /**\n * Reject the 10k most common passwords (built-in list shipped with\n * `@luckystack/login`). Default true. Set to false in tests or when\n * onboarding from a legacy system that allowed weak passwords.\n */\n forbidCommon: boolean;\n /**\n * Optional consumer-supplied predicate. Return null when the password is\n * acceptable, or a string describing why it isn't (the string is used as\n * the i18n errorCode-style key surfaced to the client).\n */\n customValidator?: (password: string) => string | null;\n}\n\nexport interface AuthConfig {\n /**\n * Whether email+password (credentials) auth is enabled. When `true` (default)\n * `@luckystack/login/register` registers the credentials provider, so it shows\n * up in `GET /auth/providers` and the login form renders the email/password\n * fields. Set `false` for an OAuth-only app — the form hides the fields AND the\n * `/auth/api/credentials` route rejects (`auth.credentialsDisabled`).\n */\n credentials: boolean;\n /** TTL for OAuth state tokens stored in Redis. */\n oauthStateTtlSeconds: number;\n /**\n * @deprecated Read `passwordPolicy.minLength`. Kept as a top-level field\n * for older consumer code; new code should use the structured policy.\n */\n passwordMinLength: number;\n /**\n * @deprecated Read `passwordPolicy.maxLength`. Kept as a top-level field\n * for older consumer code; new code should use the structured policy.\n */\n passwordMaxLength: number;\n /** Full credentials password policy. Replaces the deprecated min/max-length pair. */\n passwordPolicy: PasswordPolicyConfig;\n /** Maximum email length for credentials auth. */\n emailMaxLength: number;\n /** Maximum display-name length for credentials auth. */\n nameMaxLength: number;\n /**\n * bcrypt cost factor used when hashing passwords (registration, password\n * change, password reset). Default 10 matches industry guidance for 2026\n * hardware. Bump to 12 for higher-value accounts; 4 is acceptable for tests\n * to keep them fast.\n */\n bcryptRounds: number;\n /**\n * `'per-provider'` (default) — same email via Google and GitHub creates\n * two separate User rows (current behavior, no schema change).\n * `'unified'` — same email maps to a single User; subsequent sign-ins via\n * different providers resolve to (link to) that same User row instead of\n * creating a duplicate. Requires `email` to be `@unique` — see the\n * \"Account strategy\" migration steps in @luckystack/login's README.\n */\n providerAccountStrategy: 'per-provider' | 'unified';\n /**\n * `'framework'` — login package ships the /reset-password pages + APIs and\n * sends the reset email. Requires a registered email sender.\n * `'custom'` — login exposes only the primitives\n * (`createPasswordResetToken`, `consumePasswordResetToken`,\n * `updatePasswordHash`); the consumer wires their own UI and emails.\n * `'disabled'` (default) — no forgot-password feature; the link in\n * `LoginForm` does not render.\n */\n forgotPassword: 'framework' | 'custom' | 'disabled';\n /** Reset-token TTL in seconds when `forgotPassword === 'framework'`. */\n passwordResetTtlSeconds: number;\n /**\n * Brand/display name used in framework-mode password-reset emails (subject +\n * greeting + footer). Falls back to `'LuckyStack'` if unset; consumers should\n * override this to their own brand.\n */\n passwordResetBrand?: string;\n /** Email-change confirmation-token TTL in seconds. Default 3600 (1 hour). */\n emailChangeTtlSeconds: number;\n /**\n * Whether public self-service registration is permitted (login F18). When\n * `false`, the credentials `/register` route rejects with\n * `auth.registrationDisabled` and the login UI hides the \"create account\"\n * affordance — useful for invite-only / admin-provisioned apps. OAuth-driven\n * first-login account creation is governed separately by the provider flow.\n * DEFAULT `true` (today's behavior — open registration).\n */\n allowRegistration: boolean;\n /**\n * Frontend path the framework-mode password-reset email links to (login F22).\n * The reset token is appended as a query param. DEFAULT `/reset-password`.\n * Override when your reset page lives at a different route.\n */\n passwordResetPath: string;\n /**\n * Frontend path the email-change confirmation email links to (login F22).\n * The confirmation token is appended as a query param.\n * DEFAULT `/settings/confirm-email`, where the scaffold and `luckystack add\n * login` put the confirm page.\n */\n emailChangeConfirmPath: string;\n /**\n * Passwordless email-code login (ADR 0024): the user enters their email,\n * receives a short numeric code, and signs in by typing it. Requires a\n * registered email sender (`@luckystack/email`). DEFAULT `false`.\n * Anti-enumeration: the request endpoint always answers \"sent\".\n */\n emailCodeLogin: boolean;\n /** Email-code TTL in seconds (login + 2FA fallback codes). DEFAULT 600. */\n emailCodeTtlSeconds: number;\n /** Email-code length in digits. DEFAULT 6. */\n emailCodeLength: number;\n /** Wrong-code attempts before an email code is burned. DEFAULT 5. */\n emailCodeMaxAttempts: number;\n /**\n * Second factor at login (ADR 0024). `'optional'` = per-user opt-in: a user\n * who enrolled an authenticator app (TOTP — Google/Microsoft Authenticator,\n * Authy, …) must answer a 2FA challenge after their password/email-code is\n * verified. `'disabled'` (DEFAULT) = the challenge step never triggers, even\n * for enrolled users (kill switch).\n */\n twoFactor: 'disabled' | 'optional';\n /**\n * Allow \"send the code to my email instead\" as a 2FA fallback channel for\n * enrolled users (lost phone). Requires a registered email sender.\n * DEFAULT `true` (recovery codes always work regardless).\n */\n twoFactorEmailFallback: boolean;\n /** Pending 2FA login-challenge TTL in seconds. DEFAULT 300. */\n twoFactorChallengeTtlSeconds: number;\n /** Wrong-code attempts before a pending 2FA challenge is burned. DEFAULT 5. */\n twoFactorMaxAttempts: number;\n}\n\nexport interface OfflineQueueConfig {\n /** Hard cap on items per queue (api + sync are tracked separately). Default 200. */\n maxSize: number;\n /** Drop items older than this many ms when flushing/enqueuing. Default 1 hour. */\n maxAgeMs: number;\n /**\n * What to do when the queue is full:\n * - 'drop-oldest' (default): evict the oldest item, append the new one.\n * - 'drop-newest': reject the new item, keep the existing queue.\n * - 'reject': do not enqueue; caller must handle the failure.\n */\n dropPolicy: 'drop-oldest' | 'drop-newest' | 'reject';\n}\n\nexport interface SyncStreamThrottleConfig {\n /** Default `flushAtChars` for `createStreamThrottle({...})`. */\n flushAtChars: number;\n /** Default `flushEveryMs` for `createStreamThrottle({...})`. */\n flushEveryMs: number | false;\n /** Default `field` (payload key) for emitted chunks. */\n field: string;\n}\n\nexport interface TransportConfig {\n /**\n * Transport used for typed API/sync invocations. Socket.io remains connected\n * in both modes for rooms, presence, reconnect state and realtime callbacks.\n * `'socket'` is the backwards-compatible monolith default; `'routed-http'`\n * sends invocations over same-origin HTTP/SSE so @luckystack/router can select\n * the service owner.\n */\n invocation: 'socket' | 'routed-http';\n}\n\nexport interface ApiConfig {\n /**\n * Default response timeout (ms) for `apiRequest`. After this elapses with no\n * response (e.g. server restart/crash between emit and reply) the request\n * settles with `{ status:'error', errorCode:'api.timeout', httpStatus:504 }`\n * instead of hanging forever. Set `false` (or `0` / a negative number) to\n * disable the timeout. A per-call\n * `timeoutMs` overrides this. Default 30000.\n */\n requestTimeoutMs: number | false;\n}\n\nexport interface ValidationConfig {\n /**\n * Whether runtime input validation runs in PRODUCTION (CORE-01).\n *\n * - `'enforce'` (DEFAULT) — the structural validator (`validateType`) runs\n * against the route's resolved input type in production too, so a malformed\n * payload is rejected with `api.invalidInputType` / `sync.invalidInputType`\n * instead of reaching the handler. Only the dev-only devkit DEEP type\n * resolver (TypeScript compiler API) is skipped in prod — the already-resolved\n * generated type text is validated directly.\n * - `'off'` — restore the legacy behavior where prod skips input validation\n * entirely (input shape is the handler's responsibility). This is the loud,\n * documented opt-out; set it only if a route's generated type text can't be\n * validated structurally in your deployment.\n *\n * DEFAULT `'enforce'`. Note: this CHANGES prior behavior (prod was a no-op).\n * Set `'off'` to keep the old no-op.\n */\n runtimeMode: 'enforce' | 'off';\n}\n\nexport interface SyncConfig {\n streamThrottle: SyncStreamThrottleConfig;\n /**\n * Default response timeout (ms) for `syncRequest`'s acknowledgement. Same\n * semantics as `api.requestTimeoutMs` but for sync. Settles with\n * `sync.requestTimeout` / httpStatus 504 on expiry. `false` (or `0` / a\n * negative number) to disable. Default 30000.\n */\n requestTimeoutMs: number | false;\n /**\n * Yield to the event loop every N recipients during a broadcast fanout\n * (`receiver: 'all'` or large rooms). Lower = more responsive, higher\n * overhead. Default 100.\n */\n fanoutYieldEvery: number;\n /** Milliseconds to sleep when yielding. Default 1ms. */\n fanoutYieldMs: number;\n /**\n * Receiver-authorization policy (SYNC-07). These flags add framework-level\n * defaults read by `@luckystack/sync`'s `authorizeSyncReceiver`:\n *\n * - `allowClientReceiverAll` — when false, a client requesting the broadcast\n * receiver `'all'` is rejected unless a `preSyncAuthorize` handler approves\n * it. DEFAULT `false` (0.2.0 secure-default flip — a client can no longer\n * broadcast cluster-wide by default; opt back in with `true` for the legacy\n * permissive behavior).\n * - `requireRoomMembership` — when true, a client may only target a room it\n * has actually joined (its `roomCodes`); targeting an unjoined room is\n * rejected. DEFAULT `true` (0.2.0 secure-default flip — a client can no\n * longer fan out to a room it never joined; set `false` for the legacy\n * any-room behavior).\n *\n * BREAKING (0.2.0): both defaults now fail CLOSED. Apps that relied on\n * implicit cluster-wide / arbitrary-room broadcasts must either join the room\n * before targeting it, approve the receiver via a `preSyncAuthorize` handler,\n * or explicitly opt back into the permissive values.\n */\n allowClientReceiverAll: boolean;\n requireRoomMembership: boolean;\n /**\n * Stream backpressure tuning (SYNC-15) for `createStreamThrottle` /\n * server-initiated stream emits. Constants were previously hardcoded in the\n * sync package; surfacing them here lets a consumer tune flush cadence under\n * load without forking. DEFAULTS reproduce the historical hardcoded values.\n */\n flushPressure: SyncFlushPressureConfig;\n}\n\nexport interface SyncFlushPressureConfig {\n /** Max queued chunks before the stream applies backpressure (pauses). Default 1000. */\n highWaterMarkChunks: number;\n /** Resume emitting once the queue drains below this. Default 250. */\n lowWaterMarkChunks: number;\n /** Hard cap on bytes buffered for a single stream before dropping/erroring. Default 5_242_880 (5 MiB). */\n maxBufferedBytes: number;\n}\n\nexport interface SocketConfig {\n /**\n * Maximum payload size (bytes) for any single Socket.io message (whole-frame\n * buffer). DEFAULT 5 MiB (5 * 1024 * 1024). This is the SOCKET-transport cap; the\n * HTTP transport has a SEPARATE, independently-configurable body cap\n * (`http.requestBodyMaxBytes`, default 1 MiB). The two are intentionally distinct —\n * set both to the same value for a uniform per-call ceiling across transports.\n */\n maxHttpBufferSize: number;\n /** ms with no pong response before the server considers the client gone. */\n pingTimeout: number;\n /** ms between pings. */\n pingInterval: number;\n /**\n * Minimum ms between client → server `activity` heartbeats (repo-src C-CFG /\n * presence C1). The client activity tracker in `src/_sockets` reads this to\n * throttle how often mouse/keyboard/touch activity is reported; the server\n * (and `@luckystack/presence`) records every heartbeat it receives. DEFAULT\n * 10000 (10s) — a missing key keeps the historical cadence.\n */\n activityHeartbeatThrottleMs: number;\n /**\n * Hard cap on how many rooms a single session may be joined to at once. When a\n * join would exceed the cap the OLDEST joined room is left first (FIFO eviction)\n * so `session.roomCodes` can't grow unbounded in Redis (session-bloat DoS).\n * DEFAULT 50. Set to `false` to disable the cap (unbounded — legacy behavior).\n */\n maxRoomsPerSession: number | false;\n}\n\nexport interface DevConfig {\n /** Debounce window for hot-reload triggers. */\n hotReloadDebounceMs: number;\n /** Chokidar `awaitWriteFinish.stabilityThreshold`. */\n watcherStabilityThresholdMs: number;\n /** Chokidar `awaitWriteFinish.pollInterval`. */\n watcherPollIntervalMs: number;\n /**\n * When true, log a warning the first time an api/sync route is invoked\n * without an `inputType` (typically because generated types haven't been\n * regenerated since the route was added). Helps catch routes that ship\n * with no runtime input validation. Default false (silent), set to true\n * in dev to surface missing types.\n */\n warnOnMissingInputType?: boolean;\n}\n\nexport interface PathsConfig {\n /** Frontend source root. */\n srcDir: string;\n /** Server-side source root. */\n serverDir: string;\n /** Shared (universal) source root. */\n sharedDir: string;\n /** Where uploaded user assets (avatars, etc.) live. */\n uploadsDir: string;\n /** Public static assets served as-is. */\n publicDir: string;\n /**\n * @deprecated Use `serverFunctionDirs` instead. Kept for backwards\n * compatibility with projects that set the singular form before the\n * function-injection system grew multi-directory support. When both are\n * present, `serverFunctionDirs` wins.\n */\n serverFunctionsDir: string;\n /**\n * Server-side function modules consumed by API/sync handlers. The\n * codegen and runtime walk every listed directory in order and merge the\n * results into one `Functions` interface / object. Duplicate keys\n * (same `<dirname>.<filename>.<export>` path produced by two roots)\n * fail the build — `shared/` is canonical, so the conflict tells the\n * consumer to delete the override.\n *\n * Default: `['functions', 'shared']`.\n *\n * Nested subdirectories work transparently — `functions/test/helper.ts`\n * with `export const foo = …` shows up as\n * `functions.test.helper.foo` on the injected `functions` parameter.\n */\n serverFunctionDirs: string[];\n /** Generated socket types output path (relative to project root). */\n generatedSocketTypes: string;\n /** Generated API input schemas output path. */\n generatedApiSchemas: string;\n /** Generated API docs JSON output path. */\n generatedApiDocs: string;\n}\n\nexport interface ProjectConfig {\n app: AppConfig;\n logging: LoggingConfig;\n rateLimiting: RateLimitingConfig;\n session: SessionConfig;\n http: HttpConfig;\n auth: AuthConfig;\n socket: SocketConfig;\n transport: TransportConfig;\n api: ApiConfig;\n sync: SyncConfig;\n validation: ValidationConfig;\n offlineQueue: OfflineQueueConfig;\n dev: DevConfig;\n paths: PathsConfig;\n defaultLanguage: string;\n /** Default theme for new users / fallback when no session preference exists. */\n defaultTheme?: 'light' | 'dark';\n /** Enable per-room activity broadcasting (presence). */\n socketActivityBroadcaster?: boolean;\n /** Show the floating socket-status indicator badge from `@luckystack/presence/client`. */\n socketStatusIndicator?: boolean;\n /** Enable client → server `updateLocation` syncing. */\n locationProviderEnabled?: boolean;\n /** Where to redirect the user after a successful OAuth callback. */\n loginRedirectUrl?: string;\n /**\n * Base origin used to build OAuth callback redirect URIs\n * (`<oauthCallbackBase>/auth/callback/<provider>`). This is the BACKEND\n * origin the provider redirects to — in dev typically `http://localhost:80`,\n * in prod the public domain. Read by `@luckystack/login/register`'s env-driven\n * provider scan so OAuth wiring needs no consumer code. Empty default — the\n * consumer's `config.ts` sets it.\n */\n oauthCallbackBase?: string;\n}\n\nexport type ProjectConfigInput = DeepPartial<ProjectConfig>;\n\nexport const DEFAULT_PROJECT_CONFIG: ProjectConfig = {\n app: {\n publicUrl: '',\n },\n logging: {\n devLogs: false,\n devNotifications: false,\n socketStatus: false,\n socketStartup: false,\n stream: false,\n timestamps: true,\n },\n rateLimiting: {\n enabled: true,\n store: 'memory',\n redisKeyPrefix: 'rate-limit',\n defaultApiLimit: 60,\n defaultIpLimit: 100,\n windowMs: 60_000,\n cleanupIntervalMs: 60_000,\n onStoreError: 'memory',\n skipLoopbackInDev: false,\n //? DD-CORE-D3: consumed exclusively by @luckystack/login, not by core itself.\n auth: {\n enabled: false,\n maxAttempts: 5,\n maxAttemptsPerAccount: 50,\n windowMs: 15 * 60 * 1000,\n },\n },\n session: {\n basedToken: false,\n expiryDays: 7,\n perUser: 'single',\n maxConcurrentPerUser: null,\n onConflict: 'revokeOld',\n notifyOldDeviceOnRevoke: true,\n //? Empty default — `getProjectName()` reads `process.env.PROJECT_NAME` at\n //? call time and falls back to `'luckystack'`. Avoids capturing env at\n //? module-load before dotenv runs.\n projectName: '',\n },\n http: {\n sessionCookieName: 'token',\n sessionCookieSameSite: 'Strict',\n sessionCookiePath: '/',\n requestBodyMaxBytes: 1024 * 1024,\n healthEndpoint: '/_health',\n liveEndpoint: '/livez',\n readyEndpoint: '/readyz',\n testResetEndpoint: '/_test/reset',\n trustProxy: false,\n //? CORE-O3: skip 1 hop from the RIGHT of X-Forwarded-For (the rightmost\n //? entry is appended by your own trusted proxy) instead of trusting the\n //? leftmost, client-controlled hop. Only consulted when `trustProxy` is on.\n trustedProxyHopCount: 1,\n //? CORE-O10 secure default: in cookie-mode, ignore any `Authorization: Bearer`\n //? / `handshake.auth.token` fallback so a stolen token cannot bypass the\n //? cookie/CSRF model. Set true to restore the legacy cookie-then-bearer\n //? fallback. Token-mode (`basedToken: true`) is unaffected.\n acceptBearerInCookieMode: false,\n //? 0.2.0 secure-default flip (SEC-13): `/_health` no longer exposes a stable,\n //? unsalted `sha256(secret)` fingerprint. Default mode is `'hmac'` keyed on\n //? the `'@bootUuid'` sentinel — the per-boot UUID both server + router already\n //? share via the boot handshake — so the synchronized-env hash rotates every\n //? restart and is no longer offline dictionary-attackable. Set an explicit\n //? non-empty `salt` to pin a stable HMAC key across restarts, or `mode:'plain'`\n //? to restore the legacy unsalted wire output.\n healthHash: {\n mode: 'hmac',\n salt: '@bootUuid',\n },\n stream: {\n queryParam: 'stream',\n enabledValue: 'true',\n connectedComment: ': connected',\n },\n securityHeaders: {\n frameOptions: 'SAMEORIGIN',\n referrerPolicy: 'no-referrer',\n //? '1; mode=block' is deprecated (Chrome 78+ ignores it; can trigger\n //? reflected-XSS in older IE/Edge auditors). '0' disables the legacy\n //? auditor and defers to CSP, which is the modern defence.\n xssProtection: '0',\n contentTypeOptions: 'nosniff',\n },\n cors: {\n allowedMethods: 'GET, POST, PUT, DELETE, OPTIONS',\n allowedHeaders: 'Content-Type, Authorization, X-Session-Based-Token, X-CSRF-Token, X-Request-Id',\n exposedHeaders: 'X-Session-Token, X-Request-Id',\n credentials: true,\n allowedOrigins: [],\n allowLocalhost: false,\n allowOriginless: false,\n },\n },\n auth: {\n credentials: true,\n oauthStateTtlSeconds: 60 * 10,\n passwordMinLength: 8,\n passwordMaxLength: 191,\n passwordPolicy: {\n minLength: 8,\n maxLength: 191,\n requireUppercase: false,\n requireLowercase: false,\n requireNumber: false,\n requireSpecial: false,\n forbidCommon: true,\n },\n emailMaxLength: 191,\n nameMaxLength: 191,\n bcryptRounds: 10,\n providerAccountStrategy: 'per-provider',\n forgotPassword: 'disabled',\n passwordResetTtlSeconds: 60 * 60,\n emailChangeTtlSeconds: 60 * 60,\n allowRegistration: true,\n passwordResetPath: '/reset-password',\n emailChangeConfirmPath: '/settings/confirm-email',\n emailCodeLogin: false,\n emailCodeTtlSeconds: 60 * 10,\n emailCodeLength: 6,\n emailCodeMaxAttempts: 5,\n twoFactor: 'disabled',\n twoFactorEmailFallback: true,\n twoFactorChallengeTtlSeconds: 60 * 5,\n twoFactorMaxAttempts: 5,\n },\n socket: {\n maxHttpBufferSize: 5 * 1024 * 1024,\n pingTimeout: 20_000,\n pingInterval: 25_000,\n activityHeartbeatThrottleMs: 10_000,\n maxRoomsPerSession: 50,\n },\n transport: {\n invocation: 'socket',\n },\n api: {\n //? Default OFF (was 30_000): a legit handler may run for minutes (e.g. a deep\n //? image parse / long upstream call) and must not be aborted by a wall-clock\n //? race. A disconnecting client still aborts the handler via the wired\n //? abortSignal; set a number to opt back into a hard per-request ceiling\n //? (streaming requests are exempt even then — see runHttpApiExecution).\n requestTimeoutMs: false,\n },\n validation: {\n runtimeMode: 'enforce',\n },\n sync: {\n streamThrottle: {\n flushAtChars: 32,\n flushEveryMs: 50,\n field: 'chunk',\n },\n fanoutYieldEvery: 100,\n fanoutYieldMs: 1,\n requestTimeoutMs: 30_000,\n allowClientReceiverAll: false,\n requireRoomMembership: true,\n flushPressure: {\n highWaterMarkChunks: 1000,\n lowWaterMarkChunks: 250,\n maxBufferedBytes: 5 * 1024 * 1024,\n },\n },\n offlineQueue: {\n maxSize: 200,\n maxAgeMs: 60 * 60 * 1000,\n dropPolicy: 'drop-oldest',\n },\n dev: {\n hotReloadDebounceMs: 120,\n watcherStabilityThresholdMs: 120,\n watcherPollIntervalMs: 20,\n },\n paths: {\n srcDir: 'src',\n serverDir: 'server',\n sharedDir: 'shared',\n uploadsDir: 'uploads',\n publicDir: 'public',\n serverFunctionsDir: 'server/functions',\n serverFunctionDirs: ['functions', 'shared'],\n generatedSocketTypes: 'src/_sockets/apiTypes.generated.ts',\n generatedApiSchemas: 'src/_sockets/apiInputSchemas.generated.ts',\n generatedApiDocs: 'src/docs/apiDocs.generated.json',\n },\n defaultLanguage: 'en',\n defaultTheme: 'light',\n socketActivityBroadcaster: false,\n socketStatusIndicator: false,\n locationProviderEnabled: false,\n loginRedirectUrl: '/',\n oauthCallbackBase: '',\n};\n\nconst registry = createRegistry<ProjectConfig, ProjectConfigInput>(DEFAULT_PROJECT_CONFIG, {\n //? Always merge the consumer override over the pristine defaults (not the\n //? previously-stored config) — matches the historical register behaviour\n //? where each call rebuilds from `DEFAULT_PROJECT_CONFIG`.\n transform: (input) => deepMerge(DEFAULT_PROJECT_CONFIG, input),\n});\n\nexport const registerProjectConfig = (config: ProjectConfigInput): void => {\n registry.register(config);\n};\n\nexport const getProjectConfig = (): ProjectConfig => registry.get();\n\n//? Resolve the project namespace at call time. Single source of truth used\n//? for Redis key prefixes (`<projectName>-session:`, `-activeUsers:`,\n//? `-pwreset:`, `-oauth-state:`, etc.) across session.ts, logout.ts,\n//? rateLimiter.ts, passwordReset.ts, login.ts, testResetRoute.ts.\n//?\n//? Resolution order (first non-empty wins):\n//? 1. `projectConfig.session.projectName` (if a consumer set it explicitly)\n//? 2. `process.env.PROJECT_NAME` (read at call time — works after dotenv)\n//? 3. literal `'luckystack'` as the absolute fallback\nexport const getProjectName = (): string => {\n const fromConfig = registry.get().session.projectName;\n if (fromConfig && fromConfig.length > 0) return fromConfig;\n const fromEnv = process.env.PROJECT_NAME;\n if (fromEnv && fromEnv.length > 0) return fromEnv;\n return 'luckystack';\n};\n\n//? Guard for code paths that MUST run after registration (e.g. the server's\n//? startup sequence). Log once, never throw — framework packages should\n//? still do something reasonable when called in a test or CLI context that\n//? never registered.\nexport const isProjectConfigRegistered = (): boolean => registry.isRegistered();\n"],"mappings":";AAsBA,IAAM,kBAAkB;AAWjB,IAAM,gBAAgB,CAAC,UAAqD;AACjF,MAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO;AACxD,QAAM,QAAQ,OAAO,eAAe,KAAK;AACzC,SAAO,UAAU,OAAO,aAAa,UAAU;AACjD;AAEA,IAAM,oBAAoB,CACxB,MACA,UACA,OACA,SACM;AACN,MAAI,aAAa,OAAW,QAAO;AACnC,MAAI,CAAC,cAAc,IAAI,KAAK,CAAC,cAAc,QAAQ,GAAG;AACpD,WAAQ,YAAkB;AAAA,EAC5B;AAKA,MAAI,SAAS,mBAAmB,KAAK,IAAI,QAAQ,GAAG;AAClD,WAAQ,YAAkB;AAAA,EAC5B;AACA,OAAK,IAAI,QAAQ;AACjB,MAAI;AACF,UAAM,SAAkC,EAAE,GAAI,KAAiC;AAC/E,eAAW,CAAC,KAAK,aAAa,KAAK,OAAO,QAAQ,QAAmC,GAAG;AACtF,UAAI,kBAAkB,OAAW;AAMjC,UAAI,QAAQ,YAAa;AACzB,YAAM,YAAa,KAAiC,GAAG;AACvD,aAAO,GAAG,IACR,cAAc,SAAS,KAAK,cAAc,aAAa,IACnD,kBAAkB,WAAW,eAAuC,QAAQ,GAAG,IAAI,IACnF;AAAA,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W;AAAA,IACX,YAAY;AAAA,IACZ,WAAW;AAAA,IACX,oBAAoB;AAAA,IACpB,oBAAoB,CAAC,aAAa,QAAQ;AAAA,IAC1C,sBAAsB;AAAA,IACtB,qBAAqB;AAAA,IACrB,kBAAkB;AAAA,EACpB;AAAA,EACA,iBAAiB;AAAA,EACjB,cAAc;AAAA,EACd,2BAA2B;AAAA,EAC3B,uBAAuB;AAAA,EACvB,yBAAyB;AAAA,EACzB,kBAAkB;AAAA,EAClB,mBAAmB;AACrB;AAEA,IAAM,WAAW,eAAkD,wBAAwB;AAAA;AAAA;AAAA;AAAA,EAIzF,WAAW,CAAC,UAAU,UAAU,wBAAwB,KAAK;AAC/D,CAAC;AAEM,IAAM,wBAAwB,CAAC,WAAqC;AACzE,WAAS,SAAS,MAAM;AAC1B;AAEO,IAAM,mBAAmB,MAAqB,SAAS,IAAI;AAW3D,IAAM,iBAAiB,MAAc;AAC1C,QAAM,aAAa,SAAS,IAAI,EAAE,QAAQ;AAC1C,MAAI,cAAc,WAAW,SAAS,EAAG,QAAO;AAChD,QAAM,UAAU,QAAQ,IAAI;AAC5B,MAAI,WAAW,QAAQ,SAAS,EAAG,QAAO;AAC1C,SAAO;AACT;AAMO,IAAM,4BAA4B,MAAe,SAAS,aAAa;","names":[]}
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  captureException,
3
3
  getLogger
4
- } from "./chunk-C4AK6P5D.js";
4
+ } from "./chunk-NJULJZ3N.js";
5
5
  import {
6
6
  createRegistry,
7
7
  getProjectConfig
8
- } from "./chunk-PN2FPJXI.js";
8
+ } from "./chunk-55YXIACQ.js";
9
9
 
10
10
  // src/apiMethodMapRegistry.ts
11
11
  var registry = createRegistry(null);
@@ -726,4 +726,4 @@ export {
726
726
  DEFAULT_PAGE_ROUTE_RULES,
727
727
  validatePagePath
728
728
  };
729
- //# sourceMappingURL=chunk-RC7ZQBO6.js.map
729
+ //# sourceMappingURL=chunk-EZIBIQXO.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createRegistry,
3
3
  getProjectConfig
4
- } from "./chunk-PN2FPJXI.js";
4
+ } from "./chunk-55YXIACQ.js";
5
5
 
6
6
  // src/redactedLogKeys.ts
7
7
  var DEFAULT_REDACTED_LOG_KEYS = [
@@ -21,23 +21,28 @@ var DEFAULT_REDACTED_LOG_KEYS = [
21
21
  //? which strips both `totpSecret` and `recoveryCodes`.
22
22
  "recoverycodes"
23
23
  ];
24
+ var normalizeLogKey = (key) => key.toLowerCase().replaceAll(/[-_]/g, "");
24
25
  var redactedKeys = new Set(DEFAULT_REDACTED_LOG_KEYS.map((key) => key.toLowerCase()));
25
- var SENSITIVE_KEY_SUFFIXES = ["token", "secret", "apikey", "password"];
26
+ var normalizedRedactedKeys = new Set(DEFAULT_REDACTED_LOG_KEYS.map((key) => normalizeLogKey(key)));
27
+ var SENSITIVE_KEY_SUFFIXES = ["token", "secret", "apikey", "password", "secretkey", "privatekey"];
26
28
  var registerRedactedLogKeys = (keys) => {
27
29
  for (const key of keys) {
28
30
  redactedKeys.add(key.toLowerCase());
31
+ normalizedRedactedKeys.add(normalizeLogKey(key));
29
32
  }
30
33
  };
31
34
  var getRedactedLogKeys = () => [...redactedKeys];
32
35
  var isRedactedLogKey = (key) => {
33
- const lower = key.toLowerCase();
34
- if (redactedKeys.has(lower)) return true;
35
- return SENSITIVE_KEY_SUFFIXES.some((suffix) => lower.endsWith(suffix));
36
+ const normalized = normalizeLogKey(key);
37
+ if (normalizedRedactedKeys.has(normalized)) return true;
38
+ return SENSITIVE_KEY_SUFFIXES.some((suffix) => normalized.endsWith(suffix));
36
39
  };
37
40
  var resetRedactedLogKeysForTests = () => {
38
41
  redactedKeys.clear();
42
+ normalizedRedactedKeys.clear();
39
43
  for (const key of DEFAULT_REDACTED_LOG_KEYS) {
40
44
  redactedKeys.add(key.toLowerCase());
45
+ normalizedRedactedKeys.add(normalizeLogKey(key));
41
46
  }
42
47
  };
43
48
  var REDACTED_PLACEHOLDER = "[redacted]";
@@ -49,14 +54,18 @@ var sanitizeForLog = (value, depth = 0, _seen) => {
49
54
  const seen = _seen ?? /* @__PURE__ */ new WeakSet();
50
55
  if (seen.has(value)) return "[circular]";
51
56
  seen.add(value);
52
- if (Array.isArray(value)) {
53
- return value.map((item) => sanitizeForLog(item, depth + 1, seen));
54
- }
55
- const out = {};
56
- for (const [key, nested] of Object.entries(value)) {
57
- out[key] = isRedactedLogKey(key) ? REDACTED_PLACEHOLDER : sanitizeForLog(nested, depth + 1, seen);
57
+ try {
58
+ if (Array.isArray(value)) {
59
+ return value.map((item) => sanitizeForLog(item, depth + 1, seen));
60
+ }
61
+ const out = {};
62
+ for (const [key, nested] of Object.entries(value)) {
63
+ out[key] = isRedactedLogKey(key) ? REDACTED_PLACEHOLDER : sanitizeForLog(nested, depth + 1, seen);
64
+ }
65
+ return out;
66
+ } finally {
67
+ seen.delete(value);
58
68
  }
59
- return out;
60
69
  };
61
70
 
62
71
  // src/loggerRegistry.ts
@@ -142,6 +151,7 @@ var sanitizeContext = (context) => {
142
151
  };
143
152
  var REDACTED_VALUE_RE_CACHE_MAX = 200;
144
153
  var REDACTED_VALUE_RE_CACHE = /* @__PURE__ */ new Map();
154
+ var SCRUB_VALUE = String.raw`(?:"(?:[^"\\\r\n]|\\.)+"|'(?:[^'\\\r\n]|\\.)+'|(?:bearer|basic|digest|token)\s+[^\s,;"'&]+|[^\s,;"'&]+)`;
145
155
  var buildScrubPattern = (key) => {
146
156
  const cached = REDACTED_VALUE_RE_CACHE.get(key);
147
157
  if (cached) return cached;
@@ -151,17 +161,19 @@ var buildScrubPattern = (key) => {
151
161
  } catch {
152
162
  }
153
163
  }
154
- const escaped = key.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
164
+ const escaped = Array.from(key, (char) => char.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`)).join("[-_]?");
155
165
  const pair = {
156
- urlParam: new RegExp(String.raw`${escaped}=[^\s,;"'&]+`, "gi"),
157
- logLabel: new RegExp(String.raw`${escaped}:\s*[^\s,;"']+`, "gi")
166
+ urlParam: new RegExp(String.raw`${escaped}["']?\s*=\s*${SCRUB_VALUE}`, "gi"),
167
+ logLabel: new RegExp(String.raw`${escaped}["']?\s*:\s*${SCRUB_VALUE}`, "gi")
158
168
  };
159
169
  REDACTED_VALUE_RE_CACHE.set(key, pair);
160
170
  return pair;
161
171
  };
162
172
  var sanitizeErrorString = (value) => {
163
173
  let result = value;
164
- for (const key of getRedactedLogKeys()) {
174
+ const scrubKeys = new Set([...getRedactedLogKeys(), ...SENSITIVE_KEY_SUFFIXES].map((key) => normalizeLogKey(key)));
175
+ scrubKeys.delete("");
176
+ for (const key of scrubKeys) {
165
177
  const { urlParam, logLabel } = buildScrubPattern(key);
166
178
  result = result.replace(urlParam, () => REDACTED_PLACEHOLDER).replace(logLabel, () => REDACTED_PLACEHOLDER);
167
179
  }
@@ -368,4 +380,4 @@ export {
368
380
  setSentryUser,
369
381
  startSpan
370
382
  };
371
- //# sourceMappingURL=chunk-C4AK6P5D.js.map
383
+ //# sourceMappingURL=chunk-NJULJZ3N.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/redactedLogKeys.ts","../src/loggerRegistry.ts","../src/errorTrackerRegistry.ts","../src/sentrySetup.ts"],"sourcesContent":["//? Registry of log keys that get masked when the framework prints request /\n//? response payloads. A feature package or the consumer registers keys that\n//? the defaults and suffixes below do not cover (a domain field such as `mrn`)\n//? at boot, so nobody has to extend a static list in core to keep their own\n//? data out of logs.\n//?\n//? Lookups ignore case, `-` and `_` (`api_key`, `X-Api-Key` and `apiKey` are one\n//? key). Keys are merged with the framework defaults; `registerRedactedLogKeys`\n//? is additive — duplicate calls are idempotent.\n\nexport const DEFAULT_REDACTED_LOG_KEYS: readonly string[] = [\n 'password',\n 'confirmpassword',\n 'token',\n 'newtoken',\n 'authorization',\n 'cookie',\n 'set-cookie',\n 'csrftoken',\n 'apikey',\n 'secret',\n //? 2FA (ADR 0024). `totpSecret` already matches the `secret` suffix, but\n //? `recoveryCodes` matches neither the exact set nor any suffix — list it\n //? explicitly so the log-redaction floor mirrors the session sanitizer,\n //? which strips both `totpSecret` and `recoveryCodes`.\n 'recoverycodes',\n];\n\n//? Separators are dropped before matching so header- and snake-case spellings\n//? (`x-api-key`, `private_key`) meet the same defaults and suffixes.\nexport const normalizeLogKey = (key: string): string => key.toLowerCase().replaceAll(/[-_]/g, '');\n\n//? `redactedKeys` keeps the registered spelling (lowercased) for\n//? `getRedactedLogKeys`. `normalizedRedactedKeys` serves key lookups.\nconst redactedKeys = new Set<string>(DEFAULT_REDACTED_LOG_KEYS.map((key) => key.toLowerCase()));\nconst normalizedRedactedKeys = new Set<string>(DEFAULT_REDACTED_LOG_KEYS.map((key) => normalizeLogKey(key)));\n\n//? Sensitive SUFFIXES (0.2.0 widening). Exact-match alone missed compound keys\n//? a project naturally produces — `targetToken`, `sessionToken`, `clientSecret`,\n//? `stripeApiKey` — leaving real secrets in logs/breadcrumbs. A key whose\n//? lowercased form ENDS WITH one of these is redacted in addition to the exact\n//? set above. Suffix (not arbitrary substring) is deliberate: it catches the\n//? `<qualifier><Sensitive>` naming convention while a plain `substring` test\n//? would over-redact benign keys (e.g. a `tokenCount` metric, a `secretSanta`\n//? field). Kept conservative on purpose — register extra keys explicitly via\n//? `registerRedactedLogKeys` for project-specific names that don't fit.\n//? `secretkey` / `privatekey` cover `secretKey`, `stripeSecretKey`, `privateKey`\n//? (the bare `key` ending would over-redact `cacheKey`, `idempotencyKey`).\nexport const SENSITIVE_KEY_SUFFIXES: readonly string[] =['token', 'secret', 'apikey', 'password', 'secretkey', 'privatekey'];\n\nexport const registerRedactedLogKeys = (keys: readonly string[]): void => {\n for (const key of keys) {\n redactedKeys.add(key.toLowerCase());\n normalizedRedactedKeys.add(normalizeLogKey(key));\n }\n};\n\nexport const getRedactedLogKeys = (): readonly string[] => [...redactedKeys];\n\nexport const isRedactedLogKey = (key: string): boolean => {\n const normalized = normalizeLogKey(key);\n if (normalizedRedactedKeys.has(normalized)) return true;\n return SENSITIVE_KEY_SUFFIXES.some((suffix) => normalized.endsWith(suffix));\n};\n\n//? Test-only helper — restore the default seed set between integration tests.\n//? Never call from production code; keys registered at boot would be\n//? re-exposed.\nexport const resetRedactedLogKeysForTests = (): void => {\n redactedKeys.clear();\n normalizedRedactedKeys.clear();\n for (const key of DEFAULT_REDACTED_LOG_KEYS) {\n redactedKeys.add(key.toLowerCase());\n normalizedRedactedKeys.add(normalizeLogKey(key));\n }\n};\n\n/** Placeholder substituted for a redacted value. */\nexport const REDACTED_PLACEHOLDER = '[redacted]';\n\n//? Distinct from REDACTED_PLACEHOLDER so an over-deep BENIGN value (a numeric id,\n//? a timestamp) isn't mislabeled as a masked secret — the marker reads as\n//? structural truncation, not redaction.\nexport const DEPTH_TRUNCATED_PLACEHOLDER = '[truncated: max depth]';\n\n//? Depth cap so a self-referential / pathologically deep object can't make the\n//? sanitize pass blow the stack on a hot log/capture path.\nconst MAX_SANITIZE_DEPTH = 8;\n\n/**\n * Recursively deep-copy `value`, replacing any property whose key matches the\n * registered redacted-keys set (case-insensitive) with {@link REDACTED_PLACEHOLDER}\n * (SYNC-17 defense-in-depth). Use it at raw log / `captureException` context\n * sites so a token/password nested anywhere in a payload never lands verbatim in\n * a logger sink or error-tracker breadcrumb.\n *\n * - Primitives pass through unchanged.\n * - Arrays are mapped element-wise (array indices are never \"keys\", so an\n * element is only redacted by its own nested object keys).\n * - Cycles / over-deep graphs are cut at {@link MAX_SANITIZE_DEPTH} with\n * {@link DEPTH_TRUNCATED_PLACEHOLDER}; the input is never mutated.\n */\nexport const sanitizeForLog = (value: unknown, depth = 0, _seen?: WeakSet<object>): unknown => {\n if (depth > MAX_SANITIZE_DEPTH) return DEPTH_TRUNCATED_PLACEHOLDER;\n if (value === null || typeof value !== 'object') return value;\n\n //? Cycle detection: if we have already visited this reference higher up in the\n //? call stack, replace it with a marker rather than recursing into it — this\n //? prevents a stack overflow when `value` contains a circular reference (e.g.\n //? an Error whose `.cause` links back to itself, or a Node IncomingMessage\n //? with circular HTTP-socket references).\n const seen = _seen ?? new WeakSet<object>();\n if (seen.has(value)) return '[circular]';\n seen.add(value);\n\n try {\n if (Array.isArray(value)) {\n return value.map((item) => sanitizeForLog(item, depth + 1, seen));\n }\n\n const out: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {\n out[key] = isRedactedLogKey(key) ? REDACTED_PLACEHOLDER : sanitizeForLog(nested, depth + 1, seen);\n }\n return out;\n } finally {\n //? Leave the set on the way back up so `seen` holds only ANCESTORS: the same\n //? object in a sibling position (`{ actor: user, target: user }`) is shared,\n //? not circular, and must be copied rather than reported as a loop.\n seen.delete(value);\n }\n};\n","//? Pluggable logger so framework code does not have to write directly to\n//? stdout. The default implementation uses `console.{debug,info,warn,error}`\n//? directly with no trailing color-code argument — that argument was only\n//? meaningful when `initConsolelog()` (a dev-only monkey-patch) had been\n//? installed, but the default logger needs to be safe in production too.\n//?\n//? Installers route framework logs to Pino / Winston / Datadog / etc. by\n//? calling `registerLogger({ debug, info, warn, error })` once at boot,\n//? mirroring the rest of the registry pattern in this package. Dev installs\n//? that want colored output should call `registerLogger(createDevLogger())`.\n//?\n//? Read at call-time via `getLogger()` so registration order does not matter\n//? — same contract as `getProjectConfig()` and friends.\n\nimport { createRegistry } from './createRegistry';\nimport { getProjectConfig } from './projectConfig';\n\nexport type LoggerContext = Record<string, unknown>;\n\nexport interface Logger {\n debug: (message: string, context?: LoggerContext) => void;\n info: (message: string, context?: LoggerContext) => void;\n warn: (message: string, context?: LoggerContext) => void;\n error: (message: string, error?: unknown, context?: LoggerContext) => void;\n}\n\n//? Prefix a log message with an ISO-8601 UTC timestamp when\n//? `logging.timestamps` is on (the default). Read at call time so a consumer's\n//? config registration order doesn't matter, and so it can be toggled off under\n//? a log aggregator that stamps its own time. Only the framework's BUILT-IN\n//? loggers use this — a registered custom logger owns its own formatting.\nconst withTimestamp = (message: string): string =>\n getProjectConfig().logging.timestamps ? `[${new Date().toISOString()}] ${message}` : message;\n\nconst defaultLogger: Logger = {\n debug: (message, context) => {\n if (context === undefined) {console.debug(withTimestamp(message));}\n else {console.debug(withTimestamp(message), context);}\n },\n info: (message, context) => {\n if (context === undefined) {console.info(withTimestamp(message));}\n else {console.info(withTimestamp(message), context);}\n },\n warn: (message, context) => {\n if (context === undefined) {console.warn(withTimestamp(message));}\n else {console.warn(withTimestamp(message), context);}\n },\n error: (message, error, context) => {\n if (error !== undefined && context !== undefined) console.error(withTimestamp(message), error, context);\n else if (error !== undefined) console.error(withTimestamp(message), error);\n else if (context === undefined) {console.error(withTimestamp(message));}\n else {console.error(withTimestamp(message), context);}\n },\n};\n\n//? Dev-mode logger factory: wraps the default behavior with the colored\n//? terminal output that `initConsolelog()` produces. Install via\n//? `registerLogger(createDevLogger())` from a dev-only entry. Note: this\n//? still depends on `initConsolelog()` having been called to interpret the\n//? trailing color string — without it, the codes will appear as literal\n//? text. Use the default logger when running in production or unsure.\nexport const createDevLogger = (): Logger => ({\n debug: (message, context) => {\n if (context === undefined) {console.log(withTimestamp(message), 'cyan');}\n else {console.log(withTimestamp(message), context, 'cyan');}\n },\n info: (message, context) => {\n if (context === undefined) {console.log(withTimestamp(message));}\n else {console.log(withTimestamp(message), context);}\n },\n warn: (message, context) => {\n if (context === undefined) {console.log(withTimestamp(message), 'yellow');}\n else {console.log(withTimestamp(message), context, 'yellow');}\n },\n error: (message, error, context) => {\n if (error !== undefined && context !== undefined) console.log(withTimestamp(message), error, context, 'red');\n else if (error !== undefined) console.log(withTimestamp(message), error, 'red');\n else if (context === undefined) {console.log(withTimestamp(message), 'red');}\n else {console.log(withTimestamp(message), context, 'red');}\n },\n});\n\nconst registry = createRegistry<Logger>(defaultLogger);\n\nexport const registerLogger = (logger: Logger): void => {\n registry.register(logger);\n};\n\nexport const getLogger = (): Logger => registry.get();\n\nexport const isLoggerRegistered = (): boolean => registry.isRegistered();\n\n//? Test-only helper — restore the default logger between integration tests.\n//? Never call from production code.\nexport const resetLoggerForTests = (): void => {\n registry.reset();\n};\n","//? Backend-agnostic error-tracker registry. Lives in @luckystack/core\n//? (not @luckystack/error-tracking) because framework code in core /\n//? api / sync needs to call it without taking a hard dep on a specific\n//? observability backend. The error-tracking package provides adapter\n//? IMPLEMENTATIONS (Sentry, Datadog, PostHog); the slot lives here.\n//?\n//? Multiple adapters can be registered at once via `registerErrorTrackers([...])` —\n//? every event fans out to all of them. Per-adapter errors are swallowed\n//? so one buggy tracker can't break the chain.\n\n//? The AsyncLocalStorage identity scope deliberately lives in the separate\n//? server-only errorTrackerIdentity.ts module. This registry is also reached by\n//? the browser-safe legacy capture seam, so it must remain free of node:* imports.\nimport type { ErrorTrackerUser } from './errorTrackerIdentity';\nimport { getRedactedLogKeys, normalizeLogKey, REDACTED_PLACEHOLDER, sanitizeForLog, SENSITIVE_KEY_SUFFIXES } from './redactedLogKeys';\nimport { getLogger } from './loggerRegistry';\n\nexport type { ErrorTrackerUser } from './errorTrackerIdentity';\n\nexport type ErrorTrackerContext = Record<string, unknown>;\n\n//? SYNC-17 defense-in-depth: scrub registered redacted keys (tokens, passwords,\n//? auth/cookie headers) from the context object before it fans out to any\n//? adapter, so a raw token nested in a capture context never reaches Sentry /\n//? Datadog / PostHog breadcrumbs. Returns the original reference when there is\n//? nothing to sanitize (no context) to avoid needless allocation on the hot path.\nconst sanitizeContext = (context?: ErrorTrackerContext): ErrorTrackerContext | undefined => {\n if (!context) return context;\n return sanitizeForLog(context) as ErrorTrackerContext;\n};\n\n//? ET-O2 value-level scrub: error.message and error.stack can contain\n//? interpolated secrets (\"token=abc123\") that bypass the key-based context\n//? scrub. Replace `key=value` and `key: value` patterns for every registered\n//? redacted key so the string never reaches an adapter verbatim.\n//? Runs at capture time (not on every Error construction) to stay off the\n//? hot path; the result is cached on the sanitized context so each adapter\n//? fan-out step reads the same pre-scrubbed string.\n//? BOOT-TIME ONLY: `registerRedactedLogKeys` must be called at boot with a\n//? static key set (framework package init / project boot). Calling it with\n//? dynamically generated strings (route names, tenant IDs, etc.) at request\n//? time will cause this cache to grow without bound. A hard cap (200 entries)\n//? logs a warning when exceeded so misuse is immediately diagnosable.\nconst REDACTED_VALUE_RE_CACHE_MAX = 200;\ninterface ScrubPatternPair {\n urlParam: RegExp; // matches <key>=<value> (URL-param style)\n logLabel: RegExp; // matches <key>: <value> (log-label style)\n}\nconst REDACTED_VALUE_RE_CACHE = new Map<string, ScrubPatternPair>();\n\n//? A secret value: a double- or single-quoted string (escapes allowed), an\n//? HTTP auth scheme plus its credential, or a bare run up to a delimiter. The\n//? scheme alternative comes before the bare run so `Bearer <token>` is taken\n//? whole instead of stopping after the scheme word.\nconst SCRUB_VALUE = String.raw`(?:\"(?:[^\"\\\\\\r\\n]|\\\\.)+\"|'(?:[^'\\\\\\r\\n]|\\\\.)+'|(?:bearer|basic|digest|token)\\s+[^\\s,;\"'&]+|[^\\s,;\"'&]+)`;\n\nconst buildScrubPattern = (key: string): ScrubPatternPair => {\n const cached = REDACTED_VALUE_RE_CACHE.get(key);\n if (cached) return cached;\n if (REDACTED_VALUE_RE_CACHE.size >= REDACTED_VALUE_RE_CACHE_MAX) {\n try {\n getLogger().warn(`errorTracker: REDACTED_VALUE_RE_CACHE exceeded ${String(REDACTED_VALUE_RE_CACHE_MAX)} entries — registerRedactedLogKeys must only be called at boot with a static key set, not with dynamic/runtime-varying strings.`);\n } catch {\n // last-resort swallow\n }\n }\n //? `key` is normalized (no `-`/`_`); an optional separator between its\n //? characters matches `api_key`, `x-api-key` and `apiKey` alike, as the\n //? object-key lookup does. Each `[-_]?` takes at most one character and\n //? nothing around it repeats, so a failed match costs at most the key length.\n const escaped = Array.from(key, (char) => char.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`)).join('[-_]?');\n //? Two separate passes — one for `key=value` (URL-param style), one for\n //? `key: value` (log-label style) — to avoid alternation complexity and the\n //? subtle behaviours that arise when mixing capturing and non-capturing groups\n //? inside a single pattern (ET-O2 alternation fix).\n //? `+` (not `*`) for the value portion so `key=` with an empty value is NOT\n //? replaced (empty parameters are not secrets worth scrubbing and a `*` match\n //? would turn innocent `foo=` markers into `[redacted]`).\n //? The key may be followed by its closing quote (JSON `\"password\":\"x\"`) and\n //? spaces around the separator (`password = x`). A quoted value or an\n //? auth-scheme value (`Bearer <token>`) is consumed as one unit: stopping at\n //? the first space or quote left the actual secret behind.\n const pair: ScrubPatternPair = {\n urlParam: new RegExp(String.raw`${escaped}[\"']?\\s*=\\s*${SCRUB_VALUE}`, 'gi'),\n logLabel: new RegExp(String.raw`${escaped}[\"']?\\s*:\\s*${SCRUB_VALUE}`, 'gi'),\n };\n REDACTED_VALUE_RE_CACHE.set(key, pair);\n return pair;\n};\n\nexport const sanitizeErrorString = (value: string): string => {\n let result = value;\n // Scrub matching `key=value` / `key: value` patterns for every registered\n // redacted key so interpolated secrets (e.g. \"token=abc\") never reach an adapter.\n //? The suffixes join the registered keys: the pattern has no left boundary,\n //? so `secretkey` also catches `stripe_secret_key=`, like the key lookup.\n const scrubKeys = new Set([...getRedactedLogKeys(), ...SENSITIVE_KEY_SUFFIXES].map((key) => normalizeLogKey(key)));\n scrubKeys.delete('');\n for (const key of scrubKeys) {\n const { urlParam, logLabel } = buildScrubPattern(key);\n result = result.replace(urlParam, () => REDACTED_PLACEHOLDER).replace(logLabel, () => REDACTED_PLACEHOLDER);\n }\n return result;\n};\n\n//? Produce a sanitized version of an Error's message and stack so adapters\n//? can emit pre-scrubbed strings without touching the original Error object.\nexport const sanitizeErrorStrings = (\n error: unknown,\n): { message: string; stack: string | undefined } | null => {\n if (!(error instanceof Error)) return null;\n return {\n message: sanitizeErrorString(error.message),\n stack: error.stack === undefined ? undefined : sanitizeErrorString(error.stack),\n };\n};\n\nexport interface ErrorTrackerEvent {\n /** When false, the adapter must not forward this event (beforeSend opt-out). */\n forwarded: boolean;\n kind: 'exception' | 'message';\n payload: Record<string, unknown>;\n}\n\n//? `SpanResult<T>` was a conditional unwrap of Promise. It's now an alias\n//? for `T` directly because the conditional collapsed to T in both branches\n//? and tsup's dts emit choked on the conditional widening. Kept as an\n//? exported alias so adapter authors can still annotate with `SpanResult<T>`\n//? for documentation intent.\nexport type SpanResult<T> = T;\n\nexport interface ErrorTracker {\n /** Human-readable identifier (logs, diagnostics). */\n name: string;\n captureException: (error: unknown, context?: ErrorTrackerContext) => void;\n captureMessage: (\n message: string,\n level: 'info' | 'warning' | 'error' | 'fatal',\n context?: ErrorTrackerContext,\n ) => void;\n setUser: (user: ErrorTrackerUser | null) => void;\n setContext?: (key: string, context: ErrorTrackerContext | null) => void;\n startSpan?: <T>(name: string, op: string, fn: () => T) => T;\n /**\n * Optional handle-style span (#62): open a span NOW and close it later via the\n * returned handle's `finish()`. Unlike {@link startSpan} (which wraps a single\n * synchronous `fn`), this fits an open-at-preExecute / close-at-postExecute\n * request lifecycle that spans awaits. When present, the registry-level\n * {@link startSpanHandle} delegates to the FIRST registered adapter that\n * implements it so the request span reaches an adapter-only backend\n * (Datadog/PostHog/custom), not just the legacy Sentry SDK path.\n */\n startSpanHandle?: (name: string, op: string) => { finish: () => void };\n recordMetric?: (name: string, value: number, tags?: Record<string, string>) => void;\n beforeSend?: (event: ErrorTrackerEvent) => ErrorTrackerEvent | null;\n /**\n * Optional flush lifecycle hook (error-tracking ET batch). Called by\n * {@link flushErrorTrackers} on graceful shutdown so a buffered adapter\n * (PostHog batch, Sentry transport) can drain in-flight events before exit.\n * Returns a promise that resolves when the adapter has flushed.\n */\n flush?: () => Promise<void>;\n}\n\n//? Pre-capture filter (error-tracking ET batch). A registered filter runs on\n//? EVERY event just before fan-out; returning `false` DROPS the event entirely\n//? (e.g. suppress known-noisy errors, sample, or honour a per-event opt-out).\n//? Distinct from a per-adapter `beforeSend` (which transforms a single adapter's\n//? payload) — this gates the whole fan-out. Last-write-wins; `null` clears it.\nexport type PreCaptureFilter = (event: ErrorTrackerEvent) => boolean;\nlet preCaptureFilter: PreCaptureFilter | null = null;\n\nexport const registerPreCaptureFilter = (filter: PreCaptureFilter | null): void => {\n preCaptureFilter = filter;\n};\n\nconst passesPreCaptureFilter = (kind: 'exception' | 'message', payload: Record<string, unknown>): boolean => {\n if (!preCaptureFilter) return true;\n try {\n return preCaptureFilter({ forwarded: true, kind, payload });\n } catch {\n //? A throwing filter must not swallow telemetry — fail OPEN (forward).\n return true;\n }\n};\n\n//? ET-O6: the pre-capture filter payload now includes the error / message\n//? so filters can drop noisy errors by type/message (the documented use case).\n//? Separate helpers per kind so the call site stays type-safe.\nconst exceptionFilterPayload = (\n error: unknown,\n context: ErrorTrackerContext | undefined,\n): Record<string, unknown> => ({ error, context: context ?? null });\n\nconst messageFilterPayload = (\n message: string,\n level: string,\n context: ErrorTrackerContext | undefined,\n): Record<string, unknown> => ({ message, level, context: context ?? null });\n\nlet activeTrackers: ErrorTracker[] = [];\n\n//? REPLACE semantics — last-write-wins (ET-24 confirmed standard). Use\n//? `appendErrorTracker` when you need accumulate-not-replace (ET-05).\nexport const registerErrorTracker = (tracker: ErrorTracker): void => {\n activeTrackers = [tracker];\n};\n\nexport const registerErrorTrackers = (trackers: ErrorTracker[]): void => {\n activeTrackers = [...trackers];\n};\n\n/**\n * APPEND primitive (ET-05): add a tracker WITHOUT clobbering already-registered\n * ones. Fixes the async-PostHog-vs-consumer-overlay race where the loser of\n * `registerErrorTracker`'s replace silently vanished. De-duplicates by `name`\n * (re-appending the same adapter name replaces that one entry in place) so a\n * lazy adapter that registers a proxy then the real client doesn't double-fire.\n */\nexport const appendErrorTracker = (tracker: ErrorTracker): void => {\n const withoutSameName = activeTrackers.filter((t) => t.name !== tracker.name);\n activeTrackers = [...withoutSameName, tracker];\n};\n\nexport const getActiveErrorTrackers = (): ErrorTracker[] => activeTrackers;\n\n/**\n * Flush lifecycle (error-tracking ET batch): drain every adapter that exposes a\n * `flush()` before shutdown. Per-adapter failures are swallowed + logged so one\n * stuck adapter can't block graceful shutdown. Safe to call when no adapter has\n * `flush`.\n */\nexport const flushErrorTrackers = async (): Promise<void> => {\n await Promise.all(\n activeTrackers.map(async (tracker) => {\n if (!tracker.flush) return;\n try {\n await tracker.flush();\n } catch (error) {\n //? ET-O7: route to the shared failure logger (but never re-throw — a\n //? failing flush must not block graceful shutdown).\n logTrackerFailure(tracker.name, 'flush', error);\n }\n }),\n );\n};\n\nexport const captureExceptionAcrossTrackers = (\n error: unknown,\n context?: ErrorTrackerContext,\n): void => {\n const safeContext = sanitizeContext(context);\n if (!passesPreCaptureFilter('exception', exceptionFilterPayload(error, safeContext))) return;\n for (const tracker of activeTrackers) {\n try {\n tracker.captureException(error, safeContext);\n } catch (trackerError) {\n //? Fan-out error logging (error-tracking ET batch): a buggy tracker must\n //? not break the chain, but its failure was previously invisible. Log it\n //? (best-effort) so a misbehaving adapter is diagnosable.\n logTrackerFailure(tracker.name, 'captureException', trackerError);\n }\n }\n};\n\nexport const captureMessageAcrossTrackers = (\n message: string,\n level: 'info' | 'warning' | 'error' | 'fatal',\n context?: ErrorTrackerContext,\n): void => {\n const safeContext = sanitizeContext(context);\n if (!passesPreCaptureFilter('message', messageFilterPayload(message, level, safeContext))) return;\n for (const tracker of activeTrackers) {\n try {\n tracker.captureMessage(message, level, safeContext);\n } catch (trackerError) {\n logTrackerFailure(tracker.name, 'captureMessage', trackerError);\n }\n }\n};\n\n//? Best-effort fan-out failure logger. Wrapped in its own try/catch because the\n//? logger itself could throw on a broken sink, and a capture path must never\n//? throw.\nconst logTrackerFailure = (trackerName: string, op: string, error: unknown): void => {\n try {\n getLogger().warn(`errorTracker: \"${trackerName}\" threw in ${op}`, { error });\n } catch {\n // Last-resort swallow.\n }\n};\n\nexport const setErrorTrackerUser = (user: ErrorTrackerUser | null): void => {\n for (const tracker of activeTrackers) {\n try {\n tracker.setUser(user);\n } catch (error) {\n //? ET-O7: route to the shared failure logger so a misbehaving tracker is diagnosable.\n logTrackerFailure(tracker.name, 'setUser', error);\n }\n }\n};\n\nexport const recordMetricAcrossTrackers = (\n name: string,\n value: number,\n tags?: Record<string, string>,\n): void => {\n for (const tracker of activeTrackers) {\n if (tracker.recordMetric) {\n try {\n tracker.recordMetric(name, value, tags);\n } catch (error) {\n //? ET-O7: route to the shared failure logger so a misbehaving tracker is diagnosable.\n logTrackerFailure(tracker.name, 'recordMetric', error);\n }\n }\n }\n};\n\nexport const startSpanAcrossTrackers = <T>(name: string, op: string, fn: () => T): T => {\n //? Spans don't fan out cleanly to multiple backends — they're nested\n //? execution scopes. We only invoke the FIRST registered tracker's\n //? startSpan (others get notified via captureException paths if they\n //? want to instrument). When no tracker supports spans, run the fn directly.\n const first = activeTrackers.find((t) => t.startSpan);\n if (!first?.startSpan) return fn();\n return first.startSpan(name, op, fn);\n};\n\n/**\n * Handle-style span (error-tracking ET batch): for callers that can't wrap the\n * measured work in a single synchronous `fn` (streaming, cross-await spans).\n * Returns a handle whose `finish()` resolves the span's duration. The default\n * implementation is a lightweight wall-clock timer (works with any backend);\n * an adapter can supply a richer span via the existing `startSpan` callback\n * form when it needs native instrumentation. `finish()` is idempotent.\n */\nexport interface SpanHandle {\n /** Stop the span; safe to call more than once (subsequent calls are no-ops). */\n finish: () => void;\n /** Milliseconds elapsed at the moment `finish()` first ran (0 before). */\n readonly durationMs: number;\n}\n\n//? #62: open a handle-style span on the FIRST registered adapter that implements\n//? `startSpanHandle`, swallowing a throwing adapter so the wall-clock handle still\n//? works (telemetry must never break the request path). Returns `null` when no\n//? adapter supports handle-style spans.\nconst openDelegateSpanHandle = (name: string, op: string): { finish: () => void } | null => {\n const tracker = activeTrackers.find((t) => t.startSpanHandle);\n if (!tracker?.startSpanHandle) return null;\n try {\n return tracker.startSpanHandle(name, op);\n } catch (error) {\n logTrackerFailure(tracker.name, 'startSpanHandle', error);\n return null;\n }\n};\n\n//? #62: delegate the handle to the first adapter that supports `startSpanHandle`\n//? (so an adapter-only consumer — Datadog/PostHog/custom, no legacy Sentry SDK —\n//? actually gets request-timing spans), and ALWAYS keep the wall-clock timer as a\n//? backend-agnostic fallback + `durationMs` source. `finish()` is idempotent and\n//? closes the delegated span exactly once.\n//? ET-O9: removed the per-call `recordMetricAcrossTrackers` that fired on every\n//? startSpanHandle invocation — `durationMs` is available for callers that want to\n//? emit their own metric.\nexport const startSpanHandle = (name: string, op: string): SpanHandle => {\n const startedAt = Date.now();\n let finishedAt: number | null = null;\n const delegate = openDelegateSpanHandle(name, op);\n return {\n finish: () => {\n if (finishedAt !== null) return;\n finishedAt = Date.now();\n if (delegate) {\n try {\n delegate.finish();\n } catch (error) {\n logTrackerFailure('startSpanHandle', 'finish', error);\n }\n }\n },\n get durationMs() {\n return finishedAt === null ? 0 : finishedAt - startedAt;\n },\n };\n};\n","//? Legacy Sentry single-instance slot. Predates the multi-adapter\n//? ErrorTracker registry. New code should `registerErrorTracker(...)`\n//? from `@luckystack/error-tracking`; this file keeps backwards\n//? compatibility AND fans out events through any registered adapters so\n//? a project can mix legacy `initSharedSentry` + new `registerErrorTracker`\n//? during migration.\n//?\n//? The framework's own call sites (`captureException`, `captureMessage`,\n//? `setSentryUser`, `startSpan`) keep working unchanged — they now route\n//? through both the legacy slot and the new adapter list.\n\nimport {\n captureExceptionAcrossTrackers,\n captureMessageAcrossTrackers,\n setErrorTrackerUser,\n startSpanAcrossTrackers,\n} from './errorTrackerRegistry';\nimport { sanitizeForLog } from './redactedLogKeys';\n\ninterface SentryInstance {\n captureException: (exception: unknown, ...args: unknown[]) => string;\n captureMessage: (message: string, ...args: unknown[]) => string;\n setUser: (user: unknown) => void;\n setContext: (key: string, context: unknown) => void;\n startInactiveSpan?: (context: unknown) => unknown;\n}\n\nlet sentry: SentryInstance | undefined;\n\n/**\n * @deprecated Use `registerErrorTracker` from `@luckystack/error-tracking` instead.\n * Will be removed in a future major version.\n */\nexport const initSharedSentry = (instance: SentryInstance): void => {\n sentry = instance;\n};\n\n//? Pass `extra` inline via Sentry's hint-shaped second argument so contexts\n//? don't leak across concurrent captures. Previously we called\n//? `sentry.setContext('additional', context)` which is process-global until\n//? cleared — under concurrent captures the first context could leak into the\n//? second's report.\n//? CORE-O4: sanitize context before passing to the legacy Sentry slot so raw\n//? tokens/passwords don't reach `extra` when a consumer mixes initSharedSentry\n//? with framework capture. The multi-adapter path already sanitizes in\n//? errorTrackerRegistry.ts; this brings the legacy path into parity.\nexport const captureException = (\n error: unknown,\n context?: Record<string, unknown>,\n): void => {\n if (sentry) {\n if (context) {\n sentry.captureException(error, { extra: sanitizeForLog(context) as Record<string, unknown> });\n } else {\n sentry.captureException(error);\n }\n }\n //? Multi-adapter fan-out. When no adapter is registered this is a no-op.\n captureExceptionAcrossTrackers(error, context);\n};\n\nexport const captureMessage = (\n message: string,\n level: 'info' | 'warning' | 'error' | 'fatal' = 'info',\n context?: Record<string, unknown>,\n): void => {\n if (sentry) {\n if (context) {\n sentry.captureMessage(message, { level, extra: sanitizeForLog(context) as Record<string, unknown> });\n } else {\n sentry.captureMessage(message, level);\n }\n }\n captureMessageAcrossTrackers(message, level, context);\n};\n\nexport const setSentryUser = (user: {\n id?: string;\n email?: string;\n username?: string;\n} | null): void => {\n sentry?.setUser(user);\n setErrorTrackerUser(user);\n};\n\nexport const startSpan = (name: string, op: string): unknown => {\n //? Multi-adapter span coordination: first registered adapter that\n //? supports spans wins (spans don't fan out cleanly). Legacy Sentry\n //? single-instance path still creates the inactive span for backwards\n //? compatibility on consumers that haven't migrated.\n if (sentry?.startInactiveSpan) {\n return sentry.startInactiveSpan({ name, op });\n }\n //? No-op span body is intentional — this is the legacy inactive-span shape\n //? consumers built against; the real span lifecycle is managed elsewhere.\n // eslint-disable-next-line @typescript-eslint/no-empty-function -- legacy inactive-span shape\n startSpanAcrossTrackers(name, op, () => {});\n};\n"],"mappings":";;;;;;AAUO,IAAM,4BAA+C;AAAA,EAC1D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AACF;AAIO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M,iBAAiB,CAC5B,SACA,QAAgD,QAChD,YACS;AACT,MAAI,QAAQ;AACV,QAAI,SAAS;AACX,aAAO,eAAe,SAAS,EAAE,OAAO,OAAO,eAAe,OAAO,EAA6B,CAAC;AAAA,IACrG,OAAO;AACL,aAAO,eAAe,SAAS,KAAK;AAAA,IACtC;AAAA,EACF;AACA,+BAA6B,SAAS,OAAO,OAAO;AACtD;AAEO,IAAM,gBAAgB,CAAC,SAIX;AACjB,UAAQ,QAAQ,IAAI;AACpB,sBAAoB,IAAI;AAC1B;AAEO,IAAM,YAAY,CAAC,MAAc,OAAwB;AAK9D,MAAI,QAAQ,mBAAmB;AAC7B,WAAO,OAAO,kBAAkB,EAAE,MAAM,GAAG,CAAC;AAAA,EAC9C;AAIA,0BAAwB,MAAM,IAAI,MAAM;AAAA,EAAC,CAAC;AAC5C;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createRegistry
3
- } from "./chunk-PN2FPJXI.js";
3
+ } from "./chunk-55YXIACQ.js";
4
4
 
5
5
  // src/portOverrideRegistry.ts
6
6
  var portOverride;
@@ -85,4 +85,4 @@ export {
85
85
  registerSecretsResolvedListener,
86
86
  notifySecretsResolved
87
87
  };
88
- //# sourceMappingURL=chunk-6UPWMV6L.js.map
88
+ //# sourceMappingURL=chunk-YKVBUWB6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/portOverrideRegistry.ts","../src/deployConfigRegistry.ts","../src/servicesConfigRegistry.ts","../src/secretsResolved.ts"],"sourcesContent":["//? Browser-safe bridge between @luckystack/server/parseArgv and a consumer's\n//? config.ts. The positional CLI port is runtime input, while config.ports.ts\n//? remains the consumer-owned static default. Keeping this tiny registry in\n//? @luckystack/core/config lets both server and browser import the same config\n//? module without pulling Node-only server code into the client bundle.\n\nlet portOverride: number | undefined;\n\nconst validatePortOverride = (port: number): number => {\n if (!Number.isInteger(port) || port < 0 || port > 65_535) {\n throw new RangeError(\n `[luckystack:port] port override must be an integer from 0 through 65535, got: \"${String(port)}\".`,\n );\n }\n return port;\n};\n\nexport const registerPortOverride = (port: number | null): void => {\n portOverride = port === null ? undefined : validatePortOverride(port);\n};\n\nexport const getPortOverride = (): number | undefined => portOverride;\n\nexport const resetPortOverrideForTests = (): void => {\n portOverride = undefined;\n};\n","//? Deploy-time topology registered by the project at boot. Mirrors the\n//? `projectConfig` / `runtimeMapsRegistry` / `notifier` pattern: framework\n//? packages read deploy data through `getDeployConfig()` so they don't\n//? `import '../../../deploy.config'`.\n//?\n//? Only the fields core actually consumes are declared here. The project's\n//? richer `DeployConfig` (environments, bindings, routing, etc.) stays in\n//? `deploy.config.ts` and is consumed directly by the router package, which\n//? is project-glue (tier-B) and intentionally stays project-coupled.\n//?\n//? Project entrypoint registers via the direct file path\n//? (`./packages/core/src/deployConfigRegistry`) — same Vite-bundle rule we\n//? already use for projectConfig: importing the core barrel from a\n//? client-bundled file pulls server-only modules (Redis, paths, etc.).\n\nexport interface DeployResourceShape {\n type: 'redis' | 'mongo';\n urlEnvKey: string;\n synchronizedEnvKeys?: string[];\n}\n\nexport interface DeployEnvironmentShape {\n redis: string;\n mongo: string;\n fallback?: string;\n bindings: Record<string, string>;\n}\n\nexport interface DeployRoutingShape {\n onMissingService?: 'hard-error' | 'proxy-fallback';\n missingServiceErrorCode?: string;\n enableUnhealthyFallback?: boolean;\n strictBootHandshake?: boolean;\n /**\n * Opt INTO the boot-handshake's synchronized-env (cookie/session secret) drift\n * check. DEFAULT false — the router stays a dumb proxy that holds NO backend\n * secrets. Comparing synchronized-env hashes requires the router process to\n * carry the same SESSION_SECRET etc. as the backends, which most deployments\n * deliberately avoid; the always-on shared-Redis handshake is unaffected. Set\n * true only when you intentionally give the router the synchronized secrets.\n */\n verifySynchronizedEnv?: boolean;\n /** Default port the router listens on when ROUTER_PORT env var is unset (default 4000). */\n defaultRouterPort?: number;\n /** Default ms between health polls when not specified per-call (default 5000). */\n defaultHealthPollMs?: number;\n /** ms before the fallback `/_health` probe times out (default 3000). */\n healthProbeTimeoutMs?: number;\n /** Seconds the boot-UUID Redis key lives for (default 3600 = 1h). */\n bootKeyTtlSeconds?: number;\n /**\n * ms before the router gives up proxying to an upstream backend (SEC-30 /\n * router-DeployRoutingShape). Guards against slow-loris upstreams holding a\n * router worker open. The router reads this when building its proxy request.\n * DEFAULT undefined → router falls back to its own built-in default.\n */\n upstreamTimeoutMs?: number;\n /**\n * Name of the service that terminates websocket (Socket.io) traffic. The\n * router pins WS upgrade requests to this service (they cannot be load-balanced\n * round-robin without sticky sessions). DEFAULT undefined → router uses its\n * `system` convention.\n */\n websocketService?: string;\n /**\n * Immediate TLS proxy addresses/CIDRs allowed to assert\n * `x-forwarded-proto: https`. Empty/undefined trusts nobody, so a client\n * directly reaching the router cannot spoof secure-scheme backend logic.\n * Examples: `['127.0.0.1/32', '::1/128']` for same-host nginx/Caddy, or the\n * private subnet of a managed load balancer. Such a proxy may also name the\n * visitor in `x-forwarded-for`: the router forwards the last hop that proxy\n * appended.\n */\n trustedProxyCidrs?: string[];\n /**\n * Path the router exposes for its OWN health/liveness (distinct from the\n * backend `/_health` boot-handshake endpoint). DEFAULT undefined → router\n * uses its built-in default.\n */\n routerHealthPath?: string;\n /**\n * Max request body size (bytes) the router will buffer/forward before\n * rejecting with 413. DEFAULT undefined → router uses its built-in default.\n */\n maxRequestBodyBytes?: number;\n /**\n * Max size (bytes) of the upgrade `head` buffer the WS proxy forwards to the\n * upstream during a WebSocket handshake. An over-cap head is rejected (the\n * client socket is destroyed) BEFORE the upstream leg opens, so a client\n * cannot push an unbounded pre-upgrade buffer through the router. DEFAULT\n * undefined → router uses its built-in default (64 KiB).\n */\n wsMaxHeadBytes?: number;\n /**\n * Idle-timeout (ms) for an UPGRADED WebSocket pipe: when no bytes flow in\n * either direction for this long, the router tears the proxied pair down.\n * Bounds an otherwise-unbounded pre/post-auth pipe a client could hold open\n * against the router. The timer resets on any activity. DEFAULT undefined →\n * router uses its built-in default (120000 ms = 2 min). Set `0` to disable.\n */\n wsIdleTimeoutMs?: number;\n /**\n * Per-connection byte budget for an UPGRADED WebSocket pipe: when the total\n * bytes piped across both legs exceed this cap, the router tears the proxied\n * pair down. Bounds how much a single connection can stream through the\n * router. DEFAULT undefined → router uses its built-in default (100 MiB). Set\n * `false` to disable the cap (unbounded).\n */\n wsMaxBytesPerConnection?: number | false;\n}\n\nexport interface DeployDevelopmentShape {\n enableFallbackRouting?: boolean;\n healthPollMs?: number;\n switchNewTrafficToLocalWhenHealthy?: boolean;\n}\n\nexport interface DeployConfigShape {\n resources: Record<string, DeployResourceShape>;\n environments?: Record<string, DeployEnvironmentShape>;\n routing?: DeployRoutingShape;\n development?: DeployDevelopmentShape;\n}\n\nimport { createRegistry } from './createRegistry';\n\nconst DEFAULT_DEPLOY_CONFIG: DeployConfigShape = {\n resources: {},\n};\n\nconst registry = createRegistry<DeployConfigShape>(DEFAULT_DEPLOY_CONFIG);\n\nexport const registerDeployConfig = (config: DeployConfigShape): DeployConfigShape =>\n registry.register(config);\n\nexport const getDeployConfig = (): DeployConfigShape => registry.get();\n\nexport const isDeployConfigRegistered = (): boolean => registry.isRegistered();\n","//? Services config registry. The router (and presetLoader) consume the\n//? consumer's services topology — which services exist, which presets bundle\n//? them together — through this registry instead of a relative\n//? `../../../services.config` import.\n//?\n//? The consumer's `services.config.ts` registers its config at module import\n//? (side-effect pattern, identical to `deploy.config.ts:151`). Router code\n//? calls `getServicesConfig()` at request time.\n\nexport interface ServiceDefinition {\n /** 'root' -> reserved for the system service. Otherwise a folder name under srcDir. */\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents -- 'root' is documented as the reserved value; the union surfaces it in autocomplete\n source: 'root' | string;\n}\n\nexport interface PresetDefinition {\n description?: string;\n /** Services that are bundled together into one backend artifact. */\n services: string[];\n}\n\nexport interface ServicesConfigShape {\n services: Record<string, ServiceDefinition>;\n presets: Record<string, PresetDefinition>;\n /**\n * Pure-data ownership manifest for HTTP routes outside `/api/*` and `/sync/*`.\n * Keys are absolute path prefixes; values are service keys. The router uses\n * longest-prefix matching, so `/webhooks/admin` may override `/webhooks`.\n */\n customRoutes?: Record<string, string>;\n}\n\nimport { createRegistry } from './createRegistry';\n\nconst registry = createRegistry<ServicesConfigShape>(\n //? Unregistered sentinel — `get` never returns this because `resolveDefault`\n //? throws first. Typed as the real shape so the slot stays well-typed.\n { services: {}, presets: {} },\n {\n resolveDefault: (): ServicesConfigShape => {\n throw new Error(\n '@luckystack/core: services config has not been registered. Call ' +\n '`registerServicesConfig({...})` from your `services.config.ts` (which should be ' +\n 'imported as a side-effect during boot).'\n );\n },\n },\n);\n\nexport const registerServicesConfig = (config: ServicesConfigShape): ServicesConfigShape =>\n registry.register(config);\n\nexport const getServicesConfig = (): ServicesConfigShape => registry.get();\n\nexport const isServicesConfigRegistered = (): boolean => registry.isRegistered();\n","//? Decoupled \"secrets were (re)resolved\" notification channel.\n//?\n//? A secret resolver fires `notifySecretsResolved(changedKeys)` right after it\n//? overwrites `process.env` with the real values (at boot AND on rotation).\n//? `@luckystack/secret-manager` fires it AUTOMATICALLY after every resolve (via\n//? the global-symbol channel at the bottom of this file — no import edge, no\n//? `onApplied` wiring needed).\n//? Listeners then drop any client they built from the PRE-resolution env so the\n//? next use rebuilds with the resolved secret.\n//?\n//? This is deliberately generic and lives in core with ZERO dependency on\n//? secret-manager: core self-registers a Redis listener (see `redis.ts`), and\n//? any other cached-client owner (a Prisma pool, an SDK client) can subscribe\n//? the same way without coupling to the resolver package.\n\nexport type SecretsResolvedListener = (changedKeys: readonly string[] | undefined) => void;\n\nconst listeners = new Set<SecretsResolvedListener>();\n\n//? Subscribe to secret-resolution events. Returns an unsubscribe function.\nexport const registerSecretsResolvedListener = (listener: SecretsResolvedListener): (() => void) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n};\n\n//? Fire all listeners. `changedKeys` = the env NAMES whose value actually\n//? changed (never the secret values). Omit it (`undefined`) when the caller\n//? doesn't know which keys changed — listeners then treat it as \"assume\n//? relevant\" and reset defensively.\nexport const notifySecretsResolved = (changedKeys?: readonly string[]): void => {\n for (const listener of listeners) {\n try {\n listener(changedKeys);\n } catch {\n //? A misbehaving listener must never break the resolve/boot path.\n }\n }\n};\n\n//? Cross-PACKAGE channel: publish THIS core instance's `notifySecretsResolved`\n//? on a well-known global-symbol array so a decoupled package that must not\n//? depend on `@luckystack/core` — notably `@luckystack/secret-manager`, the\n//? zero-dependency resolver — can fire it right after it resolves secrets, with\n//? NO import edge. An ARRAY (not a single slot) so that if the process somehow\n//? has more than one `@luckystack/core` instance (dual-package / mixed src+dist\n//? resolution — a real footgun that also causes the env-revert), EVERY instance's\n//? redis registry gets the rebuilt client, not just the last one loaded.\nconst GLOBAL_LISTENERS_SYMBOL = Symbol.for('luckystack.secretsResolved.listeners');\n\nconst getGlobalSecretsResolvedListeners = (): SecretsResolvedListener[] => {\n const existing: unknown = Reflect.get(globalThis, GLOBAL_LISTENERS_SYMBOL);\n if (Array.isArray(existing)) return existing as SecretsResolvedListener[];\n const created: SecretsResolvedListener[] = [];\n Reflect.set(globalThis, GLOBAL_LISTENERS_SYMBOL, created);\n return created;\n};\n\ngetGlobalSecretsResolvedListeners().push(notifySecretsResolved);\n"],"mappings":";;;;;AAMA,IAAI;AAEJ,IAAM,uBAAuB,CAAC,SAAyB;AACrD,MAAI,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,OAAQ;AACxD,UAAM,IAAI;AAAA,MACR,kFAAkF,OAAO,IAAI,CAAC;AAAA,IAChG;AAAA,EACF;AACA,SAAO;AACT;AAEO,IAAM,uBAAuB,CAAC,SAA8B;AACjE,iBAAe,SAAS,OAAO,SAAY,qBAAqB,IAAI;AACtE;AAEO,IAAM,kBAAkB,MAA0B;AAElD,IAAM,4BAA4B,MAAY;AACnD,iBAAe;AACjB;;;ACqGA,IAAM,wBAA2C;AAAA,EAC/C,WAAW,CAAC;AACd;AAEA,IAAM,WAAW,eAAkC,qBAAqB;AAEjE,IAAM,uBAAuB,CAAC,WACnC,SAAS,SAAS,MAAM;AAEnB,IAAM,kBAAkB,MAAyB,SAAS,IAAI;AAE9D,IAAM,2BAA2B,MAAe,SAAS,aAAa;;;ACvG7E,IAAMA,YAAW;AAAA;AAAA;AAAA,EAGf,EAAE,UAAU,CAAC,GAAG,SAAS,CAAC,EAAE;AAAA,EAC5B;AAAA,IACE,gBAAgB,MAA2B;AACzC,YAAM,IAAI;AAAA,QACR;AAAA,MAGF;AAAA,IACF;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB,CAAC,WACrCA,UAAS,SAAS,MAAM;AAEnB,IAAM,oBAAoB,MAA2BA,UAAS,IAAI;AAElE,IAAM,6BAA6B,MAAeA,UAAS,aAAa;;;ACrC/E,IAAM,YAAY,oBAAI,IAA6B;AAG5C,IAAM,kCAAkC,CAAC,aAAoD;AAClG,YAAU,IAAI,QAAQ;AACtB,SAAO,MAAM;AACX,cAAU,OAAO,QAAQ;AAAA,EAC3B;AACF;AAMO,IAAM,wBAAwB,CAAC,gBAA0C;AAC9E,aAAW,YAAY,WAAW;AAChC,QAAI;AACF,eAAS,WAAW;AAAA,IACtB,QAAQ;AAAA,IAER;AAAA,EACF;AACF;AAUA,IAAM,0BAA0B,uBAAO,IAAI,sCAAsC;AAEjF,IAAM,oCAAoC,MAAiC;AACzE,QAAM,WAAoB,QAAQ,IAAI,YAAY,uBAAuB;AACzE,MAAI,MAAM,QAAQ,QAAQ,EAAG,QAAO;AACpC,QAAM,UAAqC,CAAC;AAC5C,UAAQ,IAAI,YAAY,yBAAyB,OAAO;AACxD,SAAO;AACT;AAEA,kCAAkC,EAAE,KAAK,qBAAqB;","names":["registry"]}
package/dist/client.d.ts CHANGED
@@ -25,7 +25,7 @@ export { registerApiMethodMap, getRegisteredApiMethod, isApiMethodMapRegistered,
25
25
  export type { HttpMethodLiteral, ApiMethodMap } from './apiMethodMapRegistry.js';
26
26
  export { registerLocales, getRegisteredLocales, getDefaultLocale, registerLanguageSource, getActiveLanguage, getLocaleByCode, } from './localesRegistry.js';
27
27
  export type { LocalesMap, LanguageSource } from './localesRegistry.js';
28
- export { registerMiddlewareHandler, getMiddlewareHandler, registerPageMiddleware, getPageMiddleware, hasPageMiddleware, } from './middlewareRegistry.js';
28
+ export { registerMiddlewareHandler, getMiddlewareHandler, registerPageMiddleware, registerPageRoute, getPageMiddleware, hasPageMiddleware, resolvePageMiddleware, } from './middlewareRegistry.js';
29
29
  export type { MiddlewareInput, MiddlewareResult, MiddlewareOutcome, MiddlewareHandler, PageMiddleware, } from './middlewareRegistry.js';
30
30
  export { registerClientHook, dispatchClientHook, dispatchVetoableClientHook, } from './clientHookBus.js';
31
31
  export type { ClientHookName, ClientHookHandler, ClientHookPayloadMap, ClientHookStopSignal, ClientHookResult, ClientDispatchResult, } from './clientHookBus.js';