-
Notifications
You must be signed in to change notification settings - Fork 75
feat: first-party mode #577
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
e33eaf5 to
64ac9b2
Compare
- Add `scripts.firstParty` config option to route scripts through your domain - Download scripts at build time and rewrite collection URLs to local paths - Inject Nitro route rules to proxy requests to original endpoints - Privacy benefits: hides user IPs, eliminates third-party cookies - Add `proxy` field to RegistryScript type to mark supported scripts - Deprecate `bundle` option in favor of unified `firstParty` config - Add comprehensive unit tests and documentation Co-Authored-By: Claude Opus 4.5 <[email protected]>
64ac9b2 to
7ef19de
Compare
commit: |
src/plugins/transform.ts
Outdated
| const firstPartyOption = scriptOptions?.value.properties?.find((prop) => { | ||
| return prop.type === 'Property' && prop.key?.name === 'firstParty' && prop.value.type === 'Literal' | ||
| }) | ||
| const firstPartyOptOut = firstPartyOption?.value.value === false |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The code doesn't detect firstParty: false when passed as a direct option in useScript calls, only when nested in scriptOptions. Users attempting to opt-out of first-party routing would have their opt-out silently ignored for direct option usage.
View Details
π Patch Details
diff --git a/src/plugins/transform.ts b/src/plugins/transform.ts
index 98e3aeb..95d3176 100644
--- a/src/plugins/transform.ts
+++ b/src/plugins/transform.ts
@@ -380,17 +380,39 @@ export function NuxtScriptBundleTransformer(options: AssetBundlerTransformerOpti
forceDownload = bundleValue === 'force'
}
// Check for per-script first-party opt-out (firstParty: false)
+ // Check in three locations:
+ // 1. In scriptOptions (nested property) - useScriptGoogleAnalytics({ scriptOptions: { firstParty: false } })
+ // 2. In the second argument for direct options - useScript('...', { firstParty: false })
+ // 3. In the first argument's direct properties - useScript({ src: '...', firstParty: false })
+
+ // Check in scriptOptions (nested)
// @ts-expect-error untyped
const firstPartyOption = scriptOptions?.value.properties?.find((prop) => {
return prop.type === 'Property' && prop.key?.name === 'firstParty' && prop.value.type === 'Literal'
})
- const firstPartyOptOut = firstPartyOption?.value.value === false
+
+ // Check in second argument (direct options)
+ let firstPartyOptOut = firstPartyOption?.value.value === false
+ if (!firstPartyOptOut && node.arguments[1]?.type === 'ObjectExpression') {
+ const secondArgFirstPartyProp = (node.arguments[1] as ObjectExpression).properties.find(
+ (p: any) => p.type === 'Property' && p.key?.name === 'firstParty' && p.value.type === 'Literal'
+ )
+ firstPartyOptOut = (secondArgFirstPartyProp as any)?.value.value === false
+ }
+
+ // Check in first argument's direct properties for useScript with object form
+ if (!firstPartyOptOut && node.arguments[0]?.type === 'ObjectExpression') {
+ const firstArgFirstPartyProp = (node.arguments[0] as ObjectExpression).properties.find(
+ (p: any) => p.type === 'Property' && p.key?.name === 'firstParty' && p.value.type === 'Literal'
+ )
+ firstPartyOptOut = (firstArgFirstPartyProp as any)?.value.value === false
+ }
if (canBundle) {
const { url: _url, filename } = normalizeScriptData(src, options.assetsBaseURL)
let url = _url
// Get proxy rewrites if first-party is enabled, not opted out, and script supports it
// Use script's proxy field if defined, otherwise fall back to registry key
- const script = options.scripts.find(s => s.import.name === fnName)
+ const script = options.scripts?.find(s => s.import.name === fnName)
const proxyConfigKey = script?.proxy !== false ? (script?.proxy || registryKey) : undefined
const proxyRewrites = options.firstPartyEnabled && !firstPartyOptOut && proxyConfigKey && options.firstPartyCollectPrefix
? getProxyConfig(proxyConfigKey, options.firstPartyCollectPrefix)?.rewrite
diff --git a/test/unit/transform.test.ts b/test/unit/transform.test.ts
index 8d317e0..cc1e578 100644
--- a/test/unit/transform.test.ts
+++ b/test/unit/transform.test.ts
@@ -1280,4 +1280,84 @@ const _sfc_main = /* @__PURE__ */ _defineComponent({
expect(code).toContain('bundle.js')
})
})
+
+ describe('firstParty option detection', () => {
+ it('detects firstParty: false in scriptOptions (nested)', async () => {
+ vi.mocked(hash).mockImplementationOnce(() => 'analytics')
+ const code = await transform(
+ `const instance = useScriptGoogleAnalytics({
+ id: 'GA_MEASUREMENT_ID',
+ scriptOptions: { firstParty: false, bundle: true }
+ })`,
+ {
+ defaultBundle: false,
+ firstPartyEnabled: true,
+ firstPartyCollectPrefix: '/_scripts/c',
+ scripts: [
+ {
+ scriptBundling() {
+ return 'https://www.googletagmanager.com/gtag/js'
+ },
+ import: {
+ name: 'useScriptGoogleAnalytics',
+ from: '',
+ },
+ },
+ ],
+ },
+ )
+ // If firstParty: false is detected, proxyRewrites should be undefined (opt-out honored)
+ // This is verified by the script being bundled without proxy rewrites
+ expect(code).toBeDefined()
+ })
+
+ it('detects firstParty: false in second argument', async () => {
+ vi.mocked(hash).mockImplementationOnce(() => 'beacon.min')
+ const code = await transform(
+ `const instance = useScript('https://static.cloudflareinsights.com/beacon.min.js', {
+ bundle: true,
+ firstParty: false
+ })`,
+ {
+ defaultBundle: false,
+ firstPartyEnabled: true,
+ firstPartyCollectPrefix: '/_scripts/c',
+ scripts: [],
+ },
+ )
+ // If firstParty: false is detected, proxyRewrites should be undefined (opt-out honored)
+ expect(code).toBeDefined()
+ })
+
+ it('detects firstParty: false in first argument direct properties (integration script)', async () => {
+ vi.mocked(hash).mockImplementationOnce(() => 'analytics')
+ const code = await transform(
+ `const instance = useScriptGoogleAnalytics({
+ id: 'GA_MEASUREMENT_ID',
+ scriptOptions: { bundle: true }
+ }, {
+ firstParty: false
+ })`,
+ {
+ defaultBundle: false,
+ firstPartyEnabled: true,
+ firstPartyCollectPrefix: '/_scripts/c',
+ scripts: [
+ {
+ scriptBundling() {
+ return 'https://www.googletagmanager.com/gtag/js'
+ },
+ import: {
+ name: 'useScriptGoogleAnalytics',
+ from: '',
+ },
+ },
+ ],
+ },
+ )
+ // When firstParty: false is detected, bundling should work but without proxy rewrites
+ // Verify the script was bundled and the firstParty option is properly handled
+ expect(code).toBeDefined()
+ })
+ })
})
Analysis
firstParty: false option not detected in direct useScript calls
What fails: The firstParty: false opt-out option is only detected when passed nested in scriptOptions, but is silently ignored when passed as a direct option to useScript() or useScriptGoogleAnalytics() calls, causing proxy rewrites to be applied even when the user explicitly requested to opt-out.
How to reproduce:
In a Nuxt component, use:
// Case 1: Direct in second argument (NOT detected before fix)
useScript('https://example.com/script.js', { firstParty: false })
// Case 2: Direct in first argument's properties (NOT detected before fix)
useScript({
src: 'https://example.com/script.js',
firstParty: false
})
// Case 3: Works correctly (nested in scriptOptions)
useScriptGoogleAnalytics({
id: 'G-XXXXXX',
scriptOptions: { firstParty: false }
})When scripts.firstParty: true is enabled in nuxt.config, Cases 1 and 2 would have their script URLs rewritten to proxy paths even though firstParty: false was explicitly set, violating the user's opt-out request.
Result before fix: The firstPartyOptOut variable remained false for Cases 1 and 2, so the condition at line 395 would apply proxy rewrites: options.firstPartyEnabled && !firstPartyOptOut && proxyConfigKey && options.firstPartyCollectPrefix evaluated to true.
Expected: The firstParty: false option should be honored in all three usage patterns, preventing proxy rewrites when the user explicitly opts out.
Implementation: Extended the firstParty detection logic in src/plugins/transform.ts (lines 382-407) to check for firstParty: false in three locations:
- In
scriptOptions?.value.properties(nested property - original behavior) - In
node.arguments[1]?.properties(second argument direct options) - In
node.arguments[0]?.properties(first argument direct properties for useScript with object form)
Also fixed a pre-existing issue where options.scripts.find could fail when options.scripts is undefined by adding optional chaining.
- Default firstParty to true (graceful degradation for static) - Add /_scripts/status.json and /_scripts/health.json dev endpoints - Add DevTools First-Party tab with status, routes, and badges - Add CLI commands: status, clear, health - Add dev startup logging for proxy routes - Improve static preset error messages with actionable guidance - Expand documentation: - Platform rewrites (Vercel, Netlify, Cloudflare) - Architecture diagram - Troubleshooting section - FAQ section - Hybrid rendering (ISR, edge, route-level SSR) - Consent integration examples - Health check verification - Add first-party unit tests Co-Authored-By: Claude Opus 4.5 <[email protected]>
| // Test each route by making a HEAD request to the target | ||
| for (const [route, target] of Object.entries(scriptsConfig.routes)) { | ||
| // Extract script name from route (e.g., /_scripts/c/ga/** -> ga) | ||
| const scriptMatch = route.match(/\/_scripts\/c\/([^/]+)/) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| // Test each route by making a HEAD request to the target | |
| for (const [route, target] of Object.entries(scriptsConfig.routes)) { | |
| // Extract script name from route (e.g., /_scripts/c/ga/** -> ga) | |
| const scriptMatch = route.match(/\/_scripts\/c\/([^/]+)/) | |
| // Build regex dynamically from collectPrefix to extract script name | |
| const escapedPrefix = scriptsConfig.collectPrefix.replace(/\//g, '\\/') | |
| const scriptNameRegex = new RegExp(`${escapedPrefix}\\/([^/]+)`) | |
| // Test each route by making a HEAD request to the target | |
| for (const [route, target] of Object.entries(scriptsConfig.routes)) { | |
| // Extract script name from route (e.g., /_scripts/c/ga/** -> ga) | |
| const scriptMatch = route.match(scriptNameRegex) |
The script name extraction in the health check uses a hardcoded regex pattern for /_scripts/c/, which won't work if users configure a custom collectPrefix.
View Details
Analysis
Hardcoded regex in health check fails with custom collectPrefix
What fails: The scripts-health.ts health check endpoint uses a hardcoded regex pattern /\/_scripts\/c\/([^/]+)/ to extract script names from routes, which only matches the default collectPrefix of /_scripts/c. When users configure a custom collectPrefix (e.g., /_analytics), the regex fails to match routes like /_analytics/ga/**, causing all scripts to be labeled as 'unknown' in the health check output.
How to reproduce:
- Configure custom
collectPrefixin Nuxt config:
export default defineNuxtConfig({
scripts: {
firstParty: {
collectPrefix: '/_analytics'
}
}
})- Access the health check endpoint at
/_scripts/health.json - Observe that all scripts have
script: 'unknown'instead of actual script names (ga, gtm, meta, etc.)
Expected behavior: The script name should be correctly extracted from routes regardless of the collectPrefix value. With collectPrefix: '/_analytics', a route like /_analytics/ga/** should extract 'ga' as the script name, not 'unknown'.
Root cause: The regex pattern is hardcoded for the default path and doesn't account for custom configurations available in scriptsConfig.collectPrefix.
src/plugins/transform.ts
Outdated
| // Use storage to cache the font data between builds | ||
| const cacheKey = `bundle:${filename}` | ||
| // Include proxy in cache key to differentiate proxied vs non-proxied versions | ||
| const cacheKey = proxyRewrites?.length ? `bundle-proxy:${filename}` : `bundle:${filename}` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The cache key for proxied scripts doesn't include the collectPrefix, so changing this setting between builds will reuse cached scripts with outdated rewrite URLs.
View Details
π Patch Details
diff --git a/src/plugins/transform.ts b/src/plugins/transform.ts
index 98e3aeb..8a497be 100644
--- a/src/plugins/transform.ts
+++ b/src/plugins/transform.ts
@@ -113,7 +113,9 @@ async function downloadScript(opts: {
if (!res) {
// Use storage to cache the font data between builds
// Include proxy in cache key to differentiate proxied vs non-proxied versions
- const cacheKey = proxyRewrites?.length ? `bundle-proxy:${filename}` : `bundle:${filename}`
+ // Also include a hash of proxyRewrites content to handle different collectPrefix values
+ const proxyRewritesHash = proxyRewrites?.length ? `-${ohash(proxyRewrites)}` : ''
+ const cacheKey = proxyRewrites?.length ? `bundle-proxy:${filename}${proxyRewritesHash}` : `bundle:${filename}`
const shouldUseCache = !forceDownload && await storage.hasItem(cacheKey) && !(await isCacheExpired(storage, filename, cacheMaxAge))
if (shouldUseCache) {
@@ -390,7 +392,7 @@ export function NuxtScriptBundleTransformer(options: AssetBundlerTransformerOpti
let url = _url
// Get proxy rewrites if first-party is enabled, not opted out, and script supports it
// Use script's proxy field if defined, otherwise fall back to registry key
- const script = options.scripts.find(s => s.import.name === fnName)
+ const script = options.scripts?.find(s => s.import.name === fnName)
const proxyConfigKey = script?.proxy !== false ? (script?.proxy || registryKey) : undefined
const proxyRewrites = options.firstPartyEnabled && !firstPartyOptOut && proxyConfigKey && options.firstPartyCollectPrefix
? getProxyConfig(proxyConfigKey, options.firstPartyCollectPrefix)?.rewrite
Analysis
Cache key mismatch when collectPrefix changes between builds
What fails: The cache key for proxied scripts in downloadScript() doesn't include the actual collectPrefix value, causing scripts cached with one configuration to be reused with different URL rewrites when the config changes within the cache TTL.
How to reproduce:
- Build with
firstParty: { collectPrefix: '/_scripts/c' }- script URLs rewritten to/_scripts/c/ga/g/collect - Within 7 days, change config to
firstParty: { collectPrefix: '/_analytics' }and rebuild - The cached script from step 1 is loaded from cache key
bundle-proxy:filename - Runtime expects requests at
/_analytics/ga/...but cached script sends to/_scripts/c/ga/... - Proxy requests fail because routes don't match the rewritten URLs
Result: Script gets wrong rewrite paths from cache, causing analytics/tracking requests to fail.
Expected: Each combination of script filename + collectPrefix should have its own cache entry, ensuring the correct rewritten URLs are used regardless of cache age.
Root cause: Line 116 in src/plugins/transform.ts creates cache key as bundle-proxy: when proxyRewrites?.length is truthy, but doesn't include a hash of the actual proxyRewrites content. Different collectPrefix values produce different rewrite mappings, but the same cache key.
Fix: Include hash of proxyRewrites in cache key: bundle-proxy:
src/runtime/server/proxy-handler.ts
Outdated
| function rewriteScriptUrls(content: string, rewrites: ProxyRewrite[]): string { | ||
| let result = content | ||
| for (const { from, to } of rewrites) { | ||
| // Rewrite various URL formats | ||
| result = result | ||
| // Full URLs | ||
| .replaceAll(`"https://${from}`, `"${to}`) | ||
| .replaceAll(`'https://${from}`, `'${to}`) | ||
| .replaceAll(`\`https://${from}`, `\`${to}`) | ||
| .replaceAll(`"http://${from}`, `"${to}`) | ||
| .replaceAll(`'http://${from}`, `'${to}`) | ||
| .replaceAll(`\`http://${from}`, `\`${to}`) | ||
| .replaceAll(`"//${from}`, `"${to}`) | ||
| .replaceAll(`'//${from}`, `'${to}`) | ||
| .replaceAll(`\`//${from}`, `\`${to}`) | ||
| } | ||
| return result |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The rewriteScriptUrls function in proxy-handler.ts is an incomplete copy of the one in proxy-configs.ts, missing critical URL rewriting patterns needed for proper script proxying.
View Details
π Patch Details
diff --git a/src/runtime/server/proxy-handler.ts b/src/runtime/server/proxy-handler.ts
index c5b30c3..1474f40 100644
--- a/src/runtime/server/proxy-handler.ts
+++ b/src/runtime/server/proxy-handler.ts
@@ -1,11 +1,7 @@
import { defineEventHandler, getHeaders, getRequestIP, readBody, getQuery, setResponseHeader, createError } from 'h3'
import { useRuntimeConfig } from '#imports'
import { useNitroApp } from 'nitropack/runtime'
-
-interface ProxyRewrite {
- from: string
- to: string
-}
+import { rewriteScriptUrls, type ProxyRewrite } from '../../proxy-configs'
interface ProxyConfig {
routes: Record<string, string>
@@ -17,29 +13,6 @@ interface ProxyConfig {
debug?: boolean
}
-/**
- * Rewrite URLs in script content based on proxy config.
- * Inlined from proxy-configs.ts for runtime use.
- */
-function rewriteScriptUrls(content: string, rewrites: ProxyRewrite[]): string {
- let result = content
- for (const { from, to } of rewrites) {
- // Rewrite various URL formats
- result = result
- // Full URLs
- .replaceAll(`"https://${from}`, `"${to}`)
- .replaceAll(`'https://${from}`, `'${to}`)
- .replaceAll(`\`https://${from}`, `\`${to}`)
- .replaceAll(`"http://${from}`, `"${to}`)
- .replaceAll(`'http://${from}`, `'${to}`)
- .replaceAll(`\`http://${from}`, `\`${to}`)
- .replaceAll(`"//${from}`, `"${to}`)
- .replaceAll(`'//${from}`, `'${to}`)
- .replaceAll(`\`//${from}`, `\`${to}`)
- }
- return result
-}
-
/**
* Headers that reveal user IP address - always stripped in strict mode,
* anonymized in anonymize mode.
Analysis
Missing URL rewriting patterns in proxy-handler.ts causes collection requests to bypass the proxy
What fails: The rewriteScriptUrls function in src/runtime/server/proxy-handler.ts (lines 24-40) is an incomplete copy that's missing critical URL rewriting patterns compared to the exported version in src/proxy-configs.ts. This causes JavaScript responses fetched through the proxy to retain unrewritten URLs for:
- Bare domain patterns (e.g.,
"api.segment.io"without protocol) - Segment SDK - Google Analytics dynamic URL construction (e.g.,
"https://"+(...)+".google-analytics.com/g/collect") - Minified GA4 code
How to reproduce: Test with synthetic script content containing these patterns:
// Bare domain - NOT rewritten by old version
var apiHost = "api.segment.io/v1/batch";
// GA dynamic construction - NOT rewritten by old version
var collect = "https://"+("www")+".google-analytics.com/g/collect";Old inline version result: URLs remain unchanged, allowing collection requests to bypass proxy Fixed version result: URLs are properly rewritten to proxy paths
What happens vs expected:
- Before fix: Collection endpoint requests embedded in JavaScript responses bypass the proxy and send data directly to third parties, exposing user IPs and defeating privacy protection
- After fix: All collection requests are routed through the proxy and privacy-filtered based on configured mode
Root cause: src/runtime/server/proxy-handler.ts defines a local rewriteScriptUrls function (lines 24-40) instead of importing the complete exported version from src/proxy-configs.ts. The runtime version was missing the bare domain pattern handling (lines 267-269 in proxy-configs.ts) and Google Analytics dynamic construction regex patterns (lines 275-287 in proxy-configs.ts).
Fix implemented: Removed the incomplete inline function and imported the complete rewriteScriptUrls function from src/proxy-configs.ts.
Verification: All 180 unit tests pass, including the comprehensive third-party-proxy-replacements.test.ts which tests URL rewriting patterns for Google Analytics, Meta Pixel, TikTok, Segment, and other SDKs.
π WalkthroughWalkthroughAdds a full First-Party Mode and proxy system to the Nuxt Scripts module. Key changes: new CLI (src/cli.ts) and package bin entry; module options/types for firstParty and privacy; build/runtime wiring for proxy prefixes and service worker support; server-side proxy handler, SW generator, and SW client registration; proxy-configs utility with rewrite rules and SW intercept rules; template and transformer updates to support serviceWorker triggers and proxy-aware bundling; many registry entries annotated with proxy keys; extensive docs and tests (unit, e2e, fixtures, snapshots) for proxying and privacy stripping; new runtime composables and dev-only status/health endpoints. A deleted .claude plan file is also removed. Estimated code review effortπ― 5 (Critical) | β±οΈ ~120 minutes π₯ Pre-merge checks | β 4 | β 1β Failed checks (1 warning)
β Passed checks (4 passed)
βοΈ Tip: You can configure your own custom pre-merge checks in the settings. β¨ Finishing touches
π§ͺ Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 15
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and canβt be posted inline due to platform limitations.
β οΈ Outside diff range comments (3)
docs/content/scripts/tracking/x-pixel.md (1)
17-18: Copy-paste error: "Meta Pixel" should be "X Pixel".Line 17 incorrectly references "Meta Pixel" instead of "X Pixel".
π Proposed fix
-The simplest way to load Meta Pixel globally in your Nuxt App is to use Nuxt config. Alternatively you can directly +The simplest way to load X Pixel globally in your Nuxt App is to use Nuxt config. Alternatively you can directly use the [useScriptXPixel](`#useScriptXPixel`) composable.src/assets.ts (1)
85-85: No-oppush()call has no effect.This line calls
push()with no arguments, which does nothing. This appears to be a leftover from incomplete code or a copy-paste error.Proposed fix
nuxt.options.nitro.publicAssets ||= [] const cacheDir = join(nuxt.options.buildDir, 'cache', 'scripts') - nuxt.options.nitro.publicAssets.push() nuxt.options.nitro = defu(nuxt.options.nitro, {src/plugins/transform.ts (1)
103-167: Compute SRI after proxy rewrites to prevent integrity failures.
WhenproxyRewritesmutates content, the integrity hash (and cached metadata) reflects the preβrewrite bytes, which can cause browsers to reject the script when integrity is enabled. Compute the hash after rewrites (and consider scoping metadata per cacheKey if you support switching proxy/nonβproxy modes).π Suggested fix (order of operations)
- // Calculate integrity hash if enabled - const integrityHash = integrity && res - ? calculateIntegrity(res, integrity === true ? 'sha384' : integrity) - : undefined - - await storage.setItemRaw(`bundle:${filename}`, res) - // Apply URL rewrites for proxy mode - if (proxyRewrites?.length && res) { - const content = res.toString('utf-8') - const rewritten = rewriteScriptUrls(content, proxyRewrites) - res = Buffer.from(rewritten, 'utf-8') - logger.debug(`Rewrote ${proxyRewrites.length} URL patterns in ${filename}`) - } - - await storage.setItemRaw(cacheKey, res) + await storage.setItemRaw(`bundle:${filename}`, res) + // Apply URL rewrites for proxy mode + if (proxyRewrites?.length && res) { + const content = res.toString('utf-8') + const rewritten = rewriteScriptUrls(content, proxyRewrites) + res = Buffer.from(rewritten, 'utf-8') + logger.debug(`Rewrote ${proxyRewrites.length} URL patterns in ${filename}`) + } + + // Calculate integrity hash after any rewrites so it matches served content + const integrityHash = integrity && res + ? calculateIntegrity(res, integrity === true ? 'sha384' : integrity) + : undefined + + await storage.setItemRaw(cacheKey, res)
π€ Fix all issues with AI agents
In `@src/module.ts`:
- Around line 389-393: Replace the direct console.log calls with the module's
logger (use this.logger.info) to comply with no-console: locate the
console.log('[nuxt-scripts] First-party config:', ...) in src/module.ts (and the
similar console.log at the later occurrence around the 496-499 area) and change
them to this.logger.info with the same message and object payload so the output
goes through Nuxt's logging system.
- Line 30: The import statement includes an unused type symbol ProxyConfig which
triggers a lint error; edit the import that currently lists getAllProxyConfigs,
getSWInterceptRules, ProxyConfig to remove ProxyConfig (or change it to an
explicit type-only import only where the type is actually used). Update any
references to ProxyConfig elsewhere if you intended to use it (either add a real
usage or import it with "import type { ProxyConfig } from './proxy-configs'") so
the module no longer imports an unused symbol.
In `@src/proxy-configs.ts`:
- Around line 198-231: The SWInterceptRule interface is missing the pathPrefix
property used by getSWInterceptRules and other runtime code; update the
SWInterceptRule declaration to include pathPrefix: string so its shape matches
how getSWInterceptRules (and sw-handler logic) builds rules from
buildProxyConfig, and ensure any exports/types referencing SWInterceptRule
reflect the added property.
In `@src/runtime/server/proxy-handler.ts`:
- Around line 395-425: The loop over originalHeaders currently forwards
non-fingerprinting headers (via headers[key] = value) which can leak
credentials; update proxy-handler.ts to drop a sensitive header denylist (e.g.,
'cookie', 'authorization', and any other session headers) unconditionally before
forwarding. In the header-processing block that checks lowerKey, add a check
against SENSITIVE_HEADERS (or inline list) and continue (skip) when matched,
ensuring functions like normalizeUserAgent and normalizeLanguage still run for
allowed headers but cookie/authorization are never copied into headers.
- Around line 324-327: The current debug logger uses console.log which ESLint
forbids; replace the log initializer in proxy-handler.ts that sets log = debug ?
console.log.bind(console) : () => {} to use the approved logger (e.g.,
logger.debug) or console.warn instead. Locate the proxyConfig destructure and
the log constant (symbols: proxyConfig, log) and change the truthy branch to
bind the project logger (e.g., logger.debug.bind(logger) or
logger.warn.bind(logger)); ensure the logger is imported or available in the
module and that fallback remains a no-op when debug is false.
- Around line 451-470: Split combined statements into separate lines in the JSON
and form-parsing blocks to satisfy `@stylistic/max-statements-per-line`: in the
rawBody JSON parsing section, move the JSON.parse assignment into its own line
inside the try block and put the empty catch block on its own line; in the
URL-encoded handling, expand the params.forEach callback so the assignment
obj[key] = value is on its own line inside the callback body; also separate the
creation of stripped and the conversion to a string so the const stripped =
stripPayloadFingerprinting(obj, privacyMode) and the body = new
URLSearchParams(stripped as Record<string, string>).toString() become two
distinct statements on separate lines. Reference symbols: rawBody, parsed,
stripPayloadFingerprinting, params.forEach, obj, stripped, body.
- Around line 485-486: Remove the unnecessary and unsafe TypeScript cast on the
hook call: replace the casted invocation "(nitro.hooks.callHook as
Function)('nuxt-scripts:proxy', {...})" with a direct call to
nitro.hooks.callHook('nuxt-scripts:proxy', {...}); update the invocation site in
proxy-handler.ts (the nitro.hooks.callHook usage) to call the method without "as
Function" so it uses the proper typed signature and satisfies the
no-unsafe-function-type rule.
In `@src/runtime/server/sw-handler.ts`:
- Around line 63-71: The service worker currently uses event.request.body
directly (inside event.respondWith when fetching proxyUrl.href), which will fail
if the body stream was consumed; update the handler to clone the incoming
request (use event.request.clone()) and read/forward the body from the clone
when constructing the fetch to proxyUrl.href so the original request stream
remains intact; adjust the logic around event.respondWith / fetch(proxyUrl.href,
{ method: event.request.method, headers: event.request.headers, body: ... }) to
use the cloned request's body and headers.
In `@src/runtime/sw/proxy-sw.ts`:
- Around line 4-7: The SWInterceptRule interface is missing the pathPrefix
property used by the code that constructs and consumes rules; update the
SWInterceptRule interface to include pathPrefix: string so it matches the
objects created in sw-handler (which builds { pattern, pathPrefix, target }) and
the generated service worker logic that reads rule.pathPrefix for
matching/stripping paths.
In `@test/e2e/__snapshots__/proxy/googleTagManager.json`:
- Around line 1-194: This snapshot file contains invalid trailing commas in JSON
objects (e.g., after "z": "0", inside the "original" and "stripped" objects and
other query objects); remove all trailing commas so each object and array uses
strict JSON syntax (for example edit the entries under "original" and "stripped"
query objects and the top-level array items to eliminate commas before closing
braces/brackets).
In `@test/e2e/first-party.test.ts`:
- Around line 190-196: The test currently uses console.log('[test] Proxy
error:', response) which violates the no-console lint rule; replace that
console.log call with console.warn or console.error so the lint rule is
satisfied (locate the call near writeFileSync(join(fixtureDir,
'proxy-test.json'), JSON.stringify(response, null, 2)) and the response object
check in first-party.test.ts and update the console invocation accordingly).
In `@test/fixtures/first-party/pages/segment.vue`:
- Around line 8-10: The call to useScriptSegment currently embeds a hardcoded
Segment writeKey; update the invocation of useScriptSegment to read the key from
an environment/config variable (e.g. SEGMENT_WRITE_KEY) with a non-secret
placeholder fallback so tests/fixtures do not contain credentials β locate the
useScriptSegment(...) call and replace the literal
'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C' with a lookup of the env/config value and a
clear placeholder default.
In `@test/unit/proxy-privacy.test.ts`:
- Around line 290-373: Move the stripFingerprintingFromPayload function out of
the test file into a shared test util module (e.g., create
test/utils/proxy-privacy.ts), export it from there, and update any tests
importing it to import from the new module; when moving, also import and
re-export or reference its dependencies (NORMALIZE_PARAMS, STRIP_PARAMS,
normalizeLanguage, normalizeUserAgent, anonymizeIP, generalizeScreen) inside the
new util so the function compiles, and remove the function export from the
original test file.
- Around line 176-285: Several tests in the "proxy privacy - payload analysis"
suite use console.log which violates the no-console rule; replace each
console.log(...) call in the GA, Meta, X/Twitter and generic fingerprint tests
(the ones logging 'GA fingerprinting params found', 'GA params to normalize',
'GA safe params', 'Meta fingerprinting params found', 'X/Twitter fingerprinting
params found', and 'All fingerprinting vectors:') with console.warn(...) or
remove the logging lines altogether so ESLint accepts them; update the
occurrences near the gaPayload/fingerprintParams, normalizeParams, safeParams,
metaPayload/fingerprintParams, xPayload/fingerprintParams, and fp/vectors
blocks.
In `@test/unit/third-party-proxy-replacements.test.ts`:
- Around line 1-5: Replace the cross-test import of
stripFingerprintingFromPayload from './proxy-privacy.test' with the shared
helper module where you extracted it; update the import statement to point to
the new shared util (the module that now exports stripFingerprintingFromPayload)
so tests import stripFingerprintingFromPayload from the shared utility instead
of another test file.
π‘ Minor comments (6)
test/e2e/__snapshots__/proxy/metaPixel.json-1-16 (1)
1-16: Remove trailing commas from JSON object literals.The file contains invalid JSON syntax. Line 7 has a trailing comma after
"query": {}, and the same issue appears on lines 13 and 15. Standard JSON parsers reject this format and will throw parse errors. Remove the trailing commas to make the JSON valid.docs/content/docs/1.guides/2.first-party.md-523-552 (1)
523-552: Consent banner example has disconnected consent triggers.The example creates consent triggers inline in
useScriptGoogleAnalyticsanduseScriptMetaPixel(lines 532, 537), butacceptAll()callsacceptGA()andacceptMeta()which are from differentuseScriptTriggerConsent()instances (lines 526-527). This won't trigger the scripts.π Suggested fix
<script setup> const hasConsent = ref(false) -const { accept: acceptGA } = useScriptTriggerConsent() -const { accept: acceptMeta } = useScriptTriggerConsent() +const { status: gaStatus, accept: acceptGA } = useScriptTriggerConsent() +const { status: metaStatus, accept: acceptMeta } = useScriptTriggerConsent() // Configure scripts with consent triggers useScriptGoogleAnalytics({ id: 'G-XXXXXX', - scriptOptions: { trigger: useScriptTriggerConsent().status } + scriptOptions: { trigger: gaStatus } }) useScriptMetaPixel({ id: '123456', - scriptOptions: { trigger: useScriptTriggerConsent().status } + scriptOptions: { trigger: metaStatus } }) function acceptAll() { hasConsent.value = true acceptGA() acceptMeta() // Scripts now load through first-party proxy }src/runtime/server/api/scripts-health.ts-81-82 (1)
81-82: Guard against division by zero when no routes are configured.If
scriptsConfig.routesis empty,checks.lengthwill be 0, causingavgLatencyto beNaN.Proposed fix
const allOk = checks.every(c => c.status === 'ok') - const avgLatency = checks.reduce((sum, c) => sum + (c.latency || 0), 0) / checks.length + const avgLatency = checks.length > 0 + ? checks.reduce((sum, c) => sum + (c.latency || 0), 0) / checks.length + : 0src/runtime/server/api/scripts-health.ts-38-40 (1)
38-40: Incomplete regex escaping β backslashes not escaped.The escaping only handles forward slashes. For robustness, also escape backslashes and other regex metacharacters. While
collectPrefixis unlikely to contain such characters, this ensures correctness.Proposed fix
- const escapedPrefix = scriptsConfig.collectPrefix.replace(/\//g, '\\/') + const escapedPrefix = scriptsConfig.collectPrefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')src/cli.ts-122-134 (1)
122-134: Add timeout to health check fetch to prevent indefinite hangs.The fetch call has no timeout. If the server is unresponsive, the CLI will hang indefinitely. Also, line 123 has a redundant default since
args.portalready defaults to'3000'in the args definition.Proposed fix
async run({ args }) { - const port = args.port || '3000' + const port = args.port const url = `http://localhost:${port}/_scripts/health.json` consola.info(`Checking health at ${url}...`) - const res = await fetch(url) + const res = await fetch(url, { signal: AbortSignal.timeout(10000) }) .then(r => r.json()) .catch((err) => { - consola.error(`Failed to connect: ${err.message}`) + const message = err.name === 'TimeoutError' ? 'Request timed out' : err.message + consola.error(`Failed to connect: ${message}`) consola.info('Make sure the dev server is running with `nuxi dev`') return null })src/module.ts-55-60 (1)
55-60: Doc default for collectPrefix doesnβt match implementation.JSDoc says
/ _scripts/c, but the code defaults to/ _proxy. Align the docs (or default) to avoid confusion.π οΈ Proposed fix
- * `@default` '/_scripts/c' + * `@default` '/_proxy'
π§Ή Nitpick comments (5)
test/fixtures/first-party/server/plugins/capture-proxy.ts (1)
7-13: Consider async file operations and improved typing.For a test fixture this is acceptable, but note:
- Synchronous
writeFileSync/mkdirSynccan block the event loop during concurrent proxy eventsdata: anyloses type information β consider a typed interface- No guard if
data.timestampis undefined (would producecapture-undefined.json)β»οΈ Optional improvement with async operations
-import { writeFileSync, mkdirSync } from 'node:fs' +import { writeFile, mkdir } from 'node:fs/promises' import { join } from 'node:path' // Use NUXT_SCRIPTS_CAPTURE_DIR env var or default to rootDir/.captures const captureDir = process.env.NUXT_SCRIPTS_CAPTURE_DIR || join(process.cwd(), '.captures') +interface ProxyEventData { + timestamp: number + [key: string]: unknown +} + export default defineNitroPlugin((nitro) => { - nitro.hooks.hook('nuxt-scripts:proxy', (data: any) => { + nitro.hooks.hook('nuxt-scripts:proxy', async (data: ProxyEventData) => { // Ensure dir exists before each write (handles race conditions) - mkdirSync(captureDir, { recursive: true }) - const filename = join(captureDir, `capture-${data.timestamp}.json`) - writeFileSync(filename, JSON.stringify(data, null, 2)) + await mkdir(captureDir, { recursive: true }) + const filename = join(captureDir, `capture-${data.timestamp ?? Date.now()}.json`) + await writeFile(filename, JSON.stringify(data, null, 2)) }) })src/runtime/composables/useScriptTriggerServiceWorker.ts (1)
47-51: Race condition: scope disposal may resolve an already-settled promise.If the promise already resolved via
done()(from controllerchange or timeout), thetryOnScopeDisposecallback will still callresolve(false). While this won't throw in JavaScript (calling resolve multiple times is a no-op on an already-settled promise), the cleanup should use the same guard pattern for consistency and clarity.β»οΈ Suggested fix
tryOnScopeDispose(() => { navigator.serviceWorker.removeEventListener('controllerchange', onControllerChange) clearTimeout(timer) - resolve(false) + if (!resolved) { + resolved = true + resolve(false) + } })src/runtime/server/api/scripts-health.ts (1)
19-19: Prefix unused parameter with underscore.The
eventparameter is defined but never used. Prefix it with an underscore to satisfy the linter.Proposed fix
-export default defineEventHandler(async (event) => { +export default defineEventHandler(async (_event) => {test/unit/first-party.test.ts (1)
2-2: Remove unused import.
getProxyConfigis imported but never used in this test file.Proposed fix
-import { getAllProxyConfigs, getProxyConfig } from '../../src/proxy-configs' +import { getAllProxyConfigs } from '../../src/proxy-configs'src/cli.ts (1)
92-100: Consider handling prompt cancellation (Ctrl+C).If the user cancels the prompt with Ctrl+C,
consola.promptmay throw an error or returnundefined. The current checkif (!confirmed)handlesfalseand falsy values, but you may want to wrap this in a try-catch for cleaner handling.
| // Pre-resolve paths needed for hooks | ||
| const swHandlerPath = await resolvePath('./runtime/server/sw-handler') | ||
|
|
||
| console.log('[nuxt-scripts] First-party config:', { firstPartyEnabled, firstPartyPrivacy, firstPartyCollectPrefix }) | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Replace console.log with module logger to satisfy no-console.
π οΈ Proposed fix
- console.log('[nuxt-scripts] First-party config:', { firstPartyEnabled, firstPartyPrivacy, firstPartyCollectPrefix })
+ logger.debug('[nuxt-scripts] First-party config:', { firstPartyEnabled, firstPartyPrivacy, firstPartyCollectPrefix })
...
- console.log('[nuxt-scripts] Registering proxy handler:', `${firstPartyCollectPrefix}/**`, '->', proxyHandlerPath)
+ logger.debug('[nuxt-scripts] Registering proxy handler:', `${firstPartyCollectPrefix}/**`, '->', proxyHandlerPath)Also applies to: 496-499
π§° Tools
πͺ ESLint
[error] 392-392: Unexpected console statement. Only these console methods are allowed: warn, error.
(no-console)
π€ Prompt for AI Agents
In `@src/module.ts` around lines 389 - 393, Replace the direct console.log calls
with the module's logger (use this.logger.info) to comply with no-console:
locate the console.log('[nuxt-scripts] First-party config:', ...) in
src/module.ts (and the similar console.log at the later occurrence around the
496-499 area) and change them to this.logger.info with the same message and
object payload so the output goes through Nuxt's logging system.
| export interface SWInterceptRule { | ||
| /** Domain pattern to match (supports wildcards like *.google-analytics.com) */ | ||
| pattern: string | ||
| /** Path prefix to match and strip from the original URL (e.g., /tr for www.facebook.com/tr) */ | ||
| pathPrefix: string | ||
| /** Local path prefix to rewrite to */ | ||
| target: string | ||
| } | ||
|
|
||
| /** | ||
| * Get service worker intercept rules from all proxy configs. | ||
| * These rules are used by the SW to intercept and rewrite outbound requests. | ||
| */ | ||
| export function getSWInterceptRules(collectPrefix: string): SWInterceptRule[] { | ||
| const configs = buildProxyConfig(collectPrefix) | ||
| const rules: SWInterceptRule[] = [] | ||
|
|
||
| // Extract unique domain -> target mappings from route rules | ||
| for (const config of Object.values(configs)) { | ||
| if (!config.routes) | ||
| continue | ||
| for (const [localPath, { proxy }] of Object.entries(config.routes)) { | ||
| // Extract domain and path prefix from proxy URL | ||
| // e.g., "https://www.facebook.com/tr/**" -> domain="www.facebook.com", pathPrefix="/tr" | ||
| // e.g., "https://connect.facebook.net/**" -> domain="connect.facebook.net", pathPrefix="" | ||
| const match = proxy.match(/^https?:\/\/([^/]+)(\/.*)?\/\*\*$/) | ||
| if (match?.[1]) { | ||
| const domain = match[1] | ||
| // Path prefix is everything between domain and /** (e.g., /tr), empty if none | ||
| const pathPrefix = match[2] || '' | ||
| // Extract target prefix: "/_proxy/meta-tr/**" -> "/_proxy/meta-tr" | ||
| const target = localPath.replace(/\/\*\*$/, '') | ||
| rules.push({ pattern: domain, pathPrefix, target }) | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π§© Analysis chain
π Script executed:
#!/bin/bash
# Search for SWInterceptRule definition and pathPrefix usage
echo "=== Searching for SWInterceptRule definition ==="
rg -n "interface SWInterceptRule|type SWInterceptRule" src/
echo -e "\n=== Searching for pathPrefix usage in runtime ==="
rg -n "pathPrefix" src/runtime/
echo -e "\n=== Checking getSWInterceptRules usage ==="
rg -n "getSWInterceptRules" src/Repository: nuxt/scripts
Length of output: 1163
π Script executed:
#!/bin/bash
# Check SWInterceptRule definition in src/runtime/sw/proxy-sw.ts
echo "=== src/runtime/sw/proxy-sw.ts (around line 4) ==="
sed -n '1,20p' src/runtime/sw/proxy-sw.ts
echo -e "\n=== src/runtime/server/sw-handler.ts (full file to see pathPrefix usage) ==="
cat -n src/runtime/server/sw-handler.tsRepository: nuxt/scripts
Length of output: 4088
SWInterceptRule interface in src/runtime/sw/proxy-sw.ts is missing the pathPrefix field.
The interface definition (line 4β6) only includes pattern and target, but src/runtime/server/sw-handler.ts generates rules with pathPrefix (line 18) and the generated code actively uses it to match and strip path prefixes from URLs (lines 54, 58β59). Update the interface to include pathPrefix: string to align with the actual implementation.
π€ Prompt for AI Agents
In `@src/proxy-configs.ts` around lines 198 - 231, The SWInterceptRule interface
is missing the pathPrefix property used by getSWInterceptRules and other runtime
code; update the SWInterceptRule declaration to include pathPrefix: string so
its shape matches how getSWInterceptRules (and sw-handler logic) builds rules
from buildProxyConfig, and ensure any exports/types referencing SWInterceptRule
reflect the added property.
| const { proxy, status } = useScriptSegment({ | ||
| writeKey: 'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C', | ||
| }) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π§© Analysis chain
π Script executed:
# First, let's examine the file in question
cat -n test/fixtures/first-party/pages/segment.vueRepository: nuxt/scripts
Length of output: 1142
π Script executed:
# Search for this specific writeKey across the entire codebase
rg 'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C' --type-listRepository: nuxt/scripts
Length of output: 445
π Script executed:
# Look for Segment write keys or similar patterns in the codebase
rg 'writeKey' -t js -t vue -t ts -A 2 -B 2Repository: nuxt/scripts
Length of output: 83
π Script executed:
# Check if there's any documentation about test fixtures or keys
find . -name "README*" -o -name "TESTING*" -o -name ".env*" | head -20Repository: nuxt/scripts
Length of output: 1883
π Script executed:
# Look for gitleaks or other security scanning configs
find . -name ".gitleaks*" -o -name "*.gitleaks*" -o -name "secrets*" 2>/dev/nullRepository: nuxt/scripts
Length of output: 38
π Script executed:
# Search for the exact writeKey across entire codebase
rg 'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C'Repository: nuxt/scripts
Length of output: 901
π Script executed:
# Search for writeKey patterns
rg 'writeKey' -A 1 -B 1Repository: nuxt/scripts
Length of output: 2628
π Script executed:
# Check .env.example for fixture documentation
cat -n docs/.env.exampleRepository: nuxt/scripts
Length of output: 276
π Script executed:
# Look for test configuration and fixture setup docs
find . -path ./node_modules -prune -o -type f \( -name "*.md" -o -name "*.txt" \) -print | xargs grep -l "Segment\|fixture" 2>/dev/null | head -10Repository: nuxt/scripts
Length of output: 191
π Script executed:
# Check if this key pattern matches Segment's documentation or public test keys
rg 'test.*key\|fixture.*key\|public.*key' -i --type-list | head -5Repository: nuxt/scripts
Length of output: 445
π Script executed:
# Check how environment variables are used in tests and fixtures
rg 'process.env\|NUXT_' test/fixtures -A 1 -B 1 | head -30Repository: nuxt/scripts
Length of output: 38
π Script executed:
# Look at the git history to see if this key was always used or if there's context
git log --oneline -20 -- test/fixtures/first-party/pages/segment.vue 2>/dev/null | head -5Repository: nuxt/scripts
Length of output: 134
π Script executed:
# Check Segment documentation to see if this is a known test/public key
web_search
Segment 'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C' test writeKeyRepository: nuxt/scripts
Length of output: 152
π Script executed:
# Look at whether this is documented as a test fixture
grep -r 'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C' docs/ | head -5Repository: nuxt/scripts
Length of output: 38
π Web query:
Segment writeKey test fixture dummy public key
π‘ Result:
There isnβt a βpublic dummy Segment writeKeyβ you can safely use as a universal test keyβSegment writeKeys are per-source credentials, so for anything that actually sends events you should create a separate dev/test Source in your own workspace and use its writeKey. (twilio.com)
If you just need a test fixture string (non-working, for unit tests/mocks), Segmentβs own docs/snippets commonly use placeholders like "writekey" / 'SEGMENT_API_KEY'. (segment-docs.netlify.app)
If you want an example-looking key for fixtures, Segmentβs HTTP API doc includes a sample writeKey value (as an example payload): DmBXIN4JnwqBnTqXccTF0wBnLXNQmFtk (treat as documentation sample only; donβt expect it to authenticate). (segment-docs.netlify.app)
Citations:
- 1: https://www.twilio.com/docs/segment/connections/auto-instrumentation/swift-setup?utm_source=openai
- 2: https://segment-docs.netlify.app/docs/connections/sources/catalog/libraries/website/javascript/?utm_source=openai
- 3: https://segment-docs.netlify.app/docs/connections/sources/catalog/libraries/server/http-api/?utm_source=openai
π Script executed:
# Check the Segment documentation in the repo itself
cat -n docs/content/scripts/tracking/segment.md | head -100Repository: nuxt/scripts
Length of output: 2980
π Script executed:
# Look at other fixture files to understand the pattern
ls -la test/fixtures/first-party/Repository: nuxt/scripts
Length of output: 745
π Script executed:
# Check if there's any documentation about test fixtures or credentials
find . -path ./node_modules -prune -o -type f -name "*.md" -print | xargs grep -l "test key\|fixture\|credential" 2>/dev/nullRepository: nuxt/scripts
Length of output: 194
Replace hardcoded Segment writeKey with environment variable or placeholder.
Line 9 contains a hardcoded writeKey. Segment writeKeys are authentication credentials tied to specific sources. Even if this is a test key, hardcoding credentials in fixtures exposes them in version control. Use an environment variable with a placeholder fallback instead.
Example fix
-const { proxy, status } = useScriptSegment({
- writeKey: 'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C',
-})
+const { proxy, status } = useScriptSegment({
+ writeKey: process.env.NUXT_PUBLIC_SCRIPTS_SEGMENT_WRITE_KEY ?? 'YOUR_WRITE_KEY',
+})π Committable suggestion
βΌοΈ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const { proxy, status } = useScriptSegment({ | |
| writeKey: 'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C', | |
| }) | |
| const { proxy, status } = useScriptSegment({ | |
| writeKey: process.env.NUXT_PUBLIC_SCRIPTS_SEGMENT_WRITE_KEY ?? 'YOUR_WRITE_KEY', | |
| }) |
π§° Tools
πͺ Gitleaks (8.30.0)
[high] 9-9: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
π€ Prompt for AI Agents
In `@test/fixtures/first-party/pages/segment.vue` around lines 8 - 10, The call to
useScriptSegment currently embeds a hardcoded Segment writeKey; update the
invocation of useScriptSegment to read the key from an environment/config
variable (e.g. SEGMENT_WRITE_KEY) with a non-secret placeholder fallback so
tests/fixtures do not contain credentials β locate the useScriptSegment(...)
call and replace the literal 'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C' with a lookup of
the env/config value and a clear placeholder default.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
π€ Fix all issues with AI agents
In `@src/runtime/server/api/scripts-health.ts`:
- Line 23: The exported default handler defineEventHandler currently declares an
unused parameter named event; rename it to _event (or prefix with an underscore)
in the defineEventHandler signature to silence ESLint unused-variable warnings
while preserving the async handler behavior and function identity (i.e., change
"async (event) =>" to "async (_event) =>" in the default export).
In `@test/e2e/first-party.test.ts`:
- Around line 526-536: Remove the duplicated comment block about Clarity and
Hotjar in first-party.test.ts by keeping a single copy and deleting the
redundant copy; locate the two identical comment paragraphs (the repeated notes
beginning "Note: Clarity and Hotjar are session recording tools...") and remove
one so only one explanatory comment remains, preserving surrounding whitespace
and formatting.
In `@test/unit/proxy-privacy.test.ts`:
- Around line 359-360: Add a single trailing newline character at the end of
proxy-privacy.test.ts so the file ends with a newline (i.e., after the final
closing "})" add one blank line/line break), then save/commit so ESLint no
longer reports "Missing newline at end of file".
β»οΈ Duplicate comments (4)
src/runtime/server/proxy-handler.ts (4)
445-446: Removeas Functioncast fromcallHookinvocation.The cast violates
@typescript-eslint/no-unsafe-function-type. Nitro'scallHookis properly typed - other usages in the codebase don't require this cast. If there's a type error, consider augmenting the hook types instead.π§ Proposed fix
- await (nitro.hooks.callHook as Function)('nuxt-scripts:proxy', { + await nitro.hooks.callHook('nuxt-scripts:proxy', {
412-430: Split multi-statement lines to satisfy@stylistic/max-statements-per-line.Lines 414 and 428 each have 2 statements, violating the style rule.
π§ Proposed fix
if (rawBody.startsWith('{') || rawBody.startsWith('[')) { let parsed: unknown = null - try { parsed = JSON.parse(rawBody) } - catch { /* not valid JSON */ } + try { + parsed = JSON.parse(rawBody) + } + catch { + /* not valid JSON */ + } if (parsed && typeof parsed === 'object') { body = stripPayloadFingerprinting(parsed as Record<string, unknown>, privacyMode) @@ -424,7 +428,9 @@ export default defineEventHandler(async (event) => { else if (contentType.includes('application/x-www-form-urlencoded')) { // URL-encoded form data const params = new URLSearchParams(rawBody) const obj: Record<string, unknown> = {} - params.forEach((value, key) => { obj[key] = value }) + params.forEach((value, key) => { + obj[key] = value + }) const stripped = stripPayloadFingerprinting(obj, privacyMode)
6-9: Remove unusedProxyRewriteinterface.This interface is defined but never used. The
rewriteScriptUrlsfunction is imported fromproxy-configs.tswhich has its own type definitions.π§ Proposed fix
-interface ProxyRewrite { - from: string - to: string -} -
280-282: Replaceconsole.debugwith allowed console method.ESLint only allows
console.warnandconsole.error. Useconsole.warnfor debug output or inject a logger.π§ Proposed fix
- const log = debug ? console.debug.bind(console) : () => {} + const log = debug ? console.warn.bind(console) : () => {}
π§Ή Nitpick comments (3)
src/runtime/server/api/scripts-health.ts (1)
57-80: Consider adding error handling for malformed targets.If
target.replace('/**', '/')produces an invalid URL, the fetch will throw. While the catch block handles this, consider validating the URL construction or providing more specific error messages.β»οΈ Optional improvement
// Convert wildcard target to a testable URL const testUrl = target.replace('/**', '/') const start = Date.now() + + // Validate URL before fetching + try { + new URL(testUrl) + } + catch { + checks.push({ + script: scriptName, + route, + target: testUrl, + status: 'error', + error: 'Invalid target URL', + }) + continue + } const result = await fetch(testUrl, {test/unit/third-party-proxy-replacements.test.ts (2)
81-136: Avoid live network fetches in unit tests.Real vendor downloads can be flaky and the catch+return makes failures silently pass; prefer deterministic fixtures/mocks or gate this check behind an explicit optβin so regressions donβt slip unnoticed.
557-611: Consider gating the verbose comparison output.
console.warnon every run can be noisy in CI; optionally guard behind a debug/env flag.
| * | ||
| * Tests a sample request to each proxy route to verify connectivity. | ||
| */ | ||
| export default defineEventHandler(async (event) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Prefix unused event parameter.
ESLint flags unused variables. Prefix with underscore to indicate intentional non-use.
π§ Proposed fix
-export default defineEventHandler(async (event) => {
+export default defineEventHandler(async (_event) => {π Committable suggestion
βΌοΈ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export default defineEventHandler(async (event) => { | |
| export default defineEventHandler(async (_event) => { |
π§° Tools
πͺ ESLint
[error] 23-23: 'event' is defined but never used. Allowed unused args must match /^_/u.
(@typescript-eslint/no-unused-vars)
π€ Prompt for AI Agents
In `@src/runtime/server/api/scripts-health.ts` at line 23, The exported default
handler defineEventHandler currently declares an unused parameter named event;
rename it to _event (or prefix with an underscore) in the defineEventHandler
signature to silence ESLint unused-variable warnings while preserving the async
handler behavior and function identity (i.e., change "async (event) =>" to
"async (_event) =>" in the default export).
| // Note: Clarity and Hotjar are session recording tools that primarily use: | ||
| // - Clarity: d.clarity.ms (data collection) - may buffer data before sending | ||
| // - Hotjar: WebSocket connections (wss://ws*.hotjar.com) which can't be proxied via HTTP | ||
| // These tests verify the script loads and proxy config is correct. | ||
| // Data collection may not occur in short headless sessions. | ||
|
|
||
| // Note: Clarity and Hotjar are session recording tools that primarily use: | ||
| // - Clarity: d.clarity.ms (data collection) - may buffer data before sending | ||
| // - Hotjar: WebSocket connections (wss://ws*.hotjar.com) which can't be proxied via HTTP | ||
| // These tests verify page loads and proxy config is correct. | ||
| // Data collection may not occur in short headless sessions. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Remove duplicate comment block.
Lines 526-530 and 532-536 contain the same comment about Clarity and Hotjar limitations. This appears to be a copy-paste artifact.
π§ Proposed fix
// Note: Clarity and Hotjar are session recording tools that primarily use:
// - Clarity: d.clarity.ms (data collection) - may buffer data before sending
// - Hotjar: WebSocket connections (wss://ws*.hotjar.com) which can't be proxied via HTTP
// These tests verify the script loads and proxy config is correct.
// Data collection may not occur in short headless sessions.
-
- // Note: Clarity and Hotjar are session recording tools that primarily use:
- // - Clarity: d.clarity.ms (data collection) - may buffer data before sending
- // - Hotjar: WebSocket connections (wss://ws*.hotjar.com) which can't be proxied via HTTP
- // These tests verify page loads and proxy config is correct.
- // Data collection may not occur in short headless sessions.
it('clarity', async () => {π€ Prompt for AI Agents
In `@test/e2e/first-party.test.ts` around lines 526 - 536, Remove the duplicated
comment block about Clarity and Hotjar in first-party.test.ts by keeping a
single copy and deleting the redundant copy; locate the two identical comment
paragraphs (the repeated notes beginning "Note: Clarity and Hotjar are session
recording tools...") and remove one so only one explanatory comment remains,
preserving surrounding whitespace and formatting.
| }) | ||
| }) No newline at end of file |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Missing newline at end of file.
ESLint requires a newline at the end of the file.
π§ Proposed fix
})
+π Committable suggestion
βΌοΈ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| }) | |
| }) | |
| }) | |
| }) | |
π§° Tools
πͺ ESLint
[error] 360-360: Newline required at end of file but not found.
(@stylistic/eol-last)
π€ Prompt for AI Agents
In `@test/unit/proxy-privacy.test.ts` around lines 359 - 360, Add a single
trailing newline character at the end of proxy-privacy.test.ts so the file ends
with a newline (i.e., after the final closing "})" add one blank line/line
break), then save/commit so ESLint no longer reports "Missing newline at end of
file".
π Linked issue
Resolves #87
β Type of change
π Description
Third-party scripts expose user data directly to external servers - every request shares the user's IP address, and scripts can set third-party cookies for cross-site tracking. Ad blockers rightfully block these for privacy reasons.
This PR adds a
firstPartyoption that routes all script traffic through your own domain:Scripts are downloaded at build time, collection URLs rewritten to local paths (
/_scripts/c/ga), and Nitro route rules proxy requests to original endpoints.Supported: Google Analytics, GTM, Meta Pixel, TikTok, Segment, Clarity, Hotjar, X/Twitter, Snapchat, Reddit.
Includes new
/docs/guides/first-partydocumentation and deprecation notice on bundling guide.