@postxl/generators 1.25.0 → 1.26.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/dist/backend-actions/actions.generator.d.ts +11 -0
- package/dist/backend-actions/actions.generator.js.map +1 -1
- package/dist/backend-actions/generators/actions-module.generator.js +11 -3
- package/dist/backend-actions/generators/actions-module.generator.js.map +1 -1
- package/dist/backend-actions/generators/dispatcher-service.generator.js +12 -4
- package/dist/backend-actions/generators/dispatcher-service.generator.js.map +1 -1
- package/dist/backend-mail/generators/conditional-files.d.ts +15 -0
- package/dist/backend-mail/generators/conditional-files.js +410 -0
- package/dist/backend-mail/generators/conditional-files.js.map +1 -0
- package/dist/backend-mail/generators/env-config.generator.d.ts +16 -0
- package/dist/backend-mail/generators/env-config.generator.js +167 -0
- package/dist/backend-mail/generators/env-config.generator.js.map +1 -0
- package/dist/backend-mail/generators/mail.service.generator.d.ts +11 -0
- package/dist/backend-mail/generators/mail.service.generator.js +243 -0
- package/dist/backend-mail/generators/mail.service.generator.js.map +1 -0
- package/dist/backend-mail/index.d.ts +5 -0
- package/dist/backend-mail/index.js +41 -0
- package/dist/backend-mail/index.js.map +1 -0
- package/dist/backend-mail/mail.generator.d.ts +78 -0
- package/dist/backend-mail/mail.generator.js +162 -0
- package/dist/backend-mail/mail.generator.js.map +1 -0
- package/dist/backend-mail/template/src/adapters/log.adapter.ts +14 -0
- package/dist/backend-mail/template/src/adapters/mail-adapter.interface.ts +27 -0
- package/dist/backend-mail/template/src/mail.config.ts +42 -0
- package/dist/backend-mail/template/src/mail.module.ts +37 -0
- package/dist/backend-mail/template/src/mail.service.test.ts +195 -0
- package/dist/backend-mail/template/src/mail.types.ts +67 -0
- package/dist/backend-mail/template/src/templates/simple.renderer.test.ts +155 -0
- package/dist/backend-mail/template/src/templates/simple.renderer.ts +171 -0
- package/dist/backend-mail/template/src/templates/template-renderer.interface.ts +5 -0
- package/dist/backend-mail/template/tsconfig.lib.json +10 -0
- package/dist/generators.js +2 -0
- package/dist/generators.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +6 -2
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.generator = exports.configureBackendMailGenerator = exports.generatorId = void 0;
|
|
37
|
+
const node_path_1 = require("node:path");
|
|
38
|
+
const Generator = __importStar(require("@postxl/generator"));
|
|
39
|
+
const backend_actions_1 = require("../backend-actions");
|
|
40
|
+
const backend_core_1 = require("../backend-core");
|
|
41
|
+
const base_1 = require("../base");
|
|
42
|
+
const types_1 = require("../types");
|
|
43
|
+
const conditional_files_1 = require("./generators/conditional-files");
|
|
44
|
+
const env_config_generator_1 = require("./generators/env-config.generator");
|
|
45
|
+
const mail_service_generator_1 = require("./generators/mail.service.generator");
|
|
46
|
+
exports.generatorId = Generator.toGeneratorInterfaceId('backend-mail');
|
|
47
|
+
/**
|
|
48
|
+
* Configure and instantiate the `backend-mail` generator.
|
|
49
|
+
*
|
|
50
|
+
* The factory filters dependencies, env vars, adapter/renderer source
|
|
51
|
+
* files, and the `createAdapter` / `createRenderer` switches in
|
|
52
|
+
* `mail.service.ts` so that a project only ever ships with the adapters
|
|
53
|
+
* and renderers it actually uses.
|
|
54
|
+
*
|
|
55
|
+
* `log` and `simple` are always included; only the opt-in extras are
|
|
56
|
+
* configurable.
|
|
57
|
+
*/
|
|
58
|
+
const configureBackendMailGenerator = (options = {}) => {
|
|
59
|
+
const extraAdapters = options.adapters ?? [];
|
|
60
|
+
const extraRenderers = options.renderers ?? [];
|
|
61
|
+
// Deduplicate in case the caller passed the same value twice.
|
|
62
|
+
const adapters = Array.from(new Set(['log', ...extraAdapters]));
|
|
63
|
+
const renderers = Array.from(new Set(['simple', ...extraRenderers]));
|
|
64
|
+
const hasSes = adapters.includes('ses');
|
|
65
|
+
const hasSmtp = adapters.includes('smtp');
|
|
66
|
+
const hasEmailmd = renderers.includes('emailmd');
|
|
67
|
+
return {
|
|
68
|
+
id: exports.generatorId,
|
|
69
|
+
requires: [backend_core_1.backendGeneratorId, base_1.baseGeneratorId, backend_actions_1.backendActionsGeneratorId, types_1.typesGeneratorId],
|
|
70
|
+
register: (context) => {
|
|
71
|
+
const moduleClass = {
|
|
72
|
+
name: Generator.toClassName('MailModule'),
|
|
73
|
+
location: Generator.toBackendModuleLocation('@mail/mail.module'),
|
|
74
|
+
};
|
|
75
|
+
const serviceLocation = Generator.toBackendModuleLocation('@mail/mail.service');
|
|
76
|
+
const service = {
|
|
77
|
+
name: Generator.toClassName('MailService'),
|
|
78
|
+
variableName: Generator.toVariableName('mailService'),
|
|
79
|
+
location: serviceLocation,
|
|
80
|
+
};
|
|
81
|
+
const configLocation = Generator.toBackendModuleLocation('@mail/mail.config');
|
|
82
|
+
const config = {
|
|
83
|
+
name: Generator.toClassName('MailConfig'),
|
|
84
|
+
location: configLocation,
|
|
85
|
+
type: { name: Generator.toTypeName('MailConfigValues'), location: configLocation },
|
|
86
|
+
};
|
|
87
|
+
if (hasSes) {
|
|
88
|
+
context.backend.packageJson.dependencies.push({ packageName: '@aws-sdk/client-ses', version: '3.997.0' });
|
|
89
|
+
}
|
|
90
|
+
if (hasSmtp) {
|
|
91
|
+
context.backend.packageJson.dependencies.push({ packageName: 'nodemailer', version: '^6.9.16' });
|
|
92
|
+
context.backend.packageJson.devDependencies.push({
|
|
93
|
+
packageName: '@types/nodemailer',
|
|
94
|
+
version: '^6.4.17',
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
if (hasEmailmd) {
|
|
98
|
+
context.backend.packageJson.dependencies.push({ packageName: 'emailmd', version: '0.2.1' });
|
|
99
|
+
}
|
|
100
|
+
const mailModule = {
|
|
101
|
+
name: Generator.toBackendModuleName('mail'),
|
|
102
|
+
moduleClass,
|
|
103
|
+
apiModuleRegistration: {
|
|
104
|
+
code: Generator.ts('MailModule.forRoot(config.mail)'),
|
|
105
|
+
},
|
|
106
|
+
envConfig: (0, env_config_generator_1.buildEnvConfig)({ adapters, renderers }),
|
|
107
|
+
};
|
|
108
|
+
context.backend.modules.push(mailModule);
|
|
109
|
+
const provider = {
|
|
110
|
+
module: mailModule,
|
|
111
|
+
service,
|
|
112
|
+
scopes: new Set([(0, backend_actions_1.toScopeName)('mail')]),
|
|
113
|
+
needsForwardRef: false,
|
|
114
|
+
actions: {
|
|
115
|
+
summary: {
|
|
116
|
+
action: {
|
|
117
|
+
name: Generator.toTypeName('Action_Mail'),
|
|
118
|
+
location: Generator.toBackendModuleLocation('@mail/mail.types'),
|
|
119
|
+
},
|
|
120
|
+
result: {
|
|
121
|
+
name: Generator.toTypeName('ActionResult_Mail'),
|
|
122
|
+
location: Generator.toBackendModuleLocation('@mail/mail.types'),
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
context.actions.providers.push(provider);
|
|
128
|
+
return {
|
|
129
|
+
...context,
|
|
130
|
+
mail: { module: moduleClass, service, config, adapters, renderers },
|
|
131
|
+
};
|
|
132
|
+
},
|
|
133
|
+
generate: async (context) => {
|
|
134
|
+
const vfs = new Generator.VirtualFileSystem();
|
|
135
|
+
// Static files only (see `template/src/`). Everything adapter- or
|
|
136
|
+
// renderer-specific is emitted below via `vfs.write`.
|
|
137
|
+
await vfs.loadFolder({ diskPath: (0, node_path_1.resolve)(__dirname, './template') });
|
|
138
|
+
vfs.write('/src/mail.service.ts', (0, mail_service_generator_1.generateMailService)({ adapters, renderers }));
|
|
139
|
+
if (hasSes) {
|
|
140
|
+
vfs.write('/src/adapters/ses.adapter.ts', conditional_files_1.sesAdapterSource);
|
|
141
|
+
}
|
|
142
|
+
if (hasSmtp) {
|
|
143
|
+
vfs.write('/src/adapters/smtp.adapter.ts', conditional_files_1.smtpAdapterSource);
|
|
144
|
+
vfs.write('/src/adapters/smtp.adapter.test.ts', conditional_files_1.smtpAdapterTestSource);
|
|
145
|
+
}
|
|
146
|
+
if (hasEmailmd) {
|
|
147
|
+
vfs.write('/src/templates/emailmd.renderer.ts', conditional_files_1.emailmdRendererSource);
|
|
148
|
+
vfs.write('/src/templates/emailmd.renderer.test.ts', conditional_files_1.emailmdRendererTestSource);
|
|
149
|
+
}
|
|
150
|
+
context.vfs.insertFromVfs({ targetPath: '/backend/libs/mail', vfs });
|
|
151
|
+
return context;
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
};
|
|
155
|
+
exports.configureBackendMailGenerator = configureBackendMailGenerator;
|
|
156
|
+
/**
|
|
157
|
+
* Default generator: bundles `log` + `simple` only. Use
|
|
158
|
+
* `configureBackendMailGenerator({ adapters, renderers })` to opt in to
|
|
159
|
+
* more adapters or renderers.
|
|
160
|
+
*/
|
|
161
|
+
exports.generator = (0, exports.configureBackendMailGenerator)();
|
|
162
|
+
//# sourceMappingURL=mail.generator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mail.generator.js","sourceRoot":"","sources":["../../src/backend-mail/mail.generator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,yCAAmC;AAEnC,6DAA8C;AAE9C,wDAM2B;AAC3B,kDAA+E;AAC/E,kCAAmD;AACnD,oCAAsD;AAEtD,sEAMuC;AACvC,4EAAkE;AAClE,gFAAyE;AAwD5D,QAAA,WAAW,GAAG,SAAS,CAAC,sBAAsB,CAAC,cAAc,CAAC,CAAA;AAE3E;;;;;;;;;;GAUG;AACI,MAAM,6BAA6B,GAAG,CAC3C,UAAuC,EAAE,EACX,EAAE;IAChC,MAAM,aAAa,GAAG,OAAO,CAAC,QAAQ,IAAI,EAAE,CAAA;IAC5C,MAAM,cAAc,GAAG,OAAO,CAAC,SAAS,IAAI,EAAE,CAAA;IAE9C,8DAA8D;IAC9D,MAAM,QAAQ,GAA6C,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,GAAG,aAAa,CAAU,CAAC,CAAC,CAAA;IAClH,MAAM,SAAS,GAAiD,KAAK,CAAC,IAAI,CACxE,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,GAAG,cAAc,CAAU,CAAC,CAChD,CAAA;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EAAE,UAAU,EAAE,oBAAoB,EAAE,GAAG,EAAE,CAAC,CAAA;YACpE,OAAO,OAAO,CAAA;QAChB,CAAC;KACF,CAAA;AACH,CAAC,CAAA;AAnHY,QAAA,6BAA6B,iCAmHzC;AAED;;;;GAIG;AACU,QAAA,SAAS,GAAG,IAAA,qCAA6B,GAAE,CAAA"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Logger } from '@nestjs/common'
|
|
2
|
+
|
|
3
|
+
import type { IMailAdapter, MailPayload, MailSendResult } from './mail-adapter.interface'
|
|
4
|
+
|
|
5
|
+
export class LogAdapter implements IMailAdapter {
|
|
6
|
+
private readonly logger = new Logger(LogAdapter.name)
|
|
7
|
+
|
|
8
|
+
public send(payload: MailPayload): Promise<MailSendResult> {
|
|
9
|
+
this.logger.debug?.(
|
|
10
|
+
`Mail delivery disabled. bccCount=${(payload.bcc ?? []).length} htmlBytes=${payload.html.length}`,
|
|
11
|
+
)
|
|
12
|
+
return Promise.resolve({ success: true, status: 'disabled' })
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export type MailPayload = {
|
|
2
|
+
from: string
|
|
3
|
+
to: string
|
|
4
|
+
bcc?: string[]
|
|
5
|
+
subject: string
|
|
6
|
+
html: string
|
|
7
|
+
text?: string
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export type MailSendResultSuccessStatus = 'sent' | 'disabled'
|
|
11
|
+
export type MailSendResultErrorStatus = 'errorRejected' | 'errorInvalidEmail' | 'errorOther'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Result of a mail send attempt.
|
|
15
|
+
*
|
|
16
|
+
* `details` is constrained to an opaque string so it is safe to forward over
|
|
17
|
+
* the wire (e.g. through tRPC). Adapters MUST serialize any internal objects
|
|
18
|
+
* or errors before returning — never leak raw `Error` instances or SDK
|
|
19
|
+
* response objects out of the adapter boundary.
|
|
20
|
+
*/
|
|
21
|
+
export type MailSendResult =
|
|
22
|
+
| { success: true; status: MailSendResultSuccessStatus; details?: string }
|
|
23
|
+
| { success: false; status: MailSendResultErrorStatus; details?: string }
|
|
24
|
+
|
|
25
|
+
export interface IMailAdapter {
|
|
26
|
+
send(payload: MailPayload): Promise<MailSendResult>
|
|
27
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { Injectable } from '@nestjs/common'
|
|
2
|
+
|
|
3
|
+
export type MailAdapterName = 'log' | 'ses' | 'smtp'
|
|
4
|
+
export type MailTemplateRendererName = 'simple' | 'emailmd'
|
|
5
|
+
|
|
6
|
+
export type MailSesConfig = Readonly<{
|
|
7
|
+
region: string
|
|
8
|
+
useCredentials: boolean
|
|
9
|
+
accessKey?: string
|
|
10
|
+
secretAccessKey?: string
|
|
11
|
+
}>
|
|
12
|
+
|
|
13
|
+
export type MailSmtpConfig = Readonly<{
|
|
14
|
+
host: string
|
|
15
|
+
port: number
|
|
16
|
+
secure: boolean
|
|
17
|
+
user: string
|
|
18
|
+
password: string
|
|
19
|
+
}>
|
|
20
|
+
|
|
21
|
+
export type MailConfigValues = Readonly<{
|
|
22
|
+
isEnabled: boolean
|
|
23
|
+
adapter: MailAdapterName
|
|
24
|
+
templateRenderer: MailTemplateRendererName
|
|
25
|
+
from: string
|
|
26
|
+
admins: ReadonlyArray<string>
|
|
27
|
+
/**
|
|
28
|
+
* SES adapter configuration. Present when the `ses` adapter was enabled
|
|
29
|
+
* at generation time via `configureBackendMailGenerator({ adapters })`.
|
|
30
|
+
*/
|
|
31
|
+
ses?: MailSesConfig
|
|
32
|
+
/**
|
|
33
|
+
* SMTP adapter configuration. Present when the `smtp` adapter was
|
|
34
|
+
* enabled at generation time via `configureBackendMailGenerator({ adapters })`.
|
|
35
|
+
*/
|
|
36
|
+
smtp?: MailSmtpConfig
|
|
37
|
+
}>
|
|
38
|
+
|
|
39
|
+
@Injectable()
|
|
40
|
+
export class MailConfig {
|
|
41
|
+
constructor(public readonly values: MailConfigValues) {}
|
|
42
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { DynamicModule } from '@nestjs/common'
|
|
2
|
+
|
|
3
|
+
import { MailConfig, type MailConfigValues } from './mail.config'
|
|
4
|
+
import { MailService } from './mail.service'
|
|
5
|
+
|
|
6
|
+
export class MailModule {
|
|
7
|
+
/**
|
|
8
|
+
* Register the mail module.
|
|
9
|
+
*
|
|
10
|
+
* `global: true` is deliberate. This module is opt-in at the generator
|
|
11
|
+
* level, but once a project enables it the mail-backed actions
|
|
12
|
+
* (`sendMail`, `sendMailToUser`) are dispatched from the shared
|
|
13
|
+
* `DispatcherService` in `ActionsModule`. Because `MailModule.forRoot`
|
|
14
|
+
* is invoked once at the API root (where `config.mail` lives) and other
|
|
15
|
+
* modules like `ActionsModule` only import the plain `MailModule`
|
|
16
|
+
* symbol, Nest's dynamic-module scoping cannot reach the configured
|
|
17
|
+
* `MailService` / `MailConfig` providers without a global registration.
|
|
18
|
+
*
|
|
19
|
+
* The alternative would be to re-`forRoot` from every consumer or to
|
|
20
|
+
* couple `ActionsModule` to the mail config shape, both of which are
|
|
21
|
+
* worse than a clearly-scoped global module.
|
|
22
|
+
*/
|
|
23
|
+
static forRoot(config: MailConfigValues): DynamicModule {
|
|
24
|
+
return {
|
|
25
|
+
module: MailModule,
|
|
26
|
+
providers: [
|
|
27
|
+
MailService,
|
|
28
|
+
{
|
|
29
|
+
provide: MailConfig,
|
|
30
|
+
useValue: new MailConfig(config),
|
|
31
|
+
},
|
|
32
|
+
],
|
|
33
|
+
exports: [MailService, MailConfig],
|
|
34
|
+
global: true,
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { describe, expect, it, jest } from '@jest/globals'
|
|
2
|
+
|
|
3
|
+
import type { IMailAdapter, MailPayload, MailSendResult } from './adapters/mail-adapter.interface'
|
|
4
|
+
import { MailConfig, type MailConfigValues } from './mail.config'
|
|
5
|
+
import { createAdapter, MailService } from './mail.service'
|
|
6
|
+
import type { ITemplateRenderer } from './templates/template-renderer.interface'
|
|
7
|
+
|
|
8
|
+
type MinimalExecution = {
|
|
9
|
+
startTransformation: ReturnType<typeof jest.fn>
|
|
10
|
+
finishTransformation: ReturnType<typeof jest.fn>
|
|
11
|
+
errorActionOperation: ReturnType<typeof jest.fn>
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function createExecution(): MinimalExecution {
|
|
15
|
+
return {
|
|
16
|
+
startTransformation: jest.fn(() => Promise.resolve('op-1' as unknown)),
|
|
17
|
+
finishTransformation: jest.fn(() => Promise.resolve(undefined)),
|
|
18
|
+
errorActionOperation: jest.fn(() => Promise.resolve(undefined)),
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function createConfig(overrides: Partial<MailConfigValues> = {}): MailConfig {
|
|
23
|
+
const values: MailConfigValues = {
|
|
24
|
+
isEnabled: true,
|
|
25
|
+
adapter: 'log',
|
|
26
|
+
templateRenderer: 'simple',
|
|
27
|
+
from: 'noreply@example.com',
|
|
28
|
+
admins: ['admin@example.com'],
|
|
29
|
+
ses: { region: 'eu-central-1', useCredentials: false },
|
|
30
|
+
smtp: { host: '', port: 587, secure: false, user: '', password: '' },
|
|
31
|
+
...overrides,
|
|
32
|
+
}
|
|
33
|
+
return new MailConfig(values)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
class SpyAdapter implements IMailAdapter {
|
|
37
|
+
public readonly sent: MailPayload[] = []
|
|
38
|
+
constructor(private readonly result: MailSendResult = { success: true, status: 'sent' }) {}
|
|
39
|
+
send(payload: MailPayload): Promise<MailSendResult> {
|
|
40
|
+
this.sent.push(payload)
|
|
41
|
+
return Promise.resolve(this.result)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
class FailingAdapter implements IMailAdapter {
|
|
46
|
+
send(): Promise<MailSendResult> {
|
|
47
|
+
return Promise.resolve({ success: false, status: 'errorRejected', details: 'nope' })
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
class SpyRenderer implements ITemplateRenderer {
|
|
52
|
+
public readonly calls: Array<{ source: string; data: Record<string, unknown> }> = []
|
|
53
|
+
render(source: string, data: Record<string, unknown>) {
|
|
54
|
+
this.calls.push({ source, data })
|
|
55
|
+
return { html: `rendered:${source}`, text: `text:${source}` }
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
describe('MailService', () => {
|
|
60
|
+
it('uses LogAdapter when mail is disabled', async () => {
|
|
61
|
+
const config = createConfig({ isEnabled: false })
|
|
62
|
+
const adapter = createAdapter(config.values)
|
|
63
|
+
expect(adapter.constructor.name).toBe('LogAdapter')
|
|
64
|
+
|
|
65
|
+
const service = new MailService(config, { adapter })
|
|
66
|
+
const execution = createExecution()
|
|
67
|
+
|
|
68
|
+
const result = await service.sendMail({
|
|
69
|
+
mail: { to: 'a@example.com', subject: 'hi', html: '<p>hi</p>', informAdmins: false },
|
|
70
|
+
execution: execution as never,
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
expect(result).toEqual({ success: true, status: 'disabled' })
|
|
74
|
+
expect(execution.startTransformation).toHaveBeenCalledTimes(1)
|
|
75
|
+
expect(execution.finishTransformation).toHaveBeenCalledTimes(1)
|
|
76
|
+
expect(execution.errorActionOperation).not.toHaveBeenCalled()
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
it('includes admins in bcc when informAdmins is true', async () => {
|
|
80
|
+
const adapter = new SpyAdapter()
|
|
81
|
+
const service = new MailService(createConfig(), { adapter })
|
|
82
|
+
const execution = createExecution()
|
|
83
|
+
|
|
84
|
+
await service.sendMail({
|
|
85
|
+
mail: { to: 'a@example.com', subject: 'hi', html: '<p>hi</p>', informAdmins: true },
|
|
86
|
+
execution: execution as never,
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
expect(adapter.sent).toHaveLength(1)
|
|
90
|
+
expect(adapter.sent[0]).toMatchObject({
|
|
91
|
+
from: 'noreply@example.com',
|
|
92
|
+
to: 'a@example.com',
|
|
93
|
+
bcc: ['admin@example.com'],
|
|
94
|
+
})
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
it('does not include admins in bcc when informAdmins is false', async () => {
|
|
98
|
+
const adapter = new SpyAdapter()
|
|
99
|
+
const service = new MailService(createConfig(), { adapter })
|
|
100
|
+
const execution = createExecution()
|
|
101
|
+
|
|
102
|
+
await service.sendMail({
|
|
103
|
+
mail: { to: 'a@example.com', subject: 'hi', html: '<p>hi</p>', informAdmins: false },
|
|
104
|
+
execution: execution as never,
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
expect(adapter.sent[0]?.bcc).toEqual([])
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
it('rejects empty user email in sendMailToUser, audits the failure, and bypasses the adapter', async () => {
|
|
111
|
+
const adapter = new SpyAdapter()
|
|
112
|
+
const service = new MailService(createConfig(), { adapter })
|
|
113
|
+
const execution = createExecution()
|
|
114
|
+
|
|
115
|
+
const result = await service.sendMailToUser({
|
|
116
|
+
payload: {
|
|
117
|
+
user: { id: 'user-1' as never, name: 'Ada', email: ' ' },
|
|
118
|
+
subject: 'hi',
|
|
119
|
+
html: '<p>hi</p>',
|
|
120
|
+
informAdmins: false,
|
|
121
|
+
},
|
|
122
|
+
execution: execution as never,
|
|
123
|
+
})
|
|
124
|
+
|
|
125
|
+
expect(result).toEqual({ success: false, status: 'errorInvalidEmail', details: 'Invalid user email' })
|
|
126
|
+
expect(adapter.sent).toHaveLength(0)
|
|
127
|
+
expect(execution.startTransformation).toHaveBeenCalledTimes(1)
|
|
128
|
+
expect(execution.errorActionOperation).toHaveBeenCalledTimes(1)
|
|
129
|
+
expect(execution.finishTransformation).not.toHaveBeenCalled()
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
it('dispatch calls startTransformation and finishTransformation on success', async () => {
|
|
133
|
+
const adapter = new SpyAdapter()
|
|
134
|
+
const service = new MailService(createConfig(), { adapter })
|
|
135
|
+
const execution = createExecution()
|
|
136
|
+
|
|
137
|
+
await service.dispatch({
|
|
138
|
+
action: {
|
|
139
|
+
scope: 'mail',
|
|
140
|
+
type: 'sendMail',
|
|
141
|
+
payload: { to: 'a@example.com', subject: 'hi', html: '<p>hi</p>', informAdmins: false },
|
|
142
|
+
},
|
|
143
|
+
execution: execution as never,
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
expect(execution.startTransformation).toHaveBeenCalledTimes(1)
|
|
147
|
+
expect(execution.finishTransformation).toHaveBeenCalledTimes(1)
|
|
148
|
+
expect(execution.errorActionOperation).not.toHaveBeenCalled()
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
it('dispatch calls errorActionOperation when the adapter fails', async () => {
|
|
152
|
+
const service = new MailService(createConfig(), { adapter: new FailingAdapter() })
|
|
153
|
+
const execution = createExecution()
|
|
154
|
+
|
|
155
|
+
const result = await service.dispatch({
|
|
156
|
+
action: {
|
|
157
|
+
scope: 'mail',
|
|
158
|
+
type: 'sendMail',
|
|
159
|
+
payload: { to: 'a@example.com', subject: 'hi', html: '<p>hi</p>', informAdmins: false },
|
|
160
|
+
},
|
|
161
|
+
execution: execution as never,
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
expect(result.success).toBe(false)
|
|
165
|
+
expect(execution.startTransformation).toHaveBeenCalledTimes(1)
|
|
166
|
+
expect(execution.finishTransformation).not.toHaveBeenCalled()
|
|
167
|
+
expect(execution.errorActionOperation).toHaveBeenCalledTimes(1)
|
|
168
|
+
})
|
|
169
|
+
|
|
170
|
+
it('renderAndSend runs the configured renderer before sending', async () => {
|
|
171
|
+
const adapter = new SpyAdapter()
|
|
172
|
+
const renderer = new SpyRenderer()
|
|
173
|
+
const service = new MailService(createConfig(), { adapter, renderer })
|
|
174
|
+
const execution = createExecution()
|
|
175
|
+
|
|
176
|
+
await service.renderAndSend({
|
|
177
|
+
template: '<p>Hi {{name}}</p>',
|
|
178
|
+
data: { name: 'Ada' },
|
|
179
|
+
subject: 'hi',
|
|
180
|
+
to: 'ada@example.com',
|
|
181
|
+
execution: execution as never,
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
expect(renderer.calls).toHaveLength(1)
|
|
185
|
+
expect(renderer.calls[0]).toEqual({
|
|
186
|
+
source: '<p>Hi {{name}}</p>',
|
|
187
|
+
data: { name: 'Ada' },
|
|
188
|
+
})
|
|
189
|
+
expect(adapter.sent[0]).toMatchObject({
|
|
190
|
+
to: 'ada@example.com',
|
|
191
|
+
html: 'rendered:<p>Hi {{name}}</p>',
|
|
192
|
+
text: 'text:<p>Hi {{name}}</p>',
|
|
193
|
+
})
|
|
194
|
+
})
|
|
195
|
+
})
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { zUserId } from '@types'
|
|
2
|
+
|
|
3
|
+
import { z } from 'zod'
|
|
4
|
+
|
|
5
|
+
export type Action_Mail = Action_Mail_SendMail | Action_Mail_SendMailToUser
|
|
6
|
+
|
|
7
|
+
export type ActionResult_Mail = {
|
|
8
|
+
sendMail: SendMailResult
|
|
9
|
+
sendMailToUser: SendMailResult
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type Action_Mail_SendMail = {
|
|
13
|
+
scope: 'mail'
|
|
14
|
+
type: 'sendMail'
|
|
15
|
+
payload: SendMailPayload
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const zSendMailDecoder = z.object({
|
|
19
|
+
to: z.string().email(),
|
|
20
|
+
subject: z.string().min(2),
|
|
21
|
+
html: z.string().min(2),
|
|
22
|
+
text: z.string().optional(),
|
|
23
|
+
informAdmins: z.boolean().default(false),
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
export type SendMailPayload = z.infer<typeof zSendMailDecoder>
|
|
27
|
+
|
|
28
|
+
export type SendMailStatus = 'sent' | 'disabled' | 'errorRejected' | 'errorInvalidEmail' | 'errorOther'
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Action-level result returned by `MailService.sendMail` and
|
|
32
|
+
* `MailService.sendMailToUser`.
|
|
33
|
+
*
|
|
34
|
+
* Mirrors `MailSendResult` from the adapter interface: `details` is
|
|
35
|
+
* constrained to an opaque string so the value is safe to forward through
|
|
36
|
+
* tRPC or persist in the action-execution log without risking leakage of
|
|
37
|
+
* raw Error instances or SDK response objects.
|
|
38
|
+
*/
|
|
39
|
+
export type SendMailResult = {
|
|
40
|
+
success: boolean
|
|
41
|
+
status: SendMailStatus
|
|
42
|
+
details?: string
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export type Action_Mail_SendMailToUser = {
|
|
46
|
+
scope: 'mail'
|
|
47
|
+
type: 'sendMailToUser'
|
|
48
|
+
payload: SendMailToUserPayload
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export const zMailUser = z.object({
|
|
52
|
+
id: zUserId,
|
|
53
|
+
name: z.string(),
|
|
54
|
+
email: z.string().email(),
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
export type MailUser = z.infer<typeof zMailUser>
|
|
58
|
+
|
|
59
|
+
export const zSendMailToUserDecoder = z.object({
|
|
60
|
+
user: zMailUser,
|
|
61
|
+
subject: z.string().min(2),
|
|
62
|
+
html: z.string().min(2),
|
|
63
|
+
text: z.string().optional(),
|
|
64
|
+
informAdmins: z.boolean().default(false),
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
export type SendMailToUserPayload = z.infer<typeof zSendMailToUserDecoder>
|