Skip to content

feat!: migrate Nuxt Scripts v2 to Unhead 3#832

Open
harlan-zw wants to merge 19 commits into
mainfrom
feat/v2-unhead-3
Open

feat!: migrate Nuxt Scripts v2 to Unhead 3#832
harlan-zw wants to merge 19 commits into
mainfrom
feat/v2-unhead-3

Conversation

@harlan-zw

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

Copy link
Copy Markdown
Collaborator

🔗 Linked issue

Supersedes #829

Related to unjs/unhead#840

❓ Type of change

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

📚 Description

Nuxt 4.5 provides the Unhead 3 script lifecycle APIs needed by #829. This folds that cleanup work into the v2 migration: dependencies require Nuxt 4.5 and Unhead 3.2, useScript uses consumer scopes, provider SDKs use resolve({ waitFor }), and trigger helpers use Unhead factories.

Cleanup remains app-owned for $scripts, devtools observers, reloads, and provider callbacks. Component callers can release their own scope with dispose().

The live-provider fixture now loads one real SDK per page. It also covers Clarity's current bootstrap hosts so its child SDK, collection requests, and consent sync stay on the first-party proxy.

⚠️ Breaking changes

  • Nuxt Scripts requires Nuxt 4.5+, @unhead/vue 3.2+, and unhead 3.2+.
  • useScript() exposes the Unhead consumer scope, including signal, script, and dispose().
  • Google Maps and YouTube resolve concrete SDK APIs after readiness instead of returning nested promises.
  • Idle, interaction, and service-worker helpers return UseScriptTrigger functions.

📝 Migration

Run npx nuxi@latest upgrade --force, then update any direct Unhead dependencies to 3.2 or newer. Use dispose() to release one consumer scope; remove() still unloads the shared script for every consumer.

See docs/content/docs/4.migration-guide/2.v1-to-v2.md for the full guide.

✅ Verification

  • pnpm lint
  • pnpm typecheck
  • pnpm build
  • pnpm test:run: 978 passed, 8 skipped, 3 todo, no type errors
  • pnpm test:e2e-dev: 84 passed against live third-party SDKs

@vercel

vercel Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
scripts-playground Ready Ready Preview, Comment Jul 21, 2026 2:54pm

Request Review

@socket-security

socket-security Bot commented Jul 19, 2026

Copy link
Copy Markdown

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Added@​types/​semver@​7.7.11001007481100
Added@​unhead/​vue@​3.2.110010010096100
Addedunhead@​3.2.11001009996100

View full report

@pkg-pr-new

pkg-pr-new Bot commented Jul 19, 2026

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/@nuxt/scripts@832

commit: 4ea62dd

@coderabbitai

coderabbitai Bot commented Jul 19, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@harlan-zw, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 19 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 05b58cd3-9e53-45d1-a10b-e1e301e46e87

📥 Commits

Reviewing files that changed from the base of the PR and between c744044 and 4ea62dd.

📒 Files selected for processing (2)
  • package.json
  • packages/script/package.json
📝 Walkthrough

Walkthrough

The PR upgrades Nuxt Scripts to Nuxt 4.5 and Unhead 3.2, introduces lifecycle-aware shared script ownership and SDK readiness resolution, and adds abortable cleanup across scripts, components, registries, devtools, and server proxy flows. It also bounds cache and request sizes, streams upstream responses, updates trigger APIs and public types, expands lifecycle tests, adjusts first-party fixtures, and documents installation and v1-to-v2 migration behavior.

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

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.21% 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 title clearly summarizes the main change: migrating Nuxt Scripts v2 to Unhead 3.
Description check ✅ Passed The description is directly related to the PR and accurately explains the migration and lifecycle changes.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/v2-unhead-3

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.

@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

Caution

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

⚠️ Outside diff range comments (1)
packages/script/src/devtools.ts (1)

100-135: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Decode the full body once instead of per chunk to avoid corrupting multi-byte UTF-8.

body += chunk.toString() decodes each Buffer independently. If a multi-byte UTF-8 sequence straddles a chunk boundary (realistic for payloads above ~64KiB, and the cap here is 2MiB), each toString() emits replacement characters and JSON.parse fails with a spurious 400. Accumulate the bytes and decode once, mirroring the Uint8Array + TextDecoder approach already used in packages/script/src/runtime/server/proxy-handler.ts.

