@myfield/sdk 0.9.1 → 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/dist/index.js CHANGED
@@ -548,6 +548,33 @@ function buildAad(bucketId, wireObjectId) {
548
548
  return `myfield.bucket.sync.v1|${bucketId}|${wireObjectId}`;
549
549
  }
550
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
+
551
578
  // src/bucket/transport.ts
552
579
  var OfflineError = class extends Error {
553
580
  constructor() {
@@ -558,10 +585,10 @@ var OfflineError = class extends Error {
558
585
  var BucketTransportError = class extends Error {
559
586
  status;
560
587
  retryable;
561
- constructor(message, status) {
588
+ constructor(message, status, retryable = status === 429 || status >= 500) {
562
589
  super(message);
563
590
  this.status = status;
564
- this.retryable = status === 429 || status >= 500;
591
+ this.retryable = retryable;
565
592
  }
566
593
  };
567
594
  var BucketTransport = class {
@@ -569,11 +596,13 @@ var BucketTransport = class {
569
596
  mfid;
570
597
  keys;
571
598
  sessionProvider;
599
+ fetch;
572
600
  constructor(options) {
573
601
  this.apiBase = options.apiBase.replace(/\/+$/, "");
574
602
  this.mfid = options.mfid;
575
603
  this.keys = options.keys;
576
604
  this.sessionProvider = options.sessionProvider;
605
+ this.fetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
577
606
  }
578
607
  async pullHead(wireObjectId) {
579
608
  const currentRes = await this.request(() => ({
@@ -647,7 +676,20 @@ var BucketTransport = class {
647
676
  return { ok: false, conflict: true, remoteVersionId: body?.headVersionId ?? null };
648
677
  }
649
678
  if (!res.ok) throw new BucketTransportError(`push failed: ${res.status}`, res.status);
650
- return { ok: true, versionId };
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
+ );
651
693
  }
652
694
  async listHeads() {
653
695
  const heads = /* @__PURE__ */ new Map();
@@ -684,20 +726,29 @@ var BucketTransport = class {
684
726
  let session = await this.sessionProvider.getSession();
685
727
  let res = await this.send(build(), session);
686
728
  if (res.status === 401) {
729
+ void res.body?.cancel().catch(() => {
730
+ });
687
731
  session = await this.sessionProvider.getSession({ forceRefresh: true });
688
732
  res = await this.send(build(), session);
689
733
  if (res.status === 401) {
690
- this.sessionProvider.onUnauthorized?.();
734
+ await this.sessionProvider.onUnauthorized?.();
691
735
  throw new BucketTransportError("bucket session unauthorized", 401);
692
736
  }
693
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
+ }
694
745
  return res;
695
746
  }
696
747
  send(req, session) {
697
748
  const headers = new Headers(req.init.headers);
698
749
  headers.set("x-myfield-mfid", this.mfid);
699
750
  if (session.carrier === "bearer") headers.set("Authorization", `Bearer ${session.token}`);
700
- return fetch(req.url, {
751
+ return this.fetch(req.url, {
701
752
  ...req.init,
702
753
  headers,
703
754
  ...session.carrier === "cookie" ? { credentials: "include" } : {}
@@ -756,6 +807,7 @@ var BucketClient = class {
756
807
  unresolved = /* @__PURE__ */ new Map();
757
808
  triggerCleanup = null;
758
809
  disposed = false;
810
+ autoSync;
759
811
  constructor(options) {
760
812
  this.transport = options.transport;
761
813
  this.storage = options.storage;
@@ -769,6 +821,7 @@ var BucketClient = class {
769
821
  this.validateRemote = options.validateRemote;
770
822
  this.onChange = options.onChange;
771
823
  this.onSyncError = options.onSyncError;
824
+ this.autoSync = options.autoSync ?? true;
772
825
  }
773
826
  // ---- local reads -------------------------------------------------------
774
827
  async getFields(appObjectId) {
@@ -907,6 +960,7 @@ var BucketClient = class {
907
960
  // are scheduled by setFields/setData.
908
961
  start(options) {
909
962
  if (this.triggerCleanup || this.disposed) return;
963
+ this.autoSync = true;
910
964
  const run = options.run;
911
965
  const kick = () => void run().catch((error) => this.onSyncError?.(null, error));
912
966
  const intervalMs = options.intervalMs ?? DEFAULT_SYNC_INTERVAL_MS;
@@ -917,6 +971,7 @@ var BucketClient = class {
917
971
  kick();
918
972
  }
919
973
  stop() {
974
+ this.autoSync = false;
920
975
  this.triggerCleanup?.();
921
976
  this.triggerCleanup = null;
922
977
  for (const timer of this.pendingPushTimers.values()) clearTimeout(timer);
@@ -939,7 +994,7 @@ var BucketClient = class {
939
994
  }
940
995
  // ---- internals ---------------------------------------------------------
941
996
  schedulePush(appObjectId) {
942
- if (this.disposed || this.localOnly.has(appObjectId)) return;
997
+ if (this.disposed || !this.autoSync || this.localOnly.has(appObjectId)) return;
943
998
  const existing = this.pendingPushTimers.get(appObjectId);
944
999
  if (existing) clearTimeout(existing);
945
1000
  this.pendingPushTimers.set(
@@ -1053,6 +1108,15 @@ function createNamespacedMemoryStorageAdapter(namespace) {
1053
1108
  }
1054
1109
  function memoryAdapterOver(map) {
1055
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
+ },
1056
1120
  async get(key) {
1057
1121
  return map.has(key) ? structuredClone(map.get(key)) : null;
1058
1122
  },
@@ -1073,6 +1137,29 @@ function createIndexedDbStorageAdapter(options) {
1073
1137
  const dbName = options.dbName;
1074
1138
  const storeName = options.storeName || "kv";
1075
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
+ })),
1076
1163
  get: (key) => withIdb(
1077
1164
  dbName,
1078
1165
  storeName,
@@ -1180,6 +1267,305 @@ function openIdb(dbName, storeName) {
1180
1267
  });
1181
1268
  }
1182
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
+
1183
1569
  // src/bucket/keys.ts
1184
1570
  var ID_BLINDING_SALT = "myfield.sdk.v1";
1185
1571
  var ID_BLINDING_INFO_PREFIX = "object-id|";
@@ -1244,157 +1630,273 @@ async function unwrapBucketKeys(envelope, instanceWrappingPrivateKey) {
1244
1630
  }
1245
1631
  }
1246
1632
 
1247
- // src/auth/instance.ts
1248
- var AUTH_REQUEST_TTL_MS = 10 * 60 * 1e3;
1633
+ // src/auth/authorization.ts
1249
1634
  var AUTH_CALLBACK_FRAGMENT_PARAM = "mf_auth_result";
1250
- var DEFAULT_AUTH_IDB_NAME = "mf-sdk-auth-v1";
1251
- var BUCKET_ACCESS_CACHE_TTL_MS = 6e4;
1252
- var INSTANCE_SESSION_USABLE_WINDOW_MS = 2 * 60 * 1e3;
1253
- var INSTANCE_SESSION_BEST_EFFORT_REFRESH_WINDOW_MS = 60 * 60 * 1e3;
1254
- var FIXED_CAPABILITIES = ["read", "write"];
1255
- function createInstanceAuthClient(options = {}) {
1256
- let instance = null;
1257
- const appId = normalizeInstanceAppId(options.appId);
1258
- let mfid = "";
1259
- let currentResourceId = "";
1260
- let currentSession = null;
1261
- const inFlightSessionRefreshes = /* @__PURE__ */ new Map();
1262
- const storage = options.storage || createIndexedDbStorageAdapter({ dbName: DEFAULT_AUTH_IDB_NAME, storeName: "instance" });
1263
- const fetchImpl = options.fetchImpl || fetch;
1264
- const bucketAccessCache = /* @__PURE__ */ new Map();
1265
- const activeInstanceKey = () => `instance:${seg(appId)}:active-instance:current`;
1266
- const instanceKey = (instanceId) => `instance:${seg(appId)}:instance-key:${seg(instanceId)}`;
1267
- const pendingAuthKey = (resourceId, instanceId) => `instance:${seg(appId)}:pending-auth:${seg(resourceId)}:${seg(instanceId)}`;
1268
- const callbackPointerKey = (requestId) => `instance:${seg(appId)}:callback-pointer:${seg(requestId)}`;
1269
- const contextKey = (resourceId, instanceId) => `instance:${seg(appId)}:context:${seg(resourceId)}:${seg(instanceId)}`;
1270
- const sessionKey = (resourceId, instanceId) => `instance:${seg(appId)}:session:${seg(resourceId)}:${seg(instanceId)}`;
1271
- function isStoredAuthInstance(value, instanceId) {
1272
- return !!value && value.v === 1 && isValidInstanceId(value.instanceId) && (!instanceId || value.instanceId === instanceId) && value.signingPrivateKey instanceof CryptoKey && value.wrappingPrivateKey instanceof CryptoKey;
1273
- }
1274
- async function readStoredInstance(instanceId) {
1275
- const stored = await storage.get(instanceKey(instanceId));
1276
- return isStoredAuthInstance(stored, instanceId) ? stored : null;
1277
- }
1278
- async function writeStoredInstance(authInstance) {
1279
- const existing = await readStoredInstance(authInstance.instanceId);
1280
- const stored = {
1281
- ...authInstance,
1282
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1283
- createdAt: authInstance.createdAt || existing?.createdAt || (/* @__PURE__ */ new Date()).toISOString()
1284
- };
1285
- await storage.set(instanceKey(authInstance.instanceId), stored);
1286
- const verified = await readStoredInstance(authInstance.instanceId);
1287
- if (!verified) throw new Error("auth instance write did not persist keys");
1288
- await storage.set(activeInstanceKey(), { v: 1, instanceId: authInstance.instanceId, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
1289
- instance = verified;
1290
- return verified;
1291
- }
1292
- async function readActiveStoredInstance() {
1293
- const active = await storage.get(activeInstanceKey());
1294
- if (!active || active.v !== 1 || !isValidInstanceId(active.instanceId)) return null;
1295
- return readStoredInstance(active.instanceId);
1296
- }
1297
- async function ensureStoredInstance() {
1298
- if (instance) {
1299
- const stored = await readStoredInstance(instance.instanceId);
1300
- if (stored) return stored;
1301
- return writeStoredInstance(instance);
1302
- }
1303
- const active = await readActiveStoredInstance();
1304
- if (active) {
1305
- instance = active;
1306
- return active;
1307
- }
1308
- return writeStoredInstance(await generateAuthInstance());
1309
- }
1310
- async function readContext(resourceId) {
1311
- if (!parseBucketResourceId(resourceId)) return null;
1312
- const authInstance = await readActiveStoredInstance();
1313
- if (!authInstance) return null;
1314
- const context = await storage.get(contextKey(resourceId, authInstance.instanceId));
1315
- if (!context || context.v !== 1 || !isValidMfid(context.mfid) || context.resourceId !== resourceId || context.remoteResourceId !== void 0 && !parseBucketResourceId(context.remoteResourceId) || context.instanceId !== authInstance.instanceId) {
1316
- return null;
1317
- }
1318
- mfid = context.mfid;
1319
- currentResourceId = context.resourceId;
1320
- instance = authInstance;
1321
- return context;
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");
1322
1669
  }
1323
- async function getSessionForResource(resourceId, sessionOptions) {
1324
- const context = await readContext(resourceId);
1325
- if (!mfid || !context) throw new Error("not authorized; complete an auth callback first");
1326
- const authInstance = await ensureStoredInstance();
1327
- if (authInstance.instanceId !== context.instanceId) throw new Error("stored instance does not match authorization context");
1328
- const sessionResourceId = context.remoteResourceId || context.resourceId;
1329
- const forceRefresh = sessionOptions?.forceRefresh === true;
1330
- const refreshSessionKey = `${sessionResourceId}:${authInstance.instanceId}`;
1331
- const performRefreshSession = async () => {
1332
- const challenge = await postJson(fetchImpl, options.apiBase, "/v1/api/auth/instance-challenge", {
1333
- mfid,
1334
- resourceId: sessionResourceId,
1335
- instanceId: authInstance.instanceId
1336
- });
1337
- const proof = await signInstanceChallenge({
1338
- instance: authInstance,
1339
- challengeId: challenge.challengeId,
1340
- challenge: challenge.challenge,
1341
- mfid,
1342
- resourceId: sessionResourceId
1343
- });
1344
- const session = await postJson(fetchImpl, options.apiBase, "/v1/api/auth/instance-session", {
1345
- mfid,
1346
- resourceId: sessionResourceId,
1347
- instanceId: authInstance.instanceId,
1348
- challengeId: challenge.challengeId,
1349
- proof,
1350
- credentialCarrier: "bearer"
1351
- });
1352
- currentSession = { resourceId: sessionResourceId, credential: session.credential };
1353
- if (session.credential.carrier === "bearer") {
1354
- await storage.set(sessionKey(sessionResourceId, context.instanceId), {
1355
- v: 1,
1356
- mfid,
1357
- resourceId: sessionResourceId,
1358
- instanceId: authInstance.instanceId,
1359
- credential: session.credential,
1360
- storedAt: (/* @__PURE__ */ new Date()).toISOString()
1361
- });
1362
- }
1363
- return session.credential;
1364
- };
1365
- const refreshSession = () => {
1366
- const inFlight = inFlightSessionRefreshes.get(refreshSessionKey);
1367
- if (inFlight) return inFlight;
1368
- const promise = performRefreshSession().finally(() => {
1369
- if (inFlightSessionRefreshes.get(refreshSessionKey) === promise) inFlightSessionRefreshes.delete(refreshSessionKey);
1370
- });
1371
- inFlightSessionRefreshes.set(refreshSessionKey, promise);
1372
- return promise;
1373
- };
1374
- if (!forceRefresh) {
1375
- let cachedCredential = null;
1376
- if (currentSession?.resourceId === sessionResourceId && isSessionUsable(currentSession.credential)) {
1377
- cachedCredential = currentSession.credential;
1378
- } else {
1379
- const stored = await storage.get(sessionKey(sessionResourceId, context.instanceId));
1380
- if (stored?.v === 1 && stored.mfid === mfid && stored.resourceId === sessionResourceId && stored.instanceId === authInstance.instanceId && isSessionUsable(stored.credential)) {
1381
- currentSession = { resourceId: sessionResourceId, credential: stored.credential };
1382
- cachedCredential = stored.credential;
1383
- }
1384
- }
1385
- if (cachedCredential) {
1386
- if (shouldBestEffortRefreshSession(cachedCredential)) void refreshSession().catch(() => void 0);
1387
- return cachedCredential;
1388
- }
1389
- }
1390
- if (forceRefresh) inFlightSessionRefreshes.delete(refreshSessionKey);
1391
- return refreshSession();
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");
1392
1676
  }
1393
- return {
1394
- async ensureInstance() {
1395
- return ensureStoredInstance();
1396
- },
1397
- async authorize(request) {
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;
1866
+ };
1867
+ const refreshSession = () => {
1868
+ const inFlight = inFlightSessionRefreshes.get(refreshSessionKey);
1869
+ if (inFlight) return inFlight;
1870
+ const promise = performRefreshSession().finally(() => {
1871
+ if (inFlightSessionRefreshes.get(refreshSessionKey) === promise) inFlightSessionRefreshes.delete(refreshSessionKey);
1872
+ });
1873
+ inFlightSessionRefreshes.set(refreshSessionKey, promise);
1874
+ return promise;
1875
+ };
1876
+ if (!forceRefresh) {
1877
+ let cachedCredential = null;
1878
+ if (currentSession?.resourceId === sessionResourceId && isSessionUsable(currentSession.credential)) {
1879
+ cachedCredential = currentSession.credential;
1880
+ } else {
1881
+ const stored = await storage.get(sessionKey(sessionResourceId, context.instanceId));
1882
+ if (stored?.v === 1 && stored.mfid === mfid && stored.resourceId === sessionResourceId && stored.instanceId === authInstance.instanceId && isSessionUsable(stored.credential)) {
1883
+ currentSession = { resourceId: sessionResourceId, credential: stored.credential };
1884
+ cachedCredential = stored.credential;
1885
+ }
1886
+ }
1887
+ if (cachedCredential) {
1888
+ if (shouldBestEffortRefreshSession(cachedCredential)) void refreshSession().catch(() => void 0);
1889
+ return cachedCredential;
1890
+ }
1891
+ }
1892
+ if (forceRefresh) inFlightSessionRefreshes.delete(refreshSessionKey);
1893
+ return refreshSession();
1894
+ }
1895
+ return {
1896
+ async ensureInstance() {
1897
+ return ensureStoredInstance();
1898
+ },
1899
+ async authorize(request) {
1398
1900
  const resourceId = bucketResourceId(requireValidBucketId(request.bucketId));
1399
1901
  const authInstance = await ensureStoredInstance();
1400
1902
  currentResourceId = resourceId;
@@ -1487,6 +1989,9 @@ function createInstanceAuthClient(options = {}) {
1487
1989
  const remoteResourceId = stored.bucketAccessGrant?.resourceId || stored.resourceId;
1488
1990
  mfid = stored.mfid;
1489
1991
  currentResourceId = stored.resourceId;
1992
+ if ((await readActiveStoredInstance())?.instanceId !== authInstance.instanceId) {
1993
+ throw new ClientError("IDENTITY_MISMATCH", "Active instance changed during authorization");
1994
+ }
1490
1995
  await storage.set(contextKey(stored.resourceId, stored.instanceId), {
1491
1996
  v: 1,
1492
1997
  mfid: stored.mfid,
@@ -1498,7 +2003,6 @@ function createInstanceAuthClient(options = {}) {
1498
2003
  authorizedAt: (/* @__PURE__ */ new Date()).toISOString(),
1499
2004
  ...stored.bucketAccessGrant ? { bucketAccessGrant: stored.bucketAccessGrant } : {}
1500
2005
  });
1501
- await writeStoredInstance(authInstance);
1502
2006
  if (currentSession?.resourceId === remoteResourceId) currentSession = null;
1503
2007
  await storage.remove(sessionKey(remoteResourceId, stored.instanceId));
1504
2008
  bucketAccessCache.clear();
@@ -1554,182 +2058,6 @@ function createInstanceAuthClient(options = {}) {
1554
2058
  }
1555
2059
  };
1556
2060
  }
1557
- async function generateAuthInstance() {
1558
- const signing = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]);
1559
- const wrapping = await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
1560
- const signingPublicJwk = await crypto.subtle.exportKey("jwk", signing.publicKey);
1561
- const wrappingPublicJwk = await crypto.subtle.exportKey("jwk", wrapping.publicKey);
1562
- return {
1563
- v: 1,
1564
- instanceId: await deriveInstanceId(signingPublicJwk),
1565
- signingPublicJwk,
1566
- signingPrivateKey: signing.privateKey,
1567
- wrappingPublicJwk,
1568
- wrappingPrivateKey: wrapping.privateKey,
1569
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
1570
- };
1571
- }
1572
- async function deriveInstanceId(signingPublicJwk) {
1573
- const digest = await sha256Hex(stableStringify(jwkCore(signingPublicJwk)));
1574
- return `inst_${digest.slice(0, 32)}`;
1575
- }
1576
- async function signInstanceChallenge(input) {
1577
- const signedAt = normalizeIsoDateTime(input.signedAt) || (/* @__PURE__ */ new Date()).toISOString();
1578
- const payload = stableStringify({
1579
- v: 1,
1580
- type: "instance-proof",
1581
- instanceId: input.instance.instanceId,
1582
- challenge: input.challenge,
1583
- challengeId: input.challengeId || "",
1584
- mfid: input.mfid,
1585
- resourceId: input.resourceId,
1586
- signedAt
1587
- });
1588
- const signature = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, input.instance.signingPrivateKey, utf8Encode(payload));
1589
- return { type: "instance.es256", instanceId: input.instance.instanceId, alg: "ES256", signedAt, signature: bytesToB64url(new Uint8Array(signature)) };
1590
- }
1591
- function buildAuthRequestFragment(request) {
1592
- if (!request.requestId || !request.state) throw new Error("auth request state required");
1593
- if (!isValidInstanceId(request.instanceId)) throw new Error("invalid instanceId");
1594
- if (!isPublicP256EcJwk(request.instanceSigningPublicJwk)) throw new Error("instanceSigningPublicJwk required");
1595
- if (!isPublicP256EcJwk(request.instanceWrappingPublicJwk)) throw new Error("instanceWrappingPublicJwk required");
1596
- const redirect = new URL(request.redirectUri);
1597
- const origin = new URL(request.origin);
1598
- if (redirect.origin !== origin.origin) throw new Error("redirectUri origin mismatch");
1599
- const wire = {
1600
- response_type: "code",
1601
- client_id: request.clientId,
1602
- redirect_uri: request.redirectUri,
1603
- state: request.state,
1604
- scope: request.capabilities.join(" "),
1605
- resource_id: request.resourceId,
1606
- mf_v: 1,
1607
- mf_auth_mode: "v1",
1608
- mf_request_id: request.requestId,
1609
- mf_instance_id: request.instanceId,
1610
- mf_instance_signing_jwk: request.instanceSigningPublicJwk,
1611
- mf_instance_wrapping_jwk: request.instanceWrappingPublicJwk,
1612
- mf_issued_at: request.createdAt
1613
- };
1614
- return `#authRequest=${bytesToB64url(utf8Encode(stableStringify(wire)))}`;
1615
- }
1616
- function parseEncryptedAuthAuthorizationResultFragment(fragmentOrUrl) {
1617
- const input = String(fragmentOrUrl || "");
1618
- const rawFragment = input.includes("#") ? input.slice(input.indexOf("#") + 1) : input.replace(/^#/, "");
1619
- if (!rawFragment) return null;
1620
- const encoded = new URLSearchParams(rawFragment).get(AUTH_CALLBACK_FRAGMENT_PARAM);
1621
- if (!encoded) return null;
1622
- const envelope = JSON.parse(new TextDecoder().decode(b64urlToBytes(encoded)));
1623
- 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") {
1624
- throw new Error("auth callback result fragment invalid");
1625
- }
1626
- return envelope;
1627
- }
1628
- async function decryptEncryptedAuthAuthorizationResult(input) {
1629
- const { envelope } = input;
1630
- 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) {
1631
- throw new Error("auth callback result mismatch");
1632
- }
1633
- const ephemeralPublic = await crypto.subtle.importKey("jwk", envelope.ephemeralPublicJwk, { name: "ECDH", namedCurve: "P-256" }, false, []);
1634
- const sharedBits = await crypto.subtle.deriveBits({ name: "ECDH", public: ephemeralPublic }, input.instanceWrappingPrivateKey, 256);
1635
- const material = await crypto.subtle.importKey("raw", sharedBits, "HKDF", false, ["deriveKey"]);
1636
- const wrappingKey = await crypto.subtle.deriveKey(
1637
- { name: "HKDF", hash: "SHA-256", salt: b64urlToBytes(envelope.salt), info: utf8Encode(envelope.aad) },
1638
- material,
1639
- { name: "AES-GCM", length: 256 },
1640
- false,
1641
- ["decrypt"]
1642
- );
1643
- const plaintext = await crypto.subtle.decrypt(
1644
- { name: "AES-GCM", iv: b64urlToBytes(envelope.iv), additionalData: utf8Encode(envelope.aad) },
1645
- wrappingKey,
1646
- b64urlToBytes(envelope.ciphertext)
1647
- );
1648
- const result = normalizeAuthAuthorizationResult(JSON.parse(new TextDecoder().decode(plaintext)), envelope.requestId);
1649
- 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) {
1650
- throw new Error("auth callback result mismatch");
1651
- }
1652
- return result;
1653
- }
1654
- function normalizeAuthAuthorizationResult(value, expectedRequestId) {
1655
- const row = value;
1656
- 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") {
1657
- return null;
1658
- }
1659
- if (row.expiresAt !== void 0) {
1660
- const expiresAt = Date.parse(String(row.expiresAt));
1661
- if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return null;
1662
- }
1663
- const resource = parseBucketResourceId(row.resourceId);
1664
- if (!resource) return null;
1665
- const bucketAccessGrant = normalizeBucketAccessGrant(row.bucketAccessGrant);
1666
- if (!bucketAccessGrant) return null;
1667
- if (bucketAccessGrant.mfid !== row.mfid || !parseBucketResourceId(bucketAccessGrant.resourceId) || bucketAccessGrant.instanceId !== row.instanceId) {
1668
- return null;
1669
- }
1670
- return {
1671
- v: 1,
1672
- requestId: row.requestId,
1673
- state: row.state,
1674
- result: "approved",
1675
- mfid: row.mfid,
1676
- resourceId: resource.resourceId,
1677
- instanceId: row.instanceId,
1678
- createdAt: row.createdAt,
1679
- ...typeof row.resourceApiUrl === "string" && row.resourceApiUrl.trim() ? { resourceApiUrl: row.resourceApiUrl.trim() } : {},
1680
- bucketAccessGrant,
1681
- ...row.expiresAt ? { expiresAt: row.expiresAt } : {}
1682
- };
1683
- }
1684
- function normalizeBucketAccessGrant(value) {
1685
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
1686
- const row = value;
1687
- const resource = parseBucketResourceId(row.resourceId);
1688
- const capabilities = normalizeCapabilities(row.capabilities);
1689
- 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)) {
1690
- return null;
1691
- }
1692
- return {
1693
- v: 1,
1694
- grantRecordId: row.grantRecordId,
1695
- mfid: row.mfid,
1696
- resourceId: resource.resourceId,
1697
- instanceId: row.instanceId,
1698
- issuedAt: String(row.issuedAt || ""),
1699
- keyId: row.keyId,
1700
- capabilities,
1701
- envelope: row.envelope
1702
- };
1703
- }
1704
- function isValidBucketKeyGrantEnvelope(value, instanceId, keyId) {
1705
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1706
- const row = value;
1707
- 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") {
1708
- return false;
1709
- }
1710
- if (instanceId && row.targetInstanceId !== instanceId) return false;
1711
- if (keyId && row.keyId !== keyId) return false;
1712
- return true;
1713
- }
1714
- function bucketResourceId(bucketId) {
1715
- return `urn:myfield:bucket:${bucketId}`;
1716
- }
1717
- function parseBucketResourceId(resourceId) {
1718
- const safe = typeof resourceId === "string" ? resourceId.trim() : "";
1719
- const prefix = "urn:myfield:bucket:";
1720
- if (!safe.startsWith(prefix)) return null;
1721
- const bucketId = safe.slice(prefix.length);
1722
- return isValidBucketId(bucketId) ? { resourceId: safe, bucketId } : null;
1723
- }
1724
- function normalizeCapabilities(input) {
1725
- if (!Array.isArray(input)) return [];
1726
- const allowed = /* @__PURE__ */ new Set(["read", "write"]);
1727
- const result = [];
1728
- for (const item of input) {
1729
- if (allowed.has(item) && !result.includes(item)) result.push(item);
1730
- }
1731
- return result.sort();
1732
- }
1733
2061
  async function postJson(fetchImpl, apiBase, path, body) {
1734
2062
  const res = await fetchImpl(`${apiBase || ""}${path}`, {
1735
2063
  method: "POST",
@@ -1759,89 +2087,999 @@ function isFresh(createdAt) {
1759
2087
  const created = Date.parse(createdAt);
1760
2088
  return Number.isFinite(created) && Date.now() - created <= AUTH_REQUEST_TTL_MS;
1761
2089
  }
1762
- function isValidBucketId(value) {
1763
- const safe = typeof value === "string" ? value.trim() : "";
1764
- return /^[a-z0-9](?:[a-z0-9.-]{0,61}[a-z0-9])?$/.test(safe) && !safe.includes("..");
2090
+ function browserLocationHref() {
2091
+ if (typeof window === "undefined") throw new Error("browser window required");
2092
+ return window.location.href;
1765
2093
  }
1766
- function requireValidBucketId(value) {
1767
- if (!isValidBucketId(value)) throw new Error("invalid bucketId");
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);
1768
2130
  return value;
1769
2131
  }
1770
- function isValidInstanceId(value) {
1771
- return typeof value === "string" && /^inst_[a-f0-9]{32}$/.test(value);
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
+ };
1772
2178
  }
1773
- function isValidMfid(value) {
1774
- return typeof value === "string" && /^[a-f0-9]{32}$/.test(value);
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
+ }
1775
2260
  }
1776
- function isPublicP256EcJwk(value) {
1777
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1778
- const jwk = value;
1779
- return jwk.kty === "EC" && jwk.crv === "P-256" && typeof jwk.x === "string" && jwk.x.length > 0 && typeof jwk.y === "string" && jwk.y.length > 0;
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
+ };
1780
2389
  }
1781
- function normalizeInstanceAppId(value) {
1782
- const safe = typeof value === "string" ? value.trim() : "";
1783
- return isValidBucketId(safe) ? safe : "myfield.sdk";
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 };
1784
2415
  }
1785
- function seg(value) {
1786
- return encodeURIComponent(value);
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
+ });
1787
2424
  }
1788
- function jwkCore(jwk) {
1789
- const out = {};
1790
- for (const key of ["kty", "crv", "x", "y", "kid", "alg", "use"]) {
1791
- const value = jwk[key];
1792
- if (typeof value === "string") out[key] = value;
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
+ });
1793
2439
  }
1794
- return out;
1795
- }
1796
- function browserLocationHref() {
1797
- if (typeof window === "undefined") throw new Error("browser window required");
1798
- return window.location.href;
2440
+ return new ClientError("INVALID_STATE", error instanceof Error ? error.message : "Connection failed", { cause: error });
1799
2441
  }
1800
- function browserLocationOrigin() {
1801
- if (typeof window === "undefined") throw new Error("browser window required");
1802
- return window.location.origin;
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;
1803
2453
  }
1804
-
1805
- // src/errors.ts
1806
- var NotConnectedError = class extends Error {
1807
- constructor() {
1808
- super("bucket is not connected; call connect() first");
1809
- this.name = "NotConnectedError";
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();
1810
2497
  }
1811
- };
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
+ }
1812
2978
 
1813
2979
  // src/facade.ts
1814
- var DEFAULT_AUTH_BASE = "https://myfield.one/auth/";
1815
- var DEFAULT_API_BASE = "https://api.myfield.one";
1816
2980
  var INDEX_OBJECT_ID = "~index";
1817
2981
  var ID_FIELD = "~id";
1818
2982
  var DELETED_FIELD = "~deleted";
1819
2983
  var RESERVED_PREFIX = "~";
1820
- function createInstance(options = {}) {
1821
- const namespace = normalizeNamespace(options.namespace);
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());
1822
2995
  const storageKind = options.storage || "indexeddb";
1823
2996
  const baseAdapter = storageKind === "memory" ? createNamespacedMemoryStorageAdapter(`myfield-sdk:${namespace}`) : createIndexedDbStorageAdapter({ dbName: `myfield-sdk:${namespace}` });
1824
2997
  const authAdapter = prefixedAdapter(baseAdapter, "auth:");
1825
2998
  const buckets = /* @__PURE__ */ new Map();
1826
- return {
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 = {
1827
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,
1828
3063
  createBucket(bucketOptions) {
1829
3064
  const bucketId = String(bucketOptions?.id || "").trim();
1830
3065
  if (!bucketId) throw new Error("bucket id is required");
1831
3066
  if (!isValidBucketId(bucketId)) throw new Error("invalid bucketId");
1832
- const existing = buckets.get(bucketId);
1833
- if (existing) return existing;
1834
- const bucket = createBucketFacade({ namespace, bucketId, dataAdapter: baseAdapter, authAdapter });
1835
- buckets.set(bucketId, bucket);
1836
- return bucket;
3067
+ return getLocalBucket(bucketId).bucket;
1837
3068
  }
1838
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;
1839
3078
  }
1840
3079
  function createBucketFacade(deps) {
1841
- const { bucketId, dataAdapter, authAdapter } = deps;
1842
- const endpointsKey = `meta:${bucketId}:endpoints`;
3080
+ const { bucketId, dataAdapter, connection } = deps;
1843
3081
  const actorKey = `meta:actor`;
1844
- let state = "disconnected";
3082
+ let state = connection.state;
1845
3083
  let client = null;
1846
3084
  let clientInit = null;
1847
3085
  let liveTransport = null;
@@ -1849,14 +3087,11 @@ function createBucketFacade(deps) {
1849
3087
  let autoSync = true;
1850
3088
  let syncIntervalMs;
1851
3089
  let disposed = false;
1852
- let authClient = null;
1853
- let popupAuthClient = null;
1854
- let authPageOrigin = "";
1855
- let authPopupWindow = null;
1856
- let authPopupPollTimer = null;
1857
- let pendingConnect = null;
1858
- let pendingConnectDone = null;
1859
- let popupMessageListener = null;
3090
+ let connectedAccess = null;
3091
+ let activating = null;
3092
+ let verifiedAccess = null;
3093
+ let connecting = null;
3094
+ let lastFailure = null;
1860
3095
  const listeners = { state: /* @__PURE__ */ new Set(), change: /* @__PURE__ */ new Set() };
1861
3096
  function emitState(next, detail) {
1862
3097
  if (state !== next) {
@@ -1870,12 +3105,6 @@ function createBucketFacade(deps) {
1870
3105
  if (objectId.startsWith(RESERVED_PREFIX)) return;
1871
3106
  for (const handler of listeners.change) handler(objectId);
1872
3107
  }
1873
- function settlePendingConnect() {
1874
- if (!pendingConnect) return;
1875
- const settle = pendingConnect;
1876
- pendingConnect = null;
1877
- settle.resolve(state);
1878
- }
1879
3108
  function ensureClient() {
1880
3109
  if (clientInit) return clientInit;
1881
3110
  clientInit = (async () => {
@@ -1904,6 +3133,7 @@ function createBucketFacade(deps) {
1904
3133
  }
1905
3134
  },
1906
3135
  storage: dataAdapter,
3136
+ autoSync: autoSync && Boolean(liveTransport),
1907
3137
  actorId,
1908
3138
  localOnlyObjectIds: [INDEX_OBJECT_ID],
1909
3139
  validateRemote: assertRemoteObjectId,
@@ -1915,7 +3145,9 @@ function createBucketFacade(deps) {
1915
3145
  onChange: onClientChange,
1916
3146
  onSyncError: (objectId, error) => {
1917
3147
  if (error instanceof OfflineError) return;
1918
- emitState(state, `sync error${objectId ? ` (${objectId})` : ""}: ${formatError(error)}`);
3148
+ const detail = `sync error${objectId ? ` (${objectId})` : ""}: ${formatError(error)}`;
3149
+ if (connection.state === "connected") connection.report(localError(error, detail));
3150
+ else emitState(state, detail);
1919
3151
  }
1920
3152
  });
1921
3153
  return client;
@@ -2098,172 +3330,118 @@ function createBucketFacade(deps) {
2098
3330
  if (!autoSync || !client) return;
2099
3331
  client.start({ run: runSyncPass, ...syncIntervalMs !== void 0 ? { intervalMs: syncIntervalMs } : {} });
2100
3332
  }
2101
- async function readStoredEndpoints() {
2102
- const stored = await dataAdapter.get(endpointsKey);
2103
- const authBase = stored?.authBase || DEFAULT_AUTH_BASE;
2104
- return {
2105
- authBase,
2106
- apiBase: stored?.apiBase || apiBaseForAuthBase(authBase)
2107
- };
2108
- }
2109
- async function ensureAuthClients(endpoints) {
2110
- if (authClient) return authClient;
2111
- if (typeof window === "undefined") throw new Error("connect()/resume() require a browser environment");
2112
- const origin = window.location.origin;
2113
- const authPageUrl = normalizeAuthBase(endpoints.authBase);
2114
- authPageOrigin = new URL(authPageUrl, window.location.href).origin;
2115
- const baseOptions = {
2116
- appId: new URL(origin).hostname,
2117
- apiBase: endpoints.apiBase,
2118
- redirectUri: origin + window.location.pathname,
2119
- origin,
2120
- storage: authAdapter
2121
- };
2122
- authClient = createInstanceAuthClient({
2123
- ...baseOptions,
2124
- authPageUrl: addCallbackTransport(authPageUrl, "same-tab")
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
2125
3343
  });
2126
- popupAuthClient = createInstanceAuthClient({
2127
- ...baseOptions,
2128
- authPageUrl: addCallbackTransport(authPageUrl, "popup"),
2129
- openAuthUrl: (url) => openAuthPopupUrl(url)
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(() => {
2130
3365
  });
2131
- popupMessageListener = (event) => void onPopupMessage(event);
2132
- window.addEventListener("message", popupMessageListener);
2133
- return authClient;
2134
- }
2135
- function clearPopupMonitor() {
2136
- if (authPopupPollTimer != null) {
2137
- clearInterval(authPopupPollTimer);
2138
- authPopupPollTimer = null;
2139
- }
2140
- }
2141
- function tryOpenPopupShell() {
2142
- clearPopupMonitor();
2143
- authPopupWindow?.close();
2144
- const width = 520;
2145
- const height = 720;
2146
- const left = Math.max(0, Math.floor(window.screenX + (window.outerWidth - width) / 2));
2147
- const top = Math.max(0, Math.floor(window.screenY + (window.outerHeight - height) / 2));
2148
- authPopupWindow = window.open(
2149
- "about:blank",
2150
- "myfield-sdk-auth",
2151
- `popup=yes,width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`
2152
- );
2153
- if (!authPopupWindow || authPopupWindow.closed) {
2154
- authPopupWindow = null;
2155
- return false;
2156
- }
2157
- try {
2158
- authPopupWindow.document.title = "Opening Myfield...";
2159
- authPopupWindow.document.body.textContent = "Opening Myfield authorization...";
2160
- } catch {
3366
+ });
3367
+ if (state === "connected") bindTransport();
3368
+ function activate() {
3369
+ const current = bindTransport();
3370
+ if (verifiedAccess === current) {
3371
+ startAutoSync();
3372
+ return Promise.resolve();
2161
3373
  }
2162
- authPopupWindow.focus();
2163
- authPopupPollTimer = setInterval(() => {
2164
- if (!authPopupWindow?.closed) return;
2165
- clearPopupMonitor();
2166
- if (state === "connecting") {
2167
- emitState("disconnected", "authorization window closed");
2168
- settlePendingConnect();
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;
2169
3392
  }
2170
- }, 500);
2171
- return true;
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;
2172
3400
  }
2173
- function openAuthPopupUrl(url) {
2174
- if (!authPopupWindow || authPopupWindow.closed) {
2175
- if (!tryOpenPopupShell()) throw new Error("authorization popup was blocked");
2176
- }
2177
- try {
2178
- authPopupWindow.location.href = url;
2179
- authPopupWindow.focus();
2180
- } catch {
2181
- authPopupWindow = window.open(url, "myfield-sdk-auth");
2182
- 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();
2183
3406
  }
2184
- }
2185
- async function onPopupMessage(event) {
2186
- if (event.origin !== authPageOrigin) return;
2187
- const message = event.data;
2188
- if (!message || message.type !== "myfield.auth.callback" || typeof message.callbackUrl !== "string") return;
2189
- clearPopupMonitor();
2190
- authPopupWindow?.close();
2191
- authPopupWindow = null;
2192
- await handleCallbackUrl(message.callbackUrl);
2193
- }
2194
- async function handleCallbackUrl(callbackUrl) {
2195
- try {
2196
- const auth = await ensureAuthClients(await readStoredEndpoints());
2197
- const callback = await auth.handleCallback(callbackUrl);
2198
- if (!callback) return null;
2199
- if (callback.result === "approved") {
2200
- await establish({ forceRefresh: true });
2201
- } else {
2202
- emitState("disconnected", callback.errorDescription || callback.error || callback.result);
2203
- settlePendingConnect();
2204
- }
2205
- return callback;
2206
- } catch (error) {
2207
- emitState("disconnected", formatError(error));
2208
- settlePendingConnect();
2209
- 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");
2210
3428
  }
2211
- }
2212
- async function establish(sessionOptions = {}) {
2213
- emitState("connecting");
3429
+ let next;
2214
3430
  try {
2215
- const endpoints = await readStoredEndpoints();
2216
- const auth = await ensureAuthClients(endpoints);
2217
- const c = await ensureClient();
2218
- await auth.getSession(bucketId, sessionOptions);
2219
- const access = await auth.getBucketAccess(bucketId);
2220
- if (!access.resourceApiUrl) throw new Error("auth callback missing resourceApiUrl; reconnect through the current Myfield auth page");
2221
- const transport = new BucketTransport({
2222
- apiBase: access.resourceApiUrl,
2223
- mfid: access.mfid,
2224
- keys: access.keys,
2225
- sessionProvider: {
2226
- getSession: (sessionOpts) => auth.getSession(bucketId, sessionOpts),
2227
- onUnauthorized: () => {
2228
- liveTransport = null;
2229
- liveWireId = null;
2230
- c.stop();
2231
- emitState("disconnected", "unauthorized");
2232
- }
2233
- }
2234
- });
2235
- await verifyConnectedTransport(transport, access.keys.wireObjectId);
2236
- liveTransport = transport;
2237
- liveWireId = access.keys.wireObjectId;
2238
- startAutoSync();
2239
- emitState("connected");
3431
+ next = await (prompt ? connection.connect() : connection.resume());
2240
3432
  } catch (error) {
2241
- client?.stop();
2242
- emitState("disconnected", formatError(error));
2243
- } finally {
2244
- settlePendingConnect();
3433
+ if (error === lastFailure || isAbortError(error)) return "disconnected";
3434
+ throw error;
2245
3435
  }
2246
- }
2247
- async function verifyConnectedTransport(transport, wireObjectId) {
2248
- await transport.pullHead(await wireObjectId(INDEX_OBJECT_ID));
2249
- }
2250
- async function handleStartupCallback() {
2251
- const href = window.location.href;
2252
- if (!href.includes("mf_auth_result") && !new URL(href).searchParams.get("mf_request_id")) return false;
2253
- const callback = await handleCallbackUrl(href);
2254
- if (callback) stripCallbackFromUrl();
2255
- return !!callback;
2256
- }
2257
- function stripCallbackFromUrl() {
3436
+ if (next !== "connected") return next;
2258
3437
  try {
2259
- const url = new URL(window.location.href);
2260
- url.hash = "";
2261
- for (const param of ["state", "error", "error_description", "error_uri", "mf_request_id", "mf_result"]) url.searchParams.delete(param);
2262
- window.history.replaceState(null, "", url.toString());
3438
+ await reconcile();
2263
3439
  } catch {
3440
+ return "disconnected";
2264
3441
  }
3442
+ return next;
2265
3443
  }
2266
- return {
3444
+ const bucket = {
2267
3445
  id: bucketId,
2268
3446
  get state() {
2269
3447
  return state;
@@ -2272,87 +3450,28 @@ function createBucketFacade(deps) {
2272
3450
  return createBucketBinaryValue(input, options);
2273
3451
  },
2274
3452
  async ready() {
2275
- await ensureClient();
2276
3453
  },
2277
3454
  put,
2278
3455
  get: getObject,
2279
3456
  update,
2280
3457
  delete: deleteObject,
2281
3458
  list,
2282
- async resume() {
2283
- if (disposed) throw new Error("disposed");
2284
- await ensureClient();
2285
- if (typeof window === "undefined") return state;
2286
- if (state !== "disconnected") return state;
2287
- const auth = await ensureAuthClients(await readStoredEndpoints());
2288
- if (await handleStartupCallback()) return state;
2289
- const context = await auth.getContext(bucketId);
2290
- if (context) await establish();
2291
- return state;
2292
- },
2293
- async connect(options) {
2294
- if (disposed) throw new Error("disposed");
2295
- if (options?.autoSync !== void 0) autoSync = options.autoSync;
2296
- if (options?.authBase) {
2297
- const endpoints = await readStoredEndpoints();
2298
- const authBase = normalizeAuthBase(options.authBase);
2299
- await dataAdapter.set(endpointsKey, {
2300
- authBase,
2301
- apiBase: apiBaseForAuthBase(authBase) || endpoints.apiBase
2302
- });
2303
- if (popupMessageListener && typeof window !== "undefined") {
2304
- window.removeEventListener("message", popupMessageListener);
2305
- popupMessageListener = null;
2306
- }
2307
- authClient = null;
2308
- popupAuthClient = null;
2309
- }
2310
- if (state === "connected") return state;
2311
- if (pendingConnectDone) return pendingConnectDone;
2312
- const resumed = await this.resume();
2313
- if (resumed !== "disconnected") return resumed;
2314
- if (pendingConnectDone) return pendingConnectDone;
2315
- const auth = await ensureAuthClients(await readStoredEndpoints());
2316
- emitState("connecting");
2317
- const done = new Promise((resolve) => {
2318
- pendingConnect = { resolve };
2319
- }).finally(() => {
2320
- if (pendingConnectDone === done) pendingConnectDone = null;
2321
- });
2322
- pendingConnectDone = done;
2323
- try {
2324
- if (shouldUseSameTabAuth() || !tryOpenPopupShell()) {
2325
- clearPopupMonitor();
2326
- authPopupWindow = null;
2327
- await auth.authorize({ bucketId });
2328
- } else {
2329
- await popupAuthClient.authorize({ bucketId });
2330
- }
2331
- } catch (error) {
2332
- authPopupWindow?.close();
2333
- authPopupWindow = null;
2334
- clearPopupMonitor();
2335
- emitState("disconnected", formatError(error));
2336
- 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 })"));
2337
3463
  }
2338
- return done;
2339
- },
2340
- async disconnect() {
2341
- liveTransport = null;
2342
- liveWireId = null;
2343
- client?.stop();
2344
- if (authClient) await authClient.clearContext(bucketId);
2345
- emitState("disconnected");
2346
- settlePendingConnect();
3464
+ if (options?.autoSync !== void 0) this.setAutoSync(options.autoSync);
3465
+ return connectLegacy(true);
2347
3466
  },
3467
+ disconnect: () => connection.disconnect(),
2348
3468
  async sync() {
2349
3469
  await sync();
2350
3470
  },
2351
3471
  setAutoSync(enabled) {
2352
3472
  autoSync = enabled;
2353
- if (!client) return;
2354
- if (enabled && liveTransport) startAutoSync();
2355
- if (!enabled) client.stop();
3473
+ void reconcile().catch(() => {
3474
+ });
2356
3475
  },
2357
3476
  on(event, handler) {
2358
3477
  const set = listeners[event];
@@ -2360,10 +3479,12 @@ function createBucketFacade(deps) {
2360
3479
  return () => set.delete(handler);
2361
3480
  },
2362
3481
  dispose() {
3482
+ if (disposed) return;
2363
3483
  disposed = true;
2364
3484
  client?.dispose();
2365
- clearPopupMonitor();
2366
- if (popupMessageListener && typeof window !== "undefined") window.removeEventListener("message", popupMessageListener);
3485
+ stopState();
3486
+ stopLocal();
3487
+ deps.onDispose?.();
2367
3488
  },
2368
3489
  __bindTestTransport(transport) {
2369
3490
  liveTransport = transport;
@@ -2371,53 +3492,52 @@ function createBucketFacade(deps) {
2371
3492
  emitState("connected");
2372
3493
  }
2373
3494
  };
3495
+ return { bucket, connectInstance };
2374
3496
  }
2375
3497
  function normalizeNamespace(value) {
2376
- const namespace = value === void 0 ? "default" : String(value).trim();
2377
- if (!namespace) throw new Error("namespace is required");
2378
- if (!/^[a-z0-9]{1,32}$/.test(namespace)) {
2379
- 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");
2380
3501
  }
2381
3502
  return namespace;
2382
3503
  }
2383
3504
  function prefixedAdapter(adapter, prefix) {
2384
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}` }))) } : {},
2385
3508
  get: (key) => adapter.get(`${prefix}${key}`),
2386
3509
  set: (key, value) => adapter.set(`${prefix}${key}`, value),
2387
3510
  remove: (key) => adapter.remove(`${prefix}${key}`),
2388
3511
  keys: async (keyPrefix) => (await adapter.keys(`${prefix}${keyPrefix}`)).map((key) => key.slice(prefix.length))
2389
3512
  };
2390
3513
  }
2391
- function addCallbackTransport(url, transport) {
2392
- const parsed = new URL(url, typeof window === "undefined" ? "https://localhost/" : window.location.href);
2393
- parsed.searchParams.set("callbackTransport", transport);
2394
- return parsed.toString();
2395
- }
2396
- function normalizeAuthBase(value) {
2397
- const parsed = new URL(String(value || DEFAULT_AUTH_BASE), typeof window === "undefined" ? DEFAULT_AUTH_BASE : window.location.href);
2398
- const pathname = parsed.pathname.replace(/\/+$/, "");
2399
- parsed.pathname = pathname.endsWith("/auth") ? `${pathname}/` : `${pathname}/auth/`;
2400
- parsed.search = "";
2401
- parsed.hash = "";
2402
- return parsed.toString();
2403
- }
2404
- function apiBaseForAuthBase(authBase) {
2405
- const parsed = new URL(authBase);
2406
- if (parsed.hostname === "myfield.one") return DEFAULT_API_BASE;
2407
- if (parsed.hostname === "dev.myfield.space") return "https://api-dev.myfield.space";
2408
- if (parsed.hostname === "staging.myfield.space") return "https://api-staging.myfield.space";
2409
- return `${parsed.protocol}//api.${parsed.host}`;
2410
- }
2411
- function shouldUseSameTabAuth() {
2412
- if (typeof navigator === "undefined") return false;
2413
- const platform = navigator.platform || "";
2414
- const userAgent = navigator.userAgent || "";
2415
- return /iPad|iPhone|iPod/.test(userAgent) || platform === "MacIntel" && navigator.maxTouchPoints > 1;
3514
+ function isAbortError(error) {
3515
+ return error instanceof Error && error.name === "AbortError";
2416
3516
  }
2417
3517
  function formatError(error) {
2418
3518
  return error instanceof Error ? error.message : String(error);
2419
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
+ }
2420
3539
  export {
3540
+ ClientError,
2421
3541
  NotConnectedError,
2422
3542
  OfflineError,
2423
3543
  createInstance