@midsummer-ai/sdk 0.1.0-staging.4966 → 0.1.0-staging.4974

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.
@@ -1,7 +1,7 @@
1
1
  import { t as StorageError } from "./errors-B1tO_wdm.mjs";
2
- import { a as checkListLimit, c as checkPartNumber, d as checkSha256, f as checkUploadId, h as missingByHead, i as checkKey, l as checkParts, m as invalid, o as checkMetadata, r as checkBucketName, s as checkMissingKeys, u as checkRange } from "./names-44OMPNTX.mjs";
2
+ import { a as checkListLimit, c as checkPartNumber, d as checkSha256, f as checkUploadId, g as missingByHead, h as invalid, i as checkKey, l as checkParts, o as checkMetadata, p as checkWatch, r as checkBucketName, s as checkMissingKeys, u as checkRange } from "./names-C-VZGec6.mjs";
3
3
  import { a as processEnv, n as here, o as workloadTransport, r as late, t as clientHeaders } from "./here-C2jhTheQ.mjs";
4
- import { bucketsOf, remote, repeatable, serve } from "./wire.mjs";
4
+ import { bucketsOf, decodeFrame, encodeFrame, remote, repeatable, serve, watchFrames } from "./wire.mjs";
5
5
  //#region src/socket.ts
6
6
  /**
7
7
  * Storage's wire over a WebSocket: one connection carries every call, so a client pays for one HTTP
@@ -26,6 +26,7 @@ const encoder = new TextEncoder();
26
26
  const SOCKET_LIFE_MS = 6e4;
27
27
  const SOCKET_FRAMES = 4e3;
28
28
  const SESSION_CONCURRENCY = 32;
29
+ const SESSION_WATCHES = 100;
29
30
  const hex = (bytes) => [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
30
31
  async function sign(secret, challenge) {
31
32
  const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
@@ -84,6 +85,10 @@ function socket(url, options) {
84
85
  return fallback.send(frame);
85
86
  }
86
87
  },
88
+ subscribe(frame, on) {
89
+ if (noSocket) throw new StorageError("unavailable", "Watching needs a WebSocket, and this runtime has none");
90
+ return lines.reduce((least, one) => one.inFlight() < least.inFlight() ? one : least).subscribe(frame, on);
91
+ },
87
92
  close() {
88
93
  for (const one of lines) one.close();
89
94
  }
@@ -93,6 +98,10 @@ function socket(url, options) {
93
98
  function line(url, options) {
94
99
  const Socket = options.WebSocket ?? globalThis.WebSocket;
95
100
  const waiting = /* @__PURE__ */ new Map();
101
+ const streams = /* @__PURE__ */ new Map();
102
+ const lose = (ws) => {
103
+ for (const [id, stream] of streams) if (stream.on === ws) streams.delete(id), stream.deliver(null);
104
+ };
96
105
  let open = null;
97
106
  let next = 0;
98
107
  function connect() {
@@ -120,12 +129,14 @@ function line(url, options) {
120
129
  signature
121
130
  })));
122
131
  else if (said.ready) clearTimeout(late), ready(ws);
123
- else if (said.closing) open = null;
132
+ else if (said.closing) open = null, lose(ws);
124
133
  else lost(new StorageError("forbidden", said.refused ?? "Storage refused the key"));
125
134
  return;
126
135
  }
127
136
  const message = new Uint8Array(event.data);
128
137
  const id = new DataView(message.buffer, message.byteOffset).getUint32(0, true);
138
+ const stream = streams.get(id);
139
+ if (stream) return stream.deliver(message.subarray(4));
129
140
  waiting.get(id)?.done(message.subarray(4));
130
141
  waiting.delete(id);
131
142
  });
@@ -134,6 +145,7 @@ function line(url, options) {
134
145
  if (open === opening) open = null;
135
146
  refused(new Unreached());
136
147
  for (const [id, call] of waiting) if (call.on === ws) waiting.delete(id), call.lost();
148
+ lose(ws);
137
149
  };
138
150
  ws.addEventListener("close", closed);
139
151
  ws.addEventListener("error", closed);
