Skip to content

Commit

Permalink
refactor: move all options to consola.options without duplication
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Apr 10, 2023
1 parent 5af0e99 commit 2d31ef4
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 75 deletions.
2 changes: 1 addition & 1 deletion examples/index.html
Expand Up @@ -11,7 +11,7 @@

consola.wrapAll();

for (let type of Object.keys(consola._types).sort()) {
for (let type of Object.keys(consola.options.types).sort()) {
consola[type]("Open developer tools to see the magic!");
}

Expand Down
2 changes: 1 addition & 1 deletion examples/index.legacy.html
Expand Up @@ -11,7 +11,7 @@

consola.wrapAll();

for (let type of Object.keys(consola._types).sort()) {
for (let type of Object.keys(consola.options.types).sort()) {
consola[type]("Open developer tools to see the magic!");
}

Expand Down
4 changes: 2 additions & 2 deletions examples/utils/index.ts
Expand Up @@ -8,7 +8,7 @@ export function reporterDemo(reporter) {
reporters: [reporter],
});

for (const type of Object.keys(consola._types).sort()) {
for (const type of Object.keys(consola.options.types).sort()) {
consola[type](randomSentence());
}

Expand All @@ -21,7 +21,7 @@ export function reporterDemo(reporter) {

const tagged = consola.withTag("unjs").withTag("router");

for (const type of Object.keys(consola._types).sort()) {
for (const type of Object.keys(consola.options.types).sort()) {
tagged[type](randomSentence());
}
}
Expand Down
125 changes: 60 additions & 65 deletions src/consola.ts
Expand Up @@ -6,8 +6,6 @@ import type {
ConsolaReporter,
ConsolaLogObject,
logType,
LogLevel,
ConsolaMockFn,
ConsolaReporterLogObject,
} from "./types";
import type { PromptOptions } from "./prompt";
Expand All @@ -16,54 +14,44 @@ let paused = false;
const queue: any[] = [];

export class Consola {
_reporters: ConsolaReporter[];
_types: Record<logType, ConsolaLogObject>;
_level: LogLevel;
_defaults: ConsolaLogObject;
_async: boolean | undefined;
_stdout: any;
_stderr: any;
_mockFn: ConsolaMockFn | undefined;
_throttle: any;
_throttleMin: any;
_prompt: typeof import("./prompt").prompt | undefined;
options: ConsolaOptions;

_lastLogSerialized: any;
_lastLog: any;
_lastLogTime: any;
_lastLogCount: any;
_throttleTimeout: any;

options: ConsolaOptions;

constructor(options: Partial<ConsolaOptions> = {}) {
this.options = options;

this._reporters = options.reporters || [];
this._types = options.types || Types;
this._level = normalizeLogLevel(options.level, this._types);
this._defaults = options.defaults || {};
this._async = options.async !== undefined ? options.async : undefined;
this._stdout = options.stdout;
this._stderr = options.stderr;
this._mockFn = options.mockFn;
this._throttle = options.throttle || 1000;
this._throttleMin = options.throttleMin || 5;
this._prompt = options.prompt;
const types = options.types || Types;
this.options = {
// Defaults
throttle: 1000,
throttleMin: 5,
// User
...options,
// Overrides, Normalizations and Clones
defaults: { ...options.defaults },
level: normalizeLogLevel(options.level, types),
reporters: [...(options.reporters || [])],
types,
};

console.log("this.options", this.options);

// Create logger functions for current instance
for (const type in this._types) {
for (const type in types) {
const defaults: ConsolaLogObject = {
type: type as logType,
...this._types[type as logType],
...this._defaults,
...types[type as logType],
...this.options.defaults,
};
(this as any)[type] = this._wrapLogFn(defaults);
(this as any)[type].raw = this._wrapLogFn(defaults, true);
}

// Use _mockFn if is set
if (this._mockFn) {
if (this.options.mockFn) {
this.mockTypes();
}

Expand All @@ -76,11 +64,15 @@ export class Consola {
}

get level() {
return this._level;
return this.options.level;
}

set level(level) {
this._level = normalizeLogLevel(level, this._types);
this.options.level = normalizeLogLevel(
level,
this.options.types,
this.options.level
);
}

get stdout() {
Expand All @@ -94,56 +86,56 @@ export class Consola {
}

prompt<T extends PromptOptions>(message: string, opts: T) {
if (!this._prompt) {
if (!this.options.prompt) {
throw new Error("prompt is not supported!");
}
return this._prompt<any, any, T>(message, opts);
return this.options.prompt<any, any, T>(message, opts);
}

create(options: ConsolaOptions): ConsolaInstance {
create(options: Partial<ConsolaOptions>): ConsolaInstance {
return new Consola({
reporters: this._reporters,
level: this.level,
types: this._types,
defaults: this._defaults,
stdout: this._stdout,
stderr: this._stderr,
mockFn: this._mockFn,
...this.options,
...options,
}) as ConsolaInstance;
}

withDefaults(defaults: ConsolaLogObject): ConsolaInstance {
return this.create({
defaults: { ...this._defaults, ...defaults },
...this.options,
defaults: {
...this.options.defaults,
...defaults,
},
});
}

withTag(tag: string): ConsolaInstance {
return this.withDefaults({
tag: this._defaults.tag ? this._defaults.tag + ":" + tag : tag,
tag: this.options.defaults.tag
? this.options.defaults.tag + ":" + tag
: tag,
});
}

addReporter(reporter: ConsolaReporter) {
this._reporters.push(reporter);
this.options.reporters.push(reporter);
return this;
}

removeReporter(reporter: ConsolaReporter) {
if (reporter) {
const i = this._reporters.indexOf(reporter);
const i = this.options.reporters.indexOf(reporter);
if (i >= 0) {
return this._reporters.splice(i, 1);
return this.options.reporters.splice(i, 1);
}
} else {
this._reporters.splice(0);
this.options.reporters.splice(0);
}
return this;
}

setReporters(reporters: ConsolaReporter[]) {
this._reporters = Array.isArray(reporters) ? reporters : [reporters];
this.options.reporters = Array.isArray(reporters) ? reporters : [reporters];
return this;
}

Expand All @@ -158,7 +150,7 @@ export class Consola {
}

wrapConsole() {
for (const type in this._types) {
for (const type in this.options.types) {
// Backup original value
if (!(console as any)["__" + type]) {
// eslint-disable-line no-console
Expand All @@ -170,7 +162,7 @@ export class Consola {
}

restoreConsole() {
for (const type in this._types) {
for (const type in this.options.types) {
// Restore if backup is available
if ((console as any)["__" + type]) {
// eslint-disable-line no-console
Expand Down Expand Up @@ -232,15 +224,15 @@ export class Consola {
}

mockTypes(mockFn?: (type: string, currentType: any) => any) {
this._mockFn = mockFn || this._mockFn;
const _mockFn = mockFn || this.options.mockFn;

if (typeof this._mockFn !== "function") {
if (typeof _mockFn !== "function") {
return;
}

for (const type in this._types) {
for (const type in this.options.types) {
(this as any)[type] =
this._mockFn(type as logType, (this as any)._types[type]) ||
_mockFn(type as logType, (this as any)._types[type]) ||
(this as any)[type];
(this as any)[type].raw = (this as any)[type];
}
Expand All @@ -258,7 +250,7 @@ export class Consola {

_logFn(defaults: ConsolaLogObject, args: any[], isRaw?: boolean) {
if (((defaults.level as number) || 0) > this.level) {
return this._async ? Promise.resolve(false) : false;
return this.options.async ? Promise.resolve(false) : false;
}

// Construct a new log object
Expand Down Expand Up @@ -302,7 +294,7 @@ export class Consola {
* we don't want to log a duplicate
*/
const resolveLog = (newLog = false) => {
const repeated = this._lastLogCount - this._throttleMin;
const repeated = this._lastLogCount - this.options.throttleMin;
if (this._lastLog && repeated > 0) {
const args = [...this._lastLog.args];
if (repeated > 1) {
Expand All @@ -315,7 +307,7 @@ export class Consola {
// Log
if (newLog) {
this._lastLog = logObj;
if (this._async) {
if (this.options.async) {
return this._logAsync(logObj as ConsolaReporterLogObject);
} else {
this._log(logObj as ConsolaReporterLogObject);
Expand All @@ -329,7 +321,7 @@ export class Consola {
? (logObj.date as any) - this._lastLogTime
: 0;
this._lastLogTime = logObj.date;
if (diffTime < this._throttle) {
if (diffTime < this.options.throttle) {
try {
const serializedLog = JSON.stringify([
logObj.type,
Expand All @@ -340,9 +332,12 @@ export class Consola {
this._lastLogSerialized = serializedLog;
if (isSameLog) {
this._lastLogCount++;
if (this._lastLogCount > this._throttleMin) {
if (this._lastLogCount > this.options.throttleMin) {
// Auto-resolve when throttle is timed out
this._throttleTimeout = setTimeout(resolveLog, this._throttle);
this._throttleTimeout = setTimeout(
resolveLog,
this.options.throttle
);
return; // SPAM!
}
}
Expand All @@ -355,7 +350,7 @@ export class Consola {
}

_log(logObj: ConsolaReporterLogObject) {
for (const reporter of this._reporters) {
for (const reporter of this.options.reporters) {
reporter.log(logObj, {
async: false,
stdout: this.stdout,
Expand All @@ -366,7 +361,7 @@ export class Consola {

_logAsync(logObj: ConsolaReporterLogObject) {
return Promise.all(
this._reporters.map((reporter) =>
this.options.reporters.map((reporter) =>
reporter.log(logObj, {
async: true,
stdout: this.stdout,
Expand Down
12 changes: 6 additions & 6 deletions src/types.ts
Expand Up @@ -64,16 +64,16 @@ export interface ConsolaReporter {
}

export interface ConsolaOptions {
reporters?: ConsolaReporter[];
types?: Record<logType, ConsolaLogObject>;
level?: LogLevel;
defaults?: ConsolaLogObject;
reporters: ConsolaReporter[];
types: Record<logType, ConsolaLogObject>;
level: LogLevel;
defaults: ConsolaLogObject;
throttle: number;
throttleMin: number;
async?: boolean;
stdout?: NodeJS.WritableStream;
stderr?: NodeJS.WritableStream;
mockFn?: ConsolaMockFn;
throttle?: number;
throttleMin?: number;
prompt?: typeof import("./prompt").prompt | undefined;
}

Expand Down

0 comments on commit 2d31ef4

Please sign in to comment.