@aglyn/plugins-email 1.0.0-beta.221 → 1.0.0-beta.222

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 (82) hide show
  1. package/README.md +5 -4
  2. package/package.json +16 -17
  3. package/src/lib/components/email-template-detail.d.ts +5 -13
  4. package/src/lib/components/email-template-detail.js +29 -426
  5. package/src/lib/components/email-template-detail.js.map +1 -1
  6. package/src/lib/components/email-zones.d.ts +15 -0
  7. package/src/lib/components/email-zones.js +1 -0
  8. package/src/lib/components/email-zones.js.map +1 -1
  9. package/src/lib/components/list-detail-card.d.ts +0 -36
  10. package/src/lib/components/list-detail-card.js +125 -84
  11. package/src/lib/components/list-detail-card.js.map +1 -1
  12. package/src/lib/components/list-members-panel.d.ts +17 -0
  13. package/src/lib/components/list-members-panel.js +14 -0
  14. package/src/lib/components/list-members-panel.js.map +1 -1
  15. package/src/lib/components/site-package-email-preview.d.ts +13 -0
  16. package/src/lib/components/site-package-email-preview.js +47 -0
  17. package/src/lib/components/site-package-email-preview.js.map +1 -0
  18. package/src/lib/components/suppressions-card.js +75 -6
  19. package/src/lib/components/suppressions-card.js.map +1 -1
  20. package/src/lib/components/use-org-email-topics.js +2 -9
  21. package/src/lib/components/use-org-email-topics.js.map +1 -1
  22. package/src/lib/constants/site-package.d.ts +21 -0
  23. package/src/lib/constants/site-package.js +21 -0
  24. package/src/lib/constants/site-package.js.map +1 -0
  25. package/src/lib/declarations.console-server.d.ts +12 -0
  26. package/src/lib/declarations.console-server.js +73 -0
  27. package/src/lib/declarations.console-server.js.map +1 -1
  28. package/src/lib/list-import.d.ts +64 -75
  29. package/src/lib/list-import.js +43 -158
  30. package/src/lib/list-import.js.map +1 -1
  31. package/src/lib/model/email-topic-catalog.d.ts +24 -0
  32. package/src/lib/model/email-topic-catalog.js +19 -0
  33. package/src/lib/model/email-topic-catalog.js.map +1 -1
  34. package/src/lib/model/index.d.ts +0 -25
  35. package/src/lib/model/index.js +0 -27
  36. package/src/lib/model/index.js.map +1 -1
  37. package/src/lib/plugin.d.ts +8 -0
  38. package/src/lib/plugin.js +76 -2
  39. package/src/lib/plugin.js.map +1 -1
  40. package/src/lib/server/person-eraser.d.ts +39 -0
  41. package/src/lib/server/person-eraser.js +44 -0
  42. package/src/lib/server/person-eraser.js.map +1 -0
  43. package/src/lib/server-console.js +9 -9
  44. package/src/lib/server-console.js.map +1 -1
  45. package/src/lib/server-list-gate.d.ts +7 -0
  46. package/src/lib/server-list-gate.js +10 -3
  47. package/src/lib/server-list-gate.js.map +1 -1
  48. package/src/lib/server-list-import.d.ts +20 -177
  49. package/src/lib/server-list-import.js +34 -594
  50. package/src/lib/server-list-import.js.map +1 -1
  51. package/src/lib/server.js +16 -29
  52. package/src/lib/server.js.map +1 -1
  53. package/src/lib/testing/stand-in-send-tally.d.ts +29 -0
  54. package/src/lib/testing/stand-in-send-tally.js +52 -0
  55. package/src/lib/testing/stand-in-send-tally.js.map +1 -0
  56. package/src/lib/transfer/email-transfer-catalog.d.ts +151 -0
  57. package/src/lib/transfer/email-transfer-catalog.js +536 -0
  58. package/src/lib/transfer/email-transfer-catalog.js.map +1 -0
  59. package/src/lib/transfer/list-import-steps.d.ts +44 -0
  60. package/src/lib/transfer/list-import-steps.js +201 -0
  61. package/src/lib/transfer/list-import-steps.js.map +1 -0
  62. package/src/lib/transfer/list-members.server.d.ts +165 -0
  63. package/src/lib/transfer/list-members.server.js +911 -0
  64. package/src/lib/transfer/list-members.server.js.map +1 -0
  65. package/src/lib/transfer/suppressions.server.d.ts +69 -0
  66. package/src/lib/transfer/suppressions.server.js +282 -0
  67. package/src/lib/transfer/suppressions.server.js.map +1 -0
  68. package/src/lib/transfer/topics-package.d.ts +56 -0
  69. package/src/lib/transfer/topics-package.js +87 -0
  70. package/src/lib/transfer/topics-package.js.map +1 -0
  71. package/src/lib/transfer/topics-package.server.d.ts +33 -0
  72. package/src/lib/transfer/topics-package.server.js +171 -0
  73. package/src/lib/transfer/topics-package.server.js.map +1 -0
  74. package/src/lib/transfer/transfer-reads.server.d.ts +25 -0
  75. package/src/lib/transfer/transfer-reads.server.js +34 -0
  76. package/src/lib/transfer/transfer-reads.server.js.map +1 -0
  77. package/src/lib/components/list-import-drawer.d.ts +0 -22
  78. package/src/lib/components/list-import-drawer.js +0 -662
  79. package/src/lib/components/list-import-drawer.js.map +0 -1
  80. package/src/lib/model/template-report.d.ts +0 -158
  81. package/src/lib/model/template-report.js +0 -249
  82. package/src/lib/model/template-report.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/email/src/lib/components/suppressions-card.tsx"],"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'use client'\n\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { ICON_VARIANT_CLOSE } from '@aglyn/shared-data-enums'\nimport { mdiEmailCheckOutline } from '@aglyn/shared-data-mdi'\nimport {\n CardDisplay,\n Container,\n MdiIcon,\n SrOnly,\n useConfirmationContext,\n} from '@aglyn/shared-ui-jsx'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListQueryNotices, {\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\n/*\n * The shared drawer, reached by its own path.\n *\n * `@aglyn/shared-ui-jsx`'s barrel deliberately does not re-export this one, so\n * a deep import is the supported way in rather than an escape hatch. The\n * console's `CreateArtifactDrawer` — what Screens, Components, Layouts and\n * Templates create through — is this same component with a form inside it,\n * and it lives in `apps/console`, which a plugin library may not import. So\n * the chrome is composed from the same primitive rather than duplicated from\n * the wrapper.\n */\nimport { NavigationDrawerComponent } from '@aglyn/shared-ui-jsx/components/navigation-drawer.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Alert,\n Chip,\n IconButton,\n Stack,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport Button from '@mui/material/Button'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport { collection, deleteDoc, doc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useListQuery } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport {\n SUPPRESSION_FILTER_HEADERS,\n SUPPRESSION_LIST_QUERY,\n} from '../constants/list-queries'\nimport {\n describeSuppressionReason as describeReason,\n readSuppressionTotals,\n SUPPRESSION_REASONS,\n type SuppressionTotals,\n} from './suppression-totals'\nimport { orgSiteName, useEmailOrgMount } from './email-org-mount'\n\nexport interface SuppressionsCardProps {\n hostId: string\n}\n\n/** A stored entry. `reason` is absent on anything written before AGL-2408. */\ninterface SuppressionRow {\n $id: string\n email?: string\n reason?: string\n suppressedAt?: { seconds?: number } | null\n createdAt?: { seconds?: number } | null\n /**\n * The site this entry was copied from when the two stopped being one\n * sender (AGL-3320). The copy keeps the original's reason and dates.\n */\n carriedFromHostId?: string\n}\n\n/*\n * What the suppressions grid's Filters panel offers, every clause and the\n * search on the list's query (AGL-3321): see `SUPPRESSION_LIST_QUERY`. The\n * Reason choices are the stored reasons, by the words the column uses.\n */\nconst SUPPRESSION_FILTER_OPTIONS = {\n reason: Object.entries(SUPPRESSION_REASONS).map(([value, described]) => ({\n value,\n label: described.label,\n })),\n}\nconst SUPPRESSION_SELECT_FIELDS = ['reason']\n\n/**\n * `YYYY-MM-DD` from a Firestore timestamp shape, or an em dash.\n *\n * `createdAt` first, and that ordering is the column's meaning rather than a\n * preference. Both writers restamp `suppressedAt` on every touch and write\n * `createdAt` only when the document is new, precisely so that a bounce\n * arriving after an unsubscribe does not move the date the person actually\n * unsubscribed. Reading `suppressedAt` first put the restamp on screen under a\n * heading that says \"Since\", and it is also the field the list is ordered by,\n * so a re-touched row would have sorted by one date and displayed another.\n */\nfunction onDate(row: SuppressionRow): string {\n const seconds = row.createdAt?.seconds ?? row.suppressedAt?.seconds\n if (!seconds) return '—'\n return new Date(seconds * 1000).toISOString().slice(0, 10)\n}\n\n/**\n * Suppressions (AGL-2410): who is not being emailed, and why.\n *\n * ## What was missing\n *\n * `hosts/{hostId}/suppressions` was written by two paths — the unsubscribe\n * handler and, since AGL-1918, the Resend webhook on a permanent bounce or a\n * complaint — and read by exactly one: `campaign-send.ts`, to filter an\n * audience. Nothing in the console displayed it. So a merchant could not\n * answer any of:\n *\n * - *\"My campaign says 500 recipients and 480 sent — who were the other\n * 20?\"* The send returns `{recipients, sent}` and the difference was\n * unexplained.\n * - *\"Is my list going stale?\"* A bounce rate is the single most useful\n * number about a list and there was nowhere to see it.\n * - *\"This address was suppressed by mistake.\"* There was no way to remove\n * an entry — and a link prescanner unsubscribing someone (AGL-2408 §2) was\n * therefore unrecoverable from inside the product.\n *\n * ## Why a surface and not another counter\n *\n * AGL-1918 deliberately did NOT write a `stats.bounces` counter alongside its\n * fix, because a number with no screen to show it is the written-but-never-\n * read shape this issue is about, one level up. So the fix is the READER, and\n * the breakdown here is derived from the rows on screen rather than from a\n * second stored figure that could disagree with them.\n *\n * ## Removing an entry\n *\n * A plain client `deleteDoc`, and that is a decision. The list belongs to the\n * merchant, host admins already read it through the same rules, and removing\n * a row does nothing except make an address targetable again — there is no\n * counter to launder and no money attached, which is the AGL-1367 test for\n * whether a write has to move server-side.\n *\n * The confirmation is not decoration either: for a `bounce` the address very\n * likely does not exist, and mailing it again is what a provider scores the\n * sending domain on. So the dialog says which reason is being overridden\n * rather than asking a generic \"are you sure\".\n */\nexport function SuppressionsCard(props: SuppressionsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n // Present on the organization's page, which can name the other site.\n const orgMount = useEmailOrgMount()\n const [adding, setAdding] = useState(false)\n\n const [addInput, setAddInput] = useState('')\n const [addNote, setAddNote] = useState('')\n const [busy, setBusy] = useState(false)\n\n /*\n * The page IS the query, ordered by the server (AGL-2501, AGL-2292), and\n * every filter and search word is a predicate on it (AGL-3321).\n *\n * This was `limit(500)` with no `orderBy`, sorted by date in the browser.\n * Firestore answers an unordered limit in DOCUMENT-ID order, and an entry\n * here is keyed by `sha256(email)` — so the window was five hundred\n * addresses chosen by the hash of the address, and the client sort dressed\n * that sample up as the newest five hundred. A list past the ceiling\n * therefore hid whoever bounced this morning behind whoever happened to\n * hash low, with no gap on screen to notice and no control asking for more.\n *\n * `createdAt` is the safe field to order on, and that is checked rather\n * than assumed: both writers — the unsubscribe handler and the Resend\n * bounce/complaint webhook — stamp it when the document is created, the\n * pre-AGL-2408 handler wrote `{ email, createdAt }`, and `suppressions` is\n * not in `IMPORTABLE_FIELDS`, so no restore path can produce a row without\n * one. `suppressedAt` would NOT be safe: it is absent on every entry\n * written before AGL-1918, and `orderBy` drops documents that lack the\n * field rather than mis-sorting them.\n */\n const gridFilter = useListGridFilter({ selectFields: SUPPRESSION_SELECT_FIELDS })\n const {\n rows: entries,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n plan,\n } = useListQuery<SuppressionRow>({\n collection: collection(firestore, 'hosts', hostId, 'suppressions'),\n declaration: SUPPRESSION_LIST_QUERY,\n request: { clauses: gridFilter.clauses, search: gridFilter.searchWords },\n deps: [firestore, hostId],\n idField: '$id',\n })\n const filtering =\n gridFilter.clauses.length > 0 || gridFilter.searchWords.some((word) => word.trim())\n const refusals = useMemo(\n () =>\n listQueryRefusals(plan.refused, {\n fields: SUPPRESSION_LIST_QUERY.fields,\n headers: SUPPRESSION_FILTER_HEADERS,\n options: SUPPRESSION_FILTER_OPTIONS,\n }),\n [plan.refused],\n )\n\n /*==========================================\n * THE BREAKDOWN IS A SERVER AGGREGATE, not a tally of the page.\n *\n * These chips answer \"is my list going stale?\", and they were a `reduce`\n * over whatever the listener had fetched — so on a site past the old\n * ceiling \"Bounced: 140\" meant 140 of an arbitrary five hundred, and under\n * a ten-row page it would have meant 140 of ten. A bounce rate computed\n * from a sample is not a bounce rate, and nothing on screen said it was one.\n *\n * `readSuppressionTotals` holds the four reads and the remainder rule for\n * unsubscribes, and the organization's summary of every site's list asks\n * the same function, so a site's figures read the same on both pages.\n *=========================================*/\n const [totalsEpoch, setTotalsEpoch] = useState(0)\n const [totals, setTotals] = useState<SuppressionTotals | null>(null)\n useEffect(() => {\n let active = true\n void readSuppressionTotals(firestore, hostId)\n .then((read) => {\n if (active) setTotals(read)\n })\n .catch(() => {\n // Held at null rather than zeroed. \"Bounced: 0\" is a confident wrong\n // number in the reassuring direction, and this card exists to warn.\n if (active) setTotals(null)\n })\n return () => {\n active = false\n }\n // The list is a live listener and refreshes itself; an aggregate is a\n // one-shot read and would otherwise keep reporting the breakdown from\n // before the address was put back.\n }, [firestore, hostId, totalsEpoch])\n\n /*\n * The ADD, through a route rather than a client write.\n *\n * The Remove button below writes straight from the browser, and this does\n * not, which looks inconsistent until the document id is considered: an\n * entry is keyed by `sha256` of the normalized address, and a browser\n * computing that itself would be a second derivation of the key every\n * reader shares. Getting it wrong is silent and one-directional — the\n * merchant is told the person is suppressed and the mail keeps going. A\n * removal has no such hazard: it names a row that is already on screen.\n */\n const handleAdd = useCallback(async () => {\n const typed = addInput.trim()\n if (!typed || busy) return\n setBusy(true)\n try {\n const response = await authorizedFetch(\n user,\n '/api/email/suppression-add',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, emails: typed, note: addNote.trim() }),\n },\n )\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n return void enqueueSnackbar(\n payload?.error ?? 'The address could not be suppressed.',\n { variant: 'error' },\n )\n }\n const results = (payload?.results ?? []) as Array<{\n input: string\n added: boolean\n refusal?: string\n }>\n const added = Number(payload?.added ?? 0)\n const rejected = results.filter(\n (result) => result.refusal === 'not-an-address',\n )\n // The refusals are NAMED, because \"3 of 5 added\" leaves an operator to\n // work out which two, and the two that failed are the ones somebody\n // asked to stop being emailed.\n if (rejected.length) {\n enqueueSnackbar(\n `Not an email address: ${rejected\n .map((result) => result.input)\n .join(', ')}`,\n { variant: 'warning' },\n )\n }\n if (added) {\n enqueueSnackbar(\n added === 1\n ? 'Added to the suppression list'\n : `${added} addresses added to the suppression list`,\n { variant: 'success', persist: false },\n )\n } else if (!rejected.length) {\n enqueueSnackbar('Already on the suppression list', { variant: 'info' })\n }\n if (added) {\n setAddInput('')\n setAddNote('')\n setAdding(false)\n setTotalsEpoch((epoch) => epoch + 1)\n }\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error' })\n } finally {\n setBusy(false)\n }\n }, [addInput, addNote, busy, user, hostId, enqueueSnackbar])\n\n /**\n * Whether one address is ALSO on the platform-wide list.\n *\n * The two lists are consulted together at send time and were visible\n * separately, so a merchant who removed their own entry could still find\n * the address was never mailed, with nothing anywhere saying why. The\n * platform entry is invisible to them and cannot be lifted by them, which\n * is precisely why it has to be said before the click rather than\n * discovered from a recipient count that stays short.\n */\n const isBlockedPlatformWide = useCallback(\n async (email: string): Promise<boolean> => {\n try {\n const response = await authorizedFetch(\n user,\n '/api/email/suppression-status',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, emails: email }),\n },\n )\n if (!response.ok) return false\n const payload = await response.json().catch(() => ({}))\n return ((payload?.platform ?? []) as string[]).length > 0\n } catch (error) {\n console.error(error)\n return false\n }\n },\n [user, hostId],\n )\n\n const handleRemove = async (row: SuppressionRow) => {\n const reason = describeReason(row.reason).label.toLowerCase()\n // The platform entry is invisible to a merchant and cannot be lifted by\n // one, so removing the site's row here changes nothing about whether the\n // address is mailed. Saying so BEFORE the click is the whole point: the\n // alternative is a merchant who removes the row, sends again, and sees a\n // recipient count that is still short with nothing explaining it.\n /*\n * ASKED, NOT MOUNTED.\n *\n * One keyed read for the one address the merchant is acting on, at the\n * moment they act. Fetching this for every visible row on mount would be\n * a request per page render for an answer that is only ever needed on a\n * click, and this card is one tab of a page a merchant opens to read.\n *\n * A failed check answers \"not blocked\", which is the ordinary case: the\n * dialog then reads exactly as it did before, and the removal still\n * works. Refusing to open the dialog because a supplementary lookup\n * failed would make an outage on an explanation into an outage on the\n * control it explains.\n */\n const alsoPlatform = row.email\n ? await isBlockedPlatformWide(row.email)\n : false\n const accepted = await confirm({\n title: alsoPlatform\n ? 'This address will still be skipped'\n : 'Put this address back on your list?',\n description: alsoPlatform\n ? `${row.email ?? 'This address'} bounced permanently or reported ` +\n 'spam somewhere else in Aglyn, so it is on the platform-wide list ' +\n 'as well as yours. Removing your entry will not start mail ' +\n 'reaching it — contact support to have the platform entry lifted.'\n : `${row.email ?? 'This address'} is suppressed because it ` +\n `${reason === 'bounced' ? 'bounced permanently' : reason === 'marked as spam' ? 'was marked as spam' : reason === 'added by hand' ? 'was added by hand' : 'unsubscribed'}. ` +\n 'Removing the entry means your next campaign will email it again.',\n confirmationText: 'Remove',\n confirmationButtonProps: { color: 'error' },\n })\n // `confirm` resolves with NO VALUE and REJECTS on cancel, so gating on\n // the resolved value alone makes this always return (AGL-950).\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n try {\n await deleteDoc(\n doc(firestore, 'hosts', hostId, 'suppressions', row.$id),\n )\n enqueueSnackbar('Removed from the suppression list', {\n variant: 'success',\n persist: false,\n })\n setTotalsEpoch((epoch) => epoch + 1)\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error' })\n }\n }\n\n const columns: GridColDef<SuppressionRow>[] = [\n {\n field: 'email',\n headerName: 'Address',\n flex: 1,\n minWidth: 240,\n /*\n Entries are keyed by `sha256(email)` because addresses are PII, and the\n address itself is stored in the document. An older row written before\n the address was stored has only its hash — which tells a merchant\n nothing, so it says so rather than displaying 64 hex characters.\n */\n renderCell: ({ row }) =>\n row.email || (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'(address not recorded)'}\n </Typography>\n ),\n },\n {\n field: 'reason',\n headerName: 'Reason',\n width: 230,\n // An absent reason is an unsubscribe, as the chip says.\n valueGetter: (_value, row) => String(row.reason ?? 'unsubscribe'),\n renderCell: ({ row }) => {\n const described = describeReason(row.reason)\n return (\n <Stack\n direction=\"row\"\n spacing={0.5}\n sx={{ alignItems: 'center', height: '100%' }}\n >\n <Chip\n size=\"small\"\n color={described.color}\n variant=\"outlined\"\n label={described.label}\n />\n {/*\n A copy made when sites stopped being one sender. It is an\n entry like any other; the marker says why an address nobody\n on this site acted on is on its list.\n */}\n {row.carriedFromHostId ? (\n <Tooltip\n title={`Copied from ${\n orgMount\n ? orgSiteName(orgMount, row.carriedFromHostId)\n : 'another site'\n } when the two stopped being one sender`}\n >\n <Chip size=\"small\" variant=\"outlined\" label=\"Copied\" />\n </Tooltip>\n ) : null}\n </Stack>\n )\n },\n },\n {\n field: 'since',\n headerName: 'Since',\n width: 140,\n valueGetter: (_value, row) => onDate(row),\n },\n /*\n A SUPPRESSION HAS NO PAGE, so the row does not open one — this is the\n surface's one list whose rows are not a way in to anything. What it does\n have is the one act a merchant performs on an entry, and the trailing\n cluster is where every other list on this surface keeps that: a bare\n `Remove` in the row is a click that puts an address back into mailing\n range, sitting where the reader's eye is running along the row.\n */\n listActionsColumn(\n (row: SuppressionRow) => (\n <ListRowActions\n label={row.email || 'this entry'}\n items={[\n {\n key: 'remove',\n label: 'Remove from the list',\n icon: <MdiIcon path={mdiEmailCheckOutline.path} size={0.8} />,\n destructive: true,\n onClick: () => void handleRemove(row),\n },\n ]}\n />\n ),\n { width: 72 },\n ),\n ]\n\n return (\n <CardDisplay\n header=\"Suppressions\"\n help={pluginDocsHelp('emailCampaigns', { anchor: '#compliance' })}\n contentGutterX\n contentGutterY\n contentBordered=\"all\"\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"contained\"\n onClick={() => setAdding(true)}\n >\n {'Add'}\n </Button>\n ),\n }}\n >\n <Stack spacing={1.5}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Addresses this site’s marketing email skips. Someone lands here ' +\n 'by clicking unsubscribe, by bouncing permanently, by marking a ' +\n 'message as spam, or because you added them — this is where the ' +\n 'gap between a campaign’s recipient count and what it actually ' +\n 'sent comes from.'}\n </Typography>\n {entries.length === 0 && !hasMore && !filtering ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Nobody is suppressed. Every address in your audiences is ' +\n 'currently mailable.'}\n </Typography>\n ) : (\n <>\n <Stack direction=\"row\" spacing={1} sx={{ flexWrap: 'wrap' }}>\n {totals === null ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Could not read the breakdown. This is not the same as ' +\n 'nobody having bounced.'}\n </Typography>\n ) : (\n Object.entries(totals)\n // A reason nobody has hit is not news, and three chips\n // reading zero make the two that matter harder to find.\n .filter(([, total]) => total > 0)\n .map(([reason, total]) => {\n const described = describeReason(reason)\n return (\n <Chip\n key={reason}\n size=\"small\"\n color={described.color}\n variant=\"outlined\"\n label={`${described.label}: ${total}`}\n />\n )\n })\n )}\n </Stack>\n <ListFilterChips\n fields={SUPPRESSION_LIST_QUERY.fields}\n headers={SUPPRESSION_FILTER_HEADERS}\n clauses={gridFilter.clauses}\n onChange={gridFilter.setClauses}\n options={SUPPRESSION_FILTER_OPTIONS}\n />\n <ListQueryNotices refused={refusals} notices={plan.notices} />\n <ListTable\n aria-label=\"Suppressed addresses\"\n rows={entries}\n columns={listFilterGridColumns(\n columns as GridColDef[],\n SUPPRESSION_LIST_QUERY.fields,\n SUPPRESSION_FILTER_OPTIONS,\n SUPPRESSION_FILTER_HEADERS,\n )}\n rowHeight={TABLE_ROW_HEIGHT}\n // Paged by the footer below, so the grid must not also slice.\n hideFooter\n // The panel and the search go to the query; the grid neither\n // filters nor sorts the page it holds.\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n disableColumnSorting\n noRowsLabel=\"No suppressions match these filters\"\n />\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={entries.length}\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n // The collection's real size, so the footer's count line says\n // \"1–10 of 812\" rather than \"of more than 10\" — the aggregate\n // above already knows it, and it is the same number the chips\n // are a breakdown of. A filtered list's size is unknown.\n count={\n totals && !filtering\n ? Object.values(totals).reduce((a, b) => a + b, 0)\n : undefined\n }\n />\n </>\n )}\n </Stack>\n {/*\n A DRAWER, not a form stacked above the table.\n Creating is a drawer and picking is a dialog, which is how Screens,\n Components, Layouts and Templates all take a name before they create\n one; the chrome here is the same `NavigationDrawerComponent` those go\n through, composed directly because the console's wrapper around it\n lives in an application a plugin library may not import.\n */}\n <NavigationDrawerComponent\n open={adding}\n anchor=\"right\"\n variant=\"temporary\"\n onClose={() => setAdding(false)}\n AppBarProps={{ color: 'surface' }}\n appBarLeft={\n <>\n <IconButton\n color=\"inherit\"\n edge=\"start\"\n onClick={() => setAdding(false)}\n sx={{ mr: 2 }}\n >\n <MdiIcon path={ICON_VARIANT_CLOSE.path} />\n <SrOnly>{'close drawer'}</SrOnly>\n </IconButton>\n <Typography variant=\"h6\" component=\"div\">\n {'Stop emailing an address'}\n </Typography>\n </>\n }\n appBarRight={\n <Button\n variant=\"outlined\"\n color=\"inherit\"\n onClick={() => setAdding(false)}\n >\n {'Cancel'}\n </Button>\n }\n >\n <Container gutterY>\n <Stack spacing={2}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Use this when somebody asks you to stop emailing them by ' +\n 'reply, by phone, or in person. They stay on your audiences ' +\n 'and keep every record you hold about them — this only stops ' +\n 'this site’s marketing email reaching them.'}\n </Typography>\n <TextField\n label=\"Email addresses\"\n value={addInput}\n onChange={(event) => setAddInput(event.target.value)}\n multiline\n minRows={3}\n fullWidth\n autoFocus\n helperText={\n 'One per line, or separated by commas. Up to 50 at a time.'\n }\n />\n <TextField\n label=\"Note (optional)\"\n value={addNote}\n onChange={(event) => setAddNote(event.target.value)}\n fullWidth\n helperText={\n 'How the request reached you. Kept with the entry as the ' +\n 'record that it was honored.'\n }\n slotProps={{ htmlInput: { maxLength: 200 } }}\n />\n <Alert severity=\"info\">\n {'Order confirmations, booking reminders and password resets ' +\n 'are unaffected. Somebody who asked to stop hearing from ' +\n 'your marketing still gets their receipt.'}\n </Alert>\n <Stack direction=\"row\" spacing={1} sx={{ justifyContent: 'flex-end' }}>\n <Button\n variant=\"contained\"\n disabled={busy || !addInput.trim()}\n onClick={() => void handleAdd()}\n >\n {'Add to suppression list'}\n </Button>\n </Stack>\n </Stack>\n </Container>\n </NavigationDrawerComponent>\n </CardDisplay>\n )\n}\nSuppressionsCard.displayName = 'SuppressionsCard'\n\nexport default SuppressionsCard\n"],"names":["pluginDocsHelp","ICON_VARIANT_CLOSE","mdiEmailCheckOutline","CardDisplay","Container","MdiIcon","SrOnly","useConfirmationContext","ListFilterChips","ListPagination","ListQueryNotices","listQueryRefusals","ListRowActions","ListTable","listActionsColumn","listFilterGridColumns","TABLE_ROW_HEIGHT","useListGridFilter","NavigationDrawerComponent","useSnackbar","Alert","Chip","IconButton","Stack","TextField","Tooltip","Typography","Button","collection","deleteDoc","doc","useCallback","useEffect","useMemo","useState","useFirestore","useUser","useListQuery","authorizedFetch","SUPPRESSION_FILTER_HEADERS","SUPPRESSION_LIST_QUERY","describeSuppressionReason","describeReason","readSuppressionTotals","SUPPRESSION_REASONS","orgSiteName","useEmailOrgMount","SUPPRESSION_FILTER_OPTIONS","reason","Object","entries","map","value","described","label","SUPPRESSION_SELECT_FIELDS","onDate","row","seconds","createdAt","suppressedAt","Date","toISOString","slice","SuppressionsCard","props","hostId","firestore","data","user","enqueueSnackbar","confirm","orgMount","adding","setAdding","addInput","setAddInput","addNote","setAddNote","busy","setBusy","gridFilter","selectFields","rows","hasMore","page","setPage","pageSize","setPageSize","plan","declaration","request","clauses","search","searchWords","deps","idField","filtering","length","some","word","trim","refusals","refused","fields","headers","options","totalsEpoch","setTotalsEpoch","totals","setTotals","active","then","read","catch","handleAdd","typed","response","method","body","JSON","stringify","emails","note","payload","json","ok","error","variant","results","added","Number","rejected","filter","result","refusal","input","join","persist","epoch","console","isBlockedPlatformWide","email","platform","handleRemove","toLowerCase","alsoPlatform","accepted","title","description","confirmationText","confirmationButtonProps","color","$id","columns","field","headerName","flex","minWidth","renderCell","width","valueGetter","_value","String","direction","spacing","sx","alignItems","height","size","carriedFromHostId","items","key","icon","path","destructive","onClick","header","help","anchor","contentGutterX","contentGutterY","contentBordered","HeaderProps","action","flexWrap","total","onChange","setClauses","notices","aria-label","rowHeight","hideFooter","filterMode","filterModel","onFilterModelChange","quickFilter","disableColumnSorting","noRowsLabel","rowCount","onPageChange","onPageSizeChange","count","values","reduce","a","b","undefined","open","onClose","AppBarProps","appBarLeft","edge","mr","component","appBarRight","gutterY","event","target","multiline","minRows","fullWidth","autoFocus","helperText","slotProps","htmlInput","maxLength","severity","justifyContent","disabled","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,cAAc,QAAQ,eAAc;AAC7C,SAASC,kBAAkB,QAAQ,2BAA0B;AAC7D,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SACEC,WAAW,EACXC,SAAS,E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AMtG,UAAU;8BAExB;;0BAIL,cAAA,KAACtE;oBAAUoN,OAAO;8BAChB,cAAA,MAACjM;wBAAM8I,SAAS;;0CACd,KAAC3I;gCAAWsG,SAAQ;gCAAQwB,OAAM;0CAC/B,8DACC,gEACA,iEACA;;0CAEJ,KAAChI;gCACC8B,OAAM;gCACNF,OAAOuB;gCACPgH,UAAU,CAAC8B,QAAU7I,YAAY6I,MAAMC,MAAM,CAACtK,KAAK;gCACnDuK,SAAS;gCACTC,SAAS;gCACTC,SAAS;gCACTC,SAAS;gCACTC,YACE;;0CAGJ,KAACvM;gCACC8B,OAAM;gCACNF,OAAOyB;gCACP8G,UAAU,CAAC8B,QAAU3I,WAAW2I,MAAMC,MAAM,CAACtK,KAAK;gCAClDyK,SAAS;gCACTE,YACE,6DACA;gCAEFC,WAAW;oCAAEC,WAAW;wCAAEC,WAAW;oCAAI;gCAAE;;0CAE7C,KAAC9M;gCAAM+M,UAAS;0CACb,gEACC,6DACA;;0CAEJ,KAAC5M;gCAAM6I,WAAU;gCAAMC,SAAS;gCAAGC,IAAI;oCAAE8D,gBAAgB;gCAAW;0CAClE,cAAA,KAACzM;oCACCqG,SAAQ;oCACRqG,UAAUtJ,QAAQ,CAACJ,SAAS0B,IAAI;oCAChC2E,SAAS,IAAM,KAAK7D;8CAEnB;;;;;;;;;AAQjB;AACAnD,iBAAiBsK,WAAW,GAAG;AAE/B,eAAetK,iBAAgB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/email/src/lib/components/suppressions-card.tsx"],"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'use client'\n\nimport { TransferResumeImport } from '@aglyn/aglyn/app-utils/transfer-resume-import'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { useTransferLauncher } from '@aglyn/aglyn/app-utils/transfer-launcher-context'\nimport { ICON_VARIANT_CLOSE } from '@aglyn/shared-data-enums'\nimport {\n mdiEmailCheckOutline,\n mdiTrayArrowDown,\n mdiTrayArrowUp,\n} from '@aglyn/shared-data-mdi'\nimport {\n CardDisplay,\n Container,\n MdiIcon,\n SrOnly,\n useConfirmationContext,\n} from '@aglyn/shared-ui-jsx'\nimport ListFilterChips from '@aglyn/shared-ui-jsx/components/list-filter-chips.component'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport ListQueryNotices, {\n listQueryRefusals,\n} from '@aglyn/shared-ui-jsx/components/list-query-notices.component'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { listFilterGridColumns } from '@aglyn/shared-ui-jsx/const/list-grid-filter'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useListGridFilter } from '@aglyn/shared-ui-jsx/hooks/use-list-grid-filter'\n/*\n * The shared drawer, reached by its own path.\n *\n * `@aglyn/shared-ui-jsx`'s barrel deliberately does not re-export this one, so\n * a deep import is the supported way in rather than an escape hatch. The\n * console's `CreateArtifactDrawer` — what Screens, Components, Layouts and\n * Templates create through — is this same component with a form inside it,\n * and it lives in `apps/console`, which a plugin library may not import. So\n * the chrome is composed from the same primitive rather than duplicated from\n * the wrapper.\n */\nimport { NavigationDrawerComponent } from '@aglyn/shared-ui-jsx/components/navigation-drawer.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Alert,\n Chip,\n IconButton,\n Stack,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport Button from '@mui/material/Button'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport { collection, deleteDoc, doc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useListQuery } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport {\n SUPPRESSION_FILTER_HEADERS,\n SUPPRESSION_LIST_QUERY,\n} from '../constants/list-queries'\nimport {\n describeSuppressionReason as describeReason,\n readSuppressionTotals,\n SUPPRESSION_REASONS,\n type SuppressionTotals,\n} from './suppression-totals'\nimport { orgSiteName, useEmailOrgMount } from './email-org-mount'\nimport { SUPPRESSIONS_RESOURCE } from '../transfer/email-transfer-catalog'\n\nexport interface SuppressionsCardProps {\n hostId: string\n}\n\n/** A stored entry. `reason` is absent on anything written before AGL-2408. */\ninterface SuppressionRow {\n $id: string\n email?: string\n reason?: string\n suppressedAt?: { seconds?: number } | null\n createdAt?: { seconds?: number } | null\n /**\n * The site this entry was copied from when the two stopped being one\n * sender (AGL-3320). The copy keeps the original's reason and dates.\n */\n carriedFromHostId?: string\n}\n\n/*\n * What the suppressions grid's Filters panel offers, every clause and the\n * search on the list's query (AGL-3321): see `SUPPRESSION_LIST_QUERY`. The\n * Reason choices are the stored reasons, by the words the column uses.\n */\nconst SUPPRESSION_FILTER_OPTIONS = {\n reason: Object.entries(SUPPRESSION_REASONS).map(([value, described]) => ({\n value,\n label: described.label,\n })),\n}\nconst SUPPRESSION_SELECT_FIELDS = ['reason']\n\n/**\n * `YYYY-MM-DD` from a Firestore timestamp shape, or an em dash.\n *\n * `createdAt` first, and that ordering is the column's meaning rather than a\n * preference. Both writers restamp `suppressedAt` on every touch and write\n * `createdAt` only when the document is new, precisely so that a bounce\n * arriving after an unsubscribe does not move the date the person actually\n * unsubscribed. Reading `suppressedAt` first put the restamp on screen under a\n * heading that says \"Since\", and it is also the field the list is ordered by,\n * so a re-touched row would have sorted by one date and displayed another.\n */\nfunction onDate(row: SuppressionRow): string {\n const seconds = row.createdAt?.seconds ?? row.suppressedAt?.seconds\n if (!seconds) return '—'\n return new Date(seconds * 1000).toISOString().slice(0, 10)\n}\n\n/**\n * Suppressions (AGL-2410): who is not being emailed, and why.\n *\n * ## What was missing\n *\n * `hosts/{hostId}/suppressions` was written by two paths — the unsubscribe\n * handler and, since AGL-1918, the Resend webhook on a permanent bounce or a\n * complaint — and read by exactly one: `campaign-send.ts`, to filter an\n * audience. Nothing in the console displayed it. So a merchant could not\n * answer any of:\n *\n * - *\"My campaign says 500 recipients and 480 sent — who were the other\n * 20?\"* The send returns `{recipients, sent}` and the difference was\n * unexplained.\n * - *\"Is my list going stale?\"* A bounce rate is the single most useful\n * number about a list and there was nowhere to see it.\n * - *\"This address was suppressed by mistake.\"* There was no way to remove\n * an entry — and a link prescanner unsubscribing someone (AGL-2408 §2) was\n * therefore unrecoverable from inside the product.\n *\n * ## Why a surface and not another counter\n *\n * AGL-1918 deliberately did NOT write a `stats.bounces` counter alongside its\n * fix, because a number with no screen to show it is the written-but-never-\n * read shape this issue is about, one level up. So the fix is the READER, and\n * the breakdown here is derived from the rows on screen rather than from a\n * second stored figure that could disagree with them.\n *\n * ## Removing an entry\n *\n * A plain client `deleteDoc`, and that is a decision. The list belongs to the\n * merchant, host admins already read it through the same rules, and removing\n * a row does nothing except make an address targetable again — there is no\n * counter to launder and no money attached, which is the AGL-1367 test for\n * whether a write has to move server-side.\n *\n * The confirmation is not decoration either: for a `bounce` the address very\n * likely does not exist, and mailing it again is what a provider scores the\n * sending domain on. So the dialog says which reason is being overridden\n * rather than asking a generic \"are you sure\".\n */\nexport function SuppressionsCard(props: SuppressionsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n // Present on the organization's page, which can name the other site.\n const orgMount = useEmailOrgMount()\n const [adding, setAdding] = useState(false)\n\n const [addInput, setAddInput] = useState('')\n const [addNote, setAddNote] = useState('')\n const [busy, setBusy] = useState(false)\n\n /*\n * The page IS the query, ordered by the server (AGL-2501, AGL-2292), and\n * every filter and search word is a predicate on it (AGL-3321).\n *\n * This was `limit(500)` with no `orderBy`, sorted by date in the browser.\n * Firestore answers an unordered limit in DOCUMENT-ID order, and an entry\n * here is keyed by `sha256(email)` — so the window was five hundred\n * addresses chosen by the hash of the address, and the client sort dressed\n * that sample up as the newest five hundred. A list past the ceiling\n * therefore hid whoever bounced this morning behind whoever happened to\n * hash low, with no gap on screen to notice and no control asking for more.\n *\n * `createdAt` is the safe field to order on, and that is checked rather\n * than assumed: both writers — the unsubscribe handler and the Resend\n * bounce/complaint webhook — stamp it when the document is created, the\n * pre-AGL-2408 handler wrote `{ email, createdAt }`, and `suppressions` is\n * not in `IMPORTABLE_FIELDS`, so no restore path can produce a row without\n * one. `suppressedAt` would NOT be safe: it is absent on every entry\n * written before AGL-1918, and `orderBy` drops documents that lack the\n * field rather than mis-sorting them.\n */\n const gridFilter = useListGridFilter({ selectFields: SUPPRESSION_SELECT_FIELDS })\n const {\n rows: entries,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n plan,\n } = useListQuery<SuppressionRow>({\n collection: collection(firestore, 'hosts', hostId, 'suppressions'),\n declaration: SUPPRESSION_LIST_QUERY,\n request: { clauses: gridFilter.clauses, search: gridFilter.searchWords },\n deps: [firestore, hostId],\n idField: '$id',\n })\n const filtering =\n gridFilter.clauses.length > 0 || gridFilter.searchWords.some((word) => word.trim())\n /*\n * IMPORT AND EXPORT (AGL-3529) open the console's transfer wizard and\n * export dialog on this site's list. An import only ever adds: an address\n * already here keeps its entry, and nothing removes one. The export's\n * \"current filter\" is this table's own query.\n */\n const transfer = useTransferLauncher()\n const exportFilter = filtering\n ? {\n label: 'Entries matching the table’s filters',\n value: { filters: plan.filters },\n }\n : null\n const refusals = useMemo(\n () =>\n listQueryRefusals(plan.refused, {\n fields: SUPPRESSION_LIST_QUERY.fields,\n headers: SUPPRESSION_FILTER_HEADERS,\n options: SUPPRESSION_FILTER_OPTIONS,\n }),\n [plan.refused],\n )\n\n /*==========================================\n * THE BREAKDOWN IS A SERVER AGGREGATE, not a tally of the page.\n *\n * These chips answer \"is my list going stale?\", and they were a `reduce`\n * over whatever the listener had fetched — so on a site past the old\n * ceiling \"Bounced: 140\" meant 140 of an arbitrary five hundred, and under\n * a ten-row page it would have meant 140 of ten. A bounce rate computed\n * from a sample is not a bounce rate, and nothing on screen said it was one.\n *\n * `readSuppressionTotals` holds the four reads and the remainder rule for\n * unsubscribes, and the organization's summary of every site's list asks\n * the same function, so a site's figures read the same on both pages.\n *=========================================*/\n const [totalsEpoch, setTotalsEpoch] = useState(0)\n const [totals, setTotals] = useState<SuppressionTotals | null>(null)\n useEffect(() => {\n let active = true\n void readSuppressionTotals(firestore, hostId)\n .then((read) => {\n if (active) setTotals(read)\n })\n .catch(() => {\n // Held at null rather than zeroed. \"Bounced: 0\" is a confident wrong\n // number in the reassuring direction, and this card exists to warn.\n if (active) setTotals(null)\n })\n return () => {\n active = false\n }\n // The list is a live listener and refreshes itself; an aggregate is a\n // one-shot read and would otherwise keep reporting the breakdown from\n // before the address was put back.\n }, [firestore, hostId, totalsEpoch])\n\n /*\n * The ADD, through a route rather than a client write.\n *\n * The Remove button below writes straight from the browser, and this does\n * not, which looks inconsistent until the document id is considered: an\n * entry is keyed by `sha256` of the normalized address, and a browser\n * computing that itself would be a second derivation of the key every\n * reader shares. Getting it wrong is silent and one-directional — the\n * merchant is told the person is suppressed and the mail keeps going. A\n * removal has no such hazard: it names a row that is already on screen.\n */\n const handleAdd = useCallback(async () => {\n const typed = addInput.trim()\n if (!typed || busy) return\n setBusy(true)\n try {\n const response = await authorizedFetch(\n user,\n '/api/email/suppression-add',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, emails: typed, note: addNote.trim() }),\n },\n )\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n return void enqueueSnackbar(\n payload?.error ?? 'The address could not be suppressed.',\n { variant: 'error' },\n )\n }\n const results = (payload?.results ?? []) as Array<{\n input: string\n added: boolean\n refusal?: string\n }>\n const added = Number(payload?.added ?? 0)\n const rejected = results.filter(\n (result) => result.refusal === 'not-an-address',\n )\n // The refusals are NAMED, because \"3 of 5 added\" leaves an operator to\n // work out which two, and the two that failed are the ones somebody\n // asked to stop being emailed.\n if (rejected.length) {\n enqueueSnackbar(\n `Not an email address: ${rejected\n .map((result) => result.input)\n .join(', ')}`,\n { variant: 'warning' },\n )\n }\n if (added) {\n enqueueSnackbar(\n added === 1\n ? 'Added to the suppression list'\n : `${added} addresses added to the suppression list`,\n { variant: 'success', persist: false },\n )\n } else if (!rejected.length) {\n enqueueSnackbar('Already on the suppression list', { variant: 'info' })\n }\n if (added) {\n setAddInput('')\n setAddNote('')\n setAdding(false)\n setTotalsEpoch((epoch) => epoch + 1)\n }\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error' })\n } finally {\n setBusy(false)\n }\n }, [addInput, addNote, busy, user, hostId, enqueueSnackbar])\n\n /**\n * Whether one address is ALSO on the platform-wide list.\n *\n * The two lists are consulted together at send time and were visible\n * separately, so a merchant who removed their own entry could still find\n * the address was never mailed, with nothing anywhere saying why. The\n * platform entry is invisible to them and cannot be lifted by them, which\n * is precisely why it has to be said before the click rather than\n * discovered from a recipient count that stays short.\n */\n const isBlockedPlatformWide = useCallback(\n async (email: string): Promise<boolean> => {\n try {\n const response = await authorizedFetch(\n user,\n '/api/email/suppression-status',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, emails: email }),\n },\n )\n if (!response.ok) return false\n const payload = await response.json().catch(() => ({}))\n return ((payload?.platform ?? []) as string[]).length > 0\n } catch (error) {\n console.error(error)\n return false\n }\n },\n [user, hostId],\n )\n\n const handleRemove = async (row: SuppressionRow) => {\n const reason = describeReason(row.reason).label.toLowerCase()\n // The platform entry is invisible to a merchant and cannot be lifted by\n // one, so removing the site's row here changes nothing about whether the\n // address is mailed. Saying so BEFORE the click is the whole point: the\n // alternative is a merchant who removes the row, sends again, and sees a\n // recipient count that is still short with nothing explaining it.\n /*\n * ASKED, NOT MOUNTED.\n *\n * One keyed read for the one address the merchant is acting on, at the\n * moment they act. Fetching this for every visible row on mount would be\n * a request per page render for an answer that is only ever needed on a\n * click, and this card is one tab of a page a merchant opens to read.\n *\n * A failed check answers \"not blocked\", which is the ordinary case: the\n * dialog then reads exactly as it did before, and the removal still\n * works. Refusing to open the dialog because a supplementary lookup\n * failed would make an outage on an explanation into an outage on the\n * control it explains.\n */\n const alsoPlatform = row.email\n ? await isBlockedPlatformWide(row.email)\n : false\n const accepted = await confirm({\n title: alsoPlatform\n ? 'This address will still be skipped'\n : 'Put this address back on your list?',\n description: alsoPlatform\n ? `${row.email ?? 'This address'} bounced permanently or reported ` +\n 'spam somewhere else in Aglyn, so it is on the platform-wide list ' +\n 'as well as yours. Removing your entry will not start mail ' +\n 'reaching it — contact support to have the platform entry lifted.'\n : `${row.email ?? 'This address'} is suppressed because it ` +\n `${reason === 'bounced' ? 'bounced permanently' : reason === 'marked as spam' ? 'was marked as spam' : reason === 'added by hand' ? 'was added by hand' : 'unsubscribed'}. ` +\n 'Removing the entry means your next campaign will email it again.',\n confirmationText: 'Remove',\n confirmationButtonProps: { color: 'error' },\n })\n // `confirm` resolves with NO VALUE and REJECTS on cancel, so gating on\n // the resolved value alone makes this always return (AGL-950).\n .then(() => true)\n .catch(() => false)\n if (!accepted) return\n try {\n await deleteDoc(\n doc(firestore, 'hosts', hostId, 'suppressions', row.$id),\n )\n enqueueSnackbar('Removed from the suppression list', {\n variant: 'success',\n persist: false,\n })\n setTotalsEpoch((epoch) => epoch + 1)\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', { variant: 'error' })\n }\n }\n\n const columns: GridColDef<SuppressionRow>[] = [\n {\n field: 'email',\n headerName: 'Address',\n flex: 1,\n minWidth: 240,\n /*\n Entries are keyed by `sha256(email)` because addresses are PII, and the\n address itself is stored in the document. An older row written before\n the address was stored has only its hash — which tells a merchant\n nothing, so it says so rather than displaying 64 hex characters.\n */\n renderCell: ({ row }) =>\n row.email || (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'(address not recorded)'}\n </Typography>\n ),\n },\n {\n field: 'reason',\n headerName: 'Reason',\n width: 230,\n // An absent reason is an unsubscribe, as the chip says.\n valueGetter: (_value, row) => String(row.reason ?? 'unsubscribe'),\n renderCell: ({ row }) => {\n const described = describeReason(row.reason)\n return (\n <Stack\n direction=\"row\"\n spacing={0.5}\n sx={{ alignItems: 'center', height: '100%' }}\n >\n <Chip\n size=\"small\"\n color={described.color}\n variant=\"outlined\"\n label={described.label}\n />\n {/*\n A copy made when sites stopped being one sender. It is an\n entry like any other; the marker says why an address nobody\n on this site acted on is on its list.\n */}\n {row.carriedFromHostId ? (\n <Tooltip\n title={`Copied from ${\n orgMount\n ? orgSiteName(orgMount, row.carriedFromHostId)\n : 'another site'\n } when the two stopped being one sender`}\n >\n <Chip size=\"small\" variant=\"outlined\" label=\"Copied\" />\n </Tooltip>\n ) : null}\n </Stack>\n )\n },\n },\n {\n field: 'since',\n headerName: 'Since',\n width: 140,\n valueGetter: (_value, row) => onDate(row),\n },\n /*\n A SUPPRESSION HAS NO PAGE, so the row does not open one — this is the\n surface's one list whose rows are not a way in to anything. What it does\n have is the one act a merchant performs on an entry, and the trailing\n cluster is where every other list on this surface keeps that: a bare\n `Remove` in the row is a click that puts an address back into mailing\n range, sitting where the reader's eye is running along the row.\n */\n listActionsColumn(\n (row: SuppressionRow) => (\n <ListRowActions\n label={row.email || 'this entry'}\n items={[\n {\n key: 'remove',\n label: 'Remove from the list',\n icon: <MdiIcon path={mdiEmailCheckOutline.path} size={0.8} />,\n destructive: true,\n onClick: () => void handleRemove(row),\n },\n ]}\n />\n ),\n { width: 72 },\n ),\n ]\n\n return (\n <CardDisplay\n header=\"Suppressions\"\n help={pluginDocsHelp('emailCampaigns', { anchor: '#compliance' })}\n contentGutterX\n contentGutterY\n contentBordered=\"all\"\n HeaderProps={{\n action: (\n <Stack direction=\"row\" spacing={1}>\n {/* Each only for whom the route takes it (AGL-3554). */}\n {transfer?.can('export', { resource: SUPPRESSIONS_RESOURCE, scope: 'host', hostId }) ? (\n <Button\n size=\"small\"\n variant=\"outlined\"\n startIcon={<MdiIcon path={mdiTrayArrowDown.path} size={0.8} />}\n onClick={() =>\n transfer.openExport({\n resource: SUPPRESSIONS_RESOURCE,\n scope: 'host',\n hostId,\n ...(exportFilter ? { filter: exportFilter } : {}),\n })\n }\n >\n {'Export'}\n </Button>\n ) : null}\n {/* An import left unfinished, reopened where it stopped (AGL-3549). */}\n <TransferResumeImport\n target={{ resource: SUPPRESSIONS_RESOURCE, scope: 'host', hostId }}\n onFinished={() => setTotalsEpoch((epoch) => epoch + 1)}\n />\n {transfer?.can('import', { resource: SUPPRESSIONS_RESOURCE, scope: 'host', hostId }) ? (\n <Button\n size=\"small\"\n variant=\"outlined\"\n startIcon={<MdiIcon path={mdiTrayArrowUp.path} size={0.8} />}\n onClick={() =>\n transfer.openImport({\n resource: SUPPRESSIONS_RESOURCE,\n scope: 'host',\n hostId,\n onFinished: () => setTotalsEpoch((epoch) => epoch + 1),\n })\n }\n >\n {'Import'}\n </Button>\n ) : null}\n <Button\n size=\"small\"\n variant=\"contained\"\n onClick={() => setAdding(true)}\n >\n {'Add'}\n </Button>\n </Stack>\n ),\n }}\n >\n <Stack spacing={1.5}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Addresses this site’s marketing email skips. Someone lands here ' +\n 'by clicking unsubscribe, by bouncing permanently, by marking a ' +\n 'message as spam, or because you added them — this is where the ' +\n 'gap between a campaign’s recipient count and what it actually ' +\n 'sent comes from.'}\n </Typography>\n {entries.length === 0 && !hasMore && !filtering ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Nobody is suppressed. Every address in your audiences is ' +\n 'currently mailable.'}\n </Typography>\n ) : (\n <>\n <Stack direction=\"row\" spacing={1} sx={{ flexWrap: 'wrap' }}>\n {totals === null ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Could not read the breakdown. This is not the same as ' +\n 'nobody having bounced.'}\n </Typography>\n ) : (\n Object.entries(totals)\n // A reason nobody has hit is not news, and three chips\n // reading zero make the two that matter harder to find.\n .filter(([, total]) => total > 0)\n .map(([reason, total]) => {\n const described = describeReason(reason)\n return (\n <Chip\n key={reason}\n size=\"small\"\n color={described.color}\n variant=\"outlined\"\n label={`${described.label}: ${total}`}\n />\n )\n })\n )}\n </Stack>\n <ListFilterChips\n fields={SUPPRESSION_LIST_QUERY.fields}\n headers={SUPPRESSION_FILTER_HEADERS}\n clauses={gridFilter.clauses}\n onChange={gridFilter.setClauses}\n options={SUPPRESSION_FILTER_OPTIONS}\n />\n <ListQueryNotices refused={refusals} notices={plan.notices} />\n <ListTable\n aria-label=\"Suppressed addresses\"\n rows={entries}\n columns={listFilterGridColumns(\n columns as GridColDef[],\n SUPPRESSION_LIST_QUERY.fields,\n SUPPRESSION_FILTER_OPTIONS,\n SUPPRESSION_FILTER_HEADERS,\n )}\n rowHeight={TABLE_ROW_HEIGHT}\n // Paged by the footer below, so the grid must not also slice.\n hideFooter\n // The panel and the search go to the query; the grid neither\n // filters nor sorts the page it holds.\n filterMode=\"server\"\n filterModel={gridFilter.filterModel}\n onFilterModelChange={gridFilter.onFilterModelChange}\n quickFilter\n disableColumnSorting\n noRowsLabel=\"No suppressions match these filters\"\n />\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={entries.length}\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n // The collection's real size, so the footer's count line says\n // \"1–10 of 812\" rather than \"of more than 10\" — the aggregate\n // above already knows it, and it is the same number the chips\n // are a breakdown of. A filtered list's size is unknown.\n count={\n totals && !filtering\n ? Object.values(totals).reduce((a, b) => a + b, 0)\n : undefined\n }\n />\n </>\n )}\n </Stack>\n {/*\n A DRAWER, not a form stacked above the table.\n Creating is a drawer and picking is a dialog, which is how Screens,\n Components, Layouts and Templates all take a name before they create\n one; the chrome here is the same `NavigationDrawerComponent` those go\n through, composed directly because the console's wrapper around it\n lives in an application a plugin library may not import.\n */}\n <NavigationDrawerComponent\n open={adding}\n anchor=\"right\"\n variant=\"temporary\"\n onClose={() => setAdding(false)}\n AppBarProps={{ color: 'surface' }}\n appBarLeft={\n <>\n <IconButton\n color=\"inherit\"\n edge=\"start\"\n onClick={() => setAdding(false)}\n sx={{ mr: 2 }}\n >\n <MdiIcon path={ICON_VARIANT_CLOSE.path} />\n <SrOnly>{'close drawer'}</SrOnly>\n </IconButton>\n <Typography variant=\"h6\" component=\"div\">\n {'Stop emailing an address'}\n </Typography>\n </>\n }\n appBarRight={\n <Button\n variant=\"outlined\"\n color=\"inherit\"\n onClick={() => setAdding(false)}\n >\n {'Cancel'}\n </Button>\n }\n >\n <Container gutterY>\n <Stack spacing={2}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Use this when somebody asks you to stop emailing them by ' +\n 'reply, by phone, or in person. They stay on your audiences ' +\n 'and keep every record you hold about them — this only stops ' +\n 'this site’s marketing email reaching them.'}\n </Typography>\n <TextField\n label=\"Email addresses\"\n value={addInput}\n onChange={(event) => setAddInput(event.target.value)}\n multiline\n minRows={3}\n fullWidth\n autoFocus\n helperText={\n 'One per line, or separated by commas. Up to 50 at a time.'\n }\n />\n <TextField\n label=\"Note (optional)\"\n value={addNote}\n onChange={(event) => setAddNote(event.target.value)}\n fullWidth\n helperText={\n 'How the request reached you. Kept with the entry as the ' +\n 'record that it was honored.'\n }\n slotProps={{ htmlInput: { maxLength: 200 } }}\n />\n <Alert severity=\"info\">\n {'Order confirmations, booking reminders and password resets ' +\n 'are unaffected. Somebody who asked to stop hearing from ' +\n 'your marketing still gets their receipt.'}\n </Alert>\n <Stack direction=\"row\" spacing={1} sx={{ justifyContent: 'flex-end' }}>\n <Button\n variant=\"contained\"\n disabled={busy || !addInput.trim()}\n onClick={() => void handleAdd()}\n >\n {'Add to suppression list'}\n </Button>\n </Stack>\n </Stack>\n </Container>\n </NavigationDrawerComponent>\n </CardDisplay>\n )\n}\nSuppressionsCard.displayName = 'SuppressionsCard'\n\nexport default SuppressionsCard\n"],"names":["TransferResumeImport","pluginDocsHelp","useTransferLauncher","ICON_VARIANT_CLOSE","mdiEmailCheckOutline","mdiTrayArrowDown","mdiTrayArrowUp","CardDisplay","Container","MdiIcon","SrOnly","useConfirmationContext","ListFilterChips","ListPagination","ListQueryNotices","listQueryRefusals","ListRowActions","ListTable","listActionsColumn","listFilterGridColumns","TABLE_ROW_HEIGHT","useListGridFilter","NavigationDrawerComponent","useSnackbar","Alert","Chip","IconButton","Stack","TextField","Tooltip","Typography","Button","collection","deleteDoc","doc","useCallback","useEffect","useMemo","useState","useFirestore","useUser","useListQuery","authorizedFetch","SUPPRESSION_FILTER_HEADERS","SUPPRESSION_LIST_QUERY","describeSuppressionReason","describeReason","readSuppressionTotals","SUPPRESSION_REASONS","orgSiteName","useEmailOrgMount","SUPPRESSIONS_RESOURCE","SUPPRESSION_FILTER_OPTIONS","reason","Object","entries","map","value","described","label","SUPPRESSION_SELECT_FIELDS","onDate","row","seconds","createdAt","suppressedAt","Date","toISOString","slice","SuppressionsCard","props","hostId","firestore","data","user","enqueueSnackbar","confirm","orgMount","adding","setAdding","addInput","setAddInput","addNote","setAddNote","busy","setBusy","gridFilter","selectFields","rows","hasMore","page","setPage","pageSize","setPageSize","plan","declaration","request","clauses","search","searchWords","deps","idField","filtering","length","some","word","trim","transfer","exportFilter","filters","refusals","refused","fields","headers","options","totalsEpoch","setTotalsEpoch","totals","setTotals","active","then","read","catch","handleAdd","typed","response","method","body","JSON","stringify","emails","note","payload","json","ok","error","variant","results","added","Number","rejected","filter","result","refusal","input","join","persist","epoch","console","isBlockedPlatformWide","email","platform","handleRemove","toLowerCase","alsoPlatform","accepted","title","description","confirmationText","confirmationButtonProps","color","$id","columns","field","headerName","flex","minWidth","renderCell","width","valueGetter","_value","String","direction","spacing","sx","alignItems","height","size","carriedFromHostId","items","key","icon","path","destructive","onClick","header","help","anchor","contentGutterX","contentGutterY","contentBordered","HeaderProps","action","can","resource","scope","startIcon","openExport","target","onFinished","openImport","flexWrap","total","onChange","setClauses","notices","aria-label","rowHeight","hideFooter","filterMode","filterModel","onFilterModelChange","quickFilter","disableColumnSorting","noRowsLabel","rowCount","onPageChange","onPageSizeChange","count","values","reduce","a","b","undefined","open","onClose","AppBarProps","appBarLeft","edge","mr","component","appBarRight","gutterY","event","multiline","minRows","fullWidth","autoFocus","helperText","slotProps","htmlInput","maxLength","severity","justifyContent","disabled","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,oBAAoB,QAAQ,gDAA+C;AACpF,SAASC,cAAc,QAAQ,eAAc;AAC7C,SAASC,mBAAmB,QAAQ,mDAAkD;AACtF,SAASC,kBAAkB,QAAQ,2BAA0B;AAC7D,SACEC,oBAAoB,EACpBC,gBAAgB,EAChBC,cAAc,QACT,yBAAwB;AAC/B,SACEC,WAAW,EACXC,SAAS,EACTC,OAAO,EACPC,MAAM,EACNC,sBAAsB,QACjB,uBAAsB;AAC7B,OAAOC,qBAAqB,8DAA6D;AACzF,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,OAAOC,oBACLC,iBAAiB,QACZ,+DAA8D;AACrE,SACEC,cAAc,EACdC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,SAASC,gBAAgB,QAAQ,8CAA6C;AAC9E,SAASC,iBAAiB,QAAQ,kDAAiD;AACnF;;;;;;;;;;CAUC,GACD,SAASC,yBAAyB,QAAQ,8DAA6D;AACvG,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,KAAK,EACLC,IAAI,EACJC,UAAU,EACVC,KAAK,EACLC,SAAS,EACTC,OAAO,EACPC,UAAU,QACL,gBAAe;AACtB,OAAOC,YAAY,uB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iJ,WAAU;gCAAMC,SAAS;gCAAGC,IAAI;oCAAEqE,gBAAgB;gCAAW;0CAClE,cAAA,KAACpN;oCACCyG,SAAQ;oCACR4G,UAAUhK,QAAQ,CAACJ,SAAS0B,IAAI;oCAChC8E,SAAS,IAAM,KAAK7D;8CAEnB;;;;;;;;;AAQjB;AACAtD,iBAAiBgL,WAAW,GAAG;AAE/B,eAAehL,iBAAgB"}
@@ -14,9 +14,8 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */ 'use client';
17
- import { _ as _extends } from "@swc/helpers/_/_extends";
18
17
  import { mergeSubscriptionTopics, normalizeSubscriptionTopic } from "@aglyn/aglyn";
19
- import { EMAIL_TOPICS_COLLECTION } from "../model/email-topic-catalog.js";
18
+ import { EMAIL_TOPICS_COLLECTION, emailTopicDocument } from "../model/email-topic-catalog.js";
20
19
  import { collection, deleteField, doc, limit, orderBy, query, setDoc } from "firebase/firestore";
21
20
  import { useMemo } from "react";
22
21
  import { useFirestore, useFirestoreCollection, useOrgDataScope } from "@aglyn/tenant-feature-instance";
@@ -44,13 +43,7 @@ import { useFirestore, useFirestoreCollection, useOrgDataScope } from "@aglyn/te
44
43
  * same call serves a custom topic and a built-in being retired for the first
45
44
  * time.
46
45
  */ export async function writeEmailTopic(firestore, scope, topic) {
47
- await setDoc(doc(firestore, scope[0], scope[1], EMAIL_TOPICS_COLLECTION, topic.id), _extends({
48
- name: topic.name,
49
- description: topic.description,
50
- archived: topic.archived
51
- }, topic.doubleOptIn === undefined ? {} : {
52
- doubleOptIn: topic.doubleOptIn === null ? deleteField() : topic.doubleOptIn
53
- }), {
46
+ await setDoc(doc(firestore, scope[0], scope[1], EMAIL_TOPICS_COLLECTION, topic.id), emailTopicDocument(topic, deleteField()), {
54
47
  merge: true
55
48
  });
56
49
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/email/src/lib/components/use-org-email-topics.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'use client'\n\nimport {\n mergeSubscriptionTopics,\n normalizeSubscriptionTopic,\n type SubscriptionTopic,\n} from '@aglyn/aglyn'\nimport { EMAIL_TOPICS_COLLECTION } from '../model/email-topic-catalog'\nimport type { Firestore } from 'firebase/firestore'\nimport {\n collection,\n deleteField,\n doc,\n limit,\n orderBy,\n query,\n setDoc,\n} from 'firebase/firestore'\nimport { useMemo } from 'react'\nimport {\n useFirestore,\n useFirestoreCollection,\n useOrgDataScope,\n} from '@aglyn/tenant-feature-instance'\n\n/**\n * Write one topic's document — the ONE writer of the topic catalog.\n *\n * Two surfaces change a topic: its own page, which edits the name and the\n * description, and the list card's row menu, which retires and restores. They\n * write the same document and have to agree about its shape, so the write\n * lives here rather than once in each.\n *\n * ## Why it is a complete statement and not a patch\n *\n * `archived` is written on every save rather than only when it changes. A\n * merge that omitted it would leave a restored topic carrying `archived: true`\n * from an earlier save — which reads on screen as restored and behaves as\n * retired, because the composer's picker and the recipient's preference page\n * both read the stored flag.\n *\n * ## Why a built-in saves the same way\n *\n * `DECLARED_SUBSCRIPTION_TOPICS` is the FLOOR of the catalog, not its initial\n * contents: the four built-ins have no stored document until somebody changes\n * one. `setDoc` at the built-in's own id is what creates the override, so the\n * same call serves a custom topic and a built-in being retired for the first\n * time.\n */\nexport async function writeEmailTopic(\n firestore: Firestore,\n scope: readonly [string, string],\n topic: {\n id: string\n name: string\n description: string\n archived: boolean\n /**\n * Whether this stream needs a confirmation click, or `null`/omitted for\n * \"whatever the site says\".\n *\n * The only field on this document with THREE states, which is why it is\n * the only one written conditionally: `archived` is written on every save\n * because a merge that omitted it would carry an old value forward, and a\n * `doubleOptIn` written on every save could never be un-chosen back to\n * the site default. `deleteField()` is what returns it, so clearing is a\n * real act rather than a value that happens to look like an absence.\n */\n doubleOptIn?: boolean | null\n },\n): Promise<void> {\n await setDoc(\n doc(firestore, scope[0], scope[1], EMAIL_TOPICS_COLLECTION, topic.id),\n {\n name: topic.name,\n description: topic.description,\n archived: topic.archived,\n ...(topic.doubleOptIn === undefined\n ? {}\n : {\n doubleOptIn:\n topic.doubleOptIn === null ? deleteField() : topic.doubleOptIn,\n }),\n },\n { merge: true },\n )\n}\n\n/**\n * How many stored topics one read fetches.\n *\n * A ceiling on the READ, not on the catalog. A preference page stops being a\n * preference page somewhere well before two hundred checkboxes, so an org that\n * reaches this has a different problem than a truncated list — and the read is\n * ordered, so what a merchant past it loses is the tail of the alphabet rather\n * than an arbitrary sample.\n */\nconst TOPIC_READ_CEILING = 200\n\n/**\n * The org's email topic catalog, as both the console card and the composer's\n * picker read it.\n *\n * ONE hook for both surfaces, because they have to agree: a topic the composer\n * offers must be one the preference page can render, and a topic the card\n * archives must leave the picker. Two reads of the same collection with two\n * different merge rules is how the composer comes to send a campaign under a\n * topic nobody can unsubscribe from.\n *\n * ORG-scoped, following `lists` (AGL-254) — see `subscription-topics.ts` for why the\n * definitions are org-shared while the recipient's opt-outs are per site.\n *\n * Ordered by the server rather than capped and re-sorted here (AGL-2501,\n * AGL-2292). `name` is safe to order on because every writer of this\n * collection is the topics card, which refuses to save a nameless topic —\n * `orderBy` DROPS documents that lack the field rather than mis-sorting them,\n * so that claim is about the writers and not a preference.\n */\nexport function useOrgEmailTopics(\n /** The site the catalog is read through, or `null` on the org page. */\n hostId: string | null,\n options?: {\n /**\n * Whether to read at all. Default true.\n *\n * For a caller whose only use of the catalog is a picker inside a control\n * somebody has to open — a create drawer, an edit drawer — where reading\n * on mount charges every reader of the list for a field none of them\n * asked for. A `false` here opens no listener, exactly as a null query\n * does, and the catalog reads as empty until it flips.\n */\n enabled?: boolean\n /**\n * The organization itself, for a caller mounted over the org rather than\n * under one of its sites. It skips the site's org lookup, and it is the\n * only way the catalog can be read with no site at all.\n */\n orgId?: string | null\n },\n): {\n topics: SubscriptionTopic[]\n /** `['orgs', orgId]`, or null until the org lookup settles. */\n scope: readonly [string, string] | null\n} {\n const firestore = useFirestore()\n const enabled = options?.enabled ?? true\n // The org lookup is async (AGL-1061): null until it settles, and null\n // forever for a host with no owning org. An explicit org is ready at once.\n const { scope } = useOrgDataScope({\n hostId: hostId || undefined,\n orgId: options?.orgId || undefined,\n })\n const { data: stored } = useFirestoreCollection<Record<string, unknown>>(\n () =>\n scope && enabled\n ? query(\n collection(firestore, scope[0], scope[1], EMAIL_TOPICS_COLLECTION),\n orderBy('name'),\n limit(TOPIC_READ_CEILING),\n )\n : null,\n [firestore, scope, enabled],\n { idField: '$id' },\n )\n const topics = useMemo(\n () =>\n mergeSubscriptionTopics(\n (stored ?? [])\n .map((doc) => normalizeSubscriptionTopic(String(doc['$id'] ?? ''), doc))\n .filter((topic): topic is SubscriptionTopic => !!topic),\n ),\n [stored],\n )\n return { topics, scope: scope as readonly [string, string] | null }\n}\n"],"names":["mergeSubscriptionTopics","normalizeSubscriptionTopic","EMAIL_TOPICS_COLLECTION","collection","deleteField","doc","limit","orderBy","query","setDoc","useMemo","useFirestore","useFirestoreCollection","useOrgDataScope","writeEmailTopic","firestore","scope","topic","id","name","description","archived","doubleOptIn","undefined","merge","TOPIC_READ_CEILING","useOrgEmailTopics","hostId","options","enabled","orgId","data","stored","idField","topics","map","String","filter"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,uBAAuB,EACvBC,0BAA0B,QAErB,eAAc;AACrB,SAASC,uBAAuB,QAAQ,kCAA8B;AAEtE,SACEC,UAAU,EACVC,WAAW,EACXC,GAAG,EACHC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,MAAM,QACD,qBAAoB;AAC3B,SAASC,OAAO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AlCJ,2BAA2BmC,QAAO/B,WAAAA,GAAG,CAAC,MAAM,YAAVA,WAAc,KAAKA;WAClEgC,MAAM,CAAC,CAACpB,QAAsC,CAAC,CAACA,SAEvD;QAACe;KAAO;IAEV,OAAO;QAAEE;QAAQlB,OAAOA;IAA0C;AACpE"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/email/src/lib/components/use-org-email-topics.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'use client'\n\nimport {\n mergeSubscriptionTopics,\n normalizeSubscriptionTopic,\n type SubscriptionTopic,\n} from '@aglyn/aglyn'\nimport { EMAIL_TOPICS_COLLECTION, emailTopicDocument } from '../model/email-topic-catalog'\nimport type { Firestore } from 'firebase/firestore'\nimport {\n collection,\n deleteField,\n doc,\n limit,\n orderBy,\n query,\n setDoc,\n} from 'firebase/firestore'\nimport { useMemo } from 'react'\nimport {\n useFirestore,\n useFirestoreCollection,\n useOrgDataScope,\n} from '@aglyn/tenant-feature-instance'\n\n/**\n * Write one topic's document — the ONE writer of the topic catalog.\n *\n * Two surfaces change a topic: its own page, which edits the name and the\n * description, and the list card's row menu, which retires and restores. They\n * write the same document and have to agree about its shape, so the write\n * lives here rather than once in each.\n *\n * ## Why it is a complete statement and not a patch\n *\n * `archived` is written on every save rather than only when it changes. A\n * merge that omitted it would leave a restored topic carrying `archived: true`\n * from an earlier save — which reads on screen as restored and behaves as\n * retired, because the composer's picker and the recipient's preference page\n * both read the stored flag.\n *\n * ## Why a built-in saves the same way\n *\n * `DECLARED_SUBSCRIPTION_TOPICS` is the FLOOR of the catalog, not its initial\n * contents: the four built-ins have no stored document until somebody changes\n * one. `setDoc` at the built-in's own id is what creates the override, so the\n * same call serves a custom topic and a built-in being retired for the first\n * time.\n */\nexport async function writeEmailTopic(\n firestore: Firestore,\n scope: readonly [string, string],\n topic: {\n id: string\n name: string\n description: string\n archived: boolean\n /**\n * Whether this stream needs a confirmation click, or `null`/omitted for\n * \"whatever the site says\".\n *\n * The only field on this document with THREE states, which is why it is\n * the only one written conditionally: `archived` is written on every save\n * because a merge that omitted it would carry an old value forward, and a\n * `doubleOptIn` written on every save could never be un-chosen back to\n * the site default. `deleteField()` is what returns it, so clearing is a\n * real act rather than a value that happens to look like an absence.\n */\n doubleOptIn?: boolean | null\n },\n): Promise<void> {\n await setDoc(\n doc(firestore, scope[0], scope[1], EMAIL_TOPICS_COLLECTION, topic.id),\n emailTopicDocument(topic, deleteField()),\n { merge: true },\n )\n}\n\n/**\n * How many stored topics one read fetches.\n *\n * A ceiling on the READ, not on the catalog. A preference page stops being a\n * preference page somewhere well before two hundred checkboxes, so an org that\n * reaches this has a different problem than a truncated list — and the read is\n * ordered, so what a merchant past it loses is the tail of the alphabet rather\n * than an arbitrary sample.\n */\nconst TOPIC_READ_CEILING = 200\n\n/**\n * The org's email topic catalog, as both the console card and the composer's\n * picker read it.\n *\n * ONE hook for both surfaces, because they have to agree: a topic the composer\n * offers must be one the preference page can render, and a topic the card\n * archives must leave the picker. Two reads of the same collection with two\n * different merge rules is how the composer comes to send a campaign under a\n * topic nobody can unsubscribe from.\n *\n * ORG-scoped, following `lists` (AGL-254) — see `subscription-topics.ts` for why the\n * definitions are org-shared while the recipient's opt-outs are per site.\n *\n * Ordered by the server rather than capped and re-sorted here (AGL-2501,\n * AGL-2292). `name` is safe to order on because every writer of this\n * collection is the topics card, which refuses to save a nameless topic —\n * `orderBy` DROPS documents that lack the field rather than mis-sorting them,\n * so that claim is about the writers and not a preference.\n */\nexport function useOrgEmailTopics(\n /** The site the catalog is read through, or `null` on the org page. */\n hostId: string | null,\n options?: {\n /**\n * Whether to read at all. Default true.\n *\n * For a caller whose only use of the catalog is a picker inside a control\n * somebody has to open — a create drawer, an edit drawer — where reading\n * on mount charges every reader of the list for a field none of them\n * asked for. A `false` here opens no listener, exactly as a null query\n * does, and the catalog reads as empty until it flips.\n */\n enabled?: boolean\n /**\n * The organization itself, for a caller mounted over the org rather than\n * under one of its sites. It skips the site's org lookup, and it is the\n * only way the catalog can be read with no site at all.\n */\n orgId?: string | null\n },\n): {\n topics: SubscriptionTopic[]\n /** `['orgs', orgId]`, or null until the org lookup settles. */\n scope: readonly [string, string] | null\n} {\n const firestore = useFirestore()\n const enabled = options?.enabled ?? true\n // The org lookup is async (AGL-1061): null until it settles, and null\n // forever for a host with no owning org. An explicit org is ready at once.\n const { scope } = useOrgDataScope({\n hostId: hostId || undefined,\n orgId: options?.orgId || undefined,\n })\n const { data: stored } = useFirestoreCollection<Record<string, unknown>>(\n () =>\n scope && enabled\n ? query(\n collection(firestore, scope[0], scope[1], EMAIL_TOPICS_COLLECTION),\n orderBy('name'),\n limit(TOPIC_READ_CEILING),\n )\n : null,\n [firestore, scope, enabled],\n { idField: '$id' },\n )\n const topics = useMemo(\n () =>\n mergeSubscriptionTopics(\n (stored ?? [])\n .map((doc) => normalizeSubscriptionTopic(String(doc['$id'] ?? ''), doc))\n .filter((topic): topic is SubscriptionTopic => !!topic),\n ),\n [stored],\n )\n return { topics, scope: scope as readonly [string, string] | null }\n}\n"],"names":["mergeSubscriptionTopics","normalizeSubscriptionTopic","EMAIL_TOPICS_COLLECTION","emailTopicDocument","collection","deleteField","doc","limit","orderBy","query","setDoc","useMemo","useFirestore","useFirestoreCollection","useOrgDataScope","writeEmailTopic","firestore","scope","topic","id","merge","TOPIC_READ_CEILING","useOrgEmailTopics","hostId","options","enabled","undefined","orgId","data","stored","idField","topics","map","String","filter"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SACEA,uBAAuB,EACvBC,0BAA0B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A0CA;mBAAlCL,2BAA2BgC,QAAO3B,WAAAA,GAAG,CAAC,MAAM,YAAVA,WAAc,KAAKA;WAClE4B,MAAM,CAAC,CAAChB,QAAsC,CAAC,CAACA,SAEvD;QAACW;KAAO;IAEV,OAAO;QAAEE;QAAQd,OAAOA;IAA0C;AACpE"}
@@ -0,0 +1,21 @@
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
+ * The package kind a site's own emails are listed as (AGL-3533) — the
19
+ * platform's, so a site package import names it and this plugin draws it.
20
+ */
21
+ export declare const SITE_EMAIL_PACKAGE_KIND = "emailTemplate";
@@ -0,0 +1,21 @@
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
+ * The package kind a site's own emails are listed as (AGL-3533) — the
18
+ * platform's, so a site package import names it and this plugin draws it.
19
+ */ export const SITE_EMAIL_PACKAGE_KIND = 'emailTemplate';
20
+
21
+ //# sourceMappingURL=site-package.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/email/src/lib/constants/site-package.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\n/**\n * The package kind a site's own emails are listed as (AGL-3533) — the\n * platform's, so a site package import names it and this plugin draws it.\n */\nexport const SITE_EMAIL_PACKAGE_KIND = 'emailTemplate'\n"],"names":["SITE_EMAIL_PACKAGE_KIND"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;CAGC,GACD,OAAO,MAAMA,0BAA0B,gBAAe"}
@@ -14,6 +14,14 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
+ /**
18
+ * What this plugin imports and exports (AGL-3529), declared in
19
+ * `plugins.config.json` and answered here: one list's members, a site's
20
+ * suppression list, and the organization's email topics as workspace
21
+ * package items (AGL-3550). The console's transfer routes are the only
22
+ * callers, so the tenant does not register them.
23
+ */
24
+ export declare function registerEmailTransferResources(): void;
17
25
  /**
18
26
  * The email plugin's CONSOLE-ONLY server declarations (AGL-3305), named under
19
27
  * `consoleServerDeclarations` in `plugins.config.json` and run at the
@@ -27,5 +35,9 @@
27
35
  *
28
36
  * Light at boot: the module that does the work is imported the first time a
29
37
  * stream is reopened.
38
+ *
39
+ * It also answers what this plugin imports and exports
40
+ * ({@link registerEmailTransferResources}), whose only callers are the
41
+ * console's transfer routes.
30
42
  */
31
43
  export declare function registerEmailConsoleServerDeclarations(): void;
@@ -1,3 +1,4 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
1
2
  /**
2
3
  * @license
3
4
  * Copyright 2026 Aglyn LLC
@@ -16,7 +17,68 @@
16
17
  */ // The registry's own module, not the `@aglyn/aglyn/server` barrel: boot needs
17
18
  // one registry, not the whole server surface.
18
19
  import { registerPluginEmailStreams } from "@aglyn/aglyn/plugin-manager/plugin-email-streams";
20
+ import { registerPluginPersonEraser } from "@aglyn/aglyn/plugin-manager/plugin-person-erasure";
21
+ import { registerPluginTransferResource } from "@aglyn/aglyn/plugin-manager/plugin-transfer-resources";
19
22
  import { BUNDLE_ID } from "./constants/bundle-common.js";
23
+ import { LIST_MEMBER_ALIASES, LIST_MEMBER_LOCKED_RULES, LIST_MEMBER_MATCH_KEYS, LIST_MEMBERS_RESOURCE, listMemberCatalog, SUPPRESSION_ALIASES, SUPPRESSION_LOCKED_RULES, SUPPRESSION_MATCH_KEYS, SUPPRESSIONS_RESOURCE, suppressionCatalog } from "./transfer/email-transfer-catalog.js";
24
+ import { EMAIL_TOPIC_PACKAGE_RULES, EMAIL_TOPICS_TRANSFER_KEY, emailTopicDependencies, emailTopicPackageContent, remapEmailTopicIds } from "./transfer/topics-package.js";
25
+ /** The topics package's server half (AGL-3550), loaded when an import or export first asks. */ const topicsPackage = async ()=>(await import("./transfer/topics-package.server.js")).createEmailTopicsPackage();
26
+ /**
27
+ * A resource's reads and writes, loaded the first time a transfer asks: the
28
+ * catalog, the keys and the rules are this light module's, and the hooks
29
+ * that touch Firestore are imported on first use.
30
+ */ function lazyTransferHooks(load) {
31
+ return {
32
+ count: async (ctx, options)=>{
33
+ var _ref;
34
+ var _count, _this;
35
+ return (_ref = (_count = (_this = await load()).count) == null ? void 0 : _count.call(_this, ctx, options)) != null ? _ref : 0;
36
+ },
37
+ readPage: async (ctx, cursor, fieldIds, options)=>(await load()).readPage(ctx, cursor, fieldIds, options),
38
+ lookup: async (ctx, requests)=>(await load()).lookup(ctx, requests),
39
+ apply: async (ctx, chunk, writer)=>(await load()).apply(ctx, chunk, writer),
40
+ revert: async (ctx, snapshot, decisions)=>(await load()).revert(ctx, snapshot, decisions)
41
+ };
42
+ }
43
+ /**
44
+ * What this plugin imports and exports (AGL-3529), declared in
45
+ * `plugins.config.json` and answered here: one list's members, a site's
46
+ * suppression list, and the organization's email topics as workspace
47
+ * package items (AGL-3550). The console's transfer routes are the only
48
+ * callers, so the tenant does not register them.
49
+ */ export function registerEmailTransferResources() {
50
+ registerPluginTransferResource(LIST_MEMBERS_RESOURCE, _extends({
51
+ fields: ()=>listMemberCatalog(),
52
+ matchKeys: LIST_MEMBER_MATCH_KEYS,
53
+ aliases: LIST_MEMBER_ALIASES,
54
+ lockedRules: ()=>LIST_MEMBER_LOCKED_RULES
55
+ }, lazyTransferHooks(async ()=>(await import("./transfer/list-members.server.js")).listMembersTransferResource), {
56
+ // The list import's own dry run: the contact columns and the screening.
57
+ plan: async (ctx, input)=>(await import("./transfer/list-members.server.js")).planListMembers(ctx, input)
58
+ }), {
59
+ pluginId: BUNDLE_ID
60
+ });
61
+ registerPluginTransferResource(SUPPRESSIONS_RESOURCE, _extends({
62
+ fields: ()=>suppressionCatalog(),
63
+ matchKeys: SUPPRESSION_MATCH_KEYS,
64
+ aliases: SUPPRESSION_ALIASES,
65
+ lockedRules: ()=>SUPPRESSION_LOCKED_RULES
66
+ }, lazyTransferHooks(async ()=>(await import("./transfer/suppressions.server.js")).suppressionsTransferResource)), {
67
+ pluginId: BUNDLE_ID
68
+ });
69
+ registerPluginTransferResource(EMAIL_TOPICS_TRANSFER_KEY, {
70
+ items: async (ctx)=>(await topicsPackage()).items(ctx),
71
+ dependencies: ()=>emailTopicDependencies(),
72
+ remapIds: (item)=>remapEmailTopicIds(emailTopicPackageContent(item)),
73
+ readItems: async (ctx, ids)=>(await topicsPackage()).readItems(ctx, ids),
74
+ writeItems: async (ctx, items, writer)=>(await topicsPackage()).writeItems(ctx, items, writer),
75
+ revertItems: async (ctx, steps)=>(await topicsPackage()).revertItems(ctx, steps),
76
+ problems: async (ctx, write)=>(await topicsPackage()).problems(ctx, write),
77
+ rules: EMAIL_TOPIC_PACKAGE_RULES
78
+ }, {
79
+ pluginId: BUNDLE_ID
80
+ });
81
+ }
20
82
  /**
21
83
  * The email plugin's CONSOLE-ONLY server declarations (AGL-3305), named under
22
84
  * `consoleServerDeclarations` in `plugins.config.json` and run at the
@@ -30,6 +92,10 @@ import { BUNDLE_ID } from "./constants/bundle-common.js";
30
92
  *
31
93
  * Light at boot: the module that does the work is imported the first time a
32
94
  * stream is reopened.
95
+ *
96
+ * It also answers what this plugin imports and exports
97
+ * ({@link registerEmailTransferResources}), whose only callers are the
98
+ * console's transfer routes.
33
99
  */ export function registerEmailConsoleServerDeclarations() {
34
100
  // The registry replaces this plugin's earlier entry, so a second call (a
35
101
  // hot reload, a spec) is harmless.
@@ -38,6 +104,13 @@ import { BUNDLE_ID } from "./constants/bundle-common.js";
38
104
  }, {
39
105
  pluginId: BUNDLE_ID
40
106
  });
107
+ // The email plugin's share of a person erasure (AGL-2623, AGL-3080): the
108
+ // person comes off every audience list. Required, and loaded with the first
109
+ // erasure.
110
+ registerPluginPersonEraser(async (request)=>(await import("./server/person-eraser.js")).emailPersonEraser(request), {
111
+ pluginId: BUNDLE_ID
112
+ });
113
+ registerEmailTransferResources();
41
114
  }
42
115
 
43
116
  //# sourceMappingURL=declarations.console-server.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/email/src/lib/declarations.console-server.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\n// The registry's own module, not the `@aglyn/aglyn/server` barrel: boot needs\n// one registry, not the whole server surface.\nimport { registerPluginEmailStreams } from '@aglyn/aglyn/plugin-manager/plugin-email-streams'\nimport { BUNDLE_ID } from './constants/bundle-common'\n\n/**\n * The email plugin's CONSOLE-ONLY server declarations (AGL-3305), named under\n * `consoleServerDeclarations` in `plugins.config.json` and run at the\n * console's boot.\n *\n * It fills `plugin-email-streams`: when an account's answer about product\n * updates turns back to yes in the console, core asks this plugin to reopen\n * that one stream on the marketing site, over this plugin's topic catalog.\n * The only caller is a console route, so the tenant — which serves the public\n * internet — does not register it.\n *\n * Light at boot: the module that does the work is imported the first time a\n * stream is reopened.\n */\nexport function registerEmailConsoleServerDeclarations(): void {\n // The registry replaces this plugin's earlier entry, so a second call (a\n // hot reload, a spec) is harmless.\n registerPluginEmailStreams(\n {\n rejoin: async (request) => (await import('./server')).rejoinStreamForAccount(request),\n },\n { pluginId: BUNDLE_ID },\n )\n}\n"],"names":["registerPluginEmailStreams","BUNDLE_ID","registerEmailConsoleServerDeclarations","rejoin","request","rejoinStreamForAccount","pluginId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,8CAA8C;AAC9C,SAASA,0BAA0B,QAAQ,mDAAkD;AAC7F,SAASC,SAAS,QAAQ,+BAA2B;AAErD;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC;IACd,yEAAyE;IACzE,mCAAmC;IACnCF,2BACE;QACEG,QAAQ,OAAOC,UAAY,AAAC,CAAA,MAAM,MAAM,CAAC,cAAU,EAAGC,sBAAsB,CAACD;IAC/E,GACA;QAAEE,UAAUL;IAAU;AAE1B"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/email/src/lib/declarations.console-server.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\n// The registry's own module, not the `@aglyn/aglyn/server` barrel: boot needs\n// one registry, not the whole server surface.\nimport { registerPluginEmailStreams } from '@aglyn/aglyn/plugin-manager/plugin-email-streams'\nimport { registerPluginPersonEraser } from '@aglyn/aglyn/plugin-manager/plugin-person-erasure'\nimport {\n registerPluginTransferResource,\n type TransferRecordsHooks,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport {\n LIST_MEMBER_ALIASES,\n LIST_MEMBER_LOCKED_RULES,\n LIST_MEMBER_MATCH_KEYS,\n LIST_MEMBERS_RESOURCE,\n listMemberCatalog,\n SUPPRESSION_ALIASES,\n SUPPRESSION_LOCKED_RULES,\n SUPPRESSION_MATCH_KEYS,\n SUPPRESSIONS_RESOURCE,\n suppressionCatalog,\n} from './transfer/email-transfer-catalog'\nimport {\n EMAIL_TOPIC_PACKAGE_RULES,\n EMAIL_TOPICS_TRANSFER_KEY,\n emailTopicDependencies,\n emailTopicPackageContent,\n remapEmailTopicIds,\n} from './transfer/topics-package'\n\n/** The topics package's server half (AGL-3550), loaded when an import or export first asks. */\nconst topicsPackage = async () => (await import('./transfer/topics-package.server')).createEmailTopicsPackage()\n\n/**\n * A resource's reads and writes, loaded the first time a transfer asks: the\n * catalog, the keys and the rules are this light module's, and the hooks\n * that touch Firestore are imported on first use.\n */\nfunction lazyTransferHooks(\n load: () => Promise<TransferRecordsHooks>,\n): Pick<TransferRecordsHooks, 'count' | 'readPage' | 'lookup' | 'apply' | 'revert'> {\n return {\n count: async (ctx, options) => ((await load()).count?.(ctx, options) ?? 0),\n readPage: async (ctx, cursor, fieldIds, options) => (await load()).readPage(ctx, cursor, fieldIds, options),\n lookup: async (ctx, requests) => (await load()).lookup(ctx, requests),\n apply: async (ctx, chunk, writer) => (await load()).apply(ctx, chunk, writer),\n revert: async (ctx, snapshot, decisions) => (await load()).revert(ctx, snapshot, decisions),\n }\n}\n\n/**\n * What this plugin imports and exports (AGL-3529), declared in\n * `plugins.config.json` and answered here: one list's members, a site's\n * suppression list, and the organization's email topics as workspace\n * package items (AGL-3550). The console's transfer routes are the only\n * callers, so the tenant does not register them.\n */\nexport function registerEmailTransferResources(): void {\n registerPluginTransferResource(\n LIST_MEMBERS_RESOURCE,\n {\n fields: () => listMemberCatalog(),\n matchKeys: LIST_MEMBER_MATCH_KEYS,\n aliases: LIST_MEMBER_ALIASES,\n lockedRules: () => LIST_MEMBER_LOCKED_RULES,\n ...lazyTransferHooks(async () => (await import('./transfer/list-members.server')).listMembersTransferResource),\n // The list import's own dry run: the contact columns and the screening.\n plan: async (ctx, input) => (await import('./transfer/list-members.server')).planListMembers(ctx, input),\n },\n { pluginId: BUNDLE_ID },\n )\n registerPluginTransferResource(\n SUPPRESSIONS_RESOURCE,\n {\n fields: () => suppressionCatalog(),\n matchKeys: SUPPRESSION_MATCH_KEYS,\n aliases: SUPPRESSION_ALIASES,\n lockedRules: () => SUPPRESSION_LOCKED_RULES,\n ...lazyTransferHooks(async () => (await import('./transfer/suppressions.server')).suppressionsTransferResource),\n },\n { pluginId: BUNDLE_ID },\n )\n registerPluginTransferResource(\n EMAIL_TOPICS_TRANSFER_KEY,\n {\n items: async (ctx) => (await topicsPackage()).items(ctx),\n dependencies: () => emailTopicDependencies(),\n remapIds: (item) => remapEmailTopicIds(emailTopicPackageContent(item)),\n readItems: async (ctx, ids) => (await topicsPackage()).readItems(ctx, ids),\n writeItems: async (ctx, items, writer) => (await topicsPackage()).writeItems(ctx, items as never, writer),\n revertItems: async (ctx, steps) => (await topicsPackage()).revertItems(ctx, steps as never),\n problems: async (ctx, write) => (await topicsPackage()).problems(ctx, write as never),\n rules: EMAIL_TOPIC_PACKAGE_RULES,\n },\n { pluginId: BUNDLE_ID },\n )\n}\n\n/**\n * The email plugin's CONSOLE-ONLY server declarations (AGL-3305), named under\n * `consoleServerDeclarations` in `plugins.config.json` and run at the\n * console's boot.\n *\n * It fills `plugin-email-streams`: when an account's answer about product\n * updates turns back to yes in the console, core asks this plugin to reopen\n * that one stream on the marketing site, over this plugin's topic catalog.\n * The only caller is a console route, so the tenant — which serves the public\n * internet — does not register it.\n *\n * Light at boot: the module that does the work is imported the first time a\n * stream is reopened.\n *\n * It also answers what this plugin imports and exports\n * ({@link registerEmailTransferResources}), whose only callers are the\n * console's transfer routes.\n */\nexport function registerEmailConsoleServerDeclarations(): void {\n // The registry replaces this plugin's earlier entry, so a second call (a\n // hot reload, a spec) is harmless.\n registerPluginEmailStreams(\n {\n rejoin: async (request) => (await import('./server')).rejoinStreamForAccount(request),\n },\n { pluginId: BUNDLE_ID },\n )\n // The email plugin's share of a person erasure (AGL-2623, AGL-3080): the\n // person comes off every audience list. Required, and loaded with the first\n // erasure.\n registerPluginPersonEraser(\n async (request) => (await import('./server/person-eraser')).emailPersonEraser(request),\n { pluginId: BUNDLE_ID },\n )\n registerEmailTransferResources()\n}\n"],"names":["registerPluginEmailStreams","registerPluginPersonEraser","registerPluginTransferResource","BUNDLE_ID","LIST_MEMBER_ALIASES","LIST_MEMBER_LOCKED_RULES","LIST_MEMBER_MATCH_KEYS","LIST_MEMBERS_RESOURCE","listMemberCatalog","SUPPRESSION_ALIASES","SUPPRESSION_LOCKED_RULES","SUPPRESSION_MATCH_KEYS","SUPPRESSIONS_RESOURCE","suppressionCatalog","EMAIL_TOPIC_PACKAGE_RULES","EMAIL_TOPICS_TRANSFER_KEY","emailTopicDependencies","emailTopicPackageContent","remapEmailTopicIds","topicsPackage","createEmailTopicsPackage","lazyTransferHooks","load","count","ctx","options","readPage","cursor","fieldIds","lookup","requests","apply","chunk","writer","revert","snapshot","decisions","registerEmailTransferResources","fields","matchKeys","aliases","lockedRules","listMembersTransferResource","plan","input","planListMembers","pluginId","suppressionsTransferResource","items","dependencies","remapIds","item","readItems","ids","writeItems","revertItems","steps","problems","write","rules","registerEmailConsoleServer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