@thisisagile/easy
Version:
Straightforward library for building domain-driven microservice architectures
1 lines • 83.1 kB
Source Map (JSON)
{"version":3,"sources":["../src/types/Object.ts","../src/utils/Promise.ts","../src/types/Meta.ts","../src/types/Enum.ts","../src/types/Try.ts","../src/types/Template.ts","../src/types/ToText.ts","../src/types/Exception.ts","../src/validation/When.ts","../src/types/Context.ts","../src/types/Result.ts","../src/types/Results.ts","../src/validation/Validate.ts","../src/types/Case.ts","../src/types/IsEqual.ts","../src/utils/If.ts","../src/types/List.ts"],"sourcesContent":["import { List, toList } from './List';\nimport { ifDefined } from '../utils/If';\n\nexport type Entry<T = unknown> = [key: string, value: T];\n\nexport function entries<T = unknown>(subject: { [p: string]: T } | ArrayLike<T>): List<Entry<T>> {\n return ifDefined(\n subject,\n () => toList<Entry<T>>([...Object.entries(subject), ...Object.entries(Object.getPrototypeOf(subject) ?? {})] as Entry<T>[]),\n () => toList<Entry<T>>()\n );\n}\n\nexport function values<T = unknown>(subject: { [p: string]: T } | ArrayLike<T>): List<T> {\n return toList([...Object.values<T>(subject), ...Object.values<T>(Object.getPrototypeOf(subject) ?? {})]);\n}\n\nexport function keys<T = unknown>(subject: { [p: string]: T } | ArrayLike<T>): List<string> {\n return toList([...Object.keys(subject), ...Object.keys(Object.getPrototypeOf(subject) ?? {})]);\n}\n\nexport function extractKeys<T extends Record<string | number, unknown>, K extends keyof T>(\n obj: T,\n keys: K[] | readonly (keyof T)[]\n): {\n keys: Pick<T, K>;\n} & Omit<T, K> {\n return keys\n .filter((k): k is K => k in obj)\n .reduce(\n (acc, key) => {\n (acc.keys as T)[key] = obj[key];\n delete acc[key];\n return acc;\n },\n { keys: {} as Pick<T, K>, ...obj }\n );\n}\n","import { toArray } from '../types/Array';\nimport { ErrorOrigin } from '../types/ErrorOrigin';\nimport { List, toList } from '../types/List';\nimport { asString } from '../types/Text';\nimport { on, use } from '../types/Constructor';\nimport { keys, values } from '../types/Object';\n\ntype Pro<A> = A | PromiseLike<A>;\ntype Aw<A> = Awaited<A>;\n\nexport const resolve = <S = unknown>(subject: S | PromiseLike<S>): Promise<S> => Promise.resolve(subject);\nexport const reject = <S = never>(e: ErrorOrigin): Promise<S> => Promise.reject(e);\n\nexport const tuple = {\n 2: <F, S>(first: Pro<F>, second: Pro<S>): Promise<[Aw<F>, Aw<S>]> => Promise.all([first, second]),\n 3: <F, S, T>(first: Pro<F>, second: Pro<S>, third: Pro<T>): Promise<[Aw<F>, Aw<S>, Aw<T>]> => Promise.all([first, second, third]),\n 4: <F, S, T, Fo>(first: Pro<F>, second: Pro<S>, third: Pro<T>, forth: Pro<Fo>): Promise<[Aw<F>, Aw<S>, Aw<T>, Aw<Fo>]> =>\n Promise.all([first, second, third, forth]),\n 5: <F, S, T, Fo, Fi>(first: Pro<F>, second: Pro<S>, third: Pro<T>, forth: Pro<Fo>, fifth: Pro<Fi>): Promise<[Aw<F>, Aw<S>, Aw<T>, Aw<Fo>, Aw<Fi>]> =>\n Promise.all([first, second, third, forth, fifth]),\n all: <F, S>(first: Pro<F>, second: Pro<S>[]): Promise<[Aw<F>, Aw<S[]>]> => Promise.all([first, Promise.all(second)]),\n spread: <F, S>(first: Pro<F>, ...second: Pro<S>[]): Promise<[Aw<F>, Aw<S[]>]> => Promise.all([first, Promise.all(toArray(second))]),\n list: <T>(list: Pro<T>[]): Promise<List<Aw<T>>> => Promise.all([...list]).then(toList),\n settled: <T>(list: Pro<T>[]): Promise<{ fulfilled: List<Aw<T>>; rejected: List<string> }> =>\n Promise.allSettled([...list]).then(rs => ({\n fulfilled: toList(...rs.filter(r => r.status === 'fulfilled').map(r => r.value)),\n rejected: toList(...rs.filter(r => r.status === 'rejected').map(r => asString(r.reason))),\n })),\n object: <T extends Record<string, unknown>>(obj: T): Promise<{ [K in keyof T]: Aw<T[K]> }> =>\n use(keys(obj), ks => tuple.list(values(obj)).then(vs => vs.reduce((acc: any, v, i) => on(acc, a => (a[ks[i]] = v)), {}) as { [K in keyof T]: Aw<T[K]> })),\n};\n\nexport const tuple2 = tuple[2];\nexport const tuple3 = tuple[3];\nexport const tuple4 = tuple[4];\nexport const tuple5 = tuple[5];\nexport const tupleO = tuple.object;\nexport const settled = tuple.settled;\n","import 'reflect-metadata';\nimport { List, toList } from './List';\nimport { isDefined } from './Is';\nimport { on, use } from './Constructor';\nimport { Optional } from './Types';\nimport { Entry, entries, values } from './Object';\n\ntype MetaParseOptions = { initial?: any; skipUndefined?: boolean };\n\nclass ClassMeta {\n constructor(\n readonly subject: any,\n private readonly data: any = (subject.prototype ?? subject).constructor\n ) {}\n\n get = <T>(key: string): T => Reflect.getMetadata(key, this.data) as T;\n\n set = <T>(key: string, value: T): T => {\n Reflect.defineMetadata(key, value, this.data);\n return value;\n };\n\n entries = <T = unknown>(): List<Entry<T>> => entries<T>(this.subject);\n\n parse = <Out, Value>(f: (v: Value) => Out, options: MetaParseOptions = {}): Record<string, Out> => {\n const { initial = {}, skipUndefined = false } = options;\n return this.entries<Value>().reduce((a, [k, val]) => use(f(val), v => (isDefined(v) || !skipUndefined ? on(a, a => (a[k] = v)) : a)), initial);\n };\n\n properties = (key?: string): List<PropertyMeta> =>\n toList([...Object.getOwnPropertyNames(this.subject), ...Object.getOwnPropertyNames(Object.getPrototypeOf(this.subject))])\n .map(p => this.property(p))\n .filter(p => (key ? p.get(key) : p));\n\n keys = <T = any>(key: string): List<T> =>\n this.properties()\n .map(p => p.get<T>(key))\n .reduce((list, u) => (u ? list.add(u) : list), toList<T>());\n\n values = <T = unknown>(): List<T> => values<T>(this.subject);\n\n property = (property: string | symbol): PropertyMeta => new PropertyMeta(this.subject, property);\n}\n\nclass PropertyMeta {\n constructor(\n readonly subject: any,\n readonly property: string | symbol,\n private readonly data = Reflect.getMetadata(property, subject)\n ) {}\n\n get value(): any {\n return this.subject[this.property];\n }\n\n get = <T>(key: string): Optional<T> => (isDefined(this.data) && isDefined(this.data[key]) ? (this.data[key] as T) : undefined);\n\n set = <T>(key: string, value: T): T => {\n Reflect.defineMetadata(this.property, { ...this.data, [key]: value }, this.subject);\n return value;\n };\n}\n\nexport const meta = (subject: unknown): ClassMeta => new ClassMeta(subject ?? {});\n","import { Id } from './Id';\nimport { List, toList } from './List';\nimport { isAn } from './IsA';\nimport { meta } from './Meta';\nimport { isDefined, isFunction } from './Is';\nimport { Validatable } from './Validatable';\nimport { JsonValue } from './Json';\nimport { Get, ofGet } from './Get';\nimport { TypeGuard } from './TypeGuard';\n\nexport type EnumConstructor<E = unknown> = {\n all<E extends Enum>(): List<E>;\n byIds<E extends Enum>(ids: Id[]): List<E>;\n byId<E extends Enum>(id: Id, alt?: Get<E, unknown>): E;\n isEnum: boolean;\n};\n\nexport const isEnumConstructor = <E = unknown>(c: unknown): c is EnumConstructor<E> => isFunction(c) && (c as any).isEnum;\n\nexport abstract class Enum implements Validatable {\n static isEnum = true;\n\n protected constructor(\n readonly name: string,\n readonly id: Id = name.toLowerCase(),\n readonly code: string = id.toString()\n ) {}\n\n get isValid(): boolean {\n return isDefined(this.id);\n }\n\n static all<E extends Enum>(): List<E> {\n return meta(this.allTuple<E>()).values<E>();\n }\n\n static filter<E extends Enum>(p: (value: E, index: number, array: E[]) => unknown, params?: unknown): List<E> {\n return this.all<E>().filter(p, params);\n }\n\n static first<E extends Enum>(p?: (value: E, index: number, array: E[]) => unknown, params?: unknown): E {\n return this.all<E>().first(p, params);\n }\n\n static byIds<E extends Enum>(ids: Id[] = []): List<E> {\n return toList(ids)\n .mapDefined(id => this.byId<E>(id))\n .distinct();\n }\n\n static byId<E extends Enum>(id: Id, alt?: Get<E, unknown>): E {\n return this.allTuple<E>()[id] ?? ofGet(alt);\n }\n\n protected static allTuple<E extends Enum>(): Record<Id, E> {\n return meta(this).get(`all-${this.name}`) ?? meta(this).set(`all-${this.name}`, meta(this).values<E>().filter(isEnum).toObject('id'));\n }\n\n equals<E extends Enum>(other: E | Id): other is E {\n return this.id === (isEnum(other) ? other.id : other);\n }\n\n isIn<E extends Enum>(...items: E[] | Id[]): boolean {\n return items.some(i => this.equals(i));\n }\n\n toJSON(): JsonValue {\n return this.id;\n }\n\n toString(): string {\n return this.id.toString();\n }\n}\n\nexport const isEnum: TypeGuard<Enum> = (e?: unknown): e is Enum => isDefined(e) && e instanceof Enum && isAn<Enum>(e, 'name', 'id', 'code');\n","import { isDefined, isEmpty, isTrue } from './Is';\nimport { validate } from '../validation/Validate';\nimport { Construct, Constructor, ofConstruct } from './Constructor';\nimport { Validatable } from './Validatable';\nimport { Get, ofGet } from './Get';\nimport { Func } from './Func';\nimport { Optional } from './Types';\n\nexport abstract class Try<T = unknown> implements Validatable {\n is = {\n defined: (prop?: Func<unknown, T>): Try<T> => this.filter(v => isDefined(prop ? prop(v) : v)),\n empty: (prop?: Func<unknown, T>): Try<T> => this.filter(v => isEmpty(prop ? prop(v) : v)),\n valid: (prop?: Func<unknown, T>): Try<T> => this.filter(v => validate(prop ? prop(v) : v).isValid),\n true: (prop?: Func<unknown, T>): Try<T> => this.filter(v => isTrue(prop ? prop(v) : v)),\n false: (prop?: Func<unknown, T>): Try<T> => this.filter(v => !isTrue(prop ? prop(v) : v)),\n not: {\n defined: (prop?: Func<unknown, T>): Try<T> => this.filter(v => !isDefined(prop ? prop(v) : v)),\n empty: (prop?: Func<unknown, T>): Try<T> => this.filter(v => !isEmpty(prop ? prop(v) : v)),\n valid: (prop?: Func<unknown, T>): Try<T> => this.filter(v => !validate(prop ? prop(v) : v).isValid),\n },\n };\n\n if = this.is;\n\n abstract get value(): T;\n\n abstract get error(): Error;\n\n abstract get isValid(): boolean;\n\n static of = <T>(c: Get<T | Try<T>>, ...args: unknown[]): Try<T> => {\n try {\n const out = ofGet(c, ...args);\n return new Success(out instanceof Try ? out.value : out);\n } catch (e) {\n return new Failure(e as Error);\n }\n };\n\n abstract map<U>(f: Func<U | Try<U>, T>): Try<U>;\n\n abstract recover(f: Func<T | Try<T>, Error>): Try<T>;\n\n abstract recoverFrom(type: Constructor<Error>, f: Func<T | Try<T>, Error>): Try<T>;\n\n abstract accept(f: Func<void, T>): Try<T>;\n\n abstract filter(predicate: Func<boolean, T>): Try<T>;\n\n abstract or(value: Get<T>): T;\n\n abstract orElse(value?: Get<T>): Optional<T>;\n\n abstract orThrow(error: Construct<Error>): T;\n}\n\nclass Success<T> extends Try<T> {\n constructor(readonly value: T) {\n super();\n }\n\n get error(): Error {\n throw new Error('No error found');\n }\n\n get isValid(): boolean {\n return true;\n }\n\n map<U>(f: Func<U | Try<U>, T>): Try<U> {\n return tryTo<U>(f, this.value);\n }\n\n recover(f: Func<T | Try<T>, Error>): Try<T> {\n return this;\n }\n\n recoverFrom(type: Constructor<Error>, f: Func<T | Try<T>, Error>): Try<T> {\n return this;\n }\n\n accept(f: Func<void, T>): Try<T> {\n return tryTo(() => {\n f(this.value);\n return this;\n });\n }\n\n filter(predicate: Func<boolean, T>): Try<T> {\n return tryTo(() => {\n if (predicate(this.value)) return this;\n throw new Error(`Applying filter(${predicate.toString()}) failed.`);\n });\n }\n\n or(value: Get<T>): T {\n return this.value;\n }\n\n orElse(value?: Get<T>): Optional<T> {\n return this.value;\n }\n\n orThrow(_error: Construct<Error>): T {\n return this.value;\n }\n}\n\nclass Failure<T> extends Try<T> {\n constructor(readonly error: Error) {\n super();\n }\n\n get value(): T {\n throw this.error;\n }\n\n get isValid(): boolean {\n return false;\n }\n\n map<U>(f: Func<U | Try<U>, T>): Try<U> {\n return new Failure<U>(this.error);\n }\n\n recover<U>(f: Func<U | Try<U>, Error>): Try<U> {\n return tryTo<U>(f, this.error);\n }\n\n recoverFrom<U>(type: Constructor<Error>, f: Func<T | Try<T>, Error>): Try<T> {\n return tryTo(() => (this.error instanceof type ? this.recover(f) : this));\n }\n\n accept(f: Func<void, T>): Try<T> {\n return this;\n }\n\n filter(predicate: Func<boolean, T>): Try<T> {\n return this;\n }\n\n or(value: Get<T>): T {\n return ofGet(value);\n }\n\n orElse(value?: Get<T>): Optional<T> {\n return ofGet(value);\n }\n\n orThrow(error: Construct<Error>): T {\n throw ofConstruct(error);\n }\n}\n\nexport const tryTo = <T>(c: Get<T | Try<T>>, ...args: unknown[]) => Try.of<T>(c, ...args);\n","import { List, toList } from './List';\nimport { asString, Text } from './Text';\nimport { toName } from './Constructor';\nimport { entries } from './Object';\nimport { text, textValue } from './ToText';\nimport { tryTo } from './Try';\n\nexport type TemplateOptions = { typeof?: Text; property?: Text; actual?: Text; subject?: Text };\n\nexport class Template implements Text {\n private knownPrefixes = new Set(['typeof', 'property', 'actual', 'subject']);\n\n constructor(\n private readonly template: string,\n private readonly subject: unknown = {},\n private readonly options: TemplateOptions = {}\n ) {}\n\n toString = (): string => {\n return entries(this.options)\n .reduce((t, [k]) => this.option(t, k), this.object())\n .replace(' ', ' ');\n };\n\n private readonly props = (tmpl: string, key: string, result: List<string> = toList()): string[] => {\n const i1 = tmpl.indexOf(`{${key}`);\n if (i1 < 0) {\n return result;\n }\n const i2 = tmpl.indexOf('}', i1);\n return this.props(tmpl.slice(i2 + 1), key, result.add(tmpl.substring(i1 + 1, i2)));\n };\n\n private readonly object = (): string =>\n tryTo(() => this.template.replace(/\\{this\\./g, '{'))\n .map(t => t.replace(/\\{([^{}]+)}/g, (match, p) => (this.knownPrefixes.has(p.split('.')[0]) ? match : textValue(this.subject, p))))\n .or('');\n\n private readonly option = (tmpl: string, prop: string): string => {\n return this.props(tmpl, prop).reduce((t: string, p) => t.replace(`{${p}}`, textValue(this.options, p)), tmpl);\n };\n}\n\nexport function template(tmpl: Text, subject: unknown, options: TemplateOptions = {}): Text {\n return new Template(asString(tmpl), subject, {\n typeof: toName(subject),\n subject: text(JSON.stringify(subject)),\n ...options,\n });\n}\n","import { asString, capitalize, replaceAll, Text } from './Text';\nimport { toName } from './Constructor';\nimport { Optional } from './Types';\nimport { Get, ofGet } from './Get';\nimport { isEmpty, isNotEmpty } from './Is';\nimport { List, toList } from './List';\nimport { JsonValue } from './Json';\nimport { template } from './Template';\n\nexport class ToText implements Text {\n constructor(readonly subject: string) {}\n\n get cap(): ToText {\n return this.map(s => capitalize(s?.toLowerCase()));\n }\n\n get capFirst(): ToText {\n return this.map(s => capitalize(s));\n }\n\n get title(): ToText {\n return this.map(s =>\n s\n .split(' ')\n .map(w => text(w).cap)\n .join(' ')\n );\n }\n\n get pascal(): ToText {\n return this.title.replace(' ', '');\n }\n\n get lower(): ToText {\n return this.map(s => s.toLowerCase());\n }\n\n get upper(): ToText {\n return this.map(s => s.toUpperCase());\n }\n\n get camel(): ToText {\n return this.title.trim.map(s => `${s.charAt(0).toLowerCase()}${s.slice(1)}`);\n }\n\n get kebab(): ToText {\n return this.lower.replace(' ', '-');\n }\n\n get strictKebab(): ToText {\n return this.map(s => s.replace(/[^a-z\\d]+/gi, ' ').trim()).kebab;\n }\n\n get slug(): ToText {\n return this.map(s =>\n s\n .replace(/ß/g, 'ss')\n .normalize('NFKD')\n .replace(/[\\u0300-\\u036F]/g, '')\n .toLowerCase()\n .replace(/[^a-z\\d]+/g, '-')\n .replace(/(^-)|(-$)/g, '')\n );\n }\n\n get snake(): ToText {\n return this.upper.replace(' ', '_');\n }\n\n get plural(): ToText {\n return this.ifLike('') ?? this.add('s');\n }\n\n get space(): ToText {\n return this.map(s => s.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]/g, ' '));\n }\n\n get sentence(): ToText {\n return this.isEmpty ? this : this.map(s => `${s.charAt(0).toUpperCase()}${s.slice(1)}.`);\n }\n\n get initials(): ToText {\n return this.map(s =>\n s\n .split(' ')\n .map(w => w[0])\n .join('')\n );\n }\n\n get trim(): ToText {\n return this.map(s => s.replace(/[- ,_#]/g, ''));\n }\n\n get trimSentence(): ToText {\n return this.map(s =>\n s\n .replace(/[\\u200B-\\u200D\\uFEFF]/g, '')\n .replace(/[\\s\\u00A0]+/g, ' ')\n .replace(/\\s+([.,;:!?])/g, '$1')\n .trim()\n );\n }\n\n get isEmpty(): boolean {\n return isEmpty(this.toString());\n }\n\n parse = (subject: unknown, options = {}): ToText => text(template(this.subject, subject, { typeof: toName(subject), ...options }));\n\n is = (...others: unknown[]): boolean => others.some(o => this.toString() === text(o).toString());\n\n equals = this.is;\n\n like = (...others: unknown[]): boolean => others.some(o => this.trim.lower.toString().includes(text(o).trim.lower.toString()));\n\n isLike = (...others: unknown[]): boolean => others.some(o => this.trim.lower.is(text(o).trim.lower));\n\n ifLike = (...others: unknown[]): Optional<this> => (this.isLike(...others) ? this : undefined);\n\n endsWith = (end?: unknown): boolean => this.subject.endsWith(asString(end));\n\n startsWith = (end?: unknown): boolean => this.subject.startsWith(asString(end));\n\n first = (n: number): ToText => this.map(s => s.substring(0, n));\n\n last = (n: number): ToText => this.map(s => s.substring(s.length - n));\n\n map = (func: Get<string, string>): ToText => text(ofGet(func, this.subject));\n\n replace = (search: Text, replace: Text): ToText => this.map(s => replaceAll(s, search, replace));\n\n add = (add?: unknown, separator = ''): ToText => this.map(s => (isNotEmpty(add) ? `${s}${separator}${text(add)}` : s));\n\n with = (separator: string, ...other: unknown[]): ToText =>\n this.map(s =>\n toList(s)\n .add(...other.map(u => text(u).toString()))\n .filter(s => isNotEmpty(s))\n .join(separator)\n );\n\n split = (separator: string = ' '): List<string> => toList(this.subject.split(separator));\n\n toString(): string {\n return this.subject;\n }\n\n toJSON(): JsonValue {\n return this.subject;\n }\n}\n\nexport function text(subject?: unknown, alt = ''): ToText {\n const sub = subject ? asString(subject) : alt;\n return new ToText(sub !== '[object Object]' ? sub : '');\n}\n\nexport function textValue(subject: any, prop: string): string {\n const p = prop.split('.');\n const root = subject?.[p[0]];\n const initial = typeof root === 'object' && root !== null ? root : text(root);\n return (\n p\n .splice(1)\n .reduce((t, s) => (typeof t === 'object' && t !== null ? t : text(t))?.[s], initial)\n ?.toString() ?? ''\n );\n}\n","import { asString, Text } from './Text';\nimport { Enum } from './Enum';\nimport { isDefined } from './Is';\nimport { Id } from './Id';\n\nimport { text } from './ToText';\n\nexport class Exception extends Enum {\n static readonly AlreadyExists = new Exception('Subject already exists');\n static readonly DoesNotExist = new Exception('Does not exist');\n static readonly IsMissingId = new Exception('Subject is missing an id');\n static readonly IsNotImplemented = new Exception('Is not implemented');\n static readonly IsNotValid = new Exception('Is not valid');\n static readonly Unknown = new Exception('Unknown error');\n\n constructor(\n readonly message: string,\n id?: Id,\n readonly reason?: Text\n ) {\n super(message, id ?? text(message).pascal.toString());\n }\n\n static readonly CouldNotExecute = (target: Text): Exception => new Exception(`Could not execute ${target}.`, 'CouldNotExecute');\n\n static readonly CouldNotValidate = (target: Text): Exception => new Exception(`Could not validate ${target}.`, 'CouldNotValidate');\n\n static readonly EnvironmentVariableNotFound = (variable: Text): Exception =>\n new Exception(`Environment variable ${text(variable).upper} could not be found.`, 'EnvironmentVariableNotFound');\n\n because = (reason: Text): Exception => new Exception(this.message, this.id, reason);\n}\n\nexport const isException = (e?: unknown, t?: Text): e is Exception => e instanceof Exception && (isDefined(t) ? e.equals(asString(t)) : true);\nexport const isDoesNotExist = (e?: unknown): e is Exception => e instanceof Exception && Exception.DoesNotExist.equals(e);\n","import { validate } from './Validate';\nimport { Results } from '../types/Results';\nimport { Constructor } from '../types/Constructor';\nimport { Get, ofGet, Predicate } from '../types/Get';\nimport { isDefined, isEmpty, isIn } from '../types/Is';\nimport { toArray } from '../types/Array';\nimport { ErrorOrigin } from '../types/ErrorOrigin';\nimport { reject, resolve } from '../utils/Promise';\nimport { Exception } from '../types/Exception';\n\nexport class When<W> {\n constructor(\n readonly subject: W,\n readonly valid = true,\n private results?: Results\n ) {}\n\n get not(): When<W> {\n return this.clone(!this.valid);\n }\n\n get and(): When<W> {\n return this.clone(this.valid);\n }\n\n get isDefined(): When<W> {\n return this.clone(this.valid === isDefined(this.subject));\n }\n\n get isEmpty(): When<W> {\n return this.clone(this.valid === isEmpty(this.subject));\n }\n\n get isTrue(): When<W> {\n return this.clone(this.valid === !!this.subject);\n }\n\n get isValid(): When<W> {\n this.results = validate(this.subject);\n return this.clone(this.valid === this.results.isValid);\n }\n\n isInstance = <U>(c: Constructor<U>): When<W> => this.clone(this.valid === this.subject instanceof c);\n\n with = (pred: Predicate<W>): When<W> => this.clone(this.valid === ofGet(pred, this.subject));\n\n contains = (property: (w: W) => unknown): When<W> => this.clone(this.valid === isDefined(ofGet(property, this.subject)));\n\n in = (...items: W[]): When<W> => this.clone(this.valid === isIn(this.subject, toArray(...items)));\n\n is = (item: W): When<W> => this.clone(this.valid === (this.subject === item));\n\n reject = (error?: Get<ErrorOrigin, W>): Promise<NonNullable<W>> =>\n !this.valid ? resolve(this.subject as NonNullable<W>) : reject(ofGet(error, this.subject) ?? this.results ?? Exception.Unknown);\n\n recover = (f: (item: W) => W | Promise<W>): Promise<W> => resolve(!this.valid ? this.subject : f(this.subject));\n\n protected clone = (result = true): When<W> => new When(this.subject, result, this.results);\n}\n\nexport const when = <T>(subject: T): When<T> => new When<T>(subject);\n","import { Uuid } from './Uuid';\nimport { Identity } from './Identity';\nimport { Optional } from './Types';\n\nimport { text } from './ToText';\n\nexport interface EnvContext {\n readonly domain: string;\n readonly name: string;\n readonly host: string;\n readonly port: number;\n readonly app: string;\n\n get(key: string, alt?: string): Optional<string>;\n}\n\nexport class DotEnvContext implements EnvContext {\n readonly domain = process.env.DOMAIN ?? 'easy';\n readonly name = process.env.ENVIRONMENT_NAME ?? '';\n readonly host = process.env.HOST ?? '';\n readonly port = Number.parseInt(process.env.PORT ?? '8080');\n readonly app = process.env.APP ?? '';\n\n readonly get = (key: string, alt?: string): Optional<string> => {\n const k = text(key)\n .map(k => k.replace(/([a-z])([A-Z])/g, '$1 $2'))\n .snake.toString();\n return process.env[k] ?? alt;\n };\n}\n\nexport interface RequestContext {\n token?: any;\n identity?: Identity;\n jwt: string;\n correlationId?: Uuid;\n lastError?: string;\n lastErrorStack?: string;\n create: (f: () => void) => void;\n\n get<T>(key: string): T;\n\n set<T>(key: string, value: T): T;\n\n wrap<T>(f: () => Promise<T>): Promise<T>;\n}\n\nexport class BaseRequestContext implements RequestContext {\n private state: any = {};\n\n get token(): any {\n return this.get('token');\n }\n\n set token(token: any) {\n this.set('token', token);\n }\n\n get identity(): Identity {\n return this.token as Identity;\n }\n\n get jwt(): string {\n return this.get('jwt');\n }\n\n set jwt(jwt: string) {\n this.set('jwt', jwt);\n }\n\n get correlationId(): Uuid {\n return this.get('correlationId');\n }\n\n set correlationId(id: Uuid) {\n this.set('correlationId', id);\n }\n\n get lastError(): Optional<string> {\n return this.get('lastError');\n }\n\n set lastError(error: Optional<string>) {\n this.set('lastError', error);\n }\n\n public get<T>(key: string): T {\n return this.state[key] as T;\n }\n\n public set<T>(key: string, value: T): T {\n return (this.state[key] = value);\n }\n\n public readonly create = (f: () => void): void => f();\n\n public readonly wrap = <T>(f: () => Promise<T>): Promise<T> => f();\n}\n\n/**\n * @deprecated Renamed to BaseRequestContext\n */\nexport class BaseContext extends BaseRequestContext {}\n\nexport interface Contexts {\n env?: EnvContext;\n request?: RequestContext;\n other?: any;\n}\n\nexport class Context {\n constructor(protected state: Contexts = {}) {\n this.state = {\n ...{\n env: new DotEnvContext(),\n request: new BaseRequestContext(),\n other: {},\n },\n ...this.state,\n };\n }\n\n get env(): EnvContext {\n return this.state.env as EnvContext;\n }\n\n set env(env: EnvContext) {\n this.state.env = env;\n }\n\n get request(): RequestContext {\n return this.state.request as RequestContext;\n }\n\n set request(request: RequestContext) {\n this.state.request = request;\n }\n\n get other(): any {\n return this.state.other;\n }\n}\n\nexport const ctx = new Context();\n","import { isA } from './IsA';\nimport { Text } from './Text';\nimport { ctx } from './Context';\nimport { TypeGuard } from './TypeGuard';\n\nexport type Result = { message: string; location?: string; domain?: string };\n\nexport const toResult = (message: Text, location?: Text, domain: Text = ctx.env.domain): Result => ({\n message: message.toString(),\n location: location?.toString(),\n domain: domain?.toString(),\n});\n\nexport const isResult: TypeGuard<Result> = (r?: unknown): r is Result => isA<Result>(r, 'message');\n","import { Text } from './Text';\nimport { isResult, Result, toResult } from './Result';\nimport { Validatable } from './Validatable';\nimport { isDefined } from './Is';\nimport { toArray } from './Array';\n\nconst parse = (...rs: (Text | Result)[]): Result[] => toArray(...rs).map(r => (isResult(r) ? r : toResult(r)));\n\nexport class Results implements Validatable {\n public readonly results: Result[];\n\n constructor(...rs: (Text | Result)[]) {\n this.results = parse(...rs);\n }\n\n get length(): number {\n return this.results.length;\n }\n\n get isValid(): boolean {\n return this.results.length === 0;\n }\n\n add = (...rs: (Text | Result)[]): Results => toResults(...this.results, ...parse(...rs));\n}\n\nexport const toResults = (...r: (Text | Result)[]): Results => new Results(...r);\n\nexport const isResults = (r?: unknown): r is Results => isDefined(r) && r instanceof Results;\n","import { Constraint } from './Contraints';\nimport { when } from './When';\nimport type { TemplateOptions } from '../types/Template';\nimport { isResults, Results, toResults } from '../types/Results';\nimport { toName } from '../types/Constructor';\nimport { toResult } from '../types/Result';\nimport { List, toList } from '../types/List';\nimport { meta } from '../types/Meta';\nimport { isArray, isFunction } from '../types/Is';\nimport type { Text } from '../types/Text';\nimport { asString } from '../types/Text';\nimport { choose } from '../types/Case';\nimport { isEnum } from '../types/Enum';\nimport { isValue } from '../types/Value';\nimport { isValidatable } from '../types/Validatable';\nimport { text } from '../types/ToText';\n\nexport type Validator = { property: string | symbol; constraint: Constraint; text: Text; actual?: Text };\n\nexport const asResults = (subject: unknown, template: Text, options: TemplateOptions = {}): Results =>\n toResults(toResult(text(template).parse(subject, options), toName(subject)));\n\nconst validators = (subject: unknown): List<Validator> =>\n meta(subject)\n .keys<List<Validator>>('constraint')\n .reduce((list, vs) => list.add(vs), toList<Validator>());\n\nconst runValidator = (v: Validator, subject?: unknown): Results => {\n try {\n const actual = isFunction((subject as any)[v.property]) ? (subject as any)[v.property]() : (subject as any)[v.property];\n const constraint = v.constraint(actual);\n return isResults(constraint)\n ? constraint\n : !constraint\n ? asResults(subject, v.text, {\n ...v,\n actual,\n })\n : toResults();\n } catch (e) {\n return asResults(subject, asString(e));\n }\n};\n\nconst constraints = (subject?: unknown): Results =>\n validators(subject)\n .map(vs => runValidator(vs, subject))\n .reduce((rs, r) => rs.add(...r.results), toResults());\n\nexport const validate = (subject?: unknown): Results =>\n choose(subject)\n .is.not.defined(\n s => s,\n () => toResults('Subject is not defined.')\n )\n .type(isEnum, e => (e.isValid ? toResults() : asResults(e, 'This is not a valid {typeof}.')))\n .type(isValue, v => (v.isValid ? toResults() : asResults(v, 'This is not a valid {typeof}.')))\n .type(isArray, a => a.map(i => validate(i)).reduce((rs, r) => rs.add(...r.results), toResults()))\n .type(isValidatable, v => constraints(v))\n .else(toResults());\n\nexport const validateReject = <T>(subject: T): Promise<T> => when(subject).not.isValid.reject();\n\nexport const isValid = <T>(t: T): boolean => validate(t).isValid;\n","import { Get, ofGet, Predicate } from './Get';\nimport { TypeGuard } from './TypeGuard';\nimport { Func } from './Func';\nimport { isDefined, isEmpty } from './Is';\nimport { validate } from '../validation/Validate';\nimport { tryTo } from './Try';\n\nclass CaseBuilder<V> {\n is = {\n true: <T>(pred: Predicate<V>, out: Get<T, V>): Case<T, V> => this.case(pred, out),\n false: <T>(pred: Predicate<V>, out: Get<T, V>): Case<T, V> => this.case(!ofGet(pred, this.v), out),\n truthy: <T>(prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(!!prop(this.v), out),\n falsy: <T>(prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(!prop(this.v), out),\n defined: <T>(prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(isDefined(prop(this.v)), out),\n empty: <T>(prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(isEmpty(prop(this.v)), out),\n valid: <T>(prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(validate(prop(this.v)).isValid, out),\n in: <T>(prop: Get<Array<V>, V>, out: Get<T, V>): Case<T, V> => this.case(ofGet(prop, this.v).includes(this.v), out),\n type: <T, U = unknown>(guard: TypeGuard<U>, out: Func<T, U>): Case<T, V> => this.type<T, U>(guard, out),\n not: {\n true: <T>(pred: Predicate<V>, out: Get<T, V>): Case<T, V> => this.case(!ofGet(pred, this.v), out),\n false: <T>(pred: Predicate<V>, out: Get<T, V>): Case<T, V> => this.case(pred, out),\n truthy: <T>(prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(!prop(this.v), out),\n falsy: <T>(prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(!!prop(this.v), out),\n defined: <T>(prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(!isDefined(prop(this.v)), out),\n empty: <T>(prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(!isEmpty(prop(this.v)), out),\n valid: <T>(prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(!validate(prop(this.v)).isValid, out),\n in: <T>(prop: Get<Array<V>, V>, out: Get<T, V>): Case<T, V> => this.case(!ofGet(prop, this.v).includes(this.v), out),\n type: <T, U = unknown>(guard: TypeGuard<U>, out: Get<T, V>): Case<T, V> => this.case(v => !guard(v as unknown), out),\n },\n };\n if = this.is;\n\n constructor(readonly v: V) {}\n\n case<T>(pred: Predicate<V>, out: Get<T, V>): Case<T, V> {\n return new Case<T, V>(this.v).case(pred, out);\n }\n\n type<T, U = unknown>(guard: TypeGuard<U>, out: Func<T, U>): Case<T, V> {\n return new Case<T, V>(this.v).type<U>(guard, out);\n }\n\n equals<T>(value: V, out: Get<T, V>): Case<T, V> {\n return new Case<T, V>(this.v).equals(value, out);\n }\n}\n\nclass Case<T, V = unknown> {\n is = {\n true: (pred: Predicate<V>, out: Get<T, V>): Case<T, V> => this.case(pred, out),\n false: (pred: Predicate<V>, out: Get<T, V>): Case<T, V> => this.case(!ofGet(pred, this.value), out),\n truthy: (prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(!!prop(this.value), out),\n falsy: (prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(!prop(this.value), out),\n defined: (prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(isDefined(prop(this.value)), out),\n empty: (prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(isEmpty(prop(this.value)), out),\n valid: (prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(validate(prop(this.value)).isValid, out),\n in: (prop: Get<Array<V>, V>, out: Get<T, V>): Case<T, V> => this.case(ofGet(prop, this.value).includes(this.value), out),\n type: <U>(guard: TypeGuard<U>, out: Func<T, U>): Case<T, V> => this.type<U>(guard, out),\n not: {\n true: (pred: Predicate<V>, out: Get<T, V>): Case<T, V> => this.case(!ofGet(pred, this.value), out),\n false: (pred: Predicate<V>, out: Get<T, V>): Case<T, V> => this.case(pred, out),\n truthy: (prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(!prop(this.value), out),\n falsy: (prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(!!prop(this.value), out),\n defined: (prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(!isDefined(prop(this.value)), out),\n empty: (prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(!isEmpty(prop(this.value)), out),\n valid: (prop: Func<unknown, V>, out: Get<T, V>): Case<T, V> => this.case(!validate(prop(this.value)).isValid, out),\n in: (prop: Get<Array<V>, V>, out: Get<T, V>): Case<T, V> => this.case(!ofGet(prop, this.value).includes(this.value), out),\n type: <U>(guard: TypeGuard<U>, out: Get<T, V>): Case<T, V> => this.case(v => !guard(v as unknown), out),\n },\n };\n if = this.is;\n\n constructor(\n protected value: V,\n protected outcome?: T\n ) {}\n\n case(pred: Predicate<V>, out: Get<T, V>): Case<T, V> {\n return tryTo(pred, this.value)\n .is.true()\n .map(() => ofGet(out, this.value))\n .map(res => new Found(this.value, res) as Case<T, V>)\n .or(this);\n }\n\n type<U>(guard: TypeGuard<U>, out: Func<T, U>): Case<T, V> {\n return tryTo(guard, this.value)\n .is.true()\n .map(() => out(this.value as unknown as U))\n .map(res => new Found(this.value, res) as Case<T, V>)\n .or(this);\n }\n\n equals(value: V, out: Get<T, V>): Case<T, V> {\n return this.case(this.value === value, out);\n }\n\n else(alt: Get<T, V>): T {\n return ofGet<T, V>(alt, this.value);\n }\n}\n\nclass Found<T, V> extends Case<T, V> {\n constructor(\n protected value: V,\n protected outcome: T\n ) {\n super(value, outcome);\n }\n\n case(pred: Predicate<V>, out: Get<T, V>): this {\n return this;\n }\n\n type<U>(guard: TypeGuard<U>, out: Func<T, U>): Case<T, V> {\n return this;\n }\n\n equals(value: V, out: Get<T, V>): Case<T, V> {\n return this;\n }\n\n else(alt: Get<T, V>): T {\n return this.outcome;\n }\n}\n\nexport const choose = <V>(value: V) => new CaseBuilder<V>(value);\n","import { isArray, isObject } from './Is';\nimport { choose } from './Case';\n\nconst isEqualArray = (one: unknown[], another: unknown[]): boolean =>\n choose([one, another])\n .case(([o, a]) => !isArray(o) || !isArray(a), false)\n .case(([o, a]) => o?.length !== a?.length, false)\n .else(([o, a]) => !o.some((v, i) => !isEqual(v, a[i])));\n\nconst isEqualObject = (one: any, another: any): boolean =>\n choose([Object.keys(one), Object.keys(another)])\n .case(([keysO, keysA]) => keysO.length !== keysA.length, false)\n .case(([keysO, keysA]) => keysO.some(k => !keysA.includes(k)), false)\n .case(([keysO]) => keysO.some(k => !isEqual(one[k], another[k])), false)\n .else(true);\n\nexport const isEqual = (one?: unknown, another?: unknown): boolean =>\n choose([one, another])\n .case(([o, a]) => o === a, true)\n .case(\n ([o, a]) => isArray(o) || isArray(a),\n ([o, a]) => isEqualArray(o as [], a as [])\n )\n .case(\n ([o, a]) => o == null || a == null || (!isObject(o) && !isObject(a)),\n ([o, a]) => o !== o && a !== a\n )\n .else(([o, a]) => isEqualObject(o, a));\n","import { isDefined, isNotEmpty, isPresent, isTrue } from '../types/Is';\nimport { Optional } from '../types/Types';\nimport { Construct, ofConstruct, use } from '../types/Constructor';\nimport { OneOrMore } from '../types/Array';\nimport { toList } from '../types/List';\nimport { isEqual } from '../types/IsEqual';\n\nexport function ifTrue<Out, In = unknown>(o: unknown, f: Construct<Out, NonNullable<In>>, alt: Construct<Out>): Out;\nexport function ifTrue<Out, In = unknown>(o: unknown, f: Construct<Out, NonNullable<In>>, alt?: Construct<Out>): Optional<Out>;\nexport function ifTrue<Out, In = unknown>(o: unknown, f: Construct<Out, NonNullable<In>>, alt?: Construct<Out>): Optional<Out> {\n return isTrue(o) ? ofConstruct(f, o) : ofConstruct(alt, o);\n}\n\nexport function ifFalse<Out, In = unknown>(o: unknown, f: Construct<Out, NonNullable<In>>, alt: Construct<Out>): Out;\nexport function ifFalse<Out, In = unknown>(o: unknown, f: Construct<Out, NonNullable<In>>, alt?: Construct<Out>): Optional<Out>;\nexport function ifFalse<Out, In = unknown>(o: unknown, f: Construct<Out, NonNullable<In>>, alt?: Construct<Out>): Optional<Out> {\n return !isTrue(o) ? ofConstruct(f, o) : ofConstruct(alt, o);\n}\n\nexport function ifDefined<Out, In = unknown>(o: Optional<In>, f: Construct<Out, NonNullable<In>>, alt: Construct<Out>): Out;\nexport function ifDefined<Out, In = unknown>(o: Optional<In>, f: Construct<Out, NonNullable<In>>, alt?: Construct<Out>): Optional<Out>;\nexport function ifDefined<Out, In = unknown>(o: Optional<In>, f: Construct<Out, NonNullable<In>>, alt?: Construct<Out>): Optional<Out> {\n return isDefined(o) ? ofConstruct(f, o) : ofConstruct(alt);\n}\n\nexport function ifNotEmpty<Out, In = unknown>(o: In, f: Construct<Out, NonNullable<In>>, alt: Construct<Out>): Out;\nexport function ifNotEmpty<Out, In = unknown>(o: In, f?: Construct<Out, NonNullable<In>>, alt?: Construct<Out>): Optional<Out>;\nexport function ifNotEmpty<Out, In = unknown>(o: In, f: Construct<Out, NonNullable<In>>, alt?: Construct<Out>): Optional<Out>;\nexport function ifNotEmpty<Out, In = unknown>(o: In, f: Construct<Out, NonNullable<In>> = o => o as Out, alt?: Construct<Out>): Optional<Out> {\n return isNotEmpty(o) ? ofConstruct(f, o) : ofConstruct(alt, o);\n}\n\nexport function ifEqual<Out>(one: unknown, another: unknown, f: Construct<Out>, alt: Construct<Out>): Out;\nexport function ifEqual<Out>(one: unknown, another: unknown, f: Construct<Out>, alt?: Construct<Out>): Optional<Out>;\nexport function ifEqual<Out>(one: unknown, another: unknown, f: Construct<Out>, alt?: Construct<Out>): Optional<Out> {\n return isEqual(one, another) ? ofConstruct(f) : ofConstruct(alt);\n}\n\nexport function ifEither<Out, In = unknown>(os: OneOrMore<In>, f: Construct<Out, NonNullable<In>>, alt: Construct<Out>): Out;\nexport function ifEither<Out, In = unknown>(os: OneOrMore<In>, f?: Construct<Out, NonNullable<In>>, alt?: Construct<Out>): Optional<Out>;\nexport function ifEither<Out, In = unknown>(os: OneOrMore<In>, f: Construct<Out, NonNullable<In>>, alt?: Construct<Out>): Optional<Out>;\nexport function ifEither<Out, In = unknown>(os: OneOrMore<In>, f: Construct<Out, NonNullable<In>> = o => o as Out, alt?: Construct<Out>): Optional<Out> {\n return use(\n toList(os).first(o => isPresent(o)),\n o => (isDefined(o) ? ofConstruct(f, o) : ofConstruct(alt, o))\n );\n}\n","import { ArrayLike, toArray } from './Array';\nimport { Constructor, on, use } from './Constructor';\nimport type { Json } from './Json';\nimport { isArray, isDefined, isEmpty } from './Is';\nimport { isA } from './IsA';\nimport { Get, GetProperty, ofGet, ofProperty } from './Get';\nimport type { Id } from './Id';\nimport { equals } from './Text';\nimport { Optional } from './Types';\nimport { ifDefined, ifTrue } from '../utils/If';\nimport { AnyKey } from './AnyKey';\nimport { traverse } from '../utils/Traverse';\nimport { Indexed } from './Indexed';\n\ntype Pred<T> = (value: T, index: number, obj: T[]) => unknown;\n\nexport class List<T = unknown> extends Array<T> {\n get ids(): List<Id> {\n return this.mapDefined(i => (i as any).id as Id);\n }\n\n get indexed(): List<Indexed<T>> {\n return this.map((v, index) => ({ ...v, index }));\n }\n\n isSubSetOf(...items: ArrayLike<T>): boolean {\n return this.diff(items).length === 0;\n }\n\n isSuperSetOf(...items: ArrayLike<T>): boolean {\n return this.length > items.length && toList(...items).isSubSetOf(...this);\n }\n\n isIntersectingWith(...items: ArrayLike<T>): boolean {\n return this.intersect(items).length > 0;\n }\n\n isDisjointWith(...items: ArrayLike<T>): boolean {\n return !this.isIntersectingWith(...items);\n }\n\n areEqual(...items: ArrayLike<T>): boolean {\n return this.isSubSetOf(...items) && toList(...items).isSubSetOf(...this);\n }\n\n asc(p: GetProperty<T, any>): List<T> {\n return toList<T>(...this).sort((e1, e2) => (ofProperty(e1, p) > ofProperty(e2, p) ? 1 : -1));\n }\n\n desc(p: GetProperty<T, any>): List<T> {\n return toList<T>(...this).sort((e1, e2) => (ofProperty(e1, p) < ofProperty(e2, p) ? 1 : -1));\n }\n\n first(p?: Pred<T>, params?: unknown): T {\n return (p ? this.find(p, params) : this[0]) as T;\n }\n\n firstValue<V>(f: (t: T) => V, alt?: Get<V, T>): Optional<V> {\n return ifDefined(\n this.first(t => !!f(t)),\n f,\n v => ofGet(alt, v)\n );\n }\n\n isFirst(value: T): boolean {\n return value === this.first();\n }\n\n next(p?: Pred<T>, params?: unknown): T {\n return p ? this[this.findIndex(p, params) + 1] : this[0];\n }\n\n prev(p?: Pred<T>, params?: unknown): T {\n return p ? this[this.findIndex(p, params) - 1] : this[0];\n }\n\n last(p?: Pred<T>, params?: unknown): T {\n return p ? this.filter(p, params).last() : this[this.length - 1];\n }\n\n isLast(value: T): boolean {\n return value === this.last();\n }\n\n overlaps(...items: ArrayLike<T>): boolean {\n return toList<T>(...items).some(i => this.some(t => i === t));\n }\n\n diff(others: ArrayLike<T>): List<T> {\n return this.filter(i => !others.includes(i));\n }\n\n diffByKey<U = T>(others: ArrayLike<U>, key: keyof T & keyof U): List<T> {\n return this.filter((i: any) => !others.some((o: any) => o[key] === i[key]));\n }\n\n symmetricDiff(others: ArrayLike<T>): List<T> {\n return this.diff(others).concat(toList<T>(...others).diff(this));\n }\n\n symmetricDiffByKey(others: ArrayLike<T>, key: keyof T): List<T> {\n return this.diffByKey(others, key).concat(toList<T>(...others).diffByKey(this, key));\n }\n\n intersect(others: ArrayLike<T>): List<T> {\n return this.filter(i => others.includes(i));\n }\n\n intersectByKey<U>(others: ArrayLike<U>, key: keyof T & keyof U): List<T> {\n return this.filter((i: any) => others.some((o: any) => o[key] === i[key]));\n }\n\n intersectBy<U>(others: ArrayLike<U>, f: (value: T, value2: U) => boolean): List<T> {\n return this.filter(i => others.some(o => f(i, o as U)));\n }\n\n accumulate(...keys: (keyof T)[]): List<T> {\n return this.map((d, i, arr) => {\n const acc = keys.reduce((acc, v) => {\n (acc as any)[v] = i === 0 ? d[v] : (arr[i - 1][v] as number) + (d[v] as number);\n return acc;\n }, d);\n arr[i] = acc;\n return acc;\n });\n }\n\n toJSON(): Json[] {\n return this.reduce((a, i) => {\n a.push(JSON.parse(JSON.stringify(i ?? {})));\n return a;\n }, new Array<Json>());\n }\n\n map<U>(f: (value: T, index: number, array: T[]) => U, params?: unknown): List<U> {\n return toList<U>(super.map(f, params));\n }\n\n flatMap<U, This = unknown>(f: (this: This, value: T, index: number, array: T[]) => ReadonlyArray<U> | U, params?: This): List<U> {\n return toList<U>(super.flatMap(f, params));\n }\n\n mapDefined<U>(f: (value: T, index: number, array: T[]) => U, params?: unknown): List<NonNullable<U>> {\n return this.map(f, params).defined();\n }\n\n mapAsync(f: (i: T) => Promise<T>): Promise<List<T>> {\n return Promise.all(super.map(e => f(e))).then(a => toList<T>(a));\n }\n\n mapSerial<U>(f: (i: T) => Promise<U>): Promise<List<U>> {\n return super.reduce((p, item) => p.then(results => on(results, async r => r.push(await f(item)))), Promise.resolve(toList<U>()));\n }\n\n distinct(): List<T> {\n return this.filter((i, index) => this.indexOf(i) === index);\n }\n\n distinctByKey(key: keyof T): List<T> {\n const seen = new Set<T[keyof T]>();\n return this.filter(item => !seen.has(item[key]) && seen.add(item[key]));\n }\n\n distinctByValue(): List<T> {\n const seen = new Set<string>();\n return this.filter(item => !seen.has(JSON.stringify(item)) && seen.add(JSON.stringify(item)));\n }\n\n filter(p: Pred<T>, params?: unknown): List<T> {\n return toList<T>(super.filter(p, params));\n }\n\n sum(p: (t: T) => number): number {\n return this.reduce((sum: number, i) => sum + p(i), 0);\n }\n\n max(p: (value: T) => any): T;\n\n max(key: keyof T): T;\n\n max(p: keyof T | ((value: T) => any)): T {\n return this.desc(p).first();\n }\n\n min(key: keyof T): T;\n\n min(p: (value: T) => any): T;\n\n min(p: keyof T | ((value: T) => any)): T {\n return this.asc(p).first();\n }\n\n byId(id: Id): T {\n return this.first(i => equals((i as any).id, id));\n }\n\n byKey(key: keyof T, value: unknown): T {\n return this.first(i => i[key] == value);\n }\n\n add(...items: ArrayLike<T>): this {\n super.push(...toArray(...items));\n return this;\n }\n\n concat(...items: ConcatArray<T>[]): List<T>;\n\n concat(...items: (T | ConcatArray<T>)[]): List<T>;\n\n concat(...items: (T | ConcatArray<T>)[]): List<T> {\n return toList<T>(super.concat(...items));\n }\n\n reverse(): List<T> {\n return toList<T>(super.reverse());\n }\n\n splice(start: number, deleteCount?: number): List<T>;\n\n splice(start: number, deleteCount: number, ...items: T[]): List<T>;\n\n splice(start: number, deleteCount: number, ...items: T[]): List<T> {\n return toList<T>(super.splice(start, deleteCount, ...items));\n }\n\n remove(item: T): List<T> {\n const index = this.indexOf(item);\n if (index > -1) {\n this.splice(index, 1);\n }\n return this;\n }\n\n move(sourceId: Id, destinationId: Id): List<T> {\n return this.moveOn('id' as keyof T, sourceId, destinationId);\n }\n\n moveOn(key: keyof T, sourceId: Id, destinationId: Id): List<T> {\n const source = this.findIndex(i => equals(i[key], sourceId));\n const dest = this.findIndex(i => equals(i[key], destinationId));\n return on(toList<T>(...this), r => r.splice(dest, 0, ...r.splice(source, 1)));\n }\n\n replace(key: keyof T, item: T): List<T> {\n const index = this.findIndex(i => i[key] === item?.[key]);\n ifTrue(index != -1, () => this.splice(index, 1, item));\n return this;\n }\n\n switch(item: T): List<T> {\n return this.includes(item) ? this.remove(item) : this.add(item);\n }\n\n switchOn<U = T>(item: U, on: AnyKey<U>): List<T>;\n\n switchOn<T>(item: T, on: Pred<T>): List<T>;\n\n switchOn<U = T>(item: T, on: AnyKey<U> | Pred<T>): List<T> {\n return use(typeof on === 'function' ? this.find(on) : use(traverse(item, on), v => this.find(i => traverse(i, on) === v)), i =>\n i ? this.remove(i) : this.add(item)\n );\n }\n\n defined(): List<NonNullable<T>> {\n return this.reduce((l, v) => (isDefined(v) ? l.add(v) : l), toList<NonNullable<T>>());\n }\n\n toObject(key: keyof T, options: { deleteKey?: boolean } = {}): Record<string | number | symbol, T> {\n return this.reduce((o: any, i) => {\n o[i[key]] = i;\n if (options.deleteKey) delete o[i[key]][key];\n return o;\n }, {});\n }\n\n toObjectList(key: keyof T): Record<string | number | symbol, List<T>> {\n return this.reduce(\n (a, t) => {\n const k = t[key] as unknown as string | number | symbol;\n a[k] = a[k] ?? toList();\n a[k].push(t);\n return a;\n },\n {} as Record<string | number | symbol, List<T>>\n );\n }\n\n orElse(...alt: ArrayLike<T>): Optional<List<T>> {\n return !isEmpty(this) ? this : !isEmpty(...alt) ? toList<T>(...alt) : undefined;\n }\n\n weave(insertFrom: T[], interval: number): this {\n for (let i = interval, n = 0; i <= this.length && n < insertFrom.length; i += int