@terreno/syncdb 57.19.2 → 57.20.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 (44) hide show
  1. package/CHANGELOG.md +393 -0
  2. package/README.md +2 -1
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +19 -2
  5. package/dist/client.js.map +1 -1
  6. package/dist/client.test.js +65 -1
  7. package/dist/client.test.js.map +1 -1
  8. package/dist/devConsoleLogger.d.ts +16 -0
  9. package/dist/devConsoleLogger.d.ts.map +1 -0
  10. package/dist/devConsoleLogger.js +162 -0
  11. package/dist/devConsoleLogger.js.map +1 -0
  12. package/dist/devConsoleLogger.test.d.ts +2 -0
  13. package/dist/devConsoleLogger.test.d.ts.map +1 -0
  14. package/dist/devConsoleLogger.test.js +271 -0
  15. package/dist/devConsoleLogger.test.js.map +1 -0
  16. package/dist/index.d.ts +5 -2
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +10 -2
  19. package/dist/index.js.map +1 -1
  20. package/dist/query/localQuery.test.d.ts +2 -0
  21. package/dist/query/localQuery.test.d.ts.map +1 -0
  22. package/dist/query/localQuery.test.js +14 -0
  23. package/dist/query/localQuery.test.js.map +1 -0
  24. package/dist/react/hooks.test.js +51 -2
  25. package/dist/react/hooks.test.js.map +1 -1
  26. package/dist/react/windowHooks.test.js +21 -0
  27. package/dist/react/windowHooks.test.js.map +1 -1
  28. package/dist/sync/httpChannel.d.ts +19 -2
  29. package/dist/sync/httpChannel.d.ts.map +1 -1
  30. package/dist/sync/httpChannel.js +16 -3
  31. package/dist/sync/httpChannel.js.map +1 -1
  32. package/dist/sync/httpChannel.test.js +23 -1
  33. package/dist/sync/httpChannel.test.js.map +1 -1
  34. package/package.json +6 -1
  35. package/src/client.test.ts +68 -1
  36. package/src/client.ts +24 -2
  37. package/src/devConsoleLogger.test.ts +332 -0
  38. package/src/devConsoleLogger.ts +192 -0
  39. package/src/index.ts +16 -1
  40. package/src/query/localQuery.test.ts +16 -0
  41. package/src/react/hooks.test.tsx +62 -2
  42. package/src/react/windowHooks.test.tsx +25 -0
  43. package/src/sync/httpChannel.test.ts +26 -0
  44. package/src/sync/httpChannel.ts +36 -5
@@ -16,7 +16,7 @@ import type {PersisterFactory} from "./persisters/types";
16
16
  import {idbGet} from "./storage/idb";
17
17
  import {SYNC_SCHEMA_VERSION} from "./storage/schema";
18
18
  import {CURSORS_TABLE} from "./storage/types";
19
- import {AuthRequiredError, type HttpChannel} from "./sync/httpChannel";
19
+ import {AuthRequiredError, createHttpChannel, type HttpChannel} from "./sync/httpChannel";
20
20
  import type {SyncTransport} from "./sync/transport";
21
21
  import {createFakeTransport, type FakeTransport} from "./testing/fakeTransport";
