@crvouga/mockingbird-runtime 0.0.0-reserved → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +130 -1
  2. package/dist/adapter-node.d.ts +2521 -0
  3. package/dist/adapter-node.js +6920 -0
  4. package/dist/adapter-node.js.map +7 -0
  5. package/dist/admin-ui.js +25 -0
  6. package/dist/admin-ui.js.map +7 -0
  7. package/dist/chunk-2KDYLZXC.js +118 -0
  8. package/dist/chunk-2KDYLZXC.js.map +7 -0
  9. package/dist/chunk-2Y25NPCV.js +1289 -0
  10. package/dist/chunk-2Y25NPCV.js.map +7 -0
  11. package/dist/chunk-4SAK6MQT.js +246 -0
  12. package/dist/chunk-4SAK6MQT.js.map +7 -0
  13. package/dist/chunk-ANCCZFF2.js +778 -0
  14. package/dist/chunk-ANCCZFF2.js.map +7 -0
  15. package/dist/chunk-EBGYPQPA.js +198 -0
  16. package/dist/chunk-EBGYPQPA.js.map +7 -0
  17. package/dist/chunk-EQLY2YOA.js +274 -0
  18. package/dist/chunk-EQLY2YOA.js.map +7 -0
  19. package/dist/chunk-G62YDIIJ.js +7664 -0
  20. package/dist/chunk-G62YDIIJ.js.map +7 -0
  21. package/dist/chunk-HU6IOAFC.js +437 -0
  22. package/dist/chunk-HU6IOAFC.js.map +7 -0
  23. package/dist/chunk-RNAHPNUJ.js +97 -0
  24. package/dist/chunk-RNAHPNUJ.js.map +7 -0
  25. package/dist/chunk-UP4QOSFD.js +87 -0
  26. package/dist/chunk-UP4QOSFD.js.map +7 -0
  27. package/dist/chunk-XNS34BPF.js +2489 -0
  28. package/dist/chunk-XNS34BPF.js.map +7 -0
  29. package/dist/core.d.ts +356 -0
  30. package/dist/core.js +51 -0
  31. package/dist/core.js.map +7 -0
  32. package/dist/crypto-XS5XCMRJ.js +21 -0
  33. package/dist/crypto-XS5XCMRJ.js.map +7 -0
  34. package/dist/helpers-UD7CG4WQ.js +18 -0
  35. package/dist/helpers-UD7CG4WQ.js.map +7 -0
  36. package/dist/http-codec.d.ts +72 -0
  37. package/dist/http-codec.js +25 -0
  38. package/dist/http-codec.js.map +7 -0
  39. package/dist/http-provider.d.ts +3243 -0
  40. package/dist/http-provider.js +37920 -0
  41. package/dist/http-provider.js.map +7 -0
  42. package/dist/index.d.ts +10 -0
  43. package/dist/index.js +23 -0
  44. package/dist/index.js.map +7 -0
  45. package/dist/mqtt-broker/node.d.ts +632 -0
  46. package/dist/mqtt-broker/node.js +355 -0
  47. package/dist/mqtt-broker/node.js.map +7 -0
  48. package/dist/mqtt-broker.d.ts +990 -0
  49. package/dist/mqtt-broker.js +913 -0
  50. package/dist/mqtt-broker.js.map +7 -0
  51. package/dist/openapi-metadata.d.ts +290 -0
  52. package/dist/openapi-metadata.js +28 -0
  53. package/dist/openapi-metadata.js.map +7 -0
  54. package/dist/openapi.d.ts +252 -0
  55. package/dist/openapi.js +45 -0
  56. package/dist/openapi.js.map +7 -0
  57. package/dist/preview/artifacts.d.ts +19 -0
  58. package/dist/preview/artifacts.js +40 -0
  59. package/dist/preview/artifacts.js.map +7 -0
  60. package/dist/preview/bridge.d.ts +21 -0
  61. package/dist/preview/bridge.js +9 -0
  62. package/dist/preview/bridge.js.map +7 -0
  63. package/dist/preview/harness.d.ts +12 -0
  64. package/dist/preview/harness.js +65 -0
  65. package/dist/preview/harness.js.map +7 -0
  66. package/dist/preview/host.d.ts +30 -0
  67. package/dist/preview/host.js +70 -0
  68. package/dist/preview/host.js.map +7 -0
  69. package/dist/service/admin.d.ts +106 -0
  70. package/dist/service/admin.js +340 -0
  71. package/dist/service/admin.js.map +7 -0
  72. package/dist/service.d.ts +2665 -0
  73. package/dist/service.js +264 -0
  74. package/dist/service.js.map +7 -0
  75. package/dist/sqlite.d.ts +69 -0
  76. package/dist/sqlite.js +19 -0
  77. package/dist/sqlite.js.map +7 -0
  78. package/dist/ui.d.ts +37 -0
  79. package/dist/ui.js +702 -0
  80. package/dist/ui.js.map +7 -0
  81. package/package.json +130 -6
