@terreno/syncdb 57.3.0 → 57.6.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 (160) hide show
  1. package/README.md +3 -3
  2. package/dist/auth/betterAuthAdapter.js +1 -1
  3. package/dist/auth/betterAuthAdapter.js.map +1 -1
  4. package/dist/auth/betterAuthReactClient.d.ts +17 -0
  5. package/dist/auth/betterAuthReactClient.d.ts.map +1 -0
  6. package/dist/auth/betterAuthReactClient.js +11 -0
  7. package/dist/auth/betterAuthReactClient.js.map +1 -0
  8. package/dist/auth/betterAuthReactClient.test.d.ts +2 -0
  9. package/dist/auth/betterAuthReactClient.test.d.ts.map +1 -0
  10. package/dist/auth/betterAuthReactClient.test.js +43 -0
  11. package/dist/auth/betterAuthReactClient.test.js.map +1 -0
  12. package/dist/client.adminWindowMutation.test.d.ts +2 -0
  13. package/dist/client.adminWindowMutation.test.d.ts.map +1 -0
  14. package/dist/client.adminWindowMutation.test.js +65 -0
  15. package/dist/client.adminWindowMutation.test.js.map +1 -0
  16. package/dist/client.d.ts +22 -0
  17. package/dist/client.d.ts.map +1 -1
  18. package/dist/client.js +89 -12
  19. package/dist/client.js.map +1 -1
  20. package/dist/client.test.js +308 -12
  21. package/dist/client.test.js.map +1 -1
  22. package/dist/codegen/emitSdk.js +3 -3
  23. package/dist/codegen/emitSdk.js.map +1 -1
  24. package/dist/codegen/generate.test.js +32 -2
  25. package/dist/codegen/generate.test.js.map +1 -1
  26. package/dist/codegen/safeIdentifiers.d.ts +5 -0
  27. package/dist/codegen/safeIdentifiers.d.ts.map +1 -1
  28. package/dist/codegen/safeIdentifiers.js +8 -0
  29. package/dist/codegen/safeIdentifiers.js.map +1 -1
  30. package/dist/codegen/safeIdentifiers.test.js +20 -8
  31. package/dist/codegen/safeIdentifiers.test.js.map +1 -1
  32. package/dist/codegen/types.d.ts +4 -3
  33. package/dist/codegen/types.d.ts.map +1 -1
  34. package/dist/crypto/keyProviders.js +1 -1
  35. package/dist/crypto/keyProviders.js.map +1 -1
  36. package/dist/debug/debugChannel.test.js +5 -0
  37. package/dist/debug/debugChannel.test.js.map +1 -1
  38. package/dist/debug/debugLog.d.ts +1 -0
  39. package/dist/debug/debugLog.d.ts.map +1 -1
  40. package/dist/debug/debugLog.js +1 -0
  41. package/dist/debug/debugLog.js.map +1 -1
  42. package/dist/debug/devtools.d.ts +6 -0
  43. package/dist/debug/devtools.d.ts.map +1 -0
  44. package/dist/debug/devtools.js +111 -0
  45. package/dist/debug/devtools.js.map +1 -0
  46. package/dist/debug/devtools.test.d.ts +2 -0
  47. package/dist/debug/devtools.test.d.ts.map +1 -0
  48. package/dist/debug/devtools.test.js +168 -0
  49. package/dist/debug/devtools.test.js.map +1 -0
  50. package/dist/index.d.ts +1 -0
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +1 -0
  53. package/dist/index.js.map +1 -1
  54. package/dist/isolated/defaultPersisterFactoryNativeErrors.isolated.d.ts +2 -0
  55. package/dist/isolated/defaultPersisterFactoryNativeErrors.isolated.d.ts.map +1 -0
  56. package/dist/isolated/defaultPersisterFactoryNativeErrors.isolated.js +19 -0
  57. package/dist/isolated/defaultPersisterFactoryNativeErrors.isolated.js.map +1 -0
  58. package/dist/mutations/outbox.d.ts +7 -3
  59. package/dist/mutations/outbox.d.ts.map +1 -1
  60. package/dist/mutations/outbox.js +6 -0
  61. package/dist/mutations/outbox.js.map +1 -1
  62. package/dist/mutations/outbox.test.js +17 -0
  63. package/dist/mutations/outbox.test.js.map +1 -1
  64. package/dist/react/collectionHooks.js +2 -2
  65. package/dist/react/collectionHooks.js.map +1 -1
  66. package/dist/storage/idb.d.ts +1 -0
  67. package/dist/storage/idb.d.ts.map +1 -1
  68. package/dist/storage/idb.js +1 -0
  69. package/dist/storage/idb.js.map +1 -1
  70. package/dist/storage/schema.d.ts.map +1 -1
  71. package/dist/storage/schema.js +1 -0
  72. package/dist/storage/schema.js.map +1 -1
  73. package/dist/storage/store.d.ts +3 -2
  74. package/dist/storage/store.d.ts.map +1 -1
  75. package/dist/storage/store.test.js +6 -6
  76. package/dist/storage/store.test.js.map +1 -1
  77. package/dist/storage/types.d.ts +1 -7
  78. package/dist/storage/types.d.ts.map +1 -1
  79. package/dist/sync/deltaApplier.d.ts +2 -0
  80. package/dist/sync/deltaApplier.d.ts.map +1 -1
  81. package/dist/sync/deltaApplier.js +9 -0
  82. package/dist/sync/deltaApplier.js.map +1 -1
  83. package/dist/sync/deltaApplier.test.js +63 -0
  84. package/dist/sync/deltaApplier.test.js.map +1 -1
  85. package/dist/sync/entityRepair.d.ts +1 -0
  86. package/dist/sync/entityRepair.d.ts.map +1 -1
  87. package/dist/sync/entityRepair.js +1 -0
  88. package/dist/sync/entityRepair.js.map +1 -1
  89. package/dist/sync/httpChannel.d.ts +3 -1
  90. package/dist/sync/httpChannel.d.ts.map +1 -1
  91. package/dist/sync/httpChannel.js +3 -1
  92. package/dist/sync/httpChannel.js.map +1 -1
  93. package/dist/sync/httpChannel.test.js +68 -0
  94. package/dist/sync/httpChannel.test.js.map +1 -1
  95. package/dist/sync/replayCoordinator.d.ts +6 -12
  96. package/dist/sync/replayCoordinator.d.ts.map +1 -1
  97. package/dist/sync/replayCoordinator.js +44 -16
  98. package/dist/sync/replayCoordinator.js.map +1 -1
  99. package/dist/sync/replayCoordinator.test.js +29 -10
  100. package/dist/sync/replayCoordinator.test.js.map +1 -1
  101. package/dist/sync/socketTransport.d.ts +3 -45
  102. package/dist/sync/socketTransport.d.ts.map +1 -1
  103. package/dist/sync/socketTransport.js +73 -9
  104. package/dist/sync/socketTransport.js.map +1 -1
  105. package/dist/sync/socketTransport.test.js +41 -1
  106. package/dist/sync/socketTransport.test.js.map +1 -1
  107. package/dist/sync/transport.d.ts +9 -1
  108. package/dist/sync/transport.d.ts.map +1 -1
  109. package/dist/sync/transport.js +1 -1
  110. package/dist/sync/transport.js.map +1 -1
  111. package/dist/sync/windowHydrate.d.ts +25 -0
  112. package/dist/sync/windowHydrate.d.ts.map +1 -0
  113. package/dist/sync/windowHydrate.js +67 -0
  114. package/dist/sync/windowHydrate.js.map +1 -0
  115. package/dist/sync/windowHydrate.test.d.ts +2 -0
  116. package/dist/sync/windowHydrate.test.d.ts.map +1 -0
  117. package/dist/sync/windowHydrate.test.js +164 -0
  118. package/dist/sync/windowHydrate.test.js.map +1 -0
  119. package/dist/testing/fakeTransport.js +1 -1
  120. package/dist/testing/fakeTransport.js.map +1 -1
  121. package/dist/types.d.ts +15 -0
  122. package/dist/types.d.ts.map +1 -1
  123. package/package.json +9 -4
  124. package/src/auth/betterAuthReactClient.test.ts +50 -0
  125. package/src/auth/betterAuthReactClient.ts +33 -0
  126. package/src/client.adminWindowMutation.test.ts +69 -0
  127. package/src/client.test.ts +321 -3
  128. package/src/client.ts +125 -8
  129. package/src/codegen/emitSdk.ts +3 -3
  130. package/src/codegen/generate.test.ts +35 -2
  131. package/src/codegen/safeIdentifiers.test.ts +37 -10
  132. package/src/codegen/safeIdentifiers.ts +17 -0
  133. package/src/codegen/types.ts +3 -3
  134. package/src/debug/debugChannel.test.ts +6 -0
  135. package/src/debug/debugLog.ts +1 -0
  136. package/src/debug/devtools.test.ts +234 -0
  137. package/src/debug/devtools.ts +196 -0
  138. package/src/index.ts +4 -0
  139. package/src/isolated/defaultPersisterFactoryNativeErrors.isolated.ts +23 -0
  140. package/src/mutations/outbox.test.ts +20 -0
  141. package/src/mutations/outbox.ts +11 -3
  142. package/src/react/collectionHooks.ts +2 -2
  143. package/src/storage/idb.ts +1 -0
  144. package/src/storage/schema.ts +1 -0
  145. package/src/storage/store.ts +2 -2
  146. package/src/storage/types.ts +1 -8
  147. package/src/sync/deltaApplier.test.ts +70 -0
  148. package/src/sync/deltaApplier.ts +10 -0
  149. package/src/sync/entityRepair.ts +1 -0
  150. package/src/sync/httpChannel.test.ts +82 -0
  151. package/src/sync/httpChannel.ts +5 -0
  152. package/src/sync/replayCoordinator.test.ts +28 -0
  153. package/src/sync/replayCoordinator.ts +53 -14
  154. package/src/sync/socketTransport.test.ts +45 -2
  155. package/src/sync/socketTransport.ts +106 -20
  156. package/src/sync/transport.ts +7 -1
  157. package/src/sync/windowHydrate.test.ts +179 -0
  158. package/src/sync/windowHydrate.ts +97 -0
  159. package/src/testing/fakeTransport.ts +1 -1
  160. package/src/types.ts +16 -0
