@aglyn/tenant-data-admin 1.0.0-beta.201 → 1.0.0-beta.203

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 (35) hide show
  1. package/package.json +7 -7
  2. package/src/lib/server/card-payment-velocity.d.ts +85 -0
  3. package/src/lib/server/card-payment-velocity.js +202 -0
  4. package/src/lib/server/card-payment-velocity.js.map +1 -0
  5. package/src/lib/server/configured-url-fetch.d.ts +42 -0
  6. package/src/lib/server/configured-url-fetch.js +118 -0
  7. package/src/lib/server/configured-url-fetch.js.map +1 -0
  8. package/src/lib/server/hosted-page-review.d.ts +22 -2
  9. package/src/lib/server/hosted-page-review.js +43 -7
  10. package/src/lib/server/hosted-page-review.js.map +1 -1
  11. package/src/lib/server/member-email-aliases.js +18 -7
  12. package/src/lib/server/member-email-aliases.js.map +1 -1
  13. package/src/lib/server/notifications.d.ts +8 -0
  14. package/src/lib/server/notifications.js +92 -17
  15. package/src/lib/server/notifications.js.map +1 -1
  16. package/src/lib/server/org-member-notice.js +20 -5
  17. package/src/lib/server/org-member-notice.js.map +1 -1
  18. package/src/lib/server/organizations.d.ts +10 -1
  19. package/src/lib/server/organizations.js +12 -4
  20. package/src/lib/server/organizations.js.map +1 -1
  21. package/src/lib/server/outbound-send-review.d.ts +4 -2
  22. package/src/lib/server/outbound-send-review.js +1 -1
  23. package/src/lib/server/outbound-send-review.js.map +1 -1
  24. package/src/lib/server/render-system-email.d.ts +176 -0
  25. package/src/lib/server/render-system-email.js +315 -0
  26. package/src/lib/server/render-system-email.js.map +1 -0
  27. package/src/lib/server/staff-alert-email.d.ts +2 -1
  28. package/src/lib/server/staff-alert-email.js +16 -5
  29. package/src/lib/server/staff-alert-email.js.map +1 -1
  30. package/src/lib/server/stripe-transfer-reversal.d.ts +63 -0
  31. package/src/lib/server/stripe-transfer-reversal.js +177 -0
  32. package/src/lib/server/stripe-transfer-reversal.js.map +1 -0
  33. package/src/tenancy.d.ts +2 -0
  34. package/src/tenancy.js +2 -0
  35. package/src/tenancy.js.map +1 -1
