Skip to content

Commit

Permalink
move node specific code into a platform file
Browse files Browse the repository at this point in the history
  • Loading branch information
paperdave committed Mar 2, 2023
1 parent ca8f9df commit 90cc16e
Show file tree
Hide file tree
Showing 17 changed files with 118 additions and 92 deletions.
5 changes: 5 additions & 0 deletions .changeset/calm-ads-beam.md
@@ -0,0 +1,5 @@
---
"@paperdave/logger": minor
---

`writeLine` now accepts no arguments to default to printing a fully blank line
5 changes: 5 additions & 0 deletions .changeset/heavy-toys-tap.md
@@ -0,0 +1,5 @@
---
"@paperdave/logger": minor
---

Fix color issues with printing errors, warn(), and many other places.
5 changes: 5 additions & 0 deletions .changeset/slow-spiders-search.md
@@ -0,0 +1,5 @@
---
"@paperdave/logger": major
---

In options passed to `new Logger()` Remove `error` in favor of `type: "error"`
6 changes: 6 additions & 0 deletions packages/paperdave-logger/local.ts
@@ -0,0 +1,6 @@
import { error, info, warn } from './src';

info('Hello world!');
warn('Hello world!');
info(new Error('Hello world!'));
error(new Error('Hello world!'));
2 changes: 1 addition & 1 deletion packages/paperdave-logger/src/error.ts
Expand Up @@ -122,7 +122,7 @@ export function formatErrorObj(err: Error | PrintableError) {
hideName ? '' : (name ?? 'Error') + ': ',
message ?? 'Unknown error',
description ? '\n' + description : '',
hideStack || !stack ? '' : '\n' + formatStackTrace(err),
hideStack || !stack ? '' : '\n' + chalk.reset(formatStackTrace(err)),
description || (!hideStack && stack) ? '\n' : '',
].join('');
}
Expand Down
1 change: 0 additions & 1 deletion packages/paperdave-logger/src/index.ts
@@ -1,4 +1,3 @@
export * from './deprecated';
export { LogWidget } from './widget';
export { CLIError, type PrintableError } from './error';
export { setLogFilter } from './filter';
Expand Down
29 changes: 11 additions & 18 deletions packages/paperdave-logger/src/log-base.ts
@@ -1,13 +1,10 @@
import chalk from 'chalk';
import chalk, { ChalkInstance } from 'chalk';
import stripAnsi from 'strip-ansi';
import type { ChalkInstance } from 'chalk';
import { writeSync } from 'fs';
import { platformWrite } from '$platform';
import { inspect } from 'util';
import { formatErrorObj } from './error';
import { isLogVisible } from './filter';
import type { CustomLoggerColor, CustomLoggerOptions, StringLike } from './types';
import { LogFunction } from './types';
import { STDERR, STDOUT } from './util';
import { CustomLoggerColor, CustomLoggerOptions, LogFunction, StringLike } from './types';
import { clearWidgets, redrawWidgets } from './widget';

