react-native-minimal-webview 1.0.1 → 1.2.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 (78) hide show
  1. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +19 -32
  2. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +55 -26
  3. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +3 -3
  4. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +2 -1
  5. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +8 -8
  6. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +5 -7
  7. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +32 -44
  8. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +2 -2
  9. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +7 -8
  10. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +2 -2
  11. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +4 -5
  12. package/build/WebView.d.ts +1 -9
  13. package/build/WebView.d.ts.map +1 -1
  14. package/build/WebView.js +37 -107
  15. package/build/WebView.js.map +1 -1
  16. package/build/bridge/createBridge.d.ts +19 -13
  17. package/build/bridge/createBridge.d.ts.map +1 -1
  18. package/build/bridge/createBridge.js +33 -45
  19. package/build/bridge/createBridge.js.map +1 -1
  20. package/build/bridge/endpoint.d.ts +3 -8
  21. package/build/bridge/endpoint.d.ts.map +1 -1
  22. package/build/bridge/endpoint.js +2 -3
  23. package/build/bridge/endpoint.js.map +1 -1
  24. package/build/bridge/origins.d.ts +5 -2
  25. package/build/bridge/origins.d.ts.map +1 -1
  26. package/build/bridge/origins.js +15 -4
  27. package/build/bridge/origins.js.map +1 -1
  28. package/build/bridge/pageClient.generated.d.ts +1 -1
  29. package/build/bridge/pageClient.generated.d.ts.map +1 -1
  30. package/build/bridge/pageClient.generated.js +1 -1
  31. package/build/bridge/pageClient.generated.js.map +1 -1
  32. package/build/index.d.ts +1 -1
  33. package/build/index.d.ts.map +1 -1
  34. package/build/index.js +1 -1
  35. package/build/index.js.map +1 -1
  36. package/build/{defaultNavigationRules.d.ts → navigationRules.d.ts} +10 -1
  37. package/build/navigationRules.d.ts.map +1 -0
  38. package/build/navigationRules.js +93 -0
  39. package/build/navigationRules.js.map +1 -0
  40. package/build/refStore.d.ts.map +1 -1
  41. package/build/refStore.js +13 -19
  42. package/build/refStore.js.map +1 -1
  43. package/build/types.d.ts +55 -35
  44. package/build/types.d.ts.map +1 -1
  45. package/ios/DelegateProxy.swift +32 -30
  46. package/ios/DocumentEnd.swift +1 -2
  47. package/ios/Hooks.swift +28 -28
  48. package/ios/Loads.swift +5 -4
  49. package/ios/MRWInvoke.h +10 -9
  50. package/ios/MRWInvoke.m +39 -24
  51. package/ios/MinimalWebView+Navigation.swift +18 -16
  52. package/ios/MinimalWebView+Scripts.swift +0 -8
  53. package/ios/MinimalWebView.podspec +0 -1
  54. package/ios/MinimalWebView.swift +77 -35
  55. package/ios/MinimalWebViewModule.swift +1 -0
  56. package/ios/NavigationRules.swift +15 -15
  57. package/ios/OriginRules.swift +6 -0
  58. package/ios/PlatformSettings.swift +3 -22
  59. package/ios/Recovery.swift +6 -5
  60. package/ios/SharedCookies.swift +1 -2
  61. package/package.json +7 -3
  62. package/src/WebView.tsx +50 -123
  63. package/src/bridge/createBridge.ts +48 -56
  64. package/src/bridge/endpoint.ts +6 -9
  65. package/src/bridge/origins.ts +18 -6
  66. package/src/bridge/pageClient.generated.ts +1 -1
  67. package/src/bridge/pageClient.ts +3 -7
  68. package/src/bridge/protocol.ts +1 -1
  69. package/src/index.ts +1 -1
  70. package/src/navigationRules.ts +111 -0
  71. package/src/refStore.ts +15 -21
  72. package/src/types.ts +56 -35
  73. package/build/defaultNavigationRules.d.ts.map +0 -1
  74. package/build/defaultNavigationRules.js +0 -22
  75. package/build/defaultNavigationRules.js.map +0 -1
  76. package/ios/MRWExceptions.h +0 -9
  77. package/ios/MRWExceptions.m +0 -10
  78. package/src/defaultNavigationRules.ts +0 -24
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-minimal-webview",
3
- "version": "1.0.1",
3
+ "version": "1.2.0",
4
4
  "description": "A React Native WebView that hands you the iOS and Android WebView APIs, instead of wrapping each one in a prop",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",
@@ -30,7 +30,7 @@
30
30
  "test": "jest",
31
31
  "lint": "eslint --max-warnings 0 src extensions example .github && prettier --check .",
32
32
  "prepare": "npm run clean && npm run build",
33
- "check": "npm test && npm run lint && knip --config .config/knip.json && tsc --noEmit -p src/__tests__/tsconfig.json && tsc --noEmit -p extensions/src/__tests__/tsconfig.json && (cd example && npx tsc --noEmit) && node .github/scripts/check-doc-samples.mts && npm run prepare && npm run docs:check",
33
+ "check": "npm test && npm run lint && knip --config .config/knip.json && tsc --noEmit -p src/__tests__/tsconfig.json && tsc --noEmit -p extensions/src/__tests__/tsconfig.json && (cd example && npx tsc --noEmit) && node .github/scripts/check-doc-samples.mts && npm run prepare && npm run docs:check && tsc --noEmit -p .github/scripts && tsc --noEmit -p example/maestro/scripts",
34
34
  "mutation": "stryker run .config/stryker.config.json",
35
35
  "build:page-client": "node .github/scripts/build-page-client.mts",
36
36
  "gen:platform-types": "node .github/scripts/gen-platform-types.mts",
@@ -46,7 +46,6 @@
46
46
  "android-webview",
47
47
  "ios",
48
48
  "android",
