UNPKG

2.87 kBJavaScriptView Raw
1"use strict";
2// Copyright (c) Microsoft Corporation. All rights reserved.
3// Licensed under the MIT license. See LICENSE file in the project root for details.
4Object.defineProperty(exports, "__esModule", { value: true });
5exports.makePatchingRequire = void 0;
6var path = require("path");
7var semver = require("semver");
8/* tslint:disable-next-line:no-var-requires */
9var moduleModule = require("module");
10var nativeModules = Object.keys(process.binding("natives"));
11var originalRequire = moduleModule.prototype.require;
12function makePatchingRequire(knownPatches) {
13 var patchedModules = {};
14 return function patchedRequire(moduleId) {
15 var originalModule = originalRequire.apply(this, arguments);
16 if (knownPatches[moduleId]) {
17 // Fetch the specific path of the module
18 var modulePath = moduleModule._resolveFilename(moduleId, this);
19 if (patchedModules.hasOwnProperty(modulePath)) {
20 // This module has already been patched, no need to reapply
21 return patchedModules[modulePath];
22 }
23 var moduleVersion = void 0;
24 if (nativeModules.indexOf(moduleId) < 0) {
25 try {
26 moduleVersion = originalRequire.call(this, path.join(moduleId, "package.json")).version;
27 }
28 catch (e) {
29 // This should only happen if moduleId is actually a path rather than a module
30 // This is not a supported scenario
31 return originalModule;
32 }
33 }
34 else {
35 // This module is implemented natively so we cannot find a package.json
36 // Instead, take the version of node itself
37 moduleVersion = process.version.substring(1);
38 }
39 var prereleaseTagIndex = moduleVersion.indexOf("-");
40 if (prereleaseTagIndex >= 0) {
41 // We ignore prerelease tags to avoid impossible to fix gaps in support
42 // e.g. supporting console in >= 4.0.0 would otherwise not include
43 // 8.0.0-pre
44 moduleVersion = moduleVersion.substring(0, prereleaseTagIndex);
45 }
46 var modifiedModule = originalModule;
47 for (var _i = 0, _a = knownPatches[moduleId]; _i < _a.length; _i++) {
48 var modulePatcher = _a[_i];
49 if (semver.satisfies(moduleVersion, modulePatcher.versionSpecifier)) {
50 modifiedModule = modulePatcher.patch(modifiedModule, modulePath);
51 }
52 }
53 return patchedModules[modulePath] = modifiedModule;
54 }
55 return originalModule;
56 };
57}
58exports.makePatchingRequire = makePatchingRequire;
59//# sourceMappingURL=patchRequire.js.map
\No newline at end of file