@@ -220,6 +220,29 @@ describe("generateSyncDbSdk", () => {
220
220
  }
221
221
  });
222
222
 
223
+ it("applies retries: true and numeric overrides", async () => {
224
+ const dir = await mkdtemp(join(tmpdir(), "syncdb-codegen-"));
225
+ const out = join(dir, "syncDbSdk.ts");
226
+ try {
227
+ const enabled = await generateSyncDbSdk({
228
+ config: {overrides: {todos: {retries: true}}},
229
+ format: false,
230
+ out,
231
+ schema: fixturePath,
232
+ });
233
+ expect(enabled).toContain("retries: true");
234
+ const numbered = await generateSyncDbSdk({
235
+ config: {overrides: {todos: {retries: 4}}},
236
+ format: false,
237
+ out,
238
+ schema: fixturePath,
239
+ });
240
+ expect(numbered).toContain("retries: 4");
241
+ } finally {
242
+ await rm(dir, {force: true, recursive: true});
243
+ }
244
+ });
245
+
223
246
  it("formats the generated file when format is true", async () => {
224
247
  const dir = await mkdtemp(join(tmpdir(), "syncdb-codegen-"));
225
248
  const out = join(dir, "syncDbSdk.ts");
@@ -236,7 +259,7 @@ describe("generateSyncDbSdk", () => {
236
259
  }
237
260
  });
238
261
 
239
- it("rejects collection names that are not TypeScript identifiers", async () => {
262
+ it("rejects unsafe sync collection names", async () => {
240
263
  const spec = await loadSpec(fixturePath);
241
264
  const discovered = discoverCollections({spec});
242
265
  const first = discovered[0];
@@ -252,7 +275,17 @@ describe("generateSyncDbSdk", () => {
252
275
  },
253
276
  ],
254
277
  })
255
- ).toThrow(/not a TypeScript identifier/);
278
+ ).toThrow(/not a valid sync collection name/);
279
+ });
280
+
281
+ it("rejects invalid retries overrides", async () => {
282
+ const spec = await loadSpec(fixturePath);
283
+ const first = discoverCollections({spec})[0];
284
+ expect(() =>
285
+ emitSdk({
286
+ collections: [{...first, retries: Number.NaN}],
287
+ })
288
+ ).toThrow(/Invalid retries/);
256
289
  });
