@mdbase-dev/sdk 0.2.109 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +1 -0
  2. package/dist/app-host/cloud-copy-host.d.ts +3 -1
  3. package/dist/app-host/cloud-copy-host.js +27 -3
  4. package/dist/app-host/cloud-copy-host.js.map +1 -1
  5. package/dist/app-host/http-log.d.ts +12 -2
  6. package/dist/app-host/http-log.js +25 -0
  7. package/dist/app-host/http-log.js.map +1 -1
  8. package/dist/app-host/local-facade.js +3 -1
  9. package/dist/app-host/local-facade.js.map +1 -1
  10. package/dist/app-host/log-pump.js +4 -1
  11. package/dist/app-host/log-pump.js.map +1 -1
  12. package/dist/app-host/log-push.d.ts +12 -0
  13. package/dist/app-host/log-push.js +96 -3
  14. package/dist/app-host/log-push.js.map +1 -1
  15. package/dist/app-host/wasm-runtime.d.ts +5 -0
  16. package/dist/app-host/wasm-runtime.js +9 -0
  17. package/dist/app-host/wasm-runtime.js.map +1 -1
  18. package/dist/app-host/web-sign-in-session.d.ts +6 -2
  19. package/dist/app-host/web-sign-in-session.js +7 -3
  20. package/dist/app-host/web-sign-in-session.js.map +1 -1
  21. package/dist/application/asset-pins.json +4 -4
  22. package/dist/application/file-access.js +14 -2
  23. package/dist/application/file-access.js.map +1 -1
  24. package/dist/application/phase.d.ts +1 -1
  25. package/dist/application/phase.js +7 -2
  26. package/dist/application/phase.js.map +1 -1
  27. package/dist/application/worker.js +424 -66
  28. package/dist/browser/mdbase-sdk.js +462 -78
  29. package/dist/browser/mdbase-sdk.min.js +60 -60
  30. package/dist/client.d.ts +13 -2
  31. package/dist/client.js +28 -13
  32. package/dist/client.js.map +1 -1
  33. package/dist/collection-api.d.ts +1 -1
  34. package/dist/collection-api.js.map +1 -1
  35. package/dist/describe-error.d.ts +2 -2
  36. package/dist/describe-error.js +9 -5
  37. package/dist/describe-error.js.map +1 -1
  38. package/dist/files.d.ts +12 -1
  39. package/dist/files.js +170 -29
  40. package/dist/files.js.map +1 -1
  41. package/dist/native/provenance.json +5 -5
  42. package/dist/native/runtime.wasm +0 -0
  43. package/dist/presence.d.ts +12 -1
  44. package/dist/presence.js +23 -4
  45. package/dist/presence.js.map +1 -1
  46. package/dist/request-deadline.d.ts +4 -0
  47. package/dist/request-deadline.js +30 -0
  48. package/dist/request-deadline.js.map +1 -0
  49. package/dist/settle.js +5 -4
  50. package/dist/settle.js.map +1 -1
  51. package/dist/testing/memory-replica.d.ts +6 -1
  52. package/dist/testing/memory-replica.js +54 -29
  53. package/dist/testing/memory-replica.js.map +1 -1
  54. package/dist/wire.d.ts +4 -1
  55. package/dist/wire.js +3 -1
  56. package/dist/wire.js.map +1 -1
  57. package/dist/write-ledger.d.ts +1 -1
  58. package/dist/write-ledger.js +35 -21
  59. package/dist/write-ledger.js.map +1 -1
  60. package/package.json +1 -1
