Skip to content

feat: compiled mode - #857

Closed
harlan-zw wants to merge 28 commits into
mainfrom
feat/static-precompile
Closed

harlan-zw wants to merge 28 commits into
mainfrom
feat/static-precompile

Conversation

@harlan-zw

@harlan-zw harlan-zw commented Jul 19, 2026 •

Copy link
Copy Markdown
Collaborator

🔗 Linked issue

Related to #832.

❓ Type of change

  • 📖 Documentation
  • 🐞 Bug fix
  • 👌 Enhancement
  • ✨ New feature
  • 🧹 Chore
  • ⚠️ Breaking change

📚 Description

Adds opt-in build-time precompilation for static head declarations across server and client runtimes. Unsupported syntax fails with source context, while normal Unhead imports and runtime behavior remain unchanged when precompilation is disabled.

* perf(bundler): unify AST transforms into one parse/walk pipeline

TreeshakeServerComposables, UseSeoMetaTransform and MinifyTransform each
ran their own oxc parseSync + oxc-walker walk + MagicString over the same
modules, so a module matching all three code filters parsed three times
per build.

The new private createTransformPipeline runs all three concerns over a
single parse, ScopeTracker walk, MagicString and sourcemap:

- rolldown-first filtering: the unified plugin's transform.filter uses the
  union code regex and the shared JS/Vue id filter so rolldown/Vite skip
  the JS hook natively; cheap per-concern regexes re-gate phases inside
  the handler
- phase order per call site is preserved: treeshake claims removed
  statement ranges first, and the seoMeta/minify phases skip any node
  inside a claimed range (previously guaranteed by plugin registration
  order)
- per-target dispatch stays per transform call via resolveBuildConsumer;
  unknown targets retain server code, sharedDuringBuild stays on
- overlapping edits from two phases are detected up front and throw one
  contextual error (file + offsets) with no partial output
- parser failures return undefined (no transform), matching the previous
  MinifyTransform behavior
- the treeshake provenance check accepts importPaths, defaulting to the
  seoMeta importPaths inside the unified pipeline

The public factories (TreeshakeServerComposables, UseSeoMetaTransform,
MinifyTransform) remain exported as thin single-concern adapters over the
pipeline; Unhead()/createFrameworkPlugin() now register one plugin.

Combined transform-positive module: 375 -> 745 ops/s (~2.0x); prefiltered
unrelated module: 333k -> 539k ops/s (no regression).

