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

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 (46) hide show
  1. package/auth/contract.d.mts +1 -1
  2. package/auth/contract.mjs +2 -2
  3. package/auth/index.d.mts +1 -1
  4. package/auth/index.mjs +1 -1
  5. package/auth/mail.d.mts +1 -1
  6. package/auth/password.mjs +1 -1
  7. package/auth/react.mjs +1 -1
  8. package/{auth-C7yU9QWZ.mjs → auth-BH2Lfguc.mjs} +49 -3
  9. package/calls/contract.d.mts +23 -0
  10. package/calls/contract.mjs +293 -0
  11. package/calls/index.d.mts +147 -0
  12. package/calls/index.mjs +1131 -0
  13. package/calls/protocol.d.mts +2 -0
  14. package/calls/protocol.mjs +33 -0
  15. package/calls/react.d.mts +56 -0
  16. package/calls/react.mjs +225 -0
  17. package/calls/stand-in.d.mts +22 -0
  18. package/calls/stand-in.mjs +390 -0
  19. package/calls/ui.d.mts +76 -0
  20. package/calls/ui.mjs +783 -0
  21. package/email/client.d.mts +1 -1
  22. package/email/contract.d.mts +1 -1
  23. package/email/inbox.d.mts +1 -1
  24. package/email/index.d.mts +1 -1
  25. package/email/smtp.d.mts +1 -1
  26. package/email/stand-in.d.mts +1 -1
  27. package/{engine-Be7yur9O.mjs → engine-CmTP59GT.mjs} +1 -1
  28. package/flows/contract.d.mts +1 -1
  29. package/flows/index.d.mts +1 -1
  30. package/{guard-Br3K8CVx.mjs → guard-VPI6xq4z.mjs} +1 -1
  31. package/here-C2jhTheQ.mjs +1 -1
  32. package/{index-CkyNDcba.d.mts → index-BmjcZfRb.d.mts} +8 -0
  33. package/{index-DI_L79Hc.d.mts → index-bperY8NN.d.mts} +2 -2
  34. package/index-c616Dbux.d.mts +343 -0
  35. package/kv/contract.d.mts +5 -0
  36. package/kv/contract.mjs +3 -0
  37. package/kv/wire.d.mts +77 -4
  38. package/kv/wire.mjs +492 -201
  39. package/package.json +43 -1
  40. package/protocol-BeBvbfKf.d.mts +185 -0
  41. package/queues/contract.d.mts +1 -1
  42. package/queues/index.d.mts +1 -342
  43. package/queues/stand-in.d.mts +1 -1
  44. package/queues/wire.d.mts +1 -1
  45. package/{style-BJzVvUKV.mjs → style-DXd-0Cxo.mjs} +1 -163
  46. package/tokens-BpV8U5E1.mjs +164 -0
@@ -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>;
@@ -1,6 +1,6 @@
1
1
  import { i as __toCommonJS, n as __esmMin, r as __exportAll, t as __commonJSMin } from "./rolldown-runtime-CL6CfywC.mjs";
2
2
  import { KEY_PREFIX } from "./auth/key.mjs";
3
- import { h as IDENTITY_SCOPES, o as ourWords, u as JoinRefused, x as resourceOf } from "./guard-Br3K8CVx.mjs";
3
+ import { h as IDENTITY_SCOPES, o as ourWords, u as JoinRefused, x as resourceOf } from "./guard-VPI6xq4z.mjs";
4
4
  import { impersonationIdentifier } from "./auth/impersonate.mjs";
