@mdbase-dev/sdk 0.2.59 → 0.2.62

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.
@@ -234,7 +234,7 @@ var MdbaseSDK = (() => {
234
234
  }
235
235
  function toHex(b) {
236
236
  let s = "";
237
- for (const x of b) s += x.toString(16).padStart(2, "0");
237
+ for (const x of b) s += hexBytes[x];
238
238
  return s;
239
239
  }
240
240
  function fromHex(s) {
@@ -248,7 +248,7 @@ var MdbaseSDK = (() => {
248
248
  for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
249
249
  return true;
250
250
  }
251
- var Float64, MAX_DEPTH, CborError, U64_MAX, I64_MIN, textEncoder, textDecoder, Writer, Reader;
251
+ var Float64, MAX_DEPTH, CborError, U64_MAX, I64_MIN, textEncoder, textDecoder, Writer, Reader, hexBytes;
252
252
  var init_cbor = __esm({
253
253
  "src/cbor.ts"() {
254
254
  "use strict";
@@ -495,6 +495,7 @@ var MdbaseSDK = (() => {
495
495
  }
496
496
  }
497
497
  };
498
+ hexBytes = Array.from({ length: 256 }, (_, n) => n.toString(16).padStart(2, "0"));
498
499
  }
499
500
  });
500
501
 
@@ -4996,8 +4997,11 @@ var MdbaseSDK = (() => {
4996
4997
  });
4997
4998
 
4998
4999
  // src/records/session.ts
4999
- function resting(record5) {
5000
- return confirmed(record5) ? "saved" : "saved_on_device";
5000
+ function matches(record5, key3, value2) {
5001
+ if (key3 === null) return value2 === record5.body;
5002
+ const actual = fieldOf(record5.frontmatter, key3);
5003
+ if (actual === void 0 || value2 === void 0) return actual === value2;
5004
+ return equal(toValue(actual), toValue(toPlain(value2)));
5001
5005
  }
5002
5006
  function equal(a, b) {
5003
5007
  const x = encode(a), y = encode(b);
@@ -5046,6 +5050,7 @@ var MdbaseSDK = (() => {
5046
5050
  init_errors();
5047
5051
  init_session();
5048
5052
  init_values();
5053
+ init_plain();
5049
5054
  init_witness();
5050
5055
  RecordSessionImpl = class {
5051
5056
  constructor(client, record5, reserve) {
@@ -5054,7 +5059,7 @@ var MdbaseSDK = (() => {
5054
5059
  complete(record5);
5055
5060
  this.base = copy(record5);
5056
5061
  this.body = record5.body;
5057
- this.state = isProtected(record5) ? "conflict" : resting(record5);
5062
+ this.state = isProtected(record5) ? "conflict" : this.restState;
5058
5063
  this.publish();
5059
5064
  }
5060
5065
  client;
@@ -5064,6 +5069,8 @@ var MdbaseSDK = (() => {
5064
5069
  patch = /* @__PURE__ */ new Map();
5065
5070
  remote = null;
5066
5071
  captured = null;
5072
+ pendingEdits = /* @__PURE__ */ new Map();
5073
+ driveGeneration = 0;
5067
5074
  lastReceipt = null;
5068
5075
  state;
5069
5076
  why = null;
@@ -5104,6 +5111,24 @@ var MdbaseSDK = (() => {
5104
5111
  recovery: { ...hint, receipt: null, write: null }
5105
5112
  };
5106
5113
  }
5114
+ if (!this.active && !hint && this.base.state.state === "pending" && !this.pendingEdits.size) {
5115
+ const edits = /* @__PURE__ */ new Map();
5116
+ for (const { ops, receipt: receipt4 } of await this.client.pendingWrites({ signal })) {
5117
+ for (const op2 of ops) {
5118
+ if (op2.kind !== "update" || op2.id !== this.id) continue;
5119
+ const mutation2 = receipt4.mutation;
5120
+ if (op2.body !== void 0 || op2.bodyEdits?.length) {
5121
+ const body = op2.body ?? receipt4.records?.find((record5) => record5.id === this.id)?.body ?? this.base.body;
5122
+ edits.set(null, { mutation: mutation2, value: body });
5123
+ }
5124
+ for (const [key3, value2] of Object.entries(op2.patch ?? {}))
5125
+ edits.set(key3, { mutation: mutation2, value: toValue(value2) });
5126
+ for (const key3 of op2.unset ?? []) edits.set(key3, { mutation: mutation2, value: void 0 });
5127
+ }
5128
+ }
5129
+ this.charge(this.body, this.patch, this.base, this.remote, this.lastReceipt, this.captured, edits);
5130
+ this.pendingEdits = edits;
5131
+ }
5107
5132
  signal?.throwIfAborted();
5108
5133
  if (this.captured) {
5109
5134
  this.state = "recovery";
@@ -5121,8 +5146,11 @@ var MdbaseSDK = (() => {
5121
5146
  get dirty() {
5122
5147
  return this.body !== this.base.body || this.patch.size > 0;
5123
5148
  }
5149
+ get restState() {
5150
+ return !this.pendingEdits.size && confirmed(this.base) ? "saved" : "saved_on_device";
5151
+ }
5124
5152
  get retained() {
5125
- return this.dirty || this.captured !== null || !confirmed(this.base);
5153
+ return this.dirty || this.captured !== null || this.pendingEdits.size > 0 || !confirmed(this.base);
5126
5154
  }
5127
5155
  getSnapshot = () => this.snapshot;
5128
5156
  subscribe = (listener) => {
@@ -5172,13 +5200,13 @@ var MdbaseSDK = (() => {
5172
5200
  };
5173
5201
  edited() {
5174
5202
  if (!this.captured && this.state !== "conflict" && this.state !== "deleted") {
5175
- this.state = this.dirty ? "unsaved" : resting(this.base);
5203
+ this.state = this.dirty ? "unsaved" : this.restState;
5176
5204
  this.why = null;
5177
5205
  }
5178
5206
  this.publish();
5179
5207
  this.schedule();
5180
5208
  }
5181
- charge(body = this.body, patch = this.patch, base = this.base, remote = this.remote, receipt4 = this.lastReceipt, captured = this.captured) {
5209
+ charge(body = this.body, patch = this.patch, base = this.base, remote = this.remote, receipt4 = this.lastReceipt, captured = this.captured, pendingEdits = this.pendingEdits) {
5182
5210
  let bytes10 = retainedBytes(base) + textBytes(body) + encode(new Map([...patch].map(([k, v]) => [k, v ?? null]))).byteLength * 2;
5183
5211
  if (remote) bytes10 += retainedBytes(remote);
5184
5212
  if (captured)
@@ -5187,6 +5215,8 @@ var MdbaseSDK = (() => {
5187
5215
  [...captured.patch].map(([k, v]) => [k, v ?? null])
5188
5216
  )
5189
5217
  ).byteLength * 2;
5218
+ for (const [key3, edit] of pendingEdits)
5219
+ bytes10 += encode([key3, edit.mutation, edit.value ?? null]).byteLength * 2;
5190
5220
  if (receipt4) bytes10 += retainedBytes(receipt4);
5191
5221
  this.reserve(bytes10);
5192
5222
  }
@@ -5237,6 +5267,73 @@ var MdbaseSDK = (() => {
5237
5267
  complete(record5, this.id);
5238
5268
  return record5;
5239
5269
  }
5270
+ /** The projection can change after either a refusal or a successful write
5271
+ * followed by a peer edit. Only the original MID distinguishes them. */
5272
+ async readWithReceipts(signal) {
5273
+ const receipts = /* @__PURE__ */ new Map();
5274
+ for (; ; ) {
5275
+ const current3 = await this.read(signal);
5276
+ if (this.captured) return { current: current3, receipts };
5277
+ const count = receipts.size;
5278
+ for (const [key3, { mutation: mutation2, value: value2 }] of this.pendingEdits) {
5279
+ const present2 = matches(current3, key3, value2);
5280
+ if (!confirmed(current3) && present2) continue;
5281
+ if (!receipts.has(mutation2)) {
5282
+ const receipt5 = await this.client.receipt(mutation2, { signal });
5283
+ signal.throwIfAborted();
5284
+ if (receipt5.mutation !== mutation2)
5285
+ throw refusal("outcome_unknown", "native receipt changed identity", "mutation_identity_mismatch");
5286
+ receipts.set(mutation2, receipt5);
5287
+ }
5288
+ const receipt4 = receipts.get(mutation2);
5289
+ if (receipt4.state === "unknown" || receipt4.state === "pending" && !present2)
5290
+ throw refusal("outcome_unknown", "the projection does not qualify this device write yet", "unqualified_readback");
5291
+ }
5292
+ if (receipts.size === count) return { current: current3, receipts };
5293
+ }
5294
+ }
5295
+ /** Restore only a refused write's missing edits. Newer typing and field
5296
+ * edits win, including an explicit unset; unrelated remote fields survive. */
5297
+ reconcilePending(current3, receipts) {
5298
+ if (!receipts.size) return;
5299
+ const remaining = new Map(this.pendingEdits);
5300
+ const patch = new Map(this.patch);
5301
+ const bodyEdited = this.body !== this.base.body;
5302
+ let body = bodyEdited ? this.body : current3.body;
5303
+ let rolledBack = false;
5304
+ for (const [key3, { mutation: mutation2, value: value2 }] of this.pendingEdits) {
5305
+ const receipt4 = receipts.get(mutation2);
5306
+ if (!receipt4 || receipt4.state === "pending" || receipt4.state === "unknown") continue;
5307
+ remaining.delete(key3);
5308
+ if (receipt4.state !== "rejected" && receipt4.status !== "conflicted" || matches(current3, key3, value2)) continue;
5309
+ rolledBack = true;
5310
+ if (key3 === null) {
5311
+ if (!bodyEdited) body = value2;
5312
+ } else if (!patch.has(key3)) {
5313
+ patch.set(key3, value2);
5314
+ }
5315
+ }
5316
+ const last = this.lastReceipt && (receipts.get(this.lastReceipt.mutation) ?? this.lastReceipt);
5317
+ if (rolledBack) {
5318
+ for (const [key3, value2] of patch) {
5319
+ if (matches(current3, key3, value2)) patch.delete(key3);
5320
+ }
5321
+ const differs = body !== current3.body || patch.size > 0;
5322
+ this.charge(body, patch, current3, differs ? current3 : null, last, this.captured, remaining);
5323
+ this.base = copy(current3);
5324
+ this.remote = differs ? copy(current3) : null;
5325
+ this.body = body;
5326
+ this.patch = patch;
5327
+ if (differs) {
5328
+ this.state = "conflict";
5329
+ this.why = refusal("conflict", "a device write was refused at head", "record_session_conflict").toProblem();
5330
+ }
5331
+ } else {
5332
+ this.charge(this.body, this.patch, this.base, this.remote, last, this.captured, remaining);
5333
+ }
5334
+ this.pendingEdits = remaining;
5335
+ this.lastReceipt = last;
5336
+ }
5240
5337
  /** Native change notifications are hints only; hydrate the same UUID. */
5241
5338
  refresh = () => {
5242
5339
  if (!this.active) return Promise.resolve();
@@ -5248,20 +5345,26 @@ var MdbaseSDK = (() => {
5248
5345
  this.refreshRunning = (async () => {
5249
5346
  do {
5250
5347
  this.refreshAgain = false;
5348
+ const generation = this.driveGeneration;
5251
5349
  try {
5252
- const current3 = await this.read(signal);
5350
+ const { current: current3, receipts } = await this.readWithReceipts(signal);
5351
+ if (generation !== this.driveGeneration) {
5352
+ this.refreshAgain = true;
5353
+ continue;
5354
+ }
5253
5355
  if (this.captured || this.running) {
5254
5356
  if (this.captured && !this.running)
5255
5357
  void this.start(false, {}).catch(() => {
5256
5358
  });
5257
5359
  continue;
5258
5360
  }
5361
+ this.reconcilePending(current3, receipts);
5259
5362
  this.charge(this.body, this.patch, this.base, current3);
5260
5363
  if (!this.dirty) {
5261
5364
  this.base = copy(current3);
5262
5365
  this.body = current3.body;
5263
5366
  this.remote = null;
5264
- this.state = isProtected(current3) ? "conflict" : resting(current3);
5367
+ this.state = isProtected(current3) ? "conflict" : this.restState;
5265
5368
  this.why = null;
5266
5369
  } else if (current3.revision !== this.base.revision || isProtected(current3)) {
5267
5370
  this.remote = copy(current3);
@@ -5275,6 +5378,10 @@ var MdbaseSDK = (() => {
5275
5378
  this.publish();
5276
5379
  } catch (error5) {
5277
5380
  if (signal.aborted) return;
5381
+ if (generation !== this.driveGeneration || this.running) {
5382
+ this.refreshAgain = !this.running;
5383
+ continue;
5384
+ }
5278
5385
  this.why = problem2(error5);
5279
5386
  this.state = this.why.code === "not_found" ? "deleted" : this.captured ? "recovery" : "error";
5280
5387
  this.publish();
@@ -5315,8 +5422,12 @@ var MdbaseSDK = (() => {
5315
5422
  until: Date.now() + duration,
5316
5423
  margin: Math.min(2e3, Math.floor(duration / 4))
5317
5424
  };
5318
- const drive = () => this.drive(signal, budget, write);
5425
+ const drive = () => {
5426
+ this.driveGeneration++;
5427
+ return this.drive(signal, budget, write);
5428
+ };
5319
5429
  const run2 = (prior ? prior.then(drive, drive) : drive()).finally(() => {
5430
+ this.driveGeneration++;
5320
5431
  limit.clear();
5321
5432
  if (this.running !== run2) return;
5322
5433
  this.running = null;
@@ -5336,12 +5447,13 @@ var MdbaseSDK = (() => {
5336
5447
  continue;
5337
5448
  }
5338
5449
  if (!submit)
5339
- return confirmed(this.base) ? { ok: true, record: copy(this.base) } : {
5450
+ return this.restState === "saved" ? { ok: true, record: copy(this.base) } : {
5340
5451
  ok: true,
5341
5452
  record: copy(this.base),
5342
5453
  saved: "on_device"
5343
5454
  };
5344
- const current3 = await this.read(signal);
5455
+ const { current: current3, receipts } = await this.readWithReceipts(signal);
5456
+ this.reconcilePending(current3, receipts);
5345
5457
  if (isProtected(current3)) {
5346
5458
  this.charge(this.body, this.patch, this.base, current3);
5347
5459
  this.remote = copy(current3);
@@ -5362,10 +5474,10 @@ var MdbaseSDK = (() => {
5362
5474
  this.base = copy(current3);
5363
5475
  this.body = current3.body;
5364
5476
  this.remote = null;
5365
- this.state = resting(current3);
5477
+ this.state = this.restState;
5366
5478
  this.why = null;
5367
5479
  this.publish();
5368
- return confirmed(current3) ? { ok: true, record: copy(current3) } : { ok: true, record: copy(current3), saved: "on_device" };
5480
+ return this.restState === "saved" ? { ok: true, record: copy(current3) } : { ok: true, record: copy(current3), saved: "on_device" };
5369
5481
  }
5370
5482
  if (current3.revision !== this.base.revision || this.state === "conflict") {
5371
5483
  this.charge(this.body, this.patch, this.base, current3);
@@ -5501,14 +5613,23 @@ var MdbaseSDK = (() => {
5501
5613
  }
5502
5614
  const current3 = await this.read(signal);
5503
5615
  const kept = receipt4.state === "pending";
5504
- if (kept ? isProtected(current3) : !confirmed(current3))
5616
+ const edits = new Map(this.pendingEdits);
5617
+ const submitted = new Map(captured.patch);
5618
+ if (captured.body !== this.base.body) submitted.set(null, captured.body);
5619
+ for (const [key3, value2] of submitted) {
5620
+ if (kept) edits.set(key3, { mutation: receipt4.mutation, value: value2 });
5621
+ else edits.delete(key3);
5622
+ }
5623
+ if (kept ? isProtected(current3) || [...submitted].some(([key3, value2]) => !matches(current3, key3, value2)) : !confirmed(current3))
5505
5624
  throw refusal(
5506
5625
  "outcome_unknown",
5507
- "confirmed receipt has pending/protected current readback",
5626
+ "record readback does not qualify the native receipt",
5508
5627
  "unqualified_readback"
5509
5628
  );
5510
- this.charge(this.body, this.patch, current3, null);
5511
5629
  const sameBody = this.body === captured.body;
5630
+ const conflict2 = !kept && !sameBody && current3.body !== captured.body && current3.body !== this.body;
5631
+ this.charge(this.body, this.patch, current3, conflict2 ? current3 : null, receipt4, null, edits);
5632
+ this.pendingEdits = edits;
5512
5633
  for (const [key3, value2] of captured.patch) {
5513
5634
  const latest = this.patch.get(key3);
5514
5635
  if (this.patch.has(key3) && (value2 === void 0 ? latest === void 0 : latest !== void 0 && equal(value2, latest)))
@@ -5517,8 +5638,10 @@ var MdbaseSDK = (() => {
5517
5638
  this.base = copy(current3);
5518
5639
  if (sameBody) this.body = current3.body;
5519
5640
  this.captured = null;
5520
- this.remote = null;
5521
- this.state = this.dirty ? "unsaved" : resting(current3);
5641
+ this.remote = conflict2 ? copy(current3) : null;
5642
+ if (conflict2)
5643
+ throw refusal("conflict", "record body changed while saving an earlier draft", "record_session_conflict");
5644
+ this.state = this.dirty ? "unsaved" : this.restState;
5522
5645
  this.why = null;
5523
5646
  this.publish();
5524
5647
  }
@@ -5537,7 +5660,7 @@ var MdbaseSDK = (() => {
5537
5660
  "a confirmed unprotected native record is required for resolution",
5538
5661
  "native_protection_resolution_required"
5539
5662
  );
5540
- const body = "body" in choice ? choice.body : choice.keep === "theirs" ? remote.body : this.body;
5663
+ const body = "body" in choice ? choice.body : choice.keep === "theirs" || this.body === this.base.body ? remote.body : this.body;
5541
5664
  const patch = "keep" in choice && choice.keep === "theirs" ? /* @__PURE__ */ new Map() : this.patch;
5542
5665
  this.charge(body, patch, remote, null);
5543
5666
  this.base = copy(remote);
@@ -9137,9 +9260,9 @@ var MdbaseSDK = (() => {
9137
9260
  this.check(request3.signal);
9138
9261
  this.checkReadSession(records2.session);
9139
9262
  const invalid8 = records2.invalid.filter((row3) => row3.claims.some((claim) => sameIdentity(claim, account)));
9140
- const matches = records2.people.filter((row3) => row3.identities.some((claim) => sameIdentity(claim, account)));
9141
- const match = matches[0];
9142
- const me = invalid8.length ? { status: "invalid", paths: invalid8.map((row3) => row3.path) } : matches.length > 1 ? { status: "ambiguous", paths: matches.map((row3) => row3.path) } : match ? { status: "linked", person: match } : { status: "unlinked" };
9263
+ const matches2 = records2.people.filter((row3) => row3.identities.some((claim) => sameIdentity(claim, account)));
9264
+ const match = matches2[0];
9265
+ const me = invalid8.length ? { status: "invalid", paths: invalid8.map((row3) => row3.path) } : matches2.length > 1 ? { status: "ambiguous", paths: matches2.map((row3) => row3.path) } : match ? { status: "linked", person: match } : { status: "unlinked" };
9143
9266
  return { account, me, people: records2.people, invalid: records2.invalid.map(({ claims: _, ...row3 }) => row3), ...members === void 0 ? {} : { members } };
9144
9267
  }
9145
9268
  async records(options) {
@@ -9761,6 +9884,7 @@ var MdbaseSDK = (() => {
9761
9884
  "approval_window_closed",
9762
9885
  "account_confirmation_required",
9763
9886
  "recovery_required",
9887
+ "installation_removed",
9764
9888
  "open_failed",
9765
9889
  "device_keys_unavailable",
9766
9890
  "busy",
@@ -9868,7 +9992,7 @@ var MdbaseSDK = (() => {
9868
9992
  old_connector_running: ["Quit the old mdbase Connect app", "The old mdbase Connect app is still running on the computer that has this collection. Quit it there (including its menu-bar or tray icon), then open the mdbase desktop app.", "retry", "warning"],
9869
9993
  sync_required: ["Give this app access again", "Access to this collection changed since you approved this app. Approve it again to keep using the collection.", "approve", "warning", false, "Approve again"],
9870
9994
  no_device_registered: ["Turn on sync for this collection", "No computer is offering this collection to apps. Open the mdbase desktop app on the computer that has it and turn on sync. Web apps can reach a collection once sync is on.", "retry", "info"],
9871
- installation_scope_removed: ["Access was removed", "This app's previous installation cannot regain access to this collection. Request access again to approve a new installation for this collection. Your other collections keep their access.", "approve", "warning", false, "Request access again"],
9995
+ installation_scope_removed: ["Access was removed", "This app's previous installation cannot regain access to this collection. Request access again to approve a new installation for this collection.", "approve", "warning", false, "Request access again"],
9872
9996
  access_removed: ["You no longer have access", "You were removed from this collection, so this app can't open it. Ask its owner to add you again, or choose another collection.", "choose_collection", "warning"],
9873
9997
  collection_deleted: ["Collection deleted", "This collection was deleted, so it can't be opened any more. Choose another collection.", "choose_collection", "info"],
9874
9998
  collection_unavailable: ["Collection not available", "This collection can't be opened from this app right now. It may no longer be shared with this app, or the computer that offered it stopped. Choose another collection, or try again later.", "choose_collection", "warning"],
@@ -9895,6 +10019,7 @@ var MdbaseSDK = (() => {
9895
10019
  outcome_unknown: ["Not sure that worked", "The connection dropped before mdbase confirmed it. Check whether it went through before trying again.", "resolve_outcome", "warning"],
9896
10020
  internal: GENERIC,
9897
10021
  refused: ["Sign-in didn't go through", "mdbase didn't accept this sign-in. Try signing in again.", "sign_in", "warning"],
10022
+ installation_removed: ["This app's access was removed", "Sign out of this app on this device, then sign in to approve a new installation.", "none", "warning"],
9898
10023
  expired: ["Sign-in timed out", "The sign-in request expired. Start again to get a new one.", "sign_in", "warning"],
9899
10024
  approval_window_closed: ["Sign-in wasn't finished", "The mdbase window was closed before access was approved. Sign in again to continue.", "sign_in", "info"],
9900
10025
  account_confirmation_required: ["Confirm your account", "Confirm which mdbase account to use, then continue.", "sign_in", "info"],
@@ -9949,7 +10074,7 @@ var MdbaseSDK = (() => {
9949
10074
  configuration_unsupported: ["This app can't set up this collection", "This app's setup isn't supported by this version of mdbase. Contact the app's developer.", "contact_support", "warning"],
9950
10075
  setup_forbidden: ["You can't set up this collection", "Your access to this collection doesn't allow setting it up. Ask its owner to open it in this app first.", "choose_collection", "warning"],
9951
10076
  setup_conflict: ["Setup needs your decision", "Some things in this collection differ from what this app needs. Review them to continue.", "set_up", "warning", false, "Review setup"],
9952
- setup_unresolved: ["Setup can't finish", "This collection is missing something this app needs, and setup can't add it. A note type this app set up may have been changed or removed. Restore it, then try again.", "retry", "warning"],
10077
+ setup_unresolved: ["Setup can't finish", "This collection is missing a note format this app needs. Add or update a note type that supports that format, then try setup again.", "retry", "warning"],
9953
10078
  // Setup would leave something already in the collection invalid; the API
9954
10079
  // problem's message names the cause and the definition's path.
9955
10080
  collection_setup_conflict: ["Collection setup conflicts", "Setting up this app would conflict with definitions already in this collection, so nothing was changed. A note type may have been renamed or customised and still use an older definition. Update or remove it, then try again.", "retry", "warning"],
@@ -24998,7 +25123,7 @@ ${end.comment}` : end.comment;
24998
25123
  field(uuidBytes(binding2.application_id)),
24999
25124
  field(uuidBytes(binding2.authorization_id)),
25000
25125
  field(new TextEncoder().encode(binding2.application_declaration_id)),
25001
- field(hexBytes(binding2.application_manifest_digest)),
25126
+ field(hexBytes2(binding2.application_manifest_digest)),
25002
25127
  field(uuidBytes(binding2.application_installation_id)),
25003
25128
  ...keys2.map(field),
25004
25129
  field(new TextEncoder().encode(binding2.flow)),
@@ -25072,9 +25197,9 @@ ${end.comment}` : end.comment;
25072
25197
  throw new Error("Invalid UUID value.");
25073
25198
  }
25074
25199
  const compact = value2.replaceAll("-", "");
25075
- return hexBytes(compact);
25200
+ return hexBytes2(compact);
25076
25201
  }
25077
- function hexBytes(value2) {
25202
+ function hexBytes2(value2) {
25078
25203
  if (!/^[0-9a-f]+$/u.test(value2) || value2.length % 2 !== 0) {
25079
25204
  throw new Error("Invalid hexadecimal value.");
25080
25205
  }
@@ -26359,18 +26484,6 @@ ${end.comment}` : end.comment;
26359
26484
  }
26360
26485
  });
26361
26486
 
26362
- // src/app-host/opening-progress.ts
26363
- function isAppOpeningProgress(value2) {
26364
- return typeof value2 === "string" && stages.includes(value2);
26365
- }
26366
- var stages;
26367
- var init_opening_progress = __esm({
26368
- "src/app-host/opening-progress.ts"() {
26369
- "use strict";
26370
- stages = ["joining", "opening_store", "connecting_log", "syncing", "loading_snapshot", "replaying", "waiting_for_key", "verifying_read", "checking_setup"];
26371
- }
26372
- });
26373
-
26374
26487
  // src/transport/inprocess.ts
26375
26488
  function inProcessConnector(runtime2, options = {}) {
26376
26489
  return {
@@ -29956,9 +30069,9 @@ ${end.comment}` : end.comment;
29956
30069
  }
29957
30070
  });
29958
30071
  }
29959
- column(st, i) {
30072
+ column(st, i, tag) {
29960
30073
  const capi = this.sqlite3.capi;
29961
- switch (capi.sqlite3_column_type(st.pointer, i)) {
30074
+ switch (tag) {
29962
30075
  case SQLITE_NULL:
29963
30076
  return { kind: "Null" };
29964
30077
  case SQLITE_INTEGER: {
@@ -30012,9 +30125,9 @@ ${end.comment}` : end.comment;
30012
30125
  while (st.step()) {
30013
30126
  if (limits && ++rows2 > limits.maxRows) throw new IndexError("Full", "index reply row budget exceeded");
30014
30127
  for (let c = 0; c < columns; c++) {
30128
+ if (limits && ++valueCount > limits.maxValues) throw new IndexError("Full", "index reply value budget exceeded");
30129
+ const tag = capi.sqlite3_column_type(st.pointer, c);
30015
30130
  if (limits) {
30016
- if (++valueCount > limits.maxValues) throw new IndexError("Full", "index reply value budget exceeded");
30017
- const tag = capi.sqlite3_column_type(st.pointer, c);
30018
30131
  if (tag === SQLITE_TEXT || tag === SQLITE_BLOB) {
30019
30132
  addBytes(5);
30020
30133
  addBytes(capi.sqlite3_column_bytes(st.pointer, c));
@@ -30022,7 +30135,7 @@ ${end.comment}` : end.comment;
30022
30135
  else if (tag === SQLITE_NULL) addBytes(1);
30023
30136
  else throw new IndexError("Other", "unknown SQLite value type");
30024
30137
  }
30025
- values.push(this.column(st, c));
30138
+ values.push(this.column(st, c, tag));
30026
30139
  }
30027
30140
  }
30028
30141
  out.push({
@@ -30258,33 +30371,46 @@ ${end.comment}` : end.comment;
30258
30371
  }
30259
30372
  };
30260
30373
  Writer2 = class {
30261
- parts = [];
30374
+ bytes = new Uint8Array(128);
30375
+ view = new DataView(this.bytes.buffer);
30262
30376
  length = 0;
30263
30377
  values = 0;
30264
30378
  constructor(op2) {
30265
30379
  this.put(MAGIC);
30266
30380
  this.byte(op2);
30267
30381
  }
30382
+ reserve(size2) {
30383
+ const start = this.length;
30384
+ const end = start + size2;
30385
+ if (end > APP_INDEX_LIMITS.maxBytes) throw full();
30386
+ if (end > this.bytes.length) {
30387
+ const capacity = Math.min(APP_INDEX_LIMITS.maxBytes, Math.max(end, this.bytes.length * 2));
30388
+ const next = new Uint8Array(capacity);
30389
+ next.set(this.bytes.subarray(0, start));
30390
+ this.bytes = next;
30391
+ this.view = new DataView(next.buffer);
30392
+ }
30393
+ this.length = end;
30394
+ return start;
30395
+ }
30268
30396
  put(b) {
30269
- if (b.length > APP_INDEX_LIMITS.maxBytes - this.length) throw full();
30270
- this.length += b.length;
30271
- this.parts.push(b);
30397
+ const at = this.reserve(b.length);
30398
+ this.bytes.set(b, at);
30272
30399
  }
30273
30400
  byte(n) {
30274
- this.put(Uint8Array.of(n));
30401
+ const at = this.reserve(1);
30402
+ this.bytes[at] = n;
30275
30403
  }
30276
30404
  u32(n) {
30277
30405
  if (!Number.isSafeInteger(n) || n < 0 || n > 4294967295) throw invalid7();
30278
- const b = new Uint8Array(4);
30279
- new DataView(b.buffer).setUint32(0, n, true);
30280
- this.put(b);
30406
+ const at = this.reserve(4);
30407
+ this.view.setUint32(at, n, true);
30281
30408
  }
30282
30409
  int(n, signed) {
30283
30410
  if (typeof n !== "bigint" || n < (signed ? I64_MIN2 : 0n) || n > (signed ? I64_MAX : U64_MAX2)) throw invalid7();
30284
- const b = new Uint8Array(8), v = new DataView(b.buffer);
30285
- if (signed) v.setBigInt64(0, n, true);
30286
- else v.setBigUint64(0, n, true);
30287
- this.put(b);
30411
+ const at = this.reserve(8);
30412
+ if (signed) this.view.setBigInt64(at, n, true);
30413
+ else this.view.setBigUint64(at, n, true);
30288
30414
  }
30289
30415
  data(b) {
30290
30416
  this.u32(b.length);
@@ -30303,9 +30429,8 @@ ${end.comment}` : end.comment;
30303
30429
  case "Real": {
30304
30430
  if (!Number.isFinite(v.value)) throw invalid7();
30305
30431
  this.byte(2);
30306
- const b = new Uint8Array(8);
30307
- new DataView(b.buffer).setFloat64(0, v.value, true);
30308
- this.put(b);
30432
+ const at = this.reserve(8);
30433
+ this.view.setFloat64(at, v.value, true);
30309
30434
  return;
30310
30435
  }
30311
30436
  case "Text":
@@ -30321,13 +30446,7 @@ ${end.comment}` : end.comment;
30321
30446
  }
30322
30447
  }
30323
30448
  done() {
30324
- const out = new Uint8Array(this.length);
30325
- let at = 0;
30326
- for (const part of this.parts) {
30327
- out.set(part, at);
30328
- at += part.length;
30329
- }
30330
- return out;
30449
+ return this.bytes.slice(0, this.length);
30331
30450
  }
30332
30451
  };
30333
30452
  AppBinaryIndexHost = class {
@@ -33877,7 +33996,7 @@ ${end.comment}` : end.comment;
33877
33996
  conflicts.push({
33878
33997
  target: r.target,
33879
33998
  ...canAdopt ? { adoptable: { digest: r.currentDigest } } : {},
33880
- message: canAdopt && seed ? `Your ${thing.bare} has changes that can't be combined with the version this app needs. You can replace it with this app's version.` : canAdopt && r.installed ? `${The} was changed after this app set it up. You can replace it with this app's version.` : canAdopt ? `This collection already has a ${thing.bare} that differs from the one this app needs. You can replace it with this app's version.` : r.installed ? `${The} was changed after this app set it up, so it can't be updated automatically.` : `${The} can't be set up automatically.`
33999
+ message: seed && r.kind === "type" && !r.installed ? `The existing note type at "${r.target}" differs from the one this app needs. ${canAdopt ? "You can replace it with this app's version." : "Change the existing type to support this app, or rename it and update the notes that use it. Then run setup again."}` : canAdopt && seed ? `Your ${thing.bare} has changes that can't be combined with the version this app needs. You can replace it with this app's version.` : canAdopt && r.installed ? `${The} was changed after this app set it up. You can replace it with this app's version.` : canAdopt ? `This collection already has a ${thing.bare} that differs from the one this app needs. You can replace it with this app's version.` : r.installed ? `${The} was changed after this app set it up, so it can't be updated automatically.` : `${The} can't be set up automatically.`
33881
34000
  });
33882
34001
  break;
33883
34002
  }
@@ -33954,7 +34073,7 @@ ${end.comment}` : end.comment;
33954
34073
  name2 = (target2) => (target2.split("/").pop() ?? target2).replace(/\.(md|ya?ml|json)$/i, "");
33955
34074
  plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
33956
34075
  setting = (path) => (path.split("/").filter(Boolean).pop() ?? path).replace(/[_-]+/g, " ");
33957
- UNRESOLVED = "This collection is missing something this app needs, and setup can't add it. A note type this app set up may have been changed or removed. Restore it, then try again.";
34076
+ UNRESOLVED = "This collection is missing a note format this app needs. Add or update a note type that supports that format, then try setup again.";
33958
34077
  }
33959
34078
  });
33960
34079
 
@@ -38914,6 +39033,18 @@ ${end.comment}` : end.comment;
38914
39033
  }
38915
39034
  });
38916
39035
 
39036
+ // src/app-host/opening-progress.ts
39037
+ function isAppOpeningProgress(value2) {
39038
+ return typeof value2 === "string" && stages.includes(value2);
39039
+ }
39040
+ var stages;
39041
+ var init_opening_progress = __esm({
39042
+ "src/app-host/opening-progress.ts"() {
39043
+ "use strict";
39044
+ stages = ["joining", "opening_store", "connecting_log", "syncing", "loading_snapshot", "replaying", "waiting_for_key", "verifying_read", "checking_setup"];
39045
+ }
39046
+ });
39047
+
38917
39048
  // src/application/sign-out.ts
38918
39049
  function pendingWrites(connection) {
38919
39050
  let status = 0, ledger = 0;
@@ -49796,7 +49927,9 @@ ${end.comment}` : end.comment;
49796
49927
  var init_runtime = __esm({
49797
49928
  "src/application/runtime.ts"() {
49798
49929
  "use strict";
49930
+ init_opening_progress();
49799
49931
  init_errors();
49932
+ init_performance_mark();
49800
49933
  init_worker_protocol();
49801
49934
  init_sign_out();
49802
49935
  init_scope();
@@ -49987,7 +50120,12 @@ ${end.comment}` : end.comment;
49987
50120
  }
49988
50121
  } else if (status !== "blocked") this.loggedProblem = null;
49989
50122
  const { problemDetail: _native, ...raw } = this.raw;
49990
- this.snapshot = Object.freeze({ ...raw, ...native ? { problemDetail: native } : {}, status, problem: problem7, openingProgress: status === "opening" ? readiness3.checking ? "checking_setup" : this.raw.openingProgress ?? null : null, collections: Object.freeze(this.raw.collections.map((value2) => Object.freeze({ ...value2 }))), readiness: readiness3 });
50123
+ const openingProgress = status === "opening" ? raw.status === "opening" ? raw.openingProgress ?? null : readiness3.checking ? "checking_setup" : null : null;
50124
+ const previous = this.snapshot;
50125
+ this.snapshot = Object.freeze({ ...raw, ...native ? { problemDetail: native } : {}, status, problem: problem7, openingProgress, collections: Object.freeze(this.raw.collections.map((value2) => Object.freeze({ ...value2 }))), readiness: readiness3 });
50126
+ if (id6 !== null && isAppOpeningProgress(openingProgress) && (previous.selectedCollectionId !== id6 || previous.openingProgress !== openingProgress)) {
50127
+ performanceMark(`mdbase:open:stage:${openingProgress}`);
50128
+ }
49991
50129
  }
49992
50130
  for (const listener of [...this.listeners]) try {
49993
50131
  listener();
@@ -51070,12 +51208,12 @@ ${end.comment}` : end.comment;
51070
51208
  // src/application/asset-pins.json
51071
51209
  var asset_pins_default = {
51072
51210
  runtime: {
51073
- sha256: "051bc364e712b4ad25f58d4649a90624c10a910e35a9066221be4e95cfbfdeaa",
51074
- bytes: 4071435,
51075
- maxBytes: 4071435,
51211
+ sha256: "a27b57d4cb9c978725922af25928bb4242eb9580fa502815ea75993bbe92fe20",
51212
+ bytes: 4135951,
51213
+ maxBytes: 4135951,
51076
51214
  source: {
51077
51215
  repository: "mdbase-dev/mdbase-connect",
51078
- commit: "84f9cec4a0a9f22443a8e0f5b16b682503da0620"
51216
+ commit: "7ed4e0b55a8c1becfc10ddbea55d794543ca1e15"
51079
51217
  }
51080
51218
  },
51081
51219
  sqlite: {
@@ -51129,7 +51267,6 @@ ${end.comment}` : end.comment;
51129
51267
  }
51130
51268
 
51131
51269
  // src/application/startup-timing.ts
51132
- init_opening_progress();
51133
51270
  init_performance_mark();
51134
51271
  var PREFIX = "mdbase:startup:";
51135
51272
  var WAITS = /* @__PURE__ */ new Set(["signed_out", "authorizing", "choosing", "needs_approval", "needs_setup", "problem", "unavailable", "closed"]);
@@ -51182,10 +51319,6 @@ ${end.comment}` : end.comment;
51182
51319
  if (changed3) performanceMark("mdbase:open:requested");
51183
51320
  if (selection.requested.approved && (changed3 || !previous?.selection.requested.approved)) performanceMark("mdbase:open:approved");
51184
51321
  }
51185
- if (phase.kind === "opening" && isAppOpeningProgress(phase.progress)) {
51186
- const prev = previous?.phase.kind === "opening" && previous.phase.collectionId === phase.collectionId ? previous.phase.progress : null;
51187
- if (prev !== phase.progress) performanceMark(`mdbase:open:stage:${phase.progress}`);
51188
- }
51189
51322
  if (phase.kind === "ready" && (previous?.phase.kind !== "ready" || previous.phase.connection !== phase.connection)) performanceMark("mdbase:open:ready");
51190
51323
  }
51191
51324
 
@@ -55143,7 +55276,7 @@ ${end.comment}` : end.comment;
55143
55276
  * sign-in gesture; a pending ledger keeps its SAME request for authorize(). */
55144
55277
  start() {
55145
55278
  return this.operation(async () => {
55146
- if (this.flow && this.base.status !== "blocked") return this.getSnapshot();
55279
+ if (this.flow && (this.base.status !== "blocked" || this.base.problem === "installation_removed")) return this.getSnapshot();
55147
55280
  this.publish({ status: "starting", problem: null, signOutResult: null });
55148
55281
  const p = this.options;
55149
55282
  this.flow ??= await AppProtectedInstallationSignIn.open({
@@ -55180,6 +55313,7 @@ ${end.comment}` : end.comment;
55180
55313
  * exchange, confirmation or attestation controls are needed by consumers. */
55181
55314
  authorize(options = {}) {
55182
55315
  this.check();
55316
+ if (this.base.problem === "installation_removed") return Promise.reject(failure2("refused"));
55183
55317
  if (this.authorizationRateLimit && Date.now() < this.authorizationRetryAt) return Promise.reject(this.authorizationRateLimit);
55184
55318
  const poll = this.pending !== null && this.pending === this.polling ? this.pending : null;
55185
55319
  if (!this.flow || this.pending && !poll) return Promise.reject(failure2("busy"));
@@ -55217,7 +55351,14 @@ ${end.comment}` : end.comment;
55217
55351
  await this.openDevice();
55218
55352
  this.check();
55219
55353
  await this.abandonUnfinishedNativeChoice();
55220
- const consent = await this.flow.startCollectionConsent(this.installation, this.options.requestedCreateCollections ?? this.options.freshRequestedCreateCollections ?? false, hint, this.options.freshRequestedPrivateDevice === true);
55354
+ let consent;
55355
+ try {
55356
+ consent = await this.flow.startCollectionConsent(this.installation, this.options.requestedCreateCollections ?? this.options.freshRequestedCreateCollections ?? false, hint, this.options.freshRequestedPrivateDevice === true);
55357
+ } catch (error5) {
55358
+ if (!await this.handleRemovedInstallation(error5)) throw error5;
55359
+ portal.close();
55360
+ return this.getSnapshot();
55361
+ }
55221
55362
  this.check();
55222
55363
  this.consentPending = true;
55223
55364
  portal.navigate(consent.verificationUri);
@@ -55613,7 +55754,13 @@ ${end.comment}` : end.comment;
55613
55754
  /** `kept`: this installation's last listing instead of a read. It is not an
55614
55755
  * accepted inventory, so an approval missing from it is not a removal. */
55615
55756
  async refreshCollections(kept = null) {
55616
- const collections = kept ?? await this.flow.listApprovedCollections(this.installation);
55757
+ let collections;
55758
+ try {
55759
+ collections = kept ?? await this.flow.listApprovedCollections(this.installation);
55760
+ } catch (error5) {
55761
+ if (await this.handleRemovedInstallation(error5)) return;
55762
+ throw error5;
55763
+ }
55617
55764
  this.check();
55618
55765
  this.listCached = kept !== null;
55619
55766
  if (!kept) {
@@ -55639,6 +55786,25 @@ ${end.comment}` : end.comment;
55639
55786
  if (this.freshApproval && picked && visible.some((c) => c.collectionId === picked)) await this.openSlot(picked, true);
55640
55787
  else if (visible.length === 1) await this.openSlot(visible[0].collectionId, true);
55641
55788
  }
55789
+ /** Only Connect's exact refusal of this installation's own bearer ends
55790
+ * access across its scopes. Keep the ledger for explicit, per-scope recovery. */
55791
+ async handleRemovedInstallation(error5) {
55792
+ if (!(error5 instanceof AppInstallationSignInError) || !isAppServerProblem(error5.server) || error5.server.status !== 401 || error5.server.code !== "invalid_connector") return false;
55793
+ this.check();
55794
+ this.listCached = false;
55795
+ for (const id6 of this.flow.view().collectionIds) this.removedScopes.add(id6);
55796
+ this.consentPending = false;
55797
+ this.closeApprovalWindow();
55798
+ for (const slot of this.slots.values()) {
55799
+ slot.usable = false;
55800
+ slot.lifetime?.abort();
55801
+ }
55802
+ this.publish({ status: "blocked", problem: "installation_removed", problemDetail: webSignInProblem(error5).detail, collections: Object.freeze([]) });
55803
+ await this.closeSlots();
55804
+ this.check();
55805
+ this.changed();
55806
+ return true;
55807
+ }
55642
55808
  schedulePoll() {
55643
55809
  if (this.pending && !this.closing && !this.options.signal.aborted) return;
55644
55810
  const read2 = this.foregroundRead;
@@ -56104,8 +56270,8 @@ ${end.comment}` : end.comment;
56104
56270
  collectionListCached() {
56105
56271
  return this.listCached;
56106
56272
  }
56107
- /** Accepted COMPLETE inventory omission or terminal native/log refusal only.
56108
- * Local Forget, failed GETs and transient transport failures do not qualify. */
56273
+ /** A complete inventory omission, a terminal scope refusal, or rejection of
56274
+ * the installation's bearer. Transport and unrelated HTTP failures stay separate. */
56109
56275
  scopeWasRemoved(collectionId) {
56110
56276
  return this.removedScopes.has(collectionId);
56111
56277
  }