@terreno/syncdb 57.3.0 → 57.4.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 (135) hide show
  1. package/dist/auth/betterAuthReactClient.d.ts +17 -0
  2. package/dist/auth/betterAuthReactClient.d.ts.map +1 -0
  3. package/dist/auth/betterAuthReactClient.js +11 -0
  4. package/dist/auth/betterAuthReactClient.js.map +1 -0
  5. package/dist/auth/betterAuthReactClient.test.d.ts +2 -0
  6. package/dist/auth/betterAuthReactClient.test.d.ts.map +1 -0
  7. package/dist/auth/betterAuthReactClient.test.js +43 -0
  8. package/dist/auth/betterAuthReactClient.test.js.map +1 -0
  9. package/dist/client.adminWindowMutation.test.d.ts +2 -0
  10. package/dist/client.adminWindowMutation.test.d.ts.map +1 -0
  11. package/dist/client.adminWindowMutation.test.js +65 -0
  12. package/dist/client.adminWindowMutation.test.js.map +1 -0
  13. package/dist/client.d.ts +22 -0
  14. package/dist/client.d.ts.map +1 -1
  15. package/dist/client.js +46 -4
  16. package/dist/client.js.map +1 -1
  17. package/dist/client.test.js +232 -2
  18. package/dist/client.test.js.map +1 -1
  19. package/dist/codegen/emitSdk.js +3 -3
  20. package/dist/codegen/emitSdk.js.map +1 -1
  21. package/dist/codegen/generate.test.js +32 -2
  22. package/dist/codegen/generate.test.js.map +1 -1
  23. package/dist/codegen/safeIdentifiers.d.ts +5 -0
  24. package/dist/codegen/safeIdentifiers.d.ts.map +1 -1
  25. package/dist/codegen/safeIdentifiers.js +8 -0
  26. package/dist/codegen/safeIdentifiers.js.map +1 -1
  27. package/dist/codegen/safeIdentifiers.test.js +20 -8
  28. package/dist/codegen/safeIdentifiers.test.js.map +1 -1
  29. package/dist/codegen/types.d.ts +4 -3
  30. package/dist/codegen/types.d.ts.map +1 -1
  31. package/dist/debug/debugChannel.test.js +5 -0
  32. package/dist/debug/debugChannel.test.js.map +1 -1
  33. package/dist/debug/debugLog.d.ts +1 -0
  34. package/dist/debug/debugLog.d.ts.map +1 -1
  35. package/dist/debug/debugLog.js +1 -0
  36. package/dist/debug/debugLog.js.map +1 -1
  37. package/dist/index.d.ts +1 -0
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +1 -0
  40. package/dist/index.js.map +1 -1
  41. package/dist/isolated/defaultPersisterFactoryNativeErrors.isolated.d.ts +2 -0
  42. package/dist/isolated/defaultPersisterFactoryNativeErrors.isolated.d.ts.map +1 -0
  43. package/dist/isolated/defaultPersisterFactoryNativeErrors.isolated.js +19 -0
  44. package/dist/isolated/defaultPersisterFactoryNativeErrors.isolated.js.map +1 -0
  45. package/dist/mutations/outbox.d.ts +7 -3
  46. package/dist/mutations/outbox.d.ts.map +1 -1
  47. package/dist/mutations/outbox.js +6 -0
  48. package/dist/mutations/outbox.js.map +1 -1
  49. package/dist/mutations/outbox.test.js +17 -0
  50. package/dist/mutations/outbox.test.js.map +1 -1
  51. package/dist/storage/idb.d.ts +1 -0
  52. package/dist/storage/idb.d.ts.map +1 -1
  53. package/dist/storage/idb.js +1 -0
  54. package/dist/storage/idb.js.map +1 -1
  55. package/dist/storage/schema.d.ts.map +1 -1
  56. package/dist/storage/schema.js +1 -0
  57. package/dist/storage/schema.js.map +1 -1
  58. package/dist/storage/store.d.ts +3 -2
  59. package/dist/storage/store.d.ts.map +1 -1
  60. package/dist/storage/types.d.ts +1 -7
  61. package/dist/storage/types.d.ts.map +1 -1
  62. package/dist/sync/deltaApplier.d.ts +2 -0
  63. package/dist/sync/deltaApplier.d.ts.map +1 -1
  64. package/dist/sync/deltaApplier.js +9 -0
  65. package/dist/sync/deltaApplier.js.map +1 -1
  66. package/dist/sync/deltaApplier.test.js +63 -0
  67. package/dist/sync/deltaApplier.test.js.map +1 -1
  68. package/dist/sync/entityRepair.d.ts +1 -0
  69. package/dist/sync/entityRepair.d.ts.map +1 -1
  70. package/dist/sync/entityRepair.js +1 -0
  71. package/dist/sync/entityRepair.js.map +1 -1
  72. package/dist/sync/httpChannel.d.ts +3 -1
  73. package/dist/sync/httpChannel.d.ts.map +1 -1
  74. package/dist/sync/httpChannel.js +3 -1
  75. package/dist/sync/httpChannel.js.map +1 -1
  76. package/dist/sync/httpChannel.test.js +68 -0
  77. package/dist/sync/httpChannel.test.js.map +1 -1
  78. package/dist/sync/replayCoordinator.d.ts +6 -12
  79. package/dist/sync/replayCoordinator.d.ts.map +1 -1
  80. package/dist/sync/replayCoordinator.js +9 -2
  81. package/dist/sync/replayCoordinator.js.map +1 -1
  82. package/dist/sync/socketTransport.d.ts +3 -45
  83. package/dist/sync/socketTransport.d.ts.map +1 -1
  84. package/dist/sync/socketTransport.js +31 -9
  85. package/dist/sync/socketTransport.js.map +1 -1
  86. package/dist/sync/socketTransport.test.js +7 -0
  87. package/dist/sync/socketTransport.test.js.map +1 -1
  88. package/dist/sync/transport.d.ts +3 -1
  89. package/dist/sync/transport.d.ts.map +1 -1
  90. package/dist/sync/windowHydrate.d.ts +25 -0
  91. package/dist/sync/windowHydrate.d.ts.map +1 -0
  92. package/dist/sync/windowHydrate.js +67 -0
  93. package/dist/sync/windowHydrate.js.map +1 -0
  94. package/dist/sync/windowHydrate.test.d.ts +2 -0
  95. package/dist/sync/windowHydrate.test.d.ts.map +1 -0
  96. package/dist/sync/windowHydrate.test.js +164 -0
  97. package/dist/sync/windowHydrate.test.js.map +1 -0
  98. package/dist/testing/fakeTransport.js +1 -1
  99. package/dist/testing/fakeTransport.js.map +1 -1
  100. package/dist/types.d.ts +15 -0
  101. package/dist/types.d.ts.map +1 -1
  102. package/package.json +1 -1
  103. package/src/auth/betterAuthReactClient.test.ts +50 -0
  104. package/src/auth/betterAuthReactClient.ts +33 -0
  105. package/src/client.adminWindowMutation.test.ts +69 -0
  106. package/src/client.test.ts +248 -2
  107. package/src/client.ts +85 -3
  108. package/src/codegen/emitSdk.ts +3 -3
  109. package/src/codegen/generate.test.ts +35 -2
  110. package/src/codegen/safeIdentifiers.test.ts +37 -10
  111. package/src/codegen/safeIdentifiers.ts +17 -0
  112. package/src/codegen/types.ts +3 -3
  113. package/src/debug/debugChannel.test.ts +6 -0
  114. package/src/debug/debugLog.ts +1 -0
  115. package/src/index.ts +4 -0
  116. package/src/isolated/defaultPersisterFactoryNativeErrors.isolated.ts +23 -0
  117. package/src/mutations/outbox.test.ts +20 -0
  118. package/src/mutations/outbox.ts +11 -3
  119. package/src/storage/idb.ts +1 -0
  120. package/src/storage/schema.ts +1 -0
  121. package/src/storage/store.ts +2 -2
  122. package/src/storage/types.ts +1 -8
  123. package/src/sync/deltaApplier.test.ts +70 -0
  124. package/src/sync/deltaApplier.ts +10 -0
  125. package/src/sync/entityRepair.ts +1 -0
  126. package/src/sync/httpChannel.test.ts +82 -0
  127. package/src/sync/httpChannel.ts +5 -0
  128. package/src/sync/replayCoordinator.ts +10 -3
  129. package/src/sync/socketTransport.test.ts +10 -2
  130. package/src/sync/socketTransport.ts +64 -22
  131. package/src/sync/transport.ts +1 -1
  132. package/src/sync/windowHydrate.test.ts +179 -0
  133. package/src/sync/windowHydrate.ts +97 -0
  134. package/src/testing/fakeTransport.ts +1 -1
  135. package/src/types.ts +16 -0
