Read this only when editing the WebJs monorepo (this repo), not a scaffolded app. The repo is buildless: packages/ is plain .js with JSDoc (never add .ts there); TypeScript is fine in examples/, gallery/, and website/. Each in-repo app (website/, which serves the docs at /docs and the component gallery at /ui, plus examples/blog/ and the feature gallery/) is run from its OWN dir via npm run dev / npm start; as of #550 a bare webjs dev / webjs start is equivalent (each app's per-environment orchestration, the Tailwind watcher, webjs db migrate, the registry copy, moved into its webjs.dev / webjs.start tasks config, which webjs dev/start run). The sections below cover the repo-health git config, the changelog flow, and the dev error overlay.
The framework's own source is where the 800-line target and the roughly-1000
ceiling actually bite, since packages/ is plain .js with JSDoc and several
subsystems grew past both. The naming rule is settled for the whole monorepo:
the original file keeps its path and becomes the barrel, and its parts land in
a sibling directory named after it (src/slot.js stays, parts go in
src/slot/). Do not rename a barrel to match its public exports subpath. The
package.json exports map, the hand-written .d.ts overlays and the two
guard tests that derive a runtime sibling from an overlay path, the docs pages
that print importmap examples, and every relative test import all key off the
current path.
A split is a MOVE. Verify it two ways before running anything else: the barrel's
runtime export set must be identical to the pre-split module's in BOTH
directions (added empty too, since a behaviour-preserving split adds no public
surface), and every code line must survive byte-identical once comments and the
added export prefix are normalized away. Any line that changed needs a reason
in the commit message.
Four monorepo-specific traps, each of which has already cost a debugging session here:
packages/core/distis built, so a source edit is invisible until you rebuild it.npm run worktree:linkbuilds it in the worktree once (#1671), but after a split NOT rebuilding means e2e and Bun resolve the pre-split code and pass vacuously, so runnode scripts/build-framework-dist.js.- A relative
import.meta.urlwalk breaks when the file moves one level deeper.locateCoreDir's workspace fallback resolved three levels up to reachpackages/, and after the move needed four. It silently pointed at a directory that does not exist, and every/__webjs/core/*request 404d. - Drift guards read source files by path. Point each at the barrel PLUS
every module beneath it. An
assert.matchfails loudly, but anassert.doesNotMatchstarts passing vacuously. - The browser suite is mandatory for a renderer, router, component, or slot
split. Those defects are post-hydration, so
npm teststays green and the served bytes are unchanged.
The two in-repo apps (website, which serves the documentation at /docs and the component gallery at /ui, and examples/blog) deploy from ONE image built by the root Dockerfile, each run as a separate service with its own PORT (compose sets it locally, the platform injects it in prod). compose.yaml is local parity for that setup; the platform never reads it.
The readiness gate is the same /__webjs/ready endpoint the framework ships and documents (503 until fully warm, then 200, see the deployment docs page). Two seams carry it, because no single file configures every platform:
- Docker / compose / most Docker-based hosts: the root
DockerfileHEALTHCHECK(PORT-driven, dependency-freenode -e fetch) makes the image self-gate. This mirrorspackages/cli/templates/Dockerfile, the pattern the scaffold ships to users. - Railway: it IGNORES the Docker
HEALTHCHECKand only honours its ownhealthcheckPath.railway.jsondeclareshealthcheckPath: /__webjs/ready, but a service only applies it if it is wired to readrailway.json(config-as-code) AND built via the Dockerfile builder. A service left on the RAILPACK builder with no config-file path ignoresrailway.jsonentirely, so itshealthcheckPathis null and deploys serve a cold-start window. Wire each service torailway.jsonrather than settinghealthcheckPathby hand in the dashboard (dashboard values drift from the repo).
Net: edit the HEALTHCHECK for the Docker contract, keep railway.json for the Railway contract, and never hand-set deploy config in a platform dashboard.
Both subdomains used to be redirect-only apps in this repo (docs/ and packages/ui/packages/website/). They are two Cloudflare Redirect Rules now, on the webjs.dev zone, with no origin. Nothing here serves them, so this is the only in-repo record of what they do:
| Rule | Expression | Action |
|---|---|---|
| docs | http.host eq "docs.webjs.dev" |
301 static to https://webjs.dev/docs |
| ui | http.host eq "ui.webjs.dev" |
301 static to https://webjs.dev/ui |
Both are static rather than path-preserving, which is a deliberate trade rather than an oversight: every path on each host collapses onto its hub page. That was measured before the apps came out. No third-party page links to either host, neither had recent traffic, neither is in the sitemap, and the destinations were already canonicalised and indexed, so there was no ranking signal left to preserve.
Keep both rules. Already-published npm packages reach these hosts and can never be corrected. That is why the apps existed, and deleting the apps did not delete the reason. One consequence is already live: ui.webjs.dev/registry/<name>.json used to serve registry JSON and now redirects to an HTML page, so webjsui add is broken on the published @webjsdev/ui 0.3.1 through 0.3.8, which hardcode that URL and take the network path. 0.3.9 onward resolves local-first and never fetches it.
CI cannot see any of this. The two tests that asserted the redirect mappings went with the apps, and a job that reds when Cloudflare has a bad minute would be worse than the gap, so the behaviour is verified by hand:
for u in https://docs.webjs.dev/ https://ui.webjs.dev/ ; do
printf '%-28s -> ' "$u"
curl -sSI -m 15 "$u" | tr -d '\r' | awk 'tolower($1)=="location:"{print $2}'
donewebjs.dev sits behind Cloudflare, and the site's static assets (/public/tailwind.css, the brand SVGs) are served with cache-control: public, max-age=14400 at STABLE urls. Without an eviction the edge therefore keeps serving the PREVIOUS copy for up to four hours after a deploy. That shipped two visible regressions in one day (a pre-redesign stylesheet after #1179, then the un-fixed logo marks after #1185), and staleness is per-asset rather than all-or-nothing, so the site can look half-updated.
.github/workflows/purge-cdn.yml handles this on every push to main, whoever merged and however (#1652). #1594 had moved it to the merging machine, where scripts/ci-merge.sh started scripts/purge-cdn.sh in the background; that skipped silently whenever the shell lacked CLOUDFLARE_API_TOKEN or held an expired Railway login, and never ran for a merge done in the GitHub UI, so it went back to Actions. It does NOT purge immediately: a Railway build takes minutes, so an immediate purge would evict the cache while the origin still served the old bytes and the next visitor would repopulate the edge with exactly those. Instead the job asks Railway's GraphQL API for the deployment whose meta.commitHash matches the pushed sha and reads its real status, then issues a zone-wide purge_everything only on SUCCESS.
It runs after EVERY merge rather than only after a release on purpose: a package release is rare, while the site redeploys on ordinary merges. None of the four website merges on 2026-07-30 touched changelog/, so a purge tied to releases would have fired for none of them.
Reading the deployment status rather than inferring it is the second design (#1192). The first version watched the origin's /__webjs/version uptime for a restart, assuming every push to main produces a deploy. It does not: Railway marked #1189's own merge commit SKIPPED (it touched only .github and a .md), no restart ever happened, and the job failed after a 15 minute wait. Every docs-only commit would have been a red X, and a job that cries wolf on routine commits stops being read. So the status now decides:
| Deployment status | Action |
|---|---|
SUCCESS |
purge |
SKIPPED |
no purge, notice. Railway did not deploy, so the origin is unchanged and nothing is stale |
FAILED / CRASHED / REMOVED |
no purge, warning. No new content reached the origin |
| in progress, or no record yet | keep polling |
| nothing terminal within 15 minutes | no purge, warning, run still GREEN. Use the manual run below |
The purge is zone-wide rather than a path list: both asset-serving hostnames (webjs.dev, example-blog.webjs.dev) are proxied inside the one webjs.dev zone, so a single call covers them (docs.webjs.dev and ui.webjs.dev sit in the same zone but are Cloudflare redirect rules serving no assets), and a zone purge cannot silently miss an asset the way a hand-maintained list does. Purging evicts only; nothing is deleted.
-
Credentials: the workflow reads two REPOSITORY secrets (it declares no
environment:, so an environment-scoped secret would arrive empty). The manual script reads the same names from the maintainer's environment, and neither ever prints them.CLOUDFLARE_API_TOKEN, scoped to Zone / Cache Purge / Purge on thewebjs.devzone only. Do not reuse a broad account-wide token.RAILWAY_TOKEN(a Railway project token for theproductionenvironment), else therailway logintoken in~/.railway/config.json. A project token authenticates with theProject-Access-Tokenheader and an account token withAuthorization: Bearer, so the script tries both. An expired login reads as "the Railway API never answered"; runrailway login.
-
Manual purge: dispatch
purge-cdn.ymlfrom the Actions tab (gh workflow run purge-cdn.yml), which skips the deploy wait and purges straight away. Locally,scripts/purge-cdn.sh --nowskips the deploy wait and purges straight away;scripts/purge-cdn.sh <sha>waits for that commit;--dry-runreports the deploy status and purges nothing. -
Checking staleness by hand: compare the edge against the origin rather than trusting
cf-cache-status, since aHITon fresh content is fine and only differing bytes are a problem.curl -s https://webjs.up.railway.app/public/tailwind.css -o /tmp/o curl -s https://webjs.dev/tailwind.css -o /tmp/e cmp /tmp/o /tmp/e && echo fresh || echo stale
The assets that actually caused those incidents no longer depend on this purge. tailwind.css, the brand lockups and marks, and the highlight script are marked with asset() (#1194) in website/app/layout.ts, website/lib/design/brand.ts, and website/app/(site)/brand/page.ts (whose images AND download links are marked, so a designer cannot download the previous drawing while the thumbnail above it shows the new one), so each carries a ?v=<content-hash> and is served immutable for a year. examples/blog/app/layout.ts marks its stylesheet for the same reason, since example-blog.webjs.dev sits in the same Cloudflare zone. New bytes mean a new url, which no cache can serve stale.
Some urls are deliberately NOT marked, and that is the point of an opt-in helper rather than an automatic rewrite:
- the three font preloads, because the real request comes from
@font-face url()in the compiled stylesheet and CSSurl()is not rewritten. The preload cache is keyed on the full url, so a versioned hint could never satisfy the unversioned request, and each font would be fetched twice. - the favicons, whose hrefs are parsed literally by the SEO repo-health tests guarding the #1088 size bug, and where fingerprinting buys almost nothing.
The purge workflow therefore STAYS as the safety net for everything still on a stable url (an asset referenced from CSS, a srcset candidate, an un-marked path), and it remains the way to clear the edge after a deploy that changes one of those.
This repo uses git worktrees (the review subagents spawn throwaway ones under .claude/worktrees/). Git's worktree machinery can leave core.bare=true in the shared .git/config, which is lethal to the main checkout: every git operation that needs a work tree then fails with fatal: this operation must be run in a work tree. The shared value is harmless only while the main worktree carries a per-worktree override (extensions.worktreeConfig=true plus a .git/config.worktree pinning core.bare=false).
scripts/git-worktree-safe.mjs establishes that override and pins an absolute core.hooksPath to .hooks on the main worktree, where both survive a shared-config reset (which is what otherwise silently disables the framework .hooks/pre-commit). It runs from the root prepare script, so every npm install self-heals. Two manual entry points:
npm run fix:githeals the config on demand (run it if a git command reports the work-tree error).npm run check:gitasserts the invariant (core.bareresolves false, the framework hook is active) and exits non-zero otherwise. The regression test istest/repo-health/git-worktree-safe.test.mjs.
Because the pin lives in the main worktree's config.worktree, git worktree add copies it into each linked worktree, so a commit made inside a throwaway review worktree also runs the framework .hooks/pre-commit. That is harmless (the hook only blocks main and auto-generates a changelog on a version bump), and review subagents are read-only so they do not commit; the inheritance is noted here only so the behavior is not surprising.
npm run worktree:link (scripts/link-worktree-deps.mjs) links the dependency trees AGENTS.md describes, builds packages/core/dist in the worktree from its own sources rather than linking the primary's (#1671, skip with WEBJS_NO_WORKTREE_BUILD=1), and as its last step brings examples/blog's SQLite database up to a usable state. db/dev.db is gitignored, so a worktree starts with none, and an empty posts table fails three blog tests plus their enclosing progressive-enhancement suite with nothing in the output naming the cause. CI never sees this because all four jobs that boot the blog run db:migrate + db:seed first.
The guard is the row count, not the file. examples/blog/package.json runs webjs db migrate as a dev.before and a start.before step, so booting the blog once creates the file with an empty table and a file-existence check would skip forever after. The probe is a read-only node:sqlite open, which needs nothing installed. Rails' db:prepare has the same shape (seed an uninitialized database, leave an initialized one alone) and differs only in the probe, because there nothing but db:prepare creates the file.
It costs about two and a half seconds on a cold worktree and nothing once there are rows. The database path is resolved the way the blog resolves it (DATABASE_URL, falling back to db/dev.db), so the probe and the two commands always agree on which file they mean. A failure WARNS and leaves the link successful. Escape hatch: WEBJS_NO_WORKTREE_SEED=1. Regression test: test/repo-health/link-worktree-deps.test.mjs.
It runs below the primary-checkout guard, so worktree:link in the primary stays a no-op. That guard is not what keeps seeding out of the test suite, though. The defaultPrimary() repo-health test runs the script bare against its own cwd, and from a linked worktree (the mandated workflow) the guard does not fire, so the script would seed that worktree's blog database as a side effect of npm test, racing test/integration/blog-http.test.mjs reading the same file in parallel. That test therefore sets WEBJS_NO_WORKTREE_SEED=1 explicitly, and the helpers in that file strip the variable from the ambient env so an exported opt-out cannot invert the seed assertions.
npm run worktree:link symlinks a worktree's node_modules at the primary checkout's, which makes the worktree runnable and also puts a single writable path from every worktree into the primary's dependency tree. An install run inside a linked worktree therefore acts on the PRIMARY, and the damage lands on a session that did nothing wrong.
Measured on npm 11.19.0 and bun 1.3.14:
| Command, in a linked worktree | What actually happens |
|---|---|
npm install |
REPLACES the node_modules symlink with a real directory and builds a full tree there. The primary is untouched, but the worktree silently detaches and no longer runs the primary's framework source. |
npm ci |
DELETES the symlink's TARGET, meaning the whole of <primary>/node_modules, then builds a real tree locally. The primary and every other linked worktree break at once. |
bun add / bun install |
KEEPS the symlink and writes THROUGH it. New packages and .bin entries land in <primary>/node_modules. |
A preinstall script cannot prevent any of this. Under npm install it runs with node_modules already a real directory, because npm replaced the symlink before the script started. Under npm ci it runs with the primary already emptied, because npm deletes the link's target first. Under Bun it does run in time and does see the symlink, but a non-zero exit does not stop Bun (measured: bun install exited 0 with a preinstall that exited 2). A non-zero preinstall DOES block npm install and npm ci, exit code propagated verbatim, so a buggy guard there would red every CI job for no protection at all.
So prevention lives one layer up, and the rest is repair:
-
Block.
.claude/hooks/block-install-in-linked-worktree.shis aPreToolUse(Bash) hook, the only layer that sees the state before the package manager starts. It refuses an install verb whose target directory has a symlinkednode_modules, at the root OR nested (the link script plants one per workspace carrying its own tree, so a worktree whose root link was removed still holds nested links the install writes through).npm run worktree:unlinkremoves every one of those links, and the block message names it. The gate covers every manager's documented aliases (bun imatters most, since Bun writes THROUGH the link), the REMOVE verbs, andlink/rebuild/prune/audit fix, all of which mutate the tree the symlink points at. The tables are per manager, sobun upgrade, which upgrades the Bun binary, stays allowed whilepnpm upgradedoes not. Escape hatchWEBJS_NO_WORKTREE_INSTALL_GATE=1.It judges a COMMAND, never a token, in four stages. Quoted spans are neutralised FIRST, keeping their content but stripping the separators inside them, and heredoc bodies are dropped. The remainder is split on
&&,||,;,|,(,)and newlines. Each segment is then judged by its FIRST token, after leading env assignments and wrappers likesudoare stripped. Only inside a manager-led segment are the remaining tokens scanned, for the first one recognised as either an install verb or a known safe verb, so a flag sitting before the verb does not hide it. Matching the manager token anywhere in the line is the obvious shortcut and it is badly wrong: it blocksgit commit -m "fix: npm install ...",grep -rn "npm ci" AGENTS.mdandgit log --grep "npm install". A linked worktree is the mandated working state here, so that fires on ordinary commands constantly, and a gate that cries wolf is a gate someone turns off.npm test,npm run <script>,npx ...,npm initandyarn testall pass, and so does a GLOBAL install (-g/--global), which writes to the npm prefix rather than through the link and is this repo's documented post-release step. -
Report. The root
preinstallrunsscripts/warn-worktree-install.mjs, which ALWAYS exits 0 and returns immediately unless.gitis a FILE, so a normal clone and CI never see it. It names whichever of the three states it landed in and prints the repair. -
Build guard.
scripts/build-framework-dist.jsnever writes through a symlink at its out dir (#1671). A worktree linked before #1671 still carriespackages/core/distas a link at the primary's dist, and core'sprepareruns this build duringnpm ci. The build leaves the link alone until esbuild succeeds, thenunlinks it (never the target) and renames the finished staging directory into its place, so a failed build changes nothing and a concurrent reader never sees an empty dist. Test:test/packaging/build-dist-symlink.test.js. -
Undo.
npm run worktree:unlink(link-worktree-deps.mjs --unlink) removes everynode_moduleslink the link pass planted, root and nested, acting on the git toplevel from any subdirectory. It removes only links that point into the primary, so a real directory or a link you made to another tree is kept, and--checkalongside it is refused. Run it before a deliberate real install in a worktree. -
Repoint on teardown.
.claude/hooks/cleanup-merged-worktree.shrepoints any<primary>/node_modules/@webjsdev/*link targeting a worktree it is about to remove, before removing it. -
Repair on demand.
npm run worktree:linkrepairs the primary's@webjsdev/*scope: a dangling link, a link into a live foreign checkout, and an absolute in-primary link all become the relative form, and a DANGLING.name-HASHnpm staging entry is dropped. A LIVE staging entry is left strictly alone.npm run check:worktree-linksreports without writing and exits non-zero when there is work. Escape hatchWEBJS_NO_WORKTREE_REPAIR=1suppresses the repair WRITE only, so--checkignores it and still inspects; thedefaultPrimary()test needs the hatch for the same reason it needsWEBJS_NO_WORKTREE_SEED=1: the repair pass sits ABOVE the primary-checkout guard by design, so it runs in both positions and would otherwise rewrite the real checkout duringnpm test. -
Detect.
webjs doctor'sframework-linkscheck warns on a dangling or foreign@webjsdev/corelink.FRAMEWORK_RESOLVEcannot see the foreign case, because a link into a live checkout resolves perfectly.
Regression tests: test/hooks/block-install-in-linked-worktree.test.mjs, test/repo-health/warn-worktree-install.test.mjs, test/repo-health/link-worktree-deps.test.mjs, test/hooks/cleanup-merged-worktree.test.mjs, test/cli/doctor.test.mjs.
.github/workflows/ci.yml runs on every pull request into main and every
push to main, with every job's steps written inline (free on this public
repository). Nothing runs the suite locally as a gate: there is no root
webjs.ci list, no scripts/ci.sh, no pre-push hook. Run the layer you
touched by hand while you work (npm test, npm run test:browser,
WEBJS_E2E=1 node --test test/e2e/e2e.test.mjs, node scripts/run-bun-tests.js,
webjs check inside an app) and let Actions run the whole list on the PR.
The live jspm contract tests (*.live.test.*, network-bound) run nightly on
Actions too (vendor-cdn.yml, also dispatchable by hand).
The gate, merged with scripts/ci-merge.sh. main requires six
ci.yml job checks, strict, and NO review (scripts/protect-main.sh): the
owner reviews outside the merge path, and a review rule would block every
agent merge, so never add one. scripts/ci-merge.sh <N> waits for the
required checks on the PR head (gh pr checks --required --watch) and
squash-merges with --delete-branch --match-head-commit only when they are
green. It never uses --admin. Check the live protection with gh api repos/webjsdev/webjs/branches/main/protection --jq '.required_status_checks.contexts', which prints the six job names. A
release PR merges the same way, after its release gate passed on the PR head
(see "Releases" below). CI and the release both run on Actions (ci.yml, and
release.yml, which CI passing on a release merge commit triggers and which
is bound to trusted publishing), and so does the CDN purge (purge-cdn.yml,
on every push to main); scripts/release.sh is the manual fallback.
Local prerequisites for the suites: Node 24+, Bun, the Playwright
browsers (npx playwright install chromium firefox webkit), puppeteer-core
(a root devDependency), gh (authenticated), and a shell that does NOT export
FORCE_COLOR (it flips tsc to pretty output and reds two type guards that
parse the plain format). Every web-test-runner config takes a kernel-assigned
port (WTR_PORT pins one) so two runs at once cannot share port 8000.
gallery, examples/blog, and website each declare their own shorter list
(setup, then webjs check / webjs doctor / typecheck / tests two at a time)
and a ci script, so npm run ci inside an app is the app's gate. Their steps
go through the app's npm scripts on purpose: the website's pretest hook runs
scripts/copy-registry.mjs, which a bare webjs test would skip. Inside a
linked worktree run an app's list as node ../packages/cli/bin/webjs.js ci
(../../ from the blog) until the branch's CLI is on main.
webjs check is an APP-level tool: every rule assumes one application, meaning one module graph, one custom-element registry, one runtime. This repo's root is none of those, it is a workspace holding two apps plus every package's test suite plus editor fixtures plus the scaffold templates, so a root-level run used to walk all of it and report 67 collisions that no single runtime ever sees. my-counter, for instance, was reported as duplicated across a blog component, an editor-plugin fixture, two unit tests, and a type fixture, five files that never load together.
So the command now refuses in any directory with no app/, exits 1, and names the member apps to run instead. The two in-repo apps are examples/blog and website:
( cd examples/blog && npx webjs check )
( cd website && npx webjs check )Under --json the refusal is emitted as JSON rather than prose, { error: { code: 'NOT_AN_APP', message, cwd, apps } }, so an agent's parser does not choke. It carries neither violations nor summary on purpose: a consumer that ignores the exit code and reads report.violations.length should throw rather than be told a workspace is clean.
That is what .github/workflows/ci.yml has always done (it cds per app), which is why CI was green while the root-level run looked catastrophic. test/cli/check-target.test.mjs pins the two together: it parses the app list out of the for app in ...; do loop in the webjs check step and asserts set equality with the list the refusal derives from the root package.json workspaces globs. A third app added to CI is picked up automatically; one dropped from CI reds the test. That drift guard is what a --workspaces flag was rejected in favour of.
webjs doctor is deliberately NOT gated the same way. It already degrades correctly at the root (the route and asset checks report "no app to analyse") and its toolchain checks are meaningful in a workspace.
Per-task worktrees pile up when a session merges its PR but never runs git worktree remove (a skipped step, or a crash mid-task). The .claude/hooks/cleanup-merged-worktree.sh PostToolUse hook (matcher Bash, wired in .claude/settings.json) closes that gap: after any gh pr merge, it sweeps every linked worktree and removes the ones that are safe to drop, so cleanup is deterministic rather than a thing an agent has to remember.
It is conservative. A worktree is removed ONLY when it is a linked (non-primary) checkout, on a non-main/master branch, whose branch is MERGED (an ancestor of origin/main, OR a merged GitHub PR for that head branch, which is how squash-merges are detected via gh) AND whose working tree is clean apart from untracked node_modules / .webjs. It KEEPS anything dirty, unmerged, the primary checkout, or the worktree the merge was run from (you cannot remove your current directory; cd out and remove it manually), reporting each kept/removed worktree back to the model via hookSpecificOutput. It never blocks the tool (always exits 0). Escape hatch: WEBJS_NO_WORKTREE_CLEANUP=1. Regression test: test/hooks/cleanup-merged-worktree.test.mjs.
The fix only repairs the LOCAL checkout. Commits and branches are always safe on GitHub regardless.
Workflow skills live once at .claude/skills/<name>/SKILL.md. Antigravity reads
<workspace-root>/.agents/skills/<folder>/SKILL.md, so each one is mirrored as a
RELATIVE symlink .agents/skills/<name> -> ../../.claude/skills/<name>. Adding a
skill means adding the directory, the symlink, and a bullet in
.agents/rules/workflow.md; test/repo-health/agent-skill-parity.test.mjs
fails when the three drift apart. Create the link with ln -s so git records
mode 120000, and keep the target relative, or
test/repo-health/no-committed-symlinks.test.mjs rejects it.
One entry under .agents/skills/ is not a mirror: omarchy, a machine-local
absolute symlink kept untracked by .gitignore. (The app-facing teaching skill
that used to live at .agents/skills/webjs/ was removed; the brief in
AGENTS.md and the docs site replaced it.)
Lifecycle HOOKS stay Claude-only on purpose. Antigravity supports a workspace
.agents/hooks.json, but its blocking protocol (stdout {"decision":"deny"}),
its context-injection shape (injectSteps), and its tool vocabulary all differ
from Claude Code's, so a mirror is a protocol port rather than a config copy, and
a generated copy would be the duplicated rule set root AGENTS.md rules out. The
gates that bind every agent are .hooks/pre-commit and CI (#1372).
A new framework feature should ship a runnable gallery demo, not just a doc bullet.
The gallery is the standalone repo-root app gallery/, deployed at gallery.webjs.dev. You boot it (npm run dev:gallery, port 5005) and test it (npm test --workspace=@webjsdev/gallery, plus test/examples/gallery/) like website and examples/blog, so a framework change is validated against the demos. It ships in no scaffold: webjs create emits a minimal app whose only agent doc is the brief.
Enforcement is two tiers, mirroring how tests are enforced:
-
Tier 1 (commit floor):
.claude/hooks/require-scaffold-with-src.shblocks a commit that stagespackages/(core|server|cli)/srcwith no scaffold surface. It only proves you touched a scaffold file, so a documented-but-undemoed feature can still pass (this is exactly how #848 shippedforbidden()/unauthorized()with app-tree bullets and no demo). -
Tier 2 (CI gate):
test/scaffolds/gallery-coverage.test.jsreconciles the LIVE framework surface againsttest/scaffolds/gallery-coverage.jsonand FAILS when something new is neither demoed nor exempted. It gates three surfaces:@webjsdev/coreexports (a{ demo }gallery-file pointer),@webjsdev/serverexports ({ demoed: true }, verified by the gallery or a generated app importing it), and routing convention files (the stems DERIVED frompackages/server/src/router.js, each demonstrated by a file in the gallery or a generated app). It runs undernpm test, so a local--no-verifycannot skip it: a new export or convention turns CI red until classified. Thereconcile()/reconcileSet()cores are pure and their failure modes (new name, stale key, missing/over-claimed demo, empty reason) are proven with synthetic inputs alongside the real-surface assertions. The deferred backlog is tracked in #859.
When you add or rename a @webjsdev/core or @webjsdev/server export, or add a routing convention file the router parses, update the manifest the same way you write a test: add a demo pointer / { demoed: true }, or an honest exemption. All three surfaces are gated (the convention stems are derived from packages/server/src/router.js, so a new stem === '...' branch auto-appears and must be classified).
The scaffold gate is one of a FAMILY of tier-2 coverage gates that keep the framework's agent-facing surfaces from rotting behind a new feature. The others:
- Knowledge coverage (
test/knowledge/knowledge-coverage.test.js): reconciles the livewebjs checkRULESagainst the docs site (a new rule must be named on a page underwebsite/app/(site)/docs/, ideally the symptom-keyed troubleshooting page, or exempted inknowledge-coverage.json). The MCPinitprimer returns the brief frompackages/mcp/src/brief.js, andtest/repo-health/brief-parity.test.mjskeeps its twoAGENTS.mdcopies identical. - API docs + test coverage (
test/api-coverage/api-coverage.test.js): every agent-facing@webjsdev/core+@webjsdev/serverexport (NON-internal per the scaffold manifest, the single source of truth) must be referenced in the docs corpus (AGENTS.md + docs site) AND in a test. A new public export that ships undocumented or untested turns CI red. - Types round out the family and keep the hand-written
.d.tsoverlays (the@webjsdev/coreand@webjsdev/servertype surface VSCode / Neovim show) honest from three angles, per publishedexportsentry (the overlaytypesfor.plus every subpath, mapped to its sibling.js):dts-export-coverage.test.mjsproves every runtime export HAS a declaration (#388, forward direction). It READS the entry list from each package's ownexports(#1291), so a new subpath is forward-checked with no edit to the test; before that it ran over a hardcoded three-element array while fifteen overlays existed, leaving twelve subpaths unguarded in this direction. Each overlay is checked against its sibling.js, never the bare package specifier: Node resolves a bare specifier through thedefaultcondition, and four core subpaths (./directives,./context,./task,./client-router) all collapse ontodist/webjs-core-browser.js, so a bare import judged each of those overlays against the whole bundle's 101 names rather than its own module's surface, and the guard could not run at all untildistwas built. A leading_is exempt as a test-only seam (theInternal exports for unit testingblock insrc/router-client.jsis 63 such names), written as a rule rather than an ignore list that would rot with every new unit test. Three floors keep the widened guard from passing vacuously: a per-package entry count matching the reverse guard's, at least one checked name per entry, and a per-package checked-name total, which catches an entry that still resolves but to a smaller module than intended.dts-no-phantom-exports.test.mjsproves the REVERSE, that every VALUE export an overlay declares EXISTS in its NODE runtime sibling, so a type-checkingimport { x }cannot crash withxundefined on that surface (#1031). It maps each overlay to its runtime.jsby SIBLING (foo.d.tsoverlaysfoo.js), not asourcefield (most entries have none), enforces a per-package entry-count floor, and asserts it still detects a KNOWN phantom on the real package, so a resolution break degrades to a loud failure, never a vacuous pass. The@webjsdev/core.overlay is DUAL-surface, so it is checked against BOTH runtimes: the Node siblingindex.jsand the browser entryindex-browser.js(read from the server importmap), the latter allowlisting the five intentional server-only strips (renderToString/renderToStream/setCspNonceProvider/setAssetUrlProvider/setFormActionResolver) with a positive control that they stay stripped, so a NEW value the overlay declares that the browser bundle drops is caught as a browser phantom (#1035). Third,complex-export-signatures.test-d.ts(via thetype-fixtures.test.mjsrunner) pins the signatures of the complex exports (WebComponent,Task,ref,repeat, context) positively, because those overlays are deliberately richer than the loose JSDoc and an automatic shape-diff is all false positives on them. A KNOWN-real phantom deferred to a follow-up sits inKNOWN_PHANTOMSwith its issue link and is deleted when that fix lands.server-types.test.mjsand llms.txt (test/docs/llms.test.mjs) complete the family. Each reads its live surface dynamically so it cannot go stale.
No required check may FAIL because a third party is down. The required Unit + integration job used to resolve vendors against the live jspm CDN, so a jspm outage redded pull requests that had nothing to do with vendoring; PR #1149, a five-file documentation change, is the one that finally made the case (it failed on the #448 gitignore-healing test and passed on a re-run of the identical commit).
Plenty of required tests still TRY. No in-repo app carries a pin file, so every test that cold-boots one (test/preload-subset.test.mjs, the test/docs/* boot tests, test/integration/blog-http.test.mjs) asks resolveVendorImports to resolve its vendors on the first request. Under the deny those calls get a 503 without leaving the process, and each test still passes in a few seconds, because the resolve fails OPEN: an unreachable CDN yields a partial importmap and a warning, never a throw, and none of them assert on a vendor entry. That is what makes denying safe rather than disruptive, and it is why the deny prints one line per refused url: the list is there if that ever stops being true.
The rule is carried by the FILENAME, so the test runners can enforce it rather than leaving it to discipline. scripts/run-node-tests.js and scripts/run-bun-tests.js both drop any *.live.test.* file unless WEBJS_REQUIRE_NETWORK=1 is set. Everything else resolves against test/fixtures/jspm-double.mjs, an offline double that models jspm rather than merely answering it (a 5xx or 429 is transient and retries per package, a 4xx probes per install, and an unresolvable install fails the WHOLE batch, which is the premise jspmGenerate's fallback ladder is built on).
This replaced a WEBJS_SKIP_NETWORK_TESTS gate that could not work: it was opt-OUT, so CI, which never set it, always ran live; it was convention rather than something the runner could check; and two registry.npmjs.org callers were never covered by it at all. Leaving the one live parity test gated in place would not have been enough either, since after #1219 it still reds on a 4xx, and a WAF 403 or a moved route is exactly the shape #1149 hit.
Four things to keep in mind when touching this.
A new vendor test uses the double, not the network. withJspmDouble(opts, body) installs it, clears the vendor caches on both sides, and fails the test on any request the double was not asked to serve. Refusals are RECORDED rather than thrown on purpose: every fetch caller in the packages/server/src/vendor/ tree catches (jspm.js, integrity.js, resolver.js, audit.js; vendor.js itself is now the barrel), so a throw would be indistinguishable from the CDN being down and would quietly weaken whatever test hit it. The runtime deny answers 503 for the same reason, since that is the shape those call sites classify as transient.
The deny is at RUNTIME, and that was learned the hard way. Both runners preload test/fixtures/deny-live-hosts.mjs, which answers 503 for jspm.io and registry.npmjs.org unless WEBJS_REQUIRE_NETWORK is set. It needs no parsing, and within the test process it has no blind spots (a spawned child is the exception, below). It covers the transitive callers a source scan structurally cannot see: the app-boot tests reach jspm through resolveVendorImports with no fetch( anywhere in their own source. A test that depends on a third party now fails on EVERY run rather than only during an outage, which arrives the day it is written instead of months later.
The first three attempts were a STATIC scan over test sources, and each went blind a different way: a file-level exemption, so one withMockedFetch anywhere excused every live call in the file; then no regex-literal awareness, so /rel=["']modulepreload["']/ desynced the mask to end of file; then regex awareness that read the / in </li> inside a nested html`...` template as a regex opener, swallowing the closing backtick. Each fix opened a new hole, because deciding whether a / starts a regex means lexing JavaScript, and a hand-rolled lexer facing nested template literals full of markup will keep being wrong. Do not reintroduce it. If the deny needs to be tighter, tighten the deny.
A spawned child does not inherit the deny. test/vendor-cli/vendor-cli.test.mjs runs the CLI in another process, so it passes its own preload and asserts a [jspm-double] armed marker on every spawn, which reds all ten of its tests if the flag is dropped. A new test that spawns a process and vendors needs the same treatment.
The nightly is what stops a permanent skip from hiding. .github/workflows/vendor-cdn.yml runs the live files with WEBJS_REQUIRE_NETWORK=1, which selects them and lifts the deny. It does NOT promote their upstream-trouble skip into a failure: a jspm outage is not a regression, and a job that reds on one is a job whose reds get ignored. WEBJS_FAIL_ON_SKIP=1 promotes, by hand, and the nightly does not set it; a skip surfaces as a warning annotation instead. A genuine failure opens or comments on one fixed-title tracking issue, since GitHub notifies only the workflow file's last committer about a failed scheduled run.
Do not add a pull_request trigger to that workflow. A live check on a PR is a live check whatever job it sits in; making it non-required would just produce a red somebody is told to ignore, which is how a real failure gets ignored too.
.github/workflows/ci.yml is deliberately not involved. Eleven jobs share its on: block, so the filter belongs in the runners, where it also covers a local npm test.
No @webjsdev/* release merges until the release gate passes. 0.8.85 and 0.8.86 shipped with green unit suites and still broke real Bun apps (a dynamic # import of a server module 500'd every project page in Crisp; a bound form action failed after any edit), because nothing ran the PACKED packages inside a real app. The gate does:
- the suites:
npm test(Node) andnode scripts/run-bun-tests.js(Bun); runnpm run test:browsertoo; - a fresh
webjs create --db postgresapp on Bun AND Node with the candidate packed bynpm pack(core'sdistis rebuilt first): every static page renders, sign up and log in, a bound<form action=${fn}>,headers()request context, a*.server.tswith relative imports reached statically and throughawait import('#...'), then the agent-style reload stress (scripts/dev-reload-stress.mjs) and every check again after the edits, thenwebjs checkandwebjs typecheck; - with
--crisp <crisp>/apps/web, the downstream smoke: the candidate swapped into Crisp's install (restored after), Crisp's server and browser suites, and a freshbun run devloading/,/dashboard, the provisioning module chain, a server action (createProject) and/projects/<id>, before and after an edit (GATE_CRISP_PROVISION=1also waits for a real project to provision).
It needs a Postgres at GATE_PG (default postgres://crisp:crisp@localhost:5432) and creates and drops its own databases. Paste its summary into the release PR. If a release is found broken after publish, deprecate it at once (npm deprecate @webjsdev/<pkg>@<version> "<why>; use <good version>") and ship the fix through the gate.
The release gate packs all six npm libraries, including UI and IntelliSense, and overrides their dependency ranges with candidate tarballs. This allows coordinated minor releases to be verified before any dependency is published.
WebJs ships per-package per-version changelogs under changelog/<pkg>/<version>.md. The model: a version bump is the trigger. When any commit on main changes the version field in packages/<pkg>/package.json, the scripts/backfill-changelog.js generator emits a new changelog/<pkg>/<version>.md summarising every conventional-commit (feat: / fix: / breaking: / perf:) that landed in that package since the prior bump. The website renders the union of all packages' files at /changelog.
How it works for AI agents and humans:
- Bump the
versionfield in apackages/<pkg>/package.jsonand stage the change. Bumping@webjsdev/intellisenseadditionally requires a re-vendor in the same commit (node packages/editors/nvim/scripts/vendor-intellisense.mjs, thengit add -f packages/editors/nvim/vendor), because webjs.nvim ships a committed copy of that manifest andpackages/editors/nvim/test/vendor-sync.test.mjscompares it in full. - Run
git commitas usual. The.hooks/pre-commithook detects the staged bump, runsnode scripts/backfill-changelog.jsautomatically, stages the resultingchangelog/<pkg>/<version>.md, and lets the commit proceed. The bump and its release notes land in the same commit. - Optionally review and edit the generated file before pushing. The script's body excerpts are the first lines of each commit message; for
breakingentries especially, add migration notes by hand. Re-runs are idempotent (existing files are never overwritten), so hand-edits survive. - Never edit
changelog/<pkg>/<version>.mdfor a version that has already been published. Bump the version and editchangelog/<pkg>/<next>.mdinstead.
If the package has zero feat: / fix: / breaking: / perf: commits in the range (a release-only bump with no user-facing changes), the script writes nothing and the hook fails the commit. Either add a hand-written entry, downgrade the bump if it was unintentional, or git commit --no-verify to bypass.
The whole flow is tool-agnostic: the universal pre-commit hook fires for every git commit, regardless of who or what is running it. AI agents using Claude Code, Cursor, Copilot, Aider, etc. all get the same behavior, as do human contributors.
npm publishes AND GitHub Releases come from the same files, and a merged release PR publishes them on its own (#1650). Run the release gate (node scripts/release-gate.mjs) on the release PR's head and paste its summary into the PR, then merge it through scripts/ci-merge.sh <N> like any PR. When CI completes green on that merge commit, .github/workflows/release.yml runs (its workflow_run trigger names ci.yml by its name:, CI), checks out that exact commit, finds the changelog/**.md files it added, and publishes them: npm.com, GitHub Packages, the GitHub Releases, and the lockstep wrappers when @webjsdev/cli moved. A push that adds no changelog file stops after a checkout and a git diff; a PR's CI run and a red run never publish. The CDN purge is a separate workflow, purge-cdn.yml, which every push to main runs, release merges included (#1652). scripts/release.sh remains the manual and recovery path (between #1594 and #1650, while CI ran locally, it was the only one): it requires the commit green on GitHub CI, pushes the tag publish-<sha12> (the workflow's other trigger), waits for npm view to serve every new version, creates any missing GitHub Releases, and purges the CDN; every step is idempotent, so running it after an automatic release changes nothing. For each new file:
scripts/publish-npm.jsparses the frontmatter, checksnpm view @webjsdev/<pkg>@<version>; if the version is not yet on the registry, it runsnpm publish --workspace=@webjsdev/<pkg> --access=public. Idempotent: already-published versions are skipped.scripts/publish-release.jscomposes a tag<pkg>@<version>(e.g.core@0.6.0), title@webjsdev/<pkg> <version>, body (the markdown after frontmatter), then runsgh release create. Idempotent: existing release tags are skipped.
npm runs first; if it fails, the run stops before the GitHub Releases. After fixing, dispatch release.yml with republish_paths (or run scripts/release.sh, which re-pushes nothing that exists): every step is idempotent. Re-running a FAILED release run does not pick up a fix (see below), but re-running a red CI run on the merge commit does publish, since its green completion triggers release.yml again.
npm authentication is trusted publishing (OIDC), not a stored token. The job declares id-token: write, and the npm CLI detects the Actions OIDC environment and exchanges that id-token for a short-lived, workflow-scoped credential. There is no NPM_TOKEN secret, nothing to rotate, and nothing that expires. The GITHUB_TOKEN the GitHub Packages and Releases steps use is auto-provisioned. Free for public repos.
Three things this couples, all of which break every publish if changed carelessly:
- Each of the 8 published packages carries its OWN Trusted Publisher configuration on npmjs.com (trusted publishing is per package, not per repo), naming owner
webjsdev, repowebjs, and workflowrelease.yml. That includes the two unscoped wrappers,create-webjsandwebjsdev. Renamingrelease.yml, the repo, or the org breaks publishing until all 8 are updated, and the failure surfaces as an opaque404 Not Found - PUTrather than an auth error. registry-urlin thesetup-nodestep is load-bearing. It writes the.npmrcnaming the registry the exchange authenticates against. Dropping it as "only needed for tokens" breaks the exchange.- Do not upgrade npm past the bundled 11.19.x. Trusted publishing needs npm >= 11.5.1, which Node 24 already satisfies. npm
latestis 12.x, and npm 12 enables install-time security defaults (allowScriptsoff) that block esbuild's postinstall, sopackages/core/distnever builds.
A brand-new package generally cannot be created by trusted publishing, so its FIRST publish may need a one-off manual one before its Trusted Publisher configuration takes over.
Recovering a release whose npm publish failed: use the republish_paths dispatch input, NOT a re-run. Re-running the failed run does not work, and the reason is easy to miss: a re-run replays the workflow file from its ORIGINAL commit, so a run that predates a fix to release.yml never sees the fix, however long ago it was merged. Merging a fix does not re-trigger anything either, since the workflow fires only on a push touching changelog/**. So run the workflow from the Actions tab with republish_paths set to the changelog files to publish:
changelog/core/0.7.52.md changelog/core/0.7.53.md changelog/server/0.8.66.md
Space or comma separated. Every path is validated to exist before anything publishes, because a typo that silently published nothing would look exactly like success. The set is then sorted by its date: frontmatter ASC, the same ordering the push path uses, so core still publishes before server and npm's latest tag lands on the newest version rather than on whichever path was typed last. Every publish script is idempotent, so naming an already-published version is a no-op. Listing a cli changelog also republishes the two unscoped wrappers at that cli version.
You can only republish a version the workspace still holds. npm publish --workspace=<pkg> ships whatever is in that package's package.json, not the version the changelog file is named for, so once a package bumps past a version, that older version can never be republished from main. scripts/publish-npm.js compares the two and skips with a message naming both, rather than publishing the tree's version under the older version's name. That is exactly what it used to do: republishing changelog/core/0.7.52.md shipped 0.7.53 under the log line published @webjsdev/core@0.7.52, and the next file in the batch then failed with E403 cannot publish over the previously published versions, taking every remaining package with it. Getting a skipped version onto the registry after the fact is genuinely awkward, so weigh it against just releasing the next patch. Trusted publishing is bound to release.yml runs on this repo, so a local checkout of the old commit has no credential path: OIDC does not exist outside the workflow, and that commit's workflow file expects a NPM_TOKEN that no longer exists. It would take a granular token minted for the occasion, or a staged publish. A superseded version is usually not worth either.
This replaced a NPM_TOKEN repo secret that expired at npm's 90-day cap on granular write tokens and silently failed two consecutive releases (#1456). Tokens were a dead end regardless: npm removes direct publishing for bypass-2FA tokens around January 2027, leaving only OIDC or a staged publish that a human approves with 2FA.
When server or the scaffold consumes a NEW @webjsdev/core export, core MUST publish first. packages/server/src/dev/handler.js and context.js import core symbols statically (setAssetUrlProvider, setCspNonceProvider), and webjs create emits an app that imports them too. A server published against an older core dies at module load with does not provide an export named ..., and a cli published first makes every freshly scaffolded app 500 on every route. Two things force the right order:
- Give
changelog/core/<version>.mdthe EARLIESTdate:of the batch. The publish loop sorts by that timestamp ASC, and the tie-break on equal timestamps is filename DESC, which would publishserverBEFOREcore. The loop isset -esequential, so core-first is also the fail-safe order: if core's publish fails, nothing after it ships and no skew can reach the registry. - Bump the declared range in the same release PR.
packages/server/package.jsonstill declares"@webjsdev/core": "^0.7.1", which every published core satisfies, so npm cannot catch the skew. Raising it to the version that actually carries the new export makes the resolver enforce the coupling permanently, independent of publish order. The scaffold cannot be range-protected (it installs@latest), so it relies on the ordering above.
Update the global CLI after the publish lands. The maintainer scaffolds and dogfoods with the globally installed webjs CLI, which lags a release until refreshed. So once release.yml has published (verify npm view @webjsdev/cli version matches the released version), refresh the global CLI on every manager: npm update -g webjsdev, bun add -g webjsdev, and mise use -g npm:webjsdev@latest. Run them AFTER the publish, never at merge time (they pull the LATEST PUBLISHED version). The mise use line is the one that actually moves a mise-shimmed webjs (a shim on PATH ahead of the npm/bun globals); verify with mise which webjs. This is reminded automatically by the .claude/hooks/release-global-update.sh PostToolUse hook, which fires when a chore/release-* PR merges (escape hatch WEBJS_NO_RELEASE_GLOBAL_UPDATE=1, regression test test/hooks/release-global-update.test.mjs).
In development, three error sources push a structured error frame to the open tab over the existing live-reload SSE channel (a distinct webjs-error event, NOT EventSource's native error), and a small dev-only client renders a plain-DOM overlay without a manual reload: an SSR render crash (a page / layout throws, or the no-browser-globals walker trips), a non-erasable-TypeScript strip failure (which breaks only the CLIENT module fetch, so the page still SSRs but hydration is silently dead, the exact gap this closes), and a failed rebuild (previously only logged server-side). The overlay carries the message, the parsed file:line:column, a source code frame of the offending line with context, and for a TS strip the no-non-erasable hint surfaced in the UI rather than buried in a JS comment. A successful rebuild clears it (the reload also dismisses any on-screen overlay), and the current frame is replayed to a tab connecting after the breaking edit. A page render that reports a new error also answers X-Webjs-Dev-Error: 1 (#1689, dev/serve.js), and the in-place refreshPage that receives it applies nothing (router-client/fetch-apply.js), so the last good page stays on screen under the overlay and the edit that fixes it refreshes in place instead of hard-navigating.
A render frame is scoped to the URL that produced it (#1047). A render frame carries that url, and the browser half is the single gate deciding whether a frame belongs on the page currently being viewed, so an overlay comes down when the client router navigates away and never goes up for someone else's page. Three consequences worth knowing. A speculative link PREFETCH of a throwing page reports no frame at all, so hovering a link cannot break the page you are looking at (the reported symptom: the frame fans out to every open tab over the shared SSE channel, with no navigation anywhere). A render error in one tab raises nothing in a tab viewing a different page. And a successful render of a url supersedes a retained error for that SAME url, so the replay cannot hand a recovered error to a freshly-connected tab; a good render of an unrelated page deliberately leaves it standing. ts-strip and rebuild frames carry NO url and are never scoped, because they describe a still-broken build rather than one page, so navigation leaves them alone and only the next successful rebuild clears them. The gate is order-independent: the SSE frame is pushed during the render, before the navigation response is even sent, so a frame for the page being navigated TO is held and rendered once the URL advances. A held frame renders only for the navigation it belongs to, so one that arrived while the tab sat idle is dropped rather than painted on a later visit, when the page may well render fine. An idle-time frame comes from a render this tab did not navigate for (another tab's page, a background fetch of some other url), never from a link prefetch, which reports nothing at all. Mechanism: renderDevOverlay + syncDevOverlayToLocation + installDevOverlayNavSync in packages/server/src/dev-overlay.js, wired by the dev reload client to the client router's webjs:navigate and popstate (a navigation finished) plus webjs:before-cache (a navigation STARTED, since the router snapshots the page it is leaving first). That last one also detaches the overlay across the snapshot read and re-attaches it a microtask later, so the cached HTML never carries a copy the module does not own; what it must not do is strip the overlay for good, which would tear a rebuild overlay off the page on any link click. packages/core is untouched by any of it.
A reload is coalesced (#1397), so after a burst of edits the page reloads once the edits settle rather than once per saved file. The relay holds a batch of reload frames until they stop for a quiet window, or at most 5 seconds (RELOAD_MAX_HOLD_MS) into a sustained burst, then applies the STRONGEST verdict of the batch (reload > shell > page > component > css, see the dev-classify.js row in packages/server/AGENTS.md) with the union of its changed files (a frame is one line of JSON, { v, by, why, seq, inPlace, modules?, css? }, where modules lists the versioned browser urls a component verdict re-imports). A server that applies edits in place marks its frames inPlace, and a batch made only of those waits just 300ms (RELOAD_QUIET_IN_PLACE_MS, #1575). Since #1689 that is the normal case on BOTH runtimes: Bun's one long-lived dev server, Node's one long-lived server (a module.registerHooks resolve hook re-evaluates the edited chain, packages/server/src/dev/esm-hot-hooks.js), and --no-hot. A batch holding a restart signal (a changed boot id when the tab reconnects to a restarted process: a .env / package.json / lockfile / instrumentation.* / env.* edit, a crash, or a Node with no registerHooks) keeps the 2 second window (RELOAD_QUIET_MS), because acting on the first signal would reload into a server about to be killed. An error overlay is never held, since it is not a reload. Every full reload stores its { why, by } in sessionStorage and the page that loads next prints [webjs] full reload: <why> (<by>) (dev-reload-reason.js), so when a reload looks wrong, read that line first: it names the rule that forced it.
The stream is quiet, and only open while a tab is visible (#1507). A host that sleeps on network quiet (a sandbox that suspends after an idle window, a laptop) counts an in-flight request and bytes on the wire as activity, and the reload stream used to supply both forever: a : ka comment every 25 seconds per tab, for every tab open, visible or not. Now SseHub writes nothing between events, and each listener shell switches its idle timeout off for that one request (server.timeout(req, 0) on Bun, setTimeout(0) on node) rather than keeping it busy. The relay in dev-reload-worker.js holds its EventSource open only while some tab reports itself visible (visibilitychange, pagehide, a bfcache pageshow), closes it when the last one hides, and reopens it when one shows. Nothing is lost meanwhile: hello carries { boot, seq }, seq counting the reload frames the process has sent, so a reconnect that sees a different boot id or seq reloads. A dropped stream is retried by the relay with backoff (300ms doubling to 30s, reset by the next hello), never by the browser's fixed retry, and not at all while every tab is hidden. An open request is activity too, so quiet is not always enough. Measured on a pilots sandbox: a machine with a 20 second idle window stayed running for minutes with one silent, open SSE request in flight, and suspended about a minute after a plain request with nothing open. A host like that counts the in-flight request for its whole life. For it, webjs.dev.reloadIdle (seconds, or WEBJS_DEV_RELOAD_IDLE, off by default) makes the relay close the stream after that long with no edit and no interaction in any visible tab; the next interaction (tabs report pointer, key, wheel, touch and focus at most once a second), a tab showing, or an embed-bridge host command reopens it, and the hello seq reloads the page if an edit landed meanwhile. It is opt-in because local editing with the browser untouched is exactly the case live reload exists for. A frame no stream carried is recovered from the page itself (#1516). A host that holds the quiet stream across a suspend closes it at the next wake, and the reload the wake caused is written to that dead stream; a fresh relay (a new SharedWorker, or the per-tab fallback) has no previous hello to compare with; a tab that connects after a fanout never got it. So in dev every page renders <meta name="webjs-dev-reload" content='{"boot","seq"}'> from the SseHub (through setDevReloadState in dev-reload-state.js, set by startServer; an embedded createRequestHandler has no stream and renders none), the client sends it to the relay as { type: 'page' }, and the relay reloads any tab whose page differs from the server's state on that message and on every hello, targeting only the stale tabs. A tab it has reloaded is recorded as current. Nothing else in webjs dev issues a request on a timer: the /__webjs/version readiness probe runs only after a reload signal, and prefetch is driven by hover, focus and viewport, not a clock. Tests: test/dev/browser/reload-worker.test.js, test/listener/listener-core.test.js, test/e2e/dev-idle-stream.test.mjs.
The overlay client uses textContent throughout (never innerHTML), so the error content cannot inject markup. It is strictly dev-only: reportDevError early-returns when !dev, /__webjs/reload.js 404s in prod, and the prod 500 stays terse (only error.message, never the stack or a file path), so no source leaks. An embedding host can observe the same frames via the onDevError option on createRequestHandler / startServer. In the browser, renderDevOverlay dispatches a webjs:dev-overlay DOM event (detail { kind, message, file, line }) each time an overlay actually goes on screen, after the url-scope gate, which is what the dev embed bridge (#1498, dev-embed-client.js) relays to a framing host as server-error. Mechanism: buildDevErrorFrame in packages/server/src/dev-error.js, reportDevError + the SSE push in packages/server/src/dev/handler.js, the SSR-catch hook in the packages/server/src/ssr/ tree. (dev.js and ssr.js are barrels since #1365; the code is one level down.)
Read this before splitting a large source file, and before arguing about how big a module is allowed to be.
Two things live here. The first is what "well structured" means in this repo, which is mostly judgment rather than a number. The second is the mechanical procedure for barrelling a large module into a directory, which is NOT judgment: it has a small number of failure modes that are silent, and every one of them has bitten this codebase already.
SOLID, DRY, and KISS apply here the way they apply anywhere. They are prose
guidance, followed by judgment, and deliberately NOT enforced by webjs check.
That split is the same one the rest of the project uses: webjs check carries
correctness rules only (code that is wrong to ship), and anything a sensible
project could reasonably do differently stays a convention.
What they mean in practice, in a buildless framework whose source IS what runs:
- Single responsibility is about what a module OWNS, not how long it is. A
module owns one concern when you can state that concern in a sentence without
the word "and".
router-client/prefetch.jsowns speculative fetching. It is 584 lines, and it is one responsibility. - DRY applies to knowledge, not to text. Two identical lines that would change for different reasons are not duplication. A constant that appears in three places IS, which is why this repo has drift guards that read one copy and assert it against another (see the guard section below).
- KISS beats cleverness in a framework more than in an app. The source is the documentation surface for the AI agents that use WebJs, and it ships unbundled to be read. An indirection that saves five lines and costs a reader a jump is a bad trade here.
- Dependency direction matters more than dependency inversion. Modules layer
downward: constants at the bottom, then pure helpers, then orchestration.
Nothing imports upward. This is not architectural taste, it is what keeps ESM
cycles out (see below). Two subsystems are genuinely mutually recursive and
cannot layer, the client router (a navigation fetches, the fetch swaps, the
swap upgrades, an upgraded element navigates) and light-DOM slots (projecting
installs the interceptors, an intercepted mutation re-projects). Those two are
named in
test/architecture/import-cycles.test.mjs, which fails on any THIRD cycle, so the rule holds everywhere it can.
A source module targets 800 lines and should stay around 1000 at the most. The ceiling is approximate on purpose. A module at 1040 is fine; one at 1900 needs either a split or a named exemption (below), and the question to ask at that size is which responsibility it has picked up rather than how many lines it has. A barrel is exempt entirely, because its length is a function of how many names it re-exports.
Where this number comes from. It was set by measuring the frameworks this project takes its cues from, not by picking a round figure:
| Module | Lines |
|---|---|
lit/packages/lit-html/src/lit-html.ts |
2303 |
lit/packages/reactive-element/src/reactive-element.ts |
1754 |
vite/packages/vite/src/node/optimizer/index.ts |
1487 |
vite/packages/vite/src/node/server/index.ts |
1447 |
Every one of them draws its seams by responsibility and lets the orchestration entry stay large. None of them enforces a line count.
A much smaller cap is a bad trade, and this repo has the measurement.
Splitting ten modules into about ninety produced three bindings that needed
accessors because ESM forbids assigning an imported binding, one dropped import
that threw only inside a deferred callback, one symbol identity swap that
silently broke slot forwarding, and three drift guards that broke or would have
passed vacuously. Four of those six were invisible to npm test. Every module
boundary is a place where those failures can happen, so boundaries are worth
adding for cohesion and worth nothing when added to hit a number.
There is also a runtime cost. In dev the browser fetches core source files individually rather than the bundle, so N modules is N requests at one more level of import-graph depth.
The ceiling is measured with a RAW line count (the number wc -l prints,
the number you see when you open the file), because that is how #1365 specified
it and because a metric a reader cannot reproduce by looking at the file invites
argument about the metric instead of the module. The tension with dense
documentation is real: this repo's comment style can put a well-factored module
at twice its code size, and a raw ceiling must never become a reason to delete
explanation. The answer to that tension is the exemption list, not a different
metric.
There is deliberately NO CI guard for this. A line-count gate is a proxy
metric that fights cohesion: it reds forever on a generated data table like
html-entities.js, and it has to carry an exemption list that rots. So the
ceiling is a REVIEW-TIME check, not a test. Measure it when you split something:
find <the tree you produced> -name '*.js' -exec wc -l {} + | awk '$1 > 1000 && $2 != "total"'A module that genuinely cannot or should not go under the ceiling gets a NAMED exemption, argued in the PR that produces it, with its measured size and its reason. The three exemptions the #1365 split carries show what a valid reason looks like:
- lit parity (
component/lifecycle.js): the file tracks lit'sreactive-element.ts, which lit keeps WHOLE at 1754 lines, and the project's standing decision is to keep lit-derived code close to lit rather than restructure it. - mutual recursion (
render-client/parts.js): the apply and instance group calls back into itself, so a real split creates the import cycle the D4 rule forbids, and the escape (a runtime dispatch registry) is a worse trade. - a single closure over shared request state (
dev/handler.js): splitting means threading that state through a context object, a high-risk rewrite of every app's boot path for zero behaviour gain.
Note what a valid reason is NOT: "it is mostly comments." If a module is over the ceiling only because it is well documented, that is a signal the ceiling is being measured too literally, not grounds for an exemption. Say why the CODE cannot be split, or split it.
The naming rule, settled once for the whole framework: the original file keeps
its path and becomes the barrel, and its parts land in a sibling directory named
after it. So packages/core/src/slot.js stays, and its parts go in
packages/core/src/slot/. Do NOT rename the barrel to match a public export
subpath. The package.json exports map, the hand-written .d.ts overlays and
their two guard tests, the docs pages that print importmap examples, and every
relative test import all key off the current path.
A split is a MOVE, not a rewrite. Retyping a function while relocating it is
how a refactor with a green export surface ships behaviour changes. Move the
lines verbatim. The only edits a move should produce are the export keyword
where a declaration now crosses a module boundary, and the generated import
lines.
A module-scope let goes in the module that WRITES it, not the module that
looks like its topical home. ESM import bindings are read-only, so a module
cannot assign a binding it imported.
When two modules genuinely write the same binding, the owner exposes a one-statement accessor and the other module calls it:
// scroll.js owns the counter.
export let restoreGeneration = 0;
export function bumpRestoreGeneration() { restoreGeneration += 1; }
// navigator.js reads the live binding and calls the accessor to write.
import { restoreGeneration, bumpRestoreGeneration } from './scroll.js';Keep importing the binding itself wherever it is READ. Dropping it from the import list while a read site survives leaves a free variable, which throws only when that line executes. In the client router that meant a Back-button scroll restore silently landing at offset 0, with every node test still green.
Layer the modules and never import upward. Node tolerates an import cycle, but
reading a const or class binding during the cycle's evaluation phase throws
a TDZ ReferenceError at module load, and in a minified browser bundle that is
a blank page rather than a test failure.
Where a back edge is unavoidable, resolve it by calling a function at call time rather than reading a binding at module scope.
Symbol('x') mints a unique value. Symbol.for('x') looks one up in the global
registry by string. They are never interchangeable, and substituting one for the
other produces a value that no existing object carries, so every lookup quietly
returns undefined. Import the symbol from the module that created it.
This repo has guard tests that readFileSync a source file and grep it for a
constant, to pin two copies of a value against each other. Barrelling a file
breaks every one of them, and breaks them in two different ways:
- an
assert.matchfails on its own precondition, which is loud and fine; - an
assert.doesNotMatchstarts passing vacuously, which is silent and is the reason this is written down.
After any split, grep the test tree for reads of the file you just barrelled and point each guard at the barrel PLUS every module beneath it.
# 1. Export surface is identical, in BOTH directions. `added` must be empty too:
# a behaviour-preserving split adds no public surface.
node --input-type=module -e "
const before = await import('/tmp/before.js');
const after = await import('./packages/core/src/<file>.js');
const A = Object.keys(before).sort(), B = Object.keys(after).sort();
console.log(JSON.stringify({
missing: A.filter((k) => !B.includes(k)),
added: B.filter((k) => !A.includes(k)),
}));
"
# 2. Every code line survived. Normalize away comments and the `export ` prefix,
# then diff. Anything left is a line the split CHANGED, and each one needs a
# reason in the commit message.
# 3. The module loads at all (catches a TDZ throw introduced by a cycle).
node --input-type=module -e "await import('./packages/core/index-browser.js')"
node --input-type=module -e "await import('./packages/core/index.js')"
# 4. Rebuild dist BEFORE any e2e or Bun run, which resolve the built bundle and
# would otherwise test the pre-split code and pass vacuously.
node scripts/build-framework-dist.js
# 5. The browser suite is MANDATORY for a renderer, router, component, or slot
# split. Those defects are post-hydration: the export surface is unchanged,
# the SSR bytes are unchanged, and node tests stay green.
npm test && npm run test:browserStep 5 is not optional and not a formality. Of the two silent defects this codebase has hit from splitting, both were caught by the browser suite alone.