@aglyn/tenant-data-admin 1.0.0-beta.264 → 1.0.0-beta.268

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 (41) hide show
  1. package/package.json +7 -7
  2. package/src/lib/server/host-console-link.d.ts +25 -0
  3. package/src/lib/server/host-console-link.js +47 -0
  4. package/src/lib/server/host-console-link.js.map +1 -0
  5. package/src/lib/server/host-email-tokens.js +25 -2
  6. package/src/lib/server/host-email-tokens.js.map +1 -1
  7. package/src/lib/server/mobile-push-switch.d.ts +2 -0
  8. package/src/lib/server/mobile-push-switch.js.map +1 -1
  9. package/src/lib/server/notifications.d.ts +10 -4
  10. package/src/lib/server/notifications.js +34 -9
  11. package/src/lib/server/notifications.js.map +1 -1
  12. package/src/lib/server/operator-alerts.d.ts +11 -0
  13. package/src/lib/server/operator-alerts.js +29 -7
  14. package/src/lib/server/operator-alerts.js.map +1 -1
  15. package/src/lib/server/org-member-notice.d.ts +10 -0
  16. package/src/lib/server/org-member-notice.js +6 -1
  17. package/src/lib/server/org-member-notice.js.map +1 -1
  18. package/src/lib/server/organizations.js +8 -1
  19. package/src/lib/server/organizations.js.map +1 -1
  20. package/src/lib/server/push-apns.d.ts +7 -2
  21. package/src/lib/server/push-apns.js +8 -4
  22. package/src/lib/server/push-apns.js.map +1 -1
  23. package/src/lib/server/push-delivery.d.ts +5 -0
  24. package/src/lib/server/push-delivery.js +9 -4
  25. package/src/lib/server/push-delivery.js.map +1 -1
  26. package/src/lib/server/push-fcm.d.ts +8 -1
  27. package/src/lib/server/push-fcm.js +11 -3
  28. package/src/lib/server/push-fcm.js.map +1 -1
  29. package/src/lib/server/rate-limit-store.d.ts +12 -4
  30. package/src/lib/server/rate-limit-store.js +19 -4
  31. package/src/lib/server/rate-limit-store.js.map +1 -1
  32. package/src/lib/server/render-monitor.d.ts +36 -5
  33. package/src/lib/server/render-monitor.js +81 -22
  34. package/src/lib/server/render-monitor.js.map +1 -1
  35. package/src/lib/server/render-system-email.js +7 -1
  36. package/src/lib/server/render-system-email.js.map +1 -1
  37. package/src/lib/server/risk-notice.js +23 -1
  38. package/src/lib/server/risk-notice.js.map +1 -1
  39. package/src/lib/server/staff-alert-email.d.ts +10 -0
  40. package/src/lib/server/staff-alert-email.js +10 -3
  41. package/src/lib/server/staff-alert-email.js.map +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-data-admin",
3
- "version": "1.0.0-beta.264",
3
+ "version": "1.0.0-beta.268",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,12 +25,12 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.264",
29
- "@aglyn/shared-util-email": "1.0.0-beta.264",
30
- "@aglyn/shared-util-fbserver": "1.0.0-beta.264",
31
- "@aglyn/shared-util-first-touch": "1.0.0-beta.264",
32
- "@aglyn/shared-util-http": "1.0.0-beta.264",
33
- "@aglyn/shared-util-tools": "1.0.0-beta.264",
28
+ "@aglyn/aglyn": "1.0.0-beta.268",
29
+ "@aglyn/shared-util-email": "1.0.0-beta.268",
30
+ "@aglyn/shared-util-fbserver": "1.0.0-beta.268",
31
+ "@aglyn/shared-util-first-touch": "1.0.0-beta.268",
32
+ "@aglyn/shared-util-http": "1.0.0-beta.268",
33
+ "@aglyn/shared-util-tools": "1.0.0-beta.268",
34
34
  "@msgpack/msgpack": "^3.1.3",
35
35
  "@swc/helpers": "0.5.23",
36
36
  "sharp": "^0.35.5",
