@midsummer-ai/sdk 0.1.0-staging.4477 → 0.1.0-staging.4480

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.
package/auth/mail.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as EmailError } from "../index-DI_L79Hc.mjs";
1
+ import { a as EmailError } from "../index-bperY8NN.mjs";
2
2
  //#region src/auth/mail.d.ts
3
3
  type SignInMailKind = "code" | "link" | "verify" | "reset" | "invite" | "device" | "approved";
4
4
  /** One sign-in mail: whom to, which kind, the app's name, and its code or its address. */
@@ -1,4 +1,4 @@
1
- import { i as EmailEngine, m as SentMessage, n as CheckedMessage, o as EmailErrorCode, t as BatchResult } from "../index-DI_L79Hc.mjs";
1
+ import { i as EmailEngine, m as SentMessage, n as CheckedMessage, o as EmailErrorCode, t as BatchResult } from "../index-bperY8NN.mjs";
2
2
  //#region src/email/client.d.ts
3
3
  declare const MESSAGES_PATH = "/email/messages";
4
4
  type Fetch = (url: string, init: RequestInit) => Promise<Response>;
@@ -1,4 +1,4 @@
1
- import { r as Email, x as Inbox } from "../index-DI_L79Hc.mjs";
1
+ import { r as Email, x as Inbox } from "../index-bperY8NN.mjs";
2
2
  //#region src/email/contract.d.ts
3
3
  declare const CONTRACT_DOMAIN = "mail.acme.dev";
4
4
  declare const CONTRACT_SUPPRESSED = "suppressed@example.com";
package/email/inbox.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as ReceivedMail, C as InboxEngine, D as InboxThreadWithMessages, E as InboxThread, F as inbox, I as serveInbox, M as boundInbox, N as checkPage, O as MAX_REPLY, P as checkReply, S as InboxCall, T as InboxReply, b as INBOX_HEADER, j as ThreadCursor, k as MAX_THREADS, w as InboxMessage, x as Inbox, y as BoundInboxAnswer } from "../index-DI_L79Hc.mjs";
1
+ import { A as ReceivedMail, C as InboxEngine, D as InboxThreadWithMessages, E as InboxThread, F as inbox, I as serveInbox, M as boundInbox, N as checkPage, O as MAX_REPLY, P as checkReply, S as InboxCall, T as InboxReply, b as INBOX_HEADER, j as ThreadCursor, k as MAX_THREADS, w as InboxMessage, x as Inbox, y as BoundInboxAnswer } from "../index-bperY8NN.mjs";
2
2
  export { BoundInboxAnswer, INBOX_HEADER, Inbox, InboxCall, InboxEngine, InboxMessage, InboxReply, InboxThread, InboxThreadWithMessages, MAX_REPLY, MAX_THREADS, ReceivedMail, ThreadCursor, boundInbox, checkPage, checkReply, inbox, serveInbox };
package/email/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as ReceivedMail, C as InboxEngine, D as InboxThreadWithMessages, E as InboxThread, F as inbox, T as InboxReply, _ as email, a as EmailError, b as INBOX_HEADER, c as MAX_ATTACHMENT_BYTES, d as MAX_RECIPIENTS, f as OutgoingAttachment, g as checkMessage, h as addressOf, i as EmailEngine, j as ThreadCursor, k as MAX_THREADS, l as MAX_BATCH, m as SentMessage, n as CheckedMessage, o as EmailErrorCode, p as OutgoingMessage, r as Email, s as MAX_ATTACHMENTS, t as BatchResult, u as MAX_MESSAGE_BYTES, v as verifyWebhook, w as InboxMessage, x as Inbox } from "../index-DI_L79Hc.mjs";
1
+ import { A as ReceivedMail, C as InboxEngine, D as InboxThreadWithMessages, E as InboxThread, F as inbox, T as InboxReply, _ as email, a as EmailError, b as INBOX_HEADER, c as MAX_ATTACHMENT_BYTES, d as MAX_RECIPIENTS, f as OutgoingAttachment, g as checkMessage, h as addressOf, i as EmailEngine, j as ThreadCursor, k as MAX_THREADS, l as MAX_BATCH, m as SentMessage, n as CheckedMessage, o as EmailErrorCode, p as OutgoingMessage, r as Email, s as MAX_ATTACHMENTS, t as BatchResult, u as MAX_MESSAGE_BYTES, v as verifyWebhook, w as InboxMessage, x as Inbox } from "../index-bperY8NN.mjs";
2
2
  export { BatchResult, CheckedMessage, Email, EmailEngine, EmailError, EmailErrorCode, INBOX_HEADER, type Inbox, type InboxEngine, type InboxMessage, type InboxReply, type InboxThread, type InboxThreadWithMessages, MAX_ATTACHMENTS, MAX_ATTACHMENT_BYTES, MAX_BATCH, MAX_MESSAGE_BYTES, MAX_RECIPIENTS, MAX_THREADS, OutgoingAttachment, OutgoingMessage, type ReceivedMail, SentMessage, type ThreadCursor, addressOf, checkMessage, email, inbox, verifyWebhook };
package/email/smtp.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { m as SentMessage, n as CheckedMessage } from "../index-DI_L79Hc.mjs";
1
+ import { m as SentMessage, n as CheckedMessage } from "../index-bperY8NN.mjs";
2
2
  //#region src/email/smtp.d.ts
3
3
  /** A `send` that hands each message to Email at `origin` (the API's), with the client's key. */
