1
0
Fork 0

fix(docs): describe exports and mark with release status

This commit is contained in:
ssube 2020-03-31 08:49:18 -05:00
parent 6d7e72e1a8
commit e4958ee6f0
Signed by: ssube
GPG Key ID: 3EED7B957D362AF1
46 changed files with 257 additions and 30 deletions

View File

@ -4,6 +4,8 @@
## ArrayMapper.map() method ## ArrayMapper.map() method
Transform the input list into a map, extracting elements using the mapper's options.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -30,5 +30,5 @@ export declare class ArrayMapper
| Method | Modifiers | Description | | Method | Modifiers | Description |
| --- | --- | --- | | --- | --- | --- |
| [map(input)](./js-utils.arraymapper.map.md) | | | | [map(input)](./js-utils.arraymapper.map.md) | | Transform the input list into a map, extracting elements using the mapper's options. |

View File

@ -4,6 +4,8 @@
## AsyncTracker.dump() method ## AsyncTracker.dump() method
Print a listing of all tracked resources. When debug mode is enabled (DEBUG=TRUE), include stack traces.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## AsyncTracker.getStack() method ## AsyncTracker.getStack() method
Get a filtered version of the current call stack. This creates a new error to generate the stack trace and will be quite slow.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -33,7 +33,7 @@ export declare class AsyncTracker
| --- | --- | --- | | --- | --- | --- |
| [clear()](./js-utils.asynctracker.clear.md) | | | | [clear()](./js-utils.asynctracker.clear.md) | | |
| [disable()](./js-utils.asynctracker.disable.md) | | | | [disable()](./js-utils.asynctracker.disable.md) | | |
| [dump()](./js-utils.asynctracker.dump.md) | | | | [dump()](./js-utils.asynctracker.dump.md) | | Print a listing of all tracked resources. When debug mode is enabled (DEBUG=TRUE), include stack traces. |
| [enable()](./js-utils.asynctracker.enable.md) | | | | [enable()](./js-utils.asynctracker.enable.md) | | |
| [getStack()](./js-utils.asynctracker.getstack.md) | | | | [getStack()](./js-utils.asynctracker.getstack.md) | | Get a filtered version of the current call stack. This creates a new error to generate the stack trace and will be quite slow. |

View File

@ -4,6 +4,8 @@
## Checklist.data property ## Checklist.data property
TODO: switch to Set
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## Checklist class ## Checklist class
Check whether items are included or not (blacklist or whitelist, depending on `mode`<!-- -->).
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript
@ -20,7 +22,7 @@ export declare class Checklist<T> implements ChecklistOptions<T>
| Property | Modifiers | Type | Description | | Property | Modifiers | Type | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| [data](./js-utils.checklist.data.md) | | <code>Array&lt;T&gt;</code> | | | [data](./js-utils.checklist.data.md) | | <code>Array&lt;T&gt;</code> | TODO: switch to Set |
| [mode](./js-utils.checklist.mode.md) | | <code>ChecklistMode</code> | | | [mode](./js-utils.checklist.mode.md) | | <code>ChecklistMode</code> | |
## Methods ## Methods

View File

