|
- import * as inferred_types from 'inferred-types';
- import { LeftWhitespace, CamelCase, RightWhitespace, IsStringLiteral, Dasherize, Keys, Length, PascalCase } from 'inferred-types';
- import * as brilliant_errors from 'brilliant-errors';
-
- interface IDictionary<T = any> {
- [key: string]: T;
- }
-
- declare function atRandom<T = any>(things: T[], excluding?: T[] | ((item: T) => boolean)): T;
-
- /**
- * Converts a utf-8 string into Base64
- *
- * @param input any string based input
- */
- declare function toBase64(input: string): string;
- /** a string encoded as Base64 */
- type base64 = string;
- /**
- * Converts a base64 string to utf-8.
- *
- * @param input a base64 string
- * @param isJson flag to indicate that the converted payload should be treated as JSON
- * and converted to a javascript object
- */
- declare function fromBase64<T extends string | object>(input: base64, isJson?: boolean): T;
-
- declare function between(start: number, end: number): number;
-
- /**
- * **Camelize**
- *
- * Converts a string into _camelCase_ string and transforms **type** of a _string literal_ to match
- * (a _string_ type remains a _string_).
- *
- * Note: _by default whitespace on both left and right side is removed, but you can change this
- * behavior by setting the optional "preserveWhitespace" parameter to `false`_
- */
- declare function camelize<S extends string, P extends boolean | undefined = undefined>(input: S, preserveWhitespace?: P): true extends P ? `${LeftWhitespace<S>}${CamelCase<S>}${RightWhitespace<S>}` : CamelCase<S>;
-
- /**
- * Capitalizes the first character of the string passed in.
- *
- * **Note:** if input is a string literal than the typing
- * for the literal will be capitalized too
- */
- declare function capitalize<T extends Readonly<string>>(input: T): IsStringLiteral<T> extends true ? Capitalize<T> : string;
-
- /**
- * Creates a type-strong lookup function which ensures strong typing conversions from one
- * type `K` to another `V`.
- * ```ts
- * const color = createLookup<Color,RGB>(
- * { red: [255,0.0], blue: [137,207,240] },
- * [128,128,128]
- * );
- * const red = color("red");
- * const other = color("foobar"); // [137,207,240]
- * ```
- */
- declare function createLookup<K extends string | number | boolean, V extends {}, M extends (m: any) => V = (m: any) => V>(known: Record<Exclude<K, boolean>, V>, miss?: M): (v: K | boolean) => V;
-
- /**
- * Produces a _dasherized_ version of a passed in string by:
- *
- * 1. Replacing all interior whitespace with a dash
- * 2. Replacing capitalized letters with a dash followed by the lowercase variant.
- * 3. Replace underscores with dashes
- * 4. Ensuring that duplicate dashes are removed and that non-whitespaced
- * characters are not dashes
- *
- * Note: does not impact exterior whitespace, e.g., ` myDash ` is translated to ` my-dash ` and leading and closing white space is not transformed.
- */
- declare function dasherize<S extends string, P extends boolean | undefined = undefined>(input: S, preserveWhitespace?: P): true extends P ? `${LeftWhitespace<S>}${Dasherize<S>}${RightWhitespace<S>}` : Dasherize<S>;
-
- declare enum DataType {
- null = "null",
- string = "string",
- number = "number",
- bigint = "bigint",
- symbol = "symbol",
- boolean = "boolean",
- function = "function",
- undefined = "undefined",
- /** an object with key-value pairs */
- dictionary = "dictionary",
- /** an object of unknown type */
- object = "object",
- /** an array of unknown type */
- array = "array",
- /** an array of just strings */
- stringArray = "string[]",
- /** an array of just numbers */
- numberArray = "number[]",
- /** an array of just boolean flags */
- booleanArray = "boolean[]",
- /** an array of just symbols */
- symbolArray = "symbol[]",
- /** an array of just functions */
- functionArray = "function[]",
- /** an array of just `undefined` values */
- undefinedArray = "undefined[]",
- /** an array of just `null` values */
- nullArray = "null[]",
- /** an array of empty objects */
- objectArray = "object[]",
- /**
- * An array of the _same_ type of dictionary
- */
- dictionaryArray = "dictionary[]"
- }
- interface IDictionaryDescriptor {
- [key: string]: DataType | IDataDescriptor;
- }
- /**
- * A description of the type of a data structure or scalar value
- */
- type IDataDescriptor = IDictionaryDescriptor | Array<DataType | IDataDescriptor> | DataType;
- /**
- * A type-guard to check whether a given variable is a non-null based object
- */
- declare function isNonNullObject<T extends object>(thingy: unknown): thingy is T;
-
- /**
- * Describes the types of the run-time data structure.
- */
- declare function describe(data: unknown): IDataDescriptor;
-
- declare function deserialize(arr: string): any[];
-
- declare const KnownError: brilliant_errors.Constructor<[message: string, classification: `cardinality/${string}` | `network/${string}` | `invalid-type/${string}` | `missing-resource/${string}` | `not-allowed/${string}`, options?: brilliant_errors.IErrorRuntimeOptions<number> | undefined], brilliant_errors.IBrilliantError<"KnownError", "NativeDash", "cardinality" | "network" | "invalid-type" | "missing-resource" | "not-allowed", string, number, "standard">>;
- declare const isKnownError: inferred_types.TypeGuard<brilliant_errors.IBrilliantError<"KnownError", "NativeDash", "cardinality" | "network" | "invalid-type" | "missing-resource" | "not-allowed", string, number, "standard">>;
- declare const UnknownError: brilliant_errors.Constructor<[message: string, classification: `${string}/${string}`, options?: brilliant_errors.IErrorRuntimeOptions<number> | undefined], brilliant_errors.IBrilliantError<"KnownError", "NativeDash", string, string, number, "standard">>;
- declare const isUnknownError: inferred_types.TypeGuard<brilliant_errors.IBrilliantError<"KnownError", "NativeDash", string, string, number, "standard">>;
-
- /**
- * Compare two variables for equality, and optionally specify a _depth_ for dictionaries.
- */
- declare function equal(a: unknown, b: unknown, depth?: number): boolean;
-
- type FindResult<P extends string, N extends readonly string[]> = {
- all: string;
- next: () => FindResult<P, N>;
- found: true;
- } & Record<Keys<N>, string>;
- type NotFound = {
- found: false;
- } & Record<string, undefined>;
- type FindExpression<P extends string, N extends readonly string[]> = (content: string) => Length<N> extends 0 ? string[] | false : FindResult<P, N> | NotFound;
- /**
- * Finds the first instance of the given RegExp and reports on it.
- *
- * The key to understand the return type is that if no _names_ were provided then
- * it will just return an array where the first value is the entire match expression
- * and each one afterwards is a sub-expression match. If you _do_ provide names you'll
- * not only get back a named dictionary but also a `.next()` function which can let you
- * move to the next match.
- *
- * ```ts
- * const getDnsAndIp = find(".*DNS:(.*),IP:(.*)", "dns", "ip");
- * const { dns, ip } = getDnsAndIp(content);
- * ```
- * @param pattern a RegExp expression in string form
- * @param names optionally specify the names of sub-expressions in your RegExp
- */
- declare const find: <P extends string, N extends readonly string[]>(pattern: P, ...names: N) => FindExpression<P, N>;
-
- type FindAllExpression<P extends string, N extends readonly string[]> = (content: string) => Length<N> extends 0 ? string[][] : FindResult<P, N>[];
- type FindAllResult<N extends readonly string[]> = {
- all: string;
- } & Record<Keys<N>, string>;
- declare const findAll: <P extends string, N extends readonly string[]>(pattern: P, ...names: N) => FindAllExpression<P, N>;
-
- /**
- * **first**
- *
- * returns the first item in an array
- */
- declare function first<T = any>(arr: T[]): T;
-
- /**
- * **firstKey**
- *
- * returns the _first_ key in a dictionary or `false` if there are no
- * keys in the object passed in.
- */
- declare function firstKey<T extends {} = {}>(dict: T): keyof T | false;
-
- /**
- * **flatten**
- *
- * > If you know that your run-time supports using the native `[ ].flat()` language feature
- * (which all modern node runtimes and browsers largely outside of IE11 do then you should
- * use this instead).
- */
- declare function flatten<T = any>(arr: T[]): T[] | (T extends readonly (infer InnerArr)[] ? InnerArr : T)[];
-
- /**
- * **get**
- *
- * Gets a value in a deeply nested object. This is a replacement to `lodash.get`
- *
- * @param obj the base object to get the value from
- * @param dotPath the path to the object, using "." as a delimiter
- * @param defaultValue optionally you may state a default value if the operation results in `undefined`
- */
- declare function get<T = any>(obj: IDictionary, dotPath: string, defaultValue?: any): T;
-
- type GroupByFunction<T extends {}> = (v: T) => any;
- /**
- * Groups an array of dictionary items into dictionary of arrays _grouped_
- * by either a property in the array or a function that provides the key.
- *
- * ```ts
- * const data = [
- * {name: "foo", value: 1}, {name: "bar", value: 2}, {name: "foo", value: 3}
- * ];
- * // { foo: [ {value: 1}, {value: 3}], bar: [{value: 2}] }
- * const grouped = groupBy("name", data);
- * ```
- */
- declare function groupBy<T extends {}, K extends keyof T | GroupByFunction<T>>(propOrFn: K, data: readonly T[]): K extends GroupByFunction<T> ? Record<ReturnType<K>[0], ReturnType<K>[1][]> : K extends keyof T ? T[K] extends string | number ? Record<string, Omit<T, K>[]> : never : never;
-
- /**
- * Produces a dasherized random ID
- *
- * @deprecated please use `uuid` instead
- */
- declare function guid(): string;
-
- /**
- * Provides a hashing function which produces a 32-bit integer
- * hash which provides idempotency.
- *
- * This function is not intended to be used in situations where
- * there is need for strong cryptographic assurances but rather
- * where a _very_ lightweight hasher is desired.
- *
- * For more information on this hash function refer to the discussion
- * on stackoverflow: https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript
- *
- * @param digest the text digest to be hashed
- */
- declare function hash(digest: string): number;
-
- type InitialsStrategy = "all" | "kabab" | "words" | "camelCase";
- declare function initials<S extends InitialsStrategy>(input: string, strategy?: S): string;
-
- /**
- * Checks whether a given number is an _odd_ number.
- */
- declare function isEven(value: number): boolean;
-
- /**
- * Tests whether the passed in year is a leap year or not
- */
- declare function isLeapYear(year: number | Date): boolean;
-
- /**
- * Checks whether a given number is an _odd_ number.
- */
- declare function isOdd(value: number): boolean;
-
- /**
- * Tests whether the passed in string is a valid GUID. Valid GUID's
- * must be of the format. This is typically expressed in a **RegExp** as:
- *
- * ```ts
- * /^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$/
- * ```
- *
- * However, the dashes are not a strict requirement, so you may choose to validate
- * using both the above format and the non-dasherized version. Default behavior is _not_
- * to allow the non-dasherized form.
- */
- declare function isUuid(candidate: string, allowNonDashedForm?: boolean): boolean;
-
- /**
- * Provides the _keys_ of an object with the keys returned explicitly
- * as `keyof T`.
- */
- declare function keys<T extends {}>(obj: T): (keyof T)[];
-
- /**
- * **last**
- *
- * returns the last item in an array
- */
- declare function last<T = any>(arr: T[]): T;
-
- /**
- * **lastKey**
- *
- * returns the _last_ key in a dictionary or `false` if there are no
- * keys in object passed in.
- */
- declare function lastKey<T extends {}>(dict: T): keyof T | false;
-
- type Omit$1<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
- /**
- * **omit**
- *
- * Removes/omits properties of an object and returns a shallow copy with props
- * removed and with typescript types updated to reflect this removal.
- *
- * @param obj the starting state object
- * @param removals an array of properties to be removed from the object
- */
- declare function omit<T extends {}, K extends Array<keyof T>>(obj: T, ...removals: K): Omit$1<T, K[number]>;
-
- /**
- * **Pascalize**
- *
- * converts string representations in camelCase, snake_case, or space separated
- * into a PascalCase representation.
- *
- * Note: _by default it also removes surrounding white space (if it exists) but it
- * can be preserved if you change the `preserveWhitespace` flag._
- */
- declare function pascalize<S extends string, P extends boolean | undefined = undefined>(input: S, preserveWhitespace?: P): true extends P ? `${LeftWhitespace<S>}${PascalCase<S>}${RightWhitespace<S>}` : PascalCase<S>;
-
- /**
- * Joins a set of paths together into a single path.
- *
- * **Note:** trailing path never includes a `/` so add this at the end if
- * you need it.
- *
- * **Note:** the ".." characters are allowed in starting string but in no
- * other.
- *
- * **Note:** any use of the Windows "\\" will be converted to the Posix "/"
- */
- declare function pathJoin(...args: string[]): string;
-
- type PluralExceptionTuple = [pattern: RegExp, plural: string];
- type IPluralizeRuleEngine = (input: string, rule: RegExp, exceptions: string[]) => string;
- type IPluralizeRule = [
- pattern: RegExp,
- fn: IPluralizeRuleEngine,
- exceptions?: string[]
- ];
- type IExplicitPluralization = [singular: string, plural: string];
- interface IPluralizeOptions {
- /** you can manually put a string at the end and if done the default rules will not be run */
- postfix?: string;
- /** you can put in your own rules engine where you'd like */
- rules?: IPluralizeRuleEngine;
- /**
- * You can also extend or override the default "explicit rules" by sending in your
- * own dictionary mapping:
- *
- * ```ts
- * const explictPluralizations = [
- * /^foo$/: 'foey',
- * /(.*)bar$/: '$1barred',
- * ]
- * const plural = pluralize(something, { explictPluralizations });
- * ```
- */
- bespokeExceptions?: PluralExceptionTuple[];
- additionalRules?: IPluralizeRule[];
- /**
- * By default an error is thrown when passed in an empty string but setting
- * this to `true` will pass back an empty string and just ignore.
- */
- ignoreEmptyStrings?: boolean;
- }
- /**
- * A simple and light weight pluralizer utility.
- */
- declare function pluralize(input: string, options?: IPluralizeOptions): string;
-
- /**
- * Provides a dependency-free method of generating
- * a useful 4 character random string.
- *
- * > **Note:** if you want a GUID then use the `guid()`
- * function instead which leverages this function but
- * puts it into the proper GUID format
- */
- declare function randomString(): string;
-
- type Include<T, U, L extends boolean = false> = L extends true ? T extends U ? U extends T ? T : never : never : T extends U ? T : never;
- type Retain<T, K extends keyof T> = Pick<T, Include<keyof T, K>>;
- /**
- * **retain**
- *
- * Retains an explicit set of key/value pairs on a dictionary and ensures both
- * runtime value and type system remove the other properties.
- *
- * @param obj the starting state object
- * @param retainedProps an array of properties to be _retained_ on the object
- * ```ts
- * // { foo: number, bar: string }
- * const foobar = retain({foo: 1, bar: "hi", baz: ""}, "foo", "bar");
- * ```
- */
- declare function retain<T extends {}, K extends Array<keyof T>>(obj: T, ...retainedProps: K): Retain<T, K[number]>;
-
- /**
- * converts an array of _things_ into a `\n` delimited
- * string of stringified objects.
- *
- * FUTURE: If a **source** is passed in
- * -- either a _file_ or _url_ then it will stream to that
- * source.
- *
- */
- declare function serialize(arr: any[] /** , source?: url | filename **/): string;
-
- /**
- * Sets a value at a nested point within base object passed in. This is meant as a
- * replacement to use of `lodash.set()`.
- *
- * @param obj the base object which is being mutated
- * @param dotPath the path into the object where the mutation will take place, delimited by `.`
- * @param value The value to set at the _dotPath_
- * @param createIfNonExistant by default, if the path to the object does not exist then an error is thrown but if you want you can state the desire to have the full path created
- */
- declare function set(obj: IDictionary, dotPath: string, value: any, createIfNonExistant?: boolean): void;
-
- /**
- * **Snakerize**
- *
- * Converts a string to snake_case notation.
- *
- * Note: _by default it also removes surrounding white space (if it exists) but it
- * can be preserved if you change the `preserveWhitespace` flag._
- */
- declare function snakerize(input: string, preserveWhitespace?: boolean): string;
-
- /**
- * Provides the unique values for a given property in an array of
- * commonly typed objects.
- *
- * @param list the list of objects
- * @param property the property to evaluate
- */
- declare function unique<T extends IDictionary = any>(list: T[], property: keyof T & string): T[];
-
- /**
- * Produces a UUID with 32 random string characters.
- *
- * By default this will use the dasherized convention of **uuid** but you can
- * turn this off and just output the random string characters.
- */
- declare function uuid(dasherized?: boolean): string;
-
- declare const RESET_FG = "\u001B[39m";
- declare const RESET_BG = "\u001B[49m";
- /**
- * A dictionary of colors; first value is foreground,
- * second is background.
- */
- declare const COLOR: Record<IColor, [fg: number, bg: number]>;
-
- declare function paint(text: string | undefined, fg: ColorConfigurator, bg?: ColorConfigurator): string;
-
- declare function replace(find: string, corpus: string, formatting: IFormattingOptions, global?: boolean): string;
-
- type IColor = "black" | "red" | "magenta" | "yellow" | "green" | "brightRed" | "brightGreen" | "brightYellow";
- type Color = keyof typeof COLOR;
- type ColorConfigurator = (color: typeof COLOR) => [fg: number, bg: number];
- type ColorFormatter = (text?: string, bg?: ColorConfigurator) => string;
- interface IFormattingOptions {
- color?: ColorConfigurator;
- bg?: ColorConfigurator;
- italics?: true;
- underline?: true;
- strikeThrough?: true;
- }
- type FluentOneUse<TApi extends Record<string, any>, TOneUse extends string> = TOneUse extends string ? Omit<TApi, TOneUse> : TApi;
- /**
- * Defines a Fluent API, types are (in order):
- *
- * - `TFluent`: the _fns_ on the API which return the Fluent API after modifying state
- * - `TExits`: the _functions_ on the API which _exit_ the Fluent interface
- * - `TProps`: the read-only _properties_ on the API; default is _false_ indicating none
- * - `TOneUse`: the prop names of the Fluent API which should be removed from the API once used once; default is _false_ indicating none
- */
- type FluentApi<TFluent extends Record<string, (...args: any[]) => unknown>, TExits extends Record<string, (...args: any[]) => any>, TProps extends Record<string, Readonly<any>> | false = false, TOneUse extends string & keyof TFluent = "", TExclude extends string = ""> = FluentOneUse<Pick<TFluent, TOneUse>, TExclude> & Omit<TFluent, TOneUse> & TExits & Readonly<TProps>;
- /**
- * A fluent API design to replace a text block with a _formatted_ version
- */
- type IFormattingApi<X extends string = ""> = FluentApi<{
- /** Add a _foreground_ color for the text that matches */
- withColor: X extends "withColor" ? never : (fg: ColorConfigurator) => IFormattingApi<X | "withColor">;
- withItalics: () => IFormattingApi<X | "withItalics">;
- withUnderline: () => IFormattingApi<X | "withUnderline">;
- withStrikethrough: () => IFormattingApi<X | "withStrikethrough">;
- /** Add a _background_ color for the text that matches */
- withBackground: (bg: ColorConfigurator) => unknown;
- }, {
- /** provide the _corpus_ of text to search through */
- in: (corpus: string) => string;
- }, {
- config: IFormattingOptions;
- }, "withColor" | "withItalics" | "withBackground" | "withStrikethrough" | "withUnderline">;
-
- /**
- * Colorize text in the console.
- *
- * Choose a foreground color and optionally a background color.
- */
- declare const color: {
- red: (text?: string, bg?: ColorConfigurator) => string;
- magenta: (text?: string, bg?: ColorConfigurator) => string;
- black: (text?: string, bg?: ColorConfigurator) => string;
- yellow: (text?: string, bg?: ColorConfigurator) => string;
- green: (text?: string, bg?: ColorConfigurator) => string;
- brightRed: (text?: string, bg?: ColorConfigurator) => string;
- };
-
- /** _italicize_ a block of text */
- declare function italicize(text?: string): string;
- /** _underline_ a block of text */
- declare function underline(text?: string): string;
- /** ~strikethrough~ a block of text (not supported on many terminals) */
- declare function strikethrough(text?: string): string;
-
- export { COLOR, Color, ColorConfigurator, ColorFormatter, DataType, FindAllExpression, FindAllResult, FindExpression, FindResult, FluentApi, FluentOneUse, GroupByFunction, IColor, IDataDescriptor, IDictionary, IDictionaryDescriptor, IExplicitPluralization, IFormattingApi, IFormattingOptions, IPluralizeOptions, IPluralizeRule, IPluralizeRuleEngine, Include, InitialsStrategy, KnownError, NotFound, Omit$1 as Omit, PluralExceptionTuple, RESET_BG, RESET_FG, Retain, UnknownError, atRandom, base64, between, camelize, capitalize, color, createLookup, dasherize, describe, deserialize, equal, find, findAll, first, firstKey, flatten, fromBase64, get, groupBy, guid, hash, initials, isEven, isKnownError, isLeapYear, isNonNullObject, isOdd, isUnknownError, isUuid, italicize, keys, last, lastKey, omit, paint, pascalize, pathJoin, pluralize, randomString, replace, retain, serialize, set, snakerize, strikethrough, toBase64, underline, unique, uuid };
|