@drakkar.software/starfish-client 2.3.0 → 3.0.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +219 -0
- package/dist/_crypto_helpers.d.ts +4 -0
- package/dist/bindings/zustand.d.ts +5 -4
- package/dist/bindings/zustand.js +125 -79
- package/dist/bindings/zustand.js.map +4 -4
- package/dist/cap-mint.d.ts +20 -0
- package/dist/cap-mint.js +12 -0
- package/dist/cap-mint.js.map +7 -0
- package/dist/client.d.ts +52 -3
- package/dist/config.d.ts +1 -4
- package/dist/directory.d.ts +9 -0
- package/dist/directory.js +24 -0
- package/dist/directory.js.map +7 -0
- package/dist/identity.d.ts +4 -82
- package/dist/identity.js +2 -354
- package/dist/identity.js.map +4 -4
- package/dist/index.d.ts +8 -10
- package/dist/index.js +131 -251
- package/dist/index.js.map +4 -4
- package/dist/keyring.d.ts +6 -0
- package/dist/keyring.js +26 -0
- package/dist/keyring.js.map +7 -0
- package/dist/pairing.d.ts +6 -0
- package/dist/pairing.js +26 -0
- package/dist/pairing.js.map +7 -0
- package/dist/recipients.d.ts +6 -0
- package/dist/recipients.js +16 -0
- package/dist/recipients.js.map +7 -0
- package/dist/sync.d.ts +32 -8
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +2 -2
- package/dist/testing.js.map +2 -2
- package/dist/types.d.ts +48 -9
- package/package.json +3 -12
- package/dist/background-sync.js +0 -29
- package/dist/bindings/suspense.js +0 -49
- package/dist/client.js +0 -112
- package/dist/config.js +0 -18
- package/dist/crypto.js +0 -49
- package/dist/debounced-sync.js +0 -120
- package/dist/dedup.js +0 -35
- package/dist/entitlements.js +0 -41
- package/dist/export.js +0 -115
- package/dist/group-crypto.d.ts +0 -111
- package/dist/group-crypto.js +0 -205
- package/dist/group-crypto.js.map +0 -7
- package/dist/hash.d.ts +0 -10
- package/dist/hash.js +0 -34
- package/dist/history.js +0 -61
- package/dist/logger.js +0 -80
- package/dist/migrate.js +0 -38
- package/dist/mobile-lifecycle.js +0 -55
- package/dist/multi-store.js +0 -92
- package/dist/platform.d.ts +0 -52
- package/dist/platform.js +0 -62
- package/dist/polling.js +0 -52
- package/dist/resolvers.js +0 -223
- package/dist/service-worker.js +0 -55
- package/dist/storage/indexeddb.js +0 -59
- package/dist/sync.js +0 -127
- package/dist/types.js +0 -18
- package/dist/validate.js +0 -28
package/dist/resolvers.js
DELETED
|
@@ -1,223 +0,0 @@
|
|
|
1
|
-
/** Shallow structural comparison of two values. Handles objects, arrays, and primitives. */
|
|
2
|
-
function shallowEqual(a, b) {
|
|
3
|
-
if (a === b)
|
|
4
|
-
return true;
|
|
5
|
-
if (a == null || b == null)
|
|
6
|
-
return a === b;
|
|
7
|
-
if (typeof a !== typeof b)
|
|
8
|
-
return false;
|
|
9
|
-
if (typeof a !== "object")
|
|
10
|
-
return false;
|
|
11
|
-
if (Array.isArray(a) !== Array.isArray(b))
|
|
12
|
-
return false;
|
|
13
|
-
if (Array.isArray(a) && Array.isArray(b)) {
|
|
14
|
-
if (a.length !== b.length)
|
|
15
|
-
return false;
|
|
16
|
-
return a.every((v, i) => shallowEqual(v, b[i]));
|
|
17
|
-
}
|
|
18
|
-
const aObj = a;
|
|
19
|
-
const bObj = b;
|
|
20
|
-
const aKeys = Object.keys(aObj);
|
|
21
|
-
const bKeys = Object.keys(bObj);
|
|
22
|
-
if (aKeys.length !== bKeys.length)
|
|
23
|
-
return false;
|
|
24
|
-
return aKeys.every((k) => shallowEqual(aObj[k], bObj[k]));
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* Wrap a standard ConflictResolver to also return metadata about which fields conflicted.
|
|
28
|
-
* Compares local and remote keys to detect differing fields.
|
|
29
|
-
*/
|
|
30
|
-
export function withConflictMeta(resolver) {
|
|
31
|
-
return (local, remote) => {
|
|
32
|
-
const conflictedFields = [];
|
|
33
|
-
const allKeys = new Set([...Object.keys(local), ...Object.keys(remote)]);
|
|
34
|
-
for (const key of allKeys) {
|
|
35
|
-
const lv = local[key];
|
|
36
|
-
const rv = remote[key];
|
|
37
|
-
if (!shallowEqual(lv, rv)) {
|
|
38
|
-
conflictedFields.push(key);
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
const data = resolver(local, remote);
|
|
42
|
-
// Determine how it was resolved using structural comparison
|
|
43
|
-
let resolvedBy = "merged";
|
|
44
|
-
if (shallowEqual(data, local))
|
|
45
|
-
resolvedBy = "local";
|
|
46
|
-
else if (shallowEqual(data, remote))
|
|
47
|
-
resolvedBy = "remote";
|
|
48
|
-
return {
|
|
49
|
-
data,
|
|
50
|
-
meta: {
|
|
51
|
-
conflictedFields,
|
|
52
|
-
resolvedBy,
|
|
53
|
-
timestamp: Date.now(),
|
|
54
|
-
},
|
|
55
|
-
};
|
|
56
|
-
};
|
|
57
|
-
}
|
|
58
|
-
/** Compare two timestamp values. Handles both numeric (epoch) and string (ISO-8601) timestamps. */
|
|
59
|
-
function compareTimestamps(a, b) {
|
|
60
|
-
if (typeof a === "number" && typeof b === "number")
|
|
61
|
-
return a >= b;
|
|
62
|
-
return String(a ?? "") >= String(b ?? "");
|
|
63
|
-
}
|
|
64
|
-
/**
|
|
65
|
-
* Creates a conflict resolver that merges arrays by ID with per-item
|
|
66
|
-
* timestamp comparison, and uses document-level timestamp for scalars.
|
|
67
|
-
*
|
|
68
|
-
* For arrays: builds a union of both sets keyed by `idKey`. When both
|
|
69
|
-
* sides have the same item, the one with the newer `timestampKey` wins.
|
|
70
|
-
* For scalars: the document with the newer `documentTimestampKey` wins.
|
|
71
|
-
*
|
|
72
|
-
* @example
|
|
73
|
-
* ```ts
|
|
74
|
-
* const merge = createUnionMerge()
|
|
75
|
-
* const sync = new SyncManager({ ..., onConflict: merge })
|
|
76
|
-
* ```
|
|
77
|
-
*/
|
|
78
|
-
export function createUnionMerge(options) {
|
|
79
|
-
const idKey = options?.idKey ?? "id";
|
|
80
|
-
const tsKey = options?.timestampKey ?? "updatedAt";
|
|
81
|
-
const docTsKey = options?.documentTimestampKey ?? "timestamp";
|
|
82
|
-
return (local, remote) => {
|
|
83
|
-
const result = {};
|
|
84
|
-
const localNewer = compareTimestamps(local[docTsKey], remote[docTsKey]);
|
|
85
|
-
const allKeys = new Set([...Object.keys(local), ...Object.keys(remote)]);
|
|
86
|
-
for (const key of allKeys) {
|
|
87
|
-
const lv = local[key];
|
|
88
|
-
const rv = remote[key];
|
|
89
|
-
// Both sides have arrays — attempt ID-based union
|
|
90
|
-
if (Array.isArray(lv) && Array.isArray(rv)) {
|
|
91
|
-
const map = new Map();
|
|
92
|
-
// Seed with remote items
|
|
93
|
-
for (const item of rv) {
|
|
94
|
-
if (item && typeof item === "object" && idKey in item) {
|
|
95
|
-
map.set(item[idKey], item);
|
|
96
|
-
}
|
|
97
|
-
else {
|
|
98
|
-
map.set(Symbol(), item);
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
// Overlay local items (per-item timestamp wins)
|
|
102
|
-
for (const item of lv) {
|
|
103
|
-
if (item && typeof item === "object" && idKey in item) {
|
|
104
|
-
const localItem = item;
|
|
105
|
-
const id = localItem[idKey];
|
|
106
|
-
const remoteItem = map.get(id);
|
|
107
|
-
if (!remoteItem) {
|
|
108
|
-
map.set(id, localItem);
|
|
109
|
-
}
|
|
110
|
-
else {
|
|
111
|
-
if (compareTimestamps(localItem[tsKey], remoteItem[tsKey])) {
|
|
112
|
-
map.set(id, localItem);
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
else {
|
|
117
|
-
map.set(Symbol(), item);
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
result[key] = [...map.values()];
|
|
121
|
-
}
|
|
122
|
-
else if (lv !== undefined && rv !== undefined) {
|
|
123
|
-
// Scalar: document-level timestamp wins
|
|
124
|
-
result[key] = localNewer ? lv : rv;
|
|
125
|
-
}
|
|
126
|
-
else {
|
|
127
|
-
// Only one side has the key
|
|
128
|
-
result[key] = lv ?? rv;
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
return result;
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
/**
|
|
135
|
-
* Creates a conflict resolver that handles soft-deleted items (tombstones).
|
|
136
|
-
* Extends union merge with tombstone awareness: if an item exists on one side
|
|
137
|
-
* with a `deletedAtKey` set, that deletion is respected even if the other side
|
|
138
|
-
* still has the item alive — as long as the deletion timestamp is newer.
|
|
139
|
-
*/
|
|
140
|
-
export function createSoftDeleteResolver(options) {
|
|
141
|
-
const idKey = options?.idKey ?? "id";
|
|
142
|
-
const tsKey = options?.timestampKey ?? "updatedAt";
|
|
143
|
-
const deletedAtKey = options?.deletedAtKey ?? "_deletedAt";
|
|
144
|
-
const baseMerge = createUnionMerge(options);
|
|
145
|
-
return (local, remote) => {
|
|
146
|
-
const merged = baseMerge(local, remote);
|
|
147
|
-
// Build a tombstone map from both sides: id → deletedAt timestamp
|
|
148
|
-
const tombstones = new Map();
|
|
149
|
-
for (const source of [local, remote]) {
|
|
150
|
-
for (const key of Object.keys(source)) {
|
|
151
|
-
const arr = source[key];
|
|
152
|
-
if (!Array.isArray(arr))
|
|
153
|
-
continue;
|
|
154
|
-
for (const item of arr) {
|
|
155
|
-
if (item && typeof item === "object" && idKey in item && deletedAtKey in item) {
|
|
156
|
-
const rec = item;
|
|
157
|
-
const id = rec[idKey];
|
|
158
|
-
const deletedAt = rec[deletedAtKey];
|
|
159
|
-
if (typeof deletedAt === "number" || typeof deletedAt === "string") {
|
|
160
|
-
const existing = tombstones.get(id);
|
|
161
|
-
if (existing == null || compareTimestamps(deletedAt, existing))
|
|
162
|
-
tombstones.set(id, deletedAt);
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
// For merged arrays, ensure tombstoned items stay deleted
|
|
169
|
-
// (don't resurrect an item if its tombstone is newer than its updatedAt)
|
|
170
|
-
for (const key of Object.keys(merged)) {
|
|
171
|
-
const value = merged[key];
|
|
172
|
-
if (!Array.isArray(value))
|
|
173
|
-
continue;
|
|
174
|
-
merged[key] = value.filter((item) => {
|
|
175
|
-
if (!item || typeof item !== "object" || !(idKey in item))
|
|
176
|
-
return true;
|
|
177
|
-
const rec = item;
|
|
178
|
-
const id = rec[idKey];
|
|
179
|
-
const deletedAt = tombstones.get(id);
|
|
180
|
-
if (deletedAt == null)
|
|
181
|
-
return true;
|
|
182
|
-
// Keep the item if it has a deletedAt (it's the tombstone itself)
|
|
183
|
-
if (rec[deletedAtKey] != null)
|
|
184
|
-
return true;
|
|
185
|
-
// Filter out alive items that have a newer tombstone
|
|
186
|
-
return compareTimestamps(rec[tsKey], deletedAt) && rec[tsKey] !== deletedAt;
|
|
187
|
-
});
|
|
188
|
-
}
|
|
189
|
-
return merged;
|
|
190
|
-
};
|
|
191
|
-
}
|
|
192
|
-
/**
|
|
193
|
-
* Simple resolver: the document with the newer timestamp wins entirely.
|
|
194
|
-
* No per-field or per-item merging.
|
|
195
|
-
*/
|
|
196
|
-
export function timestampWinner(timestampKey = "timestamp") {
|
|
197
|
-
return (local, remote) => {
|
|
198
|
-
return compareTimestamps(local[timestampKey], remote[timestampKey])
|
|
199
|
-
? local
|
|
200
|
-
: remote;
|
|
201
|
-
};
|
|
202
|
-
}
|
|
203
|
-
/**
|
|
204
|
-
* Remove expired tombstones from an array of items.
|
|
205
|
-
* Items with a `deletedAtKey` older than `ttlMs` are pruned.
|
|
206
|
-
*
|
|
207
|
-
* @param items - Array of items, some with a deletedAt timestamp
|
|
208
|
-
* @param ttlMs - Time-to-live in ms for tombstones (default: 30 days)
|
|
209
|
-
* @param deletedAtKey - Key marking deletion timestamp (default: "_deletedAt")
|
|
210
|
-
*/
|
|
211
|
-
export function pruneTombstones(items, ttlMs = 30 * 24 * 60 * 60 * 1000, deletedAtKey = "_deletedAt") {
|
|
212
|
-
const cutoff = Date.now() - ttlMs;
|
|
213
|
-
return items.filter((item) => {
|
|
214
|
-
const deletedAt = item[deletedAtKey];
|
|
215
|
-
if (deletedAt == null)
|
|
216
|
-
return true;
|
|
217
|
-
if (typeof deletedAt === "number")
|
|
218
|
-
return deletedAt > cutoff;
|
|
219
|
-
if (typeof deletedAt === "string")
|
|
220
|
-
return new Date(deletedAt).getTime() > cutoff;
|
|
221
|
-
return false;
|
|
222
|
-
});
|
|
223
|
-
}
|
package/dist/service-worker.js
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Service Worker utilities for offline support and PWA functionality.
|
|
3
|
-
*/
|
|
4
|
-
/** Check if service workers are supported in the current environment. */
|
|
5
|
-
export function isServiceWorkerSupported() {
|
|
6
|
-
return typeof navigator !== "undefined" && "serviceWorker" in navigator;
|
|
7
|
-
}
|
|
8
|
-
/**
|
|
9
|
-
* Register a service worker for offline support.
|
|
10
|
-
* Returns the registration, or null if not supported.
|
|
11
|
-
*/
|
|
12
|
-
export async function registerServiceWorker(scriptUrl, opts) {
|
|
13
|
-
if (!isServiceWorkerSupported())
|
|
14
|
-
return null;
|
|
15
|
-
try {
|
|
16
|
-
const registration = await navigator.serviceWorker.register(scriptUrl, {
|
|
17
|
-
scope: opts?.scope,
|
|
18
|
-
});
|
|
19
|
-
if (opts?.onUpdate) {
|
|
20
|
-
registration.onupdatefound = () => {
|
|
21
|
-
const installingWorker = registration.installing;
|
|
22
|
-
if (installingWorker) {
|
|
23
|
-
installingWorker.onstatechange = () => {
|
|
24
|
-
if (installingWorker.state === "installed" &&
|
|
25
|
-
navigator.serviceWorker.controller) {
|
|
26
|
-
opts.onUpdate(registration);
|
|
27
|
-
}
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
return registration;
|
|
33
|
-
}
|
|
34
|
-
catch {
|
|
35
|
-
return null;
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
/** Unregister all service worker registrations. Returns true if any were unregistered. */
|
|
39
|
-
export async function unregisterServiceWorkers() {
|
|
40
|
-
if (!isServiceWorkerSupported())
|
|
41
|
-
return false;
|
|
42
|
-
try {
|
|
43
|
-
const registrations = await navigator.serviceWorker.getRegistrations();
|
|
44
|
-
let unregistered = false;
|
|
45
|
-
for (const registration of registrations) {
|
|
46
|
-
const result = await registration.unregister();
|
|
47
|
-
if (result)
|
|
48
|
-
unregistered = true;
|
|
49
|
-
}
|
|
50
|
-
return unregistered;
|
|
51
|
-
}
|
|
52
|
-
catch {
|
|
53
|
-
return false;
|
|
54
|
-
}
|
|
55
|
-
}
|
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* IndexedDB-based storage adapter for Zustand persistence.
|
|
3
|
-
* Implements the same interface as Zustand's StateStorage (getItem/setItem/removeItem).
|
|
4
|
-
* Supports larger data than localStorage (typically 50MB+).
|
|
5
|
-
*/
|
|
6
|
-
function openDB(dbName, storeName) {
|
|
7
|
-
return new Promise((resolve, reject) => {
|
|
8
|
-
const request = indexedDB.open(dbName, 1);
|
|
9
|
-
request.onupgradeneeded = () => {
|
|
10
|
-
const db = request.result;
|
|
11
|
-
if (!db.objectStoreNames.contains(storeName)) {
|
|
12
|
-
db.createObjectStore(storeName);
|
|
13
|
-
}
|
|
14
|
-
};
|
|
15
|
-
request.onsuccess = () => resolve(request.result);
|
|
16
|
-
request.onerror = () => reject(request.error);
|
|
17
|
-
});
|
|
18
|
-
}
|
|
19
|
-
function idbRequest(request) {
|
|
20
|
-
return new Promise((resolve, reject) => {
|
|
21
|
-
request.onsuccess = () => resolve(request.result);
|
|
22
|
-
request.onerror = () => reject(request.error);
|
|
23
|
-
});
|
|
24
|
-
}
|
|
25
|
-
export function createIndexedDBStorage(opts) {
|
|
26
|
-
const dbName = opts?.dbName ?? "starfish";
|
|
27
|
-
const storeName = opts?.storeName ?? "state";
|
|
28
|
-
let dbPromise = null;
|
|
29
|
-
function getDB() {
|
|
30
|
-
if (!dbPromise) {
|
|
31
|
-
dbPromise = openDB(dbName, storeName).catch((err) => {
|
|
32
|
-
dbPromise = null; // Reset so next call retries
|
|
33
|
-
throw err;
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
return dbPromise;
|
|
37
|
-
}
|
|
38
|
-
return {
|
|
39
|
-
async getItem(name) {
|
|
40
|
-
const db = await getDB();
|
|
41
|
-
const tx = db.transaction(storeName, "readonly");
|
|
42
|
-
const store = tx.objectStore(storeName);
|
|
43
|
-
const result = await idbRequest(store.get(name));
|
|
44
|
-
return result ?? null;
|
|
45
|
-
},
|
|
46
|
-
async setItem(name, value) {
|
|
47
|
-
const db = await getDB();
|
|
48
|
-
const tx = db.transaction(storeName, "readwrite");
|
|
49
|
-
const store = tx.objectStore(storeName);
|
|
50
|
-
await idbRequest(store.put(value, name));
|
|
51
|
-
},
|
|
52
|
-
async removeItem(name) {
|
|
53
|
-
const db = await getDB();
|
|
54
|
-
const tx = db.transaction(storeName, "readwrite");
|
|
55
|
-
const store = tx.objectStore(storeName);
|
|
56
|
-
await idbRequest(store.delete(name));
|
|
57
|
-
},
|
|
58
|
-
};
|
|
59
|
-
}
|
package/dist/sync.js
DELETED
|
@@ -1,127 +0,0 @@
|
|
|
1
|
-
import { deepMerge, stableStringify } from "@drakkar.software/starfish-protocol";
|
|
2
|
-
import { ConflictError } from "./types.js";
|
|
3
|
-
import { createEncryptor } from "./crypto.js";
|
|
4
|
-
import { ValidationError } from "./validate.js";
|
|
5
|
-
export class SyncManager {
|
|
6
|
-
client;
|
|
7
|
-
pullPath;
|
|
8
|
-
pushPath;
|
|
9
|
-
onConflict;
|
|
10
|
-
maxRetries;
|
|
11
|
-
encryptor;
|
|
12
|
-
signData;
|
|
13
|
-
logger;
|
|
14
|
-
loggerName;
|
|
15
|
-
validate;
|
|
16
|
-
lastHash = null;
|
|
17
|
-
lastCheckpoint = 0;
|
|
18
|
-
localData = {};
|
|
19
|
-
constructor(options) {
|
|
20
|
-
this.client = options.client;
|
|
21
|
-
this.pullPath = options.pullPath;
|
|
22
|
-
this.pushPath = options.pushPath;
|
|
23
|
-
this.onConflict = options.onConflict ?? deepMerge;
|
|
24
|
-
this.maxRetries = options.maxRetries ?? 3;
|
|
25
|
-
this.signData = options.signData;
|
|
26
|
-
this.logger = options.logger;
|
|
27
|
-
this.loggerName = options.loggerName ?? options.pullPath.split("/").filter(Boolean).pop() ?? options.pullPath;
|
|
28
|
-
this.validate = options.validate;
|
|
29
|
-
this.encryptor =
|
|
30
|
-
options.encryptor ??
|
|
31
|
-
(options.encryptionSecret && options.encryptionSalt
|
|
32
|
-
? createEncryptor(options.encryptionSecret, options.encryptionSalt, options.encryptionInfo)
|
|
33
|
-
: null);
|
|
34
|
-
}
|
|
35
|
-
getData() {
|
|
36
|
-
return { ...this.localData };
|
|
37
|
-
}
|
|
38
|
-
getHash() {
|
|
39
|
-
return this.lastHash;
|
|
40
|
-
}
|
|
41
|
-
getCheckpoint() {
|
|
42
|
-
return this.lastCheckpoint;
|
|
43
|
-
}
|
|
44
|
-
async pull() {
|
|
45
|
-
this.logger?.pullStart(this.loggerName);
|
|
46
|
-
const start = performance.now();
|
|
47
|
-
try {
|
|
48
|
-
const result = await this.client.pull(this.pullPath, this.lastCheckpoint);
|
|
49
|
-
if (this.encryptor) {
|
|
50
|
-
const decrypted = await this.encryptor.decrypt(result.data);
|
|
51
|
-
this.localData = decrypted;
|
|
52
|
-
result.data = decrypted;
|
|
53
|
-
}
|
|
54
|
-
else if (this.lastCheckpoint > 0) {
|
|
55
|
-
this.localData = deepMerge(this.localData, result.data);
|
|
56
|
-
result.data = this.localData;
|
|
57
|
-
}
|
|
58
|
-
else {
|
|
59
|
-
this.localData = result.data;
|
|
60
|
-
}
|
|
61
|
-
this.lastHash = result.hash;
|
|
62
|
-
this.lastCheckpoint = result.timestamp;
|
|
63
|
-
this.logger?.pullSuccess(this.loggerName, Math.round(performance.now() - start));
|
|
64
|
-
return result;
|
|
65
|
-
}
|
|
66
|
-
catch (err) {
|
|
67
|
-
this.logger?.pullError(this.loggerName, err instanceof Error ? err.message : String(err));
|
|
68
|
-
throw err;
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
async push(data) {
|
|
72
|
-
if (this.validate) {
|
|
73
|
-
const result = this.validate(data);
|
|
74
|
-
if (result !== true)
|
|
75
|
-
throw new ValidationError(result);
|
|
76
|
-
}
|
|
77
|
-
this.logger?.pushStart(this.loggerName);
|
|
78
|
-
const start = performance.now();
|
|
79
|
-
let attempt = 0;
|
|
80
|
-
let pendingData = data;
|
|
81
|
-
while (attempt <= this.maxRetries) {
|
|
82
|
-
try {
|
|
83
|
-
const payload = this.encryptor
|
|
84
|
-
? await this.encryptor.encrypt(pendingData)
|
|
85
|
-
: pendingData;
|
|
86
|
-
const sig = this.signData
|
|
87
|
-
? await this.signData(stableStringify(payload))
|
|
88
|
-
: undefined;
|
|
89
|
-
const result = await this.client.push(this.pushPath, payload, this.lastHash, sig);
|
|
90
|
-
this.lastHash = result.hash;
|
|
91
|
-
this.lastCheckpoint = result.timestamp;
|
|
92
|
-
this.localData = pendingData;
|
|
93
|
-
this.logger?.pushSuccess(this.loggerName, Math.round(performance.now() - start));
|
|
94
|
-
return result;
|
|
95
|
-
}
|
|
96
|
-
catch (err) {
|
|
97
|
-
if (!(err instanceof ConflictError) || attempt >= this.maxRetries) {
|
|
98
|
-
this.logger?.pushError(this.loggerName, err instanceof Error ? err.message : String(err));
|
|
99
|
-
throw err;
|
|
100
|
-
}
|
|
101
|
-
this.logger?.conflict(this.loggerName, attempt + 1);
|
|
102
|
-
try {
|
|
103
|
-
const remote = await this.client.pull(this.pullPath);
|
|
104
|
-
const remoteData = this.encryptor
|
|
105
|
-
? await this.encryptor.decrypt(remote.data)
|
|
106
|
-
: remote.data;
|
|
107
|
-
this.lastHash = remote.hash;
|
|
108
|
-
this.lastCheckpoint = remote.timestamp;
|
|
109
|
-
pendingData = this.onConflict(pendingData, remoteData);
|
|
110
|
-
}
|
|
111
|
-
catch (resolveErr) {
|
|
112
|
-
const msg = resolveErr instanceof Error ? resolveErr.message : String(resolveErr);
|
|
113
|
-
this.logger?.pushError(this.loggerName, `Conflict resolution failed (attempt ${attempt + 1}): ${msg}`);
|
|
114
|
-
throw resolveErr;
|
|
115
|
-
}
|
|
116
|
-
await new Promise(resolve => setTimeout(resolve, Math.min(100 * Math.pow(2, attempt), 2000) + Math.random() * 100));
|
|
117
|
-
attempt++;
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
throw new ConflictError();
|
|
121
|
-
}
|
|
122
|
-
async update(modifier) {
|
|
123
|
-
await this.pull();
|
|
124
|
-
const updated = modifier(this.localData);
|
|
125
|
-
return this.push(updated);
|
|
126
|
-
}
|
|
127
|
-
}
|
package/dist/types.js
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
/** Push conflict error (HTTP 409). */
|
|
2
|
-
export class ConflictError extends Error {
|
|
3
|
-
constructor() {
|
|
4
|
-
super("hash_mismatch");
|
|
5
|
-
this.name = "ConflictError";
|
|
6
|
-
}
|
|
7
|
-
}
|
|
8
|
-
/** HTTP error from the Starfish server. */
|
|
9
|
-
export class StarfishHttpError extends Error {
|
|
10
|
-
status;
|
|
11
|
-
body;
|
|
12
|
-
constructor(status, body) {
|
|
13
|
-
super(`HTTP ${status}: ${body}`);
|
|
14
|
-
this.status = status;
|
|
15
|
-
this.body = body;
|
|
16
|
-
this.name = "StarfishHttpError";
|
|
17
|
-
}
|
|
18
|
-
}
|
package/dist/validate.js
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
/** Error thrown when pre-push validation fails. */
|
|
2
|
-
export class ValidationError extends Error {
|
|
3
|
-
errors;
|
|
4
|
-
constructor(errors) {
|
|
5
|
-
super(`Validation failed: ${errors.join("; ")}`);
|
|
6
|
-
this.errors = errors;
|
|
7
|
-
this.name = "ValidationError";
|
|
8
|
-
}
|
|
9
|
-
}
|
|
10
|
-
/**
|
|
11
|
-
* Creates a validator from a JSON Schema object.
|
|
12
|
-
* Requires an Ajv-compatible validate function.
|
|
13
|
-
*
|
|
14
|
-
* @example
|
|
15
|
-
* ```ts
|
|
16
|
-
* import Ajv from "ajv"
|
|
17
|
-
* const ajv = new Ajv()
|
|
18
|
-
* const validator = createSchemaValidator(ajv, mySchema)
|
|
19
|
-
* ```
|
|
20
|
-
*/
|
|
21
|
-
export function createSchemaValidator(ajv, schema) {
|
|
22
|
-
const validate = ajv.compile(schema);
|
|
23
|
-
return (data) => {
|
|
24
|
-
if (validate(data))
|
|
25
|
-
return true;
|
|
26
|
-
return [ajv.errorsText(validate.errors)];
|
|
27
|
-
};
|
|
28
|
-
}
|