@antelopejs/interface-dms-mailing 0.7.0 → 0.8.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,23 +1,38 @@
1
+ <div align="center">
2
+
1
3
  # @antelopejs/interface-dms-mailing
2
4
 
3
- <div align="center">
4
- <a href="./LICENSE"><img alt="License" src="https://img.shields.io/badge/license-Apache--2.0-blue?style=for-the-badge&labelColor=000000"></a>
5
- <a href="https://discord.gg/sjK28QHrA7"><img src="https://img.shields.io/badge/Discord-18181B?logo=discord&style=for-the-badge&color=000000" alt="Discord"></a>
6
- <a href="https://antelopejs.com"><img src="https://img.shields.io/badge/Docs-18181B?style=for-the-badge&color=000000" alt="Documentation"></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"></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>
9
+
10
+ The AntelopeJS interface to send DMS mailing templates and report e-mail events from any module.
11
+
7
12
  </div>
8
13
 
9
- The public AntelopeJS interface of the DMS mailing module
10
- ([`@antelopejs/dms-mailing`](https://github.com/AntelopeJS/dms-mailing)). It
11
- carries the two interface functions other modules call, and the block and send
12
- types they exchange.
14
+ ## What it does
15
+
16
+ - Sends a published template by its slug, to one recipient or many, in a given locale and with its variables (`SendTemplate`).
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`).
19
+ - Imports past sends and their events with their own dates, for a demo data set or a move from another provider (`ImportSends`).
20
+ - Exports the template and send types (`Block`, `TemplateContent`, `VariableDefinition`, `SendStatus`, `EmailEvent`…) for code that builds or inspects templates.
21
+ - Keeps your module independent of the implementation, [`@antelopejs/dms-mailing`](https://www.npmjs.com/package/@antelopejs/dms-mailing).
22
+
23
+ ## Install
24
+
25
+ Add the interface to the module that sends e-mails:
26
+
27
+ ```bash
28
+ pnpm add @antelopejs/interface-dms-mailing
29
+ ```
30
+
31
+ ## Quick start
13
32
 
14
33
  ```ts
15
- import {
16
- RecordEmailEvent,
17
- SendTemplate,
18
- } from "@antelopejs/interface-dms-mailing";
34
+ import { RecordEmailEvent, SendTemplate } from "@antelopejs/interface-dms-mailing";
19
35
 
20
- // Render a live template and send it.
21
36
  const result = await SendTemplate("order-confirmation", {
22
37
  tenantId,
23
38
  to: [{ email: "sofie@example.com", name: "Sofie" }],
@@ -26,7 +41,6 @@ const result = await SendTemplate("order-confirmation", {
26
41
  source: "checkout",
27
42
  });
28
43
 
29
- // Report a provider event against the send it belongs to.
30
44
  await RecordEmailEvent(tenantId, {
31
45
  provider: "brevo",
32
46
  messageId,
@@ -35,20 +49,29 @@ await RecordEmailEvent(tenantId, {
35
49
  });
36
50
  ```
37
51
 
38
- A template whose footer links to an unsubscribe or a preferences page
39
- expects `unsubscribeUrl` / `preferencesUrl` in `variables` (required for the
40
- `marketing` category); a link without its URL is left out of the e-mail.
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`.
53
+
54
+ ## Compatibility
55
+
56
+ The implementation is `@antelopejs/dms-mailing >=0.5.0`; `DeclareTemplate`, `DeclareTemplateCategory` and `ImportSends` need the first release implementing interface 0.8, which depends on `>=0.8.0 <0.9.0`. The interface declares these dependencies:
57
+
58
+ <!-- docs-compat: ./package.json#dependencies -->
59
+
60
+ | Package | Range |
61
+ | --- | --- |
62
+ | `@antelopejs/interface-core` | `>=0.2.4 <1.0.0` |
63
+ | `@antelopejs/interface-email` | `>=0.0.6 <1.0.0` |
64
+
65
+ ## Documentation
66
+
67
+ - [Consumer reference](./docs/1.index.md): signatures, results, failures, tenant boundaries and template types
68
+ - [Extending the mailing module](https://dms.antelopejs.com/docs/modules/mailing/extending): sending from code, what a recipient receives, provider webhooks, automations
69
+ - [Mailing module guide](https://dms.antelopejs.com/docs/modules/mailing)
41
70
 
42
- A recipient on the workspace's suppression list (a hard bounce, a spam
43
- complaint, an unsubscription or a manual entry) gets no e-mail: its result
44
- has the status `suppressed`. A hard `bounced`, a `spam` or an `unsubscribed`
45
- event recorded through `RecordEmailEvent` puts the address on that list.
71
+ ## Contributing
46
72
 
47
- Declaring this package as a dependency is what wires a consumer to whichever
48
- module implements the interface; the implementation lives in
49
- `@antelopejs/dms-mailing` and is documented
50
- [there](https://github.com/AntelopeJS/dms-mailing/tree/main/packages/dms-mailing).
73
+ This package lives in the [`AntelopeJS/dms-mailing`](https://github.com/AntelopeJS/dms-mailing) pnpm workspace, next to the module that implements it. Read [CONTRIBUTING.md](https://github.com/AntelopeJS/dms-mailing/blob/main/CONTRIBUTING.md) and the [repository README](https://github.com/AntelopeJS/dms-mailing#contributing) for the development commands. Release this package before the module that implements it.
51
74
 
52
75
  ## License
53
76
 
54
- Apache-2.0
77
+ [Apache-2.0](./LICENSE)
package/dist/index.d.ts CHANGED
@@ -106,3 +106,60 @@ export type SendEventType = "queued" | "sent" | "delivered" | "opened" | "clicke
106
106
  export type SendStatus = SendEventType | "suppressed";
107
107
  export declare const SendTemplate: (slug: string, params: SendTemplateParams) => Promise<SendTemplateResult>;
108
108
  export declare const RecordEmailEvent: (tenantId: string, event: EmailEvent) => Promise<boolean>;
109
+ export interface TemplateDeclaration {
110
+ tenantId: string;
111
+ slug: string;
112
+ name: string;
113
+ category?: string;
114
+ content: TemplateContent;
115
+ variables?: VariableDefinition[];
116
+ testData?: Record<string, unknown>;
117
+ author?: string;
118
+ }
119
+ export type DeclarationOutcome = "created" | "updated" | "unchanged" | "kept";
120
+ export interface DeclareTemplateResult {
121
+ templateId: string;
122
+ slug: string;
123
+ outcome: DeclarationOutcome;
124
+ version: number;
125
+ }
126
+ export interface TemplateCategoryDeclaration {
127
+ tenantId: string;
128
+ id: string;
129
+ label: string;
130
+ icon: string;
131
+ }
132
+ export interface DeclareTemplateCategoryResult {
133
+ id: string;
134
+ outcome: DeclarationOutcome;
135
+ }
136
+ export interface ImportedSendEvent {
137
+ type: SendEventType;
138
+ at: Date;
139
+ details?: Record<string, unknown>;
140
+ }
141
+ export interface ImportedSend {
142
+ importId: string;
143
+ templateSlug: string;
144
+ to: EmailAddress;
145
+ sentAt: Date;
146
+ locale?: string;
147
+ variables?: Record<string, unknown>;
148
+ provider?: string;
149
+ providerMessageId?: string;
150
+ source?: string;
151
+ isTest?: boolean;
152
+ events?: ImportedSendEvent[];
153
+ }
154
+ export interface SendImport {
155
+ tenantId: string;
156
+ sends: ImportedSend[];
157
+ }
158
+ export interface ImportSendsResult {
159
+ imported: number;
160
+ skipped: number;
161
+ sendIds: string[];
162
+ }
163
+ export declare const DeclareTemplate: (declaration: TemplateDeclaration) => Promise<DeclareTemplateResult>;
164
+ export declare const DeclareTemplateCategory: (declaration: TemplateCategoryDeclaration) => Promise<DeclareTemplateCategoryResult>;
165
+ export declare const ImportSends: (params: SendImport) => Promise<ImportSendsResult>;
package/dist/index.js CHANGED
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RecordEmailEvent = exports.SendTemplate = void 0;
3
+ exports.ImportSends = exports.DeclareTemplateCategory = exports.DeclareTemplate = 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)();
7
+ exports.DeclareTemplate = (0, interface_core_1.InterfaceFunction)();
8
+ exports.DeclareTemplateCategory = (0, interface_core_1.InterfaceFunction)();
9
+ exports.ImportSends = (0, interface_core_1.InterfaceFunction)();
@@ -0,0 +1,343 @@
1
+ ---
2
+ title: Mailing interface
3
+ description: Consumer contract for sending templates and recording provider events with the DMS mailing interface.
4
+ ---
5
+
6
+ # Mailing interface
7
+
8
+ `@antelopejs/interface-dms-mailing` exposes five backend functions and the template types below: two to send and to report events, two to ship templates and categories 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
+
10
+ All five 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
+
12
+ ## SendTemplate
13
+
14
+ ```ts [Contract]
15
+ import type { EmailAddress } from "@antelopejs/interface-email";
16
+ import type { SendStatus, TemplateContent } from "@antelopejs/interface-dms-mailing";
17
+
18
+ interface SendTemplateParams {
19
+ tenantId: string;
20
+ to: EmailAddress | EmailAddress[];
21
+ locale?: string;
22
+ variables?: Record<string, unknown>;
23
+ content?: TemplateContent;
24
+ source?: string;
25
+ isTest?: boolean;
26
+ }
27
+
28
+ interface SendTemplateResult {
29
+ sendId: string;
30
+ status: SendStatus;
31
+ messageId?: string;
32
+ error?: string;
33
+ results?: SendTemplateResult[];
34
+ }
35
+
36
+ declare function SendTemplate(
37
+ slug: string,
38
+ params: SendTemplateParams,
39
+ ): Promise<SendTemplateResult>;
40
+ ```
41
+
42
+ `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.
43
+
44
+ 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.
45
+
46
+ ### Results and failures
47
+
48
+ For multiple recipients, **the top-level result describes the whole call**, not just the first recipient:
49
+
50
+ - `sendId` and `messageId` belong to the first recipient.
51
+ - `status` is the worst outcome: from best to worst, `clicked`, `opened`, `delivered`, `sent`, `queued`, `unsubscribed`, `suppressed`, `spam`, `bounced`, `failed`.
52
+ - `error` is the first nonempty error in recipient order, not necessarily the error of the recipient with the worst status.
53
+ - `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.
54
+
55
+ 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.
56
+
57
+ 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.
58
+
59
+ 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.
60
+
61
+ ### Consume per-recipient results
62
+
63
+ This example returns the outcomes for an authorized tenant; the caller decides
64
+ whether a failed recipient can be retried without duplicating delivery.
65
+
66
+ ```ts docs-check
67
+ import { SendTemplate } from "@antelopejs/interface-dms-mailing";
68
+
69
+ export async function sendOrderConfirmation(tenantId: string, recipients: string[]) {
70
+ const result = await SendTemplate("order-confirmation", {
71
+ tenantId,
72
+ to: recipients,
73
+ variables: { order: { total: "48.00" } },
74
+ source: "checkout",
75
+ });
76
+ return result.results ?? [result];
77
+ }
78
+ ```
79
+
80
+ ## RecordEmailEvent
81
+
82
+ ```ts [Contract]
83
+ type SendEventType =
84
+ | "queued" | "sent" | "delivered" | "opened" | "clicked"
85
+ | "bounced" | "spam" | "failed" | "unsubscribed";
86
+ type SendStatus = SendEventType | "suppressed";
87
+
88
+ interface EmailEvent {
89
+ provider: string;
90
+ messageId: string;
91
+ type: SendEventType;
92
+ at?: Date;
93
+ details?: Record<string, unknown>;
94
+ }
95
+
96
+ declare function RecordEmailEvent(
97
+ tenantId: string,
98
+ event: EmailEvent,
99
+ ): Promise<boolean>;
100
+ ```
101
+
102
+ `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.
103
+
104
+ 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.
105
+
106
+ 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; soft bounces and test sends do not. 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.
107
+
108
+ `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.
109
+
110
+ ## Ship templates as code
111
+
112
+ 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.
113
+
114
+ `DeclareTemplate`, `DeclareTemplateCategory` 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` 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.
115
+
116
+ ### DeclareTemplate
117
+
118
+ ```ts [Contract]
119
+ import type {
120
+ TemplateContent,
121
+ VariableDefinition,
122
+ } from "@antelopejs/interface-dms-mailing";
123
+
124
+ interface TemplateDeclaration {
125
+ tenantId: string; // explicit authorized workspace, non-blank
126
+ slug: string;
127
+ name: string;
128
+ category?: string; // a category id of the workspace settings
129
+ content: TemplateContent;
130
+ variables?: VariableDefinition[];
131
+ testData?: Record<string, unknown>;
132
+ author?: string; // shown as "updated by" / "published by"; "system" when absent
133
+ }
134
+
135
+ type DeclarationOutcome = "created" | "updated" | "unchanged" | "kept";
136
+
137
+ interface DeclareTemplateResult {
138
+ templateId: string;
139
+ slug: string;
140
+ outcome: DeclarationOutcome;
141
+ version: number; // last published version, or 0; not a live-status guarantee
142
+ }
143
+
144
+ declare function DeclareTemplate(
145
+ declaration: TemplateDeclaration,
146
+ ): Promise<DeclareTemplateResult>;
147
+ ```
148
+
149
+ 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:
150
+
151
+ | The template under that slug | Outcome | What is written |
152
+ | --- | --- | --- |
153
+ | does not exist | `created` | the template, published as v1 |
154
+ | was declared with the same declaration | `unchanged` | no content or lifecycle change, whatever a user did since; interrupted history may be repaired |
155
+ | 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) |
156
+ | 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 |
157
+
158
+ 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.
159
+
160
+ 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.
161
+
162
+ 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.
163
+
164
+ 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.
165
+
166
+ ### DeclareTemplateCategory
167
+
168
+ ```ts [Contract]
169
+ interface TemplateCategoryDeclaration {
170
+ tenantId: string;
171
+ id: string; // lowercase letters, digits and dashes
172
+ label: string;
173
+ icon: string; // a Phosphor icon, such as "i-ph-repeat"
174
+ }
175
+
176
+ interface DeclareTemplateCategoryResult {
177
+ id: string;
178
+ outcome: "created" | "updated" | "unchanged" | "kept";
179
+ }
180
+
181
+ declare function DeclareTemplateCategory(
182
+ declaration: TemplateCategoryDeclaration,
183
+ ): Promise<DeclareTemplateCategoryResult>;
184
+ ```
185
+
186
+ 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.
187
+
188
+ ### When to call
189
+
190
+ 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:
191
+
192
+ - in `construct()`, register lifecycle consumers synchronously, without calling or awaiting declarations: this ensures registration precedes startup reconciliation;
193
+ - 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;
194
+ - in a `Hook.DATABASE_INITIALIZED` handler, do not await them either: the hook's handlers run one after the other.
195
+
196
+ `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.
197
+
198
+ ```ts docs-check
199
+ import {
200
+ DeclareTemplate,
201
+ DeclareTemplateCategory,
202
+ } from "@antelopejs/interface-dms-mailing";
203
+
204
+ export async function declareMailingContent(tenantId: string): Promise<void> {
205
+ await DeclareTemplateCategory({ tenantId, id: "subscriptions", label: "Subscriptions", icon: "i-ph-repeat" });
206
+ const result = await DeclareTemplate({
207
+ tenantId,
208
+ slug: "subscription-renewed",
209
+ name: "Subscription renewed",
210
+ category: "subscriptions",
211
+ content: {
212
+ locales: {
213
+ en: {
214
+ subject: "Your {{plan.name}} plan is renewed",
215
+ preheader: "",
216
+ blocks: [
217
+ {
218
+ id: "intro",
219
+ type: "paragraph",
220
+ text: "Hello {{customer.firstName}}, thank you for staying with us.",
221
+ align: "left",
222
+ visibleIf: null,
223
+ },
224
+ ],
225
+ },
226
+ },
227
+ },
228
+ variables: [
229
+ { path: "customer.firstName", type: "string", required: true },
230
+ { path: "plan.name", type: "string", required: true },
231
+ ],
232
+ testData: { customer: { firstName: "Sofie" }, plan: { name: "Pro" } },
233
+ author: "Release script",
234
+ });
235
+ if (result.outcome === "kept") {
236
+ // Preserve the user's content and lifecycle; it may be archived.
237
+ }
238
+ }
239
+ ```
240
+
241
+ ### Initialize new SaaS workspaces
242
+
243
+ 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.
244
+
245
+ 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.
246
+
247
+ ```typescript
248
+ import { RegisterWorkspaceLifecycleConsumer } from "@antelopejs/interface-dms-saas/workspace-lifecycle";
249
+ import { declareMailingContent } from "./mailing-content"; // application function above
250
+
251
+ export function construct(): void {
252
+ RegisterWorkspaceLifecycleConsumer({
253
+ name: "application.mailing",
254
+ transitions: ["created"],
255
+ async consume({ tenantId, operationId }) {
256
+ // Application responsibility: deduplicate concurrent/replayed operationId
257
+ // durably, returning the recorded receipt for completed operations.
258
+ await declareMailingContent(tenantId);
259
+ // Persist the resource bindings and completed operation before returning
260
+ // its durable receiptId. A crash here must be recoverable on redelivery.
261
+ // Return { receiptId, ... } from that application-owned durable record.
262
+ throw new Error("Implement durable operation binding and receipt storage");
263
+ },
264
+ });
265
+ }
266
+ ```
267
+
268
+ 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.
269
+
270
+ ### Update existing SaaS workspaces
271
+
272
+ 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.
273
+
274
+ ## ImportSends
275
+
276
+ ```ts [Contract]
277
+ import type { EmailAddress } from "@antelopejs/interface-email";
278
+ import type { SendEventType } from "@antelopejs/interface-dms-mailing";
279
+
280
+ interface ImportedSendEvent {
281
+ type: SendEventType;
282
+ at: Date;
283
+ details?: Record<string, unknown>;
284
+ }
285
+
286
+ interface ImportedSend {
287
+ importId: string; // stable key chosen by the caller
288
+ templateSlug: string;
289
+ to: EmailAddress;
290
+ sentAt: Date;
291
+ locale?: string; // the workspace fallback locale when absent
292
+ variables?: Record<string, unknown>;
293
+ provider?: string;
294
+ providerMessageId?: string;
295
+ source?: string; // "import" when absent
296
+ isTest?: boolean;
297
+ events?: ImportedSendEvent[];
298
+ }
299
+
300
+ interface SendImport {
301
+ tenantId: string;
302
+ sends: ImportedSend[];
303
+ }
304
+
305
+ interface ImportSendsResult {
306
+ imported: number;
307
+ skipped: number;
308
+ sendIds: string[]; // one per entry, in the order given
309
+ }
310
+
311
+ declare function ImportSends(params: SendImport): Promise<ImportSendsResult>;
312
+ ```
313
+
314
+ **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.
315
+
316
+ 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.
317
+
318
+ 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.
319
+
320
+ 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.
321
+
322
+ ## Template types
323
+
324
+ `TemplateContent` is `{ locales: Record<string, LocaleContent> }`; each `LocaleContent` has `subject: string`, `preheader: string`, and `blocks: Block[]`.
325
+
326
+ 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"`.
327
+
328
+ | Interface / `type` | Additional fields |
329
+ | --- | --- |
330
+ | `HeroBlock` / `hero` | `imageUrl: string`, `alt: string` |
331
+ | `HeadingBlock` / `heading` | `text: string`, `align: TextAlign`, `size: number` |
332
+ | `ParagraphBlock` / `paragraph` | `text: string`, `align: TextAlign` |
333
+ | `CodeBlock` / `code` | `text: string` |
334
+ | `ListBlock` / `list` | `source: string`, `labelPath: string`, `valuePath: string` |
335
+ | `TotalBlock` / `total` | `label: string`, `value: string` |
336
+ | `ButtonBlock` / `button` | `text: string`, `href: string`, `align: TextAlign` |
337
+ | `IfBlock` / `if` | `condition: Condition`, `children: Block[]`, `elseChildren: Block[] \| null` |
338
+ | `DividerBlock` / `divider` | None |
339
+ | `FooterBlock` / `footer` | `text: string`, `unsubscribeLabel: string`, `preferencesLabel: string` |
340
+
341
+ `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`.
342
+
343
+ 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.
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "../tsconfig.json",
3
+ "compilerOptions": {
4
+ "rootDir": "..",
5
+ "composite": false,
6
+ "incremental": false,
7
+ "noEmit": true
8
+ },
9
+ "include": ["../src/**/*.ts", "./**/*.ts"]
10
+ }
package/package.json CHANGED
@@ -1,7 +1,18 @@
1
1
  {
2
2
  "name": "@antelopejs/interface-dms-mailing",
3
- "version": "0.7.0",
4
- "description": "AntelopeJS interface for DMS mailing",
3
+ "version": "0.8.0",
4
+ "description": "AntelopeJS interface for the DMS mailing module: send templates and report e-mail events from any module.",
5
+ "keywords": [
6
+ "antelopejs",
7
+ "dms",
8
+ "email",
9
+ "interface",
10
+ "mailing"
11
+ ],
12
+ "homepage": "https://dms.antelopejs.com/docs/modules/mailing/extending",
13
+ "bugs": {
14
+ "url": "https://github.com/AntelopeJS/dms-mailing/issues"
15
+ },
5
16
  "license": "Apache-2.0",
6
17
  "repository": {
7
18
  "type": "git",
@@ -11,6 +22,7 @@
11
22
  "files": [
12
23
  "dist",
13
24
  "!dist/.tsbuildinfo",
25
+ "docs",
14
26
  "LICENSE",
15
27
  "README.md"
16
28
  ],
@@ -41,11 +53,11 @@
41
53
  "typecheck": "tsc --noEmit"
42
54
  },
43
55
  "dependencies": {
44
- "@antelopejs/interface-core": ">=0.1.1 <1.0.0",
45
- "@antelopejs/interface-email": ">=0.0.5 <1.0.0"
56
+ "@antelopejs/interface-core": ">=0.2.4 <1.0.0",
57
+ "@antelopejs/interface-email": ">=0.0.6 <1.0.0"
46
58
  },
47
59
  "devDependencies": {
48
- "@antelopejs/tooling-configs": ">=0.0.7 <1.0.0",
60
+ "@antelopejs/tooling-configs": ">=0.0.9 <1.0.0",
49
61
  "@types/node": "^24.0.0",
50
62
  "oxfmt": "^0.66.0",
51
63
  "oxlint": "1.81.0",