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

refactor: use node hash #7975

Merged
merged 4 commits into from
May 11, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
18 changes: 13 additions & 5 deletions packages/plugin-vue-jsx/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const babel = require('@babel/core')
const jsx = require('@vue/babel-plugin-jsx')
const importMeta = require('@babel/plugin-syntax-import-meta')
const { createFilter, normalizePath } = require('@rollup/pluginutils')
const hash = require('hash-sum')
const { createHash } = require('crypto')
const path = require('path')

const ssrRegisterHelperId = '/__vue-jsx-ssr-register-helper'
Expand Down Expand Up @@ -158,7 +158,7 @@ function vueJsxPlugin(options = {}) {
({ name }) => ({
local: name,
exported: name,
id: hash(id + name)
id: getHash(id + name)
})
)
)
Expand All @@ -175,7 +175,7 @@ function vueJsxPlugin(options = {}) {
hotComponents.push({
local: spec.local.name,
exported: spec.exported.name,
id: hash(id + spec.exported.name)
id: getHash(id + spec.exported.name)
})
}
}
Expand All @@ -193,15 +193,15 @@ function vueJsxPlugin(options = {}) {
hotComponents.push({
local: node.declaration.name,
exported: 'default',
id: hash(id + 'default')
id: getHash(id + 'default')
})
}
} else if (isDefineComponentCall(node.declaration)) {
hasDefault = true
hotComponents.push({
local: '__default__',
exported: 'default',
id: hash(id + 'default')
id: getHash(id + 'default')
})
}
}
Expand Down Expand Up @@ -282,5 +282,13 @@ function isDefineComponentCall(node) {
)
}

/**
* @param {string} text
* @returns {string}
*/
function getHash(text) {
return createHash('sha256').update(text).digest('hex').substring(0, 8)
}

