2017-01-10 20:18:22 +03:00
|
|
|
"use strict";
|
2016-11-29 23:23:00 +03:00
|
|
|
const babylon = require("babylon");
|
2016-12-23 21:38:10 +03:00
|
|
|
const Printer = require("./src/printer").Printer;
|
2016-12-27 21:28:04 +03:00
|
|
|
const flowParser = require("flow-parser");
|
2017-01-10 01:37:45 +03:00
|
|
|
const comments = require("./src/comments");
|
2016-11-29 23:23:00 +03:00
|
|
|
|
|
|
|
var babylonOptions = {
|
2017-01-13 23:03:53 +03:00
|
|
|
sourceType: "module",
|
2016-11-29 23:23:00 +03:00
|
|
|
allowImportExportEverywhere: false,
|
|
|
|
allowReturnOutsideFunction: false,
|
|
|
|
plugins: [
|
2017-01-13 23:03:53 +03:00
|
|
|
"jsx",
|
|
|
|
"flow",
|
|
|
|
"doExpressions",
|
|
|
|
"objectRestSpread",
|
|
|
|
"decorators",
|
|
|
|
"classProperties",
|
|
|
|
"exportExtensions",
|
|
|
|
"asyncGenerators",
|
|
|
|
"functionBind",
|
|
|
|
"functionSent",
|
|
|
|
"dynamicImport"
|
2016-11-29 23:23:00 +03:00
|
|
|
]
|
|
|
|
};
|
|
|
|
|
2017-01-13 21:39:07 +03:00
|
|
|
function format(text, opts) {
|
|
|
|
opts = opts || {};
|
|
|
|
let ast;
|
|
|
|
|
2017-01-13 23:03:53 +03:00
|
|
|
if (opts.useFlowParser) {
|
2017-01-16 07:46:27 +03:00
|
|
|
ast = flowParser.parse(text, {
|
|
|
|
esproposal_class_instance_fields: true,
|
|
|
|
esproposal_class_static_fields: true,
|
|
|
|
esproposal_export_star_as: true,
|
|
|
|
});
|
2017-01-13 23:03:53 +03:00
|
|
|
if (ast.errors.length > 0) {
|
|
|
|
let msg = ast.errors[(0)].message + " on line " +
|
|
|
|
ast.errors[(0)].loc.start.line;
|
|
|
|
if (opts.filename) {
|
2017-01-13 21:39:07 +03:00
|
|
|
msg += " in file " + opts.filename;
|
2016-12-30 21:32:43 +03:00
|
|
|
}
|
2017-01-13 21:39:07 +03:00
|
|
|
throw new Error(msg);
|
2016-12-31 05:23:50 +03:00
|
|
|
}
|
2017-01-13 23:03:53 +03:00
|
|
|
} else {
|
2017-01-13 21:39:07 +03:00
|
|
|
ast = babylon.parse(text, babylonOptions);
|
|
|
|
}
|
2016-11-29 23:23:00 +03:00
|
|
|
|
2017-01-13 21:39:07 +03:00
|
|
|
// Interleave comment nodes
|
2017-01-13 23:03:53 +03:00
|
|
|
if (ast.comments) {
|
2017-01-13 21:39:07 +03:00
|
|
|
comments.attach(ast.comments, ast, text);
|
|
|
|
ast.comments = [];
|
|
|
|
}
|
|
|
|
ast.tokens = [];
|
|
|
|
opts.originalText = text;
|
|
|
|
|
|
|
|
const printer = new Printer(opts);
|
2017-01-15 07:25:30 +03:00
|
|
|
return printer.print(ast);
|
2017-01-13 21:39:07 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
function formatWithShebang(text, opts) {
|
|
|
|
if (!text.startsWith("#!")) {
|
|
|
|
return format(text, opts);
|
|
|
|
}
|
2017-01-05 20:32:56 +03:00
|
|
|
|
2017-01-13 21:39:07 +03:00
|
|
|
const index = text.indexOf("\n");
|
|
|
|
const shebang = text.slice(0, index + 1);
|
|
|
|
const programText = text.slice(index + 1);
|
|
|
|
return shebang + format(programText, opts);
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
format: function(text, opts) {
|
|
|
|
return formatWithShebang(text, opts);
|
2016-11-29 23:23:00 +03:00
|
|
|
}
|
|
|
|
};
|