@marktiderman/genesis-native 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +22 -14
  2. package/dist/{block-q6_CV0WK.d.ts → block-CQz1pOnm.d.ts} +4 -4
  3. package/dist/{blocks-ByVBKaQW.d.ts → blocks-dppiMmy-.d.ts} +7 -4
  4. package/dist/{chunk-6L36FQBX.js → chunk-EWHO5WQU.js} +3 -3
  5. package/dist/{chunk-6L36FQBX.js.map → chunk-EWHO5WQU.js.map} +1 -1
  6. package/dist/{chunk-C54LIT4N.js → chunk-FKDZP3RJ.js} +2 -2
  7. package/dist/chunk-FKDZP3RJ.js.map +1 -0
  8. package/dist/{chunk-MFHOHSEQ.js → chunk-YIF4BFQH.js} +33 -28
  9. package/dist/chunk-YIF4BFQH.js.map +1 -0
  10. package/dist/devtools.d.ts +5 -5
  11. package/dist/devtools.js +2 -2
  12. package/dist/index.d.ts +4 -4
  13. package/dist/index.js +9 -8
  14. package/dist/index.js.map +1 -1
  15. package/dist/observability.d.ts +5 -5
  16. package/dist/observability.js +3 -3
  17. package/dist/offline.d.ts +40 -0
  18. package/dist/offline.js +118 -0
  19. package/dist/offline.js.map +1 -0
  20. package/dist/persist.d.ts +11 -3
  21. package/dist/persist.js +6 -3
  22. package/dist/persist.js.map +1 -1
  23. package/dist/push.d.ts +3 -3
  24. package/dist/{query-DobJyRvs.d.ts → query--ihYsJWC.d.ts} +31 -9
  25. package/dist/{screen-boundary-BlT6KBpa.d.ts → screen-boundary-B8DlsLwb.d.ts} +8 -4
  26. package/dist/updates.d.ts +2 -2
  27. package/dist/updates.js +10 -10
  28. package/dist/updates.js.map +1 -1
  29. package/package.json +15 -10
  30. package/src/app.tsx +9 -6
  31. package/src/errors.tsx +56 -22
  32. package/src/index.ts +2 -0
  33. package/src/observability/block.tsx +1 -1
  34. package/src/offline/sqlite-local-cache.ts +161 -0
  35. package/src/persist.ts +16 -4
  36. package/src/query.ts +5 -2
  37. package/src/screen-boundary.tsx +13 -21
  38. package/src/updates/screens.tsx +10 -22
  39. package/dist/chunk-C54LIT4N.js.map +0 -1
  40. package/dist/chunk-MFHOHSEQ.js.map +0 -1
package/src/errors.tsx CHANGED
@@ -8,7 +8,7 @@
8
8
  import { Component, type ComponentType, type ErrorInfo, type ReactNode } from "react";
9
9
  import { Pressable, Text, View } from "react-native";
10
10
  import { NativeButton, NativeEmptyState } from "@marktiderman/genesis-ui-native/components";
11
- import { classifyError } from "@marktiderman/genesis-core/errors";
11
+ import { classifyError, reportError } from "@marktiderman/genesis-core/errors";
12
12
  import { toError } from "./boot";
13
13
 
14
14
  declare const __DEV__: boolean | undefined;
@@ -31,41 +31,75 @@ export interface FatalScreenProps {
31
31
  retry: () => void;
32
32
  }
33
33
 
34
- /** The default fatal screen: what went wrong and "Try again". */
35
- export function FatalScreen({ error, retry }: FatalScreenProps) {
34
+ /** Which fatal screen: the app's, one screen's, or the last-resort plain one. */
35
+ export type FatalScreenKind = "app" | "screen" | "plain";
36
+
37
+ export interface FatalScreenViewProps {
38
+ error: Error;
39
+ /** Clears the error and renders again (a screen's retry may be async, as Expo Router's is). */
40
+ retry: () => void | Promise<void>;
41
+ /**
42
+ * `app` (default): the app hit a problem, "Try again" remounts it. `screen`: one screen failed
43
+ * and the rest of the app still works (the screen boundary's default). `plain`: React Native
44
+ * primitives only, no theme, no context, nothing that can itself fail; shown when the providers
45
+ * could not start, or when the `fatal` slot threw.
46
+ */
47
+ kind?: FatalScreenKind;
48
+ }
49
+
50
+ const runRetry = (retry: FatalScreenViewProps["retry"], source: string) => () => {
51
+ void Promise.resolve(retry()).catch((e: unknown) => reportError(e, source));
52
+ };
53
+
54
+ /**
55
+ * The fatal screen: what went wrong and "Try again", for the whole app, one screen, or (with
56
+ * `kind="plain"`) the last resort that needs nothing above it.
57
+ */
58
+ export function FatalScreen({ error, retry, kind = "app" }: FatalScreenViewProps) {
59
+ if (kind === "plain") {
60
+ return (
61
+ <View testID="genesis-fatal-plain" style={{ flex: 1, justifyContent: "center", alignItems: "center", padding: 24, gap: 12 }}>
62
+ <Text accessibilityRole="header" style={{ fontSize: 17, fontWeight: "600" }}>
63
+ Something went wrong
64
+ </Text>
65
+ <Text style={{ textAlign: "center" }}>{errorDetails(error) ?? "Try again, and if it keeps happening, close and reopen the app."}</Text>
66
+ <Pressable accessibilityRole="button" onPress={() => void retry()} testID="genesis-fatal-plain-retry" style={{ padding: 12 }}>
67
+ <Text style={{ fontSize: 17 }}>Try again</Text>
68
+ </Pressable>
69
+ </View>
70
+ );
71
+ }
72
+ const screen = kind === "screen";
36
73
  return (
37
74
  <NativeEmptyState
38
75
  variant="error"
39
- title="Something went wrong"
40
- body="The app hit a problem. Try again, and if it keeps happening, close and reopen the app."
76
+ title={screen ? "This screen hit a problem" : "Something went wrong"}
77
+ body={
78
+ screen
79
+ ? "The rest of the app still works. Try again, or go back."
80
+ : "The app hit a problem. Try again, and if it keeps happening, close and reopen the app."
81
+ }
41
82
  details={errorDetails(error)}
42
83
  primaryAction={
43
- <NativeButton onPress={retry} testID="genesis-fatal-retry">
84
+ <NativeButton
85
+ onPress={screen ? runRetry(retry, "native:screen-retry") : () => void retry()}
86
+ testID={screen ? "genesis-screen-error-retry" : "genesis-fatal-retry"}
87
+ >
44
88
  Try again
45
89
  </NativeButton>
46
90
  }
47
- testID="genesis-fatal"
91
+ testID={screen ? "genesis-screen-error" : "genesis-fatal"}
48
92
  />
49
93
  );
50
94
  }
51
95
 
52
96
  /**
53
- * The last-resort fatal screen: React Native primitives only, no theme, no
54
- * context, nothing that can itself fail. Shown when the providers could not
55
- * start, or when the `fatal` slot threw.
97
+ * The last-resort fatal screen.
98
+ *
99
+ * @deprecated Use `<FatalScreen kind="plain" />`; this name goes at the next major.
56
100
  */
57
- export function PlainFatalScreen({ error, retry }: FatalScreenProps) {
58
- return (
59
- <View testID="genesis-fatal-plain" style={{ flex: 1, justifyContent: "center", alignItems: "center", padding: 24, gap: 12 }}>
60
- <Text accessibilityRole="header" style={{ fontSize: 17, fontWeight: "600" }}>
61
- Something went wrong
62
- </Text>
63
- <Text style={{ textAlign: "center" }}>{errorDetails(error) ?? "Try again, and if it keeps happening, close and reopen the app."}</Text>
64
- <Pressable accessibilityRole="button" onPress={retry} testID="genesis-fatal-plain-retry" style={{ padding: 12 }}>
65
- <Text style={{ fontSize: 17 }}>Try again</Text>
66
- </Pressable>
67
- </View>
68
- );
101
+ export function PlainFatalScreen(props: FatalScreenProps) {
102
+ return <FatalScreen {...props} kind="plain" />;
69
103
  }
70
104
 
71
105
  export interface ErrorReport {
package/src/index.ts CHANGED
@@ -32,6 +32,8 @@ export {
32
32
  } from "./boot";
33
33
  export {
34
34
  FatalScreen,
35
+ type FatalScreenKind,
36
+ type FatalScreenViewProps,
35
37
  PlainFatalScreen,
36
38
  GenesisErrorBoundary,
37
39
  installGlobalErrorHandler,
@@ -107,7 +107,7 @@ export interface ObservabilityBlock<E extends EventSchema = EventSchema> extends
107
107
  replayId(): string | undefined;
108
108
  /**
109
109
  * An Expo Router `ErrorBoundary` for a route: reports the error non-fatal
110
- * (source `screen`), shows `fallback` (default `ScreenErrorScreen`) with
110
+ * (source `screen`), shows `fallback` (default `<FatalScreen kind="screen" />`) with
111
111
  * "Try again", and is wrapped by each sink's route wrapper (Sentry's
112
112
  * `wrapExpoRouterErrorBoundary`). Build it once, at module scope.
113
113
  */
@@ -0,0 +1,161 @@
1
+ /**
2
+ * `@marktiderman/genesis-native/offline`: the phone's device cache, in SQLite
3
+ * (expo-sqlite), so lists and records open at once (ADR 0010, slice 1).
4
+ *
5
+ * import * as SQLite from "expo-sqlite";
6
+ * import { persistOffline, sqliteLocalCache } from "@marktiderman/genesis-native/offline";
7
+ *
8
+ * const db = SQLite.openDatabaseSync("genesis-offline.db");
9
+ * <GenesisNativeApp persist={persistOffline({ cache: sqliteLocalCache({ db }), resources: ["tasks"], buster: version })} … />
10
+ *
11
+ * @stability Beta
12
+ */
13
+ import type { CacheOp, LocalCache, StoredQuery, StoredRow } from "@marktiderman/genesis-core/offline";
14
+
15
+ /** The part of expo-sqlite's `SQLiteDatabase` this uses (op-sqlite fits behind a small wrapper). */
16
+ export interface SQLiteDatabaseLike {
17
+ execAsync(source: string): Promise<void>;
18
+ runAsync(source: string, params: (string | number | null)[]): Promise<unknown>;
19
+ getAllAsync<T>(source: string, params: (string | number | null)[]): Promise<T[]>;
20
+ /** Runs `task` in one exclusive transaction, so a write lands whole or not at all. */
21
+ withExclusiveTransactionAsync(task: (txn: SQLiteDatabaseLike) => Promise<void>): Promise<void>;
22
+ }
23
+
24
+ /** Options for {@link sqliteLocalCache}. */
25
+ export interface SqliteLocalCacheOptions {
26
+ db: SQLiteDatabaseLike;
27
+ }
28
+
29
+ // busy_timeout: a clear at sign-out that overlaps a save waits for it instead of failing.
30
+ const SCHEMA = `
31
+ pragma busy_timeout = 5000;
32
+ create table if not exists genesis_offline_rows (
33
+ scope text not null, resource text not null, id text not null,
34
+ row text not null, fetched_at integer not null,
35
+ primary key (scope, resource, id)
36
+ );
37
+ create table if not exists genesis_offline_queries (
38
+ scope text not null, key text not null, query_key text not null,
39
+ resource text not null, data text not null, fetched_at integer not null,
40
+ primary key (scope, key)
41
+ );`;
42
+
43
+ function assertScope(scope: string): void {
44
+ if (!/^u:[^|]+\|/.test(scope)) {
45
+ throw new Error(`[genesis offline] "${scope}" isn't a person's cache scope: build it with cacheScope(userId, workspace).`);
46
+ }
47
+ }
48
+
49
+ /** `LIKE` matches `_` and `%` as wildcards: escape them in a person's prefix. */
50
+ const likePrefix = (prefix: string) => `${prefix.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
51
+
52
+ /**
53
+ * A `LocalCache` in SQLite, for the phone. Rows and queries are separate
54
+ * tables keyed by scope, so one row is stored once whatever lists hold it,
55
+ * and every write runs in one exclusive transaction. Values are stored as
56
+ * JSON, so a `Date` in a read comes back as its ISO text (rows from Supabase
57
+ * are text already).
58
+ *
59
+ * @stability Beta
60
+ */
61
+ export function sqliteLocalCache({ db }: SqliteLocalCacheOptions): LocalCache {
62
+ let ready: Promise<void> | null = null;
63
+ const open = () => {
64
+ ready ??= db.execAsync(SCHEMA).catch((error: unknown) => {
65
+ ready = null;
66
+ throw error;
67
+ });
68
+ return ready;
69
+ };
70
+
71
+ return {
72
+ async readQueries(scope) {
73
+ assertScope(scope);
74
+ await open();
75
+ const rows = await db.getAllAsync<{ key: string; query_key: string; resource: string; data: string; fetched_at: number }>(
76
+ "select key, query_key, resource, data, fetched_at from genesis_offline_queries where scope = ?",
77
+ [scope],
78
+ );
79
+ return rows.map(
80
+ (r): StoredQuery => ({
81
+ key: r.key,
82
+ queryKey: JSON.parse(r.query_key) as unknown[],
83
+ resource: r.resource,
84
+ data: JSON.parse(r.data) as unknown,
85
+ fetchedAt: r.fetched_at,
86
+ }),
87
+ );
88
+ },
89
+
90
+ async readRows(scope, resource, ids) {
91
+ assertScope(scope);
92
+ if (ids.length === 0) return [];
93
+ await open();
94
+ const out: StoredRow[] = [];
95
+ // SQLite caps bound parameters; read in chunks.
96
+ for (let i = 0; i < ids.length; i += 500) {
97
+ const chunk = ids.slice(i, i + 500);
98
+ const rows = await db.getAllAsync<{ id: string; row: string; fetched_at: number }>(
99
+ `select id, row, fetched_at from genesis_offline_rows where scope = ? and resource = ? and id in (${chunk.map(() => "?").join(",")})`,
100
+ [scope, resource, ...chunk],
101
+ );
102
+ for (const r of rows) out.push({ resource, id: r.id, row: JSON.parse(r.row) as Record<string, unknown>, fetchedAt: r.fetched_at });
103
+ }
104
+ return out;
105
+ },
106
+
107
+ async write(scope, ops: readonly CacheOp[]) {
108
+ assertScope(scope);
109
+ if (ops.length === 0) return;
110
+ await open();
111
+ await db.withExclusiveTransactionAsync(async (txn) => {
112
+ for (const op of ops) {
113
+ if (op.kind === "row") {
114
+ // An older read never overwrites a newer one.
115
+ await txn.runAsync(
116
+ `insert into genesis_offline_rows (scope, resource, id, row, fetched_at) values (?, ?, ?, ?, ?)
117
+ on conflict (scope, resource, id) do update set row = excluded.row, fetched_at = excluded.fetched_at
118
+ where excluded.fetched_at >= genesis_offline_rows.fetched_at`,
119
+ [scope, op.row.resource, op.row.id, JSON.stringify(op.row.row), op.row.fetchedAt],
120
+ );
121
+ } else if (op.kind === "query") {
122
+ await txn.runAsync(
123
+ "insert or replace into genesis_offline_queries (scope, key, query_key, resource, data, fetched_at) values (?, ?, ?, ?, ?, ?)",
124
+ [scope, op.query.key, JSON.stringify(op.query.queryKey), op.query.resource, JSON.stringify(op.query.data), op.query.fetchedAt],
125
+ );
126
+ } else if (op.kind === "forget") {
127
+ await txn.runAsync(
128
+ `delete from genesis_offline_queries where scope = ? and key = ?${op.before === undefined ? "" : " and fetched_at < ?"}`,
129
+ op.before === undefined ? [scope, op.key] : [scope, op.key, op.before],
130
+ );
131
+ } else if (op.kind === "drop") {
132
+ await txn.runAsync("delete from genesis_offline_rows where scope = ? and resource = ? and id = ?", [scope, op.resource, op.id]);
133
+ } else {
134
+ const ids = await txn.getAllAsync<{ id: string }>(
135
+ "select id from genesis_offline_rows where scope = ? and resource = ? and fetched_at < ?",
136
+ [scope, op.resource, op.before],
137
+ );
138
+ const keep = new Set(op.keep);
139
+ for (const { id } of ids) {
140
+ if (!keep.has(id)) await txn.runAsync("delete from genesis_offline_rows where scope = ? and resource = ? and id = ?", [scope, op.resource, id]);
141
+ }
142
+ }
143
+ }
144
+ });
145
+ },
146
+
147
+ async clear(target) {
148
+ await open();
149
+ await db.withExclusiveTransactionAsync(async (txn) => {
150
+ for (const table of ["genesis_offline_rows", "genesis_offline_queries"]) {
151
+ if (!target) await txn.runAsync(`delete from ${table}`, []);
152
+ else if ("scope" in target) await txn.runAsync(`delete from ${table} where scope = ?`, [target.scope]);
153
+ else if ("user" in target) await txn.runAsync(`delete from ${table} where scope like ? escape '\\'`, [likePrefix(`u:${target.user}|`)]);
154
+ else await txn.runAsync(`delete from ${table} where scope not like ? escape '\\'`, [likePrefix(`u:${target.except}|`)]);
155
+ }
156
+ });
157
+ },
158
+ };
159
+ }
160
+
161
+ export { cacheScope, persistOffline, type LocalCache, type PersistOfflineOptions, type QueryPersistence } from "@marktiderman/genesis-core/offline";
package/src/persist.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  * @stability Beta
14
14
  */
15
15
  import { defaultShouldDehydrateQuery, type QueryClient } from "@tanstack/react-query";
16
- import { persistQueryClientRestore, persistQueryClientSubscribe } from "@tanstack/query-persist-client-core";
16
+ import { persistQueryClientRestore, persistQueryClientSave, persistQueryClientSubscribe } from "@tanstack/query-persist-client-core";
17
17
  import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister";
18
18
  import { DAY_MS, type AsyncStorageLike, type QueryPersistence } from "./query";
19
19
 
@@ -39,7 +39,11 @@ export interface QueryPersistenceOptions extends PersistQueriesOptions {
39
39
  queryClient: QueryClient;
40
40
  }
41
41
 
42
- /** Save the allowlisted queries to async storage and restore them, with a max age, an app-version buster and a user scope. */
42
+ /**
43
+ * Save the allowlisted queries to async storage and restore them, with a max age, an app-version buster and a user scope.
44
+ *
45
+ * @deprecated Use `persistOffline` with `sqliteLocalCache` from `@marktiderman/genesis-native/offline`: it keeps each record once, per person and workspace. It needs expo-sqlite, a native module, so unless the app's builds already have it the switch takes a new native build and can't ship as an OTA update (https://github.com/marktiderman/genesis/blob/main/docs/MIGRATION.md). Removed in the next major.
46
+ */
43
47
  export function createQueryPersistence({
44
48
  queryClient,
45
49
  storage,
@@ -68,14 +72,22 @@ export function createQueryPersistence({
68
72
  // An unreadable cache has already been deleted; start without it rather than fail the boot.
69
73
  }
70
74
  },
71
- subscribe: (scope) => persistQueryClientSubscribe({ queryClient, persister, buster: scoped(scope), dehydrateOptions }),
75
+ subscribe: (scope, options) => {
76
+ // Adopting: what's already in the client is saved now, not only at its next change.
77
+ if (options?.adopt && scope) void persistQueryClientSave({ queryClient, persister, buster: scoped(scope), dehydrateOptions }).catch(() => undefined);
78
+ return persistQueryClientSubscribe({ queryClient, persister, buster: scoped(scope), dehydrateOptions });
79
+ },
72
80
  clear: async () => {
73
81
  await persister.removeClient();
74
82
  },
75
83
  };
76
84
  }
77
85
 
78
- /** `createQueryPersistence` for `GenesisNativeApp`'s `persist` prop, which supplies the client. */
86
+ /**
87
+ * `createQueryPersistence` for `GenesisNativeApp`'s `persist` prop, which supplies the client.
88
+ *
89
+ * @deprecated Use `persistOffline({ cache: sqliteLocalCache({ db }), resources, buster })` from `@marktiderman/genesis-native/offline`. It needs expo-sqlite, a native module, so unless the app's builds already have it the switch takes a new native build and can't ship as an OTA update (https://github.com/marktiderman/genesis/blob/main/docs/MIGRATION.md). Removed in the next major.
90
+ */
79
91
  export function persistQueries(options: PersistQueriesOptions): (queryClient: QueryClient) => QueryPersistence {
80
92
  return (queryClient) => createQueryPersistence({ ...options, queryClient });
81
93
  }
package/src/query.ts CHANGED
@@ -50,8 +50,11 @@ export function createNativeQueryClient(config: QueryClientConfig = {}): QueryCl
50
50
  export interface QueryPersistence {
51
51
  /** Load the saved cache into the client, if it was saved for `scope`. */
52
52
  restore(scope: string): Promise<void>;
53
- /** Save on every cache change, for `scope`; returns the unsubscribe. */
54
- subscribe(scope: string): () => void;
53
+ /**
54
+ * Save on every cache change, for `scope`; returns the unsubscribe. `adopt`: the reads already
55
+ * in the client are this scope's too (the app empties the client whenever the person changes).
56
+ */
57
+ subscribe(scope: string, options?: { adopt?: boolean }): () => void;
55
58
  /**
56
59
  * Delete the saved cache. Clear the QueryClient first: the subscription
57
60
  * then saves the empty cache, so a save already in flight can't leave the
@@ -18,9 +18,8 @@
18
18
  * genesis-core. Outside Expo Router, wrap a subtree in `<ScreenErrorBoundary>`.
19
19
  */
20
20
  import { useEffect, useMemo, useRef, type ComponentType, type ReactNode } from "react";
21
- import { NativeButton, NativeEmptyState } from "@marktiderman/genesis-ui-native/components";
22
21
  import { reportError } from "@marktiderman/genesis-core/errors";
23
- import { errorDetails, GenesisErrorBoundary, type ErrorReport, type FatalScreenProps, type OnError } from "./errors";
22
+ import { FatalScreen, GenesisErrorBoundary, type ErrorReport, type FatalScreenProps, type OnError } from "./errors";
24
23
 
25
24
  /** What Expo Router gives a route's `ErrorBoundary`: the error, and `retry` to render the route again. */
26
25
  export interface ScreenErrorProps {
@@ -28,29 +27,22 @@ export interface ScreenErrorProps {
28
27
  retry: () => Promise<void>;
29
28
  }
30
29
 
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
- );
30
+ /**
31
+ * The default screen fallback: the screen hit a problem, and "Try again".
32
+ *
33
+ * @deprecated Use `<FatalScreen kind="screen" />`; this name goes at the next major.
34
+ */
35
+ export function ScreenErrorScreen(props: ScreenErrorProps) {
36
+ return <FatalScreen {...props} kind="screen" />;
47
37
  }
48
38
 
39
+ const ScreenFallback = (props: ScreenErrorProps) => <FatalScreen {...props} kind="screen" />;
40
+
49
41
  const reportThroughCore = (error: Error, report: ErrorReport) =>
50
42
  reportError(error, { source: report.source, fatal: report.fatal, ...(report.tags ? { tags: report.tags } : {}) });
51
43
 
52
44
  export interface ScreenErrorBoundaryOptions {
53
- /** What to show. Default `ScreenErrorScreen`. */
45
+ /** What to show. Default `<FatalScreen kind="screen" />`. */
54
46
  fallback?: ComponentType<ScreenErrorProps>;
55
47
  /** Where the error goes. Default `reportError` from genesis-core (the observability block, when it is on). */
56
48
  onError?: OnError;
@@ -65,7 +57,7 @@ export interface ScreenErrorBoundaryOptions {
65
57
  * @stability Beta
66
58
  */
67
59
  export function createScreenErrorBoundary(options: ScreenErrorBoundaryOptions = {}): ComponentType<ScreenErrorProps> {
68
- const Fallback = options.fallback ?? ScreenErrorScreen;
60
+ const Fallback = options.fallback ?? ScreenFallback;
69
61
  const onError = options.onError ?? reportThroughCore;
70
62
  function GenesisScreenErrorBoundary(props: ScreenErrorProps) {
71
63
  const reported = useRef<Error | null>(null);
@@ -99,7 +91,7 @@ export interface ScreenErrorBoundaryProps {
99
91
  * @stability Beta
100
92
  */
101
93
  export function ScreenErrorBoundary({ children, fallback, onError, resetKey }: ScreenErrorBoundaryProps) {
102
- const Screen = fallback ?? ScreenErrorScreen;
94
+ const Screen = fallback ?? ScreenFallback;
103
95
  // The boundary's retry is synchronous; the screen's (Expo Router's shape) returns a promise.
104
96
  const Fallback = useMemo(
105
97
  () =>
@@ -10,9 +10,8 @@ import {
10
10
  NativeButton,
11
11
  NativeEmptyState,
12
12
  NativeGlassSurface,
13
- NativeSheet,
14
- NativeSheetScrollView,
15
13
  NativeText,
14
+ NativeWhatsNewSheet,
16
15
  useLiquidGlass,
17
16
  } from "@marktiderman/genesis-ui-native/components";
18
17
  import type { ReleaseNote } from "./policy";
@@ -133,27 +132,16 @@ export interface WhatsNewProps {
133
132
  dismiss: () => void;
134
133
  }
135
134
 
136
- /** The release notes for this version, once, in a sheet. */
135
+ /**
136
+ * The release notes for this version, once, in a sheet: the updates block's slot, drawn by
137
+ * genesis-ui-native's `NativeWhatsNewSheet` (the same sheet genesis-product's uses).
138
+ */
137
139
  export function WhatsNewSheet({ notes, dismiss }: WhatsNewProps) {
138
140
  return (
139
- <NativeSheet open onOpenChange={(open) => (open ? undefined : dismiss())} testID="genesis-whats-new">
140
- {/* The notes scroll once they pass the sheet's height. */}
141
- <NativeSheetScrollView contentContainerClassName="gap-4 p-6">
142
- <NativeText preset="h3" accessibilityRole="header">
143
- What's new
144
- </NativeText>
145
- {notes.map((note) => (
146
- <View key={note.version} className="gap-1" testID={`genesis-whats-new-${note.version}`}>
147
- <NativeText preset="label">{note.title ?? `Version ${note.version}`}</NativeText>
148
- <NativeText preset="body-sm" className="text-muted-foreground">
149
- {note.body}
150
- </NativeText>
151
- </View>
152
- ))}
153
- <NativeButton onPress={dismiss} testID="genesis-whats-new-done">
154
- Got it
155
- </NativeButton>
156
- </NativeSheetScrollView>
157
- </NativeSheet>
141
+ <NativeWhatsNewSheet
142
+ notes={notes.map((note) => ({ key: note.version, title: note.title ?? `Version ${note.version}`, body: note.body }))}
143
+ dismiss={dismiss}
144
+ testID="genesis-whats-new"
145
+ />
158
146
  );
159
147
  }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/query.ts"],"names":[],"mappings":";;;;AAkBO,IAAM,MAAA,GAAS,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK;AAc9B,SAAS,uBAAA,CAAwB,MAAA,GAA4B,EAAC,EAAgB;AACnF,EAAA,MAAM,EAAE,SAAS,SAAA,EAAW,GAAG,MAAK,GAAI,MAAA,CAAO,kBAAkB,EAAC;AAClE,EAAA,OAAO,IAAI,WAAA,CAAY;AAAA,IACrB,GAAG,MAAA;AAAA,IACH,cAAA,EAAgB;AAAA,MACd,GAAG,IAAA;AAAA,MACH,OAAA,EAAS,EAAE,WAAA,EAAa,cAAA,EAAgB,QAAQ,MAAA,EAAQ,SAAA,EAAW,GAAA,EAAQ,GAAG,OAAA,EAAQ;AAAA,MACtF,SAAA,EAAW,EAAE,WAAA,EAAa,cAAA,EAAgB,GAAG,SAAA;AAAU;AACzD,GACD,CAAA;AACH;AAuCO,SAAS,qBAAA,CAAsB,EAAE,QAAA,EAAU,OAAA,EAAQ,EAAsC;AAC9F,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,YAAA,CAAa,gBAAA,CAAiB,CAAC,UAAA,KAAe;AAC5C,MAAA,MAAM,YAAA,GAAe,SAAS,gBAAA,CAAiB,QAAA,EAAU,CAAC,KAAA,KAAU,UAAA,CAAW,KAAA,KAAU,QAAQ,CAAC,CAAA;AAClG,MAAA,OAAO,MAAM,aAAa,MAAA,EAAO;AAAA,I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AO,MAAM;AACX,IAAA,UAAA,EAAW;AACX,IAAA,YAAA,EAAa;AAAA,EACf,CAAA;AACF","file":"chunk-C54LIT4N.js","sourcesContent":["/**\n * Query: a TanStack Query client with offline-safe defaults, and the contract\n * for saving it to the phone. The persister itself is in\n * `@marktiderman/genesis-native/persist`, so an app that saves nothing doesn't\n * install TanStack's persister packages.\n */\nimport { QueryClient, focusManager, isCancelledError, onlineManager, type QueryClientConfig } from \"@tanstack/react-query\";\nimport { classifyError } from \"@marktiderman/genesis-core/errors\";\nimport type { ErrorReport } from \"./errors\";\n\n/** The part of AsyncStorage (or any async key-value store) Genesis uses. */\nexport interface AsyncStorageLike {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n}\n\n/** One day in milliseconds: the default max age of the saved query cache. */\nexport const DAY_MS = 24 * 60 * 60 * 1000;\n\n/**\n * A QueryClient for a phone. `networkMode: \"offlineFirst\"` runs a query or\n * mutation once whatever the network says, then pauses its retries while the\n * device is offline (`onlineManager`, which `connectQueryLifecycle` feeds from\n * NetInfo), continues them when it is back, and refetches stale queries on\n * reconnect. So offline, a query with saved data keeps showing it\n * (`fetchStatus: \"paused\"`); one with nothing saved stays `pending` and paused\n * until the network returns (check `isPaused`, not only `isPending`, before\n * showing a spinner); and a mutation, which TanStack doesn't retry by default,\n * fails at once instead of waiting. `gcTime` matches the persisted max age, or\n * restored queries would be collected before they are used. Your `config` wins.\n */\nexport function createNativeQueryClient(config: QueryClientConfig = {}): QueryClient {\n const { queries, mutations, ...rest } = config.defaultOptions ?? {};\n return new QueryClient({\n ...config,\n defaultOptions: {\n ...rest,\n queries: { networkMode: \"offlineFirst\", gcTime: DAY_MS, staleTime: 60_000, ...queries },\n mutations: { networkMode: \"offlineFirst\", ...mutations },\n },\n });\n}\n\n/**\n * The saved query cache. A `scope` (the signed-in user's id, `\"\"` for nobody)\n * is part of what is saved: a cache saved for one user is discarded, on disk\n * too, when another scope restores it.\n */\nexport interface QueryPersistence {\n /** Load the saved cache into the client, if it was saved for `scope`. */\n restore(scope: string): Promise<void>;\n /** Save on every cache change, for `scope`; returns the unsubscribe. */\n subscribe(scope: string): () => void;\n /**\n * Delete the saved cache. Clear the QueryClient first: the subscription\n * then saves the empty cache, so a save already in flight can't leave the\n * old queries on disk.\n */\n clear(): Promise<void>;\n}\n\n/** React Native's `AppState`, or a stand-in. */\nexport interface AppStateLike {\n addEventListener(type: \"change\", listener: (state: string) => void): { remove(): void };\n}\n\n/** `@react-native-community/netinfo`'s default export, or a stand-in. */\nexport interface NetInfoLike {\n addEventListener(listener: (state: { isConnected: boolean | null }) => void): () => void;\n}\n\nexport interface QueryLifecycleOptions {\n appState?: AppStateLike;\n netInfo?: NetInfoLike;\n}\n\n/**\n * Tell TanStack Query when the app comes to the front (refetch stale\n * queries) and when the network comes and goes. Returns the cleanup.\n */\nexport function connectQueryLifecycle({ appState, netInfo }: QueryLifecycleOptions): () => void {\n if (appState) {\n focusManager.setEventListener((setFocused) => {\n const subscription = appState.addEventListener(\"change\", (state) => setFocused(state === \"active\"));\n return () => subscription.remove();\n });\n }\n if (netInfo) {\n onlineManager.setEventListener((setOnline) => netInfo.addEventListener((state) => setOnline(state.isConnected !== false)));\n }\n return () => {\n // Replacing the listener runs the cleanup of the one set above.\n if (appState) focusManager.setEventListener(() => () => {});\n if (netInfo) {\n onlineManager.setEventListener(() => () => {});\n // Nothing reports the network any more: don't leave paused queries waiting on the last\n // \"offline\" NetInfo said (offlineFirst pauses retries while offline).\n onlineManager.setOnline(true);\n }\n };\n}\n\n/** A failed query or mutation, as `reportQueryErrors` hands it on. */\nexport type QueryErrorReporter = (error: Error, report: ErrorReport) => void;\n\nexport interface ReportQueryErrorsOptions {\n /** True when the device is offline. Default TanStack's `onlineManager`. */\n isOffline?: () => boolean;\n}\n\n// A key segment that is a name (`tasks`, `chat.messages`), not an id or text.\nconst KEY_NAME = /^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;\nconst LOOKS_LIKE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-|^\\d+$|[0-9a-f]{20,}/i;\n\n/** The first segment of a query or mutation key, when it is a name; never the ids after it. */\nexport function queryKeyName(key: readonly unknown[] | undefined): string | undefined {\n const first = key?.[0];\n return typeof first === \"string\" && KEY_NAME.test(first) && !LOOKS_LIKE_ID.test(first) ? first : undefined;\n}\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(typeof value === \"string\" ? value : \"Unknown error\");\n}\n\n/**\n * Hand every query and mutation that failed for good (after its retries) to\n * `report`, as a non-fatal `query` or `mutation` error tagged with the key's\n * first segment (`query.key: \"tasks\"`), never the ids after it.\n *\n * Only errors worth a report (`classifyError(e).report`): being offline,\n * signed out, a record that's gone and the server's expected refusals\n * (forbidden, conflict, a rejected value) are the screen's to show, not\n * bugs. A cancelled query is never reported. One query or mutation opts out\n * with `meta: { reportErrors: false }`.\n *\n * Works on any client (it subscribes to the caches), so it covers a client\n * the app passed in too. Returns the unsubscribe.\n *\n * @stability Beta\n */\nexport function reportQueryErrors(client: QueryClient, report: QueryErrorReporter, options: ReportQueryErrorsOptions = {}): () => void {\n const isOffline = options.isOffline ?? (() => !onlineManager.isOnline());\n const send = (raw: unknown, source: \"query\" | \"mutation\", key: readonly unknown[] | undefined, meta: Record<string, unknown> | undefined) => {\n if (meta?.reportErrors === false || isCancelledError(raw)) return;\n if (!classifyError(raw, { isOffline }).report) return;\n const name = queryKeyName(key);\n try {\n report(toError(raw), { fatal: false, source, ...(name ? { tags: { [`${source}.key`]: name } } : {}) });\n } catch {\n // A failing reporter must not break the cache's listeners.\n }\n };\n const offQueries = client.getQueryCache().subscribe((event) => {\n if (event.type !== \"updated\" || event.action.type !== \"error\") return;\n send(event.action.error, \"query\", event.query.queryKey, event.query.meta);\n });\n const offMutations = client.getMutationCache().subscribe((event) => {\n if (event.type !== \"updated\" || event.action.type !== \"error\") return;\n send(event.action.error, \"mutation\", event.mutation.options.mutationKey, event.mutation.meta);\n });\n return () => {\n offQueries();\n offMutations();\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/boot.tsx","../src/errors.tsx","../src/screen-boundary.tsx"],"names":["jsx","NativeEmptyState","NativeButton"],"mappings":";;;;;;;AA6DO,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EACjC,IAAA;AAAA,EACT,WAAA,CAAY,IAAA,EAAc,EAAA,EAAY,MAAA,GAAS,gBAAA,EAAkB;AAC/D,IAAA,KAAA,CAAM,cAAc,IAAI,CAAA,EAAA,EAAK,MAAM,CAAA,QAAA,EAAW,EAAE,CAAA,IAAA,CAAM,CAAA;AACtD,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAEA,IAAM,kBAAA,GAAqB,GAAA;AAEpB,SAAS,QAAQ,KAAA,EAAuB;AAC7C,EAAA,IAAI,KAAA,YAAiB,OAAO,OAAO,KAAA;AACnC,EAAA,OAAO,IAAI,KAAA,CAAM,OAAO,KAAA,KAAU,QAAA,GAAW,QAAQ,eAAA,EAAiB,EAAE,KAAA,EAAO,KAAA,EAAO,CAAA;AACxF;AAGA,SAAS,aAAA,CAAc,SAA2B,EAAA,EAA4C;AAC5F,EAAA,IAAI,KAAA;AACJ,EAAA,OAAO,QAAQ,IAAA,CAAK;AAAA,IAClB,OAAA,CAAQ,IAAA;AAAA,MACN,MAAM,SAAA;AAAA,MACN,MAAM;AAAA,KACR;AAAA,IACA,IAAI,OAAA,CAAmB,CAAC,OAAA,KAAY;AAClC,MAAA,KAAA,GAAQ,UAAA,CAAW,MAAM,OAAA,CAAQ,SAAS,GAAG,EAAE,CAAA;AAAA,IACjD,CAAC;AAAA,GACF,CAAA,CAAE,OAAA,CAAQ,MAAM,YAAA,CAAa,KAAK,CAAC,CAAA;AACtC;AAGO,SAAS,UAAA,CAAW,KAAA,EAA4B,OAAA,GAAuB,EAAC,EAA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AAO,MAAA,EAAQ,UAAU,CAAA;AAAA,MACzD,CAAA,CAAA,MAAQ;AAAA,MAER;AAAA,IACF,CAAA,EAAG,CAAC,KAAA,CAAM,KAAK,CAAC,CAAA;AAChB,IAAA,uBAAOF,GAAAA,CAAC,QAAA,EAAA,EAAU,GAAG,KAAA,EAAO,CAAA;AAAA,EAC9B;AACA,EAAA,OAAA,CAAQ,OAAA,CAAQ,IAAA,IAAQ,EAAC,EAAG,MAAA,CAAwC,CAAC,KAAA,EAAO,IAAA,KAAS,IAAA,CAAK,KAAK,CAAA,EAAG,0BAA0B,CAAA;AAC9H;AAiBO,SAAS,oBAAoB,EAAE,QAAA,EAAU,QAAA,EAAU,OAAA,EAAS,UAAS,EAA6B;AACvG,EAAA,MAAM,SAAS,QAAA,IAAY,iBAAA;AAE3B,EAAA,MAAM,QAAA,GAAW,OAAA;AAAA,IACf,MACE,SAAS,cAAA,CAAe,EAAE,KAAA,EAAO,OAAM,EAAqB;AAC1D,MAAA,uBAAOA,GAAAA,CAAC,MAAA,EAAA,EAAO,OAAc,KAAA,EAAO,YAAY,OAAM,EAAG,CAAA;AAAA,IAC3D,CAAA;AAAA,IACF,CAAC,MAAM;AAAA,GACT;AACA,EAAA,uBACEA,GAAAA,CAAC,oBAAA,EAAA,EAAqB,QAAA,EAAU,QAAA,EAAU,OAAA,EAAS,OAAA,IAAW,iBAAA,EAAmB,QAAA,EAAoB,KAAA,EAAO,KAAA,EAAO,MAAA,EAAO,UACvH,QAAA,EACH,CAAA;AAEJ","file":"chunk-MFHOHSEQ.js","sourcesContent":["/**\n * Boot: the async work an app must finish before its first screen (wipe a\n * session left by a reinstall, hydrate stores, load fonts, restore the query\n * cache, read the session).\n *\n * Steps run once each, in order. A step that finished is never run again, so\n * \"try again\" after a failure resumes at the step that failed. Each step has a\n * timeout (10 seconds by default), so a hung step ends in the fatal screen with\n * retry instead of trapping the splash. A minimum keeps a fast boot from\n * flashing the splash.\n *\n * `createBoot` is the controller (no React); `BootProvider` + `useBoot()` read\n * it from components.\n */\nimport { createContext, useContext, useSyncExternalStore, type ReactNode } from \"react\";\n\nexport interface BootStepContext {\n /**\n * Aborted when the step times out. Stop work when it fires: a retry waits\n * for a timed-out run to settle before running the step again.\n */\n signal: AbortSignal;\n}\n\nexport interface BootStep {\n /** Unique within the list; names the step in errors. */\n id: string;\n run: (context: BootStepContext) => Promise<unknown> | unknown;\n /** Overrides the boot's `timeoutMs` for this step. */\n timeoutMs?: number;\n}\n\nexport type BootStatus = \"idle\" | \"booting\" | \"ready\" | \"failed\";\n\nexport interface BootState {\n status: BootStatus;\n /** Set when `status` is `\"failed\"`. */\n error: Error | null;\n /** The id of the step that failed. */\n failedStep: string | null;\n /** Ids of the steps that have finished, in order. */\n completed: readonly string[];\n}\n\nexport interface BootOptions {\n /** Shortest time the boot takes, so the splash doesn't flash. Default 0. */\n minimumMs?: number;\n /** Longest time one step may take. Default 10 000. */\n timeoutMs?: number;\n}\n\nexport interface BootController {\n getState(): BootState;\n subscribe(listener: () => void): () => void;\n /** Run the steps not yet finished. Calling it while a run is in flight returns that run. */\n start(): Promise<void>;\n /** After a failure: run again from the step that failed. */\n retry(): Promise<void>;\n}\n\n/** Thrown when a step takes longer than its timeout. */\nexport class BootTimeoutError extends Error {\n readonly step: string;\n constructor(step: string, ms: number, reason = \"did not finish\") {\n super(`Boot step \"${step}\" ${reason} within ${ms} ms.`);\n this.name = \"BootTimeoutError\";\n this.step = step;\n }\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\nexport function toError(value: unknown): Error {\n if (value instanceof Error) return value;\n return new Error(typeof value === \"string\" ? value : \"Unknown error\", { cause: value });\n}\n\n/** Resolves \"settled\" when `promise` settles, \"pending\" after `ms`. */\nfunction settledWithin(promise: Promise<unknown>, ms: number): Promise<\"settled\" | \"pending\"> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n return Promise.race([\n promise.then(\n () => \"settled\" as const,\n () => \"settled\" as const,\n ),\n new Promise<\"pending\">((resolve) => {\n timer = setTimeout(() => resolve(\"pending\"), ms);\n }),\n ]).finally(() => clearTimeout(timer));\n}\n\n/** The boot controller: runs `steps` once each, in order, with a timeout per step. */\nexport function createBoot(steps: readonly BootStep[], options: BootOptions = {}): BootController {\n const seen = new Set<string>();\n for (const step of steps) {\n if (seen.has(step.id)) throw new Error(`Boot step \"${step.id}\" is listed twice.`);\n seen.add(step.id);\n }\n const { minimumMs = 0, timeoutMs = DEFAULT_TIMEOUT_MS } = options;\n const listeners = new Set<() => void>();\n let state: BootState = { status: \"idle\", error: null, failedStep: null, completed: [] };\n let inFlight: Promise<void> | null = null;\n // A step that timed out keeps running (JavaScript can't stop it; `signal`\n // asks it to). A retry waits for it rather than running it twice at once.\n const abandoned = new Map<string, Promise<\"ok\" | \"failed\">>();\n\n const runStep = async (step: BootStep, ms: number): Promise<void> => {\n const previous = abandoned.get(step.id);\n if (previous) {\n if ((await settledWithin(previous, ms)) === \"pending\") {\n throw new BootTimeoutError(step.id, ms, \"is still running from the last attempt\");\n }\n abandoned.delete(step.id);\n // The abandoned run finished after all: it counts.\n if ((await previous) === \"ok\") return;\n }\n const controller = new AbortController();\n const running = Promise.resolve().then(() => step.run({ signal: controller.signal }));\n if ((await settledWithin(running, ms)) === \"pending\") {\n controller.abort();\n abandoned.set(step.id, running.then(() => \"ok\" as const, () => \"failed\" as const));\n throw new BootTimeoutError(step.id, ms);\n }\n await running;\n };\n\n const set = (next: Partial<BootState>) => {\n state = { ...state, ...next };\n for (const listener of listeners) listener();\n };\n\n const run = async () => {\n const started = Date.now();\n set({ status: \"booting\", error: null, failedStep: null });\n for (const step of steps) {\n if (state.completed.includes(step.id)) continue;\n try {\n await runStep(step, step.timeoutMs ?? timeoutMs);\n } catch (error) {\n set({ status: \"failed\", error: toError(error), failedStep: step.id });\n return;\n }\n set({ completed: [...state.completed, step.id] });\n }\n const wait = minimumMs - (Date.now() - started);\n if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));\n set({ status: \"ready\" });\n };\n\n const start = () => {\n if (state.status === \"ready\") return Promise.resolve();\n if (!inFlight) {\n inFlight = run().finally(() => {\n inFlight = null;\n });\n }\n return inFlight;\n };\n\n return {\n getState: () => state,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n start,\n retry: start,\n };\n}\n\nconst BootContext = createContext<BootController | null>(null);\n\n/** Makes a boot readable with `useBoot()`. */\nexport function BootProvider({ boot, children }: { boot: BootController; children: ReactNode }) {\n return <BootContext.Provider value={boot}>{children}</BootContext.Provider>;\n}\n\nexport interface UseBootReturn extends BootState {\n retry: () => void;\n}\n\n/** The boot's status, and `retry` after a failure. Inside `GenesisNativeApp` or a `BootProvider`. */\nexport function useBoot(): UseBootReturn {\n const boot = useContext(BootContext);\n if (!boot) throw new Error(\"useBoot must be used inside <GenesisNativeApp> or <BootProvider>.\");\n const state = useSyncExternalStore(boot.subscribe, boot.getState, boot.getState);\n return { ...state, retry: () => void boot.retry() };\n}\n","/**\n * Errors: a boundary per screen tree, and handlers for errors React never sees\n * (a fatal global error from `ErrorUtils`, an unhandled promise rejection).\n * All of them report through one `onError` (wire Sentry there) and show the\n * fatal screen instead of letting the app die; its \"Try again\" remounts the\n * tree with fresh state.\n */\nimport { Component, type ComponentType, type ErrorInfo, type ReactNode } from \"react\";\nimport { Pressable, Text, View } from \"react-native\";\nimport { NativeButton, NativeEmptyState } from \"@marktiderman/genesis-ui-native/components\";\nimport { classifyError } from \"@marktiderman/genesis-core/errors\";\nimport { toError } from \"./boot\";\n\ndeclare const __DEV__: boolean | undefined;\n\n/**\n * What a fatal or screen error says under its title: the safe sentence for\n * its kind (offline, signed out…), or nothing for a plain bug. The error's\n * own text can hold an email, an id or a store's internals, so it is shown\n * only in development builds.\n */\nexport function errorDetails(error: Error): string | undefined {\n if (typeof __DEV__ !== \"undefined\" && __DEV__) return error.message;\n const classified = classifyError(error);\n return classified.kind === \"unexpected\" ? undefined : classified.message;\n}\n\nexport interface FatalScreenProps {\n error: Error;\n /** Clears the error and remounts the app below the shell (and re-runs a failed boot). */\n retry: () => void;\n}\n\n/** The default fatal screen: what went wrong and \"Try again\". */\nexport function FatalScreen({ error, retry }: FatalScreenProps) {\n return (\n <NativeEmptyState\n variant=\"error\"\n title=\"Something went wrong\"\n body=\"The app hit a problem. Try again, and if it keeps happening, close and reopen the app.\"\n details={errorDetails(error)}\n primaryAction={\n <NativeButton onPress={retry} testID=\"genesis-fatal-retry\">\n Try again\n </NativeButton>\n }\n testID=\"genesis-fatal\"\n />\n );\n}\n\n/**\n * The last-resort fatal screen: React Native primitives only, no theme, no\n * context, nothing that can itself fail. Shown when the providers could not\n * start, or when the `fatal` slot threw.\n */\nexport function PlainFatalScreen({ error, retry }: FatalScreenProps) {\n return (\n <View testID=\"genesis-fatal-plain\" style={{ flex: 1, justifyContent: \"center\", alignItems: \"center\", padding: 24, gap: 12 }}>\n <Text accessibilityRole=\"header\" style={{ fontSize: 17, fontWeight: \"600\" }}>\n Something went wrong\n </Text>\n <Text style={{ textAlign: \"center\" }}>{errorDetails(error) ?? \"Try again, and if it keeps happening, close and reopen the app.\"}</Text>\n <Pressable accessibilityRole=\"button\" onPress={retry} testID=\"genesis-fatal-plain-retry\" style={{ padding: 12 }}>\n <Text style={{ fontSize: 17 }}>Try again</Text>\n </Pressable>\n </View>\n );\n}\n\nexport interface ErrorReport {\n /** True when the app could not go on (a render error, a failed boot, a fatal global error). */\n fatal: boolean;\n /**\n * `boundary` (the shell's), `screen` (a screen boundary), `global`, `boot`,\n * `rejection`, `query` and `mutation` (a failed query or mutation the\n * shell's query client saw).\n */\n source: \"boundary\" | \"screen\" | \"global\" | \"boot\" | \"rejection\" | \"query\" | \"mutation\";\n componentStack?: string;\n /** False when nothing caught it (an unhandled promise rejection). Default: handled unless fatal. */\n handled?: boolean;\n /** Low-cardinality labels (`query.key`), never ids. */\n tags?: Readonly<Record<string, string>>;\n}\n\nexport type OnError = (error: Error, report: ErrorReport) => void;\n\nexport interface GenesisErrorBoundaryProps {\n children?: ReactNode;\n /** What to render instead of the tree that threw. */\n fallback: ComponentType<FatalScreenProps>;\n onError?: OnError;\n /** Change it to clear a caught error (the tree remounts). */\n resetKey?: unknown;\n /** Called by the fallback's retry, after the error is cleared. */\n onRetry?: () => void;\n /** Reported as fatal (the app could not go on). Default true; a screen boundary reports false. */\n fatal?: boolean;\n /** The report's source. Default `boundary`. */\n source?: ErrorReport[\"source\"];\n}\n\ninterface BoundaryState {\n error: Error | null;\n}\n\n/** An error boundary whose fallback gets `{ error, retry }`. */\nexport class GenesisErrorBoundary extends Component<GenesisErrorBoundaryProps, BoundaryState> {\n override state: BoundaryState = { error: null };\n\n static getDerivedStateFromError(error: unknown): BoundaryState {\n return { error: toError(error) };\n }\n\n override componentDidCatch(error: unknown, info: ErrorInfo) {\n try {\n this.props.onError?.(toError(error), {\n fatal: this.props.fatal ?? true,\n source: this.props.source ?? \"boundary\",\n componentStack: info.componentStack ?? undefined,\n });\n } catch {\n // A failing reporter must not stop the fallback.\n }\n }\n\n override componentDidUpdate(previous: GenesisErrorBoundaryProps) {\n if (this.state.error && previous.resetKey !== this.props.resetKey) this.setState({ error: null });\n }\n\n retry = () => {\n this.setState({ error: null });\n this.props.onRetry?.();\n };\n\n override render() {\n const { error } = this.state;\n if (!error) return this.props.children ?? null;\n const Fallback = this.props.fallback;\n return <Fallback error={error} retry={this.retry} />;\n }\n}\n\n/** React Native's `ErrorUtils` (a global in every RN app), or a stand-in. */\nexport interface ErrorUtilsLike {\n getGlobalHandler(): ((error: unknown, isFatal?: boolean) => void) | undefined;\n setGlobalHandler(handler: (error: unknown, isFatal?: boolean) => void): void;\n}\n\nexport interface GlobalErrorHandlerOptions {\n errorUtils: ErrorUtilsLike;\n onError?: OnError;\n /** A fatal error: show the fatal screen. The previous handler (which would end the app) is not called. */\n onFatal: (error: Error) => void;\n /**\n * True while a fatal screen is already up. Another fatal error then goes to\n * the previous handler, which ends the app (it restarts clean) rather than\n * leaving it stuck behind a screen that may itself be broken.\n */\n alreadyFatal?: () => boolean;\n}\n\n/**\n * Route global errors to `onError`. A fatal one goes to `onFatal` instead of\n * React Native's default handler, which would close the app; a non-fatal one\n * still reaches the previous handler (LogBox in development). Returns a\n * function that puts the previous handler back.\n */\nexport function installGlobalErrorHandler({ errorUtils, onError, onFatal, alreadyFatal }: GlobalErrorHandlerOptions): () => void {\n const previous = errorUtils.getGlobalHandler();\n errorUtils.setGlobalHandler((raw, isFatal) => {\n const error = toError(raw);\n try {\n onError?.(error, { fatal: Boolean(isFatal), source: \"global\" });\n } catch {\n // A failing reporter must not take the handler down with it.\n }\n if (isFatal && !alreadyFatal?.()) onFatal(error);\n else previous?.(raw, isFatal);\n });\n return () => {\n // With no previous handler, leave one that only logs, never ours (it would call an unmounted app).\n // genesis-allow-console: the last handler left once the shell is gone; nothing else is listening.\n errorUtils.setGlobalHandler(previous ?? ((error) => console.error(error)));\n };\n}\n\n/** `globalThis.ErrorUtils` in a React Native runtime, undefined elsewhere. */\nexport function defaultErrorUtils(): ErrorUtilsLike | undefined {\n const candidate = (globalThis as { ErrorUtils?: ErrorUtilsLike }).ErrorUtils;\n return candidate && typeof candidate.setGlobalHandler === \"function\" ? candidate : undefined;\n}\n\n/** Hermes's `HermesInternal.enablePromiseRejectionTracker`, or a stand-in. */\nexport type EnableRejectionTracker = (options: {\n allRejections: boolean;\n onUnhandled: (id: number, rejection: unknown) => void;\n onHandled: (id: number) => void;\n}) => void;\n\n/**\n * Hermes's rejection tracker, when the app runs on Hermes. React Native sends\n * unhandled rejections to `ExceptionsManager` (LogBox in development), never\n * to `ErrorUtils`' global handler, so without this they never reach `onError`.\n */\nexport function defaultRejectionTracker(): EnableRejectionTracker | undefined {\n const hermes = (globalThis as { HermesInternal?: { enablePromiseRejectionTracker?: EnableRejectionTracker } }).HermesInternal;\n const enable = hermes?.enablePromiseRejectionTracker;\n return typeof enable === \"function\" ? enable.bind(hermes) : undefined;\n}\n\n/**\n * Report unhandled promise rejections to `onError`: non-fatal, and unhandled\n * (`handled: false`), so release health counts them. This replaces React\n * Native's own tracker, so each rejection is also written with\n * `console.warn`, which LogBox shows in development as before.\n */\nexport function installRejectionTracker({ enable, onError }: { enable: EnableRejectionTracker; onError: OnError }): void {\n enable({\n allRejections: true,\n onUnhandled: (id, rejection) => {\n const error = toError(rejection);\n // genesis-allow-console: React Native's own tracker writes this warning; replacing it must too (LogBox).\n console.warn(`Uncaught (in promise, id: ${id}): ${error.message}`);\n try {\n onError(error, { fatal: false, handled: false, source: \"rejection\" });\n } catch {\n // A failing reporter must not throw inside the promise machinery.\n }\n },\n onHandled: () => {},\n });\n}\n","/**\n * Screen errors: one screen fails, the rest of the app (the tab bar, the\n * other tabs) keeps working. The error is reported non-fatal, and \"Try\n * again\" renders the screen again.\n *\n * With Expo Router, export the boundary from a route or layout file; it\n * catches errors in that route and the routes below it:\n *\n * // src/lib/observability.ts\n * export const ScreenErrorBoundary = observability.screenBoundary();\n * // src/app/(app)/messages/_layout.tsx\n * export { ScreenErrorBoundary as ErrorBoundary } from \"@/lib/observability\";\n *\n * `observability.screenBoundary()` reports through the block and wraps the\n * boundary with each sink's route wrapper (Sentry's\n * `wrapExpoRouterErrorBoundary`). Without the block,\n * `createScreenErrorBoundary()` reports through `reportError` from\n * genesis-core. Outside Expo Router, wrap a subtree in `<ScreenErrorBoundary>`.\n */\nimport { useEffect, useMemo, useRef, type ComponentType, type ReactNode } from \"react\";\nimport { NativeButton, NativeEmptyState } from \"@marktiderman/genesis-ui-native/components\";\nimport { reportError } from \"@marktiderman/genesis-core/errors\";\nimport { errorDetails, GenesisErrorBoundary, type ErrorReport, type FatalScreenProps, type OnError } from \"./errors\";\n\n/** What Expo Router gives a route's `ErrorBoundary`: the error, and `retry` to render the route again. */\nexport interface ScreenErrorProps {\n error: Error;\n retry: () => Promise<void>;\n}\n\n/** The default screen fallback: the screen hit a problem, and \"Try again\". @stability Beta */\nexport function ScreenErrorScreen({ error, retry }: ScreenErrorProps) {\n return (\n <NativeEmptyState\n variant=\"error\"\n title=\"This screen hit a problem\"\n body=\"The rest of the app still works. Try again, or go back.\"\n details={errorDetails(error)}\n primaryAction={\n <NativeButton onPress={() => void Promise.resolve(retry()).catch((e: unknown) => reportError(e, \"native:screen-retry\"))} testID=\"genesis-screen-error-retry\">\n Try again\n </NativeButton>\n }\n testID=\"genesis-screen-error\"\n />\n );\n}\n\nconst reportThroughCore = (error: Error, report: ErrorReport) =>\n reportError(error, { source: report.source, fatal: report.fatal, ...(report.tags ? { tags: report.tags } : {}) });\n\nexport interface ScreenErrorBoundaryOptions {\n /** What to show. Default `ScreenErrorScreen`. */\n fallback?: ComponentType<ScreenErrorProps>;\n /** Where the error goes. Default `reportError` from genesis-core (the observability block, when it is on). */\n onError?: OnError;\n /** Wrappers around the route boundary, innermost first (Sentry's `wrapExpoRouterErrorBoundary`). */\n wrap?: readonly ((boundary: ComponentType<ScreenErrorProps>) => ComponentType<ScreenErrorProps>)[];\n}\n\n/**\n * An Expo Router `ErrorBoundary`: reports each error once (non-fatal, source\n * `screen`) and shows `fallback`. Build it once, at module scope.\n *\n * @stability Beta\n */\nexport function createScreenErrorBoundary(options: ScreenErrorBoundaryOptions = {}): ComponentType<ScreenErrorProps> {\n const Fallback = options.fallback ?? ScreenErrorScreen;\n const onError = options.onError ?? reportThroughCore;\n function GenesisScreenErrorBoundary(props: ScreenErrorProps) {\n const reported = useRef<Error | null>(null);\n useEffect(() => {\n if (reported.current === props.error) return;\n reported.current = props.error;\n try {\n onError(props.error, { fatal: false, source: \"screen\" });\n } catch {\n // A failing reporter must not take the fallback down with it.\n }\n }, [props.error]);\n return <Fallback {...props} />;\n }\n return (options.wrap ?? []).reduce<ComponentType<ScreenErrorProps>>((inner, wrap) => wrap(inner), GenesisScreenErrorBoundary);\n}\n\nexport interface ScreenErrorBoundaryProps {\n children?: ReactNode;\n fallback?: ComponentType<ScreenErrorProps>;\n /** Default `reportError` from genesis-core. */\n onError?: OnError;\n /** Change it to clear a caught error. */\n resetKey?: unknown;\n}\n\n/**\n * A boundary around part of a screen tree, for apps without Expo Router's\n * per-route boundaries: non-fatal, reported, with \"Try again\".\n *\n * @stability Beta\n */\nexport function ScreenErrorBoundary({ children, fallback, onError, resetKey }: ScreenErrorBoundaryProps) {\n const Screen = fallback ?? ScreenErrorScreen;\n // The boundary's retry is synchronous; the screen's (Expo Router's shape) returns a promise.\n const Fallback = useMemo(\n () =>\n function ScreenFallback({ error, retry }: FatalScreenProps) {\n return <Screen error={error} retry={async () => retry()} />;\n },\n [Screen],\n );\n return (\n <GenesisErrorBoundary fallback={Fallback} onError={onError ?? reportThroughCore} resetKey={resetKey} fatal={false} source=\"screen\">\n {children}\n </GenesisErrorBoundary>\n );\n}\n"]}