pcbjam/scripts/deploy/build-demo.mjs

188 lines
7.9 KiB
JavaScript
Raw Normal View History

#!/usr/bin/env node
// Build the GPL standalone for the no-backend demo (demo.pcbjam.com): pin it to
// the CDN WASM root + this tag's manifests + the static gallery, run the vite
// build, and drop the Cloudflare Pages _headers/_redirects into dist/. The
// resulting pcbjam/web/standalone/dist/ is what `wrangler pages deploy` ships.
// See docs/features/demo-deploy/ (P4).
//
// node scripts/build-demo.mjs --tag 2.7.7 [--cdn https://cdn.pcbjam.com]
//
// WASM + example bytes come from the CDN at runtime, so the local public/wasm
// symlink (dev only) is kept OUT of the bundle (temporarily moved aside during
// the build; in CI it doesn't exist at all).
import { execFileSync } from "node:child_process";
import {
copyFileSync,
existsSync,
lstatSync,
renameSync,
rmSync,
} from "node:fs";
import { join, resolve } from "node:path";
function parseArgs(argv) {
const a = {
tag: null,
cdn: "https://cdn.pcbjam.com",
repo: "https://github.com/PCBJam/pcbjam",
libTag: null,
// Marketing site the version badge links to; the in-editor waitlist form
// cross-posts to <landing>/api/waitlist unless --waitlist overrides it.
landing: "https://pcbjam.com",
waitlist: null,
// Plausible pa-*.js script URL. Off unless given (or VITE_PLAUSIBLE_SRC
// is already in the environment, which passes straight through).
plausible: null,
feat(editor): report uncaught errors to Better Stack The editor reported nothing when a session died. Evidence lived only in-tab — an 800-line React array behind a "Show console" button — so diagnosis meant asking a user to paste a screenshot. Better Stack's Error Tracking ingests the Sentry wire protocol, so this runs the stock @sentry/browser against a Better Stack DSN. Sentry.init installs its own window error/unhandledrejection handlers, so uncaught main-thread errors and the wasm traps that escape emscripten's DOM event handlers are captured with no instrumentation at the throw sites. Not their JS tag: it has no beforeSend or fingerprint hooks, its runtime spawns workers from cross-origin CDN hosts (this page is COEP: require-corp), and it ships session replay on by default — which on a CAD canvas records customers' board geometry. @sentry/browser is imported in exactly one file so the vendor stays swappable, mirroring how lib/analytics.ts isolates Plausible. Also replaces the terminal-signature regex with a shared, unit-tested predicate (wasm/terminal-error.ts) used by BOTH the fatal overlay and the reporter, so they cannot disagree. The regex was a type check written as a string match and had three live holes: `RuntimeError` was listed but never appears IN `.message`; Chrome's bare "unreachable" and "null function" matched nothing (the v0.1.20 prod log is exactly those); and narrowing "table index is out of bounds" to `\bindex out of bounds` for Firefox in 197f317 silently stopped matching Chrome's spelling. Checking the TYPE — every trap in this family is a WebAssembly.RuntimeError — covers all engines and ends the spelling chase; the message patterns remain as a fallback for paths that lose the Error object, such as a worker ErrorEvent crossing the realm boundary with error: null. 197f317's pthread-worker tap, promote() and Firefox findings are kept as-is. Notes: - Off unless VITE_ERRORS_DSN is set AND VITE_ALLOW_USER_OVERRIDE !== "1" (dev servers and every Playwright harness set the latter, and production builds never do), so a production DSN in a local .env still cannot report. With no DSN the whole SDK is const-folded out: 1,193,080 vs 1,282,463 bytes of JS. - browserApiErrors integration removed. It wraps setTimeout/rAF/addEventListener in try/catch, which is exactly how KiCad-on-Emscripten drives its main loop. - Console breadcrumbs off (collab/debug.ts's clog fires per Yjs update and would evict the ring before any crash); dom/fetch/navigation breadcrumbs kept. - beforeSend redacts token/apiKey/Bearer — collab/provider.ts puts the collab token in the y-partyserver URL, so a connection-failure string carries a live credential — and guards the cascade: one wedge produced 8 errors in prod, and after the first terminal event the rest are dropped into cascade_count. Verified end to end against the real EU host from a cross-origin-isolated page: POST /api/<id>/envelope/ -> 200, and 4 terminal throws produce 1 event (control: 1 throw, same count). Privacy policy 9, cookie policy 6 and the licenses page are updated: Better Stack is disclosed as an EU processor, and the licenses page now describes the browser app's own JS dependencies, which it never did. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-03 12:24:30 +02:00
// Better Stack error-tracking DSN (Sentry wire format). Omitted ⇒ no error
// reporting. The demo reports under its own environment: anonymous traffic
// on arbitrary hardware with no backend fails differently from the signed-in
// editor, and mixing them would drown the editor's real regressions.
errorsDsn: null,
errorsEnv: "demo",
};
for (let i = 2; i < argv.length; i++) {
const next = () => argv[++i];
switch (argv[i]) {
case "--tag": a.tag = next(); break;
case "--cdn": a.cdn = next(); break;
case "--repo": a.repo = next(); break;
// KiCad library snapshot tag (published once to libs/kicad/<libTag>/).
// Omitted ⇒ the offline built-in example symbols (back-compat).
case "--lib-tag": a.libTag = next(); break;
// kicad-packages3D snapshot tag (published once to
// libs/kicad-models/<modelsTag>/). Omitted ⇒ 3D component models off
// (the viewer renders bare boards, exactly as before the feature).
case "--models-tag": a.modelsTag = next(); break;
case "--landing": a.landing = next(); break;
case "--waitlist": a.waitlist = next(); break;
case "--plausible": a.plausible = next(); break;
feat(editor): report uncaught errors to Better Stack The editor reported nothing when a session died. Evidence lived only in-tab — an 800-line React array behind a "Show console" button — so diagnosis meant asking a user to paste a screenshot. Better Stack's Error Tracking ingests the Sentry wire protocol, so this runs the stock @sentry/browser against a Better Stack DSN. Sentry.init installs its own window error/unhandledrejection handlers, so uncaught main-thread errors and the wasm traps that escape emscripten's DOM event handlers are captured with no instrumentation at the throw sites. Not their JS tag: it has no beforeSend or fingerprint hooks, its runtime spawns workers from cross-origin CDN hosts (this page is COEP: require-corp), and it ships session replay on by default — which on a CAD canvas records customers' board geometry. @sentry/browser is imported in exactly one file so the vendor stays swappable, mirroring how lib/analytics.ts isolates Plausible. Also replaces the terminal-signature regex with a shared, unit-tested predicate (wasm/terminal-error.ts) used by BOTH the fatal overlay and the reporter, so they cannot disagree. The regex was a type check written as a string match and had three live holes: `RuntimeError` was listed but never appears IN `.message`; Chrome's bare "unreachable" and "null function" matched nothing (the v0.1.20 prod log is exactly those); and narrowing "table index is out of bounds" to `\bindex out of bounds` for Firefox in 197f317 silently stopped matching Chrome's spelling. Checking the TYPE — every trap in this family is a WebAssembly.RuntimeError — covers all engines and ends the spelling chase; the message patterns remain as a fallback for paths that lose the Error object, such as a worker ErrorEvent crossing the realm boundary with error: null. 197f317's pthread-worker tap, promote() and Firefox findings are kept as-is. Notes: - Off unless VITE_ERRORS_DSN is set AND VITE_ALLOW_USER_OVERRIDE !== "1" (dev servers and every Playwright harness set the latter, and production builds never do), so a production DSN in a local .env still cannot report. With no DSN the whole SDK is const-folded out: 1,193,080 vs 1,282,463 bytes of JS. - browserApiErrors integration removed. It wraps setTimeout/rAF/addEventListener in try/catch, which is exactly how KiCad-on-Emscripten drives its main loop. - Console breadcrumbs off (collab/debug.ts's clog fires per Yjs update and would evict the ring before any crash); dom/fetch/navigation breadcrumbs kept. - beforeSend redacts token/apiKey/Bearer — collab/provider.ts puts the collab token in the y-partyserver URL, so a connection-failure string carries a live credential — and guards the cascade: one wedge produced 8 errors in prod, and after the first terminal event the rest are dropped into cascade_count. Verified end to end against the real EU host from a cross-origin-isolated page: POST /api/<id>/envelope/ -> 200, and 4 terminal throws produce 1 event (control: 1 throw, same count). Privacy policy 9, cookie policy 6 and the licenses page are updated: Better Stack is disclosed as an EU processor, and the licenses page now describes the browser app's own JS dependencies, which it never did. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-03 12:24:30 +02:00
case "--errors-dsn": a.errorsDsn = next(); break;
case "--errors-env": a.errorsEnv = next(); break;
default: throw new Error(`unknown arg: ${argv[i]}`);
}
}
if (!a.tag) throw new Error("--tag <release tag> is required");
a.cdn = a.cdn.replace(/\/+$/, "");
a.repo = a.repo.replace(/\/+$/, "");
a.landing = a.landing.replace(/\/+$/, "");
feat(deploy/site): serve the apex from the same Pages project, no redirect rule Vercel was doing the apex->www 308 itself (its "redirect to www" project setting), so nothing about Cloudflare requires a redirect — the behaviour just disappears with Vercel. Rather than rebuild it with a zone Redirect Rule plus a proxied placeholder record, attach pcbjam.com as a SECOND custom domain on pcbjam-site. Both hosts serve the site and the pages already emit canonical=www, which is what consolidates them for search. That drops the riskiest artefact in the migration. Redirect Rules are zone-scoped and run BEFORE Workers/Pages routing, so a `contains` match instead of `eq` would 308 app./editor./demo./api. to www — breaking the product API, not just a marketing page. The sibling hosts are also the reason this was worth avoiding rather than merely guarding. APEX_MODE (lib/common.sh) selects the topology, defaulting to `serve`. 08-verify-prod.sh now dispatches through assert_apex: in serve mode it requires the apex to answer 200 with no hop, to not be a stale Vercel response, to declare canonical=www, and to expose /api/waitlist. The `redirect` mode and 07's rules/apex phases are kept for the alternative. 08 also checks the attached domains via wrangler rather than the REST API, so the whole serve-mode path needs only `wrangler login` — no zone scopes at all. Comments that explained themselves via the old redirect are corrected: astro.config.mjs, web/standalone/src/lib/config.ts and scripts/deploy/build-demo.mjs. The demo keeps posting to www — not because the apex redirects, but because a CORS preflight cannot follow one, so aiming at a host that might ever redirect is a latent breakage. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LAmkjM7okPdScp9XLW1JVr
2026-07-27 14:34:16 +02:00
// The cross-origin demo POSTs the waitlist to the marketing site's endpoint (a
// Cloudflare Pages Function). Always target the canonical www host: a CORS
// preflight cannot follow a redirect, so aiming at a host that might ever
// redirect is a latent breakage. Derive from --landing for custom/staging
// hosts, but pin the production apex to www. (The landing/version-badge link
// stays on the apex.)
const waitlistHost =
a.landing === "https://pcbjam.com" ? "https://www.pcbjam.com" : a.landing;
a.waitlist = a.waitlist || `${waitlistHost}/api/waitlist`;
return a;
}
// Best-effort source commit for the version badge's corresponding-source link;
// empty string if git isn't available (CI shallow checkout etc.) — the badge
// then falls back to the tag's release page.
function gitSha(cwd) {
try {
return execFileSync("git", ["rev-parse", "HEAD"], { cwd })
.toString()
.trim();
} catch {
return "";
}
}
function main() {
const a = parseArgs(process.argv);
const repoRoot = resolve(process.cwd());
const standalone = join(repoRoot, "web/standalone");
const dist = join(standalone, "dist");
const publicWasm = join(standalone, "public/wasm");
const stash = join(standalone, "public/.wasm.demo-stashed");
const env = {
...process.env,
// Versioned CDN: each tool resolves to wasm/<tool>/<ver>/ via this manifest.
VITE_WASM_ROOT: `${a.cdn}/wasm`,
VITE_WASM_MANIFEST: `manifest-${a.tag}.json`,
// Read-only example gallery, saves download to local.
VITE_PROJECT_SOURCE: "static",
VITE_PROJECT_MANIFEST_URL: `${a.cdn}/content/${a.tag}/manifest.json`,
feat(standalone): browser-local (IndexedDB) virtual projects Loading a folder now imports a COPY into a browser-local IndexedDB project with its own /p/:slug URL (original disk files untouched): edits persist to IDB across visits, and the project exports via Download .zip or per-file. Gated by VITE_LOCAL_PROJECTS=idb (on for the demo; off keeps the File System Access write-back flow), so it's configurable per deployment. Modular, swappable project sources behind the shared ProjectSource interface, each self-describing via a SourceDescriptor whose kind is shown verbatim in the UI — "Local (this browser)", "Remote · read-only", "Remote · editable" — on the home page, the project view, and inside the editor, so the user always knows whether/how Save persists: - remote → REST backend (remote-rw) - static → CDN gallery (remote-ro), saves download - local (new) → idbProjectStore, writable IDB store A composite layers the local store over the configured remote/gallery source, routing per slug so imported/saved projects and the gallery share one namespace. New, dependency-free (matching sync-client's raw-IDB ethos): - lib/idb-project-store.ts raw IndexedDB store + create/delete/rename/export - lib/zip.ts store-only ZIP writer (verified via system unzip) - lib/import-folder.ts FSA/webkitdirectory folder → in-memory bytes - lib/project-source-shared.ts source descriptors + deterministic uuid - components/SourceChip, components/LocalProjectsSection Home lists local projects (open/export/rename/delete). Verified: typecheck, project-source tests, prod build, and IDB key-range project isolation in-browser (prefix-colliding slugs don't leak). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 08:24:14 +02:00
// Loaded folders import into a browser-local (IndexedDB) project — editable,
// persistent, exported via Download .zip — layered over the gallery.
VITE_LOCAL_PROJECTS: "idb",
// Libraries: the full KiCad set from versioned CDN static origins when a
// --lib-tag is given (read-only, IDB-cached); else built-in offline symbols.
...(a.libTag
? {
VITE_LIBS_SOURCE: "cdn",
VITE_LIBS_MANIFEST_URL: `${a.cdn}/libs/kicad/${a.libTag}/manifest.json`,
}
: { VITE_LIBS_SOURCE: "static" }),
// 3D models: lazy per-board sparse fetch from the versioned models CDN
// (docs/features/3d-models). Off unless a --models-tag is given.
...(a.modelsTag
? {
VITE_MODELS_MANIFEST_URL: `${a.cdn}/libs/kicad-models/${a.modelsTag}/manifest.json`,
}
: {}),
VITE_YJS_PROVIDER: "broadcastchannel",
// Build identity for the version badge. The commit is the GPLv3
// corresponding-source pointer (pins the kicad + wxwidgets submodules).
VITE_APP_TAG: a.tag,
VITE_GIT_SHA: gitSha(repoRoot),
VITE_REPO_URL: a.repo,
// Version-badge "pcbjam.com" link + the in-editor waitlist form's POST target.
VITE_LANDING_URL: a.landing,
VITE_WAITLIST_URL: a.waitlist,
// Plausible analytics: explicit --plausible wins, else any env-provided value.
...(a.plausible ? { VITE_PLAUSIBLE_SRC: a.plausible } : {}),
feat(editor): report uncaught errors to Better Stack The editor reported nothing when a session died. Evidence lived only in-tab — an 800-line React array behind a "Show console" button — so diagnosis meant asking a user to paste a screenshot. Better Stack's Error Tracking ingests the Sentry wire protocol, so this runs the stock @sentry/browser against a Better Stack DSN. Sentry.init installs its own window error/unhandledrejection handlers, so uncaught main-thread errors and the wasm traps that escape emscripten's DOM event handlers are captured with no instrumentation at the throw sites. Not their JS tag: it has no beforeSend or fingerprint hooks, its runtime spawns workers from cross-origin CDN hosts (this page is COEP: require-corp), and it ships session replay on by default — which on a CAD canvas records customers' board geometry. @sentry/browser is imported in exactly one file so the vendor stays swappable, mirroring how lib/analytics.ts isolates Plausible. Also replaces the terminal-signature regex with a shared, unit-tested predicate (wasm/terminal-error.ts) used by BOTH the fatal overlay and the reporter, so they cannot disagree. The regex was a type check written as a string match and had three live holes: `RuntimeError` was listed but never appears IN `.message`; Chrome's bare "unreachable" and "null function" matched nothing (the v0.1.20 prod log is exactly those); and narrowing "table index is out of bounds" to `\bindex out of bounds` for Firefox in 197f317 silently stopped matching Chrome's spelling. Checking the TYPE — every trap in this family is a WebAssembly.RuntimeError — covers all engines and ends the spelling chase; the message patterns remain as a fallback for paths that lose the Error object, such as a worker ErrorEvent crossing the realm boundary with error: null. 197f317's pthread-worker tap, promote() and Firefox findings are kept as-is. Notes: - Off unless VITE_ERRORS_DSN is set AND VITE_ALLOW_USER_OVERRIDE !== "1" (dev servers and every Playwright harness set the latter, and production builds never do), so a production DSN in a local .env still cannot report. With no DSN the whole SDK is const-folded out: 1,193,080 vs 1,282,463 bytes of JS. - browserApiErrors integration removed. It wraps setTimeout/rAF/addEventListener in try/catch, which is exactly how KiCad-on-Emscripten drives its main loop. - Console breadcrumbs off (collab/debug.ts's clog fires per Yjs update and would evict the ring before any crash); dom/fetch/navigation breadcrumbs kept. - beforeSend redacts token/apiKey/Bearer — collab/provider.ts puts the collab token in the y-partyserver URL, so a connection-failure string carries a live credential — and guards the cascade: one wedge produced 8 errors in prod, and after the first terminal event the rest are dropped into cascade_count. Verified end to end against the real EU host from a cross-origin-isolated page: POST /api/<id>/envelope/ -> 200, and 4 terminal throws produce 1 event (control: 1 throw, same count). Privacy policy 9, cookie policy 6 and the licenses page are updated: Better Stack is disclosed as an EU processor, and the licenses page now describes the browser app's own JS dependencies, which it never did. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-03 12:24:30 +02:00
// Error tracking. The env tag rides along only when a DSN is given.
...(a.errorsDsn
? { VITE_ERRORS_DSN: a.errorsDsn, VITE_ERRORS_ENV: a.errorsEnv }
: {}),
};
console.log(`build-demo: tag=${a.tag} cdn=${a.cdn}`);
console.log(` VITE_WASM_ROOT=${env.VITE_WASM_ROOT}`);
console.log(` VITE_WASM_MANIFEST=${env.VITE_WASM_MANIFEST}`);
console.log(` VITE_PROJECT_MANIFEST_URL=${env.VITE_PROJECT_MANIFEST_URL}`);
console.log(` VITE_APP_TAG=${env.VITE_APP_TAG} VITE_GIT_SHA=${env.VITE_GIT_SHA || "(none)"}`);
console.log(` VITE_LIBS_SOURCE=${env.VITE_LIBS_SOURCE}${env.VITE_LIBS_MANIFEST_URL ? ` (${env.VITE_LIBS_MANIFEST_URL})` : ""}`);
console.log(` VITE_MODELS_MANIFEST_URL=${env.VITE_MODELS_MANIFEST_URL ?? "(unset — 3D models off)"}`);
console.log(` VITE_LANDING_URL=${env.VITE_LANDING_URL} VITE_WAITLIST_URL=${env.VITE_WAITLIST_URL}`);
console.log(` VITE_PLAUSIBLE_SRC=${env.VITE_PLAUSIBLE_SRC || "(off)"}`);
feat(editor): report uncaught errors to Better Stack The editor reported nothing when a session died. Evidence lived only in-tab — an 800-line React array behind a "Show console" button — so diagnosis meant asking a user to paste a screenshot. Better Stack's Error Tracking ingests the Sentry wire protocol, so this runs the stock @sentry/browser against a Better Stack DSN. Sentry.init installs its own window error/unhandledrejection handlers, so uncaught main-thread errors and the wasm traps that escape emscripten's DOM event handlers are captured with no instrumentation at the throw sites. Not their JS tag: it has no beforeSend or fingerprint hooks, its runtime spawns workers from cross-origin CDN hosts (this page is COEP: require-corp), and it ships session replay on by default — which on a CAD canvas records customers' board geometry. @sentry/browser is imported in exactly one file so the vendor stays swappable, mirroring how lib/analytics.ts isolates Plausible. Also replaces the terminal-signature regex with a shared, unit-tested predicate (wasm/terminal-error.ts) used by BOTH the fatal overlay and the reporter, so they cannot disagree. The regex was a type check written as a string match and had three live holes: `RuntimeError` was listed but never appears IN `.message`; Chrome's bare "unreachable" and "null function" matched nothing (the v0.1.20 prod log is exactly those); and narrowing "table index is out of bounds" to `\bindex out of bounds` for Firefox in 197f317 silently stopped matching Chrome's spelling. Checking the TYPE — every trap in this family is a WebAssembly.RuntimeError — covers all engines and ends the spelling chase; the message patterns remain as a fallback for paths that lose the Error object, such as a worker ErrorEvent crossing the realm boundary with error: null. 197f317's pthread-worker tap, promote() and Firefox findings are kept as-is. Notes: - Off unless VITE_ERRORS_DSN is set AND VITE_ALLOW_USER_OVERRIDE !== "1" (dev servers and every Playwright harness set the latter, and production builds never do), so a production DSN in a local .env still cannot report. With no DSN the whole SDK is const-folded out: 1,193,080 vs 1,282,463 bytes of JS. - browserApiErrors integration removed. It wraps setTimeout/rAF/addEventListener in try/catch, which is exactly how KiCad-on-Emscripten drives its main loop. - Console breadcrumbs off (collab/debug.ts's clog fires per Yjs update and would evict the ring before any crash); dom/fetch/navigation breadcrumbs kept. - beforeSend redacts token/apiKey/Bearer — collab/provider.ts puts the collab token in the y-partyserver URL, so a connection-failure string carries a live credential — and guards the cascade: one wedge produced 8 errors in prod, and after the first terminal event the rest are dropped into cascade_count. Verified end to end against the real EU host from a cross-origin-isolated page: POST /api/<id>/envelope/ -> 200, and 4 terminal throws produce 1 event (control: 1 throw, same count). Privacy policy 9, cookie policy 6 and the licenses page are updated: Better Stack is disclosed as an EU processor, and the licenses page now describes the browser app's own JS dependencies, which it never did. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-03 12:24:30 +02:00
console.log(` VITE_ERRORS_DSN=${env.VITE_ERRORS_DSN ? `(set, env=${env.VITE_ERRORS_ENV})` : "(off)"}`);
// Keep the dev-only WASM symlink out of the bundle (it'd copy 100s of MB into
// dist/; the CDN serves it). In CI it isn't present, so this is a no-op there.
const hadWasm = existsSync(publicWasm) || isSymlink(publicWasm);
if (hadWasm) renameSync(publicWasm, stash);
try {
execFileSync(
"pnpm",
["--dir", "web", "--filter", "@pcbjam/standalone", "build"],
{ cwd: repoRoot, env, stdio: "inherit" },
);
} finally {
if (hadWasm) renameSync(stash, publicWasm);
}
// Belt-and-suspenders: never ship local wasm even if a copy slipped through.
rmSync(join(dist, "wasm"), { recursive: true, force: true });
for (const f of ["_headers", "_redirects"]) {
copyFileSync(join(repoRoot, "deploy/demo", f), join(dist, f));
}
console.log(`done → ${dist} (ready for: wrangler pages deploy)`);
}
function isSymlink(p) {
try {
return lstatSync(p).isSymbolicLink();
} catch {
return false;
}
}
main();