257
290
  });
258
291
 
@@ -1,32 +1,59 @@
1
- import {describe, expect, it} from "bun:test";
1
+ import {describe, it} from "bun:test";
2
+ import {assert} from "chai";
2
3
 
3
- import {assertTsIdentifier, emitTsPropertyKey, emitTsString} from "./safeIdentifiers";
4
+ import {
5
+ assertSyncCollectionName,
6
+ assertTsIdentifier,
7
+ emitTsPropertyKey,
8
+ emitTsString,
9
+ } from "./safeIdentifiers";
4
10
 
5
11
  describe("assertTsIdentifier", () => {
6
12
  it("accepts TypeScript identifiers", () => {
7
- expect(assertTsIdentifier({label: "name", value: "Todo"})).toBe("Todo");
8
- expect(assertTsIdentifier({label: "name", value: "_id"})).toBe("_id");
13
+ assert.equal(assertTsIdentifier({label: "name", value: "Todo"}), "Todo");
14
+ assert.equal(assertTsIdentifier({label: "name", value: "_id"}), "_id");
9
15
  });
10
16
 
11
17
  it("rejects quote and statement injection", () => {
12
- expect(() =>
13
- assertTsIdentifier({label: "collection", value: 'todos"; process.exit(1); //'})
14
- ).toThrow(/not a TypeScript identifier/);
18
+ assert.throws(
19
+ () => assertTsIdentifier({label: "collection", value: 'todos"; process.exit(1); //'}),
20
+ /not a TypeScript identifier/
21
+ );
22
+ });
23
+ });
24
+
25
+ describe("assertSyncCollectionName", () => {
26
+ it("accepts hyphenated collection names", () => {
27
+ assert.equal(
28
+ assertSyncCollectionName({label: "collection", value: "notification-preferences"}),
29
+ "notification-preferences"
30
+ );
31
+ });
32
+
33
+ it("rejects unsafe collection names", () => {
34
+ assert.throws(
35
+ () =>
36
+ assertSyncCollectionName({
37
+ label: "collection",
38
+ value: 'notifications"; process.exit(1); //',
39
+ }),
40
+ /not a valid sync collection name/
41
+ );
15
42
  });
16
43
  });
