@atelic-action/ui 7.2.0 → 8.1.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.
Files changed (131) hide show
  1. package/README.md +439 -132
  2. package/bin/atelic-check-sentry.ts +5 -0
  3. package/dist/gate/middleware.js +15 -1
  4. package/dist/monitoring/server.d.ts +72 -0
  5. package/dist/monitoring/server.js +201 -0
  6. package/dist/vite/index.d.ts +1 -1
  7. package/dist/vite/index.js +1 -1
  8. package/dist/vite/marketing-config.d.ts +28 -1
  9. package/dist/vite/marketing-config.js +62 -0
  10. package/package.json +23 -11
  11. package/src/app/ErrorFallback.tsx +6 -2
  12. package/src/app/context/AppContext.tsx +10 -1
  13. package/src/app/index.ts +0 -1
  14. package/src/app/layout/AppPage.tsx +36 -7
  15. package/src/app/layout/DesktopRail.tsx +15 -6
  16. package/src/app/layout/MobileMenu.tsx +14 -5
  17. package/src/app/layout/MobileTabBar.tsx +3 -2
  18. package/src/app/layout/PageError.tsx +7 -4
  19. package/src/app/layout/PageSkeleton.tsx +33 -26
  20. package/src/app/layout/SectionCards.tsx +7 -2
  21. package/src/app/layout/UserMenu.tsx +13 -7
  22. package/src/app/ui/alert.tsx +42 -12
  23. package/src/app/ui/badge.tsx +1 -1
  24. package/src/app/ui/button.tsx +2 -1
  25. package/src/app/ui/command.tsx +86 -21
  26. package/src/app/ui/country-dropdown.tsx +26 -47
  27. package/src/app/ui/form.tsx +48 -9
  28. package/src/app/ui/pagination.tsx +1 -1
  29. package/src/app/ui/progress.tsx +26 -12
  30. package/src/app/ui/search-input.tsx +16 -3
  31. package/src/app/ui/select.tsx +8 -3
  32. package/src/app/ui/slider.tsx +62 -15
  33. package/src/artifact/AppErrorBoundary.tsx +12 -7
  34. package/src/artifact/ArtifactShell.tsx +5 -1
  35. package/src/artifact/ErrorFallback.tsx +8 -1
  36. package/src/artifact/artifactConfig.ts +1 -1
  37. package/src/chrome/BrandLockup.tsx +102 -17
  38. package/src/chrome/ClosingBar.tsx +5 -3
  39. package/src/chrome/ContactDock.tsx +361 -0
  40. package/src/chrome/Footer.tsx +126 -31
  41. package/src/chrome/NavBadge.tsx +8 -0
  42. package/src/chrome/NavMegaPanel.tsx +399 -0
  43. package/src/chrome/SiteHeader.tsx +268 -23
  44. package/src/chrome/SiteMenu.tsx +200 -19
  45. package/src/chrome/SiteShell.tsx +151 -14
  46. package/src/chrome/StickyCTABar.tsx +60 -2
  47. package/src/chrome/brandMark.ts +56 -0
  48. package/src/chrome/icons.ts +58 -0
  49. package/src/chrome/index.ts +16 -0
  50. package/src/chrome/navSections.ts +55 -0
  51. package/src/components/ColumnChart.tsx +27 -2
  52. package/src/components/DataTable.tsx +104 -85
  53. package/src/components/Disclosure.tsx +3 -1
  54. package/src/components/Hint.tsx +3 -24
  55. package/src/components/NotFound.tsx +7 -3
  56. package/src/components/StarRating.tsx +45 -19
  57. package/src/components/ThresholdScale.tsx +36 -26
  58. package/src/email/atoms.tsx +13 -57
  59. package/src/email/frame.tsx +4 -6
  60. package/src/email/index.ts +4 -10
  61. package/src/email/scoreboard.tsx +107 -186
  62. package/src/email/text.ts +30 -0
  63. package/src/email/theme.tsx +76 -9
  64. package/src/gate/middleware.ts +15 -1
  65. package/src/hooks/useDismiss.ts +39 -0
  66. package/src/lib/emailText.tsx +26 -0
  67. package/src/lib/phoneText.tsx +40 -0
  68. package/src/lib/useScrollsSideways.ts +26 -0
  69. package/src/monitoring/ErrorCatcherScript.tsx +15 -0
  70. package/src/monitoring/catcher.ts +118 -0
  71. package/src/monitoring/index.ts +25 -0
  72. package/src/monitoring/sdk.ts +112 -0
  73. package/src/monitoring/server.ts +244 -0
  74. package/src/monitoring/start.ts +118 -0
  75. package/src/primitives/Button.tsx +5 -1
  76. package/src/primitives/Eyebrow.tsx +6 -2
  77. package/src/primitives/ProseBlocks.tsx +6 -1
  78. package/src/primitives/SectionHeading.tsx +3 -1
  79. package/src/primitives/StarRow.tsx +23 -8
  80. package/src/routing/index.ts +1 -0
  81. package/src/routing/miss.ts +32 -0
  82. package/src/scripts/check-sentry.ts +77 -0
  83. package/src/sections/BlogIndex.tsx +17 -3
  84. package/src/sections/BlogPost.tsx +10 -1
  85. package/src/sections/CTASection.tsx +2 -2
  86. package/src/sections/CalloutPanel.tsx +34 -0
  87. package/src/sections/ComparisonTable.tsx +23 -2
  88. package/src/sections/ContactForm.tsx +61 -17
  89. package/src/sections/FAQBrowser.tsx +11 -2
  90. package/src/sections/FeatureGrid.tsx +6 -2
  91. package/src/sections/FullBleedVideo.tsx +167 -0
  92. package/src/sections/Gallery.tsx +6 -4
  93. package/src/sections/Hero.tsx +70 -39
  94. package/src/sections/JumpRail.tsx +7 -0
  95. package/src/sections/LegalPage.tsx +10 -2
  96. package/src/sections/LinkColumns.tsx +80 -0
  97. package/src/sections/LocationSection.tsx +28 -5
  98. package/src/sections/Locations.tsx +18 -5
  99. package/src/sections/LogoMarquee.tsx +43 -11
  100. package/src/sections/MapEmbed.tsx +13 -9
  101. package/src/sections/PageHero.tsx +16 -2
  102. package/src/sections/ProcessSteps.tsx +27 -4
  103. package/src/sections/ProfileCards.tsx +12 -2
  104. package/src/sections/ProofStrip.tsx +44 -0
  105. package/src/sections/RevealSlider.tsx +28 -7
  106. package/src/sections/ReviewCarousel.tsx +17 -4
  107. package/src/sections/ReviewWall.tsx +2 -2
  108. package/src/sections/SplitSection.tsx +2 -1
  109. package/src/sections/index.ts +15 -6
  110. package/src/sections/siteConfig.ts +101 -8
  111. package/src/styles/app.css +33 -2
  112. package/src/styles/artifact.css +20 -8
  113. package/src/styles/base.css +68 -13
  114. package/src/styles/chrome.css +1134 -56
  115. package/src/styles/components.css +104 -65
  116. package/src/styles/defaults.css +140 -0
  117. package/src/styles/gate.css +21 -10
  118. package/src/styles/primitives.css +108 -39
  119. package/src/styles/sections.css +500 -437
  120. package/src/styles/star-rating.css +1 -4
  121. package/src/tokens/palettes.ts +24 -4
  122. package/src/types.ts +220 -3
  123. package/src/vite/index.ts +4 -0
  124. package/src/vite/marketing-config.ts +81 -1
  125. package/src/app/CardErrorBoundary.tsx +0 -39
  126. package/src/sections/CTABanner.tsx +0 -93
  127. package/src/sections/DeviceShowcase.tsx +0 -39
  128. package/src/sections/MediaBand.tsx +0 -20
  129. package/src/sections/MenuList.tsx +0 -44
  130. package/src/sections/PressQuotes.tsx +0 -51
  131. package/src/sections/SocialStrip.tsx +0 -83