@@ -20,7 +20,7 @@ interface TestServer {
20
20
  /** Sockets that have connected, most recent last. */
21
21
  sockets: ServerSocket[];
22
22
  /** sync:subscribe payloads received, in order. */
23
- subscribes: {collections: string[]}[];
23
+ subscribes: {collections: string[]; mode?: string}[];
24
24
  /** Handler answering sync:mutate; replace per test. */
25
25
  mutateHandler: (request: SyncMutateRequest, socket: ServerSocket) => void;
26
26
  /** Handler answering sync:mutateBatch; replace per test (no-op = unsupported). */
@@ -53,7 +53,7 @@ const startServer = async (): Promise<TestServer> => {
53
53
  };
54
54
  io.on("connection", (socket) => {
55
55
  server.sockets.push(socket);
56
- socket.on("sync:subscribe", (payload: {collections: string[]}) => {
56
+ socket.on("sync:subscribe", (payload: {collections: string[]; mode?: string}) => {
57
57
  server.subscribes.push(payload);
58
58
  });
59
59
  socket.on("sync:mutate", (request: SyncMutateRequest) => {
@@ -142,6 +142,14 @@ describe("createSocketTransport", () => {
142
142
  expect(server.sockets).toHaveLength(1);
143
143
  });
144
144
 
145
+ it("subscribe emits window mode for window collections", async () => {
146
+ const subscriber = makeTransport();
147
+ subscriber.subscribe(["todos"], {mode: "window"});
148
+ await subscriber.connect();
149
+ await waitUntil(() => server.subscribes.length === 1);
150
+ expect(server.subscribes).toEqual([{collections: ["todos"], mode: "window"}]);
151
+ });
152
+
145
153
  it("subscribe emits sync:subscribe when connected and replays it on connect", async () => {
146
154
  const subscriber = makeTransport();
147
155
  // Subscribed before connect: sent once the connection opens.
@@ -28,7 +28,7 @@ import {
28
28
  * just slow) and the client waits the full {@link batchTimeoutMs} instead of
29
29
  * falling back (FIX 5).
30
30
  */
31
- export const BATCH_UNSUPPORTED_GRACE_MS = 2_000;
31
+ const BATCH_UNSUPPORTED_GRACE_MS = 2_000;
32
32
 
33
33
  /**
34
34
  * Compute the batch send timeout once a `sync:batchReceived` receipt has
@@ -37,7 +37,7 @@ export const BATCH_UNSUPPORTED_GRACE_MS = 2_000;
37
37
  * timed out prematurely just because it's slower than a single mutation
38
38
  * (FIX 5).
39
39
  */
40
- export const batchTimeoutMs = (mutationCount: number, perMutationTimeoutMs: number): number =>
40
+ const batchTimeoutMs = (mutationCount: number, perMutationTimeoutMs: number): number =>
41
41
  Math.max(perMutationTimeoutMs, mutationCount * 1_000);
42
42
 
43
43
  export interface SocketTransportConfig {
@@ -54,6 +54,8 @@ export interface SocketTransportConfig {
54
54
  * dev server does not fail the first handshake.
55
55
  */
56
56
  transports?: string[];
57
+ /** Selected organization id attached to mutate payloads when present. */
58
+ organizationIdProvider?: () => string | undefined;
57
59
  }
58
60
 
59
61
  interface PendingMutation {
@@ -86,12 +88,24 @@ interface PendingMutation {
86
88
  * subscribed collections because server-side subscription state is
87
89
  * per-connection.
88
90
  */
91
+ const withOrganizationId = <T extends object>(
92
+ payload: T,
93
+ organizationIdProvider?: () => string | undefined
94
+ ): T & {organizationId?: string} => {
95
+ const organizationId = organizationIdProvider?.()?.trim();
96
+ if (!organizationId) {
97
+ return payload;
98
+ }
99
+ return {...payload, organizationId};
100
+ };
101
+
89
102
  export const createSocketTransport = ({
90
103
  baseUrl,
91
104
  authProvider,
92
105
  timeoutMs = DEFAULT_MUTATION_TIMEOUT_MS,
93
106
  batchUnsupportedGraceMs = BATCH_UNSUPPORTED_GRACE_MS,
94
107
  transports = ["polling", "websocket"],
108
+ organizationIdProvider,
95
109
  }: SocketTransportConfig): SyncTransport => {
96
110
  const deltaListeners = new Set<(delta: SyncDelta) => void>();
97
111
  const subscribedListeners = new Set<(subscribed: SyncSubscribed) => void>();
@@ -112,6 +126,7 @@ export const createSocketTransport = ({
112
126
  >();
113
127
  let nextBatchId = 1;
114
128
  const subscribed = new Set<string>();
129
+ const subscribeMode = new Map<string, "window">();
115
130
 
116
131
  const socket: Socket = io(baseUrl, {
117
132
  auth: (callback) => {
@@ -177,17 +192,21 @@ export const createSocketTransport = ({
177
192
  listener(delta);
178
193
  }
179
194
  });
180
- socket.on("sync:subscribed", (payload: {collection?: unknown; streams?: unknown}) => {
181
- if (typeof payload?.collection !== "string" || !Array.isArray(payload.streams)) {
182
- return;
183
- }
184
- const streams = payload.streams.filter(
185
- (stream: unknown): stream is string => typeof stream === "string"
186
- );
187
- for (const listener of subscribedListeners) {
188
- listener({collection: payload.collection, streams});
195
+ socket.on(
196
+ "sync:subscribed",
197
+ (payload: {collection?: unknown; streams?: unknown; mode?: unknown}) => {
198
+ if (typeof payload?.collection !== "string" || !Array.isArray(payload.streams)) {
199
+ return;
200
+ }
201
+ const streams = payload.streams.filter(
202
+ (stream: unknown): stream is string => typeof stream === "string"
203
+ );
204
+ const mode = payload.mode === "window" ? ("window" as const) : undefined;
205
+ for (const listener of subscribedListeners) {
206
+ listener({collection: payload.collection, streams, ...(mode ? {mode} : {})});
207
+ }
189
208
  }
190
- });
209
+ );
191
210
  socket.on("sync:ack", (ack: SyncAck) => {
192
211
  settle(ack.mutationId, {ack, type: "ack"});
193
212
  });
@@ -213,7 +232,18 @@ export const createSocketTransport = ({
213
232
  socket.on("connect", () => {
214
233
  // Server-side subscriptions are per-connection: re-subscribe on reconnect.
215
234
  if (subscribed.size > 0) {
216
- socket.emit("sync:subscribe", {collections: [...subscribed]});
235
+ const windowed = [...subscribed].filter(
236
+ (collection) => subscribeMode.get(collection) === "window"
237
+ );
238
+ const full = [...subscribed].filter(
239
+ (collection) => subscribeMode.get(collection) !== "window"
240
+ );
241
+ if (full.length > 0) {
242
+ socket.emit("sync:subscribe", {collections: full});
243
+ }
244
+ if (windowed.length > 0) {
245
+ socket.emit("sync:subscribe", {collections: windowed, mode: "window"});
246
+ }
217
247
  }
218
248
  notifyStatus(true);
219
249
  });
@@ -257,14 +287,22 @@ export const createSocketTransport = ({
257
287
  rejectAllPending("Transport disconnected");
258
288
  };
259
289
 
260
- const subscribe = (collections: string[]): void => {
290
+ const subscribe = (collections: string[], options?: {mode?: "window"}): void => {
261
291
  for (const collection of collections) {
262
292
  subscribed.add(collection);
293
+ if (options?.mode === "window") {
294
+ subscribeMode.set(collection, "window");
295
+ } else {
296
+ subscribeMode.delete(collection);
297
+ }
263
298
  }
264
299
  // Only emit when connected; the connect handler (re)subscribes otherwise —
265
300
  // Socket.io would buffer a disconnected emit and duplicate the subscribe.
266
301
  if (socket.connected && collections.length > 0) {
267
- socket.emit("sync:subscribe", {collections});
302
+ socket.emit(
303
+ "sync:subscribe",
304
+ options?.mode === "window" ? {collections, mode: "window"} : {collections}
305
+ );
268
306
  }
269
307
  };
270
308
 
@@ -279,13 +317,17 @@ export const createSocketTransport = ({
279
317
  pending.set(request.mutationId, {reject, resolve, timer});
280
318
  // The server both emits sync:ack/sync:nack and invokes this Socket.io
281
319
  // ack callback; whichever arrives first settles (settle is idempotent).
282
- socket.emit("sync:mutate", request, (response: {ack?: SyncAck; nack?: SyncNack}) => {
283
- if (response?.ack) {
284
- settle(request.mutationId, {ack: response.ack, type: "ack"});
285
- } else if (response?.nack) {
286
- settle(request.mutationId, {nack: response.nack, type: "nack"});
320
+ socket.emit(
321
+ "sync:mutate",
322
+ withOrganizationId(request, organizationIdProvider),
323
+ (response: {ack?: SyncAck; nack?: SyncNack}) => {
324
+ if (response?.ack) {
325
+ settle(request.mutationId, {ack: response.ack, type: "ack"});
326
+ } else if (response?.nack) {
327
+ settle(request.mutationId, {nack: response.nack, type: "nack"});
328
+ }
287
329
  }
288
- });
330
+ );
289
331
  });
290
332
 
291
333
  const sendMutationBatch = (
@@ -358,7 +400,7 @@ export const createSocketTransport = ({
358
400
 
359
401
  socket.emit(
360
402
  "sync:mutateBatch",
361
- {...request, batchId},
403
+ withOrganizationId({...request, batchId}, organizationIdProvider),
362
404
  (response: {
363
405
  results?: ({type: "ack"; ack: SyncAck} | {type: "nack"; nack: SyncNack})[];
364
406
  }) => {
@@ -53,7 +53,7 @@ export interface SyncTransport {
53
53
  /** Close the connection and reject any in-flight mutation sends. */
54
54
  disconnect: () => void;
55
55
  /** Subscribe to delta streams for the given collections (idempotent server-side). */
56
- subscribe: (collections: string[]) => void;
56
+ subscribe: (collections: string[], options?: {mode?: "window"}) => void;
57
57
  /**
58
58
  * Send a mutation and resolve with the server's ack/nack, correlated by
59
59
  * `mutationId`. Rejects when no reply arrives within the transport's
@@ -0,0 +1,179 @@
1
+ import {describe, it} from "bun:test";
2
+ import {assert} from "chai";
3
+ import {DateTime} from "luxon";
4
+
5
+ import {createSyncStore} from "../storage/store";
6
+ import {hydrateWindowEntities} from "./windowHydrate";
7
+
8
+ const STREAM = "todos|admin";
9
+
10
+ describe("hydrateWindowEntities", () => {
11
+ it("hydrates 2 of 3 ids and ignores the unknown id", async () => {
12
+ const store = createSyncStore({collections: ["todos"]});
13
+ const requested: string[] = [];
14
+ const result = await hydrateWindowEntities({
15
+ channel: {
16
+ fetchEntities: async ({ids}) => {
17
+ requested.push(...ids);
18
+ return {
19
+ entities: [
20
+ {data: {title: "one"}, deleted: false, id: "a", seq: 4},
21
+ {data: {title: "two"}, deleted: false, id: "b", seq: 5},
22
+ ],
23
+ };
24
+ },
25
+ },
26
+ collection: "todos",
27
+ ids: ["a", "b", "missing"],
28
+ store,
29
+ });
30
+
31
+ assert.deepEqual(requested, ["a", "b", "missing"]);
32
+ assert.deepEqual(result.hydratedIds.sort(), ["a", "b"]);
33
+ const rowA = store.getEntity<{title: string}>({collection: "todos", id: "a"});
34
+ const rowB = store.getEntity<{title: string}>({collection: "todos", id: "b"});
35
+ assert.equal(rowA?.data.title, "one");
36
+ assert.equal(rowB?.seq, 5);
37
+ assert.isUndefined(store.getEntity({collection: "todos", id: "missing"}));
38
+ assert.equal(rowA?.stream, STREAM);
39
+ });
40
+
41
+ it("upserts REST rows immediately and fetches every id for seq/deleted metadata", async () => {
42
+ const store = createSyncStore({collections: ["todos"]});
43
+ const fetched: string[][] = [];
44
+ await hydrateWindowEntities({
45
+ channel: {
46
+ fetchEntities: async ({ids}) => {
47
+ fetched.push(ids);
48
+ return {
49
+ entities: [
50
+ {data: {title: "canonical-a"}, deleted: false, id: "a", seq: 7},
51
+ {data: {title: "from-entities"}, deleted: false, id: "b", seq: 9},
52
+ ],
53
+ };
54
+ },
55
+ },
56
+ collection: "todos",
57
+ ids: ["a", "b"],
58
+ restRows: {a: {title: "from-rest"}},
59
+ store,
60
+ });
61
+
62
+ assert.deepEqual(fetched, [["a", "b"]]);
63
+ const restRow = store.getEntity<{title: string}>({collection: "todos", id: "a"});
64
+ const entityRow = store.getEntity<{title: string}>({collection: "todos", id: "b"});
65
+ assert.equal(restRow?.data.title, "from-rest");
66
+ assert.equal(restRow?.seq, 7);
67
+ assert.equal(entityRow?.data.title, "from-entities");
68
+ assert.equal(entityRow?.seq, 9);
69
+ });
70
+
71
+ it("exposes REST row data before entities fetch resolves", async () => {
72
+ const store = createSyncStore({collections: ["todos"]});
73
+ const updatedAt = DateTime.utc().toISO();
74
+ let restRowDuringFetch: {data?: {title?: string; updated?: string}; seq?: number} | undefined;
75
+
76
+ await hydrateWindowEntities({
77
+ channel: {
78
+ fetchEntities: async () => {
79
+ restRowDuringFetch = store.getEntity<{title: string; updated?: string}>({
80
+ collection: "todos",
81
+ id: "a",
82
+ });
83
+ return {
84
+ entities: [{data: {title: "canonical"}, deleted: false, id: "a", seq: 11}],
85
+ };
86
+ },
87
+ },
88
+ collection: "todos",
89
+ ids: ["a"],
90
+ restRows: {a: {title: "from-rest", updated: updatedAt}},
91
+ store,
92
+ });
93
+
94
+ assert.equal(restRowDuringFetch?.data?.title, "from-rest");
95
+ assert.equal(restRowDuringFetch?.data?.updated, updatedAt);
96
+ assert.equal(restRowDuringFetch?.seq, 0);
97
+ const row = store.getEntity<{title: string; updated?: string}>({collection: "todos", id: "a"});
98
+ assert.equal(row?.seq, 11);
99
+ });
100
+
101
+ it("applies deleted metadata from entities onto REST rows", async () => {
102
+ const store = createSyncStore({collections: ["todos"]});
103
+ await hydrateWindowEntities({
104
+ channel: {
105
+ fetchEntities: async () => ({
106
+ entities: [{data: {title: "gone"}, deleted: true, id: "a", seq: 12}],
107
+ }),
108
+ },
109
+ collection: "todos",
110
+ ids: ["a"],
111
+ restRows: {a: {title: "from-rest"}},
112
+ store,
113
+ });
114
+
115
+ const row = store.getEntity<{title: string}>({collection: "todos", id: "a"});
116
+ assert.equal(row?.data.title, "from-rest");
117
+ assert.equal(row?.seq, 12);
118
+ assert.isTrue(row?.deleted);
119
+ });
120
+
121
+ it("keeps a newer live delta when the entities snapshot is already stale", async () => {
122
+ const store = createSyncStore({collections: ["todos"]});
123
+ const result = await hydrateWindowEntities({
124
+ channel: {
125
+ fetchEntities: async () => {
126
+ // A `{collection}|admin` delta lands while the entities request is in flight.
127
+ store.upsertEntity({
128
+ collection: "todos",
129
+ data: {title: "live-delta"},
130
+ id: "a",
131
+ seq: 20,
132
+ stream: STREAM,
133
+ });
134
+ return {
135
+ entities: [{data: {title: "stale-snapshot"}, deleted: true, id: "a", seq: 12}],
136
+ };
137
+ },
138
+ },
139
+ collection: "todos",
140
+ ids: ["a"],
141
+ store,
142
+ });
143
+
144
+ const row = store.getEntity<{title: string}>({collection: "todos", id: "a"});
145
+ assert.deepEqual(result.hydratedIds, ["a"]);
146
+ assert.equal(row?.data.title, "live-delta");
147
+ assert.equal(row?.seq, 20);
148
+ assert.isNotTrue(row?.deleted);
149
+ });
150
+
151
+ it("skips REST and entities upserts when a pending optimistic mutation owns the row", async () => {
152
+ const store = createSyncStore({collections: ["todos"]});
153
+ store.upsertEntity({
154
+ collection: "todos",
155
+ data: {title: "pending-local"},
156
+ id: "a",
157
+ pendingMutationId: "m-pending",
158
+ seq: 3,
159
+ stream: STREAM,
160
+ });
161
+
162
+ await hydrateWindowEntities({
163
+ channel: {
164
+ fetchEntities: async () => ({
165
+ entities: [{data: {title: "server"}, deleted: false, id: "a", seq: 99}],
166
+ }),
167
+ },
168
+ collection: "todos",
169
+ ids: ["a"],
170
+ restRows: {a: {title: "from-rest"}},
171
+ store,
172
+ });
173
+
174
+ const row = store.getEntity<{title: string}>({collection: "todos", id: "a"});
175
+ assert.equal(row?.data.title, "pending-local");
176
+ assert.equal(row?.seq, 3);
177
+ assert.equal(row?.pendingMutationId, "m-pending");
178
+ });
179
+ });
@@ -0,0 +1,97 @@
1
+ import type {SyncStore} from "../storage/store";
2
+ import {MAX_REPAIR_FETCH_IDS} from "./entityRepair";
3
+ import type {HttpChannel} from "./httpChannel";
4
+
5
+ /** Stream key window subscribers join (`{collection}|admin`). */
6
+ const adminWindowStream = (collection: string): string => `${collection}|admin`;
7
+
8
+ export interface HydrateWindowEntitiesArgs {
9
+ store: SyncStore;
10
+ channel: Pick<HttpChannel, "fetchEntities">;
11
+ collection: string;
12
+ ids: string[];
13
+ /**
14
+ * Optional REST membership payloads keyed by id. Those rows upsert immediately
15
+ * for fast UI; every requested id is still fetched from `GET /sync/entities`
16
+ * before this call resolves so seq/deleted metadata is canonical.
17
+ */
18
+ restRows?: Record<string, unknown>;
19
+ }
20
+
21
+ export interface HydrateWindowEntitiesResult {
22
+ hydratedIds: string[];
23
+ }
24
+
25
+ /**
26
+ * Upsert a window of known ids into TinyBase. REST rows render immediately;
27
+ * canonical seq/deleted metadata comes from `GET /sync/entities` for every
28
+ * requested id before this resolves. Server ids that `/sync/entities` does not
29
+ * return are ignored (no empty rows) unless a REST row already landed.
30
+ */
31
+ export const hydrateWindowEntities = async ({
32
+ store,
33
+ channel,
34
+ collection,
35
+ ids,
36
+ restRows,
37
+ }: HydrateWindowEntitiesArgs): Promise<HydrateWindowEntitiesResult> => {
38
+ const uniqueIds = [...new Set(ids.filter((id) => id.length > 0))];
39
+ if (uniqueIds.length === 0) {
40
+ return {hydratedIds: []};
41
+ }
42
+
43
+ const stream = adminWindowStream(collection);
44
+ const hydrated = new Set<string>();
45
+
46
+ for (const id of uniqueIds) {
47
+ const restData = restRows?.[id];
48
+ if (restData === undefined) {
49
+ continue;
50
+ }
51
+ const existing = store.getEntity({collection, id});
52
+ if (existing?.pendingMutationId) {
53
+ continue;
54
+ }
55
+ store.upsertEntity({
56
+ collection,
57
+ data: restData,
58
+ id,
59
+ stream,
60
+ });
61
+ hydrated.add(id);
62
+ }
63
+
64
+ for (let i = 0; i < uniqueIds.length; i += MAX_REPAIR_FETCH_IDS) {
65
+ const chunk = uniqueIds.slice(i, i + MAX_REPAIR_FETCH_IDS);
66
+ const response = await channel.fetchEntities({collection, ids: chunk});
67
+ for (const entity of response.entities) {
68
+ if (!uniqueIds.includes(entity.id)) {
69
+ continue;
70
+ }
71
+ const existing = store.getEntity({collection, id: entity.id});
72
+ if (existing?.pendingMutationId) {
73
+ continue;
74
+ }
75
+ // A live `{collection}|admin` delta can land while this fetch is in flight. Its seq is
76
+ // newer than the snapshot being applied here, so writing the snapshot back would rewind
77
+ // seq/deleted and make the next mutate conflict against a stale baseline.
78
+ if (existing && existing.seq > entity.seq) {
79
+ hydrated.add(entity.id);
80
+ continue;
81
+ }
82
+ const restData = restRows?.[entity.id];
83
+ store.upsertEntity({
84
+ collection,
85
+ data: restData !== undefined ? (existing?.data ?? restData) : entity.data,
86
+ deleted: entity.deleted,
87
+ id: entity.id,
88
+ pendingMutationId: "",
89
+ seq: entity.seq,
90
+ stream,
91
+ });
92
+ hydrated.add(entity.id);
93
+ }
94
+ }
95
+
96
+ return {hydratedIds: [...hydrated]};
97
+ };
@@ -209,7 +209,7 @@ export const createFakeTransport = (): FakeTransport => {
209
209
  setDefaultResponder: (responder?: FakeMutationResponder): void => {
210
210
  defaultResponder = responder ?? autoAck;
211
211
  },
212
- subscribe: (collections: string[]): void => {
212
+ subscribe: (collections: string[], _options?: {mode?: "window"}): void => {
213
213
  for (const collection of collections) {
214
214
  subscribed.add(collection);
215
215
  }
package/src/types.ts CHANGED
@@ -8,6 +8,9 @@
8
8
 
9
9
  export type SyncMutationOperation = "create" | "update" | "delete";
10
10
 
11
+ /** Explicit client marker for admin-panel windowed sync writes. */
12
+ export type SyncMutationMode = "adminWindow";
13
+
11
14
  /** A change event delivered by the server via `sync:delta`. */
12
15
  export interface SyncDelta {
13
16
  /** Collection tag (e.g. "todos"). */
@@ -36,12 +39,18 @@ export interface SyncDelta {
36
39
  *
37
40
  * Emitted after the server has joined the socket to every `sync:{stream}` room for the
38
41
  * collection, so it is the first moment live deltas are guaranteed to reach this client.
42
+ * `mode: "window"` means the client must not page `GET /sync/snapshot` for those streams
43
+ * (admin fan-in `{collection}|admin`; hydrate via REST + `/sync/entities` instead).
39
44
  */
45
+ type SyncSubscribeMode = "window";
46
+
40
47
  export interface SyncSubscribed {
41
48
  /** Collection tag the confirmation is for. */
42
49
  collection: string;
43
50
  /** Stream keys now joined for that collection. */
44
51
  streams: string[];
52
+ /** When `window`, skip snapshot/reconcile paging for this collection. */
53
+ mode?: SyncSubscribeMode;
45
54
  }
46
55
 
47
56
  /** A client mutation sent via `sync:mutate` or `POST /sync/mutate`. */
@@ -56,6 +65,11 @@ export interface SyncMutateRequest {
56
65
  data?: Record<string, unknown>;
57
66
  /** The seq the client last saw for this document; enables LWW conflict detection. */
58
67
  baseVersion?: number;
68
+ /**
69
+ * When `"adminWindow"`, the server applies AdminApp write semantics instead of
70
+ * product sync permissions.
71
+ */
72
+ mutationMode?: SyncMutationMode;
59
73
  }
60
74
 
61
75
  /** Successful mutation acknowledgement. */
@@ -198,6 +212,8 @@ export interface OutboxMutation {
198
212
  /** The user this mutation belongs to; replay skips mutations from other users. */
199
213
  userId: string;
200
214
  createdAt: string;
215
+ /** Persisted admin-window marker for durable outbox replay. */
216
+ mutationMode?: SyncMutationMode;
201
217
  }
202
218
 
203
219
  /** An unresolved conflict between a local mutation and the canonical server state. */