@segmentstream/ontology 0.107.0 → 0.109.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.109.0
4
+
5
+ `emailReplyMessage` from `@segmentstream/ontology/email` takes `attachments` (file name, MIME type
6
+ and bytes): the reply becomes `multipart/mixed`, its text and HTML first, with every threading
7
+ header, `Auto-Submitted` and reply key it had, and refuses more than `EMAIL_ATTACHMENTS_LIMIT`
8
+ (25 MB, Gmail's limit) of files together.
9
+
10
+ A reviewed reply approved for an email chat is now marked `Auto-Submitted: auto-replied` and
11
+ named `X-SegmentStream-Reply: review-<review id>`, as the email channel's own replies are, so no
12
+ autoresponder answers it and the channel does not take it for staff's mail.
13
+
14
+ The agent routes now admit an email chat (`email:<thread>:<address>`), whose address holds `@`,
15
+ `.` and `+`: storing the attachments of an email, reading them and sending stored files in an email
16
+ chat were refused before.
17
+
18
+ ## 0.108.0
19
+
20
+ A workspace can send its own invitation. `signIn.invitationEmail` names one of the ontology's
21
+ `emails`, which the platform then sends instead of its own invitation to a member who has not signed
22
+ in yet: when they are invited from `segmentstream ontology member invite` or the console, and from
23
+ `User.sendSignInLink` without a template. It may use only the built-in values; `check` reports
24
+ `invalid-email` for any other, and `invalid-sign-in` when the name is not a declared email.
25
+
26
+ Emails can use two more built-in values, `{{app.url}}`, the app's production address, and
27
+ `{{app.mcpUrl}}`, its MCP server's, and `sections`: boxes below the button with a title, text, a
28
+ value to copy shown large in a monospace box, labelled items with text or a command, and a note.
29
+ The starter's invitation, in `ontology/emails.ts`, uses them to give the MCP server's address and how
30
+ Claude, ChatGPT, Claude Code and Codex connect. Older platform deployments ignore both and send their
31
+ own invitation.
32
+
3
33
  ## 0.107.0
4
34
 
5
35
  The agent's own tools are permissions: `agent_tool:sandbox` (the sandbox's shell and file tools,
package/README.md CHANGED
@@ -483,14 +483,18 @@ export default defineOntology({
483
483
  policy, grants, hook content, notice text, and lower limits. Nothing defaults to open.
484
484
  `check(config, { agentConfig })` warns if open channels lack `firstContact.notice` or `limits` when
485
485
  agent config is supplied. The ontology CLI cannot see that config and says those checks are skipped.
486
- - `emails: { agreementReview: { subject, eyebrow?, heading, card?, note?, paragraphs?, action, footer?, replyTo? } }`
486
+ - `emails: { agreementReview: { subject, eyebrow?, heading, card?, note?, paragraphs?, action, sections?, footer?, replyTo? } }`
487
487
  declares the workspace's own emails, in plain text with `{{value}}` placeholders and the
488
- built-in `{{member.name}}`, `{{member.firstName}}` and `{{workspace.name}}`. A handler sends
488
+ built-in `{{member.name}}`, `{{member.firstName}}`, `{{workspace.name}}`, `{{app.url}}` and
489
+ `{{app.mcpUrl}}`. `sections` are boxes below the button, each
490
+ `{ title, text?, copy?: { label?, value }, items?: [{ label, text?, code? }], note? }`.
491
+ `signIn.invitationEmail: "memberInvitation"` names the one the platform sends instead of its
492
+ own invitation; it may use only built-in values. A handler sends
489
493
  one with `User.sendSignInLink(user, { template: "agreementReview", returnTo: "/shared/1", values })`:
490
494
  after the commit, in production, the platform emails the member a link that signs them in and
491
495
  opens `returnTo`, laid out in its design, from the workspace's name, with replies to `replyTo`
492
496
  or else the member who ran the action. Without `template` the
493
- member gets the platform's own invitation or sign-in email. `check` reports `invalid-email`.
497
+ member gets the invitation, or the platform's sign-in email. `check` reports `invalid-email`.
494
498
  - `defineOntology` checks the definition and builds the manifest. It throws
495
499
  `InvalidOntology` with every diagnostic when the definition has errors. Entities,
496
500
  actions and select options need a description.
package/dist/analyze.js CHANGED
@@ -12,7 +12,7 @@ import { AGENT_TOOL, AGENT_TOOL_VERBS, EXPLICIT_GRANT_ENTITIES, generatedActionP
12
12
  import { ON_DELETE, isRelationship } from "./relationship.js";
13
13
  import { isRole, member, role } from "./role.js";
14
14
  import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, GUEST_CHANNELS, SIGN_UP_CHANNELS, SIGN_UP_CHAT_CHANNELS, isGuestChannel, isSignInPolicy, isSignUpChannel, websiteOrigin, } from "./sign-in.js";
15
- import { emailOptions } from "./emails.js";
15
+ import { BUILT_IN_EMAIL_VALUES, emailOptions, emailValueNames, } from "./emails.js";
16
16
  import { AgentChat } from "./agent-chat.js";
17
17
  import { AgentReview } from "./agent-review.js";
18
18
  import { APP_FEEDBACK_ENTITIES } from "./app-feedback.js";
@@ -75,12 +75,15 @@ export function analyze(config, options = {}) {
75
75
  !declaredRoles.some((candidate) => candidate.name === nameToWire(config.hooks.role)))) {
76
76
  report("invalid-permission", "hooks.role", "hooks.role must name a declared ontology role.");
77
77
  }
78
+ const emails = emailOptions(config.emails, report, (name, path) => camelCaseName(name, path, "agreementReview", "Email", report));
78
79
  const signInDeclared = signInOptions(config, report);
79
80
  const guest = guestOptions(config, report);
81
+ const invitationEmail = invitationEmailOption(config, emails, report);
80
82
  const signIn = {
81
83
  ...signInDeclared,
82
84
  ...signUpOptions(config, signInDeclared, declaredRoles, report),
83
85
  ...(guest === undefined ? {} : { guest: guest.resolved }),
86
+ ...(invitationEmail === undefined ? {} : { invitationEmail }),
84
87
  };
85
88
  const discovery = config.discovery;
86
89
  if (discovery !== undefined &&
@@ -91,7 +94,6 @@ export function analyze(config, options = {}) {
91
94
  report("invalid-discovery", "discovery", 'discovery takes { model: "<provider>/<model>" }, a decision model on AI Gateway such as ' +
92
95
  '"typesafe-ai/jev-1.14.0".');
93
96
  }
94
- const emails = emailOptions(config.emails, report, (name, path) => camelCaseName(name, path, "agreementReview", "Email", report));
95
97
  const connections = collectConnections(config, report);
96
98
  const entitiesByName = new Map();
97
99
  for (const candidate of entities) {
@@ -1232,7 +1234,7 @@ function signInOptions(config, report) {
1232
1234
  return fallback;
1233
1235
  }
1234
1236
  for (const key of Object.keys(options)) {
1235
- if (!["policy", "channels", "onNewUser", "browser", "codeLink"].includes(key)) {
1237
+ if (!["policy", "channels", "onNewUser", "browser", "codeLink", "invitationEmail"].includes(key)) {
1236
1238
  report("invalid-sign-in", `signIn.${key}`, `Unknown signIn key: ${key}.`);
1237
1239
  }
1238
1240
  }
@@ -1291,6 +1293,35 @@ function signInOptions(config, report) {
1291
1293
  ...(typeof codeLink === "boolean" ? { codeLink } : {}),
1292
1294
  };
1293
1295
  }
1296
+ /**
1297
+ * `signIn.invitationEmail`: the wire name of the declared email the platform sends instead of its
1298
+ * own invitation. Nothing fills an invitation's values, so the email may use only built-in ones.
1299
+ */
1300
+ function invitationEmailOption(config, emails, report) {
1301
+ const options = config.signIn;
1302
+ const name = isPlainObject(options) ? options.invitationEmail : undefined;
1303
+ const path = "signIn.invitationEmail";
1304
+ if (name === undefined) {
1305
+ return undefined;
1306
+ }
1307
+ if (typeof name !== "string" || !/^[a-z][a-zA-Z0-9]*$/.test(name)) {
1308
+ report("invalid-sign-in", path, "invitationEmail names one of the ontology's emails, such as memberInvitation.");
1309
+ return undefined;
1310
+ }
1311
+ const wire = nameToWire(name);
1312
+ const template = emails[wire];
1313
+ if (template === undefined) {
1314
+ report("invalid-sign-in", path, `${name} is not one of the ontology's emails.`);
1315
+ return undefined;
1316
+ }
1317
+ const values = emailValueNames(template);
1318
+ if (values.length > 0) {
1319
+ report("invalid-email", `emails.${name}`, `${name} is the invitation, and nothing fills ${values.map((value) => `{{${value}}}`).join(", ")}: ` +
1320
+ `use only ${BUILT_IN_EMAIL_VALUES.map((value) => `{{${value}}}`).join(", ")}.`);
1321
+ return undefined;
1322
+ }
1323
+ return wire;
1324
+ }
1294
1325
  /**
1295
1326
  * Where strangers may sign up and the wire names of the roles each open channel grants, and the
1296
1327
  * `onSignUp` action. Every role must be a declared one other than `member`. A channel opened both
package/dist/email.d.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  /** The most characters of a reply the mail channel sends in one message. */
2
2
  export declare const EMAIL_MESSAGE_LIMIT = 100000;
3
+ /**
4
+ * The most bytes of files one reply carries, together: Gmail takes 25 MB of attachments in a
5
+ * message. A sender whose own transport takes less, such as a connection proxy, bounds them lower.
6
+ */
7
+ export declare const EMAIL_ATTACHMENTS_LIMIT = 25000000;
3
8
  /**
4
9
  * A reply's Markdown as the HTML part of an email. HTML the text holds is escaped, so a reply can
5
10
  * carry no markup, image or script the platform did not render from Markdown itself.
@@ -7,6 +12,12 @@ export declare const EMAIL_MESSAGE_LIMIT = 100000;
7
12
  export declare function renderEmailHtml(text: string): string;
8
13
  /** The subject a reply in a thread carries: the thread's own, prefixed `Re:` once. */
9
14
  export declare function replySubject(subject: string | null | undefined): string;
15
+ /** A file a reply carries. */
16
+ export interface EmailAttachment {
17
+ readonly filename: string;
18
+ readonly contentType: string;
19
+ readonly bytes: Uint8Array;
20
+ }
10
21
  /** What a reply in an email thread needs from the message it answers. */
11
22
  export interface EmailReply {
12
23
  /** The address the reply goes to: a lower-case address without a name. */
@@ -31,12 +42,17 @@ export interface EmailReply {
31
42
  * failure can find it in the thread instead of sending it twice. Letters, digits, `-` and `_`.
32
43
  */
33
44
  readonly replyKey?: string;
45
+ /**
46
+ * Files the reply carries after its text, at most {@link EMAIL_ATTACHMENTS_LIMIT} bytes
47
+ * together. With files the message is `multipart/mixed`, its text first.
48
+ */
49
+ readonly attachments?: ReadonlyArray<EmailAttachment>;
34
50
  }
35
51
  /** The header that names a reply, as {@link EmailReply.replyKey} sets it. */
36
52
  export declare const REPLY_KEY_HEADER = "X-SegmentStream-Reply";
37
53
  /**
38
- * The reply as an RFC 5322 message with a plain-text and an HTML part, for a mailbox to send in
39
- * the same thread. It names no sender: the mailbox sends from its own address.
54
+ * The reply as an RFC 5322 message with a plain-text and an HTML part, followed by its files, for
55
+ * a mailbox to send in the same thread. It names no sender: the mailbox sends from its own address.
40
56
  */
41
57
  export declare function emailReplyMessage(reply: EmailReply): string;
42
58
  /** Bytes as URL-safe base64 without padding, as the Gmail API takes a raw message. */
package/dist/email.js CHANGED
@@ -1,6 +1,11 @@
1
1
  import { Marked } from "marked";
2
2
  /** The most characters of a reply the mail channel sends in one message. */
3
3
  export const EMAIL_MESSAGE_LIMIT = 100_000;
4
+ /**
5
+ * The most bytes of files one reply carries, together: Gmail takes 25 MB of attachments in a
6
+ * message. A sender whose own transport takes less, such as a connection proxy, bounds them lower.
7
+ */
8
+ export const EMAIL_ATTACHMENTS_LIMIT = 25_000_000;
4
9
  const HTML_ESCAPES = {
5
10
  "&": "&amp;",
6
11
  "<": "&lt;",
@@ -42,17 +47,37 @@ function messageId(value) {
42
47
  return flat !== undefined && /^<[^<>\s]+>$/.test(flat) ? flat : undefined;
43
48
  }
44
49
  /** Base64 in lines of 76 characters, as MIME bodies carry it. */
45
- function base64Lines(text) {
46
- return (Buffer.from(text, "utf8")
50
+ function base64Lines(content) {
51
+ return ((typeof content === "string" ? Buffer.from(content, "utf8") : Buffer.from(content))
47
52
  .toString("base64")
48
53
  .match(/.{1,76}/g)
49
54
  ?.join("\r\n") ?? "");
50
55
  }
56
+ /** A MIME type as a header carries it, or `application/octet-stream` for anything else. */
57
+ function mediaType(value) {
58
+ const type = value.trim().toLowerCase();
59
+ return /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/.test(type)
60
+ ? type
61
+ : "application/octet-stream";
62
+ }
63
+ /**
64
+ * A file name as a MIME parameter: printable ASCII in quotes, followed by the same name in UTF-8
65
+ * (RFC 2231) when it holds anything else, so mail programs show it as it was named.
66
+ */
67
+ function fileNameParameter(parameter, filename) {
68
+ const flat = filename.replace(/[\r\n\t"\\]+/g, " ").trim() || "attachment";
69
+ const ascii = flat.replace(/[^\x20-\x7e]/g, "_");
70
+ if (ascii === flat) {
71
+ return `${parameter}="${flat}"`;
72
+ }
73
+ const encoded = encodeURIComponent(flat).replace(/['()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
74
+ return `${parameter}="${ascii}"; ${parameter}*=UTF-8''${encoded}`;
75
+ }
51
76
  /** The header that names a reply, as {@link EmailReply.replyKey} sets it. */
52
77
  export const REPLY_KEY_HEADER = "X-SegmentStream-Reply";
53
78
  /**
54
- * The reply as an RFC 5322 message with a plain-text and an HTML part, for a mailbox to send in
55
- * the same thread. It names no sender: the mailbox sends from its own address.
79
+ * The reply as an RFC 5322 message with a plain-text and an HTML part, followed by its files, for
80
+ * a mailbox to send in the same thread. It names no sender: the mailbox sends from its own address.
56
81
  */
57
82
  export function emailReplyMessage(reply) {
58
83
  if (!/^[^\s<>@,;:"]+@[^\s<>@,;:"]+$/.test(reply.to)) {
@@ -61,6 +86,11 @@ export function emailReplyMessage(reply) {
61
86
  if (reply.replyKey !== undefined && !/^[A-Za-z0-9_-]{1,128}$/.test(reply.replyKey)) {
62
87
  throw new Error("The reply's key holds characters a header cannot carry.");
63
88
  }
89
+ const attachments = reply.attachments ?? [];
90
+ const size = attachments.reduce((total, file) => total + file.bytes.byteLength, 0);
91
+ if (size > EMAIL_ATTACHMENTS_LIMIT) {
92
+ throw new Error(`A reply carries at most ${EMAIL_ATTACHMENTS_LIMIT} bytes of files.`);
93
+ }
64
94
  const boundary = `segmentstream-${crypto.randomUUID()}`;
65
95
  const parent = messageId(reply.inReplyTo);
66
96
  const references = [
@@ -79,10 +109,10 @@ export function emailReplyMessage(reply) {
79
109
  ...(reply.autoSubmitted === true ? ["Auto-Submitted: auto-replied"] : []),
80
110
  ...(reply.replyKey === undefined ? [] : [`${REPLY_KEY_HEADER}: ${reply.replyKey}`]),
81
111
  "MIME-Version: 1.0",
82
- `Content-Type: multipart/alternative; boundary="${boundary}"`,
83
112
  ];
84
- return [
85
- ...headers,
113
+ // The text and the same text as HTML: the whole message without files, its first part with them.
114
+ const text = [
115
+ `Content-Type: multipart/alternative; boundary="${boundary}"`,
86
116
  "",
87
117
  `--${boundary}`,
88
118
  "Content-Type: text/plain; charset=UTF-8",
@@ -95,6 +125,26 @@ export function emailReplyMessage(reply) {
95
125
  "",
96
126
  base64Lines(reply.html),
97
127
  `--${boundary}--`,
128
+ ];
129
+ if (attachments.length === 0) {
130
+ return [...headers, ...text, ""].join("\r\n");
131
+ }
132
+ const mixed = `segmentstream-${crypto.randomUUID()}`;
133
+ return [
134
+ ...headers,
135
+ `Content-Type: multipart/mixed; boundary="${mixed}"`,
136
+ "",
137
+ `--${mixed}`,
138
+ ...text,
139
+ ...attachments.flatMap((file) => [
140
+ `--${mixed}`,
141
+ `Content-Type: ${mediaType(file.contentType)}; ${fileNameParameter("name", file.filename)}`,
142
+ `Content-Disposition: attachment; ${fileNameParameter("filename", file.filename)}`,
143
+ "Content-Transfer-Encoding: base64",
144
+ "",
145
+ base64Lines(file.bytes),
146
+ ]),
147
+ `--${mixed}--`,
98
148
  "",
99
149
  ].join("\r\n");
100
150
  }
package/dist/emails.d.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import type { Diagnostic } from "./diagnostics.js";
2
2
  /**
3
3
  * An email the workspace writes and the platform sends with a sign-in link, named by
4
- * `User.sendSignInLink`. Every field is plain text, in which `{{name}}` stands for a value the
5
- * action passes, and `{{member.name}}`, `{{member.firstName}}` and `{{workspace.name}}` for the
6
- * recipient and the workspace. The platform lays the fields out, escapes them and adds the
4
+ * `User.sendSignInLink` or by `signIn.invitationEmail`. Every field is plain text, in which
5
+ * `{{name}}` stands for a value the action passes, and `{{member.name}}`, `{{member.firstName}}`,
6
+ * `{{workspace.name}}`, `{{app.url}}` and `{{app.mcpUrl}}` for the recipient, the workspace, the
7
+ * app's address and its MCP server's. The platform lays the fields out, escapes them and adds the
7
8
  * plain-text part; `action` labels the one button, which signs the person in and opens the path
8
9
  * the action names. A field whose text is empty once filled in is left out.
9
10
  */
@@ -22,6 +23,8 @@ export interface EmailTemplate {
22
23
  readonly paragraphs?: ReadonlyArray<string>;
23
24
  /** The button's label. */
24
25
  readonly action: string;
26
+ /** Boxes below the button, such as how to connect an AI assistant to the app. */
27
+ readonly sections?: ReadonlyArray<EmailSection>;
25
28
  /** Small print at the bottom, such as why the person received the email. */
26
29
  readonly footer?: string;
27
30
  /**
@@ -31,8 +34,32 @@ export interface EmailTemplate {
31
34
  */
32
35
  readonly replyTo?: string;
33
36
  }
34
- /** The values every email may use besides those the action passes. */
35
- export declare const BUILT_IN_EMAIL_VALUES: readonly ["member.name", "member.firstName", "workspace.name"];
37
+ /**
38
+ * A box below an email's button: a title, a line of text, a value to copy shown large in a
39
+ * monospace box, such as an address, labelled items with text or a command, and a closing note.
40
+ */
41
+ export interface EmailSection {
42
+ readonly title: string;
43
+ readonly text?: string;
44
+ /** A value the person copies into another app, such as an address. */
45
+ readonly copy?: {
46
+ readonly label?: string;
47
+ readonly value: string;
48
+ };
49
+ /** Labelled items, such as one per app: text, a command shown in a monospace box, or both. */
50
+ readonly items?: ReadonlyArray<EmailSectionItem>;
51
+ readonly note?: string;
52
+ }
53
+ export interface EmailSectionItem {
54
+ readonly label: string;
55
+ readonly text?: string;
56
+ readonly code?: string;
57
+ }
58
+ /**
59
+ * The values every email may use besides those the action passes: the recipient, the workspace,
60
+ * the app's production address and its MCP server's address, `/mcp` on the same domain.
61
+ */
62
+ export declare const BUILT_IN_EMAIL_VALUES: readonly ["member.name", "member.firstName", "workspace.name", "app.url", "app.mcpUrl"];
36
63
  /**
37
64
  * The query parameter of the callback a sign-in link is requested with, naming the queued email it
38
65
  * delivers. The platform reads it from Neon Auth's link and leaves it out of the path the person
@@ -51,6 +78,10 @@ export declare const MAX_EMAIL_PARAGRAPHS = 20;
51
78
  export declare const MAX_EMAIL_VALUES = 50;
52
79
  /** The longest path a sign-in link returns to. */
53
80
  export declare const MAX_RETURN_PATH = 1024;
81
+ /** The most sections of one email. */
82
+ export declare const MAX_EMAIL_SECTIONS = 5;
83
+ /** The most items of one section. */
84
+ export declare const MAX_EMAIL_SECTION_ITEMS = 10;
54
85
  type Report = (code: Diagnostic["code"], path: string, message: string, severity?: Diagnostic["severity"]) => void;
55
86
  /** The values an action must pass for this email: its placeholders that are not built in. */
56
87
  export declare function emailValueNames(template: EmailTemplate): ReadonlyArray<string>;
package/dist/emails.js CHANGED
@@ -1,6 +1,15 @@
1
1
  import { isRecord } from "./authoring-names.js";
2
- /** The values every email may use besides those the action passes. */
3
- export const BUILT_IN_EMAIL_VALUES = ["member.name", "member.firstName", "workspace.name"];
2
+ /**
3
+ * The values every email may use besides those the action passes: the recipient, the workspace,
4
+ * the app's production address and its MCP server's address, `/mcp` on the same domain.
5
+ */
6
+ export const BUILT_IN_EMAIL_VALUES = [
7
+ "member.name",
8
+ "member.firstName",
9
+ "workspace.name",
10
+ "app.url",
11
+ "app.mcpUrl",
12
+ ];
4
13
  /**
5
14
  * The query parameter of the callback a sign-in link is requested with, naming the queued email it
6
15
  * delivers. The platform reads it from Neon Auth's link and leaves it out of the path the person
@@ -19,6 +28,10 @@ export const MAX_EMAIL_PARAGRAPHS = 20;
19
28
  export const MAX_EMAIL_VALUES = 50;
20
29
  /** The longest path a sign-in link returns to. */
21
30
  export const MAX_RETURN_PATH = 1024;
31
+ /** The most sections of one email. */
32
+ export const MAX_EMAIL_SECTIONS = 5;
33
+ /** The most items of one section. */
34
+ export const MAX_EMAIL_SECTION_ITEMS = 10;
22
35
  const FIELDS = [
23
36
  "subject",
24
37
  "eyebrow",
@@ -27,9 +40,12 @@ const FIELDS = [
27
40
  "note",
28
41
  "paragraphs",
29
42
  "action",
43
+ "sections",
30
44
  "footer",
31
45
  "replyTo",
32
46
  ];
47
+ const SECTION_FIELDS = ["title", "text", "copy", "items", "note"];
48
+ const ITEM_FIELDS = ["label", "text", "code"];
33
49
  const REQUIRED = ["subject", "heading", "action"];
34
50
  const OPTIONAL_TEXT = ["eyebrow", "note", "footer"];
35
51
  const PLACEHOLDER = /\{\{\s*([^{}]*?)\s*\}\}/g;
@@ -51,9 +67,27 @@ function emailTexts(template) {
51
67
  ...(template.note === undefined ? [] : [["note", template.note]]),
52
68
  ...(template.paragraphs ?? []).map((text, index) => [`paragraphs.${index}`, text]),
53
69
  ["action", template.action],
70
+ ...(template.sections ?? []).flatMap((section, index) => sectionTexts(section, index)),
54
71
  ...(template.footer === undefined ? [] : [["footer", template.footer]]),
55
72
  ];
56
73
  }
74
+ /** Every text of one section, with the path of its field. */
75
+ function sectionTexts(section, index) {
76
+ const at = `sections.${index}`;
77
+ const optional = (path, text) => text === undefined ? [] : [[path, text]];
78
+ return [
79
+ [`${at}.title`, section.title],
80
+ ...optional(`${at}.text`, section.text),
81
+ ...optional(`${at}.copy.label`, section.copy?.label),
82
+ ...optional(`${at}.copy.value`, section.copy?.value),
83
+ ...(section.items ?? []).flatMap((item, itemIndex) => [
84
+ [`${at}.items.${itemIndex}.label`, item.label],
85
+ ...optional(`${at}.items.${itemIndex}.text`, item.text),
86
+ ...optional(`${at}.items.${itemIndex}.code`, item.code),
87
+ ]),
88
+ ...optional(`${at}.note`, section.note),
89
+ ];
90
+ }
57
91
  /** The placeholders of one text, in order. */
58
92
  function placeholders(text) {
59
93
  return [...text.matchAll(PLACEHOLDER)].map((match) => match[1]);
@@ -167,6 +201,9 @@ function emailTemplate(value, path, report) {
167
201
  });
168
202
  }
169
203
  }
204
+ if (value.sections !== undefined) {
205
+ valid = checkSections(value.sections, `${path}.sections`, report) && valid;
206
+ }
170
207
  if (!valid) {
171
208
  return undefined;
172
209
  }
@@ -188,10 +225,110 @@ function emailTemplate(value, path, report) {
188
225
  ? {}
189
226
  : { paragraphs: [...value.paragraphs] }),
190
227
  action: value.action,
228
+ ...(value.sections === undefined
229
+ ? {}
230
+ : { sections: value.sections.map(normalSection) }),
191
231
  ...(value.footer === undefined ? {} : { footer: value.footer }),
192
232
  ...(value.replyTo === undefined ? {} : { replyTo: value.replyTo }),
193
233
  };
194
234
  }
235
+ /** Whether every key of `value` is one of `fields`, reporting the others. */
236
+ function knownKeys(value, fields, path, report) {
237
+ let valid = true;
238
+ for (const key of Object.keys(value)) {
239
+ if (!fields.includes(key)) {
240
+ report("invalid-email", `${path}.${key}`, `Unknown field ${key}; use ${fields.join(", ")}.`);
241
+ valid = false;
242
+ }
243
+ }
244
+ return valid;
245
+ }
246
+ /** Checks `sections`: at most a few boxes, each with a title and its optional parts. */
247
+ function checkSections(value, path, report) {
248
+ if (!Array.isArray(value) || value.length > MAX_EMAIL_SECTIONS) {
249
+ report("invalid-email", path, `sections is a list of at most ${MAX_EMAIL_SECTIONS} { title, text?, copy?, items?, note? }.`);
250
+ return false;
251
+ }
252
+ let valid = true;
253
+ value.forEach((section, index) => {
254
+ const at = `${path}.${index}`;
255
+ if (!isRecord(section)) {
256
+ report("invalid-email", at, "A section is { title, text?, copy?, items?, note? }.");
257
+ valid = false;
258
+ return;
259
+ }
260
+ valid = knownKeys(section, SECTION_FIELDS, at, report) && valid;
261
+ valid = checkText(section.title, `${at}.title`, MAX_EMAIL_TEXT, report) && valid;
262
+ for (const key of ["text", "note"]) {
263
+ if (section[key] !== undefined) {
264
+ valid = checkText(section[key], `${at}.${key}`, MAX_EMAIL_TEXT, report) && valid;
265
+ }
266
+ }
267
+ if (section.copy !== undefined) {
268
+ const copy = section.copy;
269
+ if (!isRecord(copy)) {
270
+ report("invalid-email", `${at}.copy`, "copy is { label?, value }.");
271
+ valid = false;
272
+ }
273
+ else {
274
+ valid = knownKeys(copy, ["label", "value"], `${at}.copy`, report) && valid;
275
+ valid = checkText(copy.value, `${at}.copy.value`, MAX_EMAIL_TEXT, report) && valid;
276
+ if (copy.label !== undefined) {
277
+ valid = checkText(copy.label, `${at}.copy.label`, MAX_EMAIL_TEXT, report) && valid;
278
+ }
279
+ }
280
+ }
281
+ if (section.items !== undefined) {
282
+ if (!Array.isArray(section.items) || section.items.length > MAX_EMAIL_SECTION_ITEMS) {
283
+ report("invalid-email", `${at}.items`, `items is a list of at most ${MAX_EMAIL_SECTION_ITEMS} { label, text?, code? }.`);
284
+ valid = false;
285
+ }
286
+ else {
287
+ section.items.forEach((item, itemIndex) => {
288
+ const itemAt = `${at}.items.${itemIndex}`;
289
+ if (!isRecord(item)) {
290
+ report("invalid-email", itemAt, "An item is { label, text?, code? }.");
291
+ valid = false;
292
+ return;
293
+ }
294
+ valid = knownKeys(item, ITEM_FIELDS, itemAt, report) && valid;
295
+ valid = checkText(item.label, `${itemAt}.label`, MAX_EMAIL_TEXT, report) && valid;
296
+ for (const key of ["text", "code"]) {
297
+ if (item[key] !== undefined) {
298
+ valid = checkText(item[key], `${itemAt}.${key}`, MAX_EMAIL_TEXT, report) && valid;
299
+ }
300
+ }
301
+ });
302
+ }
303
+ }
304
+ });
305
+ return valid;
306
+ }
307
+ /** A checked section with only its declared fields, in order. */
308
+ function normalSection(section) {
309
+ return {
310
+ title: section.title,
311
+ ...(section.text === undefined ? {} : { text: section.text }),
312
+ ...(section.copy === undefined
313
+ ? {}
314
+ : {
315
+ copy: {
316
+ ...(section.copy.label === undefined ? {} : { label: section.copy.label }),
317
+ value: section.copy.value,
318
+ },
319
+ }),
320
+ ...(section.items === undefined
321
+ ? {}
322
+ : {
323
+ items: section.items.map((item) => ({
324
+ label: item.label,
325
+ ...(item.text === undefined ? {} : { text: item.text }),
326
+ ...(item.code === undefined ? {} : { code: item.code }),
327
+ })),
328
+ }),
329
+ ...(section.note === undefined ? {} : { note: section.note }),
330
+ };
331
+ }
195
332
  /**
196
333
  * The declared emails by wire name, each checked: its fields, their lengths and their
197
334
  * placeholders. `wireName` turns a camelCase name into its wire form, reporting one that cannot
package/dist/index.d.ts CHANGED
@@ -50,7 +50,7 @@ export type { WebhookDelivery, WebhookSignatureScheme } from "./webhooks.js";
50
50
  export type { ActionEvent, ActionTrigger, AfterOptions, AnyActionHandle, AnyWorkflow, ChangedBounds, CronOptions, CronProblem, CronTrigger, TriggerFunction, TriggerRecord, WebhookOptions, WebhookSignature, WebhookVerification, WebhookTrigger, Workflow, WorkflowFunction, WorkflowOptions, WorkflowRunContext, WorkflowTrigger, } from "./workflow.js";
51
51
  export { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_IN_METHODS, SIGN_IN_POLICIES, SIGN_UP_CHANNELS, GUEST_CHANNELS, matchesWebsite, signUpOrigin, websiteOrigin, } from "./sign-in.js";
52
52
  export type { ChannelProvider, GuestChannel, GuestOptions, ResolvedGuest, ResolvedSignInOptions, ResolvedSignUp, SignInCheck, SignInMethod, SignInOptions, SignInPolicy, SignUpChannel, SignUpOptions, } from "./sign-in.js";
53
- export type { EmailTemplate } from "./emails.js";
53
+ export type { EmailSection, EmailSectionItem, EmailTemplate } from "./emails.js";
54
54
  export { OntologyActions, OntologyReads, OntologyRuntime, OntologyWrites } from "./runtime.js";
55
55
  export type { ActionRunOptions } from "./runtime.js";
56
56
  export type { BatchOptions, BatchRecordResult, BatchResult, BatchReturning, BatchSummaryResult, CreateManyInput, FieldCondition, OntologyRuntimeService, FindOptions, FreshMetricQueryOptions, GetOptions, Principal, RecordWhere, StoredRecord, StoredValues, UpsertResult, UpdateManyInput, UpsertManyInput, } from "./runtime.js";