From e00086ea425a9cb6a849e3853bd3ae79910b3d44 Mon Sep 17 00:00:00 2001 From: Luke Karrys Date: Sat, 13 Apr 2024 20:15:06 -0700 Subject: [PATCH] feat: add timers and read --- README.md | 136 ++++++++++++++++++++++++++- lib/index.js | 84 +++++++++++++++++ tap-snapshots/test/index.js.test.cjs | 53 +++++++++++ test/index.js | 41 +++++++- test/input.js | 79 ++++++++++++++++ test/time.js | 50 ++++++++++ 6 files changed, 434 insertions(+), 9 deletions(-) create mode 100644 test/input.js create mode 100644 test/time.js diff --git a/README.md b/README.md index 770ab09..f4b174e 100644 --- a/README.md +++ b/README.md @@ -4,51 +4,109 @@ Emits events on the process object which a listener can consume and print to the This is used by various modules within the npm CLI stack in order to send log events that can be consumed by a listener on the process object. -Currently emits `log` and `output` events. +Currently emits `log`, `output`, `input`, and `time` events. ## API ```js -const { log, output } = require('proc-log') +const { log, output, input, time } = require('proc-log') ``` #### output * `output.standard(...args)` calls `process.emit('output', 'standard', ...args)` + This is for general standard output. Consumers will typically show this on stdout (after optionally formatting or filtering it). + * `output.error(...args)` calls `process.emit('output', 'error', ...args)` + This is for general error output. Consumers will typically show this on stderr (after optionally formatting or filtering it). + * `output.buffer(...args)` calls `process.emit('output', 'buffer', ...args)` + This is for buffered output. Consumers will typically buffer this until they are ready to display. + * `output.LEVELS` an array of strings of all output method names #### log * `log.error(...args)` calls `process.emit('log', 'error', ...args)` + The highest log level. For printing extremely serious errors that indicate something went wrong. + * `log.warn(...args)` calls `process.emit('log', 'warn', ...args)` + A fairly high log level. Things that the user needs to be aware of, but which won't necessarily cause improper functioning of the system. + * `log.notice(...args)` calls `process.emit('log', 'notice', ...args)` + Notices which are important, but not necessarily dangerous or a cause for excess concern. + * `log.info(...args)` calls `process.emit('log', 'info', ...args)` + Informative messages that may benefit the user, but aren't particularly important. + * `log.verbose(...args)` calls `process.emit('log', 'verbose', ...args)` + Noisy output that is more detail that most users will care about. + * `log.silly(...args)` calls `process.emit('log', 'silly', ...args)` + Extremely noisy excessive logging messages that are typically only useful for debugging. + * `log.http(...args)` calls `process.emit('log', 'http', ...args)` + Information about HTTP requests made and/or completed. + * `log.timing(...args)` calls `process.emit('log', 'timing', ...args)` + Timing information. + * `log.pause()` calls `process.emit('log', 'pause')` + Used to tell the consumer to stop printing messages. + * `log.resume()` calls `process.emit('log', 'resume')` + Used to tell the consumer that it is ok to print messages again. + * `log.LEVELS` an array of strings of all log method names +#### input + +* `input.start(fn?)` calls `process.emit('input', 'start')` + + Used to tell the consumer that the terminal is going to begin reading user input. Returns a function that will call `input.end()` for convenience. + + This also takes an optional callback which will run `input.end()` on its completion. If the callback returns a `Promise` then `input.end()` will be run during `finally()`. + +* `input.end()` calls `process.emit('input', 'end')` + + Used to tell the consumer that the terminal has stopped reading user input. + +* `input.read(...args): Promise` calls `process.emit('input', 'read', resolve, reject, ...args)` + + Used to tell the consumer that the terminal is reading user input and returns a `Promise` that the producer can `await` until the consumer has finished its async action. + + This emits `resolve` and `reject` functions (in addition to all passed in arguments) which the consumer must use to resolve the returned `Promise`. + +#### time + +* `time.start(timerName, fn?)` calls `process.emit('time', 'start', 'timerName')` + + Used to start a timer with the specified name. Returns a function that will call `time.end()` for convenience. + + This also takes an optional callback which will run `time.end()` on its completion. If the callback returns a `Promise` then `time.end()` will be run during `finally()`. + +* `time.end(timerName)` calls `process.emit('time', 'end', timeName)` + + Used to tell the consumer to stop a timer with the specified name. + ## Examples +### log + Every `log` method calls `process.emit('log', level, ...otherArgs)` internally. So in order to consume those events you need to do `process.on('log', fn)`. -### Colorize based on level +#### Colorize based on level Here's an example of how to consume `proc-log` log events and colorize them based on level: @@ -64,7 +122,7 @@ process.on('log', (level, ...args) => { }) ``` -### Pause and resume +#### Pause and resume `log.pause` and `log.resume` are included so you have the ability to tell your consumer that you want to pause or resume your display of logs. In the npm CLI we use this to buffer all logs on init until we know the correct loglevel to display. But we also setup a second handler that writes everything to a file even if paused. @@ -92,3 +150,73 @@ process.on('log', (...args) => { fs.appendFileSync('debug.log', args.join(' ')) }) ``` + +### input + +### `start` and `end` + +**producer.js** +```js +const { output, input } = require('proc-log') +const { readFromUserInput } = require('./my-read') + +// Using callback passed to `start` +try { + const res = await input.start( + readFromUserInput({ prompt: 'OK?', default: 'y' }) + ) + output.standard(`User said ${res}`) +} catch (err) { + output.error(`User cancelled: ${err}`) +} + +// Manually calling `start` and `end` +try { + input.start() + const res = await readFromUserInput({ prompt: 'OK?', default: 'y' }) + output.standard(`User said ${res}`) +} catch (err) { + output.error(`User cancelled: ${err}`) +} finally { + input.end() +} +``` + +**consumer.js** +```js +const { read } = require('read') + +process.on('input', (level) => { + if (level === 'start') { + // Hide UI to make room for user input being read + } else if (level === 'end') { + // Restore UI now that reading is ended + } +}) +``` + +### Using `read` to call `read()` + +**producer.js** +```js +const { output, input } = require('proc-log') + +try { + const res = await input.read({ prompt: 'OK?', default: 'y' }) + output.standard(`User said ${res}`) +} catch (err) { + output.error(`User cancelled: ${err}`) +} +``` + +**consumer.js** +```js +const { read } = require('read') + +process.on('input', (level, ...args) => { + if (level === 'read') { + const [res, rej, opts] = args + read(opts).then(res).catch(rej) + } +}) +``` \ No newline at end of file diff --git a/lib/index.js b/lib/index.js index 2a049e6..47aef69 100644 --- a/lib/index.js +++ b/lib/index.js @@ -5,6 +5,11 @@ module.exports = { 'error', 'buffer', ], + KEYS: { + standard: 'standard', + error: 'error', + buffer: 'buffer', + }, standard: function (...args) { return process.emit('output', 'standard', ...args) }, @@ -28,6 +33,18 @@ module.exports = { 'pause', 'resume', ], + KEYS: { + notice: 'notice', + error: 'error', + warn: 'warn', + info: 'info', + verbose: 'verbose', + http: 'http', + silly: 'silly', + timing: 'timing', + pause: 'pause', + resume: 'resume', + }, error: function (...args) { return process.emit('log', 'error', ...args) }, @@ -59,4 +76,71 @@ module.exports = { return process.emit('log', 'resume', ...args) }, }, + time: { + LEVELS: [ + 'start', + 'end', + ], + KEYS: { + start: 'start', + end: 'end', + }, + start: function (name, fn) { + process.emit('time', 'start', name) + function end () { + return process.emit('time', 'end', name) + } + if (typeof fn === 'function') { + const res = fn() + if (res && res.finally) { + return res.finally(end) + } + end() + return res + } + return end + }, + end: function (name) { + return process.emit('time', 'end', name) + }, + }, + input: { + LEVELS: [ + 'start', + 'end', + 'read', + ], + KEYS: { + start: 'start', + end: 'end', + read: 'read', + }, + start: function (fn) { + process.emit('input', 'start') + function end () { + return process.emit('input', 'end') + } + if (typeof fn === 'function') { + const res = fn() + if (res && res.finally) { + return res.finally(end) + } + end() + return res + } + return end + }, + end: function () { + return process.emit('input', 'end') + }, + read: function (...args) { + let resolve, reject + const promise = new Promise((_resolve, _reject) => { + resolve = _resolve + reject = _reject + }) + process.emit('input', 'read', resolve, reject, ...args) + return promise + }, + }, } diff --git a/tap-snapshots/test/index.js.test.cjs b/tap-snapshots/test/index.js.test.cjs index 563d0a0..a0f06a4 100644 --- a/tap-snapshots/test/index.js.test.cjs +++ b/tap-snapshots/test/index.js.test.cjs @@ -5,6 +5,37 @@ * Make sure to inspect the output below. Do not ignore changes! */ 'use strict' +exports[`test/index.js TAP input > input keys 1`] = ` +Object { + "end": "end", + "read": "read", + "start": "start", +} +` + +exports[`test/index.js TAP input > input levels 1`] = ` +Array [ + "start", + "end", + "read", +] +` + +exports[`test/index.js TAP log > log keys 1`] = ` +Object { + "error": "error", + "http": "http", + "info": "info", + "notice": "notice", + "pause": "pause", + "resume": "resume", + "silly": "silly", + "timing": "timing", + "verbose": "verbose", + "warn": "warn", +} +` + exports[`test/index.js TAP log > log levels 1`] = ` Array [ "notice", @@ -20,6 +51,14 @@ Array [ ] ` +exports[`test/index.js TAP output > output keys 1`] = ` +Object { + "buffer": "buffer", + "error": "error", + "standard": "standard", +} +` + exports[`test/index.js TAP output > output levels 1`] = ` Array [ "standard", @@ -27,3 +66,17 @@ Array [ "buffer", ] ` + +exports[`test/index.js TAP time > time keys 1`] = ` +Object { + "end": "end", + "start": "start", +} +` + +exports[`test/index.js TAP time > time levels 1`] = ` +Array [ + "start", + "end", +] +` diff --git a/test/index.js b/test/index.js index 7aa41d2..a5c5d0e 100644 --- a/test/index.js +++ b/test/index.js @@ -1,34 +1,65 @@ const t = require('tap') const procLog = require('../') -// This makes sure we are testing the two known exported methods. -t.plan(2) + +// This makes sure we are testing all known exported methods. +t.plan(4) + for (const method in procLog) { t.test(method, t => { const log = procLog[method] - const { LEVELS } = log + const { LEVELS, KEYS } = log + t.matchSnapshot(LEVELS, `${method} levels`) + t.matchSnapshot(KEYS, `${method} keys`) + + t.strictSame(Object.keys(KEYS), LEVELS, 'all keys are in levels') + t.strictSame(Object.values(KEYS), LEVELS, 'all vales are in levels') + t.test(`all ${method}.LEVELS have a function in ${method}`, t => { for (const level of LEVELS) { t.test(level, t => { t.match(log[level], Function) + process.once(method, (actual, ...args) => { t.equal(actual, level, `emitted ${method} with expected level`) - t.same(args, [1, 'two', [3], { 4: 4 }], 'got expected args') + + switch (`${method}.${level}`) { + case 'time.start': + case 'time.end': + t.strictSame(args, [1], 'single arg') + break + case 'input.start': + case 'input.end': + t.strictSame(args, [], 'no args') + break + case 'input.read': + t.match(args.slice(0, 2), [Function, Function], 'input gets resolvers') + t.same(args.slice(2), [1, 'two', [3], { 4: 4 }], 'got expected args') + break + default: + t.same(args, [1, 'two', [3], { 4: 4 }], 'got expected args') + } + t.end() }) + log[level](1, 'two', [3], { 4: 4 }) }) } + t.end() }) + t.test(`all ${method} functions are in ${method}.LEVELS`, t => { t.plan(LEVELS.length) + for (const fn in log) { - if (fn !== 'LEVELS') { + if (fn !== 'LEVELS' && fn !== 'KEYS') { t.ok(LEVELS.includes(fn), `${method}.${fn} is in ${method}.LEVELS`) } } }) + t.end() }) } diff --git a/test/input.js b/test/input.js new file mode 100644 index 0000000..dec9415 --- /dev/null +++ b/test/input.js @@ -0,0 +1,79 @@ +const t = require('tap') +const { input } = require('../') + +t.test('read', t => { + t.test('will await promise', async t => { + process.once('input', (level, resolve, reject, ...args) => { + if (level === 'read') { + t.strictSame(args, [1, 2, 3]) + setTimeout(() => resolve('done'), 100) + } + }) + + await t.resolves(input.read(1, 2, 3), 'done') + }) + + t.test('can reject promise', async t => { + process.once('input', (level, resolve, reject, ...args) => { + if (level === 'read') { + t.strictSame(args, [1, 2, 3]) + setTimeout(() => reject(new Error('not ok')), 100) + } + }) + + await t.rejects(input.read(1, 2, 3), { message: 'not ok' }) + }) + + t.end() +}) + +t.test('start and end', t => { + t.test('returns function to stop', t => { + const called = {} + const handler = (actual) => { + called[actual] = true + if (called.start && called.end) { + t.end() + } + } + + process.on('input', handler) + t.teardown(() => process.off('input', handler)) + + input.start()() + }) + + t.test('sync callback', t => { + const res = input.start((...args) => { + t.strictSame(args, [], 'get no args') + return 1 + }) + t.equal(res, 1) + t.end() + }) + + t.test('async callback', async t => { + const res = await input.start((...args) => { + t.strictSame(args, [], 'get no args') + return Promise.resolve(1) + }) + t.equal(res, 1) + }) + + t.test('async callback that errors', async t => { + const called = {} + const handler = (level) => called[level] = true + + process.on('input', handler) + t.teardown(() => process.off('input', handler)) + + await t.rejects(input.start(() => { + return Promise.reject(new Error('not ok')) + }), { message: 'not ok' }) + + t.ok(called.start) + t.ok(called.end) + }) + + t.end() +}) diff --git a/test/time.js b/test/time.js new file mode 100644 index 0000000..fd49db0 --- /dev/null +++ b/test/time.js @@ -0,0 +1,50 @@ +const t = require('tap') +const { time } = require('../') + +t.test('time returns function to stop timer', t => { + const called = {} + const handler = (actual, name) => { + t.equal(name, 'timerName') + called[actual] = true + if (called.start && called.end) { + t.end() + } + } + + process.on('time', handler) + t.teardown(() => process.off('time', handler)) + + time.start('timerName')() +}) + +t.test('time can run a sync callback', t => { + const res = time.start('timerName', (...args) => { + t.strictSame(args, [], 'get no args') + return 1 + }) + t.equal(res, 1) + t.end() +}) + +t.test('time can run an async callback', async t => { + const res = await time.start('timerName', (...args) => { + t.strictSame(args, [], 'get no args') + return Promise.resolve(1) + }) + t.equal(res, 1) +}) + +t.test('time can run an async callback that errors', async t => { + const called = {} + const handler = (level) => called[level] = true + + process.on('time', handler) + t.teardown(() => process.off('time', handler)) + + await t.rejects(time.start('timerName', () => { + return Promise.reject(new Error('not ok')) + }), { message: 'not ok' }) + + t.ok(called.start) + t.ok(called.end) +})