Skip to content

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

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

feat!: migrate Nuxt Scripts v2 to Unhead 3#832
harlan-zw wants to merge 15 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 20, 2026 1:17pm

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: 423bcbe

@coderabbitai

coderabbitai Bot commented Jul 19, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3971befb-e4b6-4b5d-8c82-bc78ad3eaa14

📥 Commits

Reviewing files that changed from the base of the PR and between 96afd55 and 423bcbe.

📒 Files selected for processing (36)
  • packages/script/src/registry.ts
  • test/e2e-dev/first-party.test.ts
  • test/fixtures/first-party/pages/adsense.vue
  • test/fixtures/first-party/pages/bing.vue
  • test/fixtures/first-party/pages/cfwa.vue
  • test/fixtures/first-party/pages/clarity.vue
  • test/fixtures/first-party/pages/crisp-test.vue
  • test/fixtures/first-party/pages/databuddy.vue
  • test/fixtures/first-party/pages/fathom.vue
  • test/fixtures/first-party/pages/ga.vue
  • test/fixtures/first-party/pages/google-maps-test.vue
  • test/fixtures/first-party/pages/google-sign-in-test.vue
  • test/fixtures/first-party/pages/gravatar-test.vue
  • test/fixtures/first-party/pages/gtm.vue
  • test/fixtures/first-party/pages/hotjar.vue
  • test/fixtures/first-party/pages/intercom-test.vue
  • test/fixtures/first-party/pages/lemonsqueezy.vue
  • test/fixtures/first-party/pages/matomo.vue
  • test/fixtures/first-party/pages/meta.vue
  • test/fixtures/first-party/pages/mixpanel.vue
  • test/fixtures/first-party/pages/npm-test.vue
  • test/fixtures/first-party/pages/paypal-test.vue
  • test/fixtures/first-party/pages/plausible.vue
  • test/fixtures/first-party/pages/posthog.vue
  • test/fixtures/first-party/pages/recaptcha-test.vue
  • test/fixtures/first-party/pages/reddit.vue
  • test/fixtures/first-party/pages/rybbit.vue
  • test/fixtures/first-party/pages/segment.vue
  • test/fixtures/first-party/pages/stripe-test.vue
  • test/fixtures/first-party/pages/tiktok.vue
  • test/fixtures/first-party/pages/umami.vue
  • test/fixtures/first-party/pages/vercel-analytics.vue
  • test/fixtures/first-party/pages/vimeo.vue
  • test/fixtures/first-party/pages/x.vue
  • test/fixtures/first-party/pages/youtube.vue
  • test/unit/third-party-proxy-replacements.test.ts

📝 Walkthrough

Walkthrough

The update moves script readiness and ownership to lifecycle-aware Unhead APIs. It adds abortable operations, per-consumer disposal, shared script facades, trigger cleanup, vendor readiness resolvers, and component teardown. Devtools and server handlers gain bounded request processing, cancellation, cache scoping, and streamed responses. Nuxt and Unhead compatibility requirements are tightened, with corresponding documentation, dependency updates, and lifecycle tests.

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 matches the changeset and covers the migration, lifecycle updates, and proxy 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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 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
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