-
-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathindex.ts
427 lines (361 loc) · 11.6 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import { join, resolve } from 'path'
import fs from 'fs-extra'
import _debug from 'debug'
import { bold, dim, green } from 'kolorist'
import type { Plugin, ResolvedConfig, ViteDevServer } from 'vite'
import type { ObjectHook } from 'rollup'
import sirv from 'sirv'
import type { FilterPattern } from '@rollup/pluginutils'
import { createFilter } from '@rollup/pluginutils'
import { createRPCServer } from 'vite-dev-rpc'
import { hash } from 'ohash'
import type { ModuleInfo, ModuleTransformInfo, PluginMetricInfo, RPCFunctions, TransformInfo } from '../types'
import { DIR_CLIENT } from '../dir'
const debug = _debug('vite-plugin-inspect')
// initial tranform (load from fs)
const dummyLoadPluginName = '__load__'
const CLIENT_ROUTE = '/__inspect'
export interface Options {
/**
* Enable the inspect plugin in dev mode (could be some performance overhead)
*
* @default true
*/
dev?: boolean
/**
* Enable the inspect plugin in build mode, and output the report to `.vite-inspect`
*
* @default false
*/
build?: boolean
/**
* @deprecated use `dev` or `build` option instead.
*/
enabled?: boolean
/**
* Directory for build inspector UI output
* Only work in build mode
*
* @default '.vite-inspect'
*/
outputDir?: string
/**
* Filter for modules to be inspected
*/
include?: FilterPattern
/**
* Filter for modules to not be inspected
*/
exclude?: FilterPattern
}
type HookHandler<T> = T extends ObjectHook<infer F> ? F : T
type HookWrapper<K extends keyof Plugin> = (
fn: NonNullable<HookHandler<Plugin[K]>>,
context: ThisParameterType<NonNullable<HookHandler<Plugin[K]>>>,
args: NonNullable<Parameters<HookHandler<Plugin[K]>>>,
order: string
) => ReturnType<HookHandler<Plugin[K]>>
export default function PluginInspect(options: Options = {}): Plugin {
const {
dev = true,
build = false,
outputDir = '.vite-inspect',
} = options
if (!dev && !build) {
return {
name: 'vite-plugin-inspect',
}
}
const filter = createFilter(options.include, options.exclude)
let config: ResolvedConfig
type TransformMap = Record<string, TransformInfo[]>
const transformMap: TransformMap = {}
const transformMapSSR: TransformMap = {}
const idMap: Record<string, string> = {}
const idMapSSR: Record<string, string> = {}
function hijackHook<K extends keyof Plugin>(plugin: Plugin, name: K, wrapper: HookWrapper<K>) {
if (!plugin[name])
return
debug(`hijack plugin "${name}"`, plugin.name)
// @ts-expect-error future
let order = plugin.order || plugin.enforce || 'normal'
const hook = plugin[name] as any
if ('handler' in hook) {
// rollup hook
const oldFn = hook.handler
order += `-${hook.order || hook.enforce || 'normal'}`
hook.handler = function (this: any, ...args: any) { return wrapper(oldFn, this, args, order) }
}
else if ('transform' in hook) {
// transformIndexHTML
const oldFn = hook.transform
order += `-${hook.order || hook.enforce || 'normal'}`
hook.transform = function (this: any, ...args: any) { return wrapper(oldFn, this, args, order) }
}
else {
// vite hook
const oldFn = hook
plugin[name] = function (this: any, ...args: any) { return wrapper(oldFn, this, args, order) }
}
}
function hijackPlugin(plugin: Plugin) {
hijackHook(plugin, 'transform', async (fn, context, args, order) => {
const code = args[0]
const id = args[1]
const ssr = args[2]?.ssr
const start = Date.now()
const _result = await fn.apply(context, args)
const end = Date.now()
const result = typeof _result === 'string' ? _result : _result?.code
const map = ssr ? transformMapSSR : transformMap
if (filter(id) && result != null) {
// initial tranform (load from fs), add a dummy
if (!map[id])
map[id] = [{ name: dummyLoadPluginName, result: code, start, end: start }]
// record transform
map[id].push({ name: plugin.name, result, start, end, order })
}
return _result
})
hijackHook(plugin, 'load', async (fn, context, args) => {
const id = args[0]
const ssr = args[1]?.ssr
const start = Date.now()
const _result = await fn.apply(context, args)
const end = Date.now()
const result = typeof _result === 'string' ? _result : _result?.code
const map = ssr ? transformMapSSR : transformMap
if (filter(id) && result != null)
map[id] = [{ name: plugin.name, result, start, end }]
return _result
})
hijackHook(plugin, 'resolveId', async (fn, context, args) => {
const id = args[0]
const ssr = args[2]?.ssr
const _result = await fn.apply(context, args)
const result = typeof _result === 'object' ? _result?.id : _result
const map = ssr ? idMapSSR : idMap
if (!id.startsWith('./') && result && result !== id)
map[id] = result
return _result
})
}
function resolveId(id = '', ssr = false): string {
if (id.startsWith('./'))
id = resolve(config.root, id).replace(/\\/g, '/')
return resolveIdRec(id, ssr)
}
function resolveIdRec(id: string, ssr = false): string {
const map = ssr ? idMapSSR : idMap
return map[id]
? resolveIdRec(map[id], ssr)
: id
}
function getPluginMetrics(ssr = false) {
const map: Record<string, PluginMetricInfo> = {}
config.plugins.forEach((i) => {
map[i.name] = {
name: i.name,
enforce: i.enforce,
invokeCount: 0,
totalTime: 0,
}
})
Object.values(ssr ? transformMapSSR : transformMap)
.forEach((transformInfos) => {
transformInfos.forEach(({ name, start, end }) => {
if (name === dummyLoadPluginName)
return
if (!map[name])
map[name] = { name, totalTime: 0, invokeCount: 0 }
map[name].totalTime += end - start
map[name].invokeCount += 1
})
})
const metrics = Object.values(map).filter(Boolean)
.sort((a, b) => a.name.localeCompare(b.name))
.sort((a, b) => b.invokeCount - a.invokeCount)
.sort((a, b) => b.totalTime - a.totalTime)
return metrics
}
function configureServer(server: ViteDevServer) {
const _invalidateModule = server.moduleGraph.invalidateModule
server.moduleGraph.invalidateModule = function (...args) {
const mod = args[0]
if (mod?.id) {
delete transformMap[mod.id]
delete transformMapSSR[mod.id]
}
return _invalidateModule.apply(this, args)
}
server.middlewares.use((req, res, next) => {
if (req.originalUrl?.includes(CLIENT_ROUTE))
req.url = req.originalUrl
next()
})
server.middlewares.use(CLIENT_ROUTE, sirv(DIR_CLIENT, {
single: true,
dev: true,
}))
createRPCServer<RPCFunctions>('vite-plugin-inspect', server.ws, {
list,
getIdInfo,
getPluginMetrics,
resolveId,
clear: clearId,
})
async function getIdInfo(id: string, ssr = false, clear = false) {
if (clear) {
clearId(id, ssr)
try {
await server.transformRequest(id, { ssr })
}
catch {}
}
const resolvedId = resolveId(id, ssr)
const map = ssr ? transformMapSSR : transformMap
return {
resolvedId,
transforms: map[resolvedId] || [],
}
}
function getModulesInfo(map: TransformMap) {
return Object.keys(map).sort()
.map((id): ModuleInfo => {
const plugins = map[id]?.map(i => i.name)
const deps = Array.from(server.moduleGraph.getModuleById(id)?.importedModules || [])
.map(i => i.id || '')
.filter(Boolean)
return {
id,
plugins,
deps,
virtual: plugins[0] !== '__load__',
}
})
}
function list() {
return {
root: config.root,
modules: getModulesInfo(transformMap),
ssrModules: getModulesInfo(transformMapSSR),
}
}
function clearId(_id: string, ssr = false) {
const id = resolveId(_id)
if (id) {
const mod = server.moduleGraph.getModuleById(id)
if (mod)
server.moduleGraph.invalidateModule(mod)
const map = ssr ? transformMapSSR : transformMap
delete map[id]
}
}
const _print = server.printUrls
server.printUrls = () => {
const colorUrl = (url: string) => green(url.replace(/:(\d+)\//, (_, port) => `:${bold(port)}/`))
const host = server.resolvedUrls?.local[0] || `${config.server.https ? 'https' : 'http'}://localhost:${config.server.port || '80'}/`
_print()
// eslint-disable-next-line no-console
console.log(` ${green('➜')} ${bold('Inspect')}: ${colorUrl(`${host}${CLIENT_ROUTE}/`)}\n`)
}
}
async function generateBuild() {
// outputs data to `node_modules/.vite/inspect folder
const targetDir = join(config.root, outputDir)
const reportsDir = join(targetDir, 'reports')
await fs.mkdir(targetDir, { recursive: true })
await fs.copy(DIR_CLIENT, targetDir, { overwrite: true })
await fs.writeFile(
join(targetDir, 'index.html'),
(await fs.readFile(join(targetDir, 'index.html'), 'utf-8'))
.replace(
'data-vite-inspect-mode="DEV"',
'data-vite-inspect-mode="BUILD"',
),
)
await fs.rm(reportsDir, {
recursive: true,
force: true,
})
await fs.mkdir(reportsDir, { recursive: true })
function getModulesInfo(map: TransformMap) {
return Object.keys(map).sort()
.map((id): ModuleInfo => {
const plugins = map[id]?.map(i => i.name)
return {
id,
deps: [],
plugins,
virtual: plugins[0] !== '__load__' && map[id][0].name !== 'vite:load-fallback',
}
})
}
function list() {
return {
root: config.root,
modules: getModulesInfo(transformMap),
ssrModules: getModulesInfo(transformMapSSR),
}
}
await fs.writeFile(
join(reportsDir, 'list.json'),
JSON.stringify(list(), null, 2),
'utf-8',
)
await fs.writeFile(
join(reportsDir, 'metrics.json'),
JSON.stringify(getPluginMetrics(false), null, 2),
'utf-8',
)
await fs.writeFile(
join(reportsDir, 'metrics-ssr.json'),
JSON.stringify(getPluginMetrics(true), null, 2),
'utf-8',
)
async function dumpModuleInfo(dir: string, map: TransformMap, ssr = false) {
await fs.ensureDir(dir)
return Promise.all(Object.entries(map)
.map(([id, info]) => fs.writeJSON(
join(dir, `${hash(id)}.json`),
<ModuleTransformInfo>{
resolvedId: resolveId(id, ssr),
transforms: info,
}),
),
)
}
await dumpModuleInfo(join(reportsDir, 'transform'), transformMap)
await dumpModuleInfo(join(reportsDir, 'transform-ssr'), transformMapSSR, true)
return targetDir
}
return <Plugin>{
name: 'vite-plugin-inspect',
enforce: 'pre',
apply(_, { command }) {
if (command === 'serve' && dev)
return true
if (command === 'build' && build)
return true
return false
},
configResolved(_config) {
config = _config
config.plugins.forEach(hijackPlugin)
},
configureServer,
load: {
order: 'pre',
handler(id, { ssr } = {}) {
const map = ssr ? transformMapSSR : transformMap
delete map[id]
return null
},
},
async buildEnd() {
const dir = await generateBuild()
// eslint-disable-next-line no-console
console.log(green('Inspect report generated at'), dim(`${dir}`))
},
}
}