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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/auth-B7rCtXFQ.d.mts +36 -0
  2. package/{build-DQo-JrlN.d.mts → build-BhmOZmGQ.d.mts} +2 -27
  3. package/client.mjs +1 -1
  4. package/contract.mjs +2 -2
  5. package/database/build.d.mts +1 -1
  6. package/database/build.mjs +35 -2
  7. package/database/server.mjs +1 -1
  8. package/database/stand-in.d.mts +2 -1
  9. package/database/stand-in.mjs +2 -2
  10. package/email/client.d.mts +5 -4
  11. package/email/client.mjs +1 -1
  12. package/email/contract.d.mts +3 -1
  13. package/email/contract.mjs +111 -4
  14. package/email/index.d.mts +85 -16
  15. package/email/index.mjs +2 -2
  16. package/email/smtp.mjs +24 -8
  17. package/email/stand-in.d.mts +3 -0
  18. package/email/stand-in.mjs +17 -7
  19. package/email-IH5OllU2.mjs +337 -0
  20. package/errors-B1tO_wdm.mjs +28 -0
  21. package/flows/contract.d.mts +13 -0
  22. package/flows/contract.mjs +483 -0
  23. package/flows/index.d.mts +148 -0
  24. package/flows/index.mjs +347 -0
  25. package/index.mjs +2 -2
  26. package/{names-DfCBKupJ.mjs → names-Do0ot5Ha.mjs} +2 -28
  27. package/package.json +29 -1
  28. package/queues/contract.mjs +144 -1
  29. package/queues/index.d.mts +149 -5
  30. package/queues/index.mjs +56 -12
  31. package/queues/stand-in.mjs +333 -31
  32. package/queues/wire.mjs +302 -16
  33. package/s3.mjs +3 -2
  34. package/{server-EDRbF2u-.mjs → server-Drjni3-F.mjs} +4 -2
  35. package/socket.mjs +1 -1
  36. package/{src-BKrQAqJN.mjs → src-CkP59_Qu.mjs} +2 -1
  37. package/stand-in.mjs +2 -1
  38. package/storage/contract.d.mts +25 -0
  39. package/storage/contract.mjs +153 -0
  40. package/storage/files.d.mts +144 -0
  41. package/storage/files.mjs +513 -0
  42. package/wire.mjs +2 -1
  43. package/email-DXtpr7pT.mjs +0 -214
@@ -0,0 +1,36 @@
1
+ //#region src/database/auth.d.ts
2
+ /** A value as `db/auth.config.ts` writes it: a string, or an environment variable read where the Database runs. */
3
+ type Configured = string | {
4
+ readonly env: string;
5
+ };
6
+ type Algorithm = "RS256" | "ES256";
7
+ /** An OIDC issuer, found by discovery: `domain` is its `iss`, `applicationID` the audience its tokens name. */
8
+ interface OidcProvider {
9
+ readonly domain: Configured;
10
+ readonly applicationID: Configured;
11
+ }
12
+ /** An issuer of JWTs that publishes no discovery document: its key set is `jwks`, an https address or a `data:` URI. */
13
+ interface JwtProvider {
14
+ readonly type: "customJwt";
15
+ readonly issuer: Configured;
16
+ readonly jwks: Configured;
17
+ readonly algorithm: Algorithm;
18
+ readonly applicationID?: Configured;
19
+ }
20
+ type AuthProvider = OidcProvider | JwtProvider;
21
+ /** `db/auth.config.ts`, as the build reads it. */
22
+ interface AuthConfig {
23
+ readonly providers: ReadonlyArray<AuthProvider>;
24
+ readonly anonymous: boolean;
25
+ }
26
+ /**
27
+ * What `verifier` reaches out with: `fetch` for key sets and discovery (the global one when left out), `resolve`
28
+ * for the addresses a host has (this machine's resolver when left out), and `now` in ms.
29
+ */
30
+ interface VerifierOptions {
31
+ readonly fetch?: (url: string, init: RequestInit) => Promise<Response>;
32
+ readonly resolve?: (host: string) => Promise<ReadonlyArray<string>>;
33
+ readonly now?: () => number;
34
+ }
35
+ //#endregion
36
+ export { AuthProvider as n, VerifierOptions as r, AuthConfig as t };
@@ -1,31 +1,6 @@
1
+ import { t as AuthConfig } from "./auth-B7rCtXFQ.mjs";
1
2
  import { $ as VectorIndex, J as IndexDeclaration, X as SearchIndex, Z as Shape, n as CronJob } from "./server-B5HK2Ou9.mjs";
2
3
  import { Node } from "acorn";
3
- //#region src/database/auth.d.ts
4
- /** A value as `db/auth.config.ts` writes it: a string, or an environment variable read where the Database runs. */
5
- type Configured = string | {
6
- readonly env: string;
7
- };
8
- type Algorithm = "RS256" | "ES256";
9
- /** An OIDC issuer, found by discovery: `domain` is its `iss`, `applicationID` the audience its tokens name. */
10
- interface OidcProvider {
11
- readonly domain: Configured;
12
- readonly applicationID: Configured;
13
- }
14
- /** An issuer of JWTs that publishes no discovery document: its key set is `jwks`, an https address or a `data:` URI. */
15
- interface JwtProvider {
16
- readonly type: "customJwt";
17
- readonly issuer: Configured;
18
- readonly jwks: Configured;
19
- readonly algorithm: Algorithm;
20
- readonly applicationID?: Configured;
21
- }
22
- type AuthProvider = OidcProvider | JwtProvider;
23
- /** `db/auth.config.ts`, as the build reads it. */
24
- interface AuthConfig {
25
- readonly providers: ReadonlyArray<AuthProvider>;
26
- readonly anonymous: boolean;
27
- }
28
- //#endregion
29
4
  //#region src/database/build.d.ts
