Commit a2e8cafb authored by patri's avatar patri
Browse files

Test New PC

1 merge request!1update some ui
Showing with 745 additions and 508 deletions
+745 -508
......@@ -5,34 +5,37 @@ Object.defineProperty(exports, "__esModule", {
});
exports.makeStaticFileCache = makeStaticFileCache;
function _fs() {
const data = _interopRequireDefault(require("fs"));
var _caching = require("../caching");
var fs = require("../../gensync-utils/fs");
_fs = function () {
function _fs2() {
const data = require("fs");
_fs2 = function () {
return data;
};
return data;
}
var _caching = require("../caching");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function makeStaticFileCache(fn) {
return (0, _caching.makeStrongCache)((filepath, cache) => {
if (cache.invalidate(() => fileMtime(filepath)) === null) {
cache.forever();
return (0, _caching.makeStrongCache)(function* (filepath, cache) {
const cached = cache.invalidate(() => fileMtime(filepath));
if (cached === null) {
return null;
}
return fn(filepath, _fs().default.readFileSync(filepath, "utf8"));
return fn(filepath, yield* fs.readFile(filepath, "utf8"));
});
}
function fileMtime(filepath) {
if (!_fs2().existsSync(filepath)) return null;
try {
return +_fs().default.statSync(filepath).mtime;
return +_fs2().statSync(filepath).mtime;
} catch (e) {
if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e;
}
......
......@@ -3,20 +3,32 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = loadFullConfig;
exports.default = void 0;
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
var _async = require("../gensync-utils/async");
var _util = require("./util");
var context = _interopRequireWildcard(require("../index"));
var context = require("../index");
var _plugin = _interopRequireDefault(require("./plugin"));
var _plugin = require("./plugin");
var _item = require("./item");
var _configChain = require("./config-chain");
function _traverse() {
const data = _interopRequireDefault(require("@babel/traverse"));
const data = require("@babel/traverse");
_traverse = function () {
return data;
......@@ -31,18 +43,16 @@ var _options = require("./validation/options");
var _plugins = require("./validation/plugins");
var _configApi = _interopRequireDefault(require("./helpers/config-api"));
var _partial = _interopRequireDefault(require("./partial"));
var _configApi = require("./helpers/config-api");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _partial = require("./partial");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
var Context = require("./cache-contexts");
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var _default = _gensync()(function* loadFullConfig(inputOpts) {
var _opts$assumptions;
function loadFullConfig(inputOpts) {
const result = (0, _partial.default)(inputOpts);
const result = yield* (0, _partial.default)(inputOpts);
if (!result) {
return null;
......@@ -50,95 +60,118 @@ function loadFullConfig(inputOpts) {
const {
options,
context
context,
fileHandling
} = result;
if (fileHandling === "ignored") {
return null;
}
const optionDefaults = {};
const passes = [[]];
const {
plugins,
presets
} = options;
try {
const {
plugins,
presets
} = options;
if (!plugins || !presets) {
throw new Error("Assertion failure - plugins and presets exist");
}
if (!plugins || !presets) {
throw new Error("Assertion failure - plugins and presets exist");
}
const presetContext = Object.assign({}, context, {
targets: options.targets
});
const ignored = function recurseDescriptors(config, pass) {
const plugins = config.plugins.reduce((acc, descriptor) => {
if (descriptor.options !== false) {
acc.push(loadPluginDescriptor(descriptor, context));
}
const toDescriptor = item => {
const desc = (0, _item.getItemDescriptor)(item);
return acc;
}, []);
const presets = config.presets.reduce((acc, descriptor) => {
if (descriptor.options !== false) {
acc.push({
preset: loadPresetDescriptor(descriptor, context),
pass: descriptor.ownPass ? [] : pass
});
}
if (!desc) {
throw new Error("Assertion failure - must be config item");
}
return desc;
};
return acc;
}, []);
if (presets.length > 0) {
passes.splice(1, 0, ...presets.map(o => o.pass).filter(p => p !== pass));
for (const _ref of presets) {
const {
preset,
pass
} = _ref;
if (!preset) return true;
const ignored = recurseDescriptors({
plugins: preset.plugins,
presets: preset.presets
}, pass);
if (ignored) return true;
preset.options.forEach(opts => {
(0, _util.mergeOptions)(optionDefaults, opts);
});
const presetsDescriptors = presets.map(toDescriptor);
const initialPluginsDescriptors = plugins.map(toDescriptor);
const pluginDescriptorsByPass = [[]];
const passes = [];
const ignored = yield* enhanceError(context, function* recursePresetDescriptors(rawPresets, pluginDescriptorsPass) {
const presets = [];
for (let i = 0; i < rawPresets.length; i++) {
const descriptor = rawPresets[i];
if (descriptor.options !== false) {
try {
if (descriptor.ownPass) {
presets.push({
preset: yield* loadPresetDescriptor(descriptor, presetContext),
pass: []
});
} else {
presets.unshift({
preset: yield* loadPresetDescriptor(descriptor, presetContext),
pass: pluginDescriptorsPass
});
}
} catch (e) {
if (e.code === "BABEL_UNKNOWN_OPTION") {
(0, _options.checkNoUnwrappedItemOptionPairs)(rawPresets, i, "preset", e);
}
throw e;
}
}
}
if (plugins.length > 0) {
pass.unshift(...plugins);
if (presets.length > 0) {
pluginDescriptorsByPass.splice(1, 0, ...presets.map(o => o.pass).filter(p => p !== pluginDescriptorsPass));
for (const {
preset,
pass
} of presets) {
if (!preset) return true;
pass.push(...preset.plugins);
const ignored = yield* recursePresetDescriptors(preset.presets, pass);
if (ignored) return true;
preset.options.forEach(opts => {
(0, _util.mergeOptions)(optionDefaults, opts);
});
}
}({
plugins: plugins.map(item => {
const desc = (0, _item.getItemDescriptor)(item);
}
})(presetsDescriptors, pluginDescriptorsByPass[0]);
if (ignored) return null;
const opts = optionDefaults;
(0, _util.mergeOptions)(opts, options);
const pluginContext = Object.assign({}, presetContext, {
assumptions: (_opts$assumptions = opts.assumptions) != null ? _opts$assumptions : {}
});
yield* enhanceError(context, function* loadPluginDescriptors() {
pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors);
if (!desc) {
throw new Error("Assertion failure - must be config item");
}
for (const descs of pluginDescriptorsByPass) {
const pass = [];
passes.push(pass);
return desc;
}),
presets: presets.map(item => {
const desc = (0, _item.getItemDescriptor)(item);
for (let i = 0; i < descs.length; i++) {
const descriptor = descs[i];
if (!desc) {
throw new Error("Assertion failure - must be config item");
if (descriptor.options !== false) {
try {
pass.push(yield* loadPluginDescriptor(descriptor, pluginContext));
} catch (e) {
if (e.code === "BABEL_UNKNOWN_PLUGIN_PROPERTY") {
(0, _options.checkNoUnwrappedItemOptionPairs)(descs, i, "plugin", e);
}
throw e;
}
}
return desc;
})
}, passes[0]);
if (ignored) return null;
} catch (e) {
if (!/^\[BABEL\]/.test(e.message)) {
e.message = `[BABEL] ${context.filename || "unknown"}: ${e.message}`;
}
}
throw e;
}
const opts = optionDefaults;
(0, _util.mergeOptions)(opts, options);
})();
opts.plugins = passes[0];
opts.presets = passes.slice(1).filter(plugins => plugins.length > 0).map(plugins => ({
plugins
......@@ -148,23 +181,40 @@ function loadFullConfig(inputOpts) {
options: opts,
passes: passes
};
});
exports.default = _default;
function enhanceError(context, fn) {
return function* (arg1, arg2) {
try {
return yield* fn(arg1, arg2);
} catch (e) {
if (!/^\[BABEL\]/.test(e.message)) {
e.message = `[BABEL] ${context.filename || "unknown"}: ${e.message}`;
}
throw e;
}
};
}
const loadDescriptor = (0, _caching.makeWeakCache)(({
const makeDescriptorLoader = apiFactory => (0, _caching.makeWeakCache)(function* ({
value,
options,
dirname,
alias
}, cache) => {
}, cache) {
if (options === false) throw new Error("Assertion failure");
options = options || {};
let item = value;
if (typeof value === "function") {
const api = Object.assign({}, context, {}, (0, _configApi.default)(cache));
const factory = (0, _async.maybeAsync)(value, `You appear to be using an async plugin/preset, but Babel has been called synchronously`);
const api = Object.assign({}, context, apiFactory(cache));
try {
item = value(api, options, dirname);
item = yield* factory(api, options, dirname);
} catch (e) {
if (alias) {
e.message += ` (While processing: ${JSON.stringify(alias)})`;
......@@ -178,8 +228,9 @@ const loadDescriptor = (0, _caching.makeWeakCache)(({
throw new Error("Plugin/Preset did not return an object.");
}
if (typeof item.then === "function") {
throw new Error(`You appear to be using an async plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version.`);
if ((0, _async.isThenable)(item)) {
yield* [];
throw new Error(`You appear to be using a promise as a plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version. ` + `As an alternative, you can prefix the promise with "await". ` + `(While processing: ${JSON.stringify(alias)})`);
}
return {
......@@ -190,7 +241,10 @@ const loadDescriptor = (0, _caching.makeWeakCache)(({
};
});
function loadPluginDescriptor(descriptor, context) {
const pluginDescriptorLoader = makeDescriptorLoader(_configApi.makePluginAPI);
const presetDescriptorLoader = makeDescriptorLoader(_configApi.makePresetAPI);
function* loadPluginDescriptor(descriptor, context) {
if (descriptor.value instanceof _plugin.default) {
if (descriptor.options) {
throw new Error("Passed options to an existing Plugin instance will not work.");
......@@ -199,15 +253,15 @@ function loadPluginDescriptor(descriptor, context) {
return descriptor.value;
}
return instantiatePlugin(loadDescriptor(descriptor, context), context);
return yield* instantiatePlugin(yield* pluginDescriptorLoader(descriptor, context), context);
}
const instantiatePlugin = (0, _caching.makeWeakCache)(({
const instantiatePlugin = (0, _caching.makeWeakCache)(function* ({
value,
options,
dirname,
alias
}, cache) => {
}, cache) {
const pluginObj = (0, _plugins.validatePluginObject)(value);
const plugin = Object.assign({}, pluginObj);
......@@ -223,7 +277,9 @@ const instantiatePlugin = (0, _caching.makeWeakCache)(({
options,
dirname
};
const inherits = cache.invalidate(data => loadPluginDescriptor(inheritsDescriptor, data));
const inherits = yield* (0, _async.forwardAsync)(loadPluginDescriptor, run => {
return cache.invalidate(data => run(inheritsDescriptor, data));
});
plugin.pre = chain(inherits.pre, plugin.pre);
plugin.post = chain(inherits.post, plugin.post);
plugin.manipulateOptions = chain(inherits.manipulateOptions, plugin.manipulateOptions);
......@@ -253,13 +309,13 @@ const validatePreset = (preset, context, descriptor) => {
}
};
const loadPresetDescriptor = (descriptor, context) => {
const preset = instantiatePreset(loadDescriptor(descriptor, context));
function* loadPresetDescriptor(descriptor, context) {
const preset = instantiatePreset(yield* presetDescriptorLoader(descriptor, context));
validatePreset(preset, context, descriptor);
return (0, _configChain.buildPresetChain)(preset, context);
};
return yield* (0, _configChain.buildPresetChain)(preset, context);
}
const instantiatePreset = (0, _caching.makeWeakCache)(({
const instantiatePreset = (0, _caching.makeWeakCacheSync)(({
value,
dirname,
alias
......
......@@ -3,10 +3,12 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = makeAPI;
exports.makeConfigAPI = makeConfigAPI;
exports.makePresetAPI = makePresetAPI;
exports.makePluginAPI = makePluginAPI;
function _semver() {
const data = _interopRequireDefault(require("semver"));
const data = require("semver");
_semver = function () {
return data;
......@@ -19,9 +21,9 @@ var _ = require("../../");
var _caching = require("../caching");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Context = require("../cache-contexts");
function makeAPI(cache) {
function makeConfigAPI(cache) {
const env = value => cache.using(data => {
if (typeof value === "undefined") return data.envName;
......@@ -47,11 +49,26 @@ function makeAPI(cache) {
env,
async: () => false,
caller,
assertVersion,
tokTypes: undefined
assertVersion
};
}
function makePresetAPI(cache) {
const targets = () => JSON.parse(cache.using(data => JSON.stringify(data.targets)));
return Object.assign({}, makeConfigAPI(cache), {
targets
});
}
function makePluginAPI(cache) {
const assumption = name => cache.using(data => data.assumptions[name]);
return Object.assign({}, makePresetAPI(cache), {
assumption
});
}
function assertVersion(range) {
if (typeof range === "number") {
if (!Number.isInteger(range)) {
......@@ -65,7 +82,7 @@ function assertVersion(range) {
throw new Error("Expected string or integer value.");
}
if (_semver().default.satisfies(_.version, range)) return;
if (_semver().satisfies(_.version, range)) return;
const limit = Error.stackTraceLimit;
if (typeof limit === "number" && limit < 25) {
......
......@@ -3,27 +3,72 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.loadOptions = loadOptions;
exports.createConfigItem = createConfigItem;
Object.defineProperty(exports, "default", {
enumerable: true,
get: function () {
return _full.default;
}
});
Object.defineProperty(exports, "loadPartialConfig", {
enumerable: true,
get: function () {
return _partial.loadPartialConfig;
}
});
exports.createConfigItemAsync = exports.createConfigItemSync = exports.loadOptionsAsync = exports.loadOptionsSync = exports.loadOptions = exports.loadPartialConfigAsync = exports.loadPartialConfigSync = exports.loadPartialConfig = void 0;
var _full = _interopRequireDefault(require("./full"));
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
var _full = require("./full");
var _partial = require("./partial");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _item = require("./item");
const loadOptionsRunner = _gensync()(function* (opts) {
var _config$options;
function loadOptions(opts) {
const config = (0, _full.default)(opts);
return config ? config.options : null;
const config = yield* (0, _full.default)(opts);
return (_config$options = config == null ? void 0 : config.options) != null ? _config$options : null;
});
const createConfigItemRunner = _gensync()(_item.createConfigItem);
const maybeErrback = runner => (opts, callback) => {
if (callback === undefined && typeof opts === "function") {
callback = opts;
opts = undefined;
}
return callback ? runner.errback(opts, callback) : runner.sync(opts);
};
const loadPartialConfig = maybeErrback(_partial.loadPartialConfig);
exports.loadPartialConfig = loadPartialConfig;
const loadPartialConfigSync = _partial.loadPartialConfig.sync;
exports.loadPartialConfigSync = loadPartialConfigSync;
const loadPartialConfigAsync = _partial.loadPartialConfig.async;
exports.loadPartialConfigAsync = loadPartialConfigAsync;
const loadOptions = maybeErrback(loadOptionsRunner);
exports.loadOptions = loadOptions;
const loadOptionsSync = loadOptionsRunner.sync;
exports.loadOptionsSync = loadOptionsSync;
const loadOptionsAsync = loadOptionsRunner.async;
exports.loadOptionsAsync = loadOptionsAsync;
const createConfigItemSync = createConfigItemRunner.sync;
exports.createConfigItemSync = createConfigItemSync;
const createConfigItemAsync = createConfigItemRunner.async;
exports.createConfigItemAsync = createConfigItemAsync;
function createConfigItem(target, options, callback) {
if (callback !== undefined) {
return createConfigItemRunner.errback(target, options, callback);
} else if (typeof options === "function") {
return createConfigItemRunner.errback(target, undefined, callback);
} else {
return createConfigItemRunner.sync(target, options);
}
}
\ No newline at end of file
......@@ -8,7 +8,7 @@ exports.createConfigItem = createConfigItem;
exports.getItemDescriptor = getItemDescriptor;
function _path() {
const data = _interopRequireDefault(require("path"));
const data = require("path");
_path = function () {
return data;
......@@ -19,17 +19,15 @@ function _path() {
var _configDescriptors = require("./config-descriptors");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function createItemFromDescriptor(desc) {
return new ConfigItem(desc);
}
function createConfigItem(value, {
function* createConfigItem(value, {
dirname = ".",
type
} = {}) {
const descriptor = (0, _configDescriptors.createDescriptor)(value, _path().default.resolve(dirname), {
const descriptor = yield* (0, _configDescriptors.createDescriptor)(value, _path().resolve(dirname), {
type,
alias: "programmatic item"
});
......@@ -37,19 +35,31 @@ function createConfigItem(value, {
}
function getItemDescriptor(item) {
if (item instanceof ConfigItem) {
if (item != null && item[CONFIG_ITEM_BRAND]) {
return item._descriptor;
}
return undefined;
}
const CONFIG_ITEM_BRAND = Symbol.for("@babel/core@7 - ConfigItem");
class ConfigItem {
constructor(descriptor) {
this._descriptor = void 0;
this[CONFIG_ITEM_BRAND] = true;
this.value = void 0;
this.options = void 0;
this.dirname = void 0;
this.name = void 0;
this.file = void 0;
this._descriptor = descriptor;
Object.defineProperty(this, "_descriptor", {
enumerable: false
});
Object.defineProperty(this, CONFIG_ITEM_BRAND, {
enumerable: false
});
this.value = this._descriptor.value;
this.options = this._descriptor.options;
this.dirname = this._descriptor.dirname;
......
......@@ -4,10 +4,10 @@ Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = loadPrivatePartialConfig;
exports.loadPartialConfig = loadPartialConfig;
exports.loadPartialConfig = void 0;
function _path() {
const data = _interopRequireDefault(require("path"));
const data = require("path");
_path = function () {
return data;
......@@ -16,7 +16,17 @@ function _path() {
return data;
}
var _plugin = _interopRequireDefault(require("./plugin"));
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
var _plugin = require("./plugin");
var _util = require("./util");
......@@ -30,7 +40,9 @@ var _options = require("./validation/options");
var _files = require("./files");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _resolveTargets = require("./resolve-targets");
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function resolveRootMode(rootDir, rootMode) {
switch (rootMode) {
......@@ -47,18 +59,18 @@ function resolveRootMode(rootDir, rootMode) {
{
const upwardRootDir = (0, _files.findConfigUpwards)(rootDir);
if (upwardRootDir !== null) return upwardRootDir;
throw Object.assign(new Error(`Babel was run with rootMode:"upward" but a root could not ` + `be found when searching upward from "${rootDir}"`), {
throw Object.assign(new Error(`Babel was run with rootMode:"upward" but a root could not ` + `be found when searching upward from "${rootDir}".\n` + `One of the following config files must be in the directory tree: ` + `"${_files.ROOT_CONFIG_FILENAMES.join(", ")}".`), {
code: "BABEL_ROOT_NOT_FOUND",
dirname: rootDir
});
}
default:
throw new Error(`Assertion failure - unknown rootMode value`);
throw new Error(`Assertion failure - unknown rootMode value.`);
}
}
function loadPrivatePartialConfig(inputOpts) {
function* loadPrivatePartialConfig(inputOpts) {
if (inputOpts != null && (typeof inputOpts !== "object" || Array.isArray(inputOpts))) {
throw new Error("Babel options must be an object, null, or undefined");
}
......@@ -69,66 +81,108 @@ function loadPrivatePartialConfig(inputOpts) {
cwd = ".",
root: rootDir = ".",
rootMode = "root",
caller
caller,
cloneInputAst = true
} = args;
const absoluteCwd = _path().default.resolve(cwd);
const absoluteCwd = _path().resolve(cwd);
const absoluteRootDir = resolveRootMode(_path().default.resolve(absoluteCwd, rootDir), rootMode);
const absoluteRootDir = resolveRootMode(_path().resolve(absoluteCwd, rootDir), rootMode);
const filename = typeof args.filename === "string" ? _path().resolve(cwd, args.filename) : undefined;
const showConfigPath = yield* (0, _files.resolveShowConfigPath)(absoluteCwd);
const context = {
filename: typeof args.filename === "string" ? _path().default.resolve(cwd, args.filename) : undefined,
filename,
cwd: absoluteCwd,
root: absoluteRootDir,
envName,
caller
caller,
showConfig: showConfigPath === filename
};
const configChain = (0, _configChain.buildRootChain)(args, context);
const configChain = yield* (0, _configChain.buildRootChain)(args, context);
if (!configChain) return null;
const options = {};
const merged = {
assumptions: {}
};
configChain.options.forEach(opts => {
(0, _util.mergeOptions)(options, opts);
(0, _util.mergeOptions)(merged, opts);
});
const options = Object.assign({}, merged, {
targets: (0, _resolveTargets.resolveTargets)(merged, absoluteRootDir),
cloneInputAst,
babelrc: false,
configFile: false,
browserslistConfigFile: false,
passPerPreset: false,
envName: context.envName,
cwd: context.cwd,
root: context.root,
rootMode: "root",
filename: typeof context.filename === "string" ? context.filename : undefined,
plugins: configChain.plugins.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor)),
presets: configChain.presets.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor))
});
options.babelrc = false;
options.configFile = false;
options.passPerPreset = false;
options.envName = context.envName;
options.cwd = context.cwd;
options.root = context.root;
options.filename = typeof context.filename === "string" ? context.filename : undefined;
options.plugins = configChain.plugins.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor));
options.presets = configChain.presets.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor));
return {
options,
context,
fileHandling: configChain.fileHandling,
ignore: configChain.ignore,
babelrc: configChain.babelrc,
config: configChain.config
config: configChain.config,
files: configChain.files
};
}
function loadPartialConfig(inputOpts) {
const result = loadPrivatePartialConfig(inputOpts);
const loadPartialConfig = _gensync()(function* (opts) {
let showIgnoredFiles = false;
if (typeof opts === "object" && opts !== null && !Array.isArray(opts)) {
var _opts = opts;
({
showIgnoredFiles
} = _opts);
opts = _objectWithoutPropertiesLoose(_opts, ["showIgnoredFiles"]);
_opts;
}
const result = yield* loadPrivatePartialConfig(opts);
if (!result) return null;
const {
options,
babelrc,
ignore,
config
config,
fileHandling,
files
} = result;
if (fileHandling === "ignored" && !showIgnoredFiles) {
return null;
}
(options.plugins || []).forEach(item => {
if (item.value instanceof _plugin.default) {
throw new Error("Passing cached plugin instances is not supported in " + "babel.loadPartialConfig()");
}
});
return new PartialConfig(options, babelrc ? babelrc.filepath : undefined, ignore ? ignore.filepath : undefined, config ? config.filepath : undefined);
}
return new PartialConfig(options, babelrc ? babelrc.filepath : undefined, ignore ? ignore.filepath : undefined, config ? config.filepath : undefined, fileHandling, files);
});
exports.loadPartialConfig = loadPartialConfig;
class PartialConfig {
constructor(options, babelrc, ignore, config) {
constructor(options, babelrc, ignore, config, fileHandling, files) {
this.options = void 0;
this.babelrc = void 0;
this.babelignore = void 0;
this.config = void 0;
this.fileHandling = void 0;
this.files = void 0;
this.options = options;
this.babelignore = ignore;
this.babelrc = babelrc;
this.config = config;
this.fileHandling = fileHandling;
this.files = files;
Object.freeze(this);
}
......
......@@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", {
exports.default = pathToPattern;
function _path() {
const data = _interopRequireDefault(require("path"));
const data = require("path");
_path = function () {
return data;
......@@ -15,19 +15,7 @@ function _path() {
return data;
}
function _escapeRegExp() {
const data = _interopRequireDefault(require("lodash/escapeRegExp"));
_escapeRegExp = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const sep = `\\${_path().default.sep}`;
const sep = `\\${_path().sep}`;
const endSep = `(?:${sep}|$)`;
const substitution = `[^${sep}]+`;
const starPat = `(?:${substitution}${sep})`;
......@@ -35,8 +23,12 @@ const starPatLast = `(?:${substitution}${endSep})`;
const starStarPat = `${starPat}*?`;
const starStarPatLast = `${starPat}*?${starPatLast}?`;
function escapeRegExp(string) {
return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
}
function pathToPattern(pattern, dirname) {
const parts = _path().default.resolve(dirname, pattern).split(_path().default.sep);
const parts = _path().resolve(dirname, pattern).split(_path().sep);
return new RegExp(["^", ...parts.map((part, i) => {
const last = i === parts.length - 1;
......@@ -44,9 +36,9 @@ function pathToPattern(pattern, dirname) {
if (part === "*") return last ? starPatLast : starPat;
if (part.indexOf("*.") === 0) {
return substitution + (0, _escapeRegExp().default)(part.slice(1)) + (last ? endSep : sep);
return substitution + escapeRegExp(part.slice(1)) + (last ? endSep : sep);
}
return (0, _escapeRegExp().default)(part) + (last ? endSep : sep);
return escapeRegExp(part) + (last ? endSep : sep);
})].join(""));
}
\ No newline at end of file
......@@ -7,6 +7,14 @@ exports.default = void 0;
class Plugin {
constructor(plugin, options, key) {
this.key = void 0;
this.manipulateOptions = void 0;
this.post = void 0;
this.pre = void 0;
this.visitor = void 0;
this.parserOverride = void 0;
this.generatorOverride = void 0;
this.options = void 0;
this.key = plugin.name || key;
this.manipulateOptions = plugin.manipulateOptions;
this.post = plugin.post;
......
......@@ -4,17 +4,14 @@ Object.defineProperty(exports, "__esModule", {
value: true
});
exports.mergeOptions = mergeOptions;
exports.isIterableIterator = isIterableIterator;
function mergeOptions(target, source) {
for (const k of Object.keys(source)) {
if (k === "parserOpts" && source.parserOpts) {
const parserOpts = source.parserOpts;
const targetObj = target.parserOpts = target.parserOpts || {};
if ((k === "parserOpts" || k === "generatorOpts" || k === "assumptions") && source[k]) {
const parserOpts = source[k];
const targetObj = target[k] || (target[k] = {});
mergeDefaultFields(targetObj, parserOpts);
} else if (k === "generatorOpts" && source.generatorOpts) {
const generatorOpts = source.generatorOpts;
const targetObj = target.generatorOpts = target.generatorOpts || {};
mergeDefaultFields(targetObj, generatorOpts);
} else {
const val = source[k];
if (val !== undefined) target[k] = val;
......@@ -27,4 +24,8 @@ function mergeDefaultFields(target, source) {
const val = source[k];
if (val !== undefined) target[k] = val;
}
}
function isIterableIterator(value) {
return !!value && typeof value.next === "function" && typeof value[Symbol.iterator] === "function";
}
\ No newline at end of file
......@@ -21,6 +21,20 @@ exports.assertConfigApplicableTest = assertConfigApplicableTest;
exports.assertConfigFileSearch = assertConfigFileSearch;
exports.assertBabelrcSearch = assertBabelrcSearch;
exports.assertPluginList = assertPluginList;
exports.assertTargets = assertTargets;
exports.assertAssumptions = assertAssumptions;
function _helperCompilationTargets() {
const data = require("@babel/helper-compilation-targets");
_helperCompilationTargets = function () {
return data;
};
return data;
}
var _options = require("./options");
function msg(loc) {
switch (loc.type) {
......@@ -88,7 +102,7 @@ function assertCallerMetadata(loc, value) {
const obj = assertObject(loc, value);
if (obj) {
if (typeof obj["name"] !== "string") {
if (typeof obj.name !== "string") {
throw new Error(`${msg(loc)} set but does not contain "name" property string`);
}
......@@ -264,5 +278,75 @@ function assertPluginTarget(loc, value) {
throw new Error(`${msg(loc)} must be a string, object, function`);
}
return value;
}
function assertTargets(loc, value) {
if ((0, _helperCompilationTargets().isBrowsersQueryValid)(value)) return value;
if (typeof value !== "object" || !value || Array.isArray(value)) {
throw new Error(`${msg(loc)} must be a string, an array of strings or an object`);
}
const browsersLoc = access(loc, "browsers");
const esmodulesLoc = access(loc, "esmodules");
assertBrowsersList(browsersLoc, value.browsers);
assertBoolean(esmodulesLoc, value.esmodules);
for (const key of Object.keys(value)) {
const val = value[key];
const subLoc = access(loc, key);
if (key === "esmodules") assertBoolean(subLoc, val);else if (key === "browsers") assertBrowsersList(subLoc, val);else if (!Object.hasOwnProperty.call(_helperCompilationTargets().TargetNames, key)) {
const validTargets = Object.keys(_helperCompilationTargets().TargetNames).join(", ");
throw new Error(`${msg(subLoc)} is not a valid target. Supported targets are ${validTargets}`);
} else assertBrowserVersion(subLoc, val);
}
return value;
}
function assertBrowsersList(loc, value) {
if (value !== undefined && !(0, _helperCompilationTargets().isBrowsersQueryValid)(value)) {
throw new Error(`${msg(loc)} must be undefined, a string or an array of strings`);
}
}
function assertBrowserVersion(loc, value) {
if (typeof value === "number" && Math.round(value) === value) return;
if (typeof value === "string") return;
throw new Error(`${msg(loc)} must be a string or an integer number`);
}
function assertAssumptions(loc, value) {
if (value === undefined) return;
if (typeof value !== "object" || value === null) {
throw new Error(`${msg(loc)} must be an object or undefined.`);
}
let root = loc;
do {
root = root.parent;
} while (root.type !== "root");
const inPreset = root.source === "preset";
for (const name of Object.keys(value)) {
const subLoc = access(loc, name);
if (!_options.assumptionsNames.has(name)) {
throw new Error(`${msg(subLoc)} is not a supported assumption.`);
}
if (typeof value[name] !== "boolean") {
throw new Error(`${msg(subLoc)} must be a boolean.`);
}
if (inPreset && value[name] === false) {
throw new Error(`${msg(subLoc)} cannot be set to 'false' inside presets.`);
}
}
return value;
}
\ No newline at end of file
......@@ -4,15 +4,15 @@ Object.defineProperty(exports, "__esModule", {
value: true
});
exports.validate = validate;
exports.checkNoUnwrappedItemOptionPairs = checkNoUnwrappedItemOptionPairs;
exports.assumptionsNames = void 0;
var _plugin = _interopRequireDefault(require("../plugin"));
var _plugin = require("../plugin");
var _removed = _interopRequireDefault(require("./removed"));
var _removed = require("./removed");
var _optionAssertions = require("./option-assertions");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const ROOT_VALIDATORS = {
cwd: _optionAssertions.assertString,
root: _optionAssertions.assertString,
......@@ -23,6 +23,7 @@ const ROOT_VALIDATORS = {
filenameRelative: _optionAssertions.assertString,
code: _optionAssertions.assertBoolean,
ast: _optionAssertions.assertBoolean,
cloneInputAst: _optionAssertions.assertBoolean,
envName: _optionAssertions.assertString
};
const BABELRC_VALIDATORS = {
......@@ -32,13 +33,17 @@ const BABELRC_VALIDATORS = {
const NONPRESET_VALIDATORS = {
extends: _optionAssertions.assertString,
ignore: _optionAssertions.assertIgnoreList,
only: _optionAssertions.assertIgnoreList
only: _optionAssertions.assertIgnoreList,
targets: _optionAssertions.assertTargets,
browserslistConfigFile: _optionAssertions.assertConfigFileSearch,
browserslistEnv: _optionAssertions.assertString
};
const COMMON_VALIDATORS = {
inputSourceMap: _optionAssertions.assertInputSourceMap,
presets: _optionAssertions.assertPluginList,
plugins: _optionAssertions.assertPluginList,
passPerPreset: _optionAssertions.assertBoolean,
assumptions: _optionAssertions.assertAssumptions,
env: assertEnvSet,
overrides: assertOverridesList,
test: _optionAssertions.assertConfigApplicableTest,
......@@ -58,13 +63,19 @@ const COMMON_VALIDATORS = {
sourceMap: _optionAssertions.assertSourceMaps,
sourceFileName: _optionAssertions.assertString,
sourceRoot: _optionAssertions.assertString,
getModuleId: _optionAssertions.assertFunction,
moduleRoot: _optionAssertions.assertString,
moduleIds: _optionAssertions.assertBoolean,
moduleId: _optionAssertions.assertString,
parserOpts: _optionAssertions.assertObject,
generatorOpts: _optionAssertions.assertObject
};
{
Object.assign(COMMON_VALIDATORS, {
getModuleId: _optionAssertions.assertFunction,
moduleRoot: _optionAssertions.assertString,
moduleIds: _optionAssertions.assertBoolean,
moduleId: _optionAssertions.assertString
});
}
const assumptionsNames = new Set(["arrayLikeIsIterable", "constantReexports", "constantSuper", "enumerableModuleMeta", "ignoreFunctionLength", "ignoreToPrimitiveHint", "iterableIsArray", "mutableTemplateObject", "noClassCalls", "noDocumentAll", "noNewArrows", "objectRestNoSymbols", "privateFieldsAsProperties", "pureGetters", "setClassMethods", "setComputedProperties", "setPublicClassFields", "setSpreadProperties", "skipForOfIteratorClosing", "superIsCallableConstructor"]);
exports.assumptionsNames = assumptionsNames;
function getSource(loc) {
return loc.type === "root" ? loc.source : getSource(loc.parent);
......@@ -117,10 +128,11 @@ function throwUnknownError(loc) {
message,
version = 5
} = _removed.default[key];
throw new ReferenceError(`Using removed Babel ${version} option: ${(0, _optionAssertions.msg)(loc)} - ${message}`);
throw new Error(`Using removed Babel ${version} option: ${(0, _optionAssertions.msg)(loc)} - ${message}`);
} else {
const unknownOptErr = `Unknown option: ${(0, _optionAssertions.msg)(loc)}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`;
throw new ReferenceError(unknownOptErr);
const unknownOptErr = new Error(`Unknown option: ${(0, _optionAssertions.msg)(loc)}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`);
unknownOptErr.code = "BABEL_UNKNOWN_OPTION";
throw unknownOptErr;
}
}
......@@ -185,4 +197,14 @@ function assertOverridesList(loc, value) {
}
return arr;
}
function checkNoUnwrappedItemOptionPairs(items, index, type, e) {
if (index === 0) return;
const lastItem = items[index - 1];
const thisItem = items[index];
if (lastItem.file && lastItem.options === undefined && typeof thisItem.value === "object") {
e.message += `\n- Maybe you meant to use\n` + `"${type}": [\n ["${lastItem.file.request}", ${JSON.stringify(thisItem.value, undefined, 2)}]\n]\n` + `To be a valid ${type}, its name and options should be wrapped in a pair of brackets`;
}
}
\ No newline at end of file
......@@ -18,14 +18,14 @@ const VALIDATORS = {
generatorOverride: _optionAssertions.assertFunction
};
function assertVisitorMap(key, value) {
const obj = (0, _optionAssertions.assertObject)(key, value);
function assertVisitorMap(loc, value) {
const obj = (0, _optionAssertions.assertObject)(loc, value);
if (obj) {
Object.keys(obj).forEach(prop => assertVisitorHandler(prop, obj[prop]));
if (obj.enter || obj.exit) {
throw new Error(`.${key} cannot contain catch-all "enter" or "exit" handlers. Please target individual nodes.`);
throw new Error(`${(0, _optionAssertions.msg)(loc)} cannot contain catch-all "enter" or "exit" handlers. Please target individual nodes.`);
}
}
......@@ -53,12 +53,19 @@ function validatePluginObject(obj) {
};
Object.keys(obj).forEach(key => {
const validator = VALIDATORS[key];
const optLoc = {
type: "option",
name: key,
parent: rootPath
};
if (validator) validator(optLoc, obj[key]);else throw new Error(`.${key} is not a valid Plugin property`);
if (validator) {
const optLoc = {
type: "option",
name: key,
parent: rootPath
};
validator(optLoc, obj[key]);
} else {
const invalidPluginPropertyError = new Error(`.${key} is not a valid Plugin property`);
invalidPluginPropertyError.code = "BABEL_UNKNOWN_PLUGIN_PROPERTY";
throw invalidPluginPropertyError;
}
});
return obj;
}
\ No newline at end of file
......@@ -28,12 +28,6 @@ Object.defineProperty(exports, "resolvePreset", {
return _files.resolvePreset;
}
});
Object.defineProperty(exports, "version", {
enumerable: true,
get: function () {
return _package.version;
}
});
Object.defineProperty(exports, "getEnv", {
enumerable: true,
get: function () {
......@@ -61,7 +55,19 @@ Object.defineProperty(exports, "template", {
Object.defineProperty(exports, "createConfigItem", {
enumerable: true,
get: function () {
return _item.createConfigItem;
return _config.createConfigItem;
}
});
Object.defineProperty(exports, "createConfigItemSync", {
enumerable: true,
get: function () {
return _config.createConfigItemSync;
}
});
Object.defineProperty(exports, "createConfigItemAsync", {
enumerable: true,
get: function () {
return _config.createConfigItemAsync;
}
});
Object.defineProperty(exports, "loadPartialConfig", {
......@@ -70,12 +76,36 @@ Object.defineProperty(exports, "loadPartialConfig", {
return _config.loadPartialConfig;
}
});
Object.defineProperty(exports, "loadPartialConfigSync", {
enumerable: true,
get: function () {
return _config.loadPartialConfigSync;
}
});
Object.defineProperty(exports, "loadPartialConfigAsync", {
enumerable: true,
get: function () {
return _config.loadPartialConfigAsync;
}
});
Object.defineProperty(exports, "loadOptions", {
enumerable: true,
get: function () {
return _config.loadOptions;
}
});
Object.defineProperty(exports, "loadOptionsSync", {
enumerable: true,
get: function () {
return _config.loadOptionsSync;
}
});
Object.defineProperty(exports, "loadOptionsAsync", {
enumerable: true,
get: function () {
return _config.loadOptionsAsync;
}
});
Object.defineProperty(exports, "transform", {
enumerable: true,
get: function () {
......@@ -148,20 +178,18 @@ Object.defineProperty(exports, "parseAsync", {
return _parse.parseAsync;
}
});
exports.types = exports.OptionManager = exports.DEFAULT_EXTENSIONS = void 0;
exports.types = exports.OptionManager = exports.DEFAULT_EXTENSIONS = exports.version = void 0;
var _file = _interopRequireDefault(require("./transformation/file/file"));
var _file = require("./transformation/file/file");
var _buildExternalHelpers = _interopRequireDefault(require("./tools/build-external-helpers"));
var _buildExternalHelpers = require("./tools/build-external-helpers");
var _files = require("./config/files");
var _package = require("../package.json");
var _environment = require("./config/helpers/environment");
function _types() {
const data = _interopRequireWildcard(require("@babel/types"));
const data = require("@babel/types");
_types = function () {
return data;
......@@ -188,7 +216,7 @@ function _parser() {
}
function _traverse() {
const data = _interopRequireDefault(require("@babel/traverse"));
const data = require("@babel/traverse");
_traverse = function () {
return data;
......@@ -198,7 +226,7 @@ function _traverse() {
}
function _template() {
const data = _interopRequireDefault(require("@babel/template"));
const data = require("@babel/template");
_template = function () {
return data;
......@@ -207,8 +235,6 @@ function _template() {
return data;
}
var _item = require("./config/item");
var _config = require("./config");
var _transform = require("./transform");
......@@ -219,13 +245,9 @@ var _transformAst = require("./transform-ast");
var _parse = require("./parse");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs"]);
const version = "7.14.6";
exports.version = version;
const DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs", ".cjs"]);
exports.DEFAULT_EXTENSIONS = DEFAULT_EXTENSIONS;
class OptionManager {
......
......@@ -3,63 +3,46 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parseSync = parseSync;
exports.parseAsync = parseAsync;
exports.parse = void 0;
exports.parseAsync = exports.parseSync = exports.parse = void 0;
var _config = _interopRequireDefault(require("./config"));
function _gensync() {
const data = require("gensync");
var _normalizeFile = _interopRequireDefault(require("./transformation/normalize-file"));
_gensync = function () {
return data;
};
var _normalizeOpts = _interopRequireDefault(require("./transformation/normalize-opts"));
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _config = require("./config");
const parse = function parse(code, opts, callback) {
if (typeof opts === "function") {
callback = opts;
opts = undefined;
}
var _parser = require("./parser");
var _normalizeOpts = require("./transformation/normalize-opts");
if (callback === undefined) return parseSync(code, opts);
const config = (0, _config.default)(opts);
const parseRunner = _gensync()(function* parse(code, opts) {
const config = yield* (0, _config.default)(opts);
if (config === null) {
return null;
}
const cb = callback;
process.nextTick(() => {
let ast = null;
return yield* (0, _parser.default)(config.passes, (0, _normalizeOpts.default)(config), code);
});
try {
const cfg = (0, _config.default)(opts);
if (cfg === null) return cb(null, null);
ast = (0, _normalizeFile.default)(cfg.passes, (0, _normalizeOpts.default)(cfg), code).ast;
} catch (err) {
return cb(err);
}
const parse = function parse(code, opts, callback) {
if (typeof opts === "function") {
callback = opts;
opts = undefined;
}
cb(null, ast);
});
if (callback === undefined) return parseRunner.sync(code, opts);
parseRunner.errback(code, opts, callback);
};
exports.parse = parse;
function parseSync(code, opts) {
const config = (0, _config.default)(opts);
if (config === null) {
return null;
}
return (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code).ast;
}
function parseAsync(code, opts) {
return new Promise((res, rej) => {
parse(code, opts, (err, result) => {
if (err == null) res(result);else rej(err);
});
});
}
\ No newline at end of file
const parseSync = parseRunner.sync;
exports.parseSync = parseSync;
const parseAsync = parseRunner.async;
exports.parseAsync = parseAsync;
\ No newline at end of file
......@@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", {
exports.default = _default;
function helpers() {
const data = _interopRequireWildcard(require("@babel/helpers"));
const data = require("@babel/helpers");
helpers = function () {
return data;
......@@ -16,7 +16,7 @@ function helpers() {
}
function _generator() {
const data = _interopRequireDefault(require("@babel/generator"));
const data = require("@babel/generator");
_generator = function () {
return data;
......@@ -26,7 +26,7 @@ function _generator() {
}
function _template() {
const data = _interopRequireDefault(require("@babel/template"));
const data = require("@babel/template");
_template = function () {
return data;
......@@ -36,7 +36,7 @@ function _template() {
}
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
const data = require("@babel/types");
t = function () {
return data;
......@@ -45,13 +45,9 @@ function t() {
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _file = require("../transformation/file/file");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const buildUmdWrapper = replacements => _template().default`
const buildUmdWrapper = replacements => (0, _template().default)`
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define(AMD_ARGUMENTS, factory);
......@@ -65,30 +61,30 @@ const buildUmdWrapper = replacements => _template().default`
});
`(replacements);
function buildGlobal(whitelist) {
function buildGlobal(allowlist) {
const namespace = t().identifier("babelHelpers");
const body = [];
const container = t().functionExpression(null, [t().identifier("global")], t().blockStatement(body));
const tree = t().program([t().expressionStatement(t().callExpression(container, [t().conditionalExpression(t().binaryExpression("===", t().unaryExpression("typeof", t().identifier("global")), t().stringLiteral("undefined")), t().identifier("self"), t().identifier("global"))]))]);
body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().assignmentExpression("=", t().memberExpression(t().identifier("global"), namespace), t().objectExpression([])))]));
buildHelpers(body, namespace, whitelist);
buildHelpers(body, namespace, allowlist);
return tree;
}
function buildModule(whitelist) {
function buildModule(allowlist) {
const body = [];
const refs = buildHelpers(body, null, whitelist);
const refs = buildHelpers(body, null, allowlist);
body.unshift(t().exportNamedDeclaration(null, Object.keys(refs).map(name => {
return t().exportSpecifier(t().cloneNode(refs[name]), t().identifier(name));
})));
return t().program(body, [], "module");
}
function buildUmd(whitelist) {
function buildUmd(allowlist) {
const namespace = t().identifier("babelHelpers");
const body = [];
body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().identifier("global"))]));
buildHelpers(body, namespace, whitelist);
buildHelpers(body, namespace, allowlist);
return t().program([buildUmdWrapper({
FACTORY_PARAMETERS: t().identifier("global"),
BROWSER_ARGUMENTS: t().assignmentExpression("=", t().memberExpression(t().identifier("root"), namespace), t().objectExpression([])),
......@@ -99,25 +95,26 @@ function buildUmd(whitelist) {
})]);
}
function buildVar(whitelist) {
function buildVar(allowlist) {
const namespace = t().identifier("babelHelpers");
const body = [];
body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().objectExpression([]))]));
const tree = t().program(body);
buildHelpers(body, namespace, whitelist);
buildHelpers(body, namespace, allowlist);
body.push(t().expressionStatement(namespace));
return tree;
}
function buildHelpers(body, namespace, whitelist) {
function buildHelpers(body, namespace, allowlist) {
const getHelperReference = name => {
return namespace ? t().memberExpression(namespace, t().identifier(name)) : t().identifier(`_${name}`);
};
const refs = {};
helpers().list.forEach(function (name) {
if (whitelist && whitelist.indexOf(name) < 0) return;
if (allowlist && allowlist.indexOf(name) < 0) return;
const ref = refs[name] = getHelperReference(name);
helpers().ensure(name, _file.default);
const {
nodes
} = helpers().get(name, getHelperReference, ref);
......@@ -126,7 +123,7 @@ function buildHelpers(body, namespace, whitelist) {
return refs;
}
function _default(whitelist, outputType = "global") {
function _default(allowlist, outputType = "global") {
let tree;
const build = {
global: buildGlobal,
......@@ -136,7 +133,7 @@ function _default(whitelist, outputType = "global") {
}[outputType];
if (build) {
tree = build(whitelist);
tree = build(allowlist);
} else {
throw new Error(`Unsupported output type ${outputType}`);
}
......
......@@ -3,15 +3,28 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformFromAstSync = transformFromAstSync;
exports.transformFromAstAsync = transformFromAstAsync;
exports.transformFromAst = void 0;
exports.transformFromAstAsync = exports.transformFromAstSync = exports.transformFromAst = void 0;
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
var _config = _interopRequireDefault(require("./config"));
var _config = require("./config");
var _transformation = require("./transformation");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const transformFromAstRunner = _gensync()(function* (ast, code, opts) {
const config = yield* (0, _config.default)(opts);
if (config === null) return null;
if (!ast) throw new Error("No AST given");
return yield* (0, _transformation.run)(config, code, ast);
});
const transformFromAst = function transformFromAst(ast, code, opts, callback) {
if (typeof opts === "function") {
......@@ -19,36 +32,15 @@ const transformFromAst = function transformFromAst(ast, code, opts, callback) {
opts = undefined;
}
if (callback === undefined) return transformFromAstSync(ast, code, opts);
const cb = callback;
process.nextTick(() => {
let cfg;
try {
cfg = (0, _config.default)(opts);
if (cfg === null) return cb(null, null);
} catch (err) {
return cb(err);
}
if (!ast) return cb(new Error("No AST given"));
(0, _transformation.runAsync)(cfg, code, ast, cb);
});
if (callback === undefined) {
return transformFromAstRunner.sync(ast, code, opts);
}
transformFromAstRunner.errback(ast, code, opts, callback);
};
exports.transformFromAst = transformFromAst;
function transformFromAstSync(ast, code, opts) {
const config = (0, _config.default)(opts);
if (config === null) return null;
if (!ast) throw new Error("No AST given");
return (0, _transformation.runSync)(config, code, ast);
}
function transformFromAstAsync(ast, code, opts) {
return new Promise((res, rej) => {
transformFromAst(ast, code, opts, (err, result) => {
if (err == null) res(result);else rej(err);
});
});
}
\ No newline at end of file
const transformFromAstSync = transformFromAstRunner.sync;
exports.transformFromAstSync = transformFromAstSync;
const transformFromAstAsync = transformFromAstRunner.async;
exports.transformFromAstAsync = transformFromAstAsync;
\ No newline at end of file
......@@ -3,89 +3,39 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformFileSync = transformFileSync;
exports.transformFileAsync = transformFileAsync;
exports.transformFile = void 0;
exports.transformFileAsync = exports.transformFileSync = exports.transformFile = void 0;
function _fs() {
const data = _interopRequireDefault(require("fs"));
function _gensync() {
const data = require("gensync");
_fs = function () {
_gensync = function () {
return data;
};
return data;
}
var _config = _interopRequireDefault(require("./config"));
var _config = require("./config");
var _transformation = require("./transformation");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var fs = require("./gensync-utils/fs");
({});
const transformFile = function transformFile(filename, opts, callback) {
let options;
if (typeof opts === "function") {
callback = opts;
opts = undefined;
}
if (opts == null) {
options = {
filename
};
} else if (opts && typeof opts === "object") {
options = Object.assign({}, opts, {
filename
});
}
process.nextTick(() => {
let cfg;
try {
cfg = (0, _config.default)(options);
if (cfg === null) return callback(null, null);
} catch (err) {
return callback(err);
}
const config = cfg;
_fs().default.readFile(filename, "utf8", function (err, code) {
if (err) return callback(err, null);
(0, _transformation.runAsync)(config, code, null, callback);
});
const transformFileRunner = _gensync()(function* (filename, opts) {
const options = Object.assign({}, opts, {
filename
});
};
exports.transformFile = transformFile;
function transformFileSync(filename, opts) {
let options;
if (opts == null) {
options = {
filename
};
} else if (opts && typeof opts === "object") {
options = Object.assign({}, opts, {
filename
});
}
const config = (0, _config.default)(options);
const config = yield* (0, _config.default)(options);
if (config === null) return null;
return (0, _transformation.runSync)(config, _fs().default.readFileSync(filename, "utf8"));
}
const code = yield* fs.readFile(filename, "utf8");
return yield* (0, _transformation.run)(config, code);
});
function transformFileAsync(filename, opts) {
return new Promise((res, rej) => {
transformFile(filename, opts, (err, result) => {
if (err == null) res(result);else rej(err);
});
});
}
\ No newline at end of file
const transformFile = transformFileRunner.errback;
exports.transformFile = transformFile;
const transformFileSync = transformFileRunner.sync;
exports.transformFileSync = transformFileSync;
const transformFileAsync = transformFileRunner.async;
exports.transformFileAsync = transformFileAsync;
\ No newline at end of file
......@@ -3,15 +3,27 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformSync = transformSync;
exports.transformAsync = transformAsync;
exports.transform = void 0;
exports.transformAsync = exports.transformSync = exports.transform = void 0;
function _gensync() {
const data = require("gensync");
var _config = _interopRequireDefault(require("./config"));
_gensync = function () {
return data;
};
return data;
}
var _config = require("./config");
var _transformation = require("./transformation");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const transformRunner = _gensync()(function* transform(code, opts) {
const config = yield* (0, _config.default)(opts);
if (config === null) return null;
return yield* (0, _transformation.run)(config, code);
});
const transform = function transform(code, opts, callback) {
if (typeof opts === "function") {
......@@ -19,34 +31,12 @@ const transform = function transform(code, opts, callback) {
opts = undefined;
}
if (callback === undefined) return transformSync(code, opts);
const cb = callback;
process.nextTick(() => {
let cfg;
try {
cfg = (0, _config.default)(opts);
if (cfg === null) return cb(null, null);
} catch (err) {
return cb(err);
}
(0, _transformation.runAsync)(cfg, code, null, cb);
});
if (callback === undefined) return transformRunner.sync(code, opts);
transformRunner.errback(code, opts, callback);
};
exports.transform = transform;
function transformSync(code, opts) {
const config = (0, _config.default)(opts);
if (config === null) return null;
return (0, _transformation.runSync)(config, code);
}
function transformAsync(code, opts) {
return new Promise((res, rej) => {
transform(code, opts, (err, result) => {
if (err == null) res(result);else rej(err);
});
});
}
\ No newline at end of file
const transformSync = transformRunner.sync;
exports.transformSync = transformSync;
const transformAsync = transformRunner.async;
exports.transformAsync = transformAsync;
\ No newline at end of file
......@@ -5,36 +5,61 @@ Object.defineProperty(exports, "__esModule", {
});
exports.default = loadBlockHoistPlugin;
function _sortBy() {
const data = _interopRequireDefault(require("lodash/sortBy"));
function _traverse() {
const data = require("@babel/traverse");
_sortBy = function () {
_traverse = function () {
return data;
};
return data;
}
var _config = _interopRequireDefault(require("../config"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _plugin = require("../config/plugin");
let LOADED_PLUGIN;
function loadBlockHoistPlugin() {
if (!LOADED_PLUGIN) {
const config = (0, _config.default)({
babelrc: false,
configFile: false,
plugins: [blockHoistPlugin]
});
LOADED_PLUGIN = config ? config.passes[0][0] : undefined;
if (!LOADED_PLUGIN) throw new Error("Assertion failure");
LOADED_PLUGIN = new _plugin.default(Object.assign({}, blockHoistPlugin, {
visitor: _traverse().default.explode(blockHoistPlugin.visitor)
}), {});
}
return LOADED_PLUGIN;
}
function priority(bodyNode) {
const priority = bodyNode == null ? void 0 : bodyNode._blockHoist;
if (priority == null) return 1;
if (priority === true) return 2;
return priority;
}
function stableSort(body) {
const buckets = Object.create(null);
for (let i = 0; i < body.length; i++) {
const n = body[i];
const p = priority(n);
const bucket = buckets[p] || (buckets[p] = []);
bucket.push(n);
}
const keys = Object.keys(buckets).map(k => +k).sort((a, b) => b - a);
let index = 0;
for (const key of keys) {
const bucket = buckets[key];
for (const n of bucket) {
body[index++] = n;
}
}
return body;
}
const blockHoistPlugin = {
name: "internal.blockHoist",
visitor: {
......@@ -42,24 +67,26 @@ const blockHoistPlugin = {
exit({
node
}) {
const {
body
} = node;
let max = Math.pow(2, 30) - 1;
let hasChange = false;
for (let i = 0; i < node.body.length; i++) {
const bodyNode = node.body[i];
for (let i = 0; i < body.length; i++) {
const n = body[i];
const p = priority(n);
if (bodyNode && bodyNode._blockHoist != null) {
if (p > max) {
hasChange = true;
break;
}
max = p;
}
if (!hasChange) return;
node.body = (0, _sortBy().default)(node.body, function (bodyNode) {
let priority = bodyNode && bodyNode._blockHoist;
if (priority == null) priority = 1;
if (priority === true) priority = 2;
return -1 * priority;
});
node.body = stableSort(body.slice());
}
}
......
......@@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", {
exports.default = void 0;
function helpers() {
const data = _interopRequireWildcard(require("@babel/helpers"));
const data = require("@babel/helpers");
helpers = function () {
return data;
......@@ -16,7 +16,7 @@ function helpers() {
}
function _traverse() {
const data = _interopRequireWildcard(require("@babel/traverse"));
const data = require("@babel/traverse");
_traverse = function () {
return data;
......@@ -36,7 +36,7 @@ function _codeFrame() {
}
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
const data = require("@babel/types");
t = function () {
return data;
......@@ -45,21 +45,25 @@ function t() {
return data;
}
function _semver() {
const data = _interopRequireDefault(require("semver"));
function _helperModuleTransforms() {
const data = require("@babel/helper-module-transforms");
_semver = function () {
_helperModuleTransforms = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _semver() {
const data = require("semver");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
_semver = function () {
return data;
};
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
return data;
}
const errorVisitor = {
enter(path, state) {
......@@ -80,9 +84,11 @@ class File {
inputMap
}) {
this._map = new Map();
this.opts = void 0;
this.declarations = {};
this.path = null;
this.ast = {};
this.scope = void 0;
this.metadata = {};
this.code = "";
this.inputMap = null;
......@@ -139,36 +145,7 @@ class File {
}
getModuleName() {
const {
filename,
filenameRelative = filename,
moduleId,
moduleIds = !!moduleId,
getModuleId,
sourceRoot: sourceRootTmp,
moduleRoot = sourceRootTmp,
sourceRoot = moduleRoot
} = this.opts;
if (!moduleIds) return null;
if (moduleId != null && !getModuleId) {
return moduleId;
}
let moduleName = moduleRoot != null ? moduleRoot + "/" : "";
if (filenameRelative) {
const sourceRootReplacer = sourceRoot != null ? new RegExp("^" + sourceRoot + "/?") : "";
moduleName += filenameRelative.replace(sourceRootReplacer, "").replace(/\.(\w*?)$/, "");
}
moduleName = moduleName.replace(/\\/g, "/");
if (getModuleId) {
return getModuleId(moduleName) || moduleName;
} else {
return moduleName;
}
return (0, _helperModuleTransforms().getModuleName)(this.opts, this.opts);
}
addImport() {
......@@ -186,8 +163,8 @@ class File {
}
if (typeof versionRange !== "string") return true;
if (_semver().default.valid(versionRange)) versionRange = `^${versionRange}`;
return !_semver().default.intersects(`<${minVersion}`, versionRange) && !_semver().default.intersects(`>=8.0.0`, versionRange);
if (_semver().valid(versionRange)) versionRange = `^${versionRange}`;
return !_semver().intersects(`<${minVersion}`, versionRange) && !_semver().intersects(`>=8.0.0`, versionRange);
}
addHelper(name) {
......@@ -200,7 +177,7 @@ class File {
if (res) return res;
}
helpers().ensure(name);
helpers().ensure(name, File);
const uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
const dependencies = {};
......@@ -232,7 +209,7 @@ class File {
throw new Error("This function has been moved into the template literal transform itself.");
}
buildCodeFrameError(node, msg, Error = SyntaxError) {
buildCodeFrameError(node, msg, _Error = SyntaxError) {
let loc = node && (node.loc || node._loc);
if (!loc && node) {
......@@ -264,7 +241,7 @@ class File {
});
}
return new Error(msg);
return new _Error(msg);
}
}
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment