Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

ci(repo): track bundle size and performance of master builds (#12469)

David Luzar4eb1e648aa78
diff --git a/.github/workflows/stats.yml b/.github/workflows/stats.yml
new file mode 100644
index 0000000000..9b79a13a1b
--- /dev/null
+++ b/.github/workflows/stats.yml
@@ -0,0 +1,65 @@
+name: Stats
+
+# Posts every master commit's production build (bundle size) and, once
+# staging.excalidraw.com serves the commit, its page-load measurements to the
+# Excalidraw+ admin's Bundle size and Performance pages (scripts/stats/).
+# OSS_STATS_TOKEN lives in the `stats` environment, which only master can use.
+
+on:
+ push:
+ branches: master
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ bundle:
+ name: Bundle size
+ runs-on: ubuntu-latest
+ environment: stats
+ steps:
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
+ - name: Setup Node.js
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: 20.x
+ - name: Install
+ run: yarn install --frozen-lockfile
+ - name: Build with bundle stats
+ run: yarn stats:bundle
+ env:
+ VITE_APP_GIT_SHA: ${{ github.sha }}
+ VITE_APP_ENABLE_ESLINT: "false"
+ - name: Post to the Excalidraw+ admin
+ run: node scripts/stats/post.mjs bundle excalidraw-app/build/bundle-stats.json
+ env:
+ OSS_STATS_TOKEN: ${{ secrets.OSS_STATS_TOKEN }}
+
+ perf:
+ name: Performance
+ runs-on: ubuntu-latest
+ environment: stats
+ # staging serves only the latest commit, so a newer push takes over
+ concurrency:
+ group: stats-perf
+ cancel-in-progress: true
+ timeout-minutes: 40
+ steps:
+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
+ - name: Setup Node.js
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: 20.x
+ - name: Install
+ run: |
+ yarn install --frozen-lockfile
+ npx playwright install --with-deps chromium
+ - name: Measure staging once it serves this commit
+ run: yarn stats:perf --wait-for ${{ github.sha }} --out perf.json
+ - name: Post to the Excalidraw+ admin
+ # not measured when staging didn't serve the commit in time
+ if: hashFiles('perf.json') != ''
+ run: node scripts/stats/post.mjs perf perf.json
+ env:
+ OSS_STATS_TOKEN: ${{ secrets.OSS_STATS_TOKEN }}
diff --git a/excalidraw-app/index.tsx b/excalidraw-app/index.tsx
index 98c902e36e..b7db2ca207 100644
--- a/excalidraw-app/index.tsx
+++ b/excalidraw-app/index.tsx
@@ -6,6 +6,9 @@ import "../excalidraw-app/sentry";
import ExcalidrawApp from "./App";
+// the entry's JavaScript and CSS loaded and ran (`scripts/stats/perf.mjs`)
+performance.mark("excalidraw:app-start");
+
window.__EXCALIDRAW_SHA__ = import.meta.env.VITE_APP_GIT_SHA;
const rootElement = document.getElementById("root")!;
const root = createRoot(rootElement);
diff --git a/package.json b/package.json
index c91ee030c3..32d974ff38 100644
--- a/package.json
+++ b/package.json
@@ -31,6 +31,7 @@
"jsdom": "22.1.0",
"lint-staged": "12.3.7",
"pepjs": "0.5.3",
+ "playwright": "1.58.2",
"prettier": "2.6.2",
"rewire": "6.0.0",
"rimraf": "^5.0.0",
@@ -60,6 +61,9 @@
"build:laser-pointer": "yarn --cwd ./packages/laser-pointer build:esm",
"build:packages": "yarn build:common && yarn build:fractional-indexing && yarn build:laser-pointer && yarn build:math && yarn build:element && yarn build:excalidraw",
"build:version": "yarn --cwd ./excalidraw-app build:version",
+ "stats:bundle": "yarn --cwd ./excalidraw-app cross-env VITE_APP_ENABLE_TRACKING=true vite build --config ../scripts/stats/vite.config.mts",
+ "stats:perf": "node ./scripts/stats/perf.mjs",
+ "stats:compare": "node ./scripts/stats/perf.mjs --compare",
"build": "yarn --cwd ./excalidraw-app build",
"build:preview": "yarn --cwd ./excalidraw-app build:preview",
"start": "yarn --cwd ./excalidraw-app start",
diff --git a/scripts/stats/bundle-stats-plugin.mts b/scripts/stats/bundle-stats-plugin.mts
new file mode 100644
index 0000000000..cc7bb341e5
--- /dev/null
+++ b/scripts/stats/bundle-stats-plugin.mts
@@ -0,0 +1,196 @@
+import fs from "node:fs";
+import path from "node:path";
+import zlib from "node:zlib";
+
+import type { Plugin, Rollup } from "vite";
+
+/**
+ * One file of the build, as `POST /api/oss/bundle-runs` stores it (see
+ * `scripts/stats/post.mjs`).
+ */
+type BundleStatsAsset = {
+ /** the same from build to build: a chunk's entry module or name, an asset's source file */
+ name: string;
+ /** the emitted file, e.g. `assets/index-CNToBGx8.js` */
+ file: string;
+ type: "js" | "css" | "html" | "font" | "other";
+ /** loaded with the page: the HTML, the entry chunk, its static imports and their CSS */
+ initial: boolean;
+ bytes: number;
+ gzipBytes: number;
+ brotliBytes: number;
+ /** a chunk's source packages → their bytes in it before minification */
+ packages: Record<string, number>;
+};
+
+const BUNDLE_STATS_FILE = "bundle-stats.json";
+
+const REPO_ROOT = path.resolve(__dirname, "../..");
+
+const NODE_MODULES = "/node_modules/";
+
+const getType = (fileName: string): BundleStatsAsset["type"] =>
+ fileName.endsWith(".js")
+ ? "js"
+ : fileName.endsWith(".css")
+ ? "css"
+ : fileName.endsWith(".html")
+ ? "html"
+ : /\.(woff2?|ttf|otf)$/.test(fileName)
+ ? "font"
+ : "other";
+
+/** A module id without Rollup's virtual-module prefix and query. */
+const cleanId = (id: string) => id.replace(/^\0/, "").split("?")[0];
+
+/** A module's path from the repo root, or from `node_modules` for dependencies. */
+const toRepoPath = (id: string) => {
+ const nodeModules = id.lastIndexOf(NODE_MODULES);
+ return nodeModules >= 0
+ ? id.slice(nodeModules + 1)
+ : path.relative(REPO_ROOT, id).split(path.sep).join("/");
+};
+
+/**
+ * The package a module comes from: its npm package, `@excalidraw/<name>` for
+ * the monorepo's packages, the app, or the bundler's own helpers.
+ */
+const getPackage = (moduleId: string) => {
+ const id = cleanId(moduleId);
+ const nodeModules = id.lastIndexOf(NODE_MODULES);
+ if (nodeModules >= 0) {
+ const [scope, name] = id
+ .slice(nodeModules + NODE_MODULES.length)
+ .split("/");
+ return scope.startsWith("@") ? `${scope}/${name}` : scope;
+ }
+ if (!path.isAbsolute(id)) {
+ // e.g. vite/preload-helper, commonjsHelpers
+ return "(bundler)";
+ }
+ const [dir, name] = toRepoPath(id).split("/");
+ return dir === "packages" ? `@excalidraw/${name}` : dir;
+};
+
+const getSizes = (source: string | Uint8Array) => {
+ const buffer = Buffer.from(source);
+ return {
+ bytes: buffer.length,
+ gzipBytes: zlib.gzipSync(buffer, { level: 9 }).length,
+ brotliBytes: zlib.brotliCompressSync(buffer, {
+ params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 11 },
+ }).length,
+ };
+};
+
+/** The chunks loaded with the page: the entries and what they import statically, and their CSS. */
+const getInitialFiles = (chunks: Rollup.OutputChunk[]) => {
+ const chunksByFile = new Map(chunks.map((chunk) => [chunk.fileName, chunk]));
+ const initial = new Set<string>();
+ const stack = chunks.filter((chunk) => chunk.isEntry);
+
+ while (stack.length) {
+ const chunk = stack.pop()!;
+ if (initial.has(chunk.fileName)) {
+ continue;
+ }
+ initial.add(chunk.fileName);
+ chunk.viteMetadata?.importedCss.forEach((css) => initial.add(css));
+ for (const fileName of chunk.imports) {
+ const imported = chunksByFile.get(fileName);
+ if (imported) {
+ stack.push(imported);
+ }
+ }
+ }
+
+ return initial;
+};
+
+/**
+ * Writes `bundle-stats.json` next to the build: every emitted file (source
+ * maps aside) with its minified, gzip and Brotli (maximum compression) sizes,
+ * whether the page loads it initially and, for chunks, the bytes per source
+ * package. Master CI (`.github/workflows/stats.yml`) posts it to the
+ * Excalidraw+ admin (`scripts/stats/post.mjs`); applied by
+ * `scripts/stats/vite.config.mts`, not by the app's own builds.
+ */
+export const bundleStatsPlugin = (): Plugin => {
+ // the assets' source files are relative to it
+ let root = process.cwd();
+
+ return {
+ name: "excalidraw-bundle-stats",
+ apply: "build",
+ enforce: "post",
+ configResolved(config) {
+ root = config.root;
+ },
+ writeBundle(options, bundle) {
+ const outputs = Object.values(bundle).filter(
+ (output) => !output.fileName.endsWith(".map"),
+ );
+ const chunks = outputs.filter(
+ (output): output is Rollup.OutputChunk => output.type === "chunk",
+ );
+ const initialFiles = getInitialFiles(chunks);
+ const usedNames = new Map<string, number>();
+
+ // unique within the build: Rollup may give shared chunks the same name
+ const uniqueName = (name: string) => {
+ const count = (usedNames.get(name) ?? 0) + 1;
+ usedNames.set(name, count);
+ return count > 1 ? `${name} (${count})` : name;
+ };
+
+ const assets = outputs.map((output): BundleStatsAsset => {
+ const type = getType(output.fileName);
+
+ if (output.type === "chunk") {
+ const packages: Record<string, number> = {};
+ for (const [id, { renderedLength }] of Object.entries(
+ output.modules,
+ )) {
+ if (renderedLength) {
+ const name = getPackage(id);
+ packages[name] = (packages[name] ?? 0) + renderedLength;
+ }
+ }
+
+ return {
+ name: uniqueName(
+ output.facadeModuleId
+ ? toRepoPath(cleanId(output.facadeModuleId))
+ : `${output.name}.js`,
+ ),
+ file: output.fileName,
+ type,
+ initial: initialFiles.has(output.fileName),
+ ...getSizes(output.code),
+ packages,
+ };
+ }
+
+ const source = output.originalFileNames?.[0];
+ return {
+ name: uniqueName(
+ source
+ ? toRepoPath(path.resolve(root, source))
+ : // emitted without a source (the HTML, CSS of chunks): the file without its hash
+ output.fileName.replace(/-[\w-]{8}(\.[^./]+)$/, "$1"),
+ ),
+ file: output.fileName,
+ type,
+ initial: type === "html" || initialFiles.has(output.fileName),
+ ...getSizes(output.source),
+ packages: {},
+ };
+ });
+
+ fs.writeFileSync(
+ path.join(options.dir!, BUNDLE_STATS_FILE),
+ JSON.stringify({ assets }, null, 2),
+ );
+ },
+ };
+};
diff --git a/scripts/stats/perf.mjs b/scripts/stats/perf.mjs
new file mode 100644
index 0000000000..eb63f703f6
--- /dev/null
+++ b/scripts/stats/perf.mjs
@@ -0,0 +1,1081 @@
+#!/usr/bin/env node
+
+/**
+ * Measures excalidraw.com in a real browser (Playwright, Chromium) for the
+ * Excalidraw+ admin's Performance page — page loads, and panning and zooming
+ * a large scene: every scenario `--iterations` times, each in a fresh browser
+ * context (cold HTTP cache) on a throttled fast-desktop connection — the
+ * conditions of Excalidraw+'s own runs, so the apps' numbers compare. Master
+ * CI runs it once staging serves the merged commit (`--wait-for`), and
+ * `post.mjs` stores the result.
+ *
+ * `--compare` (`yarn stats:compare`) instead measures two builds on this
+ * machine, alternating them, and prints a table of their differences (a CSV
+ * with `--out`): this checkout's production build — built and served locally
+ * — or `--url`, against `--base` (staging by default). The machine's speed
+ * shows in every timing, so only builds measured side by side compare.
+ *
+ * node scripts/stats/perf.mjs --url http://localhost:3000 --iterations 3
+ * node scripts/stats/perf.mjs --scenario oss-pan-zoom --iterations 1
+ * node scripts/stats/perf.mjs --wait-for <sha> --out perf.json
+ * yarn stats:compare [--iterations 10] [--out diff.csv]
+ * yarn stats:compare --url http://localhost:3000 --base https://excalidraw.com
+ */
+
+import { execFileSync, spawn } from "node:child_process";
+import fs from "node:fs";
+import net from "node:net";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { parseArgs } from "node:util";
+import { setTimeout as sleep } from "node:timers/promises";
+
+import { chromium } from "playwright";
+
+const STAGING_URL = "https://staging.excalidraw.com";
+
+const { values: args } = parseArgs({
+ options: {
+ // the app to measure — staging by default; with --compare, this checkout's build
+ url: { type: "string" },
+ iterations: { type: "string", default: "5" },
+ // the JSON file to write the run to (printed when left out); with --compare, a CSV
+ out: { type: "string" },
+ // compare --url (this checkout's build by default) with --base, measured alternately
+ compare: { type: "boolean", default: false },
+ base: { type: "string", default: STAGING_URL },
+ // a commit: wait until the url serves it (its version.json) before measuring
+ "wait-for": { type: "string" },
+ // only these scenarios (comma-separated ids)
+ scenario: { type: "string" },
+ },
+});
+
+const withoutSlash = (url) => url.replace(/\/$/, "");
+
+const APP_URL = withoutSlash(args.url ?? STAGING_URL);
+/**
+ * Loads per scenario (per build with --compare). Consecutive loads differ a
+ * little (one browser runs them all), so --compare alternates which build
+ * loads first and needs an even count for both to get the same positions.
+ */
+const ITERATIONS = args.compare
+ ? Math.ceil(Number(args.iterations) / 2) * 2
+ : Number(args.iterations);
+
+const REPO_ROOT = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ "../..",
+);
+const APP_DIR = path.join(REPO_ROOT, "excalidraw-app");
+const VITE = path.join(REPO_ROOT, "node_modules/vite/bin/vite.js");
+
+/** Same as Excalidraw+'s runs (`PERF_ENVIRONMENT` there), close to Lighthouse's desktop preset. */
+const PERF_ENVIRONMENT = {
+ viewport: { width: 1440, height: 900 },
+ network: { latencyMs: 40, downloadKbps: 10_240, uploadKbps: 10_240 },
+};
+
+const LOAD_TIMEOUT_MS = 60_000;
+
+/** Paints right after ready (the LCP is often one) are reported asynchronously. */
+const PAINT_SETTLE_MS = 1_000;
+
+/** Between loads, so the browser's work in the background after one (closing it, a renderer for the next) is done. */
+const BETWEEN_LOADS_MS = 1_000;
+
+const WAIT_FOR_DEPLOY_MS = 20 * 60_000;
+const WAIT_FOR_DEPLOY_INTERVAL_MS = 30_000;
+
+/** Analytics and error reporting stay out of the measured loads (and out of the stats). */
+const BLOCKED_URLS = [
+ "https://*.simpleanalyticscdn.com/**",
+ "https://*.sentry.io/**",
+ "https://sentry.io/**",
+];
+
+/** The app marks when its entry module runs (`excalidraw-app/index.tsx`), ending the "HTML + JS" phase. */
+const APP_START_MARK = "excalidraw:app-start";
+
+/** The app's local storage keys (`STORAGE_KEYS` in `excalidraw-app/app_constants.ts`). */
+const STORAGE_KEYS = { elements: "excalidraw", appState: "excalidraw-state" };
+
+const LARGE_SCENE_GRID = {
+ columns: 50,
+ rows: 40,
+ cellWidth: 140,
+ cellHeight: 110,
+};
+
+/**
+ * The same 2,000 elements every run (seeded): shapes, text, arrows, lines and
+ * freedraw strokes on a grid, zoomed out so all of them are drawn.
+ */
+function createLargeScene() {
+ // mulberry32
+ let seed = 42;
+ const random = () => {
+ seed = (seed + 0x6d2b79f5) | 0;
+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+ const pick = (list) => list[Math.floor(random() * list.length)];
+ const words = [
+ "Idea",
+ "Draft",
+ "Review",
+ "Ship it",
+ "Backlog",
+ "Q3 plan",
+ "API",
+ "Users",
+ ];
+ const { columns, rows, cellWidth, cellHeight } = LARGE_SCENE_GRID;
+ const elements = [];
+
+ for (let row = 0; row < rows; row++) {
+ for (let column = 0; column < columns; column++) {
+ const base = {
+ id: `perf-${elements.length}`,
+ x: column * cellWidth,
+ y: row * cellHeight,
+ width: 100,
+ height: 70,
+ angle: 0,
+ strokeColor: pick([
+ "#1e1e1e",
+ "#e03131",
+ "#2f9e44",
+ "#1971c2",
+ "#f08c00",
+ ]),
+ backgroundColor: pick([
+ "transparent",
+ "#ffc9c9",
+ "#b2f2bb",
+ "#a5d8ff",
+ "#ffec99",
+ ]),
+ fillStyle: pick(["solid", "hachure", "cross-hatch"]),
+ strokeWidth: 2,
+ strokeStyle: "solid",
+ roughness: 1,
+ opacity: 100,
+ groupIds: [],
+ frameId: null,
+ roundness: null,
+ seed: Math.floor(random() * 2 ** 31),
+ version: 1,
+ versionNonce: 0,
+ isDeleted: false,
+ boundElements: null,
+ updated: 1,
+ link: null,
+ locked: false,
+ };
+ const kind = random();
+
+ if (kind < 0.35) {
+ elements.push({ ...base, type: "rectangle", roundness: { type: 3 } });
+ } else if (kind < 0.5) {
+ elements.push({ ...base, type: "ellipse" });
+ } else if (kind < 0.6) {
+ elements.push({ ...base, type: "diamond" });
+ } else if (kind < 0.75) {
+ const text = pick(words);
+ elements.push({
+ ...base,
+ type: "text",
+ backgroundColor: "transparent",
+ width: text.length * 11,
+ height: 25,
+ text,
+ originalText: text,
+ fontSize: 20,
+ fontFamily: 5,
+ textAlign: "left",
+ verticalAlign: "top",
+ containerId: null,
+ autoResize: true,
+ lineHeight: 1.25,
+ });
+ } else if (kind < 0.9) {
+ const isArrow = kind < 0.85;
+ elements.push({
+ ...base,
+ type: isArrow ? "arrow" : "line",
+ backgroundColor: "transparent",
+ points: [
+ [0, 0],
+ [50, random() * 70 - 35],
+ [100, 70],
+ ],
+ lastCommittedPoint: null,
+ startBinding: null,
+ endBinding: null,
+ startArrowhead: null,
+ endArrowhead: isArrow ? "arrow" : null,
+ elbowed: false,
+ });
+ } else {
+ const points = Array.from({ length: 40 }, (_, index) => [
+ index * 2.5,
+ 35 + Math.sin(index / 3) * 30 * random(),
+ ]);
+ elements.push({
+ ...base,
+ type: "freedraw",
+ backgroundColor: "transparent",
+ points,
+ pressures: [],
+ simulatePressure: true,
+ lastCommittedPoint: null,
+ });
+ }
+ }
+ }
+
+ // everything in view: the grid's size times the zoom fits the viewport, centered
+ const zoom = 0.2;
+ const { width, height } = PERF_ENVIRONMENT.viewport;
+ const appState = {
+ zoom: { value: zoom },
+ scrollX: (width / zoom - columns * cellWidth) / 2,
+ scrollY: (height / zoom - rows * cellHeight) / 2,
+ };
+
+ return { elements, appState };
+}
+
+/**
+ * Collects what the Performance API only reports to observers, and counts the
+ * static canvas's draw calls — the scene is drawn once it drew elements (runs
+ * before the app's scripts).
+ */
+function installPageObservers() {
+ const state = { lcp: 0, cls: 0, longTasks: [], staticDraws: 0 };
+ window.__perf = state;
+
+ new PerformanceObserver((list) => {
+ for (const entry of list.getEntries()) {
+ state.lcp = entry.startTime;
+ }
+ }).observe({ type: "largest-contentful-paint", buffered: true });
+
+ new PerformanceObserver((list) => {
+ for (const entry of list.getEntries()) {
+ if (!entry.hadRecentInput) {
+ state.cls += entry.value;
+ }
+ }
+ }).observe({ type: "layout-shift", buffered: true });
+
+ new PerformanceObserver((list) => {
+ for (const entry of list.getEntries()) {
+ state.longTasks.push({
+ start: entry.startTime,
+ duration: entry.duration,
+ });
+ }
+ }).observe({ type: "longtask", buffered: true });
+
+ const context = CanvasRenderingContext2D.prototype;
+ for (const method of ["drawImage", "fill", "stroke", "fillText"]) {
+ const draw = context[method];
+ context[method] = function (...drawArgs) {
+ if (this.canvas.classList.contains("static")) {
+ state.staticDraws += 1;
+ }
+ return draw.apply(this, drawArgs);
+ };
+ }
+}
+
+/** Bytes and requests that finished loading, with the connection throttled. */
+async function trackNetwork(cdp) {
+ const resourceTypes = new Map();
+ const counters = { requests: 0, transferBytes: 0, jsBytes: 0 };
+
+ await cdp.send("Network.enable");
+ await cdp.send("Network.emulateNetworkConditions", {
+ offline: false,
+ latency: PERF_ENVIRONMENT.network.latencyMs,
+ downloadThroughput: (PERF_ENVIRONMENT.network.downloadKbps * 1024) / 8,
+ uploadThroughput: (PERF_ENVIRONMENT.network.uploadKbps * 1024) / 8,
+ });
+
+ cdp.on("Network.responseReceived", ({ requestId, type }) => {
+ resourceTypes.set(requestId, type);
+ });
+ cdp.on("Network.loadingFinished", ({ requestId, encodedDataLength }) => {
+ counters.requests += 1;
+ counters.transferBytes += encodedDataLength;
+ if (resourceTypes.get(requestId) === "Script") {
+ counters.jsBytes += encodedDataLength;
+ }
+ });
+
+ return { snapshot: () => ({ ...counters }) };
+}
+
+/** The first frame's `performance.now()` the scenario's `readyAt` (run in the page, every frame) returned. */
+async function waitForReady(page, readyAt) {
+ const handle = await page.waitForFunction(readyAt, undefined, {
+ timeout: LOAD_TIMEOUT_MS,
+ });
+ return handle.jsonValue();
+}
+
+/** Paint, layout shift and main-thread metrics of the page until `until` (`performance.now()`). */
+function readPageMetrics(page, until) {
+ return page.evaluate((untilTime) => {
+ const { __perf: state } = window;
+ const [navigation] = performance.getEntriesByType("navigation");
+ const fcp = performance.getEntriesByName("first-contentful-paint")[0]
+ ?.startTime;
+ // the main thread blocked between first paint and ready, like Lighthouse's TBT until TTI
+ const tbt = state.longTasks
+ .filter(({ start }) => start >= (fcp ?? 0) && start < untilTime)
+ .reduce((sum, { duration }) => sum + Math.max(0, duration - 50), 0);
+
+ return {
+ ttfb: navigation?.responseStart,
+ fcp,
+ lcp: state.lcp || undefined,
+ cls: state.cls,
+ tbt,
+ };
+ }, until);
+}
+
+/** Frames slower than this are long animation frames: a visible stutter. */
+const LONG_FRAME_MS = 50;
+
+const repeat = (count, step) => Array.from({ length: count }, () => step);
+
+/**
+ * The wheel events of the pan-and-zoom scenario, one per frame (null: a
+ * frame without one, so a zoom's sharp redraw after it stops is measured).
+ * Shift+wheel pans horizontally, ctrl/cmd+shift+wheel vertically and
+ * ctrl/cmd+wheel zooms around the pointer (`App.wheel.ts`) — whatever input
+ * device the editor assumes. From the overview at 20 %: pan it, zoom to
+ * 100 %, pan into elements not drawn at that zoom yet, zoom back out.
+ */
+const PAN_ZOOM_STEPS = [
+ ...repeat(30, { shiftKey: true, deltaY: 15 }),
+ ...repeat(30, { shiftKey: true, deltaY: -15 }),
+ ...repeat(40, { ctrlKey: true, deltaY: -2 }),
+ ...repeat(20, null),
+ ...repeat(40, { ctrlKey: true, shiftKey: true, deltaY: 20 }),
+ ...repeat(40, { shiftKey: true, deltaY: 20 }),
+ ...repeat(40, { ctrlKey: true, deltaY: 2 }),
+ ...repeat(20, null),
+];
+
+/**
+ * Plays `PAN_ZOOM_STEPS` over the canvas: each frame's main-thread work, the
+ * time between the frames, and the static canvas's draws. Headless Chromium
+ * ticks frames at a fixed 60 Hz (the frame-rate flags don't change it), so the
+ * time between frames only moves in whole frames; a frame's work — from its
+ * start until a task posted in it runs, after its rendering: the editor
+ * drawing the previous wheel event, handling the current one, style, layout
+ * and paint — shows every millisecond.
+ */
+function panAndZoom(steps) {
+ const canvas = document.querySelector(
+ "canvas.excalidraw__canvas.interactive",
+ );
+ const { left, top, width, height } = canvas.getBoundingClientRect();
+ const position = { clientX: left + width / 2, clientY: top + height / 2 };
+ const nextFrame = () =>
+ new Promise((resolve) => requestAnimationFrame(resolve));
+ const afterRendering = () =>
+ new Promise((resolve) => {
+ const channel = new MessageChannel();
+ channel.port1.onmessage = () => resolve(performance.now());
+ channel.port2.postMessage(null);
+ });
+
+ // zooms anchor on the pointer's last position
+ canvas.dispatchEvent(
+ new PointerEvent("pointermove", {
+ bubbles: true,
+ pointerType: "mouse",
+ isPrimary: true,
+ ...position,
+ }),
+ );
+
+ return (async () => {
+ const drawsBefore = window.__perf.staticDraws;
+ const work = [];
+ const intervals = [];
+ let frameStart = await nextFrame();
+ for (const step of steps) {
+ if (step) {
+ canvas.dispatchEvent(
+ new WheelEvent("wheel", {
+ bubbles: true,
+ cancelable: true,
+ deltaMode: 0,
+ ...position,
+ ...step,
+ }),
+ );
+ }
+ work.push((await afterRendering()) - frameStart);
+ const nextFrameStart = await nextFrame();
+ intervals.push(nextFrameStart - frameStart);
+ frameStart = nextFrameStart;
+ }
+ return { work, intervals, draws: window.__perf.staticDraws - drawsBefore };
+ })();
+}
+
+/**
+ * The mean frame work — the interaction's main-thread work spread over its
+ * frames, so a slower part of it shows however short — its 95th percentile,
+ * and the long frames.
+ */
+function getFrameMetrics({ work, intervals }) {
+ const sorted = [...work].sort((a, b) => a - b);
+ return {
+ frameMean: work.reduce((sum, frame) => sum + frame, 0) / work.length,
+ frameP95:
+ sorted[Math.min(sorted.length - 1, Math.floor(0.95 * sorted.length))],
+ longFrames: intervals.filter((interval) => interval > LONG_FRAME_MS).length,
+ };
+}
+
+const LARGE_SCENE = createLargeScene();
+
+/**
+ * The scenarios, by their ids in the admin's catalogue (`PERF_SCENARIOS` in
+ * Excalidraw+); `readyAt` returns `performance.now()` once the page is ready.
+ * One with `interact` measures that once the page is ready and settled,
+ * instead of the load.
+ */
+const SCENARIOS = [
+ {
+ id: "oss-editor",
+ // the welcome screen shows once the app loaded an empty scene
+ readyAt: () =>
+ document.querySelector(".welcome-screen-center")?.checkVisibility()
+ ? performance.now()
+ : 0,
+ },
+ {
+ id: "oss-large-scene",
+ scene: LARGE_SCENE,
+ readyAt: () => (window.__perf.staticDraws > 0 ? performance.now() : 0),
+ },
+ {
+ id: "oss-pan-zoom",
+ scene: LARGE_SCENE,
+ readyAt: () => (window.__perf.staticDraws > 0 ? performance.now() : 0),
+ interact: async (page) => {
+ // fonts and lazy chunks loaded, so their redraws don't land in the frames
+ await page.waitForLoadState("networkidle", { timeout: LOAD_TIMEOUT_MS });
+ const frames = await page.evaluate(panAndZoom, PAN_ZOOM_STEPS);
+ if (!frames.draws) {
+ throw new Error("The scene didn't redraw while panning and zooming");
+ }
+ return getFrameMetrics(frames);
+ },
+ },
+];
+
+async function measureOnce(browser, scenario, appUrl) {
+ const context = await browser.newContext({
+ viewport: PERF_ENVIRONMENT.viewport,
+ // the service worker's precaching would add to the measured downloads
+ serviceWorkers: "block",
+ });
+
+ try {
+ for (const url of BLOCKED_URLS) {
+ await context.route(url, (route) => route.abort());
+ }
+ await context.addInitScript(installPageObservers);
+ if (scenario.scene) {
+ await context.addInitScript(
+ ({ keys, elements, appState }) => {
+ localStorage.setItem(keys.elements, elements);
+ localStorage.setItem(keys.appState, appState);
+ },
+ {
+ keys: STORAGE_KEYS,
+ elements: JSON.stringify(scenario.scene.elements),
+ appState: JSON.stringify(scenario.scene.appState),
+ },
+ );
+ }
+
+ const page = await context.newPage();
+ const network = await trackNetwork(await context.newCDPSession(page));
+
+ // without waiting for `load`, so the polling sees the editor as soon as it's ready
+ await page.goto(appUrl, { timeout: LOAD_TIMEOUT_MS, waitUntil: "commit" });
+ const ready = await waitForReady(page, scenario.readyAt);
+ const transferred = network.snapshot();
+ await page.waitForTimeout(PAINT_SETTLE_MS);
+ const { appStart, buildSha } = await page.evaluate(
+ (mark) => ({
+ appStart: performance.getEntriesByName(mark, "mark")[0]?.startTime,
+ buildSha: window.__EXCALIDRAW_SHA__ ?? null,
+ }),
+ APP_START_MARK,
+ );
+ const validBuildSha = /^[0-9a-f]{7,40}$/.test(buildSha ?? "")
+ ? buildSha
+ : null;
+
+ if (scenario.interact) {
+ return {
+ metrics: await scenario.interact(page),
+ phases: {},
+ buildSha: validBuildSha,
+ };
+ }
+
+ return {
+ metrics: {
+ ready,
+ ...(await readPageMetrics(page, ready)),
+ ...transferred,
+ },
+ // builds without the mark have no phases
+ phases:
+ appStart === undefined
+ ? {}
+ : { appCode: Math.min(appStart, ready), editor: ready },
+ buildSha: validBuildSha,
+ };
+ } finally {
+ await context.close();
+ }
+}
+
+/** A free local port, from the OS. */
+const getFreePort = () =>
+ new Promise((resolve, reject) => {
+ const server = net.createServer();
+ server.once("error", reject);
+ server.listen(0, () => {
+ const { port } = server.address();
+ server.close(() => resolve(port));
+ });
+ });
+
+/**
+ * Builds this checkout's app for production — as Vercel does (`build:app`),
+ * minus linting — and serves it with `vite preview`: its url, the commit (and
+ * whether the checkout has changes on top), and how to stop the server.
+ */
+async function serveLocalBuild() {
+ const git = (...gitArgs) =>
+ execFileSync("git", gitArgs, { cwd: REPO_ROOT, encoding: "utf8" }).trim();
+ const sha = git("rev-parse", "HEAD");
+ const label = `this checkout (${sha.slice(0, 7)}${
+ git("status", "--porcelain") ? " + uncommitted changes" : ""
+ })`;
+
+ console.info(`⏱️ Building ${label}…`);
+ try {
+ execFileSync(process.execPath, [VITE, "build"], {
+ cwd: APP_DIR,
+ env: {
+ ...process.env,
+ VITE_APP_GIT_SHA: sha,
+ VITE_APP_ENABLE_TRACKING: "true",
+ VITE_APP_ENABLE_ESLINT: "false",
+ },
+ stdio: "pipe",
+ maxBuffer: 256 * 1024 * 1024,
+ });
+ } catch (error) {
+ console.error(
+ String(error.stderr ?? error)
+ .trim()
+ .split("\n")
+ .slice(-20)
+ .join("\n"),
+ );
+ throw new Error("The build failed (`yarn build:app` shows why)");
+ }
+
+ const port = await getFreePort();
+ const server = spawn(
+ process.execPath,
+ [VITE, "preview", "--port", String(port), "--strictPort"],
+ { cwd: APP_DIR, stdio: "ignore" },
+ );
+ // however the script ends
+ process.on("exit", () => server.kill());
+ const url = `http://localhost:${port}`;
+ for (let attempt = 0; ; attempt++) {
+ const isUp = await fetch(url)
+ .then((response) => response.ok)
+ .catch(() => false);
+ if (isUp) {
+ return { url, label, stop: () => server.kill() };
+ }
+ if (attempt > 60 || server.exitCode !== null) {
+ server.kill();
+ throw new Error("`vite preview` didn't start");
+ }
+ await sleep(500);
+ }
+}
+
+/** Whether the app serves `sha` (its version.json ends with the short hash) within the wait. */
+async function waitForDeploy(sha) {
+ const deadline = Date.now() + WAIT_FOR_DEPLOY_MS;
+
+ while (Date.now() < deadline) {
+ const deployed = await fetch(`${APP_URL}/version.json?t=${Date.now()}`, {
+ cache: "no-store",
+ })
+ .then((response) => (response.ok ? response.json() : null))
+ .then((data) => data?.version?.split("-").at(-1))
+ .catch(() => null);
+ if (deployed && sha.startsWith(deployed)) {
+ return true;
+ }
+ console.info(
+ `⏱️ ${APP_URL} serves ${
+ deployed ?? "nothing yet"
+ }, waiting for ${sha.slice(0, 7)}…`,
+ );
+ await sleep(WAIT_FOR_DEPLOY_INTERVAL_MS);
+ }
+
+ return false;
+}
+
+if (args["wait-for"] && !(await waitForDeploy(args["wait-for"]))) {
+ // a later commit's run measures it instead
+ console.warn(
+ `⏱️ ${APP_URL} didn't serve ${args["wait-for"]} in time — not measured`,
+ );
+ process.exit(0);
+}
+
+/** The metrics the runner records, in the admin's order (`PERF_METRICS` in Excalidraw+), and their units. */
+const METRIC_UNITS = {
+ ready: "ms",
+ ttfb: "ms",
+ fcp: "ms",
+ lcp: "ms",
+ tbt: "ms",
+ cls: "score",
+ jsBytes: "bytes",
+ transferBytes: "bytes",
+ requests: "count",
+ frameMean: "ms",
+ frameP95: "ms",
+ longFrames: "count",
+};
+
+/** Linear-interpolated quantile of ascending `sorted` (the admin's too). */
+const quantile = (sorted, q) => {
+ const position = (sorted.length - 1) * q;
+ const lower = Math.floor(position);
+ const upper = Math.ceil(position);
+ return sorted[lower] + (sorted[upper] - sorted[lower]) * (position - lower);
+};
+
+const summarize = (values) => {
+ const sorted = [...values].sort((a, b) => a - b);
+ return {
+ median: quantile(sorted, 0.5),
+ p25: quantile(sorted, 0.25),
+ p75: quantile(sorted, 0.75),
+ };
+};
+
+/** Below it, a difference in timings is unlikely to be the loads' noise. */
+const SIGNIFICANCE = 0.05;
+
+/**
+ * The two-sided p-value of the Mann–Whitney U test: how likely the two
+ * samples' ranks are this far apart if the builds didn't differ — no
+ * assumption on how timings spread, fit for a few loads per side. Exact (by
+ * counting the rank arrangements); ties get mid-ranks.
+ */
+function mannWhitneyP(a, b) {
+ const ranked = [
+ ...a.map((value) => ({ value, inA: true })),
+ ...b.map((value) => ({ value, inA: false })),
+ ].sort((x, y) => x.value - y.value);
+ let rankSumA = 0;
+ for (let i = 0; i < ranked.length; ) {
+ let j = i;
+ while (j + 1 < ranked.length && ranked[j + 1].value === ranked[i].value) {
+ j++;
+ }
+ // ranks i + 1 … j + 1, shared
+ const rank = (i + j + 2) / 2;
+ for (let k = i; k <= j; k++) {
+ if (ranked[k].inA) {
+ rankSumA += rank;
+ }
+ }
+ i = j + 1;
+ }
+ const m = a.length;
+ const n = b.length;
+ const uA = rankSumA - (m * (m + 1)) / 2;
+ const u = Math.floor(Math.min(uA, m * n - uA));
+
+ // arrangements of m and n values with the statistic `value`
+ const memo = new Map();
+ const count = (value, m, n) => {
+ if (value < 0) {
+ return 0;
+ }
+ if (!m || !n) {
+ return value === 0 ? 1 : 0;
+ }
+ const key = `${value},${m},${n}`;
+ if (!memo.has(key)) {
+ memo.set(key, count(value - n, m - 1, n) + count(value, m, n - 1));
+ }
+ return memo.get(key);
+ };
+ let atMost = 0;
+ for (let value = 0; value <= u; value++) {
+ atMost += count(value, m, n);
+ }
+ let arrangements = 1;
+ for (let i = 1; i <= m; i++) {
+ arrangements = (arrangements * (n + i)) / i;
+ }
+ return Math.min(1, (2 * atMost) / arrangements);
+}
+
+/**
+ * Every metric is better lower. Timings differ when the Mann–Whitney test
+ * says so (`SIGNIFICANCE`); bytes and requests don't vary from load to load,
+ * so any difference in them counts.
+ */
+function getVerdict(baseValues, nextValues) {
+ const isConstant = (values) => values.every((value) => value === values[0]);
+ const direction = Math.sign(median(nextValues) - median(baseValues));
+ const p =
+ isConstant(baseValues) && isConstant(nextValues)
+ ? direction
+ ? 0
+ : 1
+ : mannWhitneyP(baseValues, nextValues);
+ return {
+ p,
+ verdict:
+ p < SIGNIFICANCE && direction
+ ? direction > 0
+ ? "worse"
+ : "better"
+ : "~",
+ };
+}
+
+const median = (values) =>
+ quantile(
+ [...values].sort((a, b) => a - b),
+ 0.5,
+ );
+
+/** One row per scenario and metric both targets measured. */
+function compareTargets(scenarios, base, next) {
+ const rows = [];
+ for (const scenario of scenarios) {
+ const failed = (target) =>
+ target.samples.filter((s) => s.scenario === scenario.id && s.error)
+ .length;
+ for (const [metric, unit] of Object.entries(METRIC_UNITS)) {
+ const values = (target) =>
+ target.samples.flatMap((sample) =>
+ sample.scenario === scenario.id &&
+ !sample.error &&
+ sample.metrics[metric] !== undefined
+ ? [sample.metrics[metric]]
+ : [],
+ );
+ const baseValues = values(base);
+ const nextValues = values(next);
+ if (!baseValues.length || !nextValues.length) {
+ continue;
+ }
+ const baseStats = summarize(baseValues);
+ const nextStats = summarize(nextValues);
+ const delta = nextStats.median - baseStats.median;
+ rows.push({
+ scenario: scenario.id,
+ metric,
+ unit,
+ base: baseStats,
+ next: nextStats,
+ delta,
+ deltaPercent: baseStats.median
+ ? (delta / baseStats.median) * 100
+ : null,
+ ...getVerdict(baseValues, nextValues),
+ baseFailed: failed(base),
+ nextFailed: failed(next),
+ });
+ }
+ }
+ return rows;
+}
+
+const formatValue = (value, unit) =>
+ unit === "ms"
+ ? `${
+ value < 100 ? value.toFixed(1) : Math.round(value).toLocaleString("en")
+ } ms`
+ : unit === "bytes"
+ ? `${(value / 1024).toLocaleString("en", {
+ minimumFractionDigits: 1,
+ maximumFractionDigits: 1,
+ })} KiB`
+ : unit === "score"
+ ? value.toFixed(3)
+ : String(Math.round(value * 10) / 10);
+
+const formatSigned = (value, format) =>
+ `${value > 0 ? "+" : value < 0 ? "−" : "±"}${format(Math.abs(value))}`;
+
+const VERDICT_COLORS = { worse: 31, better: 32 };
+
+/** The comparison as an aligned table, the verdicts colored on a terminal. */
+function printComparison(rows) {
+ const color = (text, verdict) =>
+ process.stdout.isTTY && VERDICT_COLORS[verdict]
+ ? `\x1b[${VERDICT_COLORS[verdict]}m${text}\x1b[0m`
+ : text;
+ const header = [
+ "Scenario",
+ "Metric",
+ "Base",
+ "New",
+ "Change",
+ "Change %",
+ "Base p25–p75",
+ "New p25–p75",
+ "p",
+ "",
+ ];
+ const lines = rows.map((row, index) => [
+ index && rows[index - 1].scenario === row.scenario ? "" : row.scenario,
+ row.metric,
+ formatValue(row.base.median, row.unit),
+ formatValue(row.next.median, row.unit),
+ formatSigned(row.delta, (value) => formatValue(value, row.unit)),
+ row.deltaPercent === null
+ ? "—"
+ : formatSigned(row.deltaPercent, (value) => `${value.toFixed(1)} %`),
+ `${formatValue(row.base.p25, row.unit)} – ${formatValue(
+ row.base.p75,
+ row.unit,
+ )}`,
+ `${formatValue(row.next.p25, row.unit)} – ${formatValue(
+ row.next.p75,
+ row.unit,
+ )}`,
+ row.p < 0.001 ? "<0.001" : row.p.toFixed(3),
+ row.verdict,
+ ]);
+ const widths = header.map((title, column) =>
+ Math.max(title.length, ...lines.map((line) => line[column].length)),
+ );
+ // the names left-aligned, the numbers right-aligned
+ const pad = (cell, column) =>
+ column < 2 || column === header.length - 1
+ ? cell.padEnd(widths[column])
+ : cell.padStart(widths[column]);
+
+ console.info(header.map(pad).join(" "));
+ console.info(widths.map((width) => "─".repeat(width)).join(" "));
+ rows.forEach((row, index) =>
+ console.info(color(lines[index].map(pad).join(" "), row.verdict)),
+ );
+}
+
+const CSV_COLUMNS = [
+ "scenario",
+ "metric",
+ "unit",
+ "base_median",
+ "base_p25",
+ "base_p75",
+ "new_median",
+ "new_p25",
+ "new_p75",
+ "change",
+ "change_percent",
+ "p_value",
+ "verdict",
+ "base_failed",
+ "new_failed",
+];
+
+const toCsv = (rows) =>
+ [
+ CSV_COLUMNS.join(","),
+ ...rows.map((row) =>
+ [
+ row.scenario,
+ row.metric,
+ row.unit,
+ row.base.median,
+ row.base.p25,
+ row.base.p75,
+ row.next.median,
+ row.next.p25,
+ row.next.p75,
+ row.delta,
+ row.deltaPercent ?? "",
+ row.p,
+ row.verdict,
+ row.baseFailed,
+ row.nextFailed,
+ ].join(","),
+ ),
+ ].join("\n");
+
+const scenarios = args.scenario
+ ? SCENARIOS.filter(({ id }) => args.scenario.split(",").includes(id))
+ : SCENARIOS;
+
+// with --compare, the base and the new build alternate: whichever loads first
+// switches every iteration, so the machine drifting (warming up, other work)
+// weighs on both alike
+const localBuild = args.compare && !args.url ? await serveLocalBuild() : null;
+const target = (name, url, label = url) => ({
+ name,
+ url,
+ label,
+ samples: [],
+ buildSha: null,
+});
+const targets = args.compare
+ ? [
+ target("base", withoutSlash(args.base)),
+ localBuild
+ ? target(
+ "new",
+ localBuild.url,
+ `${localBuild.label} at ${localBuild.url}`,
+ )
+ : target("new", APP_URL),
+ ]
+ : [target(null, APP_URL)];
+
+console.info(
+ args.compare
+ ? `⏱️ Comparing ${targets[1].url} with ${targets[0].url}, ${ITERATIONS} loads each per scenario, alternating…`
+ : `⏱️ Measuring ${APP_URL}, ${ITERATIONS} loads per scenario…`,
+);
+
+const browser = await chromium.launch();
+const browserVersion = browser.version();
+
+try {
+ for (const scenario of scenarios) {
+ for (let iteration = 1; iteration <= ITERATIONS; iteration++) {
+ const order = iteration % 2 ? targets : [...targets].reverse();
+ for (const target of order) {
+ const label = `${scenario.id}${
+ target.name ? ` ${target.name}` : ""
+ } #${iteration}`;
+ try {
+ await sleep(BETWEEN_LOADS_MS);
+ const load = await measureOnce(browser, scenario, target.url);
+ target.buildSha ??= load.buildSha;
+ target.samples.push({
+ scenario: scenario.id,
+ iteration,
+ metrics: load.metrics,
+ phases: load.phases,
+ error: null,
+ });
+ console.info(
+ `⏱️ ${label}: ${
+ scenario.interact
+ ? `mean frame ${Math.round(
+ load.metrics.frameMean,
+ )} ms, p95 ${Math.round(load.metrics.frameP95)} ms, ${
+ load.metrics.longFrames
+ } long`
+ : `ready in ${Math.round(load.metrics.ready)} ms`
+ }`,
+ );
+ } catch (error) {
+ // a failed load is a sample with its error, so one flaky load doesn't lose the run
+ const message = (
+ error instanceof Error ? error.message : String(error)
+ ).split("\n")[0];
+ target.samples.push({
+ scenario: scenario.id,
+ iteration,
+ metrics: {},
+ phases: {},
+ error: message,
+ });
+ console.warn(`⏱️ ${label} failed: ${message}`);
+ }
+ }
+ }
+ }
+} finally {
+ await browser.close();
+ localBuild?.stop();
+}
+
+if (targets.some(({ samples }) => !samples.some(({ error }) => !error))) {
+ console.error("⏱️ Every page load failed");
+ process.exit(1);
+}
+
+if (args.compare) {
+ const [base, next] = targets;
+ const rows = compareTargets(scenarios, base, next);
+ const describe = ({ label, buildSha }) =>
+ `${label}${buildSha ? ` (build ${buildSha.slice(0, 7)})` : ""}`;
+
+ console.info(`\nBase: ${describe(base)}\nNew: ${describe(next)}\n`);
+ printComparison(rows);
+ for (const row of rows.filter(
+ (row, index) =>
+ (row.baseFailed || row.nextFailed) &&
+ rows.findIndex(({ scenario }) => scenario === row.scenario) === index,
+ )) {
+ console.warn(
+ `⏱️ ${row.scenario}: ${row.baseFailed} base and ${row.nextFailed} new loads failed`,
+ );
+ }
+ if (args.out) {
+ fs.writeFileSync(args.out, `${toCsv(rows)}\n`);
+ console.info(`\nWrote ${args.out}`);
+ }
+} else {
+ const [{ samples, buildSha }] = targets;
+ const run = {
+ appUrl: APP_URL,
+ buildSha,
+ environment: {
+ ...PERF_ENVIRONMENT,
+ runner: process.env.RUNNER_NAME ?? null,
+ browser: `chromium ${browserVersion}`,
+ iterations: ITERATIONS,
+ },
+ samples,
+ };
+
+ if (args.out) {
+ fs.writeFileSync(args.out, JSON.stringify(run, null, 2));
+ } else {
+ console.info(JSON.stringify(run, null, 2));
+ }
+}
diff --git a/scripts/stats/post.mjs b/scripts/stats/post.mjs
new file mode 100644
index 0000000000..db65abb82b
--- /dev/null
+++ b/scripts/stats/post.mjs
@@ -0,0 +1,87 @@
+#!/usr/bin/env node
+
+/**
+ * Posts a performance run (`perf.mjs --out`) or a build's bundle stats
+ * (`yarn stats:bundle` → `excalidraw-app/build/bundle-stats.json`) to the
+ * Excalidraw+ api, which stores it for the admin's Performance and Bundle size
+ * pages. Needs `OSS_STATS_TOKEN`; the commit is `--commit`, `GITHUB_SHA` or
+ * HEAD, read from this repo.
+ *
+ * node scripts/stats/post.mjs perf perf.json
+ * node scripts/stats/post.mjs bundle excalidraw-app/build/bundle-stats.json
+ */
+
+import { execFileSync } from "node:child_process";
+import fs from "node:fs";
+import { parseArgs } from "node:util";
+
+const {
+ positionals: [kind, file],
+ values: args,
+} = parseArgs({
+ allowPositionals: true,
+ options: {
+ commit: { type: "string" },
+ api: {
+ type: "string",
+ default:
+ process.env.OSS_STATS_API_URL || "https://backend.excalidraw.com",
+ },
+ },
+});
+
+/** The api's `OSS_STATS_TOKEN_HEADER`. */
+const TOKEN_HEADER = "x-oss-stats-token";
+
+if (!["perf", "bundle"].includes(kind) || !file) {
+ console.error(
+ "Usage: post.mjs <perf|bundle> <file.json> [--commit <sha>] [--api <url>]",
+ );
+ process.exit(1);
+}
+
+const token = process.env.OSS_STATS_TOKEN;
+if (!token) {
+ console.error("OSS_STATS_TOKEN is not set");
+ process.exit(1);
+}
+
+const git = (...gitArgs) =>
+ execFileSync("git", gitArgs, { encoding: "utf8" }).trim();
+
+const commitSha = git(
+ "rev-parse",
+ args.commit || process.env.GITHUB_SHA || "HEAD",
+);
+const commit = {
+ commitSha,
+ commitTitle: git("log", "-1", "--format=%s", commitSha),
+ runUrl: process.env.GITHUB_RUN_ID
+ ? `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`
+ : null,
+};
+const data = JSON.parse(fs.readFileSync(file, "utf8"));
+const body =
+ kind === "perf"
+ ? { ...commit, ...data }
+ : {
+ ...commit,
+ committedAt: git("log", "-1", "--format=%cI", commitSha),
+ ...data,
+ };
+
+const response = await fetch(`${args.api}/api/oss/${kind}-runs`, {
+ method: "POST",
+ headers: { "content-type": "application/json", [TOKEN_HEADER]: token },
+ body: JSON.stringify(body),
+});
+
+if (!response.ok) {
+ console.error(
+ `${response.status} ${response.statusText}: ${await response.text()}`,
+ );
+ process.exit(1);
+}
+
+const { id } = await response.json();
+console.info(`Stored the ${kind} run of ${commitSha.slice(0, 7)} as ${id}`);
diff --git a/scripts/stats/vite.config.mts b/scripts/stats/vite.config.mts
new file mode 100644
index 0000000000..0e2971ccb1
--- /dev/null
+++ b/scripts/stats/vite.config.mts
@@ -0,0 +1,17 @@
+import { defineConfig, mergeConfig } from "vite";
+
+import appConfig from "../../excalidraw-app/vite.config.mts";
+
+import { bundleStatsPlugin } from "./bundle-stats-plugin.mts";
+
+/**
+ * The app's production build plus `bundle-stats.json` (`yarn stats:bundle`,
+ * run from `excalidraw-app/` like the app's own build). The stats aren't part
+ * of the deployed builds, so they only cost CI the extra compression.
+ */
+export default defineConfig(async (env) => {
+ const config =
+ typeof appConfig === "function" ? await appConfig(env) : await appConfig;
+
+ return mergeConfig(config, { plugins: [bundleStatsPlugin()] });
+});
diff --git a/yarn.lock b/yarn.lock
index e2eb9e911b..8bbbd6fd20 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -6605,6 +6605,11 @@ fs.realpath@^1.0.0:
resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f"
integrity sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==
+ version "2.3.2"
+ resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.2.tgz#8a526f78b8fdf4623b709e0b975c52c24c02fd1a"
+ integrity sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==
+
fsevents@~2.3.2, fsevents@~2.3.3:
version "2.3.3"
resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.3.tgz#cac6407785d03675a2a5e1a5305c697b347d90d6"
@@ -8423,6 +8428,20 @@ pkg-types@^1.3.1:
mlly "^1.7.4"
pathe "^2.0.1"
+ version "1.58.2"
+ resolved "https://registry.yarnpkg.com/playwright-core/-/playwright-core-1.58.2.tgz#ac5f5b4b10d29bcf934415f0b8d133b34b0dcb13"
+ integrity sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==
+
+ version "1.58.2"
+ resolved "https://registry.yarnpkg.com/playwright/-/playwright-1.58.2.tgz#afe547164539b0bcfcb79957394a7a3fa8683cfd"
+ integrity sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==
+ dependencies:
+ playwright-core "1.58.2"
+ optionalDependencies:
+ fsevents "2.3.2"
+
version "1.0.0"
resolved "https://registry.yarnpkg.com/png-chunk-text/-/png-chunk-text-1.0.0.tgz#1c6006d8e34ba471d38e1c9c54b3f53e1085e18f"