@plugjs/plug 0.3.5 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/dist/asserts.cjs +10 -12
  2. package/dist/asserts.cjs.map +1 -1
  3. package/dist/asserts.d.ts +1 -2
  4. package/dist/asserts.mjs +9 -10
  5. package/dist/asserts.mjs.map +1 -1
  6. package/dist/async.cjs +5 -20
  7. package/dist/async.cjs.map +2 -2
  8. package/dist/async.mjs +5 -20
  9. package/dist/async.mjs.map +2 -2
  10. package/dist/build.cjs +113 -64
  11. package/dist/build.cjs.map +2 -2
  12. package/dist/build.d.ts +9 -7
  13. package/dist/build.mjs +110 -63
  14. package/dist/build.mjs.map +2 -2
  15. package/dist/cli.d.mts +12 -0
  16. package/dist/cli.mjs +266 -0
  17. package/dist/cli.mjs.map +6 -0
  18. package/dist/files.cjs +5 -3
  19. package/dist/files.cjs.map +1 -1
  20. package/dist/files.d.ts +2 -1
  21. package/dist/files.mjs +11 -4
  22. package/dist/files.mjs.map +1 -1
  23. package/dist/fork.cjs +30 -12
  24. package/dist/fork.cjs.map +1 -1
  25. package/dist/fork.d.ts +10 -0
  26. package/dist/fork.mjs +31 -13
  27. package/dist/fork.mjs.map +1 -1
  28. package/dist/helpers.cjs +32 -13
  29. package/dist/helpers.cjs.map +2 -2
  30. package/dist/helpers.d.ts +12 -0
  31. package/dist/helpers.mjs +37 -14
  32. package/dist/helpers.mjs.map +2 -2
  33. package/dist/index.cjs +5 -0
  34. package/dist/index.cjs.map +1 -1
  35. package/dist/index.d.ts +2 -1
  36. package/dist/index.mjs +4 -1
  37. package/dist/index.mjs.map +1 -1
  38. package/dist/logging/emit.cjs +4 -4
  39. package/dist/logging/emit.cjs.map +1 -1
  40. package/dist/logging/emit.mjs +4 -4
  41. package/dist/logging/emit.mjs.map +1 -1
  42. package/dist/logging/logger.cjs +43 -2
  43. package/dist/logging/logger.cjs.map +1 -1
  44. package/dist/logging/logger.d.ts +36 -3
  45. package/dist/logging/logger.mjs +43 -3
  46. package/dist/logging/logger.mjs.map +1 -1
  47. package/dist/logging/options.cjs +8 -12
  48. package/dist/logging/options.cjs.map +1 -1
  49. package/dist/logging/options.d.ts +44 -1
  50. package/dist/logging/options.mjs +8 -12
  51. package/dist/logging/options.mjs.map +1 -1
  52. package/dist/logging.cjs +14 -3
  53. package/dist/logging.cjs.map +1 -1
  54. package/dist/logging.d.ts +2 -0
  55. package/dist/logging.mjs +13 -3
  56. package/dist/logging.mjs.map +1 -1
  57. package/dist/plugs/build.cjs +63 -0
  58. package/dist/plugs/build.cjs.map +6 -0
  59. package/dist/plugs/build.d.ts +13 -0
  60. package/dist/plugs/build.mjs +37 -0
  61. package/dist/plugs/build.mjs.map +6 -0
  62. package/dist/plugs/debug.cjs +7 -9
  63. package/dist/plugs/debug.cjs.map +1 -1
  64. package/dist/plugs/debug.mjs +8 -10
  65. package/dist/plugs/debug.mjs.map +1 -1
  66. package/dist/types.cjs +12 -0
  67. package/dist/types.cjs.map +1 -1
  68. package/dist/types.d.ts +35 -9
  69. package/dist/types.mjs +5 -0
  70. package/dist/types.mjs.map +2 -2
  71. package/dist/utils/diff.cjs +1 -4
  72. package/dist/utils/diff.cjs.map +1 -1
  73. package/dist/utils/diff.mjs +1 -4
  74. package/dist/utils/diff.mjs.map +1 -1
  75. package/dist/utils/exec.cjs +5 -12
  76. package/dist/utils/exec.cjs.map +2 -2
  77. package/dist/utils/exec.d.ts +0 -2
  78. package/dist/utils/exec.mjs +6 -13
  79. package/dist/utils/exec.mjs.map +1 -1
  80. package/dist/utils/{types.cjs → singleton.cjs} +14 -13
  81. package/dist/utils/singleton.cjs.map +6 -0
  82. package/dist/utils/singleton.d.ts +12 -0
  83. package/dist/utils/singleton.mjs +13 -0
  84. package/dist/utils/singleton.mjs.map +6 -0
  85. package/dist/utils.cjs +2 -2
  86. package/dist/utils.cjs.map +1 -1
  87. package/dist/utils.d.ts +1 -1
  88. package/dist/utils.mjs +1 -1
  89. package/package.json +7 -9
  90. package/src/asserts.ts +10 -12
  91. package/src/async.ts +6 -29
  92. package/src/build.ts +169 -106
  93. package/{extra/plug.mts → src/cli.mts} +115 -141
  94. package/src/files.ts +14 -6
  95. package/src/fork.ts +42 -16
  96. package/src/helpers.ts +56 -5
  97. package/src/index.ts +2 -1
  98. package/src/logging/emit.ts +4 -4
  99. package/src/logging/logger.ts +60 -7
  100. package/src/logging/options.ts +9 -14
  101. package/src/logging.ts +20 -5
  102. package/src/plugs/build.ts +45 -0
  103. package/src/plugs/debug.ts +10 -9
  104. package/src/types.ts +54 -23
  105. package/src/utils/diff.ts +1 -6
  106. package/src/utils/exec.ts +6 -20
  107. package/src/utils/singleton.ts +19 -0
  108. package/src/utils.ts +1 -1
  109. package/cli/plug.mjs +0 -1385
  110. package/cli/ts-loader.mjs +0 -275
  111. package/cli/tsrun.mjs +0 -1204
  112. package/dist/utils/types.cjs.map +0 -6
  113. package/dist/utils/types.d.ts +0 -4
  114. package/dist/utils/types.mjs +0 -12
  115. package/dist/utils/types.mjs.map +0 -6
  116. package/extra/ts-loader.mts +0 -546
  117. package/extra/tsrun.mts +0 -127
  118. package/extra/utils.ts +0 -150
  119. package/src/utils/types.ts +0 -11
