@antelopejs/interface-dms-mailing 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,8 @@ 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`).
19
20
  - Imports past sends and their events with their own dates, for a demo data set or a move from another provider (`ImportSends`).
20
21
  - Exports the template and send types (`Block`, `TemplateContent`, `VariableDefinition`, `SendStatus`, `EmailEvent`…) for code that builds or inspects templates.
21
22
  - Keeps your module independent of the implementation, [`@antelopejs/dms-mailing`](https://www.npmjs.com/package/@antelopejs/dms-mailing).
@@ -30,14 +31,22 @@ pnpm add @antelopejs/interface-dms-mailing
30
31
 
31
32
  ## Quick start
32
33
 
33
- ```ts
34
+ ```ts fragment
34
35
  import { RecordEmailEvent, SendTemplate } from "@antelopejs/interface-dms-mailing";
35
36
 
36
- const result = await SendTemplate("order-confirmation", {
37
+ const result = await SendTemplate("order-confirmed", {
37
38
  tenantId,
38
39
  to: [{ email: "sofie@example.com", name: "Sofie" }],
39
40
  locale: "fr",
40
- variables: { order: { total: "48.00" } },
41
+ variables: {
42
+ customer: { firstName: "Sofie" },
43
+ order: {
44
+ number: "#10482",
45
+ total: { value: 4800, currency: "EUR" },
46
+ lines: [{ name: "Linen shirt", total: { value: 4800, currency: "EUR" } }],
47
+ url: "https://example.com/orders/10482",
48
+ },
49
+ },
41
50
  source: "checkout",
42
51
  });
43
52
 
@@ -49,18 +58,20 @@ await RecordEmailEvent(tenantId, {
49
58
  });
50
59
  ```
51
60
 
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`.
61
+ 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
62
 
54
63
  ## Compatibility
55
64
 
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:
65
+ 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` and `ImportSends` each take an explicit `tenantId`. The interface declares these dependencies:
57
66
 
58
- <!-- docs-compat: ./package.json#dependencies -->
67
+ <!-- antelopejs-docs-compat:start -->
59
68
 
60
- | Package | Range |
61
- | --- | --- |
62
- | `@antelopejs/interface-core` | `>=0.2.4 <1.0.0` |
63
- | `@antelopejs/interface-email` | `>=0.0.6 <1.0.0` |
69
+ | Package | Supported | Tested with |
70
+ | ----------------------------- | ---------------- | ----------- |
71
+ | `@antelopejs/interface-core` | `>=0.4.0 <1.0.0` | `0.4.0` |
72
+ | `@antelopejs/interface-email` | `>=0.0.6 <1.0.0` | `0.0.6` |
73
+
74
+ <!-- antelopejs-docs-compat:end -->
64
75
 
65
76
  ## Documentation