@@ -0,0 +1,25 @@
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
+ * A site's console page as an absolute link, for an email to the people who
19
+ * run the site: `link` is written the way a notification's is,
20
+ * `/{hostId}/products/returns`, and comes back on today's route,
21
+ * `https://app…/{orgSlug}/hosts/{subdomain}/products/returns`. When the site
22
+ * or its workspace cannot be read, the console home, so the button still
23
+ * opens somewhere the reader can find it from.
24
+ */
25
+ export declare function hostConsoleUrl(hostId: string, link: string): Promise<string>;
@@ -0,0 +1,47 @@
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
+ */ import { normalizeNotificationLink } from "@aglyn/aglyn/server";
17
+ import { platformConsoleOrigin } from "@aglyn/aglyn/app-utils/platform-brand";
18
+ import { getHostDocAdmin, getOrgForHost } from "./organizations.js";
19
+ /**
20
+ * A site's console page as an absolute link, for an email to the people who
21
+ * run the site: `link` is written the way a notification's is,
22
+ * `/{hostId}/products/returns`, and comes back on today's route,
23
+ * `https://app…/{orgSlug}/hosts/{subdomain}/products/returns`. When the site
24
+ * or its workspace cannot be read, the console home, so the button still
25
+ * opens somewhere the reader can find it from.
26
+ */ export async function hostConsoleUrl(hostId, link) {
27
+ const origin = platformConsoleOrigin();
28
+ try {
29
+ var _owner_org;
30
+ const [host, owner] = await Promise.all([
31
+ getHostDocAdmin(hostId),
32
+ getOrgForHost(hostId)
33
+ ]);
34
+ const subdomain = typeof (host == null ? void 0 : host['subdomain']) === 'string' ? host['subdomain'] : undefined;
35
+ const orgSlug = typeof (owner == null ? void 0 : (_owner_org = owner.org) == null ? void 0 : _owner_org.slug) === 'string' ? owner.org.slug : undefined;
36
+ const path = normalizeNotificationLink(link, {
37
+ orgSlug,
38
+ hostId,
39
+ hostSubdomain: subdomain
40
+ });
41
+ return (path == null ? void 0 : path.startsWith('/')) ? `${origin}${path}` : origin;
42
+ } catch (unused) {
43
+ return origin;
44
+ }
45
+ }
46
+
47
+ //# sourceMappingURL=host-console-link.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/host-console-link.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 { normalizeNotificationLink } from '@aglyn/aglyn/server'\nimport { platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { getHostDocAdmin, getOrgForHost } from './organizations'\n\n/**\n * A site's console page as an absolute link, for an email to the people who\n * run the site: `link` is written the way a notification's is,\n * `/{hostId}/products/returns`, and comes back on today's route,\n * `https://app…/{orgSlug}/hosts/{subdomain}/products/returns`. When the site\n * or its workspace cannot be read, the console home, so the button still\n * opens somewhere the reader can find it from.\n */\nexport async function hostConsoleUrl(hostId: string, link: string): Promise<string> {\n const origin = platformConsoleOrigin()\n try {\n const [host, owner] = await Promise.all([getHostDocAdmin(hostId), getOrgForHost(hostId)])\n const subdomain = typeof host?.['subdomain'] === 'string' ? host['subdomain'] : undefined\n const orgSlug = typeof owner?.org?.slug === 'string' ? owner.org.slug : undefined\n const path = normalizeNotificationLink(link, { orgSlug, hostId, hostSubdomain: subdomain })\n return path?.startsWith('/') ? `${origin}${path}` : origin\n } catch {\n return origin\n }\n}\n"],"names":["normalizeNotificationLink","platformConsoleOrigin","getHostDocAdmin","getOrgForHost","hostConsoleUrl","hostId","link","origin","owner","host","Promise","all","subdomain","undefined","orgSlug","org","slug","path","hostSubdomain","startsWith"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,yBAAyB,QAAQ,sBAAqB;AAC/D,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,eAAe,EAAEC,aAAa,QAAQ,qBAAiB;AAEhE;;;;;;;CAOC,GACD,OAAO,eAAeC,eAAeC,MAAc,EAAEC,IAAY;IAC/D,MAAMC,SAASN;IACf,IAAI;YAGqBO;QAFvB,MAAM,CAACC,MAAMD,MAAM,GAAG,MAAME,QAAQC,GAAG,CAAC;YAACT,gBAAgBG;YAASF,cAAcE;SAAQ;QACxF,MAAMO,YAAY,QAAOH,wBAAAA,IAAM,CAAC,YAAY,MAAK,WAAWA,IAAI,CAAC,YAAY,GAAGI;QAChF,MAAMC,UAAU,QAAON,0BAAAA,aAAAA,MAAOO,GAAG,qBAAVP,WAAYQ,IAAI,MAAK,WAAWR,MAAMO,GAAG,CAACC,IAAI,GAAGH;QACxE,MAAMI,OAAOjB,0BAA0BM,MAAM;YAAEQ;YAAST;YAAQa,eAAeN;QAAU;QACzF,OAAOK,CAAAA,wBAAAA,KAAME,UAAU,CAAC,QAAO,GAAGZ,SAASU,MAAM,GAAGV;IACtD,EAAE,eAAM;QACN,OAAOA;IACT;AACF"}
@@ -93,7 +93,28 @@ import { buildEmailPalette, emailPaletteBaseForHost, getTenantEmail, hostEmailOr
93
93
  * published site renders with, light scheme, since an inbox has one, and its
94
94
  * corner radius for buttons. A site with no theme of its own resolves the
95
95
  * same base the site itself does.
96
- */ function siteThemeFor(host) {
96
+ */ /**
97
+ * How the site's buttons set their label (AGL-3897): the theme's button type
98
+ * (`typography.variants.button`, the variant the site's buttons are set in),
99
+ * a `MuiButton` root override's case over it, and MUI's own button type —
100
+ * uppercase, 500 — under both, which is what the site's buttons draw when
101
+ * its theme says nothing.
102
+ */ function siteButtonText(theme) {
103
+ var _ref, _ref1;
104
+ var _read_typography_variants, _read_typography, _read_typography1, _read_components_MuiButton_styleOverrides, _read_components_MuiButton, _read_components;
105
+ const read = theme;
106
+ const type = (_ref = (_ref1 = read == null ? void 0 : (_read_typography = read.typography) == null ? void 0 : (_read_typography_variants = _read_typography.variants) == null ? void 0 : _read_typography_variants.button) != null ? _ref1 : read == null ? void 0 : (_read_typography1 = read.typography) == null ? void 0 : _read_typography1.button) != null ? _ref : {};
107
+ const root = read == null ? void 0 : (_read_components = read.components) == null ? void 0 : (_read_components_MuiButton = _read_components.MuiButton) == null ? void 0 : (_read_components_MuiButton_styleOverrides = _read_components_MuiButton.styleOverrides) == null ? void 0 : _read_components_MuiButton_styleOverrides.root;
108
+ const override = root && typeof root === 'object' ? root.textTransform : undefined;
109
+ const transform = typeof override === 'string' ? override : typeof type.textTransform === 'string' ? type.textTransform : 'uppercase';
110
+ const weight = Number(type.fontWeight);
111
+ return {
112
+ transform: transform,
113
+ weight: Number.isFinite(weight) && weight >= 100 ? weight : 500,
114
+ letterSpacing: typeof type.letterSpacing === 'string' ? type.letterSpacing : '0.02857em'
115
+ };
116
+ }
117
+ function siteThemeFor(host) {
97
118
  var _ref;
98
119
  var _theme_shape, _theme_colorSchemes;
99
120
  // Resolved, not read off `theme`: a site's edits are an override on the
@@ -108,7 +129,9 @@ import { buildEmailPalette, emailPaletteBaseForHost, getTenantEmail, hostEmailOr
108
129
  })
109
130
  }, typeof radius === 'number' ? {
110
131
  buttonRadius: radius
111
- } : {});
132
+ } : {}, {
133
+ buttonText: siteButtonText(theme)
134
+ });
112
135
  }
