Skip to content

fix(vue): batch streamed head updates via self-deleting inline scripts - #752

Merged
harlan-zw merged 2 commits into
mainfrom
fix/vue-streaming-batched-chunks
Apr 23, 2026
Merged

harlan-zw merged 2 commits into
mainfrom
fix/vue-streaming-batched-chunks

Conversation

@harlan-zw

@harlan-zw harlan-zw commented Apr 23, 2026 •

Copy link
Copy Markdown
Collaborator

🔗 Linked issue

N/A — surfaced while debugging Vue streaming hydration in examples/vite-ssr-vue-streaming.

❓ Type of change

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

📚 Description

Vue streaming relied on an SFC AST transform that injected a <HeadStream /> component into every template using useHead / useSeoMeta, plus a symmetric client vnode with data-allow-mismatch — heavy plumbing that also needed a vue-loader patch on webpack/rspack. Replaced it with per-chunk flushing in wrapStream: after each framework stream chunk, any newly added head entries are emitted as <script>window.__unhead__.push(...);document.currentScript.remove()</script>, which executes during HTML parse and removes itself before Vue hydrates. Also splits prepareStreamingTemplate at the canonical <!--app-html--> / <!--ssr-outlet--> marker so templates can wrap the stream in <div id="app">...</div> without container mismatches.

Summary by CodeRabbit

  • Refactor

    • Vue SSR streaming now emits per-chunk, self-deleting inline head update scripts between app chunks instead of using a placeholder component.
    • Vite plugin simplified to rely on index.html transforms and server streaming rather than source-level SFC injection.
    • Tests and examples updated to use the new streaming flow and template marker.
  • Chores

    • Build configuration adjusted to include previously externalized dependencies in the bundle.

@coderabbitai

coderabbitai Bot commented Apr 23, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Refactors Vue streaming SSR: removes the in-tree HeadStream component and SFC AST transforms, implements a ReadableStream-based wrapStream that injects self-deleting inline head-patch scripts, updates Vite plugin to stop source transforms, and removes three build/package dependencies.

Changes

Cohort / File(s) Summary
Dependency Management
packages/vue/package.json, packages/vue/build.config.ts
Removed magic-string, oxc-parser, and oxc-walker from package dependencies and build externals.
Stream Client Module
packages/vue/src/stream/client.ts
Removed exported HeadStream component and its Vue imports; retained createStreamableHead and other exports.
Stream Server Module
packages/vue/src/stream/server.ts, packages/unhead/src/stream/server.ts
Replaced vnode-placeholder approach with createStreamableHead().wrapStream that builds a ReadableStream, uses prepareStreamingTemplate to split template at outlet markers, forwards chunks, and injects self-deleting window.__unhead__.push(...) scripts between chunks; centralized error handling.
Vite Plugin Module
packages/vue/src/stream/vite.ts
Removed AST-based SFC transform() hook and import injection; plugin now registers streaming virtual modules and uses a never-matching transform filter; relies on index HTML transform and server stream for head updates.
Tests — Vue Streaming & Vite Plugin
packages/vue/test/streaming.test.ts, packages/vue/test/vite-plugin.test.ts, examples/vite-ssr-vue-streaming/tests/streaming.spec.ts
Updated tests to exercise wrapStream-based streaming and assert emission of self-deleting patch scripts and proper escaping; removed tests asserting SFC transform and HeadStream behavior; added plugin transform filter, resolveId, and transformIndexHtml checks.
Examples / Templates
examples/vite-ssr-vue-streaming/index.html, examples/vite-ssr-vue-streaming/src/App.vue
Added #app container with <!--app-html--> outlet marker; simplified App template root to place routed content directly.
Exports Manifest
test/exports/vue.yaml
Removed HeadStream from client/server export declarations.
Unit Tests — unhead streaming
packages/unhead/test/streaming/streaming.test.ts
Added tests verifying prepareStreamingTemplate splits template at <!--app-html--> / <!--ssr-outlet--> markers and preserves surrounding content order.

