@antelopejs/interface-dms-mailing 0.9.1 → 0.10.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.
package/README.md CHANGED
@@ -1,11 +1,11 @@
1
1
  <div align="center">
2
2
 
3
- # @antelopejs/interface-dms-mailing
3
+ # `@antelopejs/interface-dms-mailing`
4
4
 
5
- <a href="https://www.npmjs.com/package/@antelopejs/interface-dms-mailing"><img alt="npm" src="https://img.shields.io/npm/v/@antelopejs/interface-dms-mailing?style=for-the-badge&labelColor=000000&color=000000"></a>
6
- <a href="./LICENSE"><img alt="License" src="https://img.shields.io/npm/l/@antelopejs/interface-dms-mailing?style=for-the-badge&labelColor=000000&color=000000"></a>
7
- <a href="https://discord.gg/sjK28QHrA7"><img alt="Discord" src="https://img.shields.io/badge/Discord-18181B?logo=discord&style=for-the-badge&color=000000"></a>
8
- <a href="https://dms.antelopejs.com/docs/modules/mailing/extending"><img alt="Documentation" src="https://img.shields.io/badge/Docs-18181B?style=for-the-badge&color=000000"></a>
5
+ <a href="https://www.npmjs.com/package/@antelopejs/interface-dms-mailing"><img alt="npm" src="https://img.shields.io/npm/v/@antelopejs/interface-dms-mailing?style=for-the-badge&labelColor=000000&color=000000" data-illustration></a>
6
+ <a href="./LICENSE"><img alt="License" src="https://img.shields.io/npm/l/@antelopejs/interface-dms-mailing?style=for-the-badge&labelColor=000000&color=000000" data-illustration></a>
7
+ <a href="https://discord.gg/g4pFt6eXqu"><img alt="Discord" src="https://img.shields.io/badge/Discord-18181B?logo=discord&style=for-the-badge&color=000000" data-illustration></a>
8
+ <a href="https://dms.antelopejs.com/docs/modules/mailing/extending"><img alt="Documentation" src="https://img.shields.io/badge/Docs-18181B?style=for-the-badge&color=000000" data-illustration></a>
9
9
 
10
10
  The AntelopeJS interface to send DMS mailing templates and report e-mail events from any module.
11
11
 
@@ -15,7 +15,9 @@ The AntelopeJS interface to send DMS mailing templates and report e-mail events
15
15
 
16
16
  - Sends a published template by its slug, to one recipient or many, in a given locale and with its variables (`SendTemplate`).
17
17
  - Reports a provider event (delivered, opened, clicked, bounced…) against the send it belongs to (`RecordEmailEvent`).
18
- - Ships templates and template categories as code, published and idempotent, without overwriting what a user changed since (`DeclareTemplate`, `DeclareTemplateCategory`), and writes the workspace sender when a workspace is provisioned (`DeclareSender`).
18
+ - Ships templates and template categories as code when a workspace is provisioned (`DeclareTemplate`, `DeclareTemplateCategory`). A declaration writes once: a template is created already published, and a slug or category id the workspace already has is left as it is.
19
+ - Writes the workspace sender when a workspace is provisioned (`DeclareSender`).
20
+ - Sets the workspace webhook secret from code, keeping one the workspace owner set or rotated (`DeclareWebhookSecret`).
19
21
  - Imports past sends and their events with their own dates, for a demo data set or a move from another provider (`ImportSends`).
20
22
  - Exports the template and send types (`Block`, `TemplateContent`, `VariableDefinition`, `SendStatus`, `EmailEvent`…) for code that builds or inspects templates.
21
23
  - Keeps your module independent of the implementation, [`@antelopejs/dms-mailing`](https://www.npmjs.com/package/@antelopejs/dms-mailing).
@@ -30,14 +32,22 @@ pnpm add @antelopejs/interface-dms-mailing
30
32
 
31
33
  ## Quick start
32
34
 
33
- ```ts
35
+ ```ts fragment
34
36
  import { RecordEmailEvent, SendTemplate } from "@antelopejs/interface-dms-mailing";
35
37
 
36
- const result = await SendTemplate("order-confirmation", {
38
+ const result = await SendTemplate("order-confirmed", {
37
39
  tenantId,
38
40
  to: [{ email: "sofie@example.com", name: "Sofie" }],
39
41
  locale: "fr",
40
- variables: { order: { total: "48.00" } },
42
+ variables: {
43
+ customer: { firstName: "Sofie" },
44
+ order: {
45
+ number: "#10482",
46
+ total: { value: 4800, currency: "EUR" },
47
+ lines: [{ name: "Linen shirt", total: { value: 4800, currency: "EUR" } }],
48
+ url: "https://example.com/orders/10482",
49
+ },
50
+ },
41
51
  source: "checkout",
42
52
  });
43
53
 
@@ -49,18 +59,20 @@ await RecordEmailEvent(tenantId, {
49
59
  });
50
60
  ```
51
61
 
52
- A recipient on the workspace's suppression list gets no e-mail: its result has the status `suppressed`. A template whose footer links to an unsubscribe or a preferences page expects `unsubscribeUrl` / `preferencesUrl` in `variables`.
62
+ A recipient on the workspace's suppression list gets no e-mail, and its result has the status `suppressed`. A template whose footer links to an unsubscribe page or a preferences page reads their URLs from `unsubscribeUrl` and `preferencesUrl` in `variables`.
53
63
 
54
64
  ## Compatibility
55
65
 
56
- Interface 0.8 requires `@antelopejs/dms-mailing >=0.6.0`, whose interface dependency is `>=0.8.0 <0.9.0`. This includes `DeclareTemplate`, `DeclareTemplateCategory` and `ImportSends`, all requiring an explicit `tenantId`. Mailing 0.5 remains on interface 0.7. `DeclareSender` needs interface 0.9 and the first release implementing it (`>=0.9.0 <0.10.0`). The interface declares these dependencies:
66
+ A `@antelopejs/dms-mailing` release implements one minor line of this interface. The `@antelopejs/interface-dms-mailing` row of the compatibility block in the [module README](../dms-mailing/README.md#compatibility) gives that range. Use a module release whose range covers the interface release your code imports. `DeclareTemplate`, `DeclareTemplateCategory`, `DeclareSender`, `DeclareWebhookSecret` and `ImportSends` each take an explicit `tenantId`. The interface declares these dependencies:
57
67
 
58
- <!-- docs-compat: ./package.json#dependencies -->
68
+ <!-- antelopejs-docs-compat:start -->
59
69
 
60
- | Package | Range |
61
- | --- | --- |
62
- | `@antelopejs/interface-core` | `>=0.2.4 <1.0.0` |
63
- | `@antelopejs/interface-email` | `>=0.0.6 <1.0.0` |
70
+ | Package | Supported | Tested with |
71
+ | ----------------------------- | ---------------- | ----------- |
72
+ | `@antelopejs/interface-core` | `>=0.4.0 <1.0.0` | `0.4.0` |
73
+ | `@antelopejs/interface-email` | `>=0.0.6 <1.0.0` | `0.0.6` |
74
+
75
+ <!-- antelopejs-docs-compat:end -->
64
76
 
65
77
  ## Documentation
66
78
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,16 @@
1
1
  import type { EmailAddress } from "@antelopejs/interface-email";
2
+ export type JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;
3
+ export type JsonObject = {
4
+ [key: string]: JsonValue;
5
+ };
6
+ export type MoneyValue = {
7
+ value: number;
8
+ currency: string;
9
+ };
10
+ export type TemplateVariableValue = string | number | boolean | null | Date | MoneyValue | TemplateVariableValue[] | TemplateVariables;
11
+ export type TemplateVariables = {
12
+ [name: string]: TemplateVariableValue;
13
+ };
2
14
  export type ConditionOperator = "truthy" | "falsy" | "eq" | "ne" | "gt" | "lt";
3
15
  export interface Condition {
4
16
  path: string;
@@ -83,7 +95,7 @@ export interface SendTemplateParams {
83
95
  tenantId: string;
84
96
  to: EmailAddress | EmailAddress[];
85
97
  locale?: string;
86
- variables?: Record<string, unknown>;
98
+ variables?: TemplateVariables;
87
99
  content?: TemplateContent;
88
100
  source?: string;
89
101
  isTest?: boolean;
@@ -100,7 +112,7 @@ export interface EmailEvent {
100
112
  messageId: string;
101
113
  type: SendEventType;
102
114
  at?: Date;
103
- details?: Record<string, unknown>;
115
+ details?: JsonObject;
104
116
  }
105
117
  export type SendEventType = "queued" | "sent" | "delivered" | "opened" | "clicked" | "bounced" | "spam" | "failed" | "unsubscribed";
106
118
  export type SendStatus = SendEventType | "suppressed";
@@ -115,7 +127,7 @@ export interface TemplateDeclaration {
115
127
  category?: string;
116
128
  content: TemplateContent;
117
129
  variables?: VariableDefinition[];
118
- testData?: Record<string, unknown>;
130
+ testData?: JsonObject;
119
131
  author?: string;
120
132
  }
121
133
  export type DeclarationOutcome = "created" | "kept";
@@ -141,10 +153,19 @@ export interface SenderDeclaration {
141
153
  name?: string;
142
154
  replyTo?: string;
143
155
  }
156
+ export interface WebhookSecretDeclaration {
157
+ tenantId: string;
158
+ secret: string;
159
+ replaceRotated?: boolean;
160
+ }
161
+ export type WebhookSecretOutcome = "set" | "unchanged" | "kept";
162
+ export interface DeclareWebhookSecretResult {
163
+ outcome: WebhookSecretOutcome;
164
+ }
144
165
  export interface ImportedSendEvent {
145
166
  type: SendEventType;
146
167
  at: Date;
147
- details?: Record<string, unknown>;
168
+ details?: JsonObject;
148
169
  }
149
170
  export interface ImportedSend {
150
171
  importId: string;
@@ -152,7 +173,7 @@ export interface ImportedSend {
152
173
  to: EmailAddress;
153
174
  sentAt: Date;
154
175
  locale?: string;
155
- variables?: Record<string, unknown>;
176
+ variables?: JsonObject;
156
177
  provider?: string;
157
178
  providerMessageId?: string;
158
179
  source?: string;
@@ -171,4 +192,5 @@ export interface ImportSendsResult {
171
192
  export declare const DeclareTemplate: (declaration: TemplateDeclaration) => Promise<DeclareTemplateResult>;
172
193
  export declare const DeclareTemplateCategory: (declaration: TemplateCategoryDeclaration) => Promise<DeclareTemplateCategoryResult>;
173
194
  export declare const DeclareSender: (declaration: SenderDeclaration) => Promise<void>;
195
+ export declare const DeclareWebhookSecret: (declaration: WebhookSecretDeclaration) => Promise<DeclareWebhookSecretResult>;
174
196
  export declare const ImportSends: (params: SendImport) => Promise<ImportSendsResult>;
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ImportSends = exports.DeclareSender = exports.DeclareTemplateCategory = exports.DeclareTemplate = exports.LOCALIZED_TEXT_FALLBACK_LOCALE = exports.RecordEmailEvent = exports.SendTemplate = void 0;
3
+ exports.ImportSends = exports.DeclareWebhookSecret = exports.DeclareSender = exports.DeclareTemplateCategory = exports.DeclareTemplate = exports.LOCALIZED_TEXT_FALLBACK_LOCALE = exports.RecordEmailEvent = exports.SendTemplate = void 0;
4
4
  const interface_core_1 = require("@antelopejs/interface-core");
5
5
  exports.SendTemplate = (0, interface_core_1.InterfaceFunction)();
6
6
  exports.RecordEmailEvent = (0, interface_core_1.InterfaceFunction)();
@@ -8,4 +8,5 @@ exports.LOCALIZED_TEXT_FALLBACK_LOCALE = "en";
8
8
  exports.DeclareTemplate = (0, interface_core_1.InterfaceFunction)();
9
9
  exports.DeclareTemplateCategory = (0, interface_core_1.InterfaceFunction)();
10
10
  exports.DeclareSender = (0, interface_core_1.InterfaceFunction)();
11
+ exports.DeclareWebhookSecret = (0, interface_core_1.InterfaceFunction)();
11
12
  exports.ImportSends = (0, interface_core_1.InterfaceFunction)();
package/docs/1.index.md CHANGED
@@ -1,19 +1,16 @@
1
1
  ---
2
2
  title: Mailing interface
3
3
  description: Consumer contract for sending templates and recording provider events with the DMS mailing interface.
4
+ mode: reference
4
5
  ---
5
6
 
6
- # Mailing interface
7
+ `@antelopejs/interface-dms-mailing` exports seven backend functions and the template types below. `SendTemplate` sends, `RecordEmailEvent` reports provider events, `DeclareTemplate`, `DeclareTemplateCategory`, `DeclareSender` and `DeclareWebhookSecret` ship templates, categories, the sender and the webhook secret as code, and `ImportSends` imports past sends. They need `@antelopejs/dms-mailing` and an `@antelopejs/interface-email` provider loaded, and are imported from the interface package, not the runtime module's services.
7
8
 
8
- `@antelopejs/interface-dms-mailing` exposes six backend functions and the template types below: two to send and to report events, three to ship templates, categories and the sender as code, and one to import past sends. Load `@antelopejs/dms-mailing` and an `@antelopejs/interface-email` provider before calling them. Import from the interface package, not the runtime module's services.
9
+ All seven take an explicit `tenantId`. They are trusted backend calls, not permission-checked HTTP endpoints, so the calling module authenticates and authorizes the tenant. A missing implementation or a storage failure rejects the promise.
9
10
 
10
- All six functions take an explicit `tenantId`. They are trusted backend calls, not permission-checked HTTP endpoints: authenticate and authorize the tenant in the calling module. A missing implementation or a storage failure can reject the promise.
11
+ ## Per-recipient results
11
12
 
12
- ## Consume per-recipient results
13
-
14
- Publish an `order-confirmation` template in your authorized tenant, with
15
- `order.total` as a variable. This example performs a real send; use an inbox you
16
- control and supply any additional variables required by your template.
13
+ The example needs a published `order-confirmation` template with an `order.total` variable in an authorized tenant. It sends real e-mails.
17
14
 
18
15
  ```ts docs-check
19
16
  import { SendTemplate } from "@antelopejs/interface-dms-mailing";
@@ -29,23 +26,23 @@ export async function sendOrderConfirmation(tenantId: string, recipients: string
29
26
  }
30
27
  ```
31
28
 
32
- The returned array lets you inspect each recipient separately. For example, a
33
- two-recipient call can return `sent` for one address and `suppressed` for the
34
- other. Do not resend both: the first email may already be on its way, and the
35
- suppressed recipient must not be retried. The **Sends** page records the template
36
- version and locale; provider events later add delivery information.
29
+ The array holds one result per recipient, such as `sent` for one address and `suppressed` for the other. Resending the whole call delivers the first e-mail twice, and the suppressed recipient stays suppressed. The **Sends** page records each send's template version and locale, and provider events add delivery information later.
37
30
 
38
- ## SendTemplate
31
+ ## `SendTemplate`
39
32
 
40
33
  ```ts [Contract]
41
34
  import type { EmailAddress } from "@antelopejs/interface-email";
42
- import type { SendStatus, TemplateContent } from "@antelopejs/interface-dms-mailing";
35
+ import type {
36
+ SendStatus,
37
+ TemplateContent,
38
+ TemplateVariables,
39
+ } from "@antelopejs/interface-dms-mailing";
43
40
 
44
41
  interface SendTemplateParams {
45
42
  tenantId: string;
46
43
  to: EmailAddress | EmailAddress[];
47
44
  locale?: string;
48
- variables?: Record<string, unknown>;
45
+ variables?: TemplateVariables;
49
46
  content?: TemplateContent;
50
47
  source?: string;
51
48
  isTest?: boolean;
@@ -65,28 +62,32 @@ declare function SendTemplate(
65
62
  ): Promise<SendTemplateResult>;
66
63
  ```
67
64
 
68
- `to` accepts an address string or `{ email: string, name?: string }`, or an array of either. The slug resolves within the specified tenant. The template must exist even when `content` overrides its body; a non-test send requires a live template. `content` does not publish or save the override. The locale falls back through the workspace's fallback locale and available content. `source` labels the send log.
65
+ `to` accepts an address string, an `{ email: string, name?: string }` object, or an array of either. The slug resolves within `tenantId`. The template must exist even when `content` overrides its body. A non-test send needs a live template. `content` neither saves nor publishes the override. The locale is the requested one (any case, or its base language), else the workspace's fallback locale, else `en`, else the content's first locale. `source` labels the send log.
69
66
 
70
- The module renders HTML and plain text, uses batch delivery when the provider supports it, and attempts to log one row per recipient. `isTest` marks the send as a test, prefixes its subject, permits a non-live template, and excludes it from production metrics. It does not bypass the suppression list.
67
+ The module renders HTML and plain text, uses batch delivery for several recipients when the provider supports it, and tries to log one row per recipient. With `isTest`, the subject starts with `[TEST] `, the draft is used when there is one, a non-live template is accepted, and production metrics leave the send out. It does not bypass the suppression list.
71
68
 
72
69
  ### Results and failures
73
70
 
74
- For multiple recipients, **the top-level result describes the whole call**, not just the first recipient:
71
+ For several recipients, **the top-level result describes the whole call**, not only the first recipient.
75
72
 
76
73
  - `sendId` and `messageId` belong to the first recipient.
77
- - `status` is the worst outcome: from best to worst, `clicked`, `opened`, `delivered`, `sent`, `queued`, `unsubscribed`, `suppressed`, `spam`, `bounced`, `failed`.
78
- - `error` is the first nonempty error in recipient order, not necessarily the error of the recipient with the worst status.
79
- - `results` contains one result per recipient in input order. Those entries do not contain nested `results`. The type makes this field optional; the current implementation includes it even for a single recipient.
74
+ - `status` is the worst outcome. From best to worst, the order is `clicked`, `opened`, `delivered`, `sent`, `queued`, `unsubscribed`, `suppressed`, `spam`, `bounced`, `failed`.
75
+ - `error` is the first non-empty error in recipient order, not necessarily that of the worst status.
76
+ - `results` holds one result per recipient, in input order, without nested `results`. The type makes it optional, and the implementation sets it even for one recipient.
77
+
78
+ A suppressed address gets no e-mail. Its result has `status: "suppressed"` and an `error` key that starts with `$dms_mailing.errors.suppressed.`, followed by `hard_bounce`, `complaint`, `unsubscribe` or `manual`. A retry of a suppressed recipient delivers nothing and logs another `suppressed` send.
80
79
 
81
- A suppressed address receives no email. Its result has `status: "suppressed"` and an error key beginning with `$dms_mailing.errors.suppressed.`, followed by `hard_bounce`, `complaint`, `unsubscribe`, or `manual`. Do not retry suppressed recipients.
80
+ Provider failures become `failed` recipient results. If recording a send fails, its result has `sendId: ""`, `status: "failed"` and an error, and can still carry a provider `messageId`, because delivery may have happened. A `failed` result does not prove that no e-mail left, and retrying the whole call can deliver twice.
82
81
 
83
- Provider failures become failed recipient results. If recording a send fails, that result has `sendId: ""`, `status: "failed"`, and an error, but may still carry a provider `messageId`: delivery may already have happened. Do not blindly retry the whole call or infer that a failed result means no email left the provider.
82
+ Validation failures reject the promise instead of returning recipient results. The runtime's errors carry one of these codes: `no_recipient`, `template_not_found`, `template_not_live`, `invalid_content` or `missing_variables`. The interface does not export the error class. The workspace's **Missing variables** setting decides whether missing variables refuse a send. Marketing footer URLs are required system variables when the template uses them, never for test sends. Storage or notification failures can reject after side effects started, so the call is neither transactional nor idempotent.
84
83
 
85
- Validation failures reject instead of returning recipient results. The runtime's errors carry codes `no_recipient`, `template_not_found`, `template_not_live`, `invalid_content`, or `missing_variables`; the error class is not an interface export. Missing-variable refusal follows the workspace setting. Marketing footer URLs are required system variables when the template uses them; test sends do not require those system URLs. Storage or downstream notification failures can also reject after side effects have started, so this call is not transactional or idempotent.
84
+ `variables` is `TemplateVariables`, a record of strings, numbers, booleans, `null`, `Date` values, money values (`{ value: 987420, currency: "EUR" }`, in the currency's minor unit), and lists and records of the same. Dates and money are written in the send's locale. A class instance or a function does not compile, and a template path reads only the keys a record owns.
86
85
 
87
- ## RecordEmailEvent
86
+ ## `RecordEmailEvent`
88
87
 
89
88
  ```ts [Contract]
89
+ import type { JsonObject } from "@antelopejs/interface-dms-mailing";
90
+
90
91
  type SendEventType =
91
92
  | "queued" | "sent" | "delivered" | "opened" | "clicked"
92
93
  | "bounced" | "spam" | "failed" | "unsubscribed";
@@ -97,7 +98,7 @@ interface EmailEvent {
97
98
  messageId: string;
98
99
  type: SendEventType;
99
100
  at?: Date;
100
- details?: Record<string, unknown>;
101
+ details?: JsonObject;
101
102
  }
102
103
 
103
104
  declare function RecordEmailEvent(
@@ -106,28 +107,29 @@ declare function RecordEmailEvent(
106
107
  ): Promise<boolean>;
107
108
  ```
108
109
 
109
- `messageId` is the provider's message ID, not the mailing `sendId`. Matching uses the tenant and message ID; `provider` is not an authorization boundary or an additional matching key. `at` defaults to now and is a `Date` in this backend interface, unlike the ISO string in the HTTP webhook.
110
+ `messageId` is the provider's message ID, not the mailing `sendId`. The module matches the event by tenant and message ID. `provider` is neither an authorization boundary nor a matching key. `at` defaults to now. In this backend interface it is a `Date`, whereas the HTTP webhook takes an ISO string.
110
111
 
111
- The call returns `true` when it records the event. It returns `false` for an unmatched message, a duplicate event, or a send that is retiring or no longer accepts events. Supply a stable `details.eventId` for provider retries. Without it, deduplication requires the same explicit `at`, event type, and serialized details; omitting both event ID and timestamp does not deduplicate retries.
112
+ The call returns `true` when it records the event. It returns `false` for an unmatched message, a duplicate event, or a send that retention is retiring. A stable `details.eventId` deduplicates provider retries. Without it, deduplication needs the same explicit `at`, event type and serialized details, so an event with neither an event ID nor a timestamp is never deduplicated.
112
113
 
113
- Accepted events update the send timeline, status and engagement counters, publish realtime and automation events, and can notify tenant owners of template problems. A hard bounce, spam complaint, or unsubscribe suppresses the recipient. A test send suppresses only on a hard bounce; soft bounces never suppress. Suppression-write failures are logged without rejecting the recorded event. Repeated activity conflicts, storage failures, or downstream publication failures can reject; a rejection does not guarantee that no event was stored.
114
+ An accepted event updates the send's timeline, status and counters, publishes realtime and automation events, and can notify tenant owners of template problems. A hard bounce, a spam complaint or an unsubscribe suppresses the recipient, a test send only on a hard bounce, and a soft bounce never. A failed suppression write is logged without rejecting. Five activity conflicts in a row, storage failures or publication failures can reject, and a rejection does not prove that nothing was stored.
114
115
 
115
- `details.reason` supplies provider error text. `details.bounceType` distinguishes `soft`/`transient`/`temporary` from `hard`/`permanent`; otherwise the SMTP class in the reason decides. `details.url` and `details.userAgent` annotate engagement events. Authenticate a provider's webhook before translating it to this trusted call. The [runtime webhook guide](/docs/modules/mailing/extending#webhook-contract) defines HTTP authentication and response bodies.
116
+ `details.reason` holds the provider's error text. `details.bounceType` is `soft`, `transient` or `temporary`, or `hard` or `permanent`, and without it the SMTP class of the reason decides. `details.url` and `details.userAgent` annotate engagement events. The call trusts its caller, which authenticates a relayed provider webhook first. The [runtime webhook guide](/docs/modules/mailing/extending#webhook-contract) defines HTTP authentication and response bodies.
116
117
 
117
118
  ## Ship templates as code
118
119
 
119
- A project can declare its transactional templates from backend code instead of creating them in the dashboard. The content is written once, when the tenant is provisioned (see [When to call](#when-to-call)), and belongs to the tenant from then on: nothing replays it on a later boot. A newly created template claims its slug, is published as v1 with history, and is ready for `SendTemplate` when the call resolves.
120
+ A project can declare its transactional templates from backend code instead of creating them in the dashboard. The content is written once, when the tenant is provisioned (see [When to call](#when-to-call)). From then on it belongs to the tenant, and nothing replays it on a later boot. A newly created template claims its slug, is published as v1 with history, and is ready for `SendTemplate` when the call resolves.
120
121
 
121
- `DeclareTemplate`, `DeclareTemplateCategory`, `DeclareSender` and `ImportSends` require an explicit `tenantId`, in TypeScript and at runtime. Omission, an empty string or whitespace-only input rejects before any write, with `invalid_template`, `invalid_category`, `invalid_sender` or `invalid_import` respectively and `tenantId` in the message. There is no default fallback. Passing `DEFAULT_TENANT_ID` explicitly remains valid. This requirement identifies the target; it proves neither authorization nor completed provisioning. Trusted application code must enforce both. Existing `SendTemplate` and `RecordEmailEvent` contracts are unchanged.
122
+ `DeclareTemplate`, `DeclareTemplateCategory`, `DeclareSender`, `DeclareWebhookSecret` and `ImportSends` require an explicit `tenantId`, in TypeScript and at runtime. A missing, empty or blank one rejects before any write with `invalid_template`, `invalid_category`, `invalid_sender`, `invalid_webhook_secret` or `invalid_import` respectively, naming `tenantId`. No default applies, and an explicit `DEFAULT_TENANT_ID` is valid. It names the target but proves neither authorization nor provisioning, which the calling code enforces. `SendTemplate` and `RecordEmailEvent` do not run this check.
122
123
 
123
124
  ### Names and labels in several languages
124
125
 
125
- A template's `name` and a category's `label` are `LocalizedText`: one text per language, `{ en: "Welcome", fr: "Bienvenue" }`. The `en` text is required (`LOCALIZED_TEXT_FALLBACK_LOCALE`): a reader whose language has no text reads it. They are stored as localized fields (`@Localized`), so the dashboard shows, searches and sorts each user's own language, sent by the DMS frontend in `x-content-language`. Do not pass `$` i18n keys: a name is content, not a translation key. A user renaming a template in the dashboard writes the language they work in.
126
+ A template's `name` and a category's `label` are `LocalizedText`, one text per language, such as `{ en: "Welcome", fr: "Bienvenue" }`. Each text is non-blank and at most 120 characters. The `en` text (`LOCALIZED_TEXT_FALLBACK_LOCALE`) is required, and a reader whose language has no text reads it. The module stores them as localized fields (`@Localized`). The dashboard shows, searches and sorts each user's own language, which the DMS frontend sends in the `x-content-language` header. A name is content, not a `$` i18n key. A user who renames a template in the dashboard writes the language they work in.
126
127
 
127
- ### DeclareTemplate
128
+ ### `DeclareTemplate`
128
129
 
129
130
  ```ts [Contract]
130
131
  import type {
132
+ JsonObject,
131
133
  LocalizedText, // Record<string, string>
132
134
  TemplateContent,
133
135
  VariableDefinition,
@@ -140,7 +142,7 @@ interface TemplateDeclaration {
140
142
  category?: string; // a category id of the workspace settings
141
143
  content: TemplateContent;
142
144
  variables?: VariableDefinition[];
143
- testData?: Record<string, unknown>;
145
+ testData?: JsonObject;
144
146
  author?: string; // shown as "updated by" / "published by"; "system" when absent
145
147
  }
146
148
 
@@ -158,15 +160,17 @@ declare function DeclareTemplate(
158
160
  ): Promise<DeclareTemplateResult>;
159
161
  ```
160
162
 
161
- The slug is the key the caller chooses. A slug the tenant does not have yet is created and published as v1 (`created`). A slug it already has, declared before or made in the dashboard, is left as it is (`kept`): the call writes nothing, so a retried provisioning never creates a second template nor overwrites a user's work.
163
+ The slug is the caller's key. A slug the tenant does not have is created and published as v1 (`created`). A slug it has, declared before or made in the dashboard, is left as it is (`kept`), and nothing is written, so a retried provisioning neither creates a second template nor overwrites a user's work. Of two concurrent creations of one slug, the second returns `kept`.
162
164
 
163
- The declaration follows the dashboard's rules: the slug pattern and length of a new template, a non-blank name, content and variable declarations valid for the editor, at least one locale and a subject in every locale (what **Publish** requires). A creation also requires a category the workspace settings declare (or none). Validation errors use `invalid_template`, `unknown_category`, `nothing_to_publish` or `empty_subject`; their messages identify the invalid input, and they do not publish a template.
165
+ The declaration follows the dashboard's rules. The slug matches `^[a-z0-9][a-z0-9-]*$` and has at most 64 characters. The name is non-blank, and the content and variable declarations are valid for the editor. The content has at least one locale and a subject in every locale, as **Publish** requires. `author`, when present, is non-blank and at most 120 characters. A creation also needs a category that the workspace settings declare, or no category. The validation codes are `invalid_template`, `unknown_category`, `nothing_to_publish` and `empty_subject`. Their messages name the invalid input, and none of them publishes a template.
164
166
 
165
- A storage or attention-refresh failure can reject after publication commits. The committed template retains the complete latest version so history and numbered-version previews remain readable if the history insert fails; a later publication repairs that row before replacing the snapshot. An indeterminate database mutation rejects without automatic retry or rollback: rejection is not proof that nothing changed.
167
+ A storage or attention-refresh failure can reject after the publication commits. The template row keeps the complete latest version, so history and version previews stay readable if the history insert fails, and a later publication repairs that row before replacing the snapshot. An indeterminate database mutation rejects without automatic retry or rollback, so a rejection does not prove that nothing changed.
166
168
 
167
- ### DeclareTemplateCategory
169
+ ### `DeclareTemplateCategory`
168
170
 
169
171
  ```ts [Contract]
172
+ import type { LocalizedText } from "@antelopejs/interface-dms-mailing";
173
+
170
174
  interface TemplateCategoryDeclaration {
171
175
  tenantId: string;
172
176
  id: string; // lowercase letters, digits and dashes
@@ -184,9 +188,9 @@ declare function DeclareTemplateCategory(
184
188
  ): Promise<DeclareTemplateCategoryResult>;
185
189
  ```
186
190
 
187
- Adds a category to the workspace settings (`created`). An id the settings already hold, the defaults `orders`, `account`, `billing`, `marketing` and `forms` among them, is left as it is (`kept`). A label another category already has rejects with `invalid_category`. Declarations of one workspace run one after the other within one process; this queue is not a cross-process lock and does not serialize dashboard settings writes. Coordinate concurrent category/settings writers externally. Declare a category before templates that name it.
191
+ Adds a category to the workspace settings (`created`). An id the settings hold, the defaults `orders`, `account`, `billing`, `marketing` and `forms` included, is left as it is (`kept`). The `id` matches `^[a-z0-9][a-z0-9-]*$`, and the `icon` matches `i-ph-<name>`. A label that another category already has in the same language, in any letter case, rejects with `invalid_category`. Declarations of one workspace run one after another within one process. This queue is not a cross-process lock and does not serialize dashboard settings writes, so concurrent category and settings writers need outside coordination. A template declaration that names a category needs that category declared first.
188
192
 
189
- ### DeclareSender
193
+ ### `DeclareSender`
190
194
 
191
195
  ```ts [Contract]
192
196
  interface SenderDeclaration {
@@ -199,13 +203,33 @@ interface SenderDeclaration {
199
203
  declare function DeclareSender(declaration: SenderDeclaration): Promise<void>;
200
204
  ```
201
205
 
202
- Writes the Sender section of the workspace settings, so a fresh workspace sends from the project's address instead of the provider's default (and the Overview does not ask for one). It is a plain write: the declared name, address and reply-to replace the stored ones, and an absent `name` or `replyTo` clears it. Call it once, when the project provisions the workspace (`Hook.TENANT_BEING_PROVISIONED`), not on every boot: from then on the settings are the user's, and a later call would overwrite their changes. The address and the reply-to follow the settings form's rules (an internationalized domain is stored in its ASCII form), and a missing or invalid address rejects with `invalid_sender`, naming the field. It rewrites the whole settings row, like `DeclareTemplateCategory`: await one before calling the other for the same workspace.
206
+ Writes the Sender section of the workspace settings, so a fresh workspace sends from the project's address instead of the provider's default, and the Overview does not ask for one. It is a plain write. The declared name, address and reply-to replace the stored ones, and an absent `name` or `replyTo` clears it. It belongs in `Hook.TENANT_BEING_PROVISIONED`, not on every boot, because the settings are the user's afterwards and a later call overwrites their changes. The address and reply-to follow the settings form's rules (an internationalized domain is stored in ASCII form), and a missing or invalid address rejects with `invalid_sender`, naming the field. Like `DeclareTemplateCategory`, it rewrites the whole settings row, so the two are awaited one after the other for a workspace.
207
+
208
+ ### `DeclareWebhookSecret`
209
+
210
+ ```ts [Contract]
211
+ interface WebhookSecretDeclaration {
212
+ tenantId: string;
213
+ secret: string; // 32 to 120 characters
214
+ replaceRotated?: boolean; // replace a secret the workspace owner set or rotated
215
+ }
216
+
217
+ type WebhookSecretOutcome = "set" | "unchanged" | "kept";
218
+
219
+ declare function DeclareWebhookSecret(
220
+ declaration: WebhookSecretDeclaration,
221
+ ): Promise<{ outcome: WebhookSecretOutcome }>;
222
+ ```
223
+
224
+ Sets the secret a provider sends with each webhook event, for a project that needs a known one, such as a demo whose screenshots show the settings page or a provider configured ahead of the workspace. A new workspace starts with a random secret, which a declaration replaces (`set`). Declaring the stored secret again changes nothing (`unchanged`), so the call is safe on every start. A secret the workspace owner typed in the settings or rotated there is theirs: a declaration leaves it in place (`kept`) unless it passes `replaceRotated: true`. A secret stored by a module release without `DeclareWebhookSecret` counts as the owner's.
225
+
226
+ The secret is never returned, and a refused one rejects with `invalid_webhook_secret`, naming the rule (`secret` too short or too long), never the value. The call writes the secret alone, so it does not overwrite settings another writer changes at the same time.
203
227
 
204
228
  ### When to call
205
229
 
206
- Call these functions from a `Hook.TENANT_BEING_PROVISIONED` handler, registered in your module's `construct()`. The DMS fires that hook once for each tenant, when the tenant is created. For the `default` tenant, it fires on the DMS start that creates it, after every `DATABASE_INITIALIZED` handler has finished. A SaaS module fires it for each workspace it creates. The mailing tables are ready by then, so the calls do not wait for anything.
230
+ The declarations belong in a `Hook.TENANT_BEING_PROVISIONED` handler that the module registers in `construct()`. The DMS fires that hook once for each tenant, when the tenant is created. For the `default` tenant, it fires on the DMS start that creates the tenant, after every `DATABASE_INITIALIZED` handler has finished. A SaaS module fires it for each workspace it creates. The mailing tables are ready by then, so the calls do not wait for anything.
207
231
 
208
- Do not call them from `start()` or a `DATABASE_INITIALIZED` handler. They run on every boot, and the content a workspace starts with is written once. After that, it belongs to the workspace.
232
+ `start()` and `DATABASE_INITIALIZED` handlers run on every boot, so they are the wrong place. The content a workspace starts with is written once, then belongs to it.
209
233
 
210
234
  ```ts docs-check
211
235
  import { Hook, RegisterHook } from "@antelopejs/interface-dms/hooks";
@@ -254,25 +278,25 @@ export function construct(): void {
254
278
  }
255
279
  ```
256
280
 
257
- ## ImportSends
281
+ ## `ImportSends`
258
282
 
259
283
  ```ts [Contract]
260
284
  import type { EmailAddress } from "@antelopejs/interface-email";
261
- import type { SendEventType } from "@antelopejs/interface-dms-mailing";
285
+ import type { JsonObject, SendEventType } from "@antelopejs/interface-dms-mailing";
262
286
 
263
287
  interface ImportedSendEvent {
264
288
  type: SendEventType;
265
289
  at: Date;
266
- details?: Record<string, unknown>;
290
+ details?: JsonObject;
267
291
  }
268
292
 
269
293
  interface ImportedSend {
270
- importId: string; // stable key chosen by the caller
294
+ importId: string; // stable key chosen by the caller, at most 200 characters
271
295
  templateSlug: string;
272
296
  to: EmailAddress;
273
297
  sentAt: Date;
274
298
  locale?: string; // the workspace fallback locale when absent
275
- variables?: Record<string, unknown>;
299
+ variables?: JsonObject;
276
300
  provider?: string;
277
301
  providerMessageId?: string;
278
302
  source?: string; // "import" when absent
@@ -294,19 +318,19 @@ interface ImportSendsResult {
294
318
  declare function ImportSends(params: SendImport): Promise<ImportSendsResult>;
295
319
  ```
296
320
 
297
- **An import, not a send.** `SendTemplate` stamps every send with the current time, and the Overview, the template statistics and the send log read sends by that date: history from another provider, or a demo data set, cannot be replayed through it. `ImportSends` writes past sends with their own `sentAt` and events instead. Nothing is delivered, and no suppression, realtime update, automation or owner notification follows: import the suppression list separately if the old provider kept one.
321
+ **An import, not a send.** `SendTemplate` stamps every send with the current time, and the Overview, the template statistics and the send log read sends by that date. History from another provider, or a demo data set, therefore cannot go through `SendTemplate`. `ImportSends` writes past sends with their own `sentAt` and events instead. Nothing is delivered, and no suppression, realtime update, automation or owner notification follows. An old provider's suppression list needs its own import.
298
322
 
299
- Each entry names a template of the workspace (its published version is recorded) and is keyed by its `importId`: an entry imported before is skipped untouched, so a retried provisioning imports nothing twice. The events can come in any order; the send's status, open and click counters, error and soft-bounce flag follow from them as if the webhook had reported them, and an entry without events is `sent`. An unknown template rejects the whole call with `template_not_found` before anything is written; an invalid entry rejects it with `invalid_import`, naming the field (`sends.3.to`). The log retention applies to imported sends like to any other: one older than the workspace's retention (90 days by default) goes at the next nightly run, so a demo data set should stay within it.
323
+ Each entry names a template of the workspace, whose published version is recorded, and is keyed by its `importId`. An entry imported before is skipped untouched, so a retried provisioning imports nothing twice. The events can come in any order. The send's status, open and click counters, error and soft-bounce flag follow from them as if the webhook had reported them, and an entry without events is `sent`. An invalid entry rejects the whole call with `invalid_import` and names the field (`sends.3.to`). An unknown template rejects it with `template_not_found`. Both reject before anything is written. The log retention applies to imported sends like to any other. A send older than the workspace's retention (90 days by default) goes at the next nightly run, so a demo data set stays within that window.
300
324
 
301
- Events are sorted by `at` and deduplicated before storage and counting: `details.eventId` identifies provider retries; without it, the type, timestamp and serialized details must match. The earliest sorted occurrence is kept. Import IDs are scoped by tenant, not by provider: prefix them when importing more than one provider's identifier space.
325
+ Events are sorted by `at` and deduplicated before storage and counting, by `details.eventId`, or without it by type, timestamp and serialized details. The earliest sorted occurrence is kept. Import IDs are scoped by tenant, not provider, so IDs from several providers need a prefix.
302
326
 
303
- Imports are not transactional batches. A storage failure can leave earlier entries committed or an entry's events written before its send row; retry with the same immutable payload, including event order for equal timestamps. Changing an interrupted entry's payload under the same `importId` is not supported. Retention removes the deduplication record with the send, so an old key can be imported again after purge. The API records the template's current published version, not an arbitrary version from the previous provider.
327
+ Imports are not transactional. A storage failure can leave earlier entries committed, or an entry's events written before its send row. A retry with the same immutable payload, event order for equal timestamps included, completes it. Changing an interrupted entry's payload under the same `importId` is not supported. Retention removes the deduplication record with the send, so an old key can be imported again after a purge. The function records the template's current published version, not a version from the previous provider.
304
328
 
305
329
  ## Template types
306
330
 
307
- `TemplateContent` is `{ locales: Record<string, LocaleContent> }`; each `LocaleContent` has `subject: string`, `preheader: string`, and `blocks: Block[]`.
331
+ `TemplateContent` is `{ locales: Record<string, LocaleContent> }`. Each `LocaleContent` has `subject: string`, `preheader: string` and `blocks: Block[]`.
308
332
 
309
- All blocks share `BlockBase`: `id: string`, the discriminant `type: BlockType`, and `visibleIf: Condition | null`. `Block` is the union of the following exported interfaces. All listed fields are required; `TextAlign` is `"left" | "center" | "right"`.
333
+ All blocks share `BlockBase`, with `id: string`, the discriminant `type: BlockType`, and `visibleIf: Condition | null`. `Block` is the union of the following exported interfaces. All listed fields are required. `TextAlign` is `"left" | "center" | "right"`.
310
334
 
311
335
  | Interface / `type` | Additional fields |
312
336
  | --- | --- |
@@ -323,6 +347,6 @@ All blocks share `BlockBase`: `id: string`, the discriminant `type: BlockType`,
323
347
 
324
348
  `Condition` has `path: string`, `operator: ConditionOperator`, and `value: string`. Operators are `truthy`, `falsy`, `eq`, `ne`, `gt`, and `lt`. `VariableDefinition` has `path: string`, `type: VariableType`, and `required: boolean`. Variable types are `string`, `text`, `number`, `money`, `date`, `url`, `boolean`, and `array`.
325
349
 
326
- Values are written in the locale the e-mail is rendered in. A money value `{ value, currency }` (the amount in the currency's minor unit, an ISO 4217 code: `{ value: 987420, currency: "EUR" }` reads "€9,874.20" in English, "9 874,20 €" in French) and a `Date` (a long date, in the server's time zone) are formatted wherever they appear, list rows included. An ISO 8601 string is written as a date only at a path the template declares `date`: a day (`2026-11-14`) as that calendar day, a moment as its day in the server's time zone. Other values, strings the caller already formatted among them and numbers, are written as given.
350
+ Values are written in the render locale. A money value `{ value, currency }` holds the amount in the currency's minor unit and an ISO 4217 code, so `{ value: 987420, currency: "EUR" }` reads "€9,874.20" in English and "9 874,20 €" in French. It and a `Date`, a long date in the server's time zone, are formatted wherever they appear, list rows included. An ISO 8601 string is written as a date only at a path the template declares `date`. A day (`2026-11-14`) becomes that calendar day, and a moment becomes its day in the server's time zone. Other values, numbers and strings the caller already formatted included, are written as given.
327
351
 
328
- For template setup, footer variables and automation integration, use the [extending guide](/docs/modules/mailing/extending). Installation, configuration and HTTP routes remain in the runtime guide.
352
+ The [extending guide](/docs/modules/mailing/extending) covers template setup, footer variables and automations. The runtime guide covers installation, configuration and HTTP routes.
@@ -2,9 +2,17 @@
2
2
  "extends": "../tsconfig.json",
3
3
  "compilerOptions": {
4
4
  "rootDir": "..",
5
+ "module": "esnext",
6
+ "moduleResolution": "bundler",
7
+ "noUnusedLocals": false,
8
+ "noUnusedParameters": false,
5
9
  "composite": false,
6
10
  "incremental": false,
7
- "noEmit": true
11
+ "noEmit": true,
12
+ "paths": {
13
+ "@antelopejs/interface-dms-mailing": ["../src/index.ts"],
14
+ "@antelopejs/interface-dms-mailing/*": ["../src/*"]
15
+ }
8
16
  },
9
17
  "include": ["../src/**/*.ts", "./**/*.ts"]
10
18
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@antelopejs/interface-dms-mailing",
3
- "version": "0.9.1",
3
+ "version": "0.10.1",
4
4
  "description": "AntelopeJS interface for the DMS mailing module: send templates and report e-mail events from any module.",
5
5
  "keywords": [
6
6
  "antelopejs",
@@ -46,23 +46,23 @@
46
46
  },
47
47
  "scripts": {
48
48
  "build": "rimraf dist && tsc",
49
- "format": "oxfmt .",
50
- "lint": "oxlint && oxfmt --check .",
51
49
  "prepack": "pnpm run build",
52
- "release": "pnpm run lint && pnpm run build && release-it",
50
+ "release": "pnpm run build && pnpm --dir ../.. run lint && pnpm --dir ../.. run format:check && release-it",
53
51
  "typecheck": "tsc --noEmit"
54
52
  },
55
53
  "dependencies": {
56
- "@antelopejs/interface-core": ">=0.2.4 <1.0.0",
54
+ "@antelopejs/interface-core": ">=0.4.0 <1.0.0",
57
55
  "@antelopejs/interface-email": ">=0.0.6 <1.0.0"
58
56
  },
59
57
  "devDependencies": {
60
- "@antelopejs/interface-dms": ">=0.9.0 <1.0.0",
61
- "@antelopejs/tooling-configs": ">=0.0.9 <1.0.0",
58
+ "@antelopejs/interface-api": ">=0.3.0 <1.0.0",
59
+ "@antelopejs/interface-api-util": ">=0.3.0 <1.0.0",
60
+ "@antelopejs/interface-data-api": ">=0.6.1 <1.0.0",
61
+ "@antelopejs/interface-database": ">=0.3.0 <1.0.0",
62
+ "@antelopejs/interface-database-decorators": ">=0.2.0 <1.0.0",
63
+ "@antelopejs/interface-dms": ">=0.12.0 <1.0.0",
64
+ "@antelopejs/tooling-configs": ">=0.3.3 <1.0.0",
62
65
  "@types/node": "^24.0.0",
63
- "oxfmt": "^0.66.0",
64
- "oxlint": "1.81.0",
65
- "oxlint-tsgolint": "^7.0.2001",
66
66
  "release-it": "^19.2.4",
67
67
  "release-it-changelogen": "^0.1.0",
68
68
  "rimraf": "^6.1.3",