/** Taken from https://github.com/debug-js/debug/blob/d1616622e4d404863c5a98443f755b4006e971dc/src/node.js#L35. */
Expand Down Expand Up @@ -50,11 +47,11 @@ function selectColor(namespace: string) {

function getColor(color: CustomLoggerColor): ChalkInstance {
if (typeof color === 'string') {
return color in chalk ? (chalk.bold as any)[color] : chalk.bold.hex(color);
return color in chalk ? (chalk as any)[color] : chalk.hex(color);
} else if (Array.isArray(color)) {
return chalk.bold.rgb(color[0], color[1], color[2]);
return chalk.rgb(color[0], color[1], color[2]);
}
return chalk.bold.ansi256(color);
return chalk.ansi256(color);
}

const formatImplementation = {
Expand Down Expand Up @@ -114,7 +111,7 @@ export function createLogger(
color = undefined,
coloredText = false,
boldText = false,
error = false,
type = 'info',
debug = false,
} = opts;

Expand All @@ -124,7 +121,7 @@ export function createLogger(
? chalk
: color
? getColor(color)
: chalk.bold.ansi256(selectColor(name));
: chalk.ansi256(selectColor(name));
const coloredName = colorFn.bold(name);

const fn = (fmt: unknown, ...args: any[]) => {
Expand All @@ -136,14 +133,10 @@ export function createLogger(

clearWidgets();
if (fmt === undefined && args.length === 0) {
writeSync(error ? STDERR : STDOUT, '\n');
platformWrite[type]('');
} else {
writeSync(
error ? STDERR : STDOUT,
coloredName +
' ' +
(coloredText ? (boldText ? colorFn.bold(data) : colorFn(data)) : data) +
'\n'
platformWrite[type](
coloredName + ' ' + (coloredText ? (boldText ? colorFn.bold(data) : colorFn(data)) : data)
);
}
redrawWidgets();
Expand Down
16 changes: 9 additions & 7 deletions packages/paperdave-logger/src/log.ts
@@ -1,8 +1,7 @@
import { writeSync } from 'node:fs';
import { platformWrite } from '$platform';
import { formatStackTrace } from './error';
import { createLogger } from './log-base';
import { logSymbols } from './unicode';
import { STDERR, STDOUT } from './util';
import { clearWidgets, redrawWidgets } from './widget';

/** Built in blue "info" logger. */
Expand All @@ -18,23 +17,25 @@ export const warn = createLogger('warn', {

const _trace = createLogger('trace', {
color: 208,
error: true,
type: 'error',
});

/** Built in orange "trace" logger. Prints a stack trace after the message. */
export const trace = function trace(...data: any[]) {
if (_trace.visible) {
_trace(...(data.length === 0 ? [' '] : data));
writeSync(STDERR, formatStackTrace(new Error()).split('\n').slice(1).join('\n') + '\n');
platformWrite.error(formatStackTrace(new Error()).split('\n').slice(1).join('\n'));
}
} as typeof _trace;
Object.defineProperty(trace, 'visible', { get: () => _trace.visible });

/** Built in red "error" logger, uses a unicode X instead of the word Error. */
export const error = createLogger(logSymbols.error, {
id: 'error',
color: 'redBright',
coloredText: true,
error: true,
boldText: true,
type: 'error',
});

/** Built in cyan "debug" logger. */
Expand All @@ -48,11 +49,12 @@ export const success = createLogger(logSymbols.success, {
id: 'success',
color: 'greenBright',
coloredText: true,
boldText: true,
});

/** Writes raw line of text without a prefix or filtering. Does NOT support formatting features. */
export function writeLine(message: string) {
export function writeLine(message = '') {
clearWidgets();
writeSync(STDOUT, message + '\n');
platformWrite.info(message);
redrawWidgets();
}
15 changes: 15 additions & 0 deletions packages/paperdave-logger/src/platform/browser.ts
@@ -0,0 +1,15 @@
/* eslint-disable no-console */
const _console = { ...console };

export function platformWriteWidgetText() {}

export const platformWidgetEnabled = false;

export const platformWrite = {
info: _console.log,
error: _console.error,
warn: _console.warn,
debug: _console.debug,
};

export const platformUnicodeSupported = true;
43 changes: 43 additions & 0 deletions packages/paperdave-logger/src/platform/node-bun.ts
@@ -0,0 +1,43 @@
import { writeSync } from 'fs';

/** File Descriptor for standard output. */
export const STDOUT = 1;

/** File Descriptor for standard error. */
export const STDERR = 2;

/** File Descriptor for standard input. */
export const STDIN = 0;

export const platformWidgetEnabled = true;

export const platformWrite = {
info(content: string) {
writeSync(STDOUT, content + '\n');
},
error(content: string) {
writeSync(STDERR, content + '\n');
},
warn(content: string) {
writeSync(STDOUT, content + '\n');
},
debug(content: string) {
writeSync(STDOUT, content + '\n');
},
widget(content: string) {
writeSync(STDERR, content);
},
};

// Inlined from
// https://github.com/sindresorhus/is-unicode-supported/blob/main/index.js
export const platformUnicodeSupported =
process.platform === 'win32'
? Boolean(process.env.CI) ||
Boolean(process.env.WT_SESSION) || // Windows Terminal
process.env.ConEmuTask === '{cmd::Cmder}' || // ConEmu and cmder
process.env.TERM_PROGRAM === 'vscode' ||
process.env.TERM === 'xterm-256color' ||
process.env.TERM === 'alacritty' ||
process.env.TERMINAL_EMULATOR === 'JetBrains-JediTerm'
: process.env.TERM !== 'linux';
4 changes: 2 additions & 2 deletions packages/paperdave-logger/src/progress.ts
@@ -1,9 +1,9 @@
import chalk from 'chalk';
import type { EmptyObject } from '@paperdave/utils';
import { EmptyObject } from '@paperdave/utils';
import { convertHSVtoRGB } from './hsv';
import { defaultSpinnerOptions } from './spinner';
import { isUnicodeSupported } from './unicode';
import type { Color } from './util';
import { Color } from './util';
import { LogWidget } from './widget';

const boxChars = [' ', '▏', '▎', '▍', '▌', '▋', '▊', '▉'];
Expand Down
2 changes: 1 addition & 1 deletion packages/paperdave-logger/src/spinner.ts
@@ -1,5 +1,5 @@
import chalk from 'chalk';
import type { EmptyObject } from '@paperdave/utils';
import { EmptyObject } from '@paperdave/utils';
import { Color } from './util';
import { LogWidget } from './widget';

Expand Down
41 changes: 0 additions & 41 deletions packages/paperdave-logger/src/stdin.ts

This file was deleted.

4 changes: 3 additions & 1 deletion packages/paperdave-logger/src/types.ts
Expand Up @@ -21,13 +21,15 @@ export type CustomLoggerColor =
| number
| [number, number, number];

export type LogType = 'info' | 'warn' | 'debug' | 'error';

export interface CustomLoggerOptions {
id?: string;
color?: CustomLoggerColor;
coloredText?: boolean;
boldText?: boolean;
level?: number;
error?: boolean;
type?: LogType;
debug?: boolean;
}

Expand Down
14 changes: 2 additions & 12 deletions packages/paperdave-logger/src/unicode.ts
@@ -1,20 +1,10 @@
// Inlined from
// https://github.com/sindresorhus/is-unicode-supported/blob/main/index.js
import { platformUnicodeSupported } from '$platform';

/**
* Boolean if the current environment supports unicode. Functions identically to the
* `is-unicode-supported` package.
*/
export const isUnicodeSupported =
process.platform === 'win32'
? Boolean(process.env.CI) ||
Boolean(process.env.WT_SESSION) || // Windows Terminal
process.env.ConEmuTask === '{cmd::Cmder}' || // ConEmu and cmder
process.env.TERM_PROGRAM === 'vscode' ||
process.env.TERM === 'xterm-256color' ||
process.env.TERM === 'alacritty' ||
process.env.TERMINAL_EMULATOR === 'JetBrains-JediTerm'
: process.env.TERM !== 'linux';
export const isUnicodeSupported = platformUnicodeSupported;

// Inlined without chalk from
// https://github.com/sindresorhus/log-symbols/blob/main/index.js
Expand Down
13 changes: 6 additions & 7 deletions packages/paperdave-logger/src/widget.ts
@@ -1,13 +1,14 @@
import ansi from 'ansi-escapes';
import type { Timer } from '@paperdave/utils';
import { platformWidgetEnabled, platformWrite } from '$platform';
import { Timer } from '@paperdave/utils';
import { writeSync } from 'fs';
import { error, success } from './log';
import { STDERR, STDOUT } from './util';
import { STDOUT } from './util';

const widgets: LogWidget[] = [];
let widgetLineCount = 0;
let widgetTimer: Timer | undefined;
let widgetDrawingDisabled = 0;
let widgetDrawingDisabled = platformWidgetEnabled ? 0 : Infinity;

/**
* A Log Widget is a piece of log content that is held at the bottom of the console log, and can be
Expand All @@ -19,7 +20,6 @@ export abstract class LogWidget {

if (!widgetTimer) {
widgetTimer = setInterval(redrawWidgets, 1000 / 60);
// writeSync(STDERR, ansi.cursorHide);
}
}

Expand Down Expand Up @@ -119,8 +119,7 @@ export abstract class LogWidget {

export function clearWidgets() {
if (widgetLineCount) {
writeSync(
STDERR,
platformWrite.widget(
ansi.eraseLine + (ansi.cursorUp(1) + ansi.eraseLine).repeat(widgetLineCount) + '\r'
);
widgetLineCount = 0;
Expand All @@ -137,7 +136,7 @@ export function redrawWidgets() {

if (hasUpdate || widgetLineCount === 0) {
clearWidgets();
writeSync(STDERR, widgets.map(widget => widget['__internalGetText']()).join(''));
platformWrite.widget(widgets.map(widget => widget['__internalGetText']()).join(''));
}
}

Expand Down
5 changes: 4 additions & 1 deletion packages/paperdave-logger/tsconfig.json
Expand Up @@ -14,7 +14,10 @@
"allowJs": true,
"checkJs": true,
"strict": true,
"declarationDir": "dist"
"declarationDir": "dist",
"paths": {
"$platform": ["./src/platform/node-bun.ts"]
}
},
"exclude": ["**/dist"],
"include": ["src/**/*.ts", "src/**/*.js"]
Expand Down

0 comments on commit 90cc16e

Please sign in to comment.