@ -4,6 +4,8 @@
## ChildProcessError class ## ChildProcessError class
Error indicating that a child process exited with an error status.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## concat() function ## concat() function
Concatenate a list of buffers.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## constructorName() function ## constructorName() function
Get the constructor name from an instance.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## defaultWhen() function ## defaultWhen() function
Return the first element when `condition` is true and the second element when `condition` is false.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## encode() function ## encode() function
Concatenate then encode a list of buffers.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## getConstructor() function ## getConstructor() function
Get the constructor from an instance.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## getMethods() function ## getMethods() function
Get the methods from an instance and its prototypes.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## getTestLogger() function ## getTestLogger() function
Get a test logger. Returns a null logger unless `verbose` is true or run under debug mode.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## InvalidArgumentError class ## InvalidArgumentError class
Error indicating that an invalid argument was passed to a function call.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,10 @@
## isDebug() function ## isDebug() function
Test if DEBUG mode is set.
TODO: check variable value as well
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -10,13 +10,13 @@
| --- | --- | | --- | --- |
| [ArrayMapper](./js-utils.arraymapper.md) | Map an array of items into a map of arrays using the specified keys, able to <code>skip</code> initial items and gather remaining items into a <code>rest</code> key. | | [ArrayMapper](./js-utils.arraymapper.md) | Map an array of items into a map of arrays using the specified keys, able to <code>skip</code> initial items and gather remaining items into a <code>rest</code> key. |
| [AsyncTracker](./js-utils.asynctracker.md) | Async resource tracker using node's internal hooks.<!-- -->This probably won't work in a browser. It does not hold references to the resource, to avoid leaks. Adapted from https://gist.github.com/boneskull/7fe75b63d613fa940db7ec990a5f5843\#file-async-dump-js | | [AsyncTracker](./js-utils.asynctracker.md) | Async resource tracker using node's internal hooks.<!-- -->This probably won't work in a browser. It does not hold references to the resource, to avoid leaks. Adapted from https://gist.github.com/boneskull/7fe75b63d613fa940db7ec990a5f5843\#file-async-dump-js |
| [Checklist](./js-utils.checklist.md) | | | [Checklist](./js-utils.checklist.md) | Check whether items are included or not (blacklist or whitelist, depending on <code>mode</code>). |
| [ChildProcessError](./js-utils.childprocesserror.md) | | | [ChildProcessError](./js-utils.childprocesserror.md) | Error indicating that a child process exited with an error status. |
| [InvalidArgumentError](./js-utils.invalidargumenterror.md) | | | [InvalidArgumentError](./js-utils.invalidargumenterror.md) | Error indicating that an invalid argument was passed to a function call. |
| [MissingKeyError](./js-utils.missingkeyerror.md) | | | [MissingKeyError](./js-utils.missingkeyerror.md) | Error indicating that a required key did not exist in a map-like. |
| [NotFoundError](./js-utils.notfounderror.md) | | | [NotFoundError](./js-utils.notfounderror.md) | Error indicating that some value was not found. |
| [NotImplementedError](./js-utils.notimplementederror.md) | | | [NotImplementedError](./js-utils.notimplementederror.md) | Error indicating that a function has not been implemented yet. |
| [TimeoutError](./js-utils.timeouterror.md) | | | [TimeoutError](./js-utils.timeouterror.md) | Error indicating that a promise timed out. |
## Enumerations ## Enumerations
@ -28,43 +28,43 @@
| Function | Description | | Function | Description |
| --- | --- | | --- | --- |
| [concat(chunks)](./js-utils.concat.md) | | | [concat(chunks)](./js-utils.concat.md) | Concatenate a list of buffers. |
| [constructorName(val)](./js-utils.constructorname.md) | | | [constructorName(val)](./js-utils.constructorname.md) | Get the constructor name from an instance. |
| [countOf(val)](./js-utils.countof.md) | Calculate the "length" of an array or value.<!-- -->Arrays return their length, single values return 1, and nil values return 0. This counts the number of elements that setOrPush would add. | | [countOf(val)](./js-utils.countof.md) | Calculate the "length" of an array or value.<!-- -->Arrays return their length, single values return 1, and nil values return 0. This counts the number of elements that setOrPush would add. |
| [defaultWhen(condition, items)](./js-utils.defaultwhen.md) | | | [defaultWhen(condition, items)](./js-utils.defaultwhen.md) | Return the first element when <code>condition</code> is true and the second element when <code>condition</code> is false. |
| [defer(ms, val)](./js-utils.defer.md) | Resolve after a set amount of time. | | [defer(ms, val)](./js-utils.defer.md) | Resolve after a set amount of time. |
| [doesExist(val)](./js-utils.doesexist.md) | Check if a variable is not nil. | | [doesExist(val)](./js-utils.doesexist.md) | Check if a variable is not nil. |
| [encode(chunks, encoding)](./js-utils.encode.md) | | | [encode(chunks, encoding)](./js-utils.encode.md) | Concatenate then encode a list of buffers. |
| [entriesOf(map)](./js-utils.entriesof.md) | Get entries of a map-like. | | [entriesOf(map)](./js-utils.entriesof.md) | Get entries of a map-like. |
| [filterNil(list)](./js-utils.filternil.md) | Remove any null or undefined items from the list. | | [filterNil(list)](./js-utils.filternil.md) | Remove any null or undefined items from the list. |
| [getConstructor(val)](./js-utils.getconstructor.md) | | | [getConstructor(val)](./js-utils.getconstructor.md) | Get the constructor from an instance. |
| [getHead(map, key)](./js-utils.gethead.md) | Get the first element from the specified key within a map of lists. | | [getHead(map, key)](./js-utils.gethead.md) | Get the first element from the specified key within a map of lists. |
| [getHeadOrDefault(map, key, defaultValue)](./js-utils.getheadordefault.md) | Get the first element from the specified key, within a map of lists, or a default value when the key does not exist or is nil. | | [getHeadOrDefault(map, key, defaultValue)](./js-utils.getheadordefault.md) | Get the first element from the specified key, within a map of lists, or a default value when the key does not exist or is nil. |
| [getMethods(value)](./js-utils.getmethods.md) | | | [getMethods(value)](./js-utils.getmethods.md) | Get the methods from an instance and its prototypes. |
| [getOrDefault(map, key, defaultValue)](./js-utils.getordefault.md) | Get a map key or default value when the key does not exist or is nil. | | [getOrDefault(map, key, defaultValue)](./js-utils.getordefault.md) | Get a map key or default value when the key does not exist or is nil. |
| [getTestLogger(verbose)](./js-utils.gettestlogger.md) | | | [getTestLogger(verbose)](./js-utils.gettestlogger.md) | Get a test logger. Returns a null logger unless <code>verbose</code> is true or run under debug mode. |
| [isDebug()](./js-utils.isdebug.md) | | | [isDebug()](./js-utils.isdebug.md) | Test if DEBUG mode is set.<!-- -->TODO: check variable value as well |
| [isNil(val)](./js-utils.isnil.md) | Check if a value is nil. | | [isNil(val)](./js-utils.isnil.md) | Check if a value is nil. |
| [leftPad(val, min, fill)](./js-utils.leftpad.md) | | | [leftPad(val, min, fill)](./js-utils.leftpad.md) | |
| [makeDict(map)](./js-utils.makedict.md) | Turns a map or dict into a dict | | [makeDict(map)](./js-utils.makedict.md) | Turns a map or dict into a dict |
| [makeMap(val)](./js-utils.makemap.md) | Clone a map or map-like object into a new map. | | [makeMap(val)](./js-utils.makemap.md) | Clone a map or map-like object into a new map. |
| [mergeList(parts)](./js-utils.mergelist.md) | Merge arguments, which may or may not be arrays, into one return that is definitely an array. | | [mergeList(parts)](./js-utils.mergelist.md) | Merge arguments, which may or may not be arrays, into one return that is definitely an array. |
| [mergeMap(target, source)](./js-utils.mergemap.md) | Merge the <code>source</code> map into the <code>target</code> map, replacing keys that already exist. | | [mergeMap(target, source)](./js-utils.mergemap.md) | Merge the <code>source</code> map into the <code>target</code> map, replacing keys that already exist. |
| [mustCoalesce(values)](./js-utils.mustcoalesce.md) | Return the first value that is not nil.<!-- -->TODO: rename to mustDefault | | [mustCoalesce(values)](./js-utils.mustcoalesce.md) | Return the first value that is not nil.<!-- -->@<!-- -->todo: rename to mustDefault |
| [mustExist(val)](./js-utils.mustexist.md) | Assert that a variable is not nil and return the value. | | [mustExist(val)](./js-utils.mustexist.md) | Assert that a variable is not nil and return the value. |
| [mustFind(list, predicate)](./js-utils.mustfind.md) | Find a value matching the given predicate or throw. | | [mustFind(list, predicate)](./js-utils.mustfind.md) | Find a value matching the given predicate or throw. |
| [mustGet(map, key)](./js-utils.mustget.md) | Get an element from a Map and guard against nil values. | | [mustGet(map, key)](./js-utils.mustget.md) | Get an element from a Map and guard against nil values. |
| [normalizeMap(map)](./js-utils.normalizemap.md) | | | [normalizeMap(map)](./js-utils.normalizemap.md) | <b><i>(BETA)</i></b> Normalize a map-like of values into a dict of lists of strings. |
| [pairsToMap(pairs)](./js-utils.pairstomap.md) | Turns a list of name-value pairs into a map. | | [pairsToMap(pairs)](./js-utils.pairstomap.md) | Turns a list of name-value pairs into a map. |
| [pushMergeMap(args)](./js-utils.pushmergemap.md) | Merge the provided maps into a new map, merging keys that already exist by pushing new items. | | [pushMergeMap(args)](./js-utils.pushmergemap.md) | Merge the provided maps into a new map, merging keys that already exist by pushing new items. |
| [removePid(path)](./js-utils.removepid.md) | | | [removePid(path)](./js-utils.removepid.md) | Remove the file at the given <code>path</code>. |
| [setOrPush(map, key, val)](./js-utils.setorpush.md) | Set a map key to a new array or push to the existing value. | | [setOrPush(map, key, val)](./js-utils.setorpush.md) | Set a map key to a new array or push to the existing value. |
| [signal(signals)](./js-utils.signal.md) | | | [signal(signals)](./js-utils.signal.md) | |
| [spyLogger(spies)](./js-utils.spylogger.md) | | | [spyLogger(spies)](./js-utils.spylogger.md) | Create a spy logger using the provided methods, which returns itself as a child. |
| [timeout(ms, oper)](./js-utils.timeout.md) | Reject after a set amount of time if the original promise has not yet resolved. | | [timeout(ms, oper)](./js-utils.timeout.md) | Reject after a set amount of time if the original promise has not yet resolved. |
| [trim(val, max, tail)](./js-utils.trim.md) | | | [trim(val, max, tail)](./js-utils.trim.md) | |
| [waitForChild(child)](./js-utils.waitforchild.md) | | | [waitForChild(child)](./js-utils.waitforchild.md) | Wait for a child process to exit, collecting output, errors, and exit status. |
| [writePid(path)](./js-utils.writepid.md) | | | [writePid(path)](./js-utils.writepid.md) | Write the current process ID to a file at the given <code>path</code>. |
| [writeValue(stream, value)](./js-utils.writevalue.md) | | | [writeValue(stream, value)](./js-utils.writevalue.md) | |
## Interfaces ## Interfaces

View File

@ -4,10 +4,12 @@
## MissingKeyError class ## MissingKeyError class
Error indicating that a required key did not exist in a map-like.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript
export declare class MissingKeyError extends BaseError export declare class MissingKeyError extends NotFoundError
``` ```
## Constructors ## Constructors

View File

@ -6,7 +6,7 @@
Return the first value that is not nil. Return the first value that is not nil.
TODO: rename to mustDefault @<!-- -->todo: rename to mustDefault
<b>Signature:</b> <b>Signature:</b>

View File

@ -4,6 +4,11 @@
## normalizeMap() function ## normalizeMap() function
> This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.
>
Normalize a map-like of values into a dict of lists of strings.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## NotFoundError class ## NotFoundError class
Error indicating that some value was not found.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## NotImplementedError class ## NotImplementedError class
Error indicating that a function has not been implemented yet.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## removePid() function ## removePid() function
Remove the file at the given `path`<!-- -->.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## spyLogger() function ## spyLogger() function
Create a spy logger using the provided methods, which returns itself as a child.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## TimeoutError class ## TimeoutError class
Error indicating that a promise timed out.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## waitForChild() function ## waitForChild() function
Wait for a child process to exit, collecting output, errors, and exit status.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -4,6 +4,8 @@
## writePid() function ## writePid() function
Write the current process ID to a file at the given `path`<!-- -->.
<b>Signature:</b> <b>Signature:</b>
```typescript ```typescript