66
77
 
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,10 +127,10 @@ 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
- export type DeclarationOutcome = "created" | "updated" | "unchanged" | "kept";
133
+ export type DeclarationOutcome = "created" | "kept";
122
134
  export interface DeclareTemplateResult {
123
135
  templateId: string;
124
136
  slug: string;
@@ -144,7 +156,7 @@ export interface SenderDeclaration {
144
156
  export interface ImportedSendEvent {
145
157
  type: SendEventType;
146
158
  at: Date;
147
- details?: Record<string, unknown>;
159
+ details?: JsonObject;
148
160
  }
149
161
  export interface ImportedSend {
150
162
  importId: string;
@@ -152,7 +164,7 @@ export interface ImportedSend {
152
164
  to: EmailAddress;
153
165
  sentAt: Date;
154
166
  locale?: string;
155
- variables?: Record<string, unknown>;
167
+ variables?: JsonObject;
156
168
  provider?: string;
157
169
  providerMessageId?: string;
158
170
  source?: string;
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 six backend functions and the template types below. `SendTemplate` sends, `RecordEmailEvent` reports provider events, `DeclareTemplate`, `DeclareTemplateCategory` and `DeclareSender` ship templates, categories and the sender 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 six 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. A newly created template claims its slug, is published as v1 with history, and is ready for `SendTemplate` when the call resolves. Existing templates remain subject to the ownership and lifecycle rules below: `unchanged` and `kept` do not guarantee that an archived or unpublished template is sendable.
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` 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` 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, which counts as a change (`kept`).
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,11 +142,11 @@ 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
 
147
- type DeclarationOutcome = "created" | "updated" | "unchanged" | "kept";
149
+ type DeclarationOutcome = "created" | "kept";
148
150
 
149
151
  interface DeclareTemplateResult {
150
152
  templateId: string;
@@ -158,26 +160,17 @@ declare function DeclareTemplate(
158
160
  ): Promise<DeclareTemplateResult>;
159
161
  ```
160
162
 
161
- The slug is the key the caller chooses. Calling `DeclareTemplate` on every boot or hot reload is the intended use, and it never creates a second template. The module stores a fingerprint of the declaration it last applied (name, category, content, variables and test data) on the template and decides as follows:
162
-
163
- | The template under that slug | Outcome | What is written |
164
- | --- | --- | --- |
165
- | does not exist | `created` | the template, published as v1 |
166
- | was declared with the same declaration | `unchanged` | no content or lifecycle change, whatever a user did since; interrupted history may be repaired |
167
- | was declared before, is still `live` with no draft and holds exactly what the last declaration wrote | `updated` | the new declaration, published (a new version when content or variables changed) |
168
- | was edited, holds a draft, was unpublished or archived since, or was made in the dashboard | `kept` | no content or lifecycle change; interrupted history may be repaired |
169
-
170
- So a user's work always wins: once someone edits a declared template, the code stops refreshing it until the template holds exactly what the code last declared again. Archive a declared template to take it out of use for good; a declared template deleted in the dashboard is created again by the next call, since the code that declares it is the code that sends it.
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`.
171
164
 
172
- Publication compares the template's semantic revision and commits content, metadata and the declaration fingerprint together. An intervening dashboard edit causes a reread and ownership check instead of an overwrite; repeated contention rejects with `declaration_conflict`. A concurrent caller can finish an unmodified initial declaration left by an interrupted creator, but cannot publish over a user-edited seed.
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.
173
166
 
174
- 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 or refresh also requires a category the workspace settings declare (or none); `unchanged` and `kept` do not fail merely because a user removed the original category. 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.
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.
175
168
 
176
- 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 declaration or publication repairs that row before replacing the snapshot. Retry the same declaration after resolving the storage problem. An indeterminate database mutation rejects without automatic retry or rollback: rejection is not proof that nothing changed.
177
-
178
- ### DeclareTemplateCategory
169
+ ### `DeclareTemplateCategory`
179
170
 
180
171
  ```ts [Contract]
172
+ import type { LocalizedText } from "@antelopejs/interface-dms-mailing";
173
+
181
174
  interface TemplateCategoryDeclaration {
182
175
  tenantId: string;
183
176
  id: string; // lowercase letters, digits and dashes
@@ -187,7 +180,7 @@ interface TemplateCategoryDeclaration {
187
180
 
188
181
  interface DeclareTemplateCategoryResult {
189
182
  id: string;
190
- outcome: "created" | "updated" | "unchanged" | "kept";
183
+ outcome: "created" | "kept";
191
184
  }
192
185
 
193
186
  declare function DeclareTemplateCategory(
@@ -195,9 +188,9 @@ declare function DeclareTemplateCategory(
195
188
  ): Promise<DeclareTemplateCategoryResult>;
196
189
  ```
197
190
 
198
- Adds a category to the workspace settings (`created`), relabels one still as last declared (`updated`), or does nothing (`unchanged`). A category a user relabelled or removed since, and one that existed before any declaration (the defaults `orders`, `account`, `billing`, `marketing` and `forms` among them), is left as it is (`kept`): a removed category is never added back. 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.
199
192
 
200
- ### DeclareSender
193
+ ### `DeclareSender`
201
194
 
202
195
  ```ts [Contract]
203
196
  interface SenderDeclaration {
@@ -210,27 +203,24 @@ interface SenderDeclaration {
210
203
  declare function DeclareSender(declaration: SenderDeclaration): Promise<void>;
211
204
  ```
212
205
 
213
- 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.
214
207
 
215
208
  ### When to call
216
209
 
217
- The calls wait for the module and for the DMS database, so start order never makes them fail: a call made before `@antelopejs/dms-mailing` is constructed is queued by the interface, and a call made before the DMS opened its database waits for it. The DMS opens it in its own `start()`, after every module's `construct()`, so:
210
+ 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.
218
211
 
219
- - in `construct()`, register lifecycle consumers synchronously, without calling or awaiting declarations: this ensures registration precedes startup reconciliation;
220
- - in `start()`, perform explicitly scoped global work, not consumer registration that can race reconciliation. A `construct()` awaiting declarations would wait for database startup, which only runs after every `construct()` returned;
221
- - in a `Hook.DATABASE_INITIALIZED` handler, do not await them either: the hook's handlers run one after the other.
222
-
223
- `start()` runs for the process, not for each SaaS workspace. Database readiness does not mean a tenant has completed provisioning. The following application function receives its authorized target from its caller; it is not an implicit default-tenant startup initializer.
212
+ `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.
224
213
 
225
214
  ```ts docs-check
215
+ import { Hook, RegisterHook } from "@antelopejs/interface-dms/hooks";
226
216
  import {
227
217
  DeclareTemplate,
228
218
  DeclareTemplateCategory,
229
219
  } from "@antelopejs/interface-dms-mailing";
230
220
 
231
- export async function declareMailingContent(tenantId: string): Promise<void> {
221
+ async function declareMailingContent(tenantId: string): Promise<void> {
232
222
  await DeclareTemplateCategory({ tenantId, id: "subscriptions", label: { en: "Subscriptions", fr: "Abonnements" }, icon: "i-ph-repeat" });
233
- const result = await DeclareTemplate({
223
+ await DeclareTemplate({
234
224
  tenantId,
235
225
  slug: "subscription-renewed",
236
226
  name: { en: "Subscription renewed", fr: "Abonnement renouvelé" },
@@ -259,64 +249,34 @@ export async function declareMailingContent(tenantId: string): Promise<void> {
259
249
  testData: { customer: { firstName: "Sofie" }, plan: { name: "Pro" } },
260
250
  author: "Release script",
261
251
  });
262
- if (result.outcome === "kept") {
263
- // Preserve the user's content and lifecycle; it may be archived.
264
- }
265
252
  }
266
- ```
267
-
268
- ### Initialize new SaaS workspaces
269
-
270
- For an application using dms-saas, register a durable `created` consumer through `RegisterWorkspaceLifecycleConsumer` from `@antelopejs/interface-dms-saas/workspace-lifecycle`. Register it synchronously in the application's `construct()`, before startup reconciliation begins; the async consumer executes later. The `created` transition follows workspace preparation and payment; delivery is **at least once**. `TENANT_BEING_PROVISIONED` is a different, prepayment hook: an error aborts creation, with no automatic replay or compensation of consumer effects.
271
-
272
- The following is an **integration skeleton**, not a standalone persistence implementation. The application must implement the durable operation ledger and resource binding described in the comments before returning a receipt. Mailing neither depends on dms-saas nor registers this consumer.
273
-
274
- ```typescript
275
- import { RegisterWorkspaceLifecycleConsumer } from "@antelopejs/interface-dms-saas/workspace-lifecycle";
276
- import { declareMailingContent } from "./mailing-content"; // application function above
277
253
 
278
254
  export function construct(): void {
279
- RegisterWorkspaceLifecycleConsumer({
280
- name: "application.mailing",
281
- transitions: ["created"],
282
- async consume({ tenantId, operationId }) {
283
- // Application responsibility: deduplicate concurrent/replayed operationId
284
- // durably, returning the recorded receipt for completed operations.
285
- await declareMailingContent(tenantId);
286
- // Persist the resource bindings and completed operation before returning
287
- // its durable receiptId. A crash here must be recoverable on redelivery.
288
- // Return { receiptId, ... } from that application-owned durable record.
289
- throw new Error("Implement durable operation binding and receipt storage");
290
- },
255
+ RegisterHook(Hook.TENANT_BEING_PROVISIONED, async ({ tenantId }) => {
256
+ await declareMailingContent(tenantId);
291
257
  });
292
258
  }
293
259
  ```
294
260
 
295
- Use `operationId` as the durable deduplication key. Idempotent declarations make their own retries safe; they do not make arbitrary consumer side effects exactly-once. Never acknowledge success with a fabricated receipt or before resources are durably associated with the operation. Do not await declarations from `construct()` while database startup is still blocked; consumer registration and consumer execution are distinct.
296
-
297
- ### Update existing SaaS workspaces
298
-
299
- A new deployment does not emit `created` for every existing tenant. Apply code updates or backfills through an application-owned, authorized tenant inventory. For each candidate, check `IsWorkspaceProvisioningCommitted(tenantId)` from the same workspace-lifecycle entry point before declaring or importing. Proceed only on `true`; skip an uncommitted tenant, and treat lookup/inventory errors as failures, never permission to proceed. Preserve progress for retries and coordinate category/settings writers. This is separate from initializing a newly created workspace, and it must never silently fall back to the default tenant.
300
-
301
- ## ImportSends
261
+ ## `ImportSends`
302
262
 
303
263
  ```ts [Contract]
304
264
  import type { EmailAddress } from "@antelopejs/interface-email";
305
- import type { SendEventType } from "@antelopejs/interface-dms-mailing";
265
+ import type { JsonObject, SendEventType } from "@antelopejs/interface-dms-mailing";
306
266
 
307
267
  interface ImportedSendEvent {
308
268
  type: SendEventType;
309
269
  at: Date;
310
- details?: Record<string, unknown>;
270
+ details?: JsonObject;
311
271
  }
312
272
 
313
273
  interface ImportedSend {
314
- importId: string; // stable key chosen by the caller
274
+ importId: string; // stable key chosen by the caller, at most 200 characters
315
275
  templateSlug: string;
316
276
  to: EmailAddress;
317
277
  sentAt: Date;
318
278
  locale?: string; // the workspace fallback locale when absent
319
- variables?: Record<string, unknown>;
279
+ variables?: JsonObject;
320
280
  provider?: string;
321
281
  providerMessageId?: string;
322
282
  source?: string; // "import" when absent
@@ -338,19 +298,19 @@ interface ImportSendsResult {
338
298
  declare function ImportSends(params: SendImport): Promise<ImportSendsResult>;
339
299
  ```
340
300
 
341
- **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.
301
+ **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.
342
302
 
343
- 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 the call can run on every boot. 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.
303
+ 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.
344
304
 
345
- 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.
305
+ 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.
346
306
 
347
- 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.
307
+ 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.
348
308
 
349
309
  ## Template types
350
310
 
351
- `TemplateContent` is `{ locales: Record<string, LocaleContent> }`; each `LocaleContent` has `subject: string`, `preheader: string`, and `blocks: Block[]`.
311
+ `TemplateContent` is `{ locales: Record<string, LocaleContent> }`. Each `LocaleContent` has `subject: string`, `preheader: string` and `blocks: Block[]`.
352
312
 
353
- 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"`.
313
+ 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"`.
354
314
 
355
315
  | Interface / `type` | Additional fields |
356
316
  | --- | --- |
@@ -367,6 +327,6 @@ All blocks share `BlockBase`: `id: string`, the discriminant `type: BlockType`,
367
327
 
368
328
  `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`.
369
329
 
370
- 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.
330
+ 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.
371
331
 
372
- 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.
332
+ 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.0",
3
+ "version": "0.10.0",
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,22 +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/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.2.18 <1.0.0",
61
65
  "@types/node": "^24.0.0",
62
- "oxfmt": "^0.66.0",
63
- "oxlint": "1.81.0",
64
- "oxlint-tsgolint": "^7.0.2001",
65
66
  "release-it": "^19.2.4",
66
67
  "release-it-changelogen": "^0.1.0",
67
68
  "rimraf": "^6.1.3",