From 05b3ce6aa7e837ca5f0613929fe39da3d7524bd9 Mon Sep 17 00:00:00 2001 From: patak Date: Wed, 24 Aug 2022 19:50:49 +0200 Subject: [PATCH] refactor: migrate from vue/compiler-dom to parse5 (#9678) --- .prettierignore | 1 + packages/vite/LICENSE.md | 133 +++------ packages/vite/package.json | 2 +- packages/vite/rollup.config.ts | 9 - packages/vite/src/node/plugins/html.ts | 279 ++++++++++-------- .../src/node/server/middlewares/indexHtml.ts | 95 +++--- playground/html/valid.html | 7 + playground/html/vite.config.js | 3 +- pnpm-lock.yaml | 15 +- 9 files changed, 288 insertions(+), 256 deletions(-) create mode 100644 playground/html/valid.html diff --git a/.prettierignore b/.prettierignore index 0d5487354a8c98..b1ea458b9bb9d8 100644 --- a/.prettierignore +++ b/.prettierignore @@ -7,4 +7,5 @@ pnpm-lock.yaml pnpm-workspace.yaml playground/tsconfig-json-load-error/has-error/tsconfig.json playground/html/invalid.html +playground/html/valid.html playground/worker/classic-worker.js diff --git a/packages/vite/LICENSE.md b/packages/vite/LICENSE.md index 94f3a5cd7aa509..41f21cba4cd801 100644 --- a/packages/vite/LICENSE.md +++ b/packages/vite/LICENSE.md @@ -559,93 +559,6 @@ Repository: rollup/plugins --------------------------------------- -## @vue/compiler-core -License: MIT -By: Evan You -Repository: git+https://github.com/vuejs/core.git - -> The MIT License (MIT) -> -> Copyright (c) 2018-present, Yuxi (Evan) You -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -> THE SOFTWARE. - ---------------------------------------- - -## @vue/compiler-dom -License: MIT -By: Evan You -Repository: git+https://github.com/vuejs/core.git - -> The MIT License (MIT) -> -> Copyright (c) 2018-present, Yuxi (Evan) You -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -> THE SOFTWARE. - ---------------------------------------- - -## @vue/shared -License: MIT -By: Evan You -Repository: git+https://github.com/vuejs/core.git - -> The MIT License (MIT) -> -> Copyright (c) 2018-present, Yuxi (Evan) You -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -> THE SOFTWARE. - ---------------------------------------- - ## acorn License: MIT By: Marijn Haverbeke, Ingvar Stepanyan, Adrian Heine @@ -1278,6 +1191,25 @@ Repository: pillarjs/encodeurl --------------------------------------- +## entities +License: BSD-2-Clause +By: Felix Boehm +Repository: git://github.com/fb55/entities.git + +> Copyright (c) Felix Böhm +> All rights reserved. +> +> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: +> +> Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +> +> Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +> +> THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS, +> EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--------------------------------------- + ## es-module-lexer License: MIT By: Guy Bedford @@ -2405,6 +2337,33 @@ Repository: sindresorhus/open --------------------------------------- +## parse5 +License: MIT +By: Ivan Nikulin, https://github.com/inikulin/parse5/graphs/contributors +Repository: git://github.com/inikulin/parse5.git + +> Copyright (c) 2013-2019 Ivan Nikulin (ifaaan@gmail.com, https://github.com/inikulin) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + ## parseurl License: MIT By: Douglas Christopher Wilson, Jonathan Ong diff --git a/packages/vite/package.json b/packages/vite/package.json index 8372deeb483512..5df57065f5c506 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -78,7 +78,6 @@ "@rollup/plugin-node-resolve": "13.3.0", "@rollup/plugin-typescript": "^8.3.4", "@rollup/pluginutils": "^4.2.1", - "@vue/compiler-dom": "^3.2.37", "acorn": "^8.8.0", "cac": "^6.7.12", "chokidar": "^3.5.3", @@ -103,6 +102,7 @@ "mrmime": "^1.0.1", "okie": "^1.0.1", "open": "^8.4.0", + "parse5": "^7.0.0", "periscopic": "^3.0.4", "picocolors": "^1.0.0", "postcss-import": "^14.1.0", diff --git a/packages/vite/rollup.config.ts b/packages/vite/rollup.config.ts index a271d4f3562906..bf5c0e9da810a2 100644 --- a/packages/vite/rollup.config.ts +++ b/packages/vite/rollup.config.ts @@ -5,7 +5,6 @@ import nodeResolve from '@rollup/plugin-node-resolve' import typescript from '@rollup/plugin-typescript' import commonjs from '@rollup/plugin-commonjs' import json from '@rollup/plugin-json' -import alias from '@rollup/plugin-alias' import license from 'rollup-plugin-license' import MagicString from 'magic-string' import colors from 'picocolors' @@ -79,14 +78,6 @@ function createNodePlugins( declarationDir: string | false ): Plugin[] { return [ - alias({ - // packages with "module" field that doesn't play well with cjs bundles - entries: { - '@vue/compiler-dom': require.resolve( - '@vue/compiler-dom/dist/compiler-dom.cjs.js' - ) - } - }), nodeResolve({ preferBuiltins: true }), typescript({ tsconfig: path.resolve(__dirname, 'src/node/tsconfig.json'), diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index 4c46d988890462..c0963f5f5f459f 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -8,14 +8,7 @@ import type { } from 'rollup' import MagicString from 'magic-string' import colors from 'picocolors' -import type { - AttributeNode, - CompilerError, - ElementNode, - NodeTransform, - TextNode -} from '@vue/compiler-dom' -import { NodeTypes } from '@vue/compiler-dom' +import type { DefaultTreeAdapterMap, ParserError, Token } from 'parse5' import { stripLiteral } from 'strip-literal' import type { Plugin } from '../plugin' import type { ViteDevServer } from '../server' @@ -143,83 +136,141 @@ export const isAsyncScriptMap = new WeakMap< Map >() +export function nodeIsElement( + node: DefaultTreeAdapterMap['node'] +): node is DefaultTreeAdapterMap['element'] { + return node.nodeName[0] !== '#' +} + +function traverseNodes( + node: DefaultTreeAdapterMap['node'], + visitor: (node: DefaultTreeAdapterMap['node']) => void +) { + visitor(node) + if ( + nodeIsElement(node) || + node.nodeName === '#document' || + node.nodeName === '#document-fragment' + ) { + node.childNodes.forEach((childNode) => traverseNodes(childNode, visitor)) + } +} + export async function traverseHtml( html: string, filePath: string, - visitor: NodeTransform + visitor: (node: DefaultTreeAdapterMap['node']) => void ): Promise { // lazy load compiler - const { parse, transform } = await import('@vue/compiler-dom') - // @vue/compiler-core doesn't like lowercase doctypes - html = html.replace(/ { + handleParseError(e, html, filePath) + } + }) + traverseNodes(ast, visitor) } -export function getScriptInfo(node: ElementNode): { - src: AttributeNode | undefined +export function getScriptInfo(node: DefaultTreeAdapterMap['element']): { + src: Token.Attribute | undefined + sourceCodeLocation: Token.Location | undefined isModule: boolean isAsync: boolean } { - let src: AttributeNode | undefined + let src: Token.Attribute | undefined + let sourceCodeLocation: Token.Location | undefined let isModule = false let isAsync = false - for (let i = 0; i < node.props.length; i++) { - const p = node.props[i] - if (p.type === NodeTypes.ATTRIBUTE) { - if (p.name === 'src') { + for (const p of node.attrs) { + if (p.name === 'src') { + if (!src) { src = p - } else if (p.name === 'type' && p.value && p.value.content === 'module') { - isModule = true - } else if (p.name === 'async') { - isAsync = true + sourceCodeLocation = node.sourceCodeLocation?.attrs!['src'] } + } else if (p.name === 'type' && p.value && p.value === 'module') { + isModule = true + } else if (p.name === 'async') { + isAsync = true } } - return { src, isModule, isAsync } + return { src, sourceCodeLocation, isModule, isAsync } +} + +const attrValueStartRE = /=[\s\t\n\r]*(["']|.)/ + +export function overwriteAttrValue( + s: MagicString, + sourceCodeLocation: Token.Location, + newValue: string +): MagicString { + const srcString = s.slice( + sourceCodeLocation.startOffset, + sourceCodeLocation.endOffset + ) + const valueStart = srcString.match(attrValueStartRE) + if (!valueStart) { + // overwrite attr value can only be called for a well-defined value + throw new Error( + `[vite:html] internal error, failed to overwrite attribute value` + ) + } + const wrapOffset = valueStart[1] ? 1 : 0 + const valueOffset = valueStart.index! + valueStart[0].length - 1 + s.overwrite( + sourceCodeLocation.startOffset + valueOffset + wrapOffset, + sourceCodeLocation.endOffset - wrapOffset, + newValue, + { contentOnly: true } + ) + return s } /** - * Format Vue @type {CompilerError} to @type {RollupError} + * Format parse5 @type {ParserError} to @type {RollupError} */ function formatParseError( - compilerError: CompilerError, + parserError: ParserError, id: string, html: string ): RollupError { - const formattedError: RollupError = { ...(compilerError as any) } - if (compilerError.loc) { - formattedError.frame = generateCodeFrame( - html, - compilerError.loc.start.offset - ) - formattedError.loc = { - file: id, - line: compilerError.loc.start.line, - column: compilerError.loc.start.column - } + const formattedError: RollupError = { + code: parserError.code, + message: `parse5 error code ${parserError.code}` + } + formattedError.frame = generateCodeFrame(html, parserError.startOffset) + formattedError.loc = { + file: id, + line: parserError.startLine, + column: parserError.startCol } return formattedError } function handleParseError( - compilerError: CompilerError, + parserError: ParserError, html: string, filePath: string ) { + switch (parserError.code) { + case 'missing-doctype': + // ignore missing DOCTYPE + return + case 'abandoned-head-element-child': + // Accept elements without closing tag in + return + case 'duplicate-attribute': + // Accept duplicate attributes #9566 + // The first attribute is used, browsers silently ignore duplicates + return + } const parseError = { loc: filePath, frame: '', - ...formatParseError(compilerError, filePath, html) + ...formatParseError(parserError, filePath, html) } throw new Error( - `Unable to parse HTML; ${compilerError.message}\n at ${JSON.stringify( + `Unable to parse HTML; ${parseError.message}\n at ${JSON.stringify( parseError.loc )}\n${parseError.frame}` ) @@ -270,7 +321,10 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { let js = '' const s = new MagicString(html) - const assetUrls: AttributeNode[] = [] + const assetUrls: { + attr: Token.Attribute + sourceCodeLocation: Token.Location + }[] = [] const scriptUrls: ScriptAssetsUrl[] = [] const styleUrls: ScriptAssetsUrl[] = [] let inlineModuleIndex = -1 @@ -280,25 +334,25 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { let someScriptsAreDefer = false await traverseHtml(html, id, (node) => { - if (node.type !== NodeTypes.ELEMENT) { + if (!nodeIsElement(node)) { return } let shouldRemove = false // script tags - if (node.tag === 'script') { - const { src, isModule, isAsync } = getScriptInfo(node) + if (node.nodeName === 'script') { + const { src, sourceCodeLocation, isModule, isAsync } = + getScriptInfo(node) - const url = src && src.value && src.value.content + const url = src && src.value const isPublicFile = !!(url && checkPublicFile(url, config)) if (isPublicFile) { // referencing public dir url, prefix with base - s.overwrite( - src!.value!.loc.start.offset, - src!.value!.loc.end.offset, - `"${toOutputPublicFilePath(url)}"`, - { contentOnly: true } + overwriteAttrValue( + s, + sourceCodeLocation!, + toOutputPublicFilePath(url) ) } @@ -309,10 +363,10 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { // add it as an import js += `\nimport ${JSON.stringify(url)}` shouldRemove = true - } else if (node.children.length) { - const contents = node.children - .map((child: any) => child.content || '') - .join('') + } else if (node.childNodes.length) { + const scriptNode = + node.childNodes.pop() as DefaultTreeAdapterMap['textNode'] + const contents = scriptNode.value // const filePath = id.replace(normalizePath(config.root), '') addToHTMLProxyCache(config, filePath, inlineModuleIndex, { @@ -331,9 +385,10 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { ``, { contentOnly: true } ) } await traverseHtml(html, htmlPath, (node) => { - if (node.type !== NodeTypes.ELEMENT) { + if (!nodeIsElement(node)) { return } // script tags - if (node.tag === 'script') { - const { src, isModule } = getScriptInfo(node) + if (node.nodeName === 'script') { + const { src, sourceCodeLocation, isModule } = getScriptInfo(node) if (src) { - processNodeUrl(src, s, config, htmlPath, originalUrl, moduleGraph) - } else if (isModule && node.children.length) { + processNodeUrl( + src, + sourceCodeLocation!, + s, + config, + htmlPath, + originalUrl, + moduleGraph + ) + } else if (isModule && node.childNodes.length) { addInlineModule(node, 'js') } } - if (node.tag === 'style' && node.children.length) { - const children = node.children[0] as TextNode + if (node.nodeName === 'style' && node.childNodes.length) { + const children = node.childNodes[0] as DefaultTreeAdapterMap['textNode'] styleUrl.push({ - start: children.loc.start.offset, - end: children.loc.end.offset, - code: children.content + start: children.sourceCodeLocation!.startOffset, + end: children.sourceCodeLocation!.endOffset, + code: children.value }) } // elements with [href/src] attrs - const assetAttrs = assetAttrsConfig[node.tag] + const assetAttrs = assetAttrsConfig[node.nodeName] if (assetAttrs) { - for (const p of node.props) { - if ( - p.type === NodeTypes.ATTRIBUTE && - p.value && - assetAttrs.includes(p.name) - ) { - processNodeUrl(p, s, config, htmlPath, originalUrl) + for (const p of node.attrs) { + if (p.value && assetAttrs.includes(p.name)) { + processNodeUrl( + p, + node.sourceCodeLocation!.attrs![p.name], + s, + config, + htmlPath, + originalUrl + ) } } } diff --git a/playground/html/valid.html b/playground/html/valid.html new file mode 100644 index 00000000000000..9ff48bbeafba6b --- /dev/null +++ b/playground/html/valid.html @@ -0,0 +1,7 @@ + +
Accept duplicated attribute
+ + + + diff --git a/playground/html/vite.config.js b/playground/html/vite.config.js index c294e45ad424f5..571c15811d2311 100644 --- a/playground/html/vite.config.js +++ b/playground/html/vite.config.js @@ -26,7 +26,8 @@ module.exports = { __dirname, 'unicode-path/中文-にほんご-한글-🌕🌖🌗/index.html' ), - linkProps: resolve(__dirname, 'link-props/index.html') + linkProps: resolve(__dirname, 'link-props/index.html'), + valid: resolve(__dirname, 'valid.html') } } }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7ad729f221ec36..d00347c90e12fd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -214,7 +214,6 @@ importers: '@rollup/plugin-node-resolve': 13.3.0 '@rollup/plugin-typescript': ^8.3.4 '@rollup/pluginutils': ^4.2.1 - '@vue/compiler-dom': ^3.2.37 acorn: ^8.8.0 cac: ^6.7.12 chokidar: ^3.5.3 @@ -241,6 +240,7 @@ importers: mrmime: ^1.0.1 okie: ^1.0.1 open: ^8.4.0 + parse5: ^7.0.0 periscopic: ^3.0.4 picocolors: ^1.0.0 postcss: ^8.4.16 @@ -280,7 +280,6 @@ importers: '@rollup/plugin-node-resolve': 13.3.0_rollup@2.78.0 '@rollup/plugin-typescript': 8.3.4_rollup@2.78.0+tslib@2.4.0 '@rollup/pluginutils': 4.2.1 - '@vue/compiler-dom': 3.2.37 acorn: 8.8.0 cac: 6.7.12 chokidar: 3.5.3 @@ -305,6 +304,7 @@ importers: mrmime: 1.0.1 okie: 1.0.1 open: 8.4.0 + parse5: 7.0.0 periscopic: 3.0.4 picocolors: 1.0.0 postcss-import: 14.1.0_postcss@8.4.16 @@ -4238,6 +4238,11 @@ packages: engines: {node: '>= 0.8'} dev: true + /entities/4.3.1: + resolution: {integrity: sha512-o4q/dYJlmyjP2zfnaWDUC6A3BQFmVTX+tZPezK7k0GLSU9QYCauscf5Y+qcEPzKL+EixVouYDgLQK5H9GrLpkg==} + engines: {node: '>=0.12'} + dev: true + /env-paths/2.2.1: resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==} engines: {node: '>=6'} @@ -7078,6 +7083,12 @@ packages: engines: {node: '>= 0.10'} dev: true + /parse5/7.0.0: + resolution: {integrity: sha512-y/t8IXSPWTuRZqXc0ajH/UwDj4mnqLEbSttNbThcFhGrZuOyoyvNBO85PBp2jQa55wY9d07PBNjsK8ZP3K5U6g==} + dependencies: + entities: 4.3.1 + dev: true + /parseurl/1.3.3: resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} engines: {node: '>= 0.8'}