35 lines
1.0 KiB
TypeScript
35 lines
1.0 KiB
TypeScript
|
|
/**
|
||
|
|
* Shared buffer utilities for consistent binary data handling across all registry types.
|
||
|
|
*
|
||
|
|
* This module addresses the common issue where `Buffer.isBuffer(Uint8Array)` returns `false`,
|
||
|
|
* which can cause data handling bugs when binary data arrives as Uint8Array instead of Buffer.
|
||
|
|
*/
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Check if value is binary data (Buffer or Uint8Array)
|
||
|
|
*/
|
||
|
|
export function isBinaryData(value: unknown): value is Buffer | Uint8Array {
|
||
|
|
return Buffer.isBuffer(value) || value instanceof Uint8Array;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Convert any binary-like data to Buffer.
|
||
|
|
* Handles Buffer, Uint8Array, string, and objects.
|
||
|
|
*
|
||
|
|
* @param data - The data to convert to Buffer
|
||
|
|
* @returns A Buffer containing the data
|
||
|
|
*/
|
||
|
|
export function toBuffer(data: unknown): Buffer {
|
||
|
|
if (Buffer.isBuffer(data)) {
|
||
|
|
return data;
|
||
|
|
}
|
||
|
|
if (data instanceof Uint8Array) {
|
||
|
|
return Buffer.from(data);
|
||
|
|
}
|
||
|
|
if (typeof data === 'string') {
|
||
|
|
return Buffer.from(data, 'utf-8');
|
||
|
|
}
|
||
|
|
// Fallback: serialize object to JSON
|
||
|
|
return Buffer.from(JSON.stringify(data));
|
||
|
|
}
|