Sequence Diagram(s)

sequenceDiagram
  participant Server
  participant StreamWrapper
  participant TemplatePrep as prepareStreamingTemplate
  participant Browser
  Server->>StreamWrapper: call wrapStream(appStream, vueHead, template)
  StreamWrapper->>TemplatePrep: split template at outlet marker
  TemplatePrep-->>StreamWrapper: shell + end
  StreamWrapper->>Browser: enqueue shell
  alt upstream chunk arrives
    StreamWrapper->>Browser: forward chunk
    StreamWrapper->>Browser: enqueue inline self-deleting script (window.__unhead__.push(...))
  end
  StreamWrapper->>Browser: enqueue end
  Browser->>Browser: script executes and removes itself before hydration
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 Streams hop bright where templates play,
Self-shedding scripts clear the way,
No injected beans in SFC clay,
Patches pop, then slip away,
I nibble bugs and bound all day! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% 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
Title check ✅ Passed The PR title clearly and concisely describes the main change: replacing Vue's streaming head update mechanism with batched self-deleting inline scripts.
Description check ✅ Passed The PR description covers the linked issue, change type, and detailed explanation of the refactoring. However, it lacks complete adherence to all template sections.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 fix/vue-streaming-batched-chunks

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/unhead/src/stream/server.ts (1)

260-286: ⚠️ Potential issue | 🟠 Major

Interleaving script patches between chunks risks producing malformed HTML when chunk boundaries split mid-tag.

flushPatch is enqueued immediately after every value read from the framework stream. Verification confirms that Vue 3's renderToWebStream does not guarantee chunk boundaries align with HTML tag boundaries—chunks can split mid-tag or mid-attribute. If a chunk ends with <div class="a and the next begins with bc">, interleaving a <script>${patch};document.currentScript.remove()</script> between them produces invalid HTML: <div class="a<script>...</script>bc">.

To mitigate:

  • Coalesce pending head.entries and only emit the patch when renderSSRHeadSuspenseChunk has content to flush (already true).
  • Document the implementation's implicit "chunks must be tag-aligned" contract, or buffer chunks at the stream wrapper layer to ensure boundaries land between complete tokens before triggering flushes.
  • Verify that other frameworks (Solid, Svelte, etc.) routed through WebStreamableHeadContext.wrapStream also have this chunk-splitting behavior.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/unhead/src/stream/server.ts` around lines 260 - 286, The current
approach calls flushPatch immediately after each controller.enqueue(value),
which can split HTML tags across chunks and produce malformed markup; update the
streaming logic around flushPatch/renderSSRHeadSuspenseChunk so you buffer chunk
data (e.g., accumulate into a pending buffer between controller.enqueue calls)
and only inject the script patch when you can guarantee a safe boundary (for
example when the buffered data ends with a complete token like '>' or any other
heuristic you choose), then flush the buffered bytes through controller.enqueue
followed by the script patch; apply this change in the start(reader loop) where
controller.enqueue(value) and flushPatch are invoked and ensure the final
flushPatch after the reader completes also flushes any remaining buffered data;
also ensure WebStreamableHeadContext.wrapStream users
(renderSSRHeadSuspenseChunk/flushPatch) are compatible with this buffering
approach.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@packages/unhead/src/stream/server.ts`:
- Around line 260-286: The current approach calls flushPatch immediately after
each controller.enqueue(value), which can split HTML tags across chunks and
produce malformed markup; update the streaming logic around
flushPatch/renderSSRHeadSuspenseChunk so you buffer chunk data (e.g., accumulate
into a pending buffer between controller.enqueue calls) and only inject the
script patch when you can guarantee a safe boundary (for example when the
buffered data ends with a complete token like '>' or any other heuristic you
choose), then flush the buffered bytes through controller.enqueue followed by
the script patch; apply this change in the start(reader loop) where
controller.enqueue(value) and flushPatch are invoked and ensure the final
flushPatch after the reader completes also flushes any remaining buffered data;
also ensure WebStreamableHeadContext.wrapStream users
(renderSSRHeadSuspenseChunk/flushPatch) are compatible with this buffering
approach.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 90f23753-02ad-4a90-8085-0e5bbc49eb2f

