@mdbase-dev/sdk 0.1.0-beta.186 → 0.1.0-beta.188

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 (167) hide show
  1. package/README.md +189 -925
  2. package/dist/app-grant/client.js +7 -3
  3. package/dist/app-grant/client.js.map +1 -1
  4. package/dist/app-grant/setup.js +2 -2
  5. package/dist/app-grant/setup.js.map +1 -1
  6. package/dist/app-host/cloud-copy-host.js +1 -1
  7. package/dist/app-host/cloud-copy-host.js.map +1 -1
  8. package/dist/app-host/collection-readiness.js +10 -12
  9. package/dist/app-host/collection-readiness.js.map +1 -1
  10. package/dist/app-host/handover.js +1 -1
  11. package/dist/app-host/handover.js.map +1 -1
  12. package/dist/app-host/initial-sync.js +4 -4
  13. package/dist/app-host/initial-sync.js.map +1 -1
  14. package/dist/app-host/installation-sign-in.d.ts +3 -0
  15. package/dist/app-host/installation-sign-in.js +11 -2
  16. package/dist/app-host/installation-sign-in.js.map +1 -1
  17. package/dist/app-host/web-sign-in-session.d.ts +2 -0
  18. package/dist/app-host/web-sign-in-session.js +25 -3
  19. package/dist/app-host/web-sign-in-session.js.map +1 -1
  20. package/dist/application/asset-pins.json +4 -4
  21. package/dist/application/browser-capabilities.d.ts +1 -1
  22. package/dist/application/browser-capabilities.js +3 -2
  23. package/dist/application/browser-capabilities.js.map +1 -1
  24. package/dist/application/configuration.js +12 -12
  25. package/dist/application/configuration.js.map +1 -1
  26. package/dist/application/entry.d.ts +69 -108
  27. package/dist/application/entry.js +164 -91
  28. package/dist/application/entry.js.map +1 -1
  29. package/dist/application/front-door.d.ts +30 -12
  30. package/dist/application/front-door.js +2 -89
  31. package/dist/application/front-door.js.map +1 -1
  32. package/dist/application/packaged-assets.d.ts +5 -2
  33. package/dist/application/packaged-assets.js +9 -6
  34. package/dist/application/packaged-assets.js.map +1 -1
  35. package/dist/application/phase.d.ts +4 -1
  36. package/dist/application/phase.js +5 -4
  37. package/dist/application/phase.js.map +1 -1
  38. package/dist/application/private-collections.js +2 -1
  39. package/dist/application/private-collections.js.map +1 -1
  40. package/dist/application/registration-refusal.d.ts +1 -1
  41. package/dist/application/registration-refusal.js +1 -3
  42. package/dist/application/registration-refusal.js.map +1 -1
  43. package/dist/application/registration.js +1 -4
  44. package/dist/application/registration.js.map +1 -1
  45. package/dist/application/setup.d.ts +6 -9
  46. package/dist/application/setup.js +16 -0
  47. package/dist/application/setup.js.map +1 -1
  48. package/dist/application/tabs.d.ts +15 -2
  49. package/dist/application/tabs.js +35 -13
  50. package/dist/application/tabs.js.map +1 -1
  51. package/dist/application/unsynced-transfer.d.ts +1 -1
  52. package/dist/application/unsynced-transfer.js +3 -3
  53. package/dist/application/unsynced-transfer.js.map +1 -1
  54. package/dist/application/worker.js +969 -465
  55. package/dist/application/worker.js.map +1 -1
  56. package/dist/browser/mdbase-sdk.js +21319 -20764
  57. package/dist/browser/mdbase-sdk.min.js +65 -65
  58. package/dist/browser.d.ts +1 -0
  59. package/dist/browser.js +1 -0
  60. package/dist/browser.js.map +1 -1
  61. package/dist/client.d.ts +169 -81
  62. package/dist/client.js +236 -178
  63. package/dist/client.js.map +1 -1
  64. package/dist/codec.d.ts +15 -0
  65. package/dist/codec.js +44 -2
  66. package/dist/codec.js.map +1 -1
  67. package/dist/collection-api.d.ts +44 -0
  68. package/dist/collection-api.js +24 -0
  69. package/dist/collection-api.js.map +1 -0
  70. package/dist/collection-availability.js +1 -1
  71. package/dist/collection-availability.js.map +1 -1
  72. package/dist/contract-query.d.ts +22 -3
  73. package/dist/contract-query.js.map +1 -1
  74. package/dist/contract-records.d.ts +2 -1
  75. package/dist/contract-records.js.map +1 -1
  76. package/dist/describe-error.d.ts +1 -1
  77. package/dist/describe-error.js +7 -6
  78. package/dist/describe-error.js.map +1 -1
  79. package/dist/errors.d.ts +3 -5
  80. package/dist/errors.js +3 -8
  81. package/dist/errors.js.map +1 -1
  82. package/dist/files.d.ts +7 -5
  83. package/dist/files.js +16 -17
  84. package/dist/files.js.map +1 -1
  85. package/dist/holds.d.ts +2 -1
  86. package/dist/holds.js.map +1 -1
  87. package/dist/index.d.ts +7 -11
  88. package/dist/index.js +5 -7
  89. package/dist/index.js.map +1 -1
  90. package/dist/live.d.ts +2 -1
  91. package/dist/live.js.map +1 -1
  92. package/dist/manifest.d.ts +1 -1
  93. package/dist/manifest.js +1 -1
  94. package/dist/native/provenance.json +5 -5
  95. package/dist/native/runtime.wasm +0 -0
  96. package/dist/people.js +3 -7
  97. package/dist/people.js.map +1 -1
  98. package/dist/plain.d.ts +102 -0
  99. package/dist/plain.js +62 -0
  100. package/dist/plain.js.map +1 -0
  101. package/dist/presence.d.ts +2 -1
  102. package/dist/presence.js +3 -3
  103. package/dist/presence.js.map +1 -1
  104. package/dist/read-helpers.d.ts +8 -6
  105. package/dist/read-helpers.js +20 -13
  106. package/dist/read-helpers.js.map +1 -1
  107. package/dist/record-set.d.ts +98 -0
  108. package/dist/record-set.js +347 -0
  109. package/dist/record-set.js.map +1 -0
  110. package/dist/records/session.d.ts +2 -1
  111. package/dist/records/session.js +22 -20
  112. package/dist/records/session.js.map +1 -1
  113. package/dist/records/types.d.ts +5 -3
  114. package/dist/records/witness.d.ts +7 -4
  115. package/dist/records/witness.js +13 -8
  116. package/dist/records/witness.js.map +1 -1
  117. package/dist/records.js +5 -2
  118. package/dist/records.js.map +1 -1
  119. package/dist/saved-views.d.ts +12 -4
  120. package/dist/saved-views.js +51 -43
  121. package/dist/saved-views.js.map +1 -1
  122. package/dist/settle.d.ts +62 -0
  123. package/dist/settle.js +119 -0
  124. package/dist/settle.js.map +1 -0
  125. package/dist/status.d.ts +84 -28
  126. package/dist/status.js +54 -48
  127. package/dist/status.js.map +1 -1
  128. package/dist/testing/application.d.ts +16 -9
  129. package/dist/testing/application.js +48 -45
  130. package/dist/testing/application.js.map +1 -1
  131. package/dist/testing/index.d.ts +2 -2
  132. package/dist/testing/memory-contracts.d.ts +5 -0
  133. package/dist/testing/memory-contracts.js.map +1 -1
  134. package/dist/testing/memory-replica.d.ts +58 -5
  135. package/dist/testing/memory-replica.js +126 -19
  136. package/dist/testing/memory-replica.js.map +1 -1
  137. package/dist/testing/test-app.d.ts +9 -10
  138. package/dist/testing/test-app.js +8 -17
  139. package/dist/testing/test-app.js.map +1 -1
  140. package/dist/thin-client.d.ts +15 -38
  141. package/dist/thin-client.js +11 -20
  142. package/dist/thin-client.js.map +1 -1
  143. package/dist/transport/control-route.js +1 -1
  144. package/dist/transport/control-route.js.map +1 -1
  145. package/dist/transport/relay-close.d.ts +0 -1
  146. package/dist/transport/relay-close.js +4 -2
  147. package/dist/transport/relay-close.js.map +1 -1
  148. package/dist/transport/relay-pipe.js +2 -2
  149. package/dist/transport/relay-pipe.js.map +1 -1
  150. package/dist/type-packs.js +4 -4
  151. package/dist/type-packs.js.map +1 -1
  152. package/dist/validation.d.ts +1 -1
  153. package/dist/validation.js +2 -2
  154. package/dist/validation.js.map +1 -1
  155. package/dist/values.d.ts +4 -20
  156. package/dist/values.js +3 -49
  157. package/dist/values.js.map +1 -1
  158. package/dist/view-sources.d.ts +2 -1
  159. package/dist/view-sources.js +1 -1
  160. package/dist/view-sources.js.map +1 -1
  161. package/dist/wire.d.ts +7 -3
  162. package/dist/wire.js +4 -4
  163. package/dist/wire.js.map +1 -1
  164. package/dist/write-ledger.d.ts +2 -1
  165. package/dist/write-ledger.js +3 -6
  166. package/dist/write-ledger.js.map +1 -1
  167. package/package.json +1 -1
@@ -63,10 +63,10 @@ function abytes(value2, length, title = "") {
63
63
  const bytes10 = isBytes(value2);
64
64
  const ofLen = length !== void 0 ? ` of length ${length}` : "";
65
65
  const got = bytes10 ? `length=${value2.length}` : `type=${typeof value2}`;
66
- const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
66
+ const message2 = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
67
67
  if (!bytes10)
68
- throw new TypeError(message);
69
- throw new RangeError(message);
68
+ throw new TypeError(message2);
69
+ throw new RangeError(message2);
70
70
  }