22
22
  import type {
@@ -2787,6 +2787,47 @@ describe("createSyncDb", () => {
2787
2787
  });
2788
2788
 
2789
2789
  describe("lifecycle serialization (E1)", () => {
2790
+ it("drops a startup reconcile's streams request that a stop() overtook while it read the token", async () => {
2791
+ // The app stops syncdb, then signs out. A reconcile fired just before the stop is still
2792
+ // awaiting getToken(); sending its request after the stop would carry a token the
2793
+ // sign-out is revoking.
2794
+ let releaseToken = (): void => {};
2795
+ const tokenGate = new Promise<void>((resolve) => {
2796
+ releaseToken = (): void => resolve();
2797
+ });
2798
+ const sent: string[] = [];
2799
+ const httpChannel = createHttpChannel({
2800
+ authProvider: {
2801
+ getToken: async (): Promise<string> => {
2802
+ await tokenGate;
2803
+ return "token";
2804
+ },
2805
+ },
2806
+ baseUrl: "http://api",
2807
+ fetchImpl: async (input: string): Promise<Response> => {
2808
+ sent.push(input);
2809
+ return new Response(JSON.stringify({streams: []}), {status: 200});
2810
+ },
2811
+ });
2812
+ const harness = makeHarness({httpChannel});
2813
+ const client = createSyncDb(harness.config);
2814
+ const originalWarn = console.warn;
2815
+ const warnings: unknown[][] = [];
2816
+ console.warn = (...args: unknown[]): void => {
2817
+ warnings.push(args);
2818
+ };
2819
+ try {
2820
+ await client.start();
2821
+ await client.stop();
2822
+ releaseToken();
2823
+ await flush();
2824
+ } finally {
2825
+ console.warn = originalWarn;
2826
+ }
2827
+ assert.deepEqual(sent, []);
2828
+ assert.deepEqual(warnings, []);
2829
+ });
2830
+
2790
2831
  it("a rapid stop()-then-start() for a new user leaves the new user's persistence working", async () => {
2791
2832
  const name = uniqueName();
2792
2833
  const harness = makeHarness({name});
@@ -2831,6 +2872,32 @@ describe("createSyncDb", () => {
2831
2872
  await reopened.stop();
2832
2873
  });
2833
2874
 
2875
+ it("an auth change queued behind a stop() does not reconnect the stopped client", async () => {
2876
+ const harness = makeHarness();
2877
+ const observable = makeObservableTransport(harness.transport);
2878
+ const client = createSyncDb({...harness.config, transport: observable.transport});
2879
+ // start() subscribes to auth changes, then holds the mutex on its connect.
2880
+ const releaseConnect = observable.gateNextConnect();
2881
+ const startPromise = client.start();
2882
+ await waitUntil(() => observable.events.includes("connect"));
2883
+
2884
+ // A sign-out stops the client while start() is still connecting, and an auth change
2885
+ // (still the same signed-in user) fires before stop() runs: it queues behind the stop.
2886
+ const stopPromise = client.stop();
2887
+ harness.auth.emitAuthChange();
2888
+ releaseConnect();
2889
+ await startPromise;
2890
+ await stopPromise;
2891
+ const eventsAtStop = observable.events.length;
2892
+ const streamsAtStop = harness.http.state.streamsCount;
2893
+ await flush();
2894
+ await flush();
2895
+
2896
+ expect(observable.events.slice(eventsAtStop)).toEqual([]);
2897
+ expect(harness.http.state.streamsCount).toBe(streamsAtStop);
2898
+ expect(client.getSyncStatus().isOnline).toBe(false);
2899
+ });
2900
+
2834
2901
  it("double start() is a no-op: listeners are not double-registered", async () => {
2835
2902
  const harness = makeHarness();
2836
2903
  let onDeltaCalls = 0;
package/src/client.ts CHANGED
@@ -20,7 +20,12 @@ import {bootstrapStream, bootstrapStreamsBatch} from "./sync/bootstrap";
20
20
  import {getAllCursors} from "./sync/cursor";
21
21
  import {applyDelta} from "./sync/deltaApplier";
22
22
  import {repairMarkedEntities} from "./sync/entityRepair";
23
- import {AuthRequiredError, createHttpChannel, type HttpChannel} from "./sync/httpChannel";
23
+ import {
24
+ AuthRequiredError,
25
+ createHttpChannel,
26
+ type HttpChannel,
27
+ RequestSupersededError,
28
+ } from "./sync/httpChannel";
24
29
  import {createReplayCoordinator, type ReplayCoordinator} from "./sync/replayCoordinator";
25
30
  import {createSocketTransport} from "./sync/socketTransport";
26
31
  import type {SendMutationBatchResult, SendMutationResult, SyncTransport} from "./sync/transport";
@@ -830,8 +835,13 @@ export const createSyncDb = (config: SyncDbConfig): SyncDb => {
830
835
  }
831
836
  let serverStreams: {stream: string; collection: string}[];
832
837
  try {
833
- serverStreams = await httpChannel.fetchStreams();
838
+ // A reconcile fired just before a stop() is still reading the token when the app signs
839
+ // out; dropping its request here keeps it from reaching the server with the revoked one.
840
+ serverStreams = await httpChannel.fetchStreams({isSuperseded});
834
841
  } catch (error) {
842
+ if (error instanceof RequestSupersededError) {
843
+ return undefined;
844
+ }
835
845
  if (error instanceof AuthRequiredError) {
836
846
  // INV-2: a 401 is NOT a leave. Pause; leave every stream/entity intact.
837
847
  setAuthPaused(true);
@@ -1792,9 +1802,21 @@ export const createSyncDb = (config: SyncDbConfig): SyncDb => {
1792
1802
  * handler itself is stale — e.g. it was queued behind a stop() while
1793
1803
  * `getUserId()` resolves, and by the time it runs a fresh generation has
1794
1804
  * already started up for a different user.
1805
+ *
1806
+ * An auth change only belongs to the run that subscribed to it. A callback
1807
+ * that fires while a start() still holds the mutex queues behind any stop()
1808
+ * called meanwhile, so it can run after that stop(): by then the client has
1809
+ * no current user, and treating the still-signed-in session as a new
1810
+ * identity would reconnect a stopped client (for example during a sign-out
1811
+ * the app stopped syncdb for). It stands down unless the run it was queued
1812
+ * under is still the started one.
1795
1813
  */
1796
1814
  const handleAuthChange = (): void => {
1815
+ const queuedGeneration = generation;
1797
1816
  void withLifecycle(async (): Promise<void> => {
1817
+ if (!isStarted || generation !== queuedGeneration) {
1818
+ return;
1819
+ }
1798
1820
  const myGeneration = generation;
1799
1821
  const userId = await config.authProvider.getUserId();
1800
1822
  if (generation !== myGeneration) {
@@ -0,0 +1,332 @@
1
+ import {afterEach, beforeEach, describe, expect, it, mock} from "bun:test";
2
+ import {assert} from "chai";
3
+ import {
4
+ installTerrenoDevConsoleLogger,
5
+ resetTerrenoDevConsoleLoggerForTests,
6
+ } from "./devConsoleLogger";
7
+
8
+ const BASE_URL = "http://localhost:4000/";
9
+
10
+ describe("installTerrenoDevConsoleLogger", () => {
11
+ const prevFetch = globalThis.fetch;
12
+
13
+ beforeEach(() => {
14
+ process.env.TERRENO_DEV_CONSOLE_LOGGER_TEST = "true";
15
+ resetTerrenoDevConsoleLoggerForTests();
16
+ });
17
+
18
+ afterEach(() => {
19
+ resetTerrenoDevConsoleLoggerForTests();
20
+ delete process.env.TERRENO_DEV_CONSOLE_LOGGER_TEST;
21
+ globalThis.fetch = prevFetch;
22
+ });
23
+
24
+ it("installs only once per process flag", () => {
25
+ installTerrenoDevConsoleLogger({baseUrl: BASE_URL});
26
+ installTerrenoDevConsoleLogger({baseUrl: BASE_URL});
27
+ const g = globalThis as typeof globalThis & {__TERRENO_CONSOLE_LOGGER__?: boolean};
28
+ expect(g.__TERRENO_CONSOLE_LOGGER__).toBe(true);
29
+ });
30
+
31
+ it("POSTs a single batched payload after debounce with expected shape", async () => {
32
+ const fetchMock = mock((_input: RequestInfo | URL, _init?: RequestInit) =>
33
+ Promise.resolve(new Response(null, {status: 204}))
34
+ );
35
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
36
+
37
+ installTerrenoDevConsoleLogger({baseUrl: BASE_URL});
38
+ console.error("one");
39
+ console.warn("two");
40
+ await new Promise<void>((r) => {
41
+ setTimeout(r, 450);
42
+ });
43
+
44
+ expect(fetchMock.mock.calls.length).toBe(1);
45
+ expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
46
+ "http://localhost:4000/__terreno/browser-logs"
47
+ );
48
+ const init = fetchMock.mock.calls[0]?.[1] as RequestInit | undefined;
49
+ expect(init?.method).toBe("POST");
50
+ const body = JSON.parse(String(init?.body)) as {
51
+ entries: Array<{level: string; message: string}>;
52
+ };
53
+ expect(body.entries.map((e) => e.message)).toEqual(["one", "two"]);
54
+ expect(body.entries[0]?.level).toBe("error");
55
+ expect(body.entries[1]?.level).toBe("warn");
56
+ });
57
+
58
+ it("flushes bursts in server-sized batches", async () => {
59
+ const fetchMock = mock((_input: RequestInfo | URL, _init?: RequestInit) =>
60
+ Promise.resolve(new Response(null, {status: 204}))
61
+ );
62
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
63
+ const originalWarn = console.warn;
64
+ console.warn = (): void => {};
65
+
66
+ try {
67
+ installTerrenoDevConsoleLogger({baseUrl: BASE_URL});
68
+ for (let index = 0; index < 101; index += 1) {
69
+ console.warn(`line-${index}`);
70
+ }
71
+ await new Promise<void>((resolve) => {
72
+ setTimeout(resolve, 450);
73
+ });
74
+ } finally {
75
+ resetTerrenoDevConsoleLoggerForTests();
76
+ console.warn = originalWarn;
77
+ }
78
+
79
+ expect(fetchMock.mock.calls).toHaveLength(2);
80
+ const firstBody = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)) as {
81
+ entries: unknown[];
82
+ };
83
+ const secondBody = JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body)) as {
84
+ entries: unknown[];
85
+ };
86
+ expect(firstBody.entries).toHaveLength(100);
87
+ expect(secondBody.entries).toHaveLength(1);
88
+ });
89
+
90
+ it("does not install outside dev and the test opt-in", (): void => {
91
+ delete process.env.TERRENO_DEV_CONSOLE_LOGGER_TEST;
92
+ installTerrenoDevConsoleLogger({baseUrl: BASE_URL});
93
+ const g = globalThis as typeof globalThis & {__TERRENO_CONSOLE_LOGGER__?: boolean};
94
+ assert.isUndefined(g.__TERRENO_CONSOLE_LOGGER__);
95
+ });
96
+
97
+ it("drops the oldest queued lines once the queue is full", async (): Promise<void> => {
98
+ const fetchMock = mock((_input: RequestInfo | URL, _init?: RequestInit) =>
99
+ Promise.resolve(new Response(null, {status: 204}))
100
+ );
101
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
102
+ const originalWarn = console.warn;
103
+ console.warn = (): void => {};
104
+
105
+ try {
106
+ installTerrenoDevConsoleLogger({baseUrl: BASE_URL});
107
+ for (let index = 0; index < 1001; index += 1) {
108
+ console.warn(`q-${index}`);
109
+ }
110
+ await new Promise<void>((resolve) => {
111
+ setTimeout(resolve, 450);
112
+ });
113
+ } finally {
114
+ resetTerrenoDevConsoleLoggerForTests();
115
+ console.warn = originalWarn;
116
+ }
117
+
118
+ assert.isAtLeast(fetchMock.mock.calls.length, 1);
119
+ const firstBody = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)) as {
120
+ entries: Array<{message: string}>;
121
+ };
122
+ assert.equal(firstBody.entries[0]?.message, "q-1");
123
+ assert.notEqual(firstBody.entries[0]?.message, "q-0");
124
+ });
125
+
126
+ it("gives up when the retry also throws", async (): Promise<void> => {
127
+ const fetchMock = mock(() => Promise.reject(new Error("backend down")));
128
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
129
+ const originalWarn = console.warn;
130
+ console.warn = (): void => {};
131
+
132
+ try {
133
+ installTerrenoDevConsoleLogger({baseUrl: BASE_URL});
134
+ console.warn("drop-me");
135
+ await new Promise<void>((resolve) => {
136
+ setTimeout(resolve, 450);
137
+ });
138
+ } finally {
139
+ resetTerrenoDevConsoleLoggerForTests();
140
+ console.warn = originalWarn;
141
+ }
142
+
143
+ assert.equal(fetchMock.mock.calls.length, 2);
144
+ });
145
+
146
+ it("cancels a pending flush when tests reset the logger", async (): Promise<void> => {
147
+ const fetchMock = mock((_input: RequestInfo | URL, _init?: RequestInit) =>
148
+ Promise.resolve(new Response(null, {status: 204}))
149
+ );
150
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
151
+ installTerrenoDevConsoleLogger({baseUrl: BASE_URL});
152
+ console.warn("pending");
153
+ resetTerrenoDevConsoleLoggerForTests();
154
+ await new Promise<void>((resolve) => {
155
+ setTimeout(resolve, 450);
156
+ });
157
+ assert.equal(fetchMock.mock.calls.length, 0);
158
+ });
159
+
160
+ it("retries a rejected backend batch once", async () => {
161
+ const fetchMock = mock((_input: RequestInfo | URL, _init?: RequestInit) =>
162
+ Promise.resolve(
163
+ new Response(null, {
164
+ status: fetchMock.mock.calls.length === 1 ? 503 : 204,
165
+ })
166
+ )
167
+ );
168
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
169
+ const originalWarn = console.warn;
170
+ console.warn = (): void => {};
171
+
172
+ try {
173
+ installTerrenoDevConsoleLogger({baseUrl: BASE_URL});
174
+ console.warn("retry-me");
175
+ await new Promise<void>((resolve) => {
176
+ setTimeout(resolve, 450);
177
+ });
178
+ } finally {
179
+ resetTerrenoDevConsoleLoggerForTests();
180
+ console.warn = originalWarn;
181
+ }
182
+
183
+ expect(fetchMock.mock.calls).toHaveLength(2);
184
+ });
185
+
186
+ it("captures native and web global errors and restores the native handler", async (): Promise<void> => {
187
+ type GlobalHandler = (error: unknown, isFatal?: boolean) => void;
188
+ const globalRecord = globalThis as typeof globalThis & Record<string, unknown>;
189
+ const originalErrorUtils = Object.getOwnPropertyDescriptor(globalThis, "ErrorUtils");
190
+ const originalWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
191
+ const previousHandler = mock((_error: unknown, _isFatal?: boolean): void => {});
192
+ let globalHandler: GlobalHandler = previousHandler;
193
+ const listeners = new Map<string, (event: unknown) => void>();
194
+ const fetchMock = mock((_input: RequestInfo | URL, _init?: RequestInit) =>
195
+ Promise.resolve(new Response(null, {status: 204}))
196
+ );
197
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
198
+
199
+ Object.defineProperty(globalThis, "ErrorUtils", {
200
+ configurable: true,
201
+ value: {
202
+ getGlobalHandler: (): GlobalHandler => previousHandler,
203
+ setGlobalHandler: (handler: GlobalHandler): void => {
204
+ globalHandler = handler;
205
+ },
206
+ },
207
+ });
208
+ Object.defineProperty(globalThis, "window", {
209
+ configurable: true,
210
+ value: {
211
+ addEventListener: (name: string, listener: (event: unknown) => void): void => {
212
+ listeners.set(name, listener);
213
+ },
214
+ },
215
+ });
216
+
217
+ try {
218
+ installTerrenoDevConsoleLogger({baseUrl: BASE_URL});
219
+ globalHandler(new Error("native error"), true);
220
+ globalHandler("native string");
221
+ listeners.get("unhandledrejection")?.({reason: "promise error"});
222
+ listeners.get("error")?.({error: new Error("web error"), message: "window error"});
223
+ await new Promise<void>((resolve) => {
224
+ setTimeout(resolve, 450);
225
+ });
226
+
227
+ assert.equal(previousHandler.mock.calls.length, 2);
228
+ assert.equal(fetchMock.mock.calls.length, 1);
229
+ const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)) as {
230
+ entries: Array<{message: string; stack?: string}>;
231
+ };
232
+ assert.deepEqual(
233
+ body.entries.map((entry) => entry.message),
234
+ ["native error", "native string", "promise error", "window error"]
235
+ );
236
+ assert.isString(body.entries[0]?.stack);
237
+
238
+ resetTerrenoDevConsoleLoggerForTests();
239
+ assert.equal(globalHandler, previousHandler);
240
+ } finally {
241
+ resetTerrenoDevConsoleLoggerForTests();
242
+ if (originalErrorUtils) {
243
+ Object.defineProperty(globalThis, "ErrorUtils", originalErrorUtils);
244
+ } else {
245
+ Reflect.deleteProperty(globalRecord, "ErrorUtils");
246
+ }
247
+ if (originalWindow) {
248
+ Object.defineProperty(globalThis, "window", originalWindow);
249
+ } else {
250
+ Reflect.deleteProperty(globalRecord, "window");
251
+ }
252
+ }
253
+ });
254
+
255
+ // Web's default ErrorUtils handler rethrows. Metro reports a missing split-bundle module
256
+ // through it while Expo's web asyncRequire probes `import()` targets synchronously, then
257
+ // catches the rethrow and loads the bundle — so nothing failed and nothing should be logged.
258
+ it("does not log an error that the previous web handler rethrows to a catching caller", async (): Promise<void> => {
259
+ type GlobalHandler = (error: unknown, isFatal?: boolean) => void;
260
+ const globalRecord = globalThis as typeof globalThis & Record<string, unknown>;
261
+ const originalErrorUtils = Object.getOwnPropertyDescriptor(globalThis, "ErrorUtils");
262
+ const originalWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
263
+ const rethrowingHandler: GlobalHandler = (error: unknown): void => {
264
+ throw error;
265
+ };
266
+ let globalHandler: GlobalHandler = rethrowingHandler;
267
+ const listeners = new Map<string, (event: unknown) => void>();
268
+ const fetchMock = mock((_input: RequestInfo | URL, _init?: RequestInit) =>
269
+ Promise.resolve(new Response(null, {status: 204}))
270
+ );
271
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
272
+
273
+ Object.defineProperty(globalThis, "ErrorUtils", {
274
+ configurable: true,
275
+ value: {
276
+ getGlobalHandler: (): GlobalHandler => rethrowingHandler,
277
+ setGlobalHandler: (handler: GlobalHandler): void => {
278
+ globalHandler = handler;
279
+ },
280
+ },
281
+ });
282
+ Object.defineProperty(globalThis, "window", {
283
+ configurable: true,
284
+ value: {
285
+ addEventListener: (name: string, listener: (event: unknown) => void): void => {
286
+ listeners.set(name, listener);
287
+ },
288
+ },
289
+ });
290
+
291
+ try {
292
+ installTerrenoDevConsoleLogger({baseUrl: BASE_URL});
293
+ const probeError = new Error('Requiring unknown module "2746".');
294
+ let caught: unknown;
295
+ try {
296
+ globalHandler(probeError, true);
297
+ } catch (error) {
298
+ caught = error;
299
+ }
300
+ assert.strictEqual(caught, probeError);
301
+
302
+ // A rethrown error that nobody catches reaches the window listeners, with its stack.
303
+ const uncaught = new Error("lazy chunk failed");
304
+ listeners.get("unhandledrejection")?.({reason: uncaught});
305
+ await new Promise<void>((resolve) => {
306
+ setTimeout(resolve, 450);
307
+ });
308
+
309
+ assert.equal(fetchMock.mock.calls.length, 1);
310
+ const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)) as {
311
+ entries: Array<{message: string; stack?: string}>;
312
+ };
313
+ assert.deepEqual(
314
+ body.entries.map((entry) => entry.message),
315
+ ["Error: lazy chunk failed"]
316
+ );
317
+ assert.include(body.entries[0]?.stack ?? "", "lazy chunk failed");
318
+ } finally {
319
+ resetTerrenoDevConsoleLoggerForTests();
320
+ if (originalErrorUtils) {
321
+ Object.defineProperty(globalThis, "ErrorUtils", originalErrorUtils);
322
+ } else {
323
+ Reflect.deleteProperty(globalRecord, "ErrorUtils");
324
+ }
325
+ if (originalWindow) {
326
+ Object.defineProperty(globalThis, "window", originalWindow);
327
+ } else {
328
+ Reflect.deleteProperty(globalRecord, "window");
329
+ }
330
+ }
331
+ });
332
+ });
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Dev-only bridge that ships client console errors to the backend's
3
+ * `POST /__terreno/browser-logs` route so `read_logs` / `last_error` (terreno-mcp-local)
4
+ * and `terreno logs --sources browser` can read them.
5
+ *
6
+ * Lives in syncdb (not @terreno/rtk) so apps that have dropped RTK keep the bridge.
7
+ * Exposed from the package root and from the `@terreno/syncdb/devConsoleLogger`
8
+ * subpath; the subpath lets `@terreno/rtk`'s deprecated re-export pull in this file
9
+ * without bundling the sync client.
10
+ */
11
+ import {DateTime} from "luxon";
12
+
13
+ // Metro/React Native global; undefined under Node and Bun.
14
+ declare const __DEV__: boolean | undefined;
15
+
16
+ export interface InstallTerrenoDevConsoleLoggerArgs {
17
+ /** API origin that serves `/__terreno/browser-logs`, e.g. `baseUrl` from `@terreno/rtk`. */
18
+ baseUrl: string;
19
+ }
20
+
21
+ interface Queued {
22
+ level: string;
23
+ message: string;
24
+ stack?: string;
25
+ timestamp: string;
26
+ }
27
+
28
+ const MAX_BATCH_ENTRIES = 100;
29
+ const MAX_QUEUE_ENTRIES = 1000;
30
+
31
+ let queue: Queued[] = [];
32
+ let flushTimer: ReturnType<typeof setTimeout> | undefined;
33
+ let restoreConsole: (() => void) | undefined;
34
+ let restoreErrorUtils: (() => void) | undefined;
35
+ let logsUrl = "";
36
+
37
+ const postEntries = async (url: string, entries: Queued[]): Promise<Response> => {
38
+ return fetch(url, {
39
+ body: JSON.stringify({entries}),
40
+ headers: {"Content-Type": "application/json"},
41
+ method: "POST",
42
+ });
43
+ };
44
+
45
+ const isDevOrTestInstall = (): boolean => {
46
+ if (typeof __DEV__ !== "undefined" && __DEV__) {
47
+ return true;
48
+ }
49
+ if (process.env.TERRENO_DEV_CONSOLE_LOGGER_TEST === "true") {
50
+ return true;
51
+ }
52
+ return false;
53
+ };
54
+
55
+ const flush = async (): Promise<void> => {
56
+ if (queue.length === 0) {
57
+ return;
58
+ }
59
+ const pending = queue;
60
+ queue = [];
61
+ const url = logsUrl;
62
+ for (let offset = 0; offset < pending.length; offset += MAX_BATCH_ENTRIES) {
63
+ const entries = pending.slice(offset, offset + MAX_BATCH_ENTRIES);
64
+ try {
65
+ const response = await postEntries(url, entries);
66
+ if (!response.ok) {
67
+ await postEntries(url, entries);
68
+ }
69
+ } catch {
70
+ try {
71
+ await postEntries(url, entries);
72
+ } catch {
73
+ // Dev-only bridge; never break the app if the backend is down.
74
+ }
75
+ }
76
+ }
77
+ };
78
+
79
+ const scheduleFlush = (): void => {
80
+ if (flushTimer) {
81
+ return;
82
+ }
83
+ flushTimer = setTimeout(() => {
84
+ flushTimer = undefined;
85
+ void flush();
86
+ }, 400);
87
+ };
88
+
89
+ const push = (level: string, message: string, stack?: string): void => {
90
+ if (queue.length >= MAX_QUEUE_ENTRIES) {
91
+ queue.splice(0, queue.length - MAX_QUEUE_ENTRIES + 1);
92
+ }
93
+ queue.push({
94
+ level,
95
+ message: message.slice(0, 8000),
96
+ stack,
97
+ timestamp: DateTime.now().toISO(),
98
+ });
99
+ scheduleFlush();
100
+ };
101
+
102
+ /**
103
+ * Test-only teardown: clears timers, restores patched globals, and allows
104
+ * `installTerrenoDevConsoleLogger` to run again. Not exported from the package root.
105
+ */
106
+ export const resetTerrenoDevConsoleLoggerForTests = (): void => {
107
+ if (flushTimer) {
108
+ clearTimeout(flushTimer);
109
+ }
110
+ flushTimer = undefined;
111
+ queue = [];
112
+ restoreConsole?.();
113
+ restoreConsole = undefined;
114
+ restoreErrorUtils?.();
115
+ restoreErrorUtils = undefined;
116
+ logsUrl = "";
117
+ const g = globalThis as typeof globalThis & {__TERRENO_CONSOLE_LOGGER__?: boolean};
118
+ delete g.__TERRENO_CONSOLE_LOGGER__;
119
+ };
120
+
121
+ /**
122
+ * Batches `console.error` / `console.warn`, React Native `ErrorUtils`, and web
123
+ * `window` error hooks to `POST {baseUrl}/__terreno/browser-logs` (dev-only backend route).
124
+ * No-op outside `__DEV__`; installs at most once per JS runtime.
125
+ */
126
+ export const installTerrenoDevConsoleLogger = ({
127
+ baseUrl,
128
+ }: InstallTerrenoDevConsoleLoggerArgs): void => {
129
+ if (!isDevOrTestInstall()) {
130
+ return;
131
+ }
132
+ const g = globalThis as typeof globalThis & {__TERRENO_CONSOLE_LOGGER__?: boolean};
133
+ if (g.__TERRENO_CONSOLE_LOGGER__) {
134
+ return;
135
+ }
136
+ g.__TERRENO_CONSOLE_LOGGER__ = true;
137
+ logsUrl = `${baseUrl.replace(/\/$/, "")}/__terreno/browser-logs`;
138
+
139
+ const origError = console.error.bind(console);
140
+ const origWarn = console.warn.bind(console);
141
+ restoreConsole = (): void => {
142
+ console.error = origError;
143
+ console.warn = origWarn;
144
+ };
145
+ console.error = (...args: unknown[]): void => {
146
+ push("error", args.map(String).join(" "));
147
+ origError(...args);
148
+ };
149
+ console.warn = (...args: unknown[]): void => {
150
+ push("warn", args.map(String).join(" "));
151
+ origWarn(...args);
152
+ };
153
+
154
+ const errorUtils = (globalThis as Record<string, unknown>).ErrorUtils as
155
+ | {
156
+ getGlobalHandler?: () => (error: unknown, isFatal?: boolean) => void;
157
+ setGlobalHandler?: (handler: (error: unknown, isFatal?: boolean) => void) => void;
158
+ }
159
+ | undefined;
160
+ if (errorUtils?.setGlobalHandler) {
161
+ const prev = errorUtils.getGlobalHandler?.();
162
+ errorUtils.setGlobalHandler((error: unknown, isFatal?: boolean) => {
163
+ // Record the error only once a handler has consumed it. Web's default handler rethrows,
164
+ // so the error is still propagating and its caller may recover: Metro reports a missing
165
+ // split-bundle module here while Expo's web asyncRequire probes an `import()` target
166
+ // synchronously, then catches the rethrow and loads the bundle. A rethrown error that
167
+ // nothing catches reaches the window "error" / "unhandledrejection" listeners below.
168
+ prev?.(error, isFatal);
169
+ if (error instanceof Error) {
170
+ push("error", error.message, error.stack);
171
+ } else {
172
+ push("error", String(error));
173
+ }
174
+ });
175
+ restoreErrorUtils = (): void => {
176
+ if (prev) {
177
+ errorUtils.setGlobalHandler?.(prev);
178
+ }
179
+ };
180
+ }
181
+
182
+ if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
183
+ window.addEventListener("unhandledrejection", (ev: PromiseRejectionEvent) => {
184
+ const st = ev.reason instanceof Error ? ev.reason.stack : undefined;
185
+ push("error", String(ev.reason ?? "unhandledrejection"), st);
186
+ });
187
+ window.addEventListener("error", (ev: ErrorEvent) => {
188
+ const st = ev.error instanceof Error ? ev.error.stack : undefined;
189
+ push("error", String(ev.message ?? "window.error"), st);
190
+ });
191
+ }
192
+ };