@@ -15703,12 +15703,12 @@ function appReleaseTrust() {
15703
15703
  // src/application/asset-pins.json
15704
15704
  var asset_pins_default = {
15705
15705
  runtime: {
15706
- sha256: "22ab599e9f32fe8e72c42c388824380c90ab54ddccf331f4eaf695d47e54ea0b",
15707
- bytes: 4201671,
15708
- maxBytes: 4201671,
15706
+ sha256: "30af71a27c5a97592a9380b3d9e3ce683542667fbced7fcd63a188e5d17ac643",
15707
+ bytes: 4261471,
15708
+ maxBytes: 4261471,
15709
15709
  source: {
15710
15710
  repository: "mdbase-dev/mdbase-connect",
15711
- commit: "c106d4a6b427e2b9b39e725e5053d119d76833fd"
15711
+ commit: "3af3e8e1bb878be36a4efc654c70590c413fdb44"
15712
15712
  }
15713
15713
  },
15714
15714
  sqlite: {
@@ -17109,6 +17109,7 @@ var op = mapped(
17109
17109
  (v) => v.kind === "update" && v.requireLive ? { ...v, kind: "update_live" } : v
17110
17110
  );
17111
17111
  var validationLevel = enumOf("level", ["off", "warn", "error"]);
17112
+ var mutationSource = enumOf("source", ["api", "external"]);
17112
17113
  var submitParams = struct("submit-params", [
17113
17114
  [0, "ops", list(op, { nonEmpty: true }), "req1"],
17114
17115
  [1, "mutationId", uuid, "opt"],
@@ -17119,7 +17120,8 @@ var submitParams = struct("submit-params", [
17119
17120
  [6, "dryRun", bool, "opt"],
17120
17121
  [7, "include", include, "opt"],
17121
17122
  [8, "wait", enumOf("wait-for", ["pending", "confirmed", "published"]), "opt"],
17122
- [9, "validation", validationLevel, "opt"]
17123
+ [9, "validation", validationLevel, "opt"],
17124
+ [10, "source", mutationSource, "opt"]
17123
17125
  ]);
17124
17126
  var CONFLICT_FORMS = ["missing", "value", "text", "blob", "deleted"];
17125
17127
  var conflictValue = {
@@ -17387,7 +17389,7 @@ var mutation = struct("mutation", [
17387
17389
  opClock
17388
17390
  ],
17389
17391
  [4, "seed", b32],
17390
- [5, "source", enumOf("source", ["api", "external"])],
17392
+ [5, "source", mutationSource],
17391
17393
  [6, "ops", list(op, { nonEmpty: true }), "req1"],
17392
17394
  [7, "onBehalf", uuid, "opt"],
17393
17395
  [8, "conflictMode", conflictMode, "opt"],
@@ -18477,8 +18479,48 @@ var Session = class _Session {
18477
18479
  }
18478
18480
  };
18479
18481
 
18482
+ // src/request-deadline.ts
18483
+ async function withRequestDeadline(timeoutMs, caller, operation) {
18484
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 2147483647) {
18485
+ throw mdbaseError("invalid_request", "Invalid request deadline.");
18486
+ }
18487
+ const cancelled3 = () => mdbaseError("cancelled", "Request cancelled.");
18488
+ if (caller?.aborted) throw cancelled3();
18489
+ const controller = new AbortController();
18490
+ const abort = () => controller.abort(cancelled3());
18491
+ let stop;
18492
+ const stopped = new Promise((_, reject) => {
18493
+ stop = () => reject(controller.signal.reason);
18494
+ controller.signal.addEventListener("abort", stop, { once: true });
18495
+ });
18496
+ caller?.addEventListener("abort", abort, { once: true });
18497
+ const timer = setTimeout(() => controller.abort(
18498
+ mdbaseError("outcome_unknown", "Request deadline elapsed.", "request_deadline")
18499
+ ), timeoutMs);
18500
+ try {
18501
+ return await Promise.race([stopped, operation(controller.signal)]);
18502
+ } finally {
18503
+ clearTimeout(timer);
18504
+ caller?.removeEventListener("abort", abort);
18505
+ controller.signal.removeEventListener("abort", stop);
18506
+ }
18507
+ }
18508
+
18480
18509
  // src/files.ts
18481
18510
  var REGION_BUSY_WAIT_MS = 9e4;
18511
+ var UPLOAD_STALL_MS = 12e4;
18512
+ function waitForUpload(pending, signal) {
18513
+ if (!signal) return pending;
18514
+ return new Promise((resolve, reject) => {
18515
+ const stop = () => reject(mdbaseError("cancelled", "upload aborted"));
18516
+ if (signal.aborted) {
18517
+ stop();
18518
+ return;
18519
+ }
18520
+ signal.addEventListener("abort", stop, { once: true });
18521
+ pending.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
18522
+ });
18523
+ }
18482
18524
  function regionBusy(e, until) {
18483
18525
  return isMdbaseError(e, "unavailable") && e.reason === "hosted_chunk_busy" && Date.now() < until;
18484
18526
  }
@@ -18664,51 +18706,161 @@ var FilesApi = class {
18664
18706
  ...o.signal ? { signal: o.signal } : {}
18665
18707
  });
18666
18708
  }
18709
+ /** Confirm a completed transfer and return its verified file metadata. The
18710
+ * default 30 s wait covers confirmation, publication and readback together.
18711
+ * On an uncertain outcome, resolve the original mutation before retrying. */
18712
+ async settle(write, options = {}) {
18713
+ const { mutationId, fileId: fileId2 } = write;
18714
+ const timeoutMs = options.timeoutMs ?? 3e4;
18715
+ try {
18716
+ return await withRequestDeadline(timeoutMs, options.signal, async (signal) => {
18717
+ let receipt3 = write.receipt;
18718
+ if (receipt3.state === "pending") {
18719
+ try {
18720
+ receipt3 = await this.client.awaitReceipt(mutationId, { timeoutMs, signal });
18721
+ } catch (cause) {
18722
+ if (signal.aborted) throw signal.reason;
18723
+ throw new MdbaseError({ code: "outcome_unknown", recovery: "resolve_outcome", message: "Could not verify the upload receipt." }, { cause });
18724
+ }
18725
+ }
18726
+ if (receipt3.mutation !== mutationId) throw mdbaseError("internal", "Received an unrelated upload receipt.");
18727
+ if (receipt3.state === "rejected") throw new MdbaseError(receipt3.problem ?? {
18728
+ code: "conflict",
18729
+ recovery: "resolve_conflict",
18730
+ message: "The upload was rejected."
18731
+ });
18732
+ if (receipt3.state !== "confirmed" || receipt3.status !== "applied" || receipt3.conflicts?.length || receipt3.seq === void 0) {
18733
+ throw mdbaseError("outcome_unknown", "The upload has no confirmed applied receipt.");
18734
+ }
18735
+ const publication = write.receipt.published === "published" || write.receipt.published === "not_published" ? write.receipt.published : receipt3.published ?? write.receipt.published;
18736
+ if (publication === "publishing") {
18737
+ await new Promise((resolve, reject) => {
18738
+ const abort = () => {
18739
+ unsubscribe();
18740
+ reject(signal.reason);
18741
+ };
18742
+ const unsubscribe = write.onReceipt((updated) => {
18743
+ if (updated.state !== "rejected" && updated.state !== "unknown" && updated.published !== "published" && updated.published !== "not_published") return;
18744
+ unsubscribe();
18745
+ signal.removeEventListener("abort", abort);
18746
+ if (updated.state === "rejected" && updated.problem) reject(new MdbaseError(updated.problem));
18747
+ else if (updated.state !== "rejected" && updated.state !== "unknown" && updated.published === "published") resolve();
18748
+ else reject(mdbaseError("outcome_unknown", "The file publication was not confirmed."));
18749
+ });
18750
+ if (signal.aborted) abort();
18751
+ else signal.addEventListener("abort", abort, { once: true });
18752
+ });
18753
+ } else if (publication === "not_published") {
18754
+ throw mdbaseError("outcome_unknown", "The file was not published.");
18755
+ }
18756
+ let file;
18757
+ try {
18758
+ file = await this.get(fileId2, { signal });
18759
+ } catch (cause) {
18760
+ if (signal.aborted) throw signal.reason;
18761
+ throw new MdbaseError({ code: "outcome_unknown", recovery: "resolve_outcome", message: "Could not verify the uploaded file." }, { cause });
18762
+ }
18763
+ if (file.id !== fileId2 || file.confirmedSeq !== receipt3.seq || file.hold || file.state === "pending_upload") {
18764
+ throw mdbaseError("outcome_unknown", "The current file does not confirm this upload.");
18765
+ }
18766
+ return file;
18767
+ });
18768
+ } catch (error4) {
18769
+ throw withMutation(error4, "file settlement", { mutationId });
18770
+ }
18771
+ }
18667
18772
  /**
18668
18773
  * Upload a file. Resumable: on a dropped link it reconnects and sends only the chunks
18669
18774
  * the replica lacks. Returns the `file_put` write: `confirmed` means the bytes are
18670
18775
  * durable in the collection. Concurrent calls run in FIFO order on the
18671
- * session's single upload lane; confirmation does not hold up the next upload.
18776
+ * session's single upload lane. A queued caller can cancel immediately. Two
18777
+ * minutes without progress ends the active transfer with `upload_stalled`.
18778
+ * Confirmation runs outside the lane.
18672
18779
  */
18673
18780
  async upload(path, source, o = {}) {
18674
18781
  const options = { ...o };
18675
- const upload = this.uploading.then(() => this.uploadQueued(path, source, options));
18676
- this.uploading = upload.then(() => {
18782
+ const previous = this.uploading;
18783
+ const upload = waitForUpload(previous, options.signal).then(() => this.uploadQueued(path, source, options));
18784
+ const settled = upload.then(() => {
18677
18785
  }, () => {
18678
18786
  });
18787
+ this.uploading = previous.then(() => settled);
18679
18788
  return upload;
18680
18789
  }
18681
18790
  async uploadQueued(path, source, o) {
18682
18791
  gates.get(this)?.check(o.fileId ? "replace" : "add");
18683
18792
  if (o.signal?.aborted) throw mdbaseError("cancelled", "upload aborted");
18793
+ const stalled = new AbortController();
18794
+ const signal = o.signal ? AbortSignal.any([o.signal, stalled.signal]) : stalled.signal;
18795
+ let timer;
18796
+ let active = true;
18797
+ const progress2 = () => {
18798
+ if (!active || signal.aborted) return;
18799
+ clearTimeout(timer);
18800
+ timer = setTimeout(() => stalled.abort(), UPLOAD_STALL_MS);
18801
+ };
18802
+ const mutationId = o.mutationId ?? uuidv7();
18803
+ let commitSent = false;
18804
+ progress2();
18805
+ try {
18806
+ return await this.transfer(path, source, { ...o, signal, mutationId }, progress2, () => {
18807
+ commitSent = true;
18808
+ });
18809
+ } catch (error4) {
18810
+ if (signal.aborted && signal.reason === stalled.signal.reason && isMdbaseError(error4, "cancelled")) {
18811
+ throw withMutation(mdbaseError(
18812
+ commitSent ? "outcome_unknown" : "unavailable",
18813
+ "File upload made no progress for two minutes",
18814
+ "upload_stalled"
18815
+ ), "upload", { mutationId });
18816
+ }
18817
+ throw error4;
18818
+ } finally {
18819
+ active = false;
18820
+ clearTimeout(timer);
18821
+ }
18822
+ }
18823
+ async transfer(path, source, o, progress2, committing) {
18684
18824
  const size2 = sizeOf(source);
18685
18825
  const h = sha256.create();
18686
18826
  const step = 4 * 1024 * 1024;
18687
- for (let off = 0; off < size2; off += step) h.update(await sliceBytes(source, off, Math.min(size2, off + step)));
18827
+ for (let off = 0; off < size2; off += step) {
18828
+ h.update(await waitForUpload(sliceBytes(source, off, Math.min(size2, off + step)), o.signal));
18829
+ progress2();
18830
+ }
18688
18831
  const digest2 = hashFromBytes(h.digest());
18689
18832
  const transfer = o.transferId ?? uuidv7();
18690
- const open2 = { transfer, path, size: size2, digest: digest2, mutationId: o.mutationId ?? uuidv7() };
18833
+ const open2 = { transfer, path, size: size2, digest: digest2, mutationId: o.mutationId };
18691
18834
  if (o.fileId) open2.fileId = o.fileId;
18692
18835
  if (o.ifRevision) open2.ifRevision = o.ifRevision;
18693
- if (o.onProgress) this.progress.set(transfer, o.onProgress);
18836
+ const observed = /* @__PURE__ */ new Map();
18837
+ const onProgress = (p) => {
18838
+ if (p.done > (observed.get(p.phase) ?? -1)) {
18839
+ observed.set(p.phase, p.done);
18840
+ progress2();
18841
+ }
18842
+ o.onProgress?.(p);
18843
+ };
18844
+ this.progress.set(transfer, onProgress);
18694
18845
  const busyUntil = Date.now() + REGION_BUSY_WAIT_MS;
18695
- for (; ; ) {
18696
- try {
18697
- return await this.uploadOnce(source, size2, open2, o);
18698
- } catch (e) {
18699
- if (isMdbaseError(e, "unavailable") && this.client.link === "reconnecting") continue;
18700
- if (regionBusy(e, busyUntil)) {
18846
+ try {
18847
+ for (; ; ) {
18848
+ try {
18849
+ return await this.uploadOnce(source, size2, open2, o, onProgress, committing);
18850
+ } catch (e) {
18851
+ if (!o.signal.aborted && isMdbaseError(e, "unavailable") && this.client.link === "reconnecting") continue;
18852
+ if (!regionBusy(e, busyUntil)) throw e;
18701
18853
  await regionPause(e, "upload", o.signal);
18702
- continue;
18703
18854
  }
18704
- this.progress.delete(transfer);
18705
- await this.abortUpload(transfer).catch(() => {
18706
- });
18707
- throw withMutation(e, "upload", { mutationId: open2.mutationId });
18708
18855
  }
18856
+ } catch (e) {
18857
+ this.progress.delete(transfer);
18858
+ await this.releaseUpload(transfer, AbortSignal.timeout(1e3)).catch(() => {
18859
+ });
18860
+ throw withMutation(e, "upload", { mutationId: open2.mutationId });
18709
18861
  }
18710
18862
  }
18711
- async uploadOnce(source, size2, open2, o) {
18863
+ async uploadOnce(source, size2, open2, o, onProgress, committing) {
18712
18864
  const s = await this.session(o.signal);
18713
18865
  const sig = o.signal ? { signal: o.signal } : {};
18714
18866
  const opened = await s.request("open_upload", openUploadParams.enc(open2), { codec: openUploadResult, ...sig });
@@ -18730,10 +18882,10 @@ var FilesApi = class {
18730
18882
  for (let i = 0; i < chunks; i++) {
18731
18883
  if (have.has(i)) continue;
18732
18884
  const start = i * opened.chunkSize;
18733
- const bytes10 = await sliceBytes(source, start, Math.min(size2, start + opened.chunkSize));
18885
+ const bytes10 = await waitForUpload(sliceBytes(source, start, Math.min(size2, start + opened.chunkSize)), o.signal);
18734
18886
  const p = s.request("upload_chunk", uploadChunkParams.enc({ transfer: open2.transfer, index: i, bytes: bytes10 }), sig).then(() => {
18735
18887
  done += bytes10.length;
18736
- o.onProgress?.({ id: open2.transfer, phase: "receiving", done: Math.min(done, size2), total: size2 });
18888
+ onProgress({ id: open2.transfer, phase: "receiving", done: Math.min(done, size2), total: size2 });
18737
18889
  });
18738
18890
  inflight.add(p);
18739
18891
  void p.finally(() => inflight.delete(p)).catch(() => {
@@ -18741,12 +18893,14 @@ var FilesApi = class {
18741
18893
  if (inflight.size >= 4) await Promise.race(inflight);
18742
18894
  }
18743
18895
  await Promise.all(inflight);
18896
+ committing();
18744
18897
  const r = await s.request("commit_upload", m([[0, uuid.enc(open2.transfer)]]), {
18745
18898
  codec: plainAnswer(receipt),
18746
18899
  ...sig
18747
18900
  });
18748
18901
  const w = Object.assign(this.client._track(r), { fileId: opened.fileId });
18749
18902
  if (o.onProgress) {
18903
+ this.progress.set(open2.transfer, o.onProgress);
18750
18904
  void w.confirmed.finally(() => this.progress.delete(open2.transfer)).catch(() => {
18751
18905
  });
18752
18906
  } else {
@@ -18756,7 +18910,10 @@ var FilesApi = class {
18756
18910
  }
18757
18911
  /** Release the upload lane. An already captured write remains durable; use its receipt to resolve the outcome. */
18758
18912
  abortUpload(transferId) {
18759
- return this.client.call("abort_upload", m([[0, uuid.enc(transferId)]])).then(() => {
18913
+ return this.releaseUpload(transferId);
18914
+ }
18915
+ releaseUpload(transferId, signal) {
18916
+ return this.client.call("abort_upload", m([[0, uuid.enc(transferId)]]), { signal }).then(() => {
18760
18917
  });
18761
18918
  }
18762
18919
  /**
@@ -19054,7 +19211,7 @@ function unknown(mutationId, reason, text6, receipt3) {
19054
19211
  const problem4 = { code: "outcome_unknown", recovery: "resolve_outcome", reason, message: text6 };
19055
19212
  return Object.freeze({ outcome: "unknown", mutationId, ...receipt3 ? { receipt: receipt3 } : {}, problem: problem4 });
19056
19213
  }
19057
- async function settleWrite(client, input, options = {}) {
19214
+ async function settleWrite(client, input, options = {}, mayHaveUnresolved) {
19058
19215
  const signal = options.signal;
19059
19216
  let write;
19060
19217
  let mutationId;
@@ -19065,7 +19222,9 @@ async function settleWrite(client, input, options = {}) {
19065
19222
  receipt3 = await client.receipt(mutationId, { signal });
19066
19223
  } catch (e) {
19067
19224
  if (cancelled(e)) throw e;
19068
- if (isMdbaseError(e, "not_found")) return Object.freeze({ outcome: "rejected", mutationId, problem: e.toProblem() });
19225
+ if (isMdbaseError(e, "not_found") && !mayHaveUnresolved?.(mutationId)) {
19226
+ return Object.freeze({ outcome: "rejected", mutationId, problem: e.toProblem() });
19227
+ }
19069
19228
  return unknown(mutationId, "receipt_unavailable", `The write's result could not be read: ${message(e)}`);
19070
19229
  }
19071
19230
  } else {
@@ -19081,7 +19240,7 @@ async function settleWrite(client, input, options = {}) {
19081
19240
  receipt3 = await client.receipt(mutationId, { signal });
19082
19241
  } catch (lookup) {
19083
19242
  if (cancelled(lookup)) throw lookup;
19084
- if (isMdbaseError(lookup, "not_found")) return Object.freeze({ outcome: "rejected", mutationId, problem: e.toProblem() });
19243
+ if (isMdbaseError(lookup, "not_found") && e instanceof WriteRefusal) return Object.freeze({ outcome: "rejected", mutationId, problem: e.toProblem() });
19085
19244
  return unknown(mutationId, "receipt_unavailable", `The write may have been saved: ${e.message}`);
19086
19245
  }
19087
19246
  }
@@ -20819,6 +20978,7 @@ var RecordSet = class {
20819
20978
 
20820
20979
  // src/presence.ts
20821
20980
  var MAX_PRESENCE_STATE = 4096;
20981
+ var PRESENCE_FEATURE = "presence-v1";
20822
20982
  var MIN_INTERVAL_MS = 100;
20823
20983
  var PresenceApi = class {
20824
20984
  constructor(client) {
@@ -20856,6 +21016,13 @@ var PresenceApi = class {
20856
21016
  throw mdbaseError("too_large", "presence state over 4 KiB", { details: { limit: MAX_PRESENCE_STATE } });
20857
21017
  }
20858
21018
  }
21019
+ /** Whether the connected replica serves presence. False on an older runtime
21020
+ * and on a collection served by the hosted replica: `join` then rejects with
21021
+ * `unavailable` and a subscription stays empty. */
21022
+ async supported() {
21023
+ return (await this.client.ready()).hello.features.includes(PRESENCE_FEATURE);
21024
+ }
21025
+ /** Show this session on a record with `state` (any plain value up to 4 KiB). */
20859
21026
  async join(record3, state) {
20860
21027
  const v = toValue(state);
20861
21028
  this.check(v);
@@ -20887,7 +21054,10 @@ var PresenceApi = class {
20887
21054
  await this.client.call("presence_leave", /* @__PURE__ */ new Map([[0, uuid.enc(record3)]])).catch(() => {
20888
21055
  });
20889
21056
  }
20890
- /** Watch the peers on a record. Returns an unsubscribe function. */
21057
+ /** Watch who else is on a record: every session but this one, on this device
21058
+ * or another, each with a `session` pseudonym that lasts for its join, the
21059
+ * `account` and `app` the replica vouches for when it knows them, and its
21060
+ * state. Called at once and on every change. Returns an unsubscribe function. */
20891
21061
  subscribe(record3, fn) {
20892
21062
  let set2 = this.watchers.get(record3);
20893
21063
  const first = !set2;
@@ -20901,8 +21071,10 @@ var PresenceApi = class {
20901
21071
  });
20902
21072
  }
20903
21073
  return () => {
20904
- set2.delete(fn);
20905
- if (set2.size === 0) this.watchers.delete(record3);
21074
+ if (!set2.delete(fn) || set2.size > 0 || this.watchers.get(record3) !== set2) return;
21075
+ this.watchers.delete(record3);
21076
+ void this.client.ready().then((s) => s.hello.features.includes(PRESENCE_FEATURE) ? s.request("unsubscribe_presence", /* @__PURE__ */ new Map([[0, uuid.enc(record3)]])) : void 0).catch(() => {
21077
+ });
20906
21078
  };
20907
21079
  }
20908
21080
  };
@@ -21147,6 +21319,7 @@ var targets = (ops) => [...new Set(ops.flatMap((op2) => {
21147
21319
  const o = op2, id4 = o.id ?? o.record;
21148
21320
  return typeof id4 === "string" ? [id4] : [];
21149
21321
  }))];
21322
+ var unresolved = (e) => e.state === "pending" || e.problem?.code === "outcome_unknown";
21150
21323
  var entry = (mutationId, records2, state, problem4, createdAt = Date.now()) => problem4 ? { mutationId, records: records2, createdAt, state, problem: problem4 } : { mutationId, records: records2, createdAt, state };
21151
21324
  var WriteLedger = class {
21152
21325
  constructor(store2, native) {
@@ -21201,14 +21374,19 @@ var WriteLedger = class {
21201
21374
  begin(mutationId, ops) {
21202
21375
  return this.set(entry(mutationId, targets(ops), "pending"));
21203
21376
  }
21377
+ /** A stored intent can precede a late submit from another tab. */
21378
+ mayHaveUnresolved(id4) {
21379
+ const e = this.entries.get(id4);
21380
+ return !this.restored || e !== void 0 && unresolved(e);
21381
+ }
21204
21382
  /** @internal Apply a receipt from any source. */
21205
21383
  observe(r) {
21206
21384
  const e = this.entries.get(r.mutation), records2 = e?.records ?? (r.records ?? []).map((v) => v.id);
21207
21385
  if (r.state === "confirmed") {
21208
21386
  if (e) void this.drop(r.mutation);
21209
21387
  } else if (r.state === "pending") {
21210
- if (!e) void this.set(entry(r.mutation, records2, "pending"));
21211
- } else if (e?.state !== "rejected")
21388
+ if (!e || e.problem?.code === "outcome_unknown") void this.set(entry(r.mutation, records2, "pending", void 0, e?.createdAt));
21389
+ } else if (!e || e.state === "pending" || e.problem?.code === "outcome_unknown" && r.state === "rejected")
21212
21390
  void this.set(entry(r.mutation, records2, "rejected", r.problem ?? (r.state === "unknown" ? { code: "outcome_unknown", recovery: "resolve_outcome", message: "mutation unknown" } : { code: "internal", recovery: "contact_support", message: "mutation rejected" }), e?.createdAt));
21213
21391
  }
21214
21392
  /** @internal Reconcile persisted entries with the replica (on open). */
@@ -21218,12 +21396,11 @@ var WriteLedger = class {
21218
21396
  this.store.list().catch(() => []),
21219
21397
  this.native.pendingWrites().catch(() => null)
21220
21398
  ]);
21221
- for (const p of pending ?? [])
21222
- if (!this.entries.has(p.receipt.mutation)) this.entries.set(p.receipt.mutation, entry(p.receipt.mutation, targets(p.ops), "pending"));
21223
- for (const e of stored2) if (e.state === "rejected" || !this.entries.has(e.mutationId)) this.entries.set(e.mutationId, e);
21399
+ for (const e of stored2) if (!unresolved(e) || !this.entries.has(e.mutationId)) this.entries.set(e.mutationId, e);
21400
+ this.adoptPending(pending ?? []);
21224
21401
  this.changed();
21225
21402
  const live = new Set(pending?.map((p) => p.receipt.mutation));
21226
- if (pending) await Promise.all(stored2.filter((e) => e.state === "pending" && !live.has(e.mutationId)).map((e) => this.settle(e.mutationId)));
21403
+ await Promise.all(stored2.filter((e) => unresolved(e) && !live.has(e.mutationId)).map((e) => this.settle(e.mutationId)));
21227
21404
  } finally {
21228
21405
  this.restored = true;
21229
21406
  this.changed();
@@ -21234,7 +21411,9 @@ var WriteLedger = class {
21234
21411
  if (this.checking) return;
21235
21412
  this.checking = true;
21236
21413
  try {
21237
- for (const e of this.getSnapshot().pending) await this.settle(e.mutationId);
21414
+ for (const e of this.entries.values()) {
21415
+ if (unresolved(e)) await this.settle(e.mutationId, "ignore");
21416
+ }
21238
21417
  } finally {
21239
21418
  this.checking = false;
21240
21419
  }
@@ -21243,20 +21422,29 @@ var WriteLedger = class {
21243
21422
  * (another tab of the same session wrote them): list them as pending too. */
21244
21423
  async adopt() {
21245
21424
  const pending = await this.native.pendingWrites().catch(() => null);
21425
+ if (pending && this.adoptPending(pending)) this.changed();
21426
+ }
21427
+ adoptPending(pending) {
21246
21428
  let added = false;
21247
- for (const p of pending ?? [])
21248
- if (!this.entries.has(p.receipt.mutation)) {
21249
- this.entries.set(p.receipt.mutation, entry(p.receipt.mutation, targets(p.ops), "pending"));
21429
+ for (const p of pending) {
21430
+ const id4 = p.receipt.mutation, e = this.entries.get(id4);
21431
+ if (!e || e.problem?.code === "outcome_unknown") {
21432
+ this.entries.set(id4, entry(id4, targets(p.ops), "pending", void 0, e?.createdAt));
21250
21433
  added = true;
21251
21434
  }
21252
- if (added) this.changed();
21435
+ }
21436
+ return added;
21253
21437
  }
21254
- /** @internal A submit call failed: ask the replica whether it captured the write. */
21255
- async settle(id4) {
21438
+ /** Only a definite submit refusal delivered to the caller can retire an
21439
+ * intent without a receipt. A status recheck can race an in-flight submit. */
21440
+ async settle(id4, missing = "unknown") {
21441
+ const e = this.entries.get(id4);
21256
21442
  try {
21257
21443
  this.observe(await this.native.receipt(id4));
21258
21444
  } catch (error4) {
21259
- if (isMdbaseError(error4, "not_found") && this.entries.get(id4)?.state === "pending") await this.drop(id4);
21445
+ if (!isMdbaseError(error4, "not_found") || !e || this.entries.get(id4) !== e || !unresolved(e)) return;
21446
+ if (missing === "refused") await this.drop(id4);
21447
+ else if (missing === "unknown" && e.state === "pending") this.observe({ mutation: id4, state: "unknown" });
21260
21448
  }
21261
21449
  }
21262
21450
  set(e) {
@@ -21317,6 +21505,7 @@ var BASES_DISCOVERY_UNREADABLE = "bases-discovery-unreadable-v1";
21317
21505
  var BASES_ROW_PROPERTIES = "bases-row-properties-v1";
21318
21506
  var CONTRACT_QUERY_ORDER = "contract-query-order-v1";
21319
21507
  var CONTRACT_QUERY_ORDER_MTIME = "contract-query-order-mtime-v1";
21508
+ var SUBMIT_EXTERNAL_SOURCE = "submit-external-source-v1";
21320
21509
  function params(entries) {
21321
21510
  const m2 = /* @__PURE__ */ new Map();
21322
21511
  for (const [k, v] of entries) if (v !== void 0) m2.set(k, v);
@@ -21617,16 +21806,18 @@ var MdbaseClient = class _MdbaseClient {
21617
21806
  startLedger() {
21618
21807
  if (this.ledgerStarted) return;
21619
21808
  this.ledgerStarted = true;
21620
- let pending = -1;
21809
+ const restored = this.writeLedger.restore();
21810
+ let previous = this.lastStatus;
21621
21811
  this.onStatus((s) => {
21622
- const fell = pending > s.pending;
21623
- pending = s.pending;
21812
+ const settled = s.pending < previous.pending || s.confirmedThrough > previous.confirmedThrough;
21813
+ previous = s;
21624
21814
  this.updateDeferred();
21625
- if (fell) void this.writeLedger.recheck();
21626
- else if (s.pending > this.writeLedger.pendingCount) void this.writeLedger.adopt();
21815
+ void restored.then(async () => {
21816
+ if (settled) await this.writeLedger.recheck();
21817
+ if (this.lastStatus.pending > this.writeLedger.pendingCount) await this.writeLedger.adopt();
21818
+ });
21627
21819
  });
21628
21820
  this.onLink(() => this.updateDeferred());
21629
- void this.writeLedger.restore();
21630
21821
  }
21631
21822
  updateDeferred() {
21632
21823
  this.writeLedger.setDeferred(this.transportDeferred || this.linkState !== "open" || this.lastStatus.connection === "offline");
@@ -21722,7 +21913,7 @@ var MdbaseClient = class _MdbaseClient {
21722
21913
  versions: API_VERSIONS,
21723
21914
  clientName: opts.app.name,
21724
21915
  clientVersion: opts.app.version,
21725
- features: [.../* @__PURE__ */ new Set([...opts.features ?? [], "declared-collection-setup-v1", "file-stream-failure-v1", VALIDATE_PAGE, BASES_DISCOVERY_UNREADABLE, BASES_ROW_PROPERTIES, CONTRACT_QUERY_ORDER, CONTRACT_QUERY_ORDER_MTIME])],
21916
+ features: [.../* @__PURE__ */ new Set([...opts.features ?? [], PRESENCE_FEATURE, "declared-collection-setup-v1", "file-stream-failure-v1", VALIDATE_PAGE, BASES_DISCOVERY_UNREADABLE, BASES_ROW_PROPERTIES, CONTRACT_QUERY_ORDER, CONTRACT_QUERY_ORDER_MTIME, SUBMIT_EXTERNAL_SOURCE])],
21726
21917
  ...tz ? { timezone: tz } : {}
21727
21918
  };
21728
21919
  }
@@ -22906,6 +23097,12 @@ var MdbaseClient = class _MdbaseClient {
22906
23097
  /** Submit operations as one mutation: they apply together or not at all. */
22907
23098
  async submit(ops, o = {}) {
22908
23099
  if (this.hello.version.minor >= 3 && this.hello.grant.role === "viewer") throw new WriteRefusal(mdbaseError("forbidden", "You have view access, so changes can't be saved.", "read_only"));
23100
+ if (o.source === "external" && !this.hello.features.includes(SUBMIT_EXTERNAL_SOURCE)) {
23101
+ if (this.hello.grant.grant !== void 0) {
23102
+ throw new WriteRefusal(mdbaseError("forbidden", "External-source submits require a local host session.", "external_source_forbidden"));
23103
+ }
23104
+ throw new WriteRefusal(mdbaseError("upgrade_required", "This collection's replica does not support external-source submits.", "external_source_unsupported"));
23105
+ }
22909
23106
  if (o.intent !== void 0 && o.mutationId === void 0) o = { ...o, mutationId: (await intentIds(this.collectionId, o.intent))[0] };
22910
23107
  const mutationId = o.mutationId ?? uuidv7();
22911
23108
  const p = { ops, mutationId };
@@ -22915,6 +23112,7 @@ var MdbaseClient = class _MdbaseClient {
22915
23112
  if (o.include) p.include = o.include;
22916
23113
  if (o.wait) p.wait = o.wait;
22917
23114
  if (o.validation) p.validation = o.validation;
23115
+ if (o.source) p.source = o.source;
22918
23116
  if (!o.dryRun) {
22919
23117
  this.startLedger();
22920
23118
  await this.writeLedger.begin(mutationId, ops);
@@ -22930,7 +23128,6 @@ var MdbaseClient = class _MdbaseClient {
22930
23128
  receipt3 = receipts[0];
22931
23129
  } catch (e) {
22932
23130
  if (o.dryRun) throw e;
22933
- void this.writeLedger.settle(mutationId);
22934
23131
  if (isReplicaResponseProblem(e) && [
22935
23132
  "invalid_request",
22936
23133
  "invalid_record",
@@ -22942,7 +23139,11 @@ var MdbaseClient = class _MdbaseClient {
22942
23139
  "rate_limited",
22943
23140
  "too_large",
22944
23141
  "upgrade_required"
22945
- ].includes(e.code)) throw new WriteRefusal(e, { mutationId });
23142
+ ].includes(e.code)) {
23143
+ void this.writeLedger.settle(mutationId, "refused");
23144
+ throw new WriteRefusal(e, { mutationId });
23145
+ }
23146
+ void this.writeLedger.settle(mutationId);
22946
23147
  throw withMutation(e, "submit", { mutationId });
22947
23148
  }
22948
23149
  return o.dryRun ? new Write(receipt3) : this._track(receipt3);
@@ -23125,7 +23326,7 @@ var MdbaseClient = class _MdbaseClient {
23125
23326
  * if (saved.outcome === "rejected") show(describeError(saved.problem));
23126
23327
  */
23127
23328
  settle(write, options = {}) {
23128
- return settleWrite(this, write, options);
23329
+ return settleWrite(this, write, options, (id4) => this.ledgerStarted && this.writeLedger.mayHaveUnresolved(id4));
23129
23330
  }
23130
23331
  /** The current receipt of a mutation. Failures carry `mutationId`. `o.signal` cancels the read. */
23131
23332
  receipt(mutation2, o = {}) {
@@ -25599,9 +25800,12 @@ var SpareNonces = class {
25599
25800
  var MAX_FRAME2 = 16 * 1024 * 1024;
25600
25801
  var MAX_OBJECT = 9 * 1024 * 1024;
25601
25802
  var METHODS = /* @__PURE__ */ new Set(["append", "read", "head", "subscribe", "unsubscribe", "put_object", "get_object", "has_objects", "put_snapshot", "get_snapshot", "endorse_snapshot", "stream_join", "stream_leave", "stream_send"]);
25803
+ var STREAM_METHODS = /* @__PURE__ */ new Set(["stream_join", "stream_leave", "stream_send"]);
25602
25804
  var FORBIDDEN = /* @__PURE__ */ new Set(["host", "content-length", "transfer-encoding", "connection", "keep-alive", "upgrade", "te", "trailer", "expect", "range", "cookie", "authorization", "proxy-authorization", "origin", "referer", "accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "date", "dnt", "permissions-policy", "set-cookie", "via"]);
25603
25805
  var utf82 = new TextEncoder();
25604
25806
  var AppHttpLogError = class extends Error {
25807
+ /** `no_stream`: a stream call had no live push socket to travel on or got no
25808
+ * answer there. It says nothing about the HTTPS path to the log. */
25605
25809
  constructor(reason, server) {
25606
25810
  super(`app log transport: ${reason}`);
25607
25811
  this.reason = reason;
@@ -25710,6 +25914,12 @@ var AppHttpLogTransport = class {
25710
25914
  spares;
25711
25915
  responseId = 0;
25712
25916
  receiving = /* @__PURE__ */ new Map();
25917
+ streams = null;
25918
+ /** HOST ONLY: the push socket of this same authenticated generation, or null
25919
+ * when there is none. Stream calls fail as unanswered without it. */
25920
+ setStreamRoute(route2) {
25921
+ this.streams = route2;
25922
+ }
25713
25923
  /** Only active logical sends, with bytes admitted under the existing body /
25714
25924
  * range caps. Provisional network activity, never authenticated sync progress. */
25715
25925
  responseProgress() {
@@ -26012,6 +26222,20 @@ var AppHttpLogTransport = class {
26012
26222
  sidecar = call2.sidecar?.slice() ?? null;
26013
26223
  const request3 = this.request(frame);
26014
26224
  if (sidecar && request3.method !== "put_object") throw error("shape");
26225
+ if (STREAM_METHODS.has(request3.method)) {
26226
+ const route2 = this.streams;
26227
+ if (!route2) throw error("no_stream");
26228
+ try {
26229
+ reply = await route2(frame, options);
26230
+ } catch {
26231
+ throw error(options.signal.aborted || !this.isCurrent() ? "fenced" : "no_stream");
26232
+ }
26233
+ this.check(options.signal);
26234
+ this.response(reply, request3.id);
26235
+ const out2 = reply;
26236
+ reply = null;
26237
+ return out2;
26238
+ }
26015
26239
  if (request3.method === "put_object") {
26016
26240
  const size2 = number(request3.params.get(3), MAX_OBJECT), ck = bytes3(request3.params.get(4), 32), inline = request3.params.get(5);
26017
26241
  if (size2 === 0 || sidecar !== null && (inline !== void 0 || sidecar.length <= 1024 * 1024) || sidecar === null && size2 > 1024 * 1024) throw error("shape");
@@ -27039,6 +27263,10 @@ var OPEN_MS = 15e3;
27039
27263
  var UNSIGNED_ATTEMPTS = 4;
27040
27264
  var INLINE_BYTES = 64 * 1024;
27041
27265
  var MAX_FRAME3 = 1024 * 1024;
27266
+ var STREAM_METHODS2 = /* @__PURE__ */ new Set(["stream_join", "stream_leave", "stream_send"]);
27267
+ var STREAM_REPLY_MS = 1e4;
27268
+ var MAX_STREAM_CALLS = 64;
27269
+ var MAX_STREAM_FRAME = 32 * 1024;
27042
27270
  function wsOrigin(input, loopback) {
27043
27271
  const u = new URL(input);
27044
27272
  if (u.protocol === "https:") return `wss://${u.host}`;
@@ -27047,6 +27275,10 @@ function wsOrigin(input, loopback) {
27047
27275
  }
27048
27276
  var hex6 = (b) => [...b].map((v) => v.toString(16).padStart(2, "0")).join("");
27049
27277
  var request = (id4, method, params2) => encode(/* @__PURE__ */ new Map([[0, 0], [1, id4], [2, method], [3, params2]]));
27278
+ function callKey(id4) {
27279
+ if (typeof id4 === "bigint" ? id4 < 0n : typeof id4 !== "number" || !Number.isSafeInteger(id4) || id4 < 0) throw new Error("app log push: id");
27280
+ return BigInt(id4).toString();
27281
+ }
27050
27282
  function errorOf(m2) {
27051
27283
  const e = m2.get(3);
27052
27284
  if (!(e instanceof Map)) return null;
@@ -27088,6 +27320,11 @@ var AppLogPushChannel = class {
27088
27320
  unsigned = 0;
27089
27321
  life = new AbortController();
27090
27322
  token = null;
27323
+ /** Which response the current socket owes next: its `hello` (id 1), its
27324
+ * `subscribe` (id 2), and after that only answers to stream calls, whose IDs
27325
+ * are the replica's own and may be any number. */
27326
+ phase = "hello";
27327
+ calls = /* @__PURE__ */ new Map();
27091
27328
  /** Live: subscribed, so other devices' changes arrive as they commit. */
27092
27329
  get live() {
27093
27330
  return this.isLive;
@@ -27135,6 +27372,64 @@ var AppLogPushChannel = class {
27135
27372
  this.clearRetry();
27136
27373
  this.drop(1e3, "closed");
27137
27374
  }
27375
+ /** Send one replica-made stream call and resolve with the service's response
27376
+ * frame, unread: the replica checks it against its own original call. Rejects
27377
+ * when the socket is not live, is lost before the answer, or the answer does
27378
+ * not come; all three are an unknown outcome to the replica, never a retry here. */
27379
+ request(frame, options) {
27380
+ return new Promise((resolve, reject) => {
27381
+ const no = (why) => reject(new Error(`app log push: ${why}`));
27382
+ const s = this.socket;
27383
+ if (!s || !this.isLive) {
27384
+ no("not live");
27385
+ return;
27386
+ }
27387
+ if (!(frame instanceof Uint8Array) || frame.length > MAX_STREAM_FRAME || this.calls.size >= MAX_STREAM_CALLS) {
27388
+ no("call");
27389
+ return;
27390
+ }
27391
+ let key3;
27392
+ try {
27393
+ const v = decode(frame);
27394
+ if (!(v instanceof Map)) throw new Error();
27395
+ const m2 = v;
27396
+ if (m2.get(0) !== 0 || !STREAM_METHODS2.has(m2.get(2))) throw new Error();
27397
+ key3 = callKey(m2.get(1));
27398
+ } catch {
27399
+ no("call");
27400
+ return;
27401
+ }
27402
+ if (this.calls.has(key3) || options.signal.aborted) {
27403
+ no("call");
27404
+ return;
27405
+ }
27406
+ const settle = () => {
27407
+ clearTimeout(call2.timer);
27408
+ options.signal.removeEventListener("abort", call2.stop);
27409
+ this.calls.delete(key3);
27410
+ };
27411
+ const call2 = {
27412
+ resolve: (reply) => {
27413
+ settle();
27414
+ resolve(reply);
27415
+ },
27416
+ reject: (error4) => {
27417
+ settle();
27418
+ reject(error4);
27419
+ },
27420
+ timer: setTimeout(() => call2.reject(new Error("app log push: no reply")), STREAM_REPLY_MS),
27421
+ stop: () => call2.reject(new Error("app log push: aborted"))
27422
+ };
27423
+ options.signal.addEventListener("abort", call2.stop, { once: true });
27424
+ this.calls.set(key3, call2);
27425
+ try {
27426
+ s.send(frame);
27427
+ } catch {
27428
+ call2.reject(new Error("app log push: send"));
27429
+ this.lost(s, 1006);
27430
+ }
27431
+ });
27432
+ }
27138
27433
  clearRetry() {
27139
27434
  if (this.retry !== null) clearTimeout(this.retry);
27140
27435
  this.retry = null;
@@ -27177,6 +27472,7 @@ var AppLogPushChannel = class {
27177
27472
  } catch {
27178
27473
  }
27179
27474
  }
27475
+ for (const call2 of [...this.calls.values()]) call2.reject(new Error("app log push: lost"));
27180
27476
  this.setLive(false);
27181
27477
  }
27182
27478
  /** Full-jitter backoff, 1 s → 60 s; reset after a minute of a healthy socket. */
@@ -27226,6 +27522,7 @@ var AppLogPushChannel = class {
27226
27522
  }
27227
27523
  s.binaryType = "arraybuffer";
27228
27524
  this.socket = s;
27525
+ this.phase = "hello";
27229
27526
  const hello = request(1, "hello", /* @__PURE__ */ new Map([[0, [1, 0]], [1, token], [2, uuidToBytes(this.source.deviceId)], [3, sig]]));
27230
27527
  sig.fill(0);
27231
27528
  nonce.fill(0);
@@ -27279,11 +27576,23 @@ var AppLogPushChannel = class {
27279
27576
  }
27280
27577
  if (m2.get(0) !== 1) return;
27281
27578
  const id4 = m2.get(1), error4 = errorOf(m2);
27282
- if (id4 === 1) {
27579
+ if (this.phase === "live") {
27580
+ let key3;
27581
+ try {
27582
+ key3 = callKey(id4);
27583
+ } catch {
27584
+ return;
27585
+ }
27586
+ this.calls.get(key3)?.resolve(bytes10.slice());
27587
+ return;
27588
+ }
27589
+ if (this.phase === "hello") {
27590
+ if (id4 !== 1) return;
27283
27591
  if (error4) {
27284
27592
  this.refused(s, error4);
27285
27593
  return;
27286
27594
  }
27595
+ this.phase = "subscribe";
27287
27596
  try {
27288
27597
  s.send(request(2, "subscribe", /* @__PURE__ */ new Map([[0, this.collectionBytes], [1, 0], [2, INLINE_BYTES]])));
27289
27598
  } catch {
@@ -27302,6 +27611,7 @@ var AppLogPushChannel = class {
27302
27611
  return;
27303
27612
  }
27304
27613
  const head = result2.get(0), chain = result2.get(1);
27614
+ this.phase = "live";
27305
27615
  this.startPing(s);
27306
27616
  this.setLive(true);
27307
27617
  if ((typeof head === "number" || typeof head === "bigint") && chain instanceof Uint8Array && chain.length === 32)
@@ -27901,7 +28211,23 @@ function bridge(channel, source, receive, ended, bases) {
27901
28211
  current: current2
27902
28212
  };
27903
28213
  }
27904
- var LOG_WORK = /* @__PURE__ */ new Set(["submit", "resolve_hold", "open_upload", "upload_chunk", "commit_upload", "abort_upload", "fetch_file", "read_file", "ack_chunks"]);
28214
+ var LOG_WORK = /* @__PURE__ */ new Set([
28215
+ "submit",
28216
+ "resolve_hold",
28217
+ "open_upload",
28218
+ "upload_chunk",
28219
+ "commit_upload",
28220
+ "abort_upload",
28221
+ "fetch_file",
28222
+ "read_file",
28223
+ "ack_chunks",
28224
+ // Presence joins a stream and sends on it: other people see it now, not on the next turn.
28225
+ "presence_join",
28226
+ "presence_update",
28227
+ "presence_leave",
28228
+ "subscribe_presence",
28229
+ "unsubscribe_presence"
28230
+ ]);
27905
28231
  function queuesLogWork(frame) {
27906
28232
  if (!(frame instanceof Map)) return false;
27907
28233
  const fields3 = frame;
@@ -33873,6 +34199,7 @@ function equal8(a, b) {
33873
34199
  }
33874
34200
  var UNORDERED = /* @__PURE__ */ new Set(["read", "head", "subscribe", "get_object", "has_objects", "put_object", "get_snapshot"]);
33875
34201
  var MAX_CONCURRENT = 6;
34202
+ var STREAM = /* @__PURE__ */ new Set(["stream_join", "stream_leave", "stream_send"]);
33876
34203
  function serverOf(e) {
33877
34204
  try {
33878
34205
  return e.server;
@@ -34073,7 +34400,7 @@ var AppLogPump = class {
34073
34400
  continue;
34074
34401
  }
34075
34402
  if (this.runtime.acceptLogReply(c.id, reply) !== true) this.runtime.logNoResponse(c.id);
34076
- else {
34403
+ else if (!STREAM.has(c.method)) {
34077
34404
  this.problem = null;
34078
34405
  this.health = null;
34079
34406
  if (c.read) {
@@ -35839,6 +36166,14 @@ var AppWasmRuntime = class _AppWasmRuntime extends WasmRuntime {
35839
36166
  owned?.fill(0);
35840
36167
  }
35841
36168
  }
36169
+ /** HOST ONLY: the push socket became subscribed (true) or was lost (false).
36170
+ * Ephemeral stream calls travel on that socket and the log drops a socket's
36171
+ * stream memberships with it, so the replica joins again on true and forgets
36172
+ * the people it had seen on false. False when unsupported or not bound. */
36173
+ setLogStreamLink(up) {
36174
+ if (!this.active || this.retired || !this.pump || typeof this.app.rt_app_log_stream_link !== "function") return false;
36175
+ return this.guard(() => this.app.rt_app_log_stream_link(up ? 1 : 0)) === 1;
36176
+ }
35842
36177
  /** HOST ONLY wake AFTER fresh authenticated authority admission: drain/abort
35843
36178
  * original pump before SAME-owner native session/generation replacement. May
35844
36179
  * hang: owner must terminate Worker before releasing lease. Not readiness. */
@@ -38218,7 +38553,9 @@ var AppWebCloudCopyHost = class _AppWebCloudCopyHost {
38218
38553
  }
38219
38554
  /** The log's push socket for this collection, or null when the runtime cannot
38220
38555
  * sign its `hello` (older native asset): then the caller wakes on events only.
38221
- * Requires the started log. The socket never carries requests. */
38556
+ * Requires the started log. The socket carries no log requests; it does carry
38557
+ * the replica's ephemeral stream calls (presence), whose memberships are the
38558
+ * socket's own, and tells the replica when that link comes and goes. */
38222
38559
  openLogPush(events) {
38223
38560
  this.checkCollection(this.lifetime);
38224
38561
  const native = this.native, authority = this.authority, session = this.collectionSession, request3 = this.logRequest;
@@ -38232,7 +38569,8 @@ var AppWebCloudCopyHost = class _AppWebCloudCopyHost {
38232
38569
  return false;
38233
38570
  }
38234
38571
  };
38235
- return new AppLogPushChannel({
38572
+ const transport = authority.logTransport();
38573
+ const channel = new AppLogPushChannel({
38236
38574
  origin: origin4,
38237
38575
  collection: authority.collection,
38238
38576
  deviceId: session.deviceId,
@@ -38246,7 +38584,25 @@ var AppWebCloudCopyHost = class _AppWebCloudCopyHost {
38246
38584
  return Uint8Array.from(text6.match(/../g).map((v) => parseInt(v, 16)));
38247
38585
  },
38248
38586
  signHello: (nonce, token) => current2() ? native.signLogHello(nonce, token) : null
38249
- }, events, { allowLoopbackHttp: loopback });
38587
+ }, {
38588
+ push: events.push,
38589
+ ended: events.ended,
38590
+ live: (live) => {
38591
+ try {
38592
+ if (current2()) native.setLogStreamLink(live);
38593
+ } catch {
38594
+ }
38595
+ events.live(live);
38596
+ if (live) {
38597
+ try {
38598
+ this.logWorkListener?.();
38599
+ } catch {
38600
+ }
38601
+ }
38602
+ }
38603
+ }, { allowLoopbackHttp: loopback });
38604
+ transport.setStreamRoute((frame, options) => channel.request(frame, options));
38605
+ return channel;
38250
38606
  }
38251
38607
  /** Ordinary foreground log drive. Quiet/head/ACK/status are NOT read/Saved. */
38252
38608
  async driveCollection(options) {
@@ -39344,15 +39700,17 @@ var AppWebSignInSession = class {
39344
39700
  }, true);
39345
39701
  }
39346
39702
  /** One read of the current file access request. Lost reads stay pending
39347
- * until the request expires; a busy session answers with the current view. */
39703
+ * until the request expires. A skipped or failed read rejects so callers can
39704
+ * distinguish it from a confirmed pending outcome. */
39348
39705
  pollFileAccess(requestId) {
39349
39706
  const request3 = this.fileAccess;
39350
- if (!request3 || request3.requestId !== requestId || this.pending || !this.flow || !this.installation) return Promise.resolve(this.getSnapshot());
39707
+ if (!request3 || request3.requestId !== requestId || !this.flow || !this.installation) return Promise.resolve(this.getSnapshot());
39351
39708
  return this.operation(async () => {
39352
39709
  let outcome = { state: "pending" };
39353
39710
  try {
39354
39711
  outcome = await this.flow.exchangeFileAccess(this.installation, request3);
39355
- } catch {
39712
+ } catch (error4) {
39713
+ if (Date.now() < request3.expiresAt) throw error4;
39356
39714
  }
39357
39715
  this.check();
39358
39716
  if (this.fileAccess !== request3 || outcome.state === "pending" && Date.now() < request3.expiresAt) return this.getSnapshot();