@jini-ai/platform 0.7.2 → 0.7.3-next.1

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 (169) hide show
  1. package/CHANGELOG.md +2 -8
  2. package/README.md +16 -4
  3. package/dist/asset-cache.d.ts +13 -3
  4. package/dist/asset-cache.js +163 -154
  5. package/dist/blob-storage.d.ts +3 -32
  6. package/dist/blob-storage.js +1 -9
  7. package/dist/child-environment.d.ts +0 -16
  8. package/dist/child-environment.js +0 -25
  9. package/dist/command.d.ts +6 -11
  10. package/dist/command.js +8 -54
  11. package/dist/download-lock.d.ts +4 -0
  12. package/dist/download-lock.js +82 -0
  13. package/dist/download-maintenance.d.ts +5 -0
  14. package/dist/download-maintenance.js +82 -0
  15. package/dist/download-state.d.ts +8 -0
  16. package/dist/download-state.js +126 -0
  17. package/dist/download-store.d.ts +22 -0
  18. package/dist/download-store.js +174 -0
  19. package/dist/download-target.d.ts +10 -0
  20. package/dist/download-target.js +102 -0
  21. package/dist/download-transfer.d.ts +12 -0
  22. package/dist/download-transfer.js +174 -0
  23. package/dist/download-types.d.ts +162 -0
  24. package/dist/download-types.js +31 -0
  25. package/dist/download.d.ts +1 -89
  26. package/dist/download.js +8 -738
  27. package/dist/fetch-with-timeout.d.ts +7 -32
  28. package/dist/fetch-with-timeout.js +1 -77
  29. package/dist/fs/app-data-root.d.ts +28 -0
  30. package/dist/fs/app-data-root.js +35 -0
  31. package/dist/fs/atomic-write.js +1 -1
  32. package/dist/fs/boot-identity.d.ts +1 -4
  33. package/dist/fs/directory-delete-guard.d.ts +93 -0
  34. package/dist/fs/directory-delete-guard.js +148 -0
  35. package/dist/fs/directory-registry.js +45 -35
  36. package/dist/fs/directory-relocation.d.ts +82 -0
  37. package/dist/fs/directory-relocation.js +99 -0
  38. package/dist/fs/directory-running-lock.d.ts +1 -1
  39. package/dist/fs/directory-running-lock.js +24 -21
  40. package/dist/fs/directory-sync.js +1 -1
  41. package/dist/fs/directory-user-config.js +30 -3
  42. package/dist/fs/directory-workspace.d.ts +34 -30
  43. package/dist/fs/directory-workspace.js +70 -29
  44. package/dist/fs/durable-json.d.ts +6 -15
  45. package/dist/fs/durable-json.js +38 -35
  46. package/dist/fs/errno.d.ts +12 -3
  47. package/dist/fs/errno.js +5 -3
  48. package/dist/fs/file-lock.d.ts +3 -87
  49. package/dist/fs/file-lock.js +16 -30
  50. package/dist/fs/guarded-reader.js +335 -315
  51. package/dist/fs/index.d.ts +5 -0
  52. package/dist/fs/index.js +5 -0
  53. package/dist/fs/recent-directories.d.ts +46 -0
  54. package/dist/fs/recent-directories.js +68 -0
  55. package/dist/fs/remove-directory-tree.d.ts +20 -0
  56. package/dist/fs/remove-directory-tree.js +28 -0
  57. package/dist/fs/user-data-directories.js +2 -2
  58. package/dist/fs/workspace-directory.js +2 -1
  59. package/dist/fs.d.ts +16 -4
  60. package/dist/fs.js +4 -4
  61. package/dist/home-expansion.d.ts +7 -2
  62. package/dist/home-expansion.js +3 -3
  63. package/dist/http/guarded/client.d.ts +1 -2
  64. package/dist/http/guarded/client.js +2 -1
  65. package/dist/http/guarded/index.d.ts +0 -3
  66. package/dist/http/guarded/node-ports.d.ts +1 -1
  67. package/dist/http/guarded/transport.fetch.d.ts +2 -3
  68. package/dist/http/guarded/transport.fetch.js +64 -58
  69. package/dist/http.d.ts +3 -1
  70. package/dist/http.js +2 -2
  71. package/dist/index.d.ts +10 -11
  72. package/dist/index.js +7 -6
  73. package/dist/mail/activity/activity.d.ts +136 -0
  74. package/dist/mail/activity/activity.js +172 -0
  75. package/dist/mail/activity/ports.d.ts +113 -0
  76. package/dist/mail/activity/suppressions.d.ts +82 -0
  77. package/dist/mail/activity/suppressions.js +119 -0
  78. package/dist/mail/activity/vocabulary.d.ts +10 -0
  79. package/dist/mail/activity/vocabulary.js +8 -0
  80. package/dist/mail/builtin-providers.d.ts +12 -6
  81. package/dist/mail/builtin-providers.js +14 -11
  82. package/dist/mail/delivery-wrapper.js +2 -1
  83. package/dist/mail/email-sender-registry.d.ts +1 -1
  84. package/dist/mail/email-sender-registry.js +1 -1
  85. package/dist/mail/email-template-operations.d.ts +186 -0
  86. package/dist/mail/email-template-operations.js +226 -0
  87. package/dist/mail/email-template.d.ts +120 -0
  88. package/dist/mail/email-template.js +243 -0
  89. package/dist/mail/index.d.ts +4 -0
  90. package/dist/mail/index.js +3 -0
  91. package/dist/mail/prepare-sender-email.d.ts +1 -10
  92. package/dist/mail/prepare-sender-email.js +1 -11
  93. package/dist/mail/resolve-mailer.d.ts +2 -1
  94. package/dist/mail/resolve-mailer.js +5 -2
  95. package/dist/mail/senders.d.ts +0 -1
  96. package/dist/mail/senders.js +0 -1
  97. package/dist/mail/smtp.d.ts +1 -31
  98. package/dist/net/address.d.ts +1 -8
  99. package/dist/net/address.js +1 -18
  100. package/dist/net/index.d.ts +1 -1
  101. package/dist/net/index.js +1 -1
  102. package/dist/net/local-http-probe.js +1 -1
  103. package/dist/net/local-http-request.js +1 -1
  104. package/dist/process-probes.d.ts +36 -0
  105. package/dist/process-probes.js +151 -0
  106. package/dist/process-top-footprint.d.ts +7 -0
  107. package/dist/process-top-footprint.js +30 -0
  108. package/dist/process.d.ts +29 -31
  109. package/dist/process.js +18 -196
  110. package/dist/proxy-env.d.ts +12 -3
  111. package/dist/proxy-env.js +9 -8
  112. package/dist/resource-paths.d.ts +15 -3
  113. package/dist/resource-paths.js +7 -5
  114. package/dist/sandbox-env.d.ts +26 -5
  115. package/dist/sandbox-env.js +7 -7
  116. package/dist/secrets/credential-sets/contracts.d.ts +0 -1
  117. package/dist/secrets/credential-sets/contracts.js +0 -1
  118. package/dist/secrets/credential-sets/index.d.ts +2 -3
  119. package/dist/secrets/credential-sets/index.js +1 -1
  120. package/dist/secrets/credential-sets/provider-matches.d.ts +1 -1
  121. package/dist/secrets/credential-sets/provider-matches.js +1 -1
  122. package/dist/secrets/credential-sets/vault-archive.d.ts +1 -1
  123. package/dist/secrets/credential-sets/vault-archive.js +14 -8
  124. package/dist/secrets/credential-sets/vault.aad.d.ts +1 -1
  125. package/dist/secrets/credential-sets/vault.meta.d.ts +1 -1
  126. package/dist/secrets/credential-sets/vault.meta.js +1 -1
  127. package/dist/secrets/credential-sets/vault.repo.memory.d.ts +1 -1
  128. package/dist/secrets/credential-sets/vault.repo.memory.js +1 -1
  129. package/dist/secrets/credential-sets/vault.reseal-refused.d.ts +23 -0
  130. package/dist/secrets/credential-sets/vault.reseal-refused.js +36 -0
  131. package/dist/secrets/credential-sets/vault.service.d.ts +25 -5
  132. package/dist/secrets/credential-sets/vault.service.js +42 -8
  133. package/dist/secrets/index.d.ts +0 -3
  134. package/dist/secrets/index.js +5 -0
  135. package/dist/secrets/keyring.env.d.ts +1 -1
  136. package/dist/secrets/legacy-owner.d.ts +61 -0
  137. package/dist/secrets/legacy-owner.js +196 -0
  138. package/dist/secrets/root-key/decide.d.ts +89 -0
  139. package/dist/secrets/root-key/decide.js +60 -0
  140. package/dist/secrets/sealer-contract.d.ts +19 -0
  141. package/dist/secrets/sealer-contract.js +37 -0
  142. package/dist/secrets/secret-sealer.aesgcm.d.ts +1 -1
  143. package/dist/secrets/testing.d.ts +1 -0
  144. package/dist/secrets/testing.js +1 -0
  145. package/dist/shell.d.ts +4 -1
  146. package/dist/shell.js +1 -1
  147. package/dist/system.d.ts +6 -0
  148. package/dist/system.js +9 -0
  149. package/dist/terminal.d.ts +11 -96
  150. package/dist/terminal.js +80 -56
  151. package/dist/web/agent-tools.d.ts +107 -0
  152. package/dist/web/agent-tools.js +49 -0
  153. package/dist/web/index.d.ts +1 -0
  154. package/dist/web/index.js +1 -0
  155. package/package.json +38 -12
  156. package/dist/http/guarded/ports.d.ts +0 -56
  157. package/dist/http/guarded/types.d.ts +0 -8
  158. package/dist/http/guarded/types.js +0 -2
  159. package/dist/mail/email-sender.d.ts +0 -109
  160. package/dist/mail/email-sender.js +0 -10
  161. package/dist/net/endpoint-policy.d.ts +0 -39
  162. package/dist/net/endpoint-policy.js +0 -218
  163. package/dist/secrets/credential-sets/aad.d.ts +0 -7
  164. package/dist/secrets/credential-sets/aad.js +0 -7
  165. package/dist/secrets/credential-sets/repo.memory.d.ts +0 -44
  166. package/dist/secrets/credential-sets/repo.memory.js +0 -80
  167. package/dist/secrets/credential-sets/vault.types.d.ts +0 -27
  168. package/dist/secrets/credential-sets/vault.types.js +0 -49
  169. /package/dist/{http/guarded → mail/activity}/ports.js +0 -0
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @file The closed vocabularies of a mail activity ledger's derived columns: what happened to a
3
+ * send (`outcome`) and which owner sent it (`use`). They are runtime values because the activity
4
+ * operation validates caller input against them; a SQL repo only needs their types.
5
+ */
6
+ export const MAIL_ACTIVITY_OUTCOMES = ["accepted", "delivered", "bounced", "complained", "suppressed", "deferred", "failed", "unknown", "captured"];
7
+ export const MAIL_ACTIVITY_USES = ["sign_in", "newsletter_confirmation", "form_notification", "newsletter", "test", "unknown"];
8
+ //# sourceMappingURL=vocabulary.js.map
@@ -1,13 +1,14 @@
1
1
  /**
2
2
  * @file The two built-in mail providers: `smtp` (any mailbox/relay) and `console` (local only).
3
3
  *
4
- * SMTP gets its transport from the host (nodemailer is never loaded by this package); console logs
5
- * each message with its body (the local preview of sign-in/confirmation links) and reports
4
+ * SMTP gets its transport from the host (nodemailer is never loaded by this package); console hands
5
+ * each message to an explicit host preview (including sign-in/confirmation links) and reports
6
6
  * `hosted: false`, so it can never make a site look configured.
7
7
  */
