@buoy-gg/network 7.0.12 → 7.0.14

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 (136) hide show
  1. package/lib/commonjs/index.js +52 -0
  2. package/lib/commonjs/network/components/NetworkDetailStepper.js +26 -14
  3. package/lib/commonjs/network/components/NetworkEventDetailView.js +86 -14
  4. package/lib/commonjs/network/components/NetworkEventItemCompact.js +4 -0
  5. package/lib/commonjs/network/components/NetworkHeaderLive.js +32 -7
  6. package/lib/commonjs/network/components/NetworkHeaderMenu.js +183 -0
  7. package/lib/commonjs/network/components/NetworkListScreen.js +134 -8
  8. package/lib/commonjs/network/components/NetworkModal.js +198 -51
  9. package/lib/commonjs/network/components/NetworkNumberPrompt.js +178 -0
  10. package/lib/commonjs/network/components/NetworkOverrideEditor.js +797 -0
  11. package/lib/commonjs/network/components/NetworkOverrideHeaderButton.js +102 -0
  12. package/lib/commonjs/network/components/NetworkOverridesButton.js +88 -0
  13. package/lib/commonjs/network/components/NetworkOverridesScreen.js +489 -0
  14. package/lib/commonjs/network/components/response-editor/Explorer.js +973 -0
  15. package/lib/commonjs/network/components/response-editor/deleteNestedDataByPath.js +56 -0
  16. package/lib/commonjs/network/components/response-editor/editorContext.js +33 -0
  17. package/lib/commonjs/network/components/response-editor/updateNestedDataByPath.js +61 -0
  18. package/lib/commonjs/network/hooks/useNetworkSelection.js +53 -0
  19. package/lib/commonjs/network/hooks/useOverrideRules.js +36 -0
  20. package/lib/commonjs/network/overrides/applyToFetch.js +80 -0
  21. package/lib/commonjs/network/overrides/applyToXhr.js +190 -0
  22. package/lib/commonjs/network/overrides/engine.js +70 -0
  23. package/lib/commonjs/network/overrides/matchRule.js +81 -0
  24. package/lib/commonjs/network/overrides/overrideRulesStore.js +550 -0
  25. package/lib/commonjs/network/overrides/presets.js +70 -0
  26. package/lib/commonjs/network/overrides/resolveOverride.js +158 -0
  27. package/lib/commonjs/network/overrides/types.js +85 -0
  28. package/lib/commonjs/network/sync/networkSyncAdapter.js +230 -1
  29. package/lib/commonjs/network/types/index.js +5 -1
  30. package/lib/commonjs/network/utils/networkEventStore.js +52 -6
  31. package/lib/commonjs/network/utils/networkListener.js +90 -10
  32. package/lib/commonjs/network/utils/networkSelectionStore.js +193 -0
  33. package/lib/commonjs/preset.js +11 -0
  34. package/lib/module/index.js +19 -0
  35. package/lib/module/network/components/NetworkDetailStepper.js +27 -15
  36. package/lib/module/network/components/NetworkEventDetailView.js +87 -15
  37. package/lib/module/network/components/NetworkEventItemCompact.js +5 -1
  38. package/lib/module/network/components/NetworkHeaderLive.js +32 -7
  39. package/lib/module/network/components/NetworkHeaderMenu.js +177 -0
  40. package/lib/module/network/components/NetworkListScreen.js +135 -9
  41. package/lib/module/network/components/NetworkModal.js +200 -53
  42. package/lib/module/network/components/NetworkNumberPrompt.js +174 -0
  43. package/lib/module/network/components/NetworkOverrideEditor.js +794 -0
  44. package/lib/module/network/components/NetworkOverrideHeaderButton.js +99 -0
  45. package/lib/module/network/components/NetworkOverridesButton.js +85 -0
  46. package/lib/module/network/components/NetworkOverridesScreen.js +485 -0
  47. package/lib/module/network/components/response-editor/Explorer.js +972 -0
  48. package/lib/module/network/components/response-editor/deleteNestedDataByPath.js +51 -0
  49. package/lib/module/network/components/response-editor/editorContext.js +29 -0
  50. package/lib/module/network/components/response-editor/updateNestedDataByPath.js +56 -0
  51. package/lib/module/network/hooks/useNetworkSelection.js +46 -0
  52. package/lib/module/network/hooks/useOverrideRules.js +32 -0
  53. package/lib/module/network/overrides/applyToFetch.js +72 -0
  54. package/lib/module/network/overrides/applyToXhr.js +185 -0
  55. package/lib/module/network/overrides/engine.js +64 -0
  56. package/lib/module/network/overrides/matchRule.js +75 -0
  57. package/lib/module/network/overrides/overrideRulesStore.js +547 -0
  58. package/lib/module/network/overrides/presets.js +65 -0
  59. package/lib/module/network/overrides/resolveOverride.js +152 -0
  60. package/lib/module/network/overrides/types.js +80 -0
  61. package/lib/module/network/sync/networkSyncAdapter.js +230 -1
  62. package/lib/module/network/types/index.js +3 -1
  63. package/lib/module/network/utils/networkEventStore.js +52 -6
  64. package/lib/module/network/utils/networkListener.js +91 -10
  65. package/lib/module/network/utils/networkSelectionStore.js +188 -0
  66. package/lib/module/preset.js +13 -1
  67. package/lib/typescript/index.d.ts +9 -0
  68. package/lib/typescript/index.d.ts.map +1 -1
  69. package/lib/typescript/network/components/NetworkDetailStepper.d.ts +8 -5
  70. package/lib/typescript/network/components/NetworkDetailStepper.d.ts.map +1 -1
  71. package/lib/typescript/network/components/NetworkEventDetailView.d.ts +36 -1
  72. package/lib/typescript/network/components/NetworkEventDetailView.d.ts.map +1 -1
  73. package/lib/typescript/network/components/NetworkEventItemCompact.d.ts +6 -0
  74. package/lib/typescript/network/components/NetworkEventItemCompact.d.ts.map +1 -1
  75. package/lib/typescript/network/components/NetworkHeaderLive.d.ts +13 -3
  76. package/lib/typescript/network/components/NetworkHeaderLive.d.ts.map +1 -1
  77. package/lib/typescript/network/components/NetworkHeaderMenu.d.ts +46 -0
  78. package/lib/typescript/network/components/NetworkHeaderMenu.d.ts.map +1 -0
  79. package/lib/typescript/network/components/NetworkListScreen.d.ts.map +1 -1
  80. package/lib/typescript/network/components/NetworkModal.d.ts.map +1 -1
  81. package/lib/typescript/network/components/NetworkNumberPrompt.d.ts +33 -0
  82. package/lib/typescript/network/components/NetworkNumberPrompt.d.ts.map +1 -0
  83. package/lib/typescript/network/components/NetworkOverrideEditor.d.ts +17 -0
  84. package/lib/typescript/network/components/NetworkOverrideEditor.d.ts.map +1 -0
  85. package/lib/typescript/network/components/NetworkOverrideHeaderButton.d.ts +27 -0
  86. package/lib/typescript/network/components/NetworkOverrideHeaderButton.d.ts.map +1 -0
  87. package/lib/typescript/network/components/NetworkOverridesButton.d.ts +17 -0
  88. package/lib/typescript/network/components/NetworkOverridesButton.d.ts.map +1 -0
  89. package/lib/typescript/network/components/NetworkOverridesScreen.d.ts +29 -0
  90. package/lib/typescript/network/components/NetworkOverridesScreen.d.ts.map +1 -0
  91. package/lib/typescript/network/components/response-editor/Explorer.d.ts +17 -0
  92. package/lib/typescript/network/components/response-editor/Explorer.d.ts.map +1 -0
  93. package/lib/typescript/network/components/response-editor/deleteNestedDataByPath.d.ts +9 -0
  94. package/lib/typescript/network/components/response-editor/deleteNestedDataByPath.d.ts.map +1 -0
  95. package/lib/typescript/network/components/response-editor/editorContext.d.ts +29 -0
  96. package/lib/typescript/network/components/response-editor/editorContext.d.ts.map +1 -0
  97. package/lib/typescript/network/components/response-editor/updateNestedDataByPath.d.ts +10 -0
  98. package/lib/typescript/network/components/response-editor/updateNestedDataByPath.d.ts.map +1 -0
  99. package/lib/typescript/network/hooks/useNetworkSelection.d.ts +26 -0
  100. package/lib/typescript/network/hooks/useNetworkSelection.d.ts.map +1 -0
  101. package/lib/typescript/network/hooks/useOverrideRules.d.ts +29 -0
  102. package/lib/typescript/network/hooks/useOverrideRules.d.ts.map +1 -0
  103. package/lib/typescript/network/overrides/__tests__/applyToFetch.test.d.ts +16 -0
  104. package/lib/typescript/network/overrides/__tests__/applyToFetch.test.d.ts.map +1 -0
  105. package/lib/typescript/network/overrides/__tests__/applyToXhr.test.d.ts +19 -0
  106. package/lib/typescript/network/overrides/__tests__/applyToXhr.test.d.ts.map +1 -0
  107. package/lib/typescript/network/overrides/__tests__/resolveOverride.test.d.ts +22 -0
  108. package/lib/typescript/network/overrides/__tests__/resolveOverride.test.d.ts.map +1 -0
  109. package/lib/typescript/network/overrides/applyToFetch.d.ts +50 -0
  110. package/lib/typescript/network/overrides/applyToFetch.d.ts.map +1 -0
  111. package/lib/typescript/network/overrides/applyToXhr.d.ts +43 -0
  112. package/lib/typescript/network/overrides/applyToXhr.d.ts.map +1 -0
  113. package/lib/typescript/network/overrides/engine.d.ts +47 -0
  114. package/lib/typescript/network/overrides/engine.d.ts.map +1 -0
  115. package/lib/typescript/network/overrides/matchRule.d.ts +22 -0
  116. package/lib/typescript/network/overrides/matchRule.d.ts.map +1 -0
  117. package/lib/typescript/network/overrides/overrideRulesStore.d.ts +205 -0
  118. package/lib/typescript/network/overrides/overrideRulesStore.d.ts.map +1 -0
  119. package/lib/typescript/network/overrides/presets.d.ts +38 -0
  120. package/lib/typescript/network/overrides/presets.d.ts.map +1 -0
  121. package/lib/typescript/network/overrides/resolveOverride.d.ts +46 -0
  122. package/lib/typescript/network/overrides/resolveOverride.d.ts.map +1 -0
  123. package/lib/typescript/network/overrides/types.d.ts +169 -0
  124. package/lib/typescript/network/overrides/types.d.ts.map +1 -0
  125. package/lib/typescript/network/sync/networkSyncAdapter.d.ts +73 -0
  126. package/lib/typescript/network/sync/networkSyncAdapter.d.ts.map +1 -1
  127. package/lib/typescript/network/types/index.d.ts +10 -0
  128. package/lib/typescript/network/types/index.d.ts.map +1 -1
  129. package/lib/typescript/network/utils/networkEventStore.d.ts +14 -0
  130. package/lib/typescript/network/utils/networkEventStore.d.ts.map +1 -1
  131. package/lib/typescript/network/utils/networkListener.d.ts +3 -0
  132. package/lib/typescript/network/utils/networkListener.d.ts.map +1 -1
  133. package/lib/typescript/network/utils/networkSelectionStore.d.ts +117 -0
  134. package/lib/typescript/network/utils/networkSelectionStore.d.ts.map +1 -0
  135. package/lib/typescript/preset.d.ts.map +1 -1
  136. package/package.json +2 -2
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.deleteNestedDataByPath = void 0;
7
+ /**
8
+ * Deletes nested data by path
9
+ *
10
+ * @param {unknown} oldData Data to be updated
11
+ * @param {Array<string>} deletePath Path to the data to be deleted
12
+ * @returns newData without the deleted items by path
13
+ */
14
+ const deleteNestedDataByPath = (oldData, deletePath) => {
15
+ if (oldData instanceof Map) {
16
+ const newData = new Map(oldData);
17
+ if (deletePath.length === 1) {
18
+ newData.delete(deletePath[0]);
19
+ return newData;
20
+ }
21
+ const [head, ...tail] = deletePath;
22
+ newData.set(head, deleteNestedDataByPath(newData.get(head), tail));
23
+ return newData;
24
+ }
25
+ if (oldData instanceof Set) {
26
+ const setAsArray = deleteNestedDataByPath(Array.from(oldData), deletePath);
27
+ return new Set(setAsArray);
28
+ }
29
+ if (Array.isArray(oldData)) {
30
+ const newData = [...oldData];
31
+ if (deletePath.length === 1) {
32
+ return newData.filter((_, idx) => idx.toString() !== deletePath[0]);
33
+ }
34
+ const [head, ...tail] = deletePath;
35
+
36
+ // @ts-expect-error NAS
37
+ newData[head] = deleteNestedDataByPath(newData[head], tail);
38
+ return newData;
39
+ }
40
+ if (oldData instanceof Object) {
41
+ const newData = {
42
+ ...oldData
43
+ };
44
+ if (deletePath.length === 1) {
45
+ // @ts-expect-error NAS
46
+ delete newData[deletePath[0]];
47
+ return newData;
48
+ }
49
+ const [head, ...tail] = deletePath;
50
+ // @ts-expect-error NAS
51
+ newData[head] = deleteNestedDataByPath(newData[head], tail);
52
+ return newData;
53
+ }
54
+ return oldData;
55
+ };
56
+ exports.deleteNestedDataByPath = deleteNestedDataByPath;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.ResponseEditorContext = void 0;
7
+ exports.useResponseEditor = useResponseEditor;
8
+ var _react = require("react");
9
+ /**
10
+ * What the ported Explorer needs in place of React Query's cache.
11
+ *
12
+ * In the original, every edit ends at
13
+ * `queryClient.setQueryData(activeQuery.queryKey, newData)` and `activeQuery`
14
+ * doubles as the "is this editable" gate — so the whole tree is wired to one
15
+ * specific store. Here that becomes two values in context: the ROOT document
16
+ * (every op rebuilds the whole thing from the root, so each row needs it) and a
17
+ * single `onChange`.
18
+ *
19
+ * Context rather than props because Explorer recurses per node and already
20
+ * threads `activeQuery` down every level; swapping one drilled prop for another
21
+ * would have meant the same plumbing at every call site, and a row deep in a
22
+ * response is exactly where you don't want a missed prop.
23
+ */
24
+
25
+ const ResponseEditorContext = exports.ResponseEditorContext = /*#__PURE__*/(0, _react.createContext)(null);
26
+
27
+ /**
28
+ * Null outside a provider, which is how the tree stays READ-ONLY by default —
29
+ * the same role `activeQuery === undefined` played in the original.
30
+ */
31
+ function useResponseEditor() {
32
+ return (0, _react.useContext)(ResponseEditorContext);
33
+ }
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.updateNestedDataByPath = void 0;
7
+ /**
8
+ * updates nested data by path
9
+ *
10
+ * @param {JsonValue} oldData Data to be updated
11
+ * @param {Array<string>} updatePath Path to the data to be updated
12
+ * @param {JsonValue} value New value
13
+ */
14
+ const updateNestedDataByPath = (oldData, updatePath, value) => {
15
+ if (updatePath.length === 0) {
16
+ return value;
17
+ }
18
+ if (oldData instanceof Map) {
19
+ const newData = new Map(oldData);
20
+ if (updatePath.length === 1) {
21
+ newData.set(updatePath[0], value);
22
+ return newData;
23
+ }
24
+ const [head, ...tail] = updatePath;
25
+ const currentValue = newData.get(head);
26
+ newData.set(head, updateNestedDataByPath(currentValue ?? null, tail, value));
27
+ return newData;
28
+ }
29
+ if (oldData instanceof Set) {
30
+ const setAsArray = updateNestedDataByPath(Array.from(oldData), updatePath, value);
31
+ return new Set(Array.isArray(setAsArray) ? setAsArray : []);
32
+ }
33
+ if (Array.isArray(oldData)) {
34
+ const newData = [...oldData];
35
+ if (updatePath.length === 1) {
36
+ // @ts-expect-error NAS
37
+ newData[updatePath[0]] = value;
38
+ return newData;
39
+ }
40
+ const [head, ...tail] = updatePath;
41
+ // @ts-expect-error NAS
42
+ newData[head] = updateNestedDataByPath(newData[head], tail, value);
43
+ return newData;
44
+ }
45
+ if (oldData instanceof Object) {
46
+ const newData = {
47
+ ...oldData
48
+ };
49
+ if (updatePath.length === 1) {
50
+ // @ts-expect-error NAS
51
+ newData[updatePath[0]] = value;
52
+ return newData;
53
+ }
54
+ const [head, ...tail] = updatePath;
55
+ // @ts-expect-error NAS
56
+ newData[head] = updateNestedDataByPath(newData[head], tail, value);
57
+ return newData;
58
+ }
59
+ return oldData;
60
+ };
61
+ exports.updateNestedDataByPath = updateNestedDataByPath;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.useHasNetworkSelection = useHasNetworkSelection;
7
+ exports.useNetworkBodyEventId = useNetworkBodyEventId;
8
+ exports.useNetworkCursor = useNetworkCursor;
9
+ exports.useSelectedNetworkEventId = useSelectedNetworkEventId;
10
+ var _react = require("react");
11
+ var _networkSelectionStore = require("../utils/networkSelectionStore");
12
+ /**
13
+ * Narrow subscriptions to the prev/next cursor (`networkSelectionStore`).
14
+ *
15
+ * One hook per consumer, each returning the SMALLEST value that consumer
16
+ * renders — that is the whole point of moving the cursor into a store. The
17
+ * modal root takes `useHasNetworkSelection()` (a boolean that flips twice a
18
+ * session), so a step no longer re-renders `JsModal`, the header and all five
19
+ * screens; the footer and the body take the parts that actually change.
20
+ */
21
+
22
+ const subscribe = onChange => _networkSelectionStore.networkSelectionStore.subscribe(onChange);
23
+ const getState = () => _networkSelectionStore.networkSelectionStore.getState();
24
+
25
+ /**
26
+ * Is ANYTHING selected — i.e. is the detail screen up?
27
+ *
28
+ * `useSyncExternalStore` compares the selector's result, so the root only
29
+ * re-renders when this boolean flips, not on every step.
30
+ */
31
+ function useHasNetworkSelection() {
32
+ return (0, _react.useSyncExternalStore)(subscribe, () => getState().selectedId != null, () => getState().selectedId != null);
33
+ }
34
+
35
+ /** Where the USER is. Moves synchronously on tap — footer, header pin actions. */
36
+ function useSelectedNetworkEventId() {
37
+ return (0, _react.useSyncExternalStore)(subscribe, () => getState().selectedId, () => getState().selectedId);
38
+ }
39
+
40
+ /** What the BODY may render. Lags `selectedId` — see networkSelectionStore. */
41
+ function useNetworkBodyEventId() {
42
+ return (0, _react.useSyncExternalStore)(subscribe, () => getState().bodyId, () => getState().bodyId);
43
+ }
44
+
45
+ /** Cursor position + list length, for the "REQUEST n OF m" counter. */
46
+ function useNetworkCursor() {
47
+ const index = (0, _react.useSyncExternalStore)(subscribe, () => getState().index, () => getState().index);
48
+ const total = (0, _react.useSyncExternalStore)(subscribe, () => getState().ids.length, () => getState().ids.length);
49
+ return {
50
+ index,
51
+ total
52
+ };
53
+ }
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.useOverrideRules = useOverrideRules;
7
+ var _react = require("react");
8
+ var _overrideRulesStore = require("../overrides/overrideRulesStore");
9
+ var _resolveOverride = require("../overrides/resolveOverride");
10
+ /**
11
+ * Read + mutate the override rule list.
12
+ *
13
+ * `useSyncExternalStore` over the store's own subscribe/getState, which already
14
+ * hands out a stable state object per mutation (see `rebuild`) — so this can't
15
+ * tear and doesn't need a selector to stay cheap.
16
+ */
17
+ function useOverrideRules() {
18
+ const state = (0, _react.useSyncExternalStore)((0, _react.useCallback)(listener => _overrideRulesStore.overrideRulesStore.subscribe(listener), []), () => _overrideRulesStore.overrideRulesStore.getState(), () => _overrideRulesStore.overrideRulesStore.getState());
19
+ const setEnabled = (0, _react.useCallback)(enabled => _overrideRulesStore.overrideRulesStore.setEnabled(enabled), []);
20
+ const upsertRule = (0, _react.useCallback)(draft => _overrideRulesStore.overrideRulesStore.upsertRule(draft), []);
21
+ const setRuleEnabled = (0, _react.useCallback)((id, enabled) => _overrideRulesStore.overrideRulesStore.setRuleEnabled(id, enabled), []);
22
+ const removeRule = (0, _react.useCallback)(id => _overrideRulesStore.overrideRulesStore.removeRule(id), []);
23
+ const clearRules = (0, _react.useCallback)(() => _overrideRulesStore.overrideRulesStore.clearRules(), []);
24
+ return {
25
+ enabled: state.enabled,
26
+ rules: state.rules,
27
+ autoPaused: state.autoPaused,
28
+ activeCount: _overrideRulesStore.overrideRulesStore.activeCount(),
29
+ setEnabled,
30
+ upsertRule,
31
+ setRuleEnabled,
32
+ removeRule,
33
+ clearRules,
34
+ isRuleSpent: _resolveOverride.isSpent
35
+ };
36
+ }
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.canSynthesizeResponse = canSynthesizeResponse;
7
+ exports.sleep = void 0;
8
+ exports.synthesizeFetchError = synthesizeFetchError;
9
+ exports.synthesizeResponse = synthesizeResponse;
10
+ /**
11
+ * Perform an override outcome against `fetch`.
12
+ *
13
+ * WHY THIS EXISTS — and why "XHR is the single choke point" is WRONG:
14
+ *
15
+ * In bare React Native, `Libraries/Network/fetch.js` is `require('whatwg-fetch')`,
16
+ * so `fetch` really is a polyfill over XMLHttpRequest and hooking XHR alone
17
+ * would cover everything. But **Expo replaces it**: `expo/src/winter/runtime.native.ts`
18
+ * installs `expo/fetch` — a NATIVE fetch over `ExpoFetchModule` — as
19
+ * `globalThis.fetch` unless `EXPO_PUBLIC_USE_RN_FETCH=1`. Those requests never
20
+ * construct an XMLHttpRequest, so an XHR-only override silently does nothing on
21
+ * the majority of real apps.
22
+ *
23
+ * Verified the hard way on Expo SDK 56 / RN 0.85.3: rule matched, engine
24
+ * healthy, interceptor installed, and the request still came back a real 200.
25
+ *
26
+ * So overrides hook BOTH layers. `axios` still needs the XHR path (it uses
27
+ * XMLHttpRequest on every platform), and this covers `fetch` on both flavours.
28
+ */
29
+
30
+ const sleep = ms => ms > 0 ? new Promise(resolve => setTimeout(resolve, ms)) : Promise.resolve();
31
+
32
+ /**
33
+ * Can we build a `Response` in this runtime?
34
+ *
35
+ * React Native installs the whatwg-fetch `Response` global via `setUpXHR`, and
36
+ * Expo deliberately keeps it (it only swaps `fetch`). Feature-detected anyway:
37
+ * without it, the honest thing is to let the request run for real.
38
+ */
39
+ exports.sleep = sleep;
40
+ function canSynthesizeResponse() {
41
+ return typeof Response === "function";
42
+ }
43
+
44
+ /**
45
+ * Build the fake `Response` an overridden `fetch` resolves with.
46
+ *
47
+ * Note the status range: whatwg-fetch's `Response` constructor THROWS
48
+ * `RangeError` outside [200, 599], which would crash the caller instead of
49
+ * overriding it. `resolveOverride` clamps before we ever get here.
50
+ */
51
+ function synthesizeResponse(url, outcome) {
52
+ const response = new Response(outcome.body, {
53
+ status: outcome.status,
54
+ statusText: outcome.statusText,
55
+ headers: outcome.headers
56
+ });
57
+ // `Response.url` is not settable through the constructor, and consumers do
58
+ // read it (redirect checks, cache keys). whatwg-fetch stores it as a plain
59
+ // property, so assigning is both possible and correct.
60
+ try {
61
+ Object.defineProperty(response, "url", {
62
+ value: url,
63
+ configurable: true
64
+ });
65
+ } catch {
66
+ // Sealed implementation — an empty url is cosmetic, not worth failing over.
67
+ }
68
+ return response;
69
+ }
70
+
71
+ /**
72
+ * The error a failed `fetch` rejects with.
73
+ *
74
+ * These are the exact messages whatwg-fetch produces for a dead connection and
75
+ * a timeout, so app code that string-matches on them (plenty does) behaves the
76
+ * same way it would against a real failure.
77
+ */
78
+ function synthesizeFetchError(outcome) {
79
+ return new TypeError(outcome.failKind === "timeout" ? "Network request timed out" : "Network request failed");
80
+ }
@@ -0,0 +1,190 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.canSynthesize = canSynthesize;
7
+ exports.runOverride = runOverride;
8
+ /**
9
+ * Perform an override outcome against a React Native XMLHttpRequest.
10
+ *
11
+ * WHY THIS IS POSSIBLE AT ALL: React Native's XMLHttpRequest
12
+ * (`react-native/Libraries/Network/XMLHttpRequest.js`) is pure JavaScript.
13
+ * `readyState`, `status`, `responseHeaders` and `responseURL` are plain
14
+ * writable fields, and `setResponseHeaders()` / `setReadyState()` are real
15
+ * methods — `setReadyState(DONE)` dispatches the correct terminal event off
16
+ * internal flags (`_aborted` → abort, `_hasError` + `_timedOut` → timeout,
17
+ * `_hasError` → error, otherwise load; always loadend). So a response can be
18
+ * synthesized end to end without touching native code.
19
+ *
20
+ * WHY XHR IS THE ONLY PLACE WE HOOK: `react-native/Libraries/Network/fetch.js`
21
+ * is `require('whatwg-fetch')` — RN's `fetch` IS the polyfill over
22
+ * XMLHttpRequest. Overriding here therefore covers `fetch`, `axios` and raw
23
+ * XHR through one code path, and the fake response flows back up through the
24
+ * polyfill so the tool records it without any extra plumbing.
25
+ *
26
+ * Verified field-for-field on React Native 0.81.4 and 0.85.3.
27
+ *
28
+ * Four non-obvious behaviours are handled below; each one is a real bug if you
29
+ * skip it, and each is commented at the line that fixes it.
30
+ */
31
+
32
+ const HEADERS_RECEIVED = 2;
33
+ const LOADING = 3;
34
+ const DONE = 4;
35
+
36
+ /**
37
+ * The private surface of RN's XMLHttpRequest that we drive.
38
+ *
39
+ * Typed explicitly rather than reached for with `any` so that if a future React
40
+ * Native renames one of these, the compiler points at every use — and so the
41
+ * blast radius of "we depend on RN internals" is one interface.
42
+ */
43
+
44
+ const internalsOf = xhr => xhr;
45
+ let warnedUnsupported = false;
46
+
47
+ /**
48
+ * Can this XMLHttpRequest be driven by hand?
49
+ *
50
+ * The whole technique rests on RN internals, so it is feature-detected rather
51
+ * than assumed: on a browser XMLHttpRequest (react-native-web) these methods
52
+ * don't exist and `status` is a read-only getter. There, overrides no-op and
53
+ * the request goes out for real — degraded, but never broken.
54
+ */
55
+ function canSynthesize(xhr) {
56
+ const internals = internalsOf(xhr);
57
+ return typeof internals.setReadyState === "function" && typeof internals.setResponseHeaders === "function";
58
+ }
59
+ function warnUnsupported() {
60
+ if (warnedUnsupported) return;
61
+ warnedUnsupported = true;
62
+ if (typeof __DEV__ !== "undefined" && __DEV__) {
63
+ console.warn("[Buoy] Network overrides need React Native's XMLHttpRequest and this " + "environment provides a different one — requests will run normally.");
64
+ }
65
+ }
66
+
67
+ /** Synthesize a successful response. */
68
+ function respond(xhr, url, outcome) {
69
+ const internals = internalsOf(xhr);
70
+
71
+ // `_reset()` does `delete this.responseURL`, so `'responseURL' in xhr` is
72
+ // FALSE on a fresh request — and whatwg-fetch reads exactly that to populate
73
+ // `Response.url` (fetch.js:558). Without this line every overridden fetch
74
+ // response would silently carry `url: ""`.
75
+ internals.responseURL = url;
76
+ internals.status = outcome.status;
77
+ // RN has no `statusText` field at all (real requests report `undefined`), so
78
+ // this is a new own property. Harmless, and it makes the tool's list read
79
+ // correctly instead of showing a bare number.
80
+ internals.statusText = outcome.statusText;
81
+ internals.setResponseHeaders?.(outcome.headers);
82
+ // HEADERS_RECEIVED also stamps the interceptor's existing `_ttfb`, so an
83
+ // overridden request reports its injected latency like a real one.
84
+ internals.setReadyState?.(HEADERS_RECEIVED);
85
+ if (internals._aborted) return;
86
+
87
+ // whatwg-fetch sets `responseType = 'blob'` before every send
88
+ // (fetch.js:599-606), which would make RN's `response` getter demand a native
89
+ // Blob descriptor from BlobManager. But the polyfill reads the response
90
+ // exactly once — `'response' in xhr ? xhr.response : xhr.responseText`
91
+ // (fetch.js:559) — and never re-reads `responseType`. Handing back text is
92
+ // therefore both sufficient and strictly simpler: no Blob, no FileReader, no
93
+ // native round trip, and `.json()` becomes a synchronous JSON.parse.
94
+ //
95
+ // Assign the FIELD, not the property: the `responseType` setter throws once
96
+ // `_sent` is true (XMLHttpRequest.js:215), and we set `_sent` above.
97
+ internals._responseType = "text";
98
+ internals._response = outcome.body;
99
+ internals._cachedResponse = undefined; // force the getter to recompute
100
+ internals.setReadyState?.(LOADING);
101
+ if (internals._aborted) return;
102
+ internals.setReadyState?.(DONE); // dispatches 'load' then 'loadend'
103
+ }
104
+
105
+ /** Synthesize a transport failure — offline or timeout. */
106
+ function fail(xhr, outcome) {
107
+ const internals = internalsOf(xhr);
108
+ const timedOut = outcome.failKind === "timeout";
109
+
110
+ // These two flags are the entire difference between the 'error' and
111
+ // 'timeout' events — see `setReadyState` in XMLHttpRequest.js. whatwg-fetch
112
+ // turns them into `TypeError: Network request failed` and
113
+ // `TypeError: Network request timed out` respectively, which is exactly what
114
+ // the app would see from a real dead connection.
115
+ internals._hasError = true;
116
+ internals._timedOut = timedOut;
117
+ internals._responseType = "text";
118
+ internals._response = timedOut ? "Request timed out (Buoy override)" : "Network request failed (Buoy override)";
119
+ internals._cachedResponse = undefined;
120
+ internals.setReadyState?.(DONE);
121
+ }
122
+
123
+ /**
124
+ * Apply an outcome to a request that has NOT been sent yet.
125
+ *
126
+ * Returns `false` when this environment can't be driven by hand, in which case
127
+ * the caller must send the request normally.
128
+ *
129
+ * @param passThrough Sends the real request. Only used by `kind: "delay"`.
130
+ */
131
+ function runOverride(xhr, url, outcome, passThrough) {
132
+ if (!canSynthesize(xhr)) {
133
+ warnUnsupported();
134
+ return false;
135
+ }
136
+ const internals = internalsOf(xhr);
137
+
138
+ // Claim the request as sent, for all three kinds.
139
+ //
140
+ // We skip RN's own `send()`, which is what normally sets this — and `abort()`
141
+ // branches on it: with `_sent` false it treats the request as never started,
142
+ // silently `_reset()`s, and dispatches NOTHING. The app's fetch promise would
143
+ // then never settle (a hang), and for a synthesized response our own timer
144
+ // would afterwards fire 'load' on a reset object, resolving a fetch the app
145
+ // had already aborted. Claiming it means abort() dispatches DONE + 'abort'
146
+ // and whatwg-fetch rejects with AbortError, as it should.
147
+ internals._sent = true;
148
+ if (outcome.kind !== "delay") {
149
+ // Buoy's own `open()` swizzle overwrites RN's private `_requestId` with a
150
+ // string id. RN normally clobbers it back with the native numeric id inside
151
+ // `send()` — which we're skipping — so it would survive here, and
152
+ // `abort()` would hand that string to `RCTNetworking.abortRequest()`.
153
+ // Nulling it makes abort a clean no-op on the native side.
154
+ internals._requestId = null;
155
+ }
156
+ let timer = null;
157
+ const onAbort = () => {
158
+ if (timer !== null) {
159
+ clearTimeout(timer);
160
+ timer = null;
161
+ }
162
+ };
163
+ xhr.addEventListener("abort", onAbort);
164
+ const fire = () => {
165
+ timer = null;
166
+ xhr.removeEventListener("abort", onAbort);
167
+ // The real guard. `_aborted` is set unconditionally by `abort()` and
168
+ // survives its `_reset()`, so this is true whether or not the 'abort' event
169
+ // was ever dispatched.
170
+ if (internals._aborted) return;
171
+ if (outcome.kind === "delay") {
172
+ // Hand the state machine back before RN's `send()` sees it: it throws
173
+ // 'Request has already been sent' on a truthy `_sent`.
174
+ internals._sent = false;
175
+ passThrough();
176
+ return;
177
+ }
178
+ if (outcome.kind === "fail") {
179
+ fail(xhr, outcome);
180
+ return;
181
+ }
182
+ respond(xhr, url, outcome);
183
+ };
184
+
185
+ // ALWAYS asynchronous, even at 0ms. Callers legitimately attach handlers
186
+ // after `send()` returns (axios does), and a synchronous response would fire
187
+ // 'load' before they exist.
188
+ timer = setTimeout(fire, outcome.delayMs);
189
+ return true;
190
+ }
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.inspectEngine = inspectEngine;
7
+ exports.overrideForRequest = overrideForRequest;
8
+ exports.setOverrideHooks = setOverrideHooks;
9
+ var _resolveOverride = require("./resolveOverride");
10
+ /**
11
+ * The seam between the interceptor and the rule store.
12
+ *
13
+ * It exists to keep the import graph acyclic: `networkListener` needs rules,
14
+ * and the rule store needs the listener (to keep the swizzle installed while a
15
+ * rule is active). Rather than have them import each other, the store REGISTERS
16
+ * itself here and the listener asks here. Both sides import only this leaf.
17
+ *
18
+ * It's also the single place the production gate lives — see `overrideForRequest`.
19
+ */
20
+
21
+ let hooks = null;
22
+ function setOverrideHooks(next) {
23
+ hooks = next;
24
+ }
25
+
26
+ /**
27
+ * Diagnostics for the sync adapter's `debugOverrides` action.
28
+ *
29
+ * Reads the engine's own view of the world — crucially `hooks`, which is
30
+ * MODULE state here: if the interceptor and the rule store ever ended up with
31
+ * separate copies of this file, this is the only place that shows it.
32
+ */
33
+ function inspectEngine(url, method) {
34
+ return {
35
+ hooksInstalled: hooks !== null,
36
+ devFlag: typeof __DEV__ === "undefined" ? "undefined" : __DEV__,
37
+ ruleCount: hooks ? hooks.getRules().length : 0,
38
+ // Non-recording probe — a diagnostic must not burn a rule's `times` budget
39
+ // or nudge an alternating rule's phase.
40
+ matches: hooks ? (0, _resolveOverride.findMatchingRule)(url, method, hooks.getRules()) !== null : false
41
+ };
42
+ }
43
+
44
+ /**
45
+ * Resolve an override for one outgoing request, recording the hit.
46
+ *
47
+ * NEVER ACTIVE IN A PRODUCTION BUILD. A shipped app that synthesizes 500s or
48
+ * silently swallows requests is a catastrophe of a different order than a
49
+ * broken dev tool, so the gate is here — at the single entry point — rather
50
+ * than trusted to every call site.
51
+ */
52
+ function overrideForRequest(url, method) {
53
+ if (!hooks) return null;
54
+ // `__DEV__` is undefined outside React Native (unit tests, the desktop
55
+ // dashboard's bundle); only an explicit `false` — a real release build —
56
+ // disables overrides.
57
+ if (typeof __DEV__ !== "undefined" && !__DEV__) return null;
58
+ const rules = hooks.getRules();
59
+ if (rules.length === 0) return null;
60
+ const rule = (0, _resolveOverride.findMatchingRule)(url, method, rules);
61
+ if (!rule) return null;
62
+
63
+ // Phase is read BEFORE the match is recorded, so a fresh alternating rule
64
+ // (`seen === 0`) lets this first request through and takes the next one.
65
+ const applies = (0, _resolveOverride.shouldApply)(rule);
66
+ hooks.recordMatch(rule.id);
67
+ if (!applies) return null;
68
+ hooks.recordHit(rule.id);
69
+ return (0, _resolveOverride.toOutcome)(rule);
70
+ }
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.compilePattern = compilePattern;
7
+ exports.escapeRegex = escapeRegex;
8
+ exports.ruleMatches = ruleMatches;
9
+ /**
10
+ * Glob matching for override rules — a faithful port of Chrome DevTools'.
11
+ *
12
+ * Ported from `NetworkPersistenceManager.ts:1051` + `StringUtilities.ts:9` in
13
+ * the devtools-frontend source. Ported rather than reinvented on purpose: `*`
14
+ * globs are the syntax developers already have in their fingers from Chrome's
15
+ * "Override headers" `applyTo` field, and a pattern that behaves differently
16
+ * here than it does in the browser would be a quiet trap.
17
+ */
18
+
19
+ /**
20
+ * Chrome's escape set, character for character.
21
+ *
22
+ * `*` is deliberately ABSENT — it survives escaping so it can become `.*`
23
+ * below. Everything else that means something to a regex is neutered.
24
+ */
25
+ const SPECIAL_CHARACTERS = "[]{}()\\.^$+|-,?";
26
+
27
+ /**
28
+ * Escape a glob into regex source: neutralize regex metacharacters, then
29
+ * promote `*` to `.*`.
30
+ *
31
+ * `split`/`join` rather than `replaceAll` — same result, no reliance on how
32
+ * complete a given Hermes build's ES2021 surface is.
33
+ */
34
+ function escapeRegex(pattern) {
35
+ let result = "";
36
+ for (let i = 0; i < pattern.length; i++) {
37
+ const char = pattern.charAt(i);
38
+ if (SPECIAL_CHARACTERS.indexOf(char) !== -1) {
39
+ result += "\\";
40
+ }
41
+ result += char;
42
+ }
43
+ return result.split("*").join(".*");
44
+ }
45
+
46
+ /**
47
+ * Compiled patterns, cached by source.
48
+ *
49
+ * `resolveOverride` runs on EVERY request the app makes, against every rule.
50
+ * Recompiling a RegExp per request per rule is pure waste in the one place
51
+ * this feature is allowed to cost nothing.
52
+ */
53
+ const compiled = new Map();
54
+ function compilePattern(pattern) {
55
+ const cached = compiled.get(pattern);
56
+ if (cached) return cached;
57
+ // Anchored, like Chrome's `^${...}$` — a pattern describes the whole URL, so
58
+ // `pokeapi.co` matches nothing and `*pokeapi.co*` matches everything on that
59
+ // host. Predictable beats clever; the rule editor writes full URLs for you.
60
+ const regex = new RegExp(`^${escapeRegex(pattern)}$`);
61
+ // Unbounded growth isn't possible in practice (patterns come from a capped
62
+ // rule list), but a user editing a pattern character by character churns
63
+ // entries, so keep the cache from becoming a leak.
64
+ if (compiled.size > 200) compiled.clear();
65
+ compiled.set(pattern, regex);
66
+ return regex;
67
+ }
68
+
69
+ /** Does this rule apply to this request? Ignores `enabled` — callers check it. */
70
+ function ruleMatches(rule, url, method) {
71
+ if (rule.methods && rule.methods.length > 0) {
72
+ if (!rule.methods.includes(method.toUpperCase())) return false;
73
+ }
74
+ try {
75
+ return compilePattern(rule.urlPattern).test(url);
76
+ } catch {
77
+ // A pattern that can't compile matches nothing rather than throwing inside
78
+ // the app's `send()`. The rule editor validates; this is the backstop.
79
+ return false;
80
+ }
81
+ }