@koolbase/react-native 9.2.0 → 10.0.1

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 (69) hide show
  1. package/CHANGELOG.md +1348 -0
  2. package/README.md +403 -568
  3. package/dist/{auth-storage.d.ts → cjs/auth-storage.d.ts} +1 -1
  4. package/dist/cjs/index.d.ts +19 -0
  5. package/dist/cjs/index.js +125 -0
  6. package/dist/cjs/package.json +3 -0
  7. package/dist/cjs/platform.d.ts +2 -0
  8. package/dist/cjs/platform.js +43 -0
  9. package/dist/esm/auth-storage.d.ts +26 -0
  10. package/dist/esm/auth-storage.js +100 -0
  11. package/dist/esm/index.d.ts +19 -0
  12. package/dist/esm/index.js +106 -0
  13. package/dist/esm/package.json +3 -0
  14. package/dist/esm/platform.d.ts +2 -0
  15. package/dist/esm/platform.js +37 -0
  16. package/package.json +30 -30
  17. package/dist/analytics.d.ts +0 -24
  18. package/dist/analytics.js +0 -114
  19. package/dist/apple-auth.d.ts +0 -22
  20. package/dist/apple-auth.js +0 -74
  21. package/dist/auth-errors.d.ts +0 -117
  22. package/dist/auth-errors.js +0 -250
  23. package/dist/auth.d.ts +0 -213
  24. package/dist/auth.js +0 -810
  25. package/dist/cache-store.d.ts +0 -50
  26. package/dist/cache-store.js +0 -197
  27. package/dist/code-push.d.ts +0 -59
  28. package/dist/code-push.js +0 -255
  29. package/dist/conflict.d.ts +0 -80
  30. package/dist/conflict.js +0 -84
  31. package/dist/database-errors.d.ts +0 -101
  32. package/dist/database-errors.js +0 -200
  33. package/dist/database.d.ts +0 -298
  34. package/dist/database.js +0 -852
  35. package/dist/device-id.d.ts +0 -1
  36. package/dist/device-id.js +0 -60
  37. package/dist/device-metadata.d.ts +0 -36
  38. package/dist/device-metadata.js +0 -102
  39. package/dist/errors.d.ts +0 -64
  40. package/dist/errors.js +0 -85
  41. package/dist/flags.d.ts +0 -15
  42. package/dist/flags.js +0 -76
  43. package/dist/function-errors.d.ts +0 -51
  44. package/dist/function-errors.js +0 -103
  45. package/dist/functions.d.ts +0 -15
  46. package/dist/functions.js +0 -83
  47. package/dist/index.d.ts +0 -49
  48. package/dist/index.js +0 -204
  49. package/dist/logic-engine.d.ts +0 -17
  50. package/dist/logic-engine.js +0 -193
  51. package/dist/messaging.d.ts +0 -13
  52. package/dist/messaging.js +0 -36
  53. package/dist/offline-state.d.ts +0 -97
  54. package/dist/offline-state.js +0 -200
  55. package/dist/pending-write.d.ts +0 -47
  56. package/dist/pending-write.js +0 -22
  57. package/dist/realtime.d.ts +0 -44
  58. package/dist/realtime.js +0 -195
  59. package/dist/record.d.ts +0 -2
  60. package/dist/record.js +0 -23
  61. package/dist/storage-errors.d.ts +0 -163
  62. package/dist/storage-errors.js +0 -253
  63. package/dist/storage.d.ts +0 -198
  64. package/dist/storage.js +0 -451
  65. package/dist/sync-engine.d.ts +0 -30
  66. package/dist/sync-engine.js +0 -290
  67. package/dist/types.d.ts +0 -487
  68. package/dist/types.js +0 -40
  69. /package/dist/{auth-storage.js → cjs/auth-storage.js} +0 -0
