This repository has been archived by the owner on Apr 6, 2023. It is now read-only.
/
dev-bundler.ts
247 lines (224 loc) · 7.37 KB
/
dev-bundler.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
import { pathToFileURL } from 'node:url'
import { existsSync } from 'node:fs'
import { builtinModules } from 'node:module'
import { isAbsolute, resolve } from 'pathe'
import * as vite from 'vite'
import { ExternalsOptions, isExternal as _isExternal, ExternalsDefaults } from 'externality'
import { genDynamicImport, genObjectFromRawEntries } from 'knitwork'
import { hashId, uniq } from './utils'
export interface TransformChunk {
id: string,
code: string,
deps: string[],
parents: string[]
}
export interface SSRTransformResult {
code: string,
map: object,
deps: string[]
dynamicDeps: string[]
}
export interface TransformOptions {
viteServer: vite.ViteDevServer
}
function isExternal (opts: TransformOptions, id: string) {
// Externals
const ssrConfig = (opts.viteServer.config as any).ssr
const externalOpts: ExternalsOptions = {
inline: [
/virtual:/,
/\.ts$/,
...ExternalsDefaults.inline,
...ssrConfig.noExternal
],
external: [
...ssrConfig.external,
/node_modules/
],
resolve: {
type: 'module',
extensions: ['.ts', '.js', '.json', '.vue', '.mjs', '.jsx', '.tsx', '.wasm']
}
}
return _isExternal(id, opts.viteServer.config.root, externalOpts)
}
async function transformRequest (opts: TransformOptions, id: string) {
// Virtual modules start with `\0`
if (id && id.startsWith('/@id/__x00__')) {
id = '\0' + id.slice('/@id/__x00__'.length)
}
if (id && id.startsWith('/@id/')) {
id = id.slice('/@id/'.length)
}
if (id && id.startsWith('/@fs/')) {
// Absolute path
id = id.slice('/@fs'.length)
// On Windows, this may be `/C:/my/path` at this point, in which case we want to remove the `/`
if (id.match(/^\/\w:/)) {
id = id.slice(1)
}
} else if (id.startsWith('/') && !(/\/app\/entry(|.mjs)$/.test(id))) {
// Relative to the root directory
const resolvedPath = resolve(opts.viteServer.config.root, '.' + id)
if (existsSync(resolvedPath)) {
id = resolvedPath
}
}
// Vite will add ?v=123 to bypass browser cache
// Remove for externals
const withoutVersionQuery = id.replace(/\?v=\w+$/, '')
if (await isExternal(opts, withoutVersionQuery)) {
const path = builtinModules.includes(withoutVersionQuery.split('node:').pop())
? withoutVersionQuery
: isAbsolute(withoutVersionQuery) ? pathToFileURL(withoutVersionQuery).href : withoutVersionQuery
return {
code: `(global, module, _, exports, importMeta, ssrImport, ssrDynamicImport, ssrExportAll) =>
${genDynamicImport(path, { wrapper: false })}
.then(r => {
if (r.default && r.default.__esModule)
r = r.default
exports.default = r.default
ssrExportAll(r)
})
.catch(e => {
console.error(e)
throw new Error(${JSON.stringify(`[vite dev] Error loading external "${id}".`)})
})`,
deps: [],
dynamicDeps: []
}
}
// Transform
const res: SSRTransformResult = await opts.viteServer.transformRequest(id, { ssr: true }).catch((err) => {
// eslint-disable-next-line no-console
console.warn(`[SSR] Error transforming ${id}:`, err)
// console.error(err)
}) as SSRTransformResult || { code: '', map: {}, deps: [], dynamicDeps: [] }
// Wrap into a vite module
const code = `async function (global, module, exports, __vite_ssr_exports__, __vite_ssr_import_meta__, __vite_ssr_import__, __vite_ssr_dynamic_import__, __vite_ssr_exportAll__) {
${res.code || '/* empty */'};
}`
return { code, deps: res.deps || [], dynamicDeps: res.dynamicDeps || [] }
}
async function transformRequestRecursive (opts: TransformOptions, id, parent = '<entry>', chunks: Record<string, TransformChunk> = {}) {
if (chunks[id]) {
chunks[id].parents.push(parent)
return
}
const res = await transformRequest(opts, id)
const deps = uniq([...res.deps, ...res.dynamicDeps])
chunks[id] = {
id,
code: res.code,
deps,
parents: [parent]
} as TransformChunk
for (const dep of deps) {
await transformRequestRecursive(opts, dep, id, chunks)
}
return Object.values(chunks)
}
export async function bundleRequest (opts: TransformOptions, entryURL: string) {
const chunks = await transformRequestRecursive(opts, entryURL)
const listIds = (ids: string[]) => ids.map(id => `// - ${id} (${hashId(id)})`).join('\n')
const chunksCode = chunks.map(chunk => `
// --------------------
// Request: ${chunk.id}
// Parents: \n${listIds(chunk.parents)}
// Dependencies: \n${listIds(chunk.deps)}
// --------------------
const ${hashId(chunk.id + '-' + chunk.code)} = ${chunk.code}
`).join('\n')
const manifestCode = `const __modules__ = ${
genObjectFromRawEntries(chunks.map(chunk => [chunk.id, hashId(chunk.id + '-' + chunk.code)]))
}`
// https://github.com/vitejs/vite/blob/main/packages/vite/src/node/ssr/ssrModuleLoader.ts
const ssrModuleLoader = `
const __pendingModules__ = new Map()
const __pendingImports__ = new Map()
const __ssrContext__ = { global: globalThis }
function __ssrLoadModule__(url, urlStack = []) {
const pendingModule = __pendingModules__.get(url)
if (pendingModule) { return pendingModule }
const modulePromise = __instantiateModule__(url, urlStack)
__pendingModules__.set(url, modulePromise)
modulePromise.catch(() => { __pendingModules__.delete(url) })
.finally(() => { __pendingModules__.delete(url) })
return modulePromise
}
async function __instantiateModule__(url, urlStack) {
const mod = __modules__[url]
if (mod.stubModule) { return mod.stubModule }
const stubModule = { [Symbol.toStringTag]: 'Module' }
Object.defineProperty(stubModule, '__esModule', { value: true })
mod.stubModule = stubModule
// https://vitejs.dev/guide/api-hmr.html
const importMeta = { url, hot: { accept() {}, prune() {}, dispose() {}, invalidate() {}, decline() {}, on() {} } }
urlStack = urlStack.concat(url)
const isCircular = url => urlStack.includes(url)
const pendingDeps = []
const ssrImport = async (dep) => {
// TODO: Handle externals if dep[0] !== '.' | '/'
if (!isCircular(dep) && !__pendingImports__.get(dep)?.some(isCircular)) {
pendingDeps.push(dep)
if (pendingDeps.length === 1) {
__pendingImports__.set(url, pendingDeps)
}
await __ssrLoadModule__(dep, urlStack)
if (pendingDeps.length === 1) {
__pendingImports__.delete(url)
} else {
pendingDeps.splice(pendingDeps.indexOf(dep), 1)
}
}
return __modules__[dep].stubModule
}
function ssrDynamicImport (dep) {
// TODO: Handle dynamic import starting with . relative to url
return ssrImport(dep)
}
function ssrExportAll(sourceModule) {
for (const key in sourceModule) {
if (key !== 'default') {
try {
Object.defineProperty(stubModule, key, {
enumerable: true,
configurable: true,
get() { return sourceModule[key] }
})
} catch (_err) { }
}
}
}
const cjsModule = {
get exports () {
return stubModule.default
},
set exports (v) {
stubModule.default = v
},
}
await mod(
__ssrContext__.global,
cjsModule,
stubModule.default,
stubModule,
importMeta,
ssrImport,
ssrDynamicImport,
ssrExportAll
)
return stubModule
}
`
const code = [
chunksCode,
manifestCode,
ssrModuleLoader,
`export default await __ssrLoadModule__(${JSON.stringify(entryURL)})`
].join('\n\n')
return {
code,
ids: chunks.map(i => i.id)
}
}