let count = $state(0) looks like ordinary JavaScript, yet changing count updates exactly the right piece of DOM and nothing else. Every frontend developer has met the shadow of that convenience: a derived value gone stale, an effect looping forever, a list re-rendering whole rows when one cell changed. When reactivity is magic, debugging means guessing, and guessing is expensive. The honest alternative is reading the compiler and the runtime to learn what the framework actually does with your source.

Svelte’s pitch makes reading it unusually rewarding: no virtual DOM diffing, no reactive declaration blocks. Instead, a compiler rewrites your component into plain JavaScript that calls a small signals runtime, and the runtime does the invalidation work with version counters instead of dependency arrays. That design lives in a monorepo whose main package is packages/svelte, and it splits cleanly in two halves: the compiler under src/compiler and the runtime under src/internal/client. Each half is approachable on its own; the seam between them is the small set of $. helpers that generated code calls.

This article walks that seam in the real tree of sveltejs/svelte at main, pinning every claim to a file and line you can open on GitHub. We cover the three compiler phases, what each rune compiles into, how signals track dependencies, how deep $state objects are proxied, and how writes are batched into a flush. Two hand-built maps anchor the tour.

Svelte overview architecture: compiler entry, three phases, client runtime and DOM output

From left to right: the compiler entry fans out into parse, analyze and transform; the generated client code calls the signals runtime, whose sources, deriveds and batch drive the DOM output.

Reading the overview from left to right:

  • compile(), L24 is the whole compiler as one function: validate options, parse, strip TypeScript nodes, analyze, transform — five steps you can step through in a debugger.
  • parse(), L340 is a hand-written recursive-descent parser, not an off-the-shelf parser generator, producing the component AST.
  • analyze_component(), L334 walks that AST once with one visitor per node type to build scopes and classify bindings.
  • transform_component(), L19 picks the client or server code generator and prints the resulting ESTree program with esrap.
  • mount(), L70 is the public runtime entry: it creates a root effect and executes the compiled component inside it.
  • source(), L71 allocates a signal — the runtime representation of $state.
  • proxy(), L40 wraps objects and arrays in a Proxy so nested mutation stays reactive.
  • derived(), L71 builds lazy derived signals that recompute only when something reads them after an invalidation.
  • class Batch, L205 coalesces writes and schedules effect runs; flushSync() at line 1579 is its synchronous escape hatch.

The detail diagram expands each cluster into the functions that matter, so keep it beside you while reading the sections below.

Svelte detail architecture with parse, analyze, transform, signals, effects, scheduler and DOM nodes

The detail map: compiler phases on the left, the signals and effects runtime in the middle, DOM mounting and keyed blocks on the right.

Three phases, one AST

Everything begins in packages/svelte/src/compiler/index.js, a thin 237-line file. compile() at line 24 validates options, calls the parser, and then — when the component carries TypeScript, detected via parsed.metadata.ts — rewrites the AST through remove_typescript_nodes() (invoked at line 80) so later phases only see plain JavaScript nodes. That call is how <script lang="ts"> works without a plugin chain; the type-erasure trade-offs are covered in our TypeScript source tour.

Phase 1 parsing is refreshingly old-school — parse() at line 340 in phases/1-parse/index.js hands the source to the Parser class at line 18, which keeps this.template, a character index and a node stack, reading forward one token at a time. Markup becomes a fragment AST; each script block becomes an ESTree program parsed with acorn; the result is a root with fragment, instance and module fields. There is no backtracking cleverness; the code reads like the syntax it parses, which is why Svelte’s error messages point at exact character offsets.

Phase 2 is where runes stop being syntax and become data. analyze_component() at line 334 in phases/2-analyze/index.js drives a visitor table with one file per AST node type — 61 visitor files in phases/2-analyze/visitors/. The scope machinery lives in phases/scope.js, a 1,561-line module whose get_rune() at line 1447 decides whether a call expression is a rune at all. VariableDeclarator.js then maps declarations to binding kinds: at line 30 the visitor checks rune === '$state', line 41 assigns the kind 'state', and similar branches classify 'raw_state', 'derived' and 'props'. Downstream phases never re-parse your source; they consult these bindings.

Phase 3 turns analysis into code. transform_component() at line 19 in phases/3-transform/index.js returns early when generate is false, otherwise dispatches to server_component() at line 94 in transform-server.js or client_component() at line 137 in transform-client.js, depending on the generate option. The chosen generator walks the same AST with its own visitors — 54 client files and 34 server files — building a new ESTree program. esrap prints it (the print call sits at line 39) with a TypeScript-aware printer and merged source maps; render_stylesheet() at line 29 in the CSS subfolder scopes and prunes styles. Nothing is interpreted; it is printed JavaScript.

What the runes actually compile into

This is the part worth memorizing: it explains every runtime behavior you will debug. A $state declaration becomes a call to the runtime’s source(). When the initial value is an object or array, the client visitor consults should_proxy — the decision sits in VariableDeclaration.js at lines 138-139, next to the is_state_source check — and emits code that wraps the value in a deep proxy. A $derived expression becomes $.derived(() => ...); the emission is visible in CallExpression.js at lines 45-49. $effect and $effect.pre compile to $.user_effect and $.user_pre_effect (lines 65-67 of the same file). The runes are sugar for runtime calls, which is also why compileModule() at line 104 of the compiler entry can apply the same rewriting to plain .js files.

