@matfire/facteur 0.0.0 → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matteo Gassend
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,220 @@
1
- # @matfire/facteur
1
+ # Facteur
2
2
 
3
- This is a stub package published by setup-trusted-publishing to enable OIDC trusted publishing configuration.
3
+ A configurable email provider. Pick Resend, Amazon SES or SMTP (via nodemailer) with environment variables, and send email through the same client whichever one you use.
4
+
5
+ Built on [Effect](https://effect.website), with a Promise API for projects that don't use Effect.
6
+
7
+ ## Functionality
8
+
9
+ - define config through environment variables (config file support is planned)
10
+ - drivers are tree-shakeable, and each provider's SDK is an optional peer dependency
11
+ - import the same client
12
+ - send email
13
+
14
+ ## Install
15
+
16
+ Install the library and the SDK of the provider you use. The other providers' SDKs are not needed.
17
+
18
+ ```bash
19
+ npm install @matfire/facteur resend # Resend
20
+ npm install @matfire/facteur @aws-sdk/client-sesv2 # Amazon SES
21
+ npm install @matfire/facteur nodemailer # SMTP
22
+ ```
23
+
24
+ Effect is installed with the library. Add `effect` to your own dependencies too if you import from it, for example to use the [Effect API](#with-effect), pass a `Redacted` key when [choosing the provider in code](#choose-the-provider-in-code), or write a [test fake](#test-your-app-without-sending-email):
25
+
26
+ ```bash
27
+ npm install effect
28
+ ```
29
+
30
+ ## Configure
31
+
32
+ Set `FACTEUR_PROVIDER` and that provider's variables.
33
+
34
+ ### Resend
35
+
36
+ | Variable | Required |
37
+ | ------------------------- | -------- |
38
+ | `FACTEUR_PROVIDER=RESEND` | yes |
39
+ | `FACTEUR_RESEND_KEY` | yes |
40
+
41
+ ### Amazon SES
42
+
43
+ | Variable | Required | Notes |
44
+ | ------------------------------- | -------- | --------------------------------------------------------------------------------------------------- |
45
+ | `FACTEUR_PROVIDER=SES` | yes | |
46
+ | `FACTEUR_SES_REGION` | yes | |
47
+ | `FACTEUR_SES_ACCESS_KEY_ID` | no | Needs `FACTEUR_SES_SECRET_ACCESS_KEY` too |
48
+ | `FACTEUR_SES_SECRET_ACCESS_KEY` | no | Without both keys, the AWS SDK default credential chain is used (AWS env vars, `~/.aws`, IAM roles) |
49
+
50
+ ### SMTP (nodemailer)
51
+
52
+ | Variable | Required | Notes |
53
+ | ----------------------------- | -------- | ---------------------------------------------- |
54
+ | `FACTEUR_PROVIDER=NODEMAILER` | yes | |
55
+ | `FACTEUR_NODEMAILER_HOST` | yes | |
56
+ | `FACTEUR_NODEMAILER_PORT` | no | nodemailer defaults to 587, or 465 when secure |
57
+ | `FACTEUR_NODEMAILER_SECURE` | no | Defaults to `false` |
58
+ | `FACTEUR_NODEMAILER_USER` | no | Needs `FACTEUR_NODEMAILER_PASS` too |
59
+ | `FACTEUR_NODEMAILER_PASS` | no | |
60
+
61
+ An unknown provider or a missing required variable fails when the mailer is built, before any email is sent.
62
+
63
+ ## Send email
64
+
65
+ Every email needs `from`, `to`, `subject`, and at least one of `html` or `text`. `cc`, `bcc` and `replyTo` are optional. `to`, `cc`, `bcc` and `replyTo` accept one address or an array.
66
+
67
+ ### Without Effect
68
+
69
+ `createMailer` returns a Promise-based client. Create it once and reuse it.
70
+
71
+ ```ts
72
+ import { createMailer } from "@matfire/facteur";
73
+
74
+ const mailer = createMailer();
75
+
76
+ const { id } = await mailer.sendEmail({
77
+ from: "Acme <hello@acme.com>",
78
+ to: "someone@example.com",
79
+ subject: "Welcome!",
80
+ html: "<p>Thanks for signing up.</p>",
81
+ });
82
+
83
+ // On shutdown, close SMTP connections / the SES client:
84
+ await mailer.dispose();
85
+ ```
86
+
87
+ The provider is built from the environment on the first `sendEmail` call. `sendEmail` rejects with a `MailerError` if sending fails, or with a config error if the environment is incomplete.
88
+
89
+ #### Automatic cleanup with `await using`
90
+
91
+ The client supports [explicit resource management](https://github.com/tc39/proposal-explicit-resource-management). Declare it with `await using` and it is disposed when the block exits, even if sending throws. This suits short-lived work such as scripts, jobs or a single request:
92
+
93
+ ```ts
94
+ import { createMailer } from "@matfire/facteur";
95
+
96
+ {
97
+ await using mailer = createMailer();
98
+ await mailer.sendEmail({
99
+ from: "Acme <hello@acme.com>",
100
+ to: "someone@example.com",
101
+ subject: "Report ready",
102
+ text: "Your weekly report is attached.",
103
+ });
104
+ } // SMTP connections / the SES client are closed here
105
+ ```
106
+
107
+ Use `await using`, not plain `using`: closing connections is asynchronous. In a long-running server, create one client at startup and call `dispose()` on shutdown instead.
108
+
109
+ Requirements:
110
+
111
+ - **Runtime**: Node.js 24+ supports `await using` natively. Support in other runtimes and browsers varies, so check your target; where it's missing, let TypeScript or your bundler downlevel the syntax to `try`/`finally`.
112
+ - **TypeScript**: 5.2+, with `"esnext.disposable"` (or `"esnext"`) in `compilerOptions.lib`. No yearly lib up to `es2025` includes it yet. `@types/node` and `effect` already reference it, so it often works without changes.
113
+
114
+ ### With Effect
115
+
116
+ Depend on the `Mailer` service and provide `layerConfig` at your entry point.
117
+
118
+ ```ts
119
+ import { Effect } from "effect";
120
+ import { layerConfig, Mailer } from "@matfire/facteur";
121
+
122
+ const sendWelcome = Effect.fn("sendWelcome")(function* (to: string) {
123
+ const mailer = yield* Mailer;
124
+ return yield* mailer.send({
125
+ from: "Acme <hello@acme.com>",
126
+ to,
127
+ subject: "Welcome!",
128
+ html: "<p>Thanks for signing up.</p>",
129
+ });
130
+ });
131
+
132
+ sendWelcome("someone@example.com").pipe(Effect.provide(layerConfig), Effect.runPromise);
133
+ ```
134
+
135
+ `send` fails with a `MailerError`, which carries `provider`, `message` and the original `cause`:
136
+
137
+ ```ts
138
+ mailer
139
+ .send(email)
140
+ .pipe(Effect.catchTag("MailerError", (e) => Effect.logError(`[${e.provider}] ${e.message}`)));
141
+ ```
142
+
143
+ ## Choose the provider in code
144
+
145
+ To skip environment variables, import a driver directly and pass its layer to `createMailer`, or provide it with `Effect.provide`. Each driver also has a `layerConfig` that reads only its own variables.
146
+
147
+ ```ts
148
+ import { Redacted } from "effect";
149
+ import { createMailer } from "@matfire/facteur";
150
+ import * as Nodemailer from "@matfire/facteur/drivers/nodemailer";
151
+ import * as Resend from "@matfire/facteur/drivers/resend";
152
+ import * as Ses from "@matfire/facteur/drivers/ses";
153
+
154
+ createMailer(Resend.layer({ apiKey: Redacted.make(process.env.MY_RESEND_KEY!) }));
155
+ createMailer(Ses.layer({ region: "eu-west-1" })); // any SESv2 client config
156
+ createMailer(Nodemailer.layer("smtps://user:pass@host")); // any nodemailer transport config
157
+ ```
158
+
159
+ ## Test your app without sending email
160
+
161
+ `Mailer` is a regular Effect service, so tests can swap in a fake:
162
+
163
+ ```ts
164
+ import { Effect, Layer } from "effect";
165
+ import { createMailer, Mailer } from "@matfire/facteur";
166
+
167
+ const sent: Array<unknown> = [];
168
+ const MailerTest = Layer.succeed(
169
+ Mailer,
170
+ Mailer.of({
171
+ send: (email) =>
172
+ Effect.sync(() => {
173
+ sent.push(email);
174
+ return { id: "test" };
175
+ }),
176
+ }),
177
+ );
178
+
179
+ // With Effect:
180
+ await sendWelcome("a@b.com").pipe(Effect.provide(MailerTest), Effect.runPromise);
181
+
182
+ // Without Effect:
183
+ await createMailer(MailerTest).sendEmail({
184
+ from: "a@b.com",
185
+ to: "c@d.com",
186
+ subject: "Hi",
187
+ text: "Hi",
188
+ });
189
+ ```
190
+
191
+ ## Development
192
+
193
+ - Install the tools (bun, [lefthook](https://lefthook.dev), [cocogitto](https://docs.cocogitto.io)) with [mise](https://mise.jdx.dev), then the dependencies and the git hooks:
194
+
195
+ ```bash
196
+ mise install
197
+ bun install
198
+ lefthook install
199
+ ```
200
+
201
+ The hooks format staged files with oxfmt and lint them with oxlint before each commit, and check that commit messages follow [Conventional Commits](https://www.conventionalcommits.org) with `cog verify`. Release-please builds the version number and changelog from those messages, so use types such as `feat:`, `fix:` or `feat!:` for breaking changes.
202
+
203
+ - Run the unit tests:
204
+
205
+ ```bash
206
+ bun run test
207
+ ```
208
+
209
+ - Lint with [oxlint](https://oxc.rs/docs/guide/usage/linter) (warnings fail the check) and format with [oxfmt](https://oxc.rs/docs/guide/usage/formatter):
210
+
211
+ ```bash
212
+ bun run lint # or lint:fix
213
+ bun run format # or format:check
214
+ ```
215
+
216
+ - Build the library:
217
+
218
+ ```bash
219
+ bun run build
220
+ ```
@@ -0,0 +1,32 @@
1
+ import { Context, Schema } from "effect";
2
+ // src/Mailer.ts
3
+ const Recipients = Schema.Union([Schema.String, Schema.Array(Schema.String)]);
4
+ const EmailFields = {
5
+ from: Schema.String,
6
+ to: Recipients,
7
+ subject: Schema.String,
8
+ cc: Schema.optionalKey(Recipients),
9
+ bcc: Schema.optionalKey(Recipients),
10
+ replyTo: Schema.optionalKey(Recipients)
11
+ };
12
+ /**
13
+ * An email needs a body: `html`, `text`, or both. The union makes leaving out
14
+ * both a type error, and decoding enforces it at runtime.
15
+ */
16
+ const Email = Schema.Union([Schema.Struct({
17
+ ...EmailFields,
18
+ html: Schema.String,
19
+ text: Schema.optionalKey(Schema.String)
20
+ }), Schema.Struct({
21
+ ...EmailFields,
22
+ text: Schema.String,
23
+ html: Schema.optionalKey(Schema.String)
24
+ })]);
25
+ const SentEmail = Schema.Struct({ id: Schema.String });
26
+ var MailerError = class extends Schema.TaggedError()("MailerError", {
27
+ provider: Schema.String,
28
+ message: Schema.String,
29
+ cause: Schema.optionalKey(Schema.Defect())
30
+ }) {};
31
+ var Mailer = class extends Context.Service()("facteur/Mailer") {};
32
+ export { SentEmail as i, Mailer as n, MailerError as r, Email as t };
@@ -0,0 +1,40 @@
1
+ import { Context, Effect, Schema } from "effect";
2
+ /**
3
+ * An email needs a body: `html`, `text`, or both. The union makes leaving out
4
+ * both a type error, and decoding enforces it at runtime.
5
+ */
6
+ declare const Email: Schema.Union<readonly [Schema.Struct<{
7
+ readonly from: Schema.String;
8
+ readonly to: Schema.Union<readonly [Schema.String, Schema.$Array<Schema.String>]>;
9
+ readonly subject: Schema.String;
10
+ readonly cc: Schema.optionalKey<Schema.Union<readonly [Schema.String, Schema.$Array<Schema.String>]>>;
11
+ readonly bcc: Schema.optionalKey<Schema.Union<readonly [Schema.String, Schema.$Array<Schema.String>]>>;
12
+ readonly replyTo: Schema.optionalKey<Schema.Union<readonly [Schema.String, Schema.$Array<Schema.String>]>>;
13
+ readonly html: Schema.String;
14
+ readonly text: Schema.optionalKey<Schema.String>;
15
+ }>, Schema.Struct<{
16
+ readonly from: Schema.String;
17
+ readonly to: Schema.Union<readonly [Schema.String, Schema.$Array<Schema.String>]>;
18
+ readonly subject: Schema.String;
19
+ readonly cc: Schema.optionalKey<Schema.Union<readonly [Schema.String, Schema.$Array<Schema.String>]>>;
20
+ readonly bcc: Schema.optionalKey<Schema.Union<readonly [Schema.String, Schema.$Array<Schema.String>]>>;
21
+ readonly replyTo: Schema.optionalKey<Schema.Union<readonly [Schema.String, Schema.$Array<Schema.String>]>>;
22
+ readonly text: Schema.String;
23
+ readonly html: Schema.optionalKey<Schema.String>;
24
+ }>]>;
25
+ type Email = typeof Email.Type;
26
+ declare const SentEmail: Schema.Struct<{
27
+ readonly id: Schema.String;
28
+ }>;
29
+ type SentEmail = typeof SentEmail.Type;
30
+ declare const MailerError_base: Schema.Class<MailerError, Schema.TaggedStruct<"MailerError", {
31
+ readonly provider: Schema.String;
32
+ readonly message: Schema.String;
33
+ readonly cause: Schema.optionalKey<Schema.Defect>;
34
+ }>, import("effect/Cause").YieldableError>;
35
+ declare class MailerError extends MailerError_base {}
36
+ declare const Mailer_base: Context.ServiceClass<Mailer, "facteur/Mailer", {
37
+ send(email: Email): Effect.Effect<SentEmail, MailerError>;
38
+ }>;
39
+ declare class Mailer extends Mailer_base {}
40
+ export { SentEmail as i, Mailer as n, MailerError as r, Email as t };
@@ -0,0 +1,18 @@
1
+ import { TransportConfig } from "nodemailer";
2
+ import { Config, Layer } from "effect";
3
+ import { n as Mailer } from "../Mailer-DOT-aXZD.mjs";
4
+ /**
5
+ * Accepts any nodemailer transport config (SMTP options, a connection URL,
6
+ * `{ jsonTransport: true }`, ...). The transport is closed when the layer's
7
+ * scope ends.
8
+ */
9
+ export declare const layer: (transport: TransportConfig | string) => Layer.Layer<Mailer, never, never>;
10
+ /**
11
+ * SMTP transport from the environment:
12
+ *
13
+ * - `FACTEUR_NODEMAILER_HOST` (required)
14
+ * - `FACTEUR_NODEMAILER_PORT` (optional, nodemailer defaults to 587, or 465 when secure)
15
+ * - `FACTEUR_NODEMAILER_SECURE` (optional, defaults to false)
16
+ * - `FACTEUR_NODEMAILER_USER` / `FACTEUR_NODEMAILER_PASS` (optional, both needed for auth)
17
+ */
18
+ export declare const layerConfig: Layer.Layer<Mailer, Config.ConfigError, never>;
@@ -0,0 +1,60 @@
1
+ import { Config, Effect, Layer, Option, Redacted } from "effect";
2
+ import { createTransport } from "nodemailer";
3
+ import { r as recipients, t as validated } from "../validated-hMH8K05y.mjs";
4
+ import { n as Mailer, r as MailerError } from "../Mailer-Bb2tVu99.mjs";
5
+ // src/drivers/nodemailer.ts
6
+ const PROVIDER = "nodemailer";
7
+ const toSendMailOptions = (email) => ({
8
+ from: email.from,
9
+ to: recipients(email.to),
10
+ subject: email.subject,
11
+ html: email.html,
12
+ text: email.text,
13
+ cc: recipients(email.cc),
14
+ bcc: recipients(email.bcc),
15
+ replyTo: recipients(email.replyTo)
16
+ });
17
+ /**
18
+ * Accepts any nodemailer transport config (SMTP options, a connection URL,
19
+ * `{ jsonTransport: true }`, ...). The transport is closed when the layer's
20
+ * scope ends.
21
+ */
22
+ const layer = (transport) => Layer.effect(Mailer, Effect.gen(function* () {
23
+ const transporter = yield* Effect.acquireRelease(Effect.sync(() => createTransport(transport)), (created) => Effect.sync(() => created.close()));
24
+ const send = Effect.fn("facteur/nodemailer.send")(function* (email) {
25
+ return { id: (yield* Effect.tryPromise({
26
+ try: () => transporter.sendMail(toSendMailOptions(email)),
27
+ catch: (cause) => new MailerError({
28
+ provider: PROVIDER,
29
+ message: cause instanceof Error ? cause.message : "Sending with nodemailer failed",
30
+ cause
31
+ })
32
+ })).messageId };
33
+ });
34
+ return Mailer.of({ send: validated(PROVIDER, send) });
35
+ }));
36
+ /**
37
+ * SMTP transport from the environment:
38
+ *
39
+ * - `FACTEUR_NODEMAILER_HOST` (required)
40
+ * - `FACTEUR_NODEMAILER_PORT` (optional, nodemailer defaults to 587, or 465 when secure)
41
+ * - `FACTEUR_NODEMAILER_SECURE` (optional, defaults to false)
42
+ * - `FACTEUR_NODEMAILER_USER` / `FACTEUR_NODEMAILER_PASS` (optional, both needed for auth)
43
+ */
44
+ const layerConfig = Layer.unwrap(Effect.gen(function* () {
45
+ const host = yield* Config.NonEmptyString("FACTEUR_NODEMAILER_HOST");
46
+ const port = yield* Config.option(Config.Port("FACTEUR_NODEMAILER_PORT"));
47
+ const secure = yield* Config.option(Config.Boolean("FACTEUR_NODEMAILER_SECURE"));
48
+ const user = yield* Config.option(Config.String("FACTEUR_NODEMAILER_USER"));
49
+ const pass = yield* Config.option(Config.Redacted("FACTEUR_NODEMAILER_PASS"));
50
+ return layer({
51
+ host,
52
+ port: Option.getOrUndefined(port),
53
+ secure: Option.getOrUndefined(secure),
54
+ auth: Option.isSome(user) && Option.isSome(pass) ? {
55
+ user: user.value,
56
+ pass: Redacted.value(pass.value)
57
+ } : void 0
58
+ });
59
+ }));
60
+ export { layer, layerConfig };
@@ -0,0 +1,7 @@
1
+ import { Config, Layer, Redacted } from "effect";
2
+ import { n as Mailer } from "../Mailer-DOT-aXZD.mjs";
3
+ export interface ResendOptions {
4
+ readonly apiKey: Redacted.Redacted<string>;
5
+ }
6
+ export declare const layer: (options: ResendOptions) => Layer.Layer<Mailer, never, never>;
7
+ export declare const layerConfig: Layer.Layer<Mailer, Config.ConfigError, never>;
@@ -0,0 +1,49 @@
1
+ import { Config, Effect, Layer, Redacted } from "effect";
2
+ import { Resend } from "resend";
3
+ import { r as recipients, t as validated } from "../validated-hMH8K05y.mjs";
4
+ import { n as Mailer, r as MailerError } from "../Mailer-Bb2tVu99.mjs";
5
+ // src/drivers/resend.ts
6
+ const PROVIDER = "resend";
7
+ const toCreateEmailOptions = (email) => {
8
+ const base = {
9
+ from: email.from,
10
+ to: recipients(email.to),
11
+ subject: email.subject,
12
+ cc: recipients(email.cc),
13
+ bcc: recipients(email.bcc),
14
+ replyTo: recipients(email.replyTo)
15
+ };
16
+ return email.html !== void 0 ? {
17
+ ...base,
18
+ html: email.html,
19
+ text: email.text
20
+ } : {
21
+ ...base,
22
+ text: email.text
23
+ };
24
+ };
25
+ const layer = (options) => Layer.effect(Mailer, Effect.sync(() => {
26
+ const client = new Resend(Redacted.value(options.apiKey));
27
+ const send = Effect.fn("facteur/resend.send")(function* (email) {
28
+ const { data, error } = yield* Effect.tryPromise({
29
+ try: () => client.emails.send(toCreateEmailOptions(email)),
30
+ catch: (cause) => new MailerError({
31
+ provider: PROVIDER,
32
+ message: "Request to Resend failed",
33
+ cause
34
+ })
35
+ });
36
+ if (error !== null) return yield* new MailerError({
37
+ provider: PROVIDER,
38
+ message: error.message,
39
+ cause: error
40
+ });
41
+ return { id: data.id };
42
+ });
43
+ return Mailer.of({ send: validated(PROVIDER, send) });
44
+ }));
45
+ const layerConfig = Layer.unwrap(Effect.gen(function* () {
46
+ const apiKey = yield* Config.Redacted("FACTEUR_RESEND_KEY");
47
+ return layer({ apiKey });
48
+ }));
49
+ export { layer, layerConfig };
@@ -0,0 +1,17 @@
1
+ import { SESv2ClientConfig } from "@aws-sdk/client-sesv2";
2
+ import { Config, Layer } from "effect";
3
+ import { n as Mailer } from "../Mailer-DOT-aXZD.mjs";
4
+ /**
5
+ * Accepts any SESv2 client config. Without explicit `credentials`, the AWS SDK
6
+ * default credential chain is used (env vars, shared config, IAM roles, ...).
7
+ * The client is destroyed when the layer's scope ends.
8
+ */
9
+ export declare const layer: (config?: SESv2ClientConfig) => Layer.Layer<Mailer, never, never>;
10
+ /**
11
+ * SES client from the environment:
12
+ *
13
+ * - `FACTEUR_SES_REGION` (required)
14
+ * - `FACTEUR_SES_ACCESS_KEY_ID` / `FACTEUR_SES_SECRET_ACCESS_KEY` (optional, both
15
+ * needed; otherwise the AWS SDK default credential chain is used)
16
+ */
17
+ export declare const layerConfig: Layer.Layer<Mailer, Config.ConfigError, never>;
@@ -0,0 +1,77 @@
1
+ import { SESv2Client, SendEmailCommand } from "@aws-sdk/client-sesv2";
2
+ import { Config, Effect, Layer, Option, Redacted } from "effect";
3
+ import { n as recipientList, t as validated } from "../validated-hMH8K05y.mjs";
4
+ import { n as Mailer, r as MailerError } from "../Mailer-Bb2tVu99.mjs";
5
+ // src/drivers/ses.ts
6
+ const PROVIDER = "ses";
7
+ const toSendEmailInput = (email) => {
8
+ return {
9
+ FromEmailAddress: email.from,
10
+ Destination: {
11
+ ToAddresses: recipientList(email.to),
12
+ CcAddresses: recipientList(email.cc),
13
+ BccAddresses: recipientList(email.bcc)
14
+ },
15
+ ReplyToAddresses: recipientList(email.replyTo),
16
+ Content: { Simple: {
17
+ Subject: {
18
+ Data: email.subject,
19
+ Charset: "UTF-8"
20
+ },
21
+ Body: {
22
+ Html: email.html === void 0 ? void 0 : {
23
+ Data: email.html,
24
+ Charset: "UTF-8"
25
+ },
26
+ Text: email.text === void 0 ? void 0 : {
27
+ Data: email.text,
28
+ Charset: "UTF-8"
29
+ }
30
+ }
31
+ } }
32
+ };
33
+ };
34
+ /**
35
+ * Accepts any SESv2 client config. Without explicit `credentials`, the AWS SDK
36
+ * default credential chain is used (env vars, shared config, IAM roles, ...).
37
+ * The client is destroyed when the layer's scope ends.
38
+ */
39
+ const layer = (config = {}) => Layer.effect(Mailer, Effect.gen(function* () {
40
+ const client = yield* Effect.acquireRelease(Effect.sync(() => new SESv2Client(config)), (created) => Effect.sync(() => created.destroy()));
41
+ const send = Effect.fn("facteur/ses.send")(function* (email) {
42
+ const output = yield* Effect.tryPromise({
43
+ try: (signal) => client.send(new SendEmailCommand(toSendEmailInput(email)), { abortSignal: signal }),
44
+ catch: (cause) => new MailerError({
45
+ provider: PROVIDER,
46
+ message: cause instanceof Error ? cause.message : "Request to SES failed",
47
+ cause
48
+ })
49
+ });
50
+ if (output.MessageId === void 0) return yield* new MailerError({
51
+ provider: PROVIDER,
52
+ message: "SES did not return a MessageId"
53
+ });
54
+ return { id: output.MessageId };
55
+ });
56
+ return Mailer.of({ send: validated(PROVIDER, send) });
57
+ }));
58
+ /**
59
+ * SES client from the environment:
60
+ *
61
+ * - `FACTEUR_SES_REGION` (required)
62
+ * - `FACTEUR_SES_ACCESS_KEY_ID` / `FACTEUR_SES_SECRET_ACCESS_KEY` (optional, both
63
+ * needed; otherwise the AWS SDK default credential chain is used)
64
+ */
65
+ const layerConfig = Layer.unwrap(Effect.gen(function* () {
66
+ const region = yield* Config.NonEmptyString("FACTEUR_SES_REGION");
67
+ const accessKeyId = yield* Config.option(Config.String("FACTEUR_SES_ACCESS_KEY_ID"));
68
+ const secretAccessKey = yield* Config.option(Config.Redacted("FACTEUR_SES_SECRET_ACCESS_KEY"));
69
+ return layer({
70
+ region,
71
+ credentials: Option.isSome(accessKeyId) && Option.isSome(secretAccessKey) ? {
72
+ accessKeyId: accessKeyId.value,
73
+ secretAccessKey: Redacted.value(secretAccessKey.value)
74
+ } : void 0
75
+ });
76
+ }));
77
+ export { layer, layerConfig };
@@ -0,0 +1,31 @@
1
+ import { Config, Layer } from "effect";
2
+ import { i as SentEmail, n as Mailer, r as MailerError, t as Email } from "./Mailer-DOT-aXZD.mjs";
3
+ export interface MailerClient extends AsyncDisposable {
4
+ /** Sends an email. Rejects with a `MailerError` (or a config error on first use). */
5
+ readonly sendEmail: (email: Email) => Promise<SentEmail>;
6
+ /**
7
+ * Releases the provider's resources (SMTP connections, SES client).
8
+ * `await using mailer = createMailer()` calls this automatically.
9
+ */
10
+ readonly dispose: () => Promise<void>;
11
+ }
12
+ /**
13
+ * Promise API for projects that don't use Effect.
14
+ *
15
+ * Uses the env-selected provider by default, or any Mailer layer you pass
16
+ * (e.g. `Resend.layer({ apiKey })`). The provider is built on the first
17
+ * `sendEmail` call and reused until `dispose`.
18
+ */
19
+ export declare const createMailer: (layer?: Layer.Layer<Mailer, unknown>) => MailerClient;
20
+ /**
21
+ * Builds the Mailer from the environment.
22
+ *
23
+ * - `FACTEUR_PROVIDER=RESEND` + `FACTEUR_RESEND_KEY` → Resend driver
24
+ * - `FACTEUR_PROVIDER=NODEMAILER` + `FACTEUR_NODEMAILER_HOST` → nodemailer SMTP driver
25
+ * - `FACTEUR_PROVIDER=SES` + `FACTEUR_SES_REGION` → Amazon SES (v2 API) driver
26
+ *
27
+ * Drivers are imported on demand, so only the selected one's peer dependency
28
+ * (`resend`, `nodemailer` or `@aws-sdk/client-sesv2`) needs to be installed.
29
+ */
30
+ export declare const layerConfig: Layer.Layer<Mailer, Config.ConfigError | MailerError, never>;
31
+ export { Email, Mailer, MailerError, SentEmail };
package/dist/index.mjs ADDED
@@ -0,0 +1,50 @@
1
+ import { Config, Effect, Layer, ManagedRuntime } from "effect";
2
+ import { i as SentEmail, n as Mailer, r as MailerError, t as Email } from "./Mailer-Bb2tVu99.mjs";
3
+ // src/config.ts
4
+ const loadDriver = (provider, load) => Effect.tryPromise({
5
+ try: load,
6
+ catch: (cause) => new MailerError({
7
+ provider,
8
+ message: `Could not load the ${provider} driver. Is its peer dependency installed?`,
9
+ cause
10
+ })
11
+ });
12
+ /**
13
+ * Builds the Mailer from the environment.
14
+ *
15
+ * - `FACTEUR_PROVIDER=RESEND` + `FACTEUR_RESEND_KEY` → Resend driver
16
+ * - `FACTEUR_PROVIDER=NODEMAILER` + `FACTEUR_NODEMAILER_HOST` → nodemailer SMTP driver
17
+ * - `FACTEUR_PROVIDER=SES` + `FACTEUR_SES_REGION` → Amazon SES (v2 API) driver
18
+ *
19
+ * Drivers are imported on demand, so only the selected one's peer dependency
20
+ * (`resend`, `nodemailer` or `@aws-sdk/client-sesv2`) needs to be installed.
21
+ */
22
+ const layerConfig = Layer.unwrap(Effect.gen(function* () {
23
+ switch (yield* Config.Literals([
24
+ "RESEND",
25
+ "NODEMAILER",
26
+ "SES"
27
+ ], "FACTEUR_PROVIDER")) {
28
+ case "RESEND": return (yield* loadDriver("resend", () => import("./drivers/resend.mjs"))).layerConfig;
29
+ case "NODEMAILER": return (yield* loadDriver("nodemailer", () => import("./drivers/nodemailer.mjs"))).layerConfig;
30
+ case "SES": return (yield* loadDriver("ses", () => import("./drivers/ses.mjs"))).layerConfig;
31
+ }
32
+ }));
33
+ // src/client.ts
34
+ /**
35
+ * Promise API for projects that don't use Effect.
36
+ *
37
+ * Uses the env-selected provider by default, or any Mailer layer you pass
38
+ * (e.g. `Resend.layer({ apiKey })`). The provider is built on the first
39
+ * `sendEmail` call and reused until `dispose`.
40
+ */
41
+ const createMailer = (layer = layerConfig) => {
42
+ const runtime = ManagedRuntime.make(layer);
43
+ const dispose = () => runtime.dispose();
44
+ return {
45
+ sendEmail: (email) => runtime.runPromise(Mailer.use((mailer) => mailer.send(email))),
46
+ dispose,
47
+ [Symbol.asyncDispose]: dispose
48
+ };
49
+ };
50
+ export { Email, Mailer, MailerError, SentEmail, createMailer, layerConfig };
@@ -0,0 +1,20 @@
1
+ import { r as MailerError, t as Email } from "./Mailer-Bb2tVu99.mjs";
2
+ import { Effect, Schema } from "effect";
3
+ // src/internal/recipients.ts
4
+ /** Copies readonly recipient arrays into the mutable arrays provider SDKs expect. */
5
+ const recipients = (value) => typeof value === "string" || value === void 0 ? value : [...value];
6
+ /** Normalizes recipients to an array, for SDKs that only accept lists. */
7
+ const recipientList = (value) => value === void 0 ? void 0 : typeof value === "string" ? [value] : [...value];
8
+ // src/internal/validated.ts
9
+ const decodeEmail = Schema.decodeUnknownEffect(Email);
10
+ /**
11
+ * Wraps a driver's send so every email is decoded against the `Email` schema
12
+ * before it reaches the provider. The type already rules out bad input, but
13
+ * JavaScript callers and `as` casts can still get past it.
14
+ */
15
+ const validated = (provider, send) => (email) => decodeEmail(email).pipe(Effect.mapError((cause) => new MailerError({
16
+ provider,
17
+ message: `Invalid email: ${cause.message}`,
18
+ cause
19
+ })), Effect.flatMap(send));
20
+ export { recipientList as n, recipients as r, validated as t };
package/package.json CHANGED
@@ -1,19 +1,71 @@
1
1
  {
2
2
  "name": "@matfire/facteur",
3
- "version": "0.0.0",
4
- "main": "index.js",
3
+ "version": "0.1.0",
5
4
  "description": "A configurable email provider for Effect: Resend, SES and SMTP (nodemailer) behind one Mailer service.",
6
- "publishConfig": {
7
- "access": "public"
5
+ "homepage": "https://github.com/matfire/facteur#readme",
6
+ "bugs": {
7
+ "url": "https://github.com/matfire/facteur/issues"
8
8
  },
9
- "author": "Matteo Gassend <matteo@matteogassend.com>",
10
9
  "license": "MIT",
11
- "homepage": "https://github.com/matfire/facteur#readme",
10
+ "author": "Matteo Gassend <matteo@matteogassend.com>",
12
11
  "repository": {
13
12
  "type": "git",
14
13
  "url": "git+https://github.com/matfire/facteur.git"
15
14
  },
16
- "bugs": {
17
- "url": "https://github.com/matfire/facteur/issues"
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "type": "module",
19
+ "exports": {
20
+ ".": "./dist/index.mjs",
21
+ "./drivers/nodemailer": "./dist/drivers/nodemailer.mjs",
22
+ "./drivers/resend": "./dist/drivers/resend.mjs",
23
+ "./drivers/ses": "./dist/drivers/ses.mjs",
24
+ "./package.json": "./package.json"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public",
28
+ "provenance": true
29
+ },
30
+ "scripts": {
31
+ "build": "tsdown",
32
+ "dev": "tsdown --watch",
33
+ "test": "vitest",
34
+ "typecheck": "tsc --noEmit",
35
+ "prepublishOnly": "npm run build",
36
+ "lint": "oxlint --deny-warnings",
37
+ "lint:fix": "oxlint --fix",
38
+ "format": "oxfmt",
39
+ "format:check": "oxfmt --check"
40
+ },
41
+ "dependencies": {
42
+ "effect": "^4.1.5"
43
+ },
44
+ "devDependencies": {
45
+ "@aws-sdk/client-sesv2": "^3.1175.0",
46
+ "@types/node": "^26.6.5",
47
+ "nodemailer": "^10.6.1",
48
+ "oxfmt": "^0.79.0",
49
+ "oxlint": "^1.94.0",
50
+ "resend": "^6.39.0",
51
+ "tsdown": "^0.23.1",
52
+ "typescript": "7.0.2",
53
+ "vitest": "^5.0.5"
54
+ },
55
+ "peerDependencies": {
56
+ "@aws-sdk/client-sesv2": "^3.1175.0",
57
+ "nodemailer": "^10.6.1",
58
+ "resend": "^6.39.0"
59
+ },
60
+ "peerDependenciesMeta": {
61
+ "@aws-sdk/client-sesv2": {
62
+ "optional": true
63
+ },
64
+ "nodemailer": {
65
+ "optional": true
66
+ },
67
+ "resend": {
68
+ "optional": true
69
+ }
18
70
  }
19
71
  }
package/index.js DELETED
@@ -1 +0,0 @@
1
- module.exports = {};