UNPKG

monaco-editor

Version:
1,064 lines (1,063 loc) • 93.2 kB
/*!----------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Version: 0.34.1(0316a754aa4c25208bef91937efbce2ab1e3ce37) * Released under the MIT license * https://github.com/microsoft/vscode/blob/main/LICENSE.txt *-----------------------------------------------------------*/ /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- * Please make sure to make edits in the .ts file at https://github.com/microsoft/vscode-loader/ *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------*/ var _amdLoaderGlobal = this; var _commonjsGlobal = typeof global === 'object' ? global : {}; var AMDLoader; (function (AMDLoader) { AMDLoader.global = _amdLoaderGlobal; var Environment = /** @class */ (function () { function Environment() { this._detected = false; this._isWindows = false; this._isNode = false; this._isElectronRenderer = false; this._isWebWorker = false; this._isElectronNodeIntegrationWebWorker = false; } Object.defineProperty(Environment.prototype, "isWindows", { get: function () { this._detect(); return this._isWindows; }, enumerable: false, configurable: true }); Object.defineProperty(Environment.prototype, "isNode", { get: function () { this._detect(); return this._isNode; }, enumerable: false, configurable: true }); Object.defineProperty(Environment.prototype, "isElectronRenderer", { get: function () { this._detect(); return this._isElectronRenderer; }, enumerable: false, configurable: true }); Object.defineProperty(Environment.prototype, "isWebWorker", { get: function () { this._detect(); return this._isWebWorker; }, enumerable: false, configurable: true }); Object.defineProperty(Environment.prototype, "isElectronNodeIntegrationWebWorker", { get: function () { this._detect(); return this._isElectronNodeIntegrationWebWorker; }, enumerable: false, configurable: true }); Environment.prototype._detect = function () { if (this._detected) { return; } this._detected = true; this._isWindows = Environment._isWindows(); this._isNode = (typeof module !== 'undefined' && !!module.exports); this._isElectronRenderer = (typeof process !== 'undefined' && typeof process.versions !== 'undefined' && typeof process.versions.electron !== 'undefined' && process.type === 'renderer'); this._isWebWorker = (typeof AMDLoader.global.importScripts === 'function'); this._isElectronNodeIntegrationWebWorker = this._isWebWorker && (typeof process !== 'undefined' && typeof process.versions !== 'undefined' && typeof process.versions.electron !== 'undefined' && process.type === 'worker'); }; Environment._isWindows = function () { if (typeof navigator !== 'undefined') { if (navigator.userAgent && navigator.userAgent.indexOf('Windows') >= 0) { return true; } } if (typeof process !== 'undefined') { return (process.platform === 'win32'); } return false; }; return Environment; }()); AMDLoader.Environment = Environment; })(AMDLoader || (AMDLoader = {})); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ var AMDLoader; (function (AMDLoader) { var LoaderEvent = /** @class */ (function () { function LoaderEvent(type, detail, timestamp) { this.type = type; this.detail = detail; this.timestamp = timestamp; } return LoaderEvent; }()); AMDLoader.LoaderEvent = LoaderEvent; var LoaderEventRecorder = /** @class */ (function () { function LoaderEventRecorder(loaderAvailableTimestamp) { this._events = [new LoaderEvent(1 /* LoaderAvailable */, '', loaderAvailableTimestamp)]; } LoaderEventRecorder.prototype.record = function (type, detail) { this._events.push(new LoaderEvent(type, detail, AMDLoader.Utilities.getHighPerformanceTimestamp())); }; LoaderEventRecorder.prototype.getEvents = function () { return this._events; }; return LoaderEventRecorder; }()); AMDLoader.LoaderEventRecorder = LoaderEventRecorder; var NullLoaderEventRecorder = /** @class */ (function () { function NullLoaderEventRecorder() { } NullLoaderEventRecorder.prototype.record = function (type, detail) { // Nothing to do }; NullLoaderEventRecorder.prototype.getEvents = function () { return []; }; NullLoaderEventRecorder.INSTANCE = new NullLoaderEventRecorder(); return NullLoaderEventRecorder; }()); AMDLoader.NullLoaderEventRecorder = NullLoaderEventRecorder; })(AMDLoader || (AMDLoader = {})); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ var AMDLoader; (function (AMDLoader) { var Utilities = /** @class */ (function () { function Utilities() { } /** * This method does not take care of / vs \ */ Utilities.fileUriToFilePath = function (isWindows, uri) { uri = decodeURI(uri).replace(/%23/g, '#'); if (isWindows) { if (/^file:\/\/\//.test(uri)) { // This is a URI without a hostname => return only the path segment return uri.substr(8); } if (/^file:\/\//.test(uri)) { return uri.substr(5); } } else { if (/^file:\/\//.test(uri)) { return uri.substr(7); } } // Not sure... return uri; }; Utilities.startsWith = function (haystack, needle) { return haystack.length >= needle.length && haystack.substr(0, needle.length) === needle; }; Utilities.endsWith = function (haystack, needle) { return haystack.length >= needle.length && haystack.substr(haystack.length - needle.length) === needle; }; // only check for "?" before "#" to ensure that there is a real Query-String Utilities.containsQueryString = function (url) { return /^[^\#]*\?/gi.test(url); }; /** * Does `url` start with http:// or https:// or file:// or / ? */ Utilities.isAbsolutePath = function (url) { return /^((http:\/\/)|(https:\/\/)|(file:\/\/)|(\/))/.test(url); }; Utilities.forEachProperty = function (obj, callback) { if (obj) { var key = void 0; for (key in obj) { if (obj.hasOwnProperty(key)) { callback(key, obj[key]); } } } }; Utilities.isEmpty = function (obj) { var isEmpty = true; Utilities.forEachProperty(obj, function () { isEmpty = false; }); return isEmpty; }; Utilities.recursiveClone = function (obj) { if (!obj || typeof obj !== 'object' || obj instanceof RegExp) { return obj; } if (!Array.isArray(obj) && Object.getPrototypeOf(obj) !== Object.prototype) { // only clone "simple" objects return obj; } var result = Array.isArray(obj) ? [] : {}; Utilities.forEachProperty(obj, function (key, value) { if (value && typeof value === 'object') { result[key] = Utilities.recursiveClone(value); } else { result[key] = value; } }); return result; }; Utilities.generateAnonymousModule = function () { return '===anonymous' + (Utilities.NEXT_ANONYMOUS_ID++) + '==='; }; Utilities.isAnonymousModule = function (id) { return Utilities.startsWith(id, '===anonymous'); }; Utilities.getHighPerformanceTimestamp = function () { if (!this.PERFORMANCE_NOW_PROBED) { this.PERFORMANCE_NOW_PROBED = true; this.HAS_PERFORMANCE_NOW = (AMDLoader.global.performance && typeof AMDLoader.global.performance.now === 'function'); } return (this.HAS_PERFORMANCE_NOW ? AMDLoader.global.performance.now() : Date.now()); }; Utilities.NEXT_ANONYMOUS_ID = 1; Utilities.PERFORMANCE_NOW_PROBED = false; Utilities.HAS_PERFORMANCE_NOW = false; return Utilities; }()); AMDLoader.Utilities = Utilities; })(AMDLoader || (AMDLoader = {})); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ var AMDLoader; (function (AMDLoader) { function ensureError(err) { if (err instanceof Error) { return err; } var result = new Error(err.message || String(err) || 'Unknown Error'); if (err.stack) { result.stack = err.stack; } return result; } AMDLoader.ensureError = ensureError; ; var ConfigurationOptionsUtil = /** @class */ (function () { function ConfigurationOptionsUtil() { } /** * Ensure configuration options make sense */ ConfigurationOptionsUtil.validateConfigurationOptions = function (options) { function defaultOnError(err) { if (err.phase === 'loading') { console.error('Loading "' + err.moduleId + '" failed'); console.error(err); console.error('Here are the modules that depend on it:'); console.error(err.neededBy); return; } if (err.phase === 'factory') { console.error('The factory function of "' + err.moduleId + '" has thrown an exception'); console.error(err); console.error('Here are the modules that depend on it:'); console.error(err.neededBy); return; } } options = options || {}; if (typeof options.baseUrl !== 'string') { options.baseUrl = ''; } if (typeof options.isBuild !== 'boolean') { options.isBuild = false; } if (typeof options.buildForceInvokeFactory !== 'object') { options.buildForceInvokeFactory = {}; } if (typeof options.paths !== 'object') { options.paths = {}; } if (typeof options.config !== 'object') { options.config = {}; } if (typeof options.catchError === 'undefined') { options.catchError = false; } if (typeof options.recordStats === 'undefined') { options.recordStats = false; } if (typeof options.urlArgs !== 'string') { options.urlArgs = ''; } if (typeof options.onError !== 'function') { options.onError = defaultOnError; } if (!Array.isArray(options.ignoreDuplicateModules)) { options.ignoreDuplicateModules = []; } if (options.baseUrl.length > 0) { if (!AMDLoader.Utilities.endsWith(options.baseUrl, '/')) { options.baseUrl += '/'; } } if (typeof options.cspNonce !== 'string') { options.cspNonce = ''; } if (typeof options.preferScriptTags === 'undefined') { options.preferScriptTags = false; } if (!Array.isArray(options.nodeModules)) { options.nodeModules = []; } if (options.nodeCachedData && typeof options.nodeCachedData === 'object') { if (typeof options.nodeCachedData.seed !== 'string') { options.nodeCachedData.seed = 'seed'; } if (typeof options.nodeCachedData.writeDelay !== 'number' || options.nodeCachedData.writeDelay < 0) { options.nodeCachedData.writeDelay = 1000 * 7; } if (!options.nodeCachedData.path || typeof options.nodeCachedData.path !== 'string') { var err = ensureError(new Error('INVALID cached data configuration, \'path\' MUST be set')); err.phase = 'configuration'; options.onError(err); options.nodeCachedData = undefined; } } return options; }; ConfigurationOptionsUtil.mergeConfigurationOptions = function (overwrite, base) { if (overwrite === void 0) { overwrite = null; } if (base === void 0) { base = null; } var result = AMDLoader.Utilities.recursiveClone(base || {}); // Merge known properties and overwrite the unknown ones AMDLoader.Utilities.forEachProperty(overwrite, function (key, value) { if (key === 'ignoreDuplicateModules' && typeof result.ignoreDuplicateModules !== 'undefined') { result.ignoreDuplicateModules = result.ignoreDuplicateModules.concat(value); } else if (key === 'paths' && typeof result.paths !== 'undefined') { AMDLoader.Utilities.forEachProperty(value, function (key2, value2) { return result.paths[key2] = value2; }); } else if (key === 'config' && typeof result.config !== 'undefined') { AMDLoader.Utilities.forEachProperty(value, function (key2, value2) { return result.config[key2] = value2; }); } else { result[key] = AMDLoader.Utilities.recursiveClone(value); } }); return ConfigurationOptionsUtil.validateConfigurationOptions(result); }; return ConfigurationOptionsUtil; }()); AMDLoader.ConfigurationOptionsUtil = ConfigurationOptionsUtil; var Configuration = /** @class */ (function () { function Configuration(env, options) { this._env = env; this.options = ConfigurationOptionsUtil.mergeConfigurationOptions(options); this._createIgnoreDuplicateModulesMap(); this._createNodeModulesMap(); this._createSortedPathsRules(); if (this.options.baseUrl === '') { if (this.options.nodeRequire && this.options.nodeRequire.main && this.options.nodeRequire.main.filename && this._env.isNode) { var nodeMain = this.options.nodeRequire.main.filename; var dirnameIndex = Math.max(nodeMain.lastIndexOf('/'), nodeMain.lastIndexOf('\\')); this.options.baseUrl = nodeMain.substring(0, dirnameIndex + 1); } if (this.options.nodeMain && this._env.isNode) { var nodeMain = this.options.nodeMain; var dirnameIndex = Math.max(nodeMain.lastIndexOf('/'), nodeMain.lastIndexOf('\\')); this.options.baseUrl = nodeMain.substring(0, dirnameIndex + 1); } } } Configuration.prototype._createIgnoreDuplicateModulesMap = function () { // Build a map out of the ignoreDuplicateModules array this.ignoreDuplicateModulesMap = {}; for (var i = 0; i < this.options.ignoreDuplicateModules.length; i++) { this.ignoreDuplicateModulesMap[this.options.ignoreDuplicateModules[i]] = true; } }; Configuration.prototype._createNodeModulesMap = function () { // Build a map out of nodeModules array this.nodeModulesMap = Object.create(null); for (var _i = 0, _a = this.options.nodeModules; _i < _a.length; _i++) { var nodeModule = _a[_i]; this.nodeModulesMap[nodeModule] = true; } }; Configuration.prototype._createSortedPathsRules = function () { var _this = this; // Create an array our of the paths rules, sorted descending by length to // result in a more specific -> less specific order this.sortedPathsRules = []; AMDLoader.Utilities.forEachProperty(this.options.paths, function (from, to) { if (!Array.isArray(to)) { _this.sortedPathsRules.push({ from: from, to: [to] }); } else { _this.sortedPathsRules.push({ from: from, to: to }); } }); this.sortedPathsRules.sort(function (a, b) { return b.from.length - a.from.length; }); }; /** * Clone current configuration and overwrite options selectively. * @param options The selective options to overwrite with. * @result A new configuration */ Configuration.prototype.cloneAndMerge = function (options) { return new Configuration(this._env, ConfigurationOptionsUtil.mergeConfigurationOptions(options, this.options)); }; /** * Get current options bag. Useful for passing it forward to plugins. */ Configuration.prototype.getOptionsLiteral = function () { return this.options; }; Configuration.prototype._applyPaths = function (moduleId) { var pathRule; for (var i = 0, len = this.sortedPathsRules.length; i < len; i++) { pathRule = this.sortedPathsRules[i]; if (AMDLoader.Utilities.startsWith(moduleId, pathRule.from)) { var result = []; for (var j = 0, lenJ = pathRule.to.length; j < lenJ; j++) { result.push(pathRule.to[j] + moduleId.substr(pathRule.from.length)); } return result; } } return [moduleId]; }; Configuration.prototype._addUrlArgsToUrl = function (url) { if (AMDLoader.Utilities.containsQueryString(url)) { return url + '&' + this.options.urlArgs; } else { return url + '?' + this.options.urlArgs; } }; Configuration.prototype._addUrlArgsIfNecessaryToUrl = function (url) { if (this.options.urlArgs) { return this._addUrlArgsToUrl(url); } return url; }; Configuration.prototype._addUrlArgsIfNecessaryToUrls = function (urls) { if (this.options.urlArgs) { for (var i = 0, len = urls.length; i < len; i++) { urls[i] = this._addUrlArgsToUrl(urls[i]); } } return urls; }; /** * Transform a module id to a location. Appends .js to module ids */ Configuration.prototype.moduleIdToPaths = function (moduleId) { if (this._env.isNode) { var isNodeModule = ((this.nodeModulesMap[moduleId] === true) || (this.options.amdModulesPattern instanceof RegExp && !this.options.amdModulesPattern.test(moduleId))); if (isNodeModule) { // This is a node module... if (this.isBuild()) { // ...and we are at build time, drop it return ['empty:']; } else { // ...and at runtime we create a `shortcut`-path return ['node|' + moduleId]; } } } var result = moduleId; var results; if (!AMDLoader.Utilities.endsWith(result, '.js') && !AMDLoader.Utilities.isAbsolutePath(result)) { results = this._applyPaths(result); for (var i = 0, len = results.length; i < len; i++) { if (this.isBuild() && results[i] === 'empty:') { continue; } if (!AMDLoader.Utilities.isAbsolutePath(results[i])) { results[i] = this.options.baseUrl + results[i]; } if (!AMDLoader.Utilities.endsWith(results[i], '.js') && !AMDLoader.Utilities.containsQueryString(results[i])) { results[i] = results[i] + '.js'; } } } else { if (!AMDLoader.Utilities.endsWith(result, '.js') && !AMDLoader.Utilities.containsQueryString(result)) { result = result + '.js'; } results = [result]; } return this._addUrlArgsIfNecessaryToUrls(results); }; /** * Transform a module id or url to a location. */ Configuration.prototype.requireToUrl = function (url) { var result = url; if (!AMDLoader.Utilities.isAbsolutePath(result)) { result = this._applyPaths(result)[0]; if (!AMDLoader.Utilities.isAbsolutePath(result)) { result = this.options.baseUrl + result; } } return this._addUrlArgsIfNecessaryToUrl(result); }; /** * Flag to indicate if current execution is as part of a build. */ Configuration.prototype.isBuild = function () { return this.options.isBuild; }; Configuration.prototype.shouldInvokeFactory = function (strModuleId) { if (!this.options.isBuild) { // outside of a build, all factories should be invoked return true; } // during a build, only explicitly marked or anonymous modules get their factories invoked return (this.options.buildForceInvokeFactory[strModuleId] || AMDLoader.Utilities.isAnonymousModule(strModuleId)); }; /** * Test if module `moduleId` is expected to be defined multiple times */ Configuration.prototype.isDuplicateMessageIgnoredFor = function (moduleId) { return this.ignoreDuplicateModulesMap.hasOwnProperty(moduleId); }; /** * Get the configuration settings for the provided module id */ Configuration.prototype.getConfigForModule = function (moduleId) { if (this.options.config) { return this.options.config[moduleId]; } }; /** * Should errors be caught when executing module factories? */ Configuration.prototype.shouldCatchError = function () { return this.options.catchError; }; /** * Should statistics be recorded? */ Configuration.prototype.shouldRecordStats = function () { return this.options.recordStats; }; /** * Forward an error to the error handler. */ Configuration.prototype.onError = function (err) { this.options.onError(err); }; return Configuration; }()); AMDLoader.Configuration = Configuration; })(AMDLoader || (AMDLoader = {})); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ var AMDLoader; (function (AMDLoader) { /** * Load `scriptSrc` only once (avoid multiple <script> tags) */ var OnlyOnceScriptLoader = /** @class */ (function () { function OnlyOnceScriptLoader(env) { this._env = env; this._scriptLoader = null; this._callbackMap = {}; } OnlyOnceScriptLoader.prototype.load = function (moduleManager, scriptSrc, callback, errorback) { var _this = this; if (!this._scriptLoader) { if (this._env.isWebWorker) { this._scriptLoader = new WorkerScriptLoader(); } else if (this._env.isElectronRenderer) { var preferScriptTags = moduleManager.getConfig().getOptionsLiteral().preferScriptTags; if (preferScriptTags) { this._scriptLoader = new BrowserScriptLoader(); } else { this._scriptLoader = new NodeScriptLoader(this._env); } } else if (this._env.isNode) { this._scriptLoader = new NodeScriptLoader(this._env); } else { this._scriptLoader = new BrowserScriptLoader(); } } var scriptCallbacks = { callback: callback, errorback: errorback }; if (this._callbackMap.hasOwnProperty(scriptSrc)) { this._callbackMap[scriptSrc].push(scriptCallbacks); return; } this._callbackMap[scriptSrc] = [scriptCallbacks]; this._scriptLoader.load(moduleManager, scriptSrc, function () { return _this.triggerCallback(scriptSrc); }, function (err) { return _this.triggerErrorback(scriptSrc, err); }); }; OnlyOnceScriptLoader.prototype.triggerCallback = function (scriptSrc) { var scriptCallbacks = this._callbackMap[scriptSrc]; delete this._callbackMap[scriptSrc]; for (var i = 0; i < scriptCallbacks.length; i++) { scriptCallbacks[i].callback(); } }; OnlyOnceScriptLoader.prototype.triggerErrorback = function (scriptSrc, err) { var scriptCallbacks = this._callbackMap[scriptSrc]; delete this._callbackMap[scriptSrc]; for (var i = 0; i < scriptCallbacks.length; i++) { scriptCallbacks[i].errorback(err); } }; return OnlyOnceScriptLoader; }()); var BrowserScriptLoader = /** @class */ (function () { function BrowserScriptLoader() { } /** * Attach load / error listeners to a script element and remove them when either one has fired. * Implemented for browsers supporting HTML5 standard 'load' and 'error' events. */ BrowserScriptLoader.prototype.attachListeners = function (script, callback, errorback) { var unbind = function () { script.removeEventListener('load', loadEventListener); script.removeEventListener('error', errorEventListener); }; var loadEventListener = function (e) { unbind(); callback(); }; var errorEventListener = function (e) { unbind(); errorback(e); }; script.addEventListener('load', loadEventListener); script.addEventListener('error', errorEventListener); }; BrowserScriptLoader.prototype.load = function (moduleManager, scriptSrc, callback, errorback) { if (/^node\|/.test(scriptSrc)) { var opts = moduleManager.getConfig().getOptionsLiteral(); var nodeRequire = ensureRecordedNodeRequire(moduleManager.getRecorder(), (opts.nodeRequire || AMDLoader.global.nodeRequire)); var pieces = scriptSrc.split('|'); var moduleExports_1 = null; try { moduleExports_1 = nodeRequire(pieces[1]); } catch (err) { errorback(err); return; } moduleManager.enqueueDefineAnonymousModule([], function () { return moduleExports_1; }); callback(); } else { var script = document.createElement('script'); script.setAttribute('async', 'async'); script.setAttribute('type', 'text/javascript'); this.attachListeners(script, callback, errorback); var trustedTypesPolicy = moduleManager.getConfig().getOptionsLiteral().trustedTypesPolicy; if (trustedTypesPolicy) { scriptSrc = trustedTypesPolicy.createScriptURL(scriptSrc); } script.setAttribute('src', scriptSrc); // Propagate CSP nonce to dynamically created script tag. var cspNonce = moduleManager.getConfig().getOptionsLiteral().cspNonce; if (cspNonce) { script.setAttribute('nonce', cspNonce); } document.getElementsByTagName('head')[0].appendChild(script); } }; return BrowserScriptLoader; }()); function canUseEval(moduleManager) { var trustedTypesPolicy = moduleManager.getConfig().getOptionsLiteral().trustedTypesPolicy; try { var func = (trustedTypesPolicy ? self.eval(trustedTypesPolicy.createScript('', 'true')) : new Function('true')); func.call(self); return true; } catch (err) { return false; } } var WorkerScriptLoader = /** @class */ (function () { function WorkerScriptLoader() { this._cachedCanUseEval = null; } WorkerScriptLoader.prototype._canUseEval = function (moduleManager) { if (this._cachedCanUseEval === null) { this._cachedCanUseEval = canUseEval(moduleManager); } return this._cachedCanUseEval; }; WorkerScriptLoader.prototype.load = function (moduleManager, scriptSrc, callback, errorback) { if (/^node\|/.test(scriptSrc)) { var opts = moduleManager.getConfig().getOptionsLiteral(); var nodeRequire = ensureRecordedNodeRequire(moduleManager.getRecorder(), (opts.nodeRequire || AMDLoader.global.nodeRequire)); var pieces = scriptSrc.split('|'); var moduleExports_2 = null; try { moduleExports_2 = nodeRequire(pieces[1]); } catch (err) { errorback(err); return; } moduleManager.enqueueDefineAnonymousModule([], function () { return moduleExports_2; }); callback(); } else { var trustedTypesPolicy_1 = moduleManager.getConfig().getOptionsLiteral().trustedTypesPolicy; var isCrossOrigin = (/^((http:)|(https:)|(file:))/.test(scriptSrc) && scriptSrc.substring(0, self.origin.length) !== self.origin); if (!isCrossOrigin && this._canUseEval(moduleManager)) { // use `fetch` if possible because `importScripts` // is synchronous and can lead to deadlocks on Safari fetch(scriptSrc).then(function (response) { if (response.status !== 200) { throw new Error(response.statusText); } return response.text(); }).then(function (text) { text = text + "\n//# sourceURL=" + scriptSrc; var func = (trustedTypesPolicy_1 ? self.eval(trustedTypesPolicy_1.createScript('', text)) : new Function(text)); func.call(self); callback(); }).then(undefined, errorback); return; } try { if (trustedTypesPolicy_1) { scriptSrc = trustedTypesPolicy_1.createScriptURL(scriptSrc); } importScripts(scriptSrc); callback(); } catch (e) { errorback(e); } } }; return WorkerScriptLoader; }()); var NodeScriptLoader = /** @class */ (function () { function NodeScriptLoader(env) { this._env = env; this._didInitialize = false; this._didPatchNodeRequire = false; } NodeScriptLoader.prototype._init = function (nodeRequire) { if (this._didInitialize) { return; } this._didInitialize = true; // capture node modules this._fs = nodeRequire('fs'); this._vm = nodeRequire('vm'); this._path = nodeRequire('path'); this._crypto = nodeRequire('crypto'); }; // patch require-function of nodejs such that we can manually create a script // from cached data. this is done by overriding the `Module._compile` function NodeScriptLoader.prototype._initNodeRequire = function (nodeRequire, moduleManager) { // It is important to check for `nodeCachedData` first and then set `_didPatchNodeRequire`. // That's because `nodeCachedData` is set _after_ calling this for the first time... var nodeCachedData = moduleManager.getConfig().getOptionsLiteral().nodeCachedData; if (!nodeCachedData) { return; } if (this._didPatchNodeRequire) { return; } this._didPatchNodeRequire = true; var that = this; var Module = nodeRequire('module'); function makeRequireFunction(mod) { var Module = mod.constructor; var require = function require(path) { try { return mod.require(path); } finally { // nothing } }; require.resolve = function resolve(request, options) { return Module._resolveFilename(request, mod, false, options); }; require.resolve.paths = function paths(request) { return Module._resolveLookupPaths(request, mod); }; require.main = process.mainModule; require.extensions = Module._extensions; require.cache = Module._cache; return require; } Module.prototype._compile = function (content, filename) { // remove shebang and create wrapper function var scriptSource = Module.wrap(content.replace(/^#!.*/, '')); // create script var recorder = moduleManager.getRecorder(); var cachedDataPath = that._getCachedDataPath(nodeCachedData, filename); var options = { filename: filename }; var hashData; try { var data = that._fs.readFileSync(cachedDataPath); hashData = data.slice(0, 16); options.cachedData = data.slice(16); recorder.record(60 /* CachedDataFound */, cachedDataPath); } catch (_e) { recorder.record(61 /* CachedDataMissed */, cachedDataPath); } var script = new that._vm.Script(scriptSource, options); var compileWrapper = script.runInThisContext(options); // run script var dirname = that._path.dirname(filename); var require = makeRequireFunction(this); var args = [this.exports, require, this, filename, dirname, process, _commonjsGlobal, Buffer]; var result = compileWrapper.apply(this.exports, args); // cached data aftermath that._handleCachedData(script, scriptSource, cachedDataPath, !options.cachedData, moduleManager); that._verifyCachedData(script, scriptSource, cachedDataPath, hashData, moduleManager); return result; }; }; NodeScriptLoader.prototype.load = function (moduleManager, scriptSrc, callback, errorback) { var _this = this; var opts = moduleManager.getConfig().getOptionsLiteral(); var nodeRequire = ensureRecordedNodeRequire(moduleManager.getRecorder(), (opts.nodeRequire || AMDLoader.global.nodeRequire)); var nodeInstrumenter = (opts.nodeInstrumenter || function (c) { return c; }); this._init(nodeRequire); this._initNodeRequire(nodeRequire, moduleManager); var recorder = moduleManager.getRecorder(); if (/^node\|/.test(scriptSrc)) { var pieces = scriptSrc.split('|'); var moduleExports_3 = null; try { moduleExports_3 = nodeRequire(pieces[1]); } catch (err) { errorback(err); return; } moduleManager.enqueueDefineAnonymousModule([], function () { return moduleExports_3; }); callback(); } else { scriptSrc = AMDLoader.Utilities.fileUriToFilePath(this._env.isWindows, scriptSrc); var normalizedScriptSrc_1 = this._path.normalize(scriptSrc); var vmScriptPathOrUri_1 = this._getElectronRendererScriptPathOrUri(normalizedScriptSrc_1); var wantsCachedData_1 = Boolean(opts.nodeCachedData); var cachedDataPath_1 = wantsCachedData_1 ? this._getCachedDataPath(opts.nodeCachedData, scriptSrc) : undefined; this._readSourceAndCachedData(normalizedScriptSrc_1, cachedDataPath_1, recorder, function (err, data, cachedData, hashData) { if (err) { errorback(err); return; } var scriptSource; if (data.charCodeAt(0) === NodeScriptLoader._BOM) { scriptSource = NodeScriptLoader._PREFIX + data.substring(1) + NodeScriptLoader._SUFFIX; } else { scriptSource = NodeScriptLoader._PREFIX + data + NodeScriptLoader._SUFFIX; } scriptSource = nodeInstrumenter(scriptSource, normalizedScriptSrc_1); var scriptOpts = { filename: vmScriptPathOrUri_1, cachedData: cachedData }; var script = _this._createAndEvalScript(moduleManager, scriptSource, scriptOpts, callback, errorback); _this._handleCachedData(script, scriptSource, cachedDataPath_1, wantsCachedData_1 && !cachedData, moduleManager); _this._verifyCachedData(script, scriptSource, cachedDataPath_1, hashData, moduleManager); }); } }; NodeScriptLoader.prototype._createAndEvalScript = function (moduleManager, contents, options, callback, errorback) { var recorder = moduleManager.getRecorder(); recorder.record(31 /* NodeBeginEvaluatingScript */, options.filename); var script = new this._vm.Script(contents, options); var ret = script.runInThisContext(options); var globalDefineFunc = moduleManager.getGlobalAMDDefineFunc(); var receivedDefineCall = false; var localDefineFunc = function () { receivedDefineCall = true; return globalDefineFunc.apply(null, arguments); }; localDefineFunc.amd = globalDefineFunc.amd; ret.call(AMDLoader.global, moduleManager.getGlobalAMDRequireFunc(), localDefineFunc, options.filename, this._path.dirname(options.filename)); recorder.record(32 /* NodeEndEvaluatingScript */, options.filename); if (receivedDefineCall) { callback(); } else { errorback(new Error("Didn't receive define call in " + options.filename + "!")); } return script; }; NodeScriptLoader.prototype._getElectronRendererScriptPathOrUri = function (path) { if (!this._env.isElectronRenderer) { return path; } var driveLetterMatch = path.match(/^([a-z])\:(.*)/i); if (driveLetterMatch) { // windows return "file:///" + (driveLetterMatch[1].toUpperCase() + ':' + driveLetterMatch[2]).replace(/\\/g, '/'); } else { // nix return "file://" + path; } }; NodeScriptLoader.prototype._getCachedDataPath = function (config, filename) { var hash = this._crypto.createHash('md5').update(filename, 'utf8').update(config.seed, 'utf8').update(process.arch, '').digest('hex'); var basename = this._path.basename(filename).replace(/\.js$/, ''); return this._path.join(config.path, basename + "-" + hash + ".code"); }; NodeScriptLoader.prototype._handleCachedData = function (script, scriptSource, cachedDataPath, createCachedData, moduleManager) { var _this = this; if (script.cachedDataRejected) { // cached data got rejected -> delete and re-create this._fs.unlink(cachedDataPath, function (err) { moduleManager.getRecorder().record(62 /* CachedDataRejected */, cachedDataPath); _this._createAndWriteCachedData(script, scriptSource, cachedDataPath, moduleManager); if (err) { moduleManager.getConfig().onError(err); } }); } else if (createCachedData) { // no cached data, but wanted this._createAndWriteCachedData(script, scriptSource, cachedDataPath, moduleManager); } }; // Cached data format: | SOURCE_HASH | V8_CACHED_DATA | // -SOURCE_HASH is the md5 hash of the JS source (always 16 bytes) // -V8_CACHED_DATA is what v8 produces NodeScriptLoader.prototype._createAndWriteCachedData = function (script, scriptSource, cachedDataPath, moduleManager) { var _this = this; var timeout = Math.ceil(moduleManager.getConfig().getOptionsLiteral().nodeCachedData.writeDelay * (1 + Math.random())); var lastSize = -1; var iteration = 0; var hashData = undefined; var createLoop = function () { setTimeout(function () { if (!hashData) { hashData = _this._crypto.createHash('md5').update(scriptSource, 'utf8').digest(); } var cachedData = script.createCachedData(); if (cachedData.length === 0 || cachedData.length === lastSize || iteration >= 5) { // done return; } if (cachedData.length < lastSize) { // less data than before: skip, try again next round createLoop(); return; } lastSize = cachedData.length; _this._fs.writeFile(cachedDataPath, Buffer.concat([hashData, cachedData]), function (err) { if (err) { moduleManager.getConfig().onError(err); } moduleManager.getRecorder().record(63 /* CachedDataCreated */, cachedDataPath); createLoop(); }); }, timeout * (Math.pow(4, iteration++))); }; // with some delay (`timeout`) create cached data // and repeat that (with backoff delay) until the // data seems to be not changing anymore createLoop(); }; NodeScriptLoader.prototype._readSourceAndCachedData = function (sourcePath, cachedDataPath, recorder, callback) { if (!cachedDataPath) { // no cached data case this._fs.readFile(sourcePath, { encoding: 'utf8' }, callback); } else { // cached data case: read both files in parallel var source_1 = undefined; var cachedData_1 = undefined; var hashData_1 = undefined; var steps_1 = 2; var step_1 = function (err) { if (err) { callback(err); } else if (--steps_1 === 0) { callback(undefined, source_1, cachedData_1, hashData_1); } }; this._fs.readFile(sourcePath, { encoding: 'utf8' }, function (err, data) { source_1 = data; step_1(err); }); this._fs.readFile(cachedDataPath, function (err, data) { if (!err && data && data.length > 0) { hashData_1 = data.slice(0, 16); cachedData_1 = data.slice(16); recorder.record(60 /* CachedDataFound */, cachedDataPath); } else { recorder.record(61 /* CachedDataMissed */, cachedDataPath); } step_1(); // ignored: cached data is optional }); } }; NodeScriptLoader.prototype._verifyCachedData = function (script, scriptSource, cachedDataPath, hashData, moduleManager) { var _this = this; if (!hashData) { // nothing to do return; } if (script.cachedDataRejected) { // invalid anyways return; } setTimeo