@aglyn/aglyn 1.0.0-beta.261 → 1.0.0-beta.262

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/operator-alerts.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { AglynNotificationType, NotificationLevel } from './notifications'\n\n/**\n * OPERATOR ALERTS (AGL-3377): the events whoever runs an install must hear\n * about, as one typed catalog.\n *\n * Every alert is an entry here (or a plugin's entry in the same shape,\n * registered through `@aglyn/aglyn/plugin-manager/operator-alerts`) and is\n * raised through ONE server entry point, `raiseOperatorAlert` in\n * `@aglyn/tenant-data-admin/server/operator-alerts`. That entry point writes\n * the staff console notification, dedupes a flapping condition, honours the\n * per-type switches staff set on Staff → Operator alerts, and delivers by\n * email (the `operator-alert` system email) and the optional out-of-band\n * webhook. No call site composes or sends its own mail.\n *\n * The catalog holds nothing install-specific: no address, no domain, no\n * host. Recipients come from `resolveStaffAlertRecipients()` and the webhook\n * from `OPERATOR_ALERT_WEBHOOK_URL`, so an entry reads the same on aglyn.com,\n * on a self-hosted install and in an OSS consumer's deployment.\n *\n * Copy is written against merge tokens (`{{orgId}}`), filled from the\n * `context` the call site passes. A token the call site did not supply is\n * blanked, so every sentence must still read when its optional tokens are\n * empty. Never put a data subject's address or other personal data into a\n * context: the alert travels to an inbox and a webhook, not only the console.\n */\n\n/**\n * How much an alert matters.\n *\n * - `must` — money moving with nobody looking, a legal duty unmet, data not\n * protected or not erased. On and immediate unless staff change it.\n * - `should` — a fault an operator wants to know about today.\n * - `low` — routine review work; on, and batched into the daily digest.\n */\nexport type OperatorAlertTier = 'must' | 'should' | 'low'\n\nexport type OperatorAlertCategory =\n | 'billing'\n | 'payments'\n | 'legal'\n | 'data'\n | 'ops'\n | 'deliverability'\n | 'security'\n | 'support'\n\n/** `digest` batches the alert into the once-a-day operator digest. */\nexport type OperatorAlertDelivery = 'immediate' | 'digest'\n\nexport interface OperatorAlertDefinition {\n /**\n * Stable id, also the key of its settings row. Never rename: staff\n * switches are stored under it. A plugin's types start with its plugin id\n * and a dot (`commerce.taxNotReversed`).\n */\n type: string\n /** The settings row's name. */\n label: string\n /** What it means and the first thing to do, for the settings page. */\n description: string\n tier: OperatorAlertTier\n category: OperatorAlertCategory\n /** The notification title and email subject, with `{{tokens}}`. */\n title: string\n /** What happened and what to do, with `{{tokens}}`. */\n body: string\n /** Console path the alert opens, with `{{tokens}}`; the call may override. */\n link?: string\n /** The coded default; staff may change it. */\n delivery: OperatorAlertDelivery\n /**\n * How long one `dedupeKey` stays quiet after it fired, in minutes. A\n * condition that flaps inside the window is told once. `0` never dedupes.\n * A call without a `dedupeKey` is never deduped.\n */\n dedupeWindowMinutes: number\n /**\n * Fire only once the same `dedupeKey` has been raised this many times\n * inside the window — for an endpoint any stranger can hit, where one\n * refused request is noise and several are a broken secret. Default 1.\n */\n minOccurrences?: number\n /** The coded default; staff may change it. */\n defaultEnabled: boolean\n /**\n * The console notification's type. Absent is the generic\n * `system.operatorAlert`; a type that already had its own notification\n * keeps it, so its icon, label and everyone's mutes are unchanged.\n */\n notificationType?: AglynNotificationType\n /**\n * How loud its console notification is drawn (AGL-3437). Absent, the\n * tier answers — see {@link operatorAlertLevel}. Set where the tone and\n * the importance part ways: a recovery is worth hearing about and is good\n * news, and a degraded check is a must-know that is not yet an outage.\n */\n level?: NotificationLevel\n /** The plugin that contributed it; absent for core's own. */\n pluginId?: string\n}\n\n/** Values a call site passes for an alert's `{{tokens}}`. */\nexport type OperatorAlertContext = Readonly<\n Record<string, string | number | boolean | null | undefined>\n>\n\n/** The notification type an alert without its own writes under. */\nexport const OPERATOR_ALERT_DEFAULT_NOTIFICATION_TYPE: AglynNotificationType =\n 'system.operatorAlert'\n\nexport const OPERATOR_ALERT_TIER_LABELS: Record<OperatorAlertTier, string> = {\n must: 'Must know',\n should: 'Should know',\n low: 'Routine',\n}\n\n/**\n * The level an alert's notification is drawn at when its entry names none:\n * a must-know is red, a should-know amber, routine review work informational.\n */\nexport const OPERATOR_ALERT_TIER_LEVELS: Record<\n OperatorAlertTier,\n NotificationLevel\n> = {\n must: 'critical',\n should: 'warning',\n low: 'info',\n}\n\n/** The level an alert's console notification carries (AGL-3437). */\nexport function operatorAlertLevel(\n definition: Pick<OperatorAlertDefinition, 'tier' | 'level'>,\n): NotificationLevel {\n return definition.level ?? OPERATOR_ALERT_TIER_LEVELS[definition.tier]\n}\n\nexport const OPERATOR_ALERT_CATEGORY_LABELS: Record<\n OperatorAlertCategory,\n string\n> = {\n billing: 'Billing',\n payments: 'Payments & payouts',\n legal: 'Legal',\n data: 'Data protection',\n ops: 'Operations',\n deliverability: 'Email deliverability',\n security: 'Security',\n support: 'Support',\n}\n\nconst DAY = 24 * 60\n\n/**\n * Core's alerts. Plugins contribute theirs through the plugin-manager\n * registry; nothing plugin-specific belongs in this list.\n */\nexport const CORE_OPERATOR_ALERTS: readonly OperatorAlertDefinition[] = [\n // ── Fraud, risk and legal duties already alerting before AGL-3377 ──────\n {\n type: 'system.abuseReportUrgent',\n label: 'Urgent abuse, fraud or risk alert',\n description:\n 'Phishing, malware or CSAM reported on a site, card testing, a flagged or disputed payment, a held phishing email, a seller under review. Review it on Staff → Abuse reports.',\n tier: 'must',\n category: 'security',\n title: '{{title}}',\n body: '{{body}}',\n link: '/admin/abuse-reports',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'system.abuseReportUrgent',\n },\n {\n // The one lock no person placed (AGL-3450): staff confirm it before the\n // customer's appeal arrives, and re-place it as `abuse` or lift it.\n type: 'security.pageSecurityHold',\n label: 'Automatic security hold on a new workspace',\n description:\n 'The page screen held a phishing page from a workspace in its first two weeks and locked the workspace, the site and the publishing account as security. Confirm it on Staff → Abuse reports, then re-place it as abuse on Staff → Lockdown, or lift it there if it is a false positive.',\n tier: 'must',\n category: 'security',\n title: 'Security hold placed on {{orgName}}',\n body:\n '{{page}} on {{siteName}} ({{hostId}}) was held for review: {{signal}} Locked as security, pending your review: {{locks}}. The abuse row is {{reference}}. Lift the hold, or re-place it as abuse, on Staff → Lockdown (/admin/lockdown).',\n link: '/admin/abuse-reports?report={{reviewId}}',\n delivery: 'immediate',\n // One hold per workspace; a repeat inside the day is the same event.\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n notificationType: 'system.abuseReportUrgent',\n },\n {\n type: 'security.paymentFraudHold',\n label: 'Automatic security hold for payment fraud',\n description:\n 'Stripe flagged a workspace\\'s own subscription payment as fraud — a Radar block at highest risk, a Stripe fraud report, three or more cards failing within 30 minutes, an early fraud warning or a Radar review. A new workspace that never paid is locked as security (takedown) with its subscriptions canceled; an older or paying one is not locked and needs a decision. Confirm it on Staff → Abuse reports, then re-place it as abuse on Staff → Lockdown, or lift it there.',\n tier: 'must',\n category: 'security',\n title: '{{action}}: {{orgName}}',\n body:\n '{{trigger}} on {{orgName}} ({{orgId}}). Charges: {{charges}}; cards: {{cards}}, issued in {{cardCountries}}. Locked: {{locks}}. The abuse row is {{reference}}. Lift it, or re-place it as abuse, on Staff → Lockdown (/admin/lockdown).',\n link: '/admin/abuse-reports?report={{reviewId}}',\n delivery: 'immediate',\n // One per workspace per window: every further card in the burst is the\n // same event, and the abuse row carries all of them.\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n notificationType: 'system.abuseReportUrgent',\n },\n {\n type: 'system.disputeUnattributed',\n label: 'Card dispute with no owner',\n description:\n 'A chargeback arrived that no subscription, order or marketplace purchase claimed, so nothing is answering it. Find the charge in Stripe and respond before the evidence deadline.',\n tier: 'must',\n category: 'billing',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'system.disputeUnattributed',\n },\n {\n type: 'system.dmcaCounterNotice',\n label: 'DMCA counter-notice',\n description:\n 'A customer contested a takedown. The statutory clock is already running; forward it to the complainant and restore on time unless they file suit.',\n tier: 'must',\n category: 'legal',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'system.dmcaCounterNotice',\n },\n {\n type: 'system.billingWebhookHalfApplied',\n label: 'Billing webhook half applied',\n description:\n 'A Stripe event threw after its handlers began, so its effects may be partly applied and Stripe will not retry it. Reconcile the event by hand.',\n tier: 'must',\n category: 'billing',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'system.billingWebhookHalfApplied',\n },\n\n // ── MUST: billing ───────────────────────────────────────────────────────\n {\n type: 'billing.platformDisputeLost',\n label: 'Subscription dispute lost',\n description:\n 'A card dispute on a workspace subscription closed as lost: the money has been taken back. Decide whether the workspace keeps its plan.',\n tier: 'must',\n category: 'billing',\n title: 'Subscription dispute lost on workspace {{orgId}}',\n body:\n 'The card dispute {{disputeId}} on invoice {{invoiceId}} for workspace {{orgName}} ({{orgId}}) closed as lost ({{reason}}), and {{amount}} was taken back. The workspace keeps its plan until somebody decides otherwise.',\n link: '/admin/orgs/{{orgId}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 30 * DAY,\n defaultEnabled: true,\n },\n {\n type: 'billing.orphanedSubscription',\n label: 'Stripe is billing a workspace that does not exist',\n description:\n 'A subscription names a workspace that was deleted or erased, so the customer keeps being charged for nothing. Cancel or refund it in Stripe.',\n tier: 'must',\n category: 'billing',\n title: 'Subscription bills a missing workspace',\n body:\n 'Stripe subscription {{subscriptionId}} (customer {{customerId}}, plan {{plan}}) names workspace {{orgId}}, which {{reason}}. The {{eventType}} event changed nothing. Cancel or refund it in Stripe.',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n {\n type: 'billing.usageNotReported',\n label: 'Metered usage not reported to Stripe',\n description:\n 'A closed month measured billable usage and it reached no invoice. Report it to Stripe by hand or the revenue is lost.',\n tier: 'must',\n category: 'billing',\n title: 'Usage for {{month}} not billed on {{orgId}}',\n body:\n 'The closed month {{month}} measured {{amount}} of billable usage on workspace {{orgName}} ({{orgId}}), and it was not reported to Stripe ({{reason}}). Nothing will invoice it until somebody does.',\n link: '/admin/orgs/{{orgId}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 7 * DAY,\n defaultEnabled: true,\n },\n {\n type: 'billing.webhookSignatureRejected',\n label: 'Billing webhook failing its signature check',\n description:\n 'Repeated deliveries to the billing webhook were refused because their signature did not match. Usually a rolled signing secret: until it is fixed, Stripe cannot tell the install about money.',\n tier: 'must',\n category: 'billing',\n title: 'Billing webhook is refusing deliveries',\n body:\n 'The billing webhook refused several signed deliveries within six hours because their Stripe signature matched none of the configured secrets. If Stripe is the sender, its signing secret no longer matches this install’s, and no billing event is being applied.',\n link: '/admin/health',\n delivery: 'immediate',\n dedupeWindowMinutes: 6 * 60,\n minOccurrences: 3,\n defaultEnabled: true,\n },\n {\n type: 'billing.webhookInert',\n label: 'Billing webhook delivery moved nothing',\n description:\n 'Stripe delivered an event this install subscribed to, and no handler did anything with it. Usually a handler that stopped being registered.',\n tier: 'must',\n category: 'billing',\n title: 'A {{eventType}} delivery changed nothing',\n body:\n 'Stripe event {{eventId}} ({{eventType}}) was accepted and no handler acted on it. Check which handler stopped being registered, then replay the event.',\n link: '/admin/health',\n delivery: 'immediate',\n dedupeWindowMinutes: 6 * 60,\n defaultEnabled: true,\n },\n\n // ── MUST: data protection and records ───────────────────────────────────\n {\n type: 'data.personErasureFailed',\n label: 'Personal data erasure failed',\n description:\n 'A data subject’s erasure request failed. It will be retried, but the legal deadline keeps running: read the error and fix the cause.',\n tier: 'must',\n category: 'data',\n title: 'Erasure request {{requestId}} failed',\n body:\n 'The erasure request {{requestId}} on workspace {{orgName}} ({{orgId}}) failed (attempt {{attempt}}): {{error}}. The statutory deadline keeps running while it retries.',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n {\n type: 'data.orgErasureFailed',\n label: 'Workspace erasure failed',\n description:\n 'A workspace scheduled for erasure could not be erased. Its data is still held after the date it was promised gone.',\n tier: 'must',\n category: 'data',\n title: 'Workspace {{orgId}} could not be erased',\n body:\n 'The scheduled erasure of workspace {{orgName}} ({{orgId}}) did not complete: {{reason}}. It will be retried on the next run; its data is held until it succeeds.',\n link: '/admin/orgs/{{orgId}}',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n {\n type: 'data.backupExportFailed',\n label: 'Database export failed',\n description:\n 'The scheduled database export did not start. A stale export means the worst day has nothing to restore from.',\n tier: 'must',\n category: 'data',\n title: 'Database export failed',\n body:\n 'The scheduled database export did not start ({{reason}}). The last good export is getting older; check the service account’s export permission and the bucket.',\n link: '/admin/health',\n delivery: 'immediate',\n dedupeWindowMinutes: 12 * 60,\n defaultEnabled: true,\n },\n\n // ── MUST: legal ─────────────────────────────────────────────────────────\n {\n type: 'legal.abuseReportHigh',\n label: 'Takedown, impersonation or illegal-content report',\n description:\n 'A DMCA takedown, impersonation or illegal-content report. Each carries a response duty; review it on Staff → Abuse reports.',\n tier: 'must',\n category: 'legal',\n title: '{{category}} report on {{site}}',\n body:\n '{{site}} was reported for {{category}}. Reference {{reference}}. Review it and respond within the policy’s window.',\n link: '/admin/abuse-reports',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n },\n\n // ── MUST/SHOULD: health ─────────────────────────────────────────────────\n {\n type: 'system.healthDegraded',\n label: 'Health check degraded',\n description:\n 'A health check went from healthy to degraded: scheduled jobs silent, backups stale, billing deliveries failing, sign-ups refused, server errors, a site not rendering. Told once per incident.',\n tier: 'must',\n category: 'ops',\n title: '{{check}} is degraded',\n body: '{{check}} went from healthy to degraded. {{detail}}',\n link: '/admin/health',\n delivery: 'immediate',\n // Must-know, and still amber rather than red: degraded is not down.\n level: 'warning',\n // A check flapping across the line is told once an hour, not on\n // every swing.\n dedupeWindowMinutes: 60,\n defaultEnabled: true,\n },\n {\n // The post-deploy production canary (AGL-3567), raised from GitHub\n // Actions through `/api/admin/operator-alerts/canary`. Red because a\n // deploy that stops rendering pages is every published site down.\n type: 'ops.productionCanaryRed',\n label: 'Production canary failed after a deploy',\n description:\n 'Right after a tenant or console production deploy, uncached pages stopped rendering. The canary rolls the deploy back by itself when the failure holds across sites; after any rollback the next release must be promoted by hand.',\n tier: 'must',\n category: 'ops',\n title: '{{project}} production canary: {{outcome}}',\n body: '{{detail}}',\n link: '/admin/health',\n delivery: 'immediate',\n level: 'critical',\n // The caller dedupes per deployment and verdict; this only stops a\n // re-run of the same red run from telling it twice.\n dedupeWindowMinutes: 30,\n defaultEnabled: true,\n },\n {\n type: 'system.healthRecovered',\n label: 'Health check recovered',\n description: 'A degraded health check is healthy again.',\n tier: 'should',\n category: 'ops',\n title: '{{check}} recovered',\n body: '{{check}} is healthy again after {{duration}}.',\n link: '/admin/health',\n delivery: 'immediate',\n level: 'success',\n // A check flapping across the line is told once an hour, not on\n // every swing.\n dedupeWindowMinutes: 60,\n defaultEnabled: true,\n },\n {\n // The render monitor (AGL-3568): a published site fetched over HTTP, on\n // pages no cache can answer, failed several runs in a row. Red, not the\n // amber of a degraded check: every visitor without a cached copy is\n // getting an error page or a timeout right now.\n type: 'system.siteRenderFailing',\n label: 'Published site not rendering pages',\n description:\n 'The render monitor asked a published site for pages no cache can answer, several runs in a row, and got no complete page back. Visitors to cached pages may still see them, so the site can look up while every other page fails. Check the latest site runtime deployment first and roll it back if it just shipped.',\n tier: 'must',\n category: 'ops',\n title: 'Pages are not rendering on {{site}}',\n body:\n '{{site}} failed {{failures}} render checks in a row, over {{since}}. {{detail}} Cached pages may still load, so the site can look up while new renders fail.',\n link: '/admin/health',\n delivery: 'immediate',\n // Told once per outage: the monitor raises it on the edge, and the\n // window only covers a site flapping across the line.\n dedupeWindowMinutes: 30,\n defaultEnabled: true,\n },\n {\n type: 'system.siteRenderRecovered',\n label: 'Published site rendering again',\n description:\n 'A published site the render monitor had reported as not rendering serves fresh pages again.',\n tier: 'should',\n category: 'ops',\n title: '{{site}} is rendering pages again',\n body: 'Fresh page renders on {{site}} pass again after {{duration}}.',\n link: '/admin/health',\n delivery: 'immediate',\n level: 'success',\n dedupeWindowMinutes: 30,\n defaultEnabled: true,\n },\n {\n // The render monitor could not see the site (AGL-3580): bot protection\n // answered every probe it made, so it knows nothing about whether pages\n // render. Not an outage, and never worded as one — on 2026-10-05 a\n // missing probe token read as \"pages are not rendering\" for three hours\n // while the site served pages. Amber: detection is off until it is fixed.\n type: 'system.renderMonitorBlind',\n label: 'Render monitor cannot see a site',\n description:\n 'Bot protection answered the render monitor instead of a published site, several runs in a row, so nothing is checking whether that site renders pages. The site itself may be fine. Check AGLYN_PROBE_TOKEN on the console and the \"CI and uptime probe bypass\" firewall rule on the site runtime.',\n tier: 'must',\n category: 'ops',\n title: 'The render monitor cannot see {{site}}',\n body:\n 'Bot protection answered instead of {{site}} for {{runs}} runs in a row, so nothing is checking its pages. {{detail}} This is not a verdict on the site.',\n link: '/admin/health',\n delivery: 'immediate',\n level: 'warning',\n dedupeWindowMinutes: 360,\n defaultEnabled: true,\n },\n\n // ── SHOULD: billing ─────────────────────────────────────────────────────\n {\n type: 'billing.autoLocked',\n label: 'Workspace billing locked automatically',\n description:\n 'A workspace crossed its spend guard and the platform locked its billable activity. Check it is not a false positive before the customer notices.',\n tier: 'should',\n category: 'billing',\n title: 'Billing locked on {{orgName}}',\n body:\n 'Workspace {{orgName}} ({{orgId}}) was locked automatically: {{reason}}.',\n link: '/admin/orgs/{{orgId}}',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n {\n type: 'billing.platformInvoiceUncollectible',\n label: 'Subscription invoice voided or uncollectible',\n description:\n 'A workspace invoice was voided or marked uncollectible: revenue the books expected is not coming.',\n tier: 'should',\n category: 'billing',\n title: 'Invoice {{status}} on {{orgId}}',\n body:\n 'Invoice {{invoiceId}} for {{amount}} on workspace {{orgName}} ({{orgId}}) was marked {{status}}, so Stripe has stopped collecting it.',\n link: '/admin/orgs/{{orgId}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 30 * DAY,\n defaultEnabled: true,\n },\n {\n type: 'billing.connectPayoutFailed',\n label: 'Connected account payout or transfer failed',\n description:\n 'Money due to a merchant or seller did not arrive. Stripe retries on its own schedule; a human decides what happens next.',\n tier: 'should',\n category: 'billing',\n title: 'A {{kind}} to {{account}} failed',\n body:\n 'A {{amount}} Stripe {{kind}} ({{stripeId}}) to connected account {{account}} ({{merchant}}) failed: {{reason}}. The merchant’s funds are not where the ledger says.',\n delivery: 'immediate',\n dedupeWindowMinutes: 30 * DAY,\n defaultEnabled: true,\n },\n {\n type: 'staff.paymentFailed',\n label: 'Workspace payment failed',\n description:\n 'A paying workspace’s renewal failed. Stripe is retrying; the customer has been told.',\n tier: 'should',\n category: 'billing',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'staff.paymentFailed',\n },\n\n // ── SHOULD: security ────────────────────────────────────────────────────\n {\n type: 'security.staffGranted',\n label: 'Staff access granted or raised',\n description:\n 'Somebody was made staff, or a staff role was raised. If nobody on the team did it, revoke it and rotate credentials.',\n tier: 'should',\n category: 'security',\n title: '{{target}} is now {{role}} staff',\n body: '{{actor}} granted {{target}} the {{role}} staff role (was {{previous}}).',\n link: '/admin/users',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n },\n\n // ── SHOULD: support ─────────────────────────────────────────────────────\n {\n type: 'support.slaBreached',\n label: 'Support ticket past its response time',\n description:\n 'A support ticket passed its promised response time without a staff reply.',\n tier: 'should',\n category: 'support',\n title: 'Ticket past its response time: {{subject}}',\n body:\n 'The {{tier}} ticket “{{subject}}” from workspace {{orgName}} ({{orgId}}) was due a first response {{overdue}} ago and has none.',\n // The ticket itself: the support page opens `?ticketId=` on load.\n link: '/admin/support?ticketId={{ticketId}}',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n {\n type: 'support.ticketOpened',\n label: 'New support ticket',\n description: 'A subscriber opened a support ticket.',\n tier: 'should',\n category: 'support',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'digest',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'support.ticketOpened',\n // A customer asking for help, not a fault.\n level: 'info',\n },\n {\n type: 'support.ticketReply',\n label: 'Support ticket reply',\n description: 'A subscriber replied on a support ticket.',\n tier: 'should',\n category: 'support',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'digest',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'support.ticketReply',\n level: 'info',\n },\n\n // ── SHOULD: deliverability ──────────────────────────────────────────────\n {\n type: 'deliverability.sendRateSaturated',\n label: 'Email send-rate governor saturated',\n description:\n 'The platform’s email send-rate budget is exhausted, so sends are being deferred. Raise the budget or find the sender filling it.',\n tier: 'should',\n category: 'deliverability',\n title: 'Email sending is being throttled',\n body:\n 'The {{scope}} send-rate budget is full ({{detail}}), so sends are being deferred.',\n link: '/admin/emails',\n delivery: 'immediate',\n dedupeWindowMinutes: 6 * 60,\n defaultEnabled: true,\n },\n {\n type: 'deliverability.sendRateUnavailable',\n label: 'Email send-rate governor unavailable',\n description:\n 'The send-rate governor could not read its counters, so mail is going out unmetered: nothing is holding the shared domains under their hourly ceiling.',\n tier: 'should',\n category: 'deliverability',\n title: 'Email send-rate governor unavailable',\n body:\n 'The send-rate governor could not read its counters ({{error}}), so sends are being allowed unmetered until it can.',\n link: '/admin/emails',\n delivery: 'immediate',\n dedupeWindowMinutes: 6 * 60,\n defaultEnabled: true,\n },\n {\n type: 'deliverability.gatewayBlocking',\n label: 'A recipient gateway is blocking the shared domain',\n description:\n 'A mail gateway is refusing mail from the shared sending domain, so everyone behind that gateway stops receiving it.',\n tier: 'should',\n category: 'deliverability',\n title: '{{gateway}} is blocking {{domain}}',\n body:\n 'Mail from {{domain}} is being refused by {{gateway}} ({{detail}}). Recipients behind that gateway are not receiving it.',\n link: '/admin/emails',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n {\n type: 'deliverability.providerCredentialsRejected',\n label: 'Email provider rejected the credentials',\n description:\n 'The email provider refused the API key, or a sending pool is unhealthy: invites, password resets and receipts are not leaving. The webhook channel is the one that still reaches you.',\n tier: 'should',\n category: 'deliverability',\n title: 'Email delivery is failing: {{problem}}',\n body: '{{detail}}',\n link: '/admin/emails',\n delivery: 'immediate',\n dedupeWindowMinutes: 6 * 60,\n defaultEnabled: true,\n },\n {\n // A purchasing ceiling, not a job failure: the provisioning sweep ran\n // and every site keeps sending, so the copy must not read as an outage.\n type: 'deliverability.sendingDomainCapacityFull',\n label: 'Sending-domain allowance full',\n description:\n 'Every dedicated sending domain the provider allowance covers is in use, so new sites that ask for one stay on the shared pool. No mail is lost; raise the allowance or move merchants onto domains they own.',\n tier: 'should',\n category: 'deliverability',\n title: 'Sending-domain allowance full ({{held}}/{{capacity}})',\n body:\n 'The sending-domain allowance is full ({{held}} of {{capacity}} in use), so sites that asked for a dedicated domain keep sending on the shared pool. No mail is lost: what they go without is the isolation a domain of their own buys, and their campaigns are held to the pool’s stricter reputation limits. Raise AGLYN_SENDING_DOMAIN_CAPACITY once the provider allowance covers it, or move merchants onto domains they own.',\n link: '/admin/emails',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n\n // ── SHOULD: operations ──────────────────────────────────────────────────\n {\n type: 'ops.reaperStuck',\n label: 'A reaper is stuck or failing',\n description:\n 'A cleanup job (sending domains, unverified workspaces) could not finish, so what it removes keeps accumulating.',\n tier: 'should',\n category: 'ops',\n title: '{{job}} is stuck',\n body: '{{job}} could not finish: {{detail}}',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n {\n type: 'ops.pluginJobFailed',\n label: 'A plugin job failed',\n description:\n 'A plugin’s scheduled job threw: consent-group changes, the publish outbox, sending-domain provisioning, a plugin cron.',\n tier: 'should',\n category: 'ops',\n // `job` is a noun phrase that reads as a subject on its own (\"The\n // publish outbox drain\", \"The scheduled job acme-mail-send\"), so the\n // title and the body open with the same words.\n title: '{{job}} failed',\n body: '{{job}} failed: {{error}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 6 * 60,\n defaultEnabled: true,\n },\n {\n // Nightly, so once a day per provider is every run it could report.\n type: 'ops.adAudienceSyncFailed',\n label: 'Ad audience sync failed',\n description:\n 'The nightly account-holder audience sync (AGL-3780) could not update a Meta, Google or LinkedIn audience, or held a run whose audience would have shrunk by more than half. The audience keeps what it last had; check the provider credentials, or run the sync with force once the drop is confirmed.',\n tier: 'should',\n category: 'ops',\n title: 'Ad audience sync: {{provider}} not updated',\n body: 'The {{provider}} account-holder audience was not updated: {{detail}}. It keeps what it was last sent, and the next nightly run tries again.',\n link: '/admin/flags',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n {\n type: 'system.pluginVerifierRegression',\n label: 'Plugin verifier regression',\n description:\n 'A live plugin version stopped passing the static verifier.',\n tier: 'should',\n category: 'security',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'system.pluginVerifierRegression',\n },\n {\n type: 'system.bandwidthCeilingTripped',\n label: 'Bandwidth ceiling reached',\n description:\n 'A site crossed the per-month bandwidth abuse ceiling.',\n tier: 'should',\n category: 'ops',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'system.bandwidthCeilingTripped',\n },\n\n // ── LOW ─────────────────────────────────────────────────────────────────\n {\n type: 'marketplace.review',\n label: 'Plugin listing waiting for review',\n description: 'A plugin listing or version was submitted for review.',\n tier: 'low',\n category: 'security',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'digest',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'marketplace.review',\n },\n {\n type: 'system.scopeDrift',\n label: 'Resources missing a sharing scope',\n description:\n 'The weekly sweep found documents invisible to every site-scoped read: a creation path forgot the field.',\n tier: 'low',\n category: 'data',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'digest',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'system.scopeDrift',\n },\n]\n\n/** An amount in minor units, as an alert prints it: `$12.40`. */\nexport function formatOperatorAlertAmount(\n cents: number,\n currency = 'usd',\n): string {\n const value = Number(cents) / 100\n if (!Number.isFinite(value)) return ''\n try {\n return new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: String(currency || 'usd').toUpperCase(),\n }).format(value)\n } catch {\n return `${value.toFixed(2)} ${String(currency).toUpperCase()}`\n }\n}\n\n/** Replaces each `{{token}}` with its context value, or nothing. */\nexport function renderOperatorAlertTemplate(\n template: string,\n context: OperatorAlertContext | undefined,\n): string {\n return String(template ?? '')\n .replace(/\\{\\{\\s*([\\w.]+)\\s*\\}\\}/g, (_match, name: string) => {\n const value = context?.[name]\n return value === null || value === undefined ? '' : String(value)\n })\n .replace(/\\(\\s*\\)/g, '')\n .replace(/[ \\t]{2,}/g, ' ')\n .replace(/ ([.,;:])/g, '$1')\n .trim()\n}\n\n/** A staff member's answer for one type; an absent key keeps the default. */\nexport interface OperatorAlertTypeSetting {\n enabled?: boolean\n delivery?: OperatorAlertDelivery\n}\n\n/** `platformSettings/operatorAlerts`, keyed by alert type. */\nexport interface OperatorAlertSettings {\n types?: Record<string, OperatorAlertTypeSetting>\n}\n\n/** Whether a type is on, and how it is delivered, after staff's answers. */\nexport function effectiveOperatorAlertSetting(\n definition: Pick<OperatorAlertDefinition, 'type' | 'delivery' | 'defaultEnabled'>,\n settings: OperatorAlertSettings | null | undefined,\n): { enabled: boolean; delivery: OperatorAlertDelivery } {\n const answer = settings?.types?.[definition.type]\n return {\n enabled:\n typeof answer?.enabled === 'boolean'\n ? answer.enabled\n : definition.defaultEnabled,\n delivery:\n answer?.delivery === 'immediate' || answer?.delivery === 'digest'\n ? answer.delivery\n : definition.delivery,\n }\n}\n\n/**\n * Staff notification types whose alert emails the operator on a coded\n * default of immediate (AGL-3375), derived from the catalog so there is one\n * list.\n */\nexport const OPERATOR_ALERT_NOTIFICATION_TYPES: ReadonlySet<string> = new Set(\n CORE_OPERATOR_ALERTS.flatMap((definition) =>\n definition.notificationType ? [definition.notificationType] : [],\n ),\n)\n"],"names":["OPERATOR_ALERT_DEFAULT_NOTIFICATION_TYPE","OPERATOR_ALERT_TIER_LABELS","must","should","low","OPERATOR_ALERT_TIER_LEVELS","operatorAlertLevel","definition","level","tier","OPERATOR_ALERT_CATEGORY_LABELS","billing","payments","legal","data","ops","deliverability","security","support","DAY","CORE_OPERATOR_ALERTS","type","label","description","category","title","body","link","delivery","dedupeWindowMinutes","defaultEnabled","notificationType","minOccurrences","formatOperatorAlertAmount","cents","currency","value","Number","isFinite","Intl","NumberFormat","style","String","toUpperCase","format","toFixed","renderOperatorAlertTemplate","template","context","replace","_match","name","undefined","trim","effectiveOperatorAlertSetting","settings","answer","types","enabled","OPERATOR_ALERT_NOTIFICATION_TYPES","Set","flatMap"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GA6GD,iEAAiE,GACjE,OAAO,MAAMA,2CACX,uBAAsB;AAExB,OAAO,MAAMC,6BAAgE;IAC3EC,MAAM;IACNC,QAAQ;IACRC,KAAK;AACP,EAAC;AAED;;;CAGC,GACD,OAAO,MAAMC,6BAGT;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VC,qBAAqB;QACrBC,gBAAgB;QAChBC,kBAAkB;IACpB;IACA;QACEV,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;QAChBC,kBAAkB;IACpB;IAEA,2EAA2E;IAC3E;QACEV,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB,KAAKV;QAC1BW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFE,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB,IAAIV;QACzBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB,IAAI;QACzBG,gBAAgB;QAChBF,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB,IAAI;QACzBC,gBAAgB;IAClB;IAEA,2EAA2E;IAC3E;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFE,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB,KAAK;QAC1BC,gBAAgB;IAClB;IAEA,2EAA2E;IAC3E;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;IAClB;IAEA,2EAA2E;IAC3E;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNC,MAAM;QACNC,UAAU;QACV,oEAAoE;QACpEpB,OAAO;QACP,gEAAgE;QAChE,eAAe;QACfqB,qBAAqB;QACrBC,gBAAgB;IAClB;IACA;QACE,mEAAmE;QACnE,qEAAqE;QACrE,kEAAkE;QAClET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNC,MAAM;QACNC,UAAU;QACVpB,OAAO;QACP,mEAAmE;QACnE,oDAAoD;QACpDqB,qBAAqB;QACrBC,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aAAa;QACbd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNC,MAAM;QACNC,UAAU;QACVpB,OAAO;QACP,gEAAgE;QAChE,eAAe;QACfqB,qBAAqB;QACrBC,gBAAgB;IAClB;IACA;QACE,wEAAwE;QACxE,wEAAwE;QACxE,oEAAoE;QACpE,gDAAgD;QAChDT,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACV,mEAAmE;QACnE,sDAAsD;QACtDC,qBAAqB;QACrBC,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNC,MAAM;QACNC,UAAU;QACVpB,OAAO;QACPqB,qBAAqB;QACrBC,gBAAgB;IAClB;IACA;QACE,uEAAuE;QACvE,wEAAwE;QACxE,mEAAmE;QACnE,wEAAwE;QACxE,0EAA0E;QAC1ET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVpB,OAAO;QACPqB,qBAAqB;QACrBC,gBAAgB;IAClB;IAEA,2EAA2E;IAC3E;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB,KAAKV;QAC1BW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFE,UAAU;QACVC,qBAAqB,KAAKV;QAC1BW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;QAChBC,kBAAkB;IACpB;IAEA,2EAA2E;IAC3E;QACEV,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNC,MAAM;QACNC,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;IAClB;IAEA,2EAA2E;IAC3E;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACF,kEAAkE;QAClEC,MAAM;QACNC,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aAAa;QACbd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;QAChBC,kBAAkB;QAClB,2CAA2C;QAC3CvB,OAAO;IACT;IACA;QACEa,MAAM;QACNC,OAAO;QACPC,aAAa;QACbd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;QAChBC,kBAAkB;QAClBvB,OAAO;IACT;IAEA,2EAA2E;IAC3E;QACEa,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB,IAAI;QACzBC,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB,IAAI;QACzBC,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNC,MAAM;QACNC,UAAU;QACVC,qBAAqB,IAAI;QACzBC,gBAAgB;IAClB;IACA;QACE,sEAAsE;QACtE,wEAAwE;QACxET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IAEA,2EAA2E;IAC3E;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACV,kEAAkE;QAClE,qEAAqE;QACrE,+CAA+C;QAC/CC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqB,IAAI;QACzBC,gBAAgB;IAClB;IACA;QACE,oEAAoE;QACpET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNC,MAAM;QACNC,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;QAChBC,kBAAkB;IACpB;IACA;QACEV,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;QAChBC,kBAAkB;IACpB;IAEA,2EAA2E;IAC3E;QACEV,MAAM;QACNC,OAAO;QACPC,aAAa;QACbd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;QAChBC,kBAAkB;IACpB;IACA;QACEV,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;QAChBC,kBAAkB;IACpB;CACD,CAAA;AAED,+DAA+D,GAC/D,OAAO,SAASE,0BACdC,KAAa,EACbC,WAAW,KAAK;IAEh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BAAgB;KAAC,GAAG,EAAE,GAEnE"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/operator-alerts.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { AglynNotificationType, NotificationLevel } from './notifications'\n\n/**\n * OPERATOR ALERTS (AGL-3377): the events whoever runs an install must hear\n * about, as one typed catalog.\n *\n * Every alert is an entry here (or a plugin's entry in the same shape,\n * registered through `@aglyn/aglyn/plugin-manager/operator-alerts`) and is\n * raised through ONE server entry point, `raiseOperatorAlert` in\n * `@aglyn/tenant-data-admin/server/operator-alerts`. That entry point writes\n * the staff console notification, dedupes a flapping condition, honours the\n * per-type switches staff set on Staff → Operator alerts, and delivers by\n * email (the `operator-alert` system email) and the optional out-of-band\n * webhook. No call site composes or sends its own mail.\n *\n * The catalog holds nothing install-specific: no address, no domain, no\n * host. Recipients come from `resolveStaffAlertRecipients()` and the webhook\n * from `OPERATOR_ALERT_WEBHOOK_URL`, so an entry reads the same on aglyn.com,\n * on a self-hosted install and in an OSS consumer's deployment.\n *\n * Copy is written against merge tokens (`{{orgId}}`), filled from the\n * `context` the call site passes. A token the call site did not supply is\n * blanked, so every sentence must still read when its optional tokens are\n * empty. Never put a data subject's address or other personal data into a\n * context: the alert travels to an inbox and a webhook, not only the console.\n */\n\n/**\n * How much an alert matters.\n *\n * - `must` — money moving with nobody looking, a legal duty unmet, data not\n * protected or not erased. On and immediate unless staff change it.\n * - `should` — a fault an operator wants to know about today.\n * - `low` — routine review work; on, and batched into the daily digest.\n */\nexport type OperatorAlertTier = 'must' | 'should' | 'low'\n\nexport type OperatorAlertCategory =\n | 'billing'\n | 'payments'\n | 'legal'\n | 'data'\n | 'ops'\n | 'deliverability'\n | 'security'\n | 'support'\n\n/** `digest` batches the alert into the once-a-day operator digest. */\nexport type OperatorAlertDelivery = 'immediate' | 'digest'\n\nexport interface OperatorAlertDefinition {\n /**\n * Stable id, also the key of its settings row. Never rename: staff\n * switches are stored under it. A plugin's types start with its plugin id\n * and a dot (`commerce.taxNotReversed`).\n */\n type: string\n /** The settings row's name. */\n label: string\n /** What it means and the first thing to do, for the settings page. */\n description: string\n tier: OperatorAlertTier\n category: OperatorAlertCategory\n /** The notification title and email subject, with `{{tokens}}`. */\n title: string\n /** What happened and what to do, with `{{tokens}}`. */\n body: string\n /** Console path the alert opens, with `{{tokens}}`; the call may override. */\n link?: string\n /** The coded default; staff may change it. */\n delivery: OperatorAlertDelivery\n /**\n * How long one `dedupeKey` stays quiet after it fired, in minutes. A\n * condition that flaps inside the window is told once. `0` never dedupes.\n * A call without a `dedupeKey` is never deduped.\n */\n dedupeWindowMinutes: number\n /**\n * Fire only once the same `dedupeKey` has been raised this many times\n * inside the window — for an endpoint any stranger can hit, where one\n * refused request is noise and several are a broken secret. Default 1.\n */\n minOccurrences?: number\n /** The coded default; staff may change it. */\n defaultEnabled: boolean\n /**\n * The console notification's type. Absent is the generic\n * `system.operatorAlert`; a type that already had its own notification\n * keeps it, so its icon, label and everyone's mutes are unchanged.\n */\n notificationType?: AglynNotificationType\n /**\n * How loud its console notification is drawn (AGL-3437). Absent, the\n * tier answers — see {@link operatorAlertLevel}. Set where the tone and\n * the importance part ways: a recovery is worth hearing about and is good\n * news, and a degraded check is a must-know that is not yet an outage.\n */\n level?: NotificationLevel\n /** The plugin that contributed it; absent for core's own. */\n pluginId?: string\n}\n\n/** Values a call site passes for an alert's `{{tokens}}`. */\nexport type OperatorAlertContext = Readonly<\n Record<string, string | number | boolean | null | undefined>\n>\n\n/** The notification type an alert without its own writes under. */\nexport const OPERATOR_ALERT_DEFAULT_NOTIFICATION_TYPE: AglynNotificationType =\n 'system.operatorAlert'\n\nexport const OPERATOR_ALERT_TIER_LABELS: Record<OperatorAlertTier, string> = {\n must: 'Must know',\n should: 'Should know',\n low: 'Routine',\n}\n\n/**\n * The level an alert's notification is drawn at when its entry names none:\n * a must-know is red, a should-know amber, routine review work informational.\n */\nexport const OPERATOR_ALERT_TIER_LEVELS: Record<\n OperatorAlertTier,\n NotificationLevel\n> = {\n must: 'critical',\n should: 'warning',\n low: 'info',\n}\n\n/** The level an alert's console notification carries (AGL-3437). */\nexport function operatorAlertLevel(\n definition: Pick<OperatorAlertDefinition, 'tier' | 'level'>,\n): NotificationLevel {\n return definition.level ?? OPERATOR_ALERT_TIER_LEVELS[definition.tier]\n}\n\nexport const OPERATOR_ALERT_CATEGORY_LABELS: Record<\n OperatorAlertCategory,\n string\n> = {\n billing: 'Billing',\n payments: 'Payments & payouts',\n legal: 'Legal',\n data: 'Data protection',\n ops: 'Operations',\n deliverability: 'Email deliverability',\n security: 'Security',\n support: 'Support',\n}\n\nconst DAY = 24 * 60\n\n/**\n * Core's alerts. Plugins contribute theirs through the plugin-manager\n * registry; nothing plugin-specific belongs in this list.\n */\nexport const CORE_OPERATOR_ALERTS: readonly OperatorAlertDefinition[] = [\n // ── Fraud, risk and legal duties already alerting before AGL-3377 ──────\n {\n type: 'system.abuseReportUrgent',\n label: 'Urgent abuse, fraud or risk alert',\n description:\n 'Phishing, malware or CSAM reported on a site, card testing, a flagged or disputed payment, a held phishing email, a seller under review. Review it on Staff → Abuse reports.',\n tier: 'must',\n category: 'security',\n title: '{{title}}',\n body: '{{body}}',\n link: '/admin/abuse-reports',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'system.abuseReportUrgent',\n },\n {\n // The one lock no person placed (AGL-3450): staff confirm it before the\n // customer's appeal arrives, and re-place it as `abuse` or lift it.\n type: 'security.pageSecurityHold',\n label: 'Automatic security hold on a new workspace',\n description:\n 'The page screen held a phishing page from a workspace in its first two weeks and locked the workspace, the site and the publishing account as security. Confirm it on Staff → Abuse reports, then re-place it as abuse on Staff → Lockdown, or lift it there if it is a false positive.',\n tier: 'must',\n category: 'security',\n title: 'Security hold placed on {{orgName}}',\n body:\n '{{page}} on {{siteName}} ({{hostId}}) was held for review: {{signal}} Locked as security, pending your review: {{locks}}. The abuse row is {{reference}}. Lift the hold, or re-place it as abuse, on Staff → Lockdown (/admin/lockdown).',\n link: '/admin/abuse-reports?report={{reviewId}}',\n delivery: 'immediate',\n // One hold per workspace; a repeat inside the day is the same event.\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n notificationType: 'system.abuseReportUrgent',\n },\n {\n type: 'security.paymentFraudHold',\n label: 'Automatic security hold for payment fraud',\n description:\n 'Stripe flagged a workspace\\'s own subscription payment as fraud — a Radar block at highest risk, a Stripe fraud report, three or more cards failing within 30 minutes, an early fraud warning or a Radar review. A new workspace that never paid is locked as security (takedown) with its subscriptions canceled; an older or paying one is not locked and needs a decision. Confirm it on Staff → Abuse reports, then re-place it as abuse on Staff → Lockdown, or lift it there.',\n tier: 'must',\n category: 'security',\n title: '{{action}}: {{orgName}}',\n body:\n '{{trigger}} on {{orgName}} ({{orgId}}). Charges: {{charges}}; cards: {{cards}}, issued in {{cardCountries}}. Locked: {{locks}}. The abuse row is {{reference}}. Lift it, or re-place it as abuse, on Staff → Lockdown (/admin/lockdown).',\n link: '/admin/abuse-reports?report={{reviewId}}',\n delivery: 'immediate',\n // One per workspace per window: every further card in the burst is the\n // same event, and the abuse row carries all of them.\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n notificationType: 'system.abuseReportUrgent',\n },\n {\n type: 'system.disputeUnattributed',\n label: 'Card dispute with no owner',\n description:\n 'A chargeback arrived that no subscription, order or marketplace purchase claimed, so nothing is answering it. Find the charge in Stripe and respond before the evidence deadline.',\n tier: 'must',\n category: 'billing',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'system.disputeUnattributed',\n },\n {\n type: 'system.dmcaCounterNotice',\n label: 'DMCA counter-notice',\n description:\n 'A customer contested a takedown. The statutory clock is already running; forward it to the complainant and restore on time unless they file suit.',\n tier: 'must',\n category: 'legal',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'system.dmcaCounterNotice',\n },\n {\n type: 'system.billingWebhookHalfApplied',\n label: 'Billing webhook half applied',\n description:\n 'A Stripe event threw after its handlers began, so its effects may be partly applied and Stripe will not retry it. Reconcile the event by hand.',\n tier: 'must',\n category: 'billing',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'system.billingWebhookHalfApplied',\n },\n\n // ── MUST: billing ───────────────────────────────────────────────────────\n {\n type: 'billing.platformDisputeLost',\n label: 'Subscription dispute lost',\n description:\n 'A card dispute on a workspace subscription closed as lost: the money has been taken back. Decide whether the workspace keeps its plan.',\n tier: 'must',\n category: 'billing',\n title: 'Subscription dispute lost on workspace {{orgId}}',\n body:\n 'The card dispute {{disputeId}} on invoice {{invoiceId}} for workspace {{orgName}} ({{orgId}}) closed as lost ({{reason}}), and {{amount}} was taken back. The workspace keeps its plan until somebody decides otherwise.',\n link: '/admin/orgs/{{orgId}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 30 * DAY,\n defaultEnabled: true,\n },\n {\n type: 'billing.orphanedSubscription',\n label: 'Stripe is billing a workspace that does not exist',\n description:\n 'A subscription names a workspace that was deleted or erased, so the customer keeps being charged for nothing. Cancel or refund it in Stripe.',\n tier: 'must',\n category: 'billing',\n title: 'Subscription bills a missing workspace',\n body:\n 'Stripe subscription {{subscriptionId}} (customer {{customerId}}, plan {{plan}}) names workspace {{orgId}}, which {{reason}}. The {{eventType}} event changed nothing. Cancel or refund it in Stripe.',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n {\n type: 'billing.usageNotReported',\n label: 'Metered usage not reported to Stripe',\n description:\n 'A closed month measured billable usage and it reached no invoice. Report it to Stripe by hand or the revenue is lost.',\n tier: 'must',\n category: 'billing',\n title: 'Usage for {{month}} not billed on {{orgId}}',\n body:\n 'The closed month {{month}} measured {{amount}} of billable usage on workspace {{orgName}} ({{orgId}}), and it was not reported to Stripe ({{reason}}). Nothing will invoice it until somebody does.',\n link: '/admin/orgs/{{orgId}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 7 * DAY,\n defaultEnabled: true,\n },\n {\n type: 'billing.webhookSignatureRejected',\n label: 'Billing webhook failing its signature check',\n description:\n 'Repeated deliveries to the billing webhook were refused because their signature did not match. Usually a rolled signing secret: until it is fixed, Stripe cannot tell the install about money.',\n tier: 'must',\n category: 'billing',\n title: 'Billing webhook is refusing deliveries',\n body:\n 'The billing webhook refused several signed deliveries within six hours because their Stripe signature matched none of the configured secrets. If Stripe is the sender, its signing secret no longer matches this install’s, and no billing event is being applied.',\n link: '/admin/health',\n delivery: 'immediate',\n dedupeWindowMinutes: 6 * 60,\n minOccurrences: 3,\n defaultEnabled: true,\n },\n {\n type: 'billing.webhookInert',\n label: 'Billing webhook delivery moved nothing',\n description:\n 'Stripe delivered an event this install subscribed to, and no handler did anything with it. Usually a handler that stopped being registered.',\n tier: 'must',\n category: 'billing',\n title: 'A {{eventType}} delivery changed nothing',\n body:\n 'Stripe event {{eventId}} ({{eventType}}) was accepted and no handler acted on it. Check which handler stopped being registered, then replay the event.',\n link: '/admin/health',\n delivery: 'immediate',\n dedupeWindowMinutes: 6 * 60,\n defaultEnabled: true,\n },\n\n // ── MUST: data protection and records ───────────────────────────────────\n {\n type: 'data.personErasureFailed',\n label: 'Personal data erasure failed',\n description:\n 'A data subject’s erasure request failed. It will be retried, but the legal deadline keeps running: read the error and fix the cause.',\n tier: 'must',\n category: 'data',\n title: 'Erasure request {{requestId}} failed',\n body:\n 'The erasure request {{requestId}} on workspace {{orgName}} ({{orgId}}) failed (attempt {{attempt}}): {{error}}. The statutory deadline keeps running while it retries.',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n {\n type: 'data.orgErasureFailed',\n label: 'Workspace erasure failed',\n description:\n 'A workspace scheduled for erasure could not be erased. Its data is still held after the date it was promised gone.',\n tier: 'must',\n category: 'data',\n title: 'Workspace {{orgId}} could not be erased',\n body:\n 'The scheduled erasure of workspace {{orgName}} ({{orgId}}) did not complete: {{reason}}. It will be retried on the next run; its data is held until it succeeds.',\n link: '/admin/orgs/{{orgId}}',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n {\n type: 'data.backupExportFailed',\n label: 'Database export failed',\n description:\n 'The scheduled database export did not start. A stale export means the worst day has nothing to restore from.',\n tier: 'must',\n category: 'data',\n title: 'Database export failed',\n body:\n 'The scheduled database export did not start ({{reason}}). The last good export is getting older; check the service account’s export permission and the bucket.',\n link: '/admin/health',\n delivery: 'immediate',\n dedupeWindowMinutes: 12 * 60,\n defaultEnabled: true,\n },\n\n // ── MUST: legal ─────────────────────────────────────────────────────────\n {\n type: 'legal.abuseReportHigh',\n label: 'Takedown, impersonation or illegal-content report',\n description:\n 'A DMCA takedown, impersonation or illegal-content report. Each carries a response duty; review it on Staff → Abuse reports.',\n tier: 'must',\n category: 'legal',\n title: '{{category}} report on {{site}}',\n body:\n '{{site}} was reported for {{category}}. Reference {{reference}}. Review it and respond within the policy’s window.',\n link: '/admin/abuse-reports',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n },\n\n // ── MUST/SHOULD: health ─────────────────────────────────────────────────\n {\n type: 'system.healthDegraded',\n label: 'Health check degraded',\n description:\n 'A health check went from healthy to degraded: scheduled jobs silent, backups stale, billing deliveries failing, sign-ups refused, server errors, a site not rendering. Told once per incident.',\n tier: 'must',\n category: 'ops',\n title: '{{check}} is degraded',\n body: '{{check}} went from healthy to degraded. {{detail}}',\n link: '/admin/health',\n delivery: 'immediate',\n // Must-know, and still amber rather than red: degraded is not down.\n level: 'warning',\n // A check flapping across the line is told once an hour, not on\n // every swing.\n dedupeWindowMinutes: 60,\n defaultEnabled: true,\n },\n {\n // The reminder the edge alert never sends (AGL-3860): raised by the\n // operator alerts tick at 1 h and every 2 h after while a check stays\n // degraded. The tick raises it as Must know from 2 h, so its level\n // follows the tier it was raised at rather than one coded here.\n type: 'system.healthStillDegraded',\n label: 'Health check still degraded',\n description:\n 'A health check has stayed degraded for an hour or more. Told at 1 h and again every 2 h until it recovers; Should know for the first reminder, Must know from 2 h on. Open the failing endpoint, read the failing check’s code and fix the cause, or the check when the check is what is wrong.',\n tier: 'should',\n category: 'ops',\n title: '{{check}} is still degraded after {{duration}}',\n body: '{{check}} is still degraded after {{duration}}. {{detail}}',\n link: '/admin/health',\n delivery: 'immediate',\n // The tick dedupes each reminder per check per step on the check's own\n // state; the window only stops a retried tick from telling one twice.\n dedupeWindowMinutes: 60,\n defaultEnabled: true,\n },\n {\n // The post-deploy production canary (AGL-3567), raised from GitHub\n // Actions through `/api/admin/operator-alerts/canary`. Red because a\n // deploy that stops rendering pages is every published site down.\n type: 'ops.productionCanaryRed',\n label: 'Production canary failed after a deploy',\n description:\n 'Right after a tenant or console production deploy, uncached pages stopped rendering. The canary rolls the deploy back by itself when the failure holds across sites; after any rollback the next release must be promoted by hand.',\n tier: 'must',\n category: 'ops',\n title: '{{project}} production canary: {{outcome}}',\n body: '{{detail}}',\n link: '/admin/health',\n delivery: 'immediate',\n level: 'critical',\n // The caller dedupes per deployment and verdict; this only stops a\n // re-run of the same red run from telling it twice.\n dedupeWindowMinutes: 30,\n defaultEnabled: true,\n },\n {\n type: 'system.healthRecovered',\n label: 'Health check recovered',\n description: 'A degraded health check is healthy again.',\n tier: 'should',\n category: 'ops',\n title: '{{check}} recovered',\n body: '{{check}} is healthy again after {{duration}}.',\n link: '/admin/health',\n delivery: 'immediate',\n level: 'success',\n // A check flapping across the line is told once an hour, not on\n // every swing.\n dedupeWindowMinutes: 60,\n defaultEnabled: true,\n },\n {\n // The render monitor (AGL-3568): a published site fetched over HTTP, on\n // pages no cache can answer, failed several runs in a row. Red, not the\n // amber of a degraded check: every visitor without a cached copy is\n // getting an error page or a timeout right now.\n type: 'system.siteRenderFailing',\n label: 'Published site not rendering pages',\n description:\n 'The render monitor asked a published site for pages no cache can answer, several runs in a row, and got no complete page back. Visitors to cached pages may still see them, so the site can look up while every other page fails. Check the latest site runtime deployment first and roll it back if it just shipped.',\n tier: 'must',\n category: 'ops',\n title: 'Pages are not rendering on {{site}}',\n body:\n '{{site}} failed {{failures}} render checks in a row, over {{since}}. {{detail}} Cached pages may still load, so the site can look up while new renders fail.',\n link: '/admin/health',\n delivery: 'immediate',\n // Told once per outage: the monitor raises it on the edge, and the\n // window only covers a site flapping across the line.\n dedupeWindowMinutes: 30,\n defaultEnabled: true,\n },\n {\n type: 'system.siteRenderRecovered',\n label: 'Published site rendering again',\n description:\n 'A published site the render monitor had reported as not rendering serves fresh pages again.',\n tier: 'should',\n category: 'ops',\n title: '{{site}} is rendering pages again',\n body: 'Fresh page renders on {{site}} pass again after {{duration}}.',\n link: '/admin/health',\n delivery: 'immediate',\n level: 'success',\n dedupeWindowMinutes: 30,\n defaultEnabled: true,\n },\n {\n // The render monitor could not see the site (AGL-3580): bot protection\n // answered every probe it made, so it knows nothing about whether pages\n // render. Not an outage, and never worded as one — on 2026-10-05 a\n // missing probe token read as \"pages are not rendering\" for three hours\n // while the site served pages. Amber: detection is off until it is fixed.\n type: 'system.renderMonitorBlind',\n label: 'Render monitor cannot see a site',\n description:\n 'Bot protection answered the render monitor instead of a published site, several runs in a row, so nothing is checking whether that site renders pages. The site itself may be fine. Check AGLYN_PROBE_TOKEN on the console and the \"CI and uptime probe bypass\" firewall rule on the site runtime.',\n tier: 'must',\n category: 'ops',\n title: 'The render monitor cannot see {{site}}',\n body:\n 'Bot protection answered instead of {{site}} for {{runs}} runs in a row, so nothing is checking its pages. {{detail}} This is not a verdict on the site.',\n link: '/admin/health',\n delivery: 'immediate',\n level: 'warning',\n dedupeWindowMinutes: 360,\n defaultEnabled: true,\n },\n\n // ── SHOULD: billing ─────────────────────────────────────────────────────\n {\n type: 'billing.autoLocked',\n label: 'Workspace billing locked automatically',\n description:\n 'A workspace crossed its spend guard and the platform locked its billable activity. Check it is not a false positive before the customer notices.',\n tier: 'should',\n category: 'billing',\n title: 'Billing locked on {{orgName}}',\n body:\n 'Workspace {{orgName}} ({{orgId}}) was locked automatically: {{reason}}.',\n link: '/admin/orgs/{{orgId}}',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n {\n type: 'billing.platformInvoiceUncollectible',\n label: 'Subscription invoice voided or uncollectible',\n description:\n 'A workspace invoice was voided or marked uncollectible: revenue the books expected is not coming.',\n tier: 'should',\n category: 'billing',\n title: 'Invoice {{status}} on {{orgId}}',\n body:\n 'Invoice {{invoiceId}} for {{amount}} on workspace {{orgName}} ({{orgId}}) was marked {{status}}, so Stripe has stopped collecting it.',\n link: '/admin/orgs/{{orgId}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 30 * DAY,\n defaultEnabled: true,\n },\n {\n type: 'billing.connectPayoutFailed',\n label: 'Connected account payout or transfer failed',\n description:\n 'Money due to a merchant or seller did not arrive. Stripe retries on its own schedule; a human decides what happens next.',\n tier: 'should',\n category: 'billing',\n title: 'A {{kind}} to {{account}} failed',\n body:\n 'A {{amount}} Stripe {{kind}} ({{stripeId}}) to connected account {{account}} ({{merchant}}) failed: {{reason}}. The merchant’s funds are not where the ledger says.',\n delivery: 'immediate',\n dedupeWindowMinutes: 30 * DAY,\n defaultEnabled: true,\n },\n {\n type: 'staff.paymentFailed',\n label: 'Workspace payment failed',\n description:\n 'A paying workspace’s renewal failed. Stripe is retrying; the customer has been told.',\n tier: 'should',\n category: 'billing',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'staff.paymentFailed',\n },\n\n // ── SHOULD: security ────────────────────────────────────────────────────\n {\n type: 'security.staffGranted',\n label: 'Staff access granted or raised',\n description:\n 'Somebody was made staff, or a staff role was raised. If nobody on the team did it, revoke it and rotate credentials.',\n tier: 'should',\n category: 'security',\n title: '{{target}} is now {{role}} staff',\n body: '{{actor}} granted {{target}} the {{role}} staff role (was {{previous}}).',\n link: '/admin/users',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n },\n\n // ── SHOULD: support ─────────────────────────────────────────────────────\n {\n type: 'support.slaBreached',\n label: 'Support ticket past its response time',\n description:\n 'A support ticket passed its promised response time without a staff reply.',\n tier: 'should',\n category: 'support',\n title: 'Ticket past its response time: {{subject}}',\n body:\n 'The {{tier}} ticket “{{subject}}” from workspace {{orgName}} ({{orgId}}) was due a first response {{overdue}} ago and has none.',\n // The ticket itself: the support page opens `?ticketId=` on load.\n link: '/admin/support?ticketId={{ticketId}}',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n {\n type: 'support.ticketOpened',\n label: 'New support ticket',\n description: 'A subscriber opened a support ticket.',\n tier: 'should',\n category: 'support',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'digest',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'support.ticketOpened',\n // A customer asking for help, not a fault.\n level: 'info',\n },\n {\n type: 'support.ticketReply',\n label: 'Support ticket reply',\n description: 'A subscriber replied on a support ticket.',\n tier: 'should',\n category: 'support',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'digest',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'support.ticketReply',\n level: 'info',\n },\n\n // ── SHOULD: deliverability ──────────────────────────────────────────────\n {\n type: 'deliverability.sendRateSaturated',\n label: 'Email send-rate governor saturated',\n description:\n 'The platform’s email send-rate budget is exhausted, so sends are being deferred. Raise the budget or find the sender filling it.',\n tier: 'should',\n category: 'deliverability',\n title: 'Email sending is being throttled',\n body:\n 'The {{scope}} send-rate budget is full ({{detail}}), so sends are being deferred.',\n link: '/admin/emails',\n delivery: 'immediate',\n dedupeWindowMinutes: 6 * 60,\n defaultEnabled: true,\n },\n {\n type: 'deliverability.sendRateUnavailable',\n label: 'Email send-rate governor unavailable',\n description:\n 'The send-rate governor could not read its counters, so mail is going out unmetered: nothing is holding the shared domains under their hourly ceiling.',\n tier: 'should',\n category: 'deliverability',\n title: 'Email send-rate governor unavailable',\n body:\n 'The send-rate governor could not read its counters ({{error}}), so sends are being allowed unmetered until it can.',\n link: '/admin/emails',\n delivery: 'immediate',\n dedupeWindowMinutes: 6 * 60,\n defaultEnabled: true,\n },\n {\n type: 'deliverability.gatewayBlocking',\n label: 'A recipient gateway is blocking the shared domain',\n description:\n 'A mail gateway is refusing mail from the shared sending domain, so everyone behind that gateway stops receiving it.',\n tier: 'should',\n category: 'deliverability',\n title: '{{gateway}} is blocking {{domain}}',\n body:\n 'Mail from {{domain}} is being refused by {{gateway}} ({{detail}}). Recipients behind that gateway are not receiving it.',\n link: '/admin/emails',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n {\n type: 'deliverability.providerCredentialsRejected',\n label: 'Email provider rejected the credentials',\n description:\n 'The email provider refused the API key, or a sending pool is unhealthy: invites, password resets and receipts are not leaving. The webhook channel is the one that still reaches you.',\n tier: 'should',\n category: 'deliverability',\n title: 'Email delivery is failing: {{problem}}',\n body: '{{detail}}',\n link: '/admin/emails',\n delivery: 'immediate',\n dedupeWindowMinutes: 6 * 60,\n defaultEnabled: true,\n },\n {\n // A purchasing ceiling, not a job failure: the provisioning sweep ran\n // and every site keeps sending, so the copy must not read as an outage.\n type: 'deliverability.sendingDomainCapacityFull',\n label: 'Sending-domain allowance full',\n description:\n 'Every dedicated sending domain the provider allowance covers is in use, so new sites that ask for one stay on the shared pool. No mail is lost; raise the allowance or move merchants onto domains they own.',\n tier: 'should',\n category: 'deliverability',\n title: 'Sending-domain allowance full ({{held}}/{{capacity}})',\n body:\n 'The sending-domain allowance is full ({{held}} of {{capacity}} in use), so sites that asked for a dedicated domain keep sending on the shared pool. No mail is lost: what they go without is the isolation a domain of their own buys, and their campaigns are held to the pool’s stricter reputation limits. Raise AGLYN_SENDING_DOMAIN_CAPACITY once the provider allowance covers it, or move merchants onto domains they own.',\n link: '/admin/emails',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n\n // ── SHOULD: operations ──────────────────────────────────────────────────\n {\n type: 'ops.reaperStuck',\n label: 'A reaper is stuck or failing',\n description:\n 'A cleanup job (sending domains, unverified workspaces) could not finish, so what it removes keeps accumulating.',\n tier: 'should',\n category: 'ops',\n title: '{{job}} is stuck',\n body: '{{job}} could not finish: {{detail}}',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n {\n type: 'ops.pluginJobFailed',\n label: 'A plugin job failed',\n description:\n 'A plugin’s scheduled job threw: consent-group changes, the publish outbox, sending-domain provisioning, a plugin cron.',\n tier: 'should',\n category: 'ops',\n // `job` is a noun phrase that reads as a subject on its own (\"The\n // publish outbox drain\", \"The scheduled job acme-mail-send\"), so the\n // title and the body open with the same words.\n title: '{{job}} failed',\n body: '{{job}} failed: {{error}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 6 * 60,\n defaultEnabled: true,\n },\n {\n // Nightly, so once a day per provider is every run it could report.\n type: 'ops.adAudienceSyncFailed',\n label: 'Ad audience sync failed',\n description:\n 'The nightly account-holder audience sync (AGL-3780) could not update a Meta, Google or LinkedIn audience, or held a run whose audience would have shrunk by more than half. The audience keeps what it last had; check the provider credentials, or run the sync with force once the drop is confirmed.',\n tier: 'should',\n category: 'ops',\n title: 'Ad audience sync: {{provider}} not updated',\n body: 'The {{provider}} account-holder audience was not updated: {{detail}}. It keeps what it was last sent, and the next nightly run tries again.',\n link: '/admin/flags',\n delivery: 'immediate',\n dedupeWindowMinutes: DAY,\n defaultEnabled: true,\n },\n {\n type: 'system.pluginVerifierRegression',\n label: 'Plugin verifier regression',\n description:\n 'A live plugin version stopped passing the static verifier.',\n tier: 'should',\n category: 'security',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'system.pluginVerifierRegression',\n },\n {\n type: 'system.bandwidthCeilingTripped',\n label: 'Bandwidth ceiling reached',\n description:\n 'A site crossed the per-month bandwidth abuse ceiling.',\n tier: 'should',\n category: 'ops',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'immediate',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'system.bandwidthCeilingTripped',\n },\n\n // ── LOW ─────────────────────────────────────────────────────────────────\n {\n type: 'marketplace.review',\n label: 'Plugin listing waiting for review',\n description: 'A plugin listing or version was submitted for review.',\n tier: 'low',\n category: 'security',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'digest',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'marketplace.review',\n },\n {\n type: 'system.scopeDrift',\n label: 'Resources missing a sharing scope',\n description:\n 'The weekly sweep found documents invisible to every site-scoped read: a creation path forgot the field.',\n tier: 'low',\n category: 'data',\n title: '{{title}}',\n body: '{{body}}',\n delivery: 'digest',\n dedupeWindowMinutes: 0,\n defaultEnabled: true,\n notificationType: 'system.scopeDrift',\n },\n]\n\n/** An amount in minor units, as an alert prints it: `$12.40`. */\nexport function formatOperatorAlertAmount(\n cents: number,\n currency = 'usd',\n): string {\n const value = Number(cents) / 100\n if (!Number.isFinite(value)) return ''\n try {\n return new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: String(currency || 'usd').toUpperCase(),\n }).format(value)\n } catch {\n return `${value.toFixed(2)} ${String(currency).toUpperCase()}`\n }\n}\n\n/** Replaces each `{{token}}` with its context value, or nothing. */\nexport function renderOperatorAlertTemplate(\n template: string,\n context: OperatorAlertContext | undefined,\n): string {\n return String(template ?? '')\n .replace(/\\{\\{\\s*([\\w.]+)\\s*\\}\\}/g, (_match, name: string) => {\n const value = context?.[name]\n return value === null || value === undefined ? '' : String(value)\n })\n .replace(/\\(\\s*\\)/g, '')\n .replace(/[ \\t]{2,}/g, ' ')\n .replace(/ ([.,;:])/g, '$1')\n .trim()\n}\n\n/** A staff member's answer for one type; an absent key keeps the default. */\nexport interface OperatorAlertTypeSetting {\n enabled?: boolean\n delivery?: OperatorAlertDelivery\n}\n\n/** `platformSettings/operatorAlerts`, keyed by alert type. */\nexport interface OperatorAlertSettings {\n types?: Record<string, OperatorAlertTypeSetting>\n}\n\n/** Whether a type is on, and how it is delivered, after staff's answers. */\nexport function effectiveOperatorAlertSetting(\n definition: Pick<OperatorAlertDefinition, 'type' | 'delivery' | 'defaultEnabled'>,\n settings: OperatorAlertSettings | null | undefined,\n): { enabled: boolean; delivery: OperatorAlertDelivery } {\n const answer = settings?.types?.[definition.type]\n return {\n enabled:\n typeof answer?.enabled === 'boolean'\n ? answer.enabled\n : definition.defaultEnabled,\n delivery:\n answer?.delivery === 'immediate' || answer?.delivery === 'digest'\n ? answer.delivery\n : definition.delivery,\n }\n}\n\n/**\n * Staff notification types whose alert emails the operator on a coded\n * default of immediate (AGL-3375), derived from the catalog so there is one\n * list.\n */\nexport const OPERATOR_ALERT_NOTIFICATION_TYPES: ReadonlySet<string> = new Set(\n CORE_OPERATOR_ALERTS.flatMap((definition) =>\n definition.notificationType ? [definition.notificationType] : [],\n ),\n)\n"],"names":["OPERATOR_ALERT_DEFAULT_NOTIFICATION_TYPE","OPERATOR_ALERT_TIER_LABELS","must","should","low","OPERATOR_ALERT_TIER_LEVELS","operatorAlertLevel","definition","level","tier","OPERATOR_ALERT_CATEGORY_LABELS","billing","payments","legal","data","ops","deliverability","security","support","DAY","CORE_OPERATOR_ALERTS","type","label","description","category","title","body","link","delivery","dedupeWindowMinutes","defaultEnabled","notificationType","minOccurrences","formatOperatorAlertAmount","cents","currency","value","Number","isFinite","Intl","NumberFormat","style","String","toUpperCase","format","toFixed","renderOperatorAlertTemplate","template","context","replace","_match","name","undefined","trim","effectiveOperatorAlertSetting","settings","answer","types","enabled","OPERATOR_ALERT_NOTIFICATION_TYPES","Set","flatMap"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GA6GD,iEAAiE,GACjE,OAAO,MAAMA,2CACX,uBAAsB;AAExB,OAAO,MAAMC,6BAAgE;IAC3EC,MAAM;IACNC,QAAQ;IACRC,KAAK;AACP,EAAC;AAED;;;CAGC,GACD,OAAO,MAAMC,6BAGT;IACFH,MAAM;IACNC,QAAQ;IACRC,KAAK;AACP,EAAC;AAED,kEAAkE,GAClE,OAAO,SAASE,mBACdC,UAA2D;QAEpDA;IAAP,QAAOA,oBAAAA,WAAWC,KAAK,YAAhBD,oBAAoBF,0BAA0B,CAACE,WAAWE,IAAI,CAAC;AACxE;AAEA,OAAO,MAAMC,iCAGT;IACFC,SAAS;IACTC,UAAU;IACVC,OAAO;IACPC,MAAM;IACNC,KAAK;IACLC,gBAAgB;IAChBC,UAAU;IACVC,SAAS;AACX,EAAC;AAED,MAAMC,MAAM,KAAK;AAEjB;;;CAGC,GACD,OAAO,MAAMC,uBAA2D;IACtE,0EAA0E;IAC1E;QACEC,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNC,MAAM;QACNC,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;QAChBC,kBAAkB;IACpB;IACA;QACE,wEAAwE;QACxE,oEAAoE;QACpEV,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACV,qEAAqE;QACrEC,qBAAqBV;QACrBW,gBAAgB;QAChBC,kBAAkB;IACpB;IACA;QACEV,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACV,uEAAuE;QACvE,qDAAqD;QACrDC,qBAAqBV;QACrBW,gBAAgB;QAChBC,kBAAkB;IACpB;IACA;QACEV,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;QAChBC,kBAAkB;IACpB;IACA;QACEV,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;QAChBC,kBAAkB;IACpB;IACA;QACEV,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;QAChBC,kBAAkB;IACpB;IAEA,2EAA2E;IAC3E;QACEV,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB,KAAKV;QAC1BW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFE,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB,IAAIV;QACzBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB,IAAI;QACzBG,gBAAgB;QAChBF,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB,IAAI;QACzBC,gBAAgB;IAClB;IAEA,2EAA2E;IAC3E;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFE,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB,KAAK;QAC1BC,gBAAgB;IAClB;IAEA,2EAA2E;IAC3E;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;IAClB;IAEA,2EAA2E;IAC3E;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNC,MAAM;QACNC,UAAU;QACV,oEAAoE;QACpEpB,OAAO;QACP,gEAAgE;QAChE,eAAe;QACfqB,qBAAqB;QACrBC,gBAAgB;IAClB;IACA;QACE,oEAAoE;QACpE,sEAAsE;QACtE,mEAAmE;QACnE,gEAAgE;QAChET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNC,MAAM;QACNC,UAAU;QACV,uEAAuE;QACvE,sEAAsE;QACtEC,qBAAqB;QACrBC,gBAAgB;IAClB;IACA;QACE,mEAAmE;QACnE,qEAAqE;QACrE,kEAAkE;QAClET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNC,MAAM;QACNC,UAAU;QACVpB,OAAO;QACP,mEAAmE;QACnE,oDAAoD;QACpDqB,qBAAqB;QACrBC,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aAAa;QACbd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNC,MAAM;QACNC,UAAU;QACVpB,OAAO;QACP,gEAAgE;QAChE,eAAe;QACfqB,qBAAqB;QACrBC,gBAAgB;IAClB;IACA;QACE,wEAAwE;QACxE,wEAAwE;QACxE,oEAAoE;QACpE,gDAAgD;QAChDT,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACV,mEAAmE;QACnE,sDAAsD;QACtDC,qBAAqB;QACrBC,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNC,MAAM;QACNC,UAAU;QACVpB,OAAO;QACPqB,qBAAqB;QACrBC,gBAAgB;IAClB;IACA;QACE,uEAAuE;QACvE,wEAAwE;QACxE,mEAAmE;QACnE,wEAAwE;QACxE,0EAA0E;QAC1ET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVpB,OAAO;QACPqB,qBAAqB;QACrBC,gBAAgB;IAClB;IAEA,2EAA2E;IAC3E;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB,KAAKV;QAC1BW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFE,UAAU;QACVC,qBAAqB,KAAKV;QAC1BW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;QAChBC,kBAAkB;IACpB;IAEA,2EAA2E;IAC3E;QACEV,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNC,MAAM;QACNC,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;IAClB;IAEA,2EAA2E;IAC3E;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACF,kEAAkE;QAClEC,MAAM;QACNC,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aAAa;QACbd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;QAChBC,kBAAkB;QAClB,2CAA2C;QAC3CvB,OAAO;IACT;IACA;QACEa,MAAM;QACNC,OAAO;QACPC,aAAa;QACbd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqB;QACrBC,gBAAgB;QAChBC,kBAAkB;QAClBvB,OAAO;IACT;IAEA,2EAA2E;IAC3E;QACEa,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB,IAAI;QACzBC,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqB,IAAI;QACzBC,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNC,MAAM;QACNC,UAAU;QACVC,qBAAqB,IAAI;QACzBC,gBAAgB;IAClB;IACA;QACE,sEAAsE;QACtE,wEAAwE;QACxET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MACE;QACFC,MAAM;QACNC,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IAEA,2EAA2E;IAC3E;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACV,kEAAkE;QAClE,qEAAqE;QACrE,+CAA+C;QAC/CC,OAAO;QACPC,MAAM;QACNE,UAAU;QACVC,qBAAqB,IAAI;QACzBC,gBAAgB;IAClB;IACA;QACE,oEAAoE;QACpET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC,MAAM;QACNC,MAAM;QACNC,UAAU;QACVC,qBAAqBV;QACrBW,gBAAgB;IAClB;IACA;QACET,MAAM;QACNC,OAAO;QACPC,aACE;QACFd,MAAM;QACNe,UAAU;QACVC,OAAO;QACPC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,OAAO,CAAC,cAAc,KACtBA,OAAO,CAAC,cAAc,MACtBI,IAAI;AACT;AAaA,0EAA0E,GAC1E,OAAO,SAASC,8BACd/C,UAAiF,EACjFgD,QAAkD;QAEnCA;IAAf,MAAMC,SAASD,6BAAAA,kBAAAA,SAAUE,KAAK,qBAAfF,eAAiB,CAAChD,WAAWc,IAAI,CAAC;IACjD,OAAO;QACLqC,SACE,QAAOF,0BAAAA,OAAQE,OAAO,MAAK,YACvBF,OAAOE,OAAO,GACdnD,WAAWuB,cAAc;QAC/BF,UACE4B,CAAAA,0BAAAA,OAAQ5B,QAAQ,MAAK,eAAe4B,CAAAA,0BAAAA,OAAQ5B,QAAQ,MAAK,WACrD4B,OAAO5B,QAAQ,GACfrB,WAAWqB,QAAQ;IAC3B;AACF;AAEA;;;;CAIC,GACD,OAAO,MAAM+B,oCAAyD,IAAIC,IACxExC,qBAAqByC,OAAO,CAAC,CAACtD,aAC5BA,WAAWwB,gBAAgB,GAAG;QAACxB,WAAWwB,gBAAgB;KAAC,GAAG,EAAE,GAEnE"}
@@ -0,0 +1,100 @@
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
+ import { type PluginFigureCell, type PluginFigureHeadline, type PluginFigureRow, type PluginFigureTable } from '../plugin-manager/plugin-figures';
18
+ /**
19
+ * THE WEEKLY SUMMARY (AGL-3867): the free Monday email that says how each of
20
+ * a workspace's sites did last week, and how the workspace's own figures
21
+ * moved.
22
+ *
23
+ * It spends nothing. Every figure comes from a `plugin-figures` reader that
24
+ * declares a `weeklySummary`, and that reader's owner words its own lines, so
25
+ * each plugin's counting rules decide what a figure is and nothing here names
26
+ * one. AI weekly insights (AGL-2915) are the paid version that explains the
27
+ * figures, and stay opt-in because each one spends the workspace's AI credits.
28
+ *
29
+ * This module is the period, the shared wording helpers the readers use, and
30
+ * the email's words; the reads and the sends are
31
+ * `@aglyn/tenant-data-admin/server/weekly-summary`.
32
+ */
33
+ /** The key a person's switch is stored under in `users/{uid}.digestPrefs`; on until turned off. */
34
+ export declare const WEEKLY_SUMMARY_DIGEST_KEY = "weeklySummary";
35
+ /** The window every figure is read over. */
36
+ export declare const WEEKLY_SUMMARY_DAYS = 7;
37
+ /** Rows a ranked line names: the top three. */
38
+ export declare const WEEKLY_SUMMARY_TOP_ROWS = 3;
39
+ /** Counts the subject line leads with, at most. */
40
+ export declare const WEEKLY_SUMMARY_HEADLINE_COUNTS = 3;
41
+ /**
42
+ * The week a run reports on: the seven whole UTC days before the day it runs,
43
+ * so a Monday run covers Monday to Sunday and never a part-day of today.
44
+ * `now` is what each reader is handed; `week` keys the run's marker.
45
+ */
46
+ export declare function weeklySummaryPeriod(runAt: Date): {
47
+ now: Date;
48
+ week: string;
49
+ from: string;
50
+ to: string;
51
+ label: string;
52
+ };
53
+ /** `2026-10-05` as "Oct 5". */
54
+ export declare function weeklySummaryDay(day: string): string;
55
+ /** A cell as a number, `0` for anything that is not one. */
56
+ export declare function figureCount(value: PluginFigureCell | undefined): number;
57
+ /** The row whose `key` cell is `label`: "Visitors" in a table of figures. */
58
+ export declare function figureRow(table: PluginFigureTable, key: string, label: string): PluginFigureRow | undefined;
59
+ /** Whether a table carries a column, so a reader that changed shape is noticed rather than misread. */
60
+ export declare function figureHasColumn(table: PluginFigureTable, key: string): boolean;
61
+ /** "1,204 (+12%)": a cell and, when there is an earlier week to compare with, its change. */
62
+ export declare function figureWithChange(table: PluginFigureTable, row: PluginFigureRow, key: string, changeKey: string): string;
63
+ /** The named rows with the most of `key`, as "name 12 unit, name 4"; `null` when none has any. */
64
+ export declare function figureRanked(table: PluginFigureTable, nameKey: string, key: string, unit?: string, rows?: readonly PluginFigureRow[]): string | null;
65
+ /** "1 order", "18 orders". */
66
+ export declare function figurePlural(count: number, one: string, many: string): string;
67
+ /** What one reader said this week: its lines and the count it adds to the subject. */
68
+ export interface WeeklySummaryEntry {
69
+ lines: string[];
70
+ headline: PluginFigureHeadline | null;
71
+ }
72
+ /** One site's part of the email. */
73
+ export interface WeeklySummarySite {
74
+ name: string;
75
+ /** The site's dashboard in the console, absolute; `null` with no origin to build it from. */
76
+ url: string | null;
77
+ entries: readonly WeeklySummaryEntry[];
78
+ }
79
+ /** The subject's counts, summed across sites by their noun, in the order the readers first gave them. */
80
+ export declare function weeklySummaryHeadline(sites: readonly WeeklySummarySite[]): string;
81
+ export declare function composeWeeklySummarySubject(workspaceName: string, sites: readonly WeeklySummarySite[]): string;
82
+ export interface WeeklySummaryEmailInput {
83
+ workspaceName: string;
84
+ productName: string;
85
+ periodLabel: string;
86
+ sites: readonly WeeklySummarySite[];
87
+ /** The workspace's own figures, such as its deals. */
88
+ workspace: readonly WeeklySummaryEntry[];
89
+ /** Where AI weekly insights are turned on, when the plan includes them and this person has not; else `null`. */
90
+ aiInsightsUrl: string | null;
91
+ settingsUrl: string;
92
+ /** Drops the closing "why" line, which the designed email's footer carries. */
93
+ omitClosing?: boolean;
94
+ }
95
+ /**
96
+ * The email's words, or `null` when there is nothing to report at all — a
97
+ * week with no figures is not worth an email, and sending one anyway is how a
98
+ * summary trains people to ignore it. A site with nothing to say is left out.
99
+ */
100
+ export declare function composeWeeklySummaryEmailText(input: WeeklySummaryEmailInput): string | null;
@@ -0,0 +1,137 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ import { pluginFigureCellText, pluginFigureIsoWeek, pluginFigureWindows } from "../plugin-manager/plugin-figures.js";
18
+ /**
19
+ * THE WEEKLY SUMMARY (AGL-3867): the free Monday email that says how each of
20
+ * a workspace's sites did last week, and how the workspace's own figures
21
+ * moved.
22
+ *
23
+ * It spends nothing. Every figure comes from a `plugin-figures` reader that
24
+ * declares a `weeklySummary`, and that reader's owner words its own lines, so
25
+ * each plugin's counting rules decide what a figure is and nothing here names
26
+ * one. AI weekly insights (AGL-2915) are the paid version that explains the
27
+ * figures, and stay opt-in because each one spends the workspace's AI credits.
28
+ *
29
+ * This module is the period, the shared wording helpers the readers use, and
30
+ * the email's words; the reads and the sends are
31
+ * `@aglyn/tenant-data-admin/server/weekly-summary`.
32
+ */ /** The key a person's switch is stored under in `users/{uid}.digestPrefs`; on until turned off. */ export const WEEKLY_SUMMARY_DIGEST_KEY = 'weeklySummary';
33
+ /** The window every figure is read over. */ export const WEEKLY_SUMMARY_DAYS = 7;
34
+ /** Rows a ranked line names: the top three. */ export const WEEKLY_SUMMARY_TOP_ROWS = 3;
35
+ /** Counts the subject line leads with, at most. */ export const WEEKLY_SUMMARY_HEADLINE_COUNTS = 3;
36
+ /**
37
+ * The week a run reports on: the seven whole UTC days before the day it runs,
38
+ * so a Monday run covers Monday to Sunday and never a part-day of today.
39
+ * `now` is what each reader is handed; `week` keys the run's marker.
40
+ */ export function weeklySummaryPeriod(runAt) {
41
+ const startOfToday = Date.UTC(runAt.getUTCFullYear(), runAt.getUTCMonth(), runAt.getUTCDate());
42
+ const now = new Date(startOfToday - 1);
43
+ const { current } = pluginFigureWindows(now, WEEKLY_SUMMARY_DAYS);
44
+ return {
45
+ now,
46
+ week: pluginFigureIsoWeek(now),
47
+ from: current.from,
48
+ to: current.to,
49
+ label: `${weeklySummaryDay(current.from)} – ${weeklySummaryDay(current.to)}`
50
+ };
51
+ }
52
+ /** `2026-10-05` as "Oct 5". */ export function weeklySummaryDay(day) {
53
+ const at = new Date(`${day}T00:00:00Z`);
54
+ return at.toLocaleDateString('en-US', {
55
+ month: 'short',
56
+ day: 'numeric',
57
+ timeZone: 'UTC'
58
+ });
59
+ }
60
+ /** A cell as a number, `0` for anything that is not one. */ export function figureCount(value) {
61
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;
62
+ }
63
+ /** The row whose `key` cell is `label`: "Visitors" in a table of figures. */ export function figureRow(table, key, label) {
64
+ return table.rows.find((row)=>row[key] === label);
65
+ }
66
+ /** Whether a table carries a column, so a reader that changed shape is noticed rather than misread. */ export function figureHasColumn(table, key) {
67
+ return table.columns.some((column)=>column.key === key);
68
+ }
69
+ /** "1,204 (+12%)": a cell and, when there is an earlier week to compare with, its change. */ export function figureWithChange(table, row, key, changeKey) {
70
+ var _row_key;
71
+ const value = pluginFigureCellText(table, key, (_row_key = row[key]) != null ? _row_key : 0);
72
+ const change = row[changeKey];
73
+ if (typeof change !== 'number') return value;
74
+ return `${value} (${change === 0 ? 'no change' : pluginFigureCellText(table, changeKey, change)})`;
75
+ }
76
+ /** The named rows with the most of `key`, as "name 12 unit, name 4"; `null` when none has any. */ export function figureRanked(table, nameKey, key, unit = '', rows = table.rows) {
77
+ const top = rows.filter((row)=>typeof row[nameKey] === 'string' && figureCount(row[key]) > 0).slice(0, WEEKLY_SUMMARY_TOP_ROWS);
78
+ if (!top.length) return null;
79
+ return top.map((row, index)=>{
80
+ var _row_key;
81
+ const amount = pluginFigureCellText(table, key, (_row_key = row[key]) != null ? _row_key : 0);
82
+ return `${row[nameKey]} ${amount}${index === 0 && unit ? ` ${unit}` : ''}`;
83
+ }).join(', ');
84
+ }
85
+ /** "1 order", "18 orders". */ export function figurePlural(count, one, many) {
86
+ return `${count.toLocaleString('en-US')} ${count === 1 ? one : many}`;
87
+ }
88
+ /** The subject's counts, summed across sites by their noun, in the order the readers first gave them. */ export function weeklySummaryHeadline(sites) {
89
+ const sums = new Map();
90
+ for (const site of sites){
91
+ for (const { headline } of site.entries){
92
+ if (!headline || headline.count <= 0) continue;
93
+ const sum = sums.get(headline.one);
94
+ sums.set(headline.one, sum ? _extends({}, sum, {
95
+ count: sum.count + headline.count
96
+ }) : _extends({}, headline));
97
+ }
98
+ }
99
+ return [
100
+ ...sums.values()
101
+ ].slice(0, WEEKLY_SUMMARY_HEADLINE_COUNTS).map(({ count, one, many })=>figurePlural(count, one, many)).join(', ');
102
+ }
103
+ export function composeWeeklySummarySubject(workspaceName, sites) {
104
+ const headline = weeklySummaryHeadline(sites);
105
+ return headline ? `Your week at ${workspaceName}: ${headline}` : `Your week at ${workspaceName}`;
106
+ }
107
+ /**
108
+ * The email's words, or `null` when there is nothing to report at all — a
109
+ * week with no figures is not worth an email, and sending one anyway is how a
110
+ * summary trains people to ignore it. A site with nothing to say is left out.
111
+ */ export function composeWeeklySummaryEmailText(input) {
112
+ const sections = input.sites.map((site)=>({
113
+ site,
114
+ lines: site.entries.flatMap((entry)=>entry.lines)
115
+ })).filter(({ lines })=>lines.length > 0);
116
+ const workspaceLines = input.workspace.flatMap((entry)=>entry.lines);
117
+ if (!sections.length && !workspaceLines.length) return null;
118
+ const lines = [
119
+ `Here is how ${input.workspaceName} did last week, ${input.periodLabel}. ` + 'A change in brackets is against the week before.'
120
+ ];
121
+ for (const { site, lines: siteLines } of sections){
122
+ lines.push('', site.name, ...siteLines.map((line)=>`- ${line}`));
123
+ if (site.url) lines.push(`Open this site in ${input.productName}: ${site.url}`);
124
+ }
125
+ if (workspaceLines.length) {
126
+ lines.push('', `Across ${input.workspaceName}`, ...workspaceLines.map((line)=>`- ${line}`));
127
+ }
128
+ if (input.aiInsightsUrl) {
129
+ lines.push('', `Want to know why the numbers moved? AI weekly insights explain each site's figures every Monday. ` + `Turn them on from Ask about your numbers on a site's Analytics page: ${input.aiInsightsUrl}`);
130
+ }
131
+ if (!input.omitClosing) {
132
+ lines.push('', `You get this summary because you manage ${input.workspaceName}. Turn it off in Notifications: ${input.settingsUrl}`);
133
+ }
134
+ return lines.join('\n');
135
+ }
136
+
137
+ //# sourceMappingURL=weekly-summary.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/weekly-summary.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n pluginFigureCellText,\n pluginFigureIsoWeek,\n pluginFigureWindows,\n type PluginFigureCell,\n type PluginFigureHeadline,\n type PluginFigureRow,\n type PluginFigureTable,\n} from '../plugin-manager/plugin-figures'\n\n/**\n * THE WEEKLY SUMMARY (AGL-3867): the free Monday email that says how each of\n * a workspace's sites did last week, and how the workspace's own figures\n * moved.\n *\n * It spends nothing. Every figure comes from a `plugin-figures` reader that\n * declares a `weeklySummary`, and that reader's owner words its own lines, so\n * each plugin's counting rules decide what a figure is and nothing here names\n * one. AI weekly insights (AGL-2915) are the paid version that explains the\n * figures, and stay opt-in because each one spends the workspace's AI credits.\n *\n * This module is the period, the shared wording helpers the readers use, and\n * the email's words; the reads and the sends are\n * `@aglyn/tenant-data-admin/server/weekly-summary`.\n */\n\n/** The key a person's switch is stored under in `users/{uid}.digestPrefs`; on until turned off. */\nexport const WEEKLY_SUMMARY_DIGEST_KEY = 'weeklySummary'\n\n/** The window every figure is read over. */\nexport const WEEKLY_SUMMARY_DAYS = 7\n\n/** Rows a ranked line names: the top three. */\nexport const WEEKLY_SUMMARY_TOP_ROWS = 3\n\n/** Counts the subject line leads with, at most. */\nexport const WEEKLY_SUMMARY_HEADLINE_COUNTS = 3\n\n/**\n * The week a run reports on: the seven whole UTC days before the day it runs,\n * so a Monday run covers Monday to Sunday and never a part-day of today.\n * `now` is what each reader is handed; `week` keys the run's marker.\n */\nexport function weeklySummaryPeriod(runAt: Date): {\n now: Date\n week: string\n from: string\n to: string\n label: string\n} {\n const startOfToday = Date.UTC(runAt.getUTCFullYear(), runAt.getUTCMonth(), runAt.getUTCDate())\n const now = new Date(startOfToday - 1)\n const { current } = pluginFigureWindows(now, WEEKLY_SUMMARY_DAYS)\n return {\n now,\n week: pluginFigureIsoWeek(now),\n from: current.from,\n to: current.to,\n label: `${weeklySummaryDay(current.from)} – ${weeklySummaryDay(current.to)}`,\n }\n}\n\n/** `2026-10-05` as \"Oct 5\". */\nexport function weeklySummaryDay(day: string): string {\n const at = new Date(`${day}T00:00:00Z`)\n return at.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })\n}\n\n/** A cell as a number, `0` for anything that is not one. */\nexport function figureCount(value: PluginFigureCell | undefined): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0\n}\n\n/** The row whose `key` cell is `label`: \"Visitors\" in a table of figures. */\nexport function figureRow(table: PluginFigureTable, key: string, label: string): PluginFigureRow | undefined {\n return table.rows.find((row) => row[key] === label)\n}\n\n/** Whether a table carries a column, so a reader that changed shape is noticed rather than misread. */\nexport function figureHasColumn(table: PluginFigureTable, key: string): boolean {\n return table.columns.some((column) => column.key === key)\n}\n\n/** \"1,204 (+12%)\": a cell and, when there is an earlier week to compare with, its change. */\nexport function figureWithChange(\n table: PluginFigureTable,\n row: PluginFigureRow,\n key: string,\n changeKey: string,\n): string {\n const value = pluginFigureCellText(table, key, row[key] ?? 0)\n const change = row[changeKey]\n if (typeof change !== 'number') return value\n return `${value} (${change === 0 ? 'no change' : pluginFigureCellText(table, changeKey, change)})`\n}\n\n/** The named rows with the most of `key`, as \"name 12 unit, name 4\"; `null` when none has any. */\nexport function figureRanked(\n table: PluginFigureTable,\n nameKey: string,\n key: string,\n unit = '',\n rows: readonly PluginFigureRow[] = table.rows,\n): string | null {\n const top = rows\n .filter((row) => typeof row[nameKey] === 'string' && figureCount(row[key]) > 0)\n .slice(0, WEEKLY_SUMMARY_TOP_ROWS)\n if (!top.length) return null\n return top\n .map((row, index) => {\n const amount = pluginFigureCellText(table, key, row[key] ?? 0)\n return `${row[nameKey]} ${amount}${index === 0 && unit ? ` ${unit}` : ''}`\n })\n .join(', ')\n}\n\n/** \"1 order\", \"18 orders\". */\nexport function figurePlural(count: number, one: string, many: string): string {\n return `${count.toLocaleString('en-US')} ${count === 1 ? one : many}`\n}\n\n/** What one reader said this week: its lines and the count it adds to the subject. */\nexport interface WeeklySummaryEntry {\n lines: string[]\n headline: PluginFigureHeadline | null\n}\n\n/** One site's part of the email. */\nexport interface WeeklySummarySite {\n name: string\n /** The site's dashboard in the console, absolute; `null` with no origin to build it from. */\n url: string | null\n entries: readonly WeeklySummaryEntry[]\n}\n\n/** The subject's counts, summed across sites by their noun, in the order the readers first gave them. */\nexport function weeklySummaryHeadline(sites: readonly WeeklySummarySite[]): string {\n const sums = new Map<string, PluginFigureHeadline>()\n for (const site of sites) {\n for (const { headline } of site.entries) {\n if (!headline || headline.count <= 0) continue\n const sum = sums.get(headline.one)\n sums.set(headline.one, sum ? { ...sum, count: sum.count + headline.count } : { ...headline })\n }\n }\n return [...sums.values()]\n .slice(0, WEEKLY_SUMMARY_HEADLINE_COUNTS)\n .map(({ count, one, many }) => figurePlural(count, one, many))\n .join(', ')\n}\n\nexport function composeWeeklySummarySubject(workspaceName: string, sites: readonly WeeklySummarySite[]): string {\n const headline = weeklySummaryHeadline(sites)\n return headline ? `Your week at ${workspaceName}: ${headline}` : `Your week at ${workspaceName}`\n}\n\nexport interface WeeklySummaryEmailInput {\n workspaceName: string\n productName: string\n periodLabel: string\n sites: readonly WeeklySummarySite[]\n /** The workspace's own figures, such as its deals. */\n workspace: readonly WeeklySummaryEntry[]\n /** Where AI weekly insights are turned on, when the plan includes them and this person has not; else `null`. */\n aiInsightsUrl: string | null\n settingsUrl: string\n /** Drops the closing \"why\" line, which the designed email's footer carries. */\n omitClosing?: boolean\n}\n\n/**\n * The email's words, or `null` when there is nothing to report at all — a\n * week with no figures is not worth an email, and sending one anyway is how a\n * summary trains people to ignore it. A site with nothing to say is left out.\n */\nexport function composeWeeklySummaryEmailText(input: WeeklySummaryEmailInput): string | null {\n const sections = input.sites\n .map((site) => ({ site, lines: site.entries.flatMap((entry) => entry.lines) }))\n .filter(({ lines }) => lines.length > 0)\n const workspaceLines = input.workspace.flatMap((entry) => entry.lines)\n if (!sections.length && !workspaceLines.length) return null\n const lines: string[] = [\n `Here is how ${input.workspaceName} did last week, ${input.periodLabel}. ` +\n 'A change in brackets is against the week before.',\n ]\n for (const { site, lines: siteLines } of sections) {\n lines.push('', site.name, ...siteLines.map((line) => `- ${line}`))\n if (site.url) lines.push(`Open this site in ${input.productName}: ${site.url}`)\n }\n if (workspaceLines.length) {\n lines.push('', `Across ${input.workspaceName}`, ...workspaceLines.map((line) => `- ${line}`))\n }\n if (input.aiInsightsUrl) {\n lines.push(\n '',\n `Want to know why the numbers moved? AI weekly insights explain each site's figures every Monday. ` +\n `Turn them on from Ask about your numbers on a site's Analytics page: ${input.aiInsightsUrl}`,\n )\n }\n if (!input.omitClosing) {\n lines.push(\n '',\n `You get this summary because you manage ${input.workspaceName}. Turn it off in Notifications: ${input.settingsUrl}`,\n )\n }\n return lines.join('\\n')\n}\n"],"names":["pluginFigureCellText","pluginFigureIsoWeek","pluginFigureWindows","WEEKLY_SUMMARY_DIGEST_KEY","WEEKLY_SUMMARY_DAYS","WEEKLY_SUMMARY_TOP_ROWS","WEEKLY_SUMMARY_HEADLINE_COUNTS","weeklySummaryPeriod","runAt","startOfToday","Date","UTC","getUTCFullYear","getUTCMonth","getUTCDate","now","current","week","from","to","label","weeklySummaryDay","day","at","toLocaleDateString","month","timeZone","figureCount","value","Number","isFinite","figureRow","table","key","rows","find","row","figureHasColumn","columns","some","column","figureWithChange","changeKey","change","figureRanked","nameKey","unit","top","filter","slice","length","map","index","amount","join","figurePlural","count","one","many","toLocaleString","weeklySummaryHeadline","sites","sums","Map","site","headline","entries","sum","get","set","values","composeWeeklySummarySubject","workspaceName","composeWeeklySummaryEmailText","input","sections","lines","flatMap","entry","workspaceLines","workspace","periodLabel","siteLines","push","name","line","url","productName","aiInsightsUrl","omitClosing","settingsUrl"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,oBAAoB,EACpBC,mBAAmB,EACnBC,mBAAmB,QAKd,sCAAkC;AAEzC;;;;;;;;;;;;;;CAcC,GAED,iGAAiG,GACjG,OAAO,MAAMC,4BAA4B,gBAAe;AAExD,0CAA0C,GAC1C,OAAO,MAAMC,sBAAsB,EAAC;AAEpC,6CAA6C,GAC7C,OAAO,MAAMC,0BAA0B,EAAC;AAExC,iDAAiD,GACjD,OAAO,MAAMC,iCAAiC,EAAC;AAE/C;;;;CAIC,GACD,OAAO,SAASC,oBAAoBC,KAAW;IAO7C,MAAMC,eAAeC,KAAKC,GAAG,CAACH,MAAMI,cAAc,IAAIJ,MAAMK,WAAW,IAAIL,MAAMM,UAAU;IAC3F,MAAMC,MAAM,IAAIL,KAAKD,eAAe;IACpC,MAAM,EAAEO,OAAO,EAAE,GAAGd,oBAAoBa,KAAKX;IAC7C,OAAO;QACLW;QACAE,MAAMhB,oBAAoBc;QAC1BG,MAAMF,QAAQE,IAAI;QAClBC,IAAIH,QAAQG,EAAE;QACdC,OAAO,GAAGC,iBAAiBL,QAAQE,IAAI,EAAE,GAAG,EAAEG,iBAAiBL,QAAQG,EAAE,GAAG;IAC9E;AACF;AAEA,6BAA6B,GAC7B,OAAO,SAASE,iBAAiBC,GAAW;IAC1C,MAAMC,KAAK,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EnG;IACA,IAAI,CAACd,MAAMe,WAAW,EAAE;QACtBb,MAAMO,IAAI,CACR,IACA,CAAC,wCAAwC,EAAET,MAAMF,aAAa,CAAC,gCAAgC,EAAEE,MAAMgB,WAAW,EAAE;IAExH;IACA,OAAOd,MAAMtB,IAAI,CAAC;AACpB"}
@@ -165,6 +165,38 @@ export interface PluginFigureReader {
165
165
  /** The parameters the reader takes beyond its window; absent for none. */
166
166
  params?: readonly PluginFigureParam[];
167
167
  read(request: PluginFigureRequest): Promise<PluginFigureRead>;
168
+ /**
169
+ * How the reader's table reads in the weekly summary email (AGL-3867), for
170
+ * a reader that belongs in it; absent, the summary leaves it out. The owner
171
+ * words its own figures, because only the owner knows which of its columns
172
+ * say what happened: the summary reads it over 7 days with no parameters
173
+ * and lists what `lines` answers.
174
+ */
175
+ weeklySummary?: PluginFigureWeeklySummary;
176
+ }
177
+ /** A count a weekly summary's subject line may lead with, and how it is named. */
178
+ export interface PluginFigureHeadline {
179
+ count: number;
180
+ /** The noun for one, which also keys the sum across sites: "visitor". */
181
+ one: string;
182
+ /** The noun for any other count: "visitors". */
183
+ many: string;
184
+ }
185
+ /** A reader's part in the weekly summary. */
186
+ export interface PluginFigureWeeklySummary {
187
+ /**
188
+ * Which section lists it: `site`, under each site; `workspace`, once for the
189
+ * whole workspace. A workspace reader may say `site` to be read narrowed to
190
+ * each site. Absent, a site reader is `site` and a workspace reader is
191
+ * `workspace`.
192
+ */
193
+ per?: 'site' | 'workspace';
194
+ /** Where its lines sit in a section: lower first. */
195
+ order: number;
196
+ /** What the table says, one line each; `[]` when it has nothing to report this week. */
197
+ lines(table: PluginFigureTable): string[];
198
+ /** The count it adds to the subject line, or `null` for none this week. */
199
+ headline?(table: PluginFigureTable): PluginFigureHeadline | null;
168
200
  }
169
201
  export declare const PLUGIN_FIGURES: import("./plugin-services").PluginServiceContract<PluginFigureReader>;
170
202
  /** The most rows one table carries; the rest are counted in `omitted`. */
@@ -249,3 +281,13 @@ export declare function pluginFigureWindows(now: Date, days: number): {
249
281
  * reads as no change figure at all rather than as a rise from zero.
250
282
  */
251
283
  export declare function pluginFigureChange(current: number, previous: number | null): number | null;
284
+ /**
285
+ * How a cell reads to a person, by its column's kind; `null` is "—". Every
286
+ * consumer that shows a table to a person words its cells here, so an insight
287
+ * answer and a weekly summary print the same figure the same way.
288
+ */
289
+ export declare function pluginFigureCellText(table: Pick<PluginFigureTable, 'columns'>, key: string, value: PluginFigureCell | undefined): string;
290
+ /** The ISO 8601 week an instant falls in, in UTC (`2026-W38`). */
291
+ export declare function pluginFigureIsoWeek(at: Date): string;
292
+ /** The section of the weekly summary a reader is listed in, or `null` for a reader that is not in it. */
293
+ export declare function pluginFigureSummarySection(reader: PluginFigureReader): 'site' | 'workspace' | null;