8
8
  import { type Clock } from "@jini-ai/core/primitives";
9
9
  import type { MailProviderModule } from "./provider.js";
10
- import { type SmtpTransport } from "./smtp.js";
10
+ import { type SmtpTransport } from "@jini-ai/core/contracts/mail";
11
+ import type { OutboundEmail } from './types.js';
11
12
  /**
12
13
  * SMTP endpoint packed into a credential `baseUrl` (`https://host:port`); 443/465 = implicit TLS.
13
14
  * @complexity O(1).
@@ -31,9 +32,14 @@ export declare function createSmtpMailProvider(required: {
31
32
  }) => SmtpTransport;
32
33
  clock: Clock;
33
34
  }): MailProviderModule;
35
+ /** No email is delivered locally: the preview must expose usable sign-in and confirmation links.
36
+ * Local mail receipts require the host preview to accept the complete message first.
37
+ * Preview errors propagate; no receipt claims a message was previewed when the host failed.
38
+ * @complexity O(1) per message beyond the host callback; batches remain sequential. */
34
39
  export declare function createConsoleMailProvider(required: {
35
40
  clock: Clock;
36
- }, optional?: {
37
- log?: (line: string) => void;
38
- }): MailProviderModule;
41
+ preview: (required: {
42
+ message: OutboundEmail;
43
+ }) => void | Promise<void>;
44
+ }, _optional?: Record<string, never>): MailProviderModule;
39
45
  //# sourceMappingURL=builtin-providers.d.ts.map
