@midsummer-ai/sdk 0.1.0-staging.3428 → 0.1.0-staging.3434

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 (43) hide show
  1. package/auth-B7rCtXFQ.d.mts +36 -0
  2. package/{build-DQo-JrlN.d.mts → build-BhmOZmGQ.d.mts} +2 -27
  3. package/client.mjs +1 -1
  4. package/contract.mjs +2 -2
  5. package/database/build.d.mts +1 -1
  6. package/database/build.mjs +35 -2
  7. package/database/server.mjs +1 -1
  8. package/database/stand-in.d.mts +2 -1
  9. package/database/stand-in.mjs +2 -2
  10. package/email/client.d.mts +5 -4
  11. package/email/client.mjs +1 -1
  12. package/email/contract.d.mts +3 -1
  13. package/email/contract.mjs +111 -4
  14. package/email/index.d.mts +85 -16
  15. package/email/index.mjs +2 -2
  16. package/email/smtp.mjs +24 -8
  17. package/email/stand-in.d.mts +3 -0
  18. package/email/stand-in.mjs +17 -7
  19. package/email-IH5OllU2.mjs +337 -0
  20. package/errors-B1tO_wdm.mjs +28 -0
  21. package/flows/contract.d.mts +13 -0
  22. package/flows/contract.mjs +483 -0
  23. package/flows/index.d.mts +148 -0
  24. package/flows/index.mjs +347 -0
  25. package/index.mjs +2 -2
  26. package/{names-DfCBKupJ.mjs → names-Do0ot5Ha.mjs} +2 -28
  27. package/package.json +29 -1
  28. package/queues/contract.mjs +144 -1
  29. package/queues/index.d.mts +149 -5
  30. package/queues/index.mjs +56 -12
  31. package/queues/stand-in.mjs +333 -31
  32. package/queues/wire.mjs +302 -16
  33. package/s3.mjs +3 -2
  34. package/{server-EDRbF2u-.mjs → server-Drjni3-F.mjs} +4 -2
  35. package/socket.mjs +1 -1
  36. package/{src-BKrQAqJN.mjs → src-CkP59_Qu.mjs} +2 -1
  37. package/stand-in.mjs +2 -1
  38. package/storage/contract.d.mts +25 -0
  39. package/storage/contract.mjs +153 -0
  40. package/storage/files.d.mts +144 -0
  41. package/storage/files.mjs +513 -0
  42. package/wire.mjs +2 -1
  43. package/email-DXtpr7pT.mjs +0 -214
package/queues/wire.mjs CHANGED
@@ -1,11 +1,12 @@
1
1
  import { decodeFrame, encodeFrame } from "../wire.mjs";
2
- import { QueueError, checkEngineQueue, checkKey, checkReceipt, checkReceive, queueErrorCodes } from "./index.mjs";
2
+ import { QueueError, checkEngineQueue, checkEvent, checkKey, checkQueueName, checkReceipt, checkReceive, checkStepName, checkToken, checkVisibilityMs, queueErrorCodes } from "./index.mjs";
3
3
  import { z } from "zod";
4
4
  //#region src/queues/wire.ts
5
5
  /**
6
6
  * Queues' wire: how a Queues call crosses a network. `remote(transport)` is the engine a client uses;
7
7
  * `serve(engine)` replies on the other side. A server implements `serve` over its own engine and
8
- * nothing else, so the contract run through the wire holds for it too.
8
+ * nothing else, so the contract run through the wire holds for it too. Flow runs
9
+ * (`@midsummer-ai/sdk/flows`) cross the same wire: a run is a Queue's Message, kept with its steps.
9
10
  *
10
11
  * const jobs = queues(remote({ send: (frame) => env.QUEUES.send(frame) })) // in a Site
11
12
  * handle.onFrame(serve(engine)) // on the platform
@@ -14,6 +15,30 @@ import { z } from "zod";
14
15
  * JSON header, here with no body after it. One request frame gets one answer frame. Changing a frame
15
16
  * changes the contract with every server.
16
17
  */
