@yaks/cloudflare-mail 0.0.0-stage → 0.2.36

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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Jeff Peterson
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # @yaks/cloudflare-mail
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Cloudflare's mail provider at the portable `@yaks/host` boundary. `cloudflare`
4
+ sends through the account's REST API; `bound` adapts the Workers Email Sending
5
+ binding. `received` decodes an Email Routing delivery's streamed MIME into a
6
+ neutral `Incoming`, preserving headers and attachment bytes, with Email
7
+ Routing's own DKIM verdict as `verified` and its DMARC pass aligned with the
8
+ From as `vouched` (`vouched(header, from)`), read from the first
9
+ Authentication-Results, never one the sender supplied. No graph, server,
10
+ credential lookup or fixed sending domain lives here.
11
+
12
+ `cloudflare({account, token, base?, fetch?})` implements `Sender`. `deliver`
13
+ accepts the provider's payload directly, and `payload` composes one from a
14
+ portable message. Only an HTTP 429 or a connection known never to have reached
15
+ the API permits another send. `bound` makes the same distinction for the
16
+ binding's rate-limit error. Both senders return RFC Message-IDs for threading.
17
+
18
+ Listed in a config, the package lends its host the sender named `cloudflare`
19
+ (`./graph`), which `@yaks/mail` selects with `sender: {"via": "cloudflare"}`.
20
+ Its options are `account` and `token`, and `base` and `fetch`; the sender reads
21
+ them at every letter, and until both are set a letter waits. A Worker lends it
22
+ what its runtime holds: options naming an Email Sending `binding` lend a second
23
+ sender, `binding`, that sends through it (a letter bounces where the deploy
24
+ holds none), and the arrival named `cloudflare` reads a letter Email Routing
25
+ handed the Worker's `email()` as an `Incoming`.
26
+
27
+ ```json
28
+ {
29
+ "use": "@yaks/cloudflare-mail",
30
+ "with": {
31
+ "account": { "secret": "CF_ACCOUNT_ID" },
32
+ "token": { "secret": "CF_EMAIL_TOKEN" }
33
+ }
34
+ }
35
+ ```
36
+
37
+ ```ts
38
+ import { payload } from '@yaks/cloudflare-mail'
39
+ import { equal } from '@yaks/testing'
40
+ equal(
41
+ payload({
42
+ from: 'hello@books.example',
43
+ to: ['a@example.com', 'b@example.com'],
44
+ subject: 'Thursday',
45
+ text: 'At seven.',
46
+ html: '<p>At seven.</p>',
47
+ }).to,
48
+ ['a@example.com', 'b@example.com'],
49
+ )
50
+ ```
@@ -0,0 +1,22 @@
1
+ import type { Sender } from "@yaks/host/senders";
2
+ /** A sender or recipient, named or bare — the runtime's `EmailAddress`. */ export type Address = string | {
3
+ name: string;
4
+ email: string;
5
+ };
6
+ /** The builder overload of SendEmail.send: the runtime binding satisfies
7
+ * this portable shape (conform.ts). Authorization belongs to the deploy. */ export type Binding = {
8
+ send(letter: {
9
+ from: Address;
10
+ to: string | string[];
11
+ cc?: string;
12
+ replyTo?: string;
13
+ subject: string;
14
+ text?: string;
15
+ html?: string;
16
+ headers?: Record<string, string>;
17
+ }): Promise<{
18
+ messageId?: string;
19
+ }>;
20
+ };
21
+ /** A Cloudflare Workers Email Sending binding as a portable sender. */ export declare let bound: (mail?: Binding) => Sender;
22
+ //# sourceMappingURL=binding.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binding.d.ts","sources":["../binding.ts"],"names":[],"mappings":"AAEA,cAAc,MAAM,kCAAuC;AAG3D,yEAAyE,GACzE,YAAY,UAAU,MAAM;EAAK,MAAM,MAAM;EAAE,OAAO,MAAM;;AAE5D;0EAC0E,GAC1E,YAAY;EACV,KAAK;IACH,MAAM;IACN,IAAI,MAAM,GAAG,MAAM;IACnB,KAAK,MAAM;IACX,UAAU,MAAM;IAChB,SAAS,MAAM;IACf,OAAO,MAAM;IACb,OAAO,MAAM;IACb,UAAU,OAAO,MAAM,EAAE,MAAM;MAC7B;IAAU,YAAY,MAAM;;;AAOlC,qEAAqE,GACrE,OAAO,YAAI,QAAS,OAAO,YAAU,OA2BnC"}
@@ -0,0 +1,10 @@
1
+ import { type Arrival, type Sender } from "@yaks/host/senders";
2
+ import { type Binding } from "./binding.js";
3
+ import { type Account } from "./sender.js";
4
+ /** What a config passes to @yaks/cloudflare-mail. */ export type Options = Partial<Account> & {
5
+ /** the Workers Email Sending binding the host lends */ binding?: Binding;
6
+ };
7
+ /** The `cloudflare` sender, built from these options at every letter, and
8
+ * the `binding` sender where the options name a binding. */ export declare let senders: (_host: unknown, options?: Options) => Record<string, Sender>;
9
+ /** The `cloudflare` arrival: Email Routing's delivery, its MIME decoded. */ export declare let arrivals: () => Record<string, Arrival>;
10
+ //# sourceMappingURL=graph.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.d.ts","sources":["../graph.ts"],"names":[],"mappings":"AAoBA,SAAiB,KAAK,OAAO,EAAE,KAAK,MAAM,kCAAuC;AACjF,SAAS,KAAK,OAAO,uBAA6B;AAElD,SAAS,KAAK,OAAO,sBAAiC;AAEtD,mDAAmD,GACnD,YAAY,UAAU,QAAQ;EAC5B,qDAAqD,GACrD,UAAU;;AAGZ;0DAC0D,GAC1D,OAAO,YAAI,UACT,OAAO,OAAO,EACd,UAAS,YACR,OAAO,MAAM,EAAE,QAKhB;AAEF,0EAA0E,GAC1E,OAAO,YAAI,gBAAe,OAAO,MAAM,EAAE,SAGvC"}
package/_dist/mod.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./sender.js";
2
+ export * from "./binding.js";
3
+ export * from "./receive.js";
4
+ //# sourceMappingURL=mod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","sources":["../mod.ts"],"names":[],"mappings":"AACA,4BAA2B;AAC3B,6BAA4B;AAC5B,6BAA4B"}
@@ -0,0 +1,13 @@
1
+ import type { Incoming } from "@yaks/host/senders";
2
+ export type Inbound = {
3
+ from: string;
4
+ to: string;
5
+ headers: {
6
+ get(name: string): string | null;
7
+ entries?(): IterableIterator<[string, string]>;
8
+ };
9
+ raw: ReadableStream<Uint8Array>;
10
+ };
11
+ /** Whether Email Routing's DMARC verdict passed for the domain of `from`. */ export declare let vouched: (header: string | null, from: string) => boolean;
12
+ /** Decode one Email Worker delivery without writing or interpreting it. */ export declare let received: (message: Inbound) => Promise<Incoming>;
13
+ //# sourceMappingURL=receive.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"receive.d.ts","sources":["../receive.ts"],"names":[],"mappings":"AAEA,cAAc,QAAQ,kCAAuC;AAE7D,YAAY;EACV,MAAM,MAAM;EACZ,IAAI,MAAM;EACV;IACE,IAAI,MAAM,MAAM,GAAG,MAAM,GAAG,IAAI;IAChC,YAAY,kBAAkB,MAAM,EAAE,MAAM;;EAE9C,KAAK,eAAe;;AActB,2EAA2E,GAC3E,OAAO,YAAI,UAAW,QAAQ,MAAM,GAAG,IAAI,EAAE,MAAM,MAAM,KAAG,OAAO,CAMlE;AAED,yEAAyE,GACzE,OAAO,YAAI,WAAkB,SAAS,YAAU,QAAQ,UA0CvD"}
@@ -0,0 +1,50 @@
1
+ import type { Message, Receipt, Sender } from "@yaks/host/senders";
2
+ /** The Email Sending payload, as the API takes it. */ export type Payload = {
3
+ /** the sender, with a display name taken from the local part */ from: {
4
+ address: string;
5
+ name: string;
6
+ };
7
+ /** the recipients */ to: string[];
8
+ /** the addresses copied */ cc?: string[];
9
+ /** where a reply should go — the sender, unless you say otherwise */ reply_to: string;
10
+ /** the subject line */ subject: string;
11
+ /** the body as plain text */ text: string;
12
+ /** the body as HTML */ html: string;
13
+ /** the threading headers, present only on a reply */ headers?: Record<string, string>;
14
+ };
15
+ /**
16
+ * A message → the Email Sending payload. Pure, so a test asserts on it without
17
+ * a network anywhere.
18
+ */ export declare let payload: (m: Message) => Payload;
19
+ /** The part of `fetch` this file uses — satisfied by the web `fetch` and by a
20
+ * Worker's. */ export type Fetch = (url: string, init: RequestInit) => Promise<Response>;
21
+ /** What the sender needs to reach the account. */ export type Account = {
22
+ /** the Cloudflare account id */ account: string;
23
+ /** an API token that may send mail — never held by this package */ token: string;
24
+ /** the API root, to point a test at a stub (default: the API itself) */ base?: string;
25
+ /** the fetch to call through (default: the global one) */ fetch?: Fetch;
26
+ };
27
+ /**
28
+ * One Email Sending request: the API's one client here, for a caller that
29
+ * builds its own {@link Payload} (several recipients, a display name, a
30
+ * Reply-To of its own). It answers the receipt.
31
+ *
32
+ * A failure rejects with the status and the start of the response body, which
33
+ * is what gets written to the letter as `bounced.reason` — so a bounce records
34
+ * what the API reported, not just "send failed". A letter that never reached
35
+ * the API, or that it declined with a 429, rejects as `Unsent` instead.
36
+ */ export declare let deliver: ({}: Account) => (body: Payload) => Promise<Receipt>;
37
+ /**
38
+ * A {@link Sender} over Cloudflare Email Sending: {@link deliver} of the
39
+ * message's {@link payload}.
40
+ *
41
+ * ```ts
42
+ * import { cloudflare } from '@yaks/cloudflare-mail'
43
+ * // in a Worker: cloudflare({ account: env.CF_ACCOUNT, token: env.CF_EMAIL_TOKEN })
44
+ * ```
45
+ */ export declare let cloudflare: (account: Account) => Sender;
46
+ /** Build from host configuration, leaving missing credentials waiting. */ export declare let configured: (options: Partial<Account>) => {
47
+ sender?: Sender;
48
+ waiting?: string;
49
+ };
50
+ //# sourceMappingURL=sender.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sender.d.ts","sources":["../sender.ts"],"names":[],"mappings":"AAsBA,cAAc,OAAO,EAAE,OAAO,EAAE,MAAM,kCAAuC;AAE7E,oDAAoD,GACpD,YAAY;EACV,8DAA8D,GAC9D;IAAQ,SAAS,MAAM;IAAE,MAAM,MAAM;;EACrC,mBAAmB,GACnB,IAAI,MAAM;EACV,yBAAyB,GACzB,KAAK,MAAM;EACX,mEAAmE,GACnE,UAAU,MAAM;EAChB,qBAAqB,GACrB,SAAS,MAAM;EACf,2BAA2B,GAC3B,MAAM,MAAM;EACZ,qBAAqB,GACrB,MAAM,MAAM;EACZ,mDAAmD,GACnD,UAAU,OAAO,MAAM,EAAE,MAAM;;AAGjC;;;CAGC,GACD,OAAO,YAAI,UAAW,GAAG,YAAU,QAkBjC;AAEF;aACa,GACb,YAAY,SAAS,KAAK,MAAM,EAAE,MAAM,gBAAgB,QAAQ;AAEhE,gDAAgD,GAChD,YAAY;EACV,8BAA8B,GAC9B,SAAS,MAAM;EACf,iEAAiE,GACjE,OAAO,MAAM;EACb,sEAAsE,GACtE,OAAO,MAAM;EACb,wDAAwD,GACxD,QAAQ;;AAyBV;;;;;;;;;CASC,GACD,OAAO,YAAI,UACT,IAAuC,OAAO,MAC5C,MAAM,YAAY,QAAQ,SA4B7B;AAED;;;;;;;;CAQC,GACD,OAAO,YAAI,aAAc,SAAS,YAAU,OAG3C;AAED,wEAAwE,GACxE,OAAO,YAAI,aACT,SAAS,QAAQ;EACd,SAAS;EAAQ,UAAU,MAAM;EAYjC"}
package/binding.js ADDED
@@ -0,0 +1,39 @@
1
+ // Cloudflare's Workers binding at the portable Sender boundary. The binding
2
+ // owns authorization; a rate-limit refusal knows no message was accepted.
3
+ import { Unsent } from "@yaks/host/senders";
4
+ // Email Sending's Workers API names a refusal by its `code`.
5
+ let limited = (err)=>err?.code == 'E_RATE_LIMIT_EXCEEDED';
6
+ /** A Cloudflare Workers Email Sending binding as a portable sender. */ export let bound = (mail)=>({
7
+ send: async (m)=>{
8
+ if (!mail) throw new Error('this deploy has no mail binding');
9
+ let sent = await mail.send({
10
+ from: m.name ? {
11
+ name: m.name,
12
+ email: m.from
13
+ } : m.from,
14
+ to: m.to,
15
+ ...m.cc ? {
16
+ cc: m.cc
17
+ } : {},
18
+ ...m.replyAddress ? {
19
+ replyTo: m.replyAddress
20
+ } : {},
21
+ subject: m.subject,
22
+ text: m.text,
23
+ html: m.html,
24
+ ...m.replyTo ? {
25
+ headers: {
26
+ 'In-Reply-To': `<${m.replyTo}>`,
27
+ References: `<${m.replyTo}>`
28
+ }
29
+ } : {}
30
+ }).catch((err)=>{
31
+ throw limited(err) ? new Unsent(`not sent: ${err.message}`) : err;
32
+ });
33
+ let id = String(sent?.messageId ?? '').replace(/[<>]/g, '');
34
+ return id ? {
35
+ id
36
+ } : {};
37
+ }
38
+ });
39
+ //# sourceMappingURL=binding.js.map
package/binding.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binding.js","sources":["./binding.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,0EAA0E;AAE1E,SAAS,MAAM,kCAAuC;AAoBtD,6DAA6D;AAC7D,IAAI,UAAU,CAAC,MACb,AAAC,KAA2B,QAAQ;AAEtC,qEAAqE,GACrE,OAAO,IAAI,QAAQ,CAAC,OAA2B,CAAC;IAC9C,MAAM,OAAO;MACX,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM;MAC3B,IAAI,OAAO,MAAM,KAAK,IAAI,CAAC;QACzB,MAAM,EAAE,IAAI,GAAG;UAAE,MAAM,EAAE,IAAI;UAAE,OAAO,EAAE,IAAI;QAAC,IAAI,EAAE,IAAI;QACvD,IAAI,EAAE,EAAE;QACR,GAAI,EAAE,EAAE,GAAG;UAAE,IAAI,EAAE,EAAE;QAAC,IAAI,CAAC,CAAC;QAC5B,GAAI,EAAE,YAAY,GAAG;UAAE,SAAS,EAAE,YAAY;QAAC,IAAI,CAAC,CAAC;QACrD,SAAS,EAAE,OAAO;QAClB,MAAM,EAAE,IAAI;QACZ,MAAM,EAAE,IAAI;QACZ,GAAI,EAAE,OAAO,GACT;UACA,SAAS;YACP,eAAe,CAAC,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC;YAC/B,YAAY,CAAC,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC;UAC9B;QACF,IACE,CAAC,CAAC;MACR,GAAG,KAAK,CAAC,CAAC;QACR,MAAM,QAAQ,OACV,IAAI,OAAO,CAAC,UAAU,EAAE,AAAC,IAAc,OAAO,EAAE,IAChD;MACN;MACA,IAAI,KAAK,OAAO,MAAM,aAAa,IAAI,OAAO,CAAC,SAAS;MACxD,OAAO,KAAK;QAAE;MAAG,IAAI,CAAC;IACxB;EACF,CAAC,EAAC"}
package/binding.ts ADDED
@@ -0,0 +1,56 @@
1
+ // Cloudflare's Workers binding at the portable Sender boundary. The binding
2
+ // owns authorization; a rate-limit refusal knows no message was accepted.
3
+ import type { Sender } from '@yaks/host/senders'
4
+ import { Unsent } from '@yaks/host/senders'
5
+
6
+ /** A sender or recipient, named or bare — the runtime's `EmailAddress`. */
7
+ export type Address = string | { name: string; email: string }
8
+
9
+ /** The builder overload of SendEmail.send: the runtime binding satisfies
10
+ * this portable shape (conform.ts). Authorization belongs to the deploy. */
11
+ export type Binding = {
12
+ send(letter: {
13
+ from: Address
14
+ to: string | string[]
15
+ cc?: string
16
+ replyTo?: string
17
+ subject: string
18
+ text?: string
19
+ html?: string
20
+ headers?: Record<string, string>
21
+ }): Promise<{ messageId?: string }>
22
+ }
23
+
24
+ // Email Sending's Workers API names a refusal by its `code`.
25
+ let limited = (err: unknown) =>
26
+ (err as { code?: string })?.code == 'E_RATE_LIMIT_EXCEEDED'
27
+
28
+ /** A Cloudflare Workers Email Sending binding as a portable sender. */
29
+ export let bound = (mail?: Binding): Sender => ({
30
+ send: async (m) => {
31
+ if (!mail) throw new Error('this deploy has no mail binding')
32
+ let sent = await mail.send({
33
+ from: m.name ? { name: m.name, email: m.from } : m.from,
34
+ to: m.to,
35
+ ...(m.cc ? { cc: m.cc } : {}),
36
+ ...(m.replyAddress ? { replyTo: m.replyAddress } : {}),
37
+ subject: m.subject,
38
+ text: m.text,
39
+ html: m.html,
40
+ ...(m.replyTo
41
+ ? {
42
+ headers: {
43
+ 'In-Reply-To': `<${m.replyTo}>`,
44
+ References: `<${m.replyTo}>`,
45
+ },
46
+ }
47
+ : {}),
48
+ }).catch((err) => {
49
+ throw limited(err)
50
+ ? new Unsent(`not sent: ${(err as Error).message}`)
51
+ : err
52
+ })
53
+ let id = String(sent?.messageId ?? '').replace(/[<>]/g, '')
54
+ return id ? { id } : {}
55
+ },
56
+ })
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts","./testing.ts","./conform.ts","./workers.json"]},"name":"@yaks/cloudflare-mail","version":"0.2.36","license":"Apache-2.0","description":"Cloudflare Email Sending and Email Routing at the portable mail boundary.","exports":{".":"./mod.ts","./sender":"./sender.ts","./receive":"./receive.ts","./binding":"./binding.ts","./graph":"./graph.ts"},"imports":{"@yaks/cloudflare-mail":"./mod.ts","@yaks/cloudflare-mail/sender":"./sender.ts","@yaks/cloudflare-mail/receive":"./receive.ts","@yaks/cloudflare-mail/binding":"./binding.ts","@yaks/cloudflare-mail/graph":"./graph.ts"}}
package/graph.js ADDED
@@ -0,0 +1,36 @@
1
+ // The `@yaks/cloudflare-mail/graph` facet: what this plugin lends its host.
2
+ // The sender named `cloudflare`, which @yaks/mail selects with
3
+ // `sender: {"via": "cloudflare"}`, sends through the account's REST API. A
4
+ // config passes it the account and a token that may send mail:
5
+ //
6
+ // ```json
7
+ // { "use": "@yaks/cloudflare-mail",
8
+ // "with": { "account": { "secret": "CF_ACCOUNT_ID" },
9
+ // "token": { "secret": "CF_EMAIL_TOKEN" } } }
10
+ // ```
11
+ //
12
+ // The sender reads its options at every letter, so a secret set after
13
+ // start-up is used for the next one.
14
+ //
15
+ // A Worker lends the plugin what its runtime holds. Options that name an Email
16
+ // Sending `binding` lend a second sender, named `binding`, that sends through
17
+ // it, read at each letter; where the deploy holds none, a letter bounces
18
+ // saying so.
19
+ // And the arrival named `cloudflare` reads a letter Email Routing hands the
20
+ // Worker's `email()` as a neutral `Incoming`.
21
+ import { afresh } from "@yaks/host/senders";
22
+ import { bound } from "./binding.js";
23
+ import { configured } from "./sender.js";
24
+ /** The `cloudflare` sender, built from these options at every letter, and
25
+ * the `binding` sender where the options name a binding. */ export let senders = (_host, options = {})=>({
26
+ cloudflare: afresh(()=>configured(options)),
27
+ ...Object.hasOwn(options, 'binding') ? {
28
+ binding: {
29
+ send: (m)=>bound(options.binding).send(m)
30
+ }
31
+ } : {}
32
+ });
33
+ /** The `cloudflare` arrival: Email Routing's delivery, its MIME decoded. */ export let arrivals = ()=>({
34
+ cloudflare: async (message)=>(await import("./receive.js")).received(message)
35
+ });
36
+ //# sourceMappingURL=graph.js.map
package/graph.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.js","sources":["./graph.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,+DAA+D;AAC/D,2EAA2E;AAC3E,+DAA+D;AAC/D,EAAE;AACF,UAAU;AACV,oCAAoC;AACpC,wDAAwD;AACxD,0DAA0D;AAC1D,MAAM;AACN,EAAE;AACF,sEAAsE;AACtE,qCAAqC;AACrC,EAAE;AACF,+EAA+E;AAC/E,8EAA8E;AAC9E,yEAAyE;AACzE,aAAa;AACb,4EAA4E;AAC5E,8CAA8C;AAC9C,SAAS,MAAM,kCAAkE;AACjF,SAAuB,KAAK,uBAAsB;AAElD,SAAuB,UAAU,sBAAqB;AAQtD;0DAC0D,GAC1D,OAAO,IAAI,UAAU,CACnB,OACA,UAAmB,CAAC,CAAC,GACM,CAAC;IAC5B,YAAY,OAAO,IAAM,WAAW;IACpC,GAAG,OAAO,MAAM,CAAC,SAAS,aACtB;MAAE,SAAS;QAAE,MAAM,CAAC,IAAM,MAAM,QAAQ,OAAO,EAAE,IAAI,CAAC;MAAG;IAAE,IAC3D,CAAC,CAAC;EACR,CAAC,EAAC;AAEF,0EAA0E,GAC1E,OAAO,IAAI,WAAW,IAA+B,CAAC;IACpD,YAAY,OAAO,UACjB,CAAC,MAAM,MAAM,CAAC,eAAe,EAAE,QAAQ,CAAC;EAC5C,CAAC,EAAC"}
package/graph.ts ADDED
@@ -0,0 +1,48 @@
1
+ // The `@yaks/cloudflare-mail/graph` facet: what this plugin lends its host.
2
+ // The sender named `cloudflare`, which @yaks/mail selects with
3
+ // `sender: {"via": "cloudflare"}`, sends through the account's REST API. A
4
+ // config passes it the account and a token that may send mail:
5
+ //
6
+ // ```json
7
+ // { "use": "@yaks/cloudflare-mail",
8
+ // "with": { "account": { "secret": "CF_ACCOUNT_ID" },
9
+ // "token": { "secret": "CF_EMAIL_TOKEN" } } }
10
+ // ```
11
+ //
12
+ // The sender reads its options at every letter, so a secret set after
13
+ // start-up is used for the next one.
14
+ //
15
+ // A Worker lends the plugin what its runtime holds. Options that name an Email
16
+ // Sending `binding` lend a second sender, named `binding`, that sends through
17
+ // it, read at each letter; where the deploy holds none, a letter bounces
18
+ // saying so.
19
+ // And the arrival named `cloudflare` reads a letter Email Routing hands the
20
+ // Worker's `email()` as a neutral `Incoming`.
21
+ import { afresh, type Arrival, type Sender } from '@yaks/host/senders'
22
+ import { type Binding, bound } from './binding.js'
23
+ import type { Inbound } from './receive.js'
24
+ import { type Account, configured } from './sender.js'
25
+
26
+ /** What a config passes to @yaks/cloudflare-mail. */
27
+ export type Options = Partial<Account> & {
28
+ /** the Workers Email Sending binding the host lends */
29
+ binding?: Binding
30
+ }
31
+
32
+ /** The `cloudflare` sender, built from these options at every letter, and
33
+ * the `binding` sender where the options name a binding. */
34
+ export let senders = (
35
+ _host: unknown,
36
+ options: Options = {},
37
+ ): Record<string, Sender> => ({
38
+ cloudflare: afresh(() => configured(options)),
39
+ ...Object.hasOwn(options, 'binding')
40
+ ? { binding: { send: (m) => bound(options.binding).send(m) } }
41
+ : {},
42
+ })
43
+
44
+ /** The `cloudflare` arrival: Email Routing's delivery, its MIME decoded. */
45
+ export let arrivals = (): Record<string, Arrival> => ({
46
+ cloudflare: async (message) =>
47
+ (await import('./receive.js')).received(message as Inbound),
48
+ })
package/mod.js ADDED
@@ -0,0 +1,5 @@
1
+ // Cloudflare's mail provider, independent of a graph or its host.
2
+ export * from "./sender.js";
3
+ export * from "./binding.js";
4
+ export * from "./receive.js";
5
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,4BAA2B;AAC3B,6BAA4B;AAC5B,6BAA4B"}
package/mod.ts ADDED
@@ -0,0 +1,4 @@
1
+ // Cloudflare's mail provider, independent of a graph or its host.
2
+ export * from './sender.js'
3
+ export * from './binding.js'
4
+ export * from './receive.js'
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@yaks/cloudflare-mail",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/cloudflare-mail",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ },
11
+ "./sender": {
12
+ "types": "./_dist/sender.d.ts",
13
+ "default": "./sender.js"
14
+ },
15
+ "./receive": {
16
+ "types": "./_dist/receive.d.ts",
17
+ "default": "./receive.js"
18
+ },
19
+ "./binding": {
20
+ "types": "./_dist/binding.d.ts",
21
+ "default": "./binding.js"
22
+ },
23
+ "./graph": {
24
+ "types": "./_dist/graph.d.ts",
25
+ "default": "./graph.js"
26
+ }
27
+ },
28
+ "license": "Apache-2.0",
29
+ "dependencies": {
30
+ "@yaks/host": "0.2.36",
31
+ "postal-mime": "3.0.0"
32
+ },
33
+ "description": "Cloudflare Email Sending and Email Routing at the portable mail boundary.",
34
+ "repository": "https://github.com/yak-sh/yak.git"
35
+ }
package/receive.js ADDED
@@ -0,0 +1,67 @@
1
+ // Email Routing's streamed MIME at the portable incoming mail boundary.
2
+ import PostalMime from "postal-mime";
3
+ // The receiving MTA's word on a letter, from the Authentication-Results it
4
+ // wrote first, above any the sender supplied. DKIM is `verified`; `vouched`
5
+ // is DMARC passing for the From domain, and only Email Routing's own verdict
6
+ // counts for that: a signature on somebody else's domain does not vouch for
7
+ // the From.
8
+ // https://developers.cloudflare.com/email-service/api/route-emails/email-handler/
9
+ let first = (header)=>{
10
+ let said = (header ?? '').split(/,(?=\s*[^;,]+;)/)[0];
11
+ return /^\s*mx\.cloudflare\.net\s*;/i.test(said) ? said : '';
12
+ };
13
+ /** Whether Email Routing's DMARC verdict passed for the domain of `from`. */ export let vouched = (header, from)=>{
14
+ let said = first(header);
15
+ let domain = from.toLowerCase().split('@')[1];
16
+ let dmarc = said.split(';').find((s)=>/^\s*dmarc=pass\b/i.test(s));
17
+ let aligned = dmarc?.match(/\bheader\.from\s*=\s*"?([^\s;"()]+)/i)?.[1];
18
+ return !!domain && !!dmarc && aligned?.toLowerCase() == domain;
19
+ };
20
+ /** Decode one Email Worker delivery without writing or interpreting it. */ export let received = async (message)=>{
21
+ let raw = new Uint8Array(await new Response(message.raw).arrayBuffer());
22
+ let mail = await PostalMime.parse(raw);
23
+ let decoded = {
24
+ from: mail.from?.address,
25
+ subject: mail.subject,
26
+ 'message-id': mail.messageId
27
+ };
28
+ let checked = message.headers.get('authentication-results');
29
+ return {
30
+ sources: [
31
+ {
32
+ name: 'message.eml',
33
+ type: 'message/rfc822',
34
+ bytes: raw
35
+ },
36
+ {
37
+ name: 'envelope.json',
38
+ type: 'application/json',
39
+ bytes: new TextEncoder().encode(JSON.stringify({
40
+ from: message.from,
41
+ to: message.to,
42
+ headers: [
43
+ ...message.headers.entries?.() ?? []
44
+ ]
45
+ }))
46
+ }
47
+ ],
48
+ name: mail.from?.name,
49
+ from: message.from,
50
+ to: message.to,
51
+ headers: {
52
+ get: (name)=>decoded[name.toLowerCase()] ?? message.headers.get(name)
53
+ },
54
+ text: mail.text ?? '',
55
+ html: mail.html,
56
+ ...checked == null ? {} : {
57
+ verified: /(?:^|;)\s*dkim\s*=\s*pass\b/i.test(first(checked))
58
+ },
59
+ vouched: vouched(checked, mail.from?.address || message.from),
60
+ attachments: mail.attachments.map((a)=>({
61
+ name: a.filename ?? '',
62
+ type: a.mimeType || 'application/octet-stream',
63
+ bytes: typeof a.content == 'string' ? new TextEncoder().encode(a.content) : new Uint8Array(a.content)
64
+ }))
65
+ };
66
+ };
67
+ //# sourceMappingURL=receive.js.map
package/receive.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"receive.js","sources":["./receive.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,OAAO,8BAAuC;AAa9C,2EAA2E;AAC3E,4EAA4E;AAC5E,6EAA6E;AAC7E,4EAA4E;AAC5E,YAAY;AACZ,kFAAkF;AAClF,IAAI,QAAQ,CAAC;EACX,IAAI,OAAO,CAAC,UAAU,EAAE,EAAE,KAAK,CAAC,kBAAkB,CAAC,EAAE;EACrD,OAAO,+BAA+B,IAAI,CAAC,QAAQ,OAAO;AAC5D;AAEA,2EAA2E,GAC3E,OAAO,IAAI,UAAU,CAAC,QAAuB;EAC3C,IAAI,OAAO,MAAM;EACjB,IAAI,SAAS,KAAK,WAAW,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE;EAC7C,IAAI,QAAQ,KAAK,KAAK,CAAC,KAAK,IAAI,CAAC,CAAC,IAAM,oBAAoB,IAAI,CAAC;EACjE,IAAI,UAAU,OAAO,MAAM,yCAAyC,CAAC,EAAE;EACvE,OAAO,CAAC,CAAC,UAAU,CAAC,CAAC,SAAS,SAAS,iBAAiB;AAC1D,EAAC;AAED,yEAAyE,GACzE,OAAO,IAAI,WAAW,OAAO;EAC3B,IAAI,MAAM,IAAI,WAAW,MAAM,IAAI,SAAS,QAAQ,GAAG,EAAE,WAAW;EACpE,IAAI,OAAO,MAAM,WAAW,KAAK,CAAC;EAClC,IAAI,UAA8C;IAChD,MAAM,KAAK,IAAI,EAAE;IACjB,SAAS,KAAK,OAAO;IACrB,cAAc,KAAK,SAAS;EAC9B;EACA,IAAI,UAAU,QAAQ,OAAO,CAAC,GAAG,CAAC;EAClC,OAAO;IACL,SAAS;MACP;QAAE,MAAM;QAAe,MAAM;QAAkB,OAAO;MAAI;MAC1D;QACE,MAAM;QACN,MAAM;QACN,OAAO,IAAI,cAAc,MAAM,CAAC,KAAK,SAAS,CAAC;UAC7C,MAAM,QAAQ,IAAI;UAClB,IAAI,QAAQ,EAAE;UACd,SAAS;eAAI,QAAQ,OAAO,CAAC,OAAO,QAAQ,EAAE;WAAC;QACjD;MACF;KACD;IACD,MAAM,KAAK,IAAI,EAAE;IACjB,MAAM,QAAQ,IAAI;IAClB,IAAI,QAAQ,EAAE;IACd,SAAS;MACP,KAAK,CAAC,OAAS,OAAO,CAAC,KAAK,WAAW,GAAG,IAAI,QAAQ,OAAO,CAAC,GAAG,CAAC;IACpE;IACA,MAAM,KAAK,IAAI,IAAI;IACnB,MAAM,KAAK,IAAI;IACf,GAAG,WAAW,OACV,CAAC,IACD;MAAE,UAAU,+BAA+B,IAAI,CAAC,MAAM;IAAU,CAAC;IACrE,SAAS,QAAQ,SAAS,KAAK,IAAI,EAAE,WAAW,QAAQ,IAAI;IAC5D,aAAa,KAAK,WAAW,CAAC,GAAG,CAAC,CAAC,IAAM,CAAC;QACxC,MAAM,EAAE,QAAQ,IAAI;QACpB,MAAM,EAAE,QAAQ,IAAI;QACpB,OAAO,OAAO,EAAE,OAAO,IAAI,WACvB,IAAI,cAAc,MAAM,CAAC,EAAE,OAAO,IAClC,IAAI,WAAW,EAAE,OAAO;MAC9B,CAAC;EACH;AACF,EAAC"}
package/receive.ts ADDED
@@ -0,0 +1,78 @@
1
+ // Email Routing's streamed MIME at the portable incoming mail boundary.
2
+ import PostalMime from 'postal-mime'
3
+ import type { Incoming } from 'jsr:@yaks/host@0.2.36/senders'
4
+
5
+ export type Inbound = {
6
+ from: string
7
+ to: string
8
+ headers: {
9
+ get(name: string): string | null
10
+ entries?(): IterableIterator<[string, string]>
11
+ }
12
+ raw: ReadableStream<Uint8Array>
13
+ }
14
+
15
+ // The receiving MTA's word on a letter, from the Authentication-Results it
16
+ // wrote first, above any the sender supplied. DKIM is `verified`; `vouched`
17
+ // is DMARC passing for the From domain, and only Email Routing's own verdict
18
+ // counts for that: a signature on somebody else's domain does not vouch for
19
+ // the From.
20
+ // https://developers.cloudflare.com/email-service/api/route-emails/email-handler/
21
+ let first = (header: string | null) => {
22
+ let said = (header ?? '').split(/,(?=\s*[^;,]+;)/)[0]
23
+ return /^\s*mx\.cloudflare\.net\s*;/i.test(said) ? said : ''
24
+ }
25
+
26
+ /** Whether Email Routing's DMARC verdict passed for the domain of `from`. */
27
+ export let vouched = (header: string | null, from: string): boolean => {
28
+ let said = first(header)
29
+ let domain = from.toLowerCase().split('@')[1]
30
+ let dmarc = said.split(';').find((s) => /^\s*dmarc=pass\b/i.test(s))
31
+ let aligned = dmarc?.match(/\bheader\.from\s*=\s*"?([^\s;"()]+)/i)?.[1]
32
+ return !!domain && !!dmarc && aligned?.toLowerCase() == domain
33
+ }
34
+
35
+ /** Decode one Email Worker delivery without writing or interpreting it. */
36
+ export let received = async (message: Inbound): Promise<Incoming> => {
37
+ let raw = new Uint8Array(await new Response(message.raw).arrayBuffer())
38
+ let mail = await PostalMime.parse(raw)
39
+ let decoded: Record<string, string | undefined> = {
40
+ from: mail.from?.address,
41
+ subject: mail.subject,
42
+ 'message-id': mail.messageId,
43
+ }
44
+ let checked = message.headers.get('authentication-results')
45
+ return {
46
+ sources: [
47
+ { name: 'message.eml', type: 'message/rfc822', bytes: raw },
48
+ {
49
+ name: 'envelope.json',
50
+ type: 'application/json',
51
+ bytes: new TextEncoder().encode(JSON.stringify({
52
+ from: message.from,
53
+ to: message.to,
54
+ headers: [...message.headers.entries?.() ?? []],
55
+ })),
56
+ },
57
+ ],
58
+ name: mail.from?.name,
59
+ from: message.from,
60
+ to: message.to,
61
+ headers: {
62
+ get: (name) => decoded[name.toLowerCase()] ?? message.headers.get(name),
63
+ },
64
+ text: mail.text ?? '',
65
+ html: mail.html,
66
+ ...checked == null
67
+ ? {}
68
+ : { verified: /(?:^|;)\s*dkim\s*=\s*pass\b/i.test(first(checked)) },
69
+ vouched: vouched(checked, mail.from?.address || message.from),
70
+ attachments: mail.attachments.map((a) => ({
71
+ name: a.filename ?? '',
72
+ type: a.mimeType || 'application/octet-stream',
73
+ bytes: typeof a.content == 'string'
74
+ ? new TextEncoder().encode(a.content)
75
+ : new Uint8Array(a.content),
76
+ })),
77
+ }
78
+ }
package/sender.js ADDED
@@ -0,0 +1,127 @@
1
+ // Cloudflare Email Sending, as a {@link Sender}.
2
+ //
3
+ // It is one HTTP call, so this file is a payload shape and a `fetch`. It holds
4
+ // no credentials and reads no environment: the account and the token are
5
+ // arguments, which is what lets the same code run in a Worker (where secrets
6
+ // arrive on `env`), on a server (where they arrive from the process), and in a
7
+ // test (where they are made up and the `fetch` is a stub).
8
+ //
9
+ // The payload's two parts matter. `text` is the body as written; `html` is the
10
+ // same body rendered, because a mail client has no base document — a link that
11
+ // was relative in the graph reaches the reader as a broken address, which is
12
+ // why ./md.ts rejects one. The threading headers carry the bracketed
13
+ // Message-ID; the receipt returns the unbracketed one the next reply threads
14
+ // on.
15
+ //
16
+ // A failure says whether the letter left. A fetch that fails while connecting
17
+ // never reached the API (Deno names the phase, `client error (Connect)`, for a
18
+ // refused connection, a DNS failure and a broken TLS handshake alike), and a
19
+ // 429 is the API declining to take it yet. Both reject as `Unsent`, so the
20
+ // letter is tried again; anything else may have left, and is a bounce.
21
+ import { Unsent } from "@yaks/host/senders";
22
+ /**
23
+ * A message → the Email Sending payload. Pure, so a test asserts on it without
24
+ * a network anywhere.
25
+ */ export let payload = (m)=>({
26
+ from: {
27
+ address: m.from,
28
+ name: m.name ?? m.from.split('@')[0]
29
+ },
30
+ to: [
31
+ m.to
32
+ ].flat(),
33
+ ...m.cc ? {
34
+ cc: [
35
+ m.cc
36
+ ]
37
+ } : {},
38
+ reply_to: m.replyAddress ?? m.from,
39
+ subject: m.subject,
40
+ text: m.text,
41
+ // The builder requires nonempty text or HTML. A subject-only letter has
42
+ // an empty visible body, not an invalid request (T-64121's real probe).
43
+ html: m.html || (m.text ? '' : '<div></div>'),
44
+ ...m.replyTo ? {
45
+ headers: {
46
+ 'In-Reply-To': `<${m.replyTo}>`,
47
+ References: `<${m.replyTo}>`
48
+ }
49
+ } : {}
50
+ });
51
+ let parse = (raw)=>{
52
+ try {
53
+ return JSON.parse(raw);
54
+ } catch {
55
+ return {} // a non-JSON error body — the status line carries it
56
+ ;
57
+ }
58
+ };
59
+ let said = (err)=>String(err?.message ?? err);
60
+ // The connect phase, as Deno's fetch names it in the rejection.
61
+ let connecting = (err)=>/\(Connect\)/.test(said(err));
62
+ // A 429's Retry-After, in seconds, as the wait before the next try.
63
+ let wait = (res)=>{
64
+ let s = Number(res.headers.get('retry-after'));
65
+ return s > 0 ? s * 1000 : 1000;
66
+ };
67
+ /**
68
+ * One Email Sending request: the API's one client here, for a caller that
69
+ * builds its own {@link Payload} (several recipients, a display name, a
70
+ * Reply-To of its own). It answers the receipt.
71
+ *
72
+ * A failure rejects with the status and the start of the response body, which
73
+ * is what gets written to the letter as `bounced.reason` — so a bounce records
74
+ * what the API reported, not just "send failed". A letter that never reached
75
+ * the API, or that it declined with a 429, rejects as `Unsent` instead.
76
+ */ export let deliver = ({ account, token, base, fetch: call })=>{
77
+ let root = (base ?? 'https://api.cloudflare.com/client/v4').replace(/\/+$/, '');
78
+ let go = call ?? fetch;
79
+ return async (body)=>{
80
+ let res = await go(`${root}/accounts/${account}/email/sending/send`, {
81
+ method: 'POST',
82
+ headers: {
83
+ authorization: `Bearer ${token}`,
84
+ 'content-type': 'application/json'
85
+ },
86
+ body: JSON.stringify(body)
87
+ }).catch((err)=>{
88
+ throw connecting(err) ? new Unsent(`not sent: ${said(err)}`) : err;
89
+ });
90
+ let raw = await res.text();
91
+ let answer = parse(raw);
92
+ if (res.status == 429) {
93
+ throw new Unsent(`not sent (HTTP 429): ${raw.slice(0, 200)}`, wait(res));
94
+ }
95
+ if (!res.ok || !answer.success) {
96
+ throw new Error(`send failed (HTTP ${res.status}): ${raw.slice(0, 200)}`);
97
+ }
98
+ let id = String(answer.result?.message_id ?? '').replace(/[<>]/g, '');
99
+ return id ? {
100
+ id
101
+ } : {};
102
+ };
103
+ };
104
+ /**
105
+ * A {@link Sender} over Cloudflare Email Sending: {@link deliver} of the
106
+ * message's {@link payload}.
107
+ *
108
+ * ```ts
109
+ * import { cloudflare } from '@yaks/cloudflare-mail'
110
+ * // in a Worker: cloudflare({ account: env.CF_ACCOUNT, token: env.CF_EMAIL_TOKEN })
111
+ * ```
112
+ */ export let cloudflare = (account)=>{
113
+ let post = deliver(account);
114
+ return {
115
+ send: (message)=>post(payload(message))
116
+ };
117
+ };
118
+ /** Build from host configuration, leaving missing credentials waiting. */ export let configured = (options)=>options.account && options.token ? {
119
+ sender: cloudflare({
120
+ ...options,
121
+ account: options.account,
122
+ token: options.token
123
+ })
124
+ } : {
125
+ waiting: 'waiting for credentials: a cloudflare sender needs `account` and `token`'
126
+ };
127
+ //# sourceMappingURL=sender.js.map
package/sender.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sender.js","sources":["./sender.ts"],"names":[],"mappings":"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"}
package/sender.ts ADDED
@@ -0,0 +1,178 @@
1
+ // Cloudflare Email Sending, as a {@link Sender}.
2
+ //
3
+ // It is one HTTP call, so this file is a payload shape and a `fetch`. It holds
4
+ // no credentials and reads no environment: the account and the token are
5
+ // arguments, which is what lets the same code run in a Worker (where secrets
6
+ // arrive on `env`), on a server (where they arrive from the process), and in a
7
+ // test (where they are made up and the `fetch` is a stub).
8
+ //
9
+ // The payload's two parts matter. `text` is the body as written; `html` is the
10
+ // same body rendered, because a mail client has no base document — a link that
11
+ // was relative in the graph reaches the reader as a broken address, which is
12
+ // why ./md.ts rejects one. The threading headers carry the bracketed
13
+ // Message-ID; the receipt returns the unbracketed one the next reply threads
14
+ // on.
15
+ //
16
+ // A failure says whether the letter left. A fetch that fails while connecting
17
+ // never reached the API (Deno names the phase, `client error (Connect)`, for a
18
+ // refused connection, a DNS failure and a broken TLS handshake alike), and a
19
+ // 429 is the API declining to take it yet. Both reject as `Unsent`, so the
20
+ // letter is tried again; anything else may have left, and is a bounce.
21
+
22
+ import { Unsent } from '@yaks/host/senders'
23
+ import type { Message, Receipt, Sender } from '@yaks/host/senders'
24
+
25
+ /** The Email Sending payload, as the API takes it. */
26
+ export type Payload = {
27
+ /** the sender, with a display name taken from the local part */
28
+ from: { address: string; name: string }
29
+ /** the recipients */
30
+ to: string[]
31
+ /** the addresses copied */
32
+ cc?: string[]
33
+ /** where a reply should go — the sender, unless you say otherwise */
34
+ reply_to: string
35
+ /** the subject line */
36
+ subject: string
37
+ /** the body as plain text */
38
+ text: string
39
+ /** the body as HTML */
40
+ html: string
41
+ /** the threading headers, present only on a reply */
42
+ headers?: Record<string, string>
43
+ }
44
+
45
+ /**
46
+ * A message → the Email Sending payload. Pure, so a test asserts on it without
47
+ * a network anywhere.
48
+ */
49
+ export let payload = (m: Message): Payload => ({
50
+ from: { address: m.from, name: m.name ?? m.from.split('@')[0] },
51
+ to: [m.to].flat(),
52
+ ...(m.cc ? { cc: [m.cc] } : {}),
53
+ reply_to: m.replyAddress ?? m.from,
54
+ subject: m.subject,
55
+ text: m.text,
56
+ // The builder requires nonempty text or HTML. A subject-only letter has
57
+ // an empty visible body, not an invalid request (T-64121's real probe).
58
+ html: m.html || (m.text ? '' : '<div></div>'),
59
+ ...(m.replyTo
60
+ ? {
61
+ headers: {
62
+ 'In-Reply-To': `<${m.replyTo}>`,
63
+ References: `<${m.replyTo}>`,
64
+ },
65
+ }
66
+ : {}),
67
+ })
68
+
69
+ /** The part of `fetch` this file uses — satisfied by the web `fetch` and by a
70
+ * Worker's. */
71
+ export type Fetch = (url: string, init: RequestInit) => Promise<Response>
72
+
73
+ /** What the sender needs to reach the account. */
74
+ export type Account = {
75
+ /** the Cloudflare account id */
76
+ account: string
77
+ /** an API token that may send mail — never held by this package */
78
+ token: string
79
+ /** the API root, to point a test at a stub (default: the API itself) */
80
+ base?: string
81
+ /** the fetch to call through (default: the global one) */
82
+ fetch?: Fetch
83
+ }
84
+
85
+ // What the API answers with, as far as this file reads it.
86
+ type Answer = { success?: boolean; result?: { message_id?: string } }
87
+
88
+ let parse = (raw: string): Answer => {
89
+ try {
90
+ return JSON.parse(raw) as Answer
91
+ } catch {
92
+ return {} // a non-JSON error body — the status line carries it
93
+ }
94
+ }
95
+
96
+ let said = (err: unknown) => String((err as Error)?.message ?? err)
97
+
98
+ // The connect phase, as Deno's fetch names it in the rejection.
99
+ let connecting = (err: unknown) => /\(Connect\)/.test(said(err))
100
+
101
+ // A 429's Retry-After, in seconds, as the wait before the next try.
102
+ let wait = (res: Response) => {
103
+ let s = Number(res.headers.get('retry-after'))
104
+ return s > 0 ? s * 1000 : 1000
105
+ }
106
+
107
+ /**
108
+ * One Email Sending request: the API's one client here, for a caller that
109
+ * builds its own {@link Payload} (several recipients, a display name, a
110
+ * Reply-To of its own). It answers the receipt.
111
+ *
112
+ * A failure rejects with the status and the start of the response body, which
113
+ * is what gets written to the letter as `bounced.reason` — so a bounce records
114
+ * what the API reported, not just "send failed". A letter that never reached
115
+ * the API, or that it declined with a 429, rejects as `Unsent` instead.
116
+ */
117
+ export let deliver = (
118
+ { account, token, base, fetch: call }: Account,
119
+ ): (body: Payload) => Promise<Receipt> => {
120
+ let root = (base ?? 'https://api.cloudflare.com/client/v4').replace(
121
+ /\/+$/,
122
+ '',
123
+ )
124
+ let go: Fetch = call ?? fetch
125
+ return async (body: Payload): Promise<Receipt> => {
126
+ let res = await go(`${root}/accounts/${account}/email/sending/send`, {
127
+ method: 'POST',
128
+ headers: {
129
+ authorization: `Bearer ${token}`,
130
+ 'content-type': 'application/json',
131
+ },
132
+ body: JSON.stringify(body),
133
+ }).catch((err) => {
134
+ throw connecting(err) ? new Unsent(`not sent: ${said(err)}`) : err
135
+ })
136
+ let raw = await res.text()
137
+ let answer = parse(raw)
138
+ if (res.status == 429) {
139
+ throw new Unsent(`not sent (HTTP 429): ${raw.slice(0, 200)}`, wait(res))
140
+ }
141
+ if (!res.ok || !answer.success) {
142
+ throw new Error(`send failed (HTTP ${res.status}): ${raw.slice(0, 200)}`)
143
+ }
144
+ let id = String(answer.result?.message_id ?? '').replace(/[<>]/g, '')
145
+ return id ? { id } : {}
146
+ }
147
+ }
148
+
149
+ /**
150
+ * A {@link Sender} over Cloudflare Email Sending: {@link deliver} of the
151
+ * message's {@link payload}.
152
+ *
153
+ * ```ts
154
+ * import { cloudflare } from '@yaks/cloudflare-mail'
155
+ * // in a Worker: cloudflare({ account: env.CF_ACCOUNT, token: env.CF_EMAIL_TOKEN })
156
+ * ```
157
+ */
158
+ export let cloudflare = (account: Account): Sender => {
159
+ let post = deliver(account)
160
+ return { send: (message: Message) => post(payload(message)) }
161
+ }
162
+
163
+ /** Build from host configuration, leaving missing credentials waiting. */
164
+ export let configured = (
165
+ options: Partial<Account>,
166
+ ): { sender?: Sender; waiting?: string } =>
167
+ options.account && options.token
168
+ ? {
169
+ sender: cloudflare({
170
+ ...options,
171
+ account: options.account,
172
+ token: options.token,
173
+ }),
174
+ }
175
+ : {
176
+ waiting:
177
+ 'waiting for credentials: a cloudflare sender needs `account` and `token`',
178
+ }