@@ -0,0 +1,315 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ var _process_env_NEXT_PUBLIC_CONSOLE_URL;
3
+ /**
4
+ * @license
5
+ * Copyright 2026 Aglyn LLC
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */ import { EMAIL_NODE_ROOT_ID, SYSTEM_EMAIL_COLLECTION, buildDefaultEmailNodeMap, getSystemEmailTemplate, renderEmailHtml, substituteMergeTokens } from "@aglyn/shared-util-email";
19
+ import { firebaseAdmin } from "./firebase-admin.js";
20
+ import { platformMarketingHostId } from "./platform-marketing-consent.js";
21
+ import { brandMergeTokens, collectReferencedComponentIds, composeReusableComponentNodes, decodeStoredNodes, resolveBrandingProfile, sanitizeAuthorHtml } from "@aglyn/aglyn/server";
22
+ import { hostComponentReader, loadReferencedComponents } from "@aglyn/aglyn/app-utils/load-referenced-components";
23
+ import { PLATFORM_BRAND_MERGE_TOKENS, buildSystemEmailChrome, isPlatformBrandedSend } from "@aglyn/aglyn/app-utils/system-email-chrome";
24
+ // Defined beside the chrome they decide, and re-exported for the callers and
25
+ // specs that reach them through this module.
26
+ export { isPlatformBrandedSend };
27
+ /**
28
+ * Blanks any `{{token}}` the caller did not supply.
29
+ *
30
+ * `substituteMergeTokens` leaves unknown tokens untouched, which is right for
31
+ * campaigns (an author wants to see the tag they mistyped) but wrong here —
32
+ * a system email goes to a customer, and "You've been invited to
33
+ * {{org.name}}" is worse than a gap. Applied only in this resolver so
34
+ * campaign behaviour is unchanged.
35
+ */ function blankUnresolvedTokens(value) {
36
+ return value.replace(/\{\{[^}]*\}\}/g, '');
37
+ }
38
+ /**
39
+ * Origin a picked image in a system email is fetched from (AGL-1224).
40
+ *
41
+ * A system email is staff-designed and its media lives in the platform
42
+ * library, which the CONSOLE's `/api/media/cdn` route serves — the tenant app
43
+ * mounts the same route, but a recipient of an org invite has no site to
44
+ * resolve against. Same expression `app/layout.tsx` uses for the console's
45
+ * own canonical URL, so the two cannot drift per deploy.
46
+ */ const CONSOLE_ORIGIN = (_process_env_NEXT_PUBLIC_CONSOLE_URL = process.env.NEXT_PUBLIC_CONSOLE_URL) != null ? _process_env_NEXT_PUBLIC_CONSOLE_URL : 'https://app.aglyn.com';
47
+ /**
48
+ * The email blocks a platform email places, read from the site that owns
49
+ * them (AGL-3318), or `undefined` when there is nothing to read or the read
50
+ * failed.
51
+ *
52
+ * WHICH SITE. A block is a reusable component, and a component belongs to a
53
+ * site; a platform email belongs to none. The header and footer Aglyn's own
54
+ * mail wears are the ones on its marketing site, which the deployment names
55
+ * in `PLATFORM_MARKETING_HOST_ID`, the setting product-email consent already
56
+ * reads. An install that names none reads nothing, and a block placed in its
57
+ * system emails renders as nothing.
58
+ *
59
+ * NEVER A REASON NOT TO SEND. A site's own email fails its whole load when a
60
+ * component read fails, and falls back to its built-in copy. Here the copy is
61
+ * staff's design and the blocks are another site's chrome, so a failed read
62
+ * costs the blocks and nothing else: it is logged, and the design renders
63
+ * inside the coded header and footer instead (see
64
+ * {@link renderLoadedSystemEmail}) rather than being traded for the built-in
65
+ * copy. A password reset whose header could not be read still carries its
66
+ * link.
67
+ */ async function loadPlatformEmailBlocks(firestore, templateKey, nodes) {
68
+ // A design that places nothing costs nothing: no setting read, no read.
69
+ if (!collectReferencedComponentIds(nodes).size) return undefined;
70
+ const hostId = platformMarketingHostId();
71
+ if (!hostId) return undefined;
72
+ try {
73
+ return await loadReferencedComponents(nodes, hostComponentReader(firestore, hostId), {
74
+ onSkipped: (skipped)=>console.warn(JSON.stringify({
75
+ tag: 'AGL-3318:platform-email-blocks-skipped',
76
+ templateKey,
77
+ hostId,
78
+ skipped
79
+ }))
80
+ });
81
+ } catch (error) {
82
+ console.error(`system email template ${templateKey}: its email blocks failed to load from ${hostId}`, error);
83
+ return undefined;
84
+ }
85
+ }
86
+ /**
87
+ * Whether one send draws the design's email blocks: a send under the
88
+ * platform's own brand (see {@link isPlatformBrandedSend}) of a design whose
89
+ * blocks the load could read. Every other send renders the stored nodes, each
90
+ * block a placement that draws nothing, inside the coded chrome.
91
+ */ function drawsPlatformBlocks(loaded, merged, options) {
92
+ return Boolean(loaded.components && Object.keys(loaded.components).length) && isPlatformBrandedSend(merged, options);
93
+ }
94
+ /**
95
+ * A key's built-in copy as a loaded email (AGL-3322): the node map the editor
96
+ * seeds a first design with, and the catalog subject. What a key sends until
97
+ * staff publish a design, and whenever the published one cannot be read.
98
+ */ function catalogDefault(definition) {
99
+ return {
100
+ definition,
101
+ nodes: buildDefaultEmailNodeMap(definition),
102
+ subjectTemplate: definition.defaultSubject,
103
+ preheaderTemplate: '',
104
+ source: 'default'
105
+ };
106
+ }
107
+ /**
108
+ * Loads what a key sends — ONE Firestore read — ready to render per
109
+ * recipient: the published staff design, or the catalog's built-in copy
110
+ * (AGL-3322) when there is none to use (no document, no published version,
111
+ * an empty node map, or a read failure).
112
+ *
113
+ * `null` only for a key that is unknown or not Resend-delivered, which has
114
+ * nothing here to render. Split out from {@link renderSystemEmail} so a batch
115
+ * send resolves the template once and renders it per recipient, rather than
116
+ * one read each (AGL-768): a Firestore read per invite is fine, one per
117
+ * recipient in a usage-email batch is not.
118
+ *
119
+ * Reads through the Admin SDK, which bypasses the staff-only rules on the
120
+ * collection — the send path runs as the server, not as a signed-in user.
121
+ *
122
+ * A design that places email blocks costs one more read per block, from the
123
+ * platform marketing site, made here with the template so a batch pays it
124
+ * once too (AGL-3318). Whether a recipient's copy expands them is decided per
125
+ * send, by {@link renderLoadedSystemEmail}.
126
+ */ export async function loadSystemEmail(templateKey) {
127
+ const definition = getSystemEmailTemplate(templateKey);
128
+ if (!definition) return null;
129
+ // A Firebase- or Stripe-delivered email is sent by that service from its
130
+ // own templates, so rendering one here would produce output nothing ever
131
+ // sends (AGL-767).
132
+ if (definition.deliveredBy !== 'resend') return null;
133
+ try {
134
+ var _templateSnapshot_get, _templateSnapshot_get1;
135
+ const firestore = firebaseAdmin.app().firestore();
136
+ const templateRef = firestore.collection(SYSTEM_EMAIL_COLLECTION).doc(templateKey);
137
+ const templateSnapshot = await templateRef.get();
138
+ if (!templateSnapshot.exists) return catalogDefault(definition);
139
+ const versionId = templateSnapshot.get('versionId');
140
+ // Cleared by "reset to default", which nulls the pointer rather than
141
+ // deleting the document so the audit trail survives.
142
+ if (!versionId) return catalogDefault(definition);
143
+ const versionSnapshot = await templateRef.collection('versions').doc(String(versionId)).get();
144
+ // BOTH stored forms (AGL-1223). The email besigner compresses like every
145
+ // other besigner document, and versions written before it did are still
146
+ // plain maps — `decodeStoredNodes` returns those unchanged.
147
+ //
148
+ // Reading raw is the failure the guard below cannot catch: over a
149
+ // `Buffer`, `Object.keys` counts BYTE INDICES, so the emptiness test
150
+ // passes and a staff-authored email renders empty rather than falling
151
+ // back to its built-in copy.
152
+ const nodes = decodeStoredNodes(versionSnapshot.get('nodes'));
153
+ if (!nodes || !Object.keys(nodes).length) return catalogDefault(definition);
154
+ const components = await loadPlatformEmailBlocks(firestore, templateKey, nodes);
155
+ return _extends({
156
+ definition,
157
+ nodes,
158
+ subjectTemplate: String((_templateSnapshot_get = templateSnapshot.get('subject')) != null ? _templateSnapshot_get : '') || definition.defaultSubject,
159
+ preheaderTemplate: String((_templateSnapshot_get1 = templateSnapshot.get('preheader')) != null ? _templateSnapshot_get1 : ''),
160
+ source: 'designed'
161
+ }, components && {
162
+ components
163
+ });
164
+ } catch (error) {
165
+ // Never let a template problem block the send, or strip it bare: the
166
+ // recipient gets the built-in copy, in the same header and footer.
167
+ console.error(`system email template ${templateKey} failed to load; sending its built-in copy`, error);
168
+ return catalogDefault(definition);
169
+ }
170
+ }
171
+ /**
172
+ * Renders a loaded email for one recipient's merge values (AGL-768). No
173
+ * Firestore access — call {@link loadSystemEmail} once, then this per
174
+ * recipient. `null` only if the renderer produced no document at all.
175
+ *
176
+ * Which header and footer it wears is decided here, per send, because one
177
+ * batch-loaded design goes to recipients of different brands:
178
+ *
179
+ * - A send under the platform's own brand of a design whose email blocks the
180
+ * load read draws those blocks (AGL-3318), and nothing else: they ARE its
181
+ * header and footer, and a second one around them would draw both.
182
+ * - Every other send is drawn inside {@link buildSystemEmailChrome}'s chrome
183
+ * (AGL-3322): the built-in copy, which places no blocks; a design sent to a
184
+ * white-label org's people, whose blocks stay unexpanded and draw nothing,
185
+ * since they are the platform's; and a design on a deployment that names no
186
+ * marketing site, or whose blocks could not be read. The chrome is in the
187
+ * brand of the send — the org's email logo rides in its header, so a
188
+ * white-label mail carries exactly one logo.
189
+ */ export function renderLoadedSystemEmail(loaded, merge = {}, options = {}) {
190
+ var _rendered_text;
191
+ const merged = _extends({}, PLATFORM_BRAND_MERGE_TOKENS, merge);
192
+ const blocks = drawsPlatformBlocks(loaded, merged, options);
193
+ const rendered = renderEmailHtml(_extends({
194
+ nodes: blocks ? composeReusableComponentNodes(loaded.nodes, loaded.components) : loaded.nodes,
195
+ // Besigner maps are rooted at '_@_', not renderEmailHtml's default
196
+ // 'root' — without this a designed template rendered empty and the send
197
+ // fell back to built-in copy, so designing did nothing (AGL-765).
198
+ rootId: EMAIL_NODE_ROOT_ID,
199
+ subject: substituteMergeTokens(loaded.subjectTemplate, merged),
200
+ preheader: substituteMergeTokens(loaded.preheaderTemplate, merged),
201
+ merge: merged,
202
+ // The same policy the console's own preview of these nodes applies —
203
+ // `sanitizeCustomHtml` in the email plugin delegates to this exact
204
+ // function, so what staff review and what the recipient receives are one
205
+ // function of one string rather than two that have to be kept in step.
206
+ sanitize: sanitizeAuthorHtml,
207
+ // Without this a staff-picked image resolves to a site-relative CDN path,
208
+ // which is a broken-image box in the recipient's inbox (AGL-1224). The
209
+ // chrome's logo resolves against it too.
210
+ mediaOrigin: CONSOLE_ORIGIN
211
+ }, blocks ? {} : {
212
+ chrome: buildSystemEmailChrome({
213
+ definition: loaded.definition,
214
+ merged,
215
+ brandLogoUrl: options.brandLogoUrl,
216
+ brandHomeUrl: options.brandHomeUrl
217
+ })
218
+ }));
219
+ if (!(rendered == null ? void 0 : rendered.html)) return null;
220
+ return {
221
+ subject: blankUnresolvedTokens(substituteMergeTokens(loaded.subjectTemplate, merged)),
222
+ html: blankUnresolvedTokens(rendered.html),
223
+ text: blankUnresolvedTokens((_rendered_text = rendered.text) != null ? _rendered_text : ''),
224
+ source: loaded.source
225
+ };
226
+ }
227
+ /**
228
+ * Renders the system email a key sends to one recipient (AGL-750): the
229
+ * published staff design, or the catalog's built-in copy (AGL-3322), in the
230
+ * header and footer of the brand it is sent under.
231
+ *
232
+ * **`null` only for a key that is unknown or not Resend-delivered**, which
233
+ * has nothing here to render. No template document, no published version, an
234
+ * empty node map and a Firestore failure all render the built-in copy — the
235
+ * same copy the editor seeds a first design with — so a missing, half-saved
236
+ * or broken template can never mean a customer receives no email, or a bare
237
+ * one. Every caller still keeps its own hard-coded copy behind this, as the
238
+ * last resort for a render that produced nothing.
239
+ *
240
+ * A single-recipient convenience over {@link loadSystemEmail} +
241
+ * {@link renderLoadedSystemEmail}; a batch should call those two directly so
242
+ * it reads the template once.
243
+ */ export async function renderSystemEmail(templateKey, merge = {}, options = {}) {
244
+ const loaded = await loadSystemEmail(templateKey);
245
+ return loaded ? renderLoadedSystemEmail(loaded, merge, options) : null;
246
+ }
247
+ /**
248
+ * The email a template sends right now, for the staff test-send endpoint
249
+ * (AGL-766): exactly what a real send of it renders — the published design,
250
+ * or the built-in copy, with the same header and footer — so a test shows
251
+ * what recipients receive. `null` for an unknown or non-Resend key.
252
+ */ export async function renderEffectiveSystemEmail(templateKey, merge = {}, options = {}) {
253
+ return renderSystemEmail(templateKey, merge, options);
254
+ }
255
+ /** See {@link SystemEmailBrand}. */ export function systemEmailBrand(org) {
256
+ if (!org) return {
257
+ merge: {},
258
+ options: {}
259
+ };
260
+ const branding = resolveBrandingProfile(org);
261
+ const orgName = typeof org['name'] === 'string' ? org['name'].trim() : '';
262
+ return _extends({}, orgName ? {
263
+ orgName
264
+ } : {}, {
265
+ merge: brandMergeTokens(branding),
266
+ options: {
267
+ brandLogoUrl: branding.emailLogoUrl,
268
+ brandHomeUrl: branding.homeUrl
269
+ },
270
+ fromName: branding.fromName
271
+ });
272
+ }
273
+ /**
274
+ * {@link systemEmailBrand} for an org read by id, for a sender that holds
275
+ * only the id. A failed or missing read is the platform's brand: the email
276
+ * still goes, and a white-label org's people see the platform's chrome on
277
+ * one message rather than no message.
278
+ */ export async function orgSystemEmailBrand(orgId) {
279
+ if (!orgId) return systemEmailBrand(null);
280
+ try {
281
+ var _snapshot_data;
282
+ const snapshot = await firebaseAdmin.app().firestore().collection('orgs').doc(orgId).get();
283
+ return systemEmailBrand(snapshot.exists ? (_snapshot_data = snapshot.data()) != null ? _snapshot_data : null : null);
284
+ } catch (error) {
285
+ console.error(`system email brand for org ${orgId} failed to load`, error);
286
+ return systemEmailBrand(null);
287
+ }
288
+ }
289
+ /**
290
+ * The subject, text and HTML to send, with the caller's own copy as the
291
+ * last resort for a render that produced nothing: the shape every sender of
292
+ * a system email repeats, written once.
293
+ */ export function systemEmailContent(rendered, fallback) {
294
+ return _extends({
295
+ subject: (rendered == null ? void 0 : rendered.subject) || fallback.subject,
296
+ text: (rendered == null ? void 0 : rendered.text) || fallback.text
297
+ }, (rendered == null ? void 0 : rendered.html) ? {
298
+ html: rendered.html
299
+ } : {});
300
+ }
301
+ /**
302
+ * Renders a key for one recipient in a brand and returns what to send
303
+ * (AGL-3367): {@link renderSystemEmail} and {@link systemEmailContent} in
304
+ * one call, for the senders with one message to build. Never throws; a
305
+ * render that fails sends the fallback copy, which is what it sent before.
306
+ */ export async function renderSystemEmailContent(templateKey, merge, brand, fallback) {
307
+ const rendered = await renderSystemEmail(templateKey, _extends({}, brand.merge, merge), brand.options).catch((error)=>{
308
+ console.error(`system email ${templateKey} failed to render`, error);
309
+ return null;
310
+ });
311
+ return systemEmailContent(rendered, fallback);
312
+ }
313
+ export default renderSystemEmail;
314
+
315
+ //# sourceMappingURL=render-system-email.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/render-system-email.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\nimport {\n EMAIL_NODE_ROOT_ID,\n SYSTEM_EMAIL_COLLECTION,\n buildDefaultEmailNodeMap,\n getSystemEmailTemplate,\n renderEmailHtml,\n substituteMergeTokens,\n type SystemEmailTemplateDefinition,\n} from '@aglyn/shared-util-email'\nimport { firebaseAdmin } from './firebase-admin'\nimport { platformMarketingHostId } from './platform-marketing-consent'\nimport {\n brandMergeTokens,\n collectReferencedComponentIds,\n composeReusableComponentNodes,\n decodeStoredNodes,\n resolveBrandingProfile,\n sanitizeAuthorHtml,\n type ReusableComponentTree,\n} from '@aglyn/aglyn/server'\nimport {\n hostComponentReader,\n loadReferencedComponents,\n type ComponentStoreLike,\n} from '@aglyn/aglyn/app-utils/load-referenced-components'\nimport {\n PLATFORM_BRAND_MERGE_TOKENS,\n buildSystemEmailChrome,\n isPlatformBrandedSend,\n type SystemEmailBrandOptions,\n} from '@aglyn/aglyn/app-utils/system-email-chrome'\n\n// Defined beside the chrome they decide, and re-exported for the callers and\n// specs that reach them through this module.\nexport { isPlatformBrandedSend }\nexport type { SystemEmailBrandOptions }\n\n/**\n * Blanks any `{{token}}` the caller did not supply.\n *\n * `substituteMergeTokens` leaves unknown tokens untouched, which is right for\n * campaigns (an author wants to see the tag they mistyped) but wrong here —\n * a system email goes to a customer, and \"You've been invited to\n * {{org.name}}\" is worse than a gap. Applied only in this resolver so\n * campaign behaviour is unchanged.\n */\nfunction blankUnresolvedTokens(value: string): string {\n return value.replace(/\\{\\{[^}]*\\}\\}/g, '')\n}\n\n/**\n * Origin a picked image in a system email is fetched from (AGL-1224).\n *\n * A system email is staff-designed and its media lives in the platform\n * library, which the CONSOLE's `/api/media/cdn` route serves — the tenant app\n * mounts the same route, but a recipient of an org invite has no site to\n * resolve against. Same expression `app/layout.tsx` uses for the console's\n * own canonical URL, so the two cannot drift per deploy.\n */\nconst CONSOLE_ORIGIN =\n process.env.NEXT_PUBLIC_CONSOLE_URL ?? 'https://app.aglyn.com'\n\n/**\n * Which copy a system email carries: a design staff published, or the\n * catalog's built-in copy, which is what every key without a usable design\n * sends (AGL-3322).\n */\nexport type SystemEmailSource = 'designed' | 'default'\n\nexport interface RenderedSystemEmail {\n subject: string\n html: string\n text: string\n source: SystemEmailSource\n}\n\n/**\n * A system email loaded once, ready to render for any number of recipients\n * without touching Firestore again (AGL-768): the published staff design, or\n * the catalog's built-in copy when there is none.\n */\nexport interface LoadedSystemEmail {\n definition: SystemEmailTemplateDefinition\n /** The design as stored, each email block still a placement; or the built-in copy's node map. */\n nodes: Record<string, unknown>\n subjectTemplate: string\n preheaderTemplate: string\n source: SystemEmailSource\n /**\n * The published definitions of the email blocks `nodes` places, keyed by\n * id, read from the platform marketing site ONCE with the template\n * (AGL-3318), so a batch composes every recipient's copy without another\n * read. Absent when the design places none, when the deployment names no\n * marketing site, and when the read failed; each placement then renders as\n * nothing.\n */\n components?: Record<string, ReusableComponentTree>\n}\n\n/**\n * The email blocks a platform email places, read from the site that owns\n * them (AGL-3318), or `undefined` when there is nothing to read or the read\n * failed.\n *\n * WHICH SITE. A block is a reusable component, and a component belongs to a\n * site; a platform email belongs to none. The header and footer Aglyn's own\n * mail wears are the ones on its marketing site, which the deployment names\n * in `PLATFORM_MARKETING_HOST_ID`, the setting product-email consent already\n * reads. An install that names none reads nothing, and a block placed in its\n * system emails renders as nothing.\n *\n * NEVER A REASON NOT TO SEND. A site's own email fails its whole load when a\n * component read fails, and falls back to its built-in copy. Here the copy is\n * staff's design and the blocks are another site's chrome, so a failed read\n * costs the blocks and nothing else: it is logged, and the design renders\n * inside the coded header and footer instead (see\n * {@link renderLoadedSystemEmail}) rather than being traded for the built-in\n * copy. A password reset whose header could not be read still carries its\n * link.\n */\nasync function loadPlatformEmailBlocks(\n firestore: ComponentStoreLike,\n templateKey: string,\n nodes: Record<string, unknown>,\n): Promise<Record<string, ReusableComponentTree> | undefined> {\n // A design that places nothing costs nothing: no setting read, no read.\n if (!collectReferencedComponentIds(nodes as never).size) return undefined\n const hostId = platformMarketingHostId()\n if (!hostId) return undefined\n try {\n return await loadReferencedComponents(\n nodes,\n hostComponentReader(firestore, hostId),\n {\n onSkipped: (skipped) =>\n console.warn(\n JSON.stringify({\n tag: 'AGL-3318:platform-email-blocks-skipped',\n templateKey,\n hostId,\n skipped,\n }),\n ),\n },\n )\n } catch (error) {\n console.error(\n `system email template ${templateKey}: its email blocks failed to load from ${hostId}`,\n error,\n )\n return undefined\n }\n}\n\n/**\n * Whether one send draws the design's email blocks: a send under the\n * platform's own brand (see {@link isPlatformBrandedSend}) of a design whose\n * blocks the load could read. Every other send renders the stored nodes, each\n * block a placement that draws nothing, inside the coded chrome.\n */\nfunction drawsPlatformBlocks(\n loaded: LoadedSystemEmail,\n merged: Readonly<Record<string, string>>,\n options: SystemEmailBrandOptions,\n): loaded is LoadedSystemEmail & {\n components: Record<string, ReusableComponentTree>\n} {\n return (\n Boolean(loaded.components && Object.keys(loaded.components).length) &&\n isPlatformBrandedSend(merged, options)\n )\n}\n\n/**\n * A key's built-in copy as a loaded email (AGL-3322): the node map the editor\n * seeds a first design with, and the catalog subject. What a key sends until\n * staff publish a design, and whenever the published one cannot be read.\n */\nfunction catalogDefault(\n definition: SystemEmailTemplateDefinition,\n): LoadedSystemEmail {\n return {\n definition,\n nodes: buildDefaultEmailNodeMap(definition),\n subjectTemplate: definition.defaultSubject,\n preheaderTemplate: '',\n source: 'default',\n }\n}\n\n/**\n * Loads what a key sends — ONE Firestore read — ready to render per\n * recipient: the published staff design, or the catalog's built-in copy\n * (AGL-3322) when there is none to use (no document, no published version,\n * an empty node map, or a read failure).\n *\n * `null` only for a key that is unknown or not Resend-delivered, which has\n * nothing here to render. Split out from {@link renderSystemEmail} so a batch\n * send resolves the template once and renders it per recipient, rather than\n * one read each (AGL-768): a Firestore read per invite is fine, one per\n * recipient in a usage-email batch is not.\n *\n * Reads through the Admin SDK, which bypasses the staff-only rules on the\n * collection — the send path runs as the server, not as a signed-in user.\n *\n * A design that places email blocks costs one more read per block, from the\n * platform marketing site, made here with the template so a batch pays it\n * once too (AGL-3318). Whether a recipient's copy expands them is decided per\n * send, by {@link renderLoadedSystemEmail}.\n */\nexport async function loadSystemEmail(\n templateKey: string,\n): Promise<LoadedSystemEmail | null> {\n const definition = getSystemEmailTemplate(templateKey)\n if (!definition) return null\n // A Firebase- or Stripe-delivered email is sent by that service from its\n // own templates, so rendering one here would produce output nothing ever\n // sends (AGL-767).\n if (definition.deliveredBy !== 'resend') return null\n\n try {\n const firestore = firebaseAdmin.app().firestore()\n const templateRef = firestore\n .collection(SYSTEM_EMAIL_COLLECTION)\n .doc(templateKey)\n const templateSnapshot = await templateRef.get()\n if (!templateSnapshot.exists) return catalogDefault(definition)\n\n const versionId = templateSnapshot.get('versionId')\n // Cleared by \"reset to default\", which nulls the pointer rather than\n // deleting the document so the audit trail survives.\n if (!versionId) return catalogDefault(definition)\n\n const versionSnapshot = await templateRef\n .collection('versions')\n .doc(String(versionId))\n .get()\n // BOTH stored forms (AGL-1223). The email besigner compresses like every\n // other besigner document, and versions written before it did are still\n // plain maps — `decodeStoredNodes` returns those unchanged.\n //\n // Reading raw is the failure the guard below cannot catch: over a\n // `Buffer`, `Object.keys` counts BYTE INDICES, so the emptiness test\n // passes and a staff-authored email renders empty rather than falling\n // back to its built-in copy.\n const nodes = decodeStoredNodes<Record<string, unknown>>(\n versionSnapshot.get('nodes'),\n )\n if (!nodes || !Object.keys(nodes).length) return catalogDefault(definition)\n\n const components = await loadPlatformEmailBlocks(\n firestore,\n templateKey,\n nodes,\n )\n return {\n definition,\n nodes,\n subjectTemplate:\n String(templateSnapshot.get('subject') ?? '') ||\n definition.defaultSubject,\n preheaderTemplate: String(templateSnapshot.get('preheader') ?? ''),\n source: 'designed',\n ...(components && { components }),\n }\n } catch (error) {\n // Never let a template problem block the send, or strip it bare: the\n // recipient gets the built-in copy, in the same header and footer.\n console.error(\n `system email template ${templateKey} failed to load; sending its built-in copy`,\n error,\n )\n return catalogDefault(definition)\n }\n}\n\n/**\n * Renders a loaded email for one recipient's merge values (AGL-768). No\n * Firestore access — call {@link loadSystemEmail} once, then this per\n * recipient. `null` only if the renderer produced no document at all.\n *\n * Which header and footer it wears is decided here, per send, because one\n * batch-loaded design goes to recipients of different brands:\n *\n * - A send under the platform's own brand of a design whose email blocks the\n * load read draws those blocks (AGL-3318), and nothing else: they ARE its\n * header and footer, and a second one around them would draw both.\n * - Every other send is drawn inside {@link buildSystemEmailChrome}'s chrome\n * (AGL-3322): the built-in copy, which places no blocks; a design sent to a\n * white-label org's people, whose blocks stay unexpanded and draw nothing,\n * since they are the platform's; and a design on a deployment that names no\n * marketing site, or whose blocks could not be read. The chrome is in the\n * brand of the send — the org's email logo rides in its header, so a\n * white-label mail carries exactly one logo.\n */\nexport function renderLoadedSystemEmail(\n loaded: LoadedSystemEmail,\n merge: Record<string, string> = {},\n options: SystemEmailBrandOptions = {},\n): RenderedSystemEmail | null {\n const merged = { ...PLATFORM_BRAND_MERGE_TOKENS, ...merge }\n const blocks = drawsPlatformBlocks(loaded, merged, options)\n const rendered = renderEmailHtml({\n nodes: (blocks\n ? composeReusableComponentNodes(loaded.nodes as never, loaded.components)\n : loaded.nodes) as never,\n // Besigner maps are rooted at '_@_', not renderEmailHtml's default\n // 'root' — without this a designed template rendered empty and the send\n // fell back to built-in copy, so designing did nothing (AGL-765).\n rootId: EMAIL_NODE_ROOT_ID,\n subject: substituteMergeTokens(loaded.subjectTemplate, merged),\n preheader: substituteMergeTokens(loaded.preheaderTemplate, merged),\n merge: merged,\n // The same policy the console's own preview of these nodes applies —\n // `sanitizeCustomHtml` in the email plugin delegates to this exact\n // function, so what staff review and what the recipient receives are one\n // function of one string rather than two that have to be kept in step.\n sanitize: sanitizeAuthorHtml,\n // Without this a staff-picked image resolves to a site-relative CDN path,\n // which is a broken-image box in the recipient's inbox (AGL-1224). The\n // chrome's logo resolves against it too.\n mediaOrigin: CONSOLE_ORIGIN,\n // No `brandLogoUrl`: the org's email logo (AGL-2139) is the chrome\n // header's logo whenever there is one to draw, and a send that draws the\n // platform's blocks is by definition one that carries none.\n ...(blocks\n ? {}\n : {\n chrome: buildSystemEmailChrome({\n definition: loaded.definition,\n merged,\n brandLogoUrl: options.brandLogoUrl,\n brandHomeUrl: options.brandHomeUrl,\n }),\n }),\n })\n if (!rendered?.html) return null\n return {\n subject: blankUnresolvedTokens(\n substituteMergeTokens(loaded.subjectTemplate, merged),\n ),\n html: blankUnresolvedTokens(rendered.html),\n text: blankUnresolvedTokens(rendered.text ?? ''),\n source: loaded.source,\n }\n}\n\n/**\n * Renders the system email a key sends to one recipient (AGL-750): the\n * published staff design, or the catalog's built-in copy (AGL-3322), in the\n * header and footer of the brand it is sent under.\n *\n * **`null` only for a key that is unknown or not Resend-delivered**, which\n * has nothing here to render. No template document, no published version, an\n * empty node map and a Firestore failure all render the built-in copy — the\n * same copy the editor seeds a first design with — so a missing, half-saved\n * or broken template can never mean a customer receives no email, or a bare\n * one. Every caller still keeps its own hard-coded copy behind this, as the\n * last resort for a render that produced nothing.\n *\n * A single-recipient convenience over {@link loadSystemEmail} +\n * {@link renderLoadedSystemEmail}; a batch should call those two directly so\n * it reads the template once.\n */\nexport async function renderSystemEmail(\n templateKey: string,\n merge: Record<string, string> = {},\n options: SystemEmailBrandOptions = {},\n): Promise<RenderedSystemEmail | null> {\n const loaded = await loadSystemEmail(templateKey)\n return loaded ? renderLoadedSystemEmail(loaded, merge, options) : null\n}\n\n/**\n * The email a template sends right now, for the staff test-send endpoint\n * (AGL-766): exactly what a real send of it renders — the published design,\n * or the built-in copy, with the same header and footer — so a test shows\n * what recipients receive. `null` for an unknown or non-Resend key.\n */\nexport async function renderEffectiveSystemEmail(\n templateKey: string,\n merge: Record<string, string> = {},\n options: SystemEmailBrandOptions = {},\n): Promise<RenderedSystemEmail | null> {\n return renderSystemEmail(templateKey, merge, options)\n}\n\n/**\n * The brand one system email is sent under (AGL-3367): the merge tokens, the\n * chrome options and the sender name, from one place.\n *\n * `null` is the platform's own brand, and it is the answer for everything\n * the platform says on its own behalf: a staff alert, a legal receipt, an\n * enforcement notice. A workspace-context email passes the workspace's org\n * document, and `resolveBrandingProfile` decides from there: a white-label\n * org gets its own name, logo, home and support in the header and footer,\n * and every other org resolves to the platform profile, so the same call is\n * right for both.\n */\nexport interface SystemEmailBrand {\n merge: Record<string, string>\n options: SystemEmailBrandOptions\n /** The display name to send under; absent sends under the platform's. */\n fromName?: string\n /** The org's own name, for the `{{org.name}}` its copy may use. */\n orgName?: string\n}\n\n/** See {@link SystemEmailBrand}. */\nexport function systemEmailBrand(\n org: Readonly<Record<string, unknown>> | null | undefined,\n): SystemEmailBrand {\n if (!org) return { merge: {}, options: {} }\n const branding = resolveBrandingProfile(org as never)\n const orgName = typeof org['name'] === 'string' ? org['name'].trim() : ''\n return {\n ...(orgName ? { orgName } : {}),\n merge: brandMergeTokens(branding),\n options: {\n brandLogoUrl: branding.emailLogoUrl,\n brandHomeUrl: branding.homeUrl,\n },\n fromName: branding.fromName,\n }\n}\n\n/**\n * {@link systemEmailBrand} for an org read by id, for a sender that holds\n * only the id. A failed or missing read is the platform's brand: the email\n * still goes, and a white-label org's people see the platform's chrome on\n * one message rather than no message.\n */\nexport async function orgSystemEmailBrand(\n orgId: string | null | undefined,\n): Promise<SystemEmailBrand> {\n if (!orgId) return systemEmailBrand(null)\n try {\n const snapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('orgs')\n .doc(orgId)\n .get()\n return systemEmailBrand(snapshot.exists ? (snapshot.data() ?? null) : null)\n } catch (error) {\n console.error(`system email brand for org ${orgId} failed to load`, error)\n return systemEmailBrand(null)\n }\n}\n\n/** What a send takes from a rendered system email. */\nexport interface SystemEmailContent {\n subject: string\n text: string\n html?: string\n}\n\n/**\n * The subject, text and HTML to send, with the caller's own copy as the\n * last resort for a render that produced nothing: the shape every sender of\n * a system email repeats, written once.\n */\nexport function systemEmailContent(\n rendered: RenderedSystemEmail | null,\n fallback: { subject: string; text: string },\n): SystemEmailContent {\n return {\n subject: rendered?.subject || fallback.subject,\n text: rendered?.text || fallback.text,\n ...(rendered?.html ? { html: rendered.html } : {}),\n }\n}\n\n/**\n * Renders a key for one recipient in a brand and returns what to send\n * (AGL-3367): {@link renderSystemEmail} and {@link systemEmailContent} in\n * one call, for the senders with one message to build. Never throws; a\n * render that fails sends the fallback copy, which is what it sent before.\n */\nexport async function renderSystemEmailContent(\n templateKey: string,\n merge: Record<string, string>,\n brand: SystemEmailBrand,\n fallback: { subject: string; text: string },\n): Promise<SystemEmailContent> {\n const rendered = await renderSystemEmail(\n templateKey,\n { ...brand.merge, ...merge },\n brand.options,\n ).catch((error) => {\n console.error(`system email ${templateKey} failed to render`, error)\n return null\n })\n return systemEmailContent(rendered, fallback)\n}\n\nexport default renderSystemEmail\n"],"names":["process","EMAIL_NODE_ROOT_ID","SYSTEM_EMAIL_COLLECTION","buildDefaultEmailNodeMap","getSystemEmailTemplate","renderEmailHtml","substituteMergeTokens","firebaseAdmin","platformMarketingHostId","brandMergeTokens","collectReferencedComponentIds","composeReusableComponentNodes","decodeStoredNodes","resolveBrandingProfile","sanitizeAuthorHtml","hostComponentReader","loadReferencedComponents","PLATFORM_BRAND_MERGE_TOKENS","buildSystemEmailChrome","isPlatformBrandedSend","blankUnresolvedTokens","value","replace","CONSOLE_ORIGIN","env","NEXT_PUBLIC_CONSOLE_URL","loadPlatformEmailBlocks","firestore","templateKey","nodes","size","undefined","hostId","onSkipped","skipped","console","warn","JSON","stringify","tag","error","drawsPlatformBlocks","loaded","merged","options","Boolean","components","Object","keys","length","catalogDefault","definition","subjectTemplate","defaultSubject","preheaderTemplate","source","loadSystemEmail","deliveredBy","templateSnapshot","app","templateRef","collection","doc","get","exists","versionId","versionSnapshot","String","renderLoadedSystemEmail","merge","rendered","blocks","rootId","subject","preheader","sanitize","mediaOrigin","chrome","brandLogoUrl","brandHomeUrl","html","text","renderSystemEmail","renderEffectiveSystemEmail","systemEmailBrand","org","branding","orgName","trim","emailLogoUrl","homeUrl","fromName","orgSystemEmailBrand","orgId","snapshot","data","systemEmailContent","fallback","renderSystemEmailContent","brand","catch"],"mappings":";IA6EEA;AA7EF;;;;;;;;;;;;;;;CAeC,GAED,SACEC,kBAAkB,EAClBC,uBAAuB,EACvBC,wBAAwB,EACxBC,sBAAsB,EACtBC,eAAe,EACfC,qBAAqB,QAEhB,2BAA0B;AACjC,SAASC,aAAa,QAAQ,sBAAkB;AAChD,SAASC,uBAAuB,QAAQ,kCAA8B;AACtE,SACEC,gBAAgB,EAChBC,6BAA6B,EAC7BC,6BAA6B,EAC7BC,iBAAiB,EACjBC,sBAAsB,EACtBC,kBAAkB,QAEb,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,wBAAwB,QAEnB,oDAAmD;AAC1D,SACEC,2BAA2B,EAC3BC,sBAAsB,EACtBC,qBAAqB,QAEhB,6CAA4C;AAEnD,6EAA6E;AAC7E,6CAA6C;AAC7C,SAASA,qBAAqB,GAAE;AAGhC;;;;;;;;CAQC,GACD,SAASC,sBAAsBC,KAAa;IAC1C,O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CAAAA,4BAAAA,SAAUU,IAAI,IAAG;QAAEA,MAAMV,SAASU,IAAI;IAAC,IAAI,CAAC;AAEpD;AAEA;;;;;CAKC,GACD,OAAO,eAAekB,yBACpBtE,WAAmB,EACnByC,KAA6B,EAC7B8B,KAAuB,EACvBF,QAA2C;IAE3C,MAAM3B,WAAW,MAAMY,kBACrBtD,aACA,aAAKuE,MAAM9B,KAAK,EAAKA,QACrB8B,MAAMvD,OAAO,EACbwD,KAAK,CAAC,CAAC5D;QACPL,QAAQK,KAAK,CAAC,CAAC,aAAa,EAAEZ,YAAY,iBAAiB,CAAC,EAAEY;QAC9D,OAAO;IACT;IACA,OAAOwD,mBAAmB1B,UAAU2B;AACtC;AAEA,eAAef,kBAAiB"}
@@ -31,7 +31,8 @@ import { type SendEmailResult } from '@aglyn/shared-util-email';
31
31
  * Platform email metering is loaded lazily and only after a send, so that
