@luckystack/core 0.8.6 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/CLAUDE.md +2 -1
- package/dist/client.d.ts +26 -2
- package/dist/client.js +36 -10
- package/dist/client.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.8.7] - 2026-08-18
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- `MiddlewareResult` gains a deny-in-place variant: `{ success: false, status: number }`. The contract previously only supported allow and redirect, so a route guard could not say "you are signed in but not allowed here" without sending the user somewhere else — losing the requested URL and explaining nothing. `<Middleware>` now keeps the URL and renders a deny state; pass `denied` (a node, or a function of the status) to supply your own, otherwise a minimal built-in view is used. Deliberately untranslated: `translate()` returns the KEY when it cannot resolve one, so a built-in with i18n keys would print `middleware.forbidden.title` in every project that upgrades without adding them.
|
|
15
|
+
- `resolveMiddlewareOutcome(result)` + the `MiddlewareOutcome` type — one interpretation of a middleware result, shared by `<Middleware>` and `useRouter`.
|
|
16
|
+
|
|
17
|
+
### Fixed
|
|
18
|
+
|
|
19
|
+
- `Middleware.tsx` no longer carries a stray NUL byte in the `routeKey` template literal (`${location.pathname}\0${location.search}`). Harmless at runtime — the key is only used for change detection — but git classified the source file as BINARY, so `git diff` showed nothing for it and it could not be merged textually. Predates 0.8.3.
|
|
20
|
+
- `useRouter` no longer silently does nothing when a guard denies. It branched separately from `<Middleware>` and returned without navigating for any result that was neither allow nor redirect, so a guarded button simply appeared broken. Both now route through `resolveMiddlewareOutcome`, and a `status` deny navigates so the target route can render the deny state at the requested URL.
|
|
21
|
+
|
|
10
22
|
## [0.8.5] - 2026-08-17
|
|
11
23
|
|
|
12
24
|
### Added
|
package/CLAUDE.md
CHANGED
|
@@ -140,7 +140,8 @@ Foundation package for LuckyStack. Owns the socket-first transport contracts (`a
|
|
|
140
140
|
| `registerPageMiddleware(path: string, fn: PageMiddleware): void` | Register a per-page route guard. Auto-called by `src/main.tsx`'s `getRoutes()` for every page that exports `middleware`. Per-page takes precedence over the global handler. | -> docs/hooks.md |
|
|
141
141
|
| `getPageMiddleware(path: string): PageMiddleware \| undefined` | Lookup the per-page guard for a given route. Framework-internal. | -> docs/hooks.md |
|
|
142
142
|
| `hasPageMiddleware(path: string): boolean` | Existence check. | -> docs/hooks.md |
|
|
143
|
-
| `MiddlewareInput`, `MiddlewareResult`, `MiddlewareHandler`, `PageMiddleware` (types) | Route-guard contract types. Both handler shapes share the same signature. | -> docs/hooks.md |
|
|
143
|
+
| `MiddlewareInput`, `MiddlewareResult`, `MiddlewareOutcome`, `MiddlewareHandler`, `PageMiddleware` (types) | Route-guard contract types. Both handler shapes share the same signature. `MiddlewareResult` has three deny-capable shapes: allow (`{ success: true }`), redirect (`{ success: false, redirect }`) and deny-in-place (`{ success: false, status }` — keeps the URL, renders a status state). | -> docs/hooks.md |
|
|
144
|
+
| `resolveMiddlewareOutcome(result): MiddlewareOutcome` | Normalizes a middleware result to `allow` / `redirect` / `deny` / `fallback`. THE single interpretation, shared by `<Middleware>` and `useRouter` so programmatic navigation and direct URL hits cannot diverge. | -> docs/hooks.md |
|
|
144
145
|
| `validatePagePath(srcRelativePath, rules?): PagePathValidationResult` | Pure validator for the invisible-parent folder convention used by `src/main.tsx`'s page auto-discovery AND the `scaffold:page` CLI. Returns `{ valid, route?, reason? }`. | -> docs/hooks.md |
|
|
145
146
|
| `DEFAULT_PAGE_ROUTE_RULES: PageRouteRules` | Default config (private-folder prefix `'_'` + reserved framework folders). | -> docs/hooks.md |
|
|
146
147
|
| `dispatchHook<TName>(name, payload): Promise<DispatchResult>` | Internal: framework code invokes registered handlers in order; first stop signal aborts. | -> docs/hooks.md |
|
package/dist/client.d.ts
CHANGED
|
@@ -116,10 +116,28 @@ interface MiddlewareInput {
|
|
|
116
116
|
type MiddlewareResult = {
|
|
117
117
|
success: true;
|
|
118
118
|
redirect?: undefined;
|
|
119
|
+
status?: undefined;
|
|
119
120
|
} | {
|
|
120
121
|
success: false;
|
|
121
122
|
redirect: string;
|
|
123
|
+
status?: undefined;
|
|
124
|
+
} | {
|
|
125
|
+
success: false;
|
|
126
|
+
redirect?: undefined;
|
|
127
|
+
status: number;
|
|
122
128
|
} | undefined;
|
|
129
|
+
/** Normalized decision derived from a {@link MiddlewareResult}. */
|
|
130
|
+
type MiddlewareOutcome = {
|
|
131
|
+
kind: 'allow';
|
|
132
|
+
} | {
|
|
133
|
+
kind: 'redirect';
|
|
134
|
+
to: string;
|
|
135
|
+
} | {
|
|
136
|
+
kind: 'deny';
|
|
137
|
+
status: number;
|
|
138
|
+
} | {
|
|
139
|
+
kind: 'fallback';
|
|
140
|
+
};
|
|
123
141
|
type MiddlewareHandler = (input: MiddlewareInput) => MiddlewareResult | Promise<MiddlewareResult>;
|
|
124
142
|
declare const registerMiddlewareHandler: (handler: MiddlewareHandler) => void;
|
|
125
143
|
declare const getMiddlewareHandler: () => MiddlewareHandler;
|
|
@@ -302,10 +320,16 @@ declare const notify: {
|
|
|
302
320
|
warning: (input: NotifyInput) => void;
|
|
303
321
|
};
|
|
304
322
|
|
|
305
|
-
declare function Middleware({ children }: {
|
|
323
|
+
declare function Middleware({ children, denied, }: {
|
|
306
324
|
children: ReactNode;
|
|
325
|
+
/**
|
|
326
|
+
* Rendered instead of the page when middleware denies IN PLACE
|
|
327
|
+
* (`{ success: false, status }`) — the URL is kept. Pass a node, or a
|
|
328
|
+
* function to vary by status. Defaults to a minimal built-in view.
|
|
329
|
+
*/
|
|
330
|
+
denied?: ReactNode | ((status: number) => ReactNode);
|
|
307
331
|
}): react.JSX.Element | null;
|
|
308
332
|
|
|
309
333
|
declare function useRouter(): (path: string) => Promise<void>;
|
|
310
334
|
|
|
311
|
-
export { type ApiErrorResponse, type ApiRequestInterceptor, type ApiRequestInterceptorContext, type ApiResponseInterceptor, type ApiResponseInterceptorContext, type ApiStreamEvent, ApiTypeMap, AvatarProvider, type AvatarStatus, BaseSessionLayout, type ClientDispatchResult, type ClientHookHandler, type ClientHookName, type ClientHookPayloadMap, type ClientHookResult, type ClientHookStopSignal, HttpMethodLiteral, type LanguageSource, type LocalesMap, Middleware, type MiddlewareHandler, type MiddlewareInput, type MiddlewareResult, type PageMiddleware, type RoutedHttpInvocationInput, type RoutedInvocationFailure, type RoutedInvocationMethod, type RoutedInvocationResponse, type RoutedInvocationResult, SessionContext, type SessionContextValue, StreamPayload, type Theme, type TranslateParam, TranslationProvider, type TranslationRecord, apiRequest, dispatchClientHook, dispatchVetoableClientHook, getActiveLanguage, getCurrentSession, getDefaultLocale, getLocaleByCode, getMiddlewareHandler, getPageMiddleware, getRegisteredLocales, hasPageMiddleware, notify as i18nNotify, invokeRoutedHttp, proposeLogin, registerApiRequestInterceptor, registerApiResponseInterceptor, registerClientHook, registerLanguageSource, registerLocales, registerMiddlewareHandler, registerPageMiddleware, setLatestSession, translate, tryCatch, useAvatarContext, useRouter, useSession, useTheme, useTranslation, useTranslator, useUpdateLanguage };
|
|
335
|
+
export { type ApiErrorResponse, type ApiRequestInterceptor, type ApiRequestInterceptorContext, type ApiResponseInterceptor, type ApiResponseInterceptorContext, type ApiStreamEvent, ApiTypeMap, AvatarProvider, type AvatarStatus, BaseSessionLayout, type ClientDispatchResult, type ClientHookHandler, type ClientHookName, type ClientHookPayloadMap, type ClientHookResult, type ClientHookStopSignal, HttpMethodLiteral, type LanguageSource, type LocalesMap, Middleware, type MiddlewareHandler, type MiddlewareInput, type MiddlewareOutcome, type MiddlewareResult, type PageMiddleware, type RoutedHttpInvocationInput, type RoutedInvocationFailure, type RoutedInvocationMethod, type RoutedInvocationResponse, type RoutedInvocationResult, SessionContext, type SessionContextValue, StreamPayload, type Theme, type TranslateParam, TranslationProvider, type TranslationRecord, apiRequest, dispatchClientHook, dispatchVetoableClientHook, getActiveLanguage, getCurrentSession, getDefaultLocale, getLocaleByCode, getMiddlewareHandler, getPageMiddleware, getRegisteredLocales, hasPageMiddleware, notify as i18nNotify, invokeRoutedHttp, proposeLogin, registerApiRequestInterceptor, registerApiResponseInterceptor, registerClientHook, registerLanguageSource, registerLocales, registerMiddlewareHandler, registerPageMiddleware, setLatestSession, translate, tryCatch, useAvatarContext, useRouter, useSession, useTheme, useTranslation, useTranslator, useUpdateLanguage };
|
package/dist/client.js
CHANGED
|
@@ -744,6 +744,12 @@ var getLocaleByCode = (code) => {
|
|
|
744
744
|
};
|
|
745
745
|
|
|
746
746
|
// src/middlewareRegistry.ts
|
|
747
|
+
var resolveMiddlewareOutcome = (result) => {
|
|
748
|
+
if (result?.success) return { kind: "allow" };
|
|
749
|
+
if (result?.redirect) return { kind: "redirect", to: result.redirect };
|
|
750
|
+
if (typeof result?.status === "number") return { kind: "deny", status: result.status };
|
|
751
|
+
return { kind: "fallback" };
|
|
752
|
+
};
|
|
747
753
|
var DEFAULT_HANDLER = () => ({ success: true });
|
|
748
754
|
var activeHandler = DEFAULT_HANDLER;
|
|
749
755
|
var registerMiddlewareHandler = (handler) => {
|
|
@@ -915,7 +921,7 @@ var notify_default = notify2;
|
|
|
915
921
|
// src/react/Middleware.tsx
|
|
916
922
|
import { useEffect as useEffect2, useRef, useState as useState4 } from "react";
|
|
917
923
|
import { useLocation, useNavigate } from "react-router-dom";
|
|
918
|
-
import { jsx as jsx3 } from "react/jsx-runtime";
|
|
924
|
+
import { jsx as jsx3, jsxs } from "react/jsx-runtime";
|
|
919
925
|
var LOADER_DELAY_MS = 200;
|
|
920
926
|
function MiddlewareLoader() {
|
|
921
927
|
const [show, setShow] = useState4(false);
|
|
@@ -937,13 +943,23 @@ function MiddlewareLoader() {
|
|
|
937
943
|
}
|
|
938
944
|
) });
|
|
939
945
|
}
|
|
940
|
-
function
|
|
946
|
+
function MiddlewareDenied({ status }) {
|
|
947
|
+
return /* @__PURE__ */ jsx3("div", { className: "w-full h-full flex items-center justify-center p-6", role: "alert", children: /* @__PURE__ */ jsxs("div", { className: "text-center max-w-md", children: [
|
|
948
|
+
/* @__PURE__ */ jsx3("div", { className: "text-4xl font-bold text-title mb-2", children: status }),
|
|
949
|
+
/* @__PURE__ */ jsx3("div", { className: "text-common", children: status === 404 ? "This page does not exist." : "You do not have permission to view this page." })
|
|
950
|
+
] }) });
|
|
951
|
+
}
|
|
952
|
+
function Middleware({
|
|
953
|
+
children,
|
|
954
|
+
denied
|
|
955
|
+
}) {
|
|
941
956
|
const [allowed, setAllowed] = useState4(false);
|
|
942
957
|
const [checking, setChecking] = useState4(true);
|
|
958
|
+
const [deniedStatus, setDeniedStatus] = useState4(null);
|
|
943
959
|
const location = useLocation();
|
|
944
960
|
const navigate = useNavigate();
|
|
945
961
|
const { session, sessionLoaded } = useSession();
|
|
946
|
-
const routeKey = `${location.pathname}
|
|
962
|
+
const routeKey = `${location.pathname} ${location.search}`;
|
|
947
963
|
const guardedRouteRef = useRef(null);
|
|
948
964
|
useEffect2(() => {
|
|
949
965
|
let isMounted = true;
|
|
@@ -952,6 +968,7 @@ function Middleware({ children }) {
|
|
|
952
968
|
if (isRouteChange) {
|
|
953
969
|
setAllowed(false);
|
|
954
970
|
setChecking(true);
|
|
971
|
+
setDeniedStatus(null);
|
|
955
972
|
}
|
|
956
973
|
void (async () => {
|
|
957
974
|
const params = new URLSearchParams(location.search);
|
|
@@ -973,10 +990,14 @@ function Middleware({ children }) {
|
|
|
973
990
|
session
|
|
974
991
|
});
|
|
975
992
|
if (!isMounted) return;
|
|
976
|
-
|
|
993
|
+
const outcome = resolveMiddlewareOutcome(result);
|
|
994
|
+
if (outcome.kind === "allow") {
|
|
995
|
+
setDeniedStatus(null);
|
|
977
996
|
setAllowed(true);
|
|
978
|
-
} else if (
|
|
979
|
-
void navigate(
|
|
997
|
+
} else if (outcome.kind === "redirect") {
|
|
998
|
+
void navigate(outcome.to);
|
|
999
|
+
} else if (outcome.kind === "deny") {
|
|
1000
|
+
setDeniedStatus(outcome.status);
|
|
980
1001
|
} else {
|
|
981
1002
|
void navigate(getProjectConfig().loginRedirectUrl ?? "/");
|
|
982
1003
|
}
|
|
@@ -987,6 +1008,10 @@ function Middleware({ children }) {
|
|
|
987
1008
|
};
|
|
988
1009
|
}, [routeKey, location.pathname, location.search, navigate, session, sessionLoaded]);
|
|
989
1010
|
if (checking) return /* @__PURE__ */ jsx3(MiddlewareLoader, {});
|
|
1011
|
+
if (deniedStatus !== null) {
|
|
1012
|
+
const custom = typeof denied === "function" ? denied(deniedStatus) : denied;
|
|
1013
|
+
return /* @__PURE__ */ jsx3("div", { className: "w-full h-full", children: custom ?? /* @__PURE__ */ jsx3(MiddlewareDenied, { status: deniedStatus }) });
|
|
1014
|
+
}
|
|
990
1015
|
if (!allowed) return null;
|
|
991
1016
|
return /* @__PURE__ */ jsx3("div", { className: "w-full h-full", children });
|
|
992
1017
|
}
|
|
@@ -1010,11 +1035,12 @@ function useRouter() {
|
|
|
1010
1035
|
const pageMw = getPageMiddleware(path);
|
|
1011
1036
|
const handler = pageMw ?? getMiddlewareHandler();
|
|
1012
1037
|
const result = await handler({ location: path, searchParams: queryObject, session });
|
|
1013
|
-
|
|
1014
|
-
|
|
1038
|
+
const outcome = resolveMiddlewareOutcome(result);
|
|
1039
|
+
if (outcome.kind === "redirect") {
|
|
1040
|
+
return navigateHandler(outcome.to);
|
|
1015
1041
|
}
|
|
1016
|
-
if (
|
|
1017
|
-
return navigateHandler(
|
|
1042
|
+
if (outcome.kind === "allow" || outcome.kind === "deny") {
|
|
1043
|
+
return navigateHandler(path);
|
|
1018
1044
|
}
|
|
1019
1045
|
return;
|
|
1020
1046
|
};
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/apiInterceptors.ts","../src/tryCatchClient.ts","../src/routedHttpInvocation.ts","../src/apiRequest.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`.\n//?\n//? `apiRequest` (apiRequest.ts) is a monolithic typed function and Rule 21 /\n//? the `no-unsafe-api-wrappers` lint forbid wrapping it (a wrapper erases the\n//? route/version inference). This registry is the sanctioned escape hatch: a\n//? consumer registers an interceptor here instead of wrapping the call, so the\n//? typed call site is untouched and route/version inference survives.\n//?\n//? Two seams, both fire-and-mutate (NOT replace — the dispatcher reserves a\n//? structured return for control flow):\n//? - request interceptors run just before the socket emit. A handler may\n//? mutate `ctx.data` in place (inject a correlation id / feature-flag\n//? context / tenant header-equivalent) and is observation-only otherwise.\n//? - response interceptors run when the response envelope arrives, before the\n//? awaiting caller resolves. Observation-only (metrics, breadcrumb, custom\n//? logging). The envelope is NOT mutated by this seam — response rewriting\n//? belongs on the server `preApiRespond` / `transformApiResponse` hooks.\n//?\n//? Handlers are best-effort: a throw / rejection is caught + logged and never\n//? breaks the request pipeline. Both `register*` functions return an\n//? unsubscribe closure, matching `registerClientHook`'s contract.\n\nexport interface ApiRequestInterceptorContext {\n /** Resolved route name (`<page>/<api>` or `system/<api>`). */\n name: string;\n /** Route version literal (e.g. `'v1'`). */\n version: string;\n /**\n * Outgoing request payload. Mutate this object in place to augment the\n * request (correlation id, feature-flag context, ...). Replacing the\n * reference has no effect — mutate keys on the existing object.\n */\n data: Record<string, unknown>;\n}\n\nexport interface ApiResponseInterceptorContext {\n name: string;\n version: string;\n /** The response envelope the caller is about to receive (read-only intent). */\n response: { status: 'success' | 'error'; [key: string]: unknown };\n}\n\nexport type ApiRequestInterceptor = (\n ctx: ApiRequestInterceptorContext,\n) => void | Promise<void>;\n\nexport type ApiResponseInterceptor = (\n ctx: ApiResponseInterceptorContext,\n) => void | Promise<void>;\n\nimport { getLogger } from './loggerRegistry';\n\nconst requestInterceptors = new Set<ApiRequestInterceptor>();\nconst responseInterceptors = new Set<ApiResponseInterceptor>();\n\n/**\n * Register an outgoing-request interceptor. Returns an unsubscribe function.\n * Multiple interceptors run in registration order; each may mutate `ctx.data`.\n */\nexport function registerApiRequestInterceptor(interceptor: ApiRequestInterceptor): () => void {\n requestInterceptors.add(interceptor);\n return () => {\n requestInterceptors.delete(interceptor);\n };\n}\n\n/**\n * Register an incoming-response interceptor. Returns an unsubscribe function.\n */\nexport function registerApiResponseInterceptor(interceptor: ApiResponseInterceptor): () => void {\n responseInterceptors.add(interceptor);\n return () => {\n responseInterceptors.delete(interceptor);\n };\n}\n\n//? Framework-internal — invoked by `apiRequest`. Awaited so a handler can do an\n//? async lookup (read a flag store, mint a trace id) before the emit. Snapshot\n//? the set so a handler unregistering mid-dispatch can't skip a sibling.\nexport async function dispatchApiRequestInterceptors(\n ctx: ApiRequestInterceptorContext,\n): Promise<void> {\n if (requestInterceptors.size === 0) return;\n //? Snapshot so a handler that unregisters itself (or a sibling) mid-dispatch\n //? doesn't skip an un-visited handler.\n const interceptors = [...requestInterceptors];\n for (const interceptor of interceptors) {\n try {\n await interceptor(ctx);\n } catch (error) {\n getLogger().error('[apiRequestInterceptor] handler threw', error);\n }\n }\n}\n\n//? Framework-internal — invoked by `apiRequest` when the response arrives.\n//? Fire-and-forget (the caller does not await) so an interceptor can't delay\n//? the resolve; async rejections are caught + logged.\nexport function dispatchApiResponseInterceptors(\n ctx: ApiResponseInterceptorContext,\n): void {\n if (responseInterceptors.size === 0) return;\n //? Snapshot (see `dispatchApiRequestInterceptors`).\n const interceptors = [...responseInterceptors];\n for (const interceptor of interceptors) {\n try {\n const result = interceptor(ctx);\n if (result && typeof (result as Promise<unknown>).catch === 'function') {\n (result as Promise<unknown>).catch((error: unknown) => {\n getLogger().error('[apiResponseInterceptor] async handler rejected', error);\n });\n }\n } catch (error) {\n getLogger().error('[apiResponseInterceptor] handler threw', error);\n }\n }\n}\n\n/** Test helper — drop every registered interceptor. Not part of the public API. */\nexport function _resetApiInterceptorsForTests(): void {\n requestInterceptors.clear();\n responseInterceptors.clear();\n}\n","//? Browser-safe sibling of `tryCatch`. Behaviourally identical (same tuple,\n//? same params, same auto-capture on the error path) but it does NOT statically\n//? import `./sentrySetup`. The server `tryCatch.ts` reaches `sentrySetup` →\n//? `errorTrackerRegistry` → `node:async_hooks` at module-eval; that static edge\n//? is harmless on the server but drags a `node:`-externalized module into the\n//? Vite CLIENT bundle whenever a client importer (LoginForm) pulls\n//? `shared/tryCatch.ts`. So the client-reachable shim resolves HERE instead, and\n//? the only path to capture is a LAZY dynamic import taken on the error branch —\n//? keeping the node-bearing module out of the client's static graph.\n//?\n//? The server's `tryCatch.ts` is intentionally left untouched (byte-for-byte) so\n//? the server capture path keeps its synchronous, statically-linked behaviour.\n//? On the client, capture is best-effort and async-via-microtask is fine.\n\nexport default async function tryCatch<T, P = void>(\n func: (values: P) => Promise<T> | T,\n params?: P,\n context?: Record<string, unknown>\n): Promise<[Error | null, T | null]> {\n try {\n const response = await func(params as P);\n return [null, response];\n } catch (error) {\n //? Lazy capture: the import is only evaluated on the error branch, so the\n //? `node:async_hooks`-bearing module never enters the client's static graph.\n const { captureException } = await import('./sentrySetup');\n captureException(error, context);\n return [error instanceof Error ? error : new Error(String(error)), null];\n }\n}\n","import { httpFetch } from './csrf';\nimport tryCatch from './tryCatchClient';\nimport tryCatchSync from './tryCatchSync';\nimport type { HttpMethodLiteral } from './apiMethodMapRegistry';\n\nexport type RoutedInvocationMethod = HttpMethodLiteral;\n\nexport interface RoutedInvocationResponse<TResponse> {\n kind: 'response';\n response: TResponse;\n httpStatus: number;\n}\n\nexport interface RoutedInvocationFailure {\n kind: 'aborted' | 'timeout' | 'network-error' | 'invalid-response';\n}\n\nexport type RoutedInvocationResult<TResponse> =\n | RoutedInvocationResponse<TResponse>\n | RoutedInvocationFailure;\n\nexport interface RoutedHttpInvocationInput<TStream> {\n path: string;\n method: RoutedInvocationMethod;\n data: Record<string, unknown>;\n stream?: (payload: TStream) => void;\n signals?: readonly (AbortSignal | null | undefined)[];\n timeoutMs?: number | false;\n}\n\ninterface ParsedSseEvent {\n event: string;\n data: unknown;\n}\n\nconst parseJson = (value: string): unknown => {\n const [error, parsed] = tryCatchSync(() => JSON.parse(value) as unknown);\n return error ? undefined : parsed;\n};\n\nconst parseSseFrame = (frame: string): ParsedSseEvent | null => {\n let event = 'message';\n const dataLines: string[] = [];\n for (const rawLine of frame.split('\\n')) {\n const line = rawLine.endsWith('\\r') ? rawLine.slice(0, -1) : rawLine;\n if (line.length === 0 || line.startsWith(':')) continue;\n if (line.startsWith('event:')) {\n event = line.slice(6).trimStart();\n continue;\n }\n if (line.startsWith('data:')) {\n dataLines.push(line.slice(5).trimStart());\n }\n }\n if (dataLines.length === 0) return null;\n return { event, data: parseJson(dataLines.join('\\n')) };\n};\n\nconst parseSseResponse = async <TResponse>(\n response: Response,\n onStream: ((payload: never) => void) | undefined,\n): Promise<TResponse | null> => {\n const reader = response.body?.getReader();\n if (!reader) return null;\n\n const decoder = new TextDecoder();\n let buffer = '';\n let finalResponse: TResponse | null = null;\n\n const consumeFrames = (flush: boolean): void => {\n buffer = buffer.replaceAll('\\r\\n', '\\n');\n let boundary = buffer.indexOf('\\n\\n');\n while (boundary !== -1) {\n const frame = buffer.slice(0, boundary);\n buffer = buffer.slice(boundary + 2);\n const parsed = parseSseFrame(frame);\n if (parsed?.event === 'stream' && parsed.data !== undefined) {\n onStream?.(parsed.data as never);\n } else if ((parsed?.event === 'final' || parsed?.event === 'error') && parsed.data !== undefined) {\n finalResponse = parsed.data as TResponse;\n }\n boundary = buffer.indexOf('\\n\\n');\n }\n\n if (flush && buffer.trim().length > 0) {\n const parsed = parseSseFrame(buffer);\n if (parsed?.event === 'stream' && parsed.data !== undefined) {\n onStream?.(parsed.data as never);\n } else if ((parsed?.event === 'final' || parsed?.event === 'error') && parsed.data !== undefined) {\n finalResponse = parsed.data as TResponse;\n }\n buffer = '';\n }\n };\n\n let readDone = false;\n while (!readDone) {\n const { done, value } = await reader.read();\n readDone = done;\n if (!done) {\n buffer += decoder.decode(value, { stream: true });\n consumeFrames(false);\n }\n }\n buffer += decoder.decode();\n consumeFrames(true);\n return finalResponse;\n};\n\nconst buildRequest = ({\n path,\n method,\n data,\n stream,\n signal,\n}: {\n path: string;\n method: RoutedInvocationMethod;\n data: Record<string, unknown>;\n stream: boolean;\n signal: AbortSignal;\n}): { url: string; init: RequestInit } => {\n const headers = new Headers();\n if (stream) headers.set('Accept', 'text/event-stream');\n\n if (method === 'GET') {\n const params = new URLSearchParams();\n params.set('__luckystack_data', JSON.stringify(data));\n if (stream) params.set('stream', 'true');\n const separator = path.includes('?') ? '&' : '?';\n return {\n url: `${path}${separator}${params.toString()}`,\n init: { method, headers, signal },\n };\n }\n\n headers.set('Content-Type', 'application/json');\n return {\n url: stream ? `${path}${path.includes('?') ? '&' : '?'}stream=true` : path,\n init: {\n method,\n headers,\n signal,\n body: JSON.stringify(data),\n },\n };\n};\n\nexport const invokeRoutedHttp = async <TResponse, TStream = Record<string, unknown>>({\n path,\n method,\n data,\n stream,\n signals = [],\n timeoutMs,\n}: RoutedHttpInvocationInput<TStream>): Promise<RoutedInvocationResult<TResponse>> => {\n if (signals.some((signal) => signal?.aborted)) return { kind: 'aborted' };\n\n const controller = new AbortController();\n const timeoutReason = Symbol('routed-invocation-timeout');\n const didTimeout = (): boolean => controller.signal.reason === timeoutReason;\n const abortFromCaller = (): void => {\n controller.abort();\n };\n for (const signal of signals) signal?.addEventListener('abort', abortFromCaller, { once: true });\n\n const timeout = typeof timeoutMs === 'number' && timeoutMs > 0\n ? setTimeout(() => {\n controller.abort(timeoutReason);\n }, timeoutMs)\n : null;\n\n const cleanup = (): void => {\n if (timeout) clearTimeout(timeout);\n for (const signal of signals) signal?.removeEventListener('abort', abortFromCaller);\n };\n\n const request = buildRequest({\n path,\n method,\n data,\n stream: typeof stream === 'function',\n signal: controller.signal,\n });\n const [fetchError, response] = await tryCatch(() => httpFetch(request.url, request.init));\n if (fetchError || !response) {\n cleanup();\n if (didTimeout()) return { kind: 'timeout' };\n if (controller.signal.aborted) return { kind: 'aborted' };\n return { kind: 'network-error' };\n }\n\n const contentType = response.headers.get('content-type')?.toLowerCase() ?? '';\n const [parseError, parsed] = await tryCatch(async () => {\n if (contentType.includes('text/event-stream')) {\n return parseSseResponse<TResponse>(response, stream);\n }\n return (await response.json()) as TResponse;\n });\n cleanup();\n\n if (parseError || parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n if (didTimeout()) return { kind: 'timeout' };\n if (controller.signal.aborted) return { kind: 'aborted' };\n return { kind: 'invalid-response' };\n }\n\n return { kind: 'response', response: parsed, httpStatus: response.status };\n};\n","import { getProjectConfig } from \"./projectConfig\";\nimport { getLogger } from \"./loggerRegistry\";\nimport { getRegisteredApiMethod } from \"./apiMethodMapRegistry\";\nimport { inferHttpMethod, isGetMethodName } from \"./httpApiUtils\";\nimport { incrementResponseIndex, socket, waitForSocket } from \"./socketState\";\nimport type { ApiTypeMap, StreamPayload } from './apiTypeStubs';\nimport { notify } from \"./notifier\";\nimport { enqueueApiRequest, isOnline, removeApiQueueItem } from \"./offlineQueue\";\nimport { Socket } from \"socket.io-client\";\nimport { normalizeErrorResponseCore } from \"./responseNormalizer\";\nimport { parseServiceRouteName } from \"./serviceRoute\";\nimport tryCatchSync from \"./tryCatchSync\";\nimport {\n buildApiResponseEventName,\n buildApiStreamEventName,\n socketEventNames,\n} from \"./socketEvents\";\nimport {\n dispatchApiRequestInterceptors,\n dispatchApiResponseInterceptors,\n} from \"./apiInterceptors\";\nimport { invokeRoutedHttp } from './routedHttpInvocation';\n\n//? Abort controller logic:\n//? - abortable: true → always use abort controller\n//? - abortable: false → never use abort controller\n//? - abortable: undefined → use abort controller for GET APIs (from generated types)\n//? Keyed by `fullName` + a stable hash of the request `data` so the\n//? replace-previous (dedupe) semantics only fire for an IDENTICAL in-flight\n//? call. Two components polling the same GET route with DIFFERENT params no\n//? longer abort each other (each gets its own bucket); a genuine duplicate\n//? still supersedes the prior one.\n//? Size-capped at 1000 entries. All normal code paths (resolve, abort, disconnect,\n//? timeout) call `cleanupAbortController()` which deletes the entry. The cap\n//? is a safety net for edge cases where cleanup is skipped (socket torn down\n//? without a `disconnect` event, or a future code path that forgets to clean up).\nconst ABORT_CONTROLLERS_MAX = 1000;\nconst abortControllers = new Map<string, AbortController>();\n\n//? Stable, order-insensitive JSON stringify so `{a:1,b:2}` and `{b:2,a:1}`\n//? hash to the same abort-controller key. Falls back to a non-deduping unique\n//? token when the payload can't be serialised (circular ref), which is the\n//? safe choice — an unserialisable payload should never silently abort a\n//? sibling request.\nconst stableStringify = (value: unknown): string => {\n const seen = new WeakSet<object>();\n const walk = (input: unknown): unknown => {\n if (input === null || typeof input !== 'object') return input;\n if (seen.has(input)) return '[circular]';\n seen.add(input);\n if (Array.isArray(input)) return input.map((entry) => walk(entry));\n const record = input as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(record).toSorted()) {\n out[key] = walk(record[key]);\n }\n return out;\n };\n const [error, json] = tryCatchSync(() => JSON.stringify(walk(value)));\n if (error || typeof json !== 'string') {\n return `__unserializable__:${String(Date.now())}-${String(Math.random())}`;\n }\n return json;\n};\n\nconst buildAbortKey = (fullName: string, data: unknown): string =>\n `${fullName}::${stableStringify(data)}`;\n\nexport type ApiStreamEvent<T extends StreamPayload = StreamPayload> = T;\n\n/**\n * Check if an API is a GET method.\n *\n * Primary path: consult the registered `apiMethodMap` (generated from the\n * actual handler's `httpMethod` export or name-based inference at codegen\n * time). Falls back to name-prefix heuristic only when the map isn't\n * registered yet — typically because an older consumer wrapper has not called\n * `registerApiMethodMap(...)` from `src/_sockets/apiRequest.ts` before re-exporting this helper.\n */\nconst isGetMethodByPrefix = (apiName: string): boolean => isGetMethodName(apiName.toLowerCase());\n\ntype RoutedApiFailureKind = 'timeout' | 'aborted' | 'network-error' | 'invalid-response';\n\nconst routedApiErrorCode = (kind: RoutedApiFailureKind): string => {\n if (kind === 'timeout') return 'api.timeout';\n if (kind === 'aborted') return 'request.aborted';\n if (kind === 'invalid-response') return 'api.invalidServerResponse';\n return 'api.ioUnavailable';\n};\n\nexport const resolveApiRequestHttpMethod = (apiName: string, version: string) => {\n const lastSlash = apiName.lastIndexOf('/');\n if (lastSlash > 0) {\n const pagePath = apiName.slice(0, lastSlash);\n const leaf = apiName.slice(lastSlash + 1);\n const method = getRegisteredApiMethod(pagePath, leaf, version);\n if (method) return method;\n }\n return inferHttpMethod(apiName);\n};\n\nconst resolveGetMethod = (apiName: string, version: string): { isGet: boolean; usingHeuristic: boolean } => {\n //? Resolved-name shape: `pagePath/apiName`. apiMethodMap is nested by\n //? pagePath → apiName → version. Split at the last `/` so multi-segment\n //? page paths (e.g. 'admin/users') still resolve.\n const lastSlash = apiName.lastIndexOf('/');\n if (lastSlash > 0) {\n const pagePath = apiName.slice(0, lastSlash);\n const leaf = apiName.slice(lastSlash + 1);\n const method = getRegisteredApiMethod(pagePath, leaf, version);\n if (method) return { isGet: method === 'GET', usingHeuristic: false };\n }\n return { isGet: isGetMethodByPrefix(apiName), usingHeuristic: true };\n};\n\nconst canSendNow = (socketInstance: Socket) => {\n if (!socketInstance.connected) return false;\n return isOnline();\n};\n\nconst createQueueId = () => {\n return `${String(Date.now())}-${String(Math.random())}`;\n};\n\n//? Resolve logging flags at call time so registration order doesn't matter.\n//? `getLogging()` is called inside each handler instead of captured at load.\nconst getLogging = () => getProjectConfig().logging;\nconst shouldLogDev = () => getLogging().devLogs;\nconst shouldNotifyDev = () => getLogging().devNotifications;\nconst shouldLogStream = () => getLogging().stream;\n\nconst shouldUseAbortController = ({\n abortable,\n isGet,\n usingHeuristic,\n}: {\n abortable: boolean | undefined;\n isGet: boolean;\n usingHeuristic: boolean;\n}) => {\n if (abortable === true) return true;\n if (abortable === false) return false;\n //? CORE-O15: when `abortable` is unspecified and we are relying on the\n //? name-prefix heuristic (apiMethodMap not registered), default to\n //? non-abortable. A mis-named POST (e.g. `getReport`) would otherwise\n //? silently abort an identical in-flight call it has nothing to do with.\n //? Once `registerApiMethodMap` is called (normal boot), the generated map\n //? resolves the method and the heuristic path is never taken.\n if (usingHeuristic) return false;\n return isGet;\n};\n\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// Type Helpers\n// ═══════════════════════════════════════════════════════════════════════════════\n\n// Check if data input is required (i.e., T does NOT allow empty object)\n// Unions like {a:1} | {b:1} do NOT allow {}, so data will be required\ntype DataRequired<T> = Record<string, never> extends T ? false : true;\n\ntype UnionToIntersection<U> =\n (U extends unknown ? (arg: U) => void : never) extends ((arg: infer I) => void)\n ? I\n : never;\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// Global API Params - Union of ALL valid API calls with proper data enforcement\n// ═══════════════════════════════════════════════════════════════════════════════\ntype ApiRouteRecord = UnionToIntersection<{\n [P in keyof ApiTypeMap]: {\n [N in keyof ApiTypeMap[P] as P extends 'root'\n ? `system/${Extract<N, string>}`\n : `${Extract<P, string>}/${Extract<N, string>}`]: ApiTypeMap[P][N]\n }\n}[keyof ApiTypeMap]>;\n\ntype ApiFullName = Extract<keyof ApiRouteRecord, string>;\ntype VersionsForFullName<F extends ApiFullName> = keyof ApiRouteRecord[F] & string;\n\n// Force expansion of types to clear aliases in tooltips\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\n\n// Get input type for an API name (union if exists on multiple pages)\ntype InputForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = ApiRouteRecord[F][V] extends { input: infer I }\n ? I\n : never;\n\n// Get output type for an API name (union if exists on multiple pages)\ntype OutputForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = ApiRouteRecord[F][V] extends { output: infer O }\n ? O\n : never;\n\ntype StreamForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = ApiRouteRecord[F][V] extends { stream: infer S }\n ? S\n : never;\n\ntype ApiStreamCallbackForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> =\n [StreamForFullName<F, V>] extends [never]\n ? never\n : (event: ApiStreamEvent<Prettify<StreamForFullName<F, V> extends StreamPayload ? StreamForFullName<F, V> : StreamPayload>>) => void;\n\n// Build params type for a specific API name\ntype ApiParamsForFullName<\n F extends ApiFullName,\n V extends VersionsForFullName<F>\n> = DataRequired<InputForFullName<F, V>> extends true\n ? { name: F; version: V; data: Prettify<InputForFullName<F, V>>; abortable?: boolean; disableErrorMessage?: boolean; onStream?: ApiStreamCallbackForFullName<F, V>; signal?: AbortSignal; timeoutMs?: number | false; }\n : { name: F; version: V; data?: Prettify<InputForFullName<F, V>>; abortable?: boolean; disableErrorMessage?: boolean; onStream?: ApiStreamCallbackForFullName<F, V>; signal?: AbortSignal; timeoutMs?: number | false; };\n\ninterface RuntimeApiParams {\n name?: string;\n version?: string;\n data?: unknown;\n abortable?: boolean;\n disableErrorMessage?: boolean;\n onStream?: (event: ApiStreamEvent) => void;\n signal?: AbortSignal;\n /** Per-call response timeout (ms). Overrides `api.requestTimeoutMs`. `false` disables. */\n timeoutMs?: number | false;\n}\n\nexport interface ApiErrorResponse extends Record<string, unknown> {\n status: 'error';\n httpStatus: number;\n message: string;\n errorCode: string;\n errorParams?: { key: string; value: string | number | boolean }[];\n}\n\ninterface ApiSuccessResponse extends Record<string, unknown> {\n status: 'success';\n httpStatus: number;\n}\n\ntype ApiResponse = ApiErrorResponse | ApiSuccessResponse;\n\nconst normalizeApiError = ({\n response,\n fallbackErrorCode,\n fallbackHttpStatus = 500,\n}: {\n response: { status: 'error'; errorCode?: string; errorParams?: { key: string; value: string | number | boolean }[]; httpStatus?: number; message?: string };\n fallbackErrorCode: string;\n fallbackHttpStatus?: number;\n}): ApiErrorResponse => {\n const normalized = normalizeErrorResponseCore({\n response,\n fallbackErrorCode,\n fallbackHttpStatus,\n resolveMessage: ({ errorCode }) => {\n if (typeof response.message === 'string' && response.message.trim().length > 0) {\n return response.message;\n }\n return errorCode;\n },\n });\n\n return {\n status: 'error',\n message: normalized.message,\n errorCode: normalized.errorCode,\n errorParams: normalized.errorParams,\n httpStatus: normalized.httpStatus ?? fallbackHttpStatus,\n };\n};\n\n/**\n * Type-safe API request function.\n * \n * @example\n * ```typescript\n * // Full name usage - includes page in the name\n * const result = await apiRequest({ name: 'examples/publicApi', version: 'v1', data: { message: 'hello' } });\n * // result is typed correctly for publicApi\n * \n * // Global APIs use service-first naming\n * await apiRequest({ name: 'system/session', version: 'v1' });\n * ```\n */\n\nexport function apiRequest<F extends ApiFullName, V extends VersionsForFullName<F>>(\n params: ApiParamsForFullName<F, V>\n): Promise<Prettify<OutputForFullName<F, V>> | ApiErrorResponse> {\n type RequestOutput = Prettify<OutputForFullName<F, V> & ApiResponse>;\n const runtimeParams = params as RuntimeApiParams;\n const { name, version, disableErrorMessage = false, onStream, signal: externalSignal, timeoutMs } = runtimeParams;\n const payloadData = runtimeParams.data;\n\n return new Promise<RequestOutput>((resolve) => {\n void (async () => {\n //? B1 — if the consumer-supplied signal is already aborted at call\n //? time, short-circuit before we even touch the socket. Mirrors the\n //? `fetch(url, { signal })` contract.\n if (externalSignal?.aborted) {\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'request.aborted' },\n fallbackErrorCode: 'request.aborted',\n }) as RequestOutput);\n return;\n }\n if (!name || typeof name !== \"string\") {\n if (shouldLogDev()) {\n getLogger().error(\"apiRequest: Invalid name\");\n }\n if (shouldNotifyDev()) {\n notify.error({ key: 'api.invalidName' });\n }\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'api.invalidName' },\n fallbackErrorCode: 'api.invalidName',\n }) as RequestOutput);\n return;\n }\n\n if (!version || typeof version !== 'string') {\n if (shouldLogDev()) {\n getLogger().error(\"apiRequest: Invalid version\");\n }\n if (shouldNotifyDev()) {\n notify.error({ key: 'api.invalidVersion' });\n }\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'api.invalidVersion' },\n fallbackErrorCode: 'api.invalidVersion',\n }) as RequestOutput);\n return;\n }\n\n const parsedRoute = parseServiceRouteName(name);\n if (parsedRoute.status === 'error') {\n if (shouldLogDev()) {\n getLogger().error(`[apiRequest] Invalid service route name`, undefined, { name, reason: parsedRoute.reason });\n }\n if (shouldNotifyDev()) {\n notify.error({ key: 'routing.invalidServiceRouteName' });\n }\n resolve(normalizeErrorResponseCore({\n response: {\n status: 'error',\n errorCode: 'routing.invalidServiceRouteName',\n errorParams: [{ key: 'name', value: name }],\n },\n fallbackErrorCode: 'routing.invalidServiceRouteName',\n }) as RequestOutput);\n return;\n }\n\n const sanitizedName = parsedRoute.normalizedRouteName;\n\n const data = payloadData && typeof payloadData === \"object\" ? payloadData : {};\n\n if (!await waitForSocket()) {\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'api.ioUnavailable' },\n fallbackErrorCode: 'api.ioUnavailable',\n }) as RequestOutput);\n return;\n }\n if (!socket) {\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'api.ioUnavailable' },\n fallbackErrorCode: 'api.ioUnavailable',\n }) as RequestOutput);\n return;\n }\n\n //? Abort controller logic:\n //? - abortable: true → always use abort controller\n //? - abortable: false → never use abort controller\n //? - abortable: undefined → smart default (GET-like APIs get abort controller)\n //? Pass the full pagePath/apiName so the registry lookup can resolve via\n //? the generated apiMethodMap (falls back to the leaf-name prefix heuristic\n //? when the map isn't registered yet).\n const { isGet, usingHeuristic } = resolveGetMethod(sanitizedName, version);\n const useAbortController = shouldUseAbortController({\n abortable: runtimeParams.abortable,\n isGet,\n usingHeuristic,\n });\n const fullName = `api/${sanitizedName}/${version}`;\n //? Per-payload abort key: only an identical in-flight call to the same\n //? route supersedes the previous one (see `buildAbortKey` rationale).\n const abortKey = buildAbortKey(fullName, data);\n\n let signal: AbortSignal | null = null;\n let abortHandler: (() => void) | null = null;\n let queueId: string | null = null;\n let cleanupStreamListener: (() => void) | null = null;\n //? Response listener cleanup, registered once the `.once` handler is\n //? attached in `runRequest`. Lets the abort path proactively `off()` the\n //? lingering response listener instead of waiting for a response that was\n //? cancelled and will never arrive.\n let cleanupResponseListener: (() => void) | null = null;\n //? Response-timeout timer. Armed right after the request is emitted so a\n //? lost response (server restart/crash between emit and reply) settles the\n //? promise instead of hanging the awaiting caller forever.\n let responseTimeout: ReturnType<typeof setTimeout> | null = null;\n const clearResponseTimeout = () => {\n if (responseTimeout) {\n clearTimeout(responseTimeout);\n responseTimeout = null;\n }\n };\n\n const cleanupAbortController = () => {\n if (signal && abortHandler) {\n signal.removeEventListener(\"abort\", abortHandler);\n }\n abortControllers.delete(abortKey);\n };\n\n if (useAbortController) {\n if (abortControllers.has(abortKey)) {\n const prevAbortController = abortControllers.get(abortKey);\n prevAbortController?.abort();\n }\n //? Evict the oldest entry when the cap is reached (LRU-insert-order).\n //? Map preserves insertion order; the first key is the oldest in-flight entry.\n if (!abortControllers.has(abortKey) && abortControllers.size >= ABORT_CONTROLLERS_MAX) {\n const oldest = abortControllers.keys().next().value;\n if (oldest !== undefined) abortControllers.delete(oldest);\n }\n const abortController = new AbortController();\n abortControllers.set(abortKey, abortController);\n signal = abortController.signal;\n\n abortHandler = () => {\n clearResponseTimeout();\n cleanupStreamListener?.();\n cleanupStreamListener = null;\n cleanupResponseListener?.();\n cleanupResponseListener = null;\n cleanupAbortController();\n if (queueId) {\n removeApiQueueItem(queueId);\n }\n //? Resolve (not reject) with the same `request.aborted` envelope the\n //? external-signal abort path uses. Rejecting here produced an\n //? unhandled rejection for fire-and-forget GET calls that get\n //? superseded by the default replace-previous behaviour.\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'request.aborted' },\n fallbackErrorCode: 'request.aborted',\n }) as RequestOutput);\n };\n\n signal.addEventListener(\"abort\", abortHandler);\n }\n\n const runRequest = (socketInstance: Socket) => {\n if (!canSendNow(socketInstance)) {\n queueId ??= createQueueId();\n //? For the immediate reject-new path (`drop-newest` / `reject`\n //? policy) THIS item's `onDrop` fires SYNCHRONOUSLY inside\n //? `enqueueApiRequest`. We keep surfacing that as the historical\n //? `offline.queueFull` via the `!enqueued` branch, so suppress the\n //? `onDrop` resolve during the synchronous enqueue window and re-arm\n //? it only if the item was actually queued (so a LATER async eviction\n //? — drop-oldest by a future enqueue, or age expiry — still settles).\n let suppressOnDrop = true;\n //? `enqueueApiRequest` returns `false` when the offline queue is\n //? full and `dropPolicy: 'reject'` is active. Without honoring\n //? that signal the outer promise never settles and the caller\n //? awaits forever. Resolve with a normalized error envelope so\n //? callers can branch.\n const enqueued = enqueueApiRequest({\n id: queueId,\n key: fullName,\n run: (nextSocket) => {\n runRequest(nextSocket);\n },\n createdAt: Date.now(),\n //? CORE: mirror SYNC-09. Settle the awaiting caller when this\n //? QUEUED request is later EVICTED (drop-oldest by a future\n //? enqueue / age expiry) instead of ever running. Without it the\n //? promise hangs forever, since `run` is the only thing that could\n //? otherwise resolve it — `apiRequest` had drifted from the sibling\n //? `syncRequest` which already had this fix. Also tear down the\n //? abort-controller registry entry so it isn't leaked.\n onDrop: (reason) => {\n if (suppressOnDrop) return;\n cleanupAbortController();\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'offline.dropped', errorParams: [{ key: 'reason', value: reason }] },\n fallbackErrorCode: 'offline.dropped',\n }) as RequestOutput);\n },\n });\n //? Past the synchronous enqueue window: if the item is sitting in the\n //? queue, a future eviction should settle via `onDrop`.\n suppressOnDrop = false;\n if (!enqueued) {\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'offline.queueFull', httpStatus: 503 },\n fallbackErrorCode: 'offline.queueFull',\n fallbackHttpStatus: 503,\n }) as RequestOutput);\n } else if (externalSignal && queueId) {\n //? CORE-O14: if an external AbortSignal fires while the item is\n //? sitting in the offline queue, its listener inside runRequest has\n //? not been registered yet. Register a one-shot handler here so the\n //? abort is not silently ignored and the queue slot is reclaimed.\n const capturedQueueId = queueId;\n const queueAbortHandler = () => {\n removeApiQueueItem(capturedQueueId);\n cleanupAbortController();\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'request.aborted' },\n fallbackErrorCode: 'request.aborted',\n }) as RequestOutput);\n };\n externalSignal.addEventListener('abort', queueAbortHandler, { once: true });\n }\n return;\n }\n\n if (signal?.aborted) {\n return;\n }\n\n if (getProjectConfig().transport.invocation === 'routed-http') {\n void (async () => {\n const effectiveTimeoutMs = timeoutMs ?? getProjectConfig().api.requestTimeoutMs;\n const routed = await invokeRoutedHttp<ApiResponse, ApiStreamEvent>({\n path: `/api/${sanitizedName}/${version}`,\n method: resolveApiRequestHttpMethod(sanitizedName, version),\n data: data as Record<string, unknown>,\n stream: onStream,\n signals: [signal, externalSignal],\n timeoutMs: effectiveTimeoutMs,\n });\n cleanupAbortController();\n if (queueId) removeApiQueueItem(queueId);\n\n if (routed.kind !== 'response') {\n const errorCode = routedApiErrorCode(routed.kind);\n resolve(normalizeApiError({\n response: {\n status: 'error',\n errorCode,\n httpStatus: routed.kind === 'timeout' ? 504 : undefined,\n },\n fallbackErrorCode: errorCode,\n fallbackHttpStatus: routed.kind === 'timeout' ? 504 : 500,\n }) as RequestOutput);\n return;\n }\n\n const response = routed.response;\n dispatchApiResponseInterceptors({ name: sanitizedName, version, response });\n if (response.status === 'error') {\n const normalizedError = normalizeErrorResponseCore({ response });\n if (!disableErrorMessage) {\n notify.error({\n key: normalizedError.errorCode || normalizedError.message,\n params: normalizedError.errorParams,\n });\n }\n Object.assign(response, normalizedError);\n }\n resolve(response as RequestOutput);\n })();\n return;\n }\n\n const tempIndex = incrementResponseIndex();\n socketInstance.emit(socketEventNames.apiRequest, { name: fullName, data, responseIndex: tempIndex });\n\n //? B1 — bridge the consumer's AbortSignal to the server. When the\n //? signal fires we emit `apiCancel { responseIndex }` so the server\n //? handler stops emitting new chunks. We also resolve locally with\n //? `request.aborted` so the awaiting caller settles (vs awaiting\n //? a response that will never arrive because we cancelled it).\n let cleanupExternalAbort: (() => void) | null = null;\n if (externalSignal) {\n const externalAbortHandler = () => {\n clearResponseTimeout();\n socketInstance.emit(socketEventNames.apiCancel, { responseIndex: tempIndex });\n cleanupStreamListener?.();\n cleanupStreamListener = null;\n cleanupResponseListener?.();\n cleanupResponseListener = null;\n cleanupAbortController();\n cleanupExternalAbort?.();\n cleanupExternalAbort = null;\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'request.aborted' },\n fallbackErrorCode: 'request.aborted',\n }) as RequestOutput);\n };\n externalSignal.addEventListener('abort', externalAbortHandler);\n cleanupExternalAbort = () => {\n externalSignal.removeEventListener('abort', externalAbortHandler);\n };\n }\n\n //? Arm the response timeout. A per-call `timeoutMs` overrides the\n //? `api.requestTimeoutMs` config default; either may be `false` to\n //? disable. On expiry we tear down every listener/controller and settle\n //? with a 504 envelope so the awaiting caller never hangs.\n clearResponseTimeout();\n const effectiveTimeoutMs = timeoutMs ?? getProjectConfig().api.requestTimeoutMs;\n if (typeof effectiveTimeoutMs === 'number' && effectiveTimeoutMs > 0) {\n responseTimeout = setTimeout(() => {\n responseTimeout = null;\n cleanupStreamListener?.();\n cleanupStreamListener = null;\n cleanupResponseListener?.();\n cleanupResponseListener = null;\n cleanupExternalAbort?.();\n cleanupExternalAbort = null;\n cleanupAbortController();\n if (queueId) {\n removeApiQueueItem(queueId);\n }\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'api.timeout', httpStatus: 504 },\n fallbackErrorCode: 'api.timeout',\n fallbackHttpStatus: 504,\n }) as RequestOutput);\n }, effectiveTimeoutMs);\n }\n\n if (typeof onStream === 'function') {\n const streamEventName = buildApiStreamEventName(tempIndex);\n const streamListener = (streamPayload: ApiStreamEvent) => {\n if (signal?.aborted) {\n return;\n }\n\n if (shouldLogStream()) {\n getLogger().debug(`Server API Stream(${String(tempIndex)})`, { APINAME: sanitizedName, streamPayload });\n }\n\n onStream(streamPayload);\n };\n\n socketInstance.on(streamEventName, streamListener);\n cleanupStreamListener = () => {\n socketInstance.off(streamEventName, streamListener);\n };\n }\n\n if (shouldLogDev()) {\n getLogger().debug(`Client API Request(${String(tempIndex)})`, { APINAME: sanitizedName, data });\n }\n\n //? Inside the handler we type as the runtime envelope (ApiResponse).\n //? Project-specific output narrowing only matters at the call site,\n //? where `RequestOutput = OutputForFullName<F,V> & ApiResponse` is\n //? returned via `resolve(... as RequestOutput)`. When core is type-\n //? checked in isolation (e.g. per-package tsup dts build), ApiTypeMap\n //? is empty so OutputForFullName collapses to never; using ApiResponse\n //? here keeps the body type-safe in both cases.\n const responseEventName = buildApiResponseEventName(tempIndex);\n const responseListener = (response: ApiResponse) => {\n if (signal?.aborted) {\n clearResponseTimeout();\n cleanupExternalAbort?.();\n cleanupExternalAbort = null;\n return;\n }\n\n clearResponseTimeout();\n cleanupStreamListener?.();\n cleanupStreamListener = null;\n cleanupExternalAbort?.();\n cleanupExternalAbort = null;\n //? Call cleanup (not just null) so that any watcher layered on top of\n //? cleanupResponseListener (e.g. the CORE-O13 disconnect watcher) is\n //? properly torn down when a normal response arrives.\n cleanupResponseListener?.();\n cleanupResponseListener = null;\n\n const status = response.status;\n\n //? EXT-03 — fire client response interceptors when the envelope\n //? arrives (observation-only: metrics, breadcrumb, custom logging).\n dispatchApiResponseInterceptors({ name: sanitizedName, version, response });\n\n if (shouldLogDev()) {\n getLogger().debug(`Server API Response(${String(tempIndex)})`, { ...response, APINAME: sanitizedName });\n }\n\n if (status === \"error\") {\n const normalizedError = normalizeErrorResponseCore({ response });\n\n if (!disableErrorMessage) {\n if (normalizedError.errorCode) {\n notify.error({ key: normalizedError.errorCode, params: normalizedError.errorParams });\n } else {\n notify.error({ key: normalizedError.message });\n }\n }\n\n Object.assign(response, normalizedError);\n cleanupAbortController();\n resolve(response as RequestOutput);\n return;\n }\n\n cleanupAbortController();\n\n resolve(response as RequestOutput);\n };\n\n socketInstance.once(responseEventName, responseListener);\n cleanupResponseListener = () => {\n socketInstance.off(responseEventName, responseListener);\n };\n\n //? CORE-O13: when timeout is disabled AND there is no abort controller\n //? a server restart between emit and reply leaves this promise pending\n //? forever, leaking the response listener. The disconnect event is the\n //? authoritative signal that no reply will ever arrive on this socket.\n const disconnectHandler = () => {\n if (cleanupResponseListener) {\n cleanupResponseListener();\n cleanupResponseListener = null;\n }\n cleanupStreamListener?.();\n cleanupStreamListener = null;\n cleanupExternalAbort?.();\n cleanupExternalAbort = null;\n clearResponseTimeout();\n cleanupAbortController();\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'api.disconnected' },\n fallbackErrorCode: 'api.disconnected',\n }) as RequestOutput);\n };\n socketInstance.once('disconnect', disconnectHandler);\n //? Wrap the response listener to also remove the disconnect watcher on\n //? a normal reply (avoids a dangling listener on every successful call).\n const originalCleanupResponseListener = cleanupResponseListener;\n cleanupResponseListener = () => {\n socketInstance.off('disconnect', disconnectHandler);\n originalCleanupResponseListener();\n };\n };\n\n //? EXT-03 — fire client request interceptors just before the emit. They\n //? may mutate `data` in place (correlation id / feature-flag context).\n //? `data` is the same reference passed to `socketInstance.emit`, so the\n //? mutation is on the wire. Awaited so an async interceptor (flag lookup,\n //? trace-id mint) completes first; failures are caught + logged inside.\n await dispatchApiRequestInterceptors({\n name: sanitizedName,\n version,\n data: data as Record<string, unknown>,\n });\n\n //? CORE-O12: re-check the external abort signal after the interceptor\n //? await. A slow async interceptor adds uncounted latency; if the caller\n //? aborted during that window the signal is already fired but nothing has\n //? yet attached its listener (that happens inside runRequest). Settling\n //? here avoids emitting a request whose response will never be consumed.\n if (externalSignal?.aborted) {\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'request.aborted' },\n fallbackErrorCode: 'request.aborted',\n }) as RequestOutput);\n return;\n }\n\n runRequest(socket);\n })();\n });\n}","//? Locales registry — lets the framework's TranslationProvider + notify\n//? read the consumer's translation JSON files without baking them into the\n//? package. Consumer overlay: `luckystack/i18n/locales.ts` calls\n//? `registerLocales({ en: enJson, nl: nlJson, ... })`.\n//?\n//? Language source: a separate registry — `registerLanguageSource(fn)` —\n//? lets the consumer wire up where the active language comes from\n//? (typically the SessionProvider's current `session.language`). When no\n//? source is registered, the framework falls back to\n//? `getProjectConfig().defaultLanguage`.\n\nimport { getProjectConfig } from './projectConfig';\n\nexport type LocalesMap = Record<string, unknown>;\nexport type LanguageSource = () => string | null | undefined;\n\nlet activeLocales: LocalesMap = {};\nlet activeLanguageSource: LanguageSource | null = null;\n\nexport const registerLocales = (locales: LocalesMap): void => {\n activeLocales = locales;\n};\n\nexport const getRegisteredLocales = (): LocalesMap => activeLocales;\n\nexport const getDefaultLocale = (): string => getProjectConfig().defaultLanguage || 'en';\n\nexport const registerLanguageSource = (fn: LanguageSource): void => {\n activeLanguageSource = fn;\n};\n\nexport const getActiveLanguage = (): string => {\n if (activeLanguageSource) {\n const lang = activeLanguageSource();\n if (typeof lang === 'string' && lang.length > 0) return lang;\n }\n return getDefaultLocale();\n};\n\n//? Lookup a language's translation tree by code. Falls back to default\n//? language when the code isn't registered. Used by TranslationProvider\n//? + notify to resolve the active translations.\nexport const getLocaleByCode = (code: string): unknown => {\n if (code in activeLocales) return activeLocales[code];\n const fallback = getDefaultLocale();\n if (fallback in activeLocales) return activeLocales[fallback];\n return {};\n};\n","//? Middleware handler registry. The framework's `Middleware` + `Router`\n//? components (in `./react/`) call the registered handler on every\n//? navigation change to decide whether the user is allowed on the target\n//? route. Per-page `export const middleware` (see `registerPageMiddleware`\n//? below) is the canonical path; a consumer wanting a cross-cutting GLOBAL\n//? guard registers it from the client bootstrap (typically `main.tsx`) via\n//? `registerMiddlewareHandler(...)`. No separate\n//? `src/_functions/middlewareHandler.ts` file is required.\n\nimport type { BaseSessionLayout } from './sessionTypes';\n\nexport interface MiddlewareInput {\n location: string;\n searchParams: Record<string, string>;\n session: BaseSessionLayout | null;\n}\n\nexport type MiddlewareResult =\n | { success: true; redirect?: undefined }\n | { success: false; redirect: string }\n | undefined;\n\nexport type MiddlewareHandler = (input: MiddlewareInput) => MiddlewareResult | Promise<MiddlewareResult>;\n\n//? Default handler: allow by default. Per-page `middleware` exports on each\n//? `page.tsx` are the canonical route-guard path (see `registerPageMiddleware`\n//? below); the global handler is only consulted as a fallback for pages\n//? that don't declare their own guard. Allowing-by-default keeps public\n//? routes (`/`, `/login`, `/register`, ...) working without forcing every\n//? consumer to ship a `src/_functions/middlewareHandler.ts` boilerplate\n//? file just to opt-in to \"let the user through\".\n//?\n//? Consumers who need a cross-cutting global guard (telemetry, server-\n//? reachability check, maintenance banner gate) call\n//? `registerMiddlewareHandler(...)` directly from `main.tsx` with their own\n//? function — no separate file required.\nconst DEFAULT_HANDLER: MiddlewareHandler = () => ({ success: true });\n\nlet activeHandler: MiddlewareHandler = DEFAULT_HANDLER;\n\nexport const registerMiddlewareHandler = (handler: MiddlewareHandler): void => {\n activeHandler = handler;\n};\n\nexport const getMiddlewareHandler = (): MiddlewareHandler => activeHandler;\n\n//? Per-page middleware registry. Counterpart to `registerMiddlewareHandler`\n//? for the common case where each page declares its own guard locally\n//? (`export const middleware = ({ session }) => {...}` from page.tsx).\n//? The framework's `<Middleware>` component checks this map FIRST and only\n//? falls back to the global handler when no per-page entry is registered.\n//?\n//? `PageMiddleware<TSession>` matches the existing `MiddlewareHandler`\n//? signature so any handler shape is reusable on either side. The generic\n//? is purely ergonomic for consumer-side type narrowing — module\n//? augmentation of `BaseSessionLayout` flows through.\n\nexport type PageMiddleware<TSession extends BaseSessionLayout = BaseSessionLayout> = (\n input: { location: string; searchParams: Record<string, string>; session: TSession | null },\n) => MiddlewareResult | Promise<MiddlewareResult>;\n\nconst pageMiddlewares = new Map<string, PageMiddleware>();\n\nexport const registerPageMiddleware = (path: string, middleware: PageMiddleware): void => {\n pageMiddlewares.set(path, middleware);\n};\n\nexport const getPageMiddleware = (path: string): PageMiddleware | undefined =>\n pageMiddlewares.get(path);\n\nexport const hasPageMiddleware = (path: string): boolean => pageMiddlewares.has(path);\n\n/** Test helper — drop every registered per-page middleware. */\nexport const clearPageMiddlewaresForTests = (): void => {\n pageMiddlewares.clear();\n};\n","//? Shared session context. Defined in core so framework-React components\n//? (Middleware, Router, useSession-aware UI) can consume it without\n//? pulling in app code. The consumer's `SessionProvider` (in their\n//? template's `_providers/`) does the actual fetch/socket/lifecycle work\n//? and writes to this context via `<SessionContext value={...}>`.\n//?\n//? The session shape inside the context is intentionally loose\n//? (`BaseSessionLayout | null`) so app code with extended session types\n//? can read it through a typed `useSession<MySession>()` cast.\n\nimport { createContext, use } from 'react';\nimport type { BaseSessionLayout } from '../sessionTypes';\nimport {\n dispatchClientHook,\n dispatchVetoableClientHook,\n type ClientHookStopSignal,\n} from '../clientHookBus';\n\nexport interface SessionContextValue<TSession extends BaseSessionLayout = BaseSessionLayout> {\n session: TSession | null;\n sessionLoaded: boolean;\n}\n\nconst DEFAULT_VALUE: SessionContextValue = {\n session: null,\n sessionLoaded: false,\n};\n\nexport const SessionContext = createContext<SessionContextValue>(DEFAULT_VALUE);\n\nexport function useSession<TSession extends BaseSessionLayout = BaseSessionLayout>(): SessionContextValue<TSession> {\n return use(SessionContext) as SessionContextValue<TSession>;\n}\n\n//? Non-React accessor for code that runs outside the component tree\n//? (e.g. notify() called from a non-component). Kept in sync with the\n//? context by the consumer's SessionProvider via `setLatestSession()`.\nlet latestSession: BaseSessionLayout | null = null;\n\nexport const setLatestSession = (session: BaseSessionLayout | null): void => {\n const previous = latestSession;\n latestSession = session;\n\n //? Fire client-side lifecycle hooks on null↔non-null transitions. Covers\n //? both fresh login AND existing-session restore on page reload — both\n //? cases need the same downstream actions (room auto-join, analytics\n //? identify, etc). Same-id updates (avatar refresh, profile change) do\n //? NOT fire postLogin; if a `sessionUpdate` hook is needed later, add it\n //? as a third branch without breaking existing handlers.\n if (previous === null && session !== null) {\n dispatchClientHook('postLogin', { session });\n } else if (previous !== null && session === null) {\n dispatchClientHook('postLogout', { previousSession: previous });\n }\n};\n\n//? Caller-supplied `TSession` is used to narrow the return type at the\n//? callsite (consumers extend `BaseSessionLayout`). The lint rule sees it as\n//? \"used once\" but the parameter exists solely to surface the consumer's\n//? widened session type through the read API.\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- callsite-narrowing use\nexport const getCurrentSession = <TSession extends BaseSessionLayout = BaseSessionLayout>(): TSession | null =>\n latestSession as TSession | null;\n\n/**\n * Vetoable entry point for committing a null → session transition (i.e. a\n * fresh login or a page-load session restore). Dispatches the `preLogin`\n * client hook to every registered handler in parallel; if any returns a\n * stop signal, the transition is aborted and `{ committed: false, signal }`\n * is returned. Otherwise, `setLatestSession(session)` runs synchronously\n * (which fires `postLogin`) and `{ committed: true }` comes back.\n *\n * Consumer's `SessionProvider` should `await` this for non-null session\n * commits and roll local React state back to `null` when a veto comes\n * through, so the UI doesn't render a half-logged-in state.\n */\nexport type ProposeLoginResult =\n | { stopped: false; committed: true }\n | { stopped: true; signal: ClientHookStopSignal; committed: false };\n\nexport const proposeLogin = async (\n session: BaseSessionLayout,\n): Promise<ProposeLoginResult> => {\n const veto = await dispatchVetoableClientHook('preLogin', { candidateSession: session });\n if (veto.stopped) return { stopped: true, signal: veto.signal, committed: false };\n setLatestSession(session);\n return { stopped: false, committed: true };\n};\n","/* eslint-disable react-refresh/only-export-components */\nimport { createContext, use, useState, useMemo, useCallback, ReactNode } from 'react';\n\nexport type AvatarStatus = 'avatar' | 'fallback';\n\ninterface AvatarContextType {\n avatarStatuses: Record<string, AvatarStatus>;\n setAvatarStatus: (key: string, status: AvatarStatus) => void;\n}\n\nconst AvatarContext = createContext<AvatarContextType | null>(null);\n\nexport const AvatarProvider = ({ children }: { children: ReactNode }) => {\n const [avatarStatuses, setAvatarStatuses] = useState<Record<string, AvatarStatus>>({});\n\n const setAvatarStatus = useCallback((key: string, status: AvatarStatus) => {\n setAvatarStatuses(prev => ({ ...prev, [key]: status }));\n }, []);\n\n const contextValue = useMemo(() => ({\n avatarStatuses,\n setAvatarStatus,\n }), [avatarStatuses, setAvatarStatus]);\n\n return (\n <AvatarContext value={contextValue}>\n {children}\n </AvatarContext>\n );\n};\n\nexport function useAvatarContext() {\n const ctx = use(AvatarContext);\n if (!ctx) throw new Error('useAvatarContext must be used within AvatarProvider');\n return ctx;\n}\n","//? `useTheme()` — framework-owned theme state hook. Default value comes\n//? from `getProjectConfig().defaultTheme` (the union literal exported by\n//? the consumer's `config.ts`). Toggling sets the `.dark` class on\n//? `<html>`. Persistence (e.g. saving to `User.theme` via\n//? `settings/updateUser`) is up to the consumer — the hook only owns\n//? local state + DOM class.\n\nimport { useState, useCallback } from 'react';\nimport { getProjectConfig } from '../projectConfig';\n\nexport type Theme = 'light' | 'dark';\n\nconst applyDomClass = (theme: Theme): void => {\n if (typeof document === 'undefined') return;\n document.documentElement.classList.toggle('dark', theme === 'dark');\n};\n\nexport const useTheme = () => {\n const initialTheme = (getProjectConfig().defaultTheme) ?? 'light';\n const [theme, setThemeState] = useState<Theme>(initialTheme);\n\n const setTheme = useCallback((next: Theme) => {\n setThemeState(next);\n applyDomClass(next);\n }, []);\n\n return { theme, setTheme };\n};\n","/* eslint-disable react-refresh/only-export-components */\n//? Framework-owned translation provider. Reads the registered locales map\n//? (consumer registers via `registerLocales({...})` in their overlay) and\n//? the active language source (consumer registers via\n//? `registerLanguageSource(fn)`, typically `() => session?.language`).\n//? Default language falls back to `getProjectConfig().defaultLanguage`.\n\nimport { createContext, ReactNode, use, useEffect, useMemo, useState, Dispatch, SetStateAction } from 'react';\nimport {\n getActiveLanguage,\n getDefaultLocale,\n getLocaleByCode,\n getRegisteredLocales,\n} from '../localesRegistry';\n\nexport type TranslationRecord = Record<string, unknown>;\n\ninterface TranslationContextValue {\n translations: TranslationRecord;\n setLanguage: Dispatch<SetStateAction<string>>;\n}\n\nconst TranslationContext = createContext<TranslationContextValue | null>(null);\n\nconst resolveTranslations = (code: string): TranslationRecord => {\n const value = getLocaleByCode(code);\n if (value && typeof value === 'object') return value as TranslationRecord;\n return {};\n};\n\nexport function TranslationProvider({ children }: { children: ReactNode }) {\n const [language, setLanguage] = useState<string>(() => getActiveLanguage());\n const translations = useMemo(() => resolveTranslations(language), [language]);\n\n //? Poll the registered language source so changes to session.language\n //? (or whatever the consumer wired) flip the active language without a\n //? full remount. Cheap: shallow string compare every ~250ms.\n useEffect(() => {\n const handle = window.setInterval(() => {\n const next = getActiveLanguage();\n if (next !== language) setLanguage(next);\n }, 250);\n return () => { window.clearInterval(handle); };\n }, [language]);\n\n const contextValue = useMemo(() => ({ translations, setLanguage }), [translations]);\n\n return (\n <TranslationContext value={contextValue}>\n {children}\n </TranslationContext>\n );\n}\n\nexport function useTranslation() {\n const context = use(TranslationContext);\n if (!context) throw new Error('useTranslation must be used within a TranslationProvider');\n return context.translations;\n}\n\nexport function useUpdateLanguage() {\n const context = use(TranslationContext);\n if (!context) throw new Error('useUpdateLanguage must be used within a TranslationProvider');\n return context.setLanguage;\n}\n\nexport interface TranslateParam { key: string; value: string | number | boolean }\n\n//? Resolve `a.b.c` style dot-notation keys in a translation tree. Returns\n//? the key itself if it can't be resolved (so untranslated strings stand\n//? out in the UI rather than vanishing). Supports `{{param}}` substitution.\nexport function translate({ translationList, key, params }: {\n translationList: TranslationRecord;\n key: unknown;\n params?: TranslateParam[];\n}): string {\n if (typeof key !== 'string' || key.length === 0) return '';\n\n const parts = key.split('.');\n let result: unknown = translationList;\n for (const part of parts) {\n if (result && typeof result === 'object' && part in result) {\n result = (result as Record<string, unknown>)[part];\n } else {\n return key;\n }\n }\n if (typeof result !== 'string') return key;\n if (!Array.isArray(params) || params.length === 0) return result;\n\n let finalResult = result;\n for (const param of params) {\n if (!param.key) continue;\n //? Escape key before building the RegExp — a key containing regex\n //? meta-characters (e.g. `.`, `+`, `(`) would otherwise mis-substitute\n //? or cause ReDoS. Use a function-form replacer to prevent `$`-sequences\n //? in the translation value from being interpreted by String.prototype.replace.\n const escapedKey = param.key.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\n const regex = new RegExp(`\\\\{\\\\{${escapedKey}\\\\}\\\\}`, 'g');\n const replacement = String(param.value);\n finalResult = finalResult.replace(regex, () => replacement);\n }\n return finalResult;\n}\n\n//? Tiny convenience hook for the common case: pass `{ key, params }` and\n//? get the resolved string back.\nexport const useTranslator = () => {\n const translations = useTranslation();\n return ({ key, params }: { key: string; params?: TranslateParam[] }) =>\n translate({ translationList: translations, key, params });\n};\n\n//? Re-export helpers from the registry so consumers have a single import\n//? point for translation customization.\nexport { getActiveLanguage, getDefaultLocale, getRegisteredLocales };\n","//? Framework-owned i18n-backed toast notify. Reads the active language\n//? source + the registered locales map to translate `{ key, params }`\n//? before handing off to `sonner`. Registers itself with\n//? `registerNotifier` on import so framework packages (apiRequest,\n//? syncRequest) automatically emit toasts in the consumer's locale.\n//?\n//? Importing this module triggers the registration as a side effect —\n//? add `import { i18nNotify } from '@luckystack/core/client';` to the\n//? consumer's main entry once.\n\nimport { toast } from 'sonner';\nimport { registerNotifier } from '../notifier';\nimport { getActiveLanguage, getLocaleByCode } from '../localesRegistry';\nimport { translate, type TranslateParam } from './TranslationProvider';\n\ninterface NotifyInput {\n key: string;\n params?: TranslateParam[];\n}\n\nconst resolve = (input: NotifyInput): string => {\n const language = getActiveLanguage();\n const list = getLocaleByCode(language);\n return translate({\n translationList: (list && typeof list === 'object' ? list : {}) as Record<string, unknown>,\n key: input.key,\n params: input.params,\n });\n};\n\nconst notify = {\n success: (input: NotifyInput) => { toast.success(resolve(input)); },\n error: (input: NotifyInput) => { toast.error(resolve(input)); },\n info: (input: NotifyInput) => { toast.info(resolve(input)); },\n warning: (input: NotifyInput) => { toast.warning(resolve(input)); },\n};\n\n//? Side-effect: register with core so framework packages emit through\n//? this i18n-backed implementation.\nregisterNotifier(notify);\n\nexport default notify;\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\n//? registered middleware handler before navigating. Returns the guarded\n//? navigate function. Use everywhere instead of `useNavigate` directly so\n//? programmatic navigations honor the same auth/redirect rules as\n//? `<Middleware>`-wrapped page renders.\n\nimport { useLocation, useNavigate } from 'react-router-dom';\nimport { getMiddlewareHandler, getPageMiddleware } from '../middlewareRegistry';\nimport { useSession } from './sessionContext';\n\nconst getParams = (locationSearch: string) => {\n const params = new URLSearchParams(locationSearch);\n const queryObject: Record<string, string> = {};\n for (const [key, value] of params.entries()) {\n queryObject[key] = value;\n }\n return queryObject;\n};\n\nexport default function useRouter() {\n const navigateHandler = useNavigate();\n const location = useLocation();\n const { session } = useSession();\n\n const navigate = async (path: string) => {\n const queryObject = getParams(location.search);\n //? Per-page middleware first (declared via `export const middleware`\n //? on the target page.tsx), then the global fallback. Mirrors the\n //? `<Middleware>` component's resolution order so programmatic\n //? navigations honor the same guards as direct URL hits.\n const pageMw = getPageMiddleware(path);\n const handler = pageMw ?? getMiddlewareHandler();\n const result = await handler({ location: path, searchParams: queryObject, session });\n\n if (result?.success) {\n return navigateHandler(path);\n }\n if (result && !result.success && result.redirect) {\n return navigateHandler(result.redirect);\n }\n return;\n };\n\n return navigate;\n}\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;AA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W,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","effectiveTimeoutMs","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/tryCatchClient.ts","../src/routedHttpInvocation.ts","../src/apiRequest.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`.\n//?\n//? `apiRequest` (apiRequest.ts) is a monolithic typed function and Rule 21 /\n//? the `no-unsafe-api-wrappers` lint forbid wrapping it (a wrapper erases the\n//? route/version inference). This registry is the sanctioned escape hatch: a\n//? consumer registers an interceptor here instead of wrapping the call, so the\n//? typed call site is untouched and route/version inference survives.\n//?\n//? Two seams, both fire-and-mutate (NOT replace — the dispatcher reserves a\n//? structured return for control flow):\n//? - request interceptors run just before the socket emit. A handler may\n//? mutate `ctx.data` in place (inject a correlation id / feature-flag\n//? context / tenant header-equivalent) and is observation-only otherwise.\n//? - response interceptors run when the response envelope arrives, before the\n//? awaiting caller resolves. Observation-only (metrics, breadcrumb, custom\n//? logging). The envelope is NOT mutated by this seam — response rewriting\n//? belongs on the server `preApiRespond` / `transformApiResponse` hooks.\n//?\n//? Handlers are best-effort: a throw / rejection is caught + logged and never\n//? breaks the request pipeline. Both `register*` functions return an\n//? unsubscribe closure, matching `registerClientHook`'s contract.\n\nexport interface ApiRequestInterceptorContext {\n /** Resolved route name (`<page>/<api>` or `system/<api>`). */\n name: string;\n /** Route version literal (e.g. `'v1'`). */\n version: string;\n /**\n * Outgoing request payload. Mutate this object in place to augment the\n * request (correlation id, feature-flag context, ...). Replacing the\n * reference has no effect — mutate keys on the existing object.\n */\n data: Record<string, unknown>;\n}\n\nexport interface ApiResponseInterceptorContext {\n name: string;\n version: string;\n /** The response envelope the caller is about to receive (read-only intent). */\n response: { status: 'success' | 'error'; [key: string]: unknown };\n}\n\nexport type ApiRequestInterceptor = (\n ctx: ApiRequestInterceptorContext,\n) => void | Promise<void>;\n\nexport type ApiResponseInterceptor = (\n ctx: ApiResponseInterceptorContext,\n) => void | Promise<void>;\n\nimport { getLogger } from './loggerRegistry';\n\nconst requestInterceptors = new Set<ApiRequestInterceptor>();\nconst responseInterceptors = new Set<ApiResponseInterceptor>();\n\n/**\n * Register an outgoing-request interceptor. Returns an unsubscribe function.\n * Multiple interceptors run in registration order; each may mutate `ctx.data`.\n */\nexport function registerApiRequestInterceptor(interceptor: ApiRequestInterceptor): () => void {\n requestInterceptors.add(interceptor);\n return () => {\n requestInterceptors.delete(interceptor);\n };\n}\n\n/**\n * Register an incoming-response interceptor. Returns an unsubscribe function.\n */\nexport function registerApiResponseInterceptor(interceptor: ApiResponseInterceptor): () => void {\n responseInterceptors.add(interceptor);\n return () => {\n responseInterceptors.delete(interceptor);\n };\n}\n\n//? Framework-internal — invoked by `apiRequest`. Awaited so a handler can do an\n//? async lookup (read a flag store, mint a trace id) before the emit. Snapshot\n//? the set so a handler unregistering mid-dispatch can't skip a sibling.\nexport async function dispatchApiRequestInterceptors(\n ctx: ApiRequestInterceptorContext,\n): Promise<void> {\n if (requestInterceptors.size === 0) return;\n //? Snapshot so a handler that unregisters itself (or a sibling) mid-dispatch\n //? doesn't skip an un-visited handler.\n const interceptors = [...requestInterceptors];\n for (const interceptor of interceptors) {\n try {\n await interceptor(ctx);\n } catch (error) {\n getLogger().error('[apiRequestInterceptor] handler threw', error);\n }\n }\n}\n\n//? Framework-internal — invoked by `apiRequest` when the response arrives.\n//? Fire-and-forget (the caller does not await) so an interceptor can't delay\n//? the resolve; async rejections are caught + logged.\nexport function dispatchApiResponseInterceptors(\n ctx: ApiResponseInterceptorContext,\n): void {\n if (responseInterceptors.size === 0) return;\n //? Snapshot (see `dispatchApiRequestInterceptors`).\n const interceptors = [...responseInterceptors];\n for (const interceptor of interceptors) {\n try {\n const result = interceptor(ctx);\n if (result && typeof (result as Promise<unknown>).catch === 'function') {\n (result as Promise<unknown>).catch((error: unknown) => {\n getLogger().error('[apiResponseInterceptor] async handler rejected', error);\n });\n }\n } catch (error) {\n getLogger().error('[apiResponseInterceptor] handler threw', error);\n }\n }\n}\n\n/** Test helper — drop every registered interceptor. Not part of the public API. */\nexport function _resetApiInterceptorsForTests(): void {\n requestInterceptors.clear();\n responseInterceptors.clear();\n}\n","//? Browser-safe sibling of `tryCatch`. Behaviourally identical (same tuple,\n//? same params, same auto-capture on the error path) but it does NOT statically\n//? import `./sentrySetup`. The server `tryCatch.ts` reaches `sentrySetup` →\n//? `errorTrackerRegistry` → `node:async_hooks` at module-eval; that static edge\n//? is harmless on the server but drags a `node:`-externalized module into the\n//? Vite CLIENT bundle whenever a client importer (LoginForm) pulls\n//? `shared/tryCatch.ts`. So the client-reachable shim resolves HERE instead, and\n//? the only path to capture is a LAZY dynamic import taken on the error branch —\n//? keeping the node-bearing module out of the client's static graph.\n//?\n//? The server's `tryCatch.ts` is intentionally left untouched (byte-for-byte) so\n//? the server capture path keeps its synchronous, statically-linked behaviour.\n//? On the client, capture is best-effort and async-via-microtask is fine.\n\nexport default async function tryCatch<T, P = void>(\n func: (values: P) => Promise<T> | T,\n params?: P,\n context?: Record<string, unknown>\n): Promise<[Error | null, T | null]> {\n try {\n const response = await func(params as P);\n return [null, response];\n } catch (error) {\n //? Lazy capture: the import is only evaluated on the error branch, so the\n //? `node:async_hooks`-bearing module never enters the client's static graph.\n const { captureException } = await import('./sentrySetup');\n captureException(error, context);\n return [error instanceof Error ? error : new Error(String(error)), null];\n }\n}\n","import { httpFetch } from './csrf';\nimport tryCatch from './tryCatchClient';\nimport tryCatchSync from './tryCatchSync';\nimport type { HttpMethodLiteral } from './apiMethodMapRegistry';\n\nexport type RoutedInvocationMethod = HttpMethodLiteral;\n\nexport interface RoutedInvocationResponse<TResponse> {\n kind: 'response';\n response: TResponse;\n httpStatus: number;\n}\n\nexport interface RoutedInvocationFailure {\n kind: 'aborted' | 'timeout' | 'network-error' | 'invalid-response';\n}\n\nexport type RoutedInvocationResult<TResponse> =\n | RoutedInvocationResponse<TResponse>\n | RoutedInvocationFailure;\n\nexport interface RoutedHttpInvocationInput<TStream> {\n path: string;\n method: RoutedInvocationMethod;\n data: Record<string, unknown>;\n stream?: (payload: TStream) => void;\n signals?: readonly (AbortSignal | null | undefined)[];\n timeoutMs?: number | false;\n}\n\ninterface ParsedSseEvent {\n event: string;\n data: unknown;\n}\n\nconst parseJson = (value: string): unknown => {\n const [error, parsed] = tryCatchSync(() => JSON.parse(value) as unknown);\n return error ? undefined : parsed;\n};\n\nconst parseSseFrame = (frame: string): ParsedSseEvent | null => {\n let event = 'message';\n const dataLines: string[] = [];\n for (const rawLine of frame.split('\\n')) {\n const line = rawLine.endsWith('\\r') ? rawLine.slice(0, -1) : rawLine;\n if (line.length === 0 || line.startsWith(':')) continue;\n if (line.startsWith('event:')) {\n event = line.slice(6).trimStart();\n continue;\n }\n if (line.startsWith('data:')) {\n dataLines.push(line.slice(5).trimStart());\n }\n }\n if (dataLines.length === 0) return null;\n return { event, data: parseJson(dataLines.join('\\n')) };\n};\n\nconst parseSseResponse = async <TResponse>(\n response: Response,\n onStream: ((payload: never) => void) | undefined,\n): Promise<TResponse | null> => {\n const reader = response.body?.getReader();\n if (!reader) return null;\n\n const decoder = new TextDecoder();\n let buffer = '';\n let finalResponse: TResponse | null = null;\n\n const consumeFrames = (flush: boolean): void => {\n buffer = buffer.replaceAll('\\r\\n', '\\n');\n let boundary = buffer.indexOf('\\n\\n');\n while (boundary !== -1) {\n const frame = buffer.slice(0, boundary);\n buffer = buffer.slice(boundary + 2);\n const parsed = parseSseFrame(frame);\n if (parsed?.event === 'stream' && parsed.data !== undefined) {\n onStream?.(parsed.data as never);\n } else if ((parsed?.event === 'final' || parsed?.event === 'error') && parsed.data !== undefined) {\n finalResponse = parsed.data as TResponse;\n }\n boundary = buffer.indexOf('\\n\\n');\n }\n\n if (flush && buffer.trim().length > 0) {\n const parsed = parseSseFrame(buffer);\n if (parsed?.event === 'stream' && parsed.data !== undefined) {\n onStream?.(parsed.data as never);\n } else if ((parsed?.event === 'final' || parsed?.event === 'error') && parsed.data !== undefined) {\n finalResponse = parsed.data as TResponse;\n }\n buffer = '';\n }\n };\n\n let readDone = false;\n while (!readDone) {\n const { done, value } = await reader.read();\n readDone = done;\n if (!done) {\n buffer += decoder.decode(value, { stream: true });\n consumeFrames(false);\n }\n }\n buffer += decoder.decode();\n consumeFrames(true);\n return finalResponse;\n};\n\nconst buildRequest = ({\n path,\n method,\n data,\n stream,\n signal,\n}: {\n path: string;\n method: RoutedInvocationMethod;\n data: Record<string, unknown>;\n stream: boolean;\n signal: AbortSignal;\n}): { url: string; init: RequestInit } => {\n const headers = new Headers();\n if (stream) headers.set('Accept', 'text/event-stream');\n\n if (method === 'GET') {\n const params = new URLSearchParams();\n params.set('__luckystack_data', JSON.stringify(data));\n if (stream) params.set('stream', 'true');\n const separator = path.includes('?') ? '&' : '?';\n return {\n url: `${path}${separator}${params.toString()}`,\n init: { method, headers, signal },\n };\n }\n\n headers.set('Content-Type', 'application/json');\n return {\n url: stream ? `${path}${path.includes('?') ? '&' : '?'}stream=true` : path,\n init: {\n method,\n headers,\n signal,\n body: JSON.stringify(data),\n },\n };\n};\n\nexport const invokeRoutedHttp = async <TResponse, TStream = Record<string, unknown>>({\n path,\n method,\n data,\n stream,\n signals = [],\n timeoutMs,\n}: RoutedHttpInvocationInput<TStream>): Promise<RoutedInvocationResult<TResponse>> => {\n if (signals.some((signal) => signal?.aborted)) return { kind: 'aborted' };\n\n const controller = new AbortController();\n const timeoutReason = Symbol('routed-invocation-timeout');\n const didTimeout = (): boolean => controller.signal.reason === timeoutReason;\n const abortFromCaller = (): void => {\n controller.abort();\n };\n for (const signal of signals) signal?.addEventListener('abort', abortFromCaller, { once: true });\n\n const timeout = typeof timeoutMs === 'number' && timeoutMs > 0\n ? setTimeout(() => {\n controller.abort(timeoutReason);\n }, timeoutMs)\n : null;\n\n const cleanup = (): void => {\n if (timeout) clearTimeout(timeout);\n for (const signal of signals) signal?.removeEventListener('abort', abortFromCaller);\n };\n\n const request = buildRequest({\n path,\n method,\n data,\n stream: typeof stream === 'function',\n signal: controller.signal,\n });\n const [fetchError, response] = await tryCatch(() => httpFetch(request.url, request.init));\n if (fetchError || !response) {\n cleanup();\n if (didTimeout()) return { kind: 'timeout' };\n if (controller.signal.aborted) return { kind: 'aborted' };\n return { kind: 'network-error' };\n }\n\n const contentType = response.headers.get('content-type')?.toLowerCase() ?? '';\n const [parseError, parsed] = await tryCatch(async () => {\n if (contentType.includes('text/event-stream')) {\n return parseSseResponse<TResponse>(response, stream);\n }\n return (await response.json()) as TResponse;\n });\n cleanup();\n\n if (parseError || parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n if (didTimeout()) return { kind: 'timeout' };\n if (controller.signal.aborted) return { kind: 'aborted' };\n return { kind: 'invalid-response' };\n }\n\n return { kind: 'response', response: parsed, httpStatus: response.status };\n};\n","import { getProjectConfig } from \"./projectConfig\";\nimport { getLogger } from \"./loggerRegistry\";\nimport { getRegisteredApiMethod } from \"./apiMethodMapRegistry\";\nimport { inferHttpMethod, isGetMethodName } from \"./httpApiUtils\";\nimport { incrementResponseIndex, socket, waitForSocket } from \"./socketState\";\nimport type { ApiTypeMap, StreamPayload } from './apiTypeStubs';\nimport { notify } from \"./notifier\";\nimport { enqueueApiRequest, isOnline, removeApiQueueItem } from \"./offlineQueue\";\nimport { Socket } from \"socket.io-client\";\nimport { normalizeErrorResponseCore } from \"./responseNormalizer\";\nimport { parseServiceRouteName } from \"./serviceRoute\";\nimport tryCatchSync from \"./tryCatchSync\";\nimport {\n buildApiResponseEventName,\n buildApiStreamEventName,\n socketEventNames,\n} from \"./socketEvents\";\nimport {\n dispatchApiRequestInterceptors,\n dispatchApiResponseInterceptors,\n} from \"./apiInterceptors\";\nimport { invokeRoutedHttp } from './routedHttpInvocation';\n\n//? Abort controller logic:\n//? - abortable: true → always use abort controller\n//? - abortable: false → never use abort controller\n//? - abortable: undefined → use abort controller for GET APIs (from generated types)\n//? Keyed by `fullName` + a stable hash of the request `data` so the\n//? replace-previous (dedupe) semantics only fire for an IDENTICAL in-flight\n//? call. Two components polling the same GET route with DIFFERENT params no\n//? longer abort each other (each gets its own bucket); a genuine duplicate\n//? still supersedes the prior one.\n//? Size-capped at 1000 entries. All normal code paths (resolve, abort, disconnect,\n//? timeout) call `cleanupAbortController()` which deletes the entry. The cap\n//? is a safety net for edge cases where cleanup is skipped (socket torn down\n//? without a `disconnect` event, or a future code path that forgets to clean up).\nconst ABORT_CONTROLLERS_MAX = 1000;\nconst abortControllers = new Map<string, AbortController>();\n\n//? Stable, order-insensitive JSON stringify so `{a:1,b:2}` and `{b:2,a:1}`\n//? hash to the same abort-controller key. Falls back to a non-deduping unique\n//? token when the payload can't be serialised (circular ref), which is the\n//? safe choice — an unserialisable payload should never silently abort a\n//? sibling request.\nconst stableStringify = (value: unknown): string => {\n const seen = new WeakSet<object>();\n const walk = (input: unknown): unknown => {\n if (input === null || typeof input !== 'object') return input;\n if (seen.has(input)) return '[circular]';\n seen.add(input);\n if (Array.isArray(input)) return input.map((entry) => walk(entry));\n const record = input as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(record).toSorted()) {\n out[key] = walk(record[key]);\n }\n return out;\n };\n const [error, json] = tryCatchSync(() => JSON.stringify(walk(value)));\n if (error || typeof json !== 'string') {\n return `__unserializable__:${String(Date.now())}-${String(Math.random())}`;\n }\n return json;\n};\n\nconst buildAbortKey = (fullName: string, data: unknown): string =>\n `${fullName}::${stableStringify(data)}`;\n\nexport type ApiStreamEvent<T extends StreamPayload = StreamPayload> = T;\n\n/**\n * Check if an API is a GET method.\n *\n * Primary path: consult the registered `apiMethodMap` (generated from the\n * actual handler's `httpMethod` export or name-based inference at codegen\n * time). Falls back to name-prefix heuristic only when the map isn't\n * registered yet — typically because an older consumer wrapper has not called\n * `registerApiMethodMap(...)` from `src/_sockets/apiRequest.ts` before re-exporting this helper.\n */\nconst isGetMethodByPrefix = (apiName: string): boolean => isGetMethodName(apiName.toLowerCase());\n\ntype RoutedApiFailureKind = 'timeout' | 'aborted' | 'network-error' | 'invalid-response';\n\nconst routedApiErrorCode = (kind: RoutedApiFailureKind): string => {\n if (kind === 'timeout') return 'api.timeout';\n if (kind === 'aborted') return 'request.aborted';\n if (kind === 'invalid-response') return 'api.invalidServerResponse';\n return 'api.ioUnavailable';\n};\n\nexport const resolveApiRequestHttpMethod = (apiName: string, version: string) => {\n const lastSlash = apiName.lastIndexOf('/');\n if (lastSlash > 0) {\n const pagePath = apiName.slice(0, lastSlash);\n const leaf = apiName.slice(lastSlash + 1);\n const method = getRegisteredApiMethod(pagePath, leaf, version);\n if (method) return method;\n }\n return inferHttpMethod(apiName);\n};\n\nconst resolveGetMethod = (apiName: string, version: string): { isGet: boolean; usingHeuristic: boolean } => {\n //? Resolved-name shape: `pagePath/apiName`. apiMethodMap is nested by\n //? pagePath → apiName → version. Split at the last `/` so multi-segment\n //? page paths (e.g. 'admin/users') still resolve.\n const lastSlash = apiName.lastIndexOf('/');\n if (lastSlash > 0) {\n const pagePath = apiName.slice(0, lastSlash);\n const leaf = apiName.slice(lastSlash + 1);\n const method = getRegisteredApiMethod(pagePath, leaf, version);\n if (method) return { isGet: method === 'GET', usingHeuristic: false };\n }\n return { isGet: isGetMethodByPrefix(apiName), usingHeuristic: true };\n};\n\nconst canSendNow = (socketInstance: Socket) => {\n if (!socketInstance.connected) return false;\n return isOnline();\n};\n\nconst createQueueId = () => {\n return `${String(Date.now())}-${String(Math.random())}`;\n};\n\n//? Resolve logging flags at call time so registration order doesn't matter.\n//? `getLogging()` is called inside each handler instead of captured at load.\nconst getLogging = () => getProjectConfig().logging;\nconst shouldLogDev = () => getLogging().devLogs;\nconst shouldNotifyDev = () => getLogging().devNotifications;\nconst shouldLogStream = () => getLogging().stream;\n\nconst shouldUseAbortController = ({\n abortable,\n isGet,\n usingHeuristic,\n}: {\n abortable: boolean | undefined;\n isGet: boolean;\n usingHeuristic: boolean;\n}) => {\n if (abortable === true) return true;\n if (abortable === false) return false;\n //? CORE-O15: when `abortable` is unspecified and we are relying on the\n //? name-prefix heuristic (apiMethodMap not registered), default to\n //? non-abortable. A mis-named POST (e.g. `getReport`) would otherwise\n //? silently abort an identical in-flight call it has nothing to do with.\n //? Once `registerApiMethodMap` is called (normal boot), the generated map\n //? resolves the method and the heuristic path is never taken.\n if (usingHeuristic) return false;\n return isGet;\n};\n\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// Type Helpers\n// ═══════════════════════════════════════════════════════════════════════════════\n\n// Check if data input is required (i.e., T does NOT allow empty object)\n// Unions like {a:1} | {b:1} do NOT allow {}, so data will be required\ntype DataRequired<T> = Record<string, never> extends T ? false : true;\n\ntype UnionToIntersection<U> =\n (U extends unknown ? (arg: U) => void : never) extends ((arg: infer I) => void)\n ? I\n : never;\n\n// ═══════════════════════════════════════════════════════════════════════════════\n// Global API Params - Union of ALL valid API calls with proper data enforcement\n// ═══════════════════════════════════════════════════════════════════════════════\ntype ApiRouteRecord = UnionToIntersection<{\n [P in keyof ApiTypeMap]: {\n [N in keyof ApiTypeMap[P] as P extends 'root'\n ? `system/${Extract<N, string>}`\n : `${Extract<P, string>}/${Extract<N, string>}`]: ApiTypeMap[P][N]\n }\n}[keyof ApiTypeMap]>;\n\ntype ApiFullName = Extract<keyof ApiRouteRecord, string>;\ntype VersionsForFullName<F extends ApiFullName> = keyof ApiRouteRecord[F] & string;\n\n// Force expansion of types to clear aliases in tooltips\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\n\n// Get input type for an API name (union if exists on multiple pages)\ntype InputForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = ApiRouteRecord[F][V] extends { input: infer I }\n ? I\n : never;\n\n// Get output type for an API name (union if exists on multiple pages)\ntype OutputForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = ApiRouteRecord[F][V] extends { output: infer O }\n ? O\n : never;\n\ntype StreamForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = ApiRouteRecord[F][V] extends { stream: infer S }\n ? S\n : never;\n\ntype ApiStreamCallbackForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> =\n [StreamForFullName<F, V>] extends [never]\n ? never\n : (event: ApiStreamEvent<Prettify<StreamForFullName<F, V> extends StreamPayload ? StreamForFullName<F, V> : StreamPayload>>) => void;\n\n// Build params type for a specific API name\ntype ApiParamsForFullName<\n F extends ApiFullName,\n V extends VersionsForFullName<F>\n> = DataRequired<InputForFullName<F, V>> extends true\n ? { name: F; version: V; data: Prettify<InputForFullName<F, V>>; abortable?: boolean; disableErrorMessage?: boolean; onStream?: ApiStreamCallbackForFullName<F, V>; signal?: AbortSignal; timeoutMs?: number | false; }\n : { name: F; version: V; data?: Prettify<InputForFullName<F, V>>; abortable?: boolean; disableErrorMessage?: boolean; onStream?: ApiStreamCallbackForFullName<F, V>; signal?: AbortSignal; timeoutMs?: number | false; };\n\ninterface RuntimeApiParams {\n name?: string;\n version?: string;\n data?: unknown;\n abortable?: boolean;\n disableErrorMessage?: boolean;\n onStream?: (event: ApiStreamEvent) => void;\n signal?: AbortSignal;\n /** Per-call response timeout (ms). Overrides `api.requestTimeoutMs`. `false` disables. */\n timeoutMs?: number | false;\n}\n\nexport interface ApiErrorResponse extends Record<string, unknown> {\n status: 'error';\n httpStatus: number;\n message: string;\n errorCode: string;\n errorParams?: { key: string; value: string | number | boolean }[];\n}\n\ninterface ApiSuccessResponse extends Record<string, unknown> {\n status: 'success';\n httpStatus: number;\n}\n\ntype ApiResponse = ApiErrorResponse | ApiSuccessResponse;\n\nconst normalizeApiError = ({\n response,\n fallbackErrorCode,\n fallbackHttpStatus = 500,\n}: {\n response: { status: 'error'; errorCode?: string; errorParams?: { key: string; value: string | number | boolean }[]; httpStatus?: number; message?: string };\n fallbackErrorCode: string;\n fallbackHttpStatus?: number;\n}): ApiErrorResponse => {\n const normalized = normalizeErrorResponseCore({\n response,\n fallbackErrorCode,\n fallbackHttpStatus,\n resolveMessage: ({ errorCode }) => {\n if (typeof response.message === 'string' && response.message.trim().length > 0) {\n return response.message;\n }\n return errorCode;\n },\n });\n\n return {\n status: 'error',\n message: normalized.message,\n errorCode: normalized.errorCode,\n errorParams: normalized.errorParams,\n httpStatus: normalized.httpStatus ?? fallbackHttpStatus,\n };\n};\n\n/**\n * Type-safe API request function.\n * \n * @example\n * ```typescript\n * // Full name usage - includes page in the name\n * const result = await apiRequest({ name: 'examples/publicApi', version: 'v1', data: { message: 'hello' } });\n * // result is typed correctly for publicApi\n * \n * // Global APIs use service-first naming\n * await apiRequest({ name: 'system/session', version: 'v1' });\n * ```\n */\n\nexport function apiRequest<F extends ApiFullName, V extends VersionsForFullName<F>>(\n params: ApiParamsForFullName<F, V>\n): Promise<Prettify<OutputForFullName<F, V>> | ApiErrorResponse> {\n type RequestOutput = Prettify<OutputForFullName<F, V> & ApiResponse>;\n const runtimeParams = params as RuntimeApiParams;\n const { name, version, disableErrorMessage = false, onStream, signal: externalSignal, timeoutMs } = runtimeParams;\n const payloadData = runtimeParams.data;\n\n return new Promise<RequestOutput>((resolve) => {\n void (async () => {\n //? B1 — if the consumer-supplied signal is already aborted at call\n //? time, short-circuit before we even touch the socket. Mirrors the\n //? `fetch(url, { signal })` contract.\n if (externalSignal?.aborted) {\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'request.aborted' },\n fallbackErrorCode: 'request.aborted',\n }) as RequestOutput);\n return;\n }\n if (!name || typeof name !== \"string\") {\n if (shouldLogDev()) {\n getLogger().error(\"apiRequest: Invalid name\");\n }\n if (shouldNotifyDev()) {\n notify.error({ key: 'api.invalidName' });\n }\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'api.invalidName' },\n fallbackErrorCode: 'api.invalidName',\n }) as RequestOutput);\n return;\n }\n\n if (!version || typeof version !== 'string') {\n if (shouldLogDev()) {\n getLogger().error(\"apiRequest: Invalid version\");\n }\n if (shouldNotifyDev()) {\n notify.error({ key: 'api.invalidVersion' });\n }\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'api.invalidVersion' },\n fallbackErrorCode: 'api.invalidVersion',\n }) as RequestOutput);\n return;\n }\n\n const parsedRoute = parseServiceRouteName(name);\n if (parsedRoute.status === 'error') {\n if (shouldLogDev()) {\n getLogger().error(`[apiRequest] Invalid service route name`, undefined, { name, reason: parsedRoute.reason });\n }\n if (shouldNotifyDev()) {\n notify.error({ key: 'routing.invalidServiceRouteName' });\n }\n resolve(normalizeErrorResponseCore({\n response: {\n status: 'error',\n errorCode: 'routing.invalidServiceRouteName',\n errorParams: [{ key: 'name', value: name }],\n },\n fallbackErrorCode: 'routing.invalidServiceRouteName',\n }) as RequestOutput);\n return;\n }\n\n const sanitizedName = parsedRoute.normalizedRouteName;\n\n const data = payloadData && typeof payloadData === \"object\" ? payloadData : {};\n\n if (!await waitForSocket()) {\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'api.ioUnavailable' },\n fallbackErrorCode: 'api.ioUnavailable',\n }) as RequestOutput);\n return;\n }\n if (!socket) {\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'api.ioUnavailable' },\n fallbackErrorCode: 'api.ioUnavailable',\n }) as RequestOutput);\n return;\n }\n\n //? Abort controller logic:\n //? - abortable: true → always use abort controller\n //? - abortable: false → never use abort controller\n //? - abortable: undefined → smart default (GET-like APIs get abort controller)\n //? Pass the full pagePath/apiName so the registry lookup can resolve via\n //? the generated apiMethodMap (falls back to the leaf-name prefix heuristic\n //? when the map isn't registered yet).\n const { isGet, usingHeuristic } = resolveGetMethod(sanitizedName, version);\n const useAbortController = shouldUseAbortController({\n abortable: runtimeParams.abortable,\n isGet,\n usingHeuristic,\n });\n const fullName = `api/${sanitizedName}/${version}`;\n //? Per-payload abort key: only an identical in-flight call to the same\n //? route supersedes the previous one (see `buildAbortKey` rationale).\n const abortKey = buildAbortKey(fullName, data);\n\n let signal: AbortSignal | null = null;\n let abortHandler: (() => void) | null = null;\n let queueId: string | null = null;\n let cleanupStreamListener: (() => void) | null = null;\n //? Response listener cleanup, registered once the `.once` handler is\n //? attached in `runRequest`. Lets the abort path proactively `off()` the\n //? lingering response listener instead of waiting for a response that was\n //? cancelled and will never arrive.\n let cleanupResponseListener: (() => void) | null = null;\n //? Response-timeout timer. Armed right after the request is emitted so a\n //? lost response (server restart/crash between emit and reply) settles the\n //? promise instead of hanging the awaiting caller forever.\n let responseTimeout: ReturnType<typeof setTimeout> | null = null;\n const clearResponseTimeout = () => {\n if (responseTimeout) {\n clearTimeout(responseTimeout);\n responseTimeout = null;\n }\n };\n\n const cleanupAbortController = () => {\n if (signal && abortHandler) {\n signal.removeEventListener(\"abort\", abortHandler);\n }\n abortControllers.delete(abortKey);\n };\n\n if (useAbortController) {\n if (abortControllers.has(abortKey)) {\n const prevAbortController = abortControllers.get(abortKey);\n prevAbortController?.abort();\n }\n //? Evict the oldest entry when the cap is reached (LRU-insert-order).\n //? Map preserves insertion order; the first key is the oldest in-flight entry.\n if (!abortControllers.has(abortKey) && abortControllers.size >= ABORT_CONTROLLERS_MAX) {\n const oldest = abortControllers.keys().next().value;\n if (oldest !== undefined) abortControllers.delete(oldest);\n }\n const abortController = new AbortController();\n abortControllers.set(abortKey, abortController);\n signal = abortController.signal;\n\n abortHandler = () => {\n clearResponseTimeout();\n cleanupStreamListener?.();\n cleanupStreamListener = null;\n cleanupResponseListener?.();\n cleanupResponseListener = null;\n cleanupAbortController();\n if (queueId) {\n removeApiQueueItem(queueId);\n }\n //? Resolve (not reject) with the same `request.aborted` envelope the\n //? external-signal abort path uses. Rejecting here produced an\n //? unhandled rejection for fire-and-forget GET calls that get\n //? superseded by the default replace-previous behaviour.\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'request.aborted' },\n fallbackErrorCode: 'request.aborted',\n }) as RequestOutput);\n };\n\n signal.addEventListener(\"abort\", abortHandler);\n }\n\n const runRequest = (socketInstance: Socket) => {\n if (!canSendNow(socketInstance)) {\n queueId ??= createQueueId();\n //? For the immediate reject-new path (`drop-newest` / `reject`\n //? policy) THIS item's `onDrop` fires SYNCHRONOUSLY inside\n //? `enqueueApiRequest`. We keep surfacing that as the historical\n //? `offline.queueFull` via the `!enqueued` branch, so suppress the\n //? `onDrop` resolve during the synchronous enqueue window and re-arm\n //? it only if the item was actually queued (so a LATER async eviction\n //? — drop-oldest by a future enqueue, or age expiry — still settles).\n let suppressOnDrop = true;\n //? `enqueueApiRequest` returns `false` when the offline queue is\n //? full and `dropPolicy: 'reject'` is active. Without honoring\n //? that signal the outer promise never settles and the caller\n //? awaits forever. Resolve with a normalized error envelope so\n //? callers can branch.\n const enqueued = enqueueApiRequest({\n id: queueId,\n key: fullName,\n run: (nextSocket) => {\n runRequest(nextSocket);\n },\n createdAt: Date.now(),\n //? CORE: mirror SYNC-09. Settle the awaiting caller when this\n //? QUEUED request is later EVICTED (drop-oldest by a future\n //? enqueue / age expiry) instead of ever running. Without it the\n //? promise hangs forever, since `run` is the only thing that could\n //? otherwise resolve it — `apiRequest` had drifted from the sibling\n //? `syncRequest` which already had this fix. Also tear down the\n //? abort-controller registry entry so it isn't leaked.\n onDrop: (reason) => {\n if (suppressOnDrop) return;\n cleanupAbortController();\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'offline.dropped', errorParams: [{ key: 'reason', value: reason }] },\n fallbackErrorCode: 'offline.dropped',\n }) as RequestOutput);\n },\n });\n //? Past the synchronous enqueue window: if the item is sitting in the\n //? queue, a future eviction should settle via `onDrop`.\n suppressOnDrop = false;\n if (!enqueued) {\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'offline.queueFull', httpStatus: 503 },\n fallbackErrorCode: 'offline.queueFull',\n fallbackHttpStatus: 503,\n }) as RequestOutput);\n } else if (externalSignal && queueId) {\n //? CORE-O14: if an external AbortSignal fires while the item is\n //? sitting in the offline queue, its listener inside runRequest has\n //? not been registered yet. Register a one-shot handler here so the\n //? abort is not silently ignored and the queue slot is reclaimed.\n const capturedQueueId = queueId;\n const queueAbortHandler = () => {\n removeApiQueueItem(capturedQueueId);\n cleanupAbortController();\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'request.aborted' },\n fallbackErrorCode: 'request.aborted',\n }) as RequestOutput);\n };\n externalSignal.addEventListener('abort', queueAbortHandler, { once: true });\n }\n return;\n }\n\n if (signal?.aborted) {\n return;\n }\n\n if (getProjectConfig().transport.invocation === 'routed-http') {\n void (async () => {\n const effectiveTimeoutMs = timeoutMs ?? getProjectConfig().api.requestTimeoutMs;\n const routed = await invokeRoutedHttp<ApiResponse, ApiStreamEvent>({\n path: `/api/${sanitizedName}/${version}`,\n method: resolveApiRequestHttpMethod(sanitizedName, version),\n data: data as Record<string, unknown>,\n stream: onStream,\n signals: [signal, externalSignal],\n timeoutMs: effectiveTimeoutMs,\n });\n cleanupAbortController();\n if (queueId) removeApiQueueItem(queueId);\n\n if (routed.kind !== 'response') {\n const errorCode = routedApiErrorCode(routed.kind);\n resolve(normalizeApiError({\n response: {\n status: 'error',\n errorCode,\n httpStatus: routed.kind === 'timeout' ? 504 : undefined,\n },\n fallbackErrorCode: errorCode,\n fallbackHttpStatus: routed.kind === 'timeout' ? 504 : 500,\n }) as RequestOutput);\n return;\n }\n\n const response = routed.response;\n dispatchApiResponseInterceptors({ name: sanitizedName, version, response });\n if (response.status === 'error') {\n const normalizedError = normalizeErrorResponseCore({ response });\n if (!disableErrorMessage) {\n notify.error({\n key: normalizedError.errorCode || normalizedError.message,\n params: normalizedError.errorParams,\n });\n }\n Object.assign(response, normalizedError);\n }\n resolve(response as RequestOutput);\n })();\n return;\n }\n\n const tempIndex = incrementResponseIndex();\n socketInstance.emit(socketEventNames.apiRequest, { name: fullName, data, responseIndex: tempIndex });\n\n //? B1 — bridge the consumer's AbortSignal to the server. When the\n //? signal fires we emit `apiCancel { responseIndex }` so the server\n //? handler stops emitting new chunks. We also resolve locally with\n //? `request.aborted` so the awaiting caller settles (vs awaiting\n //? a response that will never arrive because we cancelled it).\n let cleanupExternalAbort: (() => void) | null = null;\n if (externalSignal) {\n const externalAbortHandler = () => {\n clearResponseTimeout();\n socketInstance.emit(socketEventNames.apiCancel, { responseIndex: tempIndex });\n cleanupStreamListener?.();\n cleanupStreamListener = null;\n cleanupResponseListener?.();\n cleanupResponseListener = null;\n cleanupAbortController();\n cleanupExternalAbort?.();\n cleanupExternalAbort = null;\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'request.aborted' },\n fallbackErrorCode: 'request.aborted',\n }) as RequestOutput);\n };\n externalSignal.addEventListener('abort', externalAbortHandler);\n cleanupExternalAbort = () => {\n externalSignal.removeEventListener('abort', externalAbortHandler);\n };\n }\n\n //? Arm the response timeout. A per-call `timeoutMs` overrides the\n //? `api.requestTimeoutMs` config default; either may be `false` to\n //? disable. On expiry we tear down every listener/controller and settle\n //? with a 504 envelope so the awaiting caller never hangs.\n clearResponseTimeout();\n const effectiveTimeoutMs = timeoutMs ?? getProjectConfig().api.requestTimeoutMs;\n if (typeof effectiveTimeoutMs === 'number' && effectiveTimeoutMs > 0) {\n responseTimeout = setTimeout(() => {\n responseTimeout = null;\n cleanupStreamListener?.();\n cleanupStreamListener = null;\n cleanupResponseListener?.();\n cleanupResponseListener = null;\n cleanupExternalAbort?.();\n cleanupExternalAbort = null;\n cleanupAbortController();\n if (queueId) {\n removeApiQueueItem(queueId);\n }\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'api.timeout', httpStatus: 504 },\n fallbackErrorCode: 'api.timeout',\n fallbackHttpStatus: 504,\n }) as RequestOutput);\n }, effectiveTimeoutMs);\n }\n\n if (typeof onStream === 'function') {\n const streamEventName = buildApiStreamEventName(tempIndex);\n const streamListener = (streamPayload: ApiStreamEvent) => {\n if (signal?.aborted) {\n return;\n }\n\n if (shouldLogStream()) {\n getLogger().debug(`Server API Stream(${String(tempIndex)})`, { APINAME: sanitizedName, streamPayload });\n }\n\n onStream(streamPayload);\n };\n\n socketInstance.on(streamEventName, streamListener);\n cleanupStreamListener = () => {\n socketInstance.off(streamEventName, streamListener);\n };\n }\n\n if (shouldLogDev()) {\n getLogger().debug(`Client API Request(${String(tempIndex)})`, { APINAME: sanitizedName, data });\n }\n\n //? Inside the handler we type as the runtime envelope (ApiResponse).\n //? Project-specific output narrowing only matters at the call site,\n //? where `RequestOutput = OutputForFullName<F,V> & ApiResponse` is\n //? returned via `resolve(... as RequestOutput)`. When core is type-\n //? checked in isolation (e.g. per-package tsup dts build), ApiTypeMap\n //? is empty so OutputForFullName collapses to never; using ApiResponse\n //? here keeps the body type-safe in both cases.\n const responseEventName = buildApiResponseEventName(tempIndex);\n const responseListener = (response: ApiResponse) => {\n if (signal?.aborted) {\n clearResponseTimeout();\n cleanupExternalAbort?.();\n cleanupExternalAbort = null;\n return;\n }\n\n clearResponseTimeout();\n cleanupStreamListener?.();\n cleanupStreamListener = null;\n cleanupExternalAbort?.();\n cleanupExternalAbort = null;\n //? Call cleanup (not just null) so that any watcher layered on top of\n //? cleanupResponseListener (e.g. the CORE-O13 disconnect watcher) is\n //? properly torn down when a normal response arrives.\n cleanupResponseListener?.();\n cleanupResponseListener = null;\n\n const status = response.status;\n\n //? EXT-03 — fire client response interceptors when the envelope\n //? arrives (observation-only: metrics, breadcrumb, custom logging).\n dispatchApiResponseInterceptors({ name: sanitizedName, version, response });\n\n if (shouldLogDev()) {\n getLogger().debug(`Server API Response(${String(tempIndex)})`, { ...response, APINAME: sanitizedName });\n }\n\n if (status === \"error\") {\n const normalizedError = normalizeErrorResponseCore({ response });\n\n if (!disableErrorMessage) {\n if (normalizedError.errorCode) {\n notify.error({ key: normalizedError.errorCode, params: normalizedError.errorParams });\n } else {\n notify.error({ key: normalizedError.message });\n }\n }\n\n Object.assign(response, normalizedError);\n cleanupAbortController();\n resolve(response as RequestOutput);\n return;\n }\n\n cleanupAbortController();\n\n resolve(response as RequestOutput);\n };\n\n socketInstance.once(responseEventName, responseListener);\n cleanupResponseListener = () => {\n socketInstance.off(responseEventName, responseListener);\n };\n\n //? CORE-O13: when timeout is disabled AND there is no abort controller\n //? a server restart between emit and reply leaves this promise pending\n //? forever, leaking the response listener. The disconnect event is the\n //? authoritative signal that no reply will ever arrive on this socket.\n const disconnectHandler = () => {\n if (cleanupResponseListener) {\n cleanupResponseListener();\n cleanupResponseListener = null;\n }\n cleanupStreamListener?.();\n cleanupStreamListener = null;\n cleanupExternalAbort?.();\n cleanupExternalAbort = null;\n clearResponseTimeout();\n cleanupAbortController();\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'api.disconnected' },\n fallbackErrorCode: 'api.disconnected',\n }) as RequestOutput);\n };\n socketInstance.once('disconnect', disconnectHandler);\n //? Wrap the response listener to also remove the disconnect watcher on\n //? a normal reply (avoids a dangling listener on every successful call).\n const originalCleanupResponseListener = cleanupResponseListener;\n cleanupResponseListener = () => {\n socketInstance.off('disconnect', disconnectHandler);\n originalCleanupResponseListener();\n };\n };\n\n //? EXT-03 — fire client request interceptors just before the emit. They\n //? may mutate `data` in place (correlation id / feature-flag context).\n //? `data` is the same reference passed to `socketInstance.emit`, so the\n //? mutation is on the wire. Awaited so an async interceptor (flag lookup,\n //? trace-id mint) completes first; failures are caught + logged inside.\n await dispatchApiRequestInterceptors({\n name: sanitizedName,\n version,\n data: data as Record<string, unknown>,\n });\n\n //? CORE-O12: re-check the external abort signal after the interceptor\n //? await. A slow async interceptor adds uncounted latency; if the caller\n //? aborted during that window the signal is already fired but nothing has\n //? yet attached its listener (that happens inside runRequest). Settling\n //? here avoids emitting a request whose response will never be consumed.\n if (externalSignal?.aborted) {\n resolve(normalizeApiError({\n response: { status: 'error', errorCode: 'request.aborted' },\n fallbackErrorCode: 'request.aborted',\n }) as RequestOutput);\n return;\n }\n\n runRequest(socket);\n })();\n });\n}","//? Locales registry — lets the framework's TranslationProvider + notify\n//? read the consumer's translation JSON files without baking them into the\n//? package. Consumer overlay: `luckystack/i18n/locales.ts` calls\n//? `registerLocales({ en: enJson, nl: nlJson, ... })`.\n//?\n//? Language source: a separate registry — `registerLanguageSource(fn)` —\n//? lets the consumer wire up where the active language comes from\n//? (typically the SessionProvider's current `session.language`). When no\n//? source is registered, the framework falls back to\n//? `getProjectConfig().defaultLanguage`.\n\nimport { getProjectConfig } from './projectConfig';\n\nexport type LocalesMap = Record<string, unknown>;\nexport type LanguageSource = () => string | null | undefined;\n\nlet activeLocales: LocalesMap = {};\nlet activeLanguageSource: LanguageSource | null = null;\n\nexport const registerLocales = (locales: LocalesMap): void => {\n activeLocales = locales;\n};\n\nexport const getRegisteredLocales = (): LocalesMap => activeLocales;\n\nexport const getDefaultLocale = (): string => getProjectConfig().defaultLanguage || 'en';\n\nexport const registerLanguageSource = (fn: LanguageSource): void => {\n activeLanguageSource = fn;\n};\n\nexport const getActiveLanguage = (): string => {\n if (activeLanguageSource) {\n const lang = activeLanguageSource();\n if (typeof lang === 'string' && lang.length > 0) return lang;\n }\n return getDefaultLocale();\n};\n\n//? Lookup a language's translation tree by code. Falls back to default\n//? language when the code isn't registered. Used by TranslationProvider\n//? + notify to resolve the active translations.\nexport const getLocaleByCode = (code: string): unknown => {\n if (code in activeLocales) return activeLocales[code];\n const fallback = getDefaultLocale();\n if (fallback in activeLocales) return activeLocales[fallback];\n return {};\n};\n","//? Middleware handler registry. The framework's `Middleware` + `Router`\n//? components (in `./react/`) call the registered handler on every\n//? navigation change to decide whether the user is allowed on the target\n//? route. Per-page `export const middleware` (see `registerPageMiddleware`\n//? below) is the canonical path; a consumer wanting a cross-cutting GLOBAL\n//? guard registers it from the client bootstrap (typically `main.tsx`) via\n//? `registerMiddlewareHandler(...)`. No separate\n//? `src/_functions/middlewareHandler.ts` file is required.\n\nimport type { BaseSessionLayout } from './sessionTypes';\n\nexport interface MiddlewareInput {\n location: string;\n searchParams: Record<string, string>;\n session: BaseSessionLayout | null;\n}\n\nexport type MiddlewareResult =\n | { success: true; redirect?: undefined; status?: undefined }\n //? Deny by sending the user somewhere else. Right for \"you are not signed in\"\n //? — `/login` is where the problem gets solved.\n | { success: false; redirect: string; status?: undefined }\n //? Deny IN PLACE: keep the requested URL and render a status state (403 for\n //? signed-in-but-not-allowed, 404 to hide a resource's existence). Redirecting\n //? an authenticated user who simply lacks a permission sends them somewhere\n //? that does not explain anything and loses the URL they were trying to reach.\n | { success: false; redirect?: undefined; status: number }\n | undefined;\n\n/** Normalized decision derived from a {@link MiddlewareResult}. */\nexport type MiddlewareOutcome =\n | { kind: 'allow' }\n | { kind: 'redirect'; to: string }\n | { kind: 'deny'; status: number }\n | { kind: 'fallback' };\n\n//? ONE interpretation of a middleware result, shared by the `<Middleware>`\n//? component (direct URL hits) and `useRouter` (programmatic navigation). They\n//? previously branched separately, which is how `useRouter` ended up silently\n//? doing nothing for any result it did not recognise.\nexport const resolveMiddlewareOutcome = (result: MiddlewareResult): MiddlewareOutcome => {\n if (result?.success) return { kind: 'allow' };\n if (result?.redirect) return { kind: 'redirect', to: result.redirect };\n if (typeof result?.status === 'number') return { kind: 'deny', status: result.status };\n //? No result at all, or a malformed one — treat as \"not allowed here\" and let\n //? the caller fall back to a safe destination.\n return { kind: 'fallback' };\n};\n\nexport type MiddlewareHandler = (input: MiddlewareInput) => MiddlewareResult | Promise<MiddlewareResult>;\n\n//? Default handler: allow by default. Per-page `middleware` exports on each\n//? `page.tsx` are the canonical route-guard path (see `registerPageMiddleware`\n//? below); the global handler is only consulted as a fallback for pages\n//? that don't declare their own guard. Allowing-by-default keeps public\n//? routes (`/`, `/login`, `/register`, ...) working without forcing every\n//? consumer to ship a `src/_functions/middlewareHandler.ts` boilerplate\n//? file just to opt-in to \"let the user through\".\n//?\n//? Consumers who need a cross-cutting global guard (telemetry, server-\n//? reachability check, maintenance banner gate) call\n//? `registerMiddlewareHandler(...)` directly from `main.tsx` with their own\n//? function — no separate file required.\nconst DEFAULT_HANDLER: MiddlewareHandler = () => ({ success: true });\n\nlet activeHandler: MiddlewareHandler = DEFAULT_HANDLER;\n\nexport const registerMiddlewareHandler = (handler: MiddlewareHandler): void => {\n activeHandler = handler;\n};\n\nexport const getMiddlewareHandler = (): MiddlewareHandler => activeHandler;\n\n//? Per-page middleware registry. Counterpart to `registerMiddlewareHandler`\n//? for the common case where each page declares its own guard locally\n//? (`export const middleware = ({ session }) => {...}` from page.tsx).\n//? The framework's `<Middleware>` component checks this map FIRST and only\n//? falls back to the global handler when no per-page entry is registered.\n//?\n//? `PageMiddleware<TSession>` matches the existing `MiddlewareHandler`\n//? signature so any handler shape is reusable on either side. The generic\n//? is purely ergonomic for consumer-side type narrowing — module\n//? augmentation of `BaseSessionLayout` flows through.\n\nexport type PageMiddleware<TSession extends BaseSessionLayout = BaseSessionLayout> = (\n input: { location: string; searchParams: Record<string, string>; session: TSession | null },\n) => MiddlewareResult | Promise<MiddlewareResult>;\n\nconst pageMiddlewares = new Map<string, PageMiddleware>();\n\nexport const registerPageMiddleware = (path: string, middleware: PageMiddleware): void => {\n pageMiddlewares.set(path, middleware);\n};\n\nexport const getPageMiddleware = (path: string): PageMiddleware | undefined =>\n pageMiddlewares.get(path);\n\nexport const hasPageMiddleware = (path: string): boolean => pageMiddlewares.has(path);\n\n/** Test helper — drop every registered per-page middleware. */\nexport const clearPageMiddlewaresForTests = (): void => {\n pageMiddlewares.clear();\n};\n","//? Shared session context. Defined in core so framework-React components\n//? (Middleware, Router, useSession-aware UI) can consume it without\n//? pulling in app code. The consumer's `SessionProvider` (in their\n//? template's `_providers/`) does the actual fetch/socket/lifecycle work\n//? and writes to this context via `<SessionContext value={...}>`.\n//?\n//? The session shape inside the context is intentionally loose\n//? (`BaseSessionLayout | null`) so app code with extended session types\n//? can read it through a typed `useSession<MySession>()` cast.\n\nimport { createContext, use } from 'react';\nimport type { BaseSessionLayout } from '../sessionTypes';\nimport {\n dispatchClientHook,\n dispatchVetoableClientHook,\n type ClientHookStopSignal,\n} from '../clientHookBus';\n\nexport interface SessionContextValue<TSession extends BaseSessionLayout = BaseSessionLayout> {\n session: TSession | null;\n sessionLoaded: boolean;\n}\n\nconst DEFAULT_VALUE: SessionContextValue = {\n session: null,\n sessionLoaded: false,\n};\n\nexport const SessionContext = createContext<SessionContextValue>(DEFAULT_VALUE);\n\nexport function useSession<TSession extends BaseSessionLayout = BaseSessionLayout>(): SessionContextValue<TSession> {\n return use(SessionContext) as SessionContextValue<TSession>;\n}\n\n//? Non-React accessor for code that runs outside the component tree\n//? (e.g. notify() called from a non-component). Kept in sync with the\n//? context by the consumer's SessionProvider via `setLatestSession()`.\nlet latestSession: BaseSessionLayout | null = null;\n\nexport const setLatestSession = (session: BaseSessionLayout | null): void => {\n const previous = latestSession;\n latestSession = session;\n\n //? Fire client-side lifecycle hooks on null↔non-null transitions. Covers\n //? both fresh login AND existing-session restore on page reload — both\n //? cases need the same downstream actions (room auto-join, analytics\n //? identify, etc). Same-id updates (avatar refresh, profile change) do\n //? NOT fire postLogin; if a `sessionUpdate` hook is needed later, add it\n //? as a third branch without breaking existing handlers.\n if (previous === null && session !== null) {\n dispatchClientHook('postLogin', { session });\n } else if (previous !== null && session === null) {\n dispatchClientHook('postLogout', { previousSession: previous });\n }\n};\n\n//? Caller-supplied `TSession` is used to narrow the return type at the\n//? callsite (consumers extend `BaseSessionLayout`). The lint rule sees it as\n//? \"used once\" but the parameter exists solely to surface the consumer's\n//? widened session type through the read API.\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters -- callsite-narrowing use\nexport const getCurrentSession = <TSession extends BaseSessionLayout = BaseSessionLayout>(): TSession | null =>\n latestSession as TSession | null;\n\n/**\n * Vetoable entry point for committing a null → session transition (i.e. a\n * fresh login or a page-load session restore). Dispatches the `preLogin`\n * client hook to every registered handler in parallel; if any returns a\n * stop signal, the transition is aborted and `{ committed: false, signal }`\n * is returned. Otherwise, `setLatestSession(session)` runs synchronously\n * (which fires `postLogin`) and `{ committed: true }` comes back.\n *\n * Consumer's `SessionProvider` should `await` this for non-null session\n * commits and roll local React state back to `null` when a veto comes\n * through, so the UI doesn't render a half-logged-in state.\n */\nexport type ProposeLoginResult =\n | { stopped: false; committed: true }\n | { stopped: true; signal: ClientHookStopSignal; committed: false };\n\nexport const proposeLogin = async (\n session: BaseSessionLayout,\n): Promise<ProposeLoginResult> => {\n const veto = await dispatchVetoableClientHook('preLogin', { candidateSession: session });\n if (veto.stopped) return { stopped: true, signal: veto.signal, committed: false };\n setLatestSession(session);\n return { stopped: false, committed: true };\n};\n","/* eslint-disable react-refresh/only-export-components */\nimport { createContext, use, useState, useMemo, useCallback, ReactNode } from 'react';\n\nexport type AvatarStatus = 'avatar' | 'fallback';\n\ninterface AvatarContextType {\n avatarStatuses: Record<string, AvatarStatus>;\n setAvatarStatus: (key: string, status: AvatarStatus) => void;\n}\n\nconst AvatarContext = createContext<AvatarContextType | null>(null);\n\nexport const AvatarProvider = ({ children }: { children: ReactNode }) => {\n const [avatarStatuses, setAvatarStatuses] = useState<Record<string, AvatarStatus>>({});\n\n const setAvatarStatus = useCallback((key: string, status: AvatarStatus) => {\n setAvatarStatuses(prev => ({ ...prev, [key]: status }));\n }, []);\n\n const contextValue = useMemo(() => ({\n avatarStatuses,\n setAvatarStatus,\n }), [avatarStatuses, setAvatarStatus]);\n\n return (\n <AvatarContext value={contextValue}>\n {children}\n </AvatarContext>\n );\n};\n\nexport function useAvatarContext() {\n const ctx = use(AvatarContext);\n if (!ctx) throw new Error('useAvatarContext must be used within AvatarProvider');\n return ctx;\n}\n","//? `useTheme()` — framework-owned theme state hook. Default value comes\n//? from `getProjectConfig().defaultTheme` (the union literal exported by\n//? the consumer's `config.ts`). Toggling sets the `.dark` class on\n//? `<html>`. Persistence (e.g. saving to `User.theme` via\n//? `settings/updateUser`) is up to the consumer — the hook only owns\n//? local state + DOM class.\n\nimport { useState, useCallback } from 'react';\nimport { getProjectConfig } from '../projectConfig';\n\nexport type Theme = 'light' | 'dark';\n\nconst applyDomClass = (theme: Theme): void => {\n if (typeof document === 'undefined') return;\n document.documentElement.classList.toggle('dark', theme === 'dark');\n};\n\nexport const useTheme = () => {\n const initialTheme = (getProjectConfig().defaultTheme) ?? 'light';\n const [theme, setThemeState] = useState<Theme>(initialTheme);\n\n const setTheme = useCallback((next: Theme) => {\n setThemeState(next);\n applyDomClass(next);\n }, []);\n\n return { theme, setTheme };\n};\n","/* eslint-disable react-refresh/only-export-components */\n//? Framework-owned translation provider. Reads the registered locales map\n//? (consumer registers via `registerLocales({...})` in their overlay) and\n//? the active language source (consumer registers via\n//? `registerLanguageSource(fn)`, typically `() => session?.language`).\n//? Default language falls back to `getProjectConfig().defaultLanguage`.\n\nimport { createContext, ReactNode, use, useEffect, useMemo, useState, Dispatch, SetStateAction } from 'react';\nimport {\n getActiveLanguage,\n getDefaultLocale,\n getLocaleByCode,\n getRegisteredLocales,\n} from '../localesRegistry';\n\nexport type TranslationRecord = Record<string, unknown>;\n\ninterface TranslationContextValue {\n translations: TranslationRecord;\n setLanguage: Dispatch<SetStateAction<string>>;\n}\n\nconst TranslationContext = createContext<TranslationContextValue | null>(null);\n\nconst resolveTranslations = (code: string): TranslationRecord => {\n const value = getLocaleByCode(code);\n if (value && typeof value === 'object') return value as TranslationRecord;\n return {};\n};\n\nexport function TranslationProvider({ children }: { children: ReactNode }) {\n const [language, setLanguage] = useState<string>(() => getActiveLanguage());\n const translations = useMemo(() => resolveTranslations(language), [language]);\n\n //? Poll the registered language source so changes to session.language\n //? (or whatever the consumer wired) flip the active language without a\n //? full remount. Cheap: shallow string compare every ~250ms.\n useEffect(() => {\n const handle = window.setInterval(() => {\n const next = getActiveLanguage();\n if (next !== language) setLanguage(next);\n }, 250);\n return () => { window.clearInterval(handle); };\n }, [language]);\n\n const contextValue = useMemo(() => ({ translations, setLanguage }), [translations]);\n\n return (\n <TranslationContext value={contextValue}>\n {children}\n </TranslationContext>\n );\n}\n\nexport function useTranslation() {\n const context = use(TranslationContext);\n if (!context) throw new Error('useTranslation must be used within a TranslationProvider');\n return context.translations;\n}\n\nexport function useUpdateLanguage() {\n const context = use(TranslationContext);\n if (!context) throw new Error('useUpdateLanguage must be used within a TranslationProvider');\n return context.setLanguage;\n}\n\nexport interface TranslateParam { key: string; value: string | number | boolean }\n\n//? Resolve `a.b.c` style dot-notation keys in a translation tree. Returns\n//? the key itself if it can't be resolved (so untranslated strings stand\n//? out in the UI rather than vanishing). Supports `{{param}}` substitution.\nexport function translate({ translationList, key, params }: {\n translationList: TranslationRecord;\n key: unknown;\n params?: TranslateParam[];\n}): string {\n if (typeof key !== 'string' || key.length === 0) return '';\n\n const parts = key.split('.');\n let result: unknown = translationList;\n for (const part of parts) {\n if (result && typeof result === 'object' && part in result) {\n result = (result as Record<string, unknown>)[part];\n } else {\n return key;\n }\n }\n if (typeof result !== 'string') return key;\n if (!Array.isArray(params) || params.length === 0) return result;\n\n let finalResult = result;\n for (const param of params) {\n if (!param.key) continue;\n //? Escape key before building the RegExp — a key containing regex\n //? meta-characters (e.g. `.`, `+`, `(`) would otherwise mis-substitute\n //? or cause ReDoS. Use a function-form replacer to prevent `$`-sequences\n //? in the translation value from being interpreted by String.prototype.replace.\n const escapedKey = param.key.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\n const regex = new RegExp(`\\\\{\\\\{${escapedKey}\\\\}\\\\}`, 'g');\n const replacement = String(param.value);\n finalResult = finalResult.replace(regex, () => replacement);\n }\n return finalResult;\n}\n\n//? Tiny convenience hook for the common case: pass `{ key, params }` and\n//? get the resolved string back.\nexport const useTranslator = () => {\n const translations = useTranslation();\n return ({ key, params }: { key: string; params?: TranslateParam[] }) =>\n translate({ translationList: translations, key, params });\n};\n\n//? Re-export helpers from the registry so consumers have a single import\n//? point for translation customization.\nexport { getActiveLanguage, getDefaultLocale, getRegisteredLocales };\n","//? Framework-owned i18n-backed toast notify. Reads the active language\n//? source + the registered locales map to translate `{ key, params }`\n//? before handing off to `sonner`. Registers itself with\n//? `registerNotifier` on import so framework packages (apiRequest,\n//? syncRequest) automatically emit toasts in the consumer's locale.\n//?\n//? Importing this module triggers the registration as a side effect —\n//? add `import { i18nNotify } from '@luckystack/core/client';` to the\n//? consumer's main entry once.\n\nimport { toast } from 'sonner';\nimport { registerNotifier } from '../notifier';\nimport { getActiveLanguage, getLocaleByCode } from '../localesRegistry';\nimport { translate, type TranslateParam } from './TranslationProvider';\n\ninterface NotifyInput {\n key: string;\n params?: TranslateParam[];\n}\n\nconst resolve = (input: NotifyInput): string => {\n const language = getActiveLanguage();\n const list = getLocaleByCode(language);\n return translate({\n translationList: (list && typeof list === 'object' ? list : {}) as Record<string, unknown>,\n key: input.key,\n params: input.params,\n });\n};\n\nconst notify = {\n success: (input: NotifyInput) => { toast.success(resolve(input)); },\n error: (input: NotifyInput) => { toast.error(resolve(input)); },\n info: (input: NotifyInput) => { toast.info(resolve(input)); },\n warning: (input: NotifyInput) => { toast.warning(resolve(input)); },\n};\n\n//? Side-effect: register with core so framework packages emit through\n//? this i18n-backed implementation.\nregisterNotifier(notify);\n\nexport default notify;\n","//? Framework-owned route guard. Wraps protected pages — runs the registered\n//? middleware handler (`registerMiddlewareHandler` in core) on every route\n//? change and renders children only when allowed. Redirects via React\n//? Router's `useNavigate` when the handler returns a redirect. Shows a\n//? loader only after a 200ms delay so fast checks don't flash a spinner.\n\nimport { ReactNode, useEffect, useRef, useState } from 'react';\nimport { useLocation, useNavigate } from 'react-router-dom';\nimport { getMiddlewareHandler, getPageMiddleware, resolveMiddlewareOutcome } from '../middlewareRegistry';\nimport { useSession } from './sessionContext';\nimport { getProjectConfig } from '../projectConfig';\n\nconst LOADER_DELAY_MS = 200;\n\nfunction MiddlewareLoader() {\n const [show, setShow] = useState(false);\n\n useEffect(() => {\n const id = globalThis.setTimeout(() => { setShow(true); }, LOADER_DELAY_MS);\n return () => { globalThis.clearTimeout(id); };\n }, []);\n\n if (!show) return null;\n\n return (\n <div className=\"w-full h-full flex items-center justify-center\" aria-busy=\"true\" aria-live=\"polite\">\n <div\n className=\"w-8 h-8 rounded-full border-2 border-container2-border border-t-primary animate-spin\"\n role=\"status\"\n aria-label=\"Loading\"\n />\n </div>\n );\n}\n\n//? Built-in deny view. Deliberately NOT translated: `translate()` returns the\n//? KEY when it cannot resolve one, so shipping `middleware.forbidden.title`\n//? here would print that literal string in every project that upgrades without\n//? adding the keys. Consumers who want their own copy (translated, branded,\n//? with a \"request access\" action) pass the `denied` prop.\nfunction MiddlewareDenied({ status }: { status: number }) {\n return (\n <div className=\"w-full h-full flex items-center justify-center p-6\" role=\"alert\">\n <div className=\"text-center max-w-md\">\n <div className=\"text-4xl font-bold text-title mb-2\">{status}</div>\n <div className=\"text-common\">\n {status === 404\n ? 'This page does not exist.'\n : 'You do not have permission to view this page.'}\n </div>\n </div>\n </div>\n );\n}\n\nexport default function Middleware({\n children,\n denied,\n}: {\n children: ReactNode;\n /**\n * Rendered instead of the page when middleware denies IN PLACE\n * (`{ success: false, status }`) — the URL is kept. Pass a node, or a\n * function to vary by status. Defaults to a minimal built-in view.\n */\n denied?: ReactNode | ((status: number) => ReactNode);\n}) {\n const [allowed, setAllowed] = useState(false);\n const [checking, setChecking] = useState(true);\n const [deniedStatus, setDeniedStatus] = useState<number | null>(null);\n\n const location = useLocation();\n const navigate = useNavigate();\n const { session, sessionLoaded } = useSession();\n\n //? Track the guarded route so a SESSION-only change re-evaluates the guard\n //? WITHOUT unmounting the page. A session update (avatar, roomCodes,\n //? preferences pushed via `updateSession`) used to flip `checking` back to\n //? true on every change → the whole page unmounted + remounted, wiping page\n //? state and aborting in-flight work. Joining a room (which saves the session\n //? and broadcasts `updateSession`) therefore looked like a full page refresh.\n //? Now we only show the loader / hide the page on a real ROUTE change; a bare\n //? session change re-checks in the background and only navigates away if the\n //? new session is no longer allowed.\n const routeKey = `${location.pathname} ${location.search}`;\n const guardedRouteRef = useRef<string | null>(null);\n\n useEffect(() => {\n let isMounted = true;\n const isRouteChange = guardedRouteRef.current !== routeKey;\n guardedRouteRef.current = routeKey;\n if (isRouteChange) {\n setAllowed(false);\n setChecking(true);\n //? Clear a previous route's deny so it can't flash on the new one.\n setDeniedStatus(null);\n }\n\n void (async () => {\n const params = new URLSearchParams(location.search);\n const queryObject: Record<string, string> = {};\n for (const [key, value] of params.entries()) {\n queryObject[key] = value;\n }\n\n //? Wait for the SessionProvider to finish its initial fetch — up to\n //? 5 seconds. Without this, we'd evaluate the middleware against a\n //? not-yet-loaded session and bounce the user back to /login.\n let count = 0;\n while (!sessionLoaded) {\n await new Promise(res => setTimeout(res, 10));\n count++;\n if (count > 500) break;\n }\n\n //? Per-page middleware first (declared in each page.tsx via\n //? `export const middleware`), then the global fallback handler\n //? registered via `registerMiddlewareHandler`. This lets pages own\n //? their own guards while keeping a central catch-all for\n //? cross-cutting cases (server-reachability checks, analytics).\n const pageMw = getPageMiddleware(location.pathname);\n const handler = pageMw ?? getMiddlewareHandler();\n const result = await handler({\n location: location.pathname,\n searchParams: queryObject,\n session,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- isMounted intentional, see comment below\n if (!isMounted) return;\n\n const outcome = resolveMiddlewareOutcome(result);\n if (outcome.kind === 'allow') {\n setDeniedStatus(null);\n setAllowed(true);\n } else if (outcome.kind === 'redirect') {\n void navigate(outcome.to);\n } else if (outcome.kind === 'deny') {\n //? Stay on the requested URL and show why. Redirecting a signed-in user\n //? who merely lacks a permission loses the URL and explains nothing.\n setDeniedStatus(outcome.status);\n } else {\n //? Navigate to a safe, deterministic fallback instead of `navigate(-1)`,\n //? which chains backwards out of the app on repeated denials (e.g. when\n //? history is shallow or the previous page was also guarded).\n void navigate(getProjectConfig().loginRedirectUrl ?? '/');\n }\n\n setChecking(false);\n })();\n\n //! isMounted check is load-bearing — without it, repeated middleware\n //? denials chain navigate(-1) and walk too far up history. Keep it.\n return () => {\n isMounted = false;\n };\n }, [routeKey, location.pathname, location.search, navigate, session, sessionLoaded]);\n\n if (checking) return <MiddlewareLoader />;\n if (deniedStatus !== null) {\n const custom = typeof denied === 'function' ? denied(deniedStatus) : denied;\n return <div className=\"w-full h-full\">{custom ?? <MiddlewareDenied status={deniedStatus} />}</div>;\n }\n if (!allowed) return null;\n return <div className=\"w-full h-full\">{children}</div>;\n}\n","//? Wrapper around react-router-dom's `useNavigate` that runs the\n//? registered middleware handler before navigating. Returns the guarded\n//? navigate function. Use everywhere instead of `useNavigate` directly so\n//? programmatic navigations honor the same auth/redirect rules as\n//? `<Middleware>`-wrapped page renders.\n\nimport { useLocation, useNavigate } from 'react-router-dom';\nimport { getMiddlewareHandler, getPageMiddleware, resolveMiddlewareOutcome } from '../middlewareRegistry';\nimport { useSession } from './sessionContext';\n\nconst getParams = (locationSearch: string) => {\n const params = new URLSearchParams(locationSearch);\n const queryObject: Record<string, string> = {};\n for (const [key, value] of params.entries()) {\n queryObject[key] = value;\n }\n return queryObject;\n};\n\nexport default function useRouter() {\n const navigateHandler = useNavigate();\n const location = useLocation();\n const { session } = useSession();\n\n const navigate = async (path: string) => {\n const queryObject = getParams(location.search);\n //? Per-page middleware first (declared via `export const middleware`\n //? on the target page.tsx), then the global fallback. Mirrors the\n //? `<Middleware>` component's resolution order so programmatic\n //? navigations honor the same guards as direct URL hits.\n const pageMw = getPageMiddleware(path);\n const handler = pageMw ?? getMiddlewareHandler();\n const result = await handler({ location: path, searchParams: queryObject, session });\n\n const outcome = resolveMiddlewareOutcome(result);\n if (outcome.kind === 'redirect') {\n return navigateHandler(outcome.to);\n }\n //? `allow` obviously navigates. So does `deny` — the target route's\n //? `<Middleware>` renders the status state THERE, which keeps the URL and\n //? shows why. Silently doing nothing (the old behaviour for anything that\n //? was not allow-or-redirect) makes the button look broken.\n if (outcome.kind === 'allow' || outcome.kind === 'deny') {\n return navigateHandler(path);\n }\n return;\n };\n\n return navigate;\n}\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,OAA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AAF,KAAC,oBAAiB;AACvC,MAAI,iBAAiB,MAAM;AACzB,UAAM,SAAS,OAAO,WAAW,aAAa,OAAO,YAAY,IAAI;AACrE,WAAO,gBAAAA,KAAC,SAAI,WAAU,iBAAiB,oBAAU,gBAAAA,KAAC,oBAAiB,QAAQ,cAAc,GAAG;AAAA,EAC9F;AACA,MAAI,CAAC,QAAS,QAAO;AACrB,SAAO,gBAAAA,KAAC,SAAI,WAAU,iBAAiB,UAAS;AAClD;;;AC/JA,SAAS,eAAAG,cAAa,eAAAC,oBAAmB;AAIzC,IAAM,YAAY,CAAC,mBAA2B;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,UAAM,UAAU,yBAAyB,MAAM;AAC/C,QAAI,QAAQ,SAAS,YAAY;AAC/B,aAAO,gBAAgB,QAAQ,EAAE;AAAA,IACnC;AAKA,QAAI,QAAQ,SAAS,WAAW,QAAQ,SAAS,QAAQ;AACvD,aAAO,gBAAgB,IAAI;AAAA,IAC7B;AACA;AAAA,EACF;AAEA,SAAO;AACT;","names":["resolve","effectiveTimeoutMs","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"]}
|