113
136
  /** The site's chrome for one kind of email, with that kind's footer reason. */ function siteChromeFor(host, templateKey) {
114
137
  var _getTenantEmail;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/host-email-tokens.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 resolveSiteTheme,\n type ThemeHostDocument,\n} from '@aglyn/aglyn/app-utils/site-theme'\nimport { sanitizeAuthorHtml } from '@aglyn/aglyn/app-utils/author-html'\nimport {\n hostTokenMerge,\n type HostTokenSource,\n} from '@aglyn/aglyn/app-utils/host-tokens'\nimport { composeHostComponentNodes } from '@aglyn/aglyn/app-utils/load-referenced-components'\nimport { buildSiteEmailChrome } from '@aglyn/aglyn/app-utils/site-email-chrome'\nimport {\n buildEmailPalette,\n emailPaletteBaseForHost,\n getTenantEmail,\n hostEmailOrigin,\n loadHostEmail,\n renderFramedTextEmail,\n renderHostEmail,\n renderLoadedHostEmail,\n type EmailChrome,\n type EmailTheme,\n type LoadedHostEmail,\n type RenderedHostEmail,\n} from '@aglyn/shared-util-email'\nimport { firebaseAdmin } from './firebase-admin'\n\n/**\n * `renderHostEmail` with `host.*` tokens resolved (AGL-1022).\n *\n * The whole point of host variables is that a publisher's email template can\n * say \"write to {{host.supportEmail}}\" and have the installing site fill it in.\n * That only happens if something resolves the tokens at SEND time, and the\n * email library cannot: `@aglyn/shared-util-email` is `scope:shared` and may\n * only depend on `scope:shared`, while the token registry is aglyn-scoped.\n *\n * So the join happens here, in the one lib that already sits above both. Three\n * alternatives were weighed and this is the one that cannot fail quietly:\n *\n * * A registration hook inside the email library would mean a provider that is\n * never registered resolves every token to nothing, silently, on a path whose\n * output has already been sent to a customer. This repo has shipped a\n * flawless security control with zero callers before; that is the shape.\n * * Threading the map through all eighteen call sites puts the burden on\n * whoever adds the nineteenth, and they will not know.\n * * Moving the registry into a `scope:shared` lib is the cleanest end state and\n * the right thing if a second shared consumer ever appears — but the only\n * candidate today is `shared/util/tools`, which is generic helpers, and\n * domain logic does not belong there.\n *\n * Costs one host read per send. Emails are not a hot path, and the read buys\n * the guarantee that a template's branding is right by construction.\n */\nexport async function renderHostEmailWithTokens(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n templateKey: string,\n merge: Record<string, string> = {},\n options: { origin?: string } = {},\n): Promise<RenderedHostEmail | null> {\n const host = await readHostTokenSource(firestore, hostId)\n return renderHostEmail(\n firestore as never,\n hostId,\n templateKey,\n // Host tokens first: an explicit caller value WINS. A sender passing\n // `host.businessName` is naming a specific thing on purpose (a white-label\n // send, a preview with sample data), and this is not the place to overrule\n // it.\n { ...hostTokenMerge(host), ...merge },\n // The HTML policy joins here for the same reason the token map does, and\n // it is the same reason: `renderEmailHtml` requires one, `scope:shared`\n // cannot import one, and this lib already sits above both. Supplying it\n // here rather than at each of the nine senders keeps their signatures\n // untouched and gives the tenth one the right policy without knowing it\n // needed to ask.\n //\n // The component graft joins on the same argument (AGL-3287): a header or\n // footer the site owner placed is a reference the shared renderer cannot\n // resolve, so every sender behind this function mails it expanded without\n // having to know it exists. Style overrides do not survive into mail —\n // they land in `sx`, which `renderEmailHtml` never reads — but property\n // values and attribute overrides do.\n //\n // And the site's header and footer (AGL-3370), which the built-in copy is\n // drawn inside; a design the owner published goes out as they built it.\n {\n ...options,\n sanitize: sanitizeAuthorHtml,\n compose: composeHostComponentNodes,\n chrome: siteChromeFor(host, templateKey),\n theme: siteThemeFor(host),\n },\n )\n}\n\n/**\n * The site's host document as the token and chrome readers see it, or null.\n *\n * A failed read must not stop the send. Every token then resolves to its\n * empty behaviour, which is the same outcome as a site that set nothing —\n * an email with a gap where the address would be, rather than no email.\n */\nasync function readHostTokenSource(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n): Promise<SiteEmailHost | null> {\n try {\n const snapshot = await firestore.collection('hosts').doc(hostId).get()\n return snapshot.exists ? (snapshot.data() as SiteEmailHost) : null\n } catch {\n return null\n }\n}\n\n/** What a site email reads off the host document: its tokens and its theme. */\ntype SiteEmailHost = HostTokenSource & {\n theme?: {\n colorSchemes?: { light?: Record<string, unknown> | null }\n shape?: { borderRadius?: unknown }\n } | null\n themeOverride?: unknown\n}\n\n/**\n * The site's theme as its email draws it (AGL-3370): the palette the\n * published site renders with, light scheme, since an inbox has one, and its\n * corner radius for buttons. A site with no theme of its own resolves the\n * same base the site itself does.\n */\nfunction siteThemeFor(host: SiteEmailHost | null): EmailTheme {\n // Resolved, not read off `theme`: a site's edits are an override on the\n // theme it picked (AGL-3404), so the stored theme alone is the design\n // before anything the site changed.\n const theme = resolveSiteTheme(host as ThemeHostDocument | null)\n const radius = theme?.shape?.borderRadius\n return {\n palette: buildEmailPalette({\n base: emailPaletteBaseForHost(host),\n colors: (theme?.colorSchemes?.light ?? null) as Record<string, unknown> | null,\n }),\n ...(typeof radius === 'number' ? { buttonRadius: radius } : {}),\n }\n}\n\n/** The site's chrome for one kind of email, with that kind's footer reason. */\nfunction siteChromeFor(\n host: HostTokenSource | null,\n templateKey: string,\n): EmailChrome {\n return buildSiteEmailChrome({\n host,\n reason: getTenantEmail(templateKey)?.footerReason,\n })\n}\n\n/** A site email loaded once for a batch, with the site's tokens beside it. */\nexport interface LoadedHostEmailWithTokens {\n loaded: LoadedHostEmail\n hostMerge: Record<string, string>\n}\n\n/**\n * {@link loadHostEmail} for a batch (AGL-3370): the template, or the built-in\n * copy in the site's header and footer, read ONCE, with the site's `host.*`\n * tokens beside it for {@link renderLoadedHostEmailWithTokens}. `null` only\n * for a key with neither, so the batch keeps its own copy.\n */\nexport async function loadHostEmailWithTokens(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n templateKey: string,\n options: { origin?: string } = {},\n): Promise<LoadedHostEmailWithTokens | null> {\n const host = await readHostTokenSource(firestore, hostId)\n const loaded = await loadHostEmail(firestore as never, hostId, templateKey, {\n ...options,\n compose: composeHostComponentNodes,\n chrome: siteChromeFor(host, templateKey),\n theme: siteThemeFor(host),\n })\n return loaded ? { loaded, hostMerge: hostTokenMerge(host) } : null\n}\n\n/** One recipient's copy of a batch-loaded site email; no reads. */\nexport function renderLoadedHostEmailWithTokens(\n bundle: LoadedHostEmailWithTokens,\n merge: Record<string, string> = {},\n): RenderedHostEmail | null {\n return renderLoadedHostEmail(\n bundle.loaded,\n { ...bundle.hostMerge, ...merge },\n sanitizeAuthorHtml,\n )\n}\n\n/**\n * The site's header and footer for one kind of email, its theme, and the\n * origin and host a stored logo reference resolves against (AGL-3370): for a sender\n * that renders per recipient itself, such as a typed campaign.\n */\nexport async function siteEmailFrame(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n templateKey: string,\n): Promise<{\n chrome: EmailChrome\n theme: EmailTheme\n mediaOrigin?: string\n mediaHostId: string\n}> {\n const host = await readHostTokenSource(firestore, hostId)\n const origin = host\n ? hostEmailOrigin({ cname: host.cname, subdomain: host.subdomain })\n : undefined\n return {\n chrome: siteChromeFor(host, templateKey),\n theme: siteThemeFor(host),\n ...(origin ? { mediaOrigin: origin } : {}),\n mediaHostId: hostId,\n }\n}\n\n/**\n * A text-only site email in the site's header and footer (AGL-3370): a\n * workflow's email step, or a message a site sends in words nobody designed.\n * The text arrives resolved; the footer's reason is the kind's, by key.\n */\nexport async function renderSiteTextEmail(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n templateKey: string,\n message: { subject: string; text: string; preheader?: string },\n): Promise<{ subject: string; html: string; text: string }> {\n const frame = await siteEmailFrame(firestore, hostId, templateKey)\n const rendered = renderFramedTextEmail({ ...message, ...frame })\n return { subject: message.subject, html: rendered.html, text: rendered.text }\n}\n\nexport default renderHostEmailWithTokens\n"],"names":["resolveSiteTheme","sanitizeAuthorHtml","hostTokenMerge","composeHostComponentNodes","buildSiteEmailChrome","buildEmailPalette","emailPaletteBaseForHost","getTenantEmail","hostEmailOrigin","loadHostEmail","renderFramedTextEmail","renderHostEmail","renderLoadedHostEmail","renderHostEmailWithTokens","firestore","hostId","templateKey","merge","options","host","readHostTokenSource","sanitize","compose","chrome","siteChromeFor","theme","siteThemeFor","snapshot","collection","doc","get","exists","data","radius","shape","borderRadius","palette","base","colors","colorSchemes","light","buttonRadius","reason","footerReason","loadHostEmailWithTokens","loaded","hostMerge","renderLoadedHostEmailWithTokens","bundle","siteEmailFrame","origin","cname","subdomain","undefined","mediaOrigin","mediaHostId","renderSiteTextEmail","message","frame","rendered","subject","html","text"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,QAEX,oCAAmC;AAC1C,SAASC,kBAAkB,QAAQ,qCAAoC;AACvE,SACEC,cAAc,QAET,qCAAoC;AAC3C,SAASC,yBAAyB,QAAQ,oDAAmD;AAC7F,SAASC,oBAAoB,QAAQ,2CAA0C;AAC/E,SACEC,iBAAiB,EACjBC,uBAAuB,EACvBC,cAAc,EACdC,eAAe,EACfC,aAAa,EACbC,qBAAqB,EACrBC,eAAe,EACfC,qBAAqB,QAKhB,2BAA0B;AAGjC;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GACD,OAAO,eAAeC,0BACpBC,SAAsC,EACtCC,MAAc,EACdC,WAAmB,EACnBC,QAAgC,CAAC,CAAC,EAClCC,UAA+B,CAAC,CAAC;IAEjC,MAAMC,OAAO,MAAMC,oBAAoBN,WAAWC;IAClD,OAAOJ,gBACLG,WACAC,QACAC,aACA,qEAAqE;IACrE,2EAA2E;IAC3E,2EAA2E;IAC3E,MAAM;IACN,aAAKd,eAAeiB,OAAUF,QAC9B,yEAAyE;IACzE,wEAAwE;IACxE,wEAAwE;IACxE,sEAAsE;IACtE,wEAAwE;IACxE,iBAAiB;IACjB,EAAE;IACF,yEAAyE;IACzE,yEAAyE;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aACvEE;QACHI,SAASnB;QACToB,QAAQC,cAAcL,MAAMH;QAC5BS,OAAOC,aAAaP;;IAEtB,OAAO0B,SAAS;QAAEA;QAAQC,WAAW5C,eAAeiB;IAAM,IAAI;AAChE;AAEA,iEAAiE,GACjE,OAAO,SAAS4B,gCACdC,MAAiC,EACjC/B,QAAgC,CAAC,CAAC;IAElC,OAAOL,sBACLoC,OAAOH,MAAM,EACb,aAAKG,OAAOF,SAAS,EAAK7B,QAC1BhB;AAEJ;AAEA;;;;CAIC,GACD,OAAO,eAAegD,eACpBnC,SAAsC,EACtCC,MAAc,EACdC,WAAmB;IAOnB,MAAMG,OAAO,MAAMC,oBAAoBN,WAAWC;IAClD,MAAMmC,SAAS/B,OACXX,gBAAgB;QAAE2C,OAAOhC,KAAKgC,KAAK;QAAEC,WAAWjC,KAAKiC,SAAS;IAAC,KAC/DC;IACJ,OAAO;QACL9B,QAAQC,cAAcL,MAAMH;QAC5BS,OAAOC,aAAaP;OAChB+B,SAAS;QAAEI,aAAaJ;IAAO,IAAI,CAAC;QACxCK,aAAaxC;;AAEjB;AAEA;;;;CAIC,GACD,OAAO,eAAeyC,oBACpB1C,SAAsC,EACtCC,MAAc,EACdC,WAAmB,EACnByC,OAA8D;IAE9D,MAAMC,QAAQ,MAAMT,eAAenC,WAAWC,QAAQC;IACtD,MAAM2C,WAAWjD,sBAAsB,aAAK+C,SAAYC;IACxD,OAAO;QAAEE,SAASH,QAAQG,OAAO;QAAEC,MAAMF,SAASE,IAAI;QAAEC,MAAMH,SAASG,IAAI;IAAC;AAC9E;AAEA,eAAejD,0BAAyB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/host-email-tokens.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 resolveSiteTheme,\n type ThemeHostDocument,\n} from '@aglyn/aglyn/app-utils/site-theme'\nimport { sanitizeAuthorHtml } from '@aglyn/aglyn/app-utils/author-html'\nimport {\n hostTokenMerge,\n type HostTokenSource,\n} from '@aglyn/aglyn/app-utils/host-tokens'\nimport { composeHostComponentNodes } from '@aglyn/aglyn/app-utils/load-referenced-components'\nimport { buildSiteEmailChrome } from '@aglyn/aglyn/app-utils/site-email-chrome'\nimport {\n buildEmailPalette,\n emailPaletteBaseForHost,\n getTenantEmail,\n hostEmailOrigin,\n loadHostEmail,\n renderFramedTextEmail,\n renderHostEmail,\n renderLoadedHostEmail,\n type EmailChrome,\n type EmailButtonText,\n type EmailTheme,\n type LoadedHostEmail,\n type RenderedHostEmail,\n} from '@aglyn/shared-util-email'\nimport { firebaseAdmin } from './firebase-admin'\n\n/**\n * `renderHostEmail` with `host.*` tokens resolved (AGL-1022).\n *\n * The whole point of host variables is that a publisher's email template can\n * say \"write to {{host.supportEmail}}\" and have the installing site fill it in.\n * That only happens if something resolves the tokens at SEND time, and the\n * email library cannot: `@aglyn/shared-util-email` is `scope:shared` and may\n * only depend on `scope:shared`, while the token registry is aglyn-scoped.\n *\n * So the join happens here, in the one lib that already sits above both. Three\n * alternatives were weighed and this is the one that cannot fail quietly:\n *\n * * A registration hook inside the email library would mean a provider that is\n * never registered resolves every token to nothing, silently, on a path whose\n * output has already been sent to a customer. This repo has shipped a\n * flawless security control with zero callers before; that is the shape.\n * * Threading the map through all eighteen call sites puts the burden on\n * whoever adds the nineteenth, and they will not know.\n * * Moving the registry into a `scope:shared` lib is the cleanest end state and\n * the right thing if a second shared consumer ever appears — but the only\n * candidate today is `shared/util/tools`, which is generic helpers, and\n * domain logic does not belong there.\n *\n * Costs one host read per send. Emails are not a hot path, and the read buys\n * the guarantee that a template's branding is right by construction.\n */\nexport async function renderHostEmailWithTokens(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n templateKey: string,\n merge: Record<string, string> = {},\n options: { origin?: string } = {},\n): Promise<RenderedHostEmail | null> {\n const host = await readHostTokenSource(firestore, hostId)\n return renderHostEmail(\n firestore as never,\n hostId,\n templateKey,\n // Host tokens first: an explicit caller value WINS. A sender passing\n // `host.businessName` is naming a specific thing on purpose (a white-label\n // send, a preview with sample data), and this is not the place to overrule\n // it.\n { ...hostTokenMerge(host), ...merge },\n // The HTML policy joins here for the same reason the token map does, and\n // it is the same reason: `renderEmailHtml` requires one, `scope:shared`\n // cannot import one, and this lib already sits above both. Supplying it\n // here rather than at each of the nine senders keeps their signatures\n // untouched and gives the tenth one the right policy without knowing it\n // needed to ask.\n //\n // The component graft joins on the same argument (AGL-3287): a header or\n // footer the site owner placed is a reference the shared renderer cannot\n // resolve, so every sender behind this function mails it expanded without\n // having to know it exists. Style overrides do not survive into mail —\n // they land in `sx`, which `renderEmailHtml` never reads — but property\n // values and attribute overrides do.\n //\n // And the site's header and footer (AGL-3370), which the built-in copy is\n // drawn inside; a design the owner published goes out as they built it.\n {\n ...options,\n sanitize: sanitizeAuthorHtml,\n compose: composeHostComponentNodes,\n chrome: siteChromeFor(host, templateKey),\n theme: siteThemeFor(host),\n },\n )\n}\n\n/**\n * The site's host document as the token and chrome readers see it, or null.\n *\n * A failed read must not stop the send. Every token then resolves to its\n * empty behaviour, which is the same outcome as a site that set nothing —\n * an email with a gap where the address would be, rather than no email.\n */\nasync function readHostTokenSource(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n): Promise<SiteEmailHost | null> {\n try {\n const snapshot = await firestore.collection('hosts').doc(hostId).get()\n return snapshot.exists ? (snapshot.data() as SiteEmailHost) : null\n } catch {\n return null\n }\n}\n\n/** What a site email reads off the host document: its tokens and its theme. */\ntype SiteEmailHost = HostTokenSource & {\n theme?: {\n colorSchemes?: { light?: Record<string, unknown> | null }\n shape?: { borderRadius?: unknown }\n } | null\n themeOverride?: unknown\n}\n\n/**\n * The site's theme as its email draws it (AGL-3370): the palette the\n * published site renders with, light scheme, since an inbox has one, and its\n * corner radius for buttons. A site with no theme of its own resolves the\n * same base the site itself does.\n */\n/**\n * How the site's buttons set their label (AGL-3897): the theme's button type\n * (`typography.variants.button`, the variant the site's buttons are set in),\n * a `MuiButton` root override's case over it, and MUI's own button type —\n * uppercase, 500 — under both, which is what the site's buttons draw when\n * its theme says nothing.\n */\nfunction siteButtonText(theme: ReturnType<typeof resolveSiteTheme> | null | undefined): EmailButtonText {\n type ButtonType = { textTransform?: unknown; fontWeight?: unknown; letterSpacing?: unknown }\n const read = theme as {\n typography?: { button?: ButtonType; variants?: { button?: ButtonType } }\n components?: { MuiButton?: { styleOverrides?: { root?: unknown } } }\n } | null\n const type = read?.typography?.variants?.button ?? read?.typography?.button ?? {}\n const root = read?.components?.MuiButton?.styleOverrides?.root\n const override = root && typeof root === 'object' ? (root as { textTransform?: unknown }).textTransform : undefined\n const transform = typeof override === 'string' ? override : typeof type.textTransform === 'string' ? type.textTransform : 'uppercase'\n const weight = Number(type.fontWeight)\n return {\n transform: transform as EmailButtonText['transform'],\n weight: Number.isFinite(weight) && weight >= 100 ? weight : 500,\n letterSpacing: typeof type.letterSpacing === 'string' ? type.letterSpacing : '0.02857em',\n }\n}\n\nfunction siteThemeFor(host: SiteEmailHost | null): EmailTheme {\n // Resolved, not read off `theme`: a site's edits are an override on the\n // theme it picked (AGL-3404), so the stored theme alone is the design\n // before anything the site changed.\n const theme = resolveSiteTheme(host as ThemeHostDocument | null)\n const radius = theme?.shape?.borderRadius\n return {\n palette: buildEmailPalette({\n base: emailPaletteBaseForHost(host),\n colors: (theme?.colorSchemes?.light ?? null) as Record<string, unknown> | null,\n }),\n ...(typeof radius === 'number' ? { buttonRadius: radius } : {}),\n buttonText: siteButtonText(theme),\n }\n}\n\n/** The site's chrome for one kind of email, with that kind's footer reason. */\nfunction siteChromeFor(\n host: HostTokenSource | null,\n templateKey: string,\n): EmailChrome {\n return buildSiteEmailChrome({\n host,\n reason: getTenantEmail(templateKey)?.footerReason,\n })\n}\n\n/** A site email loaded once for a batch, with the site's tokens beside it. */\nexport interface LoadedHostEmailWithTokens {\n loaded: LoadedHostEmail\n hostMerge: Record<string, string>\n}\n\n/**\n * {@link loadHostEmail} for a batch (AGL-3370): the template, or the built-in\n * copy in the site's header and footer, read ONCE, with the site's `host.*`\n * tokens beside it for {@link renderLoadedHostEmailWithTokens}. `null` only\n * for a key with neither, so the batch keeps its own copy.\n */\nexport async function loadHostEmailWithTokens(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n templateKey: string,\n options: { origin?: string } = {},\n): Promise<LoadedHostEmailWithTokens | null> {\n const host = await readHostTokenSource(firestore, hostId)\n const loaded = await loadHostEmail(firestore as never, hostId, templateKey, {\n ...options,\n compose: composeHostComponentNodes,\n chrome: siteChromeFor(host, templateKey),\n theme: siteThemeFor(host),\n })\n return loaded ? { loaded, hostMerge: hostTokenMerge(host) } : null\n}\n\n/** One recipient's copy of a batch-loaded site email; no reads. */\nexport function renderLoadedHostEmailWithTokens(\n bundle: LoadedHostEmailWithTokens,\n merge: Record<string, string> = {},\n): RenderedHostEmail | null {\n return renderLoadedHostEmail(\n bundle.loaded,\n { ...bundle.hostMerge, ...merge },\n sanitizeAuthorHtml,\n )\n}\n\n/**\n * The site's header and footer for one kind of email, its theme, and the\n * origin and host a stored logo reference resolves against (AGL-3370): for a sender\n * that renders per recipient itself, such as a typed campaign.\n */\nexport async function siteEmailFrame(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n templateKey: string,\n): Promise<{\n chrome: EmailChrome\n theme: EmailTheme\n mediaOrigin?: string\n mediaHostId: string\n}> {\n const host = await readHostTokenSource(firestore, hostId)\n const origin = host\n ? hostEmailOrigin({ cname: host.cname, subdomain: host.subdomain })\n : undefined\n return {\n chrome: siteChromeFor(host, templateKey),\n theme: siteThemeFor(host),\n ...(origin ? { mediaOrigin: origin } : {}),\n mediaHostId: hostId,\n }\n}\n\n/**\n * A text-only site email in the site's header and footer (AGL-3370): a\n * workflow's email step, or a message a site sends in words nobody designed.\n * The text arrives resolved; the footer's reason is the kind's, by key.\n */\nexport async function renderSiteTextEmail(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n templateKey: string,\n message: { subject: string; text: string; preheader?: string },\n): Promise<{ subject: string; html: string; text: string }> {\n const frame = await siteEmailFrame(firestore, hostId, templateKey)\n const rendered = renderFramedTextEmail({ ...message, ...frame })\n return { subject: message.subject, html: rendered.html, text: rendered.text }\n}\n\nexport default renderHostEmailWithTokens\n"],"names":["resolveSiteTheme","sanitizeAuthorHtml","hostTokenMerge","composeHostComponentNodes","buildSiteEmailChrome","buildEmailPalette","emailPaletteBaseForHost","getTenantEmail","hostEmailOrigin","loadHostEmail","renderFramedTextEmail","renderHostEmail","renderLoadedHostEmail","renderHostEmailWithTokens","firestore","hostId","templateKey","merge","options","host","readHostTokenSource","sanitize","compose","chrome","siteChromeFor","theme","siteThemeFor","snapshot","collection","doc","get","exists","data","siteButtonText","read","type","typography","variants","button","root","components","MuiButton","styleOverrides","override","textTransform","undefined","transform","weight","Number","fontWeight","isFinite","letterSpacing","radius","shape","borderRadius","palette","base","colors","colorSchemes","light","buttonRadius","buttonText","reason","footerReason","loadHostEmailWithTokens","loaded","hostMerge","renderLoadedHostEmailWithTokens","bundle","siteEmailFrame","origin","cname","subdomain","mediaOrigin","mediaHostId","renderSiteTextEmail","message","frame","rendered","subject","html","text"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,QAEX,oCAAmC;AAC1C,SAASC,kBAAkB,QAAQ,qCAAoC;AACvE,SACEC,cAAc,QAET,qCAAoC;AAC3C,SAASC,yBAAyB,QAAQ,oDAAmD;AAC7F,SAASC,oBAAoB,QAAQ,2CAA0C;AAC/E,SACEC,iBAAiB,EACjBC,uBAAuB,EACvBC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ynNotification, '$id' | 'createdAt' | 'r
34
34
  */
35
35
  export type MobilePushSender = (uids: readonly string[], payload: MobilePushPayload, context: {
36
36
  db: Firestore;
37
+ /** Each recipient's picked sound id (`users/{uid}.notificationSound`), read with their preferences. */
38
+ sounds?: Readonly<Record<string, string>>;
37
39
  }) => Promise<void>;
38
40
  /**
39
41
  * Adds a push transport to the fan-out. `notifyUsers` hands every registered
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/mobile-push-switch.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 type { AglynNotification } from '@aglyn/aglyn/server'\nimport type { Firestore } from 'firebase-admin/firestore'\n\n/**\n * Whether this deployment sends mobile push (AGL-3648).\n *\n * On unless `MOBILE_PUSH_ENABLED=0`: the variable is a kill switch, not an\n * opt-in, and it governs every push sender. Kept apart from the senders so\n * `notifyUsers` can ask before it calls one, and every caller reads the same\n * answer.\n */\nexport function mobilePushEnabled(env: Record<string, string | undefined> = process.env): boolean {\n return (env['MOBILE_PUSH_ENABLED'] ?? '').trim() !== '0'\n}\n\n/** The notification a push sender is handed, as the fan-out wrote it. */\nexport type MobilePushPayload = Omit<AglynNotification, '$id' | 'createdAt' | 'readAt'>\n\n/**\n * A push transport (APNs, FCM): sends one notification to the registered\n * devices (`users/{uid}/devices`) of `uids`. Must not throw on a delivery\n * failure; the console notification is the record and a push is a courtesy.\n */\nexport type MobilePushSender = (\n uids: readonly string[],\n payload: MobilePushPayload,\n context: { db: Firestore },\n) => Promise<void>\n\n/*\n * The registry lives on `globalThis`, not in this module: `instrumentation.ts`\n * registers the senders in its own copy of this module, and a route handler's\n * `notifyUsers` reads another one (AGL-3412). A module-scoped set is empty\n * where it is read, and every push is silently skipped.\n */\nconst SENDERS_KEY = Symbol.for('@aglyn/tenant-data-admin:mobile-push-senders')\n\nconst globalScope = globalThis as typeof globalThis & {\n [SENDERS_KEY]?: Set<MobilePushSender>\n}\n\nfunction senders(): Set<MobilePushSender> {\n const existing = globalScope[SENDERS_KEY]\n if (existing) return existing\n const created = new Set<MobilePushSender>()\n globalScope[SENDERS_KEY] = created\n return created\n}\n\n/**\n * Adds a push transport to the fan-out. `notifyUsers` hands every registered\n * sender the recipients whose preferences say push, after the feed entries\n * are committed and only while the kill switch is up. With none registered,\n * nothing is pushed. Returns the unregister function.\n */\nexport function registerMobilePushSender(sender: MobilePushSender): () => void {\n senders().add(sender)\n return () => {\n senders().delete(sender)\n }\n}\n\n/** The registered push transports, in registration order. */\nexport function mobilePushSenders(): MobilePushSender[] {\n return [...senders()]\n}\n"],"names":["mobilePushEnabled","env","process","trim","SENDERS_KEY","Symbol","for","globalScope","globalThis","senders","existing","created","Set","registerMobilePushSender","sender","add","delete","mobilePushSenders"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAKD;;;;;;;CAOC,GACD,OAAO,SAASA,kBAAkBC,MAA0CC,QAAQD,GAAG;QAC7EA;IAAR,OAAO,EAACA,2BAAAA,GAAG,CAAC,sBAAsB,YAA1BA,2BAA8B,IAAIE,IAAI,OAAO;AACvD;AAgBA;;;;;CAKC,GACD,MAAMC,cAAcC,OAAOC,GAAG,CAAC;AAE/B,MAAMC,cAAcC;AAIpB,SAASC;IACP,MAAMC,WAAWH,WAAW,CAACH,YAAY;IACzC,IAAIM,UAAU,OAAOA;IACrB,MAAMC,UAAU,IAAIC;IACpBL,WAAW,CAACH,YAAY,GAAGO;IAC3B,OAAOA;AACT;AAEA;;;;;CAKC,GACD,OAAO,SAASE,yBAAyBC,MAAwB;IAC/DL,UAAUM,GAAG,CAACD;IACd,OAAO;QACLL,UAAUO,MAAM,CAACF;IACnB;AACF;AAEA,2DAA2D,GAC3D,OAAO,SAASG;IACd,OAAO;WAAIR;KAAU;AACvB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/mobile-push-switch.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 type { AglynNotification } from '@aglyn/aglyn/server'\nimport type { Firestore } from 'firebase-admin/firestore'\n\n/**\n * Whether this deployment sends mobile push (AGL-3648).\n *\n * On unless `MOBILE_PUSH_ENABLED=0`: the variable is a kill switch, not an\n * opt-in, and it governs every push sender. Kept apart from the senders so\n * `notifyUsers` can ask before it calls one, and every caller reads the same\n * answer.\n */\nexport function mobilePushEnabled(env: Record<string, string | undefined> = process.env): boolean {\n return (env['MOBILE_PUSH_ENABLED'] ?? '').trim() !== '0'\n}\n\n/** The notification a push sender is handed, as the fan-out wrote it. */\nexport type MobilePushPayload = Omit<AglynNotification, '$id' | 'createdAt' | 'readAt'>\n\n/**\n * A push transport (APNs, FCM): sends one notification to the registered\n * devices (`users/{uid}/devices`) of `uids`. Must not throw on a delivery\n * failure; the console notification is the record and a push is a courtesy.\n */\nexport type MobilePushSender = (\n uids: readonly string[],\n payload: MobilePushPayload,\n context: {\n db: Firestore\n /** Each recipient's picked sound id (`users/{uid}.notificationSound`), read with their preferences. */\n sounds?: Readonly<Record<string, string>>\n },\n) => Promise<void>\n\n/*\n * The registry lives on `globalThis`, not in this module: `instrumentation.ts`\n * registers the senders in its own copy of this module, and a route handler's\n * `notifyUsers` reads another one (AGL-3412). A module-scoped set is empty\n * where it is read, and every push is silently skipped.\n */\nconst SENDERS_KEY = Symbol.for('@aglyn/tenant-data-admin:mobile-push-senders')\n\nconst globalScope = globalThis as typeof globalThis & {\n [SENDERS_KEY]?: Set<MobilePushSender>\n}\n\nfunction senders(): Set<MobilePushSender> {\n const existing = globalScope[SENDERS_KEY]\n if (existing) return existing\n const created = new Set<MobilePushSender>()\n globalScope[SENDERS_KEY] = created\n return created\n}\n\n/**\n * Adds a push transport to the fan-out. `notifyUsers` hands every registered\n * sender the recipients whose preferences say push, after the feed entries\n * are committed and only while the kill switch is up. With none registered,\n * nothing is pushed. Returns the unregister function.\n */\nexport function registerMobilePushSender(sender: MobilePushSender): () => void {\n senders().add(sender)\n return () => {\n senders().delete(sender)\n }\n}\n\n/** The registered push transports, in registration order. */\nexport function mobilePushSenders(): MobilePushSender[] {\n return [...senders()]\n}\n"],"names":["mobilePushEnabled","env","process","trim","SENDERS_KEY","Symbol","for","globalScope","globalThis","senders","existing","created","Set","registerMobilePushSender","sender","add","delete","mobilePushSenders"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAKD;;;;;;;CAOC,GACD,OAAO,SAASA,kBAAkBC,MAA0CC,QAAQD,GAAG;QAC7EA;IAAR,OAAO,EAACA,2BAAAA,GAAG,CAAC,sBAAsB,YAA1BA,2BAA8B,IAAIE,IAAI,OAAO;AACvD;AAoBA;;;;;CAKC,GACD,MAAMC,cAAcC,OAAOC,GAAG,CAAC;AAE/B,MAAMC,cAAcC;AAIpB,SAASC;IACP,MAAMC,WAAWH,WAAW,CAACH,YAAY;IACzC,IAAIM,UAAU,OAAOA;IACrB,MAAMC,UAAU,IAAIC;IACpBL,WAAW,CAACH,YAAY,GAAGO;IAC3B,OAAOA;AACT;AAEA;;;;;CAKC,GACD,OAAO,SAASE,yBAAyBC,MAAwB;IAC/DL,UAAUM,GAAG,CAACD;IACd,OAAO;QACLL,UAAUO,MAAM,CAACF;IACnB;AACF;AAEA,2DAA2D,GAC3D,OAAO,SAASG;IACd,OAAO;WAAIR;KAAU;AACvB"}
@@ -60,6 +60,12 @@ export interface NotifyUsersOptions {
60
60
  * place the visitor's answers are kept.
61
61
  */
62
62
  emailDetails?: readonly NotificationEmailDetail[];
63
+ /**
64
+ * Who a reply to the email reaches (AGL-3897): the visitor who filled in a
65
+ * form, so a manager answers an inquiry from the inbox it landed in. Never
66
+ * set on a staff fan-out.
67
+ */
68
+ replyTo?: string;
63
69
  }
64
70
  /** One labeled line of a notification email's details. */
65
71
  export interface NotificationEmailDetail {
@@ -90,15 +96,13 @@ declare function notifyUsersNow(uids: Iterable<string>, payload: NotificationPay
90
96
  * instead: the same console notification, plus staff's switches, the
91
97
  * operator email or digest, and the webhook. See `raiseOperatorAlert`.
92
98
  */
93
- declare function notifyStaffNow(payload: NotificationPayload): Promise<void>;
99
+ declare function notifyStaffNow(payload: NotificationPayload, options?: Pick<NotifyUsersOptions, 'emailDetails'>): Promise<void>;
94
100
  /**
95
101
  * The staff console notification alone, with the per-person email channel
96
102
  * it carries: what `notifyStaff` did before the registry, and what
97
103
  * `raiseOperatorAlert` writes as its first step. Never throws.
98
104
  */
99
- declare function notifyStaffConsoleNow(payload: NotificationPayload, options?: {
100
- skipEmail?: boolean;
101
- }): Promise<void>;
105
+ declare function notifyStaffConsoleNow(payload: NotificationPayload, options?: Pick<NotifyUsersOptions, 'skipEmail' | 'emailDetails'>): Promise<void>;
102
106
  /**
103
107
  * Notifies the org's owner + admins (billing, membership, org events).
104
108
  *
@@ -149,6 +153,8 @@ declare function notifyHostManagersNow(hostId: string, payload: NotificationPayl
149
153
  skipOwnerEmail?: boolean;
150
154
  /** What the email alone carries; see {@link NotifyUsersOptions.emailDetails}. */
151
155
  emailDetails?: readonly NotificationEmailDetail[];
156
+ /** Who a reply reaches; see {@link NotifyUsersOptions.replyTo}. */
157
+ replyTo?: string;
152
158
  }): Promise<void>;
153
159
  /** {@link notifyUsersNow}, kept alive past the response. */
154
160
  export declare function notifyUsers(...args: Parameters<typeof notifyUsersNow>): Promise<void>;
@@ -18,7 +18,9 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
18
18
  import { operatorAlertForNotificationType } from "@aglyn/aglyn/plugin-manager/operator-alerts";
19
19
  import { isEmailConfigured, sendEmail } from "@aglyn/shared-util-email";
20
20
  import { notificationPushEnabled } from "@aglyn/aglyn/app-utils/notification-push";
21
- import { platformConsoleOrigin } from "@aglyn/aglyn/app-utils/platform-brand";
21
+ import { NOTIFICATION_SOUND_FIELD, notificationSound } from "@aglyn/aglyn/app-utils/notification-sounds";
22
+ import { notificationEmailAction } from "@aglyn/aglyn/app-utils/notifications";
23
+ import { PLATFORM_BRANDING_PROFILE, platformConsoleOrigin } from "@aglyn/aglyn/app-utils/platform-brand";
22
24
  import { FieldValue } from "firebase-admin/firestore";
23
25
  import { withoutMailWithheldAccounts } from "./account-mail.js";
24
26
  import { findUserByUidAcrossPools, listStaffUidsAcrossPools } from "./auth-pools.js";
@@ -77,7 +79,7 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
77
79
  * template is read once per fan-out and rendered per recipient.
78
80
  *
79
81
  * Never throws, like everything else on this path.
80
- */ async function emailNotification(uids, payload, known, audience, emailDetails) {
82
+ */ async function emailNotification(uids, payload, known, audience, emailDetails, replyTo) {
81
83
  var _payload_body;
82
84
  /*
83
85
  * `platformConsoleOrigin`, never `NEXT_PUBLIC_CONSOLE_URL` read bare: this
@@ -101,7 +103,7 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
101
103
  let lookups = 0;
102
104
  let sent = 0;
103
105
  for (const uid of uids){
104
- var _known_uid, _payload_body1;
106
+ var _known_uid, _payload_body1, _context_line;
105
107
  if (sent >= NOTIFY_EMAIL_MAX_SENDS) break;
106
108
  let address = String((_known_uid = known[uid]) != null ? _known_uid : '').trim().toLowerCase();
107
109
  if (!address.includes('@')) {
@@ -122,6 +124,9 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
122
124
  'notification.body': (_payload_body1 = payload.body) != null ? _payload_body1 : '',
123
125
  'notification.details': details,
124
126
  'notification.url': url,
127
+ 'notification.context': (_context_line = context.line) != null ? _context_line : '',
128
+ 'notification.replyNote': replyTo ? `Reply to this email to answer ${replyTo}.` : '',
129
+ 'notification.action': notificationEmailAction(payload.type, context.brand.merge['brand.productName'] || PLATFORM_BRANDING_PROFILE.productName),
125
130
  settingsUrl
126
131
  }), context.brand.options) : null;
127
132
  const result = await sendEmail(_extends({
@@ -132,7 +137,10 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
132
137
  }), context.brand.fromName ? {
133
138
  fromName: context.brand.fromName
134
139
  } : {}, {
135
- context: 'notification',
140
+ context: 'notification'
141
+ }, replyTo ? {
142
+ replyTo
143
+ } : {}, {
136
144
  headers: {
137
145
  'List-Unsubscribe': `<${settingsUrl}>`
138
146
  }
@@ -167,9 +175,18 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
167
175
  ]);
168
176
  const slug = org.get('slug');
169
177
  const subdomain = host == null ? void 0 : host.get('subdomain');
178
+ const text = (value)=>typeof value === 'string' ? value.trim() : '';
179
+ const orgName = text(org.get('name'));
180
+ const siteName = text(host == null ? void 0 : host.get('displayName')) || text(host == null ? void 0 : host.get('name')) || text(subdomain);
181
+ const line = [
182
+ siteName,
183
+ orgName && orgName !== siteName ? orgName : ''
184
+ ].filter(Boolean).join(' · ');
170
185
  return _extends({
171
186
  brand: systemEmailBrand(org.exists ? (_org_data = org.data()) != null ? _org_data : null : null)
172
- }, typeof slug === 'string' && slug ? {
187
+ }, line ? {
188
+ line
189
+ } : {}, typeof slug === 'string' && slug ? {
173
190
  orgSlug: slug
174
191
  } : {}, typeof subdomain === 'string' && subdomain ? {
175
192
  hostSubdomain: subdomain
@@ -219,6 +236,7 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
219
236
  let count = 0;
220
237
  const mailTo = [];
221
238
  const pushTo = [];
239
+ const sounds = {};
222
240
  for (const userDoc of userDocs){
223
241
  var _options_skipEmailFor;
224
242
  const settings = userDoc.get(NOTIFICATION_SETTINGS_FIELD);
@@ -235,6 +253,7 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
235
253
  // The mobile push channel (AGL-3620); unanswered, it follows the feed.
236
254
  if (notificationPushEnabled(settings, payload.type, scope, legacy)) {
237
255
  pushTo.push(userDoc.id);
256
+ sounds[userDoc.id] = notificationSound(userDoc.get(NOTIFICATION_SOUND_FIELD)).id;
238
257
  }
239
258
  if (notificationChannelEnabled(settings, 'email', payload.type, scope, legacy) && !((_options_skipEmailFor = options.skipEmailFor) == null ? void 0 : _options_skipEmailFor.includes(userDoc.id))) {
240
259
  mailTo.push(userDoc.id);
@@ -250,7 +269,8 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
250
269
  for (const send of mobilePushSenders()){
251
270
  try {
252
271
  await send(pushTo, payload, {
253
- db
272
+ db,
273
+ sounds
254
274
  });
255
275
  } catch (error) {
256
276
  console.error('push delivery failed', error);
@@ -276,7 +296,7 @@ const NOTIFY_EMAIL_MAX_SENDS = 50;
276
296
  var _options_emails;
277
297
  const reachable = await withoutMailWithheldAccounts(mailTo);
278
298
  if (!reachable.length) return;
279
- await emailNotification(reachable, payload, (_options_emails = options.emails) != null ? _options_emails : {}, options.audience, options.emailDetails);
299
+ await emailNotification(reachable, payload, (_options_emails = options.emails) != null ? _options_emails : {}, options.audience, options.emailDetails, options.audience === 'staff' ? undefined : options.replyTo);
280
300
  }
281
301
  } catch (error) {
282
302
  console.error('notification fan-out failed', error);
@@ -316,7 +336,7 @@ async function listStaffUids() {
316
336
  * alert, a dispute nobody owns, a support ticket — is raised as that alert
317
337
  * instead: the same console notification, plus staff's switches, the
318
338
  * operator email or digest, and the webhook. See `raiseOperatorAlert`.
319
- */ async function notifyStaffNow(payload) {
339
+ */ async function notifyStaffNow(payload, options = {}) {
320
340
  try {
321
341
  const alert = operatorAlertForNotificationType(payload.type);
322
342
  if (alert) {
@@ -336,7 +356,7 @@ async function listStaffUids() {
336
356
  } : {}));
337
357
  return;
338
358
  }
339
- await notifyStaffConsole(payload);
359
+ await notifyStaffConsole(payload, options);
340
360
  } catch (error) {
341
361
  console.error('staff notification failed', error);
342
362
  }
@@ -347,10 +367,13 @@ async function listStaffUids() {
347
367
  * `raiseOperatorAlert` writes as its first step. Never throws.
348
368
  */ async function notifyStaffConsoleNow(payload, options = {}) {
349
369
  try {
370
+ var _options_emailDetails;
350
371
  await notifyUsers(await listStaffUids(), payload, _extends({
351
372
  audience: 'staff'
352
373
  }, options.skipEmail ? {
353
374
  skipEmail: true
375
+ } : {}, ((_options_emailDetails = options.emailDetails) == null ? void 0 : _options_emailDetails.length) ? {
376
+ emailDetails: options.emailDetails
354
377
  } : {}));
355
378
  } catch (error) {
356
379
  console.error('staff notification failed', error);
@@ -447,6 +470,8 @@ async function listStaffUids() {
447
470
  ]
448
471
  } : {}, options.emailDetails ? {
449
472
  emailDetails: options.emailDetails
473
+ } : {}, options.replyTo ? {
474
+ replyTo: options.replyTo
450
475
  } : {}));
451
476
  } catch (error) {
452
477
  console.error('host manager notification failed', error);