feat(insights): page speed per app with deploy markers, a web package that measures it, and the join to errors (PY3.3)

RYP-G3 in Wave P.
- @railyard/insights-web: page views (with client-side route changes),
  events, identify, and LCP, INP, CLS, FCP and TTFB per page view, sent once
  when the page is hidden or the route changes; no cookies, no storage, Do
  Not Track and consent respected. src/metrics.ts adapts MIT-licensed code
  (NOTICE keeps the licence) with two changes that match Chrome's field
  reporting: LCP stops at the first input, and INP picks its percentile from
  the page's interaction count. On six worked fixtures (after-click paint,
  two shift windows with a post-input shift, prerender activation, 120
  interactions, multi-event interactions) every metric and the p75 are
  within 10% of Chrome's values.
- Edge collector and ingest carry `performance` events (the five metrics,
  in the upstream ranges) into upstream event type 5 rows.
- Insights GET /api/v1/tenants/{org}/vitals: p75 per app, per UTC day, and
  in the day before and after each given deploy time (up to 10); ratings
  from the published thresholds; org-scoped (SQL test with hand p75s).
- Console: the Page speed screen (only with RAILYARD_REPLAY_LIVE=1) and the
  Scribase bridge `insights` answer gain `vitals` (p75 cells and one marker
  per deploy from the console's own deploy records, so a deploy is marked on
  the next read); a vitals failure never hides the rest of the tab.

The Scribase Analytics sub-tab (carve-out) joins these markers to the
environment's error issues: "This deploy raised errors by N" links to the
Errors tab.

Tests: console 128/128 (view model, bridge marker, flag gate, copy lint),
insights-web 12/12 (fixtures, client, copy), insights fork 12/12, edge
19/19, tsc clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
caelum0x 2026-09-30 04:05:42 +03:00
parent 6baaadf91a
commit 65acbbd9a3
23 changed files with 1555 additions and 9 deletions

View File

@ -0,0 +1,86 @@
import { currentSession } from "../../../../lib/current.ts";
import { deps } from "../../../../lib/deps.ts";
import { markTimes, vitalsView, type VitalsView } from "../../../../lib/vitals-view.ts";
export const dynamic = "force-dynamic";
// Page speed per app over 7 days, with a marker for each deploy and what
// changed after it (Wave P PY3.3). Shown only with RAILYARD_REPLAY_LIVE=1.
export default async function VitalsPage() {
const { repo, insights, cfg } = deps();
if (!cfg.replayLive || !insights?.vitals) {
return (
<>
<h1>Page speed</h1>
<section className="card">
<p className="muted">This part of Insights is arriving; it is not switched on for this console yet.</p>
</section>
</>
);
}
const s = (await currentSession())!;
const now = new Date();
const since = new Date(now.getTime() - 7 * 86_400_000);
const apps = await repo.listApps(s.org);
const views: { name: string; view: VitalsView | null }[] = [];
for (const app of apps) {
const marks = markTimes(await repo.listDeploys(s.org, app.id), app.id, since);
const v = await insights.vitals(s.org, { app: app.id, days: 7, marks: marks.map((d) => d.created_at) }).catch(() => null);
views.push({ name: app.name, view: v ? vitalsView(v, app.id, marks) : null });
}
return (
<>
<h1>Page speed</h1>
<p className="muted">The 75th percentile of page views in the last 7 days, and how each metric moved from the day before a deploy to the day after it.</p>
{views.length === 0 ? (
<section className="card">
<p className="muted">No apps yet. Add one on the Apps screen.</p>
</section>
) : null}
{views.map(({ name, view }) => (
<section className="card" key={name}>
<h2>{name}</h2>
{!view ? (
<p className="muted">Could not read page speed just now; try again in a minute.</p>
) : view.empty ? (
<p className="muted">No page speed yet. It arrives with the next page views once the page tag or the web package is on the site.</p>
) : (
<>
<table>
<thead>
<tr>
<th>Metric</th>
<th>75th percentile</th>
<th>Rating</th>
</tr>
</thead>
<tbody data-copy-source="insights /api/v1/tenants/{org}/vitals (live query)">
{view.metrics.map((m) => (
<tr key={m.key}>
<td>{m.label}</td>
<td>{m.value}</td>
<td>{m.rating ?? ""}</td>
</tr>
))}
</tbody>
</table>
<p className="muted">From {view.samples} page views.</p>
</>
)}
{view && view.deploys.length ? (
<>
<h3>Deploys</h3>
<ul data-copy-source="console deploy records and insights vitals around each deploy">
{view.deploys.map((d) => (
<li key={d.id}>
{d.at.slice(0, 16).replace("T", " ")} UTC, {d.branch}: {d.changes.length ? d.changes.join("; ") : "not enough page views on both sides yet"}
</li>
))}
</ul>
</>
) : null}
</section>
))}
</>
);
}

View File

@ -556,3 +556,43 @@ test("flags: a URL-keyed read is served from the edge cache for 15 s; a header-k
await clientFlags(flags, new Request("https://c/x", { headers: { "x-flags-key": key } }), T0, cache);
assert.equal(store.size, 1, "header-keyed reads are not cached");
});
test("analytics tab (PY3.3): page speed with a marker for a deploy recorded a moment ago, only with RAILYARD_REPLAY_LIVE", async () => {
const repo = new MemoryRepo(() => T0);
const asked: string[][] = [];
const row = (appId: string, lcp: number) => ({
app_id: appId,
samples: 30,
lcp: { p75: lcp, rating: (lcp <= 2500 ? "good" : "needs-improvement") as "good" | "needs-improvement" },
inp: { p75: 100, rating: "good" as const },
cls: { p75: 0.01, rating: "good" as const },
fcp: { p75: 800, rating: "good" as const },
ttfb: { p75: 150, rating: "good" as const },
});
const insights: InsightsClient = {
summary: async (orgId) => ({ org_id: orgId, since: T0.toISOString(), apps: [], funnel: { steps: [{ name: "visit", sessions: 0 }, { name: "signup", sessions: 0 }, { name: "first_action", sessions: 0 }] } }),
vitals: async (_org, q) => {
asked.push(q.marks ?? []);
return { since: T0.toISOString(), apps: [row(q.app, 2000)], daily: [], deploys: (q.marks ?? []).map((at) => ({ at, before: row(q.app, 1500), after: row(q.app, 2400) })) };
},
};
const extra = { insights, replayLive: true };
const orgId = (await call(repo, "orgs", { scribase_org_id: "org_vt", name: "V", addon: addon() }, { extra })).body.org_id as string;
await call(repo, "sites", { scribase_org_id: "org_vt", app: "shop-prod" }, { extra });
const app = (await repo.findAppByName(orgId, "shop-prod"))!;
const d = await repo.createDeploy({ org_id: orgId, app_id: app.id, url: "https://shop-prod.acme.workers.dev", commit_sha: null, branch: "main", framework: "vite", version_id: "v1", duration_ms: 1, status: "succeeded", rollback_of: null });
const tab = await call(repo, "insights", { scribase_org_id: "org_vt", app: "shop-prod" }, { extra });
assert.equal(tab.status, 200, JSON.stringify(tab.body));
const vitals = tab.body.vitals as { metrics: { key: string; value: string }[]; deploys: { id: string; at: string; changes: string[] }[] };
assert.equal(vitals.metrics[0]!.value, "2000 ms");
assert.equal(vitals.deploys[0]!.id, d.id, "the deploy is marked on the next read");
assert.equal(asked[0]![0], d.created_at);
assert.match(vitals.deploys[0]!.changes[0]!, /1500 ms to 2400 ms, slower/);
const off = await call(repo, "insights", { scribase_org_id: "org_vt", app: "shop-prod" }, { extra: { insights, replayLive: false } });
assert.equal(off.body.vitals, undefined);
assert.equal(off.body.available, true);
// A vitals failure never hides the rest of the tab.
const broken = await call(repo, "insights", { scribase_org_id: "org_vt", app: "shop-prod" }, { extra: { insights: { ...insights, vitals: async () => { throw new Error("down"); } }, replayLive: true } });
assert.equal(broken.body.available, true);
assert.equal(broken.body.vitals, undefined);
});

View File