@@ -167,6 +179,29 @@ function line(url, options) {
167
179
  if (sends === SENDS) throw new StorageError("unavailable", "The connection to Storage closed before it answered");
168
180
  }
169
181
  },
182
+ subscribe(frame, on) {
183
+ let stopped = false, id = 0, carrier = null;
184
+ connect().then((ws) => {
185
+ if (stopped) return;
186
+ if (ws.readyState !== OPEN) return on(null);
187
+ id = next = next + 1 >>> 0;
188
+ carrier = ws;
189
+ streams.set(id, {
190
+ on: ws,
191
+ deliver: on
192
+ });
193
+ ws.send(tagged(id, frame));
194
+ }, () => {
195
+ if (!stopped) on(null);
196
+ });
197
+ return { close() {
198
+ stopped = true;
199
+ if (id && streams.delete(id) && carrier?.readyState === OPEN) carrier.send(tagged(next = next + 1 >>> 0, encodeFrame({
200
+ op: "unwatch",
201
+ watch: id
202
+ })));
203
+ } };
204
+ },
170
205
  close() {
171
206
  open?.then((ws) => ws.close(1e3, "done"), () => {});
172
207
  }
@@ -206,6 +241,7 @@ function keyed(engine, credential) {
206
241
  abortUpload: (bucket, ...rest) => engine.abortUpload(writable(bucket), ...rest),
207
242
  usage: metering,
208
243
  operations: metering,
244
+ ...engine.watch ? { watch: (bucket, ...rest) => engine.watch(id(bucket), ...rest) } : {},
209
245
  ...streamsOf(engine, id, writable)
210
246
  };
211
247
  }
@@ -213,6 +249,42 @@ function keyed(engine, credential) {
213
249
  function socketSession(options) {
214
250
  const challenge = hex(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)).buffer);
215
251
  let answer = null;
252
+ let reached = null;
253
+ const watches = /* @__PURE__ */ new Map();
254
+ let ended = false;
255
+ /** Begins or ends a watch: its answers go out by `push`, tagged with the id that began it. */
256
+ const watchCall = (id, header) => {
257
+ if (header.op === "unwatch") {
258
+ const watch = typeof header.watch === "number" ? watches.get(header.watch) : void 0;
259
+ if (watch) watch.close(), watches.delete(header.watch);
260
+ return tagged(id, encodeFrame({ done: true }));
261
+ }
262
+ const push = options.push;
263
+ try {
264
+ if (!push || !reached?.watch) throw new StorageError("unavailable", "This server can't keep a watch open");
265
+ if (watches.size >= SESSION_WATCHES) throw new StorageError("invalid", `A connection holds at most ${SESSION_WATCHES} watches`);
266
+ const bucket = typeof header.bucket === "string" ? header.bucket : "";
267
+ const keys = Array.isArray(header.keys) ? header.keys : void 0, prefix = typeof header.prefix === "string" ? header.prefix : void 0;
268
+ const after = typeof header.after === "string" ? header.after : void 0;
269
+ const watching = {
270
+ ...keys ? { keys } : {},
271
+ ...prefix !== void 0 ? { prefix } : {},
272
+ ...after !== void 0 ? { after } : {}
273
+ };
274
+ checkBucketName(bucket);
275
+ checkWatch(watching);
276
+ const tell = (frame) => {
277
+ if (!ended) push(tagged(id, frame));
278
+ };
279
+ const watch = reached.watch(bucket, watching, (event) => tell(watchFrames.event(event)), (error) => (watches.delete(id), tell(watchFrames.refused(error))));
280
+ watches.set(id, watch);
281
+ watch.ready.then((cursor) => tell(watchFrames.ready(cursor)), (error) => (watches.delete(id), tell(watchFrames.refused(error instanceof StorageError ? error : new StorageError("unavailable", "The watch could not begin")))));
282
+ return null;
283
+ } catch (error) {
284
+ if (error instanceof StorageError) return tagged(id, watchFrames.refused(error));
285
+ throw error;
286
+ }
287
+ };
216
288
  let closing = false, inFlight = 0, frames = 0, drained = null;
217
289
  const turns = [];
218
290
  let settle;
