Skip to content

Commit

Permalink
refactor: enhance readability
Browse files Browse the repository at this point in the history
1. update migration

2. fix virtual client manifest
  • Loading branch information
hemengke1997 committed Oct 31, 2023
1 parent 3717075 commit ce99781
Show file tree
Hide file tree
Showing 18 changed files with 95 additions and 50 deletions.
8 changes: 8 additions & 0 deletions migration-v2.0.0.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# v2.0.0 升级指南


## 新功能

- 支持自定义base,默认取vite config 中的 base
- 支持 cacheDir,默认 `node_modules/.vite-plugin-public-typescript`。如果是非vite项目,可以指定为跟 `inputDir` 同名

**喜大普奔,再也不用看到manifest.json文件啦~**

## vite项目

1. 删除manifest.json文件
Expand Down
8 changes: 4 additions & 4 deletions pnpm-lock.yaml

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

34 changes: 26 additions & 8 deletions src/node/global-config/GlobalConfigBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,20 @@ export type GlobalConfig<T extends CacheValue = CacheValue> = UserConfig<T> & {
}

export class GlobalConfigBuilder<T extends CacheValue = CacheValue> {
private _inited = false
private _globalConfig: GlobalConfig<T>

constructor() {
this._globalConfig = {} as GlobalConfig<T>
}

init(c: UserConfig<T>) {
const root = c.viteConfig.root || process.cwd()
if (this._inited) {
// only initialize once
return this
}

const root = c.viteConfig?.root || process.cwd()
const absOutputDir = path.join(root, c.outputDir)
const absInputDir = path.join(root, c.inputDir)

Expand All @@ -35,18 +41,30 @@ export class GlobalConfigBuilder<T extends CacheValue = CacheValue> {
absOutputDir,
}

this._inited = true

return this
}

get() {
return this._globalConfig
test<Path extends keyof GlobalConfig<T> | readonly string[]>(path: Path) {
return path as any
}

set(c: UserConfig<T>) {
this._globalConfig = {
...this.get(),
...c,
get<Selected extends keyof GlobalConfig<T>>(keys: Selected[]): Pick<GlobalConfig<T>, Selected>
get<Selected extends keyof GlobalConfig<T>>(key: Selected): GlobalConfig<T>[Selected]
get<Selected extends keyof GlobalConfig<T>>(key: any): any {
const result = {} as Pick<GlobalConfig<T>, Selected>
if (Array.isArray(key)) {
;(key as Selected[]).forEach((k) => {
result[k] = this._globalConfig[k]
})
return result
} else {
return this._globalConfig[key as Selected]
}
return this
}

get all() {
return this._globalConfig
}
}
8 changes: 4 additions & 4 deletions src/node/helper/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export async function esbuildTypescript(buildOptions: IBuildOptions) {

export async function build(options: { filePath: string }, onBuildEnd?: BaseCacheProcessor['onTsBuildEnd']) {
const { filePath } = options
const getGlobalConfig = globalConfig.get()
const getGlobalConfig = globalConfig.all

const originFileName = path.basename(filePath, path.extname(filePath))

Expand All @@ -114,7 +114,7 @@ export async function build(options: { filePath: string }, onBuildEnd?: BaseCach
compiledFileName = `${originFileName}.${contentHash}`
}

debug('before onBuildEnd manifest-cache:', getGlobalConfig.manifestCache.get())
debug('before onBuildEnd manifest-cache:', getGlobalConfig.manifestCache.all)

await onBuildEnd?.(
{
Expand All @@ -125,11 +125,11 @@ export async function build(options: { filePath: string }, onBuildEnd?: BaseCach
{ code, contentHash, originFileName, silent: false },
)

debug('after onBuildEnd manifest-cache:', getGlobalConfig.manifestCache.get())
debug('after onBuildEnd manifest-cache:', getGlobalConfig.manifestCache.all)
}

export async function buildAllOnce(tsFilesGlob: string[]) {
const { cacheProcessor } = globalConfig.get()
const cacheProcessor = globalConfig.get('cacheProcessor')

const toBuildList: (() => Promise<void>)[] = []

Expand Down
6 changes: 3 additions & 3 deletions src/node/helper/file-watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ export async function handleUnlink(filePath: string, cb?: () => void) {
if (_isPublicTypescript(filePath)) {
const fileName = path.parse(filePath).name
debug('unlink:', fileName)
await globalConfig.get().cacheProcessor.deleteOldJs({ originFileName: fileName })
await globalConfig.get('cacheProcessor').deleteOldJs({ originFileName: fileName })
cb?.()
}
}

export async function handleFileAdded(filePath: string, cb?: () => void) {
if (_isPublicTypescript(filePath)) {
debug('file added:', filePath)
await build({ filePath }, (...args) => globalConfig.get().cacheProcessor.onTsBuildEnd(...args))
await build({ filePath }, (...args) => globalConfig.get('cacheProcessor').onTsBuildEnd(...args))
cb?.()
}
}
Expand All @@ -41,7 +41,7 @@ async function handleFileChange(filePath: string, cb?: () => void) {

export function initWatcher(cb: (file: HmrFile) => void) {
try {
const watcher = new Watcher(globalConfig.get().absInputDir, {
const watcher = new Watcher(globalConfig.get('absInputDir'), {
debounce: 0,
ignoreInitial: true,
recursive: true,
Expand Down
2 changes: 1 addition & 1 deletion src/node/helper/io.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export function writeFile(filename: string, content: string, hash = true): void

if (fs.existsSync(filename)) {
if (hash) {
const _hash = globalConfig.get().hash
const _hash = globalConfig.get('hash')
if (extractHashFromFileName(filename, _hash)) {
// if filename has hash, skip write file
debug('skip writeFile, filename has hash')
Expand Down
2 changes: 1 addition & 1 deletion src/node/helper/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export type HmrFile = {
event: string
}
export function reloadPage(ws: WebSocketServer, file: HmrFile) {
const { logger } = globalConfig.get()
const logger = globalConfig.get('logger')

if (!isInTest()) {
logger.info(
Expand Down
10 changes: 5 additions & 5 deletions src/node/helper/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function createInternalLogger(allowClearScreen?: boolean) {
}

export function fileRelativeRootPath(filePath: string) {
return normalizePath(`/${path.relative(globalConfig.get().viteConfig.root, filePath)}`)
return normalizePath(`/${path.relative(globalConfig.get('viteConfig')!.root, filePath)}`)
}

export function isInTest() {
Expand All @@ -47,8 +47,8 @@ export function isPublicTypescript(args: { filePath: string; inputDir: string; r
export function _isPublicTypescript(filePath: string) {
return isPublicTypescript({
filePath,
inputDir: globalConfig.get().inputDir,
root: globalConfig.get().viteConfig.root,
inputDir: globalConfig.get('inputDir'),
root: globalConfig.get('viteConfig')!.root,
})
}

Expand Down Expand Up @@ -136,7 +136,7 @@ export function validateOptions(options: OptionsTypeWithDefault) {
options.inputDir = inputDir.replace(/\/$/, '')
}

if (options.sideEffects !== undefined) {
if (options.sideEffects !== undefined && !isInTest()) {
console.warn(
colors.yellow(
`${colors.bold('(warning!)')} [${pkgName}]: sideEffects option is ${colors.bold(
Expand Down Expand Up @@ -212,7 +212,7 @@ export async function setupGlobalConfig(viteConfig: ResolvedConfig, opts: Option
...(opts as Required<OptionsTypeWithDefault>),
})

return globalConfig.get()
return globalConfig
}

export async function setupManifestCache(viteConfig: ResolvedConfig, opts: OptionsTypeWithDefault) {
Expand Down
4 changes: 2 additions & 2 deletions src/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export default function publicTypescript(options: VPPTPluginOptions = {}) {
manifestCache.writeManifestJSON()
}

const { originFilesGlob } = globalConfig.get()
const originFilesGlob = globalConfig.get('originFilesGlob')

const originFilesName = originFilesGlob.map((file) => path.parse(file).name)

Expand Down Expand Up @@ -161,7 +161,7 @@ export default function publicTypescript(options: VPPTPluginOptions = {}) {
},
generateBundle() {
if (opts.destination === 'memory') {
const c = manifestCache.get()
const c = manifestCache.all
Object.keys(c).forEach((key) => {
this.emitFile({
fileName: normalizeAssetsDirPath(`${c[key]._pathToDisk}`),
Expand Down
22 changes: 18 additions & 4 deletions src/node/manifest-cache/ManifestCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,15 @@ export type CacheValue = {
path: string
} & Partial<{ [_key: string]: string }>

export type CacheObject<V extends CacheValue> = {
export type CacheManifest<V extends CacheValue> = {
[fileName in string]: V
}

const DEFAULT_OPTIONS: ManifestConstructor = {
writable: true,
}

export class ManifestCache<T extends CacheValue = CacheValue, U extends CacheObject<T> = CacheObject<T>> {
export class ManifestCache<T extends CacheValue = CacheValue, U extends CacheManifest<T> = CacheManifest<T>> {
private _cache: U

private _manifestPath = ''
Expand All @@ -57,10 +57,24 @@ export class ManifestCache<T extends CacheValue = CacheValue, U extends CacheObj
})
}

get() {
get all() {
return Object.assign({}, this._cache)
}

get<Selected extends keyof U>(keys: Selected[]): Pick<U, Selected>
get<Selected extends keyof U>(key: Selected): U[Selected]
get<Selected extends keyof U>(key: any): any {
const result = {} as Pick<U, Selected>
if (Array.isArray(key)) {
;(key as Selected[]).forEach((k) => {
result[k] = this._cache[k]
})
return result
} else {
return this._cache[key as Selected]
}
}

// NOTE: the only way to set cache
set(c: U, opts?: { silent?: boolean }) {
const keys = Object.keys(c)
Expand Down Expand Up @@ -124,7 +138,7 @@ export class ManifestCache<T extends CacheValue = CacheValue, U extends CacheObj
}

getManifestJson() {
return this.extractPath(this.get())
return this.extractPath(this.all)
}

sortObjectByKey(c: PathOnlyCache) {
Expand Down
15 changes: 11 additions & 4 deletions src/node/manifest-cache/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { normalizePath } from 'vite'
import { globalConfig } from '../global-config'
import { DEFAULT_OPTIONS } from '../helper/default-options'
import { readJsonFile, writeJsonFile } from '../helper/io'
import { isInTest } from '../helper/utils'
import { isEmptyObject, isInTest } from '../helper/utils'
import { type CacheValue, ManifestCache } from './ManifestCache'

export type CacheValueEx = {
Expand All @@ -22,7 +22,7 @@ function getManifestPath(root?: string) {
root = process.env.__Manifest_Path__
}
if (!root) {
root = globalConfig.get().viteConfig?.root || process.cwd()
root = globalConfig.get('viteConfig')?.root || process.cwd()
}

return normalizePath(path.resolve(root, ManifestCachePath))
Expand All @@ -37,10 +37,17 @@ export function saveManifestPathToDisk() {
}

export function getManifest(root?: string) {
const manifestPath = readJsonFile(getManifestPath(root))?.manifestPath
if (!isEmptyObject(manifestCache.getManifestJson())) {
return manifestCache.getManifestJson()
}

if (!isEmptyObject(manifestCache.readManifestFile())) {
return manifestCache.readManifestFile()
}

const manifestPath = readJsonFile(getManifestPath(root))?.manifestPath
if (manifestPath) {
return readJsonFile(manifestPath)
return readJsonFile(manifestPath) || {}
}

return {}
Expand Down
2 changes: 1 addition & 1 deletion src/node/plugins/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export function pluginServer(): PluginOption {
const { src, vppt } = getScriptInfo(node)

if (vppt?.name && src?.value) {
const c = manifestCache.get()
const c = manifestCache.all
let cacheItem = manifestCache.findCacheItemByPath(src.value)

if (!cacheItem) {
Expand Down
4 changes: 2 additions & 2 deletions src/node/plugins/virtual.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { type PluginOption } from 'vite'
import { resolvedVirtualModuleId, virtualModuleId } from '../helper/virtual'
import { manifestCache } from '../manifest-cache'
import { getManifest } from '../manifest-cache'

export function pluginVirtual(): PluginOption {
const plugin: PluginOption = {
Expand All @@ -18,7 +18,7 @@ export function pluginVirtual(): PluginOption {
},
async load(id) {
if (id === resolvedVirtualModuleId) {
return `export default ${JSON.stringify(manifestCache.getManifestJson())}`
return `export default ${JSON.stringify(getManifest())}`
}
},
}
Expand Down
10 changes: 4 additions & 6 deletions src/node/processor/FileCacheProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class FileCacheProcessor extends ManifestCacheProcessor {
const {
outputDir,
viteConfig: { publicDir },
} = globalConfig.get()
} = globalConfig.get(['outputDir', 'viteConfig'])

let oldFiles: string[] = []
try {
Expand All @@ -42,7 +42,7 @@ export class FileCacheProcessor extends ManifestCacheProcessor {

debug('deleteOldJsFile - oldFiles:', oldFiles)

debug('manifestCache:', this.manifestCache.get())
debug('manifestCache:', this.manifestCache.all)

if (oldFiles.length > 0) {
for (const f of oldFiles) {
Expand All @@ -66,11 +66,9 @@ export class FileCacheProcessor extends ManifestCacheProcessor {

async addNewJs(args: AddFileArgs): Promise<void> {
const { code = '' } = args
const {
viteConfig: { publicDir },
} = globalConfig.get()
const { publicDir } = globalConfig.get('viteConfig')

const pathToDisk = this.setCache(args, globalConfig.get())
const pathToDisk = this.setCache(args, globalConfig.all)

const jsFilePath = normalizePath(path.join(publicDir, pathToDisk))

Expand Down
2 changes: 1 addition & 1 deletion src/node/processor/ManifestCacheProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,6 @@ export abstract class ManifestCacheProcessor extends BaseCacheProcessor<CacheVal
_hash: contentHash,
},
})
return this.manifestCache.get()[originFileName]._pathToDisk || ''
return this.manifestCache.get(originFileName)._pathToDisk || ''
}
}
Loading

0 comments on commit ce99781

Please sign in to comment.