📥 Commits

Reviewing files that changed from the base of the PR and between ea54e36 and 73f4782.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (13)
  • examples/vite-ssr-vue-streaming/index.html
  • examples/vite-ssr-vue-streaming/src/App.vue
  • examples/vite-ssr-vue-streaming/src/entry-client.ts
  • examples/vite-ssr-vue-streaming/tests/streaming.spec.ts
  • packages/unhead/src/stream/server.ts
  • packages/unhead/src/stream/vite.ts
  • packages/vue/build.config.ts
  • packages/vue/package.json
  • packages/vue/src/stream/client.ts
  • packages/vue/src/stream/server.ts
  • packages/vue/src/stream/vite.ts
  • packages/vue/test/streaming.test.ts
  • packages/vue/test/vite-plugin.test.ts
💤 Files with no reviewable changes (3)
  • examples/vite-ssr-vue-streaming/src/entry-client.ts
  • packages/vue/package.json
  • packages/vue/src/stream/client.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 (1)
packages/vue/src/stream/server.ts (1)

107-117: The named wrapStream re-export from unhead/stream/server has a different signature than the Vue-specific version and creates a footgun.

The core wrapStream(head, stream, template) and Vue-specific wrapStream(stream, template) have incompatible signatures. Users importing the named export would get the core version, causing a runtime error when called with the Vue pattern. Rename the re-export (e.g., coreWrapStream), remove it if unused, or document the distinction clearly. Current codebase avoids the issue by consistently using createStreamableHead().wrapStream.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/vue/src/stream/server.ts` around lines 107 - 117, The named
re-export wrapStream from 'unhead/stream/server' conflicts with the Vue-specific
wrapStream signature and can cause runtime errors; update the export block to
either remove the direct wrapStream re-export or rename it (e.g.,
coreWrapStream) so it won’t shadow the Vue pattern, and adjust any internal
imports/uses to call createStreamableHead().wrapStream for Vue usage or
coreWrapStream for the unhead core signature; ensure the export list in
packages/vue/src/stream/server.ts no longer exposes the incompatible wrapStream
name to consumers.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/vue/src/stream/server.ts`:
- Around line 74-89: wrapStream currently injects the streaming template (via
prepareStreamingTemplate and flushPatch) immediately after each ReadableStream
read which can split HTML tags if the source stream (e.g., a transformed/custom
stream) emits arbitrary byte boundaries; update wrapStream to buffer incoming
Uint8Array chunks and only call controller.enqueue and flushPatch when a safe
insertion point is detected (e.g., buffer ends with a complete tag boundary such
as a closing tag delimiter like '>' or a verified '</...>' sequence), falling
back to a maximum buffer size/time flush to avoid stalling; update
prepareStreamingTemplate/flushPatch references accordingly and add an
integration test that uses Vue's renderToWebStream to confirm chunk boundaries
are safe (or add clear JSDoc on wrapStream that only Vue renderToWebStream
output is supported if you choose the simpler documentation approach).

---

Nitpick comments:
In `@packages/vue/src/stream/server.ts`:
- Around line 107-117: The named re-export wrapStream from
'unhead/stream/server' conflicts with the Vue-specific wrapStream signature and
can cause runtime errors; update the export block to either remove the direct
wrapStream re-export or rename it (e.g., coreWrapStream) so it won’t shadow the
Vue pattern, and adjust any internal imports/uses to call
createStreamableHead().wrapStream for Vue usage or coreWrapStream for the unhead
core signature; ensure the export list in packages/vue/src/stream/server.ts no
longer exposes the incompatible wrapStream name to consumers.
🪄 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: 7cb776e6-377a-423a-9f25-39ab560387ae

