Change generateDeterministicUuid to be browser-compatible.

This commit is contained in:
Ivan Vasilov committed 2025-08-05 18:22:56 +02:00
1 parent fcd97979e5
commit 7ccfdc1bf8
1 file changed
+17 -6
+17 -6
View File
@@ -1,4 +1,3 @@
import crypto from 'crypto'
import fs from 'fs/promises'
import { compact } from 'lodash'
import path from 'path'
@@ -12,22 +11,34 @@ type DeepPartial<T> = T extends object
: T
import { SNIPPETS_DIR } from './snippets.constants'
/**
* Generates a deterministic UUID v4 from a string input
* @param input - The string to generate a UUID from
* @param inputs - The array of strings to generate a UUID from
* @returns A deterministic UUID v4 string
*/
export function generateDeterministicUuid(inputs: (string | null)[]): string {
const simpleHash = (str: string): number => {
let hash = 0
if (str.length === 0) return hash
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i)
hash = (hash << 5) - hash + char
hash = hash & hash // Convert to 32-bit integer
}
return Math.abs(hash)
}
const input = compact(inputs).join('_')
// Create a hash of the input string
const hash = crypto.createHash('sha256').update(input).digest()
// Create a deterministic random number generator using the hash as seed
let seed = simpleHash(input)
const rng = () => {
const bytes = new Uint8Array(16)
for (let i = 0; i < 16; i++) {
bytes[i] = hash[i % hash.length]
// Simple LCG (Linear Congruential Generator) for deterministic randomness
seed = (seed * 1103515245 + 12345) & 0x7fffffff
bytes[i] = (seed >>> 16) & 0xff
}
return Array.from(bytes)
}