generated from egoist/ts-lib-starter
-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.ts
364 lines (324 loc) · 9.84 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
import fs from "fs"
import path from "path"
import { pathToFileURL } from "url"
import {
build,
context,
Loader,
BuildOptions,
BuildFailure,
BuildResult,
Plugin as EsbuildPlugin,
TsconfigRaw,
} from "esbuild"
import { loadTsConfig } from "load-tsconfig"
import { dynamicImport, getRandomId, guessFormat } from "./utils"
const DIRNAME_VAR_NAME = "__injected_dirname__"
const FILENAME_VAR_NAME = "__injected_filename__"
const IMPORT_META_URL_VAR_NAME = "__injected_import_meta_url__"
export const JS_EXT_RE = /\.([mc]?[tj]s|[tj]sx)$/
const PATH_NODE_MODULES_RE = /[\/\\]node_modules[\/\\]/
function inferLoader(ext: string): Loader {
if (ext === ".mjs" || ext === ".cjs") return "js"
if (ext === ".mts" || ext === ".cts") return "ts"
return ext.slice(1) as Loader
}
export { dynamicImport }
export type RequireFunction = (
outfile: string,
ctx: { format: "cjs" | "esm" },
) => any
export type GetOutputFile = (filepath: string, format: "esm" | "cjs") => string
export type RebuildCallback = (
error: Pick<BuildFailure, "errors" | "warnings"> | null,
result: BuildResult | null,
) => void
export interface Options {
cwd?: string
/**
* The filepath to bundle and require
*/
filepath: string
/**
* The `require` function that is used to load the output file
* Default to the global `require` function
* This function can be asynchronous, i.e. returns a Promise
*/
require?: RequireFunction
/**
* esbuild options
*
* @deprecated `esbuildOptions.watch` is deprecated, use `onRebuild` instead
*/
esbuildOptions?: BuildOptions & {
watch?:
| boolean
| {
onRebuild?: RebuildCallback
}
}
/**
* Get the path to the output file
* By default we simply replace the extension with `.bundled_{randomId}.js`
*/
getOutputFile?: GetOutputFile
/**
* Enable watching and call the callback after each rebuild
*/
onRebuild?: (ctx: {
err?: Pick<BuildFailure, "errors" | "warnings">
mod?: any
dependencies?: string[]
}) => void
/** External packages */
external?: (string | RegExp)[]
/** Not external packages */
notExternal?: (string | RegExp)[]
/**
* Automatically mark node_modules as external
* @default true - `false` when `filepath` is in node_modules
*/
externalNodeModules?: boolean
/**
* A custom tsconfig path to read `paths` option
*
* Set to `false` to disable tsconfig
* Or provide a `TsconfigRaw` object
*/
tsconfig?: string | TsconfigRaw | false
/**
* Preserve compiled temporary file for debugging
* Default to `process.env.BUNDLE_REQUIRE_PRESERVE`
*/
preserveTemporaryFile?: boolean
/**
* Provide bundle format explicitly
* to skip the default format inference
*/
format?: "cjs" | "esm"
}
// Use a random path to avoid import cache
const defaultGetOutputFile: GetOutputFile = (filepath, format) =>
filepath.replace(
JS_EXT_RE,
`.bundled_${getRandomId()}.${format === "esm" ? "mjs" : "cjs"}`,
)
export { loadTsConfig }
export const tsconfigPathsToRegExp = (paths: Record<string, any>) => {
return Object.keys(paths || {}).map((key) => {
return new RegExp(`^${key.replace(/\*/, ".*")}$`)
})
}
export const match = (id: string, patterns?: (string | RegExp)[]) => {
if (!patterns) return false
return patterns.some((p) => {
if (p instanceof RegExp) {
return p.test(id)
}
return id === p || id.startsWith(p + "/")
})
}
/**
* An esbuild plugin to mark node_modules as external
*/
export const externalPlugin = ({
external,
notExternal,
externalNodeModules = true,
}: {
external?: (string | RegExp)[]
notExternal?: (string | RegExp)[]
externalNodeModules?: boolean
} = {}): EsbuildPlugin => {
return {
name: "bundle-require:external",
setup(ctx) {
ctx.onResolve({ filter: /.*/ }, async (args) => {
if (match(args.path, external)) {
return {
external: true,
}
}
if (match(args.path, notExternal)) {
// Should be resolved by esbuild
return
}
if (externalNodeModules && args.path.match(PATH_NODE_MODULES_RE)) {
const resolved = args.path[0] === "."
? path.resolve(args.resolveDir, args.path)
: args.path
return {
path: pathToFileURL(resolved).toString(),
external: true,
}
}
if (args.path[0] === "." || path.isAbsolute(args.path)) {
// Fallback to default
return
}
// Most like importing from node_modules, mark external
return {
external: true,
}
})
},
}
}
export const injectFileScopePlugin = (): EsbuildPlugin => {
return {
name: "bundle-require:inject-file-scope",
setup(ctx) {
ctx.initialOptions.define = {
...ctx.initialOptions.define,
__dirname: DIRNAME_VAR_NAME,
__filename: FILENAME_VAR_NAME,
"import.meta.url": IMPORT_META_URL_VAR_NAME,
}
ctx.onLoad({ filter: JS_EXT_RE }, async (args) => {
const contents = await fs.promises.readFile(args.path, "utf-8")
const injectLines = [
`const ${FILENAME_VAR_NAME} = ${JSON.stringify(args.path)};`,
`const ${DIRNAME_VAR_NAME} = ${JSON.stringify(
path.dirname(args.path),
)};`,
`const ${IMPORT_META_URL_VAR_NAME} = ${JSON.stringify(
pathToFileURL(args.path).href,
)};`,
]
return {
contents: injectLines.join("") + contents,
loader: inferLoader(path.extname(args.path)),
}
})
},
}
}
export function bundleRequire<T = any>(
options: Options,
): Promise<{
mod: T
dependencies: string[]
}> {
return new Promise((resolve, reject) => {
if (!JS_EXT_RE.test(options.filepath)) {
throw new Error(`${options.filepath} is not a valid JS file`)
}
const preserveTemporaryFile =
options.preserveTemporaryFile ?? !!process.env.BUNDLE_REQUIRE_PRESERVE
const cwd = options.cwd || process.cwd()
const format = options.format ?? guessFormat(options.filepath)
const tsconfig = options.tsconfig === false
? undefined
: typeof options.tsconfig === "string" || !options.tsconfig
? loadTsConfig(cwd, options.tsconfig)
: { data: options.tsconfig, path: undefined }
const resolvePaths = tsconfigPathsToRegExp(
tsconfig?.data.compilerOptions?.paths || {},
)
const extractResult = async (result: BuildResult) => {
if (!result.outputFiles) {
throw new Error(`[bundle-require] no output files`)
}
const { text } = result.outputFiles[0]
const getOutputFile = options.getOutputFile || defaultGetOutputFile
const outfile = getOutputFile(options.filepath, format)
await fs.promises.writeFile(outfile, text, "utf8")
let mod: any
const req: RequireFunction = options.require || dynamicImport
try {
mod = await req(
format === "esm" ? pathToFileURL(outfile).href : outfile,
{ format },
)
} finally {
if (!preserveTemporaryFile) {
// Remove the outfile after executed
await fs.promises.unlink(outfile)
}
}
return {
mod,
dependencies: result.metafile
? Object.keys(result.metafile.inputs)
: [],
}
}
const { watch: watchMode, ...restEsbuildOptions } =
options.esbuildOptions || {}
const esbuildOptions = {
...restEsbuildOptions,
entryPoints: [options.filepath],
absWorkingDir: cwd,
outfile: "out.js",
format,
platform: "node",
sourcemap: "inline",
bundle: true,
metafile: true,
write: false,
...(tsconfig?.path)
? { tsconfig: tsconfig.path }
: { tsconfigRaw: tsconfig?.data || {} },
plugins: [
...(options.esbuildOptions?.plugins || []),
externalPlugin({
external: options.external,
notExternal: [
...(options.notExternal || []),
...resolvePaths
],
// When `filepath` is in node_modules, this is default to false
externalNodeModules: options.externalNodeModules ?? !options.filepath.match(PATH_NODE_MODULES_RE),
}),
injectFileScopePlugin(),
],
} satisfies BuildOptions
const run = async () => {
if (!(watchMode || options.onRebuild)) {
const result = await build(esbuildOptions)
resolve(await extractResult(result))
} else {
const rebuildCallback: RebuildCallback =
typeof watchMode === "object" &&
typeof watchMode.onRebuild === "function"
? watchMode.onRebuild
: async (error, result) => {
if (error) {
options.onRebuild?.({ err: error })
}
if (result) {
options.onRebuild?.(await extractResult(result))
}
}
const onRebuildPlugin = (): EsbuildPlugin => {
return {
name: "bundle-require:on-rebuild",
setup(ctx) {
let count = 0
ctx.onEnd(async (result) => {
if (count++ === 0) {
if (result.errors.length === 0)
resolve(await extractResult(result))
} else {
if (result.errors.length > 0) {
return rebuildCallback(
{ errors: result.errors, warnings: result.warnings },
null,
)
}
if (result) {
rebuildCallback(null, result)
}
}
})
},
}
}
esbuildOptions.plugins.push(onRebuildPlugin())
const ctx = await context(esbuildOptions)
await ctx.watch()
}
}
run().catch(reject)
})
}