feat: refactoring project

This commit is contained in:
Carlos 2024-11-23 14:56:07 -05:00
parent f0c2a50c18
commit 1c6db5818d
2351 changed files with 39323 additions and 60326 deletions

27
bin/cli.js Executable file
View File

@ -0,0 +1,27 @@
#!/usr/bin/env node
const program = require('commander');
const { initProject } = require('../src/setup/init');
const { askProjectDetails } = require('../src/utils/prompts');
const { overWriteFolder } = require('../src/utils/overWriteFolder');
program
.version('1.0.0')
.description('React Crafter CLI')
.arguments('<project-directory>')
.option('--typescript', 'Use TypeScript template')
.action(async (projectDirectory, options) => {
// Use the overwrite function to manage the project directory
const shouldProceed = await overWriteFolder(projectDirectory);
console.log('shouldProceed', shouldProceed);
if (!shouldProceed) {
console.error('❌ Project initialization aborted.');
process.exit(1);
}
// Proceed with project setup
const userInput = await askProjectDetails();
initProject(projectDirectory, userInput, options);
})
.parse(process.argv);

13
bin/cli.test.js Normal file
View File

@ -0,0 +1,13 @@
const { execSync } = require('child_process');
describe('React Crafter CLI', () => {
test('CLI runs and shows version', () => {
const output = execSync('node bin/cli.js --version').toString();
expect(output.trim()).toMatch(/\\d+\\.\\d+\\.\\d+/); // Matches a version format
});
test('CLI handles missing arguments', () => {
const output = execSync('node bin/cli.js').toString();
expect(output).toContain('React Crafter CLI');
});
});

View File

@ -1,7 +1,8 @@
module.exports = { module.exports = {
testEnvironment: 'node', // Set up the environment (node, jsdom, etc.) preset: 'ts-jest',
verbose: true, // Show detailed test results roots: ['<rootDir>/src', '<rootDir>/bin'],
coverageDirectory: 'coverage', // Directory for code coverage reports testEnvironment: 'node',
collectCoverage: true, // Collect coverage information roots: ['<rootDir>/'],
coverageReporters: ['text', 'lcov'], // Reporters for coverage testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.[tj]sx?$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
}; };

3602
node_modules/.package-lock.json generated vendored

File diff suppressed because it is too large Load Diff

View File

