@flare-engine/errors 0.4.12 → 0.4.13

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["Component"],"sources":["../src/compose.ts","../src/crash-payload.ts","../src/transport.ts","../src/error-boundary.tsx","../src/global-capture.ts","../src/transports/client.ts","../src/transports/sentry.ts"],"sourcesContent":["import type { CrashTransport } from './transport.js';\n\nexport function composeTransports(...transports: CrashTransport[]): CrashTransport {\n return {\n async report(payload) {\n for (const t of transports) {\n try {\n await t.report(payload);\n } catch (err) {\n console.error('[@flare-engine/errors] composeTransports: child transport threw', err);\n }\n }\n },\n async close() {\n for (const t of transports) {\n try {\n await t.close?.();\n } catch (err) {\n console.error(\n '[@flare-engine/errors] composeTransports: child transport close threw',\n err,\n );\n }\n }\n },\n };\n}\n","/**\n * Serializable crash payload. Everything here is JSON-safe so transports can\n * post it to Sentry / Crashlytics / a custom HTTP endpoint without extra work.\n */\nexport interface CrashPayload {\n /** Error message. */\n message: string;\n /** Error name (e.g., `TypeError`). */\n name: string;\n /** Captured stack trace, if available. */\n stack: string | null;\n /** Monotonic ms timestamp — `Date.now()` at capture. */\n timestamp: number;\n /** Optional free-form context supplied by the caller. */\n context: Record<string, unknown>;\n}\n\n/**\n * Capture an unknown thrown value as a serializable crash payload. Handles\n * `Error` instances, string throws, and arbitrary values.\n */\nexport function createCrashPayload(\n error: unknown,\n context: Record<string, unknown> = {},\n): CrashPayload {\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n stack: error.stack ?? null,\n timestamp: Date.now(),\n context,\n };\n }\n if (typeof error === 'string') {\n return { message: error, name: 'Error', stack: null, timestamp: Date.now(), context };\n }\n let message: string;\n try {\n message = JSON.stringify(error);\n } catch {\n message = String(error);\n }\n return { message, name: 'NonError', stack: null, timestamp: Date.now(), context };\n}\n\n/**\n * Rebuild a payload into an `Error`, which is what error clients group by. The\n * captured stack replaces the new Error's own; a `null` stack leaves it as is.\n */\nexport function payloadToError(payload: CrashPayload): Error {\n const error = new Error(payload.message);\n error.name = payload.name;\n if (payload.stack !== null) error.stack = payload.stack;\n return error;\n}\n","import type { CrashPayload } from './crash-payload.js';\n\n/**\n * Pluggable transport for reporting crashes. Implementations send the payload\n * wherever they need — Sentry, Crashlytics, an HTTP endpoint, or nowhere.\n */\nexport interface CrashTransport {\n report(payload: CrashPayload): void | Promise<void>;\n /**\n * Tear the sink down, e.g. on consent revocation. Idempotent: a second call\n * resolves without closing twice. `report()` after `close()` sends nothing.\n * Transports with nothing to tear down leave it undefined.\n */\n close?(): Promise<void>;\n}\n\n/**\n * Call `transport.report` so that neither a synchronous throw nor a rejected\n * promise escapes. Left unhandled, a rejection surfaces on the global as an\n * `unhandledrejection` that `installGlobalErrorCapture` listens for, so each\n * failed report would trigger the next for as long as the transport is down.\n */\nexport function reportSafely(\n transport: CrashTransport,\n payload: CrashPayload,\n stage: 'reporting' | 'draining',\n): void {\n const onFailure = (err: unknown): void => {\n console.error(`[@flare-engine/errors] transport threw while ${stage}`, err);\n };\n try {\n void Promise.resolve(transport.report(payload)).catch(onFailure);\n } catch (err) {\n onFailure(err);\n }\n}\n\n/** Transport that discards every payload. The default. */\nexport function createNoopTransport(): CrashTransport {\n return {\n report() {\n /* no-op */\n },\n };\n}\n\n/**\n * Transport that logs payloads via `console.error`. Useful in development and\n * as a wrapper around another transport when debugging.\n */\nexport function createConsoleTransport(): CrashTransport {\n return {\n report(payload) {\n console.error('[@flare-engine/errors]', payload);\n },\n };\n}\n","import { Component, type ErrorInfo, type ReactNode } from 'react';\nimport { type CrashPayload, createCrashPayload } from './crash-payload.js';\nimport { type CrashTransport, reportSafely } from './transport.js';\n\nexport interface ErrorBoundaryProps {\n children: ReactNode;\n /** Rendered when an error is caught. Receives the payload + a reset callback. */\n fallback: (payload: CrashPayload, reset: () => void) => ReactNode;\n /** Transport invoked once per caught error. */\n transport?: CrashTransport;\n /** Additional context merged into every payload captured by this boundary. */\n context?: Record<string, unknown>;\n /** Called with both the raw error and the payload for custom side effects. */\n onError?: (error: unknown, payload: CrashPayload) => void;\n}\n\ninterface ErrorBoundaryState {\n payload: CrashPayload | null;\n}\n\n/**\n * React error boundary that captures render-phase errors into a structured\n * `CrashPayload`, forwards it to an optional transport, and renders the\n * caller-supplied fallback.\n */\nexport class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {\n state: ErrorBoundaryState = { payload: null };\n\n static getDerivedStateFromError(error: unknown): ErrorBoundaryState {\n return { payload: createCrashPayload(error) };\n }\n\n componentDidCatch(error: unknown, info: ErrorInfo): void {\n const context = {\n ...this.props.context,\n componentStack: info.componentStack ?? null,\n };\n const payload = createCrashPayload(error, context);\n this.setState({ payload });\n const { transport } = this.props;\n if (transport !== undefined) reportSafely(transport, payload, 'reporting');\n this.props.onError?.(error, payload);\n }\n\n reset = (): void => {\n this.setState({ payload: null });\n };\n\n render(): ReactNode {\n if (this.state.payload !== null) {\n return this.props.fallback(this.state.payload, this.reset);\n }\n return this.props.children;\n }\n}\n","import { createCrashPayload } from './crash-payload.js';\nimport { type CrashTransport, reportSafely } from './transport.js';\n\n/**\n * React Native's `global.ErrorUtils`, described structurally so this package\n * needs no React Native dependency or types.\n */\nexport interface ErrorUtilsLike {\n getGlobalHandler?(): ((error: unknown, isFatal?: boolean) => void) | undefined;\n setGlobalHandler(handler: (error: unknown, isFatal?: boolean) => void): void;\n}\n\n/**\n * What `installGlobalErrorCapture` needs from a global object.\n *\n * Both members are optional and independent, so one call handles either\n * platform: on web `globalThis` supplies `addEventListener`, on React Native it\n * supplies `ErrorUtils`, and in a test you pass a hand-built fake. Nothing here\n * references `window`, `document` or any RN type.\n */\nexport interface GlobalErrorTarget {\n addEventListener?(type: string, listener: (event: unknown) => void): void;\n removeEventListener?(type: string, listener: (event: unknown) => void): void;\n ErrorUtils?: ErrorUtilsLike;\n}\n\n/** Options for `installGlobalErrorCapture`. */\nexport interface GlobalCaptureOptions {\n /**\n * Where captured errors go. May be omitted at install and attached later with\n * `setTransport` — errors raised in between are held in the buffer below\n * rather than dropped.\n */\n transport?: CrashTransport;\n /**\n * How many pre-transport errors to retain. Default 20. The oldest is dropped\n * once full: a boot loop should not grow memory without bound, and the first\n * errors are the ones worth keeping.\n */\n bufferSize?: number;\n /** Context merged into every payload this capture produces. */\n context?: Record<string, unknown>;\n}\n\n/** Handle returned by `installGlobalErrorCapture`. */\nexport interface GlobalCaptureHandle {\n /**\n * Detach every handler this call installed and restore whatever was there\n * before. Safe to call more than once.\n */\n uninstall(): void;\n /** Attach or replace the transport, draining any buffered errors into it. */\n setTransport(transport: CrashTransport): void;\n /** How many errors are currently held awaiting a transport. */\n readonly buffered: number;\n}\n\n/** Pull the underlying error out of a structurally-typed DOM-ish event. */\nfunction unwrapEvent(event: unknown, key: 'error' | 'reason'): unknown {\n if (typeof event === 'object' && event !== null && key in event) {\n const value = (event as Record<string, unknown>)[key];\n if (value !== undefined && value !== null) return value;\n }\n // An ErrorEvent with no `.error` still carries a message worth reporting.\n if (typeof event === 'object' && event !== null && 'message' in event) {\n return (event as Record<string, unknown>).message;\n }\n return event;\n}\n\n/**\n * Route uncaught errors and unhandled rejections into a `CrashTransport`.\n *\n * `ErrorBoundary` only sees errors thrown during React's render phase. The\n * majority of a game's crashes are not there — they are in the update loop, in\n * an asset load, in a promise nobody awaited — and before this nothing carried\n * them to a transport.\n *\n * Both platforms are handled through the same call:\n *\n * ```ts\n * const capture = installGlobalErrorCapture(globalThis, { transport });\n * // ...\n * capture.uninstall();\n * ```\n *\n * The React Native handler is **chained, not replaced**: whatever handler was\n * installed before still runs, because on RN that handler is what shows the\n * red box in dev and terminates the app on a fatal. Swallowing it would convert\n * a visible crash into a silent one.\n */\nexport function installGlobalErrorCapture(\n target: GlobalErrorTarget,\n options?: GlobalCaptureOptions,\n): GlobalCaptureHandle {\n const bufferSize = Math.max(0, options?.bufferSize ?? 20);\n const context = options?.context ?? {};\n let transport: CrashTransport | null = options?.transport ?? null;\n const pending: ReturnType<typeof createCrashPayload>[] = [];\n let installed = true;\n\n const emit = (error: unknown, extra?: Record<string, unknown>): void => {\n const payload = createCrashPayload(error, extra ? { ...context, ...extra } : { ...context });\n if (transport === null) {\n if (bufferSize === 0) return;\n if (pending.length === bufferSize) pending.shift();\n pending.push(payload);\n return;\n }\n reportSafely(transport, payload, 'reporting');\n };\n\n const onError = (event: unknown): void => {\n emit(unwrapEvent(event, 'error'), { source: 'error' });\n };\n const onRejection = (event: unknown): void => {\n emit(unwrapEvent(event, 'reason'), { source: 'unhandledrejection' });\n };\n\n const canListen =\n typeof target.addEventListener === 'function' &&\n typeof target.removeEventListener === 'function';\n if (canListen) {\n target.addEventListener?.('error', onError);\n target.addEventListener?.('unhandledrejection', onRejection);\n }\n\n const errorUtils = target.ErrorUtils;\n const previousHandler = errorUtils?.getGlobalHandler?.();\n if (errorUtils !== undefined) {\n errorUtils.setGlobalHandler((error: unknown, isFatal?: boolean) => {\n // Something may have re-captured a reference to this closure; after\n // uninstall it must only forward, never report.\n if (!installed) {\n previousHandler?.(error, isFatal);\n return;\n }\n emit(error, { source: 'errorUtils', isFatal: isFatal ?? false });\n // Chain, so the platform's own reporting still happens.\n previousHandler?.(error, isFatal);\n });\n }\n\n return {\n uninstall(): void {\n if (!installed) return;\n installed = false;\n if (canListen) {\n target.removeEventListener?.('error', onError);\n target.removeEventListener?.('unhandledrejection', onRejection);\n }\n if (errorUtils !== undefined) {\n // With nothing to restore, leave a no-op rather than the dead closure.\n errorUtils.setGlobalHandler(previousHandler ?? (() => {}));\n }\n },\n setTransport(next: CrashTransport): void {\n transport = next;\n while (pending.length > 0) {\n reportSafely(next, pending.shift()!, 'draining');\n }\n },\n get buffered(): number {\n return pending.length;\n },\n };\n}\n","import { payloadToError } from '../crash-payload.js';\nimport type { CrashTransport } from '../transport.js';\n\n/**\n * A Sentry-browser-shaped client, described structurally so this package takes\n * no dependency on `@sentry/browser` (or on any particular client).\n */\nexport interface ErrorClientLike {\n captureException(error: unknown, hint?: unknown): unknown;\n}\n\n/**\n * Transport over an injected browser error client.\n *\n * `createSentryTransport` is native-only — it dynamically imports\n * `@sentry/react-native`, which does not resolve on web. This is the web half:\n * the caller supplies an already-initialised client, so this package neither\n * imports nor initialises one.\n *\n * ```ts\n * import * as Sentry from '@sentry/browser';\n * Sentry.init({ dsn });\n * const transport = createClientTransport(Sentry);\n * ```\n *\n * The payload is rebuilt into an `Error` because that is what such clients\n * group by; the original stack is preserved rather than replaced with this\n * function's own.\n */\nexport function createClientTransport(client: ErrorClientLike): CrashTransport {\n return {\n report(payload): void {\n const error = payloadToError(payload);\n try {\n client.captureException(error, { extra: payload.context });\n } catch (err) {\n console.error('[@flare-engine/errors] client.captureException threw', err);\n }\n },\n };\n}\n","import { type CrashPayload, payloadToError } from '../crash-payload.js';\nimport type { CrashTransport } from '../transport.js';\nimport { createNoopTransport } from '../transport.js';\n\n/**\n * The shape of a Sentry integration this package relies on. Structural, so no\n * type from the optional `@sentry/react-native` peer leaks into the public API;\n * the SDK's own `Integration` objects satisfy it.\n */\nexport interface SentryIntegrationLike {\n name: string;\n}\n\nexport interface SentryTransportOptions {\n dsn?: string;\n environment?: string;\n release?: string;\n sampleRate?: number;\n enabled?: boolean;\n /**\n * Chooses the integrations `init` receives. `kept` is the ADR-0008 allowlist\n * (event processors only) applied to `defaults`, the SDK's own default list;\n * without this hook `init` receives `kept`. Returning `defaults`, or any\n * capture integration such as `ReactNativeErrorHandlers`, re-enables Sentry's\n * own global handlers, which report outside the transport and so outside any\n * consent check placed in front of it. A hook that throws is logged and\n * `kept` is used.\n */\n integrations?: (\n kept: SentryIntegrationLike[],\n defaults: SentryIntegrationLike[],\n ) => SentryIntegrationLike[];\n}\n\ntype SentryMod = typeof import('@sentry/react-native');\ntype IntegrationsFn = (defaults: SentryIntegrationLike[]) => SentryIntegrationLike[];\n\n// Sentry must send only what `report()` hands it (ADR-0008). The SDK's default\n// integrations include its own global error/rejection handlers, which report\n// outside the transport and so outside any consent check placed in front of\n// it, plus collectors (breadcrumbs, device context) that attach data to every\n// event. Only event processors that enrich an event already in flight are kept.\n// Fail-safe: a name that does not match on some SDK major only loses that\n// enrichment; an unknown name can never add a capture path.\nconst KEPT_INTEGRATIONS: ReadonlySet<string> = new Set([\n 'RewriteFrames',\n 'Release',\n 'DebugMeta',\n 'SdkInfo',\n 'Dedupe',\n 'InboundFilters',\n 'NativeLinkedErrors',\n 'EventOrigin',\n]);\n\nfunction keepEventProcessors(defaults: SentryIntegrationLike[]): SentryIntegrationLike[] {\n return defaults.filter((integration) => KEPT_INTEGRATIONS.has(integration.name));\n}\n\n// The SDK calls this inside `init`, so a throwing hook must be caught here or\n// it would read as an import failure and degrade the transport to noop.\nfunction withIntegrationsHook(\n hook: NonNullable<SentryTransportOptions['integrations']>,\n): IntegrationsFn {\n return (defaults) => {\n const kept = keepEventProcessors(defaults);\n try {\n return hook(kept, defaults);\n } catch (err) {\n console.error(\n '[@flare-engine/errors] SentryTransportOptions.integrations threw — using the default allowlist',\n err,\n );\n return kept;\n }\n };\n}\n\nasync function closeSdk(mod: SentryMod): Promise<void> {\n try {\n await mod.close();\n } catch (err) {\n console.error('[@flare-engine/errors] Sentry close failed', err);\n }\n}\n\nexport function createSentryTransport(opts: SentryTransportOptions): CrashTransport {\n if (!opts.dsn || opts.enabled === false) {\n return createNoopTransport();\n }\n\n const dsn = opts.dsn;\n const integrations =\n opts.integrations === undefined ? keepEventProcessors : withIntegrationsHook(opts.integrations);\n let mod: SentryMod | null = null;\n let loadFailed = false;\n let closed = false;\n let closing: Promise<void> | null = null;\n\n return {\n async report(payload: CrashPayload): Promise<void> {\n if (loadFailed || closed) return;\n\n if (mod === null) {\n try {\n const loaded = await import('@sentry/react-native');\n // `close()` may have run while the import was pending; starting a\n // client now would leave one nothing can shut down.\n if (closed) return;\n loaded.init({\n dsn,\n environment: opts.environment,\n release: opts.release,\n sampleRate: opts.sampleRate,\n integrations,\n enableAutoSessionTracking: false,\n enableNativeCrashHandling: false,\n enableAppHangTracking: false,\n enableWatchdogTerminationTracking: false,\n sendClientReports: false,\n });\n mod = loaded;\n } catch {\n console.error(\n '[@flare-engine/errors] Failed to load @sentry/react-native — degrading to noop',\n );\n loadFailed = true;\n return;\n }\n }\n\n try {\n mod.captureException(payloadToError(payload), {\n extra: { ...payload.context, capturedAt: payload.timestamp },\n });\n } catch {\n console.error('[@flare-engine/errors] Sentry captureException failed');\n }\n },\n close(): Promise<void> {\n if (closing === null) {\n closed = true;\n closing = mod === null ? Promise.resolve() : closeSdk(mod);\n }\n return closing;\n },\n };\n}\n"],"mappings":";;;AAEA,SAAgB,kBAAkB,GAAG,YAA8C;CACjF,OAAO;EACL,MAAM,OAAO,SAAS;GACpB,KAAK,MAAM,KAAK,YACd,IAAI;IACF,MAAM,EAAE,OAAO,OAAO;GACxB,SAAS,KAAK;IACZ,QAAQ,MAAM,mEAAmE,GAAG;GACtF;EAEJ;EACA,MAAM,QAAQ;GACZ,KAAK,MAAM,KAAK,YACd,IAAI;IACF,MAAM,EAAE,QAAQ;GAClB,SAAS,KAAK;IACZ,QAAQ,MACN,yEACA,GACF;GACF;EAEJ;CACF;AACF;;;;;;ACLA,SAAgB,mBACd,OACA,UAAmC,CAAC,GACtB;CACd,IAAI,iBAAiB,OACnB,OAAO;EACL,SAAS,MAAM;EACf,MAAM,MAAM;EACZ,OAAO,MAAM,SAAS;EACtB,WAAW,KAAK,IAAI;EACpB;CACF;CAEF,IAAI,OAAO,UAAU,UACnB,OAAO;EAAE,SAAS;EAAO,MAAM;EAAS,OAAO;EAAM,WAAW,KAAK,IAAI;EAAG;CAAQ;CAEtF,IAAI;CACJ,IAAI;EACF,UAAU,KAAK,UAAU,KAAK;CAChC,QAAQ;EACN,UAAU,OAAO,KAAK;CACxB;CACA,OAAO;EAAE;EAAS,MAAM;EAAY,OAAO;EAAM,WAAW,KAAK,IAAI;EAAG;CAAQ;AAClF;;;;;AAMA,SAAgB,eA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CAClB,SAAS,KAAK;EACZ,QAAQ,MAAM,8CAA8C,GAAG;CACjE;AACF;AAEA,SAAgB,sBAAsB,MAA8C;CAClF,IAAI,CAAC,KAAK,OAAO,KAAK,YAAY,OAChC,OAAO,oBAAoB;CAG7B,MAAM,MAAM,KAAK;CACjB,MAAM,eACJ,KAAK,iBAAiB,KAAA,IAAY,sBAAsB,qBAAqB,KAAK,YAAY;CAChG,IAAI,MAAwB;CAC5B,IAAI,aAAa;CACjB,IAAI,SAAS;CACb,IAAI,UAAgC;CAEpC,OAAO;EACL,MAAM,OAAO,SAAsC;GACjD,IAAI,cAAc,QAAQ;GAE1B,IAAI,QAAQ,MACV,IAAI;IACF,MAAM,SAAS,MAAM,OAAO;IAG5B,IAAI,QAAQ;IACZ,OAAO,KAAK;KACV;KACA,aAAa,KAAK;KAClB,SAAS,KAAK;KACd,YAAY,KAAK;KACjB;KACA,2BAA2B;KAC3B,2BAA2B;KAC3B,uBAAuB;KACvB,mCAAmC;KACnC,mBAAmB;IACrB,CAAC;IACD,MAAM;GACR,QAAQ;IACN,QAAQ,MACN,gFACF;IACA,aAAa;IACb;GACF;GAGF,IAAI;IACF,IAAI,iBAAiB,eAAe,OAAO,GAAG,EAC5C,OAAO;KAAE,GAAG,QAAQ;KAAS,YAAY,QAAQ;IAAU,EAC7D,CAAC;GACH,QAAQ;IACN,QAAQ,MAAM,uDAAuD;GACvE;EACF;EACA,QAAuB;GACrB,IAAI,YAAY,MAAM;IACpB,SAAS;IACT,UAAU,QAAQ,OAAO,QAAQ,QAAQ,IAAI,SAAS,GAAG;GAC3D;GACA,OAAO;EACT;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":["Component"],"sources":["../src/compose.ts","../src/crash-payload.ts","../src/transport.ts","../src/error-boundary.tsx","../src/global-capture.ts","../src/transports/client.ts","../src/transports/sentry.ts"],"sourcesContent":["import type { CrashTransport } from './transport.js';\n\nexport function composeTransports(...transports: CrashTransport[]): CrashTransport {\n return {\n async report(payload) {\n for (const t of transports) {\n try {\n await t.report(payload);\n } catch (err) {\n console.error('[@flare-engine/errors] composeTransports: child transport threw', err);\n }\n }\n },\n async close() {\n for (const t of transports) {\n try {\n await t.close?.();\n } catch (err) {\n console.error(\n '[@flare-engine/errors] composeTransports: child transport close threw',\n err,\n );\n }\n }\n },\n };\n}\n","/**\n * Serializable crash payload. Everything here is JSON-safe so transports can\n * post it to Sentry / Crashlytics / a custom HTTP endpoint without extra work.\n */\nexport interface CrashPayload {\n /** Error message. */\n message: string;\n /** Error name (e.g., `TypeError`). */\n name: string;\n /** Captured stack trace, if available. */\n stack: string | null;\n /** Monotonic ms timestamp — `Date.now()` at capture. */\n timestamp: number;\n /** Optional free-form context supplied by the caller. */\n context: Record<string, unknown>;\n}\n\n/**\n * Capture an unknown thrown value as a serializable crash payload. Handles\n * `Error` instances, string throws, and arbitrary values.\n */\nexport function createCrashPayload(\n error: unknown,\n context: Record<string, unknown> = {},\n): CrashPayload {\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n stack: error.stack ?? null,\n timestamp: Date.now(),\n context,\n };\n }\n if (typeof error === 'string') {\n return { message: error, name: 'Error', stack: null, timestamp: Date.now(), context };\n }\n let message: string;\n try {\n message = JSON.stringify(error);\n } catch {\n message = String(error);\n }\n return { message, name: 'NonError', stack: null, timestamp: Date.now(), context };\n}\n\n/**\n * Rebuild a payload into an `Error`, which is what error clients group by. The\n * captured stack replaces the new Error's own; a `null` stack leaves it as is.\n */\nexport function payloadToError(payload: CrashPayload): Error {\n const error = new Error(payload.message);\n error.name = payload.name;\n if (payload.stack !== null) error.stack = payload.stack;\n return error;\n}\n","import type { CrashPayload } from './crash-payload.js';\n\n/**\n * Pluggable transport for reporting crashes. Implementations send the payload\n * wherever they need — Sentry, Crashlytics, an HTTP endpoint, or nowhere.\n */\nexport interface CrashTransport {\n report(payload: CrashPayload): void | Promise<void>;\n /**\n * Tear the sink down, e.g. on consent revocation. Idempotent: a second call\n * resolves without closing twice. `report()` after `close()` sends nothing.\n * Transports with nothing to tear down leave it undefined.\n */\n close?(): Promise<void>;\n}\n\n/**\n * Call `transport.report` so that neither a synchronous throw nor a rejected\n * promise escapes. Left unhandled, a rejection surfaces on the global as an\n * `unhandledrejection` that `installGlobalErrorCapture` listens for, so each\n * failed report would trigger the next for as long as the transport is down.\n */\nexport function reportSafely(\n transport: CrashTransport,\n payload: CrashPayload,\n stage: 'reporting' | 'draining',\n): void {\n const onFailure = (err: unknown): void => {\n console.error(`[@flare-engine/errors] transport threw while ${stage}`, err);\n };\n try {\n void Promise.resolve(transport.report(payload)).catch(onFailure);\n } catch (err) {\n onFailure(err);\n }\n}\n\n/** Transport that discards every payload. The default. */\nexport function createNoopTransport(): CrashTransport {\n return {\n report() {\n /* no-op */\n },\n };\n}\n\n/**\n * Transport that logs payloads via `console.error`. Useful in development and\n * as a wrapper around another transport when debugging.\n */\nexport function createConsoleTransport(): CrashTransport {\n return {\n report(payload) {\n console.error('[@flare-engine/errors]', payload);\n },\n };\n}\n","import { Component, type ErrorInfo, type ReactNode } from 'react';\nimport { type CrashPayload, createCrashPayload } from './crash-payload.js';\nimport { type CrashTransport, reportSafely } from './transport.js';\n\nexport interface ErrorBoundaryProps {\n children: ReactNode;\n /** Rendered when an error is caught. Receives the payload + a reset callback. */\n fallback: (payload: CrashPayload, reset: () => void) => ReactNode;\n /** Transport invoked once per caught error. */\n transport?: CrashTransport;\n /** Additional context merged into every payload captured by this boundary. */\n context?: Record<string, unknown>;\n /** Called with both the raw error and the payload for custom side effects. */\n onError?: (error: unknown, payload: CrashPayload) => void;\n}\n\ninterface ErrorBoundaryState {\n payload: CrashPayload | null;\n}\n\n/**\n * React error boundary that captures render-phase errors into a structured\n * `CrashPayload`, forwards it to an optional transport, and renders the\n * caller-supplied fallback.\n */\nexport class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {\n state: ErrorBoundaryState = { payload: null };\n\n static getDerivedStateFromError(error: unknown): ErrorBoundaryState {\n return { payload: createCrashPayload(error) };\n }\n\n componentDidCatch(error: unknown, info: ErrorInfo): void {\n const context = {\n ...this.props.context,\n componentStack: info.componentStack ?? null,\n };\n const payload = createCrashPayload(error, context);\n this.setState({ payload });\n const { transport } = this.props;\n if (transport !== undefined) reportSafely(transport, payload, 'reporting');\n this.props.onError?.(error, payload);\n }\n\n reset = (): void => {\n this.setState({ payload: null });\n };\n\n render(): ReactNode {\n if (this.state.payload !== null) {\n return this.props.fallback(this.state.payload, this.reset);\n }\n return this.props.children;\n }\n}\n","import { createCrashPayload } from './crash-payload.js';\nimport { type CrashTransport, reportSafely } from './transport.js';\n\n/**\n * React Native's `global.ErrorUtils`, described structurally so this package\n * needs no React Native dependency or types.\n */\nexport interface ErrorUtilsLike {\n getGlobalHandler?(): ((error: unknown, isFatal?: boolean) => void) | undefined;\n setGlobalHandler(handler: (error: unknown, isFatal?: boolean) => void): void;\n}\n\n/**\n * What `installGlobalErrorCapture` needs from a global object.\n *\n * Both members are optional and independent, so one call handles either\n * platform: on web `globalThis` supplies `addEventListener`, on React Native it\n * supplies `ErrorUtils`, and in a test you pass a hand-built fake. Nothing here\n * references `window`, `document` or any RN type.\n */\nexport interface GlobalErrorTarget {\n addEventListener?(type: string, listener: (event: unknown) => void): void;\n removeEventListener?(type: string, listener: (event: unknown) => void): void;\n ErrorUtils?: ErrorUtilsLike;\n}\n\n/** Options for `installGlobalErrorCapture`. */\nexport interface GlobalCaptureOptions {\n /**\n * Where captured errors go. May be omitted at install and attached later with\n * `setTransport` — errors raised in between are held in the buffer below\n * rather than dropped.\n */\n transport?: CrashTransport;\n /**\n * How many pre-transport errors to retain. Default 20. The oldest is dropped\n * once full: a boot loop should not grow memory without bound, and the first\n * errors are the ones worth keeping.\n */\n bufferSize?: number;\n /** Context merged into every payload this capture produces. */\n context?: Record<string, unknown>;\n}\n\n/** Handle returned by `installGlobalErrorCapture`. */\nexport interface GlobalCaptureHandle {\n /**\n * Detach every handler this call installed and restore whatever was there\n * before. Safe to call more than once.\n */\n uninstall(): void;\n /** Attach or replace the transport, draining any buffered errors into it. */\n setTransport(transport: CrashTransport): void;\n /** How many errors are currently held awaiting a transport. */\n readonly buffered: number;\n}\n\n/** Pull the underlying error out of a structurally-typed DOM-ish event. */\nfunction unwrapEvent(event: unknown, key: 'error' | 'reason'): unknown {\n if (typeof event === 'object' && event !== null && key in event) {\n const value = (event as Record<string, unknown>)[key];\n if (value !== undefined && value !== null) return value;\n }\n // An ErrorEvent with no `.error` still carries a message worth reporting.\n if (typeof event === 'object' && event !== null && 'message' in event) {\n return (event as Record<string, unknown>).message;\n }\n return event;\n}\n\n/**\n * Route uncaught errors and unhandled rejections into a `CrashTransport`.\n *\n * `ErrorBoundary` only sees errors thrown during React's render phase. The\n * majority of a game's crashes are not there — they are in the update loop, in\n * an asset load, in a promise nobody awaited — and before this nothing carried\n * them to a transport.\n *\n * Both platforms are handled through the same call:\n *\n * ```ts\n * const capture = installGlobalErrorCapture(globalThis, { transport });\n * // ...\n * capture.uninstall();\n * ```\n *\n * The React Native handler is **chained, not replaced**: whatever handler was\n * installed before still runs, because on RN that handler is what shows the\n * red box in dev and terminates the app on a fatal. Swallowing it would convert\n * a visible crash into a silent one.\n */\nexport function installGlobalErrorCapture(\n target: GlobalErrorTarget,\n options?: GlobalCaptureOptions,\n): GlobalCaptureHandle {\n const bufferSize = Math.max(0, options?.bufferSize ?? 20);\n const context = options?.context ?? {};\n let transport: CrashTransport | null = options?.transport ?? null;\n const pending: ReturnType<typeof createCrashPayload>[] = [];\n let installed = true;\n\n const emit = (error: unknown, extra?: Record<string, unknown>): void => {\n const payload = createCrashPayload(error, extra ? { ...context, ...extra } : { ...context });\n if (transport === null) {\n if (bufferSize === 0) return;\n if (pending.length === bufferSize) pending.shift();\n pending.push(payload);\n return;\n }\n reportSafely(transport, payload, 'reporting');\n };\n\n const onError = (event: unknown): void => {\n emit(unwrapEvent(event, 'error'), { source: 'error' });\n };\n const onRejection = (event: unknown): void => {\n emit(unwrapEvent(event, 'reason'), { source: 'unhandledrejection' });\n };\n\n const canListen =\n typeof target.addEventListener === 'function' &&\n typeof target.removeEventListener === 'function';\n if (canListen) {\n target.addEventListener?.('error', onError);\n target.addEventListener?.('unhandledrejection', onRejection);\n }\n\n const errorUtils = target.ErrorUtils;\n const previousHandler = errorUtils?.getGlobalHandler?.();\n if (errorUtils !== undefined) {\n errorUtils.setGlobalHandler((error: unknown, isFatal?: boolean) => {\n // Something may have re-captured a reference to this closure; after\n // uninstall it must only forward, never report.\n if (!installed) {\n previousHandler?.(error, isFatal);\n return;\n }\n emit(error, { source: 'errorUtils', isFatal: isFatal ?? false });\n // Chain, so the platform's own reporting still happens.\n previousHandler?.(error, isFatal);\n });\n }\n\n return {\n uninstall(): void {\n if (!installed) return;\n installed = false;\n if (canListen) {\n target.removeEventListener?.('error', onError);\n target.removeEventListener?.('unhandledrejection', onRejection);\n }\n if (errorUtils !== undefined) {\n // With nothing to restore, leave a no-op rather than the dead closure.\n errorUtils.setGlobalHandler(previousHandler ?? (() => {}));\n }\n },\n setTransport(next: CrashTransport): void {\n transport = next;\n while (pending.length > 0) {\n reportSafely(next, pending.shift()!, 'draining');\n }\n },\n get buffered(): number {\n return pending.length;\n },\n };\n}\n","import { payloadToError } from '../crash-payload.js';\nimport type { CrashTransport } from '../transport.js';\n\n/**\n * A Sentry-browser-shaped client, described structurally so this package takes\n * no dependency on `@sentry/browser` (or on any particular client).\n */\nexport interface ErrorClientLike {\n captureException(error: unknown, hint?: unknown): unknown;\n}\n\n/**\n * Transport over an injected browser error client.\n *\n * `createSentryTransport` is native-only — it dynamically imports\n * `@sentry/react-native`, which does not resolve on web. This is the web half:\n * the caller supplies an already-initialised client, so this package neither\n * imports nor initialises one.\n *\n * ```ts\n * import * as Sentry from '@sentry/browser';\n * Sentry.init({ dsn });\n * const transport = createClientTransport(Sentry);\n * ```\n *\n * The payload is rebuilt into an `Error` because that is what such clients\n * group by; the original stack is preserved rather than replaced with this\n * function's own.\n */\nexport function createClientTransport(client: ErrorClientLike): CrashTransport {\n return {\n report(payload): void {\n const error = payloadToError(payload);\n try {\n client.captureException(error, { extra: payload.context });\n } catch (err) {\n console.error('[@flare-engine/errors] client.captureException threw', err);\n }\n },\n };\n}\n","import { type CrashPayload, payloadToError } from '../crash-payload.js';\nimport type { CrashTransport } from '../transport.js';\nimport { createNoopTransport } from '../transport.js';\n\n/**\n * The shape of a Sentry integration this package relies on. Structural, so no\n * type from the optional `@sentry/react-native` peer leaks into the public API;\n * the SDK's own `Integration` objects satisfy it.\n */\nexport interface SentryIntegrationLike {\n name: string;\n}\n\nexport interface SentryTransportOptions {\n dsn?: string;\n environment?: string;\n release?: string;\n sampleRate?: number;\n enabled?: boolean;\n /**\n * Chooses the integrations `init` receives. `kept` is the ADR-0008 allowlist\n * (event processors only) applied to `defaults`, the SDK's own default list;\n * without this hook `init` receives `kept`. Returning `defaults`, or any\n * capture integration such as `ReactNativeErrorHandlers`, re-enables Sentry's\n * own global handlers, which report outside the transport and so outside any\n * consent check placed in front of it. A hook that throws is logged and\n * `kept` is used.\n */\n integrations?: (\n kept: SentryIntegrationLike[],\n defaults: SentryIntegrationLike[],\n ) => SentryIntegrationLike[];\n}\n\ntype SentryMod = typeof import('@sentry/react-native');\ntype IntegrationsFn = (defaults: SentryIntegrationLike[]) => SentryIntegrationLike[];\n\n// Sentry must send only what `report()` hands it (ADR-0008). The SDK's default\n// integrations include its own global error/rejection handlers, which report\n// outside the transport and so outside any consent check placed in front of\n// it, plus collectors (breadcrumbs, device context) that attach data to every\n// event. Only event processors that enrich an event already in flight are kept.\n// Fail-safe: a name that does not match on some SDK major only loses that\n// enrichment; an unknown name can never add a capture path.\nconst KEPT_INTEGRATIONS: ReadonlySet<string> = new Set([\n 'RewriteFrames',\n 'Release',\n 'DebugMeta',\n 'SdkInfo',\n 'Dedupe',\n 'InboundFilters',\n 'NativeLinkedErrors',\n 'EventOrigin',\n]);\n\nfunction keepEventProcessors(defaults: SentryIntegrationLike[]): SentryIntegrationLike[] {\n return defaults.filter((integration) => KEPT_INTEGRATIONS.has(integration.name));\n}\n\n// The SDK calls this inside `init`, so a throwing hook must be caught here or\n// it would read as an import failure and degrade the transport to noop.\nfunction withIntegrationsHook(\n hook: NonNullable<SentryTransportOptions['integrations']>,\n): IntegrationsFn {\n return (defaults) => {\n const kept = keepEventProcessors(defaults);\n try {\n return hook(kept, defaults);\n } catch (err) {\n console.error(\n '[@flare-engine/errors] SentryTransportOptions.integrations threw — using the default allowlist',\n err,\n );\n return kept;\n }\n };\n}\n\nasync function closeSdk(mod: SentryMod): Promise<void> {\n try {\n await mod.close();\n } catch (err) {\n console.error('[@flare-engine/errors] Sentry close failed', err);\n }\n}\n\nexport function createSentryTransport(opts: SentryTransportOptions): CrashTransport {\n if (!opts.dsn || opts.enabled === false) {\n return createNoopTransport();\n }\n\n const dsn = opts.dsn;\n const integrations =\n opts.integrations === undefined ? keepEventProcessors : withIntegrationsHook(opts.integrations);\n let mod: SentryMod | null = null;\n let loadFailed = false;\n let closed = false;\n let closing: Promise<void> | null = null;\n\n return {\n async report(payload: CrashPayload): Promise<void> {\n if (loadFailed || closed) return;\n\n if (mod === null) {\n try {\n const loaded = await import('@sentry/react-native');\n // `close()` may have run while the import was pending; starting a\n // client now would leave one nothing can shut down.\n if (closed) return;\n loaded.init({\n dsn,\n environment: opts.environment,\n release: opts.release,\n sampleRate: opts.sampleRate,\n integrations,\n enableAutoSessionTracking: false,\n enableNativeCrashHandling: false,\n enableAppHangTracking: false,\n enableWatchdogTerminationTracking: false,\n sendClientReports: false,\n });\n mod = loaded;\n } catch {\n console.error(\n '[@flare-engine/errors] Failed to load @sentry/react-native — degrading to noop',\n );\n loadFailed = true;\n return;\n }\n }\n\n try {\n mod.captureException(payloadToError(payload), {\n extra: { ...payload.context, capturedAt: payload.timestamp },\n });\n } catch {\n console.error('[@flare-engine/errors] Sentry captureException failed');\n }\n },\n close(): Promise<void> {\n if (closing === null) {\n closed = true;\n closing = mod === null ? Promise.resolve() : closeSdk(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;GACjD,IAAI,cAAc,QAAQ;GAE1B,IAAI,QAAQ,MACV,IAAI;IACF,MAAM,SAAS,MAAM,OAAO;IAG5B,IAAI,QAAQ;IACZ,OAAO,KAAK;KACV;KACA,aAAa,KAAK;KAClB,SAAS,KAAK;KACd,YAAY,KAAK;KACjB;KACA,2BAA2B;KAC3B,2BAA2B;KAC3B,uBAAuB;KACvB,mCAAmC;KACnC,mBAAmB;IACrB,CAAC;IACD,MAAM;GACR,QAAQ;IACN,QAAQ,MACN,gFACF;IACA,aAAa;IACb;GACF;GAGF,IAAI;IACF,IAAI,iBAAiB,eAAe,OAAO,GAAG,EAC5C,OAAO;KAAE,GAAG,QAAQ;KAAS,YAAY,QAAQ;IAAU,EAC7D,CAAC;GACH,QAAQ;IACN,QAAQ,MAAM,uDAAuD;GACvE;EACF;EACA,QAAuB;GACrB,IAAI,YAAY,MAAM;IACpB,SAAS;IACT,UAAU,QAAQ,OAAO,QAAQ,QAAQ,IAAI,SAAS,GAAG;GAC3D;GACA,OAAO;EACT;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/compose.ts","../src/crash-payload.ts","../src/transport.ts","../src/error-boundary.tsx","../src/global-capture.ts","../src/transports/client.ts","../src/transports/sentry.ts"],"sourcesContent":["import type { CrashTransport } from './transport.js';\n\nexport function composeTransports(...transports: CrashTransport[]): CrashTransport {\n return {\n async report(payload) {\n for (const t of transports) {\n try {\n await t.report(payload);\n } catch (err) {\n console.error('[@flare-engine/errors] composeTransports: child transport threw', err);\n }\n }\n },\n async close() {\n for (const t of transports) {\n try {\n await t.close?.();\n } catch (err) {\n console.error(\n '[@flare-engine/errors] composeTransports: child transport close threw',\n err,\n );\n }\n }\n },\n };\n}\n","/**\n * Serializable crash payload. Everything here is JSON-safe so transports can\n * post it to Sentry / Crashlytics / a custom HTTP endpoint without extra work.\n */\nexport interface CrashPayload {\n /** Error message. */\n message: string;\n /** Error name (e.g., `TypeError`). */\n name: string;\n /** Captured stack trace, if available. */\n stack: string | null;\n /** Monotonic ms timestamp — `Date.now()` at capture. */\n timestamp: number;\n /** Optional free-form context supplied by the caller. */\n context: Record<string, unknown>;\n}\n\n/**\n * Capture an unknown thrown value as a serializable crash payload. Handles\n * `Error` instances, string throws, and arbitrary values.\n */\nexport function createCrashPayload(\n error: unknown,\n context: Record<string, unknown> = {},\n): CrashPayload {\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n stack: error.stack ?? null,\n timestamp: Date.now(),\n context,\n };\n }\n if (typeof error === 'string') {\n return { message: error, name: 'Error', stack: null, timestamp: Date.now(), context };\n }\n let message: string;\n try {\n message = JSON.stringify(error);\n } catch {\n message = String(error);\n }\n return { message, name: 'NonError', stack: null, timestamp: Date.now(), context };\n}\n\n/**\n * Rebuild a payload into an `Error`, which is what error clients group by. The\n * captured stack replaces the new Error's own; a `null` stack leaves it as is.\n */\nexport function payloadToError(payload: CrashPayload): Error {\n const error = new Error(payload.message);\n error.name = payload.name;\n if (payload.stack !== null) error.stack = payload.stack;\n return error;\n}\n","import type { CrashPayload } from './crash-payload.js';\n\n/**\n * Pluggable transport for reporting crashes. Implementations send the payload\n * wherever they need — Sentry, Crashlytics, an HTTP endpoint, or nowhere.\n */\nexport interface CrashTransport {\n report(payload: CrashPayload): void | Promise<void>;\n /**\n * Tear the sink down, e.g. on consent revocation. Idempotent: a second call\n * resolves without closing twice. `report()` after `close()` sends nothing.\n * Transports with nothing to tear down leave it undefined.\n */\n close?(): Promise<void>;\n}\n\n/**\n * Call `transport.report` so that neither a synchronous throw nor a rejected\n * promise escapes. Left unhandled, a rejection surfaces on the global as an\n * `unhandledrejection` that `installGlobalErrorCapture` listens for, so each\n * failed report would trigger the next for as long as the transport is down.\n */\nexport function reportSafely(\n transport: CrashTransport,\n payload: CrashPayload,\n stage: 'reporting' | 'draining',\n): void {\n const onFailure = (err: unknown): void => {\n console.error(`[@flare-engine/errors] transport threw while ${stage}`, err);\n };\n try {\n void Promise.resolve(transport.report(payload)).catch(onFailure);\n } catch (err) {\n onFailure(err);\n }\n}\n\n/** Transport that discards every payload. The default. */\nexport function createNoopTransport(): CrashTransport {\n return {\n report() {\n /* no-op */\n },\n };\n}\n\n/**\n * Transport that logs payloads via `console.error`. Useful in development and\n * as a wrapper around another transport when debugging.\n */\nexport function createConsoleTransport(): CrashTransport {\n return {\n report(payload) {\n console.error('[@flare-engine/errors]', payload);\n },\n };\n}\n","import { Component, type ErrorInfo, type ReactNode } from 'react';\nimport { type CrashPayload, createCrashPayload } from './crash-payload.js';\nimport { type CrashTransport, reportSafely } from './transport.js';\n\nexport interface ErrorBoundaryProps {\n children: ReactNode;\n /** Rendered when an error is caught. Receives the payload + a reset callback. */\n fallback: (payload: CrashPayload, reset: () => void) => ReactNode;\n /** Transport invoked once per caught error. */\n transport?: CrashTransport;\n /** Additional context merged into every payload captured by this boundary. */\n context?: Record<string, unknown>;\n /** Called with both the raw error and the payload for custom side effects. */\n onError?: (error: unknown, payload: CrashPayload) => void;\n}\n\ninterface ErrorBoundaryState {\n payload: CrashPayload | null;\n}\n\n/**\n * React error boundary that captures render-phase errors into a structured\n * `CrashPayload`, forwards it to an optional transport, and renders the\n * caller-supplied fallback.\n */\nexport class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {\n state: ErrorBoundaryState = { payload: null };\n\n static getDerivedStateFromError(error: unknown): ErrorBoundaryState {\n return { payload: createCrashPayload(error) };\n }\n\n componentDidCatch(error: unknown, info: ErrorInfo): void {\n const context = {\n ...this.props.context,\n componentStack: info.componentStack ?? null,\n };\n const payload = createCrashPayload(error, context);\n this.setState({ payload });\n const { transport } = this.props;\n if (transport !== undefined) reportSafely(transport, payload, 'reporting');\n this.props.onError?.(error, payload);\n }\n\n reset = (): void => {\n this.setState({ payload: null });\n };\n\n render(): ReactNode {\n if (this.state.payload !== null) {\n return this.props.fallback(this.state.payload, this.reset);\n }\n return this.props.children;\n }\n}\n","import { createCrashPayload } from './crash-payload.js';\nimport { type CrashTransport, reportSafely } from './transport.js';\n\n/**\n * React Native's `global.ErrorUtils`, described structurally so this package\n * needs no React Native dependency or types.\n */\nexport interface ErrorUtilsLike {\n getGlobalHandler?(): ((error: unknown, isFatal?: boolean) => void) | undefined;\n setGlobalHandler(handler: (error: unknown, isFatal?: boolean) => void): void;\n}\n\n/**\n * What `installGlobalErrorCapture` needs from a global object.\n *\n * Both members are optional and independent, so one call handles either\n * platform: on web `globalThis` supplies `addEventListener`, on React Native it\n * supplies `ErrorUtils`, and in a test you pass a hand-built fake. Nothing here\n * references `window`, `document` or any RN type.\n */\nexport interface GlobalErrorTarget {\n addEventListener?(type: string, listener: (event: unknown) => void): void;\n removeEventListener?(type: string, listener: (event: unknown) => void): void;\n ErrorUtils?: ErrorUtilsLike;\n}\n\n/** Options for `installGlobalErrorCapture`. */\nexport interface GlobalCaptureOptions {\n /**\n * Where captured errors go. May be omitted at install and attached later with\n * `setTransport` — errors raised in between are held in the buffer below\n * rather than dropped.\n */\n transport?: CrashTransport;\n /**\n * How many pre-transport errors to retain. Default 20. The oldest is dropped\n * once full: a boot loop should not grow memory without bound, and the first\n * errors are the ones worth keeping.\n */\n bufferSize?: number;\n /** Context merged into every payload this capture produces. */\n context?: Record<string, unknown>;\n}\n\n/** Handle returned by `installGlobalErrorCapture`. */\nexport interface GlobalCaptureHandle {\n /**\n * Detach every handler this call installed and restore whatever was there\n * before. Safe to call more than once.\n */\n uninstall(): void;\n /** Attach or replace the transport, draining any buffered errors into it. */\n setTransport(transport: CrashTransport): void;\n /** How many errors are currently held awaiting a transport. */\n readonly buffered: number;\n}\n\n/** Pull the underlying error out of a structurally-typed DOM-ish event. */\nfunction unwrapEvent(event: unknown, key: 'error' | 'reason'): unknown {\n if (typeof event === 'object' && event !== null && key in event) {\n const value = (event as Record<string, unknown>)[key];\n if (value !== undefined && value !== null) return value;\n }\n // An ErrorEvent with no `.error` still carries a message worth reporting.\n if (typeof event === 'object' && event !== null && 'message' in event) {\n return (event as Record<string, unknown>).message;\n }\n return event;\n}\n\n/**\n * Route uncaught errors and unhandled rejections into a `CrashTransport`.\n *\n * `ErrorBoundary` only sees errors thrown during React's render phase. The\n * majority of a game's crashes are not there — they are in the update loop, in\n * an asset load, in a promise nobody awaited — and before this nothing carried\n * them to a transport.\n *\n * Both platforms are handled through the same call:\n *\n * ```ts\n * const capture = installGlobalErrorCapture(globalThis, { transport });\n * // ...\n * capture.uninstall();\n * ```\n *\n * The React Native handler is **chained, not replaced**: whatever handler was\n * installed before still runs, because on RN that handler is what shows the\n * red box in dev and terminates the app on a fatal. Swallowing it would convert\n * a visible crash into a silent one.\n */\nexport function installGlobalErrorCapture(\n target: GlobalErrorTarget,\n options?: GlobalCaptureOptions,\n): GlobalCaptureHandle {\n const bufferSize = Math.max(0, options?.bufferSize ?? 20);\n const context = options?.context ?? {};\n let transport: CrashTransport | null = options?.transport ?? null;\n const pending: ReturnType<typeof createCrashPayload>[] = [];\n let installed = true;\n\n const emit = (error: unknown, extra?: Record<string, unknown>): void => {\n const payload = createCrashPayload(error, extra ? { ...context, ...extra } : { ...context });\n if (transport === null) {\n if (bufferSize === 0) return;\n if (pending.length === bufferSize) pending.shift();\n pending.push(payload);\n return;\n }\n reportSafely(transport, payload, 'reporting');\n };\n\n const onError = (event: unknown): void => {\n emit(unwrapEvent(event, 'error'), { source: 'error' });\n };\n const onRejection = (event: unknown): void => {\n emit(unwrapEvent(event, 'reason'), { source: 'unhandledrejection' });\n };\n\n const canListen =\n typeof target.addEventListener === 'function' &&\n typeof target.removeEventListener === 'function';\n if (canListen) {\n target.addEventListener?.('error', onError);\n target.addEventListener?.('unhandledrejection', onRejection);\n }\n\n const errorUtils = target.ErrorUtils;\n const previousHandler = errorUtils?.getGlobalHandler?.();\n if (errorUtils !== undefined) {\n errorUtils.setGlobalHandler((error: unknown, isFatal?: boolean) => {\n // Something may have re-captured a reference to this closure; after\n // uninstall it must only forward, never report.\n if (!installed) {\n previousHandler?.(error, isFatal);\n return;\n }\n emit(error, { source: 'errorUtils', isFatal: isFatal ?? false });\n // Chain, so the platform's own reporting still happens.\n previousHandler?.(error, isFatal);\n });\n }\n\n return {\n uninstall(): void {\n if (!installed) return;\n installed = false;\n if (canListen) {\n target.removeEventListener?.('error', onError);\n target.removeEventListener?.('unhandledrejection', onRejection);\n }\n if (errorUtils !== undefined) {\n // With nothing to restore, leave a no-op rather than the dead closure.\n errorUtils.setGlobalHandler(previousHandler ?? (() => {}));\n }\n },\n setTransport(next: CrashTransport): void {\n transport = next;\n while (pending.length > 0) {\n reportSafely(next, pending.shift()!, 'draining');\n }\n },\n get buffered(): number {\n return pending.length;\n },\n };\n}\n","import { payloadToError } from '../crash-payload.js';\nimport type { CrashTransport } from '../transport.js';\n\n/**\n * A Sentry-browser-shaped client, described structurally so this package takes\n * no dependency on `@sentry/browser` (or on any particular client).\n */\nexport interface ErrorClientLike {\n captureException(error: unknown, hint?: unknown): unknown;\n}\n\n/**\n * Transport over an injected browser error client.\n *\n * `createSentryTransport` is native-only — it dynamically imports\n * `@sentry/react-native`, which does not resolve on web. This is the web half:\n * the caller supplies an already-initialised client, so this package neither\n * imports nor initialises one.\n *\n * ```ts\n * import * as Sentry from '@sentry/browser';\n * Sentry.init({ dsn });\n * const transport = createClientTransport(Sentry);\n * ```\n *\n * The payload is rebuilt into an `Error` because that is what such clients\n * group by; the original stack is preserved rather than replaced with this\n * function's own.\n */\nexport function createClientTransport(client: ErrorClientLike): CrashTransport {\n return {\n report(payload): void {\n const error = payloadToError(payload);\n try {\n client.captureException(error, { extra: payload.context });\n } catch (err) {\n console.error('[@flare-engine/errors] client.captureException threw', err);\n }\n },\n };\n}\n","import { type CrashPayload, payloadToError } from '../crash-payload.js';\nimport type { CrashTransport } from '../transport.js';\nimport { createNoopTransport } from '../transport.js';\n\n/**\n * The shape of a Sentry integration this package relies on. Structural, so no\n * type from the optional `@sentry/react-native` peer leaks into the public API;\n * the SDK's own `Integration` objects satisfy it.\n */\nexport interface SentryIntegrationLike {\n name: string;\n}\n\nexport interface SentryTransportOptions {\n dsn?: string;\n environment?: string;\n release?: string;\n sampleRate?: number;\n enabled?: boolean;\n /**\n * Chooses the integrations `init` receives. `kept` is the ADR-0008 allowlist\n * (event processors only) applied to `defaults`, the SDK's own default list;\n * without this hook `init` receives `kept`. Returning `defaults`, or any\n * capture integration such as `ReactNativeErrorHandlers`, re-enables Sentry's\n * own global handlers, which report outside the transport and so outside any\n * consent check placed in front of it. A hook that throws is logged and\n * `kept` is used.\n */\n integrations?: (\n kept: SentryIntegrationLike[],\n defaults: SentryIntegrationLike[],\n ) => SentryIntegrationLike[];\n}\n\ntype SentryMod = typeof import('@sentry/react-native');\ntype IntegrationsFn = (defaults: SentryIntegrationLike[]) => SentryIntegrationLike[];\n\n// Sentry must send only what `report()` hands it (ADR-0008). The SDK's default\n// integrations include its own global error/rejection handlers, which report\n// outside the transport and so outside any consent check placed in front of\n// it, plus collectors (breadcrumbs, device context) that attach data to every\n// event. Only event processors that enrich an event already in flight are kept.\n// Fail-safe: a name that does not match on some SDK major only loses that\n// enrichment; an unknown name can never add a capture path.\nconst KEPT_INTEGRATIONS: ReadonlySet<string> = new Set([\n 'RewriteFrames',\n 'Release',\n 'DebugMeta',\n 'SdkInfo',\n 'Dedupe',\n 'InboundFilters',\n 'NativeLinkedErrors',\n 'EventOrigin',\n]);\n\nfunction keepEventProcessors(defaults: SentryIntegrationLike[]): SentryIntegrationLike[] {\n return defaults.filter((integration) => KEPT_INTEGRATIONS.has(integration.name));\n}\n\n// The SDK calls this inside `init`, so a throwing hook must be caught here or\n// it would read as an import failure and degrade the transport to noop.\nfunction withIntegrationsHook(\n hook: NonNullable<SentryTransportOptions['integrations']>,\n): IntegrationsFn {\n return (defaults) => {\n const kept = keepEventProcessors(defaults);\n try {\n return hook(kept, defaults);\n } catch (err) {\n console.error(\n '[@flare-engine/errors] SentryTransportOptions.integrations threw — using the default allowlist',\n err,\n );\n return kept;\n }\n };\n}\n\nasync function closeSdk(mod: SentryMod): Promise<void> {\n try {\n await mod.close();\n } catch (err) {\n console.error('[@flare-engine/errors] Sentry close failed', err);\n }\n}\n\nexport function createSentryTransport(opts: SentryTransportOptions): CrashTransport {\n if (!opts.dsn || opts.enabled === false) {\n return createNoopTransport();\n }\n\n const dsn = opts.dsn;\n const integrations =\n opts.integrations === undefined ? keepEventProcessors : withIntegrationsHook(opts.integrations);\n let mod: SentryMod | null = null;\n let loadFailed = false;\n let closed = false;\n let closing: Promise<void> | null = null;\n\n return {\n async report(payload: CrashPayload): Promise<void> {\n if (loadFailed || closed) return;\n\n if (mod === null) {\n try {\n const loaded = await import('@sentry/react-native');\n // `close()` may have run while the import was pending; starting a\n // client now would leave one nothing can shut down.\n if (closed) return;\n loaded.init({\n dsn,\n environment: opts.environment,\n release: opts.release,\n sampleRate: opts.sampleRate,\n integrations,\n enableAutoSessionTracking: false,\n enableNativeCrashHandling: false,\n enableAppHangTracking: false,\n enableWatchdogTerminationTracking: false,\n sendClientReports: false,\n });\n mod = loaded;\n } catch {\n console.error(\n '[@flare-engine/errors] Failed to load @sentry/react-native — degrading to noop',\n );\n loadFailed = true;\n return;\n }\n }\n\n try {\n mod.captureException(payloadToError(payload), {\n extra: { ...payload.context, capturedAt: payload.timestamp },\n });\n } catch {\n console.error('[@flare-engine/errors] Sentry captureException failed');\n }\n },\n close(): Promise<void> {\n if (closing === null) {\n closed = true;\n closing = mod === null ? Promise.resolve() : closeSdk(mod);\n }\n return closing;\n },\n };\n}\n"],"mappings":";;AAEA,SAAgB,kBAAkB,GAAG,YAA8C;CACjF,OAAO;EACL,MAAM,OAAO,SAAS;GACpB,KAAK,MAAM,KAAK,YACd,IAAI;IACF,MAAM,EAAE,OAAO,OAAO;GACxB,SAAS,KAAK;IACZ,QAAQ,MAAM,mEAAmE,GAAG;GACtF;EAEJ;EACA,MAAM,QAAQ;GACZ,KAAK,MAAM,KAAK,YACd,IAAI;IACF,MAAM,EAAE,QAAQ;GAClB,SAAS,KAAK;IACZ,QAAQ,MACN,y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iBAAiB,eAAe,OAAO,GAAG,EAC5C,OAAO;KAAE,GAAG,QAAQ;KAAS,YAAY,QAAQ;IAAU,EAC7D,CAAC;GACH,QAAQ;IACN,QAAQ,MAAM,uDAAuD;GACvE;EACF;EACA,QAAuB;GACrB,IAAI,YAAY,MAAM;IACpB,SAAS;IACT,UAAU,QAAQ,OAAO,QAAQ,QAAQ,IAAI,SAAS,GAAG;GAC3D;GACA,OAAO;EACT;CACF;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/compose.ts","../src/crash-payload.ts","../src/transport.ts","../src/error-boundary.tsx","../src/global-capture.ts","../src/transports/client.ts","../src/transports/sentry.ts"],"sourcesContent":["import type { CrashTransport } from './transport.js';\n\nexport function composeTransports(...transports: CrashTransport[]): CrashTransport {\n return {\n async report(payload) {\n for (const t of transports) {\n try {\n await t.report(payload);\n } catch (err) {\n console.error('[@flare-engine/errors] composeTransports: child transport threw', err);\n }\n }\n },\n async close() {\n for (const t of transports) {\n try {\n await t.close?.();\n } catch (err) {\n console.error(\n '[@flare-engine/errors] composeTransports: child transport close threw',\n err,\n );\n }\n }\n },\n };\n}\n","/**\n * Serializable crash payload. Everything here is JSON-safe so transports can\n * post it to Sentry / Crashlytics / a custom HTTP endpoint without extra work.\n */\nexport interface CrashPayload {\n /** Error message. */\n message: string;\n /** Error name (e.g., `TypeError`). */\n name: string;\n /** Captured stack trace, if available. */\n stack: string | null;\n /** Monotonic ms timestamp — `Date.now()` at capture. */\n timestamp: number;\n /** Optional free-form context supplied by the caller. */\n context: Record<string, unknown>;\n}\n\n/**\n * Capture an unknown thrown value as a serializable crash payload. Handles\n * `Error` instances, string throws, and arbitrary values.\n */\nexport function createCrashPayload(\n error: unknown,\n context: Record<string, unknown> = {},\n): CrashPayload {\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n stack: error.stack ?? null,\n timestamp: Date.now(),\n context,\n };\n }\n if (typeof error === 'string') {\n return { message: error, name: 'Error', stack: null, timestamp: Date.now(), context };\n }\n let message: string;\n try {\n message = JSON.stringify(error);\n } catch {\n message = String(error);\n }\n return { message, name: 'NonError', stack: null, timestamp: Date.now(), context };\n}\n\n/**\n * Rebuild a payload into an `Error`, which is what error clients group by. The\n * captured stack replaces the new Error's own; a `null` stack leaves it as is.\n */\nexport function payloadToError(payload: CrashPayload): Error {\n const error = new Error(payload.message);\n error.name = payload.name;\n if (payload.stack !== null) error.stack = payload.stack;\n return error;\n}\n","import type { CrashPayload } from './crash-payload.js';\n\n/**\n * Pluggable transport for reporting crashes. Implementations send the payload\n * wherever they need — Sentry, Crashlytics, an HTTP endpoint, or nowhere.\n */\nexport interface CrashTransport {\n report(payload: CrashPayload): void | Promise<void>;\n /**\n * Tear the sink down, e.g. on consent revocation. Idempotent: a second call\n * resolves without closing twice. `report()` after `close()` sends nothing.\n * Transports with nothing to tear down leave it undefined.\n */\n close?(): Promise<void>;\n}\n\n/**\n * Call `transport.report` so that neither a synchronous throw nor a rejected\n * promise escapes. Left unhandled, a rejection surfaces on the global as an\n * `unhandledrejection` that `installGlobalErrorCapture` listens for, so each\n * failed report would trigger the next for as long as the transport is down.\n */\nexport function reportSafely(\n transport: CrashTransport,\n payload: CrashPayload,\n stage: 'reporting' | 'draining',\n): void {\n const onFailure = (err: unknown): void => {\n console.error(`[@flare-engine/errors] transport threw while ${stage}`, err);\n };\n try {\n void Promise.resolve(transport.report(payload)).catch(onFailure);\n } catch (err) {\n onFailure(err);\n }\n}\n\n/** Transport that discards every payload. The default. */\nexport function createNoopTransport(): CrashTransport {\n return {\n report() {\n /* no-op */\n },\n };\n}\n\n/**\n * Transport that logs payloads via `console.error`. Useful in development and\n * as a wrapper around another transport when debugging.\n */\nexport function createConsoleTransport(): CrashTransport {\n return {\n report(payload) {\n console.error('[@flare-engine/errors]', payload);\n },\n };\n}\n","import { Component, type ErrorInfo, type ReactNode } from 'react';\nimport { type CrashPayload, createCrashPayload } from './crash-payload.js';\nimport { type CrashTransport, reportSafely } from './transport.js';\n\nexport interface ErrorBoundaryProps {\n children: ReactNode;\n /** Rendered when an error is caught. Receives the payload + a reset callback. */\n fallback: (payload: CrashPayload, reset: () => void) => ReactNode;\n /** Transport invoked once per caught error. */\n transport?: CrashTransport;\n /** Additional context merged into every payload captured by this boundary. */\n context?: Record<string, unknown>;\n /** Called with both the raw error and the payload for custom side effects. */\n onError?: (error: unknown, payload: CrashPayload) => void;\n}\n\ninterface ErrorBoundaryState {\n payload: CrashPayload | null;\n}\n\n/**\n * React error boundary that captures render-phase errors into a structured\n * `CrashPayload`, forwards it to an optional transport, and renders the\n * caller-supplied fallback.\n */\nexport class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {\n state: ErrorBoundaryState = { payload: null };\n\n static getDerivedStateFromError(error: unknown): ErrorBoundaryState {\n return { payload: createCrashPayload(error) };\n }\n\n componentDidCatch(error: unknown, info: ErrorInfo): void {\n const context = {\n ...this.props.context,\n componentStack: info.componentStack ?? null,\n };\n const payload = createCrashPayload(error, context);\n this.setState({ payload });\n const { transport } = this.props;\n if (transport !== undefined) reportSafely(transport, payload, 'reporting');\n this.props.onError?.(error, payload);\n }\n\n reset = (): void => {\n this.setState({ payload: null });\n };\n\n render(): ReactNode {\n if (this.state.payload !== null) {\n return this.props.fallback(this.state.payload, this.reset);\n }\n return this.props.children;\n }\n}\n","import { createCrashPayload } from './crash-payload.js';\nimport { type CrashTransport, reportSafely } from './transport.js';\n\n/**\n * React Native's `global.ErrorUtils`, described structurally so this package\n * needs no React Native dependency or types.\n */\nexport interface ErrorUtilsLike {\n getGlobalHandler?(): ((error: unknown, isFatal?: boolean) => void) | undefined;\n setGlobalHandler(handler: (error: unknown, isFatal?: boolean) => void): void;\n}\n\n/**\n * What `installGlobalErrorCapture` needs from a global object.\n *\n * Both members are optional and independent, so one call handles either\n * platform: on web `globalThis` supplies `addEventListener`, on React Native it\n * supplies `ErrorUtils`, and in a test you pass a hand-built fake. Nothing here\n * references `window`, `document` or any RN type.\n */\nexport interface GlobalErrorTarget {\n addEventListener?(type: string, listener: (event: unknown) => void): void;\n removeEventListener?(type: string, listener: (event: unknown) => void): void;\n ErrorUtils?: ErrorUtilsLike;\n}\n\n/** Options for `installGlobalErrorCapture`. */\nexport interface GlobalCaptureOptions {\n /**\n * Where captured errors go. May be omitted at install and attached later with\n * `setTransport` — errors raised in between are held in the buffer below\n * rather than dropped.\n */\n transport?: CrashTransport;\n /**\n * How many pre-transport errors to retain. Default 20. The oldest is dropped\n * once full: a boot loop should not grow memory without bound, and the first\n * errors are the ones worth keeping.\n */\n bufferSize?: number;\n /** Context merged into every payload this capture produces. */\n context?: Record<string, unknown>;\n}\n\n/** Handle returned by `installGlobalErrorCapture`. */\nexport interface GlobalCaptureHandle {\n /**\n * Detach every handler this call installed and restore whatever was there\n * before. Safe to call more than once.\n */\n uninstall(): void;\n /** Attach or replace the transport, draining any buffered errors into it. */\n setTransport(transport: CrashTransport): void;\n /** How many errors are currently held awaiting a transport. */\n readonly buffered: number;\n}\n\n/** Pull the underlying error out of a structurally-typed DOM-ish event. */\nfunction unwrapEvent(event: unknown, key: 'error' | 'reason'): unknown {\n if (typeof event === 'object' && event !== null && key in event) {\n const value = (event as Record<string, unknown>)[key];\n if (value !== undefined && value !== null) return value;\n }\n // An ErrorEvent with no `.error` still carries a message worth reporting.\n if (typeof event === 'object' && event !== null && 'message' in event) {\n return (event as Record<string, unknown>).message;\n }\n return event;\n}\n\n/**\n * Route uncaught errors and unhandled rejections into a `CrashTransport`.\n *\n * `ErrorBoundary` only sees errors thrown during React's render phase. The\n * majority of a game's crashes are not there — they are in the update loop, in\n * an asset load, in a promise nobody awaited — and before this nothing carried\n * them to a transport.\n *\n * Both platforms are handled through the same call:\n *\n * ```ts\n * const capture = installGlobalErrorCapture(globalThis, { transport });\n * // ...\n * capture.uninstall();\n * ```\n *\n * The React Native handler is **chained, not replaced**: whatever handler was\n * installed before still runs, because on RN that handler is what shows the\n * red box in dev and terminates the app on a fatal. Swallowing it would convert\n * a visible crash into a silent one.\n */\nexport function installGlobalErrorCapture(\n target: GlobalErrorTarget,\n options?: GlobalCaptureOptions,\n): GlobalCaptureHandle {\n const bufferSize = Math.max(0, options?.bufferSize ?? 20);\n const context = options?.context ?? {};\n let transport: CrashTransport | null = options?.transport ?? null;\n const pending: ReturnType<typeof createCrashPayload>[] = [];\n let installed = true;\n\n const emit = (error: unknown, extra?: Record<string, unknown>): void => {\n const payload = createCrashPayload(error, extra ? { ...context, ...extra } : { ...context });\n if (transport === null) {\n if (bufferSize === 0) return;\n if (pending.length === bufferSize) pending.shift();\n pending.push(payload);\n return;\n }\n reportSafely(transport, payload, 'reporting');\n };\n\n const onError = (event: unknown): void => {\n emit(unwrapEvent(event, 'error'), { source: 'error' });\n };\n const onRejection = (event: unknown): void => {\n emit(unwrapEvent(event, 'reason'), { source: 'unhandledrejection' });\n };\n\n const canListen =\n typeof target.addEventListener === 'function' &&\n typeof target.removeEventListener === 'function';\n if (canListen) {\n target.addEventListener?.('error', onError);\n target.addEventListener?.('unhandledrejection', onRejection);\n }\n\n const errorUtils = target.ErrorUtils;\n const previousHandler = errorUtils?.getGlobalHandler?.();\n if (errorUtils !== undefined) {\n errorUtils.setGlobalHandler((error: unknown, isFatal?: boolean) => {\n // Something may have re-captured a reference to this closure; after\n // uninstall it must only forward, never report.\n if (!installed) {\n previousHandler?.(error, isFatal);\n return;\n }\n emit(error, { source: 'errorUtils', isFatal: isFatal ?? false });\n // Chain, so the platform's own reporting still happens.\n previousHandler?.(error, isFatal);\n });\n }\n\n return {\n uninstall(): void {\n if (!installed) return;\n installed = false;\n if (canListen) {\n target.removeEventListener?.('error', onError);\n target.removeEventListener?.('unhandledrejection', onRejection);\n }\n if (errorUtils !== undefined) {\n // With nothing to restore, leave a no-op rather than the dead closure.\n errorUtils.setGlobalHandler(previousHandler ?? (() => {}));\n }\n },\n setTransport(next: CrashTransport): void {\n transport = next;\n while (pending.length > 0) {\n reportSafely(next, pending.shift()!, 'draining');\n }\n },\n get buffered(): number {\n return pending.length;\n },\n };\n}\n","import { payloadToError } from '../crash-payload.js';\nimport type { CrashTransport } from '../transport.js';\n\n/**\n * A Sentry-browser-shaped client, described structurally so this package takes\n * no dependency on `@sentry/browser` (or on any particular client).\n */\nexport interface ErrorClientLike {\n captureException(error: unknown, hint?: unknown): unknown;\n}\n\n/**\n * Transport over an injected browser error client.\n *\n * `createSentryTransport` is native-only — it dynamically imports\n * `@sentry/react-native`, which does not resolve on web. This is the web half:\n * the caller supplies an already-initialised client, so this package neither\n * imports nor initialises one.\n *\n * ```ts\n * import * as Sentry from '@sentry/browser';\n * Sentry.init({ dsn });\n * const transport = createClientTransport(Sentry);\n * ```\n *\n * The payload is rebuilt into an `Error` because that is what such clients\n * group by; the original stack is preserved rather than replaced with this\n * function's own.\n */\nexport function createClientTransport(client: ErrorClientLike): CrashTransport {\n return {\n report(payload): void {\n const error = payloadToError(payload);\n try {\n client.captureException(error, { extra: payload.context });\n } catch (err) {\n console.error('[@flare-engine/errors] client.captureException threw', err);\n }\n },\n };\n}\n","import { type CrashPayload, payloadToError } from '../crash-payload.js';\nimport type { CrashTransport } from '../transport.js';\nimport { createNoopTransport } from '../transport.js';\n\n/**\n * The shape of a Sentry integration this package relies on. Structural, so no\n * type from the optional `@sentry/react-native` peer leaks into the public API;\n * the SDK's own `Integration` objects satisfy it.\n */\nexport interface SentryIntegrationLike {\n name: string;\n}\n\nexport interface SentryTransportOptions {\n dsn?: string;\n environment?: string;\n release?: string;\n sampleRate?: number;\n enabled?: boolean;\n /**\n * Chooses the integrations `init` receives. `kept` is the ADR-0008 allowlist\n * (event processors only) applied to `defaults`, the SDK's own default list;\n * without this hook `init` receives `kept`. Returning `defaults`, or any\n * capture integration such as `ReactNativeErrorHandlers`, re-enables Sentry's\n * own global handlers, which report outside the transport and so outside any\n * consent check placed in front of it. A hook that throws is logged and\n * `kept` is used.\n */\n integrations?: (\n kept: SentryIntegrationLike[],\n defaults: SentryIntegrationLike[],\n ) => SentryIntegrationLike[];\n}\n\ntype SentryMod = typeof import('@sentry/react-native');\ntype IntegrationsFn = (defaults: SentryIntegrationLike[]) => SentryIntegrationLike[];\n\n// Sentry must send only what `report()` hands it (ADR-0008). The SDK's default\n// integrations include its own global error/rejection handlers, which report\n// outside the transport and so outside any consent check placed in front of\n// it, plus collectors (breadcrumbs, device context) that attach data to every\n// event. Only event processors that enrich an event already in flight are kept.\n// Fail-safe: a name that does not match on some SDK major only loses that\n// enrichment; an unknown name can never add a capture path.\nconst KEPT_INTEGRATIONS: ReadonlySet<string> = new Set([\n 'RewriteFrames',\n 'Release',\n 'DebugMeta',\n 'SdkInfo',\n 'Dedupe',\n 'InboundFilters',\n 'NativeLinkedErrors',\n 'EventOrigin',\n]);\n\nfunction keepEventProcessors(defaults: SentryIntegrationLike[]): SentryIntegrationLike[] {\n return defaults.filter((integration) => KEPT_INTEGRATIONS.has(integration.name));\n}\n\n// The SDK calls this inside `init`, so a throwing hook must be caught here or\n// it would read as an import failure and degrade the transport to noop.\nfunction withIntegrationsHook(\n hook: NonNullable<SentryTransportOptions['integrations']>,\n): IntegrationsFn {\n return (defaults) => {\n const kept = keepEventProcessors(defaults);\n try {\n return hook(kept, defaults);\n } catch (err) {\n console.error(\n '[@flare-engine/errors] SentryTransportOptions.integrations threw — using the default allowlist',\n err,\n );\n return kept;\n }\n };\n}\n\nasync function closeSdk(mod: SentryMod): Promise<void> {\n try {\n await mod.close();\n } catch (err) {\n console.error('[@flare-engine/errors] Sentry close failed', err);\n }\n}\n\nexport function createSentryTransport(opts: SentryTransportOptions): CrashTransport {\n if (!opts.dsn || opts.enabled === false) {\n return createNoopTransport();\n }\n\n const dsn = opts.dsn;\n const integrations =\n opts.integrations === undefined ? keepEventProcessors : withIntegrationsHook(opts.integrations);\n let mod: SentryMod | null = null;\n let loadFailed = false;\n let closed = false;\n let closing: Promise<void> | null = null;\n\n return {\n async report(payload: CrashPayload): Promise<void> {\n if (loadFailed || closed) return;\n\n if (mod === null) {\n try {\n const loaded = await import('@sentry/react-native');\n // `close()` may have run while the import was pending; starting a\n // client now would leave one nothing can shut down.\n if (closed) return;\n loaded.init({\n dsn,\n environment: opts.environment,\n release: opts.release,\n sampleRate: opts.sampleRate,\n integrations,\n enableAutoSessionTracking: false,\n enableNativeCrashHandling: false,\n enableAppHangTracking: false,\n enableWatchdogTerminationTracking: false,\n sendClientReports: false,\n });\n mod = loaded;\n } catch {\n console.error(\n '[@flare-engine/errors] Failed to load @sentry/react-native — degrading to noop',\n );\n loadFailed = true;\n return;\n }\n }\n\n try {\n mod.captureException(payloadToError(payload), {\n extra: { ...payload.context, capturedAt: payload.timestamp },\n });\n } catch {\n console.error('[@flare-engine/errors] Sentry captureException failed');\n }\n },\n close(): Promise<void> {\n if (closing === null) {\n closed = true;\n closing = mod === null ? Promise.resolve() : closeSdk(mod);\n }\n return closing;\n },\n };\n}\n"],"mappings":";;AAEA,SAAgB,kBAAkB,GAAG,YAA8C;CACjF,OAAO;EACL,MAAM,OAAO,SAAS;GACpB,KAAK,MAAM,KAAK,YACd,IAAI;IACF,MAAM,EAAE,OAAO,OAAO;GACxB,SAAS,KAAK;IACZ,QAAQ,MAAM,mEAAmE,GAAG;GACtF;EAEJ;EACA,MAAM,QAAQ;GACZ,KAAK,MAAM,KAAK,YACd,IAAI;IACF,MAAM,EAAE,QAAQ;GAClB,SAAS,KAAK;IACZ,QAAQ,MACN,yEACA,GACF;GACF;EAEJ;CACF;AACF;;;;;;ACLA,SAAgB,mBACd,OACA,UAAmC,CAAC,GACtB;CACd,IAAI,iBAAiB,OACnB,OAAO;EACL,SAAS,MAAM;EACf,MAAM,MAAM;EACZ,OAAO,MAAM,SAAS;EACtB,WAAW,KAAK,IAAI;EACpB;CACF;CAEF,IAAI,OAAO,UAAU,UACnB,OAAO;EAAE,SAAS;EAAO,MAAM;EAAS,OAAO;EAAM,WAAW,KAAK,IAAI;EAAG;CAAQ;CAEtF,IAAI;CACJ,IAAI;EACF,UAAU,KAAK,UAAU,KAAK;CAChC,Q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version": "0.4.13",
4
4
  "description": "React error boundary, structured crash payload, pluggable crash transport",
5
5
  "keywords": [
6
6
  "flare-engine",