Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

babel-codemod

Package Overview
Dependencies
Maintainers
1
Versions
53
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

babel-codemod - npm Package Compare versions

Comparing version 1.7.3 to 1.7.4

src/CLIEngine.d.ts

4

package.json
{
"name": "babel-codemod",
"version": "1.7.3",
"version": "1.7.4",
"description": "babel-codemod rewrites JavaScript using babel plugins.",

@@ -70,3 +70,3 @@ "main": "src/index.js",

"typescript": "^2.7.2",
"yarnhook": "^0.1.1"
"yarnhook": "^0.2.0"
},

@@ -73,0 +73,0 @@ "dependencies": {

@@ -14,8 +14,19 @@ "use strict";

const path_1 = require("path");
const iterateSources_1 = require("./iterateSources");
const CLIEngine_1 = require("./CLIEngine");
const Config_1 = require("./Config");
const Options_1 = require("./Options");
const ProcessSnapshot_1 = require("./ProcessSnapshot");
const TransformRunner_1 = require("./TransformRunner");
function optionAnnotation(value) {
if (Array.isArray(value) || value instanceof Map) {
return ' (allows multiple)';
}
else if (typeof value === 'boolean') {
return ` (default: ${value ? 'on' : 'off'})`;
}
else {
return '';
}
}
function printHelp(argv, out) {
let $0 = path_1.basename(argv[1]);
let defaults = new Config_1.default();
out.write(`

@@ -25,12 +36,12 @@ ${$0} [OPTIONS] [PATH … | --stdio]

OPTIONS
-p, --plugin PLUGIN Transform sources with PLUGIN (allows multiple).
--remote-plugin URL Fetch a plugin from URL (allows multiple).
-o, --plugin-options PLUGIN=OPTS JSON-encoded OPTS for PLUGIN (allows multiple).
-r, --require PATH Require PATH before transform (allows multiple).
--extensions EXTS Comma-separated extensions to process (default: "${Array.from(Options_1.DEFAULT_EXTENSIONS).join(',')}").
--[no-]transpile-plugins Transpile plugins to enable future syntax (default: on).
-p, --plugin PLUGIN Transform sources with PLUGIN${optionAnnotation(defaults.localPlugins)}.
--remote-plugin URL Fetch a plugin from URL${optionAnnotation(defaults.remotePlugins)}.
-o, --plugin-options PLUGIN=OPTS JSON-encoded OPTS for PLUGIN${optionAnnotation(defaults.pluginOptions)}.
-r, --require PATH Require PATH before transform${optionAnnotation(defaults.requires)}.
--extensions EXTS Comma-separated extensions to process (default: "${Array.from(defaults.extensions).join(',')}").
--[no-]transpile-plugins Transpile plugins to enable future syntax${optionAnnotation(defaults.transpilePlugins)}.
--[no-]find-babel-config Run plugins through babel plugins/presets specified in local
.babelrc file instead of babel-preset-env (default: off).
-s, --stdio Read source from stdin and print to stdout.
-d, --dry Run plugins without modifying files on disk.
.babelrc file instead of babel-preset-env${optionAnnotation(defaults.findBabelConfig)}.
-s, --stdio Read source from stdin and print to stdout${optionAnnotation(defaults.stdio)}.
-d, --dry Run plugins without modifying files on disk${optionAnnotation(defaults.dry)}.
--version Print the version of ${$0}.

@@ -76,50 +87,25 @@ -h, --help Show this help message.

return __awaiter(this, void 0, void 0, function* () {
let options = Options_1.default.parse(argv.slice(2));
if (options instanceof Error) {
stderr.write(`ERROR: ${options.message}\n`);
let command;
try {
command = new Options_1.default(argv.slice(2)).parse();
}
catch (error) {
stderr.write(`ERROR: ${error.message}\n`);
printHelp(argv, stderr);
return 1;
}
if (options.help) {
if (command.kind === 'help') {
printHelp(argv, stdout);
return 0;
}
if (options.version) {
if (command.kind === 'version') {
printVersion(argv, stdout);
return 0;
}
let snapshot = new ProcessSnapshot_1.default();
let plugins;
try {
options.loadBabelTranspile();
options.loadRequires();
plugins = yield options.getBabelPlugins();
}
finally {
options.unloadBabelTranspile();
snapshot.restore();
}
let runner;
let stats = {
modified: 0,
total: 0,
errors: 0
};
let dryRun = options.dry;
let sourcesIterator;
if (options.stdio) {
sourcesIterator = [new TransformRunner_1.Source('<stdin>', yield getStream(stdin))][Symbol.iterator]();
}
else {
sourcesIterator = iterateSources_1.default(options.sourcePaths, options.extensions, options.ignore, fs.statSync, fs.readdirSync, fs.readFileSync);
}
runner = new TransformRunner_1.default(sourcesIterator, plugins);
let config = command.config;
let dim = stdout.isTTY ? '\x1b[2m' : '';
let reset = stdout.isTTY ? '\x1b[0m' : '';
for (let result of runner.run()) {
function onTransform(result) {
if (result.output) {
if (options.stdio) {
stdout.write(`${result.output}\n`);
}
else {
if (!config.stdio) {
if (result.output === result.source.content) {

@@ -129,7 +115,3 @@ stdout.write(`${dim}${result.source.path}${reset}\n`);

else {
stats.modified++;
stdout.write(`${result.source.path}\n`);
if (!dryRun) {
fs.writeFileSync(result.source.path, result.output);
}
}

@@ -139,4 +121,3 @@ }

else if (result.error) {
stats.errors++;
if (!options.stdio) {
if (!config.stdio) {
stderr.write(`Encountered an error while processing ${result.source.path}:\n`);

@@ -146,6 +127,6 @@ }

}
stats.total++;
}
if (!options.stdio) {
if (dryRun) {
let { stats } = yield new CLIEngine_1.default(config, onTransform, () => __awaiter(this, void 0, void 0, function* () { return yield getStream(stdin); }), (data) => stdout.write(data), fs).run();
if (!config.stdio) {
if (config.dry) {
stdout.write('DRY RUN: no files affected\n');

@@ -152,0 +133,0 @@ }

@@ -1,39 +0,17 @@

import { PathPredicate } from './iterateSources';
import { BabelPlugin, RawBabelPlugin } from './TransformRunner';
export declare const DEFAULT_EXTENSIONS: Set<string>;
export declare type ParseOptionsResult = Options | Error;
export declare class Plugin {
readonly rawPlugin: RawBabelPlugin;
readonly inferredName: string;
readonly source: string | undefined;
readonly resolvedPath: string | undefined;
readonly declaredName?: string;
constructor(rawPlugin: RawBabelPlugin, inferredName: string, source?: string | undefined, resolvedPath?: string | undefined);
import Config from './Config';
export interface RunCommand {
kind: 'run';
config: Config;
}
export interface HelpCommand {
kind: 'help';
}
export interface VersionCommand {
kind: 'version';
}
export declare type Command = RunCommand | HelpCommand | VersionCommand;
export default class Options {
readonly sourcePaths: Array<string>;
readonly localPlugins: Array<string>;
readonly remotePlugins: Array<string>;
readonly pluginOptions: Map<string, object>;
readonly extensions: Set<string>;
readonly requires: Array<string>;
readonly transpilePlugins: boolean;
readonly findBabelConfig: boolean;
readonly ignore: PathPredicate;
readonly stdio: boolean;
readonly help: boolean;
readonly version: boolean;
readonly dry: boolean;
constructor(sourcePaths: Array<string>, localPlugins: Array<string>, remotePlugins: Array<string>, pluginOptions: Map<string, object>, extensions: Set<string>, requires: Array<string>, transpilePlugins: boolean, findBabelConfig: boolean, ignore: PathPredicate, stdio: boolean, help: boolean, version: boolean, dry: boolean);
private pluginLoader;
private remotePluginLoader;
private _pluginCache?;
getPlugins(): Promise<Array<Plugin>>;
loadRequires(): void;
loadBabelTranspile(): void;
unloadBabelTranspile(): void;
getPlugin(name: string): Promise<Plugin | null>;
getBabelPlugins(): Promise<Array<BabelPlugin>>;
getBabelPlugin(name: string): Promise<BabelPlugin | null>;
static parse(args: Array<string>): ParseOptionsResult;
readonly args: Array<string>;
constructor(args: Array<string>);
parse(): RunCommand | HelpCommand | VersionCommand;
}
"use strict";
var __awaiter = (this && this.__awaiter) || function (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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const Babel = require("@babel/core");
const fs_1 = require("fs");

@@ -16,140 +7,12 @@ const glob_1 = require("glob");

const resolve_1 = require("resolve");
const source_map_support_1 = require("source-map-support");
const AllSyntaxPlugin_1 = require("./AllSyntaxPlugin");
const PluginLoader_1 = require("./PluginLoader");
const RecastPlugin_1 = require("./RecastPlugin");
const AstExplorerResolver_1 = require("./resolvers/AstExplorerResolver");
const FileSystemResolver_1 = require("./resolvers/FileSystemResolver");
const NetworkResolver_1 = require("./resolvers/NetworkResolver");
const PackageResolver_1 = require("./resolvers/PackageResolver");
const Config_1 = require("./Config");
const transpile_requires_1 = require("./transpile-requires");
exports.DEFAULT_EXTENSIONS = new Set(['.js', '.jsx']);
class Plugin {
constructor(rawPlugin, inferredName, source, resolvedPath) {
this.rawPlugin = rawPlugin;
this.inferredName = inferredName;
this.source = source;
this.resolvedPath = resolvedPath;
let instance = rawPlugin(Babel);
if (instance.name) {
this.declaredName = instance.name;
}
}
}
exports.Plugin = Plugin;
class Options {
constructor(sourcePaths, localPlugins, remotePlugins, pluginOptions, extensions, requires, transpilePlugins, findBabelConfig, ignore, stdio, help, version, dry) {
this.sourcePaths = sourcePaths;
this.localPlugins = localPlugins;
this.remotePlugins = remotePlugins;
this.pluginOptions = pluginOptions;
this.extensions = extensions;
this.requires = requires;
this.transpilePlugins = transpilePlugins;
this.findBabelConfig = findBabelConfig;
this.ignore = ignore;
this.stdio = stdio;
this.help = help;
this.version = version;
this.dry = dry;
this.pluginLoader = new PluginLoader_1.default([
new FileSystemResolver_1.default(),
new PackageResolver_1.default()
]);
this.remotePluginLoader = new PluginLoader_1.default([
new AstExplorerResolver_1.default(),
new NetworkResolver_1.default()
]);
constructor(args) {
this.args = args;
}
getPlugins() {
return __awaiter(this, void 0, void 0, function* () {
if (!this._pluginCache) {
let localPlugins = Promise.all(this.localPlugins.map((localPlugin) => __awaiter(this, void 0, void 0, function* () {
let pluginExports = yield this.pluginLoader.load(localPlugin);
let defaultExport = pluginExports['default'] || pluginExports;
return new Plugin(defaultExport, path_1.basename(localPlugin, path_1.extname(localPlugin)));
})));
let remotePlugins = Promise.all(this.remotePlugins.map((remotePlugin) => __awaiter(this, void 0, void 0, function* () {
let pluginExports = yield this.remotePluginLoader.load(remotePlugin);
let defaultExport = pluginExports['default'] || pluginExports;
return new Plugin(defaultExport, path_1.basename(remotePlugin, path_1.extname(remotePlugin)));
})));
this._pluginCache = [...(yield localPlugins), ...(yield remotePlugins)];
}
return this._pluginCache;
});
}
loadRequires() {
for (let modulePath of this.requires) {
require(modulePath);
}
}
loadBabelTranspile() {
if (this.transpilePlugins) {
transpile_requires_1.enable(this.findBabelConfig);
source_map_support_1.install();
}
}
unloadBabelTranspile() {
if (this.transpilePlugins) {
transpile_requires_1.disable();
}
}
getPlugin(name) {
return __awaiter(this, void 0, void 0, function* () {
for (let plugin of yield this.getPlugins()) {
if (plugin.declaredName === name || plugin.inferredName === name) {
return plugin;
}
}
return null;
});
}
getBabelPlugins() {
return __awaiter(this, void 0, void 0, function* () {
let result = [AllSyntaxPlugin_1.default, RecastPlugin_1.default];
for (let plugin of yield this.getPlugins()) {
let options = (plugin.declaredName && this.pluginOptions.get(plugin.declaredName)) ||
this.pluginOptions.get(plugin.inferredName);
if (options) {
result.push([plugin.rawPlugin, options]);
}
else {
result.push(plugin.rawPlugin);
}
}
return result;
});
}
getBabelPlugin(name) {
return __awaiter(this, void 0, void 0, function* () {
let plugin = yield this.getPlugin(name);
if (!plugin) {
return null;
}
let options = this.pluginOptions.get(name);
if (options) {
return [plugin.rawPlugin, options];
}
else {
return plugin.rawPlugin;
}
});
}
static parse(args) {
let sourcePaths = [];
let localPlugins = [];
let remotePlugins = [];
let pluginOptions = new Map();
let extensions = exports.DEFAULT_EXTENSIONS;
let ignore = (path, basename, root) => basename[0] === '.';
let requires = [];
let findBabelConfig = false;
let transpilePlugins = true;
let stdio = false;
let help = false;
let version = false;
let dry = false;
for (let i = 0; i < args.length; i++) {
let arg = args[i];
parse() {
let config = new Config_1.ConfigBuilder();
for (let i = 0; i < this.args.length; i++) {
let arg = this.args[i];
switch (arg) {

@@ -159,7 +22,7 @@ case '-p':

i++;
localPlugins.push(args[i]);
config.addLocalPlugin(this.args[i]);
break;
case '--remote-plugin':
i++;
remotePlugins.push(args[i]);
config.addRemotePlugin(this.args[i]);
break;

@@ -169,3 +32,3 @@ case '-o':

i++;
let nameAndOptions = args[i].split('=');
let nameAndOptions = this.args[i].split('=');
let name = nameAndOptions[0];

@@ -177,9 +40,9 @@ let optionsRaw = nameAndOptions[1];

});
pluginOptions.set(name, JSON.parse(optionsRaw));
config.setOptionsForPlugin(JSON.parse(optionsRaw), name);
}
try {
pluginOptions.set(name, JSON.parse(optionsRaw));
config.setOptionsForPlugin(JSON.parse(optionsRaw), name);
}
catch (err) {
return new Error(`unable to parse JSON config for ${name}: ${optionsRaw}`);
throw new Error(`unable to parse JSON config for ${name}: ${optionsRaw}`);
}

@@ -190,41 +53,41 @@ break;

i++;
requires.push(getRequirableModulePath(args[i]));
config.addRequire(getRequirableModulePath(this.args[i]));
break;
case '--transpile-plugins':
case '--no-transpile-plugins':
transpilePlugins = arg === '--transpile-plugins';
config.transpilePlugins(arg === '--transpile-plugins');
break;
case '--find-babel-config':
case '--no-find-babel-config':
findBabelConfig = arg === '--find-babel-config';
config.findBabelConfig(arg === '--find-babel-config');
break;
case '--extensions':
i++;
extensions = new Set(args[i].split(',').map(ext => (ext[0] === '.' ? ext : `.${ext}`)));
config.extensions(new Set(this.args[i]
.split(',')
.map(ext => (ext[0] === '.' ? ext : `.${ext}`))));
break;
case '-s':
case '--stdio':
stdio = true;
config.stdio(true);
break;
case '-h':
case '--help':
help = true;
break;
return { kind: 'help' };
case '--version':
version = true;
break;
return { kind: 'version' };
case '-d':
case '--dry':
dry = true;
config.dry(true);
break;
default:
if (arg[0] === '-') {
return new Error(`unexpected option: ${arg}`);
throw new Error(`unexpected option: ${arg}`);
}
else {
if (glob_1.hasMagic(arg)) {
sourcePaths.push(...glob_1.sync(arg));
config.addSourcePaths(...glob_1.sync(arg));
}
else {
sourcePaths.push(arg);
config.addSourcePath(arg);
}

@@ -235,3 +98,6 @@ }

}
return new Options(sourcePaths, localPlugins, remotePlugins, pluginOptions, extensions, requires, transpilePlugins, findBabelConfig, ignore, stdio, help, version, dry);
return {
kind: 'run',
config: config.build()
};
}

@@ -244,9 +110,12 @@ }

function getRequirableModulePath(modulePath) {
if (fs_1.existsSync(modulePath) || fs_1.existsSync(modulePath + '.js')) {
if (fs_1.existsSync(modulePath)) {
return path_1.resolve(modulePath);
}
else {
return resolve_1.sync(modulePath, { basedir: process.cwd() });
for (let ext of transpile_requires_1.SUPPORTED_EXTENSIONS) {
if (fs_1.existsSync(modulePath + ext)) {
return path_1.resolve(modulePath + ext);
}
}
return resolve_1.sync(modulePath, { basedir: process.cwd() });
}
//# sourceMappingURL=Options.js.map

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc