UNPKG

@liferay/amd-loader

Version:
1,393 lines (1,122 loc) 77.9 kB
/******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ "./src/loader/config.js": /*!******************************!*\ !*** ./src/loader/config.js ***! \******************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ Config) /* harmony export */ }); /* harmony import */ var _module__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./module */ "./src/loader/module.js"); function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * SPDX-FileCopyrightText: © 2014 Liferay, Inc. <https://liferay.com> * SPDX-License-Identifier: LGPL-3.0-or-later */ /** * */ var Config = /*#__PURE__*/function () { /** * Creates an instance of Configuration class * @constructor * @param {object=} cfg configuration properties */ function Config() { var cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Config); this._modules = {}; this._maps = {}; this._paths = {}; this._config = { maps: {}, paths: {} }; this._parse(cfg, 'defaultURLParams', {}); this._parse(cfg, 'explainResolutions', false); this._parse(cfg, 'showWarnings', false); this._parse(cfg, 'waitTimeout', 7000); this._parse(cfg, 'basePath', '/'); this._parse(cfg, 'resolvePath', '/o/js_resolve_modules'); this._parse(cfg, 'combine', false); this._parse(cfg, 'nonce', ''); this._parse(cfg, 'url', ''); this._parse(cfg, 'urlMaxLength', 2000); this._parse(cfg, 'logLevel', 'error'); this._parse(cfg, 'moduleType', 'module'); } /** * Whether to explain how require() calls are resolved */ _createClass(Config, [{ key: "explainResolutions", get: function get() { return this._config.explainResolutions; } /** * Whether to show development warnings */ }, { key: "showWarnings", get: function get() { return this._config.showWarnings; } /** * Time to wait for module script requests to load (in milliseconds) */ }, { key: "waitTimeout", get: function get() { return this._config.waitTimeout; } /** * The base path from where modules must be retrieved */ }, { key: "basePath", get: function get() { return this._config.basePath; } /** * The path to use when calling the server to resolve module dependencies */ }, { key: "resolvePath", get: function get() { return this._config.resolvePath; } /** * Whether to combine module requests into combo URLs */ }, { key: "combine", get: function get() { return this._config.combine; } /** * The URL of the server */ }, { key: "url", get: function get() { return this._config.url; } /** * The maximum length of a combo URL. If URL is larger than that it is split * in as many requests as needed. */ }, { key: "urlMaxLength", get: function get() { return this._config.urlMaxLength; } }, { key: "logLevel", get: function get() { return this._config.logLevel; } /** * The type to use for ESM <script> nodes. */ }, { key: "moduleType", get: function get() { return this._config.moduleType; } /** * Default parameters to add to the module request URLs */ }, { key: "defaultURLParams", get: function get() { return this._config.defaultURLParams; } /** * An object with registered module paths */ }, { key: "paths", get: function get() { return this._paths; } }, { key: "nonce", get: function get() { return this._config.nonce; } /** * Adds a module to the configuration with default field values if it * doesn't exist. Otherwise, throws an exception. * @param {string} moduleName * @param {object} moduleProperties initial properties to set on module in * addition to its name * @return {Object} the module */ }, { key: "addModule", value: function addModule(moduleName) { var moduleProperties = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (this._modules[moduleName]) { throw new Error("Module is already registered: ".concat(moduleName)); } var module = new _module__WEBPACK_IMPORTED_MODULE_0__.default(moduleName); Object.entries(moduleProperties).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), key = _ref2[0], value = _ref2[1]; module[key] = value; }); this._modules[moduleName] = module; return module; } /** * Add mappings to the current configuration * @param {object} mappings an object with one or more mappings */ }, { key: "addMappings", value: function addMappings(mappings) { Object.assign(this._maps, mappings); } /** * Add path mappings to the current configuration * @param {object} paths an object with one or more path mappings */ }, { key: "addPaths", value: function addPaths(paths) { Object.assign(this._paths, paths); } /** * Returns array with all registered modules or the requested subset of * them. * @param {?Array} moduleNames optional list of module names to retrieve * @return {Array} */ }, { key: "getModules", value: function getModules() { var _this = this; var moduleNames = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; if (moduleNames === undefined) { return Object.values(this._modules); } return moduleNames.map(function (moduleName) { return _this.getModule(moduleName); }); } /** * Returns the registered module for the moduleName. * @param {string} moduleName the module name * @return {Object} the registed module object */ }, { key: "getModule", value: function getModule(moduleName) { var module = this._modules[moduleName]; if (!module) { var mappedName = this._mapModule(moduleName); module = this._modules[mappedName]; } return module; } /** * Returns the registered module for the dependency of moduleName. * @param {string} moduleName the module name * @param {string} dependencyName the dependencyName name * @return {Object} the registed module object */ }, { key: "getDependency", value: function getDependency(moduleName, dependencyName) { var module = this.getModule(moduleName); var dependencyModule = this._modules[dependencyName]; if (!dependencyModule) { var mappedName = this._mapModule(dependencyName, module.map); dependencyModule = this._modules[mappedName]; } return dependencyModule; } /** * Update the resolve path (usually as a consequence of a redirect being * received from the server when a module resolution is attempted). * @param {string} resolvePath the updated resolve path * @return {void} */ }, { key: "updateResolvePath", value: function updateResolvePath(resolvePath) { var prefix = "".concat(window.location.protocol, "//").concat(window.location.host); if (resolvePath.startsWith(prefix)) { resolvePath = resolvePath.substr(prefix.length); } this._config.resolvePath = resolvePath; } /** * Parse a configuration property to store it in _config. * @param {object} cfg * @param {string} property * @param {*} defaultValue */ }, { key: "_parse", value: function _parse(cfg, property, defaultValue) { this._config[property] = Object.prototype.hasOwnProperty.call(cfg, property) ? cfg[property] : defaultValue; } /** * Maps module names to their aliases. Example: * __CONFIG__.maps = { * liferay: 'liferay@1.0.0' * } * * When someone does require('liferay/html/js/ac.es',...), * if the module 'liferay/html/js/ac.es' is not defined, * then a corresponding alias will be searched. If found, the name will be * replaced, so it will look like user did * require('liferay@1.0.0/html/js/ac.es',...). * * Additionally, modules can define a custom map to alias module names just * in the context of that module loading operation. When present, the * contextual module mapping will take precedence over the general one. * @param {string} moduleName The module which have to be mapped * @param {?object} contextMap Contextual module mapping information * relevant to the current load operation * @return {array} The mapped module */ }, { key: "_mapModule", value: function _mapModule(moduleName, contextMap) { if (contextMap) { moduleName = this._mapMatches(moduleName, contextMap); } if (Object.keys(this._maps).length) { moduleName = this._mapMatches(moduleName, this._maps); } return moduleName; } /** * Creates a function that transforms module names based on a provided * set of mappings. * @param {string} moduleName module name * @param {object} maps Mapping information. * @return {function} The generated mapper function */ }, { key: "_mapMatches", value: function _mapMatches(moduleName, maps) { var match = maps[moduleName]; if (match) { if (_typeof(match) === 'object') { return match.value; } return match; } match = this._mapExactMatch(moduleName, maps); // Apply partial mapping only if exactMatch hasn't been // already applied for this mapping if (!match) { match = this._mapPartialMatch(moduleName, maps); } // Apply * mapping only if neither exactMatch nor // partialMatch have been already applied for this mapping if (!match) { match = this._mapWildcardMatch(moduleName, maps); } return match || moduleName; } /** * Transforms a module name using the exactMatch mappings * in a provided mapping object. * @param {string} module The module which have to be mapped. * @param {object} maps Mapping information. * @return {object} An object with a boolean `matched` field and a string * `result` field containing the mapped module name */ }, { key: "_mapExactMatch", value: function _mapExactMatch(module, maps) { for (var alias in maps) { if (Object.prototype.hasOwnProperty.call(maps, alias)) { var aliasValue = maps[alias]; if (aliasValue.value && aliasValue.exactMatch) { if (module === alias) { return aliasValue.value; } } } } } /** * Transforms a module name using the partial mappings * in a provided mapping object. * @param {string} module The module which have to be mapped. * @param {object} maps Mapping information. * @return {object} An object with a boolean `matched` field and a string * `result` field containing the mapped module name */ }, { key: "_mapPartialMatch", value: function _mapPartialMatch(module, maps) { for (var alias in maps) { if (Object.prototype.hasOwnProperty.call(maps, alias)) { var aliasValue = maps[alias]; if (!aliasValue.exactMatch) { if (aliasValue.value) { aliasValue = aliasValue.value; } if (module === alias || module.indexOf(alias + '/') === 0) { return aliasValue + module.substring(alias.length); } } } } } /** * Transforms a module name using the wildcard mapping in a provided mapping * object. * @param {string} module The module which have to be mapped. * @param {object} maps Mapping information. * @return {object} An object with a boolean `matched` field and a string * `result` field containing the mapped module name */ }, { key: "_mapWildcardMatch", value: function _mapWildcardMatch(module, maps) { if (typeof maps['*'] === 'function') { return maps['*'](module); } } }]); return Config; }(); /***/ }), /***/ "./src/loader/dependency-resolver.js": /*!*******************************************!*\ !*** ./src/loader/dependency-resolver.js ***! \*******************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ DependencyResolver) /* harmony export */ }); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * SPDX-FileCopyrightText: © 2014 Liferay, Inc. <https://liferay.com> * SPDX-License-Identifier: LGPL-3.0-or-later */ /** * A class that calls the server to resolve module dependencies. */ var DependencyResolver = /*#__PURE__*/function () { /** * Creates an instance of DependencyResolver class * @constructor * @param {Config} config */ function DependencyResolver(config) { _classCallCheck(this, DependencyResolver); this._config = config; this._cachedResolutions = {}; } /** * Resolves modules dependencies * @param {array} modules list of modules which dependencies should be * resolved * @return {array} list of module names, representing module dependencies * (module name itself is being returned too) */ _createClass(DependencyResolver, [{ key: "resolve", value: function resolve(modules) { var _this = this; if (modules === undefined || !modules.length) { throw new Error("Argument 'modules' cannot be undefined or empty"); } var config = this._config; return new Promise(function (resolve, reject) { var resolution = _this._cachedResolutions[modules]; if (resolution) { resolve(resolution); return; } var modulesParam = "modules=".concat(encodeURIComponent(modules)); var url = "".concat(config.resolvePath, "?").concat(modulesParam); var options = { redirect: 'follow' }; if (url.length > config.urlMaxLength) { url = config.resolvePath; options = _objectSpread(_objectSpread({}, options), {}, { body: modulesParam, method: 'POST' }); } fetch(url, options).then(function (response) { if (response.redirected) { _this._config.updateResolvePath(response.url); _this.resolve(modules).then(resolve)["catch"](reject); } else { response.text().then(function (text) { var resolution = JSON.parse(text); _this._cachedResolutions[modules] = resolution; resolve(resolution); })["catch"](reject); } })["catch"](reject); }); } }]); return DependencyResolver; }(); /***/ }), /***/ "./src/loader/loader.js": /*!******************************!*\ !*** ./src/loader/loader.js ***! \******************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ Loader) /* harmony export */ }); /* harmony import */ var _package_json__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../package.json */ "./package.json"); /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./config */ "./src/loader/config.js"); /* harmony import */ var _dependency_resolver__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./dependency-resolver */ "./src/loader/dependency-resolver.js"); /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./logger */ "./src/loader/logger.js"); /* harmony import */ var _script_loader__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./script-loader */ "./src/loader/script-loader.js"); /* harmony import */ var _url_builder__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./url-builder */ "./src/loader/url-builder.js"); function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * SPDX-FileCopyrightText: © 2014 Liferay, Inc. <https://liferay.com> * SPDX-License-Identifier: LGPL-3.0-or-later */ /** * */ var Loader = /*#__PURE__*/function () { /** * Creates an instance of Loader class. * @namespace Loader * @constructor * @param {object=} config Configuration options (defaults to * window.__CONFIG__) * @param {object} document DOM document object to use (defaults to * window.document) */ function Loader() { var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var document = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; _classCallCheck(this, Loader); this._config = new _config__WEBPACK_IMPORTED_MODULE_1__.default(config || window.__CONFIG__); this._log = new _logger__WEBPACK_IMPORTED_MODULE_3__.default(this._config); this._dependencyResolver = new _dependency_resolver__WEBPACK_IMPORTED_MODULE_2__.default(this._config); this._urlBuilder = new _url_builder__WEBPACK_IMPORTED_MODULE_5__.default(this._config); this._scriptLoader = new _script_loader__WEBPACK_IMPORTED_MODULE_4__.default(document || window.document, this._config, this._log); this._requireCallId = 0; } /** * Get loader version * @return {String} the version number as specified in package.json */ _createClass(Loader, [{ key: "version", value: function version() { return _package_json__WEBPACK_IMPORTED_MODULE_0__.version; } /** * Defines a module in the system and fires * @param {string} name the name of the module * @param {array} dependencies list of module dependencies * @param {function} factory the AMD factory function of the module */ }, { key: "define", value: function define() { var config = this._config; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var name = args[0]; var module = config.getModule(name); if (module && module.defined) { this._log.warn("Module '".concat(name, "' is being redefined. Only the first"), 'definition will be used'); return; } var dependencies = args[1]; var factory = args[2]; // Acccount for call polymorphism if (args.length === 2) { factory = dependencies; dependencies = ['require', 'exports', 'module']; } // Normalize factory argument if (typeof factory !== 'function') { var exportedValue = factory; factory = function factory() { return exportedValue; }; } // Do the things module = config.getModule(name); if (!module) { throw new Error("Trying to define a module that was not registered: ".concat(name, "\n") + 'This usually means that someone is calling define() ' + 'for a module that has not been previously required.'); } if (module.defined) { throw new Error("Trying to define a module more than once: ".concat(name, "\n") + 'This usually means that someone is calling define() ' + 'more than once for the same module, which can lead to ' + 'unexpected results.'); } this._log.resolution('Defining', module.name); module.factory = factory; module.dependencies = dependencies; module.define.resolve(args); } /** * Requires list of modules. If a module is not yet registered, it will be * ignored and its implementation in the provided success callback will be * left undefined. * @param {array|string[]} modules Modules can be specified as an array of * strings or provided as multiple string * parameters. * @param {function} success Callback, which will be invoked in case of * success. The provided parameters will be * implementations of all required modules. * @param {function} failure Callback, which will be invoked in case of * failure. One parameter with information * about the error will be provided. */ }, { key: "require", value: function require() { var _this = this; var moduleLoader = this._scriptLoader; var config = this._config; var requireCallId = this._requireCallId++; var moduleNames; var success; var failure; // Account for call polymorphism for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } if (args.length === 1) { moduleNames = args[0]; success = undefined; failure = undefined; } else if (args.length === 2) { var lastArg = args[args.length - 1]; if (typeof lastArg === 'function') { moduleNames = args[0]; success = lastArg; failure = undefined; } else if (lastArg === null || lastArg === undefined) { moduleNames = args[0]; success = undefined; failure = undefined; } else { moduleNames = args; success = undefined; failure = undefined; } } else { var _lastArg = args[args.length - 1]; var successGiven = false; if (typeof _lastArg === 'function' || _lastArg === null || _lastArg === undefined) { successGiven = true; } if (!successGiven) { moduleNames = args; success = undefined; failure = undefined; } else { var penultimateArg = args[args.length - 2]; var failureGiven = false; if (typeof penultimateArg === 'function' || penultimateArg === null || penultimateArg === undefined) { failureGiven = true; } if (!failureGiven) { moduleNames = args.slice(0, args.length - 1); success = _lastArg; failure = undefined; } else { moduleNames = args.slice(0, args.length - 2); success = penultimateArg; failure = _lastArg; } } } // Flatten moduleNames argument if necessary if (typeof moduleNames === 'string') { moduleNames = [moduleNames]; } else if (moduleNames.length === 1 && Array.isArray(moduleNames[0])) { var _ref; moduleNames = (_ref = []).concat.apply(_ref, _toConsumableArray(moduleNames)); } // Provide default value for success if (success === undefined) { success = function success() {}; } // Provide default value for failure if (failure === undefined) { var captureStackError = new Error(''); failure = function failure(error) { var stack = '(n/a)'; if (captureStackError.stack) { stack = captureStackError.stack.split('\n').map(function (line) { return " ".concat(line); }).join('\n'); stack = "\n".concat(stack); } _this._log.error('\n', 'A require() call has failed but no failure handler was', 'provided.\n', 'Note that even if the call stack of this error trace', 'looks like coming from the Liferay AMD Loader, it is not', 'an error in the Loader what has caused it, but an error', 'caused by the require() call.\n', 'The reason why the Loader is in the stack trace is', "because it is printing the error so that it doesn't get", 'lost.\n', 'However, we recommend providing a failure handler in all', 'require() calls to be able to recover from errors better', 'and to avoid the appearance of this message.\n', '\n', 'Some information about the require() call follows:\n', ' · Require call id:', requireCallId, '\n', ' · Required modules:', moduleNames, '\n', ' · Missing modules:', error.missingModules ? error.missingModules : '(n/a)', '\n', ' · Stack trace of the require() call:', "".concat(stack), '\n', error); }; } // Intercept handlers to explain resolutions success = this._interceptHandler(success, 'success', requireCallId); failure = this._interceptHandler(failure, 'failure', requireCallId); // Global closure variables var resolvedModuleNames; var unregisteredModuleNames; var rejectTimeout; var timeoutRejected = false; // Do the things (note that each then() block contains a synchronous // block of code, that means that between then() blocks may be // interrupted by any parallel call) this._dependencyResolver.resolve(moduleNames).then(function (resolution) { // Show extra information when explainResolutions is active _this._log.resolution('Require call', requireCallId, 'resolved modules', moduleNames, 'to', resolution); // In case we are calling an older server, act upon errors _this._throwOnLegacyProtocolResolutionErrors(resolution); // Show server warnings/errors _this._logServerMessages(moduleNames, resolution); // Fail resolution on server errors if (resolution.errors && resolution.errors.length > 1) { throw Object.assign(new Error('The server generated some errors while ' + 'resolving modules'), { resolutionErrors: resolution.errors }); } // Merge global maps from resolution into config config.addMappings(resolution.configMap); // Merge global paths from resolution into config config.addPaths(resolution.pathMap); // Store resolved module names resolvedModuleNames = resolution.resolvedModules; // Grab unregistered module names (some of the resolved modules // may have been registered by a parallel require() call, so we // are not responsible for loading them). unregisteredModuleNames = _this._getUnregisteredModuleNames(resolvedModuleNames); // Register the modules unregisteredModuleNames.forEach(function (moduleName) { var moduleProperties = { map: resolution.moduleMap[moduleName] }; var moduleFlags = resolution.moduleFlags ? resolution.moduleFlags[moduleName] : {}; moduleFlags = moduleFlags || {}; if (moduleFlags.esModule) { moduleProperties.esModule = true; } if (moduleFlags.useESM) { moduleProperties.useESM = true; } config.addModule(moduleName, moduleProperties); }); // Prepare load timeout rejectTimeout = _this._setRejectTimeout(moduleNames, resolution, function () { timeoutRejected = true; failure.apply(void 0, arguments); }); // Load the modules we are responsible for _this._log.resolution('Fetching', unregisteredModuleNames, 'from require call', requireCallId); return moduleLoader.loadModules(unregisteredModuleNames); }).then(function () { // If reject timeout was hit don't do anything else if (timeoutRejected) { return; } // Wait for all unregistered modules to be defined return _this._waitForModuleDefinitions(resolvedModuleNames); }).then(function () { // If reject timeout was hit don't do anything else if (timeoutRejected) { return; } // Everything went well so we can clear the timeout clearTimeout(rejectTimeout); // Set the implementations of all needed modules. Note that we // set the implementation of modules not loaded by this // require() call but it is necessary in case the require() // call that loaded them aborted because of an error in the // implementation of some module. _this._setModuleImplementations(requireCallId, resolvedModuleNames); // Now get all needed modules implementations var implementations = _this._getModuleImplementations(moduleNames); // And invoke the sucess handler success.apply(void 0, _toConsumableArray(implementations)); })["catch"](function (error) { // If reject timeout was hit don't do anything else if (timeoutRejected) { return; } if (rejectTimeout) { clearTimeout(rejectTimeout); } failure(error); }); } /** * Intercept a require success or failure handler to show information to * explain resolutions. * @param {function} handler * @param {string} type * @param {number} requireCallId */ }, { key: "_interceptHandler", value: function _interceptHandler(handler, type, requireCallId) { var _this2 = this; return function () { _this2._log.resolution('Invoking', type, 'handler for', 'require call', requireCallId); try { handler.apply(void 0, arguments); } catch (error) { _this2._log.error('\n', 'A require() call', type, 'handler has thrown an error.\n', 'Note that even if the call stack of this error trace', 'looks like coming from the Liferay AMD Loader, it is not', 'an error in the Loader what has caused it, but an error', "in the handler's code.\n", 'The reason why the Loader is in the stack trace is', 'because it is printing the error on behalf of the handler', "so that it doesn't get lost.\n", 'However, we recommend wrapping all handler code inside a', 'try/catch to be able to recover from errors better and to', 'avoid the appearance of this message.\n', '\n', error); } }; } /** * Filters a list of modules and returns only those which are not yet * registered. * @param {array} moduleNames list of module names to be tested * @return {array} list of modules matching the specified filter */ }, { key: "_getUnregisteredModuleNames", value: function _getUnregisteredModuleNames(moduleNames) { var config = this._config; return moduleNames.filter(function (moduleName) { return !config.getModule(moduleName); }); } /** * Traverse a resolved dependencies array looking for server sent errors and * throw an Error if any is found. * @param {array} moduleNames list of module names to be tested * @param {object} resolution the resolution object */ }, { key: "_logServerMessages", value: function _logServerMessages(moduleNames, resolution) { if (resolution.errors && !!resolution.errors.length) { this._log.error('Errors returned from server for require(', moduleNames, '):', resolution.errors); } if (resolution.warnings && !!resolution.warnings.length) { this._log.warn('Warnings returned from server for require(', moduleNames, '):', resolution.warnings); } } /** * Set a timeout (only if allowed by configuration) to reject a Promise if * a certain set of modules has not been successfully loaded. * @param {Array} modules the modules to be loaded * @param {object} resolution the resolution object associated to the * modules * @param {function} reject the promise reject function * @return {int} a timeout id or undefined if configuration disabled timeout */ }, { key: "_setRejectTimeout", value: function _setRejectTimeout(modules, resolution, reject) { var config = this._config; if (config.waitTimeout === 0) { return undefined; } return setTimeout(function () { var resolvedModuleNames = resolution.resolvedModules; var missingModules = resolvedModuleNames.filter(function (moduleName) { var module = config.getModule(moduleName); return !module || !module.implemented; }); var error = Object.assign(new Error('Load timeout for modules: ' + modules), { missingModules: missingModules, modules: modules, resolution: resolution }); reject(error); }, config.waitTimeout); } /** * Traverse a resolved dependencies array looking for server sent errors and * throw an Error if any is found. * * @deprecated * This method exists to account for old servers' responses in new loaders. * Old servers used to send resolution errors in the `resolvedModules` field * marking them with the ':ERROR:' prefix (because of historical reasons). * * @param {object} resolution the resolution object * @throws {Error} if a resolution error is found */ }, { key: "_throwOnLegacyProtocolResolutionErrors", value: function _throwOnLegacyProtocolResolutionErrors(resolution) { var resolutionErrors = resolution.resolvedModules.filter(function (dep) { return dep.indexOf(':ERROR:') === 0; }).map(function (dep) { return dep.substr(7); }); if (resolutionErrors.length) { throw Object.assign(new Error('The following problems where detected while ' + 'resolving modules:\n' + resolutionErrors.map(function (line) { return " \xB7 ".concat(line); }).join('\n')), { resolutionErrors: resolutionErrors }); } } /** * Resolves a Promise as soon as all provided modules are defined. * @param {array} moduleNames list of module names for which to wait * @return {Promise} */ }, { key: "_waitForModuleDefinitions", value: function _waitForModuleDefinitions(moduleNames) { var config = this._config; return Promise.all(config.getModules(moduleNames).map(function (module) { return module.define; })); } /** * Resolves a Promise as soon as all provided modules are implemented. * @param {array} moduleNames list of module names for which to wait * @return {Promise} */ }, { key: "_waitForModuleImplementations", value: function _waitForModuleImplementations(moduleNames) { var config = this._config; return Promise.all(config.getModules(moduleNames).map(function (module) { return module.implement; })); } /** * Invokes the implementation method of modules passing the implementations * of its dependencies. * @throws {Error} as soon as any factory fails * @param {number} requireCallId * @param {array} moduleNames list of modules to invoke */ }, { key: "_setModuleImplementations", value: function _setModuleImplementations(requireCallId, moduleNames) { var _this3 = this; var config = this._config; config.getModules(moduleNames).forEach(function (module) { // Skip already implemented modules if (module.implemented) { return; } // Fail for already rejected implementations if (module.implement.rejected) { throw module.implement.rejection; } // Show info about resolution _this3._log.resolution('Implementing', module.name, 'from require call', requireCallId); try { // Prepare CommonJS module implementation object var moduleImpl = { get exports() { return module.implementation; }, set exports(exports) { module.implementation = exports; } }; // Prepare arguments for the AMD factory function var dependencyImplementations = module.dependencies.map(function (dependency) { if (dependency === 'exports') { return moduleImpl.exports; } else if (dependency === 'module') { return moduleImpl; } else if (dependency === 'require') { return _this3._createLocalRequire(module); } else { var dependencyModule = config.getDependency(module.name, dependency); if (!dependencyModule) { throw new Error("Unsatisfied dependency: ".concat(dependency, " ") + "found in module ".concat(module.name)); } if (!dependencyModule.implementation && !dependencyModule.implemented) { throw new Error('Module "' + dependencyModule.name + '" has not been loaded yet for context: ' + module.name); } return dependencyModule.implementation; } }); // Invoke AMD factory function var result = module.factory.apply(module, _toConsumableArray(dependencyImplementations)); // Resolve the implementation if (result !== undefined) { module.implementation = result; } module.implement.resolve(module.implementation); } catch (error) { if (!module.implement.fulfilled) { module.implement.reject(error); } throw error; } }); } /** * Create a function implementing the local require method of the AMD * specification. * @param {Object} module a module descriptor * @return {function} the local require implementation for the given module */ }, { key: "_createLocalRequire", value: function _createLocalRequire(module) { var _this4 = this; var config = this._config; var localRequire = function localRequire(moduleName) { for (var _len3 = arguments.length, rest = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { rest[_key3 - 1] = arguments[_key3]; } if (rest.length) { return _this4.require.apply(_this4, [moduleName].concat(rest)); } else { var dependencyModule = config.getDependency(module.name, moduleName); if (!dependencyModule || !('implementation' in dependencyModule)) { throw new Error('Module "' + moduleName + '" has not been loaded yet for context: ' + module.name); } return dependencyModule.implementation; } }; localRequire.toUrl = function (moduleName) { var moduleURLs = _this4._urlBuilder.build([moduleName]); return moduleURLs[0].url; }; return localRequire; } /** * Retrieves module implementations to an array. * @param {array} moduleNames list of modules, which implementations * will be collected * @return {array} list of modules implementations. */ }, { key: "_getModuleImplementations", value: function _getModuleImplementations(moduleNames) { var config = this._config; return config.getModules(moduleNames).map(function (module) { return module.implementation; }); } }]); return Loader; }(); Loader.prototype.define.amd = {}; /***/ }), /***/ "./src/loader/logger.js": /*!******************************!*\ !*** ./src/loader/logger.js ***! \******************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ Logger) /* harmony export */ }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * SPDX-FileCopyrightText: © 2014 Liferay, Inc. <https://liferay.com> * SPDX-License-Identifier: LGPL-3.0-or-later */ var levelPriority = { /* eslint-disable sort-keys */ off: 0, // shows nothing error: 1, // shows user errors warn: 2, // shows warnings about loader's internal state info: 3, // shows info messages about loader's internal state debug: 4 // shows debug messages about loader's internal state /* eslint-enable sort-keys */ }; var prefix = 'liferay-amd-loader |'; /* eslint-disable no-console */ var Logger = /*#__PURE__*/function () { function Logger(config) { _classCallCheck(this, Logger); this._config = config; } _createClass(Logger, [{ key: "error", value: function error() { var _console; if (!this._applies('error')) { return; } for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } (_console = console).error.apply(_console, [prefix].concat(args)); } }, { key: "warn", value: function warn() { var _console2; if (!this._applies('warn')) { return; } for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } (_console2 = console).warn.apply(_console2, [prefix].concat(args)); } }, { key: "info", value: function info() { var _console3; if (!this._applies('info')) { return; } for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } (_console3 = console).info.apply(_console3, [prefix].concat(args)); } }, { key: "debug", value: function debug() { var _console4; if (!this._applies('debug')) { return; } for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } (_console4 = console).debug.apply(_console4, [prefix].concat(args)); } }, { key: "resolution", value: function resolution() { var _console5; if (!this._config.explainResolutions) { return; } for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } (_console5 = console).log.apply(_console5, [prefix].concat(args)); } }, { key: "_applies", value: function _applies(logLevel) { var configPriority = levelPriority[this._config.logLevel]; var logPriority = levelPriority[logLevel]; return logPriority <= configPriority; } }]); return Logger; }(); /***/ }), /***/ "./src/loader/module.js": /*!******************************!*\ !*** ./src/loader/module.js ***! \******************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ Module) /* harmony export */ }); /* harmony impor