fix(core): Normalize binary data handling across registries and add buffer helpers
This commit is contained in:
34
ts/core/helpers.buffer.ts
Normal file
34
ts/core/helpers.buffer.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* 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));
|
||||
}
|
||||
Reference in New Issue
Block a user