babel/packages/babel-core/src/transform.js
Qix db2a9fc96e Fix order of optional argument reordering (#8376)
Previously, if the optional `opts` parameter wasn't passed, the _intent_ was to move the function it held into the `callback` parameter and null out the `opts` param - but instead, it was nulling both.
2018-07-26 11:25:35 -04:00

68 lines
1.7 KiB
JavaScript

// @flow
import loadConfig, { type InputOptions } from "./config";
import {
runSync,
runAsync,
type FileResult,
type FileResultCallback,
} from "./transformation";
type Transform = {
(code: string, callback: FileResultCallback): void,
(code: string, opts: ?InputOptions, callback: FileResultCallback): void,
// Here for backward-compatibility. Ideally use ".transformSync" if you want
// a synchronous API.
(code: string, opts: ?InputOptions): FileResult | null,
};
export const transform: Transform = (function transform(code, opts, callback) {
if (typeof opts === "function") {
callback = opts;
opts = undefined;
}
// For backward-compat with Babel 6, we allow sync transformation when
// no callback is given. Will be dropped in some future Babel major version.
if (callback === undefined) return transformSync(code, opts);
// Reassign to keep Flowtype happy.
const cb = callback;
// Just delaying the transform one tick for now to simulate async behavior
// but more async logic may land here eventually.
process.nextTick(() => {
let cfg;
try {
cfg = loadConfig(opts);
if (cfg === null) return cb(null, null);
} catch (err) {
return cb(err);
}
runAsync(cfg, code, null, cb);
});
}: Function);
export function transformSync(
code: string,
opts: ?InputOptions,
): FileResult | null {
const config = loadConfig(opts);
if (config === null) return null;
return runSync(config, code);
}
export function transformAsync(
code: string,
opts: ?InputOptions,
): Promise<FileResult | null> {
return new Promise((res, rej) => {
transform(code, opts, (err, result) => {
if (err == null) res(result);
else rej(err);
});
});
}