const isTypedArray = (value) => {
    return value instanceof Float32Array || value instanceof Float64Array;
};
const toNumber = (value) => {
    if (typeof value === 'number') {
        return value;
    }
    if (typeof value === 'bigint') {
        return Number(value);
    }
    if (typeof value === 'string') {
        const parsed = Number(value);
        if (!Number.isNaN(parsed)) {
            return parsed;
        }
    }
    throw new Error('Encountered non-numeric value while converting tensor output');
};
const mapToNumberArray = (collection) => collection.map((item) => toNumber(item));
export const normalizeVector = (vector) => {
    let sumOfSquares = 0;
    for (const value of vector) {
        sumOfSquares += value * value;
    }
    if (sumOfSquares === 0) {
        return vector.map(() => 0);
    }
    const norm = Math.sqrt(sumOfSquares);
    return vector.map((value) => value / norm);
};
export const normalizeVectors = (vectors) => vectors.map((vector) => normalizeVector(vector));
export const tensorToVectors = (tensor) => {
    if (!tensor) {
        throw new Error('Received empty embedding tensor');
    }
    if (typeof tensor.tolist === 'function') {
        const raw = tensor.tolist();
        return tensorToVectors(raw);
    }
    if (Array.isArray(tensor)) {
        if (tensor.length === 0) {
            return [];
        }
        if (Array.isArray(tensor[0])) {
            return tensor.map((vector) => mapToNumberArray(vector));
        }
        return [mapToNumberArray(tensor)];
    }
    if (isTypedArray(tensor)) {
        return [Array.from(tensor, (value) => Number(value))];
    }
    throw new Error('Unsupported embedding tensor output');
};
export const tensorToVector = (tensor) => {
    const vectors = tensorToVectors(tensor);
    if (vectors.length === 0) {
        throw new Error('Embedding tensor did not contain any vectors');
    }
    return vectors[0];
};
//# sourceMappingURL=embeddings.js.map