* perf(bundler): broaden static useSeoMeta lowering (#834)

Replace the string-only nested-object decoder with a safe recursive AST
value decoder (string/number/boolean/null literals, unary +/- on numeric
literals, expression-free template literals, arrays and plain objects with
static keys; everything else returns a bail sentinel). Nested robots-style
objects with numbers, negative numbers and booleans now compile.

Match runtime `unpackMeta` exactly for the lowered output:
- replicate `sanitizeObject` (top-level entries stringifying to 'false'
  are dropped before packing)
- render structural expansions (media objects/arrays, array values) before
  scalar/packed props, mirroring `[...extras, ...meta]`
- hoist `url`/`secureUrl` first inside media object expansions
- bail arrayable meta keys (themeColor, ...) whose objects route through
  `handleObjectEntry` at runtime
- emit `'http-equiv'` quoted (was previously invalid JS output)

Add a per-prop residual fallback: when a value-level failure occurs, the
unsupported tail is kept on the original composable adjacent to the
lowered call, but only when provably render-identical (statement position,
no options arg, no title after the failure point, disjoint resolved meta
names, and residual props primitives-routed unless nothing was lowered).

Verified by a runtime-vs-compiled equivalence corpus (37 fixtures rendered
through the real unhead server runtime from both the original call and the
transformed output) doubling as an eligibility floor so future changes
can't silently narrow supported input.
@coderabbitai

coderabbitai Bot commented Jul 19, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
Walkthrough

This PR introduces a unified bundler transform pipeline (createTransformPipeline/UnheadTransforms) that consolidates treeshaking, SEO meta lowering, minification, and a new experimental static precompilation feature. It adds sealed precompiled server/client runtimes for Unhead core and React/Solid/Svelte/Vue adapters, updates package exports and build configs for /precompiled/* subpaths, precomputes default server tags statically, and extends bundle-size CI with Vue SEO and precompile performance gates plus extensive new tests.

Changes: Unified Transform Pipeline and Bundler Integration

Layer / File(s) Summary
Unified transformation pipeline
packages/bundler/src/unplugin/createTransformPipeline.ts, MinifyTransform.ts, TreeshakeServerComposables.ts, UseSeoMetaTransform.ts, CreateHeadTransform.ts
A new createTransformPipeline/UnheadTransforms module parses/walks each file once and dispatches phase-ordered treeshake, SEO meta lowering, precompile, and minify edits; prior standalone transform plugins now delegate to it.
Bundler integration, options and docs
packages/bundler/src/unplugin/framework.ts, vite.ts, types.ts, packages/bundler/README.md, docs/head/1.guides/build-plugins/0.overview.md, package.json
Vite/framework wiring computes concern flags for a single pipeline instance, adds experimental.precompile options, rejects combining with streaming, and documents static precompilation plus new bundle-size scripts.
Transform pipeline test coverage
packages/bundler/test/transformPipeline.test.ts, useSeoMetaTransform.test.ts, seoMetaRuntimeEquivalence.test.ts, precompileTransform.test.ts, createHeadTransform.test.ts, framework.test.ts, viteBuild.integration.test.ts, fixtures, bench/unplugin-transform.bench.ts
Extensive tests validate pipeline equivalence to prior three-pass composition, static precompile validation/rejection rules, SEO packing/splitting, and Vite build integration.

Precompiled Unhead Runtime

Layer / File(s) Summary
Precompiled Unhead runtime and resolution
packages/unhead/src/precompiled/*.ts, server/createHead.ts, server/defaults.ts, utils/resolve.ts, stream/unplugin.ts, build.config.ts, precompiled.build.config.ts, package.json
Adds sealed precompiled server/client/CSR/deferred/snapshot/unique head implementations, precomputes default init tags statically, tightens resolveTags precomputed reuse, batches streaming replay, and publishes /precompiled/* exports.
Precompiled runtime test coverage
packages/unhead/test/unit/precompiled*.test.ts, streaming/unplugin.test.ts, server/defaultInitPrecomputed.test.ts
Unit tests cover DOM adoption/disposal, batching, identity collision handling, snapshot/unique modes, and streaming batch replay behavior.

Framework Adapters (React, Solid, Svelte, Vue)

Layer / File(s) Summary
Framework precompiled adapters
packages/{react,solid-js,svelte,vue}/src/precompiled*, build configs, package.json, vitest configs
Each framework gains precompiled client/CSR/deferred/server hooks, providers/context, compile-only stubs, and matching build/export/alias wiring.
Framework adapter tests and export fixtures
packages/{react,solid-js,svelte,vue}/test/precompiled*.test.*, test/exports/*.yaml
Tests verify lifecycle disposal, StrictMode/KeepAlive behavior, and uncompiled failure; export snapshots reflect new /precompiled subpaths.

Bundle Benchmarks and CI Gates

Layer / File(s) Summary
Bundle benchmarks and CI gates
bench/bundle/*, bench/precompile-gate.mjs, bench/precompile-perf-ci.mjs, .github/workflows/*.yml
Adds Vue SEO and precompile bundle variants, performance/report tooling, gzip budget checks, isolation assertions, and CI workflow steps enforcing precompile budgets.

Estimated code review effort: 5 (Critical) | ~150 minutes

Possibly related PRs

  • unjs/unhead#726: Both PRs modify Vite plugin composition in packages/bundler/src/unplugin/vite.ts around conditional transform registration.
  • unjs/unhead#783: Both PRs modify packages/bundler/src/unplugin/CreateHeadTransform.ts to tighten regex-based import/code filtering for createHead detection.
  • unjs/unhead#828: Both PRs touch the same SSR default-init precomputation mechanics in packages/unhead/src/server/createHead.ts and resolveTags in packages/unhead/src/utils/resolve.ts.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 32.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title identifies the new compiled mode feature, but it is broad relative to the static head precompilation changes.
Description check ✅ Passed The description includes the linked issue, marks the change as a new feature, and summarizes scope, behavior, and compatibility.
Finishing Touches
Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/static-precompile
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions

github-actions Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

📦 Bundle Size

✅ No notable changes · 🆕 2 new bundles tracked

All bundles (16)
Bundle Gzipped Brotli Raw
Core
Client (Minimal) 5.4 kB 4.9 kB 13.4 kB ✅
Client (Full) 9.8 kB 8.9 kB 25.5 kB ✅
Client (Self-Contained) 5.7 kB 5.1 kB 14.1 kB ✅
Server (Minimal) 4.9 kB 4.4 kB 12.3 kB ✅
Server (Self-Contained) 5.2 kB 4.7 kB 13 kB ✅
Vue
Vue Client (Minimal) 5.9 kB 5.3 kB 14.5 kB ✅
Vue Client (Full) 10.9 kB 9.9 kB 28.4 kB ✅
Vue Server (Minimal) 5.4 kB 4.9 kB 13.3 kB ✅
Vue SEO Transform 5.9 kB 5.4 kB 14.8 kB 🆕
Vue SEO Precompiled 5.9 kB 5.4 kB 14.8 kB 🆕
React
React Client (Minimal) 5.8 kB 5.3 kB 14.5 kB ✅
React Client (Full) 10.9 kB 9.9 kB 28.6 kB ✅
React Server (Minimal) 5.2 kB 4.7 kB 13 kB ✅
Schema.org
Schema.org (Minimal) 13.4 kB 12.1 kB 39 kB ✅
Schema.org Imports 0.1 kB 0.1 kB 0.1 kB ✅
Schema.org Vue Meta 0.5 kB 0.4 kB 1 kB ✅

📦 Runtime Dependencies

✅ No runtime dependency changes

All packages (10)
Package External deps Install size Largest dependency Skipped optional
@unhead/angular 10 784 kB @jridgewell/trace-mapping 146.7 kB 0
@unhead/bundler 10 811 kB @jridgewell/trace-mapping 146.7 kB 0
@unhead/cli 18 4.5 MB @oxc-parser/binding-linux-arm64-gnu 2 MB 18
@unhead/eslint-plugin 9 693.6 kB @jridgewell/trace-mapping 146.7 kB 0
@unhead/react 11 834.9 kB @jridgewell/trace-mapping 146.7 kB 0
@unhead/schema-org 9 693.6 kB @jridgewell/trace-mapping 146.7 kB 0
@unhead/solid-js 11 834.9 kB @jridgewell/trace-mapping 146.7 kB 0
@unhead/svelte 11 834.9 kB @jridgewell/trace-mapping 146.7 kB 0
@unhead/vue 11 834.9 kB @jridgewell/trace-mapping 146.7 kB 0
unhead 9 693.6 kB @jridgewell/trace-mapping 146.7 kB 0
Skipped optional dependencies (18)
  • @unhead/cli: oxc-parser -> @oxc-parser/binding-android-arm-eabi, oxc-parser -> @oxc-parser/binding-android-arm64, oxc-parser -> @oxc-parser/binding-darwin-arm64, oxc-parser -> @oxc-parser/binding-darwin-x64, oxc-parser -> @oxc-parser/binding-freebsd-x64, oxc-parser -> @oxc-parser/binding-linux-arm-gnueabihf, oxc-parser -> @oxc-parser/binding-linux-arm-musleabihf, oxc-parser -> @oxc-parser/binding-linux-arm64-musl, oxc-parser -> @oxc-parser/binding-linux-ppc64-gnu, oxc-parser -> @oxc-parser/binding-linux-riscv64-gnu, oxc-parser -> @oxc-parser/binding-linux-riscv64-musl, oxc-parser -> @oxc-parser/binding-linux-s390x-gnu, oxc-parser -> @oxc-parser/binding-linux-x64-gnu, oxc-parser -> @oxc-parser/binding-linux-x64-musl, oxc-parser -> @oxc-parser/binding-openharmony-arm64, oxc-parser -> @oxc-parser/binding-win32-arm64-msvc, oxc-parser -> @oxc-parser/binding-win32-ia32-msvc, oxc-parser -> @oxc-parser/binding-win32-x64-msvc

Production dependencies only. Peer dependencies and Unhead workspace packages are excluded. Skipped optional dependencies are unavailable on the CI platform.


⚡ Performance (directional)

⚠️ 2 slower · past the per-metric noise gate

Benchmark base → PR Δ
Bundler: treeshakeServerComposables skip unrelated code 0.002 ms → 0.003 ms 🔴 +41.3%
Bundler: treeshakeServerComposables many calls 2.619 ms → 7.300 ms 🔴 +178.7%
All benchmarks (29)
Benchmark PR Δ RME
SSR render (CPU) 0.356 ms ~ noise ±9.6%
SSR render (wall) 0.261 ms ~ noise ±5.0%
SSR allocated / render 240.9 KiB ~ noise ±5.9%
Schema.org cached render (CPU) 0.342 ms ~ noise ±5.5%
Schema.org cached render (wall) 0.249 ms ~ noise ±2.9%
Schema.org cached allocated / render 131 KiB ~ noise ±1.0%
Streaming wrapStream drain (CPU) 0.222 ms ~ noise ±6.8%
Streaming wrapStream drain (wall) 0.116 ms ~ noise ±6.1%
Streaming allocated / drain 111.3 KiB ~ noise ±0.7%
Streaming suspense chunk (CPU) 0.014 ms ~ noise ±13.7%
Streaming allocated / suspense chunk 4.9 KiB ~ noise ±0.3%
CSR DOM mutations / nav 38 ~ noise —
CSR re-render (CPU) 0.953 ms ~ noise ±4.7%
CSR re-render (wall) 0.540 ms ~ noise ±2.2%
Bundler: ssrStaticReplace skip unrelated code 0.002 ms ~ noise ±1.8%
Bundler: treeshakeServerComposables skip unrelated code 0.003 ms 🔴 +41.3% ±1.6%
Bundler: solid streaming skip JSX without head calls 0.003 ms ~ noise ±0.2%
Bundler: react streaming skip JSX without head calls 0.003 ms ~ noise ±0.4%
Bundler: transform id filter mixed ids 0.198 ms ~ noise ±0.4%
Bundler: minifyTransform inline script/style 0.520 ms ~ noise ±2.5%
Bundler: createHeadTransform many createHead calls 0.571 ms ~ noise ±3.8%
Bundler: react streaming transform JSX with head calls 1.588 ms ~ noise ±5.4%
Bundler: ssrStaticReplace many head.ssr reads 1.614 ms ~ noise ±5.2%
Bundler: useSeoMetaTransform static calls 3.606 ms ~ noise ±3.4%
Bundler: treeshakeServerComposables many calls 7.300 ms 🔴 +178.7% ±2.4%
Bundler: prefiltered module: unified pipeline 0.004 ms 🆕 new ±0.3%
Bundler: prefiltered module: three-pass composition 0.008 ms 🆕 new ±0.5%
Bundler: combined module: unified pipeline 2.961 ms 🆕 new ±3.5%
Bundler: combined module: three-pass composition 5.736 ms 🆕 new ±4.7%

🧪 Experimental sealed precompile: client and server (same commit)

The same static product metadata is built independently for unhead/precompiled/client and unhead/precompiled/server. Disabled uses the normal target runtime; enabled hoists build-finalized DOM or HTML plans. The client keeps disposal and DOM reconciliation but removes normalization, hooks, plugins, event handlers, patches, and dynamic inputs. The server collects merged plans, resolves execution-order duplicates, and joins serialized fragments. CPU samples alternate OFF/ON order and consume every result; memory is paired-bootstrap median transient heap growth.

Metric Disabled Enabled Δ
Server benchmark bundle (gzip) 5,817 B 1,380 B 🟢 -4437 B (-76.3%)
Static SSR create + collect (CPU) 1.23 µs 0.02 µs 🟢 -98.2% ±0.4 pp
Static SSR create + resolve (CPU) 0.023 ms 0.06 µs 🟢 -99.7% ±2.0 pp
Static SSR create + resolve + render (CPU) 0.031 ms 0.04 µs 🟢 -99.9% ±2.6 pp
Transient heap growth / render 38.3 KiB 0.3 KiB 🟢 -99.3% (95% upper -99.3%)
Client benchmark bundle (gzip) 8,059 B 2,275 B 🟢 -5784 B (-71.8%)
Client mount + dispose (CPU) 1.871 ms 0.705 ms 🟢 -62.3% ±1.3 pp
Client transient heap / mount + dispose 929.6 KiB 534.7 KiB 🟢 -42.5% (95% upper -42.0%)
Stricter profile bundle detail
Profile Raw Gzip Brotli Change from lifecycle runtime
Server unique 2,783 B 1,093 B 851 B -20.8% gzip
Server snapshot 2,116 B 869 B 632 B -37.0% gzip
Client CSR 5,062 B 1,787 B 1,590 B -21.5% gzip
Client snapshot 5,088 B 1,820 B 1,565 B -20.0% gzip
Client deferred initial 4,158 B 1,479 B 1,287 B -35.0% initial gzip
Client deferred async 3,443 B 1,459 B 1,323 B loaded after hydration starts
Phase detail
CPU stage Disabled Enabled Paired Δ (95% CI)
Create + collect 1.23 µs 0.02 µs -98.2% ±0.4 pp
Create + collect + resolve + render 0.031 ms 0.04 µs -99.9% ±2.6 pp

Server raw: 15,080 B → 4,115 B · Brotli: 5,251 B → 1,145 B · CPU RME: ±2.6% / ±0.5%

Client raw: 20,907 B → 6,384 B · Brotli: 7,309 B → 2,021 B · CPU RME: ±1.1% / ±1.4%

Baseline: main @ 8c82353 · 2026-10-31 · gzipped is the headline size metric · perf is directional (shared-runner, gated)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/unhead/test/unit/precompiledEntries.test.ts (1)

219-221: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert the malformed marker’s resulting behavior, not only that rendering does not throw.

At Line 220, revivePrecompiledTags converts a non-array style value into an empty Map, so this test can pass while silently discarding { filter: 1 }. Assert the rendered payload or explicitly verify the intended fallback/rejection behavior.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/unhead/test/unit/precompiledEntries.test.ts` around lines 219 - 221,
Update the test around invalidStyleObject and renderSSRHead to assert the
resulting rendered payload, not merely that rendering completes. Verify the
intended behavior when revivePrecompiledTags receives the non-array style
value—either the expected fallback output or explicit rejection—and ensure the
malformed { filter: 1 } value is not silently discarded.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/unhead/test/unit/precompiledEntries.test.ts`:
- Around line 219-221: Update the test around invalidStyleObject and
renderSSRHead to assert the resulting rendered payload, not merely that
rendering completes. Verify the intended behavior when revivePrecompiledTags
receives the non-array style value—either the expected fallback output or
explicit rejection—and ensure the malformed { filter: 1 } value is not silently
discarded.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 048cdaa1-fa83-4be9-bd0d-d03d342f5ec9

📥 Commits

Reviewing files that changed from the base of the PR and between 0a003d3 and 51536c9.

📒 Files selected for processing (2)
  • packages/unhead/src/utils/resolve.ts
  • packages/unhead/test/unit/precompiledEntries.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/unhead/src/utils/resolve.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/unhead/test/unit/precompiledEntries.test.ts (1)

41-47: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Restore the prototype spy after this test.

vi.spyOn patches the shared PrecompiledHeadInputBase.prototype._r, and there's no mockRestore()/vi.restoreAllMocks() call, so the wrapper lingers on the shared prototype for the rest of the suite. Harmless today (spy calls through), but worth cleaning up to avoid surprises if a later test also inspects _r call counts.

♻️ Suggested cleanup
   it('survives framework resolver walks without invoking the reviver', () => {
     const marker = precompile({ title: 'walked' }) as any
     const revive = vi.spyOn(Object.getPrototypeOf(marker), '_r')
     expect(marker.constructor).not.toBe(Object)
     expect(walkResolver(marker, (_key, value) => value)).toBe(marker)
     expect(revive).not.toHaveBeenCalled()
+    revive.mockRestore()
   })
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/unhead/test/unit/precompiledEntries.test.ts` around lines 41 - 47,
Restore the prototype spy created for _r in the “survives framework resolver
walks without invoking the reviver” test after its assertions, ensuring the
shared PrecompiledHeadInputBase.prototype is not patched for subsequent tests.
bench/precompile-gate.mjs (1)

31-49: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Fragile 'toJSON' substring used as a leak-detection marker in two places. Both sites detect server-only precompile-carrier leakage by searching bundle text for the generic string 'toJSON', which can legitimately appear in unrelated code (any class/library defining a custom toJSON), risking false-positive CI failures unrelated to actual leakage.

  • bench/precompile-gate.mjs#L31-L49: replace 'toJSON' (and ideally 'precompiledHeadInput') in strictMarkers with a distinctive, low-collision sentinel unique to the precompile carrier (e.g. embed a rare literal like __UNHEAD_PRECOMPILED_CARRIER__ in PrecompiledHeadInputBase/PrecompiledHeadInput and search for that).
  • bench/bundle/vue-client-seo-plugin-build.config.ts#L53-L71: use the same distinctive sentinel instead of contents.toString().includes('toJSON') for the client-bundle leak check.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@bench/precompile-gate.mjs` around lines 31 - 49, Replace the generic toJSON
and precompiledHeadInput leak markers with one distinctive sentinel literal
embedded in PrecompiledHeadInputBase/PrecompiledHeadInput, then use that same
sentinel in bench/precompile-gate.mjs lines 31-49 and
bench/bundle/vue-client-seo-plugin-build.config.ts lines 53-71; update both
checks to detect only this carrier-specific marker.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/unhead/src/precompiled.ts`:
- Around line 6-23: Update toResolvableHead to skip class Set and style
Map/array normalization when tag.tag is templateParams, matching cloneTag’s
guard. Preserve the existing normalization for all other tags so literal
template parameter values, including flat style arrays, pass through unchanged.

---

Nitpick comments:
In `@bench/precompile-gate.mjs`:
- Around line 31-49: Replace the generic toJSON and precompiledHeadInput leak
markers with one distinctive sentinel literal embedded in
PrecompiledHeadInputBase/PrecompiledHeadInput, then use that same sentinel in
bench/precompile-gate.mjs lines 31-49 and
bench/bundle/vue-client-seo-plugin-build.config.ts lines 53-71; update both
checks to detect only this carrier-specific marker.

In `@packages/unhead/test/unit/precompiledEntries.test.ts`:
- Around line 41-47: Restore the prototype spy created for _r in the “survives
framework resolver walks without invoking the reviver” test after its
assertions, ensuring the shared PrecompiledHeadInputBase.prototype is not
patched for subsequent tests.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9483063e-ab3d-4fa6-8c54-8533389728e5

📥 Commits

Reviewing files that changed from the base of the PR and between c5c8ca0 and e627e0a.

📒 Files selected for processing (35)
  • .github/workflows/bundle-size.yml
  • bench/bundle/analyze.ts
  • bench/bundle/bundle-report.ts
  • bench/bundle/bundles.ts
  • bench/bundle/precompile-report.ts
  • bench/bundle/precompile-runtime-build.config.ts
  • bench/bundle/report.ts
  • bench/bundle/src/vue-server/precompile-runtime-off.ts
  • bench/bundle/src/vue-server/precompile-runtime.ts
  • bench/bundle/update.ts
  • bench/bundle/vue-client-seo-plugin-build.config.ts
  • bench/precompile-gate.mjs
  • bench/precompile-perf-ci.mjs
  • docs/head/1.guides/build-plugins/0.overview.md
  • package.json
  • packages/bundler/README.md
  • packages/bundler/src/unplugin/createTransformPipeline.ts
  • packages/bundler/src/unplugin/types.ts
  • packages/bundler/test/precompileTransform.test.ts
  • packages/unhead/build.config.ts
  • packages/unhead/package.json
  • packages/unhead/precompiled.build.config.ts
  • packages/unhead/src/precompiled.ts
  • packages/unhead/src/precompiled/carrier.ts
  • packages/unhead/src/precompiled/resolve.ts
  • packages/unhead/src/precompiled/server.ts
  • packages/unhead/src/server/createHead.ts
  • packages/unhead/src/server/renderSSRHead.ts
  • packages/unhead/src/stream/unplugin.ts
  • packages/unhead/src/utils/resolve.ts
  • packages/unhead/test/streaming/unplugin.test.ts
  • packages/unhead/test/unit/precompiledEntries.test.ts
  • packages/unhead/test/unit/precompiledServer.test.ts
  • packages/unhead/test/unit/server/defaultInitPrecomputed.test.ts
  • test/exports/unhead.yaml
🚧 Files skipped from review as they are similar to previous changes (6)
  • packages/bundler/src/unplugin/types.ts
  • packages/bundler/README.md
  • docs/head/1.guides/build-plugins/0.overview.md
  • package.json
  • packages/unhead/src/utils/resolve.ts
  • packages/bundler/src/unplugin/createTransformPipeline.ts

Comment thread packages/unhead/src/precompiled.ts Resolved
@harlan-zw

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@harlan-zw

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
packages/unhead/precompiled.build.config.ts (1)

8-11: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Stale comment: "emits one export" no longer matches the 7 entries.

The entries list now emits multiple precompiled/* outputs, so the "one export before the rest of the package exists" wording is misleading. Consider updating it to describe the actual first-pass intent.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/unhead/precompiled.build.config.ts` around lines 8 - 11, Update the
comment adjacent to failOnWarn in the precompiled build configuration to
describe the first pass as emitting the initial precompiled entries before the
rest of the package exists, rather than claiming it emits one export. Keep the
existing build behavior unchanged.
bench/bundle/precompile-server-snapshot-build.config.ts (1)

29-33: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Add a content assertion mirroring the "unique" profile gate.

This build:done only logs size — it never checks that snapshot mode actually stripped runtime resolution/normalization machinery (as precompile-server-unique-build.config.ts does via its meta:description/new Map check). Since snapshot is the most aggressively finalized profile, a regression here (e.g. a leaked resolveTags/dedupe path) could silently inflate the bundle without failing CI.

♻️ Suggested addition
     'build:done': () => {
       const file = path.resolve(__dirname, 'dist/precompile-runtime-snapshot/vue-server/precompile-snapshot.mjs')
       const contents = fs.readFileSync(file)
+      const output = contents.toString()
+      if (output.includes('resolveTags') || output.includes('new Map'))
+        throw new Error('Snapshot server bundle retained runtime resolution/duplicate-handling machinery.')
       console.log(`PRECOMPILE SERVER SNAPSHOT Size: ${contents.length} bytes, gzip: ${zlib.gzipSync(contents).length} bytes`)
     },
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@bench/bundle/precompile-server-snapshot-build.config.ts` around lines 29 -
33, Update the build:done hook in the snapshot configuration to add a content
assertion matching the gate used by precompile-server-unique-build.config.ts,
checking the generated snapshot contents for absence of the runtime
resolution/normalization markers such as meta:description and new Map. Keep the
existing size logging and fail the build when the stripped snapshot still
contains those markers.
bench/precompile-perf-ci.mjs (1)

212-223: 🩺 Stability & Availability | 🔵 Trivial

Heap-growth retry cap may cause occasional CI flakiness.

Only 3 attempts before throwing A GC interrupted every experimental precompile heap-growth sample. On noisy CI runners with unpredictable background GC, this could intermittently fail the gate rather than just re-sampling. Consider raising the attempt count or backing off with a short delay between attempts if this proves flaky in practice.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@bench/precompile-perf-ci.mjs` around lines 212 - 223, Increase the retry
allowance in the measure function so transient GC interruptions on noisy CI
runners do not fail the benchmark after only three samples. Preserve the
existing forceGC, sampling, and nonnegative-value behavior, and keep the final
error as the fallback after the expanded retry limit.
packages/react/src/precompiled/server.ts (1)

34-39: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Unnecessary useRef guard in SSR context.

In React SSR (e.g., renderToString, renderToPipeableStream), hook state does not persist across render passes. If the component re-renders (for example, due to a Suspense boundary retry), React initializes a fresh useRef object on every execution.

As a result, this registered guard behaves identically to an unguarded array push and provides no protection against multiple executions. Consider removing it entirely to simplify the hook, as unhead safely handles duplicate tags downstream during renderSSRHead.

♻️ Proposed refactor
-  const registered = useRef(false)
-  if (!registered.current) {
-    head._p.push(input as unknown as PrecompiledHeadInput)
-    registered.current = true
-  }
+  head._p.push(input as unknown as PrecompiledHeadInput)

(Note: You can also remove useRef from the React imports at the top of the file.)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/react/src/precompiled/server.ts` around lines 34 - 39, Remove the
registered useRef guard from the precompiled head registration logic so input is
pushed directly to head._p during SSR execution. Also remove the now-unused
useRef import, while preserving the existing input cast and registration
behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@bench/bundle/bundles.ts`:
- Around line 25-34: Update the precompileClientDeferredAsync bundle entry to
reference the deferred build’s actual generated chunk rather than hardcoding
chunks/client.mjs. Align its file value with the existing deferred-build output
or generation mechanism so it remains valid when Rollup changes the chunk name,
while preserving the entry’s comparison and category.

In `@packages/react/src/precompiled/client-csr.ts`:
- Around line 36-39: Prevent useEffect thrashing by storing the finalized plan
in a useRef and using planRef.current when calling head.push, while removing
plan from the effect dependencies. Apply this change in
packages/react/src/precompiled/client-csr.ts lines 36-39 and
packages/react/src/precompiled/client-deferred.ts lines 36-39; retain head as
the dependency.

In `@packages/svelte/src/precompiled/client.ts`:
- Around line 9-12: The precompiled Svelte and Solid useHead adapters require
options and throw when transformed calls omit them. In
packages/svelte/src/precompiled/client.ts lines 9-12,
packages/svelte/src/precompiled/client-csr.ts lines 11-14, and
packages/svelte/src/precompiled/client-deferred.ts lines 11-14, make options
optional and resolve head from the Svelte context when absent; update each
useSeoMeta cast signature accordingly. In
packages/solid-js/src/precompiled/server.ts lines 8-10, make options optional,
fall back to the Solid context when omitted, and update the useSeoMeta cast
signature accordingly.

---

Nitpick comments:
In `@bench/bundle/precompile-server-snapshot-build.config.ts`:
- Around line 29-33: Update the build:done hook in the snapshot configuration to
add a content assertion matching the gate used by
precompile-server-unique-build.config.ts, checking the generated snapshot
contents for absence of the runtime resolution/normalization markers such as
meta:description and new Map. Keep the existing size logging and fail the build
when the stripped snapshot still contains those markers.

In `@bench/precompile-perf-ci.mjs`:
- Around line 212-223: Increase the retry allowance in the measure function so
transient GC interruptions on noisy CI runners do not fail the benchmark after
only three samples. Preserve the existing forceGC, sampling, and
nonnegative-value behavior, and keep the final error as the fallback after the
expanded retry limit.

In `@packages/react/src/precompiled/server.ts`:
- Around line 34-39: Remove the registered useRef guard from the precompiled
head registration logic so input is pushed directly to head._p during SSR
execution. Also remove the now-unused useRef import, while preserving the
existing input cast and registration behavior.

In `@packages/unhead/precompiled.build.config.ts`:
- Around line 8-11: Update the comment adjacent to failOnWarn in the precompiled
build configuration to describe the first pass as emitting the initial
precompiled entries before the rest of the package exists, rather than claiming
it emits one export. Keep the existing build behavior unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 59e87ef1-d20a-4d30-8a13-2e9cd2fe0ace

📥 Commits

Reviewing files that changed from the base of the PR and between e627e0a and 75df23a.

📒 Files selected for processing (101)
  • .github/workflows/bundle-size.yml
  • bench/bundle/bundles.ts
  • bench/bundle/precompile-client-deferred-runtime-build.config.ts
  • bench/bundle/precompile-client-profile-build.config.ts
  • bench/bundle/precompile-client-runtime-build.config.ts
  • bench/bundle/precompile-report.ts
  • bench/bundle/precompile-runtime-build.config.ts
  • bench/bundle/precompile-server-snapshot-build.config.ts
  • bench/bundle/precompile-server-unique-build.config.ts
  • bench/bundle/src/client/precompile-runtime-off.ts
  • bench/bundle/src/client/precompile-runtime.ts
  • bench/bundle/src/client/precompile-snapshot.ts
  • bench/bundle/src/vue-server/precompile-runtime-off.ts
  • bench/bundle/src/vue-server/precompile-runtime.ts
  • bench/bundle/src/vue-server/precompile-snapshot.ts
  • bench/bundle/src/vue-server/precompile-unique.ts
  • bench/bundle/vue-client-seo-plugin-build.config.ts
  • bench/precompile-gate.mjs
  • bench/precompile-perf-ci.mjs
  • docs/head/1.guides/build-plugins/0.overview.md
  • package.json
  • packages/bundler/README.md
  • packages/bundler/src/unplugin/CreateHeadTransform.ts
  • packages/bundler/src/unplugin/createTransformPipeline.ts
  • packages/bundler/src/unplugin/framework.ts
  • packages/bundler/src/unplugin/types.ts
  • packages/bundler/src/unplugin/vite.ts
  • packages/bundler/test/createHeadTransform.test.ts
  • packages/bundler/test/fixtures/vite-build/precompiled-client.ts
  • packages/bundler/test/framework.test.ts
  • packages/bundler/test/precompileTransform.test.ts
  • packages/bundler/test/viteBuild.integration.test.ts
  • packages/react/build.config.ts
  • packages/react/package.json
  • packages/react/src/precompiled/client-csr.ts
  • packages/react/src/precompiled/client-deferred.ts
  • packages/react/src/precompiled/client.ts
  • packages/react/src/precompiled/index.ts
  • packages/react/src/precompiled/server.ts
  • packages/react/test/precompiledClient.test.tsx
  • packages/react/test/precompiledClientProfiles.test.tsx
  • packages/react/test/precompiledNeutral.test.ts
  • packages/react/test/precompiledServer.test.tsx
  • packages/react/test/public-types.test.ts
  • packages/react/vitest.config.ts
  • packages/solid-js/build.config.ts
  • packages/solid-js/package.json
  • packages/solid-js/src/precompiled.ts
  • packages/solid-js/src/precompiled/client-csr.ts
  • packages/solid-js/src/precompiled/client-deferred.ts
  • packages/solid-js/src/precompiled/client.ts
  • packages/solid-js/src/precompiled/server.ts
  • packages/solid-js/test/precompiled.test.ts
  • packages/solid-js/vitest.config.ts
  • packages/svelte/build.config.ts
  • packages/svelte/package.json
  • packages/svelte/src/precompiled.ts
  • packages/svelte/src/precompiled/client-csr.ts
  • packages/svelte/src/precompiled/client-deferred.ts
  • packages/svelte/src/precompiled/client.ts
  • packages/svelte/src/precompiled/server.ts
  • packages/svelte/test/fixtures/Precompiled.svelte
  • packages/svelte/test/fixtures/PrecompiledCsr.svelte
  • packages/svelte/test/fixtures/PrecompiledDeferred.svelte
  • packages/svelte/test/precompiled.test.ts
  • packages/svelte/vitest.config.ts
  • packages/unhead/build.config.ts
  • packages/unhead/package.json
  • packages/unhead/precompiled.build.config.ts
  • packages/unhead/src/precompiled/client-csr.ts
  • packages/unhead/src/precompiled/client-deferred.ts
  • packages/unhead/src/precompiled/client-snapshot.ts
  • packages/unhead/src/precompiled/client.ts
  • packages/unhead/src/precompiled/server-snapshot.ts
  • packages/unhead/src/precompiled/server-unique.ts
  • packages/unhead/src/precompiled/server.ts
  • packages/unhead/src/server/createHead.ts
  • packages/unhead/src/server/defaults.ts
  • packages/unhead/src/utils/resolve.ts
  • packages/unhead/test/unit/precompiledClient.test.ts
  • packages/unhead/test/unit/precompiledClientCsr.test.ts
  • packages/unhead/test/unit/precompiledClientDeferred.test.ts
  • packages/unhead/test/unit/precompiledServer.test.ts
  • packages/unhead/test/unit/precompiledSnapshot.test.ts
  • packages/unhead/test/unit/precompiledUnique.test.ts
  • packages/vue/build.config.ts
  • packages/vue/package.json
  • packages/vue/src/precompiled/client-csr.ts
  • packages/vue/src/precompiled/client-deferred.ts
  • packages/vue/src/precompiled/client.ts
  • packages/vue/src/precompiled/index.ts
  • packages/vue/src/precompiled/server.ts
  • packages/vue/test/unit/precompiledClient.test.ts
  • packages/vue/test/unit/precompiledClientProfiles.test.ts
  • packages/vue/test/unit/precompiledServer.test.ts
  • packages/vue/vitest.config.ts
  • test/exports/react.yaml
  • test/exports/solid-js.yaml
  • test/exports/svelte.yaml
  • test/exports/unhead.yaml
  • test/exports/vue.yaml
🚧 Files skipped from review as they are similar to previous changes (6)
  • packages/bundler/src/unplugin/vite.ts
  • bench/bundle/src/vue-server/precompile-runtime-off.ts
  • packages/bundler/src/unplugin/framework.ts
  • .github/workflows/bundle-size.yml
  • packages/bundler/README.md
  • package.json

Comment thread bench/bundle/bundles.ts Resolved
# Conflicts:
#	.github/workflows/bundle-size.yml
#	bench/bundle/report.ts
#	packages/bundler/src/unplugin/MinifyTransform.ts
@harlan-zw

harlan-zw commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator Author

🤖 CLOSED

Harlan Agent Kit posted this automated review. It is not Harlan's personal review or approval. AI open source policy. Last updated: 2026-11-07 06:45 UTC.

GitHub closed this pull request. No further automated Review will run.

@harlan-zw harlan-zw added enhancement New feature or request v3 Targets Unhead v3 or the main branch labels Jul 29, 2026
@harlan-zw harlan-zw changed the title feat(bundler): precompile static head entries feat(bundler): experimental precompile static head entries Aug 3, 2026
@harlan-zw harlan-zw added harlan-agent-running An Agent holds a Task on this issue or pull request right now. harlan-agent-blocked The automated Review found a material defect in this head commit. and removed harlan-agent-running An Agent holds a Task on this issue or pull request right now. harlan-agent-blocked The automated Review found a material defect in this head commit. labels Oct 31, 2026
@harlan-zw harlan-zw added harlan-agent-running An Agent holds a Task on this issue or pull request right now. harlan-agent-blocked The automated Review found a material defect in this head commit. and removed harlan-agent-running An Agent holds a Task on this issue or pull request right now. harlan-agent-blocked The automated Review found a material defect in this head commit. labels Oct 31, 2026
@harlan-zw harlan-zw added harlan-agent-running An Agent holds a Task on this issue or pull request right now. harlan-agent-ready The automated Review passed every gate on this head commit. harlan-agent-blocked The automated Review found a material defect in this head commit. and removed harlan-agent-running An Agent holds a Task on this issue or pull request right now. harlan-agent-ready The automated Review passed every gate on this head commit. harlan-agent-blocked The automated Review found a material defect in this head commit. labels Oct 31, 2026
@harlan-zw harlan-zw closed this Nov 7, 2026
@harlan-zw harlan-zw removed the harlan-agent-blocked The automated Review found a material defect in this head commit. label Nov 7, 2026
@harlan-zw harlan-zw mentioned this pull request Nov 7, 2026
1 of 6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request v3 Targets Unhead v3 or the main branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants