babel-codemod
Advanced tools
Comparing version 1.9.8 to 2.0.0
{ | ||
"name": "babel-codemod", | ||
"version": "1.9.8", | ||
"version": "2.0.0", | ||
"description": "babel-codemod rewrites JavaScript using babel plugins.", | ||
@@ -5,0 +5,0 @@ "main": "src/index.js", |
# babel-codemod | ||
babel-codemod rewrites JavaScript using babel plugins. | ||
babel-codemod rewrites JavaScript and TypeScript using babel plugins. | ||
@@ -24,7 +24,10 @@ ## Install | ||
path/to/file.js \ | ||
another/file.js | ||
another/file.js \ | ||
a/directory | ||
``` | ||
This will re-write the files `path/to/file.js` and `another/file.js` by transforming them with the babel plugin `transform-module-name`. Multiple plugins may be specified, and multiple files or directories may be re-written at once. | ||
This will re-write the files `path/to/file.js`, `another/file.js`, and any supported files found in `a/directory` by transforming them with the babel plugin `transform-module-name`. Multiple plugins may be specified, and multiple files or directories may be re-written at once. | ||
Note that TypeScript support is provided by babel and therefore may not completely support all valid TypeScript code. If you encounter an issue, consider looking for it in the [babel issues labeled `area: typescript`](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+label%3A%22area%3A+typescript%22+) before filing an issue with babel-codemod. | ||
Plugins may also be loaded from remote URLs, including saved [AST Explorer](https://astexplorer.net/) URLs, using `--remote-plugin`. This feature should only be used as a convenience to load code that you or someone you trust wrote. It will run with your full user privileges, so please exercise caution! | ||
@@ -31,0 +34,0 @@ |
import * as Babel from '@babel/core'; | ||
import { BabelOptions, ParseOptions } from './TransformRunner'; | ||
export declare const ALL_PLUGINS: string[]; | ||
import { BabelOptions, ParseOptions } from './BabelPluginTypes'; | ||
export default function (babel: typeof Babel): { | ||
manipulateOptions(opts: BabelOptions, parserOpts: ParseOptions): void; | ||
}; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.ALL_PLUGINS = [ | ||
'flow', | ||
const path_1 = require("path"); | ||
const extensions_1 = require("./extensions"); | ||
const BASIC_PLUGINS = [ | ||
'jsx', | ||
@@ -16,10 +17,19 @@ 'asyncGenerators', | ||
]; | ||
function pluginsForFilename(filename) { | ||
let isTypeScript = extensions_1.TypeScriptExtensions.has(path_1.extname(filename)); | ||
return isTypeScript | ||
? [...BASIC_PLUGINS, 'typescript'] | ||
: [...BASIC_PLUGINS, 'flow']; | ||
} | ||
function default_1(babel) { | ||
return { | ||
manipulateOptions(opts, parserOpts) { | ||
for (let plugin of exports.ALL_PLUGINS) { | ||
if (plugin !== 'flow' || !opts.filename.endsWith('.ts')) { | ||
parserOpts.plugins.push(plugin); | ||
} | ||
} | ||
parserOpts.sourceType = 'module'; | ||
parserOpts.allowImportExportEverywhere = true; | ||
parserOpts.allowReturnOutsideFunction = true; | ||
parserOpts.allowSuperOutsideMethod = true; | ||
parserOpts.plugins = [ | ||
...(parserOpts.plugins || []), | ||
...pluginsForFilename(opts.filename) | ||
]; | ||
} | ||
@@ -26,0 +36,0 @@ }; |
@@ -22,3 +22,4 @@ /// <reference types="node" /> | ||
constructor(config: Config, onTransform?: (result: SourceTransformResult) => void, readStdin?: () => Promise<string>, writeStdout?: (data: string) => void, fs?: typeof realFs); | ||
private loadPlugins; | ||
run(): Promise<RunResult>; | ||
} |
@@ -10,5 +10,13 @@ "use strict"; | ||
}; | ||
var __asyncValues = (this && this.__asyncValues) || function (o) { | ||
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); | ||
var m = o[Symbol.asyncIterator], i; | ||
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); | ||
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } | ||
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const realFs = require("fs"); | ||
const getStream = require("get-stream"); | ||
const InlineTransformer_1 = require("./InlineTransformer"); | ||
const iterateSources_1 = require("./iterateSources"); | ||
@@ -39,3 +47,3 @@ const ProcessSnapshot_1 = require("./ProcessSnapshot"); | ||
} | ||
run() { | ||
loadPlugins() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
@@ -53,2 +61,9 @@ let snapshot = new ProcessSnapshot_1.default(); | ||
} | ||
return plugins; | ||
}); | ||
} | ||
run() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
var e_1, _a; | ||
let plugins = yield this.loadPlugins(); | ||
let runner; | ||
@@ -66,22 +81,32 @@ let modified = 0; | ||
} | ||
runner = new TransformRunner_1.default(sourcesIterator, plugins); | ||
for (let result of runner.run()) { | ||
this.onTransform(result); | ||
if (result.output) { | ||
if (this.config.stdio) { | ||
this.writeStdout(result.output); | ||
} | ||
else { | ||
if (result.output !== result.source.content) { | ||
modified++; | ||
if (!dryRun) { | ||
this.fs.writeFileSync(result.source.path, result.output); | ||
runner = new TransformRunner_1.default(sourcesIterator, new InlineTransformer_1.default(plugins)); | ||
try { | ||
for (var _b = __asyncValues(runner.run()), _c; _c = yield _b.next(), !_c.done;) { | ||
let result = yield _c.value; | ||
this.onTransform(result); | ||
if (result.output) { | ||
if (this.config.stdio) { | ||
this.writeStdout(result.output); | ||
} | ||
else { | ||
if (result.output !== result.source.content) { | ||
modified++; | ||
if (!dryRun) { | ||
this.fs.writeFileSync(result.source.path, result.output); | ||
} | ||
} | ||
} | ||
} | ||
else if (result.error) { | ||
errors++; | ||
} | ||
total++; | ||
} | ||
else if (result.error) { | ||
errors++; | ||
} | ||
catch (e_1_1) { e_1 = { error: e_1_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b); | ||
} | ||
total++; | ||
finally { if (e_1) throw e_1.error; } | ||
} | ||
@@ -88,0 +113,0 @@ return new RunResult(new RunStats(modified, errors, total)); |
@@ -0,4 +1,3 @@ | ||
import { BabelPlugin, RawBabelPlugin } from './BabelPluginTypes'; | ||
import { PathPredicate } from './iterateSources'; | ||
import { BabelPlugin, RawBabelPlugin } from './TransformRunner'; | ||
export declare const DEFAULT_EXTENSIONS: Set<string>; | ||
export declare class Plugin { | ||
@@ -5,0 +4,0 @@ readonly rawPlugin: RawBabelPlugin; |
@@ -16,2 +16,3 @@ "use strict"; | ||
const BabelPrinterPlugin_1 = require("./BabelPrinterPlugin"); | ||
const extensions_1 = require("./extensions"); | ||
const PluginLoader_1 = require("./PluginLoader"); | ||
@@ -25,3 +26,2 @@ const PrettierPrinterPlugin_1 = require("./PrettierPrinterPlugin"); | ||
const transpile_requires_1 = require("./transpile-requires"); | ||
exports.DEFAULT_EXTENSIONS = new Set(['.js', '.jsx']); | ||
class Plugin { | ||
@@ -50,3 +50,3 @@ constructor(rawPlugin, inferredName, source, resolvedPath) { | ||
class Config { | ||
constructor(sourcePaths = [], localPlugins = [], remotePlugins = [], pluginOptions = new Map(), printer = Printer.Recast, extensions = exports.DEFAULT_EXTENSIONS, requires = [], transpilePlugins = true, findBabelConfig = false, ignore = ignoreDotfiles, stdio = false, dry = false) { | ||
constructor(sourcePaths = [], localPlugins = [], remotePlugins = [], pluginOptions = new Map(), printer = Printer.Recast, extensions = extensions_1.TransformableExtensions, requires = [], transpilePlugins = true, findBabelConfig = false, ignore = ignoreDotfiles, stdio = false, dry = false) { | ||
this.sourcePaths = sourcePaths; | ||
@@ -163,3 +163,3 @@ this.localPlugins = localPlugins; | ||
constructor() { | ||
this._extensions = new Set(exports.DEFAULT_EXTENSIONS); | ||
this._extensions = new Set(extensions_1.TransformableExtensions); | ||
} | ||
@@ -166,0 +166,0 @@ sourcePaths(value) { |
@@ -17,2 +17,7 @@ "use strict"; | ||
const Options_1 = require("./Options"); | ||
// Polyfill `Symbol.asyncIterator` so `for await` will work. | ||
if (!Symbol.asyncIterator) { | ||
Symbol['asyncIterator'] = | ||
Symbol.asyncIterator || Symbol.for('Symbol.asyncIterator'); | ||
} | ||
function optionAnnotation(value) { | ||
@@ -67,2 +72,5 @@ if (Array.isArray(value) || value instanceof Map) { | ||
# Transform TypeScript sources. | ||
# ${$0} -p ./a.js my-typescript-file.ts a-component.tsx | ||
# Run with a plugin in \`node_modules\` on stdin. | ||
@@ -69,0 +77,0 @@ $ ${$0} -s -p babel-plugin-typecheck <<EOS |
@@ -8,3 +8,3 @@ "use strict"; | ||
const Config_1 = require("./Config"); | ||
const transpile_requires_1 = require("./transpile-requires"); | ||
const extensions_1 = require("./extensions"); | ||
class Options { | ||
@@ -128,3 +128,3 @@ constructor(args) { | ||
} | ||
for (let ext of transpile_requires_1.SUPPORTED_EXTENSIONS) { | ||
for (let ext of extensions_1.RequireableExtensions) { | ||
if (fs_1.existsSync(modulePath + ext)) { | ||
@@ -131,0 +131,0 @@ return path_1.resolve(modulePath + ext); |
import * as Babel from '@babel/core'; | ||
import { GeneratorOptions } from '@babel/generator'; | ||
import { AST, ParseOptions } from './TransformRunner'; | ||
import { AST, ParseOptions } from './BabelPluginTypes'; | ||
export declare function parse(code: string, options: ParseOptions, parse: (code: string, options: ParseOptions) => AST): AST; | ||
@@ -5,0 +5,0 @@ export declare function generate(ast: AST, options: GeneratorOptions, code: string, generate: (ast: AST, options: GeneratorOptions) => string): { |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const recast = require("recast"); | ||
const AllSyntaxPlugin_1 = require("./AllSyntaxPlugin"); | ||
const DEFAULT_OPTIONS = { | ||
sourceType: 'module', | ||
allowImportExportEverywhere: true, | ||
allowReturnOutsideFunction: true, | ||
allowSuperOutsideMethod: true, | ||
plugins: AllSyntaxPlugin_1.ALL_PLUGINS | ||
}; | ||
function parse(code, options, parse) { | ||
@@ -16,3 +8,3 @@ return recast.parse(code, { | ||
parse(code) { | ||
return parse(code, DEFAULT_OPTIONS); | ||
return parse(code, options); | ||
} | ||
@@ -19,0 +11,0 @@ } |
@@ -13,3 +13,3 @@ "use strict"; | ||
const path_1 = require("path"); | ||
const transpile_requires_1 = require("../transpile-requires"); | ||
const extensions_1 = require("../extensions"); | ||
function isFile(path) { | ||
@@ -29,3 +29,3 @@ return __awaiter(this, void 0, void 0, function* () { | ||
class FileSystemResolver { | ||
constructor(optionalExtensions = transpile_requires_1.SUPPORTED_EXTENSIONS) { | ||
constructor(optionalExtensions = extensions_1.PluginExtensions) { | ||
this.optionalExtensions = optionalExtensions; | ||
@@ -32,0 +32,0 @@ } |
@@ -1,4 +0,3 @@ | ||
import * as Babel from '@babel/core'; | ||
import { GeneratorOptions } from '@babel/generator'; | ||
import { Visitor } from '@babel/traverse'; | ||
/// <reference types="node" /> | ||
import Transformer from './Transformer'; | ||
export declare class Source { | ||
@@ -15,27 +14,7 @@ readonly path: string; | ||
} | ||
export interface BabelOptions { | ||
filename: string; | ||
} | ||
export interface ParseOptions { | ||
plugins: Array<string>; | ||
} | ||
export declare type AST = object; | ||
export declare type RawBabelPlugin = (babel: typeof Babel) => { | ||
name?: string; | ||
visitor?: Visitor; | ||
manipulateOptions?: (opts: object, parserOpts: ParseOptions) => void; | ||
parserOverride?: (code: string, options: ParseOptions, parse: (code: string, options: ParseOptions) => AST) => AST; | ||
generatorOverride?: (ast: AST, options: GeneratorOptions, code: string, generate: (ast: AST, options: GeneratorOptions) => string) => { | ||
code: string; | ||
map?: object; | ||
}; | ||
}; | ||
export declare type RawBabelPluginWithOptions = [RawBabelPlugin, object]; | ||
export declare type BabelPlugin = RawBabelPlugin | RawBabelPluginWithOptions; | ||
export default class TransformRunner { | ||
readonly sources: IterableIterator<Source> | Array<Source>; | ||
readonly plugins: Array<BabelPlugin>; | ||
constructor(sources: IterableIterator<Source> | Array<Source>, plugins: Array<BabelPlugin>); | ||
run(): IterableIterator<SourceTransformResult>; | ||
private transformSource; | ||
readonly transformer: Transformer; | ||
constructor(sources: IterableIterator<Source> | Array<Source>, transformer: Transformer); | ||
run(): AsyncIterableIterator<SourceTransformResult>; | ||
} |
"use strict"; | ||
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } | ||
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { | ||
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); | ||
var g = generator.apply(thisArg, _arguments || []), i, q = []; | ||
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; | ||
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } | ||
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } | ||
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } | ||
function fulfill(value) { resume("next", value); } | ||
function reject(value) { resume("throw", value); } | ||
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const core_1 = require("@babel/core"); | ||
class Source { | ||
@@ -20,28 +31,23 @@ constructor(path, content) { | ||
class TransformRunner { | ||
constructor(sources, plugins) { | ||
constructor(sources, transformer) { | ||
this.sources = sources; | ||
this.plugins = plugins; | ||
this.transformer = transformer; | ||
} | ||
*run() { | ||
for (let source of this.sources) { | ||
let transformed; | ||
try { | ||
let output = this.transformSource(source); | ||
transformed = new SourceTransformResult(source, output, null); | ||
run() { | ||
return __asyncGenerator(this, arguments, function* run_1() { | ||
for (let source of this.sources) { | ||
let transformed; | ||
try { | ||
let output = yield __await(this.transformer.transform(source.path, source.content)); | ||
transformed = new SourceTransformResult(source, output, null); | ||
} | ||
catch (err) { | ||
transformed = new SourceTransformResult(source, null, err); | ||
} | ||
yield yield __await(transformed); | ||
} | ||
catch (err) { | ||
transformed = new SourceTransformResult(source, null, err); | ||
} | ||
yield transformed; | ||
} | ||
}); | ||
} | ||
transformSource(source) { | ||
return core_1.transform(source.content, { | ||
filename: source.path, | ||
babelrc: false, | ||
plugins: this.plugins | ||
}).code; | ||
} | ||
} | ||
exports.default = TransformRunner; | ||
//# sourceMappingURL=TransformRunner.js.map |
@@ -1,4 +0,3 @@ | ||
export declare const SUPPORTED_EXTENSIONS: Set<string>; | ||
export declare function hook(code: string, filename: string): string; | ||
export declare function enable(babelrc?: boolean): void; | ||
export declare function disable(): void; |
@@ -7,15 +7,8 @@ "use strict"; | ||
const AllSyntaxPlugin_1 = require("./AllSyntaxPlugin"); | ||
const extensions_1 = require("./extensions"); | ||
let useBabelrc = false; | ||
let revert = null; | ||
exports.SUPPORTED_EXTENSIONS = new Set([ | ||
'.js', | ||
'.jsx', | ||
'.es', | ||
'.es6', | ||
'.mjs', | ||
'.ts' | ||
]); | ||
function hook(code, filename) { | ||
let ext = path_1.extname(filename); | ||
if (!exports.SUPPORTED_EXTENSIONS.has(ext)) { | ||
if (!extensions_1.PluginExtensions.has(ext)) { | ||
throw new Error(`cannot load file type '${ext}': ${filename}`); | ||
@@ -31,3 +24,3 @@ } | ||
if (!useBabelrc) { | ||
if (ext === '.ts') { | ||
if (extensions_1.TypeScriptExtensions.has(ext)) { | ||
options.presets.push(require.resolve('@babel/preset-typescript')); | ||
@@ -44,3 +37,3 @@ } | ||
revert = pirates_1.addHook(hook, { | ||
exts: Array.from(exports.SUPPORTED_EXTENSIONS), | ||
exts: Array.from(extensions_1.PluginExtensions), | ||
ignoreNodeModules: true | ||
@@ -47,0 +40,0 @@ }); |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
120485
70
1704
87