@midsummer-ai/sdk 0.1.0-staging.4459 → 0.1.0-staging.4465

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midsummer-ai/sdk",
3
- "version": "0.1.0-staging.4459",
3
+ "version": "0.1.0-staging.4465",
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.",
@@ -111,6 +111,22 @@
111
111
  "types": "./queues/wire.d.mts",
112
112
  "import": "./queues/wire.mjs"
113
113
  },
114
+ "./kv": {
115
+ "types": "./kv/index.d.mts",
116
+ "import": "./kv/index.mjs"
117
+ },
118
+ "./kv/stand-in": {
119
+ "types": "./kv/stand-in.d.mts",
120
+ "import": "./kv/stand-in.mjs"
121
+ },
122
+ "./kv/contract": {
123
+ "types": "./kv/contract.d.mts",
124
+ "import": "./kv/contract.mjs"
125
+ },
126
+ "./kv/wire": {
127
+ "types": "./kv/wire.d.mts",
128
+ "import": "./kv/wire.mjs"
129
+ },
114
130
  "./flows": {
115
131
  "types": "./flows/index.d.mts",
116
132
  "import": "./flows/index.mjs"
@@ -143,6 +159,18 @@
143
159
  "types": "./billing/contract.d.mts",
144
160
  "import": "./billing/contract.mjs"
145
161
  },
162
+ "./webhooks": {
163
+ "types": "./webhooks/index.d.mts",
164
+ "import": "./webhooks/index.mjs"
165
+ },
166
+ "./webhooks/stand-in": {
167
+ "types": "./webhooks/stand-in.d.mts",
168
+ "import": "./webhooks/stand-in.mjs"
169
+ },
170
+ "./webhooks/contract": {
171
+ "types": "./webhooks/contract.d.mts",
172
+ "import": "./webhooks/contract.mjs"
173
+ },
146
174
  "./apps": {
147
175
  "types": "./apps.d.mts",
148
176
  "import": "./apps.mjs"
@@ -313,6 +341,18 @@
313
341
  "queues/wire": [
314
342
  "./queues/wire.d.mts"
315
343
  ],
344
+ "kv": [
345
+ "./kv/index.d.mts"
346
+ ],
347
+ "kv/stand-in": [
348
+ "./kv/stand-in.d.mts"
349
+ ],
350
+ "kv/contract": [
351
+ "./kv/contract.d.mts"
352
+ ],
353
+ "kv/wire": [
354
+ "./kv/wire.d.mts"
355
+ ],
316
356
  "flows": [
317
357
  "./flows/index.d.mts"
318
358
  ],
@@ -337,6 +377,15 @@
337
377
  "billing/contract": [
338
378
  "./billing/contract.d.mts"
339
379
  ],
380
+ "webhooks": [
381
+ "./webhooks/index.d.mts"
382
+ ],
383
+ "webhooks/stand-in": [
384
+ "./webhooks/stand-in.d.mts"
385
+ ],
386
+ "webhooks/contract": [
387
+ "./webhooks/contract.d.mts"
388
+ ],
340
389
  "apps": [
341
390
  "./apps.d.mts"
342
391
  ],
@@ -0,0 +1,17 @@
1
+ import { Webhooks } from "./index.mjs";
2
+ //#region src/webhooks/contract.d.ts
3
+ declare const CONTRACT_RECEIVER = "https://hooks.example.com/contract";
4
+ declare const CONTRACT_FAILING = "https://hooks.example.com/failing";
5
+ /** What reached the receiver: each POST's address, headers and body, in order. */
6
+ type Posted = () => ReadonlyArray<{
7
+ readonly url: string;
8
+ readonly headers: Readonly<Record<string, string>>;
9
+ readonly body: string;
10
+ }>;
11
+ interface ContractCase {
12
+ readonly name: string;
13
+ run(webhooks: Webhooks, posted: Posted): Promise<void>;
14
+ }
15
+ declare const webhooksContract: ReadonlyArray<ContractCase>;
16
+ //#endregion
17
+ export { CONTRACT_FAILING, CONTRACT_RECEIVER, ContractCase, Posted, webhooksContract };
@@ -0,0 +1,163 @@
1
+ import { WebhooksError, verifyWebhook } from "./index.mjs";
2
+ //#region src/webhooks/contract.ts
3
+ /**
4
+ * Webhooks' contract: what every engine promises, as cases any test runner can run. Each case gets the webhooks under
5
+ * test and what reached `CONTRACT_RECEIVER`, the address its endpoints point at, which returns 200 to every POST but
6
+ * to `CONTRACT_FAILING`, which returns 500. The Stand-in runs them in this package, through a deployment's handle too;
7
+ * the real Capability runs the same cases with a receiver at those addresses.
8
+ *
9
+ * for (const c of webhooksContract) test(c.name, () => c.run(webhooks(standIn({ fetch: receiver.fetch })), receiver.posted))
10
+ */
11
+ const CONTRACT_RECEIVER = "https://hooks.example.com/contract";
12
+ const CONTRACT_FAILING = "https://hooks.example.com/failing";
13
+ /** A customer of the case's own, so the cases share nothing when run against one project. */
14
+ const someone = () => `cus_${crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(1))[0].toString(36)}`;
15
+ const webhooksContract = [
16
+ {
17
+ name: "a message to a customer with no endpoint is kept, sent nowhere, and its type is listed",
18
+ async run(webhooks, posted) {
19
+ const customer = someone();
20
+ const before = posted().length;
21
+ const sent = await webhooks.send({
22
+ customer,
23
+ type: "invoice.created",
24
+ data: { total: 40 }
25
+ });
26
+ equal(sent.endpoints, 0, "the endpoints it went to");
27
+ equal(posted().length, before, "what was posted");
28
+ equal((await webhooks.messages.list({ customer })).map((message) => message.id), [sent.id], "the customer's messages");
29
+ equal((await webhooks.types()).some((type) => type.type === "invoice.created"), true, "whether invoice.created is listed");
30
+ }
31
+ },
32
+ {
33
+ name: "an endpoint gets the types it names, signed with its own secret so a receiver's check passes",
34
+ async run(webhooks, posted) {
35
+ const customer = someone();
36
+ const { endpoint, secret } = await webhooks.endpoints.create({
37
+ customer,
38
+ url: CONTRACT_RECEIVER,
39
+ types: ["order.paid"]
40
+ });
41
+ equal(secret.startsWith("whsec_"), true, "whether the secret starts whsec_");
42
+ const before = posted().length;
43
+ await webhooks.send({
44
+ customer,
45
+ type: "order.refunded",
46
+ data: { order: 1 }
47
+ });
48
+ const sent = await webhooks.send({
49
+ customer,
50
+ type: "order.paid",
51
+ data: { order: 2 }
52
+ });
53
+ equal(sent.endpoints, 1, "the endpoints order.paid went to");
54
+ const delivery = await eventually(async () => (await webhooks.deliveries.list({ endpoint: endpoint.id })).find((one) => one.messageId === sent.id && one.status === "delivered"));
55
+ const arrived = posted().slice(before).find((one) => one.headers["webhook-id"] === delivery.id);
56
+ if (!arrived) throw new Error("order.paid never reached the receiver");
57
+ equal(JSON.parse(arrived.body).type, "order.paid", "the type it carried");
58
+ equal(await verifyWebhook(arrived.headers, arrived.body, secret), true, "whether the receiver's check passes");
59
+ equal(posted().slice(before).some((one) => JSON.parse(one.body).type === "order.refunded"), false, "whether order.refunded was sent");
60
+ }
61
+ },
62
+ {
63
+ name: "the same key sends once, and returns the first message whatever its data",
64
+ async run(webhooks) {
65
+ const customer = someone();
66
+ await webhooks.endpoints.create({
67
+ customer,
68
+ url: CONTRACT_RECEIVER
69
+ });
70
+ const key = `contract-${customer}`;
71
+ const first = await webhooks.send({
72
+ customer,
73
+ type: "order.paid",
74
+ data: { order: 1 },
75
+ key
76
+ });
77
+ const again = await webhooks.send({
78
+ customer,
79
+ type: "order.paid",
80
+ data: { order: 2 },
81
+ key
82
+ });
83
+ equal(again.id, first.id, "the repeat's message");
84
+ equal(again.data, { order: 1 }, "the repeat's data");
85
+ equal((await webhooks.messages.list({ customer })).length, 1, "how many messages were kept");
86
+ }
87
+ },
88
+ {
89
+ name: "a failed delivery keeps its try, and replayed to an address that takes it is delivered under the same id",
90
+ async run(webhooks) {
91
+ const customer = someone();
92
+ const { endpoint } = await webhooks.endpoints.create({
93
+ customer,
94
+ url: CONTRACT_FAILING
95
+ });
96
+ const sent = await webhooks.send({
97
+ customer,
98
+ type: "order.paid",
99
+ data: {}
100
+ });
101
+ const tried = await eventually(async () => (await webhooks.deliveries.list({ endpoint: endpoint.id })).find((one) => one.messageId === sent.id && one.attempts >= 1 && one.lastStatus !== void 0));
102
+ equal(tried.lastStatus, 500, "the first try's status");
103
+ equal((await webhooks.deliveries.show(tried.id)).tries[0]?.status, 500, "the try kept");
104
+ await webhooks.endpoints.edit(endpoint.id, { url: CONTRACT_RECEIVER });
105
+ await webhooks.deliveries.replay(tried.id);
106
+ equal((await eventually(async () => {
107
+ const shown = await webhooks.deliveries.show(tried.id);
108
+ return shown.status === "delivered" ? shown : void 0;
109
+ })).id, tried.id, "the replayed delivery's id");
110
+ }
111
+ },
112
+ {
113
+ name: "a customer, a type or a message that isn't one is refused before anything is sent",
114
+ async run(webhooks, posted) {
115
+ const before = posted().length;
116
+ await refused(() => webhooks.send({
117
+ customer: "not a customer",
118
+ type: "order.paid",
119
+ data: {}
120
+ }), "invalid");
121
+ await refused(() => webhooks.send({
122
+ customer: "cus_1",
123
+ type: "Order Paid",
124
+ data: {}
125
+ }), "invalid");
126
+ await refused(() => webhooks.send({
127
+ customer: "cus_1",
128
+ type: "order.paid",
129
+ data: "x".repeat(7e4)
130
+ }), "invalid");
131
+ await refused(() => webhooks.endpoints.create({
132
+ customer: "cus_1",
133
+ url: "http://hooks.example.com/plain"
134
+ }), "invalid");
135
+ await refused(() => webhooks.endpoints.show("wae_nobody"), "not-found");
136
+ equal(posted().length, before, "what was posted");
137
+ }
138
+ }
139
+ ];
140
+ /** Asks again at once and backs off, for an engine that delivers after its answer, as the platform does. */
141
+ async function eventually(look, ms = 3e4) {
142
+ const until = Date.now() + ms;
143
+ for (let wait = 10;; wait = Math.min(wait * 2, 1e3)) {
144
+ const found = await look();
145
+ if (found !== void 0) return found;
146
+ if (Date.now() > until) throw new Error("it never happened");
147
+ await new Promise((resolve) => setTimeout(resolve, wait));
148
+ }
149
+ }
150
+ async function refused(call, code) {
151
+ try {
152
+ await call();
153
+ } catch (error) {
154
+ if (error instanceof WebhooksError && error.code === code) return;
155
+ throw new Error(`expected a ${code} refusal, got ${error instanceof Error ? error.message : String(error)}`);
156
+ }
157
+ throw new Error(`expected a ${code} refusal, and it went through`);
158
+ }
159
+ function equal(actual, expected, what) {
160
+ if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error(`${what}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
161
+ }
162
+ //#endregion
163
+ export { CONTRACT_FAILING, CONTRACT_RECEIVER, webhooksContract };
@@ -0,0 +1,224 @@
1
+ //#region src/webhooks/index.d.ts
2
+ type WebhooksErrorCode = "invalid" | "not-found" | "forbidden" | "held" | "unavailable";
3
+ declare class WebhooksError extends Error {
4
+ readonly code: WebhooksErrorCode;
5
+ constructor(code: WebhooksErrorCode, message: string);
6
+ }
7
+ /** Which endpoints: production's, or the ones every preview of the project shares. */
8
+ type WebhooksEnvironment = "production" | "preview";
9
+ /** An endpoint one of your customers added. */
10
+ interface Endpoint {
11
+ readonly id: string;
12
+ readonly environment: WebhooksEnvironment;
13
+ readonly customer: string;
14
+ readonly url: string;
15
+ readonly description?: string;
16
+ /** The types it gets; every type when left out. */
17
+ readonly types?: ReadonlyArray<string>;
18
+ readonly enabled: boolean;
19
+ /** Why it is off: turned off by someone, failing 5 deliveries in a row, or its address returning 410 Gone. */
20
+ readonly disabled?: "by-request" | "failing" | "gone";
21
+ readonly failing: number;
22
+ readonly createdAt: number;
23
+ readonly secretAt: number;
24
+ }
25
+ /** One message to one endpoint: the same `id`, its `webhook-id`, on every try. */
26
+ interface Delivery {
27
+ readonly id: string;
28
+ readonly endpointId: string;
29
+ readonly messageId: string;
30
+ readonly customer: string;
31
+ readonly type: string;
32
+ readonly status: "pending" | "delivered" | "failed";
33
+ readonly attempts: number;
34
+ readonly nextAt?: number;
35
+ readonly lastAttemptAt?: number;
36
+ readonly lastStatus?: number;
37
+ readonly lastError?: string;
38
+ readonly createdAt: number;
39
+ readonly deliveredAt?: number;
40
+ }
41
+ /** One POST of a delivery: when, how long, the status and the start of what came back, or why nothing did. */
42
+ interface Try {
43
+ readonly at: number;
44
+ readonly ms: number;
45
+ readonly attempt: number;
46
+ readonly status?: number;
47
+ readonly body?: string;
48
+ readonly error?: string;
49
+ }
50
+ /** One message your app sent one customer, and how many endpoints it went to. */
51
+ interface Message {
52
+ readonly id: string;
53
+ readonly environment: WebhooksEnvironment;
54
+ readonly customer: string;
55
+ readonly type: string;
56
+ readonly key?: string;
57
+ readonly data: unknown;
58
+ readonly createdAt: number;
59
+ readonly endpoints: number;
60
+ }
61
+ /** A type your app has sent, with the data of its first message as an example. */
62
+ interface EventType {
63
+ readonly type: string;
64
+ readonly firstAt: number;
65
+ readonly example: unknown;
66
+ readonly exampleCut?: true;
67
+ }
68
+ interface OutgoingMessage {
69
+ /** Your app's own id for the customer, such as `cus_42`. */
70
+ readonly customer: string;
71
+ /** A `noun.verb` name in lower case, such as `order.paid`. */
72
+ readonly type: string;
73
+ /** What the message carries, as JSON; at most 64 KB with its type. */
74
+ readonly data: unknown;
75
+ /** Sent again within 30 days, the first message is returned and nothing is sent again. */
76
+ readonly key?: string;
77
+ }
78
+ /** The calls an engine takes, by the Actions' own words. */
79
+ type WebhooksOp = "send" | "message.list" | "message.show" | "type.list" | "endpoint.create" | "endpoint.list" | "endpoint.show" | "endpoint.edit" | "endpoint.rotate" | "endpoint.delete" | "endpoint.test" | "endpoint.replay" | "delivery.list" | "delivery.show" | "delivery.replay";
80
+ /** Where webhooks' calls go: the Seam under `webhooks`. A deployment's handle, the API with a token, and the Stand-in are its Adapters. */
81
+ interface WebhooksEngine {
82
+ call(op: WebhooksOp, input: Readonly<Record<string, unknown>>): Promise<unknown>;
83
+ }
84
+ interface Webhooks {
85
+ /** Sends a message to one customer's endpoints that take its type, and returns it, with how many endpoints it went to. */
86
+ send(message: OutgoingMessage): Promise<Message>;
87
+ readonly endpoints: {
88
+ /** Adds an endpoint for a customer and returns its secret, shown this once, and the types it names that were never sent. */
89
+ create(input: {
90
+ readonly customer: string;
91
+ readonly url: string;
92
+ readonly types?: ReadonlyArray<string>;
93
+ readonly description?: string;
94
+ readonly key?: string;
95
+ }): Promise<{
96
+ readonly endpoint: Endpoint;
97
+ readonly secret: string;
98
+ readonly unsent: ReadonlyArray<string>;
99
+ }>;
100
+ /** The newest first, or one customer's, each with its latest delivery. */
101
+ list(options?: {
102
+ readonly customer?: string;
103
+ readonly limit?: number;
104
+ readonly before?: string;
105
+ }): Promise<ReadonlyArray<Endpoint & {
106
+ readonly latestDelivery?: Delivery;
107
+ }>>;
108
+ show(id: string): Promise<Endpoint>;
109
+ /** Changes it; `types: null` gets it every type, `enabled` turns it off or on. */
110
+ edit(id: string, change: {
111
+ readonly url?: string;
112
+ readonly types?: ReadonlyArray<string> | null;
113
+ readonly description?: string | null;
114
+ readonly enabled?: boolean;
115
+ }): Promise<Endpoint>;
116
+ /** A new secret, shown once; the one before also signs for a day. */
117
+ rotate(id: string): Promise<{
118
+ readonly endpoint: Endpoint;
119
+ readonly secret: string;
120
+ }>;
121
+ remove(id: string): Promise<void>;
122
+ /** Sends it a `webhook.ping` now, once, and returns how it went. */
123
+ test(id: string, options?: {
124
+ readonly key?: string;
125
+ }): Promise<Delivery>;
126
+ /** Sends it again everything of its customer's since `since` that it takes and didn't get, up to 500 messages a call. */
127
+ replay(id: string, options: {
128
+ readonly since: number | Date;
129
+ }): Promise<{
130
+ readonly replayed: number;
131
+ readonly checked: number;
132
+ readonly more: boolean;
133
+ readonly next?: number;
134
+ }>;
135
+ };
136
+ readonly messages: {
137
+ list(options?: {
138
+ readonly customer?: string;
139
+ readonly limit?: number;
140
+ readonly before?: string;
141
+ }): Promise<ReadonlyArray<Message>>;
142
+ show(id: string): Promise<Message & {
143
+ readonly deliveries: ReadonlyArray<Delivery>;
144
+ }>;
145
+ };
146
+ readonly deliveries: {
147
+ /** The newest first: an endpoint's, a customer's or all of them, in one state when asked. */
148
+ list(options?: {
149
+ readonly endpoint?: string;
150
+ readonly customer?: string;
151
+ readonly status?: Delivery["status"];
152
+ readonly limit?: number;
153
+ }): Promise<ReadonlyArray<Delivery>>;
154
+ /** With every try of it, the newest first. */
155
+ show(id: string): Promise<Delivery & {
156
+ readonly tries: ReadonlyArray<Try>;
157
+ }>;
158
+ /** Sends it again from its first try, under the same id. */
159
+ replay(id: string): Promise<Delivery>;
160
+ };
161
+ /** The types your app has sent, each with an example. */
162
+ types(): Promise<ReadonlyArray<EventType>>;
163
+ }
164
+ /** At most this many bytes a message's type and data, as JSON. */
165
+ declare const MAX_MESSAGE_BYTES: number;
166
+ /**
167
+ * A call checked as every engine takes it, the same on the caller's side and the platform's: throws
168
+ * `WebhooksError("invalid")` saying what is wrong.
169
+ */
170
+ declare function checkCall(op: WebhooksOp, given: Readonly<Record<string, unknown>>): Readonly<Record<string, unknown>>;
171
+ /** Webhooks over `engine`, each call checked before it leaves. */
172
+ declare function webhooksOver(engine: WebhooksEngine): Webhooks;
173
+ /**
174
+ * Webhooks: `webhooks.send(…)` in a deployment, or `webhooks(engine).send(…)` over an engine you give: `client(…)`
175
+ * outside one, or the Stand-in in tests.
176
+ */
177
+ declare const webhooks: Webhooks & ((engine?: WebhooksEngine) => Webhooks);
178
+ /**
179
+ * Webhooks through Midsummer's API, for code outside a deployment: `project` is `<team>/<project>`, `token` a token
180
+ * whose person or agent may deploy it (`midsummer token create`). `environment` is production unless given; `api` the
181
+ * site's API, `MIDSUMMER_API` or the one this package was published for when left out.
182
+ *
183
+ * const hooks = webhooks(client({ project: "acme/shop", token: process.env.MIDSUMMER_TOKEN! }))
184
+ */
185
+ declare function client(options: {
186
+ readonly project: string;
187
+ readonly token: string;
188
+ readonly environment?: WebhooksEnvironment;
189
+ readonly api?: string;
190
+ readonly fetch?: typeof fetch;
191
+ }): WebhooksEngine;
192
+ /** What a bound webhooks handle returns: the value asked for, or the refusal, which crosses a Service Binding as data. */
193
+ type BoundWebhooksAnswer = {
194
+ readonly value: unknown;
195
+ } | {
196
+ readonly error: {
197
+ readonly code: WebhooksErrorCode;
198
+ readonly message: string;
199
+ };
200
+ };
201
+ /** What Midsummer hands a deployment as `context.webhooks`: each call carries its op, and the platform knows the project and environment. */
202
+ declare function boundWebhooks(handle: {
203
+ call(op: string, input: unknown): Promise<BoundWebhooksAnswer>;
204
+ }): WebhooksEngine;
205
+ /**
206
+ * The platform's side of a bound handle: checks each call again, as it comes from another Worker's code, and hands it
207
+ * to `engine`, the deployment's project's webhooks. A refusal is returned as data.
208
+ */
209
+ declare function serveWebhooks(engine: () => Promise<WebhooksEngine>): (op: unknown, input: unknown) => Promise<BoundWebhooksAnswer>;
210
+ /**
211
+ * Whether a delivery your app sent is genuine: signed as Standard Webhooks says with the endpoint's secret
212
+ * (`whsec_…`, shown when it was added or rotated). Give the request's headers (`webhook-id`, `webhook-timestamp`,
213
+ * `webhook-signature`) and the body exactly as it arrived, before any parsing. One older than five minutes, or ahead
214
+ * of the clock by as much, is refused. After a rotation both secrets sign for a day, and either passing is enough.
215
+ * Deliveries are at least once: drop a repeat by its `webhook-id`.
216
+ *
217
+ * const body = await request.text()
218
+ * if (!(await verifyWebhook(request.headers, body, process.env.WEBHOOK_SECRET!))) return new Response(null, { status: 401 })
219
+ */
220
+ declare function verifyWebhook(headers: Headers | Readonly<Record<string, string | undefined>>, body: string, secret: string, options?: {
221
+ readonly now?: number;
222
+ }): Promise<boolean>;
223
+ //#endregion
224
+ export { BoundWebhooksAnswer, Delivery, Endpoint, EventType, MAX_MESSAGE_BYTES, Message, OutgoingMessage, Try, Webhooks, WebhooksEngine, WebhooksEnvironment, WebhooksError, WebhooksErrorCode, WebhooksOp, boundWebhooks, checkCall, client, serveWebhooks, verifyWebhook, webhooks, webhooksOver };