4
4
  declare function relayTo(origin: string, options?: {
@@ -1,4 +1,4 @@
1
- import { C as InboxEngine, i as EmailEngine, n as CheckedMessage, w as InboxMessage } from "../index-DI_L79Hc.mjs";
1
+ import { C as InboxEngine, i as EmailEngine, n as CheckedMessage, w as InboxMessage } from "../index-bperY8NN.mjs";
2
2
  //#region src/email/stand-in.d.ts
3
3
  declare function standIn(options: {
4
4
  readonly domains: ReadonlyArray<string>;
package/here-C2jhTheQ.mjs CHANGED
@@ -12,7 +12,7 @@ function processEnv() {
12
12
  * This package's version: `0.0.0-dev` here, and in a published package the version it was published at, which the
13
13
  * release writes in its place as it stages the package (`stampSdk` in `scripts/release/packages.ts`).
14
14
  */
15
- const SDK_VERSION = "0.1.0-staging.4477";
15
+ const SDK_VERSION = "0.1.0-staging.4480";
16
16
  /**
17
17
  * The header that tells Midsummer which client made each of this package's calls: `Midsummer-Client: sdk/<version>
18
18
  * <part>`, `part` the product whose client it is (`database`, `storage`, `queues`, ...), so the platform counts which
@@ -10,11 +10,11 @@ interface InboxThread {
10
10
  readonly lastAt: number;
11
11
  readonly createdAt: number;
12
12
  }
13
- /** One message of a thread: one that arrived (`received`), or one the inbox sent, `sending` until it has gone out. */
13
+ /** One message of a thread: one that arrived (`received`), or one the inbox sent, `sending` until it has gone out, or `cancelled` when it was scheduled and cancelled before it fell due. */
14
14
  interface InboxMessage {
15
15
  readonly id: string;
16
16
  readonly threadId: string;
17
- readonly status: "received" | "sending" | "sent" | "failed";
17
+ readonly status: "received" | "sending" | "sent" | "failed" | "cancelled";
18
18
  /** Its `Message-ID` header, without the angle brackets. */
19
19
  readonly messageId: string;
20
20
  readonly from: string;
package/kv/contract.d.mts CHANGED
@@ -3,6 +3,11 @@ import { KeyValue } from "./index.mjs";
3
3
  interface KvCase {
4
4
  /** A line of the specification. */
5
5
  readonly name: string;
6
+ /**
7
+ * The case reads the engine's clock to the millisecond, so it holds only where the run moves that clock, as the
8
+ * stand-in's tests do. A live engine keeps its own clock, so a check against one lists these and runs the rest.
9
+ */
10
+ readonly exactClock?: true;
6
11
  run(world: {
7
12
  readonly kv: KeyValue;
8
13
  advance(ms: number): void;
package/kv/contract.mjs CHANGED
@@ -50,6 +50,7 @@ const kvContract = [
50
50
  },
51
51
  {
52
52
  name: "a key set with ttlSeconds is read until that second and never after",
53
+ exactClock: true,
53
54
  async run({ kv, advance }) {
54
55
  await kv.set("otp:ada", "481516", { ttlSeconds: 60 });
55
56
  advance(60 * SECOND - 1);
@@ -139,6 +140,7 @@ const kvContract = [
139
140
  },
140
141
  {
141
142
  name: "list returns keys by prefix in byte order, a page at a time, with each one's size and expiry",
143
+ exactClock: true,
142
144
  async run({ kv, at }) {
143
145
  await kv.set("session:b", "xy", { ttlSeconds: 100 });
144
146
  await kv.set("session:a", 1);
@@ -177,6 +179,7 @@ const kvContract = [
177
179
  },
178
180
  {
179
181
  name: "a limit admits max calls in any window, refuses the next with when to retry, and slides",
182
+ exactClock: true,
180
183
  async run({ kv, advance, at }) {
181
184
  const limit = () => kv.limit("ip:203.0.113.9", {
182
185
  max: 2,
package/kv/wire.d.mts CHANGED
@@ -1,6 +1,79 @@
1
1
  import { Transport } from "../wire.mjs";
2
- import { KvEngine } from "./index.mjs";
2
+ import { EngineEntry, KeyInfo, KvEngine, KvErrorCode } from "./index.mjs";
3
3
  //#region src/kv/wire.d.ts
4
+ /** The calls, in the order of their op byte: `kv.get` is 1, `kv.stats` 9. */
5
+ declare const OPS: readonly ["kv.get", "kv.set", "kv.incr", "kv.delete", "kv.expire", "kv.list", "kv.limit", "kv.limit.reset", "kv.stats"];
6
+ type KvOp = (typeof OPS)[number];
7
+ /** One call, as its frame carries it. */
8
+ type KvCall = {
9
+ readonly op: "kv.get";
10
+ readonly keys: ReadonlyArray<string>;
11
+ } | {
12
+ readonly op: "kv.set";
13
+ readonly key: string;
14
+ readonly value: string;
15
+ readonly ttlMs?: number;
16
+ readonly ifAbsent?: boolean;
17
+ } | {
18
+ readonly op: "kv.incr";
19
+ readonly key: string;
20
+ readonly by: number;
21
+ readonly ttlMs?: number;
22
+ } | {
23
+ readonly op: "kv.delete";
24
+ readonly keys: ReadonlyArray<string>;
25
+ } | {
26
+ readonly op: "kv.expire";
27
+ readonly key: string;
28
+ readonly ttlMs: number | null;
29
+ } | {
30
+ readonly op: "kv.list";
31
+ readonly prefix: string;
32
+ readonly after?: string;
33
+ readonly limit: number;
34
+ } | {
35
+ readonly op: "kv.limit";
36
+ readonly key: string;
37
+ readonly max: number;
38
+ readonly windowMs: number;
39
+ readonly cost: number;
40
+ } | {
41
+ readonly op: "kv.limit.reset";
42
+ readonly key: string;
43
+ } | {
44
+ readonly op: "kv.stats";
45
+ };
46
+ /** What each op answers when it succeeds. */
47
+ interface KvAnswers {
48
+ "kv.get": ReadonlyArray<EngineEntry | null>;
49
+ "kv.set": boolean;
50
+ "kv.incr": number;
51
+ "kv.delete": number;
52
+ "kv.expire": boolean;
53
+ "kv.list": {
54
+ readonly keys: ReadonlyArray<KeyInfo>;
55
+ readonly next?: string;
56
+ };
57
+ "kv.limit": Awaited<ReturnType<KvEngine["limit"]>>;
58
+ "kv.limit.reset": boolean;
59
+ "kv.stats": {
60
+ readonly keys: number;
61
+ readonly bytes: number;
62
+ };
63
+ }
64
+ /** A call's frame. */
65
+ declare function encodeCall(call: KvCall): Uint8Array;
66
+ /** The call a frame carries. A frame that isn't one is `invalid`, and a value past 1 MiB is `too-large`. */
67
+ declare function decodeCall(frame: Uint8Array): KvCall;
68
+ /** The frame of a call's answer. */
69
+ declare function encodeAnswer<Op extends KvOp>(op: Op, answer: KvAnswers[Op]): Uint8Array;
70
+ /** The frame of a refused call: its error's status and `why`. */
71
+ declare function errorFrame(code: KvErrorCode, why: string): Uint8Array;
72
+ /**
73
+ * The answer an `op` frame carries. A refusal throws its `KvError`; a frame that is no answer to `op` throws
74
+ * `unavailable`.
75
+ */
76
+ declare function decodeAnswer<Op extends KvOp>(op: Op, frame: Uint8Array): KvAnswers[Op];
4
77
  /** An engine that also shows how many live keys it keeps and their bytes, as a store's page and its meter read. */
5
78
  interface CountedEngine extends KvEngine {
6
79
  stats(): Promise<{
@@ -11,8 +84,8 @@ interface CountedEngine extends KvEngine {
11
84
  /** The engine on the far side of `transport`. */
12
85
  declare function remote(transport: Transport): CountedEngine;
13
86
  /**
14
- * Replies to one request frame from `engine`. Every frame is checked again here, since it comes from the network,
15
- * and a failure becomes an error frame with its code. `kv.stats` is returned only by an engine that counts.
87
+ * Replies to one call's frame from `engine`. Every frame is checked again here, since it comes from the network,
88
+ * and a failure becomes an error frame with its status. `kv.stats` is answered only by an engine that counts.
16
89
  */
17
90
  declare function serve(engine: KvEngine & {
18
91
  stats?(): Promise<{
@@ -21,4 +94,4 @@ declare function serve(engine: KvEngine & {
21
94
  }>;
22
95
  }): (frame: Uint8Array) => Promise<Uint8Array>;
23
96
  //#endregion
24
- export { CountedEngine, type Transport, remote, serve };
97
+ export { CountedEngine, KvAnswers, KvCall, KvOp, OPS, type Transport, decodeAnswer, decodeCall, encodeAnswer, encodeCall, errorFrame, remote, serve };
package/kv/wire.mjs CHANGED
@@ -1,6 +1,4 @@
1
- import { decodeFrame, encodeFrame } from "../wire.mjs";
2
- import { KvError, checkKey, checkKeys, checkLimit, checkListLimit, checkPrefix, checkTtlMs, checkValueText, kvErrorCodes } from "./index.mjs";
3
- import { z } from "zod";
1
+ import { KvError, checkKey, checkKeys, checkLimit, checkListLimit, checkPrefix, checkTtlMs, checkValueText } from "./index.mjs";
4
2
  //#region src/kv/wire.ts
5
3
  /**
6
4
  * The key-value store's wire: how a call crosses a network. `remote(transport)` is the engine a client uses;
@@ -10,208 +8,508 @@ import { z } from "zod";
10
8
  * const store = kvStore(remote({ send: (frame) => env.KV.send(frame) })) // in a site
11
9
  * handle.onFrame(serve(engine)) // on the platform
12
10
  *
13
- * Frames are Storage's (`@midsummer-ai/sdk/wire`): a 4-byte little-endian length and that many bytes of JSON
14
- * header, with no body after it. One request frame gets one reply frame. Changing a frame changes the contract
15
- * with every server.
11
+ * A call is one binary frame and its answer is another, the frame the engine serves, carried as it is from the
12
+ * caller to the engine. Every integer is
13
+ * little-endian. A call is a version byte (1), an op byte (1 to 9, in `OPS`' order) and the op's fields; an answer is
14
+ * a version byte and a status byte, then the op's answer when the status is 0, or else the error's `why`. A value is
15
+ * bytes the engine never parses: the platform checks they are JSON text. HTTP and a Worker call each carry a frame's
16
+ * length, so a frame has none of its own. `encodeCall` and `encodeAnswer` lay out each op's bytes; changing a frame
17
+ * changes the contract with every server.
16
18
  */
17
- const request = z.discriminatedUnion("op", [
18
- z.object({
19
- op: z.literal("kv.get"),
20
- keys: z.array(z.string())
21
- }).strict(),
22
- z.object({
23
- op: z.literal("kv.set"),
24
- key: z.string(),
25
- value: z.string(),
26
- ttlMs: z.number().optional(),
27
- ifAbsent: z.literal(true).optional()
28
- }).strict(),
29
- z.object({
30
- op: z.literal("kv.incr"),
31
- key: z.string(),
32
- by: z.number(),
33
- ttlMs: z.number().optional()
34
- }).strict(),
35
- z.object({
36
- op: z.literal("kv.delete"),
37
- keys: z.array(z.string())
38
- }).strict(),
39
- z.object({
40
- op: z.literal("kv.expire"),
41
- key: z.string(),
42
- ttlMs: z.number().nullable()
43
- }).strict(),
44
- z.object({
45
- op: z.literal("kv.list"),
46
- prefix: z.string(),
47
- after: z.string().optional(),
48
- limit: z.number()
49
- }).strict(),
50
- z.object({
51
- op: z.literal("kv.limit"),
52
- key: z.string(),
53
- max: z.number(),
54
- windowMs: z.number(),
55
- cost: z.number()
56
- }).strict(),
57
- z.object({
58
- op: z.literal("kv.limit.reset"),
59
- key: z.string()
60
- }).strict(),
61
- z.object({ op: z.literal("kv.stats") }).strict()
62
- ]);
63
- const entry = z.object({
64
- value: z.string(),
65
- expiresAt: z.number().optional()
66
- }).strict();
67
- const info = z.object({
68
- key: z.string(),
69
- bytes: z.number(),
70
- expiresAt: z.number().optional()
71
- }).strict();
72
- const decided = z.object({
73
- ok: z.boolean(),
74
- limit: z.number(),
75
- remaining: z.number(),
76
- resetAt: z.number(),
77
- retryAfterMs: z.number().optional()
78
- }).strict();
79
- const answer = z.union([
80
- z.object({
81
- error: z.enum(kvErrorCodes),
82
- why: z.string()
83
- }).strict(),
84
- z.object({ entries: z.array(entry.nullable()) }).strict(),
85
- z.object({ written: z.boolean() }).strict(),
86
- z.object({ value: z.number() }).strict(),
87
- z.object({ deleted: z.number() }).strict(),
88
- z.object({ found: z.boolean() }).strict(),
89
- z.object({
90
- keys: z.array(info),
91
- next: z.string().optional()
92
- }).strict(),
93
- z.object({ decided }).strict(),
94
- z.object({ reset: z.boolean() }).strict(),
95
- z.object({ stats: z.object({
96
- keys: z.number(),
97
- bytes: z.number()
98
- }).strict() }).strict()
99
- ]);
100
- /** Drops the keys whose value is undefined, as JSON would, so a frame's object reads the same on both sides. */
101
- const present = (value) => Object.fromEntries(Object.entries(value).filter(([, v]) => v !== void 0));
19
+ /** The calls, in the order of their op byte: `kv.get` is 1, `kv.stats` 9. */
20
+ const OPS = [
21
+ "kv.get",
22
+ "kv.set",
23
+ "kv.incr",
24
+ "kv.delete",
25
+ "kv.expire",
26
+ "kv.list",
27
+ "kv.limit",
28
+ "kv.limit.reset",
29
+ "kv.stats"
30
+ ];
31
+ const VERSION = 1;
32
+ /** An answer's status for each error; 0 is success. */
33
+ const STATUS = {
34
+ invalid: 1,
35
+ "too-large": 2,
36
+ quota: 3,
37
+ forbidden: 4,
38
+ unavailable: 5
39
+ };
40
+ const CODES = [
41
+ void 0,
42
+ "invalid",
43
+ "too-large",
44
+ "quota",
45
+ "forbidden",
46
+ "unavailable"
47
+ ];
48
+ const NOT_AN_ANSWER = "The key-value store answered something that is not one of its answers";
49
+ /** The longest `why` an error frame carries, in UTF-16 units: at most 3 bytes each, so it fits a `text`'s u16 length. */
50
+ const WHY_UNITS = 2e4;
51
+ const encoder = new TextEncoder();
52
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
53
+ /** A frame being written. Each number is checked against its field's range; one outside it is `invalid`. */
54
+ var Writer = class {
55
+ bytes = /* @__PURE__ */ new Uint8Array(64);
56
+ view = new DataView(this.bytes.buffer);
57
+ at = 0;
58
+ room(n) {
59
+ if (this.at + n > this.bytes.length) {
60
+ let size = this.bytes.length * 2;
61
+ while (size < this.at + n) size *= 2;
62
+ const grown = new Uint8Array(size);
63
+ grown.set(this.bytes.subarray(0, this.at));
64
+ this.bytes = grown;
65
+ this.view = new DataView(grown.buffer);
66
+ }
67
+ const at = this.at;
68
+ this.at += n;
69
+ return at;
70
+ }
71
+ whole(n, low, high, what) {
72
+ if (!Number.isSafeInteger(n) || n < low || n > high) throw new KvError("invalid", `${what} is a whole number from ${low} to ${high}`);
73
+ return n;
74
+ }
75
+ u8(n, what) {
76
+ const v = this.whole(n, 0, 255, what), at = this.room(1);
77
+ this.view.setUint8(at, v);
78
+ return this;
79
+ }
80
+ u16(n, what) {
81
+ const v = this.whole(n, 0, 65535, what), at = this.room(2);
82
+ this.view.setUint16(at, v, true);
83
+ return this;
84
+ }
85
+ u32(n, what) {
86
+ const v = this.whole(n, 0, 4294967295, what), at = this.room(4);
87
+ this.view.setUint32(at, v, true);
88
+ return this;
89
+ }
90
+ u64(n, what) {
91
+ const v = BigInt(this.whole(n, 0, Number.MAX_SAFE_INTEGER, what)), at = this.room(8);
92
+ this.view.setBigUint64(at, v, true);
93
+ return this;
94
+ }
95
+ i64(n, what) {
96
+ const v = BigInt(this.whole(n, -Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, what)), at = this.room(8);
97
+ this.view.setBigInt64(at, v, true);
98
+ return this;
99
+ }
100
+ raw(bytes) {
101
+ const at = this.room(bytes.length);
102
+ this.bytes.set(bytes, at);
103
+ return this;
104
+ }
105
+ /** A `key`, or a `text`: a u16 length, then UTF-8. */
106
+ key(text, what = "a key's length in bytes") {
107
+ const bytes = encoder.encode(text);
108
+ return this.u16(bytes.length, what).raw(bytes);
109
+ }
110
+ /** A `value`: a u32 length, then its bytes. */
111
+ value(text) {
112
+ const bytes = encoder.encode(text);
113
+ return this.u32(bytes.length, "a value's length in bytes").raw(bytes);
114
+ }
115
+ /** A `flags` byte from its bits, lowest first. */
116
+ flags(...bits) {
117
+ return this.u8(bits.reduce((byte, on, bit) => byte | (on ? 1 << bit : 0), 0), "flags");
118
+ }
119
+ done() {
120
+ return this.bytes.slice(0, this.at);
121
+ }
122
+ };
123
+ /** A frame being read. A frame cut short, a field out of its range or bytes past the last field is `bad`. */
124
+ var Reader = class {
125
+ bytes;
126
+ bad;
127
+ view;
128
+ at = 0;
129
+ constructor(bytes, bad) {
130
+ this.bytes = bytes;
131
+ this.bad = bad;
132
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
133
+ }
134
+ take(n) {
135
+ if (this.at + n > this.bytes.length) this.bad("the frame ends before its last field");
136
+ const at = this.at;
137
+ this.at += n;
138
+ return at;
139
+ }
140
+ u8() {
141
+ return this.view.getUint8(this.take(1));
142
+ }
143
+ u16() {
144
+ return this.view.getUint16(this.take(2), true);
145
+ }
146
+ u32() {
147
+ return this.view.getUint32(this.take(4), true);
148
+ }
149
+ u64() {
150
+ const n = this.view.getBigUint64(this.take(8), true);
151
+ if (n > BigInt(Number.MAX_SAFE_INTEGER)) this.bad("a time or a count is past 2^53-1");
152
+ return Number(n);
153
+ }
154
+ i64() {
155
+ const n = this.view.getBigInt64(this.take(8), true);
156
+ if (n > BigInt(Number.MAX_SAFE_INTEGER) || n < -BigInt(Number.MAX_SAFE_INTEGER)) this.bad("a whole number is past ±2^53-1");
157
+ return Number(n);
158
+ }
159
+ bytesOf(n) {
160
+ const at = this.take(n);
161
+ return this.bytes.subarray(at, at + n);
162
+ }
163
+ text(n, why) {
164
+ try {
165
+ return utf8.decode(this.bytesOf(n));
166
+ } catch (error) {
167
+ if (error instanceof KvError) throw error;
168
+ return this.bad(why);
169
+ }
170
+ }
171
+ /** A `key`, or a `text`. */
172
+ key() {
173
+ return this.text(this.u16(), "a key is not UTF-8 text");
174
+ }
175
+ /** A `flags` byte of which only the bits in `named` may be set, as an array of those bits. */
176
+ flags(named) {
177
+ const byte = this.u8();
178
+ if (byte & ~((1 << named) - 1)) this.bad("a flags byte sets a bit that isn't named");
179
+ return Array.from({ length: named }, (_, bit) => (byte & 1 << bit) !== 0);
180
+ }
181
+ end() {
182
+ if (this.at !== this.bytes.length) this.bad("the frame has bytes past its last field");
183
+ }
184
+ };
185
+ /** A call's frame. */
186
+ function encodeCall(call) {
187
+ const w = new Writer().u8(VERSION, "version").u8(OPS.indexOf(call.op) + 1, "op");
188
+ switch (call.op) {
189
+ case "kv.get":
190
+ case "kv.delete":
191
+ w.u8(call.keys.length, "the number of keys");
192
+ for (const key of call.keys) w.key(key);
193
+ break;
194
+ case "kv.set":
195
+ w.key(call.key).value(call.value).flags(call.ttlMs !== void 0, call.ifAbsent === true);
196
+ if (call.ttlMs !== void 0) w.u64(call.ttlMs, "ttlMs");
197
+ break;
198
+ case "kv.incr":
199
+ w.key(call.key).i64(call.by, "by").flags(call.ttlMs !== void 0);
200
+ if (call.ttlMs !== void 0) w.u64(call.ttlMs, "ttlMs");
201
+ break;
202
+ case "kv.expire":
203
+ w.key(call.key).flags(call.ttlMs !== null);
204
+ if (call.ttlMs !== null) w.u64(call.ttlMs, "ttlMs");
205
+ break;
206
+ case "kv.list":
207
+ w.key(call.prefix, "a prefix's length in bytes").flags(call.after !== void 0);
208
+ if (call.after !== void 0) w.key(call.after);
209
+ w.u16(call.limit, "a list's limit");
210
+ break;
211
+ case "kv.limit":
212
+ w.key(call.key).u32(call.max, "a limit's max").u64(call.windowMs, "a limit's windowMs").u32(call.cost, "a call's cost");
213
+ break;
214
+ case "kv.limit.reset": w.key(call.key);
215
+ }
216
+ return w.done();
217
+ }
218
+ /** The call a frame carries. A frame that isn't one is `invalid`, and a value past 1 MiB is `too-large`. */
219
+ function decodeCall(frame) {
220
+ const r = new Reader(frame, (why) => {
221
+ throw new KvError("invalid", why);
222
+ });
223
+ if (r.u8() !== VERSION) r.bad("the frame's version is not 1");
224
+ const op = OPS[r.u8() - 1];
225
+ if (op === void 0) r.bad("the frame's op is not a key-value call");
226
+ const keys = () => Array.from({ length: r.u8() }, () => r.key());
227
+ const ttl = (on) => on ? { ttlMs: r.u64() } : {};
228
+ let call;
229
+ switch (op) {
230
+ case "kv.get":
231
+ call = {
232
+ op,
233
+ keys: keys()
234
+ };
235
+ break;
236
+ case "kv.delete":
237
+ call = {
238
+ op,
239
+ keys: keys()
240
+ };
241
+ break;
242
+ case "kv.set": {
243
+ const key = r.key(), length = r.u32();
244
+ const bytes = r.bytesOf(length);
245
+ if (length > 1048576) throw new KvError("too-large", `a value is at most 1 MiB (1,048,576 bytes); this one is ${length}`);
246
+ let value;
247
+ try {
248
+ value = utf8.decode(bytes);
249
+ } catch {
250
+ throw new KvError("invalid", "the value is not JSON text");
251
+ }
252
+ const [timed, ifAbsent] = r.flags(2);
253
+ call = {
254
+ op,
255
+ key,
256
+ value,
257
+ ...ttl(timed),
258
+ ...ifAbsent ? { ifAbsent: true } : {}
259
+ };
260
+ break;
261
+ }
262
+ case "kv.incr":
263
+ call = {
264
+ op,
265
+ key: r.key(),
266
+ by: r.i64(),
267
+ ...ttl(r.flags(1)[0])
268
+ };
269
+ break;
270
+ case "kv.expire":
271
+ call = {
272
+ op,
273
+ key: r.key(),
274
+ ttlMs: r.flags(1)[0] ? r.u64() : null
275
+ };
276
+ break;
277
+ case "kv.list":
278
+ call = {
279
+ op,
280
+ prefix: r.key(),
281
+ ...r.flags(1)[0] ? { after: r.key() } : {},
282
+ limit: r.u16()
283
+ };
284
+ break;
285
+ case "kv.limit":
286
+ call = {
287
+ op,
288
+ key: r.key(),
289
+ max: r.u32(),
290
+ windowMs: r.u64(),
291
+ cost: r.u32()
292
+ };
293
+ break;
294
+ case "kv.limit.reset":
295
+ call = {
296
+ op,
297
+ key: r.key()
298
+ };
299
+ break;
300
+ case "kv.stats": call = { op };
301
+ }
302
+ r.end();
303
+ return call;
304
+ }
305
+ /** The frame of a call's answer. */
306
+ function encodeAnswer(op, answer) {
307
+ const w = new Writer().u8(VERSION, "version").u8(0, "status");
308
+ const asked = answer;
309
+ switch (op) {
310
+ case "kv.get": {
311
+ const entries = asked;
312
+ w.u8(entries.length, "the number of keys");
313
+ for (const entry of entries) {
314
+ w.u8(entry ? 1 : 0, "found");
315
+ if (!entry) continue;
316
+ w.flags(entry.expiresAt !== void 0).value(entry.value);
317
+ if (entry.expiresAt !== void 0) w.u64(entry.expiresAt, "expiresAt");
318
+ }
319
+ break;
320
+ }
321
+ case "kv.set":
322
+ case "kv.expire":
323
+ case "kv.limit.reset":
324
+ w.u8(asked ? 1 : 0, "the answer");
325
+ break;
326
+ case "kv.incr":
327
+ w.i64(asked, "the value");
328
+ break;
329
+ case "kv.delete":
330
+ w.u32(asked, "deleted");
331
+ break;
332
+ case "kv.list": {
333
+ const listed = asked;
334
+ w.u16(listed.keys.length, "the number of keys");
335
+ for (const info of listed.keys) {
336
+ w.key(info.key).u32(info.bytes, "a key's bytes").flags(info.expiresAt !== void 0);
337
+ if (info.expiresAt !== void 0) w.u64(info.expiresAt, "expiresAt");
338
+ }
339
+ w.flags(listed.next !== void 0);
340
+ if (listed.next !== void 0) w.key(listed.next);
341
+ break;
342
+ }
343
+ case "kv.limit": {
344
+ const decided = asked;
345
+ w.u8(decided.ok ? 1 : 0, "ok").u32(decided.limit, "limit").u32(decided.remaining, "remaining").u64(decided.resetAt, "resetAt").flags(decided.retryAfterMs !== void 0);
346
+ if (decided.retryAfterMs !== void 0) w.u64(decided.retryAfterMs, "retryAfterMs");
347
+ break;
348
+ }
349
+ case "kv.stats": {
350
+ const stats = asked;
351
+ w.u64(stats.keys, "keys").u64(stats.bytes, "bytes");
352
+ break;
353
+ }
354
+ }
355
+ return w.done();
356
+ }
357
+ /** The frame of a refused call: its error's status and `why`. */
358
+ function errorFrame(code, why) {
359
+ return new Writer().u8(VERSION, "version").u8(STATUS[code], "status").key(why.slice(0, WHY_UNITS), "a why's length in bytes").done();
360
+ }
361
+ /**
362
+ * The answer an `op` frame carries. A refusal throws its `KvError`; a frame that is no answer to `op` throws
363
+ * `unavailable`.
364
+ */
365
+ function decodeAnswer(op, frame) {
366
+ const r = new Reader(frame, () => {
367
+ throw new KvError("unavailable", NOT_AN_ANSWER);
368
+ });
369
+ if (r.u8() !== VERSION) r.bad("version");
370
+ const status = r.u8();
371
+ if (status !== 0) {
372
+ const code = CODES[status];
373
+ if (code === void 0) r.bad("status");
374
+ const why = r.key();
375
+ r.end();
376
+ throw new KvError(code, why);
377
+ }
378
+ let answer;
379
+ const expiresAt = (on) => on ? { expiresAt: r.u64() } : {};
380
+ const yes = () => {
381
+ const byte = r.u8();
382
+ if (byte > 1) r.bad("a yes or no is 0 or 1");
383
+ return byte === 1;
384
+ };
385
+ switch (op) {
386
+ case "kv.get":
387
+ answer = Array.from({ length: r.u8() }, () => {
388
+ if (!yes()) return null;
389
+ const [timed] = r.flags(1);
390
+ return {
391
+ value: r.text(r.u32(), "a value is not UTF-8 text"),
392
+ ...expiresAt(timed)
393
+ };
394
+ });
395
+ break;
396
+ case "kv.set":
397
+ case "kv.expire":
398
+ case "kv.limit.reset":
399
+ answer = yes();
400
+ break;
401
+ case "kv.incr":
402
+ answer = r.i64();
403
+ break;
404
+ case "kv.delete":
405
+ answer = r.u32();
406
+ break;
407
+ case "kv.list":
408
+ answer = {
409
+ keys: Array.from({ length: r.u16() }, () => {
410
+ return {
411
+ key: r.key(),
412
+ bytes: r.u32(),
413
+ ...expiresAt(r.flags(1)[0])
414
+ };
415
+ }),
416
+ ...r.flags(1)[0] ? { next: r.key() } : {}
417
+ };
418
+ break;
419
+ case "kv.limit":
420
+ answer = {
421
+ ok: yes(),
422
+ limit: r.u32(),
423
+ remaining: r.u32(),
424
+ resetAt: r.u64(),
425
+ ...r.flags(1)[0] ? { retryAfterMs: r.u64() } : {}
426
+ };
427
+ break;
428
+ case "kv.stats": answer = {
429
+ keys: r.u64(),
430
+ bytes: r.u64()
431
+ };
432
+ }
433
+ r.end();
434
+ return answer;
435
+ }
102
436
  /** The engine on the far side of `transport`. */
103
437
  function remote(transport) {
104
- const call = async (header) => {
105
- let frame;
438
+ const call = async (sent) => {
439
+ const frame = encodeCall(sent);
440
+ let answered;
106
441
  try {
107
- frame = await transport.send(encodeFrame(header));
442
+ answered = await transport.send(frame);
108
443
  } catch (error) {
109
444
  if (error instanceof KvError) throw error;
110
445
  if (error instanceof Error && "code" in error && (error.code === "forbidden" || error.code === "unavailable")) throw new KvError(error.code, "The key-value store could not be reached");
111
446
  throw new KvError("unavailable", "The key-value store could not be reached");
112
447
  }
113
- let parsed;
114
- try {
115
- parsed = answer.parse(decodeFrame(frame).header);
116
- } catch {
117
- throw new KvError("unavailable", "The key-value store answered something that is not one of its answers");
118
- }
119
- if ("error" in parsed) throw new KvError(parsed.error, parsed.why);
120
- return parsed;
121
- };
122
- const expect = (answered, key) => {
123
- if (!(key in answered)) throw new KvError("unavailable", "The key-value store answered another call");
124
- return answered[key];
448
+ return decodeAnswer(sent.op, answered);
125
449
  };
126
450
  return {
127
451
  async get(keys) {
128
- return expect(await call({
452
+ const entries = await call({
129
453
  op: "kv.get",
130
- keys: [...keys]
131
- }), "entries").map((found) => found ? present(found) : null);
132
- },
133
- async set(key, value, options) {
134
- return expect(await call(present({
135
- op: "kv.set",
136
- key,
137
- value,
138
- ttlMs: options.ttlMs,
139
- ifAbsent: options.ifAbsent ? true : void 0
140
- })), "written");
141
- },
142
- async incr(key, by, ttlMs) {
143
- return expect(await call(present({
144
- op: "kv.incr",
145
- key,
146
- by,
147
- ttlMs
148
- })), "value");
149
- },
150
- async delete(keys) {
151
- return expect(await call({
152
- op: "kv.delete",
153
- keys: [...keys]
154
- }), "deleted");
155
- },
156
- async expire(key, ttlMs) {
157
- return expect(await call({
158
- op: "kv.expire",
159
- key,
160
- ttlMs
161
- }), "found");
162
- },
163
- async list(options) {
164
- const listed = await call(present({
165
- op: "kv.list",
166
- prefix: options.prefix,
167
- after: options.after,
168
- limit: options.limit
169
- }));
170
- const keys = expect(listed, "keys").map((found) => present(found));
171
- const next = listed.next;
172
- return {
173
- keys,
174
- ...next === void 0 ? {} : { next }
175
- };
176
- },
177
- async limit(key, options) {
178
- return present(expect(await call({
179
- op: "kv.limit",
180
- key,
181
- ...options
182
- }), "decided"));
183
- },
184
- async resetLimit(key) {
185
- return expect(await call({
186
- op: "kv.limit.reset",
187
- key
188
- }), "reset");
454
+ keys
455
+ });
456
+ if (entries.length !== keys.length) throw new KvError("unavailable", "The key-value store answered another call");
457
+ return entries;
189
458
  },
190
- async stats() {
191
- return expect(await call({ op: "kv.stats" }), "stats");
192
- }
459
+ set: (key, value, options) => call({
460
+ op: "kv.set",
461
+ key,
462
+ value,
463
+ ...options.ttlMs === void 0 ? {} : { ttlMs: options.ttlMs },
464
+ ...options.ifAbsent ? { ifAbsent: true } : {}
465
+ }),
466
+ incr: (key, by, ttlMs) => call({
467
+ op: "kv.incr",
468
+ key,
469
+ by,
470
+ ...ttlMs === void 0 ? {} : { ttlMs }
471
+ }),
472
+ delete: (keys) => call({
473
+ op: "kv.delete",
474
+ keys
475
+ }),
476
+ expire: (key, ttlMs) => call({
477
+ op: "kv.expire",
478
+ key,
479
+ ttlMs
480
+ }),
481
+ list: (options) => call({
482
+ op: "kv.list",
483
+ prefix: options.prefix,
484
+ ...options.after === void 0 ? {} : { after: options.after },
485
+ limit: options.limit
486
+ }),
487
+ limit: (key, options) => call({
488
+ op: "kv.limit",
489
+ key,
490
+ max: options.max,
491
+ windowMs: options.windowMs,
492
+ cost: options.cost
493
+ }),
494
+ resetLimit: (key) => call({
495
+ op: "kv.limit.reset",
496
+ key
497
+ }),
498
+ stats: () => call({ op: "kv.stats" })
193
499
  };
194
500
  }
195
501
  /**
196
- * Replies to one request frame from `engine`. Every frame is checked again here, since it comes from the network,
197
- * and a failure becomes an error frame with its code. `kv.stats` is returned only by an engine that counts.
502
+ * Replies to one call's frame from `engine`. Every frame is checked again here, since it comes from the network,
503
+ * and a failure becomes an error frame with its status. `kv.stats` is answered only by an engine that counts.
198
504
  */
199
505
  function serve(engine) {
200
506
  return async (frame) => {
201
507
  try {
202
- let header;
203
- try {
204
- header = decodeFrame(frame).header;
205
- } catch {
206
- throw new KvError("invalid", "the frame is not a frame");
207
- }
208
- const parsed = request.safeParse(header);
209
- if (!parsed.success) throw new KvError("invalid", "the request frame is not a key-value call");
210
- const call = parsed.data;
508
+ const call = decodeCall(frame);
211
509
  switch (call.op) {
212
510
  case "kv.get":
213
511
  checkKeys(call.keys);
214
- return encodeFrame({ entries: await engine.get(call.keys) });
512
+ return encodeAnswer(call.op, await engine.get(call.keys));
215
513
  case "kv.set":
216
514
  checkKey(call.key);
217
515
  checkValueText(call.value);
@@ -221,27 +519,26 @@ function serve(engine) {
221
519
  throw new KvError("invalid", "the value is not JSON text");
222
520
  }
223
521
  if (call.ttlMs !== void 0) checkTtlMs(call.ttlMs);
224
- return encodeFrame({ written: await engine.set(call.key, call.value, {
522
+ return encodeAnswer(call.op, await engine.set(call.key, call.value, {
225
523
  ...call.ttlMs === void 0 ? {} : { ttlMs: call.ttlMs },
226
524
  ...call.ifAbsent ? { ifAbsent: true } : {}
227
- }) });
525
+ }));
228
526
  case "kv.incr":
229
527
  checkKey(call.key);
230
- if (!Number.isSafeInteger(call.by)) throw new KvError("invalid", "by is a whole number");
231
528
  if (call.ttlMs !== void 0) checkTtlMs(call.ttlMs);
232
- return encodeFrame({ value: await engine.incr(call.key, call.by, call.ttlMs) });
529
+ return encodeAnswer(call.op, await engine.incr(call.key, call.by, call.ttlMs));
233
530
  case "kv.delete":
234
531
  checkKeys(call.keys);
235
- return encodeFrame({ deleted: await engine.delete(call.keys) });
532
+ return encodeAnswer(call.op, await engine.delete(call.keys));
236
533
  case "kv.expire":
237
534
  checkKey(call.key);
238
535
  if (call.ttlMs !== null) checkTtlMs(call.ttlMs);
239
- return encodeFrame({ found: await engine.expire(call.key, call.ttlMs) });
536
+ return encodeAnswer(call.op, await engine.expire(call.key, call.ttlMs));
240
537
  case "kv.list":
241
538
  checkPrefix(call.prefix);
242
539
  if (call.after !== void 0) checkKey(call.after);
243
540
  checkListLimit(call.limit);
244
- return encodeFrame(await engine.list({
541
+ return encodeAnswer(call.op, await engine.list({
245
542
  prefix: call.prefix,
246
543
  limit: call.limit,
247
544
  ...call.after === void 0 ? {} : { after: call.after }
@@ -249,29 +546,23 @@ function serve(engine) {
249
546
  case "kv.limit":
250
547
  checkKey(call.key);
251
548
  checkLimit(call);
252
- return encodeFrame({ decided: await engine.limit(call.key, {
549
+ return encodeAnswer(call.op, await engine.limit(call.key, {
253
550
  max: call.max,
254
551
  windowMs: call.windowMs,
255
552
  cost: call.cost
256
- }) });
553
+ }));
257
554
  case "kv.limit.reset":
258
555
  checkKey(call.key);
259
- return encodeFrame({ reset: await engine.resetLimit(call.key) });
556
+ return encodeAnswer(call.op, await engine.resetLimit(call.key));
260
557
  case "kv.stats":
261
558
  if (!engine.stats) throw new KvError("invalid", "this store doesn't count its keys");
262
- return encodeFrame({ stats: await engine.stats() });
559
+ return encodeAnswer(call.op, await engine.stats());
263
560
  }
264
561
  } catch (error) {
265
- if (error instanceof KvError) return encodeFrame({
266
- error: error.code,
267
- why: error.message
268
- });
269
- return encodeFrame({
270
- error: "unavailable",
271
- why: "The key-value store failed to answer"
272
- });
562
+ if (error instanceof KvError) return errorFrame(error.code, error.message);
563
+ return errorFrame("unavailable", "The key-value store failed to answer");
273
564
  }
274
565
  };
275
566
  }
276
567
  //#endregion
277
- export { remote, serve };
568
+ export { OPS, decodeAnswer, decodeCall, encodeAnswer, encodeCall, errorFrame, remote, serve };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midsummer-ai/sdk",
3
- "version": "0.1.0-staging.4477",
3
+ "version": "0.1.0-staging.4480",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "description": "Midsummer's handles for an app's code: its Database, Storage, Queues, Vector DB, AI, Email and Agents, with stand-ins for tests.",