@@ -1,290 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.SyncEngine = void 0;
7
- const offline_state_1 = require("./offline-state");
8
- const errors_1 = require("./errors");
9
- const netinfo_1 = __importDefault(require("@react-native-community/netinfo"));
10
- const cache_store_1 = require("./cache-store");
11
- /**
12
- * Internal signal that the server refused a write because the record moved.
13
- *
14
- * Not exported: a conflict during replay becomes durable state rather than
15
- * reaching a caller, since nobody is waiting on a write made hours ago.
16
- */
17
- /**
18
- * Whether the server's answer can change on a later attempt.
19
- *
20
- * Terminal means the same request would meet the same decision: the data does
21
- * not satisfy the collection's rules, the record is gone, the caller is not
22
- * permitted, a unique value is taken. Retrying spends attempts to learn what is
23
- * already known.
24
- *
25
- * 403 is terminal even though a role change could later permit it. A queue that
26
- * holds writes indefinitely against a maybe is how a retry loop becomes
27
- * invisible — surfacing it lets an app retry deliberately if roles change.
28
- */
29
- function isTerminal(status) {
30
- return status === 400 || status === 403 || status === 404 || status === 409;
31
- }
32
- /** Raised when the server refused for a reason retrying cannot change. */
33
- class TerminalRejection extends Error {
34
- constructor(message, status) {
35
- super(message);
36
- this.status = status;
37
- Object.setPrototypeOf(this, new.target.prototype);
38
- }
39
- }
40
- class RevisionMismatch extends Error {
41
- constructor(serverRecord, serverRevision) {
42
- super('revision mismatch');
43
- this.serverRecord = serverRecord;
44
- this.serverRevision = serverRevision;
45
- Object.setPrototypeOf(this, new.target.prototype);
46
- }
47
- }
48
- class SyncEngine {
49
- constructor(config, getUserId, getToken, onSyncComplete, onSessionExpired) {
50
- this.isSyncing = false;
51
- this.config = config;
52
- this.getUserId = getUserId;
53
- this.getToken = getToken;
54
- this.onSyncComplete = onSyncComplete;
55
- this.onSessionExpired = onSessionExpired;
56
- }
57
- start() {
58
- this.unsubscribe = netinfo_1.default.addEventListener(state => {
59
- if (state.isConnected && state.isInternetReachable !== false) {
60
- this.flush();
61
- }
62
- });
63
- }
64
- stop() {
65
- this.unsubscribe?.();
66
- }
67
- async flush() {
68
- if (this.isSyncing)
69
- return;
70
- const userId = this.getUserId();
71
- if (!userId)
72
- return;
73
- this.isSyncing = true;
74
- try {
75
- // Before anything is sent. Writes queued by an earlier version sit under a
76
- // different key, and a migration that ran after replay — or depended on
77
- // being online — would give the same input different outcomes. It clears
78
- // the old key when done, so later calls find nothing and return.
79
- await (0, offline_state_1.migrateLegacyQueue)(userId);
80
- const { pending } = await (0, offline_state_1.readOfflineState)(userId);
81
- if (pending.length === 0)
82
- return;
83
- // Records whose chain stopped this pass. Writes queued after a conflicted
84
- // one were composed against the state it would have produced, so applying
85
- // them now would write against a state their baseline never described.
86
- const blocked = new Set();
87
- for (const queued of pending) {
88
- if (queued.recordId && blocked.has(queued.recordId))
89
- continue;
90
- // Read fresh. The list was taken at the start of the pass, so a write
91
- // behind one that has already landed still carries the revision it was
92
- // queued with — and would replay against a revision its predecessor has
93
- // since superseded, conflicting for a reason the user never caused.
94
- const state = await (0, offline_state_1.readOfflineState)(userId);
95
- const write = state.pending.find((w) => w.id === queued.id);
96
- if (!write)
97
- continue;
98
- try {
99
- const revision = await this.executeWrite(write);
100
- // The replayed write just changed the server; the cache must stop
101
- // testifying to the old world. Mirrors the online paths — a replayed
102
- // delete evicts the record, and every replayed write invalidates the
103
- // collection's cached queries, so the next query reconverges instead
104
- // of serving a ghost.
105
- if (write.operation === 'delete' && write.recordId) {
106
- await (0, cache_store_1.removeCachedRecord)(userId, write.recordId);
107
- }
108
- await (0, cache_store_1.invalidateCache)(userId, write.collection);
109
- await (0, offline_state_1.mutateOfflineState)(userId, (s) => {
110
- s.pending = s.pending.filter((w) => w.id !== write.id);
111
- // Anything behind this for the same record was composed against its
112
- // result, and now knows the revision that result carries.
113
- if (revision !== undefined && write.recordId) {
114
- for (const w of s.pending) {
115
- if (w.recordId === write.recordId)
116
- w.baseRevision = revision;
117
- }
118
- }
119
- });
120
- }
121
- catch (e) {
122
- if (e instanceof errors_1.KoolbaseUnauthenticatedError) {
123
- // The session is gone, so nothing else in the queue can succeed.
124
- // Stopping beats spending a retry on every remaining write against
125
- // a token the server has already refused; the queue is intact and
126
- // replays after login.
127
- await this.onSessionExpired?.();
128
- return;
129
- }
130
- if (e instanceof RevisionMismatch) {
131
- // Not a failure to retry — retrying cannot help. It becomes durable
132
- // unresolved state, in one write so it can be in neither place nor
133
- // both.
134
- await (0, offline_state_1.mutateOfflineState)(userId, (s) => {
135
- s.pending = s.pending.filter((w) => w.id !== write.id);
136
- s.conflicts.push({
137
- id: write.id,
138
- // The record moved between the change being made and the queue
139
- // reaching it — distinct from a write that never had a baseline
140
- // to compare against at all.
141
- reason: 'concurrent_modification',
142
- operation: write.operation,
143
- collection: write.collection,
144
- recordId: write.recordId,
145
- local: write.data,
146
- baseline: write.baseline,
147
- server: e.serverRecord,
148
- baseRevision: write.baseRevision,
149
- serverRevision: e.serverRevision,
150
- createdAt: new Date().toISOString(),
151
- });
152
- });
153
- if (write.recordId)
154
- blocked.add(write.recordId);
155
- continue;
156
- }
157
- if (e instanceof TerminalRejection) {
158
- // The server made a decision that will not change on a later
159
- // attempt. Retrying spends attempts to learn what is already known;
160
- // dropping loses a change the user believes is saved. It waits,
161
- // with what the server said, so someone can act on it.
162
- await (0, offline_state_1.mutateOfflineState)(userId, (s) => {
163
- s.pending = s.pending.filter((w) => w.id !== write.id);
164
- s.conflicts.push({
165
- id: write.id,
166
- reason: 'rejected',
167
- operation: write.operation,
168
- collection: write.collection,
169
- recordId: write.recordId ?? '',
170
- local: write.data,
171
- baseline: write.baseline,
172
- baseRevision: write.baseRevision,
173
- message: e.message,
174
- createdAt: new Date().toISOString(),
175
- });
176
- });
177
- // A terminally rejected insert leaves an optimistic record behind
178
- // — cached at enqueue for a record the server refused to create.
179
- // Left alone it is a phantom: it renders as saved, and an offline
180
- // edit against it queues a write to a record that does not exist.
181
- // Evict it, and invalidate the collection so cached queries stop
182
- // serving it. The conflict above keeps the user's data and the
183
- // server's verdict; the cache stops testifying to a fiction.
184
- // MUTATION: phantom eviction removed
185
- if (write.recordId)
186
- blocked.add(write.recordId);
187
- continue;
188
- }
189
- // Retryable: the network, a 5xx, a rate limit. The count is kept so a
190
- // caller can see a write that keeps failing, but nothing drops it —
191
- // a write discarded after three attempts is discarded silently, and
192
- // the user is never told.
193
- await (0, offline_state_1.mutateOfflineState)(userId, (s) => {
194
- const w = s.pending.find((x) => x.id === write.id);
195
- if (w)
196
- w.retries += 1;
197
- });
198
- }
199
- }
200
- this.onSyncComplete?.();
201
- }
202
- finally {
203
- this.isSyncing = false;
204
- }
205
- }
206
- /**
207
- * Sends one queued write, returning the revision the record now carries.
208
- *
209
- * The revision matters to whatever is queued behind this for the same record:
210
- * those were composed against this one's result and cannot know its revision
211
- * until the server assigns it.
212
- */
213
- async executeWrite(write) {
214
- const token = await this.getToken();
215
- const headers = {
216
- 'Content-Type': 'application/json',
217
- 'x-api-key': this.config.publicKey,
218
- ...(token ? { Authorization: `Bearer ${token}` } : {}),
219
- };
220
- const url = write.operation === 'insert'
221
- ? `${this.config.baseUrl}/v1/sdk/db/insert`
222
- : `${this.config.baseUrl}/v1/sdk/db/records/${write.recordId}`;
223
- let res;
224
- if (write.operation === 'insert') {
225
- res = await fetch(url, {
226
- method: 'POST',
227
- headers,
228
- // The write's own id: generated at enqueue, identical on every retry.
229
- // Without it, an insert whose response was lost duplicated on replay —
230
- // the server had no way to recognise the repeat.
231
- body: JSON.stringify({
232
- collection: write.collection,
233
- data: write.data,
234
- idempotency_key: write.id,
235
- }),
236
- });
237
- }
238
- else if (write.operation === 'update') {
239
- res = await fetch(url, {
240
- method: 'PATCH',
241
- headers,
242
- // The revision the change was composed against. The server applies it
243
- // only if the record still carries that revision, so nothing can land
244
- // between the client deciding the write is safe and the server applying
245
- // it — which matters here most of all, since hours may have passed.
246
- body: JSON.stringify({
247
- data: write.data,
248
- ...(write.baseRevision !== undefined
249
- ? { expected_revision: write.baseRevision }
250
- : {}),
251
- }),
252
- });
253
- }
254
- else {
255
- const q = write.baseRevision !== undefined
256
- ? `?expected_revision=${write.baseRevision}`
257
- : '';
258
- res = await fetch(`${url}${q}`, { method: 'DELETE', headers });
259
- }
260
- if (res.status === 401)
261
- throw new errors_1.KoolbaseUnauthenticatedError('unauthorized');
262
- if (res.status === 409) {
263
- const body = await res.json().catch(() => ({}));
264
- if (body?.code === 'revision_mismatch') {
265
- throw new RevisionMismatch(body?.details?.record, body?.details?.current_revision);
266
- }
267
- }
268
- if (!res.ok && res.status !== 204) {
269
- const body = await res.json().catch(() => ({}));
270
- const message = body?.error ?? `${write.operation} failed`;
271
- // A 404 on a delete means the record is already gone, which is what the
272
- // write was asking for. Satisfied, not failed.
273
- if (res.status === 404 && write.operation === 'delete')
274
- return undefined;
275
- if (isTerminal(res.status))
276
- throw new TerminalRejection(message, res.status);
277
- throw new Error(`${write.operation} sync failed: ${res.status}`);
278
- }
279
- const text = await res.text().catch(() => '');
280
- if (!text)
281
- return undefined;
282
- try {
283
- return JSON.parse(text)?.$revision;
284
- }
285
- catch {
286
- return undefined;
287
- }
288
- }
289
- }
290
- exports.SyncEngine = SyncEngine;