5
5
  import { $ as queueAfterTransactionHook, $t as getOrigin, A as freshSessionMiddleware, At as userSchema, B as sensitiveSessionMiddleware, Bt as jwtVerify, C as parseScopeField, Ct as parseAccountOutput, D as constantTimeEqual, Dt as parseUserInput, E as generateRandomString, Et as parseSessionOutput, F as listSessions, Ft as decodeJwt, G as createAuthMiddleware, Gt as JWTExpired, H as appendQueryParams, Ht as JOSEError, I as requestOnlySessionMiddleware, It as decodeProtectedHeader, J as defu, Jt as hasServerSessionStore, K as isAPIError$1, Kt as sha256, L as revokeOtherSessions, Lt as importJWK, M as getSession, Mt as number, N as getSessionFromCtx, Nt as string, O as getOAuthServerContext, Ot as parseUserOutput, P as isStateful, Pt as signJWT, Q as getCurrentAdapter, Qt as getHost, R as revokeSession, Rt as createLocalJWKSet, S as parseProviderEmailVerified, St as mergeSchema, T as symmetricEncrypt, Tt as parseSessionInput, U as normalizePathname, Ut as JWKSNoMatchingKey, V as sessionMiddleware, Vt as isJwkSet, W as createAuthEndpoint, Wt as JWKSTimeout, X as findInvalidTrustedProxies, Xt as isPromise, Y as createRateLimitKey, Yt as shouldBindAccountCookieToSessionUser, Z as getIP, Zt as getBaseURL, _ as encodeBasicCredentials, _t as parseSetCookieHeader, a as resolveSigningKey, an as BASE_ERROR_CODES, at as tryGetCurrentAuthEndpointContext, b as getPrimaryClientId, bt as buildSyntheticUserOutput, c as getDefaultKeyAlg, ct as deleteSessionCookie, d as getOperationId, dt as setCookieCache, en as getProtocol, et as runWithAdapter, f as verifyJwsAccessToken, ft as setSessionCookie, g as resolveClientAssertionParams, gt as createRouter$1, h as betterFetch, ht as setAccountCookie, i as getJwtToken, in as trimTrailingSlashes, it as getCurrentAuthEndpointContext, j as getAuthoritativeSessionFromCtx, jt as coreSchema, k as setOAuthState, kt as filterOutputFields, l as getJwksAdapter, lt as expireCookie, m as fetchRefusingRedirects, mt as getAccountCookie, n as metadataResponse, nn as isRequestLike, nt as runtimeSchemaCheckFor, o as signJWT$1, on as defineErrorCodes, ot as createHash, p as DPOP_SIGNING_ALGORITHMS, pt as createHMAC, q as isLoopbackHost$1, qt as hkdf, r as oauthProvider, rn as resolveBaseURL, rt as schemaCheckFor, s as createJwk, sn as wildcardMatch, st as createCookieGetter, t as getIssuer, tn as isDynamicBaseURLConfig, tt as runWithTransaction, u as dispatchAuthEndpoint, ut as getCookies, v as generateCodeChallenge, vt as parseCookieCachePayload, w as symmetricDecrypt, wt as parseAdditionalUserInputFromProviderProfile, x as mergeScopes, xt as getSessionDefaultFields, y as getOAuth2Tokens, yt as getDate$1, z as revokeSessions, zt as SignJWT } from "./authorize-BzDrbYtI-0gOzDrp2.mjs";
6
6
  import { B as getBooleanEnvVar, E as bytesToHex, F as logger, H as isDevelopment, M as utf8ToBytes, P as createLogger, R as ENV, U as isProduction, V as getEnvVar, W as isTest, a as createRandomStringGenerator, b as getAuthTables, c as ATTR_DB_COLLECTION_NAME, d as ATTR_HTTP_RESPONSE_STATUS_CODE, g as base64Url, h as base64$1, i as generateId$1, o as createWithSpan, s as ATTR_CONTEXT, t as encodeDeterministicId, u as ATTR_HOOK_TYPE, v as toUint8Array, y as safeJSONParse, z as env } from "./get-id-field-vhOArqXN.mjs";
@@ -1,4 +1,4 @@
1
- import { QueueEngine } from "../queues/index.mjs";
1
+ import { d as QueueEngine } from "../index-c616Dbux.mjs";
2
2
  //#region src/flows/contract.d.ts
3
3
  interface FlowCase {
4
4
  /** A line of the specification. */
package/flows/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { Json, QueueEngine, RunStatus } from "../queues/index.mjs";
1
+ import { _ as RunStatus, d as QueueEngine, s as Json } from "../index-c616Dbux.mjs";
2
2
  //#region src/flows/index.d.ts
3
3
  /** What a step that failed for good throws into its Flow's function: `step` is its name, `message` the last error. */
4
4
  declare class StepFailed extends Error {
@@ -1,5 +1,5 @@
1
1
  import "./auth/key.mjs";
2
- import { l as screenName, t as authCss } from "./style-BJzVvUKV.mjs";
2
+ import { l as screenName, t as authCss } from "./style-DXd-0Cxo.mjs";
3
3
  //#region src/auth/agents.ts
4
4
  /**
5
5
  * Agents as users of your app: API keys, and sign-in for MCP clients, both limited to the scopes your app
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.4483";
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
@@ -172,6 +172,14 @@ interface AuthOptions {
172
172
  readonly signInPage?: string;
173
173
  /** The app's own page that asks the person whether to let a client in; sign-in's own page when left out. */
174
174
  readonly consentPage?: string;
175
+ /**
176
+ * Hands a signed-in person a call token at `GET /api/auth/call-token?room=<name>` when `allow` says they may join
177
+ * that room: `allow: (user, room) => room === "support-" + user.id` lets each person into their own support call
178
+ * only. With none, that route hands out nothing.
179
+ */
180
+ readonly calls?: {
181
+ allow(user: AuthUser, room: string): boolean | Promise<boolean>;
182
+ };
175
183
  }
176
184
  /** One of the app's users. `publicMetadata` is the app's to set from its server (`auth.users.setMetadata`). */
177
185
  interface AuthUser {
@@ -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;
@@ -0,0 +1,343 @@
1
+ //#region src/queues/index.d.ts
2
+ /**
3
+ * Queues: a Team's Queues of Messages, which the SDK reaches by the name an Environment binds each one
4
+ * under (`midsummer env binding set`).
5
+ *
6
+ * import { queues } from "@midsummer-ai/sdk/queues"
7
+ * import { standIn } from "@midsummer-ai/sdk/queues/stand-in"
8
+ *
9
+ * const jobs = queues(standIn({ clock: Date.now }))
10
+ * const emails = jobs.queue("emails")
11
+ * await emails.send({ to: "ada@example.com" }, { key: `welcome:${userId}` })
12
+ * for (const delivery of await emails.receive({ limit: 10 })) {
13
+ * try { await mail(delivery.body); await emails.ack(delivery.receipt) }
14
+ * catch { await emails.retry(delivery.receipt) }
15
+ * }
16
+ * const { depth, oldestSentAt } = await emails.stats()
17
+ *
18
+ * In a deployment, in any framework, and under `midsummer dev`, `queue` reaches the queue the
19
+ * environment binds under a name, with nothing to connect:
20
+ *
21
+ * import { queue } from "@midsummer-ai/sdk/queues"
22
+ *
23
+ * await queue("emails").send({ to: "ada@example.com" })
24
+ *
25
+ * The Stand-in keeps Messages in memory, for tests and `midsummer dev`. Code can pull its Messages
26
+ * with `receive`, or a consumer can deliver each one to a path of your site (`midsummer queue
27
+ * consumer set`). Each engine is held to the cases in `@midsummer-ai/sdk/queues/contract`; a
28
+ * behaviour that is not a case there is not promised.
29
+ *
30
+ * Delivery is at least once. A Message received is hidden from other receivers for its visibility
31
+ * window; acked, it is gone; retried, or left until the window ends, it is delivered again, a later
32
+ * time each attempt (10 seconds after the first, doubling, at most 10 minutes). Once it has been
33
+ * delivered `maxAttempts` times (5 unless the receiver says), a retry or an ended window moves it
34
+ * to the Queue's dead-letter Queue, `queue.deadLetter`, where it waits to be read and never moves on.
35
+ * A receipt names one delivery: acking or retrying one whose window has ended does nothing.
36
+ *
37
+ * A send with a `key` is made once: sending the same key to the same Queue again, within a day,
38
+ * returns the first Message's id and sends nothing. Schedules send with one, so a Schedule's minute
39
+ * sends once however often it is reached.
40
+ *
41
+ * Messages sent with the same `group` are delivered one at a time, in the order sent: the next is
42
+ * delivered only once the one before it is acked or moved to the dead-letter Queue, and a retried one
43
+ * keeps its place, so order-dependent work (a customer's payments, one document's edits) never runs
44
+ * out of order. Each group goes on apart from the others. A Queue can let a group have more at once,
45
+ * and limit deliveries a period (`midsummer queue edit`); its limits hold Messages back, never drop them.
46
+ *
47
+ * A receiver whose work takes longer than its visibility window extends it with `extend`, as often as
48
+ * it needs, before the window ends.
49
+ *
50
+ * Names and bodies are checked here, before anything leaves the caller. Every failure is a
51
+ * `QueueError`, whose `code` is the one the wire carries.
52
+ */
53
+ /** Why a Queues call failed: as Storage's codes say (`invalid`, `forbidden`, `quota`, `unavailable` …), and `not-found` for a Flow run there is none of. */
54
+ type QueueErrorCode = "invalid" | "forbidden" | "quota" | "unavailable" | "not-found";
55
+ declare const queueErrorCodes: ReadonlyArray<QueueErrorCode>;
56
+ declare class QueueError extends Error {
57
+ readonly code: QueueErrorCode;
58
+ constructor(code: QueueErrorCode, why: string);
59
+ }
60
+ /** Any value JSON can carry. */
61
+ type Json = string | number | boolean | null | ReadonlyArray<Json> | {
62
+ readonly [key: string]: Json;
63
+ };
64
+ /** One delivery of a Message: its body as sent, and the receipt that acks or retries it. */
65
+ interface Delivery<Body = Json> {
66
+ readonly id: string;
67
+ readonly body: Body;
68
+ /** When it was sent, in milliseconds since the epoch. */
69
+ readonly sentAt: number;
70
+ /** Which delivery this is: 1 the first time it is received. */
71
+ readonly attempt: number;
72
+ /** Names this delivery; it acks or retries it until `visibleUntil`, and does nothing after. */
73
+ readonly receipt: string;
74
+ /** When the visibility window ends and the Message may be delivered again. */
75
+ readonly visibleUntil: number;
76
+ /** The Flow run this Message carries (`@midsummer-ai/sdk/flows`); a Flow's `work` runs it. */
77
+ readonly run?: string;
78
+ }
79
+ interface SendOptions {
80
+ /** Seconds before it can be received: 0 to 31,536,000 (365 days), 0 by default. */
81
+ readonly delaySeconds?: number;
82
+ /** Makes the send once: 1 to 128 printable characters. */
83
+ readonly key?: string;
84
+ /** Delivers it after the group's earlier Messages, one at a time: 1 to 128 printable characters, such as `customer:42`. */
85
+ readonly group?: string;
86
+ }
87
+ interface ReceiveOptions {
88
+ /** At most this many: 1 to 100, 10 by default. */
89
+ readonly limit?: number;
90
+ /** Seconds each delivery is hidden from other receivers: 1 to 43,200, 30 by default. */
91
+ readonly visibilitySeconds?: number;
92
+ /** Deliveries after which a retry moves the Message to the dead-letter Queue: 1 to 100, 5 by default. */
93
+ readonly maxAttempts?: number;
94
+ }
95
+ /**
96
+ * What a Queue holds now. Each count stops at 1,000, with `more` set when there are more: reading
97
+ * stats never reads a whole Queue.
98
+ */
99
+ interface QueueStats {
100
+ /** Every Message not yet acked: ready, in flight and delayed. */
101
+ readonly depth: number;
102
+ /** Messages that can be received now. */
103
+ readonly ready: number;
104
+ /** Messages delivered whose visibility window has not ended. */
105
+ readonly inFlight: number;
106
+ /** Messages sent with a delay, or retried, that cannot be received yet. */
107
+ readonly delayed: number;
108
+ /** When the oldest Message not yet acked was sent; absent when there is none. */
109
+ readonly oldestSentAt?: number;
110
+ /** Messages in the dead-letter Queue. */
111
+ readonly dead: number;
112
+ readonly more?: true;
113
+ }
114
+ /** The Messages of one Queue. */
115
+ interface Queue {
116
+ readonly name: string;
117
+ /** Sends one Message. Its body is any JSON value, at most 128 KiB as JSON. */
118
+ send(body: Json, options?: SendOptions): Promise<{
119
+ readonly id: string;
120
+ }>;
121
+ /** Sends up to 100 Messages together, received in the order given; ids in the same order. */
122
+ sendBatch(messages: ReadonlyArray<{
123
+ readonly body: Json;
124
+ } & SendOptions>): Promise<{
125
+ readonly ids: ReadonlyArray<string>;
126
+ }>;
127
+ /**
128
+ * Up to `limit` Messages that can be received now, oldest first. An engine looks at a bounded
129
+ * number of Messages a call, so it may answer fewer, or none, while it moves exhausted ones to the
130
+ * dead-letter Queue: receive again.
131
+ */
132
+ receive<Body = Json>(options?: ReceiveOptions): Promise<ReadonlyArray<Delivery<Body>>>;
133
+ /** Ends a Message: it is not delivered again. */
134
+ ack(receipt: string): Promise<void>;
135
+ /**
136
+ * Hands a Message back to be delivered again after `delaySeconds`, or after the backoff when not
137
+ * given: 10 seconds after the first delivery, doubling, at most 600. Past its `maxAttempts` it
138
+ * moves to the dead-letter Queue instead.
139
+ */
140
+ retry(receipt: string, options?: {
141
+ readonly delaySeconds?: number;
142
+ }): Promise<void>;
143
+ /**
144
+ * Keeps a delivery hidden `visibilitySeconds` (1 to 43,200, 30 by default) from now, for work that
145
+ * takes longer than its window. Returns when the window now ends, or undefined when the receipt has
146
+ * already ended, and the work should stop: the Message may be delivered again.
147
+ */
148
+ extend(receipt: string, options?: {
149
+ readonly visibilitySeconds?: number;
150
+ }): Promise<number | undefined>;
151
+ stats(): Promise<QueueStats>;
152
+ /** Where this Queue's Messages go once they have been delivered `maxAttempts` times. Its own Messages never move on. */
153
+ readonly deadLetter: Queue;
154
+ }
155
+ interface Queues {
156
+ /** A Queue by name: 1 to 63 lowercase letters, digits, hyphens and underscores, starting with a letter or digit. */
157
+ queue(name: string): Queue;
158
+ }
159
+ /** A Message as an engine is given it: its body as JSON text. */
160
+ interface EngineMessage {
161
+ readonly body: string;
162
+ readonly delayMs: number;
163
+ readonly key?: string;
164
+ readonly group?: string;
165
+ }
166
+ /** Where a Flow run is: delivered or ready to be (`running`), parked until it wakes, or ended. */
167
+ type RunStatus = "running" | "sleeping" | "waiting" | "completed" | "failed" | "cancelled";
168
+ /** One recorded step of a run, as an engine keeps it: its value as JSON text. A wait that timed out has none. */
169
+ interface EngineStep {
170
+ /** The step's name, with `#2`, `#3` … after it for its second and later uses in one run. */
171
+ readonly id: string;
172
+ readonly kind: "run" | "sleep" | "wait";
173
+ readonly state: "done" | "failed" | "retrying" | "sleeping" | "waiting";
174
+ readonly value?: string;
175
+ readonly error?: string;
176
+ /** How many times its work threw. */
177
+ readonly failures: number;
178
+ /** When a sleeping or waiting step wakes, or a retrying one runs again. */
179
+ readonly until?: number;
180
+ /** The signal a wait waits for. */
181
+ readonly event?: string;
182
+ readonly at: number;
183
+ }
184
+ /** A Flow run as an engine keeps it: input and output as JSON text, and its steps in the order first recorded. */
185
+ interface EngineRun {
186
+ readonly id: string;
187
+ readonly status: RunStatus;
188
+ readonly input: string;
189
+ readonly startedAt: number;
190
+ readonly endedAt?: number;
191
+ readonly nextAt?: number;
192
+ readonly output?: string;
193
+ readonly error?: string;
194
+ readonly deadline?: number;
195
+ readonly group?: string;
196
+ readonly steps: ReadonlyArray<EngineStep>;
197
+ }
198
+ /**
199
+ * What a delivery of a run records about one step: a value its work returned, or the error it threw
200
+ * with how many retries the step allows; a sleep of `ms`; or a wait for the signal `event` of at most
201
+ * `timeoutMs`.
202
+ */
203
+ type StepWrite = {
204
+ readonly kind: "run";
205
+ readonly id: string;
206
+ readonly value: string;
207
+ } | {
208
+ readonly kind: "run";
209
+ readonly id: string;
210
+ readonly error: string;
211
+ readonly retries: number;
212
+ } | {
213
+ readonly kind: "sleep";
214
+ readonly id: string;
215
+ readonly ms: number;
216
+ } | {
217
+ readonly kind: "wait";
218
+ readonly id: string;
219
+ readonly event: string;
220
+ readonly timeoutMs: number;
221
+ };
222
+ /** A delivery as an engine returns it: its body as JSON text. */
223
+ interface EngineDelivery extends Omit<Delivery, "body"> {
224
+ readonly body: string;
225
+ }
226
+ /**
227
+ * Where Messages live: the Seam under `queues()`. The Stand-in and the real Capability are its
228
+ * Adapters. Calls arrive checked: a Queue's name is valid (with `.dead` after it for a dead-letter
229
+ * Queue), bodies are JSON text, times are milliseconds and defaults are filled in.
230
+ */
231
+ interface QueueEngine {
232
+ /** Sends the Messages in order and returns their ids, a keyed one's first id when it was sent before. */
233
+ send(queue: string, messages: ReadonlyArray<EngineMessage>): Promise<ReadonlyArray<string>>;
234
+ receive(queue: string, options: {
235
+ readonly limit: number;
236
+ readonly visibilityMs: number;
237
+ readonly maxAttempts: number;
238
+ }): Promise<ReadonlyArray<EngineDelivery>>;
239
+ ack(queue: string, receipt: string): Promise<void>;
240
+ /** With no `delayMs`, the backoff after the delivery's attempt (`backoffMs`). */
241
+ retry(queue: string, receipt: string, delayMs?: number): Promise<void>;
242
+ /** Moves a current delivery's window to end `visibilityMs` from now and returns that time; undefined once the receipt has ended. */
243
+ extend(queue: string, receipt: string, visibilityMs: number): Promise<number | undefined>;
244
+ stats(queue: string): Promise<QueueStats>;
245
+ /**
246
+ * Starts a Flow run with its input, as one Message of the Queue that carries it: within `timeoutMs`
247
+ * when given, in `group` when given. An id used before starts nothing and returns `started: false`.
248
+ */
249
+ start(queue: string, run: {
250
+ readonly id: string;
251
+ readonly input: string;
252
+ readonly timeoutMs?: number;
253
+ readonly group?: string;
254
+ }): Promise<{
255
+ readonly id: string;
256
+ readonly started: boolean;
257
+ }>;
258
+ /**
259
+ * The run a current delivery carries, with its steps and the engine's time, for its code to run
260
+ * again; undefined once the receipt has ended. A run that has ended, or passed its deadline (failing
261
+ * it), comes back ended: its code doesn't run.
262
+ */
263
+ load(queue: string, runId: string, receipt: string): Promise<{
264
+ readonly now: number;
265
+ readonly run: EngineRun;
266
+ } | undefined>;
267
+ /**
268
+ * Records one step for a current delivery and returns it as now kept: the first value recorded
269
+ * wins, so of two deliveries the second takes the first's. A step that sleeps, waits or retries
270
+ * ends the delivery, its Message delivered again when it wakes. Undefined once the delivery or the
271
+ * run has ended: the code stops.
272
+ */
273
+ record(queue: string, runId: string, receipt: string, step: StepWrite): Promise<EngineStep | undefined>;
274
+ /** Ends a run with what its code returned, or why it failed; a delivery that has ended, or a run that has, changes nothing. */
275
+ finish(queue: string, runId: string, receipt: string, end: {
276
+ readonly output: string;
277
+ } | {
278
+ readonly error: string;
279
+ }): Promise<void>;
280
+ /**
281
+ * Sends a run a signal: `delivered` when the run was waiting for `event` and wakes now, `kept` when
282
+ * it is kept for the run's next wait for it, `ended` when the run has ended, `missing` when there is
283
+ * no such run. A `key` sent before keeps nothing more.
284
+ */
285
+ signal(queue: string, runId: string, signal: {
286
+ readonly event: string;
287
+ readonly value: string;
288
+ readonly key?: string;
289
+ }): Promise<"delivered" | "kept" | "ended" | "missing">;
290
+ /** Cancels a run and returns it; undefined when there is none. */
291
+ cancel(queue: string, runId: string): Promise<EngineRun | undefined>;
292
+ run(queue: string, runId: string): Promise<EngineRun | undefined>;
293
+ }
294
+ /** The suffix that marks a Queue's dead-letter Queue; no Queue's own name has a dot. */
295
+ declare const DEAD = ".dead";
296
+ /** Where a run's Queues frames go with its Workload token (`workloadTransport`). */
297
+ declare const WORKLOAD_PATH = "/queues/workload";
298
+ /** The delay before a Message's next delivery after its `attempt`-th: 10 seconds, doubling, at most 10 minutes. */
299
+ declare function backoffMs(attempt: number): number;
300
+ /** Stats' counts stop at this many. */
301
+ declare const STATS_CAP = 1000;
302
+ declare function invalid(why: string): never;
303
+ declare function checkQueueName(name: string): void;
304
+ /** A name as an engine is given it: a Queue's, or its dead-letter Queue's. */
305
+ declare function checkEngineQueue(queue: string): void;
306
+ declare function checkKey(key: string): void;
307
+ /** A group or a run's id: 1 to 128 printable characters, without spaces. */
308
+ declare function checkToken(value: string, what: string): void;
309
+ /** A signal's event: as a step's name is, since a wait's event is its step's name unless it says. */
310
+ declare function checkEvent(event: string): void;
311
+ /** A step's name: 1 to 200 characters, without line breaks or other control characters. */
312
+ declare function checkStepName(name: string): void;
313
+ /** The longest a delay, a sleep, a wait or a run's timeout may be: 365 days. */
314
+ declare const MAX_WAIT_MS: number;
315
+ /** Bodies are at most this many bytes of JSON. */
316
+ declare const MAX_BODY: number;
317
+ /** The JSON text of `body`, which must be a JSON value of at most 128 KiB. */
318
+ declare function bodyText(body: unknown): string;
319
+ declare function checkReceipt(receipt: string): void;
320
+ declare function checkDelaySeconds(seconds: number): void;
321
+ /** A visibility window in milliseconds: whole seconds, 1 to 43,200. */
322
+ declare function checkVisibilityMs(ms: number): void;
323
+ declare function checkReceive(options: {
324
+ readonly limit: number;
325
+ readonly visibilityMs: number;
326
+ readonly maxAttempts: number;
327
+ }): void;
328
+ /**
329
+ * The engine of the environment this code runs in: the request's own in a deployment, a run's
330
+ * through its Workload session (a CI run, an agent's dev server, `midsummer dev --view`; a view's
331
+ * own queue on a view), or `midsummer dev`'s on this computer. Every call goes to the one current when it is made. Flows reach their
332
+ * Queues through it too.
333
+ */
334
+ declare function hereEngine(): QueueEngine;
335
+ /**
336
+ * The queue the environment binds under `name`, from code in a deployment in any framework, or
337
+ * `midsummer dev`'s queue of that name.
338
+ */
339
+ declare function queue(name: string): Queue;
340
+ /** Queues over `engine`: the Stand-in's in tests, or `hereEngine()`. */
341
+ declare function queues(engine: QueueEngine): Queues;
342
+ //#endregion
343
+ export { checkReceive as A, bodyText as C, checkKey as D, checkEvent as E, invalid as F, queue as I, queueErrorCodes as L, checkToken as M, checkVisibilityMs as N, checkQueueName as O, hereEngine as P, queues as R, backoffMs as S, checkEngineQueue as T, RunStatus as _, EngineRun as a, StepWrite as b, MAX_BODY as c, QueueEngine as d, QueueError as f, ReceiveOptions as g, Queues as h, EngineMessage as i, checkStepName as j, checkReceipt as k, MAX_WAIT_MS as l, QueueStats as m, Delivery as n, EngineStep as o, QueueErrorCode as p, EngineDelivery as r, Json as s, DEAD as t, Queue as u, STATS_CAP as v, checkDelaySeconds as w, WORKLOAD_PATH as x, SendOptions as y };
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 };