18
+ const stepWrite = z.union([
19
+ z.object({
20
+ kind: z.literal("run"),
21
+ id: z.string(),
22
+ value: z.string()
23
+ }).strict(),
24
+ z.object({
25
+ kind: z.literal("run"),
26
+ id: z.string(),
27
+ error: z.string(),
28
+ retries: z.number()
29
+ }).strict(),
30
+ z.object({
31
+ kind: z.literal("sleep"),
32
+ id: z.string(),
33
+ ms: z.number()
34
+ }).strict(),
35
+ z.object({
36
+ kind: z.literal("wait"),
37
+ id: z.string(),
38
+ event: z.string(),
39
+ timeoutMs: z.number()
40
+ }).strict()
41
+ ]);
17
42
  const request = z.discriminatedUnion("op", [
18
43
  z.object({
19
44
  op: z.literal("queue.send"),
@@ -21,7 +46,8 @@ const request = z.discriminatedUnion("op", [
21
46
  messages: z.array(z.object({
22
47
  body: z.string(),
23
48
  delayMs: z.number(),
24
- key: z.string().optional()
49
+ key: z.string().optional(),
50
+ group: z.string().optional()
25
51
  }).strict()).min(1).max(100)
26
52
  }).strict(),
27
53
  z.object({
@@ -42,9 +68,62 @@ const request = z.discriminatedUnion("op", [
42
68
  receipt: z.string(),
43
69
  delayMs: z.number().optional()
44
70
  }).strict(),
71
+ z.object({
72
+ op: z.literal("queue.extend"),
73
+ queue: z.string(),
74
+ receipt: z.string(),
75
+ visibilityMs: z.number()
76
+ }).strict(),
45
77
  z.object({
46
78
  op: z.literal("queue.stats"),
47
79
  queue: z.string()
80
+ }).strict(),
81
+ z.object({
82
+ op: z.literal("run.start"),
83
+ queue: z.string(),
84
+ id: z.string(),
85
+ input: z.string(),
86
+ timeoutMs: z.number().optional(),
87
+ group: z.string().optional()
88
+ }).strict(),
89
+ z.object({
90
+ op: z.literal("run.load"),
91
+ queue: z.string(),
92
+ run: z.string(),
93
+ receipt: z.string()
94
+ }).strict(),
95
+ z.object({
96
+ op: z.literal("run.record"),
97
+ queue: z.string(),
98
+ run: z.string(),
99
+ receipt: z.string(),
100
+ step: stepWrite
101
+ }).strict(),
102
+ z.object({
103
+ op: z.literal("run.finish"),
104
+ queue: z.string(),
105
+ run: z.string(),
106
+ receipt: z.string(),
107
+ output: z.string().optional(),
108
+ error: z.string().optional()
109
+ }).strict(),
110
+ z.object({
111
+ op: z.literal("run.signal"),
112
+ queue: z.string(),
113
+ run: z.string(),
114
+ event: z.string(),
115
+ value: z.string(),
116
+ key: z.string().optional()
117
+ }).strict(),
118
+ z.object({
119
+ op: z.literal("run.cancel"),
120
+ queue: z.string(),
121
+ run: z.string()
122
+ }).strict(),
123
+ z.object({
124
+ op: z.literal("run.show"),
125
+ queue: z.string(),
126
+ run: z.string()
48
127
  }).strict()
49
128
  ]);
50
129
  const delivery = z.object({
@@ -53,7 +132,8 @@ const delivery = z.object({
53
132
  sentAt: z.number(),
54
133
  attempt: z.number(),
55
134
  receipt: z.string(),
56
- visibleUntil: z.number()
135
+ visibleUntil: z.number(),
136
+ run: z.string().optional()
57
137
  }).strict();
58
138
  const stats = z.object({
59
139
  depth: z.number(),
@@ -64,6 +144,47 @@ const stats = z.object({
64
144
  dead: z.number(),
65
145
  more: z.literal(true).optional()
66
146
  }).strict();
147
+ const step = z.object({
148
+ id: z.string(),
149
+ kind: z.enum([
150
+ "run",
151
+ "sleep",
152
+ "wait"
153
+ ]),
154
+ state: z.enum([
155
+ "done",
156
+ "failed",
157
+ "retrying",
158
+ "sleeping",
159
+ "waiting"
160
+ ]),
161
+ value: z.string().optional(),
162
+ error: z.string().optional(),
163
+ failures: z.number(),
164
+ until: z.number().optional(),
165
+ event: z.string().optional(),
166
+ at: z.number()
167
+ }).strict();
168
+ const run = z.object({
169
+ id: z.string(),
170
+ status: z.enum([
171
+ "running",
172
+ "sleeping",
173
+ "waiting",
174
+ "completed",
175
+ "failed",
176
+ "cancelled"
177
+ ]),
178
+ input: z.string(),
179
+ startedAt: z.number(),
180
+ endedAt: z.number().optional(),
181
+ nextAt: z.number().optional(),
182
+ output: z.string().optional(),
183
+ error: z.string().optional(),
184
+ deadline: z.number().optional(),
185
+ group: z.string().optional(),
186
+ steps: z.array(step)
187
+ }).strict();
67
188
  const answer = z.union([
68
189
  z.object({
69
190
  error: z.enum(queueErrorCodes),
@@ -72,8 +193,32 @@ const answer = z.union([
72
193
  z.object({ ids: z.array(z.string()) }).strict(),
73
194
  z.object({ deliveries: z.array(delivery) }).strict(),
74
195
  z.object({ stats }).strict(),
75
- z.object({ done: z.literal(true) }).strict()
196
+ z.object({ done: z.literal(true) }).strict(),
197
+ z.object({ visibleUntil: z.number().nullable() }).strict(),
198
+ z.object({ started: z.object({
199
+ id: z.string(),
200
+ started: z.boolean()
201
+ }).strict() }).strict(),
202
+ z.object({ loaded: z.object({
203
+ now: z.number(),
204
+ run
205
+ }).strict().nullable() }).strict(),
206
+ z.object({ step: step.nullable() }).strict(),
207
+ z.object({ signal: z.enum([
208
+ "delivered",
209
+ "kept",
210
+ "ended",
211
+ "missing"
212
+ ]) }).strict(),
213
+ z.object({ run: run.nullable() }).strict()
76
214
  ]);
215
+ /** Drops the keys whose value is undefined, as JSON would, so a frame's object reads the same on both sides. */
216
+ const present = (value) => Object.fromEntries(Object.entries(value).filter(([, v]) => v !== void 0));
217
+ const stepOf = (value) => present(value);
218
+ const runOf = (value) => ({
219
+ ...present(value),
220
+ steps: value.steps.map(stepOf)
221
+ });
77
222
  /** The engine on the far side of `transport`. */
78
223
  function remote(transport) {
79
224
  const call = async (header) => {
@@ -128,15 +273,111 @@ function remote(transport) {
128
273
  ...delayMs === void 0 ? {} : { delayMs }
129
274
  });
130
275
  },
276
+ async extend(queue, receipt, visibilityMs) {
277
+ return expect(await call({
278
+ op: "queue.extend",
279
+ queue,
280
+ receipt,
281
+ visibilityMs
282
+ }), "visibleUntil") ?? void 0;
283
+ },
131
284
  async stats(queue) {
132
285
  return expect(await call({
133
286
  op: "queue.stats",
134
287
  queue
135
288
  }), "stats");
289
+ },
290
+ async start(queue, started) {
291
+ return expect(await call({
292
+ op: "run.start",
293
+ queue,
294
+ ...started
295
+ }), "started");
296
+ },
297
+ async load(queue, runId, receipt) {
298
+ const loaded = expect(await call({
299
+ op: "run.load",
300
+ queue,
301
+ run: runId,
302
+ receipt
303
+ }), "loaded");
304
+ return loaded ? {
305
+ now: loaded.now,
306
+ run: runOf(loaded.run)
307
+ } : void 0;
308
+ },
309
+ async record(queue, runId, receipt, written) {
310
+ const kept = expect(await call({
311
+ op: "run.record",
312
+ queue,
313
+ run: runId,
314
+ receipt,
315
+ step: written
316
+ }), "step");
317
+ return kept ? stepOf(kept) : void 0;
318
+ },
319
+ async finish(queue, runId, receipt, end) {
320
+ await call({
321
+ op: "run.finish",
322
+ queue,
323
+ run: runId,
324
+ receipt,
325
+ ...end
326
+ });
327
+ },
328
+ async signal(queue, runId, signal) {
329
+ return expect(await call({
330
+ op: "run.signal",
331
+ queue,
332
+ run: runId,
333
+ ...signal
334
+ }), "signal");
335
+ },
336
+ async cancel(queue, runId) {
337
+ const found = expect(await call({
338
+ op: "run.cancel",
339
+ queue,
340
+ run: runId
341
+ }), "run");
342
+ return found ? runOf(found) : void 0;
343
+ },
344
+ async run(queue, runId) {
345
+ const found = expect(await call({
346
+ op: "run.show",
347
+ queue,
348
+ run: runId
349
+ }), "run");
350
+ return found ? runOf(found) : void 0;
136
351
  }
137
352
  };
138
353
  }
139
354
  const encoder = new TextEncoder();
355
+ /** Whether `text` is JSON of at most 128 KiB; throws `invalid` saying `what` otherwise. */
356
+ function checkJson(text, what) {
357
+ if (encoder.encode(text).length > 131072) throw new QueueError("invalid", `${what} is at most 131,072 bytes of JSON`);
358
+ try {
359
+ JSON.parse(text);
360
+ } catch {
361
+ throw new QueueError("invalid", `${what} is not JSON`);
362
+ }
363
+ }
364
+ const whole = (n, low, high) => Number.isSafeInteger(n) && n >= low && n <= high;
365
+ /** A run's Queue: its own, never its dead-letter Queue. */
366
+ function checkRunQueue(queue) {
367
+ if (queue.endsWith(".dead")) throw new QueueError("invalid", "runs are on a queue, never its dead-letter queue");
368
+ checkQueueName(queue);
369
+ }
370
+ /** A step as a frame carries it, checked again: a frame comes from the network. */
371
+ function checkStep(written) {
372
+ checkStepName(written.id);
373
+ if (written.kind === "run" && "value" in written) checkJson(written.value, "a step's value");
374
+ if (written.kind === "run" && "retries" in written && !whole(written.retries, 0, 100)) throw new QueueError("invalid", "a step's retries are 0 to 100");
375
+ if (written.kind === "sleep" && !whole(written.ms, 0, 31536e6)) throw new QueueError("invalid", "a sleep is at most 365 days");
376
+ if (written.kind === "wait") {
377
+ checkEvent(written.event);
378
+ if (!whole(written.timeoutMs, 1e3, 31536e6)) throw new QueueError("invalid", "a wait's timeout is 1 second to 365 days");
379
+ }
380
+ }
140
381
  /** Answers frames from `remote` with `engine`, checking each again: a frame comes from the network. */
141
382
  function serve(engine) {
142
383
  return async (frame) => {
@@ -150,23 +391,21 @@ function serve(engine) {
150
391
  const parsed = request.safeParse(header);
151
392
  if (!parsed.success) throw new QueueError("invalid", "the request frame is not a Queues call");
152
393
  const call = parsed.data;
153
- checkEngineQueue(call.queue);
394
+ if (call.op.startsWith("run.")) checkRunQueue(call.queue);
395
+ else checkEngineQueue(call.queue);
154
396
  switch (call.op) {
155
397
  case "queue.send":
156
398
  for (const message of call.messages) {
157
399
  if (message.key !== void 0) checkKey(message.key);
158
- if (!Number.isSafeInteger(message.delayMs) || message.delayMs < 0 || message.delayMs > 432e5) throw new QueueError("invalid", "a delay is 0 to 43,200 seconds");
159
- if (encoder.encode(message.body).length > 131072) throw new QueueError("invalid", "a body is at most 131,072 bytes of JSON");
160
- try {
161
- JSON.parse(message.body);
162
- } catch {
163
- throw new QueueError("invalid", "a body is not JSON");
164
- }
400
+ if (message.group !== void 0) checkToken(message.group, "a group");
401
+ if (!whole(message.delayMs, 0, 31536e6)) throw new QueueError("invalid", "a delay is 0 to 31,536,000 seconds");
402
+ checkJson(message.body, "a body");
165
403
  }
166
- return encodeFrame({ ids: await engine.send(call.queue, call.messages.map(({ body, delayMs, key }) => ({
404
+ return encodeFrame({ ids: await engine.send(call.queue, call.messages.map(({ body, delayMs, key, group }) => ({
167
405
  body,
168
406
  delayMs,
169
- ...key === void 0 ? {} : { key }
407
+ ...key === void 0 ? {} : { key },
408
+ ...group === void 0 ? {} : { group }
170
409
  }))) });
171
410
  case "queue.receive":
172
411
  checkReceive(call);
@@ -181,10 +420,57 @@ function serve(engine) {
181
420
  return encodeFrame({ done: true });
182
421
  case "queue.retry":
183
422
  checkReceipt(call.receipt);
184
- if (call.delayMs !== void 0 && (!Number.isSafeInteger(call.delayMs) || call.delayMs < 0 || call.delayMs > 432e5)) throw new QueueError("invalid", "a delay is 0 to 43,200 seconds");
423
+ if (call.delayMs !== void 0 && !whole(call.delayMs, 0, 31536e6)) throw new QueueError("invalid", "a delay is 0 to 31,536,000 seconds");
185
424
  await engine.retry(call.queue, call.receipt, call.delayMs);
186
425
  return encodeFrame({ done: true });
426
+ case "queue.extend":
427
+ checkReceipt(call.receipt);
428
+ checkVisibilityMs(call.visibilityMs);
429
+ return encodeFrame({ visibleUntil: await engine.extend(call.queue, call.receipt, call.visibilityMs) ?? null });
187
430
  case "queue.stats": return encodeFrame({ stats: await engine.stats(call.queue) });
431
+ case "run.start":
432
+ checkToken(call.id, "a run's id");
433
+ checkJson(call.input, "a run's input");
434
+ if (call.group !== void 0) checkToken(call.group, "a group");
435
+ if (call.timeoutMs !== void 0 && !whole(call.timeoutMs, 1e3, 31536e6)) throw new QueueError("invalid", "a run's timeout is 1 second to 365 days");
436
+ return encodeFrame({ started: await engine.start(call.queue, {
437
+ id: call.id,
438
+ input: call.input,
439
+ ...call.timeoutMs === void 0 ? {} : { timeoutMs: call.timeoutMs },
440
+ ...call.group === void 0 ? {} : { group: call.group }
441
+ }) });
442
+ case "run.load":
443
+ checkToken(call.run, "a run's id");
444
+ checkReceipt(call.receipt);
445
+ return encodeFrame({ loaded: await engine.load(call.queue, call.run, call.receipt) ?? null });
446
+ case "run.record":
447
+ checkToken(call.run, "a run's id");
448
+ checkReceipt(call.receipt);
449
+ checkStep(call.step);
450
+ return encodeFrame({ step: await engine.record(call.queue, call.run, call.receipt, call.step) ?? null });
451
+ case "run.finish":
452
+ checkToken(call.run, "a run's id");
453
+ checkReceipt(call.receipt);
454
+ if (call.output === void 0 === (call.error === void 0)) throw new QueueError("invalid", "a run ends with an output or an error");
455
+ if (call.output !== void 0) checkJson(call.output, "a run's output");
456
+ await engine.finish(call.queue, call.run, call.receipt, call.output !== void 0 ? { output: call.output } : { error: call.error.slice(0, 2e3) });
457
+ return encodeFrame({ done: true });
458
+ case "run.signal":
459
+ checkToken(call.run, "a run's id");
460
+ checkEvent(call.event);
461
+ if (call.key !== void 0) checkToken(call.key, "a signal's key");
462
+ checkJson(call.value, "a signal's value");
463
+ return encodeFrame({ signal: await engine.signal(call.queue, call.run, {
464
+ event: call.event,
465
+ value: call.value,
466
+ ...call.key === void 0 ? {} : { key: call.key }
467
+ }) });
468
+ case "run.cancel":
469
+ checkToken(call.run, "a run's id");
470
+ return encodeFrame({ run: await engine.cancel(call.queue, call.run) ?? null });
471
+ case "run.show":
472
+ checkToken(call.run, "a run's id");
473
+ return encodeFrame({ run: await engine.run(call.queue, call.run) ?? null });
188
474
  }
189
475
  } catch (error) {
190
476
  if (error instanceof QueueError) return encodeFrame({
package/s3.mjs CHANGED
@@ -1,5 +1,6 @@
1
- import { a as checkMetadata, h as StorageError, l as checkUploadId, m as sha256, n as checkBucketName, o as checkPartNumber, r as checkKey, s as checkParts } from "./names-DfCBKupJ.mjs";
2
- import { r as streamsOf } from "./src-BKrQAqJN.mjs";
1
+ import { t as StorageError } from "./errors-B1tO_wdm.mjs";
2
+ import { a as checkMetadata, l as checkUploadId, m as sha256, n as checkBucketName, o as checkPartNumber, r as checkKey, s as checkParts } from "./names-Do0ot5Ha.mjs";
3
+ import { r as streamsOf } from "./src-CkP59_Qu.mjs";
3
4
  //#region src/s3.ts
4
5
  /**
5
6
  * Storage over the S3 protocol, so the tools and SDKs that speak it reach a Project's Buckets
@@ -987,7 +987,8 @@ var QueryBuilder = class QueryBuilder {
987
987
  * ctx.auth.getUserIdentity(): the signed-in caller as their sign-in provider's verified token says
988
988
  * (`{ tokenIdentifier, subject, issuer, name, email, ... }`), or null for none. The Database trusts the
989
989
  * providers `db/auth.config.ts` names. `ctx.auth` is always there, a copy or `{ auth }` taken out of the context
990
- * too; when someone is signed in, `ctx.auth.subject` and `ctx.auth.issuer` are theirs.
990
+ * too, so `if (!ctx.auth)` passes everyone and the build refuses it; check `getUserIdentity()`. When someone is
991
+ * signed in, `ctx.auth.subject` and `ctx.auth.issuer` are theirs.
991
992
  * ctx.scheduler: runAfter(ms, fn, args), runAt(time, fn, args), status(id), cancel(id).
992
993
  * ctx.storage: the Database's files, by storage id. getUrl(id) and getMetadata(id) anywhere; in a mutation or an action
993
994
  * also generateUploadUrl() (a URL that takes one POST of a file and returns `{ storageId }`) and
@@ -1370,7 +1371,8 @@ function identityOf(subject, issuer, claims) {
1370
1371
  }
1371
1372
  /**
1372
1373
  * `ctx.auth`, as Convex's: always there, `getUserIdentity()` the signed-in caller or null for no one, and their
1373
- * `subject` and `issuer` beside it when someone is signed in.
1374
+ * `subject` and `issuer` beside it when someone is signed in. Its own truth means nothing, so the build refuses a
1375
+ * test of it (`authTests` in `./build`).
1374
1376
  */
1375
1377
  function authOf(user, issuer, claims) {
1376
1378
  const identity = user ? identityOf(user, issuer, claims) : null;
package/socket.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { d as sign, f as socket, l as keyed, p as socketSession, u as sameHex } from "./src-BKrQAqJN.mjs";
1
+ import { d as sign, f as socket, l as keyed, p as socketSession, u as sameHex } from "./src-CkP59_Qu.mjs";
2
2
  export { keyed, sameHex, sign, socket, socketSession };
@@ -1,4 +1,5 @@
1
- import { a as checkMetadata, c as checkRange, d as invalid, h as StorageError, i as checkListLimit, l as checkUploadId, n as checkBucketName, o as checkPartNumber, r as checkKey, s as checkParts } from "./names-DfCBKupJ.mjs";
1
+ import { t as StorageError } from "./errors-B1tO_wdm.mjs";
2
+ import { a as checkMetadata, c as checkRange, d as invalid, i as checkListLimit, l as checkUploadId, n as checkBucketName, o as checkPartNumber, r as checkKey, s as checkParts } from "./names-Do0ot5Ha.mjs";
2
3
  import { bucketsOf, remote, repeatable, serve } from "./wire.mjs";
3
4
  import { n as late, r as processEnv, t as here } from "./here-CeqGJW21.mjs";
4
5
  //#region src/socket.ts
package/stand-in.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { f as resolveRange, h as StorageError, m as sha256, p as sameSizes, u as compareKeys } from "./names-DfCBKupJ.mjs";
1
+ import { t as StorageError } from "./errors-B1tO_wdm.mjs";
2
+ import { f as resolveRange, m as sha256, p as sameSizes, u as compareKeys } from "./names-Do0ot5Ha.mjs";
2
3
  //#region src/stand-in.ts
3
4
  /**
4
5
  * Storage's Stand-in: the Capability's behaviour in memory, for `midsummer dev` and tests. It holds
@@ -0,0 +1,25 @@
1
+ import { n as AuthProvider } from "../auth-B7rCtXFQ.mjs";
2
+ import { FileRule, Files } from "./files.mjs";
3
+ //#region src/storage/contract.d.ts
4
+ /** One bucket of a server under test, and its own users' tokens. */
5
+ interface FilesHarness {
6
+ /** The provider the harness signs tokens as, to name in the bucket's settings. */
7
+ readonly provider: AuthProvider;
8
+ /** Gives the bucket these rules, trusting `provider`, as `storage bucket settings set` does. */
9
+ allow(rules: ReadonlyArray<FileRule>): Promise<void>;
10
+ /** A token `provider` signed for `subject`: good now, expired an hour ago, or signed by an issuer the bucket doesn't trust. */
11
+ token(subject: string, options?: {
12
+ readonly expired?: boolean;
13
+ readonly untrusted?: boolean;
14
+ }): Promise<string>;
15
+ /** The bucket's files as the user `token` is, or with none as anyone. */
16
+ files(token?: string): Files;
17
+ }
18
+ interface FilesCase {
19
+ /** A line of the specification. */
20
+ readonly name: string;
21
+ run(harness: FilesHarness): Promise<void>;
22
+ }
23
+ declare const filesContract: ReadonlyArray<FilesCase>;
24
+ //#endregion
25
+ export { FilesCase, FilesHarness, filesContract };
@@ -0,0 +1,153 @@
1
+ import { t as StorageError } from "../errors-B1tO_wdm.mjs";
2
+ //#region src/storage/contract.ts
3
+ /**
4
+ * The files endpoint's contract: what every server of it promises an app's users, as cases any test runner runs. The
5
+ * Stand-in (`filesStandIn`) runs them in this package; the platform runs the same cases through its own endpoint.
6
+ *
7
+ * for (const c of filesContract) test(c.name, () => c.run(harness()))
8
+ *
9
+ * Each case gets a harness over one empty bucket, `acme`'s `avatars`, and throws when the server breaks a promise.
10
+ * Expected values are written out, never computed with the SDK's own code.
11
+ */
12
+ const OWN = {
13
+ prefix: "users/{subject}/",
14
+ access: "write"
15
+ };
16
+ const filesContract = [
17
+ {
18
+ name: "a signed-in user puts a file in their own folder, reads it back byte for byte and lists their folder",
19
+ async run(h) {
20
+ await h.allow([OWN]);
21
+ const ada = h.files(await h.token("ada"));
22
+ const put = await ada.put("users/ada/notes.txt", "hello", { contentType: "text/plain" });
23
+ equal([
24
+ put.key,
25
+ put.size,
26
+ put.contentType
27
+ ], [
28
+ "users/ada/notes.txt",
29
+ 5,
30
+ "text/plain"
31
+ ], "the put's answer");
32
+ equal(put.etag, "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", "the etag");
33
+ const read = await ada.get("users/ada/notes.txt");
34
+ equal(read && new TextDecoder().decode(read.body), "hello", "the bytes read");
35
+ equal((await ada.list({ prefix: "users/ada/" })).files.map((file) => file.key), ["users/ada/notes.txt"], "the listing");
36
+ equal(await ada.get("users/ada/nothing.txt"), null, "a file that isn't there");
37
+ await ada.delete("users/ada/notes.txt");
38
+ equal(await ada.get("users/ada/notes.txt"), null, "the file after its delete");
39
+ }
40
+ },
41
+ {
42
+ name: "one user never reads, lists, replaces or deletes another's files, and is told the folder that is theirs",
43
+ async run(h) {
44
+ await h.allow([OWN]);
45
+ await h.files(await h.token("ada")).put("users/ada/notes.txt", "hello");
46
+ const bob = h.files(await h.token("bob"));
47
+ await refused(() => bob.get("users/ada/notes.txt"), "forbidden", "No rule of this bucket lets this user read users/ada/notes.txt. They may read under users/bob/.");
48
+ await refused(() => bob.list({ prefix: "users/ada/" }), "forbidden");
49
+ await refused(() => bob.list({ prefix: "users/" }), "forbidden");
50
+ await refused(() => bob.put("users/ada/notes.txt", "mine now"), "forbidden");
51
+ await refused(() => bob.delete("users/ada/notes.txt"), "forbidden");
52
+ const read = await h.files(await h.token("ada")).get("users/ada/notes.txt");
53
+ equal(read && new TextDecoder().decode(read.body), "hello", "ada's file, untouched");
54
+ }
55
+ },
56
+ {
57
+ name: "no token, an expired one or one from an issuer the bucket doesn't trust reaches no private file",
58
+ async run(h) {
59
+ await h.allow([OWN]);
60
+ await h.files(await h.token("ada")).put("users/ada/notes.txt", "hello");
61
+ await refused(() => h.files().get("users/ada/notes.txt"), "forbidden", "Sign in to read this: send the user's token from your sign-in provider as Authorization: Bearer <token>.");
62
+ await refused(() => h.files().put("users/ada/new.txt", "hi"), "forbidden");
63
+ await refused(async () => h.files(await h.token("ada", { expired: true })).get("users/ada/notes.txt"), "forbidden");
64
+ await refused(async () => h.files(await h.token("ada", { untrusted: true })).get("users/ada/notes.txt"), "forbidden");
65
+ }
66
+ },
67
+ {
68
+ name: "a public folder is read by anyone and a shared one by every signed-in user, and neither is written by them",
69
+ async run(h) {
70
+ await h.allow([
71
+ OWN,
72
+ {
73
+ prefix: "shared/",
74
+ access: "read"
75
+ },
76
+ {
77
+ prefix: "public/",
78
+ access: "read",
79
+ public: true
80
+ },
81
+ {
82
+ prefix: "admin/",
83
+ access: "write"
84
+ }
85
+ ]);
86
+ const ada = h.files(await h.token("ada"));
87
+ await ada.put("admin/x.txt", "x");
88
+ await refused(() => h.files().put("public/logo.txt", "logo"), "forbidden");
89
+ await refused(() => ada.put("public/logo.txt", "logo"), "forbidden");
90
+ await refused(() => ada.put("shared/terms.txt", "terms"), "forbidden");
91
+ equal(await h.files().get("public/logo.txt"), null, "a public file that isn't there");
92
+ equal(await ada.get("shared/terms.txt"), null, "a shared file that isn't there");
93
+ await refused(() => h.files().get("shared/terms.txt"), "forbidden");
94
+ }
95
+ },
96
+ {
97
+ name: "a file is taken at its rule's size and refused one byte over it, and refused in a type the rule doesn't take",
98
+ async run(h) {
99
+ await h.allow([{
100
+ prefix: "users/{subject}/",
101
+ access: "write",
102
+ maxBytes: 5,
103
+ contentTypes: ["text/*", "image/png"]
104
+ }]);
105
+ const ada = h.files(await h.token("ada"));
106
+ equal((await ada.put("users/ada/five.txt", "12345", { contentType: "text/plain; charset=utf-8" })).size, 5, "five bytes");
107
+ await refused(() => ada.put("users/ada/six.txt", "123456", { contentType: "text/plain" }), "invalid", "This file is 6 bytes; this bucket takes at most 5 here.");
108
+ await refused(() => ada.put("users/ada/x.gif", "GIF", { contentType: "image/gif" }), "invalid", "This bucket takes text/*, image/png here, not image/gif.");
109
+ equal(await ada.get("users/ada/six.txt"), null, "the file refused for its size");
110
+ }
111
+ },
112
+ {
113
+ name: "a key that climbs out of its folder, or into a preview's, is refused before anything is read",
114
+ async run(h) {
115
+ await h.allow([OWN, {
116
+ prefix: "",
117
+ access: "read"
118
+ }]);
119
+ const ada = h.files(await h.token("ada"));
120
+ await refused(() => ada.put("users/ada/../bob/notes.txt", "hi"), "invalid");
121
+ await refused(() => ada.get(".previews/main-1a2b3c/users/ada/x.txt"), "invalid");
122
+ await refused(() => ada.put("users/ada//x.txt", "hi"), "invalid");
123
+ }
124
+ },
125
+ {
126
+ name: "a bucket with no rules reaches nothing, as if there were none, and a put only where there is none is refused once there is one",
127
+ async run(h) {
128
+ await h.allow([]);
129
+ await refused(async () => h.files(await h.token("ada")).put("users/ada/x.txt", "hi"), "not_found");
130
+ await h.allow([OWN]);
131
+ const ada = h.files(await h.token("ada"));
132
+ await ada.put("users/ada/x.txt", "first", { ifNoneMatch: "*" });
133
+ await refused(() => ada.put("users/ada/x.txt", "second", { ifNoneMatch: "*" }), "conflict");
134
+ }
135
+ }
136
+ ];
137
+ /** Throws unless `call` fails with a `StorageError` of `code`, and, when given, exactly `message`. */
138
+ async function refused(call, code, message) {
139
+ let caught;
140
+ try {
141
+ await call();
142
+ } catch (error) {
143
+ caught = error;
144
+ }
145
+ if (!(caught instanceof StorageError)) throw new Error(`expected a ${code} StorageError, got ${caught === void 0 ? "success" : String(caught)}`);
146
+ if (caught.code !== code) throw new Error(`expected ${code}, got ${caught.code}: ${caught.message}`);
147
+ if (message !== void 0 && caught.message !== message) throw new Error(`expected the message ${JSON.stringify(message)}, got ${JSON.stringify(caught.message)}`);
148
+ }
149
+ function equal(actual, expected, what) {
150
+ if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error(`${what}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
151
+ }
152
+ //#endregion
153
+ export { filesContract };