bunderstack-sync 0.17.0-beta.2 → 0.17.0-beta.3

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.
@@ -0,0 +1,66 @@
1
+ /** Per-key coalescing queue for high-frequency row updates.
2
+ *
3
+ * Cursor-shaped workloads call `collection.update()` many times a second. Sent
4
+ * one-for-one, each call is a request, a database write and a broadcast. This
5
+ * queue holds a single merged slot per row key: while a request is in flight,
6
+ * further updates for that key merge into the slot and go out as one follow-up
7
+ * once it lands. Request frequency settles at `min(update rate, 1/RTT)` without
8
+ * a tuned throttle constant, and the optimistic UI is untouched — only the
9
+ * network is coalesced.
10
+ */
11
+ export function createUpdateQueue(config) {
12
+ const slots = new Map();
13
+ async function drain(key, slot) {
14
+ while (Object.keys(slot.changes).length > 0) {
15
+ // Taking changes and waiters as one snapshot is what guarantees a waiter
16
+ // resolves only after a request that carried its own changes.
17
+ const changes = slot.changes;
18
+ const waiters = slot.waiters;
19
+ slot.changes = {};
20
+ slot.waiters = [];
21
+ try {
22
+ await config.onResult(await config.send(key, changes));
23
+ for (const waiter of waiters)
24
+ waiter.resolve();
25
+ }
26
+ catch (error) {
27
+ // Replaying queued changes on top of a failed base would diverge from
28
+ // the server silently, so the whole key is rolled back instead.
29
+ const queued = slot.waiters;
30
+ slot.changes = {};
31
+ slot.waiters = [];
32
+ for (const waiter of [...waiters, ...queued])
33
+ waiter.reject(error);
34
+ }
35
+ }
36
+ slots.delete(key);
37
+ }
38
+ return {
39
+ enqueue(key, changes) {
40
+ let slot = slots.get(key);
41
+ if (!slot) {
42
+ slot = { changes: {}, waiters: [], done: null };
43
+ slots.set(key, slot);
44
+ }
45
+ Object.assign(slot.changes, changes);
46
+ const promise = new Promise((resolve, reject) => {
47
+ slot.waiters.push({ resolve, reject });
48
+ });
49
+ if (!slot.done)
50
+ slot.done = drain(key, slot);
51
+ return promise;
52
+ },
53
+ settle(key) {
54
+ const slot = slots.get(key);
55
+ if (!slot)
56
+ return Promise.resolve();
57
+ const waiters = slot.waiters;
58
+ slot.changes = {};
59
+ slot.waiters = [];
60
+ for (const waiter of waiters)
61
+ waiter.resolve();
62
+ return slot.done ?? Promise.resolve();
63
+ },
64
+ };
65
+ }
66
+ //# sourceMappingURL=update-queue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"update-queue.js","sourceRoot":"","sources":["../src/update-queue.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AA+BH,MAAM,UAAU,iBAAiB,CAC/B,MAAqC;IAErC,MAAM,KAAK,GAAG,IAAI,GAAG,EAAc,CAAA;IAEnC,KAAK,UAAU,KAAK,CAAC,GAAS,EAAE,IAAU;QACxC,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC5C,yEAAyE;YACzE,8DAA8D;YAC9D,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAA;YAC5B,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAA;YAC5B,IAAI,CAAC,OAAO,GAAG,EAAE,CAAA;YACjB,IAAI,CAAC,OAAO,GAAG,EAAE,CAAA;YACjB,IAAI,CAAC;gBACH,MAAM,MAAM,CAAC,QAAQ,CAAC,MAAM,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAA;gBACtD,KAAK,MAAM,MAAM,IAAI,OAAO;oBAAE,MAAM,CAAC,OAAO,EAAE,CAAA;YAChD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,sEAAsE;gBACtE,gEAAgE;gBAChE,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAA;gBAC3B,IAAI,CAAC,OAAO,GAAG,EAAE,CAAA;gBACjB,IAAI,CAAC,OAAO,GAAG,EAAE,CAAA;gBACjB,KAAK,MAAM,MAAM,IAAI,CAAC,GAAG,OAAO,EAAE,GAAG,MAAM,CAAC;oBAAE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YACpE,CAAC;QACH,CAAC;QACD,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;IACnB,CAAC;IAED,OAAO;QACL,OAAO,CAAC,GAAG,EAAE,OAAO;YAClB,IAAI,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;YACzB,IAAI,CAAC,IAAI,EAAE,CAAC;gBACV,IAAI,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAA;gBAC/C,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,CAAA;YACtB,CAAC;YACD,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;YACpC,MAAM,OAAO,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;gBACpD,IAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAA;YACzC,CAAC,CAAC,CAAA;YACF,IAAI,CAAC,IAAI,CAAC,IAAI;gBAAE,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC,CAAA;YAC5C,OAAO,OAAO,CAAA;QAChB,CAAC;QACD,MAAM,CAAC,GAAG;YACR,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;YAC3B,IAAI,CAAC,IAAI;gBAAE,OAAO,OAAO,CAAC,OAAO,EAAE,CAAA;YACnC,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAA;YAC5B,IAAI,CAAC,OAAO,GAAG,EAAE,CAAA;YACjB,IAAI,CAAC,OAAO,GAAG,EAAE,CAAA;YACjB,KAAK,MAAM,MAAM,IAAI,OAAO;gBAAE,MAAM,CAAC,OAAO,EAAE,CAAA;YAC9C,OAAO,IAAI,CAAC,IAAI,IAAI,OAAO,CAAC,OAAO,EAAE,CAAA;QACvC,CAAC;KACF,CAAA;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bunderstack-sync",
3
- "version": "0.17.0-beta.2",
3
+ "version": "0.17.0-beta.3",
4
4
  "description": "TanStack DB collections synchronized through Bunderstack's typed oRPC client and realtime iterator.",