@ -8,7 +8,7 @@ export async function POST(req: Request) {
const { cfg, repo, sites, insights } = deps();
if (!cfg.scribaseBridgeSecret) return json({ error: "bridge_not_configured" }, 503);
const r = await handleBridge(
{ repo, secret: cfg.scribaseBridgeSecret, consoleUrl: cfg.consoleUrl, now: () => new Date(), sites, insights, insightsUrl: cfg.insightsUrl, acceptLegacy: cfg.bridgeAcceptLegacy },
{ repo, secret: cfg.scribaseBridgeSecret, consoleUrl: cfg.consoleUrl, now: () => new Date(), sites, insights, insightsUrl: cfg.insightsUrl, acceptLegacy: cfg.bridgeAcceptLegacy, replayLive: cfg.replayLive },
"insights",
{ id: req.headers.get("webhook-id"), timestamp: req.headers.get("webhook-timestamp"), signature: req.headers.get("webhook-signature") },
await req.text(),

View File

@ -24,6 +24,7 @@ import { access } from "../../../../../lib/ladder.ts";
import { listDeploys } from "../../deploys/service.ts";
import { addApp, AppError, normaliseAppName } from "../../../../../lib/apps.ts";
import { firstEvent, type InsightsClient } from "../../../../../lib/insights.ts";
import { markTimes, vitalsView } from "../../../../../lib/vitals-view.ts";
import { capMessage } from "../../../../../lib/caps.ts";
import { registerSite, syncSites, type SitesStore } from "../../../../../lib/sites.ts";
import { issueAiKey, issueConnectToken } from "../../../../../lib/ai/provision.ts";
@ -71,6 +72,8 @@ export interface BridgeDeps {
flags?: FlagsDeps;
/** Railyard Watch (PY2.2); absent in tests that do not need it. */
watch?: WatchDeps;
/** Page speed with deploy markers in the Analytics tab (PY3.3), only with RAILYARD_REPLAY_LIVE=1. */
replayLive?: boolean;
/** P-Y1 transition: accept unbound ids and orgs syncs without `addon.as_of` (RAILYARD_BRIDGE_ACCEPT_LEGACY=1). */
acceptLegacy?: boolean;
}
@ -351,9 +354,11 @@ async function insightsFor(deps: BridgeDeps, body: Record<string, unknown>): Pro
const summary = await deps.insights.summary(who.orgId, { app: app.id, days: 7 });
const row = summary.apps.find((a) => a.app_id === app.id);
const limit = access(await deps.repo.getEntitlement(who.orgId), now).eventsLimit;
const vitals = await vitalsFor(deps, who.orgId, app.id, now);
return {
status: 200,
body: {
...(vitals ? { vitals } : {}),
available: true,
app: app.name,
first_event_at: row?.first_event_at ?? null,
@ -367,6 +372,18 @@ async function insightsFor(deps: BridgeDeps, body: Record<string, unknown>): Pro
};
}
/**
* Page speed and deploy markers for the Analytics tab (PY3.3). Absent unless
* RAILYARD_REPLAY_LIVE is on; a vitals error never hides the rest of the tab.
*/
async function vitalsFor(deps: BridgeDeps, orgId: string, appId: string, now: Date) {
if (!deps.replayLive || !deps.insights?.vitals) return null;
const since = new Date(now.getTime() - 7 * 86_400_000);
const marks = markTimes(await deps.repo.listDeploys(orgId, appId), appId, since);
const v = await deps.insights.vitals(orgId, { app: appId, days: 7, marks: marks.map((d) => d.created_at) }).catch(() => null);
return v ? vitalsView(v, appId, marks) : null;
}
/** The AI gateway for one project environment (PY1.4, BYOK only). The key goes to the Scribase control plane only. */
async function aiFor(deps: BridgeDeps, body: Record<string, unknown>): Promise<BridgeResult> {
const scribaseOrgId = parseOrgRef(body);

View File

@ -8,8 +8,22 @@ export interface InsightsSummary {
funnel: { steps: { name: "visit" | "signup" | "first_action"; sessions: number }[] };
}
export type VitalMetric = "lcp" | "inp" | "cls" | "fcp" | "ttfb";
export type VitalRating = "good" | "needs-improvement" | "poor";
export type VitalsRow = { app_id: string; samples: number } & Record<VitalMetric, { p75: number | null; rating: VitalRating | null }>;
/** The fork's `/api/v1/tenants/{org}/vitals` answer (PY3.3). */
export interface InsightsVitals {
since: string;
apps: VitalsRow[];
daily: (VitalsRow & { day: string })[];
deploys: { at: string; before: VitalsRow | null; after: VitalsRow | null }[];
}
export interface InsightsClient {
summary(orgId: string, opts?: { app?: string; days?: number }): Promise<InsightsSummary>;
/** Web vitals p75 (PY3.3); optional so older fakes and deployments still type-check. */
vitals?(orgId: string, opts: { app: string; days?: number; marks?: string[] }): Promise<InsightsVitals>;
}
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@ -39,6 +53,15 @@ export function insightsClient(opts: { apiUrl: string; token: string; fetchImpl?
if (!isSummary(body)) throw new Error("Insights answered with an unexpected shape");
return body;
},
async vitals(orgId, { app, days = 7, marks = [] }) {
if (!UUID.test(orgId) || !UUID.test(app)) throw new Error("invalid org or app id");
const q = new URLSearchParams({ app, days: String(days), ...(marks.length ? { marks: marks.slice(0, 10).join(",") } : {}) });
const res = await fetchImpl(`${base}/api/v1/tenants/${orgId}/vitals?${q}`, { headers: { authorization: `Bearer ${opts.token}`, accept: "application/json" } });
if (!res.ok) throw new Error(`Insights answered ${res.status}`);
const body = (await res.json()) as InsightsVitals;
if (!body || !Array.isArray(body.apps) || !Array.isArray(body.daily) || !Array.isArray(body.deploys)) throw new Error("Insights answered with an unexpected shape");
return body;
},
};
}

View File

@ -0,0 +1,72 @@
// Page speed with deploy markers (Wave P PY3.3): the view model, the flag
// gate and the copy lint with the flag on. The bridge answer is tested in
// app/api/v1/bridge/scribase/bridge.test.ts.
// node --test lib/vitals-view.test.ts
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import type { Deploy } from "./types.ts";
import type { InsightsVitals, VitalsRow } from "./insights.ts";
import { format, markTimes, vitalsView } from "./vitals-view.ts";
import { errors, formatFindings, lintUnits } from "../../../policy/copy-lint.mjs";
const NOW = new Date("2026-09-30T12:00:00Z");
const APP = "5d1c0000-aaaa-4aaa-8aaa-5d1c0000aaaa";
const row = (lcp: number, inp: number, cls: number): VitalsRow => ({
app_id: APP,
samples: 40,
lcp: { p75: lcp, rating: lcp <= 2500 ? "good" : lcp > 4000 ? "poor" : "needs-improvement" },
inp: { p75: inp, rating: "good" },
cls: { p75: cls, rating: "good" },
fcp: { p75: 900, rating: "good" },
ttfb: { p75: 200, rating: "good" },
});
const deploy = (id: string, at: string, over: Partial<Deploy> = {}): Deploy => ({
id, org_id: "o", app_id: APP, url: "https://shop.acme.workers.dev", commit_sha: null, branch: "main", framework: "vite", version_id: null, duration_ms: 1, status: "succeeded", rollback_of: null, created_at: at, ...over,
});
test("the view: p75 per metric with a plain rating, and per deploy what changed after it", () => {
const d1 = deploy("d1", "2026-09-29T12:00:00.000Z");
const v: InsightsVitals = {
since: "2026-09-23T12:00:00.000Z",
apps: [row(2600, 120, 0.05)],
daily: [{ ...row(2600, 120, 0.05), day: "2026-09-29" }],
deploys: [{ at: d1.created_at, before: row(1300, 120, 0.05), after: row(3750, 125, 0.2) }],
};
const view = vitalsView(v, APP, [d1]);
assert.deepEqual(view.metrics.map((m) => [m.key, m.value, m.rating]), [
["lcp", "2600 ms", "needs work"],
["inp", "120 ms", "good"],
["cls", "0.05", "good"],
["fcp", "900 ms", "good"],
["ttfb", "200 ms", "good"],
]);
assert.deepEqual(view.deploys[0]!.changes.slice(0, 3), [
"Largest paint (LCP) 1300 ms to 3750 ms, slower",
"Response to input (INP) 120 ms to 125 ms, about the same",
"Layout shift (CLS) 0.05 to 0.20, more shifting",
]);
assert.equal(view.deploys[0]!.worse, "cls");
assert.equal(format("lcp", null), "no data");
// Only this app's successful deploys in the window, newest first, at most 10.
const many = [deploy("old", "2026-09-01T00:00:00Z"), deploy("fail", "2026-09-29T00:00:00Z", { status: "failed" }), deploy("other", "2026-09-29T00:00:00Z", { app_id: "x" }), ...Array.from({ length: 12 }, (_, i) => deploy(`n${i}`, `2026-09-2${Math.min(9, 4 + Math.floor(i / 2))}T0${i % 10}:00:00Z`))];
const marks = markTimes(many, APP, new Date("2026-09-23T12:00:00Z"));
assert.equal(marks.length, 10);
assert.ok(marks.every((m) => m.status === "succeeded" && m.app_id === APP));
assert.ok(marks[0]!.created_at >= marks[9]!.created_at);
});
test("the Page speed screen passes the copy lint with the flag on, and checks the flag first", () => {
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
const src = readFileSync(join(ROOT, "app/(app)/insights/vitals/page.tsx"), "utf8");
assert.match(src, /if \(!cfg\.replayLive \|\| !insights\?\.vitals\)/);
const strings = [...src.matchAll(/["`]([^"`\n]{12,})["`]|>([^<>{}\n]{12,})</g)].map((m) => (m[1] ?? m[2])!.trim()).filter((s) => !/^[\^[/.]|https?:|\$\{|^[a-z-]+:|insights \//.test(s));
const model = readFileSync(join(ROOT, "lib/vitals-view.ts"), "utf8");
const modelStrings = [...model.matchAll(/"([^"\n]{12,})"/g)].map((m) => m[1]!);
const units = [...strings, ...modelStrings].map((text) => ({ text, surface: "app-ui", where: "vitals" }));
const found = errors(lintUnits(units, { flags: { RAILYARD_REPLAY_LIVE: "1" } }));
assert.deepEqual(found, [], formatFindings(found));
});

View File

@ -0,0 +1,92 @@
// Page speed per app with deploy markers (Wave P PY3.3) as a pure model, for
// the console page and the Scribase Analytics tab (through the bridge).
// Markers come from the console's own deploy records, so a deploy shows up
// as soon as it is recorded (the pages refresh within 60 s).
import type { InsightsVitals, VitalMetric, VitalRating, VitalsRow } from "./insights.ts";
import type { Deploy } from "./types.ts";
export const METRICS: { key: VitalMetric; label: string; unit: "ms" | "" }[] = [
{ key: "lcp", label: "Largest paint (LCP)", unit: "ms" },
{ key: "inp", label: "Response to input (INP)", unit: "ms" },
{ key: "cls", label: "Layout shift (CLS)", unit: "" },
{ key: "fcp", label: "First paint (FCP)", unit: "ms" },
{ key: "ttfb", label: "Server response (TTFB)", unit: "ms" },
];
const RATING: Record<VitalRating, string> = { good: "good", "needs-improvement": "needs work", poor: "poor" };
/** A change under this share of the earlier value is shown as "about the same". */
const NOISE = 0.1;
export interface MetricCell {
key: VitalMetric;
label: string;
value: string;
rating: string | null;
}
export interface DeployMarker {
id: string;
at: string;
branch: string;
url: string;
/** Plain lines such as "Largest paint (LCP) 1300 ms to 3750 ms, slower". */
changes: string[];
/** The metric that got worse the most, if any got worse beyond noise. */
worse: VitalMetric | null;
}
export interface VitalsView {
samples: number;
metrics: MetricCell[];
daily: { day: string; samples: number; lcp: string; inp: string; cls: string }[];
deploys: DeployMarker[];
empty: boolean;
}
export function format(key: VitalMetric, v: number | null): string {
if (v === null) return "no data";
return key === "cls" ? v.toFixed(2) : `${Math.round(v)} ms`;
}
/** The deploy times to compare: the app's successful deploys in the window, newest first, at most 10. */
export function markTimes(deploys: Deploy[], appId: string, since: Date): Deploy[] {
return deploys
.filter((d) => d.app_id === appId && d.status === "succeeded" && Date.parse(d.created_at) >= since.getTime())
.sort((a, b) => (a.created_at < b.created_at ? 1 : -1))
.slice(0, 10);
}
function change(key: VitalMetric, label: string, before: number | null, after: number | null): { line: string; worse: number } | null {
if (before === null || after === null) return null;
const base = Math.max(before, key === "cls" ? 0.01 : 1);
const delta = (after - before) / base;
const trend = Math.abs(delta) < NOISE ? "about the same" : delta > 0 ? "slower" : "faster";
const word = key === "cls" && trend !== "about the same" ? (delta > 0 ? "more shifting" : "less shifting") : trend;
return { line: `${label} ${format(key, before)} to ${format(key, after)}, ${word}`, worse: delta >= NOISE ? delta : 0 };
}
export function vitalsView(v: InsightsVitals, appId: string, deploys: Deploy[]): VitalsView {
const row: VitalsRow | undefined = v.apps.find((a) => a.app_id === appId);
const metrics = METRICS.map((m) => ({ key: m.key, label: m.label, value: format(m.key, row?.[m.key].p75 ?? null), rating: row?.[m.key].rating ? RATING[row[m.key].rating as VitalRating] : null }));
const daily = v.daily
.filter((d) => d.app_id === appId)
.map((d) => ({ day: d.day, samples: d.samples, lcp: format("lcp", d.lcp.p75), inp: format("inp", d.inp.p75), cls: format("cls", d.cls.p75) }));
const byTime = new Map(v.deploys.map((d) => [new Date(d.at).toISOString(), d]));
const markers = deploys.map((d) => {
const cmp = byTime.get(new Date(d.created_at).toISOString());
let worst = 0;
let worse: VitalMetric | null = null;
const changes: string[] = [];
for (const m of METRICS) {
const c = change(m.key, m.label, cmp?.before?.[m.key].p75 ?? null, cmp?.after?.[m.key].p75 ?? null);
if (!c) continue;
changes.push(c.line);
if (c.worse > worst) {
worst = c.worse;
worse = m.key;
}
}
return { id: d.id, at: d.created_at, branch: d.branch, url: d.url, changes, worse };
});
return { samples: row?.samples ?? 0, metrics, daily, deploys: markers, empty: !row || row.samples === 0 };
}

View File

@ -10,7 +10,7 @@
"cf:build": "opennextjs-cloudflare build",
"cf:deploy": "opennextjs-cloudflare deploy",
"typecheck": "tsc --noEmit",
"test": "node --test test/*.test.ts app/api/v1/deploys/*.test.ts app/api/v1/bridge/scribase/*.test.ts lib/ai/*.test.ts lib/flags/*.test.ts lib/watch/*.test.ts lib/ship/*.test.ts lib/insights-depth/*.test.ts",
"test": "node --test test/*.test.ts app/api/v1/deploys/*.test.ts app/api/v1/bridge/scribase/*.test.ts lib/ai/*.test.ts lib/flags/*.test.ts lib/watch/*.test.ts lib/ship/*.test.ts lib/insights-depth/*.test.ts lib/vitals-view.test.ts",
"test:bundle": "node --test test/bundle-secrets.test.ts"
},
"dependencies": {

View File

@ -3,7 +3,9 @@
export const MAX_BATCH = 100;
export const MAX_BODY_BYTES = 64 * 1024;
const TYPES = new Set(["event", "identify"]);
const TYPES = new Set(["event", "identify", "performance"]);
/** Web vitals of one page view (PY3.3), with the upstream collector's ranges. */
export const VITALS = { lcp: 60000, inp: 60000, cls: 100, fcp: 60000, ttfb: 60000 };
/** The app's own user id (PY3.2): short and plain; the same pattern Insights ingest checks. */
export const USER_ID = /^[A-Za-z0-9@._:+=-]{1,50}$/;
@ -44,12 +46,23 @@ export function parseOne(item) {
if (p.user !== undefined && p.user !== null && !(typeof p.user === "string" && USER_ID.test(p.user))) return { error: "invalid user" };
const user = typeof p.user === "string" ? p.user : null;
if (type === "identify" && !user) return { error: "identify needs user" };
const vitals = {};
if (type === "performance") {
for (const [k, max] of Object.entries(VITALS)) {
const v = p[k];
if (v === undefined || v === null) continue;
if (typeof v !== "number" || !Number.isFinite(v) || v < 0 || v > max) return { error: `invalid ${k}` };
vitals[k] = v;
}
if (!Object.keys(vitals).length) return { error: "performance needs a metric" };
}
return {
siteKey,
event: {
type,
...(id ? { id } : {}),
...(user ? { user } : {}),
...vitals,
name: str(p.name, 50),
url,
hostname: str(p.hostname, 100),

View File

@ -69,3 +69,13 @@ test("PY3.2: the page tag exposes identify and sends it only for a plain user id
assert.deepEqual(bodies.map((b) => [b.type, b.payload.user, b.payload.name ?? null]), [["identify", "user_42", null], ["event", "user_42", "created_project"]]);
assert.deepEqual(bodies[0].payload.data, { plan: "pro" });
});
test("PY3.3: a performance event carries only the five metrics, in range", () => {
const ok = parseOne({ type: "performance", payload: { website: "ry_site_abcdefgh", url: "/", lcp: 2100, inp: 180, cls: 0.05, fcp: 900, ttfb: 300, duration: 5000 } });
assert.deepEqual([ok.event.lcp, ok.event.inp, ok.event.cls, ok.event.fcp, ok.event.ttfb], [2100, 180, 0.05, 900, 300]);
assert.equal(ok.event.duration, undefined);
assert.equal(parseOne({ type: "performance", payload: { website: "ry_site_abcdefgh", url: "/" } }).error, "performance needs a metric");
assert.equal(parseOne({ type: "performance", payload: { website: "ry_site_abcdefgh", url: "/", lcp: -3 } }).error, "invalid lcp");
assert.equal(parseOne({ type: "performance", payload: { website: "ry_site_abcdefgh", url: "/", cls: "0.1" } }).error, "invalid cls");
assert.equal(parseOne({ type: "event", payload: { website: "ry_site_abcdefgh", url: "/", lcp: 5 } }).event.lcp, undefined, "metrics ride only on performance events");
});

View File

@ -0,0 +1,11 @@
// Railyard fork addition (PY3.3): web vitals p75 per app, per day, and around deploy times.
import { authorized, db, intParam, json, reply } from '@/railyard/route-kit';
import { vitals } from '@/railyard/vitals';
export const dynamic = 'force-dynamic';
export async function GET(request: Request, { params }: { params: Promise<{ org: string }> }) {
if (!authorized(request)) return json({ error: 'unauthorized' }, 401);
const q = new URL(request.url).searchParams;
return reply(await vitals(db, (await params).org, { app: q.get('app'), days: intParam(q.get('days')), marks: q.get('marks') }, new Date()));
}

View File

@ -22,7 +22,7 @@ export const USER_ID = /^[A-Za-z0-9@._:+=-]{1,50}$/;
export interface EdgeEvent {
/** `identify` (PY3.2) links the visitor's session to `user` and merges `data` into the profile. */
type: 'event' | 'identify';
type: 'event' | 'identify' | 'performance';
name: string | null;
url: string;
hostname: string | null;
@ -36,6 +36,31 @@ export interface EdgeEvent {
ts: string;
/** The app's user id when the person is signed in (PY3.2); null for anonymous visitors. */
user: string | null;
/** Web vitals of a `performance` event (PY3.3); null elsewhere. */
vitals: Vitals | null;
}
export interface Vitals {
lcp?: number;
inp?: number;
cls?: number;
fcp?: number;
ttfb?: number;
}
/** The upstream collector's ranges for each metric. */
export const VITAL_MAX: Record<keyof Vitals, number> = { lcp: 60000, inp: 60000, cls: 100, fcp: 60000, ttfb: 60000 };
export const EVENT_TYPE_PERFORMANCE = 5;
function parseVitals(e: Record<string, unknown>): Vitals | null | undefined {
const out: Vitals = {};
for (const [k, max] of Object.entries(VITAL_MAX) as [keyof Vitals, number][]) {
const v = e[k];
if (v === undefined || v === null) continue;
if (typeof v !== 'number' || !Number.isFinite(v) || v < 0 || v > max) return undefined;
out[k] = v;
}
return Object.keys(out).length ? out : null;
}
export interface EdgeBatch {
@ -58,7 +83,7 @@ function parseEvent(v: unknown): EdgeEvent | null {
const url = str(e.url, 2000);
const visitor = str(e.visitor, 64);
const ts = str(e.ts, 40);
if ((e.type !== 'event' && e.type !== 'identify') || url === null || !visitor || !/^[0-9a-f]{16,64}$/.test(visitor) || !ts || Number.isNaN(Date.parse(ts))) return null;
if ((e.type !== 'event' && e.type !== 'identify' && e.type !== 'performance') || url === null || !visitor || !/^[0-9a-f]{16,64}$/.test(visitor) || !ts || Number.isNaN(Date.parse(ts))) return null;
let data: EdgeEvent['data'] = null;
if (e.data && typeof e.data === 'object' && !Array.isArray(e.data)) {
const entries = Object.entries(e.data as Record<string, unknown>).filter(
@ -72,9 +97,12 @@ function parseEvent(v: unknown): EdgeEvent | null {
const user = e.user === null || e.user === undefined ? null : typeof e.user === 'string' && USER_ID.test(e.user) ? e.user : undefined;
if (user === undefined) return null;
if (e.type === 'identify' && user === null) return null;
const vitals = e.type === 'performance' ? parseVitals(e) : null;
if (vitals === undefined || (e.type === 'performance' && vitals === null)) return null;
return {
type: e.type,
user,
vitals,
name,
url,
hostname: str(e.hostname, 100),
@ -138,6 +166,11 @@ export interface EventRow {
country: string | null;
eventName: string | null;
eventData: Record<string, string | number | boolean> | null;
lcp?: number;
inp?: number;
cls?: number;
fcp?: number;
ttfb?: number;
}
/** Maps one collector event to upstream rows. `id` derives stable UUIDs (upstream's v5 hash). */
@ -168,7 +201,7 @@ export function toRows(appId: string, e: EdgeEvent, id: (...parts: string[]) =>
websiteId: appId,
sessionId,
visitId: id(sessionId, hour),
eventType: e.name ? EVENT_TYPE_CUSTOM : EVENT_TYPE_PAGE_VIEW,
eventType: e.type === 'performance' ? EVENT_TYPE_PERFORMANCE : e.name ? EVENT_TYPE_CUSTOM : EVENT_TYPE_PAGE_VIEW,
createdAt,
pageTitle: e.title,
hostname: e.hostname ?? current.hostname,
@ -180,8 +213,9 @@ export function toRows(appId: string, e: EdgeEvent, id: (...parts: string[]) =>
screen: e.screen,
language: e.language,
country: e.country,
eventName: e.name,
eventData: e.data,
eventName: e.type === 'performance' ? null : e.name,
eventData: e.type === 'performance' ? null : e.data,
...(e.vitals ?? {}),
},
};
}
@ -232,7 +266,7 @@ export async function ingest(deps: IngestDeps, body: IngestBody): Promise<Ingest
sessions.add(rows.session.id);
await deps.createSession(rows.session);
}
if (e.type === 'event') {
if (e.type === 'event' || e.type === 'performance') {
await deps.saveEvent(rows.event);
stored += 1;
}

View File

@ -0,0 +1,116 @@
// Web vitals (PY3.3) at the SQL level on a throwaway cluster: performance
// events from the collector land as upstream type 5 rows with their metrics;
// p75 per app, per day and around a deploy equal hand-computed values; org
// isolation. Skipped when pg_ctl/initdb are missing.
import { test, after } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync, spawnSync } from 'node:child_process';
import { mkdtempSync, readdirSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
import { toPositional } from './tenancy.ts';
import { parseIngest, toRows } from './ingest.ts';
import { rate, vitals } from './vitals.ts';
const HERE = dirname(fileURLToPath(import.meta.url));
const MIGRATIONS = join(HERE, '../../prisma/migrations');
const have = spawnSync('pg_ctl', ['--version']).status === 0 && spawnSync('initdb', ['--version']).status === 0;
const ORG_A = '0b8f6a3e-1111-4a3e-8b8f-0b8f6a3e1111';
const ORG_B = '0b8f6a3e-2222-4a3e-8b8f-0b8f6a3e2222';
const APP_A = '5d1c0000-aaaa-4aaa-8aaa-5d1c0000aaaa';
const APP_B = '5d1c0000-bbbb-4bbb-8bbb-5d1c0000bbbb';
const NOW = new Date('2026-09-30T12:00:00Z');
const DEPLOY = '2026-09-29T12:00:00.000Z';
const id = (...p) => {
const h = createHash('sha256').update(p.join('|')).digest('hex');
return `${h.slice(0, 8)}-${h.slice(8, 12)}-5${h.slice(13, 16)}-8${h.slice(17, 20)}-${h.slice(20, 32)}`;
};
test('ratings follow the published thresholds', () => {
assert.equal(rate('lcp', 2500), 'good');
assert.equal(rate('lcp', 2501), 'needs-improvement');
assert.equal(rate('lcp', 4001), 'poor');
assert.equal(rate('cls', 0.1), 'good');
assert.equal(rate('inp', 600), 'poor');
assert.equal(rate('ttfb', null), null);
});
test('a performance event from the collector is validated and becomes an upstream type 5 row', () => {
const body = (ev) => ({ org_id: ORG_A, sent_at: NOW.toISOString(), batches: [{ site_key: 'ry_site_abcdefgh12', app_id: APP_A, events: [ev] }] });
const base = { type: 'performance', name: null, url: '/', hostname: 'shop.example', referrer: null, title: null, language: null, screen: null, data: null, visitor: 'a'.repeat(32), country: null, ts: NOW.toISOString() };
const ok = parseIngest(body({ ...base, lcp: 2100, inp: 180, cls: 0.05, fcp: 900, ttfb: 300 }));
assert.notEqual(typeof ok, 'string');
const rows = toRows(APP_A, ok.batches[0].events[0], id);
assert.equal(rows.event.eventType, 5);
assert.deepEqual([rows.event.lcp, rows.event.inp, rows.event.cls, rows.event.fcp, rows.event.ttfb], [2100, 180, 0.05, 900, 300]);
assert.equal(parseIngest(body({ ...base })), 'an event is malformed', 'a performance event needs a metric');
assert.equal(parseIngest(body({ ...base, lcp: -1 })), 'an event is malformed');
assert.equal(parseIngest(body({ ...base, cls: 101 })), 'an event is malformed');
assert.equal(parseIngest(body({ ...base, type: 'event', name: 'x', lcp: 5 })).batches[0].events[0].vitals, null, 'metrics ride only on performance events');
});
test('p75 per app, per day and around a deploy equal hand-computed values; org B sees none of org A', { skip: have ? false : 'pg_ctl/initdb not installed' }, async () => {
const dir = mkdtempSync(join(tmpdir(), 'ry-insights-vitals-'));
const port = String(50000 + Math.floor(Math.random() * 1900));
after(() => {
spawnSync('pg_ctl', ['-D', join(dir, 'data'), '-m', 'immediate', 'stop'], { stdio: 'ignore' });
rmSync(dir, { recursive: true, force: true });
});
execFileSync('initdb', ['-D', join(dir, 'data'), '-U', 'postgres', '-A', 'trust', '--no-sync'], { stdio: 'ignore' });
execFileSync('pg_ctl', ['-D', join(dir, 'data'), '-o', `-p ${port} -k ${dir} -c listen_addresses='' -c TimeZone=UTC`, '-w', 'start'], { stdio: 'ignore' });
const psql = (args) => execFileSync('psql', ['-h', dir, '-p', port, '-U', 'postgres', '-v', 'ON_ERROR_STOP=1', '-q', ...args], { encoding: 'utf8' });
for (const m of readdirSync(MIGRATIONS).filter((d) => /^\d+_/.test(d)).sort((a, b) => parseInt(a) - parseInt(b))) psql(['-f', join(MIGRATIONS, m, 'migration.sql')]);
const lit = (v) => (v === null || v === undefined ? 'null' : `'${String(v).replace(/'/g, "''")}'`);
let n = 0;
const db = {
async query(sql, data) {
const { text, values } = toPositional(sql, data);
const name = `q${++n}`;
const out = psql(['--csv', '-c', `prepare ${name} as ${text.replace(/\s+/g, ' ')}; execute ${name}${values.length ? `(${values.map(lit).join(', ')})` : ''};`]).trim();
if (!out) return [];
const [head, ...rows] = out.split('\n').map((l) => l.split(','));
return rows.map((r) => Object.fromEntries(head.map((h, i) => [h, r[i] === '' ? null : r[i]])));
},
};
for (const [org, app] of [[ORG_A, APP_A], [ORG_B, APP_B]]) {
psql(['-c', `insert into team (team_id, name, created_at) values ('${org}', 'o', now()); insert into website (website_id, name, team_id, created_at) values ('${app}', 's', '${org}', now())`]);
}
const perf = (app, at, v) =>
psql(['-c', `insert into website_event (event_id, website_id, session_id, visit_id, created_at, url_path, event_type, lcp, inp, cls, fcp, ttfb) values (gen_random_uuid(), '${app}', gen_random_uuid(), gen_random_uuid(), '${at}', '/', 5, ${v.lcp}, ${v.inp}, ${v.cls}, ${v.fcp}, ${v.ttfb})`]);
// Before the deploy (the previous 24 h): fast. After: LCP got slower.
const before = [1000, 1200, 1400, 1600];
const afterLcp = [2000, 3000, 4000, 5000];
before.forEach((l, i) => perf(APP_A, `2026-09-29T0${i}:00:00Z`, { lcp: l, inp: 100, cls: 0.01, fcp: 800, ttfb: 200 }));
afterLcp.forEach((l, i) => perf(APP_A, `2026-09-29T1${3 + i}:00:00Z`, { lcp: l, inp: 150, cls: 0.02, fcp: 900, ttfb: 250 }));
// A page view (type 1) is not a vitals sample; org B has its own slow page.
psql(['-c', `insert into website_event (event_id, website_id, session_id, visit_id, created_at, url_path, event_type) values (gen_random_uuid(), '${APP_A}', gen_random_uuid(), gen_random_uuid(), '2026-09-29T15:00:00Z', '/', 1)`]);
perf(APP_B, '2026-09-29T15:00:00Z', { lcp: 9000, inp: 900, cls: 0.9, fcp: 5000, ttfb: 3000 });
const p75 = (xs) => {
const s = [...xs].sort((a, b) => a - b);
const pos = 0.75 * (s.length - 1);
const lo = Math.floor(pos);
return s[lo] + (s[Math.min(lo + 1, s.length - 1)] - s[lo]) * (pos - lo);
};
const r = await vitals(db, ORG_A, { app: APP_A, days: 7, marks: DEPLOY }, NOW);
assert.equal(r.apps.length, 1);
assert.equal(r.apps[0].samples, 8);
assert.equal(r.apps[0].lcp.p75, p75([...before, ...afterLcp]));
assert.equal(r.apps[0].lcp.rating, rate('lcp', p75([...before, ...afterLcp])));
assert.deepEqual(r.daily.map((d) => [d.day, d.samples]), [['2026-09-29', 8]]);
const [d] = r.deploys;
assert.equal(d.at, DEPLOY);
assert.equal(d.before.lcp.p75, p75(before));
assert.equal(d.after.lcp.p75, p75(afterLcp));
assert.equal(d.before.lcp.rating, 'good');
assert.equal(d.after.lcp.rating, 'poor');
assert.equal(d.after.cls.p75, 0.02);
const b = await vitals(db, ORG_B, { app: APP_A, days: 7 }, NOW);
assert.deepEqual(b.apps, [], 'org B naming org A\'s app sees nothing');
const bAll = await vitals(db, ORG_B, {}, NOW);
assert.deepEqual(bAll.apps.map((x) => [x.app_id, x.lcp.p75]), [[APP_B, 9000]]);
assert.equal(typeof (await vitals(db, ORG_A, { marks: DEPLOY }, NOW)), 'string', 'marks need an app');
});

View File

@ -0,0 +1,122 @@
/**
* Web vitals per app (fork addition, PY3.3): the 75th percentile of LCP, INP,
* CLS, FCP and TTFB from page views (`performance` events, upstream event type
* 5), overall, per UTC day, and before and after given deploy times. Scoped by
* the org through `website.team_id`; bound parameters only.
*
* p75 is the figure Chrome's own field reporting uses to rate a page; the
* ratings use the published thresholds (good / needs improvement / poor).
*/
// Kept import-free so node:test runs these modules without the app's build.
const isUuid = (v: unknown): v is string =>
typeof v === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v);
export const METRICS = ['lcp', 'inp', 'cls', 'fcp', 'ttfb'] as const;
export type Metric = (typeof METRICS)[number];
/** [good at or below, poor above]. */
export const THRESHOLDS: Record<Metric, [number, number]> = {
lcp: [2500, 4000],
inp: [200, 500],
cls: [0.1, 0.25],
fcp: [1800, 3000],
ttfb: [800, 1800],
};
export type Rating = 'good' | 'needs-improvement' | 'poor';
export function rate(metric: Metric, value: number | null): Rating | null {
if (value === null) return null;
const [good, poor] = THRESHOLDS[metric];
return value <= good ? 'good' : value > poor ? 'poor' : 'needs-improvement';
}
const P75 = METRICS.map((m) => `percentile_cont(0.75) within group (order by e.${m}) as ${m}_p75`).join(',\n ');
const FROM = `
from website_event e
join website w on w.website_id = e.website_id
where w.team_id = {{orgId::uuid}} and w.deleted_at is null
and ({{appId}}::uuid is null or e.website_id = {{appId}}::uuid)
and e.event_type = 5
and e.created_at >= {{from::timestamptz}} and e.created_at < {{to::timestamptz}}`;
export const VITALS_SQL = `
select e.website_id::text as app_id,
${P75},
count(*) as samples
${FROM}
group by e.website_id
order by e.website_id`;
export const VITALS_DAILY_SQL = `
select e.website_id::text as app_id, date_trunc('day', e.created_at, 'UTC') as day,
${P75},
count(*) as samples
${FROM}
group by 1, 2
order by 2, 1`;
export interface Query {
query<T>(sql: string, data: Record<string, unknown>): Promise<T[]>;
}
export interface MetricValue {
p75: number | null;
rating: Rating | null;
}
export type VitalsRow = { app_id: string; samples: number } & Record<Metric, MetricValue>;
const num = (v: unknown): number | null => (v === null || v === undefined || v === '' ? null : Math.round(Number(v) * 1000) / 1000);
function toRow(r: Record<string, unknown>): VitalsRow {
const out = { app_id: String(r.app_id), samples: Number(r.samples) } as VitalsRow;
for (const m of METRICS) {
const p75 = num(r[`${m}_p75`]);
out[m] = { p75, rating: rate(m, p75) };
}
return out;
}
export interface DeployComparison {
at: string;
before: VitalsRow | null;
after: VitalsRow | null;
}
/**
* `GET /api/v1/tenants/{org}/vitals?app=&days=&marks=<iso,iso>`: overall and
* daily p75 over the window, and for each deploy time (at most 10) the p75 in
* the 24 hours before and after it.
*/
export async function vitals(
db: Query,
orgId: string,
q: { app?: string | null; days?: number; marks?: string | null },
now: Date,
): Promise<{ since: string; apps: VitalsRow[]; daily: (VitalsRow & { day: string })[]; deploys: DeployComparison[] } | string> {
if (!isUuid(orgId)) return 'org must be a UUID';
const appId = q.app ?? null;
if (appId !== null && !isUuid(appId)) return 'app must be a UUID';
const days = q.days ?? 7;
if (!Number.isInteger(days) || days < 1 || days > 90) return 'days must be 1 to 90';
const marks = (q.marks ?? '').split(',').filter(Boolean);
if (marks.length > 10 || marks.some((m) => Number.isNaN(Date.parse(m)))) return 'marks must be up to 10 times';
if (marks.length && appId === null) return 'marks need app (deploys belong to one app)';
const from = new Date(now.getTime() - days * 86_400_000).toISOString();
const to = now.toISOString();
const apps = (await db.query<Record<string, unknown>>(VITALS_SQL, { orgId, appId, from, to })).map(toRow);
const daily = (await db.query<Record<string, unknown>>(VITALS_DAILY_SQL, { orgId, appId, from, to })).map((r) => ({ ...toRow(r), day: new Date(r.day as string).toISOString().slice(0, 10) }));
const deploys: DeployComparison[] = [];
for (const m of marks) {
const at = new Date(m);
const window = (a: number, b: number) =>
db.query<Record<string, unknown>>(VITALS_SQL, { orgId, appId, from: new Date(at.getTime() + a).toISOString(), to: new Date(at.getTime() + b).toISOString() });
const [before] = await window(-86_400_000, 0);
const [after] = await window(0, 86_400_000);
deploys.push({ at: at.toISOString(), before: before ? toRow(before) : null, after: after ? toRow(after) : null });
}
return { since: from, apps, daily, deploys };
}

View File

@ -0,0 +1,27 @@
@railyard/insights-web
Copyright 2026 Railyard
src/metrics.ts adapts the page-speed collection of umami-software/umami
(src/tracker/index.ts, v3.4.0), which carries this licence:
MIT License
Copyright (c) 2022 Umami Software, Inc. <hello@umami.is>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,39 @@
# @railyard/insights-web
Railyard Insights for web apps: page views (including client-side route
changes), custom events, identify, and five page-speed metrics for each page
view. No cookies and no storage; nothing is sent when Do Not Track is on or
when `consent()` returns false. No dependencies.
```ts
import { createInsightsWeb } from '@railyard/insights-web';
const insights = createInsightsWeb({
site: 'ry_site_...', // public, like an anon key
collector: 'https://collect.example',
});
insights.track('signup');
insights.identify(user.id, { plan: 'pro' });
```
## Page speed
Each page view reports, once, when the page is hidden or the route changes:
| Metric | What it is |
|---|---|
| LCP | when the largest text or image finished painting, up to the first click or key press |
| INP | how long the page took to respond to input (the slowest, skipping one per 50 inputs) |
| CLS | how much the layout moved (the worst burst of shifts) |
| FCP | when the first text or image painted |
| TTFB | when the server's first byte arrived |
The numbers follow the definitions Chrome uses for its own field reporting
(`computeVitals` in `src/metrics.ts`, tested against worked fixtures within
10%). Insights shows the 75th percentile per app and, for each deploy, how
each metric moved from the day before to the day after.
The one-line page tag (`/s.js`) sends page views and events only; use this
package to add page speed.
`NOTICE` lists the MIT-licensed source `src/metrics.ts` adapts.

View File

@ -0,0 +1,24 @@
{
"name": "@railyard/insights-web",
"version": "0.1.0",
"description": "Railyard Insights for web apps: page views, events, identify and the five page-speed metrics per page view, with no cookies and no storage. No dependencies.",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",
"exports": {
".": "./src/index.ts",
"./metrics": "./src/metrics.ts"
},
"files": [
"src",
"README.md",
"NOTICE"
],
"engines": {
"node": ">=22.18"
},
"scripts": {
"test": "node --test test/*.test.ts"
},
"license": "UNLICENSED"
}

View File

@ -0,0 +1,164 @@
/**
* Railyard Insights for web apps (Wave P PY3.3): page views (including
* client-side route changes), custom events, identify, and the five
* page-speed metrics of each page view, sent once when the page is hidden or
* the route changes. No cookies, no storage; nothing is sent when Do Not
* Track is on or consent is refused.
*
* import { createInsightsWeb } from '@railyard/insights-web';
* const insights = createInsightsWeb({ site: 'ry_site_...', collector: 'https://collect.example' });
* insights.track('signup');
* insights.identify(user.id, { plan: 'pro' });
*/
import { computeVitals, type PerfEntry, type Vitals } from './metrics.ts';
export { computeVitals, p75, type PerfEntry, type Vitals } from './metrics.ts';
export type Value = string | number | boolean;
interface ObserverLike {
observe(opts: Record<string, unknown>): void;
takeRecords?(): PerfEntry[];
}
/** The browser pieces used; tests pass their own. */
export interface WebEnv {
location: { pathname: string; search: string; hostname: string };
document: { referrer: string; title: string; visibilityState?: string; addEventListener(type: string, fn: () => void): void };
navigator: { doNotTrack?: string | null; language?: string; sendBeacon?(url: string, data: Blob | string): boolean };
screen?: { width: number; height: number };
history?: { pushState(...args: unknown[]): void; replaceState?(...args: unknown[]): void };
addEventListener(type: string, fn: () => void): void;
fetch?(url: string, init: Record<string, unknown>): Promise<unknown>;
PerformanceObserver?: {
new (cb: (list: { getEntries(): PerfEntry[] }) => void): ObserverLike;
supportedEntryTypes?: readonly string[];
};
performance?: { interactionCount?: number };
Blob?: new (parts: string[], opts: { type: string }) => Blob;
}
export interface InsightsWebOptions {
site: string;
collector: string;
consent?: () => boolean;
/** Send page views automatically (default true). */
pageViews?: boolean;
/** Measure page speed (default true). */
vitals?: boolean;
env?: WebEnv;
}
const SITE = /^ry_site_[A-Za-z0-9_-]{4,90}$/;
const USER_ID = /^[A-Za-z0-9@._:+=-]{1,50}$/;
const OBSERVED = ['navigation', 'paint', 'largest-contentful-paint', 'layout-shift', 'event', 'first-input'];
function clean(data?: Record<string, unknown>): Record<string, Value> | undefined {
if (!data) return undefined;
const out: Record<string, Value> = {};
for (const [k, v] of Object.entries(data)) {
if (Object.keys(out).length >= 20 || k.length > 50) continue;
if (typeof v === 'string') out[k] = v.slice(0, 500);
else if ((typeof v === 'number' && Number.isFinite(v)) || typeof v === 'boolean') out[k] = v;
}
return Object.keys(out).length ? out : undefined;
}
export function createInsightsWeb(options: InsightsWebOptions) {
if (!SITE.test(options.site ?? '')) throw new Error('createInsightsWeb needs the site key (ry_site_...)');
const base = options.collector.replace(/\/+$/, '');
if (!/^https?:\/\//.test(base)) throw new Error('createInsightsWeb needs the collector URL');
const env = options.env ?? (globalThis as unknown as WebEnv);
const endpoint = `${base}/api/send`;
const allowed = () => env.navigator.doNotTrack !== '1' && (options.consent ? options.consent() : true);
let user: string | null = null;
let entries: PerfEntry[] = [];
let vitalsSent = false;
let lastUrl: string | null = null;
const payload = (url = env.location.pathname + env.location.search) => ({
website: options.site,
url,
hostname: env.location.hostname,
referrer: env.document.referrer || null,
title: env.document.title,
language: env.navigator.language,
...(env.screen ? { screen: `${env.screen.width}x${env.screen.height}` } : {}),
...(user ? { user } : {}),
});
const post = (type: 'event' | 'identify' | 'performance', p: Record<string, unknown>) => {
if (!allowed()) return;
const body = JSON.stringify({ type, payload: p });
if (env.navigator.sendBeacon && env.Blob && env.navigator.sendBeacon(endpoint, new env.Blob([body], { type: 'text/plain' }))) return;
void env.fetch?.(endpoint, { method: 'POST', body, keepalive: true, headers: { 'content-type': 'text/plain' } })?.catch?.(() => {});
};
const sendVitals = () => {
if (vitalsSent || options.vitals === false || !env.PerformanceObserver) return;
const supported = env.PerformanceObserver.supportedEntryTypes ?? [];
const v: Vitals = computeVitals(entries, { interactionCount: env.performance?.interactionCount, layoutShiftSupported: supported.includes('layout-shift') });
vitalsSent = true;
// The metrics belong to the page view they were measured on, even after a route change.
if (Object.keys(v).length) post('performance', { ...payload(lastUrl ?? undefined), ...v });
};
const page = () => {
const url = env.location.pathname + env.location.search;
if (url === lastUrl) return;
if (lastUrl !== null) {
// A client-side route change: the previous page view's metrics go first.
sendVitals();
entries = [];
vitalsSent = false;
}
lastUrl = url;
if (options.pageViews !== false) post('event', payload());
};
if (options.vitals !== false && env.PerformanceObserver) {
const supported = env.PerformanceObserver.supportedEntryTypes ?? OBSERVED;
for (const type of OBSERVED.filter((t) => supported.includes(t))) {
try {
const obs = new env.PerformanceObserver((list) => {
entries = [...entries, ...list.getEntries()];
});
obs.observe(type === 'event' ? { type, buffered: true, durationThreshold: 40 } : { type, buffered: true });
} catch {
// Not supported in this browser.
}
}
env.document.addEventListener('visibilitychange', () => {
if (env.document.visibilityState === 'hidden') sendVitals();
});
env.addEventListener('pagehide', sendVitals);
}
if (env.history) {
const push = env.history.pushState.bind(env.history);
env.history.pushState = (...args: unknown[]) => {
push(...args);
page();
};
}
env.addEventListener('popstate', page);
page();
return {
track(name: string, data?: Record<string, unknown>) {
const d = clean(data);
post('event', { ...payload(), name: String(name).slice(0, 50), ...(d ? { data: d } : {}) });
},
identify(userId: string, traits?: Record<string, unknown>) {
if (!USER_ID.test(userId)) throw new Error('identify needs the app user id: 1 to 50 of A-Z a-z 0-9 @ . _ : + = -');
user = userId;
const d = clean(traits);
post('identify', { ...payload(), ...(d ? { data: d } : {}) });
},
reset() {
user = null;
},
/** Sends this page view's metrics now (normally done when the page is hidden). */
flushVitals: sendVitals,
};
}

View File

@ -0,0 +1,110 @@
/**
* The five page-speed metrics of one page view (Wave P PY3.3), computed from
* the browser's performance entries the way Chrome's own field reporting
* defines them. Adapted from MIT-licensed source (see NOTICE), with two
* changes so the numbers match Chrome's:
*
* - LCP stops at the first user input: a larger paint after a click, tap or
* key press is not the page's LCP.
* - INP picks its percentile from the page's total interaction count
* (`performance.interactionCount` when the browser gives it), not only
* from the slow interactions that were observed.
*
* Pure: entries in, numbers out, so it is tested without a browser.
*/
export interface PerfEntry {
entryType: string;
name: string;
startTime: number;
duration: number;
responseStart?: number;
activationStart?: number;
/** layout-shift */
value?: number;
hadRecentInput?: boolean;
/** event / first-input */
interactionId?: number;
}
export interface Vitals {
lcp?: number;
inp?: number;
cls?: number;
fcp?: number;
ttfb?: number;
}
const INPUT_EVENTS = new Set(['pointerdown', 'pointerup', 'mousedown', 'click', 'keydown', 'keyup', 'touchstart']);
const round = (v: number, places = 0) => {
const f = 10 ** places;
return Math.round(v * f) / f;
};
/**
* @param entries every entry observed for the page view (navigation, paint,
* largest-contentful-paint, layout-shift, event, first-input)
* @param opts.interactionCount the page's interaction count when known
* @param opts.layoutShiftSupported true where the browser reports layout
* shifts: a page with none has CLS 0, as Chrome reports it
*/
export function computeVitals(entries: readonly PerfEntry[], opts: { interactionCount?: number; layoutShiftSupported?: boolean } = {}): Vitals {
const interactionCount = opts.interactionCount;
const out: Vitals = {};
const nav = entries.find((e) => e.entryType === 'navigation');
const activationStart = nav?.activationStart ?? 0;
if (nav && typeof nav.responseStart === 'number') out.ttfb = round(Math.max(nav.responseStart - activationStart, 0));
const fcp = entries.find((e) => e.entryType === 'paint' && e.name === 'first-contentful-paint');
if (fcp) out.fcp = round(Math.max(fcp.startTime - activationStart, 0));
// LCP: the last candidate before the first input.
const inputs = entries.filter((e) => (e.entryType === 'event' || e.entryType === 'first-input') && INPUT_EVENTS.has(e.name));
const firstInput = inputs.length ? Math.min(...inputs.map((e) => e.startTime)) : Infinity;
const lcps = entries.filter((e) => e.entryType === 'largest-contentful-paint' && e.startTime < firstInput).sort((a, b) => a.startTime - b.startTime);
const lcp = lcps[lcps.length - 1];
if (lcp) out.lcp = round(Math.max(lcp.startTime - activationStart, 0));
// CLS: the worst session window (shifts under 1 s apart, a window at most 5 s long).
let windowValue = 0;
let windowFirst: PerfEntry | null = null;
let windowLast: PerfEntry | null = null;
let cls: number | undefined;
for (const e of entries.filter((x) => x.entryType === 'layout-shift' && !x.hadRecentInput).sort((a, b) => a.startTime - b.startTime)) {
if (windowFirst && windowLast && e.startTime - windowLast.startTime < 1000 && e.startTime - windowFirst.startTime < 5000) {
windowValue += e.value ?? 0;
windowLast = e;
} else {
windowValue = e.value ?? 0;
windowFirst = e;
windowLast = e;
}
cls = Math.max(cls ?? 0, windowValue);
}
if (cls !== undefined) out.cls = round(cls, 4);
else if (opts.layoutShiftSupported) out.cls = 0;
// INP: the longest duration per interaction, then one skipped per 50 interactions.
const byInteraction = new Map<number, number>();
for (const e of entries) {
if ((e.entryType === 'event' || e.entryType === 'first-input') && e.interactionId) {
byInteraction.set(e.interactionId, Math.max(byInteraction.get(e.interactionId) ?? 0, e.duration));
}
}
const durations = [...byInteraction.values()].sort((a, b) => b - a);
if (durations.length) {
const count = Math.max(interactionCount ?? 0, durations.length);
out.inp = round(durations[Math.min(Math.floor(count / 50), durations.length - 1)] as number);
}
return out;
}
/** The 75th percentile (linear, as the Insights p75 is computed). */
export function p75(values: readonly number[]): number | null {
if (!values.length) return null;
const s = [...values].sort((a, b) => a - b);
const pos = 0.75 * (s.length - 1);
const lo = Math.floor(pos);
return (s[lo] as number) + ((s[Math.min(lo + 1, s.length - 1)] as number) - (s[lo] as number)) * (pos - lo);
}

View File

@ -0,0 +1,111 @@
// @railyard/insights-web (Wave P PY3.3) in a stand-in browser: page views,
// route changes, identify, and one performance event per page view whose
// payload passes the edge collector's own parser.
// node --test test/*.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createInsightsWeb, type PerfEntry, type WebEnv } from '../src/index.ts';
import { parseOne } from '../../../apps/insights-edge/src/payload.mjs';
function browser(opts: { dnt?: string; supported?: string[] } = {}) {
const sent: { type: string; payload: Record<string, unknown> }[] = [];
const listeners: Record<string, (() => void)[]> = {};
const observers: { type: string; cb: (l: { getEntries(): PerfEntry[] }) => void }[] = [];
const on = (t: string, f: () => void) => void (listeners[t] = [...(listeners[t] ?? []), f]);
const env: WebEnv = {
location: { pathname: '/', search: '', hostname: 'shop.example' },
document: { referrer: '', title: 'Shop', visibilityState: 'visible', addEventListener: on },
navigator: {
doNotTrack: opts.dnt ?? '0',
language: 'en-US',
sendBeacon: (_url, data) => {
const p = JSON.parse((data as unknown as { text: string }).text);
const parsed = parseOne(p);
assert.ok(!('error' in parsed), JSON.stringify(parsed));
sent.push(p);
return true;
},
},
screen: { width: 1440, height: 900 },
history: { pushState() {} },
addEventListener: on,
PerformanceObserver: Object.assign(
class {
cb: (l: { getEntries(): PerfEntry[] }) => void;
constructor(cb: (l: { getEntries(): PerfEntry[] }) => void) {
this.cb = cb;
}
observe(o: Record<string, unknown>) {
observers.push({ type: String(o.type), cb: this.cb });
}
},
{ supportedEntryTypes: opts.supported ?? ['navigation', 'paint', 'largest-contentful-paint', 'layout-shift', 'event', 'first-input'] },
),
performance: { interactionCount: 3 },
Blob: class {
text: string;
constructor(parts: string[]) {
this.text = parts.join('');
}
} as unknown as WebEnv['Blob'],
};
const emit = (entries: PerfEntry[]) => {
for (const e of entries) for (const o of observers.filter((x) => x.type === e.entryType)) o.cb({ getEntries: () => [e] });
};
const fire = (t: string) => (listeners[t] ?? []).forEach((f) => f());
return { env, sent, emit, fire };
}
test('a page view, then the page speed of that view once when the page is hidden', () => {
const b = browser();
createInsightsWeb({ site: 'ry_site_abcdefgh1234', collector: 'https://collect.test/', env: b.env });
b.emit([
{ entryType: 'navigation', name: '', startTime: 0, duration: 900, responseStart: 180 },
{ entryType: 'paint', name: 'first-contentful-paint', startTime: 600, duration: 0 },
{ entryType: 'largest-contentful-paint', name: '', startTime: 1400, duration: 0 },
{ entryType: 'layout-shift', name: '', startTime: 800, duration: 0, value: 0.04 },
{ entryType: 'event', name: 'click', startTime: 3000, duration: 72, interactionId: 5 },
]);
b.env.document.visibilityState = 'hidden';
b.fire('visibilitychange');
b.fire('pagehide');
assert.deepEqual(b.sent.map((s) => s.type), ['event', 'performance']);
const perf = b.sent[1]!.payload;
assert.deepEqual([perf.ttfb, perf.fcp, perf.lcp, perf.cls, perf.inp], [180, 600, 1400, 0.04, 72]);
assert.equal(perf.url, '/');
});
test('a client-side route change sends the previous view\'s metrics, then a new page view; identify tags later events', () => {
const b = browser();
const i = createInsightsWeb({ site: 'ry_site_abcdefgh1234', collector: 'https://collect.test', env: b.env });
b.emit([{ entryType: 'layout-shift', name: '', startTime: 100, duration: 0, value: 0.2 }]);
i.identify('user_42', { plan: 'pro' });
b.env.location.pathname = '/pricing';
b.env.history!.pushState({}, '', '/pricing');
i.track('checkout_started', { plan: 'pro' });
assert.deepEqual(b.sent.map((s) => [s.type, s.payload.url, s.payload.user ?? null]), [
['event', '/', null],
['identify', '/', 'user_42'],
['performance', '/', 'user_42'],
['event', '/pricing', 'user_42'],
['event', '/pricing', 'user_42'],
]);
assert.equal(b.sent[2]!.payload.cls, 0.2);
assert.throws(() => i.identify('bad id'), /identify needs/);
});
test('Do Not Track: nothing at all is sent; no layout-shift support: no CLS is made up', () => {
const dnt = browser({ dnt: '1' });
const i = createInsightsWeb({ site: 'ry_site_abcdefgh1234', collector: 'https://collect.test', env: dnt.env });
i.track('x');
dnt.fire('pagehide');
assert.equal(dnt.sent.length, 0);
const safari = browser({ supported: ['navigation', 'paint'] });
createInsightsWeb({ site: 'ry_site_abcdefgh1234', collector: 'https://collect.test', env: safari.env });
safari.emit([{ entryType: 'navigation', name: '', startTime: 0, duration: 1, responseStart: 90 }]);
safari.fire('pagehide');
const perf = safari.sent.find((s) => s.type === 'performance')!.payload;
assert.equal(perf.ttfb, 90);
assert.equal(perf.cls, undefined);
});

View File

@ -0,0 +1,30 @@
// The web package docs and messages (PY3.3) pass the vendored copy denylist.
// Page-speed copy is allowed with RAILYARD_REPLAY_LIVE on (rule
// railyard-slot-replay); the views that show it check that flag first
// (apps/console/lib/vitals-view.test.ts), so the docs are linted as live.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { errors, formatFindings, lintUnits, markdownUnits } from '../../../policy/copy-lint.mjs';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
const LIVE = { RAILYARD_REPLAY_LIVE: '1' };
test('README and messages pass the copy lint; the upstream name appears only in NOTICE', () => {
const units = [
...markdownUnits(readFileSync(join(ROOT, 'README.md'), 'utf8'), { where: 'README.md' }),
...['src/index.ts', 'src/metrics.ts'].flatMap((f) =>
[...readFileSync(join(ROOT, f), 'utf8').replace(/^\s*(\/\/|\*).*$/gm, '').matchAll(/["'`]([^"'`\n]{12,})["'`]/g)]
.map((m) => m[1] as string)
.filter((s) => !/^[\^[/.]|https?:|\$\{/.test(s))
.map((text) => ({ text, surface: 'docs', where: f })),
),
];
const found = errors(lintUnits(units, { flags: LIVE }));
assert.deepEqual(found, [], formatFindings(found));
for (const f of ['README.md', 'src/index.ts', 'src/metrics.ts', 'package.json']) assert.doesNotMatch(readFileSync(join(ROOT, f), 'utf8'), /umami/i, f);
assert.match(readFileSync(join(ROOT, 'NOTICE'), 'utf8'), /MIT License/);
});

View File

@ -0,0 +1,355 @@
{
"about": "Page loads with their performance entries and the value Chrome's field reporting gives for each metric, worked out by hand from the published metric definitions (web.dev: LCP stops at the first input; CLS is the worst session window, shifts under 1 s apart and a window at most 5 s, excluding shifts after input; INP is the longest interaction after skipping one per 50 interactions; FCP, LCP and TTFB count from activation). The test allows 10%.",
"loads": [
{
"name": "plain load",
"entries": [
{
"entryType": "navigation",
"name": "https://shop.example/",
"startTime": 0,
"duration": 2000,
"responseStart": 320,
"activationStart": 0
},
{
"entryType": "paint",
"name": "first-contentful-paint",
"startTime": 900,
"duration": 0
},
{
"entryType": "largest-contentful-paint",
"name": "",
"startTime": 900,
"duration": 0
},
{
"entryType": "largest-contentful-paint",
"name": "",
"startTime": 1800,
"duration": 0
},
{
"entryType": "layout-shift",
"name": "",
"startTime": 1000,
"duration": 0,
"value": 0.02,
"hadRecentInput": false
},
{
"entryType": "layout-shift",
"name": "",
"startTime": 1500,
"duration": 0,
"value": 0.03,
"hadRecentInput": false
},
{
"entryType": "event",
"name": "click",
"startTime": 3000,
"duration": 64,
"interactionId": 1
},
{
"entryType": "event",
"name": "keydown",
"startTime": 4000,
"duration": 120,
"interactionId": 2
}
],
"chrome": {
"ttfb": 320,
"fcp": 900,
"lcp": 1800,
"cls": 0.05,
"inp": 120
}
},
{
"name": "a larger paint after a click is not the LCP",
"entries": [
{
"entryType": "navigation",
"name": "https://shop.example/",
"startTime": 0,
"duration": 2000,
"responseStart": 250,
"activationStart": 0
},
{
"entryType": "paint",
"name": "first-contentful-paint",
"startTime": 1000,
"duration": 0
},
{
"entryType": "largest-contentful-paint",
"name": "",
"startTime": 1200,
"duration": 0
},
{
"entryType": "event",
"name": "click",
"startTime": 3000,
"duration": 48,
"interactionId": 1
},
{
"entryType": "largest-contentful-paint",
"name": "",
"startTime": 5200,
"duration": 0
}
],
"chrome": {
"ttfb": 250,
"fcp": 1000,
"lcp": 1200,
"cls": 0,
"inp": 48
}
},
{
"name": "two layout-shift windows; a shift right after input does not count",
"entries": [
{
"entryType": "navigation",
"name": "https://shop.example/",
"startTime": 0,
"duration": 2000,
"responseStart": 400,
"activationStart": 0
},
{
"entryType": "paint",
"name": "first-contentful-paint",
"startTime": 700,
"duration": 0
},
{
"entryType": "largest-contentful-paint",
"name": "",
"startTime": 700,
"duration": 0
},
{
"entryType": "layout-shift",
"name": "",
"startTime": 500,
"duration": 0,
"value": 0.1,
"hadRecentInput": false
},
{
"entryType": "layout-shift",
"name": "",
"startTime": 900,
"duration": 0,
"value": 0.05,
"hadRecentInput": false
},
{
"entryType": "layout-shift",
"name": "",
"startTime": 2500,
"duration": 0,
"value": 0.3,
"hadRecentInput": true
},
{
"entryType": "layout-shift",
"name": "",
"startTime": 4000,
"duration": 0,
"value": 0.12,
"hadRecentInput": false
},
{
"entryType": "layout-shift",
"name": "",
"startTime": 4800,
"duration": 0,
"value": 0.11,
"hadRecentInput": false
},
{
"entryType": "layout-shift",
"name": "",
"startTime": 5600,
"duration": 0,
"value": 0.02,
"hadRecentInput": false
}
],
"chrome": {
"ttfb": 400,
"fcp": 700,
"lcp": 700,
"cls": 0.25
}
},
{
"name": "prerendered page: times count from activation",
"entries": [
{
"entryType": "navigation",
"name": "https://shop.example/",
"startTime": 0,
"duration": 2000,
"responseStart": 300,
"activationStart": 400
},
{
"entryType": "paint",
"name": "first-contentful-paint",
"startTime": 1100,
"duration": 0
},
{
"entryType": "largest-contentful-paint",
"name": "",
"startTime": 1500,
"duration": 0
}
],
"chrome": {
"ttfb": 0,
"fcp": 700,
"lcp": 1100,
"cls": 0
}
},
{
"name": "120 interactions: INP skips the two slowest",
"interactionCount": 120,
"entries": [
{
"entryType": "navigation",
"name": "https://shop.example/",
"startTime": 0,
"duration": 2000,
"responseStart": 200,
"activationStart": 0
},
{
"entryType": "paint",
"name": "first-contentful-paint",
"startTime": 600,
"duration": 0
},
{
"entryType": "largest-contentful-paint",
"name": "",
"startTime": 600,
"duration": 0
},
{
"entryType": "event",
"name": "click",
"startTime": 1000,
"duration": 400,
"interactionId": 1
},
{
"entryType": "event",
"name": "click",
"startTime": 2000,
"duration": 350,
"interactionId": 2
},
{
"entryType": "event",
"name": "keydown",
"startTime": 3000,
"duration": 300,
"interactionId": 3
},
{
"entryType": "event",
"name": "click",
"startTime": 4000,
"duration": 280,
"interactionId": 4
},
{
"entryType": "event",
"name": "pointerdown",
"startTime": 5000,
"duration": 200,
"interactionId": 5
}
],
"chrome": {
"ttfb": 200,
"fcp": 600,
"lcp": 600,
"cls": 0,
"inp": 300
}
},
{
"name": "one interaction, several events: its longest one counts",
"entries": [
{
"entryType": "navigation",
"name": "https://shop.example/",
"startTime": 0,
"duration": 2000,
"responseStart": 500,
"activationStart": 0
},
{
"entryType": "paint",
"name": "first-contentful-paint",
"startTime": 1300,
"duration": 0
},
{
"entryType": "largest-contentful-paint",
"name": "",
"startTime": 1000,
"duration": 0
},
{
"entryType": "event",
"name": "keydown",
"startTime": 2000,
"duration": 80,
"interactionId": 7
},
{
"entryType": "event",
"name": "keyup",
"startTime": 2100,
"duration": 140,
"interactionId": 7
},
{
"entryType": "event",
"name": "pointerdown",
"startTime": 3000,
"duration": 60,
"interactionId": 8
},
{
"entryType": "largest-contentful-paint",
"name": "",
"startTime": 2500,
"duration": 0
}
],
"chrome": {
"ttfb": 500,
"fcp": 1300,
"lcp": 1000,
"cls": 0,
"inp": 140
}
}
]
}

View File

@ -0,0 +1,50 @@
// Page-speed metrics (Wave P PY3.3): the numbers for each fixture page load
// are within 10% of what Chrome's field reporting gives for the same entries,
// and so is the 75th percentile over all of them (the figure the views show).
// node --test test/*.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { computeVitals, p75, type PerfEntry, type Vitals } from '../src/metrics.ts';
const HERE = dirname(fileURLToPath(import.meta.url));
const fixture = JSON.parse(readFileSync(join(HERE, 'fixtures/chrome-page-loads.json'), 'utf8')) as {
loads: { name: string; entries: PerfEntry[]; chrome: Vitals; interactionCount?: number }[];
};
const METRICS = ['lcp', 'inp', 'cls', 'fcp', 'ttfb'] as const;
const within10 = (got: number | undefined, want: number) => got !== undefined && (want === 0 ? got === 0 : Math.abs(got - want) / want <= 0.1);
for (const load of fixture.loads) {
test(`within 10% of Chrome: ${load.name}`, () => {
const got = computeVitals(load.entries, { interactionCount: load.interactionCount, layoutShiftSupported: true });
for (const m of METRICS) {
const want = load.chrome[m];
if (want === undefined) assert.equal(got[m], undefined, `${m} should be absent`);
else assert.ok(within10(got[m], want), `${m}: got ${got[m]}, Chrome ${want}`);
}
});
}
test('the p75 over all loads is within 10% of the p75 of the Chrome values', () => {
const ours = fixture.loads.map((l) => computeVitals(l.entries, { interactionCount: l.interactionCount, layoutShiftSupported: true }));
for (const m of METRICS) {
const chrome = fixture.loads.map((l) => l.chrome[m]).filter((v): v is number => v !== undefined);
const mine = ours.map((v) => v[m]).filter((v): v is number => v !== undefined);
assert.equal(mine.length, chrome.length, m);
assert.ok(within10(p75(mine) ?? undefined, p75(chrome) as number), `${m}: p75 ${p75(mine)} vs ${p75(chrome)}`);
}
});
test('without the two corrections the LCP and INP cases would be far off (the fixture is not trivial)', () => {
const lcpCase = fixture.loads[1]!;
const lastCandidate = Math.max(...lcpCase.entries.filter((e) => e.entryType === 'largest-contentful-paint').map((e) => e.startTime));
assert.ok(!within10(lastCandidate, lcpCase.chrome.lcp as number), 'the paint after the click is 4x the real LCP');
const inpCase = fixture.loads[4]!;
const slowest = Math.max(...inpCase.entries.filter((e) => e.interactionId).map((e) => e.duration));
assert.ok(!within10(slowest, inpCase.chrome.inp as number));
// A browser without layout-shift reporting gives no CLS rather than a made-up 0.
assert.equal(computeVitals(fixture.loads[3]!.entries).cls, undefined);
});