forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcustomization_hooks.js
402 lines (370 loc) · 12 KB
/
customization_hooks.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
'use strict';
const {
ArrayPrototypeFindIndex,
ArrayPrototypePush,
ArrayPrototypeSplice,
ObjectAssign,
ObjectFreeze,
StringPrototypeStartsWith,
Symbol,
} = primordials;
const {
isAnyArrayBuffer,
isArrayBufferView,
} = require('internal/util/types');
const { BuiltinModule } = require('internal/bootstrap/realm');
const {
ERR_INVALID_RETURN_PROPERTY_VALUE,
} = require('internal/errors').codes;
const { validateFunction } = require('internal/validators');
const { isAbsolute } = require('path');
const { pathToFileURL, fileURLToPath } = require('internal/url');
let debug = require('internal/util/debuglog').debuglog('module_hooks', (fn) => {
debug = fn;
});
/**
* @typedef {import('internal/modules/cjs/loader.js').Module} Module
*/
/**
* @typedef {(
* specifier: string,
* context: Partial<ModuleResolveContext>,
* ) => ModuleResolveResult
* } NextResolve
* @typedef {(
* specifier: string,
* context: ModuleResolveContext,
* nextResolve: NextResolve,
* ) => ModuleResolveResult
* } ResolveHook
* @typedef {(
* url: string,
* context: Partial<ModuleLoadContext>,
* ) => ModuleLoadResult
* } NextLoad
* @typedef {(
* url: string,
* context: ModuleLoadContext,
* nextLoad: NextLoad,
* ) => ModuleLoadResult
* } LoadHook
*/
// Use arrays for better insertion and iteration performance, we don't care
// about deletion performance as much.
/** @type {ResolveHook[]} */
const resolveHooks = [];
/** @type {LoadHook[]} */
const loadHooks = [];
const hookId = Symbol('kModuleHooksIdKey');
let nextHookId = 0;
class ModuleHooks {
/**
* @param {ResolveHook|undefined} resolve User-provided hook.
* @param {LoadHook|undefined} load User-provided hook.
*/
constructor(resolve, load) {
this[hookId] = Symbol(`module-hook-${nextHookId++}`);
// Always initialize all hooks, if it's unspecified it'll be an owned undefined.
this.resolve = resolve;
this.load = load;
if (resolve) {
ArrayPrototypePush(resolveHooks, this);
}
if (load) {
ArrayPrototypePush(loadHooks, this);
}
ObjectFreeze(this);
}
// TODO(joyeecheung): we may want methods that allow disabling/enabling temporarily
// which just sets the item in the array to undefined temporarily.
// TODO(joyeecheung): this can be the [Symbol.dispose] implementation to pair with
// `using` when the explicit resource management proposal is shipped by V8.
/**
* Deregister the hook instance.
*/
deregister() {
const id = this[hookId];
let index = ArrayPrototypeFindIndex(resolveHooks, (hook) => hook[hookId] === id);
if (index !== -1) {
ArrayPrototypeSplice(resolveHooks, index, 1);
}
index = ArrayPrototypeFindIndex(loadHooks, (hook) => hook[hookId] === id);
if (index !== -1) {
ArrayPrototypeSplice(loadHooks, index, 1);
}
}
};
/**
* TODO(joyeecheung): taken an optional description?
* @param {{ resolve?: ResolveHook, load?: LoadHook }} hooks User-provided hooks
* @returns {ModuleHooks}
*/
function registerHooks(hooks) {
const { resolve, load } = hooks;
if (resolve) {
validateFunction(resolve, 'hooks.resolve');
}
if (load) {
validateFunction(load, 'hooks.load');
}
return new ModuleHooks(resolve, load);
}
/**
* @param {string} filename
* @returns {string}
*/
function convertCJSFilenameToURL(filename) {
if (!filename) { return filename; }
const builtinId = BuiltinModule.normalizeRequirableId(filename);
if (builtinId) {
return `node:${builtinId}`;
}
// Handle the case where filename is neither a path, nor a built-in id,
// which is possible via monkey-patching.
if (isAbsolute(filename)) {
return pathToFileURL(filename).href;
}
return filename;
}
/**
* @param {string} url
* @returns {string}
*/
function convertURLToCJSFilename(url) {
if (!url) { return url; }
const builtinId = BuiltinModule.normalizeRequirableId(url);
if (builtinId) {
return builtinId;
}
if (StringPrototypeStartsWith(url, 'file://')) {
return fileURLToPath(url);
}
return url;
}
/**
* Convert a list of hooks into a function that can be used to do an operation through
* a chain of hooks. If any of the hook returns without calling the next hook, it
* must return shortCircuit: true to stop the chain from continuing to avoid
* forgetting to invoke the next hook by mistake.
* @param {ModuleHooks[]} hooks A list of hooks whose last argument is `nextHook`.
* @param {'load'|'resolve'} name Name of the hook in ModuleHooks.
* @param {Function} defaultStep The default step in the chain.
* @param {Function} validate A function that validates and sanitize the result returned by the chain.
*/
function buildHooks(hooks, name, defaultStep, validate, mergedContext) {
let lastRunIndex = hooks.length;
/**
* Helper function to wrap around invocation of user hook or the default step
* in order to fill in missing arguments or check returned results.
* Due to the merging of the context, this must be a closure.
* @param {number} index Index in the chain. Default step is 0, last added hook is 1,
* and so on.
* @param {Function} userHookOrDefault Either the user hook or the default step to invoke.
* @param {Function|undefined} next The next wrapped step. If this is the default step, it's undefined.
* @returns {Function} Wrapped hook or default step.
*/
function wrapHook(index, userHookOrDefault, next) {
return function nextStep(arg0, context) {
lastRunIndex = index;
if (context && context !== mergedContext) {
ObjectAssign(mergedContext, context);
}
const hookResult = userHookOrDefault(arg0, mergedContext, next);
if (lastRunIndex > 0 && lastRunIndex === index && !hookResult.shortCircuit) {
throw new ERR_INVALID_RETURN_PROPERTY_VALUE('true', name, 'shortCircuit',
hookResult.shortCircuit);
}
return validate(arg0, mergedContext, hookResult);
};
}
const chain = [wrapHook(0, defaultStep)];
for (let i = 0; i < hooks.length; ++i) {
const wrappedHook = wrapHook(i + 1, hooks[i][name], chain[i]);
ArrayPrototypePush(chain, wrappedHook);
}
return chain[chain.length - 1];
}
/**
* @typedef {object} ModuleResolveResult
* @property {string} url Resolved URL of the module.
* @property {string|undefined} format Format of the module.
* @property {ImportAttributes|undefined} importAttributes Import attributes for the request.
* @property {boolean|undefined} shortCircuit Whether the next hook has been skipped.
*/
/**
* Validate the result returned by a chain of resolve hook.
* @param {string} specifier Specifier passed into the hooks.
* @param {ModuleResolveContext} context Context passed into the hooks.
* @param {ModuleResolveResult} result Result produced by resolve hooks.
* @returns {ModuleResolveResult}
*/
function validateResolve(specifier, context, result) {
const { url, format, importAttributes } = result;
if (typeof url !== 'string') {
throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
'a URL string',
'resolve',
'url',
url,
);
}
if (format && typeof format !== 'string') {
throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
'a string',
'resolve',
'format',
format,
);
}
if (importAttributes && typeof importAttributes !== 'object') {
throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
'an object',
'resolve',
'importAttributes',
importAttributes,
);
}
return {
__proto__: null,
url,
format,
importAttributes,
};
}
/**
* @typedef {object} ModuleLoadResult
* @property {string|undefined} format Format of the loaded module.
* @property {string|ArrayBuffer|TypedArray} source Source code of the module.
* @property {boolean|undefined} shortCircuit Whether the next hook has been skipped.
*/
/**
* Validate the result returned by a chain of resolve hook.
* @param {string} url URL passed into the hooks.
* @param {ModuleLoadContext} context Context passed into the hooks.
* @param {ModuleLoadResult} result Result produced by load hooks.
* @returns {ModuleLoadResult}
*/
function validateLoad(url, context, result) {
const { source, format } = result;
// To align with module.register(), the load hooks are still invoked for
// the builtins even though the default load step only provides null as source,
// and any source content for builtins provided by the user hooks are ignored.
if (!StringPrototypeStartsWith(url, 'node:') &&
typeof result.source !== 'string' &&
!isAnyArrayBuffer(source) &&
!isArrayBufferView(source)) {
throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
'a string, an ArrayBuffer, or a TypedArray',
'load',
'source',
source,
);
}
if (typeof format !== 'string' && format !== undefined) {
throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
'a string',
'load',
'format',
format,
);
}
return {
__proto__: null,
format,
source,
};
}
class ModuleResolveContext {
/**
* Context for the resolve hook.
* @param {string|undefined} parentURL Parent URL.
* @param {ImportAttributes|undefined} importAttributes Import attributes.
* @param {string[]} conditions Conditions.
*/
constructor(parentURL, importAttributes, conditions) {
this.parentURL = parentURL;
this.importAttributes = importAttributes;
this.conditions = conditions;
// TODO(joyeecheung): a field to differentiate between require and import?
}
};
class ModuleLoadContext {
/**
* Context for the load hook.
* @param {string|undefined} format URL.
* @param {ImportAttributes|undefined} importAttributes Import attributes.
* @param {string[]} conditions Conditions.
*/
constructor(format, importAttributes, conditions) {
this.format = format;
this.importAttributes = importAttributes;
this.conditions = conditions;
}
};
let decoder;
/**
* Load module source for a url, through a hooks chain if it exists.
* @param {string} url
* @param {string|undefined} originalFormat
* @param {ImportAttributes|undefined} importAttributes
* @param {string[]} conditions
* @param {(url: string, context: ModuleLoadContext) => ModuleLoadResult} defaultLoad
* @returns {ModuleLoadResult}
*/
function loadWithHooks(url, originalFormat, importAttributes, conditions, defaultLoad) {
debug('loadWithHooks', url, originalFormat);
const context = new ModuleLoadContext(originalFormat, importAttributes, conditions);
if (loadHooks.length === 0) {
return defaultLoad(url, context);
}
const runner = buildHooks(loadHooks, 'load', defaultLoad, validateLoad, context);
const result = runner(url, context);
const { source, format } = result;
if (!isAnyArrayBuffer(source) && !isArrayBufferView(source)) {
return result;
}
switch (format) {
// Text formats:
case undefined:
case 'module':
case 'commonjs':
case 'json':
case 'module-typescript':
case 'commonjs-typescript':
case 'typescript': {
decoder ??= new (require('internal/encoding').TextDecoder)();
result.source = decoder.decode(source);
break;
}
default:
break;
}
return result;
}
/**
* Resolve module request to a url, through a hooks chain if it exists.
* @param {string} specifier
* @param {string|undefined} parentURL
* @param {ImportAttributes|undefined} importAttributes
* @param {string[]} conditions
* @param {(specifier: string, context: ModuleResolveContext) => ModuleResolveResult} defaultResolve
* @returns {ModuleResolveResult}
*/
function resolveWithHooks(specifier, parentURL, importAttributes, conditions, defaultResolve) {
debug('resolveWithHooks', specifier, parentURL, importAttributes);
const context = new ModuleResolveContext(parentURL, importAttributes, conditions);
if (resolveHooks.length === 0) {
return defaultResolve(specifier, context);
}
const runner = buildHooks(resolveHooks, 'resolve', defaultResolve, validateResolve, context);
return runner(specifier, context);
}
module.exports = {
convertCJSFilenameToURL,
convertURLToCJSFilename,
loadHooks,
loadWithHooks,
registerHooks,
resolveHooks,
resolveWithHooks,
};