@myfield/sdk 0.9.0 → 0.9.2
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 +25 -0
- package/README.md +34 -54
- package/dist/index.js +1964 -674
- package/docs/API.md +145 -57
- package/docs/BUCKET-SPEC.md +33 -13
- package/package.json +4 -2
- package/src/auth/authorization.ts +254 -0
- package/src/auth/flow.ts +93 -0
- package/src/auth/identifiers.ts +46 -0
- package/src/auth/instance.ts +33 -514
- package/src/auth/keys.ts +73 -0
- package/src/auth/proof.ts +26 -0
- package/src/auth/session.ts +16 -0
- package/src/auth/store.ts +90 -0
- package/src/auth/types.ts +47 -0
- package/src/bucket/client.ts +79 -36
- package/src/bucket/format.ts +67 -18
- package/src/bucket/store.ts +31 -0
- package/src/bucket/transport.ts +73 -11
- package/src/errors.ts +31 -0
- package/src/facade.ts +337 -330
- package/src/index.ts +6 -0
- package/src/remote/bucket.ts +180 -0
- package/src/remote/client.ts +38 -0
- package/src/remote/connection.ts +529 -0
- package/src/remote/feed.ts +80 -0
- package/src/remote/http.ts +78 -0
- package/src/remote/session.ts +31 -0
- package/types/index.d.ts +85 -1
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();
|
|
@@ -506,6 +548,33 @@ function buildAad(bucketId, wireObjectId) {
|
|
|
506
548
|
return `myfield.bucket.sync.v1|${bucketId}|${wireObjectId}`;
|
|
507
549
|
}
|
|
508
550
|
|
|
551
|
+
// src/errors.ts
|
|
552
|
+
var NotConnectedError = class extends Error {
|
|
553
|
+
constructor() {
|
|
554
|
+
super("bucket is not connected; call connect() first");
|
|
555
|
+
this.name = "NotConnectedError";
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
var REVOKED_AUTHORIZATION_CODES = ["GRANT_REVOKED", "GRANT_NOT_FOUND", "AUTH_FAILED"];
|
|
559
|
+
var ClientError = class extends Error {
|
|
560
|
+
code;
|
|
561
|
+
status;
|
|
562
|
+
requestId;
|
|
563
|
+
retryable;
|
|
564
|
+
retryAfterMs;
|
|
565
|
+
maxBytes;
|
|
566
|
+
constructor(code, message, options = {}) {
|
|
567
|
+
super(message, { cause: options.cause });
|
|
568
|
+
this.name = "ClientError";
|
|
569
|
+
this.code = code;
|
|
570
|
+
this.status = options.status;
|
|
571
|
+
this.requestId = options.requestId;
|
|
572
|
+
this.retryable = options.retryable ?? false;
|
|
573
|
+
this.retryAfterMs = options.retryAfterMs;
|
|
574
|
+
this.maxBytes = options.maxBytes;
|
|
575
|
+
}
|
|
576
|
+
};
|
|
577
|
+
|
|
509
578
|
// src/bucket/transport.ts
|
|
510
579
|
var OfflineError = class extends Error {
|
|
511
580
|
constructor() {
|
|
@@ -516,10 +585,10 @@ var OfflineError = class extends Error {
|
|
|
516
585
|
var BucketTransportError = class extends Error {
|
|
517
586
|
status;
|
|
518
587
|
retryable;
|
|
519
|
-
constructor(message, status) {
|
|
588
|
+
constructor(message, status, retryable = status === 429 || status >= 500) {
|
|
520
589
|
super(message);
|
|
521
590
|
this.status = status;
|
|
522
|
-
this.retryable =
|
|
591
|
+
this.retryable = retryable;
|
|
523
592
|
}
|
|
524
593
|
};
|
|
525
594
|
var BucketTransport = class {
|
|
@@ -527,11 +596,13 @@ var BucketTransport = class {
|
|
|
527
596
|
mfid;
|
|
528
597
|
keys;
|
|
529
598
|
sessionProvider;
|
|
599
|
+
fetch;
|
|
530
600
|
constructor(options) {
|
|
531
601
|
this.apiBase = options.apiBase.replace(/\/+$/, "");
|
|
532
602
|
this.mfid = options.mfid;
|
|
533
603
|
this.keys = options.keys;
|
|
534
604
|
this.sessionProvider = options.sessionProvider;
|
|
605
|
+
this.fetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
|
|
535
606
|
}
|
|
536
607
|
async pullHead(wireObjectId) {
|
|
537
608
|
const currentRes = await this.request(() => ({
|
|
@@ -605,36 +676,93 @@ var BucketTransport = class {
|
|
|
605
676
|
return { ok: false, conflict: true, remoteVersionId: body?.headVersionId ?? null };
|
|
606
677
|
}
|
|
607
678
|
if (!res.ok) throw new BucketTransportError(`push failed: ${res.status}`, res.status);
|
|
608
|
-
|
|
679
|
+
const result = await readJsonObject(res, "push");
|
|
680
|
+
if (result.ok === true) return { ok: true, versionId };
|
|
681
|
+
if (result.ok === false && ["version-mismatch", "conflict"].includes(String(result.reason))) {
|
|
682
|
+
return { ok: false, conflict: true, remoteVersionId: typeof result.headVersionId === "string" ? result.headVersionId : null };
|
|
683
|
+
}
|
|
684
|
+
if (result.ok === false && result.reason === "unauthorized") {
|
|
685
|
+
await this.sessionProvider.onUnauthorized?.();
|
|
686
|
+
throw new BucketTransportError("push was not authorized", 401, false);
|
|
687
|
+
}
|
|
688
|
+
throw new BucketTransportError(
|
|
689
|
+
`push returned an unconfirmed acknowledgement${typeof result.reason === "string" ? `: ${result.reason}` : ""}`,
|
|
690
|
+
res.status,
|
|
691
|
+
result.reason !== "invalid-input"
|
|
692
|
+
);
|
|
609
693
|
}
|
|
610
|
-
|
|
694
|
+
async listHeads() {
|
|
695
|
+
const heads = /* @__PURE__ */ new Map();
|
|
696
|
+
const indexRes = await this.request(() => ({ url: `${this.bucketUrl()}/objects:index`, init: { method: "GET" } }));
|
|
697
|
+
if (!indexRes.ok) throw new BucketTransportError(`object index failed: ${indexRes.status}`, indexRes.status);
|
|
698
|
+
const index = await readJsonObject(indexRes, "object index");
|
|
699
|
+
if (!Array.isArray(index.objects)) throw new BucketTransportError("object index returned invalid response", indexRes.status);
|
|
700
|
+
addHeads(heads, index.objects);
|
|
701
|
+
let cursor = typeof index.feedCursor === "string" ? index.feedCursor : null;
|
|
702
|
+
let hasMore = index.hasMoreFeed === true;
|
|
703
|
+
for (let page = 0; hasMore; page += 1) {
|
|
704
|
+
if (page >= MAX_FEED_PAGES) throw new BucketTransportError("feed did not end within page limit", 500);
|
|
705
|
+
const query = new URLSearchParams({ limit: String(FEED_PAGE_LIMIT) });
|
|
706
|
+
if (cursor) query.set("cursor", cursor);
|
|
707
|
+
const feedRes = await this.request(() => ({ url: `${this.bucketUrl()}/feed?${query}`, init: { method: "GET" } }));
|
|
708
|
+
if (!feedRes.ok) throw new BucketTransportError(`feed failed: ${feedRes.status}`, feedRes.status);
|
|
709
|
+
const feed = await readJsonObject(feedRes, "feed");
|
|
710
|
+
if (!Array.isArray(feed.entries)) throw new BucketTransportError("feed returned invalid response", feedRes.status);
|
|
711
|
+
addHeads(heads, feed.entries);
|
|
712
|
+
const next = typeof feed.cursor === "string" ? feed.cursor : null;
|
|
713
|
+
hasMore = feed.hasMore === true && next !== null && next !== cursor;
|
|
714
|
+
cursor = next;
|
|
715
|
+
}
|
|
716
|
+
return heads;
|
|
717
|
+
}
|
|
718
|
+
bucketUrl() {
|
|
611
719
|
const syncRoot = this.apiBase.endsWith("/v1/api/sync") ? this.apiBase : `${this.apiBase}/v1/api/sync`;
|
|
612
|
-
return `${syncRoot}/buckets/${encodeURIComponent(this.keys.bucketId)}
|
|
720
|
+
return `${syncRoot}/buckets/${encodeURIComponent(this.keys.bucketId)}`;
|
|
721
|
+
}
|
|
722
|
+
objectUrl(wireObjectId) {
|
|
723
|
+
return `${this.bucketUrl()}/objects/${encodeURIComponent(wireObjectId)}`;
|
|
613
724
|
}
|
|
614
725
|
async request(build) {
|
|
615
726
|
let session = await this.sessionProvider.getSession();
|
|
616
727
|
let res = await this.send(build(), session);
|
|
617
728
|
if (res.status === 401) {
|
|
729
|
+
void res.body?.cancel().catch(() => {
|
|
730
|
+
});
|
|
618
731
|
session = await this.sessionProvider.getSession({ forceRefresh: true });
|
|
619
732
|
res = await this.send(build(), session);
|
|
620
733
|
if (res.status === 401) {
|
|
621
|
-
this.sessionProvider.onUnauthorized?.();
|
|
734
|
+
await this.sessionProvider.onUnauthorized?.();
|
|
622
735
|
throw new BucketTransportError("bucket session unauthorized", 401);
|
|
623
736
|
}
|
|
624
737
|
}
|
|
738
|
+
if (res.status === 403) {
|
|
739
|
+
const body = await res.clone().json().catch(() => null);
|
|
740
|
+
if (REVOKED_AUTHORIZATION_CODES.includes(body?.code || "")) {
|
|
741
|
+
await this.sessionProvider.onUnauthorized?.();
|
|
742
|
+
throw new BucketTransportError("bucket authorization revoked", 403);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
625
745
|
return res;
|
|
626
746
|
}
|
|
627
747
|
send(req, session) {
|
|
628
748
|
const headers = new Headers(req.init.headers);
|
|
629
749
|
headers.set("x-myfield-mfid", this.mfid);
|
|
630
750
|
if (session.carrier === "bearer") headers.set("Authorization", `Bearer ${session.token}`);
|
|
631
|
-
return fetch(req.url, {
|
|
751
|
+
return this.fetch(req.url, {
|
|
632
752
|
...req.init,
|
|
633
753
|
headers,
|
|
634
754
|
...session.carrier === "cookie" ? { credentials: "include" } : {}
|
|
635
755
|
});
|
|
636
756
|
}
|
|
637
757
|
};
|
|
758
|
+
var FEED_PAGE_LIMIT = 100;
|
|
759
|
+
var MAX_FEED_PAGES = 1e4;
|
|
760
|
+
function addHeads(heads, entries) {
|
|
761
|
+
for (const entry of entries) {
|
|
762
|
+
const row = entry;
|
|
763
|
+
if (typeof row?.objectId === "string" && typeof row.versionId === "string") heads.set(row.objectId, row.versionId);
|
|
764
|
+
}
|
|
765
|
+
}
|
|
638
766
|
async function readJsonObject(res, label) {
|
|
639
767
|
const contentType = res.headers.get("content-type") || "";
|
|
640
768
|
if (contentType && !contentType.toLowerCase().includes("application/json")) {
|
|
@@ -666,6 +794,8 @@ var BucketClient = class {
|
|
|
666
794
|
maxCasAttempts;
|
|
667
795
|
pushDebounceMs;
|
|
668
796
|
maxEncodedObjectBytes = DEFAULT_MAX_ENCODED_OBJECT_BYTES;
|
|
797
|
+
localOnly;
|
|
798
|
+
validateRemote;
|
|
669
799
|
onChange;
|
|
670
800
|
onSyncError;
|
|
671
801
|
clock = new LwwClock();
|
|
@@ -673,8 +803,11 @@ var BucketClient = class {
|
|
|
673
803
|
objectLocks = /* @__PURE__ */ new Map();
|
|
674
804
|
pendingPushTimers = /* @__PURE__ */ new Map();
|
|
675
805
|
watched = /* @__PURE__ */ new Set();
|
|
806
|
+
// Avoids re-downloading an unresolvable object until its head changes.
|
|
807
|
+
unresolved = /* @__PURE__ */ new Map();
|
|
676
808
|
triggerCleanup = null;
|
|
677
809
|
disposed = false;
|
|
810
|
+
autoSync;
|
|
678
811
|
constructor(options) {
|
|
679
812
|
this.transport = options.transport;
|
|
680
813
|
this.storage = options.storage;
|
|
@@ -684,8 +817,11 @@ var BucketClient = class {
|
|
|
684
817
|
this.mergeStrategyFor = options.mergeStrategyFor || (() => ({ kind: "lww-map" }));
|
|
685
818
|
this.maxCasAttempts = options.maxCasAttempts ?? DEFAULT_MAX_CAS_ATTEMPTS;
|
|
686
819
|
this.pushDebounceMs = options.pushDebounceMs ?? DEFAULT_PUSH_DEBOUNCE_MS;
|
|
820
|
+
this.localOnly = new Set(options.localOnlyObjectIds || []);
|
|
821
|
+
this.validateRemote = options.validateRemote;
|
|
687
822
|
this.onChange = options.onChange;
|
|
688
823
|
this.onSyncError = options.onSyncError;
|
|
824
|
+
this.autoSync = options.autoSync ?? true;
|
|
689
825
|
}
|
|
690
826
|
// ---- local reads -------------------------------------------------------
|
|
691
827
|
async getFields(appObjectId) {
|
|
@@ -698,6 +834,10 @@ var BucketClient = class {
|
|
|
698
834
|
if (!record || record.doc.t !== "opaque") return null;
|
|
699
835
|
return record.doc.data;
|
|
700
836
|
}
|
|
837
|
+
async lastModified(appObjectId) {
|
|
838
|
+
const record = await this.readRecord(appObjectId);
|
|
839
|
+
return record && record.doc.t === "lww-map" ? lwwMapLatestTs(record.doc) : null;
|
|
840
|
+
}
|
|
701
841
|
async knownObjectIds() {
|
|
702
842
|
const keys = await this.storage.keys(`${this.prefix}:obj:`);
|
|
703
843
|
return keys.map((key) => decodeURIComponent(key.slice(`${this.prefix}:obj:`.length)));
|
|
@@ -734,7 +874,7 @@ var BucketClient = class {
|
|
|
734
874
|
dirty: true
|
|
735
875
|
});
|
|
736
876
|
this.schedulePush(appObjectId);
|
|
737
|
-
this.onChange?.(appObjectId);
|
|
877
|
+
this.onChange?.(appObjectId, "local");
|
|
738
878
|
return lwwMapValues(nextDoc);
|
|
739
879
|
});
|
|
740
880
|
}
|
|
@@ -750,7 +890,7 @@ var BucketClient = class {
|
|
|
750
890
|
dirty: true
|
|
751
891
|
});
|
|
752
892
|
this.schedulePush(appObjectId);
|
|
753
|
-
this.onChange?.(appObjectId);
|
|
893
|
+
this.onChange?.(appObjectId, "local");
|
|
754
894
|
});
|
|
755
895
|
}
|
|
756
896
|
// ---- sync --------------------------------------------------------------
|
|
@@ -772,27 +912,46 @@ var BucketClient = class {
|
|
|
772
912
|
const ids = /* @__PURE__ */ new Set([...await this.knownObjectIds(), ...this.watched]);
|
|
773
913
|
await this.syncObjects(ids);
|
|
774
914
|
}
|
|
775
|
-
async
|
|
776
|
-
|
|
777
|
-
const
|
|
778
|
-
const
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
const
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
if (
|
|
789
|
-
|
|
915
|
+
async syncPass(options = {}) {
|
|
916
|
+
if (!this.transport.listHeads) throw new Error("transport does not list current heads");
|
|
917
|
+
const heads = await this.transport.listHeads();
|
|
918
|
+
for (const wireObjectId of options.skipWireIds || []) heads.delete(wireObjectId);
|
|
919
|
+
const known = /* @__PURE__ */ new Map();
|
|
920
|
+
const ids = new Set([...this.watched].filter((id) => !this.localOnly.has(id)));
|
|
921
|
+
for (const id of await this.knownObjectIds()) {
|
|
922
|
+
if (this.localOnly.has(id)) continue;
|
|
923
|
+
const record = await this.readRecord(id);
|
|
924
|
+
if (!record) continue;
|
|
925
|
+
const wireObjectId = await this.wireId(id);
|
|
926
|
+
known.set(wireObjectId, id);
|
|
927
|
+
const head = heads.get(wireObjectId);
|
|
928
|
+
if (record.dirty || head === void 0 || head !== record.remoteVersionId) ids.add(id);
|
|
929
|
+
}
|
|
930
|
+
for (const [wireObjectId, versionId] of heads) {
|
|
931
|
+
if (known.has(wireObjectId) || !options.resolveUnknown || this.unresolved.get(wireObjectId) === versionId) continue;
|
|
932
|
+
try {
|
|
933
|
+
const id = await options.resolveUnknown(wireObjectId, versionId);
|
|
934
|
+
if (id && !this.localOnly.has(id) && await this.wireId(id) === wireObjectId) {
|
|
935
|
+
this.unresolved.delete(wireObjectId);
|
|
936
|
+
ids.add(id);
|
|
937
|
+
} else {
|
|
938
|
+
this.unresolved.set(wireObjectId, versionId);
|
|
939
|
+
}
|
|
940
|
+
} catch (error) {
|
|
941
|
+
this.onSyncError?.(null, error);
|
|
790
942
|
}
|
|
791
943
|
}
|
|
792
|
-
const ids = /* @__PURE__ */ new Set([...this.watched, ...dirtyIdsBefore, ...changedIds]);
|
|
793
|
-
if (indexObjectId) ids.delete(indexObjectId);
|
|
794
944
|
await this.syncObjects(ids);
|
|
795
945
|
}
|
|
946
|
+
async pullDoc(wireObjectId, versionId) {
|
|
947
|
+
const payload = await this.transport.pullPayload(wireObjectId, versionId);
|
|
948
|
+
return payload.found ? decodePayloadDoc(payload.plaintext) : null;
|
|
949
|
+
}
|
|
950
|
+
async pullRemoteDoc(appObjectId) {
|
|
951
|
+
const wireObjectId = await this.wireId(appObjectId);
|
|
952
|
+
const head = await this.transport.pullHead(wireObjectId);
|
|
953
|
+
return head.found ? this.pullDoc(wireObjectId, head.versionId) : null;
|
|
954
|
+
}
|
|
796
955
|
watch(appObjectIds) {
|
|
797
956
|
for (const id of appObjectIds) this.watched.add(id);
|
|
798
957
|
}
|
|
@@ -801,8 +960,10 @@ var BucketClient = class {
|
|
|
801
960
|
// are scheduled by setFields/setData.
|
|
802
961
|
start(options) {
|
|
803
962
|
if (this.triggerCleanup || this.disposed) return;
|
|
804
|
-
|
|
805
|
-
const
|
|
963
|
+
this.autoSync = true;
|
|
964
|
+
const run = options.run;
|
|
965
|
+
const kick = () => void run().catch((error) => this.onSyncError?.(null, error));
|
|
966
|
+
const intervalMs = options.intervalMs ?? DEFAULT_SYNC_INTERVAL_MS;
|
|
806
967
|
const timer = intervalMs > 0 ? setInterval(kick, intervalMs) : null;
|
|
807
968
|
this.triggerCleanup = () => {
|
|
808
969
|
if (timer) clearInterval(timer);
|
|
@@ -810,6 +971,7 @@ var BucketClient = class {
|
|
|
810
971
|
kick();
|
|
811
972
|
}
|
|
812
973
|
stop() {
|
|
974
|
+
this.autoSync = false;
|
|
813
975
|
this.triggerCleanup?.();
|
|
814
976
|
this.triggerCleanup = null;
|
|
815
977
|
for (const timer of this.pendingPushTimers.values()) clearTimeout(timer);
|
|
@@ -832,7 +994,7 @@ var BucketClient = class {
|
|
|
832
994
|
}
|
|
833
995
|
// ---- internals ---------------------------------------------------------
|
|
834
996
|
schedulePush(appObjectId) {
|
|
835
|
-
if (this.disposed) return;
|
|
997
|
+
if (this.disposed || !this.autoSync || this.localOnly.has(appObjectId)) return;
|
|
836
998
|
const existing = this.pendingPushTimers.get(appObjectId);
|
|
837
999
|
if (existing) clearTimeout(existing);
|
|
838
1000
|
this.pendingPushTimers.set(
|
|
@@ -844,6 +1006,7 @@ var BucketClient = class {
|
|
|
844
1006
|
);
|
|
845
1007
|
}
|
|
846
1008
|
async performSync(appObjectId) {
|
|
1009
|
+
if (this.localOnly.has(appObjectId)) return false;
|
|
847
1010
|
const wireObjectId = await this.wireId(appObjectId);
|
|
848
1011
|
let remoteChangedLocal = false;
|
|
849
1012
|
for (let attempt = 0; attempt < this.maxCasAttempts; attempt += 1) {
|
|
@@ -863,6 +1026,7 @@ var BucketClient = class {
|
|
|
863
1026
|
const payload = await this.transport.pullPayload(wireObjectId, head.versionId);
|
|
864
1027
|
if (!payload.found) return "retry";
|
|
865
1028
|
const remoteDoc = decodePayloadDoc(payload.plaintext);
|
|
1029
|
+
this.validateRemote?.(appObjectId, remoteDoc);
|
|
866
1030
|
const merged = record ? this.merge(appObjectId, record.doc, remoteDoc) : remoteDoc;
|
|
867
1031
|
const localViewChanged = !record || !docsEqual(merged, record.doc);
|
|
868
1032
|
const remoteNeedsUpdate = !docsEqual(merged, remoteDoc);
|
|
@@ -871,7 +1035,7 @@ var BucketClient = class {
|
|
|
871
1035
|
await this.writeRecord(appObjectId, { v: 1, doc: merged, remoteVersionId: head.versionId, dirty: false });
|
|
872
1036
|
if (localViewChanged) {
|
|
873
1037
|
remoteChangedLocal = true;
|
|
874
|
-
this.onChange?.(appObjectId);
|
|
1038
|
+
this.onChange?.(appObjectId, "remote");
|
|
875
1039
|
}
|
|
876
1040
|
return remoteChangedLocal;
|
|
877
1041
|
}
|
|
@@ -880,7 +1044,7 @@ var BucketClient = class {
|
|
|
880
1044
|
await this.writeRecord(appObjectId, { v: 1, doc: merged, remoteVersionId: result.versionId, dirty: false });
|
|
881
1045
|
if (localViewChanged) {
|
|
882
1046
|
remoteChangedLocal = true;
|
|
883
|
-
this.onChange?.(appObjectId);
|
|
1047
|
+
this.onChange?.(appObjectId, "remote");
|
|
884
1048
|
}
|
|
885
1049
|
return remoteChangedLocal;
|
|
886
1050
|
}
|
|
@@ -905,15 +1069,12 @@ var BucketClient = class {
|
|
|
905
1069
|
async dirtyObjectIds() {
|
|
906
1070
|
const ids = [];
|
|
907
1071
|
for (const id of await this.knownObjectIds()) {
|
|
1072
|
+
if (this.localOnly.has(id)) continue;
|
|
908
1073
|
const record = await this.readRecord(id);
|
|
909
1074
|
if (record?.dirty) ids.push(id);
|
|
910
1075
|
}
|
|
911
1076
|
return ids;
|
|
912
1077
|
}
|
|
913
|
-
async indexFields(indexObjectId) {
|
|
914
|
-
const record = await this.readRecord(indexObjectId);
|
|
915
|
-
return record?.doc.t === "lww-map" ? lwwMapValues(record.doc) : {};
|
|
916
|
-
}
|
|
917
1078
|
async readRecord(appObjectId) {
|
|
918
1079
|
const record = await this.storage.get(this.recordKey(appObjectId));
|
|
919
1080
|
if (!record || record.v !== 1 || !record.doc) return null;
|
|
@@ -934,10 +1095,6 @@ function docsEqual(a, b) {
|
|
|
934
1095
|
if (a.t === "opaque" && b.t === "opaque") return JSON.stringify(a.data) === JSON.stringify(b.data);
|
|
935
1096
|
return false;
|
|
936
1097
|
}
|
|
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
1098
|
|
|
942
1099
|
// src/bucket/store.ts
|
|
943
1100
|
var memoryNamespaceRegistry = /* @__PURE__ */ new Map();
|
|
@@ -951,6 +1108,15 @@ function createNamespacedMemoryStorageAdapter(namespace) {
|
|
|
951
1108
|
}
|
|
952
1109
|
function memoryAdapterOver(map) {
|
|
953
1110
|
return {
|
|
1111
|
+
async removePrefix(prefix) {
|
|
1112
|
+
for (const key of map.keys()) if (key.startsWith(prefix)) map.delete(key);
|
|
1113
|
+
},
|
|
1114
|
+
async insertIfEmpty(prefix, entries) {
|
|
1115
|
+
if ([...map.keys()].some((key) => key.startsWith(prefix))) return false;
|
|
1116
|
+
const cloned = entries.map(({ key, value }) => ({ key, value: structuredClone(value) }));
|
|
1117
|
+
for (const { key, value } of cloned) map.set(key, value);
|
|
1118
|
+
return true;
|
|
1119
|
+
},
|
|
954
1120
|
async get(key) {
|
|
955
1121
|
return map.has(key) ? structuredClone(map.get(key)) : null;
|
|
956
1122
|
},
|
|
@@ -971,6 +1137,29 @@ function createIndexedDbStorageAdapter(options) {
|
|
|
971
1137
|
const dbName = options.dbName;
|
|
972
1138
|
const storeName = options.storeName || "kv";
|
|
973
1139
|
return {
|
|
1140
|
+
removePrefix: (prefix) => withIdb(dbName, storeName, (db) => new Promise((resolve, reject) => {
|
|
1141
|
+
const tx = db.transaction(storeName, "readwrite");
|
|
1142
|
+
tx.objectStore(storeName).delete(IDBKeyRange.bound(prefix, `${prefix}\uFFFF`));
|
|
1143
|
+
tx.oncomplete = () => resolve();
|
|
1144
|
+
tx.onabort = tx.onerror = () => reject(tx.error || new Error("Atomic removal failed"));
|
|
1145
|
+
})),
|
|
1146
|
+
insertIfEmpty: (prefix, entries) => withIdb(dbName, storeName, (db) => new Promise((resolve, reject) => {
|
|
1147
|
+
const tx = db.transaction(storeName, "readwrite"), store = tx.objectStore(storeName);
|
|
1148
|
+
let inserted = false;
|
|
1149
|
+
const count = store.count(IDBKeyRange.bound(prefix, `${prefix}\uFFFF`));
|
|
1150
|
+
count.onsuccess = () => {
|
|
1151
|
+
if (count.result) return;
|
|
1152
|
+
try {
|
|
1153
|
+
for (const { key, value } of entries) store.put(value, key);
|
|
1154
|
+
inserted = true;
|
|
1155
|
+
} catch (error) {
|
|
1156
|
+
tx.abort();
|
|
1157
|
+
reject(error);
|
|
1158
|
+
}
|
|
1159
|
+
};
|
|
1160
|
+
tx.oncomplete = () => resolve(inserted);
|
|
1161
|
+
tx.onabort = tx.onerror = () => reject(tx.error || new Error("Atomic write failed"));
|
|
1162
|
+
})),
|
|
974
1163
|
get: (key) => withIdb(
|
|
975
1164
|
dbName,
|
|
976
1165
|
storeName,
|
|
@@ -1078,6 +1267,305 @@ function openIdb(dbName, storeName) {
|
|
|
1078
1267
|
});
|
|
1079
1268
|
}
|
|
1080
1269
|
|
|
1270
|
+
// src/auth/identifiers.ts
|
|
1271
|
+
function isValidBucketId(value) {
|
|
1272
|
+
const safe = typeof value === "string" ? value.trim() : "";
|
|
1273
|
+
return /^[a-z0-9](?:[a-z0-9.-]{0,61}[a-z0-9])?$/.test(safe) && !safe.includes("..");
|
|
1274
|
+
}
|
|
1275
|
+
function requireValidBucketId(value) {
|
|
1276
|
+
if (!isValidBucketId(value)) throw new Error("invalid bucketId");
|
|
1277
|
+
return value;
|
|
1278
|
+
}
|
|
1279
|
+
function isValidInstanceId(value) {
|
|
1280
|
+
return typeof value === "string" && /^inst_[a-f0-9]{32}$/.test(value);
|
|
1281
|
+
}
|
|
1282
|
+
function isValidMfid(value) {
|
|
1283
|
+
return typeof value === "string" && /^[a-f0-9]{32}$/.test(value);
|
|
1284
|
+
}
|
|
1285
|
+
function isPublicP256EcJwk(value) {
|
|
1286
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1287
|
+
const jwk = value;
|
|
1288
|
+
return jwk.kty === "EC" && jwk.crv === "P-256" && typeof jwk.x === "string" && jwk.x.length > 0 && typeof jwk.y === "string" && jwk.y.length > 0;
|
|
1289
|
+
}
|
|
1290
|
+
function bucketResourceId(bucketId) {
|
|
1291
|
+
return `urn:myfield:bucket:${bucketId}`;
|
|
1292
|
+
}
|
|
1293
|
+
function parseBucketResourceId(resourceId) {
|
|
1294
|
+
const safe = typeof resourceId === "string" ? resourceId.trim() : "";
|
|
1295
|
+
const prefix = "urn:myfield:bucket:";
|
|
1296
|
+
if (!safe.startsWith(prefix)) return null;
|
|
1297
|
+
const bucketId = safe.slice(prefix.length);
|
|
1298
|
+
return isValidBucketId(bucketId) ? { resourceId: safe, bucketId } : null;
|
|
1299
|
+
}
|
|
1300
|
+
function resolveAppId(value) {
|
|
1301
|
+
const appId = value === void 0 ? typeof window === "undefined" ? "" : window.location.hostname : value;
|
|
1302
|
+
if (typeof appId !== "string" || appId !== appId.trim() || !isValidBucketId(appId) || !appId.split(".").every((label) => /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label))) {
|
|
1303
|
+
throw new ClientError("INVALID_INPUT", "appId must be a lowercase domain-form identifier of 1\u201363 characters");
|
|
1304
|
+
}
|
|
1305
|
+
return appId;
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
// src/auth/keys.ts
|
|
1309
|
+
async function createInstanceKey() {
|
|
1310
|
+
const signing = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]);
|
|
1311
|
+
const wrapping = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
|
|
1312
|
+
const signingPublicJwk = await crypto.subtle.exportKey("jwk", signing.publicKey);
|
|
1313
|
+
const wrappingPublicJwk = await crypto.subtle.exportKey("jwk", wrapping.publicKey);
|
|
1314
|
+
return {
|
|
1315
|
+
v: 1,
|
|
1316
|
+
instanceId: await deriveInstanceId(signingPublicJwk),
|
|
1317
|
+
signingPublicJwk,
|
|
1318
|
+
signingPrivateKey: signing.privateKey,
|
|
1319
|
+
wrappingPublicJwk,
|
|
1320
|
+
wrappingPrivateKey: wrapping.privateKey,
|
|
1321
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1322
|
+
};
|
|
1323
|
+
}
|
|
1324
|
+
async function deriveInstanceId(signingPublicJwk) {
|
|
1325
|
+
const core = {
|
|
1326
|
+
kty: String(signingPublicJwk.kty || ""),
|
|
1327
|
+
crv: String(signingPublicJwk.crv || ""),
|
|
1328
|
+
x: String(signingPublicJwk.x || ""),
|
|
1329
|
+
y: String(signingPublicJwk.y || "")
|
|
1330
|
+
};
|
|
1331
|
+
const digest = await sha256Hex(stableStringify(core));
|
|
1332
|
+
return `inst_${digest.slice(0, 32)}`;
|
|
1333
|
+
}
|
|
1334
|
+
function toInstanceKey(value) {
|
|
1335
|
+
return {
|
|
1336
|
+
instanceId: value.instanceId,
|
|
1337
|
+
signingPublicJwk: { ...value.signingPublicJwk },
|
|
1338
|
+
signingPrivateKey: value.signingPrivateKey,
|
|
1339
|
+
wrappingPublicJwk: { ...value.wrappingPublicJwk },
|
|
1340
|
+
wrappingPrivateKey: value.wrappingPrivateKey,
|
|
1341
|
+
createdAt: value.createdAt
|
|
1342
|
+
};
|
|
1343
|
+
}
|
|
1344
|
+
async function validateInstanceKey(value) {
|
|
1345
|
+
const invalid = (cause) => new ClientError("INVALID_INPUT", "Invalid instance key", { cause });
|
|
1346
|
+
try {
|
|
1347
|
+
if (!value || typeof value !== "object" || typeof value.createdAt !== "string" || !value.createdAt.endsWith("Z") || !Number.isFinite(Date.parse(value.createdAt))) throw invalid();
|
|
1348
|
+
value = { ...value, signingPublicJwk: { ...value.signingPublicJwk }, wrappingPublicJwk: { ...value.wrappingPublicJwk } };
|
|
1349
|
+
const { signingPrivateKey: sign, wrappingPrivateKey: wrap } = value;
|
|
1350
|
+
for (const [key, name, usage] of [[sign, "ECDSA", "sign"], [wrap, "ECDH", "deriveBits"]]) {
|
|
1351
|
+
if (!(key instanceof CryptoKey) || key.type !== "private" || key.extractable || key.algorithm.name !== name || key.algorithm.namedCurve !== "P-256" || !key.usages.includes(usage)) throw invalid();
|
|
1352
|
+
}
|
|
1353
|
+
if (value.instanceId !== await deriveInstanceId(value.signingPublicJwk)) throw invalid();
|
|
1354
|
+
const publicSign = await crypto.subtle.importKey("jwk", value.signingPublicJwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
|
|
1355
|
+
const challenge = crypto.getRandomValues(new Uint8Array(32));
|
|
1356
|
+
const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, sign, challenge);
|
|
1357
|
+
if (!await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, publicSign, signature, challenge)) throw invalid();
|
|
1358
|
+
const publicWrap = await crypto.subtle.importKey("jwk", value.wrappingPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
|
|
1359
|
+
const ephemeral = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
|
|
1360
|
+
const left = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeral.publicKey }, wrap, 256));
|
|
1361
|
+
const right = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: publicWrap }, ephemeral.privateKey, 256));
|
|
1362
|
+
if (!left.every((byte, i) => byte === right[i])) throw invalid();
|
|
1363
|
+
return {
|
|
1364
|
+
v: 1,
|
|
1365
|
+
instanceId: value.instanceId,
|
|
1366
|
+
signingPublicJwk: { ...value.signingPublicJwk },
|
|
1367
|
+
signingPrivateKey: sign,
|
|
1368
|
+
wrappingPublicJwk: { ...value.wrappingPublicJwk },
|
|
1369
|
+
wrappingPrivateKey: wrap,
|
|
1370
|
+
createdAt: value.createdAt
|
|
1371
|
+
};
|
|
1372
|
+
} catch (cause) {
|
|
1373
|
+
throw cause instanceof ClientError ? cause : invalid(cause);
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
// src/auth/store.ts
|
|
1378
|
+
function authRecordKeys(appId) {
|
|
1379
|
+
const prefix = `instance:${encodeURIComponent(appId)}:`;
|
|
1380
|
+
const segment2 = encodeURIComponent;
|
|
1381
|
+
return {
|
|
1382
|
+
prefix,
|
|
1383
|
+
active: `${prefix}active-instance:current`,
|
|
1384
|
+
keyPrefix: `${prefix}instance-key:`,
|
|
1385
|
+
key: (id) => `${prefix}instance-key:${segment2(id)}`,
|
|
1386
|
+
pending: (resource, id) => `${prefix}pending-auth:${segment2(resource)}:${segment2(id)}`,
|
|
1387
|
+
callback: (id) => `${prefix}callback-pointer:${segment2(id)}`,
|
|
1388
|
+
context: (resource, id) => `${prefix}context:${segment2(resource)}:${segment2(id)}`,
|
|
1389
|
+
session: (resource, id) => `${prefix}session:${segment2(resource)}:${segment2(id)}`,
|
|
1390
|
+
endpoints: (bucket) => `meta:${bucket}:endpoints`
|
|
1391
|
+
};
|
|
1392
|
+
}
|
|
1393
|
+
function createInstanceKeyStore(storage, appId) {
|
|
1394
|
+
const keys = authRecordKeys(appId);
|
|
1395
|
+
async function read(id) {
|
|
1396
|
+
const value = await storage.get(keys.key(id));
|
|
1397
|
+
if (!value) return null;
|
|
1398
|
+
if (value.v !== 1 || value.instanceId !== id || !isValidInstanceId(id) || !isPublicP256EcJwk(value.signingPublicJwk) || !isPublicP256EcJwk(value.wrappingPublicJwk) || !(value.signingPrivateKey instanceof CryptoKey) || !(value.wrappingPrivateKey instanceof CryptoKey)) {
|
|
1399
|
+
throw new ClientError("INVALID_INSTANCE_KEY", "Stored instance key is invalid");
|
|
1400
|
+
}
|
|
1401
|
+
return value;
|
|
1402
|
+
}
|
|
1403
|
+
async function active() {
|
|
1404
|
+
let pointer = await storage.get(keys.active);
|
|
1405
|
+
if (pointer === null) {
|
|
1406
|
+
if (!(await storage.keys(keys.keyPrefix)).length) return null;
|
|
1407
|
+
pointer = await storage.get(keys.active);
|
|
1408
|
+
if (pointer === null) throw new ClientError("INVALID_INSTANCE_KEY", "Instance key has no active pointer");
|
|
1409
|
+
}
|
|
1410
|
+
if (pointer.v !== 1 || !isValidInstanceId(pointer.instanceId)) throw new ClientError("INVALID_INSTANCE_KEY", "Stored instance pointer is invalid");
|
|
1411
|
+
const value = await read(pointer.instanceId);
|
|
1412
|
+
if (!value) throw new ClientError("INVALID_INSTANCE_KEY", "Stored instance key is missing");
|
|
1413
|
+
return value;
|
|
1414
|
+
}
|
|
1415
|
+
async function insert(instance) {
|
|
1416
|
+
if (await storage.get(keys.active) !== null) return false;
|
|
1417
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1418
|
+
const entries = [
|
|
1419
|
+
{ key: keys.key(instance.instanceId), value: { ...instance, updatedAt: now } },
|
|
1420
|
+
{ key: keys.active, value: { v: 1, instanceId: instance.instanceId, updatedAt: now } }
|
|
1421
|
+
];
|
|
1422
|
+
if (storage.insertIfEmpty) return storage.insertIfEmpty(keys.keyPrefix, entries);
|
|
1423
|
+
if ((await storage.keys(keys.keyPrefix)).length) return false;
|
|
1424
|
+
const written = [];
|
|
1425
|
+
try {
|
|
1426
|
+
for (const entry of entries) {
|
|
1427
|
+
await storage.set(entry.key, entry.value);
|
|
1428
|
+
written.push(entry.key);
|
|
1429
|
+
}
|
|
1430
|
+
} catch (error) {
|
|
1431
|
+
for (const key of written) await storage.remove(key);
|
|
1432
|
+
throw error;
|
|
1433
|
+
}
|
|
1434
|
+
return true;
|
|
1435
|
+
}
|
|
1436
|
+
let ensuring;
|
|
1437
|
+
async function save(instance) {
|
|
1438
|
+
if (!await insert(instance)) throw new ClientError("KEY_EXISTS", "An instance key already exists for this appId");
|
|
1439
|
+
}
|
|
1440
|
+
async function create(beforeWrite = () => {
|
|
1441
|
+
}) {
|
|
1442
|
+
const instance = await createInstanceKey();
|
|
1443
|
+
beforeWrite();
|
|
1444
|
+
await save(instance);
|
|
1445
|
+
return instance;
|
|
1446
|
+
}
|
|
1447
|
+
return {
|
|
1448
|
+
keys,
|
|
1449
|
+
read,
|
|
1450
|
+
active,
|
|
1451
|
+
import: save,
|
|
1452
|
+
create,
|
|
1453
|
+
async remove() {
|
|
1454
|
+
if (storage.removePrefix) return storage.removePrefix(keys.prefix);
|
|
1455
|
+
for (const key of await storage.keys(keys.prefix)) await storage.remove(key);
|
|
1456
|
+
},
|
|
1457
|
+
ensure() {
|
|
1458
|
+
return ensuring ??= (async () => {
|
|
1459
|
+
const saved = await active();
|
|
1460
|
+
if (saved) return saved;
|
|
1461
|
+
try {
|
|
1462
|
+
await create();
|
|
1463
|
+
} catch (error) {
|
|
1464
|
+
if (!(error instanceof ClientError) || error.code !== "KEY_EXISTS") throw error;
|
|
1465
|
+
}
|
|
1466
|
+
const value = await active();
|
|
1467
|
+
if (!value) throw new ClientError("INVALID_INSTANCE_KEY", "Instance key was not saved");
|
|
1468
|
+
return value;
|
|
1469
|
+
})().finally(() => {
|
|
1470
|
+
ensuring = void 0;
|
|
1471
|
+
});
|
|
1472
|
+
}
|
|
1473
|
+
};
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
// src/auth/flow.ts
|
|
1477
|
+
var notAuthorized = (message, cause) => new ClientError("NOT_AUTHORIZED", message, { cause });
|
|
1478
|
+
function createAuthorizationFlow(deps) {
|
|
1479
|
+
const getBucketId = deps.getBucketId ?? deps.getAppId;
|
|
1480
|
+
let closeAuthorization = () => {
|
|
1481
|
+
};
|
|
1482
|
+
async function ownCallback(url, storage) {
|
|
1483
|
+
const resourceId = bucketResourceId(getBucketId());
|
|
1484
|
+
const requestId = url.searchParams.get("mf_request_id");
|
|
1485
|
+
if (!requestId) return false;
|
|
1486
|
+
const keys = authRecordKeys(deps.getAppId());
|
|
1487
|
+
const pointer = await storage.get(keys.callback(requestId));
|
|
1488
|
+
if (pointer?.resourceId !== resourceId || pointer.requestId !== requestId) return false;
|
|
1489
|
+
const pending = await storage.get(pointer.pendingKey);
|
|
1490
|
+
if (pending && pending.resourceId !== resourceId) return false;
|
|
1491
|
+
return true;
|
|
1492
|
+
}
|
|
1493
|
+
function clearCallbackUrl(url) {
|
|
1494
|
+
const current = new URL(window.location.href);
|
|
1495
|
+
if (current.searchParams.get("mf_request_id") !== url.searchParams.get("mf_request_id")) return;
|
|
1496
|
+
for (const key of ["state", "error", "error_description", "error_uri", "mf_request_id", "mf_result"]) current.searchParams.delete(key);
|
|
1497
|
+
const hash = new URLSearchParams(current.hash.slice(1));
|
|
1498
|
+
if (hash.has("mf_auth_result")) {
|
|
1499
|
+
hash.delete("mf_auth_result");
|
|
1500
|
+
current.hash = hash.toString();
|
|
1501
|
+
}
|
|
1502
|
+
window.history.replaceState(null, "", current.href);
|
|
1503
|
+
}
|
|
1504
|
+
async function handleCallback(auth, url, signal, addressBar) {
|
|
1505
|
+
try {
|
|
1506
|
+
const result = await auth.handleCallback(url.href);
|
|
1507
|
+
signal.throwIfAborted();
|
|
1508
|
+
if (result?.result !== "approved") throw notAuthorized(result?.errorDescription || result?.result || "Invalid authorization callback");
|
|
1509
|
+
} catch (error) {
|
|
1510
|
+
signal.throwIfAborted();
|
|
1511
|
+
if (error instanceof ClientError && error.code === "NOT_AUTHORIZED") throw error;
|
|
1512
|
+
throw notAuthorized("Invalid authorization callback", error);
|
|
1513
|
+
} finally {
|
|
1514
|
+
if (addressBar) clearCallbackUrl(url);
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
function requestAuthorization(auth, storage, url, signal, setPopup) {
|
|
1518
|
+
signal.throwIfAborted();
|
|
1519
|
+
const ios = typeof navigator !== "undefined" && (/iPad|iPhone|iPod/.test(navigator.userAgent) || navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
|
|
1520
|
+
const popup = ios ? null : window.open("about:blank", `myfield-sdk-auth:${getBucketId()}`, "popup=yes,width=520,height=720");
|
|
1521
|
+
if (!popup && deps.persistent === false) throw new ClientError("INVALID_STATE", "Redirect authorization requires persistent storage");
|
|
1522
|
+
setPopup(popup);
|
|
1523
|
+
return new Promise((resolve, reject) => {
|
|
1524
|
+
let processing = false;
|
|
1525
|
+
let settled = false;
|
|
1526
|
+
let timer;
|
|
1527
|
+
const finish = (error) => {
|
|
1528
|
+
if (settled) return;
|
|
1529
|
+
settled = true;
|
|
1530
|
+
if (timer) clearInterval(timer);
|
|
1531
|
+
window.removeEventListener("message", onMessage);
|
|
1532
|
+
signal.removeEventListener("abort", onAbort);
|
|
1533
|
+
popup?.close();
|
|
1534
|
+
closeAuthorization = () => {
|
|
1535
|
+
};
|
|
1536
|
+
if (error) reject(error);
|
|
1537
|
+
else resolve();
|
|
1538
|
+
};
|
|
1539
|
+
const onAbort = () => finish(signal.reason);
|
|
1540
|
+
const onMessage = (event) => {
|
|
1541
|
+
if (!popup || event.source !== popup || ![new URL(url).origin, window.location.origin].includes(event.origin)) return;
|
|
1542
|
+
const message = event.data;
|
|
1543
|
+
if (!message || message.type !== "myfield.auth.callback" || typeof message.callbackUrl !== "string") return;
|
|
1544
|
+
void (async () => {
|
|
1545
|
+
let callbackUrl;
|
|
1546
|
+
try {
|
|
1547
|
+
callbackUrl = new URL(message.callbackUrl);
|
|
1548
|
+
} catch {
|
|
1549
|
+
return;
|
|
1550
|
+
}
|
|
1551
|
+
if (!await ownCallback(callbackUrl, storage) || processing || settled) return;
|
|
1552
|
+
processing = true;
|
|
1553
|
+
await handleCallback(auth, callbackUrl, signal, false);
|
|
1554
|
+
finish();
|
|
1555
|
+
})().catch(finish);
|
|
1556
|
+
};
|
|
1557
|
+
window.addEventListener("message", onMessage);
|
|
1558
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1559
|
+
closeAuthorization = onAbort;
|
|
1560
|
+
if (popup) timer = setInterval(() => {
|
|
1561
|
+
if (popup.closed && !processing) finish(notAuthorized("Authorization window closed"));
|
|
1562
|
+
}, 250);
|
|
1563
|
+
void auth.authorize({ bucketId: getBucketId() }).catch(finish);
|
|
1564
|
+
});
|
|
1565
|
+
}
|
|
1566
|
+
return { ownCallback, handleCallback, requestAuthorization, close: () => closeAuthorization() };
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1081
1569
|
// src/bucket/keys.ts
|
|
1082
1570
|
var ID_BLINDING_SALT = "myfield.sdk.v1";
|
|
1083
1571
|
var ID_BLINDING_INFO_PREFIX = "object-id|";
|
|
@@ -1142,123 +1630,239 @@ async function unwrapBucketKeys(envelope, instanceWrappingPrivateKey) {
|
|
|
1142
1630
|
}
|
|
1143
1631
|
}
|
|
1144
1632
|
|
|
1145
|
-
// src/auth/
|
|
1146
|
-
var AUTH_REQUEST_TTL_MS = 10 * 60 * 1e3;
|
|
1633
|
+
// src/auth/authorization.ts
|
|
1147
1634
|
var AUTH_CALLBACK_FRAGMENT_PARAM = "mf_auth_result";
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
}
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
};
|
|
1183
|
-
await storage.set(instanceKey(authInstance.instanceId), stored);
|
|
1184
|
-
const verified = await readStoredInstance(authInstance.instanceId);
|
|
1185
|
-
if (!verified) throw new Error("auth instance write did not persist keys");
|
|
1186
|
-
await storage.set(activeInstanceKey(), { v: 1, instanceId: authInstance.instanceId, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
1187
|
-
instance = verified;
|
|
1188
|
-
return verified;
|
|
1189
|
-
}
|
|
1190
|
-
async function readActiveStoredInstance() {
|
|
1191
|
-
const active = await storage.get(activeInstanceKey());
|
|
1192
|
-
if (!active || active.v !== 1 || !isValidInstanceId(active.instanceId)) return null;
|
|
1193
|
-
return readStoredInstance(active.instanceId);
|
|
1194
|
-
}
|
|
1195
|
-
async function ensureStoredInstance() {
|
|
1196
|
-
if (instance) {
|
|
1197
|
-
const stored = await readStoredInstance(instance.instanceId);
|
|
1198
|
-
if (stored) return stored;
|
|
1199
|
-
return writeStoredInstance(instance);
|
|
1200
|
-
}
|
|
1201
|
-
const active = await readActiveStoredInstance();
|
|
1202
|
-
if (active) {
|
|
1203
|
-
instance = active;
|
|
1204
|
-
return active;
|
|
1205
|
-
}
|
|
1206
|
-
return writeStoredInstance(await generateAuthInstance());
|
|
1635
|
+
function buildAuthRequestFragment(request) {
|
|
1636
|
+
if (!request.requestId || !request.state) throw new Error("auth request state required");
|
|
1637
|
+
if (!isValidInstanceId(request.instanceId)) throw new Error("invalid instanceId");
|
|
1638
|
+
if (!isPublicP256EcJwk(request.instanceSigningPublicJwk)) throw new Error("instanceSigningPublicJwk required");
|
|
1639
|
+
if (!isPublicP256EcJwk(request.instanceWrappingPublicJwk)) throw new Error("instanceWrappingPublicJwk required");
|
|
1640
|
+
const redirect = new URL(request.redirectUri);
|
|
1641
|
+
const origin = new URL(request.origin);
|
|
1642
|
+
if (redirect.origin !== origin.origin) throw new Error("redirectUri origin mismatch");
|
|
1643
|
+
const wire = {
|
|
1644
|
+
response_type: "code",
|
|
1645
|
+
client_id: request.clientId,
|
|
1646
|
+
redirect_uri: request.redirectUri,
|
|
1647
|
+
state: request.state,
|
|
1648
|
+
scope: request.capabilities.join(" "),
|
|
1649
|
+
resource_id: request.resourceId,
|
|
1650
|
+
mf_v: 1,
|
|
1651
|
+
mf_auth_mode: "v1",
|
|
1652
|
+
mf_request_id: request.requestId,
|
|
1653
|
+
mf_instance_id: request.instanceId,
|
|
1654
|
+
mf_instance_signing_jwk: request.instanceSigningPublicJwk,
|
|
1655
|
+
mf_instance_wrapping_jwk: request.instanceWrappingPublicJwk,
|
|
1656
|
+
mf_issued_at: request.createdAt
|
|
1657
|
+
};
|
|
1658
|
+
return `#authRequest=${bytesToB64url(utf8Encode(stableStringify(wire)))}`;
|
|
1659
|
+
}
|
|
1660
|
+
function parseEncryptedAuthAuthorizationResultFragment(fragmentOrUrl) {
|
|
1661
|
+
const input = String(fragmentOrUrl || "");
|
|
1662
|
+
const rawFragment = input.includes("#") ? input.slice(input.indexOf("#") + 1) : input.replace(/^#/, "");
|
|
1663
|
+
if (!rawFragment) return null;
|
|
1664
|
+
const encoded = new URLSearchParams(rawFragment).get(AUTH_CALLBACK_FRAGMENT_PARAM);
|
|
1665
|
+
if (!encoded) return null;
|
|
1666
|
+
const envelope = JSON.parse(new TextDecoder().decode(b64urlToBytes(encoded)));
|
|
1667
|
+
if (!envelope || envelope.v !== 1 || envelope.typ !== "auth.authorization-result.envelope.v1" || envelope.alg !== "ECDH-HKDF-SHA-256/AES-GCM-256" || typeof envelope.requestId !== "string" || typeof envelope.state !== "string" || !parseBucketResourceId(envelope.resourceId) || !isValidInstanceId(envelope.instanceId || "") || !isPublicP256EcJwk(envelope.ephemeralPublicJwk) || typeof envelope.salt !== "string" || typeof envelope.iv !== "string" || typeof envelope.aad !== "string" || typeof envelope.ciphertext !== "string") {
|
|
1668
|
+
throw new Error("auth callback result fragment invalid");
|
|
1207
1669
|
}
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
return null;
|
|
1215
|
-
}
|
|
1216
|
-
mfid = context.mfid;
|
|
1217
|
-
currentResourceId = context.resourceId;
|
|
1218
|
-
instance = authInstance;
|
|
1219
|
-
return context;
|
|
1670
|
+
return envelope;
|
|
1671
|
+
}
|
|
1672
|
+
async function decryptEncryptedAuthAuthorizationResult(input) {
|
|
1673
|
+
const { envelope } = input;
|
|
1674
|
+
if (input.expectedRequestId && envelope.requestId !== input.expectedRequestId || input.expectedState && envelope.state !== input.expectedState || input.expectedResourceId && envelope.resourceId !== input.expectedResourceId || input.expectedInstanceId && envelope.instanceId !== input.expectedInstanceId) {
|
|
1675
|
+
throw new Error("auth callback result mismatch");
|
|
1220
1676
|
}
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1677
|
+
const ephemeralPublic = await crypto.subtle.importKey("jwk", envelope.ephemeralPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
|
|
1678
|
+
const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, input.instanceWrappingPrivateKey, 256);
|
|
1679
|
+
const material = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveKey"]);
|
|
1680
|
+
const wrappingKey = await crypto.subtle.deriveKey(
|
|
1681
|
+
{ name: "HKDF", hash: "SHA-256", salt: b64urlToBytes(envelope.salt), info: utf8Encode(envelope.aad) },
|
|
1682
|
+
material,
|
|
1683
|
+
{ name: "AES-GCM", length: 256 },
|
|
1684
|
+
false,
|
|
1685
|
+
["decrypt"]
|
|
1686
|
+
);
|
|
1687
|
+
const plaintext = await crypto.subtle.decrypt(
|
|
1688
|
+
{ name: "AES-GCM", iv: b64urlToBytes(envelope.iv), additionalData: utf8Encode(envelope.aad) },
|
|
1689
|
+
wrappingKey,
|
|
1690
|
+
b64urlToBytes(envelope.ciphertext)
|
|
1691
|
+
);
|
|
1692
|
+
const result = normalizeAuthAuthorizationResult(JSON.parse(new TextDecoder().decode(plaintext)), envelope.requestId);
|
|
1693
|
+
if (!result || result.state !== envelope.state || result.resourceId !== envelope.resourceId || result.instanceId !== envelope.instanceId || input.expectedState && result.state !== input.expectedState || input.expectedResourceId && result.resourceId !== input.expectedResourceId || input.expectedInstanceId && result.instanceId !== input.expectedInstanceId) {
|
|
1694
|
+
throw new Error("auth callback result mismatch");
|
|
1695
|
+
}
|
|
1696
|
+
return result;
|
|
1697
|
+
}
|
|
1698
|
+
function normalizeAuthAuthorizationResult(value, expectedRequestId) {
|
|
1699
|
+
const row = value;
|
|
1700
|
+
if (!row || row.v !== 1 || row.result !== "approved" || typeof row.requestId !== "string" || expectedRequestId && row.requestId !== expectedRequestId || typeof row.state !== "string" || !isValidMfid(row.mfid || "") || !parseBucketResourceId(row.resourceId) || !isValidInstanceId(row.instanceId || "") || typeof row.createdAt !== "string") {
|
|
1701
|
+
return null;
|
|
1702
|
+
}
|
|
1703
|
+
if (row.expiresAt !== void 0) {
|
|
1704
|
+
const expiresAt = Date.parse(String(row.expiresAt));
|
|
1705
|
+
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return null;
|
|
1706
|
+
}
|
|
1707
|
+
const resource = parseBucketResourceId(row.resourceId);
|
|
1708
|
+
if (!resource) return null;
|
|
1709
|
+
const bucketAccessGrant = normalizeBucketAccessGrant(row.bucketAccessGrant);
|
|
1710
|
+
if (!bucketAccessGrant) return null;
|
|
1711
|
+
if (bucketAccessGrant.mfid !== row.mfid || !parseBucketResourceId(bucketAccessGrant.resourceId) || bucketAccessGrant.instanceId !== row.instanceId) {
|
|
1712
|
+
return null;
|
|
1713
|
+
}
|
|
1714
|
+
return {
|
|
1715
|
+
v: 1,
|
|
1716
|
+
requestId: row.requestId,
|
|
1717
|
+
state: row.state,
|
|
1718
|
+
result: "approved",
|
|
1719
|
+
mfid: row.mfid,
|
|
1720
|
+
resourceId: resource.resourceId,
|
|
1721
|
+
instanceId: row.instanceId,
|
|
1722
|
+
createdAt: row.createdAt,
|
|
1723
|
+
...typeof row.resourceApiUrl === "string" && row.resourceApiUrl.trim() ? { resourceApiUrl: row.resourceApiUrl.trim() } : {},
|
|
1724
|
+
bucketAccessGrant,
|
|
1725
|
+
...row.expiresAt ? { expiresAt: row.expiresAt } : {}
|
|
1726
|
+
};
|
|
1727
|
+
}
|
|
1728
|
+
function normalizeBucketAccessGrant(value) {
|
|
1729
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
1730
|
+
const row = value;
|
|
1731
|
+
const resource = parseBucketResourceId(row.resourceId);
|
|
1732
|
+
const capabilities = normalizeCapabilities(row.capabilities);
|
|
1733
|
+
if (row.v !== 1 || !/^ar_[a-f0-9]{32}$/.test(String(row.grantRecordId || "")) || !isValidMfid(row.mfid) || !resource || !isValidInstanceId(row.instanceId) || !/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) || capabilities.length < 1 || !isValidBucketKeyGrantEnvelope(row.envelope, row.instanceId, row.keyId)) {
|
|
1734
|
+
return null;
|
|
1735
|
+
}
|
|
1736
|
+
return {
|
|
1737
|
+
v: 1,
|
|
1738
|
+
grantRecordId: row.grantRecordId,
|
|
1739
|
+
mfid: row.mfid,
|
|
1740
|
+
resourceId: resource.resourceId,
|
|
1741
|
+
instanceId: row.instanceId,
|
|
1742
|
+
issuedAt: String(row.issuedAt || ""),
|
|
1743
|
+
keyId: row.keyId,
|
|
1744
|
+
capabilities,
|
|
1745
|
+
envelope: row.envelope
|
|
1746
|
+
};
|
|
1747
|
+
}
|
|
1748
|
+
function isValidBucketKeyGrantEnvelope(value, instanceId, keyId) {
|
|
1749
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1750
|
+
const row = value;
|
|
1751
|
+
if (row.kind !== "bucket-key" || !isValidBucketId(row.bucketId) || !/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) || !isValidInstanceId(row.targetInstanceId) || row.wrapAlg !== "ECDH-HKDF-SHA-256/AES-GCM-256" || !isPublicP256EcJwk(row.targetWrappingPublicJwk) || !isPublicP256EcJwk(row.ephemeralPublicJwk) || typeof row.salt !== "string" || typeof row.iv !== "string" || typeof row.aad !== "string" || typeof row.ciphertext !== "string") {
|
|
1752
|
+
return false;
|
|
1753
|
+
}
|
|
1754
|
+
if (instanceId && row.targetInstanceId !== instanceId) return false;
|
|
1755
|
+
if (keyId && row.keyId !== keyId) return false;
|
|
1756
|
+
return true;
|
|
1757
|
+
}
|
|
1758
|
+
function normalizeCapabilities(input) {
|
|
1759
|
+
if (!Array.isArray(input)) return [];
|
|
1760
|
+
const allowed = /* @__PURE__ */ new Set(["read", "write"]);
|
|
1761
|
+
const result = [];
|
|
1762
|
+
for (const item of input) {
|
|
1763
|
+
if (allowed.has(item) && !result.includes(item)) result.push(item);
|
|
1764
|
+
}
|
|
1765
|
+
return result.sort();
|
|
1766
|
+
}
|
|
1767
|
+
|
|
1768
|
+
// src/remote/session.ts
|
|
1769
|
+
function createSessionClient(postJson2) {
|
|
1770
|
+
return {
|
|
1771
|
+
createChallenge(identity) {
|
|
1772
|
+
return postJson2("/v1/api/auth/instance-challenge", identity);
|
|
1773
|
+
},
|
|
1774
|
+
async createSession(input) {
|
|
1775
|
+
const session = await postJson2("/v1/api/auth/instance-session", {
|
|
1776
|
+
...input,
|
|
1777
|
+
credentialCarrier: "bearer"
|
|
1778
|
+
});
|
|
1779
|
+
return session.credential;
|
|
1780
|
+
}
|
|
1781
|
+
};
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
// src/auth/proof.ts
|
|
1785
|
+
async function signInstanceChallenge(input) {
|
|
1786
|
+
const signedAt = normalizeIsoDateTime(input.signedAt) || (/* @__PURE__ */ new Date()).toISOString();
|
|
1787
|
+
const payload = stableStringify({
|
|
1788
|
+
v: 1,
|
|
1789
|
+
type: "instance-proof",
|
|
1790
|
+
instanceId: input.instance.instanceId,
|
|
1791
|
+
challenge: input.challenge,
|
|
1792
|
+
challengeId: input.challengeId || "",
|
|
1793
|
+
mfid: input.mfid,
|
|
1794
|
+
resourceId: input.resourceId,
|
|
1795
|
+
signedAt
|
|
1796
|
+
});
|
|
1797
|
+
const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, input.instance.signingPrivateKey, utf8Encode(payload));
|
|
1798
|
+
return { type: "instance.es256", instanceId: input.instance.instanceId, alg: "ES256", signedAt, signature: bytesToB64url(new Uint8Array(signature)) };
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
// src/auth/session.ts
|
|
1802
|
+
async function createSession(input, client) {
|
|
1803
|
+
const { instance, mfid, resourceId } = input;
|
|
1804
|
+
const identity = { mfid, resourceId, instanceId: instance.instanceId };
|
|
1805
|
+
const challenge = await client.createChallenge(identity);
|
|
1806
|
+
const proof = await signInstanceChallenge({ instance, mfid, resourceId, challengeId: challenge.challengeId, challenge: challenge.challenge });
|
|
1807
|
+
return client.createSession({ ...identity, challengeId: challenge.challengeId, proof });
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
// src/auth/instance.ts
|
|
1811
|
+
var AUTH_REQUEST_TTL_MS = 10 * 60 * 1e3;
|
|
1812
|
+
var DEFAULT_AUTH_IDB_NAME = "mf-sdk-auth-v1";
|
|
1813
|
+
var BUCKET_ACCESS_CACHE_TTL_MS = 6e4;
|
|
1814
|
+
var INSTANCE_SESSION_USABLE_WINDOW_MS = 2 * 60 * 1e3;
|
|
1815
|
+
var INSTANCE_SESSION_BEST_EFFORT_REFRESH_WINDOW_MS = 60 * 60 * 1e3;
|
|
1816
|
+
var FIXED_CAPABILITIES = ["read", "write"];
|
|
1817
|
+
function createInstanceAuthClient(options = {}) {
|
|
1818
|
+
const appId = resolveAppId(options.appId);
|
|
1819
|
+
let mfid = "";
|
|
1820
|
+
let currentResourceId = "";
|
|
1821
|
+
let currentSession = null;
|
|
1822
|
+
const inFlightSessionRefreshes = /* @__PURE__ */ new Map();
|
|
1823
|
+
const storage = options.storage || createIndexedDbStorageAdapter({ dbName: DEFAULT_AUTH_IDB_NAME, storeName: "instance" });
|
|
1824
|
+
const fetchImpl = options.fetchImpl || fetch;
|
|
1825
|
+
const sessions = createSessionClient((path, body) => postJson(fetchImpl, options.apiBase, path, body));
|
|
1826
|
+
const bucketAccessCache = /* @__PURE__ */ new Map();
|
|
1827
|
+
const keyStore = createInstanceKeyStore(storage, appId);
|
|
1828
|
+
const { pending: pendingAuthKey, callback: callbackPointerKey, context: contextKey, session: sessionKey } = keyStore.keys;
|
|
1829
|
+
const readStoredInstance = keyStore.read;
|
|
1830
|
+
const readActiveStoredInstance = keyStore.active;
|
|
1831
|
+
const ensureStoredInstance = keyStore.ensure;
|
|
1832
|
+
async function readContext(resourceId) {
|
|
1833
|
+
if (!parseBucketResourceId(resourceId)) return null;
|
|
1834
|
+
const authInstance = await readActiveStoredInstance();
|
|
1835
|
+
if (!authInstance) return null;
|
|
1836
|
+
const context = await storage.get(contextKey(resourceId, authInstance.instanceId));
|
|
1837
|
+
if (!context || context.v !== 1 || !isValidMfid(context.mfid) || context.resourceId !== resourceId || context.remoteResourceId !== void 0 && !parseBucketResourceId(context.remoteResourceId) || context.instanceId !== authInstance.instanceId) {
|
|
1838
|
+
return null;
|
|
1839
|
+
}
|
|
1840
|
+
mfid = context.mfid;
|
|
1841
|
+
currentResourceId = context.resourceId;
|
|
1842
|
+
return context;
|
|
1843
|
+
}
|
|
1844
|
+
async function getSessionForResource(resourceId, sessionOptions) {
|
|
1845
|
+
const context = await readContext(resourceId);
|
|
1846
|
+
if (!mfid || !context) throw new Error("not authorized; complete an auth callback first");
|
|
1847
|
+
const authInstance = await ensureStoredInstance();
|
|
1848
|
+
if (authInstance.instanceId !== context.instanceId) throw new Error("stored instance does not match authorization context");
|
|
1849
|
+
const sessionResourceId = context.remoteResourceId || context.resourceId;
|
|
1850
|
+
const forceRefresh = sessionOptions?.forceRefresh === true;
|
|
1851
|
+
const refreshSessionKey = `${sessionResourceId}:${authInstance.instanceId}`;
|
|
1852
|
+
const performRefreshSession = async () => {
|
|
1853
|
+
const credential = await createSession({ instance: authInstance, mfid, resourceId: sessionResourceId }, sessions);
|
|
1854
|
+
currentSession = { resourceId: sessionResourceId, credential };
|
|
1855
|
+
if (credential.carrier === "bearer") {
|
|
1856
|
+
await storage.set(sessionKey(sessionResourceId, context.instanceId), {
|
|
1857
|
+
v: 1,
|
|
1858
|
+
mfid,
|
|
1859
|
+
resourceId: sessionResourceId,
|
|
1860
|
+
instanceId: authInstance.instanceId,
|
|
1861
|
+
credential,
|
|
1862
|
+
storedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1863
|
+
});
|
|
1864
|
+
}
|
|
1865
|
+
return credential;
|
|
1262
1866
|
};
|
|
1263
1867
|
const refreshSession = () => {
|
|
1264
1868
|
const inFlight = inFlightSessionRefreshes.get(refreshSessionKey);
|
|
@@ -1385,6 +1989,9 @@ function createInstanceAuthClient(options = {}) {
|
|
|
1385
1989
|
const remoteResourceId = stored.bucketAccessGrant?.resourceId || stored.resourceId;
|
|
1386
1990
|
mfid = stored.mfid;
|
|
1387
1991
|
currentResourceId = stored.resourceId;
|
|
1992
|
+
if ((await readActiveStoredInstance())?.instanceId !== authInstance.instanceId) {
|
|
1993
|
+
throw new ClientError("IDENTITY_MISMATCH", "Active instance changed during authorization");
|
|
1994
|
+
}
|
|
1388
1995
|
await storage.set(contextKey(stored.resourceId, stored.instanceId), {
|
|
1389
1996
|
v: 1,
|
|
1390
1997
|
mfid: stored.mfid,
|
|
@@ -1396,7 +2003,6 @@ function createInstanceAuthClient(options = {}) {
|
|
|
1396
2003
|
authorizedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1397
2004
|
...stored.bucketAccessGrant ? { bucketAccessGrant: stored.bucketAccessGrant } : {}
|
|
1398
2005
|
});
|
|
1399
|
-
await writeStoredInstance(authInstance);
|
|
1400
2006
|
if (currentSession?.resourceId === remoteResourceId) currentSession = null;
|
|
1401
2007
|
await storage.remove(sessionKey(remoteResourceId, stored.instanceId));
|
|
1402
2008
|
bucketAccessCache.clear();
|
|
@@ -1452,182 +2058,6 @@ function createInstanceAuthClient(options = {}) {
|
|
|
1452
2058
|
}
|
|
1453
2059
|
};
|
|
1454
2060
|
}
|
|
1455
|
-
async function generateAuthInstance() {
|
|
1456
|
-
const signing = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]);
|
|
1457
|
-
const wrapping = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
|
|
1458
|
-
const signingPublicJwk = await crypto.subtle.exportKey("jwk", signing.publicKey);
|
|
1459
|
-
const wrappingPublicJwk = await crypto.subtle.exportKey("jwk", wrapping.publicKey);
|
|
1460
|
-
return {
|
|
1461
|
-
v: 1,
|
|
1462
|
-
instanceId: await deriveInstanceId(signingPublicJwk),
|
|
1463
|
-
signingPublicJwk,
|
|
1464
|
-
signingPrivateKey: signing.privateKey,
|
|
1465
|
-
wrappingPublicJwk,
|
|
1466
|
-
wrappingPrivateKey: wrapping.privateKey,
|
|
1467
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1468
|
-
};
|
|
1469
|
-
}
|
|
1470
|
-
async function deriveInstanceId(signingPublicJwk) {
|
|
1471
|
-
const digest = await sha256Hex(stableStringify(jwkCore(signingPublicJwk)));
|
|
1472
|
-
return `inst_${digest.slice(0, 32)}`;
|
|
1473
|
-
}
|
|
1474
|
-
async function signInstanceChallenge(input) {
|
|
1475
|
-
const signedAt = normalizeIsoDateTime(input.signedAt) || (/* @__PURE__ */ new Date()).toISOString();
|
|
1476
|
-
const payload = stableStringify({
|
|
1477
|
-
v: 1,
|
|
1478
|
-
type: "instance-proof",
|
|
1479
|
-
instanceId: input.instance.instanceId,
|
|
1480
|
-
challenge: input.challenge,
|
|
1481
|
-
challengeId: input.challengeId || "",
|
|
1482
|
-
mfid: input.mfid,
|
|
1483
|
-
resourceId: input.resourceId,
|
|
1484
|
-
signedAt
|
|
1485
|
-
});
|
|
1486
|
-
const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, input.instance.signingPrivateKey, utf8Encode(payload));
|
|
1487
|
-
return { type: "instance.es256", instanceId: input.instance.instanceId, alg: "ES256", signedAt, signature: bytesToB64url(new Uint8Array(signature)) };
|
|
1488
|
-
}
|
|
1489
|
-
function buildAuthRequestFragment(request) {
|
|
1490
|
-
if (!request.requestId || !request.state) throw new Error("auth request state required");
|
|
1491
|
-
if (!isValidInstanceId(request.instanceId)) throw new Error("invalid instanceId");
|
|
1492
|
-
if (!isPublicP256EcJwk(request.instanceSigningPublicJwk)) throw new Error("instanceSigningPublicJwk required");
|
|
1493
|
-
if (!isPublicP256EcJwk(request.instanceWrappingPublicJwk)) throw new Error("instanceWrappingPublicJwk required");
|
|
1494
|
-
const redirect = new URL(request.redirectUri);
|
|
1495
|
-
const origin = new URL(request.origin);
|
|
1496
|
-
if (redirect.origin !== origin.origin) throw new Error("redirectUri origin mismatch");
|
|
1497
|
-
const wire = {
|
|
1498
|
-
response_type: "code",
|
|
1499
|
-
client_id: request.clientId,
|
|
1500
|
-
redirect_uri: request.redirectUri,
|
|
1501
|
-
state: request.state,
|
|
1502
|
-
scope: request.capabilities.join(" "),
|
|
1503
|
-
resource_id: request.resourceId,
|
|
1504
|
-
mf_v: 1,
|
|
1505
|
-
mf_auth_mode: "v1",
|
|
1506
|
-
mf_request_id: request.requestId,
|
|
1507
|
-
mf_instance_id: request.instanceId,
|
|
1508
|
-
mf_instance_signing_jwk: request.instanceSigningPublicJwk,
|
|
1509
|
-
mf_instance_wrapping_jwk: request.instanceWrappingPublicJwk,
|
|
1510
|
-
mf_issued_at: request.createdAt
|
|
1511
|
-
};
|
|
1512
|
-
return `#authRequest=${bytesToB64url(utf8Encode(stableStringify(wire)))}`;
|
|
1513
|
-
}
|
|
1514
|
-
function parseEncryptedAuthAuthorizationResultFragment(fragmentOrUrl) {
|
|
1515
|
-
const input = String(fragmentOrUrl || "");
|
|
1516
|
-
const rawFragment = input.includes("#") ? input.slice(input.indexOf("#") + 1) : input.replace(/^#/, "");
|
|
1517
|
-
if (!rawFragment) return null;
|
|
1518
|
-
const encoded = new URLSearchParams(rawFragment).get(AUTH_CALLBACK_FRAGMENT_PARAM);
|
|
1519
|
-
if (!encoded) return null;
|
|
1520
|
-
const envelope = JSON.parse(new TextDecoder().decode(b64urlToBytes(encoded)));
|
|
1521
|
-
if (!envelope || envelope.v !== 1 || envelope.typ !== "auth.authorization-result.envelope.v1" || envelope.alg !== "ECDH-HKDF-SHA-256/AES-GCM-256" || typeof envelope.requestId !== "string" || typeof envelope.state !== "string" || !parseBucketResourceId(envelope.resourceId) || !isValidInstanceId(envelope.instanceId || "") || !isPublicP256EcJwk(envelope.ephemeralPublicJwk) || typeof envelope.salt !== "string" || typeof envelope.iv !== "string" || typeof envelope.aad !== "string" || typeof envelope.ciphertext !== "string") {
|
|
1522
|
-
throw new Error("auth callback result fragment invalid");
|
|
1523
|
-
}
|
|
1524
|
-
return envelope;
|
|
1525
|
-
}
|
|
1526
|
-
async function decryptEncryptedAuthAuthorizationResult(input) {
|
|
1527
|
-
const { envelope } = input;
|
|
1528
|
-
if (input.expectedRequestId && envelope.requestId !== input.expectedRequestId || input.expectedState && envelope.state !== input.expectedState || input.expectedResourceId && envelope.resourceId !== input.expectedResourceId || input.expectedInstanceId && envelope.instanceId !== input.expectedInstanceId) {
|
|
1529
|
-
throw new Error("auth callback result mismatch");
|
|
1530
|
-
}
|
|
1531
|
-
const ephemeralPublic = await crypto.subtle.importKey("jwk", envelope.ephemeralPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
|
|
1532
|
-
const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, input.instanceWrappingPrivateKey, 256);
|
|
1533
|
-
const material = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveKey"]);
|
|
1534
|
-
const wrappingKey = await crypto.subtle.deriveKey(
|
|
1535
|
-
{ name: "HKDF", hash: "SHA-256", salt: b64urlToBytes(envelope.salt), info: utf8Encode(envelope.aad) },
|
|
1536
|
-
material,
|
|
1537
|
-
{ name: "AES-GCM", length: 256 },
|
|
1538
|
-
false,
|
|
1539
|
-
["decrypt"]
|
|
1540
|
-
);
|
|
1541
|
-
const plaintext = await crypto.subtle.decrypt(
|
|
1542
|
-
{ name: "AES-GCM", iv: b64urlToBytes(envelope.iv), additionalData: utf8Encode(envelope.aad) },
|
|
1543
|
-
wrappingKey,
|
|
1544
|
-
b64urlToBytes(envelope.ciphertext)
|
|
1545
|
-
);
|
|
1546
|
-
const result = normalizeAuthAuthorizationResult(JSON.parse(new TextDecoder().decode(plaintext)), envelope.requestId);
|
|
1547
|
-
if (!result || result.state !== envelope.state || result.resourceId !== envelope.resourceId || result.instanceId !== envelope.instanceId || input.expectedState && result.state !== input.expectedState || input.expectedResourceId && result.resourceId !== input.expectedResourceId || input.expectedInstanceId && result.instanceId !== input.expectedInstanceId) {
|
|
1548
|
-
throw new Error("auth callback result mismatch");
|
|
1549
|
-
}
|
|
1550
|
-
return result;
|
|
1551
|
-
}
|
|
1552
|
-
function normalizeAuthAuthorizationResult(value, expectedRequestId) {
|
|
1553
|
-
const row = value;
|
|
1554
|
-
if (!row || row.v !== 1 || row.result !== "approved" || typeof row.requestId !== "string" || expectedRequestId && row.requestId !== expectedRequestId || typeof row.state !== "string" || !isValidMfid(row.mfid || "") || !parseBucketResourceId(row.resourceId) || !isValidInstanceId(row.instanceId || "") || typeof row.createdAt !== "string") {
|
|
1555
|
-
return null;
|
|
1556
|
-
}
|
|
1557
|
-
if (row.expiresAt !== void 0) {
|
|
1558
|
-
const expiresAt = Date.parse(String(row.expiresAt));
|
|
1559
|
-
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return null;
|
|
1560
|
-
}
|
|
1561
|
-
const resource = parseBucketResourceId(row.resourceId);
|
|
1562
|
-
if (!resource) return null;
|
|
1563
|
-
const bucketAccessGrant = normalizeBucketAccessGrant(row.bucketAccessGrant);
|
|
1564
|
-
if (!bucketAccessGrant) return null;
|
|
1565
|
-
if (bucketAccessGrant.mfid !== row.mfid || !parseBucketResourceId(bucketAccessGrant.resourceId) || bucketAccessGrant.instanceId !== row.instanceId) {
|
|
1566
|
-
return null;
|
|
1567
|
-
}
|
|
1568
|
-
return {
|
|
1569
|
-
v: 1,
|
|
1570
|
-
requestId: row.requestId,
|
|
1571
|
-
state: row.state,
|
|
1572
|
-
result: "approved",
|
|
1573
|
-
mfid: row.mfid,
|
|
1574
|
-
resourceId: resource.resourceId,
|
|
1575
|
-
instanceId: row.instanceId,
|
|
1576
|
-
createdAt: row.createdAt,
|
|
1577
|
-
...typeof row.resourceApiUrl === "string" && row.resourceApiUrl.trim() ? { resourceApiUrl: row.resourceApiUrl.trim() } : {},
|
|
1578
|
-
bucketAccessGrant,
|
|
1579
|
-
...row.expiresAt ? { expiresAt: row.expiresAt } : {}
|
|
1580
|
-
};
|
|
1581
|
-
}
|
|
1582
|
-
function normalizeBucketAccessGrant(value) {
|
|
1583
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
1584
|
-
const row = value;
|
|
1585
|
-
const resource = parseBucketResourceId(row.resourceId);
|
|
1586
|
-
const capabilities = normalizeCapabilities(row.capabilities);
|
|
1587
|
-
if (row.v !== 1 || !/^ar_[a-f0-9]{32}$/.test(String(row.grantRecordId || "")) || !isValidMfid(row.mfid) || !resource || !isValidInstanceId(row.instanceId) || !/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) || capabilities.length < 1 || !isValidBucketKeyGrantEnvelope(row.envelope, row.instanceId, row.keyId)) {
|
|
1588
|
-
return null;
|
|
1589
|
-
}
|
|
1590
|
-
return {
|
|
1591
|
-
v: 1,
|
|
1592
|
-
grantRecordId: row.grantRecordId,
|
|
1593
|
-
mfid: row.mfid,
|
|
1594
|
-
resourceId: resource.resourceId,
|
|
1595
|
-
instanceId: row.instanceId,
|
|
1596
|
-
issuedAt: String(row.issuedAt || ""),
|
|
1597
|
-
keyId: row.keyId,
|
|
1598
|
-
capabilities,
|
|
1599
|
-
envelope: row.envelope
|
|
1600
|
-
};
|
|
1601
|
-
}
|
|
1602
|
-
function isValidBucketKeyGrantEnvelope(value, instanceId, keyId) {
|
|
1603
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1604
|
-
const row = value;
|
|
1605
|
-
if (row.kind !== "bucket-key" || !isValidBucketId(row.bucketId) || !/^bk_[a-f0-9]{32}$/.test(String(row.keyId || "")) || !isValidInstanceId(row.targetInstanceId) || row.wrapAlg !== "ECDH-HKDF-SHA-256/AES-GCM-256" || !isPublicP256EcJwk(row.targetWrappingPublicJwk) || !isPublicP256EcJwk(row.ephemeralPublicJwk) || typeof row.salt !== "string" || typeof row.iv !== "string" || typeof row.aad !== "string" || typeof row.ciphertext !== "string") {
|
|
1606
|
-
return false;
|
|
1607
|
-
}
|
|
1608
|
-
if (instanceId && row.targetInstanceId !== instanceId) return false;
|
|
1609
|
-
if (keyId && row.keyId !== keyId) return false;
|
|
1610
|
-
return true;
|
|
1611
|
-
}
|
|
1612
|
-
function bucketResourceId(bucketId) {
|
|
1613
|
-
return `urn:myfield:bucket:${bucketId}`;
|
|
1614
|
-
}
|
|
1615
|
-
function parseBucketResourceId(resourceId) {
|
|
1616
|
-
const safe = typeof resourceId === "string" ? resourceId.trim() : "";
|
|
1617
|
-
const prefix = "urn:myfield:bucket:";
|
|
1618
|
-
if (!safe.startsWith(prefix)) return null;
|
|
1619
|
-
const bucketId = safe.slice(prefix.length);
|
|
1620
|
-
return isValidBucketId(bucketId) ? { resourceId: safe, bucketId } : null;
|
|
1621
|
-
}
|
|
1622
|
-
function normalizeCapabilities(input) {
|
|
1623
|
-
if (!Array.isArray(input)) return [];
|
|
1624
|
-
const allowed = /* @__PURE__ */ new Set(["read", "write"]);
|
|
1625
|
-
const result = [];
|
|
1626
|
-
for (const item of input) {
|
|
1627
|
-
if (allowed.has(item) && !result.includes(item)) result.push(item);
|
|
1628
|
-
}
|
|
1629
|
-
return result.sort();
|
|
1630
|
-
}
|
|
1631
2061
|
async function postJson(fetchImpl, apiBase, path, body) {
|
|
1632
2062
|
const res = await fetchImpl(`${apiBase || ""}${path}`, {
|
|
1633
2063
|
method: "POST",
|
|
@@ -1657,88 +2087,999 @@ function isFresh(createdAt) {
|
|
|
1657
2087
|
const created = Date.parse(createdAt);
|
|
1658
2088
|
return Number.isFinite(created) && Date.now() - created <= AUTH_REQUEST_TTL_MS;
|
|
1659
2089
|
}
|
|
1660
|
-
function
|
|
1661
|
-
|
|
1662
|
-
return
|
|
2090
|
+
function browserLocationHref() {
|
|
2091
|
+
if (typeof window === "undefined") throw new Error("browser window required");
|
|
2092
|
+
return window.location.href;
|
|
1663
2093
|
}
|
|
1664
|
-
function
|
|
1665
|
-
if (
|
|
2094
|
+
function browserLocationOrigin() {
|
|
2095
|
+
if (typeof window === "undefined") throw new Error("browser window required");
|
|
2096
|
+
return window.location.origin;
|
|
2097
|
+
}
|
|
2098
|
+
|
|
2099
|
+
// src/remote/http.ts
|
|
2100
|
+
function isRecord2(value) {
|
|
2101
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2102
|
+
}
|
|
2103
|
+
function requireString(value, name) {
|
|
2104
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
2105
|
+
throw new ClientError("INVALID_INPUT", `${name} must be a non-empty string`);
|
|
2106
|
+
}
|
|
2107
|
+
}
|
|
2108
|
+
function invalidResponse(response, message = "Invalid protocol response", cause) {
|
|
2109
|
+
return new ClientError("INVALID_RESPONSE", message, {
|
|
2110
|
+
status: response.status,
|
|
2111
|
+
requestId: response.headers.get("x-request-id") ?? void 0,
|
|
2112
|
+
cause
|
|
2113
|
+
});
|
|
2114
|
+
}
|
|
2115
|
+
function networkError(cause, signal) {
|
|
2116
|
+
signal?.throwIfAborted();
|
|
2117
|
+
throw new ClientError("NETWORK_ERROR", "Network request failed", { retryable: true, cause });
|
|
2118
|
+
}
|
|
2119
|
+
async function readJson(response, signal) {
|
|
2120
|
+
let value;
|
|
2121
|
+
try {
|
|
2122
|
+
value = await response.json();
|
|
2123
|
+
} catch (cause) {
|
|
2124
|
+
signal?.throwIfAborted();
|
|
2125
|
+
if (!(cause instanceof SyntaxError)) return networkError(cause, signal);
|
|
2126
|
+
throw invalidResponse(response, "Invalid JSON response", cause);
|
|
2127
|
+
}
|
|
2128
|
+
signal?.throwIfAborted();
|
|
2129
|
+
if (!isRecord2(value)) throw invalidResponse(response);
|
|
1666
2130
|
return value;
|
|
1667
2131
|
}
|
|
1668
|
-
function
|
|
1669
|
-
|
|
2132
|
+
function createHttpRequest(options) {
|
|
2133
|
+
requireString(options.apiBase, "apiBase");
|
|
2134
|
+
let base;
|
|
2135
|
+
try {
|
|
2136
|
+
base = new URL(options.apiBase);
|
|
2137
|
+
} catch (cause) {
|
|
2138
|
+
throw new ClientError("INVALID_INPUT", "apiBase must be an HTTP(S) origin", { cause });
|
|
2139
|
+
}
|
|
2140
|
+
if (!["http:", "https:"].includes(base.protocol) || base.pathname !== "/" || base.search || base.hash || base.username || base.password) {
|
|
2141
|
+
throw new ClientError("INVALID_INPUT", "apiBase must be an HTTP(S) origin without a path, query, fragment or credentials");
|
|
2142
|
+
}
|
|
2143
|
+
const fetch2 = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
2144
|
+
if (typeof fetch2 !== "function") throw new ClientError("INVALID_INPUT", "fetch must be a function");
|
|
2145
|
+
return async (path, init) => {
|
|
2146
|
+
init.signal?.throwIfAborted();
|
|
2147
|
+
let response;
|
|
2148
|
+
try {
|
|
2149
|
+
response = await fetch2(new URL(path, base).href, { ...init, credentials: "omit" });
|
|
2150
|
+
} catch (cause) {
|
|
2151
|
+
return networkError(cause, init.signal);
|
|
2152
|
+
}
|
|
2153
|
+
if (response.ok) return response;
|
|
2154
|
+
let body = {};
|
|
2155
|
+
try {
|
|
2156
|
+
const value = await response.json();
|
|
2157
|
+
if (isRecord2(value)) body = value;
|
|
2158
|
+
} catch {
|
|
2159
|
+
init.signal?.throwIfAborted();
|
|
2160
|
+
}
|
|
2161
|
+
const details = isRecord2(body.details) ? body.details : {};
|
|
2162
|
+
const retry = response.headers.get("retry-after");
|
|
2163
|
+
const seconds = retry !== null && /^\d+(?:\.\d+)?$/.test(retry.trim()) ? Number(retry) : NaN;
|
|
2164
|
+
const date = retry === null ? NaN : Date.parse(retry);
|
|
2165
|
+
const retryAfterMs = Number.isFinite(seconds) ? seconds * 1e3 : Number.isFinite(date) ? Math.max(0, date - Date.now()) : void 0;
|
|
2166
|
+
throw new ClientError(
|
|
2167
|
+
typeof body.code === "string" && body.code ? body.code : "HTTP_ERROR",
|
|
2168
|
+
typeof body.message === "string" && body.message ? body.message : typeof body.error === "string" && body.error ? body.error : `HTTP ${response.status}`,
|
|
2169
|
+
{
|
|
2170
|
+
status: response.status,
|
|
2171
|
+
requestId: typeof body.requestId === "string" ? body.requestId : response.headers.get("x-request-id") ?? void 0,
|
|
2172
|
+
retryable: typeof details.retryable === "boolean" ? details.retryable : response.status === 408 || response.status === 429 || response.status >= 500,
|
|
2173
|
+
retryAfterMs,
|
|
2174
|
+
maxBytes: typeof details.maxBytes === "number" ? details.maxBytes : void 0
|
|
2175
|
+
}
|
|
2176
|
+
);
|
|
2177
|
+
};
|
|
1670
2178
|
}
|
|
1671
|
-
|
|
1672
|
-
|
|
2179
|
+
|
|
2180
|
+
// src/remote/feed.ts
|
|
2181
|
+
function isFeedHint(value) {
|
|
2182
|
+
return isRecord2(value) && typeof value.objectId === "string" && value.objectId.length > 0 && typeof value.versionId === "string" && value.versionId.length > 0;
|
|
2183
|
+
}
|
|
2184
|
+
async function openFeedStream(response, signal) {
|
|
2185
|
+
const stream = readFeedStream(response, signal);
|
|
2186
|
+
await stream.next();
|
|
2187
|
+
return stream;
|
|
2188
|
+
}
|
|
2189
|
+
async function* readFeedStream(response, signal) {
|
|
2190
|
+
if (!response.body || response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== "text/event-stream") {
|
|
2191
|
+
await response.body?.cancel().catch(() => {
|
|
2192
|
+
});
|
|
2193
|
+
throw invalidResponse(response, "Expected an event stream");
|
|
2194
|
+
}
|
|
2195
|
+
const reader = response.body.getReader();
|
|
2196
|
+
const decoder = new TextDecoder();
|
|
2197
|
+
const cancel = () => {
|
|
2198
|
+
void reader.cancel(signal?.reason).catch(() => {
|
|
2199
|
+
});
|
|
2200
|
+
};
|
|
2201
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
2202
|
+
let buffer = "", event = "", data = [], ready = false;
|
|
2203
|
+
try {
|
|
2204
|
+
signal?.throwIfAborted();
|
|
2205
|
+
for (; ; ) {
|
|
2206
|
+
let chunk;
|
|
2207
|
+
try {
|
|
2208
|
+
chunk = await reader.read();
|
|
2209
|
+
} catch (cause) {
|
|
2210
|
+
signal?.throwIfAborted();
|
|
2211
|
+
throw new ClientError("NETWORK_ERROR", "Feed stream interrupted", { retryable: true, cause });
|
|
2212
|
+
}
|
|
2213
|
+
signal?.throwIfAborted();
|
|
2214
|
+
buffer += decoder.decode(chunk.value, { stream: !chunk.done });
|
|
2215
|
+
let match;
|
|
2216
|
+
while ((match = /\r\n|\r|\n/.exec(buffer)) !== null) {
|
|
2217
|
+
if (!chunk.done && match.index === buffer.length - 1 && match[0] === "\r") break;
|
|
2218
|
+
const line = buffer.slice(0, match.index);
|
|
2219
|
+
buffer = buffer.slice(match.index + match[0].length);
|
|
2220
|
+
if (line === "") {
|
|
2221
|
+
if (event === "sync-ready" && data.length && !ready) {
|
|
2222
|
+
ready = true;
|
|
2223
|
+
yield void 0;
|
|
2224
|
+
} else if (event === "sync-feed" && data.length) {
|
|
2225
|
+
if (!ready) throw invalidResponse(response, "Feed change received before readiness");
|
|
2226
|
+
let value;
|
|
2227
|
+
try {
|
|
2228
|
+
value = JSON.parse(data.join("\n"));
|
|
2229
|
+
} catch (cause) {
|
|
2230
|
+
throw invalidResponse(response, "Invalid feed event", cause);
|
|
2231
|
+
}
|
|
2232
|
+
const entries = isRecord2(value) && Array.isArray(value.entries) ? value.entries : [value];
|
|
2233
|
+
if (!entries.every(isFeedHint)) throw invalidResponse(response, "Invalid feed hint");
|
|
2234
|
+
for (const entry of entries) {
|
|
2235
|
+
signal?.throwIfAborted();
|
|
2236
|
+
if (isFeedHint(entry)) yield { objectId: entry.objectId, versionId: entry.versionId };
|
|
2237
|
+
}
|
|
2238
|
+
}
|
|
2239
|
+
event = "";
|
|
2240
|
+
data = [];
|
|
2241
|
+
} else if (!line.startsWith(":")) {
|
|
2242
|
+
const colon = line.indexOf(":");
|
|
2243
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
2244
|
+
const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
2245
|
+
if (field === "event") event = value;
|
|
2246
|
+
if (field === "data") data.push(value);
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
if (chunk.done) {
|
|
2250
|
+
if (!ready) throw invalidResponse(response, "Feed ended before readiness");
|
|
2251
|
+
break;
|
|
2252
|
+
}
|
|
2253
|
+
}
|
|
2254
|
+
} finally {
|
|
2255
|
+
signal?.removeEventListener("abort", cancel);
|
|
2256
|
+
await reader.cancel().catch(() => {
|
|
2257
|
+
});
|
|
2258
|
+
reader.releaseLock();
|
|
2259
|
+
}
|
|
1673
2260
|
}
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
return
|
|
2261
|
+
|
|
2262
|
+
// src/remote/bucket.ts
|
|
2263
|
+
function isHistory(value) {
|
|
2264
|
+
return Array.isArray(value) && value.every((id) => typeof id === "string" && id.length > 0) && new Set(value).size === value.length;
|
|
2265
|
+
}
|
|
2266
|
+
function pageQuery(options) {
|
|
2267
|
+
const query = new URLSearchParams();
|
|
2268
|
+
if (options.cursor != null) {
|
|
2269
|
+
if (typeof options.cursor !== "string") throw new ClientError("INVALID_INPUT", "cursor must be a string or null");
|
|
2270
|
+
if (options.cursor) query.set("cursor", options.cursor);
|
|
2271
|
+
}
|
|
2272
|
+
if (options.limit !== void 0) {
|
|
2273
|
+
if (!Number.isInteger(options.limit) || options.limit < 1) throw new ClientError("INVALID_INPUT", "limit must be a positive integer");
|
|
2274
|
+
query.set("limit", String(options.limit));
|
|
2275
|
+
}
|
|
2276
|
+
return query;
|
|
2277
|
+
}
|
|
2278
|
+
function isVersionMeta(value, objectId, versionId) {
|
|
2279
|
+
return isRecord2(value) && value.objectId === objectId && typeof value.versionId === "string" && value.versionId.length > 0 && (versionId === void 0 || value.versionId === versionId) && Array.isArray(value.parentVersionIds) && value.parentVersionIds.every((id) => typeof id === "string" && id.length > 0);
|
|
2280
|
+
}
|
|
2281
|
+
function segment(id) {
|
|
2282
|
+
requireString(id, "ID");
|
|
2283
|
+
if (id === "." || id === "..") throw new ClientError("INVALID_INPUT", "Dot segments cannot be requested");
|
|
2284
|
+
return encodeURIComponent(id);
|
|
2285
|
+
}
|
|
2286
|
+
function writableId(id) {
|
|
2287
|
+
requireString(id, "ID");
|
|
2288
|
+
if (id === "." || id.includes("..")) throw new ClientError("INVALID_INPUT", "Dot-segment IDs cannot be committed");
|
|
2289
|
+
}
|
|
2290
|
+
function createBucketClient(request, bucketId) {
|
|
2291
|
+
const root = `/v1/api/sync/buckets/${segment(bucketId)}`;
|
|
2292
|
+
const objectPath = (id) => `${root}/objects/${segment(id)}`;
|
|
2293
|
+
const versionPath = (id, versionId) => `${objectPath(id)}/versions/${segment(versionId)}`;
|
|
2294
|
+
async function json(path, options) {
|
|
2295
|
+
const response = await request(path, { signal: options.signal });
|
|
2296
|
+
return { response, body: await readJson(response, options.signal) };
|
|
2297
|
+
}
|
|
2298
|
+
async function getVersionMeta(objectId, versionId, options = {}) {
|
|
2299
|
+
const { response, body } = await json(`${versionPath(objectId, versionId)}/meta`, options);
|
|
2300
|
+
if (!isVersionMeta(body, objectId, versionId)) throw invalidResponse(response);
|
|
2301
|
+
return body;
|
|
2302
|
+
}
|
|
2303
|
+
return {
|
|
2304
|
+
async getCurrent(objectId, options = {}) {
|
|
2305
|
+
const query = new URLSearchParams({ miss: "null" });
|
|
2306
|
+
if (options.knownVersionId != null) {
|
|
2307
|
+
requireString(options.knownVersionId, "knownVersionId");
|
|
2308
|
+
query.set("have", options.knownVersionId);
|
|
2309
|
+
}
|
|
2310
|
+
const { response, body } = await json(`${objectPath(objectId)}/current?${query}`, options);
|
|
2311
|
+
if (body.versionId === null && body.headVersionMeta === null) return null;
|
|
2312
|
+
if (typeof body.versionId !== "string" || !isVersionMeta(body.headVersionMeta, objectId, body.versionId)) throw invalidResponse(response);
|
|
2313
|
+
if (options.knownVersionId != null && !Object.hasOwn(body, "history")) throw invalidResponse(response, "Missing history evidence");
|
|
2314
|
+
if (Object.hasOwn(body, "history") && body.history !== null) {
|
|
2315
|
+
if (!isHistory(body.history)) throw invalidResponse(response);
|
|
2316
|
+
if (body.history.length && (body.history[0] !== body.versionId || options.knownVersionId != null && body.history.at(-1) !== options.knownVersionId)) throw invalidResponse(response);
|
|
2317
|
+
}
|
|
2318
|
+
return body;
|
|
2319
|
+
},
|
|
2320
|
+
getVersionMeta,
|
|
2321
|
+
async listVersions(objectId, versionId, options = {}) {
|
|
2322
|
+
const query = pageQuery(options);
|
|
2323
|
+
query.set("history", "full");
|
|
2324
|
+
const { response, body } = await json(`${versionPath(objectId, versionId)}/meta?${query}`, options);
|
|
2325
|
+
if (!isVersionMeta(body, objectId, versionId) || !isHistory(body.history) || !query.has("cursor") && body.history[0] !== versionId || !(body.nextCursor === null || typeof body.nextCursor === "string" && body.nextCursor.length > 0)) throw invalidResponse(response);
|
|
2326
|
+
return body;
|
|
2327
|
+
},
|
|
2328
|
+
async getIndex(options = {}) {
|
|
2329
|
+
const { response, body } = await json(`${root}/objects:index`, options);
|
|
2330
|
+
if (body.bucketId !== bucketId || !Array.isArray(body.objects) || !body.objects.every(isFeedHint) || !(body.feedCursor === null || typeof body.feedCursor === "string") || typeof body.hasMoreFeed !== "boolean") throw invalidResponse(response);
|
|
2331
|
+
return body;
|
|
2332
|
+
},
|
|
2333
|
+
async listFeed(options = {}) {
|
|
2334
|
+
const query = pageQuery(options);
|
|
2335
|
+
const { response, body } = await json(`${root}/feed${query.size ? `?${query}` : ""}`, options);
|
|
2336
|
+
if (!Array.isArray(body.entries) || !body.entries.every(isFeedHint) || typeof body.cursor !== "string" || typeof body.hasMore !== "boolean") throw invalidResponse(response);
|
|
2337
|
+
return body;
|
|
2338
|
+
},
|
|
2339
|
+
async watchFeed(options = {}) {
|
|
2340
|
+
const response = await request(`${root}/feed/stream`, { headers: { accept: "text/event-stream" }, signal: options.signal });
|
|
2341
|
+
return openFeedStream(response, options.signal);
|
|
2342
|
+
},
|
|
2343
|
+
async getPayload(objectId, versionId, options = {}) {
|
|
2344
|
+
return request(`${versionPath(objectId, versionId)}/payload`, { signal: options.signal });
|
|
2345
|
+
},
|
|
2346
|
+
async getVersion(objectId, versionId, options = {}) {
|
|
2347
|
+
const path = versionPath(objectId, versionId);
|
|
2348
|
+
let payload;
|
|
2349
|
+
let failed = false;
|
|
2350
|
+
const download = request(`${path}/payload`, { signal: options.signal }).then((response) => {
|
|
2351
|
+
if (failed) void response.body?.cancel().catch(() => {
|
|
2352
|
+
});
|
|
2353
|
+
else payload = response;
|
|
2354
|
+
return response;
|
|
2355
|
+
});
|
|
2356
|
+
try {
|
|
2357
|
+
const [meta, response] = await Promise.all([getVersionMeta(objectId, versionId, options), download]);
|
|
2358
|
+
return { meta, payload: response };
|
|
2359
|
+
} catch (error) {
|
|
2360
|
+
failed = true;
|
|
2361
|
+
void payload?.body?.cancel().catch(() => {
|
|
2362
|
+
});
|
|
2363
|
+
throw error;
|
|
2364
|
+
}
|
|
2365
|
+
},
|
|
2366
|
+
async commit(input, options = {}) {
|
|
2367
|
+
if (!isRecord2(input) || !isRecord2(input.meta)) throw new ClientError("INVALID_INPUT", "Commit metadata is required");
|
|
2368
|
+
if (input.expectedHeadVersionId !== null) requireString(input.expectedHeadVersionId, "expectedHeadVersionId");
|
|
2369
|
+
writableId(input.meta.objectId);
|
|
2370
|
+
writableId(input.meta.versionId);
|
|
2371
|
+
if (!(input.payload instanceof Blob) && !(input.payload instanceof Uint8Array)) throw new ClientError("INVALID_INPUT", "Payload must be a Blob or Uint8Array");
|
|
2372
|
+
let headers;
|
|
2373
|
+
try {
|
|
2374
|
+
headers = new Headers({
|
|
2375
|
+
"content-type": "application/octet-stream",
|
|
2376
|
+
"x-myfield-version-meta": bytesToB64url(utf8Encode(JSON.stringify(input.meta)))
|
|
2377
|
+
});
|
|
2378
|
+
if (input.expectedHeadVersionId !== null) headers.set("x-myfield-expected-head-version-id", input.expectedHeadVersionId);
|
|
2379
|
+
} catch (cause) {
|
|
2380
|
+
throw new ClientError("INVALID_INPUT", "Invalid commit metadata or CAS header", { cause });
|
|
2381
|
+
}
|
|
2382
|
+
const response = await request(objectPath(input.meta.objectId), { method: "POST", headers, body: input.payload, signal: options.signal });
|
|
2383
|
+
const body = await readJson(response, options.signal);
|
|
2384
|
+
if (body.ok === true) return body;
|
|
2385
|
+
if (body.ok === false && (body.reason === "version-mismatch" || body.reason === "conflict")) return body;
|
|
2386
|
+
throw invalidResponse(response, "Invalid commit result");
|
|
2387
|
+
}
|
|
2388
|
+
};
|
|
1678
2389
|
}
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
2390
|
+
|
|
2391
|
+
// src/remote/client.ts
|
|
2392
|
+
function createRemoteClient(options) {
|
|
2393
|
+
if (!isRecord2(options)) throw new ClientError("INVALID_INPUT", "Client options are required");
|
|
2394
|
+
const httpRequest = createHttpRequest(options);
|
|
2395
|
+
const { mfid, bucketId, getCredential } = options;
|
|
2396
|
+
requireString(mfid, "mfid");
|
|
2397
|
+
if (typeof getCredential !== "function") throw new ClientError("INVALID_INPUT", "getCredential must be a function");
|
|
2398
|
+
const request = async (path, init = {}) => {
|
|
2399
|
+
init.signal?.throwIfAborted();
|
|
2400
|
+
const credential = await getCredential();
|
|
2401
|
+
requireString(credential?.token, "token");
|
|
2402
|
+
init.signal?.throwIfAborted();
|
|
2403
|
+
let headers;
|
|
2404
|
+
try {
|
|
2405
|
+
headers = new Headers(init.headers);
|
|
2406
|
+
headers.set("x-myfield-mfid", mfid);
|
|
2407
|
+
headers.set("authorization", `Bearer ${credential.token}`);
|
|
2408
|
+
} catch (cause) {
|
|
2409
|
+
throw new ClientError("INVALID_INPUT", "Invalid request headers", { cause });
|
|
2410
|
+
}
|
|
2411
|
+
return httpRequest(path, { ...init, headers });
|
|
2412
|
+
};
|
|
2413
|
+
const bucket = createBucketClient(request, bucketId);
|
|
2414
|
+
return { getBucket: () => bucket };
|
|
1682
2415
|
}
|
|
1683
|
-
|
|
1684
|
-
|
|
2416
|
+
|
|
2417
|
+
// src/remote/connection.ts
|
|
2418
|
+
var DEFAULT_AUTH_URL = "https://myfield.one/auth/";
|
|
2419
|
+
function notAuthorized2(message, cause) {
|
|
2420
|
+
return new ClientError("NOT_AUTHORIZED", message, {
|
|
2421
|
+
cause,
|
|
2422
|
+
...cause instanceof ClientError ? { status: cause.status, requestId: cause.requestId } : {}
|
|
2423
|
+
});
|
|
1685
2424
|
}
|
|
1686
|
-
function
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
2425
|
+
function isAuthorizationError(error) {
|
|
2426
|
+
return error.code === "NOT_AUTHORIZED" || error.status === 401 || error.status === 403 && REVOKED_AUTHORIZATION_CODES.includes(error.code);
|
|
2427
|
+
}
|
|
2428
|
+
function connectionError(error) {
|
|
2429
|
+
if (error instanceof ClientError) {
|
|
2430
|
+
if (isAuthorizationError(error)) return error.code === "NOT_AUTHORIZED" ? error : notAuthorized2(error.message, error);
|
|
2431
|
+
if (["INVALID_STATE", "INVALID_INSTANCE_KEY", "NETWORK_ERROR"].includes(error.code)) return error;
|
|
2432
|
+
if (error.retryable) return new ClientError("NETWORK_ERROR", error.message, {
|
|
2433
|
+
cause: error,
|
|
2434
|
+
retryable: true,
|
|
2435
|
+
status: error.status,
|
|
2436
|
+
requestId: error.requestId,
|
|
2437
|
+
retryAfterMs: error.retryAfterMs
|
|
2438
|
+
});
|
|
1691
2439
|
}
|
|
1692
|
-
return
|
|
1693
|
-
}
|
|
1694
|
-
function browserLocationHref() {
|
|
1695
|
-
if (typeof window === "undefined") throw new Error("browser window required");
|
|
1696
|
-
return window.location.href;
|
|
2440
|
+
return new ClientError("INVALID_STATE", error instanceof Error ? error.message : "Connection failed", { cause: error });
|
|
1697
2441
|
}
|
|
1698
|
-
function
|
|
1699
|
-
|
|
1700
|
-
|
|
2442
|
+
function normalizeAuthUrl(value) {
|
|
2443
|
+
let url;
|
|
2444
|
+
try {
|
|
2445
|
+
url = new URL(value);
|
|
2446
|
+
} catch (cause) {
|
|
2447
|
+
throw new ClientError("INVALID_INPUT", "authUrl must be an absolute HTTP(S) URL", { cause });
|
|
2448
|
+
}
|
|
2449
|
+
if (!/^https?:$/.test(url.protocol) || url.username || url.password || url.search || url.hash) {
|
|
2450
|
+
throw new ClientError("INVALID_INPUT", "authUrl must be an HTTP(S) page URL without credentials, query or fragment");
|
|
2451
|
+
}
|
|
2452
|
+
return url.href;
|
|
1701
2453
|
}
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
2454
|
+
function apiOrigin(value) {
|
|
2455
|
+
let url;
|
|
2456
|
+
try {
|
|
2457
|
+
url = new URL(value);
|
|
2458
|
+
} catch (cause) {
|
|
2459
|
+
throw new ClientError("NOT_AUTHORIZED", "Authorization has no valid API address", { cause });
|
|
2460
|
+
}
|
|
2461
|
+
if (!/^https?:$/.test(url.protocol) || url.username || url.password || url.search || url.hash || !["/", "/v1/api/sync", "/v1/api/sync/"].includes(url.pathname)) {
|
|
2462
|
+
throw new ClientError("NOT_AUTHORIZED", "Unsupported authorization API address");
|
|
2463
|
+
}
|
|
2464
|
+
return url.origin;
|
|
2465
|
+
}
|
|
2466
|
+
function createInstanceConnection(deps) {
|
|
2467
|
+
let bucketId, resourceId;
|
|
2468
|
+
const storageAppId = deps.getAppId;
|
|
2469
|
+
let remoteClient = null;
|
|
2470
|
+
let localAccess = null;
|
|
2471
|
+
let connectionController = null;
|
|
2472
|
+
let flow = null;
|
|
2473
|
+
let state = "disconnected";
|
|
2474
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
2475
|
+
let forceSessionRefresh = false;
|
|
2476
|
+
let disconnecting = null;
|
|
2477
|
+
let cleanup = Promise.resolve();
|
|
2478
|
+
let storageQueue = Promise.resolve();
|
|
2479
|
+
let keyChanges = Promise.resolve();
|
|
2480
|
+
let generation = 0;
|
|
2481
|
+
let disposed = false;
|
|
2482
|
+
const browserAuth = createAuthorizationFlow(deps);
|
|
2483
|
+
const { ownCallback, handleCallback, requestAuthorization } = browserAuth;
|
|
2484
|
+
function assertRuntime() {
|
|
2485
|
+
if (disposed) throw new ClientError("INVALID_STATE", "Instance runtime has stopped");
|
|
2486
|
+
}
|
|
2487
|
+
function assertUsable() {
|
|
2488
|
+
assertRuntime();
|
|
2489
|
+
bucketId = deps.getBucketId?.() ?? storageAppId();
|
|
2490
|
+
resourceId = `urn:myfield:bucket:${bucketId}`;
|
|
2491
|
+
}
|
|
2492
|
+
function assertKeyMutable() {
|
|
2493
|
+
if (disposed || remoteClient || flow || deps.hasActiveConnection?.()) {
|
|
2494
|
+
throw new ClientError("INVALID_STATE", "Disconnect before changing an instance key");
|
|
2495
|
+
}
|
|
2496
|
+
storageAppId();
|
|
1708
2497
|
}
|
|
1709
|
-
|
|
2498
|
+
function changeKey(operation) {
|
|
2499
|
+
try {
|
|
2500
|
+
assertKeyMutable();
|
|
2501
|
+
} catch (error) {
|
|
2502
|
+
return Promise.reject(error);
|
|
2503
|
+
}
|
|
2504
|
+
const result = keyChanges.then(async () => {
|
|
2505
|
+
await cleanup;
|
|
2506
|
+
assertKeyMutable();
|
|
2507
|
+
return operation(createInstanceKeyStore(deps.auth, storageAppId()));
|
|
2508
|
+
});
|
|
2509
|
+
keyChanges = result.then(() => {
|
|
2510
|
+
}, () => {
|
|
2511
|
+
});
|
|
2512
|
+
return result;
|
|
2513
|
+
}
|
|
2514
|
+
function emitState(next, error) {
|
|
2515
|
+
if (state === next && !error) return;
|
|
2516
|
+
state = next;
|
|
2517
|
+
for (const listener of [...listeners]) {
|
|
2518
|
+
try {
|
|
2519
|
+
listener(next, error);
|
|
2520
|
+
} catch {
|
|
2521
|
+
}
|
|
2522
|
+
}
|
|
2523
|
+
}
|
|
2524
|
+
function queue(signal, operation) {
|
|
2525
|
+
const next = storageQueue.then(async () => {
|
|
2526
|
+
signal.throwIfAborted();
|
|
2527
|
+
try {
|
|
2528
|
+
return await operation();
|
|
2529
|
+
} catch (error) {
|
|
2530
|
+
signal.throwIfAborted();
|
|
2531
|
+
throw connectionError(error);
|
|
2532
|
+
}
|
|
2533
|
+
});
|
|
2534
|
+
storageQueue = next.catch(() => {
|
|
2535
|
+
});
|
|
2536
|
+
return next;
|
|
2537
|
+
}
|
|
2538
|
+
function guardedStorage(signal, appId) {
|
|
2539
|
+
const keys = authRecordKeys(appId);
|
|
2540
|
+
const prefix = keys.prefix;
|
|
2541
|
+
return {
|
|
2542
|
+
...deps.auth.insertIfEmpty ? { insertIfEmpty: (prefix2, entries) => queue(signal, () => deps.auth.insertIfEmpty(prefix2, entries)) } : {},
|
|
2543
|
+
get: (key) => queue(signal, () => deps.auth.get(key)),
|
|
2544
|
+
keys: (prefix2) => queue(signal, () => deps.auth.keys(prefix2)),
|
|
2545
|
+
remove: (key) => queue(signal, () => deps.auth.remove(key)),
|
|
2546
|
+
set: (key, value) => queue(signal, async () => {
|
|
2547
|
+
if (key.startsWith(`${prefix}context:`)) {
|
|
2548
|
+
const context = value;
|
|
2549
|
+
const identity = await deps.auth.get(keys.active);
|
|
2550
|
+
signal.throwIfAborted();
|
|
2551
|
+
if (context.resourceId !== resourceId || identity?.instanceId !== context.instanceId) {
|
|
2552
|
+
throw new ClientError("NOT_AUTHORIZED", "Callback does not match the active instance and bucket");
|
|
2553
|
+
}
|
|
2554
|
+
if (!context.resourceApiUrl) throw new ClientError("NOT_AUTHORIZED", "Callback is missing its API address");
|
|
2555
|
+
apiOrigin(context.resourceApiUrl);
|
|
2556
|
+
const grant = context.bucketAccessGrant;
|
|
2557
|
+
const instance = await deps.auth.get(keys.key(context.instanceId));
|
|
2558
|
+
if (!grant || !instance) throw new ClientError("NOT_AUTHORIZED", "Missing bucket grant or instance key");
|
|
2559
|
+
const bucketKeys = await unwrapBucketKeys(grant.envelope, instance.wrappingPrivateKey);
|
|
2560
|
+
signal.throwIfAborted();
|
|
2561
|
+
if (grant.resourceId !== `urn:myfield:bucket:${bucketKeys.bucketId}`) throw new ClientError("NOT_AUTHORIZED", "Grant and bucket key identify different resources");
|
|
2562
|
+
}
|
|
2563
|
+
await deps.auth.set(key, value);
|
|
2564
|
+
})
|
|
2565
|
+
};
|
|
2566
|
+
}
|
|
2567
|
+
function fetchFor(signal) {
|
|
2568
|
+
return async (input, init) => {
|
|
2569
|
+
signal.throwIfAborted();
|
|
2570
|
+
const other = init?.signal;
|
|
2571
|
+
if (!other || other === signal) {
|
|
2572
|
+
const response = await globalThis.fetch(input, { ...init, signal });
|
|
2573
|
+
if (signal.aborted) {
|
|
2574
|
+
void response.body?.cancel().catch(() => {
|
|
2575
|
+
});
|
|
2576
|
+
signal.throwIfAborted();
|
|
2577
|
+
}
|
|
2578
|
+
return response;
|
|
2579
|
+
}
|
|
2580
|
+
const controller = new AbortController();
|
|
2581
|
+
const signals = [signal, other];
|
|
2582
|
+
const abort = () => controller.abort(signals.find((item) => item.aborted)?.reason);
|
|
2583
|
+
const detach = () => {
|
|
2584
|
+
for (const item of signals) item.removeEventListener("abort", abort);
|
|
2585
|
+
};
|
|
2586
|
+
for (const item of signals) {
|
|
2587
|
+
if (item.aborted) abort();
|
|
2588
|
+
else item.addEventListener("abort", abort, { once: true });
|
|
2589
|
+
}
|
|
2590
|
+
controller.signal.addEventListener("abort", detach, { once: true });
|
|
2591
|
+
try {
|
|
2592
|
+
controller.signal.throwIfAborted();
|
|
2593
|
+
const response = await globalThis.fetch(input, { ...init, signal: controller.signal });
|
|
2594
|
+
if (controller.signal.aborted) {
|
|
2595
|
+
void response.body?.cancel().catch(() => {
|
|
2596
|
+
});
|
|
2597
|
+
controller.signal.throwIfAborted();
|
|
2598
|
+
}
|
|
2599
|
+
if (!response.body) {
|
|
2600
|
+
detach();
|
|
2601
|
+
return response;
|
|
2602
|
+
}
|
|
2603
|
+
const reader = response.body.getReader();
|
|
2604
|
+
const body = new ReadableStream({
|
|
2605
|
+
async pull(output) {
|
|
2606
|
+
try {
|
|
2607
|
+
const result = await reader.read();
|
|
2608
|
+
controller.signal.throwIfAborted();
|
|
2609
|
+
if (result.done) {
|
|
2610
|
+
detach();
|
|
2611
|
+
output.close();
|
|
2612
|
+
} else output.enqueue(result.value);
|
|
2613
|
+
} catch (error) {
|
|
2614
|
+
detach();
|
|
2615
|
+
output.error(error);
|
|
2616
|
+
}
|
|
2617
|
+
},
|
|
2618
|
+
async cancel(reason) {
|
|
2619
|
+
detach();
|
|
2620
|
+
await reader.cancel(reason);
|
|
2621
|
+
}
|
|
2622
|
+
});
|
|
2623
|
+
const wrapped = new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
2624
|
+
for (const property of ["url", "redirected", "type"]) Object.defineProperty(wrapped, property, { value: response[property] });
|
|
2625
|
+
return wrapped;
|
|
2626
|
+
} catch (error) {
|
|
2627
|
+
detach();
|
|
2628
|
+
throw error;
|
|
2629
|
+
}
|
|
2630
|
+
};
|
|
2631
|
+
}
|
|
2632
|
+
async function clearAccess(removeGrant) {
|
|
2633
|
+
const prefix = authRecordKeys(storageAppId()).prefix;
|
|
2634
|
+
const keys = await deps.auth.keys(prefix);
|
|
2635
|
+
const contexts = [];
|
|
2636
|
+
const sessions = /* @__PURE__ */ new Set([resourceId]);
|
|
2637
|
+
for (const key of keys.filter((key2) => key2.startsWith(`${prefix}context:`))) {
|
|
2638
|
+
const context = await deps.auth.get(key);
|
|
2639
|
+
if (context?.resourceId !== resourceId) continue;
|
|
2640
|
+
sessions.add(context.remoteResourceId || resourceId);
|
|
2641
|
+
contexts.push(key);
|
|
2642
|
+
}
|
|
2643
|
+
for (const key of keys.filter((key2) => key2.startsWith(`${prefix}session:`))) {
|
|
2644
|
+
const session = await deps.auth.get(key);
|
|
2645
|
+
if (session && sessions.has(session.resourceId)) await deps.auth.remove(key);
|
|
2646
|
+
}
|
|
2647
|
+
if (!removeGrant) return;
|
|
2648
|
+
for (const key of contexts) await deps.auth.remove(key);
|
|
2649
|
+
for (const key of keys) {
|
|
2650
|
+
if (!key.startsWith(`${prefix}pending-auth:`) && !key.startsWith(`${prefix}callback-pointer:`)) continue;
|
|
2651
|
+
const pending = await deps.auth.get(key);
|
|
2652
|
+
if (pending?.resourceId === resourceId) await deps.auth.remove(key);
|
|
2653
|
+
}
|
|
2654
|
+
}
|
|
2655
|
+
function invalidate(controller, error) {
|
|
2656
|
+
if (connectionController !== controller) return cleanup;
|
|
2657
|
+
remoteClient = null;
|
|
2658
|
+
localAccess = null;
|
|
2659
|
+
connectionController = null;
|
|
2660
|
+
forceSessionRefresh = true;
|
|
2661
|
+
cleanup = cleanup.catch(() => {
|
|
2662
|
+
}).then(() => storageQueue).then(() => clearAccess(false));
|
|
2663
|
+
controller.abort(error);
|
|
2664
|
+
emitState("disconnected", error);
|
|
2665
|
+
return cleanup;
|
|
2666
|
+
}
|
|
2667
|
+
async function prepare(current) {
|
|
2668
|
+
const controller = current.controller;
|
|
2669
|
+
const signal = controller.signal;
|
|
2670
|
+
signal.throwIfAborted();
|
|
2671
|
+
if (typeof window === "undefined") throw new ClientError("INVALID_STATE", "Connecting requires a browser");
|
|
2672
|
+
const storage = guardedStorage(signal, storageAppId());
|
|
2673
|
+
let authorizationPopup = null;
|
|
2674
|
+
const authUrl = deps.authUrl ?? DEFAULT_AUTH_URL;
|
|
2675
|
+
const makeAuth = (apiBase) => createInstanceAuthClient({
|
|
2676
|
+
appId: storageAppId(),
|
|
2677
|
+
apiBase,
|
|
2678
|
+
storage,
|
|
2679
|
+
fetchImpl: apiBase ? (input, init) => {
|
|
2680
|
+
const url = new URL(String(input));
|
|
2681
|
+
return createHttpRequest({ apiBase, fetch: fetchFor(signal) })(url.pathname + url.search, init || {});
|
|
2682
|
+
} : fetchFor(signal),
|
|
2683
|
+
origin: window.location.origin,
|
|
2684
|
+
redirectUri: window.location.origin + window.location.pathname,
|
|
2685
|
+
authPageUrl: authUrl,
|
|
2686
|
+
openAuthUrl: (target) => {
|
|
2687
|
+
signal.throwIfAborted();
|
|
2688
|
+
const parsed = new URL(target);
|
|
2689
|
+
parsed.searchParams.set("callbackTransport", authorizationPopup ? "popup" : "same-tab");
|
|
2690
|
+
if (authorizationPopup) authorizationPopup.location.href = parsed.href;
|
|
2691
|
+
else window.location.href = parsed.href;
|
|
2692
|
+
}
|
|
2693
|
+
});
|
|
2694
|
+
let auth = makeAuth();
|
|
2695
|
+
let context = await auth.getContext(bucketId);
|
|
2696
|
+
return { establish: async () => {
|
|
2697
|
+
const publish = async (next) => {
|
|
2698
|
+
signal.throwIfAborted();
|
|
2699
|
+
emitState("connecting");
|
|
2700
|
+
const apiBase = apiOrigin(next.resourceApiUrl || "");
|
|
2701
|
+
auth = makeAuth(apiBase);
|
|
2702
|
+
let access;
|
|
2703
|
+
try {
|
|
2704
|
+
access = await auth.getBucketAccess(bucketId);
|
|
2705
|
+
} catch (error) {
|
|
2706
|
+
signal.throwIfAborted();
|
|
2707
|
+
throw notAuthorized2("Bucket authorization is unusable", error);
|
|
2708
|
+
}
|
|
2709
|
+
if (access.resourceId !== `urn:myfield:bucket:${access.bucketId}`) throw notAuthorized2("Grant and bucket key identify different resources");
|
|
2710
|
+
const getCredential = async (forceRefresh = forceSessionRefresh) => {
|
|
2711
|
+
signal.throwIfAborted();
|
|
2712
|
+
let session;
|
|
2713
|
+
try {
|
|
2714
|
+
session = await auth.getSession(bucketId, { forceRefresh });
|
|
2715
|
+
} catch (error) {
|
|
2716
|
+
signal.throwIfAborted();
|
|
2717
|
+
if (error instanceof ClientError) throw connectionError(error);
|
|
2718
|
+
throw notAuthorized2("Session response is unusable", error);
|
|
2719
|
+
}
|
|
2720
|
+
signal.throwIfAborted();
|
|
2721
|
+
if (!session || session.carrier !== "bearer" || typeof session.token !== "string" || !session.token) throw notAuthorized2("A bearer session is required");
|
|
2722
|
+
forceSessionRefresh = false;
|
|
2723
|
+
return { token: session.token };
|
|
2724
|
+
};
|
|
2725
|
+
await getCredential(current.prompt || forceSessionRefresh);
|
|
2726
|
+
signal.throwIfAborted();
|
|
2727
|
+
remoteClient = createRemoteClient({ apiBase, mfid: access.mfid, bucketId: access.bucketId, getCredential, fetch: fetchFor(signal) });
|
|
2728
|
+
localAccess = { access, signal, fetch: fetchFor(signal), sessionProvider: {
|
|
2729
|
+
getSession: (options) => handleOperation(controller, async () => {
|
|
2730
|
+
signal.throwIfAborted();
|
|
2731
|
+
const session = await auth.getSession(bucketId, options);
|
|
2732
|
+
signal.throwIfAborted();
|
|
2733
|
+
return session;
|
|
2734
|
+
}),
|
|
2735
|
+
onUnauthorized: () => invalidate(controller, notAuthorized2("Bucket authorization is no longer valid"))
|
|
2736
|
+
} };
|
|
2737
|
+
emitState("connected");
|
|
2738
|
+
signal.throwIfAborted();
|
|
2739
|
+
return state;
|
|
2740
|
+
};
|
|
2741
|
+
try {
|
|
2742
|
+
const pageUrl = new URL(window.location.href);
|
|
2743
|
+
if (await ownCallback(pageUrl, storage)) {
|
|
2744
|
+
emitState("connecting");
|
|
2745
|
+
await handleCallback(auth, pageUrl, signal, true);
|
|
2746
|
+
context = await auth.getContext(bucketId);
|
|
2747
|
+
}
|
|
2748
|
+
if (context) return await publish(context);
|
|
2749
|
+
} catch (error) {
|
|
2750
|
+
signal.throwIfAborted();
|
|
2751
|
+
const failure = connectionError(error);
|
|
2752
|
+
if (failure.code !== "NOT_AUTHORIZED" || !current.prompt) throw failure;
|
|
2753
|
+
forceSessionRefresh = true;
|
|
2754
|
+
await queue(signal, () => clearAccess(false));
|
|
2755
|
+
}
|
|
2756
|
+
signal.throwIfAborted();
|
|
2757
|
+
if (!current.prompt) {
|
|
2758
|
+
emitState("disconnected");
|
|
2759
|
+
return "disconnected";
|
|
2760
|
+
}
|
|
2761
|
+
emitState("connecting");
|
|
2762
|
+
auth = makeAuth();
|
|
2763
|
+
await requestAuthorization(auth, storage, authUrl, signal, (popup) => {
|
|
2764
|
+
authorizationPopup = popup;
|
|
2765
|
+
});
|
|
2766
|
+
context = await auth.getContext(bucketId);
|
|
2767
|
+
if (!context) throw notAuthorized2("Authorization context unavailable");
|
|
2768
|
+
return publish(context);
|
|
2769
|
+
} };
|
|
2770
|
+
}
|
|
2771
|
+
function requireConnection() {
|
|
2772
|
+
assertUsable();
|
|
2773
|
+
if (!remoteClient || !connectionController || !localAccess) throw notAuthorized2("Call instance.connect() before Remote operations");
|
|
2774
|
+
return { client: remoteClient, controller: connectionController, access: localAccess.access };
|
|
2775
|
+
}
|
|
2776
|
+
async function invoke(operation) {
|
|
2777
|
+
const { client, controller } = requireConnection();
|
|
2778
|
+
return handleOperation(controller, () => operation(client.getBucket()));
|
|
2779
|
+
}
|
|
2780
|
+
async function handleOperation(controller, operation) {
|
|
2781
|
+
try {
|
|
2782
|
+
return await operation();
|
|
2783
|
+
} catch (error) {
|
|
2784
|
+
if (error instanceof ClientError && isAuthorizationError(error)) {
|
|
2785
|
+
const failure = notAuthorized2(error.message, error);
|
|
2786
|
+
await invalidate(controller, failure);
|
|
2787
|
+
throw failure;
|
|
2788
|
+
}
|
|
2789
|
+
throw error;
|
|
2790
|
+
}
|
|
2791
|
+
}
|
|
2792
|
+
const remote = {
|
|
2793
|
+
async getBucketKey(options) {
|
|
2794
|
+
options?.signal?.throwIfAborted();
|
|
2795
|
+
const { access } = requireConnection();
|
|
2796
|
+
return { bucketId: access.bucketId, keyId: access.keys.keyId, cryptoKey: access.keys.payloadKey };
|
|
2797
|
+
},
|
|
2798
|
+
getCurrent: (...args) => invoke((bucket) => bucket.getCurrent(...args)),
|
|
2799
|
+
getVersion: (...args) => invoke((bucket) => bucket.getVersion(...args)),
|
|
2800
|
+
getVersionMeta: (...args) => invoke((bucket) => bucket.getVersionMeta(...args)),
|
|
2801
|
+
getPayload: (...args) => invoke((bucket) => bucket.getPayload(...args)),
|
|
2802
|
+
commit: (...args) => invoke((bucket) => bucket.commit(...args)),
|
|
2803
|
+
getIndex: (...args) => invoke((bucket) => bucket.getIndex(...args)),
|
|
2804
|
+
listFeed: (...args) => invoke((bucket) => bucket.listFeed(...args)),
|
|
2805
|
+
listVersions: (...args) => invoke((bucket) => bucket.listVersions(...args)),
|
|
2806
|
+
async watchFeed(options) {
|
|
2807
|
+
const { client, controller } = requireConnection();
|
|
2808
|
+
const stream = await handleOperation(controller, () => client.getBucket().watchFeed(options)).catch((error) => {
|
|
2809
|
+
controller.signal.throwIfAborted();
|
|
2810
|
+
throw error;
|
|
2811
|
+
});
|
|
2812
|
+
if (controller.signal.aborted) {
|
|
2813
|
+
await stream.return(void 0);
|
|
2814
|
+
controller.signal.throwIfAborted();
|
|
2815
|
+
}
|
|
2816
|
+
const watched = {
|
|
2817
|
+
async next() {
|
|
2818
|
+
try {
|
|
2819
|
+
controller.signal.throwIfAborted();
|
|
2820
|
+
const next = await handleOperation(controller, () => stream.next());
|
|
2821
|
+
controller.signal.throwIfAborted();
|
|
2822
|
+
return next;
|
|
2823
|
+
} catch (error) {
|
|
2824
|
+
await stream.return(void 0);
|
|
2825
|
+
controller.signal.throwIfAborted();
|
|
2826
|
+
throw error;
|
|
2827
|
+
}
|
|
2828
|
+
},
|
|
2829
|
+
return: (value) => stream.return(value),
|
|
2830
|
+
throw: (error) => stream.throw(error),
|
|
2831
|
+
[Symbol.asyncIterator]() {
|
|
2832
|
+
return watched;
|
|
2833
|
+
}
|
|
2834
|
+
};
|
|
2835
|
+
const asyncDispose = Reflect.get(Symbol, "asyncDispose");
|
|
2836
|
+
if (typeof asyncDispose === "symbol") {
|
|
2837
|
+
Object.defineProperty(watched, asyncDispose, { value: async () => {
|
|
2838
|
+
await stream.return(void 0);
|
|
2839
|
+
} });
|
|
2840
|
+
}
|
|
2841
|
+
return watched;
|
|
2842
|
+
}
|
|
2843
|
+
};
|
|
2844
|
+
function start(prompt, args) {
|
|
2845
|
+
if (args.length) return Promise.reject(new ClientError("INVALID_INPUT", "Connection methods take no arguments"));
|
|
2846
|
+
try {
|
|
2847
|
+
assertUsable();
|
|
2848
|
+
} catch (error) {
|
|
2849
|
+
return Promise.reject(error);
|
|
2850
|
+
}
|
|
2851
|
+
if (remoteClient) return Promise.resolve("connected");
|
|
2852
|
+
if (flow) {
|
|
2853
|
+
const current2 = flow;
|
|
2854
|
+
if (prompt && !current2.prompt) {
|
|
2855
|
+
const waitingGeneration = generation;
|
|
2856
|
+
return current2.promise.catch((error) => {
|
|
2857
|
+
if (!(error instanceof ClientError) || error.code !== "NOT_AUTHORIZED") throw error;
|
|
2858
|
+
}).then(() => {
|
|
2859
|
+
if (generation !== waitingGeneration || disposed) throw new DOMException("Connection cancelled", "AbortError");
|
|
2860
|
+
return start(prompt, args);
|
|
2861
|
+
});
|
|
2862
|
+
}
|
|
2863
|
+
return flow.promise;
|
|
2864
|
+
}
|
|
2865
|
+
const controller = new AbortController();
|
|
2866
|
+
const current = { controller, prompt, promise: null };
|
|
2867
|
+
connectionController = controller;
|
|
2868
|
+
current.promise = Promise.all([cleanup, keyChanges]).then(() => prepare(current)).then((prepared) => prepared.establish()).catch(async (error) => {
|
|
2869
|
+
if (controller.signal.aborted) throw controller.signal.reason;
|
|
2870
|
+
const failure = connectionError(error);
|
|
2871
|
+
controller.abort(failure);
|
|
2872
|
+
if (failure.code === "NOT_AUTHORIZED") {
|
|
2873
|
+
forceSessionRefresh = true;
|
|
2874
|
+
cleanup = cleanup.catch(() => {
|
|
2875
|
+
}).then(() => storageQueue).then(() => clearAccess(false));
|
|
2876
|
+
await cleanup;
|
|
2877
|
+
}
|
|
2878
|
+
if (connectionController === controller) {
|
|
2879
|
+
connectionController = null;
|
|
2880
|
+
remoteClient = null;
|
|
2881
|
+
localAccess = null;
|
|
2882
|
+
emitState("disconnected", failure);
|
|
2883
|
+
}
|
|
2884
|
+
if (failure.code === "INVALID_INSTANCE_KEY" && !current.prompt) return "disconnected";
|
|
2885
|
+
throw failure;
|
|
2886
|
+
}).finally(() => {
|
|
2887
|
+
if (flow === current) flow = null;
|
|
2888
|
+
});
|
|
2889
|
+
flow = current;
|
|
2890
|
+
return current.promise;
|
|
2891
|
+
}
|
|
2892
|
+
function stop(reason) {
|
|
2893
|
+
generation++;
|
|
2894
|
+
const controller = connectionController;
|
|
2895
|
+
connectionController = null;
|
|
2896
|
+
remoteClient = null;
|
|
2897
|
+
localAccess = null;
|
|
2898
|
+
flow = null;
|
|
2899
|
+
controller?.abort(reason);
|
|
2900
|
+
browserAuth.close();
|
|
2901
|
+
}
|
|
2902
|
+
return {
|
|
2903
|
+
get state() {
|
|
2904
|
+
return state;
|
|
2905
|
+
},
|
|
2906
|
+
get active() {
|
|
2907
|
+
return Boolean(remoteClient || flow);
|
|
2908
|
+
},
|
|
2909
|
+
getLocalAccess() {
|
|
2910
|
+
assertUsable();
|
|
2911
|
+
if (!localAccess) throw notAuthorized2("Connect before using Local synchronization");
|
|
2912
|
+
return localAccess;
|
|
2913
|
+
},
|
|
2914
|
+
report(error) {
|
|
2915
|
+
if (!disposed) emitState(state, error);
|
|
2916
|
+
},
|
|
2917
|
+
fail(error, signal) {
|
|
2918
|
+
if (connectionController?.signal === signal) return invalidate(connectionController, connectionError(error));
|
|
2919
|
+
return Promise.resolve();
|
|
2920
|
+
},
|
|
2921
|
+
on(event, listener) {
|
|
2922
|
+
assertRuntime();
|
|
2923
|
+
if (event !== "state" || typeof listener !== "function") throw new ClientError("INVALID_INPUT", "A state listener is required");
|
|
2924
|
+
listeners.add(listener);
|
|
2925
|
+
return () => {
|
|
2926
|
+
listeners.delete(listener);
|
|
2927
|
+
};
|
|
2928
|
+
},
|
|
2929
|
+
remote: { getBucket: (...args) => {
|
|
2930
|
+
assertUsable();
|
|
2931
|
+
if (args.length) throw new ClientError("INVALID_INPUT", "getBucket takes no arguments");
|
|
2932
|
+
return remote;
|
|
2933
|
+
} },
|
|
2934
|
+
async getKey() {
|
|
2935
|
+
if (disposed) throw new ClientError("INVALID_STATE", "Instance runtime has stopped");
|
|
2936
|
+
const appId = storageAppId();
|
|
2937
|
+
await keyChanges;
|
|
2938
|
+
const key = await createInstanceKeyStore(deps.auth, appId).active();
|
|
2939
|
+
return key ? toInstanceKey(key) : null;
|
|
2940
|
+
},
|
|
2941
|
+
createKey: () => changeKey(async (store) => toInstanceKey(await store.create(assertKeyMutable))),
|
|
2942
|
+
importKey: (key) => changeKey(async (store) => {
|
|
2943
|
+
const validated = await validateInstanceKey(key);
|
|
2944
|
+
assertKeyMutable();
|
|
2945
|
+
await store.import(validated);
|
|
2946
|
+
}),
|
|
2947
|
+
removeKey: () => changeKey((store) => store.remove()),
|
|
2948
|
+
resume: (...args) => start(false, args),
|
|
2949
|
+
connect: (...args) => start(true, args),
|
|
2950
|
+
disconnect() {
|
|
2951
|
+
try {
|
|
2952
|
+
assertUsable();
|
|
2953
|
+
} catch (error) {
|
|
2954
|
+
return Promise.reject(error);
|
|
2955
|
+
}
|
|
2956
|
+
stop(new DOMException("Connection disconnected", "AbortError"));
|
|
2957
|
+
if (disconnecting) {
|
|
2958
|
+
emitState("disconnected");
|
|
2959
|
+
return disconnecting;
|
|
2960
|
+
}
|
|
2961
|
+
const operation = cleanup.catch(() => {
|
|
2962
|
+
}).then(() => storageQueue).then(() => clearAccess(true)).finally(() => {
|
|
2963
|
+
if (disconnecting === operation) disconnecting = null;
|
|
2964
|
+
});
|
|
2965
|
+
cleanup = operation;
|
|
2966
|
+
disconnecting = operation;
|
|
2967
|
+
emitState("disconnected");
|
|
2968
|
+
return operation;
|
|
2969
|
+
},
|
|
2970
|
+
dispose() {
|
|
2971
|
+
disposed = true;
|
|
2972
|
+
stop(new DOMException("Instance runtime stopped", "AbortError"));
|
|
2973
|
+
state = "disconnected";
|
|
2974
|
+
listeners.clear();
|
|
2975
|
+
}
|
|
2976
|
+
};
|
|
2977
|
+
}
|
|
1710
2978
|
|
|
1711
2979
|
// src/facade.ts
|
|
1712
|
-
var DEFAULT_AUTH_BASE = "https://myfield.one/auth/";
|
|
1713
|
-
var DEFAULT_API_BASE = "https://api.myfield.one";
|
|
1714
2980
|
var INDEX_OBJECT_ID = "~index";
|
|
2981
|
+
var ID_FIELD = "~id";
|
|
1715
2982
|
var DELETED_FIELD = "~deleted";
|
|
1716
2983
|
var RESERVED_PREFIX = "~";
|
|
1717
|
-
|
|
1718
|
-
|
|
2984
|
+
var instanceTestCleanup = /* @__PURE__ */ new WeakMap();
|
|
2985
|
+
function createInstance(input = {}, ...extra) {
|
|
2986
|
+
if (typeof input === "string" && extra.length) throw new ClientError("INVALID_INPUT", "createInstance accepts an appId or an options object, without additional arguments");
|
|
2987
|
+
const options = typeof input === "string" ? { appId: input } : input;
|
|
2988
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) throw new ClientError("INVALID_INPUT", "Instance options are required");
|
|
2989
|
+
if (["authStorage", "dbName", "storeName"].some((key) => key in options)) throw new ClientError("INVALID_INPUT", "Custom database configuration is not supported");
|
|
2990
|
+
const authUrl = options.authUrl === void 0 ? void 0 : normalizeAuthUrl(options.authUrl);
|
|
2991
|
+
const explicitAppId = options.appId === void 0 ? void 0 : resolveAppId(options.appId);
|
|
2992
|
+
let resolvedAppId = explicitAppId;
|
|
2993
|
+
const getAppId = () => resolvedAppId ??= resolveAppId();
|
|
2994
|
+
const namespace = normalizeNamespace(options.namespace === void 0 ? explicitAppId : String(options.namespace).trim());
|
|
1719
2995
|
const storageKind = options.storage || "indexeddb";
|
|
1720
2996
|
const baseAdapter = storageKind === "memory" ? createNamespacedMemoryStorageAdapter(`myfield-sdk:${namespace}`) : createIndexedDbStorageAdapter({ dbName: `myfield-sdk:${namespace}` });
|
|
1721
2997
|
const authAdapter = prefixedAdapter(baseAdapter, "auth:");
|
|
1722
2998
|
const buckets = /* @__PURE__ */ new Map();
|
|
1723
|
-
|
|
2999
|
+
const connections = /* @__PURE__ */ new Map();
|
|
3000
|
+
const connectionDeps = {
|
|
3001
|
+
getAppId,
|
|
3002
|
+
data: baseAdapter,
|
|
3003
|
+
auth: authAdapter,
|
|
3004
|
+
hasActiveConnection: () => connection.active || [...connections.values()].some((value) => value.active),
|
|
3005
|
+
persistent: storageKind !== "memory",
|
|
3006
|
+
authUrl
|
|
3007
|
+
};
|
|
3008
|
+
const connection = createInstanceConnection(connectionDeps);
|
|
3009
|
+
let disposed = false;
|
|
3010
|
+
function getLocalBucket(bucketId) {
|
|
3011
|
+
if (disposed) throw new ClientError("INVALID_STATE", "Instance runtime has stopped");
|
|
3012
|
+
const existing = buckets.get(bucketId);
|
|
3013
|
+
if (existing) return existing;
|
|
3014
|
+
let isDefault = false;
|
|
3015
|
+
try {
|
|
3016
|
+
isDefault = bucketId === getAppId();
|
|
3017
|
+
} catch {
|
|
3018
|
+
}
|
|
3019
|
+
let resource = isDefault ? connection : connections.get(bucketId);
|
|
3020
|
+
if (!resource) {
|
|
3021
|
+
resource = createInstanceConnection({ ...connectionDeps, getBucketId: () => bucketId });
|
|
3022
|
+
connections.set(bucketId, resource);
|
|
3023
|
+
}
|
|
3024
|
+
const owned = resource;
|
|
3025
|
+
const runtime = createBucketFacade({ bucketId, dataAdapter: baseAdapter, connection: owned, onDispose: () => {
|
|
3026
|
+
if (buckets.get(bucketId) === runtime) buckets.delete(bucketId);
|
|
3027
|
+
if (owned !== connection && connections.get(bucketId) === owned) {
|
|
3028
|
+
connections.delete(bucketId);
|
|
3029
|
+
owned.dispose();
|
|
3030
|
+
}
|
|
3031
|
+
} });
|
|
3032
|
+
buckets.set(bucketId, runtime);
|
|
3033
|
+
return runtime;
|
|
3034
|
+
}
|
|
3035
|
+
function startLocal(prompt, args) {
|
|
3036
|
+
try {
|
|
3037
|
+
if (args.length > 1) throw new ClientError("INVALID_INPUT", "Connection accepts one options object");
|
|
3038
|
+
const options2 = args[0];
|
|
3039
|
+
if (options2 !== void 0 && (!options2 || typeof options2 !== "object" || Array.isArray(options2) || Object.keys(options2).some((key) => key !== "autoSync") || "autoSync" in options2 && options2.autoSync !== void 0 && typeof options2.autoSync !== "boolean")) {
|
|
3040
|
+
throw new ClientError("INVALID_INPUT", "Only autoSync is supported");
|
|
3041
|
+
}
|
|
3042
|
+
const runtime = getLocalBucket(getAppId());
|
|
3043
|
+
return runtime.connectInstance(prompt, options2?.autoSync);
|
|
3044
|
+
} catch (error) {
|
|
3045
|
+
return Promise.reject(error);
|
|
3046
|
+
}
|
|
3047
|
+
}
|
|
3048
|
+
const instance = {
|
|
1724
3049
|
namespace,
|
|
3050
|
+
remote: connection.remote,
|
|
3051
|
+
get state() {
|
|
3052
|
+
return connection.state;
|
|
3053
|
+
},
|
|
3054
|
+
getBucket: () => getLocalBucket(getAppId()).bucket,
|
|
3055
|
+
resume: (...args) => startLocal(false, args),
|
|
3056
|
+
on: connection.on,
|
|
3057
|
+
connect: (...args) => startLocal(true, args),
|
|
3058
|
+
getKey: connection.getKey,
|
|
3059
|
+
createKey: connection.createKey,
|
|
3060
|
+
importKey: connection.importKey,
|
|
3061
|
+
removeKey: connection.removeKey,
|
|
3062
|
+
disconnect: connection.disconnect,
|
|
1725
3063
|
createBucket(bucketOptions) {
|
|
1726
3064
|
const bucketId = String(bucketOptions?.id || "").trim();
|
|
1727
3065
|
if (!bucketId) throw new Error("bucket id is required");
|
|
1728
3066
|
if (!isValidBucketId(bucketId)) throw new Error("invalid bucketId");
|
|
1729
|
-
|
|
1730
|
-
if (existing) return existing;
|
|
1731
|
-
const bucket = createBucketFacade({ namespace, bucketId, dataAdapter: baseAdapter, authAdapter });
|
|
1732
|
-
buckets.set(bucketId, bucket);
|
|
1733
|
-
return bucket;
|
|
3067
|
+
return getLocalBucket(bucketId).bucket;
|
|
1734
3068
|
}
|
|
1735
3069
|
};
|
|
3070
|
+
if (explicitAppId) getLocalBucket(explicitAppId);
|
|
3071
|
+
instanceTestCleanup.set(instance, () => {
|
|
3072
|
+
disposed = true;
|
|
3073
|
+
for (const runtime of buckets.values()) runtime.bucket.dispose();
|
|
3074
|
+
for (const resource of connections.values()) resource.dispose();
|
|
3075
|
+
connection.dispose();
|
|
3076
|
+
});
|
|
3077
|
+
return instance;
|
|
1736
3078
|
}
|
|
1737
3079
|
function createBucketFacade(deps) {
|
|
1738
|
-
const { bucketId, dataAdapter,
|
|
1739
|
-
const endpointsKey = `meta:${bucketId}:endpoints`;
|
|
3080
|
+
const { bucketId, dataAdapter, connection } = deps;
|
|
1740
3081
|
const actorKey = `meta:actor`;
|
|
1741
|
-
let state =
|
|
3082
|
+
let state = connection.state;
|
|
1742
3083
|
let client = null;
|
|
1743
3084
|
let clientInit = null;
|
|
1744
3085
|
let liveTransport = null;
|
|
@@ -1746,14 +3087,11 @@ function createBucketFacade(deps) {
|
|
|
1746
3087
|
let autoSync = true;
|
|
1747
3088
|
let syncIntervalMs;
|
|
1748
3089
|
let disposed = false;
|
|
1749
|
-
let
|
|
1750
|
-
let
|
|
1751
|
-
let
|
|
1752
|
-
let
|
|
1753
|
-
let
|
|
1754
|
-
let pendingConnect = null;
|
|
1755
|
-
let pendingConnectDone = null;
|
|
1756
|
-
let popupMessageListener = null;
|
|
3090
|
+
let connectedAccess = null;
|
|
3091
|
+
let activating = null;
|
|
3092
|
+
let verifiedAccess = null;
|
|
3093
|
+
let connecting = null;
|
|
3094
|
+
let lastFailure = null;
|
|
1757
3095
|
const listeners = { state: /* @__PURE__ */ new Set(), change: /* @__PURE__ */ new Set() };
|
|
1758
3096
|
function emitState(next, detail) {
|
|
1759
3097
|
if (state !== next) {
|
|
@@ -1767,12 +3105,6 @@ function createBucketFacade(deps) {
|
|
|
1767
3105
|
if (objectId.startsWith(RESERVED_PREFIX)) return;
|
|
1768
3106
|
for (const handler of listeners.change) handler(objectId);
|
|
1769
3107
|
}
|
|
1770
|
-
function settlePendingConnect() {
|
|
1771
|
-
if (!pendingConnect) return;
|
|
1772
|
-
const settle = pendingConnect;
|
|
1773
|
-
pendingConnect = null;
|
|
1774
|
-
settle.resolve(state);
|
|
1775
|
-
}
|
|
1776
3108
|
function ensureClient() {
|
|
1777
3109
|
if (clientInit) return clientInit;
|
|
1778
3110
|
clientInit = (async () => {
|
|
@@ -1794,25 +3126,58 @@ function createBucketFacade(deps) {
|
|
|
1794
3126
|
push(wireObjectId, plaintext, expectedHeadVersionId) {
|
|
1795
3127
|
if (!liveTransport) return Promise.reject(new OfflineError());
|
|
1796
3128
|
return liveTransport.push(wireObjectId, plaintext, expectedHeadVersionId);
|
|
3129
|
+
},
|
|
3130
|
+
listHeads() {
|
|
3131
|
+
if (!liveTransport?.listHeads) return Promise.reject(new OfflineError());
|
|
3132
|
+
return liveTransport.listHeads();
|
|
1797
3133
|
}
|
|
1798
3134
|
},
|
|
1799
3135
|
storage: dataAdapter,
|
|
3136
|
+
autoSync: autoSync && Boolean(liveTransport),
|
|
1800
3137
|
actorId,
|
|
3138
|
+
localOnlyObjectIds: [INDEX_OBJECT_ID],
|
|
3139
|
+
validateRemote: assertRemoteObjectId,
|
|
1801
3140
|
wireObjectId: (appObjectId) => {
|
|
1802
3141
|
if (!liveWireId) return Promise.reject(new OfflineError());
|
|
1803
3142
|
return liveWireId(appObjectId);
|
|
1804
3143
|
},
|
|
1805
3144
|
storagePrefix: `data:${bucketId}`,
|
|
1806
|
-
onChange:
|
|
3145
|
+
onChange: onClientChange,
|
|
1807
3146
|
onSyncError: (objectId, error) => {
|
|
1808
3147
|
if (error instanceof OfflineError) return;
|
|
1809
|
-
|
|
3148
|
+
const detail = `sync error${objectId ? ` (${objectId})` : ""}: ${formatError(error)}`;
|
|
3149
|
+
if (connection.state === "connected") connection.report(localError(error, detail));
|
|
3150
|
+
else emitState(state, detail);
|
|
1810
3151
|
}
|
|
1811
3152
|
});
|
|
1812
3153
|
return client;
|
|
1813
3154
|
})();
|
|
1814
3155
|
return clientInit;
|
|
1815
3156
|
}
|
|
3157
|
+
function assertRemoteObjectId(objectId, doc) {
|
|
3158
|
+
if (objectId.startsWith(RESERVED_PREFIX) || doc.t !== "lww-map") return;
|
|
3159
|
+
const remoteId = doc.fields[ID_FIELD]?.v;
|
|
3160
|
+
if (remoteId !== void 0 && remoteId !== objectId) throw new Error(`object id mismatch for ${objectId}`);
|
|
3161
|
+
}
|
|
3162
|
+
const pendingIndexRefreshes = /* @__PURE__ */ new Set();
|
|
3163
|
+
function onClientChange(objectId, source) {
|
|
3164
|
+
if (objectId.startsWith(RESERVED_PREFIX)) return;
|
|
3165
|
+
if (source === "local") {
|
|
3166
|
+
emitChange(objectId);
|
|
3167
|
+
return;
|
|
3168
|
+
}
|
|
3169
|
+
const refresh = refreshIndexEntry(objectId).catch((error) => emitState(state, `index update failed (${objectId}): ${formatError(error)}`)).finally(() => {
|
|
3170
|
+
pendingIndexRefreshes.delete(refresh);
|
|
3171
|
+
emitChange(objectId);
|
|
3172
|
+
});
|
|
3173
|
+
pendingIndexRefreshes.add(refresh);
|
|
3174
|
+
}
|
|
3175
|
+
async function refreshIndexEntry(objectId) {
|
|
3176
|
+
const c = await ensureClient();
|
|
3177
|
+
const raw = await c.getFields(objectId);
|
|
3178
|
+
const latest = await c.lastModified(objectId);
|
|
3179
|
+
await upsertIndexEntry(objectId, raw?.[DELETED_FIELD] === true, latest ?? Date.now());
|
|
3180
|
+
}
|
|
1816
3181
|
function assertObjectId(objectId) {
|
|
1817
3182
|
if (typeof objectId !== "string" || !objectId) throw new Error("objectId must be a non-empty string");
|
|
1818
3183
|
if (objectId.startsWith(RESERVED_PREFIX)) throw new Error(`object ids starting with "${RESERVED_PREFIX}" are reserved`);
|
|
@@ -1823,10 +3188,16 @@ function createBucketFacade(deps) {
|
|
|
1823
3188
|
if (name.startsWith(RESERVED_PREFIX)) throw new Error(`field names starting with "${RESERVED_PREFIX}" are reserved`);
|
|
1824
3189
|
}
|
|
1825
3190
|
}
|
|
1826
|
-
|
|
3191
|
+
let lastIndexRev = 0;
|
|
3192
|
+
async function upsertIndexEntry(objectId, deleted, updatedAtMs = Date.now()) {
|
|
1827
3193
|
const c = await ensureClient();
|
|
3194
|
+
lastIndexRev = Math.max(lastIndexRev + 1, Date.now());
|
|
1828
3195
|
await c.setFields(INDEX_OBJECT_ID, {
|
|
1829
|
-
[objectId]: {
|
|
3196
|
+
[objectId]: {
|
|
3197
|
+
updatedAt: new Date(updatedAtMs).toISOString(),
|
|
3198
|
+
rev: lastIndexRev,
|
|
3199
|
+
...deleted ? { deleted: true } : {}
|
|
3200
|
+
}
|
|
1830
3201
|
});
|
|
1831
3202
|
}
|
|
1832
3203
|
function publicView(raw) {
|
|
@@ -1845,6 +3216,9 @@ function createBucketFacade(deps) {
|
|
|
1845
3216
|
}
|
|
1846
3217
|
return changed;
|
|
1847
3218
|
}
|
|
3219
|
+
function withObjectId(updates, objectId, known) {
|
|
3220
|
+
return known[ID_FIELD] === objectId ? updates : { ...updates, [ID_FIELD]: objectId };
|
|
3221
|
+
}
|
|
1848
3222
|
async function put(objectId, object) {
|
|
1849
3223
|
assertObjectId(objectId);
|
|
1850
3224
|
assertFieldNames(object);
|
|
@@ -1852,11 +3226,11 @@ function createBucketFacade(deps) {
|
|
|
1852
3226
|
const known = await c.getFields(objectId) || {};
|
|
1853
3227
|
const updates = { ...object };
|
|
1854
3228
|
for (const name of Object.keys(known)) {
|
|
1855
|
-
if (!(name in object)) updates[name] = void 0;
|
|
3229
|
+
if (!(name in object) && name !== ID_FIELD) updates[name] = void 0;
|
|
1856
3230
|
}
|
|
1857
3231
|
const changed = await dropUnchanged(updates, known);
|
|
1858
3232
|
if (Object.keys(changed).length === 0) return;
|
|
1859
|
-
await c.setFields(objectId, changed);
|
|
3233
|
+
await c.setFields(objectId, withObjectId(changed, objectId, known));
|
|
1860
3234
|
await upsertIndexEntry(objectId, false);
|
|
1861
3235
|
}
|
|
1862
3236
|
async function update(objectId, fields) {
|
|
@@ -1868,7 +3242,7 @@ function createBucketFacade(deps) {
|
|
|
1868
3242
|
if (DELETED_FIELD in known) updates[DELETED_FIELD] = void 0;
|
|
1869
3243
|
const changed = await dropUnchanged(updates, known);
|
|
1870
3244
|
if (Object.keys(changed).length === 0) return;
|
|
1871
|
-
await c.setFields(objectId, changed);
|
|
3245
|
+
await c.setFields(objectId, withObjectId(changed, objectId, known));
|
|
1872
3246
|
await upsertIndexEntry(objectId, false);
|
|
1873
3247
|
}
|
|
1874
3248
|
async function getObject(objectId) {
|
|
@@ -1893,7 +3267,7 @@ function createBucketFacade(deps) {
|
|
|
1893
3267
|
for (const name of Object.keys(known)) {
|
|
1894
3268
|
if (!name.startsWith(RESERVED_PREFIX)) updates[name] = void 0;
|
|
1895
3269
|
}
|
|
1896
|
-
await c.setFields(objectId, updates);
|
|
3270
|
+
await c.setFields(objectId, withObjectId(updates, objectId, known));
|
|
1897
3271
|
await upsertIndexEntry(objectId, true);
|
|
1898
3272
|
}
|
|
1899
3273
|
async function list(options) {
|
|
@@ -1914,186 +3288,160 @@ function createBucketFacade(deps) {
|
|
|
1914
3288
|
}
|
|
1915
3289
|
async function sync() {
|
|
1916
3290
|
if (!liveTransport) throw new NotConnectedError();
|
|
3291
|
+
await runSyncPass();
|
|
3292
|
+
}
|
|
3293
|
+
async function runSyncPass() {
|
|
1917
3294
|
const c = await ensureClient();
|
|
1918
|
-
const
|
|
1919
|
-
|
|
1920
|
-
|
|
3295
|
+
const wireId = liveWireId;
|
|
3296
|
+
if (!wireId) throw new OfflineError();
|
|
3297
|
+
let legacyIndex;
|
|
3298
|
+
await c.syncPass({
|
|
3299
|
+
skipWireIds: [await wireId(INDEX_OBJECT_ID)],
|
|
3300
|
+
resolveUnknown: async (wireObjectId, versionId) => {
|
|
3301
|
+
const doc = await c.pullDoc(wireObjectId, versionId);
|
|
3302
|
+
if (!doc || doc.t !== "lww-map") return null;
|
|
3303
|
+
const id = doc.fields[ID_FIELD]?.v;
|
|
3304
|
+
if (typeof id === "string") return id;
|
|
3305
|
+
if (legacyIndex === void 0) {
|
|
3306
|
+
const legacy = await c.pullRemoteDoc(INDEX_OBJECT_ID);
|
|
3307
|
+
legacyIndex = legacy?.t === "lww-map" ? legacy.fields : null;
|
|
3308
|
+
}
|
|
3309
|
+
for (const candidate of Object.keys(legacyIndex || {})) {
|
|
3310
|
+
if (!candidate.startsWith(RESERVED_PREFIX) && await wireId(candidate) === wireObjectId) return candidate;
|
|
3311
|
+
}
|
|
3312
|
+
return null;
|
|
3313
|
+
}
|
|
3314
|
+
});
|
|
3315
|
+
await writeMissingObjectIds(c);
|
|
3316
|
+
await Promise.all(pendingIndexRefreshes);
|
|
3317
|
+
}
|
|
3318
|
+
async function writeMissingObjectIds(c) {
|
|
3319
|
+
const upgraded = [];
|
|
3320
|
+
for (const id of await c.knownObjectIds()) {
|
|
3321
|
+
if (id.startsWith(RESERVED_PREFIX)) continue;
|
|
1921
3322
|
const raw = await c.getFields(id);
|
|
1922
|
-
|
|
3323
|
+
if (!raw || raw[ID_FIELD] === id) continue;
|
|
3324
|
+
await c.setFields(id, { [ID_FIELD]: id });
|
|
3325
|
+
upgraded.push(id);
|
|
1923
3326
|
}
|
|
1924
|
-
|
|
3327
|
+
for (const id of upgraded) await c.flush(id);
|
|
1925
3328
|
}
|
|
1926
3329
|
function startAutoSync() {
|
|
1927
3330
|
if (!autoSync || !client) return;
|
|
1928
|
-
client.
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
if (authClient) return authClient;
|
|
1941
|
-
if (typeof window === "undefined") throw new Error("connect()/resume() require a browser environment");
|
|
1942
|
-
const origin = window.location.origin;
|
|
1943
|
-
const authPageUrl = normalizeAuthBase(endpoints.authBase);
|
|
1944
|
-
authPageOrigin = new URL(authPageUrl, window.location.href).origin;
|
|
1945
|
-
const baseOptions = {
|
|
1946
|
-
appId: new URL(origin).hostname,
|
|
1947
|
-
apiBase: endpoints.apiBase,
|
|
1948
|
-
redirectUri: origin + window.location.pathname,
|
|
1949
|
-
origin,
|
|
1950
|
-
storage: authAdapter
|
|
1951
|
-
};
|
|
1952
|
-
authClient = createInstanceAuthClient({
|
|
1953
|
-
...baseOptions,
|
|
1954
|
-
authPageUrl: addCallbackTransport(authPageUrl, "same-tab")
|
|
3331
|
+
client.start({ run: runSyncPass, ...syncIntervalMs !== void 0 ? { intervalMs: syncIntervalMs } : {} });
|
|
3332
|
+
}
|
|
3333
|
+
function bindTransport() {
|
|
3334
|
+
const current = connection.getLocalAccess();
|
|
3335
|
+
if (current === connectedAccess) return current;
|
|
3336
|
+
connectedAccess = current;
|
|
3337
|
+
liveTransport = new BucketTransport({
|
|
3338
|
+
apiBase: current.access.resourceApiUrl,
|
|
3339
|
+
mfid: current.access.mfid,
|
|
3340
|
+
keys: current.access.keys,
|
|
3341
|
+
sessionProvider: current.sessionProvider,
|
|
3342
|
+
fetch: current.fetch
|
|
1955
3343
|
});
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
3344
|
+
liveWireId = current.access.keys.wireObjectId;
|
|
3345
|
+
return current;
|
|
3346
|
+
}
|
|
3347
|
+
function stopLocal() {
|
|
3348
|
+
liveTransport = null;
|
|
3349
|
+
liveWireId = null;
|
|
3350
|
+
connectedAccess = null;
|
|
3351
|
+
verifiedAccess = null;
|
|
3352
|
+
activating = null;
|
|
3353
|
+
client?.stop();
|
|
3354
|
+
}
|
|
3355
|
+
let connectionState = connection.state;
|
|
3356
|
+
const stopState = connection.on("state", (next, error) => {
|
|
3357
|
+
if (disposed) return;
|
|
3358
|
+
const entered = next === "connected" && connectionState !== "connected";
|
|
3359
|
+
connectionState = next;
|
|
3360
|
+
if (next === "disconnected" && error) lastFailure = error;
|
|
3361
|
+
if (next === "connected") bindTransport();
|
|
3362
|
+
else stopLocal();
|
|
3363
|
+
emitState(next, error ? formatError(error) : void 0);
|
|
3364
|
+
if (entered) void reconcile().catch(() => {
|
|
1960
3365
|
});
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
authPopupPollTimer = null;
|
|
1969
|
-
}
|
|
1970
|
-
}
|
|
1971
|
-
function tryOpenPopupShell() {
|
|
1972
|
-
clearPopupMonitor();
|
|
1973
|
-
authPopupWindow?.close();
|
|
1974
|
-
const width = 520;
|
|
1975
|
-
const height = 720;
|
|
1976
|
-
const left = Math.max(0, Math.floor(window.screenX + (window.outerWidth - width) / 2));
|
|
1977
|
-
const top = Math.max(0, Math.floor(window.screenY + (window.outerHeight - height) / 2));
|
|
1978
|
-
authPopupWindow = window.open(
|
|
1979
|
-
"about:blank",
|
|
1980
|
-
"myfield-sdk-auth",
|
|
1981
|
-
`popup=yes,width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`
|
|
1982
|
-
);
|
|
1983
|
-
if (!authPopupWindow || authPopupWindow.closed) {
|
|
1984
|
-
authPopupWindow = null;
|
|
1985
|
-
return false;
|
|
1986
|
-
}
|
|
1987
|
-
try {
|
|
1988
|
-
authPopupWindow.document.title = "Opening Myfield...";
|
|
1989
|
-
authPopupWindow.document.body.textContent = "Opening Myfield authorization...";
|
|
1990
|
-
} catch {
|
|
3366
|
+
});
|
|
3367
|
+
if (state === "connected") bindTransport();
|
|
3368
|
+
function activate() {
|
|
3369
|
+
const current = bindTransport();
|
|
3370
|
+
if (verifiedAccess === current) {
|
|
3371
|
+
startAutoSync();
|
|
3372
|
+
return Promise.resolve();
|
|
1991
3373
|
}
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
3374
|
+
if (activating) return activating;
|
|
3375
|
+
const operation = (async () => {
|
|
3376
|
+
const transport = liveTransport;
|
|
3377
|
+
await ensureClient();
|
|
3378
|
+
current.signal.throwIfAborted();
|
|
3379
|
+
await transport.pullHead(await current.access.keys.wireObjectId(INDEX_OBJECT_ID));
|
|
3380
|
+
current.signal.throwIfAborted();
|
|
3381
|
+
if (disposed) return;
|
|
3382
|
+
verifiedAccess = current;
|
|
3383
|
+
startAutoSync();
|
|
3384
|
+
})().catch(async (error) => {
|
|
3385
|
+
current.signal.throwIfAborted();
|
|
3386
|
+
if (disposed) return;
|
|
3387
|
+
const failure = localError(error);
|
|
3388
|
+
if (failure.retryable) {
|
|
3389
|
+
connection.report(failure);
|
|
3390
|
+
startAutoSync();
|
|
3391
|
+
return;
|
|
1999
3392
|
}
|
|
2000
|
-
|
|
2001
|
-
|
|
3393
|
+
await connection.fail(failure, current.signal);
|
|
3394
|
+
throw failure;
|
|
3395
|
+
}).finally(() => {
|
|
3396
|
+
if (activating === operation) activating = null;
|
|
3397
|
+
});
|
|
3398
|
+
activating = operation;
|
|
3399
|
+
return operation;
|
|
2002
3400
|
}
|
|
2003
|
-
function
|
|
2004
|
-
if (
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
authPopupWindow.location.href = url;
|
|
2009
|
-
authPopupWindow.focus();
|
|
2010
|
-
} catch {
|
|
2011
|
-
authPopupWindow = window.open(url, "myfield-sdk-auth");
|
|
2012
|
-
if (!authPopupWindow) throw new Error("authorization popup was blocked");
|
|
3401
|
+
function reconcile() {
|
|
3402
|
+
if (disposed) return Promise.resolve();
|
|
3403
|
+
if (!autoSync || !liveTransport) {
|
|
3404
|
+
client?.stop();
|
|
3405
|
+
return Promise.resolve();
|
|
2013
3406
|
}
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
return callback;
|
|
2036
|
-
} catch (error) {
|
|
2037
|
-
emitState("disconnected", formatError(error));
|
|
2038
|
-
settlePendingConnect();
|
|
2039
|
-
return null;
|
|
3407
|
+
return activate();
|
|
3408
|
+
}
|
|
3409
|
+
function connectInstance(prompt, enabled) {
|
|
3410
|
+
if (enabled !== void 0) bucket.setAutoSync(enabled);
|
|
3411
|
+
const operation = prompt ? connection.connect() : connection.resume();
|
|
3412
|
+
if (connecting?.operation === operation) return connecting.result;
|
|
3413
|
+
const done = operation.then(async (next) => {
|
|
3414
|
+
if (next === "connected") await reconcile();
|
|
3415
|
+
return next;
|
|
3416
|
+
}).finally(() => {
|
|
3417
|
+
if (connecting?.result === done) connecting = null;
|
|
3418
|
+
});
|
|
3419
|
+
connecting = { operation, result: done };
|
|
3420
|
+
return done;
|
|
3421
|
+
}
|
|
3422
|
+
async function connectLegacy(prompt) {
|
|
3423
|
+
if (disposed) throw new Error("disposed");
|
|
3424
|
+
await ensureClient();
|
|
3425
|
+
if (typeof window === "undefined") {
|
|
3426
|
+
if (!prompt) return state;
|
|
3427
|
+
throw new ClientError("INVALID_STATE", "Connecting requires a browser");
|
|
2040
3428
|
}
|
|
2041
|
-
|
|
2042
|
-
async function establish(sessionOptions = {}) {
|
|
2043
|
-
emitState("connecting");
|
|
3429
|
+
let next;
|
|
2044
3430
|
try {
|
|
2045
|
-
|
|
2046
|
-
const auth = await ensureAuthClients(endpoints);
|
|
2047
|
-
const c = await ensureClient();
|
|
2048
|
-
await auth.getSession(bucketId, sessionOptions);
|
|
2049
|
-
const access = await auth.getBucketAccess(bucketId);
|
|
2050
|
-
if (!access.resourceApiUrl) throw new Error("auth callback missing resourceApiUrl; reconnect through the current Myfield auth page");
|
|
2051
|
-
const transport = new BucketTransport({
|
|
2052
|
-
apiBase: access.resourceApiUrl,
|
|
2053
|
-
mfid: access.mfid,
|
|
2054
|
-
keys: access.keys,
|
|
2055
|
-
sessionProvider: {
|
|
2056
|
-
getSession: (sessionOpts) => auth.getSession(bucketId, sessionOpts),
|
|
2057
|
-
onUnauthorized: () => {
|
|
2058
|
-
liveTransport = null;
|
|
2059
|
-
liveWireId = null;
|
|
2060
|
-
c.stop();
|
|
2061
|
-
emitState("disconnected", "unauthorized");
|
|
2062
|
-
}
|
|
2063
|
-
}
|
|
2064
|
-
});
|
|
2065
|
-
await verifyConnectedTransport(transport, access.keys.wireObjectId);
|
|
2066
|
-
liveTransport = transport;
|
|
2067
|
-
liveWireId = access.keys.wireObjectId;
|
|
2068
|
-
startAutoSync();
|
|
2069
|
-
emitState("connected");
|
|
3431
|
+
next = await (prompt ? connection.connect() : connection.resume());
|
|
2070
3432
|
} catch (error) {
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
} finally {
|
|
2074
|
-
settlePendingConnect();
|
|
3433
|
+
if (error === lastFailure || isAbortError(error)) return "disconnected";
|
|
3434
|
+
throw error;
|
|
2075
3435
|
}
|
|
2076
|
-
|
|
2077
|
-
async function verifyConnectedTransport(transport, wireObjectId) {
|
|
2078
|
-
await transport.pullHead(await wireObjectId(INDEX_OBJECT_ID));
|
|
2079
|
-
}
|
|
2080
|
-
async function handleStartupCallback() {
|
|
2081
|
-
const href = window.location.href;
|
|
2082
|
-
if (!href.includes("mf_auth_result") && !new URL(href).searchParams.get("mf_request_id")) return false;
|
|
2083
|
-
const callback = await handleCallbackUrl(href);
|
|
2084
|
-
if (callback) stripCallbackFromUrl();
|
|
2085
|
-
return !!callback;
|
|
2086
|
-
}
|
|
2087
|
-
function stripCallbackFromUrl() {
|
|
3436
|
+
if (next !== "connected") return next;
|
|
2088
3437
|
try {
|
|
2089
|
-
|
|
2090
|
-
url.hash = "";
|
|
2091
|
-
for (const param of ["state", "error", "error_description", "error_uri", "mf_request_id", "mf_result"]) url.searchParams.delete(param);
|
|
2092
|
-
window.history.replaceState(null, "", url.toString());
|
|
3438
|
+
await reconcile();
|
|
2093
3439
|
} catch {
|
|
3440
|
+
return "disconnected";
|
|
2094
3441
|
}
|
|
3442
|
+
return next;
|
|
2095
3443
|
}
|
|
2096
|
-
|
|
3444
|
+
const bucket = {
|
|
2097
3445
|
id: bucketId,
|
|
2098
3446
|
get state() {
|
|
2099
3447
|
return state;
|
|
@@ -2102,87 +3450,28 @@ function createBucketFacade(deps) {
|
|
|
2102
3450
|
return createBucketBinaryValue(input, options);
|
|
2103
3451
|
},
|
|
2104
3452
|
async ready() {
|
|
2105
|
-
await ensureClient();
|
|
2106
3453
|
},
|
|
2107
3454
|
put,
|
|
2108
3455
|
get: getObject,
|
|
2109
3456
|
update,
|
|
2110
3457
|
delete: deleteObject,
|
|
2111
3458
|
list,
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
if (state !== "disconnected") return state;
|
|
2117
|
-
const auth = await ensureAuthClients(await readStoredEndpoints());
|
|
2118
|
-
if (await handleStartupCallback()) return state;
|
|
2119
|
-
const context = await auth.getContext(bucketId);
|
|
2120
|
-
if (context) await establish();
|
|
2121
|
-
return state;
|
|
2122
|
-
},
|
|
2123
|
-
async connect(options) {
|
|
2124
|
-
if (disposed) throw new Error("disposed");
|
|
2125
|
-
if (options?.autoSync !== void 0) autoSync = options.autoSync;
|
|
2126
|
-
if (options?.authBase) {
|
|
2127
|
-
const endpoints = await readStoredEndpoints();
|
|
2128
|
-
const authBase = normalizeAuthBase(options.authBase);
|
|
2129
|
-
await dataAdapter.set(endpointsKey, {
|
|
2130
|
-
authBase,
|
|
2131
|
-
apiBase: apiBaseForAuthBase(authBase) || endpoints.apiBase
|
|
2132
|
-
});
|
|
2133
|
-
if (popupMessageListener && typeof window !== "undefined") {
|
|
2134
|
-
window.removeEventListener("message", popupMessageListener);
|
|
2135
|
-
popupMessageListener = null;
|
|
2136
|
-
}
|
|
2137
|
-
authClient = null;
|
|
2138
|
-
popupAuthClient = null;
|
|
2139
|
-
}
|
|
2140
|
-
if (state === "connected") return state;
|
|
2141
|
-
if (pendingConnectDone) return pendingConnectDone;
|
|
2142
|
-
const resumed = await this.resume();
|
|
2143
|
-
if (resumed !== "disconnected") return resumed;
|
|
2144
|
-
if (pendingConnectDone) return pendingConnectDone;
|
|
2145
|
-
const auth = await ensureAuthClients(await readStoredEndpoints());
|
|
2146
|
-
emitState("connecting");
|
|
2147
|
-
const done = new Promise((resolve) => {
|
|
2148
|
-
pendingConnect = { resolve };
|
|
2149
|
-
}).finally(() => {
|
|
2150
|
-
if (pendingConnectDone === done) pendingConnectDone = null;
|
|
2151
|
-
});
|
|
2152
|
-
pendingConnectDone = done;
|
|
2153
|
-
try {
|
|
2154
|
-
if (shouldUseSameTabAuth() || !tryOpenPopupShell()) {
|
|
2155
|
-
clearPopupMonitor();
|
|
2156
|
-
authPopupWindow = null;
|
|
2157
|
-
await auth.authorize({ bucketId });
|
|
2158
|
-
} else {
|
|
2159
|
-
await popupAuthClient.authorize({ bucketId });
|
|
2160
|
-
}
|
|
2161
|
-
} catch (error) {
|
|
2162
|
-
authPopupWindow?.close();
|
|
2163
|
-
authPopupWindow = null;
|
|
2164
|
-
clearPopupMonitor();
|
|
2165
|
-
emitState("disconnected", formatError(error));
|
|
2166
|
-
settlePendingConnect();
|
|
3459
|
+
resume: () => connectLegacy(false),
|
|
3460
|
+
connect(options) {
|
|
3461
|
+
if (options && typeof options === "object" && options.authBase !== void 0) {
|
|
3462
|
+
return Promise.reject(new ClientError("INVALID_INPUT", "Pass the authorization page as createInstance({ authUrl })"));
|
|
2167
3463
|
}
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
async disconnect() {
|
|
2171
|
-
liveTransport = null;
|
|
2172
|
-
liveWireId = null;
|
|
2173
|
-
client?.stop();
|
|
2174
|
-
if (authClient) await authClient.clearContext(bucketId);
|
|
2175
|
-
emitState("disconnected");
|
|
2176
|
-
settlePendingConnect();
|
|
3464
|
+
if (options?.autoSync !== void 0) this.setAutoSync(options.autoSync);
|
|
3465
|
+
return connectLegacy(true);
|
|
2177
3466
|
},
|
|
3467
|
+
disconnect: () => connection.disconnect(),
|
|
2178
3468
|
async sync() {
|
|
2179
3469
|
await sync();
|
|
2180
3470
|
},
|
|
2181
3471
|
setAutoSync(enabled) {
|
|
2182
3472
|
autoSync = enabled;
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
if (!enabled) client.stop();
|
|
3473
|
+
void reconcile().catch(() => {
|
|
3474
|
+
});
|
|
2186
3475
|
},
|
|
2187
3476
|
on(event, handler) {
|
|
2188
3477
|
const set = listeners[event];
|
|
@@ -2190,10 +3479,12 @@ function createBucketFacade(deps) {
|
|
|
2190
3479
|
return () => set.delete(handler);
|
|
2191
3480
|
},
|
|
2192
3481
|
dispose() {
|
|
3482
|
+
if (disposed) return;
|
|
2193
3483
|
disposed = true;
|
|
2194
3484
|
client?.dispose();
|
|
2195
|
-
|
|
2196
|
-
|
|
3485
|
+
stopState();
|
|
3486
|
+
stopLocal();
|
|
3487
|
+
deps.onDispose?.();
|
|
2197
3488
|
},
|
|
2198
3489
|
__bindTestTransport(transport) {
|
|
2199
3490
|
liveTransport = transport;
|
|
@@ -2201,53 +3492,52 @@ function createBucketFacade(deps) {
|
|
|
2201
3492
|
emitState("connected");
|
|
2202
3493
|
}
|
|
2203
3494
|
};
|
|
3495
|
+
return { bucket, connectInstance };
|
|
2204
3496
|
}
|
|
2205
3497
|
function normalizeNamespace(value) {
|
|
2206
|
-
const namespace = value === void 0 ? "default" :
|
|
2207
|
-
if (
|
|
2208
|
-
|
|
2209
|
-
throw new Error("namespace must use lowercase letters and digits only (a-z0-9, max 32)");
|
|
3498
|
+
const namespace = value === void 0 ? "default" : value;
|
|
3499
|
+
if (typeof namespace !== "string" || namespace.length > 63 || !namespace.split(".").every((label) => /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label))) {
|
|
3500
|
+
throw new ClientError("INVALID_INPUT", "namespace must be a lowercase domain-form name of 1\u201363 characters");
|
|
2210
3501
|
}
|
|
2211
3502
|
return namespace;
|
|
2212
3503
|
}
|
|
2213
3504
|
function prefixedAdapter(adapter, prefix) {
|
|
2214
3505
|
return {
|
|
3506
|
+
...adapter.removePrefix ? { removePrefix: (keyPrefix) => adapter.removePrefix(`${prefix}${keyPrefix}`) } : {},
|
|
3507
|
+
...adapter.insertIfEmpty ? { insertIfEmpty: (keyPrefix, entries) => adapter.insertIfEmpty(`${prefix}${keyPrefix}`, entries.map((entry) => ({ ...entry, key: `${prefix}${entry.key}` }))) } : {},
|
|
2215
3508
|
get: (key) => adapter.get(`${prefix}${key}`),
|
|
2216
3509
|
set: (key, value) => adapter.set(`${prefix}${key}`, value),
|
|
2217
3510
|
remove: (key) => adapter.remove(`${prefix}${key}`),
|
|
2218
3511
|
keys: async (keyPrefix) => (await adapter.keys(`${prefix}${keyPrefix}`)).map((key) => key.slice(prefix.length))
|
|
2219
3512
|
};
|
|
2220
3513
|
}
|
|
2221
|
-
function
|
|
2222
|
-
|
|
2223
|
-
parsed.searchParams.set("callbackTransport", transport);
|
|
2224
|
-
return parsed.toString();
|
|
2225
|
-
}
|
|
2226
|
-
function normalizeAuthBase(value) {
|
|
2227
|
-
const parsed = new URL(String(value || DEFAULT_AUTH_BASE), typeof window === "undefined" ? DEFAULT_AUTH_BASE : window.location.href);
|
|
2228
|
-
const pathname = parsed.pathname.replace(/\/+$/, "");
|
|
2229
|
-
parsed.pathname = pathname.endsWith("/auth") ? `${pathname}/` : `${pathname}/auth/`;
|
|
2230
|
-
parsed.search = "";
|
|
2231
|
-
parsed.hash = "";
|
|
2232
|
-
return parsed.toString();
|
|
2233
|
-
}
|
|
2234
|
-
function apiBaseForAuthBase(authBase) {
|
|
2235
|
-
const parsed = new URL(authBase);
|
|
2236
|
-
if (parsed.hostname === "myfield.one") return DEFAULT_API_BASE;
|
|
2237
|
-
if (parsed.hostname === "dev.myfield.space") return "https://api-dev.myfield.space";
|
|
2238
|
-
if (parsed.hostname === "staging.myfield.space") return "https://api-staging.myfield.space";
|
|
2239
|
-
return `${parsed.protocol}//api.${parsed.host}`;
|
|
2240
|
-
}
|
|
2241
|
-
function shouldUseSameTabAuth() {
|
|
2242
|
-
if (typeof navigator === "undefined") return false;
|
|
2243
|
-
const platform = navigator.platform || "";
|
|
2244
|
-
const userAgent = navigator.userAgent || "";
|
|
2245
|
-
return /iPad|iPhone|iPod/.test(userAgent) || platform === "MacIntel" && navigator.maxTouchPoints > 1;
|
|
3514
|
+
function isAbortError(error) {
|
|
3515
|
+
return error instanceof Error && error.name === "AbortError";
|
|
2246
3516
|
}
|
|
2247
3517
|
function formatError(error) {
|
|
2248
3518
|
return error instanceof Error ? error.message : String(error);
|
|
2249
3519
|
}
|
|
3520
|
+
function localError(error, message = formatError(error)) {
|
|
3521
|
+
if (error instanceof ClientError) {
|
|
3522
|
+
if (message === error.message) return error;
|
|
3523
|
+
return new ClientError(error.code, message, {
|
|
3524
|
+
cause: error,
|
|
3525
|
+
retryable: error.retryable,
|
|
3526
|
+
status: error.status,
|
|
3527
|
+
requestId: error.requestId,
|
|
3528
|
+
retryAfterMs: error.retryAfterMs,
|
|
3529
|
+
maxBytes: error.maxBytes
|
|
3530
|
+
});
|
|
3531
|
+
}
|
|
3532
|
+
const retryable = error instanceof BucketTransportError ? error.retryable : error instanceof TypeError;
|
|
3533
|
+
return new ClientError(retryable ? "NETWORK_ERROR" : "SYNC_FAILED", message, {
|
|
3534
|
+
cause: error,
|
|
3535
|
+
retryable,
|
|
3536
|
+
status: error instanceof BucketTransportError ? error.status : void 0
|
|
3537
|
+
});
|
|
3538
|
+
}
|
|
2250
3539
|
export {
|
|
3540
|
+
ClientError,
|
|
2251
3541
|
NotConnectedError,
|
|
2252
3542
|
OfflineError,
|
|
2253
3543
|
createInstance
|