Skip to content

Commit

Permalink
Replace chalk with picocolors (#16359)
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed Mar 19, 2024
1 parent 3a255c8 commit f356584
Show file tree
Hide file tree
Showing 14 changed files with 160 additions and 164 deletions.
16 changes: 8 additions & 8 deletions Gulpfile.mjs
Expand Up @@ -5,7 +5,7 @@ import { createRequire } from "module";
import { fileURLToPath } from "url";
import plumber from "gulp-plumber";
import through from "through2";
import chalk from "chalk";
import colors from "picocolors";
import filter from "gulp-filter";
import gulp from "gulp";
import { rollup } from "rollup";
Expand Down Expand Up @@ -125,7 +125,7 @@ function generateHelpers(generator, dest, filename, message) {
file.contents = Buffer.from(
await formatCode(await generateCode(filename), dest + file.path)
);
log(`${chalk.green("✔")} Generated ${message}`);
log(`${colors.green("✔")} Generated ${message}`);
callback(null, file);
})
)
Expand Down Expand Up @@ -352,7 +352,7 @@ function buildRollup(packages, buildStandalone) {
/@babel\/preset-modules\/.*/,
];

log(`Compiling '${chalk.cyan(input)}' with rollup ...`);
log(`Compiling '${colors.cyan(input)}' with rollup ...`);
const bundle = await rollup({
input,
external: buildStandalone ? [] : external,
Expand Down Expand Up @@ -562,15 +562,15 @@ function buildRollup(packages, buildStandalone) {

if (!process.env.IS_PUBLISH) {
log(
chalk.yellow(
`Skipped minification of '${chalk.cyan(
colors.yellow(
`Skipped minification of '${colors.cyan(
outputFile
)}' because not publishing`
)
);
return undefined;
}
log(`Minifying '${chalk.cyan(outputFile)}'...`);
log(`Minifying '${colors.cyan(outputFile)}'...`);

await bundle.write({
file: outputFile.replace(/\.js$/, ".min.js"),
Expand All @@ -597,7 +597,7 @@ function buildRollup(packages, buildStandalone) {

function buildRollupDts(packages) {
async function build(input, output, banner) {
log(`Bundling '${chalk.cyan(output)}' with rollup ...`);
log(`Bundling '${colors.cyan(output)}' with rollup ...`);

const bundle = await rollup({
input,
Expand Down Expand Up @@ -837,7 +837,7 @@ ${fs.readFileSync(path.join(path.dirname(input), "license"), "utf8")}*/
gulp.task("build-cjs-bundles", () => {
if (!USE_ESM) {
log(
chalk.yellow(
colors.yellow(
"Skipping CJS-compat bundles for ESM-based builds, because not compiling to ESM"
)
);
Expand Down
10 changes: 2 additions & 8 deletions babel-worker.cjs
Expand Up @@ -2,11 +2,7 @@ const { transformAsync } = require("@babel/core");
const { mkdirSync, statSync, readFileSync, writeFileSync } = require("fs");
const path = require("path");
const { log } = require("./scripts/utils/logger.cjs");

let chalk;
const chalkP = import("chalk").then(ns => {
chalk = ns.default;
});
const colors = require("picocolors");

function needCompile(src, dest) {
let destStat;
Expand All @@ -24,13 +20,11 @@ function needCompile(src, dest) {
}

exports.transform = async function transform(src, dest, opts = {}) {
if (!chalk) await chalkP;

mkdirSync(path.dirname(dest), { recursive: true });
if (!needCompile(src, dest)) {
return;
}
log(`Compiling '${chalk.cyan(src)}'...`);
log(`Compiling '${colors.cyan(src)}'...`);
const content = readFileSync(src, { encoding: "utf8" });
const { code, map } = await transformAsync(content, {
filename: src,
Expand Down
21 changes: 0 additions & 21 deletions babel.config.js
Expand Up @@ -325,10 +325,6 @@ module.exports = function (api) {
test: unambiguousSources.map(normalize),
sourceType: "unambiguous",
},
env === "standalone" && {
test: /chalk/,
plugins: [pluginReplaceNavigator],
},
].filter(Boolean),
};

Expand Down Expand Up @@ -1051,20 +1047,3 @@ function pluginGeneratorOptimization({ types: t }) {
},
};
}

function pluginReplaceNavigator({ template }) {
return {
visitor: {
MemberExpression(path) {
const object = path.get("object");
if (object.isIdentifier({ name: "navigator" })) {
object.replaceWith(
template.expression.ast`
typeof navigator == "object" ? navigator : {}
`
);
}
},
},
};
}
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -49,7 +49,6 @@
"@yarnpkg/types": "^4.0.0",
"babel-plugin-transform-charcodes": "^0.2.0",
"c8": "^8.0.1",
"chalk": "^5.3.0",
"charcodes": "^0.2.0",
"core-js": "^3.31.1",
"eslint": "^8.57.0",
Expand All @@ -71,6 +70,7 @@
"jest-worker": "^30.0.0-alpha.2",
"lint-staged": "^15.2.0",
"mergeiterator": "^1.4.4",
"picocolors": "^1.0.0",
"prettier": "^3.2.5",
"rollup": "^4.9.1",
"rollup-plugin-dts": "^6.1.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/babel-code-frame/package.json
Expand Up @@ -17,7 +17,7 @@
"main": "./lib/index.js",
"dependencies": {
"@babel/highlight": "workspace:^",
"chalk": "condition:BABEL_8_BREAKING ? ^5.3.0 : ^2.4.2 (esm:default|Chalk)"
"picocolors": "^1.0.0"
},
"devDependencies": {
"import-meta-resolve": "^4.0.0",
Expand Down
40 changes: 21 additions & 19 deletions packages/babel-code-frame/src/index.ts
@@ -1,17 +1,19 @@
import highlight, { shouldHighlight } from "@babel/highlight";

import chalk, { Chalk as ChalkClass, type ChalkInstance as Chalk } from "chalk";
import colors, { createColors } from "picocolors";
import type { Colors, Formatter } from "picocolors/types";

let chalkWithForcedColor: Chalk = undefined;
function getChalk(forceColor: boolean) {
const compose: <T, U, V>(f: (gv: U) => V, g: (v: T) => U) => (v: T) => V =
(f, g) => v =>
f(g(v));

let pcWithForcedColor: Colors = undefined;
function getColors(forceColor: boolean) {
if (forceColor) {
chalkWithForcedColor ??= process.env.BABEL_8_BREAKING
? new ChalkClass({ level: 1 })
: // @ts-expect-error .Instance was .constructor in chalk 2
new chalk.constructor({ enabled: true, level: 1 });
return chalkWithForcedColor;
pcWithForcedColor ??= createColors(true);
return pcWithForcedColor;
}
return chalk;
return colors;
}

let deprecationWarningShown = false;
Expand Down Expand Up @@ -49,13 +51,13 @@ export interface Options {
}

/**
* Chalk styles for code frame token types.
* Styles for code frame token types.
*/
function getDefs(chalk: Chalk) {
function getDefs(colors: Colors) {
return {
gutter: chalk.grey,
marker: chalk.red.bold,
message: chalk.red.bold,
gutter: colors.gray,
marker: compose(colors.red, colors.bold),
message: compose(colors.red, colors.bold),
};
}

Expand Down Expand Up @@ -149,10 +151,10 @@ export function codeFrameColumns(
): string {
const highlighted =
(opts.highlightCode || opts.forceColor) && shouldHighlight(opts);
const chalk = getChalk(opts.forceColor);
const defs = getDefs(chalk);
const maybeHighlight = (chalkFn: Chalk, string: string) => {
return highlighted ? chalkFn(string) : string;
const colors = getColors(opts.forceColor);
const defs = getDefs(colors);
const maybeHighlight = (fmt: Formatter, string: string) => {
return highlighted ? fmt(string) : string;
};
const lines = rawLines.split(NEWLINE);
const { start, end, markerLines } = getMarkerLines(loc, lines, opts);
Expand Down Expand Up @@ -210,7 +212,7 @@ export function codeFrameColumns(
}

if (highlighted) {
return chalk.reset(frame);
return colors.reset(frame);
} else {
return frame;
}
Expand Down
69 changes: 27 additions & 42 deletions packages/babel-code-frame/test/index.js
@@ -1,51 +1,35 @@
import { USE_ESM } from "$repo-utils";

import stripAnsi from "strip-ansi";
import chalk from "chalk";
import colors, { createColors } from "picocolors";
import _codeFrame, { codeFrameColumns } from "../lib/index.js";
const codeFrame = _codeFrame.default || _codeFrame;

import { createRequire } from "module";
const require = createRequire(import.meta.url);
const babelHighlightPicocolors = require(
require.resolve("picocolors", {
paths: [require.resolve("@babel/highlight")],
}),
);

describe("@babel/code-frame", function () {
let babelHighlightChalk;
beforeAll(async function () {
if (USE_ESM && process.env.BABEL_8_BREAKING) {
const { resolve } = await import("import-meta-resolve");
({ default: babelHighlightChalk } = await import(
resolve("chalk", resolve("@babel/highlight", import.meta.url))
));
} else {
babelHighlightChalk = require(
require.resolve("chalk", {
paths: [require.resolve("@babel/highlight")],
}),
);
}
});
const compose = (f, g) => v => f(g(v));

function stubColorSupport(supported) {
let originalChalkEnabled;
let originalChalkLevel;
let originalHighlightChalkEnabled;
let originalHighlightChalkLevel;
describe("@babel/code-frame", function () {
function stubColorSupport(colors, supported) {
let originalColorsCopy;

beforeEach(function () {
originalChalkLevel = chalk.level;
originalChalkEnabled = chalk.enabled;
originalHighlightChalkLevel = babelHighlightChalk.level;
originalHighlightChalkEnabled = babelHighlightChalk.enabled;

babelHighlightChalk.level = chalk.level = supported ? 1 : 0;
babelHighlightChalk.enabled = chalk.enabled = supported;
if (supported === colors.isColorSupported) {
originalColorsCopy = null;
} else {
originalColorsCopy = { ...colors };
Object.assign(colors, createColors(supported));
}
});

afterEach(function () {
chalk.level = originalChalkLevel;
chalk.enabled = originalChalkEnabled;
babelHighlightChalk.level = originalHighlightChalkLevel;
babelHighlightChalk.enabled = originalHighlightChalkEnabled;
if (originalColorsCopy) {
Object.assign(colors, originalColorsCopy);
}
});
}

Expand Down Expand Up @@ -139,7 +123,8 @@ describe("@babel/code-frame", function () {
});

describe("when colors are supported", () => {
stubColorSupport(true);
stubColorSupport(colors, true);
stubColorSupport(babelHighlightPicocolors, true);

test("opts.highlightCode", function () {
const rawLines = "console.log('babel')";
Expand Down Expand Up @@ -191,8 +176,8 @@ describe("@babel/code-frame", function () {
);
});
test("opts.forceColor", function () {
const marker = chalk.red.bold;
const gutter = chalk.grey;
const marker = compose(colors.red, colors.bold);
const gutter = colors.gray;

const rawLines = ["", "", "", ""].join("\n");
expect(
Expand All @@ -202,7 +187,7 @@ describe("@babel/code-frame", function () {
forceColor: true,
}),
).toEqual(
chalk.reset(
colors.reset(
[
" " + gutter(" 2 |"),
marker(">") + gutter(" 3 |"),
Expand All @@ -213,8 +198,8 @@ describe("@babel/code-frame", function () {
});

test("jsx", function () {
const gutter = chalk.grey;
const yellow = chalk.yellow;
const gutter = colors.gray;
const yellow = colors.yellow;

const rawLines = ["<div />"].join("\n");

Expand All @@ -228,7 +213,7 @@ describe("@babel/code-frame", function () {
),
).toEqual(
JSON.stringify(
chalk.reset(
colors.reset(
" " +
gutter(" 1 |") +
" " +
Expand Down
5 changes: 3 additions & 2 deletions packages/babel-highlight/package.json
Expand Up @@ -16,8 +16,9 @@
"main": "./lib/index.js",
"dependencies": {
"@babel/helper-validator-identifier": "workspace:^",
"chalk": "condition:BABEL_8_BREAKING ? ^5.3.0 : ^2.4.2 (esm:default|Chalk)",
"js-tokens": "condition:BABEL_8_BREAKING ? ^8.0.0 : ^4.0.0"
"chalk": "condition:BABEL_8_BREAKING ? : ^2.4.2",
"js-tokens": "condition:BABEL_8_BREAKING ? ^8.0.0 : ^4.0.0",
"picocolors": "^1.0.0"
},
"devDependencies": {
"strip-ansi": "^4.0.0"
Expand Down

0 comments on commit f356584

Please sign in to comment.