49
- "react-native-minimal-webview",
50
49
  "MinimalWebView"
51
50
  ],
52
51
  "repository": "https://github.com/RasmusKard/react-native-minimal-webview",
@@ -84,9 +83,14 @@
84
83
  },
85
84
  "jest": {
86
85
  "preset": "jest-expo",
86
+ "clearMocks": true,
87
+ "restoreMocks": true,
87
88
  "roots": [
88
89
  "<rootDir>/src",
89
90
  "<rootDir>/extensions/src"
91
+ ],
92
+ "testMatch": [
93
+ "**/*.test.{ts,tsx}"
90
94
  ]
91
95
  },
92
96
  "peerDependencies": {
package/src/WebView.tsx CHANGED
@@ -2,9 +2,10 @@ import { requireNativeModule, requireNativeView } from 'expo';
2
2
  import { type Ref, useEffect, useMemo, useRef, useState } from 'react';
3
3
  import { AppState, Platform, type ViewProps } from 'react-native';
4
4
 
5
- import { CONNECTION, originGuard } from './bridge/createBridge';
5
+ import { type BridgeEvent, CONNECTION } from './bridge/createBridge';
6
6
  import { codedError } from './bridge/endpoint';
7
- import { defaultNavigationRules } from './defaultNavigationRules';
7
+ import { originGuard } from './bridge/origins';
8
+ import { checkNavigationRules, defaultNavigationRules } from './navigationRules';
8
9
  import { REACT_NATIVE_WEBVIEW_DEFAULTS } from './reactNativeWebViewDefaults';
9
10
  import { useAttach } from './refStore';
10
11
  import type {
@@ -12,7 +13,6 @@ import type {
12
13
  InjectedScript,
13
14
  LoadErrorEvent,
14
15
  NavigationEvent,
15
- NavigationRule,
16
16
  NavigationState,
17
17
  ProcessGoneEvent,
18
18
  SettingValue,
@@ -22,16 +22,11 @@ import type {
22
22
  import { DEFAULTS } from './types.defaults';
23
23
 
24
24
  type Native<T> = { nativeEvent: T };
25
- /** The native view's event props, by name and payload. */
26
25
  type NativeHandlers<E> = { [K in keyof E]: (event: Native<E[K]>) => void };
27
26
 
28
27
  /** The event without the `target` (the view's tag) React Native adds to every native event. */
29
28
  const own = <T,>({ target: _, ...event }: T & { target?: unknown }) => event as T;
30
29
 
31
- /** A page's message comes with its origin, as native verified it (`location.origin` form). */
32
- export type BridgeEvent =
33
- { message: string; origin: string } | { navigated: true } | { unavailable: true };
34
-
35
30
  /**
36
31
  * An event as native sends it: `key` is the hook's key, `core` for the core's own. `askId` is set when native waits for
37
32
  * the answer.
@@ -90,7 +85,6 @@ type NativeProps = ViewProps &
90
85
  /** With each script's `origins` in its code (`nativeScripts`). */
91
86
  injectedScripts: Omit<InjectedScript, 'origins'>[] | undefined;
92
87
  ref: Ref<NativeMethods>;
93
- /** iOS only: Android's CookieManager is already shared. */
94
88
  sharedCookies: boolean | undefined;
95
89
  /**
96
90
  * The platform's settings by root and name, as JSON: `ios` or `android` with the cross-platform props on top. A
@@ -113,6 +107,7 @@ type NativeProps = ViewProps &
113
107
  export type NativeMethods = {
114
108
  goBack(): Promise<void>;
115
109
  goForward(): Promise<void>;
110
+ load(url: string): Promise<void>;
116
111
  reload(): Promise<void>;
117
112
  stopLoading(): Promise<void>;
118
113
  bridgePost(message: string): Promise<void>;
@@ -151,6 +146,12 @@ const unawaited = (call: Promise<unknown> | undefined, name: string) =>
151
146
  console.error(`[react-native-minimal-webview] ${name} failed`, error);
152
147
  });
153
148
 
149
+ /**
150
+ * Whether `url` is a `javascript:` URL as a URL parser reads it (leading controls and spaces skipped, tabs and newlines
151
+ * dropped): Android's loadUrl would run its script.
152
+ */
153
+ const isJavaScriptUrl = (url: string) => /^[\0- ]*javascript:/i.test(url.replace(/[\t\n\r]/g, ''));
154
+
154
155
  /**
155
156
  * A WebView whose core decides navigations and owns the navigation state: see {@link WebViewProps} and
156
157
  * {@link WebViewRef}.
@@ -161,10 +162,6 @@ export function WebView(props: WebViewProps) {
161
162
  return <WebViewInstance key={creationKey(props)} {...props} />;
162
163
  }
163
164
 
164
- /**
165
- * Warns in development, once per WebView, when another bridge replaces its bridge, which recreated it: a bridge made
166
- * in render (`bridge={createBridge(…)}`) would reload the page at every render.
167
- */
168
165
  function useBridgeChangeWarning(bridge: WebViewProps['bridge']) {
169
166
  const last = useRef(bridge);
170
167
  const warned = useRef(false);
@@ -196,8 +193,6 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
196
193
  [inFlight]
197
194
  );
198
195
 
199
- // A handle can outlive its native view (one captured before an unmount): navigation is then a no-op, and what
200
- // answers rejects with `unavailable`.
201
196
  const [handle] = useState((): WebViewRef => {
202
197
  const gone = (): never => {
203
198
  throw codedError({ code: 'unavailable', message: 'the WebView is gone' });
@@ -231,6 +226,24 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
231
226
  return {
232
227
  goBack: () => unawaited(native.current?.goBack(), 'goBack'),
233
228
  goForward: () => unawaited(native.current?.goForward(), 'goForward'),
229
+ load: (url) => {
230
+ if (isJavaScriptUrl(url)) {
231
+ if (__DEV__)
232
+ console.warn(
233
+ '[react-native-minimal-webview] load: a javascript: URL loads nothing; run a script with evaluate'
234
+ );
235
+ return;
236
+ }
237
+ // mounted() parses a JSON result, and load has none. A view that went away or never came loads nothing, as
238
+ // a navigation method does after an unmount.
239
+ unawaited(
240
+ mounted(() => native.current?.load(url).then(() => 'null')).catch((error: unknown) => {
241
+ const code = (error as { code?: string } | null)?.code;
242
+ if (code !== 'unavailable' && code !== 'navigated') throw error;
243
+ }),
244
+ 'load'
245
+ );
246
+ },
234
247
  reload: () => unawaited(native.current?.reload(), 'reload'),
235
248
  stopLoading: () => unawaited(native.current?.stopLoading(), 'stopLoading'),
236
249
  evaluate: (script) => mounted(() => native.current?.evaluate(script)),
@@ -243,7 +256,6 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
243
256
  });
244
257
  const publish = useAttach(ref, handle);
245
258
 
246
- // onLoadStart and onLoadEnd are the edges of `loading`; native sets the ended load's `outcome`.
247
259
  const onNavigationState = ({ nativeEvent }: Native<NavigationState>) => {
248
260
  const state = own(nativeEvent);
249
261
  const was = publish(state);
@@ -265,12 +277,6 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
265
277
  return () => connection.detach();
266
278
  }, [connection]);
267
279
 
268
- const onBridge = ({ nativeEvent }: Native<BridgeEvent>) => {
269
- if ('message' in nativeEvent) connection?.receive(nativeEvent.message, nativeEvent.origin);
270
- else if ('navigated' in nativeEvent) connection?.navigated();
271
- else connection?.markUnavailable();
272
- };
273
-
274
280
  const requestHandlers = useRequestHandlers(props);
275
281
  const hookOptions = useHookOptions(props.extensions);
276
282
  const navigationRules = useNavigationRules(props.navigationRules);
@@ -279,20 +285,14 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
279
285
  const [asks] = useState(() => new Map<number, AbortController>());
280
286
  useEffect(() => () => asks.forEach((controller) => controller.abort()), [asks]);
281
287
 
282
- // The core's own events: a warning for the developer, and an ask native stopped waiting for.
283
- const onCoreEvent = (name: string, payload: Record<string, unknown>) => {
284
- if (name === 'warning')
285
- console.warn(`[react-native-minimal-webview] ${String(payload['message'])}`);
286
- else if (name === 'askCancelled') asks.get(payload['askId'] as number)?.abort();
287
- else return false;
288
- return true;
289
- };
290
-
291
288
  const onHookEvent = async ({
292
289
  nativeEvent: { key, name, payload, askId },
293
290
  }: Native<AskableEvent>) => {
294
291
  const core = key === 'core';
295
- if (core && onCoreEvent(name, payload)) return;
292
+ // The core's own events: a warning for the developer, and an ask native stopped waiting for.
293
+ if (core && name === 'warning')
294
+ return console.warn(`[react-native-minimal-webview] ${String(payload['message'])}`);
295
+ if (core && name === 'askCancelled') return asks.get(payload['askId'] as number)?.abort();
296
296
  const request = REQUESTS.find((prop) => core && prop === name);
297
297
  // The later of two extensions with one key, as in useHookOptions. No hook is registered under `core`.
298
298
  const owner = props.extensions?.findLast((e): e is HookExtension => !!e && e.key === key);
@@ -335,7 +335,7 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
335
335
  requestHandlers={requestHandlers}
336
336
  onNavigation={({ nativeEvent }) => props.onNavigation?.(own(nativeEvent))}
337
337
  onNavigationState={onNavigationState}
338
- onBridge={onBridge}
338
+ onBridge={({ nativeEvent }) => connection?.receive(nativeEvent)}
339
339
  onHookEvent={onHookEvent}
340
340
  onError={({ nativeEvent }) => props.onError?.(own(nativeEvent))}
341
341
  onProcessGone={({ nativeEvent }) => props.onProcessGone?.(own(nativeEvent))}
@@ -365,97 +365,27 @@ function nativeScripts(scripts: InjectedScript[] | undefined) {
365
365
  });
366
366
  }
367
367
 
368
- /** Each rule field's kind, from its type, so that a field missing here, or not in the type, fails to compile. */
369
- const RULE_FIELDS = new Map(
370
- Object.entries({
371
- scheme: 'list',
372
- host: 'list',
373
- path: 'list',
374
- query: 'list',
375
- mainFrame: 'flag',
376
- newWindow: 'flag',
377
- userInitiated: 'flag',
378
- action: 'action',
379
- } satisfies {
380
- [K in keyof NavigationRule]-?: NonNullable<NavigationRule[K]> extends readonly string[]
381
- ? 'list'
382
- : NonNullable<NavigationRule[K]> extends boolean
383
- ? 'flag'
384
- : 'action';
385
- })
386
- );
387
- const ACTIONS: unknown[] = Object.keys({
388
- allow: 0,
389
- block: 0,
390
- external: 0,
391
- ask: 0,
392
- } satisfies Record<NavigationRule['action'], 0>);
393
-
394
- /** A value as a warning shows it. */
395
- const shown = (value: unknown) => {
396
- try {
397
- return JSON.stringify(value) ?? String(value);
398
- } catch {
399
- // A BigInt, a circular value or a throwing toJSON: the message runs in production too, so it must not throw.
400
- return typeof value === 'bigint' ? String(value) : Object.prototype.toString.call(value);
401
- }
402
- };
403
-
404
- /** What a field of each kind takes, as a warning says it, and the check. */
405
- const FIELD_KINDS = {
406
- list: {
407
- takes: 'an array of strings',
408
- ok: (value: unknown) =>
409
- Array.isArray(value) && value.every((entry) => typeof entry === 'string'),
410
- },
411
- flag: { takes: 'true or false', ok: (value: unknown) => typeof value === 'boolean' },
412
- action: { takes: `one of ${shown(ACTIONS)}`, ok: (value: unknown) => ACTIONS.includes(value) },
413
- };
414
-
415
- function ruleProblem(rule: unknown) {
416
- if (typeof rule !== 'object' || rule === null) return `must be an object, not ${shown(rule)}`;
417
- // A missing action is checked as an undefined one; any other field may be undefined (unset).
418
- for (const [key, value] of Object.entries({ action: undefined, ...rule })) {
419
- const kind = RULE_FIELDS.get(key);
420
- if (!kind) return `unknown key ${shown(key)}`;
421
- if ((value !== undefined || kind === 'action') && !FIELD_KINDS[kind].ok(value))
422
- return `${key} must be ${FIELD_KINDS[kind].takes}, not ${shown(value)}`;
423
- }
424
- return undefined;
425
- }
426
-
427
368
  /**
428
- * The rules as the core gets them. The core skips an unknown key and a non-boolean flag, which would widen a rule
429
- * (`hosts` would match every host), so a malformed rule becomes a `block` one. The same array when none is malformed.
369
+ * The rules as the core gets them (`checkNavigationRules`), and a development warning for each malformed one. The same
370
+ * array when none is malformed.
430
371
  */
431
372
  function useNavigationRules(rules: WebViewProps['navigationRules']) {
432
- const given: unknown = rules ?? defaultNavigationRules;
433
- const { checked, warnings } = useMemo(() => {
434
- if (!Array.isArray(given))
435
- return {
436
- checked: [],
437
- warnings: [`navigationRules: must be an array, not ${shown(given)}; treated as []`],
438
- };
439
- // Array.from, not map: map skips a sparse array's holes, which would reach native unchecked.
440
- const problems = Array.from(given, ruleProblem);
441
- return {
442
- checked: problems.some(Boolean)
443
- ? Array.from(given, (rule: unknown, i) => (problems[i] ? { action: 'block' } : rule))
444
- : given,
445
- warnings: problems.flatMap((problem, i) =>
446
- problem
447
- ? [`navigationRules[${i}]: ${problem}; it blocks every navigation that reaches it`]
448
- : []
449
- ),
450
- };
451
- }, [given]);
373
+ const { checked, warnings } = useMemo(
374
+ () => checkNavigationRules(rules ?? defaultNavigationRules),
375
+ [rules]
376
+ );
377
+ useDevWarnings(warnings);
378
+ return checked;
379
+ }
380
+
381
+ /** Logs each warning in development, again only when the list changes. */
382
+ function useDevWarnings(warnings: string[]) {
452
383
  const json = JSON.stringify(warnings);
453
384
  useEffect(() => {
454
385
  if (!__DEV__) return;
455
386
  for (const warning of JSON.parse(json) as string[])
456
387
  console.warn(`[react-native-minimal-webview] ${warning}`);
457
388
  }, [json]);
458
- return checked as NavigationRule[];
459
389
  }
460
390
 
461
391
  /** The `REQUESTS` with a prop set, as a new array only when that set changes. */
@@ -472,14 +402,11 @@ function useRequestHandlers(props: WebViewProps) {
472
402
  function useHookOptions(extensions: WebViewProps['extensions']) {
473
403
  const on = (extensions ?? []).filter((extension) => !!extension);
474
404
  const keys = on.map(({ key }) => key);
475
- const repeated = JSON.stringify([...new Set(keys.filter((key, i) => keys.indexOf(key) !== i))]);
476
- useEffect(() => {
477
- if (!__DEV__) return;
478
- for (const key of JSON.parse(repeated) as string[])
479
- console.warn(
480
- `[react-native-minimal-webview] extensions: two extensions have the key ${key}; the later one wins`
481
- );
482
- }, [repeated]);
405
+ useDevWarnings(
406
+ [...new Set(keys.filter((key, i) => keys.indexOf(key) !== i))].map(
407
+ (key) => `extensions: two extensions have the key ${key}; the later one wins`
408
+ )
409
+ );
483
410
  const json = JSON.stringify(
484
411
  withoutOff(
485
412
  Object.fromEntries(
@@ -1,10 +1,22 @@
1
- import type { Bridge, BridgeOptions, BridgeSchema, BridgeSender } from '../types';
1
+ import type { Bridge, BridgeOptions, BridgeSchema, BridgeSender, SchemaOf } from '../types';
2
2
  import { DEFAULTS } from '../types.defaults';
3
3
  import { codedError, createEndpoint } from './endpoint';
4
- import { invalidOrigins, originForms } from './origins';
5
- import { MATCHES_ORIGIN, PAGE_CLIENT } from './pageClient.generated';
4
+ import { originGuard } from './origins';
5
+ import { PAGE_CLIENT } from './pageClient.generated';
6
6
  import { type BridgeMessage, parseBridgeMessage } from './protocol';
7
7
 
8
+ /**
9
+ * What native reports to the bridge: a page's message with its origin as native verified it (`location.origin` form);
10
+ * a new document committed, so messages queue until its page client says `ready`; the renderer crashed, so no document
11
+ * is shown until the next commit; or the platform lacks the WebView features the bridge needs, so calls reject with
12
+ * `unavailable`.
13
+ */
14
+ export type BridgeEvent =
15
+ | { message: string; origin: string }
16
+ | { navigated: true }
17
+ | { crashed: true }
18
+ | { unavailable: true };
19
+
8
20
  /** What `<WebView>` needs from a bridge: `Bridge`'s `[CONNECTION]`, a key the package doesn't export. */
9
21
  export type BridgeConnection = {
10
22
  allowedOrigins: string[];
@@ -12,31 +24,11 @@ export type BridgeConnection = {
12
24
  script: string;
13
25
  attach(post: (message: string) => void): void;
14
26
  detach(): void;
15
- /** A message from the page, and its origin as native verified it. */
16
- receive(message: string, origin: string): void;
17
- /** The platform lacks the WebView features the bridge needs: calls reject with `unavailable`. */
18
- markUnavailable(): void;
19
- /** A new document committed: queue messages until its page client says `ready`. */
20
- navigated(): void;
27
+ receive(event: BridgeEvent): void;
21
28
  };
22
29
 
23
30
  export const CONNECTION = Symbol('bridgeConnection');
24
31
 
25
- /**
26
- * A page-side expression true where `location.origin` matches `origins`, or null when they include `*`. Throws an
27
- * `Error` starting with `what` for a rule that is neither `*` nor what `parseOrigin` takes.
28
- */
29
- export function originGuard(what: string, origins: string[]): string | null {
30
- const invalid = invalidOrigins(origins);
31
- if (invalid.length) {
32
- throw new Error(
33
- `${what} ${JSON.stringify(invalid)} (use https://example.com or https://*.example.com, no path)`
34
- );
35
- }
36
- const forms = originForms(origins);
37
- return forms.any ? null : `(${MATCHES_ORIGIN})(${JSON.stringify(forms)}, location.origin)`;
38
- }
39
-
40
32
  const MAX_QUEUE = 1000;
41
33
 
42
34
  /**
@@ -48,10 +40,10 @@ const MAX_QUEUE = 1000;
48
40
  * @see [Bridge example](https://rasmuskard.github.io/react-native-minimal-webview/guides/examples/#the-bridge)
49
41
  * @group Bridge
50
42
  */
51
- export function createBridge<Schema extends BridgeSchema = BridgeSchema>(
43
+ export function createBridge<Schema extends SchemaOf<Schema> = BridgeSchema>(
52
44
  options: BridgeOptions
53
45
  ): Bridge<Schema> {
54
- // `*` or what origins.ts parses: addWebMessageListener's rules minus custom schemes.
46
+ // The rule syntax is addWebMessageListener's, minus custom schemes.
55
47
  const guard = originGuard('createBridge: invalid allowedOrigins', options.allowedOrigins);
56
48
  const timeoutMs = options.timeoutMs ?? DEFAULTS.BridgeOptions.timeoutMs;
57
49
  if (!(timeoutMs >= 0)) {
@@ -60,21 +52,15 @@ export function createBridge<Schema extends BridgeSchema = BridgeSchema>(
60
52
  );
61
53
  }
62
54
  let post: ((message: string) => void) | null = null;
63
- // idle: no document committed since attach. loading: one committed and hasn't said `ready` yet.
55
+ // idle: no document shown (none committed since attach, or it crashed). loading: one committed and hasn't said `ready` yet.
64
56
  let phase: 'idle' | 'loading' | 'ready' = 'idle';
65
57
  // The token of the document that last said `ready` (protocol.ts `doc`).
66
58
  let doc: string | undefined;
67
- // Messages for the next document that says `ready`. Only the latest document's: see navigated().
59
+ // Messages for the next document that says `ready`. Only the latest document's: see `receive`.
68
60
  let queue: BridgeMessage[] = [];
69
61
  let unavailable = false;
70
62
 
71
- const deliver = (message: BridgeMessage) => {
72
- post?.(JSON.stringify({ ...message, doc }));
73
- if (message.kind === 'call') {
74
- const call = endpoint.pending.get(message.id);
75
- if (call) call.sent = true;
76
- }
77
- };
63
+ const deliver = (message: BridgeMessage) => post?.(JSON.stringify({ ...message, doc }));
78
64
 
79
65
  const endpoint = createEndpoint<BridgeSender>(
80
66
  (message) => {
@@ -84,26 +70,29 @@ export function createBridge<Schema extends BridgeSchema = BridgeSchema>(
84
70
  JSON.stringify(message);
85
71
  queue.push(message);
86
72
  const dropped = queue.length > MAX_QUEUE ? queue.shift() : undefined;
87
- if (dropped?.kind === 'call') {
88
- const call = endpoint.pending.get(dropped.id);
73
+ if (dropped?.kind === 'call')
89
74
  endpoint.rejectPending(
90
75
  'unavailable',
91
76
  'the bridge queue was full',
92
- (pending) => pending === call
77
+ (id) => id === dropped.id
93
78
  );
94
- }
95
79
  }
96
80
  },
97
81
  timeoutMs,
98
82
  'n'
99
83
  );
100
84
 
101
- const rejectSent = (message: string) =>
102
- endpoint.rejectPending('navigated', message, (call) => call.sent);
85
+ // A pending call not in the queue was posted to a document.
86
+ const rejectSent = (message: string) => {
87
+ const queued = new Set(
88
+ queue.map((queuedMessage) => queuedMessage.kind === 'call' && queuedMessage.id)
89
+ );
90
+ endpoint.rejectPending('navigated', message, (id) => !queued.has(id));
91
+ };
103
92
  const unavailableMessage =
104
93
  'this WebView lacks the features the bridge needs; update Android System WebView';
105
94
 
106
- const receive = (text: string, origin: string) => {
95
+ const receiveMessage = (text: string, origin: string) => {
107
96
  const message = parseBridgeMessage(text);
108
97
  if (typeof message === 'string') {
109
98
  if (__DEV__)
@@ -143,24 +132,27 @@ export function createBridge<Schema extends BridgeSchema = BridgeSchema>(
143
132
  detach() {
144
133
  post = null;
145
134
  phase = 'idle';
135
+ rejectSent('the WebView went away');
146
136
  queue = [];
147
- endpoint.rejectPending('navigated', 'the WebView went away');
137
+ endpoint.rejectPending('unavailable', 'the WebView went away');
148
138
  },
149
- receive,
150
- navigated() {
151
- rejectSent('the page navigated');
152
- // The previous document never said `ready` (a page outside allowedOrigins): what was queued for it does not
153
- // carry over to an unrelated next one.
154
- if (phase === 'loading') {
155
- endpoint.rejectPending('navigated', 'the page navigated before the bridge was ready');
139
+ receive(event) {
140
+ if ('message' in event) receiveMessage(event.message, event.origin);
141
+ else if ('unavailable' in event) {
142
+ unavailable = true;
156
143
  queue = [];
144
+ endpoint.rejectPending('unavailable', unavailableMessage);
145
+ } else {
146
+ rejectSent('the page navigated');
147
+ // The previous document never said `ready` (a page outside allowedOrigins): what was queued for it does not
148
+ // carry over to an unrelated next one.
149
+ if (phase === 'loading') {
150
+ endpoint.rejectPending('unavailable', 'the page navigated before the bridge was ready');
151
+ queue = [];
152
+ }
153
+ // What is queued after a crash is for the reload.
154
+ phase = 'crashed' in event ? 'idle' : 'loading';
157
155
  }
158
- phase = 'loading';
159
- },
160
- markUnavailable() {
161
- unavailable = true;
162
- queue = [];
163
- endpoint.rejectPending('unavailable', unavailableMessage);
164
156
  },
165
157
  };
166
158
 
@@ -1,19 +1,16 @@
1
1
  // One side of the bridge, the same in RN (createBridge.ts) and in the page (pageClient.ts): calls with timeouts,
2
2
  // handlers and events. The transport, the `ready` handshake and the document tokens are each side's own. The page
3
- // client is compiled with this file into one script (.github/scripts/build-page-client.mts), so it imports only types.
4
- import type { ErrorCode } from '../types';
3
+ // client is compiled with this file into one script (.github/scripts/build-page-client.mts).
4
+ import type { CodedError, ErrorCode } from '../types';
5
5
  import type { BridgeErrorCode, BridgeMessage } from './protocol';
6
6
 
7
7
  type Pending = {
8
8
  resolve(value: unknown): void;
9
9
  reject(error: Error): void;
10
10
  timer: ReturnType<typeof setTimeout> | undefined;
11
- /** Posted to a document, not just queued for the next one (RN). */
12
- sent: boolean;
13
11
  };
14
12
 
15
- /** A `CodedError` (types.ts): what a ref method or bridge call rejects with. */
16
- export const codedError = ({ code, message }: { code: ErrorCode; message: string }) =>
13
+ export const codedError = ({ code, message }: { code: ErrorCode; message: string }): CodedError =>
17
14
  Object.assign(new Error(message), { code });
18
15
 
19
16
  /**
@@ -51,7 +48,7 @@ export function createEndpoint<Sender = void>(
51
48
  Math.min(ms, 2 ** 31 - 1)
52
49
  )
53
50
  : undefined;
54
- pending.set(id, { resolve, reject, timer, sent: false });
51
+ pending.set(id, { resolve, reject, timer });
55
52
  try {
56
53
  send({ id, kind: 'call', method, params });
57
54
  } catch (error) {
@@ -75,9 +72,9 @@ export function createEndpoint<Sender = void>(
75
72
  listeners.set(event, set.add(listener));
76
73
  return () => set.delete(listener);
77
74
  },
78
- rejectPending(code: BridgeErrorCode, message: string, only?: (call: Pending) => boolean) {
75
+ rejectPending(code: BridgeErrorCode, message: string, only?: (id: string) => boolean) {
79
76
  for (const [id, call] of pending) {
80
- if (only && !only(call)) continue;
77
+ if (only && !only(id)) continue;
81
78
  clearTimeout(call.timer);
82
79
  call.reject(codedError({ code, message }));
83
80
  pending.delete(id);
@@ -1,5 +1,6 @@
1
- // The origin rules in RN: parser, validator, and the matcher whose text build-page-client.mts cuts out as MATCHES_ORIGIN
2
- // for the guards that createBridge and injectedScripts put around page code.
1
+ // The origin rules in RN: parser, the guard that createBridge and injectedScripts put around page code, and the
2
+ // matcher whose text build-page-client.mts cuts out as MATCHES_ORIGIN for that guard.
3
+ import { MATCHES_ORIGIN } from './pageClient.generated';
3
4
 
4
5
  /**
5
6
  * An origin rule (`http(s)://host[:port]`, `http(s)://*.host[:port]`) or a `location.origin`, parsed; null for anything
@@ -18,10 +19,6 @@ export const parseOrigin = (text: string) => {
18
19
  return { scheme, wildcard: !!wildcard, hostPort: `${host}${portSuffix}` };
19
20
  };
20
21
 
21
- /** The rules that are neither `*` nor what `parseOrigin` takes. */
22
- export const invalidOrigins = (rules: string[]) =>
23
- rules.filter((rule) => rule !== '*' && !parseOrigin(rule));
24
-
25
22
  /** Origin rules in `location.origin` form, for `matchesOrigin`: exact origins, and wildcards as prefix and suffix. */
26
23
  export type OriginForms = { any: boolean; exact: string[]; wild: [string, string][] };
27
24
 
@@ -59,3 +56,18 @@ export function matchesOrigin(forms: OriginForms, origin: string) {
59
56
  }
60
57
  return false;
61
58
  }
59
+
60
+ /**
61
+ * A page-side expression true where `location.origin` matches `origins`, or null when they include `*`. Throws an
62
+ * `Error` starting with `what` for a rule that is neither `*` nor what `parseOrigin` takes.
63
+ */
64
+ export function originGuard(what: string, origins: string[]): string | null {
65
+ const invalid = origins.filter((rule) => rule !== '*' && !parseOrigin(rule));
66
+ if (invalid.length) {
67
+ throw new Error(
68
+ `${what} ${JSON.stringify(invalid)} (use https://example.com or https://*.example.com, no path)`
69
+ );
70
+ }
71
+ const forms = originForms(origins);
72
+ return forms.any ? null : `(${MATCHES_ORIGIN})(${JSON.stringify(forms)}, location.origin)`;
73
+ }
@@ -1,5 +1,5 @@
1
1
  // Generated by .github/scripts/build-page-client.mts from pageClient.ts, endpoint.ts and origins.ts. Do not edit.
2
2
  export const PAGE_CLIENT =
3
- "function (w, timeoutMs) {\nconst codedError = ({ code, message }) => Object.assign(new Error(message), { code });\nfunction createEndpoint(send, timeoutMs, idPrefix) {\n const handlers = new Map();\n const listeners = new Map();\n const pending = new Map();\n let nextId = 0;\n return {\n pending,\n call(method, params, options) {\n const ms = options?.timeoutMs ?? timeoutMs;\n if (!(ms >= 0))\n return Promise.reject(new RangeError(`${method}: timeoutMs must be 0 or more, not ${ms}`));\n const id = `${idPrefix}${++nextId}`;\n return new Promise((resolve, reject) => {\n const timer = ms > 0 && ms < Infinity\n ? setTimeout(() => {\n pending.delete(id);\n reject(codedError({ code: 'timeout', message: `${method} timed out after ${ms} ms` }));\n }, Math.min(ms, 2 ** 31 - 1))\n : undefined;\n pending.set(id, { resolve, reject, timer, sent: false });\n try {\n send({ id, kind: 'call', method, params });\n }\n catch (error) {\n clearTimeout(timer);\n pending.delete(id);\n throw error;\n }\n });\n },\n emit(event, payload) {\n send({ kind: 'event', method: event, params: payload });\n },\n handle(method, handler) {\n handlers.set(method, handler);\n return () => {\n if (handlers.get(method) === handler)\n handlers.delete(method);\n };\n },\n on(event, listener) {\n const set = listeners.get(event) ?? new Set();\n listeners.set(event, set.add(listener));\n return () => set.delete(listener);\n },\n rejectPending(code, message, only) {\n for (const [id, call] of pending) {\n if (only && !only(call))\n continue;\n clearTimeout(call.timer);\n call.reject(codedError({ code, message }));\n pending.delete(id);\n }\n },\n async receive(message, reply, sender) {\n switch (message.kind) {\n case 'call': {\n const { id, method } = message;\n const fail = (code, text) => reply({ id, kind: 'error', error: { code, message: text } });\n const handler = handlers.get(method);\n if (!handler)\n return fail('not_found', `no handler for ${method}`);\n try {\n reply({ id, kind: 'result', value: await handler(message.params, sender) });\n }\n catch (error) {\n fail('handler_error', error instanceof Error ? error.message : String(error));\n }\n return;\n }\n case 'event':\n listeners.get(message.method)?.forEach((listener) => {\n try {\n listener(message.params, sender);\n }\n catch (error) {\n void Promise.reject(error);\n }\n });\n return;\n case 'result':\n case 'error': {\n const call = pending.get(message.id);\n if (!call)\n return;\n pending.delete(message.id);\n clearTimeout(call.timer);\n if (message.kind === 'result')\n call.resolve(message.value);\n else\n call.reject(codedError(message.error));\n }\n }\n },\n };\n}\nfunction installPageClient(w, timeoutMs) {\n if (w.nativeBridge || w !== w.top)\n return;\n const doc = Math.random().toString(36).slice(2, 10);\n const ios = w.webkit?.messageHandlers?.nativeBridge;\n const android = w.nativeBridgeTransport;\n const send = (message) => {\n const text = JSON.stringify({ ...message, doc });\n (ios ?? android)?.postMessage(text);\n };\n const endpoint = createEndpoint(send, timeoutMs, 'p');\n const receive = async (text) => {\n const message = JSON.parse(text);\n if (message.doc === doc)\n await endpoint.receive(message, send);\n };\n if (android)\n android.onmessage = (event) => void receive(event.data);\n w.nativeBridge = Object.freeze({\n call: endpoint.call,\n emit: endpoint.emit,\n handle: endpoint.handle,\n on: endpoint.on,\n __receive: receive,\n });\n if (w.document.readyState === 'loading') {\n w.document.addEventListener('DOMContentLoaded', () => send({ kind: 'ready' }), {\n once: true,\n });\n }\n else {\n send({ kind: 'ready' });\n }\n w.addEventListener('pageshow', (event) => {\n if (!event.persisted)\n return;\n endpoint.rejectPending('navigated', 'the page was left before the call was answered');\n send({ kind: 'ready' });\n });\n}\nreturn installPageClient(w, timeoutMs);\n}";
3
+ "function (w, timeoutMs) {\nconst codedError = ({ code, message }) => Object.assign(new Error(message), { code });\nfunction createEndpoint(send, timeoutMs, idPrefix) {\n const handlers = new Map();\n const listeners = new Map();\n const pending = new Map();\n let nextId = 0;\n return {\n pending,\n call(method, params, options) {\n const ms = options?.timeoutMs ?? timeoutMs;\n if (!(ms >= 0))\n return Promise.reject(new RangeError(`${method}: timeoutMs must be 0 or more, not ${ms}`));\n const id = `${idPrefix}${++nextId}`;\n return new Promise((resolve, reject) => {\n const timer = ms > 0 && ms < Infinity\n ? setTimeout(() => {\n pending.delete(id);\n reject(codedError({ code: 'timeout', message: `${method} timed out after ${ms} ms` }));\n }, Math.min(ms, 2 ** 31 - 1))\n : undefined;\n pending.set(id, { resolve, reject, timer });\n try {\n send({ id, kind: 'call', method, params });\n }\n catch (error) {\n clearTimeout(timer);\n pending.delete(id);\n throw error;\n }\n });\n },\n emit(event, payload) {\n send({ kind: 'event', method: event, params: payload });\n },\n handle(method, handler) {\n handlers.set(method, handler);\n return () => {\n if (handlers.get(method) === handler)\n handlers.delete(method);\n };\n },\n on(event, listener) {\n const set = listeners.get(event) ?? new Set();\n listeners.set(event, set.add(listener));\n return () => set.delete(listener);\n },\n rejectPending(code, message, only) {\n for (const [id, call] of pending) {\n if (only && !only(id))\n continue;\n clearTimeout(call.timer);\n call.reject(codedError({ code, message }));\n pending.delete(id);\n }\n },\n async receive(message, reply, sender) {\n switch (message.kind) {\n case 'call': {\n const { id, method } = message;\n const fail = (code, text) => reply({ id, kind: 'error', error: { code, message: text } });\n const handler = handlers.get(method);\n if (!handler)\n return fail('not_found', `no handler for ${method}`);\n try {\n reply({ id, kind: 'result', value: await handler(message.params, sender) });\n }\n catch (error) {\n fail('handler_error', error instanceof Error ? error.message : String(error));\n }\n return;\n }\n case 'event':\n listeners.get(message.method)?.forEach((listener) => {\n try {\n listener(message.params, sender);\n }\n catch (error) {\n void Promise.reject(error);\n }\n });\n return;\n case 'result':\n case 'error': {\n const call = pending.get(message.id);\n if (!call)\n return;\n pending.delete(message.id);\n clearTimeout(call.timer);\n if (message.kind === 'result')\n call.resolve(message.value);\n else\n call.reject(codedError(message.error));\n }\n }\n },\n };\n}\nfunction installPageClient(w, timeoutMs) {\n if (w.nativeBridge || w !== w.top)\n return;\n const doc = Math.random().toString(36).slice(2, 10);\n const ios = w.webkit?.messageHandlers?.nativeBridge;\n const android = w.nativeBridgeTransport;\n const send = (message) => {\n const text = JSON.stringify({ ...message, doc });\n (ios ?? android)?.postMessage(text);\n };\n const endpoint = createEndpoint(send, timeoutMs, 'p');\n const receive = async (text) => {\n const message = JSON.parse(text);\n if (message.doc === doc)\n await endpoint.receive(message, send);\n };\n if (android)\n android.onmessage = (event) => void receive(event.data);\n w.nativeBridge = Object.freeze({\n call: endpoint.call,\n emit: endpoint.emit,\n handle: endpoint.handle,\n on: endpoint.on,\n __receive: receive,\n });\n if (w.document.readyState === 'loading') {\n w.document.addEventListener('DOMContentLoaded', () => send({ kind: 'ready' }), {\n once: true,\n });\n }\n else {\n send({ kind: 'ready' });\n }\n w.addEventListener('pageshow', (event) => {\n if (!event.persisted)\n return;\n endpoint.rejectPending('navigated', 'the page was left before the call was answered');\n send({ kind: 'ready' });\n });\n}\nreturn installPageClient(w, timeoutMs);\n}";
4
4
  export const MATCHES_ORIGIN =
5
5
  "(() => {\nfunction hasAt(text, part, at) {\n for (let k = 0; k < part.length; k++)\n if (text[at + k] !== part[k])\n return false;\n return true;\n}\nfunction matchesOrigin(forms, origin) {\n if (forms.any)\n return true;\n for (let i = 0; i < forms.exact.length; i++)\n if (forms.exact[i] === origin)\n return true;\n for (let i = 0; i < forms.wild.length; i++) {\n const prefix = forms.wild[i][0];\n const suffix = forms.wild[i][1];\n const start = origin.length - suffix.length;\n if (start > prefix.length && hasAt(origin, prefix, 0) && hasAt(origin, suffix, start))\n return true;\n }\n return false;\n}\nreturn matchesOrigin;\n})()";
@@ -1,9 +1,6 @@
1
- // The page side of the bridge: installs `window.nativeBridge`. It runs inside the web page, so
2
- // .github/scripts/build-page-client.mts compiles it, with ./endpoint.ts, into the PAGE_CLIENT string that native
3
- // injects at document start. Each direction is a plain pipe: page -> native through `postMessage` (iOS
4
- // WKScriptMessageHandler at `webkit.messageHandlers.nativeBridge`, Android addWebMessageListener at
5
- // `window.nativeBridgeTransport`), native -> page through `__receive` (iOS callAsyncJavaScript) or the transport's
6
- // `onmessage` (Android). Messages follow ./protocol.ts; answers to either side's calls travel as ordinary messages.
1
+ // The page side of the bridge: installs `window.nativeBridge`. It runs in the page, compiled into PAGE_CLIENT by
2
+ // .github/scripts/build-page-client.mts. Page -> native: iOS WKScriptMessageHandler, Android addWebMessageListener;
3
+ // native -> page: `__receive` (iOS callAsyncJavaScript) or the transport's `onmessage` (Android).
7
4
  import type { PageBridge } from '../types';
8
5
  import { createEndpoint } from './endpoint';
9
6
  import type { BridgeMessage as Message } from './protocol';
@@ -49,7 +46,6 @@ export function installPageClient(w: PageWindow, timeoutMs: number) {
49
46
  /** iOS's entry point, origin-checked there. */
50
47
  __receive: receive,
51
48
  });
52
- // `ready` (protocol.ts) waits for DOMContentLoaded: a call delivered earlier would get `not_found`.
53
49
  if (w.document.readyState === 'loading') {
54
50
  w.document.addEventListener('DOMContentLoaded', () => send({ kind: 'ready' }), {
55
51
  once: true,
@@ -1,4 +1,4 @@
1
- // The bridge wire format. The RN side parses with it; the page client imports only its types.
1
+ // The bridge wire format. The RN side parses with it.
2
2
  import type { ErrorCode } from '../types';
3
3
 
4
4
  /** The codes a bridge call rejects with: the page may send only these. */