版博士V2.0程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

522 lines
21 KiB

  1. import * as inferred_types from 'inferred-types';
  2. import { LeftWhitespace, CamelCase, RightWhitespace, IsStringLiteral, Dasherize, Keys, Length, PascalCase } from 'inferred-types';
  3. import * as brilliant_errors from 'brilliant-errors';
  4. interface IDictionary<T = any> {
  5. [key: string]: T;
  6. }
  7. declare function atRandom<T = any>(things: T[], excluding?: T[] | ((item: T) => boolean)): T;
  8. /**
  9. * Converts a utf-8 string into Base64
  10. *
  11. * @param input any string based input
  12. */
  13. declare function toBase64(input: string): string;
  14. /** a string encoded as Base64 */
  15. type base64 = string;
  16. /**
  17. * Converts a base64 string to utf-8.
  18. *
  19. * @param input a base64 string
  20. * @param isJson flag to indicate that the converted payload should be treated as JSON
  21. * and converted to a javascript object
  22. */
  23. declare function fromBase64<T extends string | object>(input: base64, isJson?: boolean): T;
  24. declare function between(start: number, end: number): number;
  25. /**
  26. * **Camelize**
  27. *
  28. * Converts a string into _camelCase_ string and transforms **type** of a _string literal_ to match
  29. * (a _string_ type remains a _string_).
  30. *
  31. * Note: _by default whitespace on both left and right side is removed, but you can change this
  32. * behavior by setting the optional "preserveWhitespace" parameter to `false`_
  33. */
  34. 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>;
  35. /**
  36. * Capitalizes the first character of the string passed in.
  37. *
  38. * **Note:** if input is a string literal than the typing
  39. * for the literal will be capitalized too
  40. */
  41. declare function capitalize<T extends Readonly<string>>(input: T): IsStringLiteral<T> extends true ? Capitalize<T> : string;
  42. /**
  43. * Creates a type-strong lookup function which ensures strong typing conversions from one
  44. * type `K` to another `V`.
  45. * ```ts
  46. * const color = createLookup<Color,RGB>(
  47. * { red: [255,0.0], blue: [137,207,240] },
  48. * [128,128,128]
  49. * );
  50. * const red = color("red");
  51. * const other = color("foobar"); // [137,207,240]
  52. * ```
  53. */
  54. 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;
  55. /**
  56. * Produces a _dasherized_ version of a passed in string by:
  57. *
  58. * 1. Replacing all interior whitespace with a dash
  59. * 2. Replacing capitalized letters with a dash followed by the lowercase variant.
  60. * 3. Replace underscores with dashes
  61. * 4. Ensuring that duplicate dashes are removed and that non-whitespaced
  62. * characters are not dashes
  63. *
  64. * Note: does not impact exterior whitespace, e.g., ` myDash ` is translated to ` my-dash ` and leading and closing white space is not transformed.
  65. */
  66. 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>;
  67. declare enum DataType {
  68. null = "null",
  69. string = "string",
  70. number = "number",
  71. bigint = "bigint",
  72. symbol = "symbol",
  73. boolean = "boolean",
  74. function = "function",
  75. undefined = "undefined",
  76. /** an object with key-value pairs */
  77. dictionary = "dictionary",
  78. /** an object of unknown type */
  79. object = "object",
  80. /** an array of unknown type */
  81. array = "array",
  82. /** an array of just strings */
  83. stringArray = "string[]",
  84. /** an array of just numbers */
  85. numberArray = "number[]",
  86. /** an array of just boolean flags */
  87. booleanArray = "boolean[]",
  88. /** an array of just symbols */
  89. symbolArray = "symbol[]",
  90. /** an array of just functions */
  91. functionArray = "function[]",
  92. /** an array of just `undefined` values */
  93. undefinedArray = "undefined[]",
  94. /** an array of just `null` values */
  95. nullArray = "null[]",
  96. /** an array of empty objects */
  97. objectArray = "object[]",
  98. /**
  99. * An array of the _same_ type of dictionary
  100. */
  101. dictionaryArray = "dictionary[]"
  102. }
  103. interface IDictionaryDescriptor {
  104. [key: string]: DataType | IDataDescriptor;
  105. }
  106. /**
  107. * A description of the type of a data structure or scalar value
  108. */
  109. type IDataDescriptor = IDictionaryDescriptor | Array<DataType | IDataDescriptor> | DataType;
  110. /**
  111. * A type-guard to check whether a given variable is a non-null based object
  112. */
  113. declare function isNonNullObject<T extends object>(thingy: unknown): thingy is T;
  114. /**
  115. * Describes the types of the run-time data structure.
  116. */
  117. declare function describe(data: unknown): IDataDescriptor;
  118. declare function deserialize(arr: string): any[];
  119. 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">>;
  120. declare const isKnownError: inferred_types.TypeGuard<brilliant_errors.IBrilliantError<"KnownError", "NativeDash", "cardinality" | "network" | "invalid-type" | "missing-resource" | "not-allowed", string, number, "standard">>;
  121. 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">>;
  122. declare const isUnknownError: inferred_types.TypeGuard<brilliant_errors.IBrilliantError<"KnownError", "NativeDash", string, string, number, "standard">>;
  123. /**
  124. * Compare two variables for equality, and optionally specify a _depth_ for dictionaries.
  125. */
  126. declare function equal(a: unknown, b: unknown, depth?: number): boolean;
  127. type FindResult<P extends string, N extends readonly string[]> = {
  128. all: string;
  129. next: () => FindResult<P, N>;
  130. found: true;
  131. } & Record<Keys<N>, string>;
  132. type NotFound = {
  133. found: false;
  134. } & Record<string, undefined>;
  135. type FindExpression<P extends string, N extends readonly string[]> = (content: string) => Length<N> extends 0 ? string[] | false : FindResult<P, N> | NotFound;
  136. /**
  137. * Finds the first instance of the given RegExp and reports on it.
  138. *
  139. * The key to understand the return type is that if no _names_ were provided then
  140. * it will just return an array where the first value is the entire match expression
  141. * and each one afterwards is a sub-expression match. If you _do_ provide names you'll
  142. * not only get back a named dictionary but also a `.next()` function which can let you
  143. * move to the next match.
  144. *
  145. * ```ts
  146. * const getDnsAndIp = find(".*DNS:(.*),IP:(.*)", "dns", "ip");
  147. * const { dns, ip } = getDnsAndIp(content);
  148. * ```
  149. * @param pattern a RegExp expression in string form
  150. * @param names optionally specify the names of sub-expressions in your RegExp
  151. */
  152. declare const find: <P extends string, N extends readonly string[]>(pattern: P, ...names: N) => FindExpression<P, N>;
  153. type FindAllExpression<P extends string, N extends readonly string[]> = (content: string) => Length<N> extends 0 ? string[][] : FindResult<P, N>[];
  154. type FindAllResult<N extends readonly string[]> = {
  155. all: string;
  156. } & Record<Keys<N>, string>;
  157. declare const findAll: <P extends string, N extends readonly string[]>(pattern: P, ...names: N) => FindAllExpression<P, N>;
  158. /**
  159. * **first**
  160. *
  161. * returns the first item in an array
  162. */
  163. declare function first<T = any>(arr: T[]): T;
  164. /**
  165. * **firstKey**
  166. *
  167. * returns the _first_ key in a dictionary or `false` if there are no
  168. * keys in the object passed in.
  169. */
  170. declare function firstKey<T extends {} = {}>(dict: T): keyof T | false;
  171. /**
  172. * **flatten**
  173. *
  174. * > If you know that your run-time supports using the native `[ ].flat()` language feature
  175. * (which all modern node runtimes and browsers largely outside of IE11 do then you should
  176. * use this instead).
  177. */
  178. declare function flatten<T = any>(arr: T[]): T[] | (T extends readonly (infer InnerArr)[] ? InnerArr : T)[];
  179. /**
  180. * **get**
  181. *
  182. * Gets a value in a deeply nested object. This is a replacement to `lodash.get`
  183. *
  184. * @param obj the base object to get the value from
  185. * @param dotPath the path to the object, using "." as a delimiter
  186. * @param defaultValue optionally you may state a default value if the operation results in `undefined`
  187. */
  188. declare function get<T = any>(obj: IDictionary, dotPath: string, defaultValue?: any): T;
  189. type GroupByFunction<T extends {}> = (v: T) => any;
  190. /**
  191. * Groups an array of dictionary items into dictionary of arrays _grouped_
  192. * by either a property in the array or a function that provides the key.
  193. *
  194. * ```ts
  195. * const data = [
  196. * {name: "foo", value: 1}, {name: "bar", value: 2}, {name: "foo", value: 3}
  197. * ];
  198. * // { foo: [ {value: 1}, {value: 3}], bar: [{value: 2}] }
  199. * const grouped = groupBy("name", data);
  200. * ```
  201. */
  202. 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;
  203. /**
  204. * Produces a dasherized random ID
  205. *
  206. * @deprecated please use `uuid` instead
  207. */
  208. declare function guid(): string;
  209. /**
  210. * Provides a hashing function which produces a 32-bit integer
  211. * hash which provides idempotency.
  212. *
  213. * This function is not intended to be used in situations where
  214. * there is need for strong cryptographic assurances but rather
  215. * where a _very_ lightweight hasher is desired.
  216. *
  217. * For more information on this hash function refer to the discussion
  218. * on stackoverflow: https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript
  219. *
  220. * @param digest the text digest to be hashed
  221. */
  222. declare function hash(digest: string): number;
  223. type InitialsStrategy = "all" | "kabab" | "words" | "camelCase";
  224. declare function initials<S extends InitialsStrategy>(input: string, strategy?: S): string;
  225. /**
  226. * Checks whether a given number is an _odd_ number.
  227. */
  228. declare function isEven(value: number): boolean;
  229. /**
  230. * Tests whether the passed in year is a leap year or not
  231. */
  232. declare function isLeapYear(year: number | Date): boolean;
  233. /**
  234. * Checks whether a given number is an _odd_ number.
  235. */
  236. declare function isOdd(value: number): boolean;
  237. /**
  238. * Tests whether the passed in string is a valid GUID. Valid GUID's
  239. * must be of the format. This is typically expressed in a **RegExp** as:
  240. *
  241. * ```ts
  242. * /^(\{{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})$/
  243. * ```
  244. *
  245. * However, the dashes are not a strict requirement, so you may choose to validate
  246. * using both the above format and the non-dasherized version. Default behavior is _not_
  247. * to allow the non-dasherized form.
  248. */
  249. declare function isUuid(candidate: string, allowNonDashedForm?: boolean): boolean;
  250. /**
  251. * Provides the _keys_ of an object with the keys returned explicitly
  252. * as `keyof T`.
  253. */
  254. declare function keys<T extends {}>(obj: T): (keyof T)[];
  255. /**
  256. * **last**
  257. *
  258. * returns the last item in an array
  259. */
  260. declare function last<T = any>(arr: T[]): T;
  261. /**
  262. * **lastKey**
  263. *
  264. * returns the _last_ key in a dictionary or `false` if there are no
  265. * keys in object passed in.
  266. */
  267. declare function lastKey<T extends {}>(dict: T): keyof T | false;
  268. type Omit$1<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
  269. /**
  270. * **omit**
  271. *
  272. * Removes/omits properties of an object and returns a shallow copy with props
  273. * removed and with typescript types updated to reflect this removal.
  274. *
  275. * @param obj the starting state object
  276. * @param removals an array of properties to be removed from the object
  277. */
  278. declare function omit<T extends {}, K extends Array<keyof T>>(obj: T, ...removals: K): Omit$1<T, K[number]>;
  279. /**
  280. * **Pascalize**
  281. *
  282. * converts string representations in camelCase, snake_case, or space separated
  283. * into a PascalCase representation.
  284. *
  285. * Note: _by default it also removes surrounding white space (if it exists) but it
  286. * can be preserved if you change the `preserveWhitespace` flag._
  287. */
  288. 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>;
  289. /**
  290. * Joins a set of paths together into a single path.
  291. *
  292. * **Note:** trailing path never includes a `/` so add this at the end if
  293. * you need it.
  294. *
  295. * **Note:** the ".." characters are allowed in starting string but in no
  296. * other.
  297. *
  298. * **Note:** any use of the Windows "\\" will be converted to the Posix "/"
  299. */
  300. declare function pathJoin(...args: string[]): string;
  301. type PluralExceptionTuple = [pattern: RegExp, plural: string];
  302. type IPluralizeRuleEngine = (input: string, rule: RegExp, exceptions: string[]) => string;
  303. type IPluralizeRule = [
  304. pattern: RegExp,
  305. fn: IPluralizeRuleEngine,
  306. exceptions?: string[]
  307. ];
  308. type IExplicitPluralization = [singular: string, plural: string];
  309. interface IPluralizeOptions {
  310. /** you can manually put a string at the end and if done the default rules will not be run */
  311. postfix?: string;
  312. /** you can put in your own rules engine where you'd like */
  313. rules?: IPluralizeRuleEngine;
  314. /**
  315. * You can also extend or override the default "explicit rules" by sending in your
  316. * own dictionary mapping:
  317. *
  318. * ```ts
  319. * const explictPluralizations = [
  320. * /^foo$/: 'foey',
  321. * /(.*)bar$/: '$1barred',
  322. * ]
  323. * const plural = pluralize(something, { explictPluralizations });
  324. * ```
  325. */
  326. bespokeExceptions?: PluralExceptionTuple[];
  327. additionalRules?: IPluralizeRule[];
  328. /**
  329. * By default an error is thrown when passed in an empty string but setting
  330. * this to `true` will pass back an empty string and just ignore.
  331. */
  332. ignoreEmptyStrings?: boolean;
  333. }
  334. /**
  335. * A simple and light weight pluralizer utility.
  336. */
  337. declare function pluralize(input: string, options?: IPluralizeOptions): string;
  338. /**
  339. * Provides a dependency-free method of generating
  340. * a useful 4 character random string.
  341. *
  342. * > **Note:** if you want a GUID then use the `guid()`
  343. * function instead which leverages this function but
  344. * puts it into the proper GUID format
  345. */
  346. declare function randomString(): string;
  347. 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;
  348. type Retain<T, K extends keyof T> = Pick<T, Include<keyof T, K>>;
  349. /**
  350. * **retain**
  351. *
  352. * Retains an explicit set of key/value pairs on a dictionary and ensures both
  353. * runtime value and type system remove the other properties.
  354. *
  355. * @param obj the starting state object
  356. * @param retainedProps an array of properties to be _retained_ on the object
  357. * ```ts
  358. * // { foo: number, bar: string }
  359. * const foobar = retain({foo: 1, bar: "hi", baz: ""}, "foo", "bar");
  360. * ```
  361. */
  362. declare function retain<T extends {}, K extends Array<keyof T>>(obj: T, ...retainedProps: K): Retain<T, K[number]>;
  363. /**
  364. * converts an array of _things_ into a `\n` delimited
  365. * string of stringified objects.
  366. *
  367. * FUTURE: If a **source** is passed in
  368. * -- either a _file_ or _url_ then it will stream to that
  369. * source.
  370. *
  371. */
  372. declare function serialize(arr: any[] /** , source?: url | filename **/): string;
  373. /**
  374. * Sets a value at a nested point within base object passed in. This is meant as a
  375. * replacement to use of `lodash.set()`.
  376. *
  377. * @param obj the base object which is being mutated
  378. * @param dotPath the path into the object where the mutation will take place, delimited by `.`
  379. * @param value The value to set at the _dotPath_
  380. * @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
  381. */
  382. declare function set(obj: IDictionary, dotPath: string, value: any, createIfNonExistant?: boolean): void;
  383. /**
  384. * **Snakerize**
  385. *
  386. * Converts a string to snake_case notation.
  387. *
  388. * Note: _by default it also removes surrounding white space (if it exists) but it
  389. * can be preserved if you change the `preserveWhitespace` flag._
  390. */
  391. declare function snakerize(input: string, preserveWhitespace?: boolean): string;
  392. /**
  393. * Provides the unique values for a given property in an array of
  394. * commonly typed objects.
  395. *
  396. * @param list the list of objects
  397. * @param property the property to evaluate
  398. */
  399. declare function unique<T extends IDictionary = any>(list: T[], property: keyof T & string): T[];
  400. /**
  401. * Produces a UUID with 32 random string characters.
  402. *
  403. * By default this will use the dasherized convention of **uuid** but you can
  404. * turn this off and just output the random string characters.
  405. */
  406. declare function uuid(dasherized?: boolean): string;
  407. declare const RESET_FG = "\u001B[39m";
  408. declare const RESET_BG = "\u001B[49m";
  409. /**
  410. * A dictionary of colors; first value is foreground,
  411. * second is background.
  412. */
  413. declare const COLOR: Record<IColor, [fg: number, bg: number]>;
  414. declare function paint(text: string | undefined, fg: ColorConfigurator, bg?: ColorConfigurator): string;
  415. declare function replace(find: string, corpus: string, formatting: IFormattingOptions, global?: boolean): string;
  416. type IColor = "black" | "red" | "magenta" | "yellow" | "green" | "brightRed" | "brightGreen" | "brightYellow";
  417. type Color = keyof typeof COLOR;
  418. type ColorConfigurator = (color: typeof COLOR) => [fg: number, bg: number];
  419. type ColorFormatter = (text?: string, bg?: ColorConfigurator) => string;
  420. interface IFormattingOptions {
  421. color?: ColorConfigurator;
  422. bg?: ColorConfigurator;
  423. italics?: true;
  424. underline?: true;
  425. strikeThrough?: true;
  426. }
  427. type FluentOneUse<TApi extends Record<string, any>, TOneUse extends string> = TOneUse extends string ? Omit<TApi, TOneUse> : TApi;
  428. /**
  429. * Defines a Fluent API, types are (in order):
  430. *
  431. * - `TFluent`: the _fns_ on the API which return the Fluent API after modifying state
  432. * - `TExits`: the _functions_ on the API which _exit_ the Fluent interface
  433. * - `TProps`: the read-only _properties_ on the API; default is _false_ indicating none
  434. * - `TOneUse`: the prop names of the Fluent API which should be removed from the API once used once; default is _false_ indicating none
  435. */
  436. 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>;
  437. /**
  438. * A fluent API design to replace a text block with a _formatted_ version
  439. */
  440. type IFormattingApi<X extends string = ""> = FluentApi<{
  441. /** Add a _foreground_ color for the text that matches */
  442. withColor: X extends "withColor" ? never : (fg: ColorConfigurator) => IFormattingApi<X | "withColor">;
  443. withItalics: () => IFormattingApi<X | "withItalics">;
  444. withUnderline: () => IFormattingApi<X | "withUnderline">;
  445. withStrikethrough: () => IFormattingApi<X | "withStrikethrough">;
  446. /** Add a _background_ color for the text that matches */
  447. withBackground: (bg: ColorConfigurator) => unknown;
  448. }, {
  449. /** provide the _corpus_ of text to search through */
  450. in: (corpus: string) => string;
  451. }, {
  452. config: IFormattingOptions;
  453. }, "withColor" | "withItalics" | "withBackground" | "withStrikethrough" | "withUnderline">;
  454. /**
  455. * Colorize text in the console.
  456. *
  457. * Choose a foreground color and optionally a background color.
  458. */
  459. declare const color: {
  460. red: (text?: string, bg?: ColorConfigurator) => string;
  461. magenta: (text?: string, bg?: ColorConfigurator) => string;
  462. black: (text?: string, bg?: ColorConfigurator) => string;
  463. yellow: (text?: string, bg?: ColorConfigurator) => string;
  464. green: (text?: string, bg?: ColorConfigurator) => string;
  465. brightRed: (text?: string, bg?: ColorConfigurator) => string;
  466. };
  467. /** _italicize_ a block of text */
  468. declare function italicize(text?: string): string;
  469. /** _underline_ a block of text */
  470. declare function underline(text?: string): string;
  471. /** ~strikethrough~ a block of text (not supported on many terminals) */
  472. declare function strikethrough(text?: string): string;
  473. 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 };