@luckystack/core 0.11.0 → 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.
- package/CHANGELOG.md +11 -0
- package/dist/{chunk-IJYNVM2W.js → chunk-P3SSLA3E.js} +2 -2
- package/dist/chunk-P3SSLA3E.js.map +1 -0
- package/dist/{chunk-5FXBTGYL.js → chunk-XDX5MV54.js} +2 -2
- package/dist/chunk-XDX5MV54.js.map +1 -0
- package/dist/client.js +3 -3
- package/dist/eslint/index.js +125 -8
- package/dist/eslint/index.js.map +1 -1
- package/dist/eslint/rules/no-untranslated-jsx-text.d.ts +4 -0
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/{sentrySetup-HNIURVUZ.js → sentrySetup-OLZ4BO7Q.js} +2 -2
- package/package.json +3 -3
- package/dist/chunk-5FXBTGYL.js.map +0 -1
- package/dist/chunk-IJYNVM2W.js.map +0 -1
- /package/dist/{sentrySetup-HNIURVUZ.js.map → sentrySetup-OLZ4BO7Q.js.map} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,17 @@ All notable changes to `@luckystack/core` are documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [0.12.0] - 2026-10-15
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **ESLint rule `luckystack/no-untranslated-jsx-text`** (`@luckystack/core/eslint`, on as a warning): text in JSX goes through the project translator. It replaces `react/jsx-no-literals` from `eslint-plugin-react`, which stopped at ESLint 9 and was kept for this one rule. Same behaviour as the options the scaffold ran it with: JSX text and string/template literals in a child `{…}` are reported, attribute values are not, and punctuation, digits and units such as `px` are allowed. `allowedStrings` replaces that allow-list. A disable for `react/jsx-no-literals` becomes `luckystack/no-untranslated-jsx-text`.
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
|
|
16
|
+
- The optional `eslint` peer accepts ESLint 9 and 10 (`^9.0.0 || ^10.0.0`), so a project already on ESLint 10 installs without a peer conflict. The bundled rules use no API that ESLint 10 removed.
|
|
17
|
+
- Requires Node.js 22.13 or newer (was 20). Node 20 stopped receiving security updates in April 2026, and the scaffold's lint toolchain (ESLint 10) needs 22.13.
|
|
18
|
+
|
|
8
19
|
## [0.11.0] - 2026-10-14
|
|
9
20
|
|
|
10
21
|
### Changed
|
|
@@ -163,7 +163,7 @@ var sanitizeErrorString = (value) => {
|
|
|
163
163
|
let result = value;
|
|
164
164
|
for (const key of getRedactedLogKeys()) {
|
|
165
165
|
const { urlParam, logLabel } = buildScrubPattern(key);
|
|
166
|
-
result = result.replace(urlParam, REDACTED_PLACEHOLDER).replace(logLabel, REDACTED_PLACEHOLDER);
|
|
166
|
+
result = result.replace(urlParam, () => REDACTED_PLACEHOLDER).replace(logLabel, () => REDACTED_PLACEHOLDER);
|
|
167
167
|
}
|
|
168
168
|
return result;
|
|
169
169
|
};
|
|
@@ -368,4 +368,4 @@ export {
|
|
|
368
368
|
setSentryUser,
|
|
369
369
|
startSpan
|
|
370
370
|
};
|
|
371
|
-
//# sourceMappingURL=chunk-
|
|
371
|
+
//# sourceMappingURL=chunk-P3SSLA3E.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/redactedLogKeys.ts","../src/loggerRegistry.ts","../src/errorTrackerRegistry.ts","../src/sentrySetup.ts"],"sourcesContent":["//? Registry of log keys that get masked when the framework prints request /\n//? response payloads. Feature packages register their domain-specific\n//? sensitive keys at boot (login → `password`, email → `apiKey`, etc.) so a\n//? consumer of the package never has to remember to extend a static list in\n//? core to keep their own data out of logs.\n//?\n//? Lookups are case-insensitive. Keys are merged with the framework defaults;\n//? `registerRedactedLogKeys` is additive — duplicate calls are idempotent.\n\nexport const DEFAULT_REDACTED_LOG_KEYS: readonly string[] = [\n 'password',\n 'confirmpassword',\n 'token',\n 'newtoken',\n 'authorization',\n 'cookie',\n 'set-cookie',\n 'csrftoken',\n 'apikey',\n 'secret',\n //? 2FA (ADR 0024). `totpSecret` already matches the `secret` suffix, but\n //? `recoveryCodes` matches neither the exact set nor any suffix — list it\n //? explicitly so the log-redaction floor mirrors the session sanitizer,\n //? which strips both `totpSecret` and `recoveryCodes`.\n 'recoverycodes',\n];\n\nconst redactedKeys = new Set<string>(DEFAULT_REDACTED_LOG_KEYS.map((key) => key.toLowerCase()));\n\n//? Sensitive SUFFIXES (0.2.0 widening). Exact-match alone missed compound keys\n//? a project naturally produces — `targetToken`, `sessionToken`, `clientSecret`,\n//? `stripeApiKey` — leaving real secrets in logs/breadcrumbs. A key whose\n//? lowercased form ENDS WITH one of these is redacted in addition to the exact\n//? set above. Suffix (not arbitrary substring) is deliberate: it catches the\n//? `<qualifier><Sensitive>` naming convention while a plain `substring` test\n//? would over-redact benign keys (e.g. a `tokenCount` metric, a `secretSanta`\n//? field). Kept conservative on purpose — register extra keys explicitly via\n//? `registerRedactedLogKeys` for project-specific names that don't fit.\nconst SENSITIVE_KEY_SUFFIXES: readonly string[] = ['token', 'secret', 'apikey', 'password'];\n\nexport const registerRedactedLogKeys = (keys: readonly string[]): void => {\n for (const key of keys) {\n redactedKeys.add(key.toLowerCase());\n }\n};\n\nexport const getRedactedLogKeys = (): readonly string[] => [...redactedKeys];\n\nexport const isRedactedLogKey = (key: string): boolean => {\n const lower = key.toLowerCase();\n if (redactedKeys.has(lower)) return true;\n return SENSITIVE_KEY_SUFFIXES.some((suffix) => lower.endsWith(suffix));\n};\n\n//? Test-only helper — restore the default seed set between integration tests.\n//? Never call from production code; framework packages register their own\n//? keys at boot and clearing would re-expose them.\nexport const resetRedactedLogKeysForTests = (): void => {\n redactedKeys.clear();\n for (const key of DEFAULT_REDACTED_LOG_KEYS) {\n redactedKeys.add(key.toLowerCase());\n }\n};\n\n/** Placeholder substituted for a redacted value. */\nexport const REDACTED_PLACEHOLDER = '[redacted]';\n\n//? Distinct from REDACTED_PLACEHOLDER so an over-deep BENIGN value (a numeric id,\n//? a timestamp) isn't mislabeled as a masked secret — the marker reads as\n//? structural truncation, not redaction.\nexport const DEPTH_TRUNCATED_PLACEHOLDER = '[truncated: max depth]';\n\n//? Depth cap so a self-referential / pathologically deep object can't make the\n//? sanitize pass blow the stack on a hot log/capture path.\nconst MAX_SANITIZE_DEPTH = 8;\n\n/**\n * Recursively deep-copy `value`, replacing any property whose key matches the\n * registered redacted-keys set (case-insensitive) with {@link REDACTED_PLACEHOLDER}\n * (SYNC-17 defense-in-depth). Use it at raw log / `captureException` context\n * sites so a token/password nested anywhere in a payload never lands verbatim in\n * a logger sink or error-tracker breadcrumb.\n *\n * - Primitives pass through unchanged.\n * - Arrays are mapped element-wise (array indices are never \"keys\", so an\n * element is only redacted by its own nested object keys).\n * - Cycles / over-deep graphs are cut at {@link MAX_SANITIZE_DEPTH} with\n * {@link DEPTH_TRUNCATED_PLACEHOLDER}; the input is never mutated.\n */\nexport const sanitizeForLog = (value: unknown, depth = 0, _seen?: WeakSet<object>): unknown => {\n if (depth > MAX_SANITIZE_DEPTH) return DEPTH_TRUNCATED_PLACEHOLDER;\n if (value === null || typeof value !== 'object') return value;\n\n //? Cycle detection: if we have already visited this reference higher up in the\n //? call stack, replace it with a marker rather than recursing into it — this\n //? prevents a stack overflow when `value` contains a circular reference (e.g.\n //? an Error whose `.cause` links back to itself, or a Node IncomingMessage\n //? with circular HTTP-socket references).\n const seen = _seen ?? new WeakSet<object>();\n if (seen.has(value)) return '[circular]';\n seen.add(value);\n\n if (Array.isArray(value)) {\n return value.map((item) => sanitizeForLog(item, depth + 1, seen));\n }\n\n const out: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {\n out[key] = isRedactedLogKey(key) ? REDACTED_PLACEHOLDER : sanitizeForLog(nested, depth + 1, seen);\n }\n return out;\n};\n","//? Pluggable logger so framework code does not have to write directly to\n//? stdout. The default implementation uses `console.{debug,info,warn,error}`\n//? directly with no trailing color-code argument — that argument was only\n//? meaningful when `initConsolelog()` (a dev-only monkey-patch) had been\n//? installed, but the default logger needs to be safe in production too.\n//?\n//? Installers route framework logs to Pino / Winston / Datadog / etc. by\n//? calling `registerLogger({ debug, info, warn, error })` once at boot,\n//? mirroring the rest of the registry pattern in this package. Dev installs\n//? that want colored output should call `registerLogger(createDevLogger())`.\n//?\n//? Read at call-time via `getLogger()` so registration order does not matter\n//? — same contract as `getProjectConfig()` and friends.\n\nimport { createRegistry } from './createRegistry';\nimport { getProjectConfig } from './projectConfig';\n\nexport type LoggerContext = Record<string, unknown>;\n\nexport interface Logger {\n debug: (message: string, context?: LoggerContext) => void;\n info: (message: string, context?: LoggerContext) => void;\n warn: (message: string, context?: LoggerContext) => void;\n error: (message: string, error?: unknown, context?: LoggerContext) => void;\n}\n\n//? Prefix a log message with an ISO-8601 UTC timestamp when\n//? `logging.timestamps` is on (the default). Read at call time so a consumer's\n//? config registration order doesn't matter, and so it can be toggled off under\n//? a log aggregator that stamps its own time. Only the framework's BUILT-IN\n//? loggers use this — a registered custom logger owns its own formatting.\nconst withTimestamp = (message: string): string =>\n getProjectConfig().logging.timestamps ? `[${new Date().toISOString()}] ${message}` : message;\n\nconst defaultLogger: Logger = {\n debug: (message, context) => {\n if (context === undefined) {console.debug(withTimestamp(message));}\n else {console.debug(withTimestamp(message), context);}\n },\n info: (message, context) => {\n if (context === undefined) {console.info(withTimestamp(message));}\n else {console.info(withTimestamp(message), context);}\n },\n warn: (message, context) => {\n if (context === undefined) {console.warn(withTimestamp(message));}\n else {console.warn(withTimestamp(message), context);}\n },\n error: (message, error, context) => {\n if (error !== undefined && context !== undefined) console.error(withTimestamp(message), error, context);\n else if (error !== undefined) console.error(withTimestamp(message), error);\n else if (context === undefined) {console.error(withTimestamp(message));}\n else {console.error(withTimestamp(message), context);}\n },\n};\n\n//? Dev-mode logger factory: wraps the default behavior with the colored\n//? terminal output that `initConsolelog()` produces. Install via\n//? `registerLogger(createDevLogger())` from a dev-only entry. Note: this\n//? still depends on `initConsolelog()` having been called to interpret the\n//? trailing color string — without it, the codes will appear as literal\n//? text. Use the default logger when running in production or unsure.\nexport const createDevLogger = (): Logger => ({\n debug: (message, context) => {\n if (context === undefined) {console.log(withTimestamp(message), 'cyan');}\n else {console.log(withTimestamp(message), context, 'cyan');}\n },\n info: (message, context) => {\n if (context === undefined) {console.log(withTimestamp(message));}\n else {console.log(withTimestamp(message), context);}\n },\n warn: (message, context) => {\n if (context === undefined) {console.log(withTimestamp(message), 'yellow');}\n else {console.log(withTimestamp(message), context, 'yellow');}\n },\n error: (message, error, context) => {\n if (error !== undefined && context !== undefined) console.log(withTimestamp(message), error, context, 'red');\n else if (error !== undefined) console.log(withTimestamp(message), error, 'red');\n else if (context === undefined) {console.log(withTimestamp(message), 'red');}\n else {console.log(withTimestamp(message), context, 'red');}\n },\n});\n\nconst registry = createRegistry<Logger>(defaultLogger);\n\nexport const registerLogger = (logger: Logger): void => {\n registry.register(logger);\n};\n\nexport const getLogger = (): Logger => registry.get();\n\nexport const isLoggerRegistered = (): boolean => registry.isRegistered();\n\n//? Test-only helper — restore the default logger between integration tests.\n//? Never call from production code.\nexport const resetLoggerForTests = (): void => {\n registry.reset();\n};\n","//? Backend-agnostic error-tracker registry. Lives in @luckystack/core\n//? (not @luckystack/error-tracking) because framework code in core /\n//? api / sync needs to call it without taking a hard dep on a specific\n//? observability backend. The error-tracking package provides adapter\n//? IMPLEMENTATIONS (Sentry, Datadog, PostHog); the slot lives here.\n//?\n//? Multiple adapters can be registered at once via `registerErrorTrackers([...])` —\n//? every event fans out to all of them. Per-adapter errors are swallowed\n//? so one buggy tracker can't break the chain.\n\n//? The AsyncLocalStorage identity scope deliberately lives in the separate\n//? server-only errorTrackerIdentity.ts module. This registry is also reached by\n//? the browser-safe legacy capture seam, so it must remain free of node:* imports.\nimport type { ErrorTrackerUser } from './errorTrackerIdentity';\nimport { getRedactedLogKeys, REDACTED_PLACEHOLDER, sanitizeForLog } from './redactedLogKeys';\nimport { getLogger } from './loggerRegistry';\n\nexport type { ErrorTrackerUser } from './errorTrackerIdentity';\n\nexport type ErrorTrackerContext = Record<string, unknown>;\n\n//? SYNC-17 defense-in-depth: scrub registered redacted keys (tokens, passwords,\n//? auth/cookie headers) from the context object before it fans out to any\n//? adapter, so a raw token nested in a capture context never reaches Sentry /\n//? Datadog / PostHog breadcrumbs. Returns the original reference when there is\n//? nothing to sanitize (no context) to avoid needless allocation on the hot path.\nconst sanitizeContext = (context?: ErrorTrackerContext): ErrorTrackerContext | undefined => {\n if (!context) return context;\n return sanitizeForLog(context) as ErrorTrackerContext;\n};\n\n//? ET-O2 value-level scrub: error.message and error.stack can contain\n//? interpolated secrets (\"token=abc123\") that bypass the key-based context\n//? scrub. Replace `key=value` and `key: value` patterns for every registered\n//? redacted key so the string never reaches an adapter verbatim.\n//? Runs at capture time (not on every Error construction) to stay off the\n//? hot path; the result is cached on the sanitized context so each adapter\n//? fan-out step reads the same pre-scrubbed string.\n//? BOOT-TIME ONLY: `registerRedactedLogKeys` must be called at boot with a\n//? static key set (framework package init / project boot). Calling it with\n//? dynamically generated strings (route names, tenant IDs, etc.) at request\n//? time will cause this cache to grow without bound. A hard cap (200 entries)\n//? logs a warning when exceeded so misuse is immediately diagnosable.\nconst REDACTED_VALUE_RE_CACHE_MAX = 200;\ninterface ScrubPatternPair {\n urlParam: RegExp; // matches <key>=<value> (URL-param style)\n logLabel: RegExp; // matches <key>: <value> (log-label style)\n}\nconst REDACTED_VALUE_RE_CACHE = new Map<string, ScrubPatternPair>();\n\nconst buildScrubPattern = (key: string): ScrubPatternPair => {\n const cached = REDACTED_VALUE_RE_CACHE.get(key);\n if (cached) return cached;\n if (REDACTED_VALUE_RE_CACHE.size >= REDACTED_VALUE_RE_CACHE_MAX) {\n try {\n getLogger().warn(`errorTracker: REDACTED_VALUE_RE_CACHE exceeded ${String(REDACTED_VALUE_RE_CACHE_MAX)} entries — registerRedactedLogKeys must only be called at boot with a static key set, not with dynamic/runtime-varying strings.`);\n } catch {\n // last-resort swallow\n }\n }\n const escaped = key.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\n //? Two separate passes — one for `key=value` (URL-param style), one for\n //? `key: value` (log-label style) — to avoid alternation complexity and the\n //? subtle behaviours that arise when mixing capturing and non-capturing groups\n //? inside a single pattern (ET-O2 alternation fix).\n //? `+` (not `*`) for the value portion so `key=` with an empty value is NOT\n //? replaced (empty parameters are not secrets worth scrubbing and a `*` match\n //? would turn innocent `foo=` markers into `[redacted]`).\n const pair: ScrubPatternPair = {\n urlParam: new RegExp(String.raw`${escaped}=[^\\s,;\"'&]+`, 'gi'),\n logLabel: new RegExp(String.raw`${escaped}:\\s*[^\\s,;\"']+`, 'gi'),\n };\n REDACTED_VALUE_RE_CACHE.set(key, pair);\n return pair;\n};\n\nexport const sanitizeErrorString = (value: string): string => {\n let result = value;\n // Scrub matching `key=value` / `key: value` patterns for every registered\n // redacted key so interpolated secrets (e.g. \"token=abc\") never reach an adapter.\n for (const key of getRedactedLogKeys()) {\n const { urlParam, logLabel } = buildScrubPattern(key);\n result = result.replace(urlParam, () => REDACTED_PLACEHOLDER).replace(logLabel, () => REDACTED_PLACEHOLDER);\n }\n return result;\n};\n\n//? Produce a sanitized version of an Error's message and stack so adapters\n//? can emit pre-scrubbed strings without touching the original Error object.\nexport const sanitizeErrorStrings = (\n error: unknown,\n): { message: string; stack: string | undefined } | null => {\n if (!(error instanceof Error)) return null;\n return {\n message: sanitizeErrorString(error.message),\n stack: error.stack === undefined ? undefined : sanitizeErrorString(error.stack),\n };\n};\n\nexport interface ErrorTrackerEvent {\n /** When false, the adapter must not forward this event (beforeSend opt-out). */\n forwarded: boolean;\n kind: 'exception' | 'message';\n payload: Record<string, unknown>;\n}\n\n//? `SpanResult<T>` was a conditional unwrap of Promise. It's now an alias\n//? for `T` directly because the conditional collapsed to T in both branches\n//? and tsup's dts emit choked on the conditional widening. Kept as an\n//? exported alias so adapter authors can still annotate with `SpanResult<T>`\n//? for documentation intent.\nexport type SpanResult<T> = T;\n\nexport interface ErrorTracker {\n /** Human-readable identifier (logs, diagnostics). */\n name: string;\n captureException: (error: unknown, context?: ErrorTrackerContext) => void;\n captureMessage: (\n message: string,\n level: 'info' | 'warning' | 'error' | 'fatal',\n context?: ErrorTrackerContext,\n ) => void;\n setUser: (user: ErrorTrackerUser | null) => void;\n setContext?: (key: string, context: ErrorTrackerContext | null) => void;\n startSpan?: <T>(name: string, op: string, fn: () => T) => T;\n /**\n * Optional handle-style span (#62): open a span NOW and close it later via the\n * returned handle's `finish()`. Unlike {@link startSpan} (which wraps a single\n * synchronous `fn`), this fits an open-at-preExecute / close-at-postExecute\n * request lifecycle that spans awaits. When present, the registry-level\n * {@link startSpanHandle} delegates to the FIRST registered adapter that\n * implements it so the request span reaches an adapter-only backend\n * (Datadog/PostHog/custom), not just the legacy Sentry SDK path.\n */\n startSpanHandle?: (name: string, op: string) => { finish: () => void };\n recordMetric?: (name: string, value: number, tags?: Record<string, string>) => void;\n beforeSend?: (event: ErrorTrackerEvent) => ErrorTrackerEvent | null;\n /**\n * Optional flush lifecycle hook (error-tracking ET batch). Called by\n * {@link flushErrorTrackers} on graceful shutdown so a buffered adapter\n * (PostHog batch, Sentry transport) can drain in-flight events before exit.\n * Returns a promise that resolves when the adapter has flushed.\n */\n flush?: () => Promise<void>;\n}\n\n//? Pre-capture filter (error-tracking ET batch). A registered filter runs on\n//? EVERY event just before fan-out; returning `false` DROPS the event entirely\n//? (e.g. suppress known-noisy errors, sample, or honour a per-event opt-out).\n//? Distinct from a per-adapter `beforeSend` (which transforms a single adapter's\n//? payload) — this gates the whole fan-out. Last-write-wins; `null` clears it.\nexport type PreCaptureFilter = (event: ErrorTrackerEvent) => boolean;\nlet preCaptureFilter: PreCaptureFilter | null = null;\n\nexport const registerPreCaptureFilter = (filter: PreCaptureFilter | null): void => {\n preCaptureFilter = filter;\n};\n\nconst passesPreCaptureFilter = (kind: 'exception' | 'message', payload: Record<string, unknown>): boolean => {\n if (!preCaptureFilter) return true;\n try {\n return preCaptureFilter({ forwarded: true, kind, payload });\n } catch {\n //? A throwing filter must not swallow telemetry — fail OPEN (forward).\n return true;\n }\n};\n\n//? ET-O6: the pre-capture filter payload now includes the error / message\n//? so filters can drop noisy errors by type/message (the documented use case).\n//? Separate helpers per kind so the call site stays type-safe.\nconst exceptionFilterPayload = (\n error: unknown,\n context: ErrorTrackerContext | undefined,\n): Record<string, unknown> => ({ error, context: context ?? null });\n\nconst messageFilterPayload = (\n message: string,\n level: string,\n context: ErrorTrackerContext | undefined,\n): Record<string, unknown> => ({ message, level, context: context ?? null });\n\nlet activeTrackers: ErrorTracker[] = [];\n\n//? REPLACE semantics — last-write-wins (ET-24 confirmed standard). Use\n//? `appendErrorTracker` when you need accumulate-not-replace (ET-05).\nexport const registerErrorTracker = (tracker: ErrorTracker): void => {\n activeTrackers = [tracker];\n};\n\nexport const registerErrorTrackers = (trackers: ErrorTracker[]): void => {\n activeTrackers = [...trackers];\n};\n\n/**\n * APPEND primitive (ET-05): add a tracker WITHOUT clobbering already-registered\n * ones. Fixes the async-PostHog-vs-consumer-overlay race where the loser of\n * `registerErrorTracker`'s replace silently vanished. De-duplicates by `name`\n * (re-appending the same adapter name replaces that one entry in place) so a\n * lazy adapter that registers a proxy then the real client doesn't double-fire.\n */\nexport const appendErrorTracker = (tracker: ErrorTracker): void => {\n const withoutSameName = activeTrackers.filter((t) => t.name !== tracker.name);\n activeTrackers = [...withoutSameName, tracker];\n};\n\nexport const getActiveErrorTrackers = (): ErrorTracker[] => activeTrackers;\n\n/**\n * Flush lifecycle (error-tracking ET batch): drain every adapter that exposes a\n * `flush()` before shutdown. Per-adapter failures are swallowed + logged so one\n * stuck adapter can't block graceful shutdown. Safe to call when no adapter has\n * `flush`.\n */\nexport const flushErrorTrackers = async (): Promise<void> => {\n await Promise.all(\n activeTrackers.map(async (tracker) => {\n if (!tracker.flush) return;\n try {\n await tracker.flush();\n } catch (error) {\n //? ET-O7: route to the shared failure logger (but never re-throw — a\n //? failing flush must not block graceful shutdown).\n logTrackerFailure(tracker.name, 'flush', error);\n }\n }),\n );\n};\n\nexport const captureExceptionAcrossTrackers = (\n error: unknown,\n context?: ErrorTrackerContext,\n): void => {\n const safeContext = sanitizeContext(context);\n if (!passesPreCaptureFilter('exception', exceptionFilterPayload(error, safeContext))) return;\n for (const tracker of activeTrackers) {\n try {\n tracker.captureException(error, safeContext);\n } catch (trackerError) {\n //? Fan-out error logging (error-tracking ET batch): a buggy tracker must\n //? not break the chain, but its failure was previously invisible. Log it\n //? (best-effort) so a misbehaving adapter is diagnosable.\n logTrackerFailure(tracker.name, 'captureException', trackerError);\n }\n }\n};\n\nexport const captureMessageAcrossTrackers = (\n message: string,\n level: 'info' | 'warning' | 'error' | 'fatal',\n context?: ErrorTrackerContext,\n): void => {\n const safeContext = sanitizeContext(context);\n if (!passesPreCaptureFilter('message', messageFilterPayload(message, level, safeContext))) return;\n for (const tracker of activeTrackers) {\n try {\n tracker.captureMessage(message, level, safeContext);\n } catch (trackerError) {\n logTrackerFailure(tracker.name, 'captureMessage', trackerError);\n }\n }\n};\n\n//? Best-effort fan-out failure logger. Wrapped in its own try/catch because the\n//? logger itself could throw on a broken sink, and a capture path must never\n//? throw.\nconst logTrackerFailure = (trackerName: string, op: string, error: unknown): void => {\n try {\n getLogger().warn(`errorTracker: \"${trackerName}\" threw in ${op}`, { error });\n } catch {\n // Last-resort swallow.\n }\n};\n\nexport const setErrorTrackerUser = (user: ErrorTrackerUser | null): void => {\n for (const tracker of activeTrackers) {\n try {\n tracker.setUser(user);\n } catch (error) {\n //? ET-O7: route to the shared failure logger so a misbehaving tracker is diagnosable.\n logTrackerFailure(tracker.name, 'setUser', error);\n }\n }\n};\n\nexport const recordMetricAcrossTrackers = (\n name: string,\n value: number,\n tags?: Record<string, string>,\n): void => {\n for (const tracker of activeTrackers) {\n if (tracker.recordMetric) {\n try {\n tracker.recordMetric(name, value, tags);\n } catch (error) {\n //? ET-O7: route to the shared failure logger so a misbehaving tracker is diagnosable.\n logTrackerFailure(tracker.name, 'recordMetric', error);\n }\n }\n }\n};\n\nexport const startSpanAcrossTrackers = <T>(name: string, op: string, fn: () => T): T => {\n //? Spans don't fan out cleanly to multiple backends — they're nested\n //? execution scopes. We only invoke the FIRST registered tracker's\n //? startSpan (others get notified via captureException paths if they\n //? want to instrument). When no tracker supports spans, run the fn directly.\n const first = activeTrackers.find((t) => t.startSpan);\n if (!first?.startSpan) return fn();\n return first.startSpan(name, op, fn);\n};\n\n/**\n * Handle-style span (error-tracking ET batch): for callers that can't wrap the\n * measured work in a single synchronous `fn` (streaming, cross-await spans).\n * Returns a handle whose `finish()` resolves the span's duration. The default\n * implementation is a lightweight wall-clock timer (works with any backend);\n * an adapter can supply a richer span via the existing `startSpan` callback\n * form when it needs native instrumentation. `finish()` is idempotent.\n */\nexport interface SpanHandle {\n /** Stop the span; safe to call more than once (subsequent calls are no-ops). */\n finish: () => void;\n /** Milliseconds elapsed at the moment `finish()` first ran (0 before). */\n readonly durationMs: number;\n}\n\n//? #62: open a handle-style span on the FIRST registered adapter that implements\n//? `startSpanHandle`, swallowing a throwing adapter so the wall-clock handle still\n//? works (telemetry must never break the request path). Returns `null` when no\n//? adapter supports handle-style spans.\nconst openDelegateSpanHandle = (name: string, op: string): { finish: () => void } | null => {\n const tracker = activeTrackers.find((t) => t.startSpanHandle);\n if (!tracker?.startSpanHandle) return null;\n try {\n return tracker.startSpanHandle(name, op);\n } catch (error) {\n logTrackerFailure(tracker.name, 'startSpanHandle', error);\n return null;\n }\n};\n\n//? #62: delegate the handle to the first adapter that supports `startSpanHandle`\n//? (so an adapter-only consumer — Datadog/PostHog/custom, no legacy Sentry SDK —\n//? actually gets request-timing spans), and ALWAYS keep the wall-clock timer as a\n//? backend-agnostic fallback + `durationMs` source. `finish()` is idempotent and\n//? closes the delegated span exactly once.\n//? ET-O9: removed the per-call `recordMetricAcrossTrackers` that fired on every\n//? startSpanHandle invocation — `durationMs` is available for callers that want to\n//? emit their own metric.\nexport const startSpanHandle = (name: string, op: string): SpanHandle => {\n const startedAt = Date.now();\n let finishedAt: number | null = null;\n const delegate = openDelegateSpanHandle(name, op);\n return {\n finish: () => {\n if (finishedAt !== null) return;\n finishedAt = Date.now();\n if (delegate) {\n try {\n delegate.finish();\n } catch (error) {\n logTrackerFailure('startSpanHandle', 'finish', error);\n }\n }\n },\n get durationMs() {\n return finishedAt === null ? 0 : finishedAt - startedAt;\n },\n };\n};\n","//? Legacy Sentry single-instance slot. Predates the multi-adapter\n//? ErrorTracker registry. New code should `registerErrorTracker(...)`\n//? from `@luckystack/error-tracking`; this file keeps backwards\n//? compatibility AND fans out events through any registered adapters so\n//? a project can mix legacy `initSharedSentry` + new `registerErrorTracker`\n//? during migration.\n//?\n//? The framework's own call sites (`captureException`, `captureMessage`,\n//? `setSentryUser`, `startSpan`) keep working unchanged — they now route\n//? through both the legacy slot and the new adapter list.\n\nimport {\n captureExceptionAcrossTrackers,\n captureMessageAcrossTrackers,\n setErrorTrackerUser,\n startSpanAcrossTrackers,\n} from './errorTrackerRegistry';\nimport { sanitizeForLog } from './redactedLogKeys';\n\ninterface SentryInstance {\n captureException: (exception: unknown, ...args: unknown[]) => string;\n captureMessage: (message: string, ...args: unknown[]) => string;\n setUser: (user: unknown) => void;\n setContext: (key: string, context: unknown) => void;\n startInactiveSpan?: (context: unknown) => unknown;\n}\n\nlet sentry: SentryInstance | undefined;\n\n/**\n * @deprecated Use `registerErrorTracker` from `@luckystack/error-tracking` instead.\n * Will be removed in a future major version.\n */\nexport const initSharedSentry = (instance: SentryInstance): void => {\n sentry = instance;\n};\n\n//? Pass `extra` inline via Sentry's hint-shaped second argument so contexts\n//? don't leak across concurrent captures. Previously we called\n//? `sentry.setContext('additional', context)` which is process-global until\n//? cleared — under concurrent captures the first context could leak into the\n//? second's report.\n//? CORE-O4: sanitize context before passing to the legacy Sentry slot so raw\n//? tokens/passwords don't reach `extra` when a consumer mixes initSharedSentry\n//? with framework capture. The multi-adapter path already sanitizes in\n//? errorTrackerRegistry.ts; this brings the legacy path into parity.\nexport const captureException = (\n error: unknown,\n context?: Record<string, unknown>,\n): void => {\n if (sentry) {\n if (context) {\n sentry.captureException(error, { extra: sanitizeForLog(context) as Record<string, unknown> });\n } else {\n sentry.captureException(error);\n }\n }\n //? Multi-adapter fan-out. When no adapter is registered this is a no-op.\n captureExceptionAcrossTrackers(error, context);\n};\n\nexport const captureMessage = (\n message: string,\n level: 'info' | 'warning' | 'error' | 'fatal' = 'info',\n context?: Record<string, unknown>,\n): void => {\n if (sentry) {\n if (context) {\n sentry.captureMessage(message, { level, extra: sanitizeForLog(context) as Record<string, unknown> });\n } else {\n sentry.captureMessage(message, level);\n }\n }\n captureMessageAcrossTrackers(message, level, context);\n};\n\nexport const setSentryUser = (user: {\n id?: string;\n email?: string;\n username?: string;\n} | null): void => {\n sentry?.setUser(user);\n setErrorTrackerUser(user);\n};\n\nexport const startSpan = (name: string, op: string): unknown => {\n //? Multi-adapter span coordination: first registered adapter that\n //? supports spans wins (spans don't fan out cleanly). Legacy Sentry\n //? single-instance path still creates the inactive span for backwards\n //? compatibility on consumers that haven't migrated.\n if (sentry?.startInactiveSpan) {\n return sentry.startInactiveSpan({ name, op });\n }\n //? No-op span body is intentional — this is the legacy inactive-span shape\n //? consumers built against; the real span lifecycle is managed elsewhere.\n // eslint-disable-next-line @typescript-eslint/no-empty-function -- legacy inactive-span shape\n startSpanAcrossTrackers(name, op, () => {});\n};\n"],"mappings":";;;;;;AASO,IAAM,4BAA+C;AAAA,EAC1D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AACF;AAEA,IAAM,eAAe,IAAI,IAAY,0BAA0B,IAAI,CAAC,QAAQ,IAAI,YAAY,CAAC,C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P3SSLA3E.js";
|
|
5
5
|
import {
|
|
6
6
|
createRegistry,
|
|
7
7
|
getProjectConfig
|
|
@@ -726,4 +726,4 @@ export {
|
|
|
726
726
|
DEFAULT_PAGE_ROUTE_RULES,
|
|
727
727
|
validatePagePath
|
|
728
728
|
};
|
|
729
|
-
//# sourceMappingURL=chunk-
|
|
729
|
+
//# sourceMappingURL=chunk-XDX5MV54.js.map
|
|
@@ -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,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AM,MAAM;AAC9B;","names":["registry","responseIndex","registry","token"]}
|
package/dist/client.js
CHANGED
|
@@ -43,11 +43,11 @@ import {
|
|
|
43
43
|
tryCatchSync,
|
|
44
44
|
validatePagePath,
|
|
45
45
|
waitForSocket
|
|
46
|
-
} from "./chunk-
|
|
46
|
+
} from "./chunk-XDX5MV54.js";
|
|
47
47
|
import {
|
|
48
48
|
getLogger,
|
|
49
49
|
registerLogger
|
|
50
|
-
} from "./chunk-
|
|
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-
|
|
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
|
}
|
package/dist/eslint/index.js
CHANGED
|
@@ -351,8 +351,122 @@ var rule7 = {
|
|
|
351
351
|
};
|
|
352
352
|
var no_unsafe_sync_wrappers_default = rule7;
|
|
353
353
|
|
|
354
|
-
// src/eslint/rules/
|
|
354
|
+
// src/eslint/rules/no-untranslated-jsx-text.ts
|
|
355
|
+
var DEFAULT_ALLOWED_JSX_STRINGS = [
|
|
356
|
+
"!",
|
|
357
|
+
"?",
|
|
358
|
+
"-",
|
|
359
|
+
"/",
|
|
360
|
+
":",
|
|
361
|
+
",",
|
|
362
|
+
"(",
|
|
363
|
+
")",
|
|
364
|
+
"%",
|
|
365
|
+
"&",
|
|
366
|
+
"@",
|
|
367
|
+
"#",
|
|
368
|
+
"$",
|
|
369
|
+
"^",
|
|
370
|
+
"*",
|
|
371
|
+
"+",
|
|
372
|
+
"=",
|
|
373
|
+
"|",
|
|
374
|
+
".",
|
|
375
|
+
"...",
|
|
376
|
+
"0",
|
|
377
|
+
"1",
|
|
378
|
+
"2",
|
|
379
|
+
"3",
|
|
380
|
+
"4",
|
|
381
|
+
"5",
|
|
382
|
+
"6",
|
|
383
|
+
"7",
|
|
384
|
+
"8",
|
|
385
|
+
"9",
|
|
386
|
+
"10",
|
|
387
|
+
"\u2022",
|
|
388
|
+
"\xBB",
|
|
389
|
+
"\xAB",
|
|
390
|
+
"\u2014",
|
|
391
|
+
"\u2013",
|
|
392
|
+
"x",
|
|
393
|
+
"px",
|
|
394
|
+
"rem",
|
|
395
|
+
"em",
|
|
396
|
+
"ms",
|
|
397
|
+
"s",
|
|
398
|
+
"\xB0"
|
|
399
|
+
];
|
|
400
|
+
var WHITESPACE_ONLY = /^\s+$/;
|
|
401
|
+
var ELEMENT_TYPES = /* @__PURE__ */ new Set(["JSXElement", "JSXFragment"]);
|
|
402
|
+
var asRuleNode2 = (node) => node;
|
|
403
|
+
var parentSkippingConcatenation = (node) => {
|
|
404
|
+
let current = node;
|
|
405
|
+
while (current.parent?.type === "BinaryExpression") current = current.parent;
|
|
406
|
+
return current.parent ?? null;
|
|
407
|
+
};
|
|
408
|
+
var isChildPosition = (node) => {
|
|
409
|
+
const parent = parentSkippingConcatenation(node);
|
|
410
|
+
if (!parent) return false;
|
|
411
|
+
if (ELEMENT_TYPES.has(parent.type)) return true;
|
|
412
|
+
return parent.type === "JSXExpressionContainer" && ELEMENT_TYPES.has(parent.parent?.type ?? "");
|
|
413
|
+
};
|
|
355
414
|
var rule8 = {
|
|
415
|
+
meta: {
|
|
416
|
+
type: "suggestion",
|
|
417
|
+
docs: {
|
|
418
|
+
description: "Disallow untranslated text in JSX. User-facing text goes through the project translator."
|
|
419
|
+
},
|
|
420
|
+
messages: {
|
|
421
|
+
untranslated: 'Untranslated text in JSX: "{{text}}". Put user-facing text through the project translator (`useTranslator`) so every language gets it.'
|
|
422
|
+
},
|
|
423
|
+
schema: [
|
|
424
|
+
{
|
|
425
|
+
type: "object",
|
|
426
|
+
properties: {
|
|
427
|
+
allowedStrings: { type: "array", items: { type: "string" }, uniqueItems: true }
|
|
428
|
+
},
|
|
429
|
+
additionalProperties: false
|
|
430
|
+
}
|
|
431
|
+
]
|
|
432
|
+
},
|
|
433
|
+
create(context) {
|
|
434
|
+
const options = context.options[0] ?? {};
|
|
435
|
+
const allowed = new Set((options.allowedStrings ?? DEFAULT_ALLOWED_JSX_STRINGS).map((s) => s.trim()));
|
|
436
|
+
const isAllowedText = (node) => {
|
|
437
|
+
if (typeof node.value !== "string" || WHITESPACE_ONLY.test(node.value) || node.value === "") return true;
|
|
438
|
+
return allowed.has(node.value.trim()) || node.raw !== void 0 && allowed.has(node.raw.trim());
|
|
439
|
+
};
|
|
440
|
+
const report = (node) => {
|
|
441
|
+
const ruleNode = asRuleNode2(node);
|
|
442
|
+
context.report({
|
|
443
|
+
node: ruleNode,
|
|
444
|
+
messageId: "untranslated",
|
|
445
|
+
data: { text: context.sourceCode.getText(ruleNode).trim() }
|
|
446
|
+
});
|
|
447
|
+
};
|
|
448
|
+
const listener = {
|
|
449
|
+
JSXText(rawNode) {
|
|
450
|
+
const node = rawNode;
|
|
451
|
+
if (!isAllowedText(node) && isChildPosition(node)) report(node);
|
|
452
|
+
},
|
|
453
|
+
Literal(rawNode) {
|
|
454
|
+
const node = rawNode;
|
|
455
|
+
if (!isAllowedText(node) && isChildPosition(node)) report(node);
|
|
456
|
+
},
|
|
457
|
+
TemplateLiteral(rawNode) {
|
|
458
|
+
const node = rawNode;
|
|
459
|
+
const parent = parentSkippingConcatenation(node);
|
|
460
|
+
if (parent?.type === "JSXExpressionContainer" && parent.parent?.type === "JSXElement") report(node);
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
return listener;
|
|
464
|
+
}
|
|
465
|
+
};
|
|
466
|
+
var no_untranslated_jsx_text_default = rule8;
|
|
467
|
+
|
|
468
|
+
// src/eslint/rules/prefer-luckystack-confirm.ts
|
|
469
|
+
var rule9 = {
|
|
356
470
|
meta: {
|
|
357
471
|
type: "suggestion",
|
|
358
472
|
docs: {
|
|
@@ -378,10 +492,10 @@ var rule8 = {
|
|
|
378
492
|
};
|
|
379
493
|
}
|
|
380
494
|
};
|
|
381
|
-
var prefer_luckystack_confirm_default =
|
|
495
|
+
var prefer_luckystack_confirm_default = rule9;
|
|
382
496
|
|
|
383
497
|
// src/eslint/rules/prefer-luckystack-dropdown.ts
|
|
384
|
-
var
|
|
498
|
+
var rule10 = {
|
|
385
499
|
meta: {
|
|
386
500
|
type: "suggestion",
|
|
387
501
|
docs: {
|
|
@@ -404,10 +518,10 @@ var rule9 = {
|
|
|
404
518
|
return listener;
|
|
405
519
|
}
|
|
406
520
|
};
|
|
407
|
-
var prefer_luckystack_dropdown_default =
|
|
521
|
+
var prefer_luckystack_dropdown_default = rule10;
|
|
408
522
|
|
|
409
523
|
// src/eslint/rules/prefer-luckystack-notify.ts
|
|
410
|
-
var
|
|
524
|
+
var rule11 = {
|
|
411
525
|
meta: {
|
|
412
526
|
type: "suggestion",
|
|
413
527
|
docs: {
|
|
@@ -433,7 +547,7 @@ var rule10 = {
|
|
|
433
547
|
};
|
|
434
548
|
}
|
|
435
549
|
};
|
|
436
|
-
var prefer_luckystack_notify_default =
|
|
550
|
+
var prefer_luckystack_notify_default = rule11;
|
|
437
551
|
|
|
438
552
|
// src/eslint/index.ts
|
|
439
553
|
var allRules = {
|
|
@@ -446,7 +560,8 @@ var allRules = {
|
|
|
446
560
|
"prefer-luckystack-confirm": prefer_luckystack_confirm_default,
|
|
447
561
|
"prefer-luckystack-notify": prefer_luckystack_notify_default,
|
|
448
562
|
"no-direct-prisma-import-in-components": no_direct_prisma_import_in_components_default,
|
|
449
|
-
"no-arbitrary-tailwind-color": no_arbitrary_tailwind_color_default
|
|
563
|
+
"no-arbitrary-tailwind-color": no_arbitrary_tailwind_color_default,
|
|
564
|
+
"no-untranslated-jsx-text": no_untranslated_jsx_text_default
|
|
450
565
|
};
|
|
451
566
|
var hasApi = hasPackage("@luckystack/api");
|
|
452
567
|
var hasCore = hasPackage("@luckystack/core");
|
|
@@ -466,7 +581,9 @@ var ruleSeverities = {
|
|
|
466
581
|
"luckystack/prefer-luckystack-confirm": "warn",
|
|
467
582
|
"luckystack/prefer-luckystack-notify": "warn",
|
|
468
583
|
"luckystack/no-direct-prisma-import-in-components": "warn",
|
|
469
|
-
"luckystack/no-arbitrary-tailwind-color": "warn"
|
|
584
|
+
"luckystack/no-arbitrary-tailwind-color": "warn",
|
|
585
|
+
//? User-facing text goes through the translator (AGENTS.md rule 13).
|
|
586
|
+
"luckystack/no-untranslated-jsx-text": "warn"
|
|
470
587
|
};
|
|
471
588
|
var luckystackConfig = [
|
|
472
589
|
{
|