Templates take a different route than most frameworks: the client generator emits one HTML string per component; at load time from_html() at line 65 in internal/client/dom/template.js parses it once and hands every instance a cheap clone_node copy (line 90, import_node fallback for Firefox). There is no per-render innerHTML. Updates are performed by render_effect closures wired into anchor positions, and keyed list diffing lives in each() at line 241 in dom/blocks/each.js.

The server half mirrors the client shape without a signals graph: server_component() produces functions that append HTML strings through internal/server/renderer.js. The same component source yields an interactive client module and a string renderer — output any Node server can run directly.

Inside the signals graph

reactivity/sources.js is the surface of $state. source() at line 71 allocates the value, its reactions set, and version fields. The public write path is set() at line 148, which proxies incoming values and delegates to internal_set() at line 177 — the batch-aware core that records the write, bumps versions and schedules reactions. mutate() at line 133 handles in-place edits, and update() at line 291 implements the += fast path. Deriveds are lazy: derived() at line 71 in deriveds.js registers but does not compute; update_derived() at line 481 recomputes on demand, and async_derived() at line 321 extends the idea across awaits.

The tracking heart is update_reaction() at line 522 in internal/client/runtime.js (1,641 lines). While a reaction runs, every signal read is recorded as a dependency; afterwards the reaction carries one of three statuses driven by set_signal_status() at line 10 in reactivity/status.js: CLEAN, MAYBE_DIRTY, or DIRTY. Staleness is decided by integer versions, not deep comparisons: a module-level read_version counter sits at line 161, increment_write_version() at line 170 bumps the clock on every write, version_of() at line 178 resolves a signal’s effective version through the active batch, and is_dirty() at line 291 decides whether a MAYBE_DIRTY reaction actually reruns.

Deep reactivity is isolated in proxy.js (443 lines). proxy() at line 40 returns new Proxy (line 118) whose handlers read through and write through to versioned signals; get_proxied_value() at line 380 unwraps on demand, and inspectable_array() at line 423 exists purely so devtools display honest arrays. The proxy writes back through the same internal_set() path, so a nested item.count += 1 costs the same bookkeeping as a top-level assignment.

From reactive assignments to compiled signals

The engineering delta between Svelte 4 and Svelte 5 is visible in file weights. Svelte 4’s compiler chased assignments at build time and injected invalidation code per mutation site; correctness lived entirely in compile-time reasoning. Svelte 5 moves invalidation into a runtime graph shipped in a handful of files: runtime.js 1,641 lines, batch.js 2,047, deriveds.js 588, proxy.js 443 — about 4,700 lines for the reactive core, against 1,561 lines of scope machinery on the compiler side.

The runtime encodes signal state as a single bitmask integer per signal, defined in internal/client/constants.js: DERIVED = 1 << 1 at line 2, RENDER_EFFECT = 1 << 3 at line 4, BLOCK_EFFECT = 1 << 4 at line 14, BRANCH_EFFECT = 1 << 5 at line 15, and ROOT_EFFECT = 1 << 6 at line 16, with the dirtiness states packed above them — CLEAN = 1 << 10 (line 32), DIRTY = 1 << 11 (line 33), MAYBE_DIRTY = 1 << 12 (line 34). One integer answers “what kind of reaction is this and should it run” with two bitwise ANDs. The repository itself is a pnpm workspace — pnpm-workspace.yaml sits at the repo root.

Batching and the flush cycle

Writes must not flush immediately, or one handler changing five signals would paint five times. class Batch at line 205 in batch.js — at 2,047 lines the largest file on the client — collects writes in a map, schedules itself on the microtask queue, and when it commits, drains effects through flush_queued_effects() at line 1690 in dependency order. flushSync() at line 1579 forces that drain synchronously and is re-exported as flush from internal/client/index.js at line 120, so the flushSync imported from svelte is this function. Effects are built by effect_root() at line 269 in effects.js, render_effect() at line 384, template_effect() at line 394, and branch() at line 442 — branches being the disposable subtrees behind {#if} and {#each} — and torn down by destroy_effect() at line 519. mount() at line 70 in render.js ties it together: one root effect, one cloned template, wired render effects.

Honest Limits

  • Line numbers are pinned to main as of 2026-11-24 and will drift; expect occasional off-by-a-few after refactor waves.
  • Skipped by design: compiler/migrate/, the accessibility visitors under 2-analyze/visitors/shared/a11y/, compiler/preprocess/, the experimental custom-renderer flag, svelte/reactivity collection classes such as SvelteMap, and legacy-mode interop in internal/client/dom/legacy/.
  • The detail diagram compresses CSS handling into a single render_stylesheet node; scoping and selector pruning deserve their own walkthrough.
  • The two diagrams are hand-built maps verified against the tree, not mechanical AST exports; they emphasize structure over exhaustiveness.
  • Async handling (async_derived, boundary blocks) is evolving toward an experimental async mode; treat those edges as moving targets.
Watch PyShine on YouTube

Contents