From 2794ec07104defd9224ae5f23f8b233019f7a69f Mon Sep 17 00:00:00 2001 From: Zen-cronic <83657429+Zen-cronic@users.noreply.github.com> Date: Fri, 12 Jul 2024 12:24:02 -0400 Subject: [PATCH 01/11] added: entryPoint option --- dist/__tests__/e2e/scope-logger-2.test.js | 49 +++++++++++++++++++ dist/__tests__/unit/options.test.js | 3 ++ dist/logger.js | 12 +++-- dist/utils/entryPoint.js | 25 ++++++++++ package-lock.json | 21 +++++--- package.json | 11 +++-- src/__tests__/e2e/scope-logger-2.test.ts | 59 +++++++++++++++++++++++ src/__tests__/unit/options.test.ts | 3 ++ src/logger.ts | 16 ++++-- src/types.ts | 2 + src/utils/entryPoint.ts | 24 +++++++++ 11 files changed, 204 insertions(+), 21 deletions(-) create mode 100644 dist/__tests__/e2e/scope-logger-2.test.js create mode 100644 dist/utils/entryPoint.js create mode 100644 src/__tests__/e2e/scope-logger-2.test.ts create mode 100644 src/utils/entryPoint.ts diff --git a/dist/__tests__/e2e/scope-logger-2.test.js b/dist/__tests__/e2e/scope-logger-2.test.js new file mode 100644 index 0000000..e8b2aa6 --- /dev/null +++ b/dist/__tests__/e2e/scope-logger-2.test.js @@ -0,0 +1,49 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +require("jest-to-log"); +const index_1 = require("../../index"); +const globals_1 = require("@jest/globals"); +describe("scope-logger", () => { + function fn_2() { + const logger = new index_1.NodeLogger("Log tester"); + function inner_fn_2() { + const testVari = 123; + const { logTitle: result } = logger.log({ testVari }); + process.stderr.write(result + "\n"); + // "Log tester: *inner_fn_2* -> *fn_2* -> *Object.*\n"); + } + inner_fn_2(); + } + function fn_3() { + const logger = new index_1.NodeLogger("Log tester"); + const testOuterArr = [1, 2, 3]; + const testInnerArr = [1, 2, 3]; + testOuterArr.map((num) => { + testInnerArr.forEach((num) => { + const { logTitle: result } = logger.log({ num }); + process.stderr.write(result + "\n"); + }); + }); + } + describe("given an array function inside a function call", () => { + it("should log: array fn -> main fn", async () => { + const logger = new index_1.NodeLogger("Log tester"); + const expected = `Log tester: *Array.forEach* -> *fn_1*\n`.repeat(3); + function fn_1() { + const testArr = [1, 2, 3]; + testArr.forEach((number) => { + //the log method uses stdout + logger.log({ number }); + }); + } + //Object.toLogStdoutMatcher + (0, globals_1.expect)(fn_1).toLogStdout(expected); + }); + }); + describe("2) given a nested function inside a function call", () => { + it("should log: inner fn -> outer fn", async () => { }); + }); + describe("3) given a nested array function inside an array function call", () => { + it("should log: inner array fn -> outer array fn -> main fn", async () => { }); + }); +}); diff --git a/dist/__tests__/unit/options.test.js b/dist/__tests__/unit/options.test.js index 27b5c67..624e279 100644 --- a/dist/__tests__/unit/options.test.js +++ b/dist/__tests__/unit/options.test.js @@ -30,6 +30,7 @@ describe("immutability and configurability of option arguments", () => { }); }).not.toThrow(); expect(logger._options).toStrictEqual({ + ...defaultOptions, ignoreIterators: true, onlyFirstElem: true, }); @@ -44,6 +45,7 @@ describe("immutability and configurability of option arguments", () => { }); }).not.toThrow(); expect(logger._options).toStrictEqual({ + ...defaultOptions, ignoreIterators: true, onlyFirstElem: true, }); @@ -57,6 +59,7 @@ describe("immutability and configurability of option arguments", () => { }); }).not.toThrow(); expect(logger._options).toStrictEqual({ + ...defaultOptions, ignoreIterators: false, onlyFirstElem: true, }); diff --git a/dist/logger.js b/dist/logger.js index 9b8ed97..77c4eda 100644 --- a/dist/logger.js +++ b/dist/logger.js @@ -7,6 +7,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function ( var _Logger_instances, _a, _Logger_handleOnlyFirstElem, _Logger_validateArgs, _Logger_setOptions, _Logger_selectColour; Object.defineProperty(exports, "__esModule", { value: true }); exports.Logger = void 0; +const entryPoint_1 = require("./utils/entryPoint"); class Logger { /** * @@ -17,9 +18,12 @@ class Logger { _Logger_instances.add(this); this.args = null; this.namespace = namespace; - this._options = options || Object.assign({}, _a.defaultOptions); this.firstElem = null; _a.colourNum = __classPrivateFieldGet(this, _Logger_instances, "m", _Logger_selectColour).call(this); + this._options = + options !== undefined + ? Object.assign({}, _a.defaultOptions, options) + : Object.assign({}, _a.defaultOptions); if (options) { Object.defineProperty(this, "_options", { value: this._options, @@ -29,7 +33,7 @@ class Logger { }); } //args can change - //_options may change + //_options may change unless set in constructor //namespace cannot change Object.defineProperty(this, "namespace", { value: this.namespace, @@ -48,8 +52,7 @@ class Logger { __classPrivateFieldGet(this, _Logger_instances, "m", _Logger_validateArgs).call(this, args); __classPrivateFieldGet(this, _Logger_instances, "m", _Logger_setOptions).call(this, options); this.args = args; - // let logReturn = this.#handleOnlyFirstElem(err.stack); - let logReturn = __classPrivateFieldGet(this, _Logger_instances, "m", _Logger_handleOnlyFirstElem).call(this, errorStack); + const logReturn = __classPrivateFieldGet(this, _Logger_instances, "m", _Logger_handleOnlyFirstElem).call(this, errorStack); return logReturn; } // /** @@ -228,5 +231,6 @@ Logger.NATIVE_ITERATORS_TYPES = [ Logger.defaultOptions = Object.freeze({ ignoreIterators: false, onlyFirstElem: false, + entryPoint: (0, entryPoint_1.getDefaultEntryPoint)(), }); Logger.colourNum = 7; diff --git a/dist/utils/entryPoint.js b/dist/utils/entryPoint.js new file mode 100644 index 0000000..2a9bcb2 --- /dev/null +++ b/dist/utils/entryPoint.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getDefaultEntryPoint = exports.isESModule = void 0; +function isESModule() { + let isESM = false; + try { + require("assert"); + console.log("is cjs"); + } + catch (error) { + isESM = true; + throw error; + } + return isESM; +} +exports.isESModule = isESModule; +const entryPointMap = { + ESM: "ModuleJob.run", + CJS: "Module._compile", +}; +function getDefaultEntryPoint() { + const isESM = isESModule(); + return isESM ? entryPointMap.ESM : entryPointMap.CJS; +} +exports.getDefaultEntryPoint = getDefaultEntryPoint; diff --git a/package-lock.json b/package-lock.json index 0919c1d..8b93f3e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "@types/jest": "^29.5.12", "@types/node": "^20.12.11", "jest": "^29.7.0", + "jest-to-log": "^1.0.0", "nodemon": "^3.0.3", "ts-jest": "^29.1.2", "ts-node": "^10.9.2", @@ -1418,12 +1419,12 @@ } }, "node_modules/braces": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", "dev": true, "dependencies": { - "fill-range": "^7.0.1" + "fill-range": "^7.1.1" }, "engines": { "node": ">=8" @@ -1913,9 +1914,9 @@ } }, "node_modules/fill-range": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", - "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", "dev": true, "dependencies": { "to-regex-range": "^5.0.1" @@ -2781,6 +2782,12 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/jest-to-log": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/jest-to-log/-/jest-to-log-1.0.0.tgz", + "integrity": "sha512-TmY2pCrrAOcyD/8/TKrKwl6L999FqKSitulmoaM3Lpxk1wXliYmxCpdzDOzRDzr7e5q3saBsuAcYPSAbg/yH8Q==", + "dev": true + }, "node_modules/jest-util": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", diff --git a/package.json b/package.json index ea2e431..c3bce16 100644 --- a/package.json +++ b/package.json @@ -17,15 +17,15 @@ "start": "node index", "build": "tsc --watch", "check:tar": "npm pack && tar -xvzf *.tgz && rm -rf package *.tgz", - "dev:pg": "nodemon --watch \"pg/**\" --ext \"ts,json\" --exec \"ts-node\"", - "dev:tests": "nodemon --watch \"dev/**\" --ext \"ts,json\" --exec \"ts-node\"", - + + "dev:pg": "nodemon --watch \"pg/**\" --ext \"js,ts,json,mjs,cjs\" --exec \"ts-node\"", + "dev:tests": "nodemon --watch \"dev/**\" --ext \"js,ts,json,mjs,cjs\" --exec \"ts-node\"", + "test:jest": "jest --watch", "test:ci": "jest --ci", "test:js": "jest --watch --config jest.config.dist.js", - "test": "set NODE_OPTIONS=-r ts-node/register && jest --watch", - "test:ts:ci":"export NODE_OPTIONS='-r ts-node/register' && jest --ci" + "test:ts:ci": "export NODE_OPTIONS='-r ts-node/register' && jest --ci" }, "keywords": [ "log", @@ -37,6 +37,7 @@ "@types/jest": "^29.5.12", "@types/node": "^20.12.11", "jest": "^29.7.0", + "jest-to-log": "^1.0.0", "nodemon": "^3.0.3", "ts-jest": "^29.1.2", "ts-node": "^10.9.2", diff --git a/src/__tests__/e2e/scope-logger-2.test.ts b/src/__tests__/e2e/scope-logger-2.test.ts new file mode 100644 index 0000000..beed28a --- /dev/null +++ b/src/__tests__/e2e/scope-logger-2.test.ts @@ -0,0 +1,59 @@ +import "jest-to-log"; +import { NodeLogger } from "../../index"; +import { expect } from "@jest/globals"; + +describe("scope-logger", () => { + function fn_2() { + const logger = new NodeLogger("Log tester"); + function inner_fn_2() { + const testVari = 123; + const { logTitle: result } = logger.log({ testVari }); + + process.stderr.write(result + "\n"); + + // "Log tester: *inner_fn_2* -> *fn_2* -> *Object.*\n"); + } + + inner_fn_2(); + } + + function fn_3() { + const logger = new NodeLogger("Log tester"); + + const testOuterArr = [1, 2, 3]; + + const testInnerArr = [1, 2, 3]; + + testOuterArr.map((num) => { + testInnerArr.forEach((num) => { + const { logTitle: result } = logger.log({ num }); + + process.stderr.write(result + "\n"); + }); + }); + } + describe("given an array function inside a function call", () => { + it("should log: array fn -> main fn", async () => { + const logger = new NodeLogger("Log tester"); + const expected = `Log tester: *Array.forEach* -> *fn_1*\n`.repeat(3); + function fn_1() { + const testArr = [1, 2, 3]; + + testArr.forEach((number) => { + //the log method uses stdout + logger.log({ number }); + }); + } + //Object.toLogStdoutMatcher + expect(fn_1).toLogStdout(expected); + }); + }); + + describe("2) given a nested function inside a function call", () => { + it("should log: inner fn -> outer fn", async () => {}); + }); + + describe("3) given a nested array function inside an array function call", () => { + it("should log: inner array fn -> outer array fn -> main fn", async () => {}); + }); +}); diff --git a/src/__tests__/unit/options.test.ts b/src/__tests__/unit/options.test.ts index 9baf650..81c8e3b 100644 --- a/src/__tests__/unit/options.test.ts +++ b/src/__tests__/unit/options.test.ts @@ -37,6 +37,7 @@ describe("immutability and configurability of option arguments", () => { }).not.toThrow(); expect(logger._options).toStrictEqual({ + ...defaultOptions, ignoreIterators: true, onlyFirstElem: true, }); @@ -53,6 +54,7 @@ describe("immutability and configurability of option arguments", () => { }).not.toThrow(); expect(logger._options).toStrictEqual({ + ...defaultOptions, ignoreIterators: true, onlyFirstElem: true, }); @@ -69,6 +71,7 @@ describe("immutability and configurability of option arguments", () => { }).not.toThrow(); expect(logger._options).toStrictEqual({ + ...defaultOptions, ignoreIterators: false, onlyFirstElem: true, }); diff --git a/src/logger.ts b/src/logger.ts index fbb015e..0a003e2 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -1,5 +1,7 @@ "use strict"; +import { getDefaultEntryPoint } from "./utils/entryPoint"; + // TC: same callStackParser implm except entry point function call // _formatLogContent() is same implm for both browser and node @@ -48,14 +50,15 @@ class Logger { static defaultOptions = Object.freeze({ ignoreIterators: false, onlyFirstElem: false, + entryPoint: getDefaultEntryPoint(), }); static colourNum: number = 7; args: Object | null; namespace: string; - _options: LogOptions; firstElem: string | null; + _options: LogOptions; /** * @@ -66,10 +69,14 @@ class Logger { constructor(namespace: string, options?: LogOptions) { this.args = null; this.namespace = namespace; - this._options = options || Object.assign({}, Logger.defaultOptions); this.firstElem = null; Logger.colourNum = this.#selectColour(); + this._options = + options !== undefined + ? Object.assign({}, Logger.defaultOptions, options) + : Object.assign({}, Logger.defaultOptions); + if (options) { Object.defineProperty(this, "_options", { value: this._options, @@ -80,7 +87,7 @@ class Logger { } //args can change - //_options may change + //_options may change unless set in constructor //namespace cannot change Object.defineProperty(this, "namespace", { @@ -108,8 +115,7 @@ class Logger { this.args = args; - // let logReturn = this.#handleOnlyFirstElem(err.stack); - let logReturn = this.#handleOnlyFirstElem(errorStack); + const logReturn = this.#handleOnlyFirstElem(errorStack); return logReturn; } diff --git a/src/types.ts b/src/types.ts index 69966a5..302f131 100644 --- a/src/types.ts +++ b/src/types.ts @@ -7,3 +7,5 @@ export type WorkerMessage = WorkerErrorMessage | WorkerNonErrorMessage; export type NonNullProcessSend = NonNullable; export type FileExt = "js" | "ts"; + +export type DefaultEntryPoint = "ModuleJob.run" | "Module._compile"; diff --git a/src/utils/entryPoint.ts b/src/utils/entryPoint.ts new file mode 100644 index 0000000..37db6db --- /dev/null +++ b/src/utils/entryPoint.ts @@ -0,0 +1,24 @@ +import { type DefaultEntryPoint } from "../types"; + +export function isESModule(): boolean { + let isESM = false; + try { + require("assert"); + console.log("is cjs"); + } catch (error) { + isESM = true; + throw error; + } + return isESM; +} + +const entryPointMap: { ESM: DefaultEntryPoint; CJS: DefaultEntryPoint } = { + ESM: "ModuleJob.run", + CJS: "Module._compile", +}; + +export function getDefaultEntryPoint(): DefaultEntryPoint { + const isESM = isESModule(); + + return isESM ? entryPointMap.ESM : entryPointMap.CJS; +} From 503ab8829d1d4d6db6ad61a6d7686ce7214cf7e4 Mon Sep 17 00:00:00 2001 From: Zen-cronic <83657429+Zen-cronic@users.noreply.github.com> Date: Fri, 12 Jul 2024 12:42:36 -0400 Subject: [PATCH 02/11] added: start test migration --- dist/__tests__/e2e/scope-logger-2.test.js | 23 +++++++++++++++++++-- dist/__tests__/unit/options.test.js | 1 - dist/node.js | 22 +++++++++++++------- src/__tests__/e2e/scope-logger-2.test.ts | 24 ++++++++++++++++++++-- src/__tests__/unit/options.test.ts | 1 - src/logger.ts | 1 + src/node.ts | 25 +++++++++++++++-------- 7 files changed, 76 insertions(+), 21 deletions(-) diff --git a/dist/__tests__/e2e/scope-logger-2.test.js b/dist/__tests__/e2e/scope-logger-2.test.js index e8b2aa6..5a6f3ba 100644 --- a/dist/__tests__/e2e/scope-logger-2.test.js +++ b/dist/__tests__/e2e/scope-logger-2.test.js @@ -27,8 +27,27 @@ describe("scope-logger", () => { } describe("given an array function inside a function call", () => { it("should log: array fn -> main fn", async () => { - const logger = new index_1.NodeLogger("Log tester"); - const expected = `Log tester: *Array.forEach* -> *fn_1*\n`.repeat(3); + const logger = new index_1.NodeLogger("Log tester", { + entryPoint: "Object.toLogStdoutMatcher", + }); + const expected = `Log tester: *Array.forEach* -> *fn_1*` + + "\n" + + "{\n" + + ' "number": 1\n' + + "}\n" + + "\n" + + `Log tester: *Array.forEach* -> *fn_1*` + + "\n" + + "{\n" + + ' "number": 2\n' + + "}\n" + + "\n" + + `Log tester: *Array.forEach* -> *fn_1*` + + "\n" + + "{\n" + + ' "number": 3\n' + + "}\n" + + "\n"; function fn_1() { const testArr = [1, 2, 3]; testArr.forEach((number) => { diff --git a/dist/__tests__/unit/options.test.js b/dist/__tests__/unit/options.test.js index 624e279..2cae89b 100644 --- a/dist/__tests__/unit/options.test.js +++ b/dist/__tests__/unit/options.test.js @@ -11,7 +11,6 @@ describe("immutability and configurability of option arguments", () => { onlyFirstElem: true, }); const calledWith = JSON.stringify(logger._options); - // const escapedCalledWith = calledWith.replace(/\"/g, '\\"'); const expectedErrorMsg = new RegExp(`Cannot redefine _options in the instance if the constructor is called with options.\nAlready called with: ${calledWith}`); expect(() => { testArr.forEach((num) => { diff --git a/dist/node.js b/dist/node.js index 6803a4c..d4350ae 100644 --- a/dist/node.js +++ b/dist/node.js @@ -27,7 +27,8 @@ class NodeLogger extends logger_1.Logger { const currentLine = callStackParts[logLineIndex]; //at" "x" "y let currentLineParts = currentLine.trim().split(" "); - if (!currentLine || currentLineParts[1] === "Module._compile") { + // if (!currentLine || currentLineParts[1] === "Module._compile") { + if (!currentLine || currentLineParts[1] === this._options.entryPoint) { break; } //processTicksAndRejections (unix) | process.processTicksAndRejections @@ -60,12 +61,19 @@ class NodeLogger extends logger_1.Logger { } logTitle = logTitle.concat(`*${calleeFunc}*`, delimiter); } - //" ->" - const testEnvDelimiter = delimiter.trimEnd(); - //dev (or) prod - delimiter - const checkDelimiter = process.env.NODE_ENV === "test" ? testEnvDelimiter : delimiter; - if (logTitle.endsWith(checkDelimiter)) { - logTitle = logTitle.slice(0, -checkDelimiter.length); + // //" ->" + // const testEnvDelimiter = delimiter.trimEnd(); + // //dev (or) prod - delimiter + // const checkDelimiter = + // process.env.NODE_ENV === "test" ? testEnvDelimiter : delimiter; + // if (logTitle.endsWith(checkDelimiter)) { + // logTitle = logTitle.slice(0, -checkDelimiter.length); + // } + //trim cuz concated before break + logTitle = logTitle.trimEnd(); + const trimmedDelimiter = delimiter.trimEnd(); + if (logTitle.endsWith(trimmedDelimiter)) { + logTitle = logTitle.slice(0, -trimmedDelimiter.length); } return logTitle; } diff --git a/src/__tests__/e2e/scope-logger-2.test.ts b/src/__tests__/e2e/scope-logger-2.test.ts index beed28a..d4103e8 100644 --- a/src/__tests__/e2e/scope-logger-2.test.ts +++ b/src/__tests__/e2e/scope-logger-2.test.ts @@ -34,8 +34,28 @@ describe("scope-logger", () => { } describe("given an array function inside a function call", () => { it("should log: array fn -> main fn", async () => { - const logger = new NodeLogger("Log tester"); - const expected = `Log tester: *Array.forEach* -> *fn_1*\n`.repeat(3); + const logger = new NodeLogger("Log tester", { + entryPoint: "Object.toLogStdoutMatcher", + }); + const expected = + `Log tester: *Array.forEach* -> *fn_1*` + + "\n" + + "{\n" + + ' "number": 1\n' + + "}\n" + + "\n" + + `Log tester: *Array.forEach* -> *fn_1*` + + "\n" + + "{\n" + + ' "number": 2\n' + + "}\n" + + "\n" + + `Log tester: *Array.forEach* -> *fn_1*` + + "\n" + + "{\n" + + ' "number": 3\n' + + "}\n" + + "\n"; function fn_1() { const testArr = [1, 2, 3]; diff --git a/src/__tests__/unit/options.test.ts b/src/__tests__/unit/options.test.ts index 81c8e3b..66cfcdd 100644 --- a/src/__tests__/unit/options.test.ts +++ b/src/__tests__/unit/options.test.ts @@ -13,7 +13,6 @@ describe("immutability and configurability of option arguments", () => { const calledWith = JSON.stringify(logger._options); - // const escapedCalledWith = calledWith.replace(/\"/g, '\\"'); const expectedErrorMsg = new RegExp( `Cannot redefine _options in the instance if the constructor is called with options.\nAlready called with: ${calledWith}` ); diff --git a/src/logger.ts b/src/logger.ts index 0a003e2..5dd0db2 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -8,6 +8,7 @@ import { getDefaultEntryPoint } from "./utils/entryPoint"; interface LogOptions { ignoreIterators?: boolean; onlyFirstElem?: boolean; + entryPoint: string; } interface LogReturn { diff --git a/src/node.ts b/src/node.ts index 08e5592..e7d1847 100644 --- a/src/node.ts +++ b/src/node.ts @@ -31,7 +31,8 @@ export class NodeLogger extends Logger implements IEnv { //at" "x" "y let currentLineParts = currentLine.trim().split(" "); - if (!currentLine || currentLineParts[1] === "Module._compile") { + // if (!currentLine || currentLineParts[1] === "Module._compile") { + if (!currentLine || currentLineParts[1] === this._options.entryPoint) { break; } @@ -80,15 +81,23 @@ export class NodeLogger extends Logger implements IEnv { logTitle = logTitle.concat(`*${calleeFunc}*`, delimiter); } - //" ->" - const testEnvDelimiter = delimiter.trimEnd(); + // //" ->" + // const testEnvDelimiter = delimiter.trimEnd(); - //dev (or) prod - delimiter - const checkDelimiter = - process.env.NODE_ENV === "test" ? testEnvDelimiter : delimiter; + // //dev (or) prod - delimiter + // const checkDelimiter = + // process.env.NODE_ENV === "test" ? testEnvDelimiter : delimiter; - if (logTitle.endsWith(checkDelimiter)) { - logTitle = logTitle.slice(0, -checkDelimiter.length); + // if (logTitle.endsWith(checkDelimiter)) { + // logTitle = logTitle.slice(0, -checkDelimiter.length); + // } + + //trim cuz concated before break + logTitle = logTitle.trimEnd(); + const trimmedDelimiter = delimiter.trimEnd(); + + if (logTitle.endsWith(trimmedDelimiter)) { + logTitle = logTitle.slice(0, -trimmedDelimiter.length); } return logTitle; From 50aab7f7f182a94459f161fe97cf746f567c5dc7 Mon Sep 17 00:00:00 2001 From: Zen-cronic <83657429+Zen-cronic@users.noreply.github.com> Date: Fri, 12 Jul 2024 16:44:03 -0400 Subject: [PATCH 03/11] updated: github actions v4 --- .github/workflows/build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a5bdddf..e46617c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -11,9 +11,9 @@ jobs: node-version: [14.x] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Use Node.js Version ${{ matrix.node-version }} - uses: actions/setup-node@v2 + uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} - name: Check shell From 149e1549983f2039062f51ffffea0c1ea97288c7 Mon Sep 17 00:00:00 2001 From: Zen-cronic <83657429+Zen-cronic@users.noreply.github.com> Date: Fri, 12 Jul 2024 18:00:14 -0400 Subject: [PATCH 04/11] updated: _formatLogBody --- dist/__tests__/e2e/scope-logger-2.test.js | 55 +++++++++------ dist/browser.js | 21 +----- dist/logger.js | 27 +++++++ dist/node.js | 15 +--- dist/utils/entryPoint.js | 1 - package.json | 2 +- src/__tests__/e2e/scope-logger-2.test.ts | 65 +++++++++-------- src/browser.ts | 28 +------- src/logger.ts | 41 ++++++++++- src/node.ts | 24 +------ src/utils/entryPoint.ts | 1 - tsconfig.json | 86 ----------------------- 12 files changed, 139 insertions(+), 227 deletions(-) diff --git a/dist/__tests__/e2e/scope-logger-2.test.js b/dist/__tests__/e2e/scope-logger-2.test.js index 5a6f3ba..a5c32fd 100644 --- a/dist/__tests__/e2e/scope-logger-2.test.js +++ b/dist/__tests__/e2e/scope-logger-2.test.js @@ -4,16 +4,6 @@ require("jest-to-log"); const index_1 = require("../../index"); const globals_1 = require("@jest/globals"); describe("scope-logger", () => { - function fn_2() { - const logger = new index_1.NodeLogger("Log tester"); - function inner_fn_2() { - const testVari = 123; - const { logTitle: result } = logger.log({ testVari }); - process.stderr.write(result + "\n"); - // "Log tester: *inner_fn_2* -> *fn_2* -> *Object.*\n"); - } - inner_fn_2(); - } function fn_3() { const logger = new index_1.NodeLogger("Log tester"); const testOuterArr = [1, 2, 3]; @@ -26,41 +16,60 @@ describe("scope-logger", () => { }); } describe("given an array function inside a function call", () => { - it("should log: array fn -> main fn", async () => { + it("should log: array fn -> main fn", () => { const logger = new index_1.NodeLogger("Log tester", { entryPoint: "Object.toLogStdoutMatcher", }); - const expected = `Log tester: *Array.forEach* -> *fn_1*` + + function testFn() { + const testArr = [1, 2, 3]; + testArr.forEach((number) => { + logger.log({ number }); + }); + } + //w/ JSON.stringify(_, _, 2) for logBody + const expectedStr = `Log tester: *Array.forEach* -> *testFn*` + "\n" + "{\n" + ' "number": 1\n' + "}\n" + "\n" + - `Log tester: *Array.forEach* -> *fn_1*` + + `Log tester: *Array.forEach* -> *testFn*` + "\n" + "{\n" + ' "number": 2\n' + "}\n" + "\n" + - `Log tester: *Array.forEach* -> *fn_1*` + + `Log tester: *Array.forEach* -> *testFn*` + "\n" + "{\n" + ' "number": 3\n' + "}\n" + "\n"; - function fn_1() { - const testArr = [1, 2, 3]; - testArr.forEach((number) => { - //the log method uses stdout - logger.log({ number }); - }); - } //Object.toLogStdoutMatcher - (0, globals_1.expect)(fn_1).toLogStdout(expected); + (0, globals_1.expect)(testFn).toLogStdout(expectedStr); }); }); describe("2) given a nested function inside a function call", () => { - it("should log: inner fn -> outer fn", async () => { }); + it("should log: inner fn -> outer fn", async () => { + function testFn() { + const logger = new index_1.NodeLogger("Log tester"); + function inner_testFn() { + const testVari = 123; + logger.log({ testVari }, { entryPoint: "Object.toLogStdoutMatcher" }); + } + inner_testFn(); + } + const expectedStr = "Log tester: *inner_testFn* -> *testFn*" + + "\n" + + "{" + + "\n" + + ' "testVari": 123' + + "\n" + + "}" + + "\n" + + "\n"; + (0, globals_1.expect)(testFn).toLogStdout(expectedStr); + }); }); describe("3) given a nested array function inside an array function call", () => { it("should log: inner array fn -> outer array fn -> main fn", async () => { }); diff --git a/dist/browser.js b/dist/browser.js index 9c26c49..6b85784 100644 --- a/dist/browser.js +++ b/dist/browser.js @@ -81,25 +81,6 @@ class BrowserLogger extends logger_1.Logger { colouredLog = colouredLog.replace(new RegExp(delimiter, "g"), colouredDelimiter); return colouredLog; } - _formatLogContent() { - const { args } = this; - let logBody = JSON.stringify(args, (_, val) => { - if (typeof val == "function") { - return val.name + " :f()"; - } - else if (typeof val == "undefined") { - return "undefined"; - } - else if (!val && typeof val == "object") { - return "null"; - } - return val; - }, 2); - logBody = logBody.replace(/(\{)|(\})/g, (match) => { - return "\x1b[1;3" + logger_1.Logger.colourNum.toString() + "m" + match + "\x1b[0m"; - }); - return logBody; - } _selectColour() { const { namespace } = this; let numerator; @@ -131,7 +112,7 @@ class BrowserLogger extends logger_1.Logger { } else { const logTitle = this._formatLogCall(this._callStackParser(errorStack)); - const logBody = this._formatLogContent(); + const logBody = this._formatLogBody(); this._writeLog(logTitle, logBody); const logReturn = Object.freeze({ stack: err.stack, diff --git a/dist/logger.js b/dist/logger.js index 77c4eda..244d1c4 100644 --- a/dist/logger.js +++ b/dist/logger.js @@ -120,6 +120,33 @@ class Logger { // } // return logTitle; // } + _formatLogBody() { + const { args } = this; + let logBody = JSON.stringify(args, (_, val) => { + let printedVal = ""; + switch (typeof val) { + case "function": + if (!val.name) { + printedVal = "anonymous()"; + } + else { + printedVal = `${val.name}()`; + } + break; + case "undefined": { + printedVal = "undefined"; + break; + } + default: + break; + } + return printedVal || val; + }, 2); + logBody = logBody.replace(/(\{)|(\})/g, (match) => { + return "\x1b[1;3" + _a.colourNum.toString() + "m" + match + "\x1b[0m"; + }); + return logBody; + } /** * Disables all log messages of a particular logger instance/namespace * @returns {Logger} diff --git a/dist/node.js b/dist/node.js index d4350ae..e860b39 100644 --- a/dist/node.js +++ b/dist/node.js @@ -91,19 +91,6 @@ class NodeLogger extends logger_1.Logger { colouredLog = colouredLog.replace(new RegExp(delimiter, "g"), colouredDelimiter); return colouredLog; } - _formatLogContent() { - const { args } = this; - let logBody = JSON.stringify(args, (_, val) => { - if (typeof val === "function") { - return val.name + " :f()"; - } - return val; - }, 2); - logBody = logBody.replace(/(\{)|(\})/g, (match) => { - return "\x1b[1;3" + logger_1.Logger.colourNum.toString() + "m" + match + "\x1b[0m"; - }); - return logBody; - } _selectColour() { const { namespace } = this; let numerator; @@ -138,7 +125,7 @@ class NodeLogger extends logger_1.Logger { } else { const logTitle = this._formatLogCall(this._callStackParser(errorStack)); - const logBody = this._formatLogContent(); + const logBody = this._formatLogBody(); this._writeLog(logTitle, logBody); const logReturn = Object.freeze({ stack: err.stack, diff --git a/dist/utils/entryPoint.js b/dist/utils/entryPoint.js index 2a9bcb2..7f49e1f 100644 --- a/dist/utils/entryPoint.js +++ b/dist/utils/entryPoint.js @@ -5,7 +5,6 @@ function isESModule() { let isESM = false; try { require("assert"); - console.log("is cjs"); } catch (error) { isESM = true; diff --git a/package.json b/package.json index c3bce16..bd733f5 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ "check:tar": "npm pack && tar -xvzf *.tgz && rm -rf package *.tgz", "dev:pg": "nodemon --watch \"pg/**\" --ext \"js,ts,json,mjs,cjs\" --exec \"ts-node\"", - "dev:tests": "nodemon --watch \"dev/**\" --ext \"js,ts,json,mjs,cjs\" --exec \"ts-node\"", + "dev": "nodemon --watch \"dev/**\" --ext \"js,ts,json,mjs,cjs\" --exec \"ts-node\"", "test:jest": "jest --watch", "test:ci": "jest --ci", diff --git a/src/__tests__/e2e/scope-logger-2.test.ts b/src/__tests__/e2e/scope-logger-2.test.ts index d4103e8..1265f38 100644 --- a/src/__tests__/e2e/scope-logger-2.test.ts +++ b/src/__tests__/e2e/scope-logger-2.test.ts @@ -3,20 +3,6 @@ import { NodeLogger } from "../../index"; import { expect } from "@jest/globals"; describe("scope-logger", () => { - function fn_2() { - const logger = new NodeLogger("Log tester"); - function inner_fn_2() { - const testVari = 123; - const { logTitle: result } = logger.log({ testVari }); - - process.stderr.write(result + "\n"); - - // "Log tester: *inner_fn_2* -> *fn_2* -> *Object.*\n"); - } - - inner_fn_2(); - } - function fn_3() { const logger = new NodeLogger("Log tester"); @@ -33,44 +19,67 @@ describe("scope-logger", () => { }); } describe("given an array function inside a function call", () => { - it("should log: array fn -> main fn", async () => { + it("should log: array fn -> main fn", () => { const logger = new NodeLogger("Log tester", { entryPoint: "Object.toLogStdoutMatcher", }); - const expected = - `Log tester: *Array.forEach* -> *fn_1*` + + function testFn() { + const testArr = [1, 2, 3]; + + testArr.forEach((number) => { + logger.log({ number }); + }); + } + + //w/ JSON.stringify(_, _, 2) for logBody + const expectedStr = + `Log tester: *Array.forEach* -> *testFn*` + "\n" + "{\n" + ' "number": 1\n' + "}\n" + "\n" + - `Log tester: *Array.forEach* -> *fn_1*` + + `Log tester: *Array.forEach* -> *testFn*` + "\n" + "{\n" + ' "number": 2\n' + "}\n" + "\n" + - `Log tester: *Array.forEach* -> *fn_1*` + + `Log tester: *Array.forEach* -> *testFn*` + "\n" + "{\n" + ' "number": 3\n' + "}\n" + "\n"; - function fn_1() { - const testArr = [1, 2, 3]; - testArr.forEach((number) => { - //the log method uses stdout - logger.log({ number }); - }); - } //Object.toLogStdoutMatcher - expect(fn_1).toLogStdout(expected); + expect(testFn).toLogStdout(expectedStr); }); }); describe("2) given a nested function inside a function call", () => { - it("should log: inner fn -> outer fn", async () => {}); + it("should log: inner fn -> outer fn", async () => { + function testFn() { + const logger = new NodeLogger("Log tester"); + function inner_testFn() { + const testVari = 123; + logger.log({ testVari }, { entryPoint: "Object.toLogStdoutMatcher" }); + } + inner_testFn(); + } + + const expectedStr = + "Log tester: *inner_testFn* -> *testFn*" + + "\n" + + "{" + + "\n" + + ' "testVari": 123' + + "\n" + + "}" + + "\n" + + "\n"; + expect(testFn).toLogStdout(expectedStr); + }); }); describe("3) given a nested array function inside an array function call", () => { diff --git a/src/browser.ts b/src/browser.ts index 02fcd1e..e4e7059 100644 --- a/src/browser.ts +++ b/src/browser.ts @@ -118,32 +118,6 @@ export class BrowserLogger extends Logger implements IEnv { return colouredLog; } - _formatLogContent(): string { - const { args } = this; - - let logBody = JSON.stringify( - args, - (_, val) => { - if (typeof val == "function") { - return val.name + " :f()"; - } else if (typeof val == "undefined") { - return "undefined"; - } else if (!val && typeof val == "object") { - return "null"; - } - - return val; - }, - 2 - ); - - logBody = logBody.replace(/(\{)|(\})/g, (match) => { - return "\x1b[1;3" + Logger.colourNum.toString() + "m" + match + "\x1b[0m"; - }); - - return logBody; - } - _selectColour(): number { const { namespace } = this; @@ -182,7 +156,7 @@ export class BrowserLogger extends Logger implements IEnv { return earlyLog; } else { const logTitle = this._formatLogCall(this._callStackParser(errorStack)); - const logBody = this._formatLogContent(); + const logBody = this._formatLogBody(); this._writeLog(logTitle, logBody); diff --git a/src/logger.ts b/src/logger.ts index 5dd0db2..9000da9 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -3,12 +3,12 @@ import { getDefaultEntryPoint } from "./utils/entryPoint"; // TC: same callStackParser implm except entry point function call -// _formatLogContent() is same implm for both browser and node +// _formatLogBody() is same implm for both browser and node interface LogOptions { ignoreIterators?: boolean; onlyFirstElem?: boolean; - entryPoint: string; + entryPoint?: string; } interface LogReturn { @@ -21,7 +21,6 @@ interface IEnv { _writeLog(logTitle: string, logBody: string): void; _callStackParser(callStack: string): string; _formatLogCall(logCall: string): string; - _formatLogContent(): string; _selectColour(): number; _createErrorStack(): { stack: string }; log(args: Object, options?: LogOptions): LogReturn; @@ -305,6 +304,42 @@ class Logger { // return logTitle; // } + _formatLogBody(): string { + const { args } = this; + + let logBody = JSON.stringify( + args, + (_, val) => { + let printedVal: string = ""; + + switch (typeof val) { + case "function": + if (!val.name) { + printedVal = "anonymous()"; + } else { + printedVal = `${val.name}()`; + } + break; + case "undefined": { + printedVal = "undefined"; + break; + } + + default: + break; + } + + return printedVal || val; + }, + 2 + ); + + logBody = logBody.replace(/(\{)|(\})/g, (match) => { + return "\x1b[1;3" + Logger.colourNum.toString() + "m" + match + "\x1b[0m"; + }); + + return logBody; + } /** * Disables all log messages of a particular logger instance/namespace * @returns {Logger} diff --git a/src/node.ts b/src/node.ts index e7d1847..f4e7445 100644 --- a/src/node.ts +++ b/src/node.ts @@ -130,28 +130,6 @@ export class NodeLogger extends Logger implements IEnv { return colouredLog; } - _formatLogContent(): string { - const { args } = this; - - let logBody = JSON.stringify( - args, - (_, val) => { - if (typeof val === "function") { - return val.name + " :f()"; - } - - return val; - }, - 2 - ); - - logBody = logBody.replace(/(\{)|(\})/g, (match) => { - return "\x1b[1;3" + Logger.colourNum.toString() + "m" + match + "\x1b[0m"; - }); - - return logBody; - } - _selectColour(): number { const { namespace } = this; @@ -194,7 +172,7 @@ export class NodeLogger extends Logger implements IEnv { return earlyLog; } else { const logTitle = this._formatLogCall(this._callStackParser(errorStack)); - const logBody = this._formatLogContent(); + const logBody = this._formatLogBody(); this._writeLog(logTitle, logBody); diff --git a/src/utils/entryPoint.ts b/src/utils/entryPoint.ts index 37db6db..5dcd2ff 100644 --- a/src/utils/entryPoint.ts +++ b/src/utils/entryPoint.ts @@ -4,7 +4,6 @@ export function isESModule(): boolean { let isESM = false; try { require("assert"); - console.log("is cjs"); } catch (error) { isESM = true; throw error; diff --git a/tsconfig.json b/tsconfig.json index 1632ce1..ebb76bc 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,108 +3,22 @@ "compilerOptions": { /* Visit https://aka.ms/tsconfig to read more about this file */ - /* Projects */ - // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ - // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ - // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ - // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ - // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ - /* Language and Environment */ "target": "es2020" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, - // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ - // "jsx": "preserve", /* Specify what JSX code is generated. */ - // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ - // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ - // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ - // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ - // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ - // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ - // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ - // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ - // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ /* Modules */ "module": "commonjs" /* Specify what module code is generated. */, "rootDir": "./src" /* Specify the root folder within your source files. */, - // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ - // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ - // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ - // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ - // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ - // "types": [], /* Specify type package names to be included without being referenced in a source file. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ - // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ - // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ - // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ - // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ - // "resolveJsonModule": true, /* Enable importing .json files. */ - // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ - // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ - - /* JavaScript Support */ - // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ - // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ - // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ - - /* Emit */ - // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ - // "declarationMap": true, /* Create sourcemaps for d.ts files. */ - // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ - // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ - // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ - // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ "outDir": "dist" /* Specify an output folder for all emitted files. */, - // "removeComments": true, /* Disable emitting comments. */ - // "noEmit": true, /* Disable emitting files from a compilation. */ - // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ - // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ - // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ - // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ - // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ - // "newLine": "crlf", /* Set the newline character for emitting files. */ - // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ - // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ - // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ - // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ - // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ - // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ /* Interop Constraints */ - // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ - // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ - // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, - // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, /* Type Checking */ "strict": true /* Enable all strict type-checking options. */, - // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ - // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ - // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ - // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ - // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ - // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ - // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ - // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ - // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ - // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ - // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ - // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ - // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ - // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ - // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ /* Completeness */ - // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ "skipLibCheck": true /* Skip type checking all .d.ts files. */ }, "exclude": ["pg", "node_modules", "dev", "src/types.ts"] From f8df4ffe736a3f6e5c57e27dc5c714e0ee36d92c Mon Sep 17 00:00:00 2001 From: Zen-cronic <83657429+Zen-cronic@users.noreply.github.com> Date: Fri, 12 Jul 2024 18:30:09 -0400 Subject: [PATCH 05/11] refactored: scope-logger e2e --- dist/__tests__/e2e/scope-logger-2.test.js | 51 ++++++++++++------ dist/node.js | 12 +---- src/__tests__/e2e/scope-logger-2.test.ts | 66 ++++++++++++++++------- src/node.ts | 15 +----- 4 files changed, 85 insertions(+), 59 deletions(-) diff --git a/dist/__tests__/e2e/scope-logger-2.test.js b/dist/__tests__/e2e/scope-logger-2.test.js index a5c32fd..3bba038 100644 --- a/dist/__tests__/e2e/scope-logger-2.test.js +++ b/dist/__tests__/e2e/scope-logger-2.test.js @@ -4,17 +4,6 @@ require("jest-to-log"); const index_1 = require("../../index"); const globals_1 = require("@jest/globals"); describe("scope-logger", () => { - function fn_3() { - const logger = new index_1.NodeLogger("Log tester"); - const testOuterArr = [1, 2, 3]; - const testInnerArr = [1, 2, 3]; - testOuterArr.map((num) => { - testInnerArr.forEach((num) => { - const { logTitle: result } = logger.log({ num }); - process.stderr.write(result + "\n"); - }); - }); - } describe("given an array function inside a function call", () => { it("should log: array fn -> main fn", () => { const logger = new index_1.NodeLogger("Log tester", { @@ -49,10 +38,10 @@ describe("scope-logger", () => { (0, globals_1.expect)(testFn).toLogStdout(expectedStr); }); }); - describe("2) given a nested function inside a function call", () => { - it("should log: inner fn -> outer fn", async () => { + describe("given a nested function inside a function call", () => { + it("should log: inner fn -> outer fn", () => { + const logger = new index_1.NodeLogger("Log tester"); function testFn() { - const logger = new index_1.NodeLogger("Log tester"); function inner_testFn() { const testVari = 123; logger.log({ testVari }, { entryPoint: "Object.toLogStdoutMatcher" }); @@ -71,7 +60,37 @@ describe("scope-logger", () => { (0, globals_1.expect)(testFn).toLogStdout(expectedStr); }); }); - describe("3) given a nested array function inside an array function call", () => { - it("should log: inner array fn -> outer array fn -> main fn", async () => { }); + describe("given a nested array function inside an array function call", () => { + it("should log: inner array fn -> outer array fn -> main fn", () => { + const logger = new index_1.NodeLogger("Log tester", { + entryPoint: "Object.toLogStdoutMatcher", + }); + const testOuterArr = [1, 2, 3]; + const testInnerArr = [1, 2, 3]; + function testFn() { + testOuterArr.map((_) => { + testInnerArr.forEach((testVari) => { + logger.log({ testVari }); + }); + }); + } + const outerRepeat = testOuterArr.length; + const innerRepeat = testInnerArr.length; + const ttlRepeat = outerRepeat * innerRepeat; + let expectedStr = ""; + const expectedLogCall = "Log tester: *Array.forEach* -> *Array.map* -> *testFn*" + "\n"; + const expectedLogBody = (printVal) => { + return ("{" + "\n" + ` "testVari": ${printVal}` + "\n" + "}" + "\n" + "\n"); + }; + let innerCount = 0; + for (let i = 0; i < ttlRepeat; i++) { + if (innerCount === innerRepeat) { + //reset + innerCount = 0; + } + expectedStr += expectedLogCall + expectedLogBody(++innerCount); + } + (0, globals_1.expect)(testFn).toLogStdout(expectedStr); + }); }); }); diff --git a/dist/node.js b/dist/node.js index e860b39..0a74429 100644 --- a/dist/node.js +++ b/dist/node.js @@ -42,7 +42,7 @@ class NodeLogger extends logger_1.Logger { let calleeFunc = ""; //4 - async | constructor //3 - normal func - //2 - 1 abv iterable | anonymous (at (location)) + //2 - 1 abv iterable | anonymous func (at (location)) if (currentLinePartsLen === 3) { calleeFunc = currentLineParts[1]; //iterable func or normal func @@ -61,15 +61,7 @@ class NodeLogger extends logger_1.Logger { } logTitle = logTitle.concat(`*${calleeFunc}*`, delimiter); } - // //" ->" - // const testEnvDelimiter = delimiter.trimEnd(); - // //dev (or) prod - delimiter - // const checkDelimiter = - // process.env.NODE_ENV === "test" ? testEnvDelimiter : delimiter; - // if (logTitle.endsWith(checkDelimiter)) { - // logTitle = logTitle.slice(0, -checkDelimiter.length); - // } - //trim cuz concated before break + //trim cuz concat-ed before the entryPoint break logTitle = logTitle.trimEnd(); const trimmedDelimiter = delimiter.trimEnd(); if (logTitle.endsWith(trimmedDelimiter)) { diff --git a/src/__tests__/e2e/scope-logger-2.test.ts b/src/__tests__/e2e/scope-logger-2.test.ts index 1265f38..59f0f44 100644 --- a/src/__tests__/e2e/scope-logger-2.test.ts +++ b/src/__tests__/e2e/scope-logger-2.test.ts @@ -3,21 +3,6 @@ import { NodeLogger } from "../../index"; import { expect } from "@jest/globals"; describe("scope-logger", () => { - function fn_3() { - const logger = new NodeLogger("Log tester"); - - const testOuterArr = [1, 2, 3]; - - const testInnerArr = [1, 2, 3]; - - testOuterArr.map((num) => { - testInnerArr.forEach((num) => { - const { logTitle: result } = logger.log({ num }); - - process.stderr.write(result + "\n"); - }); - }); - } describe("given an array function inside a function call", () => { it("should log: array fn -> main fn", () => { const logger = new NodeLogger("Log tester", { @@ -57,10 +42,10 @@ describe("scope-logger", () => { }); }); - describe("2) given a nested function inside a function call", () => { - it("should log: inner fn -> outer fn", async () => { + describe("given a nested function inside a function call", () => { + it("should log: inner fn -> outer fn", () => { + const logger = new NodeLogger("Log tester"); function testFn() { - const logger = new NodeLogger("Log tester"); function inner_testFn() { const testVari = 123; logger.log({ testVari }, { entryPoint: "Object.toLogStdoutMatcher" }); @@ -82,7 +67,48 @@ describe("scope-logger", () => { }); }); - describe("3) given a nested array function inside an array function call", () => { - it("should log: inner array fn -> outer array fn -> main fn", async () => {}); + describe("given a nested array function inside an array function call", () => { + it("should log: inner array fn -> outer array fn -> main fn", () => { + const logger = new NodeLogger("Log tester", { + entryPoint: "Object.toLogStdoutMatcher", + }); + + const testOuterArr = [1, 2, 3]; + const testInnerArr = [1, 2, 3]; + + function testFn() { + testOuterArr.map((_) => { + testInnerArr.forEach((testVari) => { + logger.log({ testVari }); + }); + }); + } + + const outerRepeat: number = testOuterArr.length; + const innerRepeat: number = testInnerArr.length; + const ttlRepeat: number = outerRepeat * innerRepeat; + + let expectedStr = ""; + + const expectedLogCall = + "Log tester: *Array.forEach* -> *Array.map* -> *testFn*" + "\n"; + + const expectedLogBody = (printVal: number) => { + return ( + "{" + "\n" + ` "testVari": ${printVal}` + "\n" + "}" + "\n" + "\n" + ); + }; + + let innerCount = 0; + for (let i = 0; i < ttlRepeat; i++) { + if (innerCount === innerRepeat) { + //reset + innerCount = 0; + } + expectedStr += expectedLogCall + expectedLogBody(++innerCount); + } + + expect(testFn).toLogStdout(expectedStr); + }); }); }); diff --git a/src/node.ts b/src/node.ts index f4e7445..45c4509 100644 --- a/src/node.ts +++ b/src/node.ts @@ -56,7 +56,7 @@ export class NodeLogger extends Logger implements IEnv { //4 - async | constructor //3 - normal func - //2 - 1 abv iterable | anonymous (at (location)) + //2 - 1 abv iterable | anonymous func (at (location)) if (currentLinePartsLen === 3) { calleeFunc = currentLineParts[1]; @@ -81,18 +81,7 @@ export class NodeLogger extends Logger implements IEnv { logTitle = logTitle.concat(`*${calleeFunc}*`, delimiter); } - // //" ->" - // const testEnvDelimiter = delimiter.trimEnd(); - - // //dev (or) prod - delimiter - // const checkDelimiter = - // process.env.NODE_ENV === "test" ? testEnvDelimiter : delimiter; - - // if (logTitle.endsWith(checkDelimiter)) { - // logTitle = logTitle.slice(0, -checkDelimiter.length); - // } - - //trim cuz concated before break + //trim cuz concat-ed before the entryPoint break logTitle = logTitle.trimEnd(); const trimmedDelimiter = delimiter.trimEnd(); From e61b6bae9f2d96466d51ad02a289909471b547d9 Mon Sep 17 00:00:00 2001 From: Zen-cronic <83657429+Zen-cronic@users.noreply.github.com> Date: Fri, 12 Jul 2024 19:10:25 -0400 Subject: [PATCH 06/11] updated: migrated disableAll unit --- dist/__tests__/e2e/scope-logger.test.js | 132 +++++++++------ dist/__tests__/unit/disableAll-2.test.js | 60 +++++++ dist/__tests__/unit/disableAll.test.js | 73 +++++--- .../__tests__/unit/disableAll.test.process.js | 57 ------- dist/logger.js | 7 +- src/__tests__/e2e/scope-logger-2.test.ts | 114 ------------- .../e2e/scope-logger.test.process.ts | 92 ---------- src/__tests__/e2e/scope-logger.test.ts | 160 +++++++++++------- src/__tests__/unit/disableAll.test.process.ts | 68 -------- src/__tests__/unit/disableAll.test.ts | 93 ++++++---- src/logger.ts | 7 +- 11 files changed, 347 insertions(+), 516 deletions(-) create mode 100644 dist/__tests__/unit/disableAll-2.test.js delete mode 100644 dist/__tests__/unit/disableAll.test.process.js delete mode 100644 src/__tests__/e2e/scope-logger-2.test.ts delete mode 100644 src/__tests__/e2e/scope-logger.test.process.ts delete mode 100644 src/__tests__/unit/disableAll.test.process.ts diff --git a/dist/__tests__/e2e/scope-logger.test.js b/dist/__tests__/e2e/scope-logger.test.js index d101fcb..3bba038 100644 --- a/dist/__tests__/e2e/scope-logger.test.js +++ b/dist/__tests__/e2e/scope-logger.test.js @@ -1,64 +1,96 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const testHelper_1 = require("../../utils/testHelper"); +require("jest-to-log"); +const index_1 = require("../../index"); +const globals_1 = require("@jest/globals"); describe("scope-logger", () => { - const { createMessagePromise, createWorkerDataPromise } = (0, testHelper_1.setupTest)("e2e", - //either js or ts works - "scope-logger.test.process.ts"); - /** - * - * @param {string} expectedResult - * @param {boolean} [waitMessageFromWorker=false] - */ - async function runTestCase(expectedResult, waitMessageFromWorker = false) { - let promises = [ - createWorkerDataPromise(), - ]; - if (waitMessageFromWorker) { - promises.push(createMessagePromise()); - } - const promisesResult = await Promise.all(promises); - const workerData = promisesResult[0]; - const message = promisesResult[1]; - const { length = 1 } = message || {}; - if (typeof length !== "number") { - throw new Error(`Invalid length from child process: ${length}`); - } - const discolouredResult = workerData.replace(/(\x1b\[\d+;\d+m)|(\x1b\[\d+m)/g, ""); - expectedResult = expectedResult.repeat(length); - expect(discolouredResult).toBe(expectedResult); - } - describe("1) given an array function inside a function call", () => { - it("should log: array fn -> main fn", async () => { - try { - const expected = `Log tester: *Array.forEach* -> *fn_1*\n`; - await runTestCase(expected, true); - } - catch (error) { - throw new Error(error); + describe("given an array function inside a function call", () => { + it("should log: array fn -> main fn", () => { + const logger = new index_1.NodeLogger("Log tester", { + entryPoint: "Object.toLogStdoutMatcher", + }); + function testFn() { + const testArr = [1, 2, 3]; + testArr.forEach((number) => { + logger.log({ number }); + }); } + //w/ JSON.stringify(_, _, 2) for logBody + const expectedStr = `Log tester: *Array.forEach* -> *testFn*` + + "\n" + + "{\n" + + ' "number": 1\n' + + "}\n" + + "\n" + + `Log tester: *Array.forEach* -> *testFn*` + + "\n" + + "{\n" + + ' "number": 2\n' + + "}\n" + + "\n" + + `Log tester: *Array.forEach* -> *testFn*` + + "\n" + + "{\n" + + ' "number": 3\n' + + "}\n" + + "\n"; + //Object.toLogStdoutMatcher + (0, globals_1.expect)(testFn).toLogStdout(expectedStr); }); }); - describe("2) given a nested function inside a function call", () => { - it("should log: inner fn -> outer fn", async () => { - try { - const expected = `Log tester: *inner_fn_2* -> *fn_2*\n`; - await runTestCase(expected); - } - catch (error) { - throw new Error(error); + describe("given a nested function inside a function call", () => { + it("should log: inner fn -> outer fn", () => { + const logger = new index_1.NodeLogger("Log tester"); + function testFn() { + function inner_testFn() { + const testVari = 123; + logger.log({ testVari }, { entryPoint: "Object.toLogStdoutMatcher" }); + } + inner_testFn(); } + const expectedStr = "Log tester: *inner_testFn* -> *testFn*" + + "\n" + + "{" + + "\n" + + ' "testVari": 123' + + "\n" + + "}" + + "\n" + + "\n"; + (0, globals_1.expect)(testFn).toLogStdout(expectedStr); }); }); - describe("3) given a nested array function inside an array function call", () => { - it("should log: inner array fn -> outer array fn -> main fn", async () => { - try { - const expected = `Log tester: *Array.forEach* -> *Array.map* -> *fn_3*\n`; - await runTestCase(expected, true); + describe("given a nested array function inside an array function call", () => { + it("should log: inner array fn -> outer array fn -> main fn", () => { + const logger = new index_1.NodeLogger("Log tester", { + entryPoint: "Object.toLogStdoutMatcher", + }); + const testOuterArr = [1, 2, 3]; + const testInnerArr = [1, 2, 3]; + function testFn() { + testOuterArr.map((_) => { + testInnerArr.forEach((testVari) => { + logger.log({ testVari }); + }); + }); } - catch (error) { - throw new Error(error); + const outerRepeat = testOuterArr.length; + const innerRepeat = testInnerArr.length; + const ttlRepeat = outerRepeat * innerRepeat; + let expectedStr = ""; + const expectedLogCall = "Log tester: *Array.forEach* -> *Array.map* -> *testFn*" + "\n"; + const expectedLogBody = (printVal) => { + return ("{" + "\n" + ` "testVari": ${printVal}` + "\n" + "}" + "\n" + "\n"); + }; + let innerCount = 0; + for (let i = 0; i < ttlRepeat; i++) { + if (innerCount === innerRepeat) { + //reset + innerCount = 0; + } + expectedStr += expectedLogCall + expectedLogBody(++innerCount); } + (0, globals_1.expect)(testFn).toLogStdout(expectedStr); }); }); }); diff --git a/dist/__tests__/unit/disableAll-2.test.js b/dist/__tests__/unit/disableAll-2.test.js new file mode 100644 index 0000000..59728ba --- /dev/null +++ b/dist/__tests__/unit/disableAll-2.test.js @@ -0,0 +1,60 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +require("jest-to-log"); +const index_1 = require("../../index"); +const globals_1 = require("@jest/globals"); +describe("disableAll() method", () => { + describe("1) given that disableAll() is called directly on an instance", () => { + it("should log nothing", () => { + const logger = new index_1.NodeLogger("Log tester"); + let logResult = {}; + function testFn() { + logger.disableAll(); + const foo = "bar"; + const logReturn = logger.log({ foo }); + logResult = { ...logReturn }; + } + (0, globals_1.expect)(testFn).toLogStdout(""); + //logResult assigned only after the abv assertion + (0, globals_1.expect)(logResult).toStrictEqual({ + stack: null, + logTitle: null, + logBody: null, + }); + }); + }); + describe("2) given that disableAll() is called on the constructor (indirectly on the instance)", () => { + it("should log nothing", () => { + const logger = new index_1.NodeLogger("Log tester").disableAll(); + let logResult = {}; + function testFn() { + const foo = "bar"; + const logReturn = logger.log({ foo }); + logResult = { ...logReturn }; + } + (0, globals_1.expect)(testFn).toLogStdout(""); + (0, globals_1.expect)(logResult).toStrictEqual({ + stack: null, + logTitle: null, + logBody: null, + }); + }); + }); + describe("3) given that the log method is called by the instance after invoking disableAll() on the constructor", () => { + it("should NOT throw", () => { + const logger = new index_1.NodeLogger("Log tester").disableAll(); + let logResult = {}; + function testFn() { + const foo = "bar"; + const logReturn = logger.log({ foo }); + logResult = { ...logReturn }; + } + (0, globals_1.expect)(testFn).toLogStdout(""); + (0, globals_1.expect)(logResult).toStrictEqual({ + stack: null, + logTitle: null, + logBody: null, + }); + }); + }); +}); diff --git a/dist/__tests__/unit/disableAll.test.js b/dist/__tests__/unit/disableAll.test.js index c249079..59728ba 100644 --- a/dist/__tests__/unit/disableAll.test.js +++ b/dist/__tests__/unit/disableAll.test.js @@ -1,37 +1,60 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const testHelper_1 = require("../../utils/testHelper"); +require("jest-to-log"); +const index_1 = require("../../index"); +const globals_1 = require("@jest/globals"); describe("disableAll() method", () => { - const { createWorkerDataPromise } = (0, testHelper_1.setupTest)("unit", "disableAll.test.process.ts"); - /** - * - * Only createWorkerDataPromise; Nu createMessagePromise - * @returns {Promise<{discolouredResult: string}>} - */ - async function processWorkerPromises() { - const promiseResult = await createWorkerDataPromise(); - const workerData = promiseResult; - const discolouredResult = workerData.replace(/(\x1b\[\d+;\d+m)|(\x1b\[\d+m)/g, ""); - return { discolouredResult }; - } describe("1) given that disableAll() is called directly on an instance", () => { - it("should log nothing", async () => { - const { discolouredResult } = await processWorkerPromises(); - //just \n - const expected = "\n"; - expect(discolouredResult).toBe(expected); + it("should log nothing", () => { + const logger = new index_1.NodeLogger("Log tester"); + let logResult = {}; + function testFn() { + logger.disableAll(); + const foo = "bar"; + const logReturn = logger.log({ foo }); + logResult = { ...logReturn }; + } + (0, globals_1.expect)(testFn).toLogStdout(""); + //logResult assigned only after the abv assertion + (0, globals_1.expect)(logResult).toStrictEqual({ + stack: null, + logTitle: null, + logBody: null, + }); }); }); describe("2) given that disableAll() is called on the constructor (indirectly on the instance)", () => { - it("should log nothing", async () => { - const { discolouredResult } = await processWorkerPromises(); - const expected = "\n"; - expect(discolouredResult).toBe(expected); + it("should log nothing", () => { + const logger = new index_1.NodeLogger("Log tester").disableAll(); + let logResult = {}; + function testFn() { + const foo = "bar"; + const logReturn = logger.log({ foo }); + logResult = { ...logReturn }; + } + (0, globals_1.expect)(testFn).toLogStdout(""); + (0, globals_1.expect)(logResult).toStrictEqual({ + stack: null, + logTitle: null, + logBody: null, + }); }); }); - describe("3) given that the log method is called after invoking disableAll() on the constructor", () => { - it("should NOT throw", async () => { - expect(async () => await processWorkerPromises()).not.toThrow(); + describe("3) given that the log method is called by the instance after invoking disableAll() on the constructor", () => { + it("should NOT throw", () => { + const logger = new index_1.NodeLogger("Log tester").disableAll(); + let logResult = {}; + function testFn() { + const foo = "bar"; + const logReturn = logger.log({ foo }); + logResult = { ...logReturn }; + } + (0, globals_1.expect)(testFn).toLogStdout(""); + (0, globals_1.expect)(logResult).toStrictEqual({ + stack: null, + logTitle: null, + logBody: null, + }); }); }); }); diff --git a/dist/__tests__/unit/disableAll.test.process.js b/dist/__tests__/unit/disableAll.test.process.js deleted file mode 100644 index f3ee11f..0000000 --- a/dist/__tests__/unit/disableAll.test.process.js +++ /dev/null @@ -1,57 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const index_1 = require("../../index"); -(async function () { - try { - //instance - function fn_1() { - const logger = new index_1.NodeLogger("Log tester"); - logger.disableAll(); - const foo = "bar"; - const { logTitle: result } = logger.log({ foo }); - process.stderr.write(result + "\n"); - } - //constructor - function fn_2() { - const logger = new index_1.NodeLogger("Log tester").disableAll(); - const foo = "bar"; - const { logTitle: result } = logger.log({ foo }); - process.stderr.write(result + "\n"); - } - //not throw - function fn_3() { - const logger = new index_1.NodeLogger("Log tester").disableAll(); - const foo = "bar"; - const { logTitle: result } = logger.log({ foo }); - process.stderr.write(result + "\n"); - } - const testCaseNum = await new Promise((resolve, reject) => { - process.once("message", (message) => { - if (typeof message === "number") { - console.log("message from parent: " + message); - resolve(message); - } - else { - reject(new Error("Invalid test case sent from main process")); - } - }); - }); - switch (testCaseNum) { - case 1: - fn_1(); - break; - case 2: - fn_2(); - break; - case 3: - fn_3(); - break; - default: - break; - } - } - catch (error) { - // Send the error message to the parent process - process.send({ error: error.message }); - } -})(); diff --git a/dist/logger.js b/dist/logger.js index 244d1c4..4416475 100644 --- a/dist/logger.js +++ b/dist/logger.js @@ -149,14 +149,13 @@ class Logger { } /** * Disables all log messages of a particular logger instance/namespace - * @returns {Logger} */ disableAll() { const noopLike = () => { return Object.freeze({ - stack: "", - logTitle: "", - logBody: "", + stack: null, + logTitle: null, + logBody: null, }); }; this.earlyLog = noopLike; diff --git a/src/__tests__/e2e/scope-logger-2.test.ts b/src/__tests__/e2e/scope-logger-2.test.ts deleted file mode 100644 index 59f0f44..0000000 --- a/src/__tests__/e2e/scope-logger-2.test.ts +++ /dev/null @@ -1,114 +0,0 @@ -import "jest-to-log"; -import { NodeLogger } from "../../index"; -import { expect } from "@jest/globals"; - -describe("scope-logger", () => { - describe("given an array function inside a function call", () => { - it("should log: array fn -> main fn", () => { - const logger = new NodeLogger("Log tester", { - entryPoint: "Object.toLogStdoutMatcher", - }); - function testFn() { - const testArr = [1, 2, 3]; - - testArr.forEach((number) => { - logger.log({ number }); - }); - } - - //w/ JSON.stringify(_, _, 2) for logBody - const expectedStr = - `Log tester: *Array.forEach* -> *testFn*` + - "\n" + - "{\n" + - ' "number": 1\n' + - "}\n" + - "\n" + - `Log tester: *Array.forEach* -> *testFn*` + - "\n" + - "{\n" + - ' "number": 2\n' + - "}\n" + - "\n" + - `Log tester: *Array.forEach* -> *testFn*` + - "\n" + - "{\n" + - ' "number": 3\n' + - "}\n" + - "\n"; - - //Object.toLogStdoutMatcher - expect(testFn).toLogStdout(expectedStr); - }); - }); - - describe("given a nested function inside a function call", () => { - it("should log: inner fn -> outer fn", () => { - const logger = new NodeLogger("Log tester"); - function testFn() { - function inner_testFn() { - const testVari = 123; - logger.log({ testVari }, { entryPoint: "Object.toLogStdoutMatcher" }); - } - inner_testFn(); - } - - const expectedStr = - "Log tester: *inner_testFn* -> *testFn*" + - "\n" + - "{" + - "\n" + - ' "testVari": 123' + - "\n" + - "}" + - "\n" + - "\n"; - expect(testFn).toLogStdout(expectedStr); - }); - }); - - describe("given a nested array function inside an array function call", () => { - it("should log: inner array fn -> outer array fn -> main fn", () => { - const logger = new NodeLogger("Log tester", { - entryPoint: "Object.toLogStdoutMatcher", - }); - - const testOuterArr = [1, 2, 3]; - const testInnerArr = [1, 2, 3]; - - function testFn() { - testOuterArr.map((_) => { - testInnerArr.forEach((testVari) => { - logger.log({ testVari }); - }); - }); - } - - const outerRepeat: number = testOuterArr.length; - const innerRepeat: number = testInnerArr.length; - const ttlRepeat: number = outerRepeat * innerRepeat; - - let expectedStr = ""; - - const expectedLogCall = - "Log tester: *Array.forEach* -> *Array.map* -> *testFn*" + "\n"; - - const expectedLogBody = (printVal: number) => { - return ( - "{" + "\n" + ` "testVari": ${printVal}` + "\n" + "}" + "\n" + "\n" - ); - }; - - let innerCount = 0; - for (let i = 0; i < ttlRepeat; i++) { - if (innerCount === innerRepeat) { - //reset - innerCount = 0; - } - expectedStr += expectedLogCall + expectedLogBody(++innerCount); - } - - expect(testFn).toLogStdout(expectedStr); - }); - }); -}); diff --git a/src/__tests__/e2e/scope-logger.test.process.ts b/src/__tests__/e2e/scope-logger.test.process.ts deleted file mode 100644 index 004ec00..0000000 --- a/src/__tests__/e2e/scope-logger.test.process.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { NodeLogger } from "../../index"; -import { NonNullProcessSend } from "../../types"; - -const logger = new NodeLogger("Log tester"); - - -(async function () { - try { - function fn_1() { - const testArr = [1, 2, 3]; - - testArr.forEach((number) => { - //the log method uses stdout - const { logTitle: result, stack } = logger.log({ number }); - - process.stderr.write(result + "\n"); - }); - - (process.send as NonNullProcessSend)({ - length: testArr.length, - }); - } - - function fn_2() { - const logger = new NodeLogger("Log tester"); - function inner_fn_2() { - const testVari = 123; - const { logTitle: result } = logger.log({ testVari }); - - process.stderr.write(result + "\n"); - - // "Log tester: *inner_fn_2* -> *fn_2* -> *Object.*\n"); - - } - - inner_fn_2(); - } - - function fn_3() { - const logger = new NodeLogger("Log tester"); - - const testOuterArr = [1, 2, 3]; - - const testInnerArr = [1, 2, 3]; - - testOuterArr.map((num) => { - testInnerArr.forEach((num) => { - const { logTitle: result } = logger.log({ num }); - - process.stderr.write(result + "\n"); - }); - }); - - // process.stderr.write(testOuterArr.length * testInnerArr.length) - (process.send as NonNullProcessSend)({ - length: testOuterArr.length * testInnerArr.length, - }); - } - - //when process.exit() - const testCaseNum = await new Promise((resolve, reject) => { - process.once("message", (message) => { - if (typeof message === "number") { - console.log("message from parent: " + message); - - resolve(message); - } else { - reject(new Error("Invalid test case sent from main process")); - } - }); - }); - - switch (testCaseNum) { - case 1: - fn_1(); - break; - - case 2: - fn_2(); - break; - case 3: - fn_3(); - break; - - default: - break; - } - } catch (error: any) { - // Send the error message to the parent process - (process.send as NonNullProcessSend)({ error: (error as Error).message }); - } -})(); diff --git a/src/__tests__/e2e/scope-logger.test.ts b/src/__tests__/e2e/scope-logger.test.ts index fa400b8..59f0f44 100644 --- a/src/__tests__/e2e/scope-logger.test.ts +++ b/src/__tests__/e2e/scope-logger.test.ts @@ -1,84 +1,114 @@ -import { WorkerNonErrorMessage } from "../../types"; -import { setupTest } from "../../utils/testHelper"; +import "jest-to-log"; +import { NodeLogger } from "../../index"; +import { expect } from "@jest/globals"; describe("scope-logger", () => { - const { createMessagePromise, createWorkerDataPromise } = setupTest( - "e2e", - //either js or ts works - "scope-logger.test.process.ts" + describe("given an array function inside a function call", () => { + it("should log: array fn -> main fn", () => { + const logger = new NodeLogger("Log tester", { + entryPoint: "Object.toLogStdoutMatcher", + }); + function testFn() { + const testArr = [1, 2, 3]; - ); - /** - * - * @param {string} expectedResult - * @param {boolean} [waitMessageFromWorker=false] - */ - - - async function runTestCase( - expectedResult: string, - waitMessageFromWorker: boolean = false - ) { - let promises: (Promise | Promise)[] = [ - createWorkerDataPromise(), - ]; - - if (waitMessageFromWorker) { - promises.push(createMessagePromise()); - } + testArr.forEach((number) => { + logger.log({ number }); + }); + } - const promisesResult = await Promise.all(promises); + //w/ JSON.stringify(_, _, 2) for logBody + const expectedStr = + `Log tester: *Array.forEach* -> *testFn*` + + "\n" + + "{\n" + + ' "number": 1\n' + + "}\n" + + "\n" + + `Log tester: *Array.forEach* -> *testFn*` + + "\n" + + "{\n" + + ' "number": 2\n' + + "}\n" + + "\n" + + `Log tester: *Array.forEach* -> *testFn*` + + "\n" + + "{\n" + + ' "number": 3\n' + + "}\n" + + "\n"; - const workerData = promisesResult[0]; - const message = promisesResult[1]; + //Object.toLogStdoutMatcher + expect(testFn).toLogStdout(expectedStr); + }); + }); - const { length = 1 } = message || {}; - if (typeof length !== "number") { - throw new Error(`Invalid length from child process: ${length}`); - } + describe("given a nested function inside a function call", () => { + it("should log: inner fn -> outer fn", () => { + const logger = new NodeLogger("Log tester"); + function testFn() { + function inner_testFn() { + const testVari = 123; + logger.log({ testVari }, { entryPoint: "Object.toLogStdoutMatcher" }); + } + inner_testFn(); + } - const discolouredResult = (workerData as string).replace( - /(\x1b\[\d+;\d+m)|(\x1b\[\d+m)/g, - "" - ); + const expectedStr = + "Log tester: *inner_testFn* -> *testFn*" + + "\n" + + "{" + + "\n" + + ' "testVari": 123' + + "\n" + + "}" + + "\n" + + "\n"; + expect(testFn).toLogStdout(expectedStr); + }); + }); - expectedResult = expectedResult.repeat(length); - expect(discolouredResult).toBe(expectedResult); - } + describe("given a nested array function inside an array function call", () => { + it("should log: inner array fn -> outer array fn -> main fn", () => { + const logger = new NodeLogger("Log tester", { + entryPoint: "Object.toLogStdoutMatcher", + }); - describe("1) given an array function inside a function call", () => { - it("should log: array fn -> main fn", async () => { - try { - const expected = `Log tester: *Array.forEach* -> *fn_1*\n`; + const testOuterArr = [1, 2, 3]; + const testInnerArr = [1, 2, 3]; - await runTestCase(expected, true); - } catch (error: any) { - throw new Error(error); + function testFn() { + testOuterArr.map((_) => { + testInnerArr.forEach((testVari) => { + logger.log({ testVari }); + }); + }); } - }); - }); - describe("2) given a nested function inside a function call", () => { - it("should log: inner fn -> outer fn", async () => { - try { - const expected = `Log tester: *inner_fn_2* -> *fn_2*\n`; + const outerRepeat: number = testOuterArr.length; + const innerRepeat: number = testInnerArr.length; + const ttlRepeat: number = outerRepeat * innerRepeat; - await runTestCase(expected); - } catch (error: any) { - throw new Error(error); - } - }); - }); + let expectedStr = ""; + + const expectedLogCall = + "Log tester: *Array.forEach* -> *Array.map* -> *testFn*" + "\n"; - describe("3) given a nested array function inside an array function call", () => { - it("should log: inner array fn -> outer array fn -> main fn", async () => { - try { - const expected = `Log tester: *Array.forEach* -> *Array.map* -> *fn_3*\n`; + const expectedLogBody = (printVal: number) => { + return ( + "{" + "\n" + ` "testVari": ${printVal}` + "\n" + "}" + "\n" + "\n" + ); + }; - await runTestCase(expected, true); - } catch (error: any) { - throw new Error(error); + let innerCount = 0; + for (let i = 0; i < ttlRepeat; i++) { + if (innerCount === innerRepeat) { + //reset + innerCount = 0; + } + expectedStr += expectedLogCall + expectedLogBody(++innerCount); } + + expect(testFn).toLogStdout(expectedStr); }); }); }); diff --git a/src/__tests__/unit/disableAll.test.process.ts b/src/__tests__/unit/disableAll.test.process.ts deleted file mode 100644 index e868545..0000000 --- a/src/__tests__/unit/disableAll.test.process.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { NodeLogger } from "../../index"; -import { NonNullProcessSend } from "../../types"; - -(async function () { - try { - //instance - function fn_1() { - const logger = new NodeLogger("Log tester"); - - logger.disableAll(); - - const foo = "bar"; - const { logTitle: result } = logger.log({ foo }); - - process.stderr.write(result + "\n"); - } - - //constructor - function fn_2() { - const logger = new NodeLogger("Log tester").disableAll(); - const foo = "bar"; - const { logTitle: result } = logger.log({ foo }); - - process.stderr.write(result + "\n"); - } - - //not throw - function fn_3() { - const logger = new NodeLogger("Log tester").disableAll(); - - const foo = "bar"; - const { logTitle: result } = logger.log({ foo }); - - process.stderr.write(result + "\n"); - } - - const testCaseNum = await new Promise((resolve, reject) => { - process.once("message", (message) => { - if (typeof message === "number") { - console.log("message from parent: " + message); - - resolve(message); - } else { - reject(new Error("Invalid test case sent from main process")); - } - }); - }); - - switch (testCaseNum) { - case 1: - fn_1(); - break; - - case 2: - fn_2(); - break; - case 3: - fn_3(); - break; - - default: - break; - } - } catch (error: any) { - // Send the error message to the parent process - (process.send as NonNullProcessSend)({ error: (error as Error).message }); - } -})(); diff --git a/src/__tests__/unit/disableAll.test.ts b/src/__tests__/unit/disableAll.test.ts index 730aea0..0954f41 100644 --- a/src/__tests__/unit/disableAll.test.ts +++ b/src/__tests__/unit/disableAll.test.ts @@ -1,52 +1,71 @@ -import { setupTest } from "../../utils/testHelper"; +import "jest-to-log"; +import { NodeLogger } from "../../index"; +import { expect } from "@jest/globals"; describe("disableAll() method", () => { - const { createWorkerDataPromise } = setupTest( - "unit", - "disableAll.test.process.ts" - ); - - /** - * - * Only createWorkerDataPromise; Nu createMessagePromise - * @returns {Promise<{discolouredResult: string}>} - */ - async function processWorkerPromises(): Promise<{ - discolouredResult: string; - }> { - const promiseResult = await createWorkerDataPromise(); - const workerData = promiseResult; - - const discolouredResult = workerData.replace( - /(\x1b\[\d+;\d+m)|(\x1b\[\d+m)/g, - "" - ); - - return { discolouredResult }; - } - describe("1) given that disableAll() is called directly on an instance", () => { - it("should log nothing", async () => { - const { discolouredResult } = await processWorkerPromises(); + it("should log nothing", () => { + const logger = new NodeLogger("Log tester"); + + let logResult = {}; + + function testFn() { + logger.disableAll(); + + const foo = "bar"; + const logReturn = logger.log({ foo }); + + logResult = { ...logReturn }; + } - //just \n - const expected = "\n"; + expect(testFn).toLogStdout(""); - expect(discolouredResult).toBe(expected); + //logResult assigned only after the abv assertion + expect(logResult).toStrictEqual({ + stack: null, + logTitle: null, + logBody: null, + }); }); }); describe("2) given that disableAll() is called on the constructor (indirectly on the instance)", () => { - it("should log nothing", async () => { - const { discolouredResult } = await processWorkerPromises(); + it("should log nothing", () => { + const logger = new NodeLogger("Log tester").disableAll(); - const expected = "\n"; - expect(discolouredResult).toBe(expected); + let logResult = {}; + + function testFn() { + const foo = "bar"; + const logReturn = logger.log({ foo }); + logResult = { ...logReturn }; + } + expect(testFn).toLogStdout(""); + + expect(logResult).toStrictEqual({ + stack: null, + logTitle: null, + logBody: null, + }); }); }); - describe("3) given that the log method is called after invoking disableAll() on the constructor", () => { - it("should NOT throw", async () => { - expect(async () => await processWorkerPromises()).not.toThrow(); + describe("3) given that the log method is called by the instance after invoking disableAll() on the constructor", () => { + it("should NOT throw", () => { + const logger = new NodeLogger("Log tester").disableAll(); + let logResult = {}; + + function testFn() { + const foo = "bar"; + const logReturn = logger.log({ foo }); + logResult = { ...logReturn }; + } + + expect(testFn).toLogStdout(""); + expect(logResult).toStrictEqual({ + stack: null, + logTitle: null, + logBody: null, + }); }); }); }); diff --git a/src/logger.ts b/src/logger.ts index 9000da9..aee81a8 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -342,14 +342,13 @@ class Logger { } /** * Disables all log messages of a particular logger instance/namespace - * @returns {Logger} */ disableAll(): this { const noopLike = () => { return Object.freeze({ - stack: "", - logTitle: "", - logBody: "", + stack: null, + logTitle: null, + logBody: null, }); }; From 0352136bf5dec32b80cfeaa5c633ca9c58f5d4c4 Mon Sep 17 00:00:00 2001 From: Zen-cronic <83657429+Zen-cronic@users.noreply.github.com> Date: Fri, 12 Jul 2024 19:12:58 -0400 Subject: [PATCH 07/11] continue: onlyFirstElemOption unit --- .../unit/onlyFirstElemOption-2.test.js | 73 ++++++++++++++ .../unit/onlyFirstElemOption-2.test.ts | 99 +++++++++++++++++++ 2 files changed, 172 insertions(+) create mode 100644 dist/__tests__/unit/onlyFirstElemOption-2.test.js create mode 100644 src/__tests__/unit/onlyFirstElemOption-2.test.ts diff --git a/dist/__tests__/unit/onlyFirstElemOption-2.test.js b/dist/__tests__/unit/onlyFirstElemOption-2.test.js new file mode 100644 index 0000000..4742bce --- /dev/null +++ b/dist/__tests__/unit/onlyFirstElemOption-2.test.js @@ -0,0 +1,73 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +require("jest-to-log"); +const index_1 = require("../../index"); +describe("onlyFirstElem option", () => { + function fn_1() { + const logger = new index_1.NodeLogger("Log tester"); + let stackPrintCount = 0; + const universeArr = [1, 2, 3]; + const spaceArr = [1, 2, 3]; + const outerArr = [1, 2, 3]; + const middleArr = [1, 2, 3]; + const innerArr = [1, 2, 3]; + const allArr = [ + universeArr, + spaceArr, + outerArr, + middleArr, + innerArr, + ]; + let length = 1; + for (let i = 0; i < allArr.length; i++) { + length = length * allArr[i].length; + } + universeArr.map(() => { + spaceArr.forEach(() => { + outerArr.map(() => { + middleArr.forEach(() => { + innerArr.map((num) => { + //only once + const { logTitle: result, stack } = logger.log({ num }, { onlyFirstElem: true }); + // "Log tester: *Array.map* -> *Array.forEach* -> *Array.map* -> *Array.forEach* -> *Array.map* -> *fn_1*\n"; + process.stderr.write(result + "\n"); + stackPrintCount++; + if (stackPrintCount <= 1) { + } + }); + }); + }); + }); + }); + } + function fn_2() { + const logger = new index_1.NodeLogger("Log tester"); + const testOuter = [1, 2, 3]; + const testInner = [1, 2, 3]; + testOuter.forEach(() => { + testInner.map((integer) => { + const { logTitle: result } = logger.log({ integer }, { onlyFirstElem: true }); + process.stderr.write(result + "\n"); + }); + }); + const testAnotherArr = new Int8Array(3); + testAnotherArr.forEach((integer) => { + const { logTitle: result } = logger.log({ integer }); + process.stderr.write(result + "\n"); + }); + //"Log tester: *Array.map* -> *Array.forEach* -> *fn_1* -> *Object.*\n + + //Log tester: "Int8Array.map" -> *fn_1*\n"; x length + } + describe("1) given n number of nested array functions", () => { + it("should log only the first element; the outer arrays are ignored recursively", async () => { + const expected = "Log tester: *Array.map* -> *Array.forEach* -> *Array.map* -> *Array.forEach* -> *Array.map* -> *fn_1*\n" + + "null\n".repeat(1); + }); + }); + describe("2) given the same instance of the log method is called on a different variable without any options", () => { + it("should log the other variable with default options: onlyFirstElem = false", async () => { + const expected = "Log tester: *Array.map* -> *Array.forEach* -> *fn_2*\n" + + "Log tester: *Int8Array.forEach* -> *fn_2*\n".repeat(1); + }); + }); +}); diff --git a/src/__tests__/unit/onlyFirstElemOption-2.test.ts b/src/__tests__/unit/onlyFirstElemOption-2.test.ts new file mode 100644 index 0000000..8c06c99 --- /dev/null +++ b/src/__tests__/unit/onlyFirstElemOption-2.test.ts @@ -0,0 +1,99 @@ +import "jest-to-log"; +import { NodeLogger } from "../../index"; +import { expect } from "@jest/globals"; + +describe("onlyFirstElem option", () => { + function fn_1() { + const logger = new NodeLogger("Log tester"); + + let stackPrintCount = 0; + + const universeArr: number[] = [1, 2, 3]; + const spaceArr: number[] = [1, 2, 3]; + const outerArr: number[] = [1, 2, 3]; + const middleArr: number[] = [1, 2, 3]; + const innerArr: number[] = [1, 2, 3]; + + const allArr: number[][] = [ + universeArr, + spaceArr, + outerArr, + middleArr, + innerArr, + ]; + + let length: number = 1; + for (let i = 0; i < allArr.length; i++) { + length = length * allArr[i].length; + } + + universeArr.map(() => { + spaceArr.forEach(() => { + outerArr.map(() => { + middleArr.forEach(() => { + innerArr.map((num) => { + //only once + const { logTitle: result, stack } = logger.log( + { num }, + { onlyFirstElem: true } + ); + + // "Log tester: *Array.map* -> *Array.forEach* -> *Array.map* -> *Array.forEach* -> *Array.map* -> *fn_1*\n"; + + process.stderr.write(result + "\n"); + + stackPrintCount++; + if (stackPrintCount <= 1) { + } + }); + }); + }); + }); + }); + } + + function fn_2() { + const logger = new NodeLogger("Log tester"); + + const testOuter = [1, 2, 3]; + const testInner = [1, 2, 3]; + + testOuter.forEach(() => { + testInner.map((integer) => { + const { logTitle: result } = logger.log( + { integer }, + { onlyFirstElem: true } + ); + + process.stderr.write(result + "\n"); + }); + }); + + const testAnotherArr = new Int8Array(3); + + testAnotherArr.forEach((integer) => { + const { logTitle: result } = logger.log({ integer }); + + process.stderr.write(result + "\n"); + }); + + //"Log tester: *Array.map* -> *Array.forEach* -> *fn_1* -> *Object.*\n + + //Log tester: "Int8Array.map" -> *fn_1*\n"; x length + } + + describe("1) given n number of nested array functions", () => { + it("should log only the first element; the outer arrays are ignored recursively", async () => { + const expected = + "Log tester: *Array.map* -> *Array.forEach* -> *Array.map* -> *Array.forEach* -> *Array.map* -> *fn_1*\n" + + "null\n".repeat(1); + }); + }); + + describe("2) given the same instance of the log method is called on a different variable without any options", () => { + it("should log the other variable with default options: onlyFirstElem = false", async () => { + const expected = + "Log tester: *Array.map* -> *Array.forEach* -> *fn_2*\n" + + "Log tester: *Int8Array.forEach* -> *fn_2*\n".repeat(1); + }); + }); +}); From ae376c9916afad4f230020a4373444ee1cc9d283 Mon Sep 17 00:00:00 2001 From: Zen-cronic <83657429+Zen-cronic@users.noreply.github.com> Date: Sat, 13 Jul 2024 12:06:25 -0400 Subject: [PATCH 08/11] updated: migrated onlyFirstElemOption unit --- dist/__tests__/unit/disableAll-2.test.js | 60 --------- .../unit/onlyFirstElemOption-2.test.js | 73 ---------- .../unit/onlyFirstElemOption.test.js | 99 +++++++++----- .../unit/onlyFirstElemOption.test.process.js | 88 ------------ jest.config.dist.js | 1 - jest.config.js | 2 - package.json | 6 +- .../unit/onlyFirstElemOption-2.test.ts | 99 -------------- .../unit/onlyFirstElemOption.test.process.ts | 115 ---------------- .../unit/onlyFirstElemOption.test.ts | 127 +++++++++++------- 10 files changed, 143 insertions(+), 527 deletions(-) delete mode 100644 dist/__tests__/unit/disableAll-2.test.js delete mode 100644 dist/__tests__/unit/onlyFirstElemOption-2.test.js delete mode 100644 dist/__tests__/unit/onlyFirstElemOption.test.process.js delete mode 100644 src/__tests__/unit/onlyFirstElemOption-2.test.ts delete mode 100644 src/__tests__/unit/onlyFirstElemOption.test.process.ts diff --git a/dist/__tests__/unit/disableAll-2.test.js b/dist/__tests__/unit/disableAll-2.test.js deleted file mode 100644 index 59728ba..0000000 --- a/dist/__tests__/unit/disableAll-2.test.js +++ /dev/null @@ -1,60 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -require("jest-to-log"); -const index_1 = require("../../index"); -const globals_1 = require("@jest/globals"); -describe("disableAll() method", () => { - describe("1) given that disableAll() is called directly on an instance", () => { - it("should log nothing", () => { - const logger = new index_1.NodeLogger("Log tester"); - let logResult = {}; - function testFn() { - logger.disableAll(); - const foo = "bar"; - const logReturn = logger.log({ foo }); - logResult = { ...logReturn }; - } - (0, globals_1.expect)(testFn).toLogStdout(""); - //logResult assigned only after the abv assertion - (0, globals_1.expect)(logResult).toStrictEqual({ - stack: null, - logTitle: null, - logBody: null, - }); - }); - }); - describe("2) given that disableAll() is called on the constructor (indirectly on the instance)", () => { - it("should log nothing", () => { - const logger = new index_1.NodeLogger("Log tester").disableAll(); - let logResult = {}; - function testFn() { - const foo = "bar"; - const logReturn = logger.log({ foo }); - logResult = { ...logReturn }; - } - (0, globals_1.expect)(testFn).toLogStdout(""); - (0, globals_1.expect)(logResult).toStrictEqual({ - stack: null, - logTitle: null, - logBody: null, - }); - }); - }); - describe("3) given that the log method is called by the instance after invoking disableAll() on the constructor", () => { - it("should NOT throw", () => { - const logger = new index_1.NodeLogger("Log tester").disableAll(); - let logResult = {}; - function testFn() { - const foo = "bar"; - const logReturn = logger.log({ foo }); - logResult = { ...logReturn }; - } - (0, globals_1.expect)(testFn).toLogStdout(""); - (0, globals_1.expect)(logResult).toStrictEqual({ - stack: null, - logTitle: null, - logBody: null, - }); - }); - }); -}); diff --git a/dist/__tests__/unit/onlyFirstElemOption-2.test.js b/dist/__tests__/unit/onlyFirstElemOption-2.test.js deleted file mode 100644 index 4742bce..0000000 --- a/dist/__tests__/unit/onlyFirstElemOption-2.test.js +++ /dev/null @@ -1,73 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -require("jest-to-log"); -const index_1 = require("../../index"); -describe("onlyFirstElem option", () => { - function fn_1() { - const logger = new index_1.NodeLogger("Log tester"); - let stackPrintCount = 0; - const universeArr = [1, 2, 3]; - const spaceArr = [1, 2, 3]; - const outerArr = [1, 2, 3]; - const middleArr = [1, 2, 3]; - const innerArr = [1, 2, 3]; - const allArr = [ - universeArr, - spaceArr, - outerArr, - middleArr, - innerArr, - ]; - let length = 1; - for (let i = 0; i < allArr.length; i++) { - length = length * allArr[i].length; - } - universeArr.map(() => { - spaceArr.forEach(() => { - outerArr.map(() => { - middleArr.forEach(() => { - innerArr.map((num) => { - //only once - const { logTitle: result, stack } = logger.log({ num }, { onlyFirstElem: true }); - // "Log tester: *Array.map* -> *Array.forEach* -> *Array.map* -> *Array.forEach* -> *Array.map* -> *fn_1*\n"; - process.stderr.write(result + "\n"); - stackPrintCount++; - if (stackPrintCount <= 1) { - } - }); - }); - }); - }); - }); - } - function fn_2() { - const logger = new index_1.NodeLogger("Log tester"); - const testOuter = [1, 2, 3]; - const testInner = [1, 2, 3]; - testOuter.forEach(() => { - testInner.map((integer) => { - const { logTitle: result } = logger.log({ integer }, { onlyFirstElem: true }); - process.stderr.write(result + "\n"); - }); - }); - const testAnotherArr = new Int8Array(3); - testAnotherArr.forEach((integer) => { - const { logTitle: result } = logger.log({ integer }); - process.stderr.write(result + "\n"); - }); - //"Log tester: *Array.map* -> *Array.forEach* -> *fn_1* -> *Object.*\n + - //Log tester: "Int8Array.map" -> *fn_1*\n"; x length - } - describe("1) given n number of nested array functions", () => { - it("should log only the first element; the outer arrays are ignored recursively", async () => { - const expected = "Log tester: *Array.map* -> *Array.forEach* -> *Array.map* -> *Array.forEach* -> *Array.map* -> *fn_1*\n" + - "null\n".repeat(1); - }); - }); - describe("2) given the same instance of the log method is called on a different variable without any options", () => { - it("should log the other variable with default options: onlyFirstElem = false", async () => { - const expected = "Log tester: *Array.map* -> *Array.forEach* -> *fn_2*\n" + - "Log tester: *Int8Array.forEach* -> *fn_2*\n".repeat(1); - }); - }); -}); diff --git a/dist/__tests__/unit/onlyFirstElemOption.test.js b/dist/__tests__/unit/onlyFirstElemOption.test.js index cfa60e0..0a5a3d6 100644 --- a/dist/__tests__/unit/onlyFirstElemOption.test.js +++ b/dist/__tests__/unit/onlyFirstElemOption.test.js @@ -1,45 +1,76 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -const testHelper_1 = require("../../utils/testHelper"); +require("jest-to-log"); +const index_1 = require("../../index"); +const globals_1 = require("@jest/globals"); describe("onlyFirstElem option", () => { - const { createMessagePromise, createWorkerDataPromise } = (0, testHelper_1.setupTest)("unit", "onlyFirstElemOption.test.process.ts"); - /** - * - * @param {boolean} [removeNullAndN=false] - * @returns {Promise<{length: number;discolouredResult: string;}>} - */ - async function processWorkerPromises(removeNullAndN) { - let promises = [ - createWorkerDataPromise(), - createMessagePromise(), - ]; - const promisesResult = await Promise.all(promises); - let workerData = promisesResult[0]; - if (removeNullAndN) { - workerData = workerData.replace(/null\n/g, ""); - } - const message = promisesResult[1]; - const { length = 1 } = message || {}; - if (typeof length !== "number") { - throw new Error(`Invalid length from child process: ${length}`); - } - const discolouredResult = workerData.replace(/(\x1b\[\d+;\d+m)|(\x1b\[\d+m)/g, ""); - return { length, discolouredResult }; - } describe("1) given n number of nested array functions", () => { - it("should log only the first element; the outer arrays are ignored recursively", async () => { - const { length, discolouredResult } = await processWorkerPromises(); - const expected = "Log tester: *Array.map* -> *Array.forEach* -> *Array.map* -> *Array.forEach* -> *Array.map* -> *fn_1*\n" + - "null\n".repeat(length); - expect(discolouredResult).toBe(expected); + it("should log only the first element; the outer arrays are ignored recursively", () => { + const logger = new index_1.NodeLogger("Log tester", { + onlyFirstElem: true, + entryPoint: "Object.toLogStdoutMatcher", + }); + function testFn() { + const universeArr = [1, 2, 3]; + const spaceArr = [1, 2, 3]; + const outerArr = [1, 2, 3]; + const middleArr = [1, 2, 3]; + const innerArr = [1, 2, 3]; + universeArr.map(() => { + spaceArr.forEach(() => { + outerArr.map(() => { + middleArr.forEach(() => { + innerArr.map((num) => { + //only once + logger.log({ num }); + }); + }); + }); + }); + }); + } + const expected = "Log tester: *Array.map* -> *Array.forEach* -> *Array.map* -> *Array.forEach* -> *Array.map* -> *testFn*\n" + + "{\n" + + ' "num": 1\n' + + "}\n" + + "\n"; + (0, globals_1.expect)(testFn).toLogStdout(expected); }); }); describe("2) given the same instance of the log method is called on a different variable without any options", () => { it("should log the other variable with default options: onlyFirstElem = false", async () => { - const { length, discolouredResult } = await processWorkerPromises(true); - const expected = "Log tester: *Array.map* -> *Array.forEach* -> *fn_2*\n" + - "Log tester: *Int8Array.forEach* -> *fn_2*\n".repeat(length); - expect(discolouredResult).toBe(expected); + function testFn() { + const logger = new index_1.NodeLogger("Log tester"); + const testOuter = [1, 2, 3]; + const testInner = [1, 2, 3]; + testOuter.forEach(() => { + testInner.map((num_1) => { + logger.log({ num_1 }, { onlyFirstElem: true, entryPoint: "Object.toLogStdoutMatcher" }); + }); + }); + const testAnotherArr = new Uint8Array(3); + testAnotherArr.forEach((num_2) => { + logger.log({ num_2 }, { entryPoint: "Object.toLogStdoutMatcher" }); + }); + } + const expectedFirstCall = "Log tester: *Array.map* -> *Array.forEach* -> *testFn*" + + "\n" + + "{\n" + + ' "num_1": 1\n' + + "}\n" + + "\n"; + const expectedSecondCall = [1, 2, 3].reduce((acc, _) => { + const logCallAndBody = "Log tester: *Uint8Array.forEach* -> *testFn*" + + "\n" + + "{\n" + + ` "num_2": 0\n` + + "}\n" + + "\n"; + acc += logCallAndBody; + return acc; + }, ""); + const expectedStr = expectedFirstCall + expectedSecondCall; + (0, globals_1.expect)(testFn).toLogStdout(expectedStr); }); }); }); diff --git a/dist/__tests__/unit/onlyFirstElemOption.test.process.js b/dist/__tests__/unit/onlyFirstElemOption.test.process.js deleted file mode 100644 index 54f3351..0000000 --- a/dist/__tests__/unit/onlyFirstElemOption.test.process.js +++ /dev/null @@ -1,88 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const index_1 = require("../../index"); -(async function () { - try { - function fn_1() { - const logger = new index_1.NodeLogger("Log tester"); - let stackPrintCount = 0; - const universeArr = [1, 2, 3]; - const spaceArr = [1, 2, 3]; - const outerArr = [1, 2, 3]; - const middleArr = [1, 2, 3]; - const innerArr = [1, 2, 3]; - const allArr = [ - universeArr, - spaceArr, - outerArr, - middleArr, - innerArr, - ]; - let length = 1; - for (let i = 0; i < allArr.length; i++) { - length = length * allArr[i].length; - } - universeArr.map(() => { - spaceArr.forEach(() => { - outerArr.map(() => { - middleArr.forEach(() => { - innerArr.map((num) => { - //only once - const { logTitle: result, stack } = logger.log({ num }, { onlyFirstElem: true }); - // "Log tester: *Array.map* -> *Array.forEach* -> *Array.map* -> *Array.forEach* -> *Array.map* -> *fn_1*\n"; - process.stderr.write(result + "\n"); - stackPrintCount++; - if (stackPrintCount <= 1) { - } - }); - }); - }); - }); - }); - process.send({ length: length - 1 }); - } - function fn_2() { - const logger = new index_1.NodeLogger("Log tester"); - const testOuter = [1, 2, 3]; - const testInner = [1, 2, 3]; - testOuter.forEach(() => { - testInner.map((integer) => { - const { logTitle: result } = logger.log({ integer }, { onlyFirstElem: true }); - process.stderr.write(result + "\n"); - }); - }); - const testAnotherArr = new Int8Array(3); - testAnotherArr.forEach((integer) => { - const { logTitle: result } = logger.log({ integer }); - process.stderr.write(result + "\n"); - }); - //"Log tester: *Array.map* -> *Array.forEach* -> *fn_1* -> *Object.*\n + - //Log tester: "Int8Array.map" -> *fn_1*\n"; x length - process.send({ length: testAnotherArr.length }); - } - const testCaseNum = await new Promise((resolve, reject) => { - process.once("message", (message) => { - if (typeof message === "number") { - console.log("message from parent: " + message); - resolve(message); - } - else { - reject(new Error("Invalid test case sent from main process")); - } - }); - }); - switch (testCaseNum) { - case 1: - fn_1(); - break; - case 2: - fn_2(); - break; - default: - break; - } - } - catch (error) { - process.send({ error: error.message }); - } -})(); diff --git a/jest.config.dist.js b/jest.config.dist.js index 35e54e6..f3b0686 100644 --- a/jest.config.dist.js +++ b/jest.config.dist.js @@ -1,5 +1,4 @@ -"use strict"; /** @type {import('ts-jest').JestConfigWithTsJest} */ module.exports = { diff --git a/jest.config.js b/jest.config.js index 423cc80..2e34448 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,4 +1,3 @@ -"use strict"; /** @type {import('ts-jest').JestConfigWithTsJest} */ module.exports = { @@ -6,7 +5,6 @@ module.exports = { testMatch: ["**/__tests__/**/*.+(spec|test).+(ts|tsx)"], transform: { - // "^.+\\.(ts|tsx)$": "ts-jest", "^.+\\.(ts|tsx)$": ["ts-jest", {isolatedModules: true}], }, }; diff --git a/package.json b/package.json index bd733f5..7fb989d 100644 --- a/package.json +++ b/package.json @@ -21,10 +21,10 @@ "dev:pg": "nodemon --watch \"pg/**\" --ext \"js,ts,json,mjs,cjs\" --exec \"ts-node\"", "dev": "nodemon --watch \"dev/**\" --ext \"js,ts,json,mjs,cjs\" --exec \"ts-node\"", - "test:jest": "jest --watch", + "test:jest": "jest --watchAll", "test:ci": "jest --ci", - "test:js": "jest --watch --config jest.config.dist.js", - "test": "set NODE_OPTIONS=-r ts-node/register && jest --watch", + "test:js": "jest --watchAll --config jest.config.dist.js", + "test": "set NODE_OPTIONS=-r ts-node/register && jest --watchAll", "test:ts:ci": "export NODE_OPTIONS='-r ts-node/register' && jest --ci" }, "keywords": [ diff --git a/src/__tests__/unit/onlyFirstElemOption-2.test.ts b/src/__tests__/unit/onlyFirstElemOption-2.test.ts deleted file mode 100644 index 8c06c99..0000000 --- a/src/__tests__/unit/onlyFirstElemOption-2.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import "jest-to-log"; -import { NodeLogger } from "../../index"; -import { expect } from "@jest/globals"; - -describe("onlyFirstElem option", () => { - function fn_1() { - const logger = new NodeLogger("Log tester"); - - let stackPrintCount = 0; - - const universeArr: number[] = [1, 2, 3]; - const spaceArr: number[] = [1, 2, 3]; - const outerArr: number[] = [1, 2, 3]; - const middleArr: number[] = [1, 2, 3]; - const innerArr: number[] = [1, 2, 3]; - - const allArr: number[][] = [ - universeArr, - spaceArr, - outerArr, - middleArr, - innerArr, - ]; - - let length: number = 1; - for (let i = 0; i < allArr.length; i++) { - length = length * allArr[i].length; - } - - universeArr.map(() => { - spaceArr.forEach(() => { - outerArr.map(() => { - middleArr.forEach(() => { - innerArr.map((num) => { - //only once - const { logTitle: result, stack } = logger.log( - { num }, - { onlyFirstElem: true } - ); - - // "Log tester: *Array.map* -> *Array.forEach* -> *Array.map* -> *Array.forEach* -> *Array.map* -> *fn_1*\n"; - - process.stderr.write(result + "\n"); - - stackPrintCount++; - if (stackPrintCount <= 1) { - } - }); - }); - }); - }); - }); - } - - function fn_2() { - const logger = new NodeLogger("Log tester"); - - const testOuter = [1, 2, 3]; - const testInner = [1, 2, 3]; - - testOuter.forEach(() => { - testInner.map((integer) => { - const { logTitle: result } = logger.log( - { integer }, - { onlyFirstElem: true } - ); - - process.stderr.write(result + "\n"); - }); - }); - - const testAnotherArr = new Int8Array(3); - - testAnotherArr.forEach((integer) => { - const { logTitle: result } = logger.log({ integer }); - - process.stderr.write(result + "\n"); - }); - - //"Log tester: *Array.map* -> *Array.forEach* -> *fn_1* -> *Object.*\n + - //Log tester: "Int8Array.map" -> *fn_1*\n"; x length - } - - describe("1) given n number of nested array functions", () => { - it("should log only the first element; the outer arrays are ignored recursively", async () => { - const expected = - "Log tester: *Array.map* -> *Array.forEach* -> *Array.map* -> *Array.forEach* -> *Array.map* -> *fn_1*\n" + - "null\n".repeat(1); - }); - }); - - describe("2) given the same instance of the log method is called on a different variable without any options", () => { - it("should log the other variable with default options: onlyFirstElem = false", async () => { - const expected = - "Log tester: *Array.map* -> *Array.forEach* -> *fn_2*\n" + - "Log tester: *Int8Array.forEach* -> *fn_2*\n".repeat(1); - }); - }); -}); diff --git a/src/__tests__/unit/onlyFirstElemOption.test.process.ts b/src/__tests__/unit/onlyFirstElemOption.test.process.ts deleted file mode 100644 index 55cf3fd..0000000 --- a/src/__tests__/unit/onlyFirstElemOption.test.process.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { NodeLogger } from "../../index"; -import { NonNullProcessSend } from "../../types"; - -(async function () { - try { - function fn_1() { - const logger = new NodeLogger("Log tester"); - - let stackPrintCount = 0; - - const universeArr: number[] = [1, 2, 3]; - const spaceArr: number[] = [1, 2, 3]; - const outerArr: number[] = [1, 2, 3]; - const middleArr: number[] = [1, 2, 3]; - const innerArr: number[] = [1, 2, 3]; - - const allArr: number[][] = [ - universeArr, - spaceArr, - outerArr, - middleArr, - innerArr, - ]; - - let length: number = 1; - for (let i = 0; i < allArr.length; i++) { - length = length * allArr[i].length; - } - - universeArr.map(() => { - spaceArr.forEach(() => { - outerArr.map(() => { - middleArr.forEach(() => { - innerArr.map((num) => { - //only once - const { logTitle: result, stack } = logger.log( - { num }, - { onlyFirstElem: true } - ); - - // "Log tester: *Array.map* -> *Array.forEach* -> *Array.map* -> *Array.forEach* -> *Array.map* -> *fn_1*\n"; - - process.stderr.write(result + "\n"); - - stackPrintCount++; - if (stackPrintCount <= 1) { - } - }); - }); - }); - }); - }); - - (process.send as NonNullProcessSend)({ length: length - 1 }); - } - - function fn_2() { - const logger = new NodeLogger("Log tester"); - - const testOuter = [1, 2, 3]; - const testInner = [1, 2, 3]; - - testOuter.forEach(() => { - testInner.map((integer) => { - const { logTitle: result } = logger.log( - { integer }, - { onlyFirstElem: true } - ); - - process.stderr.write(result + "\n"); - }); - }); - - const testAnotherArr = new Int8Array(3); - - testAnotherArr.forEach((integer) => { - const { logTitle: result } = logger.log({ integer }); - - process.stderr.write(result + "\n"); - }); - - //"Log tester: *Array.map* -> *Array.forEach* -> *fn_1* -> *Object.*\n + - //Log tester: "Int8Array.map" -> *fn_1*\n"; x length - - (process.send as NonNullProcessSend)({ length: testAnotherArr.length }); - } - - const testCaseNum = await new Promise((resolve, reject) => { - process.once("message", (message) => { - if (typeof message === "number") { - console.log("message from parent: " + message); - - resolve(message); - } else { - reject(new Error("Invalid test case sent from main process")); - } - }); - }); - - switch (testCaseNum) { - case 1: - fn_1(); - break; - - case 2: - fn_2(); - break; - - default: - break; - } - } catch (error: any) { - (process.send as NonNullProcessSend)({ error: (error as Error).message }); - } -})(); diff --git a/src/__tests__/unit/onlyFirstElemOption.test.ts b/src/__tests__/unit/onlyFirstElemOption.test.ts index 29ad1f2..1a9918f 100644 --- a/src/__tests__/unit/onlyFirstElemOption.test.ts +++ b/src/__tests__/unit/onlyFirstElemOption.test.ts @@ -1,68 +1,91 @@ -import { WorkerNonErrorMessage } from "../../types"; -import { setupTest } from "../../utils/testHelper"; +import "jest-to-log"; +import { NodeLogger } from "../../index"; +import { expect } from "@jest/globals"; describe("onlyFirstElem option", () => { - const { createMessagePromise, createWorkerDataPromise } = setupTest( - "unit", - "onlyFirstElemOption.test.process.ts" - ); - - /** - * - * @param {boolean} [removeNullAndN=false] - * @returns {Promise<{length: number;discolouredResult: string;}>} - */ - async function processWorkerPromises(removeNullAndN?: boolean): Promise<{ - length: number; - discolouredResult: string; - }> { - let promises: (Promise | Promise)[] = [ - createWorkerDataPromise(), - createMessagePromise(), - ]; - - const promisesResult = await Promise.all(promises); - - let workerData = promisesResult[0]; - if (removeNullAndN) { - workerData = (workerData as string).replace(/null\n/g, ""); - } - const message = promisesResult[1]; - - const { length = 1 } = message || {}; - if (typeof length !== "number") { - throw new Error(`Invalid length from child process: ${length}`); - } - - const discolouredResult = (workerData as string).replace( - /(\x1b\[\d+;\d+m)|(\x1b\[\d+m)/g, - "" - ); - - return { length, discolouredResult }; - } - describe("1) given n number of nested array functions", () => { - it("should log only the first element; the outer arrays are ignored recursively", async () => { - const { length, discolouredResult } = await processWorkerPromises(); + it("should log only the first element; the outer arrays are ignored recursively", () => { + const logger = new NodeLogger("Log tester", { + onlyFirstElem: true, + entryPoint: "Object.toLogStdoutMatcher", + }); + function testFn() { + const universeArr: number[] = [1, 2, 3]; + const spaceArr: number[] = [1, 2, 3]; + const outerArr: number[] = [1, 2, 3]; + const middleArr: number[] = [1, 2, 3]; + const innerArr: number[] = [1, 2, 3]; + + universeArr.map(() => { + spaceArr.forEach(() => { + outerArr.map(() => { + middleArr.forEach(() => { + innerArr.map((num) => { + //only once + logger.log({ num }); + }); + }); + }); + }); + }); + } const expected = - "Log tester: *Array.map* -> *Array.forEach* -> *Array.map* -> *Array.forEach* -> *Array.map* -> *fn_1*\n" + - "null\n".repeat(length); + "Log tester: *Array.map* -> *Array.forEach* -> *Array.map* -> *Array.forEach* -> *Array.map* -> *testFn*\n" + + "{\n" + + ' "num": 1\n' + + "}\n" + + "\n"; - expect(discolouredResult).toBe(expected); + expect(testFn).toLogStdout(expected); }); }); describe("2) given the same instance of the log method is called on a different variable without any options", () => { it("should log the other variable with default options: onlyFirstElem = false", async () => { - const { length, discolouredResult } = await processWorkerPromises(true); + function testFn() { + const logger = new NodeLogger("Log tester"); - const expected = - "Log tester: *Array.map* -> *Array.forEach* -> *fn_2*\n" + - "Log tester: *Int8Array.forEach* -> *fn_2*\n".repeat(length); + const testOuter = [1, 2, 3]; + const testInner = [1, 2, 3]; + + testOuter.forEach(() => { + testInner.map((num_1) => { + logger.log( + { num_1 }, + { onlyFirstElem: true, entryPoint: "Object.toLogStdoutMatcher" } + ); + }); + }); + + const testAnotherArr = new Uint8Array(3); + + testAnotherArr.forEach((num_2) => { + logger.log({ num_2 }, { entryPoint: "Object.toLogStdoutMatcher" }); + }); + } + + const expectedFirstCall: string = + "Log tester: *Array.map* -> *Array.forEach* -> *testFn*" + + "\n" + + "{\n" + + ' "num_1": 1\n' + + "}\n" + + "\n"; + const expectedSecondCall: string = [1, 2, 3].reduce((acc, _) => { + const logCallAndBody = + "Log tester: *Uint8Array.forEach* -> *testFn*" + + "\n" + + "{\n" + + ` "num_2": 0\n` + + "}\n" + + "\n"; + acc += logCallAndBody; + return acc; + }, ""); - expect(discolouredResult).toBe(expected); + const expectedStr = expectedFirstCall + expectedSecondCall; + expect(testFn).toLogStdout(expectedStr); }); }); }); From 447c9403eaa9052281b0a5615972071b8b06d469 Mon Sep 17 00:00:00 2001 From: Zen-cronic <83657429+Zen-cronic@users.noreply.github.com> Date: Sat, 13 Jul 2024 12:17:56 -0400 Subject: [PATCH 09/11] updated: migrated logCallerLineChecker unit --- .../unit/logCallerLineChecker.test.js | 27 +++++-------- dist/node.js | 11 +----- .../unit/logCallerLineChecker.test.ts | 38 ++++++------------- src/node.ts | 13 +------ 4 files changed, 25 insertions(+), 64 deletions(-) diff --git a/dist/__tests__/unit/logCallerLineChecker.test.js b/dist/__tests__/unit/logCallerLineChecker.test.js index 277394a..4eeede9 100644 --- a/dist/__tests__/unit/logCallerLineChecker.test.js +++ b/dist/__tests__/unit/logCallerLineChecker.test.js @@ -11,44 +11,35 @@ describe("logCallerLineChecker func", () => { //js: 3 const fileExt = (0, testHelper_1.determineFileExt)(__filename); const currentLogCallerLine = fileExt === "ts" ? 2 : 3; + // const currentLogCallerLine = 2 describe("given a call stack is provided", () => { it("should return the index of the line containing the main log func call", () => { - // at NodeLogger.captureStackTrace [as log] (C:...) - // at log (C:...) - //NOT NodeLogger.log - //revmp: // at NodeLogger._createErrorStack () - // at NodeLogger.log () + // at NodeLogger.log () // at Object. () // at Promise.then.completed () - const logger = new index_1.NodeLogger("Test"); + const logger = new index_1.NodeLogger("Test", { + entryPoint: "Promise.then.completed", + }); const foo = "bar"; const logInfo = logger.log({ foo }); - // console.log('===================================='); - // console.log(logInfo.stack); - // console.log('===================================='); const result = (0, logCallerLineChecker_1.default)(logInfo.stack); expect(result).toBe(currentLogCallerLine); }); }); describe("given a call stack is provided inside a function in the test suite", () => { it("should return the index of the line containing the main log func call", () => { - // at NodeLogger.captureStackTrace [as log] (C:...) - // at log (C:...) - // at Object.testWrapper (C:...) - // revmp: // at NodeLogger._createErrorStack () - // at NodeLogger.log () + // at NodeLogger.log () // at testWrapper () // at Object. () // at Promise.then.completed () const testWrapper = () => { - const logger = new index_1.NodeLogger("Test"); + const logger = new index_1.NodeLogger("Test", { + entryPoint: "Promise.then.completed", + }); const bar = "foo"; const logInfo = logger.log({ bar }); - // console.log('===================================='); - // console.log(logInfo.stack); - // console.log('===================================='); const result = (0, logCallerLineChecker_1.default)(logInfo.stack); expect(result).toBe(currentLogCallerLine); }; diff --git a/dist/node.js b/dist/node.js index 0a74429..d4839ff 100644 --- a/dist/node.js +++ b/dist/node.js @@ -7,11 +7,6 @@ exports.NodeLogger = void 0; const logger_1 = require("./logger"); const logCallerLineChecker_1 = __importDefault(require("./utils/logCallerLineChecker")); class NodeLogger extends logger_1.Logger { - // static loggers: NodeLogger[] = []; - // constructor(namespace: string, options?: LogOptions) { - // super(namespace, options); - // NodeLogger.loggers.push(this); - // } _writeLog(logTitle, logBody) { process.stdout.write(logTitle + "\n" + logBody + "\n\n"); } @@ -27,7 +22,6 @@ class NodeLogger extends logger_1.Logger { const currentLine = callStackParts[logLineIndex]; //at" "x" "y let currentLineParts = currentLine.trim().split(" "); - // if (!currentLine || currentLineParts[1] === "Module._compile") { if (!currentLine || currentLineParts[1] === this._options.entryPoint) { break; } @@ -46,7 +40,7 @@ class NodeLogger extends logger_1.Logger { if (currentLinePartsLen === 3) { calleeFunc = currentLineParts[1]; //iterable func or normal func - const [iterableType, iterableFunc] = calleeFunc.split("."); + const [iterableType, _iterableFunc_] = calleeFunc.split("."); if (logger_1.Logger.NATIVE_ITERATORS_TYPES.includes(iterableType) && this._options.ignoreIterators) { continue; @@ -102,8 +96,7 @@ class NodeLogger extends logger_1.Logger { } _createErrorStack() { const err = {}; - //modified to include till Module._compile - Error.stackTraceLimit = 15; + Error.stackTraceLimit = 100; Error.captureStackTrace(err); return err; } diff --git a/src/__tests__/unit/logCallerLineChecker.test.ts b/src/__tests__/unit/logCallerLineChecker.test.ts index 9ac43ed..628b0c1 100644 --- a/src/__tests__/unit/logCallerLineChecker.test.ts +++ b/src/__tests__/unit/logCallerLineChecker.test.ts @@ -1,5 +1,4 @@ import { NodeLogger } from "../../index"; -// import { NodeLogger } from "../../node"; import { LogReturn } from "../../logger"; import { FileExt } from "../../types"; import logCallerLineChecker from "../../utils/logCallerLineChecker"; @@ -8,30 +7,24 @@ import { determineFileExt } from "../../utils/testHelper"; describe("logCallerLineChecker func", () => { //ts: 2 //js: 3 - const fileExt: FileExt = determineFileExt(__filename) - const currentLogCallerLine = fileExt === "ts" ? 2 : 3 + const fileExt: FileExt = determineFileExt(__filename); + const currentLogCallerLine = fileExt === "ts" ? 2 : 3; + // const currentLogCallerLine = 2 describe("given a call stack is provided", () => { it("should return the index of the line containing the main log func call", () => { - // at NodeLogger.captureStackTrace [as log] (C:...) - // at log (C:...) - //NOT NodeLogger.log - - //revmp: // at NodeLogger._createErrorStack () - // at NodeLogger.log () + // at NodeLogger.log () // at Object. () // at Promise.then.completed () - const logger = new NodeLogger("Test"); + const logger = new NodeLogger("Test", { + entryPoint: "Promise.then.completed", + }); const foo = "bar"; const logInfo: LogReturn = logger.log({ foo }); - // console.log('===================================='); - // console.log(logInfo.stack); - // console.log('===================================='); - const result: number = logCallerLineChecker(logInfo.stack as string); expect(result).toBe(currentLogCallerLine); @@ -40,25 +33,18 @@ describe("logCallerLineChecker func", () => { describe("given a call stack is provided inside a function in the test suite", () => { it("should return the index of the line containing the main log func call", () => { - // at NodeLogger.captureStackTrace [as log] (C:...) - // at log (C:...) - // at Object.testWrapper (C:...) - - // revmp: // at NodeLogger._createErrorStack () - // at NodeLogger.log () + // at NodeLogger.log () // at testWrapper () // at Object. () // at Promise.then.completed () const testWrapper = () => { - const logger = new NodeLogger("Test"); + const logger = new NodeLogger("Test", { + entryPoint: "Promise.then.completed", + }); const bar = "foo"; - const logInfo: LogReturn= logger.log({ bar }); - - // console.log('===================================='); - // console.log(logInfo.stack); - // console.log('===================================='); + const logInfo: LogReturn = logger.log({ bar }); const result: number = logCallerLineChecker(logInfo.stack as string); expect(result).toBe(currentLogCallerLine); diff --git a/src/node.ts b/src/node.ts index 45c4509..f652bb6 100644 --- a/src/node.ts +++ b/src/node.ts @@ -2,13 +2,6 @@ import { IEnv, LogOptions, LogReturn, Logger } from "./logger"; import logCallerLineChecker from "./utils/logCallerLineChecker"; export class NodeLogger extends Logger implements IEnv { - // static loggers: NodeLogger[] = []; - - // constructor(namespace: string, options?: LogOptions) { - // super(namespace, options); - // NodeLogger.loggers.push(this); - // } - _writeLog(logTitle: string, logBody: string) { process.stdout.write(logTitle + "\n" + logBody + "\n\n"); } @@ -31,7 +24,6 @@ export class NodeLogger extends Logger implements IEnv { //at" "x" "y let currentLineParts = currentLine.trim().split(" "); - // if (!currentLine || currentLineParts[1] === "Module._compile") { if (!currentLine || currentLineParts[1] === this._options.entryPoint) { break; } @@ -61,7 +53,7 @@ export class NodeLogger extends Logger implements IEnv { calleeFunc = currentLineParts[1]; //iterable func or normal func - const [iterableType, iterableFunc] = calleeFunc.split("."); + const [iterableType, _iterableFunc_] = calleeFunc.split("."); if ( Logger.NATIVE_ITERATORS_TYPES.includes(iterableType) && @@ -143,8 +135,7 @@ export class NodeLogger extends Logger implements IEnv { _createErrorStack() { const err = {}; - //modified to include till Module._compile - Error.stackTraceLimit = 15; + Error.stackTraceLimit = 100; Error.captureStackTrace(err); return err as { stack: string }; From b4f6a79dc60be055ba012104f421db384da39a6b Mon Sep 17 00:00:00 2001 From: Zen-cronic <83657429+Zen-cronic@users.noreply.github.com> Date: Sat, 13 Jul 2024 12:26:30 -0400 Subject: [PATCH 10/11] updated: ci node 16 --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e46617c..43f34a5 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -8,7 +8,7 @@ jobs: strategy: matrix: - node-version: [14.x] + node-version: [16.x] steps: - uses: actions/checkout@v4 From d0d79f2726afcee8a30ac37409e39a971b8dbf0a Mon Sep 17 00:00:00 2001 From: Zen-cronic <83657429+Zen-cronic@users.noreply.github.com> Date: Sat, 13 Jul 2024 12:28:40 -0400 Subject: [PATCH 11/11] updated: support node >= 16 --- .travis.yml | 7 ------- package.json | 2 +- 2 files changed, 1 insertion(+), 8 deletions(-) delete mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index a4cd3b8..0000000 --- a/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: node_js -node_js: - - 14 -install: - - npm install -script: - - npm run test:ci diff --git a/package.json b/package.json index 7fb989d..23fe5f7 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "homepage": "https://github.com/Zen-cronic/scope-logger/#readme", "main": "index.js", "engines": { - "node": ">=14" + "node": ">=16" }, "scripts": { "start": "node index",