@aglyn/aglyn 1.22.3 → 1.23.0
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.
- package/package.json +11 -11
- package/src/lib/app-utils/docs-help.generated.d.ts +2 -2
- package/src/lib/app-utils/docs-help.generated.js +2 -0
- package/src/lib/app-utils/docs-help.generated.js.map +1 -1
- package/src/lib/app-utils/error-beacon.d.ts +5 -1
- package/src/lib/app-utils/error-beacon.js +6 -2
- package/src/lib/app-utils/error-beacon.js.map +1 -1
- package/src/lib/app-utils/system-email-chrome.d.ts +6 -2
- package/src/lib/app-utils/system-email-chrome.js +15 -3
- package/src/lib/app-utils/system-email-chrome.js.map +1 -1
|
@@ -254,7 +254,11 @@ export declare function isRecaptchaTimeout(error: unknown): boolean;
|
|
|
254
254
|
* (`watchFirestoreQueueFailure`, AGL-4156).
|
|
255
255
|
*/
|
|
256
256
|
export declare const FIRESTORE_QUEUE_KIND = "firestore-queue";
|
|
257
|
-
/**
|
|
257
|
+
/**
|
|
258
|
+
* The assertion, or the IndexedDB rejection that arrives beside it: the
|
|
259
|
+
* browser ended the transaction under the SDK, whichever call it was in (a
|
|
260
|
+
* record read, a cursor, or opening the database in a webview).
|
|
261
|
+
*/
|
|
258
262
|
export declare function isFirestoreQueueFailureReport(error: unknown): boolean;
|
|
259
263
|
/**
|
|
260
264
|
* The label for a fault we RECOVER from and still want to see, or undefined.
|
|
@@ -301,8 +301,12 @@ const RECAPTCHA_TIMEOUT_MESSAGE = /^(?:Error: )?reCAPTCHA Timeout\b/;
|
|
|
301
301
|
* died, and the first b815 moves the tab onto the memory cache and reloads it
|
|
302
302
|
* (`watchFirestoreQueueFailure`, AGL-4156).
|
|
303
303
|
*/ export const FIRESTORE_QUEUE_KIND = 'firestore-queue';
|
|
304
|
-
const FIRESTORE_QUEUE_MESSAGE = /INTERNAL ASSERTION FAILED: Unexpected state \(ID: b815\)|Attempt to get a record from database without an in-progress transaction/;
|
|
305
|
-
/**
|
|
304
|
+
const FIRESTORE_QUEUE_MESSAGE = /INTERNAL ASSERTION FAILED: Unexpected state \(ID: b815\)|Attempt to (?:get a record from|open a cursor in) database without an in-progress transaction|IndexedDB transaction '[^']*' failed: AbortError/;
|
|
305
|
+
/**
|
|
306
|
+
* The assertion, or the IndexedDB rejection that arrives beside it: the
|
|
307
|
+
* browser ended the transaction under the SDK, whichever call it was in (a
|
|
308
|
+
* record read, a cursor, or opening the database in a webview).
|
|
309
|
+
*/ export function isFirestoreQueueFailureReport(error) {
|
|
306
310
|
const message = error == null ? void 0 : error.message;
|
|
307
311
|
return typeof message === 'string' && FIRESTORE_QUEUE_MESSAGE.test(message);
|
|
308
312
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/error-beacon.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * First-party browser error beacon (AGL-1538).\n *\n * Crashlytics does not exist for web, and adding a third-party error vendor\n * is a subprocessor-list decision that was explicitly deferred. This is the\n * first-party alternative: `window.onerror` / `unhandledrejection` handlers\n * that batch uncaught failures to the app's own `/api/errors` route, which\n * forwards them to Google Cloud Error Reporting — a processor already on the\n * list, alerting through the GCP stack that already pages (AGL-1502).\n *\n * Design constraints, in order:\n *\n * - **It must never become the outage.** Everything is wrapped; a failure to\n * report is silence, not a thrown error. Batches are capped per page so an\n * error thrown in a loop cannot DDoS our own API — after `maxPerPage`\n * events the beacon disarms for the rest of the pageview.\n * - **No PII.** URLs are scrubbed to origin + pathname (query strings and\n * fragments carry tokens and search terms), no user id, no cookies —\n * the payload is the error text and where in the CODE it happened.\n * Cross-origin scripts surface as the browser's opaque \"Script error.\"\n * with no stack; those are dropped since they cannot be acted on.\n * - **Dedupe.** One page throwing the same error on every frame reports it\n * once.\n *\n * Framework-free on purpose: the console mounts it from its root layout, the\n * tenant runtime from its own, and neither needs React here. Deliberately NO\n * 'use client' directive — inside this shared lib the directive forks the\n * module graph (AGL-52); every importer is already a client module.\n */\n\nimport { browserFamily, type BrowserFamily } from './browser-family'\nimport { isCrossPoolDesync } from './cross-pool-desync'\nimport { isForeignScriptUrl, stackFrameUrls } from './foreign-script'\nimport { isStaleBuildError, recoverStaleBuildRejection } from './stale-build-error'\n\nexport interface ErrorBeaconEvent {\n /**\n * Which handler caught it — 'error' | 'unhandledrejection' — or the\n * family it was labeled with: 'hydration', {@link AUTH_DESYNC_KIND},\n * {@link CHUNK_LOAD_KIND}, or a caller's own kind for a handled error.\n * Lands at `jsonPayload.kind`, where the alert policies filter on it.\n */\n kind: string\n /** Error message, clamped. */\n message: string\n /** Stack trace when the thrown value carried one, clamped. */\n stack?: string\n /** Script URL for stackless `window.onerror` events, scrubbed. */\n source?: string\n line?: number\n col?: number\n /** Page URL, scrubbed to origin + pathname. */\n url: string\n /**\n * On a `hydration` event from builds before AGL-3738 only: the page\n * translator whose rewrite was visible in the document when React gave up\n * — see {@link pageTranslationSignal}. Today's beacon drops a mismatch on a\n * translated page instead of sending it, so the field stays only for what\n * older tabs still report.\n */\n translated?: string\n /** On a `hydration` event only: `navigator.language`, clamped. */\n language?: string\n /**\n * On every event: the coarse browser family — one of seven, see\n * {@link browserFamily} (AGL-3732). Never the user agent, never a version.\n * Stamped by the queue, so a caller never sets it.\n */\n browser?: BrowserFamily\n}\n\nexport interface ErrorBeaconOptions {\n /** POST target; same-origin. Default `/api/errors`. */\n endpoint?: string\n /** 0..1 — fraction of pageviews that report at all. Default 1. */\n sampleRate?: number\n /** Max events reported per pageview before the beacon disarms. */\n maxPerPage?: number\n}\n\nconst MAX_MESSAGE = 1_024\nconst MAX_STACK = 8_192\nconst FLUSH_DELAY_MS = 2_000\n\n/** Origin + pathname only — query strings and fragments never leave. */\nfunction scrubUrl(raw: string | null | undefined): string {\n if (!raw) return ''\n try {\n const url = new URL(String(raw), window.location.href)\n return `${url.origin}${url.pathname}`\n } catch {\n return ''\n }\n}\n\nfunction clamp(value: unknown, max: number): string {\n return String(value ?? '').slice(0, max)\n}\n\n/**\n * Was this thrown by a script somebody ELSE evaluated into our page?\n *\n * Three tells, all read off the frames' positions and none off a function\n * name — a name would be a denylist needing a new entry per vendor.\n *\n * **Every frame is the DOCUMENT.** Measured 2026-09-02 (AGL-2523) on\n * aglyn.com/pricing, reported as an error of ours:\n *\n * sendDataToNative@https://aglyn.com/pricing:1:1325\n * sendPageHideMessage@https://aglyn.com/pricing:1:4139\n * @https://aglyn.com/pricing:1:6257\n *\n * `sendDataToNative` is the Meta in-app browser's native bridge, injected by\n * the Facebook/Instagram webview. In WebKit's format the code was evaluated\n * inline, so every frame is the document rather than a script we served.\n *\n * The document is every URL it has BEEN at, not only where it is now.\n * Measured 2026-10-31 on app.aglyn.com/signin, the same bridge:\n *\n * sendDataToNative@https://app.aglyn.com/:1:1325\n * sendPageHideMessage@https://app.aglyn.com/:1:4139\n * @https://app.aglyn.com/:1:6257\n *\n * The webview evaluated its script into the document at `/`, and the page\n * then moved to `/signin` on the client. A frame keeps the URL its script was\n * evaluated under; `location` does not. So the beacon passes both the URL the\n * document was served at ({@link documentLoadUrl}) and the one it is at now.\n * Any other page of ours is not this document, and a frame there keeps the\n * report.\n *\n * **Every frame is under a FOREIGN scheme.** Measured 2026-09-10 (AGL-2786) on\n * aglyn.com, the same bridge in the Android webview:\n *\n * at sendDataToNative (iabjs://navigation_performance_logger_android:1:10632)\n *\n * That webview names its scripts under its own `iabjs://` scheme, and\n * extensions do the same under theirs — see `FOREIGN_SCRIPT_SCHEMES`.\n *\n * **Every frame is a script with NO URL** (AGL-3423). Measured on the\n * sign-up page and on aglyn.com/solutions/agencies:\n *\n * at eval (<anonymous>)\n * at predicate (eval at evaluate (:234:30), <anonymous>:11:37)\n *\n * at <anonymous>:1:54\n * at <anonymous>:1:64\n *\n * An automation driver's `evaluate` and a snippet pasted into devtools. Every\n * script we serve has a URL — a chunk, a CDN asset, or the document for an\n * inline one — so a frame whose position is `<anonymous>:line:col`, or code\n * `eval`'d by such a frame, was not served by us. See\n * {@link anonymousScriptFrameCount} for exactly which frames count.\n *\n * ⚑ Deliberately `every`, and deliberately compared against the document\n * rather than against our asset path. A rule like \"no frame under\n * `/_next/static/`\" would delete EVERY error from a self-hosted deployment\n * that serves its assets from a CDN, because none of its frames would match.\n * Comparing to the document cannot fail that way: a CDN frame is not the\n * document either, so it keeps the report.\n *\n * A stack may mix the tells frame by frame. Nothing we ship can be fixed in\n * response to any of them, which is the same test the opaque `Script error.`\n * cut already applies.\n *\n * The cost is honest and small: a throw from one of our own inline\n * bootstrap scripts looks the same and is dropped with it. That trade buys a\n * rule that needs no maintenance as new webviews and extensions appear.\n */\nexport function isInjectedThirdPartyFrame(\n stack: string,\n documentUrls: string | readonly string[],\n): boolean {\n const urls = stackFrameUrls(stack)\n // No frames parsed is not evidence of anything — keep the report. A stack\n // with neither a URL nor an anonymous-script frame is exactly that: an\n // empty frame list must never read as \"every frame is injected\".\n if (!urls.length && !anonymousScriptFrameCount(stack)) return false\n // An empty URL is not a document. `scrubUrl` answers '' for a frame it\n // cannot parse, and that must not match a lookup that found nothing.\n const documentAt = (\n typeof documentUrls === 'string' ? [documentUrls] : documentUrls\n ).filter(Boolean)\n // Anonymous frames need no test of their own — they are injected by\n // definition — so `every` over the URLs is `every` over the whole stack.\n // One URL of ours, even as the origin of an `eval`, keeps the report.\n return urls.every(\n (url) => isForeignScriptUrl(url) || documentAt.includes(scrubUrl(url)),\n )\n}\n\n/**\n * The URL this document was served at, before any move on the client.\n *\n * The navigation timing entry keeps it: `history.pushState` changes\n * `location` and leaves the entry alone. Where an engine has no entry, the\n * page's URL now is the fallback, which is why the beacon reads this once,\n * at install: it is installed as its module loads, before the app's own\n * router has moved the page anywhere.\n */\nexport function documentLoadUrl(): string {\n try {\n const [entry] = performance.getEntriesByType('navigation')\n const served = scrubUrl(entry?.name)\n if (served) return served\n } catch {\n // An engine without navigation timing.\n }\n return scrubUrl(window.location.href)\n}\n\n/** A frame line, in V8's `at …` format or WebKit/Firefox's `fn@location`. */\nconst STACK_FRAME_LINE = /^\\s*at\\s|@/\n\n/**\n * A position in a script that has no URL.\n *\n * - `<anonymous>:line:col` — V8's name for such a script, both for a top-level\n * snippet and as the position of code run through `eval`/`new Function`.\n * - `eval at …` — V8's origin of `eval`'d code. When OUR script ran the eval\n * its URL is inside this origin, `stackFrameUrls` reads it, and the report\n * is kept; that is how the marketing plugin's `runJs` step stays reported.\n * - `debugger eval code:line:col` — Firefox's devtools console, in the\n * `fn@location` format WebKit also uses.\n *\n * ⚑ A BARE `(<anonymous>)` with no line and column is NOT one of these. It is\n * how V8 prints a builtin — `at Array.forEach (<anonymous>)`,\n * `at JSON.parse (<anonymous>)` — and a builtin is called by whoever called\n * it, including us.\n */\nconst ANONYMOUS_SCRIPT_POSITION =\n /<anonymous>:\\d+:\\d+|\\beval at\\s|\\bdebugger eval code:\\d+:\\d+/\n\n/** How many frames of this stack are in a script with no URL at all. */\nexport function anonymousScriptFrameCount(stack: string): number {\n let count = 0\n for (const line of stack.split('\\n')) {\n if (STACK_FRAME_LINE.test(line) && ANONYMOUS_SCRIPT_POSITION.test(line)) {\n count += 1\n }\n }\n return count\n}\n\n/**\n * Browser notices that are not failures, and that no fix of ours could act on.\n *\n * `ResizeObserver loop completed with undelivered notifications` (and its older\n * wording, `ResizeObserver loop limit exceeded`) is the browser saying it\n * deferred some resize callbacks to the next frame. Nothing threw: the event\n * carries no error object and no stack, and every observer is still\n * delivered. It arrived from the Besigner on 2026-09-26 and paged. Dropped, on\n * the browser's exact wording.\n */\nconst BENIGN_BROWSER_NOTICE =\n /^(?:Uncaught )?(?:Error: )?ResizeObserver loop (?:completed with undelivered notifications|limit exceeded)/\n\nexport function isBenignBrowserNotice(message: string): boolean {\n return BENIGN_BROWSER_NOTICE.test(message)\n}\n\n/**\n * Whether the document is a page a visitor navigated to over the web\n * (AGL-3759).\n *\n * Only `http:` and `https:` qualify. A document at `about:blank` or\n * `about:srcdoc` is a COPY of our page: a translator extension or a site that\n * frames our markup renders it into a fresh document with no URL of its own,\n * and our scripts run there too. Next.js's app router then throws\n * `Failed to construct 'URL': Invalid URL` resolving its canonical URL against\n * `window.location.href`, which no code of ours can prevent and no visitor on\n * the real page ever sees. `file:` (a saved page) and an extension's own\n * scheme are copies in the same sense.\n *\n * A missing or unreadable location is not a web document either: nothing\n * from it can be traced to a page we serve.\n */\nexport function isWebDocument(\n location: { protocol?: string } | null | undefined,\n): boolean {\n try {\n const protocol = location?.protocol\n return protocol === 'http:' || protocol === 'https:'\n } catch {\n return false\n }\n}\n\n/**\n * A rejection that says only \"this was cancelled\" (AGL-3734).\n *\n * `AbortError` is what a request rejects with when its `AbortSignal` fires —\n * a deadline we set, a component that unmounted, a search the author typed\n * past — and what the browser rejects every in-flight fetch with when the\n * document goes away under it. On 2026-10-10 one arrived from\n * `/edit-access`, the page a published site opens in a popup or a hidden\n * iframe and then CLOSES itself the moment it has its answer. The report had\n * no stack and no message past the name, so there was no call site to fix:\n * the page's own mint was already caught, and whatever else the console shell\n * had in flight was cut off by the site ending the page, which is the flow\n * working.\n *\n * Why the classifier rather than each call site: every request on every\n * console page can be the one in flight when a page is torn down, and the\n * abort is the intended outcome in every case. There is nothing a fix of ours\n * could change, and nothing in the report to locate it by.\n *\n * Narrow on purpose. Only `name === 'AbortError'`, and only for an UNHANDLED\n * REJECTION — not `TimeoutError`, which is `AbortSignal.timeout` saying a\n * deadline was MISSED (a real slowness), and not an uncaught `error` event or\n * a `reportHandledError` call, where somebody chose to report it.\n */\nexport function isAbortRejection(reason: unknown): boolean {\n try {\n return (\n typeof reason === 'object' &&\n reason !== null &&\n (reason as { name?: unknown }).name === 'AbortError'\n )\n } catch {\n // A getter that throws leaves the rejection reported, never dropped.\n return false\n }\n}\n\n/**\n * `kind` for Firebase's `auth/tenant-id-mismatch` — a sibling tab signed in to\n * another account pool (AGL-3280). The console recovers the tab by reloading\n * it once it is hidden and deliberately leaves the rejection unhandled so it\n * is still seen; this label is what lets it be seen by RATE instead of paging\n * on each of the several rejections one storage event raises.\n */\nexport const AUTH_DESYNC_KIND = 'auth-desync'\n\n/**\n * `kind` for a chunk the document names and the origin no longer serves\n * (AGL-3279). Every boundary reloads once for it; what still arrives is the\n * failure the reload did not cure. One of those is a visitor on a bad\n * connection; a burst of them is a broken deploy, which only a rate can tell.\n */\nexport const CHUNK_LOAD_KIND = 'chunk-load'\n\n/**\n * `kind` for reCAPTCHA's own `reCAPTCHA Timeout` rejection (AGL-4068).\n *\n * App Check's reCAPTCHA provider loads Google's script, and that script\n * rejects a promise of its own when its iframe does not answer in time: a\n * tab throttled in the background, a slow or blocked `gstatic.com`. No call\n * site of ours awaits it, so it lands as an unhandled rejection whose whole\n * stack is Google's script. App Check retries with backoff on the next token\n * request, so the visitor's page keeps working. One of these is a slow\n * network; a burst is App Check failing for everyone, which only a rate can\n * tell. Two arrived on 2026-10-25 and each paged.\n */\nexport const RECAPTCHA_TIMEOUT_KIND = 'recaptcha-timeout'\n\nconst RECAPTCHA_TIMEOUT_MESSAGE = /^(?:Error: )?reCAPTCHA Timeout\\b/\n\n/** Google's reCAPTCHA scripts, wherever the provider loads them from. */\nconst RECAPTCHA_SCRIPT_URL =\n /^https:\\/\\/(?:www\\.)?(?:gstatic\\.com|google\\.com|recaptcha\\.net)\\/recaptcha\\//\n\n/**\n * reCAPTCHA's timeout, by its wording AND by a stack that is only Google's\n * script. A message alone is not enough: one of our frames in the stack means\n * our code chose to throw that text, and that stays reported as itself.\n */\nexport function isRecaptchaTimeout(error: unknown): boolean {\n const message = (error as { message?: unknown } | null)?.message\n if (typeof message !== 'string' || !RECAPTCHA_TIMEOUT_MESSAGE.test(message)) {\n return false\n }\n const stack = (error as { stack?: unknown }).stack\n if (typeof stack !== 'string') return true\n return stackFrameUrls(stack).every((url) => RECAPTCHA_SCRIPT_URL.test(url))\n}\n\n/**\n * `kind` for the Firestore SDK's failed write queue: its IndexedDB transaction\n * died, and the first b815 moves the tab onto the memory cache and reloads it\n * (`watchFirestoreQueueFailure`, AGL-4156).\n */\nexport const FIRESTORE_QUEUE_KIND = 'firestore-queue'\n\nconst FIRESTORE_QUEUE_MESSAGE =\n /INTERNAL ASSERTION FAILED: Unexpected state \\(ID: b815\\)|Attempt to get a record from database without an in-progress transaction/\n\n/** The assertion, or the IndexedDB rejection that arrives beside it. */\nexport function isFirestoreQueueFailureReport(error: unknown): boolean {\n const message = (error as { message?: unknown } | null)?.message\n return typeof message === 'string' && FIRESTORE_QUEUE_MESSAGE.test(message)\n}\n\n/**\n * The label for a fault we RECOVER from and still want to see, or undefined.\n *\n * These could be ours, so unlike an injected stack they are never dropped:\n * they are written at full severity under their own `kind`, the per-entry\n * policy excludes that kind, and a rate policy watches it — the same split\n * `hydration` already has.\n */\nexport function recoveredErrorKind(error: unknown): string | undefined {\n try {\n if (isCrossPoolDesync(error)) return AUTH_DESYNC_KIND\n if (isStaleBuildError(error)) return CHUNK_LOAD_KIND\n if (isRecaptchaTimeout(error)) return RECAPTCHA_TIMEOUT_KIND\n if (isFirestoreQueueFailureReport(error)) return FIRESTORE_QUEUE_KIND\n } catch {\n // A getter that throws leaves the event unlabeled, never unreported.\n }\n return undefined\n}\n\n/**\n * React's hydration-mismatch family, which a page TRANSLATOR causes and a\n * real render divergence also causes.\n *\n * These are `onRecoverableError` reports, not crashes: React has already\n * re-rendered on the client and the visitor has a working page. They arrive\n * here as uncaught errors only because React re-throws them to `reportError`.\n *\n * They are marked rather than dropped, and the distinction is the whole\n * design. Dropping would hide a real hydration regression, which is a genuine\n * and expensive bug; the entries stay in `client-errors` at full severity and\n * still group in Error Reporting. What the mark buys is that the log-match\n * policy can stop paging on a single report, while a rate-based policy on the\n * same mark still catches a systemic one.\n *\n * ⚠️ THE MARK IS NOT A VERDICT, and the one cluster this repo has measured is\n * why. Eight #418 reports arrived inside a nine-minute window on 2026-09-01,\n * on one build, and the three pages they came from were exactly the three\n * carrying a form — `/`, `/pricing` and the solutions pages reported nothing\n * in the same window, which no browser-side rewrite would respect. A placed\n * form was expanding inside its own grafted subtree, so every page carrying\n * one shipped six nested `<form>` elements; nested forms are invalid HTML, the\n * parser dropped the inner ones, and the client tree disagreed with the server\n * tree. The visible cost was a submission the route never received, because\n * the native submit came from an unhandled ancestor and the browser fell back\n * to a GET with the visitor's name, email and message in the address bar. The\n * reports stopped because the nesting was fixed, roughly a quarter of an hour\n * after the last one.\n *\n * So a rate low enough not to page is a reason to READ the entry — the page\n * it names, and whether the set of pages has a shape — never a reason to\n * assume somebody's extension.\n */\nconst HYDRATION_MINIFIED = /Minified React error #(?:418|423|425)\\b/\nconst HYDRATION_TEXT =\n /Hydration failed because|Text content does not match server-rendered HTML|There was an error while hydrating/\n\nexport function isHydrationMismatch(message: string): boolean {\n return HYDRATION_MINIFIED.test(message) || HYDRATION_TEXT.test(message)\n}\n\n/**\n * WHICH TRANSLATOR rewrote this page's text, read off the document, or\n * undefined when none visibly did.\n *\n * A hydration report on its own cannot say whether React disagreed with our\n * server render or with a translator that rewrote the server's text before\n * React reached it, and the two look identical in `client-errors`: the\n * minified #418, a stack inside the react-dom chunk, the page URL, nothing\n * else. aglyn.com/ carried eight of them between 2026-09-22 and 2026-10-10.\n * The visitor at 2026-10-09 22:28Z went on to sign up two minutes later with\n * Chrome Translate rewriting the console (the `<font>` crash #1342 fixed); the\n * two on 2026-09-22/23 were desktop Chrome OS in Hyderabad, while every other\n * Indian, Pakistani and Turkish home-page visit in GA that fortnight hydrated\n * without a report — so neither the build nor the time zone was the variable,\n * and the beacon had nothing to say which visitor it was.\n *\n * The signatures are the ones each translator leaves on the DOM it rewrote:\n *\n * - Chrome (and every Chromium that ships Google Translate) sets\n * `translated-ltr` / `translated-rtl` on `<html>` and wraps each rewritten\n * run in `<font style=\"vertical-align: inherit;\">`.\n * - Microsoft Translator (Edge) stamps `_msttexthash` / `_msthash` on every\n * element whose text it replaced.\n * - Any translator that does the job properly rewrites `<html lang>`, which is\n * compared against the `servedLang` the beacon read at install, before\n * hydration began.\n *\n * Never throws: it runs inside the error handler.\n */\nexport function pageTranslationSignal(\n doc: Document,\n servedLang: string | null | undefined,\n): string | undefined {\n try {\n const root = doc.documentElement\n if (!root) return undefined\n if (\n root.classList.contains('translated-ltr') ||\n root.classList.contains('translated-rtl') ||\n doc.querySelector('font[style*=\"vertical-align: inherit\"]')\n ) {\n return 'chrome'\n }\n if (doc.querySelector('[_msttexthash], [_msthash]')) return 'microsoft'\n const lang = root.getAttribute('lang')\n if (servedLang && lang && lang.toLowerCase() !== servedLang.toLowerCase()) {\n return `lang:${clamp(lang, 16)}`\n }\n } catch {\n // An unreadable document leaves the event unlabeled, never unreported.\n }\n return undefined\n}\n\n/**\n * A TRANSLATOR'S MARK, REMEMBERED FROM THE MOMENT IT APPEARS (AGL-3738).\n *\n * {@link pageTranslationSignal} read at the moment React reports a mismatch\n * is reading a document the translator no longer owns. React reports a\n * hydration mismatch only after it has client-rendered the root to recover,\n * and that render resets `<html>`'s attributes to the ones it rendered —\n * Chrome's `translated-ltr` class goes, `lang` returns to the served value —\n * and replaces every `<font>` wrapper and hash-stamped element with fresh\n * nodes. Measured 2026-10-12 by hydrating aglyn.com/ with a Chrome-style\n * rewrite of one heading: the report fired with `<html lang=\"en\">`, no class\n * and no `<font>` left anywhere. Six es-US #418s arrived that day on\n * aglyn.com/ and orbita-digital.aglyn.app/ (a Spanish site served as `en`);\n * one carried `lang:en` — the beacon had been installed after the translator\n * set `lang=\"es\"`, so React's reset was the only rewrite left to see, and the\n * same simulation reproduces exactly that label — and the other five carried\n * nothing. The same two pages hydrated cleanly under es-US, en-GB and ru\n * locales and time zones: nothing on them formats by the visitor's locale.\n *\n * So the mark is read when the translator LEAVES it: once at install, for a\n * translator that ran first, and then from a `MutationObserver` until one is\n * seen. A translator rewrites the page before React reaches it — that is what\n * makes it a mismatch — so its mutations are delivered before the report.\n *\n * Cheap on purpose: one observer on `<html>`'s own `class`/`lang`, and one on\n * the tree that looks only at added `<font>` elements and Microsoft's hash\n * attributes, both disconnected as soon as a mark is found. Never throws, and\n * a browser without `MutationObserver` gets the read-at-report behavior.\n */\nexport function watchPageTranslation(\n doc: Document,\n servedLang: string | null | undefined,\n): () => string | undefined {\n let seen = pageTranslationSignal(doc, servedLang)\n const observers: MutationObserver[] = []\n\n const stop = () => {\n for (const observer of observers.splice(0)) observer.disconnect()\n }\n\n const inspect = (records: MutationRecord[]) => {\n if (seen) return\n let relevant = false\n for (const record of records) {\n if (record.type === 'attributes') {\n relevant = true\n break\n }\n for (const node of Array.from(record.addedNodes)) {\n if (node.nodeName === 'FONT') {\n relevant = true\n break\n }\n }\n if (relevant) break\n }\n if (!relevant) return\n seen = pageTranslationSignal(doc, servedLang)\n if (seen) stop()\n }\n\n try {\n const root = doc.documentElement\n if (!seen && root && typeof MutationObserver === 'function') {\n const onRoot = new MutationObserver(inspect)\n onRoot.observe(root, { attributes: true, attributeFilter: ['class', 'lang'] })\n const onTree = new MutationObserver(inspect)\n onTree.observe(root, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['_msttexthash', '_msthash'],\n })\n observers.push(onRoot, onTree)\n }\n } catch {\n // No observer: the report falls back to reading the document as it is.\n }\n\n return () => {\n try {\n // A rewrite in the same task as the report has not been delivered yet.\n for (const observer of observers) inspect(observer.takeRecords())\n return seen ?? pageTranslationSignal(doc, servedLang)\n } catch {\n return undefined\n }\n }\n}\n\n/**\n * WHAT A REJECTED PROMISE ACTUALLY CARRIED (AGL-3279).\n *\n * `unhandledrejection` hands over whatever was passed to `reject`, and only\n * an `Error` brings a message and a stack. A rejection with anything else —\n * an API's `{ code, message }` object, a `DOMException` from an aborted\n * fetch, a bare string, a `Response` — used to be reported as the literal\n * words \"Unhandled promise rejection\" with no stack and no other field,\n * which names the handler rather than the failure. One such report arrived\n * on 2026-09-21 from the Besigner editor and there is nothing in it to act\n * on: no message, no stack, no code, nothing but the page.\n *\n * So the value is DESCRIBED rather than defaulted. In order of how much a\n * reader can do with it: the error's own message; a string as itself; a\n * `name`/`code`/`message` shape assembled from whatever of those it has —\n * the shape every Firebase, DOM and fetch rejection takes; the value's own\n * `toString` when it says more than `[object Object]`; and last its own\n * keys, which at least name what kind of thing rejected.\n *\n * Nothing here may throw: a getter on the reason can, `toString` can, and\n * a describer that throws inside the rejection handler loses the report it\n * was called to improve.\n */\nexport function describeRejectionReason(reason: unknown): string {\n try {\n if (reason instanceof Error && reason.message) return reason.message\n if (typeof reason === 'string') return reason\n if (reason === null || reason === undefined) {\n return `Unhandled promise rejection (${String(reason)})`\n }\n if (typeof reason !== 'object') {\n return `Unhandled promise rejection (${typeof reason}: ${String(reason)})`\n }\n const shape = reason as Record<string, unknown>\n const named = [\n shape['name'] ?? shape['code'] ?? '',\n shape['message'] ?? shape['statusText'] ?? '',\n ]\n .map((part) => String(part ?? '').trim())\n .filter(Boolean)\n if (named.length) return named.join(': ')\n const printed = String(reason)\n if (printed && printed !== '[object Object]') return printed\n const keys = Object.keys(shape).slice(0, 12).join(', ')\n return keys\n ? `Unhandled promise rejection (object with ${keys})`\n : 'Unhandled promise rejection (empty object)'\n } catch {\n return 'Unhandled promise rejection (undescribable)'\n }\n}\n\n/**\n * How many frames a thrown error keeps, on a pageview that reports (AGL-3423).\n *\n * V8 keeps ten by default, and ten is not enough to find where a render loop\n * STARTED. The Besigner's one React #185 report (2026-09-24) was a\n * react-final-form field's `setState` inside final-form's `notify` loop, and\n * every one of its ten frames was inside those two libraries: the component\n * whose update fed the loop was cut off below them. Fifty reaches past a\n * form library's own frames to ours, and still fits the {@link MAX_STACK}\n * clamp at the length a minified frame line has.\n */\nexport const BEACON_STACK_TRACE_LIMIT = 50\n\n/**\n * Raises the engine's frame limit to `limit`, never lowers it. V8 and\n * JavaScriptCore read `Error.stackTraceLimit`; an engine that does not has no\n * such number, and is left without one rather than handed a property it\n * ignores. It applies to errors created after the call, which is why the\n * beacon sets it at install, at module scope of the app's first client chunk.\n */\nexport function raiseStackTraceLimit(limit: number): void {\n try {\n const engine = Error as ErrorConstructor & { stackTraceLimit?: number }\n const current = engine.stackTraceLimit\n if (typeof current !== 'number' || current >= limit) return\n engine.stackTraceLimit = limit\n } catch {\n // A frozen or exotic `Error` keeps its own limit.\n }\n}\n\nlet installed = false\n\n/**\n * The live beacon's `enqueue`, published for {@link reportHandledError}.\n *\n * Null until `installErrorBeacon` runs, and null forever on a surface that\n * never installs one — so a caught error reported from a page with no beacon\n * is silently dropped rather than throwing inside somebody's error handler.\n */\nlet publishEvent: ((event: ErrorBeaconEvent) => void) | null = null\n\n/**\n * Re-export so `error-beacon` stays the one name a caller has to know for\n * browser error reporting. The definition lives in its own module because a\n * boundary that imports it must not pull the installer below into a chunk\n * every visitor downloads.\n */\nexport { redispatchCaughtError } from './redispatch-caught-error'\n\n/**\n * Report an error the code ALREADY CAUGHT.\n *\n * The two window handlers below see only what nothing caught. A `catch` that\n * swallows its error is invisible to them by construction, which is the whole\n * failure mode this exists for: a background write that can only fail\n * silently is one that stays broken for as long as nobody thinks to look.\n *\n * It rides the same queue as an uncaught error, which is the point — the\n * dedupe collapses a failure that repeats on every edit into one report, and\n * `maxPerPage` bounds it, so a call site in a loop cannot turn a broken\n * feature into a flood. Reporting is never worth an exception of its own, so\n * every path here returns rather than throws.\n */\nexport function reportHandledError(\n error: unknown,\n options?: { kind?: string },\n): void {\n try {\n if (!publishEvent) return\n const thrown = error as Error | undefined\n const message = clamp(\n thrown?.message ?? (typeof error === 'string' ? error : ''),\n MAX_MESSAGE,\n )\n if (!message) return\n publishEvent({\n kind: clamp(options?.kind ?? 'handled', 32),\n message,\n stack: thrown?.stack ? clamp(thrown.stack, MAX_STACK) : undefined,\n url: scrubUrl(window.location.href),\n })\n } catch {\n // An observer that throws is worse than one that misses an event.\n }\n}\n\n/**\n * Installs the handlers once per page. Safe to call from module scope of a\n * client bundle: it no-ops during SSR and on repeat calls.\n */\nexport function installErrorBeacon(options?: ErrorBeaconOptions): void {\n if (typeof window === 'undefined' || installed) return\n installed = true\n\n const endpoint = options?.endpoint ?? '/api/errors'\n const sampleRate = options?.sampleRate ?? 1\n const maxPerPage = options?.maxPerPage ?? 10\n // Only a sampled pageview REPORTS. Every pageview recovers a stale build\n // (the rejection handler below), because a tab left on a dead deploy is a\n // visitor's problem whether or not its errors are counted.\n const sampled = Math.random() < sampleRate\n // A copy of the page in a document that is not on the web reports nothing\n // by either door, whatever it throws: see `isWebDocument`.\n const reporting = sampled && isWebDocument(window.location)\n // The document's language as SERVED, read before hydration and before any\n // translator has had a chance to rewrite it (`pageTranslationSignal`).\n const servedLang = document.documentElement?.getAttribute('lang') ?? null\n // Watched from now, because React's recovery erases the translator's marks\n // before a mismatch is reported (`watchPageTranslation`, AGL-3738).\n const translation = watchPageTranslation(document, servedLang)\n // Where the document was served, read now for the same reason: a script a\n // webview evaluated at load keeps this URL after the page moves on\n // (`isInjectedThirdPartyFrame`).\n const servedUrl = documentLoadUrl()\n if (reporting) raiseStackTraceLimit(BEACON_STACK_TRACE_LIMIT)\n // Classified once, here, and only the family is kept: the user-agent\n // string itself never reaches the queue (AGL-3732).\n let browser: BrowserFamily = 'other'\n try {\n browser = browserFamily(navigator.userAgent)\n } catch {\n // An unreadable navigator is just `other`.\n }\n\n const seen = new Set<string>()\n let queued: ErrorBeaconEvent[] = []\n let sent = 0\n let timer: ReturnType<typeof setTimeout> | null = null\n\n const flush = () => {\n timer = null\n if (!queued.length) return\n const batch = queued\n queued = []\n try {\n const body = JSON.stringify({ events: batch })\n // sendBeacon survives unloads and never blocks; keepalive fetch is the\n // fallback for browsers that refuse the payload.\n if (!navigator.sendBeacon?.(endpoint, body)) {\n void fetch(endpoint, {\n method: 'POST',\n body,\n keepalive: true,\n headers: { 'Content-Type': 'application/json' },\n }).catch((): undefined => undefined)\n }\n } catch {\n // Reporting never breaks the page.\n }\n }\n\n const enqueue = (event: ErrorBeaconEvent) => {\n if (!reporting || sent >= maxPerPage) return\n // Message + first stack line: enough identity to collapse a render loop\n // without collapsing distinct errors that share a message.\n const key = `${event.message}\\x00${(event.stack ?? '').split('\\n', 2).join('\\n')}`\n if (seen.has(key)) return\n seen.add(key)\n sent += 1\n queued.push({ ...event, browser })\n if (!timer) timer = setTimeout(flush, FLUSH_DELAY_MS)\n }\n // Null on a pageview that does not report, so it reports nothing by either\n // door rather than one by one and none by the other.\n publishEvent = reporting ? enqueue : null\n\n window.addEventListener('error', (event) => {\n try {\n const error = event.error as Error | undefined\n const message = clamp(error?.message ?? event.message, MAX_MESSAGE)\n // Cross-origin scripts yield an opaque \"Script error.\" with nothing\n // actionable attached; reporting it would only create a noisy group.\n if (!message || message === 'Script error.') return\n if (isBenignBrowserNotice(message)) return\n const pageUrl = scrubUrl(window.location.href)\n const fullStack = error?.stack ? String(error.stack) : undefined\n // A webview or extension that evaluated its own code into our page —\n // see `isInjectedThirdPartyFrame`. Nothing we ship can be changed in\n // response, so it is dropped on the same test as `Script error.`.\n // Judged on the WHOLE stack, before the clamp: a frame of ours past the\n // clamp still makes the error ours.\n if (fullStack && isInjectedThirdPartyFrame(fullStack, [pageUrl, servedUrl])) {\n return\n }\n const stack = fullStack ? clamp(fullStack, MAX_STACK) : undefined\n // MARKED, not dropped: a translator causes a hydration mismatch and so\n // does a real render divergence, and a recovered fault is still a\n // fault. Only a rate tells either apart from noise — and the\n // translator's own mark on the DOM, when it left one.\n const kind =\n recoveredErrorKind(error ?? { message }) ??\n (isHydrationMismatch(message) ? 'hydration' : 'error')\n const translated = kind === 'hydration' ? translation() : undefined\n // A mismatch on a page a translator rewrote is the translator's, not\n // ours (AGL-3738): React compared our render with text we did not\n // write, recovered, and the visitor has a working page. Nothing we ship\n // can change in response, so it goes the way of an injected stack. The\n // mark is evidence on the document, not a guess about the visitor — an\n // unmarked mismatch is still reported, and still the one to read.\n if (translated) return\n enqueue({\n kind,\n message,\n stack,\n source: scrubUrl(event.filename) || undefined,\n line: typeof event.lineno === 'number' ? event.lineno : undefined,\n col: typeof event.colno === 'number' ? event.colno : undefined,\n url: pageUrl,\n ...(kind === 'hydration' && navigator.language\n ? { language: clamp(navigator.language, 16) }\n : {}),\n })\n } catch {\n // Never rethrow from an error handler.\n }\n })\n\n window.addEventListener('unhandledrejection', (event) => {\n try {\n // An `import()` of a chunk this document names and the origin dropped,\n // which no boundary saw. Recovered by a reload once the tab is hidden,\n // and, like a boundary's reload, not reported: see\n // `recoverStaleBuildRejection`. A tab whose recovery is spent still\n // reports it, as `chunk-load`.\n if (recoverStaleBuildRejection(event.reason)) return\n // A cancelled request, ours or the browser's on teardown: see\n // `isAbortRejection` for why this is dropped and how narrowly.\n if (isAbortRejection(event.reason)) return\n const reason = event.reason as Error | undefined\n const message = clamp(describeRejectionReason(event.reason), MAX_MESSAGE)\n if (!message) return\n const pageUrl = scrubUrl(window.location.href)\n const fullStack = reason?.stack ? String(reason.stack) : undefined\n // The same injected-code drop as an uncaught error: a rejection raised\n // by a devtools snippet or an automation driver's `evaluate` is no more\n // ours for having been a promise.\n if (fullStack && isInjectedThirdPartyFrame(fullStack, [pageUrl, servedUrl])) {\n return\n }\n enqueue({\n kind: recoveredErrorKind(event.reason) ?? 'unhandledrejection',\n message,\n stack: fullStack ? clamp(fullStack, MAX_STACK) : undefined,\n url: pageUrl,\n })\n } catch {\n // Never rethrow from an error handler.\n }\n })\n\n // A batch waiting out its debounce when the page hides would be lost;\n // `pagehide`/`visibilitychange` are the last reliable moments to send.\n window.addEventListener('pagehide', flush)\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'hidden') flush()\n })\n}\n"],"names":["browserFamily","isCrossPoolDesync","isForeignScriptUrl","stackFrameUrls","isStaleBuildError","recoverStaleBuildRejection","MAX_MESSAGE","MAX_STACK","FLUSH_DELAY_MS","scrubUrl","raw","url","URL","String","window","location","href","origin","pathname","clamp","value","max","slice","isInjectedThirdPartyFrame","stack","documentUrls","urls","length","anonymousScriptFrameCount","documentAt","filter","Boolean","every","includes","documentLoadUrl","entry","performance","getEntriesByType","served","name","STACK_FRAME_LINE","ANONYMOUS_SCRIPT_POSITION","count","line","split","test","BENIGN_BROWSER_NOTICE","isBenignBrowserNotice","message","isWebDocument","protocol","isAbortRejection","reason","AUTH_DESYNC_KIND","CHUNK_LOAD_KIND","RECAPTCHA_TIMEOUT_KIND","RECAPTCHA_TIMEOUT_MESSAGE","RECAPTCHA_SCRIPT_URL","isRecaptchaTimeout","error","FIRESTORE_QUEUE_KIND","FIRESTORE_QUEUE_MESSAGE","isFirestoreQueueFailureReport","recoveredErrorKind","undefined","HYDRATION_MINIFIED","HYDRATION_TEXT","isHydrationMismatch","pageTranslationSignal","doc","servedLang","root","documentElement","classList","contains","querySelector","lang","getAttribute","toLowerCase","watchPageTranslation","seen","observers","stop","observer","splice","disconnect","inspect","records","relevant","record","type","node","Array","from","addedNodes","nodeName","MutationObserver","onRoot","observe","attributes","attributeFilter","onTree","childList","subtree","push","takeRecords","describeRejectionReason","shape","Error","named","map","part","trim","join","printed","keys","Object","BEACON_STACK_TRACE_LIMIT","raiseStackTraceLimit","limit","engine","current","stackTraceLimit","installed","publishEvent","redispatchCaughtError","reportHandledError","options","thrown","kind","installErrorBeacon","document","endpoint","sampleRate","maxPerPage","sampled","Math","random","reporting","translation","servedUrl","browser","navigator","userAgent","Set","queued","sent","timer","flush","batch","body","JSON","stringify","events","sendBeacon","fetch","method","keepalive","headers","catch","enqueue","event","key","has","add","setTimeout","addEventListener","pageUrl","fullStack","translated","source","filename","lineno","col","colno","language","visibilityState"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GAED,SAASA,aAAa,QAA4B,sBAAkB;AACpE,SAASC,iBA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;YACd,MAAMuH,UAAU9J,SAASK,OAAOC,QAAQ,CAACC,IAAI;YAC7C,MAAMwJ,YAAYpH,CAAAA,0BAAAA,OAAQ5B,KAAK,IAAGX,OAAOuC,OAAO5B,KAAK,IAAIwC;YACzD,uEAAuE;YACvE,wEAAwE;YACxE,kCAAkC;YAClC,IAAIwG,aAAajJ,0BAA0BiJ,WAAW;gBAACD;gBAAS3B;aAAU,GAAG;gBAC3E;YACF;YACAoB,QAAQ;gBACN/B,IAAI,GAAElE,sBAAAA,mBAAmBkG,MAAM7G,MAAM,aAA/BW,sBAAoC;gBAC1Cf;gBACAxB,OAAOgJ,YAAYrJ,MAAMqJ,WAAWjK,aAAayD;gBACjDrD,KAAK4J;YACP;QACF,EAAE,eAAM;QACN,uCAAuC;QACzC;IACF;IAEA,sEAAsE;IACtE,uEAAuE;IACvEzJ,OAAOwJ,gBAAgB,CAAC,YAAYlB;IACpCjB,SAASmC,gBAAgB,CAAC,oBAAoB;QAC5C,IAAInC,SAAS6C,eAAe,KAAK,UAAU5B;IAC7C;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/error-beacon.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * First-party browser error beacon (AGL-1538).\n *\n * Crashlytics does not exist for web, and adding a third-party error vendor\n * is a subprocessor-list decision that was explicitly deferred. This is the\n * first-party alternative: `window.onerror` / `unhandledrejection` handlers\n * that batch uncaught failures to the app's own `/api/errors` route, which\n * forwards them to Google Cloud Error Reporting — a processor already on the\n * list, alerting through the GCP stack that already pages (AGL-1502).\n *\n * Design constraints, in order:\n *\n * - **It must never become the outage.** Everything is wrapped; a failure to\n * report is silence, not a thrown error. Batches are capped per page so an\n * error thrown in a loop cannot DDoS our own API — after `maxPerPage`\n * events the beacon disarms for the rest of the pageview.\n * - **No PII.** URLs are scrubbed to origin + pathname (query strings and\n * fragments carry tokens and search terms), no user id, no cookies —\n * the payload is the error text and where in the CODE it happened.\n * Cross-origin scripts surface as the browser's opaque \"Script error.\"\n * with no stack; those are dropped since they cannot be acted on.\n * - **Dedupe.** One page throwing the same error on every frame reports it\n * once.\n *\n * Framework-free on purpose: the console mounts it from its root layout, the\n * tenant runtime from its own, and neither needs React here. Deliberately NO\n * 'use client' directive — inside this shared lib the directive forks the\n * module graph (AGL-52); every importer is already a client module.\n */\n\nimport { browserFamily, type BrowserFamily } from './browser-family'\nimport { isCrossPoolDesync } from './cross-pool-desync'\nimport { isForeignScriptUrl, stackFrameUrls } from './foreign-script'\nimport { isStaleBuildError, recoverStaleBuildRejection } from './stale-build-error'\n\nexport interface ErrorBeaconEvent {\n /**\n * Which handler caught it — 'error' | 'unhandledrejection' — or the\n * family it was labeled with: 'hydration', {@link AUTH_DESYNC_KIND},\n * {@link CHUNK_LOAD_KIND}, or a caller's own kind for a handled error.\n * Lands at `jsonPayload.kind`, where the alert policies filter on it.\n */\n kind: string\n /** Error message, clamped. */\n message: string\n /** Stack trace when the thrown value carried one, clamped. */\n stack?: string\n /** Script URL for stackless `window.onerror` events, scrubbed. */\n source?: string\n line?: number\n col?: number\n /** Page URL, scrubbed to origin + pathname. */\n url: string\n /**\n * On a `hydration` event from builds before AGL-3738 only: the page\n * translator whose rewrite was visible in the document when React gave up\n * — see {@link pageTranslationSignal}. Today's beacon drops a mismatch on a\n * translated page instead of sending it, so the field stays only for what\n * older tabs still report.\n */\n translated?: string\n /** On a `hydration` event only: `navigator.language`, clamped. */\n language?: string\n /**\n * On every event: the coarse browser family — one of seven, see\n * {@link browserFamily} (AGL-3732). Never the user agent, never a version.\n * Stamped by the queue, so a caller never sets it.\n */\n browser?: BrowserFamily\n}\n\nexport interface ErrorBeaconOptions {\n /** POST target; same-origin. Default `/api/errors`. */\n endpoint?: string\n /** 0..1 — fraction of pageviews that report at all. Default 1. */\n sampleRate?: number\n /** Max events reported per pageview before the beacon disarms. */\n maxPerPage?: number\n}\n\nconst MAX_MESSAGE = 1_024\nconst MAX_STACK = 8_192\nconst FLUSH_DELAY_MS = 2_000\n\n/** Origin + pathname only — query strings and fragments never leave. */\nfunction scrubUrl(raw: string | null | undefined): string {\n if (!raw) return ''\n try {\n const url = new URL(String(raw), window.location.href)\n return `${url.origin}${url.pathname}`\n } catch {\n return ''\n }\n}\n\nfunction clamp(value: unknown, max: number): string {\n return String(value ?? '').slice(0, max)\n}\n\n/**\n * Was this thrown by a script somebody ELSE evaluated into our page?\n *\n * Three tells, all read off the frames' positions and none off a function\n * name — a name would be a denylist needing a new entry per vendor.\n *\n * **Every frame is the DOCUMENT.** Measured 2026-09-02 (AGL-2523) on\n * aglyn.com/pricing, reported as an error of ours:\n *\n * sendDataToNative@https://aglyn.com/pricing:1:1325\n * sendPageHideMessage@https://aglyn.com/pricing:1:4139\n * @https://aglyn.com/pricing:1:6257\n *\n * `sendDataToNative` is the Meta in-app browser's native bridge, injected by\n * the Facebook/Instagram webview. In WebKit's format the code was evaluated\n * inline, so every frame is the document rather than a script we served.\n *\n * The document is every URL it has BEEN at, not only where it is now.\n * Measured 2026-10-31 on app.aglyn.com/signin, the same bridge:\n *\n * sendDataToNative@https://app.aglyn.com/:1:1325\n * sendPageHideMessage@https://app.aglyn.com/:1:4139\n * @https://app.aglyn.com/:1:6257\n *\n * The webview evaluated its script into the document at `/`, and the page\n * then moved to `/signin` on the client. A frame keeps the URL its script was\n * evaluated under; `location` does not. So the beacon passes both the URL the\n * document was served at ({@link documentLoadUrl}) and the one it is at now.\n * Any other page of ours is not this document, and a frame there keeps the\n * report.\n *\n * **Every frame is under a FOREIGN scheme.** Measured 2026-09-10 (AGL-2786) on\n * aglyn.com, the same bridge in the Android webview:\n *\n * at sendDataToNative (iabjs://navigation_performance_logger_android:1:10632)\n *\n * That webview names its scripts under its own `iabjs://` scheme, and\n * extensions do the same under theirs — see `FOREIGN_SCRIPT_SCHEMES`.\n *\n * **Every frame is a script with NO URL** (AGL-3423). Measured on the\n * sign-up page and on aglyn.com/solutions/agencies:\n *\n * at eval (<anonymous>)\n * at predicate (eval at evaluate (:234:30), <anonymous>:11:37)\n *\n * at <anonymous>:1:54\n * at <anonymous>:1:64\n *\n * An automation driver's `evaluate` and a snippet pasted into devtools. Every\n * script we serve has a URL — a chunk, a CDN asset, or the document for an\n * inline one — so a frame whose position is `<anonymous>:line:col`, or code\n * `eval`'d by such a frame, was not served by us. See\n * {@link anonymousScriptFrameCount} for exactly which frames count.\n *\n * ⚑ Deliberately `every`, and deliberately compared against the document\n * rather than against our asset path. A rule like \"no frame under\n * `/_next/static/`\" would delete EVERY error from a self-hosted deployment\n * that serves its assets from a CDN, because none of its frames would match.\n * Comparing to the document cannot fail that way: a CDN frame is not the\n * document either, so it keeps the report.\n *\n * A stack may mix the tells frame by frame. Nothing we ship can be fixed in\n * response to any of them, which is the same test the opaque `Script error.`\n * cut already applies.\n *\n * The cost is honest and small: a throw from one of our own inline\n * bootstrap scripts looks the same and is dropped with it. That trade buys a\n * rule that needs no maintenance as new webviews and extensions appear.\n */\nexport function isInjectedThirdPartyFrame(\n stack: string,\n documentUrls: string | readonly string[],\n): boolean {\n const urls = stackFrameUrls(stack)\n // No frames parsed is not evidence of anything — keep the report. A stack\n // with neither a URL nor an anonymous-script frame is exactly that: an\n // empty frame list must never read as \"every frame is injected\".\n if (!urls.length && !anonymousScriptFrameCount(stack)) return false\n // An empty URL is not a document. `scrubUrl` answers '' for a frame it\n // cannot parse, and that must not match a lookup that found nothing.\n const documentAt = (\n typeof documentUrls === 'string' ? [documentUrls] : documentUrls\n ).filter(Boolean)\n // Anonymous frames need no test of their own — they are injected by\n // definition — so `every` over the URLs is `every` over the whole stack.\n // One URL of ours, even as the origin of an `eval`, keeps the report.\n return urls.every(\n (url) => isForeignScriptUrl(url) || documentAt.includes(scrubUrl(url)),\n )\n}\n\n/**\n * The URL this document was served at, before any move on the client.\n *\n * The navigation timing entry keeps it: `history.pushState` changes\n * `location` and leaves the entry alone. Where an engine has no entry, the\n * page's URL now is the fallback, which is why the beacon reads this once,\n * at install: it is installed as its module loads, before the app's own\n * router has moved the page anywhere.\n */\nexport function documentLoadUrl(): string {\n try {\n const [entry] = performance.getEntriesByType('navigation')\n const served = scrubUrl(entry?.name)\n if (served) return served\n } catch {\n // An engine without navigation timing.\n }\n return scrubUrl(window.location.href)\n}\n\n/** A frame line, in V8's `at …` format or WebKit/Firefox's `fn@location`. */\nconst STACK_FRAME_LINE = /^\\s*at\\s|@/\n\n/**\n * A position in a script that has no URL.\n *\n * - `<anonymous>:line:col` — V8's name for such a script, both for a top-level\n * snippet and as the position of code run through `eval`/`new Function`.\n * - `eval at …` — V8's origin of `eval`'d code. When OUR script ran the eval\n * its URL is inside this origin, `stackFrameUrls` reads it, and the report\n * is kept; that is how the marketing plugin's `runJs` step stays reported.\n * - `debugger eval code:line:col` — Firefox's devtools console, in the\n * `fn@location` format WebKit also uses.\n *\n * ⚑ A BARE `(<anonymous>)` with no line and column is NOT one of these. It is\n * how V8 prints a builtin — `at Array.forEach (<anonymous>)`,\n * `at JSON.parse (<anonymous>)` — and a builtin is called by whoever called\n * it, including us.\n */\nconst ANONYMOUS_SCRIPT_POSITION =\n /<anonymous>:\\d+:\\d+|\\beval at\\s|\\bdebugger eval code:\\d+:\\d+/\n\n/** How many frames of this stack are in a script with no URL at all. */\nexport function anonymousScriptFrameCount(stack: string): number {\n let count = 0\n for (const line of stack.split('\\n')) {\n if (STACK_FRAME_LINE.test(line) && ANONYMOUS_SCRIPT_POSITION.test(line)) {\n count += 1\n }\n }\n return count\n}\n\n/**\n * Browser notices that are not failures, and that no fix of ours could act on.\n *\n * `ResizeObserver loop completed with undelivered notifications` (and its older\n * wording, `ResizeObserver loop limit exceeded`) is the browser saying it\n * deferred some resize callbacks to the next frame. Nothing threw: the event\n * carries no error object and no stack, and every observer is still\n * delivered. It arrived from the Besigner on 2026-09-26 and paged. Dropped, on\n * the browser's exact wording.\n */\nconst BENIGN_BROWSER_NOTICE =\n /^(?:Uncaught )?(?:Error: )?ResizeObserver loop (?:completed with undelivered notifications|limit exceeded)/\n\nexport function isBenignBrowserNotice(message: string): boolean {\n return BENIGN_BROWSER_NOTICE.test(message)\n}\n\n/**\n * Whether the document is a page a visitor navigated to over the web\n * (AGL-3759).\n *\n * Only `http:` and `https:` qualify. A document at `about:blank` or\n * `about:srcdoc` is a COPY of our page: a translator extension or a site that\n * frames our markup renders it into a fresh document with no URL of its own,\n * and our scripts run there too. Next.js's app router then throws\n * `Failed to construct 'URL': Invalid URL` resolving its canonical URL against\n * `window.location.href`, which no code of ours can prevent and no visitor on\n * the real page ever sees. `file:` (a saved page) and an extension's own\n * scheme are copies in the same sense.\n *\n * A missing or unreadable location is not a web document either: nothing\n * from it can be traced to a page we serve.\n */\nexport function isWebDocument(\n location: { protocol?: string } | null | undefined,\n): boolean {\n try {\n const protocol = location?.protocol\n return protocol === 'http:' || protocol === 'https:'\n } catch {\n return false\n }\n}\n\n/**\n * A rejection that says only \"this was cancelled\" (AGL-3734).\n *\n * `AbortError` is what a request rejects with when its `AbortSignal` fires —\n * a deadline we set, a component that unmounted, a search the author typed\n * past — and what the browser rejects every in-flight fetch with when the\n * document goes away under it. On 2026-10-10 one arrived from\n * `/edit-access`, the page a published site opens in a popup or a hidden\n * iframe and then CLOSES itself the moment it has its answer. The report had\n * no stack and no message past the name, so there was no call site to fix:\n * the page's own mint was already caught, and whatever else the console shell\n * had in flight was cut off by the site ending the page, which is the flow\n * working.\n *\n * Why the classifier rather than each call site: every request on every\n * console page can be the one in flight when a page is torn down, and the\n * abort is the intended outcome in every case. There is nothing a fix of ours\n * could change, and nothing in the report to locate it by.\n *\n * Narrow on purpose. Only `name === 'AbortError'`, and only for an UNHANDLED\n * REJECTION — not `TimeoutError`, which is `AbortSignal.timeout` saying a\n * deadline was MISSED (a real slowness), and not an uncaught `error` event or\n * a `reportHandledError` call, where somebody chose to report it.\n */\nexport function isAbortRejection(reason: unknown): boolean {\n try {\n return (\n typeof reason === 'object' &&\n reason !== null &&\n (reason as { name?: unknown }).name === 'AbortError'\n )\n } catch {\n // A getter that throws leaves the rejection reported, never dropped.\n return false\n }\n}\n\n/**\n * `kind` for Firebase's `auth/tenant-id-mismatch` — a sibling tab signed in to\n * another account pool (AGL-3280). The console recovers the tab by reloading\n * it once it is hidden and deliberately leaves the rejection unhandled so it\n * is still seen; this label is what lets it be seen by RATE instead of paging\n * on each of the several rejections one storage event raises.\n */\nexport const AUTH_DESYNC_KIND = 'auth-desync'\n\n/**\n * `kind` for a chunk the document names and the origin no longer serves\n * (AGL-3279). Every boundary reloads once for it; what still arrives is the\n * failure the reload did not cure. One of those is a visitor on a bad\n * connection; a burst of them is a broken deploy, which only a rate can tell.\n */\nexport const CHUNK_LOAD_KIND = 'chunk-load'\n\n/**\n * `kind` for reCAPTCHA's own `reCAPTCHA Timeout` rejection (AGL-4068).\n *\n * App Check's reCAPTCHA provider loads Google's script, and that script\n * rejects a promise of its own when its iframe does not answer in time: a\n * tab throttled in the background, a slow or blocked `gstatic.com`. No call\n * site of ours awaits it, so it lands as an unhandled rejection whose whole\n * stack is Google's script. App Check retries with backoff on the next token\n * request, so the visitor's page keeps working. One of these is a slow\n * network; a burst is App Check failing for everyone, which only a rate can\n * tell. Two arrived on 2026-10-25 and each paged.\n */\nexport const RECAPTCHA_TIMEOUT_KIND = 'recaptcha-timeout'\n\nconst RECAPTCHA_TIMEOUT_MESSAGE = /^(?:Error: )?reCAPTCHA Timeout\\b/\n\n/** Google's reCAPTCHA scripts, wherever the provider loads them from. */\nconst RECAPTCHA_SCRIPT_URL =\n /^https:\\/\\/(?:www\\.)?(?:gstatic\\.com|google\\.com|recaptcha\\.net)\\/recaptcha\\//\n\n/**\n * reCAPTCHA's timeout, by its wording AND by a stack that is only Google's\n * script. A message alone is not enough: one of our frames in the stack means\n * our code chose to throw that text, and that stays reported as itself.\n */\nexport function isRecaptchaTimeout(error: unknown): boolean {\n const message = (error as { message?: unknown } | null)?.message\n if (typeof message !== 'string' || !RECAPTCHA_TIMEOUT_MESSAGE.test(message)) {\n return false\n }\n const stack = (error as { stack?: unknown }).stack\n if (typeof stack !== 'string') return true\n return stackFrameUrls(stack).every((url) => RECAPTCHA_SCRIPT_URL.test(url))\n}\n\n/**\n * `kind` for the Firestore SDK's failed write queue: its IndexedDB transaction\n * died, and the first b815 moves the tab onto the memory cache and reloads it\n * (`watchFirestoreQueueFailure`, AGL-4156).\n */\nexport const FIRESTORE_QUEUE_KIND = 'firestore-queue'\n\nconst FIRESTORE_QUEUE_MESSAGE =\n /INTERNAL ASSERTION FAILED: Unexpected state \\(ID: b815\\)|Attempt to (?:get a record from|open a cursor in) database without an in-progress transaction|IndexedDB transaction '[^']*' failed: AbortError/\n\n/**\n * The assertion, or the IndexedDB rejection that arrives beside it: the\n * browser ended the transaction under the SDK, whichever call it was in (a\n * record read, a cursor, or opening the database in a webview).\n */\nexport function isFirestoreQueueFailureReport(error: unknown): boolean {\n const message = (error as { message?: unknown } | null)?.message\n return typeof message === 'string' && FIRESTORE_QUEUE_MESSAGE.test(message)\n}\n\n/**\n * The label for a fault we RECOVER from and still want to see, or undefined.\n *\n * These could be ours, so unlike an injected stack they are never dropped:\n * they are written at full severity under their own `kind`, the per-entry\n * policy excludes that kind, and a rate policy watches it — the same split\n * `hydration` already has.\n */\nexport function recoveredErrorKind(error: unknown): string | undefined {\n try {\n if (isCrossPoolDesync(error)) return AUTH_DESYNC_KIND\n if (isStaleBuildError(error)) return CHUNK_LOAD_KIND\n if (isRecaptchaTimeout(error)) return RECAPTCHA_TIMEOUT_KIND\n if (isFirestoreQueueFailureReport(error)) return FIRESTORE_QUEUE_KIND\n } catch {\n // A getter that throws leaves the event unlabeled, never unreported.\n }\n return undefined\n}\n\n/**\n * React's hydration-mismatch family, which a page TRANSLATOR causes and a\n * real render divergence also causes.\n *\n * These are `onRecoverableError` reports, not crashes: React has already\n * re-rendered on the client and the visitor has a working page. They arrive\n * here as uncaught errors only because React re-throws them to `reportError`.\n *\n * They are marked rather than dropped, and the distinction is the whole\n * design. Dropping would hide a real hydration regression, which is a genuine\n * and expensive bug; the entries stay in `client-errors` at full severity and\n * still group in Error Reporting. What the mark buys is that the log-match\n * policy can stop paging on a single report, while a rate-based policy on the\n * same mark still catches a systemic one.\n *\n * ⚠️ THE MARK IS NOT A VERDICT, and the one cluster this repo has measured is\n * why. Eight #418 reports arrived inside a nine-minute window on 2026-09-01,\n * on one build, and the three pages they came from were exactly the three\n * carrying a form — `/`, `/pricing` and the solutions pages reported nothing\n * in the same window, which no browser-side rewrite would respect. A placed\n * form was expanding inside its own grafted subtree, so every page carrying\n * one shipped six nested `<form>` elements; nested forms are invalid HTML, the\n * parser dropped the inner ones, and the client tree disagreed with the server\n * tree. The visible cost was a submission the route never received, because\n * the native submit came from an unhandled ancestor and the browser fell back\n * to a GET with the visitor's name, email and message in the address bar. The\n * reports stopped because the nesting was fixed, roughly a quarter of an hour\n * after the last one.\n *\n * So a rate low enough not to page is a reason to READ the entry — the page\n * it names, and whether the set of pages has a shape — never a reason to\n * assume somebody's extension.\n */\nconst HYDRATION_MINIFIED = /Minified React error #(?:418|423|425)\\b/\nconst HYDRATION_TEXT =\n /Hydration failed because|Text content does not match server-rendered HTML|There was an error while hydrating/\n\nexport function isHydrationMismatch(message: string): boolean {\n return HYDRATION_MINIFIED.test(message) || HYDRATION_TEXT.test(message)\n}\n\n/**\n * WHICH TRANSLATOR rewrote this page's text, read off the document, or\n * undefined when none visibly did.\n *\n * A hydration report on its own cannot say whether React disagreed with our\n * server render or with a translator that rewrote the server's text before\n * React reached it, and the two look identical in `client-errors`: the\n * minified #418, a stack inside the react-dom chunk, the page URL, nothing\n * else. aglyn.com/ carried eight of them between 2026-09-22 and 2026-10-10.\n * The visitor at 2026-10-09 22:28Z went on to sign up two minutes later with\n * Chrome Translate rewriting the console (the `<font>` crash #1342 fixed); the\n * two on 2026-09-22/23 were desktop Chrome OS in Hyderabad, while every other\n * Indian, Pakistani and Turkish home-page visit in GA that fortnight hydrated\n * without a report — so neither the build nor the time zone was the variable,\n * and the beacon had nothing to say which visitor it was.\n *\n * The signatures are the ones each translator leaves on the DOM it rewrote:\n *\n * - Chrome (and every Chromium that ships Google Translate) sets\n * `translated-ltr` / `translated-rtl` on `<html>` and wraps each rewritten\n * run in `<font style=\"vertical-align: inherit;\">`.\n * - Microsoft Translator (Edge) stamps `_msttexthash` / `_msthash` on every\n * element whose text it replaced.\n * - Any translator that does the job properly rewrites `<html lang>`, which is\n * compared against the `servedLang` the beacon read at install, before\n * hydration began.\n *\n * Never throws: it runs inside the error handler.\n */\nexport function pageTranslationSignal(\n doc: Document,\n servedLang: string | null | undefined,\n): string | undefined {\n try {\n const root = doc.documentElement\n if (!root) return undefined\n if (\n root.classList.contains('translated-ltr') ||\n root.classList.contains('translated-rtl') ||\n doc.querySelector('font[style*=\"vertical-align: inherit\"]')\n ) {\n return 'chrome'\n }\n if (doc.querySelector('[_msttexthash], [_msthash]')) return 'microsoft'\n const lang = root.getAttribute('lang')\n if (servedLang && lang && lang.toLowerCase() !== servedLang.toLowerCase()) {\n return `lang:${clamp(lang, 16)}`\n }\n } catch {\n // An unreadable document leaves the event unlabeled, never unreported.\n }\n return undefined\n}\n\n/**\n * A TRANSLATOR'S MARK, REMEMBERED FROM THE MOMENT IT APPEARS (AGL-3738).\n *\n * {@link pageTranslationSignal} read at the moment React reports a mismatch\n * is reading a document the translator no longer owns. React reports a\n * hydration mismatch only after it has client-rendered the root to recover,\n * and that render resets `<html>`'s attributes to the ones it rendered —\n * Chrome's `translated-ltr` class goes, `lang` returns to the served value —\n * and replaces every `<font>` wrapper and hash-stamped element with fresh\n * nodes. Measured 2026-10-12 by hydrating aglyn.com/ with a Chrome-style\n * rewrite of one heading: the report fired with `<html lang=\"en\">`, no class\n * and no `<font>` left anywhere. Six es-US #418s arrived that day on\n * aglyn.com/ and orbita-digital.aglyn.app/ (a Spanish site served as `en`);\n * one carried `lang:en` — the beacon had been installed after the translator\n * set `lang=\"es\"`, so React's reset was the only rewrite left to see, and the\n * same simulation reproduces exactly that label — and the other five carried\n * nothing. The same two pages hydrated cleanly under es-US, en-GB and ru\n * locales and time zones: nothing on them formats by the visitor's locale.\n *\n * So the mark is read when the translator LEAVES it: once at install, for a\n * translator that ran first, and then from a `MutationObserver` until one is\n * seen. A translator rewrites the page before React reaches it — that is what\n * makes it a mismatch — so its mutations are delivered before the report.\n *\n * Cheap on purpose: one observer on `<html>`'s own `class`/`lang`, and one on\n * the tree that looks only at added `<font>` elements and Microsoft's hash\n * attributes, both disconnected as soon as a mark is found. Never throws, and\n * a browser without `MutationObserver` gets the read-at-report behavior.\n */\nexport function watchPageTranslation(\n doc: Document,\n servedLang: string | null | undefined,\n): () => string | undefined {\n let seen = pageTranslationSignal(doc, servedLang)\n const observers: MutationObserver[] = []\n\n const stop = () => {\n for (const observer of observers.splice(0)) observer.disconnect()\n }\n\n const inspect = (records: MutationRecord[]) => {\n if (seen) return\n let relevant = false\n for (const record of records) {\n if (record.type === 'attributes') {\n relevant = true\n break\n }\n for (const node of Array.from(record.addedNodes)) {\n if (node.nodeName === 'FONT') {\n relevant = true\n break\n }\n }\n if (relevant) break\n }\n if (!relevant) return\n seen = pageTranslationSignal(doc, servedLang)\n if (seen) stop()\n }\n\n try {\n const root = doc.documentElement\n if (!seen && root && typeof MutationObserver === 'function') {\n const onRoot = new MutationObserver(inspect)\n onRoot.observe(root, { attributes: true, attributeFilter: ['class', 'lang'] })\n const onTree = new MutationObserver(inspect)\n onTree.observe(root, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['_msttexthash', '_msthash'],\n })\n observers.push(onRoot, onTree)\n }\n } catch {\n // No observer: the report falls back to reading the document as it is.\n }\n\n return () => {\n try {\n // A rewrite in the same task as the report has not been delivered yet.\n for (const observer of observers) inspect(observer.takeRecords())\n return seen ?? pageTranslationSignal(doc, servedLang)\n } catch {\n return undefined\n }\n }\n}\n\n/**\n * WHAT A REJECTED PROMISE ACTUALLY CARRIED (AGL-3279).\n *\n * `unhandledrejection` hands over whatever was passed to `reject`, and only\n * an `Error` brings a message and a stack. A rejection with anything else —\n * an API's `{ code, message }` object, a `DOMException` from an aborted\n * fetch, a bare string, a `Response` — used to be reported as the literal\n * words \"Unhandled promise rejection\" with no stack and no other field,\n * which names the handler rather than the failure. One such report arrived\n * on 2026-09-21 from the Besigner editor and there is nothing in it to act\n * on: no message, no stack, no code, nothing but the page.\n *\n * So the value is DESCRIBED rather than defaulted. In order of how much a\n * reader can do with it: the error's own message; a string as itself; a\n * `name`/`code`/`message` shape assembled from whatever of those it has —\n * the shape every Firebase, DOM and fetch rejection takes; the value's own\n * `toString` when it says more than `[object Object]`; and last its own\n * keys, which at least name what kind of thing rejected.\n *\n * Nothing here may throw: a getter on the reason can, `toString` can, and\n * a describer that throws inside the rejection handler loses the report it\n * was called to improve.\n */\nexport function describeRejectionReason(reason: unknown): string {\n try {\n if (reason instanceof Error && reason.message) return reason.message\n if (typeof reason === 'string') return reason\n if (reason === null || reason === undefined) {\n return `Unhandled promise rejection (${String(reason)})`\n }\n if (typeof reason !== 'object') {\n return `Unhandled promise rejection (${typeof reason}: ${String(reason)})`\n }\n const shape = reason as Record<string, unknown>\n const named = [\n shape['name'] ?? shape['code'] ?? '',\n shape['message'] ?? shape['statusText'] ?? '',\n ]\n .map((part) => String(part ?? '').trim())\n .filter(Boolean)\n if (named.length) return named.join(': ')\n const printed = String(reason)\n if (printed && printed !== '[object Object]') return printed\n const keys = Object.keys(shape).slice(0, 12).join(', ')\n return keys\n ? `Unhandled promise rejection (object with ${keys})`\n : 'Unhandled promise rejection (empty object)'\n } catch {\n return 'Unhandled promise rejection (undescribable)'\n }\n}\n\n/**\n * How many frames a thrown error keeps, on a pageview that reports (AGL-3423).\n *\n * V8 keeps ten by default, and ten is not enough to find where a render loop\n * STARTED. The Besigner's one React #185 report (2026-09-24) was a\n * react-final-form field's `setState` inside final-form's `notify` loop, and\n * every one of its ten frames was inside those two libraries: the component\n * whose update fed the loop was cut off below them. Fifty reaches past a\n * form library's own frames to ours, and still fits the {@link MAX_STACK}\n * clamp at the length a minified frame line has.\n */\nexport const BEACON_STACK_TRACE_LIMIT = 50\n\n/**\n * Raises the engine's frame limit to `limit`, never lowers it. V8 and\n * JavaScriptCore read `Error.stackTraceLimit`; an engine that does not has no\n * such number, and is left without one rather than handed a property it\n * ignores. It applies to errors created after the call, which is why the\n * beacon sets it at install, at module scope of the app's first client chunk.\n */\nexport function raiseStackTraceLimit(limit: number): void {\n try {\n const engine = Error as ErrorConstructor & { stackTraceLimit?: number }\n const current = engine.stackTraceLimit\n if (typeof current !== 'number' || current >= limit) return\n engine.stackTraceLimit = limit\n } catch {\n // A frozen or exotic `Error` keeps its own limit.\n }\n}\n\nlet installed = false\n\n/**\n * The live beacon's `enqueue`, published for {@link reportHandledError}.\n *\n * Null until `installErrorBeacon` runs, and null forever on a surface that\n * never installs one — so a caught error reported from a page with no beacon\n * is silently dropped rather than throwing inside somebody's error handler.\n */\nlet publishEvent: ((event: ErrorBeaconEvent) => void) | null = null\n\n/**\n * Re-export so `error-beacon` stays the one name a caller has to know for\n * browser error reporting. The definition lives in its own module because a\n * boundary that imports it must not pull the installer below into a chunk\n * every visitor downloads.\n */\nexport { redispatchCaughtError } from './redispatch-caught-error'\n\n/**\n * Report an error the code ALREADY CAUGHT.\n *\n * The two window handlers below see only what nothing caught. A `catch` that\n * swallows its error is invisible to them by construction, which is the whole\n * failure mode this exists for: a background write that can only fail\n * silently is one that stays broken for as long as nobody thinks to look.\n *\n * It rides the same queue as an uncaught error, which is the point — the\n * dedupe collapses a failure that repeats on every edit into one report, and\n * `maxPerPage` bounds it, so a call site in a loop cannot turn a broken\n * feature into a flood. Reporting is never worth an exception of its own, so\n * every path here returns rather than throws.\n */\nexport function reportHandledError(\n error: unknown,\n options?: { kind?: string },\n): void {\n try {\n if (!publishEvent) return\n const thrown = error as Error | undefined\n const message = clamp(\n thrown?.message ?? (typeof error === 'string' ? error : ''),\n MAX_MESSAGE,\n )\n if (!message) return\n publishEvent({\n kind: clamp(options?.kind ?? 'handled', 32),\n message,\n stack: thrown?.stack ? clamp(thrown.stack, MAX_STACK) : undefined,\n url: scrubUrl(window.location.href),\n })\n } catch {\n // An observer that throws is worse than one that misses an event.\n }\n}\n\n/**\n * Installs the handlers once per page. Safe to call from module scope of a\n * client bundle: it no-ops during SSR and on repeat calls.\n */\nexport function installErrorBeacon(options?: ErrorBeaconOptions): void {\n if (typeof window === 'undefined' || installed) return\n installed = true\n\n const endpoint = options?.endpoint ?? '/api/errors'\n const sampleRate = options?.sampleRate ?? 1\n const maxPerPage = options?.maxPerPage ?? 10\n // Only a sampled pageview REPORTS. Every pageview recovers a stale build\n // (the rejection handler below), because a tab left on a dead deploy is a\n // visitor's problem whether or not its errors are counted.\n const sampled = Math.random() < sampleRate\n // A copy of the page in a document that is not on the web reports nothing\n // by either door, whatever it throws: see `isWebDocument`.\n const reporting = sampled && isWebDocument(window.location)\n // The document's language as SERVED, read before hydration and before any\n // translator has had a chance to rewrite it (`pageTranslationSignal`).\n const servedLang = document.documentElement?.getAttribute('lang') ?? null\n // Watched from now, because React's recovery erases the translator's marks\n // before a mismatch is reported (`watchPageTranslation`, AGL-3738).\n const translation = watchPageTranslation(document, servedLang)\n // Where the document was served, read now for the same reason: a script a\n // webview evaluated at load keeps this URL after the page moves on\n // (`isInjectedThirdPartyFrame`).\n const servedUrl = documentLoadUrl()\n if (reporting) raiseStackTraceLimit(BEACON_STACK_TRACE_LIMIT)\n // Classified once, here, and only the family is kept: the user-agent\n // string itself never reaches the queue (AGL-3732).\n let browser: BrowserFamily = 'other'\n try {\n browser = browserFamily(navigator.userAgent)\n } catch {\n // An unreadable navigator is just `other`.\n }\n\n const seen = new Set<string>()\n let queued: ErrorBeaconEvent[] = []\n let sent = 0\n let timer: ReturnType<typeof setTimeout> | null = null\n\n const flush = () => {\n timer = null\n if (!queued.length) return\n const batch = queued\n queued = []\n try {\n const body = JSON.stringify({ events: batch })\n // sendBeacon survives unloads and never blocks; keepalive fetch is the\n // fallback for browsers that refuse the payload.\n if (!navigator.sendBeacon?.(endpoint, body)) {\n void fetch(endpoint, {\n method: 'POST',\n body,\n keepalive: true,\n headers: { 'Content-Type': 'application/json' },\n }).catch((): undefined => undefined)\n }\n } catch {\n // Reporting never breaks the page.\n }\n }\n\n const enqueue = (event: ErrorBeaconEvent) => {\n if (!reporting || sent >= maxPerPage) return\n // Message + first stack line: enough identity to collapse a render loop\n // without collapsing distinct errors that share a message.\n const key = `${event.message}\\x00${(event.stack ?? '').split('\\n', 2).join('\\n')}`\n if (seen.has(key)) return\n seen.add(key)\n sent += 1\n queued.push({ ...event, browser })\n if (!timer) timer = setTimeout(flush, FLUSH_DELAY_MS)\n }\n // Null on a pageview that does not report, so it reports nothing by either\n // door rather than one by one and none by the other.\n publishEvent = reporting ? enqueue : null\n\n window.addEventListener('error', (event) => {\n try {\n const error = event.error as Error | undefined\n const message = clamp(error?.message ?? event.message, MAX_MESSAGE)\n // Cross-origin scripts yield an opaque \"Script error.\" with nothing\n // actionable attached; reporting it would only create a noisy group.\n if (!message || message === 'Script error.') return\n if (isBenignBrowserNotice(message)) return\n const pageUrl = scrubUrl(window.location.href)\n const fullStack = error?.stack ? String(error.stack) : undefined\n // A webview or extension that evaluated its own code into our page —\n // see `isInjectedThirdPartyFrame`. Nothing we ship can be changed in\n // response, so it is dropped on the same test as `Script error.`.\n // Judged on the WHOLE stack, before the clamp: a frame of ours past the\n // clamp still makes the error ours.\n if (fullStack && isInjectedThirdPartyFrame(fullStack, [pageUrl, servedUrl])) {\n return\n }\n const stack = fullStack ? clamp(fullStack, MAX_STACK) : undefined\n // MARKED, not dropped: a translator causes a hydration mismatch and so\n // does a real render divergence, and a recovered fault is still a\n // fault. Only a rate tells either apart from noise — and the\n // translator's own mark on the DOM, when it left one.\n const kind =\n recoveredErrorKind(error ?? { message }) ??\n (isHydrationMismatch(message) ? 'hydration' : 'error')\n const translated = kind === 'hydration' ? translation() : undefined\n // A mismatch on a page a translator rewrote is the translator's, not\n // ours (AGL-3738): React compared our render with text we did not\n // write, recovered, and the visitor has a working page. Nothing we ship\n // can change in response, so it goes the way of an injected stack. The\n // mark is evidence on the document, not a guess about the visitor — an\n // unmarked mismatch is still reported, and still the one to read.\n if (translated) return\n enqueue({\n kind,\n message,\n stack,\n source: scrubUrl(event.filename) || undefined,\n line: typeof event.lineno === 'number' ? event.lineno : undefined,\n col: typeof event.colno === 'number' ? event.colno : undefined,\n url: pageUrl,\n ...(kind === 'hydration' && navigator.language\n ? { language: clamp(navigator.language, 16) }\n : {}),\n })\n } catch {\n // Never rethrow from an error handler.\n }\n })\n\n window.addEventListener('unhandledrejection', (event) => {\n try {\n // An `import()` of a chunk this document names and the origin dropped,\n // which no boundary saw. Recovered by a reload once the tab is hidden,\n // and, like a boundary's reload, not reported: see\n // `recoverStaleBuildRejection`. A tab whose recovery is spent still\n // reports it, as `chunk-load`.\n if (recoverStaleBuildRejection(event.reason)) return\n // A cancelled request, ours or the browser's on teardown: see\n // `isAbortRejection` for why this is dropped and how narrowly.\n if (isAbortRejection(event.reason)) return\n const reason = event.reason as Error | undefined\n const message = clamp(describeRejectionReason(event.reason), MAX_MESSAGE)\n if (!message) return\n const pageUrl = scrubUrl(window.location.href)\n const fullStack = reason?.stack ? String(reason.stack) : undefined\n // The same injected-code drop as an uncaught error: a rejection raised\n // by a devtools snippet or an automation driver's `evaluate` is no more\n // ours for having been a promise.\n if (fullStack && isInjectedThirdPartyFrame(fullStack, [pageUrl, servedUrl])) {\n return\n }\n enqueue({\n kind: recoveredErrorKind(event.reason) ?? 'unhandledrejection',\n message,\n stack: fullStack ? clamp(fullStack, MAX_STACK) : undefined,\n url: pageUrl,\n })\n } catch {\n // Never rethrow from an error handler.\n }\n })\n\n // A batch waiting out its debounce when the page hides would be lost;\n // `pagehide`/`visibilitychange` are the last reliable moments to send.\n window.addEventListener('pagehide', flush)\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'hidden') flush()\n })\n}\n"],"names":["browserFamily","isCrossPoolDesync","isForeignScriptUrl","stackFrameUrls","isStaleBuildError","recoverStaleBuildRejection","MAX_MESSAGE","MAX_STACK","FLUSH_DELAY_MS","scrubUrl","raw","url","URL","String","window","location","href","origin","pathname","clamp","value","max","slice","isInjectedThirdPartyFrame","stack","documentUrls","urls","length","anonymousScriptFrameCount","documentAt","filter","Boolean","every","includes","documentLoadUrl","entry","performance","getEntriesByType","served","name","STACK_FRAME_LINE","ANONYMOUS_SCRIPT_POSITION","count","line","split","test","BENIGN_BROWSER_NOTICE","isBenignBrowserNotice","message","isWebDocument","protocol","isAbortRejection","reason","AUTH_DESYNC_KIND","CHUNK_LOAD_KIND","RECAPTCHA_TIMEOUT_KIND","RECAPTCHA_TIMEOUT_MESSAGE","RECAPTCHA_SCRIPT_URL","isRecaptchaTimeout","error","FIRESTORE_QUEUE_KIND","FIRESTORE_QUEUE_MESSAGE","isFirestoreQueueFailureReport","recoveredErrorKind","undefined","HYDRATION_MINIFIED","HYDRATION_TEXT","isHydrationMismatch","pageTranslationSignal","doc","servedLang","root","documentElement","classList","contains","querySelector","lang","getAttribute","toLowerCase","watchPageTranslation","seen","observers","stop","observer","splice","disconnect","inspect","records","relevant","record","type","node","Array","from","addedNodes","nodeName","MutationObserver","onRoot","observe","attributes","attributeFilter","onTree","childList","subtree","push","takeRecords","describeRejectionReason","shape","Error","named","map","part","trim","join","printed","keys","Object","BEACON_STACK_TRACE_LIMIT","raiseStackTraceLimit","limit","engine","current","stackTraceLimit","installed","publishEvent","redispatchCaughtError","reportHandledError","options","thrown","kind","installErrorBeacon","document","endpoint","sampleRate","maxPerPage","sampled","Math","random","reporting","translation","servedUrl","browser","navigator","userAgent","Set","queued","sent","timer","flush","batch","body","JSON","stringify","events","sendBeacon","fetch","method","keepalive","headers","catch","enqueue","event","key","has","add","setTimeout","addEventListener","pageUrl","fullStack","translated","source","filename","lineno","col","colno","language","visibilityState"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GAED,SAASA,aAAa,QAA4B,sBAAkB;AACpE,SAASC,iBAAiB,QAAQ,yBAAqB;AACvD,SAASC,kBAAkB,EAAEC,cAAc,QAAQ,sBAAkB;AACrE,SAASC,iBAAiB,EAAEC,0BAA0B,QAAQ,yBAAqB;AA+CnF,MAAMC,cAAc;AACpB,MAAMC,YAAY;AAClB,MAAMC,iBAAiB;AAEvB,sEAAsE,GACtE,SAASC,SAASC,GAA8B;IAC9C,IAAI,CAACA,KAAK,OAAO;IACjB,IAAI;QACF,MAAMC,MAAM,IAAIC,IAAIC,OAAOH,MAAMI,OAAOC,QAAQ,CAACC,IAAI;QACrD,OAAO,GAAGL,IAAIM,MAAM,GAAGN,IAAIO,QAAQ,EAAE;IACvC,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAEA,SAASC,MAAMC,KAAc,EAAEC,GAAW;IACxC,OAAOR,OAAOO,gBAAAA,QAAS,IAAIE,KAAK,CAAC,GAAGD;AACtC;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoEC,GACD,OAAO,SAASE,0BACdC,KAAa,EACbC,YAAwC;IAExC,MAAMC,OAAOvB,eAAeqB;IAC5B,0EAA0E;IAC1E,uEAAuE;IACvE,iEAAiE;IACjE,IAAI,CAACE,KAAKC,MAAM,IAAI,CAACC,0BAA0BJ,QAAQ,OAAO;IAC9D,uEAAuE;IACvE,qEAAqE;IACrE,MAAMK,aAAa,AACjB,CAAA,OAAOJ,iBAAiB,WAAW;QAACA;KAAa,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YACvE,uEAAuE;YACvE,mDAAmD;YACnD,oEAAoE;YACpE,+BAA+B;YAC/B,IAAI1D,2BAA2B4J,MAAM7G,MAAM,GAAG;YAC9C,8DAA8D;YAC9D,+DAA+D;YAC/D,IAAID,iBAAiB8G,MAAM7G,MAAM,GAAG;YACpC,MAAMA,SAAS6G,MAAM7G,MAAM;YAC3B,MAAMJ,UAAU7B,MAAMuF,wBAAwBuD,MAAM7G,MAAM,GAAG9C;YAC7D,IAAI,CAAC0C,SAAS;YACd,MAAMuH,UAAU9J,SAASK,OAAOC,QAAQ,CAACC,IAAI;YAC7C,MAAMwJ,YAAYpH,CAAAA,0BAAAA,OAAQ5B,KAAK,IAAGX,OAAOuC,OAAO5B,KAAK,IAAIwC;YACzD,uEAAuE;YACvE,wEAAwE;YACxE,kCAAkC;YAClC,IAAIwG,aAAajJ,0BAA0BiJ,WAAW;gBAACD;gBAAS3B;aAAU,GAAG;gBAC3E;YACF;YACAoB,QAAQ;gBACN/B,IAAI,GAAElE,sBAAAA,mBAAmBkG,MAAM7G,MAAM,aAA/BW,sBAAoC;gBAC1Cf;gBACAxB,OAAOgJ,YAAYrJ,MAAMqJ,WAAWjK,aAAayD;gBACjDrD,KAAK4J;YACP;QACF,EAAE,eAAM;QACN,uCAAuC;QACzC;IACF;IAEA,sEAAsE;IACtE,uEAAuE;IACvEzJ,OAAOwJ,gBAAgB,CAAC,YAAYlB;IACpCjB,SAASmC,gBAAgB,CAAC,oBAAoB;QAC5C,IAAInC,SAAS6C,eAAe,KAAK,UAAU5B;IAC7C;AACF"}
|
|
@@ -114,8 +114,12 @@ export interface SystemEmailBrandOptions {
|
|
|
114
114
|
*/
|
|
115
115
|
export declare function isPlatformBrandedSend(merged: Readonly<Record<string, string>>, options?: SystemEmailBrandOptions): boolean;
|
|
116
116
|
export interface SystemEmailChromeInput extends SystemEmailBrandOptions {
|
|
117
|
-
/**
|
|
118
|
-
|
|
117
|
+
/**
|
|
118
|
+
* The email being sent; its `footerReason` is the footer's first line, and
|
|
119
|
+
* its `key` decides whether the header logo is a link
|
|
120
|
+
* ({@link HEADER_LOGO_UNLINKED}).
|
|
121
|
+
*/
|
|
122
|
+
definition: Pick<SystemEmailTemplateDefinition, 'footerReason'> & Partial<Pick<SystemEmailTemplateDefinition, 'key'>>;
|
|
119
123
|
/**
|
|
120
124
|
* The send's merge map, platform brand tokens under the caller's — the map
|
|
121
125
|
* the body renders with, which is what makes the reason's tokens resolve to
|
|
@@ -91,6 +91,17 @@ import { PLATFORM_BRANDING_PROFILE, PLATFORM_BRAND_LEGAL_NAME, PLATFORM_BRAND_NA
|
|
|
91
91
|
if (String((_options_brandLogoUrl = options.brandLogoUrl) != null ? _options_brandLogoUrl : '').trim()) return false;
|
|
92
92
|
return Object.entries(PLATFORM_BRAND_MERGE_TOKENS).every(([token, value])=>merged[token] === value);
|
|
93
93
|
}
|
|
94
|
+
/**
|
|
95
|
+
* Emails whose header logo is drawn with no link (AGL-4224).
|
|
96
|
+
*
|
|
97
|
+
* The logo is the first thing in the mail a finger can land on, and it led to
|
|
98
|
+
* the marketing home page. New sign-ups pressed it in the confirmation mail,
|
|
99
|
+
* some of them five times across a resend, never pressed the button under
|
|
100
|
+
* it, and stayed unverified with no workspace. A mail that exists for one
|
|
101
|
+
* button offers no other way out above that button.
|
|
102
|
+
*/ const HEADER_LOGO_UNLINKED = new Set([
|
|
103
|
+
'email-verification'
|
|
104
|
+
]);
|
|
94
105
|
/** A non-empty trimmed string, else undefined. */ const clean = (value)=>{
|
|
95
106
|
const text = typeof value === 'string' ? value.trim() : '';
|
|
96
107
|
return text.length ? text : undefined;
|
|
@@ -127,11 +138,12 @@ import { PLATFORM_BRANDING_PROFILE, PLATFORM_BRAND_LEGAL_NAME, PLATFORM_BRAND_NA
|
|
|
127
138
|
* through the same merge substitution as the body, so `{{org.name}}` and
|
|
128
139
|
* `{{brand.productName}}` read exactly as they do in the copy above them.
|
|
129
140
|
*/ export function buildSystemEmailChrome(input) {
|
|
130
|
-
var _input_now, _merged_brandproductName;
|
|
141
|
+
var _input_now, _definition_key, _merged_brandproductName;
|
|
131
142
|
const { definition, merged, brandLogoUrl, brandHomeUrl } = input;
|
|
132
143
|
const now = (_input_now = input.now) != null ? _input_now : ()=>new Date();
|
|
133
144
|
const reason = clean(definition.footerReason);
|
|
134
145
|
const support = supportLink(merged['brand.supportUrl']);
|
|
146
|
+
const linkLogo = !HEADER_LOGO_UNLINKED.has((_definition_key = definition.key) != null ? _definition_key : '');
|
|
135
147
|
const footer = _extends({}, reason ? {
|
|
136
148
|
reason
|
|
137
149
|
} : {}, support ? {
|
|
@@ -146,7 +158,7 @@ import { PLATFORM_BRANDING_PROFILE, PLATFORM_BRAND_LEGAL_NAME, PLATFORM_BRAND_NA
|
|
|
146
158
|
logoUrl: PLATFORM_EMAIL_LOGO_URL
|
|
147
159
|
} : {}, {
|
|
148
160
|
logoAlt: PLATFORM_BRAND_NAME
|
|
149
|
-
}, PLATFORM_HOME_URL ? {
|
|
161
|
+
}, linkLogo && PLATFORM_HOME_URL ? {
|
|
150
162
|
href: PLATFORM_HOME_URL
|
|
151
163
|
} : {}),
|
|
152
164
|
footer: _extends({}, footer, {
|
|
@@ -161,7 +173,7 @@ import { PLATFORM_BRANDING_PROFILE, PLATFORM_BRAND_LEGAL_NAME, PLATFORM_BRAND_NA
|
|
|
161
173
|
logoUrl
|
|
162
174
|
} : {}, {
|
|
163
175
|
logoAlt: (_merged_brandproductName = merged['brand.productName']) != null ? _merged_brandproductName : ''
|
|
164
|
-
}, home && /^https?:\/\//i.test(home) ? {
|
|
176
|
+
}, linkLogo && home && /^https?:\/\//i.test(home) ? {
|
|
165
177
|
href: home
|
|
166
178
|
} : {}),
|
|
167
179
|
footer
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/system-email-chrome.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The header and footer a system email is drawn inside, for the brand it is\n * sent under (AGL-3322).\n *\n * A system email's built-in copy is a few lines of text, and only a staff\n * design can place the platform marketing site's email blocks. Without this,\n * the mail the platform sends most — every password reset, invite and alert\n * nobody has designed — would name its sender nowhere but the From line, and\n * tell the reader neither why it came nor where to get help. The renderer\n * draws whatever `EmailChrome` it is handed; this module decides what that\n * is, which comes down to one question: whose mail is this?\n *\n * ## The platform's own\n *\n * Its logo linked to its home page, and a footer of the email's reason, the\n * support link and a `© {year} {legal name} · {postal address}` line. Every\n * value is read from `platform-brand.ts`, so a renamed or self-hosted\n * deployment prints its own configuration: its logo or its name in bold, its\n * home page or no link, its address or none — and never ours. The Aglyn\n * defaults there apply only while the deployment is still called Aglyn.\n *\n * ## A white-label organization's\n *\n * Its own email logo, or its product name in bold; the reason, whose brand\n * tokens are the agency's; and a support link only when the agency set one.\n * No legal line: the only legal name and address this module knows are the\n * platform's, and the recipient is the agency's customer, who must not learn\n * the platform exists from the foot of an invite.\n *\n * Pure: no reads, no clock of its own that a test cannot replace.\n */\n\nimport type {\n EmailChrome,\n EmailChromeFooter,\n} from '@aglyn/shared-util-email/email-render'\nimport type { SystemEmailTemplateDefinition } from '@aglyn/shared-util-email/system-email-catalog'\n\nimport { brandMergeTokens } from './plan-entitlements'\nimport {\n PLATFORM_BRANDING_PROFILE,\n PLATFORM_BRAND_LEGAL_NAME,\n PLATFORM_BRAND_NAME,\n PLATFORM_EMAIL_LOGO_URL,\n PLATFORM_HOME_URL,\n PLATFORM_POSTAL_ADDRESS,\n} from './platform-brand'\n\n/**\n * `brand.*` tokens every system email resolves, UNDER whatever the caller\n * supplies (AGL-2139).\n *\n * The order is the whole safety property. A system email blanks any token\n * the caller did not provide, so a designed template written against\n * `{{brand.productName}}` would ship with a hole in the sentence at any send\n * site that forgot to pass one. Defaulting to the platform profile means the\n * worst case is the platform's own copy rather than a gap — and an\n * org-context sender that spreads `brandMergeTokens(branding)` into its merge\n * map wins, because a later key overwrites an earlier one.\n *\n * The platform-scoped senders — password reset, email verification, the\n * security alerts, the staff erasure-hold alert — genuinely have no org (each\n * says so at its own call site, and password reset deliberately refuses to\n * look one up because that would be an enumeration oracle). The platform IS\n * their brand, so these are the right answer for them.\n */\nexport const PLATFORM_BRAND_MERGE_TOKENS: Readonly<Record<string, string>> =\n brandMergeTokens(PLATFORM_BRANDING_PROFILE)\n\n/**\n * Brand inputs that are NOT merge tokens (AGL-2139).\n *\n * `brand.productName` and friends ride the merge map because a designer types\n * them into copy. The logo and the home page are structural — the header the\n * renderer draws, or does not — so they are options rather than tokens a\n * template could forget to place.\n */\nexport interface SystemEmailBrandOptions {\n /** The org's resolved `emailLogoUrl`; absent or blank is no org logo. */\n brandLogoUrl?: string | null\n /**\n * The org's resolved `homeUrl`: where a white-label header links. Only an\n * `http(s)` URL is linked; a `mailto:` home is no destination for a logo.\n */\n brandHomeUrl?: string | null\n /**\n * The org's resolved `primaryColor` (AGL-3370): a white-label send's\n * buttons and links wear it, over the platform palette. Absent or blank is\n * the platform's own accent.\n */\n brandPrimaryColor?: string | null\n}\n\n/**\n * Whether a send goes out under the PLATFORM's brand, which is the only kind\n * that may carry the platform's header and footer — the marketing site's\n * email blocks (AGL-3318), or the chrome {@link buildSystemEmailChrome} draws\n * in their place (AGL-3322).\n *\n * Those are the platform's logo, its address, its line telling the reader why\n * they get the mail. An agency on white-label sells its clients a product\n * with no vendor in it, and an invite or a usage summary sent to one of their\n * people reads as the agency's own mail. One platform footer in it names the\n * vendor the whole tier is bought to hide.\n *\n * Read off what the send is actually branded as, rather than asked of the\n * caller, so no sender can forget to say. An org-context sender spreads\n * `brandMergeTokens(resolveBrandingProfile(org))` over the defaults and passes\n * the profile's email logo. A white-label profile never inherits the\n * platform's support URL (AGL-2428), so its tokens differ from\n * {@link PLATFORM_BRAND_MERGE_TOKENS} on `brand.supportUrl` at least, and the\n * platform profile has no email logo of its own, so any logo is an org's. The\n * org-less senders, and every org without white-label, which resolves to the\n * platform profile itself, match the defaults exactly: those sends are the\n * platform's.\n */\nexport function isPlatformBrandedSend(\n merged: Readonly<Record<string, string>>,\n options: SystemEmailBrandOptions = {},\n): boolean {\n if (String(options.brandLogoUrl ?? '').trim()) return false\n return Object.entries(PLATFORM_BRAND_MERGE_TOKENS).every(\n ([token, value]) => merged[token] === value,\n )\n}\n\nexport interface SystemEmailChromeInput extends SystemEmailBrandOptions {\n /** The email being sent; its `footerReason` is the footer's first line. */\n definition: Pick<SystemEmailTemplateDefinition, 'footerReason'>\n /**\n * The send's merge map, platform brand tokens under the caller's — the map\n * the body renders with, which is what makes the reason's tokens resolve to\n * the same names the body uses.\n */\n merged: Readonly<Record<string, string>>\n /** The clock the copyright year is read from. */\n now?: () => Date\n}\n\n/** A non-empty trimmed string, else undefined. */\nconst clean = (value: string | null | undefined): string | undefined => {\n const text = typeof value === 'string' ? value.trim() : ''\n return text.length ? text : undefined\n}\n\n/**\n * The footer's support link, from the send's `brand.supportUrl`, or\n * undefined when it has none.\n *\n * Empty is a decision, not a gap: a white-label org that set no support URL\n * gets NO line rather than the platform's desk (AGL-2428), which cannot help\n * its customers and would name the vendor to them. A `mailto:` reads as the\n * mailbox, which is what the reader has to type into a client that does not\n * follow the link; a web page reads as an instruction.\n */\nfunction supportLink(\n url: string | undefined,\n): EmailChromeFooter['support'] | undefined {\n const href = clean(url)\n if (!href) return undefined\n if (/^mailto:/i.test(href)) {\n const address = clean(href.slice('mailto:'.length).split('?')[0])\n return address ? { label: address, href } : undefined\n }\n return { label: 'Get help', href }\n}\n\n/**\n * The chrome one system email is drawn inside, for the brand it is sent\n * under. See the module comment for the two shapes and why they differ.\n *\n * The reason and the other lines go out as templates: the renderer runs them\n * through the same merge substitution as the body, so `{{org.name}}` and\n * `{{brand.productName}}` read exactly as they do in the copy above them.\n */\nexport function buildSystemEmailChrome(\n input: SystemEmailChromeInput,\n): EmailChrome {\n const { definition, merged, brandLogoUrl, brandHomeUrl } = input\n const now = input.now ?? (() => new Date())\n const reason = clean(definition.footerReason)\n const support = supportLink(merged['brand.supportUrl'])\n const footer: EmailChromeFooter = {\n ...(reason ? { reason } : {}),\n ...(support ? { support } : {}),\n }\n\n if (isPlatformBrandedSend(merged, { brandLogoUrl })) {\n const legal =\n `© ${now().getUTCFullYear()} ${PLATFORM_BRAND_LEGAL_NAME}` +\n (PLATFORM_POSTAL_ADDRESS ? ` · ${PLATFORM_POSTAL_ADDRESS}` : '')\n return {\n header: {\n ...(PLATFORM_EMAIL_LOGO_URL ? { logoUrl: PLATFORM_EMAIL_LOGO_URL } : {}),\n logoAlt: PLATFORM_BRAND_NAME,\n ...(PLATFORM_HOME_URL ? { href: PLATFORM_HOME_URL } : {}),\n },\n footer: { ...footer, legal },\n }\n }\n\n const logoUrl = clean(brandLogoUrl)\n const home = clean(brandHomeUrl)\n return {\n header: {\n ...(logoUrl ? { logoUrl } : {}),\n logoAlt: merged['brand.productName'] ?? '',\n ...(home && /^https?:\\/\\//i.test(home) ? { href: home } : {}),\n },\n footer,\n }\n}\n"],"names":["brandMergeTokens","PLATFORM_BRANDING_PROFILE","PLATFORM_BRAND_LEGAL_NAME","PLATFORM_BRAND_NAME","PLATFORM_EMAIL_LOGO_URL","PLATFORM_HOME_URL","PLATFORM_POSTAL_ADDRESS","PLATFORM_BRAND_MERGE_TOKENS","isPlatformBrandedSend","merged","options","String","brandLogoUrl","trim","Object","entries","every","token","value","clean","text","length","undefined","supportLink","url","href","test","address","slice","split","label","buildSystemEmailChrome","input","definition","brandHomeUrl","now","Date","reason","footerReason","support","footer","legal","getUTCFullYear","header","logoUrl","logoAlt","home"],"mappings":"AAAA;;;;;;;;;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AGF;IAC3D,MAAMG,OAAMH,aAAAA,MAAMG,GAAG,YAATH,aAAc,IAAM,IAAII;IACpC,MAAMC,SAASlB,MAAMc,WAAWK,YAAY;IAC5C,MAAMC,UAAUhB,YAAYd,MAAM,CAAC,mBAAmB;IACtD,MAAM+B,SAA4B,aAC5BH,SAAS;QAAEA;IAAO,IAAI,CAAC,GACvBE,UAAU;QAAEA;IAAQ,IAAI,CAAC;IAG/B,IAAI/B,sBAAsBC,QAAQ;QAAEG;IAAa,IAAI;QACnD,MAAM6B,QACJ,CAAC,EAAE,EAAEN,MAAMO,cAAc,GAAG,CAAC,EAAExC,2BAA2B,GACzDI,CAAAA,0BAA0B,CAAC,GAAG,EAAEA,yBAAyB,GAAG,EAAC;QAChE,OAAO;YACLqC,QAAQ,aACFvC,0BAA0B;gBAAEwC,SAASxC;YAAwB,IAAI,CAAC;gBACtEyC,SAAS1C;eACLE,oBAAoB;gBAAEoB,MAAMpB;YAAkB,IAAI,CAAC;YAEzDmC,QAAQ,aAAKA;gBAAQC;;QACvB;IACF;IAEA,MAAMG,UAAUzB,MAAMP;IACtB,MAAMkC,OAAO3B,MAAMe;IACnB,OAAO;QACLS,QAAQ,aACFC,UAAU;YAAEA;QAAQ,IAAI,CAAC;YAC7BC,OAAO,GAAEpC,2BAAAA,MAAM,CAAC,oBAAoB,YAA3BA,2BAA+B;WACpCqC,QAAQ,gBAAgBpB,IAAI,CAACoB,QAAQ;YAAErB,MAAMqB;QAAK,IAAI,CAAC;QAE7DN;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/system-email-chrome.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The header and footer a system email is drawn inside, for the brand it is\n * sent under (AGL-3322).\n *\n * A system email's built-in copy is a few lines of text, and only a staff\n * design can place the platform marketing site's email blocks. Without this,\n * the mail the platform sends most — every password reset, invite and alert\n * nobody has designed — would name its sender nowhere but the From line, and\n * tell the reader neither why it came nor where to get help. The renderer\n * draws whatever `EmailChrome` it is handed; this module decides what that\n * is, which comes down to one question: whose mail is this?\n *\n * ## The platform's own\n *\n * Its logo linked to its home page, and a footer of the email's reason, the\n * support link and a `© {year} {legal name} · {postal address}` line. Every\n * value is read from `platform-brand.ts`, so a renamed or self-hosted\n * deployment prints its own configuration: its logo or its name in bold, its\n * home page or no link, its address or none — and never ours. The Aglyn\n * defaults there apply only while the deployment is still called Aglyn.\n *\n * ## A white-label organization's\n *\n * Its own email logo, or its product name in bold; the reason, whose brand\n * tokens are the agency's; and a support link only when the agency set one.\n * No legal line: the only legal name and address this module knows are the\n * platform's, and the recipient is the agency's customer, who must not learn\n * the platform exists from the foot of an invite.\n *\n * Pure: no reads, no clock of its own that a test cannot replace.\n */\n\nimport type {\n EmailChrome,\n EmailChromeFooter,\n} from '@aglyn/shared-util-email/email-render'\nimport type { SystemEmailTemplateDefinition } from '@aglyn/shared-util-email/system-email-catalog'\n\nimport { brandMergeTokens } from './plan-entitlements'\nimport {\n PLATFORM_BRANDING_PROFILE,\n PLATFORM_BRAND_LEGAL_NAME,\n PLATFORM_BRAND_NAME,\n PLATFORM_EMAIL_LOGO_URL,\n PLATFORM_HOME_URL,\n PLATFORM_POSTAL_ADDRESS,\n} from './platform-brand'\n\n/**\n * `brand.*` tokens every system email resolves, UNDER whatever the caller\n * supplies (AGL-2139).\n *\n * The order is the whole safety property. A system email blanks any token\n * the caller did not provide, so a designed template written against\n * `{{brand.productName}}` would ship with a hole in the sentence at any send\n * site that forgot to pass one. Defaulting to the platform profile means the\n * worst case is the platform's own copy rather than a gap — and an\n * org-context sender that spreads `brandMergeTokens(branding)` into its merge\n * map wins, because a later key overwrites an earlier one.\n *\n * The platform-scoped senders — password reset, email verification, the\n * security alerts, the staff erasure-hold alert — genuinely have no org (each\n * says so at its own call site, and password reset deliberately refuses to\n * look one up because that would be an enumeration oracle). The platform IS\n * their brand, so these are the right answer for them.\n */\nexport const PLATFORM_BRAND_MERGE_TOKENS: Readonly<Record<string, string>> =\n brandMergeTokens(PLATFORM_BRANDING_PROFILE)\n\n/**\n * Brand inputs that are NOT merge tokens (AGL-2139).\n *\n * `brand.productName` and friends ride the merge map because a designer types\n * them into copy. The logo and the home page are structural — the header the\n * renderer draws, or does not — so they are options rather than tokens a\n * template could forget to place.\n */\nexport interface SystemEmailBrandOptions {\n /** The org's resolved `emailLogoUrl`; absent or blank is no org logo. */\n brandLogoUrl?: string | null\n /**\n * The org's resolved `homeUrl`: where a white-label header links. Only an\n * `http(s)` URL is linked; a `mailto:` home is no destination for a logo.\n */\n brandHomeUrl?: string | null\n /**\n * The org's resolved `primaryColor` (AGL-3370): a white-label send's\n * buttons and links wear it, over the platform palette. Absent or blank is\n * the platform's own accent.\n */\n brandPrimaryColor?: string | null\n}\n\n/**\n * Whether a send goes out under the PLATFORM's brand, which is the only kind\n * that may carry the platform's header and footer — the marketing site's\n * email blocks (AGL-3318), or the chrome {@link buildSystemEmailChrome} draws\n * in their place (AGL-3322).\n *\n * Those are the platform's logo, its address, its line telling the reader why\n * they get the mail. An agency on white-label sells its clients a product\n * with no vendor in it, and an invite or a usage summary sent to one of their\n * people reads as the agency's own mail. One platform footer in it names the\n * vendor the whole tier is bought to hide.\n *\n * Read off what the send is actually branded as, rather than asked of the\n * caller, so no sender can forget to say. An org-context sender spreads\n * `brandMergeTokens(resolveBrandingProfile(org))` over the defaults and passes\n * the profile's email logo. A white-label profile never inherits the\n * platform's support URL (AGL-2428), so its tokens differ from\n * {@link PLATFORM_BRAND_MERGE_TOKENS} on `brand.supportUrl` at least, and the\n * platform profile has no email logo of its own, so any logo is an org's. The\n * org-less senders, and every org without white-label, which resolves to the\n * platform profile itself, match the defaults exactly: those sends are the\n * platform's.\n */\nexport function isPlatformBrandedSend(\n merged: Readonly<Record<string, string>>,\n options: SystemEmailBrandOptions = {},\n): boolean {\n if (String(options.brandLogoUrl ?? '').trim()) return false\n return Object.entries(PLATFORM_BRAND_MERGE_TOKENS).every(\n ([token, value]) => merged[token] === value,\n )\n}\n\nexport interface SystemEmailChromeInput extends SystemEmailBrandOptions {\n /**\n * The email being sent; its `footerReason` is the footer's first line, and\n * its `key` decides whether the header logo is a link\n * ({@link HEADER_LOGO_UNLINKED}).\n */\n definition: Pick<SystemEmailTemplateDefinition, 'footerReason'> &\n Partial<Pick<SystemEmailTemplateDefinition, 'key'>>\n /**\n * The send's merge map, platform brand tokens under the caller's — the map\n * the body renders with, which is what makes the reason's tokens resolve to\n * the same names the body uses.\n */\n merged: Readonly<Record<string, string>>\n /** The clock the copyright year is read from. */\n now?: () => Date\n}\n\n/**\n * Emails whose header logo is drawn with no link (AGL-4224).\n *\n * The logo is the first thing in the mail a finger can land on, and it led to\n * the marketing home page. New sign-ups pressed it in the confirmation mail,\n * some of them five times across a resend, never pressed the button under\n * it, and stayed unverified with no workspace. A mail that exists for one\n * button offers no other way out above that button.\n */\nconst HEADER_LOGO_UNLINKED: ReadonlySet<string> = new Set([\n 'email-verification',\n])\n\n/** A non-empty trimmed string, else undefined. */\nconst clean = (value: string | null | undefined): string | undefined => {\n const text = typeof value === 'string' ? value.trim() : ''\n return text.length ? text : undefined\n}\n\n/**\n * The footer's support link, from the send's `brand.supportUrl`, or\n * undefined when it has none.\n *\n * Empty is a decision, not a gap: a white-label org that set no support URL\n * gets NO line rather than the platform's desk (AGL-2428), which cannot help\n * its customers and would name the vendor to them. A `mailto:` reads as the\n * mailbox, which is what the reader has to type into a client that does not\n * follow the link; a web page reads as an instruction.\n */\nfunction supportLink(\n url: string | undefined,\n): EmailChromeFooter['support'] | undefined {\n const href = clean(url)\n if (!href) return undefined\n if (/^mailto:/i.test(href)) {\n const address = clean(href.slice('mailto:'.length).split('?')[0])\n return address ? { label: address, href } : undefined\n }\n return { label: 'Get help', href }\n}\n\n/**\n * The chrome one system email is drawn inside, for the brand it is sent\n * under. See the module comment for the two shapes and why they differ.\n *\n * The reason and the other lines go out as templates: the renderer runs them\n * through the same merge substitution as the body, so `{{org.name}}` and\n * `{{brand.productName}}` read exactly as they do in the copy above them.\n */\nexport function buildSystemEmailChrome(\n input: SystemEmailChromeInput,\n): EmailChrome {\n const { definition, merged, brandLogoUrl, brandHomeUrl } = input\n const now = input.now ?? (() => new Date())\n const reason = clean(definition.footerReason)\n const support = supportLink(merged['brand.supportUrl'])\n const linkLogo = !HEADER_LOGO_UNLINKED.has(definition.key ?? '')\n const footer: EmailChromeFooter = {\n ...(reason ? { reason } : {}),\n ...(support ? { support } : {}),\n }\n\n if (isPlatformBrandedSend(merged, { brandLogoUrl })) {\n const legal =\n `© ${now().getUTCFullYear()} ${PLATFORM_BRAND_LEGAL_NAME}` +\n (PLATFORM_POSTAL_ADDRESS ? ` · ${PLATFORM_POSTAL_ADDRESS}` : '')\n return {\n header: {\n ...(PLATFORM_EMAIL_LOGO_URL ? { logoUrl: PLATFORM_EMAIL_LOGO_URL } : {}),\n logoAlt: PLATFORM_BRAND_NAME,\n ...(linkLogo && PLATFORM_HOME_URL ? { href: PLATFORM_HOME_URL } : {}),\n },\n footer: { ...footer, legal },\n }\n }\n\n const logoUrl = clean(brandLogoUrl)\n const home = clean(brandHomeUrl)\n return {\n header: {\n ...(logoUrl ? { logoUrl } : {}),\n logoAlt: merged['brand.productName'] ?? '',\n ...(linkLogo && home && /^https?:\\/\\//i.test(home) ? { href: home } : {}),\n },\n footer,\n }\n}\n"],"names":["brandMergeTokens","PLATFORM_BRANDING_PROFILE","PLATFORM_BRAND_LEGAL_NAME","PLATFORM_BRAND_NAME","PLATFORM_EMAIL_LOGO_URL","PLATFORM_HOME_URL","PLATFORM_POSTAL_ADDRESS","PLATFORM_BRAND_MERGE_TOKENS","isPlatformBrandedSend","merged","options","String","brandLogoUrl","trim","Object","entries","every","token","value","HEADER_LOGO_UNLINKED","Set","clean","text","length","undefined","supportLink","url","href","test","address","slice","split","label","buildSystemEmailChrome","input","definition","brandHomeUrl","now","Date","reason","footerReason","support","linkLogo","has","key","footer","legal","getUTCFullYear","header","logoUrl","logoAlt","home"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BC;AAQD,SAASA,gBAAgB,QAAQ,yBAAqB;AACtD,SACEC,yBAAyB,EACzBC,yBAAyB,EACzBC,mBAAmB,EACnBC,uBAAuB,EACvBC,iBAAiB,EACjBC,uBAAuB,QAClB,sBAAkB;AAEzB;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,MAAMC,8BACXP,iBAAiBC,2BAA0B;AA0B7C;;;;;;;;;;;;;;;;;;;;;;CAsBC,GACD,OAAO,SAASO,sBACdC,MAAwC,EACxCC,UAAmC,CAAC,CAAC;QAE1BA;IAAX,IAAIC,QAAOD,wBAAAA,QAAQE,YAAY,YAApBF,wBAAwB,IAAIG,IAAI,IAAI,OAAO;IACtD,OAAOC,OAAOC,OAAO,CAACR,6BAA6BS,KAAK,CACtD,CAAC,CAACC,OAAOC,MAAM,GAAKT,MAAM,CAACQ,MAAM,KAAKC;AAE1C;AAoBA;;;;;;;;CAQC,GACD,MAAMC,uBAA4C,IAAIC,IAAI;IACxD;CACD;AAED,gDAAgD,GAChD,MAAMC,QAAQ,CAACH;IACb,MAAMI,OAAO,OAAOJ,UAAU,WAAWA,MAAML,IAAI,KAAK;IACxD,OAAOS,KAAKC,MAAM,GAAGD,OAAOE;AAC9B;AAEA;;;;;;;;;CASC,GACD,SAASC,YACPC,GAAuB;IAEvB,MAAMC,OAAON,MAAMK;IACnB,IAAI,CAACC,MAAM,OAAOH;IAClB,IAAI,YAAYI,IAAI,CA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