📥 Commits

Reviewing files that changed from the base of the PR and between 73f4782 and 1d89d57.

📒 Files selected for processing (2)
  • packages/unhead/src/stream/server.ts
  • packages/vue/src/stream/server.ts

Comment thread packages/vue/src/stream/server.ts Resolved
Vue streaming relied on an SFC AST transform that injected a
`<HeadStream />` component into every template using `useHead` /
`useSeoMeta`, plus a symmetric client vnode with `data-allow-mismatch`
— heavy plumbing that also needed vue-loader patching on webpack/rspack.

Replaced it with per-chunk flushing inside the Vue `wrapStream` wrapper:
after each Vue stream chunk, any newly added head entries are emitted as
`<script>window.__unhead__.push(...);document.currentScript.remove()</script>`.
The script executes during HTML parse (updating the client head state
progressively) and removes itself before Vue hydrates, so no `<HeadStream />`
vnode or `data-allow-mismatch` workaround is needed.

Only safe on Vue because `renderToWebStream` streams chunks in document
order per resolved Suspense boundary. React / Solid / Svelte reveal
boundaries out-of-order and continue to use in-tree `<HeadStream />`.

Drops from `@unhead/vue`:
- SFC AST transform in `@unhead/vue/stream/vite` (and the `magic-string`,
  `oxc-parser`, `oxc-walker` deps)
- `HeadStream` component on server + client and the `_shellRendered`
  coordination flag
@harlan-zw
harlan-zw force-pushed the fix/vue-streaming-batched-chunks branch from 1d89d57 to a292331 Compare April 23, 2026 06:10

@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/vue/src/stream/server.ts (1)

82-97: Optional: the trailing flushPatch after the read loop is redundant.

Line 88 already calls flushPatch(controller) after every successful chunk, and no Vue code path adds new head entries between the final { done: true } read and the controller.close() call. renderSSRHeadSuspenseChunk returns an empty string when head.entries.size === 0, so the extra call on line 95 is a no-op in practice — fine to leave, but can be removed for clarity.

♻️ Proposed simplification
             }
             finally {
               reader.releaseLock()
             }

-            flushPatch(controller)
             controller.enqueue(encoder.encode(end))
             controller.close()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/vue/src/stream/server.ts` around lines 82 - 97, The trailing call to
flushPatch(controller) after the read loop is redundant since
flushPatch(controller) is already invoked for every chunk inside the loop (see
reader.read() loop and flushPatch references); remove the extra
flushPatch(controller) that occurs just before
controller.enqueue(encoder.encode(end)) and controller.close() so the
finalization only enqueues the end marker and closes the controller, leaving
reader.releaseLock() and the in-loop flushes intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/vue/src/stream/server.ts`:
- Around line 82-97: The trailing call to flushPatch(controller) after the read
loop is redundant since flushPatch(controller) is already invoked for every
chunk inside the loop (see reader.read() loop and flushPatch references); remove
the extra flushPatch(controller) that occurs just before
controller.enqueue(encoder.encode(end)) and controller.close() so the
finalization only enqueues the end marker and closes the controller, leaving
reader.releaseLock() and the in-loop flushes intact.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8ca9f499-58b1-4a59-a36c-995c568df530

📥 Commits

Reviewing files that changed from the base of the PR and between 1d89d57 and a292331.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (8)
  • examples/vite-ssr-vue-streaming/tests/streaming.spec.ts
  • packages/vue/build.config.ts
  • packages/vue/package.json
  • packages/vue/src/stream/client.ts
  • packages/vue/src/stream/server.ts
  • packages/vue/src/stream/vite.ts
  • packages/vue/test/streaming.test.ts
  • packages/vue/test/vite-plugin.test.ts
💤 Files with no reviewable changes (2)
  • packages/vue/package.json
  • packages/vue/src/stream/client.ts
✅ Files skipped from review due to trivial changes (1)
  • examples/vite-ssr-vue-streaming/tests/streaming.spec.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/vue/build.config.ts
  • packages/vue/test/streaming.test.ts

