@anfenn/dync 1.0.25 → 1.0.26

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.
@@ -20,1741 +20,47 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/react/index.ts
21
21
  var react_exports = {};
22
22
  __export(react_exports, {
23
- makeDync: () => makeDync
23
+ useLiveQuery: () => useLiveQuery,
24
+ useSyncState: () => useSyncState
24
25
  });
25
26
  module.exports = __toCommonJS(react_exports);
26
27
 
27
- // src/react/useDync.ts
28
+ // src/react/useSyncState.ts
28
29
  var import_react = require("react");
29
-
30
- // src/logger.ts
31
- function newLogger(base, min) {
32
- const order = {
33
- debug: 10,
34
- info: 20,
35
- warn: 30,
36
- error: 40,
37
- none: 100
38
- };
39
- const threshold = order[min];
40
- const enabled = (lvl) => order[lvl] >= threshold;
41
- return {
42
- debug: (...a) => enabled("debug") && base.debug?.(...a),
43
- info: (...a) => enabled("info") && base.info?.(...a),
44
- warn: (...a) => enabled("warn") && base.warn?.(...a),
45
- error: (...a) => enabled("error") && base.error?.(...a)
46
- };
47
- }
48
-
49
- // src/types.ts
50
- var SERVER_PK = "id";
51
- var LOCAL_PK = "_localId";
52
- var UPDATED_AT = "updated_at";
53
- var ApiError = class extends Error {
54
- isNetworkError;
55
- cause;
56
- constructor(message, isNetworkError2, cause) {
57
- super(message);
58
- this.name = "ApiError";
59
- this.isNetworkError = isNetworkError2;
60
- this.cause = cause;
61
- }
62
- };
63
-
64
- // src/createLocalId.ts
65
- function createLocalId() {
66
- if (typeof globalThis.crypto?.randomUUID === "function") {
67
- return globalThis.crypto.randomUUID();
68
- }
69
- throw new Error("createLocalId(): crypto.randomUUID is not available");
70
- }
71
-
72
- // src/helpers.ts
73
- function parseApiError(error) {
74
- if (error instanceof ApiError) {
75
- return error;
76
- }
77
- if (typeof error === "string") {
78
- return new ApiError(error, false);
79
- }
80
- return new ApiError(error.message, isNetworkError(error), error);
81
- }
82
- function isNetworkError(error) {
83
- const message = error.message?.toLowerCase() ?? "";
84
- const name = error.name;
85
- if (message.includes("failed to fetch") || message.includes("network request failed")) {
86
- return true;
87
- }
88
- const code = error.code;
89
- if (code === "ERR_NETWORK" || code === "ECONNABORTED" || code === "ENOTFOUND" || code === "ECONNREFUSED") {
90
- return true;
91
- }
92
- if (error.isAxiosError && error.response === void 0) {
93
- return true;
94
- }
95
- if (name === "ApolloError" && error.networkError) {
96
- return true;
97
- }
98
- if (message.includes("network error") || message.includes("networkerror")) {
99
- return true;
100
- }
101
- return false;
102
- }
103
- function sleep(ms, signal) {
104
- return new Promise((resolve) => {
105
- if (signal?.aborted) {
106
- resolve();
107
- return;
108
- }
109
- const timer = setTimeout(resolve, ms);
110
- signal?.addEventListener("abort", () => {
111
- clearTimeout(timer);
112
- resolve();
113
- });
114
- });
115
- }
116
- function orderFor(a) {
117
- switch (a) {
118
- case "create" /* Create */:
119
- return 1;
120
- case "update" /* Update */:
121
- return 2;
122
- case "remove" /* Remove */:
123
- return 3;
124
- }
125
- }
126
- function omitFields(item, fields) {
127
- const result = { ...item };
128
- for (const k of fields) delete result[k];
129
- return result;
130
- }
131
- function deleteKeyIfEmptyObject(obj, key) {
132
- if (obj[key] && Object.keys(obj[key]).length === 0) {
133
- delete obj[key];
134
- }
135
- }
136
-
137
- // src/addVisibilityChangeListener.ts
138
- function addVisibilityChangeListener(add, currentSubscription, onVisibilityChange) {
139
- if (add && !currentSubscription) {
140
- const handler = () => {
141
- onVisibilityChange(document.visibilityState === "visible");
142
- };
143
- document.addEventListener("visibilitychange", handler);
144
- return {
145
- remove: () => {
146
- document.removeEventListener("visibilitychange", handler);
147
- }
148
- };
149
- } else if (!add && currentSubscription) {
150
- currentSubscription.remove();
151
- return void 0;
152
- }
153
- return currentSubscription;
154
- }
155
-
156
- // src/core/StateManager.ts
157
- var LOCAL_ONLY_SYNC_FIELDS = [LOCAL_PK, UPDATED_AT];
158
- var DYNC_STATE_TABLE = "_dync_state";
159
- var SYNC_STATE_KEY = "sync_state";
160
- var DEFAULT_STATE = {
161
- firstLoadDone: false,
162
- pendingChanges: [],
163
- lastPulled: {}
164
- };
165
- var StateManager = class {
166
- persistedState;
167
- syncStatus;
168
- apiError;
169
- listeners = /* @__PURE__ */ new Set();
170
- storageAdapter;
171
- hydrated = false;
172
- constructor(ctx) {
173
- this.storageAdapter = ctx.storageAdapter;
174
- this.persistedState = DEFAULT_STATE;
175
- this.syncStatus = ctx.initialStatus ?? "disabled";
176
- }
177
- /**
178
- * Load state from the database. Called after stores() defines the schema.
179
- */
180
- async hydrate() {
181
- if (this.hydrated) return;
182
- if (!this.storageAdapter) {
183
- throw new Error("Cannot hydrate state without a storage adapter");
184
- }
185
- const table = this.storageAdapter.table(DYNC_STATE_TABLE);
186
- const row = await table.get(SYNC_STATE_KEY);
187
- if (row?.value) {
188
- this.persistedState = parseStoredState(row.value);
189
- }
190
- this.hydrated = true;
191
- this.emit();
192
- }
193
- emit() {
194
- this.listeners.forEach((fn) => fn(this.getSyncState()));
195
- }
196
- async persist() {
197
- if (!this.hydrated || !this.storageAdapter) return;
198
- this.emit();
199
- const table = this.storageAdapter.table(DYNC_STATE_TABLE);
200
- await table.put({ [LOCAL_PK]: SYNC_STATE_KEY, value: JSON.stringify(this.persistedState) });
201
- }
202
- getState() {
203
- return clonePersistedState(this.persistedState);
204
- }
205
- setState(setterOrState) {
206
- this.persistedState = resolveNextState(this.persistedState, setterOrState);
207
- return this.persist();
208
- }
209
- setApiError(error) {
210
- this.apiError = error ? parseApiError(error) : void 0;
211
- this.emit();
212
- }
213
- addPendingChange(change) {
214
- const next = clonePersistedState(this.persistedState);
215
- const queueItem = next.pendingChanges.find((p) => p.localId === change.localId && p.tableName === change.tableName);
216
- const omittedChanges = omitFields(change.changes, LOCAL_ONLY_SYNC_FIELDS);
217
- const omittedBefore = omitFields(change.before, LOCAL_ONLY_SYNC_FIELDS);
218
- const omittedAfter = omitFields(change.after, LOCAL_ONLY_SYNC_FIELDS);
219
- const hasChanges = Object.keys(omittedChanges || {}).length > 0;
220
- const action = change.action;
221
- if (queueItem) {
222
- if (queueItem.action === "remove" /* Remove */) {
223
- return Promise.resolve();
224
- }
225
- queueItem.version += 1;
226
- if (action === "remove" /* Remove */) {
227
- queueItem.action = "remove" /* Remove */;
228
- } else if (hasChanges) {
229
- queueItem.changes = { ...queueItem.changes, ...omittedChanges };
230
- queueItem.after = { ...queueItem.after, ...omittedAfter };
231
- }
232
- } else if (action === "remove" /* Remove */ || hasChanges) {
233
- next.pendingChanges = [...next.pendingChanges];
234
- next.pendingChanges.push({
235
- action,
236
- tableName: change.tableName,
237
- localId: change.localId,
238
- id: change.id,
239
- version: 1,
240
- changes: omittedChanges,
241
- before: omittedBefore,
242
- after: omittedAfter
243
- });
244
- }
245
- this.persistedState = next;
246
- return this.persist();
247
- }
248
- samePendingVersion(tableName, localId, version) {
249
- return this.persistedState.pendingChanges.find((p) => p.localId === localId && p.tableName === tableName)?.version === version;
250
- }
251
- removePendingChange(localId, tableName) {
252
- const next = clonePersistedState(this.persistedState);
253
- next.pendingChanges = next.pendingChanges.filter((p) => !(p.localId === localId && p.tableName === tableName));
254
- this.persistedState = next;
255
- return this.persist();
256
- }
257
- updatePendingChange(tableName, localId, action, id) {
258
- const next = clonePersistedState(this.persistedState);
259
- const changeItem = next.pendingChanges.find((p) => p.tableName === tableName && p.localId === localId);
260
- if (changeItem) {
261
- changeItem.action = action;
262
- if (id) changeItem.id = id;
263
- this.persistedState = next;
264
- return this.persist();
265
- }
266
- return Promise.resolve();
267
- }
268
- setPendingChangeBefore(tableName, localId, before) {
269
- const next = clonePersistedState(this.persistedState);
270
- const changeItem = next.pendingChanges.find((p) => p.tableName === tableName && p.localId === localId);
271
- if (changeItem) {
272
- changeItem.before = { ...changeItem.before ?? {}, ...before };
273
- this.persistedState = next;
274
- return this.persist();
275
- }
276
- return Promise.resolve();
277
- }
278
- hasConflicts(localId) {
279
- return Boolean(this.persistedState.conflicts?.[localId]);
280
- }
281
- getSyncStatus() {
282
- return this.syncStatus;
283
- }
284
- setSyncStatus(status) {
285
- if (this.syncStatus === status) return;
286
- this.syncStatus = status;
287
- this.emit();
288
- }
289
- getSyncState() {
290
- return buildSyncState(this.persistedState, this.syncStatus, this.hydrated, this.apiError);
291
- }
292
- subscribe(listener) {
293
- this.listeners.add(listener);
294
- return () => this.listeners.delete(listener);
295
- }
296
- };
297
- function parseStoredState(stored) {
298
- const parsed = JSON.parse(stored);
299
- if (parsed.pendingChanges) {
300
- parsed.pendingChanges = parsed.pendingChanges.map((change) => ({
301
- ...change,
302
- timestamp: change.timestamp ? new Date(change.timestamp) : change.timestamp
303
- }));
304
- }
305
- return parsed;
306
- }
307
- function resolveNextState(current, setterOrState) {
308
- if (typeof setterOrState === "function") {
309
- return { ...current, ...setterOrState(clonePersistedState(current)) };
310
- }
311
- return { ...current, ...setterOrState };
312
- }
313
- function buildSyncState(state, status, hydrated, apiError) {
314
- const persisted = clonePersistedState(state);
315
- const syncState = {
316
- ...persisted,
317
- status,
318
- hydrated,
319
- apiError
320
- };
321
- deleteKeyIfEmptyObject(syncState, "conflicts");
322
- return syncState;
323
- }
324
- function clonePersistedState(state) {
325
- return {
326
- ...state,
327
- pendingChanges: state.pendingChanges.map((change) => ({
328
- ...change,
329
- changes: cloneRecord(change.changes),
330
- before: cloneRecord(change.before),
331
- after: cloneRecord(change.after)
332
- })),
333
- lastPulled: { ...state.lastPulled },
334
- conflicts: cloneConflicts(state.conflicts)
335
- };
336
- }
337
- function cloneConflicts(conflicts) {
338
- if (!conflicts) return void 0;
339
- const next = {};
340
- for (const [key, value] of Object.entries(conflicts)) {
341
- next[key] = {
342
- tableName: value.tableName,
343
- fields: value.fields.map((field) => ({ ...field }))
344
- };
345
- }
346
- return next;
347
- }
348
- function cloneRecord(record) {
349
- if (!record) return record;
350
- return { ...record };
351
- }
352
-
353
- // src/core/tableEnhancers.ts
354
- function wrapWithMutationEmitter(table, tableName, emitMutation) {
355
- const rawAdd = table.raw.add;
356
- const rawPut = table.raw.put;
357
- const rawUpdate = table.raw.update;
358
- const rawDelete = table.raw.delete;
359
- const rawBulkAdd = table.raw.bulkAdd;
360
- const rawBulkPut = table.raw.bulkPut;
361
- const rawBulkUpdate = table.raw.bulkUpdate;
362
- const rawBulkDelete = table.raw.bulkDelete;
363
- const rawClear = table.raw.clear;
364
- table.add = async (item) => {
365
- const result = await rawAdd(item);
366
- emitMutation({ type: "add", tableName, keys: [result] });
367
- return result;
368
- };
369
- table.put = async (item) => {
370
- const result = await rawPut(item);
371
- emitMutation({ type: "update", tableName, keys: [result] });
372
- return result;
373
- };
374
- table.update = async (key, changes) => {
375
- const result = await rawUpdate(key, changes);
376
- if (result > 0) {
377
- emitMutation({ type: "update", tableName, keys: [key] });
378
- }
379
- return result;
380
- };
381
- table.delete = async (key) => {
382
- await rawDelete(key);
383
- emitMutation({ type: "delete", tableName, keys: [key] });
384
- };
385
- table.bulkAdd = async (items) => {
386
- const result = await rawBulkAdd(items);
387
- if (items.length > 0) {
388
- emitMutation({ type: "add", tableName });
389
- }
390
- return result;
391
- };
392
- table.bulkPut = async (items) => {
393
- const result = await rawBulkPut(items);
394
- if (items.length > 0) {
395
- emitMutation({ type: "update", tableName });
396
- }
397
- return result;
398
- };
399
- table.bulkUpdate = async (keysAndChanges) => {
400
- const result = await rawBulkUpdate(keysAndChanges);
401
- if (result > 0) {
402
- emitMutation({ type: "update", tableName, keys: keysAndChanges.map((kc) => kc.key) });
403
- }
404
- return result;
405
- };
406
- table.bulkDelete = async (keys) => {
407
- await rawBulkDelete(keys);
408
- if (keys.length > 0) {
409
- emitMutation({ type: "delete", tableName });
410
- }
411
- };
412
- table.clear = async () => {
413
- await rawClear();
414
- emitMutation({ type: "delete", tableName });
415
- };
416
- }
417
- function setupEnhancedTables({ owner, tableCache, enhancedTables, getTable }, tableNames) {
418
- for (const tableName of tableNames) {
419
- tableCache.delete(tableName);
420
- enhancedTables.delete(tableName);
421
- if (!Object.prototype.hasOwnProperty.call(owner, tableName)) {
422
- Object.defineProperty(owner, tableName, {
423
- get: () => getTable(tableName),
424
- enumerable: true,
425
- configurable: true
426
- });
427
- }
428
- }
429
- }
430
- function enhanceSyncTable({ table, tableName, withTransaction, state, enhancedTables, emitMutation }) {
431
- const rawAdd = table.raw.add;
432
- const rawPut = table.raw.put;
433
- const rawUpdate = table.raw.update;
434
- const rawDelete = table.raw.delete;
435
- const rawBulkAdd = table.raw.bulkAdd;
436
- const rawBulkPut = table.raw.bulkPut;
437
- const rawBulkUpdate = table.raw.bulkUpdate;
438
- const rawBulkDelete = table.raw.bulkDelete;
439
- const rawClear = table.raw.clear;
440
- const wrappedAdd = async (item) => {
441
- let localId = item._localId;
442
- if (!localId) localId = createLocalId();
443
- const syncedItem = {
444
- ...item,
445
- _localId: localId,
446
- updated_at: (/* @__PURE__ */ new Date()).toISOString()
447
- };
448
- let result;
449
- await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async () => {
450
- result = await rawAdd(syncedItem);
451
- await state.addPendingChange({
452
- action: "create" /* Create */,
453
- tableName,
454
- localId,
455
- changes: syncedItem,
456
- before: null,
457
- after: syncedItem
458
- });
459
- });
460
- emitMutation({ type: "add", tableName, keys: [localId] });
461
- return result;
462
- };
463
- const wrappedPut = async (item) => {
464
- let localId = item._localId;
465
- if (!localId) localId = createLocalId();
466
- const syncedItem = {
467
- ...item,
468
- _localId: localId,
469
- updated_at: (/* @__PURE__ */ new Date()).toISOString()
470
- };
471
- let result;
472
- let isUpdate = false;
473
- let existingRecord;
474
- await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
475
- const txTable = tables[tableName];
476
- existingRecord = await txTable.get(localId);
477
- isUpdate = !!existingRecord;
478
- result = await rawPut(syncedItem);
479
- await state.addPendingChange({
480
- action: isUpdate ? "update" /* Update */ : "create" /* Create */,
481
- tableName,
482
- localId,
483
- id: existingRecord?.id,
484
- changes: syncedItem,
485
- before: existingRecord ?? null,
486
- after: syncedItem
487
- });
488
- });
489
- emitMutation({ type: isUpdate ? "update" : "add", tableName, keys: [localId] });
490
- return result;
491
- };
492
- const wrappedUpdate = async (key, changes) => {
493
- const updatedChanges = {
494
- ...changes,
495
- updated_at: (/* @__PURE__ */ new Date()).toISOString()
496
- };
497
- let result = 0;
498
- await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
499
- const txTable = tables[tableName];
500
- const record = await txTable.get(key);
501
- if (!record) {
502
- throw new Error(`Record with key=${key} not found`);
503
- }
504
- result = await rawUpdate(key, updatedChanges) ?? 0;
505
- if (result > 0) {
506
- await state.addPendingChange({
507
- action: "update" /* Update */,
508
- tableName,
509
- localId: key,
510
- id: record.id,
511
- changes: updatedChanges,
512
- before: record,
513
- after: { ...record, ...updatedChanges }
514
- });
515
- }
516
- });
517
- if (result > 0) {
518
- emitMutation({ type: "update", tableName, keys: [key] });
519
- }
520
- return result;
521
- };
522
- const wrappedDelete = async (key) => {
523
- let deletedLocalId;
524
- await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
525
- const txTable = tables[tableName];
526
- const record = await txTable.get(key);
527
- await rawDelete(key);
528
- if (record) {
529
- deletedLocalId = record._localId;
530
- await state.addPendingChange({
531
- action: "remove" /* Remove */,
532
- tableName,
533
- localId: record._localId,
534
- id: record.id,
535
- changes: null,
536
- before: record
537
- });
538
- }
539
- });
540
- if (deletedLocalId) {
541
- emitMutation({ type: "delete", tableName, keys: [deletedLocalId] });
542
- }
543
- };
544
- const wrappedBulkAdd = async (items) => {
545
- if (items.length === 0) return [];
546
- const now = (/* @__PURE__ */ new Date()).toISOString();
547
- const syncedItems = items.map((item) => {
548
- const localId = item._localId || createLocalId();
549
- return {
550
- ...item,
551
- _localId: localId,
552
- updated_at: now
553
- };
554
- });
555
- let result;
556
- await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async () => {
557
- result = await rawBulkAdd(syncedItems);
558
- for (const syncedItem of syncedItems) {
559
- await state.addPendingChange({
560
- action: "create" /* Create */,
561
- tableName,
562
- localId: syncedItem._localId,
563
- changes: syncedItem,
564
- before: null,
565
- after: syncedItem
566
- });
567
- }
568
- });
569
- emitMutation({ type: "add", tableName, keys: syncedItems.map((i) => i._localId) });
570
- return result;
571
- };
572
- const wrappedBulkPut = async (items) => {
573
- if (items.length === 0) return [];
574
- const now = (/* @__PURE__ */ new Date()).toISOString();
575
- const syncedItems = items.map((item) => {
576
- const localId = item._localId || createLocalId();
577
- return {
578
- ...item,
579
- _localId: localId,
580
- updated_at: now
581
- };
582
- });
583
- const localIds = syncedItems.map((i) => i._localId);
584
- let result;
585
- await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
586
- const txTable = tables[tableName];
587
- const existingRecords = await txTable.bulkGet(localIds);
588
- const existingMap = /* @__PURE__ */ new Map();
589
- for (let i = 0; i < localIds.length; i++) {
590
- if (existingRecords[i]) {
591
- existingMap.set(localIds[i], existingRecords[i]);
592
- }
593
- }
594
- result = await rawBulkPut(syncedItems);
595
- for (const syncedItem of syncedItems) {
596
- const existing = existingMap.get(syncedItem._localId);
597
- await state.addPendingChange({
598
- action: existing ? "update" /* Update */ : "create" /* Create */,
599
- tableName,
600
- localId: syncedItem._localId,
601
- id: existing?.id,
602
- changes: syncedItem,
603
- before: existing ?? null,
604
- after: syncedItem
605
- });
606
- }
607
- });
608
- emitMutation({ type: "update", tableName, keys: localIds });
609
- return result;
610
- };
611
- const wrappedBulkUpdate = async (keysAndChanges) => {
612
- if (keysAndChanges.length === 0) return 0;
613
- const now = (/* @__PURE__ */ new Date()).toISOString();
614
- const updatedKeysAndChanges = keysAndChanges.map(({ key, changes }) => ({
615
- key,
616
- changes: {
617
- ...changes,
618
- updated_at: now
619
- }
620
- }));
621
- let result = 0;
622
- const updatedKeys = [];
623
- await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
624
- const txTable = tables[tableName];
625
- const keys = updatedKeysAndChanges.map((kc) => kc.key);
626
- const records = await txTable.bulkGet(keys);
627
- const recordMap = /* @__PURE__ */ new Map();
628
- for (let i = 0; i < keys.length; i++) {
629
- if (records[i]) {
630
- recordMap.set(String(keys[i]), records[i]);
631
- }
632
- }
633
- result = await rawBulkUpdate(updatedKeysAndChanges);
634
- for (const { key, changes } of updatedKeysAndChanges) {
635
- const record = recordMap.get(String(key));
636
- if (record) {
637
- updatedKeys.push(record._localId);
638
- await state.addPendingChange({
639
- action: "update" /* Update */,
640
- tableName,
641
- localId: record._localId,
642
- id: record.id,
643
- changes,
644
- before: record,
645
- after: { ...record, ...changes }
646
- });
647
- }
648
- }
649
- });
650
- if (updatedKeys.length > 0) {
651
- emitMutation({ type: "update", tableName, keys: updatedKeys });
652
- }
653
- return result;
654
- };
655
- const wrappedBulkDelete = async (keys) => {
656
- if (keys.length === 0) return;
657
- const deletedLocalIds = [];
658
- await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
659
- const txTable = tables[tableName];
660
- const records = await txTable.bulkGet(keys);
661
- await rawBulkDelete(keys);
662
- for (const record of records) {
663
- if (record) {
664
- deletedLocalIds.push(record._localId);
665
- await state.addPendingChange({
666
- action: "remove" /* Remove */,
667
- tableName,
668
- localId: record._localId,
669
- id: record.id,
670
- changes: null,
671
- before: record
672
- });
673
- }
674
- }
675
- });
676
- if (deletedLocalIds.length > 0) {
677
- emitMutation({ type: "delete", tableName, keys: deletedLocalIds });
678
- }
679
- };
680
- const wrappedClear = async () => {
681
- const deletedLocalIds = [];
682
- await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
683
- const txTable = tables[tableName];
684
- const allRecords = await txTable.toArray();
685
- await rawClear();
686
- for (const record of allRecords) {
687
- if (record._localId) {
688
- deletedLocalIds.push(record._localId);
689
- await state.addPendingChange({
690
- action: "remove" /* Remove */,
691
- tableName,
692
- localId: record._localId,
693
- id: record.id,
694
- changes: null,
695
- before: record
696
- });
697
- }
698
- }
699
- });
700
- if (deletedLocalIds.length > 0) {
701
- emitMutation({ type: "delete", tableName, keys: deletedLocalIds });
702
- }
703
- };
704
- table.add = wrappedAdd;
705
- table.put = wrappedPut;
706
- table.update = wrappedUpdate;
707
- table.delete = wrappedDelete;
708
- table.bulkAdd = wrappedBulkAdd;
709
- table.bulkPut = wrappedBulkPut;
710
- table.bulkUpdate = wrappedBulkUpdate;
711
- table.bulkDelete = wrappedBulkDelete;
712
- table.clear = wrappedClear;
713
- enhancedTables.add(tableName);
714
- }
715
-
716
- // src/core/pullOperations.ts
717
- async function pullAll(ctx) {
718
- let firstSyncError;
719
- const changedTables = [];
720
- for (const [tableName, api] of Object.entries(ctx.syncApis)) {
721
- try {
722
- const lastPulled = ctx.state.getState().lastPulled[tableName];
723
- const since = lastPulled ? new Date(lastPulled) : /* @__PURE__ */ new Date(0);
724
- ctx.logger.debug(`[dync] pull:start tableName=${tableName} since=${since.toISOString()}`);
725
- const serverData = await api.list(since);
726
- const changed = await processPullData(tableName, serverData, since, ctx);
727
- if (changed) changedTables.push(tableName);
728
- } catch (err) {
729
- firstSyncError = firstSyncError ?? err;
730
- ctx.logger.error(`[dync] pull:error tableName=${tableName}`, err);
731
- }
732
- }
733
- return { error: firstSyncError, changedTables };
734
- }
735
- async function handleRemoteItemUpdate(table, tableName, localItem, remote, ctx) {
736
- const pendingChange = ctx.state.getState().pendingChanges.find((p) => p.tableName === tableName && p.localId === localItem._localId);
737
- const conflictStrategy = ctx.conflictResolutionStrategy;
738
- if (pendingChange) {
739
- ctx.logger.debug(`[dync] pull:conflict-strategy:${conflictStrategy} tableName=${tableName} id=${remote.id}`);
740
- switch (conflictStrategy) {
741
- case "local-wins":
742
- break;
743
- case "remote-wins": {
744
- const merged = { ...remote, _localId: localItem._localId };
745
- await table.raw.update(localItem._localId, merged);
746
- await ctx.state.removePendingChange(localItem._localId, tableName);
747
- break;
748
- }
749
- case "try-shallow-merge": {
750
- const changes = pendingChange.changes || {};
751
- const before = pendingChange.before || {};
752
- const fields = Object.entries(changes).filter(([k, localValue]) => k in before && k in remote && before[k] !== remote[k] && localValue !== remote[k]).map(([key, localValue]) => ({ key, localValue, remoteValue: remote[key] }));
753
- if (fields.length > 0) {
754
- ctx.logger.warn(`[dync] pull:${conflictStrategy}:conflicts-found`, JSON.stringify(fields, null, 4));
755
- await ctx.state.setState((syncState) => ({
756
- ...syncState,
757
- conflicts: {
758
- ...syncState.conflicts || {},
759
- [localItem._localId]: { tableName, fields }
760
- }
761
- }));
762
- } else {
763
- const localChangedKeys = Object.keys(changes);
764
- const preservedLocal = { _localId: localItem._localId };
765
- for (const k of localChangedKeys) {
766
- if (k in localItem) preservedLocal[k] = localItem[k];
767
- }
768
- const merged = { ...remote, ...preservedLocal };
769
- await table.raw.update(localItem._localId, merged);
770
- await ctx.state.setState((syncState) => {
771
- const ss = { ...syncState };
772
- delete ss.conflicts?.[localItem._localId];
773
- return ss;
774
- });
775
- }
776
- break;
777
- }
778
- }
779
- } else {
780
- const merged = { ...localItem, ...remote };
781
- await table.raw.update(localItem._localId, merged);
782
- ctx.logger.debug(`[dync] pull:merge-remote tableName=${tableName} id=${remote.id}`);
783
- }
784
- }
785
- async function pullAllBatch(ctx) {
786
- let firstSyncError;
787
- const changedTables = [];
788
- try {
789
- const sinceMap = {};
790
- for (const tableName of ctx.batchSync.syncTables) {
791
- const lastPulled = ctx.state.getState().lastPulled[tableName];
792
- sinceMap[tableName] = lastPulled ? new Date(lastPulled) : /* @__PURE__ */ new Date(0);
793
- }
794
- ctx.logger.debug(`[dync] pull:batch:start tables=${[...ctx.batchSync.syncTables].join(",")}`, sinceMap);
795
- const serverDataByTable = await ctx.batchSync.pull(sinceMap);
796
- for (const [tableName, serverData] of Object.entries(serverDataByTable)) {
797
- if (!ctx.batchSync.syncTables.includes(tableName)) {
798
- ctx.logger.warn(`[dync] pull:batch:unknown-table tableName=${tableName}`);
799
- continue;
800
- }
801
- try {
802
- const changed = await processPullData(tableName, serverData, sinceMap[tableName], ctx);
803
- if (changed) changedTables.push(tableName);
804
- } catch (err) {
805
- firstSyncError = firstSyncError ?? err;
806
- ctx.logger.error(`[dync] pull:batch:error tableName=${tableName}`, err);
807
- }
808
- }
809
- } catch (err) {
810
- firstSyncError = err;
811
- ctx.logger.error(`[dync] pull:batch:error`, err);
812
- }
813
- return { error: firstSyncError, changedTables };
814
- }
815
- async function processPullData(tableName, serverData, since, ctx) {
816
- if (!serverData?.length) return false;
817
- ctx.logger.debug(`[dync] pull:process tableName=${tableName} count=${serverData.length}`);
818
- let newest = since;
819
- let hasChanges = false;
820
- await ctx.withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
821
- const txTable = tables[tableName];
822
- const pendingRemovalById = new Set(
823
- ctx.state.getState().pendingChanges.filter((p) => p.tableName === tableName && p.action === "remove" /* Remove */).map((p) => p.id)
824
- );
825
- for (const remote of serverData) {
826
- const remoteUpdated = new Date(remote.updated_at);
827
- if (remoteUpdated > newest) newest = remoteUpdated;
828
- if (pendingRemovalById.has(remote.id)) {
829
- ctx.logger.debug(`[dync] pull:skip-pending-remove tableName=${tableName} id=${remote.id}`);
830
- continue;
831
- }
832
- const localItem = await txTable.where("id").equals(remote.id).first();
833
- if (remote.deleted) {
834
- if (localItem) {
835
- await txTable.raw.delete(localItem._localId);
836
- ctx.logger.debug(`[dync] pull:remove tableName=${tableName} id=${remote.id}`);
837
- hasChanges = true;
838
- }
839
- continue;
840
- }
841
- delete remote.deleted;
842
- if (localItem) {
843
- await handleRemoteItemUpdate(txTable, tableName, localItem, remote, ctx);
844
- hasChanges = true;
845
- } else {
846
- const newLocalItem = { ...remote, _localId: createLocalId() };
847
- await txTable.raw.add(newLocalItem);
848
- ctx.logger.debug(`[dync] pull:add tableName=${tableName} id=${remote.id}`);
849
- hasChanges = true;
850
- }
851
- }
852
- await ctx.state.setState((syncState) => ({
853
- ...syncState,
854
- lastPulled: {
855
- ...syncState.lastPulled,
856
- [tableName]: newest.toISOString()
857
- }
858
- }));
859
- });
860
- return hasChanges;
861
- }
862
-
863
- // src/core/pushOperations.ts
864
- async function handleRemoveSuccess(change, ctx) {
865
- const { tableName, localId, id } = change;
866
- ctx.logger.debug(`[dync] push:remove:success tableName=${tableName} localId=${localId} id=${id}`);
867
- await ctx.state.removePendingChange(localId, tableName);
868
- }
869
- async function handleUpdateSuccess(change, ctx) {
870
- const { tableName, localId, version, changes } = change;
871
- ctx.logger.debug(`[dync] push:update:success tableName=${tableName} localId=${localId} id=${change.id}`);
872
- if (ctx.state.samePendingVersion(tableName, localId, version)) {
873
- await ctx.state.removePendingChange(localId, tableName);
874
- } else {
875
- await ctx.state.setPendingChangeBefore(tableName, localId, changes);
876
- }
877
- }
878
- async function handleCreateSuccess(change, serverResult, ctx) {
879
- const { tableName, localId, version, changes, id } = change;
880
- ctx.logger.debug(`[dync] push:create:success tableName=${tableName} localId=${localId} id=${id ?? serverResult.id}`);
881
- await ctx.withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
882
- const txTable = tables[tableName];
883
- const wasChanged = await txTable.raw.update(localId, serverResult) ?? 0;
884
- if (wasChanged && ctx.state.samePendingVersion(tableName, localId, version)) {
885
- await ctx.state.removePendingChange(localId, tableName);
886
- } else {
887
- const nextAction = wasChanged ? "update" /* Update */ : "remove" /* Remove */;
888
- await ctx.state.updatePendingChange(tableName, localId, nextAction, serverResult.id);
889
- if (nextAction === "remove" /* Remove */) return;
890
- }
891
- });
892
- const finalItem = { ...changes, ...serverResult, _localId: localId };
893
- ctx.syncOptions.onAfterRemoteAdd?.(tableName, finalItem);
894
- }
895
- async function pushAll(ctx) {
896
- let firstSyncError;
897
- const changesSnapshot = [...ctx.state.getState().pendingChanges].sort((a, b) => orderFor(a.action) - orderFor(b.action));
898
- for (const change of changesSnapshot) {
899
- try {
900
- await pushOne(change, ctx);
901
- } catch (err) {
902
- firstSyncError = firstSyncError ?? err;
903
- ctx.logger.error(`[dync] push:error change=${JSON.stringify(change)}`, err);
904
- }
905
- }
906
- return firstSyncError;
907
- }
908
- async function pushOne(change, ctx) {
909
- const api = ctx.syncApis[change.tableName];
910
- if (!api) return;
911
- ctx.logger.debug(`[dync] push:attempt action=${change.action} tableName=${change.tableName} localId=${change.localId}`);
912
- const { action, tableName, localId, id, changes, after } = change;
913
- switch (action) {
914
- case "remove" /* Remove */:
915
- if (!id) {
916
- ctx.logger.warn(`[dync] push:remove:no-id tableName=${tableName} localId=${localId}`);
917
- await ctx.state.removePendingChange(localId, tableName);
918
- return;
919
- }
920
- await api.remove(id);
921
- await handleRemoveSuccess(change, ctx);
922
- break;
923
- case "update" /* Update */: {
924
- if (ctx.state.hasConflicts(localId)) {
925
- ctx.logger.warn(`[dync] push:update:skipping-with-conflicts tableName=${tableName} localId=${localId} id=${id}`);
926
- return;
927
- }
928
- const exists = await api.update(id, changes, after);
929
- if (exists) {
930
- await handleUpdateSuccess(change, ctx);
931
- } else {
932
- await handleMissingRemoteRecord(change, ctx);
933
- }
934
- break;
935
- }
936
- case "create" /* Create */: {
937
- const result = await api.add(changes);
938
- if (result) {
939
- await handleCreateSuccess(change, result, ctx);
940
- } else {
941
- ctx.logger.warn(`[dync] push:create:no-result tableName=${tableName} localId=${localId} id=${id}`);
942
- if (ctx.state.samePendingVersion(tableName, localId, change.version)) {
943
- await ctx.state.removePendingChange(localId, tableName);
944
- }
945
- }
946
- break;
947
- }
948
- }
949
- }
950
- async function handleMissingRemoteRecord(change, ctx) {
951
- const { tableName, localId } = change;
952
- const strategy = ctx.syncOptions.missingRemoteRecordDuringUpdateStrategy;
953
- let localItem;
954
- await ctx.withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
955
- const txTable = tables[tableName];
956
- localItem = await txTable.get(localId);
957
- if (!localItem) {
958
- ctx.logger.warn(`[dync] push:missing-remote:no-local-item tableName=${tableName} localId=${localId}`);
959
- await ctx.state.removePendingChange(localId, tableName);
960
- return;
961
- }
962
- switch (strategy) {
963
- case "delete-local-record":
964
- await txTable.raw.delete(localId);
965
- ctx.logger.debug(`[dync] push:missing-remote:${strategy} tableName=${tableName} id=${localItem.id}`);
966
- break;
967
- case "insert-remote-record": {
968
- const newItem = {
969
- ...localItem,
970
- _localId: createLocalId(),
971
- updated_at: (/* @__PURE__ */ new Date()).toISOString()
972
- };
973
- await txTable.raw.add(newItem);
974
- await txTable.raw.delete(localId);
975
- await ctx.state.addPendingChange({
976
- action: "create" /* Create */,
977
- tableName,
978
- localId: newItem._localId,
979
- changes: newItem,
980
- before: null
981
- });
982
- ctx.logger.debug(`[dync] push:missing-remote:${strategy} tableName=${tableName} id=${newItem.id}`);
983
- break;
984
- }
985
- case "ignore":
986
- ctx.logger.debug(`[dync] push:missing-remote:${strategy} tableName=${tableName} id=${localItem.id}`);
987
- break;
988
- default:
989
- ctx.logger.error(`[dync] push:missing-remote:unknown-strategy tableName=${tableName} id=${localItem.id} strategy=${strategy}`);
990
- break;
991
- }
992
- await ctx.state.removePendingChange(localId, tableName);
993
- });
994
- ctx.syncOptions.onAfterMissingRemoteRecordDuringUpdate?.(strategy, localItem);
995
- }
996
- async function pushAllBatch(ctx) {
997
- let firstSyncError;
998
- try {
999
- const changesSnapshot = [...ctx.state.getState().pendingChanges].filter((change) => ctx.batchSync.syncTables.includes(change.tableName)).sort((a, b) => orderFor(a.action) - orderFor(b.action));
1000
- if (changesSnapshot.length === 0) {
1001
- ctx.logger.debug("[dync] push:batch:no-changes");
1002
- return void 0;
1003
- }
1004
- const changesToPush = changesSnapshot.filter((change) => {
1005
- if (change.action === "update" /* Update */ && ctx.state.hasConflicts(change.localId)) {
1006
- ctx.logger.warn(`[dync] push:batch:skipping-with-conflicts tableName=${change.tableName} localId=${change.localId}`);
1007
- return false;
1008
- }
1009
- return true;
1010
- });
1011
- if (changesToPush.length === 0) {
1012
- ctx.logger.debug("[dync] push:batch:all-skipped");
1013
- return void 0;
1014
- }
1015
- const payloads = changesToPush.map((change) => ({
1016
- table: change.tableName,
1017
- action: change.action === "create" /* Create */ ? "add" : change.action === "update" /* Update */ ? "update" : "remove",
1018
- localId: change.localId,
1019
- id: change.id,
1020
- data: change.action === "remove" /* Remove */ ? void 0 : change.changes
1021
- }));
1022
- ctx.logger.debug(`[dync] push:batch:start count=${payloads.length}`);
1023
- const results = await ctx.batchSync.push(payloads);
1024
- const resultMap = /* @__PURE__ */ new Map();
1025
- for (const result of results) {
1026
- resultMap.set(result.localId, result);
1027
- }
1028
- for (const change of changesToPush) {
1029
- const result = resultMap.get(change.localId);
1030
- if (!result) {
1031
- ctx.logger.warn(`[dync] push:batch:missing-result localId=${change.localId}`);
1032
- continue;
1033
- }
1034
- try {
1035
- await processBatchPushResult(change, result, ctx);
1036
- } catch (err) {
1037
- firstSyncError = firstSyncError ?? err;
1038
- ctx.logger.error(`[dync] push:batch:error localId=${change.localId}`, err);
1039
- }
1040
- }
1041
- } catch (err) {
1042
- firstSyncError = err;
1043
- ctx.logger.error("[dync] push:batch:error", err);
1044
- }
1045
- return firstSyncError;
1046
- }
1047
- async function processBatchPushResult(change, result, ctx) {
1048
- const { action, tableName, localId } = change;
1049
- if (!result.success) {
1050
- if (action === "update" /* Update */) {
1051
- await handleMissingRemoteRecord(change, ctx);
1052
- } else {
1053
- ctx.logger.warn(`[dync] push:batch:failed tableName=${tableName} localId=${localId} error=${result.error}`);
1054
- }
1055
- return;
1056
- }
1057
- switch (action) {
1058
- case "remove" /* Remove */:
1059
- handleRemoveSuccess(change, ctx);
1060
- break;
1061
- case "update" /* Update */:
1062
- handleUpdateSuccess(change, ctx);
1063
- break;
1064
- case "create" /* Create */: {
1065
- const serverResult = { id: result.id };
1066
- if (result.updated_at) {
1067
- serverResult.updated_at = result.updated_at;
1068
- }
1069
- await handleCreateSuccess(change, serverResult, ctx);
1070
- break;
1071
- }
1072
- }
1073
- }
1074
-
1075
- // src/core/firstLoad.ts
1076
- var yieldToEventLoop = () => sleep(0);
1077
- var WRITE_BATCH_SIZE = 200;
1078
- async function startFirstLoad(ctx) {
1079
- ctx.logger.debug("[dync] Starting first load...");
1080
- if (ctx.state.getState().firstLoadDone) {
1081
- ctx.logger.debug("[dync] First load already completed");
1082
- return;
1083
- }
1084
- let error;
1085
- for (const [tableName, api] of Object.entries(ctx.syncApis)) {
1086
- if (!api.firstLoad) {
1087
- ctx.logger.error(`[dync] firstLoad:no-api-function tableName=${tableName}`);
1088
- continue;
1089
- }
1090
- try {
1091
- ctx.logger.info(`[dync] firstLoad:start tableName=${tableName}`);
1092
- let lastId;
1093
- let isEmptyTable = true;
1094
- let batchCount = 0;
1095
- let totalInserted = 0;
1096
- let totalUpdated = 0;
1097
- while (true) {
1098
- const batch = await api.firstLoad(lastId);
1099
- if (!batch?.length) break;
1100
- batchCount++;
1101
- const { inserted, updated } = await processBatchInChunks(ctx, tableName, batch, isEmptyTable, lastId === void 0);
1102
- totalInserted += inserted;
1103
- totalUpdated += updated;
1104
- if (ctx.onProgress) {
1105
- ctx.onProgress({
1106
- table: tableName,
1107
- inserted: totalInserted,
1108
- updated: totalUpdated,
1109
- total: totalInserted + totalUpdated
1110
- });
1111
- }
1112
- if (lastId === void 0) {
1113
- isEmptyTable = await ctx.table(tableName).count() === batch.length;
1114
- }
1115
- if (lastId !== void 0 && lastId === batch[batch.length - 1].id) {
1116
- throw new Error(`Duplicate records downloaded, stopping to prevent infinite loop`);
1117
- }
1118
- lastId = batch[batch.length - 1].id;
1119
- if (batchCount % 5 === 0) {
1120
- await yieldToEventLoop();
1121
- }
1122
- }
1123
- ctx.logger.info(`[dync] firstLoad:done tableName=${tableName} inserted=${totalInserted} updated=${totalUpdated}`);
1124
- } catch (err) {
1125
- error = error ?? err;
1126
- ctx.logger.error(`[dync] firstLoad:error tableName=${tableName}`, err);
1127
- }
1128
- }
1129
- await ctx.state.setState((syncState) => ({
1130
- ...syncState,
1131
- firstLoadDone: true,
1132
- error
1133
- }));
1134
- ctx.logger.debug("[dync] First load completed");
1135
- }
1136
- async function processBatchInChunks(ctx, tableName, batch, isEmptyTable, isFirstBatch) {
1137
- let newest = new Date(ctx.state.getState().lastPulled[tableName] || 0);
1138
- return ctx.withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
1139
- const txTable = tables[tableName];
1140
- let tableIsEmpty = isEmptyTable;
1141
- if (isFirstBatch) {
1142
- const count = await txTable.count();
1143
- tableIsEmpty = count === 0;
1144
- }
1145
- const activeRecords = [];
1146
- for (const remote of batch) {
1147
- const remoteUpdated = new Date(remote.updated_at || 0);
1148
- if (remoteUpdated > newest) newest = remoteUpdated;
1149
- if (remote.deleted) continue;
1150
- delete remote.deleted;
1151
- remote._localId = createLocalId();
1152
- activeRecords.push(remote);
1153
- }
1154
- let inserted = 0;
1155
- let updated = 0;
1156
- if (tableIsEmpty) {
1157
- for (let i = 0; i < activeRecords.length; i += WRITE_BATCH_SIZE) {
1158
- const chunk = activeRecords.slice(i, i + WRITE_BATCH_SIZE);
1159
- await txTable.raw.bulkAdd(chunk);
1160
- inserted += chunk.length;
1161
- }
1162
- } else {
1163
- for (let i = 0; i < activeRecords.length; i += WRITE_BATCH_SIZE) {
1164
- const chunk = activeRecords.slice(i, i + WRITE_BATCH_SIZE);
1165
- const chunkResult = await processChunkWithLookup(txTable, chunk);
1166
- inserted += chunkResult.inserted;
1167
- updated += chunkResult.updated;
1168
- }
1169
- }
1170
- await ctx.state.setState((syncState) => ({
1171
- ...syncState,
1172
- lastPulled: {
1173
- ...syncState.lastPulled,
1174
- [tableName]: newest.toISOString()
1175
- }
1176
- }));
1177
- return { inserted, updated };
1178
- });
1179
- }
1180
- async function processChunkWithLookup(txTable, chunk) {
1181
- const serverIds = chunk.filter((r) => r.id != null).map((r) => r.id);
1182
- const existingByServerId = /* @__PURE__ */ new Map();
1183
- if (serverIds.length > 0) {
1184
- const existingRecords = await txTable.where("id").anyOf(serverIds).toArray();
1185
- for (const existing of existingRecords) {
1186
- existingByServerId.set(existing.id, existing);
1187
- }
1188
- }
1189
- const toAdd = [];
1190
- let updated = 0;
1191
- for (const remote of chunk) {
1192
- const existing = remote.id != null ? existingByServerId.get(remote.id) : void 0;
1193
- if (existing) {
1194
- const merged = Object.assign({}, existing, remote, { _localId: existing._localId });
1195
- await txTable.raw.update(existing._localId, merged);
1196
- updated++;
1197
- } else {
1198
- toAdd.push(remote);
1199
- }
1200
- }
1201
- if (toAdd.length > 0) {
1202
- await txTable.raw.bulkAdd(toAdd);
1203
- }
1204
- existingByServerId.clear();
1205
- return { inserted: toAdd.length, updated };
1206
- }
1207
- async function startFirstLoadBatch(ctx) {
1208
- ctx.logger.debug("[dync] Starting batch first load...");
1209
- if (ctx.state.getState().firstLoadDone) {
1210
- ctx.logger.debug("[dync] First load already completed");
1211
- return;
1212
- }
1213
- if (!ctx.batchSync.firstLoad) {
1214
- ctx.logger.warn("[dync] firstLoad:batch:no-firstLoad-function");
1215
- await ctx.state.setState((syncState) => ({
1216
- ...syncState,
1217
- firstLoadDone: true
1218
- }));
1219
- return;
1220
- }
1221
- let error;
1222
- try {
1223
- ctx.logger.info(`[dync] firstLoad:batch:start tables=${[...ctx.batchSync.syncTables].join(",")}`);
1224
- const progress = {};
1225
- for (const tableName of ctx.batchSync.syncTables) {
1226
- progress[tableName] = { inserted: 0, updated: 0 };
1227
- }
1228
- let cursors = {};
1229
- for (const tableName of ctx.batchSync.syncTables) {
1230
- cursors[tableName] = void 0;
1231
- }
1232
- let batchCount = 0;
1233
- while (true) {
1234
- const result = await ctx.batchSync.firstLoad(cursors);
1235
- if (!result.hasMore && Object.values(result.data).every((d) => !d?.length)) {
1236
- break;
1237
- }
1238
- batchCount++;
1239
- for (const [tableName, batch] of Object.entries(result.data)) {
1240
- if (!ctx.batchSync.syncTables.includes(tableName)) {
1241
- ctx.logger.warn(`[dync] firstLoad:batch:unknown-table tableName=${tableName}`);
1242
- continue;
1243
- }
1244
- if (!batch?.length) continue;
1245
- const isFirstBatch = progress[tableName].inserted === 0 && progress[tableName].updated === 0;
1246
- const isEmptyTable = isFirstBatch && await ctx.table(tableName).count() === 0;
1247
- const { inserted, updated } = await processBatchInChunks(ctx, tableName, batch, isEmptyTable, isFirstBatch);
1248
- progress[tableName].inserted += inserted;
1249
- progress[tableName].updated += updated;
1250
- if (ctx.onProgress) {
1251
- ctx.onProgress({
1252
- table: tableName,
1253
- inserted: progress[tableName].inserted,
1254
- updated: progress[tableName].updated,
1255
- total: progress[tableName].inserted + progress[tableName].updated
1256
- });
1257
- }
1258
- }
1259
- cursors = result.cursors;
1260
- if (batchCount % 5 === 0) {
1261
- await yieldToEventLoop();
1262
- }
1263
- if (!result.hasMore) {
1264
- break;
1265
- }
1266
- }
1267
- for (const [tableName, p] of Object.entries(progress)) {
1268
- ctx.logger.info(`[dync] firstLoad:batch:done tableName=${tableName} inserted=${p.inserted} updated=${p.updated}`);
1269
- }
1270
- } catch (err) {
1271
- error = err;
1272
- ctx.logger.error("[dync] firstLoad:batch:error", err);
1273
- }
1274
- await ctx.state.setState((syncState) => ({
1275
- ...syncState,
1276
- firstLoadDone: true,
1277
- error
1278
- }));
1279
- ctx.logger.debug("[dync] Batch first load completed");
30
+ function useSyncState(db) {
31
+ const cacheRef = (0, import_react.useRef)(db.sync.state);
32
+ const subscribe = (0, import_react.useCallback)(
33
+ (listener) => db.sync.onStateChange((nextState) => {
34
+ cacheRef.current = nextState;
35
+ listener();
36
+ }),
37
+ [db]
38
+ );
39
+ const getSnapshot = (0, import_react.useCallback)(() => {
40
+ const fresh = db.sync.state;
41
+ if (JSON.stringify(fresh) !== JSON.stringify(cacheRef.current)) {
42
+ cacheRef.current = fresh;
43
+ }
44
+ return cacheRef.current;
45
+ }, [db]);
46
+ return (0, import_react.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
1280
47
  }
1281
48
 
1282
- // src/index.shared.ts
1283
- var DEFAULT_SYNC_INTERVAL_MILLIS = 2e3;
1284
- var DEFAULT_LOGGER = console;
1285
- var DEFAULT_MIN_LOG_LEVEL = "debug";
1286
- var DEFAULT_MISSING_REMOTE_RECORD_STRATEGY = "insert-remote-record";
1287
- var DEFAULT_CONFLICT_RESOLUTION_STRATEGY = "try-shallow-merge";
1288
- var DyncBase = class {
1289
- adapter;
1290
- tableCache = /* @__PURE__ */ new Map();
1291
- mutationWrappedTables = /* @__PURE__ */ new Set();
1292
- syncEnhancedTables = /* @__PURE__ */ new Set();
1293
- mutationListeners = /* @__PURE__ */ new Set();
1294
- visibilitySubscription;
1295
- openPromise;
1296
- disableSyncPromise;
1297
- disableSyncPromiseResolver;
1298
- sleepAbortController;
1299
- closing = false;
1300
- // Per-table sync mode
1301
- syncApis = {};
1302
- // Batch sync mode
1303
- batchSync;
1304
- syncedTables = /* @__PURE__ */ new Set();
1305
- syncOptions;
1306
- logger;
1307
- syncTimerStarted = false;
1308
- mutationsDuringSync = false;
1309
- state;
1310
- name;
1311
- constructor(databaseName, syncApisOrBatchSync, storageAdapter, options) {
1312
- const isBatchMode = typeof syncApisOrBatchSync.push === "function";
1313
- if (isBatchMode) {
1314
- this.batchSync = syncApisOrBatchSync;
1315
- this.syncedTables = new Set(this.batchSync.syncTables);
1316
- } else {
1317
- this.syncApis = syncApisOrBatchSync;
1318
- this.syncedTables = new Set(Object.keys(this.syncApis));
1319
- }
1320
- this.adapter = storageAdapter;
1321
- this.name = databaseName;
1322
- this.syncOptions = {
1323
- syncInterval: DEFAULT_SYNC_INTERVAL_MILLIS,
1324
- logger: DEFAULT_LOGGER,
1325
- minLogLevel: DEFAULT_MIN_LOG_LEVEL,
1326
- missingRemoteRecordDuringUpdateStrategy: DEFAULT_MISSING_REMOTE_RECORD_STRATEGY,
1327
- conflictResolutionStrategy: DEFAULT_CONFLICT_RESOLUTION_STRATEGY,
1328
- ...options ?? {}
1329
- };
1330
- this.logger = newLogger(this.syncOptions.logger, this.syncOptions.minLogLevel);
1331
- this.state = new StateManager({
1332
- storageAdapter: this.adapter
1333
- });
1334
- const driverInfo = "driverType" in this.adapter ? ` (Driver: ${this.adapter.driverType})` : "";
1335
- this.logger.debug(`[dync] Initialized with ${this.adapter.type}${driverInfo}`);
1336
- }
1337
- version(versionNumber) {
1338
- const self = this;
1339
- const schemaOptions = {};
1340
- let storesDefined = false;
1341
- const builder = {
1342
- stores(schema) {
1343
- const usesStructuredSchema = Object.values(schema).some((def) => typeof def !== "string");
1344
- const stateTableSchema = usesStructuredSchema ? {
1345
- columns: {
1346
- [LOCAL_PK]: { type: "TEXT" },
1347
- value: { type: "TEXT" }
1348
- }
1349
- } : LOCAL_PK;
1350
- const fullSchema = {
1351
- ...schema,
1352
- [DYNC_STATE_TABLE]: stateTableSchema
1353
- };
1354
- for (const [tableName, tableSchema] of Object.entries(schema)) {
1355
- const isSyncTable = self.syncedTables.has(tableName);
1356
- if (typeof tableSchema === "string") {
1357
- if (isSyncTable) {
1358
- fullSchema[tableName] = `${LOCAL_PK}, &${SERVER_PK}, ${tableSchema}, ${UPDATED_AT}`;
1359
- }
1360
- self.logger.debug(
1361
- `[dync] Defining ${isSyncTable ? "" : "non-"}sync table '${tableName}' with primary key & indexes '${fullSchema[tableName]}'`
1362
- );
1363
- } else {
1364
- if (isSyncTable) {
1365
- fullSchema[tableName] = self.injectSyncColumns(tableSchema);
1366
- }
1367
- const schemaColumns = Object.keys(fullSchema[tableName].columns ?? {}).join(", ");
1368
- const schemaIndexes = (fullSchema[tableName].indexes ?? []).map((idx) => idx.columns.join("+")).join(", ");
1369
- self.logger.debug(
1370
- `[dync] Defining ${isSyncTable ? "" : "non-"}sync table '${tableName}' with columns ${schemaColumns} and indexes ${schemaIndexes}`
1371
- );
1372
- }
1373
- }
1374
- storesDefined = true;
1375
- self.adapter.defineSchema(versionNumber, fullSchema, schemaOptions);
1376
- self.setupEnhancedTables(Object.keys(schema));
1377
- return builder;
1378
- },
1379
- sqlite(configure) {
1380
- if (!storesDefined) {
1381
- throw new Error("Call stores() before registering sqlite migrations");
1382
- }
1383
- const sqliteOptions = schemaOptions.sqlite ??= {};
1384
- const migrations = sqliteOptions.migrations ??= {};
1385
- const configurator = {
1386
- upgrade(handler) {
1387
- migrations.upgrade = handler;
1388
- },
1389
- downgrade(handler) {
1390
- migrations.downgrade = handler;
1391
- }
1392
- };
1393
- configure(configurator);
1394
- return builder;
1395
- }
1396
- };
1397
- return builder;
1398
- }
1399
- async open() {
1400
- if (this.closing) {
1401
- return;
1402
- }
1403
- if (this.openPromise) {
1404
- return this.openPromise;
1405
- }
1406
- this.openPromise = (async () => {
1407
- if (this.closing) return;
1408
- await this.adapter.open();
1409
- if (this.closing) return;
1410
- await this.state.hydrate();
1411
- })();
1412
- return this.openPromise;
1413
- }
1414
- async close() {
1415
- this.closing = true;
1416
- if (this.openPromise) {
1417
- await this.openPromise.catch(() => {
1418
- });
1419
- this.openPromise = void 0;
1420
- }
1421
- await this.enableSync(false);
1422
- await this.adapter.close();
1423
- this.tableCache.clear();
1424
- this.mutationWrappedTables.clear();
1425
- this.syncEnhancedTables.clear();
1426
- }
1427
- async delete() {
1428
- await this.adapter.delete();
1429
- this.tableCache.clear();
1430
- this.mutationWrappedTables.clear();
1431
- this.syncEnhancedTables.clear();
1432
- }
1433
- async query(callback) {
1434
- return this.adapter.query(callback);
1435
- }
1436
- table(name) {
1437
- if (this.tableCache.has(name)) {
1438
- return this.tableCache.get(name);
1439
- }
1440
- const table = this.adapter.table(name);
1441
- const isSyncTable = this.syncedTables.has(name);
1442
- if (isSyncTable && !this.syncEnhancedTables.has(name)) {
1443
- this.enhanceSyncTable(table, name);
1444
- } else if (!isSyncTable && !this.mutationWrappedTables.has(name) && name !== DYNC_STATE_TABLE) {
1445
- wrapWithMutationEmitter(table, name, this.emitMutation.bind(this));
1446
- this.mutationWrappedTables.add(name);
1447
- }
1448
- this.tableCache.set(name, table);
1449
- return table;
1450
- }
1451
- async withTransaction(mode, tableNames, fn) {
1452
- await this.open();
1453
- return this.adapter.transaction(mode, tableNames, async () => {
1454
- const tables = {};
1455
- for (const tableName of tableNames) {
1456
- tables[tableName] = this.table(tableName);
1457
- }
1458
- return fn(tables);
1459
- });
1460
- }
1461
- setupEnhancedTables(tableNames) {
1462
- setupEnhancedTables(
1463
- {
1464
- owner: this,
1465
- tableCache: this.tableCache,
1466
- enhancedTables: this.syncEnhancedTables,
1467
- getTable: (name) => this.table(name)
1468
- },
1469
- tableNames
1470
- );
1471
- for (const tableName of tableNames) {
1472
- this.mutationWrappedTables.delete(tableName);
1473
- }
1474
- }
1475
- injectSyncColumns(schema) {
1476
- const columns = schema.columns ?? {};
1477
- if (columns[LOCAL_PK]) {
1478
- throw new Error(`Column '${LOCAL_PK}' is auto-injected for sync tables and cannot be defined manually.`);
1479
- }
1480
- if (columns[SERVER_PK]) {
1481
- throw new Error(`Column '${SERVER_PK}' is auto-injected for sync tables and cannot be defined manually.`);
1482
- }
1483
- if (columns[UPDATED_AT]) {
1484
- throw new Error(`Column '${UPDATED_AT}' is auto-injected for sync tables and cannot be defined manually.`);
1485
- }
1486
- const injectedColumns = {
1487
- ...columns,
1488
- [LOCAL_PK]: { type: "TEXT" },
1489
- [SERVER_PK]: { type: "INTEGER", unique: true },
1490
- [UPDATED_AT]: { type: "TEXT" }
1491
- };
1492
- const userIndexes = schema.indexes ?? [];
1493
- const hasUpdatedAtIndex = userIndexes.some((idx) => idx.columns.length === 1 && idx.columns[0] === UPDATED_AT);
1494
- const injectedIndexes = hasUpdatedAtIndex ? userIndexes : [...userIndexes, { columns: [UPDATED_AT] }];
1495
- return {
1496
- ...schema,
1497
- columns: injectedColumns,
1498
- indexes: injectedIndexes
1499
- };
1500
- }
1501
- enhanceSyncTable(table, tableName) {
1502
- enhanceSyncTable({
1503
- table,
1504
- tableName,
1505
- withTransaction: this.withTransaction.bind(this),
1506
- state: this.state,
1507
- enhancedTables: this.syncEnhancedTables,
1508
- emitMutation: this.emitMutation.bind(this)
1509
- });
1510
- }
1511
- async syncOnce() {
1512
- if (this.closing) {
1513
- return;
1514
- }
1515
- if (this.syncStatus === "syncing") {
1516
- this.mutationsDuringSync = true;
1517
- return;
1518
- }
1519
- this.syncStatus = "syncing";
1520
- this.mutationsDuringSync = false;
1521
- const pullResult = await this.pullAll();
1522
- const firstPushSyncError = await this.pushAll();
1523
- for (const tableName of pullResult.changedTables) {
1524
- this.emitMutation({ type: "pull", tableName });
1525
- }
1526
- this.syncStatus = "idle";
1527
- this.state.setApiError(pullResult.error ?? firstPushSyncError);
1528
- if (this.mutationsDuringSync) {
1529
- this.mutationsDuringSync = false;
1530
- this.syncOnce().catch(() => {
1531
- });
1532
- }
1533
- }
1534
- async pullAll() {
1535
- const baseContext = {
1536
- logger: this.logger,
1537
- state: this.state,
1538
- table: this.table.bind(this),
1539
- withTransaction: this.withTransaction.bind(this),
1540
- conflictResolutionStrategy: this.syncOptions.conflictResolutionStrategy
1541
- };
1542
- if (this.batchSync) {
1543
- return pullAllBatch({
1544
- ...baseContext,
1545
- batchSync: this.batchSync
1546
- });
1547
- }
1548
- return pullAll({
1549
- ...baseContext,
1550
- syncApis: this.syncApis
1551
- });
1552
- }
1553
- async pushAll() {
1554
- const baseContext = {
1555
- logger: this.logger,
1556
- state: this.state,
1557
- table: this.table.bind(this),
1558
- withTransaction: this.withTransaction.bind(this),
1559
- syncOptions: this.syncOptions
1560
- };
1561
- if (this.batchSync) {
1562
- return pushAllBatch({
1563
- ...baseContext,
1564
- batchSync: this.batchSync
1565
- });
1566
- }
1567
- return pushAll({
1568
- ...baseContext,
1569
- syncApis: this.syncApis
1570
- });
1571
- }
1572
- startSyncTimer(start) {
1573
- if (start) {
1574
- void this.tryStart();
1575
- } else {
1576
- this.syncTimerStarted = false;
1577
- }
1578
- }
1579
- async tryStart() {
1580
- if (this.syncTimerStarted) return;
1581
- this.syncTimerStarted = true;
1582
- while (this.syncTimerStarted) {
1583
- this.sleepAbortController = new AbortController();
1584
- await this.syncOnce();
1585
- await sleep(this.syncOptions.syncInterval, this.sleepAbortController.signal);
1586
- }
1587
- this.syncStatus = "disabled";
1588
- this.disableSyncPromiseResolver?.();
1589
- }
1590
- setupVisibilityListener(add) {
1591
- this.visibilitySubscription = addVisibilityChangeListener(add, this.visibilitySubscription, (isVisible) => this.handleVisibilityChange(isVisible));
1592
- }
1593
- handleVisibilityChange(isVisible) {
1594
- if (isVisible) {
1595
- this.logger.debug("[dync] sync:start-in-foreground");
1596
- this.startSyncTimer(true);
1597
- } else {
1598
- this.logger.debug("[dync] sync:pause-in-background");
1599
- this.startSyncTimer(false);
1600
- }
1601
- }
1602
- async startFirstLoad(onProgress) {
1603
- await this.open();
1604
- const baseContext = {
1605
- logger: this.logger,
1606
- state: this.state,
1607
- table: this.table.bind(this),
1608
- withTransaction: this.withTransaction.bind(this),
1609
- onProgress
1610
- };
1611
- if (this.batchSync) {
1612
- await startFirstLoadBatch({
1613
- ...baseContext,
1614
- batchSync: this.batchSync
1615
- });
1616
- } else {
1617
- await startFirstLoad({
1618
- ...baseContext,
1619
- syncApis: this.syncApis
1620
- });
1621
- }
1622
- for (const tableName of this.syncedTables) {
1623
- this.emitMutation({ type: "pull", tableName });
1624
- }
1625
- }
1626
- getSyncState() {
1627
- return this.state.getSyncState();
1628
- }
1629
- async resolveConflict(localId, keepLocal) {
1630
- const conflict = this.state.getState().conflicts?.[localId];
1631
- if (!conflict) {
1632
- this.logger.warn(`[dync] No conflict found for localId: ${localId}`);
1633
- return;
1634
- }
1635
- await this.withTransaction("rw", [conflict.tableName, DYNC_STATE_TABLE], async (tables) => {
1636
- const txTable = tables[conflict.tableName];
1637
- if (!keepLocal) {
1638
- const item = await txTable.get(localId);
1639
- if (item) {
1640
- for (const field of conflict.fields) {
1641
- item[field.key] = field.remoteValue;
1642
- }
1643
- await txTable.raw.update(localId, item);
1644
- } else {
1645
- this.logger.warn(`[dync] No local item found for localId: ${localId} to apply remote values`);
1646
- }
1647
- await this.state.setState((syncState) => ({
1648
- ...syncState,
1649
- pendingChanges: syncState.pendingChanges.filter((p) => !(p.localId === localId && p.tableName === conflict.tableName))
1650
- }));
1651
- }
1652
- await this.state.setState((syncState) => {
1653
- const ss = { ...syncState };
1654
- delete ss.conflicts?.[localId];
1655
- return ss;
1656
- });
1657
- });
1658
- }
1659
- async enableSync(enabled) {
1660
- if (!enabled) {
1661
- if (this.syncTimerStarted) {
1662
- this.disableSyncPromise = new Promise((resolve) => {
1663
- this.disableSyncPromiseResolver = resolve;
1664
- });
1665
- this.sleepAbortController?.abort();
1666
- this.syncStatus = "disabling";
1667
- this.startSyncTimer(false);
1668
- this.setupVisibilityListener(false);
1669
- return this.disableSyncPromise;
1670
- }
1671
- this.syncStatus = "disabled";
1672
- this.setupVisibilityListener(false);
1673
- return Promise.resolve();
1674
- }
1675
- this.syncStatus = "idle";
1676
- this.startSyncTimer(true);
1677
- this.setupVisibilityListener(true);
1678
- return Promise.resolve();
1679
- }
1680
- get syncStatus() {
1681
- return this.state.getSyncStatus();
1682
- }
1683
- set syncStatus(status) {
1684
- this.state.setSyncStatus(status);
1685
- }
1686
- onSyncStateChange(fn) {
1687
- return this.state.subscribe(fn);
1688
- }
1689
- onMutation(fn) {
1690
- this.mutationListeners.add(fn);
1691
- return () => this.mutationListeners.delete(fn);
1692
- }
1693
- emitMutation(event) {
1694
- if (event.type === "add" || event.type === "update" || event.type === "delete") {
1695
- if (this.syncTimerStarted) {
1696
- this.syncOnce().catch(() => {
1697
- });
1698
- }
1699
- }
1700
- for (const listener of this.mutationListeners) {
1701
- listener(event);
1702
- }
1703
- }
1704
- // Public API
1705
- sync = {
1706
- enable: this.enableSync.bind(this),
1707
- startFirstLoad: this.startFirstLoad.bind(this),
1708
- getState: this.getSyncState.bind(this),
1709
- resolveConflict: this.resolveConflict.bind(this),
1710
- onStateChange: this.onSyncStateChange.bind(this),
1711
- onMutation: this.onMutation.bind(this)
1712
- };
1713
- };
1714
- var DyncConstructor = DyncBase;
1715
- var Dync = DyncConstructor;
1716
-
1717
- // src/react/useDync.ts
1718
- function makeDync(config) {
1719
- const db = "syncApis" in config ? new Dync(config.databaseName, config.syncApis, config.storageAdapter, config.options) : new Dync(config.databaseName, config.batchSync, config.storageAdapter, config.options);
1720
- let cachedState = db.sync.getState();
1721
- const subscribe = (listener) => db.sync.onStateChange((nextState) => {
1722
- cachedState = nextState;
1723
- listener();
1724
- });
1725
- const getSnapshot = () => {
1726
- const fresh = db.sync.getState();
1727
- if (JSON.stringify(fresh) !== JSON.stringify(cachedState)) {
1728
- cachedState = fresh;
1729
- }
1730
- return cachedState;
1731
- };
1732
- const useDync = () => {
1733
- const syncState = (0, import_react.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
1734
- return { db, syncState };
1735
- };
1736
- const boundUseLiveQuery = (querier, deps = [], tables) => {
1737
- return useLiveQueryImpl(db, querier, deps, tables);
1738
- };
1739
- return {
1740
- db,
1741
- useDync,
1742
- useLiveQuery: boundUseLiveQuery
1743
- };
1744
- }
1745
- function useLiveQueryImpl(db, querier, deps = [], tables) {
1746
- const [result, setResult] = (0, import_react.useState)(void 0);
1747
- const [, setError] = (0, import_react.useState)(null);
1748
- const isMountedRef = (0, import_react.useRef)(true);
1749
- const queryVersionRef = (0, import_react.useRef)(0);
1750
- const querierRef = (0, import_react.useRef)(querier);
1751
- const tablesRef = (0, import_react.useRef)(tables);
49
+ // src/react/useLiveQuery.ts
50
+ var import_react2 = require("react");
51
+ function useLiveQuery(db, querier, deps = [], tables) {
52
+ const [result, setResult] = (0, import_react2.useState)(void 0);
53
+ const [, setError] = (0, import_react2.useState)(null);
54
+ const isMountedRef = (0, import_react2.useRef)(true);
55
+ const queryVersionRef = (0, import_react2.useRef)(0);
56
+ const querierRef = (0, import_react2.useRef)(querier);
57
+ const tablesRef = (0, import_react2.useRef)(tables);
1752
58
  querierRef.current = querier;
1753
59
  tablesRef.current = tables;
1754
- const runQuery = (0, import_react.useCallback)(async () => {
60
+ const runQuery = (0, import_react2.useCallback)(async () => {
1755
61
  const currentVersion = ++queryVersionRef.current;
1756
62
  try {
1757
- const queryResult = await querierRef.current(db);
63
+ const queryResult = await querierRef.current();
1758
64
  if (isMountedRef.current && currentVersion === queryVersionRef.current) {
1759
65
  setResult(queryResult);
1760
66
  setError(null);
@@ -1764,11 +70,11 @@ function useLiveQueryImpl(db, querier, deps = [], tables) {
1764
70
  setError(err);
1765
71
  }
1766
72
  }
1767
- }, [db]);
1768
- (0, import_react.useEffect)(() => {
73
+ }, []);
74
+ (0, import_react2.useEffect)(() => {
1769
75
  runQuery();
1770
76
  }, [...deps, runQuery]);
1771
- (0, import_react.useEffect)(() => {
77
+ (0, import_react2.useEffect)(() => {
1772
78
  isMountedRef.current = true;
1773
79
  const unsubscribe = db.sync.onMutation((event) => {
1774
80
  if (!tablesRef.current || tablesRef.current.includes(event.tableName)) {
@@ -1784,6 +90,7 @@ function useLiveQueryImpl(db, querier, deps = [], tables) {
1784
90
  }
1785
91
  // Annotate the CommonJS export names for ESM import in node:
1786
92
  0 && (module.exports = {
1787
- makeDync
93
+ useLiveQuery,
94
+ useSyncState
1788
95
  });
1789
96
  //# sourceMappingURL=index.cjs.map