-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathwrapRequire.ts
More file actions
307 lines (263 loc) · 8.88 KB
/
wrapRequire.ts
File metadata and controls
307 lines (263 loc) · 8.88 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
/* eslint-disable max-lines-per-function */
import * as mod from "module";
import { BuiltinModule } from "./BuiltinModule";
import { isBuiltinModule } from "./isBuiltinModule";
import { getModuleInfoFromPath } from "./getModuleInfoFromPath";
import { Package } from "./Package";
import { satisfiesVersion } from "../../helpers/satisfiesVersion";
import { removeNodePrefix } from "../../helpers/removeNodePrefix";
import { RequireInterceptor } from "./RequireInterceptor";
import type { PackageJson } from "type-fest";
import { isMainJsFile } from "./isMainJsFile";
import { WrapPackageInfo } from "./WrapPackageInfo";
import { getInstance } from "../AgentSingleton";
const originalRequire = mod.prototype.require;
let isRequireWrapped = false;
let packages: Package[] = [];
let builtinModules: BuiltinModule[] = [];
let pkgCache = new Map<string, unknown>();
let builtinCache = new Map<string, unknown>();
/**
* Wraps the require function to intercept require calls.
* This function makes sure that the require function is only wrapped once.
*/
export function wrapRequire() {
if (isRequireWrapped) {
return;
}
// @ts-expect-error Not included in the Node.js types
if (typeof mod._resolveFilename !== "function") {
throw new Error(
`Could not find the _resolveFilename function in node:module using Node.js version ${process.version}`
);
}
// Prevent wrapping the require function multiple times
isRequireWrapped = true;
// @ts-expect-error TS doesn't know that we are not overwriting the subproperties
mod.prototype.require = function wrapped() {
// eslint-disable-next-line prefer-rest-params
return patchedRequire.call(this, arguments);
};
// Wrap process.getBuiltinModule, which allows requiring builtin modules (since Node.js v22.3.0)
if (typeof process.getBuiltinModule === "function") {
process.getBuiltinModule = function wrappedGetBuiltinModule() {
// eslint-disable-next-line prefer-rest-params
return patchedRequire.call(this, arguments);
};
}
}
/**
* Update the list of external packages that should be patched.
*/
export function setPackagesToPatch(packagesToPatch: Package[]) {
packages = packagesToPatch;
// Reset cache
pkgCache = new Map();
}
/**
* Update the list of builtin modules that should be patched.
*/
export function setBuiltinModulesToPatch(
builtinModulesToPatch: BuiltinModule[]
) {
builtinModules = builtinModulesToPatch;
// Reset cache
builtinCache = new Map();
}
/**
* Our custom require function that intercepts require calls.
*/
function patchedRequire(this: mod | NodeJS.Process, args: IArguments) {
// Apply the original require function
const originalExports = originalRequire.apply(
this,
args as unknown as [string]
);
if (!args.length || typeof args[0] !== "string") {
return originalExports;
}
/**
* Parameter that is passed to the require function
* Can be a module name, a relative / absolute path
*/
const id = args[0] as string;
try {
// Check if it's a builtin module
// They are easier to patch (no file patching)
// Separate handling for builtin modules improves the performance
if (isBuiltinModule(id)) {
// Call function for patching builtin modules with the same context (this)
return patchBuiltinModule.call(this, id, originalExports);
}
// Call function for patching external packages
return patchPackage.call(this as mod, id, originalExports);
} catch (error) {
if (error instanceof Error) {
getInstance()?.onFailedToWrapModule(id, error);
}
return originalExports;
}
}
/**
* Run all require interceptors for the builtin module and cache the result.
*/
function patchBuiltinModule(id: string, originalExports: unknown) {
const moduleName = removeNodePrefix(id);
// Check if already cached
if (builtinCache.has(moduleName)) {
return builtinCache.get(moduleName);
}
// Check if we want to patch this builtin module
const matchingBuiltins = builtinModules.filter(
(m) => m.getName() === moduleName
);
// We don't want to patch this builtin module
if (!matchingBuiltins.length) {
return originalExports;
}
// Get interceptors from all matching builtin modules
const interceptors = matchingBuiltins
.map((m) => m.getRequireInterceptors())
.flat();
return executeInterceptors(
interceptors,
originalExports,
builtinCache,
moduleName,
{
name: moduleName,
type: "builtin",
}
);
}
/**
* Run all require interceptors for the package and cache the result.
* Also checks the package versions. Not used for builtin modules.
*/
function patchPackage(this: mod, id: string, originalExports: unknown) {
// Get the full filepath of the required js file
// @ts-expect-error Not included in the Node.js types
const filename = mod._resolveFilename(id, this);
if (!filename) {
throw new Error("Could not resolve filename using _resolveFilename");
}
// Ignore .json files
if (filename.endsWith(".json")) {
return originalExports;
}
// Check if cache has the filename
if (pkgCache.has(filename)) {
return pkgCache.get(filename);
}
// Parses the filename to extract the module name, the base dir of the module and the relative path of the included file
const pathInfo = getModuleInfoFromPath(filename);
if (!pathInfo) {
// Can happen if the package is not inside a node_modules folder, like the dev build of our library itself
return originalExports;
}
const moduleName = pathInfo.name;
// Get all versioned packages for the module name
const versionedPackages = packages
.filter((pkg) => pkg.getName() === moduleName)
.map((pkg) => pkg.getVersions())
.flat();
// Read the package.json of the required package
const packageJson = originalRequire(
`${pathInfo.base}/package.json`
) as PackageJson;
// Get the version of the installed package
const installedPkgVersion = packageJson.version;
if (!installedPkgVersion) {
throw new Error(
`Could not get installed package version for ${moduleName}`
);
}
const agent = getInstance();
agent?.onPackageRequired(moduleName, installedPkgVersion);
// We don't want to patch this package because we do not have any hooks for it
if (!versionedPackages.length) {
return originalExports;
}
// Check if the installed package version is supported (get all matching versioned packages)
const matchingVersionedPackages = versionedPackages.filter((pkg) =>
satisfiesVersion(pkg.getRange(), installedPkgVersion)
);
// Report to the agent that the package was wrapped or not if it's version is not supported
agent?.onPackageWrapped(moduleName, {
version: installedPkgVersion,
supported: !!matchingVersionedPackages.length,
});
if (!matchingVersionedPackages.length) {
// We don't want to patch this package version
return originalExports;
}
// Check if the required file is the main file of the package or another js file inside the package
const isMainFile = isMainJsFile(pathInfo, id, filename, packageJson);
let interceptors: RequireInterceptor[] = [];
if (isMainFile) {
interceptors = matchingVersionedPackages
.map((pkg) => pkg.getRequireInterceptors())
.flat();
} else {
// If it's not the main file, we want to check if the want to patch the required file
interceptors = matchingVersionedPackages
.map((pkg) => pkg.getRequireFileInterceptor(pathInfo.path) || [])
.flat();
}
return executeInterceptors(
interceptors,
originalExports,
pkgCache,
filename as string,
{
name: pathInfo.name,
version: installedPkgVersion,
type: "external",
path: {
base: pathInfo.base,
relative: pathInfo.path,
},
}
);
}
/**
* Executes the provided require interceptor functions and sets the cache.
*/
function executeInterceptors(
interceptors: RequireInterceptor[],
exports: unknown,
cache: Map<string, unknown>,
cacheKey: string,
wrapPackageInfo: WrapPackageInfo
) {
// Cache because we need to prevent this called again if module is imported inside interceptors
cache.set(cacheKey, exports);
// Return early if no interceptors
if (!interceptors.length) {
return exports;
}
// Foreach interceptor function
for (const interceptor of interceptors) {
// If one interceptor fails, we don't want to stop the other interceptors
try {
const returnVal = interceptor(exports, wrapPackageInfo);
// If the interceptor returns a value, we want to use this value as the new exports
if (typeof returnVal !== "undefined") {
exports = returnVal;
}
} catch (error) {
if (error instanceof Error) {
getInstance()?.onFailedToWrapModule(wrapPackageInfo.name, error);
}
}
}
// Finally cache the result
cache.set(cacheKey, exports);
return exports;
}
/**
* Returns the unwrapped require function.
*/
export function getOriginalRequire() {
return originalRequire;
}