lib/condenser/processors/node_modules/rollup/dist/rollup.js in condenser-0.0.5 vs lib/condenser/processors/node_modules/rollup/dist/rollup.js in condenser-0.0.7
- old
+ new
@@ -1,47 +1,71 @@
/*
@license
- Rollup.js v1.17.0
- Mon, 15 Jul 2019 04:31:04 GMT - commit 5d1541a577b06d9004a3533bde672761e5798482
+ Rollup.js v1.20.2
+ Sun, 25 Aug 2019 05:31:46 GMT - commit b1747e49d9659799a8c128d3052e5e5703362c37
https://github.com/rollup/rollup
Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
-function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
-
-var util = _interopDefault(require('util'));
+var index = require('./shared/index.js');
+var util = require('util');
var path = require('path');
-var path__default = _interopDefault(path);
var fs = require('fs');
var acorn = require('acorn');
-var acorn__default = _interopDefault(acorn);
var events = require('events');
-var module$1 = _interopDefault(require('module'));
+require('module');
-var version = "1.17.0";
+/*! *****************************************************************************
+Copyright (c) Microsoft Corporation. All rights reserved.
+Licensed under the Apache License, Version 2.0 (the "License"); you may not use
+this file except in compliance with the License. You may obtain a copy of the
+License at http://www.apache.org/licenses/LICENSE-2.0
+THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+MERCHANTABLITY OR NON-INFRINGEMENT.
+
+See the Apache Version 2.0 License for specific language governing permissions
+and limitations under the License.
+***************************************************************************** */
+function __awaiter(thisArg, _arguments, P, generator) {
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try {
+ step(generator.next(value));
+ }
+ catch (e) {
+ reject(e);
+ } }
+ function rejected(value) { try {
+ step(generator["throw"](value));
+ }
+ catch (e) {
+ reject(e);
+ } }
+ function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+}
+
var minimalisticAssert = assert;
function assert(val, msg) {
if (!val)
throw new Error(msg || 'Assertion failed');
}
assert.equal = function assertEqual(l, r, msg) {
if (l != r)
throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
};
-function createCommonjsModule(fn, module) {
- return module = { exports: {} }, fn(module, module.exports), module.exports;
-}
-
-var inherits_browser = createCommonjsModule(function (module) {
+var inherits_browser = index.createCommonjsModule(function (module) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
@@ -64,11 +88,11 @@
ctor.prototype.constructor = ctor;
};
}
});
-var inherits = createCommonjsModule(function (module) {
+var inherits = index.createCommonjsModule(function (module) {
try {
var util$1 = util;
if (typeof util$1.inherits !== 'function')
throw '';
module.exports = util$1.inherits;
@@ -1890,57 +1914,49 @@
}
}
}
const NO_SEMICOLON = { isNoStatement: true };
+// This assumes there are only white-space and comments between start and the string we are looking for
function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
let searchPos, charCodeAfterSlash;
searchPos = code.indexOf(searchString, start);
while (true) {
start = code.indexOf('/', start);
if (start === -1 || start > searchPos)
return searchPos;
charCodeAfterSlash = code.charCodeAt(++start);
++start;
- if (charCodeAfterSlash === 47 /*"/"*/) {
- start = code.indexOf('\n', start) + 1;
- if (start === 0)
- return -1;
- if (start > searchPos) {
- searchPos = code.indexOf(searchString, start);
- }
+ // With our assumption, '/' always starts a comment. Determine comment type:
+ start =
+ charCodeAfterSlash === 47 /*"/"*/
+ ? code.indexOf('\n', start) + 1
+ : code.indexOf('*/', start) + 2;
+ if (start > searchPos) {
+ searchPos = code.indexOf(searchString, start);
}
- else if (charCodeAfterSlash === 42 /*"*"*/) {
- start = code.indexOf('*/', start) + 2;
- if (start > searchPos) {
- searchPos = code.indexOf(searchString, start);
- }
- }
}
}
-function findFirstLineBreakOutsideComment(code, start = 0) {
- let lineBreakPos, charCodeAfterSlash;
+// This assumes "code" only contains white-space and comments
+function findFirstLineBreakOutsideComment(code) {
+ let lineBreakPos, charCodeAfterSlash, start = 0;
lineBreakPos = code.indexOf('\n', start);
while (true) {
start = code.indexOf('/', start);
if (start === -1 || start > lineBreakPos)
return lineBreakPos;
+ // With our assumption, '/' always starts a comment. Determine comment type:
charCodeAfterSlash = code.charCodeAt(++start);
if (charCodeAfterSlash === 47 /*"/"*/)
return lineBreakPos;
- ++start;
- if (charCodeAfterSlash === 42 /*"*"*/) {
- start = code.indexOf('*/', start) + 2;
- if (start > lineBreakPos) {
- lineBreakPos = code.indexOf('\n', start);
- }
+ start = code.indexOf('*/', start + 2) + 2;
+ if (start > lineBreakPos) {
+ lineBreakPos = code.indexOf('\n', start);
}
}
}
function renderStatementList(statements, code, start, end, options) {
- if (statements.length === 0)
- return;
let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
let nextNode = statements[0];
let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
if (nextNodeNeedsBoundaries) {
nextNodeStart =
@@ -2013,10 +2029,21 @@
separator: null,
start
});
return splitUpNodes;
}
+// This assumes there are only white-space and comments between start and end
+function removeLineBreaks(code, start, end) {
+ while (true) {
+ const lineBreakPos = findFirstLineBreakOutsideComment(code.original.slice(start, end));
+ if (lineBreakPos === -1) {
+ break;
+ }
+ start = start + lineBreakPos + 1;
+ code.remove(start - 1, start);
+ }
+}
const chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
const base = 64;
function toBase64(num) {
let outStr = '';
@@ -2613,27 +2640,13 @@
}
function makeLegal(str) {
str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
if (startsWithDigit(str) || blacklisted[str])
str = `_${str}`;
- return str;
+ return str || '_';
}
-const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
-const relativePath = /^\.?\.\//;
-function isAbsolute(path) {
- return absolutePath.test(path);
-}
-function isRelative(path) {
- return relativePath.test(path);
-}
-function normalize(path) {
- if (path.indexOf('\\') == -1)
- return path;
- return path.replace(/\\/g, '/');
-}
-
class ExternalModule {
constructor(graph, id, moduleSideEffects) {
this.exportsNames = false;
this.exportsNamespace = false;
this.mostCommonSuggestion = 0;
@@ -2670,15 +2683,15 @@
if (options.paths) {
this.renderPath =
typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
}
if (!this.renderPath) {
- if (!isAbsolute(this.id)) {
+ if (!index.isAbsolute(this.id)) {
this.renderPath = this.id;
}
else {
- this.renderPath = normalize(path.relative(inputBase, this.id));
+ this.renderPath = index.normalize(path.relative(inputBase, this.id));
this.renormalizeRenderPath = true;
}
}
return this.renderPath;
}
@@ -7737,13 +7750,13 @@
return value;
}
function defaultConverter(k, v) {
return isKeyed(v) ? v.toMap() : v.toList();
}
-var version$1 = "4.0.0-rc.11";
+var version = "4.0.0-rc.11";
var Immutable = {
- version: version$1,
+ version: version,
Collection: Collection,
// Note: Iterable is deprecated
Iterable: Collection,
Seq: Seq,
Map: Map$1,
@@ -8670,10 +8683,19 @@
}
}
getAssignedVariableName() {
return (this.originalId && this.originalId.name) || null;
}
+ getBaseVariableName() {
+ const original = this.getOriginalVariable();
+ if (original === this) {
+ return super.getBaseVariableName();
+ }
+ else {
+ return original.getBaseVariableName();
+ }
+ }
getName() {
const original = this.getOriginalVariable();
if (original === this) {
return super.getName();
}
@@ -8713,11 +8735,10 @@
else {
original.setSafeName(name);
}
}
}
-ExportDefaultVariable.prototype.getBaseVariableName = ExportDefaultVariable.prototype.getName;
const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
@@ -8875,15 +8896,10 @@
this.containsExternalNamespace = false;
this.referencedEarly = false;
this.references = [];
this.context = context;
this.module = context.module;
- for (const name of this.context.getExports().concat(this.context.getReexports())) {
- if (name[0] === '*' && name.length > 1)
- this.containsExternalNamespace = true;
- this.memberVariables[name] = this.context.traceExport(name);
- }
}
addReference(identifier) {
this.references.push(identifier);
this.name = identifier.name;
}
@@ -8920,10 +8936,17 @@
for (const memberName of Object.keys(this.memberVariables))
this.context.includeVariable(this.memberVariables[memberName]);
}
}
}
+ initialise() {
+ for (const name of this.context.getExports().concat(this.context.getReexports())) {
+ if (name[0] === '*' && name.length > 1)
+ this.containsExternalNamespace = true;
+ this.memberVariables[name] = this.context.traceExport(name);
+ }
+ }
renderBlock(options) {
const _ = options.compact ? '' : ' ';
const n = options.compact ? '' : '\n';
const t = options.indent;
const members = Object.keys(this.memberVariables).map(name => {
@@ -8977,11 +9000,11 @@
dependencies.some(dep => {
if (!dep.reexports)
return false;
return dep.reexports.some(expt => {
if (expt.reexported === 'default') {
- local = dep.namedExportsMode ? `${dep.name}.${expt.imported}` : dep.name;
+ local = dep.namedExportsMode && expt.imported !== '*' ? `${dep.name}.${expt.imported}` : dep.name;
return true;
}
return false;
});
});
@@ -8994,17 +9017,24 @@
if (reexports && namedExportsMode) {
reexports.forEach(specifier => {
if (specifier.reexported === '*') {
if (!compact && exportBlock)
exportBlock += '\n';
- exportBlock +=
- `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
- `${t}if${_}(k${_}!==${_}'default')${_}Object.defineProperty(exports,${_}k,${_}{${n}` +
- `${t}${t}enumerable:${_}true,${n}` +
- `${t}${t}get:${_}function${_}()${_}{${n}` +
- `${t}${t}${t}return ${name}[k];${n}` +
- `${t}${t}}${n}${t}});${n}});`;
+ if (specifier.needsLiveBinding) {
+ exportBlock +=
+ `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
+ `${t}if${_}(k${_}!==${_}'default')${_}Object.defineProperty(exports,${_}k,${_}{${n}` +
+ `${t}${t}enumerable:${_}true,${n}` +
+ `${t}${t}get:${_}function${_}()${_}{${n}` +
+ `${t}${t}${t}return ${name}[k];${n}` +
+ `${t}${t}}${n}${t}});${n}});`;
+ }
+ else {
+ exportBlock +=
+ `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
+ `${t}if${_}(k${_}!==${_}'default')${_}exports[k]${_}=${_}${name}[k];${n}});`;
+ }
}
});
}
});
dependencies.forEach(({ name, imports, reexports, isChunk, namedExportsMode: depNamedExportsMode }) => {
@@ -9075,29 +9105,35 @@
})
.filter(Boolean)
.join(options.compact ? '' : '\n');
}
-function getInteropNamespace(_, n, t) {
- return `function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
+function copyPropertyLiveBinding(_, n, t, i) {
+ return (`${i}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
+ `${i}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
+ `${i}${t}enumerable:${_}true,${n}` +
+ `${i}${t}get:${_}function${_}()${_}{${n}` +
+ `${i}${t}${t}return e[k];${n}` +
+ `${i}${t}}${n}` +
+ `${i}});${n}`);
+}
+function copyPropertyStatic(_, n, _t, i) {
+ return `${i}n[k]${_}=e${_}[k];${n}`;
+}
+function getInteropNamespace(_, n, t, liveBindings) {
+ return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
`${t}if${_}(e${_}&&${_}e.__esModule)${_}{${_}return e;${_}}${_}else${_}{${n}` +
`${t}${t}var n${_}=${_}{};${n}` +
`${t}${t}if${_}(e)${_}{${n}` +
`${t}${t}${t}Object.keys(e).forEach(function${_}(k)${_}{${n}` +
- `${t}${t}${t}${t}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
- `${t}${t}${t}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
- `${t}${t}${t}${t}${t}enumerable:${_}true,${n}` +
- `${t}${t}${t}${t}${t}get:${_}function${_}()${_}{${n}` +
- `${t}${t}${t}${t}${t}${t}return e[k];${n}` +
- `${t}${t}${t}${t}${t}}${n}` +
- `${t}${t}${t}${t}});${n}` +
+ (liveBindings ? copyPropertyLiveBinding : copyPropertyStatic)(_, n, t, t + t + t + t) +
`${t}${t}${t}});${n}` +
`${t}${t}}${n}` +
`${t}${t}n['default']${_}=${_}e;${n}` +
`${t}${t}return n;${n}` +
`${t}}${n}` +
- `}${n}${n}`;
+ `}${n}${n}`);
}
const builtins$1 = {
assert: true,
buffer: true,
@@ -9176,11 +9212,11 @@
const interopBlock = getInteropBlock(dependencies, options, varOrConst);
if (interopBlock) {
magicString.prepend(interopBlock + n + n);
}
if (accessedGlobals.has(INTEROP_NAMESPACE_VARIABLE)) {
- magicString.prepend(getInteropNamespace(_, n, t));
+ magicString.prepend(getInteropNamespace(_, n, t, options.externalLiveBindings !== false));
}
if (intro)
magicString.prepend(intro);
const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
if (exportBlock)
@@ -9240,11 +9276,11 @@
`function ${INTEROP_DEFAULT_VARIABLE}${_}(${ex})${_}{${_}return${_}` +
`(${ex}${_}&&${_}(typeof ${ex}${_}===${_}'object')${_}&&${_}'default'${_}in ${ex})${_}` +
`?${_}${ex}['default']${_}:${_}${ex}${options.compact ? '' : '; '}}${n}${n}`;
}
if (accessedGlobals.has(INTEROP_NAMESPACE_VARIABLE)) {
- intro += getInteropNamespace(_, n, t);
+ intro += getInteropNamespace(_, n, t, options.externalLiveBindings !== false);
}
if (importBlock)
intro += importBlock + n + n;
const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t, `module.exports${_}=${_}`);
magicString.prepend(intro);
@@ -9386,27 +9422,12 @@
return `${lineNum}: ${tabsToSpaces(str)}`;
})
.join('\n');
}
-function getAliasName(id) {
- const base = path.basename(id);
- return base.substr(0, base.length - path.extname(id).length);
-}
-function relativeId(id) {
- if (typeof process === 'undefined' || !isAbsolute(id))
- return id;
- return path.relative(process.cwd(), id);
-}
-function isPlainName(name) {
- // not starting with "./", "/". "../"
- return !(name[0] === '/' ||
- (name[1] === '.' && (name[2] === '/' || (name[2] === '.' && name[3] === '/'))));
-}
-
function error(base, props) {
- if (base instanceof Error === false)
+ if (!(base instanceof Error))
base = Object.assign(new Error(base.message), base);
if (props)
Object.assign(base, props);
throw base;
}
@@ -9430,96 +9451,93 @@
Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
Errors["BAD_LOADER"] = "BAD_LOADER";
- Errors["CHUNK_NOT_FOUND"] = "CHUNK_NOT_FOUND";
+ Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
- Errors["INVALID_ASSET_NAME"] = "INVALID_ASSET_NAME";
+ Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
+ Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
Errors["INVALID_OPTION"] = "INVALID_OPTION";
Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
+ Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
+ Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
})(Errors || (Errors = {}));
-function errAssetNotFinalisedForFileName(asset) {
+function errAssetNotFinalisedForFileName(name) {
return {
code: Errors.ASSET_NOT_FINALISED,
- message: `Plugin error - Unable to get file name for asset "${asset.name}". Ensure that the source is set and that generate is called first.`
+ message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
};
}
-function errChunkNotGeneratedForFileName(entry) {
+function errCannotEmitFromOptionsHook() {
return {
- code: Errors.CHUNK_NOT_GENERATED,
- message: `Plugin error - Unable to get file name for chunk "${entry.name}". Ensure that generate is called first.`
+ code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
+ message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
};
}
-function errAssetReferenceIdNotFoundForFilename(assetReferenceId) {
+function errChunkNotGeneratedForFileName(name) {
return {
- code: Errors.ASSET_NOT_FOUND,
- message: `Plugin error - Unable to get file name for unknown asset "${assetReferenceId}".`
+ code: Errors.CHUNK_NOT_GENERATED,
+ message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
};
}
function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
return {
code: Errors.ASSET_NOT_FOUND,
message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
};
}
-function errAssetSourceAlreadySet(asset) {
+function errAssetSourceAlreadySet(name) {
return {
code: Errors.ASSET_SOURCE_ALREADY_SET,
- message: `Plugin error - Unable to set the source for asset "${asset.name}", source already set.`
+ message: `Unable to set the source for asset "${name}", source already set.`
};
}
-function errAssetSourceMissingForSetSource(asset) {
+function errNoAssetSourceSet(assetName) {
return {
code: Errors.ASSET_SOURCE_MISSING,
- message: `Plugin error creating asset "${asset.name}", setAssetSource call without a source.`
+ message: `Plugin error creating asset "${assetName}" - no asset source set.`
};
}
-function errNoAssetSourceSet(asset) {
- return {
- code: Errors.ASSET_SOURCE_MISSING,
- message: `Plugin error creating asset "${asset.name}" - no asset source set.`
- };
-}
function errBadLoader(id) {
return {
code: Errors.BAD_LOADER,
- message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
+ message: `Error loading ${index.relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
};
}
-function errChunkReferenceIdNotFoundForFilename(chunkReferenceId) {
- return {
- code: Errors.CHUNK_NOT_FOUND,
- message: `Plugin error - Unable to get file name for unknown chunk "${chunkReferenceId}".`
- };
-}
function errDeprecation(deprecation) {
return Object.assign({ code: Errors.DEPRECATED_FEATURE }, (typeof deprecation === 'string' ? { message: deprecation } : deprecation));
}
-function errInvalidAssetName(name) {
+function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
return {
- code: Errors.INVALID_ASSET_NAME,
- message: `Plugin error creating asset, name "${name}" is not a plain (non relative or absolute URL) string name.`
+ code: Errors.FILE_NOT_FOUND,
+ message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
};
}
+function errFileNameConflict(fileName) {
+ return {
+ code: Errors.FILE_NAME_CONFLICT,
+ message: `Could not emit file "${fileName}" as it conflicts with an already emitted file.`
+ };
+}
function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
return {
code: Errors.INVALID_CHUNK,
- message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
+ message: `Cannot assign ${index.relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
};
}
function errInternalIdCannotBeExternal(source, importer) {
return {
code: Errors.INVALID_EXTERNAL_ID,
- message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
+ message: `'${source}' is imported as an external by ${index.relativeId(importer)}, but is already an existing non-external module id.`
};
}
function errInvalidOption(option, explanation) {
return {
code: Errors.INVALID_OPTION,
@@ -9530,52 +9548,58 @@
return {
code: Errors.INVALID_ROLLUP_PHASE,
message: `Cannot call addWatchFile after the build has finished.`
};
}
-function errInvalidRollupPhaseForEmitChunk() {
+function errInvalidRollupPhaseForChunkEmission() {
return {
code: Errors.INVALID_ROLLUP_PHASE,
- message: `Cannot call emitChunk after module loading has finished.`
+ message: `Cannot emit chunks after module loading has finished.`
};
}
function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) {
return {
code: Errors.NAMESPACE_CONFLICT,
- message: `Conflicting namespaces: ${relativeId(reexportingModule.id)} re-exports '${name}' from both ${relativeId(reexportingModule.exportsAll[name])} and ${relativeId(additionalExportAllModule.exportsAll[name])} (will be ignored)`,
+ message: `Conflicting namespaces: ${index.relativeId(reexportingModule.id)} re-exports '${name}' from both ${index.relativeId(reexportingModule.exportsAll[name])} and ${index.relativeId(additionalExportAllModule.exportsAll[name])} (will be ignored)`,
name,
reexporter: reexportingModule.id,
sources: [reexportingModule.exportsAll[name], additionalExportAllModule.exportsAll[name]]
};
}
function errEntryCannotBeExternal(unresolvedId) {
return {
code: Errors.UNRESOLVED_ENTRY,
- message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
+ message: `Entry module cannot be external (${index.relativeId(unresolvedId)}).`
};
}
function errUnresolvedEntry(unresolvedId) {
return {
code: Errors.UNRESOLVED_ENTRY,
- message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
+ message: `Could not resolve entry module (${index.relativeId(unresolvedId)}).`
};
}
function errUnresolvedImport(source, importer) {
return {
code: Errors.UNRESOLVED_IMPORT,
- message: `Could not resolve '${source}' from ${relativeId(importer)}`
+ message: `Could not resolve '${source}' from ${index.relativeId(importer)}`
};
}
function errUnresolvedImportTreatedAsExternal(source, importer) {
return {
code: Errors.UNRESOLVED_IMPORT,
- importer: relativeId(importer),
- message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
+ importer: index.relativeId(importer),
+ message: `'${source}' is imported by ${index.relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
source,
url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
};
}
+function errFailedValidation(message) {
+ return {
+ code: Errors.VALIDATION_ERROR,
+ message
+ };
+}
// Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
// if the property name isn't trivial
const shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
function property(prop) {
@@ -10682,21 +10706,23 @@
}
else {
this.usedBranch.include(includeChildrenRecursively);
}
}
- render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) {
+ render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
if (!this.test.included) {
const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
+ const inclusionStart = (this.consequent.included
+ ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
+ : colonPos) + 1;
+ if (preventASI) {
+ removeLineBreaks(code, inclusionStart, this.usedBranch.start);
+ }
+ code.remove(this.start, inclusionStart);
if (this.consequent.included) {
- const questionmarkPos = findFirstOccurrenceOutsideComment(code.original, '?', this.test.end);
- code.remove(this.start, questionmarkPos + 1);
code.remove(colonPos, this.end);
}
- else {
- code.remove(this.start, colonPos + 1);
- }
removeAnnotations(this, code);
this.usedBranch.render(code, options, {
isCalleeOfRenderedParent: renderedParentType
? isCalleeOfRenderedParent
: this.parent.callee === this,
@@ -10944,43 +10970,62 @@
}
}
}
}
+class ImportDeclaration extends NodeBase {
+ bind() { }
+ hasEffects() {
+ return false;
+ }
+ initialise() {
+ this.context.addImport(this);
+ }
+ render(code, _options, { start, end } = BLANK) {
+ code.remove(start, end);
+ }
+}
+ImportDeclaration.prototype.needsBoundaries = true;
+
class Import extends NodeBase {
constructor() {
super(...arguments);
this.exportMode = 'auto';
}
- include() {
+ hasEffects() {
+ return true;
+ }
+ include(includeChildrenRecursively) {
if (!this.included) {
this.included = true;
this.context.includeDynamicImport(this);
}
+ this.source.include(includeChildrenRecursively);
}
initialise() {
this.context.addDynamicImport(this);
}
render(code, options) {
if (this.inlineNamespace) {
const _ = options.compact ? '' : ' ';
const s = options.compact ? '' : ';';
- code.overwrite(this.parent.start, this.parent.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`);
+ code.overwrite(this.start, this.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`);
return;
}
const importMechanism = this.getDynamicImportMechanism(options);
if (importMechanism) {
- code.overwrite(this.parent.start, findFirstOccurrenceOutsideComment(code.original, '(', this.parent.callee.end) + 1, importMechanism.left);
- code.overwrite(this.parent.end - 1, this.parent.end, importMechanism.right);
+ code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, importMechanism.left);
+ code.overwrite(this.end - 1, this.end, importMechanism.right);
}
+ this.source.render(code, options);
}
renderFinalResolution(code, resolution, format) {
if (this.included) {
if (format === 'amd' && resolution.startsWith("'.") && resolution.endsWith(".js'")) {
resolution = resolution.slice(0, -4) + "'";
}
- code.overwrite(this.parent.arguments[0].start, this.parent.arguments[0].end, resolution);
+ code.overwrite(this.source.start, this.source.end, resolution);
}
}
setResolution(exportMode, inlineNamespace) {
this.exportMode = exportMode;
if (inlineNamespace) {
@@ -11052,24 +11097,10 @@
}
return null;
}
}
-class ImportDeclaration extends NodeBase {
- bind() { }
- hasEffects() {
- return false;
- }
- initialise() {
- this.context.addImport(this);
- }
- render(code, _options, { start, end } = BLANK) {
- code.remove(start, end);
- }
-}
-ImportDeclaration.prototype.needsBoundaries = true;
-
class LabeledStatement extends NodeBase {
hasEffects(options) {
return this.body.hasEffects(options.setIgnoreLabel(this.label.name).setIgnoreBreakStatements());
}
}
@@ -11214,15 +11245,18 @@
}
else {
this.usedBranch.include(includeChildrenRecursively);
}
}
- render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) {
+ render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
if (!this.left.included || !this.right.included) {
const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
if (this.right.included) {
code.remove(this.start, operatorPos + 2);
+ if (preventASI) {
+ removeLineBreaks(code, operatorPos + 2, this.right.start);
+ }
}
else {
code.remove(operatorPos, this.end);
}
removeAnnotations(this, code);
@@ -11459,15 +11493,15 @@
const fileName = baseVariable instanceof ExternalVariable
? baseVariable.module.id
: baseVariable.context.fileName;
this.context.warn({
code: 'MISSING_EXPORT',
- exporter: relativeId(fileName),
- importer: relativeId(this.context.fileName),
- message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
+ exporter: index.relativeId(fileName),
+ importer: index.relativeId(this.context.fileName),
+ message: `'${exportName}' is not exported by '${index.relativeId(fileName)}'`,
missing: exportName,
- url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module-`
+ url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
}, path[0].pos);
return 'undefined';
}
return this.resolveNamespaceVariables(variable, path.slice(1));
}
@@ -11559,11 +11593,11 @@
url: 'https://rollupjs.org/guide/en/#a-simple-example'
});
}
// external modules (non-entry modules that start with neither '.' or '/')
// are skipped at this stage.
- if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
+ if (importer !== undefined && !index.isAbsolute(source) && source[0] !== '.')
return null;
// `resolve` processes paths from right to left, prepending them until an
// absolute path is created. Absolute importees therefore shortcircuit the
// resolve call and require no special handing on our part.
// See https://nodejs.org/api/path.html#path_path_resolve_paths
@@ -11583,11 +11617,15 @@
system: prop => (prop === null ? `module.meta` : `module.meta.${prop}`),
umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`)
};
const getRelativeUrlFromDocument = (relativePath) => getResolveUrl(`'${relativePath}', document.currentScript && document.currentScript.src || document.baseURI`);
const relativeUrlMechanisms = {
- amd: relativePath => getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`),
+ amd: relativePath => {
+ if (relativePath[0] !== '.')
+ relativePath = './' + relativePath;
+ return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
+ },
cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
iife: relativePath => getRelativeUrlFromDocument(relativePath),
system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
umd: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`
@@ -11607,11 +11645,15 @@
umd: ['document', 'require', 'URL']
};
const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
+const FILE_PREFIX = 'ROLLUP_FILE_URL_';
class MetaProperty extends NodeBase {
+ hasEffects() {
+ return false;
+ }
hasEffectsWhenAccessedAtPath(path) {
return path.length > 1;
}
include() {
if (!this.included) {
@@ -11623,11 +11665,13 @@
: null);
if (metaProperty) {
if (metaProperty === 'url') {
this.scope.addAccessedGlobalsByFormat(accessedMetaUrlGlobals);
}
- else if (metaProperty.startsWith(ASSET_PREFIX) || metaProperty.startsWith(CHUNK_PREFIX)) {
+ else if (metaProperty.startsWith(FILE_PREFIX) ||
+ metaProperty.startsWith(ASSET_PREFIX) ||
+ metaProperty.startsWith(CHUNK_PREFIX)) {
this.scope.addAccessedGlobalsByFormat(accessedFileUrlGlobals);
}
}
}
}
@@ -11638,25 +11682,34 @@
}
renderFinalMechanism(code, chunkId, format, pluginDriver) {
if (!this.included)
return;
const parent = this.parent;
- const importMetaProperty = this.metaProperty;
- if (importMetaProperty &&
- (importMetaProperty.startsWith(ASSET_PREFIX) || importMetaProperty.startsWith(CHUNK_PREFIX))) {
+ const metaProperty = this.metaProperty;
+ if (metaProperty &&
+ (metaProperty.startsWith(FILE_PREFIX) ||
+ metaProperty.startsWith(ASSET_PREFIX) ||
+ metaProperty.startsWith(CHUNK_PREFIX))) {
+ let referenceId = null;
let assetReferenceId = null;
let chunkReferenceId = null;
let fileName;
- if (importMetaProperty.startsWith(ASSET_PREFIX)) {
- assetReferenceId = importMetaProperty.substr(ASSET_PREFIX.length);
- fileName = this.context.getAssetFileName(assetReferenceId);
+ if (metaProperty.startsWith(FILE_PREFIX)) {
+ referenceId = metaProperty.substr(FILE_PREFIX.length);
+ fileName = this.context.getFileName(referenceId);
}
+ else if (metaProperty.startsWith(ASSET_PREFIX)) {
+ this.context.warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, false);
+ assetReferenceId = metaProperty.substr(ASSET_PREFIX.length);
+ fileName = this.context.getFileName(assetReferenceId);
+ }
else {
- chunkReferenceId = importMetaProperty.substr(CHUNK_PREFIX.length);
- fileName = this.context.getChunkFileName(chunkReferenceId);
+ this.context.warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, false);
+ chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length);
+ fileName = this.context.getFileName(chunkReferenceId);
}
- const relativePath = normalize(path.relative(path.dirname(chunkId), fileName));
+ const relativePath = index.normalize(path.relative(path.dirname(chunkId), fileName));
let replacement;
if (assetReferenceId !== null) {
replacement = pluginDriver.hookFirstSync('resolveAssetUrl', [
{
assetFileName: fileName,
@@ -11674,19 +11727,20 @@
chunkId,
chunkReferenceId,
fileName,
format,
moduleId: this.context.module.id,
+ referenceId: referenceId || assetReferenceId || chunkReferenceId,
relativePath
}
]);
}
code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
return;
}
const replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
- importMetaProperty,
+ metaProperty,
{
chunkId,
format,
moduleId: this.context.module.id
}
@@ -12182,11 +12236,11 @@
initialise() {
this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
}
render(code, options) {
if (this.argument) {
- this.argument.render(code, options);
+ this.argument.render(code, options, { preventASI: true });
if (this.argument.start === this.start + 6 /* 'return'.length */) {
code.prependLeft(this.start + 6, ' ');
}
}
}
@@ -12225,18 +12279,21 @@
if (includeChildrenRecursively || node.shouldBeIncluded())
node.include(includeChildrenRecursively);
}
this.expressions[this.expressions.length - 1].include(includeChildrenRecursively);
}
- render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) {
+ render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
let includedNodes = 0;
for (const { node, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
if (!node.included) {
treeshakeNode(node, code, start, end);
continue;
}
includedNodes++;
+ if (includedNodes === 1 && preventASI) {
+ removeLineBreaks(code, start, node.start);
+ }
if (node === this.expressions[this.expressions.length - 1] && includedNodes === 1) {
node.render(code, options, {
isCalleeOfRenderedParent: renderedParentType
? isCalleeOfRenderedParent
: this.parent.callee === this,
@@ -12406,10 +12463,13 @@
class ThrowStatement extends NodeBase {
hasEffects(_options) {
return true;
}
+ render(code, options) {
+ this.argument.render(code, options, { preventASI: true });
+ }
}
class TryStatement extends NodeBase {
constructor() {
super(...arguments);
@@ -12764,12 +12824,12 @@
ForStatement,
FunctionDeclaration,
FunctionExpression: FunctionExpression$1,
Identifier: Identifier$1,
IfStatement,
- Import,
ImportDeclaration,
+ ImportExpression: Import,
LabeledStatement,
Literal,
LogicalExpression,
MemberExpression,
MetaProperty,
@@ -13063,11 +13123,14 @@
c(spec, st);
}
c(node.source, st, "Expression");
};
-base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.Literal = base$1.Import = ignore;
+base$1.ImportExpression = function (node, st, c) {
+ c(node.source, st, "Expression");
+};
+base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.Literal = ignore;
base$1.TaggedTemplateExpression = function (node, st, c) {
c(node.tag, st, "Expression");
c(node.quasi, st, "Expression");
};
@@ -13241,11 +13304,11 @@
timeEnd = NOOP;
}
}
const defaultAcornOptions = {
- ecmaVersion: 2019,
+ ecmaVersion: 2020,
preserveParens: false,
sourceType: 'module'
};
function tryParse(module, Parser, acornOptions) {
try {
@@ -13266,21 +13329,22 @@
}
}
function handleMissingExport(exportName, importingModule, importedModule, importerStart) {
importingModule.error({
code: 'MISSING_EXPORT',
- message: `'${exportName}' is not exported by ${relativeId(importedModule)}`,
- url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module-`
+ message: `'${exportName}' is not exported by ${index.relativeId(importedModule)}`,
+ url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
}, importerStart);
}
const MISSING_EXPORT_SHIM_DESCRIPTION = {
identifier: null,
localName: MISSING_EXPORT_SHIM_VARIABLE
};
class Module {
constructor(graph, id, moduleSideEffects, isEntry) {
- this.chunkAlias = null;
+ this.chunkFileNames = new Set();
+ this.chunkName = null;
this.comments = [];
this.dependencies = [];
this.dynamicallyImportedBy = [];
this.dynamicDependencies = [];
this.dynamicImports = [];
@@ -13298,10 +13362,11 @@
this.isExecuted = false;
this.isUserDefinedEntryPoint = false;
this.manualChunkAlias = null;
this.reexports = Object.create(null);
this.sources = [];
+ this.userChunkNames = new Set();
this.usesTopLevelAwait = false;
this.namespaceVariable = undefined;
this.transformDependencies = null;
this.id = id;
this.graph = graph;
@@ -13369,11 +13434,11 @@
}
return allExportNames;
}
getDynamicImportExpressions() {
return this.dynamicImports.map(({ node }) => {
- const importArgument = node.parent.arguments[0];
+ const importArgument = node.source;
if (importArgument instanceof TemplateLiteral &&
importArgument.quasis.length === 1 &&
importArgument.quasis[0].value.cooked) {
return importArgument.quasis[0].value.cooked;
}
@@ -13403,11 +13468,15 @@
}
getExports() {
return Object.keys(this.exports);
}
getOrCreateNamespace() {
- return (this.namespaceVariable || (this.namespaceVariable = new NamespaceVariable(this.astContext)));
+ if (!this.namespaceVariable) {
+ this.namespaceVariable = new NamespaceVariable(this.astContext);
+ this.namespaceVariable.initialise();
+ }
+ return this.namespaceVariable;
}
getReexports() {
if (this.transitiveReexports) {
return this.transitiveReexports;
}
@@ -13551,21 +13620,18 @@
const magicString = this.magicString.clone();
this.ast.render(magicString, options);
this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
return magicString;
}
- setSource({ ast, code, customTransformCache, moduleSideEffects, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformAssets, transformChunks, transformDependencies }) {
+ setSource({ ast, code, customTransformCache, moduleSideEffects, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles }) {
this.code = code;
this.originalCode = originalCode;
this.originalSourcemap = originalSourcemap;
this.sourcemapChain = sourcemapChain;
- if (transformAssets) {
- this.transformAssets = transformAssets;
+ if (transformFiles) {
+ this.transformFiles = transformFiles;
}
- if (transformChunks) {
- this.transformChunks = transformChunks;
- }
this.transformDependencies = transformDependencies;
this.customTransformCache = customTransformCache;
if (typeof moduleSideEffects === 'boolean') {
this.moduleSideEffects = moduleSideEffects;
}
@@ -13592,13 +13658,12 @@
this.graph.treeshakingOptions.annotations),
code,
deoptimizationTracker: this.graph.deoptimizationTracker,
error: this.error.bind(this),
fileName,
- getAssetFileName: this.graph.pluginDriver.getAssetFileName,
- getChunkFileName: this.graph.moduleLoader.getChunkFileName.bind(this.graph.moduleLoader),
getExports: this.getExports.bind(this),
+ getFileName: this.graph.pluginDriver.getFileName,
getModuleExecIndex: () => this.execIndex,
getModuleName: this.basename.bind(this),
getReexports: this.getReexports.bind(this),
importDescriptions: this.importDescriptions,
includeDynamicImport: this.includeDynamicImport.bind(this),
@@ -13615,11 +13680,12 @@
traceVariable: this.traceVariable.bind(this),
treeshake: !!this.graph.treeshakingOptions,
tryCatchDeoptimization: (!this.graph.treeshakingOptions ||
this.graph.treeshakingOptions.tryCatchDeoptimization),
usesTopLevelAwait: false,
- warn: this.warn.bind(this)
+ warn: this.warn.bind(this),
+ warnDeprecation: this.graph.warnDeprecation.bind(this.graph)
};
this.scope = new ModuleScope(this.graph.scope, this.astContext);
this.ast = new Program$1(this.esTreeAst, { type: 'Module', context: this.astContext }, this.scope);
timeEnd('analyse ast', 3);
}
@@ -13633,13 +13699,12 @@
moduleSideEffects: this.moduleSideEffects,
originalCode: this.originalCode,
originalSourcemap: this.originalSourcemap,
resolvedIds: this.resolvedIds,
sourcemapChain: this.sourcemapChain,
- transformAssets: this.transformAssets,
- transformChunks: this.transformChunks,
- transformDependencies: this.transformDependencies
+ transformDependencies: this.transformDependencies,
+ transformFiles: this.transformFiles
};
}
traceVariable(name) {
const localVariable = this.scope.variables.get(name);
if (localVariable) {
@@ -13808,13 +13873,13 @@
}
shimMissingExport(name) {
if (!this.exports[name]) {
this.graph.warn({
code: 'SHIMMED_EXPORT',
- exporter: relativeId(this.id),
+ exporter: index.relativeId(this.id),
exportName: name,
- message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
+ message: `Missing export "${name}" has been shimmed in module ${index.relativeId(this.id)}.`
});
this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
}
}
}
@@ -14124,14 +14189,14 @@
}
}
return { orderedModules, cyclePaths };
}
function getCyclePath(id, parentId, parents) {
- const path = [relativeId(id)];
+ const path = [index.relativeId(id)];
let curId = parentId;
while (curId !== id) {
- path.push(relativeId(curId));
+ path.push(index.relativeId(curId));
curId = parents[curId];
if (!curId)
break;
}
path.push(path[0]);
@@ -14232,28 +14297,20 @@
plugin: err.plugin
});
});
}
-function renderNamePattern(pattern, patternName, getReplacement) {
- if (!isPlainName(pattern))
- error({
- code: 'INVALID_PATTERN',
- message: `Invalid output pattern "${pattern}" for ${patternName}, cannot be an absolute or relative URL or path.`
- });
+function renderNamePattern(pattern, patternName, replacements) {
+ if (!index.isPlainPathFragment(pattern))
+ return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths and must not contain invalid characters.`));
return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
- const replacement = getReplacement(type);
- if (replacement === undefined)
- error({
- code: 'INVALID_PATTERN_REPLACEMENT',
- message: `"${type}" is not a valid substitution name in output option ${patternName} pattern.`
- });
- if (!isPlainName(replacement))
- error({
- code: 'INVALID_PATTERN_REPLACEMENT',
- message: `Invalid replacement "${replacement}" for "${type}" in ${patternName} pattern, must be a plain path name.`
- });
+ if (!replacements.hasOwnProperty(type)) {
+ return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
+ }
+ const replacement = replacements[type]();
+ if (!index.isPlainPathFragment(replacement))
+ return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
return replacement;
});
}
function makeUnique(name, existingNames) {
if (name in existingNames === false)
@@ -14264,14 +14321,10 @@
while (existingNames[(uniqueName = name + ++uniqueIndex + ext)])
;
return uniqueName;
}
-function sanitizeFileName(name) {
- return name.replace(/[\0?*]/g, '_');
-}
-
function getGlobalName(module, globals, graph, hasExports) {
let globalName;
if (typeof globals === 'function') {
globalName = globals(module.id);
}
@@ -14297,19 +14350,22 @@
class Chunk$1 {
constructor(graph, orderedModules) {
this.entryModules = [];
this.exportMode = 'named';
this.facadeModule = null;
- this.id = undefined;
+ this.id = null;
this.indentString = undefined;
this.manualChunkAlias = null;
this.usedModules = undefined;
+ this.variableName = 'chunk';
this.dependencies = undefined;
this.dynamicDependencies = undefined;
this.exportNames = Object.create(null);
this.exports = new Set();
+ this.fileName = null;
this.imports = new Set();
+ this.name = null;
this.needsExportsShim = false;
this.renderedDeclarations = undefined;
this.renderedHash = undefined;
this.renderedModuleSources = new Map();
this.renderedSource = null;
@@ -14330,78 +14386,86 @@
if (module.isEntryPoint ||
module.dynamicallyImportedBy.some(module => orderedModules.indexOf(module) === -1)) {
this.entryModules.push(module);
}
}
- const entryModule = this.entryModules[0];
- if (entryModule) {
- this.variableName = makeLegal(path.basename(entryModule.chunkAlias || entryModule.manualChunkAlias || getAliasName(entryModule.id)));
+ const moduleForNaming = this.entryModules[0] || this.orderedModules[this.orderedModules.length - 1];
+ if (moduleForNaming) {
+ this.variableName = makeLegal(path.basename(moduleForNaming.chunkName ||
+ moduleForNaming.manualChunkAlias ||
+ index.getAliasName(moduleForNaming.id)));
}
- else {
- this.variableName = '__chunk_' + ++graph.curChunkIndex;
- }
}
- static generateFacade(graph, facadedModule) {
+ static generateFacade(graph, facadedModule, facadeName) {
const chunk = new Chunk$1(graph, []);
+ chunk.assignFacadeName(facadeName, facadedModule);
+ if (!facadedModule.facadeChunk) {
+ facadedModule.facadeChunk = chunk;
+ }
chunk.dependencies = [facadedModule.chunk];
chunk.dynamicDependencies = [];
chunk.facadeModule = facadedModule;
- facadedModule.facadeChunk = chunk;
for (const exportName of facadedModule.getAllExportNames()) {
const tracedVariable = facadedModule.getVariableForExportName(exportName);
chunk.exports.add(tracedVariable);
chunk.exportNames[exportName] = tracedVariable;
}
return chunk;
}
- canModuleBeFacade(moduleExportNamesByVariable, moduleChunkAlias) {
- if (this.manualChunkAlias && moduleChunkAlias && this.manualChunkAlias !== moduleChunkAlias) {
- return false;
- }
+ canModuleBeFacade(moduleExportNamesByVariable) {
for (const exposedVariable of this.exports) {
if (!moduleExportNamesByVariable.has(exposedVariable)) {
return false;
}
}
return true;
}
generateFacades() {
const facades = [];
for (const module of this.entryModules) {
+ const requiredFacades = Array.from(module.userChunkNames).map(name => ({
+ name
+ }));
+ if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
+ requiredFacades.push({});
+ }
+ requiredFacades.push(...Array.from(module.chunkFileNames).map(fileName => ({ fileName })));
+ if (requiredFacades.length === 0) {
+ requiredFacades.push({});
+ }
if (!this.facadeModule) {
const exportNamesByVariable = module.getExportNamesByVariable();
- if (this.graph.preserveModules ||
- this.canModuleBeFacade(exportNamesByVariable, module.chunkAlias)) {
+ if (this.graph.preserveModules || this.canModuleBeFacade(exportNamesByVariable)) {
this.facadeModule = module;
+ module.facadeChunk = this;
for (const [variable, exportNames] of exportNamesByVariable) {
for (const exportName of exportNames) {
this.exportNames[exportName] = variable;
}
}
- continue;
+ this.assignFacadeName(requiredFacades.shift(), module);
}
}
- facades.push(Chunk$1.generateFacade(this.graph, module));
+ for (const facadeName of requiredFacades) {
+ facades.push(Chunk$1.generateFacade(this.graph, module, facadeName));
+ }
}
return facades;
}
generateId(pattern, patternName, addons, options, existingNames) {
- this.id = makeUnique(renderNamePattern(pattern, patternName, type => {
- switch (type) {
- case 'format':
- return options.format === 'es' ? 'esm' : options.format;
- case 'hash':
- return this.computeContentHashWithDependencies(addons, options);
- case 'name':
- return this.getChunkName();
- }
- return undefined;
+ if (this.fileName !== null) {
+ return this.fileName;
+ }
+ return makeUnique(renderNamePattern(pattern, patternName, {
+ format: () => (options.format === 'es' ? 'esm' : options.format),
+ hash: () => this.computeContentHashWithDependencies(addons, options),
+ name: () => this.getChunkName()
}), existingNames);
}
generateIdPreserveModules(preserveModulesRelativeDir, existingNames) {
- const sanitizedId = sanitizeFileName(this.orderedModules[0].id);
- this.id = makeUnique(normalize(isAbsolute(this.orderedModules[0].id)
+ const sanitizedId = index.sanitizeFileName(this.orderedModules[0].id);
+ return makeUnique(index.normalize(index.isAbsolute(this.orderedModules[0].id)
? relative(preserveModulesRelativeDir, sanitizedId)
: '_virtual/' + path.basename(sanitizedId)), existingNames);
}
generateInternalExports(options) {
if (this.facadeModule !== null)
@@ -14439,32 +14503,34 @@
this.exportNames[safeExportName] = variable;
}
}
}
getChunkName() {
- return this.chunkName || (this.chunkName = this.computeChunkName());
+ return this.name || (this.name = index.sanitizeFileName(this.getFallbackChunkName()));
}
getDynamicImportIds() {
return this.dynamicDependencies.map(chunk => chunk.id).filter(Boolean);
}
getExportNames() {
return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportNames).sort()));
}
getImportIds() {
- return this.dependencies.map(chunk => chunk.id);
+ return this.dependencies.map(chunk => chunk.id).filter(Boolean);
}
getRenderedHash() {
if (this.renderedHash)
return this.renderedHash;
if (!this.renderedSource)
return '';
const hash = _256();
+ const hashAugmentation = this.calculateHashAugmentation();
+ hash.update(hashAugmentation);
hash.update(this.renderedSource.toString());
hash.update(this.getExportNames()
.map(exportName => {
const variable = this.exportNames[exportName];
- return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
+ return `${index.relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
})
.join(','));
return (this.renderedHash = hash.digest('hex'));
}
getRenderedSourceLength() {
@@ -14707,16 +14773,13 @@
const dep = this.dependencies[i];
if (dep instanceof ExternalModule && !dep.renormalizeRenderPath)
continue;
const renderedDependency = this.renderedDeclarations.dependencies[i];
const depId = dep instanceof ExternalModule ? renderedDependency.id : dep.id;
- let relPath = this.id ? normalize(relative(path.dirname(this.id), depId)) : depId;
- if (!relPath.startsWith('../'))
- relPath = './' + relPath;
if (dep instanceof Chunk$1)
renderedDependency.namedExportsMode = dep.exportMode !== 'default';
- renderedDependency.id = relPath;
+ renderedDependency.id = this.getRelativePath(depId);
}
this.finaliseDynamicImports(format);
this.finaliseImportMetas(format);
const hasExports = this.renderedDeclarations.exports.length !== 0 ||
this.renderedDeclarations.dependencies.some(dep => (dep.reexports && dep.reexports.length !== 0));
@@ -14777,18 +14840,13 @@
file = path.resolve(options.sourcemapFile || options.file);
else if (options.dir)
file = path.resolve(options.dir, this.id);
else
file = path.resolve(this.id);
- if (this.graph.pluginDriver.hasLoadersOrTransforms) {
- const decodedMap = magicString.generateDecodedMap({});
- map = collapseSourcemaps(this, file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources);
- }
- else {
- map = magicString.generateMap({ file, includeContent: !options.sourcemapExcludeSources });
- }
- map.sources = map.sources.map(sourcePath => normalize(options.sourcemapPathTransform ? options.sourcemapPathTransform(sourcePath) : sourcePath));
+ const decodedMap = magicString.generateDecodedMap({});
+ map = collapseSourcemaps(this, file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources);
+ map.sources = map.sources.map(sourcePath => index.normalize(options.sourcemapPathTransform ? options.sourcemapPathTransform(sourcePath) : sourcePath));
timeEnd('sourcemap', 3);
}
if (options.compact !== true && code[code.length - 1] !== '\n')
code += '\n';
return { code, map };
@@ -14841,23 +14899,41 @@
dependency = depModule;
}
chunkDependencies.add(dependency);
}
}
- computeChunkName() {
- if (this.manualChunkAlias) {
- return sanitizeFileName(this.manualChunkAlias);
+ assignFacadeName({ fileName, name }, facadedModule) {
+ if (fileName) {
+ this.fileName = fileName;
}
- if (this.facadeModule !== null) {
- return sanitizeFileName(this.facadeModule.chunkAlias || getAliasName(this.facadeModule.id));
+ else {
+ this.name = index.sanitizeFileName(name || facadedModule.chunkName || index.getAliasName(facadedModule.id));
}
- for (const module of this.orderedModules) {
- if (module.chunkAlias)
- return sanitizeFileName(module.chunkAlias);
- }
- return 'chunk';
}
+ calculateHashAugmentation() {
+ const facadeModule = this.facadeModule;
+ const getChunkName = this.getChunkName.bind(this);
+ const preRenderedChunk = {
+ dynamicImports: this.getDynamicImportIds(),
+ exports: this.getExportNames(),
+ facadeModuleId: facadeModule && facadeModule.id,
+ imports: this.getImportIds(),
+ isDynamicEntry: facadeModule !== null && facadeModule.dynamicallyImportedBy.length > 0,
+ isEntry: facadeModule !== null && facadeModule.isEntryPoint,
+ modules: this.renderedModules,
+ get name() {
+ return getChunkName();
+ }
+ };
+ const hashAugmentation = this.graph.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [preRenderedChunk], (hashAugmentation, pluginHash) => {
+ if (pluginHash) {
+ hashAugmentation += pluginHash;
+ }
+ return hashAugmentation;
+ });
+ return hashAugmentation;
+ }
computeContentHashWithDependencies(addons, options) {
const hash = _256();
hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':'));
hash.update(options.format);
this.visitDependencies(dep => {
@@ -14874,27 +14950,19 @@
if (!resolution)
continue;
if (resolution instanceof Module) {
if (resolution.chunk !== this && isChunkRendered(resolution.chunk)) {
const resolutionChunk = resolution.facadeChunk || resolution.chunk;
- let relPath = normalize(relative(path.dirname(this.id), resolutionChunk.id));
- if (!relPath.startsWith('../'))
- relPath = './' + relPath;
- node.renderFinalResolution(code, `'${relPath}'`, format);
+ node.renderFinalResolution(code, `'${this.getRelativePath(resolutionChunk.id)}'`, format);
}
}
- else if (resolution instanceof ExternalModule) {
- let resolutionId = resolution.id;
- if (resolution.renormalizeRenderPath) {
- resolutionId = normalize(relative(path.dirname(this.id), resolution.renderPath));
- if (!resolutionId.startsWith('../'))
- resolutionId = './' + resolutionId;
- }
- node.renderFinalResolution(code, `'${resolutionId}'`, format);
- }
else {
- node.renderFinalResolution(code, resolution, format);
+ node.renderFinalResolution(code, resolution instanceof ExternalModule
+ ? `'${resolution.renormalizeRenderPath
+ ? this.getRelativePath(resolution.renderPath)
+ : resolution.id}'`
+ : resolution, format);
}
}
}
}
finaliseImportMetas(format) {
@@ -14909,10 +14977,11 @@
for (let exportName of this.getExportNames()) {
let exportChunk;
let importName;
let needsLiveBinding = false;
if (exportName[0] === '*') {
+ needsLiveBinding = options.externalLiveBindings !== false;
exportChunk = this.graph.moduleById.get(exportName.substr(1));
importName = exportName = '*';
}
else {
const variable = this.exportNames[exportName];
@@ -14926,11 +14995,11 @@
needsLiveBinding = variable.isReassigned;
}
else {
exportChunk = module;
importName = variable.name;
- needsLiveBinding = true;
+ needsLiveBinding = options.externalLiveBindings !== false;
}
}
let reexportDeclaration = reexportDeclarations.get(exportChunk);
if (!reexportDeclaration)
reexportDeclarations.set(exportChunk, (reexportDeclaration = []));
@@ -15025,10 +15094,23 @@
uninitialized
});
}
return exports;
}
+ getFallbackChunkName() {
+ if (this.manualChunkAlias) {
+ return this.manualChunkAlias;
+ }
+ if (this.fileName) {
+ return index.getAliasName(this.fileName);
+ }
+ return index.getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
+ }
+ getRelativePath(targetPath) {
+ const relativePath = index.normalize(relative(path.dirname(this.id), targetPath));
+ return relativePath.startsWith('../') ? relativePath : './' + relativePath;
+ }
inlineChunkDependencies(chunk, deep) {
for (const dep of chunk.dependencies) {
if (dep instanceof ExternalModule) {
if (this.dependencies.indexOf(dep) === -1)
this.dependencies.push(dep);
@@ -15253,127 +15335,40 @@
} while (((lastChunk = chunk), (chunk = nextChunk), (nextChunk = execGroup[++execGroupIndex]), chunk));
}
return chunks;
}
-const tt = acorn__default.tokTypes;
-const isIdentifierStart = acorn__default.isIdentifierStart;
-var acornBigint = function (Parser) {
- return class extends Parser {
- parseLiteral(value) {
- const node = super.parseLiteral(value);
- if (node.raw.charCodeAt(node.raw.length - 1) == 110)
- node.bigint = this.getNumberInput(node.start, node.end);
- return node;
- }
- readRadixNumber(radix) {
- let start = this.pos;
- this.pos += 2; // 0x
- let val = this.readInt(radix);
- if (val === null)
- this.raise(this.start + 2, `Expected number in radix ${radix}`);
- if (this.input.charCodeAt(this.pos) == 110) {
- let str = this.getNumberInput(start, this.pos);
- val = typeof BigInt !== "undefined" ? BigInt(str) : null;
- ++this.pos;
- }
- else if (isIdentifierStart(this.fullCharCodeAtPos()))
- this.raise(this.pos, "Identifier directly after number");
- return this.finishToken(tt.num, val);
- }
- readNumber(startsWithDot) {
- let start = this.pos;
- // Not an int
- if (startsWithDot)
- return super.readNumber(startsWithDot);
- // Legacy octal
- if (this.input.charCodeAt(start) === 48 && this.input.charCodeAt(start + 1) !== 110) {
- return super.readNumber(startsWithDot);
- }
- if (this.readInt(10) === null)
- this.raise(start, "Invalid number");
- // Not a BigInt, reset and parse again
- if (this.input.charCodeAt(this.pos) != 110) {
- this.pos = start;
- return super.readNumber(startsWithDot);
- }
- let str = this.getNumberInput(start, this.pos);
- let val = typeof BigInt !== "undefined" ? BigInt(str) : null;
- ++this.pos;
- return this.finishToken(tt.num, val);
- }
- // This is basically a hook for acorn-numeric-separator
- getNumberInput(start, end) {
- if (super.getNumberInput)
- return super.getNumberInput(start, end);
- return this.input.slice(start, end);
- }
- };
-};
-
-/* eslint-disable no-underscore-dangle */
-const DynamicImportKey = 'Import';
-// NOTE: This allows `yield import()` to parse correctly.
-acorn.tokTypes._import.startsExpr = true;
-function parseDynamicImport() {
- const node = this.startNode();
- this.next();
- if (this.type !== acorn.tokTypes.parenL) {
- this.unexpected();
- }
- return this.finishNode(node, DynamicImportKey);
-}
-function parenAfter() {
- return /^(\s|\/\/.*|\/\*[^]*?\*\/)*\(/.test(this.input.slice(this.pos));
-}
-function dynamicImport(Parser) {
- return class extends Parser {
- parseStatement(context, topLevel, exports) {
- if (this.type === acorn.tokTypes._import && parenAfter.call(this)) {
- return this.parseExpressionStatement(this.startNode(), this.parseExpression());
- }
- return super.parseStatement(context, topLevel, exports);
- }
- parseExprAtom(refDestructuringErrors) {
- if (this.type === acorn.tokTypes._import) {
- return parseDynamicImport.call(this);
- }
- return super.parseExprAtom(refDestructuringErrors);
- }
- };
-}
-
-const tt$1 = acorn__default.tokTypes;
+const tt = acorn.tokTypes;
const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
const nextTokenIsDot = parser => {
skipWhiteSpace.lastIndex = parser.pos;
let skip = skipWhiteSpace.exec(parser.input);
let next = parser.pos + skip[0].length;
return parser.input.slice(next, next + 1) === ".";
};
var acornImportMeta = function (Parser) {
return class extends Parser {
parseExprAtom(refDestructuringErrors) {
- if (this.type !== tt$1._import || !nextTokenIsDot(this))
+ if (this.type !== tt._import || !nextTokenIsDot(this))
return super.parseExprAtom(refDestructuringErrors);
if (!this.options.allowImportExportEverywhere && !this.inModule) {
this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
}
let node = this.startNode();
node.meta = this.parseIdent(true);
- this.expect(tt$1.dot);
+ this.expect(tt.dot);
node.property = this.parseIdent(true);
if (node.property.name !== "meta") {
this.raiseRecoverable(node.property.start, "The only valid meta property for import is import.meta");
}
if (this.containsEsc) {
this.raiseRecoverable(node.property.start, "\"meta\" in import.meta must not contain escape sequences");
}
return this.finishNode(node, "MetaProperty");
}
parseStatement(context, topLevel, exports) {
- if (this.type !== tt$1._import || !nextTokenIsDot(this)) {
+ if (this.type !== tt._import || !nextTokenIsDot(this)) {
return super.parseStatement(context, topLevel, exports);
}
let node = this.startNode();
let expr = this.parseExpression();
return this.parseExpressionStatement(node, expr);
@@ -15444,147 +15439,233 @@
trackedPaths.tracked = true;
return found;
}
}
-/*! *****************************************************************************
-Copyright (c) Microsoft Corporation. All rights reserved.
-Licensed under the Apache License, Version 2.0 (the "License"); you may not use
-this file except in compliance with the License. You may obtain a copy of the
-License at http://www.apache.org/licenses/LICENSE-2.0
+var BuildPhase;
+(function (BuildPhase) {
+ BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
+ BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
+ BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
+})(BuildPhase || (BuildPhase = {}));
-THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
-WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
-MERCHANTABLITY OR NON-INFRINGEMENT.
-
-See the Apache Version 2.0 License for specific language governing permissions
-and limitations under the License.
-***************************************************************************** */
-function __awaiter(thisArg, _arguments, P, generator) {
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try {
- step(generator.next(value));
+function generateAssetFileName(name, source, output) {
+ const emittedName = name || 'asset';
+ return makeUnique(renderNamePattern(output.assetFileNames, 'output.assetFileNames', {
+ hash() {
+ const hash = _256();
+ hash.update(emittedName);
+ hash.update(':');
+ hash.update(source);
+ return hash.digest('hex').substr(0, 8);
+ },
+ ext: () => path.extname(emittedName).substr(1),
+ extname: () => path.extname(emittedName),
+ name: () => emittedName.substr(0, emittedName.length - path.extname(emittedName).length)
+ }), output.bundle);
+}
+function reserveFileNameInBundle(fileName, bundle) {
+ if (fileName in bundle) {
+ return error(errFileNameConflict(fileName));
+ }
+ bundle[fileName] = FILE_PLACEHOLDER;
+}
+const FILE_PLACEHOLDER = {
+ isPlaceholder: true
+};
+function hasValidType(emittedFile) {
+ return (emittedFile &&
+ (emittedFile.type === 'asset' ||
+ emittedFile.type === 'chunk'));
+}
+function hasValidName(emittedFile) {
+ const validatedName = emittedFile.fileName || emittedFile.name;
+ return (!validatedName || (typeof validatedName === 'string' && index.isPlainPathFragment(validatedName)));
+}
+function getValidSource(source, emittedFile, fileReferenceId) {
+ if (typeof source !== 'string' && !Buffer.isBuffer(source)) {
+ const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
+ return error(errFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string of Buffer.`));
+ }
+ return source;
+}
+function getAssetFileName(file, referenceId) {
+ if (typeof file.fileName !== 'string') {
+ return error(errAssetNotFinalisedForFileName(file.name || referenceId));
+ }
+ return file.fileName;
+}
+function getChunkFileName(file) {
+ const fileName = file.fileName || (file.module && file.module.facadeChunk.id);
+ if (!fileName)
+ return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
+ return fileName;
+}
+class FileEmitter {
+ constructor(graph) {
+ this.filesByReferenceId = new Map();
+ // tslint:disable member-ordering
+ this.buildFilesByReferenceId = this.filesByReferenceId;
+ this.output = null;
+ this.emitFile = (emittedFile) => {
+ if (!hasValidType(emittedFile)) {
+ return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile &&
+ emittedFile.type}".`));
+ }
+ if (!hasValidName(emittedFile)) {
+ return error(errFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths and do not contain invalid characters, received "${emittedFile.fileName ||
+ emittedFile.name}".`));
+ }
+ if (emittedFile.type === 'chunk') {
+ return this.emitChunk(emittedFile);
+ }
+ else {
+ return this.emitAsset(emittedFile);
+ }
+ };
+ this.getFileName = (fileReferenceId) => {
+ const emittedFile = this.filesByReferenceId.get(fileReferenceId);
+ if (!emittedFile)
+ return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
+ if (emittedFile.type === 'chunk') {
+ return getChunkFileName(emittedFile);
+ }
+ else {
+ return getAssetFileName(emittedFile, fileReferenceId);
+ }
+ };
+ this.setAssetSource = (referenceId, requestedSource) => {
+ const consumedFile = this.filesByReferenceId.get(referenceId);
+ if (!consumedFile)
+ return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
+ if (consumedFile.type !== 'asset') {
+ return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
+ }
+ if (consumedFile.source !== undefined) {
+ return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
+ }
+ const source = getValidSource(requestedSource, consumedFile, referenceId);
+ if (this.output) {
+ this.finalizeAsset(consumedFile, source, referenceId, this.output);
+ }
+ else {
+ consumedFile.source = source;
+ }
+ };
+ this.graph = graph;
+ }
+ startOutput(outputBundle, assetFileNames) {
+ this.filesByReferenceId = new Map(this.buildFilesByReferenceId);
+ this.output = {
+ assetFileNames,
+ bundle: outputBundle
+ };
+ for (const emittedFile of this.filesByReferenceId.values()) {
+ if (emittedFile.fileName) {
+ reserveFileNameInBundle(emittedFile.fileName, this.output.bundle);
+ }
}
- catch (e) {
- reject(e);
- } }
- function rejected(value) { try {
- step(generator["throw"](value));
+ for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) {
+ if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
+ this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.output);
+ }
}
- catch (e) {
- reject(e);
- } }
- function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-}
-
-function addWithNewReferenceId(item, idMap, hashBase) {
- let referenceId;
- do {
- const hash = _256();
- if (referenceId) {
- hash.update(referenceId);
+ }
+ assertAssetsFinalized() {
+ for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) {
+ if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
+ error(errNoAssetSourceSet(emittedFile.name || referenceId));
}
- else {
- hash.update(hashBase);
+ }
+ emitAsset(emittedAsset) {
+ const source = typeof emittedAsset.source !== 'undefined'
+ ? getValidSource(emittedAsset.source, emittedAsset, null)
+ : undefined;
+ const consumedAsset = {
+ fileName: emittedAsset.fileName,
+ name: emittedAsset.name,
+ source,
+ type: 'asset'
+ };
+ const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
+ if (this.output) {
+ if (emittedAsset.fileName) {
+ reserveFileNameInBundle(emittedAsset.fileName, this.output.bundle);
+ }
+ if (source !== undefined) {
+ this.finalizeAsset(consumedAsset, source, referenceId, this.output);
+ }
}
- referenceId = hash.digest('hex').substr(0, 8);
- } while (idMap.has(referenceId));
- idMap.set(referenceId, item);
- return referenceId;
-}
-
-function getAssetFileName(asset, existingNames, assetFileNames) {
- if (asset.source === undefined)
- error(errNoAssetSourceSet(asset));
- if (asset.fileName)
- return asset.fileName;
- return makeUnique(renderNamePattern(assetFileNames, 'assetFileNames', name => {
- switch (name) {
- case 'hash':
- const hash = _256();
- hash.update(name);
- hash.update(':');
- hash.update(asset.source);
- return hash.digest('hex').substr(0, 8);
- case 'name':
- return asset.name.substr(0, asset.name.length - path.extname(asset.name).length);
- case 'extname':
- return path.extname(asset.name);
- case 'ext':
- return path.extname(asset.name).substr(1);
+ return referenceId;
+ }
+ emitChunk(emittedChunk) {
+ if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
+ error(errInvalidRollupPhaseForChunkEmission());
}
- return undefined;
- }), existingNames);
-}
-function createAssetPluginHooks(assetsByReferenceId, outputBundle, assetFileNames) {
- return {
- emitAsset(name, source) {
- if (typeof name !== 'string' || !isPlainName(name))
- error(errInvalidAssetName(name));
- const asset = { name, source: source, fileName: undefined };
- if (outputBundle && source !== undefined)
- finaliseAsset(asset, outputBundle, assetFileNames);
- return addWithNewReferenceId(asset, assetsByReferenceId, name);
- },
- setAssetSource(assetReferenceId, source) {
- const asset = assetsByReferenceId.get(assetReferenceId);
- if (!asset)
- return error(errAssetReferenceIdNotFoundForSetSource(assetReferenceId));
- if (asset.source !== undefined)
- return error(errAssetSourceAlreadySet(asset));
- if (typeof source !== 'string' && !source)
- return error(errAssetSourceMissingForSetSource(asset));
- asset.source = source;
- if (outputBundle)
- finaliseAsset(asset, outputBundle, assetFileNames);
- },
- getAssetFileName(assetReferenceId) {
- const asset = assetsByReferenceId.get(assetReferenceId);
- if (!asset)
- return error(errAssetReferenceIdNotFoundForFilename(assetReferenceId));
- if ((asset).fileName === undefined)
- return error(errAssetNotFinalisedForFileName(asset));
- return (asset).fileName;
+ if (typeof emittedChunk.id !== 'string') {
+ return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
}
- };
-}
-function finaliseAsset(asset, outputBundle, assetFileNames) {
- const fileName = getAssetFileName(asset, outputBundle, assetFileNames);
- asset.fileName = fileName;
- outputBundle[fileName] = {
- fileName,
- isAsset: true,
- source: asset.source
- };
-}
-function createTransformEmitAsset(assetsByReferenceId, emitAsset) {
- const assets = [];
- return {
- assets,
- emitAsset: (name, source) => {
- const assetReferenceId = emitAsset(name, source);
- const asset = assetsByReferenceId.get(assetReferenceId);
- assets.push({
- fileName: undefined,
- name: asset.name,
- source: asset.source
- });
- return assetReferenceId;
+ const consumedChunk = {
+ fileName: emittedChunk.fileName,
+ module: null,
+ name: emittedChunk.name || emittedChunk.id,
+ type: 'chunk'
+ };
+ this.graph.moduleLoader
+ .addEntryModules([
+ {
+ fileName: emittedChunk.fileName || null,
+ id: emittedChunk.id,
+ name: emittedChunk.name || null
+ }
+ ], false)
+ .then(({ newEntryModules: [module] }) => {
+ consumedChunk.module = module;
+ })
+ .catch(() => {
+ // Avoid unhandled Promise rejection as the error will be thrown later
+ // once module loading has finished
+ });
+ return this.assignReferenceId(consumedChunk, emittedChunk.id);
+ }
+ assignReferenceId(file, idBase) {
+ let referenceId;
+ do {
+ const hash = _256();
+ if (referenceId) {
+ hash.update(referenceId);
+ }
+ else {
+ hash.update(idBase);
+ }
+ referenceId = hash.digest('hex').substr(0, 8);
+ } while (this.filesByReferenceId.has(referenceId));
+ this.filesByReferenceId.set(referenceId, file);
+ return referenceId;
+ }
+ finalizeAsset(consumedFile, source, referenceId, output) {
+ const fileName = consumedFile.fileName ||
+ this.findExistingAssetFileNameWithSource(output.bundle, source) ||
+ generateAssetFileName(consumedFile.name, source, output);
+ // We must not modify the original assets to avoid interaction between outputs
+ const assetWithFileName = Object.assign({}, consumedFile, { source, fileName });
+ this.filesByReferenceId.set(referenceId, assetWithFileName);
+ output.bundle[fileName] = { fileName, isAsset: true, source };
+ }
+ findExistingAssetFileNameWithSource(bundle, source) {
+ for (const fileName of Object.keys(bundle)) {
+ const outputFile = bundle[fileName];
+ if (outputFile.isAsset &&
+ (Buffer.isBuffer(source) && Buffer.isBuffer(outputFile.source)
+ ? source.equals(outputFile.source)
+ : source === outputFile.source))
+ return fileName;
}
- };
+ return null;
+ }
}
-var BuildPhase;
-(function (BuildPhase) {
- BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
- BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
- BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
-})(BuildPhase || (BuildPhase = {}));
-
const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
const deprecatedHooks = [
{ active: true, deprecated: 'ongenerate', replacement: 'generateBundle' },
{ active: true, deprecated: 'onwrite', replacement: 'generateBundle/writeBundle' },
{ active: true, deprecated: 'transformBundle', replacement: 'renderChunk' },
@@ -15601,32 +15682,57 @@
}, active);
}
}
}
}
+function throwPluginError(err, plugin, { hook, id } = {}) {
+ if (typeof err === 'string')
+ err = { message: err };
+ if (err.code && err.code !== Errors.PLUGIN_ERROR) {
+ err.pluginCode = err.code;
+ }
+ err.code = Errors.PLUGIN_ERROR;
+ err.plugin = plugin;
+ if (hook) {
+ err.hook = hook;
+ }
+ if (id) {
+ err.id = id;
+ }
+ return error(err);
+}
function createPluginDriver(graph, options, pluginCache, watcher) {
warnDeprecatedHooks(options.plugins, graph);
+ function getDeprecatedHookHandler(handler, handlerName, newHandlerName, pluginName, acitveDeprecation) {
+ let deprecationWarningShown = false;
+ return ((...args) => {
+ if (!deprecationWarningShown) {
+ deprecationWarningShown = true;
+ graph.warnDeprecation({
+ message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
+ plugin: pluginName
+ }, acitveDeprecation);
+ }
+ return handler(...args);
+ });
+ }
const plugins = [
...options.plugins,
getRollupDefaultPlugin(options.preserveSymlinks)
];
- const { emitAsset, getAssetFileName, setAssetSource } = createAssetPluginHooks(graph.assetsById);
+ const fileEmitter = new FileEmitter(graph);
const existingPluginKeys = new Set();
- let hasLoadersOrTransforms = false;
const pluginContexts = plugins.map((plugin, pidx) => {
let cacheable = true;
if (typeof plugin.cacheKey !== 'string') {
if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) || existingPluginKeys.has(plugin.name)) {
cacheable = false;
}
else {
existingPluginKeys.add(plugin.name);
}
}
- if (!hasLoadersOrTransforms &&
- (plugin.load || plugin.transform || plugin.transformBundle || plugin.transformChunk))
- hasLoadersOrTransforms = true;
let cacheInstance;
if (!pluginCache) {
cacheInstance = noCache;
}
else if (cacheable) {
@@ -15641,29 +15747,19 @@
if (graph.phase >= BuildPhase.GENERATE)
this.error(errInvalidRollupPhaseForAddWatchFile());
graph.watchFiles[id] = true;
},
cache: cacheInstance,
- emitAsset,
- emitChunk(id, options) {
- if (graph.phase > BuildPhase.LOAD_AND_PARSE)
- this.error(errInvalidRollupPhaseForEmitChunk());
- return pluginDriver.emitChunk(id, options);
- },
+ emitAsset: getDeprecatedHookHandler((name, source) => fileEmitter.emitFile({ type: 'asset', name, source }), 'emitAsset', 'emitFile', plugin.name, false),
+ emitChunk: getDeprecatedHookHandler((id, options) => fileEmitter.emitFile({ type: 'chunk', id, name: options && options.name }), 'emitChunk', 'emitFile', plugin.name, false),
+ emitFile: fileEmitter.emitFile,
error(err) {
- if (typeof err === 'string')
- err = { message: err };
- if (err.code)
- err.pluginCode = err.code;
- err.code = 'PLUGIN_ERROR';
- err.plugin = plugin.name;
- return error(err);
+ return throwPluginError(err, plugin.name);
},
- getAssetFileName: getAssetFileName,
- getChunkFileName(chunkReferenceId) {
- return graph.moduleLoader.getChunkFileName(chunkReferenceId);
- },
+ getAssetFileName: getDeprecatedHookHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, false),
+ getChunkFileName: getDeprecatedHookHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, false),
+ getFileName: fileEmitter.getFileName,
getModuleInfo(moduleId) {
const foundModule = graph.moduleById.get(moduleId);
if (foundModule == null) {
throw new Error(`Unable to find module ${moduleId}`);
}
@@ -15675,49 +15771,25 @@
: foundModule.sources.map(id => foundModule.resolvedIds[id].id),
isEntry: foundModule instanceof Module && foundModule.isEntryPoint,
isExternal: foundModule instanceof ExternalModule
};
},
- isExternal: (() => {
- let deprecationWarningShown = false;
- return (id, parentId, isResolved = false) => {
- if (!deprecationWarningShown) {
- deprecationWarningShown = true;
- graph.warnDeprecation({
- message: `The "this.isExternal" plugin context function used by plugin ${plugin.name} is deprecated. The "this.resolve" plugin context function should be used instead.`,
- plugin: plugin.name
- }, false);
- }
- return graph.moduleLoader.isExternal(id, parentId, isResolved);
- };
- })(),
+ isExternal: getDeprecatedHookHandler((id, parentId, isResolved = false) => graph.moduleLoader.isExternal(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, false),
meta: {
- rollupVersion: version
+ rollupVersion: index.version
},
get moduleIds() {
return graph.moduleById.keys();
},
parse: graph.contextParse,
resolve(source, importer, options) {
return graph.moduleLoader.resolveId(source, importer, options && options.skipSelf ? pidx : null);
},
- resolveId: (() => {
- let deprecationWarningShown = false;
- return (source, importer) => {
- if (!deprecationWarningShown) {
- deprecationWarningShown = true;
- graph.warnDeprecation({
- message: `The "this.resolveId" plugin context function used by plugin ${plugin.name} is deprecated. The "this.resolve" plugin context function should be used instead.`,
- plugin: plugin.name
- }, false);
- }
- return graph.moduleLoader
- .resolveId(source, importer)
- .then(resolveId => resolveId && resolveId.id);
- };
- })(),
- setAssetSource,
+ resolveId: getDeprecatedHookHandler((source, importer) => graph.moduleLoader
+ .resolveId(source, importer)
+ .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, false),
+ setAssetSource: fileEmitter.setAssetSource,
warn(warning) {
if (typeof warning === 'string')
warning = { message: warning };
if (warning.code)
warning.pluginCode = warning.code;
@@ -15766,22 +15838,12 @@
});
}
return hook.apply(context, args);
}
catch (err) {
- if (typeof err === 'string')
- err = { message: err };
- if (err.code !== 'PLUGIN_ERROR') {
- if (err.code)
- err.pluginCode = err.code;
- err.code = 'PLUGIN_ERROR';
- }
- err.plugin = plugin.name;
- err.hook = hookName;
- error(err);
+ return throwPluginError(err, plugin.name, { hook: hookName });
}
- return undefined;
}
function runHook(hookName, args, pluginIndex, permitValues = false, hookContext) {
const plugin = plugins[pluginIndex];
let context = pluginContexts[pluginIndex];
const hook = plugin[hookName];
@@ -15803,33 +15865,18 @@
message: `Error running plugin hook ${hookName} for ${plugin.name}, expected a function hook.`
});
}
return hook.apply(context, args);
})
- .catch(err => {
- if (typeof err === 'string')
- err = { message: err };
- if (err.code !== 'PLUGIN_ERROR') {
- if (err.code)
- err.pluginCode = err.code;
- err.code = 'PLUGIN_ERROR';
- }
- err.plugin = plugin.name;
- err.hook = hookName;
- error(err);
- });
+ .catch(err => throwPluginError(err, plugin.name, { hook: hookName }));
}
const pluginDriver = {
- emitAsset,
- emitChunk(id, options) {
- return graph.moduleLoader.addEntryModuleAndGetReferenceId({
- alias: (options && options.name) || null,
- unresolvedId: id
- });
+ emitFile: fileEmitter.emitFile,
+ finaliseAssets() {
+ fileEmitter.assertAssetsFinalized();
},
- getAssetFileName: getAssetFileName,
- hasLoadersOrTransforms,
+ getFileName: fileEmitter.getFileName,
// chains, ignores returns
hookSeq(name, args, hookContext) {
let promise = Promise.resolve();
for (let i = 0; i < plugins.length; i++)
promise = promise.then(() => runHook(name, args, i, false, hookContext));
@@ -15905,10 +15952,22 @@
return value;
return hookPromise.then((result) => reduce.call(pluginContexts[i], value, result, plugins[i]));
});
}
return promise;
+ },
+ // chains, reduces returns of type R, to type T, handling the reduced value separately. permits hooks as values.
+ hookReduceValueSync(name, initial, args, reduce, hookContext) {
+ let acc = initial;
+ for (let i = 0; i < plugins.length; i++) {
+ const result = runHookSync(name, args, i, true, hookContext);
+ acc = reduce.call(pluginContexts[i], acc, result, plugins[i]);
+ }
+ return acc;
+ },
+ startOutput(outputBundle, assetFileNames) {
+ fileEmitter.startOutput(outputBundle, assetFileNames);
}
};
return pluginDriver;
}
function createPluginCache(cache) {
@@ -16001,16 +16060,14 @@
function transform(graph, source, module) {
const id = module.id;
const sourcemapChain = [];
let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
- const baseEmitAsset = graph.pluginDriver.emitAsset;
const originalCode = source.code;
let ast = source.ast;
- let transformDependencies;
- let emittedAssets;
- const emittedChunks = [];
+ const transformDependencies = [];
+ const emittedFiles = [];
let customTransformCache = false;
let moduleSideEffects = null;
let trackedPluginCache;
let curPlugin;
const curSource = source.code;
@@ -16019,29 +16076,23 @@
if (!customTransformCache && trackedPluginCache.used)
customTransformCache = true;
if (customTransformCache) {
if (result && typeof result === 'object' && Array.isArray(result.dependencies)) {
for (const dep of result.dependencies) {
- const depId = path.resolve(path.dirname(id), dep);
- if (!graph.watchFiles[depId])
- graph.watchFiles[depId] = true;
+ graph.watchFiles[path.resolve(path.dirname(id), dep)] = true;
}
}
}
else {
- // assets/chunks emitted by a transform hook need to be emitted again if the hook is skipped
- if (emittedAssets.length)
- module.transformAssets = emittedAssets;
- if (emittedChunks.length)
- module.transformChunks = emittedChunks;
+ // files emitted by a transform hook need to be emitted again if the hook is skipped
+ if (emittedFiles.length)
+ module.transformFiles = emittedFiles;
if (result && typeof result === 'object' && Array.isArray(result.dependencies)) {
// not great, but a useful way to track this without assuming WeakMap
if (!curPlugin.warnedTransformDependencies)
graph.warnDeprecation(`Returning "dependencies" from the "transform" hook as done by plugin ${plugin.name} is deprecated. The "this.addWatchFile" plugin context function should be used instead.`, true);
curPlugin.warnedTransformDependencies = true;
- if (!transformDependencies)
- transformDependencies = [];
for (const dep of result.dependencies)
transformDependencies.push(path.resolve(path.dirname(id), dep));
}
}
if (typeof result === 'string') {
@@ -16076,12 +16127,10 @@
curPlugin = plugin;
if (curPlugin.cacheKey)
customTransformCache = true;
else
trackedPluginCache = trackPluginCache(pluginContext.cache);
- let emitAsset;
- ({ assets: emittedAssets, emitAsset } = createTransformEmitAsset(graph.assetsById, baseEmitAsset));
return Object.assign({}, pluginContext, { cache: trackedPluginCache ? trackedPluginCache.cache : pluginContext.cache, warn(warning, pos) {
if (typeof warning === 'string')
warning = { message: warning };
if (pos)
augmentCodeLocation(warning, pos, curSource, id);
@@ -16096,28 +16145,35 @@
augmentCodeLocation(err, pos, curSource, id);
err.id = id;
err.hook = 'transform';
return pluginContext.error(err);
},
- emitAsset,
+ emitAsset(name, source) {
+ const emittedFile = { type: 'asset', name, source };
+ emittedFiles.push(Object.assign({}, emittedFile));
+ return graph.pluginDriver.emitFile(emittedFile);
+ },
emitChunk(id, options) {
- emittedChunks.push({ id, options });
- return graph.pluginDriver.emitChunk(id, options);
+ const emittedFile = { type: 'chunk', id, name: options && options.name };
+ emittedFiles.push(Object.assign({}, emittedFile));
+ return graph.pluginDriver.emitFile(emittedFile);
},
+ emitFile(emittedFile) {
+ emittedFiles.push(emittedFile);
+ return graph.pluginDriver.emitFile(emittedFile);
+ },
addWatchFile(id) {
- if (!transformDependencies)
- transformDependencies = [];
transformDependencies.push(id);
pluginContext.addWatchFile(id);
},
setAssetSource(assetReferenceId, source) {
pluginContext.setAssetSource(assetReferenceId, source);
if (!customTransformCache && !setAssetSourceErr) {
try {
this.error({
code: 'INVALID_SETASSETSOURCE',
- message: `setAssetSource cannot be called in transform for caching reasons. Use emitAsset with a source, or call setAssetSource in another hook.`
+ message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
});
}
catch (err) {
setAssetSourceErr = err;
}
@@ -16134,21 +16190,11 @@
sourcemapChain.length = 0;
}
return new SourceMap(Object.assign({}, combinedMap, { file: null, sourcesContent: combinedMap.sourcesContent }));
} });
})
- .catch(err => {
- if (typeof err === 'string')
- err = { message: err };
- if (err.code !== 'PLUGIN_ERROR') {
- if (err.code)
- err.pluginCode = err.code;
- err.code = 'PLUGIN_ERROR';
- }
- err.id = id;
- error(err);
- })
+ .catch(err => throwPluginError(err, curPlugin.name, { hook: 'transform', id }))
.then(code => {
if (!customTransformCache && setAssetSourceErr)
throw setAssetSourceErr;
return {
ast: ast,
@@ -16162,11 +16208,11 @@
};
});
}
function normalizeRelativeExternalId(importer, source) {
- return isRelative(source) ? path.resolve(importer, '..', source) : source;
+ return index.isRelative(source) ? path.resolve(importer, '..', source) : source;
}
function getIdMatcher(option) {
if (option === true) {
return () => true;
}
@@ -16199,110 +16245,95 @@
const isPureExternalModule = getIdMatcher(pureExternalModules);
return (id, external) => !(external && isPureExternalModule(id));
}
class ModuleLoader {
constructor(graph, modulesById, pluginDriver, external, getManualChunk, moduleSideEffects, pureExternalModules) {
- this.entriesByReferenceId = new Map();
- this.entryModules = [];
+ this.indexedEntryModules = [];
this.latestLoadModulesPromise = Promise.resolve();
this.manualChunkModules = {};
- this.loadEntryModule = ({ alias, unresolvedId }, isEntry) => this.pluginDriver.hookFirst('resolveId', [unresolvedId, undefined]).then(resolveIdResult => {
+ this.nextEntryModuleIndex = 0;
+ this.loadEntryModule = (unresolvedId, isEntry) => this.pluginDriver.hookFirst('resolveId', [unresolvedId, undefined]).then(resolveIdResult => {
if (resolveIdResult === false ||
(resolveIdResult && typeof resolveIdResult === 'object' && resolveIdResult.external)) {
return error(errEntryCannotBeExternal(unresolvedId));
}
const id = resolveIdResult && typeof resolveIdResult === 'object'
? resolveIdResult.id
: resolveIdResult;
if (typeof id === 'string') {
- return this.fetchModule(id, undefined, true, isEntry).then(module => {
- if (alias !== null) {
- if (module.chunkAlias !== null && module.chunkAlias !== alias) {
- return error(errCannotAssignModuleToChunk(module.id, alias, module.chunkAlias));
- }
- module.chunkAlias = alias;
- }
- return module;
- });
+ return this.fetchModule(id, undefined, true, isEntry);
}
return error(errUnresolvedEntry(unresolvedId));
});
this.graph = graph;
this.modulesById = modulesById;
this.pluginDriver = pluginDriver;
this.isExternal = getIdMatcher(external);
this.hasModuleSideEffects = getHasModuleSideEffects(moduleSideEffects, pureExternalModules, graph);
this.getManualChunk = typeof getManualChunk === 'function' ? getManualChunk : () => null;
}
- addEntryModuleAndGetReferenceId(unresolvedEntryModule) {
- const entryRecord = {
- module: null,
- name: unresolvedEntryModule.unresolvedId
- };
- const referenceId = addWithNewReferenceId(entryRecord, this.entriesByReferenceId, unresolvedEntryModule.unresolvedId);
- this.addEntryModules([unresolvedEntryModule], false)
- .then(({ newEntryModules: [module] }) => {
- entryRecord.module = module;
- })
- .catch(() => {
- // Avoid unhandled Promise rejection as the error will be thrown later
- // once module loading has finished
- });
- return referenceId;
- }
addEntryModules(unresolvedEntryModules, isUserDefined) {
- const loadNewEntryModulesPromise = Promise.all(unresolvedEntryModules.map(unresolvedEntryModule => this.loadEntryModule(unresolvedEntryModule, true))).then(entryModules => {
+ const firstEntryModuleIndex = this.nextEntryModuleIndex;
+ this.nextEntryModuleIndex += unresolvedEntryModules.length;
+ const loadNewEntryModulesPromise = Promise.all(unresolvedEntryModules.map(({ fileName, id, name }) => this.loadEntryModule(id, true).then(module => {
+ if (fileName !== null) {
+ module.chunkFileNames.add(fileName);
+ }
+ else if (name !== null) {
+ if (module.chunkName === null) {
+ module.chunkName = name;
+ }
+ if (isUserDefined) {
+ module.userChunkNames.add(name);
+ }
+ }
+ return module;
+ }))).then(entryModules => {
+ let moduleIndex = firstEntryModuleIndex;
for (const entryModule of entryModules) {
entryModule.isUserDefinedEntryPoint = entryModule.isUserDefinedEntryPoint || isUserDefined;
- const existingEntryModule = this.entryModules.find(module => module.id === entryModule.id);
- if (!existingEntryModule) {
- this.entryModules.push(entryModule);
+ const existingIndexModule = this.indexedEntryModules.find(indexedModule => indexedModule.module.id === entryModule.id);
+ if (!existingIndexModule) {
+ this.indexedEntryModules.push({ module: entryModule, index: moduleIndex });
}
+ else {
+ existingIndexModule.index = Math.min(existingIndexModule.index, moduleIndex);
+ }
+ moduleIndex++;
}
+ this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
return entryModules;
});
return this.awaitLoadModulesPromise(loadNewEntryModulesPromise).then(newEntryModules => ({
- entryModules: this.entryModules,
+ entryModules: this.indexedEntryModules.map(({ module }) => module),
manualChunkModulesByAlias: this.manualChunkModules,
newEntryModules
}));
}
addManualChunks(manualChunks) {
const unresolvedManualChunks = [];
for (const alias of Object.keys(manualChunks)) {
const manualChunkIds = manualChunks[alias];
- for (const unresolvedId of manualChunkIds) {
- unresolvedManualChunks.push({ alias: null, unresolvedId, manualChunkAlias: alias });
+ for (const id of manualChunkIds) {
+ unresolvedManualChunks.push({ id, alias });
}
}
- const loadNewManualChunkModulesPromise = Promise.all(unresolvedManualChunks.map(unresolvedManualChunk => this.loadEntryModule(unresolvedManualChunk, false))).then(manualChunkModules => {
+ const loadNewManualChunkModulesPromise = Promise.all(unresolvedManualChunks.map(({ id }) => this.loadEntryModule(id, false))).then(manualChunkModules => {
for (let index = 0; index < manualChunkModules.length; index++) {
- this.addToManualChunk(unresolvedManualChunks[index].manualChunkAlias, manualChunkModules[index]);
+ this.addModuleToManualChunk(unresolvedManualChunks[index].alias, manualChunkModules[index]);
}
});
return this.awaitLoadModulesPromise(loadNewManualChunkModulesPromise);
}
- getChunkFileName(referenceId) {
- const entryRecord = this.entriesByReferenceId.get(referenceId);
- if (!entryRecord)
- return error(errChunkReferenceIdNotFoundForFilename(referenceId));
- const fileName = entryRecord.module &&
- (entryRecord.module.facadeChunk
- ? entryRecord.module.facadeChunk.id
- : entryRecord.module.chunk.id);
- if (!fileName)
- return error(errChunkNotGeneratedForFileName(entryRecord));
- return fileName;
- }
resolveId(source, importer, skip) {
return __awaiter(this, void 0, void 0, function* () {
return this.normalizeResolveIdResult(this.isExternal(source, importer, false)
? false
: yield this.pluginDriver.hookFirst('resolveId', [source, importer], null, skip), importer, source);
});
}
- addToManualChunk(alias, module) {
+ addModuleToManualChunk(alias, module) {
if (module.manualChunkAlias !== null && module.manualChunkAlias !== alias) {
error(errCannotAssignModuleToChunk(module.id, alias, module.manualChunkAlias));
}
module.manualChunkAlias = alias;
if (!this.manualChunkModules[alias]) {
@@ -16324,19 +16355,19 @@
});
};
return getCombinedPromise().then(() => loadNewModulesPromise);
}
fetchAllDependencies(module) {
- const fetchDynamicImportsPromise = Promise.all(module.getDynamicImportExpressions().map((specifier, index) => this.resolveDynamicImport(module, specifier, module.id).then(resolvedId => {
+ const fetchDynamicImportsPromise = Promise.all(module.getDynamicImportExpressions().map((specifier, index$1) => this.resolveDynamicImport(module, specifier, module.id).then(resolvedId => {
if (resolvedId === null)
return;
- const dynamicImport = module.dynamicImports[index];
+ const dynamicImport = module.dynamicImports[index$1];
if (typeof resolvedId === 'string') {
dynamicImport.resolution = resolvedId;
return;
}
- return this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId).then(module => {
+ return this.fetchResolvedDependency(index.relativeId(resolvedId.id), module.id, resolvedId).then(module => {
dynamicImport.resolution = module;
});
})));
fetchDynamicImportsPromise.catch(() => { });
return Promise.all(module.sources.map(source => this.resolveAndFetchDependency(module, source))).then(() => fetchDynamicImportsPromise);
@@ -16351,11 +16382,11 @@
}
const module = new Module(this.graph, id, moduleSideEffects, isEntry);
this.modulesById.set(id, module);
const manualChunkAlias = this.getManualChunk(id);
if (typeof manualChunkAlias === 'string') {
- this.addToManualChunk(manualChunkAlias, module);
+ this.addModuleToManualChunk(manualChunkAlias, module);
}
timeStart('load modules', 3);
return Promise.resolve(this.pluginDriver.hookFirst('load', [id]))
.catch((err) => {
timeEnd('load modules', 3);
@@ -16377,18 +16408,14 @@
.then(sourceDescription => {
const cachedModule = this.graph.cachedModules.get(id);
if (cachedModule &&
!cachedModule.customTransformCache &&
cachedModule.originalCode === sourceDescription.code) {
- if (cachedModule.transformAssets) {
- for (const { name, source } of cachedModule.transformAssets)
- this.pluginDriver.emitAsset(name, source);
+ if (cachedModule.transformFiles) {
+ for (const emittedFile of cachedModule.transformFiles)
+ this.pluginDriver.emitFile(emittedFile);
}
- if (cachedModule.transformChunks) {
- for (const { id, options } of cachedModule.transformChunks)
- this.pluginDriver.emitChunk(id, options);
- }
return cachedModule;
}
if (typeof sourceDescription.moduleSideEffects === 'boolean') {
module.moduleSideEffects = sourceDescription.moduleSideEffects;
}
@@ -16436,11 +16463,11 @@
return this.fetchModule(resolvedId.id, importer, resolvedId.moduleSideEffects, false);
}
}
handleMissingImports(resolvedId, source, importer) {
if (resolvedId === null) {
- if (isRelative(source)) {
+ if (index.isRelative(source)) {
error(errUnresolvedImport(source, importer));
}
this.graph.warn(errUnresolvedImportTreatedAsExternal(source, importer));
return {
external: true,
@@ -16619,32 +16646,30 @@
warned[str] = true;
};
}
function normalizeEntryModules(entryModules) {
if (typeof entryModules === 'string') {
- return [{ alias: null, unresolvedId: entryModules }];
+ return [{ fileName: null, name: null, id: entryModules }];
}
if (Array.isArray(entryModules)) {
- return entryModules.map(unresolvedId => ({ alias: null, unresolvedId }));
+ return entryModules.map(id => ({ fileName: null, name: null, id }));
}
- return Object.keys(entryModules).map(alias => ({
- alias,
- unresolvedId: entryModules[alias]
+ return Object.keys(entryModules).map(name => ({
+ fileName: null,
+ id: entryModules[name],
+ name
}));
}
class Graph {
constructor(options, watcher) {
- this.assetsById = new Map();
- this.curChunkIndex = 0;
this.moduleById = new Map();
this.needsTreeshakingPass = false;
this.phase = BuildPhase.LOAD_AND_PARSE;
this.watchFiles = Object.create(null);
this.externalModules = [];
this.modules = [];
this.onwarn = options.onwarn || makeOnwarn();
- this.curChunkIndex = 0;
this.deoptimizationTracker = new EntityPathTracker();
this.cachedModules = new Map();
if (options.cache) {
if (options.cache.modules)
for (const module of options.cache.modules)
@@ -16705,15 +16730,13 @@
this.getModuleContext = id => moduleContext.get(id) || this.context;
}
else {
this.getModuleContext = () => this.context;
}
- this.acornOptions = options.acorn || {};
+ this.acornOptions = options.acorn ? Object.assign({}, options.acorn) : {};
const acornPluginsToInject = [];
- acornPluginsToInject.push(dynamicImport);
acornPluginsToInject.push(acornImportMeta);
- acornPluginsToInject.push(acornBigint);
if (options.experimentalTopLevelAwait) {
this.acornOptions.allowAwaitOutsideFunction = true;
}
const acornInjectPlugins = options.acornInjectPlugins;
acornPluginsToInject.push(...(Array.isArray(acornInjectPlugins)
@@ -16816,27 +16839,17 @@
chunk.link();
}
chunks = chunks.filter(isChunkRendered);
const facades = [];
for (const chunk of chunks) {
- for (const facade of chunk.generateFacades()) {
- facades.push(facade);
- }
+ facades.push(...chunk.generateFacades());
}
timeEnd('generate chunks', 2);
this.phase = BuildPhase.GENERATE;
return chunks.concat(facades);
});
}
- finaliseAssets(assetFileNames) {
- const outputBundle = Object.create(null);
- this.assetsById.forEach(asset => {
- if (asset.source !== undefined)
- finaliseAsset(asset, outputBundle, assetFileNames);
- });
- return outputBundle;
- }
getCache() {
// handle plugin cache eviction
for (const name in this.pluginCache) {
const cache = this.pluginCache[name];
let allDeleted = true;
@@ -16877,11 +16890,11 @@
warning.toString = () => {
let str = '';
if (warning.plugin)
str += `(${warning.plugin} plugin) `;
if (warning.loc)
- str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
+ str += `${index.relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
str += warning.message;
return str;
};
this.onwarn(warning);
}
@@ -16918,11 +16931,11 @@
const importDescription = module.importDescriptions[importName];
if (importDescription.name !== '*' &&
!importDescription.module.getVariableForExportName(importDescription.name)) {
module.warn({
code: 'NON_EXISTENT_EXPORT',
- message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
+ message: `Non-existent export '${importDescription.name}' is imported from ${index.relativeId(importDescription.module.id)}`,
name: importDescription.name,
source: importDescription.module.id
}, importDescription.start);
}
}
@@ -16968,41 +16981,41 @@
\tError Message: ${err.message}`
});
});
}
-function assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons) {
- const usedIds = {};
- const [entryChunks, otherChunks] = chunks.reduce(([entryChunks, otherChunks], chunk) => {
+function assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons, bundle) {
+ const entryChunks = [];
+ const otherChunks = [];
+ for (const chunk of chunks) {
(chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
? entryChunks
: otherChunks).push(chunk);
- return [entryChunks, otherChunks];
- }, [[], []]);
+ }
// make sure entry chunk names take precedence with regard to deconflicting
const chunksForNaming = entryChunks.concat(otherChunks);
- for (let i = 0; i < chunksForNaming.length; i++) {
- const chunk = chunksForNaming[i];
+ for (const chunk of chunksForNaming) {
+ const facadeModule = chunk.facadeModule;
if (outputOptions.file) {
chunk.id = path.basename(outputOptions.file);
}
else if (inputOptions.preserveModules) {
- chunk.generateIdPreserveModules(inputBase, usedIds);
+ chunk.id = chunk.generateIdPreserveModules(inputBase, bundle);
}
else {
let pattern, patternName;
- if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
+ if (facadeModule && facadeModule.isUserDefinedEntryPoint) {
pattern = outputOptions.entryFileNames || '[name].js';
patternName = 'output.entryFileNames';
}
else {
pattern = outputOptions.chunkFileNames || '[name]-[hash].js';
patternName = 'output.chunkFileNames';
}
- chunk.generateId(pattern, patternName, addons, outputOptions, usedIds);
+ chunk.id = chunk.generateId(pattern, patternName, addons, outputOptions, bundle);
}
- usedIds[chunk.id] = true;
+ bundle[chunk.id] = FILE_PLACEHOLDER;
}
}
// ported from https://github.com/substack/node-commondir
function commondir(files) {
@@ -17068,188 +17081,10 @@
});
}
return exportMode;
}
-const createGetOption = (config, command) => (name, defaultValue) => command[name] !== undefined
- ? command[name]
- : config[name] !== undefined
- ? config[name]
- : defaultValue;
-const normalizeObjectOptionValue = (optionValue) => {
- if (!optionValue) {
- return optionValue;
- }
- if (typeof optionValue !== 'object') {
- return {};
- }
- return optionValue;
-};
-const getObjectOption = (config, command, name) => {
- const commandOption = normalizeObjectOptionValue(command[name]);
- const configOption = normalizeObjectOptionValue(config[name]);
- if (commandOption !== undefined) {
- return commandOption && configOption ? Object.assign({}, configOption, commandOption) : commandOption;
- }
- return configOption;
-};
-const defaultOnWarn = warning => {
- if (typeof warning === 'string') {
- console.warn(warning);
- }
- else {
- console.warn(warning.message);
- }
-};
-const getOnWarn = (config, defaultOnWarnHandler = defaultOnWarn) => config.onwarn
- ? warning => config.onwarn(warning, defaultOnWarnHandler)
- : defaultOnWarnHandler;
-const getExternal = (config, command) => {
- const configExternal = config.external;
- return typeof configExternal === 'function'
- ? (id, ...rest) => configExternal(id, ...rest) || command.external.indexOf(id) !== -1
- : (typeof config.external === 'string'
- ? [configExternal]
- : Array.isArray(configExternal)
- ? configExternal
- : []).concat(command.external);
-};
-const commandAliases = {
- c: 'config',
- d: 'dir',
- e: 'external',
- f: 'format',
- g: 'globals',
- h: 'help',
- i: 'input',
- m: 'sourcemap',
- n: 'name',
- o: 'file',
- v: 'version',
- w: 'watch'
-};
-function mergeOptions({ config = {}, command: rawCommandOptions = {}, defaultOnWarnHandler }) {
- const command = getCommandOptions(rawCommandOptions);
- const inputOptions = getInputOptions(config, command, defaultOnWarnHandler);
- if (command.output) {
- Object.assign(command, command.output);
- }
- const output = config.output;
- const normalizedOutputOptions = Array.isArray(output) ? output : output ? [output] : [];
- if (normalizedOutputOptions.length === 0)
- normalizedOutputOptions.push({});
- const outputOptions = normalizedOutputOptions.map(singleOutputOptions => getOutputOptions(singleOutputOptions, command));
- const unknownOptionErrors = [];
- const validInputOptions = Object.keys(inputOptions);
- addUnknownOptionErrors(unknownOptionErrors, Object.keys(config), validInputOptions, 'input option', /^output$/);
- const validOutputOptions = Object.keys(outputOptions[0]);
- addUnknownOptionErrors(unknownOptionErrors, outputOptions.reduce((allKeys, options) => allKeys.concat(Object.keys(options)), []), validOutputOptions, 'output option');
- const validCliOutputOptions = validOutputOptions.filter(option => option !== 'sourcemapPathTransform');
- addUnknownOptionErrors(unknownOptionErrors, Object.keys(command), validInputOptions.concat(validCliOutputOptions, Object.keys(commandAliases), 'config', 'environment', 'silent'), 'CLI flag', /^_|output|(config.*)$/);
- return {
- inputOptions,
- optionError: unknownOptionErrors.length > 0 ? unknownOptionErrors.join('\n') : null,
- outputOptions
- };
-}
-function addUnknownOptionErrors(errors, options, validOptions, optionType, ignoredKeys = /$./) {
- const unknownOptions = options.filter(key => validOptions.indexOf(key) === -1 && !ignoredKeys.test(key));
- if (unknownOptions.length > 0)
- errors.push(`Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${validOptions.sort().join(', ')}`);
-}
-function getCommandOptions(rawCommandOptions) {
- const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
- ? rawCommandOptions.external.split(',')
- : [];
- return Object.assign({}, rawCommandOptions, { external, globals: typeof rawCommandOptions.globals === 'string'
- ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
- const [id, variableName] = globalDefinition.split(':');
- globals[id] = variableName;
- if (external.indexOf(id) === -1) {
- external.push(id);
- }
- return globals;
- }, Object.create(null))
- : undefined });
-}
-function getInputOptions(config, command = { external: [], globals: undefined }, defaultOnWarnHandler) {
- const getOption = createGetOption(config, command);
- const inputOptions = {
- acorn: config.acorn,
- acornInjectPlugins: config.acornInjectPlugins,
- cache: getOption('cache'),
- chunkGroupingSize: getOption('chunkGroupingSize', 5000),
- context: config.context,
- experimentalCacheExpiry: getOption('experimentalCacheExpiry', 10),
- experimentalOptimizeChunks: getOption('experimentalOptimizeChunks'),
- experimentalTopLevelAwait: getOption('experimentalTopLevelAwait'),
- external: getExternal(config, command),
- inlineDynamicImports: getOption('inlineDynamicImports', false),
- input: getOption('input', []),
- manualChunks: getOption('manualChunks'),
- moduleContext: config.moduleContext,
- onwarn: getOnWarn(config, defaultOnWarnHandler),
- perf: getOption('perf', false),
- plugins: config.plugins,
- preserveModules: getOption('preserveModules'),
- preserveSymlinks: getOption('preserveSymlinks'),
- shimMissingExports: getOption('shimMissingExports'),
- strictDeprecations: getOption('strictDeprecations', false),
- treeshake: getObjectOption(config, command, 'treeshake'),
- watch: config.watch
- };
- // support rollup({ cache: prevBuildObject })
- if (inputOptions.cache && inputOptions.cache.cache)
- inputOptions.cache = inputOptions.cache.cache;
- return inputOptions;
-}
-function getOutputOptions(config, command = {}) {
- const getOption = createGetOption(config, command);
- let format = getOption('format');
- // Handle format aliases
- switch (format) {
- case 'esm':
- case 'module':
- format = 'es';
- break;
- case 'commonjs':
- format = 'cjs';
- }
- return {
- amd: Object.assign({}, config.amd, command.amd),
- assetFileNames: getOption('assetFileNames'),
- banner: getOption('banner'),
- chunkFileNames: getOption('chunkFileNames'),
- compact: getOption('compact', false),
- dir: getOption('dir'),
- dynamicImportFunction: getOption('dynamicImportFunction'),
- entryFileNames: getOption('entryFileNames'),
- esModule: getOption('esModule', true),
- exports: getOption('exports'),
- extend: getOption('extend'),
- file: getOption('file'),
- footer: getOption('footer'),
- format: format === 'esm' ? 'es' : format,
- freeze: getOption('freeze', true),
- globals: getOption('globals'),
- indent: getOption('indent', true),
- interop: getOption('interop', true),
- intro: getOption('intro'),
- name: getOption('name'),
- namespaceToStringTag: getOption('namespaceToStringTag', false),
- noConflict: getOption('noConflict'),
- outro: getOption('outro'),
- paths: getOption('paths'),
- preferConst: getOption('preferConst'),
- sourcemap: getOption('sourcemap'),
- sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
- sourcemapFile: getOption('sourcemapFile'),
- sourcemapPathTransform: getOption('sourcemapPathTransform'),
- strict: getOption('strict', true)
- };
-}
-
function checkOutputOptions(options) {
if (options.format === 'es6') {
error(errDeprecation({
message: 'The "es6" output format is deprecated – use "esm" instead',
url: `https://rollupjs.org/guide/en/#output-format`
@@ -17264,11 +17099,11 @@
}
function getAbsoluteEntryModulePaths(chunks) {
const absoluteEntryModulePaths = [];
for (const chunk of chunks) {
for (const entryModule of chunk.entryModules) {
- if (isAbsolute(entryModule.id)) {
+ if (index.isAbsolute(entryModule.id)) {
absoluteEntryModulePaths.push(entryModule.id);
}
}
}
return absoluteEntryModulePaths;
@@ -17278,11 +17113,11 @@
throw new Error(`bundle.generate(...) now returns a Promise instead of a { code, map } object`);
}
};
function applyOptionHook(inputOptions, plugin) {
if (plugin.options)
- return plugin.options.call({ meta: { rollupVersion: version } }, inputOptions) || inputOptions;
+ return plugin.options.call({ meta: { rollupVersion: index.version } }, inputOptions) || inputOptions;
return inputOptions;
}
function ensureArray(items) {
if (Array.isArray(items)) {
return items.filter(Boolean);
@@ -17290,15 +17125,15 @@
if (items) {
return [items];
}
return [];
}
-function getInputOptions$1(rawInputOptions) {
+function getInputOptions(rawInputOptions) {
if (!rawInputOptions) {
throw new Error('You must supply an options object to rollup');
}
- let { inputOptions, optionError } = mergeOptions({
+ let { inputOptions, optionError } = index.mergeOptions({
config: rawInputOptions
});
if (optionError)
inputOptions.onwarn({ message: optionError, code: 'UNKNOWN_OPTION' });
inputOptions = ensureArray(inputOptions.plugins).reduce(applyOptionHook, inputOptions);
@@ -17348,44 +17183,70 @@
}
let curWatcher;
function setWatcher(watcher) {
curWatcher = watcher;
}
+function assignChunksToBundle(chunks, outputBundle) {
+ for (let i = 0; i < chunks.length; i++) {
+ const chunk = chunks[i];
+ const facadeModule = chunk.facadeModule;
+ outputBundle[chunk.id] = {
+ code: undefined,
+ dynamicImports: chunk.getDynamicImportIds(),
+ exports: chunk.getExportNames(),
+ facadeModuleId: facadeModule && facadeModule.id,
+ fileName: chunk.id,
+ imports: chunk.getImportIds(),
+ isDynamicEntry: facadeModule !== null && facadeModule.dynamicallyImportedBy.length > 0,
+ isEntry: facadeModule !== null && facadeModule.isEntryPoint,
+ map: undefined,
+ modules: chunk.renderedModules,
+ get name() {
+ return chunk.getChunkName();
+ }
+ };
+ }
+ return outputBundle;
+}
function rollup(rawInputOptions) {
- try {
- const inputOptions = getInputOptions$1(rawInputOptions);
+ return __awaiter(this, void 0, void 0, function* () {
+ const inputOptions = getInputOptions(rawInputOptions);
initialiseTimers(inputOptions);
const graph = new Graph(inputOptions, curWatcher);
curWatcher = undefined;
// remove the cache option from the memory after graph creation (cache is not used anymore)
const useCache = rawInputOptions.cache !== false;
delete inputOptions.cache;
delete rawInputOptions.cache;
timeStart('BUILD', 1);
- return graph.pluginDriver
- .hookParallel('buildStart', [inputOptions])
- .then(() => graph.build(inputOptions.input, inputOptions.manualChunks, inputOptions.inlineDynamicImports))
- .then(chunks => graph.pluginDriver.hookParallel('buildEnd', []).then(() => chunks), err => graph.pluginDriver.hookParallel('buildEnd', [err]).then(() => {
+ let chunks;
+ try {
+ yield graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
+ chunks = yield graph.build(inputOptions.input, inputOptions.manualChunks, inputOptions.inlineDynamicImports);
+ }
+ catch (err) {
+ yield graph.pluginDriver.hookParallel('buildEnd', [err]);
throw err;
- }))
- .then(chunks => {
- timeEnd('BUILD', 1);
- // ensure we only do one optimization pass per build
- let optimized = false;
- function getOutputOptions(rawOutputOptions) {
- return normalizeOutputOptions(inputOptions, rawOutputOptions, chunks.length > 1, graph.pluginDriver);
- }
- function generate(outputOptions, isWrite) {
+ }
+ yield graph.pluginDriver.hookParallel('buildEnd', []);
+ timeEnd('BUILD', 1);
+ // ensure we only do one optimization pass per build
+ let optimized = false;
+ function getOutputOptions(rawOutputOptions) {
+ return normalizeOutputOptions(inputOptions, rawOutputOptions, chunks.length > 1, graph.pluginDriver);
+ }
+ function generate(outputOptions, isWrite) {
+ return __awaiter(this, void 0, void 0, function* () {
timeStart('GENERATE', 1);
const assetFileNames = outputOptions.assetFileNames || 'assets/[name]-[hash][extname]';
- const outputBundle = graph.finaliseAssets(assetFileNames);
+ const outputBundleWithPlaceholders = Object.create(null);
+ let outputBundle;
const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
- return graph.pluginDriver
- .hookParallel('renderStart', [])
- .then(() => createAddons(graph, outputOptions))
- .then(addons => {
- // pre-render all chunks
+ graph.pluginDriver.startOutput(outputBundleWithPlaceholders, assetFileNames);
+ try {
+ yield graph.pluginDriver.hookParallel('renderStart', []);
+ const addons = yield createAddons(graph, outputOptions);
for (const chunk of chunks) {
if (!inputOptions.preserveModules)
chunk.generateInternalExports(outputOptions);
if (chunk.facadeModule && chunk.facadeModule.isEntryPoint)
chunk.exportMode = getExportMode(chunk, outputOptions);
@@ -17395,124 +17256,88 @@
}
if (!optimized && inputOptions.experimentalOptimizeChunks) {
optimizeChunks(chunks, outputOptions, inputOptions.chunkGroupingSize, inputBase);
optimized = true;
}
- assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons);
- // assign to outputBundle
- for (let i = 0; i < chunks.length; i++) {
- const chunk = chunks[i];
- const facadeModule = chunk.facadeModule;
- outputBundle[chunk.id] = {
- code: undefined,
- dynamicImports: chunk.getDynamicImportIds(),
- exports: chunk.getExportNames(),
- facadeModuleId: facadeModule && facadeModule.id,
- fileName: chunk.id,
- imports: chunk.getImportIds(),
- isDynamicEntry: facadeModule !== null && facadeModule.dynamicallyImportedBy.length > 0,
- isEntry: facadeModule !== null && facadeModule.isEntryPoint,
- map: undefined,
- modules: chunk.renderedModules,
- get name() {
- return chunk.getChunkName();
- }
- };
- }
- return Promise.all(chunks.map(chunk => {
- const outputChunk = outputBundle[chunk.id];
+ assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons, outputBundleWithPlaceholders);
+ outputBundle = assignChunksToBundle(chunks, outputBundleWithPlaceholders);
+ yield Promise.all(chunks.map(chunk => {
+ const outputChunk = outputBundleWithPlaceholders[chunk.id];
return chunk.render(outputOptions, addons, outputChunk).then(rendered => {
outputChunk.code = rendered.code;
outputChunk.map = rendered.map;
return graph.pluginDriver.hookParallel('ongenerate', [
Object.assign({ bundle: outputChunk }, outputOptions),
outputChunk
]);
});
- })).then(() => { });
- })
- .catch(error => graph.pluginDriver.hookParallel('renderError', [error]).then(() => {
+ }));
+ }
+ catch (error) {
+ yield graph.pluginDriver.hookParallel('renderError', [error]);
throw error;
- }))
- .then(() => {
- // run generateBundle hook
- // assets emitted during generateBundle are unique to that specific generate call
- const assets = new Map(graph.assetsById);
- const generateAssetPluginHooks = createAssetPluginHooks(assets, outputBundle, assetFileNames);
- return graph.pluginDriver
- .hookSeq('generateBundle', [outputOptions, outputBundle, isWrite], context => (Object.assign({}, context, generateAssetPluginHooks)))
- .then(() => {
- // throw errors for assets not finalised with a source
- assets.forEach(asset => {
- if (asset.fileName === undefined)
- finaliseAsset(asset, outputBundle, assetFileNames);
- });
+ }
+ yield graph.pluginDriver.hookSeq('generateBundle', [outputOptions, outputBundle, isWrite]);
+ graph.pluginDriver.finaliseAssets();
+ timeEnd('GENERATE', 1);
+ return outputBundle;
+ });
+ }
+ const cache = useCache ? graph.getCache() : undefined;
+ const result = {
+ cache: cache,
+ generate: ((rawOutputOptions) => {
+ const promise = generate(getOutputOptions(rawOutputOptions), false).then(result => createOutput(result));
+ Object.defineProperty(promise, 'code', throwAsyncGenerateError);
+ Object.defineProperty(promise, 'map', throwAsyncGenerateError);
+ return promise;
+ }),
+ watchFiles: Object.keys(graph.watchFiles),
+ write: ((rawOutputOptions) => {
+ const outputOptions = getOutputOptions(rawOutputOptions);
+ if (!outputOptions.dir && !outputOptions.file) {
+ error({
+ code: 'MISSING_OPTION',
+ message: 'You must specify "output.file" or "output.dir" for the build.'
});
- })
- .then(() => {
- timeEnd('GENERATE', 1);
- return outputBundle;
- });
- }
- const cache = useCache ? graph.getCache() : undefined;
- const result = {
- cache: cache,
- generate: ((rawOutputOptions) => {
- const promise = generate(getOutputOptions(rawOutputOptions), false).then(result => createOutput(result));
- Object.defineProperty(promise, 'code', throwAsyncGenerateError);
- Object.defineProperty(promise, 'map', throwAsyncGenerateError);
- return promise;
- }),
- watchFiles: Object.keys(graph.watchFiles),
- write: ((rawOutputOptions) => {
- const outputOptions = getOutputOptions(rawOutputOptions);
- if (!outputOptions.dir && !outputOptions.file) {
- error({
- code: 'MISSING_OPTION',
- message: 'You must specify "output.file" or "output.dir" for the build.'
- });
+ }
+ return generate(outputOptions, true).then((bundle) => __awaiter(this, void 0, void 0, function* () {
+ let chunkCnt = 0;
+ for (const fileName of Object.keys(bundle)) {
+ const file = bundle[fileName];
+ if (file.isAsset)
+ continue;
+ chunkCnt++;
+ if (chunkCnt > 1)
+ break;
}
- return generate(outputOptions, true).then(bundle => {
- let chunkCnt = 0;
- for (const fileName of Object.keys(bundle)) {
- const file = bundle[fileName];
- if (file.isAsset)
- continue;
- chunkCnt++;
- if (chunkCnt > 1)
- break;
- }
- if (chunkCnt > 1) {
- if (outputOptions.sourcemapFile)
- error({
- code: 'INVALID_OPTION',
- message: '"output.sourcemapFile" is only supported for single-file builds.'
- });
- if (typeof outputOptions.file === 'string')
- error({
- code: 'INVALID_OPTION',
- message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file".' +
- (typeof inputOptions.input !== 'string' ||
- inputOptions.inlineDynamicImports === true
- ? ''
- : ' To inline dynamic imports, set the "inlineDynamicImports" option.')
- });
- }
- return Promise.all(Object.keys(bundle).map(chunkId => writeOutputFile(graph, result, bundle[chunkId], outputOptions)))
- .then(() => graph.pluginDriver.hookParallel('writeBundle', [bundle]))
- .then(() => createOutput(bundle));
- });
- })
- };
- if (inputOptions.perf === true)
- result.getTimings = getTimings;
- return result;
- });
- }
- catch (err) {
- return Promise.reject(err);
- }
+ if (chunkCnt > 1) {
+ if (outputOptions.sourcemapFile)
+ error({
+ code: 'INVALID_OPTION',
+ message: '"output.sourcemapFile" is only supported for single-file builds.'
+ });
+ if (typeof outputOptions.file === 'string')
+ error({
+ code: 'INVALID_OPTION',
+ message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file".' +
+ (typeof inputOptions.input !== 'string' ||
+ inputOptions.inlineDynamicImports === true
+ ? ''
+ : ' To inline dynamic imports, set the "inlineDynamicImports" option.')
+ });
+ }
+ yield Promise.all(Object.keys(bundle).map(chunkId => writeOutputFile(graph, result, bundle[chunkId], outputOptions)));
+ yield graph.pluginDriver.hookParallel('writeBundle', [bundle]);
+ return createOutput(bundle);
+ }));
+ })
+ };
+ if (inputOptions.perf === true)
+ result.getTimings = getTimings;
+ return result;
+ });
}
var SortingFileType;
(function (SortingFileType) {
SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
@@ -17529,11 +17354,11 @@
}
function createOutput(outputBundle) {
return {
output: Object.keys(outputBundle)
.map(fileName => outputBundle[fileName])
- .sort((outputFileA, outputFileB) => {
+ .filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
const fileTypeA = getSortingFileType(outputFileA);
const fileTypeB = getSortingFileType(outputFileB);
if (fileTypeA === fileTypeB)
return 0;
return fileTypeA < fileTypeB ? -1 : 1;
@@ -17575,21 +17400,24 @@
}
function normalizeOutputOptions(inputOptions, rawOutputOptions, hasMultipleChunks, pluginDriver) {
if (!rawOutputOptions) {
throw new Error('You must supply an options object');
}
- const mergedOptions = mergeOptions({
+ const mergedOptions = index.mergeOptions({
config: {
output: Object.assign({}, rawOutputOptions, rawOutputOptions.output, inputOptions.output)
}
});
if (mergedOptions.optionError)
throw new Error(mergedOptions.optionError);
// now outputOptions is an array, but rollup.rollup API doesn't support arrays
const mergedOutputOptions = mergedOptions.outputOptions[0];
const outputOptionsReducer = (outputOptions, result) => result || outputOptions;
- const outputOptions = pluginDriver.hookReduceArg0Sync('outputOptions', [mergedOutputOptions], outputOptionsReducer);
+ const outputOptions = pluginDriver.hookReduceArg0Sync('outputOptions', [mergedOutputOptions], outputOptionsReducer, pluginContext => {
+ const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
+ return Object.assign({}, pluginContext, { emitFile: emitError, setAssetSource: emitError });
+ });
checkOutputOptions(outputOptions);
if (typeof outputOptions.file === 'string') {
if (typeof outputOptions.dir === 'string')
error({
code: 'INVALID_OPTION',
@@ -17620,11 +17448,11 @@
});
}
return outputOptions;
}
-var utils$1 = createCommonjsModule(function (module, exports) {
+var utils$1 = index.createCommonjsModule(function (module, exports) {
exports.isInteger = num => {
if (typeof num === 'number') {
return Number.isInteger(num);
}
if (typeof num === 'string' && num.trim() !== '') {
@@ -18895,11 +18723,11 @@
CHAR_SPACE: 32,
CHAR_TAB: 9,
CHAR_UNDERSCORE: 95,
CHAR_VERTICAL_LINE: 124,
CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
- SEP: path__default.sep,
+ SEP: path.sep,
/**
* Create EXTGLOB_CHARS
*/
extglobChars(chars) {
return {
@@ -18916,11 +18744,11 @@
globChars(win32) {
return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
}
};
-var utils$2 = createCommonjsModule(function (module, exports) {
+var utils$2 = index.createCommonjsModule(function (module, exports) {
const win32 = process.platform === 'win32';
const { REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL, REGEX_REMOVE_BACKSLASH } = constants$1;
exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
@@ -18940,11 +18768,11 @@
};
exports.isWindows = options => {
if (options && typeof options.windows === 'boolean') {
return options.windows;
}
- return win32 === true || path__default.sep === '\\';
+ return win32 === true || path.sep === '\\';
};
exports.escapeLast = (input, char, lastIdx) => {
let idx = input.lastIndexOf(char, lastIdx);
if (idx === -1)
return input;
@@ -20045,11 +19873,11 @@
* @return {Boolean}
* @api public
*/
picomatch.matchBase = (input, glob, options, posix = utils$2.isWindows(options)) => {
let regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
- return regex.test(path__default.basename(input));
+ return regex.test(path.basename(input));
};
/**
* Returns true if **any** of the given glob `patterns` match the specified `string`.
*
* ```js
@@ -20648,36 +20476,13 @@
}
return !includeMatchers.length;
};
};
-var modules = {};
-var getModule = function (dir) {
- var rootPath = dir ? path__default.resolve(dir) : process.cwd();
- var rootName = path__default.join(rootPath, '@root');
- var root = modules[rootName];
- if (!root) {
- root = new module$1(rootName);
- root.filename = rootName;
- root.paths = module$1._nodeModulePaths(rootPath);
- modules[rootName] = root;
- }
- return root;
-};
-var requireRelative = function (requested, relativeTo) {
- var root = getModule(relativeTo);
- return root.require(requested);
-};
-requireRelative.resolve = function (requested, relativeTo) {
- var root = getModule(relativeTo);
- return module$1._resolveFilename(requested, root);
-};
-var requireRelative_1 = requireRelative;
-
let chokidar;
try {
- chokidar = requireRelative_1('chokidar', process.cwd());
+ chokidar = index.relative('chokidar', process.cwd());
}
catch (err) {
chokidar = null;
}
var chokidar$1 = chokidar;
@@ -20866,18 +20671,18 @@
this.invalidated = true;
this.cache = null;
this.watcher = watcher;
this.closed = false;
this.watched = new Set();
- const { inputOptions, outputOptions } = mergeOptions({
+ const { inputOptions, outputOptions } = index.mergeOptions({
config
});
this.inputOptions = inputOptions;
this.outputs = outputOptions;
this.outputFiles = this.outputs.map(output => {
if (output.file || output.dir)
- return path__default.resolve(output.file || output.dir);
+ return path.resolve(output.file || output.dir);
return undefined;
});
const watchOptions = inputOptions.watch || {};
if ('useChokidar' in watchOptions)
watchOptions.chokidar = watchOptions.useChokidar;
@@ -20992,9 +20797,9 @@
}
function watch(configs) {
return new Watcher(configs).emitter;
}
-exports.VERSION = version;
+exports.VERSION = index.version;
exports.rollup = rollup;
exports.watch = watch;
//# sourceMappingURL=rollup.js.map