71
71
  function copyBytes(bytes10) {
72
72
  return Uint8Array.from(abytes(bytes10));
@@ -1717,16 +1717,16 @@ function foldFlowLines(text6, indent, mode = "flow", { indentAtStart, lineWidth
1717
1717
  onFold();
1718
1718
  let res = text6.slice(0, folds[0]);
1719
1719
  for (let i2 = 0; i2 < folds.length; ++i2) {
1720
- const fold = folds[i2];
1720
+ const fold2 = folds[i2];
1721
1721
  const end2 = folds[i2 + 1] || text6.length;
1722
- if (fold === 0)
1722
+ if (fold2 === 0)
1723
1723
  res = `
1724
1724
  ${indent}${text6.slice(0, end2)}`;
1725
1725
  else {
1726
- if (mode === FOLD_QUOTED && escapedFolds[fold])
1727
- res += `${text6[fold]}\\`;
1726
+ if (mode === FOLD_QUOTED && escapedFolds[fold2])
1727
+ res += `${text6[fold2]}\\`;
1728
1728
  res += `
1729
- ${indent}${text6.slice(fold + 1, end2)}`;
1729
+ ${indent}${text6.slice(fold2 + 1, end2)}`;
1730
1730
  }
1731
1731
  }
1732
1732
  return res;
@@ -1776,27 +1776,27 @@ function lineLengthOverLimit(str2, lineWidth, indentLength) {
1776
1776
  return true;
1777
1777
  }
1778
1778
  function doubleQuotedString(value2, ctx) {
1779
- const json2 = JSON.stringify(value2);
1779
+ const json3 = JSON.stringify(value2);
1780
1780
  if (ctx.options.doubleQuotedAsJSON)
1781
- return json2;
1781
+ return json3;
1782
1782
  const { implicitKey } = ctx;
1783
1783
  const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
1784
1784
  const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : "");
1785
1785
  let str2 = "";
1786
1786
  let start = 0;
1787
- for (let i = 0, ch = json2[i]; ch; ch = json2[++i]) {
1788
- if (ch === " " && json2[i + 1] === "\\" && json2[i + 2] === "n") {
1789
- str2 += json2.slice(start, i) + "\\ ";
1787
+ for (let i = 0, ch = json3[i]; ch; ch = json3[++i]) {
1788
+ if (ch === " " && json3[i + 1] === "\\" && json3[i + 2] === "n") {
1789
+ str2 += json3.slice(start, i) + "\\ ";
1790
1790
  i += 1;
1791
1791
  start = i;
1792
1792
  ch = "\\";
1793
1793
  }
1794
1794
  if (ch === "\\")
1795
- switch (json2[i + 1]) {
1795
+ switch (json3[i + 1]) {
1796
1796
  case "u":
1797
1797
  {
1798
- str2 += json2.slice(start, i);
1799
- const code = json2.substr(i + 2, 4);
1798
+ str2 += json3.slice(start, i);
1799
+ const code = json3.substr(i + 2, 4);
1800
1800
  switch (code) {
1801
1801
  case "0000":
1802
1802
  str2 += "\\0";
@@ -1826,23 +1826,23 @@ function doubleQuotedString(value2, ctx) {
1826
1826
  if (code.substr(0, 2) === "00")
1827
1827
  str2 += "\\x" + code.substr(2);
1828
1828
  else
1829
- str2 += json2.substr(i, 6);
1829
+ str2 += json3.substr(i, 6);
1830
1830
  }
1831
1831
  i += 5;
1832
1832
  start = i + 1;
1833
1833
  }
1834
1834
  break;
1835
1835
  case "n":
1836
- if (implicitKey || json2[i + 2] === '"' || json2.length < minMultiLineLength) {
1836
+ if (implicitKey || json3[i + 2] === '"' || json3.length < minMultiLineLength) {
1837
1837
  i += 1;
1838
1838
  } else {
1839
- str2 += json2.slice(start, i) + "\n\n";
1840
- while (json2[i + 2] === "\\" && json2[i + 3] === "n" && json2[i + 4] !== '"') {
1839
+ str2 += json3.slice(start, i) + "\n\n";
1840
+ while (json3[i + 2] === "\\" && json3[i + 3] === "n" && json3[i + 4] !== '"') {
1841
1841
  str2 += "\n";
1842
1842
  i += 2;
1843
1843
  }
1844
1844
  str2 += indent;
1845
- if (json2[i + 2] === " ")
1845
+ if (json3[i + 2] === " ")
1846
1846
  str2 += "\\";
1847
1847
  i += 1;
1848
1848
  start = i + 1;
@@ -1852,7 +1852,7 @@ function doubleQuotedString(value2, ctx) {
1852
1852
  i += 1;
1853
1853
  }
1854
1854
  }
1855
- str2 = start ? str2 + json2.slice(start) : json2;
1855
+ str2 = start ? str2 + json3.slice(start) : json3;
1856
1856
  return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false));
1857
1857
  }
1858
1858
  function singleQuotedString(value2, ctx) {
@@ -3925,11 +3925,11 @@ var Document = class _Document {
3925
3925
  throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
3926
3926
  }
3927
3927
  // json & jsonArg are only used from toJSON()
3928
- toJS({ json: json2, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
3928
+ toJS({ json: json3, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
3929
3929
  const ctx = {
3930
3930
  anchors: /* @__PURE__ */ new Map(),
3931
3931
  doc: this,
3932
- keep: !json2,
3932
+ keep: !json3,
3933
3933
  mapAsMap: mapAsMap === true,
3934
3934
  mapKeyWarned: false,
3935
3935
  maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
@@ -3968,22 +3968,22 @@ function assertCollection(contents) {
3968
3968
 
3969
3969
  // node_modules/yaml/browser/dist/errors.js
3970
3970
  var YAMLError = class extends Error {
3971
- constructor(name2, pos, code, message) {
3971
+ constructor(name2, pos, code, message2) {
3972
3972
  super();
3973
3973
  this.name = name2;
3974
3974
  this.code = code;
3975
- this.message = message;
3975
+ this.message = message2;
3976
3976
  this.pos = pos;
3977
3977
  }
3978
3978
  };
3979
3979
  var YAMLParseError = class extends YAMLError {
3980
- constructor(pos, code, message) {
3981
- super("YAMLParseError", pos, code, message);
3980
+ constructor(pos, code, message2) {
3981
+ super("YAMLParseError", pos, code, message2);
3982
3982
  }
3983
3983
  };
3984
3984
  var YAMLWarning = class extends YAMLError {
3985
- constructor(pos, code, message) {
3986
- super("YAMLWarning", pos, code, message);
3985
+ constructor(pos, code, message2) {
3986
+ super("YAMLWarning", pos, code, message2);
3987
3987
  }
3988
3988
  };
3989
3989
  var prettifyError = (src, lc) => (error4) => {
@@ -4580,8 +4580,8 @@ function composeCollection(CN2, ctx, token, props, onError) {
4580
4580
  const { anchor, newlineAfterProp: nl } = props;
4581
4581
  const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken;
4582
4582
  if (lastProp && (!nl || nl.offset < lastProp.offset)) {
4583
- const message = "Missing newline after block sequence props";
4584
- onError(lastProp, "MISSING_CHAR", message);
4583
+ const message2 = "Missing newline after block sequence props";
4584
+ onError(lastProp, "MISSING_CHAR", message2);
4585
4585
  }
4586
4586
  }
4587
4587
  const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq";
@@ -4646,15 +4646,15 @@ function resolveBlockScalar(ctx, scalar, onError) {
4646
4646
  trimIndent = indent.length;
4647
4647
  } else {
4648
4648
  if (indent.length < trimIndent) {
4649
- const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator";
4650
- onError(offset + indent.length, "MISSING_CHAR", message);
4649
+ const message2 = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator";
4650
+ onError(offset + indent.length, "MISSING_CHAR", message2);
4651
4651
  }
4652
4652
  if (header.indent === 0)
4653
4653
  trimIndent = indent.length;
4654
4654
  contentStart = i;
4655
4655
  if (trimIndent === 0 && !ctx.atRoot) {
4656
- const message = "Block scalar values in collections must be indented";
4657
- onError(offset, "BAD_INDENT", message);
4656
+ const message2 = "Block scalar values in collections must be indented";
4657
+ onError(offset, "BAD_INDENT", message2);
4658
4658
  }
4659
4659
  break;
4660
4660
  }
@@ -4677,8 +4677,8 @@ function resolveBlockScalar(ctx, scalar, onError) {
4677
4677
  content = content.slice(0, -1);
4678
4678
  if (content && indent.length < trimIndent) {
4679
4679
  const src = header.indent ? "explicit indentation indicator" : "first line";
4680
- const message = `Block scalar lines must not be less indented than their ${src}`;
4681
- onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message);
4680
+ const message2 = `Block scalar lines must not be less indented than their ${src}`;
4681
+ onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message2);
4682
4682
  indent = "";
4683
4683
  }
4684
4684
  if (type === Scalar.BLOCK_LITERAL) {
@@ -4756,8 +4756,8 @@ function parseBlockScalarHeader({ offset, props }, strict, onError) {
4756
4756
  break;
4757
4757
  case "comment":
4758
4758
  if (strict && !hasSpace) {
4759
- const message = "Comments must be separated from other tokens by white space characters";
4760
- onError(token, "MISSING_CHAR", message);
4759
+ const message2 = "Comments must be separated from other tokens by white space characters";
4760
+ onError(token, "MISSING_CHAR", message2);
4761
4761
  }
4762
4762
  length += token.source.length;
4763
4763
  comment = token.source.substring(1);
@@ -4768,8 +4768,8 @@ function parseBlockScalarHeader({ offset, props }, strict, onError) {
4768
4768
  break;
4769
4769
  /* istanbul ignore next should not happen */
4770
4770
  default: {
4771
- const message = `Unexpected token in block scalar header: ${token.type}`;
4772
- onError(token, "UNEXPECTED_TOKEN", message);
4771
+ const message2 = `Unexpected token in block scalar header: ${token.type}`;
4772
+ onError(token, "UNEXPECTED_TOKEN", message2);
4773
4773
  const ts = token.source;
4774
4774
  if (ts && typeof ts === "string")
4775
4775
  length += ts.length;
@@ -4901,8 +4901,8 @@ function doubleQuotedValue(source, onError) {
4901
4901
  if (ch === "\r" && source[i + 1] === "\n")
4902
4902
  continue;
4903
4903
  if (ch === "\n") {
4904
- const { fold, offset } = foldNewline(source, i);
4905
- res += fold;
4904
+ const { fold: fold2, offset } = foldNewline(source, i);
4905
+ res += fold2;
4906
4906
  i = offset;
4907
4907
  } else if (ch === "\\") {
4908
4908
  let next = source[++i];
@@ -4942,19 +4942,19 @@ function doubleQuotedValue(source, onError) {
4942
4942
  return res;
4943
4943
  }
4944
4944
  function foldNewline(source, offset) {
4945
- let fold = "";
4945
+ let fold2 = "";
4946
4946
  let ch = source[offset + 1];
4947
4947
  while (ch === " " || ch === " " || ch === "\n" || ch === "\r") {
4948
4948
  if (ch === "\r" && source[offset + 2] !== "\n")
4949
4949
  break;
4950
4950
  if (ch === "\n")
4951
- fold += "\n";
4951
+ fold2 += "\n";
4952
4952
  offset += 1;
4953
4953
  ch = source[offset + 1];
4954
4954
  }
4955
- if (!fold)
4956
- fold = " ";
4957
- return { fold, offset };
4955
+ if (!fold2)
4956
+ fold2 = " ";
4957
+ return { fold: fold2, offset };
4958
4958
  }
4959
4959
  var escapeCodes = {
4960
4960
  "0": "\0",
@@ -5126,13 +5126,13 @@ function composeNode(ctx, token, props, onError) {
5126
5126
  if (anchor)
5127
5127
  node.anchor = anchor.source.substring(1);
5128
5128
  } catch (error4) {
5129
- const message = error4 instanceof Error ? error4.message : String(error4);
5130
- onError(token, "RESOURCE_EXHAUSTION", message);
5129
+ const message2 = error4 instanceof Error ? error4.message : String(error4);
5130
+ onError(token, "RESOURCE_EXHAUSTION", message2);
5131
5131
  }
5132
5132
  break;
5133
5133
  default: {
5134
- const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`;
5135
- onError(token, "UNEXPECTED_TOKEN", message);
5134
+ const message2 = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`;
5135
+ onError(token, "UNEXPECTED_TOKEN", message2);
5136
5136
  isSrcToken = false;
5137
5137
  }
5138
5138
  }
@@ -5264,12 +5264,12 @@ var Composer = class {
5264
5264
  this.prelude = [];
5265
5265
  this.errors = [];
5266
5266
  this.warnings = [];
5267
- this.onError = (source, code, message, warning2) => {
5267
+ this.onError = (source, code, message2, warning2) => {
5268
5268
  const pos = getErrorPos(source);
5269
5269
  if (warning2)
5270
- this.warnings.push(new YAMLWarning(pos, code, message));
5270
+ this.warnings.push(new YAMLWarning(pos, code, message2));
5271
5271
  else
5272
- this.errors.push(new YAMLParseError(pos, code, message));
5272
+ this.errors.push(new YAMLParseError(pos, code, message2));
5273
5273
  };
5274
5274
  this.directives = new Directives({ version: options.version || "1.2" });
5275
5275
  this.options = options;
@@ -5337,10 +5337,10 @@ ${cb}` : comment;
5337
5337
  *next(token) {
5338
5338
  switch (token.type) {
5339
5339
  case "directive":
5340
- this.directives.add(token.source, (offset, message, warning2) => {
5340
+ this.directives.add(token.source, (offset, message2, warning2) => {
5341
5341
  const pos = getErrorPos(token);
5342
5342
  pos[0] += offset;
5343
- this.onError(pos, "BAD_DIRECTIVE", message, warning2);
5343
+ this.onError(pos, "BAD_DIRECTIVE", message2, warning2);
5344
5344
  });
5345
5345
  this.prelude.push(token.source);
5346
5346
  this.atDirectives = true;
@@ -6145,15 +6145,15 @@ var LineCounter = class {
6145
6145
  };
6146
6146
 
6147
6147
  // node_modules/yaml/browser/dist/parse/parser.js
6148
- function includesToken(list3, type) {
6149
- for (let i = 0; i < list3.length; ++i)
6150
- if (list3[i].type === type)
6148
+ function includesToken(list4, type) {
6149
+ for (let i = 0; i < list4.length; ++i)
6150
+ if (list4[i].type === type)
6151
6151
  return true;
6152
6152
  return false;
6153
6153
  }
6154
- function findNonEmptyIndex(list3) {
6155
- for (let i = 0; i < list3.length; ++i) {
6156
- switch (list3[i].type) {
6154
+ function findNonEmptyIndex(list4) {
6155
+ for (let i = 0; i < list4.length; ++i) {
6156
+ switch (list4[i].type) {
6157
6157
  case "space":
6158
6158
  case "comment":
6159
6159
  case "newline":
@@ -6281,8 +6281,8 @@ var Parser = class {
6281
6281
  }
6282
6282
  const type = tokenType(source);
6283
6283
  if (!type) {
6284
- const message = `Not a YAML token: ${source}`;
6285
- yield* this.pop({ type: "error", offset: this.offset, message, source });
6284
+ const message2 = `Not a YAML token: ${source}`;
6285
+ yield* this.pop({ type: "error", offset: this.offset, message: message2, source });
6286
6286
  this.offset += source.length;
6287
6287
  } else if (type === "scalar") {
6288
6288
  this.atNewLine = false;
@@ -6372,8 +6372,8 @@ var Parser = class {
6372
6372
  *pop(error4) {
6373
6373
  const token = error4 ?? this.stack.pop();
6374
6374
  if (!token) {
6375
- const message = "Tried to pop an empty stack";
6376
- yield { type: "error", offset: this.offset, source: "", message };
6375
+ const message2 = "Tried to pop an empty stack";
6376
+ yield { type: "error", offset: this.offset, source: "", message: message2 };
6377
6377
  } else if (this.stack.length === 0) {
6378
6378
  yield token;
6379
6379
  } else {
@@ -14609,22 +14609,22 @@ var MdbaseConnectError = class extends Error {
14609
14609
  return this.problem.details;
14610
14610
  }
14611
14611
  };
14612
- function connectProblem(code, message, ...[options = {}]) {
14612
+ function connectProblem(code, message2, ...[options = {}]) {
14613
14613
  const definition = CONNECT_PROBLEM_CATALOG[code];
14614
14614
  return {
14615
14615
  problem_version: CONNECT_PROBLEM_VERSION,
14616
14616
  code,
14617
14617
  category: definition.category,
14618
14618
  recovery: definition.recovery,
14619
- message,
14619
+ message: message2,
14620
14620
  ...options.details === void 0 ? {} : { details: options.details },
14621
14621
  ...options.operationOutcome === void 0 ? {} : { operation_outcome: options.operationOutcome },
14622
14622
  ...options.traceId === void 0 ? {} : { trace_id: options.traceId }
14623
14623
  };
14624
14624
  }
14625
- function connectError(code, message, ...args) {
14625
+ function connectError(code, message2, ...args) {
14626
14626
  const options = args[0];
14627
- return new MdbaseConnectError(connectProblem(code, message, ...args), {
14627
+ return new MdbaseConnectError(connectProblem(code, message2, ...args), {
14628
14628
  status: options?.status,
14629
14629
  cause: options?.cause
14630
14630
  });
@@ -14656,9 +14656,9 @@ function semanticContractVersion(requirements) {
14656
14656
  invalidAuthorizationSelection("Unsupported declared capability contract version.");
14657
14657
  return version3;
14658
14658
  }
14659
- function invalidAuthorizationSelection(message) {
14660
- throw connectError("invalid_application_manifest", message, {
14661
- details: { issues: [{ path: "/requirements/capabilities", keyword: "authorizationSelection", message, params: {} }] }
14659
+ function invalidAuthorizationSelection(message2) {
14660
+ throw connectError("invalid_application_manifest", message2, {
14661
+ details: { issues: [{ path: "/requirements/capabilities", keyword: "authorizationSelection", message: message2, params: {} }] }
14662
14662
  });
14663
14663
  }
14664
14664
  function validateAuthorizationSelection(requirements, options) {
@@ -15407,8 +15407,8 @@ function isLoopback(hostname) {
15407
15407
  function invalid(issues) {
15408
15408
  return { valid: false, issues };
15409
15409
  }
15410
- function issue(path, keyword, message, params2 = {}) {
15411
- return { path, keyword, message, params: params2 };
15410
+ function issue(path, keyword, message2, params2 = {}) {
15411
+ return { path, keyword, message: message2, params: params2 };
15412
15412
  }
15413
15413
  function asObject(value2) {
15414
15414
  return value2 !== null && typeof value2 === "object" && !Array.isArray(value2) ? value2 : {};
@@ -15528,6 +15528,7 @@ var MdbaseError = class extends Error {
15528
15528
  code;
15529
15529
  recovery;
15530
15530
  reason;
15531
+ /** Plain JSON, whatever the problem carries. Read one field with a narrowing check. */
15531
15532
  details;
15532
15533
  retryAfterMs;
15533
15534
  issues;
@@ -15539,8 +15540,6 @@ var MdbaseError = class extends Error {
15539
15540
  * dry runs, which capture nothing. Not part of {@link toProblem}.
15540
15541
  */
15541
15542
  mutationId;
15542
- /** Every original mutation of a failed partial batch, in op order. */
15543
- mutationIds;
15544
15543
  constructor(problem4, context = {}) {
15545
15544
  super(problem4.message, context.cause === void 0 ? void 0 : { cause: context.cause });
15546
15545
  this.name = "MdbaseError";
@@ -15551,10 +15550,7 @@ var MdbaseError = class extends Error {
15551
15550
  if (problem4.retryAfterMs !== void 0) this.retryAfterMs = problem4.retryAfterMs;
15552
15551
  if (problem4.issues !== void 0) this.issues = problem4.issues;
15553
15552
  if (problem4.traceId !== void 0) this.traceId = problem4.traceId;
15554
- const ids = context.mutationIds ? Object.freeze([...context.mutationIds]) : void 0;
15555
- const id4 = context.mutationId ?? ids?.[0];
15556
- if (id4 !== void 0) this.mutationId = id4;
15557
- if (ids !== void 0) this.mutationIds = ids;
15553
+ if (context.mutationId !== void 0) this.mutationId = context.mutationId;
15558
15554
  }
15559
15555
  toProblem() {
15560
15556
  const p = { code: this.code, recovery: this.recovery, message: this.message };
@@ -15566,9 +15562,9 @@ var MdbaseError = class extends Error {
15566
15562
  return p;
15567
15563
  }
15568
15564
  };
15569
- function mdbaseError(code, message, extra = {}) {
15565
+ function mdbaseError(code, message2, extra = {}) {
15570
15566
  const more = typeof extra === "string" ? { reason: extra } : extra;
15571
- return new MdbaseError({ code, recovery: ERROR_CODES[code], message, ...more });
15567
+ return new MdbaseError({ code, recovery: ERROR_CODES[code], message: message2, ...more });
15572
15568
  }
15573
15569
  function isMdbaseError(e, code) {
15574
15570
  return e instanceof MdbaseError && (code === void 0 || e.code === code);
@@ -15691,12 +15687,12 @@ function appReleaseTrust() {
15691
15687
  // src/application/asset-pins.json
15692
15688
  var asset_pins_default = {
15693
15689
  runtime: {
15694
- sha256: "6fca774a331cb457912e2e3ec53452cb5a4edda9d54213a33e7b58fa73226f1a",
15695
- bytes: 3872491,
15696
- maxBytes: 3872491,
15690
+ sha256: "7004351583c3a79411e644fafe9f5786816d32ea058605d1905fd50666012f40",
15691
+ bytes: 3875815,
15692
+ maxBytes: 3875815,
15697
15693
  source: {
15698
15694
  repository: "mdbase-dev/mdbase-connect",
15699
- commit: "efa183f510ca188b855b65351b74d91641c415ef"
15695
+ commit: "aae332572834fbfa065c0f696017c0de3540649d"
15700
15696
  }
15701
15697
  },
15702
15698
  sqlite: {
@@ -15718,16 +15714,16 @@ var asset_pins_default = {
15718
15714
  var runtime = Object.freeze({ sha256: asset_pins_default.runtime.sha256, bytes: asset_pins_default.runtime.bytes, maxBytes: asset_pins_default.runtime.maxBytes });
15719
15715
  var sqlite = Object.freeze({ sha256: asset_pins_default.sqlite.sha256, bytes: asset_pins_default.sqlite.bytes, maxBytes: asset_pins_default.sqlite.maxBytes });
15720
15716
  var unavailable = () => mdbaseError("unavailable", "SDK packaged application assets unavailable", "application_packaged_assets_unavailable");
15721
- function packagedApplicationAssets(environment, appOrigin) {
15717
+ function packagedApplicationAssets(environment, appOrigin, anchor) {
15722
15718
  if (!applicationEnvironmentAllowed(environment)) throw unavailable();
15723
15719
  const release = appReleaseTrust();
15724
15720
  selectAppEnvironment({ environment, appOrigin, release });
15725
15721
  let runtimeUrl, sqliteUrl;
15726
15722
  try {
15727
- const module = new URL(import.meta.url);
15723
+ const module = new URL(anchor ?? import.meta.url);
15728
15724
  if (urlOrigin(module) !== appOrigin || module.username || module.password) throw unavailable();
15729
- runtimeUrl = new URL("../native/runtime.wasm", import.meta.url);
15730
- sqliteUrl = new URL("../native/sqlite3.wasm", import.meta.url);
15725
+ runtimeUrl = anchor === void 0 ? new URL("../native/runtime.wasm", import.meta.url) : new URL("../native/runtime.wasm", module);
15726
+ sqliteUrl = anchor === void 0 ? new URL("../native/sqlite3.wasm", import.meta.url) : new URL("../native/sqlite3.wasm", module);
15731
15727
  if (urlOrigin(runtimeUrl) !== appOrigin || urlOrigin(sqliteUrl) !== appOrigin) throw unavailable();
15732
15728
  } catch {
15733
15729
  throw unavailable();
@@ -15736,7 +15732,7 @@ function packagedApplicationAssets(environment, appOrigin) {
15736
15732
  const initializeSqlite = async (options) => {
15737
15733
  const WorkerScope2 = globalThis.WorkerGlobalScope;
15738
15734
  if (typeof WorkerScope2 !== "function" || !(globalThis instanceof WorkerScope2)) throw unavailable();
15739
- const initializer = new URL("../native/sqlite3.js", import.meta.url);
15735
+ const initializer = anchor === void 0 ? new URL("../native/sqlite3.js", import.meta.url) : new URL("../native/sqlite3.js", anchor);
15740
15736
  const { default: initialize2 } = await import(
15741
15737
  /* @vite-ignore */
15742
15738
  /* webpackIgnore: true */
@@ -15862,8 +15858,8 @@ var Float64 = class {
15862
15858
  };
15863
15859
  var MAX_DEPTH = 128;
15864
15860
  var CborError = class extends Error {
15865
- constructor(kind, message) {
15866
- super(message ?? kind);
15861
+ constructor(kind, message2) {
15862
+ super(message2 ?? kind);
15867
15863
  this.kind = kind;
15868
15864
  this.name = "CborError";
15869
15865
  }
@@ -16229,17 +16225,64 @@ function bytesEqual(a, b) {
16229
16225
  return true;
16230
16226
  }
16231
16227
 
16228
+ // src/plain.ts
16229
+ function toPlain(v) {
16230
+ if (v === null || typeof v === "boolean" || typeof v === "number" || typeof v === "string") return v;
16231
+ if (typeof v === "bigint") return v.toString();
16232
+ if (v instanceof Float64) return v.value;
16233
+ if (v instanceof Uint8Array) return toHex(v);
16234
+ if (Array.isArray(v)) return v.map(toPlain);
16235
+ return Object.fromEntries([...v].map(([k, x]) => [String(k), toPlain(x)]));
16236
+ }
16237
+ function fieldOf(value2, key3) {
16238
+ return typeof value2 === "object" && value2 !== null && !Array.isArray(value2) && Object.hasOwn(value2, key3) ? value2[key3] : void 0;
16239
+ }
16240
+ function toValue(v) {
16241
+ if (v === void 0 || v === null) return null;
16242
+ if (typeof v !== "object") return v;
16243
+ if (v instanceof Float64) return v;
16244
+ if (Array.isArray(v)) return v.map(toValue);
16245
+ if (v instanceof Map) {
16246
+ const m3 = /* @__PURE__ */ new Map();
16247
+ for (const [k, x] of v) m3.set(k, toValue(x));
16248
+ return m3;
16249
+ }
16250
+ if (v instanceof Date) return v.toISOString();
16251
+ const m2 = /* @__PURE__ */ new Map();
16252
+ for (const [k, x] of Object.entries(v)) if (x !== void 0) m2.set(k, toValue(x));
16253
+ return m2;
16254
+ }
16255
+
16232
16256
  // src/codec.ts
16233
16257
  var SchemaError = class extends Error {
16234
- constructor(ty, message, unknown = false) {
16235
- super(`${ty}: ${message}`);
16258
+ constructor(ty, message2, unknown2 = false) {
16259
+ super(`${ty}: ${message2}`);
16236
16260
  this.ty = ty;
16237
- this.unknown = unknown;
16261
+ this.unknown = unknown2;
16238
16262
  this.name = "SchemaError";
16239
16263
  }
16240
16264
  ty;
16241
16265
  unknown;
16242
16266
  };
16267
+ var plainMode = false;
16268
+ function decodePlain(codec, c) {
16269
+ const was = plainMode;
16270
+ plainMode = true;
16271
+ try {
16272
+ return codec.dec(c);
16273
+ } finally {
16274
+ plainMode = was;
16275
+ }
16276
+ }
16277
+ function plainAnswer(codec) {
16278
+ return {
16279
+ name: codec.name,
16280
+ enc: () => {
16281
+ throw new SchemaError(codec.name, "an answer is decoded, never encoded");
16282
+ },
16283
+ dec: (c) => decodePlain(codec, c)
16284
+ };
16285
+ }
16243
16286
  function kindOf(c) {
16244
16287
  if (c === null) return "null";
16245
16288
  if (c instanceof Uint8Array) return "bytes";
@@ -16354,7 +16397,15 @@ var value = {
16354
16397
  },
16355
16398
  dec: (c) => {
16356
16399
  checkValue(c);
16357
- return c;
16400
+ return plainMode ? toPlain(c) : c;
16401
+ }
16402
+ };
16403
+ var json2 = {
16404
+ name: "value",
16405
+ enc: (v) => value.enc(toValue(v)),
16406
+ dec: (c) => {
16407
+ checkValue(c);
16408
+ return toPlain(c);
16358
16409
  }
16359
16410
  };
16360
16411
  function checkValue(c, depth = 0) {
@@ -16404,7 +16455,7 @@ function dataMap(item) {
16404
16455
  if (typeof k !== "string") throw new SchemaError(name2, "data map keys must be text");
16405
16456
  m2.set(k, item.dec(x));
16406
16457
  }
16407
- return m2;
16458
+ return plainMode ? Object.fromEntries(m2) : m2;
16408
16459
  }
16409
16460
  };
16410
16461
  }
@@ -16652,15 +16703,15 @@ function acquireNamedLease(locks, name2, signal) {
16652
16703
  acquiredResolve = resolve;
16653
16704
  acquiredReject = reject;
16654
16705
  });
16655
- let cancelled2 = false;
16706
+ let cancelled3 = false;
16656
16707
  const onAbort = () => {
16657
- cancelled2 = true;
16708
+ cancelled3 = true;
16658
16709
  acquiredReject(new AppReplicaOwnerError("aborted"));
16659
16710
  };
16660
16711
  signal?.addEventListener("abort", onAbort, { once: true });
16661
16712
  const request3 = Promise.resolve().then(() => locks.request(name2, { mode: "exclusive", ifAvailable: true }, async (lock) => {
16662
16713
  signal?.removeEventListener("abort", onAbort);
16663
- if (cancelled2 || signal?.aborted) {
16714
+ if (cancelled3 || signal?.aborted) {
16664
16715
  acquiredReject(new AppReplicaOwnerError("aborted"));
16665
16716
  return;
16666
16717
  }
@@ -17076,8 +17127,8 @@ var nonOkResponses = /* @__PURE__ */ new WeakSet();
17076
17127
  var privateDeviceFieldRefused = /* @__PURE__ */ new WeakSet();
17077
17128
  function unknownPrivateDeviceField(status, error4) {
17078
17129
  if (status !== 400 || !error4 || typeof error4 !== "object" || Array.isArray(error4)) return false;
17079
- const { code, message } = error4;
17080
- return code === "invalid_request" && typeof message === "string" && message.length <= 512 && /unrecognized key/i.test(message) && message.includes("requested_private_device");
17130
+ const { code, message: message2 } = error4;
17131
+ return code === "invalid_request" && typeof message2 === "string" && message2.length <= 512 && /unrecognized key/i.test(message2) && message2.includes("requested_private_device");
17081
17132
  }
17082
17133
  var hex = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
17083
17134
  var UUID3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
@@ -17243,7 +17294,7 @@ var AppProtectedInstallationSignIn = class _AppProtectedInstallationSignIn {
17243
17294
  const base = "version,requestId,installationId,deviceId,secret,appId,kind,origin,cpOrigin,environment,selection,confirmed,nativeStarted,proof,token";
17244
17295
  const legacy = parsed?.version === 1;
17245
17296
  const fields3 = `${base},requestedCreateCollections,collectionIds,createCollections,consentRequest`;
17246
- const r = legacy ? { ...object2(parsed, base), version: 3, renewal: null, requestedCreateCollections: false, collectionIds: [], createCollections: false, consentRequest: null } : parsed?.version === 2 ? { ...object2(parsed, fields3), version: 3, renewal: null } : object2(parsed, `${fields3},renewal${Object.hasOwn(parsed, "collectionSelection") ? ",collectionSelection" : ""}${Object.hasOwn(parsed, "timerConsent") ? ",timerConsent" : ""}${Object.hasOwn(parsed, "timerChannel") ? ",timerChannel" : ""}${Object.hasOwn(parsed, "owner") ? ",owner" : ""}${Object.hasOwn(parsed, "collectionListing") ? ",collectionListing" : ""}${Object.hasOwn(parsed, "collectionRecoveries") ? ",collectionRecoveries" : ""}${Object.hasOwn(parsed, "recoveryFor") ? ",recoveryFor" : ""}${Object.hasOwn(parsed, "nativeAuthorization") ? ",nativeAuthorization" : ""}${Object.hasOwn(parsed, "nativeSelection") ? ",nativeSelection" : ""}${Object.hasOwn(parsed, "nativeGrants") ? ",nativeGrants" : ""}${Object.hasOwn(parsed, "requestedPrivateDevice") ? ",requestedPrivateDevice" : ""}${Object.hasOwn(parsed, "privateDeviceCollectionIds") ? ",privateDeviceCollectionIds" : ""}`);
17297
+ const r = legacy ? { ...object2(parsed, base), version: 3, renewal: null, requestedCreateCollections: false, collectionIds: [], createCollections: false, consentRequest: null } : parsed?.version === 2 ? { ...object2(parsed, fields3), version: 3, renewal: null } : object2(parsed, `${fields3},renewal${Object.hasOwn(parsed, "collectionSelection") ? ",collectionSelection" : ""}${Object.hasOwn(parsed, "timerConsent") ? ",timerConsent" : ""}${Object.hasOwn(parsed, "timerChannel") ? ",timerChannel" : ""}${Object.hasOwn(parsed, "owner") ? ",owner" : ""}${Object.hasOwn(parsed, "collectionListing") ? ",collectionListing" : ""}${Object.hasOwn(parsed, "collectionRecoveries") ? ",collectionRecoveries" : ""}${Object.hasOwn(parsed, "recoveryFor") ? ",recoveryFor" : ""}${Object.hasOwn(parsed, "nativeAuthorization") ? ",nativeAuthorization" : ""}${Object.hasOwn(parsed, "nativeSelection") ? ",nativeSelection" : ""}${Object.hasOwn(parsed, "nativeGrants") ? ",nativeGrants" : ""}${Object.hasOwn(parsed, "requestedPrivateDevice") ? ",requestedPrivateDevice" : ""}${Object.hasOwn(parsed, "privateDeviceCollectionIds") ? ",privateDeviceCollectionIds" : ""}${Object.hasOwn(parsed, "requestSent") ? ",requestSent" : ""}`);
17247
17298
  if (r.version !== 3 || r.appId !== p.appId || r.owner !== p.owner || r.kind !== (p.installationKind ?? "app-runtime") || r.origin !== p.origin || r.cpOrigin !== p.cpOrigin || r.environment !== p.environment || typeof r.confirmed !== "boolean" || typeof r.nativeStarted !== "boolean") throw fail3("recovery_required");
17248
17299
  const s = r;
17249
17300
  if (typeof s.requestedCreateCollections !== "boolean" || typeof s.createCollections !== "boolean" || p.requestedCreateCollections !== void 0 && p.requestedCreateCollections !== s.requestedCreateCollections) throw fail3("binding");
@@ -17287,6 +17338,7 @@ var AppProtectedInstallationSignIn = class _AppProtectedInstallationSignIn {
17287
17338
  text(r2.secret, /^pair_[A-Za-z0-9_-]{43}$/);
17288
17339
  if (r2.requestId === s.requestId || r2.secret === s.secret) throw fail3("recovery_required");
17289
17340
  }
17341
+ if (s.requestSent !== void 0 && s.requestSent !== s.requestId) throw fail3("recovery_required");
17290
17342
  if (s.timerChannel !== void 0) {
17291
17343
  if (!s.token || !s.selection) throw fail3("recovery_required");
17292
17344
  try {
@@ -17488,7 +17540,8 @@ var AppProtectedInstallationSignIn = class _AppProtectedInstallationSignIn {
17488
17540
  try {
17489
17541
  const requestId = crypto.randomUUID(), secret = `pair_${btoa(String.fromCharCode(...bytes10)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`;
17490
17542
  if (requestId === s.requestId || requestId === s.renewal?.requestId || secret === s.secret) throw fail3("binding");
17491
- await this.save({ ...s, requestId, secret, renewal: { requestId: s.requestId, secret: s.secret } });
17543
+ const { requestSent: _sent, ...unsent } = s;
17544
+ await this.save({ ...unsent, requestId, secret, renewal: { requestId: s.requestId, secret: s.secret } });
17492
17545
  this.expiredRequestId = null;
17493
17546
  return await this.startRequest();
17494
17547
  } finally {
@@ -17516,6 +17569,7 @@ var AppProtectedInstallationSignIn = class _AppProtectedInstallationSignIn {
17516
17569
  const uri = verificationUri(v.verification_uri, `${s.cpOrigin}/pair/${s.requestId}`, hint);
17517
17570
  if (v.pairing_id !== s.requestId || v.pairing_secret !== s.secret || uri === null || v.installation_device !== true || v.app_id !== s.appId || v.app_origin !== s.origin || v.app_name !== this.options.appName || !Number.isSafeInteger(v.expires_in) || v.expires_in < 0 || v.expires_in > 600) throw fail3("response");
17518
17571
  this.expiredRequestId = null;
17572
+ if (this.state.requestSent !== s.requestId) await this.save({ ...this.state, requestSent: s.requestId });
17519
17573
  return Object.freeze({ ...this.view(), verificationUri: uri });
17520
17574
  }
17521
17575
  /** Scoped replies must echo the immutable protected CID. Legacy normal
@@ -18017,6 +18071,12 @@ var AppProtectedInstallationSignIn = class _AppProtectedInstallationSignIn {
18017
18071
  }
18018
18072
  });
18019
18073
  }
18074
+ /** A sign-in gesture sent this pending request and Connect accepted it: a
18075
+ * restarted session may keep reading it. False once signed in. */
18076
+ requestSent() {
18077
+ this.check();
18078
+ return !this.state.token && this.state.requestSent === this.state.requestId;
18079
+ }
18020
18080
  /** True when this installation registered a Web Push channel (so a browser
18021
18081
  * push subscription exists for the app). Metadata only. */
18022
18082
  hasWebPushChannel() {
@@ -19767,34 +19827,9 @@ function waitForOpenRetry(milliseconds, signal) {
19767
19827
  }
19768
19828
 
19769
19829
  // src/values.ts
19770
- function toValue(v) {
19771
- if (v === void 0 || v === null) return null;
19772
- if (typeof v !== "object") return v;
19773
- if (v instanceof Float64) return v;
19774
- if (Array.isArray(v)) return v.map(toValue);
19775
- if (v instanceof Map) {
19776
- const m3 = /* @__PURE__ */ new Map();
19777
- for (const [k, x] of v) m3.set(k, toValue(x));
19778
- return m3;
19779
- }
19780
- if (v instanceof Date) return v.toISOString();
19781
- const m2 = /* @__PURE__ */ new Map();
19782
- for (const [k, x] of Object.entries(v)) if (x !== void 0) m2.set(k, toValue(x));
19783
- return m2;
19784
- }
19785
19830
  function toFmMap(v) {
19786
19831
  return toValue(v);
19787
19832
  }
19788
- function toPlain(v) {
19789
- if (v === null || typeof v === "boolean" || typeof v === "number" || typeof v === "string") return v;
19790
- if (typeof v === "bigint") return v.toString();
19791
- if (v instanceof Float64) return v.value;
19792
- if (v instanceof Uint8Array) return toHex(v);
19793
- if (Array.isArray(v)) return v.map(toPlain);
19794
- const o = {};
19795
- for (const [k, x] of v) o[String(k)] = toPlain(x);
19796
- return o;
19797
- }
19798
19833
  function valueEquals(a, b) {
19799
19834
  if (a === b) return true;
19800
19835
  if (a instanceof Float64 && b instanceof Float64) return Object.is(a.value, b.value) || a.value === b.value;
@@ -19975,14 +20010,14 @@ var issue2 = struct("issue", [
19975
20010
  [0, "code", tstr],
19976
20011
  [1, "severity", severity],
19977
20012
  [2, "message", tstr],
19978
- [3, "details", value, "opt"]
20013
+ [3, "details", json2, "opt"]
19979
20014
  ]);
19980
20015
  var problem = struct("problem", [
19981
20016
  [0, "code", tstr],
19982
20017
  [1, "recovery", recovery],
19983
20018
  [2, "message", tstr],
19984
20019
  [3, "reason", tstr, "opt"],
19985
- [4, "details", value, "opt"],
20020
+ [4, "details", json2, "opt"],
19986
20021
  [5, "retryAfterMs", uint, "opt"],
19987
20022
  [6, "issues", list(issue2), "opt"],
19988
20023
  [7, "traceId", tstr, "opt"]
@@ -20048,7 +20083,7 @@ var INCIDENT_KINDS = [
20048
20083
  ];
20049
20084
  var incident = struct("incident", [
20050
20085
  [0, "kind", enumOf("incident-kind", INCIDENT_KINDS)],
20051
- [1, "details", value, "opt"]
20086
+ [1, "details", json2, "opt"]
20052
20087
  ]);
20053
20088
  var progress = struct("progress", [
20054
20089
  [0, "done", uint],
@@ -20892,7 +20927,7 @@ var TEXT_MAX = 4096;
20892
20927
  var ITEMS_MAX = 4096;
20893
20928
  var ROWS_MAX = 65536;
20894
20929
  var utf82 = new TextEncoder();
20895
- var bad2 = (message, unknown = false) => new SchemaError("app-bases-v1", message, unknown);
20930
+ var bad2 = (message2, unknown2 = false) => new SchemaError("app-bases-v1", message2, unknown2);
20896
20931
  function text2(c, max = TEXT_MAX) {
20897
20932
  if (typeof c !== "string" || utf82.encode(c).length > max) throw bad2("bounded text required");
20898
20933
  return c;
@@ -21248,7 +21283,7 @@ var validationIssue2 = struct("validation-issue", [
21248
21283
  [0, "code", tstr],
21249
21284
  [1, "severity", severity],
21250
21285
  [2, "message", tstr],
21251
- [3, "details", value, "opt"],
21286
+ [3, "details", json2, "opt"],
21252
21287
  [4, "location", tstr, "opt"],
21253
21288
  [5, "typeName", tstr, "opt"],
21254
21289
  [6, "tier", tier]
@@ -21260,7 +21295,7 @@ var row = struct("record-validation", [
21260
21295
  [3, "revision", hash]
21261
21296
  ]);
21262
21297
  var rows = list(row);
21263
- var invalid3 = (message) => new SchemaError("record-validations", message);
21298
+ var invalid3 = (message2) => new SchemaError("record-validations", message2);
21264
21299
  var recordValidations = {
21265
21300
  name: "record-validations",
21266
21301
  enc: (v) => rows.enc(v),
@@ -21796,12 +21831,12 @@ var FilesApi = class {
21796
21831
  if (version3.major !== 1 || version3.minor < 2) {
21797
21832
  throw mdbaseError("upgrade_required", "this replica's change feed does not name files", "change_entity_unsupported");
21798
21833
  }
21799
- return this.client.watchChanges(options.cursor, (batch) => {
21834
+ return this.client.watchChanges((batch) => {
21800
21835
  const changes = batch.changes.filter((c) => c.entity === "file" || c.entity === void 0 && c.kind === "remove");
21801
21836
  const unclassified = batch.changes.some((c) => c.entity === void 0 && c.kind === "put");
21802
21837
  if (unclassified) onChanges({ changes: [], cursor: batch.cursor, reset: true });
21803
21838
  else if (changes.length || batch.reset) onChanges({ changes, cursor: batch.cursor, reset: batch.reset });
21804
- });
21839
+ }, options);
21805
21840
  }
21806
21841
  wire(s) {
21807
21842
  if (this.wired.has(s)) return;
@@ -21848,7 +21883,7 @@ var FilesApi = class {
21848
21883
  });
21849
21884
  }
21850
21885
  async session(signal, read = false) {
21851
- const s = await (read ? this.client.readyForRead(signal) : this.client.ready(signal));
21886
+ const s = await (read ? this.client.readyForRead(signal) : this.client.ready({ signal }));
21852
21887
  this.wire(s);
21853
21888
  return s;
21854
21889
  }
@@ -21879,11 +21914,12 @@ var FilesApi = class {
21879
21914
  cursor = page.cursor;
21880
21915
  }
21881
21916
  }
21882
- get(f, signal) {
21917
+ /** One file's handle by ID or path. `o.signal` cancels the read. */
21918
+ get(f, o = {}) {
21883
21919
  return this.client.call("get_file", m([[0, fileRef(f)]]), {
21884
21920
  codec: fileView,
21885
21921
  retry: true,
21886
- ...signal ? { signal } : {}
21922
+ ...o.signal ? { signal: o.signal } : {}
21887
21923
  });
21888
21924
  }
21889
21925
  /**
@@ -21964,7 +22000,7 @@ var FilesApi = class {
21964
22000
  }
21965
22001
  await Promise.all(inflight);
21966
22002
  const r = await s.request("commit_upload", m([[0, uuid2.enc(open2.transfer)]]), {
21967
- codec: receipt,
22003
+ codec: plainAnswer(receipt),
21968
22004
  ...sig
21969
22005
  });
21970
22006
  const w = Object.assign(this.client._track(r), { fileId: opened.fileId });
@@ -22002,7 +22038,7 @@ var FilesApi = class {
22002
22038
  const self = this;
22003
22039
  const pending = new AbortController();
22004
22040
  const cancelledError = mdbaseError("cancelled", "file download cancelled");
22005
- let cancelled2 = false;
22041
+ let cancelled3 = false;
22006
22042
  let finished = false;
22007
22043
  let cancelSent = false;
22008
22044
  let detachAbort = () => {
@@ -22019,7 +22055,7 @@ var FilesApi = class {
22019
22055
  };
22020
22056
  const cancel = () => {
22021
22057
  if (finished) return;
22022
- cancelled2 = true;
22058
+ cancelled3 = true;
22023
22059
  detachAbort();
22024
22060
  fileReject(cancelledError);
22025
22061
  pending.abort();
@@ -22028,7 +22064,7 @@ var FilesApi = class {
22028
22064
  const stream = new ReadableStream({
22029
22065
  async start(ctrl) {
22030
22066
  const onAbort = () => {
22031
- if (finished || cancelled2) return;
22067
+ if (finished || cancelled3) return;
22032
22068
  cancel();
22033
22069
  ctrl.error(cancelledError);
22034
22070
  };
@@ -22040,7 +22076,7 @@ var FilesApi = class {
22040
22076
  }
22041
22077
  try {
22042
22078
  session = await self.session(pending.signal, true);
22043
- if (cancelled2) return;
22079
+ if (cancelled3) return;
22044
22080
  const p = m([[0, fileRef(f)]]);
22045
22081
  if (o.range) p.set(1, [o.range[0], o.range[1]]);
22046
22082
  if (o.revision) p.set(2, hash.enc(o.revision));
@@ -22071,7 +22107,7 @@ var FilesApi = class {
22071
22107
  self.early.clear();
22072
22108
  self.earlyFailures.clear();
22073
22109
  }
22074
- if (cancelled2) {
22110
+ if (cancelled3) {
22075
22111
  cancelRemote();
22076
22112
  finished = true;
22077
22113
  return;
@@ -22080,14 +22116,14 @@ var FilesApi = class {
22080
22116
  fileResolve(view);
22081
22117
  total = o.range ? o.range[1] : view.size;
22082
22118
  const deliver = (c) => {
22083
- if (cancelled2 || finished) return;
22119
+ if (cancelled3 || finished) return;
22084
22120
  ctrl.enqueue(c.bytes);
22085
22121
  received += c.bytes.length;
22086
22122
  o.onProgress?.({ id: streamId, phase: "streaming", done: received, total });
22087
- if (cancelled2 || finished) return;
22123
+ if (cancelled3 || finished) return;
22088
22124
  void session.request("ack_chunks", m([[0, streamId], [1, c.offset + c.bytes.length]])).catch(() => {
22089
22125
  });
22090
- if (c.last && !cancelled2 && !finished) {
22126
+ if (c.last && !cancelled3 && !finished) {
22091
22127
  finished = true;
22092
22128
  detachAbort();
22093
22129
  self.streams.delete(streamId);
@@ -22129,10 +22165,10 @@ var FilesApi = class {
22129
22165
  * `downloadStream`). Includes canonical unindexed Markdown Blob sources;
22130
22166
  * ordinary Blob support and AttachmentV1 behavior are unchanged. */
22131
22167
  async download(f, o = {}) {
22132
- const view = typeof f === "object" && "size" in f ? f : await this.get(f, o.signal);
22168
+ const view = typeof f === "object" && "size" in f ? f : await this.get(f, o);
22133
22169
  if (view.size > MAX_CONVENIENCE_BYTES) {
22134
22170
  throw mdbaseError("too_large", `file is ${view.size} bytes; use downloadStream`, {
22135
- details: /* @__PURE__ */ new Map([["limit", MAX_CONVENIENCE_BYTES]])
22171
+ details: { limit: MAX_CONVENIENCE_BYTES }
22136
22172
  });
22137
22173
  }
22138
22174
  const out = new Uint8Array(view.size);
@@ -22146,9 +22182,9 @@ var FilesApi = class {
22146
22182
  }
22147
22183
  return out.subarray(0, off);
22148
22184
  }
22149
- /** Materialize a remote file on this device. */
22150
- fetch(f, signal) {
22151
- return this.client.call("fetch_file", m([[0, uuid2.enc(fileId(f))]]), { retry: true, ...signal ? { signal } : {} }).then(() => {
22185
+ /** Materialize a remote file on this device. `o.signal` cancels the request. */
22186
+ fetch(f, o = {}) {
22187
+ return this.client.call("fetch_file", m([[0, uuid2.enc(fileId(f))]]), { retry: true, ...o.signal ? { signal: o.signal } : {} }).then(() => {
22152
22188
  });
22153
22189
  }
22154
22190
  /** Drop the local copy of a confirmed, unheld file (hosting app only). */
@@ -22167,8 +22203,7 @@ var FilesApi = class {
22167
22203
  async move(f, to, o = {}) {
22168
22204
  gates.get(this)?.check("move");
22169
22205
  const op2 = { kind: "file_move", id: f.id, from: f.path, to, updateRefs: o.updateRefs ?? true };
22170
- const [w] = await this.client.submit([o.ifRevision ? { ...op2, ifRevision: o.ifRevision } : op2], o);
22171
- return w;
22206
+ return this.client.submit([o.ifRevision ? { ...op2, ifRevision: o.ifRevision } : op2], o);
22172
22207
  }
22173
22208
  /** Delete a file. With a FileView, a concurrent replacement supersedes the delete. */
22174
22209
  async delete(f, o = {}) {
@@ -22176,17 +22211,114 @@ var FilesApi = class {
22176
22211
  const op2 = { kind: "file_delete", id: fileId(f) };
22177
22212
  if (typeof f === "object" && "digest" in f) op2.base = f.digest;
22178
22213
  if (o.ifRevision) op2.ifRevision = o.ifRevision;
22179
- const [w] = await this.client.submit([op2], o);
22180
- return w;
22214
+ return this.client.submit([op2], o);
22181
22215
  }
22182
22216
  };
22183
22217
 
22218
+ // src/settle.ts
22219
+ var DEFAULT_WAIT_MS = 3e3;
22220
+ var cancelled = (e) => isMdbaseError(e, "cancelled");
22221
+ var message = (e) => e instanceof Error ? e.message : String(e);
22222
+ function unknown(mutationId, reason, text6, receipt3) {
22223
+ const problem4 = { code: "outcome_unknown", recovery: "resolve_outcome", reason, message: text6 };
22224
+ return Object.freeze({ outcome: "unknown", mutationId, ...receipt3 ? { receipt: receipt3 } : {}, problem: problem4 });
22225
+ }
22226
+ async function settleWrite(client, input, options = {}) {
22227
+ const signal = options.signal;
22228
+ let write;
22229
+ let mutationId;
22230
+ let receipt3;
22231
+ if (typeof input === "string") {
22232
+ mutationId = input;
22233
+ try {
22234
+ receipt3 = await client.receipt(mutationId, { signal });
22235
+ } catch (e) {
22236
+ if (cancelled(e)) throw e;
22237
+ if (isMdbaseError(e, "not_found")) return Object.freeze({ outcome: "rejected", mutationId, problem: e.toProblem() });
22238
+ return unknown(mutationId, "receipt_unavailable", `The write's result could not be read: ${message(e)}`);
22239
+ }
22240
+ } else {
22241
+ try {
22242
+ write = await input;
22243
+ mutationId = write.mutationId;
22244
+ receipt3 = write.receipt;
22245
+ } catch (e) {
22246
+ if (!(e instanceof MdbaseError) || cancelled(e)) throw e;
22247
+ if (e.mutationId === void 0) return Object.freeze({ outcome: "rejected", problem: e.toProblem() });
22248
+ mutationId = e.mutationId;
22249
+ try {
22250
+ receipt3 = await client.receipt(mutationId, { signal });
22251
+ } catch (lookup) {
22252
+ if (cancelled(lookup)) throw lookup;
22253
+ if (isMdbaseError(lookup, "not_found")) return Object.freeze({ outcome: "rejected", mutationId, problem: e.toProblem() });
22254
+ return unknown(mutationId, "receipt_unavailable", `The write may have been saved: ${e.message}`);
22255
+ }
22256
+ }
22257
+ }
22258
+ if (receipt3.state === "pending") {
22259
+ try {
22260
+ receipt3 = await client.awaitReceipt(mutationId, { timeoutMs: options.timeoutMs ?? DEFAULT_WAIT_MS, signal });
22261
+ write?.update(receipt3);
22262
+ } catch (e) {
22263
+ if (cancelled(e)) throw e;
22264
+ receipt3 = write?.receipt ?? receipt3;
22265
+ }
22266
+ }
22267
+ if (receipt3.mutation !== mutationId) {
22268
+ throw new MdbaseError(
22269
+ { code: "internal", recovery: "contact_support", message: "the replica answered with another mutation's receipt" },
22270
+ { mutationId }
22271
+ );
22272
+ }
22273
+ if (receipt3.state === "unknown") {
22274
+ const problem4 = receipt3.problem ?? { code: "outcome_unknown", recovery: "resolve_outcome", message: "The write's result is not known." };
22275
+ return Object.freeze({ outcome: "unknown", mutationId, receipt: receipt3, problem: problem4 });
22276
+ }
22277
+ if (receipt3.state === "rejected") {
22278
+ const problem4 = receipt3.problem ?? { code: "internal", recovery: "contact_support", message: "The write was rejected without a reason." };
22279
+ return Object.freeze({ outcome: "rejected", mutationId, receipt: receipt3, problem: problem4 });
22280
+ }
22281
+ let read;
22282
+ if (options.read) {
22283
+ const how = options.read === true ? {} : options.read;
22284
+ const named = receipt3.records?.length === 1 ? receipt3.records[0].id : void 0;
22285
+ const ref = how.record ?? write?.recordId ?? named;
22286
+ if (ref === void 0) {
22287
+ throw new MdbaseError(
22288
+ { code: "invalid_request", recovery: "fix_request", message: "settle cannot tell which record to read back; pass read.record" },
22289
+ { mutationId }
22290
+ );
22291
+ }
22292
+ try {
22293
+ read = await readBack(client, ref, how, signal);
22294
+ } catch (e) {
22295
+ if (cancelled(e)) throw e;
22296
+ return unknown(mutationId, "readback_failed", `The write was kept, but the record could not be read back: ${message(e)}`, receipt3);
22297
+ }
22298
+ }
22299
+ const kept = { mutationId, receipt: receipt3, ...read };
22300
+ if (receipt3.state === "pending") return Object.freeze({ outcome: "saved_on_device", ...kept });
22301
+ if (receipt3.status === "conflicted") return Object.freeze({ outcome: "conflicted", ...kept, conflicts: Object.freeze([...receipt3.conflicts ?? []]) });
22302
+ return Object.freeze({ outcome: "confirmed", ...kept });
22303
+ }
22304
+ async function readBack(client, ref, how, signal) {
22305
+ let record3;
22306
+ try {
22307
+ record3 = await client.get(ref, { include: how.include, signal });
22308
+ } catch (e) {
22309
+ if (!isMdbaseError(e, "not_found")) throw e;
22310
+ return how.contract ? { record: null, contractRecord: null } : { record: null };
22311
+ }
22312
+ return how.contract ? { record: record3, contractRecord: await client.getContract(record3, how.contract, { signal }) } : { record: record3 };
22313
+ }
22314
+
22184
22315
  // src/read-helpers.ts
22185
22316
  var READ_MANY_MAX_REFS = 1e3;
22186
22317
  var READ_MANY_MAX_CONCURRENCY = 16;
22187
- async function readMany(client, refs, include3, signal, options = {}) {
22318
+ async function readMany(client, refs, o = {}) {
22319
+ const { include: include3, signal } = o;
22188
22320
  signal?.throwIfAborted();
22189
- const concurrency = options.concurrency ?? 8;
22321
+ const concurrency = o.concurrency ?? 8;
22190
22322
  if (!Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > READ_MANY_MAX_CONCURRENCY) {
22191
22323
  throw mdbaseError(
22192
22324
  "invalid_request",
@@ -22203,6 +22335,10 @@ async function readMany(client, refs, include3, signal, options = {}) {
22203
22335
  }
22204
22336
  const selections2 = Array.from(refs, capture);
22205
22337
  const capturedInclude = include3 ? Object.freeze({ ...include3 }) : void 0;
22338
+ const read = {
22339
+ ...capturedInclude ? { include: capturedInclude } : {},
22340
+ ...signal ? { signal } : {}
22341
+ };
22206
22342
  const records2 = new Array(selections2.length);
22207
22343
  let next = 0, failed = false, failure2;
22208
22344
  async function worker() {
@@ -22210,11 +22346,7 @@ async function readMany(client, refs, include3, signal, options = {}) {
22210
22346
  try {
22211
22347
  signal?.throwIfAborted();
22212
22348
  const index = next++, selected = selections2[index];
22213
- const record3 = await client.get(
22214
- selected,
22215
- capturedInclude,
22216
- signal
22217
- );
22349
+ const record3 = await client.get(selected, read);
22218
22350
  signal?.throwIfAborted();
22219
22351
  if (failed) return;
22220
22352
  if (typeof selected === "string" && record3.id !== selected) {
@@ -22263,8 +22395,8 @@ function capture(ref) {
22263
22395
  }
22264
22396
  return Object.freeze({ path: ref.path });
22265
22397
  }
22266
- function queryPages(client, query, include3, signal, options = {}) {
22267
- return client.pages(query, include3, signal, options);
22398
+ function queryPages(client, query, o = {}) {
22399
+ return client.pages(query, o);
22268
22400
  }
22269
22401
 
22270
22402
  // src/records/witness.ts
@@ -22285,14 +22417,14 @@ function complete(record3, id4) {
22285
22417
  );
22286
22418
  }
22287
22419
  }
22288
- function protectedRecord(record3) {
22420
+ function isProtected(record3) {
22289
22421
  return record3.state.hold !== void 0 || record3.state.unresolved !== void 0 && record3.state.unresolved !== 0;
22290
22422
  }
22291
22423
  function confirmed(record3) {
22292
- return record3.state.state === "confirmed" && !protectedRecord(record3);
22424
+ return record3.state.state === "confirmed" && !isProtected(record3);
22293
22425
  }
22294
- function copy(record3) {
22295
- return recordView.dec(decode(encode(recordView.enc(record3))));
22426
+ function copy(data) {
22427
+ return structuredClone(data);
22296
22428
  }
22297
22429
  function problem2(error4) {
22298
22430
  if (error4 instanceof MdbaseError) return error4.toProblem();
@@ -22303,16 +22435,19 @@ function problem2(error4) {
22303
22435
  error4 instanceof Error ? error4.message : "record session failure"
22304
22436
  ).toProblem();
22305
22437
  }
22306
- function refusal(code, message, reason) {
22438
+ function refusal(code, message2, reason) {
22307
22439
  return new MdbaseError({
22308
22440
  code,
22309
- message,
22441
+ message: message2,
22310
22442
  reason,
22311
22443
  recovery: code === "conflict" ? "resolve_conflict" : code === "outcome_unknown" ? "resolve_outcome" : "retry"
22312
22444
  });
22313
22445
  }
22314
- function recordBytes(record3) {
22315
- return encode(recordView.enc(record3)).byteLength * 2;
22446
+ function retainedBytes(data) {
22447
+ return JSON.stringify(
22448
+ data,
22449
+ (_key, v) => typeof v === "bigint" ? v.toString() : v instanceof Uint8Array ? toHex(v) : v
22450
+ ).length * 2;
22316
22451
  }
22317
22452
  function textBytes(text6) {
22318
22453
  if (text6.length > MAX_BYTES)
@@ -22342,7 +22477,7 @@ var RecordSessionImpl = class {
22342
22477
  complete(record3);
22343
22478
  this.base = copy(record3);
22344
22479
  this.body = record3.body;
22345
- this.state = protectedRecord(record3) ? "conflict" : resting(record3);
22480
+ this.state = isProtected(record3) ? "conflict" : resting(record3);
22346
22481
  this.publish();
22347
22482
  }
22348
22483
  client;
@@ -22447,7 +22582,7 @@ var RecordSessionImpl = class {
22447
22582
  const next = new Map(this.patch);
22448
22583
  for (const [key3, input] of patch instanceof Map ? patch : Object.entries(patch)) {
22449
22584
  const value2 = input === void 0 ? void 0 : decode(encode(toValue(input)));
22450
- const before = this.base.frontmatter.get(key3);
22585
+ const before = Object.hasOwn(this.base.frontmatter, key3) ? toValue(this.base.frontmatter[key3]) : void 0;
22451
22586
  if (!this.captured?.patch.has(key3) && (value2 === void 0 && before === void 0 || value2 !== void 0 && before !== void 0 && equal5(value2, before)))
22452
22587
  next.delete(key3);
22453
22588
  else next.set(key3, value2);
@@ -22465,35 +22600,35 @@ var RecordSessionImpl = class {
22465
22600
  this.schedule();
22466
22601
  }
22467
22602
  charge(body = this.body, patch = this.patch, base = this.base, remote = this.remote, receipt3 = this.lastReceipt, captured = this.captured) {
22468
- let bytes10 = recordBytes(base) + textBytes(body) + encode(new Map([...patch].map(([k, v]) => [k, v ?? null]))).byteLength * 2;
22469
- if (remote) bytes10 += recordBytes(remote);
22603
+ let bytes10 = retainedBytes(base) + textBytes(body) + encode(new Map([...patch].map(([k, v]) => [k, v ?? null]))).byteLength * 2;
22604
+ if (remote) bytes10 += retainedBytes(remote);
22470
22605
  if (captured)
22471
22606
  bytes10 += textBytes(captured.body) + encode(
22472
22607
  new Map(
22473
22608
  [...captured.patch].map(([k, v]) => [k, v ?? null])
22474
22609
  )
22475
22610
  ).byteLength * 2;
22476
- if (receipt3) bytes10 += encode(receipt.enc(receipt3)).byteLength * 2;
22611
+ if (receipt3) bytes10 += retainedBytes(receipt3);
22477
22612
  this.reserve(bytes10);
22478
22613
  }
22479
22614
  publish() {
22480
22615
  this.charge();
22481
- const fm = new Map(this.base.frontmatter);
22616
+ const fm = new Map(
22617
+ Object.entries(this.base.frontmatter)
22618
+ );
22482
22619
  for (const [k, v] of this.patch) {
22483
22620
  if (v === void 0) fm.delete(k);
22484
- else fm.set(k, v);
22621
+ else fm.set(k, toPlain(v));
22485
22622
  }
22486
22623
  this.snapshot = Object.freeze({
22487
22624
  state: this.state,
22488
22625
  body: this.body,
22489
- frontmatter: decode(encode(fm)),
22626
+ frontmatter: structuredClone(Object.fromEntries(fm)),
22490
22627
  record: copy(this.base),
22491
22628
  remote: this.remote ? copy(this.remote) : null,
22492
22629
  dirty: this.dirty,
22493
22630
  problem: this.why,
22494
- lastReceipt: this.lastReceipt ? receipt.dec(
22495
- decode(encode(receipt.enc(this.lastReceipt)))
22496
- ) : null,
22631
+ lastReceipt: this.lastReceipt ? copy(this.lastReceipt) : null,
22497
22632
  recovery: this.captured ? Object.freeze({ ...this.captured.recovery }) : null
22498
22633
  });
22499
22634
  for (const listener of [...this.listeners]) {
@@ -22518,7 +22653,7 @@ var RecordSessionImpl = class {
22518
22653
  }
22519
22654
  }
22520
22655
  async read(signal) {
22521
- const record3 = await this.client.get(this.id, include2, signal);
22656
+ const record3 = await this.client.get(this.id, { include: include2, signal });
22522
22657
  signal.throwIfAborted();
22523
22658
  complete(record3, this.id);
22524
22659
  return record3;
@@ -22547,9 +22682,9 @@ var RecordSessionImpl = class {
22547
22682
  this.base = copy(current2);
22548
22683
  this.body = current2.body;
22549
22684
  this.remote = null;
22550
- this.state = protectedRecord(current2) ? "conflict" : resting(current2);
22685
+ this.state = isProtected(current2) ? "conflict" : resting(current2);
22551
22686
  this.why = null;
22552
- } else if (current2.revision !== this.base.revision || protectedRecord(current2)) {
22687
+ } else if (current2.revision !== this.base.revision || isProtected(current2)) {
22553
22688
  this.remote = copy(current2);
22554
22689
  this.state = "conflict";
22555
22690
  this.why = refusal(
@@ -22628,7 +22763,7 @@ var RecordSessionImpl = class {
22628
22763
  saved: "on_device"
22629
22764
  };
22630
22765
  const current2 = await this.read(signal);
22631
- if (protectedRecord(current2)) {
22766
+ if (isProtected(current2)) {
22632
22767
  this.charge(this.body, this.patch, this.base, current2);
22633
22768
  this.remote = copy(current2);
22634
22769
  throw refusal(
@@ -22726,11 +22861,13 @@ var RecordSessionImpl = class {
22726
22861
  }
22727
22862
  async settle(signal, budget) {
22728
22863
  const captured = this.captured, original = captured.recovery;
22729
- const receipt3 = await this.client.awaitReceipt(
22730
- original.mutationId,
22731
- Math.max(1, budget.until - Date.now() - budget.margin),
22864
+ const receipt3 = await this.client.awaitReceipt(original.mutationId, {
22865
+ timeoutMs: Math.max(
22866
+ 1,
22867
+ budget.until - Date.now() - budget.margin
22868
+ ),
22732
22869
  signal
22733
- );
22870
+ });
22734
22871
  signal.throwIfAborted();
22735
22872
  if (receipt3.mutation !== original.mutationId)
22736
22873
  throw refusal(
@@ -22769,7 +22906,7 @@ var RecordSessionImpl = class {
22769
22906
  }
22770
22907
  const current2 = await this.read(signal);
22771
22908
  const kept = receipt3.state === "pending";
22772
- if (kept ? protectedRecord(current2) : !confirmed(current2))
22909
+ if (kept ? isProtected(current2) : !confirmed(current2))
22773
22910
  throw refusal(
22774
22911
  "outcome_unknown",
22775
22912
  "confirmed receipt has pending/protected current readback",
@@ -22912,7 +23049,10 @@ var RecordsApi = class {
22912
23049
  if (this.closed)
22913
23050
  throw mdbaseError("unavailable", "record sessions client closed");
22914
23051
  options.signal?.throwIfAborted();
22915
- const current2 = await this.client.get(ref, include2, options.signal);
23052
+ const current2 = await this.client.get(ref, {
23053
+ include: include2,
23054
+ signal: options.signal
23055
+ });
22916
23056
  options.signal?.throwIfAborted();
22917
23057
  if (this.closed)
22918
23058
  throw mdbaseError("unavailable", "record sessions client closed");
@@ -23042,7 +23182,7 @@ var RecordsApi = class {
23042
23182
  }
23043
23183
  startWatch() {
23044
23184
  if (this.watch) return;
23045
- const watch = this.client.watchChanges(void 0, (batch) => {
23185
+ const watch = this.client.watchChanges((batch) => {
23046
23186
  for (const [id4, slot] of this.slots)
23047
23187
  if (slot.leases > 0 && (batch.reset || batch.changes.some((change3) => change3.id === id4)))
23048
23188
  void slot.session.refresh();
@@ -23095,28 +23235,28 @@ var RecordsApi = class {
23095
23235
 
23096
23236
  // src/saved-views.ts
23097
23237
  var SAVED_VIEW_CONTRACT = Object.freeze({ id: "mdbase.view", version: "1.0.0" });
23098
- var map3 = (v) => v instanceof Map ? v : void 0;
23238
+ var map3 = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : void 0;
23239
+ var list3 = (v) => Array.isArray(v) ? v : [];
23099
23240
  var text3 = (v) => typeof v === "string" ? v : void 0;
23100
- var warning = (code, message, path) => ({ code, severity: "warning", message, details: /* @__PURE__ */ new Map([["path", path]]) });
23241
+ var warning = (code, message2, path) => ({ code, severity: "warning", message: message2, details: { path } });
23101
23242
  var notFound = (e, path) => {
23102
23243
  if (isMdbaseError(e, "not_found")) throw mdbaseError("not_found", `saved view source '${path}' was not found`, "view_not_found");
23103
23244
  throw e;
23104
23245
  };
23105
23246
  var refPath = (ref) => typeof ref === "string" ? ref : ref.path;
23106
23247
  function properties(record3, view) {
23107
- const metadata2 = map3(record3.get("properties"));
23248
+ const metadata2 = map3(fieldOf(record3, "properties"));
23108
23249
  const out = [];
23109
- const select = Array.isArray(view.get("select")) ? view.get("select") : [];
23110
- for (const selection of select) {
23250
+ for (const selection of list3(fieldOf(view, "select"))) {
23111
23251
  const object9 = map3(selection);
23112
23252
  const selector = text3(selection);
23113
- const key3 = object9 ? text3(object9.get("name")) : selector?.slice(selector.lastIndexOf(".") + 1);
23253
+ const key3 = object9 ? text3(fieldOf(object9, "name")) : selector?.slice(selector.lastIndexOf(".") + 1);
23114
23254
  if (!key3) continue;
23115
- const meta = map3(metadata2?.get(object9 || !selector ? key3 : selector)) ?? map3(metadata2?.get(key3));
23255
+ const meta = map3(fieldOf(metadata2, object9 || !selector ? key3 : selector)) ?? map3(fieldOf(metadata2, key3));
23116
23256
  const property = { key: key3 };
23117
- const label = text3(object9?.get("label")) ?? text3(meta?.get("label"));
23118
- const description = text3(object9?.get("description")) ?? text3(meta?.get("description"));
23119
- const format = text3(meta?.get("format")), hidden = meta?.get("hidden");
23257
+ const label = text3(fieldOf(object9, "label")) ?? text3(fieldOf(meta, "label"));
23258
+ const description = text3(fieldOf(object9, "description")) ?? text3(fieldOf(meta, "description"));
23259
+ const format = text3(fieldOf(meta, "format")), hidden = fieldOf(meta, "hidden");
23120
23260
  if (label !== void 0) property.label = label;
23121
23261
  if (description !== void 0) property.description = description;
23122
23262
  if (format !== void 0) property.format = format;
@@ -23125,7 +23265,8 @@ function properties(record3, view) {
23125
23265
  }
23126
23266
  return out;
23127
23267
  }
23128
- async function listSavedViews(client, folder, signal) {
23268
+ async function listSavedViews(client, o = {}) {
23269
+ const { folder, signal } = o;
23129
23270
  const sources = [], diagnostics = [];
23130
23271
  const prefix = folder ? folder.replace(/\/?$/, "/") : "";
23131
23272
  let cursor, complete2 = true;
@@ -23148,8 +23289,8 @@ async function listSavedViews(client, folder, signal) {
23148
23289
  return;
23149
23290
  }
23150
23291
  const fields3 = projection.fields, views = [], ids = /* @__PURE__ */ new Set();
23151
- for (const item of Array.isArray(fields3.get("views")) ? fields3.get("views") : []) {
23152
- const view = map3(item), id4 = text3(view?.get("id")), name2 = text3(view?.get("name"));
23292
+ for (const item of list3(fieldOf(fields3, "views"))) {
23293
+ const view = map3(item), id4 = text3(fieldOf(view, "id")), name2 = text3(fieldOf(view, "name"));
23153
23294
  if (!view || !id4 || !name2) continue;
23154
23295
  if (ids.has(id4)) {
23155
23296
  diagnostics.push(warning("invalid_view", "View record contains duplicate named-view IDs.", record3.path));
@@ -23157,13 +23298,14 @@ async function listSavedViews(client, folder, signal) {
23157
23298
  }
23158
23299
  ids.add(id4);
23159
23300
  const descriptor = { id: id4, name: name2, properties: properties(fields3, view) };
23160
- if (view.has("presentation")) descriptor.presentation = view.get("presentation");
23301
+ const presentation = fieldOf(view, "presentation");
23302
+ if (presentation !== void 0) descriptor.presentation = presentation;
23161
23303
  views.push(descriptor);
23162
23304
  }
23163
23305
  sources.push({
23164
23306
  record: record3.id,
23165
- id: text3(fields3.get("id")) ?? record3.path,
23166
- name: text3(fields3.get("name")) ?? record3.path,
23307
+ id: text3(fieldOf(fields3, "id")) ?? record3.path,
23308
+ name: text3(fieldOf(fields3, "name")) ?? record3.path,
23167
23309
  source: { path: record3.path, format: SAVED_VIEW_CONTRACT.id, revision: record3.revision, writable: true },
23168
23310
  views
23169
23311
  });
@@ -23175,68 +23317,73 @@ async function listSavedViews(client, folder, signal) {
23175
23317
  }
23176
23318
  async function executeSavedView(client, source, viewId, o = {}) {
23177
23319
  const signal = o.signal;
23178
- const record3 = await client.getContract(source, SAVED_VIEW_CONTRACT, signal).catch((e) => notFound(e, refPath(source)));
23320
+ const record3 = await client.getContract(source, SAVED_VIEW_CONTRACT, { signal }).catch((e) => notFound(e, refPath(source)));
23179
23321
  const fields3 = record3.fields, path = record3.path;
23180
- const views = Array.isArray(fields3.get("views")) ? fields3.get("views").map(map3) : [];
23181
- const ids = views.map((view2) => text3(view2?.get("id")));
23322
+ const views = list3(fieldOf(fields3, "views")).map(map3);
23323
+ const ids = views.map((view2) => text3(fieldOf(view2, "id")));
23182
23324
  if (new Set(ids).size !== ids.length) throw mdbaseError("invalid_request", "View record contains duplicate named-view IDs.", "invalid_view");
23183
23325
  const view = views[ids.indexOf(viewId)];
23184
23326
  if (!view) throw mdbaseError("not_found", `named view '${viewId}' was not found`, "view_not_found");
23185
- const shared = map3(fields3.get("query")) ?? /* @__PURE__ */ new Map();
23327
+ const shared = map3(fieldOf(fields3, "query"));
23186
23328
  const query = /* @__PURE__ */ new Map();
23187
- const types = view.get("types") ?? shared.get("types");
23329
+ const types = fieldOf(view, "types") ?? fieldOf(shared, "types");
23188
23330
  if (types !== void 0) query.set("types", types);
23189
- const wheres = [text3(shared.get("where")), text3(view.get("where"))].filter((w) => !!w);
23331
+ const wheres = [text3(fieldOf(shared, "where")), text3(fieldOf(view, "where"))].filter((w) => !!w);
23190
23332
  if (wheres.length) query.set("where", wheres.length === 2 ? `(${wheres[0]}) && (${wheres[1]})` : wheres[0]);
23191
- const projections = new Map(map3(shared.get("projections")));
23192
- for (const [name2, definition] of map3(view.get("projections")) ?? []) {
23333
+ const projections = new Map(Object.entries(map3(fieldOf(shared, "projections")) ?? {}));
23334
+ for (const [name2, definition] of Object.entries(map3(fieldOf(view, "projections")) ?? {})) {
23193
23335
  const existing = projections.get(name2);
23194
23336
  if (existing !== void 0 && canonical(existing) !== canonical(definition))
23195
23337
  throw mdbaseError("invalid_request", `Projection '${name2}' has conflicting definitions.`, "invalid_view");
23196
23338
  projections.set(name2, definition);
23197
23339
  }
23198
- if (projections.size) query.set("projections", projections);
23199
- for (const key3 of ["select", "order_by", "group_by", "summaries", "limit", "offset", "include_body", "frontmatter_mode"])
23200
- if (view.has(key3)) query.set(key3, view.get(key3));
23201
- if (fields3.has("summary_functions")) query.set("summary_functions", fields3.get("summary_functions"));
23340
+ if (projections.size) query.set("projections", Object.fromEntries(projections));
23341
+ for (const key3 of ["select", "order_by", "group_by", "summaries", "limit", "offset", "include_body", "frontmatter_mode"]) {
23342
+ const value2 = fieldOf(view, key3);
23343
+ if (value2 !== void 0) query.set(key3, value2);
23344
+ }
23345
+ const summaryFunctions = fieldOf(fields3, "summary_functions");
23346
+ if (summaryFunctions !== void 0) query.set("summary_functions", summaryFunctions);
23202
23347
  if (o.limit !== void 0) query.set("limit", o.limit);
23203
23348
  if (o.offset !== void 0) query.set("offset", o.offset);
23204
23349
  if (o.timezone !== void 0) query.set("timezone", o.timezone);
23205
- const declaration = map3(map3(view.get("context") ?? shared.get("context"))?.get("this"));
23206
- const onMissing = text3(declaration?.get("on_missing")) ?? "view";
23350
+ const declaration = map3(fieldOf(map3(fieldOf(view, "context") ?? fieldOf(shared, "context")), "this"));
23351
+ const onMissing = text3(fieldOf(declaration, "on_missing")) ?? "view";
23207
23352
  let context = o.context;
23208
23353
  if (context === void 0 && onMissing === "error") throw mdbaseError("invalid_request", "This named view requires an invocation context.", "context_required");
23209
23354
  if (context === void 0 && onMissing === "view") context = { path };
23210
23355
  if (context !== void 0) {
23211
- const required = Array.isArray(declaration?.get("types")) ? declaration.get("types").filter((t) => typeof t === "string") : [];
23356
+ const required = list3(fieldOf(declaration, "types")).filter((t) => typeof t === "string");
23212
23357
  let contextPath = typeof context === "string" ? void 0 : context.path;
23213
23358
  if (required.length || contextPath === void 0) {
23214
- const bound = await client.get(context, void 0, signal);
23359
+ const bound = await client.get(context, { signal });
23215
23360
  contextPath = bound.path;
23216
23361
  if (required.length && !bound.types.some((t) => required.some((r) => r.toLowerCase() === t.toLowerCase())))
23217
23362
  throw mdbaseError("invalid_request", "The invocation context does not match an allowed context type.", "context_type_mismatch");
23218
23363
  }
23219
- query.set("context", /* @__PURE__ */ new Map([["this", /* @__PURE__ */ new Map([["path", contextPath]])]]));
23364
+ query.set("context", { this: { path: contextPath } });
23220
23365
  }
23221
- const result2 = await client.query(query, o.include, signal);
23366
+ const result2 = await client.query(Object.fromEntries(query), { include: o.include, signal });
23222
23367
  return { ...result2, view: { path, view: viewId } };
23223
23368
  }
23224
- async function readSavedViewSource(client, source, signal) {
23225
- const contract = await client.getContract(source, SAVED_VIEW_CONTRACT, signal).catch((e) => notFound(e, refPath(source)));
23226
- const record3 = await client.get(contract.id, { document: true }, signal);
23369
+ async function readSavedViewSource(client, source, o = {}) {
23370
+ const signal = o.signal;
23371
+ const contract = await client.getContract(source, SAVED_VIEW_CONTRACT, { signal }).catch((e) => notFound(e, refPath(source)));
23372
+ const record3 = await client.get(contract.id, { include: { document: true }, signal });
23227
23373
  if (record3.revision !== contract.revision || typeof record3.document !== "string")
23228
23374
  throw mdbaseError("unavailable", "saved view source changed while it was read", "view_source_changed");
23229
23375
  return { path: record3.path, format: SAVED_VIEW_CONTRACT.id, revision: record3.revision, document: record3.document, record: record3.id };
23230
23376
  }
23231
23377
  function canonical(v) {
23232
- if (v instanceof Map) return `{${[...v].map(([k, x]) => [JSON.stringify(String(k)), canonical(x)]).sort((a, b) => a[0] < b[0] ? -1 : 1).map(([k, x]) => `${k}:${x}`).join(",")}}`;
23233
23378
  if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`;
23234
- return typeof v === "bigint" ? `${v}n` : JSON.stringify(v instanceof Uint8Array ? [...v] : v);
23379
+ if (v !== null && typeof v === "object")
23380
+ return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`;
23381
+ return JSON.stringify(v);
23235
23382
  }
23236
23383
 
23237
23384
  // src/view-sources.ts
23238
- function invalid4(message) {
23239
- return mdbaseError("invalid_request", message, "view_source_witness_required");
23385
+ function invalid4(message2) {
23386
+ return mdbaseError("invalid_request", message2, "view_source_witness_required");
23240
23387
  }
23241
23388
  function identity(id4) {
23242
23389
  try {
@@ -23266,7 +23413,7 @@ function sourceOptions(options) {
23266
23413
  async function readViewSourceRecord(client, source, options = {}) {
23267
23414
  const expectedId = typeof source === "string" ? source : "id" in source ? source.id : void 0;
23268
23415
  const expected = expectedId === void 0 ? void 0 : uuid2.dec(uuid2.enc(expectedId));
23269
- const record3 = await client.get(source, { ...options.include, document: true }, options.signal);
23416
+ const record3 = await client.get(source, { include: { ...options.include, document: true }, signal: options.signal });
23270
23417
  fullSource(record3);
23271
23418
  if (expected !== void 0 && record3.id !== expected) throw invalid4("view source readback belongs to another record");
23272
23419
  return record3;
@@ -23400,6 +23547,303 @@ var LiveResult = class {
23400
23547
  }
23401
23548
  };
23402
23549
 
23550
+ // src/record-set.ts
23551
+ var PAGE = 1e3;
23552
+ var REREAD_MAX = 500;
23553
+ var REREAD_CONCURRENCY = 8;
23554
+ var RETRY_MIN_MS = 250;
23555
+ var RETRY_MAX_MS = 3e4;
23556
+ function passing(e) {
23557
+ if (!(e instanceof MdbaseError)) return false;
23558
+ if (e.recovery === "retry") return true;
23559
+ return e.code === "invalid_request" && (e.reason === "cursor_stale" || e.reason === "cursor_expired") || e.code === "conflict" && e.reason === "collection_changed";
23560
+ }
23561
+ var problemOf = (e) => e instanceof MdbaseError ? e.toProblem() : { code: "internal", recovery: "contact_support", message: e instanceof Error ? e.message : String(e) };
23562
+ var fold = (type) => type.replace(/[A-Z]/g, (c) => c.toLowerCase());
23563
+ var sameTypes = (a, b) => a.length === b.length && a.every((t, i) => t === b[i]);
23564
+ var unchanged = (a, b) => a.revision === b.revision && a.path === b.path && a.state.state === b.state.state && a.state.hold?.id === b.state.hold?.id && a.state.unresolved === b.state.unresolved && sameTypes(a.types, b.types);
23565
+ var RecordSet = class {
23566
+ /** @internal `MdbaseClient.recordSet`. */
23567
+ constructor(client, options = {}) {
23568
+ this.client = client;
23569
+ this.signal = options.signal;
23570
+ this.pending = client.status.pending;
23571
+ this.types = options.types?.length ? [...options.types] : void 0;
23572
+ this.folded = this.types?.map(fold);
23573
+ this.include = options.include ? { ...options.include } : void 0;
23574
+ this.ready = new Promise((resolve, reject) => {
23575
+ this.resolveReady = resolve;
23576
+ this.rejectReady = reject;
23577
+ });
23578
+ this.ready.catch(() => {
23579
+ });
23580
+ this.offStatus = client.onStatus((s) => {
23581
+ const settled = s.pending < this.pending;
23582
+ this.pending = s.pending;
23583
+ if (!settled) return;
23584
+ for (const r of this.byId.values()) if (r.state.state === "pending") this.queued.add(r.id);
23585
+ void this.work();
23586
+ });
23587
+ this.startWatch();
23588
+ this.signal?.addEventListener("abort", this.abort, { once: true });
23589
+ if (this.signal?.aborted) this.close();
23590
+ }
23591
+ client;
23592
+ /** Resolves when the set is first `current`; rejects if it fails or closes first. */
23593
+ ready;
23594
+ resolveReady;
23595
+ rejectReady;
23596
+ lifetime = new AbortController();
23597
+ listeners = /* @__PURE__ */ new Set();
23598
+ types;
23599
+ folded;
23600
+ include;
23601
+ byId = /* @__PURE__ */ new Map();
23602
+ view = Object.freeze({ records: Object.freeze([]), state: "loading", problem: null });
23603
+ /** Changed since `view.records` was built. */
23604
+ touched = false;
23605
+ state = "loading";
23606
+ problem = null;
23607
+ watch;
23608
+ offWatch = () => {
23609
+ };
23610
+ offStatus;
23611
+ abort = () => this.close();
23612
+ /** Where the change feed was last read to, so a replaced watch resumes there. */
23613
+ cursor;
23614
+ /** Records the feed named since they were last read. */
23615
+ queued = /* @__PURE__ */ new Set();
23616
+ /** A complete read has finished. */
23617
+ loaded = false;
23618
+ /** A complete read is needed. */
23619
+ dirty = true;
23620
+ working = false;
23621
+ /** A retry that is waiting, and what it will do. */
23622
+ timer;
23623
+ again;
23624
+ delay = RETRY_MIN_MS;
23625
+ pending;
23626
+ signal;
23627
+ getSnapshot = () => this.view;
23628
+ get(id4) {
23629
+ return this.byId.get(id4);
23630
+ }
23631
+ subscribe = (listener) => {
23632
+ if (this.state !== "closed") this.listeners.add(listener);
23633
+ return () => {
23634
+ this.listeners.delete(listener);
23635
+ };
23636
+ };
23637
+ /** Read every record again: after `failed`, or when something the change
23638
+ * feed does not report (a type definition) has changed. */
23639
+ reload() {
23640
+ if (this.state === "closed") return Promise.reject(mdbaseError("cancelled", "record set closed"));
23641
+ this.dirty = true;
23642
+ this.delay = RETRY_MIN_MS;
23643
+ if (this.state === "failed") {
23644
+ this.problem = null;
23645
+ this.publish(this.loaded ? "stale" : "loading");
23646
+ if (this.watch.state === "failed" || this.watch.state === "closed") this.startWatch();
23647
+ }
23648
+ return new Promise((resolve, reject) => {
23649
+ const off = this.subscribe(() => {
23650
+ if (this.state === "current" && !this.dirty) {
23651
+ off();
23652
+ resolve();
23653
+ } else if (this.state === "failed" || this.state === "closed") {
23654
+ off();
23655
+ reject(new MdbaseError(this.problem ?? { code: "cancelled", recovery: "none", message: "record set closed" }));
23656
+ }
23657
+ });
23658
+ this.resume();
23659
+ });
23660
+ }
23661
+ close() {
23662
+ if (this.state === "closed") return;
23663
+ this.lifetime.abort();
23664
+ this.cancelRetry();
23665
+ this.signal?.removeEventListener("abort", this.abort);
23666
+ this.offStatus();
23667
+ this.offWatch();
23668
+ this.watch();
23669
+ this.rejectReady(mdbaseError("cancelled", "record set closed"));
23670
+ this.publish("closed");
23671
+ this.listeners.clear();
23672
+ }
23673
+ startWatch() {
23674
+ this.offWatch();
23675
+ const watch = this.client.watchChanges((batch) => {
23676
+ if (this.watch === watch) this.changed(batch);
23677
+ }, { cursor: this.cursor });
23678
+ this.watch = watch;
23679
+ if (this.cursor === void 0) this.dirty = true;
23680
+ this.offWatch = watch.subscribe((state, error4) => {
23681
+ if (this.watch !== watch || this.state === "closed" || this.state === "failed") return;
23682
+ if (state === "active") {
23683
+ void this.work();
23684
+ return;
23685
+ }
23686
+ if (state === "stale") {
23687
+ if (this.loaded) this.publish("stale");
23688
+ return;
23689
+ }
23690
+ if (state === "closed") {
23691
+ this.close();
23692
+ return;
23693
+ }
23694
+ if (state === "failed") {
23695
+ if (error4 && passing(error4) && this.client.link !== "closed") this.retry(error4, () => this.startWatch());
23696
+ else this.fail(error4 ?? mdbaseError("unavailable", "the change watch stopped"));
23697
+ }
23698
+ });
23699
+ }
23700
+ changed(batch) {
23701
+ this.cursor = batch.cursor;
23702
+ if (batch.reset) this.dirty = true;
23703
+ for (const c of batch.changes) {
23704
+ if (c.entity === "file") continue;
23705
+ if (c.kind === "put" && this.types && c.types && !this.byId.has(c.id) && !this.member(c.types)) continue;
23706
+ if (c.kind === "remove" && !this.byId.has(c.id)) continue;
23707
+ this.queued.add(c.id);
23708
+ }
23709
+ void this.work();
23710
+ }
23711
+ member(types) {
23712
+ return !this.folded || types.some((t) => this.folded.includes(fold(t)));
23713
+ }
23714
+ /** One worker at a time: a complete read when one is needed, else rereads. */
23715
+ async work() {
23716
+ if (this.working || this.timer !== void 0) return;
23717
+ this.working = true;
23718
+ try {
23719
+ while (this.state !== "closed" && this.state !== "failed" && this.watch.state === "active" && (this.dirty || this.queued.size)) {
23720
+ if (!this.dirty && this.queued.size <= REREAD_MAX) await this.reread();
23721
+ else if (!await this.load()) {
23722
+ this.retry(null, () => void this.work());
23723
+ return;
23724
+ }
23725
+ this.delay = RETRY_MIN_MS;
23726
+ }
23727
+ } catch (e) {
23728
+ if (this.state === "closed" || isMdbaseError(e, "cancelled")) return;
23729
+ if (passing(e)) this.retry(e, () => void this.work());
23730
+ else this.fail(e);
23731
+ return;
23732
+ } finally {
23733
+ this.working = false;
23734
+ }
23735
+ if (this.state === "closed" || this.state === "failed" || this.watch.state !== "active") return;
23736
+ this.problem = null;
23737
+ this.publish("current");
23738
+ this.resolveReady();
23739
+ }
23740
+ retry(why, again) {
23741
+ this.problem = why?.toProblem() ?? null;
23742
+ this.publish(this.loaded ? "stale" : "loading");
23743
+ const delay = this.delay;
23744
+ this.delay = Math.min(delay * 2, RETRY_MAX_MS);
23745
+ clearTimeout(this.timer);
23746
+ this.again = again;
23747
+ this.timer = setTimeout(() => this.resume(), delay);
23748
+ }
23749
+ /** Do now what a waiting retry would do; without one, work. */
23750
+ resume() {
23751
+ clearTimeout(this.timer);
23752
+ this.timer = void 0;
23753
+ const again = this.again ?? (() => void this.work());
23754
+ this.again = void 0;
23755
+ if (this.state !== "closed") again();
23756
+ }
23757
+ cancelRetry() {
23758
+ clearTimeout(this.timer);
23759
+ this.timer = void 0;
23760
+ this.again = void 0;
23761
+ }
23762
+ fail(e) {
23763
+ this.cancelRetry();
23764
+ this.problem = problemOf(e);
23765
+ this.rejectReady(e instanceof MdbaseError ? e : new MdbaseError(this.problem));
23766
+ this.publish("failed");
23767
+ }
23768
+ /** One complete read. False when the replica could not answer completely. */
23769
+ async load() {
23770
+ const signal = this.lifetime.signal;
23771
+ this.dirty = false;
23772
+ this.queued.clear();
23773
+ this.publish(this.loaded ? "stale" : "loading");
23774
+ const next = /* @__PURE__ */ new Map();
23775
+ let complete2 = true;
23776
+ try {
23777
+ const query = { ...this.types ? { types: [...this.types] } : {}, limit: PAGE };
23778
+ for await (const page of this.client.pages(query, { include: this.include, signal })) {
23779
+ for (const r of page.records) next.set(r.id, r);
23780
+ complete2 &&= page.complete;
23781
+ if (!this.loaded) this.apply(page.records.map((r) => ({ record: r })), this.state);
23782
+ }
23783
+ } catch (e) {
23784
+ this.dirty = true;
23785
+ throw e;
23786
+ }
23787
+ const changes = [...next.values()].map((record3) => ({ record: record3 }));
23788
+ const removed = [...this.byId.keys()].filter((id4) => !next.has(id4)).map((id4) => ({ id: id4 }));
23789
+ this.loaded ||= complete2;
23790
+ if (!complete2) this.dirty = true;
23791
+ this.apply([...changes, ...removed], this.state);
23792
+ return complete2;
23793
+ }
23794
+ async reread() {
23795
+ const signal = this.lifetime.signal;
23796
+ const ids = [...this.queued];
23797
+ this.queued.clear();
23798
+ const read = new Array(ids.length);
23799
+ let next = 0;
23800
+ try {
23801
+ await Promise.all(Array.from({ length: Math.min(REREAD_CONCURRENCY, ids.length) }, async () => {
23802
+ while (next < ids.length) {
23803
+ const i = next++;
23804
+ read[i] = await this.client.find(ids[i], { include: this.include, signal });
23805
+ }
23806
+ }));
23807
+ } catch (e) {
23808
+ for (const id4 of ids) this.queued.add(id4);
23809
+ throw e;
23810
+ }
23811
+ this.apply(ids.map((id4, i) => read[i] && this.member(read[i].types) ? { record: read[i] } : { id: id4 }), this.state);
23812
+ }
23813
+ /** Put or remove records, then tell listeners what changed. */
23814
+ apply(entries, state) {
23815
+ const changes = [];
23816
+ for (const entry2 of entries) {
23817
+ const id4 = "record" in entry2 ? entry2.record.id : entry2.id;
23818
+ const previous = this.byId.get(id4);
23819
+ if ("record" in entry2) {
23820
+ this.byId.set(id4, entry2.record);
23821
+ if (!previous) changes.push({ kind: "put", record: entry2.record });
23822
+ else if (!unchanged(previous, entry2.record)) changes.push({ kind: "put", record: entry2.record, previous });
23823
+ } else if (previous) {
23824
+ this.byId.delete(id4);
23825
+ changes.push({ kind: "remove", previous });
23826
+ }
23827
+ }
23828
+ this.touched ||= entries.length > 0;
23829
+ this.publish(state, changes);
23830
+ }
23831
+ publish(state, changes = []) {
23832
+ if (this.state === "closed") return;
23833
+ const problem4 = state === "current" ? null : this.problem;
23834
+ if (!this.touched && state === this.state && problem4 === this.view.problem) return;
23835
+ this.state = state;
23836
+ this.view = Object.freeze({ records: this.touched ? Object.freeze([...this.byId.values()]) : this.view.records, state, problem: problem4 });
23837
+ this.touched = false;
23838
+ for (const listener of [...this.listeners]) {
23839
+ try {
23840
+ listener(changes);
23841
+ } catch {
23842
+ }
23843
+ }
23844
+ }
23845
+ };
23846
+
23403
23847
  // src/presence.ts
23404
23848
  var MAX_PRESENCE_STATE = 4096;
23405
23849
  var MIN_INTERVAL_MS = 100;
@@ -23421,7 +23865,7 @@ var PresenceApi = class {
23421
23865
  this.wired.add(s);
23422
23866
  s.onPush("presence", (p) => {
23423
23867
  try {
23424
- const v = presencePush.dec(p);
23868
+ const v = decodePlain(presencePush, p);
23425
23869
  for (const fn of this.watchers.get(v.record) ?? []) fn(v.peers);
23426
23870
  } catch {
23427
23871
  }
@@ -23436,7 +23880,7 @@ var PresenceApi = class {
23436
23880
  check(state) {
23437
23881
  const n = JSON.stringify(state, (_k, v) => typeof v === "bigint" ? v.toString() : v instanceof Map ? [...v] : v).length;
23438
23882
  if (n > MAX_PRESENCE_STATE) {
23439
- throw mdbaseError("too_large", "presence state over 4 KiB", { details: /* @__PURE__ */ new Map([["limit", MAX_PRESENCE_STATE]]) });
23883
+ throw mdbaseError("too_large", "presence state over 4 KiB", { details: { limit: MAX_PRESENCE_STATE } });
23440
23884
  }
23441
23885
  }
23442
23886
  async join(record3, state) {
@@ -23600,8 +24044,8 @@ function conflictMessage(r, adoptable) {
23600
24044
  if (adoptable) return `${r.target} already exists with different content. Review it, then adopt it to let this pack manage it.`;
23601
24045
  return r.reason ? `${r.target} can't be changed: ${r.reason}.` : `${r.target} can't be changed by this pack.`;
23602
24046
  }
23603
- function toPlan(raw, pack, options) {
23604
- const a = obj(toPlain(raw));
24047
+ function toPlan(assessment, pack, options) {
24048
+ const a = obj(assessment);
23605
24049
  const resources = (Array.isArray(a.resources) ? a.resources : []).map(resource);
23606
24050
  const summary = Object.fromEntries(ACTIONS.map((k) => [k, resources.filter((r) => r.action === k).map((r) => r.target)]));
23607
24051
  const adoptable = {};
@@ -23705,7 +24149,7 @@ async function applyTypePack(client, plan, o = {}) {
23705
24149
  const writes = r.writes ?? [];
23706
24150
  if (!writes.length) return { outcome: "already_current", receipt: applied.desired };
23707
24151
  const ops = writes.map((w) => w.doc === void 0 ? { kind: "resource_delete", path: w.path, ...opt("baseRevision", w.baseRevision) } : { kind: "resource_put", path: w.path, doc: w.doc, ...opt("baseRevision", w.baseRevision), ...w.mustNotExist ? { mustNotExist: true } : {} });
23708
- const write = (await client.submit(ops, { ...o, allowPartial: false }))[0];
24152
+ const write = await client.submit(ops, o);
23709
24153
  const receipt3 = write.receipt;
23710
24154
  if (receipt3.state === "rejected" || receipt3.state === "unknown") {
23711
24155
  throw new MdbaseError(receipt3.problem ?? (receipt3.state === "unknown" ? { code: "outcome_unknown", recovery: "resolve_outcome", message: "The type pack install outcome is unknown." } : { code: "internal", recovery: "contact_support", message: "The type pack install was rejected." }), { mutationId: receipt3.mutation });
@@ -23837,8 +24281,8 @@ var WriteLedger = class {
23837
24281
  }
23838
24282
  }
23839
24283
  /** @internal Persist intent BEFORE the write is submitted. */
23840
- begin(mutationIds, ops) {
23841
- return Promise.all(mutationIds.map((id4, i) => this.set(entry(id4, targets(mutationIds.length === 1 ? ops : [ops[i]]), "pending"))));
24284
+ begin(mutationId, ops) {
24285
+ return this.set(entry(mutationId, targets(ops), "pending"));
23842
24286
  }
23843
24287
  /** @internal Apply a receipt from any source. */
23844
24288
  observe(r) {
@@ -23890,10 +24334,7 @@ var WriteLedger = class {
23890
24334
  }
23891
24335
  if (added) this.changed();
23892
24336
  }
23893
- /** @internal A submit call failed: ask the replica whether it captured these. */
23894
- settleAll(ids) {
23895
- return Promise.all(ids.map((id4) => this.settle(id4)));
23896
- }
24337
+ /** @internal A submit call failed: ask the replica whether it captured the write. */
23897
24338
  async settle(id4) {
23898
24339
  try {
23899
24340
  this.observe(await this.native.receipt(id4));
@@ -23927,6 +24368,7 @@ var WriteLedger = class {
23927
24368
  };
23928
24369
 
23929
24370
  // src/client.ts
24371
+ var CHANGES_PAGE = 1e3;
23930
24372
  function snapshotQueryValue(value2) {
23931
24373
  if (value2 instanceof Float64) return new Float64(value2.value);
23932
24374
  if (value2 instanceof Date) return new Date(value2);
@@ -24002,6 +24444,8 @@ var Write = class {
24002
24444
  * is a final non-publication, not success. Without files, settles at confirmation.
24003
24445
  * Rejects rejected/unknown outcomes; not a native custody/durable ACK gate. */
24004
24446
  published;
24447
+ /** The record a single-record write targets (create, update, replace, rename, delete). */
24448
+ recordId;
24005
24449
  get mutationId() {
24006
24450
  return this.receipt.mutation;
24007
24451
  }
@@ -24090,8 +24534,11 @@ var LiveQuery = class {
24090
24534
  fn(this, null);
24091
24535
  return () => this.listeners.delete(fn);
24092
24536
  }
24093
- /** Change the query (for example a larger `limit` window). Re-subscribes. */
24094
- async setQuery(query, include3 = this.include) {
24537
+ /** Change the query (for example a larger `limit` window). Re-subscribes.
24538
+ * `o.include` replaces what each record carries; without it the current
24539
+ * include is kept. */
24540
+ async setQuery(query, o = {}) {
24541
+ const { include: include3 = this.include } = o;
24095
24542
  this.query = query;
24096
24543
  this.include = include3;
24097
24544
  this.result.markStale();
@@ -24402,9 +24849,9 @@ var MdbaseClient = class _MdbaseClient {
24402
24849
  }
24403
24850
  /** Recheck session identity after waiting for catch-up (SDK-internal use). */
24404
24851
  async readyForRead(signal, immediate = false) {
24405
- if (!this.fenceReads) return immediate ? this.currentSession() : this.ready(signal);
24852
+ if (!this.fenceReads) return immediate ? this.currentSession() : this.ready({ signal });
24406
24853
  for (; ; ) {
24407
- const s = immediate ? this.currentSession() : await this.ready(signal);
24854
+ const s = immediate ? this.currentSession() : await this.ready({ signal });
24408
24855
  await this.readFence(signal);
24409
24856
  if (s === this.session && !s.closed && this.readFencedAt === null) return s;
24410
24857
  if (immediate) this.currentSession();
@@ -24433,8 +24880,9 @@ var MdbaseClient = class _MdbaseClient {
24433
24880
  }
24434
24881
  return this.session;
24435
24882
  }
24436
- /** @internal Wait until a session is open (or the client closes). */
24437
- async ready(signal) {
24883
+ /** @internal Wait until a session is open (or the client closes); `o.signal` cancels the wait. */
24884
+ async ready(o = {}) {
24885
+ const signal = o.signal;
24438
24886
  for (; ; ) {
24439
24887
  if (this.linkState === "closed") throw this.linkError ?? mdbaseError("unavailable", "client closed");
24440
24888
  if (this.session && !this.session.closed) return this.session;
@@ -24445,17 +24893,16 @@ var MdbaseClient = class _MdbaseClient {
24445
24893
  });
24446
24894
  }
24447
24895
  }
24448
- /**
24449
- * Advanced: run a request on the current session; on a dropped link, wait for the
24450
- * reconnect and retry when `retry` (idempotent requests only).
24451
- */
24452
24896
  async call(method, p, o = {}) {
24453
24897
  const codec = o.codec;
24454
24898
  const read = this.fenceReads && READ_METHODS.has(method);
24455
24899
  for (; ; ) {
24456
- const s = read ? await this.readyForRead(o.signal, !o.retry) : o.retry ? await this.ready(o.signal) : this.currentSession();
24900
+ const s = read ? await this.readyForRead(o.signal, !o.retry) : o.retry ? await this.ready({ signal: o.signal }) : this.currentSession();
24457
24901
  try {
24458
- const r = await s.request(method, p, { ...o.signal ? { signal: o.signal } : {}, ...codec ? { codec } : {} });
24902
+ const r = await s.request(method, p, {
24903
+ ...o.signal ? { signal: o.signal } : {},
24904
+ ...codec ? { codec: plainAnswer(codec) } : {}
24905
+ });
24459
24906
  if (read && (s !== this.session || s.closed || this.closing)) {
24460
24907
  if (o.retry && !this.closing) continue;
24461
24908
  throw mdbaseError("unavailable", "the session changed during the read", { reason: "reconnecting" });
@@ -24498,7 +24945,7 @@ var MdbaseClient = class _MdbaseClient {
24498
24945
  if (this.fenceReads && this.session !== s) return;
24499
24946
  let u;
24500
24947
  try {
24501
- u = queryUpdate.dec(p);
24948
+ u = decodePlain(queryUpdate, p);
24502
24949
  } catch {
24503
24950
  return;
24504
24951
  }
@@ -24514,7 +24961,7 @@ var MdbaseClient = class _MdbaseClient {
24514
24961
  });
24515
24962
  s.onPush("receipt", (p) => {
24516
24963
  try {
24517
- const r = receipt.dec(p);
24964
+ const r = decodePlain(receipt, p);
24518
24965
  if (this.session === s) this.noteReceipt(r);
24519
24966
  const w = this.writes.get(r.mutation);
24520
24967
  if (w) {
@@ -24543,7 +24990,7 @@ var MdbaseClient = class _MdbaseClient {
24543
24990
  });
24544
24991
  s.onPush("conflicts", (p) => {
24545
24992
  try {
24546
- this.emitConflicts(list(conflictEntry).dec(p));
24993
+ this.emitConflicts(decodePlain(list(conflictEntry), p));
24547
24994
  } catch {
24548
24995
  }
24549
24996
  });
@@ -24687,13 +25134,14 @@ var MdbaseClient = class _MdbaseClient {
24687
25134
  * revalidate the authenticated session and all readiness gates after any await.
24688
25135
  * Missing chain or any error means remain hosted; never substitute asOf or the
24689
25136
  * current head/generations. Decoding does not authenticate a witness or switch.
25137
+ * `o.signal` cancels the read.
24690
25138
  */
24691
- async appliedPrefix(seq2, signal) {
25139
+ async appliedPrefix(seq2, o = {}) {
24692
25140
  const p = appliedPrefixParams.enc({ seq: seq2 });
24693
25141
  const r = await this.call("applied_prefix", p, {
24694
25142
  codec: appliedPrefix,
24695
25143
  retry: false,
24696
- ...signal ? { signal } : {}
25144
+ ...o.signal ? { signal: o.signal } : {}
24697
25145
  });
24698
25146
  if (r.seq !== seq2 || r.chain !== void 0 && (seq2 === 0 || r.appliedThrough < seq2)) {
24699
25147
  throw mdbaseError("invalid_request", "applied_prefix: inconsistent historical proof", "prefix_response");
@@ -24725,9 +25173,9 @@ var MdbaseClient = class _MdbaseClient {
24725
25173
  * definition and schema and each contract's schemas, bounded by the replica
24726
25174
  * (`too_large` when over budget; read them with `resources.get` instead).
24727
25175
  * A producer that cannot describe definitions fails `upgrade_required`.
25176
+ * `o.signal` cancels the read.
24728
25177
  */
24729
- async describe(options = {}) {
24730
- const o = options instanceof AbortSignal ? { signal: options } : options;
25178
+ async describe(o = {}) {
24731
25179
  const result2 = await this.call("describe", o.definitions ? params([[0, true]]) : null, {
24732
25180
  codec: describeResult,
24733
25181
  retry: true,
@@ -24762,8 +25210,9 @@ var MdbaseClient = class _MdbaseClient {
24762
25210
  * Core's temporal typing for top-level fields under a query's exact `types` OR list
24763
25211
  * (`date` / `date_time` only when every type agrees; otherwise `none`). The answer is
24764
25212
  * bound to a catalog generation; nested paths are `none`. The SDK never infers typing.
25213
+ * `o.signal` cancels the read.
24765
25214
  */
24766
- describeTyping(types, paths, signal) {
25215
+ describeTyping(types, paths, o = {}) {
24767
25216
  const strings = (a, max) => Array.isArray(a) && a.length <= max && a.every((s) => typeof s === "string" && s.length > 0 && s.length <= 1024);
24768
25217
  if (!strings(types, DESCRIBE_TYPING_MAX_TYPES) || !strings(paths, DESCRIBE_TYPING_MAX_PATHS)) {
24769
25218
  return Promise.reject(mdbaseError("invalid_request", "describe_typing: at most 64 types and 256 non-empty paths", "typing_bounds"));
@@ -24771,7 +25220,7 @@ var MdbaseClient = class _MdbaseClient {
24771
25220
  return this.call("describe_typing", params([[0, [...types]], [1, [...paths]]]), {
24772
25221
  codec: describeTypingResult,
24773
25222
  retry: true,
24774
- ...signal ? { signal } : {}
25223
+ ...o.signal ? { signal: o.signal } : {}
24775
25224
  }).then((r) => {
24776
25225
  if (r.fields.length !== paths.length || r.fields.some((f, i) => f.path !== paths[i])) {
24777
25226
  throw mdbaseError("internal", "describe_typing answered for different paths", "invalid_typing_response");
@@ -24779,15 +25228,16 @@ var MdbaseClient = class _MdbaseClient {
24779
25228
  return r;
24780
25229
  });
24781
25230
  }
24782
- /** One record by ID or path. Throws `not_found`. */
24783
- get(ref, include3, signal) {
25231
+ /** One record by ID or path. Throws `not_found`. `o.include` adds the body
25232
+ * and other parts to the record; `o.signal` cancels the read. */
25233
+ get(ref, o = {}) {
24784
25234
  return this.call(
24785
25235
  "get",
24786
25236
  params([
24787
25237
  [0, refValue(ref)],
24788
- [1, includeValue(include3)]
25238
+ [1, includeValue(o.include)]
24789
25239
  ]),
24790
- { codec: recordView, retry: true, ...signal ? { signal } : {} }
25240
+ { codec: recordView, retry: true, ...o.signal ? { signal: o.signal } : {} }
24791
25241
  );
24792
25242
  }
24793
25243
  /**
@@ -24797,15 +25247,16 @@ var MdbaseClient = class _MdbaseClient {
24797
25247
  * `invalid_request`/`data_contract_ambiguous` (select `type`; details: the types),
24798
25248
  * `invalid_record`/`data_contract_record_invalid` (with issues), and
24799
25249
  * `upgrade_required`/`contract_records_unsupported` from an older replica.
25250
+ * `o.signal` cancels the read.
24800
25251
  */
24801
- async getContract(ref, contract, signal) {
25252
+ async getContract(ref, contract, o = {}) {
24802
25253
  const r = await this.contractCall("get_contract_v1", params([
24803
25254
  [0, 1],
24804
25255
  [1, refValue(ref)],
24805
25256
  [2, contract.id],
24806
25257
  [3, contract.version],
24807
25258
  [4, contract.type]
24808
- ]), contractRecordWire, signal);
25259
+ ]), (answer) => decodePlain(contractRecordWire, answer), o.signal);
24809
25260
  if (r.version !== 1) throw mdbaseError("upgrade_required", "unsupported contract record", "contract_records_unsupported");
24810
25261
  return {
24811
25262
  id: r.id,
@@ -24826,27 +25277,38 @@ var MdbaseClient = class _MdbaseClient {
24826
25277
  [5, fields3],
24827
25278
  [6, unset?.length ? unset : void 0],
24828
25279
  [7, promote ? true : void 0]
24829
- ]), contractWritePlan, signal);
25280
+ // Exact: the plan's patch and base go back in an op unchanged.
25281
+ ]), contractWritePlan.dec, signal);
24830
25282
  if (plan.version !== 1) throw mdbaseError("upgrade_required", "unsupported contract write plan", "contract_records_unsupported");
24831
25283
  return plan;
24832
25284
  }
24833
- contractCall(method, p, codec, signal) {
24834
- return this.call(method, p, { codec, retry: true, ...signal ? { signal } : {} }).catch((e) => {
25285
+ async contractCall(method, p, decode3, signal) {
25286
+ let answer;
25287
+ try {
25288
+ answer = await this.call(method, p, { retry: true, ...signal ? { signal } : {} });
25289
+ } catch (e) {
24835
25290
  if (isMdbaseError(e, "invalid_request") && e.reason === "unknown_method") {
24836
25291
  throw mdbaseError("upgrade_required", "this replica does not serve contract-scoped records", "contract_records_unsupported");
24837
25292
  }
24838
25293
  throw e;
24839
- });
25294
+ }
25295
+ try {
25296
+ return decode3(answer);
25297
+ } catch (e) {
25298
+ throw schemaToError(e, `${method} result`);
25299
+ }
24840
25300
  }
24841
25301
  /** Bounded ordered ordinary gets. Missing/refused reads fail the batch;
24842
- * duplicate slots and the original signal are retained, not a snapshot. */
24843
- readMany(refs, include3, signal, options = {}) {
24844
- return readMany(this, refs, include3, signal, options);
24845
- }
24846
- /** One record, or `null` when there is none. */
24847
- async find(ref, include3, signal) {
25302
+ * duplicate slots and the original signal are retained, not a snapshot.
25303
+ * `o.include` and `o.signal` apply to every get; `o.concurrency` bounds the
25304
+ * gets in flight. */
25305
+ readMany(refs, o = {}) {
25306
+ return readMany(this, refs, o);
25307
+ }
25308
+ /** One record, or `null` when there is none. `o` is as for {@link get}. */
25309
+ async find(ref, o = {}) {
24848
25310
  try {
24849
- return await this.get(ref, include3, signal);
25311
+ return await this.get(ref, o);
24850
25312
  } catch (e) {
24851
25313
  if (isMdbaseError(e, "not_found")) return null;
24852
25314
  throw e;
@@ -24855,19 +25317,21 @@ var MdbaseClient = class _MdbaseClient {
24855
25317
  /**
24856
25318
  * One page of a query, evaluated by the replica (body predicates and links
24857
25319
  * included, §4). Pass `result.cursor` back as `query.cursor` for the next.
24858
- * `opts.contract` is not supported by the live replica dispatch. Supplying it
25320
+ * `o.include` adds the body and other parts to each record; `o.signal`
25321
+ * cancels the read.
25322
+ * `o.contract` is not supported by the live replica dispatch. Supplying it
24859
25323
  * returns `invalid_request` with reason `unknown_param`; no contract filter
24860
25324
  * is applied. The option remains encoded unchanged for API compatibility.
24861
25325
  */
24862
- query(query, include3, signal, opts = {}) {
25326
+ query(query, o = {}) {
24863
25327
  return this.call(
24864
25328
  "query",
24865
25329
  params([
24866
25330
  [0, toValue(query)],
24867
- [1, includeValue(include3)],
24868
- [2, opts.contract]
25331
+ [1, includeValue(o.include)],
25332
+ [2, o.contract]
24869
25333
  ]),
24870
- { codec: queryResult, retry: true, ...signal ? { signal } : {} }
25334
+ { codec: queryResult, retry: true, ...o.signal ? { signal: o.signal } : {} }
24871
25335
  );
24872
25336
  }
24873
25337
  /** Canonical contract projections with validation issues and ordinary cursor
@@ -24949,7 +25413,8 @@ var MdbaseClient = class _MdbaseClient {
24949
25413
  }
24950
25414
  /** Definitions: `mdbase.yaml`, type files, contract files (§4.1). */
24951
25415
  resources = {
24952
- get: (path, signal) => this.call("get_resource", params([[0, path]]), { codec: resourceView, retry: true, ...signal ? { signal } : {} }),
25416
+ /** One definition by path. `o.signal` cancels the read. */
25417
+ get: (path, o = {}) => this.call("get_resource", params([[0, path]]), { codec: resourceView, retry: true, ...o.signal ? { signal: o.signal } : {} }),
24953
25418
  /** One bounded resource inventory page. Text defaults to false; limit defaults
24954
25419
  * to 64 (maximum 128). Preserve folder/text/limit on continuation. Collect all
24955
25420
  * pages before assessing a complete snapshot; stale/expired cursors require
@@ -24972,18 +25437,18 @@ var MdbaseClient = class _MdbaseClient {
24972
25437
  if (o.baseRevision && o.mustNotExist) {
24973
25438
  return Promise.reject(mdbaseError("invalid_request", "baseRevision and mustNotExist are exclusive"));
24974
25439
  }
24975
- return this.one(
24976
- {
25440
+ return this.submit(
25441
+ [{
24977
25442
  kind: "resource_put",
24978
25443
  path,
24979
25444
  doc,
24980
25445
  ...o.baseRevision ? { baseRevision: o.baseRevision } : {},
24981
25446
  ...o.mustNotExist ? { mustNotExist: true } : {}
24982
- },
25447
+ }],
24983
25448
  o
24984
25449
  );
24985
25450
  },
24986
- delete: (path, o = {}) => this.one({ kind: "resource_delete", path, ...o.baseRevision ? { baseRevision: o.baseRevision } : {} }, o)
25451
+ delete: (path, o = {}) => this.submit([{ kind: "resource_delete", path, ...o.baseRevision ? { baseRevision: o.baseRevision } : {} }], o)
24987
25452
  };
24988
25453
  /** Type packs: `plan` (writes nothing), review, then `apply(plan)` as one
24989
25454
  * guarded all-or-nothing mutation (needs `definitions.manage`). */
@@ -25001,19 +25466,24 @@ var MdbaseClient = class _MdbaseClient {
25001
25466
  updateSource: (seen, document, options) => updateViewSource(this, seen, document, options),
25002
25467
  getSourceRecord: (source, options = {}) => readViewSourceRecord(this, source, options),
25003
25468
  /** `mdbase.view` sources (spec 12 `list_views` shape), resolved over served
25004
- * contract queries: the native runtime has no `list_views` RPC. */
25005
- list: (folder, signal) => listSavedViews(this, folder, signal),
25469
+ * contract queries: the native runtime has no `list_views` RPC. `o.folder`
25470
+ * keeps the sources under one folder; `o.signal` cancels the read. */
25471
+ list: (o = {}) => listSavedViews(this, o),
25006
25472
  /** Spec 11 named-view resolution, executed as one ordinary native query. */
25007
25473
  execute: (source, view, o = {}) => executeSavedView(this, source, view, o),
25008
- readSource: (source, signal) => readSavedViewSource(this, source, signal)
25474
+ /** The current source document of one `mdbase.view` record. `o.signal`
25475
+ * cancels the read. */
25476
+ readSource: (source, o = {}) => readSavedViewSource(this, source, o)
25009
25477
  };
25010
25478
  /**
25011
25479
  * Pending mutations of this session's owner (its grant, or the device), oldest
25012
25480
  * first (§6): a new session after a reload sees writes made before it. Follow
25013
25481
  * each with `awaitReceipt`, or keep the `mutationId` you chose and call
25014
- * `receipt(id)` / `awaitReceipt(id)`. Pages through everything.
25482
+ * `receipt(id)` / `awaitReceipt(id)`. Pages through everything; `o.signal`
25483
+ * cancels the read.
25015
25484
  */
25016
- async pendingWrites(signal) {
25485
+ async pendingWrites(o = {}) {
25486
+ const signal = o.signal;
25017
25487
  const out = [];
25018
25488
  let after;
25019
25489
  for (; ; ) {
@@ -25039,27 +25509,30 @@ var MdbaseClient = class _MdbaseClient {
25039
25509
  return this.preflight({ kind: "delete", id: refId(target2) });
25040
25510
  }
25041
25511
  async preflight(op2) {
25042
- const [w] = await this.submit([op2], { dryRun: true });
25043
- const r = w.receipt;
25512
+ const r = (await this.submit([op2], { dryRun: true })).receipt;
25044
25513
  if (r.state === "rejected") throw new MdbaseError(r.problem);
25045
25514
  return r.preflight ?? { rewrites: [], broken: [] };
25046
25515
  }
25047
- /** Every page of a query. Cursor resets require explicit caller clearing;
25048
- * otherwise cursor_expired/cursor_stale is thrown unchanged. */
25049
- async *pages(query, include3, signal, options = {}) {
25516
+ /** Every page of a query. `o.include` and `o.signal` apply to every page.
25517
+ * Cursor resets require explicit caller clearing through `o.onReset`;
25518
+ * otherwise cursor_expired/cursor_stale is thrown unchanged. The query and
25519
+ * `o` are captured when iteration starts. */
25520
+ async *pages(query, o = {}) {
25521
+ const { include: include3, signal, onReset } = o;
25050
25522
  const original = snapshotQueryValue(query);
25051
25523
  const originalInclude = include3 ? { ...include3 } : void 0;
25524
+ const read = { ...originalInclude ? { include: originalInclude } : {}, ...signal ? { signal } : {} };
25052
25525
  let cursor = original.cursor, restarted = false, pagesYielded = 0;
25053
25526
  delete original.cursor;
25054
25527
  for (; ; ) {
25055
25528
  signal?.throwIfAborted();
25056
25529
  let page;
25057
25530
  try {
25058
- page = await this.query(cursor !== void 0 ? { ...original, cursor } : { ...original }, originalInclude, signal);
25531
+ page = await this.query(cursor !== void 0 ? { ...original, cursor } : { ...original }, read);
25059
25532
  } catch (error4) {
25060
- if (!options.onReset || restarted || !isMdbaseError(error4, "invalid_request") || error4.recovery !== "fix_request" || error4.reason !== "cursor_expired" && error4.reason !== "cursor_stale") throw error4;
25533
+ if (!onReset || restarted || !isMdbaseError(error4, "invalid_request") || error4.recovery !== "fix_request" || error4.reason !== "cursor_expired" && error4.reason !== "cursor_stale") throw error4;
25061
25534
  signal?.throwIfAborted();
25062
- await options.onReset({ reason: error4.reason, error: error4, pagesYielded, ...signal ? { signal } : {} });
25535
+ await onReset({ reason: error4.reason, error: error4, pagesYielded, ...signal ? { signal } : {} });
25063
25536
  signal?.throwIfAborted();
25064
25537
  restarted = true;
25065
25538
  cursor = void 0;
@@ -25076,16 +25549,29 @@ var MdbaseClient = class _MdbaseClient {
25076
25549
  cursor = page.cursor;
25077
25550
  }
25078
25551
  }
25079
- /** Shared alias of pages(): whole native pages, no implicit cursor reset. */
25080
- queryPages(query, include3, signal, options = {}) {
25081
- return queryPages(this, query, include3, signal, options);
25552
+ /** Shared alias of pages(): whole native pages, no implicit cursor reset.
25553
+ * `o.include` and `o.signal` apply to every page; `o.onReset` opts in to one
25554
+ * first-page restart. */
25555
+ queryPages(query, o = {}) {
25556
+ return queryPages(this, query, o);
25082
25557
  }
25083
25558
  /**
25084
- * A live query. Subscribe for pushes; keep lists cheap with a `limit` window and no
25085
- * bodies, and widen the window with `setQuery`.
25559
+ * Every record of the chosen types (default: all), read completely and then
25560
+ * kept current: the set an app lists, searches and renders from. Close it
25561
+ * when done.
25086
25562
  */
25087
- live(query, include3) {
25088
- const l = new LiveQuery(this, query, include3);
25563
+ recordSet(options = {}) {
25564
+ return new RecordSet(this, options);
25565
+ }
25566
+ /**
25567
+ * A live query: one window of at most 1,000 records and 1 MiB, with the
25568
+ * replica's order and counts. Subscribe for pushes; keep lists cheap with a
25569
+ * `limit` window and no bodies, and widen the window with `setQuery`. For a
25570
+ * whole collection use `recordSet`. `o.include` adds the body and other
25571
+ * parts to each record.
25572
+ */
25573
+ live(query, o = {}) {
25574
+ const l = new LiveQuery(this, query, o.include);
25089
25575
  this.lives.add(l);
25090
25576
  void this._resubscribeLive(l, true);
25091
25577
  return l;
@@ -25136,25 +25622,28 @@ var MdbaseClient = class _MdbaseClient {
25136
25622
  });
25137
25623
  }
25138
25624
  }
25139
- /** One page of the change feed. A `reset: true` result means "re-read what you cache". */
25140
- changes(cursor, limit, signal) {
25625
+ /** One page of the change feed, from `o.cursor` (default: the start) and of
25626
+ * at most `o.limit` changes. A `reset: true` result means "re-read what you
25627
+ * cache". `o.signal` cancels the read. */
25628
+ changes(o = {}) {
25141
25629
  return this.call(
25142
25630
  "changes",
25143
25631
  params([
25144
- [0, cursor ?? null],
25145
- [1, limit]
25632
+ [0, o.cursor ?? null],
25633
+ [1, o.limit]
25146
25634
  ]),
25147
- { codec: changesResult, retry: true, ...signal ? { signal } : {} }
25635
+ { codec: changesResult, retry: true, ...o.signal ? { signal: o.signal } : {} }
25148
25636
  );
25149
25637
  }
25150
25638
  /**
25151
- * Follow the change feed from `cursor`. `onChanges` gets every batch; `reset: true`
25152
- * means the app must re-read what it caches. Survives reconnects.
25639
+ * Follow the change feed from `o.cursor` (default: the start). `onChanges` gets
25640
+ * every batch; `reset: true` means the app must re-read what it caches. Survives
25641
+ * reconnects.
25153
25642
  * `ready` confirms the first watch ACK, not a complete/current collection cache.
25154
25643
  * After reconnect, observe `state`; an already-resolved promise is not freshness.
25155
25644
  */
25156
- watchChanges(cursor, onChanges) {
25157
- let last = cursor, stopped = false, epoch = 0;
25645
+ watchChanges(onChanges, o = {}) {
25646
+ let last = o.cursor, stopped = false, epoch = 0;
25158
25647
  let state = "starting", error4 = null;
25159
25648
  let active = null, controller = null;
25160
25649
  let offPush = null, offClose = null;
@@ -25275,10 +25764,16 @@ var MdbaseClient = class _MdbaseClient {
25275
25764
  publish("starting");
25276
25765
  if (!current2()) return;
25277
25766
  try {
25278
- const first = await s.request("changes", params([[0, last ?? null], [2, true]]), { codec: changesResult, signal });
25279
- if (!current2()) return;
25280
- last = first.cursor;
25281
- if (first.changes.length || first.reset) deliver(first);
25767
+ let page = await s.request("changes", params([[0, last ?? null], [1, CHANGES_PAGE], [2, true]]), { codec: changesResult, signal });
25768
+ for (; ; ) {
25769
+ if (!current2()) return;
25770
+ last = page.cursor;
25771
+ if (page.changes.length || page.reset) deliver(page);
25772
+ if (!current2()) return;
25773
+ if (page.changes.length < CHANGES_PAGE) break;
25774
+ clearEarly();
25775
+ page = await s.request("changes", params([[0, last], [1, CHANGES_PAGE]]), { codec: changesResult, signal });
25776
+ }
25282
25777
  while (early.length && current2()) deliver(early.shift());
25283
25778
  clearEarly();
25284
25779
  initial = false;
@@ -25307,13 +25802,15 @@ var MdbaseClient = class _MdbaseClient {
25307
25802
  Object.defineProperties(watch, { state: { get: () => state }, error: { get: () => error4 } });
25308
25803
  return Object.freeze(watch);
25309
25804
  }
25310
- /** Validate these records, or every record. Every record is validated a
25805
+ /** Validate `o.refs`, or every record without them. Every record is validated a
25311
25806
  * page at a time when the replica grants `validate-page-v1`; each page is an
25312
25807
  * independent READ, so records changed meanwhile may be missed or repeated.
25313
- * Older replicas validate every record in one bounded request. */
25314
- async validate(refs, signal) {
25808
+ * Older replicas validate every record in one bounded request. `o.signal`
25809
+ * cancels the read. */
25810
+ async validate(o = {}) {
25811
+ const signal = o.signal;
25315
25812
  signal?.throwIfAborted();
25316
- const { targets: targets2, expected } = captureValidation(refs);
25813
+ const { targets: targets2, expected } = captureValidation(o.refs);
25317
25814
  const call2 = (p) => this.call("validate", p, {
25318
25815
  codec: recordValidations,
25319
25816
  retry: true,
@@ -25335,8 +25832,10 @@ var MdbaseClient = class _MdbaseClient {
25335
25832
  }
25336
25833
  }
25337
25834
  /** Independent native app-host Bases READ, exact original held session.
25338
- * Unsupported transports refuse: no generic execute_view/data fallback. */
25339
- async executeAppBases(request3, signal) {
25835
+ * Unsupported transports refuse: no generic execute_view/data fallback.
25836
+ * `o.signal` cancels the read. */
25837
+ async executeAppBases(request3, o = {}) {
25838
+ const signal = o.signal;
25340
25839
  const window = request3.window === void 0 ? null : { ...request3.window };
25341
25840
  const bytes10 = encodeAppBasesRequest({ ...request3, ...window === null ? {} : { window } });
25342
25841
  const session = await this.readyForRead(signal);
@@ -25352,11 +25851,13 @@ var MdbaseClient = class _MdbaseClient {
25352
25851
  * `executeViewPages`). Each page is an independent READ; `changedSinceFirst`
25353
25852
  * marks pages taken after the collection changed. */
25354
25853
  executeAppBasesPages(request3, options = {}) {
25355
- return appBasesPages((r, signal) => this.executeAppBases(r, signal), request3, options);
25854
+ return appBasesPages((r, signal) => this.executeAppBases(r, signal ? { signal } : {}), request3, options);
25356
25855
  }
25357
25856
  /** One bounded native discovery page. Empty views do not mean EOF when a
25358
- * continuation is present. Supplied handles never silently restart/retry. */
25359
- async listAppBasesViews(request3, signal) {
25857
+ * continuation is present. Supplied handles never silently restart/retry.
25858
+ * `o.signal` cancels the read. */
25859
+ async listAppBasesViews(request3, o = {}) {
25860
+ const signal = o.signal;
25360
25861
  const limit = request3.limit, bytes10 = encodeAppBasesDiscoveryRequest(request3);
25361
25862
  const session = await this.readyForRead(signal);
25362
25863
  const reply = await session.readAppBasesDiscovery("list-views", bytes10, signal);
@@ -25370,8 +25871,10 @@ var MdbaseClient = class _MdbaseClient {
25370
25871
  }
25371
25872
  }
25372
25873
  /** Exact current source for one native UUID/SHA/original ordinal, never path
25373
- * aliases, inferred catalog entries, generic RPC or cached document fallback. */
25374
- async readAppBasesViewSource(request3, signal) {
25874
+ * aliases, inferred catalog entries, generic RPC or cached document fallback.
25875
+ * `o.signal` cancels the read. */
25876
+ async readAppBasesViewSource(request3, o = {}) {
25877
+ const signal = o.signal;
25375
25878
  const original = { ...request3 }, bytes10 = encodeAppBasesSourceRequest(original);
25376
25879
  const session = await this.readyForRead(signal);
25377
25880
  const reply = await session.readAppBasesDiscovery("read-view-source", bytes10, signal);
@@ -25385,15 +25888,12 @@ var MdbaseClient = class _MdbaseClient {
25385
25888
  }
25386
25889
  }
25387
25890
  // ---------------------------------------------------------------- writes (§5, §6)
25388
- /** Submit operations as one mutation (or one per op with `allowPartial`). */
25891
+ /** Submit operations as one mutation: they apply together or not at all. */
25389
25892
  async submit(ops, o = {}) {
25390
25893
  if (this.hello.version.minor >= 3 && this.hello.grant.role === "viewer") throw mdbaseError("forbidden", "You have view access, so changes can't be saved.", "read_only");
25391
25894
  if (o.intent !== void 0 && o.mutationId === void 0) o = { ...o, mutationId: (await intentIds(this.collectionId, o.intent))[0] };
25392
- const p = { ops, mutationId: o.mutationId ?? uuidv7() };
25393
- if (o.allowPartial) {
25394
- p.allowPartial = true;
25395
- p.mutationIds = ops.map((_, i) => i === 0 ? p.mutationId : uuidv7());
25396
- }
25895
+ const mutationId = o.mutationId ?? uuidv7();
25896
+ const p = { ops, mutationId };
25397
25897
  if (o.conflictMode) p.conflictMode = o.conflictMode;
25398
25898
  if (o.timezone) p.timezone = o.timezone;
25399
25899
  if (o.dryRun) p.dryRun = true;
@@ -25402,25 +25902,26 @@ var MdbaseClient = class _MdbaseClient {
25402
25902
  if (o.validation) p.validation = o.validation;
25403
25903
  if (!o.dryRun) {
25404
25904
  this.startLedger();
25405
- await this.writeLedger.begin(p.mutationIds ?? [p.mutationId], ops);
25905
+ await this.writeLedger.begin(mutationId, ops);
25406
25906
  }
25407
- let receipts;
25907
+ let receipt3;
25408
25908
  try {
25409
- receipts = await this.call("submit", submitParams.enc(p), {
25909
+ const receipts = await this.call("submit", submitParams.enc(p), {
25410
25910
  codec: submitResult,
25411
25911
  retry: true,
25412
25912
  ...o.signal ? { signal: o.signal } : {}
25413
25913
  });
25914
+ if (receipts.length !== 1) throw mdbaseError("internal", "submit answered without exactly one receipt", "invalid_submit_response");
25915
+ receipt3 = receipts[0];
25414
25916
  } catch (e) {
25415
25917
  if (o.dryRun) throw e;
25416
- void this.writeLedger.settleAll(p.mutationIds ?? [p.mutationId]);
25417
- throw withMutation(e, "submit", p.mutationIds ? { mutationIds: p.mutationIds } : { mutationId: p.mutationId });
25918
+ void this.writeLedger.settle(mutationId);
25919
+ throw withMutation(e, "submit", { mutationId });
25418
25920
  }
25419
- return receipts.map((r) => o.dryRun ? new Write(r) : this._track(r));
25921
+ return o.dryRun ? new Write(receipt3) : this._track(receipt3);
25420
25922
  }
25421
- async one(op2, o) {
25422
- const [w] = await this.submit([op2], o);
25423
- return w;
25923
+ async record(op2, o) {
25924
+ return Object.assign(await this.submit([op2], o), { recordId: op2.id });
25424
25925
  }
25425
25926
  /** Create a record. The ID is minted here, so the app can use it before confirmation. */
25426
25927
  create(input, o = {}) {
@@ -25433,7 +25934,7 @@ var MdbaseClient = class _MdbaseClient {
25433
25934
  if (input.frontmatter !== void 0) op2.frontmatter = toFmMap(input.frontmatter);
25434
25935
  if (input.body !== void 0) op2.body = input.body;
25435
25936
  if (input.document !== void 0) op2.document = input.document;
25436
- return this.one(op2, o).then((write) => Object.assign(write, { recordId: op2.id }));
25937
+ return this.record(op2, o);
25437
25938
  }
25438
25939
  async createThroughContract(input, contract, o) {
25439
25940
  if (input.document !== void 0) throw mdbaseError("invalid_request", "a contract create takes frontmatter fields, not a document");
@@ -25445,7 +25946,7 @@ var MdbaseClient = class _MdbaseClient {
25445
25946
  const op2 = { kind: "create", id: input.id ?? uuidv7(), type: plan.type, frontmatter: plan.patch };
25446
25947
  if (input.path !== void 0) op2.path = input.path;
25447
25948
  if (input.body !== void 0) op2.body = input.body;
25448
- return Object.assign(await this.one(op2, o), { recordId: op2.id });
25949
+ return this.record(op2, o);
25449
25950
  }
25450
25951
  /**
25451
25952
  * Update a record by field-level intent. Pass the `RecordView` you edited from, and
@@ -25454,7 +25955,7 @@ var MdbaseClient = class _MdbaseClient {
25454
25955
  */
25455
25956
  update(target2, changes, o = {}) {
25456
25957
  if (changes.contract) return this.updateThroughContract(target2, changes, changes.contract, o);
25457
- return this.one(this.updateOp(target2, changes), o);
25958
+ return this.record(this.updateOp(target2, changes), o);
25458
25959
  }
25459
25960
  async updateThroughContract(target2, c, contract, o) {
25460
25961
  if (c.add || c.remove) {
@@ -25472,7 +25973,7 @@ var MdbaseClient = class _MdbaseClient {
25472
25973
  if (plan.base.length) op2.base = plan.base;
25473
25974
  if (c.updateRefs !== void 0) op2.updateRefs = c.updateRefs;
25474
25975
  if (c.ifRevision) op2.ifRevision = c.ifRevision;
25475
- return this.one(op2, o);
25976
+ return this.record(op2, o);
25476
25977
  }
25477
25978
  /** Build an `update` op (exposed for batching with `submit`). */
25478
25979
  updateOp(target2, c) {
@@ -25506,15 +26007,15 @@ var MdbaseClient = class _MdbaseClient {
25506
26007
  const base = [];
25507
26008
  const touched = [...op2.patch?.keys() ?? [], ...op2.unset ?? []];
25508
26009
  for (const k of new Set(touched)) {
25509
- const v = seen.frontmatter.get(k);
25510
- base.push(v === void 0 ? { key: k } : { key: k, observed: v });
26010
+ const v = Object.hasOwn(seen.frontmatter, k) ? seen.frontmatter[k] : void 0;
26011
+ base.push(v === void 0 ? { key: k } : { key: k, observed: toValue(v) });
25511
26012
  }
25512
26013
  if (base.length) op2.base = base;
25513
26014
  }
25514
26015
  if (seen && op2.patch) {
25515
26016
  for (const [k, v] of [...op2.patch]) {
25516
- const cur = seen.frontmatter.get(k);
25517
- if (cur !== void 0 && valueEquals(cur, v)) {
26017
+ const cur = Object.hasOwn(seen.frontmatter, k) ? seen.frontmatter[k] : void 0;
26018
+ if (cur !== void 0 && valueEquals(toValue(cur), v)) {
25518
26019
  op2.patch.delete(k);
25519
26020
  op2.base = op2.base?.filter((b) => b.key !== k);
25520
26021
  }
@@ -25531,7 +26032,7 @@ var MdbaseClient = class _MdbaseClient {
25531
26032
  if (!seen) throw mdbaseError("invalid_request", "replaceDocument needs the RecordView it was edited from");
25532
26033
  if (seen.document !== void 0) op2.base = { path: seen.path, doc: seen.document };
25533
26034
  if (o.ifRevision) op2.ifRevision = o.ifRevision;
25534
- return this.one(op2, o);
26035
+ return this.record(op2, o);
25535
26036
  }
25536
26037
  /**
25537
26038
  * Delete a record. With a RecordView, a concurrent change supersedes the delete.
@@ -25544,13 +26045,13 @@ var MdbaseClient = class _MdbaseClient {
25544
26045
  return this.contractPlan(contract, target2, void 0, void 0, o.signal).then((plan) => {
25545
26046
  const op3 = { kind: "delete", id: plan.id, baseRevision: plan.revision };
25546
26047
  if (rest.ifRevision) op3.ifRevision = rest.ifRevision;
25547
- return this.one(op3, rest);
26048
+ return this.record(op3, rest);
25548
26049
  });
25549
26050
  }
25550
26051
  const op2 = { kind: "delete", id: refId(target2) };
25551
26052
  if (typeof target2 === "object" && "revision" in target2) op2.baseRevision = target2.revision;
25552
26053
  if (o.ifRevision) op2.ifRevision = o.ifRevision;
25553
- return this.one(op2, o);
26054
+ return this.record(op2, o);
25554
26055
  }
25555
26056
  /** Rename (move) a record; `updateRefs` rewrites links to it (default true).
25556
26057
  * With `contract`, the record must implement it, and moves from its current path. */
@@ -25561,7 +26062,7 @@ var MdbaseClient = class _MdbaseClient {
25561
26062
  }
25562
26063
  const op2 = { kind: "rename", id: target2.id, from: target2.path, to, updateRefs: o.updateRefs ?? true };
25563
26064
  if (o.ifRevision) op2.ifRevision = o.ifRevision;
25564
- return this.one(op2, o);
26065
+ return this.record(op2, o);
25565
26066
  }
25566
26067
  /** @internal Track a receipt the replica returned outside `submit`. */
25567
26068
  _track(r) {
@@ -25583,63 +26084,48 @@ var MdbaseClient = class _MdbaseClient {
25583
26084
  return w;
25584
26085
  }
25585
26086
  /**
25586
- * Settle a write for the UI: waits up to `timeoutMs` (default 3 s) for the log
25587
- * to confirm it. Still pending then is `saved_on_device`, not a failure: the
25588
- * write is kept on this device and the ledger settles it later. With
25589
- * `readBack`, `record` is the record as it now reads here.
26087
+ * Settle a write: wait for the sync service to confirm it (3 s by default),
26088
+ * and with `read`, read the record back as it now reads here.
26089
+ *
26090
+ * Pass the write, the promise of one, or the mutation ID of an earlier write
26091
+ * whose result was `unknown`. The answer is a {@link Settlement}; the only
26092
+ * rejections are cancellation and a call that cannot be settled as asked.
26093
+ * Nothing is ever submitted again.
26094
+ *
26095
+ * const saved = await db.settle(db.update(record, { patch }), { read: true });
26096
+ * if (saved.outcome === "rejected") show(describeError(saved.problem));
25590
26097
  */
25591
- async save(write, o = {}) {
25592
- const w = await write;
25593
- let r = w.receipt;
25594
- if (r.state === "pending") {
25595
- try {
25596
- r = await this.awaitReceipt(w.mutationId, o.timeoutMs ?? 3e3, o.signal);
25597
- w.update(r);
25598
- } catch (e) {
25599
- if (isMdbaseError(e, "cancelled")) throw e;
25600
- r = w.receipt;
25601
- }
25602
- }
25603
- const outcome = r.state === "confirmed" ? "confirmed" : r.state === "pending" ? "saved_on_device" : "rejected";
25604
- const records2 = w.records;
25605
- let record3 = records2[0];
25606
- if (o.readBack && outcome !== "rejected" && record3) {
25607
- record3 = await this.find(record3.id, void 0, o.signal).catch(() => null) ?? record3;
25608
- }
25609
- return Object.freeze({
25610
- outcome,
25611
- mutationId: w.mutationId,
25612
- records: records2,
25613
- ...record3 ? { record: record3 } : {},
25614
- ...outcome === "rejected" && r.problem ? { problem: r.problem } : {}
25615
- });
26098
+ settle(write, options = {}) {
26099
+ return settleWrite(this, write, options);
25616
26100
  }
25617
- /** The current receipt of a mutation. Failures carry `mutationId`. */
25618
- receipt(mutation2, signal) {
26101
+ /** The current receipt of a mutation. Failures carry `mutationId`. `o.signal` cancels the read. */
26102
+ receipt(mutation2, o = {}) {
25619
26103
  return this.call("receipt", params([[0, uuid2.enc(mutation2)]]), {
25620
26104
  codec: receipt,
25621
26105
  retry: true,
25622
- ...signal ? { signal } : {}
26106
+ ...o.signal ? { signal: o.signal } : {}
25623
26107
  }).catch((e) => {
25624
26108
  throw withMutation(e, "receipt", { mutationId: mutation2 });
25625
26109
  });
25626
26110
  }
25627
- /** Resolves when the receipt leaves `pending`, or at `timeoutMs` with the pending receipt. */
25628
- awaitReceipt(mutation2, timeoutMs, signal) {
26111
+ /** Resolves when the receipt leaves `pending`, or at `o.timeoutMs` with the
26112
+ * pending receipt. `o.signal` cancels the wait. */
26113
+ awaitReceipt(mutation2, o = {}) {
25629
26114
  return this.call(
25630
26115
  "await",
25631
26116
  params([
25632
26117
  [0, uuid2.enc(mutation2)],
25633
- [1, timeoutMs]
26118
+ [1, o.timeoutMs]
25634
26119
  ]),
25635
- { codec: receipt, retry: true, ...signal ? { signal } : {} }
26120
+ { codec: receipt, retry: true, ...o.signal ? { signal: o.signal } : {} }
25636
26121
  ).catch((e) => {
25637
26122
  throw withMutation(e, "await", { mutationId: mutation2 });
25638
26123
  });
25639
26124
  }
25640
26125
  // ---------------------------------------------------------------- holds and conflicts (§8)
25641
- listHolds(signal) {
25642
- return this.call("list_holds", null, { codec: list(hold), retry: true, ...signal ? { signal } : {} });
26126
+ /** The current holds. `o.signal` cancels the read. */
26127
+ listHolds(o = {}) {
26128
+ return this.call("list_holds", null, { codec: list(hold), retry: true, ...o.signal ? { signal: o.signal } : {} });
25643
26129
  }
25644
26130
  /** Call `fn` with the holds now and on every change. */
25645
26131
  onHolds(fn) {
@@ -25671,11 +26157,12 @@ var MdbaseClient = class _MdbaseClient {
25671
26157
  );
25672
26158
  return this._track(r);
25673
26159
  }
25674
- listConflicts(record3, signal) {
25675
- return this.call("list_conflicts", record3 ? params([[0, uuid2.enc(record3)]]) : null, {
26160
+ /** The current conflicts, of `o.record` only when given. `o.signal` cancels the read. */
26161
+ listConflicts(o = {}) {
26162
+ return this.call("list_conflicts", o.record ? params([[0, uuid2.enc(o.record)]]) : null, {
25676
26163
  codec: list(conflictEntry),
25677
26164
  retry: true,
25678
- ...signal ? { signal } : {}
26165
+ ...o.signal ? { signal: o.signal } : {}
25679
26166
  });
25680
26167
  }
25681
26168
  onConflicts(fn) {
@@ -25696,18 +26183,17 @@ var MdbaseClient = class _MdbaseClient {
25696
26183
  }
25697
26184
  /** Accept what the record kept. */
25698
26185
  dismissConflict(entry2, o = {}) {
25699
- return this.one({ kind: "conflict_dismiss", mutation: entry2.mutation, record: entry2.conflict.id }, o);
26186
+ return this.submit([{ kind: "conflict_dismiss", mutation: entry2.mutation, record: entry2.conflict.id }], o);
25700
26187
  }
25701
26188
  /** Resolve a field conflict with a chosen value, dismissing it in the same mutation. */
25702
- async resolveConflict(entry2, field, chosen, o = {}) {
25703
- const [w] = await this.submit(
26189
+ resolveConflict(entry2, field, chosen, o = {}) {
26190
+ return this.submit(
25704
26191
  [
25705
26192
  { kind: "update", id: entry2.conflict.id, patch: /* @__PURE__ */ new Map([[field, toValue(chosen)]]) },
25706
26193
  { kind: "conflict_dismiss", mutation: entry2.mutation, record: entry2.conflict.id }
25707
26194
  ],
25708
26195
  o
25709
26196
  );
25710
- return w;
25711
26197
  }
25712
26198
  // ---------------------------------------------------------------- private collections (§8.3)
25713
26199
  /**
@@ -25715,9 +26201,10 @@ var MdbaseClient = class _MdbaseClient {
25715
26201
  * hosting the replica (no grant). `exchangeReady` is challenge/reveal readiness,
25716
26202
  * NOT approval/key delivery. Once ready, `sas` is the host-only comparison code
25717
26203
  * to display beside Allow; the user must check it matches on the other computer.
26204
+ * `o.signal` cancels the read.
25718
26205
  */
25719
- pendingDevices(signal) {
25720
- return this.call("pending_devices", null, { codec: list(pendingDevice), retry: true, ...signal ? { signal } : {} });
26206
+ pendingDevices(o = {}) {
26207
+ return this.call("pending_devices", null, { codec: list(pendingDevice), retry: true, ...o.signal ? { signal: o.signal } : {} });
25721
26208
  }
25722
26209
  /**
25723
26210
  * Confirm with the six digits displayed for the current host exchange, only
@@ -25760,7 +26247,9 @@ var MdbaseClient = class _MdbaseClient {
25760
26247
  accountSecret(secret);
25761
26248
  await this.call("account_key_unlock", params([[0, secret]]));
25762
26249
  },
25763
- status: (signal) => this.call("account_key_status", null, { codec: accountKeyStatus, retry: true, ...signal ? { signal } : {} })
26250
+ /** Where an account-key unlock stands on this replica. `o.signal` cancels
26251
+ * the read. */
26252
+ status: (o = {}) => this.call("account_key_status", null, { codec: accountKeyStatus, retry: true, ...o.signal ? { signal: o.signal } : {} })
25764
26253
  };
25765
26254
  /** Recovery key for a private collection (hosting app only). */
25766
26255
  recoveryKey = {
@@ -26584,13 +27073,12 @@ function keyWaitDetail(status) {
26584
27073
  const found = status.incidents.find((incident2) => incident2.kind === "waiting_for_key");
26585
27074
  if (!found) return null;
26586
27075
  const out = { through: status.confirmedThrough, head: status.headKnown };
26587
- const d = found.details;
26588
- const get = (k) => d instanceof Map ? d.get(k) : d && typeof d === "object" ? d[k] : void 0;
27076
+ const get = (k) => fieldOf(found.details, k);
26589
27077
  const reason = get("reason");
26590
27078
  if (typeof reason === "string" && /^[a-z_]{1,32}$/.test(reason)) out.key = reason;
26591
27079
  for (const k of ["position", "at"]) {
26592
27080
  const v = get(k);
26593
- if (typeof v === "number" || typeof v === "bigint") out[k] = Number(v);
27081
+ if (typeof v === "number") out[k] = v;
26594
27082
  }
26595
27083
  return out;
26596
27084
  }
@@ -27475,11 +27963,11 @@ var AppCpPrivateBootstrap = class {
27475
27963
  const genesis = object6(result2.genesis);
27476
27964
  if (genesis.seq !== 1) throw fail7("response");
27477
27965
  const item = bytes6(genesis.item, 256 * 1024);
27478
- const domain = new TextEncoder().encode("mdbase/v1/chain"), message = new Uint8Array(1 + domain.length + item.length);
27479
- message[0] = domain.length;
27480
- message.set(domain, 1);
27481
- message.set(item, 1 + domain.length);
27482
- const digest2 = new Uint8Array(await crypto.subtle.digest("SHA-256", message));
27966
+ const domain = new TextEncoder().encode("mdbase/v1/chain"), message2 = new Uint8Array(1 + domain.length + item.length);
27967
+ message2[0] = domain.length;
27968
+ message2.set(domain, 1);
27969
+ message2.set(item, 1 + domain.length);
27970
+ const digest2 = new Uint8Array(await crypto.subtle.digest("SHA-256", message2));
27483
27971
  this.check(options.signal);
27484
27972
  const metadata2 = this.copy({ collection: this.scope.collection, deviceId: this.scope.deviceId, logOrigin: this.scope.logOrigin, rootPublicKey: this.root, genesisItem: item, expectedGenesis: `sha256:${hex7(digest2)}`, approval: enrol ? "pending" : "creator", ...this.displayName === void 0 ? {} : { displayName: this.displayName } });
27485
27973
  await this.persistence.completed(this.copy(metadata2), options);
@@ -27954,10 +28442,10 @@ function abytes2(value2, length, title = "") {
27954
28442
  const bytes10 = isBytes2(value2);
27955
28443
  const ofLen = length !== void 0 ? ` of length ${length}` : "";
27956
28444
  const got = bytes10 ? `length=${value2.length}` : `type=${typeof value2}`;
27957
- const message = atitle2(title) + "expected Uint8Array" + ofLen + ", got " + got;
28445
+ const message2 = atitle2(title) + "expected Uint8Array" + ofLen + ", got " + got;
27958
28446
  if (!bytes10)
27959
- throw new TypeError(message);
27960
- throw new RangeError(message);
28447
+ throw new TypeError(message2);
28448
+ throw new RangeError(message2);
27961
28449
  }
27962
28450
  var aobject2 = (value2, label) => {
27963
28451
  if (value2 === null || typeof value2 !== "object" || Array.isArray(value2))
@@ -31301,7 +31789,7 @@ var _HMAC = class {
31301
31789
  }
31302
31790
  };
31303
31791
  var hmac = /* @__PURE__ */ (() => {
31304
- const hmac_ = ((hash2, key3, message) => new _HMAC(hash2, key3).update(message).digest());
31792
+ const hmac_ = ((hash2, key3, message2) => new _HMAC(hash2, key3).update(message2).digest());
31305
31793
  hmac_.create = (hash2, key3) => new _HMAC(hash2, key3);
31306
31794
  return hmac_;
31307
31795
  })();
@@ -31373,15 +31861,15 @@ var AccountKeyError = class extends Error {
31373
31861
  /** A machine-readable detail: `too_short`, `too_long`, `strength`, `wrong_prefix`, `checksum`, …, or a control-plane error code. */
31374
31862
  reason;
31375
31863
  retryAfterMs;
31376
- constructor(code, message, extra = {}) {
31377
- super(message);
31864
+ constructor(code, message2, extra = {}) {
31865
+ super(message2);
31378
31866
  this.name = "AccountKeyError";
31379
31867
  this.code = code;
31380
31868
  if (extra.reason !== void 0) this.reason = extra.reason;
31381
31869
  if (extra.retryAfterMs !== void 0) this.retryAfterMs = extra.retryAfterMs;
31382
31870
  }
31383
31871
  };
31384
- var err = (code, message, reason) => new AccountKeyError(code, message, reason === void 0 ? {} : { reason });
31872
+ var err = (code, message2, reason) => new AccountKeyError(code, message2, reason === void 0 ? {} : { reason });
31385
31873
  var utf83 = new TextEncoder();
31386
31874
  function domainHash(tag, m2) {
31387
31875
  const t = utf83.encode(tag);
@@ -31495,8 +31983,8 @@ function deriveRecoveryDevice(secret, collection) {
31495
31983
  const device = uuidText(domainHash("mdbase/v1/recovery-id", concat(c, signPk)).subarray(0, 16));
31496
31984
  return { device, signSeed, signPk, kemSk, kemPk, noisePk: new Uint8Array(32) };
31497
31985
  }
31498
- function recoverySign(d, message) {
31499
- return ed25519.sign(message, d.signSeed);
31986
+ function recoverySign(d, message2) {
31987
+ return ed25519.sign(message2, d.signSeed);
31500
31988
  }
31501
31989
  function wipeRecoveryDevice(d) {
31502
31990
  wipe(d.signSeed, d.kemSk);
@@ -32316,16 +32804,16 @@ var PrivateAccount = class {
32316
32804
  if (r.mode !== "password" || version2(r.version) !== expected + 1 || r.key_id !== keyIdHex) throw bad7("put");
32317
32805
  }
32318
32806
  async collections(signal) {
32319
- let list3;
32807
+ let list4;
32320
32808
  try {
32321
- list3 = await this.replica.privateCollections({ signal });
32809
+ list4 = await this.replica.privateCollections({ signal });
32322
32810
  } catch (e) {
32323
32811
  throw mapPortError(e);
32324
32812
  }
32325
32813
  this.check(signal);
32326
- if (!Array.isArray(list3) || list3.some((c) => typeof c !== "string") || new Set(list3).size !== list3.length) throw bad7("collections");
32327
- for (const c of list3) uuidBytes(c);
32328
- return list3;
32814
+ if (!Array.isArray(list4) || list4.some((c) => typeof c !== "string") || new Set(list4).size !== list4.length) throw bad7("collections");
32815
+ for (const c of list4) uuidBytes(c);
32816
+ return list4;
32329
32817
  }
32330
32818
  /** Enrol and key the recovery device in each private collection; collect the ones that failed. */
32331
32819
  async keyAll(secret, signal) {
@@ -34939,7 +35427,7 @@ var MAX_BODY = 64 * 1024;
34939
35427
  var REQUEST_MS = 15e3;
34940
35428
  var SETTLE_MS = 45e3;
34941
35429
  var unavailable5 = (reason) => new AccountKeyError("unavailable", "The account key service refused or was unreachable.", { reason });
34942
- var cancelled = () => new AccountKeyError("cancelled", "Account key request cancelled.");
35430
+ var cancelled2 = () => new AccountKeyError("cancelled", "Account key request cancelled.");
34943
35431
  var unsupported = () => unavailable5("not_supported");
34944
35432
  var hex9 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
34945
35433
  var HEX322 = /^[0-9a-f]{64}$/;
@@ -34966,7 +35454,7 @@ var AppCpAccountKeyControl = class {
34966
35454
  fetchImpl;
34967
35455
  now;
34968
35456
  check(signal) {
34969
- if (signal.aborted || this.lifetime.signal.aborted) throw cancelled();
35457
+ if (signal.aborted || this.lifetime.signal.aborted) throw cancelled2();
34970
35458
  let current2 = false;
34971
35459
  try {
34972
35460
  current2 = this.session.isCurrent() === true && this.session.accountId === this.accountId && this.session.deviceId === this.deviceId && this.session.cpOrigin === this.origin;
@@ -35114,7 +35602,7 @@ async function accountKeyStatus2(control, signal) {
35114
35602
  } catch (error4) {
35115
35603
  throw mapPortError(error4);
35116
35604
  }
35117
- if (signal.aborted) throw cancelled();
35605
+ if (signal.aborted) throw cancelled2();
35118
35606
  const r = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {}, mode = r.mode;
35119
35607
  if (mode !== "password" && mode !== "strict" && mode !== "none") throw unavailable5("response");
35120
35608
  return {
@@ -35142,7 +35630,7 @@ async function unlockPrivateDevice(session, native, secret, options) {
35142
35630
  if (password === recovery2 || typeof (password ? secret.password : secret.recoveryKey) !== "string" || !Number.isSafeInteger(settleMs) || settleMs < 1)
35143
35631
  throw new AppAccountKeyUnlockError("unavailable", "binding");
35144
35632
  const current2 = () => {
35145
- if (signal.aborted) throw cancelled();
35633
+ if (signal.aborted) throw cancelled2();
35146
35634
  if (session.isCurrent() !== true) throw unavailable5("fenced");
35147
35635
  };
35148
35636
  current2();
@@ -37185,7 +37673,7 @@ var AppWebCloudCopyHost = class _AppWebCloudCopyHost {
37185
37673
  }
37186
37674
  try {
37187
37675
  await Promise.race([
37188
- this.readClient.query({ limit: 1 }, void 0, ctrl.signal),
37676
+ this.readClient.query({ limit: 1 }, { signal: ctrl.signal }),
37189
37677
  aborted
37190
37678
  ]);
37191
37679
  this.checkCollection(signal);
@@ -37722,9 +38210,9 @@ async function otherDatabaseNames(scope, ledger, unlabelled) {
37722
38210
  for (const purpose of ["create", "join"]) others.add(`${scoped[0]}${id4}.${purpose}`);
37723
38211
  for (const purpose of ["create", "enrol"]) others.add(`${scoped[1]}${id4}.${purpose}`);
37724
38212
  }
37725
- const list3 = indexedDB.databases;
37726
- if (typeof list3 === "function") {
37727
- const found = await bounded2(list3.call(indexedDB), []);
38213
+ const list4 = indexedDB.databases;
38214
+ if (typeof list4 === "function") {
38215
+ const found = await bounded2(list4.call(indexedDB), []);
37728
38216
  for (const { name: name2 } of found) if (name2 && scoped.some((p) => name2.startsWith(p))) others.add(name2);
37729
38217
  }
37730
38218
  }
@@ -37826,6 +38314,8 @@ var AppWebSignInSession = class {
37826
38314
  receiptRead = null;
37827
38315
  foregroundRead = null;
37828
38316
  attested = false;
38317
+ /** start() resumed a request sent before a restart: an expired or cancelled one ends quietly. */
38318
+ restoredPending = false;
37829
38319
  acknowledged = false;
37830
38320
  consentPending = false;
37831
38321
  listCached = false;
@@ -38031,7 +38521,10 @@ var AppWebSignInSession = class {
38031
38521
  }
38032
38522
  await this.refreshCollections(kept);
38033
38523
  }
38034
- } else this.publish({ status: view.state === "pending" ? "signed_out" : "authorizing" });
38524
+ } else {
38525
+ this.restoredPending = view.state === "pending" && this.flow.requestSent();
38526
+ this.publish({ status: view.state === "pending" && !this.restoredPending ? "signed_out" : "authorizing" });
38527
+ }
38035
38528
  return this.getSnapshot();
38036
38529
  });
38037
38530
  }
@@ -38067,6 +38560,7 @@ var AppWebSignInSession = class {
38067
38560
  beginAuthorization(portal, options) {
38068
38561
  const hint = { collectionHint: options.collectionHint ?? null };
38069
38562
  const view = this.flow.view();
38563
+ this.restoredPending = false;
38070
38564
  this.authorizationStartedAt = performance.now();
38071
38565
  this.publish({ timing: Object.freeze({ firstScreenMs: null, readyMs: null }), approval: null });
38072
38566
  return this.operation(async () => {
@@ -38250,7 +38744,16 @@ var AppWebSignInSession = class {
38250
38744
  }
38251
38745
  return;
38252
38746
  }
38253
- let view = await this.exchangeReceipt(() => this.flow.exchange());
38747
+ let view;
38748
+ try {
38749
+ view = await this.exchangeReceipt(() => this.flow.exchange());
38750
+ } catch (error4) {
38751
+ if (!this.restoredPending || !(error4 instanceof AppInstallationSignInError) || error4.reason !== "expired" && error4.reason !== "refused") throw error4;
38752
+ this.check();
38753
+ this.restoredPending = false;
38754
+ this.publish({ status: "signed_out", problem: null });
38755
+ return;
38756
+ }
38254
38757
  this.check();
38255
38758
  if (!view) return;
38256
38759
  if (view.state === "account_selected") {
@@ -41155,9 +41658,9 @@ async function appUnsyncedWork(databaseName, signal) {
41155
41658
  return row2(databaseName, WORK, work, null, signal);
41156
41659
  }
41157
41660
  async function exists(databaseName, signal) {
41158
- const list3 = globalThis.indexedDB?.databases;
41159
- if (typeof list3 !== "function") return null;
41160
- const names = await list3.call(globalThis.indexedDB);
41661
+ const list4 = globalThis.indexedDB?.databases;
41662
+ if (typeof list4 !== "function") return null;
41663
+ const names = await list4.call(globalThis.indexedDB);
41161
41664
  signal.throwIfAborted();
41162
41665
  return names.some((entry2) => entry2.name === databaseName);
41163
41666
  }
@@ -42313,24 +42816,25 @@ async function initialize(event) {
42313
42816
  const port = event.ports[0], value2 = event.data;
42314
42817
  let binding = null;
42315
42818
  try {
42316
- if (!port || event.ports.length !== 1 || !Array.isArray(value2) || value2.length !== 3 && value2.length !== 4 || value2[0] !== APPLICATION_WORKER_PROTOCOL || !applicationWorkerBinding(value2[1])) throw new ApplicationWorkerError("application_worker_binding");
42819
+ if (!port || event.ports.length !== 1 || !Array.isArray(value2) || value2.length < 3 || value2.length > 5 || value2[0] !== APPLICATION_WORKER_PROTOCOL || !applicationWorkerBinding(value2[1])) throw new ApplicationWorkerError("application_worker_binding");
42317
42820
  binding = value2[1];
42318
42821
  const declaration = applicationDeclaration(value2[2]);
42319
- const storageNamespace = value2.length === 4 ? value2[3] : null;
42822
+ const storageNamespace = value2.length >= 4 ? value2[3] : null, anchor = value2.length === 5 ? value2[4] : void 0;
42320
42823
  if (storageNamespace !== null && (typeof storageNamespace !== "string" || storageNamespace !== declaration.storage.applicationNamespace)) throw new ApplicationWorkerError("application_worker_binding");
42824
+ if (anchor !== void 0 && typeof anchor !== "string") throw new ApplicationWorkerError("application_worker_binding");
42321
42825
  if (declaration.origin !== currentAppOrigin()) throw new ApplicationWorkerError("application_worker_binding");
42322
- const packaged = packagedApplicationAssets(declaration.environment, declaration.origin);
42826
+ const packaged = packagedApplicationAssets(declaration.environment, declaration.origin, anchor);
42323
42827
  owner = new ApplicationWorkerHost(port, binding, declaration, packaged, globalThis.navigator.locks, storageNamespace);
42324
42828
  const primary = binding;
42325
- globalThis.addEventListener("message", (message) => {
42326
- const data = message.data;
42829
+ globalThis.addEventListener("message", (message2) => {
42830
+ const data = message2.data;
42327
42831
  if (!owner || !Array.isArray(data) || data.length !== 4 || data[0] !== APPLICATION_WORKER_PROTOCOL || data[1] !== primary || !applicationWorkerBinding(data[3])) {
42328
- for (const input of message.ports) input.close();
42832
+ for (const input of message2.ports) input.close();
42329
42833
  return;
42330
42834
  }
42331
- if (data[2] === "attach" && message.ports.length === 1) owner.attach(message.ports[0], data[3]);
42332
- else if (data[2] === "detach" && message.ports.length === 0) owner.detachClient(data[3]);
42333
- else for (const input of message.ports) input.close();
42835
+ if (data[2] === "attach" && message2.ports.length === 1) owner.attach(message2.ports[0], data[3]);
42836
+ else if (data[2] === "detach" && message2.ports.length === 0) owner.detachClient(data[3]);
42837
+ else for (const input of message2.ports) input.close();
42334
42838
  });
42335
42839
  } catch (error4) {
42336
42840
  try {