@aglyn/shared-util-email 1.0.0-beta.143

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.
Files changed (72) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +104 -0
  3. package/package.json +37 -0
  4. package/src/index.d.ts +37 -0
  5. package/src/index.js +46 -0
  6. package/src/index.js.map +1 -0
  7. package/src/lib/email-delivery-events.d.ts +198 -0
  8. package/src/lib/email-delivery-events.js +310 -0
  9. package/src/lib/email-delivery-events.js.map +1 -0
  10. package/src/lib/email-health.d.ts +154 -0
  11. package/src/lib/email-health.js +264 -0
  12. package/src/lib/email-health.js.map +1 -0
  13. package/src/lib/email-media-src.d.ts +33 -0
  14. package/src/lib/email-media-src.js +113 -0
  15. package/src/lib/email-media-src.js.map +1 -0
  16. package/src/lib/email-merge.d.ts +31 -0
  17. package/src/lib/email-merge.js +36 -0
  18. package/src/lib/email-merge.js.map +1 -0
  19. package/src/lib/email-render.d.ts +114 -0
  20. package/src/lib/email-render.js +293 -0
  21. package/src/lib/email-render.js.map +1 -0
  22. package/src/lib/email-revenue-window.d.ts +55 -0
  23. package/src/lib/email-revenue-window.js +58 -0
  24. package/src/lib/email-revenue-window.js.map +1 -0
  25. package/src/lib/host-email-render.d.ts +99 -0
  26. package/src/lib/host-email-render.js +126 -0
  27. package/src/lib/host-email-render.js.map +1 -0
  28. package/src/lib/host-sender.d.ts +86 -0
  29. package/src/lib/host-sender.js +131 -0
  30. package/src/lib/host-sender.js.map +1 -0
  31. package/src/lib/marketing-send.d.ts +466 -0
  32. package/src/lib/marketing-send.js +459 -0
  33. package/src/lib/marketing-send.js.map +1 -0
  34. package/src/lib/platform-sending-domain.d.ts +362 -0
  35. package/src/lib/platform-sending-domain.js +697 -0
  36. package/src/lib/platform-sending-domain.js.map +1 -0
  37. package/src/lib/received-email.d.ts +86 -0
  38. package/src/lib/received-email.js +124 -0
  39. package/src/lib/received-email.js.map +1 -0
  40. package/src/lib/send-ceilings.d.ts +394 -0
  41. package/src/lib/send-ceilings.js +341 -0
  42. package/src/lib/send-ceilings.js.map +1 -0
  43. package/src/lib/send-email.d.ts +385 -0
  44. package/src/lib/send-email.js +586 -0
  45. package/src/lib/send-email.js.map +1 -0
  46. package/src/lib/send-rate.d.ts +298 -0
  47. package/src/lib/send-rate.js +310 -0
  48. package/src/lib/send-rate.js.map +1 -0
  49. package/src/lib/sender-reputation.d.ts +357 -0
  50. package/src/lib/sender-reputation.js +392 -0
  51. package/src/lib/sender-reputation.js.map +1 -0
  52. package/src/lib/sending-domain.d.ts +744 -0
  53. package/src/lib/sending-domain.js +798 -0
  54. package/src/lib/sending-domain.js.map +1 -0
  55. package/src/lib/sending-mailbox.d.ts +132 -0
  56. package/src/lib/sending-mailbox.js +192 -0
  57. package/src/lib/sending-mailbox.js.map +1 -0
  58. package/src/lib/stored-email-nodes.d.ts +38 -0
  59. package/src/lib/stored-email-nodes.js +78 -0
  60. package/src/lib/stored-email-nodes.js.map +1 -0
  61. package/src/lib/svix-signature.d.ts +38 -0
  62. package/src/lib/svix-signature.js +55 -0
  63. package/src/lib/svix-signature.js.map +1 -0
  64. package/src/lib/system-email-catalog.d.ts +170 -0
  65. package/src/lib/system-email-catalog.js +828 -0
  66. package/src/lib/system-email-catalog.js.map +1 -0
  67. package/src/lib/tenant-email-catalog.d.ts +78 -0
  68. package/src/lib/tenant-email-catalog.js +452 -0
  69. package/src/lib/tenant-email-catalog.js.map +1 -0
  70. package/src/lib/text-email-html.d.ts +32 -0
  71. package/src/lib/text-email-html.js +119 -0
  72. package/src/lib/text-email-html.js.map +1 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,104 @@
