Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions packages/script/src/plugins/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,7 @@ export function NuxtScriptBundleTransformer(options: AssetBundlerTransformerOpti
else {
// Handle case where we need to add scriptInput (registry scripts)
const integrityProps = integrityHash ? `, integrity: '${integrityHash}', crossorigin: 'anonymous'` : ''
const bundledSrcProperty = nuxt.options.dev ? `_bundledSrc: '${url}', ` : ''
if (node.arguments[0]) {
// There's at least one argument
const optionsNode = node.arguments[0]
Expand All @@ -585,17 +586,20 @@ export function NuxtScriptBundleTransformer(options: AssetBundlerTransformerOpti
s.appendLeft(scriptInput.end - 1, integrityProps)
}
else {
s.appendRight(scriptInput.end - 1, `, src: '${url}'${integrityProps}`)
const lastProperty = scriptInput.properties.at(-1)
s.appendRight(lastProperty?.end ?? scriptInput.start + 1, `${lastProperty ? ', ' : ''}src: '${url}'${integrityProps}`)
if (bundledSrcProperty)
s.appendRight(optionsNode.start + 1, bundledSrcProperty)
}
}
}
else {
s.appendRight(node.arguments[0].start + 1, ` scriptInput: { src: '${url}'${integrityProps} }, `)
s.appendRight(optionsNode.start + 1, ` ${bundledSrcProperty}scriptInput: { src: '${url}'${integrityProps} }, `)
}
}
else {
// No arguments at all, replace empty () with new argument
s.overwrite(node.callee.end, node.end, `({ scriptInput: { src: '${url}'${integrityProps} } })`)
s.overwrite(node.callee.end, node.end, `({ ${bundledSrcProperty}scriptInput: { src: '${url}'${integrityProps} } })`)
}
}
})
Expand Down
8 changes: 5 additions & 3 deletions packages/script/src/runtime/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,10 +213,12 @@ export function useRegistryScript<T extends Record<string | symbol, any>, O = Em
const init = scriptOptions.beforeInit

if (import.meta.dev) {
// A URL injected by the bundler still needs validation.
const bundledSrc = '_bundledSrc' in userOptions ? userOptions._bundledSrc : undefined
const configuredSrc = typeof scriptConfig === 'object' && scriptConfig?.scriptInput?.src
const hasCustomSrc = userSrc && (userSrc !== bundledSrc || configuredSrc)
scriptOptions._validate = () => {
// a manual trigger also means it was disabled by nuxt.config
// overriding the src will skip validation
if (!userOptions.scriptInput?.src && !scriptOptions.skipValidation && options.schema) {
if (!hasCustomSrc && !scriptOptions.skipValidation && options.schema) {
return validateScriptInputSchema(options.schema, userOptions)
}
}
Expand Down
41 changes: 41 additions & 0 deletions test/e2e/bundled-validation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { createResolver } from '@nuxt/kit'
import { createPage, url } from '@nuxt/test-utils/e2e'
import { describe, expect, it } from 'vitest'
import { setupFixture } from '../utils/setup-fixture'

const { resolve } = createResolver(import.meta.url)

describe('bundled registry validation', { timeout: 120000 }, async () => {
await setupFixture({
rootDir: resolve('../fixtures/bundled-validation'),
browser: true,
browserOptions: { type: 'chromium', launch: { headless: true } },
dev: true,
})

it('skips a bundled script with invalid options', async () => {
const page = await createPage()
try {
const logs: string[] = []
page.on('console', message => logs.push(message.text()))
await page.goto(url('/'), { waitUntil: 'hydration' })
expect(await page.textContent('#status')).toBe('awaitingLoad')
expect(await page.locator('script[data-cf-beacon]').count()).toBe(0)
expect(logs.some(log => log.includes('Skipping script `cloudflareWebAnalytics` due to invalid options'))).toBe(true)
}
finally {
await page.close()
}
})

it.each(['?valid=1', '?custom=1'])('loads the script for %s', async (query) => {
const page = await createPage()
try {
await page.goto(url(`/${query}`), { waitUntil: 'hydration' })
await expect.poll(() => page.textContent('#status')).toBe('loaded')
}
finally {
await page.close()
}
})
})
14 changes: 14 additions & 0 deletions test/fixtures/bundled-validation/app.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<script setup lang="ts">
const { custom, valid } = useRoute().query
const { status } = custom
? useScriptCloudflareWebAnalytics({
token: '123',
scriptInput: { src: 'data:text/javascript,void%200' },
scriptOptions: { bundle: false },
})
: useScriptCloudflareWebAnalytics({ token: valid ? 'a'.repeat(32) : '123' })
</script>

<template>
<p id="status">{{ status }}</p>
</template>
12 changes: 12 additions & 0 deletions test/fixtures/bundled-validation/nuxt.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { defineNuxtConfig } from 'nuxt/config'

export default defineNuxtConfig({
modules: ['@nuxt/scripts'],
compatibilityDate: '2026-11-25',
hooks: {
'scripts:registry'(registry) {
const analytics = registry.find(script => script.registryKey === 'cloudflareWebAnalytics')!
analytics.src = 'data:text/javascript,void%200'
},
},
})
Loading