🐛 Proposed fix
       if (req.method === 'POST') {
-        let body = ''
+        const chunks: Buffer[] = []
         let size = 0
         let finished = false
@@
         function onAborted() {
           finished = true
-          body = ''
+          chunks.length = 0
           cleanup()
         }
         function onData(chunk: Buffer) {
           if (finished)
             return
           size += chunk.byteLength
           if (size > DEVTOOLS_API_MAX_BODY_SIZE) {
             finished = true
-            body = ''
+            chunks.length = 0
             cleanup()
@@
             res.end('payload too large')
             return
           }
-          body += chunk.toString()
+          chunks.push(chunk)
         }
         function onEnd() {
           if (finished)
             return
           finished = true
           cleanup()
           try {
-            const data = JSON.parse(body)
+            const data = JSON.parse(Buffer.concat(chunks).toString('utf8'))
             scriptsState = { ...data, updatedAt: Date.now() }
             res.statusCode = 200
             res.end('ok')
           }
           catch {
             res.statusCode = 400
             res.end('invalid json')
           }
-          body = ''
+          chunks.length = 0
         }
🤖 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/script/src/devtools.ts` around lines 100 - 135, Update the
request-body accumulation in the onData and onEnd handlers to retain raw
Buffer/Uint8Array chunks and decode the complete body only once after receiving
the end event, following the existing TextDecoder approach in proxy-handler.ts.
Preserve the size-limit handling and JSON parsing behavior while eliminating
per-chunk UTF-8 decoding.
🧹 Nitpick comments (1)
packages/script/src/runtime/registry/google-maps.ts (1)

54-77: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

Extract the shared "install-and-restore global readiness handler" pattern. All three resolvers reimplement the same previousReady capture → restoreReadyonReady (invoke prior handler with dev-error logging → resolve/reject) sequence. A single helper (parameterized by getter/setter/deleter for the global slot and an optional "verify API present else reject" callback) would remove the duplication and keep the restore semantics consistent.

  • packages/script/src/runtime/registry/google-maps.ts#L54-L77: replace the inline maps.__ib__ install/restore block with the shared helper (resolve { maps }, no reject path).
  • packages/script/src/runtime/registry/crisp.ts#L56-L82: use the helper for window.CRISP_READY_TRIGGER, passing the $crisp?.is presence check for the reject path.
  • packages/script/src/runtime/registry/youtube-player.ts#L50-L76: use the helper for window.onYouTubeIframeAPIReady, passing the window.YT presence check for the reject path.
🤖 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/script/src/runtime/registry/google-maps.ts` around lines 54 - 77,
Extract the shared global readiness-handler installation and restoration logic
into one helper, including prior-handler invocation, dev-error logging, and
restoration semantics. In packages/script/src/runtime/registry/google-maps.ts
lines 54-77, replace the inline block while resolving { maps } without a reject
callback; apply the helper in packages/script/src/runtime/registry/crisp.ts
lines 56-82 with the $crisp?.is presence check for rejection; and apply it in
packages/script/src/runtime/registry/youtube-player.ts lines 50-76 with the
window.YT presence check for rejection.
🤖 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/script/src/module.ts`:
- Around line 537-552: Update the Unhead package resolution around
readPackageJSON to iterate through nuxt.options.modulesDir and call it
separately for each modules directory, selecting the first valid package result
for `@unhead/vue` and unhead. Preserve the existing incompatibleUnheadPackages
validation and error behavior after resolution.

---

Outside diff comments:
In `@packages/script/src/devtools.ts`:
- Around line 100-135: Update the request-body accumulation in the onData and
onEnd handlers to retain raw Buffer/Uint8Array chunks and decode the complete
body only once after receiving the end event, following the existing TextDecoder
approach in proxy-handler.ts. Preserve the size-limit handling and JSON parsing
behavior while eliminating per-chunk UTF-8 decoding.

---

Nitpick comments:
In `@packages/script/src/runtime/registry/google-maps.ts`:
- Around line 54-77: Extract the shared global readiness-handler installation
and restoration logic into one helper, including prior-handler invocation,
dev-error logging, and restoration semantics. In
packages/script/src/runtime/registry/google-maps.ts lines 54-77, replace the
inline block while resolving { maps } without a reject callback; apply the
helper in packages/script/src/runtime/registry/crisp.ts lines 56-82 with the
$crisp?.is presence check for rejection; and apply it in
packages/script/src/runtime/registry/youtube-player.ts lines 50-76 with the
window.YT presence check for rejection.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 12b3d139-67b6-42fa-985b-ee8e9481e712

📥 Commits

Reviewing files that changed from the base of the PR and between 9293d18 and a118eb1.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (56)
  • docs/content/docs/1.getting-started/2.installation.md
  • docs/content/docs/3.api/1.use-script.md
  • docs/content/docs/4.migration-guide/2.v1-to-v2.md
  • package.json
  • packages/devtools-app/composables/rpc.ts
  • packages/devtools-app/composables/state.ts
  • packages/devtools-app/utils/fetch.ts
  • packages/script/package.json
  • packages/script/src/devtools.ts
  • packages/script/src/module.ts
  • packages/script/src/registry-types.json
  • packages/script/src/runtime/components/GoogleMaps/ScriptGoogleMaps.vue
  • packages/script/src/runtime/components/GoogleMaps/useGoogleMapsResource.ts
  • packages/script/src/runtime/components/ScriptCarbonAds.vue
  • packages/script/src/runtime/components/ScriptCrisp.vue
  • packages/script/src/runtime/components/ScriptIntercom.vue
  • packages/script/src/runtime/components/ScriptLemonSqueezy.vue
  • packages/script/src/runtime/components/ScriptPayPalButtons.vue
  • packages/script/src/runtime/components/ScriptPayPalMessages.vue
  • packages/script/src/runtime/components/ScriptStripePricingTable.vue
  • packages/script/src/runtime/components/ScriptVimeoPlayer.vue
  • packages/script/src/runtime/composables/useScript.ts
  • packages/script/src/runtime/composables/useScriptEventPage.ts
  • packages/script/src/runtime/composables/useScriptTriggerIdleTimeout.ts
  • packages/script/src/runtime/composables/useScriptTriggerInteraction.ts
  • packages/script/src/runtime/composables/useScriptTriggerServiceWorker.ts
  • packages/script/src/runtime/devtools-standalone-bridge.client.ts
  • packages/script/src/runtime/npm-script-stub.ts
  • packages/script/src/runtime/registry/crisp.ts
  • packages/script/src/runtime/registry/google-maps.ts
  • packages/script/src/runtime/registry/speedcurve.ts
  • packages/script/src/runtime/registry/usercentrics.ts
  • packages/script/src/runtime/registry/youtube-player.ts
  • packages/script/src/runtime/server/instagram-embed.ts
  • packages/script/src/runtime/server/proxy-handler.ts
  • packages/script/src/runtime/server/utils/cache-config.ts
  • packages/script/src/runtime/server/utils/cached-upstream.ts
  • packages/script/src/runtime/types.ts
  • packages/script/src/runtime/utils/abortable-promise.ts
  • packages/script/src/runtime/utils/after-next-paint.ts
  • packages/script/src/runtime/utils/nuxt-ready-script-trigger.ts
  • pnpm-workspace.yaml
  • test/e2e/base.test.ts
  • test/e2e/basic.test.ts
  • test/fixtures/unhead-v3/package.json
  • test/types/types.test-d.ts
  • test/unit/abortable-promise.test.ts
  • test/unit/cached-upstream-lifecycle.test.ts
  • test/unit/google-maps-lifecycle.test.ts
  • test/unit/npm-script-stub-lifecycle.test.ts
  • test/unit/registry-readiness.test.ts
  • test/unit/script-trigger-lifecycle.test.ts
  • test/unit/speedcurve-after-next-paint.test.ts
  • test/unit/use-script-lifecycle.test.ts
  • test/unit/youtube-player-lifecycle.test.ts
  • vitest.config.ts

Comment thread packages/script/src/module.ts
# Conflicts:
#	docs/content/docs/1.getting-started/2.installation.md
#	docs/content/docs/3.api/1.use-script.md
# Conflicts:
#	packages/script/src/runtime/server/proxy-handler.ts
#	packages/script/src/runtime/server/utils/cached-upstream.ts
@harlan-zw

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 21, 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.

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