import { NIL } from 'uuid'; // custom implementation of stringify, as provided uuid's are not valid according to RFC4122 const stringify = (buffer: Buffer | null): string => { if (buffer === null) { return NIL; } if (buffer.length != 16) { throw new Error('Invalid buffer length for uuid: ' + buffer.length); } if (buffer.equals(Buffer.alloc(16))) { return NIL; // If buffer is all zeros, return zero'd uuid } const hex = buffer.toString('hex'); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; }; const parseUuid = (uuid: string): Buffer => { const uuidTester = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i; if (!uuidTester.test(uuid)) { throw new Error('Invalid UUID'); } return Buffer.from(uuid.replaceAll('-', ''), 'hex'); }; export const uuidTransformer = { to(uuid: string): Buffer { return parseUuid(uuid); }, from(bin: Buffer | null): string { return stringify(bin); }, };