@@ -29,6 +29,7 @@
29
29
  * open file of its own passes `open`; one whose matcher already leaves its
30
30
  * open paths out may still pass its own `needsSession`, which wins over both.
31
31
  */
32
+ import { reportServerError } from "../monitoring/server.js";
32
33
  import { isAllowed } from "./config.js";
33
34
  import { verifyToken } from "./tokens.js";
34
35
  import { createNeedsSession, type WallOpenings } from "./wall.js";
@@ -53,7 +54,7 @@ function readCookie(header: string, name: string): string | undefined {
53
54
  export function createMiddleware(options: MiddlewareOptions = {}) {
54
55
  const needsSession = options.needsSession ?? createNeedsSession(options.open);
55
56
 
56
- return async function middleware(request: Request): Promise<Response | undefined> {
57
+ async function decide(request: Request): Promise<Response | undefined> {
57
58
  const secret = process.env.GATE_SESSION_SECRET;
58
59
  if (!secret) return; // gate off, let everything through
59
60
 
@@ -69,6 +70,19 @@ export function createMiddleware(options: MiddlewareOptions = {}) {
69
70
  const login = new URL("/login", url.origin);
70
71
  login.searchParams.set("next", url.pathname + url.search);
71
72
  return Response.redirect(login.toString(), 302);
73
+ }
74
+
75
+ // A throw is reported to Sentry (when a DSN is set) and thrown again, so
76
+ // the request fails exactly as it did; a pass and a block are untouched.
77
+ // The expected misses (a malformed cookie, a token that fails to verify)
78
+ // are answers, not errors, and stay quiet.
79
+ return async function middleware(request: Request): Promise<Response | undefined> {
80
+ try {
81
+ return await decide(request);
82
+ } catch (error) {
83
+ await reportServerError(error, { request, tags: { source: "middleware" } });
84
+ throw error;
85
+ }
72
86
  };
73
87
  }
74
88
 
@@ -0,0 +1,39 @@
1
+ import { type RefObject, useEffect, useRef } from "react";
2
+
3
+ /** What closed it: the Escape key, or a press somewhere outside. */
4
+ export type DismissReason = "escape" | "outside";
5
+
6
+ /**
7
+ * Closes a popover, a panel, or a menu the two ways a reader expects: the
8
+ * Escape key, and a press anywhere outside the element `ref` holds. It
9
+ * listens only while `active`, on the document, and calls `onDismiss` with
10
+ * the reason, so the caller decides what else to do (hand focus back on
11
+ * Escape, leave it where the press put it). The latest `onDismiss` is always
12
+ * the one called, so a caller can pass an inline function. Used by `Hint`,
13
+ * `SiteHeader`, and `ContactDock`; it touches the document only inside an
14
+ * effect, so a component using it still prerenders.
15
+ */
16
+ export function useDismiss(
17
+ active: boolean,
18
+ ref: RefObject<HTMLElement | null>,
19
+ onDismiss: (reason: DismissReason) => void,
20
+ ): void {
21
+ const latest = useRef(onDismiss);
22
+ latest.current = onDismiss;
23
+
24
+ useEffect(() => {
25
+ if (!active) return;
26
+ const onKey = (event: KeyboardEvent) => {
27
+ if (event.key === "Escape") latest.current("escape");
28
+ };
29
+ const onPointer = (event: PointerEvent) => {
30
+ if (!ref.current?.contains(event.target as Node)) latest.current("outside");
31
+ };
32
+ document.addEventListener("keydown", onKey);
33
+ document.addEventListener("pointerdown", onPointer);
34
+ return () => {
35
+ document.removeEventListener("keydown", onKey);
36
+ document.removeEventListener("pointerdown", onPointer);
37
+ };
38
+ }, [active, ref]);
39
+ }
@@ -0,0 +1,26 @@
1
+ import { Fragment, type ReactNode } from "react";
2
+
3
+ /**
4
+ * An email address with its break opportunities marked: after the @ and
5
+ * before each dot of the domain, so a narrow column wraps it there and
6
+ * never inside a word ("hello@" / "kestrelhollow" / ".example.com"). The
7
+ * words read and copy exactly as the address.
8
+ */
9
+ export function breakableEmail(email: string): ReactNode {
10
+ const at = email.indexOf("@");
11
+ if (at === -1) return email;
12
+ const [first, ...rest] = email.slice(at + 1).split(".");
13
+ return (
14
+ <>
15
+ {email.slice(0, at + 1)}
16
+ <wbr />
17
+ {first}
18
+ {rest.map((part, index) => (
19
+ // biome-ignore lint/suspicious/noArrayIndexKey: the parts of one address never reorder
20
+ <Fragment key={index}>
21
+ <wbr />.{part}
22
+ </Fragment>
23
+ ))}
24
+ </>
25
+ );
26
+ }
@@ -0,0 +1,40 @@
1
+ import type { ReactNode } from "react";
2
+
3
+ /** A run that reads as a phone number: seven digits or more, with the usual separators. */
4
+ const PHONE = /(\+?\(?\d[\d\s().-]{5,}\d)/;
5
+
6
+ /** Whether a link calls: a `tel:` href. */
7
+ export function isTel(href: string | undefined): boolean {
8
+ return href?.startsWith("tel:") ?? false;
9
+ }
10
+
11
+ /**
12
+ * Wraps each phone number in a run of words in `.tel-number`, which never
13
+ * breaks, so a call link holding more than the number (a dock row's label
14
+ * and line, a menu row) wraps its words and holds its number whole.
15
+ * Anything that is not a string passes through as it is.
16
+ *
17
+ * The run comes back inside one plain inline span, so a flex parent (a
18
+ * button, a row) sees the words as the one item a bare string was: split
19
+ * into separate items, the space before the number was dropped at an
20
+ * item's edge and the parent's gap stood in its place, wider than a space.
21
+ */
22
+ export function holdPhoneNumbers(content: ReactNode): ReactNode {
23
+ if (typeof content !== "string") return content;
24
+ const parts = content.split(PHONE);
25
+ if (parts.length === 1) return content;
26
+ return (
27
+ <span>
28
+ {parts.map((part, at) =>
29
+ at % 2 === 1 && (part.match(/\d/g)?.length ?? 0) >= 7 ? (
30
+ // biome-ignore lint/suspicious/noArrayIndexKey: the runs of one string never reorder
31
+ <span key={at} className="tel-number">
32
+ {part}
33
+ </span>
34
+ ) : (
35
+ part
36
+ ),
37
+ )}
38
+ </span>
39
+ );
40
+ }
@@ -0,0 +1,26 @@
1
+ import { useEffect, useRef, useState } from "react";
2
+
3
+ /**
4
+ * Whether a box is narrower than what it holds, kept current as either
5
+ * resizes. False on the server and until the first measure, so the box only
6
+ * takes a tab stop and a name once it actually scrolls: a scrolling region a
7
+ * keyboard cannot reach fails axe's `scrollable-region-focusable`, and one
8
+ * that takes a tab stop while it holds nothing to scroll is a stop for
9
+ * nothing. Used by `DataTable` and `ComparisonTable`.
10
+ */
11
+ export function useScrollsSideways<T extends HTMLElement = HTMLDivElement>() {
12
+ const ref = useRef<T>(null);
13
+ const [active, setActive] = useState(false);
14
+ useEffect(() => {
15
+ const box = ref.current;
16
+ if (!box) return;
17
+ const measure = () => setActive(box.scrollWidth > box.clientWidth + 1);
18
+ measure();
19
+ if (typeof ResizeObserver === "undefined") return;
20
+ const observer = new ResizeObserver(measure);
21
+ observer.observe(box);
22
+ if (box.firstElementChild) observer.observe(box.firstElementChild);
23
+ return () => observer.disconnect();
24
+ }, []);
25
+ return { ref, active };
26
+ }
@@ -0,0 +1,15 @@
1
+ import { errorCatcherScript } from "./catcher";
2
+
3
+ /**
4
+ * The inline early catcher as an element, for the first place in a root
5
+ * route's `<head>`, ahead of `<HeadContent />`: it runs before any other
6
+ * script, so an error thrown before the app's own JavaScript is held until
7
+ * `startErrorReporting` hands it to Sentry. It is a few hundred bytes, well
8
+ * inside the first kilobyte a browser scans for the charset.
9
+ */
10
+ export function ErrorCatcherScript() {
11
+ return (
12
+ // biome-ignore lint/security/noDangerouslySetInnerHtml: the package's own constant script, no outside input
13
+ <script dangerouslySetInnerHTML={{ __html: errorCatcherScript }} />
14
+ );
15
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * The early catcher: the buffer every error lands in before the Sentry SDK
3
+ * has loaded, on one well known global, so an error thrown in the first
4
+ * moments of a page (before first paint, before the app's own script runs)
5
+ * is held rather than lost. Two things install it, to the same contract:
6
+ * the inline script a site's root route sets first in `<head>`
7
+ * (`errorCatcherScript`), and `installCatcher`, which `startErrorReporting`
8
+ * calls in case the page has no inline script. Whichever runs first wins;
9
+ * the other sees the global and leaves it alone.
10
+ *
11
+ * Nothing here imports the SDK or touches `window` at module scope, so the
12
+ * module is safe in a prerender and costs a page next to nothing.
13
+ */
14
+
15
+ /** The global the catcher lives on. */
16
+ export const CATCHER_GLOBAL = "__atelicErrors";
17
+
18
+ /** How many errors the buffer holds before it counts the rest as dropped. */
19
+ export const CATCHER_CAP = 20;
20
+
21
+ /** What raised a held error: the window's error event, an unhandled rejection, or a render crash. */
22
+ export type CaughtKind = "error" | "unhandledrejection" | "boundary";
23
+
24
+ /** One held error: what was thrown (an Error, a reason, or a message), how, and when. */
25
+ export interface CaughtError {
26
+ error: unknown;
27
+ kind: CaughtKind;
28
+ at: number;
29
+ }
30
+
31
+ /** The catcher, as the inline script and `installCatcher` both shape it. */
32
+ export interface Catcher {
33
+ q: CaughtError[];
34
+ max: number;
35
+ /** Errors past the cap, counted and let go. */
36
+ dropped: number;
37
+ push: (error: unknown, kind: CaughtKind) => void;
38
+ onError: (event: ErrorEvent) => void;
39
+ onRejection: (event: PromiseRejectionEvent) => void;
40
+ /** Set once the SDK is up: every error from then on goes straight to it. */
41
+ report?: (error: unknown, kind: CaughtKind) => void;
42
+ /**
43
+ * The launch check, set once reporting starts: throws a clearly named
44
+ * error from the package's own code on the next turn, uncaught, so a
45
+ * site can confirm in Sentry that it arrives with a readable, source
46
+ * mapped stack. Run `window.__atelicErrors.test()` in the console.
47
+ */
48
+ test?: () => void;
49
+ }
50
+
51
+ type CatcherWindow = Window & { [CATCHER_GLOBAL]?: Catcher };
52
+
53
+ /**
54
+ * The inline catcher, as a script for the first place in `<head>`: ES5, no
55
+ * dependencies, and the same shape `installCatcher` builds. It holds up to
56
+ * twenty errors and rejections and counts the rest. `ErrorCatcherScript`
57
+ * renders it; a site that builds its head another way inlines the string.
58
+ */
59
+ export const errorCatcherScript =
60
+ `(function(w){if(!w||w.${CATCHER_GLOBAL})return;` +
61
+ `var q=[],c={q:q,max:${CATCHER_CAP},dropped:0};` +
62
+ "c.push=function(e,k){if(q.length<c.max)q.push({error:e,kind:k,at:+new Date()});else c.dropped++};" +
63
+ 'c.onError=function(v){c.push(v&&v.error!=null?v.error:v&&v.message,"error")};' +
64
+ 'c.onRejection=function(v){c.push(v?v.reason:v,"unhandledrejection")};' +
65
+ 'w.addEventListener("error",c.onError);' +
66
+ 'w.addEventListener("unhandledrejection",c.onRejection);' +
67
+ `w.${CATCHER_GLOBAL}=c})(window);`;
68
+
69
+ /** The catcher on this window, when one is installed. */
70
+ export function readCatcher(win: Window): Catcher | undefined {
71
+ return (win as CatcherWindow)[CATCHER_GLOBAL];
72
+ }
73
+
74
+ /**
75
+ * Installs the catcher on a window that has none and returns it, or returns
76
+ * the one already there (the inline script's). Browser only: call it from an
77
+ * effect or a start function, never during a render.
78
+ */
79
+ export function installCatcher(win: Window): Catcher {
80
+ const existing = readCatcher(win);
81
+ if (existing) return existing;
82
+ const q: CaughtError[] = [];
83
+ const catcher: Catcher = {
84
+ q,
85
+ max: CATCHER_CAP,
86
+ dropped: 0,
87
+ push(error, kind) {
88
+ if (q.length < catcher.max) q.push({ error, kind, at: Date.now() });
89
+ else catcher.dropped++;
90
+ },
91
+ onError(event) {
92
+ catcher.push(event?.error != null ? event.error : event?.message, "error");
93
+ },
94
+ onRejection(event) {
95
+ catcher.push(event ? event.reason : event, "unhandledrejection");
96
+ },
97
+ };
98
+ win.addEventListener("error", catcher.onError);
99
+ win.addEventListener("unhandledrejection", catcher.onRejection);
100
+ (win as CatcherWindow)[CATCHER_GLOBAL] = catcher;
101
+ return catcher;
102
+ }
103
+
104
+ /**
105
+ * Hands an error to whatever is listening: the SDK once it has loaded, the
106
+ * buffer before that. For an error the window never sees, such as a render
107
+ * crash an error boundary catches. A page where reporting was never started
108
+ * and no inline catcher runs has nothing listening, so the error is let go
109
+ * quietly rather than held by a catcher nobody will read. A no op where
110
+ * there is no window (a prerender).
111
+ */
112
+ export function reportError(error: unknown, kind: CaughtKind = "boundary"): void {
113
+ if (typeof window === "undefined") return;
114
+ const catcher = readCatcher(window);
115
+ if (!catcher) return;
116
+ if (catcher.report) catcher.report(error, kind);
117
+ else catcher.push(error, kind);
118
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Error reporting for a site, in the browser: the early catcher and the
3
+ * start function. The server side is its own built entry,
4
+ * `@atelic-action/ui/monitoring/server`, since a Vercel function imports it
5
+ * uncompiled. README.md, Error Reporting, has the wiring.
6
+ */
7
+ export {
8
+ CATCHER_CAP,
9
+ CATCHER_GLOBAL,
10
+ type Catcher,
11
+ type CaughtError,
12
+ type CaughtKind,
13
+ errorCatcherScript,
14
+ installCatcher,
15
+ readCatcher,
16
+ reportError,
17
+ } from "./catcher";
18
+ export { ErrorCatcherScript } from "./ErrorCatcherScript";
19
+ export {
20
+ afterFirstPaint,
21
+ type ErrorReportingOptions,
22
+ LAUNCH_CHECK_MESSAGE,
23
+ startErrorReporting,
24
+ throwLaunchCheck,
25
+ } from "./start";
@@ -0,0 +1,112 @@
1
+ /**
2
+ * The Sentry browser SDK, set up for errors alone, in the one module
3
+ * `startErrorReporting` imports dynamically, so a page downloads it only
4
+ * after first paint and only when a DSN is configured.
5
+ *
6
+ * Built from the SDK's parts rather than `init()`: `init()` pulls in every
7
+ * default integration (breadcrumbs, sessions, the browser API wrappers) even
8
+ * when told not to use them, where a client given its integrations by name
9
+ * bundles only those. No tracing, no replay, no breadcrumbs: breadcrumbs
10
+ * would carry the console, the requests a page makes, and what a reader
11
+ * clicked, none of which an error report needs.
12
+ */
13
+ import {
14
+ BrowserClient,
15
+ captureException,
16
+ dedupeIntegration,
17
+ defaultStackParser,
18
+ eventFiltersIntegration,
19
+ functionToStringIntegration,
20
+ globalHandlersIntegration,
21
+ httpContextIntegration,
22
+ linkedErrorsIntegration,
23
+ makeFetchTransport,
24
+ setCurrentClient,
25
+ } from "@sentry/browser";
26
+ import type { CaughtKind } from "./catcher";
27
+
28
+ /**
29
+ * Noise the reports leave out, kept short on purpose. An error whose top
30
+ * frame is a browser extension's script is the extension's, not the site's.
31
+ * The two messages are the bridges in app webviews (an email app's or a
32
+ * social app's built in browser) failing between the page and the app.
33
+ */
34
+ export const DENY_URLS = [
35
+ /^chrome-extension:\/\//,
36
+ /^moz-extension:\/\//,
37
+ /^safari-(web-)?extension:\/\//,
38
+ ];
39
+ export const IGNORE_ERRORS = [/Java object is gone/, /Error invoking postMessage/];
40
+
41
+ /**
42
+ * What an event may carry of its request, matching the server reporter: the
43
+ * URL with no query string or fragment, and the user agent. The SDK's own
44
+ * request integration attaches the full URL and the referrer, and a link can
45
+ * carry a reader's personal parameters in either, so they are cut here, the
46
+ * last step before an event leaves the page.
47
+ */
48
+ export function scrubRequest<
49
+ T extends {
50
+ request?: { url?: string; headers?: Record<string, string> };
51
+ exception?: { values?: { stacktrace?: { frames?: { filename?: string }[] } }[] };
52
+ },
53
+ >(event: T): T {
54
+ // A frame's file is the page itself for an inline script, query and all.
55
+ for (const value of event.exception?.values ?? []) {
56
+ for (const frame of value.stacktrace?.frames ?? []) {
57
+ if (frame.filename) frame.filename = frame.filename.replace(/[?#].*$/, "");
58
+ }
59
+ }
60
+ const request = event.request;
61
+ if (!request) return event;
62
+ if (request.url) {
63
+ try {
64
+ const parsed = new URL(request.url);
65
+ request.url = `${parsed.origin}${parsed.pathname}`;
66
+ } catch {
67
+ delete request.url;
68
+ }
69
+ }
70
+ const agent = request.headers?.["User-Agent"];
71
+ if (agent) request.headers = { "User-Agent": agent };
72
+ else delete request.headers;
73
+ return event;
74
+ }
75
+
76
+ export interface SDKOptions {
77
+ dsn: string;
78
+ release?: string;
79
+ environment?: string;
80
+ }
81
+
82
+ /** Starts the client and returns how an error reaches it, tagged with what raised it. */
83
+ export function initSentry({ dsn, release, environment }: SDKOptions) {
84
+ const client = new BrowserClient({
85
+ dsn,
86
+ release,
87
+ environment,
88
+ transport: makeFetchTransport,
89
+ stackParser: defaultStackParser,
90
+ denyUrls: DENY_URLS,
91
+ ignoreErrors: IGNORE_ERRORS,
92
+ beforeSend: scrubRequest,
93
+ integrations: [
94
+ eventFiltersIntegration(),
95
+ functionToStringIntegration(),
96
+ globalHandlersIntegration(),
97
+ linkedErrorsIntegration(),
98
+ dedupeIntegration(),
99
+ httpContextIntegration(),
100
+ ],
101
+ });
102
+ setCurrentClient(client);
103
+ client.init();
104
+ return (error: unknown, kind: CaughtKind, early = false, dropped = 0) => {
105
+ captureException(error, {
106
+ tags: { source: kind, ...(early ? { early: "true" } : {}) },
107
+ // How many errors the early catcher let go past its cap, on each
108
+ // replayed one, so a burst before the SDK arrived is still visible.
109
+ ...(dropped > 0 ? { extra: { earlyDropped: dropped } } : {}),
110
+ });
111
+ };
112
+ }
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Error reporting on the server: a dependency free Sentry reporter for a
3
+ * Vercel function or middleware. Built to dist/ with the gate (CLAUDE.md,
4
+ * the built corner), since Vercel runs a function's package imports as
5
+ * shipped, so this file imports nothing and touches only what a function and
6
+ * the middleware runtime both have (fetch, `AbortController`, `crypto`).
7
+ *
8
+ * import { reportServerError, withErrorReporting } from "@atelic-action/ui/monitoring/server";
9
+ *
10
+ * Privacy: a report carries the request's method and path, and its user
11
+ * agent, never its body, its query string, or any other header. A contact
12
+ * form's request holds a person's name, address, and message.
13
+ */
14
+
15
+ /** The parts of a DSN a report is sent with. */
16
+ export interface ParsedDSN {
17
+ /** The public key, sent as `sentry_key`. */
18
+ key: string;
19
+ projectId: string;
20
+ /** Where the envelope is posted. */
21
+ envelopeURL: string;
22
+ }
23
+
24
+ export interface ServerReportOptions {
25
+ /** Defaults to `SENTRY_DSN`, then `VITE_SENTRY_DSN`, from the environment. */
26
+ dsn?: string;
27
+ /** The request being handled; only its method, path, and user agent are read. */
28
+ request?: Request;
29
+ /** Tags beside the runtime's, e.g. `{ route: "contact" }`. */
30
+ tags?: Record<string, string>;
31
+ /** Defaults to `VERCEL_GIT_COMMIT_SHA`. */
32
+ release?: string;
33
+ /** Defaults to `VERCEL_ENV`. */
34
+ environment?: string;
35
+ /** How long the send may take, in milliseconds. Defaults to 2000. */
36
+ timeoutMs?: number;
37
+ }
38
+
39
+ /** One stack frame in Sentry's exception format. */
40
+ export interface SentryFrame {
41
+ function?: string;
42
+ filename?: string;
43
+ lineno?: number;
44
+ colno?: number;
45
+ in_app: boolean;
46
+ }
47
+
48
+ const SDK = { name: "atelic.server", version: "1" };
49
+
50
+ function environmentValue(name: string): string | undefined {
51
+ const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process
52
+ ?.env;
53
+ const value = env?.[name];
54
+ return value === "" ? undefined : value;
55
+ }
56
+
57
+ /**
58
+ * Reads a DSN (`https://<key>@<host>[/<path>]/<project>`) into the URL its
59
+ * envelopes are posted to. Undefined for anything that is not one.
60
+ */
61
+ export function parseDSN(dsn: string | undefined): ParsedDSN | undefined {
62
+ if (!dsn) return undefined;
63
+ let url: URL;
64
+ try {
65
+ url = new URL(dsn);
66
+ } catch {
67
+ return undefined;
68
+ }
69
+ const key = url.username;
70
+ const parts = url.pathname.split("/").filter(Boolean);
71
+ const projectId = parts.pop();
72
+ if (!key || !projectId || !/^\d+$/.test(projectId)) return undefined;
73
+ const prefix = parts.length ? `/${parts.join("/")}` : "";
74
+ const envelopeURL = `${url.protocol}//${url.host}${prefix}/api/${projectId}/envelope/?sentry_key=${encodeURIComponent(key)}&sentry_version=7`;
75
+ return { key, projectId, envelopeURL };
76
+ }
77
+
78
+ /**
79
+ * The frames of a V8 stack (`at fn (file:line:col)`, `at file:line:col`),
80
+ * oldest call first, as Sentry lists them. A frame inside `node_modules` is
81
+ * not the site's own code.
82
+ */
83
+ export function parseStack(stack: string | undefined): SentryFrame[] {
84
+ if (!stack) return [];
85
+ const frames: SentryFrame[] = [];
86
+ for (const line of stack.split("\n")) {
87
+ const match = line.match(/^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/);
88
+ if (!match) continue;
89
+ const [, fn, filename, lineno, colno] = match;
90
+ frames.push({
91
+ ...(fn ? { function: fn } : {}),
92
+ filename,
93
+ lineno: Number(lineno),
94
+ colno: Number(colno),
95
+ in_app: !filename.includes("node_modules"),
96
+ });
97
+ }
98
+ return frames.reverse();
99
+ }
100
+
101
+ /** The runtime a report came from: Vercel's edge, Node, or neither. */
102
+ function runtime(): string {
103
+ if (typeof (globalThis as { EdgeRuntime?: unknown }).EdgeRuntime !== "undefined") return "edge";
104
+ const node = (globalThis as { process?: { versions?: { node?: string } } }).process?.versions
105
+ ?.node;
106
+ return node ? "node" : "unknown";
107
+ }
108
+
109
+ function eventID(): string {
110
+ const random = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto?.randomUUID;
111
+ if (random) return random.call(globalThis.crypto).replaceAll("-", "");
112
+ let id = "";
113
+ for (let i = 0; i < 32; i++) id += Math.floor(Math.random() * 16).toString(16);
114
+ return id;
115
+ }
116
+
117
+ /** The thrown value as Sentry's exception: its type, message, and frames. */
118
+ function exceptionOf(error: unknown) {
119
+ if (error instanceof Error) {
120
+ const frames = parseStack(error.stack);
121
+ return {
122
+ type: error.name || "Error",
123
+ value: error.message,
124
+ ...(frames.length ? { stacktrace: { frames } } : {}),
125
+ };
126
+ }
127
+ let value: string;
128
+ try {
129
+ value = typeof error === "string" ? error : JSON.stringify(error);
130
+ } catch {
131
+ value = String(error);
132
+ }
133
+ return { type: "Error", value: value ?? String(error) };
134
+ }
135
+
136
+ /**
137
+ * The request as a report may carry it: the method, the URL with no query
138
+ * string or fragment, and the user agent. Never the body, never another
139
+ * header.
140
+ */
141
+ function requestOf(request: Request | undefined) {
142
+ if (!request) return undefined;
143
+ let url: string | undefined;
144
+ try {
145
+ const parsed = new URL(request.url);
146
+ url = `${parsed.origin}${parsed.pathname}`;
147
+ } catch {
148
+ url = undefined;
149
+ }
150
+ const agent = request.headers?.get?.("user-agent");
151
+ return {
152
+ method: request.method,
153
+ ...(url ? { url } : {}),
154
+ ...(agent ? { headers: { "User-Agent": agent } } : {}),
155
+ };
156
+ }
157
+
158
+ /**
159
+ * The envelope a report is sent as: the envelope header, the item header,
160
+ * and the event, one JSON document to a line. Exported for the tests.
161
+ */
162
+ export function buildEnvelope(
163
+ error: unknown,
164
+ dsn: string,
165
+ options: Omit<ServerReportOptions, "dsn" | "timeoutMs"> = {},
166
+ now: Date = new Date(),
167
+ ): string {
168
+ const id = eventID();
169
+ const release = options.release ?? environmentValue("VERCEL_GIT_COMMIT_SHA");
170
+ const environment = options.environment ?? environmentValue("VERCEL_ENV");
171
+ const request = requestOf(options.request);
172
+ const event = {
173
+ event_id: id,
174
+ timestamp: now.getTime() / 1000,
175
+ platform: "javascript",
176
+ level: "error",
177
+ sdk: SDK,
178
+ ...(release ? { release } : {}),
179
+ ...(environment ? { environment } : {}),
180
+ tags: { runtime: runtime(), ...options.tags },
181
+ ...(request ? { request } : {}),
182
+ exception: { values: [exceptionOf(error)] },
183
+ };
184
+ const header = { event_id: id, sent_at: now.toISOString(), dsn, sdk: SDK };
185
+ return [JSON.stringify(header), JSON.stringify({ type: "event" }), JSON.stringify(event)].join(
186
+ "\n",
187
+ );
188
+ }
189
+
190
+ /**
191
+ * Reports an error to Sentry from a function or the middleware. Resolves
192
+ * true when Sentry took it and false otherwise (no DSN, a bad DSN, a failed
193
+ * or slow send), and never throws, so a report can never become a second
194
+ * failure. With no DSN it sends nothing.
195
+ */
196
+ export async function reportServerError(
197
+ error: unknown,
198
+ options: ServerReportOptions = {},
199
+ ): Promise<boolean> {
200
+ try {
201
+ const dsn =
202
+ options.dsn ?? environmentValue("SENTRY_DSN") ?? environmentValue("VITE_SENTRY_DSN");
203
+ const parsed = parseDSN(dsn);
204
+ if (!dsn || !parsed) return false;
205
+ const body = buildEnvelope(error, dsn, options);
206
+ const controller = new AbortController();
207
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 2000);
208
+ try {
209
+ const response = await fetch(parsed.envelopeURL, {
210
+ method: "POST",
211
+ headers: { "Content-Type": "application/x-sentry-envelope" },
212
+ body,
213
+ signal: controller.signal,
214
+ });
215
+ // The answer's body is never read, so it is let go at once rather
216
+ // than held open until the runtime collects it.
217
+ await response.body?.cancel().catch(() => {});
218
+ return response.ok;
219
+ } finally {
220
+ clearTimeout(timer);
221
+ }
222
+ } catch {
223
+ return false;
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Wraps a function's handler so a throw is reported, then thrown again: the
229
+ * platform still answers the request as it would have, and Sentry hears of
230
+ * it first. `export const POST = withErrorReporting(async (request) => ...)`.
231
+ */
232
+ export function withErrorReporting<Args extends [Request, ...unknown[]], Result>(
233
+ handler: (...args: Args) => Result | Promise<Result>,
234
+ options: Omit<ServerReportOptions, "request"> = {},
235
+ ): (...args: Args) => Promise<Result> {
236
+ return async (...args: Args) => {
237
+ try {
238
+ return await handler(...args);
239
+ } catch (error) {
240
+ await reportServerError(error, { ...options, request: args[0] });
241
+ throw error;
242
+ }
243
+ };
244
+ }