@marktiderman/genesis-native 0.4.4 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +98 -6
  2. package/dist/{block-Onqx7NiK.d.ts → block-DFnC8j5U.d.ts} +53 -3
  3. package/dist/{blocks-C2RDpvaN.d.ts → blocks-CyXjSGwV.d.ts} +12 -93
  4. package/dist/{chunk-75YP72G6.js → chunk-6L36FQBX.js} +95 -7
  5. package/dist/chunk-6L36FQBX.js.map +1 -0
  6. package/dist/chunk-C54LIT4N.js +73 -0
  7. package/dist/chunk-C54LIT4N.js.map +1 -0
  8. package/dist/chunk-MFHOHSEQ.js +249 -0
  9. package/dist/chunk-MFHOHSEQ.js.map +1 -0
  10. package/dist/chunk-VIC2KXMA.js +35 -0
  11. package/dist/chunk-VIC2KXMA.js.map +1 -0
  12. package/dist/devtools.d.ts +5 -4
  13. package/dist/devtools.js +3 -1
  14. package/dist/devtools.js.map +1 -1
  15. package/dist/index.d.ts +28 -4
  16. package/dist/index.js +13 -192
  17. package/dist/index.js.map +1 -1
  18. package/dist/observability.d.ts +33 -7
  19. package/dist/observability.js +20 -7
  20. package/dist/observability.js.map +1 -1
  21. package/dist/persist.d.ts +2 -1
  22. package/dist/persist.js +1 -1
  23. package/dist/push.d.ts +3 -3
  24. package/dist/query-DobJyRvs.d.ts +208 -0
  25. package/dist/screen-boundary-BlT6KBpa.d.ts +43 -0
  26. package/dist/updates.d.ts +2 -2
  27. package/dist/updates.js +3 -0
  28. package/dist/updates.js.map +1 -1
  29. package/dist/web-handoff.d.ts +88 -0
  30. package/dist/web-handoff.js +78 -0
  31. package/dist/web-handoff.js.map +1 -0
  32. package/package.json +10 -5
  33. package/src/app.tsx +16 -2
  34. package/src/errors.tsx +46 -7
  35. package/src/index.ts +24 -0
  36. package/src/observability/block.tsx +132 -5
  37. package/src/observability/index.ts +2 -0
  38. package/src/observability/sentry.ts +41 -6
  39. package/src/observability/sink.ts +30 -1
  40. package/src/query.ts +67 -1
  41. package/src/reload.ts +56 -0
  42. package/src/screen-boundary.tsx +116 -0
  43. package/src/updates/channels.ts +3 -0
  44. package/src/updates/checker.ts +3 -0
  45. package/src/web-handoff.ts +165 -0
  46. package/dist/chunk-75YP72G6.js.map +0 -1
  47. package/dist/chunk-VTJDIKFC.js +0 -39
  48. package/dist/chunk-VTJDIKFC.js.map +0 -1
  49. package/dist/query-DUmVAfsF.d.ts +0 -70
@@ -19,7 +19,14 @@
19
19
  * `beforeBreadcrumb`, `beforeSendLog`), and the user as an id only;
20
20
  * - no default PII, screenshots, view hierarchy or accessibility labels, and
21
21
  * touch breadcrumbs without the touched element's label (labels hold names);
22
- * - fatal errors marked unhandled, so release health counts them as crashes.
22
+ * - fatal errors and unhandled promise rejections marked unhandled, so
23
+ * release health counts them;
24
+ * - trace headers (`sentry-trace`, `baggage`) sent only to the hosts in
25
+ * `tracePropagationTargets` (none by default), never to every request;
26
+ * - `flush` before an update reloads the app (the observability block
27
+ * registers it), the last event id and the replay id for a support
28
+ * request, and `wrapExpoRouterErrorBoundary` around the block's screen
29
+ * boundary.
23
30
  *
24
31
  * Native crashes (sentry-cocoa, sentry-android) are built on the device's
25
32
  * native side and don't pass through these JavaScript hooks.
@@ -32,7 +39,7 @@
32
39
  import type { ComponentType } from "react";
33
40
  import type { VersionSignature } from "../updates/signature";
34
41
  import { scrubEvent, scrubRecord, scrubString } from "./scrub";
35
- import type { ObservabilitySink } from "./sink";
42
+ import type { ObservabilitySink, RouteErrorBoundaryProps } from "./sink";
36
43
 
37
44
  type Options = Record<string, unknown>;
38
45
  type Hook<T> = (value: T, hint?: unknown) => T | null | PromiseLike<T | null>;
@@ -50,6 +57,13 @@ export interface SentryLike {
50
57
  setUser(user: { id: string } | null): void;
51
58
  setTag(key: string, value: string): void;
52
59
  expoRouterIntegration?(options?: { enableTimeToInitialDisplay?: boolean }): unknown;
60
+ /** Sentry 8.17+ (`wrapExpoRouterErrorBoundary`): reports a route's error from its `ErrorBoundary`. */
61
+ wrapExpoRouterErrorBoundary?(boundary: ComponentType<RouteErrorBoundaryProps>): ComponentType<RouteErrorBoundaryProps>;
62
+ /** Sends what is queued. Takes no timeout on React Native: the observability block holds the deadline. */
63
+ flush?(): PromiseLike<boolean>;
64
+ lastEventId?(): string | undefined;
65
+ /** The active session replay integration, when replay is on (`getReplay()?.getReplayId()`). */
66
+ getReplay?(): { getReplayId(): string | null | undefined } | undefined;
53
67
  metrics?: {
54
68
  distribution(name: string, value: number, options?: Options): void;
55
69
  count(name: string, value?: number, options?: Options): void;
@@ -69,6 +83,15 @@ export interface SentrySinkOptions {
69
83
  tracesSampleRate?: number;
70
84
  /** Navigation spans and time to initial display through Expo Router. Default true. */
71
85
  expoRouter?: boolean | { enableTimeToInitialDisplay?: boolean };
86
+ /**
87
+ * The URLs that get Sentry's trace headers (`sentry-trace`, `baggage`),
88
+ * as strings (matched anywhere in the URL) or regular expressions: your
89
+ * own API and Supabase project (`["https://abc.supabase.co"]`). Default
90
+ * none: no request carries them, so third-party hosts never see your
91
+ * trace ids and their CORS never trips on the extra headers. Wins over
92
+ * `init.tracePropagationTargets`.
93
+ */
94
+ tracePropagationTargets?: readonly (string | RegExp)[];
72
95
  /** More integrations (replay, profiling). Masking is yours to set on them. */
73
96
  integrations?: readonly unknown[];
74
97
  /**
@@ -140,6 +163,7 @@ function chain<T>(ours: (value: T) => T | null, theirs: unknown): Hook<T> {
140
163
  export function sentrySink(sentry: SentryLike, options: SentrySinkOptions): ObservabilitySink {
141
164
  const { dsn, signature, applicationId, scrub = true } = options;
142
165
  if (!dsn) {
166
+ // genesis-allow-console: a build set-up warning, before any reporter exists.
143
167
  if (!isDev()) (options.onMissingDsn ?? (() => console.warn("[observability] EXPO_PUBLIC_SENTRY_DSN is not set: errors are not reported to Sentry.")))();
144
168
  return { name: "sentry (no DSN)" };
145
169
  }
@@ -168,6 +192,8 @@ export function sentrySink(sentry: SentryLike, options: SentrySinkOptions): Obse
168
192
  reportAccessibilityIdentifier: false,
169
193
  tracesSampleRate: options.tracesSampleRate ?? (environment === "production" ? 0.2 : 1),
170
194
  ...extra,
195
+ // Only the app's own hosts: Sentry's mobile default would add the headers to every request.
196
+ tracePropagationTargets: [...(options.tracePropagationTargets ?? (Array.isArray(extra.tracePropagationTargets) ? extra.tracePropagationTargets : []))],
171
197
  dsn,
172
198
  environment,
173
199
  ...sentryRelease(signature, applicationId),
@@ -185,17 +211,22 @@ export function sentrySink(sentry: SentryLike, options: SentrySinkOptions): Obse
185
211
  for (const [key, value] of Object.entries(signatureTags(signature))) sentry.setTag(key, value);
186
212
  }
187
213
 
214
+ let lastEventId: string | undefined;
188
215
  return {
189
216
  name: "sentry",
190
217
  // Sentry deduplicates by error object, and `beforeSend` scrubs: it always gets the original.
191
218
  scrubsErrors: true,
192
219
  captureError(error, context) {
193
- sentry.captureException(error, {
194
- // Unhandled when the app could not go on, so release health counts it as a crash.
195
- mechanism: { handled: !context.fatal, type: `genesis.${context.source}` },
220
+ lastEventId = sentry.captureException(error, {
221
+ // Unhandled when the app could not go on, or nothing caught it, so release health counts it.
222
+ mechanism: { handled: context.handled ?? !context.fatal, type: `genesis.${context.source}` },
196
223
  captureContext: {
197
224
  level: context.fatal ? "fatal" : "error",
198
- tags: { "genesis.source": context.source, ...(context.route ? { route: context.route } : {}) },
225
+ tags: {
226
+ ...(context.tags ? (scrub ? scrubRecord(context.tags) ?? {} : context.tags) : {}),
227
+ "genesis.source": context.source,
228
+ ...(context.route ? { route: context.route } : {}),
229
+ },
199
230
  ...(context.componentStack ? { contexts: { react: { componentStack: scrub ? scrubString(context.componentStack) : context.componentStack } } } : {}),
200
231
  },
201
232
  });
@@ -218,5 +249,9 @@ export function sentrySink(sentry: SentryLike, options: SentrySinkOptions): Obse
218
249
  },
219
250
  timing: (name, ms, tags) => sentry.metrics?.distribution(name, ms, { unit: "millisecond", attributes: tags }),
220
251
  wrap: (root) => sentry.wrap(root),
252
+ wrapRouteErrorBoundary: sentry.wrapExpoRouterErrorBoundary ? (boundary) => sentry.wrapExpoRouterErrorBoundary!(boundary) : undefined,
253
+ flush: sentry.flush ? () => sentry.flush!() : undefined,
254
+ lastEventId: () => sentry.lastEventId?.() ?? lastEventId,
255
+ replayId: () => sentry.getReplay?.()?.getReplayId() ?? undefined,
221
256
  };
222
257
  }
@@ -16,11 +16,22 @@ import type { EventValues } from "./events";
16
16
  export interface ErrorContext {
17
17
  /** True when the app could not go on (a render error, a failed boot, a fatal global error). */
18
18
  fatal: boolean;
19
- /** `boundary`, `global`, `boot`, `rejection` (the shell's), or the app's own (`updates:policy`, `sync`). */
19
+ /**
20
+ * `boundary`, `global`, `boot`, `rejection`, `screen`, `query`, `mutation`
21
+ * (the shell's), a package's (`chat:attachment-action`, through
22
+ * `reportError` from genesis-core) or the app's own (`updates:policy`, `sync`).
23
+ */
20
24
  source: string;
21
25
  componentStack?: string;
22
26
  /** The route pattern on screen (`/(app)/settings`), when known. */
23
27
  route?: string | null;
28
+ /**
29
+ * False when nothing caught it (an unhandled promise rejection): release
30
+ * health counts it. Default: handled unless `fatal`.
31
+ */
32
+ handled?: boolean;
33
+ /** Low-cardinality labels (`query.key: "tasks"`), scrubbed like everything else. */
34
+ tags?: Readonly<Record<string, string>>;
24
35
  }
25
36
 
26
37
  export type BreadcrumbLevel = "debug" | "info" | "warning" | "error";
@@ -60,6 +71,24 @@ export interface ObservabilitySink {
60
71
  timing?(name: string, ms: number, tags?: TimingTags): void;
61
72
  /** Wraps the root layout (Sentry's `wrap`, EAS Observe's `ObserveRoot.wrap`). */
62
73
  wrap?<P extends Record<string, unknown>>(root: ComponentType<P>): ComponentType<P>;
74
+ /**
75
+ * Wraps an Expo Router per-route `ErrorBoundary` (Sentry's
76
+ * `wrapExpoRouterErrorBoundary`). A sink that wraps reports the route's
77
+ * error itself, so the block's screen boundary doesn't send it to that sink again.
78
+ */
79
+ wrapRouteErrorBoundary?(boundary: ComponentType<RouteErrorBoundaryProps>): ComponentType<RouteErrorBoundaryProps>;
80
+ /** Send what is queued, within `timeoutMs`; resolves false when it didn't finish. Called before an update reloads the app. */
81
+ flush?(timeoutMs: number): PromiseLike<boolean> | boolean | void;
82
+ /** The id of the last error event this sink sent, for a support request or feedback. */
83
+ lastEventId?(): string | undefined;
84
+ /** The current session replay's id, when replay is on. */
85
+ replayId?(): string | undefined;
86
+ }
87
+
88
+ /** What Expo Router gives a route's `ErrorBoundary`: the error, and `retry` to render the route again. */
89
+ export interface RouteErrorBoundaryProps {
90
+ error: Error;
91
+ retry: () => Promise<void>;
63
92
  }
64
93
 
65
94
  /** A copy of `error` whose message and stack have been scrubbed (for sinks that don't scrub themselves). */
package/src/query.ts CHANGED
@@ -4,7 +4,9 @@
4
4
  * `@marktiderman/genesis-native/persist`, so an app that saves nothing doesn't
5
5
  * install TanStack's persister packages.
6
6
  */
7
- import { QueryClient, focusManager, onlineManager, type QueryClientConfig } from "@tanstack/react-query";
7
+ import { QueryClient, focusManager, isCancelledError, onlineManager, type QueryClientConfig } from "@tanstack/react-query";
8
+ import { classifyError } from "@marktiderman/genesis-core/errors";
9
+ import type { ErrorReport } from "./errors";
8
10
 
9
11
  /** The part of AsyncStorage (or any async key-value store) Genesis uses. */
10
12
  export interface AsyncStorageLike {
@@ -98,3 +100,67 @@ export function connectQueryLifecycle({ appState, netInfo }: QueryLifecycleOptio
98
100
  }
99
101
  };
100
102
  }
103
+
104
+ /** A failed query or mutation, as `reportQueryErrors` hands it on. */
105
+ export type QueryErrorReporter = (error: Error, report: ErrorReport) => void;
106
+
107
+ export interface ReportQueryErrorsOptions {
108
+ /** True when the device is offline. Default TanStack's `onlineManager`. */
109
+ isOffline?: () => boolean;
110
+ }
111
+
112
+ // A key segment that is a name (`tasks`, `chat.messages`), not an id or text.
113
+ const KEY_NAME = /^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;
114
+ const LOOKS_LIKE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-|^\d+$|[0-9a-f]{20,}/i;
115
+
116
+ /** The first segment of a query or mutation key, when it is a name; never the ids after it. */
117
+ export function queryKeyName(key: readonly unknown[] | undefined): string | undefined {
118
+ const first = key?.[0];
119
+ return typeof first === "string" && KEY_NAME.test(first) && !LOOKS_LIKE_ID.test(first) ? first : undefined;
120
+ }
121
+
122
+ function toError(value: unknown): Error {
123
+ return value instanceof Error ? value : new Error(typeof value === "string" ? value : "Unknown error");
124
+ }
125
+
126
+ /**
127
+ * Hand every query and mutation that failed for good (after its retries) to
128
+ * `report`, as a non-fatal `query` or `mutation` error tagged with the key's
129
+ * first segment (`query.key: "tasks"`), never the ids after it.
130
+ *
131
+ * Only errors worth a report (`classifyError(e).report`): being offline,
132
+ * signed out, a record that's gone and the server's expected refusals
133
+ * (forbidden, conflict, a rejected value) are the screen's to show, not
134
+ * bugs. A cancelled query is never reported. One query or mutation opts out
135
+ * with `meta: { reportErrors: false }`.
136
+ *
137
+ * Works on any client (it subscribes to the caches), so it covers a client
138
+ * the app passed in too. Returns the unsubscribe.
139
+ *
140
+ * @stability Beta
141
+ */
142
+ export function reportQueryErrors(client: QueryClient, report: QueryErrorReporter, options: ReportQueryErrorsOptions = {}): () => void {
143
+ const isOffline = options.isOffline ?? (() => !onlineManager.isOnline());
144
+ const send = (raw: unknown, source: "query" | "mutation", key: readonly unknown[] | undefined, meta: Record<string, unknown> | undefined) => {
145
+ if (meta?.reportErrors === false || isCancelledError(raw)) return;
146
+ if (!classifyError(raw, { isOffline }).report) return;
147
+ const name = queryKeyName(key);
148
+ try {
149
+ report(toError(raw), { fatal: false, source, ...(name ? { tags: { [`${source}.key`]: name } } : {}) });
150
+ } catch {
151
+ // A failing reporter must not break the cache's listeners.
152
+ }
153
+ };
154
+ const offQueries = client.getQueryCache().subscribe((event) => {
155
+ if (event.type !== "updated" || event.action.type !== "error") return;
156
+ send(event.action.error, "query", event.query.queryKey, event.query.meta);
157
+ });
158
+ const offMutations = client.getMutationCache().subscribe((event) => {
159
+ if (event.type !== "updated" || event.action.type !== "error") return;
160
+ send(event.action.error, "mutation", event.mutation.options.mutationKey, event.mutation.meta);
161
+ });
162
+ return () => {
163
+ offQueries();
164
+ offMutations();
165
+ };
166
+ }
package/src/reload.ts ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Before the app reloads itself (an over-the-air update applied now, a
3
+ * channel switch), the JavaScript runtime is thrown away with whatever it
4
+ * had queued. `onBeforeReload` registers work that must happen first (the
5
+ * observability block flushes its sinks there); the updates block awaits
6
+ * `runBeforeReload()` before `reloadAsync`. Each hook gets a share of a short
7
+ * deadline, and a slow or failing hook never stops the reload.
8
+ */
9
+
10
+ /** Work to finish before a reload; gets the milliseconds it has. */
11
+ export type BeforeReloadHook = (timeoutMs: number) => unknown;
12
+
13
+ // On globalThis, so the `/updates` and `/observability` entries share one list even when bundled apart.
14
+ const KEY = Symbol.for("genesis.beforeReload");
15
+ type Holder = { [KEY]?: Set<BeforeReloadHook> };
16
+
17
+ function hooks(): Set<BeforeReloadHook> {
18
+ const holder = globalThis as Holder;
19
+ return (holder[KEY] ??= new Set());
20
+ }
21
+
22
+ /** Run `hook` before every reload the updates block starts. Returns the unregister. @stability Beta */
23
+ export function onBeforeReload(hook: BeforeReloadHook): () => void {
24
+ hooks().add(hook);
25
+ return () => {
26
+ hooks().delete(hook);
27
+ };
28
+ }
29
+
30
+ /** The default deadline for every hook together. */
31
+ export const BEFORE_RELOAD_TIMEOUT_MS = 2000;
32
+
33
+ /**
34
+ * Run every registered hook, in parallel, and resolve when they have all
35
+ * settled or `timeoutMs` has passed, whichever is first. Never rejects.
36
+ *
37
+ * @stability Beta
38
+ */
39
+ export async function runBeforeReload(timeoutMs: number = BEFORE_RELOAD_TIMEOUT_MS): Promise<void> {
40
+ const list = [...hooks()];
41
+ if (list.length === 0) return;
42
+ const settled = Promise.allSettled(
43
+ list.map(async (hook) => {
44
+ await hook(timeoutMs);
45
+ }),
46
+ );
47
+ let timer: ReturnType<typeof setTimeout> | undefined;
48
+ const deadline = new Promise<void>((resolve) => {
49
+ timer = setTimeout(resolve, timeoutMs);
50
+ });
51
+ try {
52
+ await Promise.race([settled, deadline]);
53
+ } finally {
54
+ if (timer !== undefined) clearTimeout(timer);
55
+ }
56
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Screen errors: one screen fails, the rest of the app (the tab bar, the
3
+ * other tabs) keeps working. The error is reported non-fatal, and "Try
4
+ * again" renders the screen again.
5
+ *
6
+ * With Expo Router, export the boundary from a route or layout file; it
7
+ * catches errors in that route and the routes below it:
8
+ *
9
+ * // src/lib/observability.ts
10
+ * export const ScreenErrorBoundary = observability.screenBoundary();
11
+ * // src/app/(app)/messages/_layout.tsx
12
+ * export { ScreenErrorBoundary as ErrorBoundary } from "@/lib/observability";
13
+ *
14
+ * `observability.screenBoundary()` reports through the block and wraps the
15
+ * boundary with each sink's route wrapper (Sentry's
16
+ * `wrapExpoRouterErrorBoundary`). Without the block,
17
+ * `createScreenErrorBoundary()` reports through `reportError` from
18
+ * genesis-core. Outside Expo Router, wrap a subtree in `<ScreenErrorBoundary>`.
19
+ */
20
+ import { useEffect, useMemo, useRef, type ComponentType, type ReactNode } from "react";
21
+ import { NativeButton, NativeEmptyState } from "@marktiderman/genesis-ui-native/components";
22
+ import { reportError } from "@marktiderman/genesis-core/errors";
23
+ import { errorDetails, GenesisErrorBoundary, type ErrorReport, type FatalScreenProps, type OnError } from "./errors";
24
+
25
+ /** What Expo Router gives a route's `ErrorBoundary`: the error, and `retry` to render the route again. */
26
+ export interface ScreenErrorProps {
27
+ error: Error;
28
+ retry: () => Promise<void>;
29
+ }
30
+
31
+ /** The default screen fallback: the screen hit a problem, and "Try again". @stability Beta */
32
+ export function ScreenErrorScreen({ error, retry }: ScreenErrorProps) {
33
+ return (
34
+ <NativeEmptyState
35
+ variant="error"
36
+ title="This screen hit a problem"
37
+ body="The rest of the app still works. Try again, or go back."
38
+ details={errorDetails(error)}
39
+ primaryAction={
40
+ <NativeButton onPress={() => void Promise.resolve(retry()).catch((e: unknown) => reportError(e, "native:screen-retry"))} testID="genesis-screen-error-retry">
41
+ Try again
42
+ </NativeButton>
43
+ }
44
+ testID="genesis-screen-error"
45
+ />
46
+ );
47
+ }
48
+
49
+ const reportThroughCore = (error: Error, report: ErrorReport) =>
50
+ reportError(error, { source: report.source, fatal: report.fatal, ...(report.tags ? { tags: report.tags } : {}) });
51
+
52
+ export interface ScreenErrorBoundaryOptions {
53
+ /** What to show. Default `ScreenErrorScreen`. */
54
+ fallback?: ComponentType<ScreenErrorProps>;
55
+ /** Where the error goes. Default `reportError` from genesis-core (the observability block, when it is on). */
56
+ onError?: OnError;
57
+ /** Wrappers around the route boundary, innermost first (Sentry's `wrapExpoRouterErrorBoundary`). */
58
+ wrap?: readonly ((boundary: ComponentType<ScreenErrorProps>) => ComponentType<ScreenErrorProps>)[];
59
+ }
60
+
61
+ /**
62
+ * An Expo Router `ErrorBoundary`: reports each error once (non-fatal, source
63
+ * `screen`) and shows `fallback`. Build it once, at module scope.
64
+ *
65
+ * @stability Beta
66
+ */
67
+ export function createScreenErrorBoundary(options: ScreenErrorBoundaryOptions = {}): ComponentType<ScreenErrorProps> {
68
+ const Fallback = options.fallback ?? ScreenErrorScreen;
69
+ const onError = options.onError ?? reportThroughCore;
70
+ function GenesisScreenErrorBoundary(props: ScreenErrorProps) {
71
+ const reported = useRef<Error | null>(null);
72
+ useEffect(() => {
73
+ if (reported.current === props.error) return;
74
+ reported.current = props.error;
75
+ try {
76
+ onError(props.error, { fatal: false, source: "screen" });
77
+ } catch {
78
+ // A failing reporter must not take the fallback down with it.
79
+ }
80
+ }, [props.error]);
81
+ return <Fallback {...props} />;
82
+ }
83
+ return (options.wrap ?? []).reduce<ComponentType<ScreenErrorProps>>((inner, wrap) => wrap(inner), GenesisScreenErrorBoundary);
84
+ }
85
+
86
+ export interface ScreenErrorBoundaryProps {
87
+ children?: ReactNode;
88
+ fallback?: ComponentType<ScreenErrorProps>;
89
+ /** Default `reportError` from genesis-core. */
90
+ onError?: OnError;
91
+ /** Change it to clear a caught error. */
92
+ resetKey?: unknown;
93
+ }
94
+
95
+ /**
96
+ * A boundary around part of a screen tree, for apps without Expo Router's
97
+ * per-route boundaries: non-fatal, reported, with "Try again".
98
+ *
99
+ * @stability Beta
100
+ */
101
+ export function ScreenErrorBoundary({ children, fallback, onError, resetKey }: ScreenErrorBoundaryProps) {
102
+ const Screen = fallback ?? ScreenErrorScreen;
103
+ // The boundary's retry is synchronous; the screen's (Expo Router's shape) returns a promise.
104
+ const Fallback = useMemo(
105
+ () =>
106
+ function ScreenFallback({ error, retry }: FatalScreenProps) {
107
+ return <Screen error={error} retry={async () => retry()} />;
108
+ },
109
+ [Screen],
110
+ );
111
+ return (
112
+ <GenesisErrorBoundary fallback={Fallback} onError={onError ?? reportThroughCore} resetKey={resetKey} fatal={false} source="screen">
113
+ {children}
114
+ </GenesisErrorBoundary>
115
+ );
116
+ }
@@ -15,6 +15,7 @@
15
15
  */
16
16
  import { toError, type UpdatesModuleLike, type UpdatesOnError, type UpdatesStorageLike } from "./modules";
17
17
  import type { ReloadGuard } from "./checker";
18
+ import { runBeforeReload } from "../reload";
18
19
 
19
20
  export type ChannelSwitchResult =
20
21
  /** The reload was sent; JS may stop at any moment. */
@@ -83,6 +84,8 @@ export function createChannelSwitcher(options: ChannelSwitcherOptions): ChannelS
83
84
  const check = await u.checkForUpdateAsync();
84
85
  if (check.isAvailable || check.isRollBackToEmbedded) await u.fetchUpdateAsync();
85
86
  if (!guard.canReload()) return { kind: "blocked" };
87
+ // Queued crash reports and events would be lost with the runtime: flush them first.
88
+ await runBeforeReload();
86
89
  await u.reloadAsync(reloadScreenOptions ? { reloadScreenOptions } : undefined);
87
90
  return { kind: "reloading" };
88
91
  } catch (raw) {
@@ -12,6 +12,7 @@
12
12
  */
13
13
  import { createStore, type Store } from "./store";
14
14
  import { manifestField, toError, type UpdatesModuleLike, type UpdatesOnError } from "./modules";
15
+ import { runBeforeReload } from "../reload";
15
16
 
16
17
  export interface ReloadGuard {
17
18
  /** Hold reloads off until the returned function is called. */
@@ -173,6 +174,8 @@ export function createUpdateChecker(options: UpdateCheckerOptions): UpdateChecke
173
174
  }
174
175
  store.setState({ status: "reloading", blocked: false });
175
176
  try {
177
+ // Queued crash reports and events would be lost with the runtime: flush them first.
178
+ await runBeforeReload();
176
179
  await updates.reloadAsync(reloadScreenOptions ? { reloadScreenOptions } : undefined);
177
180
  return true;
178
181
  } catch (raw) {
@@ -0,0 +1,165 @@
1
+ /**
2
+ * `@marktiderman/genesis-native/web-handoff`: open a page of the web app signed in as the person
3
+ * using the app, so work the app leaves to the web carries on without a sign-in screen.
4
+ *
5
+ * The app asks its server for a single-use, short-lived link (genesis-supabase's
6
+ * `createWebHandoff`, the `mint` route) with the session's access token, then opens it in the
7
+ * in-app browser. The modules are injected, never imported:
8
+ *
9
+ * ```ts
10
+ * import * as WebBrowser from "expo-web-browser";
11
+ * await openOnWeb("/clients/1/forms", {
12
+ * endpoint: "https://app.example.com/api/auth/handoff",
13
+ * getAccessToken: async () => (await supabase.auth.getSession()).data.session?.access_token,
14
+ * browser: WebBrowser,
15
+ * });
16
+ * ```
17
+ *
18
+ * Why the in-app browser (`openBrowserAsync`: SFSafariViewController on iOS, a Custom Tab on
19
+ * Android) and not `Linking.openURL` (Safari): the person stays in the app and Done brings them
20
+ * back; and the in-app browser keeps its own website data between openings, so after the first
21
+ * handoff the page is already signed in as them and goes straight to the path. Safari may be
22
+ * signed in as someone else, which would ask them to switch every time. Not
23
+ * `openAuthSessionAsync` either: it shows the system "wants to use … to sign in" alert each time.
24
+ *
25
+ * @packageDocumentation
26
+ */
27
+
28
+ /** `expo-web-browser`'s `openBrowserAsync`, as the shape used here. */
29
+ export interface WebBrowserLike {
30
+ openBrowserAsync(url: string, options?: Record<string, unknown>): Promise<unknown>;
31
+ }
32
+
33
+ /** @stability Beta */
34
+ export interface OpenOnWebOptions {
35
+ /** The mint route: `https://<web app>/api/auth/handoff`. Its origin is also the web app's. */
36
+ endpoint: string;
37
+ /** The signed-in session's access token, or nothing when signed out. */
38
+ getAccessToken: () => Promise<string | null | undefined> | string | null | undefined;
39
+ /** `import * as WebBrowser from "expo-web-browser"`. */
40
+ browser: WebBrowserLike;
41
+ /** Passed to `openBrowserAsync` (presentationStyle, controlsColor…). */
42
+ browserOptions?: Record<string, unknown>;
43
+ /** The web page that completes a handoff, also shown signed out. Default `/auth/handoff`. */
44
+ pagePath?: string;
45
+ /** Give up on the server after this long and open the page signed out. Default 8000 ms. */
46
+ timeoutMs?: number;
47
+ fetch?: typeof fetch;
48
+ }
49
+
50
+ export type OpenOnWebResult =
51
+ /** Opened signed in (the page may still ask "Continue as …?" the first time). */
52
+ | { signedIn: true }
53
+ /**
54
+ * Opened the page signed out, so the person signs in there and lands on the path: no session
55
+ * here, the server unreachable, no email on the account (Supabase signs in by email link), or
56
+ * too many links in a minute.
57
+ */
58
+ | { signedIn: false; reason: "signed_out" | "unreachable" | "no_email" | "rate_limited" | "refused" };
59
+
60
+ /** Only paths on the web app: one leading `/`, no `//`, no backslash or control characters. */
61
+ function isAppPath(path: string): boolean {
62
+ // eslint-disable-next-line no-control-regex
63
+ return path.startsWith("/") && !path.startsWith("//") && !/[\\\u0000-\u0020\u007f-\u009f]/.test(path);
64
+ }
65
+
66
+ /**
67
+ * Open `path` on the web app, signed in as the app's person. Throws for a path that isn't the
68
+ * web app's own (`https://…`, `//host`); the server checks again. When a signed-in link can't
69
+ * be had, opens the page signed out instead of failing the tap.
70
+ *
71
+ * @stability Beta
72
+ */
73
+ export async function openOnWeb(path: string, options: OpenOnWebOptions): Promise<OpenOnWebResult> {
74
+ if (!isAppPath(path)) throw new TypeError(`openOnWeb takes a path on the web app, like "/settings"; got ${JSON.stringify(path)}.`);
75
+ const { endpoint, browser, browserOptions, pagePath = "/auth/handoff", timeoutMs = 8000 } = options;
76
+ const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
77
+ const origin = new URL(endpoint).origin;
78
+ // Signed out: the web app's sign-in page, which returns to the path afterwards.
79
+ const signedOutUrl = `${origin}${isAppPath(pagePath) ? pagePath : "/auth/handoff"}#${new URLSearchParams({ next: path }).toString()}`;
80
+ const open = async (url: string) => {
81
+ await browser.openBrowserAsync(url, browserOptions);
82
+ };
83
+
84
+ const token = await options.getAccessToken();
85
+ if (!token) {
86
+ await open(signedOutUrl);
87
+ return { signedIn: false, reason: "signed_out" };
88
+ }
89
+
90
+ let response: Response;
91
+ const controller = new AbortController();
92
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
93
+ try {
94
+ response = await doFetch(endpoint, {
95
+ method: "POST",
96
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
97
+ body: JSON.stringify({ path }),
98
+ signal: controller.signal,
99
+ });
100
+ } catch {
101
+ await open(signedOutUrl);
102
+ return { signedIn: false, reason: "unreachable" };
103
+ } finally {
104
+ clearTimeout(timer);
105
+ }
106
+
107
+ const body = (await response.json().catch(() => ({}))) as { url?: unknown; error?: unknown; fallbackUrl?: unknown };
108
+ const sameOrigin = (url: unknown): url is string => {
109
+ if (typeof url !== "string") return false;
110
+ try {
111
+ return new URL(url).origin === origin;
112
+ } catch {
113
+ return false;
114
+ }
115
+ };
116
+ if (response.ok && sameOrigin(body.url)) {
117
+ await open(body.url);
118
+ return { signedIn: true };
119
+ }
120
+ if (response.status === 400) throw new TypeError(`The server refused ${JSON.stringify(path)} as a web path.`);
121
+ await open(sameOrigin(body.fallbackUrl) ? body.fallbackUrl : signedOutUrl);
122
+ const reason = body.error === "no_email" || body.error === "rate_limited" ? body.error : "refused";
123
+ return { signedIn: false, reason };
124
+ }
125
+
126
+ /** @stability Beta */
127
+ export interface SignOutOnWebOptions {
128
+ /** The sign-out route: `https://<web app>/api/auth/handoff-signout`. */
129
+ endpoint: string;
130
+ /** The session's access token, still valid: call this before the app signs out. */
131
+ getAccessToken: () => Promise<string | null | undefined> | string | null | undefined;
132
+ /** Give up after this long. Default 5000 ms. */
133
+ timeoutMs?: number;
134
+ fetch?: typeof fetch;
135
+ }
136
+
137
+ /**
138
+ * End the web sessions this app session handed off with {@link openOnWeb} (and only those; never
139
+ * the person's other devices). Call it just before the app's own sign-out, while the access token
140
+ * still works. It never throws, so it can't block signing out; it returns how many it ended.
141
+ *
142
+ * @stability Beta
143
+ */
144
+ export async function signOutOnWeb(options: SignOutOnWebOptions): Promise<number> {
145
+ const { endpoint, timeoutMs = 5000 } = options;
146
+ const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
147
+ const controller = new AbortController();
148
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
149
+ try {
150
+ const token = await options.getAccessToken();
151
+ if (!token) return 0;
152
+ const response = await doFetch(endpoint, {
153
+ method: "POST",
154
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
155
+ body: "{}",
156
+ signal: controller.signal,
157
+ });
158
+ const body = (await response.json().catch(() => ({}))) as { count?: unknown };
159
+ return response.ok && typeof body.count === "number" ? body.count : 0;
160
+ } catch {
161
+ return 0;
162
+ } finally {
163
+ clearTimeout(timer);
164
+ }
165
+ }