@@ -227,6 +299,11 @@ function socketSession(options) {
227
299
  return inFlight === 0 ? Promise.resolve() : new Promise((resolve) => drained = resolve);
228
300
  },
229
301
  settled,
302
+ end() {
303
+ ended = true;
304
+ for (const watch of watches.values()) watch.close();
305
+ watches.clear();
306
+ },
230
307
  async receive(message) {
231
308
  if (typeof message === "string") {
232
309
  if (answer) return null;
@@ -241,13 +318,22 @@ function socketSession(options) {
241
318
  settle("refused");
242
319
  return JSON.stringify({ refused: "The key is unknown, or the signature does not match" });
243
320
  }
244
- answer = serve(keyed(options.engine, credential));
321
+ reached = keyed(options.engine, credential);
322
+ answer = serve(reached);
245
323
  settle("ready");
246
324
  return JSON.stringify({ ready: true });
247
325
  }
248
326
  if (!answer) return null;
249
327
  const bytes = message instanceof Uint8Array ? message : message instanceof Blob ? new Uint8Array(await message.arrayBuffer()) : new Uint8Array(message);
250
328
  const id = new DataView(bytes.buffer, bytes.byteOffset).getUint32(0, true);
329
+ let header;
330
+ try {
331
+ header = decodeFrame(bytes.subarray(4)).header;
332
+ } catch {
333
+ header = void 0;
334
+ }
335
+ const op = typeof header === "object" && header !== null ? header.op : void 0;
336
+ if (op === "watch" || op === "unwatch") return watchCall(id, header);
251
337
  inFlight += 1;
252
338
  frames += 1;
253
339
  if (inFlight > SESSION_CONCURRENCY) await new Promise((go) => turns.push(go));
@@ -469,6 +555,16 @@ function storage(engine) {
469
555
  if (engine.missing) return engine.missing(name, keys);
470
556
  return missingByHead(engine, name, keys);
471
557
  },
558
+ watch(options) {
559
+ checkWatch(options);
560
+ return watchOf((on, ended) => {
561
+ if (!engine.watch) throw new StorageError("unavailable", "Watching needs a connection that stays open: connect with a storage key, client(origin, { key, secret }).");
562
+ return engine.watch(name, {
563
+ ...options.keys ? { keys: [...options.keys] } : { prefix: options.prefix ?? "" },
564
+ ...options.after !== void 0 ? { after: options.after } : {}
565
+ }, on, ended);
566
+ });
567
+ },
472
568
  async delete(key) {
473
569
  checkKey(key);
474
570
  return engine.delete(name, key);
@@ -524,6 +620,67 @@ function storage(engine) {
524
620
  };
525
621
  } };
526
622
  }
