import type { AlgebraicType } from './algebraic_type.ts'; import type { Typespace } from './autogen/types.ts'; import BinaryReader from './binary_reader.ts'; import BinaryWriter from './binary_writer.ts'; import type { ParamsObj } from './reducers.ts'; import type { ColumnBuilder, TypeBuilder } from './type_builders.ts'; import type { CamelCase, SnakeCase } from './type_util.ts'; export function deepEqual(obj1: unknown, obj2: unknown): boolean { if (obj1 === obj2) return true; if ( typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null ) { return false; } let firstKey = 0; if (obj1 instanceof Uint8Array && obj2 instanceof Uint8Array) { if (obj1.length !== obj2.length) return false; for (let i = 0; i < obj1.length; i++) { if (obj1[i] !== obj2[i]) return false; } // Typed-array indices precede other enumerable keys and are already equal. firstKey = obj1.length; } const keys1 = Object.keys(obj1); const keys2 = Object.keys(obj2); if (keys1.length !== keys2.length) return false; const values1 = obj1 as Record; const values2 = obj2 as Record; for (let i = firstKey; i < keys1.length; i++) { const key = keys1[i]; if ( !Object.prototype.propertyIsEnumerable.call(obj2, key) || !deepEqual(values1[key], values2[key]) ) { return false; } } return true; } export function uint8ArrayToHexString(array: Uint8Array): string { return Array.prototype.map .call(array.reverse(), x => ('00' + x.toString(16)).slice(-2)) .join(''); } export function uint8ArrayToU128(array: Uint8Array): bigint { if (array.length != 16) { throw new Error(`Uint8Array is not 16 bytes long: ${array}`); } return new BinaryReader(array).readU128(); } export function uint8ArrayToU256(array: Uint8Array): bigint { if (array.length != 32) { throw new Error(`Uint8Array is not 32 bytes long: [${array}]`); } return new BinaryReader(array).readU256(); } export function hexStringToUint8Array(str: string): Uint8Array { if (str.startsWith('0x')) { str = str.slice(2); } const matches = str.match(/.{1,2}/g) || []; const data = Uint8Array.from( matches.map((byte: string) => parseInt(byte, 16)) ); return data.reverse(); } export function hexStringToU128(str: string): bigint { return uint8ArrayToU128(hexStringToUint8Array(str)); } export function hexStringToU256(str: string): bigint { return uint8ArrayToU256(hexStringToUint8Array(str)); } export function u128ToUint8Array(data: bigint): Uint8Array { const writer = new BinaryWriter(16); writer.writeU128(data); return writer.getBuffer(); } export function u128ToHexString(data: bigint): string { return uint8ArrayToHexString(u128ToUint8Array(data)); } export function u256ToUint8Array(data: bigint): Uint8Array { const writer = new BinaryWriter(32); writer.writeU256(data); return writer.getBuffer(); } export function u256ToHexString(data: bigint): string { return uint8ArrayToHexString(u256ToUint8Array(data)); } /** * Coerces a value that should be a `bigint` — but may arrive as a `number` * or decimal string after passing through JSON — into a `bigint`. * * Every other type is rejected up front: bare `BigInt()` would silently * accept booleans (`true` → `1n`), arrays (`[42]` → `42n`) and empty * strings (`'' ` → `0n`), turning malformed payloads into valid-looking * ids instead of failing early. * * @param value The value to coerce * @param what Type name used in the error message (e.g. `'ConnectionId'`) */ export function coerceToBigInt(value: unknown, what: string): bigint { if (typeof value === 'bigint') return value; if (typeof value === 'number') return BigInt(value); if (typeof value === 'string' && value.trim() !== '') return BigInt(value); throw new TypeError( `Cannot convert ${typeof value} to ${what}: expected bigint, integer number, or decimal string` ); } /** * Converts a string to PascalCase (UpperCamelCase). * @param str The string to convert * @returns The converted string */ export function toPascalCase(s: string): string { const str = toCamelCase(s); return str.charAt(0).toUpperCase() + str.slice(1); } /** * Type safe conversion from a string like "some_identifier-name" to "someIdentifierName". * @param str The string to convert * @returns The converted string */ export function toCamelCase(s: T): CamelCase { const str = s .replace(/[-_]+/g, '_') // collapse runs to a single separator (no backtracking issue) .replace(/_([a-zA-Z0-9])/g, (_, c) => c.toUpperCase()); return (str.charAt(0).toLowerCase() + str.slice(1)) as CamelCase; } /** Type safe conversion from a string like "some_Identifier-name" to "some_identifier_name". * @param str The string to convert * @returns The converted string */ export function toSnakeCase(str: T): SnakeCase { return str .replace(/([A-Z])/g, '_$1') // insert underscores before capitals .replace(/[-\s]+/g, '_') // replace spaces and dashes with underscores .toLowerCase() as SnakeCase; } export function bsatnBaseSize(typespace: Typespace, ty: AlgebraicType): number { const assumedArrayLength = 4; while (ty.tag === 'Ref') ty = typespace.types[ty.value]; if (ty.tag === 'Product') { let sum = 0; for (const { algebraicType: elem } of ty.value.elements) { sum += bsatnBaseSize(typespace, elem); } return sum; } else if (ty.tag === 'Sum') { let min = Infinity; for (const { algebraicType: vari } of ty.value.variants) { const vSize = bsatnBaseSize(typespace, vari); if (vSize < min) min = vSize; } if (min === Infinity) min = 0; return 4 + min; } else if (ty.tag == 'Array') { return 4 + assumedArrayLength * bsatnBaseSize(typespace, ty.value); } return { String: 4 + assumedArrayLength, Sum: 1, Bool: 1, I8: 1, U8: 1, I16: 2, U16: 2, I32: 4, U32: 4, F32: 4, I64: 8, U64: 8, F64: 8, I128: 16, U128: 16, I256: 32, U256: 32, }[ty.tag]; } export type CoerceTypeBuilder< Col extends TypeBuilder | ColumnBuilder, > = Col extends ColumnBuilder ? Col['typeBuilder'] : Col; export type CoerceParams = { [k in keyof Params & string]: CoerceTypeBuilder; }; export function coerceParams( params: Params ): CoerceParams { return Object.fromEntries( Object.entries(params).map(([n, c]) => [ n, 'typeBuilder' in c ? c.typeBuilder : c, ]) ) as CoerceParams; } export const hasOwn: ( o: object, k: K ) => o is K extends PropertyKey ? { [k in K]: unknown } : never = Object.hasOwn as any;