17
44
 
18
45
  describe("emitTsString", () => {
19
46
  it("JSON-escapes quotes so they cannot close a generated string", () => {
20
- expect(emitTsString('todos"; process.exit(1); //')).toBe('"todos\\"; process.exit(1); //"');
47
+ assert.equal(emitTsString('todos"; process.exit(1); //'), '"todos\\"; process.exit(1); //"');
21
48
  });
22
49
  });
23
50
 
24
51
  describe("emitTsPropertyKey", () => {
25
52
  it("emits bare identifiers", () => {
26
- expect(emitTsPropertyKey("title")).toBe("title");
53
+ assert.equal(emitTsPropertyKey("title"), "title");
27
54
  });
28
55
 
29
56
  it("quotes keys that are not identifiers", () => {
30
- expect(emitTsPropertyKey('foo"; bar')).toBe('"foo\\"; bar"');
57
+ assert.equal(emitTsPropertyKey('foo"; bar'), '"foo\\"; bar"');
31
58
  });
32
59
  });
@@ -1,4 +1,5 @@
1
1
  const TS_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
2
+ const SYNC_COLLECTION = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
2
3
 
3
4
  export const assertTsIdentifier = ({label, value}: {label: string; value: string}): string => {
4
5
  if (!TS_IDENTIFIER.test(value)) {
@@ -7,6 +8,22 @@ export const assertTsIdentifier = ({label, value}: {label: string; value: string
7
8
  return value;
8
9
  };
9
10
 
11
+ /** Sync collection tags may use hyphens (e.g. notification-preferences) but must be safe in JSON strings. */
12
+ export const assertSyncCollectionName = ({
13
+ label,
14
+ value,
15
+ }: {
16
+ label: string;
17
+ value: string;
18
+ }): string => {
19
+ if (!SYNC_COLLECTION.test(value)) {
20
+ throw new Error(
21
+ `Invalid ${label}: ${JSON.stringify(value)} is not a valid sync collection name`
22
+ );
23
+ }
24
+ return value;
25
+ };
26
+
10
27
  export const emitTsString = (value: string): string => JSON.stringify(value);
11
28
 
12
29
  export const emitTsPropertyKey = (key: string): string => {
@@ -1,4 +1,4 @@
1
- export interface TerrenoSyncExtension {
1
+ interface TerrenoSyncExtension {
2
2
  collection: string;
3
3
  scope: string;
4
4
  }
@@ -18,7 +18,7 @@ export interface OpenApiSchema {
18
18
  description?: string;
19
19
  }
20
20
 
21
- export interface OpenApiOperation {
21
+ interface OpenApiOperation {
22
22
  "x-terreno-sync"?: TerrenoSyncExtension;
23
23
  requestBody?: {
24
24
  content?: Record<string, {schema?: OpenApiSchema}>;
@@ -31,7 +31,7 @@ export interface OpenApiOperation {
31
31
  >;
32
32
  }
33
33
 
34
- export interface OpenApiPathItem {
34
+ interface OpenApiPathItem {
35
35
  get?: OpenApiOperation;
36
36
  post?: OpenApiOperation;
37
37
  patch?: OpenApiOperation;
@@ -118,4 +118,10 @@ describe("attachDebugChannel", () => {
118
118
 
119
119
  expect(debuggerLog.getEvents()).toHaveLength(0);
120
120
  });
121
+
122
+ it("uses BroadcastChannel when the runtime provides it", () => {
123
+ const log = createSyncDebugLog();
124
+ const bridge = attachDebugChannel({log, name: "factory-probe"});
125
+ bridge?.close();
126
+ });
121
127
  });
@@ -148,6 +148,7 @@ const emptyByType = (): Record<SyncDebugEventType, number> => ({
148
148
  /**
149
149
  * Create an in-memory debug log backed by a circular buffer.
150
150
  */
151
+ /** @internal */
151
152
  export const createSyncDebugLog = (options: SyncDebugLogOptions = {}): SyncDebugLog => {
152
153
  const capacity = Math.max(1, options.capacity ?? DEFAULT_CAPACITY);
153
154
  const clock = options.clock ?? ((): string => DateTime.now().toISO() ?? new Date().toISOString());
@@ -0,0 +1,234 @@
1
+ import {afterEach, describe, it} from "bun:test";
2
+ import {assert} from "chai";
3
+
4
+ import {createSyncDb, type SyncDb} from "../client";
5
+ import {OUTBOX_TABLE} from "../storage/types";
6
+ import {createFakeTransport} from "../testing/fakeTransport";
7
+
8
+ interface TestDevtoolsInspect {
9
+ collections: Record<
10
+ string,
11
+ {entities: Array<{data: unknown; id: string; seq: number}>; total: number; truncated: boolean}
12
+ >;
13
+ debug?: {events: unknown[]};
14
+ outbox: Record<string, {args?: unknown}>;
15
+ status: {online?: boolean};
16
+ }
17
+
18
+ interface TestDevtoolsClient {
19
+ inspect: (options?: Record<string, unknown>) => TestDevtoolsInspect;
20
+ snapshot: (
21
+ options?: Record<string, unknown>
22
+ ) => TestDevtoolsInspect & {mergeableContent: unknown};
23
+ setLocalEntity: (args: Record<string, unknown>) => void;
24
+ deleteLocalEntity: (args: Record<string, unknown>) => void;
25
+ merge: (content: unknown) => void;
26
+ mutate: (args: Record<string, unknown>) => unknown;
27
+ flush: () => Promise<void>;
28
+ reconcile: () => Promise<void>;
29
+ forceResync: () => Promise<unknown>;
30
+ resolveConflict: (args: Record<string, unknown>) => void;
31
+ retryFailed: (args: Record<string, unknown>) => void;
32
+ goOffline: () => void;
33
+ goOnline: () => Promise<void>;
34
+ clearDebug: () => void;
35
+ }
36
+
37
+ interface TestDevtoolsRegistry {
38
+ clients: Record<string, TestDevtoolsClient>;
39
+ list: () => string[];
40
+ }
41
+
42
+ const getRegistry = (): TestDevtoolsRegistry | undefined => {
43
+ return (
44
+ globalThis as typeof globalThis & {
45
+ __TERRENO_SYNCDB__?: TestDevtoolsRegistry;
46
+ }
47
+ ).__TERRENO_SYNCDB__;
48
+ };
49
+
50
+ const createDebugClient = ({name}: {name: string}): SyncDb => {
51
+ return createSyncDb({
52
+ authProvider: {
53
+ getToken: async (): Promise<string | null> => "token",
54
+ getUserId: async (): Promise<string | null> => "user-1",
55
+ onAuthChange:
56
+ (_callback: () => void): (() => void) =>
57
+ (): void => {},
58
+ },
59
+ collections: ["todos", "notes"],
60
+ debug: true,
61
+ name,
62
+ reconcileIntervalMs: 0,
63
+ transport: createFakeTransport(),
64
+ });
65
+ };
66
+
67
+ afterEach((): void => {
68
+ Reflect.deleteProperty(globalThis, "__TERRENO_SYNCDB__");
69
+ });
70
+
71
+ describe("SyncDB devtools registry", () => {
72
+ it("registers debug clients with debugger state and mutation controls", async (): Promise<void> => {
73
+ const client = createDebugClient({name: "devtools-test"});
74
+ await client.start();
75
+
76
+ const registry = getRegistry();
77
+ assert.include(registry?.list() ?? [], "devtools-test");
78
+ const bridge = registry?.clients["devtools-test"];
79
+ assert.exists(bridge);
80
+
81
+ bridge.setLocalEntity({
82
+ collection: "todos",
83
+ data: {password: "visible-to-MCP-redactor", title: "Local"},
84
+ id: "todo-1",
85
+ seq: 4,
86
+ stream: "todos|owner:user-1",
87
+ });
88
+ const state = bridge.inspect();
89
+ assert.equal(state?.collections.todos?.entities[0]?.id, "todo-1");
90
+ assert.equal(state?.collections.todos?.entities[0]?.seq, 4);
91
+ assert.exists(state?.debug);
92
+
93
+ const snapshot = bridge.snapshot();
94
+ bridge.deleteLocalEntity({collection: "todos", id: "todo-1"});
95
+ assert.lengthOf(bridge.inspect().collections.todos?.entities ?? [], 0);
96
+ bridge.merge(snapshot.mergeableContent);
97
+ assert.lengthOf(bridge.inspect().collections.todos?.entities ?? [], 0);
98
+
99
+ bridge.mutate({
100
+ collection: "todos",
101
+ data: {title: "Updated"},
102
+ id: "todo-1",
103
+ operation: "update",
104
+ });
105
+ await bridge.flush();
106
+ assert.equal(
107
+ (bridge.inspect().collections.todos?.entities[0]?.data as {title?: string})?.title,
108
+ "Updated"
109
+ );
110
+ await client.stop();
111
+ });
112
+
113
+ it("CRDT-merges snapshot content instead of replacing newer local rows", async (): Promise<void> => {
114
+ const client = createDebugClient({name: "merge-test"});
115
+ await client.start();
116
+ const bridge = getRegistry()?.clients["merge-test"];
117
+ assert.exists(bridge);
118
+
119
+ bridge.setLocalEntity({
120
+ collection: "todos",
121
+ data: {title: "Original"},
122
+ id: "todo-1",
123
+ seq: 1,
124
+ stream: "todos|owner:user-1",
125
+ });
126
+ const snapshot = bridge.snapshot();
127
+ bridge.setLocalEntity({
128
+ collection: "todos",
129
+ data: {title: "Newer"},
130
+ id: "todo-1",
131
+ seq: 2,
132
+ stream: "todos|owner:user-1",
133
+ });
134
+ bridge.setLocalEntity({
135
+ collection: "notes",
136
+ data: {title: "Kept"},
137
+ id: "note-1",
138
+ seq: 1,
139
+ stream: "notes|owner:user-1",
140
+ });
141
+ bridge.merge(snapshot.mergeableContent);
142
+
143
+ const state = bridge.inspect();
144
+ assert.equal((state.collections.todos?.entities[0]?.data as {title?: string})?.title, "Newer");
145
+ assert.equal(state.collections.notes?.entities[0]?.id, "note-1");
146
+ await client.stop();
147
+ });
148
+
149
+ it("exposes inspect filters, outbox decoding, and remaining debugger controls", async (): Promise<void> => {
150
+ const first = createDebugClient({name: "zeta-client"});
151
+ const second = createDebugClient({name: "alpha-client"});
152
+ await first.start();
153
+ await second.start();
154
+ const registry = getRegistry();
155
+ assert.deepEqual(registry?.list(), ["alpha-client", "zeta-client"]);
156
+ const bridge = registry?.clients["alpha-client"];
157
+ assert.exists(bridge);
158
+
159
+ bridge.setLocalEntity({
160
+ collection: "todos",
161
+ data: {title: "One"},
162
+ id: "todo-1",
163
+ seq: 1,
164
+ stream: "todos|owner:user-1",
165
+ });
166
+ bridge.setLocalEntity({
167
+ collection: "todos",
168
+ data: {title: "Two"},
169
+ id: "todo-2",
170
+ seq: 1,
171
+ stream: "todos|owner:user-1",
172
+ });
173
+ second.store.raw.setRow(OUTBOX_TABLE, "m-json", {
174
+ args: JSON.stringify({title: "queued"}),
175
+ collection: "todos",
176
+ });
177
+ second.store.raw.setRow(OUTBOX_TABLE, "m-invalid", {
178
+ args: "{not-json",
179
+ collection: "todos",
180
+ });
181
+
182
+ const filtered = bridge.inspect({collection: "todos", entityId: "todo-2", limit: 1});
183
+ assert.deepEqual(Object.keys(filtered.collections), ["todos"]);
184
+ assert.equal(filtered.collections.todos?.entities[0]?.id, "todo-2");
185
+ assert.equal(filtered.collections.todos?.total, 1);
186
+
187
+ const truncated = bridge.inspect({collection: "todos", limit: 1});
188
+ assert.isTrue(truncated.collections.todos?.truncated);
189
+ assert.lengthOf(truncated.collections.todos?.entities ?? [], 1);
190
+
191
+ const missing = bridge.inspect({collection: "todos", entityId: "missing"});
192
+ assert.lengthOf(missing.collections.todos?.entities ?? [], 0);
193
+
194
+ const quiet = bridge.inspect({includeDebugEvents: false});
195
+ assert.deepEqual(quiet.debug?.events, []);
196
+ assert.equal((quiet.outbox["m-json"]?.args as {title?: string})?.title, "queued");
197
+ assert.equal(quiet.outbox["m-invalid"]?.args, "{not-json");
198
+
199
+ assert.throws((): void => {
200
+ bridge.deleteLocalEntity({collection: "unknown", id: "x"});
201
+ }, /Unknown collection "unknown"/);
202
+
203
+ bridge.goOffline();
204
+ await bridge.goOnline();
205
+ await bridge.reconcile();
206
+ await bridge.forceResync();
207
+ await bridge.flush();
208
+ bridge.clearDebug();
209
+ bridge.retryFailed({entityId: "todo-1"});
210
+ assert.throws((): void => {
211
+ bridge.resolveConflict({mutationId: "missing", strategy: "keepLocal"});
212
+ });
213
+ assert.deepEqual(bridge.inspect({includeDebugEvents: false}).debug?.events, []);
214
+ await first.stop();
215
+ await second.stop();
216
+ });
217
+
218
+ it("does not register clients when debugging is disabled", (): void => {
219
+ createSyncDb({
220
+ authProvider: {
221
+ getToken: async (): Promise<string | null> => "token",
222
+ getUserId: async (): Promise<string | null> => "user-1",
223
+ onAuthChange:
224
+ (_callback: () => void): (() => void) =>
225
+ (): void => {},
226
+ },
227
+ collections: ["todos"],
228
+ name: "production-client",
229
+ transport: createFakeTransport(),
230
+ });
231
+
232
+ assert.isUndefined(getRegistry());
233
+ });
234
+ });
@@ -0,0 +1,196 @@
1
+ import {DateTime} from "luxon";
2
+ import type {MergeableContent} from "tinybase";
3
+
4
+ import type {SyncDb} from "../client";
5
+ import {listConflicts} from "../mutations/conflicts";
6
+ import {CURSORS_TABLE, KNOWN_STREAMS_TABLE, OUTBOX_TABLE} from "../storage/types";
7
+ import type {ConflictResolutionStrategy, SyncMutationOperation} from "../types";
8
+
9
+ const DEFAULT_ENTITY_LIMIT = 500;
10
+ const MAX_ENTITY_LIMIT = 2_000;
11
+
12
+ interface SyncDbDevtoolsInspectOptions {
13
+ collection?: string;
14
+ entityId?: string;
15
+ includeDebugEvents?: boolean;
16
+ limit?: number;
17
+ }
18
+
19
+ interface SyncDbDevtoolsMutation {
20
+ collection: string;
21
+ operation: SyncMutationOperation;
22
+ id?: string;
23
+ data?: Record<string, unknown>;
24
+ maxAttempts?: number;
25
+ }
26
+
27
+ interface SyncDbDevtoolsState {
28
+ capturedAt: string;
29
+ name: string;
30
+ status: ReturnType<SyncDb["getSyncStatus"]>;
31
+ collections: Record<
32
+ string,
33
+ {
34
+ entities: ReturnType<SyncDb["store"]["listEntities"]>;
35
+ total: number;
36
+ truncated: boolean;
37
+ }
38
+ >;
39
+ outbox: Record<string, unknown>;
40
+ conflicts: ReturnType<typeof listConflicts>;
41
+ cursors: Record<string, unknown>;
42
+ knownStreams: Record<string, unknown>;
43
+ needsRepair: ReturnType<SyncDb["store"]["listNeedsRepair"]>;
44
+ values: Record<string, unknown>;
45
+ debug?: ReturnType<NonNullable<SyncDb["debug"]>["snapshot"]>;
46
+ }
47
+
48
+ interface SyncDbDevtoolsSnapshot extends SyncDbDevtoolsState {
49
+ mergeableContent: unknown;
50
+ }
51
+
52
+ interface SyncDbDevtoolsClient {
53
+ inspect: (options?: SyncDbDevtoolsInspectOptions) => SyncDbDevtoolsState;
54
+ snapshot: (options?: SyncDbDevtoolsInspectOptions) => SyncDbDevtoolsSnapshot;
55
+ mutate: (args: SyncDbDevtoolsMutation) => ReturnType<SyncDb["mutate"]>;
56
+ setLocalEntity: (args: {
57
+ collection: string;
58
+ id: string;
59
+ data: unknown;
60
+ deleted?: boolean;
61
+ seq?: number;
62
+ stream?: string;
63
+ }) => void;
64
+ deleteLocalEntity: (args: {collection: string; id: string}) => void;
65
+ merge: (content: unknown) => void;
66
+ flush: () => Promise<void>;
67
+ reconcile: () => Promise<void>;
68
+ forceResync: () => ReturnType<SyncDb["forceResync"]>;
69
+ resolveConflict: (args: {mutationId: string; strategy: ConflictResolutionStrategy}) => void;
70
+ retryFailed: (args: {entityId: string}) => void;
71
+ goOffline: () => void;
72
+ goOnline: () => Promise<void>;
73
+ clearDebug: () => void;
74
+ }
75
+
76
+ interface SyncDbDevtoolsRegistry {
77
+ clients: Record<string, SyncDbDevtoolsClient>;
78
+ list: () => string[];
79
+ }
80
+
81
+ const getRegistry = (): SyncDbDevtoolsRegistry => {
82
+ const globalWithRegistry = globalThis as typeof globalThis & {
83
+ __TERRENO_SYNCDB__?: SyncDbDevtoolsRegistry;
84
+ };
85
+ if (!globalWithRegistry.__TERRENO_SYNCDB__) {
86
+ const clients: Record<string, SyncDbDevtoolsClient> = {};
87
+ globalWithRegistry.__TERRENO_SYNCDB__ = {
88
+ clients,
89
+ list: (): string[] => Object.keys(clients).sort(),
90
+ };
91
+ }
92
+ return globalWithRegistry.__TERRENO_SYNCDB__;
93
+ };
94
+
95
+ const decodeOutbox = (rows: Record<string, unknown>): Record<string, unknown> => {
96
+ return Object.fromEntries(
97
+ Object.entries(rows).map(([mutationId, value]) => {
98
+ const row =
99
+ typeof value === "object" && value !== null ? (value as Record<string, unknown>) : {value};
100
+ let args: unknown = row.args;
101
+ if (typeof row.args === "string") {
102
+ try {
103
+ args = JSON.parse(row.args);
104
+ } catch {
105
+ args = row.args;
106
+ }
107
+ }
108
+ return [mutationId, {...row, args}];
109
+ })
110
+ );
111
+ };
112
+
113
+ export const registerSyncDbDevtools = ({client, name}: {client: SyncDb; name: string}): void => {
114
+ const inspect = (options: SyncDbDevtoolsInspectOptions = {}): SyncDbDevtoolsState => {
115
+ const limit = Math.min(Math.max(options.limit ?? DEFAULT_ENTITY_LIMIT, 1), MAX_ENTITY_LIMIT);
116
+ const selectedCollections = options.collection
117
+ ? [options.collection]
118
+ : [...client.store.collections];
119
+ const collections: SyncDbDevtoolsState["collections"] = {};
120
+
121
+ for (const collection of selectedCollections) {
122
+ const allEntities = options.entityId
123
+ ? [
124
+ client.store.getEntity({
125
+ collection,
126
+ id: options.entityId,
127
+ }),
128
+ ].filter((entity) => entity !== undefined)
129
+ : client.store.listEntities({collection, includeDeleted: true});
130
+ collections[collection] = {
131
+ entities: allEntities.slice(0, limit),
132
+ total: allEntities.length,
133
+ truncated: allEntities.length > limit,
134
+ };
135
+ }
136
+
137
+ return {
138
+ capturedAt: DateTime.utc().toISO(),
139
+ collections,
140
+ conflicts: listConflicts({store: client.store}),
141
+ cursors: client.store.raw.getTable(CURSORS_TABLE),
142
+ ...(client.debug
143
+ ? {
144
+ debug:
145
+ options.includeDebugEvents === false
146
+ ? {
147
+ ...client.debug.snapshot(),
148
+ events: [],
149
+ }
150
+ : client.debug.snapshot(),
151
+ }
152
+ : {}),
153
+ knownStreams: client.store.raw.getTable(KNOWN_STREAMS_TABLE),
154
+ name,
155
+ needsRepair: client.store.listNeedsRepair(),
156
+ outbox: decodeOutbox(client.store.raw.getTable(OUTBOX_TABLE)),
157
+ status: client.getSyncStatus(),
158
+ values: client.store.raw.getValues(),
159
+ };
160
+ };
161
+
162
+ const devtoolsClient: SyncDbDevtoolsClient = {
163
+ clearDebug: (): void => {
164
+ client.debug?.clear();
165
+ },
166
+ deleteLocalEntity: ({collection, id}): void => {
167
+ if (!client.store.collections.includes(collection)) {
168
+ throw new Error(`Unknown collection "${collection}".`);
169
+ }
170
+ client.store.raw.delRow(collection, id);
171
+ },
172
+ flush: async (): Promise<void> => {
173
+ await client.replayOutbox();
174
+ },
175
+ forceResync: client.forceResync,
176
+ goOffline: client.goOffline,
177
+ goOnline: client.goOnline,
178
+ inspect,
179
+ merge: (content): void => {
180
+ client.store.raw.applyMergeableChanges(content as MergeableContent);
181
+ },
182
+ mutate: client.mutate,
183
+ reconcile: client.reconcile,
184
+ resolveConflict: client.resolveConflict,
185
+ retryFailed: client.retryFailed,
186
+ setLocalEntity: ({collection, id, data, deleted, seq, stream}): void => {
187
+ client.store.upsertEntity({collection, data, deleted, id, seq, stream});
188
+ },
189
+ snapshot: (options = {}): SyncDbDevtoolsSnapshot => ({
190
+ ...inspect(options),
191
+ mergeableContent: client.store.raw.getMergeableContent(),
192
+ }),
193
+ };
194
+
195
+ getRegistry().clients[name] = devtoolsClient;
196
+ };
package/src/index.ts CHANGED
@@ -85,6 +85,10 @@ export {
85
85
  betterAuthAdapter,
86
86
  DEFAULT_AUTH_POLL_INTERVAL_MS,
87
87
  } from "./auth/betterAuthAdapter";
88
+ export {
89
+ type BetterAuthReactClientLike,
90
+ bridgeBetterAuthReactClient,
91
+ } from "./auth/betterAuthReactClient";
88
92
  export type {
89
93
  BetterAuthClientLike,
90
94
  BetterAuthGetSessionResult,
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Isolated: mock expo-sqlite as missing or incomplete so loadExpoSqlite error
3
+ * paths do not leak into the rest of the suite.
4
+ */
5
+ import {describe, expect, it, mock} from "bun:test";
6
+
7
+ mock.module("expo-sqlite", () => ({}));
8
+ mock.module("tinybase/persisters/persister-expo-sqlite", () => ({
9
+ createExpoSqlitePersister: () => ({}),
10
+ }));
11
+
12
+ import {createDefaultPersisterFactory} from "../persisters/defaultPersisterFactory.native";
13
+ import {createSyncStore} from "../storage/store";
14
+
15
+ describe("createDefaultPersisterFactory (native errors)", () => {
16
+ it("throws when expo-sqlite has no openDatabaseSync", () => {
17
+ const factory = createDefaultPersisterFactory();
18
+ const store = createSyncStore({collections: ["todos"]});
19
+ expect(() => factory({databaseName: "terreno-syncdb.db", store: store.raw})).toThrow(
20
+ /expo-sqlite peer/
21
+ );
22
+ });
23
+ });