30
5
  /** A file the Database would refuse; the message gives the file, and the line when there is one. */
31
6
  declare class Refused extends Error {
@@ -117,4 +92,4 @@ declare function buildDatabase(sources: Readonly<Record<string, string>>, strip:
117
92
  /** A shape as a TypeScript type. */
118
93
  declare function typeOf(shape: Shape | null | undefined): string;
119
94
  //#endregion
120
- export { MODULE_BYTES as a, blockNames as c, exported as d, isSource as f, AuthConfig as h, BuiltFunction as i, buildDatabase as l, unboundCalls as m, BUILD_FILES as n, Packages as o, typeOf as p, Built as r, Refused as s, BUILD_BYTES as t, enumAsObject as u };
95
+ export { MODULE_BYTES as a, blockNames as c, exported as d, isSource as f, BuiltFunction as i, buildDatabase as l, unboundCalls as m, BUILD_FILES as n, Packages as o, typeOf as p, Built as r, Refused as s, BUILD_BYTES as t, enumAsObject as u };
package/client.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { a as SOCKET_PATH, c as signedHttp, i as FRAMES_PATH, o as client, s as serveSigned } from "./src-BKrQAqJN.mjs";
1
+ import { a as SOCKET_PATH, c as signedHttp, i as FRAMES_PATH, o as client, s as serveSigned } from "./src-CkP59_Qu.mjs";
2
2
  export { FRAMES_PATH, SOCKET_PATH, client, serveSigned, signedHttp };
package/contract.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { h as StorageError } from "./names-DfCBKupJ.mjs";
2
- import "./src-BKrQAqJN.mjs";
1
+ import { t as StorageError } from "./errors-B1tO_wdm.mjs";
2
+ import "./src-CkP59_Qu.mjs";
3
3
  //#region src/contract.ts
4
4
  /**
5
5
  * Storage's contract: what every engine promises, as cases any test runner can run. The Stand-in
@@ -1,2 +1,2 @@
1
- import { a as MODULE_BYTES, c as blockNames, d as exported, f as isSource, i as BuiltFunction, l as buildDatabase, m as unboundCalls, n as BUILD_FILES, o as Packages, p as typeOf, r as Built, s as Refused, t as BUILD_BYTES, u as enumAsObject } from "../build-DQo-JrlN.mjs";
1
+ import { a as MODULE_BYTES, c as blockNames, d as exported, f as isSource, i as BuiltFunction, l as buildDatabase, m as unboundCalls, n as BUILD_FILES, o as Packages, p as typeOf, r as Built, s as Refused, t as BUILD_BYTES, u as enumAsObject } from "../build-BhmOZmGQ.mjs";
2
2
  export { BUILD_BYTES, BUILD_FILES, Built, BuiltFunction, MODULE_BYTES, Packages, Refused, blockNames, buildDatabase, enumAsObject, exported, isSource, typeOf, unboundCalls };
@@ -1,5 +1,5 @@
1
1
  import { f as indexFields, h as orderable, l as defineSchema, u as defineTable, y as v } from "../bytes-C2pcyl9u.mjs";
2
- import { E as scheduleOf } from "../server-EDRbF2u-.mjs";
2
+ import { E as scheduleOf } from "../server-Drjni3-F.mjs";
3
3
  import { t as authConfigOf } from "../auth-1W-SzpD3.mjs";
4
4
  import { parse } from "acorn";
5
5
  //#region src/database/build.ts
@@ -1017,6 +1017,37 @@ function inspect(file, path, text, built) {
1017
1017
  return tree;
1018
1018
  }
1019
1019
  /**
1020
+ * Every test of `ctx.auth` itself for truth or null in a module: `!ctx.auth`, `if (ctx.auth)`, `ctx.auth && …`,
1021
+ * `ctx.auth == null` and the like, where `ctx` is a function's context (a handler's first parameter, or any
1022
+ * name `ctx`) and `auth` may be taken out of it (`({ auth }) => !auth`). `ctx.auth` is there for every caller,
1023
+ * so each such test passes everyone, signed in or not; the build refuses it. Tests of what it holds, such as
1024
+ * `!ctx.auth.subject` or `await ctx.auth.getUserIdentity()`, are not found.
1025
+ */
1026
+ function authTests(tree) {
1027
+ const contexts = /* @__PURE__ */ new Set(["ctx"]), auths = /* @__PURE__ */ new Set();
1028
+ const isFunction = (node) => /^(FunctionExpression|ArrowFunctionExpression)$/u.test(node?.type ?? "");
1029
+ for (const node of nodes(tree)) {
1030
+ const first = (node.type === "Property" && !node.computed && (node.key.name ?? node.key.value) === "handler" && isFunction(node.value) ? node.value : node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "httpAction" && isFunction(node.arguments[0]) ? node.arguments[0] : null)?.params[0];
1031
+ if (first?.type === "Identifier") contexts.add(first.name);
1032
+ if (first?.type === "ObjectPattern") {
1033
+ for (const p of first.properties) if (p.type === "Property" && !p.computed && (p.key.name ?? p.key.value) === "auth" && p.value.type === "Identifier") auths.add(p.value.name);
1034
+ }
1035
+ }
1036
+ const isAuth = (node) => !!node && (node.type === "MemberExpression" && !node.computed && !node.optional && node.property.name === "auth" && node.object.type === "Identifier" && contexts.has(node.object.name) || node.type === "Identifier" && auths.has(node.name));
1037
+ const isNothing = (node) => node.type === "Literal" && node.value === null && node.raw === "null" || node.type === "Identifier" && node.name === "undefined" || node.type === "UnaryExpression" && node.operator === "void";
1038
+ const found = [];
1039
+ for (const node of nodes(tree)) if (node.type === "UnaryExpression" && node.operator === "!" && isAuth(node.argument)) found.push(node);
1040
+ else if (/^(IfStatement|ConditionalExpression|WhileStatement|DoWhileStatement|ForStatement)$/u.test(node.type) && isAuth(node.test)) found.push(node.test);
1041
+ else if (node.type === "LogicalExpression" && isAuth(node.left)) found.push(node);
1042
+ else if (node.type === "BinaryExpression" && [
1043
+ "==",
1044
+ "!=",
1045
+ "===",
1046
+ "!=="
1047
+ ].includes(node.operator) && (isAuth(node.left) && isNothing(node.right) || isAuth(node.right) && isNothing(node.left))) found.push(node);
1048
+ return found.sort((a, b) => a.start - b.start);
1049
+ }
1050
+ /**
1020
1051
  * A file's functions, as top-level exports; the HTTP actions written as a route's `handler`; and the
1021
1052
  * count of definer calls anywhere (each must be one of them).
1022
1053
  */
@@ -1327,6 +1358,8 @@ function buildDatabase(sources, strip, options = {}) {
1327
1358
  const author = from[file];
1328
1359
  const tree = inspect(author, file, files[file], files);
1329
1360
  if (file.startsWith("node_modules/") && !file.startsWith(`${PROJECT}/`)) continue;
1361
+ const unsafe = authTests(tree)[0];
1362
+ if (unsafe) throw new Refused(`${author}${unsafe.loc ? `:${unsafe.loc.start.line}` : ""}: \`${files[file].slice(unsafe.start, unsafe.end)}\` checks nobody: \`ctx.auth\` is there for every caller, signed in or not. Check the caller instead: \`const user = await ctx.auth.getUserIdentity()\`, then \`if (!user)\`.`);
1330
1363
  const { defs, calls, routed } = definersOf(tree, file.replace(/\.mjs$/u, "").replaceAll("/", "."));
1331
1364
  if (file.startsWith(`${PROJECT}/`)) {
1332
1365
  if (calls) throw new Refused(`${author}: a function is defined in db/, never in a file outside it`);
@@ -1735,7 +1768,7 @@ export interface UserIdentity {
1735
1768
  readonly address?: string; readonly updatedAt?: string;
1736
1769
  readonly [claim: string]: unknown;
1737
1770
  }
1738
- /** The caller: \`getUserIdentity()\` gives the signed-in caller, or null for none; \`subject\` and \`issuer\` are a signed-in caller's. */
1771
+ /** The caller. \`ctx.auth\` is there for every caller, signed in or not, so check \`await getUserIdentity()\`: the signed-in caller, or null for none. \`subject\` and \`issuer\` are a signed-in caller's, and undefined for anyone else. */
1739
1772
  export interface Auth { getUserIdentity(): Promise<UserIdentity | null>; readonly subject?: string; readonly issuer?: string | null }
1740
1773
  export interface Scheduler {
1741
1774
  runAfter<F extends FunctionReference<"mutation" | "action">>(ms: number, fn: F, args: ArgsOf<F>): string;
@@ -1,3 +1,3 @@
1
1
  import { _ as shapeError, f as indexFields, l as defineSchema, m as isIdForm, s as ID_FORM, u as defineTable, v as tableCode, y as v } from "../bytes-C2pcyl9u.mjs";
2
- import { C as paginationOptsValidator, D as take, E as scheduleOf, S as nextCron, T as readLimited, _ as isFunction, a as Refusal, b as limits, c as cronJobs, d as httpAction, f as httpRouter, g as internalQuery, h as internalMutation, i as NotFoundError, l as fetchOver, m as internalAction, n as HttpRouter, o as TooLarge, p as increment, r as InsufficientError, s as action, t as Crons, u as give, v as isIdOf, w as query, x as mutation, y as isRouter } from "../server-EDRbF2u-.mjs";
2
+ import { C as paginationOptsValidator, D as take, E as scheduleOf, S as nextCron, T as readLimited, _ as isFunction, a as Refusal, b as limits, c as cronJobs, d as httpAction, f as httpRouter, g as internalQuery, h as internalMutation, i as NotFoundError, l as fetchOver, m as internalAction, n as HttpRouter, o as TooLarge, p as increment, r as InsufficientError, s as action, t as Crons, u as give, v as isIdOf, w as query, x as mutation, y as isRouter } from "../server-Drjni3-F.mjs";
3
3
  export { Crons, HttpRouter, ID_FORM, InsufficientError, NotFoundError, Refusal, TooLarge, action, cronJobs, defineSchema, defineTable, fetchOver, give, httpAction, httpRouter, increment, indexFields, internalAction, internalMutation, internalQuery, isFunction, isIdForm, isIdOf, isRouter, limits, mutation, nextCron, paginationOptsValidator, query, readLimited, scheduleOf, shapeError, tableCode, take, v };
@@ -1,6 +1,7 @@
1
1
  import { p as Storage } from "../index-Ci6mGXqz.mjs";
2
- import { h as AuthConfig, r as Built } from "../build-DQo-JrlN.mjs";
2
+ import { t as AuthConfig } from "../auth-B7rCtXFQ.mjs";
3
3
  import { a as FileMetadata, c as FunctionReference, d as HttpRouter, n as CronJob, s as FunctionKind, v as RegisteredFunction, y as Row } from "../server-B5HK2Ou9.mjs";
4
+ import { r as Built } from "../build-BhmOZmGQ.mjs";
4
5
  import { t as DatabaseError } from "../errors-x2vXKi0u.mjs";
5
6
  import { A as VectorControl, M as VectorEngine } from "../index-B9zs0wIp.mjs";
6
7
  //#region src/database/stand-in.d.ts
@@ -1,7 +1,7 @@
1
- import { n as storage } from "../src-BKrQAqJN.mjs";
1
+ import { n as storage } from "../src-CkP59_Qu.mjs";
2
2
  import { standIn } from "../stand-in.mjs";
3
3
  import { _ as shapeError, a as tagBytes, b as valueAt, f as indexFields, g as shapeAt, i as keyBytes, o as untagBytes, v as tableCode } from "../bytes-C2pcyl9u.mjs";
4
- import { A as comparePrefix, M as indexTuple, O as valueKey, S as nextCron, T as readLimited, _ as isFunction, a as Refusal, b as limits, i as NotFoundError, j as documentBytes, k as compareKey, l as fetchOver, o as TooLarge, r as InsufficientError, y as isRouter } from "../server-EDRbF2u-.mjs";
4
+ import { A as comparePrefix, M as indexTuple, O as valueKey, S as nextCron, T as readLimited, _ as isFunction, a as Refusal, b as limits, i as NotFoundError, j as documentBytes, k as compareKey, l as fetchOver, o as TooLarge, r as InsufficientError, y as isRouter } from "../server-Drjni3-F.mjs";
5
5
  import { DatabaseError } from "./errors.mjs";
6
6
  import { i as verifier, n as sessionEnd, r as trustedOf } from "../auth-1W-SzpD3.mjs";
7
7
  import { standIn as standIn$1 } from "../vector/stand-in.mjs";
@@ -1,4 +1,4 @@
1
- import { CheckedMessage, EmailEngine, EmailErrorCode, SentMessage } from "./index.mjs";
1
+ import { BatchResult, CheckedMessage, EmailEngine, EmailErrorCode, SentMessage } from "./index.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>;
@@ -9,9 +9,10 @@ declare function client(origin: string, options: {
9
9
  }): EmailEngine;
10
10
  /**
11
11
  * The platform's side of the wire: checks the request again, as it comes from the network, and hands
12
- * the key and the Message to `send`, which throws an `EmailError` for a refusal.
12
+ * the key and the Message to `send`, or the key and a batch's Messages to `batch`, which throw an
13
+ * `EmailError` for a refusal of the whole; a batch returns each Message's own refusal in its list.
13
14
  */
14
- declare function serveMessages(send: (key: string, message: CheckedMessage) => Promise<SentMessage>): (request: Request) => Promise<Response>;
15
+ declare function serveMessages(send: (key: string, message: CheckedMessage) => Promise<SentMessage>, batch?: (key: string, messages: ReadonlyArray<CheckedMessage>) => Promise<ReadonlyArray<BatchResult>>): (request: Request) => Promise<Response>;
15
16
  /** What a bound Email handle returns: the Message as sent, or the refusal, which crosses a Service Binding as data. */
16
17
  type BoundAnswer = SentMessage | {
17
18
  readonly error: {
@@ -21,7 +22,7 @@ type BoundAnswer = SentMessage | {
21
22
  };
22
23
  /**
23
24
  * What Midsummer hands a Deployment as `context.email`: sends from the Sending domains its
24
- * Environment binds, with no key.
25
+ * Environment binds, with no key. A batch goes one Message at a time over it.
25
26
  *
26
27
  * await email(boundEmail(context.email)).send({ from: "Acme <hi@acme.dev>", to: ["ada@example.com"], subject: "Hi", text: "Hello" })
27
28
  */
package/email/client.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { c as client, l as serveBound, o as MESSAGES_PATH, s as boundEmail, u as serveMessages } from "../email-DXtpr7pT.mjs";
1
+ import { d as MESSAGES_PATH, f as boundEmail, h as serveMessages, m as serveBound, p as client } from "../email-IH5OllU2.mjs";
2
2
  export { MESSAGES_PATH, boundEmail, client, serveBound, serveMessages };
@@ -2,10 +2,12 @@ import { Email } from "./index.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";
5
+ /** The time an engine's clock reads while it runs the contract: noon, 27 October 2026, UTC. */
6
+ declare const CONTRACT_NOW: number;
5
7
  interface ContractCase {
6
8
  readonly name: string;
7
9
  run(email: Email): Promise<void>;
8
10
  }
9
11
  declare const emailContract: ReadonlyArray<ContractCase>;
10
12
  //#endregion
11
- export { CONTRACT_DOMAIN, CONTRACT_SUPPRESSED, ContractCase, emailContract };
13
+ export { CONTRACT_DOMAIN, CONTRACT_NOW, CONTRACT_SUPPRESSED, ContractCase, emailContract };
@@ -1,14 +1,17 @@
1
- import { t as EmailError } from "../email-DXtpr7pT.mjs";
1
+ import { t as EmailError } from "../email-IH5OllU2.mjs";
2
2
  //#region src/email/contract.ts
3
3
  /**
4
4
  * Email's contract: what every engine promises, as cases any test runner can run. The Stand-in runs
5
5
  * them in this package; the real Capability runs the same cases against a Project set up with the
6
- * fixture: `mail.acme.dev` a verified Sending domain, and `suppressed@example.com` suppressed.
6
+ * fixture: `mail.acme.dev` a verified Sending domain, and `suppressed@example.com` suppressed, its
7
+ * clock at `CONTRACT_NOW`.
7
8
  *
8
- * for (const c of emailContract) test(c.name, () => c.run(email(standIn({ domains: [CONTRACT_DOMAIN], suppressed: [CONTRACT_SUPPRESSED] }))))
9
+ * for (const c of emailContract) test(c.name, () => c.run(email(standIn({ domains: [CONTRACT_DOMAIN], suppressed: [CONTRACT_SUPPRESSED], clock: () => CONTRACT_NOW }))))
9
10
  */
10
11
  const CONTRACT_DOMAIN = "mail.acme.dev";
11
12
  const CONTRACT_SUPPRESSED = "suppressed@example.com";
13
+ /** The time an engine's clock reads while it runs the contract: noon, 27 October 2026, UTC. */
14
+ const CONTRACT_NOW = Date.UTC(2026, 9, 27, 12);
12
15
  const emailContract = [
13
16
  {
14
17
  name: "a Message from a verified Sending domain is sent, and the same key sends it once",
@@ -60,6 +63,110 @@ const emailContract = [
60
63
  })).state, "suppressed", "the state with nobody left");
61
64
  }
62
65
  },
66
+ {
67
+ name: "a Message carries files; one with a program or script, past twenty files or over 10 MB a file is refused as invalid before it is sent",
68
+ async run(email) {
69
+ const pdf = new TextEncoder().encode("%PDF-1.4\n%âã\n");
70
+ const base = {
71
+ from: "billing@mail.acme.dev",
72
+ to: "ada@example.com",
73
+ subject: "Your invoice",
74
+ text: "Attached."
75
+ };
76
+ equal((await email.send({
77
+ ...base,
78
+ attachments: [{
79
+ filename: "invoice.pdf",
80
+ content: pdf
81
+ }, {
82
+ filename: "logo.png",
83
+ content: "iVBORw0KGgo=",
84
+ contentId: "logo"
85
+ }],
86
+ key: "invoice-files"
87
+ })).state, "sent", "the state with files");
88
+ await refuses(() => email.send({
89
+ ...base,
90
+ attachments: [{
91
+ filename: "setup.exe",
92
+ content: pdf
93
+ }]
94
+ }), "invalid");
95
+ await refuses(() => email.send({
96
+ ...base,
97
+ attachments: Array.from({ length: 21 }, (_, index) => ({
98
+ filename: `page-${index}.pdf`,
99
+ content: pdf
100
+ }))
101
+ }), "invalid");
102
+ await refuses(() => email.send({
103
+ ...base,
104
+ attachments: [{
105
+ filename: "big.pdf",
106
+ content: /* @__PURE__ */ new Uint8Array(10485761)
107
+ }]
108
+ }), "invalid");
109
+ }
110
+ },
111
+ {
112
+ name: "a batch answers each Message on its own: one refused is answered with why, and the rest are sent",
113
+ async run(email) {
114
+ equal((await email.batch([
115
+ {
116
+ from: "hi@mail.acme.dev",
117
+ to: "ada@example.com",
118
+ subject: "One",
119
+ text: "Hello",
120
+ key: "batch-one"
121
+ },
122
+ {
123
+ from: "hi@acme.dev",
124
+ to: "ada@example.com",
125
+ subject: "Two",
126
+ text: "Hello",
127
+ key: "batch-two"
128
+ },
129
+ {
130
+ from: "hi@mail.acme.dev",
131
+ to: "grace@example.com",
132
+ subject: "Three",
133
+ text: "Hello",
134
+ key: "batch-three"
135
+ }
136
+ ])).map((result) => "message" in result ? result.message.state : result.error.code), [
137
+ "sent",
138
+ "unverified",
139
+ "sent"
140
+ ], "each result");
141
+ }
142
+ },
143
+ {
144
+ name: "a Message scheduled for later is queued until then, with when it is due",
145
+ async run(email) {
146
+ const at = CONTRACT_NOW + 36e5;
147
+ const later = await email.send({
148
+ from: "hi@mail.acme.dev",
149
+ to: "ada@example.com",
150
+ subject: "Reminder",
151
+ text: "Tomorrow",
152
+ sendAt: at,
153
+ key: "reminder-later"
154
+ });
155
+ equal([later.state, later.sendAt], ["queued", at], "the state and when it is due");
156
+ }
157
+ },
158
+ {
159
+ name: "a test Message is sent without a verified Sending domain, to no one",
160
+ async run(email) {
161
+ equal((await email.send({
162
+ from: "hi@not-yet-verified.dev",
163
+ to: "bounce@example.com",
164
+ subject: "Try",
165
+ text: "Hello",
166
+ test: true
167
+ })).state, "sent", "the test Message's state");
168
+ }
169
+ },
63
170
  {
64
171
  name: "a Message that is not one is refused as invalid before it is sent",
65
172
  async run(email) {
@@ -96,4 +203,4 @@ async function refuses(call, code) {
96
203
  throw new Error(`expected ${code}, but it was sent`);
97
204
  }
98
205
  //#endregion
99
- export { CONTRACT_DOMAIN, CONTRACT_SUPPRESSED, emailContract };
206
+ export { CONTRACT_DOMAIN, CONTRACT_NOW, CONTRACT_SUPPRESSED, emailContract };
package/email/index.d.mts CHANGED
@@ -5,25 +5,41 @@
5
5
  * import { email } from "@midsummer-ai/sdk/email"
6
6
  *
7
7
  * const sent = await email().send({ from: "Acme <hi@mail.acme.dev>", to: "ada@example.com", subject: "Welcome", text: "Hello", key: "welcome-ada" })
8
+ * await email().send({ from: "billing@mail.acme.dev", to: "ada@example.com", template: "invoice-paid", variables: { name: "Ada", total: "$40" },
9
+ * attachments: [{ filename: "invoice.pdf", content: pdfBytes }], key: "invoice-1043" })
10
+ * await email().batch(people.map((person) => ({ from: "news@mail.acme.dev", to: person.email, template: "digest", variables: { name: person.name },
11
+ * stream: "broadcast", topic: "digest", key: `digest-2026-11-${person.id}` })))
8
12
  *
9
13
  * With no engine, `email()` sends from a deployment, in any framework, with nothing to connect.
10
14
  * Otherwise `engine` is where Messages go: the Stand-in (`@midsummer-ai/sdk/email/stand-in`) in tests,
11
15
  * or code outside Midsummer with an email key (`email(client(origin, { key }))` from
12
16
  * `@midsummer-ai/sdk/email/client`). Every engine is held to the cases in `@midsummer-ai/sdk/email/contract`.
13
17
  *
14
- * Addresses and the Message's shape are checked here, before anything leaves the caller. Reuse a
15
- * Message's `key` to retry while the original Message is retained for thirty days. After that
18
+ * Addresses, files and the Message's shape are checked here, before anything leaves the caller. Reuse
19
+ * a Message's `key` to retry while the original Message is retained for thirty days. After that
16
20
  * Message is purged, the same key can send another Message. A suppressed recipient (one that bounced
17
- * or complained) is left out and named in `suppressed`; a Message with nobody left is `suppressed`.
18
- * Every failure is an `EmailError`, whose `code` tells you which kind.
21
+ * or complained, or left a broadcast's topic) is left out and named in `suppressed`; a Message with
22
+ * nobody left is `suppressed`. A Message with `sendAt` is `queued` until then. `test: true` sends to
23
+ * no one: each recipient's outcome is its address's (`bounce@…`, `soft-bounce@…`, `complaint@…`, else
24
+ * delivered), told to your webhooks as a real one would be. Every failure is an `EmailError`, whose
25
+ * `code` tells you which kind.
19
26
  *
20
- * Delivery events reach a Project's webhooks signed; `verifyWebhook` checks a delivery.
27
+ * Delivery events reach a Project's webhooks signed as Standard Webhooks says, as every webhook
28
+ * Midsummer sends is; `verifyWebhook` checks one with the endpoint's secret.
21
29
  */
22
30
  type EmailErrorCode = "invalid" | "unverified" | "forbidden" | "unavailable";
23
31
  declare class EmailError extends Error {
24
32
  readonly code: EmailErrorCode;
25
33
  constructor(code: EmailErrorCode, message: string);
26
34
  }
35
+ /** A file a Message carries: its bytes (or base64 of them), its name, and a content id to show it inline (`<img src="cid:logo">`). */
36
+ interface OutgoingAttachment {
37
+ readonly filename: string;
38
+ readonly content: Uint8Array | string;
39
+ /** From the name's extension when left out. */
40
+ readonly contentType?: string;
41
+ readonly contentId?: string;
42
+ }
27
43
  /** An address is `ada@example.com` or `Ada <ada@example.com>`. */
28
44
  interface OutgoingMessage {
29
45
  readonly from: string;
@@ -31,7 +47,8 @@ interface OutgoingMessage {
31
47
  readonly cc?: ReadonlyArray<string>;
32
48
  readonly bcc?: ReadonlyArray<string>;
33
49
  readonly replyTo?: string;
34
- readonly subject: string;
50
+ /** Needed unless `template` gives it. */
51
+ readonly subject?: string;
35
52
  readonly text?: string;
36
53
  readonly html?: string;
37
54
  /**
@@ -39,38 +56,90 @@ interface OutgoingMessage {
39
56
  * Message is purged, the same key can send another Message.
40
57
  */
41
58
  readonly key?: string;
59
+ /** At most 20 files, each at most 10 MB, the Message with them at most 18 MB; programs and scripts are refused. */
60
+ readonly attachments?: ReadonlyArray<OutgoingAttachment>;
61
+ /** A Template of the Team's, by name: its subject, text and HTML, filled from `variables` (every `{{name}}` it has, and no other). */
62
+ readonly template?: string;
63
+ readonly variables?: Readonly<Record<string, string | number>>;
64
+ /** When to send it, up to thirty days ahead. */
65
+ readonly sendAt?: Date | number;
66
+ /** `broadcast` for what you send to many, with a `topic` its one recipient can leave in one click. */
67
+ readonly stream?: "transactional" | "broadcast";
68
+ readonly topic?: string;
69
+ readonly tag?: string;
70
+ readonly metadata?: Readonly<Record<string, string>>;
71
+ readonly track?: {
72
+ readonly opens?: boolean;
73
+ readonly clicks?: boolean;
74
+ };
75
+ /** Send it to no one, recorded and told to webhooks as if sent. */
76
+ readonly test?: boolean;
42
77
  }
43
- /** A Message as the engine took it: `to` always a list. */
44
- interface CheckedMessage extends Omit<OutgoingMessage, "to"> {
78
+ /** A Message as the engine takes it: `to` always a list, files in base64, `sendAt` in milliseconds. */
79
+ interface CheckedMessage extends Omit<OutgoingMessage, "to" | "attachments" | "sendAt"> {
45
80
  readonly to: ReadonlyArray<string>;
81
+ readonly attachments?: ReadonlyArray<{
82
+ readonly filename: string;
83
+ readonly content: string;
84
+ readonly contentType?: string;
85
+ readonly contentId?: string;
86
+ }>;
87
+ readonly sendAt?: number;
46
88
  }
47
89
  interface SentMessage {
48
90
  readonly id: string;
49
- /** `queued` while the send is still under way; `failed` when it was refused, with `error`. */
91
+ /** `queued` while the send is still under way, or until `sendAt`; `failed` when it was refused, with `error`. */
50
92
  readonly state: "sent" | "queued" | "suppressed" | "failed";
51
93
  readonly suppressed: ReadonlyArray<string>;
52
94
  readonly error?: string;
95
+ /** When it is to be sent, while it waits for that. */
96
+ readonly sendAt?: number;
53
97
  }
54
- /** Where Messages go: the Seam under `email()`. The Stand-in and the real Capability are its Adapters. */
98
+ /** One Message of a batch: sent, or refused with why, the rest going on regardless. */
99
+ type BatchResult = {
100
+ readonly message: SentMessage;
101
+ } | {
102
+ readonly error: {
103
+ readonly code: EmailErrorCode;
104
+ readonly message: string;
105
+ };
106
+ };
107
+ /** Where Messages go: the Seam under `email()`. The Stand-in and the real Capability are its Adapters; one without `batch` sends a batch one Message at a time. */
55
108
  interface EmailEngine {
56
109
  send(message: CheckedMessage): Promise<SentMessage>;
110
+ batch?(messages: ReadonlyArray<CheckedMessage>): Promise<ReadonlyArray<BatchResult>>;
57
111
  }
58
112
  interface Email {
59
113
  send(message: OutgoingMessage): Promise<SentMessage>;
114
+ /** Up to 100 Messages, each its own with its own key; none carries files. Returns each one's result in order. */
115
+ batch(messages: ReadonlyArray<OutgoingMessage>): Promise<ReadonlyArray<BatchResult>>;
60
116
  }
61
117
  /** The bare address of `Ada <ada@acme.dev>` or `ada@acme.dev`, lowercase; `invalid` when it is none. */
62
118
  declare function addressOf(value: string): string;
63
119
  /** At most this many recipients, to, cc and bcc together. */
64
120
  declare const MAX_RECIPIENTS = 50;
121
+ /** At most this many files a Message, each at most `MAX_ATTACHMENT_BYTES`, and the Message with them at most `MAX_MESSAGE_BYTES`. */
122
+ declare const MAX_ATTACHMENTS = 20;
123
+ declare const MAX_ATTACHMENT_BYTES: number;
124
+ declare const MAX_MESSAGE_BYTES: number;
125
+ /** At most this many Messages a batch. */
126
+ declare const MAX_BATCH = 100;
127
+ /** A Message checked as the engine takes it; throws `EmailError("invalid")` saying what is wrong. */
128
+ declare function checkMessage(message: OutgoingMessage): CheckedMessage;
65
129
  declare function email(given?: EmailEngine): Email;
66
130
  /**
67
- * Whether a webhook delivery is genuine: its `Midsummer-Signature` header (`t=<ms>,v1=<hex>`) is the
68
- * HMAC-SHA256 of `<t>.<body>` under the webhook's secret, made within `toleranceMs` (five minutes) of
69
- * `now`. Pass the body exactly as it arrived. Deliveries are at least once: dedupe by `Midsummer-Event-Id`.
131
+ * Whether a webhook delivery Midsummer sent is genuine: signed as Standard Webhooks says, as every
132
+ * webhook Midsummer sends is (email delivery events, Inbox rules' `email.received`, a Team's or an
133
+ * agent's endpoints, an installed app's events). Give the request's headers (`webhook-id`,
134
+ * `webhook-timestamp`, `webhook-signature`), the body exactly as it arrived, and the endpoint's
135
+ * secret (`whsec_…`, shown when it was made or rotated). A delivery older than five minutes, or
136
+ * ahead of the clock by as much, is refused. After a rotation both secrets sign for a day, and either
137
+ * passing is enough. Deliveries are at least once: drop a repeat by its `webhook-id`.
138
+ *
139
+ * if (!(await verifyWebhook(request.headers, body, process.env.MIDSUMMER_WEBHOOK_SECRET!))) return new Response(null, { status: 401 })
70
140
  */
71
- declare function verifyWebhook(secret: string, signature: string | null, body: string, options?: {
141
+ declare function verifyWebhook(headers: Headers | Readonly<Record<string, string | undefined>>, body: string, secret: string, options?: {
72
142
  readonly now?: number;
73
- readonly toleranceMs?: number;
74
143
  }): Promise<boolean>;
75
144
  //#endregion
76
- export { CheckedMessage, Email, EmailEngine, EmailError, EmailErrorCode, MAX_RECIPIENTS, OutgoingMessage, SentMessage, addressOf, email, verifyWebhook };
145
+ export { BatchResult, CheckedMessage, Email, EmailEngine, EmailError, EmailErrorCode, MAX_ATTACHMENTS, MAX_ATTACHMENT_BYTES, MAX_BATCH, MAX_MESSAGE_BYTES, MAX_RECIPIENTS, OutgoingAttachment, OutgoingMessage, SentMessage, addressOf, checkMessage, email, verifyWebhook };
package/email/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { a as verifyWebhook, i as email, n as MAX_RECIPIENTS, r as addressOf, t as EmailError } from "../email-DXtpr7pT.mjs";
2
- export { EmailError, MAX_RECIPIENTS, addressOf, email, verifyWebhook };
1
+ import { a as MAX_MESSAGE_BYTES, c as checkMessage, i as MAX_BATCH, l as email, n as MAX_ATTACHMENTS, o as MAX_RECIPIENTS, r as MAX_ATTACHMENT_BYTES, s as addressOf, t as EmailError, u as verifyWebhook } from "../email-IH5OllU2.mjs";
2
+ export { EmailError, MAX_ATTACHMENTS, MAX_ATTACHMENT_BYTES, MAX_BATCH, MAX_MESSAGE_BYTES, MAX_RECIPIENTS, addressOf, checkMessage, email, verifyWebhook };
package/email/smtp.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { c as client, i as email, t as EmailError } from "../email-DXtpr7pT.mjs";
1
+ import { l as email, p as client, t as EmailError } from "../email-IH5OllU2.mjs";
2
2
  import { createServer } from "node:net";
3
3
  import { createServer as createServer$1 } from "node:tls";
4
4
  //#region src/email/smtp.ts
@@ -14,13 +14,15 @@ import { createServer as createServer$1 } from "node:tls";
14
14
  * from this computer, so a key never crosses a network in the clear. The message's `To` and `Cc`
15
15
  * recipients that the envelope names are its to and cc, and the envelope's others its bcc (a message
16
16
  * naming none of them goes to each blind recipient alone); its `Message-ID` is the Message's key, so a client sending it again sends it once. Its text and HTML
17
- * parts are read from plain, multipart, quoted-printable and base64 bodies.
17
+ * parts are read from plain, multipart, quoted-printable and base64 bodies, and every other part (one
18
+ * a client marks as an attachment, or of any type but text) is a file the Message carries, an inline
19
+ * one by its `Content-ID`, held to the limits every Message keeps to.
18
20
  *
19
21
  * Email's refusals come back as SMTP replies: an unknown key `535`, a sender off a verified Sending
20
22
  * domain `550`, anything not a Message `554`, and Email out of reach `451`, which a client tries again.
21
23
  */
22
- /** At most this many bytes of message. */
23
- const MAX_BYTES = 2e6;
24
+ /** At most this many bytes of message: 18 MB of words and files, once a client has encoded them in base64. */
25
+ const MAX_BYTES = 26e6;
24
26
  /** A `send` that hands each message to Email at `origin` (the API's), with the client's key. */
25
27
  function relayTo(origin, options = {}) {
26
28
  return (key, message) => email(client(origin, {
@@ -232,7 +234,7 @@ function split(raw) {
232
234
  }
233
235
  /** A parameter of a header such as Content-Type: `boundary`, `charset`. */
234
236
  const parameter = (header, name) => new RegExp(`;\\s*${name}="?([^";]+)"?`, "i").exec(header)?.[1];
235
- /** The text and HTML of a part, by its content type, through multiparts. */
237
+ /** The text and HTML of a part, by its content type, through multiparts; any other part is a file. */
236
238
  function bodies(headers, body, found) {
237
239
  const type = headers.get("content-type") ?? "text/plain";
238
240
  if (/^multipart\//i.test(type)) {
@@ -246,7 +248,20 @@ function bodies(headers, body, found) {
246
248
  return;
247
249
  }
248
250
  const encoding = (headers.get("content-transfer-encoding") ?? "7bit").toLowerCase();
249
- const content = decode(encoding === "base64" ? Buffer.from(body.toString("latin1").replace(/\s+/g, ""), "base64") : encoding === "quoted-printable" ? Buffer.from(body.toString("latin1").replace(/=\r?\n/g, "").replace(/=([0-9A-Fa-f]{2})/g, (_, h) => String.fromCharCode(parseInt(h, 16))), "latin1") : body, parameter(type, "charset")).replace(/\r\n$/, "");
251
+ const bytes = encoding === "base64" ? Buffer.from(body.toString("latin1").replace(/\s+/g, ""), "base64") : encoding === "quoted-printable" ? Buffer.from(body.toString("latin1").replace(/=\r?\n/g, "").replace(/=([0-9A-Fa-f]{2})/g, (_, h) => String.fromCharCode(parseInt(h, 16))), "latin1") : body;
252
+ const disposition = headers.get("content-disposition") ?? "";
253
+ const filename = parameter(disposition, "filename") ?? parameter(type, "name");
254
+ if (/^\s*attachment/i.test(disposition) || filename || !/^text\/(plain|html)/i.test(type)) {
255
+ const contentId = headers.get("content-id")?.replace(/^<|>$/g, "");
256
+ found.files.push({
257
+ filename: words(filename ?? "attachment"),
258
+ content: bytes.toString("base64"),
259
+ contentType: type.split(";")[0].trim().toLowerCase(),
260
+ ...contentId ? { contentId } : {}
261
+ });
262
+ return;
263
+ }
264
+ const content = decode(bytes, parameter(type, "charset")).replace(/\r\n$/, "");
250
265
  if (/^text\/html/i.test(type)) found.html ??= content;
251
266
  else if (/^text\/plain/i.test(type)) found.text ??= content;
252
267
  }
@@ -263,7 +278,7 @@ function addresses(value) {
263
278
  */
264
279
  function parse(raw, envelope, recipients) {
265
280
  const { headers, body } = split(raw);
266
- const found = {};
281
+ const found = { files: [] };
267
282
  bodies(headers, body, found);
268
283
  const bare = [...new Set(recipients.map((address) => address.toLowerCase()))];
269
284
  const named = (header) => addresses(headers.get(header)).filter((address) => bare.includes(address));
@@ -276,7 +291,8 @@ function parse(raw, envelope, recipients) {
276
291
  ...replyTo ? { replyTo: words(replyTo) } : {},
277
292
  subject: words(headers.get("subject") ?? "") || "(no subject)",
278
293
  ...found.text !== void 0 ? { text: found.text } : {},
279
- ...found.html !== void 0 ? { html: found.html } : {}
294
+ ...found.html !== void 0 ? { html: found.html } : {},
295
+ ...found.files.length ? { attachments: found.files } : {}
280
296
  };
281
297
  if (!to.length && !cc.length) return bcc.map((address) => ({
282
298
  ...common,
@@ -3,6 +3,9 @@ import { CheckedMessage, EmailEngine } from "./index.mjs";
3
3
  declare function standIn(options: {
4
4
  readonly domains: ReadonlyArray<string>;
5
5
  readonly suppressed?: ReadonlyArray<string>;
6
+ readonly optedOut?: ReadonlyArray<string>;
7
+ readonly templates?: ReadonlyArray<string>;
8
+ readonly clock?: () => number;
6
9
  }): EmailEngine & {
7
10
  readonly sent: ReadonlyArray<CheckedMessage & {
8
11
  readonly id: string;