-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathindex.ts
More file actions
353 lines (326 loc) · 11.8 KB
/
index.ts
File metadata and controls
353 lines (326 loc) · 11.8 KB
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
import { createRequire } from 'node:module'
import inject from '@rollup/plugin-inject'
import stdLibBrowser from 'node-stdlib-browser'
import { handleCircularDependancyWarning } from 'node-stdlib-browser/helpers/rollup/plugin'
import esbuildPlugin from 'node-stdlib-browser/helpers/esbuild/plugin'
import type { Plugin } from 'vite'
import { compareModuleNames, isEnabled, isNodeProtocolImport, toRegExp, withoutNodeProtocol } from './utils'
type TransformHook = Extract<Plugin['transform'], Function>
export type BuildTarget = 'build' | 'dev'
export type BooleanOrBuildTarget = boolean | BuildTarget
export type ModuleName = keyof typeof stdLibBrowser
export type ModuleNameWithoutNodePrefix<T = ModuleName> = T extends `node:${infer P}` ? P : never
export type PolyfillOptions = {
/**
* Includes specific modules. If empty, includes all modules
* @example
*
* ```ts
* nodePolyfills({
* include: ['fs', 'path'],
* })
* ```
*/
include?: ModuleNameWithoutNodePrefix[],
/**
* @example
*
* ```ts
* nodePolyfills({
* exclude: ['fs', 'path'],
* })
* ```
*/
exclude?: ModuleNameWithoutNodePrefix[],
/**
* Specify whether specific globals should be polyfilled.
*
* @example
*
* ```ts
* nodePolyfills({
* globals: {
* Buffer: false,
* global: true,
* process: 'build',
* },
* })
* ```
*/
globals?: {
Buffer?: BooleanOrBuildTarget,
global?: BooleanOrBuildTarget,
process?: BooleanOrBuildTarget,
},
/**
* Specify alternative modules to use in place of the default polyfills.
*
* @example
*
* ```ts
* nodePolyfills({
* overrides: {
* fs: 'memfs',
* },
* })
* ```
*/
overrides?: { [Key in ModuleNameWithoutNodePrefix]?: string },
/**
* Specify whether the Node protocol version of an import (e.g. `node:buffer`) should be polyfilled too.
*
* @default true
*/
protocolImports?: boolean,
}
export type PolyfillOptionsResolved = {
include: ModuleNameWithoutNodePrefix[],
exclude: ModuleNameWithoutNodePrefix[],
globals: {
Buffer: BooleanOrBuildTarget,
global: BooleanOrBuildTarget,
process: BooleanOrBuildTarget,
},
overrides: { [Key in ModuleNameWithoutNodePrefix]?: string },
protocolImports: boolean,
}
const globalShimBanners = {
buffer: [
`import __buffer_polyfill from 'vite-plugin-node-polyfills/shims/buffer'`,
`globalThis.Buffer = globalThis.Buffer || __buffer_polyfill`,
],
global: [
`import __global_polyfill from 'vite-plugin-node-polyfills/shims/global'`,
`globalThis.global = globalThis.global || __global_polyfill`,
],
process: [
`import __process_polyfill from 'vite-plugin-node-polyfills/shims/process'`,
`globalThis.process = globalThis.process || __process_polyfill`,
],
}
const isModuleName = (name: string): name is ModuleName => {
return name in stdLibBrowser
}
/**
* Returns a Vite plugin to polyfill Node's Core Modules for browser environments. Supports `node:` protocol imports.
*
* @example
*
* ```ts
* // vite.config.ts
* import { defineConfig } from 'vite'
* import { nodePolyfills } from 'vite-plugin-node-polyfills'
*
* export default defineConfig({
* plugins: [
* nodePolyfills({
* // Specific modules that should not be polyfilled.
* exclude: [],
* // Whether to polyfill specific globals.
* globals: {
* Buffer: true, // can also be 'build', 'dev', or false
* global: true,
* process: true,
* },
* // Whether to polyfill `node:` protocol imports.
* protocolImports: true,
* }),
* ],
* })
* ```
*/
export const nodePolyfills = (options: PolyfillOptions = {}): Plugin[] => {
const optionsResolved: PolyfillOptionsResolved = {
include: [],
exclude: [],
overrides: {},
protocolImports: true,
...options,
globals: {
Buffer: true,
global: true,
process: true,
...options.globals,
},
}
const isExcluded = (moduleName: ModuleName) => {
if (optionsResolved.include.length > 0) {
return !optionsResolved.include.some((includedName) => compareModuleNames(moduleName, includedName))
}
return optionsResolved.exclude.some((excludedName) => compareModuleNames(moduleName, excludedName))
}
const toOverride = (name: ModuleNameWithoutNodePrefix): string | void => {
if (isEnabled(optionsResolved.globals.Buffer, 'dev') && /^buffer$/.test(name)) {
return 'vite-plugin-node-polyfills/shims/buffer'
}
if (isEnabled(optionsResolved.globals.global, 'dev') && /^global$/.test(name)) {
return 'vite-plugin-node-polyfills/shims/global'
}
if (isEnabled(optionsResolved.globals.process, 'dev') && /^process$/.test(name)) {
return 'vite-plugin-node-polyfills/shims/process'
}
if (name in optionsResolved.overrides) {
return optionsResolved.overrides[name]
}
}
const polyfills = (Object.entries(stdLibBrowser) as Array<[ModuleName, string]>).reduce<Record<ModuleName, string>>((included, [name, value]) => {
if (!optionsResolved.protocolImports) {
if (isNodeProtocolImport(name)) {
return included
}
}
if (!isExcluded(name)) {
included[name] = toOverride(withoutNodeProtocol(name)) || value
}
return included
}, {} as Record<ModuleName, string>)
const require = createRequire(import.meta.url)
const globalShimPaths = [
...((isEnabled(optionsResolved.globals.Buffer, 'dev')) ? [require.resolve('vite-plugin-node-polyfills/shims/buffer')] : []),
...((isEnabled(optionsResolved.globals.global, 'dev')) ? [require.resolve('vite-plugin-node-polyfills/shims/global')] : []),
...((isEnabled(optionsResolved.globals.process, 'dev')) ? [require.resolve('vite-plugin-node-polyfills/shims/process')] : []),
]
const resolvePlugin: Plugin = {
name: 'vite-plugin-node-polyfills:resolve',
enforce: 'pre',
resolveId: {
// @ts-expect-error -- hook filters are only supported in Vite 6.3.0+
filter: { id: new RegExp(Object.keys(stdLibBrowser).map((name) => `^${name}\/?$`).join('|')) },
async handler(source, importer, opts) {
if (!optionsResolved.protocolImports && isNodeProtocolImport(source)) {
return
}
source = source.endsWith('/') ? source.slice(0, -1) : source // strip trailing slash
if (!isModuleName(source) || isExcluded(source)) {
return
}
const aliased = toOverride(withoutNodeProtocol(source)) || stdLibBrowser[source]
const resolved = await this.resolve(aliased, importer, { skipSelf: true, ...opts })
return resolved
},
},
}
const globalShimsBanner = [
...((isEnabled(optionsResolved.globals.Buffer, 'dev')) ? globalShimBanners.buffer : []),
...((isEnabled(optionsResolved.globals.global, 'dev')) ? globalShimBanners.global : []),
...((isEnabled(optionsResolved.globals.process, 'dev')) ? globalShimBanners.process : []),
``,
].join('\n')
let rawInjectPlugin: Plugin | false | undefined
function transform(this: ThisParameterType<TransformHook>, code: string, id: string, opts: Parameters<TransformHook>[2]) {
if (rawInjectPlugin === undefined) {
throw new Error('transform called before inject plugin initialization')
}
if (rawInjectPlugin === false) {
return
}
return (rawInjectPlugin.transform as TransformHook).call(this, code, id, opts)
}
const injectPlugin: Plugin = {
name: 'vite-plugin-node-polyfills:inject',
enforce: 'post',
transform,
}
const plugin: Plugin = {
name: 'vite-plugin-node-polyfills',
config(config, env) {
const isDev = env.command === 'serve'
// @ts-expect-error - this.meta.rolldownVersion only exists with rolldown-vite 7+
const isRolldownVite = !!this?.meta?.rolldownVersion
// https://github.com/niksy/node-stdlib-browser/blob/3e7cd7f3d115ac5c4593b550e7d8c4a82a0d4ac4/README.md?plain=1#L203-L209
const defines = {
...((isDev && isEnabled(optionsResolved.globals.Buffer, 'dev')) ? { Buffer: 'Buffer' } : {}),
...((isDev && isEnabled(optionsResolved.globals.global, 'dev')) ? { global: 'global' } : {}),
...((isDev && isEnabled(optionsResolved.globals.process, 'dev')) ? { process: 'process' } : {}),
}
const shimsToInject = {
// https://github.com/niksy/node-stdlib-browser/blob/3e7cd7f3d115ac5c4593b550e7d8c4a82a0d4ac4/README.md#vite
...(isEnabled(optionsResolved.globals.Buffer, 'build') ? { Buffer: 'vite-plugin-node-polyfills/shims/buffer' } : {}),
...(isEnabled(optionsResolved.globals.global, 'build') ? { global: 'vite-plugin-node-polyfills/shims/global' } : {}),
...(isEnabled(optionsResolved.globals.process, 'build') ? { process: 'vite-plugin-node-polyfills/shims/process' } : {}),
}
const isNativeInjectAvailable = env.command === 'build' && isRolldownVite
rawInjectPlugin = (Object.keys(shimsToInject).length > 0 && !isNativeInjectAvailable) ? inject(shimsToInject) as Plugin : false
if (rawInjectPlugin === false) {
delete injectPlugin.transform
} else {
// hook filters are only supported in Vite 6.3.0+
(transform as any).filter = {
code: new RegExp(Object.keys(shimsToInject).join('|')),
}
}
return {
build: {
rollupOptions: {
onwarn: (warning, rollupWarn) => {
handleCircularDependancyWarning(warning, () => {
if (config.build?.rollupOptions?.onwarn) {
return config.build.rollupOptions.onwarn(warning, rollupWarn)
}
rollupWarn(warning)
})
},
...(Object.keys(shimsToInject).length > 0 && isRolldownVite)
? { transform: { inject: shimsToInject } }
: {},
},
},
optimizeDeps: {
exclude: [
...globalShimPaths,
],
...isRolldownVite
? {
rolldownOptions: {
transform: {
define: defines,
},
plugins: [
resolvePlugin,
{
name: 'vite-plugin-node-polyfills:optimizer',
banner: isDev ? globalShimsBanner : undefined,
},
],
},
}
: {
esbuildOptions: {
banner: isDev ? { js: globalShimsBanner } : undefined,
define: defines,
inject: [
...globalShimPaths,
],
plugins: [
esbuildPlugin(polyfills),
// Supress the 'injected path "..." cannot be marked as external' error in Vite 4 (emitted by esbuild).
// https://github.com/evanw/esbuild/blob/edede3c49ad6adddc6ea5b3c78c6ea7507e03020/internal/bundler/bundler.go#L1469
{
name: 'vite-plugin-node-polyfills-shims-resolver',
setup(build) {
for (const globalShimPath of globalShimPaths) {
const globalShimsFilter = toRegExp(globalShimPath)
// https://esbuild.github.io/plugins/#on-resolve
build.onResolve({ filter: globalShimsFilter }, () => {
return {
// https://github.com/evanw/esbuild/blob/edede3c49ad6adddc6ea5b3c78c6ea7507e03020/internal/bundler/bundler.go#L1468
external: false,
path: globalShimPath,
}
})
}
},
},
],
},
},
},
}
},
}
return [
resolvePlugin,
injectPlugin,
plugin,
]
}