@ -1,33 +1,94 @@
"use strict"; 'use strict';
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, '__esModule', { value: true });
value: true
}); var picocolors = require('picocolors');
exports.codeFrameColumns = codeFrameColumns; var jsTokens = require('js-tokens');
exports.default = _default; var helperValidatorIdentifier = require('@babel/helper-validator-identifier');
var _highlight = require("@babel/highlight");
var _picocolors = _interopRequireWildcard(require("picocolors"), true); function isColorSupported() {
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } return (typeof process === "object" && (process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") ? false : picocolors.isColorSupported
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } );
const colors = typeof process === "object" && (process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") ? (0, _picocolors.createColors)(false) : _picocolors.default; }
const compose = (f, g) => v => f(g(v)); const compose = (f, g) => v => f(g(v));
let pcWithForcedColor = undefined; function buildDefs(colors) {
function getColors(forceColor) {
if (forceColor) {
var _pcWithForcedColor;
(_pcWithForcedColor = pcWithForcedColor) != null ? _pcWithForcedColor : pcWithForcedColor = (0, _picocolors.createColors)(true);
return pcWithForcedColor;
}
return colors;
}
let deprecationWarningShown = false;
function getDefs(colors) {
return { return {
keyword: colors.cyan,
capitalized: colors.yellow,
jsxIdentifier: colors.yellow,
punctuator: colors.yellow,
number: colors.magenta,
string: colors.green,
regex: colors.magenta,
comment: colors.gray,
invalid: compose(compose(colors.white, colors.bgRed), colors.bold),
gutter: colors.gray, gutter: colors.gray,
marker: compose(colors.red, colors.bold), marker: compose(colors.red, colors.bold),
message: compose(colors.red, colors.bold) message: compose(colors.red, colors.bold),
reset: colors.reset
}; };
} }
const defsOn = buildDefs(picocolors.createColors(true));
const defsOff = buildDefs(picocolors.createColors(false));
function getDefs(enabled) {
return enabled ? defsOn : defsOff;
}
const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]);
const NEWLINE$1 = /\r\n|[\n\r\u2028\u2029]/;
const BRACKET = /^[()[\]{}]$/;
let tokenize;
{
const JSX_TAG = /^[a-z][\w-]*$/i;
const getTokenType = function (token, offset, text) {
if (token.type === "name") {
if (helperValidatorIdentifier.isKeyword(token.value) || helperValidatorIdentifier.isStrictReservedWord(token.value, true) || sometimesKeywords.has(token.value)) {
return "keyword";
}
if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) === "</")) {
return "jsxIdentifier";
}
if (token.value[0] !== token.value[0].toLowerCase()) {
return "capitalized";
}
}
if (token.type === "punctuator" && BRACKET.test(token.value)) {
return "bracket";
}
if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
return "punctuator";
}
return token.type;
};
tokenize = function* (text) {
let match;
while (match = jsTokens.default.exec(text)) {
const token = jsTokens.matchToToken(match);
yield {
type: getTokenType(token, match.index, text),
value: token.value
};
}
};
}
function highlight(text) {
if (text === "") return "";
const defs = getDefs(true);
let highlighted = "";
for (const {
type,
value
} of tokenize(text)) {
if (type in defs) {
highlighted += value.split(NEWLINE$1).map(str => defs[type](str)).join("\n");
} else {
highlighted += value;
}
}
return highlighted;
}
let deprecationWarningShown = false;
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
function getMarkerLines(loc, source, opts) { function getMarkerLines(loc, source, opts) {
const startLoc = Object.assign({ const startLoc = Object.assign({
@ -86,12 +147,8 @@ function getMarkerLines(loc, source, opts) {
}; };
} }
function codeFrameColumns(rawLines, loc, opts = {}) { function codeFrameColumns(rawLines, loc, opts = {}) {
const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts); const shouldHighlight = opts.forceColor || isColorSupported() && opts.highlightCode;
const colors = getColors(opts.forceColor); const defs = getDefs(shouldHighlight);
const defs = getDefs(colors);
const maybeHighlight = (fmt, string) => {
return highlighted ? fmt(string) : string;
};
const lines = rawLines.split(NEWLINE); const lines = rawLines.split(NEWLINE);
const { const {
start, start,
@ -100,7 +157,7 @@ function codeFrameColumns(rawLines, loc, opts = {}) {
} = getMarkerLines(loc, lines, opts); } = getMarkerLines(loc, lines, opts);
const hasColumns = loc.start && typeof loc.start.column === "number"; const hasColumns = loc.start && typeof loc.start.column === "number";
const numberMaxWidth = String(end).length; const numberMaxWidth = String(end).length;
const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines; const highlightedLines = shouldHighlight ? highlight(rawLines) : rawLines;
let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => { let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => {
const number = start + 1 + index; const number = start + 1 + index;
const paddedNumber = ` ${number}`.slice(-numberMaxWidth); const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
@ -112,26 +169,26 @@ function codeFrameColumns(rawLines, loc, opts = {}) {
if (Array.isArray(hasMarker)) { if (Array.isArray(hasMarker)) {
const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
const numberOfMarkers = hasMarker[1] || 1; const numberOfMarkers = hasMarker[1] || 1;
markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), " ", markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); markerLine = ["\n ", defs.gutter(gutter.replace(/\d/g, " ")), " ", markerSpacing, defs.marker("^").repeat(numberOfMarkers)].join("");
if (lastMarkerLine && opts.message) { if (lastMarkerLine && opts.message) {
markerLine += " " + maybeHighlight(defs.message, opts.message); markerLine += " " + defs.message(opts.message);
} }
} }
return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line.length > 0 ? ` ${line}` : "", markerLine].join(""); return [defs.marker(">"), defs.gutter(gutter), line.length > 0 ? ` ${line}` : "", markerLine].join("");
} else { } else {
return ` ${maybeHighlight(defs.gutter, gutter)}${line.length > 0 ? ` ${line}` : ""}`; return ` ${defs.gutter(gutter)}${line.length > 0 ? ` ${line}` : ""}`;
} }
}).join("\n"); }).join("\n");
if (opts.message && !hasColumns) { if (opts.message && !hasColumns) {
frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
} }
if (highlighted) { if (shouldHighlight) {
return colors.reset(frame); return defs.reset(frame);
} else { } else {
return frame; return frame;
} }
} }
function _default(rawLines, lineNumber, colNumber, opts = {}) { function index (rawLines, lineNumber, colNumber, opts = {}) {
if (!deprecationWarningShown) { if (!deprecationWarningShown) {
deprecationWarningShown = true; deprecationWarningShown = true;
const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
@ -153,4 +210,7 @@ function _default(rawLines, lineNumber, colNumber, opts = {}) {
return codeFrameColumns(rawLines, location, opts); return codeFrameColumns(rawLines, location, opts);
} }
exports.codeFrameColumns = codeFrameColumns;
exports.default = index;
exports.highlight = highlight;
//# sourceMappingURL=index.js.map //# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,6 @@
{ {
"name": "@babel/code-frame", "name": "@babel/code-frame",
"version": "7.24.7", "version": "7.26.2",
"description": "Generate errors that contain a code frame that point to source locations.", "description": "Generate errors that contain a code frame that point to source locations.",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-code-frame", "homepage": "https://babel.dev/docs/en/next/babel-code-frame",
@ -16,7 +16,8 @@
}, },
"main": "./lib/index.js", "main": "./lib/index.js",
"dependencies": { "dependencies": {
"@babel/highlight": "^7.24.7", "@babel/helper-validator-identifier": "^7.25.9",
"js-tokens": "^4.0.0",
"picocolors": "^1.0.0" "picocolors": "^1.0.0"
}, },
"devDependencies": { "devDependencies": {

View File

@ -1,9 +1,20 @@
{ {
"transform-duplicate-named-capturing-groups-regex": { "transform-duplicate-named-capturing-groups-regex": {
"chrome": "126", "chrome": "126",
"opera": "112",
"edge": "126", "edge": "126",
"firefox": "129", "firefox": "129",
"safari": "17.4", "safari": "17.4",
"node": "23",
"ios": "17.4",
"electron": "31.0"
},
"transform-regexp-modifiers": {
"chrome": "125",
"opera": "111",
"edge": "125",
"firefox": "132",
"node": "23",
"electron": "31.0" "electron": "31.0"
}, },
"transform-unicode-sets-regex": { "transform-unicode-sets-regex": {
@ -22,7 +33,7 @@
"chrome": "98", "chrome": "98",
"opera": "84", "opera": "84",
"edge": "98", "edge": "98",
"firefox": "95", "firefox": "75",
"safari": "15", "safari": "15",
"node": "12", "node": "12",
"deno": "1.18", "deno": "1.18",

View File

@ -1,6 +1,6 @@
{ {
"name": "@babel/compat-data", "name": "@babel/compat-data",
"version": "7.25.2", "version": "7.26.2",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"license": "MIT", "license": "MIT",
"description": "", "description": "",

View File

@ -29,6 +29,15 @@ const propertyNames = [
for (const name of functionNames) { for (const name of functionNames) {
exports[name] = function (...args) { exports[name] = function (...args) {
if (
process.env.BABEL_8_BREAKING &&
typeof args[args.length - 1] !== "function"
) {
throw new Error(
`Starting from Babel 8.0.0, the '${name}' function expects a callback. If you need to call it synchronously, please use '${name}Sync'.`
);
}
babelP.then(babel => { babelP.then(babel => {
babel[name](...args); babel[name](...args);
}); });

View File

@ -52,6 +52,7 @@ var _patternToRegex = require("../pattern-to-regex.js");
var _configError = require("../../errors/config-error.js"); var _configError = require("../../errors/config-error.js");
var fs = require("../../gensync-utils/fs.js"); var fs = require("../../gensync-utils/fs.js");
var _rewriteStackTrace = require("../../errors/rewrite-stack-trace.js"); var _rewriteStackTrace = require("../../errors/rewrite-stack-trace.js");
var _async = require("../../gensync-utils/async.js");
const debug = _debug()("babel:config:loading:files:configuration"); const debug = _debug()("babel:config:loading:files:configuration");
const ROOT_CONFIG_FILENAMES = exports.ROOT_CONFIG_FILENAMES = ["babel.config.js", "babel.config.cjs", "babel.config.mjs", "babel.config.json", "babel.config.cts"]; const ROOT_CONFIG_FILENAMES = exports.ROOT_CONFIG_FILENAMES = ["babel.config.js", "babel.config.cjs", "babel.config.mjs", "babel.config.json", "babel.config.cts"];
const RELATIVE_CONFIG_FILENAMES = [".babelrc", ".babelrc.js", ".babelrc.cjs", ".babelrc.mjs", ".babelrc.json", ".babelrc.cts"]; const RELATIVE_CONFIG_FILENAMES = [".babelrc", ".babelrc.js", ".babelrc.cjs", ".babelrc.mjs", ".babelrc.json", ".babelrc.cts"];
@ -65,7 +66,7 @@ const runConfig = (0, _caching.makeWeakCache)(function* runConfig(options, cache
}); });
function* readConfigCode(filepath, data) { function* readConfigCode(filepath, data) {
if (!_fs().existsSync(filepath)) return null; if (!_fs().existsSync(filepath)) return null;
let options = yield* (0, _moduleTypes.default)(filepath, "You appear to be using a native ECMAScript module configuration " + "file, which is only supported when running Babel asynchronously."); let options = yield* (0, _moduleTypes.default)(filepath, (yield* (0, _async.isAsync)()) ? "auto" : "require", "You appear to be using a native ECMAScript module configuration " + "file, which is only supported when running Babel asynchronously " + "or when using the Node.js `--experimental-require-module` flag.", "You appear to be using a configuration file that contains top-level " + "await, which is only supported when running Babel asynchronously.");
let cacheNeedsConfiguration = false; let cacheNeedsConfiguration = false;
if (typeof options === "function") { if (typeof options === "function") {
({ ({
@ -102,7 +103,7 @@ function buildConfigFileObject(options, filepath) {
} }
const packageToBabelConfig = (0, _caching.makeWeakCacheSync)(file => { const packageToBabelConfig = (0, _caching.makeWeakCacheSync)(file => {
const babel = file.options["babel"]; const babel = file.options["babel"];
if (typeof babel === "undefined") return null; if (babel === undefined) return null;
if (typeof babel !== "object" || Array.isArray(babel) || babel === null) { if (typeof babel !== "object" || Array.isArray(babel) || babel === null) {
throw new _configError.default(`.babel property must be an object`, file.filepath); throw new _configError.default(`.babel property must be an object`, file.filepath);
} }
@ -135,7 +136,7 @@ const readConfigJSON5 = (0, _utils.makeStaticFileCache)((filepath, content) => {
}); });
const readIgnoreConfig = (0, _utils.makeStaticFileCache)((filepath, content) => { const readIgnoreConfig = (0, _utils.makeStaticFileCache)((filepath, content) => {
const ignoreDir = _path().dirname(filepath); const ignoreDir = _path().dirname(filepath);
const ignorePatterns = content.split("\n").map(line => line.replace(/#.*$/, "").trim()).filter(line => !!line); const ignorePatterns = content.split("\n").map(line => line.replace(/#.*$/, "").trim()).filter(Boolean);
for (const pattern of ignorePatterns) { for (const pattern of ignorePatterns) {
if (pattern[0] === "!") { if (pattern[0] === "!") {
throw new _configError.default(`Negation of file paths is not supported.`, filepath); throw new _configError.default(`Negation of file paths is not supported.`, filepath);

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
{"version":3,"names":["findConfigUpwards","rootDir","findPackageData","filepath","directories","pkg","isPackage","findRelativeConfig","pkgData","envName","caller","config","ignore","findRootConfig","dirname","loadConfig","name","Error","resolveShowConfigPath","ROOT_CONFIG_FILENAMES","exports","resolvePlugin","resolvePreset","loadPlugin","loadPreset"],"sources":["../../../src/config/files/index-browser.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\n\nimport type {\n ConfigFile,\n IgnoreFile,\n RelativeConfig,\n FilePackageData,\n} from \"./types.ts\";\n\nimport type { CallerMetadata } from \"../validation/options.ts\";\n\nexport type { ConfigFile, IgnoreFile, RelativeConfig, FilePackageData };\n\nexport function findConfigUpwards(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n rootDir: string,\n): string | null {\n return null;\n}\n\n// eslint-disable-next-line require-yield\nexport function* findPackageData(filepath: string): Handler<FilePackageData> {\n return {\n filepath,\n directories: [],\n pkg: null,\n isPackage: false,\n };\n}\n\n// eslint-disable-next-line require-yield\nexport function* findRelativeConfig(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n pkgData: FilePackageData,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler<RelativeConfig> {\n return { config: null, ignore: null };\n}\n\n// eslint-disable-next-line require-yield\nexport function* findRootConfig(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dirname: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler<ConfigFile | null> {\n return null;\n}\n\n// eslint-disable-next-line require-yield\nexport function* loadConfig(\n name: string,\n dirname: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler<ConfigFile> {\n throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`);\n}\n\n// eslint-disable-next-line require-yield\nexport function* resolveShowConfigPath(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dirname: string,\n): Handler<string | null> {\n return null;\n}\n\nexport const ROOT_CONFIG_FILENAMES: string[] = [];\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function resolvePlugin(name: string, dirname: string): string | null {\n return null;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function resolvePreset(name: string, dirname: string): string | null {\n return null;\n}\n\nexport function loadPlugin(\n name: string,\n dirname: string,\n): Handler<{\n filepath: string;\n value: unknown;\n}> {\n throw new Error(\n `Cannot load plugin ${name} relative to ${dirname} in a browser`,\n );\n}\n\nexport function loadPreset(\n name: string,\n dirname: string,\n): Handler<{\n filepath: string;\n value: unknown;\n}> {\n throw new Error(\n `Cannot load preset ${name} relative to ${dirname} in a browser`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaO,SAASA,iBAAiBA,CAE/BC,OAAe,EACA;EACf,OAAO,IAAI;AACb;AAGO,UAAUC,eAAeA,CAACC,QAAgB,EAA4B;EAC3E,OAAO;IACLA,QAAQ;IACRC,WAAW,EAAE,EAAE;IACfC,GAAG,EAAE,IAAI;IACTC,SAAS,EAAE;EACb,CAAC;AACH;AAGO,UAAUC,kBAAkBA,CAEjCC,OAAwB,EAExBC,OAAe,EAEfC,MAAkC,EACT;EACzB,OAAO;IAAEC,MAAM,EAAE,IAAI;IAAEC,MAAM,EAAE;EAAK,CAAC;AACvC;AAGO,UAAUC,cAAcA,CAE7BC,OAAe,EAEfL,OAAe,EAEfC,MAAkC,EACN;EAC5B,OAAO,IAAI;AACb;AAGO,UAAUK,UAAUA,CACzBC,IAAY,EACZF,OAAe,EAEfL,OAAe,EAEfC,MAAkC,EACb;EACrB,MAAM,IAAIO,KAAK,CAAC,eAAeD,IAAI,gBAAgBF,OAAO,eAAe,CAAC;AAC5E;AAGO,UAAUI,qBAAqBA,CAEpCJ,OAAe,EACS;EACxB,OAAO,IAAI;AACb;AAEO,MAAMK,qBAA+B,GAAAC,OAAA,CAAAD,qBAAA,GAAG,EAAE;AAG1C,SAASE,aAAaA,CAACL,IAAY,EAAEF,OAAe,EAAiB;EAC1E,OAAO,IAAI;AACb;AAGO,SAASQ,aAAaA,CAACN,IAAY,EAAEF,OAAe,EAAiB;EAC1E,OAAO,IAAI;AACb;AAEO,SAASS,UAAUA,CACxBP,IAAY,EACZF,OAAe,EAId;EACD,MAAM,IAAIG,KAAK,CACb,sBAAsBD,IAAI,gBAAgBF,OAAO,eACnD,CAAC;AACH;AAEO,SAASU,UAAUA,CACxBR,IAAY,EACZF,OAAe,EAId;EACD,MAAM,IAAIG,KAAK,CACb,sBAAsBD,IAAI,gBAAgBF,OAAO,eACnD,CAAC;AACH;AAAC","ignoreList":[]} {"version":3,"names":["findConfigUpwards","rootDir","findPackageData","filepath","directories","pkg","isPackage","findRelativeConfig","pkgData","envName","caller","config","ignore","findRootConfig","dirname","loadConfig","name","Error","resolveShowConfigPath","ROOT_CONFIG_FILENAMES","exports","resolvePlugin","resolvePreset","loadPlugin","loadPreset"],"sources":["../../../src/config/files/index-browser.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\n\nimport type {\n ConfigFile,\n IgnoreFile,\n RelativeConfig,\n FilePackageData,\n} from \"./types.ts\";\n\nimport type { CallerMetadata } from \"../validation/options.ts\";\n\nexport type { ConfigFile, IgnoreFile, RelativeConfig, FilePackageData };\n\nexport function findConfigUpwards(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n rootDir: string,\n): string | null {\n return null;\n}\n\n// eslint-disable-next-line require-yield\nexport function* findPackageData(filepath: string): Handler<FilePackageData> {\n return {\n filepath,\n directories: [],\n pkg: null,\n isPackage: false,\n };\n}\n\n// eslint-disable-next-line require-yield\nexport function* findRelativeConfig(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n pkgData: FilePackageData,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler<RelativeConfig> {\n return { config: null, ignore: null };\n}\n\n// eslint-disable-next-line require-yield\nexport function* findRootConfig(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dirname: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler<ConfigFile | null> {\n return null;\n}\n\n// eslint-disable-next-line require-yield\nexport function* loadConfig(\n name: string,\n dirname: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler<ConfigFile> {\n throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`);\n}\n\n// eslint-disable-next-line require-yield\nexport function* resolveShowConfigPath(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dirname: string,\n): Handler<string | null> {\n return null;\n}\n\nexport const ROOT_CONFIG_FILENAMES: string[] = [];\n\ntype Resolved =\n | { loader: \"require\"; filepath: string }\n | { loader: \"import\"; filepath: string };\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function resolvePlugin(name: string, dirname: string): Resolved | null {\n return null;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function resolvePreset(name: string, dirname: string): Resolved | null {\n return null;\n}\n\nexport function loadPlugin(\n name: string,\n dirname: string,\n): Handler<{\n filepath: string;\n value: unknown;\n}> {\n throw new Error(\n `Cannot load plugin ${name} relative to ${dirname} in a browser`,\n );\n}\n\nexport function loadPreset(\n name: string,\n dirname: string,\n): Handler<{\n filepath: string;\n value: unknown;\n}> {\n throw new Error(\n `Cannot load preset ${name} relative to ${dirname} in a browser`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaO,SAASA,iBAAiBA,CAE/BC,OAAe,EACA;EACf,OAAO,IAAI;AACb;AAGO,UAAUC,eAAeA,CAACC,QAAgB,EAA4B;EAC3E,OAAO;IACLA,QAAQ;IACRC,WAAW,EAAE,EAAE;IACfC,GAAG,EAAE,IAAI;IACTC,SAAS,EAAE;EACb,CAAC;AACH;AAGO,UAAUC,kBAAkBA,CAEjCC,OAAwB,EAExBC,OAAe,EAEfC,MAAkC,EACT;EACzB,OAAO;IAAEC,MAAM,EAAE,IAAI;IAAEC,MAAM,EAAE;EAAK,CAAC;AACvC;AAGO,UAAUC,cAAcA,CAE7BC,OAAe,EAEfL,OAAe,EAEfC,MAAkC,EACN;EAC5B,OAAO,IAAI;AACb;AAGO,UAAUK,UAAUA,CACzBC,IAAY,EACZF,OAAe,EAEfL,OAAe,EAEfC,MAAkC,EACb;EACrB,MAAM,IAAIO,KAAK,CAAC,eAAeD,IAAI,gBAAgBF,OAAO,eAAe,CAAC;AAC5E;AAGO,UAAUI,qBAAqBA,CAEpCJ,OAAe,EACS;EACxB,OAAO,IAAI;AACb;AAEO,MAAMK,qBAA+B,GAAAC,OAAA,CAAAD,qBAAA,GAAG,EAAE;AAO1C,SAASE,aAAaA,CAACL,IAAY,EAAEF,OAAe,EAAmB;EAC5E,OAAO,IAAI;AACb;AAGO,SAASQ,aAAaA,CAACN,IAAY,EAAEF,OAAe,EAAmB;EAC5E,OAAO,IAAI;AACb;AAEO,SAASS,UAAUA,CACxBP,IAAY,EACZF,OAAe,EAId;EACD,MAAM,IAAIG,KAAK,CACb,sBAAsBD,IAAI,gBAAgBF,OAAO,eACnD,CAAC;AACH;AAEO,SAASU,UAAUA,CACxBR,IAAY,EACZF,OAAe,EAId;EACD,MAAM,IAAIG,KAAK,CACb,sBAAsBD,IAAI,gBAAgBF,OAAO,eACnD,CAAC;AACH;AAAC","ignoreList":[]}

View File

@ -5,7 +5,7 @@ Object.defineProperty(exports, "__esModule", {
}); });
exports.default = loadCodeDefault; exports.default = loadCodeDefault;
exports.supportsESM = void 0; exports.supportsESM = void 0;
var _async = require("../../gensync-utils/async.js"); var _async3 = require("../../gensync-utils/async.js");
function _path() { function _path() {
const data = require("path"); const data = require("path");
_path = function () { _path = function () {
@ -37,8 +37,8 @@ function _debug() {
var _rewriteStackTrace = require("../../errors/rewrite-stack-trace.js"); var _rewriteStackTrace = require("../../errors/rewrite-stack-trace.js");
var _configError = require("../../errors/config-error.js"); var _configError = require("../../errors/config-error.js");
var _transformFile = require("../../transform-file.js"); var _transformFile = require("../../transform-file.js");
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
const debug = _debug()("babel:config:loading:files:module-types"); const debug = _debug()("babel:config:loading:files:module-types");
{ {
try { try {
@ -60,48 +60,67 @@ function loadCjsDefault(filepath) {
LOADING_CJS_FILES.delete(filepath); LOADING_CJS_FILES.delete(filepath);
} }
{ {
var _module; return module != null && (module.__esModule || module[Symbol.toStringTag] === "Module") ? module.default || (arguments[1] ? module : undefined) : module;
return (_module = module) != null && _module.__esModule ? module.default || (arguments[1] ? module : undefined) : module;
} }
} }
const loadMjsDefault = (0, _rewriteStackTrace.endHiddenCallStack)(function () { const loadMjsFromPath = (0, _rewriteStackTrace.endHiddenCallStack)(function () {
var _loadMjsDefault = _asyncToGenerator(function* (filepath) { var _loadMjsFromPath = _asyncToGenerator(function* (filepath) {
const url = (0, _url().pathToFileURL)(filepath).toString(); const url = (0, _url().pathToFileURL)(filepath).toString() + "?import";
{ {
if (!import_) { if (!import_) {
throw new _configError.default("Internal error: Native ECMAScript modules aren't supported by this platform.\n", filepath); throw new _configError.default("Internal error: Native ECMAScript modules aren't supported by this platform.\n", filepath);
} }
return (yield import_(url)).default; return yield import_(url);
} }
}); });
function loadMjsDefault(_x) { function loadMjsFromPath(_x) {
return _loadMjsDefault.apply(this, arguments); return _loadMjsFromPath.apply(this, arguments);
} }
return loadMjsDefault; return loadMjsFromPath;
}()); }());
function* loadCodeDefault(filepath, asyncError) { const SUPPORTED_EXTENSIONS = new Set([".js", ".mjs", ".cjs", ".cts"]);
switch (_path().extname(filepath)) { const asyncModules = new Set();
case ".cjs": function* loadCodeDefault(filepath, loader, esmError, tlaError) {
var _async2;
let async;
let ext = _path().extname(filepath);
if (!SUPPORTED_EXTENSIONS.has(ext)) ext = ".js";
const pattern = `${loader} ${ext}`;
switch (pattern) {
case "require .cjs":
case "auto .cjs":
{ {
return loadCjsDefault(filepath, arguments[2]); return loadCjsDefault(filepath, arguments[2]);
} }
case ".mjs": case "require .cts":
break; case "auto .cts":
case ".cts":
return loadCtsDefault(filepath); return loadCtsDefault(filepath);
default: case "auto .js":
case "require .js":
case "require .mjs":
try { try {
{ {
return loadCjsDefault(filepath, arguments[2]); return loadCjsDefault(filepath, arguments[2]);
} }
} catch (e) { } catch (e) {
if (e.code !== "ERR_REQUIRE_ESM") throw e; if (e.code === "ERR_REQUIRE_ASYNC_MODULE" || e.code === "ERR_REQUIRE_CYCLE_MODULE" && asyncModules.has(filepath)) {
var _async;
asyncModules.add(filepath);
if (!((_async = async) != null ? _async : async = yield* (0, _async3.isAsync)())) {
throw new _configError.default(tlaError, filepath);
}
} else if (e.code === "ERR_REQUIRE_ESM" || ext === ".mjs") {} else {
throw e;
} }
} }
if (yield* (0, _async.isAsync)()) { case "auto .mjs":
return yield* (0, _async.waitFor)(loadMjsDefault(filepath)); if ((_async2 = async) != null ? _async2 : async = yield* (0, _async3.isAsync)()) {
return (yield* (0, _async3.waitFor)(loadMjsFromPath(filepath))).default;
}
throw new _configError.default(esmError, filepath);
default:
throw new Error("Internal Babel error: unreachable code.");
} }
throw new _configError.default(asyncError, filepath);
} }
function loadCtsDefault(filepath) { function loadCtsDefault(filepath) {
const ext = ".cts"; const ext = ".cts";

File diff suppressed because one or more lines are too long

View File

@ -49,8 +49,11 @@ const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/;
const resolvePlugin = exports.resolvePlugin = resolveStandardizedName.bind(null, "plugin"); const resolvePlugin = exports.resolvePlugin = resolveStandardizedName.bind(null, "plugin");
const resolvePreset = exports.resolvePreset = resolveStandardizedName.bind(null, "preset"); const resolvePreset = exports.resolvePreset = resolveStandardizedName.bind(null, "preset");
function* loadPlugin(name, dirname) { function* loadPlugin(name, dirname) {
const filepath = resolvePlugin(name, dirname, yield* (0, _async.isAsync)()); const {
const value = yield* requireModule("plugin", filepath); filepath,
loader
} = resolvePlugin(name, dirname, yield* (0, _async.isAsync)());
const value = yield* requireModule("plugin", loader, filepath);
debug("Loaded plugin %o from %o.", name, dirname); debug("Loaded plugin %o from %o.", name, dirname);
return { return {
filepath, filepath,
@ -58,8 +61,11 @@ function* loadPlugin(name, dirname) {
}; };
} }
function* loadPreset(name, dirname) { function* loadPreset(name, dirname) {
const filepath = resolvePreset(name, dirname, yield* (0, _async.isAsync)()); const {
const value = yield* requireModule("preset", filepath); filepath,
loader
} = resolvePreset(name, dirname, yield* (0, _async.isAsync)());
const value = yield* requireModule("preset", loader, filepath);
debug("Loaded preset %o from %o.", name, dirname); debug("Loaded preset %o from %o.", name, dirname);
return { return {
filepath, filepath,
@ -154,7 +160,10 @@ function resolveStandardizedNameForRequire(type, name, dirname) {
while (!res.done) { while (!res.done) {
res = it.next(tryRequireResolve(res.value, dirname)); res = it.next(tryRequireResolve(res.value, dirname));
} }
return res.value; return {
loader: "require",
filepath: res.value
};
} }
function resolveStandardizedNameForImport(type, name, dirname) { function resolveStandardizedNameForImport(type, name, dirname) {
const parentUrl = (0, _url().pathToFileURL)(_path().join(dirname, "./babel-virtual-resolve-base.js")).href; const parentUrl = (0, _url().pathToFileURL)(_path().join(dirname, "./babel-virtual-resolve-base.js")).href;
@ -163,15 +172,18 @@ function resolveStandardizedNameForImport(type, name, dirname) {
while (!res.done) { while (!res.done) {
res = it.next(tryImportMetaResolve(res.value, parentUrl)); res = it.next(tryImportMetaResolve(res.value, parentUrl));
} }
return (0, _url().fileURLToPath)(res.value); return {
loader: "auto",
filepath: (0, _url().fileURLToPath)(res.value)
};
} }
function resolveStandardizedName(type, name, dirname, resolveESM) { function resolveStandardizedName(type, name, dirname, allowAsync) {
if (!_moduleTypes.supportsESM || !resolveESM) { if (!_moduleTypes.supportsESM || !allowAsync) {
return resolveStandardizedNameForRequire(type, name, dirname); return resolveStandardizedNameForRequire(type, name, dirname);
} }
try { try {
const resolved = resolveStandardizedNameForImport(type, name, dirname); const resolved = resolveStandardizedNameForImport(type, name, dirname);
if (!(0, _fs().existsSync)(resolved)) { if (!(0, _fs().existsSync)(resolved.filepath)) {
throw Object.assign(new Error(`Could not resolve "${name}" in file ${dirname}.`), { throw Object.assign(new Error(`Could not resolve "${name}" in file ${dirname}.`), {
type: "MODULE_NOT_FOUND" type: "MODULE_NOT_FOUND"
}); });
@ -190,7 +202,7 @@ function resolveStandardizedName(type, name, dirname, resolveESM) {
{ {
var LOADING_MODULES = new Set(); var LOADING_MODULES = new Set();
} }
function* requireModule(type, name) { function* requireModule(type, loader, name) {
{ {
if (!(yield* (0, _async.isAsync)()) && LOADING_MODULES.has(name)) { if (!(yield* (0, _async.isAsync)()) && LOADING_MODULES.has(name)) {
throw new Error(`Reentrant ${type} detected trying to load "${name}". This module is not ignored ` + "and is trying to load itself while compiling itself, leading to a dependency cycle. " + 'We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.'); throw new Error(`Reentrant ${type} detected trying to load "${name}". This module is not ignored ` + "and is trying to load itself while compiling itself, leading to a dependency cycle. " + 'We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.');
@ -201,7 +213,7 @@ function* requireModule(type, name) {
LOADING_MODULES.add(name); LOADING_MODULES.add(name);
} }
{ {
return yield* (0, _moduleTypes.default)(name, `You appear to be using a native ECMAScript module ${type}, ` + "which is only supported when running Babel asynchronously.", true); return yield* (0, _moduleTypes.default)(name, loader, `You appear to be using a native ECMAScript module ${type}, ` + "which is only supported when running Babel asynchronously " + "or when using the Node.js `--experimental-require-module` flag.", `You appear to be using a ${type} that contains top-level await, ` + "which is only supported when running Babel asynchronously.", true);
} }
} catch (err) { } catch (err) {
err.message = `[BABEL]: ${err.message} (While processing: ${name})`; err.message = `[BABEL]: ${err.message} (While processing: ${name})`;

File diff suppressed because one or more lines are too long

View File

@ -235,9 +235,9 @@ const instantiatePlugin = (0, _caching.makeWeakCache)(function* ({
const inherits = yield* (0, _async.forwardAsync)(loadPluginDescriptor, run => { const inherits = yield* (0, _async.forwardAsync)(loadPluginDescriptor, run => {
return cache.invalidate(data => run(inheritsDescriptor, data)); return cache.invalidate(data => run(inheritsDescriptor, data));
}); });
plugin.pre = chain(inherits.pre, plugin.pre); plugin.pre = chainMaybeAsync(inherits.pre, plugin.pre);
plugin.post = chain(inherits.post, plugin.post); plugin.post = chainMaybeAsync(inherits.post, plugin.post);
plugin.manipulateOptions = chain(inherits.manipulateOptions, plugin.manipulateOptions); plugin.manipulateOptions = chainMaybeAsync(inherits.manipulateOptions, plugin.manipulateOptions);
plugin.visitor = _traverse().default.visitors.merge([inherits.visitor || {}, plugin.visitor || {}]); plugin.visitor = _traverse().default.visitors.merge([inherits.visitor || {}, plugin.visitor || {}]);
if (inherits.externalDependencies.length > 0) { if (inherits.externalDependencies.length > 0) {
if (externalDependencies.length === 0) { if (externalDependencies.length === 0) {
@ -296,13 +296,15 @@ function* loadPresetDescriptor(descriptor, context) {
externalDependencies: preset.externalDependencies externalDependencies: preset.externalDependencies
}; };
} }
function chain(a, b) { function chainMaybeAsync(a, b) {
const fns = [a, b].filter(Boolean); if (!a) return b;
if (fns.length <= 1) return fns[0]; if (!b) return a;
return function (...args) { return function (...args) {
for (const fn of fns) { const res = a.apply(this, args);
fn.apply(this, args); if (res && typeof res.then === "function") {
return res.then(() => b.apply(this, args));
} }
return b.apply(this, args);
}; };
} }
0 && 0; 0 && 0;

File diff suppressed because one or more lines are too long

View File

@ -17,7 +17,7 @@ var _index = require("../../index.js");
var _caching = require("../caching.js"); var _caching = require("../caching.js");
function makeConfigAPI(cache) { function makeConfigAPI(cache) {
const env = value => cache.using(data => { const env = value => cache.using(data => {
if (typeof value === "undefined") return data.envName; if (value === undefined) return data.envName;
if (typeof value === "function") { if (typeof value === "function") {
return (0, _caching.assertSimpleType)(value(data.envName)); return (0, _caching.assertSimpleType)(value(data.envName));
} }

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -21,7 +21,7 @@ var _options = require("./validation/options.js");
var _index = require("./files/index.js"); var _index = require("./files/index.js");
var _resolveTargets = require("./resolve-targets.js"); var _resolveTargets = require("./resolve-targets.js");
const _excluded = ["showIgnoredFiles"]; const _excluded = ["showIgnoredFiles"];
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 _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; }
function resolveRootMode(rootDir, rootMode) { function resolveRootMode(rootDir, rootMode) {
switch (rootMode) { switch (rootMode) {
case "root": case "root":

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -15,8 +15,8 @@ function _gensync() {
}; };
return data; return data;
} }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
const runGenerator = _gensync()(function* (item) { const runGenerator = _gensync()(function* (item) {
return yield* item; return yield* item;
}); });

File diff suppressed because one or more lines are too long

View File

@ -94,18 +94,7 @@ Object.defineProperty(exports, "parseSync", {
return _parse.parseSync; return _parse.parseSync;
} }
}); });
Object.defineProperty(exports, "resolvePlugin", { exports.resolvePreset = exports.resolvePlugin = void 0;
enumerable: true,
get: function () {
return _index.resolvePlugin;
}
});
Object.defineProperty(exports, "resolvePreset", {
enumerable: true,
get: function () {
return _index.resolvePreset;
}
});
Object.defineProperty((0, exports), "template", { Object.defineProperty((0, exports), "template", {
enumerable: true, enumerable: true,
get: function () { get: function () {
@ -181,7 +170,7 @@ Object.defineProperty((0, exports), "traverse", {
exports.version = exports.types = void 0; exports.version = exports.types = void 0;
var _file = require("./transformation/file/file.js"); var _file = require("./transformation/file/file.js");
var _buildExternalHelpers = require("./tools/build-external-helpers.js"); var _buildExternalHelpers = require("./tools/build-external-helpers.js");
var _index = require("./config/files/index.js"); var resolvers = require("./config/files/index.js");
var _environment = require("./config/helpers/environment.js"); var _environment = require("./config/helpers/environment.js");
function _types() { function _types() {
const data = require("@babel/types"); const data = require("@babel/types");
@ -224,7 +213,11 @@ var _transformAst = require("./transform-ast.js");
var _parse = require("./parse.js"); var _parse = require("./parse.js");
var thisFile = require("./index.js"); var thisFile = require("./index.js");
; ;
const version = exports.version = "7.25.2"; const version = exports.version = "7.26.0";
const resolvePlugin = (name, dirname) => resolvers.resolvePlugin(name, dirname, false).filepath;
exports.resolvePlugin = resolvePlugin;
const resolvePreset = (name, dirname) => resolvers.resolvePreset(name, dirname, false).filepath;
exports.resolvePreset = resolvePreset;
const DEFAULT_EXTENSIONS = exports.DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs", ".cjs"]); const DEFAULT_EXTENSIONS = exports.DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs", ".cjs"]);
; ;
{ {

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
{"version":3,"names":["_parser","data","require","_codeFrame","_missingPluginHelper","parser","pluginPasses","parserOpts","highlightCode","filename","code","results","plugins","plugin","parserOverride","ast","parse","undefined","push","length","then","Error","err","message","loc","missingPlugin","codeFrame","codeFrameColumns","start","line","column","generateMissingPluginMessage"],"sources":["../../src/parser/index.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\nimport { parse, type File as ParseResult } from \"@babel/parser\";\nimport { codeFrameColumns } from \"@babel/code-frame\";\nimport generateMissingPluginMessage from \"./util/missing-plugin-helper.ts\";\nimport type { PluginPasses } from \"../config/index.ts\";\n\nexport type { ParseResult };\n\nexport default function* parser(\n pluginPasses: PluginPasses,\n { parserOpts, highlightCode = true, filename = \"unknown\" }: any,\n code: string,\n): Handler<ParseResult> {\n try {\n const results = [];\n for (const plugins of pluginPasses) {\n for (const plugin of plugins) {\n const { parserOverride } = plugin;\n if (parserOverride) {\n const ast = parserOverride(code, parserOpts, parse);\n\n if (ast !== undefined) results.push(ast);\n }\n }\n }\n\n if (results.length === 0) {\n return parse(code, parserOpts);\n } else if (results.length === 1) {\n // @ts-expect-error - If we want to allow async parsers\n yield* [];\n if (typeof results[0].then === \"function\") {\n throw new Error(\n `You appear to be using an async parser plugin, ` +\n `which your current version of Babel does not support. ` +\n `If you're using a published plugin, you may need to upgrade ` +\n `your @babel/core version.`,\n );\n }\n return results[0];\n }\n // TODO: Add an error code\n throw new Error(\"More than one plugin attempted to override parsing.\");\n } catch (err) {\n if (err.code === \"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED\") {\n err.message +=\n \"\\nConsider renaming the file to '.mjs', or setting sourceType:module \" +\n \"or sourceType:unambiguous in your Babel config for this file.\";\n // err.code will be changed to BABEL_PARSE_ERROR later.\n }\n\n const { loc, missingPlugin } = err;\n if (loc) {\n const codeFrame = codeFrameColumns(\n code,\n {\n start: {\n line: loc.line,\n column: loc.column + 1,\n },\n },\n {\n highlightCode,\n },\n );\n if (missingPlugin) {\n err.message =\n `${filename}: ` +\n generateMissingPluginMessage(\n missingPlugin[0],\n loc,\n codeFrame,\n filename,\n );\n } else {\n err.message = `${filename}: ${err.message}\\n\\n` + codeFrame;\n }\n err.code = \"BABEL_PARSE_ERROR\";\n }\n throw err;\n }\n}\n"],"mappings":";;;;;;AACA,SAAAA,QAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,OAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,WAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,UAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,IAAAG,oBAAA,GAAAF,OAAA;AAKe,UAAUG,MAAMA,CAC7BC,YAA0B,EAC1B;EAAEC,UAAU;EAAEC,aAAa,GAAG,IAAI;EAAEC,QAAQ,GAAG;AAAe,CAAC,EAC/DC,IAAY,EACU;EACtB,IAAI;IACF,MAAMC,OAAO,GAAG,EAAE;IAClB,KAAK,MAAMC,OAAO,IAAIN,YAAY,EAAE;MAClC,KAAK,MAAMO,MAAM,IAAID,OAAO,EAAE;QAC5B,MAAM;UAAEE;QAAe,CAAC,GAAGD,MAAM;QACjC,IAAIC,cAAc,EAAE;UAClB,MAAMC,GAAG,GAAGD,cAAc,CAACJ,IAAI,EAAEH,UAAU,EAAES,eAAK,CAAC;UAEnD,IAAID,GAAG,KAAKE,SAAS,EAAEN,OAAO,CAACO,IAAI,CAACH,GAAG,CAAC;QAC1C;MACF;IACF;IAEA,IAAIJ,OAAO,CAACQ,MAAM,KAAK,CAAC,EAAE;MACxB,OAAO,IAAAH,eAAK,EAACN,IAAI,EAAEH,UAAU,CAAC;IAChC,CAAC,MAAM,IAAII,OAAO,CAACQ,MAAM,KAAK,CAAC,EAAE;MAE/B,OAAO,EAAE;MACT,IAAI,OAAOR,OAAO,CAAC,CAAC,CAAC,CAACS,IAAI,KAAK,UAAU,EAAE;QACzC,MAAM,IAAIC,KAAK,CACb,iDAAiD,GAC/C,wDAAwD,GACxD,8DAA8D,GAC9D,2BACJ,CAAC;MACH;MACA,OAAOV,OAAO,CAAC,CAAC,CAAC;IACnB;IAEA,MAAM,IAAIU,KAAK,CAAC,qDAAqD,CAAC;EACxE,CAAC,CAAC,OAAOC,GAAG,EAAE;IACZ,IAAIA,GAAG,CAACZ,IAAI,KAAK,yCAAyC,EAAE;MAC1DY,GAAG,CAACC,OAAO,IACT,uEAAuE,GACvE,+DAA+D;IAEnE;IAEA,MAAM;MAAEC,GAAG;MAAEC;IAAc,CAAC,GAAGH,GAAG;IAClC,IAAIE,GAAG,EAAE;MACP,MAAME,SAAS,GAAG,IAAAC,6BAAgB,EAChCjB,IAAI,EACJ;QACEkB,KAAK,EAAE;UACLC,IAAI,EAAEL,GAAG,CAACK,IAAI;UACdC,MAAM,EAAEN,GAAG,CAACM,MAAM,GAAG;QACvB;MACF,CAAC,EACD;QACEtB;MACF,CACF,CAAC;MACD,IAAIiB,aAAa,EAAE;QACjBH,GAAG,CAACC,OAAO,GACT,GAAGd,QAAQ,IAAI,GACf,IAAAsB,4BAA4B,EAC1BN,aAAa,CAAC,CAAC,CAAC,EAChBD,GAAG,EACHE,SAAS,EACTjB,QACF,CAAC;MACL,CAAC,MAAM;QACLa,GAAG,CAACC,OAAO,GAAG,GAAGd,QAAQ,KAAKa,GAAG,CAACC,OAAO,MAAM,GAAGG,SAAS;MAC7D;MACAJ,GAAG,CAACZ,IAAI,GAAG,mBAAmB;IAChC;IACA,MAAMY,GAAG;EACX;AACF;AAAC","ignoreList":[]} {"version":3,"names":["_parser","data","require","_codeFrame","_missingPluginHelper","parser","pluginPasses","parserOpts","highlightCode","filename","code","results","plugins","plugin","parserOverride","ast","parse","undefined","push","length","then","Error","err","message","loc","missingPlugin","codeFrame","codeFrameColumns","start","line","column","generateMissingPluginMessage"],"sources":["../../src/parser/index.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\nimport { parse, type File as ParseResult } from \"@babel/parser\";\nimport { codeFrameColumns } from \"@babel/code-frame\";\nimport generateMissingPluginMessage from \"./util/missing-plugin-helper.ts\";\nimport type { PluginPasses } from \"../config/index.ts\";\n\nexport type { ParseResult };\n\nexport default function* parser(\n pluginPasses: PluginPasses,\n { parserOpts, highlightCode = true, filename = \"unknown\" }: any,\n code: string,\n): Handler<ParseResult> {\n try {\n const results = [];\n for (const plugins of pluginPasses) {\n for (const plugin of plugins) {\n const { parserOverride } = plugin;\n if (parserOverride) {\n const ast = parserOverride(code, parserOpts, parse);\n\n if (ast !== undefined) results.push(ast);\n }\n }\n }\n\n if (results.length === 0) {\n return parse(code, parserOpts);\n } else if (results.length === 1) {\n // If we want to allow async parsers\n yield* [];\n if (typeof results[0].then === \"function\") {\n throw new Error(\n `You appear to be using an async parser plugin, ` +\n `which your current version of Babel does not support. ` +\n `If you're using a published plugin, you may need to upgrade ` +\n `your @babel/core version.`,\n );\n }\n return results[0];\n }\n // TODO: Add an error code\n throw new Error(\"More than one plugin attempted to override parsing.\");\n } catch (err) {\n if (err.code === \"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED\") {\n err.message +=\n \"\\nConsider renaming the file to '.mjs', or setting sourceType:module \" +\n \"or sourceType:unambiguous in your Babel config for this file.\";\n // err.code will be changed to BABEL_PARSE_ERROR later.\n }\n\n const { loc, missingPlugin } = err;\n if (loc) {\n const codeFrame = codeFrameColumns(\n code,\n {\n start: {\n line: loc.line,\n column: loc.column + 1,\n },\n },\n {\n highlightCode,\n },\n );\n if (missingPlugin) {\n err.message =\n `${filename}: ` +\n generateMissingPluginMessage(\n missingPlugin[0],\n loc,\n codeFrame,\n filename,\n );\n } else {\n err.message = `${filename}: ${err.message}\\n\\n` + codeFrame;\n }\n err.code = \"BABEL_PARSE_ERROR\";\n }\n throw err;\n }\n}\n"],"mappings":";;;;;;AACA,SAAAA,QAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,OAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,WAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,UAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,IAAAG,oBAAA,GAAAF,OAAA;AAKe,UAAUG,MAAMA,CAC7BC,YAA0B,EAC1B;EAAEC,UAAU;EAAEC,aAAa,GAAG,IAAI;EAAEC,QAAQ,GAAG;AAAe,CAAC,EAC/DC,IAAY,EACU;EACtB,IAAI;IACF,MAAMC,OAAO,GAAG,EAAE;IAClB,KAAK,MAAMC,OAAO,IAAIN,YAAY,EAAE;MAClC,KAAK,MAAMO,MAAM,IAAID,OAAO,EAAE;QAC5B,MAAM;UAAEE;QAAe,CAAC,GAAGD,MAAM;QACjC,IAAIC,cAAc,EAAE;UAClB,MAAMC,GAAG,GAAGD,cAAc,CAACJ,IAAI,EAAEH,UAAU,EAAES,eAAK,CAAC;UAEnD,IAAID,GAAG,KAAKE,SAAS,EAAEN,OAAO,CAACO,IAAI,CAACH,GAAG,CAAC;QAC1C;MACF;IACF;IAEA,IAAIJ,OAAO,CAACQ,MAAM,KAAK,CAAC,EAAE;MACxB,OAAO,IAAAH,eAAK,EAACN,IAAI,EAAEH,UAAU,CAAC;IAChC,CAAC,MAAM,IAAII,OAAO,CAACQ,MAAM,KAAK,CAAC,EAAE;MAE/B,OAAO,EAAE;MACT,IAAI,OAAOR,OAAO,CAAC,CAAC,CAAC,CAACS,IAAI,KAAK,UAAU,EAAE;QACzC,MAAM,IAAIC,KAAK,CACb,iDAAiD,GAC/C,wDAAwD,GACxD,8DAA8D,GAC9D,2BACJ,CAAC;MACH;MACA,OAAOV,OAAO,CAAC,CAAC,CAAC;IACnB;IAEA,MAAM,IAAIU,KAAK,CAAC,qDAAqD,CAAC;EACxE,CAAC,CAAC,OAAOC,GAAG,EAAE;IACZ,IAAIA,GAAG,CAACZ,IAAI,KAAK,yCAAyC,EAAE;MAC1DY,GAAG,CAACC,OAAO,IACT,uEAAuE,GACvE,+DAA+D;IAEnE;IAEA,MAAM;MAAEC,GAAG;MAAEC;IAAc,CAAC,GAAGH,GAAG;IAClC,IAAIE,GAAG,EAAE;MACP,MAAME,SAAS,GAAG,IAAAC,6BAAgB,EAChCjB,IAAI,EACJ;QACEkB,KAAK,EAAE;UACLC,IAAI,EAAEL,GAAG,CAACK,IAAI;UACdC,MAAM,EAAEN,GAAG,CAACM,MAAM,GAAG;QACvB;MACF,CAAC,EACD;QACEtB;MACF,CACF,CAAC;MACD,IAAIiB,aAAa,EAAE;QACjBH,GAAG,CAACC,OAAO,GACT,GAAGd,QAAQ,IAAI,GACf,IAAAsB,4BAA4B,EAC1BN,aAAa,CAAC,CAAC,CAAC,EAChBD,GAAG,EACHE,SAAS,EACTjB,QACF,CAAC;MACL,CAAC,MAAM;QACLa,GAAG,CAACC,OAAO,GAAG,GAAGd,QAAQ,KAAKa,GAAG,CAACC,OAAO,MAAM,GAAGG,SAAS;MAC7D;MACAJ,GAAG,CAACZ,IAAI,GAAG,mBAAmB;IAChC;IACA,MAAMY,GAAG;EACX;AACF;AAAC","ignoreList":[]}

View File

@ -87,12 +87,6 @@ const pluginNameMap = {
url: "https://github.com/babel/babel/tree/main/packages/babel-preset-react" url: "https://github.com/babel/babel/tree/main/packages/babel-preset-react"
} }
}, },
importAttributes: {
syntax: {
name: "@babel/plugin-syntax-import-attributes",
url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-attributes"
}
},
pipelineOperator: { pipelineOperator: {
syntax: { syntax: {
name: "@babel/plugin-syntax-pipeline-operator", name: "@babel/plugin-syntax-pipeline-operator",
@ -204,6 +198,12 @@ const pluginNameMap = {
url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-assertions" url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-assertions"
} }
}, },
importAttributes: {
syntax: {
name: "@babel/plugin-syntax-import-attributes",
url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-attributes"
}
},
importMeta: { importMeta: {
syntax: { syntax: {
name: "@babel/plugin-syntax-import-meta", name: "@babel/plugin-syntax-import-meta",

File diff suppressed because one or more lines are too long

View File

@ -17,6 +17,7 @@ var _normalizeOpts = require("./normalize-opts.js");
var _normalizeFile = require("./normalize-file.js"); var _normalizeFile = require("./normalize-file.js");
var _generate = require("./file/generate.js"); var _generate = require("./file/generate.js");
var _deepArray = require("../config/helpers/deep-array.js"); var _deepArray = require("../config/helpers/deep-array.js");
var _async = require("../gensync-utils/async.js");
function* run(config, code, ast) { function* run(config, code, ast) {
const file = yield* (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code, ast); const file = yield* (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code, ast);
const opts = file.opts; const opts = file.opts;
@ -57,24 +58,21 @@ function* run(config, code, ast) {
}; };
} }
function* transformFile(file, pluginPasses) { function* transformFile(file, pluginPasses) {
const async = yield* (0, _async.isAsync)();
for (const pluginPairs of pluginPasses) { for (const pluginPairs of pluginPasses) {
const passPairs = []; const passPairs = [];
const passes = []; const passes = [];
const visitors = []; const visitors = [];
for (const plugin of pluginPairs.concat([(0, _blockHoistPlugin.default)()])) { for (const plugin of pluginPairs.concat([(0, _blockHoistPlugin.default)()])) {
const pass = new _pluginPass.default(file, plugin.key, plugin.options); const pass = new _pluginPass.default(file, plugin.key, plugin.options, async);
passPairs.push([plugin, pass]); passPairs.push([plugin, pass]);
passes.push(pass); passes.push(pass);
visitors.push(plugin.visitor); visitors.push(plugin.visitor);
} }
for (const [plugin, pass] of passPairs) { for (const [plugin, pass] of passPairs) {
const fn = plugin.pre; if (plugin.pre) {
if (fn) { const fn = (0, _async.maybeAsync)(plugin.pre, `You appear to be using an async plugin/preset, but Babel has been called synchronously`);
const result = fn.call(pass, file); yield* fn.call(pass, file);
yield* [];
if (isThenable(result)) {
throw new Error(`You appear to be using an plugin with an async .pre, ` + `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.`);
}
} }
} }
const visitor = _traverse().default.visitors.merge(visitors, passes, file.opts.wrapPluginVisitorMethod); const visitor = _traverse().default.visitors.merge(visitors, passes, file.opts.wrapPluginVisitorMethod);
@ -82,20 +80,13 @@ function* transformFile(file, pluginPasses) {
(0, _traverse().default)(file.ast, visitor, file.scope); (0, _traverse().default)(file.ast, visitor, file.scope);
} }
for (const [plugin, pass] of passPairs) { for (const [plugin, pass] of passPairs) {
const fn = plugin.post; if (plugin.post) {
if (fn) { const fn = (0, _async.maybeAsync)(plugin.post, `You appear to be using an async plugin/preset, but Babel has been called synchronously`);
const result = fn.call(pass, file); yield* fn.call(pass, file);
yield* [];
if (isThenable(result)) {
throw new Error(`You appear to be using an plugin with an async .post, ` + `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.`);
} }
} }
} }
} }
}
function isThenable(val) {
return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function";
}
0 && 0; 0 && 0;
//# sourceMappingURL=index.js.map //# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@ -5,18 +5,20 @@ Object.defineProperty(exports, "__esModule", {
}); });
exports.default = void 0; exports.default = void 0;
class PluginPass { class PluginPass {
constructor(file, key, options) { constructor(file, key, options, isAsync) {
this._map = new Map(); this._map = new Map();
this.key = void 0; this.key = void 0;
this.file = void 0; this.file = void 0;
this.opts = void 0; this.opts = void 0;
this.cwd = void 0; this.cwd = void 0;
this.filename = void 0; this.filename = void 0;
this.isAsync = void 0;
this.key = key; this.key = key;
this.file = file; this.file = file;
this.opts = options || {}; this.opts = options || {};
this.cwd = file.opts.cwd; this.cwd = file.opts.cwd;
this.filename = file.opts.filename; this.filename = file.opts.filename;
this.isAsync = isAsync;
} }
set(key, val) { set(key, val) {
this._map.set(key, val); this._map.set(key, val);

View File

@ -1 +1 @@
{"version":3,"names":["PluginPass","constructor","file","key","options","_map","Map","opts","cwd","filename","set","val","get","availableHelper","name","versionRange","addHelper","buildCodeFrameError","node","msg","_Error","exports","default","prototype","getModuleName","addImport"],"sources":["../../src/transformation/plugin-pass.ts"],"sourcesContent":["import type * as t from \"@babel/types\";\nimport type File from \"./file/file.ts\";\n\nexport default class PluginPass<Options = object> {\n _map: Map<unknown, unknown> = new Map();\n key: string | undefined | null;\n file: File;\n opts: Partial<Options>;\n\n // The working directory that Babel's programmatic options are loaded\n // relative to.\n cwd: string;\n\n // The absolute path of the file being compiled.\n filename: string | void;\n\n constructor(file: File, key?: string | null, options?: Options) {\n this.key = key;\n this.file = file;\n this.opts = options || {};\n this.cwd = file.opts.cwd;\n this.filename = file.opts.filename;\n }\n\n set(key: unknown, val: unknown) {\n this._map.set(key, val);\n }\n\n get(key: unknown): any {\n return this._map.get(key);\n }\n\n availableHelper(name: string, versionRange?: string | null) {\n return this.file.availableHelper(name, versionRange);\n }\n\n addHelper(name: string) {\n return this.file.addHelper(name);\n }\n\n buildCodeFrameError(\n node: t.Node | undefined | null,\n msg: string,\n _Error?: typeof Error,\n ) {\n return this.file.buildCodeFrameError(node, msg, _Error);\n }\n}\n\nif (!process.env.BABEL_8_BREAKING) {\n (PluginPass as any).prototype.getModuleName = function getModuleName(\n this: PluginPass,\n ): string | undefined {\n // @ts-expect-error only exists in Babel 7\n return this.file.getModuleName();\n };\n (PluginPass as any).prototype.addImport = function addImport(\n this: PluginPass,\n ): void {\n // @ts-expect-error only exists in Babel 7\n this.file.addImport();\n };\n}\n"],"mappings":";;;;;;AAGe,MAAMA,UAAU,CAAmB;EAahDC,WAAWA,CAACC,IAAU,EAAEC,GAAmB,EAAEC,OAAiB,EAAE;IAAA,KAZhEC,IAAI,GAA0B,IAAIC,GAAG,CAAC,CAAC;IAAA,KACvCH,GAAG;IAAA,KACHD,IAAI;IAAA,KACJK,IAAI;IAAA,KAIJC,GAAG;IAAA,KAGHC,QAAQ;IAGN,IAAI,CAACN,GAAG,GAAGA,GAAG;IACd,IAAI,CAACD,IAAI,GAAGA,IAAI;IAChB,IAAI,CAACK,IAAI,GAAGH,OAAO,IAAI,CAAC,CAAC;IACzB,IAAI,CAACI,GAAG,GAAGN,IAAI,CAACK,IAAI,CAACC,GAAG;IACxB,IAAI,CAACC,QAAQ,GAAGP,IAAI,CAACK,IAAI,CAACE,QAAQ;EACpC;EAEAC,GAAGA,CAACP,GAAY,EAAEQ,GAAY,EAAE;IAC9B,IAAI,CAACN,IAAI,CAACK,GAAG,CAACP,GAAG,EAAEQ,GAAG,CAAC;EACzB;EAEAC,GAAGA,CAACT,GAAY,EAAO;IACrB,OAAO,IAAI,CAACE,IAAI,CAACO,GAAG,CAACT,GAAG,CAAC;EAC3B;EAEAU,eAAeA,CAACC,IAAY,EAAEC,YAA4B,EAAE;IAC1D,OAAO,IAAI,CAACb,IAAI,CAACW,eAAe,CAACC,IAAI,EAAEC,YAAY,CAAC;EACtD;EAEAC,SAASA,CAACF,IAAY,EAAE;IACtB,OAAO,IAAI,CAACZ,IAAI,CAACc,SAAS,CAACF,IAAI,CAAC;EAClC;EAEAG,mBAAmBA,CACjBC,IAA+B,EAC/BC,GAAW,EACXC,MAAqB,EACrB;IACA,OAAO,IAAI,CAAClB,IAAI,CAACe,mBAAmB,CAACC,IAAI,EAAEC,GAAG,EAAEC,MAAM,CAAC;EACzD;AACF;AAACC,OAAA,CAAAC,OAAA,GAAAtB,UAAA;AAEkC;EAChCA,UAAU,CAASuB,SAAS,CAACC,aAAa,GAAG,SAASA,aAAaA,CAAA,EAE9C;IAEpB,OAAO,IAAI,CAACtB,IAAI,CAACsB,aAAa,CAAC,CAAC;EAClC,CAAC;EACAxB,UAAU,CAASuB,SAAS,CAACE,SAAS,GAAG,SAASA,SAASA,CAAA,EAEpD;IAEN,IAAI,CAACvB,IAAI,CAACuB,SAAS,CAAC,CAAC;EACvB,CAAC;AACH;AAAC","ignoreList":[]} {"version":3,"names":["PluginPass","constructor","file","key","options","isAsync","_map","Map","opts","cwd","filename","set","val","get","availableHelper","name","versionRange","addHelper","buildCodeFrameError","node","msg","_Error","exports","default","prototype","getModuleName","addImport"],"sources":["../../src/transformation/plugin-pass.ts"],"sourcesContent":["import type * as t from \"@babel/types\";\nimport type File from \"./file/file.ts\";\n\nexport default class PluginPass<Options = object> {\n _map: Map<unknown, unknown> = new Map();\n key: string | undefined | null;\n file: File;\n opts: Partial<Options>;\n\n /**\n * The working directory that Babel's programmatic options are loaded\n * relative to.\n */\n cwd: string;\n\n /** The absolute path of the file being compiled. */\n filename: string | void;\n\n /**\n * Is Babel executed in async mode or not.\n */\n isAsync: boolean;\n\n constructor(\n file: File,\n key: string | null,\n options: Options | undefined,\n isAsync: boolean,\n ) {\n this.key = key;\n this.file = file;\n this.opts = options || {};\n this.cwd = file.opts.cwd;\n this.filename = file.opts.filename;\n this.isAsync = isAsync;\n }\n\n set(key: unknown, val: unknown) {\n this._map.set(key, val);\n }\n\n get(key: unknown): any {\n return this._map.get(key);\n }\n\n availableHelper(name: string, versionRange?: string | null) {\n return this.file.availableHelper(name, versionRange);\n }\n\n addHelper(name: string) {\n return this.file.addHelper(name);\n }\n\n buildCodeFrameError(\n node: t.Node | undefined | null,\n msg: string,\n _Error?: typeof Error,\n ) {\n return this.file.buildCodeFrameError(node, msg, _Error);\n }\n}\n\nif (!process.env.BABEL_8_BREAKING) {\n (PluginPass as any).prototype.getModuleName = function getModuleName(\n this: PluginPass,\n ): string | undefined {\n // @ts-expect-error only exists in Babel 7\n return this.file.getModuleName();\n };\n (PluginPass as any).prototype.addImport = function addImport(\n this: PluginPass,\n ): void {\n // @ts-expect-error only exists in Babel 7\n this.file.addImport();\n };\n}\n"],"mappings":";;;;;;AAGe,MAAMA,UAAU,CAAmB;EAoBhDC,WAAWA,CACTC,IAAU,EACVC,GAAkB,EAClBC,OAA4B,EAC5BC,OAAgB,EAChB;IAAA,KAxBFC,IAAI,GAA0B,IAAIC,GAAG,CAAC,CAAC;IAAA,KACvCJ,GAAG;IAAA,KACHD,IAAI;IAAA,KACJM,IAAI;IAAA,KAMJC,GAAG;IAAA,KAGHC,QAAQ;IAAA,KAKRL,OAAO;IAQL,IAAI,CAACF,GAAG,GAAGA,GAAG;IACd,IAAI,CAACD,IAAI,GAAGA,IAAI;IAChB,IAAI,CAACM,IAAI,GAAGJ,OAAO,IAAI,CAAC,CAAC;IACzB,IAAI,CAACK,GAAG,GAAGP,IAAI,CAACM,IAAI,CAACC,GAAG;IACxB,IAAI,CAACC,QAAQ,GAAGR,IAAI,CAACM,IAAI,CAACE,QAAQ;IAClC,IAAI,CAACL,OAAO,GAAGA,OAAO;EACxB;EAEAM,GAAGA,CAACR,GAAY,EAAES,GAAY,EAAE;IAC9B,IAAI,CAACN,IAAI,CAACK,GAAG,CAACR,GAAG,EAAES,GAAG,CAAC;EACzB;EAEAC,GAAGA,CAACV,GAAY,EAAO;IACrB,OAAO,IAAI,CAACG,IAAI,CAACO,GAAG,CAACV,GAAG,CAAC;EAC3B;EAEAW,eAAeA,CAACC,IAAY,EAAEC,YAA4B,EAAE;IAC1D,OAAO,IAAI,CAACd,IAAI,CAACY,eAAe,CAACC,IAAI,EAAEC,YAAY,CAAC;EACtD;EAEAC,SAASA,CAACF,IAAY,EAAE;IACtB,OAAO,IAAI,CAACb,IAAI,CAACe,SAAS,CAACF,IAAI,CAAC;EAClC;EAEAG,mBAAmBA,CACjBC,IAA+B,EAC/BC,GAAW,EACXC,MAAqB,EACrB;IACA,OAAO,IAAI,CAACnB,IAAI,CAACgB,mBAAmB,CAACC,IAAI,EAAEC,GAAG,EAAEC,MAAM,CAAC;EACzD;AACF;AAACC,OAAA,CAAAC,OAAA,GAAAvB,UAAA;AAEkC;EAChCA,UAAU,CAASwB,SAAS,CAACC,aAAa,GAAG,SAASA,aAAaA,CAAA,EAE9C;IAEpB,OAAO,IAAI,CAACvB,IAAI,CAACuB,aAAa,CAAC,CAAC;EAClC,CAAC;EACAzB,UAAU,CAASwB,SAAS,CAACE,SAAS,GAAG,SAASA,SAASA,CAAA,EAEpD;IAEN,IAAI,CAACxB,IAAI,CAACwB,SAAS,CAAC,CAAC;EACvB,CAAC;AACH;AAAC","ignoreList":[]}

View File

@ -1,6 +1,6 @@
{ {
"name": "@babel/core", "name": "@babel/core",
"version": "7.25.2", "version": "7.26.0",
"description": "Babel compiler core.", "description": "Babel compiler core.",
"main": "./lib/index.js", "main": "./lib/index.js",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
@ -47,15 +47,15 @@
}, },
"dependencies": { "dependencies": {
"@ampproject/remapping": "^2.2.0", "@ampproject/remapping": "^2.2.0",
"@babel/code-frame": "^7.24.7", "@babel/code-frame": "^7.26.0",
"@babel/generator": "^7.25.0", "@babel/generator": "^7.26.0",
"@babel/helper-compilation-targets": "^7.25.2", "@babel/helper-compilation-targets": "^7.25.9",
"@babel/helper-module-transforms": "^7.25.2", "@babel/helper-module-transforms": "^7.26.0",
"@babel/helpers": "^7.25.0", "@babel/helpers": "^7.26.0",
"@babel/parser": "^7.25.0", "@babel/parser": "^7.26.0",
"@babel/template": "^7.25.0", "@babel/template": "^7.25.9",
"@babel/traverse": "^7.25.2", "@babel/traverse": "^7.25.9",
"@babel/types": "^7.25.2", "@babel/types": "^7.26.0",
"convert-source-map": "^2.0.0", "convert-source-map": "^2.0.0",
"debug": "^4.1.0", "debug": "^4.1.0",
"gensync": "^1.0.0-beta.2", "gensync": "^1.0.0-beta.2",
@ -63,12 +63,12 @@
"semver": "^6.3.1" "semver": "^6.3.1"
}, },
"devDependencies": { "devDependencies": {
"@babel/helper-transform-fixture-test-runner": "^7.25.2", "@babel/helper-transform-fixture-test-runner": "^7.26.0",
"@babel/plugin-syntax-flow": "^7.24.7", "@babel/plugin-syntax-flow": "^7.26.0",
"@babel/plugin-transform-flow-strip-types": "^7.25.2", "@babel/plugin-transform-flow-strip-types": "^7.25.9",
"@babel/plugin-transform-modules-commonjs": "^7.24.8", "@babel/plugin-transform-modules-commonjs": "^7.25.9",
"@babel/preset-env": "^7.25.2", "@babel/preset-env": "^7.26.0",
"@babel/preset-typescript": "^7.24.7", "@babel/preset-typescript": "^7.26.0",
"@jridgewell/trace-mapping": "^0.3.25", "@jridgewell/trace-mapping": "^0.3.25",
"@types/convert-source-map": "^2.0.0", "@types/convert-source-map": "^2.0.0",
"@types/debug": "^4.1.0", "@types/debug": "^4.1.0",

View File

@ -74,13 +74,17 @@ export function* resolveShowConfigPath(
export const ROOT_CONFIG_FILENAMES: string[] = []; export const ROOT_CONFIG_FILENAMES: string[] = [];
type Resolved =
| { loader: "require"; filepath: string }
| { loader: "import"; filepath: string };
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
export function resolvePlugin(name: string, dirname: string): string | null { export function resolvePlugin(name: string, dirname: string): Resolved | null {
return null; return null;
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
export function resolvePreset(name: string, dirname: string): string | null { export function resolvePreset(name: string, dirname: string): Resolved | null {
return null; return null;
} }

File diff suppressed because one or more lines are too long

View File

@ -12,9 +12,9 @@ exports.Placeholder = Placeholder;
exports.Program = Program; exports.Program = Program;
function File(node) { function File(node) {
if (node.program) { if (node.program) {
this.print(node.program.interpreter, node); this.print(node.program.interpreter);
} }
this.print(node.program, node); this.print(node.program);
} }
function Program(node) { function Program(node) {
var _node$directives; var _node$directives;
@ -24,23 +24,24 @@ function Program(node) {
if (directivesLen) { if (directivesLen) {
var _node$directives$trai; var _node$directives$trai;
const newline = node.body.length ? 2 : 1; const newline = node.body.length ? 2 : 1;
this.printSequence(node.directives, node, { this.printSequence(node.directives, {
trailingCommentsLineOffset: newline trailingCommentsLineOffset: newline
}); });
if (!((_node$directives$trai = node.directives[directivesLen - 1].trailingComments) != null && _node$directives$trai.length)) { if (!((_node$directives$trai = node.directives[directivesLen - 1].trailingComments) != null && _node$directives$trai.length)) {
this.newline(newline); this.newline(newline);
} }
} }
this.printSequence(node.body, node); this.printSequence(node.body);
} }
function BlockStatement(node) { function BlockStatement(node) {
var _node$directives2; var _node$directives2;
this.tokenChar(123); this.tokenChar(123);
const exit = this.enterDelimited();
const directivesLen = (_node$directives2 = node.directives) == null ? void 0 : _node$directives2.length; const directivesLen = (_node$directives2 = node.directives) == null ? void 0 : _node$directives2.length;
if (directivesLen) { if (directivesLen) {
var _node$directives$trai2; var _node$directives$trai2;
const newline = node.body.length ? 2 : 1; const newline = node.body.length ? 2 : 1;
this.printSequence(node.directives, node, { this.printSequence(node.directives, {
indent: true, indent: true,
trailingCommentsLineOffset: newline trailingCommentsLineOffset: newline
}); });
@ -48,15 +49,14 @@ function BlockStatement(node) {
this.newline(newline); this.newline(newline);
} }
} }
const exit = this.enterForStatementInit(false); this.printSequence(node.body, {
this.printSequence(node.body, node, {
indent: true indent: true
}); });
exit(); exit();
this.rightBrace(node); this.rightBrace(node);
} }
function Directive(node) { function Directive(node) {
this.print(node.value, node); this.print(node.value);
this.semicolon(); this.semicolon();
} }
const unescapedSingleQuoteRE = /(?:^|[^\\])(?:\\\\)*'/; const unescapedSingleQuoteRE = /(?:^|[^\\])(?:\\\\)*'/;

File diff suppressed because one or more lines are too long

View File

@ -20,7 +20,7 @@ const {
function ClassDeclaration(node, parent) { function ClassDeclaration(node, parent) {
const inExport = isExportDefaultDeclaration(parent) || isExportNamedDeclaration(parent); const inExport = isExportDefaultDeclaration(parent) || isExportNamedDeclaration(parent);
if (!inExport || !this._shouldPrintDecoratorsBeforeExport(parent)) { if (!inExport || !this._shouldPrintDecoratorsBeforeExport(parent)) {
this.printJoin(node.decorators, node); this.printJoin(node.decorators);
} }
if (node.declare) { if (node.declare) {
this.word("declare"); this.word("declare");
@ -33,24 +33,24 @@ function ClassDeclaration(node, parent) {
this.word("class"); this.word("class");
if (node.id) { if (node.id) {
this.space(); this.space();
this.print(node.id, node); this.print(node.id);
} }
this.print(node.typeParameters, node); this.print(node.typeParameters);
if (node.superClass) { if (node.superClass) {
this.space(); this.space();
this.word("extends"); this.word("extends");
this.space(); this.space();
this.print(node.superClass, node); this.print(node.superClass);
this.print(node.superTypeParameters, node); this.print(node.superTypeParameters);
} }
if (node.implements) { if (node.implements) {
this.space(); this.space();
this.word("implements"); this.word("implements");
this.space(); this.space();
this.printList(node.implements, node); this.printList(node.implements);
} }
this.space(); this.space();
this.print(node.body, node); this.print(node.body);
} }
function ClassBody(node) { function ClassBody(node) {
this.tokenChar(123); this.tokenChar(123);
@ -58,28 +58,63 @@ function ClassBody(node) {
this.tokenChar(125); this.tokenChar(125);
} else { } else {
this.newline(); this.newline();
const exit = this.enterForStatementInit(false); const separator = classBodyEmptySemicolonsPrinter(this, node);
this.printSequence(node.body, node, { separator == null || separator(-1);
indent: true const exit = this.enterDelimited();
this.printJoin(node.body, {
statement: true,
indent: true,
separator,
printTrailingSeparator: true
}); });
exit(); exit();
if (!this.endsWith(10)) this.newline(); if (!this.endsWith(10)) this.newline();
this.rightBrace(node); this.rightBrace(node);
} }
} }
function classBodyEmptySemicolonsPrinter(printer, node) {
if (!printer.tokenMap || node.start == null || node.end == null) {
return null;
}
const indexes = printer.tokenMap.getIndexes(node);
if (!indexes) return null;
let k = 1;
let occurrenceCount = 0;
let nextLocIndex = 0;
const advanceNextLocIndex = () => {
while (nextLocIndex < node.body.length && node.body[nextLocIndex].start == null) {
nextLocIndex++;
}
};
advanceNextLocIndex();
return i => {
if (nextLocIndex <= i) {
nextLocIndex = i + 1;
advanceNextLocIndex();
}
const end = nextLocIndex === node.body.length ? node.end : node.body[nextLocIndex].start;
let tok;
while (k < indexes.length && printer.tokenMap.matchesOriginal(tok = printer._tokens[indexes[k]], ";") && tok.start < end) {
printer.token(";", undefined, occurrenceCount++);
k++;
}
};
}
function ClassProperty(node) { function ClassProperty(node) {
this.printJoin(node.decorators);
if (!node.static && !this.format.preserveFormat) {
var _node$key$loc; var _node$key$loc;
this.printJoin(node.decorators, node);
const endLine = (_node$key$loc = node.key.loc) == null || (_node$key$loc = _node$key$loc.end) == null ? void 0 : _node$key$loc.line; const endLine = (_node$key$loc = node.key.loc) == null || (_node$key$loc = _node$key$loc.end) == null ? void 0 : _node$key$loc.line;
if (endLine) this.catchUp(endLine); if (endLine) this.catchUp(endLine);
}
this.tsPrintClassMemberModifiers(node); this.tsPrintClassMemberModifiers(node);
if (node.computed) { if (node.computed) {
this.tokenChar(91); this.tokenChar(91);
this.print(node.key, node); this.print(node.key);
this.tokenChar(93); this.tokenChar(93);
} else { } else {
this._variance(node); this._variance(node);
this.print(node.key, node); this.print(node.key);
} }
if (node.optional) { if (node.optional) {
this.tokenChar(63); this.tokenChar(63);
@ -87,18 +122,18 @@ function ClassProperty(node) {
if (node.definite) { if (node.definite) {
this.tokenChar(33); this.tokenChar(33);
} }
this.print(node.typeAnnotation, node); this.print(node.typeAnnotation);
if (node.value) { if (node.value) {
this.space(); this.space();
this.tokenChar(61); this.tokenChar(61);
this.space(); this.space();
this.print(node.value, node); this.print(node.value);
} }
this.semicolon(); this.semicolon();
} }
function ClassAccessorProperty(node) { function ClassAccessorProperty(node) {
var _node$key$loc2; var _node$key$loc2;
this.printJoin(node.decorators, node); this.printJoin(node.decorators);
const endLine = (_node$key$loc2 = node.key.loc) == null || (_node$key$loc2 = _node$key$loc2.end) == null ? void 0 : _node$key$loc2.line; const endLine = (_node$key$loc2 = node.key.loc) == null || (_node$key$loc2 = _node$key$loc2.end) == null ? void 0 : _node$key$loc2.line;
if (endLine) this.catchUp(endLine); if (endLine) this.catchUp(endLine);
this.tsPrintClassMemberModifiers(node); this.tsPrintClassMemberModifiers(node);
@ -106,11 +141,11 @@ function ClassAccessorProperty(node) {
this.space(); this.space();
if (node.computed) { if (node.computed) {
this.tokenChar(91); this.tokenChar(91);
this.print(node.key, node); this.print(node.key);
this.tokenChar(93); this.tokenChar(93);
} else { } else {
this._variance(node); this._variance(node);
this.print(node.key, node); this.print(node.key);
} }
if (node.optional) { if (node.optional) {
this.tokenChar(63); this.tokenChar(63);
@ -118,46 +153,48 @@ function ClassAccessorProperty(node) {
if (node.definite) { if (node.definite) {
this.tokenChar(33); this.tokenChar(33);
} }
this.print(node.typeAnnotation, node); this.print(node.typeAnnotation);
if (node.value) { if (node.value) {
this.space(); this.space();
this.tokenChar(61); this.tokenChar(61);
this.space(); this.space();
this.print(node.value, node); this.print(node.value);
} }
this.semicolon(); this.semicolon();
} }
function ClassPrivateProperty(node) { function ClassPrivateProperty(node) {
this.printJoin(node.decorators, node); this.printJoin(node.decorators);
if (node.static) { if (node.static) {
this.word("static"); this.word("static");
this.space(); this.space();
} }
this.print(node.key, node); this.print(node.key);
this.print(node.typeAnnotation, node); this.print(node.typeAnnotation);
if (node.value) { if (node.value) {
this.space(); this.space();
this.tokenChar(61); this.tokenChar(61);
this.space(); this.space();
this.print(node.value, node); this.print(node.value);
} }
this.semicolon(); this.semicolon();
} }
function ClassMethod(node) { function ClassMethod(node) {
this._classMethodHead(node); this._classMethodHead(node);
this.space(); this.space();
this.print(node.body, node); this.print(node.body);
} }
function ClassPrivateMethod(node) { function ClassPrivateMethod(node) {
this._classMethodHead(node); this._classMethodHead(node);
this.space(); this.space();
this.print(node.body, node); this.print(node.body);
} }
function _classMethodHead(node) { function _classMethodHead(node) {
this.printJoin(node.decorators);
if (!this.format.preserveFormat) {
var _node$key$loc3; var _node$key$loc3;
this.printJoin(node.decorators, node);
const endLine = (_node$key$loc3 = node.key.loc) == null || (_node$key$loc3 = _node$key$loc3.end) == null ? void 0 : _node$key$loc3.line; const endLine = (_node$key$loc3 = node.key.loc) == null || (_node$key$loc3 = _node$key$loc3.end) == null ? void 0 : _node$key$loc3.line;
if (endLine) this.catchUp(endLine); if (endLine) this.catchUp(endLine);
}
this.tsPrintClassMemberModifiers(node); this.tsPrintClassMemberModifiers(node);
this._methodHead(node); this._methodHead(node);
} }
@ -169,7 +206,7 @@ function StaticBlock(node) {
this.tokenChar(125); this.tokenChar(125);
} else { } else {
this.newline(); this.newline();
this.printSequence(node.body, node, { this.printSequence(node.body, {
indent: true indent: true
}); });
this.rightBrace(node); this.rightBrace(node);

File diff suppressed because one or more lines are too long

View File

@ -36,7 +36,8 @@ const {
isCallExpression, isCallExpression,
isLiteral, isLiteral,
isMemberExpression, isMemberExpression,
isNewExpression isNewExpression,
isPattern
} = _t; } = _t;
function UnaryExpression(node) { function UnaryExpression(node) {
const { const {
@ -48,7 +49,7 @@ function UnaryExpression(node) {
} else { } else {
this.token(operator); this.token(operator);
} }
this.print(node.argument, node); this.print(node.argument);
} }
function DoExpression(node) { function DoExpression(node) {
if (node.async) { if (node.async) {
@ -57,55 +58,62 @@ function DoExpression(node) {
} }
this.word("do"); this.word("do");
this.space(); this.space();
this.print(node.body, node); this.print(node.body);
} }
function ParenthesizedExpression(node) { function ParenthesizedExpression(node) {
this.tokenChar(40); this.tokenChar(40);
this.print(node.expression, node); const exit = this.enterDelimited();
this.print(node.expression);
exit();
this.rightParens(node); this.rightParens(node);
} }
function UpdateExpression(node) { function UpdateExpression(node) {
if (node.prefix) { if (node.prefix) {
this.token(node.operator); this.token(node.operator);
this.print(node.argument, node); this.print(node.argument);
} else { } else {
this.printTerminatorless(node.argument, node, true); this.print(node.argument, true);
this.token(node.operator); this.token(node.operator);
} }
} }
function ConditionalExpression(node) { function ConditionalExpression(node) {
this.print(node.test, node); this.print(node.test);
this.space(); this.space();
this.tokenChar(63); this.tokenChar(63);
this.space(); this.space();
this.print(node.consequent, node); this.print(node.consequent);
this.space(); this.space();
this.tokenChar(58); this.tokenChar(58);
this.space(); this.space();
this.print(node.alternate, node); this.print(node.alternate);
} }
function NewExpression(node, parent) { function NewExpression(node, parent) {
this.word("new"); this.word("new");
this.space(); this.space();
this.print(node.callee, node); this.print(node.callee);
if (this.format.minified && node.arguments.length === 0 && !node.optional && !isCallExpression(parent, { if (this.format.minified && node.arguments.length === 0 && !node.optional && !isCallExpression(parent, {
callee: node callee: node
}) && !isMemberExpression(parent) && !isNewExpression(parent)) { }) && !isMemberExpression(parent) && !isNewExpression(parent)) {
return; return;
} }
this.print(node.typeArguments, node); this.print(node.typeArguments);
this.print(node.typeParameters, node); this.print(node.typeParameters);
if (node.optional) { if (node.optional) {
this.token("?."); this.token("?.");
} }
if (node.arguments.length === 0 && this.tokenMap && !this.tokenMap.endMatches(node, ")")) {
return;
}
this.tokenChar(40); this.tokenChar(40);
const exit = this.enterForStatementInit(false); const exit = this.enterDelimited();
this.printList(node.arguments, node); this.printList(node.arguments, {
printTrailingSeparator: this.shouldPrintTrailingComma(")")
});
exit(); exit();
this.rightParens(node); this.rightParens(node);
} }
function SequenceExpression(node) { function SequenceExpression(node) {
this.printList(node.expressions, node); this.printList(node.expressions);
} }
function ThisExpression() { function ThisExpression() {
this.word("this"); this.word("this");
@ -121,7 +129,7 @@ function _shouldPrintDecoratorsBeforeExport(node) {
} }
function Decorator(node) { function Decorator(node) {
this.tokenChar(64); this.tokenChar(64);
this.print(node.expression, node); this.print(node.expression);
this.newline(); this.newline();
} }
function OptionalMemberExpression(node) { function OptionalMemberExpression(node) {
@ -132,7 +140,7 @@ function OptionalMemberExpression(node) {
optional, optional,
property property
} = node; } = node;
this.print(node.object, node); this.print(node.object);
if (!computed && isMemberExpression(property)) { if (!computed && isMemberExpression(property)) {
throw new TypeError("Got a MemberExpression for MemberExpression property"); throw new TypeError("Got a MemberExpression for MemberExpression property");
} }
@ -144,35 +152,37 @@ function OptionalMemberExpression(node) {
} }
if (computed) { if (computed) {
this.tokenChar(91); this.tokenChar(91);
this.print(property, node); this.print(property);
this.tokenChar(93); this.tokenChar(93);
} else { } else {
if (!optional) { if (!optional) {
this.tokenChar(46); this.tokenChar(46);
} }
this.print(property, node); this.print(property);
} }
} }
function OptionalCallExpression(node) { function OptionalCallExpression(node) {
this.print(node.callee, node); this.print(node.callee);
this.print(node.typeParameters, node); this.print(node.typeParameters);
if (node.optional) { if (node.optional) {
this.token("?."); this.token("?.");
} }
this.print(node.typeArguments, node); this.print(node.typeArguments);
this.tokenChar(40); this.tokenChar(40);
const exit = this.enterForStatementInit(false); const exit = this.enterDelimited();
this.printList(node.arguments, node); this.printList(node.arguments);
exit(); exit();
this.rightParens(node); this.rightParens(node);
} }
function CallExpression(node) { function CallExpression(node) {
this.print(node.callee, node); this.print(node.callee);
this.print(node.typeArguments, node); this.print(node.typeArguments);
this.print(node.typeParameters, node); this.print(node.typeParameters);
this.tokenChar(40); this.tokenChar(40);
const exit = this.enterForStatementInit(false); const exit = this.enterDelimited();
this.printList(node.arguments, node); this.printList(node.arguments, {
printTrailingSeparator: this.shouldPrintTrailingComma(")")
});
exit(); exit();
this.rightParens(node); this.rightParens(node);
} }
@ -183,7 +193,7 @@ function AwaitExpression(node) {
this.word("await"); this.word("await");
if (node.argument) { if (node.argument) {
this.space(); this.space();
this.printTerminatorless(node.argument, node, false); this.printTerminatorless(node.argument);
} }
} }
function YieldExpression(node) { function YieldExpression(node) {
@ -192,12 +202,12 @@ function YieldExpression(node) {
this.tokenChar(42); this.tokenChar(42);
if (node.argument) { if (node.argument) {
this.space(); this.space();
this.print(node.argument, node); this.print(node.argument);
} }
} else { } else {
if (node.argument) { if (node.argument) {
this.space(); this.space();
this.printTerminatorless(node.argument, node, false); this.printTerminatorless(node.argument);
} }
} }
} }
@ -206,38 +216,39 @@ function EmptyStatement() {
} }
function ExpressionStatement(node) { function ExpressionStatement(node) {
this.tokenContext |= _index.TokenContext.expressionStatement; this.tokenContext |= _index.TokenContext.expressionStatement;
this.print(node.expression, node); this.print(node.expression);
this.semicolon(); this.semicolon();
} }
function AssignmentPattern(node) { function AssignmentPattern(node) {
this.print(node.left, node); this.print(node.left);
if (node.left.type === "Identifier") { if (node.left.type === "Identifier" || isPattern(node.left)) {
if (node.left.optional) this.tokenChar(63); if (node.left.optional) this.tokenChar(63);
this.print(node.left.typeAnnotation, node); this.print(node.left.typeAnnotation);
} }
this.space(); this.space();
this.tokenChar(61); this.tokenChar(61);
this.space(); this.space();
this.print(node.right, node); this.print(node.right);
} }
function AssignmentExpression(node) { function AssignmentExpression(node) {
this.print(node.left, node); this.print(node.left);
this.space(); this.space();
if (node.operator === "in" || node.operator === "instanceof") { if (node.operator === "in" || node.operator === "instanceof") {
this.word(node.operator); this.word(node.operator);
} else { } else {
this.token(node.operator); this.token(node.operator);
this._endsWithDiv = node.operator === "/";
} }
this.space(); this.space();
this.print(node.right, node); this.print(node.right);
} }
function BindExpression(node) { function BindExpression(node) {
this.print(node.object, node); this.print(node.object);
this.token("::"); this.token("::");
this.print(node.callee, node); this.print(node.callee);
} }
function MemberExpression(node) { function MemberExpression(node) {
this.print(node.object, node); this.print(node.object);
if (!node.computed && isMemberExpression(node.property)) { if (!node.computed && isMemberExpression(node.property)) {
throw new TypeError("Got a MemberExpression for MemberExpression property"); throw new TypeError("Got a MemberExpression for MemberExpression property");
} }
@ -246,24 +257,24 @@ function MemberExpression(node) {
computed = true; computed = true;
} }
if (computed) { if (computed) {
const exit = this.enterForStatementInit(false); const exit = this.enterDelimited();
this.tokenChar(91); this.tokenChar(91);
this.print(node.property, node); this.print(node.property);
this.tokenChar(93); this.tokenChar(93);
exit(); exit();
} else { } else {
this.tokenChar(46); this.tokenChar(46);
this.print(node.property, node); this.print(node.property);
} }
} }
function MetaProperty(node) { function MetaProperty(node) {
this.print(node.meta, node); this.print(node.meta);
this.tokenChar(46); this.tokenChar(46);
this.print(node.property, node); this.print(node.property);
} }
function PrivateName(node) { function PrivateName(node) {
this.tokenChar(35); this.tokenChar(35);
this.print(node.id, node); this.print(node.id);
} }
function V8IntrinsicIdentifier(node) { function V8IntrinsicIdentifier(node) {
this.tokenChar(37); this.tokenChar(37);
@ -280,7 +291,7 @@ function ModuleExpression(node) {
if (body.body.length || body.directives.length) { if (body.body.length || body.directives.length) {
this.newline(); this.newline();
} }
this.print(body, node); this.print(body);
this.dedent(); this.dedent();
this.rightBrace(node); this.rightBrace(node);
} }

File diff suppressed because one or more lines are too long

View File

@ -89,7 +89,7 @@ function AnyTypeAnnotation() {
this.word("any"); this.word("any");
} }
function ArrayTypeAnnotation(node) { function ArrayTypeAnnotation(node) {
this.print(node.elementType, node, true); this.print(node.elementType, true);
this.tokenChar(91); this.tokenChar(91);
this.tokenChar(93); this.tokenChar(93);
} }
@ -118,11 +118,11 @@ function DeclareFunction(node, parent) {
} }
this.word("function"); this.word("function");
this.space(); this.space();
this.print(node.id, node); this.print(node.id);
this.print(node.id.typeAnnotation.typeAnnotation, node); this.print(node.id.typeAnnotation.typeAnnotation);
if (node.predicate) { if (node.predicate) {
this.space(); this.space();
this.print(node.predicate, node); this.print(node.predicate);
} }
this.semicolon(); this.semicolon();
} }
@ -134,7 +134,7 @@ function DeclaredPredicate(node) {
this.tokenChar(37); this.tokenChar(37);
this.word("checks"); this.word("checks");
this.tokenChar(40); this.tokenChar(40);
this.print(node.value, node); this.print(node.value);
this.tokenChar(41); this.tokenChar(41);
} }
function DeclareInterface(node) { function DeclareInterface(node) {
@ -147,9 +147,9 @@ function DeclareModule(node) {
this.space(); this.space();
this.word("module"); this.word("module");
this.space(); this.space();
this.print(node.id, node); this.print(node.id);
this.space(); this.space();
this.print(node.body, node); this.print(node.body);
} }
function DeclareModuleExports(node) { function DeclareModuleExports(node) {
this.word("declare"); this.word("declare");
@ -157,7 +157,7 @@ function DeclareModuleExports(node) {
this.word("module"); this.word("module");
this.tokenChar(46); this.tokenChar(46);
this.word("exports"); this.word("exports");
this.print(node.typeAnnotation, node); this.print(node.typeAnnotation);
} }
function DeclareTypeAlias(node) { function DeclareTypeAlias(node) {
this.word("declare"); this.word("declare");
@ -178,8 +178,8 @@ function DeclareVariable(node, parent) {
} }
this.word("var"); this.word("var");
this.space(); this.space();
this.print(node.id, node); this.print(node.id);
this.print(node.id.typeAnnotation, node); this.print(node.id.typeAnnotation);
this.semicolon(); this.semicolon();
} }
function DeclareExportDeclaration(node) { function DeclareExportDeclaration(node) {
@ -205,8 +205,8 @@ function EnumDeclaration(node) {
} = node; } = node;
this.word("enum"); this.word("enum");
this.space(); this.space();
this.print(id, node); this.print(id);
this.print(body, node); this.print(body);
} }
function enumExplicitType(context, name, hasExplicitType) { function enumExplicitType(context, name, hasExplicitType) {
if (hasExplicitType) { if (hasExplicitType) {
@ -225,7 +225,7 @@ function enumBody(context, node) {
context.indent(); context.indent();
context.newline(); context.newline();
for (const member of members) { for (const member of members) {
context.print(member, node); context.print(member);
context.newline(); context.newline();
} }
if (node.hasUnknownMembers) { if (node.hasUnknownMembers) {
@ -264,19 +264,15 @@ function EnumDefaultedMember(node) {
const { const {
id id
} = node; } = node;
this.print(id, node); this.print(id);
this.tokenChar(44); this.tokenChar(44);
} }
function enumInitializedMember(context, node) { function enumInitializedMember(context, node) {
const { context.print(node.id);
id,
init
} = node;
context.print(id, node);
context.space(); context.space();
context.token("="); context.token("=");
context.space(); context.space();
context.print(init, node); context.print(node.init);
context.token(","); context.token(",");
} }
function EnumBooleanMember(node) { function EnumBooleanMember(node) {
@ -291,13 +287,13 @@ function EnumStringMember(node) {
function FlowExportDeclaration(node) { function FlowExportDeclaration(node) {
if (node.declaration) { if (node.declaration) {
const declar = node.declaration; const declar = node.declaration;
this.print(declar, node); this.print(declar);
if (!isStatement(declar)) this.semicolon(); if (!isStatement(declar)) this.semicolon();
} else { } else {
this.tokenChar(123); this.tokenChar(123);
if (node.specifiers.length) { if (node.specifiers.length) {
this.space(); this.space();
this.printList(node.specifiers, node); this.printList(node.specifiers);
this.space(); this.space();
} }
this.tokenChar(125); this.tokenChar(125);
@ -305,7 +301,7 @@ function FlowExportDeclaration(node) {
this.space(); this.space();
this.word("from"); this.word("from");
this.space(); this.space();
this.print(node.source, node); this.print(node.source);
} }
this.semicolon(); this.semicolon();
} }
@ -314,26 +310,26 @@ function ExistsTypeAnnotation() {
this.tokenChar(42); this.tokenChar(42);
} }
function FunctionTypeAnnotation(node, parent) { function FunctionTypeAnnotation(node, parent) {
this.print(node.typeParameters, node); this.print(node.typeParameters);
this.tokenChar(40); this.tokenChar(40);
if (node.this) { if (node.this) {
this.word("this"); this.word("this");
this.tokenChar(58); this.tokenChar(58);
this.space(); this.space();
this.print(node.this.typeAnnotation, node); this.print(node.this.typeAnnotation);
if (node.params.length || node.rest) { if (node.params.length || node.rest) {
this.tokenChar(44); this.tokenChar(44);
this.space(); this.space();
} }
} }
this.printList(node.params, node); this.printList(node.params);
if (node.rest) { if (node.rest) {
if (node.params.length) { if (node.params.length) {
this.tokenChar(44); this.tokenChar(44);
this.space(); this.space();
} }
this.token("..."); this.token("...");
this.print(node.rest, node); this.print(node.rest);
} }
this.tokenChar(41); this.tokenChar(41);
const type = parent == null ? void 0 : parent.type; const type = parent == null ? void 0 : parent.type;
@ -344,30 +340,30 @@ function FunctionTypeAnnotation(node, parent) {
this.token("=>"); this.token("=>");
} }
this.space(); this.space();
this.print(node.returnType, node); this.print(node.returnType);
} }
function FunctionTypeParam(node) { function FunctionTypeParam(node) {
this.print(node.name, node); this.print(node.name);
if (node.optional) this.tokenChar(63); if (node.optional) this.tokenChar(63);
if (node.name) { if (node.name) {
this.tokenChar(58); this.tokenChar(58);
this.space(); this.space();
} }
this.print(node.typeAnnotation, node); this.print(node.typeAnnotation);
} }
function InterfaceExtends(node) { function InterfaceExtends(node) {
this.print(node.id, node); this.print(node.id);
this.print(node.typeParameters, node, true); this.print(node.typeParameters, true);
} }
function _interfaceish(node) { function _interfaceish(node) {
var _node$extends; var _node$extends;
this.print(node.id, node); this.print(node.id);
this.print(node.typeParameters, node); this.print(node.typeParameters);
if ((_node$extends = node.extends) != null && _node$extends.length) { if ((_node$extends = node.extends) != null && _node$extends.length) {
this.space(); this.space();
this.word("extends"); this.word("extends");
this.space(); this.space();
this.printList(node.extends, node); this.printList(node.extends);
} }
if (node.type === "DeclareClass") { if (node.type === "DeclareClass") {
var _node$mixins, _node$implements; var _node$mixins, _node$implements;
@ -375,17 +371,17 @@ function _interfaceish(node) {
this.space(); this.space();
this.word("mixins"); this.word("mixins");
this.space(); this.space();
this.printList(node.mixins, node); this.printList(node.mixins);
} }
if ((_node$implements = node.implements) != null && _node$implements.length) { if ((_node$implements = node.implements) != null && _node$implements.length) {
this.space(); this.space();
this.word("implements"); this.word("implements");
this.space(); this.space();
this.printList(node.implements, node); this.printList(node.implements);
} }
} }
this.space(); this.space();
this.print(node.body, node); this.print(node.body);
} }
function _variance(node) { function _variance(node) {
var _node$variance; var _node$variance;
@ -403,9 +399,9 @@ function InterfaceDeclaration(node) {
this.space(); this.space();
this._interfaceish(node); this._interfaceish(node);
} }
function andSeparator() { function andSeparator(occurrenceCount) {
this.space(); this.space();
this.tokenChar(38); this.token("&", false, occurrenceCount);
this.space(); this.space();
} }
function InterfaceTypeAnnotation(node) { function InterfaceTypeAnnotation(node) {
@ -415,13 +411,13 @@ function InterfaceTypeAnnotation(node) {
this.space(); this.space();
this.word("extends"); this.word("extends");
this.space(); this.space();
this.printList(node.extends, node); this.printList(node.extends);
} }
this.space(); this.space();
this.print(node.body, node); this.print(node.body);
} }
function IntersectionTypeAnnotation(node) { function IntersectionTypeAnnotation(node) {
this.printJoin(node.types, node, { this.printJoin(node.types, {
separator: andSeparator separator: andSeparator
}); });
} }
@ -433,7 +429,7 @@ function EmptyTypeAnnotation() {
} }
function NullableTypeAnnotation(node) { function NullableTypeAnnotation(node) {
this.tokenChar(63); this.tokenChar(63);
this.print(node.typeAnnotation, node); this.print(node.typeAnnotation);
} }
function NumberTypeAnnotation() { function NumberTypeAnnotation() {
this.word("number"); this.word("number");
@ -446,23 +442,23 @@ function ThisTypeAnnotation() {
} }
function TupleTypeAnnotation(node) { function TupleTypeAnnotation(node) {
this.tokenChar(91); this.tokenChar(91);
this.printList(node.types, node); this.printList(node.types);
this.tokenChar(93); this.tokenChar(93);
} }
function TypeofTypeAnnotation(node) { function TypeofTypeAnnotation(node) {
this.word("typeof"); this.word("typeof");
this.space(); this.space();
this.print(node.argument, node); this.print(node.argument);
} }
function TypeAlias(node) { function TypeAlias(node) {
this.word("type"); this.word("type");
this.space(); this.space();
this.print(node.id, node); this.print(node.id);
this.print(node.typeParameters, node); this.print(node.typeParameters);
this.space(); this.space();
this.tokenChar(61); this.tokenChar(61);
this.space(); this.space();
this.print(node.right, node); this.print(node.right);
this.semicolon(); this.semicolon();
} }
function TypeAnnotation(node, parent) { function TypeAnnotation(node, parent) {
@ -473,24 +469,24 @@ function TypeAnnotation(node, parent) {
} else if (node.optional) { } else if (node.optional) {
this.tokenChar(63); this.tokenChar(63);
} }
this.print(node.typeAnnotation, node); this.print(node.typeAnnotation);
} }
function TypeParameterInstantiation(node) { function TypeParameterInstantiation(node) {
this.tokenChar(60); this.tokenChar(60);
this.printList(node.params, node, {}); this.printList(node.params, {});
this.tokenChar(62); this.tokenChar(62);
} }
function TypeParameter(node) { function TypeParameter(node) {
this._variance(node); this._variance(node);
this.word(node.name); this.word(node.name);
if (node.bound) { if (node.bound) {
this.print(node.bound, node); this.print(node.bound);
} }
if (node.default) { if (node.default) {
this.space(); this.space();
this.tokenChar(61); this.tokenChar(61);
this.space(); this.space();
this.print(node.default, node); this.print(node.default);
} }
} }
function OpaqueType(node) { function OpaqueType(node) {
@ -498,18 +494,18 @@ function OpaqueType(node) {
this.space(); this.space();
this.word("type"); this.word("type");
this.space(); this.space();
this.print(node.id, node); this.print(node.id);
this.print(node.typeParameters, node); this.print(node.typeParameters);
if (node.supertype) { if (node.supertype) {
this.tokenChar(58); this.tokenChar(58);
this.space(); this.space();
this.print(node.supertype, node); this.print(node.supertype);
} }
if (node.impltype) { if (node.impltype) {
this.space(); this.space();
this.tokenChar(61); this.tokenChar(61);
this.space(); this.space();
this.print(node.impltype, node); this.print(node.impltype);
} }
this.semicolon(); this.semicolon();
} }
@ -523,7 +519,7 @@ function ObjectTypeAnnotation(node) {
if (props.length) { if (props.length) {
this.newline(); this.newline();
this.space(); this.space();
this.printJoin(props, node, { this.printJoin(props, {
addNewlines(leading) { addNewlines(leading) {
if (leading && !props[0]) return 1; if (leading && !props[0]) return 1;
}, },
@ -559,7 +555,7 @@ function ObjectTypeInternalSlot(node) {
} }
this.tokenChar(91); this.tokenChar(91);
this.tokenChar(91); this.tokenChar(91);
this.print(node.id, node); this.print(node.id);
this.tokenChar(93); this.tokenChar(93);
this.tokenChar(93); this.tokenChar(93);
if (node.optional) this.tokenChar(63); if (node.optional) this.tokenChar(63);
@ -567,14 +563,14 @@ function ObjectTypeInternalSlot(node) {
this.tokenChar(58); this.tokenChar(58);
this.space(); this.space();
} }
this.print(node.value, node); this.print(node.value);
} }
function ObjectTypeCallProperty(node) { function ObjectTypeCallProperty(node) {
if (node.static) { if (node.static) {
this.word("static"); this.word("static");
this.space(); this.space();
} }
this.print(node.value, node); this.print(node.value);
} }
function ObjectTypeIndexer(node) { function ObjectTypeIndexer(node) {
if (node.static) { if (node.static) {
@ -584,15 +580,15 @@ function ObjectTypeIndexer(node) {
this._variance(node); this._variance(node);
this.tokenChar(91); this.tokenChar(91);
if (node.id) { if (node.id) {
this.print(node.id, node); this.print(node.id);
this.tokenChar(58); this.tokenChar(58);
this.space(); this.space();
} }
this.print(node.key, node); this.print(node.key);
this.tokenChar(93); this.tokenChar(93);
this.tokenChar(58); this.tokenChar(58);
this.space(); this.space();
this.print(node.value, node); this.print(node.value);
} }
function ObjectTypeProperty(node) { function ObjectTypeProperty(node) {
if (node.proto) { if (node.proto) {
@ -608,40 +604,40 @@ function ObjectTypeProperty(node) {
this.space(); this.space();
} }
this._variance(node); this._variance(node);
this.print(node.key, node); this.print(node.key);
if (node.optional) this.tokenChar(63); if (node.optional) this.tokenChar(63);
if (!node.method) { if (!node.method) {
this.tokenChar(58); this.tokenChar(58);
this.space(); this.space();
} }
this.print(node.value, node); this.print(node.value);
} }
function ObjectTypeSpreadProperty(node) { function ObjectTypeSpreadProperty(node) {
this.token("..."); this.token("...");
this.print(node.argument, node); this.print(node.argument);
} }
function QualifiedTypeIdentifier(node) { function QualifiedTypeIdentifier(node) {
this.print(node.qualification, node); this.print(node.qualification);
this.tokenChar(46); this.tokenChar(46);
this.print(node.id, node); this.print(node.id);
} }
function SymbolTypeAnnotation() { function SymbolTypeAnnotation() {
this.word("symbol"); this.word("symbol");
} }
function orSeparator() { function orSeparator(occurrenceCount) {
this.space(); this.space();
this.tokenChar(124); this.token("|", false, occurrenceCount);
this.space(); this.space();
} }
function UnionTypeAnnotation(node) { function UnionTypeAnnotation(node) {
this.printJoin(node.types, node, { this.printJoin(node.types, {
separator: orSeparator separator: orSeparator
}); });
} }
function TypeCastExpression(node) { function TypeCastExpression(node) {
this.tokenChar(40); this.tokenChar(40);
this.print(node.expression, node); this.print(node.expression);
this.print(node.typeAnnotation, node); this.print(node.typeAnnotation);
this.tokenChar(41); this.tokenChar(41);
} }
function Variance(node) { function Variance(node) {
@ -655,18 +651,18 @@ function VoidTypeAnnotation() {
this.word("void"); this.word("void");
} }
function IndexedAccessType(node) { function IndexedAccessType(node) {
this.print(node.objectType, node, true); this.print(node.objectType, true);
this.tokenChar(91); this.tokenChar(91);
this.print(node.indexType, node); this.print(node.indexType);
this.tokenChar(93); this.tokenChar(93);
} }
function OptionalIndexedAccessType(node) { function OptionalIndexedAccessType(node) {
this.print(node.objectType, node); this.print(node.objectType);
if (node.optional) { if (node.optional) {
this.token("?."); this.token("?.");
} }
this.tokenChar(91); this.tokenChar(91);
this.print(node.indexType, node); this.print(node.indexType);
this.tokenChar(93); this.tokenChar(93);
} }

File diff suppressed because one or more lines are too long

View File

@ -19,41 +19,41 @@ exports.JSXSpreadAttribute = JSXSpreadAttribute;
exports.JSXSpreadChild = JSXSpreadChild; exports.JSXSpreadChild = JSXSpreadChild;
exports.JSXText = JSXText; exports.JSXText = JSXText;
function JSXAttribute(node) { function JSXAttribute(node) {
this.print(node.name, node); this.print(node.name);
if (node.value) { if (node.value) {
this.tokenChar(61); this.tokenChar(61);
this.print(node.value, node); this.print(node.value);
} }
} }
function JSXIdentifier(node) { function JSXIdentifier(node) {
this.word(node.name); this.word(node.name);
} }
function JSXNamespacedName(node) { function JSXNamespacedName(node) {
this.print(node.namespace, node); this.print(node.namespace);
this.tokenChar(58); this.tokenChar(58);
this.print(node.name, node); this.print(node.name);
} }
function JSXMemberExpression(node) { function JSXMemberExpression(node) {
this.print(node.object, node); this.print(node.object);
this.tokenChar(46); this.tokenChar(46);
this.print(node.property, node); this.print(node.property);
} }
function JSXSpreadAttribute(node) { function JSXSpreadAttribute(node) {
this.tokenChar(123); this.tokenChar(123);
this.token("..."); this.token("...");
this.print(node.argument, node); this.print(node.argument);
this.tokenChar(125); this.rightBrace(node);
} }
function JSXExpressionContainer(node) { function JSXExpressionContainer(node) {
this.tokenChar(123); this.tokenChar(123);
this.print(node.expression, node); this.print(node.expression);
this.tokenChar(125); this.rightBrace(node);
} }
function JSXSpreadChild(node) { function JSXSpreadChild(node) {
this.tokenChar(123); this.tokenChar(123);
this.token("..."); this.token("...");
this.print(node.expression, node); this.print(node.expression);
this.tokenChar(125); this.rightBrace(node);
} }
function JSXText(node) { function JSXText(node) {
const raw = this.getPossibleRaw(node); const raw = this.getPossibleRaw(node);
@ -65,51 +65,51 @@ function JSXText(node) {
} }
function JSXElement(node) { function JSXElement(node) {
const open = node.openingElement; const open = node.openingElement;
this.print(open, node); this.print(open);
if (open.selfClosing) return; if (open.selfClosing) return;
this.indent(); this.indent();
for (const child of node.children) { for (const child of node.children) {
this.print(child, node); this.print(child);
} }
this.dedent(); this.dedent();
this.print(node.closingElement, node); this.print(node.closingElement);
} }
function spaceSeparator() { function spaceSeparator() {
this.space(); this.space();
} }
function JSXOpeningElement(node) { function JSXOpeningElement(node) {
this.tokenChar(60); this.tokenChar(60);
this.print(node.name, node); this.print(node.name);
this.print(node.typeParameters, node); this.print(node.typeParameters);
if (node.attributes.length > 0) { if (node.attributes.length > 0) {
this.space(); this.space();
this.printJoin(node.attributes, node, { this.printJoin(node.attributes, {
separator: spaceSeparator separator: spaceSeparator
}); });
} }
if (node.selfClosing) { if (node.selfClosing) {
this.space(); this.space();
this.token("/>"); this.tokenChar(47);
} else { }
this.tokenChar(62); this.tokenChar(62);
} }
}
function JSXClosingElement(node) { function JSXClosingElement(node) {
this.token("</"); this.tokenChar(60);
this.print(node.name, node); this.tokenChar(47);
this.print(node.name);
this.tokenChar(62); this.tokenChar(62);
} }
function JSXEmptyExpression() { function JSXEmptyExpression() {
this.printInnerComments(); this.printInnerComments();
} }
function JSXFragment(node) { function JSXFragment(node) {
this.print(node.openingFragment, node); this.print(node.openingFragment);
this.indent(); this.indent();
for (const child of node.children) { for (const child of node.children) {
this.print(child, node); this.print(child);
} }
this.dedent(); this.dedent();
this.print(node.closingFragment, node); this.print(node.closingFragment);
} }
function JSXOpeningFragment() { function JSXOpeningFragment() {
this.tokenChar(60); this.tokenChar(60);

File diff suppressed because one or more lines are too long

View File

@ -11,43 +11,45 @@ exports._param = _param;
exports._parameters = _parameters; exports._parameters = _parameters;
exports._params = _params; exports._params = _params;
exports._predicate = _predicate; exports._predicate = _predicate;
exports._shouldPrintArrowParamsParens = _shouldPrintArrowParamsParens;
var _t = require("@babel/types"); var _t = require("@babel/types");
var _index = require("../node/index.js"); var _index = require("../node/index.js");
const { const {
isIdentifier isIdentifier
} = _t; } = _t;
function _params(node, idNode, parentNode) { function _params(node, idNode, parentNode) {
this.print(node.typeParameters, node); this.print(node.typeParameters);
const nameInfo = _getFuncIdName.call(this, idNode, parentNode); const nameInfo = _getFuncIdName.call(this, idNode, parentNode);
if (nameInfo) { if (nameInfo) {
this.sourceIdentifierName(nameInfo.name, nameInfo.pos); this.sourceIdentifierName(nameInfo.name, nameInfo.pos);
} }
this.tokenChar(40); this.tokenChar(40);
this._parameters(node.params, node); this._parameters(node.params, ")");
this.tokenChar(41);
const noLineTerminator = node.type === "ArrowFunctionExpression"; const noLineTerminator = node.type === "ArrowFunctionExpression";
this.print(node.returnType, node, noLineTerminator); this.print(node.returnType, noLineTerminator);
this._noLineTerminator = noLineTerminator; this._noLineTerminator = noLineTerminator;
} }
function _parameters(parameters, parent) { function _parameters(parameters, endToken) {
const exit = this.enterForStatementInit(false); const exit = this.enterDelimited();
const trailingComma = this.shouldPrintTrailingComma(endToken);
const paramLength = parameters.length; const paramLength = parameters.length;
for (let i = 0; i < paramLength; i++) { for (let i = 0; i < paramLength; i++) {
this._param(parameters[i], parent); this._param(parameters[i]);
if (i < parameters.length - 1) { if (trailingComma || i < paramLength - 1) {
this.tokenChar(44); this.token(",", null, i);
this.space(); this.space();
} }
} }
this.token(endToken);
exit(); exit();
} }
function _param(parameter, parent) { function _param(parameter) {
this.printJoin(parameter.decorators, parameter); this.printJoin(parameter.decorators);
this.print(parameter, parent); this.print(parameter);
if (parameter.optional) { if (parameter.optional) {
this.tokenChar(63); this.tokenChar(63);
} }
this.print(parameter.typeAnnotation, parameter); this.print(parameter.typeAnnotation);
} }
function _methodHead(node) { function _methodHead(node) {
const kind = node.kind; const kind = node.kind;
@ -67,10 +69,10 @@ function _methodHead(node) {
} }
if (node.computed) { if (node.computed) {
this.tokenChar(91); this.tokenChar(91);
this.print(key, node); this.print(key);
this.tokenChar(93); this.tokenChar(93);
} else { } else {
this.print(key, node); this.print(key);
} }
if (node.optional) { if (node.optional) {
this.tokenChar(63); this.tokenChar(63);
@ -83,23 +85,27 @@ function _predicate(node, noLineTerminatorAfter) {
this.tokenChar(58); this.tokenChar(58);
} }
this.space(); this.space();
this.print(node.predicate, node, noLineTerminatorAfter); this.print(node.predicate, noLineTerminatorAfter);
} }
} }
function _functionHead(node, parent) { function _functionHead(node, parent) {
if (node.async) { if (node.async) {
this.word("async"); this.word("async");
if (!this.format.preserveFormat) {
this._endsWithInnerRaw = false; this._endsWithInnerRaw = false;
}
this.space(); this.space();
} }
this.word("function"); this.word("function");
if (node.generator) { if (node.generator) {
if (!this.format.preserveFormat) {
this._endsWithInnerRaw = false; this._endsWithInnerRaw = false;
}
this.tokenChar(42); this.tokenChar(42);
} }
this.space(); this.space();
if (node.id) { if (node.id) {
this.print(node.id, node); this.print(node.id);
} }
this._params(node, node.id, parent); this._params(node, node.id, parent);
if (node.type !== "TSDeclareFunction") { if (node.type !== "TSDeclareFunction") {
@ -109,18 +115,17 @@ function _functionHead(node, parent) {
function FunctionExpression(node, parent) { function FunctionExpression(node, parent) {
this._functionHead(node, parent); this._functionHead(node, parent);
this.space(); this.space();
this.print(node.body, node); this.print(node.body);
} }
function ArrowFunctionExpression(node, parent) { function ArrowFunctionExpression(node, parent) {
if (node.async) { if (node.async) {
this.word("async", true); this.word("async", true);
this.space(); this.space();
} }
let firstParam; if (this._shouldPrintArrowParamsParens(node)) {
if (!this.format.retainLines && node.params.length === 1 && isIdentifier(firstParam = node.params[0]) && !hasTypesOrComments(node, firstParam)) {
this.print(firstParam, node, true);
} else {
this._params(node, undefined, parent); this._params(node, undefined, parent);
} else {
this.print(node.params[0], true);
} }
this._predicate(node, true); this._predicate(node, true);
this.space(); this.space();
@ -128,11 +133,27 @@ function ArrowFunctionExpression(node, parent) {
this.token("=>"); this.token("=>");
this.space(); this.space();
this.tokenContext |= _index.TokenContext.arrowBody; this.tokenContext |= _index.TokenContext.arrowBody;
this.print(node.body, node); this.print(node.body);
} }
function hasTypesOrComments(node, param) { function _shouldPrintArrowParamsParens(node) {
var _param$leadingComment, _param$trailingCommen; var _firstParam$leadingCo, _firstParam$trailingC;
return !!(node.typeParameters || node.returnType || node.predicate || param.typeAnnotation || param.optional || (_param$leadingComment = param.leadingComments) != null && _param$leadingComment.length || (_param$trailingCommen = param.trailingComments) != null && _param$trailingCommen.length); if (node.params.length !== 1) return true;
if (node.typeParameters || node.returnType || node.predicate) {
return true;
}
const firstParam = node.params[0];
if (!isIdentifier(firstParam) || firstParam.typeAnnotation || firstParam.optional || (_firstParam$leadingCo = firstParam.leadingComments) != null && _firstParam$leadingCo.length || (_firstParam$trailingC = firstParam.trailingComments) != null && _firstParam$trailingC.length) {
return true;
}
if (this.tokenMap) {
if (node.loc == null) return true;
if (this.tokenMap.findMatching(node, "(") !== null) return true;
const arrowToken = this.tokenMap.findMatching(node, "=>");
if ((arrowToken == null ? void 0 : arrowToken.loc) == null) return true;
return arrowToken.loc.start.line !== node.loc.start.line;
}
if (this.format.retainLines) return true;
return false;
} }
function _getFuncIdName(idNode, parent) { function _getFuncIdName(idNode, parent) {
let id = idNode; let id = idNode;

File diff suppressed because one or more lines are too long

View File

@ -31,31 +31,31 @@ function ImportSpecifier(node) {
this.word(node.importKind); this.word(node.importKind);
this.space(); this.space();
} }
this.print(node.imported, node); this.print(node.imported);
if (node.local && node.local.name !== node.imported.name) { if (node.local && node.local.name !== node.imported.name) {
this.space(); this.space();
this.word("as"); this.word("as");
this.space(); this.space();
this.print(node.local, node); this.print(node.local);
} }
} }
function ImportDefaultSpecifier(node) { function ImportDefaultSpecifier(node) {
this.print(node.local, node); this.print(node.local);
} }
function ExportDefaultSpecifier(node) { function ExportDefaultSpecifier(node) {
this.print(node.exported, node); this.print(node.exported);
} }
function ExportSpecifier(node) { function ExportSpecifier(node) {
if (node.exportKind === "type") { if (node.exportKind === "type") {
this.word("type"); this.word("type");
this.space(); this.space();
} }
this.print(node.local, node); this.print(node.local);
if (node.exported && node.local.name !== node.exported.name) { if (node.exported && node.local.name !== node.exported.name) {
this.space(); this.space();
this.word("as"); this.word("as");
this.space(); this.space();
this.print(node.exported, node); this.print(node.exported);
} }
} }
function ExportNamespaceSpecifier(node) { function ExportNamespaceSpecifier(node) {
@ -63,10 +63,10 @@ function ExportNamespaceSpecifier(node) {
this.space(); this.space();
this.word("as"); this.word("as");
this.space(); this.space();
this.print(node.exported, node); this.print(node.exported);
} }
let warningShown = false; let warningShown = false;
function _printAttributes(node) { function _printAttributes(node, hasPreviousBrace) {
const { const {
importAttributesKeyword importAttributesKeyword
} = this.format; } = this.format;
@ -88,14 +88,17 @@ Please specify the "importAttributesKeyword" generator option, whose value can b
this.word(useAssertKeyword ? "assert" : "with"); this.word(useAssertKeyword ? "assert" : "with");
this.space(); this.space();
if (!useAssertKeyword && importAttributesKeyword !== "with") { if (!useAssertKeyword && importAttributesKeyword !== "with") {
this.printList(attributes || assertions, node); this.printList(attributes || assertions);
return; return;
} }
this.tokenChar(123); const occurrenceCount = hasPreviousBrace ? 1 : 0;
this.token("{", null, occurrenceCount);
this.space(); this.space();
this.printList(attributes || assertions, node); this.printList(attributes || assertions, {
printTrailingSeparator: this.shouldPrintTrailingComma("}")
});
this.space(); this.space();
this.tokenChar(125); this.token("}", null, occurrenceCount);
} }
function ExportAllDeclaration(node) { function ExportAllDeclaration(node) {
var _node$attributes, _node$assertions; var _node$attributes, _node$assertions;
@ -110,17 +113,17 @@ function ExportAllDeclaration(node) {
this.word("from"); this.word("from");
this.space(); this.space();
if ((_node$attributes = node.attributes) != null && _node$attributes.length || (_node$assertions = node.assertions) != null && _node$assertions.length) { if ((_node$attributes = node.attributes) != null && _node$attributes.length || (_node$assertions = node.assertions) != null && _node$assertions.length) {
this.print(node.source, node, true); this.print(node.source, true);
this.space(); this.space();
this._printAttributes(node); this._printAttributes(node, false);
} else { } else {
this.print(node.source, node); this.print(node.source);
} }
this.semicolon(); this.semicolon();
} }
function maybePrintDecoratorsBeforeExport(printer, node) { function maybePrintDecoratorsBeforeExport(printer, node) {
if (isClassDeclaration(node.declaration) && printer._shouldPrintDecoratorsBeforeExport(node)) { if (isClassDeclaration(node.declaration) && printer._shouldPrintDecoratorsBeforeExport(node)) {
printer.printJoin(node.declaration.decorators, node); printer.printJoin(node.declaration.decorators);
} }
} }
function ExportNamedDeclaration(node) { function ExportNamedDeclaration(node) {
@ -129,7 +132,7 @@ function ExportNamedDeclaration(node) {
this.space(); this.space();
if (node.declaration) { if (node.declaration) {
const declar = node.declaration; const declar = node.declaration;
this.print(declar, node); this.print(declar);
if (!isStatement(declar)) this.semicolon(); if (!isStatement(declar)) this.semicolon();
} else { } else {
if (node.exportKind === "type") { if (node.exportKind === "type") {
@ -142,7 +145,7 @@ function ExportNamedDeclaration(node) {
const first = specifiers[0]; const first = specifiers[0];
if (isExportDefaultSpecifier(first) || isExportNamespaceSpecifier(first)) { if (isExportDefaultSpecifier(first) || isExportNamespaceSpecifier(first)) {
hasSpecial = true; hasSpecial = true;
this.print(specifiers.shift(), node); this.print(specifiers.shift());
if (specifiers.length) { if (specifiers.length) {
this.tokenChar(44); this.tokenChar(44);
this.space(); this.space();
@ -151,11 +154,15 @@ function ExportNamedDeclaration(node) {
break; break;
} }
} }
let hasBrace = false;
if (specifiers.length || !specifiers.length && !hasSpecial) { if (specifiers.length || !specifiers.length && !hasSpecial) {
hasBrace = true;
this.tokenChar(123); this.tokenChar(123);
if (specifiers.length) { if (specifiers.length) {
this.space(); this.space();
this.printList(specifiers, node); this.printList(specifiers, {
printTrailingSeparator: this.shouldPrintTrailingComma("}")
});
this.space(); this.space();
} }
this.tokenChar(125); this.tokenChar(125);
@ -166,11 +173,11 @@ function ExportNamedDeclaration(node) {
this.word("from"); this.word("from");
this.space(); this.space();
if ((_node$attributes2 = node.attributes) != null && _node$attributes2.length || (_node$assertions2 = node.assertions) != null && _node$assertions2.length) { if ((_node$attributes2 = node.attributes) != null && _node$attributes2.length || (_node$assertions2 = node.assertions) != null && _node$assertions2.length) {
this.print(node.source, node, true); this.print(node.source, true);
this.space(); this.space();
this._printAttributes(node); this._printAttributes(node, hasBrace);
} else { } else {
this.print(node.source, node); this.print(node.source);
} }
} }
this.semicolon(); this.semicolon();
@ -185,7 +192,7 @@ function ExportDefaultDeclaration(node) {
this.space(); this.space();
this.tokenContext |= _index.TokenContext.exportDefault; this.tokenContext |= _index.TokenContext.exportDefault;
const declar = node.declaration; const declar = node.declaration;
this.print(declar, node); this.print(declar);
if (!isStatement(declar)) this.semicolon(); if (!isStatement(declar)) this.semicolon();
} }
function ImportDeclaration(node) { function ImportDeclaration(node) {
@ -211,7 +218,7 @@ function ImportDeclaration(node) {
while (hasSpecifiers) { while (hasSpecifiers) {
const first = specifiers[0]; const first = specifiers[0];
if (isImportDefaultSpecifier(first) || isImportNamespaceSpecifier(first)) { if (isImportDefaultSpecifier(first) || isImportNamespaceSpecifier(first)) {
this.print(specifiers.shift(), node); this.print(specifiers.shift());
if (specifiers.length) { if (specifiers.length) {
this.tokenChar(44); this.tokenChar(44);
this.space(); this.space();
@ -220,13 +227,18 @@ function ImportDeclaration(node) {
break; break;
} }
} }
let hasBrace = false;
if (specifiers.length) { if (specifiers.length) {
hasBrace = true;
this.tokenChar(123); this.tokenChar(123);
this.space(); this.space();
this.printList(specifiers, node); this.printList(specifiers, {
printTrailingSeparator: this.shouldPrintTrailingComma("}")
});
this.space(); this.space();
this.tokenChar(125); this.tokenChar(125);
} else if (isTypeKind && !hasSpecifiers) { } else if (isTypeKind && !hasSpecifiers) {
hasBrace = true;
this.tokenChar(123); this.tokenChar(123);
this.tokenChar(125); this.tokenChar(125);
} }
@ -236,11 +248,11 @@ function ImportDeclaration(node) {
this.space(); this.space();
} }
if ((_node$attributes3 = node.attributes) != null && _node$attributes3.length || (_node$assertions3 = node.assertions) != null && _node$assertions3.length) { if ((_node$attributes3 = node.attributes) != null && _node$attributes3.length || (_node$assertions3 = node.assertions) != null && _node$assertions3.length) {
this.print(node.source, node, true); this.print(node.source, true);
this.space(); this.space();
this._printAttributes(node); this._printAttributes(node, hasBrace);
} else { } else {
this.print(node.source, node); this.print(node.source);
} }
this.semicolon(); this.semicolon();
} }
@ -255,7 +267,7 @@ function ImportNamespaceSpecifier(node) {
this.space(); this.space();
this.word("as"); this.word("as");
this.space(); this.space();
this.print(node.local, node); this.print(node.local);
} }
function ImportExpression(node) { function ImportExpression(node) {
this.word("import"); this.word("import");
@ -264,11 +276,11 @@ function ImportExpression(node) {
this.word(node.phase); this.word(node.phase);
} }
this.tokenChar(40); this.tokenChar(40);
this.print(node.source, node); this.print(node.source);
if (node.options != null) { if (node.options != null) {
this.tokenChar(44); this.tokenChar(44);
this.space(); this.space();
this.print(node.options, node); this.print(node.options);
} }
this.tokenChar(41); this.tokenChar(41);
} }

File diff suppressed because one or more lines are too long

View File

@ -33,7 +33,7 @@ function WithStatement(node) {
this.word("with"); this.word("with");
this.space(); this.space();
this.tokenChar(40); this.tokenChar(40);
this.print(node.object, node); this.print(node.object);
this.tokenChar(41); this.tokenChar(41);
this.printBlock(node); this.printBlock(node);
} }
@ -41,7 +41,7 @@ function IfStatement(node) {
this.word("if"); this.word("if");
this.space(); this.space();
this.tokenChar(40); this.tokenChar(40);
this.print(node.test, node); this.print(node.test);
this.tokenChar(41); this.tokenChar(41);
this.space(); this.space();
const needsBlock = node.alternate && isIfStatement(getLastStatement(node.consequent)); const needsBlock = node.alternate && isIfStatement(getLastStatement(node.consequent));
@ -50,7 +50,7 @@ function IfStatement(node) {
this.newline(); this.newline();
this.indent(); this.indent();
} }
this.printAndIndentOnComments(node.consequent, node); this.printAndIndentOnComments(node.consequent);
if (needsBlock) { if (needsBlock) {
this.dedent(); this.dedent();
this.newline(); this.newline();
@ -60,7 +60,7 @@ function IfStatement(node) {
if (this.endsWith(125)) this.space(); if (this.endsWith(125)) this.space();
this.word("else"); this.word("else");
this.space(); this.space();
this.printAndIndentOnComments(node.alternate, node); this.printAndIndentOnComments(node.alternate);
} }
} }
function getLastStatement(statement) { function getLastStatement(statement) {
@ -77,20 +77,20 @@ function ForStatement(node) {
this.space(); this.space();
this.tokenChar(40); this.tokenChar(40);
{ {
const exit = this.enterForStatementInit(true); const exit = this.enterForStatementInit();
this.tokenContext |= _index.TokenContext.forHead; this.tokenContext |= _index.TokenContext.forHead;
this.print(node.init, node); this.print(node.init);
exit(); exit();
} }
this.tokenChar(59); this.tokenChar(59);
if (node.test) { if (node.test) {
this.space(); this.space();
this.print(node.test, node); this.print(node.test);
} }
this.tokenChar(59); this.token(";", false, 1);
if (node.update) { if (node.update) {
this.space(); this.space();
this.print(node.update, node); this.print(node.update);
} }
this.tokenChar(41); this.tokenChar(41);
this.printBlock(node); this.printBlock(node);
@ -99,7 +99,7 @@ function WhileStatement(node) {
this.word("while"); this.word("while");
this.space(); this.space();
this.tokenChar(40); this.tokenChar(40);
this.print(node.test, node); this.print(node.test);
this.tokenChar(41); this.tokenChar(41);
this.printBlock(node); this.printBlock(node);
} }
@ -114,15 +114,15 @@ function ForXStatement(node) {
this.noIndentInnerCommentsHere(); this.noIndentInnerCommentsHere();
this.tokenChar(40); this.tokenChar(40);
{ {
const exit = isForOf ? null : this.enterForStatementInit(true); const exit = isForOf ? null : this.enterForStatementInit();
this.tokenContext |= isForOf ? _index.TokenContext.forOfHead : _index.TokenContext.forInHead; this.tokenContext |= isForOf ? _index.TokenContext.forOfHead : _index.TokenContext.forInHead;
this.print(node.left, node); this.print(node.left);
exit == null || exit(); exit == null || exit();
} }
this.space(); this.space();
this.word(isForOf ? "of" : "in"); this.word(isForOf ? "of" : "in");
this.space(); this.space();
this.print(node.right, node); this.print(node.right);
this.tokenChar(41); this.tokenChar(41);
this.printBlock(node); this.printBlock(node);
} }
@ -131,59 +131,59 @@ const ForOfStatement = exports.ForOfStatement = ForXStatement;
function DoWhileStatement(node) { function DoWhileStatement(node) {
this.word("do"); this.word("do");
this.space(); this.space();
this.print(node.body, node); this.print(node.body);
this.space(); this.space();
this.word("while"); this.word("while");
this.space(); this.space();
this.tokenChar(40); this.tokenChar(40);
this.print(node.test, node); this.print(node.test);
this.tokenChar(41); this.tokenChar(41);
this.semicolon(); this.semicolon();
} }
function printStatementAfterKeyword(printer, node, parent, isLabel) { function printStatementAfterKeyword(printer, node) {
if (node) { if (node) {
printer.space(); printer.space();
printer.printTerminatorless(node, parent, isLabel); printer.printTerminatorless(node);
} }
printer.semicolon(); printer.semicolon();
} }
function BreakStatement(node) { function BreakStatement(node) {
this.word("break"); this.word("break");
printStatementAfterKeyword(this, node.label, node, true); printStatementAfterKeyword(this, node.label);
} }
function ContinueStatement(node) { function ContinueStatement(node) {
this.word("continue"); this.word("continue");
printStatementAfterKeyword(this, node.label, node, true); printStatementAfterKeyword(this, node.label);
} }
function ReturnStatement(node) { function ReturnStatement(node) {
this.word("return"); this.word("return");
printStatementAfterKeyword(this, node.argument, node, false); printStatementAfterKeyword(this, node.argument);
} }
function ThrowStatement(node) { function ThrowStatement(node) {
this.word("throw"); this.word("throw");
printStatementAfterKeyword(this, node.argument, node, false); printStatementAfterKeyword(this, node.argument);
} }
function LabeledStatement(node) { function LabeledStatement(node) {
this.print(node.label, node); this.print(node.label);
this.tokenChar(58); this.tokenChar(58);
this.space(); this.space();
this.print(node.body, node); this.print(node.body);
} }
function TryStatement(node) { function TryStatement(node) {
this.word("try"); this.word("try");
this.space(); this.space();
this.print(node.block, node); this.print(node.block);
this.space(); this.space();
if (node.handlers) { if (node.handlers) {
this.print(node.handlers[0], node); this.print(node.handlers[0]);
} else { } else {
this.print(node.handler, node); this.print(node.handler);
} }
if (node.finalizer) { if (node.finalizer) {
this.space(); this.space();
this.word("finally"); this.word("finally");
this.space(); this.space();
this.print(node.finalizer, node); this.print(node.finalizer);
} }
} }
function CatchClause(node) { function CatchClause(node) {
@ -191,22 +191,22 @@ function CatchClause(node) {
this.space(); this.space();
if (node.param) { if (node.param) {
this.tokenChar(40); this.tokenChar(40);
this.print(node.param, node); this.print(node.param);
this.print(node.param.typeAnnotation, node); this.print(node.param.typeAnnotation);
this.tokenChar(41); this.tokenChar(41);
this.space(); this.space();
} }
this.print(node.body, node); this.print(node.body);
} }
function SwitchStatement(node) { function SwitchStatement(node) {
this.word("switch"); this.word("switch");
this.space(); this.space();
this.tokenChar(40); this.tokenChar(40);
this.print(node.discriminant, node); this.print(node.discriminant);
this.tokenChar(41); this.tokenChar(41);
this.space(); this.space();
this.tokenChar(123); this.tokenChar(123);
this.printSequence(node.cases, node, { this.printSequence(node.cases, {
indent: true, indent: true,
addNewlines(leading, cas) { addNewlines(leading, cas) {
if (!leading && node.cases[node.cases.length - 1] === cas) return -1; if (!leading && node.cases[node.cases.length - 1] === cas) return -1;
@ -218,7 +218,7 @@ function SwitchCase(node) {
if (node.test) { if (node.test) {
this.word("case"); this.word("case");
this.space(); this.space();
this.print(node.test, node); this.print(node.test);
this.tokenChar(58); this.tokenChar(58);
} else { } else {
this.word("default"); this.word("default");
@ -226,7 +226,7 @@ function SwitchCase(node) {
} }
if (node.consequent.length) { if (node.consequent.length) {
this.newline(); this.newline();
this.printSequence(node.consequent, node, { this.printSequence(node.consequent, {
indent: true indent: true
}); });
} }
@ -259,9 +259,9 @@ function VariableDeclaration(node, parent) {
} }
} }
} }
this.printList(node.declarations, node, { this.printList(node.declarations, {
separator: hasInits ? function () { separator: hasInits ? function (occurrenceCount) {
this.tokenChar(44); this.token(",", false, occurrenceCount);
this.newline(); this.newline();
} : undefined, } : undefined,
indent: node.declarations.length > 1 ? true : false indent: node.declarations.length > 1 ? true : false
@ -276,14 +276,14 @@ function VariableDeclaration(node, parent) {
this.semicolon(); this.semicolon();
} }
function VariableDeclarator(node) { function VariableDeclarator(node) {
this.print(node.id, node); this.print(node.id);
if (node.definite) this.tokenChar(33); if (node.definite) this.tokenChar(33);
this.print(node.id.typeAnnotation, node); this.print(node.id.typeAnnotation);
if (node.init) { if (node.init) {
this.space(); this.space();
this.tokenChar(61); this.tokenChar(61);
this.space(); this.space();
this.print(node.init, node); this.print(node.init);
} }
} }

File diff suppressed because one or more lines are too long

View File

@ -7,9 +7,9 @@ exports.TaggedTemplateExpression = TaggedTemplateExpression;
exports.TemplateElement = TemplateElement; exports.TemplateElement = TemplateElement;
exports.TemplateLiteral = TemplateLiteral; exports.TemplateLiteral = TemplateLiteral;
function TaggedTemplateExpression(node) { function TaggedTemplateExpression(node) {
this.print(node.tag, node); this.print(node.tag);
this.print(node.typeParameters, node); this.print(node.typeParameters);
this.print(node.quasi, node); this.print(node.quasi);
} }
function TemplateElement() { function TemplateElement() {
throw new Error("TemplateElement printing is handled in TemplateLiteral"); throw new Error("TemplateElement printing is handled in TemplateLiteral");
@ -21,8 +21,12 @@ function TemplateLiteral(node) {
partRaw += quasis[i].value.raw; partRaw += quasis[i].value.raw;
if (i + 1 < quasis.length) { if (i + 1 < quasis.length) {
this.token(partRaw + "${", true); this.token(partRaw + "${", true);
this.print(node.expressions[i], node); this.print(node.expressions[i]);
partRaw = "}"; partRaw = "}";
if (this.tokenMap) {
const token = this.tokenMap.findMatching(node, "}", i);
if (token) this._catchUpTo(token.loc.start);
}
} }
} }
this.token(partRaw + "`", true); this.token(partRaw + "`", true);

View File

@ -1 +1 @@
{"version":3,"names":["TaggedTemplateExpression","node","print","tag","typeParameters","quasi","TemplateElement","Error","TemplateLiteral","quasis","partRaw","i","length","value","raw","token","expressions"],"sources":["../../src/generators/template-literals.ts"],"sourcesContent":["import type Printer from \"../printer.ts\";\nimport type * as t from \"@babel/types\";\n\nexport function TaggedTemplateExpression(\n this: Printer,\n node: t.TaggedTemplateExpression,\n) {\n this.print(node.tag, node);\n this.print(node.typeParameters, node); // TS\n this.print(node.quasi, node);\n}\n\nexport function TemplateElement(this: Printer) {\n throw new Error(\"TemplateElement printing is handled in TemplateLiteral\");\n}\n\nexport function TemplateLiteral(this: Printer, node: t.TemplateLiteral) {\n const quasis = node.quasis;\n\n let partRaw = \"`\";\n\n for (let i = 0; i < quasis.length; i++) {\n partRaw += quasis[i].value.raw;\n\n if (i + 1 < quasis.length) {\n this.token(partRaw + \"${\", true);\n this.print(node.expressions[i], node);\n partRaw = \"}\";\n }\n }\n\n this.token(partRaw + \"`\", true);\n}\n"],"mappings":";;;;;;;;AAGO,SAASA,wBAAwBA,CAEtCC,IAAgC,EAChC;EACA,IAAI,CAACC,KAAK,CAACD,IAAI,CAACE,GAAG,EAAEF,IAAI,CAAC;EAC1B,IAAI,CAACC,KAAK,CAACD,IAAI,CAACG,cAAc,EAAEH,IAAI,CAAC;EACrC,IAAI,CAACC,KAAK,CAACD,IAAI,CAACI,KAAK,EAAEJ,IAAI,CAAC;AAC9B;AAEO,SAASK,eAAeA,CAAA,EAAgB;EAC7C,MAAM,IAAIC,KAAK,CAAC,wDAAwD,CAAC;AAC3E;AAEO,SAASC,eAAeA,CAAgBP,IAAuB,EAAE;EACtE,MAAMQ,MAAM,GAAGR,IAAI,CAACQ,MAAM;EAE1B,IAAIC,OAAO,GAAG,GAAG;EAEjB,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGF,MAAM,CAACG,MAAM,EAAED,CAAC,EAAE,EAAE;IACtCD,OAAO,IAAID,MAAM,CAACE,CAAC,CAAC,CAACE,KAAK,CAACC,GAAG;IAE9B,IAAIH,CAAC,GAAG,CAAC,GAAGF,MAAM,CAACG,MAAM,EAAE;MACzB,IAAI,CAACG,KAAK,CAACL,OAAO,GAAG,IAAI,EAAE,IAAI,CAAC;MAChC,IAAI,CAACR,KAAK,CAACD,IAAI,CAACe,WAAW,CAACL,CAAC,CAAC,EAAEV,IAAI,CAAC;MACrCS,OAAO,GAAG,GAAG;IACf;EACF;EAEA,IAAI,CAACK,KAAK,CAACL,OAAO,GAAG,GAAG,EAAE,IAAI,CAAC;AACjC","ignoreList":[]} {"version":3,"names":["TaggedTemplateExpression","node","print","tag","typeParameters","quasi","TemplateElement","Error","TemplateLiteral","quasis","partRaw","i","length","value","raw","token","expressions","tokenMap","findMatching","_catchUpTo","loc","start"],"sources":["../../src/generators/template-literals.ts"],"sourcesContent":["import type Printer from \"../printer.ts\";\nimport type * as t from \"@babel/types\";\n\nexport function TaggedTemplateExpression(\n this: Printer,\n node: t.TaggedTemplateExpression,\n) {\n this.print(node.tag);\n this.print(node.typeParameters); // TS\n this.print(node.quasi);\n}\n\nexport function TemplateElement(this: Printer) {\n throw new Error(\"TemplateElement printing is handled in TemplateLiteral\");\n}\n\nexport function TemplateLiteral(this: Printer, node: t.TemplateLiteral) {\n const quasis = node.quasis;\n\n let partRaw = \"`\";\n\n for (let i = 0; i < quasis.length; i++) {\n partRaw += quasis[i].value.raw;\n\n if (i + 1 < quasis.length) {\n this.token(partRaw + \"${\", true);\n this.print(node.expressions[i]);\n partRaw = \"}\";\n\n // In Babel 7 we have indivirual tokens for ${ and }, so the automatic\n // catchup logic does not work. Manually look for those tokens.\n if (!process.env.BABEL_8_BREAKING && this.tokenMap) {\n const token = this.tokenMap.findMatching(node, \"}\", i);\n if (token) this._catchUpTo(token.loc.start);\n }\n }\n }\n\n this.token(partRaw + \"`\", true);\n}\n"],"mappings":";;;;;;;;AAGO,SAASA,wBAAwBA,CAEtCC,IAAgC,EAChC;EACA,IAAI,CAACC,KAAK,CAACD,IAAI,CAACE,GAAG,CAAC;EACpB,IAAI,CAACD,KAAK,CAACD,IAAI,CAACG,cAAc,CAAC;EAC/B,IAAI,CAACF,KAAK,CAACD,IAAI,CAACI,KAAK,CAAC;AACxB;AAEO,SAASC,eAAeA,CAAA,EAAgB;EAC7C,MAAM,IAAIC,KAAK,CAAC,wDAAwD,CAAC;AAC3E;AAEO,SAASC,eAAeA,CAAgBP,IAAuB,EAAE;EACtE,MAAMQ,MAAM,GAAGR,IAAI,CAACQ,MAAM;EAE1B,IAAIC,OAAO,GAAG,GAAG;EAEjB,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGF,MAAM,CAACG,MAAM,EAAED,CAAC,EAAE,EAAE;IACtCD,OAAO,IAAID,MAAM,CAACE,CAAC,CAAC,CAACE,KAAK,CAACC,GAAG;IAE9B,IAAIH,CAAC,GAAG,CAAC,GAAGF,MAAM,CAACG,MAAM,EAAE;MACzB,IAAI,CAACG,KAAK,CAACL,OAAO,GAAG,IAAI,EAAE,IAAI,CAAC;MAChC,IAAI,CAACR,KAAK,CAACD,IAAI,CAACe,WAAW,CAACL,CAAC,CAAC,CAAC;MAC/BD,OAAO,GAAG,GAAG;MAIb,IAAqC,IAAI,CAACO,QAAQ,EAAE;QAClD,MAAMF,KAAK,GAAG,IAAI,CAACE,QAAQ,CAACC,YAAY,CAACjB,IAAI,EAAE,GAAG,EAAEU,CAAC,CAAC;QACtD,IAAII,KAAK,EAAE,IAAI,CAACI,UAAU,CAACJ,KAAK,CAACK,GAAG,CAACC,KAAK,CAAC;MAC7C;IACF;EACF;EAEA,IAAI,CAACN,KAAK,CAACL,OAAO,GAAG,GAAG,EAAE,IAAI,CAAC;AACjC","ignoreList":[]}

View File

@ -23,33 +23,50 @@ exports.SpreadElement = exports.RestElement = RestElement;
exports.StringLiteral = StringLiteral; exports.StringLiteral = StringLiteral;
exports.TopicReference = TopicReference; exports.TopicReference = TopicReference;
exports.TupleExpression = TupleExpression; exports.TupleExpression = TupleExpression;
exports._getRawIdentifier = _getRawIdentifier;
var _t = require("@babel/types"); var _t = require("@babel/types");
var _jsesc = require("jsesc"); var _jsesc = require("jsesc");
const { const {
isAssignmentPattern, isAssignmentPattern,
isIdentifier isIdentifier
} = _t; } = _t;
let lastRawIdentNode = null;
let lastRawIdentResult = "";
function _getRawIdentifier(node) {
if (node === lastRawIdentNode) return lastRawIdentResult;
lastRawIdentNode = node;
const {
name
} = node;
const token = this.tokenMap.find(node, tok => tok.value === name);
if (token) {
lastRawIdentResult = this._originalCode.slice(token.start, token.end);
return lastRawIdentResult;
}
return lastRawIdentResult = node.name;
}
function Identifier(node) { function Identifier(node) {
var _node$loc; var _node$loc;
this.sourceIdentifierName(((_node$loc = node.loc) == null ? void 0 : _node$loc.identifierName) || node.name); this.sourceIdentifierName(((_node$loc = node.loc) == null ? void 0 : _node$loc.identifierName) || node.name);
this.word(node.name); this.word(this.tokenMap ? this._getRawIdentifier(node) : node.name);
} }
function ArgumentPlaceholder() { function ArgumentPlaceholder() {
this.tokenChar(63); this.tokenChar(63);
} }
function RestElement(node) { function RestElement(node) {
this.token("..."); this.token("...");
this.print(node.argument, node); this.print(node.argument);
} }
function ObjectExpression(node) { function ObjectExpression(node) {
const props = node.properties; const props = node.properties;
this.tokenChar(123); this.tokenChar(123);
if (props.length) { if (props.length) {
const exit = this.enterForStatementInit(false); const exit = this.enterDelimited();
this.space(); this.space();
this.printList(props, node, { this.printList(props, {
indent: true, indent: true,
statement: true statement: true,
printTrailingSeparator: this.shouldPrintTrailingComma("}")
}); });
this.space(); this.space();
exit(); exit();
@ -58,44 +75,46 @@ function ObjectExpression(node) {
this.tokenChar(125); this.tokenChar(125);
} }
function ObjectMethod(node) { function ObjectMethod(node) {
this.printJoin(node.decorators, node); this.printJoin(node.decorators);
this._methodHead(node); this._methodHead(node);
this.space(); this.space();
this.print(node.body, node); this.print(node.body);
} }
function ObjectProperty(node) { function ObjectProperty(node) {
this.printJoin(node.decorators, node); this.printJoin(node.decorators);
if (node.computed) { if (node.computed) {
this.tokenChar(91); this.tokenChar(91);
this.print(node.key, node); this.print(node.key);
this.tokenChar(93); this.tokenChar(93);
} else { } else {
if (isAssignmentPattern(node.value) && isIdentifier(node.key) && node.key.name === node.value.left.name) { if (isAssignmentPattern(node.value) && isIdentifier(node.key) && node.key.name === node.value.left.name) {
this.print(node.value, node); this.print(node.value);
return; return;
} }
this.print(node.key, node); this.print(node.key);
if (node.shorthand && isIdentifier(node.key) && isIdentifier(node.value) && node.key.name === node.value.name) { if (node.shorthand && isIdentifier(node.key) && isIdentifier(node.value) && node.key.name === node.value.name) {
return; return;
} }
} }
this.tokenChar(58); this.tokenChar(58);
this.space(); this.space();
this.print(node.value, node); this.print(node.value);
} }
function ArrayExpression(node) { function ArrayExpression(node) {
const elems = node.elements; const elems = node.elements;
const len = elems.length; const len = elems.length;
this.tokenChar(91); this.tokenChar(91);
const exit = this.enterForStatementInit(false); const exit = this.enterDelimited();
for (let i = 0; i < elems.length; i++) { for (let i = 0; i < elems.length; i++) {
const elem = elems[i]; const elem = elems[i];
if (elem) { if (elem) {
if (i > 0) this.space(); if (i > 0) this.space();
this.print(elem, node); this.print(elem);
if (i < len - 1) this.tokenChar(44); if (i < len - 1 || this.shouldPrintTrailingComma("]")) {
this.token(",", false, i);
}
} else { } else {
this.tokenChar(44); this.token(",", false, i);
} }
} }
exit(); exit();
@ -119,9 +138,10 @@ function RecordExpression(node) {
this.token(startToken); this.token(startToken);
if (props.length) { if (props.length) {
this.space(); this.space();
this.printList(props, node, { this.printList(props, {
indent: true, indent: true,
statement: true statement: true,
printTrailingSeparator: this.shouldPrintTrailingComma(endToken)
}); });
this.space(); this.space();
} }
@ -148,8 +168,10 @@ function TupleExpression(node) {
const elem = elems[i]; const elem = elems[i];
if (elem) { if (elem) {
if (i > 0) this.space(); if (i > 0) this.space();
this.print(elem, node); this.print(elem);
if (i < len - 1) this.tokenChar(44); if (i < len - 1 || this.shouldPrintTrailingComma(endToken)) {
this.token(",", false, i);
}
} }
} }
this.token(endToken); this.token(endToken);
@ -217,10 +239,10 @@ function TopicReference() {
} }
} }
function PipelineTopicExpression(node) { function PipelineTopicExpression(node) {
this.print(node.expression, node); this.print(node.expression);
} }
function PipelineBareFunction(node) { function PipelineBareFunction(node) {
this.print(node.callee, node); this.print(node.callee);
} }
function PipelinePrimaryTopicReference() { function PipelinePrimaryTopicReference() {
this.tokenChar(35); this.tokenChar(35);

File diff suppressed because one or more lines are too long

View File

@ -9,6 +9,7 @@ exports.TSSatisfiesExpression = exports.TSAsExpression = TSTypeExpression;
exports.TSBigIntKeyword = TSBigIntKeyword; exports.TSBigIntKeyword = TSBigIntKeyword;
exports.TSBooleanKeyword = TSBooleanKeyword; exports.TSBooleanKeyword = TSBooleanKeyword;
exports.TSCallSignatureDeclaration = TSCallSignatureDeclaration; exports.TSCallSignatureDeclaration = TSCallSignatureDeclaration;
exports.TSInterfaceHeritage = exports.TSExpressionWithTypeArguments = exports.TSClassImplements = TSClassImplements;
exports.TSConditionalType = TSConditionalType; exports.TSConditionalType = TSConditionalType;
exports.TSConstructSignatureDeclaration = TSConstructSignatureDeclaration; exports.TSConstructSignatureDeclaration = TSConstructSignatureDeclaration;
exports.TSConstructorType = TSConstructorType; exports.TSConstructorType = TSConstructorType;
@ -17,7 +18,6 @@ exports.TSDeclareMethod = TSDeclareMethod;
exports.TSEnumDeclaration = TSEnumDeclaration; exports.TSEnumDeclaration = TSEnumDeclaration;
exports.TSEnumMember = TSEnumMember; exports.TSEnumMember = TSEnumMember;
exports.TSExportAssignment = TSExportAssignment; exports.TSExportAssignment = TSExportAssignment;
exports.TSExpressionWithTypeArguments = TSExpressionWithTypeArguments;
exports.TSExternalModuleReference = TSExternalModuleReference; exports.TSExternalModuleReference = TSExternalModuleReference;
exports.TSFunctionType = TSFunctionType; exports.TSFunctionType = TSFunctionType;
exports.TSImportEqualsDeclaration = TSImportEqualsDeclaration; exports.TSImportEqualsDeclaration = TSImportEqualsDeclaration;
@ -70,19 +70,22 @@ exports.tsPrintClassMemberModifiers = tsPrintClassMemberModifiers;
exports.tsPrintFunctionOrConstructorType = tsPrintFunctionOrConstructorType; exports.tsPrintFunctionOrConstructorType = tsPrintFunctionOrConstructorType;
exports.tsPrintPropertyOrMethodName = tsPrintPropertyOrMethodName; exports.tsPrintPropertyOrMethodName = tsPrintPropertyOrMethodName;
exports.tsPrintSignatureDeclarationBase = tsPrintSignatureDeclarationBase; exports.tsPrintSignatureDeclarationBase = tsPrintSignatureDeclarationBase;
exports.tsPrintTypeLiteralOrInterfaceBody = tsPrintTypeLiteralOrInterfaceBody; function TSTypeAnnotation(node, parent) {
function TSTypeAnnotation(node) { this.token((parent.type === "TSFunctionType" || parent.type === "TSConstructorType") && parent.typeAnnotation === node ? "=>" : ":");
this.tokenChar(58);
this.space(); this.space();
if (node.optional) this.tokenChar(63); if (node.optional) this.tokenChar(63);
this.print(node.typeAnnotation, node); this.print(node.typeAnnotation);
} }
function TSTypeParameterInstantiation(node, parent) { function TSTypeParameterInstantiation(node, parent) {
this.tokenChar(60); this.tokenChar(60);
this.printList(node.params, node, {}); let printTrailingSeparator = parent.type === "ArrowFunctionExpression" && node.params.length === 1;
if (parent.type === "ArrowFunctionExpression" && node.params.length === 1) { if (this.tokenMap && node.start != null && node.end != null) {
this.tokenChar(44); printTrailingSeparator && (printTrailingSeparator = !!this.tokenMap.find(node, t => this.tokenMap.matchesOriginal(t, ",")));
printTrailingSeparator || (printTrailingSeparator = this.shouldPrintTrailingComma(">"));
} }
this.printList(node.params, {
printTrailingSeparator
});
this.tokenChar(62); this.tokenChar(62);
} }
function TSTypeParameter(node) { function TSTypeParameter(node) {
@ -99,13 +102,13 @@ function TSTypeParameter(node) {
this.space(); this.space();
this.word("extends"); this.word("extends");
this.space(); this.space();
this.print(node.constraint, node); this.print(node.constraint);
} }
if (node.default) { if (node.default) {
this.space(); this.space();
this.tokenChar(61); this.tokenChar(61);
this.space(); this.space();
this.print(node.default, node); this.print(node.default);
} }
} }
function TSParameterProperty(node) { function TSParameterProperty(node) {
@ -125,26 +128,37 @@ function TSDeclareFunction(node, parent) {
this.space(); this.space();
} }
this._functionHead(node, parent); this._functionHead(node, parent);
this.tokenChar(59); this.semicolon();
} }
function TSDeclareMethod(node) { function TSDeclareMethod(node) {
this._classMethodHead(node); this._classMethodHead(node);
this.tokenChar(59); this.semicolon();
} }
function TSQualifiedName(node) { function TSQualifiedName(node) {
this.print(node.left, node); this.print(node.left);
this.tokenChar(46); this.tokenChar(46);
this.print(node.right, node); this.print(node.right);
} }
function TSCallSignatureDeclaration(node) { function TSCallSignatureDeclaration(node) {
this.tsPrintSignatureDeclarationBase(node); this.tsPrintSignatureDeclarationBase(node);
this.tokenChar(59); maybePrintTrailingCommaOrSemicolon(this, node);
}
function maybePrintTrailingCommaOrSemicolon(printer, node) {
if (!printer.tokenMap || !node.start || !node.end) {
printer.semicolon();
return;
}
if (printer.tokenMap.endMatches(node, ",")) {
printer.token(",");
} else if (printer.tokenMap.endMatches(node, ";")) {
printer.semicolon();
}
} }
function TSConstructSignatureDeclaration(node) { function TSConstructSignatureDeclaration(node) {
this.word("new"); this.word("new");
this.space(); this.space();
this.tsPrintSignatureDeclarationBase(node); this.tsPrintSignatureDeclarationBase(node);
this.tokenChar(59); maybePrintTrailingCommaOrSemicolon(this, node);
} }
function TSPropertySignature(node) { function TSPropertySignature(node) {
const { const {
@ -155,14 +169,14 @@ function TSPropertySignature(node) {
this.space(); this.space();
} }
this.tsPrintPropertyOrMethodName(node); this.tsPrintPropertyOrMethodName(node);
this.print(node.typeAnnotation, node); this.print(node.typeAnnotation);
this.tokenChar(59); maybePrintTrailingCommaOrSemicolon(this, node);
} }
function tsPrintPropertyOrMethodName(node) { function tsPrintPropertyOrMethodName(node) {
if (node.computed) { if (node.computed) {
this.tokenChar(91); this.tokenChar(91);
} }
this.print(node.key, node); this.print(node.key);
if (node.computed) { if (node.computed) {
this.tokenChar(93); this.tokenChar(93);
} }
@ -180,7 +194,7 @@ function TSMethodSignature(node) {
} }
this.tsPrintPropertyOrMethodName(node); this.tsPrintPropertyOrMethodName(node);
this.tsPrintSignatureDeclarationBase(node); this.tsPrintSignatureDeclarationBase(node);
this.tokenChar(59); maybePrintTrailingCommaOrSemicolon(this, node);
} }
function TSIndexSignature(node) { function TSIndexSignature(node) {
const { const {
@ -196,10 +210,9 @@ function TSIndexSignature(node) {
this.space(); this.space();
} }
this.tokenChar(91); this.tokenChar(91);
this._parameters(node.parameters, node); this._parameters(node.parameters, "]");
this.tokenChar(93); this.print(node.typeAnnotation);
this.print(node.typeAnnotation, node); maybePrintTrailingCommaOrSemicolon(this, node);
this.tokenChar(59);
} }
function TSAnyKeyword() { function TSAnyKeyword() {
this.word("any"); this.word("any");
@ -260,19 +273,16 @@ function tsPrintFunctionOrConstructorType(node) {
typeParameters typeParameters
} = node; } = node;
const parameters = node.parameters; const parameters = node.parameters;
this.print(typeParameters, node); this.print(typeParameters);
this.tokenChar(40); this.tokenChar(40);
this._parameters(parameters, node); this._parameters(parameters, ")");
this.tokenChar(41);
this.space();
this.token("=>");
this.space(); this.space();
const returnType = node.typeAnnotation; const returnType = node.typeAnnotation;
this.print(returnType.typeAnnotation, node); this.print(returnType);
} }
function TSTypeReference(node) { function TSTypeReference(node) {
this.print(node.typeName, node, true); this.print(node.typeName, !!node.typeParameters);
this.print(node.typeParameters, node, true); this.print(node.typeParameters);
} }
function TSTypePredicate(node) { function TSTypePredicate(node) {
if (node.asserts) { if (node.asserts) {
@ -292,51 +302,41 @@ function TSTypeQuery(node) {
this.space(); this.space();
this.print(node.exprName); this.print(node.exprName);
if (node.typeParameters) { if (node.typeParameters) {
this.print(node.typeParameters, node); this.print(node.typeParameters);
} }
} }
function TSTypeLiteral(node) { function TSTypeLiteral(node) {
this.tsPrintTypeLiteralOrInterfaceBody(node.members, node); printBraced(this, node, () => this.printJoin(node.members, {
} indent: true,
function tsPrintTypeLiteralOrInterfaceBody(members, node) { statement: true
tsPrintBraced(this, members, node); }));
}
function tsPrintBraced(printer, members, node) {
printer.token("{");
if (members.length) {
printer.indent();
printer.newline();
for (const member of members) {
printer.print(member, node);
printer.newline();
}
printer.dedent();
}
printer.rightBrace(node);
} }
function TSArrayType(node) { function TSArrayType(node) {
this.print(node.elementType, node, true); this.print(node.elementType, true);
this.token("[]"); this.tokenChar(91);
this.tokenChar(93);
} }
function TSTupleType(node) { function TSTupleType(node) {
this.tokenChar(91); this.tokenChar(91);
this.printList(node.elementTypes, node); this.printList(node.elementTypes, {
printTrailingSeparator: this.shouldPrintTrailingComma("]")
});
this.tokenChar(93); this.tokenChar(93);
} }
function TSOptionalType(node) { function TSOptionalType(node) {
this.print(node.typeAnnotation, node); this.print(node.typeAnnotation);
this.tokenChar(63); this.tokenChar(63);
} }
function TSRestType(node) { function TSRestType(node) {
this.token("..."); this.token("...");
this.print(node.typeAnnotation, node); this.print(node.typeAnnotation);
} }
function TSNamedTupleMember(node) { function TSNamedTupleMember(node) {
this.print(node.label, node); this.print(node.label);
if (node.optional) this.tokenChar(63); if (node.optional) this.tokenChar(63);
this.tokenChar(58); this.tokenChar(58);
this.space(); this.space();
this.print(node.elementType, node); this.print(node.elementType);
} }
function TSUnionType(node) { function TSUnionType(node) {
tsPrintUnionOrIntersectionType(this, node, "|"); tsPrintUnionOrIntersectionType(this, node, "|");
@ -345,10 +345,16 @@ function TSIntersectionType(node) {
tsPrintUnionOrIntersectionType(this, node, "&"); tsPrintUnionOrIntersectionType(this, node, "&");
} }
function tsPrintUnionOrIntersectionType(printer, node, sep) { function tsPrintUnionOrIntersectionType(printer, node, sep) {
printer.printJoin(node.types, node, { var _printer$tokenMap;
separator() { let hasLeadingToken = 0;
if ((_printer$tokenMap = printer.tokenMap) != null && _printer$tokenMap.startMatches(node, sep)) {
hasLeadingToken = 1;
printer.token(sep);
}
printer.printJoin(node.types, {
separator(i) {
this.space(); this.space();
this.token(sep); this.token(sep, null, i + hasLeadingToken);
this.space(); this.space();
} }
}); });
@ -369,24 +375,23 @@ function TSConditionalType(node) {
this.print(node.falseType); this.print(node.falseType);
} }
function TSInferType(node) { function TSInferType(node) {
this.token("infer"); this.word("infer");
this.space();
this.print(node.typeParameter); this.print(node.typeParameter);
} }
function TSParenthesizedType(node) { function TSParenthesizedType(node) {
this.tokenChar(40); this.tokenChar(40);
this.print(node.typeAnnotation, node); this.print(node.typeAnnotation);
this.tokenChar(41); this.tokenChar(41);
} }
function TSTypeOperator(node) { function TSTypeOperator(node) {
this.word(node.operator); this.word(node.operator);
this.space(); this.space();
this.print(node.typeAnnotation, node); this.print(node.typeAnnotation);
} }
function TSIndexedAccessType(node) { function TSIndexedAccessType(node) {
this.print(node.objectType, node, true); this.print(node.objectType, true);
this.tokenChar(91); this.tokenChar(91);
this.print(node.indexType, node); this.print(node.indexType);
this.tokenChar(93); this.tokenChar(93);
} }
function TSMappedType(node) { function TSMappedType(node) {
@ -394,10 +399,10 @@ function TSMappedType(node) {
nameType, nameType,
optional, optional,
readonly, readonly,
typeParameter,
typeAnnotation typeAnnotation
} = node; } = node;
this.tokenChar(123); this.tokenChar(123);
const exit = this.enterDelimited();
this.space(); this.space();
if (readonly) { if (readonly) {
tokenIfPlusMinus(this, readonly); tokenIfPlusMinus(this, readonly);
@ -405,16 +410,20 @@ function TSMappedType(node) {
this.space(); this.space();
} }
this.tokenChar(91); this.tokenChar(91);
this.word(typeParameter.name); {
this.word(node.typeParameter.name);
}
this.space(); this.space();
this.word("in"); this.word("in");
this.space(); this.space();
this.print(typeParameter.constraint, typeParameter); {
this.print(node.typeParameter.constraint);
}
if (nameType) { if (nameType) {
this.space(); this.space();
this.word("as"); this.word("as");
this.space(); this.space();
this.print(nameType, node); this.print(nameType);
} }
this.tokenChar(93); this.tokenChar(93);
if (optional) { if (optional) {
@ -424,9 +433,10 @@ function TSMappedType(node) {
if (typeAnnotation) { if (typeAnnotation) {
this.tokenChar(58); this.tokenChar(58);
this.space(); this.space();
this.print(typeAnnotation, node); this.print(typeAnnotation);
} }
this.space(); this.space();
exit();
this.tokenChar(125); this.tokenChar(125);
} }
function tokenIfPlusMinus(self, tok) { function tokenIfPlusMinus(self, tok) {
@ -435,11 +445,11 @@ function tokenIfPlusMinus(self, tok) {
} }
} }
function TSLiteralType(node) { function TSLiteralType(node) {
this.print(node.literal, node); this.print(node.literal);
} }
function TSExpressionWithTypeArguments(node) { function TSClassImplements(node) {
this.print(node.expression, node); this.print(node.expression);
this.print(node.typeParameters, node); this.print(node.typeParameters);
} }
function TSInterfaceDeclaration(node) { function TSInterfaceDeclaration(node) {
const { const {
@ -455,19 +465,22 @@ function TSInterfaceDeclaration(node) {
} }
this.word("interface"); this.word("interface");
this.space(); this.space();
this.print(id, node); this.print(id);
this.print(typeParameters, node); this.print(typeParameters);
if (extendz != null && extendz.length) { if (extendz != null && extendz.length) {
this.space(); this.space();
this.word("extends"); this.word("extends");
this.space(); this.space();
this.printList(extendz, node); this.printList(extendz);
} }
this.space(); this.space();
this.print(body, node); this.print(body);
} }
function TSInterfaceBody(node) { function TSInterfaceBody(node) {
this.tsPrintTypeLiteralOrInterfaceBody(node.body, node); printBraced(this, node, () => this.printJoin(node.body, {
indent: true,
statement: true
}));
} }
function TSTypeAliasDeclaration(node) { function TSTypeAliasDeclaration(node) {
const { const {
@ -482,27 +495,25 @@ function TSTypeAliasDeclaration(node) {
} }
this.word("type"); this.word("type");
this.space(); this.space();
this.print(id, node); this.print(id);
this.print(typeParameters, node); this.print(typeParameters);
this.space(); this.space();
this.tokenChar(61); this.tokenChar(61);
this.space(); this.space();
this.print(typeAnnotation, node); this.print(typeAnnotation);
this.tokenChar(59); this.semicolon();
} }
function TSTypeExpression(node) { function TSTypeExpression(node) {
var _expression$trailingC;
const { const {
type, type,
expression, expression,
typeAnnotation typeAnnotation
} = node; } = node;
const forceParens = !!((_expression$trailingC = expression.trailingComments) != null && _expression$trailingC.length); this.print(expression, true);
this.print(expression, node, true, undefined, forceParens);
this.space(); this.space();
this.word(type === "TSAsExpression" ? "as" : "satisfies"); this.word(type === "TSAsExpression" ? "as" : "satisfies");
this.space(); this.space();
this.print(typeAnnotation, node); this.print(typeAnnotation);
} }
function TSTypeAssertion(node) { function TSTypeAssertion(node) {
const { const {
@ -510,14 +521,14 @@ function TSTypeAssertion(node) {
expression expression
} = node; } = node;
this.tokenChar(60); this.tokenChar(60);
this.print(typeAnnotation, node); this.print(typeAnnotation);
this.tokenChar(62); this.tokenChar(62);
this.space(); this.space();
this.print(expression, node); this.print(expression);
} }
function TSInstantiationExpression(node) { function TSInstantiationExpression(node) {
this.print(node.expression, node); this.print(node.expression);
this.print(node.typeParameters, node); this.print(node.typeParameters);
} }
function TSEnumDeclaration(node) { function TSEnumDeclaration(node) {
const { const {
@ -536,53 +547,62 @@ function TSEnumDeclaration(node) {
} }
this.word("enum"); this.word("enum");
this.space(); this.space();
this.print(id, node); this.print(id);
this.space(); this.space();
tsPrintBraced(this, members, node); printBraced(this, node, () => {
var _this$shouldPrintTrai;
return this.printList(members, {
indent: true,
statement: true,
printTrailingSeparator: (_this$shouldPrintTrai = this.shouldPrintTrailingComma("}")) != null ? _this$shouldPrintTrai : true
});
});
} }
function TSEnumMember(node) { function TSEnumMember(node) {
const { const {
id, id,
initializer initializer
} = node; } = node;
this.print(id, node); this.print(id);
if (initializer) { if (initializer) {
this.space(); this.space();
this.tokenChar(61); this.tokenChar(61);
this.space(); this.space();
this.print(initializer, node); this.print(initializer);
} }
this.tokenChar(44);
} }
function TSModuleDeclaration(node) { function TSModuleDeclaration(node) {
const { const {
declare, declare,
id id,
kind
} = node; } = node;
if (declare) { if (declare) {
this.word("declare"); this.word("declare");
this.space(); this.space();
} }
if (!node.global) { if (!node.global) {
this.word(id.type === "Identifier" ? "namespace" : "module"); this.word(kind != null ? kind : id.type === "Identifier" ? "namespace" : "module");
this.space(); this.space();
} }
this.print(id, node); this.print(id);
if (!node.body) { if (!node.body) {
this.tokenChar(59); this.semicolon();
return; return;
} }
let body = node.body; let body = node.body;
while (body.type === "TSModuleDeclaration") { while (body.type === "TSModuleDeclaration") {
this.tokenChar(46); this.tokenChar(46);
this.print(body.id, body); this.print(body.id);
body = body.body; body = body.body;
} }
this.space(); this.space();
this.print(body, node); this.print(body);
} }
function TSModuleBlock(node) { function TSModuleBlock(node) {
tsPrintBraced(this, node.body, node); printBraced(this, node, () => this.printSequence(node.body, {
indent: true
}));
} }
function TSImportType(node) { function TSImportType(node) {
const { const {
@ -592,14 +612,14 @@ function TSImportType(node) {
} = node; } = node;
this.word("import"); this.word("import");
this.tokenChar(40); this.tokenChar(40);
this.print(argument, node); this.print(argument);
this.tokenChar(41); this.tokenChar(41);
if (qualifier) { if (qualifier) {
this.tokenChar(46); this.tokenChar(46);
this.print(qualifier, node); this.print(qualifier);
} }
if (typeParameters) { if (typeParameters) {
this.print(typeParameters, node); this.print(typeParameters);
} }
} }
function TSImportEqualsDeclaration(node) { function TSImportEqualsDeclaration(node) {
@ -614,20 +634,20 @@ function TSImportEqualsDeclaration(node) {
} }
this.word("import"); this.word("import");
this.space(); this.space();
this.print(id, node); this.print(id);
this.space(); this.space();
this.tokenChar(61); this.tokenChar(61);
this.space(); this.space();
this.print(moduleReference, node); this.print(moduleReference);
this.tokenChar(59); this.semicolon();
} }
function TSExternalModuleReference(node) { function TSExternalModuleReference(node) {
this.token("require("); this.token("require(");
this.print(node.expression, node); this.print(node.expression);
this.tokenChar(41); this.tokenChar(41);
} }
function TSNonNullExpression(node) { function TSNonNullExpression(node) {
this.print(node.expression, node); this.print(node.expression);
this.tokenChar(33); this.tokenChar(33);
} }
function TSExportAssignment(node) { function TSExportAssignment(node) {
@ -635,8 +655,8 @@ function TSExportAssignment(node) {
this.space(); this.space();
this.tokenChar(61); this.tokenChar(61);
this.space(); this.space();
this.print(node.expression, node); this.print(node.expression);
this.tokenChar(59); this.semicolon();
} }
function TSNamespaceExportDeclaration(node) { function TSNamespaceExportDeclaration(node) {
this.word("export"); this.word("export");
@ -645,45 +665,53 @@ function TSNamespaceExportDeclaration(node) {
this.space(); this.space();
this.word("namespace"); this.word("namespace");
this.space(); this.space();
this.print(node.id, node); this.print(node.id);
this.semicolon();
} }
function tsPrintSignatureDeclarationBase(node) { function tsPrintSignatureDeclarationBase(node) {
const { const {
typeParameters typeParameters
} = node; } = node;
const parameters = node.parameters; const parameters = node.parameters;
this.print(typeParameters, node); this.print(typeParameters);
this.tokenChar(40); this.tokenChar(40);
this._parameters(parameters, node); this._parameters(parameters, ")");
this.tokenChar(41);
const returnType = node.typeAnnotation; const returnType = node.typeAnnotation;
this.print(returnType, node); this.print(returnType);
} }
function tsPrintClassMemberModifiers(node) { function tsPrintClassMemberModifiers(node) {
const isField = node.type === "ClassAccessorProperty" || node.type === "ClassProperty"; const isField = node.type === "ClassAccessorProperty" || node.type === "ClassProperty";
if (isField && node.declare) { printModifiersList(this, node, [isField && node.declare && "declare", node.accessibility]);
this.word("declare");
this.space();
}
if (node.accessibility) {
this.word(node.accessibility);
this.space();
}
if (node.static) { if (node.static) {
this.word("static"); this.word("static");
this.space(); this.space();
} }
if (node.override) { printModifiersList(this, node, [node.override && "override", node.abstract && "abstract", isField && node.readonly && "readonly"]);
this.word("override");
this.space();
} }
if (node.abstract) { function printBraced(printer, node, cb) {
this.word("abstract"); printer.token("{");
this.space(); const exit = printer.enterDelimited();
cb();
exit();
printer.rightBrace(node);
} }
if (isField && node.readonly) { function printModifiersList(printer, node, modifiers) {
this.word("readonly"); var _printer$tokenMap2;
this.space(); const modifiersSet = new Set();
for (const modifier of modifiers) {
if (modifier) modifiersSet.add(modifier);
}
(_printer$tokenMap2 = printer.tokenMap) == null || _printer$tokenMap2.find(node, tok => {
if (modifiersSet.has(tok.value)) {
printer.token(tok.value);
printer.space();
modifiersSet.delete(tok.value);
return modifiersSet.size === 0;
}
});
for (const modifier of modifiersSet) {
printer.word(modifier);
printer.space();
} }
} }

File diff suppressed because one or more lines are too long

View File

@ -6,11 +6,32 @@ Object.defineProperty(exports, "__esModule", {
exports.default = generate; exports.default = generate;
var _sourceMap = require("./source-map.js"); var _sourceMap = require("./source-map.js");
var _printer = require("./printer.js"); var _printer = require("./printer.js");
function normalizeOptions(code, opts) { function normalizeOptions(code, opts, ast) {
if (opts.experimental_preserveFormat) {
if (typeof code !== "string") {
throw new Error("`experimental_preserveFormat` requires the original `code` to be passed to @babel/generator as a string");
}
if (!opts.retainLines) {
throw new Error("`experimental_preserveFormat` requires `retainLines` to be set to `true`");
}
if (opts.compact && opts.compact !== "auto") {
throw new Error("`experimental_preserveFormat` is not compatible with the `compact` option");
}
if (opts.minified) {
throw new Error("`experimental_preserveFormat` is not compatible with the `minified` option");
}
if (opts.jsescOption) {
throw new Error("`experimental_preserveFormat` is not compatible with the `jsescOption` option");
}
if (!Array.isArray(ast.tokens)) {
throw new Error("`experimental_preserveFormat` requires the AST to have attatched the token of the input code. Make sure to enable the `tokens: true` parser option.");
}
}
const format = { const format = {
auxiliaryCommentBefore: opts.auxiliaryCommentBefore, auxiliaryCommentBefore: opts.auxiliaryCommentBefore,
auxiliaryCommentAfter: opts.auxiliaryCommentAfter, auxiliaryCommentAfter: opts.auxiliaryCommentAfter,
shouldPrintComment: opts.shouldPrintComment, shouldPrintComment: opts.shouldPrintComment,
preserveFormat: opts.experimental_preserveFormat,
retainLines: opts.retainLines, retainLines: opts.retainLines,
retainFunctionParens: opts.retainFunctionParens, retainFunctionParens: opts.retainFunctionParens,
comments: opts.comments == null || opts.comments, comments: opts.comments == null || opts.comments,
@ -47,7 +68,7 @@ function normalizeOptions(code, opts) {
console.error("[BABEL] Note: The code generator has deoptimised the styling of " + `${opts.filename} as it exceeds the max of ${"500KB"}.`); console.error("[BABEL] Note: The code generator has deoptimised the styling of " + `${opts.filename} as it exceeds the max of ${"500KB"}.`);
} }
} }
if (format.compact) { if (format.compact || format.preserveFormat) {
format.indent.adjustMultilineComment = false; format.indent.adjustMultilineComment = false;
} }
const { const {
@ -70,7 +91,7 @@ function normalizeOptions(code, opts) {
this._format = void 0; this._format = void 0;
this._map = void 0; this._map = void 0;
this._ast = ast; this._ast = ast;
this._format = normalizeOptions(code, opts); this._format = normalizeOptions(code, opts, ast);
this._map = opts.sourceMaps ? new _sourceMap.default(opts, code) : null; this._map = opts.sourceMaps ? new _sourceMap.default(opts, code) : null;
} }
generate() { generate() {
@ -80,9 +101,9 @@ function normalizeOptions(code, opts) {
}; };
} }
function generate(ast, opts = {}, code) { function generate(ast, opts = {}, code) {
const format = normalizeOptions(code, opts); const format = normalizeOptions(code, opts, ast);
const map = opts.sourceMaps ? new _sourceMap.default(opts, code) : null; const map = opts.sourceMaps ? new _sourceMap.default(opts, code) : null;
const printer = new _printer.default(format, map); const printer = new _printer.default(format, map, ast.tokens, typeof code === "string" ? code : null);
return printer.generate(ast); return printer.generate(ast);
} }

File diff suppressed because one or more lines are too long

View File

@ -4,6 +4,7 @@ Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.TokenContext = void 0; exports.TokenContext = void 0;
exports.isLastChild = isLastChild;
exports.needsParens = needsParens; exports.needsParens = needsParens;
exports.needsWhitespace = needsWhitespace; exports.needsWhitespace = needsWhitespace;
exports.needsWhitespaceAfter = needsWhitespaceAfter; exports.needsWhitespaceAfter = needsWhitespaceAfter;
@ -13,6 +14,7 @@ var parens = require("./parentheses.js");
var _t = require("@babel/types"); var _t = require("@babel/types");
const { const {
FLIPPED_ALIAS_KEYS, FLIPPED_ALIAS_KEYS,
VISITOR_KEYS,
isCallExpression, isCallExpression,
isDecorator, isDecorator,
isExpressionStatement, isExpressionStatement,
@ -33,9 +35,9 @@ function expandAliases(obj) {
const map = new Map(); const map = new Map();
function add(type, func) { function add(type, func) {
const fn = map.get(type); const fn = map.get(type);
map.set(type, fn ? function (node, parent, stack, inForInit) { map.set(type, fn ? function (node, parent, stack, inForInit, getRawIdentifier) {
var _fn; var _fn;
return (_fn = fn(node, parent, stack, inForInit)) != null ? _fn : func(node, parent, stack, inForInit); return (_fn = fn(node, parent, stack, inForInit, getRawIdentifier)) != null ? _fn : func(node, parent, stack, inForInit, getRawIdentifier);
} : func); } : func);
} }
for (const type of Object.keys(obj)) { for (const type of Object.keys(obj)) {
@ -76,7 +78,7 @@ function needsWhitespaceBefore(node, parent) {
function needsWhitespaceAfter(node, parent) { function needsWhitespaceAfter(node, parent) {
return needsWhitespace(node, parent, 2); return needsWhitespace(node, parent, 2);
} }
function needsParens(node, parent, tokenContext, inForInit) { function needsParens(node, parent, tokenContext, inForInit, getRawIdentifier) {
var _expandedParens$get; var _expandedParens$get;
if (!parent) return false; if (!parent) return false;
if (isNewExpression(parent) && parent.callee === node) { if (isNewExpression(parent) && parent.callee === node) {
@ -85,7 +87,7 @@ function needsParens(node, parent, tokenContext, inForInit) {
if (isDecorator(parent)) { if (isDecorator(parent)) {
return !isDecoratorMemberExpression(node) && !(isCallExpression(node) && isDecoratorMemberExpression(node.callee)) && !isParenthesizedExpression(node); return !isDecoratorMemberExpression(node) && !(isCallExpression(node) && isDecoratorMemberExpression(node.callee)) && !isParenthesizedExpression(node);
} }
return (_expandedParens$get = expandedParens.get(node.type)) == null ? void 0 : _expandedParens$get(node, parent, tokenContext, inForInit); return (_expandedParens$get = expandedParens.get(node.type)) == null ? void 0 : _expandedParens$get(node, parent, tokenContext, inForInit, getRawIdentifier);
} }
function isDecoratorMemberExpression(node) { function isDecoratorMemberExpression(node) {
switch (node.type) { switch (node.type) {
@ -97,5 +99,21 @@ function isDecoratorMemberExpression(node) {
return false; return false;
} }
} }
function isLastChild(parent, child) {
const visitorKeys = VISITOR_KEYS[parent.type];
for (let i = visitorKeys.length - 1; i >= 0; i--) {
const val = parent[visitorKeys[i]];
if (val === child) {
return true;
} else if (Array.isArray(val)) {
let j = val.length - 1;
while (j >= 0 && val[j] === null) j--;
return j >= 0 && val[j] === child;
} else if (val) {
return false;
}
}
return false;
}
//# sourceMappingURL=index.js.map //# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@ -3,12 +3,11 @@
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.ArrowFunctionExpression = ArrowFunctionExpression;
exports.AssignmentExpression = AssignmentExpression; exports.AssignmentExpression = AssignmentExpression;
exports.Binary = Binary; exports.Binary = Binary;
exports.BinaryExpression = BinaryExpression; exports.BinaryExpression = BinaryExpression;
exports.ClassExpression = ClassExpression; exports.ClassExpression = ClassExpression;
exports.ConditionalExpression = ConditionalExpression; exports.ArrowFunctionExpression = exports.ConditionalExpression = ConditionalExpression;
exports.DoExpression = DoExpression; exports.DoExpression = DoExpression;
exports.FunctionExpression = FunctionExpression; exports.FunctionExpression = FunctionExpression;
exports.FunctionTypeAnnotation = FunctionTypeAnnotation; exports.FunctionTypeAnnotation = FunctionTypeAnnotation;
@ -33,13 +32,13 @@ const {
isArrayTypeAnnotation, isArrayTypeAnnotation,
isBinaryExpression, isBinaryExpression,
isCallExpression, isCallExpression,
isExportDeclaration,
isForOfStatement, isForOfStatement,
isIndexedAccessType, isIndexedAccessType,
isMemberExpression, isMemberExpression,
isObjectPattern, isObjectPattern,
isOptionalMemberExpression, isOptionalMemberExpression,
isYieldExpression isYieldExpression,
isStatement
} = _t; } = _t;
const PRECEDENCE = new Map([["||", 0], ["??", 0], ["|>", 0], ["&&", 1], ["|", 2], ["^", 3], ["&", 4], ["==", 5], ["===", 5], ["!=", 5], ["!==", 5], ["<", 6], [">", 6], ["<=", 6], [">=", 6], ["in", 6], ["instanceof", 6], [">>", 7], ["<<", 7], [">>>", 7], ["+", 8], ["-", 8], ["*", 9], ["/", 9], ["%", 9], ["**", 10]]); const PRECEDENCE = new Map([["||", 0], ["??", 0], ["|>", 0], ["&&", 1], ["|", 2], ["^", 3], ["&", 4], ["==", 5], ["===", 5], ["!=", 5], ["!==", 5], ["<", 6], [">", 6], ["<=", 6], [">=", 6], ["in", 6], ["instanceof", 6], [">>", 7], ["<<", 7], [">>>", 7], ["+", 8], ["-", 8], ["*", 9], ["/", 9], ["%", 9], ["**", 10]]);
function getBinaryPrecedence(node, nodeType) { function getBinaryPrecedence(node, nodeType) {
@ -66,14 +65,18 @@ function NullableTypeAnnotation(node, parent) {
} }
function FunctionTypeAnnotation(node, parent, tokenContext) { function FunctionTypeAnnotation(node, parent, tokenContext) {
const parentType = parent.type; const parentType = parent.type;
return parentType === "UnionTypeAnnotation" || parentType === "IntersectionTypeAnnotation" || parentType === "ArrayTypeAnnotation" || Boolean(tokenContext & _index.TokenContext.arrowFlowReturnType); return (parentType === "UnionTypeAnnotation" || parentType === "IntersectionTypeAnnotation" || parentType === "ArrayTypeAnnotation" || Boolean(tokenContext & _index.TokenContext.arrowFlowReturnType)
);
} }
function UpdateExpression(node, parent) { function UpdateExpression(node, parent) {
return hasPostfixPart(node, parent) || isClassExtendsClause(node, parent); return hasPostfixPart(node, parent) || isClassExtendsClause(node, parent);
} }
function ObjectExpression(node, parent, tokenContext) { function needsParenBeforeExpressionBrace(tokenContext) {
return Boolean(tokenContext & (_index.TokenContext.expressionStatement | _index.TokenContext.arrowBody)); return Boolean(tokenContext & (_index.TokenContext.expressionStatement | _index.TokenContext.arrowBody));
} }
function ObjectExpression(node, parent, tokenContext) {
return needsParenBeforeExpressionBrace(tokenContext);
}
function DoExpression(node, parent, tokenContext) { function DoExpression(node, parent, tokenContext) {
return !node.async && Boolean(tokenContext & _index.TokenContext.expressionStatement); return !node.async && Boolean(tokenContext & _index.TokenContext.expressionStatement);
} }
@ -115,7 +118,7 @@ function TSAsExpression(node, parent) {
} }
function TSUnionType(node, parent) { function TSUnionType(node, parent) {
const parentType = parent.type; const parentType = parent.type;
return parentType === "TSArrayType" || parentType === "TSOptionalType" || parentType === "TSIntersectionType" || parentType === "TSUnionType" || parentType === "TSRestType"; return parentType === "TSArrayType" || parentType === "TSOptionalType" || parentType === "TSIntersectionType" || parentType === "TSRestType";
} }
function TSInferType(node, parent) { function TSInferType(node, parent) {
const parentType = parent.type; const parentType = parent.type;
@ -130,11 +133,20 @@ function BinaryExpression(node, parent, tokenContext, inForStatementInit) {
} }
function SequenceExpression(node, parent) { function SequenceExpression(node, parent) {
const parentType = parent.type; const parentType = parent.type;
if (parentType === "ForStatement" || parentType === "ThrowStatement" || parentType === "ReturnStatement" || parentType === "IfStatement" && parent.test === node || parentType === "WhileStatement" && parent.test === node || parentType === "ForInStatement" && parent.right === node || parentType === "SwitchStatement" && parent.discriminant === node || parentType === "ExpressionStatement" && parent.expression === node) { if (parentType === "SequenceExpression" || parentType === "ParenthesizedExpression" || parentType === "MemberExpression" && parent.property === node || parentType === "OptionalMemberExpression" && parent.property === node || parentType === "TemplateLiteral") {
return false; return false;
} }
if (parentType === "ClassDeclaration") {
return true; return true;
} }
if (parentType === "ForOfStatement") {
return parent.right === node;
}
if (parentType === "ExportDefaultDeclaration") {
return true;
}
return !isStatement(parent);
}
function YieldExpression(node, parent) { function YieldExpression(node, parent) {
const parentType = parent.type; const parentType = parent.type;
return parentType === "BinaryExpression" || parentType === "LogicalExpression" || parentType === "UnaryExpression" || parentType === "SpreadElement" || hasPostfixPart(node, parent) || parentType === "AwaitExpression" && isYieldExpression(node) || parentType === "ConditionalExpression" && node === parent.test || isClassExtendsClause(node, parent) || isTSTypeExpression(parentType); return parentType === "BinaryExpression" || parentType === "LogicalExpression" || parentType === "UnaryExpression" || parentType === "SpreadElement" || hasPostfixPart(node, parent) || parentType === "AwaitExpression" && isYieldExpression(node) || parentType === "ConditionalExpression" && node === parent.test || isClassExtendsClause(node, parent) || isTSTypeExpression(parentType);
@ -148,9 +160,6 @@ function UnaryLike(node, parent) {
function FunctionExpression(node, parent, tokenContext) { function FunctionExpression(node, parent, tokenContext) {
return Boolean(tokenContext & (_index.TokenContext.expressionStatement | _index.TokenContext.exportDefault)); return Boolean(tokenContext & (_index.TokenContext.expressionStatement | _index.TokenContext.exportDefault));
} }
function ArrowFunctionExpression(node, parent) {
return isExportDeclaration(parent) || ConditionalExpression(node, parent);
}
function ConditionalExpression(node, parent) { function ConditionalExpression(node, parent) {
const parentType = parent.type; const parentType = parent.type;
if (parentType === "UnaryExpression" || parentType === "SpreadElement" || parentType === "BinaryExpression" || parentType === "LogicalExpression" || parentType === "ConditionalExpression" && parent.test === node || parentType === "AwaitExpression" || isTSTypeExpression(parentType)) { if (parentType === "UnaryExpression" || parentType === "SpreadElement" || parentType === "BinaryExpression" || parentType === "LogicalExpression" || parentType === "ConditionalExpression" && parent.test === node || parentType === "AwaitExpression" || isTSTypeExpression(parentType)) {
@ -161,8 +170,8 @@ function ConditionalExpression(node, parent) {
function OptionalMemberExpression(node, parent) { function OptionalMemberExpression(node, parent) {
return isCallExpression(parent) && parent.callee === node || isMemberExpression(parent) && parent.object === node; return isCallExpression(parent) && parent.callee === node || isMemberExpression(parent) && parent.object === node;
} }
function AssignmentExpression(node, parent) { function AssignmentExpression(node, parent, tokenContext) {
if (isObjectPattern(node.left)) { if (needsParenBeforeExpressionBrace(tokenContext) && isObjectPattern(node.left)) {
return true; return true;
} else { } else {
return ConditionalExpression(node, parent); return ConditionalExpression(node, parent);
@ -181,7 +190,7 @@ function LogicalExpression(node, parent) {
return parent.operator !== "??"; return parent.operator !== "??";
} }
} }
function Identifier(node, parent, tokenContext) { function Identifier(node, parent, tokenContext, _inForInit, getRawIdentifier) {
var _node$extra; var _node$extra;
const parentType = parent.type; const parentType = parent.type;
if ((_node$extra = node.extra) != null && _node$extra.parenthesized && parentType === "AssignmentExpression" && parent.left === node) { if ((_node$extra = node.extra) != null && _node$extra.parenthesized && parentType === "AssignmentExpression" && parent.left === node) {
@ -190,6 +199,9 @@ function Identifier(node, parent, tokenContext) {
return true; return true;
} }
} }
if (getRawIdentifier && getRawIdentifier(node) !== node.name) {
return false;
}
if (node.name === "let") { if (node.name === "let") {
const isFollowedByBracket = isMemberExpression(parent, { const isFollowedByBracket = isMemberExpression(parent, {
object: node, object: node,

File diff suppressed because one or more lines are too long

View File

@ -7,8 +7,10 @@ exports.default = void 0;
var _buffer = require("./buffer.js"); var _buffer = require("./buffer.js");
var n = require("./node/index.js"); var n = require("./node/index.js");
var _t = require("@babel/types"); var _t = require("@babel/types");
var _tokenMap = require("./token-map.js");
var generatorFunctions = require("./generators/index.js"); var generatorFunctions = require("./generators/index.js");
const { const {
isExpression,
isFunction, isFunction,
isStatement, isStatement,
isClassBody, isClassBody,
@ -19,59 +21,105 @@ const SCIENTIFIC_NOTATION = /e/i;
const ZERO_DECIMAL_INTEGER = /\.0+$/; const ZERO_DECIMAL_INTEGER = /\.0+$/;
const HAS_NEWLINE = /[\n\r\u2028\u2029]/; const HAS_NEWLINE = /[\n\r\u2028\u2029]/;
const HAS_NEWLINE_OR_BlOCK_COMMENT_END = /[\n\r\u2028\u2029]|\*\//; const HAS_NEWLINE_OR_BlOCK_COMMENT_END = /[\n\r\u2028\u2029]|\*\//;
function commentIsNewline(c) {
return c.type === "CommentLine" || HAS_NEWLINE.test(c.value);
}
const { const {
needsParens needsParens
} = n; } = n;
class Printer { class Printer {
constructor(format, map) { constructor(format, map, tokens, originalCode) {
this.inForStatementInit = false; this.inForStatementInit = false;
this.tokenContext = 0; this.tokenContext = 0;
this._tokens = null;
this._originalCode = null;
this._currentNode = null; this._currentNode = null;
this._indent = 0; this._indent = 0;
this._indentRepeat = 0; this._indentRepeat = 0;
this._insideAux = false; this._insideAux = false;
this._parenPushNewlineState = null;
this._noLineTerminator = false; this._noLineTerminator = false;
this._noLineTerminatorAfterNode = null;
this._printAuxAfterOnNextUserNode = false; this._printAuxAfterOnNextUserNode = false;
this._printedComments = new Set(); this._printedComments = new Set();
this._endsWithInteger = false; this._endsWithInteger = false;
this._endsWithWord = false; this._endsWithWord = false;
this._endsWithDiv = false;
this._lastCommentLine = 0; this._lastCommentLine = 0;
this._endsWithInnerRaw = false; this._endsWithInnerRaw = false;
this._indentInnerComments = true; this._indentInnerComments = true;
this.tokenMap = null;
this._boundGetRawIdentifier = this._getRawIdentifier.bind(this);
this.format = format; this.format = format;
this._tokens = tokens;
this._originalCode = originalCode;
this._indentRepeat = format.indent.style.length; this._indentRepeat = format.indent.style.length;
this._inputMap = map == null ? void 0 : map._inputMap; this._inputMap = map == null ? void 0 : map._inputMap;
this._buf = new _buffer.default(map, format.indent.style[0]); this._buf = new _buffer.default(map, format.indent.style[0]);
} }
enterForStatementInit(val) { enterForStatementInit() {
const old = this.inForStatementInit; if (this.inForStatementInit) return () => {};
if (old === val) return () => {}; this.inForStatementInit = true;
this.inForStatementInit = val;
return () => { return () => {
this.inForStatementInit = old; this.inForStatementInit = false;
};
}
enterDelimited() {
const oldInForStatementInit = this.inForStatementInit;
const oldNoLineTerminatorAfterNode = this._noLineTerminatorAfterNode;
if (oldInForStatementInit === false && oldNoLineTerminatorAfterNode === null) {
return () => {};
}
this.inForStatementInit = false;
this._noLineTerminatorAfterNode = null;
return () => {
this.inForStatementInit = oldInForStatementInit;
this._noLineTerminatorAfterNode = oldNoLineTerminatorAfterNode;
}; };
} }
generate(ast) { generate(ast) {
if (this.format.preserveFormat) {
this.tokenMap = new _tokenMap.TokenMap(ast, this._tokens, this._originalCode);
}
this.print(ast); this.print(ast);
this._maybeAddAuxComment(); this._maybeAddAuxComment();
return this._buf.get(); return this._buf.get();
} }
indent() { indent() {
if (this.format.compact || this.format.concise) return; const {
format
} = this;
if (format.preserveFormat || format.compact || format.concise) {
return;
}
this._indent++; this._indent++;
} }
dedent() { dedent() {
if (this.format.compact || this.format.concise) return; const {
format
} = this;
if (format.preserveFormat || format.compact || format.concise) {
return;
}
this._indent--; this._indent--;
} }
semicolon(force = false) { semicolon(force = false) {
this._maybeAddAuxComment(); this._maybeAddAuxComment();
if (force) { if (force) {
this._appendChar(59); this._appendChar(59);
} else { this._noLineTerminator = false;
this._queue(59); return;
} }
if (this.tokenMap) {
const node = this._currentNode;
if (node.start != null && node.end != null) {
if (!this.tokenMap.endMatches(node, ";")) {
return;
}
const indexes = this.tokenMap.getIndexes(this._currentNode);
this._catchUpTo(this._tokens[indexes[indexes.length - 1]].loc.start);
}
}
this._queue(59);
this._noLineTerminator = false; this._noLineTerminator = false;
} }
rightBrace(node) { rightBrace(node) {
@ -86,7 +134,10 @@ class Printer {
this.tokenChar(41); this.tokenChar(41);
} }
space(force = false) { space(force = false) {
if (this.format.compact) return; const {
format
} = this;
if (format.compact || format.preserveFormat) return;
if (force) { if (force) {
this._space(); this._space();
} else if (this._buf.hasContent()) { } else if (this._buf.hasContent()) {
@ -98,8 +149,8 @@ class Printer {
} }
word(str, noLineTerminatorAfter = false) { word(str, noLineTerminatorAfter = false) {
this.tokenContext = 0; this.tokenContext = 0;
this._maybePrintInnerComments(); this._maybePrintInnerComments(str);
if (this._endsWithWord || str.charCodeAt(0) === 47 && this.endsWith(47)) { if (this._endsWithWord || this._endsWithDiv && str.charCodeAt(0) === 47) {
this._space(); this._space();
} }
this._maybeAddAuxComment(); this._maybeAddAuxComment();
@ -118,21 +169,21 @@ class Printer {
this.word(str); this.word(str);
this._endsWithInteger = Number.isInteger(number) && !isNonDecimalLiteral(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str.charCodeAt(str.length - 1) !== 46; this._endsWithInteger = Number.isInteger(number) && !isNonDecimalLiteral(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str.charCodeAt(str.length - 1) !== 46;
} }
token(str, maybeNewline = false) { token(str, maybeNewline = false, occurrenceCount = 0) {
this.tokenContext = 0; this.tokenContext = 0;
this._maybePrintInnerComments(); this._maybePrintInnerComments(str, occurrenceCount);
const lastChar = this.getLastChar(); const lastChar = this.getLastChar();
const strFirst = str.charCodeAt(0); const strFirst = str.charCodeAt(0);
if (lastChar === 33 && (str === "--" || strFirst === 61) || strFirst === 43 && lastChar === 43 || strFirst === 45 && lastChar === 45 || strFirst === 46 && this._endsWithInteger) { if (lastChar === 33 && (str === "--" || strFirst === 61) || strFirst === 43 && lastChar === 43 || strFirst === 45 && lastChar === 45 || strFirst === 46 && this._endsWithInteger) {
this._space(); this._space();
} }
this._maybeAddAuxComment(); this._maybeAddAuxComment();
this._append(str, maybeNewline); this._append(str, maybeNewline, occurrenceCount);
this._noLineTerminator = false; this._noLineTerminator = false;
} }
tokenChar(char) { tokenChar(char) {
this.tokenContext = 0; this.tokenContext = 0;
this._maybePrintInnerComments(); this._maybePrintInnerComments(String.fromCharCode(char));
const lastChar = this.getLastChar(); const lastChar = this.getLastChar();
if (char === 43 && lastChar === 43 || char === 45 && lastChar === 45 || char === 46 && this._endsWithInteger) { if (char === 43 && lastChar === 43 || char === 45 && lastChar === 45 || char === 46 && this._endsWithInteger) {
this._space(); this._space();
@ -183,7 +234,7 @@ class Printer {
this._buf.source(prop, loc); this._buf.source(prop, loc);
} }
sourceWithOffset(prop, loc, columnOffset) { sourceWithOffset(prop, loc, columnOffset) {
if (!loc) return; if (!loc || this.format.preserveFormat) return;
this._catchUp(prop, loc); this._catchUp(prop, loc);
this._buf.sourceWithOffset(prop, loc, columnOffset); this._buf.sourceWithOffset(prop, loc, columnOffset);
} }
@ -199,22 +250,29 @@ class Printer {
_newline() { _newline() {
this._queue(10); this._queue(10);
} }
_append(str, maybeNewline) { _append(str, maybeNewline, occurrenceCount = 0) {
this._maybeAddParen(str); if (this.tokenMap) {
const token = this.tokenMap.findMatching(this._currentNode, str, occurrenceCount);
if (token) this._catchUpTo(token.loc.start);
}
this._maybeIndent(str.charCodeAt(0)); this._maybeIndent(str.charCodeAt(0));
this._buf.append(str, maybeNewline); this._buf.append(str, maybeNewline);
this._endsWithWord = false; this._endsWithWord = false;
this._endsWithInteger = false; this._endsWithInteger = false;
this._endsWithDiv = false;
} }
_appendChar(char) { _appendChar(char) {
this._maybeAddParenChar(char); if (this.tokenMap) {
const token = this.tokenMap.findMatching(this._currentNode, String.fromCharCode(char));
if (token) this._catchUpTo(token.loc.start);
}
this._maybeIndent(char); this._maybeIndent(char);
this._buf.appendChar(char); this._buf.appendChar(char);
this._endsWithWord = false; this._endsWithWord = false;
this._endsWithInteger = false; this._endsWithInteger = false;
this._endsWithDiv = false;
} }
_queue(char) { _queue(char) {
this._maybeAddParenChar(char);
this._maybeIndent(char); this._maybeIndent(char);
this._buf.queue(char); this._buf.queue(char);
this._endsWithWord = false; this._endsWithWord = false;
@ -230,47 +288,6 @@ class Printer {
return true; return true;
} }
} }
_maybeAddParenChar(char) {
const parenPushNewlineState = this._parenPushNewlineState;
if (!parenPushNewlineState) return;
if (char === 32) {
return;
}
if (char !== 10) {
this._parenPushNewlineState = null;
return;
}
this.tokenChar(40);
this.indent();
parenPushNewlineState.printed = true;
}
_maybeAddParen(str) {
const parenPushNewlineState = this._parenPushNewlineState;
if (!parenPushNewlineState) return;
const len = str.length;
let i;
for (i = 0; i < len && str.charCodeAt(i) === 32; i++) continue;
if (i === len) {
return;
}
const cha = str.charCodeAt(i);
if (cha !== 10) {
if (cha !== 47 || i + 1 === len) {
this._parenPushNewlineState = null;
return;
}
const chaPost = str.charCodeAt(i + 1);
if (chaPost === 42) {
return;
} else if (chaPost !== 47) {
this._parenPushNewlineState = null;
return;
}
}
this.tokenChar(40);
this.indent();
parenPushNewlineState.printed = true;
}
catchUp(line) { catchUp(line) {
if (!this.format.retainLines) return; if (!this.format.retainLines) return;
const count = line - this._buf.getCurrentLine(); const count = line - this._buf.getCurrentLine();
@ -279,38 +296,45 @@ class Printer {
} }
} }
_catchUp(prop, loc) { _catchUp(prop, loc) {
var _loc$prop; const {
if (!this.format.retainLines) return; format
const line = loc == null || (_loc$prop = loc[prop]) == null ? void 0 : _loc$prop.line; } = this;
if (line != null) { if (!format.preserveFormat) {
if (format.retainLines && loc != null && loc[prop]) {
this.catchUp(loc[prop].line);
}
return;
}
const pos = loc == null ? void 0 : loc[prop];
if (pos != null) this._catchUpTo(pos);
}
_catchUpTo({
line,
column,
index
}) {
const count = line - this._buf.getCurrentLine(); const count = line - this._buf.getCurrentLine();
if (count > 0 && this._noLineTerminator) {
return;
}
for (let i = 0; i < count; i++) { for (let i = 0; i < count; i++) {
this._newline(); this._newline();
} }
const spacesCount = count > 0 ? column : column - this._buf.getCurrentColumn();
if (spacesCount > 0) {
const spaces = this._originalCode ? this._originalCode.slice(index - spacesCount, index).replace(/[^\t\x0B\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF]/gu, " ") : " ".repeat(spacesCount);
this._append(spaces, false);
} }
} }
_getIndent() { _getIndent() {
return this._indentRepeat * this._indent; return this._indentRepeat * this._indent;
} }
printTerminatorless(node, parent, isLabel) { printTerminatorless(node) {
if (isLabel) {
this._noLineTerminator = true; this._noLineTerminator = true;
this.print(node, parent); this.print(node);
} else {
const terminatorState = {
printed: false
};
this._parenPushNewlineState = terminatorState;
this.print(node, parent);
if (terminatorState.printed) {
this.dedent();
this.newline();
this.tokenChar(41);
} }
} print(node, noLineTerminatorAfter, trailingCommentsLineOffset) {
} var _node$extra, _node$leadingComments, _node$leadingComments2;
print(node, parent, noLineTerminatorAfter, trailingCommentsLineOffset, forceParens) {
var _node$extra, _node$leadingComments;
if (!node) return; if (!node) return;
this._endsWithInnerRaw = false; this._endsWithInnerRaw = false;
const nodeType = node.type; const nodeType = node.type;
@ -323,13 +347,13 @@ class Printer {
if (printMethod === undefined) { if (printMethod === undefined) {
throw new ReferenceError(`unknown node of type ${JSON.stringify(nodeType)} with constructor ${JSON.stringify(node.constructor.name)}`); throw new ReferenceError(`unknown node of type ${JSON.stringify(nodeType)} with constructor ${JSON.stringify(node.constructor.name)}`);
} }
const oldNode = this._currentNode; const parent = this._currentNode;
this._currentNode = node; this._currentNode = node;
const oldInAux = this._insideAux; const oldInAux = this._insideAux;
this._insideAux = node.loc == null; this._insideAux = node.loc == null;
this._maybeAddAuxComment(this._insideAux && !oldInAux); this._maybeAddAuxComment(this._insideAux && !oldInAux);
const parenthesized = (_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized; const parenthesized = (_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized;
let shouldPrintParens = forceParens || parenthesized && format.retainFunctionParens && nodeType === "FunctionExpression" || needsParens(node, parent, this.tokenContext, this.inForStatementInit); let shouldPrintParens = parenthesized && format.preserveFormat || parenthesized && format.retainFunctionParens && nodeType === "FunctionExpression" || needsParens(node, parent, this.tokenContext, this.inForStatementInit, format.preserveFormat ? this._boundGetRawIdentifier : undefined);
if (!shouldPrintParens && parenthesized && (_node$leadingComments = node.leadingComments) != null && _node$leadingComments.length && node.leadingComments[0].type === "CommentBlock") { if (!shouldPrintParens && parenthesized && (_node$leadingComments = node.leadingComments) != null && _node$leadingComments.length && node.leadingComments[0].type === "CommentBlock") {
const parentType = parent == null ? void 0 : parent.type; const parentType = parent == null ? void 0 : parent.type;
switch (parentType) { switch (parentType) {
@ -346,11 +370,35 @@ class Printer {
shouldPrintParens = true; shouldPrintParens = true;
} }
} }
let exitInForStatementInit; let indentParenthesized = false;
if (!shouldPrintParens && this._noLineTerminator && ((_node$leadingComments2 = node.leadingComments) != null && _node$leadingComments2.some(commentIsNewline) || this.format.retainLines && node.loc && node.loc.start.line > this._buf.getCurrentLine())) {
shouldPrintParens = true;
indentParenthesized = true;
}
let oldNoLineTerminatorAfterNode;
let oldInForStatementInitWasTrue;
if (!shouldPrintParens) {
noLineTerminatorAfter || (noLineTerminatorAfter = parent && this._noLineTerminatorAfterNode === parent && n.isLastChild(parent, node));
if (noLineTerminatorAfter) {
var _node$trailingComment;
if ((_node$trailingComment = node.trailingComments) != null && _node$trailingComment.some(commentIsNewline)) {
if (isExpression(node)) shouldPrintParens = true;
} else {
oldNoLineTerminatorAfterNode = this._noLineTerminatorAfterNode;
this._noLineTerminatorAfterNode = node;
}
}
}
if (shouldPrintParens) { if (shouldPrintParens) {
this.tokenChar(40); this.tokenChar(40);
if (indentParenthesized) this.indent();
this._endsWithInnerRaw = false; this._endsWithInnerRaw = false;
exitInForStatementInit = this.enterForStatementInit(false); if (this.inForStatementInit) {
oldInForStatementInitWasTrue = true;
this.inForStatementInit = false;
}
oldNoLineTerminatorAfterNode = this._noLineTerminatorAfterNode;
this._noLineTerminatorAfterNode = null;
} }
this._lastCommentLine = 0; this._lastCommentLine = 0;
this._printLeadingComments(node, parent); this._printLeadingComments(node, parent);
@ -358,18 +406,25 @@ class Printer {
this.exactSource(loc, printMethod.bind(this, node, parent)); this.exactSource(loc, printMethod.bind(this, node, parent));
if (shouldPrintParens) { if (shouldPrintParens) {
this._printTrailingComments(node, parent); this._printTrailingComments(node, parent);
if (indentParenthesized) {
this.dedent();
this.newline();
}
this.tokenChar(41); this.tokenChar(41);
this._noLineTerminator = noLineTerminatorAfter; this._noLineTerminator = noLineTerminatorAfter;
exitInForStatementInit(); if (oldInForStatementInitWasTrue) this.inForStatementInit = true;
} else if (noLineTerminatorAfter && !this._noLineTerminator) { } else if (noLineTerminatorAfter && !this._noLineTerminator) {
this._noLineTerminator = true; this._noLineTerminator = true;
this._printTrailingComments(node, parent); this._printTrailingComments(node, parent);
} else { } else {
this._printTrailingComments(node, parent, trailingCommentsLineOffset); this._printTrailingComments(node, parent, trailingCommentsLineOffset);
} }
this._currentNode = oldNode; this._currentNode = parent;
format.concise = oldConcise; format.concise = oldConcise;
this._insideAux = oldInAux; this._insideAux = oldInAux;
if (oldNoLineTerminatorAfterNode !== undefined) {
this._noLineTerminatorAfterNode = oldNoLineTerminatorAfterNode;
}
this._endsWithInnerRaw = false; this._endsWithInnerRaw = false;
} }
_maybeAddAuxComment(enteredPositionlessNode) { _maybeAddAuxComment(enteredPositionlessNode) {
@ -404,7 +459,7 @@ class Printer {
return extra.raw; return extra.raw;
} }
} }
printJoin(nodes, parent, opts = {}) { printJoin(nodes, opts = {}) {
if (!(nodes != null && nodes.length)) return; if (!(nodes != null && nodes.length)) return;
let { let {
indent indent
@ -427,12 +482,14 @@ class Printer {
const node = nodes[i]; const node = nodes[i];
if (!node) continue; if (!node) continue;
if (opts.statement) this._printNewline(i === 0, newlineOpts); if (opts.statement) this._printNewline(i === 0, newlineOpts);
this.print(node, parent, undefined, opts.trailingCommentsLineOffset || 0); this.print(node, undefined, opts.trailingCommentsLineOffset || 0);
opts.iterator == null || opts.iterator(node, i); opts.iterator == null || opts.iterator(node, i);
if (i < len - 1) separator == null || separator(); if (separator != null) {
if (i < len - 1) separator(i, false);else if (opts.printTrailingSeparator) separator(i, true);
}
if (opts.statement) { if (opts.statement) {
var _node$trailingComment; var _node$trailingComment2;
if (!((_node$trailingComment = node.trailingComments) != null && _node$trailingComment.length)) { if (!((_node$trailingComment2 = node.trailingComments) != null && _node$trailingComment2.length)) {
this._lastCommentLine = 0; this._lastCommentLine = 0;
} }
if (i + 1 === len) { if (i + 1 === len) {
@ -447,10 +504,10 @@ class Printer {
} }
if (indent) this.dedent(); if (indent) this.dedent();
} }
printAndIndentOnComments(node, parent) { printAndIndentOnComments(node) {
const indent = node.leadingComments && node.leadingComments.length > 0; const indent = node.leadingComments && node.leadingComments.length > 0;
if (indent) this.indent(); if (indent) this.indent();
this.print(node, parent); this.print(node);
if (indent) this.dedent(); if (indent) this.dedent();
} }
printBlock(parent) { printBlock(parent) {
@ -458,7 +515,7 @@ class Printer {
if (node.type !== "EmptyStatement") { if (node.type !== "EmptyStatement") {
this.space(); this.space();
} }
this.print(node, parent); this.print(node);
} }
_printTrailingComments(node, parent, lineOffset) { _printTrailingComments(node, parent, lineOffset) {
const { const {
@ -477,12 +534,15 @@ class Printer {
if (!(comments != null && comments.length)) return; if (!(comments != null && comments.length)) return;
this._printComments(0, comments, node, parent); this._printComments(0, comments, node, parent);
} }
_maybePrintInnerComments() { _maybePrintInnerComments(nextTokenStr, nextTokenOccurrenceCount) {
if (this._endsWithInnerRaw) this.printInnerComments(); if (this._endsWithInnerRaw) {
var _this$tokenMap;
this.printInnerComments((_this$tokenMap = this.tokenMap) == null ? void 0 : _this$tokenMap.findMatching(this._currentNode, nextTokenStr, nextTokenOccurrenceCount));
}
this._endsWithInnerRaw = true; this._endsWithInnerRaw = true;
this._indentInnerComments = true; this._indentInnerComments = true;
} }
printInnerComments() { printInnerComments(nextToken) {
const node = this._currentNode; const node = this._currentNode;
const comments = node.innerComments; const comments = node.innerComments;
if (!(comments != null && comments.length)) return; if (!(comments != null && comments.length)) return;
@ -490,7 +550,7 @@ class Printer {
const indent = this._indentInnerComments; const indent = this._indentInnerComments;
const printedCommentsCount = this._printedComments.size; const printedCommentsCount = this._printedComments.size;
if (indent) this.indent(); if (indent) this.indent();
this._printComments(1, comments, node); this._printComments(1, comments, node, undefined, undefined, nextToken);
if (hasSpace && printedCommentsCount !== this._printedComments.size) { if (hasSpace && printedCommentsCount !== this._printedComments.size) {
this.space(); this.space();
} }
@ -499,17 +559,23 @@ class Printer {
noIndentInnerCommentsHere() { noIndentInnerCommentsHere() {
this._indentInnerComments = false; this._indentInnerComments = false;
} }
printSequence(nodes, parent, opts = {}) { printSequence(nodes, opts = {}) {
var _opts$indent; var _opts$indent;
opts.statement = true; opts.statement = true;
(_opts$indent = opts.indent) != null ? _opts$indent : opts.indent = false; (_opts$indent = opts.indent) != null ? _opts$indent : opts.indent = false;
this.printJoin(nodes, parent, opts); this.printJoin(nodes, opts);
} }
printList(items, parent, opts = {}) { printList(items, opts = {}) {
if (opts.separator == null) { if (opts.separator == null) {
opts.separator = commaSeparator; opts.separator = commaSeparator;
} }
this.printJoin(items, parent, opts); this.printJoin(items, opts);
}
shouldPrintTrailingComma(listEnd) {
if (!this.tokenMap) return null;
const listEndIndex = this.tokenMap.findLastIndex(this._currentNode, token => this.tokenMap.matchesOriginal(token, listEnd));
if (listEndIndex <= 0) return null;
return this.tokenMap.matchesOriginal(this._tokens[listEndIndex - 1], ",");
} }
_printNewline(newLine, opts) { _printNewline(newLine, opts) {
const format = this.format; const format = this.format;
@ -534,12 +600,18 @@ class Printer {
this.newline(1); this.newline(1);
} }
} }
_shouldPrintComment(comment) { _shouldPrintComment(comment, nextToken) {
if (comment.ignore) return 0; if (comment.ignore) return 0;
if (this._printedComments.has(comment)) return 0; if (this._printedComments.has(comment)) return 0;
if (this._noLineTerminator && HAS_NEWLINE_OR_BlOCK_COMMENT_END.test(comment.value)) { if (this._noLineTerminator && HAS_NEWLINE_OR_BlOCK_COMMENT_END.test(comment.value)) {
return 2; return 2;
} }
if (nextToken && this.tokenMap) {
const commentTok = this.tokenMap.find(this._currentNode, token => token.value === comment.value);
if (commentTok && commentTok.start > nextToken.start) {
return 2;
}
}
this._printedComments.add(comment); this._printedComments.add(comment);
if (!this.format.shouldPrintComment(comment.value)) { if (!this.format.shouldPrintComment(comment.value)) {
return 0; return 0;
@ -554,19 +626,11 @@ class Printer {
this.newline(1); this.newline(1);
} }
const lastCharCode = this.getLastChar(); const lastCharCode = this.getLastChar();
if (lastCharCode !== 91 && lastCharCode !== 123) { if (lastCharCode !== 91 && lastCharCode !== 123 && lastCharCode !== 40) {
this.space(); this.space();
} }
let val; let val;
if (isBlockComment) { if (isBlockComment) {
const {
_parenPushNewlineState
} = this;
if ((_parenPushNewlineState == null ? void 0 : _parenPushNewlineState.printed) === false && HAS_NEWLINE.test(comment.value)) {
this.tokenChar(40);
this.indent();
_parenPushNewlineState.printed = true;
}
val = `/*${comment.value}*/`; val = `/*${comment.value}*/`;
if (this.format.indent.adjustMultilineComment) { if (this.format.indent.adjustMultilineComment) {
var _comment$loc; var _comment$loc;
@ -590,7 +654,7 @@ class Printer {
} else { } else {
val = `/*${comment.value}*/`; val = `/*${comment.value}*/`;
} }
if (this.endsWith(47)) this._space(); if (this._endsWithDiv) this._space();
this.source("start", comment.loc); this.source("start", comment.loc);
this._append(val, isBlockComment); this._append(val, isBlockComment);
if (!isBlockComment && !noLineTerminator) { if (!isBlockComment && !noLineTerminator) {
@ -600,7 +664,7 @@ class Printer {
this.newline(1); this.newline(1);
} }
} }
_printComments(type, comments, node, parent, lineOffset = 0) { _printComments(type, comments, node, parent, lineOffset = 0, nextToken) {
const nodeLoc = node.loc; const nodeLoc = node.loc;
const len = comments.length; const len = comments.length;
let hasLoc = !!nodeLoc; let hasLoc = !!nodeLoc;
@ -611,7 +675,7 @@ class Printer {
const maybeNewline = this._noLineTerminator ? function () {} : this.newline.bind(this); const maybeNewline = this._noLineTerminator ? function () {} : this.newline.bind(this);
for (let i = 0; i < len; i++) { for (let i = 0; i < len; i++) {
const comment = comments[i]; const comment = comments[i];
const shouldPrint = this._shouldPrintComment(comment); const shouldPrint = this._shouldPrintComment(comment, nextToken);
if (shouldPrint === 2) { if (shouldPrint === 2) {
hasLoc = false; hasLoc = false;
break; break;
@ -684,9 +748,9 @@ Object.assign(Printer.prototype, generatorFunctions);
Printer.prototype.Noop = function Noop() {}; Printer.prototype.Noop = function Noop() {};
} }
var _default = exports.default = Printer; var _default = exports.default = Printer;
function commaSeparator() { function commaSeparator(occurrenceCount, last) {
this.tokenChar(44); this.token(",", false, occurrenceCount);
this.space(); if (!last) this.space();
} }
//# sourceMappingURL=printer.js.map //# sourceMappingURL=printer.js.map

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,6 @@
{ {
"name": "@babel/generator", "name": "@babel/generator",
"version": "7.25.0", "version": "7.26.2",
"description": "Turns an AST into code.", "description": "Turns an AST into code.",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"license": "MIT", "license": "MIT",
@ -19,14 +19,16 @@
"lib" "lib"
], ],
"dependencies": { "dependencies": {
"@babel/types": "^7.25.0", "@babel/parser": "^7.26.2",
"@babel/types": "^7.26.0",
"@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/gen-mapping": "^0.3.5",
"@jridgewell/trace-mapping": "^0.3.25", "@jridgewell/trace-mapping": "^0.3.25",
"jsesc": "^2.5.1" "jsesc": "^3.0.2"
}, },
"devDependencies": { "devDependencies": {
"@babel/helper-fixtures": "^7.24.8", "@babel/core": "^7.26.0",
"@babel/parser": "^7.25.0", "@babel/helper-fixtures": "^7.26.0",
"@babel/plugin-transform-typescript": "^7.25.9",
"@jridgewell/sourcemap-codec": "^1.4.15", "@jridgewell/sourcemap-codec": "^1.4.15",
"@types/jsesc": "^2.5.0", "@types/jsesc": "^2.5.0",
"charcodes": "^0.2.0" "charcodes": "^0.2.0"

View File

@ -1,6 +1,6 @@
{ {
"name": "@babel/helper-annotate-as-pure", "name": "@babel/helper-annotate-as-pure",
"version": "7.24.7", "version": "7.25.9",
"description": "Helper function to annotate paths and nodes with #__PURE__ comment", "description": "Helper function to annotate paths and nodes with #__PURE__ comment",
"repository": { "repository": {
"type": "git", "type": "git",
@ -14,10 +14,10 @@
}, },
"main": "./lib/index.js", "main": "./lib/index.js",
"dependencies": { "dependencies": {
"@babel/types": "^7.24.7" "@babel/types": "^7.25.9"
}, },
"devDependencies": { "devDependencies": {
"@babel/traverse": "^7.24.7" "@babel/traverse": "^7.25.9"
}, },
"engines": { "engines": {
"node": ">=6.9.0" "node": ">=6.9.0"

View File

@ -1,17 +0,0 @@
/* This file is automatically generated by scripts/generators/tsconfig.js */
{
"extends": [
"../../tsconfig.base.json",
"../../tsconfig.paths.json"
],
"include": [
"../../packages/babel-helper-annotate-as-pure/src/**/*.ts",
"../../lib/globals.d.ts",
"../../scripts/repo-utils/*.d.ts"
],
"references": [
{
"path": "../../packages/babel-helper-plugin-utils"
}
]
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,6 @@
{ {
"name": "@babel/helper-builder-binary-assignment-operator-visitor", "name": "@babel/helper-builder-binary-assignment-operator-visitor",
"version": "7.24.7", "version": "7.25.9",
"description": "Helper function to build binary assignment operator visitors", "description": "Helper function to build binary assignment operator visitors",
"repository": { "repository": {
"type": "git", "type": "git",
@ -14,8 +14,8 @@
}, },
"main": "./lib/index.js", "main": "./lib/index.js",
"dependencies": { "dependencies": {
"@babel/traverse": "^7.24.7", "@babel/traverse": "^7.25.9",
"@babel/types": "^7.24.7" "@babel/types": "^7.25.9"
}, },
"engines": { "engines": {
"node": ">=6.9.0" "node": ">=6.9.0"

View File

@ -1,17 +0,0 @@
/* This file is automatically generated by scripts/generators/tsconfig.js */
{
"extends": [
"../../tsconfig.base.json",
"../../tsconfig.paths.json"
],
"include": [
"../../packages/babel-helper-builder-binary-assignment-operator-visitor/src/**/*.ts",
"../../lib/globals.d.ts",
"../../scripts/repo-utils/*.d.ts"
],
"references": [
{
"path": "../../packages/babel-helper-plugin-utils"
}
]
}

File diff suppressed because one or more lines are too long

View File

@ -159,7 +159,8 @@ function getTargets(inputTargets = {}, options = {}) {
esmodules esmodules
} = inputTargets; } = inputTargets;
const { const {
configPath = "." configPath = ".",
onBrowserslistConfigFound
} = options; } = options;
validateBrowsers(browsers); validateBrowsers(browsers);
const input = generateTargets(inputTargets); const input = generateTargets(inputTargets);
@ -168,11 +169,17 @@ function getTargets(inputTargets = {}, options = {}) {
const hasTargets = shouldParseBrowsers || Object.keys(targets).length > 0; const hasTargets = shouldParseBrowsers || Object.keys(targets).length > 0;
const shouldSearchForConfig = !options.ignoreBrowserslistConfig && !hasTargets; const shouldSearchForConfig = !options.ignoreBrowserslistConfig && !hasTargets;
if (!browsers && shouldSearchForConfig) { if (!browsers && shouldSearchForConfig) {
browsers = process.env.BROWSERSLIST;
if (!browsers) {
const configFile = options.configFile || process.env.BROWSERSLIST_CONFIG || _browserslist.findConfigFile(configPath);
if (configFile != null) {
onBrowserslistConfigFound == null || onBrowserslistConfigFound(configFile);
browsers = _browserslist.loadConfig({ browsers = _browserslist.loadConfig({
config: options.configFile, config: configFile,
path: configPath,
env: options.browserslistEnv env: options.browserslistEnv
}); });
}
}
if (browsers == null) { if (browsers == null) {
{ {
browsers = []; browsers = [];

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,6 @@
{ {
"name": "@babel/helper-compilation-targets", "name": "@babel/helper-compilation-targets",
"version": "7.25.2", "version": "7.25.9",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"license": "MIT", "license": "MIT",
"description": "Helper functions on Babel compilation targets", "description": "Helper functions on Babel compilation targets",
@ -25,14 +25,14 @@
"babel-plugin" "babel-plugin"
], ],
"dependencies": { "dependencies": {
"@babel/compat-data": "^7.25.2", "@babel/compat-data": "^7.25.9",
"@babel/helper-validator-option": "^7.24.8", "@babel/helper-validator-option": "^7.25.9",
"browserslist": "^4.23.1", "browserslist": "^4.24.0",
"lru-cache": "^5.1.1", "lru-cache": "^5.1.1",
"semver": "^6.3.1" "semver": "^6.3.1"
}, },
"devDependencies": { "devDependencies": {
"@babel/helper-plugin-test-runner": "^7.24.7", "@babel/helper-plugin-test-runner": "^7.25.9",
"@types/lru-cache": "^5.1.1", "@types/lru-cache": "^5.1.1",
"@types/semver": "^5.5.0" "@types/semver": "^5.5.0"
}, },

View File

@ -50,13 +50,6 @@ function extractElementDescriptor(file, classRef, superRef, path) {
if (path.node.type === "StaticBlock") { if (path.node.type === "StaticBlock") {
throw path.buildCodeFrameError(`Static blocks are not supported in 2018-09 decorator transform, please specify { "version": "2021-12" } instead.`); throw path.buildCodeFrameError(`Static blocks are not supported in 2018-09 decorator transform, please specify { "version": "2021-12" } instead.`);
} }
if (path.isFunction()) {
{
var _path$ensureFunctionN;
(_path$ensureFunctionN = path.ensureFunctionName) != null ? _path$ensureFunctionN : path.ensureFunctionName = require("@babel/traverse").NodePath.prototype.ensureFunctionName;
}
path.ensureFunctionName(false);
}
const { const {
node, node,
scope scope
@ -71,8 +64,13 @@ function extractElementDescriptor(file, classRef, superRef, path) {
}).replace(); }).replace();
} }
const properties = [prop("kind", _core.types.stringLiteral(_core.types.isClassMethod(node) ? node.kind : "field")), prop("decorators", takeDecorators(node)), prop("static", node.static && _core.types.booleanLiteral(true)), prop("key", getKey(node))].filter(Boolean); const properties = [prop("kind", _core.types.stringLiteral(_core.types.isClassMethod(node) ? node.kind : "field")), prop("decorators", takeDecorators(node)), prop("static", node.static && _core.types.booleanLiteral(true)), prop("key", getKey(node))].filter(Boolean);
if (_core.types.isClassMethod(node)) { if (isMethod) {
properties.push(prop("value", _core.types.toExpression(node))); {
var _path$ensureFunctionN;
(_path$ensureFunctionN = path.ensureFunctionName) != null ? _path$ensureFunctionN : path.ensureFunctionName = require("@babel/traverse").NodePath.prototype.ensureFunctionName;
}
path.ensureFunctionName(false);
properties.push(prop("value", _core.types.toExpression(path.node)));
} else if (_core.types.isClassProperty(node) && node.value) { } else if (_core.types.isClassProperty(node) && node.value) {
properties.push(method("value", _core.template.statements.ast`return ${node.value}`)); properties.push(method("value", _core.template.statements.ast`return ${node.value}`));
} else { } else {

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -95,12 +95,12 @@ function createClassFeaturePlugin({
(0, _features.enableFeature)(file, feature, loose); (0, _features.enableFeature)(file, feature, loose);
{ {
if (typeof file.get(versionKey) === "number") { if (typeof file.get(versionKey) === "number") {
file.set(versionKey, "7.25.0"); file.set(versionKey, "7.25.9");
return; return;
} }
} }
if (!file.get(versionKey) || _semver.lt(file.get(versionKey), "7.25.0")) { if (!file.get(versionKey) || _semver.lt(file.get(versionKey), "7.25.9")) {
file.set(versionKey, "7.25.0"); file.set(versionKey, "7.25.9");
} }
}, },
visitor: { visitor: {
@ -108,7 +108,7 @@ function createClassFeaturePlugin({
file file
}) { }) {
var _ref; var _ref;
if (file.get(versionKey) !== "7.25.0") return; if (file.get(versionKey) !== "7.25.9") return;
if (!(0, _features.shouldTransform)(path, file)) return; if (!(0, _features.shouldTransform)(path, file)) return;
const pathIsClassDeclaration = path.isClassDeclaration(); const pathIsClassDeclaration = path.isClassDeclaration();
if (pathIsClassDeclaration) (0, _typescript.assertFieldTransformed)(path); if (pathIsClassDeclaration) (0, _typescript.assertFieldTransformed)(path);
@ -229,7 +229,7 @@ function createClassFeaturePlugin({
file file
}) { }) {
{ {
if (file.get(versionKey) !== "7.25.0") return; if (file.get(versionKey) !== "7.25.9") return;
const decl = path.get("declaration"); const decl = path.get("declaration");
if (decl.isClassDeclaration() && (0, _decorators2.hasDecorators)(decl.node)) { if (decl.isClassDeclaration() && (0, _decorators2.hasDecorators)(decl.node)) {
if (decl.node.id) { if (decl.node.id) {

View File

@ -1,6 +1,6 @@
{ {
"name": "@babel/helper-create-class-features-plugin", "name": "@babel/helper-create-class-features-plugin",
"version": "7.25.0", "version": "7.25.9",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"license": "MIT", "license": "MIT",
"description": "Compile class public and private fields, private methods and decorators to ES6", "description": "Compile class public and private fields, private methods and decorators to ES6",
@ -18,21 +18,21 @@
"babel-plugin" "babel-plugin"
], ],
"dependencies": { "dependencies": {
"@babel/helper-annotate-as-pure": "^7.24.7", "@babel/helper-annotate-as-pure": "^7.25.9",
"@babel/helper-member-expression-to-functions": "^7.24.8", "@babel/helper-member-expression-to-functions": "^7.25.9",
"@babel/helper-optimise-call-expression": "^7.24.7", "@babel/helper-optimise-call-expression": "^7.25.9",
"@babel/helper-replace-supers": "^7.25.0", "@babel/helper-replace-supers": "^7.25.9",
"@babel/helper-skip-transparent-expression-wrappers": "^7.24.7", "@babel/helper-skip-transparent-expression-wrappers": "^7.25.9",
"@babel/traverse": "^7.25.0", "@babel/traverse": "^7.25.9",
"semver": "^6.3.1" "semver": "^6.3.1"
}, },
"peerDependencies": { "peerDependencies": {
"@babel/core": "^7.0.0" "@babel/core": "^7.0.0"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.24.9", "@babel/core": "^7.25.9",
"@babel/helper-plugin-test-runner": "^7.24.7", "@babel/helper-plugin-test-runner": "^7.25.9",
"@babel/preset-env": "^7.25.0", "@babel/preset-env": "^7.25.9",
"@types/charcodes": "^0.2.0", "@types/charcodes": "^0.2.0",
"charcodes": "^0.2.0" "charcodes": "^0.2.0"
}, },

View File

@ -1,32 +0,0 @@
/* This file is automatically generated by scripts/generators/tsconfig.js */
{
"extends": [
"../../tsconfig.base.json",
"../../tsconfig.paths.json"
],
"include": [
"../../packages/babel-helper-create-class-features-plugin/src/**/*.ts",
"../../lib/globals.d.ts",
"../../scripts/repo-utils/*.d.ts"
],
"references": [
{
"path": "../../packages/babel-helper-plugin-utils"
},
{
"path": "../../packages/babel-helper-annotate-as-pure"
},
{
"path": "../../packages/babel-helper-member-expression-to-functions"
},
{
"path": "../../packages/babel-helper-optimise-call-expression"
},
{
"path": "../../packages/babel-helper-replace-supers"
},
{
"path": "../../packages/babel-helper-skip-transparent-expression-wrappers"
}
]
}

File diff suppressed because one or more lines are too long

View File

@ -49,12 +49,12 @@ function createRegExpFeaturePlugin({
} }
{ {
if (typeof file.get(versionKey) === "number") { if (typeof file.get(versionKey) === "number") {
file.set(versionKey, "7.25.2"); file.set(versionKey, "7.25.9");
return; return;
} }
} }
if (!file.get(versionKey) || _semver.lt(file.get(versionKey), "7.25.2")) { if (!file.get(versionKey) || _semver.lt(file.get(versionKey), "7.25.9")) {
file.set(versionKey, "7.25.2"); file.set(versionKey, "7.25.9");
} }
}, },
visitor: { visitor: {

View File

@ -8,8 +8,8 @@ exports.generateRegexpuOptions = generateRegexpuOptions;
exports.transformFlags = transformFlags; exports.transformFlags = transformFlags;
var _features = require("./features.js"); var _features = require("./features.js");
function generateRegexpuOptions(pattern, toTransform) { function generateRegexpuOptions(pattern, toTransform) {
const feat = (name, ok = "transform") => { const feat = name => {
return (0, _features.hasFeature)(toTransform, _features.FEATURES[name]) ? ok : false; return (0, _features.hasFeature)(toTransform, _features.FEATURES[name]) ? "transform" : false;
}; };
const featDuplicateNamedGroups = () => { const featDuplicateNamedGroups = () => {
if (!feat("duplicateNamedCaptureGroups")) return false; if (!feat("duplicateNamedCaptureGroups")) return false;
@ -22,7 +22,7 @@ function generateRegexpuOptions(pattern, toTransform) {
}; };
return { return {
unicodeFlag: feat("unicodeFlag"), unicodeFlag: feat("unicodeFlag"),
unicodeSetsFlag: feat("unicodeSetsFlag") || "parse", unicodeSetsFlag: feat("unicodeSetsFlag"),
dotAllFlag: feat("dotAllFlag"), dotAllFlag: feat("dotAllFlag"),
unicodePropertyEscapes: feat("unicodePropertyEscape"), unicodePropertyEscapes: feat("unicodePropertyEscape"),
namedGroups: feat("namedCaptureGroups") || featDuplicateNamedGroups(), namedGroups: feat("namedCaptureGroups") || featDuplicateNamedGroups(),

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,6 @@
{ {
"name": "@babel/helper-create-regexp-features-plugin", "name": "@babel/helper-create-regexp-features-plugin",
"version": "7.25.2", "version": "7.25.9",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"license": "MIT", "license": "MIT",
"description": "Compile ESNext Regular Expressions to ES5", "description": "Compile ESNext Regular Expressions to ES5",
@ -18,16 +18,16 @@
"babel-plugin" "babel-plugin"
], ],
"dependencies": { "dependencies": {
"@babel/helper-annotate-as-pure": "^7.24.7", "@babel/helper-annotate-as-pure": "^7.25.9",
"regexpu-core": "^5.3.1", "regexpu-core": "^6.1.1",
"semver": "^6.3.1" "semver": "^6.3.1"
}, },
"peerDependencies": { "peerDependencies": {
"@babel/core": "^7.0.0" "@babel/core": "^7.0.0"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.25.2", "@babel/core": "^7.25.9",
"@babel/helper-plugin-test-runner": "^7.24.7" "@babel/helper-plugin-test-runner": "^7.25.9"
}, },
"engines": { "engines": {
"node": ">=6.9.0" "node": ">=6.9.0"

View File

@ -1,20 +0,0 @@
/* This file is automatically generated by scripts/generators/tsconfig.js */
{
"extends": [
"../../tsconfig.base.json",
"../../tsconfig.paths.json"
],
"include": [
"../../packages/babel-helper-create-regexp-features-plugin/src/**/*.ts",
"../../lib/globals.d.ts",
"../../scripts/repo-utils/*.d.ts"
],
"references": [
{
"path": "../../packages/babel-helper-plugin-utils"
},
{
"path": "../../packages/babel-helper-annotate-as-pure"
}
]
}

File diff suppressed because one or more lines are too long

View File

@ -378,7 +378,7 @@ var usage = (callProvider => {
} }
handleReferencedIdentifier(path); handleReferencedIdentifier(path);
}, },
MemberExpression(path) { "MemberExpression|OptionalMemberExpression"(path) {
const { const {
key, key,
handleAsMemberExpression handleAsMemberExpression

File diff suppressed because one or more lines are too long

View File

@ -382,7 +382,7 @@ var usage = (callProvider => {
} }
handleReferencedIdentifier(path); handleReferencedIdentifier(path);
}, },
MemberExpression(path) { "MemberExpression|OptionalMemberExpression"(path) {
const { const {
key, key,
handleAsMemberExpression handleAsMemberExpression

File diff suppressed because one or more lines are too long

View File

@ -56,7 +56,7 @@ var _default = callProvider => {
} }
handleReferencedIdentifier(path); handleReferencedIdentifier(path);
}, },
MemberExpression(path) { "MemberExpression|OptionalMemberExpression"(path) {
const { const {
key, key,
handleAsMemberExpression handleAsMemberExpression

View File

@ -1,6 +1,6 @@
{ {
"name": "@babel/helper-define-polyfill-provider", "name": "@babel/helper-define-polyfill-provider",
"version": "0.6.2", "version": "0.6.3",
"description": "Babel helper to create your own polyfill provider", "description": "Babel helper to create your own polyfill provider",
"repository": { "repository": {
"type": "git", "type": "git",
@ -55,5 +55,5 @@
"webpack": "^4.42.1", "webpack": "^4.42.1",
"webpack-cli": "^3.3.11" "webpack-cli": "^3.3.11"
}, },
"gitHead": "2da4da8e1a3d87640c88a3cd7e650cbb1c049a33" "gitHead": "66340fb145086a826c496f008f67488367846c09"
} }

Some files were not shown because too many files have changed in this diff Show More