@@ -1,6 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/utils/types.ts"],
4
- "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAMO,SAAS,UAAU,MAA0B;AAClD,MAAI,MAAM,QAAQ,IAAI;AAAG,WAAO;AAChC,MAAI,SAAS;AAAM,WAAO;AAC1B,SAAO,OAAO;AAChB;",
5
- "names": []
6
- }
@@ -1,4 +0,0 @@
1
- /** A type adding the values `null` or `array` to the result of `typeof` */
2
- export type BasicType = 'string' | 'number' | 'bigint' | 'boolean' | 'symbol' | 'undefined' | 'object' | 'function' | 'null' | 'array';
3
- /** Get the _real_ type of a value, including `null` or `array` */
4
- export declare function getTypeOf(what: unknown): BasicType;
@@ -1,12 +0,0 @@
1
- // utils/types.ts
2
- function getTypeOf(what) {
3
- if (Array.isArray(what))
4
- return "array";
5
- if (what === null)
6
- return "null";
7
- return typeof what;
8
- }
9
- export {
10
- getTypeOf
11
- };
12
- //# sourceMappingURL=types.mjs.map
@@ -1,6 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/utils/types.ts"],
4
- "mappings": ";AAMO,SAAS,UAAU,MAA0B;AAClD,MAAI,MAAM,QAAQ,IAAI;AAAG,WAAO;AAChC,MAAI,SAAS;AAAM,WAAO;AAC1B,SAAO,OAAO;AAChB;",
5
- "names": []
6
- }
@@ -1,546 +0,0 @@
1
- /* ========================================================================== *
2
- * HACK BEYOND REDEMPTION: TRANSPILE .ts FILES (the esm loader) *
3
- * -------------------------------------------------------------------------- *
4
- * This relies on the Node's `--experimental-loader` feature, and uses *
5
- * ESBuild build magic to quickly transpile TypeScript files into JavaScript. *
6
- * *
7
- * The plan as it stands is as follows: *
8
- * - `.mts` files always get transpiled to ESM modules *
9
- * - `.cts` files always get transpiled to CJS modules *
10
- * - `.ts` files are treanspiled according to what's in `package.json` *
11
- * *
12
- * Additionally, when transpiling to ESM modules, we can't rely on the magic *
13
- * that Node's `require(...)` call uses to figure out which file to import. *
14
- * We need to _actually verify_ on disk what's the correct file to import. *
15
- * *
16
- * This is a single module, only available as ESM, and it will _both_ behave *
17
- * as a NodeJS' loader, _and_ inject the CJS extension handlers (hack) found *
18
- * in the `_extensions` of `node:module` (same as `require.extensions`). *
19
- * ========================================================================== */
20
-
21
- // NodeJS dependencies
22
- import _fs from 'node:fs'
23
- import _module from 'node:module'
24
- import _path from 'node:path'
25
- import _url from 'node:url'
26
- import _util from 'node:util'
27
-
28
- // ESBuild is the only external dependency
29
- import _esbuild from 'esbuild'
30
-
31
- // Local imports
32
- import { isDirectory, isFile } from './utils.js'
33
-
34
- /* ========================================================================== *
35
- * DEBUGGING AND ERRORS *
36
- * ========================================================================== */
37
-
38
- /** Supported types from `package.json` */
39
- export type Type = 'commonjs' | 'module'
40
- /** Constant identifying a `commonjs` module */
41
- const CJS = 'commonjs'
42
- /** Constant identifying an ESM `module` */
43
- const ESM = 'module'
44
-
45
- /** Setup debugging */
46
- const _debugLog = _util.debuglog('plug:ts-loader')
47
- const _debug = _debugLog.enabled
48
-
49
- /** Emit some logs if `DEBUG_TS_LOADER` is set to `true` */
50
- function _log(type: Type | null, arg: string, ...args: any []): void {
51
- if (! _debug) return
52
-
53
- const t = type === ESM ? 'esm' : type === CJS ? 'cjs' : '---'
54
- _debugLog(`[${t}] ${arg}`, ...args)
55
- }
56
-
57
- /** Fail miserably */
58
- function _throw(
59
- type: Type | null,
60
- message: string,
61
- options: { start?: Function, code?: string, cause?: any } = {},
62
- ): never {
63
- const t = type === ESM ? 'esm' : type === CJS ? 'cjs' : '---'
64
- const prefix = `[ts-loader|${t}|pid=${process.pid}]`
65
-
66
- const { start = _throw, ...extra } = options
67
- const error = new Error(`${prefix} ${message}`)
68
- Error.captureStackTrace(error, start)
69
- Object.assign(error, extra)
70
-
71
- throw error
72
- }
73
-
74
-
75
- /* ========================================================================== *
76
- * MODULE TYPES AND FORCING TYPE *
77
- * ========================================================================== */
78
-
79
- function _checkType(type: string): Type {
80
- if (type === CJS) return CJS
81
- if (type === ESM) return ESM
82
- _throw(null, `Invalid type "${process.env.__TS_LOADER_FORCE_TYPE}"`)
83
- }
84
-
85
- let _type: Type = ((): Type => {
86
- if (process.env.__TS_LOADER_FORCE_TYPE) {
87
- const type = process.env.__TS_LOADER_FORCE_TYPE
88
- _log(null, `Forcing type to "${type}" from environment`)
89
- return _checkType(type)
90
- }
91
-
92
- const findType = (directory: string): Type => {
93
- const packageFile = _path.join(directory, 'package.json')
94
- try {
95
- const packageData = _fs.readFileSync(packageFile, 'utf-8')
96
- const packageJson = JSON.parse(packageData)
97
- const packageType = packageJson.type
98
- switch (packageType) {
99
- case undefined:
100
- _log(null, `File "${packageFile}" does not declare a default type`)
101
- return CJS
102
-
103
- case CJS:
104
- case ESM:
105
- _log(null, `File "${packageFile}" declares type as "${CJS}"`)
106
- return packageType
107
-
108
- default:
109
- _log(null, `File "${packageFile}" specifies unknown type "${packageType}"`)
110
- return CJS
111
- }
112
- } catch (cause: any) {
113
- if ((cause.code !== 'ENOENT') && (cause.code !== 'EISDIR')) {
114
- _throw(null, `Unable to read or parse "${packageFile}"`, { cause, start: findType })
115
- }
116
- }
117
-
118
- const parent = _path.dirname(directory)
119
- if (directory !== parent) return findType(directory)
120
-
121
- _log(null, `Type defaulted to "${CJS}"`)
122
- return CJS
123
- }
124
-
125
- return findType(process.cwd())
126
- })()
127
-
128
- /* The `tsLoaderMarker` (symbol in global) will be a setter/getter for type */
129
- const tsLoaderMarker = Symbol.for('plugjs:tsLoader')
130
-
131
- Object.defineProperty(globalThis, tsLoaderMarker, {
132
- set(type: string): void {
133
- _log(null, `Setting type to "${type}"`)
134
- process.env.__TS_LOADER_FORCE_TYPE = _type = _checkType(type)
135
- },
136
- get(): Type {
137
- return _type
138
- },
139
- })
140
-
141
-
142
- /* ========================================================================== *
143
- * ESBUILD HELPERS *
144
- * ========================================================================== */
145
-
146
- /**
147
- * Take an ESBuild `BuildResult` or `BuildFailure` (they both have arrays
148
- * of `Message` in both `warnings` and `errors`), format them and print them
149
- * out nicely. Then fail if any error was detected.
150
- */
151
- function _esbReport(
152
- kind: 'error' | 'warning',
153
- messages: _esbuild.Message[] = [],
154
- ): void {
155
- const output = process.stderr
156
- const options = { color: !!output.isTTY, terminalWidth: output.columns || 80 }
157
-
158
- const array = _esbuild.formatMessagesSync(messages, { kind, ...options })
159
- array.forEach((message) => output.write(`${message}\n`))
160
- }
161
-
162
- /**
163
- * Transpile with ESBuild
164
- */
165
- function _esbTranpile(filename: string, type: Type): string {
166
- _log(type, `Transpiling "${filename}`)
167
-
168
- const [ format, __fileurl ] = type === ESM ?
169
- [ 'esm', 'import.meta.url' ] as const :
170
- [ 'cjs', '__filename' ] as const
171
-
172
- /* ESbuild options */
173
- const options: _esbuild.TransformOptions = {
174
- sourcefile: filename, // the original filename we're parsing
175
- format, // what are we actually transpiling to???
176
- loader: 'ts', // the format is always "typescript"
177
- sourcemap: 'inline', // always inline source maps
178
- sourcesContent: false, // do not include sources content in sourcemap
179
- platform: 'node', // d'oh! :-)
180
- minifyWhitespace: true, // https://github.com/evanw/esbuild/releases/tag/v0.16.14
181
- logLevel: 'silent', // catching those in our _esbReport below
182
- target: `node${process.versions['node']}`, // target _this_ version
183
- define: { __fileurl }, // from "globals.d.ts"
184
- }
185
-
186
- /* Emit a line on the console when loading in debug mode */
187
- if (_debug) {
188
- if (format === 'esm') {
189
- options.banner = `;(await import('node:util')).debuglog('plug:ts-loader')('[esm] Loaded "%s"', ${__fileurl});`
190
- } else if (format === 'cjs') {
191
- options.banner = `;require('node:util').debuglog('plug:ts-loader')('[cjs] Loaded "%s"', ${__fileurl});`
192
- }
193
- }
194
-
195
- /* Transpile our TypeScript file into some JavaScript stuff */
196
- let result
197
- try {
198
- const source = _fs.readFileSync(filename, 'utf-8')
199
- result = _esbuild.transformSync(source, options)
200
- } catch (cause: any) {
201
- _esbReport('error', (cause as _esbuild.TransformFailure).errors)
202
- _esbReport('warning', (cause as _esbuild.TransformFailure).warnings)
203
- _throw(type, `ESBuild error transpiling "${filename}"`, { cause, start: _esbTranpile })
204
- }
205
-
206
- /* Log transpile warnings if debugging */
207
- if (_debug) _esbReport('warning', result.warnings)
208
-
209
- /* Done! */
210
- return result.code
211
- }
212
-
213
-
214
- /* ========================================================================== *
215
- * ESM VERSION *
216
- * ========================================================================== */
217
-
218
- /** The formats that can be handled by NodeJS' loader */
219
- type Format = 'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'
220
-
221
- /* ========================================================================== */
222
-
223
- /** The type identifying a NodeJS' loader `resolve` hook. */
224
- type ResolveHook = (
225
- /** Whatever was requested to be imported (module, relative file, ...). */
226
- specifier: string,
227
- /** Context information around this `resolve` hook call. */
228
- context: ResolveContext,
229
- /** The subsequent resolve hook in the chain, or the Node.js default one. */
230
- nextResolve: ResolveNext,
231
- ) => ResolveResult | Promise<ResolveResult>
232
-
233
- /** Context information around a `resolve` hook call. */
234
- interface ResolveContext {
235
- importAssertions: object
236
- /** Export conditions of the relevant `package.json`. */
237
- conditions: string[]
238
- /** The module importing this one, or undefined if this is the entry point. */
239
- parentURL?: string | undefined
240
- }
241
-
242
- /** The subsequent resolve hook in the chain, or the Node.js default one. */
243
- type ResolveNext = (specifier: string, context: ResolveContext) => ResolveResult | Promise<ResolveResult>
244
-
245
- /** A type describing the required results from a `resolve` hook */
246
- interface ResolveResult {
247
- /** The absolute URL to which this input resolves. */
248
- url: string
249
- /** A format hint to the `load` hook (it might be ignored). */
250
- format?: Format | null | undefined
251
- /** A signal that this hook intends to terminate the chain of resolve hooks. */
252
- shortCircuit?: boolean | undefined
253
- }
254
-
255
- /* ========================================================================== */
256
-
257
- /** The type identifying a NodeJS' loader `load` hook. */
258
- type LoadHook = (
259
- /** The URL returned by the resolve chain. */
260
- url: string,
261
- /** Context information around this `load` hook call. */
262
- context: LoadContext,
263
- /** The subsequent load hook in the chain, or the Node.js default one. */
264
- nextLoad: LoadNext,
265
- ) => LoadResult | Promise<LoadResult>
266
-
267
- /** Context information around a `load` hook call. */
268
- interface LoadContext {
269
- importAssertions: object
270
- /** Export conditions of the relevant `package.json` */
271
- conditions: string[]
272
- /** The format hint from the `resolve` hook. */
273
- format?: ResolveResult['format']
274
- }
275
-
276
- /** The subsequent load hook in the chain, or the Node.js default one. */
277
- type LoadNext = (url: string, context: LoadContext) => LoadResult | Promise<LoadResult>
278
-
279
- /** A type describing the required results from a `resolve` hook */
280
- type LoadResult = {
281
- /** The format of the code being loaded. */
282
- format: Format
283
- /** A signal that this hook intends to terminate the chain of load hooks. */
284
- shortCircuit?: boolean | undefined
285
- } & ({
286
- format: 'builtin' | 'commonjs'
287
- /** When the source is `builtin` or `commonjs` no source must be returned */
288
- source?: never | undefined
289
- } | {
290
- format: 'json' | 'module'
291
- /** When the source is `json` or `module` the source can include strings */
292
- source: string | ArrayBuffer | NodeJS.TypedArray
293
- } | {
294
- format: 'wasm'
295
- /** When the source is `wasm` the source must not be a string */
296
- source: ArrayBuffer | NodeJS.TypedArray
297
- })
298
-
299
- /* ========================================================================== */
300
-
301
- /**
302
- * Our main `resolve` hook: here we need to check for a couple of options
303
- * when importing ""
304
- */
305
- export const resolve: ResolveHook = (specifier, context, nextResolve): ResolveResult | Promise<ResolveResult> => {
306
- _log(ESM, `Resolving "${specifier}" from "${context.parentURL}"`)
307
-
308
- /* We only resolve relative paths ("./xxx" or "../xxx") */
309
- if (! specifier.match(/^\.\.?\//)) return nextResolve(specifier, context)
310
-
311
- /* We only resolve if we _do_ have a parent URL and it's a file */
312
- const parentURL = context.parentURL
313
- if (! parentURL) return nextResolve(specifier, context)
314
- if (! parentURL.startsWith('file:')) return nextResolve(specifier, context)
315
-
316
- /* We only resolve here if the importer is a ".ts" or ".mts" file */
317
- if (! parentURL.match(/\.m?ts$/)) return nextResolve(specifier, context)
318
-
319
- /* The resolved URL is the specifier resolved against the parent */
320
- const url = new URL(specifier, parentURL).href
321
- const path = _url.fileURLToPath(url)
322
-
323
- /*
324
- * Here we are sure that:
325
- *
326
- * 1) we are resolving a local path (not a module)
327
- * 2) the importer is a file, ending with ".ts" or ".mts"
328
- *
329
- * Now we can check if "import 'foo'" resolves to:
330
- *
331
- * 1) directly to a file, e.g. "import './foo.js'" or "import './foo.mts'"
332
- * 2) import a "pseudo-JS file", e.g. "import './foo.js'" becomes "import './foo.ts'"
333
- * 3) imports a file without extension as if it were "import './foo.ts'"
334
- * 4) imports a directory as in "import './foo/index.ts'"
335
- *
336
- * We resolve the _final_ specifier that will be passed to the next resolver
337
- * for further potential resolution accordingly.
338
- *
339
- * We start with the easiest case: is this a real file on the disk?
340
- */
341
- if (isFile(path)) {
342
- _log(ESM, `Positive match for "${specifier}" as "${path}" (1)`)
343
- return nextResolve(specifier, context) // straight on
344
- }
345
-
346
- /*
347
- * TypeScript allows us to import "./foo.js", and internally resolves this to
348
- * "./foo.ts" (yeah, nice, right?) and while we normally wouldn't want to deal
349
- * with this kind of stuff, the "node16" module resolution mode _forces_ us to
350
- * use this syntax.
351
- */
352
- const match = specifier.match(/(.*)(\.[mc]?js$)/)
353
- if (match) {
354
- const [ , base, ext ] = match
355
- const tsspecifier = base + ext!.replace('js', 'ts')
356
- const tsurl = new URL(tsspecifier, parentURL).href
357
- const tspath = _url.fileURLToPath(tsurl)
358
-
359
- if (isFile(tspath)) {
360
- _log(ESM, `Positive match for "${specifier}" as "${tspath}" (2)`)
361
- return nextResolve(tsspecifier, context) // straight on
362
- }
363
- }
364
-
365
- /* Check if the import is actually a file with a ".ts" extension */
366
- if (isFile(`${path}.ts`)) {
367
- _log(ESM, `Positive match for "${specifier}.ts" as "${path}.ts" (3)`)
368
- return nextResolve(`${specifier}.ts`, context)
369
- }
370
-
371
- /* If the file is a directory, then see if we have an "index.ts" in there */
372
- if (isDirectory(path)) {
373
- const file = _path.resolve(path, 'index.ts') // resolve, as path is absolute
374
- if (isFile(file)) {
375
- _log(ESM, `Positive match for "${specifier}" as "${file}" (4)`)
376
- const spec = _url.pathToFileURL(file).pathname
377
- return nextResolve(spec, context)
378
- }
379
- }
380
-
381
- /* There's really nothing else we can do */
382
- return nextResolve(specifier, context)
383
- }
384
-
385
- /** Our main `load` hook */
386
- export const load: LoadHook = (url, context, nextLoad): LoadResult | Promise<LoadResult> => {
387
- _log(ESM, `Attempting to load "${url}"`)
388
-
389
- /* We only load from disk, so ignore everything else */
390
- if (! url.startsWith('file:')) return nextLoad(url, context)
391
-
392
- /* Figure our the extension (especially ".ts", ".mts" or ".cts")... */
393
- const ext = url.match(/\.[cm]?ts$/)?.[0]
394
-
395
- /* Quick and easy bail-outs for non-TS or ".cts" (always `commonjs`) */
396
- if (! ext) return nextLoad(url, context)
397
-
398
- if (ext === '.cts') {
399
- if (_debug) {
400
- _log(null, `Switching type from "module" to "commonjs" for "${url}"`)
401
- _log(null, 'Please note that named import WILL NOT WORK in this case, as Node.js performs a')
402
- _log(null, 'static analisys on the CommonJS source code, and this file is transpiled from.')
403
- _log(null, 'TypeScript to CommonJS dynamically.')
404
- }
405
- return { format: CJS, shortCircuit: true }
406
- }
407
-
408
- /* Convert the url into a file name, any error gets ignored */
409
- const filename = _url.fileURLToPath(url)
410
-
411
- /* If the file is a ".ts", we need to figure out the default type */
412
- if (ext === '.ts') {
413
- if (_type === CJS) {
414
- if (_debug) {
415
- _log(null, `Switching type from "module" to "commonjs" for "${url}"`)
416
- _log(null, 'Please note that named import WILL NOT WORK in this case, as Node.js performs a')
417
- _log(null, 'static analisys on the CommonJS source code, and this file is transpiled from.')
418
- _log(null, 'TypeScript to CommonJS dynamically.')
419
- }
420
- return { format: CJS, shortCircuit: true }
421
- }
422
- }
423
-
424
- /* Transpile with ESBuild and return our source code */
425
- const source = _esbTranpile(filename, ESM)
426
- return { source, format: ESM, shortCircuit: true }
427
- }
428
-
429
-
430
- /* ========================================================================== *
431
- * CJS VERSION *
432
- * ========================================================================== */
433
-
434
- /** The extension handler type, loading CJS modules */
435
- type ExtensionHandler = (module: NodeJS.Module, filename: string) => void
436
-
437
- /* Add the `_compile(...)` method to NodeJS' `Module` interface */
438
- declare global {
439
- namespace NodeJS {
440
- interface Module {
441
- _compile: (contents: string, filename: string) => void
442
- }
443
- }
444
- }
445
-
446
- /**
447
- * Add the `_extensions[...]` and `resolveFilename(...)` members to the
448
- * definition of `node:module`.
449
- */
450
- declare module 'node:module' {
451
- const _extensions: Record<`.${string}`, ExtensionHandler>
452
- function _resolveFilename(
453
- request: string,
454
- parent: _module | undefined,
455
- isMain: boolean,
456
- options?: any,
457
- ): string
458
- }
459
-
460
- /* ========================================================================== */
461
-
462
- const loader: ExtensionHandler = (module, filename): void => {
463
- _log(CJS, `Attempting to load "${filename}"`)
464
-
465
- /* Figure our the extension (".ts" or ".cts")... */
466
- const ext = _path.extname(filename)
467
-
468
- /* If the file is a ".ts", we need to figure out the default type */
469
- if (ext === '.ts') {
470
- /* If the _default_ module type is CJS then load as such! */
471
- if (_type === ESM) {
472
- _throw(CJS, `Must use import to load ES Module: ${filename}`, { code: 'ERR_REQUIRE_ESM' })
473
- }
474
- } else if (ext !== '.cts') {
475
- _throw(CJS, `Unsupported filename "${filename}"`)
476
- }
477
-
478
- const source = _esbTranpile(filename, CJS)
479
-
480
- /* Let node do its thing, but wrap any error it throws */
481
- try {
482
- module._compile(source, filename)
483
- } catch (cause) {
484
- // eslint-disable-next-line no-console
485
- console.error(`Error compiling module "${filename}"`, cause)
486
- }
487
- }
488
-
489
- /* Remember to load our loader for .TS/.CTS as CommonJS modules */
490
- _module._extensions['.ts'] = _module._extensions['.cts'] = loader
491
-
492
- /**
493
- * Replace _module._resolveFilename with our own.
494
- *
495
- * This is a _HACK BEYOND REDEMPTION_ and I'm ashamed of even _thinking_ about
496
- * it, but, well, it makes things work.
497
- *
498
- * TypeScript allows us to import "./foo.js", and internally resolves this to
499
- * "./foo.ts" (yeah, nice, right?) and while we normally wouldn't want to deal
500
- * with this kind of stuff, the "node16" module resolution mode _forces_ us to
501
- * use this syntax.
502
- *
503
- * And we _need_ the "node16" module resolution to properly consume "export
504
- * conditions" from other packages. Since ESBuild's plugins only work in async
505
- * mode, changing those import statements on the fly is out of the question, so
506
- * we need to hack our way into Node's own resolver.
507
- *
508
- * See my post: https://twitter.com/ianosh/status/1559484168685379590
509
- * ESBuild related fix: https://github.com/evanw/esbuild/commit/0cdc005e3d1c765a084f206741bc4bff78e30ec4
510
- */
511
- const _oldResolveFilename = _module._resolveFilename
512
- _module._resolveFilename = function(
513
- request: string,
514
- parent: _module | undefined,
515
- ...args: [ isMain: boolean, options: any ]
516
- ): any {
517
- try {
518
- /* First call the old _resolveFilename to see what Node thinks */
519
- return _oldResolveFilename.call(this, request, parent, ...args)
520
- } catch (error: any) {
521
- /* If the error was anything but "MODULE_NOT_FOUND" bail out */
522
- if (error.code !== 'MODULE_NOT_FOUND') throw error
523
-
524
- /* Check if the "request" ends with ".js", ".mjs" or ".cjs" */
525
- const match = request.match(/(.*)(\.[mc]?js$)/)
526
-
527
- /*
528
- * If the file matches our extension, _and_ we have a parent, we simply
529
- * try with a new extension (e.g. ".js" becomes ".ts")...
530
- */
531
- if (parent && match) {
532
- const [ , name, ext ] = match
533
- const tsrequest = name + ext!.replace('js', 'ts')
534
- try {
535
- const result = _oldResolveFilename.call(this, tsrequest, parent, ...args)
536
- _log(CJS, `Resolution for "${request}" intercepted as "${tsrequest}`)
537
- return result
538
- } catch (discard) {
539
- throw error // throw the _original_ error in this case
540
- }
541
- }
542
-
543
- /* We have no parent, or we don't match our extension, throw! */
544
- throw error
545
- }
546
- }