32
32
  * importing this module — which every unit test of the meter does — never
33
33
  * pulls the Firestore-backed meter, and with it the admin app, into a test
34
- * that only wanted to count credits.
34
+ * that only wanted to count credits. The system-email renderer, which reads
35
+ * its template through the same admin app, is loaded the same way.
35
36
  */
36
37
  export declare function sendStaffAlertEmail(input: {
37
38
  subject: string;
@@ -1,3 +1,4 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
1
2
  /**
2
3
  * @license
3
4
  * Copyright 2026 Aglyn LLC
@@ -30,7 +31,8 @@
30
31
  * Platform email metering is loaded lazily and only after a send, so that
31
32
  * importing this module — which every unit test of the meter does — never
32
33
  * pulls the Firestore-backed meter, and with it the admin app, into a test
33
- * that only wanted to count credits.
34
+ * that only wanted to count credits. The system-email renderer, which reads
35
+ * its template through the same admin app, is loaded the same way.
34
36
  */ export async function sendStaffAlertEmail(input) {
35
37
  var _process_env_STAFF_ALERT_EMAIL;
36
38
  const to = String((_process_env_STAFF_ALERT_EMAIL = process.env.STAFF_ALERT_EMAIL) != null ? _process_env_STAFF_ALERT_EMAIL : '').trim();
@@ -39,12 +41,21 @@
39
41
  reason: 'unconfigured'
40
42
  };
41
43
  try {
42
- const result = await sendEmail({
43
- to,
44
+ // In the platform's header and footer, as the `staff-alert` system email
45
+ // (AGL-3367). Loaded lazily for the reason the meter below is.
46
+ const { renderSystemEmailContent, systemEmailBrand } = await import("./render-system-email.js");
47
+ const content = await renderSystemEmailContent('staff-alert', {
48
+ 'alert.subject': input.subject,
49
+ 'alert.body': input.text
50
+ }, systemEmailBrand(null), {
44
51
  subject: input.subject,
45
- text: input.text,
46
- context: input.context
52
+ text: input.text
47
53
  });
54
+ const result = await sendEmail(_extends({
55
+ to
56
+ }, content, {
57
+ context: input.context
58
+ }));
48
59
  if (result.sent) {
49
60
  // Platform-scoped (AGL-1438): our own alert is our own cost.
50
61
  const { meterPlatformEmail } = await import("./email-metering.js");
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/staff-alert-email.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\nimport { sendEmail, type SendEmailResult } from '@aglyn/shared-util-email'\n\n/**\n * A staff alert by email, from LIBRARY code (AGL-2925).\n *\n * `STAFF_ALERT_EMAIL` is the one inbox every subsystem's alert lands in —\n * the console's `emailStaffAlert` in `apps/console/app/api/_lib/\n * usage-alert-email.ts` sends the cron's alerts there. A library cannot\n * call that, because a library cannot import from an app. So a library's\n * own alert — the AI meter's platform-wide free-spend ceiling is one —\n * sends through this, to the same address, with the same posture: unset is\n * the ordinary answer outside production and reports `unconfigured`, and\n * nothing here throws, because the mail is a courtesy and the refusal it\n * announces is the control.\n *\n * Platform email metering is loaded lazily and only after a send, so that\n * importing this module — which every unit test of the meter does — never\n * pulls the Firestore-backed meter, and with it the admin app, into a test\n * that only wanted to count credits.\n */\nexport async function sendStaffAlertEmail(input: {\n subject: string\n text: string\n /** Resend tag / log label. */\n context: string\n}): Promise<SendEmailResult> {\n const to = String(process.env.STAFF_ALERT_EMAIL ?? '').trim()\n if (!to.includes('@')) return { sent: false, reason: 'unconfigured' }\n try {\n const result = await sendEmail({\n to,\n subject: input.subject,\n text: input.text,\n context: input.context,\n })\n if (result.sent) {\n // Platform-scoped (AGL-1438): our own alert is our own cost.\n const { meterPlatformEmail } = await import('./email-metering')\n await meterPlatformEmail().catch(() => undefined)\n }\n return result\n } catch (error) {\n console.error('[staff-alert-email] send failed', error)\n return { sent: false, reason: 'network' }\n }\n}\n"],"names":["sendEmail","sendStaffAlertEmail","input","process","to","String","env","STAFF_ALERT_EMAIL","trim","includes","sent","reason","result","subject","text","context","meterPlatformEmail","catch","undefined","error","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,SAAS,QAA8B,2BAA0B;AAE1E;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,eAAeC,oBAAoBC,KAKzC;QACmBC;IAAlB,MAAMC,KAAKC,QAAOF,iCAAAA,QAAQG,GAAG,CAACC,iBAAiB,YAA7BJ,iCAAiC,IAAIK,IAAI;IAC3D,IAAI,CAACJ,GAAGK,QAAQ,CAAC,MAAM,OAAO;QAAEC,MAAM;QAAOC,QAAQ;IAAe;IACpE,IAAI;QACF,MAAMC,SAAS,MAAMZ,UAAU;YAC7BI;YACAS,SAASX,MAAMW,OAAO;YACtBC,MAAMZ,MAAMY,IAAI;YAChBC,SAASb,MAAMa,OAAO;QACxB;QACA,IAAIH,OAAOF,IAAI,EAAE;YACf,6DAA6D;YAC7D,MAAM,EAAEM,kBAAkB,EAAE,GAAG,MAAM,MAAM,CAAC;YAC5C,MAAMA,qBAAqBC,KAAK,CAAC,IAAMC;QACzC;QACA,OAAON;IACT,EAAE,OAAOO,OAAO;QACdC,QAAQD,KAAK,CAAC,mCAAmCA;QACjD,OAAO;YAAET,MAAM;YAAOC,QAAQ;QAAU;IAC1C;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/staff-alert-email.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\nimport { sendEmail, type SendEmailResult } from '@aglyn/shared-util-email'\n\n/**\n * A staff alert by email, from LIBRARY code (AGL-2925).\n *\n * `STAFF_ALERT_EMAIL` is the one inbox every subsystem's alert lands in —\n * the console's `emailStaffAlert` in `apps/console/app/api/_lib/\n * usage-alert-email.ts` sends the cron's alerts there. A library cannot\n * call that, because a library cannot import from an app. So a library's\n * own alert — the AI meter's platform-wide free-spend ceiling is one —\n * sends through this, to the same address, with the same posture: unset is\n * the ordinary answer outside production and reports `unconfigured`, and\n * nothing here throws, because the mail is a courtesy and the refusal it\n * announces is the control.\n *\n * Platform email metering is loaded lazily and only after a send, so that\n * importing this module — which every unit test of the meter does — never\n * pulls the Firestore-backed meter, and with it the admin app, into a test\n * that only wanted to count credits. The system-email renderer, which reads\n * its template through the same admin app, is loaded the same way.\n */\nexport async function sendStaffAlertEmail(input: {\n subject: string\n text: string\n /** Resend tag / log label. */\n context: string\n}): Promise<SendEmailResult> {\n const to = String(process.env.STAFF_ALERT_EMAIL ?? '').trim()\n if (!to.includes('@')) return { sent: false, reason: 'unconfigured' }\n try {\n // In the platform's header and footer, as the `staff-alert` system email\n // (AGL-3367). Loaded lazily for the reason the meter below is.\n const { renderSystemEmailContent, systemEmailBrand } = await import(\n './render-system-email'\n )\n const content = await renderSystemEmailContent(\n 'staff-alert',\n { 'alert.subject': input.subject, 'alert.body': input.text },\n systemEmailBrand(null),\n { subject: input.subject, text: input.text },\n )\n const result = await sendEmail({ to, ...content, context: input.context })\n if (result.sent) {\n // Platform-scoped (AGL-1438): our own alert is our own cost.\n const { meterPlatformEmail } = await import('./email-metering')\n await meterPlatformEmail().catch(() => undefined)\n }\n return result\n } catch (error) {\n console.error('[staff-alert-email] send failed', error)\n return { sent: false, reason: 'network' }\n }\n}\n"],"names":["sendEmail","sendStaffAlertEmail","input","process","to","String","env","STAFF_ALERT_EMAIL","trim","includes","sent","reason","renderSystemEmailContent","systemEmailBrand","content","subject","text","result","context","meterPlatformEmail","catch","undefined","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,SAAS,QAA8B,2BAA0B;AAE1E;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,eAAeC,oBAAoBC,KAKzC;QACmBC;IAAlB,MAAMC,KAAKC,QAAOF,iCAAAA,QAAQG,GAAG,CAACC,iBAAiB,YAA7BJ,iCAAiC,IAAIK,IAAI;IAC3D,IAAI,CAACJ,GAAGK,QAAQ,CAAC,MAAM,OAAO;QAAEC,MAAM;QAAOC,QAAQ;IAAe;IACpE,IAAI;QACF,yEAAyE;QACzE,+DAA+D;QAC/D,MAAM,EAAEC,wBAAwB,EAAEC,gBAAgB,EAAE,GAAG,MAAM,MAAM,CACjE;QAEF,MAAMC,UAAU,MAAMF,yBACpB,eACA;YAAE,iBAAiBV,MAAMa,OAAO;YAAE,cAAcb,MAAMc,IAAI;QAAC,GAC3DH,iBAAiB,OACjB;YAAEE,SAASb,MAAMa,OAAO;YAAEC,MAAMd,MAAMc,IAAI;QAAC;QAE7C,MAAMC,SAAS,MAAMjB,UAAU;YAAEI;WAAOU;YAASI,SAAShB,MAAMgB,OAAO;;QACvE,IAAID,OAAOP,IAAI,EAAE;YACf,6DAA6D;YAC7D,MAAM,EAAES,kBAAkB,EAAE,GAAG,MAAM,MAAM,CAAC;YAC5C,MAAMA,qBAAqBC,KAAK,CAAC,IAAMC;QACzC;QACA,OAAOJ;IACT,EAAE,OAAOK,OAAO;QACdC,QAAQD,KAAK,CAAC,mCAAmCA;QACjD,OAAO;YAAEZ,MAAM;YAAOC,QAAQ;QAAU;IAC1C;AACF"}
@@ -0,0 +1,63 @@
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
+ /** Why nothing was pulled back, when the answer is final. */
18
+ export type TransferReversalFailure = 'no-charge-on-cause' | 'charge-read-refused' | 'no-transfer-on-charge' | 'transfer-read-refused' | 'transfer-fully-reversed' | 'reversal-refused';
19
+ export type TransferReversalOutcome =
20
+ /** Pulled back now, or found already pulled back and adopted. */
21
+ {
22
+ kind: 'reversed';
23
+ cents: number;
24
+ reversalId: string;
25
+ adopted: boolean;
26
+ }
27
+ /** Final: settle it and record why. `owedCents` when the share was known. */
28
+ | {
29
+ kind: 'not-reversed';
30
+ reason: TransferReversalFailure;
31
+ owedCents?: number;
32
+ }
33
+ /** Nothing was attempted and nothing should be settled: retry later. */
34
+ | {
35
+ kind: 'skipped';
36
+ reason: 'no-stripe-key';
37
+ };
38
+ export interface TransferReversalCause {
39
+ /** Which door: decides the metadata key and the idempotency key. */
40
+ kind: 'dispute' | 'refund';
41
+ /** The dispute's or refund's Stripe id. */
42
+ id: string;
43
+ /** Cents going back to the cardholder. */
44
+ amountCents: number;
45
+ /** The charge whose transfer is pulled back. */
46
+ chargeId: string;
47
+ /** More metadata for the reversal: the caller's record id. */
48
+ metadata?: Record<string, string>;
49
+ }
50
+ /** Stripe failures a redelivery can actually fix. */
51
+ export declare function isTransientStripeStatus(status: number): boolean;
52
+ type FetchLike = typeof fetch;
53
+ /** The metadata key a cause's reversal is stamped and found by. */
54
+ export declare function transferReversalMetadataKey(kind: TransferReversalCause['kind']): string;
55
+ /**
56
+ * Pull the seller's proportional share of `cause` back from the charge's
57
+ * transfer. See the module header for the rules.
58
+ */
59
+ export declare function reverseDestinationTransfer(cause: TransferReversalCause, deps?: {
60
+ stripeKey?: string;
61
+ fetchImpl?: FetchLike;
62
+ }): Promise<TransferReversalOutcome>;
63
+ export {};