View File

@ -18,6 +18,8 @@ export interface ArrayMapperOptions {
/** /**
* Map an array of items into a map of arrays using the specified keys, able to `skip` initial items and gather * Map an array of items into a map of arrays using the specified keys, able to `skip` initial items and gather
* remaining items into a `rest` key. * remaining items into a `rest` key.
*
* @public
*/ */
export class ArrayMapper { export class ArrayMapper {
public readonly rest: string; public readonly rest: string;
@ -30,6 +32,11 @@ export class ArrayMapper {
this.take = Array.from(options.take); this.take = Array.from(options.take);
} }
/**
* Transform the input list into a map, extracting elements using the mapper's options.
*
* @public
*/
public map(input: Array<string>): Map<string, Array<string>> { public map(input: Array<string>): Map<string, Array<string>> {
const result = new Map(); const result = new Map();
input.forEach((it, idx) => { input.forEach((it, idx) => {

View File

@ -3,6 +3,7 @@ import { PredicateC0 } from './utils';
/** /**
* Resolve after a set amount of time. * Resolve after a set amount of time.
* @public
*/ */
export function defer<T = undefined>(ms: number, val?: T): Promise<T> { export function defer<T = undefined>(ms: number, val?: T): Promise<T> {
return new Promise((res, rej) => { return new Promise((res, rej) => {
@ -14,6 +15,7 @@ export function defer<T = undefined>(ms: number, val?: T): Promise<T> {
/** /**
* Reject after a set amount of time if the original promise has not yet resolved. * Reject after a set amount of time if the original promise has not yet resolved.
* @public
*/ */
export function timeout<T>(ms: number, oper: Promise<T>): Promise<T> { export function timeout<T>(ms: number, oper: Promise<T>): Promise<T> {
const limit = new Promise<T>((res, rej) => { const limit = new Promise<T>((res, rej) => {
@ -25,6 +27,11 @@ export function timeout<T>(ms: number, oper: Promise<T>): Promise<T> {
return Promise.race([limit, oper]); return Promise.race([limit, oper]);
} }
/**
* Reject after a set number of attempts if the given predicate does not return true.
* @public
* @throws TimeoutError
*/
export async function waitFor(cb: PredicateC0, step: number, count: number): Promise<void> { export async function waitFor(cb: PredicateC0, step: number, count: number): Promise<void> {
let accum = 0; let accum = 0;
while (accum < count) { while (accum < count) {

View File

@ -16,6 +16,8 @@ export type StackFilter = (stack: string) => string;
* *
* This probably won't work in a browser. It does not hold references to the resource, to avoid leaks. * This probably won't work in a browser. It does not hold references to the resource, to avoid leaks.
* Adapted from https://gist.github.com/boneskull/7fe75b63d613fa940db7ec990a5f5843#file-async-dump-js * Adapted from https://gist.github.com/boneskull/7fe75b63d613fa940db7ec990a5f5843#file-async-dump-js
*
* @public
*/ */
export class AsyncTracker { export class AsyncTracker {
public filter: Optional<StackFilter>; public filter: Optional<StackFilter>;
@ -43,6 +45,10 @@ export class AsyncTracker {
}); });
} }
/**
* Get a filtered version of the current call stack. This creates a new error to generate the
* stack trace and will be quite slow.
*/
public getStack(): string { public getStack(): string {
const err = new Error(); const err = new Error();
if (isNil(err.stack)) { if (isNil(err.stack)) {
@ -64,6 +70,10 @@ export class AsyncTracker {
this.hook.disable(); this.hook.disable();
} }
/**
* Print a listing of all tracked resources. When debug mode is enabled (DEBUG=TRUE), include
* stack traces.
*/
/* eslint-disable no-console, no-invalid-this */ /* eslint-disable no-console, no-invalid-this */
public dump() { public dump() {
console.error(`tracking ${this.resources.size} async resources`); console.error(`tracking ${this.resources.size} async resources`);

View File

@ -1,8 +1,18 @@
/**
* Concatenate a list of buffers.
*
* @public
*/
export function concat(chunks: Array<Buffer>): Buffer { export function concat(chunks: Array<Buffer>): Buffer {
const sum = chunks.map((it) => it.length).reduce((p, c) => p + c, 0); const sum = chunks.map((it) => it.length).reduce((p, c) => p + c, 0);
return Buffer.concat(chunks, sum); return Buffer.concat(chunks, sum);
} }
/**
* Concatenate then encode a list of buffers.
*
* @public
*/
export function encode(chunks: Array<Buffer>, encoding: string): string { export function encode(chunks: Array<Buffer>, encoding: string): string {
if (chunks.length === 0) { if (chunks.length === 0) {
return ''; return '';

View File

@ -8,7 +8,13 @@ export interface ChecklistOptions<T> {
mode: ChecklistMode; mode: ChecklistMode;
} }
/**
* Check whether items are included or not (blacklist or whitelist, depending on `mode`).
*/
export class Checklist<T> implements ChecklistOptions<T> { export class Checklist<T> implements ChecklistOptions<T> {
/**
* TODO: switch to Set
*/
public readonly data: Array<T>; public readonly data: Array<T>;
public readonly mode: ChecklistMode; public readonly mode: ChecklistMode;

View File

@ -37,6 +37,11 @@ const CHILD_EVENT = 'child process emitted error event';
const CHILD_STATUS = 'child process exited with error status'; const CHILD_STATUS = 'child process exited with error status';
const CHILD_OUTPUT = 'child process emitted error output'; const CHILD_OUTPUT = 'child process emitted error output';
/**
* Wait for a child process to exit, collecting output, errors, and exit status.
*
* @public
*/
export function waitForChild(child: ChildStreams): Promise<ChildResult> { export function waitForChild(child: ChildStreams): Promise<ChildResult> {
return new Promise((res, rej) => { return new Promise((res, rej) => {
const stderr: Array<Buffer> = []; const stderr: Array<Buffer> = [];

View File

@ -1,5 +1,10 @@
const ENV_DEBUG = 'DEBUG'; const ENV_DEBUG = 'DEBUG';
/**
* Test if DEBUG mode is set.
*
* TODO: check variable value as well
*/
export function isDebug() { export function isDebug() {
return Reflect.has(process.env, ENV_DEBUG); return Reflect.has(process.env, ENV_DEBUG);
} }

View File

@ -1,6 +1,9 @@
import { ConsoleLogger, Logger, NullLogger } from 'noicejs'; import { ConsoleLogger, Logger, NullLogger } from 'noicejs';
import { isDebug } from './Env'; import { isDebug } from './Env';
/**
* Get a test logger. Returns a null logger unless `verbose` is true or run under debug mode.
*/
export function getTestLogger(verbose = false): Logger { export function getTestLogger(verbose = false): Logger {
if (verbose || isDebug()) { if (verbose || isDebug()) {
return ConsoleLogger.global; return ConsoleLogger.global;
@ -9,6 +12,9 @@ export function getTestLogger(verbose = false): Logger {
} }
} }
/**
* Create a spy logger using the provided methods, which returns itself as a child.
*/
export function spyLogger(spies: Partial<Logger>): Logger { export function spyLogger(spies: Partial<Logger>): Logger {
const logger = { const logger = {
...spies, ...spies,

View File

@ -9,11 +9,15 @@ export interface Dict<TVal> {
/** /**
* A `Map` or dictionary object with string keys and `TVal` values. * A `Map` or dictionary object with string keys and `TVal` values.
*
* @public
*/ */
export type MapLike<TVal> = Map<string, TVal> | Dict<TVal>; export type MapLike<TVal> = Map<string, TVal> | Dict<TVal>;
/** /**
* Get an element from a Map and guard against nil values. * Get an element from a Map and guard against nil values.
*
* @public
*/ */
export function mustGet<TKey, TVal>(map: Map<TKey, TVal>, key: TKey): TVal { export function mustGet<TKey, TVal>(map: Map<TKey, TVal>, key: TKey): TVal {
const val = map.get(key); const val = map.get(key);
@ -22,6 +26,8 @@ export function mustGet<TKey, TVal>(map: Map<TKey, TVal>, key: TKey): TVal {
/** /**
* Get a map key or default value when the key does not exist or is nil. * Get a map key or default value when the key does not exist or is nil.
*
* @public
*/ */
export function getOrDefault<TKey, TVal>(map: Map<TKey, TVal>, key: TKey, defaultValue: TVal): TVal { export function getOrDefault<TKey, TVal>(map: Map<TKey, TVal>, key: TKey, defaultValue: TVal): TVal {
if (map.has(key)) { if (map.has(key)) {
@ -36,6 +42,8 @@ export function getOrDefault<TKey, TVal>(map: Map<TKey, TVal>, key: TKey, defaul
/** /**
* Get the first element from the specified key within a map of lists. * Get the first element from the specified key within a map of lists.
*
* @public
*/ */
export function getHead<TKey, TVal>(map: Map<TKey, Array<TVal>>, key: TKey): TVal { export function getHead<TKey, TVal>(map: Map<TKey, Array<TVal>>, key: TKey): TVal {
const value = map.get(key); const value = map.get(key);
@ -48,6 +56,8 @@ export function getHead<TKey, TVal>(map: Map<TKey, Array<TVal>>, key: TKey): TVa
/** /**
* Get the first element from the specified key, within a map of lists, or a default value when * Get the first element from the specified key, within a map of lists, or a default value when
* the key does not exist or is nil. * the key does not exist or is nil.
*
* @public
*/ */
export function getHeadOrDefault<TKey, TVal>(map: Map<TKey, Array<Optional<TVal>>>, key: TKey, defaultValue: TVal): TVal { export function getHeadOrDefault<TKey, TVal>(map: Map<TKey, Array<Optional<TVal>>>, key: TKey, defaultValue: TVal): TVal {
if (!map.has(key)) { if (!map.has(key)) {
@ -72,6 +82,8 @@ export function getHeadOrDefault<TKey, TVal>(map: Map<TKey, Array<Optional<TVal>
* @param map The destination map and source of existing values. * @param map The destination map and source of existing values.
* @param key The key to get and set. * @param key The key to get and set.
* @param val The value to add. * @param val The value to add.
*
* @public
*/ */
export function setOrPush<TKey, TVal>(map: Map<TKey, Array<TVal>>, key: TKey, val: TVal | Array<TVal>) { export function setOrPush<TKey, TVal>(map: Map<TKey, Array<TVal>>, key: TKey, val: TVal | Array<TVal>) {
const prev = map.get(key); const prev = map.get(key);
@ -88,6 +100,8 @@ export function setOrPush<TKey, TVal>(map: Map<TKey, Array<TVal>>, key: TKey, va
/** /**
* Merge the `source` map into the `target` map, replacing keys that already exist. * Merge the `source` map into the `target` map, replacing keys that already exist.
*
* @public
*/ */
export function mergeMap<TKey, TVal>(target: Map<TKey, TVal>, source: Map<TKey, TVal> | Array<[TKey, TVal]>) { export function mergeMap<TKey, TVal>(target: Map<TKey, TVal>, source: Map<TKey, TVal> | Array<[TKey, TVal]>) {
for (const [k, v] of source) { for (const [k, v] of source) {
@ -99,6 +113,8 @@ export function mergeMap<TKey, TVal>(target: Map<TKey, TVal>, source: Map<TKey,
/** /**
* Merge the provided maps into a new map, merging keys that already exist by pushing new items. * Merge the provided maps into a new map, merging keys that already exist by pushing new items.
*
* @public
*/ */
export function pushMergeMap<TKey, TVal>(...args: Array<Map<TKey, TVal | Array<TVal>>>): Map<TKey, Array<TVal>> { export function pushMergeMap<TKey, TVal>(...args: Array<Map<TKey, TVal | Array<TVal>>>): Map<TKey, Array<TVal>> {
const out = new Map(); const out = new Map();
@ -112,6 +128,8 @@ export function pushMergeMap<TKey, TVal>(...args: Array<Map<TKey, TVal | Array<T
/** /**
* Clone a map or map-like object into a new map. * Clone a map or map-like object into a new map.
*
* @public
*/ */
export function makeMap<TVal>(val: Optional<MapLike<TVal>>): Map<string, TVal> { export function makeMap<TVal>(val: Optional<MapLike<TVal>>): Map<string, TVal> {
// nil: empty map // nil: empty map
@ -130,6 +148,8 @@ export function makeMap<TVal>(val: Optional<MapLike<TVal>>): Map<string, TVal> {
/** /**
* Turns a map or dict into a dict * Turns a map or dict into a dict
*
* @public
*/ */
export function makeDict<TVal>(map: Optional<MapLike<TVal>>): Dict<TVal> { export function makeDict<TVal>(map: Optional<MapLike<TVal>>): Dict<TVal> {
if (isNil(map)) { if (isNil(map)) {
@ -154,6 +174,8 @@ export interface NameValuePair<TVal> {
/** /**
* Turns a list of name-value pairs into a map. * Turns a list of name-value pairs into a map.
*
* @public
*/ */
export function pairsToMap<TVal>(pairs: Array<NameValuePair<TVal>>): Map<string, TVal> { export function pairsToMap<TVal>(pairs: Array<NameValuePair<TVal>>): Map<string, TVal> {
const map = new Map(); const map = new Map();
@ -176,6 +198,11 @@ export function dictValuesToArrays<TVal>(map: MapLike<TVal>): Dict<Array<TVal>>
return data; return data;
} }
/**
* Normalize a map-like of values into a dict of lists of strings.
*
* @beta
*/
export function normalizeMap(map: MapLike<unknown>): Dict<Array<string>> { export function normalizeMap(map: MapLike<unknown>): Dict<Array<string>> {
const data: Dict<Array<string>> = {}; const data: Dict<Array<string>> = {};
for (const [key, value] of makeMap(map)) { for (const [key, value] of makeMap(map)) {
@ -193,6 +220,8 @@ export function normalizeMap(map: MapLike<unknown>): Dict<Array<string>> {
/** /**
* Get entries of a map-like. * Get entries of a map-like.
*
* @public
*/ */
export function entriesOf<TVal>(map: Optional<MapLike<TVal>>): Array<[string, TVal]> { export function entriesOf<TVal>(map: Optional<MapLike<TVal>>): Array<[string, TVal]> {
if (map instanceof Map) { if (map instanceof Map) {

View File

@ -5,6 +5,11 @@ import { doesExist, Optional } from './utils';
type OptionalErrno = Optional<NodeJS.ErrnoException>; type OptionalErrno = Optional<NodeJS.ErrnoException>;
/**
* Write the current process ID to a file at the given `path`.
*
* @public
*/
export async function writePid(path: string): Promise<void> { export async function writePid(path: string): Promise<void> {
return new Promise((res, rej) => { return new Promise((res, rej) => {
open(path, 'wx', (openErr: OptionalErrno, fd: number) => { open(path, 'wx', (openErr: OptionalErrno, fd: number) => {
@ -23,6 +28,9 @@ export async function writePid(path: string): Promise<void> {
}); });
} }
/**
* Remove the file at the given `path`.
*/
export async function removePid(path: string): Promise<void> { export async function removePid(path: string): Promise<void> {
return new Promise((res, rej) => { return new Promise((res, rej) => {
unlink(path, (err: OptionalErrno) => { unlink(path, (err: OptionalErrno) => {

View File

@ -2,10 +2,20 @@ import { isFunction } from 'lodash';
import { doesExist, isNil } from './utils'; import { doesExist, isNil } from './utils';
/**
* Get the constructor from an instance.
*
* @public
*/
export function getConstructor(val: object) { export function getConstructor(val: object) {
return val.constructor; return val.constructor;
} }
/**
* Get the methods from an instance and its prototypes.
*
* @public
*/
export function getMethods<TValue extends object>(value: TValue): Set<Function> { export function getMethods<TValue extends object>(value: TValue): Set<Function> {
const methods = new Set<Function>(); const methods = new Set<Function>();
@ -31,6 +41,11 @@ export function getMethods<TValue extends object>(value: TValue): Set<Function>
return methods; return methods;
} }
/**
* Get the constructor name from an instance.
*
* @public
*/
export function constructorName(val: object) { export function constructorName(val: object) {
return getConstructor(Reflect.getPrototypeOf(val)).name; return getConstructor(Reflect.getPrototypeOf(val)).name;
} }

View File

@ -1,5 +1,10 @@
import { BaseError } from 'noicejs'; import { BaseError } from 'noicejs';
/**
* Error indicating that a child process exited with an error status.
*
* @public
*/
export class ChildProcessError extends BaseError { export class ChildProcessError extends BaseError {
constructor(msg = 'child process exited with error status', ...nested: Array<Error>) { constructor(msg = 'child process exited with error status', ...nested: Array<Error>) {
super(msg, ...nested); super(msg, ...nested);

View File

@ -1,5 +1,10 @@
import { BaseError } from 'noicejs'; import { BaseError } from 'noicejs';
/**
* Error indicating that an invalid argument was passed to a function call.
*
* @public
*/
export class InvalidArgumentError extends BaseError { export class InvalidArgumentError extends BaseError {
constructor(msg = 'invalid argument passed', ...nested: Array<Error>) { constructor(msg = 'invalid argument passed', ...nested: Array<Error>) {
super(msg, ...nested); super(msg, ...nested);

View File

@ -1,6 +1,11 @@
import { BaseError } from 'noicejs'; import { NotFoundError } from './NotFoundError';
export class MissingKeyError extends BaseError { /**
* Error indicating that a required key did not exist in a map-like.
*
* @public
*/
export class MissingKeyError extends NotFoundError {
constructor(msg = 'missing key', ...nested: Array<Error>) { constructor(msg = 'missing key', ...nested: Array<Error>) {
super(msg, ...nested); super(msg, ...nested);
} }

View File

@ -1,5 +1,10 @@
import { BaseError } from 'noicejs'; import { BaseError } from 'noicejs';
/**
* Error indicating that some value was not found.
*
* @public
*/
export class NotFoundError extends BaseError { export class NotFoundError extends BaseError {
constructor(msg = 'value not found', ...nested: Array<Error>) { constructor(msg = 'value not found', ...nested: Array<Error>) {
super(msg, ...nested); super(msg, ...nested);

View File

@ -1,5 +1,10 @@
import { BaseError } from 'noicejs'; import { BaseError } from 'noicejs';
/**
* Error indicating that a function has not been implemented yet.
*
* @public
*/
export class NotImplementedError extends BaseError { export class NotImplementedError extends BaseError {
constructor(msg = 'method not implemented', ...nested: Array<Error>) { constructor(msg = 'method not implemented', ...nested: Array<Error>) {
super(msg, ...nested); super(msg, ...nested);

View File

@ -1,5 +1,10 @@
import { BaseError } from 'noicejs'; import { BaseError } from 'noicejs';
/**
* Error indicating that a promise timed out.
*
* @public
*/
export class TimeoutError extends BaseError { export class TimeoutError extends BaseError {
constructor(msg = 'operation timed out', ...nested: Array<Error>) { constructor(msg = 'operation timed out', ...nested: Array<Error>) {
super(msg, ...nested); super(msg, ...nested);

View File

@ -2,6 +2,8 @@ import { NotFoundError } from '../error/NotFoundError';
/** /**
* Unset value. * Unset value.
*
* @public
*/ */
/* eslint-disable-next-line @typescript-eslint/ban-types */ /* eslint-disable-next-line @typescript-eslint/ban-types */
export type Nil = null | undefined; export type Nil = null | undefined;
@ -13,41 +15,57 @@ export type SortOrder = SortAfter | SortBefore | SortEqual;
/** /**
* Value that may be nil. * Value that may be nil.
*
* @public
*/ */
export type Optional<T> = T | Nil; export type Optional<T> = T | Nil;
/** /**
* Comparison predicate for arity 0 - assert? * Comparison predicate for arity 0 - assert?
*
* @beta
*/ */
export type PredicateC0 = () => boolean; export type PredicateC0 = () => boolean;
/** /**
* Comparison predicate for arity 1 - filter. * Comparison predicate for arity 1 - filter.
*
* @beta
*/ */
export type PredicateC1<TVal> = (val: TVal, idx: number, list: Array<TVal>) => boolean; export type PredicateC1<TVal> = (val: TVal, idx: number, list: Array<TVal>) => boolean;
/** /**
* Comparison predicate for arity 2 - sort. * Comparison predicate for arity 2 - sort.
*
* @beta
*/ */
export type PredicateC2<TVal> = (pval: TVal, nval: TVal, idx: number, list: Array<TVal>) => SortOrder; export type PredicateC2<TVal> = (pval: TVal, nval: TVal, idx: number, list: Array<TVal>) => SortOrder;
/** /**
* Transform predicate for arity 0 - constructor. * Transform predicate for arity 0 - constructor.
*
* @beta
*/ */
export type PredicateR0<TVal> = () => TVal; export type PredicateR0<TVal> = () => TVal;
/** /**
* Transform predicate for arity 1 - map. * Transform predicate for arity 1 - map.
*
* @beta
*/ */
export type PredicateR1<TVal> = (val: TVal, idx: number, list: Array<TVal>) => TVal; export type PredicateR1<TVal> = (val: TVal, idx: number, list: Array<TVal>) => TVal;
/** /**
* Transform predicate for arity 2 - reduce. * Transform predicate for arity 2 - reduce.
*
* @beta
*/ */
export type PredicateR2<TVal> = (pval: TVal, nval: TVal, idx: number, list: Array<TVal>) => TVal; export type PredicateR2<TVal> = (pval: TVal, nval: TVal, idx: number, list: Array<TVal>) => TVal;
/** /**
* Check if a value is nil. * Check if a value is nil.
*
* @public
*/ */
/* eslint-disable-next-line @typescript-eslint/ban-types */ /* eslint-disable-next-line @typescript-eslint/ban-types */
export function isNil<T>(val: Optional<T>): val is Nil { export function isNil<T>(val: Optional<T>): val is Nil {
@ -60,6 +78,8 @@ export function isNil<T>(val: Optional<T>): val is Nil {
* *
* Arrays return their length, single values return 1, and nil values return 0. * Arrays return their length, single values return 1, and nil values return 0.
* This counts the number of elements that setOrPush would add. * This counts the number of elements that setOrPush would add.
*
* @public
*/ */
export function countOf(val: unknown): number { export function countOf(val: unknown): number {
if (Array.isArray(val)) { if (Array.isArray(val)) {
@ -73,6 +93,11 @@ export function countOf(val: unknown): number {
return 0; return 0;
} }
/**
* Return the first element when `condition` is true and the second element when `condition` is false.
*
* @public
*/
export function defaultWhen<TVal>(condition: boolean, ...items: Array<TVal>): TVal { export function defaultWhen<TVal>(condition: boolean, ...items: Array<TVal>): TVal {
if (condition) { if (condition) {
return items[0]; return items[0];
@ -83,6 +108,8 @@ export function defaultWhen<TVal>(condition: boolean, ...items: Array<TVal>): TV
/** /**
* Remove any null or undefined items from the list. * Remove any null or undefined items from the list.
*
* @public
*/ */
export function filterNil<TItem>(list: ArrayLike<Optional<TItem>>): Array<TItem> { export function filterNil<TItem>(list: ArrayLike<Optional<TItem>>): Array<TItem> {
return Array.from(list).filter(doesExist); return Array.from(list).filter(doesExist);
@ -90,6 +117,8 @@ export function filterNil<TItem>(list: ArrayLike<Optional<TItem>>): Array<TItem>
/** /**
* Merge arguments, which may or may not be arrays, into one return that is definitely an array. * Merge arguments, which may or may not be arrays, into one return that is definitely an array.
*
* @public
*/ */
export function mergeList<TItem>(...parts: Array<TItem | Array<TItem>>): Array<TItem> { export function mergeList<TItem>(...parts: Array<TItem | Array<TItem>>): Array<TItem> {
const out = []; const out = [];
@ -107,6 +136,8 @@ export function mergeList<TItem>(...parts: Array<TItem | Array<TItem>>): Array<T
/** /**
* Find a value matching the given predicate or throw. * Find a value matching the given predicate or throw.
*
* @public
*/ */
export function mustFind<TVal>(list: Array<Optional<TVal>>, predicate: PredicateC1<TVal>): TVal { export function mustFind<TVal>(list: Array<Optional<TVal>>, predicate: PredicateC1<TVal>): TVal {
const val = filterNil(list).find(predicate); const val = filterNil(list).find(predicate);
@ -115,6 +146,8 @@ export function mustFind<TVal>(list: Array<Optional<TVal>>, predicate: Predicate
/** /**
* Check if a variable is not nil. * Check if a variable is not nil.
*
* @public
*/ */
export function doesExist<T>(val: Optional<T>): val is T { export function doesExist<T>(val: Optional<T>): val is T {
return !isNil(val); return !isNil(val);
@ -125,6 +158,8 @@ export function doesExist<T>(val: Optional<T>): val is T {
* *
* @throws NotFoundError * @throws NotFoundError
* @returns val * @returns val
*
* @public
*/ */
export function mustExist<T>(val: Optional<T>): T { export function mustExist<T>(val: Optional<T>): T {
if (isNil(val)) { if (isNil(val)) {
@ -137,7 +172,8 @@ export function mustExist<T>(val: Optional<T>): T {
/** /**
* Return the first value that is not nil. * Return the first value that is not nil.
* *
* TODO: rename to mustDefault * @public
* @todo: rename to mustDefault
*/ */
export function mustCoalesce<T>(...values: Array<Optional<T>>): T { export function mustCoalesce<T>(...values: Array<Optional<T>>): T {
return mustFind(values, doesExist); return mustFind(values, doesExist);