1
+ # @aglyn/shared-util-email
2
+
3
+ One place that sends outbound **application** email, via
4
+ [Resend](https://resend.com).
5
+
6
+ Before this library the same ~30 lines of `fetch('https://api.resend.com/emails')`
7
+ were copy-pasted across 10 files, each reading the env vars itself and each
8
+ handling failure a little differently. Consolidating them means the provider,
9
+ the sender identity, and the failure semantics change in one place (AGL-709).
10
+
11
+ ## What is and is not in scope
12
+
13
+ | Mail | Sent by | Here? |
14
+ | --- | --- | --- |
15
+ | Invites, receipts, usage summaries, campaigns, staff alerts | Resend | ✅ |
16
+ | Verification, password reset | Firebase Auth | ❌ |
17
+ | Inbound mail to `@aglyn.com` mailboxes | Google Workspace | ❌ |
18
+
19
+ ## Configuration
20
+
21
+ Two env vars, read at call time:
22
+
23
+ ```
24
+ RESEND_API_KEY=re_xxxxxxxx
25
+ USAGE_EMAIL_FROM="Aglyn <noreply@aglyn.com>"
26
+ ```
27
+
28
+ **Both** are required. With either missing, `sendEmail()` warns and returns
29
+ `{ sent: false, reason: 'unconfigured' }` — it does not throw, so local and
30
+ preview environments run fine without a Resend account.
31
+
32
+ Setup and DNS are documented in [`docs/EMAIL_SETUP.md`](../../../../docs/EMAIL_SETUP.md).
33
+
34
+ ## Usage
35
+
36
+ ```typescript
37
+ import { sendEmail } from '@aglyn/shared-util-email'
38
+
39
+ const result = await sendEmail({
40
+ to: 'someone@example.com',
41
+ subject: 'You have been invited',
42
+ text: 'Sign in to accept.',
43
+ context: 'invite', // shows up in logs on failure
44
+ })
45
+
46
+ if (!result.sent) {
47
+ // 'unconfigured' | 'no-recipient' | 'rejected' | 'network'
48
+ console.warn('no mail went out:', result.reason)
49
+ }
50
+ ```
51
+
52
+ `sendEmail()` **never throws**. Outbound mail is best-effort everywhere in
53
+ this codebase — a checkout must not fail because a receipt bounced — so every
54
+ outcome comes back as a result object. Do check `sent`: it is what lets the
55
+ console tell a user honestly whether a message actually went out (AGL-708).
56
+
57
+ Optional fields: `html`, `headers` (e.g. `List-Unsubscribe`), `tags` (webhook
58
+ attribution), `replyTo`, and `from` (overrides the configured sender — rarely
59
+ correct, since the point of `USAGE_EMAIL_FROM` is one verified identity).
60
+
61
+ ### The transport boundary
62
+
63
+ `postResendEmail()` is the only function that POSTs to Resend's send endpoint,
64
+ and it **throws** on a payload with no `to` rather than putting it on the wire.
65
+ Such a payload cannot become a message; Resend answers `422
66
+ missing_required_field`, which costs an API call and then sits in the vendor
67
+ dashboard looking exactly like mail that failed to deliver, carrying nothing
68
+ that names the code responsible. `sendEmail()` filters recipients long before
69
+ this point, so ordinary senders never meet the guard — it is there because
70
+ `RESEND_SEND_ENDPOINT` is exported and a module that fetches it directly
71
+ bypasses every check `sendEmail()` owns.
72
+
73
+ ## Checking configuration
74
+
75
+ ```typescript
76
+ import { isEmailConfigured, describeEmailConfig, checkEmailCredentials }
77
+ from '@aglyn/shared-util-email'
78
+ ```
79
+
80
+ - `isEmailConfigured()` — both vars present. Use it to answer `501` from a
81
+ route instead of pretending to have sent.
82
+ - `describeEmailConfig()` — env presence plus the sender and its domain, with
83
+ the API key never included.
84
+ - `checkEmailCredentials()` — asks Resend whether the key is accepted
85
+ **without sending anything**, by `GET`ting the domains collection and
86
+ reading the error NAME rather than the status. A `2xx`, or a
87
+ `restricted_api_key`/`invalid_permission` rejection (what a sending-scoped
88
+ key gets, and it can only be reached once Resend has authenticated the key),
89
+ means the credential works. `missing_api_key`, `validation_error` and
90
+ `suspended_api_key` mean it was refused. Anything else is `unknown`, never
91
+ `invalid-key`. It never touches the send endpoint: a probe aimed there is
92
+ logged by Resend as a `422` on `POST /emails` and reads, in the dashboard,
93
+ as failed mail. It cannot confirm domain verification — only a real send
94
+ does that.
95
+
96
+ These back the staff-only `/api/admin/email-health` route in the console.
97
+
98
+ ## Running unit tests
99
+
100
+ Run `nx test shared-util-email` to execute the unit tests via
101
+ [Jest](https://jestjs.io).
102
+
103
+ Note: prefer bare `jest` over `nx test` when a test depends on env vars — `nx`
104
+ injects the root `.env`, which can turn a genuinely failing test green.
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@aglyn/shared-util-email",
3
+ "version": "1.0.0-beta.143",
4
+ "license": "Apache-2.0",
5
+ "homepage": "https://aglyn.com",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/aglyn/aglyn.git",
9
+ "directory": "libs/shared/util/email"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "provenance": true
14
+ },
15
+ "type": "module",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./src/index.d.ts",
19
+ "default": "./src/index.js"
20
+ },
21
+ "./*": {
22
+ "types": "./src/lib/*.d.ts",
23
+ "default": "./src/lib/*.js"
24
+ },
25
+ "./package.json": "./package.json"
26
+ },
27
+ "dependencies": {
28
+ "@aglyn/shared-data-enums": "1.0.0-beta.143",
29
+ "@aglyn/shared-util-http": "1.0.0-beta.143",
30
+ "@msgpack/msgpack": "^3.1.3",
31
+ "@swc/helpers": "0.5.23"
32
+ },
33
+ "sideEffects": false,
34
+ "types": "./src/index.d.ts",
35
+ "module": "./src/index.js",
36
+ "main": "./src/index.js"
37
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export * from './lib/send-email';
18
+ export * from './lib/send-rate';
19
+ export * from './lib/sender-reputation';
20
+ export * from './lib/send-ceilings';
21
+ export * from './lib/sending-domain';
22
+ export * from './lib/sending-mailbox';
23
+ export * from './lib/host-sender';
24
+ export * from './lib/platform-sending-domain';
25
+ export * from './lib/email-health';
26
+ export * from './lib/system-email-catalog';
27
+ export * from './lib/tenant-email-catalog';
28
+ export * from './lib/host-email-render';
29
+ export * from './lib/email-render';
30
+ export * from './lib/text-email-html';
31
+ export * from './lib/marketing-send';
32
+ export * from './lib/email-delivery-events';
33
+ export * from './lib/received-email';
34
+ export * from './lib/email-revenue-window';
35
+ export * from './lib/email-media-src';
36
+ export * from './lib/stored-email-nodes';
37
+ export * from './lib/email-merge';
package/src/index.js ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ export * from "./lib/send-email.js";
17
+ export * from "./lib/send-rate.js";
18
+ export * from "./lib/sender-reputation.js";
19
+ export * from "./lib/send-ceilings.js";
20
+ export * from "./lib/sending-domain.js";
21
+ export * from "./lib/sending-mailbox.js";
22
+ export * from "./lib/host-sender.js";
23
+ export * from "./lib/platform-sending-domain.js";
24
+ export * from "./lib/email-health.js";
25
+ export * from "./lib/system-email-catalog.js";
26
+ export * from "./lib/tenant-email-catalog.js";
27
+ export * from "./lib/host-email-render.js";
28
+ export * from "./lib/email-render.js";
29
+ export * from "./lib/text-email-html.js";
30
+ export * from "./lib/marketing-send.js";
31
+ export * from "./lib/email-delivery-events.js";
32
+ // The received-mail reader the CRM's capture route files from (AGL-2657).
33
+ // Its neighbor `./lib/svix-signature` is deliberately NOT re-exported here:
34
+ // it holds a `crypto` HMAC, and this barrel is reached from the browser
35
+ // through `@aglyn/shared-ui-email-campaigns`, so a webhook imports it by its
36
+ // own path — `@aglyn/shared-util-email/svix-signature`.
37
+ export * from "./lib/received-email.js";
38
+ export * from "./lib/email-revenue-window.js";
39
+ // Exported so the console drift guard can pin it against @aglyn/aglyn.
40
+ export * from "./lib/email-media-src.js";
41
+ // Same arrangement, same reason (AGL-1223): a copy of `decodeStoredNodes`
42
+ // this scope:shared lib may not import, pinned by `email-nodes-drift.spec.ts`.
43
+ export * from "./lib/stored-email-nodes.js";
44
+ export * from "./lib/email-merge.js";
45
+
46
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../libs/shared/util/email/src/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './lib/send-email'\nexport * from './lib/send-rate'\nexport * from './lib/sender-reputation'\nexport * from './lib/send-ceilings'\nexport * from './lib/sending-domain'\nexport * from './lib/sending-mailbox'\nexport * from './lib/host-sender'\nexport * from './lib/platform-sending-domain'\nexport * from './lib/email-health'\nexport * from './lib/system-email-catalog'\nexport * from './lib/tenant-email-catalog'\nexport * from './lib/host-email-render'\nexport * from './lib/email-render'\nexport * from './lib/text-email-html'\nexport * from './lib/marketing-send'\nexport * from './lib/email-delivery-events'\n// The received-mail reader the CRM's capture route files from (AGL-2657).\n// Its neighbor `./lib/svix-signature` is deliberately NOT re-exported here:\n// it holds a `crypto` HMAC, and this barrel is reached from the browser\n// through `@aglyn/shared-ui-email-campaigns`, so a webhook imports it by its\n// own path — `@aglyn/shared-util-email/svix-signature`.\nexport * from './lib/received-email'\nexport * from './lib/email-revenue-window'\n// Exported so the console drift guard can pin it against @aglyn/aglyn.\nexport * from './lib/email-media-src'\n// Same arrangement, same reason (AGL-1223): a copy of `decodeStoredNodes`\n// this scope:shared lib may not import, pinned by `email-nodes-drift.spec.ts`.\nexport * from './lib/stored-email-nodes'\nexport * from './lib/email-merge'\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,cAAc,sBAAkB;AAChC,cAAc,qBAAiB;AAC/B,cAAc,6BAAyB;AACvC,cAAc,yBAAqB;AACnC,cAAc,0BAAsB;AACpC,cAAc,2BAAuB;AACrC,cAAc,uBAAmB;AACjC,cAAc,mCAA+B;AAC7C,cAAc,wBAAoB;AAClC,cAAc,gCAA4B;AAC1C,cAAc,gCAA4B;AAC1C,cAAc,6BAAyB;AACvC,cAAc,wBAAoB;AAClC,cAAc,2BAAuB;AACrC,cAAc,0BAAsB;AACpC,cAAc,iCAA6B;AAC3C,0EAA0E;AAC1E,4EAA4E;AAC5E,wEAAwE;AACxE,6EAA6E;AAC7E,wDAAwD;AACxD,cAAc,0BAAsB;AACpC,cAAc,gCAA4B;AAC1C,uEAAuE;AACvE,cAAc,2BAAuB;AACrC,0EAA0E;AAC1E,+EAA+E;AAC/E,cAAc,8BAA0B;AACxC,cAAc,uBAAmB"}
@@ -0,0 +1,198 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * WHAT HAPPENED TO A MESSAGE, IN OUR OWN VOCABULARY.
19
+ *
20
+ * ## The seam
21
+ *
22
+ * A staff answer to "did they get the invite, and did they open it?" must not
23
+ * be a question about Resend. Two things follow from that, and this module is
24
+ * both of them:
25
+ *
26
+ * 1. **The stored shape is ours.** Nothing downstream — the delivery log, the
27
+ * staff card, a future export — reads a provider's field names or its event
28
+ * strings. Swapping the sender changes exactly one function in this file
29
+ * and nothing else in the tree.
30
+ * 2. **The history is ours.** The log is written into our own Firestore and
31
+ * read from there, never from the provider on render. A provider's list
32
+ * endpoint is a different shape per vendor, has its own retention window,
33
+ * and disappears entirely with the account; a record we keep survives the
34
+ * migration that the seam exists to make possible.
35
+ *
36
+ * That is a rule about the READ PATH, not a rule against ever reading the
37
+ * provider. The event feed only knows mail sent after it was connected, so
38
+ * a log fed by events alone is empty for all existing history — which is
39
+ * precisely the mail a support question is about. The second half of this
40
+ * module (see THE READ SIDE OF THE SEAM below) imports that history
41
+ * through the same neutral vocabulary, once, into the same store.
42
+ *
43
+ * ## Pure on purpose
44
+ *
45
+ * No Firestore and no admin SDK. `system-email-catalog` is imported by console
46
+ * CLIENT components through this library's barrel, so anything reachable from
47
+ * it that touched `firebase-admin` would drag the admin SDK into a browser
48
+ * bundle. Normalisation is a pure function of a payload; the writing lives in
49
+ * `@aglyn/tenant-data-admin/server/email-delivery-log`.
50
+ *
51
+ * The one `fetch` is `resendDeliveryHistorySource`, which is a function that
52
+ * must be CALLED with a key to do anything — it holds no module state and is
53
+ * unreachable from a client component, unlike an admin-SDK import, which
54
+ * executes on load.
55
+ */
56
+ /**
57
+ * The lifecycle of one message, in the order it normally happens.
58
+ *
59
+ * Chosen to be the intersection every ESP can report rather than the union of
60
+ * what any one of them does: a vendor with no equivalent for a state simply
61
+ * never produces it, and a vendor with a richer taxonomy folds into the
62
+ * nearest of these rather than widening the type. `delayed` is retryable and
63
+ * `failed` is not, which is the distinction a staffer actually needs.
64
+ */
65
+ export type EmailDeliveryEventType = 'sent' | 'delivered' | 'delayed' | 'opened' | 'clicked' | 'bounced' | 'complained' | 'failed';
66
+ /**
67
+ * One normalized delivery event.
68
+ *
69
+ * `at` is epoch milliseconds rather than a Firestore timestamp so this type
70
+ * stays usable in a browser, in a test, and in whatever writes it next.
71
+ */
72
+ export interface EmailDeliveryEvent {
73
+ type: EmailDeliveryEventType;
74
+ /** When the PROVIDER says it happened, falling back to receipt time. */
75
+ at: number;
76
+ /** Slug of the sending provider, e.g. `'resend'`. */
77
+ provider: string;
78
+ /** The provider's id for the message. Our per-message document key. */
79
+ providerMessageId: string;
80
+ /** Recipient, lowercased. One address per record even on a multi-recipient send. */
81
+ to: string;
82
+ subject: string | null;
83
+ /**
84
+ * The sender label `sendEmail` stamps on every message (`'invite'`,
85
+ * `'password-reset'`, `'campaign'`, …). This is what makes the staff view
86
+ * legible: without it a row says only that *an* email was sent.
87
+ */
88
+ context: string | null;
89
+ /** Everything else the send was tagged with, e.g. `hostId`, `campaignId`. */
90
+ tags: Record<string, string>;
91
+ /** `clicked` only: the destination the recipient followed. */
92
+ link: string | null;
93
+ /**
94
+ * `bounced` only: whether the mailbox is gone (`permanent`) or the failure
95
+ * was temporary. Lowercased, because providers disagree on capitalisation
96
+ * and a staff filter must not depend on which one is in use.
97
+ */
98
+ bounceType: 'permanent' | 'transient' | 'undetermined' | null;
99
+ /** Provider-supplied explanation, for the states that carry one. */
100
+ detail: string | null;
101
+ }
102
+ /** The later of two statuses on the lifecycle, worst winning a tie. */
103
+ export declare function worstDeliveryStatus(current: EmailDeliveryEventType | null | undefined, next: EmailDeliveryEventType): EmailDeliveryEventType;
104
+ /** Tags arrive as an array of `{name, value}` or a plain map — accept both. */
105
+ export declare function normalizeEventTags(raw: unknown): Record<string, string>;
106
+ /**
107
+ * Turns one Resend webhook payload into zero or more of our events — **the
108
+ * only function in the tree that knows Resend's wire format.**
109
+ *
110
+ * One event per recipient, not per message: a send addressed to three people
111
+ * produces one webhook, and a staff view keyed on a person has to be able to
112
+ * find it under each of them.
113
+ *
114
+ * Returns an empty array for anything unrecognised — a contact or domain
115
+ * event, an inbound `email.received`, a type added after this was written.
116
+ * Silence rather than a throw, because a webhook handler that 500s on an
117
+ * unfamiliar event teaches the provider to retry it forever.
118
+ *
119
+ * @param payload The parsed webhook body.
120
+ * @param receivedAtMs Fallback timestamp for a payload that carries none.
121
+ */
122
+ export declare function normalizeResendDeliveryEvents(payload: unknown, receivedAtMs: number): EmailDeliveryEvent[];
123
+ /** One message as the provider currently reports it, in our vocabulary. */
124
+ export interface EmailDeliverySnapshot {
125
+ provider: string;
126
+ providerMessageId: string;
127
+ to: string;
128
+ subject: string | null;
129
+ /** Epoch ms the provider says the message was created. */
130
+ sentAt: number;
131
+ /** Furthest state the provider reports. Never richer than the event feed. */
132
+ status: EmailDeliveryEventType;
133
+ }
134
+ /**
135
+ * Turns one entry from Resend's `GET /emails` list into zero or more
136
+ * snapshots — one per recipient, for the same reason the event adapter fans
137
+ * out: the staff view is keyed on a person.
138
+ *
139
+ * An unrecognised `last_event` falls back to `sent` rather than being
140
+ * dropped. The message demonstrably exists and was addressed to somebody, and
141
+ * "we sent this and cannot characterise what happened next" is a far more
142
+ * useful row than no row — which is the state that sent a staffer to the
143
+ * vendor dashboard in the first place.
144
+ */
145
+ export declare function normalizeResendSentEmails(raw: unknown): EmailDeliverySnapshot[];
146
+ /** One page of provider history, in our vocabulary. */
147
+ export interface EmailDeliveryHistoryPage {
148
+ snapshots: EmailDeliverySnapshot[];
149
+ /** Cursor for the next page, or null at the end. */
150
+ nextCursor: string | null;
151
+ }
152
+ /**
153
+ * Reads one page of already-sent mail from a provider.
154
+ *
155
+ * The shape a second provider would implement. Cursor-based rather than
156
+ * offset- or date-based because that is the lowest common denominator, and
157
+ * NOT filtered by recipient: Resend's list endpoint has no recipient
158
+ * parameter, so filtering is the caller's job and the import is a sweep
159
+ * rather than a per-person lookup. That is the right shape regardless — a
160
+ * staff page must not fan out to a third party on render.
161
+ */
162
+ export type EmailDeliveryHistorySource = (options: {
163
+ cursor?: string | null;
164
+ limit?: number;
165
+ }) => Promise<EmailDeliveryHistoryPage>;
166
+ /** Resend's list endpoint. Paginates with `after=<id>`; caps at 100. */
167
+ export declare const RESEND_EMAILS_ENDPOINT = "https://api.resend.com/emails";
168
+ /**
169
+ * {@link EmailDeliveryHistorySource} for Resend.
170
+ *
171
+ * Needs a FULL-ACCESS key: a sending-scoped key answers every read on this
172
+ * endpoint with `401 restricted_api_key`, which is the correct posture for
173
+ * the key that sends mail and the reason this takes its own.
174
+ */
175
+ export declare function resendDeliveryHistorySource(apiKey: string): EmailDeliveryHistorySource;
176
+ /** One message's content and envelope, in our vocabulary. */
177
+ export interface EmailDeliveryMessage {
178
+ provider: string;
179
+ providerMessageId: string;
180
+ to: string[];
181
+ cc: string[];
182
+ bcc: string[];
183
+ from: string | null;
184
+ replyTo: string[] | null;
185
+ subject: string | null;
186
+ /** The HTML part, or null when the message was sent as text only. */
187
+ html: string | null;
188
+ /** The plain-text part, or null. */
189
+ text: string | null;
190
+ sentAt: number | null;
191
+ status: EmailDeliveryEventType | null;
192
+ }
193
+ /** A single message by id. The shape a second provider would implement. */
194
+ export type EmailDeliveryMessageSource = (providerMessageId: string) => Promise<EmailDeliveryMessage | null>;
195
+ /** Resend's `GET /emails/:id` payload, in our vocabulary. */
196
+ export declare function normalizeResendMessage(raw: unknown): EmailDeliveryMessage | null;
197
+ /** Resend's single-message endpoint. Needs the same full-access key. */
198
+ export declare function resendDeliveryMessageSource(apiKey: string): EmailDeliveryMessageSource;