@@ -0,0 +1,1289 @@
1
+ // ../core/dist/durability.js
2
+ function withDurability(api, durable) {
3
+ let queue = Promise.resolve();
4
+ return {
5
+ fetch(request) {
6
+ const next = queue.then(async () => {
7
+ const response = await api.fetch(request);
8
+ await durable.flush();
9
+ return response;
10
+ });
11
+ queue = next.catch(() => {
12
+ });
13
+ return next;
14
+ }
15
+ };
16
+ }
17
+ var DurabilityConflictError = class extends Error {
18
+ constructor() {
19
+ super("Durable image changed in another writer; reopen before saving");
20
+ this.name = "DurabilityConflictError";
21
+ }
22
+ };
23
+ async function openDurable(options) {
24
+ const { backend, key, codec } = options;
25
+ const pageSize = options.pageSize ?? 16384;
26
+ if (!Number.isSafeInteger(pageSize) || pageSize < 1)
27
+ throw new RangeError("Invalid page size");
28
+ const image = await backend.load(key);
29
+ let previous = image ? new Uint8Array(image.bytes) : new Uint8Array();
30
+ const value = image ? codec.decode(image.bytes) : codec.create();
31
+ let revision = image?.revision ?? 0;
32
+ let storedPageSize = image?.pageSize ?? pageSize;
33
+ let queue = Promise.resolve();
34
+ let closing = false;
35
+ let closed = false;
36
+ function enqueue(run) {
37
+ if (closed || closing)
38
+ return Promise.reject(new Error("Durable handle is closed"));
39
+ const next = queue.then(run);
40
+ queue = next.catch(() => {
41
+ });
42
+ return next;
43
+ }
44
+ async function persist() {
45
+ const bytes = codec.encode(value);
46
+ const byteLength = bytes.length;
47
+ const changedPages = [];
48
+ let changedBytes = 0;
49
+ const words = bytes.byteOffset % 4 === 0 ? new Uint32Array(bytes.buffer, bytes.byteOffset, Math.floor(byteLength / 4)) : null;
50
+ const previousWords = new Uint32Array(previous.buffer, previous.byteOffset, Math.floor(previous.length / 4));
51
+ for (let offset = 0; offset < byteLength; offset += pageSize) {
52
+ const end = Math.min(offset + pageSize, byteLength);
53
+ let changed = storedPageSize !== pageSize || Math.min(pageSize, previous.length - offset) !== end - offset;
54
+ if (!changed)
55
+ changed = !equalPage(bytes, previous, words, previousWords, offset, end);
56
+ if (changed) {
57
+ changedPages.push(offset / pageSize);
58
+ changedBytes += end - offset;
59
+ }
60
+ }
61
+ if (revision !== 0 && changedPages.length === 0 && byteLength === previous.length && storedPageSize === pageSize)
62
+ return;
63
+ const replacement = previous.length !== byteLength || changedBytes >= byteLength / 2 ? new Uint8Array(bytes) : void 0;
64
+ const pages = changedPages.map((index) => {
65
+ const offset = index * pageSize;
66
+ const end = Math.min(offset + pageSize, byteLength);
67
+ return {
68
+ index,
69
+ // Buffer.slice returns a borrowed view; the TypedArray operation owns its result.
70
+ bytes: replacement ? replacement.subarray(offset, end) : Uint8Array.prototype.slice.call(bytes, offset, end)
71
+ };
72
+ });
73
+ revision = await backend.commit(key, revision, { byteLength, pageSize, pages });
74
+ if (replacement)
75
+ previous = replacement;
76
+ else
77
+ for (const page of pages)
78
+ previous.set(page.bytes, page.index * pageSize);
79
+ storedPageSize = pageSize;
80
+ }
81
+ return {
82
+ value,
83
+ flush: () => enqueue(persist),
84
+ write: (run) => enqueue(async () => {
85
+ const result = run(value);
86
+ if (result && typeof result.then === "function") {
87
+ throw new TypeError("Durable write callbacks must be synchronous");
88
+ }
89
+ await persist();
90
+ return result;
91
+ }),
92
+ close() {
93
+ if (closed)
94
+ return Promise.resolve();
95
+ if (closing)
96
+ return queue;
97
+ const next = enqueue(async () => {
98
+ await persist();
99
+ await codec.close?.(value);
100
+ closed = true;
101
+ });
102
+ closing = true;
103
+ const completion = next.catch((error) => {
104
+ closing = false;
105
+ queue = Promise.resolve();
106
+ throw error;
107
+ });
108
+ queue = completion;
109
+ return completion;
110
+ }
111
+ };
112
+ }
113
+ function equalPage(left, right, leftWords, rightWords, start, end) {
114
+ let offset = start;
115
+ if (!leftWords) {
116
+ for (; offset < end; offset++)
117
+ if (left[offset] !== right[offset])
118
+ return false;
119
+ return true;
120
+ }
121
+ while (offset < end && offset % 4 !== 0) {
122
+ if (left[offset] !== right[offset])
123
+ return false;
124
+ offset++;
125
+ }
126
+ const wordEnd = Math.floor(end / 4);
127
+ let word = offset / 4;
128
+ for (; word + 4 <= wordEnd; word += 4) {
129
+ if (leftWords[word] !== rightWords[word] || leftWords[word + 1] !== rightWords[word + 1] || leftWords[word + 2] !== rightWords[word + 2] || leftWords[word + 3] !== rightWords[word + 3])
130
+ return false;
131
+ }
132
+ for (; word < wordEnd; word++) {
133
+ if (leftWords[word] !== rightWords[word])
134
+ return false;
135
+ }
136
+ offset = word * 4;
137
+ while (offset < end) {
138
+ if (left[offset] !== right[offset])
139
+ return false;
140
+ offset++;
141
+ }
142
+ return true;
143
+ }
144
+ function applyDurablePatch(previous, patch) {
145
+ validateDurablePatch(patch);
146
+ const bytes = new Uint8Array(patch.byteLength);
147
+ bytes.set(previous.subarray(0, bytes.length));
148
+ for (const page of patch.pages)
149
+ bytes.set(page.bytes, page.index * patch.pageSize);
150
+ return bytes;
151
+ }
152
+ function validateDurablePatch(patch) {
153
+ if (!Number.isSafeInteger(patch.byteLength) || patch.byteLength < 0 || !Number.isSafeInteger(patch.pageSize) || patch.pageSize < 1) {
154
+ throw new RangeError("Invalid durable patch dimensions");
155
+ }
156
+ const seen = /* @__PURE__ */ new Set();
157
+ for (const page of patch.pages) {
158
+ const offset = page.index * patch.pageSize;
159
+ if (!Number.isSafeInteger(page.index) || page.index < 0 || offset >= patch.byteLength || page.bytes.length !== Math.min(patch.pageSize, patch.byteLength - offset) || seen.has(page.index)) {
160
+ throw new RangeError("Invalid durable page");
161
+ }
162
+ seen.add(page.index);
163
+ }
164
+ }
165
+ function validateDurableCommit(patch, previous) {
166
+ validateDurablePatch(patch);
167
+ const supplied = new Set(patch.pages.map((page) => page.index));
168
+ const count = Math.ceil(patch.byteLength / patch.pageSize);
169
+ let start = count;
170
+ if (!previous || previous.pageSize !== patch.pageSize)
171
+ start = 0;
172
+ else if (patch.byteLength > previous.byteLength)
173
+ start = Math.floor(previous.byteLength / patch.pageSize);
174
+ else if (patch.byteLength < previous.byteLength && patch.byteLength % patch.pageSize !== 0)
175
+ start = count - 1;
176
+ for (let index = start; index < count; index++) {
177
+ if (!supplied.has(index))
178
+ throw new RangeError("Missing durable page");
179
+ }
180
+ }
181
+ var MemoryDurabilityBackend = class {
182
+ images = /* @__PURE__ */ new Map();
183
+ async load(key) {
184
+ const image = this.images.get(key);
185
+ return image && { ...image, bytes: image.bytes.slice() };
186
+ }
187
+ async commit(key, expectedRevision, patch) {
188
+ const previous = this.images.get(key);
189
+ if ((previous?.revision ?? 0) !== expectedRevision)
190
+ throw new DurabilityConflictError();
191
+ validateDurableCommit(patch, previous && { byteLength: previous.bytes.length, pageSize: previous.pageSize });
192
+ const revision = expectedRevision + 1;
193
+ this.images.set(key, {
194
+ revision,
195
+ pageSize: patch.pageSize,
196
+ bytes: applyDurablePatch(previous?.bytes ?? new Uint8Array(), patch)
197
+ });
198
+ return revision;
199
+ }
200
+ };
201
+
202
+ // ../core/dist/durability-browser.js
203
+ var browserDurabilityLifecycle = {
204
+ subscribe(onSuspend) {
205
+ if (typeof globalThis.addEventListener !== "function")
206
+ return () => {
207
+ };
208
+ globalThis.addEventListener("pagehide", onSuspend);
209
+ return () => globalThis.removeEventListener("pagehide", onSuspend);
210
+ }
211
+ };
212
+ var IndexedDBDurabilityBackend = class {
213
+ database;
214
+ factory;
215
+ name;
216
+ durability;
217
+ constructor(options = {}) {
218
+ this.factory = options.indexedDB ?? globalThis.indexedDB;
219
+ if (!this.factory)
220
+ throw new Error("IndexedDB is unavailable; inject a durability backend");
221
+ this.name = options.name ?? "mockingbird";
222
+ this.durability = options.durability ?? "strict";
223
+ }
224
+ open() {
225
+ if (this.database)
226
+ return this.database;
227
+ const opening = new Promise((resolve, reject) => {
228
+ const forget = () => {
229
+ if (this.database === opening)
230
+ this.database = void 0;
231
+ };
232
+ const request = this.factory.open(this.name, 1);
233
+ request.onupgradeneeded = () => {
234
+ const db = request.result;
235
+ db.createObjectStore("images");
236
+ const pages = db.createObjectStore("pages", { keyPath: ["key", "index"] });
237
+ pages.createIndex("image", "key");
238
+ };
239
+ request.onerror = () => {
240
+ forget();
241
+ reject(request.error);
242
+ };
243
+ request.onblocked = () => {
244
+ };
245
+ request.onsuccess = () => {
246
+ const db = request.result;
247
+ db.onversionchange = () => {
248
+ db.close();
249
+ forget();
250
+ };
251
+ db.onclose = forget;
252
+ resolve(db);
253
+ };
254
+ });
255
+ this.database = opening;
256
+ return opening;
257
+ }
258
+ async load(key) {
259
+ const db = await this.open();
260
+ return new Promise((resolve, reject) => {
261
+ const tx = db.transaction(["images", "pages"], "readonly");
262
+ let image;
263
+ let failure;
264
+ tx.onabort = () => reject(failure ?? tx.error);
265
+ tx.oncomplete = () => resolve(image);
266
+ const meta = tx.objectStore("images").get(key);
267
+ meta.onsuccess = () => {
268
+ const info = meta.result;
269
+ if (!info)
270
+ return;
271
+ const request = tx.objectStore("pages").index("image").getAll(key);
272
+ request.onsuccess = () => {
273
+ try {
274
+ const bytes = new Uint8Array(info.byteLength);
275
+ const pages = request.result;
276
+ if (pages.length !== Math.ceil(info.byteLength / info.pageSize)) {
277
+ throw new Error("Incomplete durable image");
278
+ }
279
+ const patch = {
280
+ ...info,
281
+ pages: pages.map((page) => ({ index: page.index, bytes: page.bytes }))
282
+ };
283
+ validateDurablePatch(patch);
284
+ for (const page of pages)
285
+ bytes.set(page.bytes, page.index * info.pageSize);
286
+ image = { revision: info.revision, pageSize: info.pageSize, bytes };
287
+ } catch (error) {
288
+ failure = error;
289
+ tx.abort();
290
+ }
291
+ };
292
+ };
293
+ });
294
+ }
295
+ async commit(key, expectedRevision, patch) {
296
+ validateDurablePatch(patch);
297
+ const db = await this.open();
298
+ return new Promise((resolve, reject) => {
299
+ const tx = db.transaction(["images", "pages"], "readwrite", { durability: this.durability });
300
+ let failure;
301
+ tx.onabort = () => reject(failure ?? tx.error);
302
+ tx.oncomplete = () => resolve(expectedRevision + 1);
303
+ const images = tx.objectStore("images");
304
+ const pages = tx.objectStore("pages");
305
+ const request = images.get(key);
306
+ request.onsuccess = () => {
307
+ try {
308
+ const previous = request.result;
309
+ if ((previous?.revision ?? 0) !== expectedRevision) {
310
+ failure = new DurabilityConflictError();
311
+ tx.abort();
312
+ return;
313
+ }
314
+ validateDurableCommit(patch, previous);
315
+ const oldCount = previous ? Math.ceil(previous.byteLength / previous.pageSize) : 0;
316
+ const newCount = Math.ceil(patch.byteLength / patch.pageSize);
317
+ for (let index = newCount; index < oldCount; index++)
318
+ pages.delete([key, index]);
319
+ for (const page of patch.pages) {
320
+ const bytes = page.bytes.byteOffset === 0 && page.bytes.byteLength === page.bytes.buffer.byteLength ? page.bytes : new Uint8Array(page.bytes);
321
+ pages.put({ key, index: page.index, bytes });
322
+ }
323
+ images.put({
324
+ revision: expectedRevision + 1,
325
+ byteLength: patch.byteLength,
326
+ pageSize: patch.pageSize
327
+ }, key);
328
+ } catch (error) {
329
+ failure = error;
330
+ tx.abort();
331
+ }
332
+ };
333
+ });
334
+ }
335
+ /** Release this adapter's connection; does not delete any saved images. */
336
+ async close() {
337
+ const opening = this.database;
338
+ this.database = void 0;
339
+ if (opening)
340
+ (await opening).close();
341
+ }
342
+ };
343
+ var LocalStorageDurabilityBackend = class {
344
+ storage;
345
+ prefix;
346
+ locks;
347
+ constructor(options = {}) {
348
+ this.storage = options.storage ?? globalThis.localStorage;
349
+ if (!this.storage)
350
+ throw new Error("localStorage is unavailable; inject a durability backend");
351
+ this.prefix = options.prefix ?? "mockingbird:";
352
+ this.locks = options.locks ?? globalThis.navigator?.locks;
353
+ }
354
+ async load(key) {
355
+ return this.read(key);
356
+ }
357
+ read(key) {
358
+ const text = this.storage.getItem(this.prefix + key);
359
+ if (text === null)
360
+ return void 0;
361
+ const image = JSON.parse(text);
362
+ const binary = atob(image.data);
363
+ const bytes = new Uint8Array(binary.length);
364
+ for (let i = 0; i < binary.length; i++)
365
+ bytes[i] = binary.charCodeAt(i);
366
+ return { revision: image.revision, pageSize: image.pageSize, bytes };
367
+ }
368
+ async commit(key, expectedRevision, patch) {
369
+ const save = () => {
370
+ const previous = this.read(key);
371
+ if ((previous?.revision ?? 0) !== expectedRevision)
372
+ throw new DurabilityConflictError();
373
+ validateDurableCommit(patch, previous && { byteLength: previous.bytes.length, pageSize: previous.pageSize });
374
+ const bytes = applyDurablePatch(previous?.bytes ?? new Uint8Array(), patch);
375
+ let binary = "";
376
+ for (let offset = 0; offset < bytes.length; offset += 8192) {
377
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
378
+ }
379
+ const revision = expectedRevision + 1;
380
+ this.storage.setItem(this.prefix + key, JSON.stringify({ revision, pageSize: patch.pageSize, data: btoa(binary) }));
381
+ return revision;
382
+ };
383
+ return this.locks ? this.locks.request(this.prefix + key, save) : save();
384
+ }
385
+ };
386
+
387
+ // ../core/dist/durability-buffered.js
388
+ var HEADER = 32;
389
+ var MAGIC = [77, 66, 68, 74];
390
+ function isDurableJournal(bytes) {
391
+ return MAGIC.every((byte, index) => bytes[index] === byte);
392
+ }
393
+ function checksum(bytes) {
394
+ let hash = 2166136261;
395
+ for (const byte of bytes)
396
+ hash = Math.imul(hash ^ byte, 16777619);
397
+ return hash >>> 0;
398
+ }
399
+ function header(checkpointBytes, hash) {
400
+ if (checkpointBytes > 4294967295)
401
+ throw new RangeError("Buffered checkpoint exceeds 4 GiB");
402
+ const bytes = new Uint8Array(HEADER);
403
+ bytes.set(MAGIC);
404
+ const view = new DataView(bytes.buffer);
405
+ view.setUint32(4, 1, true);
406
+ view.setUint32(8, checkpointBytes, true);
407
+ view.setUint32(20, hash, true);
408
+ view.setUint32(24, checksum(bytes.subarray(0, 24)), true);
409
+ return bytes;
410
+ }
411
+ function encodeDurableCheckpoint(record) {
412
+ const bytes = new Uint8Array(HEADER + record.length);
413
+ bytes.set(header(record.length, checksum(record)));
414
+ bytes.set(record, HEADER);
415
+ return bytes;
416
+ }
417
+ function readDurableJournal(bytes) {
418
+ if (!isDurableJournal(bytes))
419
+ return void 0;
420
+ const bad = () => {
421
+ throw new Error("Invalid buffered durability image");
422
+ };
423
+ if (bytes.length < HEADER)
424
+ return bad();
425
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
426
+ const checkpointBytes = view.getUint32(8, true);
427
+ if (view.getUint32(4, true) !== 1 || view.getUint32(12, true) !== 0 || view.getUint32(16, true) !== 0 || view.getUint32(24, true) !== checksum(bytes.subarray(0, 24)) || HEADER + checkpointBytes > bytes.length)
428
+ return bad();
429
+ const checkpoint = bytes.subarray(HEADER, HEADER + checkpointBytes);
430
+ if (checksum(checkpoint) !== view.getUint32(20, true))
431
+ return bad();
432
+ const records = [checkpoint];
433
+ let offset = HEADER + checkpointBytes;
434
+ while (offset < bytes.length) {
435
+ if (offset + 8 > bytes.length)
436
+ return bad();
437
+ const length = view.getUint32(offset, true);
438
+ const hash = view.getUint32(offset + 4, true);
439
+ offset += 8;
440
+ if (offset + length > bytes.length)
441
+ return bad();
442
+ const record = bytes.subarray(offset, offset + length);
443
+ if (checksum(record) !== hash)
444
+ return bad();
445
+ records.push(record);
446
+ offset += length;
447
+ }
448
+ if (offset !== bytes.length)
449
+ return bad();
450
+ return records;
451
+ }
452
+ var timers = {
453
+ schedule(run, delay) {
454
+ const timer = setTimeout(run, delay);
455
+ timer.unref?.();
456
+ return timer;
457
+ },
458
+ cancel(timer) {
459
+ clearTimeout(timer);
460
+ }
461
+ };
462
+ async function openBufferedDurable(options) {
463
+ const { backend, key, codec } = options;
464
+ const pageSize = options.pageSize ?? 16384;
465
+ const interval = options.flushIntervalMs ?? 1e3;
466
+ const maxBatches = options.compactAfterBatches ?? 256;
467
+ if (!Number.isSafeInteger(pageSize) || pageSize < 1 || !Number.isSafeInteger(interval) || interval < 1 || !Number.isSafeInteger(maxBatches) || maxBatches < 1 || options.compactAfterBytes !== void 0 && (!Number.isSafeInteger(options.compactAfterBytes) || options.compactAfterBytes < 1))
468
+ throw new RangeError("Invalid buffered durability options");
469
+ const scheduler = options.scheduler ?? timers;
470
+ const image = await backend.load(key);
471
+ const records = image && readDurableJournal(image.bytes);
472
+ const value = image ? records ? codec.decodeJournal(records) : codec.decode(image.bytes) : codec.create();
473
+ let revision = image?.revision ?? 0;
474
+ let length = records && image ? image.bytes.length : 0;
475
+ let baseLength = records?.[0]?.length ?? 0;
476
+ let baseHash = records?.[0] ? checksum(records[0]) : 0;
477
+ let batches = records ? records.length - 1 : 0;
478
+ let tail = records && image ? new Uint8Array(image.bytes.subarray(Math.floor((length - 1) / pageSize) * pageSize)) : new Uint8Array();
479
+ let checkpointRequired = !records || image?.pageSize !== pageSize;
480
+ let previous;
481
+ if (records)
482
+ previous = codec.baseline ? codec.baseline(value) : codec.capture(value, void 0, true).token;
483
+ let generation = 0;
484
+ let saved = 0;
485
+ let queued = 0;
486
+ let inWrite = false;
487
+ let closing = false;
488
+ let closed = false;
489
+ let conflict;
490
+ let lastError;
491
+ let exposed = false;
492
+ let timer;
493
+ let timerActive = false;
494
+ let retryDelay = interval;
495
+ let queue = Promise.resolve();
496
+ function cancel() {
497
+ if (timerActive)
498
+ scheduler.cancel(timer);
499
+ timerActive = false;
500
+ }
501
+ function schedule(delay = interval) {
502
+ if (timerActive || closing || closed || conflict)
503
+ return;
504
+ timerActive = true;
505
+ timer = scheduler.schedule(() => {
506
+ timerActive = false;
507
+ if (!codec.canCapture(value)) {
508
+ schedule();
509
+ return;
510
+ }
511
+ void enqueue(() => persist()).catch(() => {
512
+ });
513
+ }, delay);
514
+ }
515
+ function failure(error) {
516
+ lastError = error;
517
+ if (error instanceof DurabilityConflictError || typeof error === "object" && error !== null && "name" in error && error.name === "DurabilityConflictError") {
518
+ conflict = error;
519
+ cancel();
520
+ stopLifecycle?.();
521
+ } else {
522
+ schedule(retryDelay);
523
+ retryDelay = Math.min(1e4, Math.max(1e3, retryDelay * 2));
524
+ }
525
+ try {
526
+ options.onError?.(error);
527
+ } catch {
528
+ }
529
+ }
530
+ function enqueue(run) {
531
+ if (closed || closing)
532
+ return Promise.reject(new Error("Durable handle is closed"));
533
+ if (conflict)
534
+ return Promise.reject(conflict);
535
+ queued++;
536
+ const next = queue.then(run).finally(() => {
537
+ queued--;
538
+ });
539
+ queue = next.catch(() => {
540
+ });
541
+ return next;
542
+ }
543
+ async function persist(force = false) {
544
+ if (conflict)
545
+ throw conflict;
546
+ cancel();
547
+ if (!checkpointRequired && generation === saved && !exposed && !force)
548
+ return;
549
+ const at = generation;
550
+ try {
551
+ const checkpoint = checkpointRequired || batches >= maxBatches || length - HEADER - baseLength >= (options.compactAfterBytes ?? Math.max(4 * 1024 * 1024, baseLength));
552
+ const capture = codec.capture(value, previous, checkpoint || exposed);
553
+ if (!capture.bytes) {
554
+ previous = capture.token;
555
+ saved = at;
556
+ codec.acknowledge(value, capture.token);
557
+ lastError = void 0;
558
+ retryDelay = interval;
559
+ return;
560
+ }
561
+ const payload = capture.bytes;
562
+ let patch;
563
+ let nextLength;
564
+ let nextBase = baseLength;
565
+ let nextHash = baseHash;
566
+ let nextBatches = batches;
567
+ if (capture.checkpoint) {
568
+ nextBase = payload.length;
569
+ nextHash = checksum(payload);
570
+ nextBatches = 0;
571
+ nextLength = HEADER + payload.length;
572
+ const bytes = new Uint8Array(nextLength);
573
+ bytes.set(header(nextBase, nextHash));
574
+ bytes.set(payload, HEADER);
575
+ const pages = [];
576
+ for (let offset = 0; offset < bytes.length; offset += pageSize)
577
+ pages.push({ index: offset / pageSize, bytes: bytes.subarray(offset, offset + pageSize) });
578
+ patch = { byteLength: nextLength, pageSize, pages };
579
+ } else {
580
+ const frame = new Uint8Array(8 + payload.length);
581
+ const view = new DataView(frame.buffer);
582
+ view.setUint32(0, payload.length, true);
583
+ view.setUint32(4, checksum(payload), true);
584
+ frame.set(payload, 8);
585
+ nextLength = length + frame.length;
586
+ nextBatches++;
587
+ const pages = /* @__PURE__ */ new Map();
588
+ let offset = length;
589
+ while (offset < nextLength) {
590
+ const index = Math.floor(offset / pageSize);
591
+ const start = index * pageSize;
592
+ let page = pages.get(index);
593
+ if (!page) {
594
+ page = new Uint8Array(Math.min(pageSize, nextLength - start));
595
+ if (index === Math.floor((length - 1) / pageSize))
596
+ page.set(tail);
597
+ pages.set(index, page);
598
+ }
599
+ const count = Math.min(page.length - (offset - start), nextLength - offset);
600
+ page.set(frame.subarray(offset - length, offset - length + count), offset - start);
601
+ offset += count;
602
+ }
603
+ patch = {
604
+ byteLength: nextLength,
605
+ pageSize,
606
+ pages: [...pages].map(([index, bytes]) => ({ index, bytes }))
607
+ };
608
+ }
609
+ const lastPage = patch.pages.find((page) => page.index === Math.floor((nextLength - 1) / pageSize));
610
+ if (!lastPage)
611
+ throw new Error("Missing buffered tail page");
612
+ const nextTail = lastPage.bytes.byteOffset === 0 && lastPage.bytes.byteLength === lastPage.bytes.buffer.byteLength ? lastPage.bytes : new Uint8Array(lastPage.bytes);
613
+ revision = await backend.commit(key, revision, patch);
614
+ tail = nextTail;
615
+ length = nextLength;
616
+ baseLength = nextBase;
617
+ baseHash = nextHash;
618
+ batches = nextBatches;
619
+ previous = capture.token;
620
+ checkpointRequired = false;
621
+ codec.acknowledge(value, capture.token);
622
+ saved = at;
623
+ lastError = void 0;
624
+ retryDelay = interval;
625
+ } catch (error) {
626
+ failure(error);
627
+ throw error;
628
+ } finally {
629
+ if (generation !== saved || exposed)
630
+ schedule();
631
+ }
632
+ }
633
+ let unsubscribe = () => {
634
+ };
635
+ let stopLifecycle;
636
+ unsubscribe = codec.subscribe(value, {
637
+ changed() {
638
+ generation++;
639
+ schedule();
640
+ },
641
+ exposed() {
642
+ exposed = true;
643
+ generation++;
644
+ schedule();
645
+ },
646
+ assertWritable() {
647
+ if (closed || closing && !inWrite)
648
+ throw new Error("Durable handle is closed");
649
+ },
650
+ closed() {
651
+ if (closing || closed)
652
+ return;
653
+ closed = true;
654
+ cancel();
655
+ unsubscribe();
656
+ stopLifecycle?.();
657
+ if (checkpointRequired || generation !== saved)
658
+ failure(new Error("Database closed directly; pending buffered changes were not acknowledged"));
659
+ void Promise.resolve().then(() => codec.close?.(value)).catch(failure);
660
+ }
661
+ });
662
+ stopLifecycle = !closed ? options.lifecycle?.subscribe(() => {
663
+ if (!closed && !closing && !conflict && codec.canCapture(value))
664
+ void enqueue(() => persist()).catch(() => {
665
+ });
666
+ }) : void 0;
667
+ if (checkpointRequired)
668
+ schedule();
669
+ return {
670
+ value,
671
+ get pending() {
672
+ return checkpointRequired || generation !== saved || queued > 0;
673
+ },
674
+ get lastError() {
675
+ return lastError;
676
+ },
677
+ flush: () => enqueue(() => persist(true)),
678
+ write: (run) => enqueue(async () => {
679
+ let result;
680
+ inWrite = true;
681
+ try {
682
+ result = run(value);
683
+ } finally {
684
+ inWrite = false;
685
+ }
686
+ if (result && typeof result.then === "function")
687
+ throw new TypeError("Durable write callbacks must be synchronous");
688
+ generation++;
689
+ await persist();
690
+ return result;
691
+ }),
692
+ close() {
693
+ if (closed)
694
+ return lastError ? Promise.reject(lastError) : Promise.resolve();
695
+ if (closing)
696
+ return queue;
697
+ const next = enqueue(async () => {
698
+ await persist(true);
699
+ await codec.close?.(value);
700
+ cancel();
701
+ unsubscribe();
702
+ stopLifecycle?.();
703
+ closed = true;
704
+ });
705
+ closing = true;
706
+ const completion = next.catch((error) => {
707
+ closing = false;
708
+ queue = Promise.resolve();
709
+ if (!conflict)
710
+ schedule();
711
+ throw error;
712
+ });
713
+ queue = completion;
714
+ return completion;
715
+ }
716
+ };
717
+ }
718
+ function packDurableRecord(metadata, snapshot) {
719
+ const meta = new TextEncoder().encode(JSON.stringify(packValue(metadata)));
720
+ const bytes = new Uint8Array(4 + meta.length + snapshot.length);
721
+ new DataView(bytes.buffer).setUint32(0, meta.length, true);
722
+ bytes.set(meta, 4);
723
+ bytes.set(snapshot, 4 + meta.length);
724
+ return bytes;
725
+ }
726
+ function unpackDurableRecord(bytes) {
727
+ if (bytes.length < 4)
728
+ throw new Error("Invalid buffered record");
729
+ const length = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0, true);
730
+ if (length > bytes.length - 4)
731
+ throw new Error("Invalid buffered record");
732
+ return {
733
+ metadata: unpackValue(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(4, 4 + length)))),
734
+ snapshot: bytes.subarray(4 + length)
735
+ };
736
+ }
737
+ function packValue(value) {
738
+ if (typeof value === "bigint")
739
+ return [2, String(value)];
740
+ if (typeof value === "number" && !Number.isFinite(value))
741
+ return [3, String(value)];
742
+ if (value instanceof Uint8Array)
743
+ return [1, Array.from(value)];
744
+ if (Array.isArray(value))
745
+ return [0, value.map(packValue)];
746
+ if (value !== null && typeof value === "object")
747
+ return [
748
+ 4,
749
+ Object.entries(value).filter(([, value2]) => value2 !== void 0).map(([key, value2]) => [key, packValue(value2)])
750
+ ];
751
+ if (value === void 0)
752
+ throw new TypeError("Undefined durable metadata");
753
+ return value;
754
+ }
755
+ function unpackValue(value) {
756
+ if (!Array.isArray(value))
757
+ return value;
758
+ const [tag, payload] = value;
759
+ switch (tag) {
760
+ case 0:
761
+ return payload.map(unpackValue);
762
+ case 1:
763
+ return new Uint8Array(payload);
764
+ case 2:
765
+ return BigInt(payload);
766
+ case 3:
767
+ return Number(payload);
768
+ case 4:
769
+ return Object.fromEntries(payload.map(([key, value2]) => [key, unpackValue(value2)]));
770
+ default:
771
+ throw new Error("Invalid durable metadata tag");
772
+ }
773
+ }
774
+
775
+ // ../core/dist/fork-map.js
776
+ var ForkMap = class _ForkMap {
777
+ owner = {};
778
+ index = { owner: this.owner, groups: [] };
779
+ order = { owner: this.owner, cells: [] };
780
+ shift = 0;
781
+ length = 0;
782
+ count = 0;
783
+ nextSequence = 0;
784
+ layout = 0;
785
+ cleared = 0;
786
+ version = 0;
787
+ constructor(entries) {
788
+ if (entries)
789
+ for (const [key, value] of entries)
790
+ this.set(key, value);
791
+ }
792
+ get size() {
793
+ return this.count;
794
+ }
795
+ get [Symbol.toStringTag]() {
796
+ return "Map";
797
+ }
798
+ fork() {
799
+ const copy = new _ForkMap();
800
+ copy.index = this.index;
801
+ copy.order = this.order;
802
+ copy.shift = this.shift;
803
+ copy.length = this.length;
804
+ copy.count = this.count;
805
+ copy.nextSequence = this.nextSequence;
806
+ this.owner = {};
807
+ return copy;
808
+ }
809
+ /** Visit changed hash buckets only. Values must be replaced, rather than mutated in place. */
810
+ *changes(previous) {
811
+ if (previous?.index === this.index)
812
+ return;
813
+ for (let group = 0; group < 32; group++) {
814
+ const currentGroup = this.index.groups[group];
815
+ const oldGroup = previous?.index.groups[group];
816
+ if (currentGroup === oldGroup)
817
+ continue;
818
+ for (let bucket = 0; bucket < 32; bucket++) {
819
+ const current = currentGroup?.buckets[bucket]?.data;
820
+ const old = oldGroup?.buckets[bucket]?.data;
821
+ if (current === old)
822
+ continue;
823
+ if (current)
824
+ for (const [key, entry] of current) {
825
+ const before = old?.get(key);
826
+ if (!before || !Object.is(before.value, entry.value) || before.sequence !== entry.sequence)
827
+ yield { key, value: entry.value, deleted: false };
828
+ }
829
+ if (old) {
830
+ for (const key of old.keys())
831
+ if (!current?.has(key))
832
+ yield { key, deleted: true };
833
+ }
834
+ }
835
+ }
836
+ }
837
+ get(key) {
838
+ return this.find(key)?.value;
839
+ }
840
+ has(key) {
841
+ return this.find(key) !== void 0;
842
+ }
843
+ set(key, value) {
844
+ if (typeof key === "number" && key === 0)
845
+ key = 0;
846
+ const hash = hashKey(key);
847
+ const existing = this.bucket(hash)?.get(key);
848
+ if (existing && Object.is(existing.value, value))
849
+ return this;
850
+ const entry = existing ? { ...existing, value } : { key, value, position: this.length++, sequence: this.nextSequence++ };
851
+ this.writableBucket(hash).set(key, entry);
852
+ this.writeOrder(entry.position, entry);
853
+ if (!existing)
854
+ this.count++;
855
+ this.version++;
856
+ return this;
857
+ }
858
+ delete(key) {
859
+ const hash = hashKey(key);
860
+ const entry = this.bucket(hash)?.get(key);
861
+ if (!entry)
862
+ return false;
863
+ this.writableBucket(hash).delete(key);
864
+ this.writeOrder(entry.position, void 0);
865
+ this.count--;
866
+ this.version++;
867
+ if (this.length > 1024 && this.length > this.count * 2)
868
+ this.compact();
869
+ return true;
870
+ }
871
+ clear() {
872
+ this.index = { owner: this.owner, groups: [] };
873
+ this.order = { owner: this.owner, cells: [] };
874
+ this.shift = this.length = this.count = this.nextSequence = 0;
875
+ this.layout++;
876
+ this.cleared++;
877
+ this.version++;
878
+ }
879
+ entries() {
880
+ return this.iterate(0);
881
+ }
882
+ keys() {
883
+ return this.iterate(1);
884
+ }
885
+ values() {
886
+ return this.iterate(2);
887
+ }
888
+ [Symbol.iterator]() {
889
+ return this.entries();
890
+ }
891
+ forEach(callback, thisArg) {
892
+ for (const [key, value] of this)
893
+ callback.call(thisArg, value, key, this);
894
+ }
895
+ find(key) {
896
+ return this.bucket(hashKey(key))?.get(key);
897
+ }
898
+ bucket(hash) {
899
+ return this.index.groups[hash >>> 5 & 31]?.buckets[hash & 31]?.data;
900
+ }
901
+ writableBucket(hash) {
902
+ if (this.index.owner !== this.owner)
903
+ this.index = { owner: this.owner, groups: this.index.groups.slice() };
904
+ const groupIndex = hash >>> 5 & 31;
905
+ let group = this.index.groups[groupIndex];
906
+ if (!group || group.owner !== this.owner) {
907
+ group = { owner: this.owner, buckets: group?.buckets.slice() ?? [] };
908
+ this.index.groups[groupIndex] = group;
909
+ }
910
+ const at = hash & 31;
911
+ let bucket = group.buckets[at];
912
+ if (!bucket || bucket.owner !== this.owner) {
913
+ bucket = { owner: this.owner, data: bucket ? this.copyBucket(bucket.data) : /* @__PURE__ */ new Map() };
914
+ group.buckets[at] = bucket;
915
+ }
916
+ return bucket.data;
917
+ }
918
+ copyBucket(bucket) {
919
+ return new Map(bucket);
920
+ }
921
+ leaf(position) {
922
+ let node = this.order;
923
+ for (let shift = this.shift; shift > 0; shift -= 5)
924
+ node = node.cells[Math.floor(position / 2 ** shift) & 31];
925
+ return node;
926
+ }
927
+ writeOrder(position, entry) {
928
+ while (position >= 2 ** (this.shift + 5)) {
929
+ this.order = { owner: this.owner, cells: [this.order] };
930
+ this.shift += 5;
931
+ }
932
+ if (this.order.owner !== this.owner)
933
+ this.order = { owner: this.owner, cells: this.order.cells.slice() };
934
+ let node = this.order;
935
+ for (let shift = this.shift; shift > 0; shift -= 5) {
936
+ const at = Math.floor(position / 2 ** shift) & 31;
937
+ let child = node.cells[at];
938
+ if (!child || child.owner !== this.owner) {
939
+ child = { owner: this.owner, cells: child?.cells.slice() ?? [] };
940
+ node.cells[at] = child;
941
+ }
942
+ node = child;
943
+ }
944
+ node.cells[position & 31] = entry;
945
+ }
946
+ compact() {
947
+ const entries = [];
948
+ for (let position = 0; position < this.length; position++) {
949
+ const entry = this.leaf(position).cells[position & 31];
950
+ if (entry)
951
+ entries.push(entry);
952
+ }
953
+ this.index = { owner: this.owner, groups: [] };
954
+ this.order = { owner: this.owner, cells: [] };
955
+ this.shift = this.length = this.count = 0;
956
+ for (const original of entries) {
957
+ const entry = { ...original, position: this.length++ };
958
+ this.writableBucket(hashKey(entry.key)).set(entry.key, entry);
959
+ this.writeOrder(entry.position, entry);
960
+ this.count++;
961
+ }
962
+ this.layout++;
963
+ }
964
+ *iterate(kind) {
965
+ let position = 0;
966
+ let layout = this.layout;
967
+ let cleared = this.cleared;
968
+ let lastSequence = -1;
969
+ let version = -1;
970
+ let leaf;
971
+ let page = -1;
972
+ for (; ; ) {
973
+ if (cleared !== this.cleared) {
974
+ position = 0;
975
+ lastSequence = -1;
976
+ cleared = this.cleared;
977
+ }
978
+ if (layout !== this.layout) {
979
+ position = 0;
980
+ while (position < this.length) {
981
+ const entry2 = this.leaf(position).cells[position & 31];
982
+ if (entry2 && entry2.sequence > lastSequence)
983
+ break;
984
+ position++;
985
+ }
986
+ layout = this.layout;
987
+ }
988
+ if (position >= this.length)
989
+ return;
990
+ const nextPage = Math.floor(position / 32);
991
+ if (page !== nextPage || version !== this.version) {
992
+ leaf = this.leaf(position);
993
+ page = nextPage;
994
+ version = this.version;
995
+ }
996
+ const entry = leaf?.cells[position++ & 31];
997
+ if (!entry)
998
+ continue;
999
+ lastSequence = entry.sequence;
1000
+ yield kind === 0 ? [entry.key, entry.value] : kind === 1 ? entry.key : entry.value;
1001
+ }
1002
+ }
1003
+ };
1004
+ function hashKey(key) {
1005
+ if (typeof key === "number" && Number.isInteger(key))
1006
+ return mix((key | 0) ^ (key / 4294967296 | 0));
1007
+ if (typeof key === "bigint")
1008
+ return mix(Number(BigInt.asIntN(32, key ^ key >> 32n)));
1009
+ const text = String(key);
1010
+ let hash = 2166136261;
1011
+ for (let i = 0; i < text.length; i++)
1012
+ hash = Math.imul(hash ^ text.charCodeAt(i), 16777619);
1013
+ return hash;
1014
+ }
1015
+ function mix(value) {
1016
+ value = Math.imul(value ^ value >>> 16, 73244475);
1017
+ value = Math.imul(value ^ value >>> 16, 73244475);
1018
+ return value ^ value >>> 16;
1019
+ }
1020
+
1021
+ // ../core/dist/mount.js
1022
+ var prefixes = /* @__PURE__ */ new WeakMap();
1023
+ var requestBaseUrl = (request) => new URL(request.url).origin + (prefixes.get(request) ?? "");
1024
+ var forwardMountContext = (source, target) => {
1025
+ const prefix = prefixes.get(source);
1026
+ if (prefix !== void 0)
1027
+ prefixes.set(target, prefix);
1028
+ return target;
1029
+ };
1030
+ function mount(api, path, relativePath) {
1031
+ const prefix = path.replace(/\/+$/, "");
1032
+ if (!/^\/(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+$/.test(prefix))
1033
+ throw new Error("mount prefix must be an absolute path of plain segments");
1034
+ const fetch = async (incoming) => {
1035
+ const url = new URL(incoming.url);
1036
+ if (url.pathname !== prefix && !url.pathname.startsWith(`${prefix}/`))
1037
+ return Response.json({ error: "not_found" }, { status: 404 });
1038
+ url.pathname = url.pathname.slice(prefix.length) || "/";
1039
+ const request = new Request(url, incoming);
1040
+ const publicPrefix = (prefixes.get(incoming) ?? "") + prefix;
1041
+ prefixes.set(request, publicPrefix);
1042
+ const suffix = relativePath?.(request) ?? "";
1043
+ const response = await api.fetch(request);
1044
+ const local = (value) => value.startsWith("/") && !value.startsWith("//") && value !== publicPrefix && !value.startsWith(`${publicPrefix}/`) ? `${publicPrefix}${suffix && value !== suffix && !value.startsWith(`${suffix}/`) ? suffix : ""}${value}` : value;
1045
+ const headers = new Headers(response.headers);
1046
+ const location = headers.get("location");
1047
+ if (location)
1048
+ headers.set("location", local(location));
1049
+ const links = headers.get("link");
1050
+ if (links)
1051
+ headers.set("link", links.replace(/<([^>]+)>/g, (_, value) => {
1052
+ const target = new URL(value, url);
1053
+ if (target.origin === url.origin)
1054
+ target.pathname = local(target.pathname);
1055
+ return `<${target.href}>`;
1056
+ }));
1057
+ const cookies = headers.getSetCookie();
1058
+ if (cookies.length) {
1059
+ headers.delete("set-cookie");
1060
+ for (const cookie of cookies)
1061
+ headers.append("set-cookie", cookie.replace(/(;\s*Path=)(\/[^;]*)/gi, (_, lead, value) => lead + local(value)));
1062
+ }
1063
+ if (incoming.method !== "HEAD" && response.body && // Media types are case-insensitive (RFC 9110 §8.3.1), and whitespace may precede ";".
1064
+ headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() === "text/html") {
1065
+ const html = rewriteHtml(await response.text(), local);
1066
+ headers.delete("content-length");
1067
+ headers.delete("content-encoding");
1068
+ headers.delete("etag");
1069
+ return new Response(html, {
1070
+ status: response.status,
1071
+ statusText: response.statusText,
1072
+ headers
1073
+ });
1074
+ }
1075
+ return new Response(incoming.method === "HEAD" ? null : response.body, {
1076
+ status: response.status,
1077
+ statusText: response.statusText,
1078
+ headers
1079
+ });
1080
+ };
1081
+ return {
1082
+ prefix,
1083
+ fetch,
1084
+ GET: fetch,
1085
+ POST: fetch,
1086
+ PUT: fetch,
1087
+ PATCH: fetch,
1088
+ DELETE: fetch,
1089
+ HEAD: fetch,
1090
+ OPTIONS: fetch
1091
+ };
1092
+ }
1093
+ var rewriteHtml = (html, local) => html.replace(/(\b(?:href|action|formaction|src)\s*=\s*["'])(\/[^"']*)(["'])/gi, (_, lead, value, quote) => lead + local(value) + quote).replace(/(\bsrcset\s*=\s*)(["'])([^"']*)\2/gi, (_, lead, quote, list) => lead + quote + list.replace(/(^|,)(\s*)(\/[^\s,]*)/g, (_2, comma, space, value) => comma + space + local(value)) + quote).replace(/<meta\b[^>]*>/gi, (tag) => /\bhttp-equiv\s*=\s*["']?refresh\b/i.test(tag) ? tag.replace(/(\bcontent\s*=\s*)(["'])(.*?)\2/i, (_, lead, quote, content) => lead + quote + content.replace(/^(\s*\d*(?:\.\d*)?\s*[;,]\s*(?:url\s*=\s*)?["']?)(\/[^"'\s]*)/i, (_2, start, value) => start + local(value)) + quote) : tag).replace(/(url\(\s*["']?)(\/[^\s)'";]*)(["']?\s*\))/gi, (_, lead, value, end) => lead + local(value) + end);
1094
+
1095
+ // ../core/dist/timeline.js
1096
+ var BRANCH_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
1097
+ var Timeline = class {
1098
+ maxCheckpoints;
1099
+ now;
1100
+ makeId;
1101
+ nodes = /* @__PURE__ */ new Map();
1102
+ heads = /* @__PURE__ */ new Map();
1103
+ /** Unreferenced nodes in the exact order they became collectible. */
1104
+ evictable = /* @__PURE__ */ new Set();
1105
+ /** Branch heads plus explicit retainers. Absent means zero. */
1106
+ references = /* @__PURE__ */ new Map();
1107
+ explicitPins = /* @__PURE__ */ new Map();
1108
+ sequence = 0;
1109
+ constructor(options = {}) {
1110
+ const max = options.maxCheckpoints ?? 1e3;
1111
+ if (!Number.isSafeInteger(max) || max < 1)
1112
+ throw new RangeError("maxCheckpoints must be a positive integer");
1113
+ this.maxCheckpoints = max;
1114
+ this.now = options.now ?? (() => this.sequence);
1115
+ this.makeId = options.id ?? ((sequence) => `cp_${sequence.toString(36).padStart(8, "0")}`);
1116
+ }
1117
+ /** Capture a new immutable value and move `branch` to it. */
1118
+ commit(value, options = {}) {
1119
+ const branch = options.branch ?? "main";
1120
+ this.assertBranch(branch);
1121
+ const parent = options.parent === void 0 ? this.heads.get(branch) ?? null : options.parent;
1122
+ if (parent !== null && !this.nodes.has(parent))
1123
+ throw new RangeError(`no checkpoint ${parent}`);
1124
+ const id = this.makeId(++this.sequence);
1125
+ if (this.nodes.has(id))
1126
+ throw new RangeError(`duplicate checkpoint id ${id}`);
1127
+ const checkpoint = Object.freeze({ id, branch, parent, at: this.now(), value });
1128
+ this.nodes.set(id, checkpoint);
1129
+ this.moveHead(branch, id);
1130
+ this.collect(this.maxCheckpoints);
1131
+ return checkpoint;
1132
+ }
1133
+ /** Create a branch pointer without copying its checkpoint value. */
1134
+ fork(branch, options = {}) {
1135
+ this.assertBranch(branch);
1136
+ if (this.heads.has(branch))
1137
+ throw new RangeError(`branch already exists: ${branch}`);
1138
+ const from = options.from ?? this.heads.get("main");
1139
+ if (from === void 0)
1140
+ return void 0;
1141
+ const checkpoint = this.get(from);
1142
+ this.moveHead(branch, checkpoint.id);
1143
+ return checkpoint;
1144
+ }
1145
+ /** Move a branch pointer to an existing checkpoint. */
1146
+ checkout(branch, id) {
1147
+ this.assertBranch(branch);
1148
+ const checkpoint = this.get(id);
1149
+ this.moveHead(branch, checkpoint.id);
1150
+ return checkpoint;
1151
+ }
1152
+ get(id) {
1153
+ const checkpoint = this.nodes.get(id);
1154
+ if (!checkpoint)
1155
+ throw new RangeError(`no checkpoint ${id}`);
1156
+ return checkpoint;
1157
+ }
1158
+ head(branch = "main") {
1159
+ const id = this.heads.get(branch);
1160
+ return id === void 0 ? void 0 : this.get(id);
1161
+ }
1162
+ hasBranch(branch) {
1163
+ return this.heads.has(branch);
1164
+ }
1165
+ branches() {
1166
+ return Object.freeze(Object.fromEntries([...this.heads].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)));
1167
+ }
1168
+ checkpoints() {
1169
+ return [...this.nodes.values()];
1170
+ }
1171
+ /** Number of retained checkpoints without allocating an array. */
1172
+ get size() {
1173
+ return this.nodes.size;
1174
+ }
1175
+ /** Pin a checkpoint independently of branch heads (used by compatibility snapshot handles). */
1176
+ retain(id) {
1177
+ const checkpoint = this.get(id);
1178
+ this.explicitPins.set(id, (this.explicitPins.get(id) ?? 0) + 1);
1179
+ this.addReference(id);
1180
+ return checkpoint;
1181
+ }
1182
+ /** Release one explicit pin. Branch heads remain pinned until moved or deleted. */
1183
+ release(id) {
1184
+ if (!this.nodes.has(id))
1185
+ return false;
1186
+ const pins = this.explicitPins.get(id) ?? 0;
1187
+ if (pins === 0)
1188
+ return false;
1189
+ if (pins === 1)
1190
+ this.explicitPins.delete(id);
1191
+ else
1192
+ this.explicitPins.set(id, pins - 1);
1193
+ this.removeReference(id);
1194
+ this.collect(this.maxCheckpoints);
1195
+ return true;
1196
+ }
1197
+ deleteBranch(branch) {
1198
+ if (branch === "main")
1199
+ throw new RangeError("cannot delete main branch");
1200
+ const previous = this.heads.get(branch);
1201
+ const deleted = this.heads.delete(branch);
1202
+ if (previous !== void 0)
1203
+ this.removeReference(previous);
1204
+ this.collect(this.maxCheckpoints);
1205
+ return deleted;
1206
+ }
1207
+ /**
1208
+ * Deterministically discard oldest unpinned checkpoints. Collection is O(number removed):
1209
+ * commits never scan pinned nodes or the retained history. Parents are metadata rather than a
1210
+ * storage dependency, so a retained node remains usable after pruning.
1211
+ */
1212
+ gc(max = this.maxCheckpoints) {
1213
+ if (!Number.isSafeInteger(max) || max < 1)
1214
+ throw new RangeError("max must be a positive integer");
1215
+ const removed = [];
1216
+ this.collect(max, removed);
1217
+ return removed;
1218
+ }
1219
+ collect(max, removed) {
1220
+ while (this.nodes.size > max && this.evictable.size > 0) {
1221
+ const id = this.evictable.values().next().value;
1222
+ this.evictable.delete(id);
1223
+ this.nodes.delete(id);
1224
+ removed?.push(id);
1225
+ }
1226
+ }
1227
+ moveHead(branch, id) {
1228
+ const previous = this.heads.get(branch);
1229
+ if (previous === id)
1230
+ return;
1231
+ if (previous !== void 0)
1232
+ this.removeReference(previous);
1233
+ this.heads.set(branch, id);
1234
+ this.addReference(id);
1235
+ }
1236
+ addReference(id) {
1237
+ this.references.set(id, (this.references.get(id) ?? 0) + 1);
1238
+ this.evictable.delete(id);
1239
+ }
1240
+ removeReference(id) {
1241
+ const next = (this.references.get(id) ?? 0) - 1;
1242
+ if (next > 0)
1243
+ this.references.set(id, next);
1244
+ else {
1245
+ this.references.delete(id);
1246
+ if (this.nodes.has(id))
1247
+ this.evictable.add(id);
1248
+ }
1249
+ }
1250
+ assertBranch(branch) {
1251
+ if (!BRANCH_PATTERN.test(branch))
1252
+ throw new RangeError(`branch must match ${BRANCH_PATTERN}`);
1253
+ }
1254
+ };
1255
+
1256
+ // ../core/dist/index.js
1257
+ var toFetchHandler = (api) => {
1258
+ return (request) => api.fetch(request);
1259
+ };
1260
+ var fromFetchHandler = (handler) => {
1261
+ return { fetch: handler };
1262
+ };
1263
+
1264
+ export {
1265
+ withDurability,
1266
+ DurabilityConflictError,
1267
+ openDurable,
1268
+ applyDurablePatch,
1269
+ validateDurablePatch,
1270
+ validateDurableCommit,
1271
+ MemoryDurabilityBackend,
1272
+ browserDurabilityLifecycle,
1273
+ IndexedDBDurabilityBackend,
1274
+ LocalStorageDurabilityBackend,
1275
+ isDurableJournal,
1276
+ encodeDurableCheckpoint,
1277
+ readDurableJournal,
1278
+ openBufferedDurable,
1279
+ packDurableRecord,
1280
+ unpackDurableRecord,
1281
+ ForkMap,
1282
+ requestBaseUrl,
1283
+ forwardMountContext,
1284
+ mount,
1285
+ Timeline,
1286
+ toFetchHandler,
1287
+ fromFetchHandler
1288
+ };
1289
+ //# sourceMappingURL=chunk-2Y25NPCV.js.map