@myfield/sdk 0.9.0 → 0.9.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.
- package/CHANGELOG.md +5 -0
- package/README.md +2 -2
- package/dist/index.js +230 -60
- package/docs/API.md +2 -1
- package/docs/BUCKET-SPEC.md +28 -13
- package/package.json +1 -1
- package/src/bucket/client.ts +74 -36
- package/src/bucket/format.ts +67 -18
- package/src/bucket/transport.ts +45 -5
- package/src/facade.ts +98 -16
package/CHANGELOG.md
CHANGED
package/README.md
CHANGED
|
@@ -89,8 +89,8 @@ compatibility metadata.
|
|
|
89
89
|
Deferred service work after this preview release:
|
|
90
90
|
|
|
91
91
|
- A bucket-scoped hibernatable WebSocket feed under the resource API root.
|
|
92
|
-
SSE remains compatibility/development-only; SDK fallback is
|
|
93
|
-
|
|
92
|
+
SSE remains compatibility/development-only; SDK fallback is timer
|
|
93
|
+
sync over the object index and feed.
|
|
94
94
|
|
|
95
95
|
## Public entry
|
|
96
96
|
|
package/dist/index.js
CHANGED
|
@@ -271,12 +271,14 @@ var PAYLOAD_FORMAT_VERSION = 1;
|
|
|
271
271
|
var HEADER_LENGTH_BYTES = 4;
|
|
272
272
|
var PART_LENGTH_BYTES = 4;
|
|
273
273
|
var BINARY_PART_MARKER = "binary-part-v1";
|
|
274
|
+
var LWW_MAP_KEYS = /* @__PURE__ */ new Set(["t", "fields", "tombstones"]);
|
|
274
275
|
function emptyLwwMapDoc() {
|
|
275
276
|
return { t: "lww-map", fields: {}, tombstones: {} };
|
|
276
277
|
}
|
|
277
278
|
function encodePayloadDoc(doc) {
|
|
278
279
|
const parts = [];
|
|
279
|
-
const
|
|
280
|
+
const body = doc.t === "lww-map" ? { ...doc.ext || {}, t: doc.t, fields: doc.fields, tombstones: doc.tombstones } : doc;
|
|
281
|
+
const header = utf8Encode(JSON.stringify(encodeHeaderValue(body, parts)));
|
|
280
282
|
let totalLength = 1 + HEADER_LENGTH_BYTES + header.byteLength;
|
|
281
283
|
for (const part of parts) totalLength += PART_LENGTH_BYTES + part.byteLength;
|
|
282
284
|
const out = new Uint8Array(totalLength);
|
|
@@ -325,7 +327,13 @@ function parsePayloadDoc(parsed) {
|
|
|
325
327
|
for (const entry of Object.values(doc.tombstones)) {
|
|
326
328
|
if (!isLwwTombstone(entry)) throw new Error("invalid lww-map tombstone");
|
|
327
329
|
}
|
|
328
|
-
|
|
330
|
+
const ext = Object.fromEntries(Object.entries(doc).filter(([key]) => !LWW_MAP_KEYS.has(key)));
|
|
331
|
+
return {
|
|
332
|
+
t: "lww-map",
|
|
333
|
+
fields: doc.fields,
|
|
334
|
+
tombstones: doc.tombstones,
|
|
335
|
+
...Object.keys(ext).length ? { ext } : {}
|
|
336
|
+
};
|
|
329
337
|
}
|
|
330
338
|
if (docRoot?.t === "opaque") return { t: "opaque", data: docRoot.data };
|
|
331
339
|
throw new Error("unknown payload doc type");
|
|
@@ -337,40 +345,73 @@ function wins(aTs, aActor, bTs, bActor) {
|
|
|
337
345
|
function fieldEntryWins(a, b) {
|
|
338
346
|
if (a.ts !== b.ts) return a.ts > b.ts;
|
|
339
347
|
if (a.actor !== b.actor) return a.actor > b.actor;
|
|
340
|
-
|
|
348
|
+
const aValue = JSON.stringify(fieldValueToCanonicalJson(a.v));
|
|
349
|
+
const bValue = JSON.stringify(fieldValueToCanonicalJson(b.v));
|
|
350
|
+
if (aValue !== bValue) return aValue > bValue;
|
|
351
|
+
return canonicalJson(a) > canonicalJson(b);
|
|
352
|
+
}
|
|
353
|
+
function tombstoneWins(a, b) {
|
|
354
|
+
if (a.ts !== b.ts || a.actor !== b.actor) return wins(a.ts, a.actor, b.ts, b.actor);
|
|
355
|
+
return canonicalJson(a) > canonicalJson(b);
|
|
341
356
|
}
|
|
342
357
|
function mergeLwwMapDocs(a, b) {
|
|
343
358
|
const tombstones = {};
|
|
344
359
|
for (const source of [a.tombstones, b.tombstones]) {
|
|
345
360
|
for (const [name, stone] of Object.entries(source)) {
|
|
346
361
|
const existing = tombstones[name];
|
|
347
|
-
if (!existing ||
|
|
362
|
+
if (!existing || tombstoneWins(stone, existing)) tombstones[name] = { ...stone };
|
|
348
363
|
}
|
|
349
364
|
}
|
|
350
365
|
const fields = {};
|
|
351
366
|
for (const source of [a.fields, b.fields]) {
|
|
352
367
|
for (const [name, entry] of Object.entries(source)) {
|
|
353
368
|
const existing = fields[name];
|
|
354
|
-
if (!existing || fieldEntryWins(entry, existing)) fields[name] = {
|
|
369
|
+
if (!existing || fieldEntryWins(entry, existing)) fields[name] = { ...entry };
|
|
355
370
|
}
|
|
356
371
|
}
|
|
357
372
|
for (const [name, stone] of Object.entries(tombstones)) {
|
|
358
373
|
const entry = fields[name];
|
|
359
374
|
if (entry && !wins(entry.ts, entry.actor, stone.ts, stone.actor)) delete fields[name];
|
|
360
375
|
}
|
|
361
|
-
|
|
376
|
+
const ext = mergeExt(a.ext, b.ext);
|
|
377
|
+
return { t: "lww-map", fields, tombstones, ...ext ? { ext } : {} };
|
|
378
|
+
}
|
|
379
|
+
function mergeExt(a, b) {
|
|
380
|
+
if (!a && !b) return void 0;
|
|
381
|
+
const merged = { ...a || {} };
|
|
382
|
+
for (const [key, value] of Object.entries(b || {})) {
|
|
383
|
+
if (!(key in merged) || canonicalJson(value) > canonicalJson(merged[key])) merged[key] = value;
|
|
384
|
+
}
|
|
385
|
+
return Object.keys(merged).length ? merged : void 0;
|
|
386
|
+
}
|
|
387
|
+
function canonicalJson(value) {
|
|
388
|
+
return stableStringify2(fieldValueToCanonicalJson(value));
|
|
389
|
+
}
|
|
390
|
+
function stableStringify2(value) {
|
|
391
|
+
if (Array.isArray(value)) return `[${value.map(stableStringify2).join(",")}]`;
|
|
392
|
+
if (value && typeof value === "object") {
|
|
393
|
+
const entries = Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
394
|
+
return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableStringify2(item)}`).join(",")}}`;
|
|
395
|
+
}
|
|
396
|
+
return JSON.stringify(value) ?? "null";
|
|
362
397
|
}
|
|
363
398
|
function lwwMapDocsEqual(a, b) {
|
|
364
|
-
return
|
|
399
|
+
return canonicalJson(canonicalLwwMapDoc(a)) === canonicalJson(canonicalLwwMapDoc(b));
|
|
365
400
|
}
|
|
366
401
|
function canonicalLwwMapDoc(doc) {
|
|
367
402
|
return {
|
|
368
|
-
fields: Object.fromEntries(
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
tombstones: Object.fromEntries(Object.entries(doc.tombstones).sort(([a], [b]) => a < b ? -1 : 1))
|
|
403
|
+
fields: Object.fromEntries(Object.entries(doc.fields).map(([name, entry]) => [name, { ...entry, v: fieldValueToCanonicalJson(entry.v) }])),
|
|
404
|
+
tombstones: doc.tombstones,
|
|
405
|
+
ext: doc.ext || {}
|
|
372
406
|
};
|
|
373
407
|
}
|
|
408
|
+
function lwwMapLatestTs(doc) {
|
|
409
|
+
let latest = null;
|
|
410
|
+
for (const entry of [...Object.values(doc.fields), ...Object.values(doc.tombstones)]) {
|
|
411
|
+
if (latest === null || entry.ts > latest) latest = entry.ts;
|
|
412
|
+
}
|
|
413
|
+
return latest;
|
|
414
|
+
}
|
|
374
415
|
function lwwMapValues(doc) {
|
|
375
416
|
return Object.fromEntries(Object.entries(doc.fields).map(([name, entry]) => [name, hydrateFieldValue(entry.v)]));
|
|
376
417
|
}
|
|
@@ -394,7 +435,8 @@ function applyLwwMapUpdates(doc, updates, clock, actor) {
|
|
|
394
435
|
const next = {
|
|
395
436
|
t: "lww-map",
|
|
396
437
|
fields: { ...doc.fields },
|
|
397
|
-
tombstones: { ...doc.tombstones }
|
|
438
|
+
tombstones: { ...doc.tombstones },
|
|
439
|
+
...doc.ext ? { ext: { ...doc.ext } } : {}
|
|
398
440
|
};
|
|
399
441
|
for (const [name, value] of Object.entries(updates)) {
|
|
400
442
|
const ts = clock.next();
|
|
@@ -607,9 +649,36 @@ var BucketTransport = class {
|
|
|
607
649
|
if (!res.ok) throw new BucketTransportError(`push failed: ${res.status}`, res.status);
|
|
608
650
|
return { ok: true, versionId };
|
|
609
651
|
}
|
|
610
|
-
|
|
652
|
+
async listHeads() {
|
|
653
|
+
const heads = /* @__PURE__ */ new Map();
|
|
654
|
+
const indexRes = await this.request(() => ({ url: `${this.bucketUrl()}/objects:index`, init: { method: "GET" } }));
|
|
655
|
+
if (!indexRes.ok) throw new BucketTransportError(`object index failed: ${indexRes.status}`, indexRes.status);
|
|
656
|
+
const index = await readJsonObject(indexRes, "object index");
|
|
657
|
+
if (!Array.isArray(index.objects)) throw new BucketTransportError("object index returned invalid response", indexRes.status);
|
|
658
|
+
addHeads(heads, index.objects);
|
|
659
|
+
let cursor = typeof index.feedCursor === "string" ? index.feedCursor : null;
|
|
660
|
+
let hasMore = index.hasMoreFeed === true;
|
|
661
|
+
for (let page = 0; hasMore; page += 1) {
|
|
662
|
+
if (page >= MAX_FEED_PAGES) throw new BucketTransportError("feed did not end within page limit", 500);
|
|
663
|
+
const query = new URLSearchParams({ limit: String(FEED_PAGE_LIMIT) });
|
|
664
|
+
if (cursor) query.set("cursor", cursor);
|
|
665
|
+
const feedRes = await this.request(() => ({ url: `${this.bucketUrl()}/feed?${query}`, init: { method: "GET" } }));
|
|
666
|
+
if (!feedRes.ok) throw new BucketTransportError(`feed failed: ${feedRes.status}`, feedRes.status);
|
|
667
|
+
const feed = await readJsonObject(feedRes, "feed");
|
|
668
|
+
if (!Array.isArray(feed.entries)) throw new BucketTransportError("feed returned invalid response", feedRes.status);
|
|
669
|
+
addHeads(heads, feed.entries);
|
|
670
|
+
const next = typeof feed.cursor === "string" ? feed.cursor : null;
|
|
671
|
+
hasMore = feed.hasMore === true && next !== null && next !== cursor;
|
|
672
|
+
cursor = next;
|
|
673
|
+
}
|
|
674
|
+
return heads;
|
|
675
|
+
}
|
|
676
|
+
bucketUrl() {
|
|
611
677
|
const syncRoot = this.apiBase.endsWith("/v1/api/sync") ? this.apiBase : `${this.apiBase}/v1/api/sync`;
|
|
612
|
-
return `${syncRoot}/buckets/${encodeURIComponent(this.keys.bucketId)}
|
|
678
|
+
return `${syncRoot}/buckets/${encodeURIComponent(this.keys.bucketId)}`;
|
|
679
|
+
}
|
|
680
|
+
objectUrl(wireObjectId) {
|
|
681
|
+
return `${this.bucketUrl()}/objects/${encodeURIComponent(wireObjectId)}`;
|
|
613
682
|
}
|
|
614
683
|
async request(build) {
|
|
615
684
|
let session = await this.sessionProvider.getSession();
|
|
@@ -635,6 +704,14 @@ var BucketTransport = class {
|
|
|
635
704
|
});
|
|
636
705
|
}
|
|
637
706
|
};
|
|
707
|
+
var FEED_PAGE_LIMIT = 100;
|
|
708
|
+
var MAX_FEED_PAGES = 1e4;
|
|
709
|
+
function addHeads(heads, entries) {
|
|
710
|
+
for (const entry of entries) {
|
|
711
|
+
const row = entry;
|
|
712
|
+
if (typeof row?.objectId === "string" && typeof row.versionId === "string") heads.set(row.objectId, row.versionId);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
638
715
|
async function readJsonObject(res, label) {
|
|
639
716
|
const contentType = res.headers.get("content-type") || "";
|
|
640
717
|
if (contentType && !contentType.toLowerCase().includes("application/json")) {
|
|
@@ -666,6 +743,8 @@ var BucketClient = class {
|
|
|
666
743
|
maxCasAttempts;
|
|
667
744
|
pushDebounceMs;
|
|
668
745
|
maxEncodedObjectBytes = DEFAULT_MAX_ENCODED_OBJECT_BYTES;
|
|
746
|
+
localOnly;
|
|
747
|
+
validateRemote;
|
|
669
748
|
onChange;
|
|
670
749
|
onSyncError;
|
|
671
750
|
clock = new LwwClock();
|
|
@@ -673,6 +752,8 @@ var BucketClient = class {
|
|
|
673
752
|
objectLocks = /* @__PURE__ */ new Map();
|
|
674
753
|
pendingPushTimers = /* @__PURE__ */ new Map();
|
|
675
754
|
watched = /* @__PURE__ */ new Set();
|
|
755
|
+
// Avoids re-downloading an unresolvable object until its head changes.
|
|
756
|
+
unresolved = /* @__PURE__ */ new Map();
|
|
676
757
|
triggerCleanup = null;
|
|
677
758
|
disposed = false;
|
|
678
759
|
constructor(options) {
|
|
@@ -684,6 +765,8 @@ var BucketClient = class {
|
|
|
684
765
|
this.mergeStrategyFor = options.mergeStrategyFor || (() => ({ kind: "lww-map" }));
|
|
685
766
|
this.maxCasAttempts = options.maxCasAttempts ?? DEFAULT_MAX_CAS_ATTEMPTS;
|
|
686
767
|
this.pushDebounceMs = options.pushDebounceMs ?? DEFAULT_PUSH_DEBOUNCE_MS;
|
|
768
|
+
this.localOnly = new Set(options.localOnlyObjectIds || []);
|
|
769
|
+
this.validateRemote = options.validateRemote;
|
|
687
770
|
this.onChange = options.onChange;
|
|
688
771
|
this.onSyncError = options.onSyncError;
|
|
689
772
|
}
|
|
@@ -698,6 +781,10 @@ var BucketClient = class {
|
|
|
698
781
|
if (!record || record.doc.t !== "opaque") return null;
|
|
699
782
|
return record.doc.data;
|
|
700
783
|
}
|
|
784
|
+
async lastModified(appObjectId) {
|
|
785
|
+
const record = await this.readRecord(appObjectId);
|
|
786
|
+
return record && record.doc.t === "lww-map" ? lwwMapLatestTs(record.doc) : null;
|
|
787
|
+
}
|
|
701
788
|
async knownObjectIds() {
|
|
702
789
|
const keys = await this.storage.keys(`${this.prefix}:obj:`);
|
|
703
790
|
return keys.map((key) => decodeURIComponent(key.slice(`${this.prefix}:obj:`.length)));
|
|
@@ -734,7 +821,7 @@ var BucketClient = class {
|
|
|
734
821
|
dirty: true
|
|
735
822
|
});
|
|
736
823
|
this.schedulePush(appObjectId);
|
|
737
|
-
this.onChange?.(appObjectId);
|
|
824
|
+
this.onChange?.(appObjectId, "local");
|
|
738
825
|
return lwwMapValues(nextDoc);
|
|
739
826
|
});
|
|
740
827
|
}
|
|
@@ -750,7 +837,7 @@ var BucketClient = class {
|
|
|
750
837
|
dirty: true
|
|
751
838
|
});
|
|
752
839
|
this.schedulePush(appObjectId);
|
|
753
|
-
this.onChange?.(appObjectId);
|
|
840
|
+
this.onChange?.(appObjectId, "local");
|
|
754
841
|
});
|
|
755
842
|
}
|
|
756
843
|
// ---- sync --------------------------------------------------------------
|
|
@@ -772,27 +859,46 @@ var BucketClient = class {
|
|
|
772
859
|
const ids = /* @__PURE__ */ new Set([...await this.knownObjectIds(), ...this.watched]);
|
|
773
860
|
await this.syncObjects(ids);
|
|
774
861
|
}
|
|
775
|
-
async
|
|
776
|
-
|
|
777
|
-
const
|
|
778
|
-
const
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
const
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
if (
|
|
789
|
-
|
|
862
|
+
async syncPass(options = {}) {
|
|
863
|
+
if (!this.transport.listHeads) throw new Error("transport does not list current heads");
|
|
864
|
+
const heads = await this.transport.listHeads();
|
|
865
|
+
for (const wireObjectId of options.skipWireIds || []) heads.delete(wireObjectId);
|
|
866
|
+
const known = /* @__PURE__ */ new Map();
|
|
867
|
+
const ids = new Set([...this.watched].filter((id) => !this.localOnly.has(id)));
|
|
868
|
+
for (const id of await this.knownObjectIds()) {
|
|
869
|
+
if (this.localOnly.has(id)) continue;
|
|
870
|
+
const record = await this.readRecord(id);
|
|
871
|
+
if (!record) continue;
|
|
872
|
+
const wireObjectId = await this.wireId(id);
|
|
873
|
+
known.set(wireObjectId, id);
|
|
874
|
+
const head = heads.get(wireObjectId);
|
|
875
|
+
if (record.dirty || head === void 0 || head !== record.remoteVersionId) ids.add(id);
|
|
876
|
+
}
|
|
877
|
+
for (const [wireObjectId, versionId] of heads) {
|
|
878
|
+
if (known.has(wireObjectId) || !options.resolveUnknown || this.unresolved.get(wireObjectId) === versionId) continue;
|
|
879
|
+
try {
|
|
880
|
+
const id = await options.resolveUnknown(wireObjectId, versionId);
|
|
881
|
+
if (id && !this.localOnly.has(id) && await this.wireId(id) === wireObjectId) {
|
|
882
|
+
this.unresolved.delete(wireObjectId);
|
|
883
|
+
ids.add(id);
|
|
884
|
+
} else {
|
|
885
|
+
this.unresolved.set(wireObjectId, versionId);
|
|
886
|
+
}
|
|
887
|
+
} catch (error) {
|
|
888
|
+
this.onSyncError?.(null, error);
|
|
790
889
|
}
|
|
791
890
|
}
|
|
792
|
-
const ids = /* @__PURE__ */ new Set([...this.watched, ...dirtyIdsBefore, ...changedIds]);
|
|
793
|
-
if (indexObjectId) ids.delete(indexObjectId);
|
|
794
891
|
await this.syncObjects(ids);
|
|
795
892
|
}
|
|
893
|
+
async pullDoc(wireObjectId, versionId) {
|
|
894
|
+
const payload = await this.transport.pullPayload(wireObjectId, versionId);
|
|
895
|
+
return payload.found ? decodePayloadDoc(payload.plaintext) : null;
|
|
896
|
+
}
|
|
897
|
+
async pullRemoteDoc(appObjectId) {
|
|
898
|
+
const wireObjectId = await this.wireId(appObjectId);
|
|
899
|
+
const head = await this.transport.pullHead(wireObjectId);
|
|
900
|
+
return head.found ? this.pullDoc(wireObjectId, head.versionId) : null;
|
|
901
|
+
}
|
|
796
902
|
watch(appObjectIds) {
|
|
797
903
|
for (const id of appObjectIds) this.watched.add(id);
|
|
798
904
|
}
|
|
@@ -801,8 +907,9 @@ var BucketClient = class {
|
|
|
801
907
|
// are scheduled by setFields/setData.
|
|
802
908
|
start(options) {
|
|
803
909
|
if (this.triggerCleanup || this.disposed) return;
|
|
804
|
-
const
|
|
805
|
-
const
|
|
910
|
+
const run = options.run;
|
|
911
|
+
const kick = () => void run().catch((error) => this.onSyncError?.(null, error));
|
|
912
|
+
const intervalMs = options.intervalMs ?? DEFAULT_SYNC_INTERVAL_MS;
|
|
806
913
|
const timer = intervalMs > 0 ? setInterval(kick, intervalMs) : null;
|
|
807
914
|
this.triggerCleanup = () => {
|
|
808
915
|
if (timer) clearInterval(timer);
|
|
@@ -832,7 +939,7 @@ var BucketClient = class {
|
|
|
832
939
|
}
|
|
833
940
|
// ---- internals ---------------------------------------------------------
|
|
834
941
|
schedulePush(appObjectId) {
|
|
835
|
-
if (this.disposed) return;
|
|
942
|
+
if (this.disposed || this.localOnly.has(appObjectId)) return;
|
|
836
943
|
const existing = this.pendingPushTimers.get(appObjectId);
|
|
837
944
|
if (existing) clearTimeout(existing);
|
|
838
945
|
this.pendingPushTimers.set(
|
|
@@ -844,6 +951,7 @@ var BucketClient = class {
|
|
|
844
951
|
);
|
|
845
952
|
}
|
|
846
953
|
async performSync(appObjectId) {
|
|
954
|
+
if (this.localOnly.has(appObjectId)) return false;
|
|
847
955
|
const wireObjectId = await this.wireId(appObjectId);
|
|
848
956
|
let remoteChangedLocal = false;
|
|
849
957
|
for (let attempt = 0; attempt < this.maxCasAttempts; attempt += 1) {
|
|
@@ -863,6 +971,7 @@ var BucketClient = class {
|
|
|
863
971
|
const payload = await this.transport.pullPayload(wireObjectId, head.versionId);
|
|
864
972
|
if (!payload.found) return "retry";
|
|
865
973
|
const remoteDoc = decodePayloadDoc(payload.plaintext);
|
|
974
|
+
this.validateRemote?.(appObjectId, remoteDoc);
|
|
866
975
|
const merged = record ? this.merge(appObjectId, record.doc, remoteDoc) : remoteDoc;
|
|
867
976
|
const localViewChanged = !record || !docsEqual(merged, record.doc);
|
|
868
977
|
const remoteNeedsUpdate = !docsEqual(merged, remoteDoc);
|
|
@@ -871,7 +980,7 @@ var BucketClient = class {
|
|
|
871
980
|
await this.writeRecord(appObjectId, { v: 1, doc: merged, remoteVersionId: head.versionId, dirty: false });
|
|
872
981
|
if (localViewChanged) {
|
|
873
982
|
remoteChangedLocal = true;
|
|
874
|
-
this.onChange?.(appObjectId);
|
|
983
|
+
this.onChange?.(appObjectId, "remote");
|
|
875
984
|
}
|
|
876
985
|
return remoteChangedLocal;
|
|
877
986
|
}
|
|
@@ -880,7 +989,7 @@ var BucketClient = class {
|
|
|
880
989
|
await this.writeRecord(appObjectId, { v: 1, doc: merged, remoteVersionId: result.versionId, dirty: false });
|
|
881
990
|
if (localViewChanged) {
|
|
882
991
|
remoteChangedLocal = true;
|
|
883
|
-
this.onChange?.(appObjectId);
|
|
992
|
+
this.onChange?.(appObjectId, "remote");
|
|
884
993
|
}
|
|
885
994
|
return remoteChangedLocal;
|
|
886
995
|
}
|
|
@@ -905,15 +1014,12 @@ var BucketClient = class {
|
|
|
905
1014
|
async dirtyObjectIds() {
|
|
906
1015
|
const ids = [];
|
|
907
1016
|
for (const id of await this.knownObjectIds()) {
|
|
1017
|
+
if (this.localOnly.has(id)) continue;
|
|
908
1018
|
const record = await this.readRecord(id);
|
|
909
1019
|
if (record?.dirty) ids.push(id);
|
|
910
1020
|
}
|
|
911
1021
|
return ids;
|
|
912
1022
|
}
|
|
913
|
-
async indexFields(indexObjectId) {
|
|
914
|
-
const record = await this.readRecord(indexObjectId);
|
|
915
|
-
return record?.doc.t === "lww-map" ? lwwMapValues(record.doc) : {};
|
|
916
|
-
}
|
|
917
1023
|
async readRecord(appObjectId) {
|
|
918
1024
|
const record = await this.storage.get(this.recordKey(appObjectId));
|
|
919
1025
|
if (!record || record.v !== 1 || !record.doc) return null;
|
|
@@ -934,10 +1040,6 @@ function docsEqual(a, b) {
|
|
|
934
1040
|
if (a.t === "opaque" && b.t === "opaque") return JSON.stringify(a.data) === JSON.stringify(b.data);
|
|
935
1041
|
return false;
|
|
936
1042
|
}
|
|
937
|
-
function diffIndexObjectIds(before, after) {
|
|
938
|
-
const ids = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)]);
|
|
939
|
-
return [...ids].filter((id) => JSON.stringify(before[id]) !== JSON.stringify(after[id]));
|
|
940
|
-
}
|
|
941
1043
|
|
|
942
1044
|
// src/bucket/store.ts
|
|
943
1045
|
var memoryNamespaceRegistry = /* @__PURE__ */ new Map();
|
|
@@ -1712,6 +1814,7 @@ var NotConnectedError = class extends Error {
|
|
|
1712
1814
|
var DEFAULT_AUTH_BASE = "https://myfield.one/auth/";
|
|
1713
1815
|
var DEFAULT_API_BASE = "https://api.myfield.one";
|
|
1714
1816
|
var INDEX_OBJECT_ID = "~index";
|
|
1817
|
+
var ID_FIELD = "~id";
|
|
1715
1818
|
var DELETED_FIELD = "~deleted";
|
|
1716
1819
|
var RESERVED_PREFIX = "~";
|
|
1717
1820
|
function createInstance(options = {}) {
|
|
@@ -1794,16 +1897,22 @@ function createBucketFacade(deps) {
|
|
|
1794
1897
|
push(wireObjectId, plaintext, expectedHeadVersionId) {
|
|
1795
1898
|
if (!liveTransport) return Promise.reject(new OfflineError());
|
|
1796
1899
|
return liveTransport.push(wireObjectId, plaintext, expectedHeadVersionId);
|
|
1900
|
+
},
|
|
1901
|
+
listHeads() {
|
|
1902
|
+
if (!liveTransport?.listHeads) return Promise.reject(new OfflineError());
|
|
1903
|
+
return liveTransport.listHeads();
|
|
1797
1904
|
}
|
|
1798
1905
|
},
|
|
1799
1906
|
storage: dataAdapter,
|
|
1800
1907
|
actorId,
|
|
1908
|
+
localOnlyObjectIds: [INDEX_OBJECT_ID],
|
|
1909
|
+
validateRemote: assertRemoteObjectId,
|
|
1801
1910
|
wireObjectId: (appObjectId) => {
|
|
1802
1911
|
if (!liveWireId) return Promise.reject(new OfflineError());
|
|
1803
1912
|
return liveWireId(appObjectId);
|
|
1804
1913
|
},
|
|
1805
1914
|
storagePrefix: `data:${bucketId}`,
|
|
1806
|
-
onChange:
|
|
1915
|
+
onChange: onClientChange,
|
|
1807
1916
|
onSyncError: (objectId, error) => {
|
|
1808
1917
|
if (error instanceof OfflineError) return;
|
|
1809
1918
|
emitState(state, `sync error${objectId ? ` (${objectId})` : ""}: ${formatError(error)}`);
|
|
@@ -1813,6 +1922,30 @@ function createBucketFacade(deps) {
|
|
|
1813
1922
|
})();
|
|
1814
1923
|
return clientInit;
|
|
1815
1924
|
}
|
|
1925
|
+
function assertRemoteObjectId(objectId, doc) {
|
|
1926
|
+
if (objectId.startsWith(RESERVED_PREFIX) || doc.t !== "lww-map") return;
|
|
1927
|
+
const remoteId = doc.fields[ID_FIELD]?.v;
|
|
1928
|
+
if (remoteId !== void 0 && remoteId !== objectId) throw new Error(`object id mismatch for ${objectId}`);
|
|
1929
|
+
}
|
|
1930
|
+
const pendingIndexRefreshes = /* @__PURE__ */ new Set();
|
|
1931
|
+
function onClientChange(objectId, source) {
|
|
1932
|
+
if (objectId.startsWith(RESERVED_PREFIX)) return;
|
|
1933
|
+
if (source === "local") {
|
|
1934
|
+
emitChange(objectId);
|
|
1935
|
+
return;
|
|
1936
|
+
}
|
|
1937
|
+
const refresh = refreshIndexEntry(objectId).catch((error) => emitState(state, `index update failed (${objectId}): ${formatError(error)}`)).finally(() => {
|
|
1938
|
+
pendingIndexRefreshes.delete(refresh);
|
|
1939
|
+
emitChange(objectId);
|
|
1940
|
+
});
|
|
1941
|
+
pendingIndexRefreshes.add(refresh);
|
|
1942
|
+
}
|
|
1943
|
+
async function refreshIndexEntry(objectId) {
|
|
1944
|
+
const c = await ensureClient();
|
|
1945
|
+
const raw = await c.getFields(objectId);
|
|
1946
|
+
const latest = await c.lastModified(objectId);
|
|
1947
|
+
await upsertIndexEntry(objectId, raw?.[DELETED_FIELD] === true, latest ?? Date.now());
|
|
1948
|
+
}
|
|
1816
1949
|
function assertObjectId(objectId) {
|
|
1817
1950
|
if (typeof objectId !== "string" || !objectId) throw new Error("objectId must be a non-empty string");
|
|
1818
1951
|
if (objectId.startsWith(RESERVED_PREFIX)) throw new Error(`object ids starting with "${RESERVED_PREFIX}" are reserved`);
|
|
@@ -1823,10 +1956,16 @@ function createBucketFacade(deps) {
|
|
|
1823
1956
|
if (name.startsWith(RESERVED_PREFIX)) throw new Error(`field names starting with "${RESERVED_PREFIX}" are reserved`);
|
|
1824
1957
|
}
|
|
1825
1958
|
}
|
|
1826
|
-
|
|
1959
|
+
let lastIndexRev = 0;
|
|
1960
|
+
async function upsertIndexEntry(objectId, deleted, updatedAtMs = Date.now()) {
|
|
1827
1961
|
const c = await ensureClient();
|
|
1962
|
+
lastIndexRev = Math.max(lastIndexRev + 1, Date.now());
|
|
1828
1963
|
await c.setFields(INDEX_OBJECT_ID, {
|
|
1829
|
-
[objectId]: {
|
|
1964
|
+
[objectId]: {
|
|
1965
|
+
updatedAt: new Date(updatedAtMs).toISOString(),
|
|
1966
|
+
rev: lastIndexRev,
|
|
1967
|
+
...deleted ? { deleted: true } : {}
|
|
1968
|
+
}
|
|
1830
1969
|
});
|
|
1831
1970
|
}
|
|
1832
1971
|
function publicView(raw) {
|
|
@@ -1845,6 +1984,9 @@ function createBucketFacade(deps) {
|
|
|
1845
1984
|
}
|
|
1846
1985
|
return changed;
|
|
1847
1986
|
}
|
|
1987
|
+
function withObjectId(updates, objectId, known) {
|
|
1988
|
+
return known[ID_FIELD] === objectId ? updates : { ...updates, [ID_FIELD]: objectId };
|
|
1989
|
+
}
|
|
1848
1990
|
async function put(objectId, object) {
|
|
1849
1991
|
assertObjectId(objectId);
|
|
1850
1992
|
assertFieldNames(object);
|
|
@@ -1852,11 +1994,11 @@ function createBucketFacade(deps) {
|
|
|
1852
1994
|
const known = await c.getFields(objectId) || {};
|
|
1853
1995
|
const updates = { ...object };
|
|
1854
1996
|
for (const name of Object.keys(known)) {
|
|
1855
|
-
if (!(name in object)) updates[name] = void 0;
|
|
1997
|
+
if (!(name in object) && name !== ID_FIELD) updates[name] = void 0;
|
|
1856
1998
|
}
|
|
1857
1999
|
const changed = await dropUnchanged(updates, known);
|
|
1858
2000
|
if (Object.keys(changed).length === 0) return;
|
|
1859
|
-
await c.setFields(objectId, changed);
|
|
2001
|
+
await c.setFields(objectId, withObjectId(changed, objectId, known));
|
|
1860
2002
|
await upsertIndexEntry(objectId, false);
|
|
1861
2003
|
}
|
|
1862
2004
|
async function update(objectId, fields) {
|
|
@@ -1868,7 +2010,7 @@ function createBucketFacade(deps) {
|
|
|
1868
2010
|
if (DELETED_FIELD in known) updates[DELETED_FIELD] = void 0;
|
|
1869
2011
|
const changed = await dropUnchanged(updates, known);
|
|
1870
2012
|
if (Object.keys(changed).length === 0) return;
|
|
1871
|
-
await c.setFields(objectId, changed);
|
|
2013
|
+
await c.setFields(objectId, withObjectId(changed, objectId, known));
|
|
1872
2014
|
await upsertIndexEntry(objectId, false);
|
|
1873
2015
|
}
|
|
1874
2016
|
async function getObject(objectId) {
|
|
@@ -1893,7 +2035,7 @@ function createBucketFacade(deps) {
|
|
|
1893
2035
|
for (const name of Object.keys(known)) {
|
|
1894
2036
|
if (!name.startsWith(RESERVED_PREFIX)) updates[name] = void 0;
|
|
1895
2037
|
}
|
|
1896
|
-
await c.setFields(objectId, updates);
|
|
2038
|
+
await c.setFields(objectId, withObjectId(updates, objectId, known));
|
|
1897
2039
|
await upsertIndexEntry(objectId, true);
|
|
1898
2040
|
}
|
|
1899
2041
|
async function list(options) {
|
|
@@ -1914,19 +2056,47 @@ function createBucketFacade(deps) {
|
|
|
1914
2056
|
}
|
|
1915
2057
|
async function sync() {
|
|
1916
2058
|
if (!liveTransport) throw new NotConnectedError();
|
|
2059
|
+
await runSyncPass();
|
|
2060
|
+
}
|
|
2061
|
+
async function runSyncPass() {
|
|
1917
2062
|
const c = await ensureClient();
|
|
1918
|
-
const
|
|
1919
|
-
|
|
1920
|
-
|
|
2063
|
+
const wireId = liveWireId;
|
|
2064
|
+
if (!wireId) throw new OfflineError();
|
|
2065
|
+
let legacyIndex;
|
|
2066
|
+
await c.syncPass({
|
|
2067
|
+
skipWireIds: [await wireId(INDEX_OBJECT_ID)],
|
|
2068
|
+
resolveUnknown: async (wireObjectId, versionId) => {
|
|
2069
|
+
const doc = await c.pullDoc(wireObjectId, versionId);
|
|
2070
|
+
if (!doc || doc.t !== "lww-map") return null;
|
|
2071
|
+
const id = doc.fields[ID_FIELD]?.v;
|
|
2072
|
+
if (typeof id === "string") return id;
|
|
2073
|
+
if (legacyIndex === void 0) {
|
|
2074
|
+
const legacy = await c.pullRemoteDoc(INDEX_OBJECT_ID);
|
|
2075
|
+
legacyIndex = legacy?.t === "lww-map" ? legacy.fields : null;
|
|
2076
|
+
}
|
|
2077
|
+
for (const candidate of Object.keys(legacyIndex || {})) {
|
|
2078
|
+
if (!candidate.startsWith(RESERVED_PREFIX) && await wireId(candidate) === wireObjectId) return candidate;
|
|
2079
|
+
}
|
|
2080
|
+
return null;
|
|
2081
|
+
}
|
|
2082
|
+
});
|
|
2083
|
+
await writeMissingObjectIds(c);
|
|
2084
|
+
await Promise.all(pendingIndexRefreshes);
|
|
2085
|
+
}
|
|
2086
|
+
async function writeMissingObjectIds(c) {
|
|
2087
|
+
const upgraded = [];
|
|
2088
|
+
for (const id of await c.knownObjectIds()) {
|
|
2089
|
+
if (id.startsWith(RESERVED_PREFIX)) continue;
|
|
1921
2090
|
const raw = await c.getFields(id);
|
|
1922
|
-
|
|
2091
|
+
if (!raw || raw[ID_FIELD] === id) continue;
|
|
2092
|
+
await c.setFields(id, { [ID_FIELD]: id });
|
|
2093
|
+
upgraded.push(id);
|
|
1923
2094
|
}
|
|
1924
|
-
|
|
2095
|
+
for (const id of upgraded) await c.flush(id);
|
|
1925
2096
|
}
|
|
1926
2097
|
function startAutoSync() {
|
|
1927
2098
|
if (!autoSync || !client) return;
|
|
1928
|
-
client.
|
|
1929
|
-
client.start({ indexObjectId: INDEX_OBJECT_ID, ...syncIntervalMs !== void 0 ? { intervalMs: syncIntervalMs } : {} });
|
|
2099
|
+
client.start({ run: runSyncPass, ...syncIntervalMs !== void 0 ? { intervalMs: syncIntervalMs } : {} });
|
|
1930
2100
|
}
|
|
1931
2101
|
async function readStoredEndpoints() {
|
|
1932
2102
|
const stored = await dataAdapter.get(endpointsKey);
|
package/docs/API.md
CHANGED
|
@@ -133,7 +133,8 @@ application-owned and is not a public SDK API concept.
|
|
|
133
133
|
- `get(id)` returns the local object or `null` when absent, deleted, or not
|
|
134
134
|
locally available.
|
|
135
135
|
- `list()` returns the local known-object index, newest first. It is not a
|
|
136
|
-
query/search API.
|
|
136
|
+
query/search API. Objects from other devices appear once a sync pulls
|
|
137
|
+
them; their `change` event fires after `list()` includes them.
|
|
137
138
|
- Object ids and field names starting with `~` are reserved and rejected.
|
|
138
139
|
|
|
139
140
|
## Connection API
|
package/docs/BUCKET-SPEC.md
CHANGED
|
@@ -54,6 +54,13 @@ The serialized-value tie-break only keeps malformed duplicate `(ts, actor)`
|
|
|
54
54
|
input deterministic. Normal writers do not emit two values at the same
|
|
55
55
|
`(ts, actor)`.
|
|
56
56
|
|
|
57
|
+
Unknown keys are kept, so the body can grow without a format-byte bump:
|
|
58
|
+
|
|
59
|
+
4. Extra keys in a field entry or tombstone travel with the winning entry;
|
|
60
|
+
full ties are broken by the canonical JSON of the whole entry.
|
|
61
|
+
5. Unknown top-level keys are unioned; on conflict the larger canonical
|
|
62
|
+
JSON wins. New top-level keys should carry their own `(ts, actor)`.
|
|
63
|
+
|
|
57
64
|
`put()` and `update()` preserve timestamps for JSON-unchanged fields.
|
|
58
65
|
Deleting a field writes a tombstone and removes the field entry; rewriting a
|
|
59
66
|
field removes its tombstone.
|
|
@@ -74,9 +81,14 @@ read or merged. This prevents a slow device clock from losing all merges.
|
|
|
74
81
|
The root package facade reserves app object ids and field names starting with
|
|
75
82
|
`~`.
|
|
76
83
|
|
|
77
|
-
- `~
|
|
78
|
-
|
|
79
|
-
|
|
84
|
+
- `~id`: the app object id (e.g. `note:<uuid>`), written with the object.
|
|
85
|
+
It maps a blinded object back to its app id without an index. It must
|
|
86
|
+
derive to the object's wire id and match the local app id; otherwise the
|
|
87
|
+
object is a sync error and is neither adopted nor pushed.
|
|
88
|
+
- `~deleted`: the deleted marker for object tombstones.
|
|
89
|
+
- `~index`: a local-only index behind `list()`, never pushed. Entries are
|
|
90
|
+
`{ updatedAt, rev, deleted? }`; a pulled object's `updatedAt` is its
|
|
91
|
+
latest field or tombstone timestamp.
|
|
80
92
|
|
|
81
93
|
Apps cannot write these names through `put()` / `update()` / `delete()`.
|
|
82
94
|
Lower-level source modules must preserve the same reservations when used by
|
|
@@ -139,15 +151,18 @@ Raw key bytes are zeroed after derivation.
|
|
|
139
151
|
|
|
140
152
|
## Sync Behavior Relevant To Format
|
|
141
153
|
|
|
142
|
-
The worker is a relay
|
|
143
|
-
|
|
154
|
+
The worker is a relay: it never decrypts payloads, but lists current
|
|
155
|
+
heads by wire id (`GET objects:index` snapshot plus `GET feed`).
|
|
144
156
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
157
|
+
Each object syncs as `pull current -> merge -> CAS push`, retrying on CAS
|
|
158
|
+
conflict and re-creating it from local state on a remote miss.
|
|
159
|
+
|
|
160
|
+
A sync pass:
|
|
148
161
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
162
|
+
1. Read `objects:index`, then `feed` from its `feedCursor` (or from the
|
|
163
|
+
start) until `hasMoreFeed` is false; later entries win. Result: wire id
|
|
164
|
+
to current version id. No cursor is persisted.
|
|
165
|
+
2. Sync each local object (not `~index`) that changed remotely, is dirty,
|
|
166
|
+
or is missing from the result.
|
|
167
|
+
3. For each unknown wire id, decrypt the payload, read `~id`, and sync it;
|
|
168
|
+
skip it until a later pass if unresolved.
|
package/package.json
CHANGED