@@ -1,13 +1,14 @@
1
1
  /**
2
2
  * @file The two built-in mail providers: `smtp` (any mailbox/relay) and `console` (local only).
3
3
  *
4
- * SMTP gets its transport from the host (nodemailer is never loaded by this package); console logs
5
- * each message with its body (the local preview of sign-in/confirmation links) and reports
4
+ * SMTP gets its transport from the host (nodemailer is never loaded by this package); console hands
5
+ * each message to an explicit host preview (including sign-in/confirmation links) and reports
6
6
  * `hosted: false`, so it can never make a site look configured.
7
7
  */
8
8
  import { nowIso } from "@jini-ai/core/primitives";
9
9
  import { effectivePort } from "../core/effective-port.js";
10
10
  import { SmtpMailerAdapter } from "./smtp.js";
11
+ import {} from "@jini-ai/core/contracts/mail";
11
12
  /**
12
13
  * SMTP endpoint packed into a credential `baseUrl` (`https://host:port`); 443/465 = implicit TLS.
13
14
  * @complexity O(1).
@@ -30,19 +31,21 @@ export function createSmtpMailProvider(required) {
30
31
  },
31
32
  };
32
33
  }
33
- export function createConsoleMailProvider(required, optional = {}) {
34
- const log = optional.log ?? ((line) => console.log(line));
34
+ /** No email is delivered locally: the preview must expose usable sign-in and confirmation links.
35
+ * Local mail receipts require the host preview to accept the complete message first.
36
+ * Preview errors propagate; no receipt claims a message was previewed when the host failed.
37
+ * @complexity O(1) per message beyond the host callback; batches remain sequential. */
38
+ export function createConsoleMailProvider(required, _optional = {}) {
39
+ if (typeof required.preview !== 'function')
40
+ throw new TypeError('A local mail preview callback is required.');
35
41
  let counter = 0;
36
42
  const mailer = {
37
43
  capabilities: () => ({ driver: "console", supportsIdempotencyKey: false, supportsWebhookFeedback: false, maxBatchSize: 1, supportsAttachments: true }),
38
44
  async send({ message }) {
39
- counter += 1;
40
- // The body is the point of a local mailer: a sign-in or confirmation link must be usable from the
41
- // log, since nothing is delivered. Text is preferred (readable); an html-only message shows its html.
42
- const body = message.text ?? message.html;
43
- const bodySuffix = body === undefined ? "" : `\n${body}`;
44
- log(`[mail:console] to=${message.to.email} subject=${JSON.stringify(message.subject)}${bodySuffix}`);
45
- return { ok: true, providerMessageId: `console-${counter}`, acceptedAt: nowIso({ clock: required.clock }) };
45
+ const receipt = ++counter;
46
+ // This is intentional mail delivery to a host preview, separate from safe diagnostics.
47
+ await required.preview({ message });
48
+ return { ok: true, providerMessageId: `console-${receipt}`, acceptedAt: nowIso({ clock: required.clock }) };
46
49
  },
47
50
  async sendBatch({ messages, ...delivery }) {
48
51
  const results = [];
@@ -4,6 +4,7 @@
4
4
  * The purpose gate still wraps the whole mailer at composition; this policy sits inside it.
5
5
  */
6
6
  import { createMailDeliveryPolicy } from "./policy.js";
7
+ import { createConsoleLogger } from '@jini-ai/core/primitives';
7
8
  import { createMailLaneLimiter } from "./rate-limit.js";
8
9
  const CAPTURE_UNAVAILABLE = { ok: false, retryable: false, errorCode: "MAIL_TEST_CAPTURE_UNAVAILABLE", message: "mail test mode is set to capture, but no capture store is available; nothing was sent" };
9
10
  /** Maps settings to policy test mode; null means capture was requested without a sink. */
@@ -34,7 +35,7 @@ function createResultObserver(required, optional) {
34
35
  return;
35
36
  observationWarned = true;
36
37
  try {
37
- (optional.warn ?? console.warn)("[mail] activity observation failed");
38
+ (optional.warn ?? ((message) => createConsoleLogger({ prefix: '' }).warn({ message })))("[mail] activity observation failed");
38
39
  }
39
40
  catch { /* Diagnostics cannot reject a send. */ }
40
41
  }
@@ -1,5 +1,5 @@
1
1
  import { type ProviderRegistry } from "@jini-ai/core/provider-registry";
2
- import { type EmailSender, type EmailSenderContext, type EmailSourceSummary } from "./email-sender.js";
2
+ import { type EmailSender, type EmailSenderContext, type EmailSourceSummary } from "@jini-ai/core/contracts/mail";
3
3
  /** Shares the existing keyed-registry admission rules; no plugin contribution category is added. */
4
4
  export type EmailSenderRegistry = ProviderRegistry<EmailSender>;
5
5
  /** Creates an isolated registry, throwing on invalid ids or duplicate built-in senders.
@@ -1,5 +1,5 @@
1
1
  import { createProviderRegistry } from "@jini-ai/core/provider-registry";
2
- import { EmailSenderError } from "./email-sender.js";
2
+ import { EmailSenderError, } from "@jini-ai/core/contracts/mail";
3
3
  /** Creates an isolated registry, throwing on invalid ids or duplicate built-in senders.
4
4
  * @complexity O(s) registrations for s senders; keyed lookup remains O(1). */
5
5
  export function createEmailSenderRegistry(required, _optional = {}) {
@@ -0,0 +1,186 @@
1
+ /**
2
+ * @module email-template-operations
3
+ *
4
+ * The ONE set of email-template operations — create, edit, rename, list, get, preview and the send
5
+ * render — that every surface of a host (its admin routes, its agent tools) calls. Permission checks
6
+ * stay with those callers.
7
+ *
8
+ * Storage is a host port ({@link EmailTemplateStore}): the host decides where a template lives and
9
+ * how its html body is written (compare-and-set writes, revision history, trash). These operations
10
+ * own input validation, version conditioning, paging and the summary/detail/preview shapes.
11
+ *
12
+ * A template's subject and fields live in its one html body, not in extra columns, so an agent edits
13
+ * a template with full-document writes. The pure renders live in `./email-template.js`.
14
+ */
15
+ import { type EmailFieldValues, type EmailTemplateField, type SendableEmail } from "./email-template.js";
16
+ /** Bounds a template's name; the body is bounded by the host's request body-size limit. */
17
+ export declare const EMAIL_TEMPLATE_NAME_MAX = 200;
18
+ export declare class EmailTemplateNotFoundError extends Error {
19
+ }
20
+ /** The caller's input is malformed; the message says how to fix it. */
21
+ export declare class EmailTemplateInputError extends Error {
22
+ }
23
+ /** `expectedVersion` no longer matches, or another writer landed mid-write. Re-read and retry. */
24
+ export declare class EmailTemplateVersionConflictError extends Error {
25
+ }
26
+ /** A live template as the host's store holds it. */
27
+ export interface EmailTemplateRecord {
28
+ id: string;
29
+ name: string;
30
+ html: string;
31
+ version: number;
32
+ updatedAt: string;
33
+ }
34
+ /** A template's html body opened for one conditioned write. */
35
+ export interface EmailTemplateHtmlSession {
36
+ /**
37
+ * The version the write is conditioned on; a stated `expectedVersion` must equal it. `null` when
38
+ * the store captured none: no stated `expectedVersion` can then match, so only an unconditioned edit proceeds.
39
+ */
40
+ version: number | null;
41
+ /** Compare-and-set write of the whole html; resolves `false` when another writer landed first. */
42
+ write(args: {
43
+ html: string;
44
+ }): Promise<boolean>;
45
+ }
46
+ /** The host's template storage. */
47
+ export interface EmailTemplateStore {
48
+ /** The live template `id`, or `null` (missing, trashed, another kind, not yet html). */
49
+ find(args: {
50
+ id: string;
51
+ }): Promise<EmailTemplateRecord | null>;
52
+ /** Atomically creates a template named `name` whose html body is born from `seedHtml`; returns it. */
53
+ create(args: {
54
+ name: string;
55
+ seedHtml: string;
56
+ actorId: string;
57
+ }): Promise<EmailTemplateRecord>;
58
+ /** Opens a live template's html body for one conditioned write. */
59
+ openHtml(args: {
60
+ id: string;
61
+ actorId: string;
62
+ }): Promise<EmailTemplateHtmlSession>;
63
+ /** Renames the template if it is still at `ifVersion`; resolves `false` when another writer landed first. */
64
+ rename(args: {
65
+ id: string;
66
+ name: string;
67
+ ifVersion: number;
68
+ }): Promise<boolean>;
69
+ /**
70
+ * Up to `limit` entries, most recently updated first (id breaking ties), strictly after the
71
+ * `before` position. An entry that is not a live template comes back as `null` and still counts.
72
+ */
73
+ listPage(args: {
74
+ limit: number;
75
+ before?: {
76
+ updatedAt: string;
77
+ id: string;
78
+ };
79
+ }): Promise<Array<EmailTemplateRecord | null>>;
80
+ }
81
+ export interface EmailTemplateSummary {
82
+ id: string;
83
+ name: string;
84
+ subject: string;
85
+ fields: EmailTemplateField[];
86
+ version: number;
87
+ updatedAt: string;
88
+ }
89
+ export interface EmailTemplateDetail extends EmailTemplateSummary {
90
+ html: string;
91
+ /** `{{field}}`s the HTML uses that `<meta name="email-fields">` does not declare. */
92
+ undeclaredFields: string[];
93
+ }
94
+ export interface EmailTemplatePreview {
95
+ subject: string;
96
+ html: string;
97
+ missingFields: string[];
98
+ undeclaredFields: string[];
99
+ /** `"admin"` keeps scripts (render in a sandboxed preview iframe); `"sent"` is the static email. */
100
+ mode: "admin" | "sent";
101
+ scriptsStripped: boolean;
102
+ /** The plain-text alternative, `"sent"` mode only. */
103
+ text?: string;
104
+ }
105
+ /** A required, trimmed, bounded string. */
106
+ export declare function requireText({ value, key, max }: {
107
+ value: unknown;
108
+ key: string;
109
+ max: number;
110
+ }, _options?: {}): string;
111
+ /** Field values: strings, numbers and booleans (stringified); anything else is refused. */
112
+ export declare function readFieldValues({ value }: {
113
+ value: unknown;
114
+ }, _options?: {}): Record<string, string>;
115
+ /**
116
+ * Creates a template; the store births its html body from the seed.
117
+ * @param required.input - `{ name, html?, subject?, fields? }`; with no `html`, a starter email is
118
+ * built from `subject` (default: the name) and `fields`.
119
+ * @throws {EmailTemplateInputError} For a missing name or malformed fields/html.
120
+ */
121
+ export declare function createEmailTemplate({ store, input, actorId }: {
122
+ store: EmailTemplateStore;
123
+ input: Record<string, unknown>;
124
+ actorId: string;
125
+ }, _options?: {}): Promise<EmailTemplateDetail>;
126
+ /**
127
+ * Replaces a template's whole HTML through the store's compare-and-set write.
128
+ * @param required.input - `{ id, html, expectedVersion? }`; a stated `expectedVersion` must be the
129
+ * version the write is actually conditioned on, or nothing is written.
130
+ * @throws {EmailTemplateNotFoundError} When `id` is not a live template.
131
+ * @throws {EmailTemplateVersionConflictError} On a stale `expectedVersion` or a concurrent write.
132
+ */
133
+ export declare function editEmailTemplate({ store, input, actorId }: {
134
+ store: EmailTemplateStore;
135
+ input: Record<string, unknown>;
136
+ actorId: string;
137
+ }, _options?: {}): Promise<EmailTemplateDetail>;
138
+ /**
139
+ * Renames a template: only its name changes, through the store's compare-and-set rename, so the
140
+ * HTML body and its revision history are untouched.
141
+ * @param required.input - `{ id, name, expectedVersion? }`.
142
+ * @throws {EmailTemplateNotFoundError} When `id` is not a live template.
143
+ * @throws {EmailTemplateVersionConflictError} On a stale `expectedVersion` or a concurrent write.
144
+ */
145
+ export declare function renameEmailTemplate({ store, input }: {
146
+ store: EmailTemplateStore;
147
+ input: Record<string, unknown>;
148
+ }, _options?: {}): Promise<EmailTemplateDetail>;
149
+ /** Every live template, most recently updated first. */
150
+ export declare function listEmailTemplates({ store, input }: {
151
+ store: EmailTemplateStore;
152
+ input?: {
153
+ limit?: unknown;
154
+ cursor?: unknown;
155
+ };
156
+ }, _options?: {}): Promise<{
157
+ templates: EmailTemplateSummary[];
158
+ nextCursor?: string;
159
+ }>;
160
+ /** One template with its HTML; `version` is the basis an edit states back as `expectedVersion`. */
161
+ export declare function getEmailTemplate({ store, id }: {
162
+ store: EmailTemplateStore;
163
+ id: string;
164
+ }, _options?: {}): Promise<EmailTemplateDetail>;
165
+ /**
166
+ * Renders a template with `{{field}}` values for the live preview. `"admin"` mode fills declared
167
+ * samples for missing values and keeps scripts (the host's preview iframe sandboxes them);
168
+ * `"sent"` mode is exactly {@link renderEmailTemplateForSend}'s output, samples unused.
169
+ * @param required.input - `{ id } | { html }`, plus `values?` and `mode?`.
170
+ */
171
+ export declare function previewEmailTemplate({ store, input }: {
172
+ store: EmailTemplateStore;
173
+ input: Record<string, unknown>;
174
+ }, _options?: {}): Promise<EmailTemplatePreview>;
175
+ /**
176
+ * The send-path operation: a saved template + values -> the `subject`/`html`/`text` an outbound
177
+ * email carries (static HTML; see `renderEmailForSend`). It sends nothing; a mail send path
178
+ * spreads the result into its message alongside `to`/`from`.
179
+ * @param required.values - Field values; a field with none renders empty and is listed in `missingFields`.
180
+ */
181
+ export declare function renderEmailTemplateForSend({ store, id, values }: {
182
+ store: EmailTemplateStore;
183
+ id: string;
184
+ values: EmailFieldValues;
185
+ }, _options?: {}): Promise<SendableEmail>;
186
+ //# sourceMappingURL=email-template-operations.d.ts.map
@@ -0,0 +1,226 @@
1
+ /**
2
+ * @module email-template-operations
3
+ *
4
+ * The ONE set of email-template operations — create, edit, rename, list, get, preview and the send
5
+ * render — that every surface of a host (its admin routes, its agent tools) calls. Permission checks
6
+ * stay with those callers.
7
+ *
8
+ * Storage is a host port ({@link EmailTemplateStore}): the host decides where a template lives and
9
+ * how its html body is written (compare-and-set writes, revision history, trash). These operations
10
+ * own input validation, version conditioning, paging and the summary/detail/preview shapes.
11
+ *
12
+ * A template's subject and fields live in its one html body, not in extra columns, so an agent edits
13
+ * a template with full-document writes. The pure renders live in `./email-template.js`.
14
+ */
15
+ import { emailTemplateSkeleton, parseFieldDeclarations, readTemplateDeclarations, renderEmailForSend, renderEmailPreview, undeclaredFieldsIn, } from "./email-template.js";
16
+ /** Bounds a template's name; the body is bounded by the host's request body-size limit. */
17
+ export const EMAIL_TEMPLATE_NAME_MAX = 200;
18
+ export class EmailTemplateNotFoundError extends Error {
19
+ }
20
+ /** The caller's input is malformed; the message says how to fix it. */
21
+ export class EmailTemplateInputError extends Error {
22
+ }
23
+ /** `expectedVersion` no longer matches, or another writer landed mid-write. Re-read and retry. */
24
+ export class EmailTemplateVersionConflictError extends Error {
25
+ }
26
+ async function loadTemplate({ store, id }, _options = {}) {
27
+ const record = await store.find({ id });
28
+ if (record === null)
29
+ throw new EmailTemplateNotFoundError(`email template '${id}' was not found`);
30
+ return record;
31
+ }
32
+ function toSummary(record, _options = {}) {
33
+ const declarations = readTemplateDeclarations({ html: record.html });
34
+ return { id: record.id, name: record.name, subject: declarations.subject, fields: declarations.fields, version: record.version, updatedAt: record.updatedAt };
35
+ }
36
+ function toDetail(record, _options = {}) {
37
+ const summary = toSummary(record);
38
+ return { ...summary, html: record.html, undeclaredFields: undeclaredFieldsIn({ html: record.html, declarations: summary }) };
39
+ }
40
+ /** A required, trimmed, bounded string. */
41
+ export function requireText({ value, key, max }, _options = {}) {
42
+ const text = typeof value === "string" ? value.trim() : "";
43
+ if (!text)
44
+ throw new EmailTemplateInputError(`${key} is required and must be a non-empty string.`);
45
+ if (text.length > max)
46
+ throw new EmailTemplateInputError(`${key} must be at most ${max} characters.`);
47
+ return text;
48
+ }
49
+ /** An optional string; `undefined` when absent. */
50
+ function optionalString({ value, key }, _options = {}) {
51
+ if (value === undefined)
52
+ return undefined;
53
+ if (typeof value !== "string")
54
+ throw new EmailTemplateInputError(`${key} must be a string.`);
55
+ return value;
56
+ }
57
+ /** Field values: strings, numbers and booleans (stringified); anything else is refused. */
58
+ export function readFieldValues({ value }, _options = {}) {
59
+ if (value === undefined)
60
+ return {};
61
+ if (value === null || typeof value !== "object" || Array.isArray(value))
62
+ throw new EmailTemplateInputError("values must be an object of field name to text.");
63
+ const out = {};
64
+ for (const [name, raw] of Object.entries(value)) {
65
+ if (!["string", "number", "boolean"].includes(typeof raw))
66
+ throw new EmailTemplateInputError(`values.${name} must be text, a number or a boolean.`);
67
+ out[name] = String(raw);
68
+ }
69
+ return out;
70
+ }
71
+ /** Field declarations from either a list of names / `{name, sample}` objects, or the meta `content` string form. */
72
+ function readFieldsInput({ value }, _options = {}) {
73
+ if (value === undefined)
74
+ return [];
75
+ if (typeof value === "string")
76
+ return parseFieldDeclarations({ content: value });
77
+ if (!Array.isArray(value))
78
+ throw new EmailTemplateInputError("fields must be a list of field names.");
79
+ const entries = value.map((entry) => (typeof entry === "string" ? entry : formatFieldObject({ entry: entry })));
80
+ return parseFieldDeclarations({ content: entries.join(",") });
81
+ }
82
+ function formatFieldObject({ entry }, _options = {}) {
83
+ const record = (entry ?? {});
84
+ if (typeof record.name !== "string")
85
+ throw new EmailTemplateInputError("each field must be a name or {name, sample}.");
86
+ if (record.name.includes(",") || record.name.includes("="))
87
+ throw new EmailTemplateInputError("field names cannot contain commas or equals signs.");
88
+ if (typeof record.sample === "string" && record.sample.includes(","))
89
+ throw new EmailTemplateInputError("field samples cannot contain commas.");
90
+ return typeof record.sample === "string" ? `${record.name}=${record.sample}` : record.name;
91
+ }
92
+ function readExpectedVersion({ value }, _options = {}) {
93
+ if (value === undefined)
94
+ return undefined;
95
+ if (!Number.isInteger(value) || value < 1)
96
+ throw new EmailTemplateInputError("expectedVersion must be the positive integer version a read returned.");
97
+ return value;
98
+ }
99
+ /**
100
+ * Creates a template; the store births its html body from the seed.
101
+ * @param required.input - `{ name, html?, subject?, fields? }`; with no `html`, a starter email is
102
+ * built from `subject` (default: the name) and `fields`.
103
+ * @throws {EmailTemplateInputError} For a missing name or malformed fields/html.
104
+ */
105
+ export async function createEmailTemplate({ store, input, actorId }, _options = {}) {
106
+ const name = requireText({ value: input.name, key: "name", max: EMAIL_TEMPLATE_NAME_MAX });
107
+ const html = optionalString({ value: input.html, key: "html" });
108
+ const subject = optionalString({ value: input.subject, key: "subject" }) ?? name;
109
+ const seed = html ?? emailTemplateSkeleton({ subject, fields: readFieldsInput({ value: input.fields }) });
110
+ return toDetail(await store.create({ name, seedHtml: seed, actorId }));
111
+ }
112
+ /**
113
+ * Replaces a template's whole HTML through the store's compare-and-set write.
114
+ * @param required.input - `{ id, html, expectedVersion? }`; a stated `expectedVersion` must be the
115
+ * version the write is actually conditioned on, or nothing is written.
116
+ * @throws {EmailTemplateNotFoundError} When `id` is not a live template.
117
+ * @throws {EmailTemplateVersionConflictError} On a stale `expectedVersion` or a concurrent write.
118
+ */
119
+ export async function editEmailTemplate({ store, input, actorId }, _options = {}) {
120
+ const id = requireText({ value: input.id, key: "id", max: EMAIL_TEMPLATE_NAME_MAX });
121
+ const html = requireText({ value: input.html, key: "html", max: Number.MAX_SAFE_INTEGER });
122
+ const expectedVersion = readExpectedVersion({ value: input.expectedVersion });
123
+ await loadTemplate({ store: store, id: id });
124
+ const session = await store.openHtml({ id, actorId });
125
+ const basis = session.version;
126
+ if (expectedVersion !== undefined && expectedVersion !== basis) {
127
+ throw new EmailTemplateVersionConflictError(`email template '${id}' is at version ${basis}, not ${expectedVersion} — re-read it and retry`);
128
+ }
129
+ if (!(await session.write({ html })))
130
+ throw new EmailTemplateVersionConflictError(`email template '${id}' was edited elsewhere — re-read it and retry`);
131
+ return toDetail(await loadTemplate({ store: store, id: id }));
132
+ }
133
+ /**
134
+ * Renames a template: only its name changes, through the store's compare-and-set rename, so the
135
+ * HTML body and its revision history are untouched.
136
+ * @param required.input - `{ id, name, expectedVersion? }`.
137
+ * @throws {EmailTemplateNotFoundError} When `id` is not a live template.
138
+ * @throws {EmailTemplateVersionConflictError} On a stale `expectedVersion` or a concurrent write.
139
+ */
140
+ export async function renameEmailTemplate({ store, input }, _options = {}) {
141
+ const id = requireText({ value: input.id, key: "id", max: EMAIL_TEMPLATE_NAME_MAX });
142
+ const name = requireText({ value: input.name, key: "name", max: EMAIL_TEMPLATE_NAME_MAX });
143
+ const expectedVersion = readExpectedVersion({ value: input.expectedVersion });
144
+ const record = await loadTemplate({ store: store, id: id });
145
+ if (expectedVersion !== undefined && expectedVersion !== record.version) {
146
+ throw new EmailTemplateVersionConflictError(`email template '${id}' is at version ${record.version}, not ${expectedVersion} — re-read it and retry`);
147
+ }
148
+ if (!(await store.rename({ id, name, ifVersion: record.version })))
149
+ throw new EmailTemplateVersionConflictError(`email template '${id}' was edited elsewhere — re-read it and retry`);
150
+ return toDetail(await loadTemplate({ store: store, id: id }));
151
+ }
152
+ /** Every live template, most recently updated first. */
153
+ export async function listEmailTemplates({ store, input = {} }, _options = {}) {
154
+ const limit = templatePageLimit({ value: input.limit });
155
+ const before = readTemplateCursor({ value: input.cursor });
156
+ const rows = await store.listPage({ limit: limit + 1, ...(before ? { before } : {}) });
157
+ const page = rows.slice(0, limit).filter((row) => row !== null);
158
+ const last = page.at(-1);
159
+ const nextCursor = rows.length > limit && last ? Buffer.from(JSON.stringify({ updatedAt: last.updatedAt, id: last.id })).toString("base64url") : undefined;
160
+ return { templates: page.map(row => toSummary(row)), ...(nextCursor ? { nextCursor } : {}) };
161
+ }
162
+ /** Bounded list size, shared by the route and tool inputs. */
163
+ function templatePageLimit({ value }, _options = {}) {
164
+ const limit = value === undefined ? 25 : Number(value);
165
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100)
166
+ throw new EmailTemplateInputError("limit must be a whole number from 1 to 100.");
167
+ return limit;
168
+ }
169
+ /** Only a timestamp/id pair from this list is accepted as a continuation. */
170
+ function readTemplateCursor({ value }, _options = {}) {
171
+ if (value === undefined)
172
+ return undefined;
173
+ try {
174
+ const parsed = JSON.parse(Buffer.from(String(value), "base64url").toString());
175
+ if (typeof parsed.updatedAt === "string" && typeof parsed.id === "string")
176
+ return { updatedAt: parsed.updatedAt, id: parsed.id };
177
+ }
178
+ catch { /* The same typed refusal covers malformed and structurally invalid tokens. */ }
179
+ throw new EmailTemplateInputError("cursor must be a nextCursor returned by email_template_list.");
180
+ }
181
+ /** One template with its HTML; `version` is the basis an edit states back as `expectedVersion`. */
182
+ export async function getEmailTemplate({ store, id }, _options = {}) {
183
+ return toDetail(await loadTemplate({ store: store, id: id }));
184
+ }
185
+ /** The HTML a preview renders: a saved template's, or unsaved HTML straight from the editor. */
186
+ async function previewSource({ store, input }, _options = {}) {
187
+ if (input.html !== undefined)
188
+ return requireText({ value: input.html, key: "html", max: Number.MAX_SAFE_INTEGER });
189
+ return (await loadTemplate({ store: store, id: requireText({ value: input.id, key: "id", max: EMAIL_TEMPLATE_NAME_MAX }) })).html;
190
+ }
191
+ function readMode({ value }, _options = {}) {
192
+ if (value === undefined || value === "admin")
193
+ return "admin";
194
+ if (value === "sent")
195
+ return "sent";
196
+ throw new EmailTemplateInputError('mode must be "admin" or "sent".');
197
+ }
198
+ /**
199
+ * Renders a template with `{{field}}` values for the live preview. `"admin"` mode fills declared
200
+ * samples for missing values and keeps scripts (the host's preview iframe sandboxes them);
201
+ * `"sent"` mode is exactly {@link renderEmailTemplateForSend}'s output, samples unused.
202
+ * @param required.input - `{ id } | { html }`, plus `values?` and `mode?`.
203
+ */
204
+ export async function previewEmailTemplate({ store, input }, _options = {}) {
205
+ const mode = readMode({ value: input.mode });
206
+ const values = readFieldValues({ value: input.values });
207
+ const html = await previewSource({ store, input });
208
+ const undeclaredFields = undeclaredFieldsIn({ html, declarations: readTemplateDeclarations({ html }) });
209
+ if (mode === "sent") {
210
+ const sent = renderEmailForSend({ html, values });
211
+ return { ...sent, undeclaredFields, mode, scriptsStripped: true };
212
+ }
213
+ // Scripts are kept: the host shows this preview in a preview iframe sandboxed without
214
+ // `allow-same-origin`, so they run in an opaque origin; `scriptsStripped: false` says so.
215
+ return { ...renderEmailPreview({ html, values }), undeclaredFields, mode, scriptsStripped: false };
216
+ }
217
+ /**
218
+ * The send-path operation: a saved template + values -> the `subject`/`html`/`text` an outbound
219
+ * email carries (static HTML; see `renderEmailForSend`). It sends nothing; a mail send path
220
+ * spreads the result into its message alongside `to`/`from`.
221
+ * @param required.values - Field values; a field with none renders empty and is listed in `missingFields`.
222
+ */
223
+ export async function renderEmailTemplateForSend({ store, id, values }, _options = {}) {
224
+ return renderEmailForSend({ html: (await loadTemplate({ store: store, id: id })).html, values });
225
+ }
226
+ //# sourceMappingURL=email-template-operations.js.map
@@ -0,0 +1,120 @@
1
+ /** The `<meta name>` a template declares its fill-in fields with. */
2
+ export declare const EMAIL_FIELDS_META_NAME = "email-fields";
3
+ export interface EmailTemplateField {
4
+ name: string;
5
+ /** Shown by the preview when the caller gives no value for this field. */
6
+ sample?: string;
7
+ }
8
+ export interface EmailTemplateDeclarations {
9
+ /** The raw `<title>` text, placeholders unfilled; `""` when the template has none. */
10
+ subject: string;
11
+ fields: EmailTemplateField[];
12
+ }
13
+ export type EmailFieldValues = Readonly<Record<string, string>>;
14
+ export interface FilledText {
15
+ text: string;
16
+ /** Placeholders the values did not cover, in first-use order; each was rendered empty. */
17
+ missingFields: string[];
18
+ }
19
+ /** The `{{field}}` names a string uses, de-duplicated in first-use order. */
20
+ export declare function placeholdersIn({ text }: {
21
+ text: string;
22
+ }, _optional?: Record<string, never>): string[];
23
+ /** Escapes a value for HTML text AND quoted-attribute context. */
24
+ export declare function escapeHtml({ value }: {
25
+ value: string;
26
+ }, _optional?: Record<string, never>): string;
27
+ /**
28
+ * Replaces every `{{field}}` with its value. An unknown field renders empty — never the literal
29
+ * braces a recipient would see — and is reported so the caller can refuse or warn.
30
+ * @param required.escape - Applied to every value: {@link escapeHtml} for HTML, identity for a subject.
31
+ * @complexity O(n) in the text length.
32
+ */
33
+ export declare function fillPlaceholders({ text, values, escape: escapeValue }: {
34
+ text: string;
35
+ values: EmailFieldValues;
36
+ escape: (required: {
37
+ value: string;
38
+ }) => string;
39
+ }, _optional?: Record<string, never>): FilledText;
40
+ /** The declared fields from a `content` attribute, first declaration of a name winning. */
41
+ export declare function parseFieldDeclarations({ content }: {
42
+ content: string;
43
+ }, _optional?: Record<string, never>): EmailTemplateField[];
44
+ /** Writes a field list back into the `content` form {@link parseFieldDeclarations} reads. */
45
+ export declare function formatFieldDeclarations({ fields }: {
46
+ fields: readonly EmailTemplateField[];
47
+ }, _optional?: Record<string, never>): string;
48
+ /**
49
+ * Reads a template's subject (`<title>`) and declared fields (`<meta name="email-fields">`).
50
+ * @complexity O(nodes).
51
+ */
52
+ export declare function readTemplateDeclarations({ html }: {
53
+ html: string;
54
+ }, _optional?: Record<string, never>): EmailTemplateDeclarations;
55
+ /** Placeholders used in the HTML (subject included) that the template never declared. */
56
+ export declare function undeclaredFieldsIn({ html, declarations }: {
57
+ html: string;
58
+ declarations: EmailTemplateDeclarations;
59
+ }, _optional?: Record<string, never>): string[];
60
+ /**
61
+ * The static HTML a mail client receives: `<script>`/`<noscript>`/`<template>`, comments, inline
62
+ * `on*` handlers and `javascript:` URLs removed (the shared `stripActiveHtml` policy), then
63
+ * `<iframe>`/`<object>`/`<embed>` (and their legacy kin), obfuscated script URLs and the template's
64
+ * own field declarations. Navigation/form/link elements and non-image data URLs are removed.
65
+ * Inline styles and classes survive: email layout depends on them.
66
+ *
67
+ * Known cost: comments are removed, so Outlook `<!--[if mso]>` conditional blocks do not survive.
68
+ * @complexity O(nodes), two parses.
69
+ */
70
+ export declare function sanitizeEmailHtml({ html }: {
71
+ html: string;
72
+ }, _optional?: Record<string, never>): string;
73
+ /**
74
+ * The plain-text alternative: the shared `htmlToText` (one line per block; head, scripts and styles
75
+ * omitted), with each link's URL written after its text so a text-only reader can still follow it.
76
+ * @complexity O(nodes).
77
+ */
78
+ export declare function emailHtmlToText({ html }: {
79
+ html: string;
80
+ }, _optional?: Record<string, never>): string;
81
+ export interface RenderedEmail {
82
+ subject: string;
83
+ html: string;
84
+ /** Placeholders no value covered, subject and body together; each rendered empty. */
85
+ missingFields: string[];
86
+ }
87
+ /** The values a preview renders with: declared samples, overridden by whatever the caller gave. */
88
+ export declare function previewValues({ declarations, values }: {
89
+ declarations: EmailTemplateDeclarations;
90
+ values: EmailFieldValues;
91
+ }, _optional?: Record<string, never>): Record<string, string>;
92
+ /**
93
+ * The preview render. Scripts are KEPT: show the result only in an iframe sandboxed without
94
+ * `allow-same-origin`, so they run in an opaque origin.
95
+ * @complexity O(n) in the template length.
96
+ */
97
+ export declare function renderEmailPreview({ html, values }: {
98
+ html: string;
99
+ values: EmailFieldValues;
100
+ }, _optional?: Record<string, never>): RenderedEmail;
101
+ export interface SendableEmail extends RenderedEmail {
102
+ /** The plain-text alternative, derived from the sanitized HTML. */
103
+ text: string;
104
+ }
105
+ /**
106
+ * Template + values -> the `subject`/`html`/`text` an `OutboundEmail` carries. Values are filled
107
+ * BEFORE sanitizing, so a value that smuggles a `javascript:` URL into an `href="{{url}}"` is
108
+ * removed with everything else. Samples are never used: a sent email shows only real values.
109
+ * @complexity O(n) in the template length.
110
+ */
111
+ export declare function renderEmailForSend({ html, values }: {
112
+ html: string;
113
+ values: EmailFieldValues;
114
+ }, _optional?: Record<string, never>): SendableEmail;
115
+ /** The starter body a template is born with when its creator gives no HTML. */
116
+ export declare function emailTemplateSkeleton({ subject, fields }: {
117
+ subject: string;
118
+ fields: readonly EmailTemplateField[];
119
+ }, _optional?: Record<string, never>): string;
120
+ //# sourceMappingURL=email-template.d.ts.map