5
5
  "keywords": [
6
6
  "bun",
@@ -19,24 +19,27 @@
19
19
  "directory": "packages/bunderstack-sync"
20
20
  },
21
21
  "files": [
22
- "src",
23
- "!src/**/*.test.ts",
24
- "!src/**/*.types.ts",
22
+ "dist",
25
23
  "README.md",
26
24
  "LICENSE"
27
25
  ],
28
26
  "type": "module",
29
- "main": "./src/index.ts",
30
- "module": "./src/index.ts",
31
- "types": "./src/index.ts",
27
+ "main": "./dist/index.js",
28
+ "module": "./dist/index.js",
29
+ "types": "./dist/index.d.ts",
32
30
  "exports": {
33
- ".": "./src/index.ts"
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "default": "./dist/index.js"
34
+ }
34
35
  },
35
36
  "scripts": {
37
+ "build": "bun ../../scripts/build-package.ts bunderstack-sync",
38
+ "prepack": "bun run build",
36
39
  "test": "bun test"
37
40
  },
38
41
  "dependencies": {
39
- "bunderstack-query": "^0.17.0-beta.2"
42
+ "bunderstack-query": "^0.17.0-beta.3"
40
43
  },
41
44
  "devDependencies": {
42
45
  "@tanstack/db": "0.6.16",
package/src/collection.ts DELETED
@@ -1,424 +0,0 @@
1
- import type { QueryClient } from '@tanstack/react-query'
2
-
3
- import {
4
- createCollection,
5
- type Collection,
6
- type StandardSchema,
7
- } from '@tanstack/db'
8
- import { queryCollectionOptions } from '@tanstack/query-db-collection'
9
-
10
- import { createUpdateQueue } from './update-queue'
11
- const MAX_LIST_LIMIT = 200
12
-
13
- type TableListResult<TRow> = {
14
- items: TRow[]
15
- hasMore: boolean
16
- nextCursor?: string
17
- total?: number
18
- limit?: number
19
- offset?: number
20
- }
21
-
22
- type TableProcedures<TRow, TCreate, TUpdate> = {
23
- list: {
24
- call(input?: Record<string, unknown>): Promise<TableListResult<TRow>>
25
- }
26
- get: { call(input: { id: string }): Promise<TRow> }
27
- create: { call(input: TCreate): Promise<TRow> }
28
- update: {
29
- call(input: {
30
- params: { id: string }
31
- query: {}
32
- headers: {}
33
- body: TUpdate
34
- }): Promise<TRow>
35
- }
36
- delete: { call(input: { id: string }): Promise<void> }
37
- }
38
-
39
- export type DirectTableApi<TRow, TCreate, TUpdate> = {
40
- list(input?: Record<string, unknown>): Promise<TableListResult<TRow>>
41
- get(id: string | number): Promise<TRow>
42
- create(input: TCreate): Promise<TRow>
43
- update(id: string | number, input: TUpdate): Promise<TRow>
44
- delete(id: string | number): Promise<void>
45
- }
46
-
47
- export type TableCollectionConfig = {
48
- tableName: string
49
- procedures: TableProcedures<any, any, any>
50
- queryClient: QueryClient
51
- /** Rows the default `.collection` syncs per fetch. Defaults to 100. For
52
- * feed-shaped tables that need real pagination use `scopedCollection`. */
53
- limit?: number
54
- }
55
-
56
- export type ScopedFilterValue =
57
- | string
58
- | number
59
- | boolean
60
- | null
61
- | readonly (string | number)[]
62
-
63
- export type ScopedCollectionOptions = {
64
- /** Equality filters, e.g. `{ replyToId: null }` — columns must be in the
65
- * table's `filterableColumns` server-side. Same name and shape as the
66
- * `filters` accepted by the list procedure. */
67
- filters?: Record<string, ScopedFilterValue>
68
- sort?: string
69
- order?: 'asc' | 'desc'
70
- /** Rows per underlying request; clamped to the server cap (200). */
71
- pageSize?: number
72
- /** Window size on first load and default `loadMore` step. Defaults to 20. */
73
- initialCount?: number
74
- }
75
-
76
- function matchesFilter(
77
- record: Record<string, unknown>,
78
- filters: Record<string, ScopedFilterValue>,
79
- ): boolean {
80
- for (const [col, expected] of Object.entries(filters)) {
81
- const actual = record[col]
82
- if (expected === null) {
83
- if (actual != null) return false
84
- } else if (Array.isArray(expected)) {
85
- if (!expected.map(String).includes(String(actual))) return false
86
- } else if (String(actual) !== String(expected)) return false
87
- }
88
- return true
89
- }
90
-
91
- /** Deterministic serialization for cache keys (object key order ignored). */
92
- function stableKey(value: unknown): string {
93
- if (value === null || typeof value !== 'object') return JSON.stringify(value)
94
- if (Array.isArray(value)) return `[${value.map(stableKey).join(',')}]`
95
- const entries = Object.entries(value as Record<string, unknown>)
96
- .sort(([a], [b]) => (a < b ? -1 : 1))
97
- .map(([k, v]) => `${JSON.stringify(k)}:${stableKey(v)}`)
98
- return `{${entries.join(',')}}`
99
- }
100
-
101
- export function createTableCollection<
102
- TRow extends { id: string | number },
103
- TCreate = Partial<TRow>,
104
- TUpdate = Partial<TRow>,
105
- >(config: TableCollectionConfig) {
106
- const table = config.procedures as TableProcedures<TRow, TCreate, TUpdate>
107
- const direct: DirectTableApi<TRow, TCreate, TUpdate> = {
108
- list: (input = {}) => table.list.call(input),
109
- get: (id) => table.get.call({ id: String(id) }),
110
- create: (input) => table.create.call(input),
111
- update: (id, input) =>
112
- table.update.call({
113
- params: { id: String(id) },
114
- query: {},
115
- headers: {},
116
- body: input,
117
- }),
118
- delete: (id) => table.delete.call({ id: String(id) }),
119
- }
120
-
121
- const collection = createCollection(
122
- queryCollectionOptions<TRow>({
123
- queryKey: [config.tableName, 'collection'],
124
- queryFn: async () => {
125
- const page = await table.list.call({ limit: config.limit ?? 100 })
126
- return page.items
127
- },
128
- queryClient: config.queryClient,
129
- getKey: (item) => item.id,
130
- onInsert: async ({ transaction }) => {
131
- let reconciled = true
132
- for (const mutation of transaction.mutations) {
133
- // Pass the client-generated `id` through as-is. TanStack DB's
134
- // optimistic insert keys the local row by this `id` (via `getKey`),
135
- // and this matches `sanitizeWriteBody`'s default on the server: a
136
- // client-supplied `id` on create is accepted unless the table's
137
- // access config sets an explicit `writableColumns` allowlist that
138
- // excludes `id`.
139
- const row = (await table.create.call(
140
- mutation.modified as unknown as TCreate,
141
- )) as TRow | undefined
142
- // Apps that DO restrict it that way get a server-assigned id, which
143
- // leaves the optimistic row keyed under the client's — `writeUpsert`
144
- // can't retire that, so those fall back to the refetch.
145
- if (row?.id != null && String(row.id) === String(mutation.key)) {
146
- applyRealtimeEvent('create', row as Record<string, unknown>)
147
- } else {
148
- reconciled = false
149
- }
150
- }
151
- return reconciled ? { refetch: false } : {}
152
- },
153
- onUpdate: async ({ transaction }) => {
154
- await Promise.all(
155
- transaction.mutations.map((mutation) =>
156
- updateQueue.enqueue(
157
- mutation.key as TRow['id'],
158
- mutation.changes as Record<string, unknown>,
159
- ),
160
- ),
161
- )
162
- return { refetch: false }
163
- },
164
- onDelete: async ({ transaction }) => {
165
- for (const mutation of transaction.mutations) {
166
- // Updates still queued for this row are superseded, and one already
167
- // in flight must land before the DELETE or the two race.
168
- await updateQueue.settle(mutation.key as TRow['id'])
169
- await table.delete.call({ id: String(mutation.key) })
170
- applyRealtimeEvent('delete', { id: mutation.key })
171
- }
172
- return { refetch: false }
173
- },
174
- }),
175
- )
176
-
177
- // Cursor-shaped workloads call `update()` many times a second. The queue
178
- // merges everything that piles up for a row while its request is in flight
179
- // into a single follow-up, so request rate tracks RTT, not call rate.
180
- const updateQueue = createUpdateQueue<TRow['id'], TRow>({
181
- send: (id, changes) =>
182
- table.update.call({
183
- params: { id: String(id) },
184
- query: {},
185
- headers: {},
186
- body: changes as unknown as TUpdate,
187
- }),
188
- onResult: async (row) => {
189
- // `writeUpsert` writes the response whole, so mutation endpoints are
190
- // contracted to return a full row. A body without an id can't be
191
- // reconciled locally — fall back to the refetch rather than write it.
192
- if ((row as TRow | undefined)?.id == null)
193
- await collection.utils.refetch()
194
- else applyRealtimeEvent('update', row as Record<string, unknown>)
195
- },
196
- })
197
-
198
- type Collection = typeof collection
199
-
200
- // Scoped/byIds collections register here so realtime events fan out to
201
- // every live view of this table, filtered client-side by each view's
202
- // own predicate (broadcasts are already access-filtered server-side).
203
- const registry: {
204
- collection: Collection
205
- matches: (record: Record<string, unknown>) => boolean
206
- refetch: () => Promise<void>
207
- }[] = []
208
-
209
- const scopedCache = new Map<string, ScopedCollection>()
210
-
211
- type ScopedCollection = {
212
- collection: Collection
213
- /** Grow the window by `count` (default initialCount) and refetch in place. */
214
- loadMore: (count?: number) => Promise<void>
215
- /** Whether the server reported rows beyond the window (as of last fetch). */
216
- hasMore: () => boolean
217
- /** Current desired window size. */
218
- size: () => number
219
- }
220
-
221
- function scopedCollection(
222
- options: ScopedCollectionOptions = {},
223
- ): ScopedCollection {
224
- const pageSize = Math.min(
225
- options.pageSize ?? MAX_LIST_LIMIT,
226
- MAX_LIST_LIMIT,
227
- )
228
- const initialCount = options.initialCount ?? 20
229
- const filters = options.filters ?? {}
230
- const cacheKey = stableKey({
231
- filters,
232
- sort: options.sort ?? null,
233
- order: options.order ?? null,
234
- pageSize,
235
- initialCount,
236
- })
237
- const cached = scopedCache.get(cacheKey)
238
- if (cached) return cached
239
-
240
- let desiredCount = initialCount
241
- let serverHasMore = false
242
-
243
- const scoped = createCollection(
244
- queryCollectionOptions<TRow>({
245
- queryKey: [config.tableName, 'scoped', cacheKey],
246
- queryFn: async () => {
247
- // Growing window: walk cursor pages (each ≤ the server cap) until
248
- // the current desired count is collected or the table runs out.
249
- // The collection stays stable across loadMore — refetching in
250
- // place only ever adds rows, so already-rendered items never
251
- // unmount (no scroll jumps or zero-item flashes).
252
- const items: TRow[] = []
253
- let cursor: string | undefined
254
- let more = false
255
- while (items.length < desiredCount) {
256
- const remaining = Math.min(pageSize, desiredCount - items.length)
257
- const page = await table.list.call({
258
- ...(Object.keys(filters).length ? { filters } : {}),
259
- ...(options.sort ? { sort: options.sort } : {}),
260
- ...(options.order ? { order: options.order } : {}),
261
- limit: remaining,
262
- ...(cursor ? { cursor } : {}),
263
- })
264
- items.push(...page.items)
265
- more = Boolean(page.hasMore && page.nextCursor)
266
- if (!more) break
267
- cursor = page.nextCursor
268
- }
269
- serverHasMore = more
270
- return items.slice(0, desiredCount)
271
- },
272
- queryClient: config.queryClient,
273
- getKey: (item) => item.id,
274
- }),
275
- )
276
-
277
- const entry: ScopedCollection = {
278
- collection: scoped,
279
- loadMore: async (count) => {
280
- desiredCount += count ?? initialCount
281
- await scoped.utils.refetch()
282
- },
283
- hasMore: () => serverHasMore,
284
- size: () => desiredCount,
285
- }
286
- registry.push({
287
- collection: scoped,
288
- matches: (record) => matchesFilter(record, filters),
289
- refetch: async () => {
290
- await scoped.utils.refetch()
291
- },
292
- })
293
- scopedCache.set(cacheKey, entry)
294
- return entry
295
- }
296
-
297
- const byIdsCache = new Map<string, Collection>()
298
-
299
- function collectionByIds(
300
- ids: readonly TRow['id'][],
301
- options: { column?: string } = {},
302
- ): Collection {
303
- const column = options.column ?? 'id'
304
- const unique = Array.from(new Set(ids.map(String))).sort()
305
- const cacheKey = `${column}:${unique.join(',')}`
306
- const cached = byIdsCache.get(cacheKey)
307
- if (cached) return cached
308
-
309
- const idSet = new Set(unique)
310
- const byIds = createCollection(
311
- queryCollectionOptions<TRow>({
312
- queryKey: [config.tableName, 'byIds', column, unique],
313
- queryFn: async () => {
314
- if (unique.length === 0) return []
315
- const items: TRow[] = []
316
- // Chunked at the server's IN-filter cap so any id set works.
317
- for (let i = 0; i < unique.length; i += MAX_LIST_LIMIT) {
318
- const chunk = unique.slice(i, i + MAX_LIST_LIMIT)
319
- const page = await table.list.call({
320
- filters: { [column]: chunk },
321
- limit: chunk.length,
322
- })
323
- items.push(...page.items)
324
- }
325
- return items
326
- },
327
- queryClient: config.queryClient,
328
- getKey: (item) => item.id,
329
- }),
330
- )
331
- registry.push({
332
- collection: byIds,
333
- matches: (record) => idSet.has(String(record[column])),
334
- refetch: async () => {
335
- await byIds.utils.refetch()
336
- },
337
- })
338
- byIdsCache.set(cacheKey, byIds)
339
- return byIds
340
- }
341
-
342
- function applyRealtimeEvent(
343
- action: 'create' | 'update' | 'delete',
344
- record: Record<string, unknown>,
345
- ) {
346
- const id = record['id'] as string | number
347
- const apply = (
348
- target: Collection,
349
- matches: (record: Record<string, unknown>) => boolean,
350
- ) => {
351
- // Collections that never started syncing (no subscribers yet) can't
352
- // accept manual writes — and don't need to: their first sync fetches
353
- // fresh data anyway.
354
- if (target.status !== 'ready') return
355
- if (action === 'delete' || !matches(record)) {
356
- if (target.get(id) !== undefined) target.utils.writeDelete(id)
357
- } else {
358
- target.utils.writeUpsert(record as unknown as TRow)
359
- }
360
- }
361
- apply(collection, () => true)
362
- for (const entry of registry) apply(entry.collection, entry.matches)
363
- }
364
-
365
- /** Refetch the base collection plus every scoped/byIds view after reconnect. */
366
- async function refetchAll() {
367
- await Promise.all([
368
- collection.utils.refetch(),
369
- ...registry.map((entry) => entry.refetch()),
370
- ])
371
- }
372
-
373
- return {
374
- collection,
375
- table: direct,
376
- scopedCollection,
377
- collectionByIds,
378
- applyRealtimeEvent,
379
- refetchAll,
380
- }
381
- }
382
-
383
- export type ScopedCollection<TRow extends { id: string | number }> = {
384
- collection: Collection<
385
- TRow,
386
- string | number,
387
- Record<string, any>,
388
- StandardSchema<TRow>
389
- >
390
- loadMore: (count?: number) => Promise<void>
391
- hasMore: () => boolean
392
- size: () => number
393
- }
394
-
395
- export type TableCollection<
396
- TRow extends { id: string | number },
397
- TCreate = Partial<TRow>,
398
- TUpdate = Partial<TRow>,
399
- > = {
400
- collection: Collection<
401
- TRow,
402
- string | number,
403
- Record<string, any>,
404
- StandardSchema<TRow>
405
- >
406
- table: DirectTableApi<TRow, TCreate, TUpdate>
407
- scopedCollection: (
408
- options?: ScopedCollectionOptions,
409
- ) => ScopedCollection<TRow>
410
- collectionByIds: (
411
- ids: readonly (string | number)[],
412
- column?: string,
413
- ) => Collection<
414
- TRow,
415
- string | number,
416
- Record<string, any>,
417
- StandardSchema<TRow>
418
- >
419
- applyRealtimeEvent: (
420
- action: 'create' | 'update' | 'delete',
421
- record: Record<string, unknown>,
422
- ) => void
423
- refetchAll: () => Promise<void>
424
- }
package/src/index.ts DELETED
@@ -1,7 +0,0 @@
1
- export { createSyncClient } from './sync-client'
2
- export type { BunderstackSyncClient, CreateFor, RowFor, SyncClientOptions } from './sync-client'
3
- export { createTableCollection } from './collection'
4
- export type { ScopedCollectionOptions, ScopedFilterValue, TableCollection, TableCollectionConfig } from './collection'
5
- export { createSyncRealtimeClient } from './realtime-sync'
6
- export type { SyncRealtimeConfig, SyncRealtimeTarget } from './realtime-sync'
7
- export type { AnyBunderstackApp, InferBuckets, InferInsert, InferSchema, InferSelect, InferTables, UploadedFile } from 'bunderstack-query'
@@ -1,61 +0,0 @@
1
- import type { QueryClient } from '@tanstack/react-query'
2
- import {
3
- syncRealtime,
4
- type RealtimeQueryApi,
5
- type RealtimeSyncHandle,
6
- } from 'bunderstack-query'
7
-
8
- type SyncableCollection = {
9
- utils: {
10
- writeUpsert: (item: unknown) => void
11
- writeDelete: (key: unknown) => void
12
- refetch: () => Promise<void>
13
- }
14
- }
15
-
16
- export type SyncRealtimeTarget = {
17
- applyRealtimeEvent: (
18
- action: 'create' | 'update' | 'delete',
19
- record: Record<string, unknown>,
20
- ) => void
21
- refetchAll: () => Promise<void>
22
- }
23
-
24
- export type SyncRealtimeConfig = {
25
- api: RealtimeQueryApi
26
- queryClient: QueryClient
27
- tables: string[]
28
- collections?: Record<string, SyncableCollection>
29
- resolve?: (table: string) => SyncRealtimeTarget | undefined
30
- resolveAll?: () => Iterable<SyncRealtimeTarget>
31
- retryMs?: number
32
- }
33
-
34
- export function createSyncRealtimeClient(
35
- config: SyncRealtimeConfig,
36
- ): RealtimeSyncHandle {
37
- const collections = config.collections ?? {}
38
- return syncRealtime({
39
- api: config.api,
40
- queryClient: config.queryClient,
41
- tables: config.tables,
42
- retryMs: config.retryMs,
43
- onChange: (event) => {
44
- if (config.resolve) {
45
- config.resolve(event.table)?.applyRealtimeEvent(event.action, event.record)
46
- return
47
- }
48
- const collection = collections[event.table]
49
- if (!collection) return
50
- if (event.action === 'delete') collection.utils.writeDelete(event.record['id'])
51
- else collection.utils.writeUpsert(event.record)
52
- },
53
- onReconnect: async () => {
54
- if (config.resolveAll) {
55
- await Promise.all([...config.resolveAll()].map((target) => target.refetchAll()))
56
- return
57
- }
58
- await Promise.all(Object.values(collections).map((collection) => collection.utils.refetch()))
59
- },
60
- })
61
- }