@luckystack/core 0.10.2 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/AGENTS.md +11 -0
  2. package/CHANGELOG.md +18 -0
  3. package/README.md +2 -88
  4. package/dist/apiInterceptors.d.ts +36 -0
  5. package/dist/apiMethodMapRegistry.d.ts +5 -0
  6. package/dist/apiRequest.d.ts +71 -0
  7. package/dist/apiTypeStubs.d.ts +3 -5
  8. package/dist/avatarConfig.d.ts +22 -0
  9. package/dist/bindAddress.d.ts +15 -0
  10. package/dist/bootUuid.d.ts +24 -0
  11. package/dist/cancelRegistry.d.ts +7 -0
  12. package/dist/checkOrigin.d.ts +6 -0
  13. package/dist/{chunk-IJYNVM2W.js → chunk-P3SSLA3E.js} +2 -2
  14. package/dist/chunk-P3SSLA3E.js.map +1 -0
  15. package/dist/{chunk-5FXBTGYL.js → chunk-XDX5MV54.js} +2 -2
  16. package/dist/chunk-XDX5MV54.js.map +1 -0
  17. package/dist/client.d.ts +46 -335
  18. package/dist/client.js +5 -5
  19. package/dist/client.js.map +1 -1
  20. package/dist/clientHookBus.d.ts +62 -0
  21. package/dist/clients.d.ts +16 -0
  22. package/dist/config.d.ts +8 -2
  23. package/dist/configUtils.d.ts +16 -0
  24. package/dist/consoleLog.d.ts +1 -0
  25. package/dist/cookies.d.ts +28 -0
  26. package/dist/createRegistry.d.ts +39 -0
  27. package/dist/csrf.d.ts +30 -0
  28. package/dist/csrfConfig.d.ts +32 -0
  29. package/dist/db.d.ts +12 -0
  30. package/dist/dbHealthCheck.d.ts +6 -0
  31. package/dist/{config-CwW3KY9r.d.ts → deployConfigRegistry.d.ts} +8 -43
  32. package/dist/emailRegistry.d.ts +139 -0
  33. package/dist/env.d.ts +38 -0
  34. package/dist/errorFormatterRegistry.d.ts +54 -0
  35. package/dist/errorTrackerIdentity.d.ts +14 -0
  36. package/dist/errorTrackerRegistry.d.ts +85 -0
  37. package/dist/escapeHtml.d.ts +6 -0
  38. package/dist/eslint/index.d.ts +5 -8
  39. package/dist/eslint/index.js +125 -8
  40. package/dist/eslint/index.js.map +1 -1
  41. package/dist/eslint/internal/hasPackage.d.ts +1 -0
  42. package/dist/eslint/internal/ruleTypes.d.ts +4 -0
  43. package/dist/eslint/rules/no-arbitrary-tailwind-color.d.ts +3 -0
  44. package/dist/eslint/rules/no-direct-prisma-import-in-components.d.ts +3 -0
  45. package/dist/eslint/rules/no-local-socket-enumeration.d.ts +3 -0
  46. package/dist/eslint/rules/no-raw-fetch-in-src.d.ts +3 -0
  47. package/dist/eslint/rules/no-raw-try-catch.d.ts +3 -0
  48. package/dist/eslint/rules/no-unsafe-api-wrappers.d.ts +3 -0
  49. package/dist/eslint/rules/no-unsafe-sync-wrappers.d.ts +3 -0
  50. package/dist/eslint/rules/no-untranslated-jsx-text.d.ts +4 -0
  51. package/dist/eslint/rules/prefer-luckystack-confirm.d.ts +3 -0
  52. package/dist/eslint/rules/prefer-luckystack-dropdown.d.ts +3 -0
  53. package/dist/eslint/rules/prefer-luckystack-notify.d.ts +3 -0
  54. package/dist/extractToken.d.ts +12 -0
  55. package/dist/extractTokenFromRequest.d.ts +12 -0
  56. package/dist/getParams.d.ts +9 -0
  57. package/dist/hooks/registry.d.ts +12 -0
  58. package/dist/hooks/types.d.ts +446 -0
  59. package/dist/httpApiUtils.d.ts +54 -0
  60. package/dist/index.d.ts +110 -1892
  61. package/dist/index.js +2 -2
  62. package/dist/index.js.map +1 -1
  63. package/dist/lease.d.ts +18 -0
  64. package/dist/localSocketEnumerationGuard.d.ts +22 -0
  65. package/dist/localeReloader.d.ts +3 -0
  66. package/dist/localesRegistry.d.ts +8 -0
  67. package/dist/localizedNormalizer.d.ts +50 -0
  68. package/dist/loggerRegistry.d.ts +12 -0
  69. package/dist/middlewareRegistry.d.ts +45 -0
  70. package/dist/notifier.d.ts +17 -0
  71. package/dist/offlineQueue.d.ts +48 -0
  72. package/dist/oneTimeToken.d.ts +43 -0
  73. package/dist/pageRouteValidation.d.ts +37 -0
  74. package/dist/paths.d.ts +35 -0
  75. package/dist/peerDeps.d.ts +23 -0
  76. package/dist/portOverrideRegistry.d.ts +3 -0
  77. package/dist/processUpload.d.ts +44 -0
  78. package/dist/{sessionTypes-DanjuPaE.d.ts → projectConfig.d.ts} +32 -129
  79. package/dist/rateLimiter.d.ts +90 -0
  80. package/dist/react/AvatarProvider.d.ts +11 -0
  81. package/dist/react/Middleware.d.ts +10 -0
  82. package/dist/react/Router.d.ts +1 -0
  83. package/dist/react/TranslationProvider.d.ts +22 -0
  84. package/dist/react/notify.d.ts +12 -0
  85. package/dist/react/sessionContext.d.ts +31 -0
  86. package/dist/react/useTheme.d.ts +5 -0
  87. package/dist/redactedLogKeys.d.ts +22 -0
  88. package/dist/redis.d.ts +15 -0
  89. package/dist/redisKeyFormatter.d.ts +7 -0
  90. package/dist/resolveClientIp.d.ts +51 -0
  91. package/dist/responseNormalizer.d.ts +33 -0
  92. package/dist/roomNameFormatterRegistry.d.ts +36 -0
  93. package/dist/roomSockets.d.ts +23 -0
  94. package/dist/routedDataQuery.d.ts +7 -0
  95. package/dist/routedHttpInvocation.d.ts +20 -0
  96. package/dist/runtimeMapsRegistry.d.ts +18 -0
  97. package/dist/runtimeTypeValidation.d.ts +13 -0
  98. package/dist/secretsResolved.d.ts +3 -0
  99. package/dist/{sentrySetup-HNIURVUZ.js → sentrySetup-OLZ4BO7Q.js} +2 -2
  100. package/dist/sentrySetup.d.ts +21 -0
  101. package/dist/serveAvatars.d.ts +5 -0
  102. package/dist/serviceRoute.d.ts +27 -0
  103. package/dist/servicesConfigRegistry.d.ts +22 -0
  104. package/dist/sessionProviderRegistry.d.ts +46 -0
  105. package/dist/sessionTypes.d.ts +79 -0
  106. package/dist/sleep.d.ts +1 -0
  107. package/dist/socketEvents.d.ts +37 -0
  108. package/dist/socketMiddlewareRegistry.d.ts +20 -0
  109. package/dist/socketRedisAdapter.d.ts +21 -0
  110. package/dist/socketState.d.ts +5 -0
  111. package/dist/socketStatusTypes.d.ts +6 -0
  112. package/dist/socketTypes.d.ts +34 -0
  113. package/dist/synchronizedEnvHashes.d.ts +66 -0
  114. package/dist/testFileConvention.d.ts +11 -0
  115. package/dist/testResetTargets.d.ts +5 -0
  116. package/dist/tryCatch.d.ts +1 -0
  117. package/dist/tryCatchClient.d.ts +1 -0
  118. package/dist/tryCatchSync.d.ts +1 -0
  119. package/dist/validateRequest.d.ts +50 -0
  120. package/docs/app-bootstrap.md +4 -449
  121. package/docs/config-registry.md +3 -346
  122. package/docs/csrf-config.md +3 -86
  123. package/docs/error-tracker-registry.md +3 -192
  124. package/docs/hooks.md +2 -295
  125. package/docs/rate-limit-strategy.md +3 -168
  126. package/docs/redis-adapter.md +5 -110
  127. package/docs/session-types.md +3 -178
  128. package/docs/socket-bootstrap.md +5 -385
  129. package/package.json +4 -4
  130. package/CLAUDE.md +0 -256
  131. package/dist/chunk-5FXBTGYL.js.map +0 -1
  132. package/dist/chunk-IJYNVM2W.js.map +0 -1
  133. package/dist/pageRouteValidation-B4Cmtfjv.d.ts +0 -280
  134. /package/dist/{sentrySetup-HNIURVUZ.js.map → sentrySetup-OLZ4BO7Q.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/apiMethodMapRegistry.ts","../src/httpApiUtils.ts","../src/socketState.ts","../src/notifier.ts","../src/tryCatchSync.ts","../src/clientHookBus.ts","../src/offlineQueue.ts","../src/responseNormalizer.ts","../src/serviceRoute.ts","../src/socketEvents.ts","../src/csrfConfig.ts","../src/tryCatch.ts","../src/csrf.ts","../src/routedDataQuery.ts","../src/sleep.ts","../src/pageRouteValidation.ts"],"sourcesContent":["//? Generated `apiMethodMap` registry. Replaces the prefix-heuristic\n//? in `isGetMethod` (apiRequest.ts) so abort-controller selection uses\n//? the actual HTTP method declared on the handler instead of guessing\n//? from the name prefix.\n//?\n//? Wiring: the project's `src/_sockets/apiRequest.ts` wrapper imports the\n//? generated runtime map and calls `registerApiMethodMap(apiMethodMap)` once at\n//? module load, immediately before re-exporting the core request helper. Until then,\n//? lookups return `undefined` and `isGetMethod` falls back to the\n//? prefix heuristic (preserving previous behavior for transitional code).\n\nexport type HttpMethodLiteral = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\nexport type ApiMethodMap = Record<string, Record<string, Record<string, HttpMethodLiteral>>>;\n\nimport { createRegistry } from './createRegistry';\n\nconst registry = createRegistry<ApiMethodMap | null>(null);\n\nexport const registerApiMethodMap = (map: ApiMethodMap): void => {\n registry.register(map);\n};\n\nexport const getRegisteredApiMethod = (\n pagePath: string,\n apiName: string,\n version: string,\n): HttpMethodLiteral | undefined => {\n const activeMap = registry.get();\n if (!activeMap) return undefined;\n //? The map shape is `Record<page, Record<name, Record<version, method>>>`;\n //? TS treats each indexed access as defined (no `noUncheckedIndexedAccess`),\n //? so the optional chains look redundant. They're not — a missing key returns\n //? undefined at runtime, which is the contract this function is documenting.\n return activeMap[pagePath]?.[apiName]?.[version];\n};\n\nexport const isApiMethodMapRegistered = (): boolean => registry.isRegistered();\n","/**\n * HTTP API Utilities\n * \n * Helpers for HTTP API request handling including:\n * - Smart HTTP method detection based on API name\n * - Method validation\n */\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\n/**\n * Single source of truth for the GET-prefix naming heuristic\n * (`get` / `fetch` / `list`). Used by both `inferHttpMethod` here and the\n * client transport's `isGetMethod` fallback in `apiRequest.ts`, so the two\n * prefix heuristics can't drift apart. Expects an already-lowercased leaf name.\n */\nexport const isGetMethodName = (methodNameLower: string): boolean =>\n methodNameLower.startsWith('get') ||\n methodNameLower.startsWith('fetch') ||\n methodNameLower.startsWith('list');\n\n/**\n * Infer the HTTP method from an API name based on common naming conventions.\n * \n * - Names starting with \"get\" → GET\n * - Names starting with \"delete\" or \"remove\" → DELETE\n * - Names starting with \"update\" or \"edit\" → PUT\n * - Everything else → POST (create operations, actions)\n * \n * @example\n * ```typescript\n * inferHttpMethod('getUserData') // → 'GET'\n * inferHttpMethod('deleteAccount') // → 'DELETE'\n * inferHttpMethod('updateProfile') // → 'PUT'\n * inferHttpMethod('createUser') // → 'POST'\n * inferHttpMethod('sendEmail') // → 'POST'\n * ```\n */\nexport const inferHttpMethod = (apiName: string): HttpMethod => {\n // Extract the method name from the full path (e.g., \"api/examples/getUserData\" → \"getUserData\")\n const nameParts = apiName.split('/');\n const lastPart = nameParts.at(-1)?.toLowerCase() ?? '';\n const methodName = /^v\\d+$/.test(lastPart)\n ? (nameParts.at(-2) ?? '').toLowerCase()\n : lastPart;\n\n if (isGetMethodName(methodName)) {\n return 'GET';\n }\n\n if (methodName.startsWith('delete') || methodName.startsWith('remove')) {\n return 'DELETE';\n }\n\n if (methodName.startsWith('update') || methodName.startsWith('edit') || methodName.startsWith('patch')) {\n return 'PUT';\n }\n\n // Default: POST for create operations and general actions\n return 'POST';\n};\n\n/**\n * Get the effective HTTP method for an API.\n * Uses explicit export if available, otherwise infers from name.\n */\nexport const getEffectiveHttpMethod = (\n apiConfig: { httpMethod?: HttpMethod },\n apiName: string\n): HttpMethod => {\n return apiConfig.httpMethod ?? inferHttpMethod(apiName);\n};\n\n/**\n * Check if an HTTP method is valid for an API.\n *\n * @param requestMethod - The method from the HTTP request\n * @param allowedMethod - The method the API accepts\n * @returns true only when the method matches the route's allowed method.\n *\n * NOTE: `OPTIONS` is intentionally NOT treated as allowed here. A custom-route\n * author wiring this into their dispatch must answer CORS preflights BEFORE the\n * route check — letting `OPTIONS` through would execute the handler on a request\n * the CSRF middleware treats as non-state-changing (CSRF-exempt), opening a\n * bypass on method-locked routes.\n */\nexport const isMethodAllowed = (\n requestMethod: string,\n allowedMethod: HttpMethod\n): boolean => {\n return requestMethod === allowedMethod;\n};\n","import type { Socket } from 'socket.io-client';\n\n// Shared, mutable socket-client state. Single source of truth for the socket\n// instance, consumed by transport helpers in @luckystack/core (apiRequest)\n// and @luckystack/sync (syncRequest), and written by the project's React\n// hook wiring in `src/_sockets/socketInitializer.ts` via `setSocket(io(...))`.\n//\n// The `export let socket` form gives importers a live binding — they always\n// see the current value after `setSocket` replaces it.\n\nexport let socket: Socket | null = null;\n\n//? One-shot waiters: promises that resolve the moment a non-null socket is\n//? set. Replacing the original `setInterval` poll (10 ms × 500 iterations)\n//? with a subscribe-and-notify pattern eliminates the busy-loop overhead and\n//? guarantees sub-tick delivery rather than up-to-10 ms latency.\nlet waiters: ((s: Socket) => void)[] = [];\n\n//? Absolute deadline for `waitForSocket` — prevents a permanently-dangling\n//? promise in environments where the socket is never created (SSR, tests).\nconst WAIT_FOR_SOCKET_TIMEOUT_MS = 5000;\n\nexport const setSocket = (next: Socket | null): void => {\n socket = next;\n //? Resolve all pending waiters the moment a real socket arrives.\n if (next) {\n const pending = waiters;\n waiters = [];\n for (const resolve of pending) {\n resolve(next);\n }\n }\n};\n\nlet responseIndex = 0;\n\nexport const incrementResponseIndex = (): number => {\n responseIndex = responseIndex + 1;\n return responseIndex;\n};\n\nexport const waitForSocket = (): Promise<Socket | null> => {\n if (socket) return Promise.resolve(socket);\n return new Promise<Socket | null>((resolve) => {\n const timer = setTimeout(() => {\n //? Time out: remove our waiter slot and resolve with null so the\n //? caller surfaces a \"socket unavailable\" path instead of hanging.\n waiters = waiters.filter((w) => w !== onSocket);\n resolve(null);\n }, WAIT_FOR_SOCKET_TIMEOUT_MS);\n\n const onSocket = (s: Socket): void => {\n clearTimeout(timer);\n resolve(s);\n };\n\n waiters.push(onSocket);\n });\n};\n","//? Client-side notifier DI. Framework packages (apiRequest, syncRequest,\n//? offline queue flush) emit toasts on transport errors. Default is silent\n//? (no-op) so tests and SSR contexts don't need a toaster installed.\n//?\n//? The project's entry point registers a notifier backed by its UI toolkit\n//? (sonner + i18n) via `registerNotifier({ error, success, ... })`.\n\nimport { createRegistry } from './createRegistry';\n\nexport interface NotifyParam {\n key: string;\n value: string | number | boolean;\n}\n\nexport interface NotifyInput {\n key: string;\n params?: NotifyParam[];\n}\n\nexport interface Notifier {\n success: (input: NotifyInput) => void;\n error: (input: NotifyInput) => void;\n info: (input: NotifyInput) => void;\n warning: (input: NotifyInput) => void;\n}\n\nconst noopNotifier: Notifier = {\n success: () => { /* no-op */ },\n error: () => { /* no-op */ },\n info: () => { /* no-op */ },\n warning: () => { /* no-op */ },\n};\n\nconst registry = createRegistry<Notifier>(noopNotifier);\n\nexport const registerNotifier = (notifier: Notifier): void => {\n registry.register(notifier);\n};\n\nexport const getNotifier = (): Notifier => registry.get();\n\n//? Delegating wrapper matching the project's existing `notify` shape so the\n//? switchover inside framework packages is a one-line import change.\nexport const notify: Notifier = {\n success: (input) => { registry.get().success(input); },\n error: (input) => { registry.get().error(input); },\n info: (input) => { registry.get().info(input); },\n warning: (input) => { registry.get().warning(input); },\n};\n","//? Synchronous sibling of `tryCatch`. The async `tryCatch` returns a Promise\n//? and auto-captures to the error tracker — neither of which fits a hot,\n//? genuinely-synchronous path (error-formatter dispatch, cookie/CSRF parse)\n//? that must stay synchronous and decides its own logging.\n//?\n//? Unlike the async `tryCatch`, this helper does NOT auto-capture to the\n//? error tracker: the call sites that need it are synchronous fallbacks that\n//? already do their own contextual logging and deliberately keep the error\n//? path side-effect-light. Capture explicitly on the error tuple when needed.\n\n//? `P = void` mirrors the async `tryCatch<T, P = void>` so a params-less call\n//? can pass just the result type: `tryCatchSync<URL>(() => new URL(raw))`.\n//? Without the default TS demands both type args (TS2558).\nexport default function tryCatchSync<T, P = void>(\n func: (values: P) => T,\n params?: P,\n): [Error | null, T | null] {\n try {\n const response = func(params as P);\n return [null, response];\n } catch (error) {\n return [error instanceof Error ? error : new Error(String(error)), null];\n }\n}\n","//? Client-side hook bus. Counterpart to the server-side `registerHook` /\n//? `dispatchHook` system in `hookRegistry.ts`, but lives here in the\n//? browser-safe surface and listens for client-side lifecycle moments:\n//? session login, session logout (and room for `sessionUpdate` later).\n//?\n//? Fired from `react/sessionContext.ts` when `setLatestSession` observes\n//? a null → non-null (postLogin) or non-null → null (postLogout) transition.\n//? That makes the fire-point framework-controlled — consumers don't have to\n//? add their own useEffect in `SessionProvider` to detect these moments.\n//?\n//? Handlers are best-effort: errors are caught + logged but don't break the\n//? session pipeline. Async handlers fire-and-forget; the caller of\n//? `setLatestSession` does not await.\n//?\n//? Typical use:\n//? import { registerClientHook } from '@luckystack/core/client';\n//?\n//? registerClientHook('postLogin', ({ session }) => {\n//? const letter = session.name?.[0]?.toLowerCase();\n//? if (letter) joinRoom(`letter-${letter}`);\n//? });\n//?\n//? Consumers with extended session shapes get narrow typing via the same\n//? `BaseSessionLayout` module augmentation pattern the rest of the framework\n//? uses (see ARCHITECTURE_EXTENSION_POINTS.md `@luckystack/login` section).\n\nimport type { BaseSessionLayout } from './sessionTypes';\nimport { getLogger } from './loggerRegistry';\n\nexport interface ClientHookPayloadMap {\n //? Fires BEFORE the framework commits a null → session transition.\n //? Handlers may return a `ClientHookStopSignal` to veto the login (e.g.\n //? account suspended since last visit, feature-flag gate, geo block).\n //? Only fires when the consumer commits the transition through the\n //? vetoable entry point — see `proposeLogin` in `react/sessionContext.ts`.\n preLogin: { candidateSession: BaseSessionLayout };\n postLogin: { session: BaseSessionLayout };\n postLogout: { previousSession: BaseSessionLayout };\n //? Fires when the offline queue drops a request (full queue with a\n //? `drop-oldest`/`drop-newest`/`reject` policy, or an item past `maxAgeMs`).\n //? The in-memory queue is not durable across refreshes; this is the seam to\n //? surface a \"your change wasn't sent\" toast or to persist the item\n //? elsewhere. `queue` says which queue, `reason` why it was dropped.\n queueItemDropped: {\n queue: 'api' | 'sync';\n key: string;\n reason: 'queue-full' | 'expired';\n dropPolicy: 'drop-oldest' | 'drop-newest' | 'reject';\n };\n}\n\nexport type ClientHookName = keyof ClientHookPayloadMap;\n\n//? Stop signal returned by a `pre*` client hook handler to veto the\n//? framework's main flow. Mirrors the server-side `HookStopSignal` shape so\n//? `errorCode` flows through the same i18n / responseNormalizer pipeline a\n//? consumer already wires up.\nexport interface ClientHookStopSignal {\n stop: true;\n errorCode: string;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-invalid-void-type -- mirrors server-side HookResult, see hooks/types.ts\nexport type ClientHookResult = void | undefined | ClientHookStopSignal;\n\nexport type ClientDispatchResult =\n | { stopped: false }\n | { stopped: true; signal: ClientHookStopSignal };\n\nexport type ClientHookHandler<N extends ClientHookName> = (\n payload: ClientHookPayloadMap[N],\n) => ClientHookResult | Promise<ClientHookResult>;\n\n//? Storage uses `unknown` handler sets so the generic `N` doesn't have to\n//? narrow at every access — the cast happens once at read/write inside the\n//? typed wrappers below, which is sound because each hook name's Set only\n//? ever sees handlers registered under that same name.\ntype AnyHandler = (payload: unknown) => ClientHookResult | Promise<ClientHookResult>;\nconst handlerSets: Partial<Record<ClientHookName, Set<AnyHandler>>> = {};\n\n/**\n * Subscribe to a client-side lifecycle hook. Returns an unsubscribe function\n * — call it to remove the handler (e.g. inside a React effect cleanup).\n *\n * Multiple handlers can be registered for the same hook; they all fire on\n * each dispatch. A handler that throws (sync) or rejects (async) is logged\n * to `console.error` and does not affect other handlers.\n */\nexport function registerClientHook<N extends ClientHookName>(\n name: N,\n handler: ClientHookHandler<N>,\n): () => void {\n const existing = handlerSets[name];\n const set = existing ?? new Set<AnyHandler>();\n if (!existing) handlerSets[name] = set;\n const wrapped = handler as AnyHandler;\n set.add(wrapped);\n return () => {\n set.delete(wrapped);\n };\n}\n\n/**\n * Fire a client-side hook (fire-and-forget). Framework-internal — consumers\n * should not call this directly. Used for `post*` hooks where any stop-signal\n * returned by a handler is intentionally ignored: a `postLogin` listener that\n * tried to \"stop\" the framework would be too late — the transition already\n * happened. Use `dispatchVetoableClientHook` for `pre*` hooks where the\n * caller actually awaits the veto decision.\n */\nexport function dispatchClientHook<N extends ClientHookName>(\n name: N,\n payload: ClientHookPayloadMap[N],\n): void {\n const set = handlerSets[name];\n if (!set || set.size === 0) return;\n //? Snapshot the set before iterating so a handler that unregisters itself\n //? (or a sibling) mid-dispatch doesn't skip un-visited handlers — Set\n //? iteration honors mid-iter deletes per ECMAScript spec, which we don't\n //? want here.\n const handlers = [...set];\n for (const handler of handlers) {\n try {\n const result = handler(payload);\n if (result && typeof (result as Promise<unknown>).catch === 'function') {\n (result as Promise<unknown>).catch((error: unknown) => {\n getLogger().error(`[clientHook:${name}] async handler rejected`, error);\n });\n }\n } catch (error) {\n getLogger().error(`[clientHook:${name}] handler threw`, error);\n }\n }\n}\n\n/**\n * Awaits every registered handler for a `pre*` client hook. If any handler\n * returns a `ClientHookStopSignal`, dispatch short-circuits and returns\n * `{ stopped: true, signal }`; callers must respect the veto (skip the\n * pending action). Handlers that throw or reject are logged but treated as\n * `undefined` — a buggy handler must not silently block the user flow.\n *\n * Mirrors `dispatchHook` from `@luckystack/core` so consumer/framework code\n * can use the same stop-signal pattern on both sides of the wire.\n */\nexport async function dispatchVetoableClientHook<N extends ClientHookName>(\n name: N,\n payload: ClientHookPayloadMap[N],\n): Promise<ClientDispatchResult> {\n const set = handlerSets[name];\n if (!set || set.size === 0) return { stopped: false };\n //? Snapshot the set (see `dispatchClientHook` for why).\n const handlers = [...set];\n for (const handler of handlers) {\n let result: ClientHookResult;\n try {\n result = await handler(payload);\n } catch (error) {\n getLogger().error(`[clientHook:${name}] vetoable handler threw`, error);\n continue;\n }\n if (result?.stop) {\n return { stopped: true, signal: result };\n }\n }\n return { stopped: false };\n}\n\n/** Test helper — drop every registered handler. Not part of the public API. */\nexport function _resetClientHooksForTests(): void {\n for (const key of Object.keys(handlerSets) as ClientHookName[]) {\n handlerSets[key]?.clear();\n }\n}\n","import { Socket } from \"socket.io-client\";\nimport { getProjectConfig } from \"./projectConfig\";\nimport { getLogger } from \"./loggerRegistry\";\nimport tryCatchSync from \"./tryCatchSync\";\nimport { dispatchClientHook } from \"./clientHookBus\";\n\n/** Why a queued item was dropped (handed to its `onDrop` callback). */\nexport type QueueDropReason = 'expired' | 'queue-full';\n\ninterface ApiQueueItem {\n id: string;\n key: string;\n run: (socketInstance: Socket) => void;\n createdAt: number;\n /**\n * Per-request override of `projectConfig.offlineQueue.dropPolicy`. See\n * `SyncQueueItem.dropPolicy` for details.\n */\n dropPolicy?: 'drop-oldest' | 'drop-newest' | 'reject';\n /**\n * Optional callback invoked when THIS item is dropped (evicted for age or\n * because the queue was full / rejected) instead of ever running (SYNC-09).\n * The transport wires this to settle the pending `syncRequest`/`apiRequest`\n * promise with an error envelope, so an evicted offline request resolves\n * rather than hanging forever. Invoked at most once; failures are swallowed.\n */\n onDrop?: (reason: QueueDropReason) => void;\n}\n\ninterface SyncQueueItem {\n id: string;\n key: string;\n run: (socketInstance: Socket) => void;\n createdAt: number;\n /**\n * Per-request override of `projectConfig.offlineQueue.dropPolicy`. Lets a\n * specific sync (\"editor cursor move\") pick `'drop-oldest'` while the app\n * default stays `'reject'` for safer sends. When omitted, falls back to\n * the global config.\n */\n dropPolicy?: 'drop-oldest' | 'drop-newest' | 'reject';\n /** See {@link ApiQueueItem.onDrop} (SYNC-09). */\n onDrop?: (reason: QueueDropReason) => void;\n}\n\nconst apiQueue: ApiQueueItem[] = [];\nconst syncQueue: SyncQueueItem[] = [];\n\n//? Independent flush guards so a long api flush doesn't no-op a concurrent\n//? sync flush (or vice versa).\nlet isFlushingApi = false;\nlet isFlushingSync = false;\n\nexport const isOnline = () => {\n if (typeof navigator === \"undefined\") return true;\n return navigator.onLine;\n};\n\n//? Common drop shape — every queue item the framework drops carries these.\ninterface DroppableItem {\n createdAt: number;\n key: string;\n dropPolicy?: 'drop-oldest' | 'drop-newest' | 'reject';\n onDrop?: (reason: QueueDropReason) => void;\n}\n\n//? Notify a dropped item's owner exactly once. Swallows callback errors so a\n//? throwing `onDrop` can't wedge the eviction/enqueue loop (SYNC-09).\nconst notifyDropped = (item: DroppableItem, reason: QueueDropReason): void => {\n if (!item.onDrop) return;\n tryCatchSync(() => { item.onDrop?.(reason); });\n};\n\n//? Dispatch the `queueItemDropped` client hook, guarded so a misbehaving\n//? handler set can't interrupt the eviction/enqueue loop (CORE-N8).\nconst safeDispatchDropHook = (\n queue: 'api' | 'sync',\n key: string,\n reason: QueueDropReason,\n dropPolicy: 'drop-oldest' | 'drop-newest' | 'reject',\n): void => {\n tryCatchSync(() => {\n dispatchClientHook('queueItemDropped', { queue, key, reason, dropPolicy });\n });\n};\n\nconst evictExpired = (\n queue: DroppableItem[],\n label: 'api' | 'sync',\n): void => {\n const { maxAgeMs, dropPolicy: globalPolicy } = getProjectConfig().offlineQueue;\n if (maxAgeMs <= 0) return;\n const cutoff = Date.now() - maxAgeMs;\n for (let i = queue.length - 1; i >= 0; i -= 1) {\n const item = queue[i];\n if (item && item.createdAt < cutoff) {\n queue.splice(i, 1);\n notifyDropped(item, 'expired');\n safeDispatchDropHook(label, item.key, 'expired', item.dropPolicy ?? globalPolicy);\n }\n }\n};\n\nconst enqueueWithPolicy = <T extends DroppableItem>(\n queue: T[],\n item: T,\n label: 'api' | 'sync',\n): boolean => {\n evictExpired(queue, label);\n const { maxSize, dropPolicy: globalPolicy } = getProjectConfig().offlineQueue;\n //? Per-request override wins over the global policy. Lets specific\n //? syncs pick 'drop-oldest' for liveness while the app default stays\n //? 'reject' for safer sends.\n const effectivePolicy = item.dropPolicy ?? globalPolicy;\n if (queue.length < maxSize) {\n queue.push(item);\n return true;\n }\n if (effectivePolicy === 'drop-oldest') {\n const dropped = queue.shift();\n queue.push(item);\n getLogger().debug(`offlineQueue:${label} full — dropped oldest item (policy=${effectivePolicy})`);\n if (dropped) {\n notifyDropped(dropped, 'queue-full');\n safeDispatchDropHook(label, dropped.key, 'queue-full', effectivePolicy);\n }\n return true;\n }\n if (effectivePolicy === 'drop-newest') {\n getLogger().debug(`offlineQueue:${label} full — dropped newest item (policy=${effectivePolicy})`);\n notifyDropped(item, 'queue-full');\n safeDispatchDropHook(label, item.key, 'queue-full', effectivePolicy);\n return false;\n }\n getLogger().warn(`offlineQueue:${label} full — rejecting enqueue (policy=${effectivePolicy})`);\n notifyDropped(item, 'queue-full');\n safeDispatchDropHook(label, item.key, 'queue-full', effectivePolicy);\n return false;\n};\n\nexport const enqueueApiRequest = (item: ApiQueueItem): boolean =>\n enqueueWithPolicy(apiQueue, item, 'api');\n\nexport const enqueueSyncRequest = (item: SyncQueueItem): boolean =>\n enqueueWithPolicy(syncQueue, item, 'sync');\n\nexport const removeApiQueueItem = (id: string) => {\n const index = apiQueue.findIndex((item) => item.id === id);\n if (index !== -1) {\n apiQueue.splice(index, 1);\n }\n};\n\nexport const removeSyncQueueItem = (id: string) => {\n const index = syncQueue.findIndex((item) => item.id === id);\n if (index !== -1) {\n syncQueue.splice(index, 1);\n }\n};\n\nexport const removeApiQueueItemsByKey = (key: string) => {\n for (let i = apiQueue.length - 1; i >= 0; i -= 1) {\n if (apiQueue[i]?.key === key) {\n apiQueue.splice(i, 1);\n }\n }\n};\n\n//? Run one dequeued item. If `run` throws, requeue it at the FRONT (so the\n//? next flush retries it in order) and signal the caller to stop this flush —\n//? otherwise a throwing item is silently lost AND the `isFlushing*` guard\n//? would be left stuck `true`, wedging every future flush.\nconst runQueueItem = <T extends { run: (s: Socket) => void }>(\n queue: T[],\n item: T,\n socketInstance: Socket,\n label: string,\n): boolean => {\n const [error] = tryCatchSync(() => { item.run(socketInstance); });\n if (error) {\n queue.unshift(item);\n getLogger().warn(`offlineQueue:${label} run threw — requeued item, pausing flush`, { error });\n return false;\n }\n return true;\n};\n\nexport const flushApiQueue = (canRun: () => boolean, socketInstance: Socket) => {\n if (isFlushingApi) return;\n evictExpired(apiQueue, 'api');\n if (apiQueue.length === 0) return;\n if (!canRun()) return;\n\n isFlushingApi = true;\n while (apiQueue.length > 0) {\n if (!canRun()) break;\n const item = apiQueue.shift();\n if (item && !runQueueItem(apiQueue, item, socketInstance, 'api')) break;\n }\n isFlushingApi = false;\n};\n\nexport const flushSyncQueue = (canRun: () => boolean, socketInstance: Socket) => {\n if (isFlushingSync) return;\n evictExpired(syncQueue, 'sync');\n if (syncQueue.length === 0) return;\n if (!canRun()) return;\n\n isFlushingSync = true;\n while (syncQueue.length > 0) {\n if (!canRun()) break;\n const item = syncQueue.shift();\n if (item && !runQueueItem(syncQueue, item, socketInstance, 'sync')) break;\n }\n isFlushingSync = false;\n};\n\nexport const getApiQueueSize = () => apiQueue.length;\nexport const getSyncQueueSize = () => syncQueue.length;\n","export interface ErrorParam {\n key: string;\n value: string | number | boolean;\n}\n\nexport interface ErrorResponseInput {\n status?: unknown;\n errorCode?: unknown;\n errorParams?: unknown;\n httpStatus?: unknown;\n}\n\nexport interface NormalizedErrorResponse {\n status: 'error';\n message: string;\n errorCode: string;\n errorParams?: ErrorParam[];\n httpStatus?: number;\n}\n\nexport const INVALID_ERROR_RESPONSE_CODE = 'error.invalidResponse';\n\nexport const isErrorParamArray = (value: unknown): value is ErrorParam[] => {\n return Array.isArray(value) && value.every((item) => {\n return (\n !!item\n && typeof item === 'object'\n && typeof (item as ErrorParam).key === 'string'\n && ['string', 'number', 'boolean'].includes(typeof (item as ErrorParam).value)\n );\n });\n};\n\nexport const normalizeErrorResponseCore = ({\n response,\n fallbackHttpStatus,\n fallbackErrorCode,\n resolveMessage,\n}: {\n response: ErrorResponseInput;\n fallbackHttpStatus?: number;\n fallbackErrorCode?: string;\n resolveMessage?: (args: { errorCode: string; errorParams?: ErrorParam[] }) => string;\n}): NormalizedErrorResponse => {\n const normalizedParams = isErrorParamArray(response.errorParams) ? response.errorParams : undefined;\n const errorCodeValue = typeof response.errorCode === 'string' ? response.errorCode.trim() : '';\n const hasErrorCode = errorCodeValue.length > 0;\n const finalErrorCode = hasErrorCode ? errorCodeValue : (fallbackErrorCode ?? INVALID_ERROR_RESPONSE_CODE);\n const providedHttpStatus = typeof response.httpStatus === 'number' ? response.httpStatus : undefined;\n\n const message = resolveMessage\n ? resolveMessage({ errorCode: finalErrorCode, errorParams: normalizedParams })\n : finalErrorCode;\n\n return {\n status: 'error',\n message,\n errorCode: finalErrorCode,\n errorParams: normalizedParams,\n httpStatus: providedHttpStatus ?? fallbackHttpStatus,\n };\n};\n\nexport const defaultHttpStatusForResponse = ({\n status,\n explicitHttpStatus,\n fallbackErrorStatus = 400,\n}: {\n status: 'success' | 'error';\n explicitHttpStatus?: number;\n fallbackErrorStatus?: number;\n}): number => {\n if (typeof explicitHttpStatus === 'number') return explicitHttpStatus;\n return status === 'success' ? 200 : fallbackErrorStatus;\n};\n","const VERSION_SEGMENT_REGEX = /^v\\d+$/;\n\nexport interface ServiceRouteParseSuccess {\n status: 'success';\n normalizedRouteName: string;\n service: string;\n routeName: string;\n}\n\nexport interface ServiceRouteParseError {\n status: 'error';\n reason: string;\n}\n\nexport type ServiceRouteParseResult = ServiceRouteParseSuccess | ServiceRouteParseError;\n\nexport interface TransportRouteParseSuccess {\n status: 'success';\n normalizedFullName: string;\n version: string;\n serviceRoute: ServiceRouteParseSuccess;\n}\n\nexport interface TransportRouteParseError {\n status: 'error';\n reason: string;\n}\n\nexport type TransportRouteParseResult = TransportRouteParseSuccess | TransportRouteParseError;\n\nconst normalizeRawRoute = (value: string): string => {\n return value.trim().replaceAll('\\\\', '/').replaceAll(/^\\/+/g, '').replaceAll(/\\/+$/g, '');\n};\n\nconst hasEmptySegments = (value: string): boolean => {\n return value.split('/').some((segment) => segment.length === 0);\n};\n\nexport const parseServiceRouteName = (value: string): ServiceRouteParseResult => {\n const normalized = normalizeRawRoute(value);\n if (!normalized) {\n return { status: 'error', reason: 'Route name cannot be empty.' };\n }\n\n if (hasEmptySegments(normalized)) {\n return { status: 'error', reason: 'Route name cannot contain empty segments.' };\n }\n\n const segments = normalized.split('/');\n if (segments.length < 2) {\n return { status: 'error', reason: 'Route name must include service and route segments.' };\n }\n\n const [service, ...routeSegments] = segments;\n const routeName = routeSegments.join('/');\n\n if (!service || !routeName) {\n return { status: 'error', reason: 'Route name must include service and route segments.' };\n }\n\n return {\n status: 'success',\n normalizedRouteName: `${service}/${routeName}`,\n service,\n routeName,\n };\n};\n\nexport const parseTransportRouteName = ({\n value,\n prefix,\n}: {\n value: string;\n prefix: 'api' | 'sync';\n}): TransportRouteParseResult => {\n const normalized = normalizeRawRoute(value);\n if (!normalized) {\n return { status: 'error', reason: 'Transport route cannot be empty.' };\n }\n\n if (hasEmptySegments(normalized)) {\n return { status: 'error', reason: 'Transport route cannot contain empty segments.' };\n }\n\n const segments = normalized.split('/');\n const routeSegments = segments[0] === prefix ? segments.slice(1) : segments;\n\n if (routeSegments.length < 3) {\n return {\n status: 'error',\n reason: `Transport route must use ${prefix}/{service}/{name}/{version} format.`,\n };\n }\n\n const version = routeSegments.at(-1);\n if (!version || !VERSION_SEGMENT_REGEX.test(version)) {\n return { status: 'error', reason: 'Route version segment must match v{number}.' };\n }\n\n const serviceRouteToken = routeSegments.slice(0, -1).join('/');\n const serviceRoute = parseServiceRouteName(serviceRouteToken);\n if (serviceRoute.status === 'error') {\n return {\n status: 'error',\n reason: serviceRoute.reason,\n };\n }\n\n return {\n status: 'success',\n normalizedFullName: `${prefix}/${serviceRoute.normalizedRouteName}/${version}`,\n version,\n serviceRoute,\n };\n};\n","const withIndex = (prefix: string, responseIndex: number | string): string => {\n return `${prefix}${String(responseIndex)}`;\n};\n\nexport const socketEventNames = {\n apiRequest: 'apiRequest',\n apiCancel: 'apiCancel',\n sync: 'sync',\n syncCancel: 'syncCancel',\n joinRoom: 'joinRoom',\n leaveRoom: 'leaveRoom',\n getJoinedRooms: 'getJoinedRooms',\n updateLocation: 'updateLocation',\n updateSession: 'updateSession',\n sessionReplaced: 'sessionReplaced',\n logout: 'logout',\n\n intentionalDisconnect: 'intentionalDisconnect',\n intentionalReconnect: 'intentionalReconnect',\n //? Client -> server activity heartbeat (mouse/keyboard/touch), throttled.\n //? Drives the server-side activity sampler that fires registered activity\n //? events (e.g. the built-in AFK detector).\n activity: 'activity',\n userAfk: 'userAfk',\n userBack: 'userBack',\n //? Emitted to a room's remaining members when a peer leaves — hard disconnect\n //? (socket close) or grace-expiry (presence MIS-003). Lets clients prune a\n //? departed peer from their roster without polling. The presence package owns\n //? the dispatch; core owns the wire-event name so client + server can't drift.\n userLeft: 'userLeft',\n\n connect: 'connect',\n disconnect: 'disconnect',\n reconnectAttempt: 'reconnect_attempt',\n connectError: 'connect_error',\n\n apiResponsePrefix: 'apiResponse-',\n apiStreamPrefix: 'apiStream-',\n syncResponsePrefix: 'sync-',\n syncProgressPrefix: 'sync-progress-',\n joinRoomResponsePrefix: 'joinRoom-',\n leaveRoomResponsePrefix: 'leaveRoom-',\n getJoinedRoomsResponsePrefix: 'getJoinedRooms-',\n} as const;\n\nexport const buildApiResponseEventName = (responseIndex: number | string): string => {\n return withIndex(socketEventNames.apiResponsePrefix, responseIndex);\n};\n\nexport const buildApiStreamEventName = (responseIndex: number | string): string => {\n return withIndex(socketEventNames.apiStreamPrefix, responseIndex);\n};\n\nexport const buildSyncResponseEventName = (responseIndex: number | string): string => {\n return withIndex(socketEventNames.syncResponsePrefix, responseIndex);\n};\n\nexport const buildSyncProgressEventName = (responseIndex: number | string): string => {\n return withIndex(socketEventNames.syncProgressPrefix, responseIndex);\n};\n\nexport const buildJoinRoomResponseEventName = (responseIndex: number | string): string => {\n return withIndex(socketEventNames.joinRoomResponsePrefix, responseIndex);\n};\n\nexport const buildLeaveRoomResponseEventName = (responseIndex: number | string): string => {\n return withIndex(socketEventNames.leaveRoomResponsePrefix, responseIndex);\n};\n\nexport const buildGetJoinedRoomsResponseEventName = (responseIndex: number | string): string => {\n return withIndex(socketEventNames.getJoinedRoomsResponsePrefix, responseIndex);\n};\n","//? CSRF configuration registry. The framework's CSRF middleware\n//? (`packages/server/src/httpRoutes/csrfMiddleware.ts`) and the\n//? client-side fetch wrapper (`packages/core/src/csrf.ts`) both consult\n//? `getCsrfConfig()` so consumers can change the header name, cookie\n//? name, token length, or cookie options without forking.\n//?\n//? The default values match the framework's pre-registry hardcodes\n//? (header `x-csrf-token`, 32-byte hex token minted at session create) so\n//? consumers who never call `registerCsrfConfig` get the historical\n//? behaviour unchanged.\n\nimport { createRegistry } from './createRegistry';\n\nexport interface CsrfCookieOptions {\n sameSite?: 'strict' | 'lax' | 'none';\n secure?: boolean;\n /**\n * Whether the login-absent double-submit cookie is HttpOnly. The client gets\n * the matching header value from the same-origin `GET /auth/csrf` JSON body,\n * so either value works; `false` remains the compatibility default.\n */\n httpOnly?: boolean;\n path?: string;\n maxAgeMs?: number;\n}\n\nexport interface CsrfConfig {\n /** Cookie name used to deliver the CSRF token to the browser. */\n cookieName: string;\n /** Request-header name the client attaches on state-changing requests. */\n headerName: string;\n /** Length in bytes of the random token minted by the session layer. */\n tokenLength: number;\n cookieOptions: CsrfCookieOptions;\n}\n\nexport const DEFAULT_CSRF_CONFIG: CsrfConfig = {\n cookieName: 'csrf-token',\n headerName: 'x-csrf-token',\n tokenLength: 32,\n cookieOptions: {\n sameSite: 'lax',\n //? `secure` intentionally UNSET so it resolves per-environment at serialize\n //? time (csrfRoute.ts) the SAME way the session cookie does — emit `Secure` in\n //? prod (SECURE=true) but NOT over plain HTTP in dev. A hardcoded `true` made\n //? the browser drop the login-absent double-submit cookie over http://, so\n //? every state-changing request 403'd. Force it on explicitly via\n //? `registerCsrfConfig({ cookieOptions: { secure: true } })` if desired.\n httpOnly: false,\n path: '/',\n maxAgeMs: 24 * 60 * 60 * 1000,\n },\n};\n\nconst registry = createRegistry<CsrfConfig, Partial<CsrfConfig>>(DEFAULT_CSRF_CONFIG, {\n //? Merge shallowly with the CURRENT config; `cookieOptions` is deep-merged\n //? so a partial override of (say) `sameSite` does not clobber `path` /\n //? `maxAgeMs`. Last-write-wins, and successive calls accumulate.\n transform: (input, current) => ({\n ...current,\n ...input,\n cookieOptions: { ...current.cookieOptions, ...input.cookieOptions },\n }),\n});\n\n/**\n * Override one or more CSRF settings. Merges shallowly with the current\n * config; `cookieOptions` is deep-merged so a partial override of (say)\n * `sameSite` does not clobber `path` / `maxAgeMs`. Last-write-wins.\n */\nexport const registerCsrfConfig = (input: Partial<CsrfConfig>): void => {\n registry.register(input);\n};\n\n/** Read the active config at call time (never at module load). */\nexport const getCsrfConfig = (): CsrfConfig => registry.get();\n\n/** Test-only — restore defaults between scenarios. */\nexport const resetCsrfConfigForTests = (): void => {\n registry.reset();\n};\n","import { captureException } from './sentrySetup';\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 captureException(error, context);\n return [error instanceof Error ? error : new Error(String(error)), null];\n }\n}\n","//? Client-side CSRF helper. Lazily fetches and caches the session's CSRF\n//? token from `/auth/csrf`, then attaches it as `x-csrf-token` on\n//? subsequent HTTP fetches in cookie mode.\n//?\n//? Token-mode sessions are CSRF-immune because cross-origin POSTs do not\n//? auto-attach the sessionStorage value; the cache simply stays empty in\n//? that mode.\n\nimport { getCsrfConfig } from './csrfConfig';\nimport { getProjectConfig } from './projectConfig';\nimport { socket } from './socketState';\nimport tryCatch from './tryCatch';\nimport tryCatchSync from './tryCatchSync';\n\n//? Tokens are scoped to the HTTP invocation origin. In routed-http mode the\n//? Socket.io connection may terminate on a remote `system` service while the\n//? invocation goes same-origin through a local router; a single socket-derived\n//? cache would fetch the CSRF token from the wrong ingress.\nconst cachedTokens = new Map<string, string>();\nconst inflightFetches = new Map<string, Promise<string | null>>();\n\nconst resolveSocketOrigin = (): string => socket?.io.opts.hostname\n ? `${socket.io.opts.secure ? 'https' : 'http'}://${socket.io.opts.hostname}${socket.io.opts.port ? `:${socket.io.opts.port}` : ''}`\n : '';\n\nconst resolveRequestOrigin = (input?: RequestInfo | URL): string => {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- SSR runtime guard\n const browserOrigin = globalThis.window !== undefined && globalThis.location?.origin\n ? globalThis.location.origin\n : '';\n if (input !== undefined) {\n let raw: string;\n if (typeof input === 'string') raw = input;\n else if (input instanceof URL) raw = input.href;\n else raw = input.url;\n const fallbackOrigin = browserOrigin.length > 0 ? browserOrigin : resolveSocketOrigin();\n const [error, parsed] = tryCatchSync(() => new URL(raw, fallbackOrigin));\n if (!error && parsed) return parsed.origin;\n }\n return browserOrigin.length > 0 ? browserOrigin : resolveSocketOrigin();\n};\n\nconst fetchCsrfToken = async (origin: string): Promise<string | null> => {\n const base = origin;\n const [error, token] = await tryCatch<string | null, undefined>(async () => {\n const response = await fetch(`${base}/auth/csrf`, {\n method: 'GET',\n credentials: 'include',\n });\n if (!response.ok) return null;\n const body = (await response.json()) as { csrfToken?: string | null };\n return body.csrfToken ?? null;\n });\n if (error) return null;\n return token ?? null;\n};\n\n/**\n * Fetch (or return the cached) CSRF token for the active session. Returns\n * null in token mode or when no session exists. Callers should attach the\n * returned value as the `X-CSRF-Token` request header.\n */\nexport const getCsrfToken = async (origin = resolveRequestOrigin()): Promise<string | null> => {\n //? Token-mode sessions: skip entirely. The server doesn't enforce CSRF\n //? in token mode, and there's no value to attach.\n if (getProjectConfig().session.basedToken) {\n return null;\n }\n\n const cached = cachedTokens.get(origin);\n if (cached) return cached;\n const inflight = inflightFetches.get(origin);\n if (inflight) return inflight;\n\n const next = fetchCsrfToken(origin).then((token) => {\n if (token) cachedTokens.set(origin, token);\n inflightFetches.delete(origin);\n return token;\n });\n inflightFetches.set(origin, next);\n return next;\n};\n\n/** Drop the cached token. Call this on logout or when a 403 csrfMismatch is seen. */\nexport const clearCsrfToken = (): void => {\n cachedTokens.clear();\n inflightFetches.clear();\n};\n\nconst STATE_CHANGING = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);\n\nconst isCsrfMismatchResponse = async (response: Response): Promise<boolean> => {\n if (response.status !== 403) return false;\n const [error, isMismatch] = await tryCatch<boolean, undefined>(async () => {\n //? `response.clone()` is used here so the ORIGINAL response body stream is\n //? preserved for the caller (the clone is consumed, the original is not).\n //? This is important: `httpFetch` returns the original `response` reference\n //? to the caller so it can read its body, and cloning before reading is the\n //? correct way to peek at the body without consuming it.\n const cloned = response.clone();\n const body = (await cloned.json()) as { errorCode?: string };\n return body.errorCode === 'auth.csrfMismatch';\n });\n if (error) return false;\n return isMismatch ?? false;\n};\n\n/**\n * Drop-in replacement for `fetch` that automatically attaches the framework's\n * `X-CSRF-Token` and `X-Request-Id` headers to state-changing requests in\n * cookie mode. Use this for any project-side HTTP call that hits a\n * LuckyStack `/api/*`, `/sync/*`, or `/auth/api/*` endpoint.\n *\n * Behavior:\n * - GET / OPTIONS / HEAD: passes through without CSRF (read-only).\n * - Token mode: passes through without CSRF (immune by design).\n * - Cookie mode + state-changing method: lazily fetches `/auth/csrf` once,\n * caches, attaches as `x-csrf-token`. On a 403 `auth.csrfMismatch`\n * response, clears the cache and retries once.\n * - `credentials: 'include'` is forced unless the caller overrode it.\n *\n * @example\n * import { httpFetch } from '@luckystack/core/client';\n * const res = await httpFetch('/api/system/myRoute/v1', {\n * method: 'POST',\n * body: JSON.stringify({ ... }),\n * });\n */\nexport const httpFetch: typeof fetch = async (input, init = {}) => {\n const method = (init.method ?? 'GET').toUpperCase();\n const headers = new Headers(init.headers);\n const config = getProjectConfig();\n if (config.session.basedToken && !headers.has('Authorization')) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- SSR runtime guard\n const token = globalThis.window === undefined\n ? null\n : tryCatchSync(() => globalThis.sessionStorage.getItem('token'))[1];\n if (token) headers.set('Authorization', `Bearer ${token}`);\n }\n if (!headers.has('Content-Type') && init.body && typeof init.body === 'string') {\n headers.set('Content-Type', 'application/json');\n }\n\n const csrfHeaderName = getCsrfConfig().headerName;\n const send = async (csrfToken: string | null): Promise<Response> => {\n const finalHeaders = new Headers(headers);\n if (csrfToken && STATE_CHANGING.has(method) && !finalHeaders.has(csrfHeaderName)) {\n finalHeaders.set(csrfHeaderName, csrfToken);\n }\n return fetch(input, {\n ...init,\n method,\n headers: finalHeaders,\n credentials: init.credentials ?? 'include',\n });\n };\n\n if (!STATE_CHANGING.has(method) || config.session.basedToken) {\n return send(null);\n }\n\n const requestOrigin = resolveRequestOrigin(input);\n const token = await getCsrfToken(requestOrigin);\n let response = await send(token);\n\n //? On csrfMismatch, the cached token is stale (session rotated). Clear and\n //? retry ONCE with a fresh fetch — covers the case where the user logged\n //? back in while a tab was idle. The retry is intentionally limited to one\n //? attempt: a second csrfMismatch means the session is broken in a way a\n //? fresh token won't fix (e.g. session expired), and retrying would loop.\n if (await isCsrfMismatchResponse(response)) {\n clearCsrfToken();\n const refreshed = await getCsrfToken(requestOrigin);\n if (refreshed) {\n response = await send(refreshed);\n }\n }\n\n return response;\n};\n","//? The GET half of the routed-HTTP wire contract: a GET keeps its declared\n//? method, so its payload can only ride the query string. The client\n//? (`routedHttpInvocation.ts`) and the test-runner's Layer-5 `callApi` both\n//? build that URL here, so the reserved key cannot drift between them. The\n//? server reads the same key in `@luckystack/server` (`apiRoute.ts`).\n//?\n//? Import-free on purpose: the root `@luckystack/core` entry is server-safe\n//? and must not pull the browser-only client modules in.\n\nexport const ROUTED_DATA_QUERY_KEY = '__luckystack_data';\n\n/**\n * Append `data` to `path` as the reserved `__luckystack_data` query value\n * (JSON-encoded), plus any `extraParams`. Tolerates a `path` that already\n * carries a query string.\n */\nexport const buildRoutedGetUrl = (\n path: string,\n data: unknown,\n extraParams?: Record<string, string>,\n): string => {\n const params = new URLSearchParams();\n params.set(ROUTED_DATA_QUERY_KEY, JSON.stringify(data));\n for (const [key, value] of Object.entries(extraParams ?? {})) params.set(key, value);\n const separator = path.includes('?') ? '&' : '?';\n return `${path}${separator}${params.toString()}`;\n};\n","export default function sleep(ms: number) {\n return new Promise<void>((resolve) => setTimeout(resolve, ms));\n}\n","//? Pure page-route validator. Lives in @luckystack/core (no Node deps) so\n//? both the client-side router (`src/main.tsx`'s `getRoutes()`) AND the\n//? devkit-side scaffold CLI / hot-reload validator can consume it through\n//? the same single source of truth.\n//?\n//? Implements the invisible-parent folder convention: a folder starting\n//? with `privateFolderPrefix` is stripped from the URL but its CHILDREN\n//? remain routeable. A `page.tsx` placed directly inside such a folder\n//? (no non-private sibling segment) is invalid because it has no URL.\n//?\n//? Reserved framework folders (`_api`, `_sync`, `_components`, …) NEVER\n//? host a page, even nested — placing `page.tsx` anywhere under one of\n//? them is a hard error.\n\nexport interface PageRouteRules {\n /**\n * Single-character prefix that marks a folder as **invisible-parent** for\n * page routing. Default: `'_'`.\n */\n privateFolderPrefix: string;\n /**\n * Folder names that are reserved for framework-internal use and may NEVER\n * host a `page.tsx`, nested or otherwise. Scaffold + page-discovery emit\n * a hard error when a page is placed inside one.\n */\n scaffoldIgnoredFolders: readonly string[];\n}\n\nexport const DEFAULT_PAGE_ROUTE_RULES: PageRouteRules = {\n privateFolderPrefix: '_',\n scaffoldIgnoredFolders: [\n '_api',\n '_sync',\n '_function',\n '_functions',\n '_component',\n '_components',\n '_provider',\n '_providers',\n '_locale',\n '_locales',\n '_socket',\n '_sockets',\n '_shared',\n '_server',\n ],\n};\n\nexport interface PagePathValidationResult {\n /** `true` when the page file produces a routeable URL. */\n valid: boolean;\n /** Computed URL when `valid`. Always begins with `/`. `/` for root page. */\n route?: string;\n /** Human-readable explanation when `!valid`. */\n reason?: string;\n}\n\n/**\n * Validate a `page.tsx` file path relative to `src/`. Accepts both\n * forward and back slashes, with or without a leading `./` or `/`.\n * The filename **must** be `page.tsx` (or `page.jsx`); other filenames\n * return `valid: false`.\n *\n * Examples (defaults):\n * admin/page.tsx -> { valid: true, route: '/admin' }\n * _housing/renting/page.tsx -> { valid: true, route: '/renting' }\n * _housing/page.tsx -> { valid: false, reason: 'no URL segment left after stripping underscore folders' }\n * _api/something/page.tsx -> { valid: false, reason: 'page.tsx cannot live inside reserved folder _api' }\n * page.tsx -> { valid: true, route: '/' }\n * some/route.tsx -> { valid: false, reason: 'not a page file (expected page.tsx)' }\n */\nexport const validatePagePath = (\n srcRelativePath: string,\n rules: PageRouteRules = DEFAULT_PAGE_ROUTE_RULES,\n): PagePathValidationResult => {\n const normalized = srcRelativePath.replaceAll('\\\\', '/').replace(/^\\.\\//, '').replace(/^\\/+/, '');\n const segments = normalized.split('/').filter((segment) => segment.length > 0);\n\n if (segments.length === 0) {\n return { valid: false, reason: 'empty path' };\n }\n\n const filename = segments.at(-1);\n if (filename !== 'page.tsx' && filename !== 'page.jsx') {\n return { valid: false, reason: 'not a page file (expected page.tsx)' };\n }\n\n const folderSegments = segments.slice(0, -1);\n const prefix = rules.privateFolderPrefix;\n const reserved = rules.scaffoldIgnoredFolders;\n\n for (const reservedName of reserved) {\n if (folderSegments.includes(reservedName)) {\n return { valid: false, reason: `page.tsx cannot live inside reserved folder ${reservedName}` };\n }\n }\n\n const visibleSegments = folderSegments.filter((segment) => !segment.startsWith(prefix));\n\n if (folderSegments.length > 0 && visibleSegments.length === 0) {\n return { valid: false, reason: 'no URL segment left after stripping underscore folders' };\n }\n\n const route = visibleSegments.length === 0 ? '/' : `/${visibleSegments.join('/')}`;\n return { valid: true, route };\n};\n"],"mappings":";;;;;;;;;;AAiBA,IAAM,WAAW,eAAoC,IAAI;AAElD,IAAM,uBAAuB,CAAC,QAA4B;AAC/D,WAAS,SAAS,GAAG;AACvB;AAEO,IAAM,yBAAyB,CACpC,UACA,SACA,YACkC;AAClC,QAAM,YAAY,SAAS,IAAI;AAC/B,MAAI,CAAC,UAAW,QAAO;AAKvB,SAAO,UAAU,QAAQ,IAAI,OAAO,IAAI,OAAO;AACjD;AAEO,IAAM,2BAA2B,MAAe,SAAS,aAAa;;;ACrBtE,IAAM,kBAAkB,CAAC,oBAC9B,gBAAgB,WAAW,KAAK,KAChC,gBAAgB,WAAW,OAAO,KAClC,gBAAgB,WAAW,MAAM;AAmB5B,IAAM,kBAAkB,CAAC,YAAgC;AAE9D,QAAM,YAAY,QAAQ,MAAM,GAAG;AACnC,QAAM,WAAW,UAAU,GAAG,EAAE,GAAG,YAAY,KAAK;AACpD,QAAM,aAAa,SAAS,KAAK,QAAQ,KACpC,UAAU,GAAG,EAAE,KAAK,IAAI,YAAY,IACrC;AAEJ,MAAI,gBAAgB,UAAU,GAAG;AAC/B,WAAO;AAAA,EACT;AAEA,MAAI,WAAW,WAAW,QAAQ,KAAK,WAAW,WAAW,QAAQ,GAAG;AAC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EAAE;AAC3C,QAAM,SAAS,MAAM;AACrB,QAAM,WAAW,MAAM;AAEvB,aAAW,gBAAgB,UAAU;AACnC,QAAI,eAAe,SAAS,YAAY,GAAG;AACzC,aAAO,EAAE,OAAO,OAAO,QAAQ,+CAA+C,YAAY,GAAG;AAAA,IAC/F;AAAA,EACF;AAEA,QAAM,kBAAkB,eAAe,OAAO,CAAC,YAAY,CAAC,QAAQ,WAAW,MAAM,CAAC;AAEtF,MAAI,eAAe,SAAS,KAAK,gBAAgB,WAAW,GAAG;AAC7D,WAAO,EAAE,OAAO,OAAO,QAAQ,yDAAyD;AAAA,EAC1F;AAEA,QAAM,QAAQ,gBAAgB,WAAW,IAAI,MAAM,IAAI,gBAAgB,KAAK,GAAG,CAAC;AAChF,SAAO,EAAE,OAAO,MAAM,MAAM;AAC9B;","names":["registry","responseIndex","registry","token"]}
package/dist/client.d.ts CHANGED
@@ -1,335 +1,46 @@
1
- import { StreamPayload, ApiTypeMap } from './apiTypeStubs.js';
2
- export { SyncTypeMap } from './apiTypeStubs.js';
3
- import { H as HttpMethodLiteral } from './pageRouteValidation-B4Cmtfjv.js';
4
- export { A as ApiMethodMap, D as DEFAULT_PAGE_ROUTE_RULES, L as Logger, a as LoggerContext, N as Notifier, b as NotifyInput, c as NotifyParam, P as PagePathValidationResult, d as PageRouteRules, R as ROUTED_DATA_QUERY_KEY, S as SOCKETSTATUS, e as buildApiResponseEventName, f as buildApiStreamEventName, g as buildGetJoinedRoomsResponseEventName, h as buildJoinRoomResponseEventName, i as buildLeaveRoomResponseEventName, j as buildRoutedGetUrl, k as buildSyncProgressEventName, l as buildSyncResponseEventName, m as clearCsrfToken, n as enqueueApiRequest, o as enqueueSyncRequest, p as flushApiQueue, q as flushSyncQueue, r as getApiQueueSize, s as getCsrfToken, t as getLogger, u as getNotifier, v as getRegisteredApiMethod, w as getSyncQueueSize, x as httpFetch, y as incrementResponseIndex, z as isApiMethodMapRegistered, B as isOnline, C as normalizeErrorResponseCore, E as notify, F as parseServiceRouteName, G as registerApiMethodMap, I as registerLogger, J as registerNotifier, K as removeApiQueueItem, M as removeApiQueueItemsByKey, O as removeSyncQueueItem, Q as setSocket, T as sleep, U as socket, V as socketEventNames, W as statusContent, X as tryCatchSync, Y as validatePagePath, Z as waitForSocket } from './pageRouteValidation-B4Cmtfjv.js';
5
- import { B as BaseSessionLayout } from './sessionTypes-DanjuPaE.js';
6
- export { A as AppConfig, a as AuthProps, L as LoggingConfig, P as ProjectConfig, R as RateLimitingConfig, S as SessionConfig, b as SessionLocation, T as TransportConfig, g as getProjectConfig, i as isProjectConfigRegistered, r as registerProjectConfig } from './sessionTypes-DanjuPaE.js';
7
- import * as react from 'react';
8
- import { ReactNode, Dispatch, SetStateAction } from 'react';
9
- import 'socket.io-client';
10
-
11
- type ApiStreamEvent<T extends StreamPayload = StreamPayload> = T;
12
- type DataRequired<T> = Record<string, never> extends T ? false : true;
13
- type UnionToIntersection<U> = (U extends unknown ? (arg: U) => void : never) extends ((arg: infer I) => void) ? I : never;
14
- type ApiRouteRecord = UnionToIntersection<{
15
- [P in keyof ApiTypeMap]: {
16
- [N in keyof ApiTypeMap[P] as P extends 'root' ? `system/${Extract<N, string>}` : `${Extract<P, string>}/${Extract<N, string>}`]: ApiTypeMap[P][N];
17
- };
18
- }[keyof ApiTypeMap]>;
19
- type ApiFullName = Extract<keyof ApiRouteRecord, string>;
20
- type VersionsForFullName<F extends ApiFullName> = keyof ApiRouteRecord[F] & string;
21
- type Prettify<T> = {
22
- [K in keyof T]: T[K];
23
- } & {};
24
- type InputForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = ApiRouteRecord[F][V] extends {
25
- input: infer I;
26
- } ? I : never;
27
- type OutputForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = ApiRouteRecord[F][V] extends {
28
- output: infer O;
29
- } ? O : never;
30
- type StreamForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = ApiRouteRecord[F][V] extends {
31
- stream: infer S;
32
- } ? S : never;
33
- type ApiStreamCallbackForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = [
34
- StreamForFullName<F, V>
35
- ] extends [never] ? never : (event: ApiStreamEvent<Prettify<StreamForFullName<F, V> extends StreamPayload ? StreamForFullName<F, V> : StreamPayload>>) => void;
36
- type ApiParamsForFullName<F extends ApiFullName, V extends VersionsForFullName<F>> = DataRequired<InputForFullName<F, V>> extends true ? {
37
- name: F;
38
- version: V;
39
- data: Prettify<InputForFullName<F, V>>;
40
- abortable?: boolean;
41
- disableErrorMessage?: boolean;
42
- onStream?: ApiStreamCallbackForFullName<F, V>;
43
- signal?: AbortSignal;
44
- timeoutMs?: number | false;
45
- } : {
46
- name: F;
47
- version: V;
48
- data?: Prettify<InputForFullName<F, V>>;
49
- abortable?: boolean;
50
- disableErrorMessage?: boolean;
51
- onStream?: ApiStreamCallbackForFullName<F, V>;
52
- signal?: AbortSignal;
53
- timeoutMs?: number | false;
54
- };
55
- interface ApiErrorResponse extends Record<string, unknown> {
56
- status: 'error';
57
- httpStatus: number;
58
- message: string;
59
- errorCode: string;
60
- errorParams?: {
61
- key: string;
62
- value: string | number | boolean;
63
- }[];
64
- }
65
- /**
66
- * Type-safe API request function.
67
- *
68
- * @example
69
- * ```typescript
70
- * // Full name usage - includes page in the name
71
- * const result = await apiRequest({ name: 'examples/publicApi', version: 'v1', data: { message: 'hello' } });
72
- * // result is typed correctly for publicApi
73
- *
74
- * // Global APIs use service-first naming
75
- * await apiRequest({ name: 'system/session', version: 'v1' });
76
- * ```
77
- */
78
- declare function apiRequest<F extends ApiFullName, V extends VersionsForFullName<F>>(params: ApiParamsForFullName<F, V>): Promise<Prettify<OutputForFullName<F, V>> | ApiErrorResponse>;
79
-
80
- declare function tryCatch<T, P = void>(func: (values: P) => Promise<T> | T, params?: P, context?: Record<string, unknown>): Promise<[Error | null, T | null]>;
81
-
82
- type RoutedInvocationMethod = HttpMethodLiteral;
83
- interface RoutedInvocationResponse<TResponse> {
84
- kind: 'response';
85
- response: TResponse;
86
- httpStatus: number;
87
- }
88
- interface RoutedInvocationFailure {
89
- kind: 'aborted' | 'timeout' | 'network-error' | 'invalid-response';
90
- }
91
- type RoutedInvocationResult<TResponse> = RoutedInvocationResponse<TResponse> | RoutedInvocationFailure;
92
- interface RoutedHttpInvocationInput<TStream> {
93
- path: string;
94
- method: RoutedInvocationMethod;
95
- data: Record<string, unknown>;
96
- stream?: (payload: TStream) => void;
97
- signals?: readonly (AbortSignal | null | undefined)[];
98
- timeoutMs?: number | false;
99
- }
100
- declare const invokeRoutedHttp: <TResponse, TStream = Record<string, unknown>>({ path, method, data, stream, signals, timeoutMs, }: RoutedHttpInvocationInput<TStream>) => Promise<RoutedInvocationResult<TResponse>>;
101
-
102
- type LocalesMap = Record<string, unknown>;
103
- type LanguageSource = () => string | null | undefined;
104
- declare const registerLocales: (locales: LocalesMap) => void;
105
- declare const getRegisteredLocales: () => LocalesMap;
106
- declare const getDefaultLocale: () => string;
107
- declare const registerLanguageSource: (fn: LanguageSource) => void;
108
- declare const getActiveLanguage: () => string;
109
- declare const getLocaleByCode: (code: string) => unknown;
110
-
111
- interface MiddlewareInput {
112
- location: string;
113
- searchParams: Record<string, string>;
114
- session: BaseSessionLayout | null;
115
- }
116
- type MiddlewareResult = {
117
- success: true;
118
- redirect?: undefined;
119
- status?: undefined;
120
- } | {
121
- success: false;
122
- redirect: string;
123
- status?: undefined;
124
- } | {
125
- success: false;
126
- redirect?: undefined;
127
- status: number;
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
- };
141
- type MiddlewareHandler = (input: MiddlewareInput) => MiddlewareResult | Promise<MiddlewareResult>;
142
- declare const registerMiddlewareHandler: (handler: MiddlewareHandler) => void;
143
- declare const getMiddlewareHandler: () => MiddlewareHandler;
144
- type PageMiddleware<TSession extends BaseSessionLayout = BaseSessionLayout> = (input: {
145
- location: string;
146
- searchParams: Record<string, string>;
147
- session: TSession | null;
148
- }) => MiddlewareResult | Promise<MiddlewareResult>;
149
- declare const registerPageMiddleware: (path: string, middleware: PageMiddleware) => void;
150
- declare const getPageMiddleware: (path: string) => PageMiddleware | undefined;
151
- declare const hasPageMiddleware: (path: string) => boolean;
152
-
153
- interface ClientHookPayloadMap {
154
- preLogin: {
155
- candidateSession: BaseSessionLayout;
156
- };
157
- postLogin: {
158
- session: BaseSessionLayout;
159
- };
160
- postLogout: {
161
- previousSession: BaseSessionLayout;
162
- };
163
- queueItemDropped: {
164
- queue: 'api' | 'sync';
165
- key: string;
166
- reason: 'queue-full' | 'expired';
167
- dropPolicy: 'drop-oldest' | 'drop-newest' | 'reject';
168
- };
169
- }
170
- type ClientHookName = keyof ClientHookPayloadMap;
171
- interface ClientHookStopSignal {
172
- stop: true;
173
- errorCode: string;
174
- }
175
- type ClientHookResult = void | undefined | ClientHookStopSignal;
176
- type ClientDispatchResult = {
177
- stopped: false;
178
- } | {
179
- stopped: true;
180
- signal: ClientHookStopSignal;
181
- };
182
- type ClientHookHandler<N extends ClientHookName> = (payload: ClientHookPayloadMap[N]) => ClientHookResult | Promise<ClientHookResult>;
183
- /**
184
- * Subscribe to a client-side lifecycle hook. Returns an unsubscribe function
185
- * — call it to remove the handler (e.g. inside a React effect cleanup).
186
- *
187
- * Multiple handlers can be registered for the same hook; they all fire on
188
- * each dispatch. A handler that throws (sync) or rejects (async) is logged
189
- * to `console.error` and does not affect other handlers.
190
- */
191
- declare function registerClientHook<N extends ClientHookName>(name: N, handler: ClientHookHandler<N>): () => void;
192
- /**
193
- * Fire a client-side hook (fire-and-forget). Framework-internal — consumers
194
- * should not call this directly. Used for `post*` hooks where any stop-signal
195
- * returned by a handler is intentionally ignored: a `postLogin` listener that
196
- * tried to "stop" the framework would be too late — the transition already
197
- * happened. Use `dispatchVetoableClientHook` for `pre*` hooks where the
198
- * caller actually awaits the veto decision.
199
- */
200
- declare function dispatchClientHook<N extends ClientHookName>(name: N, payload: ClientHookPayloadMap[N]): void;
201
- /**
202
- * Awaits every registered handler for a `pre*` client hook. If any handler
203
- * returns a `ClientHookStopSignal`, dispatch short-circuits and returns
204
- * `{ stopped: true, signal }`; callers must respect the veto (skip the
205
- * pending action). Handlers that throw or reject are logged but treated as
206
- * `undefined` — a buggy handler must not silently block the user flow.
207
- *
208
- * Mirrors `dispatchHook` from `@luckystack/core` so consumer/framework code
209
- * can use the same stop-signal pattern on both sides of the wire.
210
- */
211
- declare function dispatchVetoableClientHook<N extends ClientHookName>(name: N, payload: ClientHookPayloadMap[N]): Promise<ClientDispatchResult>;
212
-
213
- interface ApiRequestInterceptorContext {
214
- /** Resolved route name (`<page>/<api>` or `system/<api>`). */
215
- name: string;
216
- /** Route version literal (e.g. `'v1'`). */
217
- version: string;
218
- /**
219
- * Outgoing request payload. Mutate this object in place to augment the
220
- * request (correlation id, feature-flag context, ...). Replacing the
221
- * reference has no effect — mutate keys on the existing object.
222
- */
223
- data: Record<string, unknown>;
224
- }
225
- interface ApiResponseInterceptorContext {
226
- name: string;
227
- version: string;
228
- /** The response envelope the caller is about to receive (read-only intent). */
229
- response: {
230
- status: 'success' | 'error';
231
- [key: string]: unknown;
232
- };
233
- }
234
- type ApiRequestInterceptor = (ctx: ApiRequestInterceptorContext) => void | Promise<void>;
235
- type ApiResponseInterceptor = (ctx: ApiResponseInterceptorContext) => void | Promise<void>;
236
- /**
237
- * Register an outgoing-request interceptor. Returns an unsubscribe function.
238
- * Multiple interceptors run in registration order; each may mutate `ctx.data`.
239
- */
240
- declare function registerApiRequestInterceptor(interceptor: ApiRequestInterceptor): () => void;
241
- /**
242
- * Register an incoming-response interceptor. Returns an unsubscribe function.
243
- */
244
- declare function registerApiResponseInterceptor(interceptor: ApiResponseInterceptor): () => void;
245
-
246
- interface SessionContextValue<TSession extends BaseSessionLayout = BaseSessionLayout> {
247
- session: TSession | null;
248
- sessionLoaded: boolean;
249
- }
250
- declare const SessionContext: react.Context<SessionContextValue<BaseSessionLayout>>;
251
- declare function useSession<TSession extends BaseSessionLayout = BaseSessionLayout>(): SessionContextValue<TSession>;
252
- declare const setLatestSession: (session: BaseSessionLayout | null) => void;
253
- declare const getCurrentSession: <TSession extends BaseSessionLayout = BaseSessionLayout>() => TSession | null;
254
- /**
255
- * Vetoable entry point for committing a null → session transition (i.e. a
256
- * fresh login or a page-load session restore). Dispatches the `preLogin`
257
- * client hook to every registered handler in parallel; if any returns a
258
- * stop signal, the transition is aborted and `{ committed: false, signal }`
259
- * is returned. Otherwise, `setLatestSession(session)` runs synchronously
260
- * (which fires `postLogin`) and `{ committed: true }` comes back.
261
- *
262
- * Consumer's `SessionProvider` should `await` this for non-null session
263
- * commits and roll local React state back to `null` when a veto comes
264
- * through, so the UI doesn't render a half-logged-in state.
265
- */
266
- type ProposeLoginResult = {
267
- stopped: false;
268
- committed: true;
269
- } | {
270
- stopped: true;
271
- signal: ClientHookStopSignal;
272
- committed: false;
273
- };
274
- declare const proposeLogin: (session: BaseSessionLayout) => Promise<ProposeLoginResult>;
275
-
276
- type AvatarStatus = 'avatar' | 'fallback';
277
- interface AvatarContextType {
278
- avatarStatuses: Record<string, AvatarStatus>;
279
- setAvatarStatus: (key: string, status: AvatarStatus) => void;
280
- }
281
- declare const AvatarProvider: ({ children }: {
282
- children: ReactNode;
283
- }) => react.JSX.Element;
284
- declare function useAvatarContext(): AvatarContextType;
285
-
286
- type Theme = 'light' | 'dark';
287
- declare const useTheme: () => {
288
- theme: Theme;
289
- setTheme: (next: Theme) => void;
290
- };
291
-
292
- type TranslationRecord = Record<string, unknown>;
293
- declare function TranslationProvider({ children }: {
294
- children: ReactNode;
295
- }): react.JSX.Element;
296
- declare function useTranslation(): TranslationRecord;
297
- declare function useUpdateLanguage(): Dispatch<SetStateAction<string>>;
298
- interface TranslateParam {
299
- key: string;
300
- value: string | number | boolean;
301
- }
302
- declare function translate({ translationList, key, params }: {
303
- translationList: TranslationRecord;
304
- key: unknown;
305
- params?: TranslateParam[];
306
- }): string;
307
- declare const useTranslator: () => ({ key, params }: {
308
- key: string;
309
- params?: TranslateParam[];
310
- }) => string;
311
-
312
- interface NotifyInput {
313
- key: string;
314
- params?: TranslateParam[];
315
- }
316
- declare const notify: {
317
- success: (input: NotifyInput) => void;
318
- error: (input: NotifyInput) => void;
319
- info: (input: NotifyInput) => void;
320
- warning: (input: NotifyInput) => void;
321
- };
322
-
323
- declare function Middleware({ children, denied, }: {
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);
331
- }): react.JSX.Element | null;
332
-
333
- declare function useRouter(): (path: string) => Promise<void>;
334
-
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 };
1
+ export { apiRequest } from './apiRequest.js';
2
+ export type { ApiStreamEvent, ApiErrorResponse } from './apiRequest.js';
3
+ export { default as sleep } from './sleep.js';
4
+ export { default as tryCatch } from './tryCatchClient.js';
5
+ export { default as tryCatchSync } from './tryCatchSync.js';
6
+ export { getProjectConfig, registerProjectConfig, isProjectConfigRegistered, } from './projectConfig.js';
7
+ export type { ProjectConfig, AppConfig, LoggingConfig, RateLimitingConfig, SessionConfig, TransportConfig, } from './projectConfig.js';
8
+ export { notify, registerNotifier, getNotifier } from './notifier.js';
9
+ export type { Notifier, NotifyInput, NotifyParam } from './notifier.js';
10
+ export { socket, setSocket, incrementResponseIndex, waitForSocket, } from './socketState.js';
11
+ export { isOnline, enqueueApiRequest, enqueueSyncRequest, removeApiQueueItem, removeSyncQueueItem, removeApiQueueItemsByKey, flushApiQueue, flushSyncQueue, getApiQueueSize, getSyncQueueSize, } from './offlineQueue.js';
12
+ export { normalizeErrorResponseCore } from './responseNormalizer.js';
13
+ export { getCsrfToken, clearCsrfToken, httpFetch } from './csrf.js';
14
+ export { invokeRoutedHttp } from './routedHttpInvocation.js';
15
+ export { ROUTED_DATA_QUERY_KEY, buildRoutedGetUrl } from './routedDataQuery.js';
16
+ export type { RoutedHttpInvocationInput, RoutedInvocationFailure, RoutedInvocationMethod, RoutedInvocationResponse, RoutedInvocationResult, } from './routedHttpInvocation.js';
17
+ export { parseServiceRouteName } from './serviceRoute.js';
18
+ export { buildApiResponseEventName, buildApiStreamEventName, buildSyncProgressEventName, buildSyncResponseEventName, buildJoinRoomResponseEventName, buildLeaveRoomResponseEventName, buildGetJoinedRoomsResponseEventName, socketEventNames, } from './socketEvents.js';
19
+ export type { statusContent, SOCKETSTATUS } from './socketStatusTypes.js';
20
+ export type { ApiTypeMap, SyncTypeMap, StreamPayload } from './apiTypeStubs.js';
21
+ export type { BaseSessionLayout, SessionLocation, AuthProps } from './sessionTypes.js';
22
+ export { getLogger, registerLogger } from './loggerRegistry.js';
23
+ export type { Logger, LoggerContext } from './loggerRegistry.js';
24
+ export { registerApiMethodMap, getRegisteredApiMethod, isApiMethodMapRegistered, } from './apiMethodMapRegistry.js';
25
+ export type { HttpMethodLiteral, ApiMethodMap } from './apiMethodMapRegistry.js';
26
+ export { registerLocales, getRegisteredLocales, getDefaultLocale, registerLanguageSource, getActiveLanguage, getLocaleByCode, } from './localesRegistry.js';
27
+ export type { LocalesMap, LanguageSource } from './localesRegistry.js';
28
+ export { registerMiddlewareHandler, getMiddlewareHandler, registerPageMiddleware, getPageMiddleware, hasPageMiddleware, } from './middlewareRegistry.js';
29
+ export type { MiddlewareInput, MiddlewareResult, MiddlewareOutcome, MiddlewareHandler, PageMiddleware, } from './middlewareRegistry.js';
30
+ export { registerClientHook, dispatchClientHook, dispatchVetoableClientHook, } from './clientHookBus.js';
31
+ export type { ClientHookName, ClientHookHandler, ClientHookPayloadMap, ClientHookStopSignal, ClientHookResult, ClientDispatchResult, } from './clientHookBus.js';
32
+ export { registerApiRequestInterceptor, registerApiResponseInterceptor, } from './apiInterceptors.js';
33
+ export type { ApiRequestInterceptor, ApiResponseInterceptor, ApiRequestInterceptorContext, ApiResponseInterceptorContext, } from './apiInterceptors.js';
34
+ export { validatePagePath, DEFAULT_PAGE_ROUTE_RULES, } from './pageRouteValidation.js';
35
+ export type { PageRouteRules, PagePathValidationResult, } from './pageRouteValidation.js';
36
+ export { SessionContext, useSession, setLatestSession, getCurrentSession, proposeLogin, } from './react/sessionContext.js';
37
+ export type { SessionContextValue } from './react/sessionContext.js';
38
+ export { AvatarProvider, useAvatarContext } from './react/AvatarProvider.js';
39
+ export type { AvatarStatus } from './react/AvatarProvider.js';
40
+ export { useTheme } from './react/useTheme.js';
41
+ export type { Theme } from './react/useTheme.js';
42
+ export { TranslationProvider, useTranslation, useUpdateLanguage, translate, useTranslator, } from './react/TranslationProvider.js';
43
+ export type { TranslationRecord, TranslateParam } from './react/TranslationProvider.js';
44
+ export { default as i18nNotify } from './react/notify.js';
45
+ export { default as Middleware } from './react/Middleware.js';
46
+ export { default as useRouter } from './react/Router.js';
package/dist/client.js CHANGED
@@ -43,11 +43,11 @@ import {
43
43
  tryCatchSync,
44
44
  validatePagePath,
45
45
  waitForSocket
46
- } from "./chunk-5FXBTGYL.js";
46
+ } from "./chunk-XDX5MV54.js";
47
47
  import {
48
48
  getLogger,
49
49
  registerLogger
50
- } from "./chunk-IJYNVM2W.js";
50
+ } from "./chunk-P3SSLA3E.js";
51
51
  import {
52
52
  getProjectConfig,
53
53
  isProjectConfigRegistered,
@@ -103,7 +103,7 @@ async function tryCatch(func, params, context) {
103
103
  const response = await func(params);
104
104
  return [null, response];
105
105
  } catch (error) {
106
- const { captureException } = await import("./sentrySetup-HNIURVUZ.js");
106
+ const { captureException } = await import("./sentrySetup-OLZ4BO7Q.js");
107
107
  captureException(error, context);
108
108
  return [error instanceof Error ? error : new Error(String(error)), null];
109
109
  }
@@ -818,12 +818,12 @@ var applyDomClass = (theme) => {
818
818
  };
819
819
  var useTheme = () => {
820
820
  const initialTheme = getProjectConfig().defaultTheme ?? "light";
821
- const [theme, setThemeState] = useState2(initialTheme);
821
+ const [themeState, setThemeState] = useState2(initialTheme);
822
822
  const setTheme = useCallback2((next) => {
823
823
  setThemeState(next);
824
824
  applyDomClass(next);
825
825
  }, []);
826
- return { theme, setTheme };
826
+ return { theme: themeState, setTheme };
827
827
  };
828
828
 
829
829
  // src/react/TranslationProvider.tsx