@luckystack/core 0.6.2 → 0.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/apiInterceptors.ts","../src/apiRequest.ts","../src/tryCatchClient.ts","../src/localesRegistry.ts","../src/middlewareRegistry.ts","../src/react/sessionContext.ts","../src/react/AvatarProvider.tsx","../src/react/useTheme.ts","../src/react/TranslationProvider.tsx","../src/react/notify.ts","../src/react/Middleware.tsx","../src/react/Router.tsx"],"sourcesContent":["//? EXT-03 — client-side request/response interceptor registry for `apiRequest`.\r\n//?\r\n//? `apiRequest` (apiRequest.ts) is a monolithic typed function and Rule 21 /\r\n//? the `no-unsafe-api-wrappers` lint forbid wrapping it (a wrapper erases the\r\n//? route/version inference). This registry is the sanctioned escape hatch: a\r\n//? consumer registers an interceptor here instead of wrapping the call, so the\r\n//? typed call site is untouched and route/version inference survives.\r\n//?\r\n//? Two seams, both fire-and-mutate (NOT replace — the dispatcher reserves a\r\n//? structured return for control flow):\r\n//? - request interceptors run just before the socket emit. A handler may\r\n//? mutate `ctx.data` in place (inject a correlation id / feature-flag\r\n//? context / tenant header-equivalent) and is observation-only otherwise.\r\n//? - response interceptors run when the response envelope arrives, before the\r\n//? awaiting caller resolves. Observation-only (metrics, breadcrumb, custom\r\n//? logging). The envelope is NOT mutated by this seam — response rewriting\r\n//? belongs on the server `preApiRespond` / `transformApiResponse` hooks.\r\n//?\r\n//? Handlers are best-effort: a throw / rejection is caught + logged and never\r\n//? breaks the request pipeline. Both `register*` functions return an\r\n//? unsubscribe closure, matching `registerClientHook`'s contract.\r\n\r\nexport interface ApiRequestInterceptorContext {\r\n /** Resolved route name (`<page>/<api>` or `system/<api>`). */\r\n name: string;\r\n /** Route version literal (e.g. `'v1'`). */\r\n version: string;\r\n /**\r\n * Outgoing request payload. Mutate this object in place to augment the\r\n * request (correlation id, feature-flag context, ...). Replacing the\r\n * reference has no effect — mutate keys on the existing object.\r\n */\r\n data: Record<string, unknown>;\r\n}\r\n\r\nexport interface ApiResponseInterceptorContext {\r\n name: string;\r\n version: string;\r\n /** The response envelope the caller is about to receive (read-only intent). */\r\n response: { status: 'success' | 'error'; [key: string]: unknown };\r\n}\r\n\r\nexport type ApiRequestInterceptor = (\r\n ctx: ApiRequestInterceptorContext,\r\n) => void | Promise<void>;\r\n\r\nexport type ApiResponseInterceptor = (\r\n ctx: ApiResponseInterceptorContext,\r\n) => void | Promise<void>;\r\n\r\nimport { getLogger } from './loggerRegistry';\r\n\r\nconst requestInterceptors = new Set<ApiRequestInterceptor>();\r\nconst responseInterceptors = new Set<ApiResponseInterceptor>();\r\n\r\n/**\r\n * Register an outgoing-request interceptor. Returns an unsubscribe function.\r\n * Multiple interceptors run in registration order; each may mutate `ctx.data`.\r\n */\r\nexport function registerApiRequestInterceptor(interceptor: ApiRequestInterceptor): () => void {\r\n requestInterceptors.add(interceptor);\r\n return () => {\r\n requestInterceptors.delete(interceptor);\r\n };\r\n}\r\n\r\n/**\r\n * Register an incoming-response interceptor. Returns an unsubscribe function.\r\n */\r\nexport function registerApiResponseInterceptor(interceptor: ApiResponseInterceptor): () => void {\r\n responseInterceptors.add(interceptor);\r\n return () => {\r\n responseInterceptors.delete(interceptor);\r\n };\r\n}\r\n\r\n//? Framework-internal — invoked by `apiRequest`. Awaited so a handler can do an\r\n//? async lookup (read a flag store, mint a trace id) before the emit. Snapshot\r\n//? the set so a handler unregistering mid-dispatch can't skip a sibling.\r\nexport async function dispatchApiRequestInterceptors(\r\n ctx: ApiRequestInterceptorContext,\r\n): Promise<void> {\r\n if (requestInterceptors.size === 0) return;\r\n //? Snapshot so a handler that unregisters itself (or a sibling) mid-dispatch\r\n //? doesn't skip an un-visited handler.\r\n const interceptors = [...requestInterceptors];\r\n for (const interceptor of interceptors) {\r\n try {\r\n await interceptor(ctx);\r\n } catch (error) {\r\n getLogger().error('[apiRequestInterceptor] handler threw', error);\r\n }\r\n }\r\n}\r\n\r\n//? Framework-internal — invoked by `apiRequest` when the response arrives.\r\n//? Fire-and-forget (the caller does not await) so an interceptor can't delay\r\n//? the resolve; async rejections are caught + logged.\r\nexport function dispatchApiResponseInterceptors(\r\n ctx: ApiResponseInterceptorContext,\r\n): void {\r\n if (responseInterceptors.size === 0) return;\r\n //? Snapshot (see `dispatchApiRequestInterceptors`).\r\n const interceptors = [...responseInterceptors];\r\n for (const interceptor of interceptors) {\r\n try {\r\n const result = interceptor(ctx);\r\n if (result && typeof (result as Promise<unknown>).catch === 'function') {\r\n (result as Promise<unknown>).catch((error: unknown) => {\r\n getLogger().error('[apiResponseInterceptor] async handler rejected', error);\r\n });\r\n }\r\n } catch (error) {\r\n getLogger().error('[apiResponseInterceptor] handler threw', error);\r\n }\r\n }\r\n}\r\n\r\n/** Test helper — drop every registered interceptor. Not part of the public API. */\r\nexport function _resetApiInterceptorsForTests(): void {\r\n requestInterceptors.clear();\r\n responseInterceptors.clear();\r\n}\r\n","import { getProjectConfig } from \"./projectConfig\";\r\nimport { getLogger } from \"./loggerRegistry\";\r\nimport { getRegisteredApiMethod } from \"./apiMethodMapRegistry\";\r\nimport { isGetMethodName } from \"./httpApiUtils\";\r\nimport { incrementResponseIndex, socket, waitForSocket } from \"./socketState\";\r\nimport type { ApiTypeMap, StreamPayload } from './apiTypeStubs';\r\nimport { notify } from \"./notifier\";\r\nimport { enqueueApiRequest, isOnline, removeApiQueueItem } from \"./offlineQueue\";\r\nimport { Socket } from \"socket.io-client\";\r\nimport { normalizeErrorResponseCore } from \"./responseNormalizer\";\r\nimport { parseServiceRouteName } from \"./serviceRoute\";\r\nimport tryCatchSync from \"./tryCatchSync\";\r\nimport {\r\n buildApiResponseEventName,\r\n buildApiStreamEventName,\r\n socketEventNames,\r\n} from \"./socketEvents\";\r\nimport {\r\n dispatchApiRequestInterceptors,\r\n dispatchApiResponseInterceptors,\r\n} from \"./apiInterceptors\";\r\n\r\n//? Abort controller logic:\r\n//? - abortable: true → always use abort controller\r\n//? - abortable: false → never use abort controller\r\n//? - abortable: undefined → use abort controller for GET APIs (from generated types)\r\n//? Keyed by `fullName` + a stable hash of the request `data` so the\r\n//? replace-previous (dedupe) semantics only fire for an IDENTICAL in-flight\r\n//? call. Two components polling the same GET route with DIFFERENT params no\r\n//? longer abort each other (each gets its own bucket); a genuine duplicate\r\n//? still supersedes the prior one.\r\n//? Size-capped at 1000 entries. All normal code paths (resolve, abort, disconnect,\r\n//? timeout) call `cleanupAbortController()` which deletes the entry. The cap\r\n//? is a safety net for edge cases where cleanup is skipped (socket torn down\r\n//? without a `disconnect` event, or a future code path that forgets to clean up).\r\nconst ABORT_CONTROLLERS_MAX = 1000;\r\nconst abortControllers = new Map<string, AbortController>();\r\n\r\n//? Stable, order-insensitive JSON stringify so `{a:1,b:2}` and `{b:2,a:1}`\r\n//? hash to the same abort-controller key. Falls back to a non-deduping unique\r\n//? token when the payload can't be serialised (circular ref), which is the\r\n//? safe choice — an unserialisable payload should never silently abort a\r\n//? sibling request.\r\nconst stableStringify = (value: unknown): string => {\r\n const seen = new WeakSet<object>();\r\n const walk = (input: unknown): unknown => {\r\n if (input === null || typeof input !== 'object') return input;\r\n if (seen.has(input)) return '[circular]';\r\n seen.add(input);\r\n if (Array.isArray(input)) return input.map((entry) => walk(entry));\r\n const record = input as Record<string, unknown>;\r\n const out: Record<string, unknown> = {};\r\n for (const key of Object.keys(record).toSorted()) {\r\n out[key] = walk(record[key]);\r\n }\r\n return out;\r\n };\r\n const [error, json] = tryCatchSync(() => JSON.stringify(walk(value)));\r\n if (error || typeof json !== 'string') {\r\n return `__unserializable__:${String(Date.now())}-${String(Math.random())}`;\r\n }\r\n return json;\r\n};\r\n\r\nconst buildAbortKey = (fullName: string, data: unknown): string =>\r\n `${fullName}::${stableStringify(data)}`;\r\n\r\nexport type ApiStreamEvent<T extends StreamPayload = StreamPayload> = T;\r\n\r\n/**\r\n * Check if an API is a GET method.\r\n *\r\n * Primary path: consult the registered `apiMethodMap` (generated from the\r\n * actual handler's `httpMethod` export or name-based inference at codegen\r\n * time). Falls back to name-prefix heuristic only when the map isn't\r\n * registered yet — typically because the consumer hasn't called\r\n * `registerApiMethodMap(...)` from their `socketInitializer.ts` boot file.\r\n */\r\nconst isGetMethodByPrefix = (apiName: string): boolean => isGetMethodName(apiName.toLowerCase());\r\n\r\nconst resolveGetMethod = (apiName: string, version: string): { isGet: boolean; usingHeuristic: boolean } => {\r\n //? Resolved-name shape: `pagePath/apiName`. apiMethodMap is nested by\r\n //? pagePath → apiName → version. Split at the last `/` so multi-segment\r\n //? page paths (e.g. 'admin/users') still resolve.\r\n const lastSlash = apiName.lastIndexOf('/');\r\n if (lastSlash > 0) {\r\n const pagePath = apiName.slice(0, lastSlash);\r\n const leaf = apiName.slice(lastSlash + 1);\r\n const method = getRegisteredApiMethod(pagePath, leaf, version);\r\n if (method) return { isGet: method === 'GET', usingHeuristic: false };\r\n }\r\n return { isGet: isGetMethodByPrefix(apiName), usingHeuristic: true };\r\n};\r\n\r\nconst canSendNow = (socketInstance: Socket) => {\r\n if (!socketInstance.connected) return false;\r\n return isOnline();\r\n};\r\n\r\nconst createQueueId = () => {\r\n return `${String(Date.now())}-${String(Math.random())}`;\r\n};\r\n\r\n//? Resolve logging flags at call time so registration order doesn't matter.\r\n//? `getLogging()` is called inside each handler instead of captured at load.\r\nconst getLogging = () => getProjectConfig().logging;\r\nconst shouldLogDev = () => getLogging().devLogs;\r\nconst shouldNotifyDev = () => getLogging().devNotifications;\r\nconst shouldLogStream = () => getLogging().stream;\r\n\r\nconst shouldUseAbortController = ({\r\n abortable,\r\n isGet,\r\n usingHeuristic,\r\n}: {\r\n abortable: boolean | undefined;\r\n isGet: boolean;\r\n usingHeuristic: boolean;\r\n}) => {\r\n if (abortable === true) return true;\r\n if (abortable === false) return false;\r\n //? CORE-O15: when `abortable` is unspecified and we are relying on the\r\n //? name-prefix heuristic (apiMethodMap not registered), default to\r\n //? non-abortable. A mis-named POST (e.g. `getReport`) would otherwise\r\n //? silently abort an identical in-flight call it has nothing to do with.\r\n //? Once `registerApiMethodMap` is called (normal boot), the generated map\r\n //? resolves the method and the heuristic path is never taken.\r\n if (usingHeuristic) return false;\r\n return isGet;\r\n};\r\n\r\n\r\n// ═══════════════════════════════════════════════════════════════════════════════\r\n// Type Helpers\r\n// ═══════════════════════════════════════════════════════════════════════════════\r\n\r\n// Check if data input is required (i.e., T does NOT allow empty object)\r\n// Unions like {a:1} | {b:1} do NOT allow {}, so data will be required\r\ntype DataRequired<T> = Record<string, never> extends T ? false : true;\r\n\r\ntype UnionToIntersection<U> =\r\n (U extends unknown ? (arg: U) => void : never) extends ((arg: infer I) => void)\r\n ? I\r\n : never;\r\n\r\n// ═══════════════════════════════════════════════════════════════════════════════\r\n// Global API Params - Union of ALL valid API calls with proper data enforcement\r\n// ═══════════════════════════════════════════════════════════════════════════════\r\ntype ApiRouteRecord = UnionToIntersection<{\r\n [P in keyof ApiTypeMap]: {\r\n [N in keyof ApiTypeMap[P] as P extends 'root'\r\n ? `system/${Extract<N, string>}`\r\n : `${Extract<P, string>}/${Extract<N, string>}`]: ApiTypeMap[P][N]\r\n }\r\n}[keyof ApiTypeMap]>;\r\n\r\ntype ApiFullName = Extract<keyof ApiRouteRecord, string>;\r\ntype VersionsForFullName<F extends ApiFullName> = keyof ApiRouteRecord[F] & string;\r\n\r\n// Force expansion of types to clear aliases in tooltips\r\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\r\n\r\n// Get input type for an API name (union if exists on multiple pages)\r\ntype InputForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = ApiRouteRecord[F][V] extends { input: infer I }\r\n ? I\r\n : never;\r\n\r\n// Get output type for an API name (union if exists on multiple pages)\r\ntype OutputForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = ApiRouteRecord[F][V] extends { output: infer O }\r\n ? O\r\n : never;\r\n\r\ntype StreamForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = ApiRouteRecord[F][V] extends { stream: infer S }\r\n ? S\r\n : never;\r\n\r\ntype ApiStreamCallbackForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> =\r\n [StreamForFullName<F, V>] extends [never]\r\n ? never\r\n : (event: ApiStreamEvent<Prettify<StreamForFullName<F, V> extends StreamPayload ? StreamForFullName<F, V> : StreamPayload>>) => void;\r\n\r\n// Build params type for a specific API name\r\ntype ApiParamsForFullName<\r\n F extends ApiFullName,\r\n V extends VersionsForFullName<F>\r\n> = DataRequired<InputForFullName<F, V>> extends true\r\n ? { name: F; version: V; data: Prettify<InputForFullName<F, V>>; abortable?: boolean; disableErrorMessage?: boolean; onStream?: ApiStreamCallbackForFullName<F, V>; signal?: AbortSignal; timeoutMs?: number | false; }\r\n : { name: F; version: V; data?: Prettify<InputForFullName<F, V>>; abortable?: boolean; disableErrorMessage?: boolean; onStream?: ApiStreamCallbackForFullName<F, V>; signal?: AbortSignal; timeoutMs?: number | false; };\r\n\r\ninterface RuntimeApiParams {\r\n name?: string;\r\n version?: string;\r\n data?: unknown;\r\n abortable?: boolean;\r\n disableErrorMessage?: boolean;\r\n onStream?: (event: ApiStreamEvent) => void;\r\n signal?: AbortSignal;\r\n /** Per-call response timeout (ms). Overrides `api.requestTimeoutMs`. `false` disables. */\r\n timeoutMs?: number | false;\r\n}\r\n\r\nexport interface ApiErrorResponse extends Record<string, unknown> {\r\n status: 'error';\r\n httpStatus: number;\r\n message: string;\r\n errorCode: string;\r\n errorParams?: { key: string; value: string | number | boolean }[];\r\n}\r\n\r\ninterface ApiSuccessResponse extends Record<string, unknown> {\r\n status: 'success';\r\n httpStatus: number;\r\n}\r\n\r\ntype ApiResponse = ApiErrorResponse | ApiSuccessResponse;\r\n\r\nconst normalizeApiError = ({\r\n response,\r\n fallbackErrorCode,\r\n fallbackHttpStatus = 500,\r\n}: {\r\n response: { status: 'error'; errorCode?: string; errorParams?: { key: string; value: string | number | boolean }[]; httpStatus?: number; message?: string };\r\n fallbackErrorCode: string;\r\n fallbackHttpStatus?: number;\r\n}): ApiErrorResponse => {\r\n const normalized = normalizeErrorResponseCore({\r\n response,\r\n fallbackErrorCode,\r\n fallbackHttpStatus,\r\n resolveMessage: ({ errorCode }) => {\r\n if (typeof response.message === 'string' && response.message.trim().length > 0) {\r\n return response.message;\r\n }\r\n return errorCode;\r\n },\r\n });\r\n\r\n return {\r\n status: 'error',\r\n message: normalized.message,\r\n errorCode: normalized.errorCode,\r\n errorParams: normalized.errorParams,\r\n httpStatus: normalized.httpStatus ?? fallbackHttpStatus,\r\n };\r\n};\r\n\r\n/**\r\n * Type-safe API request function.\r\n * \r\n * @example\r\n * ```typescript\r\n * // Full name usage - includes page in the name\r\n * const result = await apiRequest({ name: 'examples/publicApi', version: 'v1', data: { message: 'hello' } });\r\n * // result is typed correctly for publicApi\r\n * \r\n * // Global APIs use service-first naming\r\n * await apiRequest({ name: 'system/session', version: 'v1' });\r\n * ```\r\n */\r\n\r\nexport function apiRequest<F extends ApiFullName, V extends VersionsForFullName<F>>(\r\n params: ApiParamsForFullName<F, V>\r\n): Promise<Prettify<OutputForFullName<F, V>> | ApiErrorResponse> {\r\n type RequestOutput = Prettify<OutputForFullName<F, V> & ApiResponse>;\r\n const runtimeParams = params as RuntimeApiParams;\r\n const { name, version, disableErrorMessage = false, onStream, signal: externalSignal, timeoutMs } = runtimeParams;\r\n const payloadData = runtimeParams.data;\r\n\r\n return new Promise<RequestOutput>((resolve) => {\r\n void (async () => {\r\n //? B1 — if the consumer-supplied signal is already aborted at call\r\n //? time, short-circuit before we even touch the socket. Mirrors the\r\n //? `fetch(url, { signal })` contract.\r\n if (externalSignal?.aborted) {\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'request.aborted' },\r\n fallbackErrorCode: 'request.aborted',\r\n }) as RequestOutput);\r\n return;\r\n }\r\n if (!name || typeof name !== \"string\") {\r\n if (shouldLogDev()) {\r\n getLogger().error(\"apiRequest: Invalid name\");\r\n }\r\n if (shouldNotifyDev()) {\r\n notify.error({ key: 'api.invalidName' });\r\n }\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'api.invalidName' },\r\n fallbackErrorCode: 'api.invalidName',\r\n }) as RequestOutput);\r\n return;\r\n }\r\n\r\n if (!version || typeof version !== 'string') {\r\n if (shouldLogDev()) {\r\n getLogger().error(\"apiRequest: Invalid version\");\r\n }\r\n if (shouldNotifyDev()) {\r\n notify.error({ key: 'api.invalidVersion' });\r\n }\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'api.invalidVersion' },\r\n fallbackErrorCode: 'api.invalidVersion',\r\n }) as RequestOutput);\r\n return;\r\n }\r\n\r\n const parsedRoute = parseServiceRouteName(name);\r\n if (parsedRoute.status === 'error') {\r\n if (shouldLogDev()) {\r\n getLogger().error(`[apiRequest] Invalid service route name`, undefined, { name, reason: parsedRoute.reason });\r\n }\r\n if (shouldNotifyDev()) {\r\n notify.error({ key: 'routing.invalidServiceRouteName' });\r\n }\r\n resolve(normalizeErrorResponseCore({\r\n response: {\r\n status: 'error',\r\n errorCode: 'routing.invalidServiceRouteName',\r\n errorParams: [{ key: 'name', value: name }],\r\n },\r\n fallbackErrorCode: 'routing.invalidServiceRouteName',\r\n }) as RequestOutput);\r\n return;\r\n }\r\n\r\n const sanitizedName = parsedRoute.normalizedRouteName;\r\n\r\n const data = payloadData && typeof payloadData === \"object\" ? payloadData : {};\r\n\r\n if (!await waitForSocket()) {\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'api.ioUnavailable' },\r\n fallbackErrorCode: 'api.ioUnavailable',\r\n }) as RequestOutput);\r\n return;\r\n }\r\n if (!socket) {\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'api.ioUnavailable' },\r\n fallbackErrorCode: 'api.ioUnavailable',\r\n }) as RequestOutput);\r\n return;\r\n }\r\n\r\n //? Abort controller logic:\r\n //? - abortable: true → always use abort controller\r\n //? - abortable: false → never use abort controller\r\n //? - abortable: undefined → smart default (GET-like APIs get abort controller)\r\n //? Pass the full pagePath/apiName so the registry lookup can resolve via\r\n //? the generated apiMethodMap (falls back to the leaf-name prefix heuristic\r\n //? when the map isn't registered yet).\r\n const { isGet, usingHeuristic } = resolveGetMethod(sanitizedName, version);\r\n const useAbortController = shouldUseAbortController({\r\n abortable: runtimeParams.abortable,\r\n isGet,\r\n usingHeuristic,\r\n });\r\n const fullName = `api/${sanitizedName}/${version}`;\r\n //? Per-payload abort key: only an identical in-flight call to the same\r\n //? route supersedes the previous one (see `buildAbortKey` rationale).\r\n const abortKey = buildAbortKey(fullName, data);\r\n\r\n let signal: AbortSignal | null = null;\r\n let abortHandler: (() => void) | null = null;\r\n let queueId: string | null = null;\r\n let cleanupStreamListener: (() => void) | null = null;\r\n //? Response listener cleanup, registered once the `.once` handler is\r\n //? attached in `runRequest`. Lets the abort path proactively `off()` the\r\n //? lingering response listener instead of waiting for a response that was\r\n //? cancelled and will never arrive.\r\n let cleanupResponseListener: (() => void) | null = null;\r\n //? Response-timeout timer. Armed right after the request is emitted so a\r\n //? lost response (server restart/crash between emit and reply) settles the\r\n //? promise instead of hanging the awaiting caller forever.\r\n let responseTimeout: ReturnType<typeof setTimeout> | null = null;\r\n const clearResponseTimeout = () => {\r\n if (responseTimeout) {\r\n clearTimeout(responseTimeout);\r\n responseTimeout = null;\r\n }\r\n };\r\n\r\n const cleanupAbortController = () => {\r\n if (signal && abortHandler) {\r\n signal.removeEventListener(\"abort\", abortHandler);\r\n }\r\n abortControllers.delete(abortKey);\r\n };\r\n\r\n if (useAbortController) {\r\n if (abortControllers.has(abortKey)) {\r\n const prevAbortController = abortControllers.get(abortKey);\r\n prevAbortController?.abort();\r\n }\r\n //? Evict the oldest entry when the cap is reached (LRU-insert-order).\r\n //? Map preserves insertion order; the first key is the oldest in-flight entry.\r\n if (!abortControllers.has(abortKey) && abortControllers.size >= ABORT_CONTROLLERS_MAX) {\r\n const oldest = abortControllers.keys().next().value;\r\n if (oldest !== undefined) abortControllers.delete(oldest);\r\n }\r\n const abortController = new AbortController();\r\n abortControllers.set(abortKey, abortController);\r\n signal = abortController.signal;\r\n\r\n abortHandler = () => {\r\n clearResponseTimeout();\r\n cleanupStreamListener?.();\r\n cleanupStreamListener = null;\r\n cleanupResponseListener?.();\r\n cleanupResponseListener = null;\r\n cleanupAbortController();\r\n if (queueId) {\r\n removeApiQueueItem(queueId);\r\n }\r\n //? Resolve (not reject) with the same `request.aborted` envelope the\r\n //? external-signal abort path uses. Rejecting here produced an\r\n //? unhandled rejection for fire-and-forget GET calls that get\r\n //? superseded by the default replace-previous behaviour.\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'request.aborted' },\r\n fallbackErrorCode: 'request.aborted',\r\n }) as RequestOutput);\r\n };\r\n\r\n signal.addEventListener(\"abort\", abortHandler);\r\n }\r\n\r\n const runRequest = (socketInstance: Socket) => {\r\n if (!canSendNow(socketInstance)) {\r\n queueId ??= createQueueId();\r\n //? For the immediate reject-new path (`drop-newest` / `reject`\r\n //? policy) THIS item's `onDrop` fires SYNCHRONOUSLY inside\r\n //? `enqueueApiRequest`. We keep surfacing that as the historical\r\n //? `offline.queueFull` via the `!enqueued` branch, so suppress the\r\n //? `onDrop` resolve during the synchronous enqueue window and re-arm\r\n //? it only if the item was actually queued (so a LATER async eviction\r\n //? — drop-oldest by a future enqueue, or age expiry — still settles).\r\n let suppressOnDrop = true;\r\n //? `enqueueApiRequest` returns `false` when the offline queue is\r\n //? full and `dropPolicy: 'reject'` is active. Without honoring\r\n //? that signal the outer promise never settles and the caller\r\n //? awaits forever. Resolve with a normalized error envelope so\r\n //? callers can branch.\r\n const enqueued = enqueueApiRequest({\r\n id: queueId,\r\n key: fullName,\r\n run: (nextSocket) => {\r\n runRequest(nextSocket);\r\n },\r\n createdAt: Date.now(),\r\n //? CORE: mirror SYNC-09. Settle the awaiting caller when this\r\n //? QUEUED request is later EVICTED (drop-oldest by a future\r\n //? enqueue / age expiry) instead of ever running. Without it the\r\n //? promise hangs forever, since `run` is the only thing that could\r\n //? otherwise resolve it — `apiRequest` had drifted from the sibling\r\n //? `syncRequest` which already had this fix. Also tear down the\r\n //? abort-controller registry entry so it isn't leaked.\r\n onDrop: (reason) => {\r\n if (suppressOnDrop) return;\r\n cleanupAbortController();\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'offline.dropped', errorParams: [{ key: 'reason', value: reason }] },\r\n fallbackErrorCode: 'offline.dropped',\r\n }) as RequestOutput);\r\n },\r\n });\r\n //? Past the synchronous enqueue window: if the item is sitting in the\r\n //? queue, a future eviction should settle via `onDrop`.\r\n suppressOnDrop = false;\r\n if (!enqueued) {\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'offline.queueFull', httpStatus: 503 },\r\n fallbackErrorCode: 'offline.queueFull',\r\n fallbackHttpStatus: 503,\r\n }) as RequestOutput);\r\n } else if (externalSignal && queueId) {\r\n //? CORE-O14: if an external AbortSignal fires while the item is\r\n //? sitting in the offline queue, its listener inside runRequest has\r\n //? not been registered yet. Register a one-shot handler here so the\r\n //? abort is not silently ignored and the queue slot is reclaimed.\r\n const capturedQueueId = queueId;\r\n const queueAbortHandler = () => {\r\n removeApiQueueItem(capturedQueueId);\r\n cleanupAbortController();\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'request.aborted' },\r\n fallbackErrorCode: 'request.aborted',\r\n }) as RequestOutput);\r\n };\r\n externalSignal.addEventListener('abort', queueAbortHandler, { once: true });\r\n }\r\n return;\r\n }\r\n\r\n if (signal?.aborted) {\r\n return;\r\n }\r\n\r\n const tempIndex = incrementResponseIndex();\r\n socketInstance.emit(socketEventNames.apiRequest, { name: fullName, data, responseIndex: tempIndex });\r\n\r\n //? B1 — bridge the consumer's AbortSignal to the server. When the\r\n //? signal fires we emit `apiCancel { responseIndex }` so the server\r\n //? handler stops emitting new chunks. We also resolve locally with\r\n //? `request.aborted` so the awaiting caller settles (vs awaiting\r\n //? a response that will never arrive because we cancelled it).\r\n let cleanupExternalAbort: (() => void) | null = null;\r\n if (externalSignal) {\r\n const externalAbortHandler = () => {\r\n clearResponseTimeout();\r\n socketInstance.emit(socketEventNames.apiCancel, { responseIndex: tempIndex });\r\n cleanupStreamListener?.();\r\n cleanupStreamListener = null;\r\n cleanupResponseListener?.();\r\n cleanupResponseListener = null;\r\n cleanupAbortController();\r\n cleanupExternalAbort?.();\r\n cleanupExternalAbort = null;\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'request.aborted' },\r\n fallbackErrorCode: 'request.aborted',\r\n }) as RequestOutput);\r\n };\r\n externalSignal.addEventListener('abort', externalAbortHandler);\r\n cleanupExternalAbort = () => {\r\n externalSignal.removeEventListener('abort', externalAbortHandler);\r\n };\r\n }\r\n\r\n //? Arm the response timeout. A per-call `timeoutMs` overrides the\r\n //? `api.requestTimeoutMs` config default; either may be `false` to\r\n //? disable. On expiry we tear down every listener/controller and settle\r\n //? with a 504 envelope so the awaiting caller never hangs.\r\n clearResponseTimeout();\r\n const effectiveTimeoutMs = timeoutMs ?? getProjectConfig().api.requestTimeoutMs;\r\n if (typeof effectiveTimeoutMs === 'number' && effectiveTimeoutMs > 0) {\r\n responseTimeout = setTimeout(() => {\r\n responseTimeout = null;\r\n cleanupStreamListener?.();\r\n cleanupStreamListener = null;\r\n cleanupResponseListener?.();\r\n cleanupResponseListener = null;\r\n cleanupExternalAbort?.();\r\n cleanupExternalAbort = null;\r\n cleanupAbortController();\r\n if (queueId) {\r\n removeApiQueueItem(queueId);\r\n }\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'api.timeout', httpStatus: 504 },\r\n fallbackErrorCode: 'api.timeout',\r\n fallbackHttpStatus: 504,\r\n }) as RequestOutput);\r\n }, effectiveTimeoutMs);\r\n }\r\n\r\n if (typeof onStream === 'function') {\r\n const streamEventName = buildApiStreamEventName(tempIndex);\r\n const streamListener = (streamPayload: ApiStreamEvent) => {\r\n if (signal?.aborted) {\r\n return;\r\n }\r\n\r\n if (shouldLogStream()) {\r\n getLogger().debug(`Server API Stream(${String(tempIndex)})`, { APINAME: sanitizedName, streamPayload });\r\n }\r\n\r\n onStream(streamPayload);\r\n };\r\n\r\n socketInstance.on(streamEventName, streamListener);\r\n cleanupStreamListener = () => {\r\n socketInstance.off(streamEventName, streamListener);\r\n };\r\n }\r\n\r\n if (shouldLogDev()) {\r\n getLogger().debug(`Client API Request(${String(tempIndex)})`, { APINAME: sanitizedName, data });\r\n }\r\n\r\n //? Inside the handler we type as the runtime envelope (ApiResponse).\r\n //? Project-specific output narrowing only matters at the call site,\r\n //? where `RequestOutput = OutputForFullName<F,V> & ApiResponse` is\r\n //? returned via `resolve(... as RequestOutput)`. When core is type-\r\n //? checked in isolation (e.g. per-package tsup dts build), ApiTypeMap\r\n //? is empty so OutputForFullName collapses to never; using ApiResponse\r\n //? here keeps the body type-safe in both cases.\r\n const responseEventName = buildApiResponseEventName(tempIndex);\r\n const responseListener = (response: ApiResponse) => {\r\n if (signal?.aborted) {\r\n clearResponseTimeout();\r\n cleanupExternalAbort?.();\r\n cleanupExternalAbort = null;\r\n return;\r\n }\r\n\r\n clearResponseTimeout();\r\n cleanupStreamListener?.();\r\n cleanupStreamListener = null;\r\n cleanupExternalAbort?.();\r\n cleanupExternalAbort = null;\r\n //? Call cleanup (not just null) so that any watcher layered on top of\r\n //? cleanupResponseListener (e.g. the CORE-O13 disconnect watcher) is\r\n //? properly torn down when a normal response arrives.\r\n cleanupResponseListener?.();\r\n cleanupResponseListener = null;\r\n\r\n const status = response.status;\r\n\r\n //? EXT-03 — fire client response interceptors when the envelope\r\n //? arrives (observation-only: metrics, breadcrumb, custom logging).\r\n dispatchApiResponseInterceptors({ name: sanitizedName, version, response });\r\n\r\n if (shouldLogDev()) {\r\n getLogger().debug(`Server API Response(${String(tempIndex)})`, { ...response, APINAME: sanitizedName });\r\n }\r\n\r\n if (status === \"error\") {\r\n const normalizedError = normalizeErrorResponseCore({ response });\r\n\r\n if (!disableErrorMessage) {\r\n if (normalizedError.errorCode) {\r\n notify.error({ key: normalizedError.errorCode, params: normalizedError.errorParams });\r\n } else {\r\n notify.error({ key: normalizedError.message });\r\n }\r\n }\r\n\r\n Object.assign(response, normalizedError);\r\n cleanupAbortController();\r\n resolve(response as RequestOutput);\r\n return;\r\n }\r\n\r\n cleanupAbortController();\r\n\r\n resolve(response as RequestOutput);\r\n };\r\n\r\n socketInstance.once(responseEventName, responseListener);\r\n cleanupResponseListener = () => {\r\n socketInstance.off(responseEventName, responseListener);\r\n };\r\n\r\n //? CORE-O13: when timeout is disabled AND there is no abort controller\r\n //? a server restart between emit and reply leaves this promise pending\r\n //? forever, leaking the response listener. The disconnect event is the\r\n //? authoritative signal that no reply will ever arrive on this socket.\r\n const disconnectHandler = () => {\r\n if (cleanupResponseListener) {\r\n cleanupResponseListener();\r\n cleanupResponseListener = null;\r\n }\r\n cleanupStreamListener?.();\r\n cleanupStreamListener = null;\r\n cleanupExternalAbort?.();\r\n cleanupExternalAbort = null;\r\n clearResponseTimeout();\r\n cleanupAbortController();\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'api.disconnected' },\r\n fallbackErrorCode: 'api.disconnected',\r\n }) as RequestOutput);\r\n };\r\n socketInstance.once('disconnect', disconnectHandler);\r\n //? Wrap the response listener to also remove the disconnect watcher on\r\n //? a normal reply (avoids a dangling listener on every successful call).\r\n const originalCleanupResponseListener = cleanupResponseListener;\r\n cleanupResponseListener = () => {\r\n socketInstance.off('disconnect', disconnectHandler);\r\n originalCleanupResponseListener();\r\n };\r\n };\r\n\r\n //? EXT-03 — fire client request interceptors just before the emit. They\r\n //? may mutate `data` in place (correlation id / feature-flag context).\r\n //? `data` is the same reference passed to `socketInstance.emit`, so the\r\n //? mutation is on the wire. Awaited so an async interceptor (flag lookup,\r\n //? trace-id mint) completes first; failures are caught + logged inside.\r\n await dispatchApiRequestInterceptors({\r\n name: sanitizedName,\r\n version,\r\n data: data as Record<string, unknown>,\r\n });\r\n\r\n //? CORE-O12: re-check the external abort signal after the interceptor\r\n //? await. A slow async interceptor adds uncounted latency; if the caller\r\n //? aborted during that window the signal is already fired but nothing has\r\n //? yet attached its listener (that happens inside runRequest). Settling\r\n //? here avoids emitting a request whose response will never be consumed.\r\n if (externalSignal?.aborted) {\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'request.aborted' },\r\n fallbackErrorCode: 'request.aborted',\r\n }) as RequestOutput);\r\n return;\r\n }\r\n\r\n runRequest(socket);\r\n })();\r\n });\r\n}","//? Browser-safe sibling of `tryCatch`. Behaviourally identical (same tuple,\r\n//? same params, same auto-capture on the error path) but it does NOT statically\r\n//? import `./sentrySetup`. The server `tryCatch.ts` reaches `sentrySetup` →\r\n//? `errorTrackerRegistry` → `node:async_hooks` at module-eval; that static edge\r\n//? is harmless on the server but drags a `node:`-externalized module into the\r\n//? Vite CLIENT bundle whenever a client importer (LoginForm) pulls\r\n//? `shared/tryCatch.ts`. So the client-reachable shim resolves HERE instead, and\r\n//? the only path to capture is a LAZY dynamic import taken on the error branch —\r\n//? keeping the node-bearing module out of the client's static graph.\r\n//?\r\n//? The server's `tryCatch.ts` is intentionally left untouched (byte-for-byte) so\r\n//? the server capture path keeps its synchronous, statically-linked behaviour.\r\n//? On the client, capture is best-effort and async-via-microtask is fine.\r\n\r\nexport default async function tryCatch<T, P = void>(\r\n func: (values: P) => Promise<T> | T,\r\n params?: P,\r\n context?: Record<string, unknown>\r\n): Promise<[Error | null, T | null]> {\r\n try {\r\n const response = await func(params as P);\r\n return [null, response];\r\n } catch (error) {\r\n //? Lazy capture: the import is only evaluated on the error branch, so the\r\n //? `node:async_hooks`-bearing module never enters the client's static graph.\r\n const { captureException } = await import('./sentrySetup');\r\n captureException(error, context);\r\n return [error instanceof Error ? error : new Error(String(error)), null];\r\n }\r\n}\r\n","//? Locales registry — lets the framework's TranslationProvider + notify\r\n//? read the consumer's translation JSON files without baking them into the\r\n//? package. Consumer overlay: `luckystack/i18n/locales.ts` calls\r\n//? `registerLocales({ en: enJson, nl: nlJson, ... })`.\r\n//?\r\n//? Language source: a separate registry — `registerLanguageSource(fn)` —\r\n//? lets the consumer wire up where the active language comes from\r\n//? (typically the SessionProvider's current `session.language`). When no\r\n//? source is registered, the framework falls back to\r\n//? `getProjectConfig().defaultLanguage`.\r\n\r\nimport { getProjectConfig } from './projectConfig';\r\n\r\nexport type LocalesMap = Record<string, unknown>;\r\nexport type LanguageSource = () => string | null | undefined;\r\n\r\nlet activeLocales: LocalesMap = {};\r\nlet activeLanguageSource: LanguageSource | null = null;\r\n\r\nexport const registerLocales = (locales: LocalesMap): void => {\r\n activeLocales = locales;\r\n};\r\n\r\nexport const getRegisteredLocales = (): LocalesMap => activeLocales;\r\n\r\nexport const getDefaultLocale = (): string => getProjectConfig().defaultLanguage || 'en';\r\n\r\nexport const registerLanguageSource = (fn: LanguageSource): void => {\r\n activeLanguageSource = fn;\r\n};\r\n\r\nexport const getActiveLanguage = (): string => {\r\n if (activeLanguageSource) {\r\n const lang = activeLanguageSource();\r\n if (typeof lang === 'string' && lang.length > 0) return lang;\r\n }\r\n return getDefaultLocale();\r\n};\r\n\r\n//? Lookup a language's translation tree by code. Falls back to default\r\n//? language when the code isn't registered. Used by TranslationProvider\r\n//? + notify to resolve the active translations.\r\nexport const getLocaleByCode = (code: string): unknown => {\r\n if (code in activeLocales) return activeLocales[code];\r\n const fallback = getDefaultLocale();\r\n if (fallback in activeLocales) return activeLocales[fallback];\r\n return {};\r\n};\r\n","//? Middleware handler registry. The framework's `Middleware` + `Router`\r\n//? components (in `./react/`) call the registered handler on every\r\n//? navigation change to decide whether the user is allowed on the target\r\n//? route. Per-page `export const middleware` (see `registerPageMiddleware`\r\n//? below) is the canonical path; a consumer wanting a cross-cutting GLOBAL\r\n//? guard registers it from the client bootstrap (typically `main.tsx`) via\r\n//? `registerMiddlewareHandler(...)`. No separate\r\n//? `src/_functions/middlewareHandler.ts` file is required.\r\n\r\nimport type { BaseSessionLayout } from './sessionTypes';\r\n\r\nexport interface MiddlewareInput {\r\n location: string;\r\n searchParams: Record<string, string>;\r\n session: BaseSessionLayout | null;\r\n}\r\n\r\nexport type MiddlewareResult =\r\n | { success: true; redirect?: undefined }\r\n | { success: false; redirect: string }\r\n | undefined;\r\n\r\nexport type MiddlewareHandler = (input: MiddlewareInput) => MiddlewareResult | Promise<MiddlewareResult>;\r\n\r\n//? Default handler: allow by default. Per-page `middleware` exports on each\r\n//? `page.tsx` are the canonical route-guard path (see `registerPageMiddleware`\r\n//? below); the global handler is only consulted as a fallback for pages\r\n//? that don't declare their own guard. Allowing-by-default keeps public\r\n//? routes (`/`, `/login`, `/register`, ...) working without forcing every\r\n//? consumer to ship a `src/_functions/middlewareHandler.ts` boilerplate\r\n//? file just to opt-in to \"let the user through\".\r\n//?\r\n//? Consumers who need a cross-cutting global guard (telemetry, server-\r\n//? reachability check, maintenance banner gate) call\r\n//? `registerMiddlewareHandler(...)` directly from `main.tsx` with their own\r\n//? function — no separate file required.\r\nconst DEFAULT_HANDLER: MiddlewareHandler = () => ({ success: true });\r\n\r\nlet activeHandler: MiddlewareHandler = DEFAULT_HANDLER;\r\n\r\nexport const registerMiddlewareHandler = (handler: MiddlewareHandler): void => {\r\n activeHandler = handler;\r\n};\r\n\r\nexport const getMiddlewareHandler = (): MiddlewareHandler => activeHandler;\r\n\r\n//? Per-page middleware registry. Counterpart to `registerMiddlewareHandler`\r\n//? for the common case where each page declares its own guard locally\r\n//? (`export const middleware = ({ session }) => {...}` from page.tsx).\r\n//? The framework's `<Middleware>` component checks this map FIRST and only\r\n//? falls back to the global handler when no per-page entry is registered.\r\n//?\r\n//? `PageMiddleware<TSession>` matches the existing `MiddlewareHandler`\r\n//? signature so any handler shape is reusable on either side. The generic\r\n//? is purely ergonomic for consumer-side type narrowing — module\r\n//? augmentation of `BaseSessionLayout` flows through.\r\n\r\nexport type PageMiddleware<TSession extends BaseSessionLayout = BaseSessionLayout> = (\r\n input: { location: string; searchParams: Record<string, string>; session: TSession | null },\r\n) => MiddlewareResult | Promise<MiddlewareResult>;\r\n\r\nconst pageMiddlewares = new Map<string, PageMiddleware>();\r\n\r\nexport const registerPageMiddleware = (path: string, middleware: PageMiddleware): void => {\r\n pageMiddlewares.set(path, middleware);\r\n};\r\n\r\nexport const getPageMiddleware = (path: string): PageMiddleware | undefined =>\r\n pageMiddlewares.get(path);\r\n\r\nexport const hasPageMiddleware = (path: string): boolean => pageMiddlewares.has(path);\r\n\r\n/** Test helper — drop every registered per-page middleware. */\r\nexport const clearPageMiddlewaresForTests = (): void => {\r\n pageMiddlewares.clear();\r\n};\r\n","//? Shared session context. Defined in core so framework-React components\r\n//? (Middleware, Router, useSession-aware UI) can consume it without\r\n//? pulling in app code. The consumer's `SessionProvider` (in their\r\n//? template's `_providers/`) does the actual fetch/socket/lifecycle work\r\n//? and writes to this context via `<SessionContext value={...}>`.\r\n//?\r\n//? The session shape inside the context is intentionally loose\r\n//? (`BaseSessionLayout | null`) so app code with extended session types\r\n//? can read it through a typed `useSession<MySession>()` cast.\r\n\r\nimport { createContext, use } from 'react';\r\nimport type { BaseSessionLayout } from '../sessionTypes';\r\nimport {\r\n dispatchClientHook,\r\n dispatchVetoableClientHook,\r\n type ClientHookStopSignal,\r\n} from '../clientHookBus';\r\n\r\nexport interface SessionContextValue<TSession extends BaseSessionLayout = BaseSessionLayout> {\r\n session: TSession | null;\r\n sessionLoaded: boolean;\r\n}\r\n\r\nconst DEFAULT_VALUE: SessionContextValue = {\r\n session: null,\r\n sessionLoaded: false,\r\n};\r\n\r\nexport const SessionContext = createContext<SessionContextValue>(DEFAULT_VALUE);\r\n\r\nexport function useSession<TSession extends BaseSessionLayout = BaseSessionLayout>(): SessionContextValue<TSession> {\r\n return use(SessionContext) as SessionContextValue<TSession>;\r\n}\r\n\r\n//? Non-React accessor for code that runs outside the component tree\r\n//? (e.g. notify() called from a non-component). Kept in sync with the\r\n//? context by the consumer's SessionProvider via `setLatestSession()`.\r\nlet latestSession: BaseSessionLayout | null = null;\r\n\r\nexport const setLatestSession = (session: BaseSessionLayout | null): void => {\r\n const previous = latestSession;\r\n latestSession = session;\r\n\r\n //? Fire client-side lifecycle hooks on null↔non-null transitions. Covers\r\n //? both fresh login AND existing-session restore on page reload — both\r\n //? cases need the same downstream actions (room auto-join, analytics\r\n //? identify, etc). Same-id updates (avatar refresh, profile change) do\r\n //? NOT fire postLogin; if a `sessionUpdate` hook is needed later, add it\r\n //? as a third branch without breaking existing handlers.\r\n if (previous === null && session !== null) {\r\n dispatchClientHook('postLogin', { session });\r\n } else if (previous !== null && session === null) {\r\n dispatchClientHook('postLogout', { previousSession: previous });\r\n }\r\n};\r\n\r\n//? Caller-supplied `TSession` is used to narrow the return type at the\r\n//? callsite (consumers extend `BaseSessionLayout`). The lint rule sees it as\r\n//? \"used once\" but the parameter exists solely to surface the consumer's\r\n//? widened session type through the read API.\r\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- callsite-narrowing use\r\nexport const getCurrentSession = <TSession extends BaseSessionLayout = BaseSessionLayout>(): TSession | null =>\r\n latestSession as TSession | null;\r\n\r\n/**\r\n * Vetoable entry point for committing a null → session transition (i.e. a\r\n * fresh login or a page-load session restore). Dispatches the `preLogin`\r\n * client hook to every registered handler in parallel; if any returns a\r\n * stop signal, the transition is aborted and `{ committed: false, signal }`\r\n * is returned. Otherwise, `setLatestSession(session)` runs synchronously\r\n * (which fires `postLogin`) and `{ committed: true }` comes back.\r\n *\r\n * Consumer's `SessionProvider` should `await` this for non-null session\r\n * commits and roll local React state back to `null` when a veto comes\r\n * through, so the UI doesn't render a half-logged-in state.\r\n */\r\nexport type ProposeLoginResult =\r\n | { stopped: false; committed: true }\r\n | { stopped: true; signal: ClientHookStopSignal; committed: false };\r\n\r\nexport const proposeLogin = async (\r\n session: BaseSessionLayout,\r\n): Promise<ProposeLoginResult> => {\r\n const veto = await dispatchVetoableClientHook('preLogin', { candidateSession: session });\r\n if (veto.stopped) return { stopped: true, signal: veto.signal, committed: false };\r\n setLatestSession(session);\r\n return { stopped: false, committed: true };\r\n};\r\n","/* eslint-disable react-refresh/only-export-components */\r\nimport { createContext, use, useState, useMemo, useCallback, ReactNode } from 'react';\r\n\r\nexport type AvatarStatus = 'avatar' | 'fallback';\r\n\r\ninterface AvatarContextType {\r\n avatarStatuses: Record<string, AvatarStatus>;\r\n setAvatarStatus: (key: string, status: AvatarStatus) => void;\r\n}\r\n\r\nconst AvatarContext = createContext<AvatarContextType | null>(null);\r\n\r\nexport const AvatarProvider = ({ children }: { children: ReactNode }) => {\r\n const [avatarStatuses, setAvatarStatuses] = useState<Record<string, AvatarStatus>>({});\r\n\r\n const setAvatarStatus = useCallback((key: string, status: AvatarStatus) => {\r\n setAvatarStatuses(prev => ({ ...prev, [key]: status }));\r\n }, []);\r\n\r\n const contextValue = useMemo(() => ({\r\n avatarStatuses,\r\n setAvatarStatus,\r\n }), [avatarStatuses, setAvatarStatus]);\r\n\r\n return (\r\n <AvatarContext value={contextValue}>\r\n {children}\r\n </AvatarContext>\r\n );\r\n};\r\n\r\nexport function useAvatarContext() {\r\n const ctx = use(AvatarContext);\r\n if (!ctx) throw new Error('useAvatarContext must be used within AvatarProvider');\r\n return ctx;\r\n}\r\n","//? `useTheme()` — framework-owned theme state hook. Default value comes\r\n//? from `getProjectConfig().defaultTheme` (the union literal exported by\r\n//? the consumer's `config.ts`). Toggling sets the `.dark` class on\r\n//? `<html>`. Persistence (e.g. saving to `User.theme` via\r\n//? `settings/updateUser`) is up to the consumer — the hook only owns\r\n//? local state + DOM class.\r\n\r\nimport { useState, useCallback } from 'react';\r\nimport { getProjectConfig } from '../projectConfig';\r\n\r\nexport type Theme = 'light' | 'dark';\r\n\r\nconst applyDomClass = (theme: Theme): void => {\r\n if (typeof document === 'undefined') return;\r\n document.documentElement.classList.toggle('dark', theme === 'dark');\r\n};\r\n\r\nexport const useTheme = () => {\r\n const initialTheme = (getProjectConfig().defaultTheme) ?? 'light';\r\n const [theme, setThemeState] = useState<Theme>(initialTheme);\r\n\r\n const setTheme = useCallback((next: Theme) => {\r\n setThemeState(next);\r\n applyDomClass(next);\r\n }, []);\r\n\r\n return { theme, setTheme };\r\n};\r\n","/* eslint-disable react-refresh/only-export-components */\r\n//? Framework-owned translation provider. Reads the registered locales map\r\n//? (consumer registers via `registerLocales({...})` in their overlay) and\r\n//? the active language source (consumer registers via\r\n//? `registerLanguageSource(fn)`, typically `() => session?.language`).\r\n//? Default language falls back to `getProjectConfig().defaultLanguage`.\r\n\r\nimport { createContext, ReactNode, use, useEffect, useMemo, useState, Dispatch, SetStateAction } from 'react';\r\nimport {\r\n getActiveLanguage,\r\n getDefaultLocale,\r\n getLocaleByCode,\r\n getRegisteredLocales,\r\n} from '../localesRegistry';\r\n\r\nexport type TranslationRecord = Record<string, unknown>;\r\n\r\ninterface TranslationContextValue {\r\n translations: TranslationRecord;\r\n setLanguage: Dispatch<SetStateAction<string>>;\r\n}\r\n\r\nconst TranslationContext = createContext<TranslationContextValue | null>(null);\r\n\r\nconst resolveTranslations = (code: string): TranslationRecord => {\r\n const value = getLocaleByCode(code);\r\n if (value && typeof value === 'object') return value as TranslationRecord;\r\n return {};\r\n};\r\n\r\nexport function TranslationProvider({ children }: { children: ReactNode }) {\r\n const [language, setLanguage] = useState<string>(() => getActiveLanguage());\r\n const translations = useMemo(() => resolveTranslations(language), [language]);\r\n\r\n //? Poll the registered language source so changes to session.language\r\n //? (or whatever the consumer wired) flip the active language without a\r\n //? full remount. Cheap: shallow string compare every ~250ms.\r\n useEffect(() => {\r\n const handle = window.setInterval(() => {\r\n const next = getActiveLanguage();\r\n if (next !== language) setLanguage(next);\r\n }, 250);\r\n return () => { window.clearInterval(handle); };\r\n }, [language]);\r\n\r\n const contextValue = useMemo(() => ({ translations, setLanguage }), [translations]);\r\n\r\n return (\r\n <TranslationContext value={contextValue}>\r\n {children}\r\n </TranslationContext>\r\n );\r\n}\r\n\r\nexport function useTranslation() {\r\n const context = use(TranslationContext);\r\n if (!context) throw new Error('useTranslation must be used within a TranslationProvider');\r\n return context.translations;\r\n}\r\n\r\nexport function useUpdateLanguage() {\r\n const context = use(TranslationContext);\r\n if (!context) throw new Error('useUpdateLanguage must be used within a TranslationProvider');\r\n return context.setLanguage;\r\n}\r\n\r\nexport interface TranslateParam { key: string; value: string | number | boolean }\r\n\r\n//? Resolve `a.b.c` style dot-notation keys in a translation tree. Returns\r\n//? the key itself if it can't be resolved (so untranslated strings stand\r\n//? out in the UI rather than vanishing). Supports `{{param}}` substitution.\r\nexport function translate({ translationList, key, params }: {\r\n translationList: TranslationRecord;\r\n key: unknown;\r\n params?: TranslateParam[];\r\n}): string {\r\n if (typeof key !== 'string' || key.length === 0) return '';\r\n\r\n const parts = key.split('.');\r\n let result: unknown = translationList;\r\n for (const part of parts) {\r\n if (result && typeof result === 'object' && part in result) {\r\n result = (result as Record<string, unknown>)[part];\r\n } else {\r\n return key;\r\n }\r\n }\r\n if (typeof result !== 'string') return key;\r\n if (!Array.isArray(params) || params.length === 0) return result;\r\n\r\n let finalResult = result;\r\n for (const param of params) {\r\n if (!param.key) continue;\r\n //? Escape key before building the RegExp — a key containing regex\r\n //? meta-characters (e.g. `.`, `+`, `(`) would otherwise mis-substitute\r\n //? or cause ReDoS. Use a function-form replacer to prevent `$`-sequences\r\n //? in the translation value from being interpreted by String.prototype.replace.\r\n const escapedKey = param.key.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\r\n const regex = new RegExp(`\\\\{\\\\{${escapedKey}\\\\}\\\\}`, 'g');\r\n const replacement = String(param.value);\r\n finalResult = finalResult.replace(regex, () => replacement);\r\n }\r\n return finalResult;\r\n}\r\n\r\n//? Tiny convenience hook for the common case: pass `{ key, params }` and\r\n//? get the resolved string back.\r\nexport const useTranslator = () => {\r\n const translations = useTranslation();\r\n return ({ key, params }: { key: string; params?: TranslateParam[] }) =>\r\n translate({ translationList: translations, key, params });\r\n};\r\n\r\n//? Re-export helpers from the registry so consumers have a single import\r\n//? point for translation customization.\r\nexport { getActiveLanguage, getDefaultLocale, getRegisteredLocales };\r\n","//? Framework-owned i18n-backed toast notify. Reads the active language\r\n//? source + the registered locales map to translate `{ key, params }`\r\n//? before handing off to `sonner`. Registers itself with\r\n//? `registerNotifier` on import so framework packages (apiRequest,\r\n//? syncRequest) automatically emit toasts in the consumer's locale.\r\n//?\r\n//? Importing this module triggers the registration as a side effect —\r\n//? add `import { i18nNotify } from '@luckystack/core/client';` to the\r\n//? consumer's main entry once.\r\n\r\nimport { toast } from 'sonner';\r\nimport { registerNotifier } from '../notifier';\r\nimport { getActiveLanguage, getLocaleByCode } from '../localesRegistry';\r\nimport { translate, type TranslateParam } from './TranslationProvider';\r\n\r\ninterface NotifyInput {\r\n key: string;\r\n params?: TranslateParam[];\r\n}\r\n\r\nconst resolve = (input: NotifyInput): string => {\r\n const language = getActiveLanguage();\r\n const list = getLocaleByCode(language);\r\n return translate({\r\n translationList: (list && typeof list === 'object' ? list : {}) as Record<string, unknown>,\r\n key: input.key,\r\n params: input.params,\r\n });\r\n};\r\n\r\nconst notify = {\r\n success: (input: NotifyInput) => { toast.success(resolve(input)); },\r\n error: (input: NotifyInput) => { toast.error(resolve(input)); },\r\n info: (input: NotifyInput) => { toast.info(resolve(input)); },\r\n warning: (input: NotifyInput) => { toast.warning(resolve(input)); },\r\n};\r\n\r\n//? Side-effect: register with core so framework packages emit through\r\n//? this i18n-backed implementation.\r\nregisterNotifier(notify);\r\n\r\nexport default notify;\r\n","//? Framework-owned route guard. Wraps protected pages — runs the registered\r\n//? middleware handler (`registerMiddlewareHandler` in core) on every route\r\n//? change and renders children only when allowed. Redirects via React\r\n//? Router's `useNavigate` when the handler returns a redirect. Shows a\r\n//? loader only after a 200ms delay so fast checks don't flash a spinner.\r\n\r\nimport { ReactNode, useEffect, useRef, useState } from 'react';\r\nimport { useLocation, useNavigate } from 'react-router-dom';\r\nimport { getMiddlewareHandler, getPageMiddleware } from '../middlewareRegistry';\r\nimport { useSession } from './sessionContext';\r\nimport { getProjectConfig } from '../projectConfig';\r\n\r\nconst LOADER_DELAY_MS = 200;\r\n\r\nfunction MiddlewareLoader() {\r\n const [show, setShow] = useState(false);\r\n\r\n useEffect(() => {\r\n const id = globalThis.setTimeout(() => { setShow(true); }, LOADER_DELAY_MS);\r\n return () => { globalThis.clearTimeout(id); };\r\n }, []);\r\n\r\n if (!show) return null;\r\n\r\n return (\r\n <div className=\"w-full h-full flex items-center justify-center\" aria-busy=\"true\" aria-live=\"polite\">\r\n <div\r\n className=\"w-8 h-8 rounded-full border-2 border-container2-border border-t-primary animate-spin\"\r\n role=\"status\"\r\n aria-label=\"Loading\"\r\n />\r\n </div>\r\n );\r\n}\r\n\r\nexport default function Middleware({ children }: { children: ReactNode }) {\r\n const [allowed, setAllowed] = useState(false);\r\n const [checking, setChecking] = useState(true);\r\n\r\n const location = useLocation();\r\n const navigate = useNavigate();\r\n const { session, sessionLoaded } = useSession();\r\n\r\n //? Track the guarded route so a SESSION-only change re-evaluates the guard\r\n //? WITHOUT unmounting the page. A session update (avatar, roomCodes,\r\n //? preferences pushed via `updateSession`) used to flip `checking` back to\r\n //? true on every change → the whole page unmounted + remounted, wiping page\r\n //? state and aborting in-flight work. Joining a room (which saves the session\r\n //? and broadcasts `updateSession`) therefore looked like a full page refresh.\r\n //? Now we only show the loader / hide the page on a real ROUTE change; a bare\r\n //? session change re-checks in the background and only navigates away if the\r\n //? new session is no longer allowed.\r\n const routeKey = `${location.pathname}\u0000${location.search}`;\r\n const guardedRouteRef = useRef<string | null>(null);\r\n\r\n useEffect(() => {\r\n let isMounted = true;\r\n const isRouteChange = guardedRouteRef.current !== routeKey;\r\n guardedRouteRef.current = routeKey;\r\n if (isRouteChange) {\r\n setAllowed(false);\r\n setChecking(true);\r\n }\r\n\r\n void (async () => {\r\n const params = new URLSearchParams(location.search);\r\n const queryObject: Record<string, string> = {};\r\n for (const [key, value] of params.entries()) {\r\n queryObject[key] = value;\r\n }\r\n\r\n //? Wait for the SessionProvider to finish its initial fetch — up to\r\n //? 5 seconds. Without this, we'd evaluate the middleware against a\r\n //? not-yet-loaded session and bounce the user back to /login.\r\n let count = 0;\r\n while (!sessionLoaded) {\r\n await new Promise(res => setTimeout(res, 10));\r\n count++;\r\n if (count > 500) break;\r\n }\r\n\r\n //? Per-page middleware first (declared in each page.tsx via\r\n //? `export const middleware`), then the global fallback handler\r\n //? registered via `registerMiddlewareHandler`. This lets pages own\r\n //? their own guards while keeping a central catch-all for\r\n //? cross-cutting cases (server-reachability checks, analytics).\r\n const pageMw = getPageMiddleware(location.pathname);\r\n const handler = pageMw ?? getMiddlewareHandler();\r\n const result = await handler({\r\n location: location.pathname,\r\n searchParams: queryObject,\r\n session,\r\n });\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- isMounted intentional, see comment below\r\n if (!isMounted) return;\r\n\r\n if (result?.success) {\r\n setAllowed(true);\r\n } else if (result?.redirect) {\r\n void navigate(result.redirect);\r\n } else {\r\n //? Navigate to a safe, deterministic fallback instead of `navigate(-1)`,\r\n //? which chains backwards out of the app on repeated denials (e.g. when\r\n //? history is shallow or the previous page was also guarded).\r\n void navigate(getProjectConfig().loginRedirectUrl ?? '/');\r\n }\r\n\r\n setChecking(false);\r\n })();\r\n\r\n //! isMounted check is load-bearing — without it, repeated middleware\r\n //? denials chain navigate(-1) and walk too far up history. Keep it.\r\n return () => {\r\n isMounted = false;\r\n };\r\n }, [routeKey, location.pathname, location.search, navigate, session, sessionLoaded]);\r\n\r\n if (checking) return <MiddlewareLoader />;\r\n if (!allowed) return null;\r\n return <div className=\"w-full h-full\">{children}</div>;\r\n}\r\n","//? Wrapper around react-router-dom's `useNavigate` that runs the\r\n//? registered middleware handler before navigating. Returns the guarded\r\n//? navigate function. Use everywhere instead of `useNavigate` directly so\r\n//? programmatic navigations honor the same auth/redirect rules as\r\n//? `<Middleware>`-wrapped page renders.\r\n\r\nimport { useLocation, useNavigate } from 'react-router-dom';\r\nimport { getMiddlewareHandler, getPageMiddleware } from '../middlewareRegistry';\r\nimport { useSession } from './sessionContext';\r\n\r\nconst getParams = (locationSearch: string) => {\r\n const params = new URLSearchParams(locationSearch);\r\n const queryObject: Record<string, string> = {};\r\n for (const [key, value] of params.entries()) {\r\n queryObject[key] = value;\r\n }\r\n return queryObject;\r\n};\r\n\r\nexport default function useRouter() {\r\n const navigateHandler = useNavigate();\r\n const location = useLocation();\r\n const { session } = useSession();\r\n\r\n const navigate = async (path: string) => {\r\n const queryObject = getParams(location.search);\r\n //? Per-page middleware first (declared via `export const middleware`\r\n //? on the target page.tsx), then the global fallback. Mirrors the\r\n //? `<Middleware>` component's resolution order so programmatic\r\n //? navigations honor the same guards as direct URL hits.\r\n const pageMw = getPageMiddleware(path);\r\n const handler = pageMw ?? getMiddlewareHandler();\r\n const result = await handler({ location: path, searchParams: queryObject, session });\r\n\r\n if (result?.success) {\r\n return navigateHandler(path);\r\n }\r\n if (result && !result.success && result.redirect) {\r\n return navigateHandler(result.redirect);\r\n }\r\n return;\r\n };\r\n\r\n return navigate;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,IAAM,sBAAsB,oBAAI,IAA2B;AAC3D,IAAM,uBAAuB,oBAAI,IAA4B;AAMtD,SAAS,8BAA8B,aAAgD;AAC5F,sBAAoB,IAAI,WAAW;AACnC,SAAO,MAAM;AACX,wBAAoB,OAAO,WAAW;AAAA,EACxC;AACF;AAKO,SAAS,+BAA+B,aAAiD;AAC9F,uBAAqB,IAAI,WAAW;AACpC,SAAO,MAAM;AACX,yBAAqB,OAAO,WAAW;AAAA,EACzC;AACF;AAKA,eAAsB,+BACpB,KACe;AACf,MAAI,oBAAoB,SAAS,EAAG;AAGpC,QAAM,eAAe,CAAC,GAAG,mBAAmB;AAC5C,aAAW,eAAe,cAAc;AACtC,QAAI;AACF,YAAM,YAAY,GAAG;AAAA,IACvB,SAAS,OAAO;AACd,gBAAU,EAAE,MAAM,yCAAyC,KAAK;AAAA,IAClE;AAAA,EAC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;AAC5C,QAAM,SAAS,IAAI,gBAAgB,cAAc;AACjD,QAAM,cAAsC,CAAC;AAC7C,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,GAAG;AAC3C,gBAAY,GAAG,IAAI;AAAA,EACrB;AACA,SAAO;AACT;AAEe,SAAR,YAA6B;AAClC,QAAM,kBAAkBC,aAAY;AACpC,QAAM,WAAWC,aAAY;AAC7B,QAAM,EAAE,QAAQ,IAAI,WAAW;AAE/B,QAAM,WAAW,OAAO,SAAiB;AACvC,UAAM,cAAc,UAAU,SAAS,MAAM;AAK7C,UAAM,SAAS,kBAAkB,IAAI;AACrC,UAAM,UAAU,UAAU,qBAAqB;AAC/C,UAAM,SAAS,MAAM,QAAQ,EAAE,UAAU,MAAM,cAAc,aAAa,QAAQ,CAAC;AAEnF,QAAI,QAAQ,SAAS;AACnB,aAAO,gBAAgB,IAAI;AAAA,IAC7B;AACA,QAAI,UAAU,CAAC,OAAO,WAAW,OAAO,UAAU;AAChD,aAAO,gBAAgB,OAAO,QAAQ;AAAA,IACxC;AACA;AAAA,EACF;AAEA,SAAO;AACT;","names":["resolve","createContext","use","useState","useCallback","useState","useCallback","createContext","use","useMemo","useState","jsx","createContext","useState","useMemo","use","notify","useEffect","useState","jsx","useState","useEffect","useLocation","useNavigate","useNavigate","useLocation"]}
1
+ {"version":3,"sources":["../src/apiInterceptors.ts","../src/apiRequest.ts","../src/tryCatchClient.ts","../src/localesRegistry.ts","../src/middlewareRegistry.ts","../src/react/sessionContext.ts","../src/react/AvatarProvider.tsx","../src/react/useTheme.ts","../src/react/TranslationProvider.tsx","../src/react/notify.ts","../src/react/Middleware.tsx","../src/react/Router.tsx"],"sourcesContent":["//? EXT-03 — client-side request/response interceptor registry for `apiRequest`.\r\n//?\r\n//? `apiRequest` (apiRequest.ts) is a monolithic typed function and Rule 21 /\r\n//? the `no-unsafe-api-wrappers` lint forbid wrapping it (a wrapper erases the\r\n//? route/version inference). This registry is the sanctioned escape hatch: a\r\n//? consumer registers an interceptor here instead of wrapping the call, so the\r\n//? typed call site is untouched and route/version inference survives.\r\n//?\r\n//? Two seams, both fire-and-mutate (NOT replace — the dispatcher reserves a\r\n//? structured return for control flow):\r\n//? - request interceptors run just before the socket emit. A handler may\r\n//? mutate `ctx.data` in place (inject a correlation id / feature-flag\r\n//? context / tenant header-equivalent) and is observation-only otherwise.\r\n//? - response interceptors run when the response envelope arrives, before the\r\n//? awaiting caller resolves. Observation-only (metrics, breadcrumb, custom\r\n//? logging). The envelope is NOT mutated by this seam — response rewriting\r\n//? belongs on the server `preApiRespond` / `transformApiResponse` hooks.\r\n//?\r\n//? Handlers are best-effort: a throw / rejection is caught + logged and never\r\n//? breaks the request pipeline. Both `register*` functions return an\r\n//? unsubscribe closure, matching `registerClientHook`'s contract.\r\n\r\nexport interface ApiRequestInterceptorContext {\r\n /** Resolved route name (`<page>/<api>` or `system/<api>`). */\r\n name: string;\r\n /** Route version literal (e.g. `'v1'`). */\r\n version: string;\r\n /**\r\n * Outgoing request payload. Mutate this object in place to augment the\r\n * request (correlation id, feature-flag context, ...). Replacing the\r\n * reference has no effect — mutate keys on the existing object.\r\n */\r\n data: Record<string, unknown>;\r\n}\r\n\r\nexport interface ApiResponseInterceptorContext {\r\n name: string;\r\n version: string;\r\n /** The response envelope the caller is about to receive (read-only intent). */\r\n response: { status: 'success' | 'error'; [key: string]: unknown };\r\n}\r\n\r\nexport type ApiRequestInterceptor = (\r\n ctx: ApiRequestInterceptorContext,\r\n) => void | Promise<void>;\r\n\r\nexport type ApiResponseInterceptor = (\r\n ctx: ApiResponseInterceptorContext,\r\n) => void | Promise<void>;\r\n\r\nimport { getLogger } from './loggerRegistry';\r\n\r\nconst requestInterceptors = new Set<ApiRequestInterceptor>();\r\nconst responseInterceptors = new Set<ApiResponseInterceptor>();\r\n\r\n/**\r\n * Register an outgoing-request interceptor. Returns an unsubscribe function.\r\n * Multiple interceptors run in registration order; each may mutate `ctx.data`.\r\n */\r\nexport function registerApiRequestInterceptor(interceptor: ApiRequestInterceptor): () => void {\r\n requestInterceptors.add(interceptor);\r\n return () => {\r\n requestInterceptors.delete(interceptor);\r\n };\r\n}\r\n\r\n/**\r\n * Register an incoming-response interceptor. Returns an unsubscribe function.\r\n */\r\nexport function registerApiResponseInterceptor(interceptor: ApiResponseInterceptor): () => void {\r\n responseInterceptors.add(interceptor);\r\n return () => {\r\n responseInterceptors.delete(interceptor);\r\n };\r\n}\r\n\r\n//? Framework-internal — invoked by `apiRequest`. Awaited so a handler can do an\r\n//? async lookup (read a flag store, mint a trace id) before the emit. Snapshot\r\n//? the set so a handler unregistering mid-dispatch can't skip a sibling.\r\nexport async function dispatchApiRequestInterceptors(\r\n ctx: ApiRequestInterceptorContext,\r\n): Promise<void> {\r\n if (requestInterceptors.size === 0) return;\r\n //? Snapshot so a handler that unregisters itself (or a sibling) mid-dispatch\r\n //? doesn't skip an un-visited handler.\r\n const interceptors = [...requestInterceptors];\r\n for (const interceptor of interceptors) {\r\n try {\r\n await interceptor(ctx);\r\n } catch (error) {\r\n getLogger().error('[apiRequestInterceptor] handler threw', error);\r\n }\r\n }\r\n}\r\n\r\n//? Framework-internal — invoked by `apiRequest` when the response arrives.\r\n//? Fire-and-forget (the caller does not await) so an interceptor can't delay\r\n//? the resolve; async rejections are caught + logged.\r\nexport function dispatchApiResponseInterceptors(\r\n ctx: ApiResponseInterceptorContext,\r\n): void {\r\n if (responseInterceptors.size === 0) return;\r\n //? Snapshot (see `dispatchApiRequestInterceptors`).\r\n const interceptors = [...responseInterceptors];\r\n for (const interceptor of interceptors) {\r\n try {\r\n const result = interceptor(ctx);\r\n if (result && typeof (result as Promise<unknown>).catch === 'function') {\r\n (result as Promise<unknown>).catch((error: unknown) => {\r\n getLogger().error('[apiResponseInterceptor] async handler rejected', error);\r\n });\r\n }\r\n } catch (error) {\r\n getLogger().error('[apiResponseInterceptor] handler threw', error);\r\n }\r\n }\r\n}\r\n\r\n/** Test helper — drop every registered interceptor. Not part of the public API. */\r\nexport function _resetApiInterceptorsForTests(): void {\r\n requestInterceptors.clear();\r\n responseInterceptors.clear();\r\n}\r\n","import { getProjectConfig } from \"./projectConfig\";\r\nimport { getLogger } from \"./loggerRegistry\";\r\nimport { getRegisteredApiMethod } from \"./apiMethodMapRegistry\";\r\nimport { isGetMethodName } from \"./httpApiUtils\";\r\nimport { incrementResponseIndex, socket, waitForSocket } from \"./socketState\";\r\nimport type { ApiTypeMap, StreamPayload } from './apiTypeStubs';\r\nimport { notify } from \"./notifier\";\r\nimport { enqueueApiRequest, isOnline, removeApiQueueItem } from \"./offlineQueue\";\r\nimport { Socket } from \"socket.io-client\";\r\nimport { normalizeErrorResponseCore } from \"./responseNormalizer\";\r\nimport { parseServiceRouteName } from \"./serviceRoute\";\r\nimport tryCatchSync from \"./tryCatchSync\";\r\nimport {\r\n buildApiResponseEventName,\r\n buildApiStreamEventName,\r\n socketEventNames,\r\n} from \"./socketEvents\";\r\nimport {\r\n dispatchApiRequestInterceptors,\r\n dispatchApiResponseInterceptors,\r\n} from \"./apiInterceptors\";\r\n\r\n//? Abort controller logic:\r\n//? - abortable: true → always use abort controller\r\n//? - abortable: false → never use abort controller\r\n//? - abortable: undefined → use abort controller for GET APIs (from generated types)\r\n//? Keyed by `fullName` + a stable hash of the request `data` so the\r\n//? replace-previous (dedupe) semantics only fire for an IDENTICAL in-flight\r\n//? call. Two components polling the same GET route with DIFFERENT params no\r\n//? longer abort each other (each gets its own bucket); a genuine duplicate\r\n//? still supersedes the prior one.\r\n//? Size-capped at 1000 entries. All normal code paths (resolve, abort, disconnect,\r\n//? timeout) call `cleanupAbortController()` which deletes the entry. The cap\r\n//? is a safety net for edge cases where cleanup is skipped (socket torn down\r\n//? without a `disconnect` event, or a future code path that forgets to clean up).\r\nconst ABORT_CONTROLLERS_MAX = 1000;\r\nconst abortControllers = new Map<string, AbortController>();\r\n\r\n//? Stable, order-insensitive JSON stringify so `{a:1,b:2}` and `{b:2,a:1}`\r\n//? hash to the same abort-controller key. Falls back to a non-deduping unique\r\n//? token when the payload can't be serialised (circular ref), which is the\r\n//? safe choice — an unserialisable payload should never silently abort a\r\n//? sibling request.\r\nconst stableStringify = (value: unknown): string => {\r\n const seen = new WeakSet<object>();\r\n const walk = (input: unknown): unknown => {\r\n if (input === null || typeof input !== 'object') return input;\r\n if (seen.has(input)) return '[circular]';\r\n seen.add(input);\r\n if (Array.isArray(input)) return input.map((entry) => walk(entry));\r\n const record = input as Record<string, unknown>;\r\n const out: Record<string, unknown> = {};\r\n for (const key of Object.keys(record).toSorted()) {\r\n out[key] = walk(record[key]);\r\n }\r\n return out;\r\n };\r\n const [error, json] = tryCatchSync(() => JSON.stringify(walk(value)));\r\n if (error || typeof json !== 'string') {\r\n return `__unserializable__:${String(Date.now())}-${String(Math.random())}`;\r\n }\r\n return json;\r\n};\r\n\r\nconst buildAbortKey = (fullName: string, data: unknown): string =>\r\n `${fullName}::${stableStringify(data)}`;\r\n\r\nexport type ApiStreamEvent<T extends StreamPayload = StreamPayload> = T;\r\n\r\n/**\r\n * Check if an API is a GET method.\r\n *\r\n * Primary path: consult the registered `apiMethodMap` (generated from the\r\n * actual handler's `httpMethod` export or name-based inference at codegen\r\n * time). Falls back to name-prefix heuristic only when the map isn't\r\n * registered yet — typically because the consumer hasn't called\r\n * `registerApiMethodMap(...)` from their `socketInitializer.ts` boot file.\r\n */\r\nconst isGetMethodByPrefix = (apiName: string): boolean => isGetMethodName(apiName.toLowerCase());\r\n\r\nconst resolveGetMethod = (apiName: string, version: string): { isGet: boolean; usingHeuristic: boolean } => {\r\n //? Resolved-name shape: `pagePath/apiName`. apiMethodMap is nested by\r\n //? pagePath → apiName → version. Split at the last `/` so multi-segment\r\n //? page paths (e.g. 'admin/users') still resolve.\r\n const lastSlash = apiName.lastIndexOf('/');\r\n if (lastSlash > 0) {\r\n const pagePath = apiName.slice(0, lastSlash);\r\n const leaf = apiName.slice(lastSlash + 1);\r\n const method = getRegisteredApiMethod(pagePath, leaf, version);\r\n if (method) return { isGet: method === 'GET', usingHeuristic: false };\r\n }\r\n return { isGet: isGetMethodByPrefix(apiName), usingHeuristic: true };\r\n};\r\n\r\nconst canSendNow = (socketInstance: Socket) => {\r\n if (!socketInstance.connected) return false;\r\n return isOnline();\r\n};\r\n\r\nconst createQueueId = () => {\r\n return `${String(Date.now())}-${String(Math.random())}`;\r\n};\r\n\r\n//? Resolve logging flags at call time so registration order doesn't matter.\r\n//? `getLogging()` is called inside each handler instead of captured at load.\r\nconst getLogging = () => getProjectConfig().logging;\r\nconst shouldLogDev = () => getLogging().devLogs;\r\nconst shouldNotifyDev = () => getLogging().devNotifications;\r\nconst shouldLogStream = () => getLogging().stream;\r\n\r\nconst shouldUseAbortController = ({\r\n abortable,\r\n isGet,\r\n usingHeuristic,\r\n}: {\r\n abortable: boolean | undefined;\r\n isGet: boolean;\r\n usingHeuristic: boolean;\r\n}) => {\r\n if (abortable === true) return true;\r\n if (abortable === false) return false;\r\n //? CORE-O15: when `abortable` is unspecified and we are relying on the\r\n //? name-prefix heuristic (apiMethodMap not registered), default to\r\n //? non-abortable. A mis-named POST (e.g. `getReport`) would otherwise\r\n //? silently abort an identical in-flight call it has nothing to do with.\r\n //? Once `registerApiMethodMap` is called (normal boot), the generated map\r\n //? resolves the method and the heuristic path is never taken.\r\n if (usingHeuristic) return false;\r\n return isGet;\r\n};\r\n\r\n\r\n// ═══════════════════════════════════════════════════════════════════════════════\r\n// Type Helpers\r\n// ═══════════════════════════════════════════════════════════════════════════════\r\n\r\n// Check if data input is required (i.e., T does NOT allow empty object)\r\n// Unions like {a:1} | {b:1} do NOT allow {}, so data will be required\r\ntype DataRequired<T> = Record<string, never> extends T ? false : true;\r\n\r\ntype UnionToIntersection<U> =\r\n (U extends unknown ? (arg: U) => void : never) extends ((arg: infer I) => void)\r\n ? I\r\n : never;\r\n\r\n// ═══════════════════════════════════════════════════════════════════════════════\r\n// Global API Params - Union of ALL valid API calls with proper data enforcement\r\n// ═══════════════════════════════════════════════════════════════════════════════\r\ntype ApiRouteRecord = UnionToIntersection<{\r\n [P in keyof ApiTypeMap]: {\r\n [N in keyof ApiTypeMap[P] as P extends 'root'\r\n ? `system/${Extract<N, string>}`\r\n : `${Extract<P, string>}/${Extract<N, string>}`]: ApiTypeMap[P][N]\r\n }\r\n}[keyof ApiTypeMap]>;\r\n\r\ntype ApiFullName = Extract<keyof ApiRouteRecord, string>;\r\ntype VersionsForFullName<F extends ApiFullName> = keyof ApiRouteRecord[F] & string;\r\n\r\n// Force expansion of types to clear aliases in tooltips\r\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\r\n\r\n// Get input type for an API name (union if exists on multiple pages)\r\ntype InputForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = ApiRouteRecord[F][V] extends { input: infer I }\r\n ? I\r\n : never;\r\n\r\n// Get output type for an API name (union if exists on multiple pages)\r\ntype OutputForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = ApiRouteRecord[F][V] extends { output: infer O }\r\n ? O\r\n : never;\r\n\r\ntype StreamForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = ApiRouteRecord[F][V] extends { stream: infer S }\r\n ? S\r\n : never;\r\n\r\ntype ApiStreamCallbackForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> =\r\n [StreamForFullName<F, V>] extends [never]\r\n ? never\r\n : (event: ApiStreamEvent<Prettify<StreamForFullName<F, V> extends StreamPayload ? StreamForFullName<F, V> : StreamPayload>>) => void;\r\n\r\n// Build params type for a specific API name\r\ntype ApiParamsForFullName<\r\n F extends ApiFullName,\r\n V extends VersionsForFullName<F>\r\n> = DataRequired<InputForFullName<F, V>> extends true\r\n ? { name: F; version: V; data: Prettify<InputForFullName<F, V>>; abortable?: boolean; disableErrorMessage?: boolean; onStream?: ApiStreamCallbackForFullName<F, V>; signal?: AbortSignal; timeoutMs?: number | false; }\r\n : { name: F; version: V; data?: Prettify<InputForFullName<F, V>>; abortable?: boolean; disableErrorMessage?: boolean; onStream?: ApiStreamCallbackForFullName<F, V>; signal?: AbortSignal; timeoutMs?: number | false; };\r\n\r\ninterface RuntimeApiParams {\r\n name?: string;\r\n version?: string;\r\n data?: unknown;\r\n abortable?: boolean;\r\n disableErrorMessage?: boolean;\r\n onStream?: (event: ApiStreamEvent) => void;\r\n signal?: AbortSignal;\r\n /** Per-call response timeout (ms). Overrides `api.requestTimeoutMs`. `false` disables. */\r\n timeoutMs?: number | false;\r\n}\r\n\r\nexport interface ApiErrorResponse extends Record<string, unknown> {\r\n status: 'error';\r\n httpStatus: number;\r\n message: string;\r\n errorCode: string;\r\n errorParams?: { key: string; value: string | number | boolean }[];\r\n}\r\n\r\ninterface ApiSuccessResponse extends Record<string, unknown> {\r\n status: 'success';\r\n httpStatus: number;\r\n}\r\n\r\ntype ApiResponse = ApiErrorResponse | ApiSuccessResponse;\r\n\r\nconst normalizeApiError = ({\r\n response,\r\n fallbackErrorCode,\r\n fallbackHttpStatus = 500,\r\n}: {\r\n response: { status: 'error'; errorCode?: string; errorParams?: { key: string; value: string | number | boolean }[]; httpStatus?: number; message?: string };\r\n fallbackErrorCode: string;\r\n fallbackHttpStatus?: number;\r\n}): ApiErrorResponse => {\r\n const normalized = normalizeErrorResponseCore({\r\n response,\r\n fallbackErrorCode,\r\n fallbackHttpStatus,\r\n resolveMessage: ({ errorCode }) => {\r\n if (typeof response.message === 'string' && response.message.trim().length > 0) {\r\n return response.message;\r\n }\r\n return errorCode;\r\n },\r\n });\r\n\r\n return {\r\n status: 'error',\r\n message: normalized.message,\r\n errorCode: normalized.errorCode,\r\n errorParams: normalized.errorParams,\r\n httpStatus: normalized.httpStatus ?? fallbackHttpStatus,\r\n };\r\n};\r\n\r\n/**\r\n * Type-safe API request function.\r\n * \r\n * @example\r\n * ```typescript\r\n * // Full name usage - includes page in the name\r\n * const result = await apiRequest({ name: 'examples/publicApi', version: 'v1', data: { message: 'hello' } });\r\n * // result is typed correctly for publicApi\r\n * \r\n * // Global APIs use service-first naming\r\n * await apiRequest({ name: 'system/session', version: 'v1' });\r\n * ```\r\n */\r\n\r\nexport function apiRequest<F extends ApiFullName, V extends VersionsForFullName<F>>(\r\n params: ApiParamsForFullName<F, V>\r\n): Promise<Prettify<OutputForFullName<F, V>> | ApiErrorResponse> {\r\n type RequestOutput = Prettify<OutputForFullName<F, V> & ApiResponse>;\r\n const runtimeParams = params as RuntimeApiParams;\r\n const { name, version, disableErrorMessage = false, onStream, signal: externalSignal, timeoutMs } = runtimeParams;\r\n const payloadData = runtimeParams.data;\r\n\r\n return new Promise<RequestOutput>((resolve) => {\r\n void (async () => {\r\n //? B1 — if the consumer-supplied signal is already aborted at call\r\n //? time, short-circuit before we even touch the socket. Mirrors the\r\n //? `fetch(url, { signal })` contract.\r\n if (externalSignal?.aborted) {\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'request.aborted' },\r\n fallbackErrorCode: 'request.aborted',\r\n }) as RequestOutput);\r\n return;\r\n }\r\n if (!name || typeof name !== \"string\") {\r\n if (shouldLogDev()) {\r\n getLogger().error(\"apiRequest: Invalid name\");\r\n }\r\n if (shouldNotifyDev()) {\r\n notify.error({ key: 'api.invalidName' });\r\n }\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'api.invalidName' },\r\n fallbackErrorCode: 'api.invalidName',\r\n }) as RequestOutput);\r\n return;\r\n }\r\n\r\n if (!version || typeof version !== 'string') {\r\n if (shouldLogDev()) {\r\n getLogger().error(\"apiRequest: Invalid version\");\r\n }\r\n if (shouldNotifyDev()) {\r\n notify.error({ key: 'api.invalidVersion' });\r\n }\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'api.invalidVersion' },\r\n fallbackErrorCode: 'api.invalidVersion',\r\n }) as RequestOutput);\r\n return;\r\n }\r\n\r\n const parsedRoute = parseServiceRouteName(name);\r\n if (parsedRoute.status === 'error') {\r\n if (shouldLogDev()) {\r\n getLogger().error(`[apiRequest] Invalid service route name`, undefined, { name, reason: parsedRoute.reason });\r\n }\r\n if (shouldNotifyDev()) {\r\n notify.error({ key: 'routing.invalidServiceRouteName' });\r\n }\r\n resolve(normalizeErrorResponseCore({\r\n response: {\r\n status: 'error',\r\n errorCode: 'routing.invalidServiceRouteName',\r\n errorParams: [{ key: 'name', value: name }],\r\n },\r\n fallbackErrorCode: 'routing.invalidServiceRouteName',\r\n }) as RequestOutput);\r\n return;\r\n }\r\n\r\n const sanitizedName = parsedRoute.normalizedRouteName;\r\n\r\n const data = payloadData && typeof payloadData === \"object\" ? payloadData : {};\r\n\r\n if (!await waitForSocket()) {\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'api.ioUnavailable' },\r\n fallbackErrorCode: 'api.ioUnavailable',\r\n }) as RequestOutput);\r\n return;\r\n }\r\n if (!socket) {\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'api.ioUnavailable' },\r\n fallbackErrorCode: 'api.ioUnavailable',\r\n }) as RequestOutput);\r\n return;\r\n }\r\n\r\n //? Abort controller logic:\r\n //? - abortable: true → always use abort controller\r\n //? - abortable: false → never use abort controller\r\n //? - abortable: undefined → smart default (GET-like APIs get abort controller)\r\n //? Pass the full pagePath/apiName so the registry lookup can resolve via\r\n //? the generated apiMethodMap (falls back to the leaf-name prefix heuristic\r\n //? when the map isn't registered yet).\r\n const { isGet, usingHeuristic } = resolveGetMethod(sanitizedName, version);\r\n const useAbortController = shouldUseAbortController({\r\n abortable: runtimeParams.abortable,\r\n isGet,\r\n usingHeuristic,\r\n });\r\n const fullName = `api/${sanitizedName}/${version}`;\r\n //? Per-payload abort key: only an identical in-flight call to the same\r\n //? route supersedes the previous one (see `buildAbortKey` rationale).\r\n const abortKey = buildAbortKey(fullName, data);\r\n\r\n let signal: AbortSignal | null = null;\r\n let abortHandler: (() => void) | null = null;\r\n let queueId: string | null = null;\r\n let cleanupStreamListener: (() => void) | null = null;\r\n //? Response listener cleanup, registered once the `.once` handler is\r\n //? attached in `runRequest`. Lets the abort path proactively `off()` the\r\n //? lingering response listener instead of waiting for a response that was\r\n //? cancelled and will never arrive.\r\n let cleanupResponseListener: (() => void) | null = null;\r\n //? Response-timeout timer. Armed right after the request is emitted so a\r\n //? lost response (server restart/crash between emit and reply) settles the\r\n //? promise instead of hanging the awaiting caller forever.\r\n let responseTimeout: ReturnType<typeof setTimeout> | null = null;\r\n const clearResponseTimeout = () => {\r\n if (responseTimeout) {\r\n clearTimeout(responseTimeout);\r\n responseTimeout = null;\r\n }\r\n };\r\n\r\n const cleanupAbortController = () => {\r\n if (signal && abortHandler) {\r\n signal.removeEventListener(\"abort\", abortHandler);\r\n }\r\n abortControllers.delete(abortKey);\r\n };\r\n\r\n if (useAbortController) {\r\n if (abortControllers.has(abortKey)) {\r\n const prevAbortController = abortControllers.get(abortKey);\r\n prevAbortController?.abort();\r\n }\r\n //? Evict the oldest entry when the cap is reached (LRU-insert-order).\r\n //? Map preserves insertion order; the first key is the oldest in-flight entry.\r\n if (!abortControllers.has(abortKey) && abortControllers.size >= ABORT_CONTROLLERS_MAX) {\r\n const oldest = abortControllers.keys().next().value;\r\n if (oldest !== undefined) abortControllers.delete(oldest);\r\n }\r\n const abortController = new AbortController();\r\n abortControllers.set(abortKey, abortController);\r\n signal = abortController.signal;\r\n\r\n abortHandler = () => {\r\n clearResponseTimeout();\r\n cleanupStreamListener?.();\r\n cleanupStreamListener = null;\r\n cleanupResponseListener?.();\r\n cleanupResponseListener = null;\r\n cleanupAbortController();\r\n if (queueId) {\r\n removeApiQueueItem(queueId);\r\n }\r\n //? Resolve (not reject) with the same `request.aborted` envelope the\r\n //? external-signal abort path uses. Rejecting here produced an\r\n //? unhandled rejection for fire-and-forget GET calls that get\r\n //? superseded by the default replace-previous behaviour.\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'request.aborted' },\r\n fallbackErrorCode: 'request.aborted',\r\n }) as RequestOutput);\r\n };\r\n\r\n signal.addEventListener(\"abort\", abortHandler);\r\n }\r\n\r\n const runRequest = (socketInstance: Socket) => {\r\n if (!canSendNow(socketInstance)) {\r\n queueId ??= createQueueId();\r\n //? For the immediate reject-new path (`drop-newest` / `reject`\r\n //? policy) THIS item's `onDrop` fires SYNCHRONOUSLY inside\r\n //? `enqueueApiRequest`. We keep surfacing that as the historical\r\n //? `offline.queueFull` via the `!enqueued` branch, so suppress the\r\n //? `onDrop` resolve during the synchronous enqueue window and re-arm\r\n //? it only if the item was actually queued (so a LATER async eviction\r\n //? — drop-oldest by a future enqueue, or age expiry — still settles).\r\n let suppressOnDrop = true;\r\n //? `enqueueApiRequest` returns `false` when the offline queue is\r\n //? full and `dropPolicy: 'reject'` is active. Without honoring\r\n //? that signal the outer promise never settles and the caller\r\n //? awaits forever. Resolve with a normalized error envelope so\r\n //? callers can branch.\r\n const enqueued = enqueueApiRequest({\r\n id: queueId,\r\n key: fullName,\r\n run: (nextSocket) => {\r\n runRequest(nextSocket);\r\n },\r\n createdAt: Date.now(),\r\n //? CORE: mirror SYNC-09. Settle the awaiting caller when this\r\n //? QUEUED request is later EVICTED (drop-oldest by a future\r\n //? enqueue / age expiry) instead of ever running. Without it the\r\n //? promise hangs forever, since `run` is the only thing that could\r\n //? otherwise resolve it — `apiRequest` had drifted from the sibling\r\n //? `syncRequest` which already had this fix. Also tear down the\r\n //? abort-controller registry entry so it isn't leaked.\r\n onDrop: (reason) => {\r\n if (suppressOnDrop) return;\r\n cleanupAbortController();\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'offline.dropped', errorParams: [{ key: 'reason', value: reason }] },\r\n fallbackErrorCode: 'offline.dropped',\r\n }) as RequestOutput);\r\n },\r\n });\r\n //? Past the synchronous enqueue window: if the item is sitting in the\r\n //? queue, a future eviction should settle via `onDrop`.\r\n suppressOnDrop = false;\r\n if (!enqueued) {\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'offline.queueFull', httpStatus: 503 },\r\n fallbackErrorCode: 'offline.queueFull',\r\n fallbackHttpStatus: 503,\r\n }) as RequestOutput);\r\n } else if (externalSignal && queueId) {\r\n //? CORE-O14: if an external AbortSignal fires while the item is\r\n //? sitting in the offline queue, its listener inside runRequest has\r\n //? not been registered yet. Register a one-shot handler here so the\r\n //? abort is not silently ignored and the queue slot is reclaimed.\r\n const capturedQueueId = queueId;\r\n const queueAbortHandler = () => {\r\n removeApiQueueItem(capturedQueueId);\r\n cleanupAbortController();\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'request.aborted' },\r\n fallbackErrorCode: 'request.aborted',\r\n }) as RequestOutput);\r\n };\r\n externalSignal.addEventListener('abort', queueAbortHandler, { once: true });\r\n }\r\n return;\r\n }\r\n\r\n if (signal?.aborted) {\r\n return;\r\n }\r\n\r\n const tempIndex = incrementResponseIndex();\r\n socketInstance.emit(socketEventNames.apiRequest, { name: fullName, data, responseIndex: tempIndex });\r\n\r\n //? B1 — bridge the consumer's AbortSignal to the server. When the\r\n //? signal fires we emit `apiCancel { responseIndex }` so the server\r\n //? handler stops emitting new chunks. We also resolve locally with\r\n //? `request.aborted` so the awaiting caller settles (vs awaiting\r\n //? a response that will never arrive because we cancelled it).\r\n let cleanupExternalAbort: (() => void) | null = null;\r\n if (externalSignal) {\r\n const externalAbortHandler = () => {\r\n clearResponseTimeout();\r\n socketInstance.emit(socketEventNames.apiCancel, { responseIndex: tempIndex });\r\n cleanupStreamListener?.();\r\n cleanupStreamListener = null;\r\n cleanupResponseListener?.();\r\n cleanupResponseListener = null;\r\n cleanupAbortController();\r\n cleanupExternalAbort?.();\r\n cleanupExternalAbort = null;\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'request.aborted' },\r\n fallbackErrorCode: 'request.aborted',\r\n }) as RequestOutput);\r\n };\r\n externalSignal.addEventListener('abort', externalAbortHandler);\r\n cleanupExternalAbort = () => {\r\n externalSignal.removeEventListener('abort', externalAbortHandler);\r\n };\r\n }\r\n\r\n //? Arm the response timeout. A per-call `timeoutMs` overrides the\r\n //? `api.requestTimeoutMs` config default; either may be `false` to\r\n //? disable. On expiry we tear down every listener/controller and settle\r\n //? with a 504 envelope so the awaiting caller never hangs.\r\n clearResponseTimeout();\r\n const effectiveTimeoutMs = timeoutMs ?? getProjectConfig().api.requestTimeoutMs;\r\n if (typeof effectiveTimeoutMs === 'number' && effectiveTimeoutMs > 0) {\r\n responseTimeout = setTimeout(() => {\r\n responseTimeout = null;\r\n cleanupStreamListener?.();\r\n cleanupStreamListener = null;\r\n cleanupResponseListener?.();\r\n cleanupResponseListener = null;\r\n cleanupExternalAbort?.();\r\n cleanupExternalAbort = null;\r\n cleanupAbortController();\r\n if (queueId) {\r\n removeApiQueueItem(queueId);\r\n }\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'api.timeout', httpStatus: 504 },\r\n fallbackErrorCode: 'api.timeout',\r\n fallbackHttpStatus: 504,\r\n }) as RequestOutput);\r\n }, effectiveTimeoutMs);\r\n }\r\n\r\n if (typeof onStream === 'function') {\r\n const streamEventName = buildApiStreamEventName(tempIndex);\r\n const streamListener = (streamPayload: ApiStreamEvent) => {\r\n if (signal?.aborted) {\r\n return;\r\n }\r\n\r\n if (shouldLogStream()) {\r\n getLogger().debug(`Server API Stream(${String(tempIndex)})`, { APINAME: sanitizedName, streamPayload });\r\n }\r\n\r\n onStream(streamPayload);\r\n };\r\n\r\n socketInstance.on(streamEventName, streamListener);\r\n cleanupStreamListener = () => {\r\n socketInstance.off(streamEventName, streamListener);\r\n };\r\n }\r\n\r\n if (shouldLogDev()) {\r\n getLogger().debug(`Client API Request(${String(tempIndex)})`, { APINAME: sanitizedName, data });\r\n }\r\n\r\n //? Inside the handler we type as the runtime envelope (ApiResponse).\r\n //? Project-specific output narrowing only matters at the call site,\r\n //? where `RequestOutput = OutputForFullName<F,V> & ApiResponse` is\r\n //? returned via `resolve(... as RequestOutput)`. When core is type-\r\n //? checked in isolation (e.g. per-package tsup dts build), ApiTypeMap\r\n //? is empty so OutputForFullName collapses to never; using ApiResponse\r\n //? here keeps the body type-safe in both cases.\r\n const responseEventName = buildApiResponseEventName(tempIndex);\r\n const responseListener = (response: ApiResponse) => {\r\n if (signal?.aborted) {\r\n clearResponseTimeout();\r\n cleanupExternalAbort?.();\r\n cleanupExternalAbort = null;\r\n return;\r\n }\r\n\r\n clearResponseTimeout();\r\n cleanupStreamListener?.();\r\n cleanupStreamListener = null;\r\n cleanupExternalAbort?.();\r\n cleanupExternalAbort = null;\r\n //? Call cleanup (not just null) so that any watcher layered on top of\r\n //? cleanupResponseListener (e.g. the CORE-O13 disconnect watcher) is\r\n //? properly torn down when a normal response arrives.\r\n cleanupResponseListener?.();\r\n cleanupResponseListener = null;\r\n\r\n const status = response.status;\r\n\r\n //? EXT-03 — fire client response interceptors when the envelope\r\n //? arrives (observation-only: metrics, breadcrumb, custom logging).\r\n dispatchApiResponseInterceptors({ name: sanitizedName, version, response });\r\n\r\n if (shouldLogDev()) {\r\n getLogger().debug(`Server API Response(${String(tempIndex)})`, { ...response, APINAME: sanitizedName });\r\n }\r\n\r\n if (status === \"error\") {\r\n const normalizedError = normalizeErrorResponseCore({ response });\r\n\r\n if (!disableErrorMessage) {\r\n if (normalizedError.errorCode) {\r\n notify.error({ key: normalizedError.errorCode, params: normalizedError.errorParams });\r\n } else {\r\n notify.error({ key: normalizedError.message });\r\n }\r\n }\r\n\r\n Object.assign(response, normalizedError);\r\n cleanupAbortController();\r\n resolve(response as RequestOutput);\r\n return;\r\n }\r\n\r\n cleanupAbortController();\r\n\r\n resolve(response as RequestOutput);\r\n };\r\n\r\n socketInstance.once(responseEventName, responseListener);\r\n cleanupResponseListener = () => {\r\n socketInstance.off(responseEventName, responseListener);\r\n };\r\n\r\n //? CORE-O13: when timeout is disabled AND there is no abort controller\r\n //? a server restart between emit and reply leaves this promise pending\r\n //? forever, leaking the response listener. The disconnect event is the\r\n //? authoritative signal that no reply will ever arrive on this socket.\r\n const disconnectHandler = () => {\r\n if (cleanupResponseListener) {\r\n cleanupResponseListener();\r\n cleanupResponseListener = null;\r\n }\r\n cleanupStreamListener?.();\r\n cleanupStreamListener = null;\r\n cleanupExternalAbort?.();\r\n cleanupExternalAbort = null;\r\n clearResponseTimeout();\r\n cleanupAbortController();\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'api.disconnected' },\r\n fallbackErrorCode: 'api.disconnected',\r\n }) as RequestOutput);\r\n };\r\n socketInstance.once('disconnect', disconnectHandler);\r\n //? Wrap the response listener to also remove the disconnect watcher on\r\n //? a normal reply (avoids a dangling listener on every successful call).\r\n const originalCleanupResponseListener = cleanupResponseListener;\r\n cleanupResponseListener = () => {\r\n socketInstance.off('disconnect', disconnectHandler);\r\n originalCleanupResponseListener();\r\n };\r\n };\r\n\r\n //? EXT-03 — fire client request interceptors just before the emit. They\r\n //? may mutate `data` in place (correlation id / feature-flag context).\r\n //? `data` is the same reference passed to `socketInstance.emit`, so the\r\n //? mutation is on the wire. Awaited so an async interceptor (flag lookup,\r\n //? trace-id mint) completes first; failures are caught + logged inside.\r\n await dispatchApiRequestInterceptors({\r\n name: sanitizedName,\r\n version,\r\n data: data as Record<string, unknown>,\r\n });\r\n\r\n //? CORE-O12: re-check the external abort signal after the interceptor\r\n //? await. A slow async interceptor adds uncounted latency; if the caller\r\n //? aborted during that window the signal is already fired but nothing has\r\n //? yet attached its listener (that happens inside runRequest). Settling\r\n //? here avoids emitting a request whose response will never be consumed.\r\n if (externalSignal?.aborted) {\r\n resolve(normalizeApiError({\r\n response: { status: 'error', errorCode: 'request.aborted' },\r\n fallbackErrorCode: 'request.aborted',\r\n }) as RequestOutput);\r\n return;\r\n }\r\n\r\n runRequest(socket);\r\n })();\r\n });\r\n}","//? Browser-safe sibling of `tryCatch`. Behaviourally identical (same tuple,\r\n//? same params, same auto-capture on the error path) but it does NOT statically\r\n//? import `./sentrySetup`. The server `tryCatch.ts` reaches `sentrySetup` →\r\n//? `errorTrackerRegistry` → `node:async_hooks` at module-eval; that static edge\r\n//? is harmless on the server but drags a `node:`-externalized module into the\r\n//? Vite CLIENT bundle whenever a client importer (LoginForm) pulls\r\n//? `shared/tryCatch.ts`. So the client-reachable shim resolves HERE instead, and\r\n//? the only path to capture is a LAZY dynamic import taken on the error branch —\r\n//? keeping the node-bearing module out of the client's static graph.\r\n//?\r\n//? The server's `tryCatch.ts` is intentionally left untouched (byte-for-byte) so\r\n//? the server capture path keeps its synchronous, statically-linked behaviour.\r\n//? On the client, capture is best-effort and async-via-microtask is fine.\r\n\r\nexport default async function tryCatch<T, P = void>(\r\n func: (values: P) => Promise<T> | T,\r\n params?: P,\r\n context?: Record<string, unknown>\r\n): Promise<[Error | null, T | null]> {\r\n try {\r\n const response = await func(params as P);\r\n return [null, response];\r\n } catch (error) {\r\n //? Lazy capture: the import is only evaluated on the error branch, so the\r\n //? `node:async_hooks`-bearing module never enters the client's static graph.\r\n const { captureException } = await import('./sentrySetup');\r\n captureException(error, context);\r\n return [error instanceof Error ? error : new Error(String(error)), null];\r\n }\r\n}\r\n","//? Locales registry — lets the framework's TranslationProvider + notify\r\n//? read the consumer's translation JSON files without baking them into the\r\n//? package. Consumer overlay: `luckystack/i18n/locales.ts` calls\r\n//? `registerLocales({ en: enJson, nl: nlJson, ... })`.\r\n//?\r\n//? Language source: a separate registry — `registerLanguageSource(fn)` —\r\n//? lets the consumer wire up where the active language comes from\r\n//? (typically the SessionProvider's current `session.language`). When no\r\n//? source is registered, the framework falls back to\r\n//? `getProjectConfig().defaultLanguage`.\r\n\r\nimport { getProjectConfig } from './projectConfig';\r\n\r\nexport type LocalesMap = Record<string, unknown>;\r\nexport type LanguageSource = () => string | null | undefined;\r\n\r\nlet activeLocales: LocalesMap = {};\r\nlet activeLanguageSource: LanguageSource | null = null;\r\n\r\nexport const registerLocales = (locales: LocalesMap): void => {\r\n activeLocales = locales;\r\n};\r\n\r\nexport const getRegisteredLocales = (): LocalesMap => activeLocales;\r\n\r\nexport const getDefaultLocale = (): string => getProjectConfig().defaultLanguage || 'en';\r\n\r\nexport const registerLanguageSource = (fn: LanguageSource): void => {\r\n activeLanguageSource = fn;\r\n};\r\n\r\nexport const getActiveLanguage = (): string => {\r\n if (activeLanguageSource) {\r\n const lang = activeLanguageSource();\r\n if (typeof lang === 'string' && lang.length > 0) return lang;\r\n }\r\n return getDefaultLocale();\r\n};\r\n\r\n//? Lookup a language's translation tree by code. Falls back to default\r\n//? language when the code isn't registered. Used by TranslationProvider\r\n//? + notify to resolve the active translations.\r\nexport const getLocaleByCode = (code: string): unknown => {\r\n if (code in activeLocales) return activeLocales[code];\r\n const fallback = getDefaultLocale();\r\n if (fallback in activeLocales) return activeLocales[fallback];\r\n return {};\r\n};\r\n","//? Middleware handler registry. The framework's `Middleware` + `Router`\r\n//? components (in `./react/`) call the registered handler on every\r\n//? navigation change to decide whether the user is allowed on the target\r\n//? route. Per-page `export const middleware` (see `registerPageMiddleware`\r\n//? below) is the canonical path; a consumer wanting a cross-cutting GLOBAL\r\n//? guard registers it from the client bootstrap (typically `main.tsx`) via\r\n//? `registerMiddlewareHandler(...)`. No separate\r\n//? `src/_functions/middlewareHandler.ts` file is required.\r\n\r\nimport type { BaseSessionLayout } from './sessionTypes';\r\n\r\nexport interface MiddlewareInput {\r\n location: string;\r\n searchParams: Record<string, string>;\r\n session: BaseSessionLayout | null;\r\n}\r\n\r\nexport type MiddlewareResult =\r\n | { success: true; redirect?: undefined }\r\n | { success: false; redirect: string }\r\n | undefined;\r\n\r\nexport type MiddlewareHandler = (input: MiddlewareInput) => MiddlewareResult | Promise<MiddlewareResult>;\r\n\r\n//? Default handler: allow by default. Per-page `middleware` exports on each\r\n//? `page.tsx` are the canonical route-guard path (see `registerPageMiddleware`\r\n//? below); the global handler is only consulted as a fallback for pages\r\n//? that don't declare their own guard. Allowing-by-default keeps public\r\n//? routes (`/`, `/login`, `/register`, ...) working without forcing every\r\n//? consumer to ship a `src/_functions/middlewareHandler.ts` boilerplate\r\n//? file just to opt-in to \"let the user through\".\r\n//?\r\n//? Consumers who need a cross-cutting global guard (telemetry, server-\r\n//? reachability check, maintenance banner gate) call\r\n//? `registerMiddlewareHandler(...)` directly from `main.tsx` with their own\r\n//? function — no separate file required.\r\nconst DEFAULT_HANDLER: MiddlewareHandler = () => ({ success: true });\r\n\r\nlet activeHandler: MiddlewareHandler = DEFAULT_HANDLER;\r\n\r\nexport const registerMiddlewareHandler = (handler: MiddlewareHandler): void => {\r\n activeHandler = handler;\r\n};\r\n\r\nexport const getMiddlewareHandler = (): MiddlewareHandler => activeHandler;\r\n\r\n//? Per-page middleware registry. Counterpart to `registerMiddlewareHandler`\r\n//? for the common case where each page declares its own guard locally\r\n//? (`export const middleware = ({ session }) => {...}` from page.tsx).\r\n//? The framework's `<Middleware>` component checks this map FIRST and only\r\n//? falls back to the global handler when no per-page entry is registered.\r\n//?\r\n//? `PageMiddleware<TSession>` matches the existing `MiddlewareHandler`\r\n//? signature so any handler shape is reusable on either side. The generic\r\n//? is purely ergonomic for consumer-side type narrowing — module\r\n//? augmentation of `BaseSessionLayout` flows through.\r\n\r\nexport type PageMiddleware<TSession extends BaseSessionLayout = BaseSessionLayout> = (\r\n input: { location: string; searchParams: Record<string, string>; session: TSession | null },\r\n) => MiddlewareResult | Promise<MiddlewareResult>;\r\n\r\nconst pageMiddlewares = new Map<string, PageMiddleware>();\r\n\r\nexport const registerPageMiddleware = (path: string, middleware: PageMiddleware): void => {\r\n pageMiddlewares.set(path, middleware);\r\n};\r\n\r\nexport const getPageMiddleware = (path: string): PageMiddleware | undefined =>\r\n pageMiddlewares.get(path);\r\n\r\nexport const hasPageMiddleware = (path: string): boolean => pageMiddlewares.has(path);\r\n\r\n/** Test helper — drop every registered per-page middleware. */\r\nexport const clearPageMiddlewaresForTests = (): void => {\r\n pageMiddlewares.clear();\r\n};\r\n","//? Shared session context. Defined in core so framework-React components\r\n//? (Middleware, Router, useSession-aware UI) can consume it without\r\n//? pulling in app code. The consumer's `SessionProvider` (in their\r\n//? template's `_providers/`) does the actual fetch/socket/lifecycle work\r\n//? and writes to this context via `<SessionContext value={...}>`.\r\n//?\r\n//? The session shape inside the context is intentionally loose\r\n//? (`BaseSessionLayout | null`) so app code with extended session types\r\n//? can read it through a typed `useSession<MySession>()` cast.\r\n\r\nimport { createContext, use } from 'react';\r\nimport type { BaseSessionLayout } from '../sessionTypes';\r\nimport {\r\n dispatchClientHook,\r\n dispatchVetoableClientHook,\r\n type ClientHookStopSignal,\r\n} from '../clientHookBus';\r\n\r\nexport interface SessionContextValue<TSession extends BaseSessionLayout = BaseSessionLayout> {\r\n session: TSession | null;\r\n sessionLoaded: boolean;\r\n}\r\n\r\nconst DEFAULT_VALUE: SessionContextValue = {\r\n session: null,\r\n sessionLoaded: false,\r\n};\r\n\r\nexport const SessionContext = createContext<SessionContextValue>(DEFAULT_VALUE);\r\n\r\nexport function useSession<TSession extends BaseSessionLayout = BaseSessionLayout>(): SessionContextValue<TSession> {\r\n return use(SessionContext) as SessionContextValue<TSession>;\r\n}\r\n\r\n//? Non-React accessor for code that runs outside the component tree\r\n//? (e.g. notify() called from a non-component). Kept in sync with the\r\n//? context by the consumer's SessionProvider via `setLatestSession()`.\r\nlet latestSession: BaseSessionLayout | null = null;\r\n\r\nexport const setLatestSession = (session: BaseSessionLayout | null): void => {\r\n const previous = latestSession;\r\n latestSession = session;\r\n\r\n //? Fire client-side lifecycle hooks on null↔non-null transitions. Covers\r\n //? both fresh login AND existing-session restore on page reload — both\r\n //? cases need the same downstream actions (room auto-join, analytics\r\n //? identify, etc). Same-id updates (avatar refresh, profile change) do\r\n //? NOT fire postLogin; if a `sessionUpdate` hook is needed later, add it\r\n //? as a third branch without breaking existing handlers.\r\n if (previous === null && session !== null) {\r\n dispatchClientHook('postLogin', { session });\r\n } else if (previous !== null && session === null) {\r\n dispatchClientHook('postLogout', { previousSession: previous });\r\n }\r\n};\r\n\r\n//? Caller-supplied `TSession` is used to narrow the return type at the\r\n//? callsite (consumers extend `BaseSessionLayout`). The lint rule sees it as\r\n//? \"used once\" but the parameter exists solely to surface the consumer's\r\n//? widened session type through the read API.\r\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- callsite-narrowing use\r\nexport const getCurrentSession = <TSession extends BaseSessionLayout = BaseSessionLayout>(): TSession | null =>\r\n latestSession as TSession | null;\r\n\r\n/**\r\n * Vetoable entry point for committing a null → session transition (i.e. a\r\n * fresh login or a page-load session restore). Dispatches the `preLogin`\r\n * client hook to every registered handler in parallel; if any returns a\r\n * stop signal, the transition is aborted and `{ committed: false, signal }`\r\n * is returned. Otherwise, `setLatestSession(session)` runs synchronously\r\n * (which fires `postLogin`) and `{ committed: true }` comes back.\r\n *\r\n * Consumer's `SessionProvider` should `await` this for non-null session\r\n * commits and roll local React state back to `null` when a veto comes\r\n * through, so the UI doesn't render a half-logged-in state.\r\n */\r\nexport type ProposeLoginResult =\r\n | { stopped: false; committed: true }\r\n | { stopped: true; signal: ClientHookStopSignal; committed: false };\r\n\r\nexport const proposeLogin = async (\r\n session: BaseSessionLayout,\r\n): Promise<ProposeLoginResult> => {\r\n const veto = await dispatchVetoableClientHook('preLogin', { candidateSession: session });\r\n if (veto.stopped) return { stopped: true, signal: veto.signal, committed: false };\r\n setLatestSession(session);\r\n return { stopped: false, committed: true };\r\n};\r\n","/* eslint-disable react-refresh/only-export-components */\r\nimport { createContext, use, useState, useMemo, useCallback, ReactNode } from 'react';\r\n\r\nexport type AvatarStatus = 'avatar' | 'fallback';\r\n\r\ninterface AvatarContextType {\r\n avatarStatuses: Record<string, AvatarStatus>;\r\n setAvatarStatus: (key: string, status: AvatarStatus) => void;\r\n}\r\n\r\nconst AvatarContext = createContext<AvatarContextType | null>(null);\r\n\r\nexport const AvatarProvider = ({ children }: { children: ReactNode }) => {\r\n const [avatarStatuses, setAvatarStatuses] = useState<Record<string, AvatarStatus>>({});\r\n\r\n const setAvatarStatus = useCallback((key: string, status: AvatarStatus) => {\r\n setAvatarStatuses(prev => ({ ...prev, [key]: status }));\r\n }, []);\r\n\r\n const contextValue = useMemo(() => ({\r\n avatarStatuses,\r\n setAvatarStatus,\r\n }), [avatarStatuses, setAvatarStatus]);\r\n\r\n return (\r\n <AvatarContext value={contextValue}>\r\n {children}\r\n </AvatarContext>\r\n );\r\n};\r\n\r\nexport function useAvatarContext() {\r\n const ctx = use(AvatarContext);\r\n if (!ctx) throw new Error('useAvatarContext must be used within AvatarProvider');\r\n return ctx;\r\n}\r\n","//? `useTheme()` — framework-owned theme state hook. Default value comes\r\n//? from `getProjectConfig().defaultTheme` (the union literal exported by\r\n//? the consumer's `config.ts`). Toggling sets the `.dark` class on\r\n//? `<html>`. Persistence (e.g. saving to `User.theme` via\r\n//? `settings/updateUser`) is up to the consumer — the hook only owns\r\n//? local state + DOM class.\r\n\r\nimport { useState, useCallback } from 'react';\r\nimport { getProjectConfig } from '../projectConfig';\r\n\r\nexport type Theme = 'light' | 'dark';\r\n\r\nconst applyDomClass = (theme: Theme): void => {\r\n if (typeof document === 'undefined') return;\r\n document.documentElement.classList.toggle('dark', theme === 'dark');\r\n};\r\n\r\nexport const useTheme = () => {\r\n const initialTheme = (getProjectConfig().defaultTheme) ?? 'light';\r\n const [theme, setThemeState] = useState<Theme>(initialTheme);\r\n\r\n const setTheme = useCallback((next: Theme) => {\r\n setThemeState(next);\r\n applyDomClass(next);\r\n }, []);\r\n\r\n return { theme, setTheme };\r\n};\r\n","/* eslint-disable react-refresh/only-export-components */\r\n//? Framework-owned translation provider. Reads the registered locales map\r\n//? (consumer registers via `registerLocales({...})` in their overlay) and\r\n//? the active language source (consumer registers via\r\n//? `registerLanguageSource(fn)`, typically `() => session?.language`).\r\n//? Default language falls back to `getProjectConfig().defaultLanguage`.\r\n\r\nimport { createContext, ReactNode, use, useEffect, useMemo, useState, Dispatch, SetStateAction } from 'react';\r\nimport {\r\n getActiveLanguage,\r\n getDefaultLocale,\r\n getLocaleByCode,\r\n getRegisteredLocales,\r\n} from '../localesRegistry';\r\n\r\nexport type TranslationRecord = Record<string, unknown>;\r\n\r\ninterface TranslationContextValue {\r\n translations: TranslationRecord;\r\n setLanguage: Dispatch<SetStateAction<string>>;\r\n}\r\n\r\nconst TranslationContext = createContext<TranslationContextValue | null>(null);\r\n\r\nconst resolveTranslations = (code: string): TranslationRecord => {\r\n const value = getLocaleByCode(code);\r\n if (value && typeof value === 'object') return value as TranslationRecord;\r\n return {};\r\n};\r\n\r\nexport function TranslationProvider({ children }: { children: ReactNode }) {\r\n const [language, setLanguage] = useState<string>(() => getActiveLanguage());\r\n const translations = useMemo(() => resolveTranslations(language), [language]);\r\n\r\n //? Poll the registered language source so changes to session.language\r\n //? (or whatever the consumer wired) flip the active language without a\r\n //? full remount. Cheap: shallow string compare every ~250ms.\r\n useEffect(() => {\r\n const handle = window.setInterval(() => {\r\n const next = getActiveLanguage();\r\n if (next !== language) setLanguage(next);\r\n }, 250);\r\n return () => { window.clearInterval(handle); };\r\n }, [language]);\r\n\r\n const contextValue = useMemo(() => ({ translations, setLanguage }), [translations]);\r\n\r\n return (\r\n <TranslationContext value={contextValue}>\r\n {children}\r\n </TranslationContext>\r\n );\r\n}\r\n\r\nexport function useTranslation() {\r\n const context = use(TranslationContext);\r\n if (!context) throw new Error('useTranslation must be used within a TranslationProvider');\r\n return context.translations;\r\n}\r\n\r\nexport function useUpdateLanguage() {\r\n const context = use(TranslationContext);\r\n if (!context) throw new Error('useUpdateLanguage must be used within a TranslationProvider');\r\n return context.setLanguage;\r\n}\r\n\r\nexport interface TranslateParam { key: string; value: string | number | boolean }\r\n\r\n//? Resolve `a.b.c` style dot-notation keys in a translation tree. Returns\r\n//? the key itself if it can't be resolved (so untranslated strings stand\r\n//? out in the UI rather than vanishing). Supports `{{param}}` substitution.\r\nexport function translate({ translationList, key, params }: {\r\n translationList: TranslationRecord;\r\n key: unknown;\r\n params?: TranslateParam[];\r\n}): string {\r\n if (typeof key !== 'string' || key.length === 0) return '';\r\n\r\n const parts = key.split('.');\r\n let result: unknown = translationList;\r\n for (const part of parts) {\r\n if (result && typeof result === 'object' && part in result) {\r\n result = (result as Record<string, unknown>)[part];\r\n } else {\r\n return key;\r\n }\r\n }\r\n if (typeof result !== 'string') return key;\r\n if (!Array.isArray(params) || params.length === 0) return result;\r\n\r\n let finalResult = result;\r\n for (const param of params) {\r\n if (!param.key) continue;\r\n //? Escape key before building the RegExp — a key containing regex\r\n //? meta-characters (e.g. `.`, `+`, `(`) would otherwise mis-substitute\r\n //? or cause ReDoS. Use a function-form replacer to prevent `$`-sequences\r\n //? in the translation value from being interpreted by String.prototype.replace.\r\n const escapedKey = param.key.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\r\n const regex = new RegExp(`\\\\{\\\\{${escapedKey}\\\\}\\\\}`, 'g');\r\n const replacement = String(param.value);\r\n finalResult = finalResult.replace(regex, () => replacement);\r\n }\r\n return finalResult;\r\n}\r\n\r\n//? Tiny convenience hook for the common case: pass `{ key, params }` and\r\n//? get the resolved string back.\r\nexport const useTranslator = () => {\r\n const translations = useTranslation();\r\n return ({ key, params }: { key: string; params?: TranslateParam[] }) =>\r\n translate({ translationList: translations, key, params });\r\n};\r\n\r\n//? Re-export helpers from the registry so consumers have a single import\r\n//? point for translation customization.\r\nexport { getActiveLanguage, getDefaultLocale, getRegisteredLocales };\r\n","//? Framework-owned i18n-backed toast notify. Reads the active language\r\n//? source + the registered locales map to translate `{ key, params }`\r\n//? before handing off to `sonner`. Registers itself with\r\n//? `registerNotifier` on import so framework packages (apiRequest,\r\n//? syncRequest) automatically emit toasts in the consumer's locale.\r\n//?\r\n//? Importing this module triggers the registration as a side effect —\r\n//? add `import { i18nNotify } from '@luckystack/core/client';` to the\r\n//? consumer's main entry once.\r\n\r\nimport { toast } from 'sonner';\r\nimport { registerNotifier } from '../notifier';\r\nimport { getActiveLanguage, getLocaleByCode } from '../localesRegistry';\r\nimport { translate, type TranslateParam } from './TranslationProvider';\r\n\r\ninterface NotifyInput {\r\n key: string;\r\n params?: TranslateParam[];\r\n}\r\n\r\nconst resolve = (input: NotifyInput): string => {\r\n const language = getActiveLanguage();\r\n const list = getLocaleByCode(language);\r\n return translate({\r\n translationList: (list && typeof list === 'object' ? list : {}) as Record<string, unknown>,\r\n key: input.key,\r\n params: input.params,\r\n });\r\n};\r\n\r\nconst notify = {\r\n success: (input: NotifyInput) => { toast.success(resolve(input)); },\r\n error: (input: NotifyInput) => { toast.error(resolve(input)); },\r\n info: (input: NotifyInput) => { toast.info(resolve(input)); },\r\n warning: (input: NotifyInput) => { toast.warning(resolve(input)); },\r\n};\r\n\r\n//? Side-effect: register with core so framework packages emit through\r\n//? this i18n-backed implementation.\r\nregisterNotifier(notify);\r\n\r\nexport default notify;\r\n","//? Framework-owned route guard. Wraps protected pages — runs the registered\r\n//? middleware handler (`registerMiddlewareHandler` in core) on every route\r\n//? change and renders children only when allowed. Redirects via React\r\n//? Router's `useNavigate` when the handler returns a redirect. Shows a\r\n//? loader only after a 200ms delay so fast checks don't flash a spinner.\r\n\r\nimport { ReactNode, useEffect, useRef, useState } from 'react';\r\nimport { useLocation, useNavigate } from 'react-router-dom';\r\nimport { getMiddlewareHandler, getPageMiddleware } from '../middlewareRegistry';\r\nimport { useSession } from './sessionContext';\r\nimport { getProjectConfig } from '../projectConfig';\r\n\r\nconst LOADER_DELAY_MS = 200;\r\n\r\nfunction MiddlewareLoader() {\r\n const [show, setShow] = useState(false);\r\n\r\n useEffect(() => {\r\n const id = globalThis.setTimeout(() => { setShow(true); }, LOADER_DELAY_MS);\r\n return () => { globalThis.clearTimeout(id); };\r\n }, []);\r\n\r\n if (!show) return null;\r\n\r\n return (\r\n <div className=\"w-full h-full flex items-center justify-center\" aria-busy=\"true\" aria-live=\"polite\">\r\n <div\r\n className=\"w-8 h-8 rounded-full border-2 border-container2-border border-t-primary animate-spin\"\r\n role=\"status\"\r\n aria-label=\"Loading\"\r\n />\r\n </div>\r\n );\r\n}\r\n\r\nexport default function Middleware({ children }: { children: ReactNode }) {\r\n const [allowed, setAllowed] = useState(false);\r\n const [checking, setChecking] = useState(true);\r\n\r\n const location = useLocation();\r\n const navigate = useNavigate();\r\n const { session, sessionLoaded } = useSession();\r\n\r\n //? Track the guarded route so a SESSION-only change re-evaluates the guard\r\n //? WITHOUT unmounting the page. A session update (avatar, roomCodes,\r\n //? preferences pushed via `updateSession`) used to flip `checking` back to\r\n //? true on every change → the whole page unmounted + remounted, wiping page\r\n //? state and aborting in-flight work. Joining a room (which saves the session\r\n //? and broadcasts `updateSession`) therefore looked like a full page refresh.\r\n //? Now we only show the loader / hide the page on a real ROUTE change; a bare\r\n //? session change re-checks in the background and only navigates away if the\r\n //? new session is no longer allowed.\r\n const routeKey = `${location.pathname}\u0000${location.search}`;\r\n const guardedRouteRef = useRef<string | null>(null);\r\n\r\n useEffect(() => {\r\n let isMounted = true;\r\n const isRouteChange = guardedRouteRef.current !== routeKey;\r\n guardedRouteRef.current = routeKey;\r\n if (isRouteChange) {\r\n setAllowed(false);\r\n setChecking(true);\r\n }\r\n\r\n void (async () => {\r\n const params = new URLSearchParams(location.search);\r\n const queryObject: Record<string, string> = {};\r\n for (const [key, value] of params.entries()) {\r\n queryObject[key] = value;\r\n }\r\n\r\n //? Wait for the SessionProvider to finish its initial fetch — up to\r\n //? 5 seconds. Without this, we'd evaluate the middleware against a\r\n //? not-yet-loaded session and bounce the user back to /login.\r\n let count = 0;\r\n while (!sessionLoaded) {\r\n await new Promise(res => setTimeout(res, 10));\r\n count++;\r\n if (count > 500) break;\r\n }\r\n\r\n //? Per-page middleware first (declared in each page.tsx via\r\n //? `export const middleware`), then the global fallback handler\r\n //? registered via `registerMiddlewareHandler`. This lets pages own\r\n //? their own guards while keeping a central catch-all for\r\n //? cross-cutting cases (server-reachability checks, analytics).\r\n const pageMw = getPageMiddleware(location.pathname);\r\n const handler = pageMw ?? getMiddlewareHandler();\r\n const result = await handler({\r\n location: location.pathname,\r\n searchParams: queryObject,\r\n session,\r\n });\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- isMounted intentional, see comment below\r\n if (!isMounted) return;\r\n\r\n if (result?.success) {\r\n setAllowed(true);\r\n } else if (result?.redirect) {\r\n void navigate(result.redirect);\r\n } else {\r\n //? Navigate to a safe, deterministic fallback instead of `navigate(-1)`,\r\n //? which chains backwards out of the app on repeated denials (e.g. when\r\n //? history is shallow or the previous page was also guarded).\r\n void navigate(getProjectConfig().loginRedirectUrl ?? '/');\r\n }\r\n\r\n setChecking(false);\r\n })();\r\n\r\n //! isMounted check is load-bearing — without it, repeated middleware\r\n //? denials chain navigate(-1) and walk too far up history. Keep it.\r\n return () => {\r\n isMounted = false;\r\n };\r\n }, [routeKey, location.pathname, location.search, navigate, session, sessionLoaded]);\r\n\r\n if (checking) return <MiddlewareLoader />;\r\n if (!allowed) return null;\r\n return <div className=\"w-full h-full\">{children}</div>;\r\n}\r\n","//? Wrapper around react-router-dom's `useNavigate` that runs the\r\n//? registered middleware handler before navigating. Returns the guarded\r\n//? navigate function. Use everywhere instead of `useNavigate` directly so\r\n//? programmatic navigations honor the same auth/redirect rules as\r\n//? `<Middleware>`-wrapped page renders.\r\n\r\nimport { useLocation, useNavigate } from 'react-router-dom';\r\nimport { getMiddlewareHandler, getPageMiddleware } from '../middlewareRegistry';\r\nimport { useSession } from './sessionContext';\r\n\r\nconst getParams = (locationSearch: string) => {\r\n const params = new URLSearchParams(locationSearch);\r\n const queryObject: Record<string, string> = {};\r\n for (const [key, value] of params.entries()) {\r\n queryObject[key] = value;\r\n }\r\n return queryObject;\r\n};\r\n\r\nexport default function useRouter() {\r\n const navigateHandler = useNavigate();\r\n const location = useLocation();\r\n const { session } = useSession();\r\n\r\n const navigate = async (path: string) => {\r\n const queryObject = getParams(location.search);\r\n //? Per-page middleware first (declared via `export const middleware`\r\n //? on the target page.tsx), then the global fallback. Mirrors the\r\n //? `<Middleware>` component's resolution order so programmatic\r\n //? navigations honor the same guards as direct URL hits.\r\n const pageMw = getPageMiddleware(path);\r\n const handler = pageMw ?? getMiddlewareHandler();\r\n const result = await handler({ location: path, searchParams: queryObject, session });\r\n\r\n if (result?.success) {\r\n return navigateHandler(path);\r\n }\r\n if (result && !result.success && result.redirect) {\r\n return navigateHandler(result.redirect);\r\n }\r\n return;\r\n };\r\n\r\n return navigate;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,IAAM,sBAAsB,oBAAI,IAA2B;AAC3D,IAAM,uBAAuB,oBAAI,IAA4B;AAMtD,SAAS,8BAA8B,aAAgD;AAC5F,sBAAoB,IAAI,WAAW;AACnC,SAAO,MAAM;AACX,wBAAoB,OAAO,WAAW;AAAA,EACxC;AACF;AAKO,SAAS,+BAA+B,aAAiD;AAC9F,uBAAqB,IAAI,WAAW;AACpC,SAAO,MAAM;AACX,yBAAqB,OAAO,WAAW;AAAA,EACzC;AACF;AAKA,eAAsB,+BACpB,KACe;AACf,MAAI,oBAAoB,SAAS,EAAG;AAGpC,QAAM,eAAe,CAAC,GAAG,mBAAmB;AAC5C,aAAW,eAAe,cAAc;AACtC,QAAI;AACF,YAAM,YAAY,GAAG;AAAA,IACvB,SAAS,OAAO;AACd,gBAAU,EAAE,MAAM,yCAAyC,KAAK;AAAA,IAClE;AAAA,EACF;AACF;AAKO,SAAS,gCACd,KACM;AACN,MAAI,qBAAqB,SAAS,EAAG;AAErC,QAAM,eAAe,CAAC,GAAG,oBAAoB;AAC7C,aAAW,eAAe,cAAc;AACtC,QAAI;AACF,YAAM,SAAS,YAAY,GAAG;AAC9B,UAAI,UAAU,OAAQ,OAA4B,UAAU,YAAY;AACtE,QAAC,OAA4B,MAAM,CAAC,UAAmB;AACrD,oBAAU,EAAE,MAAM,mDAAmD,KAAK;AAAA,QAC5E,CAAC;AAAA,MACH;AAAA,IACF,SAAS,OAAO;AACd,gBAAU,EAAE,MAAM,0CAA0C,KAAK;AAAA,IACnE;AAAA,EACF;AACF;;;ACjFA,IAAM,wBAAwB;AAC9B,IAAM,mBAAmB,oBAAI,IAA6B;AAO1D,IAAM,kBAAkB,CAAC,UAA2B;AAClD,QAAM,OAAO,oBAAI,QAAg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O,gBAAgB,IAAI;AAAA,IAC7B;AACA,QAAI,UAAU,CAAC,OAAO,WAAW,OAAO,UAAU;AAChD,aAAO,gBAAgB,OAAO,QAAQ;AAAA,IACxC;AACA;AAAA,EACF;AAEA,SAAO;AACT;","names":["resolve","createContext","use","useState","useCallback","useState","useCallback","createContext","use","useMemo","useState","jsx","createContext","useState","useMemo","use","notify","useEffect","useState","jsx","useState","useEffect","useLocation","useNavigate","useNavigate","useLocation"]}
package/dist/index.d.ts CHANGED
@@ -1,12 +1,12 @@
1
- import { a6 as ErrorParam, a7 as ErrorResponseInput, a8 as NormalizedErrorResponse, a9 as HealthHashConfig, aa as DeepPartial, B as BaseSessionLayout, b as AuthProps } from './pageRouteValidation-DfiiLorR.js';
2
- export { ab as ApiConfig, A as ApiMethodMap, a as AppConfig, ac as AuthConfig, ad as AuthRateLimitConfig, ae as CorsConfig, D as DEFAULT_PAGE_ROUTE_RULES, af as DEFAULT_PROJECT_CONFIG, ag as DevConfig, ah as HttpConfig, H as HttpMethodLiteral, ai as HttpStreamConfig, aj as INVALID_ERROR_RESPONSE_CODE, L as Logger, c as LoggerContext, d as LoggingConfig, N as Notifier, e as NotifyInput, f as NotifyParam, ak as OfflineQueueConfig, P as PagePathValidationResult, g as PageRouteRules, al as PasswordPolicyConfig, am as PathsConfig, h as ProjectConfig, an as ProjectConfigInput, ao as QueueDropReason, ap as RateLimitIdentity, aq as RateLimitIdentityParams, R as RateLimitingConfig, S as SOCKETSTATUS, ar as SecurityHeadersConfig, as as ServiceRouteParseError, at as ServiceRouteParseResult, au as ServiceRouteParseSuccess, i as SessionConfig, j as SessionLocation, av as SocketConfig, aw as SyncConfig, ax as SyncFlushPressureConfig, ay as SyncStreamThrottleConfig, az as TransportRouteParseError, aA as TransportRouteParseResult, aB as TransportRouteParseSuccess, aC as ValidationConfig, k as buildApiResponseEventName, l as buildApiStreamEventName, m as buildGetJoinedRoomsResponseEventName, n as buildJoinRoomResponseEventName, o as buildLeaveRoomResponseEventName, p as buildSyncProgressEventName, q as buildSyncResponseEventName, r as clearCsrfToken, aD as createDevLogger, aE as deepMerge, aF as defaultHttpStatusForResponse, s as enqueueApiRequest, t as enqueueSyncRequest, u as flushApiQueue, v as flushSyncQueue, w as getApiQueueSize, x as getCsrfToken, y as getLogger, z as getNotifier, C as getProjectConfig, aG as getProjectName, E as getRegisteredApiMethod, F as getSyncQueueSize, G as httpFetch, I as incrementResponseIndex, J as isApiMethodMapRegistered, aH as isErrorParamArray, aI as isLoggerRegistered, K as isOnline, aJ as isPlainObject, M as isProjectConfigRegistered, O as normalizeErrorResponseCore, Q as notify, T as parseServiceRouteName, aK as parseTransportRouteName, U as registerApiMethodMap, V as registerLogger, W as registerNotifier, X as registerProjectConfig, Y as removeApiQueueItem, Z as removeApiQueueItemsByKey, _ as removeSyncQueueItem, aL as resetLoggerForTests, $ as setSocket, a0 as sleep, a1 as socket, a2 as socketEventNames, a3 as statusContent, a4 as validatePagePath, a5 as waitForSocket } from './pageRouteValidation-DfiiLorR.js';
1
+ import { a6 as ErrorParam, a7 as ErrorResponseInput, a8 as NormalizedErrorResponse, a9 as HealthHashConfig, aa as DeepPartial, B as BaseSessionLayout, b as AuthProps } from './pageRouteValidation-vDT5SERL.js';
2
+ export { ab as ApiConfig, A as ApiMethodMap, a as AppConfig, ac as AuthConfig, ad as AuthRateLimitConfig, ae as CorsConfig, D as DEFAULT_PAGE_ROUTE_RULES, af as DEFAULT_PROJECT_CONFIG, ag as DevConfig, ah as HttpConfig, H as HttpMethodLiteral, ai as HttpStreamConfig, aj as INVALID_ERROR_RESPONSE_CODE, L as Logger, c as LoggerContext, d as LoggingConfig, N as Notifier, e as NotifyInput, f as NotifyParam, ak as OfflineQueueConfig, P as PagePathValidationResult, g as PageRouteRules, al as PasswordPolicyConfig, am as PathsConfig, h as ProjectConfig, an as ProjectConfigInput, ao as QueueDropReason, ap as RateLimitIdentity, aq as RateLimitIdentityParams, R as RateLimitingConfig, S as SOCKETSTATUS, ar as SecretManagerConfigRef, as as SecurityHeadersConfig, at as ServiceRouteParseError, au as ServiceRouteParseResult, av as ServiceRouteParseSuccess, i as SessionConfig, j as SessionLocation, aw as SocketConfig, ax as SyncConfig, ay as SyncFlushPressureConfig, az as SyncStreamThrottleConfig, aA as TransportRouteParseError, aB as TransportRouteParseResult, aC as TransportRouteParseSuccess, aD as ValidationConfig, k as buildApiResponseEventName, l as buildApiStreamEventName, m as buildGetJoinedRoomsResponseEventName, n as buildJoinRoomResponseEventName, o as buildLeaveRoomResponseEventName, p as buildSyncProgressEventName, q as buildSyncResponseEventName, r as clearCsrfToken, aE as createDevLogger, aF as deepMerge, aG as defaultHttpStatusForResponse, s as enqueueApiRequest, t as enqueueSyncRequest, u as flushApiQueue, v as flushSyncQueue, w as getApiQueueSize, x as getCsrfToken, y as getLogger, z as getNotifier, C as getProjectConfig, aH as getProjectName, E as getRegisteredApiMethod, F as getSyncQueueSize, G as httpFetch, I as incrementResponseIndex, J as isApiMethodMapRegistered, aI as isErrorParamArray, aJ as isLoggerRegistered, K as isOnline, aK as isPlainObject, M as isProjectConfigRegistered, O as normalizeErrorResponseCore, Q as notify, T as parseServiceRouteName, aL as parseTransportRouteName, U as registerApiMethodMap, V as registerLogger, W as registerNotifier, X as registerProjectConfig, Y as removeApiQueueItem, Z as removeApiQueueItemsByKey, _ as removeSyncQueueItem, aM as resetLoggerForTests, $ as setSocket, a0 as sleep, a1 as socket, a2 as socketEventNames, a3 as statusContent, a4 as validatePagePath, a5 as waitForSocket } from './pageRouteValidation-vDT5SERL.js';
3
3
  export { ApiTypeMap, StreamPayload, SyncTypeMap } from './apiTypeStubs.js';
4
4
  import { Server, Socket } from 'socket.io';
5
5
  import { z } from 'zod';
6
6
  import * as _prisma_client_runtime_library from '@prisma/client/runtime/library';
7
7
  import * as _prisma_client from '@prisma/client';
8
8
  import { PrismaClient } from '@prisma/client';
9
- import Redis, { Redis as Redis$1 } from 'ioredis';
9
+ import Redis$1, { Redis } from 'ioredis';
10
10
  import { RedisAdapterOptions } from '@socket.io/redis-adapter';
11
11
  import { ServerResponse, IncomingMessage, IncomingHttpHeaders } from 'node:http';
12
12
  import 'socket.io-client';
@@ -679,6 +679,7 @@ declare const isDbHealthCheckRegistered: () => boolean;
679
679
  declare const resetDbHealthCheckForTests: () => void;
680
680
 
681
681
  declare const resetDefaultRedisClient: () => void;
682
+ declare const rebuildDefaultRedisClient: () => Redis;
682
683
  interface RedisConnectionOptions {
683
684
  host: string;
684
685
  port: number;
@@ -687,7 +688,11 @@ interface RedisConnectionOptions {
687
688
  }
688
689
  declare const getRedisConnectionOptions: () => RedisConnectionOptions;
689
690
  declare const registerStrayPrefixCommand: (...commands: string[]) => void;
690
- declare const redis: Redis;
691
+ declare const redis: Redis$1;
692
+
693
+ type SecretsResolvedListener = (changedKeys: readonly string[] | undefined) => void;
694
+ declare const registerSecretsResolvedListener: (listener: SecretsResolvedListener) => (() => void);
695
+ declare const notifySecretsResolved: (changedKeys?: readonly string[]) => void;
691
696
 
692
697
  type RedisKeyFormatter = (namespace: string, suffix: string) => string;
693
698
  declare const defaultRedisKeyFormatter: RedisKeyFormatter;
@@ -718,15 +723,15 @@ declare const releaseLease: (name: string, token: string) => Promise<boolean>;
718
723
 
719
724
  declare const DEFAULT_CLIENT_KEY = "default";
720
725
  declare const registerPrismaClient: (client: PrismaClient, key?: string) => PrismaClient;
721
- declare const registerRedisClient: (client: Redis$1, key?: string) => Redis$1;
726
+ declare const registerRedisClient: (client: Redis, key?: string) => Redis;
722
727
  declare const isPrismaClientRegistered: () => boolean;
723
728
  declare const isRedisClientRegistered: () => boolean;
724
729
  declare const getPrismaClientKeys: () => string[];
725
730
  declare const getRedisClientKeys: () => string[];
726
731
  declare const getPrismaClientFor: (key?: string) => PrismaClient;
727
- declare const getRedisClientFor: (key?: string) => Redis$1;
732
+ declare const getRedisClientFor: (key?: string) => Redis;
728
733
  declare const getPrismaClient: () => PrismaClient;
729
- declare const getRedisClient: () => Redis$1;
734
+ declare const getRedisClient: () => Redis;
730
735
  declare const resetClientsForTests: () => void;
731
736
 
732
737
  interface AttachSocketRedisAdapterOptions {
@@ -740,9 +745,9 @@ interface AttachSocketRedisAdapterOptions {
740
745
  * a dedicated adapter connection, custom auth, or a sentinel/cluster handle.
741
746
  * When omitted the framework duplicates the default `redis` handle.
742
747
  */
743
- pubClient?: Redis$1;
748
+ pubClient?: Redis;
744
749
  /** Pre-built sub client (see `pubClient`). */
745
- subClient?: Redis$1;
750
+ subClient?: Redis;
746
751
  }
747
752
  declare const attachSocketRedisAdapter: (io: Server, options?: AttachSocketRedisAdapterOptions) => void;
748
753
 
@@ -1890,4 +1895,4 @@ declare const clearAllHooks: () => void;
1890
1895
  declare const registerSyncHook: <TName extends SyncHookName>(name: TName, handler: SyncHookHandler<SyncHookPayloads[TName]>) => (() => void);
1891
1896
  declare const dispatchSyncHook: <TName extends SyncHookName>(name: TName, payload: SyncHookPayloads[TName]) => void;
1892
1897
 
1893
- export { type ApiAuthRejectedPayload, type ApiErrorPayload, type ApiResponseEnvelope, AuthProps, type AvatarConfig, type AvatarConfigInput, BOOT_KEY_PREFIX, BaseSessionLayout, type CheckRateLimitParams, type CookiePrefixConstraints, type CorsRejectedPayload, type CreateLocalizedNormalizerInput, type CsrfConfig, type CsrfCookieOptions, type CsrfMismatchPayload, DEFAULT_AVATAR_CONFIG, DEFAULT_CLIENT_KEY, DEFAULT_CSRF_CONFIG, DEFAULT_ENV_FILES, DEFAULT_REDACTED_LOG_KEYS, DEPTH_TRUNCATED_PLACEHOLDER, type DbHealthCheck, type DbHealthResult, DeepPartial, type DeployConfigShape, type DeployDevelopmentShape, type DeployEnvironmentShape, type DeployResourceShape, type DeployRoutingShape, type DispatchResult, type EmailAttachment, type EmailMessage, type EmailResult, type EmailSender, type EmailSenderRegistry, type ErrorFormatter, type ErrorFormatterContext, ErrorParam, ErrorResponseInput, type ErrorTracker, type ErrorTrackerContext, type ErrorTrackerEvent, type ErrorTrackerUser, type FormatterEnvelope, GENERATED_API_DOCS_PATH, GENERATED_API_SCHEMAS_PATH, GENERATED_SOCKET_TYPES_PATH, HealthHashConfig, type HealthHashDescriptor, type HookHandler, type HookName, type HookPayloads, type HookResult, type HookSessionShape, type HookStopSignal, type HttpMethod, type LanguageCode, type LocaleReloader, type LocalizedNormalizer, type NormalizeErrorResponseInput, NormalizedErrorResponse, type OnUploadCompletePayload, type OnUploadStartPayload, type OneTimeTokenHandle, PUBLIC_DIR, type PeerRequire, type PostApiExecutePayload, type PostApiRespondPayload, type PostApiValidatePayload, type PostAvatarServePayload, type PostErrorNormalizePayload, type PostHttpRequestPayload, type PostSessionRefreshPayload, type PostSyncAuthorizePayload, type PostSyncExecutePayload, type PostSyncFanoutPayload, type PostSyncValidatePayload, type PreApiExecutePayload, type PreApiRespondPayload, type PreApiValidatePayload, type PreAvatarServePayload, type PreCaptureFilter, type PreErrorNormalizePayload, type PreHttpRequestPayload, type PreServerStopPayload, type PreSessionRefreshPayload, type PreSocketMessagePayload, type PreSyncAuthorizePayload, type PreSyncExecutePayload, type PreSyncFanoutPayload, type PreSyncRecipientPayload, type PreSyncValidatePayload, type PresetDefinition, type ProcessUploadInput, type ProcessUploadResult, REDACTED_PLACEHOLDER, ROOT_DIR, type RateLimitExceededPayload, type RateLimitResult, type RateLimitStrategy, type RedisConnectionOptions, type RedisKeyFormatter, type Registry, type RegistryOptions, type ResolveClientIpParams, type RoomNameFormatter, type RoomNameFormatterContext, type RuntimeApiMapsResult, type RuntimeEnv, type RuntimeMapsProvider, type RuntimeSyncMapsResult, SERVER_DIR, SERVER_FUNCTIONS_DIR, SHARED_DIR, SRC_DIR, type ServiceDefinition, type ServicesConfigShape, type SessionCreatedPayload, type SessionLogoutInput, type SessionProvider, type SessionRevokedPayload, type SessionSaveResult, type SocketMiddleware, type SpanHandle, type SpanResult, type SyncErrorPayload, type SyncHookHandler, type SyncHookName, type SyncHookPayloads, TSCONFIG_ALIAS_FILES, type TranslateFunction, type TranslateInput, UNKNOWN_CLIENT_IP, UPLOADS_DIR, type ValidationResult$1 as ValidationResult, abortAllForSocket, abortApiByResponseIndex, abortSyncByCb, acquireLease, allowedOrigin, type apiMessage, appendErrorTracker, applyCookiePrefixConstraints, applyErrorFormatter, applySocketMiddlewares, applyStrayKeyPrefix, attachSocketRedisAdapter, bootstrapEnv, captureException, captureExceptionAcrossTrackers, captureMessage, captureMessageAcrossTrackers, checkRateLimit, clearAllHooks, clearAllRateLimits, clearRateLimit, clearSocketMiddlewares, collectSynchronizedEnvKeys, computeSynchronizedEnvHashes, consumeOneTimeToken, consumeOneTimeTokenJson, createLocalizedNormalizer, createRegistry, defaultRateLimitStrategy, defaultRedisKeyFormatter, defaultRoomNameFormatter, deriveTokenBucketId, describeHealthHashConfig, dispatchHook, dispatchSyncHook, ensurePeerDepInstalled, env, escapeHtml, extractLanguageFromHeader, extractTokenFromRequest, extractTokenFromSocket, flushErrorTrackers, formatKey, formatRoomName, getActiveErrorTrackers, getAvatarConfig, getBindAddress, getCookieValue, getCsrfConfig, getCurrentErrorTrackerIdentity, getDbHealthCheck, getDeployConfig, getEffectiveHttpMethod, getEmailSender, getEmailSenderByName, getEnv, getEnvFiles, getErrorFormatter, getGeneratedApiDocsPath, getGeneratedApiSchemasPath, getGeneratedSocketTypesPath, getIoInstance, getLocaleReloader, getLocalizedNormalizer, getParams, getPrismaClient, getPrismaClientFor, getPrismaClientKeys, getPublicDir, getRateLimitStatus, getRateLimitStrategy, getRedactedLogKeys, getRedisClient, getRedisClientFor, getRedisClientKeys, getRedisConnectionOptions, getRedisKeyFormatter, getRegisteredSessionProvider, getRoomNameFormatter, getRuntimeApiMaps, getRuntimeSyncMaps, getServerDir, getServerFunctionDirs, getServerFunctionsDir, getServicesConfig, getSharedDir, getSocketMiddlewares, getSrcDir, getUploadsDir, hasCookie, hashSynchronizedValue, hashSynchronizedValueWith, inferHttpMethod, initConsolelog, initSharedSentry, isDbHealthCheckRegistered, isDeployConfigRegistered, isEmailSenderRegistered, isFalsy, isGetMethodName, isLocalizedNormalizerRegistered, isLoopbackIp, isMethodAllowed, isPrismaClientRegistered, isPrismaClientResolvable, isProduction, isRedactedLogKey, isRedisClientRegistered, isRuntimeMapsProviderRegistered, isServicesConfigRegistered, isSessionProviderRegistered, issueOneTimeToken, listEmailSenderNames, loadEnvFiles, loadPeer, normalizeErrorResponse, normalizeOrigin, oneTimeTokenKey, performLogout, prisma, processUpload, readBootUuid, readSession, recordMetricAcrossTrackers, redis, registerApiAbortController, registerAvatarConfig, registerBindAddress, registerCsrfConfig, registerDbHealthCheck, registerDeployConfig, registerEmailSender, registerEmailSenders, registerErrorFormatter, registerErrorTracker, registerErrorTrackers, registerHook, registerLocaleReloader, registerLocalizedNormalizer, registerPreCaptureFilter, registerPrismaClient, registerRateLimitStrategy, registerRedactedLogKeys, registerRedisClient, registerRedisKeyFormatter, registerRoomNameFormatter, registerRuntimeMapsProvider, registerServicesConfig, registerSessionProvider, registerSocketMiddleware, registerStrayPrefixCommand, registerSyncAbortController, registerSyncHook, releaseLease, removeSession, renewLease, resetClientsForTests, resetCsrfConfigForTests, resetDbHealthCheckForTests, resetDefaultRedisClient, resetRedactedLogKeysForTests, resetRedisKeyFormatterForTests, resetSessionProviderForTests, resolveClientIp, resolveEnvKey, resolveErrorMessage, resolveFromRoot, resolveHealthHashConfig, resolveHealthHashConfigFromDescriptor, runWithErrorTrackerIdentity, runWithErrorTrackerIdentityScope, sanitizeErrorString, sanitizeErrorStrings, sanitizeForLog, serveAvatar, setCurrentErrorTrackerIdentity, setErrorTrackerUser, setIoInstance, setSentryUser, startSpan, startSpanAcrossTrackers, startSpanHandle, type syncMessage, tryCatch, tryCatchSync, unregisterApiAbortController, unregisterSyncAbortController, validateInputByType, validateRequest, writeBootUuid, writeSession };
1898
+ export { type ApiAuthRejectedPayload, type ApiErrorPayload, type ApiResponseEnvelope, AuthProps, type AvatarConfig, type AvatarConfigInput, BOOT_KEY_PREFIX, BaseSessionLayout, type CheckRateLimitParams, type CookiePrefixConstraints, type CorsRejectedPayload, type CreateLocalizedNormalizerInput, type CsrfConfig, type CsrfCookieOptions, type CsrfMismatchPayload, DEFAULT_AVATAR_CONFIG, DEFAULT_CLIENT_KEY, DEFAULT_CSRF_CONFIG, DEFAULT_ENV_FILES, DEFAULT_REDACTED_LOG_KEYS, DEPTH_TRUNCATED_PLACEHOLDER, type DbHealthCheck, type DbHealthResult, DeepPartial, type DeployConfigShape, type DeployDevelopmentShape, type DeployEnvironmentShape, type DeployResourceShape, type DeployRoutingShape, type DispatchResult, type EmailAttachment, type EmailMessage, type EmailResult, type EmailSender, type EmailSenderRegistry, type ErrorFormatter, type ErrorFormatterContext, ErrorParam, ErrorResponseInput, type ErrorTracker, type ErrorTrackerContext, type ErrorTrackerEvent, type ErrorTrackerUser, type FormatterEnvelope, GENERATED_API_DOCS_PATH, GENERATED_API_SCHEMAS_PATH, GENERATED_SOCKET_TYPES_PATH, HealthHashConfig, type HealthHashDescriptor, type HookHandler, type HookName, type HookPayloads, type HookResult, type HookSessionShape, type HookStopSignal, type HttpMethod, type LanguageCode, type LocaleReloader, type LocalizedNormalizer, type NormalizeErrorResponseInput, NormalizedErrorResponse, type OnUploadCompletePayload, type OnUploadStartPayload, type OneTimeTokenHandle, PUBLIC_DIR, type PeerRequire, type PostApiExecutePayload, type PostApiRespondPayload, type PostApiValidatePayload, type PostAvatarServePayload, type PostErrorNormalizePayload, type PostHttpRequestPayload, type PostSessionRefreshPayload, type PostSyncAuthorizePayload, type PostSyncExecutePayload, type PostSyncFanoutPayload, type PostSyncValidatePayload, type PreApiExecutePayload, type PreApiRespondPayload, type PreApiValidatePayload, type PreAvatarServePayload, type PreCaptureFilter, type PreErrorNormalizePayload, type PreHttpRequestPayload, type PreServerStopPayload, type PreSessionRefreshPayload, type PreSocketMessagePayload, type PreSyncAuthorizePayload, type PreSyncExecutePayload, type PreSyncFanoutPayload, type PreSyncRecipientPayload, type PreSyncValidatePayload, type PresetDefinition, type ProcessUploadInput, type ProcessUploadResult, REDACTED_PLACEHOLDER, ROOT_DIR, type RateLimitExceededPayload, type RateLimitResult, type RateLimitStrategy, type RedisConnectionOptions, type RedisKeyFormatter, type Registry, type RegistryOptions, type ResolveClientIpParams, type RoomNameFormatter, type RoomNameFormatterContext, type RuntimeApiMapsResult, type RuntimeEnv, type RuntimeMapsProvider, type RuntimeSyncMapsResult, SERVER_DIR, SERVER_FUNCTIONS_DIR, SHARED_DIR, SRC_DIR, type SecretsResolvedListener, type ServiceDefinition, type ServicesConfigShape, type SessionCreatedPayload, type SessionLogoutInput, type SessionProvider, type SessionRevokedPayload, type SessionSaveResult, type SocketMiddleware, type SpanHandle, type SpanResult, type SyncErrorPayload, type SyncHookHandler, type SyncHookName, type SyncHookPayloads, TSCONFIG_ALIAS_FILES, type TranslateFunction, type TranslateInput, UNKNOWN_CLIENT_IP, UPLOADS_DIR, type ValidationResult$1 as ValidationResult, abortAllForSocket, abortApiByResponseIndex, abortSyncByCb, acquireLease, allowedOrigin, type apiMessage, appendErrorTracker, applyCookiePrefixConstraints, applyErrorFormatter, applySocketMiddlewares, applyStrayKeyPrefix, attachSocketRedisAdapter, bootstrapEnv, captureException, captureExceptionAcrossTrackers, captureMessage, captureMessageAcrossTrackers, checkRateLimit, clearAllHooks, clearAllRateLimits, clearRateLimit, clearSocketMiddlewares, collectSynchronizedEnvKeys, computeSynchronizedEnvHashes, consumeOneTimeToken, consumeOneTimeTokenJson, createLocalizedNormalizer, createRegistry, defaultRateLimitStrategy, defaultRedisKeyFormatter, defaultRoomNameFormatter, deriveTokenBucketId, describeHealthHashConfig, dispatchHook, dispatchSyncHook, ensurePeerDepInstalled, env, escapeHtml, extractLanguageFromHeader, extractTokenFromRequest, extractTokenFromSocket, flushErrorTrackers, formatKey, formatRoomName, getActiveErrorTrackers, getAvatarConfig, getBindAddress, getCookieValue, getCsrfConfig, getCurrentErrorTrackerIdentity, getDbHealthCheck, getDeployConfig, getEffectiveHttpMethod, getEmailSender, getEmailSenderByName, getEnv, getEnvFiles, getErrorFormatter, getGeneratedApiDocsPath, getGeneratedApiSchemasPath, getGeneratedSocketTypesPath, getIoInstance, getLocaleReloader, getLocalizedNormalizer, getParams, getPrismaClient, getPrismaClientFor, getPrismaClientKeys, getPublicDir, getRateLimitStatus, getRateLimitStrategy, getRedactedLogKeys, getRedisClient, getRedisClientFor, getRedisClientKeys, getRedisConnectionOptions, getRedisKeyFormatter, getRegisteredSessionProvider, getRoomNameFormatter, getRuntimeApiMaps, getRuntimeSyncMaps, getServerDir, getServerFunctionDirs, getServerFunctionsDir, getServicesConfig, getSharedDir, getSocketMiddlewares, getSrcDir, getUploadsDir, hasCookie, hashSynchronizedValue, hashSynchronizedValueWith, inferHttpMethod, initConsolelog, initSharedSentry, isDbHealthCheckRegistered, isDeployConfigRegistered, isEmailSenderRegistered, isFalsy, isGetMethodName, isLocalizedNormalizerRegistered, isLoopbackIp, isMethodAllowed, isPrismaClientRegistered, isPrismaClientResolvable, isProduction, isRedactedLogKey, isRedisClientRegistered, isRuntimeMapsProviderRegistered, isServicesConfigRegistered, isSessionProviderRegistered, issueOneTimeToken, listEmailSenderNames, loadEnvFiles, loadPeer, normalizeErrorResponse, normalizeOrigin, notifySecretsResolved, oneTimeTokenKey, performLogout, prisma, processUpload, readBootUuid, readSession, rebuildDefaultRedisClient, recordMetricAcrossTrackers, redis, registerApiAbortController, registerAvatarConfig, registerBindAddress, registerCsrfConfig, registerDbHealthCheck, registerDeployConfig, registerEmailSender, registerEmailSenders, registerErrorFormatter, registerErrorTracker, registerErrorTrackers, registerHook, registerLocaleReloader, registerLocalizedNormalizer, registerPreCaptureFilter, registerPrismaClient, registerRateLimitStrategy, registerRedactedLogKeys, registerRedisClient, registerRedisKeyFormatter, registerRoomNameFormatter, registerRuntimeMapsProvider, registerSecretsResolvedListener, registerServicesConfig, registerSessionProvider, registerSocketMiddleware, registerStrayPrefixCommand, registerSyncAbortController, registerSyncHook, releaseLease, removeSession, renewLease, resetClientsForTests, resetCsrfConfigForTests, resetDbHealthCheckForTests, resetDefaultRedisClient, resetRedactedLogKeysForTests, resetRedisKeyFormatterForTests, resetSessionProviderForTests, resolveClientIp, resolveEnvKey, resolveErrorMessage, resolveFromRoot, resolveHealthHashConfig, resolveHealthHashConfigFromDescriptor, runWithErrorTrackerIdentity, runWithErrorTrackerIdentityScope, sanitizeErrorString, sanitizeErrorStrings, sanitizeForLog, serveAvatar, setCurrentErrorTrackerIdentity, setErrorTrackerUser, setIoInstance, setSentryUser, startSpan, startSpanAcrossTrackers, startSpanHandle, type syncMessage, tryCatch, tryCatchSync, unregisterApiAbortController, unregisterSyncAbortController, validateInputByType, validateRequest, writeBootUuid, writeSession };