import { F as FactoryFunction, b as UnitConstructor, c as UnitDependencies, I as Index, M as Matrix$1 } from './index-B4LIOfHN.js'; export { B as BaseUnitDef, d as BigNumber, e as BigNumberConstructor, C as Complex, f as ComplexConstructor, g as ComplexValue, h as ConverterFn, U as CoreUnit, j as CreateFunction, k as CreateUnitDefObject, l as CreateUnitOptions, D as DenseMatrix, m as DependencyName, n as FactoryMeta, o as Fraction, p as FractionConstructor, q as FractionValue, r as IndexDimension, L as LegacyFactory, N as Numeric, P as ParseOptions, s as PrefixDef, t as PrefixTable, R as Range, S as ScalarBinaryOp, u as ScalarUnaryOp, v as SparseMatrix, w as SubtractScalar, T as TypeConverters, x as Unit, y as UnitComponent, z as UnitConfig, A as UnitDef, E as UnitFormatOptions, a as UnitInstance, G as UnitJSON, H as UnitSystem, J as UnitSystemEntry, K as assertDependencies, O as create, Q as factory, V as isArray, W as isBigInt, X as isBigNumber, Y as isBoolean, Z as isCollection, _ as isComplex, $ as isDate, a0 as isDenseMatrix, a1 as isFactory, a2 as isFraction, a3 as isFunction, a4 as isIndex, a5 as isMap, a6 as isMatrix, a7 as isNull, a8 as isNumber, a9 as isObject, aa as isOptionalDependency, ab as isRange, ac as isRegExp, ad as isSparseMatrix, ae as isString, af as isUndefined, i as isUnit, ag as sortFactories, ah as stripOptionalNotation, ai as typeOf } from './index-B4LIOfHN.js'; declare const createUnitClass: FactoryFunction; /** The full dependency bundle for `createUnitClass`. */ declare const unitDependencies: UnitDependencies; /** * Split value representation with sign, coefficients, and exponent */ interface SplitValue { sign: '+' | '-' | ''; coefficients: number[]; exponent: number; } /** * Configuration for number type handling */ interface NumberTypeConfig { number: 'number' | 'BigNumber' | 'bigint' | 'Fraction'; numberFallback: 'number' | 'BigNumber'; } /** * Format options for number formatting */ interface FormatOptions { notation?: 'auto' | 'exponential' | 'fixed' | 'engineering' | 'bin' | 'oct' | 'hex'; precision?: number; wordSize?: number; lowerExp?: number; upperExp?: number; } /** * Normalized format options */ interface NormalizedFormatOptions { notation: 'auto' | 'exponential' | 'fixed' | 'engineering' | 'bin' | 'oct' | 'hex'; precision: number | undefined; wordSize: number | undefined; } /** * Check if a number is integer * @param value The value to check * @return true if value is an integer */ declare function isInteger(value: number | boolean): boolean; /** * Ensure the number type is compatible with the provided value. * If not, return 'number' instead. * * For example: * * safeNumberType('2.3', { number: 'bigint', numberFallback: 'number' }) * * will return 'number' and not 'bigint' because trying to create a bigint with * value 2.3 would throw an exception. * * @param numberStr The number as a string * @param config Configuration with number type preferences * @returns The safe number type to use */ declare function safeNumberType(numberStr: string, config: NumberTypeConfig): 'number' | 'BigNumber' | 'bigint' | 'Fraction'; /** * Calculate the sign of a number * @param x The number * @returns 1 for positive, -1 for negative, 0 for zero */ declare const sign: (x: number) => number; /** * Calculate the base-2 logarithm of a number * @param x The number * @returns The base-2 logarithm */ declare const log2: (x: number) => number; /** * Calculate the base-10 logarithm of a number * @param x The number * @returns The base-10 logarithm */ declare const log10: (x: number) => number; /** * Calculate the natural logarithm of a number + 1 * @param x The number * @returns ln(x + 1) */ declare const log1p: (x: number) => number; /** * Calculate cubic root for a number * * Code from es6-shim.js: * https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1564-L1577 * * @param x The number * @returns The cubic root of x */ declare const cbrt: (x: number) => number; /** * Calculates exponentiation minus 1 * @param x The exponent * @return exp(x) - 1 */ declare const expm1: (x: number) => number; /** * Convert a number to a formatted string representation. * * Syntax: * * format(value) * format(value, options) * format(value, precision) * format(value, fn) * * Where: * * {number} value The value to be formatted * {Object} options An object with formatting options. Available options: * {string} notation * Number notation. Choose from: * 'fixed' Always use regular number notation. * For example '123.40' and '14000000' * 'exponential' Always use exponential notation. * For example '1.234e+2' and '1.4e+7' * 'engineering' Always use engineering notation. * For example '123.4e+0' and '14.0e+6' * 'auto' (default) Regular number notation for numbers * having an absolute value between * `lowerExp` and `upperExp` bounds, and * uses exponential notation elsewhere. * Lower bound is included, upper bound * is excluded. * For example '123.4' and '1.4e7'. * 'bin', 'oct, or * 'hex' Format the number using binary, octal, * or hexadecimal notation. * For example '0b1101' and '0x10fe'. * {number} wordSize The word size in bits to use for formatting * in binary, octal, or hexadecimal notation. * To be used only with 'bin', 'oct', or 'hex' * values for 'notation' option. When this option * is defined the value is formatted as a signed * twos complement integer of the given word size * and the size suffix is appended to the output. * For example * format(-1, {notation: 'hex', wordSize: 8}) === '0xffi8'. * Default value is undefined. * {number} precision A number between 0 and 16 to round * the digits of the number. * In case of notations 'exponential', * 'engineering', and 'auto', * `precision` defines the total * number of significant digits returned. * In case of notation 'fixed', * `precision` defines the number of * significant digits after the decimal * point. * `precision` is undefined by default, * not rounding any digits. * {number} lowerExp Exponent determining the lower boundary * for formatting a value with an exponent * when `notation='auto`. * Default value is `-3`. * {number} upperExp Exponent determining the upper boundary * for formatting a value with an exponent * when `notation='auto`. * Default value is `5`. * {Function} fn A custom formatting function. Can be used to override the * built-in notations. Function `fn` is called with `value` as * parameter and must return a string. Is useful for example to * format all values inside a matrix in a particular way. * * Examples: * * format(6.4) // '6.4' * format(1240000) // '1.24e6' * format(1/3) // '0.3333333333333333' * format(1/3, 3) // '0.333' * format(21385, 2) // '21000' * format(12.071, {notation: 'fixed'}) // '12' * format(2.3, {notation: 'fixed', precision: 2}) // '2.30' * format(52.8, {notation: 'exponential'}) // '5.28e+1' * format(12345678, {notation: 'engineering'}) // '12.345678e+6' * * @param value The number to format * @param options Optional formatting options or custom formatter function or precision * @return The formatted value */ declare function format$2(value: number, options?: FormatOptions | ((value: number) => string) | number): string; /** * Normalize format options into an object: * { * notation: string, * precision: number | undefined, * wordSize: number | undefined * } * @param options The input options * @returns Normalized format options */ declare function normalizeFormatOptions(options?: FormatOptions | number): NormalizedFormatOptions; /** * Split a number into sign, coefficients, and exponent * @param value The number or string to split * @return Object containing sign, coefficients, and exponent */ declare function splitNumber(value: number | string): SplitValue; /** * Format a number in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3' * @param value The number or string to format * @param precision Optional number of significant figures to return * @returns The formatted string */ declare function toEngineering$1(value: number | string, precision?: number): string; /** * Format a number with fixed notation. * @param value The number or string to format * @param precision Optional number of decimals after the decimal point * @returns The formatted string */ declare function toFixed$1(value: number | string, precision?: number): string; /** * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3' * @param value The number or string to format * @param precision Number of digits in formatted output * @returns The formatted string */ declare function toExponential$1(value: number | string, precision?: number): string; /** * Format a number with a certain precision * @param value The number or string to format * @param precision Optional number of digits * @param options Optional formatting options (lowerExp, upperExp) * @return The formatted string */ declare function toPrecision(value: number | string, precision?: number, options?: FormatOptions): string; /** * Round the number of digits of a number * @param split A value split with .splitNumber(value) * @param precision A positive integer * @return Object containing sign, coefficients, and exponent with rounded digits */ declare function roundDigits(split: SplitValue, precision?: number): SplitValue; /** * Count the number of significant digits of a number. * * For example: * 2.34 returns 3 * 0.0034 returns 2 * 120.5e+30 returns 4 * * @param value The number * @return Number of significant digits */ declare function digits(value: number): number; /** * Compares two floating point numbers. * @param a First value to compare * @param b Second value to compare * @param relTol The relative tolerance, indicating the maximum allowed difference relative to the larger absolute value. Must be greater than 0. * @param absTol The minimum absolute tolerance, useful for comparisons near zero. Must be at least 0. * @return whether the two numbers are nearly equal * * @throws Error If `relTol` is less than or equal to 0. * @throws Error If `absTol` is less than 0. * * @example * nearlyEqual(1.000000001, 1.0, 1e-8); // true * nearlyEqual(1.000000002, 1.0, 0); // false * nearlyEqual(1.0, 1.009, undefined, 0.01); // true * nearlyEqual(0.000000001, 0.0, undefined, 1e-8); // true */ declare function nearlyEqual(a: number, b: number, relTol?: number, absTol?: number): boolean; /** * Calculate the hyperbolic arccos of a number * @param x The number * @return The hyperbolic arccosine */ declare const acosh: (x: number) => number; /** * Calculate the hyperbolic arcsine of a number * @param x The number * @return The hyperbolic arcsine */ declare const asinh: (x: number) => number; /** * Calculate the hyperbolic arctangent of a number * @param x The number * @return The hyperbolic arctangent */ declare const atanh: (x: number) => number; /** * Calculate the hyperbolic cosine of a number * @param x The number * @returns The hyperbolic cosine */ declare const cosh: (x: number) => number; /** * Calculate the hyperbolic sine of a number * @param x The number * @returns The hyperbolic sine */ declare const sinh: (x: number) => number; /** * Calculate the hyperbolic tangent of a number * @param x The number * @returns The hyperbolic tangent */ declare const tanh: (x: number) => number; /** * Returns a value with the magnitude of x and the sign of y. * @param x The value providing the magnitude * @param y The value providing the sign * @returns Value with magnitude of x and sign of y */ declare function copysign(x: number, y: number): number; /** * Check if x^y is 0 due to infinity * @param x The base * @param y The exponent * @returns true if x^y is 0 due to infinity */ declare function isPowZeroAtInfinity(x: number, y: number): boolean; /** * Shared utility functions used across core utility modules. * This file must have ZERO imports from other core utility files * to serve as the base of the dependency graph and break circular imports. */ /** * A safe hasOwnProperty * @param {Object} object * @param {string} property */ declare function hasOwnProperty(object: unknown, property: string): boolean; /** * True when `text` ends with `search`. (Equivalent to `String.prototype.endsWith`; * kept as a named helper so relocated modules read the same as their mathjs origin.) */ declare function endsWith(text: string, search: string): boolean; /** * Warn to the console at most once per distinct message, deduped for the process * lifetime. Used for deprecation notices (e.g. `Unit.toNumber`). */ declare const warnOnce: (...args: unknown[]) => void; /** A function whose results are cached; clear the cache with `delete fn.cache`. */ interface MemoizedFunction { (...args: unknown[]): unknown; cache?: Map; } /** * Memoize a pure function, caching results in a `Map` keyed by a string hash of the * arguments (default `JSON.stringify`; override via `hasher`). Pass `limit` to bound * the cache to N most-recently-used entries (LRU eviction via `Map` insertion order — * on a hit the key is moved to the most-recent end; on overflow the oldest key is * dropped); omit for an unbounded cache. The cache is exposed as `fn.cache` and can be * reset with `delete fn.cache` — the next call lazily recreates it. (The relocated * `Unit` relies on that reset when `createUnit`/`deleteUnit` invalidate the unit-name * lookup cache, and passes `limit: 100` to bound the parse cache.) */ declare function memoize(fn: (...args: unknown[]) => unknown, { hasher, limit }?: { hasher?: (args: unknown[]) => string; limit?: number; }): MemoizedFunction; /** * Clone an object * * clone(x) * * Can clone any primitive type, array, and object. * If x has a function clone, this function will be invoked to clone the object. * * @param {*} x * @return {*} clone */ declare function clone$1(x: T): T; /** * Apply map to all properties of an object * @param {Object} object * @param {function} callback * @return {Object} Returns a copy of the object with mapped properties */ declare function mapObject(object: Record, callback: (value: T) => U): Record; /** * Extend object a with the properties of object b * @param {Object} a * @param {Object} b * @return {Object} a */ declare function extend, U extends Record>(a: T, b: U): T & U; /** * Deep extend an object a with the properties of object b * @param {Object} a * @param {Object} b * @returns {Object} */ declare function deepExtend(a: T, b: unknown): T; /** * Deep test equality of all fields in two pairs of arrays or objects. * Compares values and functions strictly (ie. 2 is not the same as '2'). * @param {Array | Object} a * @param {Array | Object} b * @returns {boolean} */ declare function deepStrictEqual(a: unknown, b: unknown): boolean; /** * Recursively flatten a nested object. * @param {Object} nestedObject * @return {Object} Returns the flattened object */ declare function deepFlatten(nestedObject: Record): Record; /** * Test whether the current JavaScript engine supports Object.defineProperty * @returns {boolean} returns true if supported */ declare function canDefineProperty(): boolean; /** * Attach a lazy loading property to a constant. * The given function `fn` is called once when the property is first requested. * * @param {Object} object Object where to add the property * @param {string} prop Property name * @param {Function} valueResolver Function returning the property value. Called * without arguments. */ declare function lazy(object: Record, prop: string, valueResolver: () => T): void; /** * Traverse a path into an object. * When a namespace is missing, it will be created * @param {Object} object * @param {string | string[]} path A dot separated string like 'name.space' * @return {Object} Returns the object at the end of the path */ declare function traverse(object: Record, path: string | string[]): Record; /** * Test whether an object is a factory. a factory has fields: * * - factory: function (type: Object, config: Object, load: function, typed: function [, math: Object]) (required) * - name: string (optional) * - path: string A dot separated path (optional) * - math: boolean If true (false by default), the math namespace is passed * as fifth argument of the factory function * * @param {*} object * @returns {boolean} */ declare function isLegacyFactory(object: unknown): boolean; /** * Get a nested property from an object * @param {Object} object * @param {string | string[]} path * @returns {Object} */ declare function get$1(object: Record, path: string | string[]): unknown; /** * Set a nested property in an object * Mutates the object itself * If the path doesn't exist, it will be created * @param {Object} object * @param {string | string[]} path * @param {*} value * @returns {Object} */ declare function set>(object: T, path: string | string[], value: unknown): T; /** * Create an object composed of the picked object properties * @param {Object} object * @param {string[]} properties * @param {function} [transform] Optional value to transform a value when picking it * @return {Object} */ declare function pick(object: Record, properties: string[], transform?: (value: unknown, key: string) => unknown): Record; /** * Shallow version of pick, creating an object composed of the picked object properties * but not for nested properties * @param {Object} object * @param {string[]} properties * @return {Object} */ declare function pickShallow(object: Record, properties: string[]): Record; /** * Configuration interface for math.js */ interface ConfigOptions { relTol: number; absTol: number; matrix: 'Matrix' | 'Array'; number: 'number' | 'BigNumber' | 'bigint' | 'Fraction'; numberFallback: 'number' | 'BigNumber'; precision: number; predictable: boolean; randomSeed: string | null; legacySubset: boolean; } type MathJsConfig = ConfigOptions; declare const DEFAULT_CONFIG: ConfigOptions; /** * Custom error type for Mathjs errors * @extends Error */ declare class MathjsError extends Error { isMathjsError: true; /** * Create a MathjsError * @param message Error message */ constructor(message: string); } /** * Create a range error with the message: * 'Dimension mismatch ( != )' * Or with a custom message when called with a single string argument. * * The single canonical `DimensionError` for the whole monorepo (Bucket B, commit 1), * exposed via the `@danielsimonjr/mathts-core/internal` subpath. `expression/src/error/ * DimensionError.ts` and `functions/src/error/DimensionError.ts` are now thin * re-export shims of this class — a `DimensionError` thrown in one package is * `instanceof DimensionError` in any other, since there is only ever one class * identity. `core/src/array.ts` (and the ~20 other call sites across matrix algos, * subset, resize, concat, reshape, ...) all throw this same class. */ declare class DimensionError extends RangeError { actual?: number | number[]; expected?: number | number[]; relation?: string; isDimensionError: true; /** * @param actual - The actual size or custom error message * @param expected - The expected size (optional if actual is a custom message) * @param relation - Optional relation between actual and expected size: '!=', '<', etc. */ constructor(actual: number | number[] | string, expected?: number | number[], relation?: string); } /** * Custom error type for index out of range errors. * * The single canonical `IndexError` for the whole monorepo (Bucket B, commit 1), * exposed via the `@danielsimonjr/mathts-core/internal` subpath. `expression/src/error/ * IndexError.ts` and `functions/src/error/IndexError.ts` are now thin re-export shims * of this class — an `IndexError` thrown in one package is `instanceof IndexError` * in any other, since there is only ever one class identity. `core/src/array.ts` / * `core/src/collection.ts` (and the many other call sites across concat, subset, * cumsum, mapSlices, ...) all throw this same class. * * @extends RangeError */ declare class IndexError extends RangeError { index: number; min: number | undefined; max: number | undefined; isIndexError: true; /** * Create an IndexError * * Can be called in two ways: * - IndexError(index, max) - assumes min=0 * - IndexError(index, min, max) * * @param index The actual index * @param min Minimum index (included), or max if only 2 args provided * @param max Maximum index (excluded) */ constructor(index: number, min?: number, max?: number); } declare function createIndexError(index: number, min?: number, max?: number): IndexError; /** * Formatting options accepted by the generic `format` helper. Extends the * numeric {@link FormatOptions} with the string-level `truncate` and the * fraction rendering mode, or is a precision number, or a custom formatter. */ type GeneralFormatOptions = number | ((value: unknown) => string) | (FormatOptions & { truncate?: number; fraction?: 'ratio' | 'decimal'; }); /** * Format a value of any type into a string. * * Usage: * math.format(value) * math.format(value, precision) * math.format(value, options) * * When value is a function: * * - When the function has a property `syntax`, it returns this * syntax description. * - In other cases, a string `'function'` is returned. * * When `value` is an Object: * * - When the object contains a property `format` being a function, this * function is invoked as `value.format(options)` and the result is returned. * - When the object has its own `toString` method, this method is invoked * and the result is returned. * - In other cases the function will loop over all object properties and * return JSON object notation like '{"a": 2, "b": 3}'. * * Example usage: * math.format(2/7) // '0.2857142857142857' * math.format(math.pi, 3) // '3.14' * math.format(new Complex(2, 3)) // '2 + 3i' * math.format('hello') // '"hello"' * * @param {*} value Value to be stringified * @param {Object | number | Function} [options] * Formatting options. See src/utils/number.js:format for a * description of the available options controlling number output. * This generic "format" also supports the option property `truncate: NN` * giving the maximum number NN of characters to return (if there would * have been more, they are deleted and replaced by an ellipsis). * @return {string} str */ declare function format$1(value: unknown, options?: unknown): string; /** * Stringify a value into a string enclosed in double quotes. * Unescaped double quotes and backslashes inside the value are escaped. * @param {*} value * @return {string} */ declare function stringify(value: unknown): string; /** * Escape special HTML characters * @param {*} value * @return {string} */ declare function escape(value: unknown): string; /** * Compare two strings * @param {string} x * @param {string} y * @returns {number} */ declare function compareText(x: unknown, y: unknown): number; /** * Structural contract for the BigNumber values handled by this formatter. * Captures exactly the methods/properties used here. The configured BigNumber * implementation (e.g. decimal.js) provides these; the project's `BigNumber` * type alias points at a minimal local Decimal that does not declare them all, * so we model the runtime contract explicitly. */ interface BigNumberValue { e: number; constructor: new (value: number | string) => BigNumberValue; isFinite(): boolean; isNaN(): boolean; isZero(): boolean; isInteger(): boolean; gt(other: number | BigNumberValue): boolean; greaterThan(other: number | BigNumberValue): boolean; lessThan(other: number | BigNumberValue): boolean; add(other: number | BigNumberValue): BigNumberValue; sub(other: number | BigNumberValue): BigNumberValue; mul(other: number | BigNumberValue): BigNumberValue; pow(exp: number | BigNumberValue): BigNumberValue; toNumber(): number; toFixed(places?: number): string; toExponential(places?: number): string; toPrecision(sd?: number): string; toSignificantDigits(sd?: number): BigNumberValue; toBinary(): string; toOctal(): string; toHexadecimal(): string; } /** * Convert a BigNumber to a formatted string representation. * * Syntax: * * format(value) * format(value, options) * format(value, precision) * format(value, fn) * * Where: * * {number} value The value to be formatted * {Object} options An object with formatting options. Available options: * {string} notation * Number notation. Choose from: * 'fixed' Always use regular number notation. * For example '123.40' and '14000000' * 'exponential' Always use exponential notation. * For example '1.234e+2' and '1.4e+7' * 'auto' (default) Regular number notation for numbers * having an absolute value between * `lower` and `upper` bounds, and uses * exponential notation elsewhere. * Lower bound is included, upper bound * is excluded. * For example '123.4' and '1.4e7'. * 'bin', 'oct, or * 'hex' Format the number using binary, octal, * or hexadecimal notation. * For example '0b1101' and '0x10fe'. * {number} wordSize The word size in bits to use for formatting * in binary, octal, or hexadecimal notation. * To be used only with 'bin', 'oct', or 'hex' * values for 'notation' option. When this option * is defined the value is formatted as a signed * twos complement integer of the given word size * and the size suffix is appended to the output. * For example * format(-1, {notation: 'hex', wordSize: 8}) === '0xffi8'. * Default value is undefined. * {number} precision A number between 0 and 16 to round * the digits of the number. * In case of notations 'exponential', * 'engineering', and 'auto', * `precision` defines the total * number of significant digits returned. * In case of notation 'fixed', * `precision` defines the number of * significant digits after the decimal * point. * `precision` is undefined by default. * {number} lowerExp Exponent determining the lower boundary * for formatting a value with an exponent * when `notation='auto`. * Default value is `-3`. * {number} upperExp Exponent determining the upper boundary * for formatting a value with an exponent * when `notation='auto`. * Default value is `5`. * {Function} fn A custom formatting function. Can be used to override the * built-in notations. Function `fn` is called with `value` as * parameter and must return a string. Is useful for example to * format all values inside a matrix in a particular way. * * Examples: * * format(6.4) // '6.4' * format(1240000) // '1.24e6' * format(1/3) // '0.3333333333333333' * format(1/3, 3) // '0.333' * format(21385, 2) // '21000' * format(12e8, {notation: 'fixed'}) // returns '1200000000' * format(2.3, {notation: 'fixed', precision: 4}) // returns '2.3000' * format(52.8, {notation: 'exponential'}) // returns '5.28e+1' * format(12400, {notation: 'engineering'}) // returns '12.400e+3' * * @param {BigNumber} value * @param {Object | Function | number | BigNumber} [options] * @return {string} str The formatted value */ declare function format(value: unknown, options?: unknown): string; /** * Format a BigNumber in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3' * @param {BigNumber} value * @param {number} [precision] Optional number of significant figures to return. */ declare function toEngineering(value: BigNumberValue, precision?: number): string; /** * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3' * @param {BigNumber} value * @param {number} [precision] Number of digits in formatted output. * If not provided, the maximum available digits * is used. * @returns {string} str */ declare function toExponential(value: BigNumberValue, precision?: number): string; /** * Format a number with fixed notation. * @param {BigNumber} value * @param {number} [precision=undefined] Optional number of decimals after the * decimal point. Undefined by default. */ declare function toFixed(value: BigNumberValue, precision?: number): string; type NestedArray = T | NestedArray[]; interface IdentifiedValue { value: T; identifier: number; } /** * Calculate the size of a multi dimensional array. * This function checks the size of the first entry, it does not validate * whether all dimensions match. (use function `validate` for that) * @param {Array} x * @return {number[]} size */ declare function arraySize(x: NestedArray): number[]; /** * Validate whether each element in a multi dimensional array has * a size corresponding to the provided size array. * @param {Array} array Array to be validated * @param {number[]} size Array with the size of each dimension * @throws DimensionError */ declare function validate(array: NestedArray, size: number[]): void; /** * Validate whether the source of the index matches the size of the Array * @param {Array | Matrix} value Array to be validated * @param {Index} index Index with the source information to validate * @throws DimensionError */ declare function validateIndexSourceSize(value: unknown[] | Matrix$1, index: Index): void; /** * Test whether index is an integer number with index >= 0 and index < length * when length is provided * @param {number} index Zero-based index * @param {number} [length] Length of the array */ declare function validateIndex(index: number | undefined, length?: number): void; /** * Test if an index has empty values * @param {Index} index Zero-based index */ declare function isEmptyIndex(index: Index): boolean; /** * Resize a multi dimensional array. The resized array is returned. * @param {Array | number} array Array to be resized * @param {number[]} size Array with the size of each dimension * @param {*} [defaultValue=0] Value to be filled in new entries, * zero by default. Specify for example `null`, * to clearly see entries that are not explicitly * set. * @return {Array} array The resized array */ declare function resize(array: T | T[] | NestedArray, size: number[], defaultValue?: T): NestedArray; /** * Re-shape a multi dimensional array to fit the specified dimensions * @param {Array} array Array to be reshaped * @param {number[]} sizes List of sizes for each dimension * @returns {Array} Array whose data has been formatted to fit the * specified dimensions * * @throws {DimensionError} If the product of the new dimension sizes does * not equal that of the old ones */ declare function reshape(array: NestedArray, sizes: number[]): NestedArray; /** * Replaces the wildcard -1 in the sizes array. * @param {number[]} sizes List of sizes for each dimension. At most one wildcard. * @param {number} currentLength Number of elements in the array. * @throws {Error} If more than one wildcard or unable to replace it. * @returns {number[]} The sizes array with wildcard replaced. */ declare function processSizesWildcard(sizes: number[], currentLength: number): number[]; /** * Squeeze a multi dimensional array * @param {Array} array * @param {Array} [size] * @returns {Array} returns the array itself */ declare function squeeze(array: NestedArray, size?: number[]): T | NestedArray; /** * Unsqueeze a multi dimensional array: add dimensions when missing * * Parameter `size` will be mutated to match the new, unsqueezed matrix size. * * @param {Array} array * @param {number} dims Desired number of dimensions of the array * @param {number} [outer] Number of outer dimensions to be added * @param {Array} [size] Current size of array. * @returns {Array} returns the array itself * @private */ declare function unsqueeze(array: NestedArray, dims: number, outer?: number, size?: number[]): NestedArray; /** * Flatten a multi dimensional array, put all elements in a one dimensional * array * @param {Array} array A multi dimensional array * @param {boolean} isRectangular Optional. If the array is rectangular (not jagged) * @return {Array} The flattened array (1 dimensional) */ declare function flatten(array: NestedArray, isRectangular?: boolean): T[]; /** * A safe map * @param {Array} array * @param {function} callback */ declare function map(array: T[], callback: (value: T, index: number, array: T[]) => U): U[]; /** * A safe forEach * @param {Array} array * @param {function} callback */ declare function forEach(array: T[], callback: (value: T, index: number, array: T[]) => void): void; /** * A safe filter * @param {Array} array * @param {function} callback */ declare function filter(array: T[], callback: (value: T, index: number, array: T[]) => boolean): T[]; /** * Filter values in an array given a regular expression * @param {Array} array * @param {RegExp} regexp * @return {Array} Returns the filtered array * @private */ declare function filterRegExp(array: string[], regexp: RegExp): string[]; /** * A safe join * @param {Array} array * @param {string} separator */ declare function join(array: T[], separator: string): string; /** * Assign a numeric identifier to every element of a sorted array * @param {Array} a An array * @return {Array} An array of objects containing the original value and its identifier */ declare function identify(a: T[]): IdentifiedValue[]; /** * Remove the numeric identifier from the elements * @param {array} a An array * @return {array} An array of values without identifiers */ declare function generalize(a: IdentifiedValue[]): T[]; /** * Check the datatype of a given object * This is a low level implementation that should only be used by * parent Matrix classes such as SparseMatrix or DenseMatrix * This method does not validate Array Matrix shape * @param {Array} array * @param {function} typeOf Callback function to use to determine the type of a value * @return {string} */ declare function getArrayDataType(array: unknown[], typeOf: (value: unknown) => string): string | undefined; /** * Return the last item from an array * @param {Array} array * @returns {*} */ declare function last(array: T[]): T; /** * Get all but the last element of array. * * KNOWN DIVERGENCE (Bucket B slice 2): only `expression/src/utils/array.ts` had * this; `functions/src/utils/array.ts` never defined it, and it was dead code * even in expression (unused outside its own definition). Re-exported from * expression's shim only — see the module header. * @param {Array} array * @returns {Array} */ declare function initial(array: T[]): T[]; /** * Concatenates many arrays in the specified direction * @param {...Array} arrays All the arrays to concatenate * @param {number} concatDim The dimension on which to concatenate (zero-based) * @returns {Array} */ declare function concat(...args: [...NestedArray[], number]): NestedArray[]; /** * Receives two or more sizes and gets the broadcasted size for both. * @param {...number[]} sizes Sizes to broadcast together * @returns {number[]} The broadcasted size */ declare function broadcastSizes(...sizes: number[][]): number[]; /** * Checks if it's possible to broadcast a size to another size * @param {number[]} size The size of the array to check * @param {number[]} toSize The size of the array to validate if it can be broadcasted to */ declare function checkBroadcastingRules(size: number[], toSize: number[]): void; /** * Broadcasts a single array to a certain size * @param {Array} array Array to be broadcasted * @param {number[]} toSize Size to broadcast the array * @returns {Array} The broadcasted array */ declare function broadcastTo(array: NestedArray, toSize: number[]): NestedArray; /** * Broadcasts arrays and returns the broadcasted arrays in an array * @param {...Array | any} arrays * @returns {Array[]} The broadcasted arrays */ declare function broadcastArrays(...arrays: NestedArray[]): NestedArray[]; /** * Stretches a matrix up to a certain size in a certain dimension * @param {Array} arrayToStretch * @param {number[]} sizeToStretch * @param {number} dimToStretch * @returns {Array} The stretched array */ declare function stretch(arrayToStretch: NestedArray, sizeToStretch: number, dimToStretch: number): NestedArray; /** * Retrieves a single element from an array given an index. * * @param {Array} array - The array from which to retrieve the value. * @param {Array} index - An array of indices specifying the position of the desired element in each dimension. * @returns {*} - The value at the specified position in the array. * * @example * const arr = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]; * const index = [1, 0, 1]; * console.log(get(arr, index)); // 6 */ declare function get(array: NestedArray, index: number[]): T; /** * Recursively maps over each element of nested array using a provided callback function. * * @param {Array} array - The array to be mapped. * @param {Function} callback - The function to execute on each element, taking three arguments: * - `value` (any): The current element being processed in the array. * - `index` (Array): The index of the current element being processed in the array. * - `array` (Array): The array `deepMap` was called upon. * @param {boolean} [skipIndex=false] - If true, the callback function is called with only the value. * @returns {Array} A new array with each element being the result of the callback function. */ declare function deepMap$1(array: NestedArray, callback: ((value: T, index: number[], array: NestedArray) => U) | ((value: T) => U), skipIndex?: boolean): NestedArray; /** * Recursively iterates over each element in a multi-dimensional array and applies a callback function. * * @param {Array} array - The multi-dimensional array to iterate over. * @param {Function} callback - The function to execute for each element. It receives three arguments: * - {any} value: The current element being processed in the array. * - {Array} index: The index of the current element in each dimension. * - {Array} array: The original array being processed. * @param {boolean} [skipIndex=false] - If true, the callback function is called with only the value. */ declare function deepForEach$1(array: NestedArray, callback: ((value: T, index: number[], array: NestedArray) => void) | ((value: T) => void), skipIndex?: boolean): void; /** * Deep clones a multidimensional array * @param {Array} array * @returns {Array} cloned array */ declare function clone(array: T[]): T[]; interface Matrix { forEach(callback: (value: T) => void, skipZeros: boolean, recurse: boolean): void; map(callback: (value: T) => U, skipZeros: boolean, recurse: boolean): Matrix; size(): number[]; valueOf(): T[]; create(data: T[], datatype?: string): Matrix; datatype(): string | undefined; } interface SparseMatrix { _values: T[]; _index: number[]; _ptr: number[]; } /** * Test whether an array contains collections * @param array - Array to test * @returns Returns true when the array contains one or multiple * collections (Arrays or Matrices). Returns false otherwise. */ declare function containsCollections(array: unknown[]): boolean; /** * Recursively loop over all elements in a given multi dimensional array * and invoke the callback on each of the elements. * @param array - Array or Matrix to iterate over * @param callback - The callback method is invoked with one parameter: the current element in the array */ declare function deepForEach(array: T[] | Matrix, callback: (value: T) => void): void; /** * Execute the callback function element wise for each element in array and any * nested array * Returns an array with the results * @param array - Array or Matrix to map over * @param callback - The callback is called with two parameters: * value1 and value2, which contain the current * element of both arrays. * @param skipZeros - Invoke callback function for non-zero values only. * * @return Mapped result */ declare function deepMap(array: T[] | Matrix, callback: (value: T) => U, skipZeros?: boolean): U[] | Matrix; /** * Reduce a given matrix or array to a new matrix or * array with one less dimension, applying the given * callback in the selected dimension. * @param mat - Array or Matrix to reduce * @param dim - Dimension to reduce * @param callback - Callback function * @return Reduced result */ declare function reduce(mat: T[] | Matrix, dim: number, callback: (acc: U | T, val: T) => U): U[] | Matrix; /** * Scatter function for sparse matrix operations * @param a - Sparse matrix * @param j - Column index * @param w - Work array for marking visited rows * @param x - Work array for storing values * @param u - Work array for marking updated rows * @param mark - Current mark value * @param cindex - Column index array to update * @param f - Binary function to apply * @param inverse - Whether to inverse the function arguments * @param update - Whether to update existing values * @param value - Value to use in binary function */ declare function scatter(a: SparseMatrix, j: number, w: number[], x: T[] | null, u: number[], mark: number, cindex: number[], f?: (a: T, b: T) => T, inverse?: boolean, update?: boolean, value?: T): void; /** * Transpose a 2D array. Private helper used only by `core/src/collection.ts`'s * `_reduce` (Bucket B slice 2 canonical) — mirrors `expression/src/utils/switch.ts` * / `functions/src/utils/switch.ts`, which remain in place unchanged for now * (not part of this slice's named scope). Not exported from `internal.ts`. * @private */ declare function _switch(mat: T[][]): T[][]; /** * A map facade on a bare object. * * The small number of methods needed to implement a scope, * forwarding on to the SafeProperty functions. Over time, the codebase * will stop using this method, as all objects will be Maps, rather than * more security prone objects. */ /** * The iterator type `Map` itself declares, derived from the installed TS lib * rather than hard-coded: older libs say `IterableIterator<[K, V]>`, TS >= 5.6 * says `MapIterator<[K, V]>` (which additionally requires `[Symbol.dispose]`). * Deriving it keeps `implements Map` honest on every TS version. */ type MapEntryIterator = ReturnType[typeof Symbol.iterator]>; declare class ObjectWrappingMap implements Map { wrappedObject: Record; readonly [Symbol.toStringTag]: string; constructor(object: Record); /** * Declared as a real method rather than assigned in the constructor through a * cast. The old form satisfied the runtime but never appeared in the emitted * type, so `implements Map` was a lie that only surfaced downstream: * consumers compiling with `skipLibCheck: false` got TS2420 ("incorrectly * implements interface 'Map'... '[Symbol.iterator]' is missing"). */ [Symbol.iterator](): MapEntryIterator; keys(): IterableIterator; get(key: K): V | undefined; set(key: K, value: V): this; has(key: K): boolean; entries(): IterableIterator<[K, V]>; values(): IterableIterator; forEach(callback: (value: V, key: K, map: Map) => void): void; delete(key: K): boolean; clear(): void; get size(): number; } /** * Create a map with two partitions: a and b. * The set with bKeys determines which keys/values are read/written to map b, * all other values are read/written to map a * * For example: * * const a = new Map() * const b = new Map() * const p = new PartitionedMap(a, b, new Set(['x', 'y'])) * * In this case, values `x` and `y` are read/written to map `b`, * all other values are read/written to map `a`. */ declare class PartitionedMap implements Map { a: Map; b: Map; bKeys: Set; readonly [Symbol.toStringTag]: string; /** * @param a - Primary map * @param b - Secondary map * @param bKeys - Set of keys that should be read/written to map b */ constructor(a: Map, b: Map, bKeys: Set); /** See the note on `ObjectWrappingMap[Symbol.iterator]` — same fix. */ [Symbol.iterator](): MapEntryIterator; get(key: K): V | undefined; set(key: K, value: V): this; has(key: K): boolean; keys(): IterableIterator; values(): IterableIterator; entries(): IterableIterator<[K, V]>; forEach(callback: (value: V, key: K, map: Map) => void): void; delete(key: K): boolean; clear(): void; get size(): number; } /** * Creates an empty map, or whatever your platform's polyfill is. * * @returns an empty Map or Map like object. */ declare function createEmptyMap(): Map; /** * Creates a Map from the given object. * * @param mapOrObject - Map or object to convert * @returns Map instance */ declare function createMap(mapOrObject?: Map | Record | null): Map; /** * Unwraps a map into an object. * * @param map - Map to convert to object * @returns Plain object */ declare function toObject(map: Map): Record; /** * Copies the contents of key-value pairs from each `objects` in to `map`. * * Object is `objects` can be a `Map` or object. * * This is the `Map` analog to `Object.assign`. */ declare function assign(map: Map, ...objects: (Map | Record | null | undefined)[]): Map; /** * Returns `true` if `object` is an {@link ObjectWrappingMap}. * * Defined here, next to the class it guards, so `is.ts` need not import * `map.ts` — that import was the sole edge closing the `is`/`map` cycle. */ declare function isObjectWrappingMap(object: unknown): object is ObjectWrappingMap; /** * Shared type-only shapes for the two independent WASM loader implementations * (`functions/src/wasm/WasmLoader.ts` and `matrix/src/backends/WasmLoader.ts`). * * Both packages bind to the same `mathts-as.wasm` AssemblyScript binary but each * declares its own package-scoped subset of the exported function ABI (`WasmModule` * genuinely differs between the two — matrix only needs matrix-relevant exports, * functions needs the full breadth including signal/geometry/special-function * kernels — so `WasmModule` stays local to each package). `LoadingMetrics` (perf * timings) and `WasmManifest` (the SHA-384 integrity manifest shape) were, * however, byte-for-byte identical copies with no principled reason to diverge; * consolidated here (cross-package type-dedup pass, * docs/Architecture/duplicate-symbols.json). * * @module @danielsimonjr/mathts-core/types/wasm-loader */ /** * Loading performance metrics for a WASM module load/instantiate cycle. */ interface LoadingMetrics { fileReadMs: number; compileMs: number; instantiateMs: number; totalMs: number; fromCache: boolean; } /** * SHA-384 integrity manifest: maps a `.wasm` filename to its * `"sha384-"` value (SRI-style), as generated by * `tools/generate-wasm-manifest.mjs`. */ interface WasmManifest { [fileName: string]: string; } /** * Shared WASM-loader runtime logic — SHA-384 integrity verification + packaged * artifact path resolution — consolidated here so `functions` and `matrix` build * on ONE copy instead of maintaining byte-identical forks. * * Why core: `matrix` cannot import from `functions` (functions depends on matrix, * which would invert the edge and create a cycle), so the historical solution was * to duplicate this logic in both packages. Both packages already depend on * `core`, so `@danielsimonjr/mathts-core/internal` is a home reachable from both * WITHOUT introducing a cycle. Exposed ONLY via the `/internal` subpath (never the * browser-facing `.` entry); every filesystem/crypto access uses a LAZY dynamic * `import()` so this module stays browser-safe (no static `node:` imports). * * SECURITY INVARIANT (CLAUDE.md "Security Invariants" #1): the SHA-384 * hash-and-compare-before-instantiate is preserved BYTE-FOR-BYTE from the former * per-package `integrity.ts` copies — same algorithm, same fail-closed/soft-warn * behavior. Do NOT bypass, weaken to a non-cryptographic check, or skip on * streaming compile paths. Regression-covered by * `functions/tests/security/wasm-integrity.test.ts` and * `matrix/tests/security/wasm-integrity.test.ts`. * * The build pipeline writes a JSON manifest beside the .wasm artefact: * * { * "mathts-as.wasm": "sha384-" * } * * At load time the runtime hashes the freshly read buffer with SHA-384 and * compares against the manifest. A mismatch throws — preventing silent * code-injection if the .wasm artefact is tampered with on disk or in transit * (e.g. a CDN/MITM compromise). * * Browser path uses `crypto.subtle.digest('SHA-384', buf)`. * Node path uses `crypto.createHash('sha384').update(buf).digest()`. * * If the manifest is missing or has no entry for the given file, we emit a * console warning and fall through. This keeps existing unsigned builds usable * while making signed builds tamper-evident. * * @module @danielsimonjr/mathts-core/internal (wasm-loader) */ /** * Compute the SHA-384 digest of a buffer and return base64 encoding, * prefixed with "sha384-" to match SRI conventions. */ declare function sha384OfBuffer(buffer: ArrayBuffer | Uint8Array): Promise; /** * Load the manifest sitting next to the .wasm artefact. * * @param wasmPath Resolved path or URL to the .wasm file. * @returns parsed manifest, or `null` if the manifest cannot be located. */ declare function loadWasmManifest(wasmPath: string): Promise; /** * Verify a freshly loaded WASM buffer against the manifest. * * @throws Error if the buffer's SHA-384 differs from the manifest entry. */ declare function verifyWasmIntegrity(buffer: ArrayBuffer | Uint8Array, wasmPath: string, options?: { manifest?: WasmManifest | null; required?: boolean; }): Promise; /** * Robustly locate a packaged `.wasm` artifact across both the monorepo-source * layout and the published-package layout (Node only). * * The historical loaders hard-coded `../../../lib/wasm/` relative to * `import.meta.url`, which only resolved for the monorepo source layout and * pointed outside the package once bundled/published — so the wasm was never * found and every consumer silently fell back to JS. This walks up from the * calling module's directory probing `/wasm/` and * `/dist/wasm/` at each level, matching bundled dist, unbundled dist, * and monorepo source. * * The caller injects its OWN `metaUrl` (its `import.meta.url`) so resolution is * relative to the calling package, not to core. * * @returns absolute path to the artifact, or `null` if not found. */ declare function resolvePackagedWasm(metaUrl: string, wasmFile: string): Promise; /** * Canonical fallback location for the packaged wasm when {@link resolvePackagedWasm} * finds nothing: `/dist/wasm/`, with the package root found * by walking up from `metaUrl` to the nearest `package.json`. This replaces the * historical `../../../lib/wasm/` fabrication, which was only correct for the * pre-bundling source layout. The returned path is where the binary SHOULD be, so * the missing-binary warning tells the user exactly what to build. * * In browser mode (no filesystem) it returns the bundle-relative `./wasm/` * URL — correct for a served `dist/`, which is the only layout browsers see. */ declare function defaultWasmLocation(metaUrl: string, wasmFile: string, opts?: { browser?: boolean; }): Promise; export { type BigNumberValue, type ConfigOptions, DEFAULT_CONFIG, DimensionError, FactoryFunction, type FormatOptions, type GeneralFormatOptions, type IdentifiedValue, Index, IndexError, type LoadingMetrics, type MathJsConfig, MathjsError, Matrix$1 as Matrix, type MemoizedFunction, type NestedArray, type NormalizedFormatOptions, type NumberTypeConfig, ObjectWrappingMap, PartitionedMap, type SplitValue, UnitConstructor, UnitDependencies, type WasmManifest, _switch, acosh, arraySize, asinh, assign as assignMap, atanh, broadcastArrays, broadcastSizes, broadcastTo, canDefineProperty, cbrt, checkBroadcastingRules, clone$1 as clone, clone as cloneArray, compareText, concat, containsCollections, copysign, cosh, createEmptyMap, createIndexError, createMap, createUnitClass, deepExtend, deepFlatten, deepForEach, deepForEach$1 as deepForEachArray, deepMap, deepMap$1 as deepMapArray, deepStrictEqual, defaultWasmLocation, digits, endsWith, escape, expm1, extend, filter, filterRegExp, flatten, forEach, format$2 as format, format as formatBigNumber, format$1 as formatGeneric, generalize, get$1 as get, getArrayDataType, get as getArrayElement, hasOwnProperty, identify, initial, isEmptyIndex, isInteger, isLegacyFactory, isObjectWrappingMap, isPowZeroAtInfinity, join, last, lazy, loadWasmManifest, log10, log1p, log2, map, mapObject, memoize, nearlyEqual, normalizeFormatOptions, pick, pickShallow, processSizesWildcard, reduce, reshape, resize, resolvePackagedWasm, roundDigits, safeNumberType, scatter, set, sha384OfBuffer, sign, sinh, splitNumber, squeeze, stretch, stringify, tanh, toEngineering$1 as toEngineering, toEngineering as toEngineeringBigNumber, toExponential$1 as toExponential, toExponential as toExponentialBigNumber, toFixed$1 as toFixed, toFixed as toFixedBigNumber, toObject, toPrecision, traverse, unitDependencies, unsqueeze, validate, validateIndex, validateIndexSourceSize, verifyWasmIntegrity, warnOnce };