623
+ /** A watch read with `for await`, over an engine's: what it is told waits in order until it is taken. */
624
+ function watchOf(start) {
625
+ const waiting = [];
626
+ let wake = null, done = false, failure = null;
627
+ const poke = () => {
628
+ const go = wake;
629
+ wake = null;
630
+ go?.();
631
+ };
632
+ let started;
633
+ try {
634
+ started = start((event) => {
635
+ if (!done) waiting.push(event), poke();
636
+ }, (error) => {
637
+ if (!done) failure = error, done = true, poke();
638
+ });
639
+ } catch (error) {
640
+ const refused = error instanceof StorageError ? error : new StorageError("unavailable", String(error));
641
+ started = {
642
+ ready: Promise.reject(refused),
643
+ close() {}
644
+ };
645
+ failure = refused;
646
+ done = true;
647
+ }
648
+ started.ready.catch((error) => {
649
+ if (!done) failure = error instanceof StorageError ? error : new StorageError("unavailable", String(error)), done = true, poke();
650
+ });
651
+ const close = () => {
652
+ if (!done) done = true, started.close(), poke();
653
+ };
654
+ return {
655
+ ready: started.ready,
656
+ close,
657
+ [Symbol.asyncIterator]() {
658
+ return {
659
+ async next() {
660
+ for (;;) {
661
+ if (waiting.length) return {
662
+ value: waiting.shift(),
663
+ done: false
664
+ };
665
+ if (failure) throw failure;
666
+ if (done) return {
667
+ value: void 0,
668
+ done: true
669
+ };
670
+ await new Promise((resolve) => wake = resolve);
671
+ }
672
+ },
673
+ async return() {
674
+ close();
675
+ return {
676
+ value: void 0,
677
+ done: true
678
+ };
679
+ }
680
+ };
681
+ }
682
+ };
683
+ }
527
684
  function bytesOf(body) {
528
685
  if (typeof body === "string") return new TextEncoder().encode(body);
529
686
  if (body instanceof Uint8Array) return body;
package/stand-in.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { m as StorageEngine } from "./index-_phnWnst.mjs";
1
+ import { g as StorageEngine } from "./index-BhrtT3r7.mjs";
2
2
  //#region src/stand-in.d.ts
3
3
  declare function standIn(options: {
4
4
  readonly clock: () => number;
package/stand-in.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as StorageError } from "./errors-B1tO_wdm.mjs";
2
- import { _ as sameSizes, g as resolveRange, n as checkBodySha256, p as compareKeys, v as sha256, y as uploadSha256Refusal } from "./names-44OMPNTX.mjs";
2
+ import { _ as resolveRange, b as uploadSha256Refusal, m as compareKeys, n as checkBodySha256, v as sameSizes, y as sha256 } from "./names-C-VZGec6.mjs";
3
3
  //#region src/stand-in.ts
4
4
  /**
5
5
  * Storage's Stand-in: the Capability's behaviour in memory, for `midsummer dev` and tests. It holds
@@ -9,6 +9,8 @@ import { _ as sameSizes, g as resolveRange, n as checkBodySha256, p as compareKe
9
9
  *
10
10
  * A Bucket exists from its first put. Everything is lost when the process ends.
11
11
  */
12
+ /** Changes a Bucket keeps for watches to catch up from. */
13
+ const KEPT = 1e5;
12
14
  function standIn(options) {
13
15
  const buckets = /* @__PURE__ */ new Map();
14
16
  const calls = /* @__PURE__ */ new Map();
@@ -43,6 +45,27 @@ function standIn(options) {
43
45
  range: at
44
46
  };
45
47
  };
48
+ const epoch = crypto.randomUUID().slice(0, 8);
49
+ let seq = 0;
50
+ const changes = /* @__PURE__ */ new Map();
51
+ const watchers = /* @__PURE__ */ new Map();
52
+ const matches = (options, key) => options.keys ? options.keys.includes(key) : key.startsWith(options.prefix ?? "");
53
+ const changed = (bucket, key, etag) => {
54
+ seq += 1;
55
+ let log = changes.get(bucket);
56
+ if (!log) changes.set(bucket, log = []);
57
+ log.push({
58
+ seq,
59
+ key,
60
+ etag
61
+ });
62
+ if (log.length > KEPT) log.shift();
63
+ for (const watcher of watchers.get(bucket) ?? []) if (matches(watcher.options, key)) watcher.on({
64
+ key,
65
+ etag,
66
+ cursor: `${epoch}.${seq}`
67
+ });
68
+ };
46
69
  const engine = {
47
70
  async put(bucket, key, body, put) {
48
71
  count(bucket, true);
@@ -63,6 +86,7 @@ function standIn(options) {
63
86
  object,
64
87
  body: body.slice()
65
88
  });
89
+ changed(bucket, key, etag);
66
90
  return object;
67
91
  },
68
92
  async get(bucket, key, range, limit) {
@@ -85,7 +109,7 @@ function standIn(options) {
85
109
  },
86
110
  async delete(bucket, key) {
87
111
  count(bucket, true);
88
- buckets.get(bucket)?.delete(key);
112
+ if (buckets.get(bucket)?.delete(key)) changed(bucket, key, null);
89
113
  },
90
114
  async list(bucket, { prefix, delimiter, after, limit }) {
91
115
  count(bucket, false);
@@ -124,6 +148,7 @@ function standIn(options) {
124
148
  object,
125
149
  body: source.body
126
150
  });
151
+ changed(bucket, to, object.etag);
127
152
  return object;
128
153
  },
129
154
  async createUpload(bucket, key, upload) {
@@ -177,6 +202,41 @@ function standIn(options) {
177
202
  uploadOf(bucket, key, uploadId);
178
203
  uploads.delete(uploadId);
179
204
  },
205
+ watch(bucket, watching, on) {
206
+ const log = changes.get(bucket) ?? [];
207
+ if (watching.after !== void 0) {
208
+ const [from, at] = watching.after.split(".");
209
+ const first = log[0]?.seq ?? seq + 1;
210
+ if (from !== epoch || Number(at) > seq) on({
211
+ reset: true,
212
+ cursor: `${epoch}.${seq}`
213
+ });
214
+ else if (Number(at) < first - 1) on({
215
+ reset: true,
216
+ cursor: `${epoch}.${seq}`
217
+ });
218
+ else {
219
+ const latest = /* @__PURE__ */ new Map();
220
+ for (const row of log) if (row.seq > Number(at) && matches(watching, row.key)) latest.delete(row.key), latest.set(row.key, row);
221
+ for (const row of latest.values()) on({
222
+ key: row.key,
223
+ etag: row.etag,
224
+ cursor: `${epoch}.${row.seq}`
225
+ });
226
+ }
227
+ }
228
+ const watcher = {
229
+ options: watching,
230
+ on
231
+ };
232
+ let set = watchers.get(bucket);
233
+ if (!set) watchers.set(bucket, set = /* @__PURE__ */ new Set());
234
+ set.add(watcher);
235
+ return {
236
+ ready: Promise.resolve(`${epoch}.${seq}`),
237
+ close: () => void watchers.get(bucket)?.delete(watcher)
238
+ };
239
+ },
180
240
  async operations(bucket, from, to) {
181
241
  const window = (calls.get(bucket) ?? []).filter((call) => call.at >= from && call.at < to);
182
242
  return {
@@ -1,4 +1,4 @@
1
- import { m as StorageEngine, t as Body } from "../index-_phnWnst.mjs";
1
+ import { g as StorageEngine, t as Body } from "../index-BhrtT3r7.mjs";
2
2
  import { n as AuthProvider, r as VerifierOptions } from "../auth-B7rCtXFQ.mjs";
3
3
  //#region src/storage/files.d.ts
4
4
  /** Whether a rule only reads its folder, or reads, puts and deletes in it. */
package/storage/files.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as StorageError } from "../errors-B1tO_wdm.mjs";
2
- import { r as checkBucketName } from "../names-44OMPNTX.mjs";
2
+ import { r as checkBucketName } from "../names-C-VZGec6.mjs";
3
3
  import { t as clientHeaders } from "../here-C2jhTheQ.mjs";
4
4
  import { inertHeaders } from "../inert.mjs";
5
5
  import { DatabaseError } from "../database/errors.mjs";
package/wire.d.mts CHANGED
@@ -1,9 +1,22 @@
1
- import { m as StorageEngine } from "./index-_phnWnst.mjs";
1
+ import { D as StorageError, g as StorageEngine, x as WatchEvent } from "./index-BhrtT3r7.mjs";
2
2
  //#region src/wire.d.ts
3
3
  /** Carries one request frame to a server and brings back its answer frame. */
4
4
  interface Transport {
5
5
  send(frame: Uint8Array): Promise<Uint8Array>;
6
+ /**
7
+ * Sends a frame whose answers keep coming (a watch), each to `on`, until `close`; `on(null)` says the connection
8
+ * carrying it was lost or is moving, so nothing more comes on it. Only a connection that stays open has it.
9
+ */
10
+ subscribe?(frame: Uint8Array, on: (answer: Uint8Array | null) => void): {
11
+ close(): void;
12
+ };
6
13
  }
14
+ /** The frames a watch is answered with, as a server sends them. */
15
+ declare const watchFrames: {
16
+ ready: (cursor: string) => Uint8Array<ArrayBufferLike>;
17
+ event: (event: WatchEvent) => Uint8Array<ArrayBufferLike>;
18
+ refused: (error: StorageError) => Uint8Array<ArrayBufferLike>;
19
+ };
7
20
  /**
8
21
  * The engine on the client's side of the wire. With `batch`, the calls made in the same turn travel
9
22
  * as one batch frame (the platform's own calls do not batch; clients that issue many at once do).
@@ -51,4 +64,4 @@ declare function decodeFrame(frame: Uint8Array): {
51
64
  body: Uint8Array;
52
65
  };
53
66
  //#endregion
54
- export { Transport, bucketsOf, decodeFrame, encodeFrame, http, remote, repeatable, serve, serveHttp };
67
+ export { Transport, bucketsOf, decodeFrame, encodeFrame, http, remote, repeatable, serve, serveHttp, watchFrames };
package/wire.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as storageErrorCodes, r as storageErrorReasons, t as StorageError } from "./errors-B1tO_wdm.mjs";
2
- import { a as checkListLimit, c as checkPartNumber, d as checkSha256, f as checkUploadId, h as missingByHead, i as checkKey, l as checkParts, o as checkMetadata, r as checkBucketName, s as checkMissingKeys, u as checkRange } from "./names-44OMPNTX.mjs";
2
+ import { a as checkListLimit, c as checkPartNumber, d as checkSha256, f as checkUploadId, g as missingByHead, i as checkKey, l as checkParts, o as checkMetadata, r as checkBucketName, s as checkMissingKeys, u as checkRange } from "./names-C-VZGec6.mjs";
3
3
  import { t as clientHeaders } from "./here-C2jhTheQ.mjs";
4
4
  import { z } from "zod";
5
5
  //#region src/wire.ts
@@ -110,6 +110,17 @@ const request = z.discriminatedUnion("op", [
110
110
  bucket: z.string(),
111
111
  from: z.number(),
112
112
  to: z.number()
113
+ }).strict(),
114
+ z.object({
115
+ op: z.literal("watch"),
116
+ bucket: z.string(),
117
+ keys: z.array(z.string()).optional(),
118
+ prefix: z.string().optional(),
119
+ after: z.string().optional()
120
+ }).strict(),
121
+ z.object({
122
+ op: z.literal("unwatch"),
123
+ watch: z.number().int()
113
124
  }).strict()
114
125
  ]);
115
126
  const stored = z.object({
@@ -156,6 +167,35 @@ const answer = z.union([
156
167
  }).strict() }).strict(),
157
168
  z.object({ again: z.literal(true) }).strict()
158
169
  ]);
170
+ /** What a watch is answered, again and again: ready from a cursor, the keys that changed, a reset, or a refusal that ends it. */
171
+ const watchAnswer = z.union([
172
+ z.object({
173
+ error: z.enum(storageErrorCodes),
174
+ why: z.string(),
175
+ reason: z.enum(storageErrorReasons).optional()
176
+ }).strict(),
177
+ z.object({ watching: z.string() }).strict(),
178
+ z.object({ events: z.array(z.object({
179
+ key: z.string(),
180
+ etag: z.string().nullable(),
181
+ cursor: z.string()
182
+ }).strict()) }).strict(),
183
+ z.object({ reset: z.string() }).strict()
184
+ ]);
185
+ /** The frames a watch is answered with, as a server sends them. */
186
+ const watchFrames = {
187
+ ready: (cursor) => encodeFrame({ watching: cursor }),
188
+ event: (event) => encodeFrame("reset" in event ? { reset: event.cursor } : { events: [{
189
+ key: event.key,
190
+ etag: event.etag,
191
+ cursor: event.cursor
192
+ }] }),
193
+ refused: (error) => encodeFrame({
194
+ error: error.code,
195
+ why: error.message,
196
+ ...error.reason ? { reason: error.reason } : {}
197
+ })
198
+ };
159
199
  const BATCH_MAX = 256;
160
200
  const BATCH_BYTES = 16777216;
161
201
  const PART_BYTES = 8388608;
@@ -427,6 +467,75 @@ function remote(transport, options = {}) {
427
467
  to
428
468
  });
429
469
  return reply.operations;
470
+ },
471
+ watch(bucket, options, on, ended) {
472
+ const subscribe = transport.subscribe?.bind(transport);
473
+ if (!subscribe) throw new StorageError("unavailable", "Watching needs a connection that stays open: connect with a storage key, client(origin, { key, secret }).");
474
+ let cursor = options.after, closed = false, isReady = false, tries = 0;
475
+ let current = null, timer;
476
+ let resolve, reject;
477
+ const ready = new Promise((yes, no) => (resolve = yes, reject = no));
478
+ const fail = (error) => {
479
+ closed = true;
480
+ current?.close();
481
+ if (isReady) ended(error);
482
+ else reject(error);
483
+ };
484
+ const again = () => {
485
+ current?.close();
486
+ current = null;
487
+ if (closed) return;
488
+ tries += 1;
489
+ if (!isReady && tries > 3) return fail(new StorageError("unavailable", "A watch needs a WebSocket to Storage, and none could be opened from here: check that this network lets WebSockets through to the API."));
490
+ timer = setTimeout(open, tries === 1 ? 0 : Math.min(100 * 2 ** tries, 1e4));
491
+ };
492
+ const open = () => {
493
+ if (closed) return;
494
+ const frame = encodeFrame({
495
+ op: "watch",
496
+ bucket,
497
+ ...options.keys ? { keys: [...options.keys] } : { prefix: options.prefix ?? "" },
498
+ ...cursor !== void 0 ? { after: cursor } : {}
499
+ });
500
+ current = subscribe(frame, (bytes) => {
501
+ if (closed) return;
502
+ if (bytes === null) return again();
503
+ let reply;
504
+ try {
505
+ reply = watchAnswer.parse(decodeFrame(bytes).header);
506
+ } catch {
507
+ return again();
508
+ }
509
+ if ("error" in reply) {
510
+ const error = new StorageError(reply.error, reply.why, reply.reason);
511
+ return error.code === "unavailable" ? again() : fail(error);
512
+ }
513
+ if ("watching" in reply) {
514
+ tries = 0;
515
+ cursor = reply.watching;
516
+ if (!isReady) isReady = true, resolve(reply.watching);
517
+ return;
518
+ }
519
+ if ("reset" in reply) {
520
+ cursor = reply.reset;
521
+ return on({
522
+ reset: true,
523
+ cursor: reply.reset
524
+ });
525
+ }
526
+ for (const event of reply.events) cursor = event.cursor, on(event);
527
+ });
528
+ };
529
+ open();
530
+ return {
531
+ ready,
532
+ close() {
533
+ closed = true;
534
+ clearTimeout(timer);
535
+ current?.close();
536
+ if (!isReady) reject(new StorageError("unavailable", "The watch was closed before it was ready"));
537
+ }
538
+ };
430
539
  }
431
540
  };
432
541
  return engine;
@@ -498,7 +607,9 @@ function repeatableCall(call) {
498
607
  case "delete":
499
608
  case "uploadPart":
500
609
  case "usage":
501
- case "operations": return true;
610
+ case "operations":
611
+ case "watch":
612
+ case "unwatch": return true;
502
613
  case "put": return call.ifNoneMatch === void 0 && call.ifMatch === void 0;
503
614
  case "copy":
504
615
  case "createUpload":
@@ -522,7 +633,7 @@ function bucketsOf(frame) {
522
633
  };
523
634
  const add = (header) => {
524
635
  const call = request.safeParse(header);
525
- if (call.success) names.add(call.data.bucket);
636
+ if (call.success && "bucket" in call.data) names.add(call.data.bucket);
526
637
  };
527
638
  const outer = read(frame);
528
639
  if (!outer) return [];
@@ -600,6 +711,7 @@ function serve(engine) {
600
711
  };
601
712
  }
602
713
  async function answerTo(engine, call, body) {
714
+ if (call.op === "watch" || call.op === "unwatch") throw new StorageError("invalid", "A watch is answered only on the socket a storage key opens: client(origin, { key, secret }).");
603
715
  checkBucketName(call.bucket);
604
716
  switch (call.op) {
605
717
  case "put": {
@@ -754,4 +866,4 @@ function decodeFrame(frame) {
754
866
  };
755
867
  }
756
868
  //#endregion
757
- export { bucketsOf, decodeFrame, encodeFrame, http, remote, repeatable, serve, serveHttp };
869
+ export { bucketsOf, decodeFrame, encodeFrame, http, remote, repeatable, serve, serveHttp, watchFrames };