forked from nodejs/import-in-the-middle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hook.js
364 lines (316 loc) · 9.85 KB
/
hook.js
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
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2.0 License.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2021 Datadog, Inc.
const { URL } = require('url')
const { inspect } = require('util')
const specifiers = new Map()
const isWin = process.platform === 'win32'
// FIXME: Typescript extensions are added temporarily until we find a better
// way of supporting arbitrary extensions
const EXTENSION_RE = /\.(js|mjs|cjs|ts|mts|cts)$/
const NODE_VERSION = process.versions.node.split('.')
const NODE_MAJOR = Number(NODE_VERSION[0])
const NODE_MINOR = Number(NODE_VERSION[1])
let entrypoint
let getExports
if (NODE_MAJOR >= 20 || (NODE_MAJOR === 18 && NODE_MINOR >= 19)) {
getExports = require('./lib/get-exports.js')
} else {
getExports = (url) => import(url).then(Object.keys)
}
function hasIitm (url) {
try {
return new URL(url).searchParams.has('iitm')
} catch {
return false
}
}
function isIitm (url, meta) {
return url === meta.url || url === meta.url.replace('hook.mjs', 'hook.js')
}
function deleteIitm (url) {
let resultUrl
try {
const urlObj = new URL(url)
if (urlObj.searchParams.has('iitm')) {
urlObj.searchParams.delete('iitm')
resultUrl = urlObj.href
if (resultUrl.startsWith('file:node:')) {
resultUrl = resultUrl.replace('file:', '')
}
if (resultUrl.startsWith('file:///node:')) {
resultUrl = resultUrl.replace('file:///', '')
}
} else {
resultUrl = urlObj.href
}
} catch {
resultUrl = url
}
return resultUrl
}
function isNodeMajor16AndMinor17OrGreater () {
return NODE_MAJOR === 16 && NODE_MINOR >= 17
}
function isFileProtocol (urlObj) {
return urlObj.protocol === 'file:'
}
function isNodeProtocol (urlObj) {
return urlObj.protocol === 'node:'
}
function needsToAddFileProtocol (urlObj) {
if (NODE_MAJOR === 17) {
return !isFileProtocol(urlObj)
}
if (isNodeMajor16AndMinor17OrGreater()) {
return !isFileProtocol(urlObj) && !isNodeProtocol(urlObj)
}
return !isFileProtocol(urlObj) && NODE_MAJOR < 18
}
/**
* Determines if a specifier represents an export all ESM line.
* Note that the expected `line` isn't 100% valid ESM. It is derived
* from the `getExports` function wherein we have recognized the true
* line and re-mapped it to one we expect.
*
* @param {string} line
* @returns {boolean}
*/
function isStarExportLine (line) {
return /^\* from /.test(line)
}
function isBareSpecifier (specifier) {
// Relative and absolute paths are not bare specifiers.
if (
specifier.startsWith('.') ||
specifier.startsWith('/')) {
return false
}
// Valid URLs are not bare specifiers. (file:, http:, node:, etc.)
// eslint-disable-next-line no-prototype-builtins
if (URL.hasOwnProperty('canParse')) {
return !URL.canParse(specifier)
}
try {
// eslint-disable-next-line no-new
new URL(specifier)
return false
} catch (err) {
return true
}
}
function emitWarning (err) {
// Unfortunately, process.emitWarning does not output the full error
// with error.cause like console.warn does so we need to inspect it when
// tracing warnings
const warnMessage = process.execArgv.includes('--trace-warnings') ? inspect(err) : err
process.emitWarning(warnMessage)
}
/**
* Processes a module's exports and builds a set of setter blocks.
*
* @param {object} params
* @param {string} params.srcUrl The full URL to the module to process.
* @param {object} params.context Provided by the loaders API.
* @param {Function} params.parentGetSource Provides the source code for the parent module.
* @param {bool} params.excludeDefault Exclude the default export.
*
* @returns {Promise<Map<string, string>>} The shimmed setters for all the exports
* from the module and any transitive export all modules.
*/
async function processModule ({ srcUrl, context, parentGetSource, parentResolve, excludeDefault }) {
const exportNames = await getExports(srcUrl, context, parentGetSource)
const starExports = new Set()
const setters = new Map()
const addSetter = (name, setter, isStarExport = false) => {
if (setters.has(name)) {
if (isStarExport) {
// If there's already a matching star export, delete it
if (starExports.has(name)) {
setters.delete(name)
}
// and return so this is excluded
return
}
// if we already have this export but it is from a * export, overwrite it
if (starExports.has(name)) {
starExports.delete(name)
setters.set(name, setter)
}
} else {
// Store export * exports so we know they can be overridden by explicit
// named exports
if (isStarExport) {
starExports.add(name)
}
setters.set(name, setter)
}
}
for (const n of exportNames) {
if (n === 'default' && excludeDefault) continue
if (isStarExportLine(n) === true) {
const [, modFile] = n.split('* from ')
let modUrl
if (isBareSpecifier(modFile)) {
// Bare specifiers need to be resolved relative to the parent module.
const result = await parentResolve(modFile, { parentURL: srcUrl })
modUrl = result.url
} else {
modUrl = new URL(modFile, srcUrl).href
}
const setters = await processModule({
srcUrl: modUrl,
context,
parentGetSource,
parentResolve,
excludeDefault: true
})
for (const [name, setter] of setters.entries()) {
addSetter(name, setter, true)
}
} else {
addSetter(n, `
let $${n} = _.${n}
export { $${n} as ${n} }
set.${n} = (v) => {
$${n} = v
return true
}
`)
}
}
return setters
}
function addIitm (url) {
const urlObj = new URL(url)
urlObj.searchParams.set('iitm', 'true')
return needsToAddFileProtocol(urlObj) ? 'file:' + urlObj.href : urlObj.href
}
function createHook (meta) {
let cachedResolve
const iitmURL = new URL('lib/register.js', meta.url).toString()
async function resolve (specifier, context, parentResolve) {
cachedResolve = parentResolve
// See github.com/nodejs/import-in-the-middle/pull/76.
if (specifier === iitmURL) {
return {
url: specifier,
shortCircuit: true
}
}
const { parentURL = '' } = context
const newSpecifier = deleteIitm(specifier)
if (isWin && parentURL.indexOf('file:node') === 0) {
context.parentURL = ''
}
const url = await parentResolve(newSpecifier, context, parentResolve)
if (parentURL === '' && !EXTENSION_RE.test(url.url)) {
entrypoint = url.url
return { url: url.url, format: 'commonjs' }
}
if (isIitm(parentURL, meta) || hasIitm(parentURL)) {
return url
}
// Node.js v21 renames importAssertions to importAttributes
if (
(context.importAssertions && context.importAssertions.type === 'json') ||
(context.importAttributes && context.importAttributes.type === 'json')
) {
return url
}
// If the file is referencing itself, we need to skip adding the iitm search params
if (url.url === parentURL) {
return {
url: url.url,
shortCircuit: true,
format: url.format
}
}
specifiers.set(url.url, specifier)
return {
url: addIitm(url.url),
shortCircuit: true,
format: url.format
}
}
async function getSource (url, context, parentGetSource) {
if (hasIitm(url)) {
const realUrl = deleteIitm(url)
try {
const setters = await processModule({
srcUrl: realUrl,
context,
parentGetSource,
parentResolve: cachedResolve
})
return {
source: `
import { register } from '${iitmURL}'
import * as namespace from ${JSON.stringify(realUrl)}
// Mimic a Module object (https://tc39.es/ecma262/#sec-module-namespace-objects).
const _ = Object.assign(
Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } }),
namespace
)
const set = {}
${Array.from(setters.values()).join('\n')}
register(${JSON.stringify(realUrl)}, _, set, ${JSON.stringify(specifiers.get(realUrl))})
`
}
} catch (cause) {
// If there are other ESM loader hooks registered as well as iitm,
// depending on the order they are registered, source might not be
// JavaScript.
//
// If we fail to parse a module for exports, we should fall back to the
// parent loader. These modules will not be wrapped with proxies and
// cannot be Hook'ed but at least this does not take down the entire app
// and block iitm from being used.
//
// We log the error because there might be bugs in iitm and without this
// it would be very tricky to debug
const err = new Error(`'import-in-the-middle' failed to wrap '${realUrl}'`)
err.cause = cause
emitWarning(err)
// Revert back to the non-iitm URL
url = realUrl
}
}
return parentGetSource(url, context, parentGetSource)
}
// For Node.js 16.12.0 and higher.
async function load (url, context, parentLoad) {
if (hasIitm(url)) {
const { source } = await getSource(url, context, parentLoad)
return {
source,
shortCircuit: true,
format: 'module'
}
}
return parentLoad(url, context, parentLoad)
}
if (NODE_MAJOR >= 17 || (NODE_MAJOR === 16 && NODE_MINOR >= 12)) {
return { load, resolve }
} else {
return {
load,
resolve,
getSource,
getFormat (url, context, parentGetFormat) {
if (hasIitm(url)) {
return {
format: 'module'
}
}
if (url === entrypoint) {
return {
format: 'commonjs'
}
}
return parentGetFormat(url, context, parentGetFormat)
}
}
}
}
module.exports = { createHook }