Skip to content

Commit

Permalink
[Proposal] Swap Chalk for Kleur (#520)
Browse files Browse the repository at this point in the history
* Initial conversion

* Add types for packages that have them

* a few missed re-orderings

* fix typing check

* strip ansi-escapes
  • Loading branch information
stramel authored Jun 22, 2020
1 parent 5ea4e8f commit e7d67ff
Show file tree
Hide file tree
Showing 19 changed files with 1,481 additions and 655 deletions.
1,900 changes: 1,359 additions & 541 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@
"@rollup/plugin-replace": "^2.1.0",
"cacache": "^15.0.0",
"cachedir": "^2.3.0",
"chalk": "^4.0.0",
"chokidar": "^3.4.0",
"compressible": "^2.0.18",
"cosmiconfig": "^6.0.0",
Expand All @@ -74,6 +73,7 @@
"http-proxy": "^1.18.1",
"is-builtin-module": "^3.0.0",
"jsonschema": "^1.2.5",
"kleur": "^4.0.1",
"mime-types": "^2.1.26",
"mkdirp": "^1.0.3",
"npm-run-path": "^4.0.1",
Expand All @@ -100,11 +100,16 @@
"@types/cacache": "^12.0.1",
"@types/compressible": "^2.0.0",
"@types/css-modules-loader-core": "^1.1.0",
"@types/detect-port": "^1.3.0",
"@types/es-module-lexer": "^0.3.0",
"@types/etag": "^1.8.0",
"@types/http-proxy": "^1.17.4",
"@types/mime-types": "^2.1.0",
"@types/mkdirp": "^1.0.0",
"@types/rimraf": "^3.0.0",
"@types/signal-exit": "^3.0.0",
"@types/tar": "^4.0.3",
"@types/validate-npm-package-name": "^3.0.0",
"@types/ws": "^7.2.4",
"cross-env": "^7.0.2",
"dir-compare": "^2.2.0",
Expand Down
6 changes: 3 additions & 3 deletions src/commands/add-rm.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import {CommandOptions} from '../util';
import {command as installCommand} from './install';
import {promises as fs} from 'fs';
import got from 'got';
import path from 'path';
import {promises as fs} from 'fs';
import {CommandOptions} from '../util';
import {command as installCommand} from './install';

export async function addCommand(addValue: string, commandOptions: CommandOptions) {
const {cwd, config, pkgManifest} = commandOptions;
Expand Down
8 changes: 4 additions & 4 deletions src/commands/build.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import chalk from 'chalk';
import {EventEmitter} from 'events';
import execa from 'execa';
import {promises as fs} from 'fs';
import glob from 'glob';
import * as colors from 'kleur/colors';
import mkdirp from 'mkdirp';
import npmRunPath from 'npm-run-path';
import path from 'path';
Expand Down Expand Up @@ -36,7 +36,7 @@ export async function command(commandOptions: CommandOptions) {
const dependencyImportMapLoc = path.join(config.installOptions.dest, 'import-map.json');

// Start with a fresh install of your dependencies, always.
console.log(chalk.yellow('! rebuilding dependencies...'));
console.log(colors.yellow('! rebuilding dependencies...'));
await installCommand(commandOptions);

const messageBus = new EventEmitter();
Expand Down Expand Up @@ -79,7 +79,7 @@ export async function command(commandOptions: CommandOptions) {
const finalDirectoryLoc = config.devOptions.out;

if (config.scripts.length <= 1) {
console.error(chalk.red(`No build scripts found, so nothing to build.`));
console.error(colors.red(`No build scripts found, so nothing to build.`));
console.error(`See https://www.snowpack.dev/#build-scripts for help getting started.`);
return;
}
Expand Down Expand Up @@ -360,7 +360,7 @@ export async function command(commandOptions: CommandOptions) {
msg:
`"plugins": ["@snowpack/plugin-webpack"]\n\n` +
`Connect a bundler plugin to optimize your build for production.\n` +
chalk.dim(`Set "devOptions.bundle" configuration to false to remove this message.`),
colors.dim(`Set "devOptions.bundle" configuration to false to remove this message.`),
});
}
} else {
Expand Down
26 changes: 14 additions & 12 deletions src/commands/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
*/

import cacache from 'cacache';
import chalk from 'chalk';
import isCompressible from 'compressible';
import etag from 'etag';
import {EventEmitter} from 'events';
Expand All @@ -34,6 +33,7 @@ import {existsSync, promises as fs, readFileSync} from 'fs';
import http from 'http';
import HttpProxy from 'http-proxy';
import http2 from 'http2';
import * as colors from 'kleur/colors';
import mime from 'mime-types';
import npmRunPath from 'npm-run-path';
import os from 'os';
Expand Down Expand Up @@ -110,8 +110,9 @@ const sendFile = (
ext = '.html',
) => {
const ETag = etag(body, {weak: true});
const contentType = mime.contentType(ext)
const headers: Record<string, string> = {
'Content-Type': mime.contentType(ext) || 'application/octet-stream',
'Content-Type': contentType || 'application/octet-stream',
'Access-Control-Allow-Origin': '*',
ETag,
Vary: 'Accept-Encoding',
Expand All @@ -127,7 +128,8 @@ const sendFile = (
if (
req.headers['cache-control']?.includes('no-transform') ||
['HEAD', 'OPTIONS'].includes(req.method!) ||
!isCompressible(mime.contentType(ext))
!contentType ||
!isCompressible(contentType)
) {
acceptEncoding = '';
}
Expand All @@ -136,7 +138,7 @@ const sendFile = (
if (err) {
res.end();
console.error(
chalk.red(` ✘ An error occurred while compressing ${chalk.bold(req.url)}`),
colors.red(` ✘ An error occurred while compressing ${colors.bold(req.url)}`),
err,
);
}
Expand Down Expand Up @@ -252,7 +254,7 @@ export async function command(commandOptions: CommandOptions) {

// Start with a fresh install of your dependencies, if needed.
if (!(await checkLockfileHash(DEV_DEPENDENCIES_DIR)) || !existsSync(dependencyImportMapLoc)) {
console.log(chalk.yellow('! updating dependencies...'));
console.log(colors.yellow('! updating dependencies...'));
await installCommand(commandOptions);
await updateLockfileHash(DEV_DEPENDENCIES_DIR);
}
Expand Down Expand Up @@ -453,22 +455,22 @@ export async function command(commandOptions: CommandOptions) {
credentials = await readCredentials(cwd);
} catch (e) {
console.error(
chalk.red(
`✘ No HTTPS credentials found! Missing Files: ${chalk.bold(
colors.red(
`✘ No HTTPS credentials found! Missing Files: ${colors.bold(
'snowpack.crt',
)}, ${chalk.bold('snowpack.key')}`,
)}, ${colors.bold('snowpack.key')}`,
),
);
console.log();
console.log('You can automatically generate credentials for your project via either:');
console.log();
console.log(
` - ${chalk.cyan('devcert')}: ${chalk.yellow('npx devcert-cli generate localhost')}`,
` - ${colors.cyan('devcert')}: ${colors.yellow('npx devcert-cli generate localhost')}`,
);
console.log(' https://github.com/davewasmer/devcert-cli (no install required)');
console.log();
console.log(
` - ${chalk.cyan('mkcert')}: ${chalk.yellow(
` - ${colors.cyan('mkcert')}: ${colors.yellow(
'mkcert -install && mkcert -key-file snowpack.key -cert-file snowpack.crt localhost',
)}`,
);
Expand Down Expand Up @@ -632,7 +634,7 @@ export async function command(commandOptions: CommandOptions) {
}

if (!fileLoc) {
const prefix = chalk.red(' ✘ ');
const prefix = colors.red(' ✘ ');
console.error(`[404] ${reqUrl}\n${attemptedFileLoads.map((loc) => prefix + loc).join('\n')}`);
return sendError(res, 404);
}
Expand Down Expand Up @@ -822,7 +824,7 @@ export async function command(commandOptions: CommandOptions) {
}
})
.on('error', (err: Error) => {
console.error(chalk.red(` ✘ Failed to start server at port ${chalk.bold(port)}.`), err);
console.error(colors.red(` ✘ Failed to start server at port ${colors.bold(port)}.`), err);
server.close();
process.exit(1);
})
Expand Down
6 changes: 3 additions & 3 deletions src/commands/esbuildPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import {Service, startService} from 'esbuild';
import * as colors from 'kleur/colors';
import path from 'path';
import {checkIsPreact} from './build-util';
import {SnowpackPluginBuildResult} from '../config';
import chalk from 'chalk';
import {checkIsPreact} from './build-util';

let esbuildService: Service | null = null;

Expand All @@ -17,7 +17,7 @@ export function esbuildPlugin() {
jsxFragment: isPreact ? 'Fragment' : undefined,
});
for (const warning of warnings) {
console.error(chalk.bold('! ') + filePath);
console.error(colors.bold('! ') + filePath);
console.error(' ' + warning.text);
}
return {result: js || ''} as SnowpackPluginBuildResult;
Expand Down
34 changes: 17 additions & 17 deletions src/commands/install.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import {ImportSpecifier, init as initESModuleLexer, parse} from 'es-module-lexer';
import rollupPluginAlias from '@rollup/plugin-alias';
import rollupPluginCommonjs, {RollupCommonJSOptions} from '@rollup/plugin-commonjs';
import rollupPluginJson from '@rollup/plugin-json';
import rollupPluginNodeResolve from '@rollup/plugin-node-resolve';
import rollupPluginReplace from '@rollup/plugin-replace';
import chalk from 'chalk';
import {init as initESModuleLexer, parse} from 'es-module-lexer';
import fs from 'fs';
import * as colors from 'kleur/colors';
import mkdirp from 'mkdirp';
import ora from 'ora';
import path from 'path';
Expand Down Expand Up @@ -62,18 +62,18 @@ const CJS_PACKAGES_TO_AUTO_DETECT = [
];

const cwd = process.cwd();
const banner = chalk.bold(`snowpack`) + ` installing... `;
const banner = colors.bold(`snowpack`) + ` installing... `;
let spinner = ora(banner);
let spinnerHasError = false;
let installResults: [string, InstallResult][] = [];
let dependencyStats: DependencyStatsOutput | null = null;

function defaultLogError(msg: string) {
if (!spinnerHasError) {
spinner.stopAndPersist({symbol: chalk.cyan('⠼')});
spinner.stopAndPersist({symbol: colors.cyan('⠼')});
}
spinnerHasError = true;
spinner = ora(chalk.red(msg));
spinner = ora(colors.red(msg));
spinner.fail();
}

Expand All @@ -85,13 +85,13 @@ function formatInstallResults(): string {
return installResults
.map(([d, result]) => {
if (result === 'SUCCESS') {
return chalk.green(d);
return colors.green(d);
}
if (result === 'ASSET') {
return chalk.yellow(d);
return colors.yellow(d);
}
if (result === 'FAIL') {
return chalk.red(d);
return colors.red(d);
}
return d;
})
Expand Down Expand Up @@ -163,7 +163,7 @@ function resolveWebDependency(dep: string): DependencyLoc {
if (!depManifestLoc || !depManifest) {
throw new ErrorWithHint(
`Package "${dep}" not found. Have you installed it?`,
depManifestLoc ? chalk.italic(depManifestLoc) : '',
depManifestLoc ? colors.italic(depManifestLoc) : '',
);
}
if (
Expand Down Expand Up @@ -330,8 +330,8 @@ export async function install(
if (Object.keys(installEntrypoints).length === 0 && Object.keys(assetEntrypoints).length === 0) {
logError(`No ESM dependencies found!`);
console.log(
chalk.dim(
` At least one dependency must have an ESM "module" entrypoint. You can find modern, web-ready packages at ${chalk.underline(
colors.dim(
` At least one dependency must have an ESM "module" entrypoint. You can find modern, web-ready packages at ${colors.underline(
'https://www.pika.dev',
)}`,
),
Expand All @@ -351,7 +351,7 @@ export async function install(
!!webDependencies &&
rollupPluginDependencyCache({
installTypes,
log: (url) => logUpdate(chalk.dim(url)),
log: (url) => logUpdate(colors.dim(url)),
}),
rollupPluginAlias({
entries: Object.entries(installAlias).map(([alias, mod]) => ({
Expand Down Expand Up @@ -436,7 +436,7 @@ export async function install(
const suggestion = MISSING_PLUGIN_SUGGESTIONS[failedExtension] || err.message;
// Display posix-style on all environments, mainly to help with CI :)
const fileName = errFilePath.replace(cwd + path.sep, '').replace(/\\/g, '/');
logError(`${chalk.bold('snowpack')} failed to load ${chalk.bold(fileName)}\n ${suggestion}`);
logError(`${colors.bold('snowpack')} failed to load ${colors.bold(fileName)}\n ${suggestion}`);
return;
}
}
Expand Down Expand Up @@ -499,19 +499,19 @@ export async function command({cwd, config, lockfile, pkgManifest}: CommandOptio
config,
).catch((err) => {
if (err.loc) {
console.log('\n' + chalk.red.bold(`✘ ${err.loc.file}`));
console.log('\n' + colors.red(colors.bold(`✘ ${err.loc.file}`)));
}
if (err.url) {
console.log(chalk.dim(`👉 ${err.url}`));
console.log(colors.dim(`👉 ${err.url}`));
}
throw err;
});

if (finalResult) {
spinner.succeed(
chalk.bold(`snowpack`) +
colors.bold(`snowpack`) +
` install complete${spinnerHasError ? ' with errors.' : '.'}` +
chalk.dim(` [${((Date.now() - startTime) / 1000).toFixed(2)}s]`),
colors.dim(` [${((Date.now() - startTime) / 1000).toFixed(2)}s]`),
);
if (!!dependencyStats) {
console.log(printStats(dependencyStats));
Expand Down
Loading

0 comments on commit e7d67ff

Please sign in to comment.