@telepath-computer/television 1.4.25 → 1.4.27

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.
@@ -0,0 +1,1413 @@
1
+ // packages/shared/src/resources/errors.ts
2
+ function resourceError(code, message) {
3
+ return Object.assign(new Error(message), { code });
4
+ }
5
+
6
+ // packages/shared/src/resources/names.ts
7
+ var encoder = new TextEncoder();
8
+ function utf8ByteLength(text) {
9
+ return encoder.encode(text).length;
10
+ }
11
+
12
+ // packages/shared/src/resources/json-paths.ts
13
+ var JSON_STORE_MAX_KEY_BYTES = 768;
14
+ var JSON_STORE_MAX_DEPTH = 32;
15
+ var INDEX_PATTERN = /^(?:0|[1-9][0-9]*)$/;
16
+ function parseJsonPath(path) {
17
+ const segments = path.split("/").filter((segment) => segment.length > 0);
18
+ checkPathSegments(segments);
19
+ return segments;
20
+ }
21
+ function checkPathSegments(segments) {
22
+ if (segments.length > JSON_STORE_MAX_DEPTH) {
23
+ throw resourceError("invalid-path", `A path has at most ${JSON_STORE_MAX_DEPTH} segments.`);
24
+ }
25
+ for (const segment of segments) {
26
+ if (!isValidKey(segment)) {
27
+ throw resourceError("invalid-path", `A path key is at most ${JSON_STORE_MAX_KEY_BYTES} bytes.`);
28
+ }
29
+ }
30
+ }
31
+ function tooDeepError() {
32
+ return resourceError("invalid-path", `A value can be at most ${JSON_STORE_MAX_DEPTH} keys below the store's root.`);
33
+ }
34
+ function isValidKey(key) {
35
+ return key.length > 0 && !key.includes("/") && utf8ByteLength(key) <= JSON_STORE_MAX_KEY_BYTES;
36
+ }
37
+ function isIndexKey(key) {
38
+ return INDEX_PATTERN.test(key);
39
+ }
40
+ function isArrayIndexIn(array, key) {
41
+ return isIndexKey(key) && Number(key) < array.length;
42
+ }
43
+ function isJsonObject(value) {
44
+ return typeof value === "object" && value !== null && !Array.isArray(value);
45
+ }
46
+ function readJsonValue(value, segments) {
47
+ let current = value;
48
+ for (const segment of segments) {
49
+ if (Array.isArray(current)) {
50
+ current = isArrayIndexIn(current, segment) ? current[Number(segment)] : void 0;
51
+ } else if (isJsonObject(current)) {
52
+ current = Object.hasOwn(current, segment) ? current[segment] : void 0;
53
+ } else {
54
+ return void 0;
55
+ }
56
+ if (current === void 0) return void 0;
57
+ }
58
+ return current;
59
+ }
60
+ function jsonEqual(left, right) {
61
+ if (left === right) return true;
62
+ if (left === void 0 || right === void 0 || left === null || right === null) return false;
63
+ if (Array.isArray(left) || Array.isArray(right)) {
64
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;
65
+ return left.every((element, index) => jsonEqual(element, right[index]));
66
+ }
67
+ if (typeof left !== "object" || typeof right !== "object") return false;
68
+ const leftKeys = Object.keys(left);
69
+ if (leftKeys.length !== Object.keys(right).length) return false;
70
+ return leftKeys.every((key) => Object.hasOwn(right, key) && jsonEqual(left[key], right[key]));
71
+ }
72
+ function compareChildKeys(left, right) {
73
+ const leftIndex = isIndexKey(left);
74
+ const rightIndex = isIndexKey(right);
75
+ if (leftIndex !== rightIndex) return leftIndex ? -1 : 1;
76
+ if (leftIndex && left.length !== right.length) return left.length - right.length;
77
+ return left < right ? -1 : left > right ? 1 : 0;
78
+ }
79
+ function childKeys(value) {
80
+ if (Array.isArray(value)) return value.map((_, index) => String(index));
81
+ if (isJsonObject(value)) return Object.keys(value).sort(compareChildKeys);
82
+ return [];
83
+ }
84
+
85
+ // packages/shared/src/resources/json-values.ts
86
+ var ServerValuePlaceholder = class {
87
+ serverValue;
88
+ constructor(serverValue) {
89
+ this.serverValue = serverValue;
90
+ Object.freeze(this);
91
+ }
92
+ };
93
+ var DeleteValuePlaceholder = class {
94
+ constructor() {
95
+ Object.freeze(this);
96
+ }
97
+ };
98
+ function serverTimestamp() {
99
+ return new ServerValuePlaceholder({ kind: "timestamp" });
100
+ }
101
+ function increment(n) {
102
+ return new ServerValuePlaceholder({ kind: "increment", by: n });
103
+ }
104
+ function deleteValue() {
105
+ return new DeleteValuePlaceholder();
106
+ }
107
+ function invalidValue(message) {
108
+ return resourceError("invalid-value", message);
109
+ }
110
+ function isPlainObject(value) {
111
+ const prototype = Object.getPrototypeOf(value);
112
+ return prototype === Object.prototype || prototype === null;
113
+ }
114
+ function checkServerValueSpec(spec) {
115
+ if (typeof spec !== "object" || spec === null) throw invalidValue("A server value is malformed.");
116
+ const record = spec;
117
+ if (record.kind === "timestamp" && Object.keys(record).length === 1) return;
118
+ if (record.kind === "increment" && Object.keys(record).length === 2 && typeof record.by === "number" && Number.isFinite(record.by)) {
119
+ return;
120
+ }
121
+ throw invalidValue("increment() takes a finite number.");
122
+ }
123
+ function checkValue(value, allowServerValues, ancestors, depth) {
124
+ if (value === null || typeof value === "boolean" || typeof value === "string") return;
125
+ if (typeof value === "number") {
126
+ if (!Number.isFinite(value)) throw invalidValue("A stored number must be finite.");
127
+ return;
128
+ }
129
+ if (allowServerValues && value instanceof ServerValuePlaceholder) {
130
+ checkServerValueSpec(value.serverValue);
131
+ return;
132
+ }
133
+ if (typeof value !== "object") {
134
+ throw invalidValue(`A ${typeof value} is not a JSON value.`);
135
+ }
136
+ if (ancestors.has(value)) throw invalidValue("A value cannot contain itself.");
137
+ ancestors.add(value);
138
+ if (Array.isArray(value)) {
139
+ if (value.length > 0 && depth >= JSON_STORE_MAX_DEPTH) throw tooDeepError();
140
+ for (let index = 0; index < value.length; index++) {
141
+ if (!(index in value)) throw invalidValue("An array cannot have holes.");
142
+ checkValue(value[index], allowServerValues, ancestors, depth + 1);
143
+ }
144
+ } else {
145
+ if (!isPlainObject(value)) {
146
+ throw invalidValue("Only plain objects, arrays, strings, finite numbers, booleans and null are JSON values.");
147
+ }
148
+ const keys = Object.keys(value);
149
+ if (keys.length > 0 && depth >= JSON_STORE_MAX_DEPTH) throw tooDeepError();
150
+ for (const key of keys) {
151
+ if (!isValidKey(key)) {
152
+ throw invalidValue("An object key must be non-empty, contain no /, and be at most 768 bytes.");
153
+ }
154
+ checkValue(value[key], allowServerValues, ancestors, depth + 1);
155
+ }
156
+ }
157
+ ancestors.delete(value);
158
+ }
159
+ function validateJsonValue(value) {
160
+ checkValue(value, false, /* @__PURE__ */ new Set(), 0);
161
+ }
162
+ function validateWriteValue(value) {
163
+ checkValue(value, true, /* @__PURE__ */ new Set(), 0);
164
+ }
165
+ function validateUpdateValues(values) {
166
+ if (typeof values !== "object" || values === null || Array.isArray(values) || !isPlainObject(values)) {
167
+ throw invalidValue("update() takes an object of paths and values.");
168
+ }
169
+ for (const key of Object.keys(values)) {
170
+ const entry = values[key];
171
+ if (!(entry instanceof DeleteValuePlaceholder)) validateWriteValue(entry);
172
+ }
173
+ }
174
+ function setMember(target, key, value) {
175
+ Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
176
+ }
177
+ function encodeWriteValue(value) {
178
+ const serverValues = [];
179
+ const encode = (node, at) => {
180
+ if (node instanceof ServerValuePlaceholder) {
181
+ serverValues.push({ at, serverValue: { ...node.serverValue } });
182
+ return null;
183
+ }
184
+ if (Array.isArray(node)) return node.map((element, index) => encode(element, [...at, String(index)]));
185
+ if (node !== null && typeof node === "object") {
186
+ const encoded = {};
187
+ for (const key of Object.keys(node)) setMember(encoded, key, encode(node[key], [...at, key]));
188
+ return encoded;
189
+ }
190
+ return node;
191
+ };
192
+ const encodedValue = encode(value, []);
193
+ return serverValues.length > 0 ? { value: encodedValue, serverValues } : { value: encodedValue };
194
+ }
195
+ function encodeUpdateEntries(values) {
196
+ return Object.keys(values).map((key) => {
197
+ const entry = values[key];
198
+ return entry instanceof DeleteValuePlaceholder ? { key, delete: true } : { key, value: encodeWriteValue(entry) };
199
+ });
200
+ }
201
+ function placeAt(node, at, depth, leaf, copies) {
202
+ if (depth === at.length) {
203
+ if (node instanceof ServerValuePlaceholder) throw invalidValue("Two server values share one position.");
204
+ return leaf;
205
+ }
206
+ const key = at[depth];
207
+ if (Array.isArray(node) && isArrayIndexIn(node, key)) {
208
+ const copy = copies.has(node) ? node : node.slice();
209
+ copies.add(copy);
210
+ copy[Number(key)] = placeAt(node[Number(key)], at, depth + 1, leaf, copies);
211
+ return copy;
212
+ }
213
+ if (isJsonObject(node) && !(node instanceof ServerValuePlaceholder) && Object.hasOwn(node, key)) {
214
+ const copy = copies.has(node) ? node : { ...node };
215
+ copies.add(copy);
216
+ setMember(copy, key, placeAt(node[key], at, depth + 1, leaf, copies));
217
+ return copy;
218
+ }
219
+ throw invalidValue("A server value does not stand at a position in the written value.");
220
+ }
221
+ function decodeWriteValue(encoded) {
222
+ if (typeof encoded !== "object" || encoded === null || !Object.hasOwn(encoded, "value")) {
223
+ throw invalidValue("A written value is missing.");
224
+ }
225
+ const record = encoded;
226
+ validateJsonValue(record.value);
227
+ let decoded = record.value;
228
+ const serverValues = record.serverValues ?? [];
229
+ if (!Array.isArray(serverValues)) throw invalidValue("Server values are malformed.");
230
+ const copies = /* @__PURE__ */ new Set();
231
+ for (const serverValue of serverValues) {
232
+ if (typeof serverValue !== "object" || serverValue === null) throw invalidValue("A server value is malformed.");
233
+ const { at, serverValue: spec } = serverValue;
234
+ if (!Array.isArray(at) || !at.every((key) => typeof key === "string")) {
235
+ throw invalidValue("A server value's position is malformed.");
236
+ }
237
+ checkServerValueSpec(spec);
238
+ decoded = placeAt(decoded, at, 0, new ServerValuePlaceholder({ ...spec }), copies);
239
+ }
240
+ return decoded;
241
+ }
242
+ function decodeUpdateEntries(encoded) {
243
+ if (!Array.isArray(encoded)) throw invalidValue("An update's entries are malformed.");
244
+ return encoded.map((entry) => {
245
+ if (typeof entry !== "object" || entry === null || typeof entry.key !== "string") {
246
+ throw invalidValue("An update entry is malformed.");
247
+ }
248
+ const { key, delete: isDelete, value } = entry;
249
+ if (isDelete === true) return [key, new DeleteValuePlaceholder()];
250
+ return [key, decodeWriteValue(value)];
251
+ });
252
+ }
253
+
254
+ // packages/shared/src/resources/json-apply.ts
255
+ var JSON_STORE_MAX_BYTES = 1048576;
256
+ var JSON_STORE_MAX_WRITE_MESSAGE_BYTES = 16777216;
257
+ function invalidPath(message) {
258
+ return resourceError("invalid-path", message);
259
+ }
260
+ function applyJsonWrite(current, write, context, options = {}) {
261
+ let result = current;
262
+ const copies = /* @__PURE__ */ new Set();
263
+ for (const mutation of toMutations(write)) {
264
+ if ("remove" in mutation) {
265
+ result = removeAt(result, mutation.segments, 0, copies);
266
+ } else {
267
+ const leaf = materialize(mutation.value, mutation.segments, current, context);
268
+ if (mutation.segments.length + depthBelow(leaf) > JSON_STORE_MAX_DEPTH) throw tooDeepError();
269
+ result = setAt(result, mutation.segments, 0, leaf, copies);
270
+ }
271
+ }
272
+ if (options.checkSize !== false) checkJsonSize(result);
273
+ return result;
274
+ }
275
+ function toMutations(write) {
276
+ const base = parseJsonPath(write.path);
277
+ switch (write.kind) {
278
+ case "set":
279
+ validateWriteValue(write.value);
280
+ return [{ segments: base, value: write.value }];
281
+ case "remove":
282
+ return [{ segments: base, remove: true }];
283
+ case "update": {
284
+ const mutations = write.entries.map(([key, value]) => {
285
+ const relative = key.split("/").filter((segment) => segment.length > 0);
286
+ const segments = [...base, ...relative];
287
+ checkPathSegments(segments);
288
+ if (value instanceof DeleteValuePlaceholder) return { segments, remove: true };
289
+ validateWriteValue(value);
290
+ return { segments, value };
291
+ });
292
+ refuseOverlappingPaths(mutations.map((mutation) => mutation.segments));
293
+ return mutations;
294
+ }
295
+ }
296
+ }
297
+ function refuseOverlappingPaths(paths) {
298
+ const root = { end: false, children: /* @__PURE__ */ new Map() };
299
+ for (const segments of paths) {
300
+ let node = root;
301
+ for (const segment of segments) {
302
+ if (node.end) break;
303
+ let child2 = node.children.get(segment);
304
+ if (!child2) {
305
+ child2 = { end: false, children: /* @__PURE__ */ new Map() };
306
+ node.children.set(segment, child2);
307
+ }
308
+ node = child2;
309
+ }
310
+ if (node.end || node.children.size > 0) {
311
+ throw invalidPath("An update's keys must not address the same path or lie within one another.");
312
+ }
313
+ node.end = true;
314
+ }
315
+ }
316
+ function writable(node, copies) {
317
+ if (copies.has(node)) return node;
318
+ const copy = Array.isArray(node) ? node.slice() : { ...node };
319
+ copies.add(copy);
320
+ return copy;
321
+ }
322
+ function materialize(node, at, original, context) {
323
+ if (node instanceof ServerValuePlaceholder) {
324
+ const spec = node.serverValue;
325
+ if (spec.kind === "timestamp") return context.now;
326
+ const before = readJsonValue(original, at);
327
+ const filled = typeof before === "number" ? before + spec.by : spec.by;
328
+ if (!Number.isFinite(filled)) throw resourceError("invalid-value", "An increment would leave a number that is not finite.");
329
+ return filled;
330
+ }
331
+ if (Array.isArray(node)) return node.map((element, index) => materialize(element, [...at, String(index)], original, context));
332
+ if (node !== null && typeof node === "object") {
333
+ const copy = {};
334
+ for (const key of Object.keys(node)) setMember(copy, key, materialize(node[key], [...at, key], original, context));
335
+ return copy;
336
+ }
337
+ return node;
338
+ }
339
+ function setAt(node, segments, depth, leaf, copies) {
340
+ if (depth === segments.length) return leaf;
341
+ const key = segments[depth];
342
+ if (Array.isArray(node)) {
343
+ if (!isArrayIndexIn(node, key)) {
344
+ throw invalidPath("Below an array, a path key must be the index of an existing element.");
345
+ }
346
+ const copy2 = writable(node, copies);
347
+ copy2[Number(key)] = setAt(node[Number(key)], segments, depth + 1, leaf, copies);
348
+ return copy2;
349
+ }
350
+ const copy = isJsonObject(node) ? writable(node, copies) : writable({}, copies);
351
+ const child2 = isJsonObject(node) && Object.hasOwn(node, key) ? node[key] : void 0;
352
+ setMember(copy, key, setAt(child2, segments, depth + 1, leaf, copies));
353
+ return copy;
354
+ }
355
+ function removeAt(node, segments, depth, copies) {
356
+ if (depth === segments.length) return void 0;
357
+ const key = segments[depth];
358
+ if (Array.isArray(node)) {
359
+ if (!isArrayIndexIn(node, key)) {
360
+ throw invalidPath("Below an array, a path key must be the index of an existing element.");
361
+ }
362
+ if (depth === segments.length - 1) throw invalidPath("An array element cannot be deleted; write the whole array.");
363
+ const element = node[Number(key)];
364
+ const child3 = removeAt(element, segments, depth + 1, copies);
365
+ if (child3 === element) return node;
366
+ const copy2 = writable(node, copies);
367
+ copy2[Number(key)] = child3;
368
+ return copy2;
369
+ }
370
+ if (!isJsonObject(node) || !Object.hasOwn(node, key)) return node;
371
+ const child2 = removeAt(node[key], segments, depth + 1, copies);
372
+ if (child2 === node[key]) return node;
373
+ const copy = writable(node, copies);
374
+ if (child2 === void 0) delete copy[key];
375
+ else setMember(copy, key, child2);
376
+ return copy;
377
+ }
378
+ function depthBelow(value) {
379
+ let deepest = 0;
380
+ const visit = (node, depth) => {
381
+ if (depth > deepest) deepest = depth;
382
+ if (deepest > JSON_STORE_MAX_DEPTH) return;
383
+ if (Array.isArray(node)) for (const element of node) visit(element, depth + 1);
384
+ else if (isJsonObject(node)) for (const key of Object.keys(node)) visit(node[key], depth + 1);
385
+ };
386
+ visit(value, 0);
387
+ return deepest;
388
+ }
389
+ function jsonByteLength(value) {
390
+ return value === void 0 ? 0 : utf8ByteLength(JSON.stringify(value));
391
+ }
392
+ function checkJsonSize(value) {
393
+ if (jsonByteLength(value) > JSON_STORE_MAX_BYTES) {
394
+ throw resourceError("too-large", `A store's value is at most ${JSON_STORE_MAX_BYTES} bytes of compact JSON.`);
395
+ }
396
+ }
397
+ function checkWriteMessage(message) {
398
+ if (utf8ByteLength(message) > JSON_STORE_MAX_WRITE_MESSAGE_BYTES) throw writeMessageTooLarge();
399
+ }
400
+ function writeMessageTooLarge() {
401
+ return resourceError("too-large", `A write is at most ${JSON_STORE_MAX_WRITE_MESSAGE_BYTES} bytes as sent.`);
402
+ }
403
+
404
+ // packages/shared/src/resources/wire.ts
405
+ var ADMIN_ROUTE_PREFIX = "/api/resources/v1";
406
+ var ARTIFACT_ROUTE_PREFIX = "/artifact-resources";
407
+ var resourceRoute = (resourceID, action = "") => `${ADMIN_ROUTE_PREFIX}/resources/${encodeURIComponent(resourceID)}${action === "" ? "" : `/${action}`}`;
408
+ var artifactRoute = (artifactID, action) => `${ADMIN_ROUTE_PREFIX}/artifacts/${encodeURIComponent(artifactID)}/${action}`;
409
+ var adminRoutes = {
410
+ /** GET, with an optional `artifact` query parameter. */
411
+ list: `${ADMIN_ROUTE_PREFIX}/resources`,
412
+ /** GET. */
413
+ info: (resourceID) => resourceRoute(resourceID),
414
+ describe: (resourceID) => resourceRoute(resourceID, "describe"),
415
+ bind: (resourceID) => resourceRoute(resourceID, "bind"),
416
+ unbind: (resourceID) => resourceRoute(resourceID, "unbind"),
417
+ destroy: (resourceID) => resourceRoute(resourceID, "destroy"),
418
+ /** POST: creates the artifact's share link at a level, or changes its level. */
419
+ share: (artifactID) => artifactRoute(artifactID, "share"),
420
+ /** POST: revokes the artifact's share link. */
421
+ unshare: (artifactID) => artifactRoute(artifactID, "unshare"),
422
+ /** POST, with the bindings flag on. */
423
+ jsonCreate: `${ADMIN_ROUTE_PREFIX}/json/create`,
424
+ /** GET, with the store's address (`storeQuery`) and a `path` query parameter. */
425
+ jsonGet: `${ADMIN_ROUTE_PREFIX}/json/value`,
426
+ // POST, each naming its store in the body's `store`.
427
+ jsonSet: `${ADMIN_ROUTE_PREFIX}/json/set`,
428
+ jsonUpdate: `${ADMIN_ROUTE_PREFIX}/json/update`,
429
+ jsonPush: `${ADMIN_ROUTE_PREFIX}/json/push`,
430
+ jsonRemove: `${ADMIN_ROUTE_PREFIX}/json/remove`
431
+ };
432
+
433
+ // packages/shared/src/resources/page-wire.ts
434
+ var CONNECTION_SUFFIX = "/v1/connection";
435
+ var artifactRoutes = {
436
+ /** The page connection under an artifact ID or a share ID. */
437
+ connection: (id) => `${ARTIFACT_ROUTE_PREFIX}/${encodeURIComponent(id)}${CONNECTION_SUFFIX}`
438
+ };
439
+
440
+ // packages/shared/src/resources/sdk-connection.ts
441
+ var BACKOFF_START_MS = 250;
442
+ var BACKOFF_CAP_MS = 3e4;
443
+ var ARTIFACT_PATH = /^\/artifact\/([^/]+)(?:\/|$)/;
444
+ function pageIDFromPath(pathname) {
445
+ const match = ARTIFACT_PATH.exec(pathname);
446
+ if (!match) return null;
447
+ try {
448
+ return decodeURIComponent(match[1]);
449
+ } catch {
450
+ return null;
451
+ }
452
+ }
453
+ function callPage(callback, ...args) {
454
+ try {
455
+ callback(...args);
456
+ } catch (error) {
457
+ if (typeof globalThis.reportError === "function") {
458
+ globalThis.reportError(error);
459
+ } else {
460
+ queueMicrotask(() => {
461
+ throw error;
462
+ });
463
+ }
464
+ }
465
+ }
466
+ function refusal(code, error) {
467
+ return resourceError(code, error);
468
+ }
469
+ function disconnected() {
470
+ return refusal("disconnected", "The page is disconnected from the server.");
471
+ }
472
+ function ownStoreAddresses(ownStore) {
473
+ return ownStore === void 0 ? [null] : [null, ownStore];
474
+ }
475
+ function addressOf(store) {
476
+ return store === null ? {} : { resourceID: store };
477
+ }
478
+ var SdkConnection = class {
479
+ /** The ID in the page's address: its artifact's ID or a share ID. */
480
+ id;
481
+ socket = null;
482
+ currentStatus = "idle";
483
+ statusCallbacks = /* @__PURE__ */ new Set();
484
+ serverTimeOffset = 0;
485
+ /**
486
+ * The page's level on its artifact's own store, null when its address
487
+ * reaches no artifact that has a store, from the open connection's opening
488
+ * state and changes of access; undefined while no connection's opening
489
+ * state has arrived (specs/arch/resources/sdk.md#^sdk-access).
490
+ */
491
+ level = void 0;
492
+ accessCallbacks = /* @__PURE__ */ new Set();
493
+ /** `getAccess` calls waiting for an opening state. */
494
+ accessWaiters = /* @__PURE__ */ new Set();
495
+ /** The resource ID of the artifact's own store, when the same connection gave it. */
496
+ ownStore = void 0;
497
+ /** The page's level on each store its artifact is bound to explicitly, from the same connection. */
498
+ bindings = /* @__PURE__ */ new Map();
499
+ /** Sequence numbers increase across connections, so a write made on a new connection is always above a value an earlier one sent. */
500
+ nextSeq = 1;
501
+ /** The highest sequence number sent on the current connection: writes are sent in sequence order. */
502
+ sentSeq = 0;
503
+ nextID = 0;
504
+ writes = /* @__PURE__ */ new Map();
505
+ requests = /* @__PURE__ */ new Map();
506
+ subscriptions = /* @__PURE__ */ new Map();
507
+ eventCallbacks = /* @__PURE__ */ new Set();
508
+ queueObservers = /* @__PURE__ */ new Set();
509
+ attempt = 0;
510
+ reconnectTimer = null;
511
+ idleCheckQueued = false;
512
+ constructor(id) {
513
+ this.id = id;
514
+ }
515
+ /** The server's clock as the page estimates it, from the last opening state. */
516
+ serverNow() {
517
+ return Date.now() + this.serverTimeOffset;
518
+ }
519
+ /** Unconfirmed writes, in sequence order. */
520
+ queue() {
521
+ return [...this.writes.values()];
522
+ }
523
+ /**
524
+ * Calls `observer` with the stores whose queued writes changed whenever
525
+ * writes are queued or leave the queue, giving the artifact's own store by
526
+ * both its addresses.
527
+ */
528
+ observeQueue(observer) {
529
+ this.queueObservers.add(observer);
530
+ }
531
+ /**
532
+ * Whether two addresses reach one store: the artifact's own store is one
533
+ * store without a resource ID and, once the open connection has given it,
534
+ * by its resource ID (specs/arch/resources/json-store.md#^js-arch-local-writes).
535
+ */
536
+ sameStore(left, right) {
537
+ const own = ownStoreAddresses(this.ownStore);
538
+ return left === right || own.includes(left) && own.includes(right);
539
+ }
540
+ // --- The connection status ---
541
+ get status() {
542
+ return this.currentStatus;
543
+ }
544
+ /** Calls back with the status as it stands soon after registration, then with each change. */
545
+ onStatus(callback) {
546
+ const entry = { callback, heard: null };
547
+ this.statusCallbacks.add(entry);
548
+ this.ensureConnected();
549
+ queueMicrotask(() => {
550
+ if (!this.statusCallbacks.has(entry) || entry.heard !== null) return;
551
+ entry.heard = this.currentStatus;
552
+ callPage(callback, this.currentStatus);
553
+ });
554
+ return () => {
555
+ if (this.statusCallbacks.delete(entry)) this.queueIdleCheck();
556
+ };
557
+ }
558
+ setStatus(status) {
559
+ if (this.currentStatus === status) return;
560
+ this.currentStatus = status;
561
+ for (const entry of [...this.statusCallbacks]) {
562
+ if (entry.heard === null || entry.heard === status || !this.statusCallbacks.has(entry)) continue;
563
+ entry.heard = status;
564
+ callPage(entry.callback, status);
565
+ }
566
+ }
567
+ // --- The page's access level ---
568
+ /**
569
+ * Resolves with the page's level on its artifact's own store, null when its
570
+ * address reaches no artifact that has a store. Waits while a connection
571
+ * opens, and fails at once while the page is disconnected.
572
+ */
573
+ access() {
574
+ if (this.currentStatus === "disconnected") return Promise.reject(disconnected());
575
+ if (this.currentStatus === "connected" && this.level !== void 0) return Promise.resolve(this.level);
576
+ return new Promise((resolve, reject) => {
577
+ this.accessWaiters.add({ resolve, reject });
578
+ this.ensureConnected();
579
+ });
580
+ }
581
+ /** Calls back with the page's level once a connection's opening state has arrived, which may be at once, then with each change. */
582
+ onAccess(callback) {
583
+ const entry = { callback, heard: void 0 };
584
+ this.accessCallbacks.add(entry);
585
+ this.ensureConnected();
586
+ if (this.level !== void 0) queueMicrotask(() => this.tellAccess(entry));
587
+ return () => {
588
+ if (this.accessCallbacks.delete(entry)) this.queueIdleCheck();
589
+ };
590
+ }
591
+ tellAccess(entry) {
592
+ if (!this.accessCallbacks.has(entry) || this.level === void 0 || entry.heard === this.level) return;
593
+ entry.heard = this.level;
594
+ callPage(entry.callback, this.level);
595
+ }
596
+ /**
597
+ * The page's level on a store as the open connection reported it, for a
598
+ * write's local check: on its artifact's own store by either address, and
599
+ * on a bound store, whose level the server limits by that one; unknown
600
+ * without an opening state on the open connection, and for a store the
601
+ * page is not known to reach (specs/arch/resources/sdk.md#Handles).
602
+ */
603
+ knownLevel(store) {
604
+ if (this.level === void 0) return void 0;
605
+ if (store === null || store === this.ownStore) return this.level ?? void 0;
606
+ return this.bindings.get(store);
607
+ }
608
+ /** Takes the page's access whole, from an opening state or a change of it, and returns its level. */
609
+ takeAccess(access) {
610
+ const level = access.access ?? null;
611
+ const ownStore = this.ownStore;
612
+ this.level = level;
613
+ this.ownStore = access.store;
614
+ this.bindings.clear();
615
+ for (const binding of access.bindings) this.bindings.set(binding.resourceID, binding.access);
616
+ if (this.ownStore !== ownStore && this.writes.size > 0) this.notifyQueue(ownStoreAddresses(ownStore), this.ownStore);
617
+ return level;
618
+ }
619
+ // --- Requests, subscriptions and events ---
620
+ /** Throws `disconnected` while the page is disconnected, when requests and writes fail at once. */
621
+ requireReachable() {
622
+ if (this.currentStatus === "disconnected") throw disconnected();
623
+ }
624
+ /** Sends a request once the connection is open; while the page is disconnected it fails at once. */
625
+ request(body) {
626
+ if (this.currentStatus === "disconnected") return Promise.reject(disconnected());
627
+ const id = `r${this.nextID++}`;
628
+ const full = { ...body, id };
629
+ return new Promise((resolve, reject) => {
630
+ this.requests.set(id, { message: full, resolve, reject });
631
+ this.ensureConnected();
632
+ if (this.currentStatus === "connected") this.send(full);
633
+ });
634
+ }
635
+ /** Subscribes on this connection and every later one, until the subscription ends or is unsubscribed. */
636
+ subscribe(store, path, handlers) {
637
+ const id = `s${this.nextID++}`;
638
+ this.subscriptions.set(id, { store, path, handlers });
639
+ this.ensureConnected();
640
+ if (this.currentStatus === "connected") this.send({ type: "subscribe", id, ...addressOf(store), path });
641
+ return () => {
642
+ if (!this.subscriptions.delete(id)) return;
643
+ if (this.currentStatus === "connected") this.send({ type: "unsubscribe", id });
644
+ this.queueIdleCheck();
645
+ };
646
+ }
647
+ onEvent(callback) {
648
+ const entry = (event) => callback(event);
649
+ this.eventCallbacks.add(entry);
650
+ this.ensureConnected();
651
+ return () => {
652
+ if (this.eventCallbacks.delete(entry)) this.queueIdleCheck();
653
+ };
654
+ }
655
+ // --- Writes ---
656
+ /**
657
+ * Queues a write and sends it once a connection's opening state has
658
+ * arrived. Throws, queueing nothing, while the page is disconnected, when
659
+ * the open connection reported the page's level on the store as `read`,
660
+ * or when the message would exceed the message limit.
661
+ */
662
+ write(store, write, local, onMismatch) {
663
+ this.requireReachable();
664
+ if (this.knownLevel(store) === "read") {
665
+ throw refusal("read-only", store === null ? "This page can only read this artifact's store." : `This page can only read resource ${store}.`);
666
+ }
667
+ const seq = this.nextSeq;
668
+ const message = JSON.stringify({ type: "write", seq, ...addressOf(store), write });
669
+ checkWriteMessage(message);
670
+ this.nextSeq += 1;
671
+ let settle;
672
+ const done = new Promise((resolve, reject) => {
673
+ settle = { resolve, reject };
674
+ });
675
+ this.writes.set(seq, { seq, store, local, message, settle, onMismatch });
676
+ this.ensureConnected();
677
+ this.notifyQueue([store], this.ownStore);
678
+ this.flushWrites();
679
+ return done;
680
+ }
681
+ // --- The connection ---
682
+ needed() {
683
+ return this.writes.size > 0 || this.requests.size > 0 || this.accessWaiters.size > 0 || this.subscriptions.size > 0 || this.eventCallbacks.size > 0 || this.accessCallbacks.size > 0 || this.statusCallbacks.size > 0;
684
+ }
685
+ /** Opens a connection when the page has none and is not waiting to reconnect. */
686
+ ensureConnected() {
687
+ if (this.socket !== null || this.reconnectTimer !== null) return;
688
+ this.setStatus("connecting");
689
+ this.connect();
690
+ }
691
+ connect() {
692
+ this.reconnectTimer = null;
693
+ const url = `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}${artifactRoutes.connection(this.id)}`;
694
+ const socket = new WebSocket(url);
695
+ this.socket = socket;
696
+ socket.addEventListener("message", (event) => {
697
+ if (this.socket !== socket || typeof event.data !== "string") return;
698
+ this.receive(JSON.parse(event.data));
699
+ });
700
+ socket.addEventListener("close", () => this.closed(socket));
701
+ }
702
+ queueIdleCheck() {
703
+ if (this.idleCheckQueued) return;
704
+ this.idleCheckQueued = true;
705
+ queueMicrotask(() => {
706
+ this.idleCheckQueued = false;
707
+ if (this.needed()) return;
708
+ if (this.reconnectTimer !== null) clearTimeout(this.reconnectTimer);
709
+ this.reconnectTimer = null;
710
+ this.attempt = 0;
711
+ const socket = this.socket;
712
+ this.socket = null;
713
+ this.forgetAccess();
714
+ socket?.close();
715
+ this.setStatus("idle");
716
+ });
717
+ }
718
+ /** A connection closed, not by the SDK: the page is disconnected until a later connection's opening state. */
719
+ closed(socket) {
720
+ if (this.socket !== socket) return;
721
+ this.socket = null;
722
+ const ownStore = this.ownStore;
723
+ this.forgetAccess();
724
+ if (!this.needed()) {
725
+ this.setStatus("idle");
726
+ return;
727
+ }
728
+ const base = Math.min(BACKOFF_CAP_MS, BACKOFF_START_MS * 2 ** this.attempt);
729
+ this.attempt += 1;
730
+ this.reconnectTimer = setTimeout(() => this.connect(), base / 2 + Math.random() * base / 2);
731
+ this.setStatus("disconnected");
732
+ this.failOutstanding(disconnected(), ownStore);
733
+ this.queueIdleCheck();
734
+ }
735
+ /**
736
+ * The access came from a connection's opening state, changes of it and
737
+ * events, so it holds only while that connection is open: a level changed
738
+ * while the page has no connection reaches it with the next opening state.
739
+ * Access callbacks keep what they last heard, and hear the next opening
740
+ * state's level only if it differs.
741
+ */
742
+ forgetAccess() {
743
+ this.level = void 0;
744
+ this.ownStore = void 0;
745
+ this.bindings.clear();
746
+ }
747
+ /** Rolls back every unconfirmed write at once and rejects it and every outstanding request with `error`. */
748
+ failOutstanding(error, ownStore) {
749
+ const rolledBack = this.queue();
750
+ this.writes.clear();
751
+ const requests = [...this.requests.values(), ...this.accessWaiters];
752
+ this.requests.clear();
753
+ this.accessWaiters.clear();
754
+ if (rolledBack.length > 0) this.notifyQueue([...new Set(rolledBack.map((queued) => queued.store))], ownStore);
755
+ for (const queued of rolledBack) queued.settle.reject(error);
756
+ for (const request of requests) request.reject(error);
757
+ }
758
+ send(message) {
759
+ this.socket?.send(JSON.stringify(message));
760
+ }
761
+ /**
762
+ * Sends, in sequence order, every queued write not yet sent on the open
763
+ * connection. Writes are sent only here, so a write the page makes while it
764
+ * hears an earlier one still reaches the server after it.
765
+ */
766
+ flushWrites() {
767
+ if (this.currentStatus !== "connected") return;
768
+ for (let seq = this.sentSeq + 1; seq < this.nextSeq; seq++) {
769
+ this.sentSeq = seq;
770
+ const queued = this.writes.get(seq);
771
+ if (queued) this.socket?.send(queued.message);
772
+ }
773
+ }
774
+ /** Tells the queue's observers whose queued writes changed, naming the own store, when it is among them, by both the addresses `ownStore` gives it. */
775
+ notifyQueue(stores, ownStore) {
776
+ const own = ownStoreAddresses(ownStore);
777
+ const changed2 = stores.some((store) => own.includes(store)) ? [.../* @__PURE__ */ new Set([...stores, ...own])] : stores;
778
+ for (const observer of this.queueObservers) observer(changed2);
779
+ }
780
+ open(message) {
781
+ this.attempt = 0;
782
+ this.serverTimeOffset = message.serverTime - Date.now();
783
+ const level = this.takeAccess(message);
784
+ for (const [id, subscription] of this.subscriptions) this.send({ type: "subscribe", id, ...addressOf(subscription.store), path: subscription.path });
785
+ for (const request of this.requests.values()) this.send(request.message);
786
+ const first = this.writes.keys().next();
787
+ this.sentSeq = (first.done === true ? this.nextSeq : first.value) - 1;
788
+ this.setStatus("connected");
789
+ const waiters = [...this.accessWaiters];
790
+ this.accessWaiters.clear();
791
+ for (const waiter of waiters) waiter.resolve(level);
792
+ this.accessChanged();
793
+ this.flushWrites();
794
+ this.queueIdleCheck();
795
+ }
796
+ /** Tells each access callback the level now, if it has not heard it. */
797
+ accessChanged() {
798
+ for (const entry of [...this.accessCallbacks]) this.tellAccess(entry);
799
+ }
800
+ receive(message) {
801
+ switch (message.type) {
802
+ case "open":
803
+ this.open(message);
804
+ return;
805
+ case "unavailable":
806
+ this.refuseEverything(refusal("unavailable", message.error));
807
+ return;
808
+ case "applied":
809
+ this.acknowledge(message.seq, (queued) => queued.settle.resolve({ kind: "applied" }));
810
+ return;
811
+ case "mismatch":
812
+ this.acknowledge(message.seq, (queued) => {
813
+ queued.onMismatch?.(message.current);
814
+ queued.settle.resolve({ kind: "mismatch", current: message.current, valueSeq: message.valueSeq });
815
+ });
816
+ return;
817
+ case "refused":
818
+ this.acknowledge(message.seq, (queued) => queued.settle.reject(refusal(message.code, message.error)));
819
+ return;
820
+ case "access":
821
+ this.takeAccess(message);
822
+ this.accessChanged();
823
+ return;
824
+ case "event":
825
+ this.event(message.event);
826
+ return;
827
+ case "value": {
828
+ const subscription = this.subscriptions.get(message.id);
829
+ if (subscription) {
830
+ subscription.handlers.onValue(message.result, message.seq);
831
+ return;
832
+ }
833
+ this.answer(message.id, message);
834
+ return;
835
+ }
836
+ case "error": {
837
+ const subscription = this.subscriptions.get(message.id);
838
+ if (subscription) {
839
+ this.subscriptions.delete(message.id);
840
+ subscription.handlers.onEnd(refusal(message.code, message.error));
841
+ this.queueIdleCheck();
842
+ return;
843
+ }
844
+ const request = this.requests.get(message.id);
845
+ if (!request) return;
846
+ this.requests.delete(message.id);
847
+ request.reject(refusal(message.code, message.error));
848
+ this.queueIdleCheck();
849
+ return;
850
+ }
851
+ case "resources":
852
+ case "resource":
853
+ this.answer(message.id, message);
854
+ return;
855
+ }
856
+ }
857
+ answer(id, reply) {
858
+ const request = this.requests.get(id);
859
+ if (!request) return;
860
+ this.requests.delete(id);
861
+ request.resolve(reply);
862
+ this.queueIdleCheck();
863
+ }
864
+ acknowledge(seq, settle) {
865
+ const queued = this.writes.get(seq);
866
+ if (!queued) return;
867
+ this.writes.delete(seq);
868
+ settle(queued);
869
+ this.notifyQueue([queued.store], this.ownStore);
870
+ this.queueIdleCheck();
871
+ }
872
+ event(event) {
873
+ switch (event.event) {
874
+ case "bound":
875
+ this.bindings.set(event.resourceID, event.access);
876
+ break;
877
+ case "unbound":
878
+ case "destroyed":
879
+ this.bindings.delete(event.resourceID);
880
+ break;
881
+ default:
882
+ break;
883
+ }
884
+ for (const callback of [...this.eventCallbacks]) callPage(callback, event);
885
+ }
886
+ /** The resource layer refuses every request: subscriptions end, and everything outstanding fails, with `unavailable`. */
887
+ refuseEverything(error) {
888
+ for (const [id, subscription] of [...this.subscriptions]) {
889
+ this.subscriptions.delete(id);
890
+ subscription.handlers.onEnd(error);
891
+ }
892
+ this.failOutstanding(error, this.ownStore);
893
+ this.queueIdleCheck();
894
+ }
895
+ };
896
+
897
+ // packages/shared/src/resources/sdk-page.ts
898
+ var connection = null;
899
+ var setups = [];
900
+ function onPageConnection(setup) {
901
+ setups.push(setup);
902
+ if (connection) setup(connection);
903
+ }
904
+ function requireArtifactPage() {
905
+ if (connection) return connection.id;
906
+ const id = pageIDFromPath(location.pathname);
907
+ if (id === null) {
908
+ throw resourceError("not-artifact-page", "This page is not served as an artifact's content, so it has no resources.");
909
+ }
910
+ return id;
911
+ }
912
+ function pageConnection() {
913
+ if (connection) return connection;
914
+ connection = new SdkConnection(requireArtifactPage());
915
+ for (const setup of setups) setup(connection);
916
+ return connection;
917
+ }
918
+
919
+ // packages/shared/src/resources/push-keys.ts
920
+ var PUSH_KEY_ALPHABET = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
921
+ var TIME_CHARACTERS = 8;
922
+ var RANDOM_CHARACTERS = 12;
923
+ var lastTime = -1;
924
+ var lastRandom = new Array(RANDOM_CHARACTERS).fill(0);
925
+ function generatePushKey() {
926
+ const now = Date.now();
927
+ if (now === lastTime) {
928
+ let position = RANDOM_CHARACTERS - 1;
929
+ while (position >= 0 && lastRandom[position] === PUSH_KEY_ALPHABET.length - 1) {
930
+ lastRandom[position] = 0;
931
+ position--;
932
+ }
933
+ if (position >= 0) lastRandom[position]++;
934
+ } else {
935
+ lastTime = now;
936
+ const bytes = crypto.getRandomValues(new Uint8Array(RANDOM_CHARACTERS));
937
+ for (let position = 0; position < RANDOM_CHARACTERS; position++) {
938
+ lastRandom[position] = bytes[position] & PUSH_KEY_ALPHABET.length - 1;
939
+ }
940
+ }
941
+ const timeCharacters = new Array(TIME_CHARACTERS);
942
+ let time = now;
943
+ for (let position = TIME_CHARACTERS - 1; position >= 0; position--) {
944
+ timeCharacters[position] = PUSH_KEY_ALPHABET.charAt(time % PUSH_KEY_ALPHABET.length);
945
+ time = Math.floor(time / PUSH_KEY_ALPHABET.length);
946
+ }
947
+ return timeCharacters.join("") + lastRandom.map((index) => PUSH_KEY_ALPHABET.charAt(index)).join("");
948
+ }
949
+
950
+ // packages/shared/src/resources/sdk-json-store.ts
951
+ var MAX_TRANSACTION_CALLS = 25;
952
+ var refStates = /* @__PURE__ */ new WeakMap();
953
+ function stateOf(ref2) {
954
+ const state = refStates.get(ref2);
955
+ if (!state) throw resourceError("invalid-path", "Not a reference made by ref() or child().");
956
+ return state;
957
+ }
958
+ function parsePath(path) {
959
+ if (typeof path !== "string") throw resourceError("invalid-path", "A path is a string of keys separated by /.");
960
+ return parseJsonPath(path);
961
+ }
962
+ var JsonRef = class _JsonRef {
963
+ key;
964
+ path;
965
+ constructor(store, segments) {
966
+ refStates.set(this, { store, segments });
967
+ this.key = segments.length === 0 ? null : segments[segments.length - 1];
968
+ this.path = segments.join("/");
969
+ }
970
+ get parent() {
971
+ const { store, segments } = stateOf(this);
972
+ return segments.length === 0 ? null : new _JsonRef(store, segments.slice(0, -1));
973
+ }
974
+ get root() {
975
+ const { store, segments } = stateOf(this);
976
+ return segments.length === 0 ? this : new _JsonRef(store, []);
977
+ }
978
+ };
979
+ var JsonThenableRef = class extends JsonRef {
980
+ done;
981
+ constructor(store, segments, written) {
982
+ super(store, segments);
983
+ this.done = written.then(() => new JsonRef(store, segments));
984
+ this.done.catch(() => void 0);
985
+ }
986
+ then(onFulfilled, onRejected) {
987
+ return this.done.then(onFulfilled, onRejected);
988
+ }
989
+ catch(onRejected) {
990
+ return this.done.catch(onRejected);
991
+ }
992
+ finally(onFinally) {
993
+ return this.done.finally(onFinally);
994
+ }
995
+ };
996
+ function getStore(resourceID) {
997
+ requireArtifactPage();
998
+ return Object.freeze({ resourceID: resourceID === void 0 ? null : String(resourceID) });
999
+ }
1000
+ function ref(store, path = "") {
1001
+ requireArtifactPage();
1002
+ return new JsonRef(store, parsePath(path));
1003
+ }
1004
+ function child(parent, path) {
1005
+ requireArtifactPage();
1006
+ const { store, segments } = stateOf(parent);
1007
+ const joined = [...segments, ...parsePath(path)];
1008
+ checkPathSegments(joined);
1009
+ return new JsonRef(store, joined);
1010
+ }
1011
+ function isWithin(inner, outer) {
1012
+ return outer.length <= inner.length && outer.every((segment, index) => inner[index] === segment);
1013
+ }
1014
+ function pendingAt(pendingPaths, segments) {
1015
+ return pendingPaths.some((path) => isWithin(path, segments) || isWithin(segments, path));
1016
+ }
1017
+ function nest(segments, value) {
1018
+ let node = value;
1019
+ for (let index = segments.length - 1; index >= 0; index--) {
1020
+ const parent = {};
1021
+ setMember(parent, segments[index], node);
1022
+ node = parent;
1023
+ }
1024
+ return node;
1025
+ }
1026
+ function viewAt(connection2, store, confirmed, segments) {
1027
+ let root = confirmed.result.exists ? nest(confirmed.segments, confirmed.result.value) : void 0;
1028
+ const pendingPaths = [];
1029
+ for (const queued of connection2.queue()) {
1030
+ if (!connection2.sameStore(queued.store, store)) continue;
1031
+ const local = queued.local;
1032
+ for (const path of local.paths) pendingPaths.push(path);
1033
+ if (queued.seq <= confirmed.seq) continue;
1034
+ try {
1035
+ root = applyJsonWrite(root, local.apply, { now: local.now }, { checkSize: false });
1036
+ } catch {
1037
+ }
1038
+ }
1039
+ return { value: readJsonValue(root, segments), pendingPaths };
1040
+ }
1041
+ var JsonSnapshot = class _JsonSnapshot {
1042
+ key;
1043
+ ref;
1044
+ metadata;
1045
+ value;
1046
+ pendingPaths;
1047
+ constructor(snapshotRef, value, pendingPaths) {
1048
+ this.ref = snapshotRef;
1049
+ this.key = snapshotRef.key;
1050
+ this.value = value;
1051
+ this.pendingPaths = pendingPaths;
1052
+ this.metadata = Object.freeze({ hasPendingWrites: pendingAt(pendingPaths, stateOf(snapshotRef).segments) });
1053
+ }
1054
+ get size() {
1055
+ if (Array.isArray(this.value)) return this.value.length;
1056
+ return isJsonObject(this.value) ? Object.keys(this.value).length : 0;
1057
+ }
1058
+ exists() {
1059
+ return this.value !== void 0;
1060
+ }
1061
+ val() {
1062
+ return this.value === void 0 ? void 0 : structuredClone(this.value);
1063
+ }
1064
+ child(path) {
1065
+ const childRef = child(this.ref, path);
1066
+ return new _JsonSnapshot(childRef, readJsonValue(this.value, parsePath(path)), this.pendingPaths);
1067
+ }
1068
+ forEach(fn) {
1069
+ for (const key of childKeys(this.value)) {
1070
+ if (fn(this.child(key)) === true) return true;
1071
+ }
1072
+ return false;
1073
+ }
1074
+ };
1075
+ var locations = /* @__PURE__ */ new Map();
1076
+ function locationKey(store, segments) {
1077
+ return JSON.stringify([store, ...segments]);
1078
+ }
1079
+ function sameValue(left, right) {
1080
+ if (left === void 0 || right === void 0) return left === right;
1081
+ return jsonEqual(left, right);
1082
+ }
1083
+ function childEvents(before, after) {
1084
+ const old = isJsonObject(before) ? before : {};
1085
+ const next = isJsonObject(after) ? after : {};
1086
+ const keys = [.../* @__PURE__ */ new Set([...Object.keys(old), ...Object.keys(next)])].sort(compareChildKeys);
1087
+ const events = [];
1088
+ for (const key of keys) {
1089
+ const inOld = Object.hasOwn(old, key);
1090
+ const inNext = Object.hasOwn(next, key);
1091
+ if (inNext && !inOld) events.push({ kind: "child-added", key, value: next[key] });
1092
+ else if (inOld && !inNext) events.push({ kind: "child-removed", key, value: old[key] });
1093
+ else if (!jsonEqual(old[key], next[key])) events.push({ kind: "child-changed", key, value: next[key] });
1094
+ }
1095
+ return events;
1096
+ }
1097
+ function deliverView(location2, listeners, view) {
1098
+ const locationRef = new JsonRef(location2.store, location2.segments);
1099
+ const pending = pendingAt(view.pendingPaths, location2.segments);
1100
+ const childCalls = [];
1101
+ const valueListeners = [];
1102
+ for (const listener of listeners) {
1103
+ if (!location2.listeners.has(listener)) continue;
1104
+ if (listener.kind === "value") {
1105
+ const changed2 = !listener.delivered || !sameValue(listener.last, view.value);
1106
+ const cleared = listener.delivered && listener.lastPending && !pending;
1107
+ listener.lastPending = pending;
1108
+ if (!changed2 && !cleared) continue;
1109
+ listener.delivered = true;
1110
+ listener.last = view.value;
1111
+ valueListeners.push(listener);
1112
+ continue;
1113
+ }
1114
+ const before = listener.delivered ? listener.last : void 0;
1115
+ listener.delivered = true;
1116
+ listener.last = view.value;
1117
+ for (const event of childEvents(before, view.value)) {
1118
+ if (event.kind === listener.kind) childCalls.push({ key: event.key, listener, value: event.value });
1119
+ }
1120
+ }
1121
+ childCalls.sort((left, right) => compareChildKeys(left.key, right.key));
1122
+ for (const { key, listener, value } of childCalls) {
1123
+ if (location2.listeners.has(listener)) callPage(listener.callback, new JsonSnapshot(child(locationRef, key), value, view.pendingPaths));
1124
+ }
1125
+ for (const listener of valueListeners) {
1126
+ if (location2.listeners.has(listener)) callPage(listener.callback, new JsonSnapshot(locationRef, view.value, view.pendingPaths));
1127
+ }
1128
+ }
1129
+ function deliverStart(location2, listener) {
1130
+ const start = listener.start;
1131
+ listener.start = null;
1132
+ if (start !== null && !listener.delivered && location2.listeners.has(listener)) deliverView(location2, [listener], start);
1133
+ }
1134
+ function capture(connection2, affected) {
1135
+ const changes = [];
1136
+ for (const location2 of affected) {
1137
+ if (location2.confirmed === null) continue;
1138
+ changes.push({
1139
+ location: location2,
1140
+ listeners: [...location2.listeners],
1141
+ view: viewAt(connection2, location2.store.resourceID, location2.confirmed, location2.segments)
1142
+ });
1143
+ }
1144
+ return changes;
1145
+ }
1146
+ function deliverChange(changes) {
1147
+ for (const { location: location2, listeners, view } of changes) {
1148
+ for (const listener of listeners) deliverStart(location2, listener);
1149
+ deliverView(location2, listeners, view);
1150
+ }
1151
+ }
1152
+ var waitingDeliveries = [];
1153
+ var delivering = false;
1154
+ function runDelivery(delivery) {
1155
+ waitingDeliveries.push(delivery);
1156
+ if (delivering) return;
1157
+ delivering = true;
1158
+ try {
1159
+ for (let next = waitingDeliveries.shift(); next !== void 0; next = waitingDeliveries.shift()) next();
1160
+ } finally {
1161
+ delivering = false;
1162
+ }
1163
+ }
1164
+ function changed(connection2, affected) {
1165
+ const changes = capture(connection2, affected);
1166
+ if (changes.length > 0) runDelivery(() => deliverChange(changes));
1167
+ }
1168
+ function refreshStores(connection2, stores) {
1169
+ changed(connection2, [...locations.values()].filter((location2) => stores.includes(location2.store.resourceID)));
1170
+ }
1171
+ onPageConnection((connection2) => connection2.observeQueue((stores) => refreshStores(connection2, stores)));
1172
+ function endLocation(location2, error) {
1173
+ if (locations.get(location2.key) === location2) locations.delete(location2.key);
1174
+ const listeners = [...location2.listeners];
1175
+ location2.listeners.clear();
1176
+ for (const listener of listeners) {
1177
+ if (listener.onError) callPage(listener.onError, error);
1178
+ }
1179
+ }
1180
+ function listen(listenRef, kind, callback, onError) {
1181
+ const connection2 = pageConnection();
1182
+ const { store, segments } = stateOf(listenRef);
1183
+ const key = locationKey(store.resourceID, segments);
1184
+ let location2 = locations.get(key);
1185
+ if (!location2) {
1186
+ const created = { key, store, segments, confirmed: null, listeners: /* @__PURE__ */ new Set(), unsubscribe: () => void 0 };
1187
+ locations.set(key, created);
1188
+ created.unsubscribe = connection2.subscribe(store.resourceID, segments.join("/"), {
1189
+ onValue: (result, seq) => {
1190
+ created.confirmed = { segments, result, seq };
1191
+ changed(connection2, [created]);
1192
+ },
1193
+ onEnd: (error) => endLocation(created, error)
1194
+ });
1195
+ location2 = created;
1196
+ }
1197
+ const listener = { kind, callback, onError, delivered: false, start: null, last: void 0, lastPending: false };
1198
+ const target = location2;
1199
+ target.listeners.add(listener);
1200
+ if (target.confirmed !== null) {
1201
+ listener.start = viewAt(connection2, store.resourceID, target.confirmed, segments);
1202
+ queueMicrotask(() => runDelivery(() => deliverStart(target, listener)));
1203
+ }
1204
+ return () => {
1205
+ if (!target.listeners.delete(listener) || target.listeners.size > 0) return;
1206
+ if (locations.get(key) === target) locations.delete(key);
1207
+ target.unsubscribe();
1208
+ };
1209
+ }
1210
+ function onValue(valueRef, callback, onError) {
1211
+ return listen(valueRef, "value", callback, onError);
1212
+ }
1213
+ function onChildAdded(parentRef, callback, onError) {
1214
+ return listen(parentRef, "child-added", callback, onError);
1215
+ }
1216
+ function onChildChanged(parentRef, callback, onError) {
1217
+ return listen(parentRef, "child-changed", callback, onError);
1218
+ }
1219
+ function onChildRemoved(parentRef, callback, onError) {
1220
+ return listen(parentRef, "child-removed", callback, onError);
1221
+ }
1222
+ function heldView(connection2, store, segments) {
1223
+ for (const location2 of locations.values()) {
1224
+ if (!connection2.sameStore(location2.store.resourceID, store) || location2.confirmed === null || !isWithin(segments, location2.segments)) continue;
1225
+ return viewAt(connection2, store, location2.confirmed, segments);
1226
+ }
1227
+ return null;
1228
+ }
1229
+ async function fetchView(connection2, store, segments) {
1230
+ const reply = await connection2.request({ type: "get", ...store === null ? {} : { resourceID: store }, path: segments.join("/") });
1231
+ if (reply.type !== "value") throw resourceError("unavailable", "The server answered a read unexpectedly.");
1232
+ return viewAt(connection2, store, { segments, result: reply.result, seq: reply.seq }, segments);
1233
+ }
1234
+ async function get(getRef) {
1235
+ const connection2 = pageConnection();
1236
+ const { store, segments } = stateOf(getRef);
1237
+ const view = await fetchView(connection2, store.resourceID, segments);
1238
+ return new JsonSnapshot(getRef, view.value, view.pendingPaths);
1239
+ }
1240
+ function pendingNow(connection2, store) {
1241
+ return connection2.queue().flatMap((queued) => connection2.sameStore(queued.store, store) ? queued.local.paths : []);
1242
+ }
1243
+ function queueWrite(writeRef, wire, apply, paths, onMismatch) {
1244
+ const { store } = stateOf(writeRef);
1245
+ const connection2 = pageConnection();
1246
+ const now = connection2.serverNow();
1247
+ applyJsonWrite(void 0, apply, { now }, { checkSize: false });
1248
+ const local = { apply, paths, now };
1249
+ return connection2.write(store.resourceID, wire, local, onMismatch);
1250
+ }
1251
+ function settled(start) {
1252
+ try {
1253
+ return start();
1254
+ } catch (error) {
1255
+ return Promise.reject(error);
1256
+ }
1257
+ }
1258
+ function set(setRef, value) {
1259
+ return settled(() => {
1260
+ requireArtifactPage();
1261
+ const { segments } = stateOf(setRef);
1262
+ validateWriteValue(value);
1263
+ const path = segments.join("/");
1264
+ const encoded = encodeWriteValue(value);
1265
+ return queueWrite(setRef, { kind: "set", path, value: encoded }, { kind: "set", path, value: decodeWriteValue(encoded) }, [segments]);
1266
+ }).then(() => void 0);
1267
+ }
1268
+ function update(updateRef, values) {
1269
+ return settled(() => {
1270
+ requireArtifactPage();
1271
+ const { segments } = stateOf(updateRef);
1272
+ validateUpdateValues(values);
1273
+ const path = segments.join("/");
1274
+ const encoded = encodeUpdateEntries(values);
1275
+ const entries = decodeUpdateEntries(encoded);
1276
+ const paths = entries.map(([key]) => [...segments, ...parsePath(key)]);
1277
+ return queueWrite(updateRef, { kind: "update", path, entries: encoded }, { kind: "update", path, entries }, paths);
1278
+ }).then(() => void 0);
1279
+ }
1280
+ function push(parentRef, value) {
1281
+ requireArtifactPage();
1282
+ const { store, segments } = stateOf(parentRef);
1283
+ const key = generatePushKey();
1284
+ const childSegments = [...segments, key];
1285
+ checkPathSegments(childSegments);
1286
+ const done = value === void 0 ? Promise.resolve() : settled(() => {
1287
+ validateWriteValue(value);
1288
+ const encoded = encodeWriteValue(value);
1289
+ const wire = { kind: "push", path: segments.join("/"), key, value: encoded };
1290
+ return queueWrite(parentRef, wire, { kind: "set", path: childSegments.join("/"), value: decodeWriteValue(encoded) }, [childSegments]);
1291
+ }).then(() => void 0);
1292
+ return new JsonThenableRef(store, childSegments, done);
1293
+ }
1294
+ function remove(removeRef) {
1295
+ return settled(() => {
1296
+ requireArtifactPage();
1297
+ const { segments } = stateOf(removeRef);
1298
+ const path = segments.join("/");
1299
+ return queueWrite(removeRef, { kind: "remove", path }, { kind: "remove", path }, [segments]);
1300
+ }).then(() => void 0);
1301
+ }
1302
+ function runTransaction(transactionRef, fn) {
1303
+ return settled(async () => {
1304
+ const connection2 = pageConnection();
1305
+ connection2.requireReachable();
1306
+ const { store, segments } = stateOf(transactionRef);
1307
+ const path = segments.join("/");
1308
+ const first = heldView(connection2, store.resourceID, segments) ?? await fetchView(connection2, store.resourceID, segments);
1309
+ const start = first.value === void 0 ? { exists: false } : { exists: true, value: first.value };
1310
+ return new Promise((resolve, reject) => {
1311
+ const finish = (committed, value) => resolve({ committed, snapshot: new JsonSnapshot(transactionRef, value, pendingNow(connection2, store.resourceID)) });
1312
+ const attempt = (current, calls) => {
1313
+ let result;
1314
+ try {
1315
+ result = fn(current.exists ? structuredClone(current.value) : void 0);
1316
+ if (result === void 0) {
1317
+ finish(false, current.exists ? current.value : void 0);
1318
+ return;
1319
+ }
1320
+ validateJsonValue(result);
1321
+ const committed = structuredClone(result);
1322
+ queueWrite(
1323
+ transactionRef,
1324
+ { kind: "compare-and-set", path, expected: current, value: committed },
1325
+ { kind: "set", path, value: committed },
1326
+ [segments],
1327
+ (now) => {
1328
+ if (calls >= MAX_TRANSACTION_CALLS) {
1329
+ reject(resourceError("max-retries", `The transaction's function was called ${MAX_TRANSACTION_CALLS} times without a commit.`));
1330
+ return;
1331
+ }
1332
+ attempt(now, calls + 1);
1333
+ }
1334
+ ).then((outcome) => {
1335
+ if (outcome.kind === "applied") finish(true, committed);
1336
+ }, reject);
1337
+ } catch (error) {
1338
+ reject(error);
1339
+ }
1340
+ };
1341
+ attempt(start, 1);
1342
+ });
1343
+ });
1344
+ }
1345
+
1346
+ // packages/shared/src/resources/sdk.ts
1347
+ function unexpectedReply() {
1348
+ return resourceError("unavailable", "The server answered a request unexpectedly.");
1349
+ }
1350
+ async function getAccess() {
1351
+ const level = await pageConnection().access();
1352
+ if (level === null) throw resourceError("no-store", "This page's address reaches no artifact that has a store.");
1353
+ return level;
1354
+ }
1355
+ function onAccessChanged(callback) {
1356
+ return pageConnection().onAccess(callback);
1357
+ }
1358
+ async function listResources() {
1359
+ const reply = await pageConnection().request({ type: "list" });
1360
+ if (reply.type !== "resources") throw unexpectedReply();
1361
+ return [...reply.resources].sort((left, right) => left.resourceID < right.resourceID ? -1 : left.resourceID > right.resourceID ? 1 : 0);
1362
+ }
1363
+ async function getResourceInfo(resourceID) {
1364
+ const reply = await pageConnection().request({ type: "info", resourceID: String(resourceID) });
1365
+ if (reply.type !== "resource") throw unexpectedReply();
1366
+ return reply.resource;
1367
+ }
1368
+ function onResourcesChanged(callback) {
1369
+ return pageConnection().onEvent(callback);
1370
+ }
1371
+ function getConnectionStatus() {
1372
+ return pageConnection().status;
1373
+ }
1374
+ function onConnectionStatusChanged(callback) {
1375
+ return pageConnection().onStatus(callback);
1376
+ }
1377
+ function serverTimestamp2() {
1378
+ requireArtifactPage();
1379
+ return serverTimestamp();
1380
+ }
1381
+ function increment2(n) {
1382
+ requireArtifactPage();
1383
+ return increment(n);
1384
+ }
1385
+ function deleteValue2() {
1386
+ requireArtifactPage();
1387
+ return deleteValue();
1388
+ }
1389
+ export {
1390
+ child,
1391
+ deleteValue2 as deleteValue,
1392
+ get,
1393
+ getAccess,
1394
+ getConnectionStatus,
1395
+ getResourceInfo,
1396
+ getStore,
1397
+ increment2 as increment,
1398
+ listResources,
1399
+ onAccessChanged,
1400
+ onChildAdded,
1401
+ onChildChanged,
1402
+ onChildRemoved,
1403
+ onConnectionStatusChanged,
1404
+ onResourcesChanged,
1405
+ onValue,
1406
+ push,
1407
+ ref,
1408
+ remove,
1409
+ runTransaction,
1410
+ serverTimestamp2 as serverTimestamp,
1411
+ set,
1412
+ update
1413
+ };