prepareStreamingTemplate now splits at <!--app-html--> / <!--ssr-outlet-->
when present so streamed app content lands inside the mount container.
Falls back to <body>/</body> splitting when no marker exists.

Without marker support, an `<div id="app">` in the template ended up
after the streamed Vue output, forcing apps to wrap their root component
in a redundant `<div id="app">`. That setup hydrated incorrectly because
`app.mount('#app')` treats `#app` as a container and expects App's root
vnode to be its first child, not the container itself.

- examples/vite-ssr-vue-streaming: add #app container in index.html and
  drop the redundant wrapper from App.vue
- streaming.spec.ts: stop filtering hydration warnings (was masking the
  bug) and assert on warnings as well as errors
- update stale exports snapshot (HeadStream was removed by the previous
  commit on this branch)

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/unhead/src/stream/server.ts (1)

357-363: ⚠️ Potential issue | 🟡 Minor

Strip the artificial suffix from the tail only.

Line 363 removes the first </body></html> occurrence. If the template already contains that literal earlier, for example inside an inline script string, this corrupts the template and leaves the artificial suffix in shell.

🐛 Proposed fix
+    const artificialShellSuffix = '</body></html>'
     const shellParsed = parseHtmlForIndexes(`${shellPart}</body></html>`)
-    const shell = applyHeadToHtml(shellParsed, {
+    const shellWithInjectedHead = applyHeadToHtml(shellParsed, {
       htmlAttrs: ssr.htmlAttrs,
       headTags: bootstrapScript + ssr.headTags,
       bodyAttrs: ssr.bodyAttrs,
       bodyTags: '',
-    }).replace('</body></html>', '')
+    })
+    const shell = shellWithInjectedHead.endsWith(artificialShellSuffix)
+      ? shellWithInjectedHead.slice(0, -artificialShellSuffix.length)
+      : shellWithInjectedHead
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/unhead/src/stream/server.ts` around lines 357 - 363, The code
currently removes the first occurrence of the artificial suffix by using
.replace('</body></html>','') which can corrupt templates if that literal
appears earlier; change the logic around shell creation (after
parseHtmlForIndexes and applyHeadToHtml where shellParsed, shellPart and shell
are used) to strip the artificial suffix only from the tail — detect if the
resulting string endsWith('</body></html>') and if so remove that trailing
substring (or remove the lastIndexOf occurrence at the string end) instead of a
global/first replace so embedded occurrences are preserved.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@packages/unhead/src/stream/server.ts`:
- Around line 357-363: The code currently removes the first occurrence of the
artificial suffix by using .replace('</body></html>','') which can corrupt
templates if that literal appears earlier; change the logic around shell
creation (after parseHtmlForIndexes and applyHeadToHtml where shellParsed,
shellPart and shell are used) to strip the artificial suffix only from the tail
— detect if the resulting string endsWith('</body></html>') and if so remove
that trailing substring (or remove the lastIndexOf occurrence at the string end)
instead of a global/first replace so embedded occurrences are preserved.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 57efd665-b6e7-4b12-9842-cfc632b612a1

📥 Commits

Reviewing files that changed from the base of the PR and between a292331 and f363884.

📒 Files selected for processing (6)
  • examples/vite-ssr-vue-streaming/index.html
  • examples/vite-ssr-vue-streaming/src/App.vue
  • examples/vite-ssr-vue-streaming/tests/streaming.spec.ts
  • packages/unhead/src/stream/server.ts
  • packages/unhead/test/streaming/streaming.test.ts
  • test/exports/vue.yaml
💤 Files with no reviewable changes (1)
  • test/exports/vue.yaml
✅ Files skipped from review due to trivial changes (2)
  • examples/vite-ssr-vue-streaming/src/App.vue
  • packages/unhead/test/streaming/streaming.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/vite-ssr-vue-streaming/tests/streaming.spec.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant