@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.
- package/README.md +98 -6
- package/dist/{block-Onqx7NiK.d.ts → block-DFnC8j5U.d.ts} +53 -3
- package/dist/{blocks-C2RDpvaN.d.ts → blocks-CyXjSGwV.d.ts} +12 -93
- package/dist/{chunk-75YP72G6.js → chunk-6L36FQBX.js} +95 -7
- package/dist/chunk-6L36FQBX.js.map +1 -0
- package/dist/chunk-C54LIT4N.js +73 -0
- package/dist/chunk-C54LIT4N.js.map +1 -0
- package/dist/chunk-MFHOHSEQ.js +249 -0
- package/dist/chunk-MFHOHSEQ.js.map +1 -0
- package/dist/chunk-VIC2KXMA.js +35 -0
- package/dist/chunk-VIC2KXMA.js.map +1 -0
- package/dist/devtools.d.ts +5 -4
- package/dist/devtools.js +3 -1
- package/dist/devtools.js.map +1 -1
- package/dist/index.d.ts +28 -4
- package/dist/index.js +13 -192
- package/dist/index.js.map +1 -1
- package/dist/observability.d.ts +33 -7
- package/dist/observability.js +20 -7
- package/dist/observability.js.map +1 -1
- package/dist/persist.d.ts +2 -1
- package/dist/persist.js +1 -1
- package/dist/push.d.ts +3 -3
- package/dist/query-DobJyRvs.d.ts +208 -0
- package/dist/screen-boundary-BlT6KBpa.d.ts +43 -0
- package/dist/updates.d.ts +2 -2
- package/dist/updates.js +3 -0
- package/dist/updates.js.map +1 -1
- package/dist/web-handoff.d.ts +88 -0
- package/dist/web-handoff.js +78 -0
- package/dist/web-handoff.js.map +1 -0
- package/package.json +10 -5
- package/src/app.tsx +16 -2
- package/src/errors.tsx +46 -7
- package/src/index.ts +24 -0
- package/src/observability/block.tsx +132 -5
- package/src/observability/index.ts +2 -0
- package/src/observability/sentry.ts +41 -6
- package/src/observability/sink.ts +30 -1
- package/src/query.ts +67 -1
- package/src/reload.ts +56 -0
- package/src/screen-boundary.tsx +116 -0
- package/src/updates/channels.ts +3 -0
- package/src/updates/checker.ts +3 -0
- package/src/web-handoff.ts +165 -0
- package/dist/chunk-75YP72G6.js.map +0 -1
- package/dist/chunk-VTJDIKFC.js +0 -39
- package/dist/chunk-VTJDIKFC.js.map +0 -1
- package/dist/query-DUmVAfsF.d.ts +0 -70
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// src/web-handoff.ts
|
|
2
|
+
function isAppPath(path) {
|
|
3
|
+
return path.startsWith("/") && !path.startsWith("//") && !/[\\\u0000-\u0020\u007f-\u009f]/.test(path);
|
|
4
|
+
}
|
|
5
|
+
async function openOnWeb(path, options) {
|
|
6
|
+
if (!isAppPath(path)) throw new TypeError(`openOnWeb takes a path on the web app, like "/settings"; got ${JSON.stringify(path)}.`);
|
|
7
|
+
const { endpoint, browser, browserOptions, pagePath = "/auth/handoff", timeoutMs = 8e3 } = options;
|
|
8
|
+
const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
9
|
+
const origin = new URL(endpoint).origin;
|
|
10
|
+
const signedOutUrl = `${origin}${isAppPath(pagePath) ? pagePath : "/auth/handoff"}#${new URLSearchParams({ next: path }).toString()}`;
|
|
11
|
+
const open = async (url) => {
|
|
12
|
+
await browser.openBrowserAsync(url, browserOptions);
|
|
13
|
+
};
|
|
14
|
+
const token = await options.getAccessToken();
|
|
15
|
+
if (!token) {
|
|
16
|
+
await open(signedOutUrl);
|
|
17
|
+
return { signedIn: false, reason: "signed_out" };
|
|
18
|
+
}
|
|
19
|
+
let response;
|
|
20
|
+
const controller = new AbortController();
|
|
21
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
22
|
+
try {
|
|
23
|
+
response = await doFetch(endpoint, {
|
|
24
|
+
method: "POST",
|
|
25
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
|
26
|
+
body: JSON.stringify({ path }),
|
|
27
|
+
signal: controller.signal
|
|
28
|
+
});
|
|
29
|
+
} catch {
|
|
30
|
+
await open(signedOutUrl);
|
|
31
|
+
return { signedIn: false, reason: "unreachable" };
|
|
32
|
+
} finally {
|
|
33
|
+
clearTimeout(timer);
|
|
34
|
+
}
|
|
35
|
+
const body = await response.json().catch(() => ({}));
|
|
36
|
+
const sameOrigin = (url) => {
|
|
37
|
+
if (typeof url !== "string") return false;
|
|
38
|
+
try {
|
|
39
|
+
return new URL(url).origin === origin;
|
|
40
|
+
} catch {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
if (response.ok && sameOrigin(body.url)) {
|
|
45
|
+
await open(body.url);
|
|
46
|
+
return { signedIn: true };
|
|
47
|
+
}
|
|
48
|
+
if (response.status === 400) throw new TypeError(`The server refused ${JSON.stringify(path)} as a web path.`);
|
|
49
|
+
await open(sameOrigin(body.fallbackUrl) ? body.fallbackUrl : signedOutUrl);
|
|
50
|
+
const reason = body.error === "no_email" || body.error === "rate_limited" ? body.error : "refused";
|
|
51
|
+
return { signedIn: false, reason };
|
|
52
|
+
}
|
|
53
|
+
async function signOutOnWeb(options) {
|
|
54
|
+
const { endpoint, timeoutMs = 5e3 } = options;
|
|
55
|
+
const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
56
|
+
const controller = new AbortController();
|
|
57
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
58
|
+
try {
|
|
59
|
+
const token = await options.getAccessToken();
|
|
60
|
+
if (!token) return 0;
|
|
61
|
+
const response = await doFetch(endpoint, {
|
|
62
|
+
method: "POST",
|
|
63
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
|
64
|
+
body: "{}",
|
|
65
|
+
signal: controller.signal
|
|
66
|
+
});
|
|
67
|
+
const body = await response.json().catch(() => ({}));
|
|
68
|
+
return response.ok && typeof body.count === "number" ? body.count : 0;
|
|
69
|
+
} catch {
|
|
70
|
+
return 0;
|
|
71
|
+
} finally {
|
|
72
|
+
clearTimeout(timer);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export { openO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IAAA;AAAA,MACN,QAAQ,UAAA,CAAW;AAAA,KACpB,CAAA;AACD,IAAA,MAAM,IAAA,GAAQ,MAAM,QAAA,CAAS,IAAA,GAAO,KAAA,CAAM,OAAO,EAAC,CAAE,CAAA;AACpD,IAAA,OAAO,SAAS,EAAA,IAAM,OAAO,KAAK,KAAA,KAAU,QAAA,GAAW,KAAK,KAAA,GAAQ,CAAA;AAAA,EACtE,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,CAAA;AAAA,EACT,CAAA,SAAE;AACA,IAAA,YAAA,CAAa,KAAK,CAAA;AAAA,EACpB;AACF","file":"web-handoff.js","sourcesContent":["/**\n * `@marktiderman/genesis-native/web-handoff`: open a page of the web app signed in as the person\n * using the app, so work the app leaves to the web carries on without a sign-in screen.\n *\n * The app asks its server for a single-use, short-lived link (genesis-supabase's\n * `createWebHandoff`, the `mint` route) with the session's access token, then opens it in the\n * in-app browser. The modules are injected, never imported:\n *\n * ```ts\n * import * as WebBrowser from \"expo-web-browser\";\n * await openOnWeb(\"/clients/1/forms\", {\n * endpoint: \"https://app.example.com/api/auth/handoff\",\n * getAccessToken: async () => (await supabase.auth.getSession()).data.session?.access_token,\n * browser: WebBrowser,\n * });\n * ```\n *\n * Why the in-app browser (`openBrowserAsync`: SFSafariViewController on iOS, a Custom Tab on\n * Android) and not `Linking.openURL` (Safari): the person stays in the app and Done brings them\n * back; and the in-app browser keeps its own website data between openings, so after the first\n * handoff the page is already signed in as them and goes straight to the path. Safari may be\n * signed in as someone else, which would ask them to switch every time. Not\n * `openAuthSessionAsync` either: it shows the system \"wants to use … to sign in\" alert each time.\n *\n * @packageDocumentation\n */\n\n/** `expo-web-browser`'s `openBrowserAsync`, as the shape used here. */\nexport interface WebBrowserLike {\n openBrowserAsync(url: string, options?: Record<string, unknown>): Promise<unknown>;\n}\n\n/** @stability Beta */\nexport interface OpenOnWebOptions {\n /** The mint route: `https://<web app>/api/auth/handoff`. Its origin is also the web app's. */\n endpoint: string;\n /** The signed-in session's access token, or nothing when signed out. */\n getAccessToken: () => Promise<string | null | undefined> | string | null | undefined;\n /** `import * as WebBrowser from \"expo-web-browser\"`. */\n browser: WebBrowserLike;\n /** Passed to `openBrowserAsync` (presentationStyle, controlsColor…). */\n browserOptions?: Record<string, unknown>;\n /** The web page that completes a handoff, also shown signed out. Default `/auth/handoff`. */\n pagePath?: string;\n /** Give up on the server after this long and open the page signed out. Default 8000 ms. */\n timeoutMs?: number;\n fetch?: typeof fetch;\n}\n\nexport type OpenOnWebResult =\n /** Opened signed in (the page may still ask \"Continue as …?\" the first time). */\n | { signedIn: true }\n /**\n * Opened the page signed out, so the person signs in there and lands on the path: no session\n * here, the server unreachable, no email on the account (Supabase signs in by email link), or\n * too many links in a minute.\n */\n | { signedIn: false; reason: \"signed_out\" | \"unreachable\" | \"no_email\" | \"rate_limited\" | \"refused\" };\n\n/** Only paths on the web app: one leading `/`, no `//`, no backslash or control characters. */\nfunction isAppPath(path: string): boolean {\n // eslint-disable-next-line no-control-regex\n return path.startsWith(\"/\") && !path.startsWith(\"//\") && !/[\\\\\\u0000-\\u0020\\u007f-\\u009f]/.test(path);\n}\n\n/**\n * Open `path` on the web app, signed in as the app's person. Throws for a path that isn't the\n * web app's own (`https://…`, `//host`); the server checks again. When a signed-in link can't\n * be had, opens the page signed out instead of failing the tap.\n *\n * @stability Beta\n */\nexport async function openOnWeb(path: string, options: OpenOnWebOptions): Promise<OpenOnWebResult> {\n if (!isAppPath(path)) throw new TypeError(`openOnWeb takes a path on the web app, like \"/settings\"; got ${JSON.stringify(path)}.`);\n const { endpoint, browser, browserOptions, pagePath = \"/auth/handoff\", timeoutMs = 8000 } = options;\n const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n const origin = new URL(endpoint).origin;\n // Signed out: the web app's sign-in page, which returns to the path afterwards.\n const signedOutUrl = `${origin}${isAppPath(pagePath) ? pagePath : \"/auth/handoff\"}#${new URLSearchParams({ next: path }).toString()}`;\n const open = async (url: string) => {\n await browser.openBrowserAsync(url, browserOptions);\n };\n\n const token = await options.getAccessToken();\n if (!token) {\n await open(signedOutUrl);\n return { signedIn: false, reason: \"signed_out\" };\n }\n\n let response: Response;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n response = await doFetch(endpoint, {\n method: \"POST\",\n headers: { authorization: `Bearer ${token}`, \"content-type\": \"application/json\" },\n body: JSON.stringify({ path }),\n signal: controller.signal,\n });\n } catch {\n await open(signedOutUrl);\n return { signedIn: false, reason: \"unreachable\" };\n } finally {\n clearTimeout(timer);\n }\n\n const body = (await response.json().catch(() => ({}))) as { url?: unknown; error?: unknown; fallbackUrl?: unknown };\n const sameOrigin = (url: unknown): url is string => {\n if (typeof url !== \"string\") return false;\n try {\n return new URL(url).origin === origin;\n } catch {\n return false;\n }\n };\n if (response.ok && sameOrigin(body.url)) {\n await open(body.url);\n return { signedIn: true };\n }\n if (response.status === 400) throw new TypeError(`The server refused ${JSON.stringify(path)} as a web path.`);\n await open(sameOrigin(body.fallbackUrl) ? body.fallbackUrl : signedOutUrl);\n const reason = body.error === \"no_email\" || body.error === \"rate_limited\" ? body.error : \"refused\";\n return { signedIn: false, reason };\n}\n\n/** @stability Beta */\nexport interface SignOutOnWebOptions {\n /** The sign-out route: `https://<web app>/api/auth/handoff-signout`. */\n endpoint: string;\n /** The session's access token, still valid: call this before the app signs out. */\n getAccessToken: () => Promise<string | null | undefined> | string | null | undefined;\n /** Give up after this long. Default 5000 ms. */\n timeoutMs?: number;\n fetch?: typeof fetch;\n}\n\n/**\n * End the web sessions this app session handed off with {@link openOnWeb} (and only those; never\n * the person's other devices). Call it just before the app's own sign-out, while the access token\n * still works. It never throws, so it can't block signing out; it returns how many it ended.\n *\n * @stability Beta\n */\nexport async function signOutOnWeb(options: SignOutOnWebOptions): Promise<number> {\n const { endpoint, timeoutMs = 5000 } = options;\n const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const token = await options.getAccessToken();\n if (!token) return 0;\n const response = await doFetch(endpoint, {\n method: \"POST\",\n headers: { authorization: `Bearer ${token}`, \"content-type\": \"application/json\" },\n body: \"{}\",\n signal: controller.signal,\n });\n const body = (await response.json().catch(() => ({}))) as { count?: unknown };\n return response.ok && typeof body.count === \"number\" ? body.count : 0;\n } catch {\n return 0;\n } finally {\n clearTimeout(timer);\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@marktiderman/genesis-native",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
|
-
"description": "The native app shell for Genesis Expo apps: one GenesisNativeApp root that runs boot steps behind the splash, catches errors into a fatal screen with retry, persists the query cache, gates on the Supabase session and normalizes deep links. An optional updates block (/updates) adds force upgrade, maintenance, an update banner and what's new; an optional push block (/push) adds push registration, tap routing, the badge and a notification settings screen with quiet hours and private previews; the observability block (/observability) reports errors, breadcrumbs, typed analytics events and timings through vendor-neutral sinks (Sentry, EAS Observe, console) with PII scrubbed on the device; the devtools overlay (/devtools) is a debug sheet for development and preview builds. Blocks (defineBlock declarations, through `blocks`) add boot steps, roots, slot fills and Settings rows. Every part is a slot and is also exported on its own. Part of the Genesis framework.",
|
|
7
|
+
"description": "The native app shell for Genesis Expo apps: one GenesisNativeApp root that runs boot steps behind the splash, catches errors into a fatal screen with retry, persists the query cache, gates on the Supabase session and normalizes deep links. An optional updates block (/updates) adds force upgrade, maintenance, an update banner and what's new; an optional push block (/push) adds push registration, tap routing, the badge and a notification settings screen with quiet hours and private previews; the observability block (/observability) reports errors, breadcrumbs, typed analytics events and timings through vendor-neutral sinks (Sentry, EAS Observe, console) with PII scrubbed on the device; the devtools overlay (/devtools) is a debug sheet for development and preview builds. openOnWeb (/web-handoff) opens a page of the web app signed in as the same person. Blocks (defineBlock declarations, through `blocks`) add boot steps, roots, slot fills and Settings rows. Every part is a slot and is also exported on its own. Part of the Genesis framework.",
|
|
8
8
|
"repository": {
|
|
9
9
|
"type": "git",
|
|
10
10
|
"url": "git+https://github.com/marktiderman/genesis.git",
|
|
@@ -57,6 +57,11 @@
|
|
|
57
57
|
"react-native": "./src/devtools/index.ts",
|
|
58
58
|
"import": "./dist/devtools.js"
|
|
59
59
|
},
|
|
60
|
+
"./web-handoff": {
|
|
61
|
+
"types": "./dist/web-handoff.d.ts",
|
|
62
|
+
"react-native": "./src/web-handoff.ts",
|
|
63
|
+
"import": "./dist/web-handoff.js"
|
|
64
|
+
},
|
|
60
65
|
"./dev-warnings": {
|
|
61
66
|
"types": "./dist/dev-warnings.d.ts",
|
|
62
67
|
"react-native": "./src/dev-warnings.ts",
|
|
@@ -76,10 +81,10 @@
|
|
|
76
81
|
"README.md"
|
|
77
82
|
],
|
|
78
83
|
"dependencies": {
|
|
79
|
-
"@marktiderman/genesis-core": "^
|
|
84
|
+
"@marktiderman/genesis-core": "^2.0.0",
|
|
80
85
|
"@marktiderman/genesis-design-system": "^1.5.0",
|
|
81
|
-
"@marktiderman/genesis-features": "^0.6.
|
|
82
|
-
"@marktiderman/genesis-ui-native": "^
|
|
86
|
+
"@marktiderman/genesis-features": "^0.6.1",
|
|
87
|
+
"@marktiderman/genesis-ui-native": "^3.0.0"
|
|
83
88
|
},
|
|
84
89
|
"peerDependencies": {
|
|
85
90
|
"@tanstack/query-async-storage-persister": "^5.0.0",
|
package/src/app.tsx
CHANGED
|
@@ -12,7 +12,9 @@
|
|
|
12
12
|
* └ errorBoundary → `bottomSheet`'s provider, if given → your screens (or `signedOut`)
|
|
13
13
|
*
|
|
14
14
|
* Every error the shell catches goes to each block's `onError` (the
|
|
15
|
-
* observability block reports it) and then to the app's own `onError
|
|
15
|
+
* observability block reports it) and then to the app's own `onError`:
|
|
16
|
+
* render, global, boot and unhandled-rejection errors, and queries and
|
|
17
|
+
* mutations that failed unexpectedly (`reportQueryErrors`).
|
|
16
18
|
*
|
|
17
19
|
* `blocks` (`defineBlock` declarations a native shell can run) are resolved
|
|
18
20
|
* once: requirements checked, boot steps run behind the splash, roots
|
|
@@ -55,7 +57,7 @@ import {
|
|
|
55
57
|
} from "./errors";
|
|
56
58
|
import { SessionProvider, createSessionStore, type AuthClientLike } from "./auth";
|
|
57
59
|
import { useHeldLink, type HeldLinkAuth, type LinkHold } from "./held-link";
|
|
58
|
-
import { connectQueryLifecycle, createNativeQueryClient, type QueryLifecycleOptions, type QueryPersistence } from "./query";
|
|
60
|
+
import { connectQueryLifecycle, createNativeQueryClient, reportQueryErrors, type QueryLifecycleOptions, type QueryPersistence } from "./query";
|
|
59
61
|
import { resolveBlocks } from "@marktiderman/genesis-features/blocks";
|
|
60
62
|
import { BlocksProvider, reportToBlocks, type NativeBlock } from "./blocks";
|
|
61
63
|
import type { DevtoolsSlots } from "./devtools/slots";
|
|
@@ -171,6 +173,15 @@ export interface GenesisNativeAppProps {
|
|
|
171
173
|
rejectionTracker?: EnableRejectionTracker | null;
|
|
172
174
|
/** `AppState` and NetInfo, so queries refetch on focus and know the network. */
|
|
173
175
|
lifecycle?: QueryLifecycleOptions;
|
|
176
|
+
/**
|
|
177
|
+
* Report queries and mutations that failed for good to `onError` (and so
|
|
178
|
+
* to the observability block), non-fatal, as `query` / `mutation` with the
|
|
179
|
+
* key's first segment as a tag. Only unexpected errors: offline, signed
|
|
180
|
+
* out, not found and the server's expected refusals are left to the
|
|
181
|
+
* screen. One query opts out with `meta: { reportErrors: false }`.
|
|
182
|
+
* Default true. Read once.
|
|
183
|
+
*/
|
|
184
|
+
reportQueryErrors?: boolean;
|
|
174
185
|
/**
|
|
175
186
|
* Every caught error, after the blocks' own `onError` (the observability
|
|
176
187
|
* block, `createObservability` from `/observability`, reports to Sentry
|
|
@@ -279,6 +290,7 @@ function ThemedShell(props: GenesisNativeAppProps) {
|
|
|
279
290
|
const toolbarWithoutScroll = Boolean(keyboardToolbar) && !keyboardScroll;
|
|
280
291
|
useEffect(() => {
|
|
281
292
|
if (typeof __DEV__ === "undefined" || !__DEV__) return;
|
|
293
|
+
// genesis-allow-console: development-only set-up mistakes, shown as LogBox errors on purpose.
|
|
282
294
|
if (missingProvider) console.error(MISSING_KEYBOARD_PROVIDER);
|
|
283
295
|
if (toolbarWithoutScroll) console.error(TOOLBAR_WITHOUT_SCROLL);
|
|
284
296
|
}, [missingProvider, toolbarWithoutScroll]);
|
|
@@ -391,6 +403,8 @@ function Shell(props: GenesisNativeAppProps) {
|
|
|
391
403
|
if (enable) installRejectionTracker({ enable, onError });
|
|
392
404
|
}, [rejectionTracker]);
|
|
393
405
|
useEffect(() => (lifecycle ? connectQueryLifecycle(lifecycle) : undefined), [lifecycle]);
|
|
406
|
+
const [queryReports] = useState(() => props.reportQueryErrors !== false);
|
|
407
|
+
useEffect(() => (queryReports ? reportQueryErrors(client, onError) : undefined), [client, queryReports]);
|
|
394
408
|
|
|
395
409
|
// Splash: up until boot has finished (the session step included), or failed.
|
|
396
410
|
const settled = bootState.status === "ready" || bootState.status === "failed" || fatal !== null;
|
package/src/errors.tsx
CHANGED
|
@@ -8,8 +8,23 @@
|
|
|
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
12
|
import { toError } from "./boot";
|
|
12
13
|
|
|
14
|
+
declare const __DEV__: boolean | undefined;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* What a fatal or screen error says under its title: the safe sentence for
|
|
18
|
+
* its kind (offline, signed out…), or nothing for a plain bug. The error's
|
|
19
|
+
* own text can hold an email, an id or a store's internals, so it is shown
|
|
20
|
+
* only in development builds.
|
|
21
|
+
*/
|
|
22
|
+
export function errorDetails(error: Error): string | undefined {
|
|
23
|
+
if (typeof __DEV__ !== "undefined" && __DEV__) return error.message;
|
|
24
|
+
const classified = classifyError(error);
|
|
25
|
+
return classified.kind === "unexpected" ? undefined : classified.message;
|
|
26
|
+
}
|
|
27
|
+
|
|
13
28
|
export interface FatalScreenProps {
|
|
14
29
|
error: Error;
|
|
15
30
|
/** Clears the error and remounts the app below the shell (and re-runs a failed boot). */
|
|
@@ -23,7 +38,7 @@ export function FatalScreen({ error, retry }: FatalScreenProps) {
|
|
|
23
38
|
variant="error"
|
|
24
39
|
title="Something went wrong"
|
|
25
40
|
body="The app hit a problem. Try again, and if it keeps happening, close and reopen the app."
|
|
26
|
-
details={error
|
|
41
|
+
details={errorDetails(error)}
|
|
27
42
|
primaryAction={
|
|
28
43
|
<NativeButton onPress={retry} testID="genesis-fatal-retry">
|
|
29
44
|
Try again
|
|
@@ -45,7 +60,7 @@ export function PlainFatalScreen({ error, retry }: FatalScreenProps) {
|
|
|
45
60
|
<Text accessibilityRole="header" style={{ fontSize: 17, fontWeight: "600" }}>
|
|
46
61
|
Something went wrong
|
|
47
62
|
</Text>
|
|
48
|
-
<Text style={{ textAlign: "center" }}>{error.
|
|
63
|
+
<Text style={{ textAlign: "center" }}>{errorDetails(error) ?? "Try again, and if it keeps happening, close and reopen the app."}</Text>
|
|
49
64
|
<Pressable accessibilityRole="button" onPress={retry} testID="genesis-fatal-plain-retry" style={{ padding: 12 }}>
|
|
50
65
|
<Text style={{ fontSize: 17 }}>Try again</Text>
|
|
51
66
|
</Pressable>
|
|
@@ -56,8 +71,17 @@ export function PlainFatalScreen({ error, retry }: FatalScreenProps) {
|
|
|
56
71
|
export interface ErrorReport {
|
|
57
72
|
/** True when the app could not go on (a render error, a failed boot, a fatal global error). */
|
|
58
73
|
fatal: boolean;
|
|
59
|
-
|
|
74
|
+
/**
|
|
75
|
+
* `boundary` (the shell's), `screen` (a screen boundary), `global`, `boot`,
|
|
76
|
+
* `rejection`, `query` and `mutation` (a failed query or mutation the
|
|
77
|
+
* shell's query client saw).
|
|
78
|
+
*/
|
|
79
|
+
source: "boundary" | "screen" | "global" | "boot" | "rejection" | "query" | "mutation";
|
|
60
80
|
componentStack?: string;
|
|
81
|
+
/** False when nothing caught it (an unhandled promise rejection). Default: handled unless fatal. */
|
|
82
|
+
handled?: boolean;
|
|
83
|
+
/** Low-cardinality labels (`query.key`), never ids. */
|
|
84
|
+
tags?: Readonly<Record<string, string>>;
|
|
61
85
|
}
|
|
62
86
|
|
|
63
87
|
export type OnError = (error: Error, report: ErrorReport) => void;
|
|
@@ -71,6 +95,10 @@ export interface GenesisErrorBoundaryProps {
|
|
|
71
95
|
resetKey?: unknown;
|
|
72
96
|
/** Called by the fallback's retry, after the error is cleared. */
|
|
73
97
|
onRetry?: () => void;
|
|
98
|
+
/** Reported as fatal (the app could not go on). Default true; a screen boundary reports false. */
|
|
99
|
+
fatal?: boolean;
|
|
100
|
+
/** The report's source. Default `boundary`. */
|
|
101
|
+
source?: ErrorReport["source"];
|
|
74
102
|
}
|
|
75
103
|
|
|
76
104
|
interface BoundaryState {
|
|
@@ -86,7 +114,15 @@ export class GenesisErrorBoundary extends Component<GenesisErrorBoundaryProps, B
|
|
|
86
114
|
}
|
|
87
115
|
|
|
88
116
|
override componentDidCatch(error: unknown, info: ErrorInfo) {
|
|
89
|
-
|
|
117
|
+
try {
|
|
118
|
+
this.props.onError?.(toError(error), {
|
|
119
|
+
fatal: this.props.fatal ?? true,
|
|
120
|
+
source: this.props.source ?? "boundary",
|
|
121
|
+
componentStack: info.componentStack ?? undefined,
|
|
122
|
+
});
|
|
123
|
+
} catch {
|
|
124
|
+
// A failing reporter must not stop the fallback.
|
|
125
|
+
}
|
|
90
126
|
}
|
|
91
127
|
|
|
92
128
|
override componentDidUpdate(previous: GenesisErrorBoundaryProps) {
|
|
@@ -145,6 +181,7 @@ export function installGlobalErrorHandler({ errorUtils, onError, onFatal, alread
|
|
|
145
181
|
});
|
|
146
182
|
return () => {
|
|
147
183
|
// With no previous handler, leave one that only logs, never ours (it would call an unmounted app).
|
|
184
|
+
// genesis-allow-console: the last handler left once the shell is gone; nothing else is listening.
|
|
148
185
|
errorUtils.setGlobalHandler(previous ?? ((error) => console.error(error)));
|
|
149
186
|
};
|
|
150
187
|
}
|
|
@@ -174,8 +211,9 @@ export function defaultRejectionTracker(): EnableRejectionTracker | undefined {
|
|
|
174
211
|
}
|
|
175
212
|
|
|
176
213
|
/**
|
|
177
|
-
* Report unhandled promise rejections to `onError
|
|
178
|
-
*
|
|
214
|
+
* Report unhandled promise rejections to `onError`: non-fatal, and unhandled
|
|
215
|
+
* (`handled: false`), so release health counts them. This replaces React
|
|
216
|
+
* Native's own tracker, so each rejection is also written with
|
|
179
217
|
* `console.warn`, which LogBox shows in development as before.
|
|
180
218
|
*/
|
|
181
219
|
export function installRejectionTracker({ enable, onError }: { enable: EnableRejectionTracker; onError: OnError }): void {
|
|
@@ -183,9 +221,10 @@ export function installRejectionTracker({ enable, onError }: { enable: EnableRej
|
|
|
183
221
|
allRejections: true,
|
|
184
222
|
onUnhandled: (id, rejection) => {
|
|
185
223
|
const error = toError(rejection);
|
|
224
|
+
// genesis-allow-console: React Native's own tracker writes this warning; replacing it must too (LogBox).
|
|
186
225
|
console.warn(`Uncaught (in promise, id: ${id}): ${error.message}`);
|
|
187
226
|
try {
|
|
188
|
-
onError(error, { fatal: false, source: "rejection" });
|
|
227
|
+
onError(error, { fatal: false, handled: false, source: "rejection" });
|
|
189
228
|
} catch {
|
|
190
229
|
// A failing reporter must not throw inside the promise machinery.
|
|
191
230
|
}
|
package/src/index.ts
CHANGED
|
@@ -45,11 +45,35 @@ export {
|
|
|
45
45
|
type GenesisErrorBoundaryProps,
|
|
46
46
|
type GlobalErrorHandlerOptions,
|
|
47
47
|
type OnError,
|
|
48
|
+
errorDetails,
|
|
48
49
|
} from "./errors";
|
|
50
|
+
export {
|
|
51
|
+
ScreenErrorBoundary,
|
|
52
|
+
ScreenErrorScreen,
|
|
53
|
+
createScreenErrorBoundary,
|
|
54
|
+
type ScreenErrorBoundaryOptions,
|
|
55
|
+
type ScreenErrorBoundaryProps,
|
|
56
|
+
type ScreenErrorProps,
|
|
57
|
+
} from "./screen-boundary";
|
|
58
|
+
export { onBeforeReload, runBeforeReload, BEFORE_RELOAD_TIMEOUT_MS, type BeforeReloadHook } from "./reload";
|
|
59
|
+
// Re-exported for apps: what kind of error this is (for a toast), and the reporting seam.
|
|
60
|
+
export {
|
|
61
|
+
classifyError,
|
|
62
|
+
errorMessages,
|
|
63
|
+
reportError,
|
|
64
|
+
type ClassifiedError,
|
|
65
|
+
type ClassifyErrorOptions,
|
|
66
|
+
type ErrorKind,
|
|
67
|
+
type ErrorMessages,
|
|
68
|
+
} from "@marktiderman/genesis-core/errors";
|
|
49
69
|
export {
|
|
50
70
|
createNativeQueryClient,
|
|
51
71
|
connectQueryLifecycle,
|
|
52
72
|
DAY_MS,
|
|
73
|
+
reportQueryErrors,
|
|
74
|
+
queryKeyName,
|
|
75
|
+
type QueryErrorReporter,
|
|
76
|
+
type ReportQueryErrorsOptions,
|
|
53
77
|
type AppStateLike,
|
|
54
78
|
type AsyncStorageLike,
|
|
55
79
|
type NetInfoLike,
|
|
@@ -11,13 +11,27 @@
|
|
|
11
11
|
* and a `route.time_on_screen` timing for the route left. Route patterns
|
|
12
12
|
* (`/(app)/clients/[id]`) are used, never the values in them.
|
|
13
13
|
*
|
|
14
|
+
* Creating it also:
|
|
15
|
+
* - registers it as genesis-core's error reporter (`setErrorReporter`), so a
|
|
16
|
+
* package's `reportError(e, "chat:…")` reaches the sinks as a non-fatal error;
|
|
17
|
+
* - registers a before-reload hook (`onBeforeReload`) that flushes the sinks
|
|
18
|
+
* before an update reloads the app.
|
|
19
|
+
*
|
|
20
|
+
* `observability.screenBoundary()` is an Expo Router `ErrorBoundary` for a
|
|
21
|
+
* route (reported non-fatal, wrapped by Sentry's route wrapper), and
|
|
22
|
+
* `lastEventId()` / `replayId()` let a support or feedback screen point at
|
|
23
|
+
* the event.
|
|
24
|
+
*
|
|
14
25
|
* Everything a sink receives has been scrubbed (see `scrub.ts`), and the
|
|
15
26
|
* last breadcrumbs and errors are kept, scrubbed, for the devtools overlay
|
|
16
27
|
* (`recent`).
|
|
17
28
|
*/
|
|
18
29
|
import { createContext, useContext, useEffect, useRef, useSyncExternalStore, type ComponentType, type ReactNode } from "react";
|
|
19
30
|
import { defineBlock } from "@marktiderman/genesis-features/blocks";
|
|
31
|
+
import { setErrorReporter } from "@marktiderman/genesis-core/errors";
|
|
20
32
|
import { useSession } from "../auth";
|
|
33
|
+
import { onBeforeReload } from "../reload";
|
|
34
|
+
import { createScreenErrorBoundary, type ScreenErrorProps } from "../screen-boundary";
|
|
21
35
|
import type { NativeBlock, NativeBlockRootProps } from "../blocks";
|
|
22
36
|
import type { ErrorReport } from "../errors";
|
|
23
37
|
import { checkEvent, type EventProps, type EventSchema } from "./events";
|
|
@@ -60,6 +74,13 @@ export interface ObservabilityOptions<E extends EventSchema = EventSchema> {
|
|
|
60
74
|
recent?: { breadcrumbs?: number; errors?: number };
|
|
61
75
|
/** A sink threw, or `track` was called with something the schema doesn't allow. Default `console.warn` in development. */
|
|
62
76
|
onProblem?: (problem: string, error?: unknown) => void;
|
|
77
|
+
/**
|
|
78
|
+
* Become genesis-core's error reporter, so packages' `reportError` calls
|
|
79
|
+
* reach the sinks. Default true; the last block created wins.
|
|
80
|
+
*/
|
|
81
|
+
reportErrors?: boolean;
|
|
82
|
+
/** Flush the sinks before an update reloads the app, within this many milliseconds. Default 2000; 0 turns it off. */
|
|
83
|
+
flushBeforeReloadMs?: number;
|
|
63
84
|
now?: () => number;
|
|
64
85
|
}
|
|
65
86
|
|
|
@@ -78,6 +99,19 @@ export interface ObservabilityBlock<E extends EventSchema = EventSchema> extends
|
|
|
78
99
|
wrap<P extends Record<string, unknown>>(root: ComponentType<P>): ComponentType<P>;
|
|
79
100
|
/** The last breadcrumbs and errors, scrubbed, for the devtools overlay. */
|
|
80
101
|
readonly recent: RecentStore;
|
|
102
|
+
/** Send what every sink has queued; resolves false when one didn't finish within `timeoutMs` (default 2000). */
|
|
103
|
+
flush(timeoutMs?: number): Promise<boolean>;
|
|
104
|
+
/** The id of the last error event a sink sent (Sentry's), for a support request or feedback. */
|
|
105
|
+
lastEventId(): string | undefined;
|
|
106
|
+
/** The current session replay's id, when a sink records replays. */
|
|
107
|
+
replayId(): string | undefined;
|
|
108
|
+
/**
|
|
109
|
+
* An Expo Router `ErrorBoundary` for a route: reports the error non-fatal
|
|
110
|
+
* (source `screen`), shows `fallback` (default `ScreenErrorScreen`) with
|
|
111
|
+
* "Try again", and is wrapped by each sink's route wrapper (Sentry's
|
|
112
|
+
* `wrapExpoRouterErrorBoundary`). Build it once, at module scope.
|
|
113
|
+
*/
|
|
114
|
+
screenBoundary(fallback?: ComponentType<ScreenErrorProps>): ComponentType<ScreenErrorProps>;
|
|
81
115
|
/** For the shell: every error it catches. */
|
|
82
116
|
readonly onError: (error: Error, report: ErrorReport) => void;
|
|
83
117
|
readonly Root: ComponentType<NativeBlockRootProps>;
|
|
@@ -85,6 +119,8 @@ export interface ObservabilityBlock<E extends EventSchema = EventSchema> extends
|
|
|
85
119
|
|
|
86
120
|
declare const __DEV__: boolean | undefined;
|
|
87
121
|
|
|
122
|
+
let releaseReloadHook: (() => void) | undefined;
|
|
123
|
+
|
|
88
124
|
const TIMING_NAME = /^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/;
|
|
89
125
|
|
|
90
126
|
function createRecentStore(maxCrumbs: number, maxErrors: number): RecentStore & { addCrumb(c: Breadcrumb): void; addError(e: RecentError): void } {
|
|
@@ -124,6 +160,7 @@ export function createObservability<const E extends EventSchema = EventSchema>(o
|
|
|
124
160
|
const problem =
|
|
125
161
|
options.onProblem ??
|
|
126
162
|
((message: string, error?: unknown) => {
|
|
163
|
+
// genesis-allow-console: the block's own development warning; it can't report to itself.
|
|
127
164
|
if (typeof __DEV__ !== "undefined" && __DEV__) console.warn(`[observability] ${message}`, error ?? "");
|
|
128
165
|
});
|
|
129
166
|
const recent = createRecentStore(options.recent?.breadcrumbs ?? 50, options.recent?.errors ?? 20);
|
|
@@ -158,9 +195,16 @@ export function createObservability<const E extends EventSchema = EventSchema>(o
|
|
|
158
195
|
each("breadcrumb", (s) => s.breadcrumb?.(crumb));
|
|
159
196
|
};
|
|
160
197
|
|
|
161
|
-
const captureError = (value: unknown, context: Partial<ErrorContext> = {}) => {
|
|
198
|
+
const captureError = (value: unknown, context: Partial<ErrorContext> = {}, skip?: ReadonlySet<ObservabilitySink>) => {
|
|
162
199
|
const error = toError(value);
|
|
163
|
-
const full: ErrorContext = {
|
|
200
|
+
const full: ErrorContext = {
|
|
201
|
+
fatal: context.fatal ?? false,
|
|
202
|
+
source: context.source ?? "app",
|
|
203
|
+
route: context.route ?? route,
|
|
204
|
+
componentStack: context.componentStack,
|
|
205
|
+
...(context.handled !== undefined ? { handled: context.handled } : {}),
|
|
206
|
+
...(context.tags ? { tags: context.tags } : {}),
|
|
207
|
+
};
|
|
164
208
|
let safe: Error | undefined;
|
|
165
209
|
const scrubbed = () => (safe ??= scrubbedError(error));
|
|
166
210
|
try {
|
|
@@ -168,8 +212,54 @@ export function createObservability<const E extends EventSchema = EventSchema>(o
|
|
|
168
212
|
} catch {
|
|
169
213
|
// never let the overlay's list stop a report
|
|
170
214
|
}
|
|
171
|
-
|
|
172
|
-
|
|
215
|
+
let forSinks: ErrorContext = full;
|
|
216
|
+
try {
|
|
217
|
+
forSinks = {
|
|
218
|
+
...full,
|
|
219
|
+
...(full.componentStack ? { componentStack: scrubString(full.componentStack) } : {}),
|
|
220
|
+
...(full.tags ? { tags: scrubValue(full.tags) as Record<string, string> } : {}),
|
|
221
|
+
};
|
|
222
|
+
} catch {
|
|
223
|
+
// Tags that can't be scrubbed are dropped, never sent raw.
|
|
224
|
+
forSinks = { ...full, componentStack: undefined, tags: undefined };
|
|
225
|
+
}
|
|
226
|
+
each("captureError", (s) => {
|
|
227
|
+
if (skip?.has(s)) return;
|
|
228
|
+
s.captureError?.(s.scrubsErrors ? error : scrubbed(), s.scrubsErrors ? full : forSinks);
|
|
229
|
+
});
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
const flush = async (timeoutMs = 2000): Promise<boolean> => {
|
|
233
|
+
const results = sinks.map(async (sink) => {
|
|
234
|
+
if (!sink.flush) return true;
|
|
235
|
+
try {
|
|
236
|
+
return (await sink.flush(timeoutMs)) !== false;
|
|
237
|
+
} catch (error) {
|
|
238
|
+
problem(`${sink.name}.flush threw`, error);
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
243
|
+
const deadline = new Promise<boolean>((resolve) => {
|
|
244
|
+
timer = setTimeout(() => resolve(false), timeoutMs);
|
|
245
|
+
});
|
|
246
|
+
try {
|
|
247
|
+
return await Promise.race([Promise.all(results).then((all) => all.every(Boolean)), deadline]);
|
|
248
|
+
} finally {
|
|
249
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
const firstOf = (read: (sink: ObservabilitySink) => string | undefined): string | undefined => {
|
|
254
|
+
for (const sink of sinks) {
|
|
255
|
+
try {
|
|
256
|
+
const value = read(sink);
|
|
257
|
+
if (value) return value;
|
|
258
|
+
} catch (error) {
|
|
259
|
+
problem(`${sink.name} threw reading an id`, error);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
return undefined;
|
|
173
263
|
};
|
|
174
264
|
|
|
175
265
|
const setUser = (id: string | null) => {
|
|
@@ -263,7 +353,35 @@ export function createObservability<const E extends EventSchema = EventSchema>(o
|
|
|
263
353
|
wrap(root) {
|
|
264
354
|
return sinks.reduce((wrapped, sink) => (sink.wrap ? sink.wrap(wrapped) : wrapped), root);
|
|
265
355
|
},
|
|
266
|
-
onError: (error, report) =>
|
|
356
|
+
onError: (error, report) =>
|
|
357
|
+
captureError(error, {
|
|
358
|
+
fatal: report.fatal,
|
|
359
|
+
source: report.source,
|
|
360
|
+
componentStack: report.componentStack,
|
|
361
|
+
...(report.handled !== undefined ? { handled: report.handled } : {}),
|
|
362
|
+
...(report.tags ? { tags: report.tags } : {}),
|
|
363
|
+
}),
|
|
364
|
+
flush,
|
|
365
|
+
lastEventId: () => firstOf((s) => s.lastEventId?.()),
|
|
366
|
+
replayId: () => firstOf((s) => s.replayId?.()),
|
|
367
|
+
screenBoundary(fallback) {
|
|
368
|
+
const wrapping = sinks.filter((s) => s.wrapRouteErrorBoundary);
|
|
369
|
+
// A sink whose wrapper reports the route's error (Sentry's) isn't sent it a second time.
|
|
370
|
+
const skip = new Set(wrapping);
|
|
371
|
+
return createScreenErrorBoundary({
|
|
372
|
+
fallback,
|
|
373
|
+
onError: (error, report) => captureError(error, { fatal: report.fatal, source: report.source }, skip),
|
|
374
|
+
wrap: wrapping.map((sink) => (boundary: ComponentType<ScreenErrorProps>) => {
|
|
375
|
+
try {
|
|
376
|
+
return sink.wrapRouteErrorBoundary!(boundary);
|
|
377
|
+
} catch (error) {
|
|
378
|
+
problem(`${sink.name}.wrapRouteErrorBoundary threw`, error);
|
|
379
|
+
skip.delete(sink);
|
|
380
|
+
return boundary;
|
|
381
|
+
}
|
|
382
|
+
}),
|
|
383
|
+
});
|
|
384
|
+
},
|
|
267
385
|
Root: function ObservabilityRoot({ children }: NativeBlockRootProps) {
|
|
268
386
|
return (
|
|
269
387
|
<ObservabilityContext.Provider value={block as ObservabilityBlock}>
|
|
@@ -274,6 +392,15 @@ export function createObservability<const E extends EventSchema = EventSchema>(o
|
|
|
274
392
|
);
|
|
275
393
|
},
|
|
276
394
|
};
|
|
395
|
+
if (options.reportErrors !== false) {
|
|
396
|
+
setErrorReporter((value, context) =>
|
|
397
|
+
captureError(value, { fatal: context.fatal ?? false, source: context.source, ...(context.tags ? { tags: context.tags } : {}) }),
|
|
398
|
+
);
|
|
399
|
+
}
|
|
400
|
+
const flushMs = options.flushBeforeReloadMs ?? 2000;
|
|
401
|
+
// The newest block replaces the last one's hook (Fast Refresh builds the block again).
|
|
402
|
+
releaseReloadHook?.();
|
|
403
|
+
releaseReloadHook = flushMs > 0 && sinks.some((s) => s.flush) ? onBeforeReload(() => flush(flushMs)) : undefined;
|
|
277
404
|
return block;
|
|
278
405
|
}
|
|
279
406
|
|
|
@@ -37,8 +37,10 @@ export {
|
|
|
37
37
|
type ObservabilitySink,
|
|
38
38
|
type ObserveLike,
|
|
39
39
|
type ObserveSinkOptions,
|
|
40
|
+
type RouteErrorBoundaryProps,
|
|
40
41
|
type TimingTags,
|
|
41
42
|
} from "./sink";
|
|
42
43
|
export { sentrySink, sentryRelease, signatureTags, type SentryLike, type SentrySinkOptions } from "./sentry";
|
|
43
44
|
export { defineEvents, checkEvent, type EventCheck, type EventPropSpec, type EventProps, type EventSchema, type EventValues } from "./events";
|
|
45
|
+
export { ScreenErrorScreen, createScreenErrorBoundary, type ScreenErrorProps } from "../screen-boundary";
|
|
44
46
|
export { FILTERED, isSecretKey, scrubEvent, scrubRecord, scrubString, scrubUrl, scrubValue, type ScrubbableEvent } from "./scrub";
|