Skip to content
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

fix: avoid source map plugin from replacing valid code #30890

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions npm/vite-dev-server/src/plugins/sourcemap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ export const CypressSourcemap = (
const sourcemap = this.getCombinedSourcemap()
const sourcemapUrl = sourcemap.toUrl()

if (/\/\/# sourceMappingURL=/i.test(code)) {
if (/\/\/# sourceMappingURL=(?!['"])/i.test(code)) {
// If the code already has a sourceMappingURL, it is not an inlined sourcemap
// and we should replace it with the new sourcemap
code = code.replace(/\/\/# sourceMappingURL=(.*)$/m, `//# sourceMappingURL=${sourcemapUrl}`)
code = code.replace(/\/\/# sourceMappingURL=(?!['"])(.*)$/m, `//# sourceMappingURL=${sourcemapUrl}`)
} else {
// If the code does not have a sourceMappingURL, we should append the new sourcemap
code += `\n//# sourceMappingURL=${sourcemapUrl}`
Expand Down
25 changes: 25 additions & 0 deletions npm/vite-dev-server/test/plugins/sourcemap.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,4 +104,29 @@ describe('sourcemap plugin', () => {
throw new Error('transform is not a function')
}
})

it('should not touch sourceMappingURL if it is part of the code', () => {
const code = 'console.log("\n//# sourceMappingURL=")'
const id = `test.js`
const options = {} as ViteDevServerConfig
const vite = {} as Vite
const plugin = CypressSourcemap(options, vite) as Plugin & { getCombinedSourcemap: () => { toUrl: () => string } }

plugin.getCombinedSourcemap = () => {
return {
toUrl: () => 'data:application/json;base64,eyJ2ZXJzaW9uIjozfQ==',
}
}

expect(plugin.name).to.equal('cypress:sourcemap')
expect(plugin.enforce).to.equal('post')

if (plugin.transform instanceof Function) {
const result = plugin.transform.call(plugin, code, id)

expect(result.code).to.eq('console.log("\n//# sourceMappingURL=")\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozfQ==')
} else {
throw new Error('transform is not a function')
}
})
})
Loading