module.exports = vueJsxPlugin
vueJsxPlugin.default = vueJsxPlugin
3 changes: 1 addition & 2 deletions packages/plugin-vue-jsx/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
"@babel/plugin-syntax-import-meta": "^7.10.4",
"@babel/plugin-transform-typescript": "^7.16.8",
"@rollup/pluginutils": "^4.2.1",
"@vue/babel-plugin-jsx": "^1.1.1",
"hash-sum": "^2.0.0"
"@vue/babel-plugin-jsx": "^1.1.1"
}
}
2 changes: 0 additions & 2 deletions packages/plugin-vue/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,7 @@
},
"devDependencies": {
"@rollup/pluginutils": "^4.2.1",
"@types/hash-sum": "^1.0.0",
"debug": "^4.3.4",
"hash-sum": "^2.0.0",
"rollup": "^2.59.0",
"slash": "^4.0.0",
"source-map": "^0.6.1",
Expand Down
8 changes: 6 additions & 2 deletions packages/plugin-vue/src/utils/descriptorCache.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import fs from 'fs'
import path from 'path'
import slash from 'slash'
import hash from 'hash-sum'
import { createHash } from 'crypto'
import type { CompilerError, SFCDescriptor } from 'vue/compiler-sfc'
import type { ResolvedOptions, VueQuery } from '..'

Expand All @@ -27,7 +27,7 @@ export function createDescriptor(
// ensure the path is normalized in a way that is consistent inside
// project (relative to root) and on different systems.
const normalizedPath = slash(path.normalize(path.relative(root, filename)))
descriptor.id = hash(normalizedPath + (isProduction ? source : ''))
descriptor.id = getHash(normalizedPath + (isProduction ? source : ''))

cache.set(filename, descriptor)
return { descriptor, errors }
Expand Down Expand Up @@ -77,3 +77,7 @@ export function setSrcDescriptor(filename: string, entry: SFCDescriptor): void {
// should use other key
cache.set(`${filename}?src=${entry.id}`, entry)
}

function getHash(text: string): string {
return createHash('sha256').update(text).digest('hex').substring(0, 8)
}
10 changes: 1 addition & 9 deletions packages/vite/src/node/__tests__/asset.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,4 @@
import { assetFileNamesToFileName, getAssetHash } from '../plugins/asset'

describe('getAssetHash', () => {
test('8-digit hex', () => {
const hash = getAssetHash(Buffer.alloc(0))

expect(hash).toMatch(/^[\da-f]{8}$/)
})
})
import { assetFileNamesToFileName } from '../plugins/asset'

describe('assetFileNamesToFileName', () => {
// on Windows, both forward slashes and backslashes may appear in the input
Expand Down
8 changes: 8 additions & 0 deletions packages/vite/src/node/__tests__/utils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
getHash,
getPotentialTsSrcPaths,
injectQuery,
isWindows,
Expand Down Expand Up @@ -97,3 +98,10 @@ test('ts import of file with .js and query param', () => {
'test-file.js.tsx?lee=123'
])
})

describe('getHash', () => {
test('8-digit hex', () => {
const hash = getHash(Buffer.alloc(0))
expect(hash).toMatch(/^[\da-f]{8}$/)
})
})
6 changes: 1 addition & 5 deletions packages/vite/src/node/optimizer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import fs from 'fs'
import path from 'path'
import _debug from 'debug'
import colors from 'picocolors'
import { createHash } from 'crypto'
import type { BuildOptions as EsbuildBuildOptions } from 'esbuild'
import { build } from 'esbuild'
import type { ResolvedConfig } from '../config'
import {
createDebugger,
emptyDir,
getHash,
lookupFile,
normalizePath,
writeFile,
Expand Down Expand Up @@ -826,10 +826,6 @@ function getOptimizedBrowserHash(
return getHash(hash + JSON.stringify(deps) + timestamp)
}

export function getHash(text: string): string {
return createHash('sha256').update(text).digest('hex').substring(0, 8)
}

export function optimizedDepInfoFromId(
metadata: DepOptimizationMetadata,
id: string
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/optimizer/registerMissing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import _debug from 'debug'
import {
runOptimizeDeps,
getOptimizedDepPath,
getHash,
depsFromOptimizedDepInfo,
newDepOptimizationProcessing,
loadCachedDepOptimizationMetadata,
Expand All @@ -19,6 +18,7 @@ import type {
OptimizedDeps
} from '.'
import type { ViteDevServer } from '..'
import { getHash } from '../utils'

const isDebugEnabled = _debug('vite:deps').enabled

Expand Down
11 changes: 3 additions & 8 deletions packages/vite/src/node/plugins/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ import { cleanUrl } from '../utils'
import { FS_PREFIX } from '../constants'
import type { OutputOptions, PluginContext } from 'rollup'
import MagicString from 'magic-string'
import { createHash } from 'crypto'
import { normalizePath } from '../utils'
import { getHash, normalizePath } from '../utils'

export const assetUrlRE = /__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?/g

Expand Down Expand Up @@ -195,7 +194,7 @@ export function getAssetFilename(
* const fileName = assetFileNamesToFileName(
* 'assets/[name].[hash][extname]',
* '/path/to/file.txt',
* getAssetHash(content),
* getHash(content),
* content
* )
* // fileName: 'assets/file.982d9e3e.txt'
Expand Down Expand Up @@ -300,7 +299,7 @@ async function fileToBuiltUrl(
// https://bundlers.tooling.report/hashing/asset-cascade/
// https://github.com/rollup/rollup/issues/3415
const map = assetHashToFilenameMap.get(config)!
const contentHash = getAssetHash(content)
const contentHash = getHash(content)
const { search, hash } = parseUrl(id)
const postfix = (search || '') + (hash || '')
const output = config.build?.rollupOptions?.output
Expand Down Expand Up @@ -337,10 +336,6 @@ async function fileToBuiltUrl(
return url
}

export function getAssetHash(content: Buffer | string): string {
return createHash('sha256').update(content).digest('hex').slice(0, 8)
}

export async function urlToBuiltUrl(
url: string,
importer: string,
Expand Down
8 changes: 4 additions & 4 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import {
normalizePath,
processSrcSet,
parseRequest,
combineSourcemaps
combineSourcemaps,
getHash
} from '../utils'
import type { Plugin } from '../plugin'
import type { ResolvedConfig } from '../config'
Expand All @@ -33,8 +34,7 @@ import {
getAssetFilename,
assetUrlRE,
fileToUrl,
checkPublicFile,
getAssetHash
checkPublicFile
} from './asset'
import MagicString from 'magic-string'
import type * as PostCSS from 'postcss'
Expand Down Expand Up @@ -355,7 +355,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
const query = parseRequest(id)
if (inlineCSS && isHTMLProxy) {
addToHTMLProxyTransformResult(
`${getAssetHash(cleanUrl(id))}_${Number.parseInt(query!.index)}`,
`${getHash(cleanUrl(id))}_${Number.parseInt(query!.index)}`,
css
)
return `export default ''`
Expand Down
8 changes: 4 additions & 4 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type {
import {
cleanUrl,
generateCodeFrame,
getHash,
isDataUrl,
isExternalUrl,
normalizePath,
Expand All @@ -23,8 +24,7 @@ import {
checkPublicFile,
assetUrlRE,
urlToBuiltUrl,
getAssetFilename,
getAssetHash
getAssetFilename
} from './asset'
import { isCSSRequest } from './css'
import { modulePreloadPolyfillId } from './modulePreloadPolyfill'
Expand Down Expand Up @@ -374,7 +374,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
addToHTMLProxyCache(config, filePath, inlineModuleIndex, { code })
// will transform with css plugin and cache result with css-post plugin
js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`
const hash = getAssetHash(cleanUrl(id))
const hash = getHash(cleanUrl(id))
// will transform in `applyHtmlTransforms`
s.overwrite(
styleNode.loc.start.offset,
Expand All @@ -393,7 +393,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
code: styleNode.content
})
js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`
const hash = getAssetHash(cleanUrl(id))
const hash = getHash(cleanUrl(id))
// will transform in `applyHtmlTransforms`
s.overwrite(
styleNode.loc.start.offset,
Expand Down
8 changes: 4 additions & 4 deletions packages/vite/src/node/plugins/worker.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ResolvedConfig } from '../config'
import type { Plugin } from '../plugin'
import { fileToUrl, getAssetHash } from './asset'
import { cleanUrl, injectQuery, parseRequest } from '../utils'
import { fileToUrl } from './asset'
import { cleanUrl, getHash, injectQuery, parseRequest } from '../utils'
import type Rollup from 'rollup'
import { ENV_PUBLIC_PATH } from '../constants'
import path from 'path'
Expand Down Expand Up @@ -143,7 +143,7 @@ function emitSourcemapForWorkerEntry(
const basename = path.parse(cleanUrl(id)).name
const data = sourcemap.toString()
const content = Buffer.from(data)
const contentHash = getAssetHash(content)
const contentHash = getHash(content)
const fileName = `${basename}.${contentHash}.js.map`
const filePath = path.posix.join(config.build.assetsDir, fileName)
emitWorkerSourcemap(context, config, {
Expand Down Expand Up @@ -186,7 +186,7 @@ export async function workerFileToUrl(
}
const code = await bundleWorkerEntry(ctx, config, id, query)
const basename = path.parse(cleanUrl(id)).name
const contentHash = getAssetHash(code)
const contentHash = getHash(code)
const fileName = path.posix.join(
config.build.assetsDir,
`${basename}.${contentHash}.js`
Expand Down
5 changes: 5 additions & 0 deletions packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import colors from 'picocolors'
import fs from 'fs'
import os from 'os'
import path from 'path'
import { createHash } from 'crypto'
import { pathToFileURL, URL } from 'url'
import {
FS_PREFIX,
Expand Down Expand Up @@ -734,3 +735,7 @@ export function parseRequest(id: string): Record<string, string> | null {
}

export const blankReplacer = (match: string) => ' '.repeat(match.length)

export function getHash(text: Buffer | string): string {
return createHash('sha256').update(text).digest('hex').substring(0, 8)
}
13 changes: 0 additions & 13 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.