Line data Source code
1 2356 : export const ASSERTION_FAILURE_PREFIX = '[Assertion failed]: '
2 :
3 : type AssertReporter = (
4 : message: string,
5 : context?: Record<string, unknown>
6 : ) => void
7 :
8 2356 : let reporter: AssertReporter | null = null
9 : let reporterForwardsToRum = false
10 :
11 : /**
12 : * Register a reporter for assertion failures in non-DEV environments.
13 : * Called once at app startup by platform/ or higher layers to wire in
14 : * Sentry, toast notifications, etc.
15 : */
16 2355 : export function setAssertReporter(
17 : fn: AssertReporter | null,
18 : options: { forwardsToRum?: boolean } = {}
19 : ): void {
20 2355 : reporter = fn
21 2355 : reporterForwardsToRum = fn !== null && options.forwardsToRum === true
22 : }
23 :
24 : export function hasRumAssertReporter(): boolean {
25 : return reporterForwardsToRum
26 : }
27 :
28 : /**
29 : * Centralized invariant assertion.
30 : *
31 : * - Always: console.error
32 : * - DEV: throws (surfaces bugs immediately)
33 : * - Otherwise: delegates to registered reporter (Sentry, toast, etc.)
34 : *
35 : * Reporters forward `message` to external telemetry, so it must be a static
36 : * description of the invariant. Put diagnostic values in `context` so they do
37 : * not affect grouping or deduplication.
38 : */
39 3338702 : export function assert(
40 : condition: unknown,
41 : message: string,
42 : context?: Record<string, unknown>
43 : ): asserts condition {
44 3338702 : if (condition) return
45 :
46 4 : const formatted = `${ASSERTION_FAILURE_PREFIX}${message}`
47 4 : console.error(formatted)
48 :
49 : if (import.meta.env.DEV) {
50 : throw new Error(formatted)
51 : }
52 :
53 3338702 : try {
54 3338702 : reporter?.(formatted, context)
55 : } catch (error) {
56 0 : console.error('[Assertion reporter failed]', error)
57 : }
58 : }
|