|
| 1 | +import * as Hash from 'typestub-ipfs-only-hash'; |
| 2 | + |
| 3 | +export type IpfsCidV0 = `Qm${string}`; |
| 4 | + |
| 5 | +type SupportedInput = string | Uint8Array | ArrayBuffer | ArrayBufferView; |
| 6 | + |
| 7 | +// Ensure string inputs are encoded without relying on Node's global Buffer, falling back to util.TextEncoder when needed. |
| 8 | +const encodeString = (value: string): Uint8Array => { |
| 9 | + if (typeof TextEncoder !== 'undefined') { |
| 10 | + return new TextEncoder().encode(value); |
| 11 | + } |
| 12 | + |
| 13 | + try { |
| 14 | + // eslint-disable-next-line @typescript-eslint/no-var-requires |
| 15 | + const { TextEncoder: NodeTextEncoder } = require('util'); |
| 16 | + return new NodeTextEncoder().encode(value); |
| 17 | + } catch (error) { |
| 18 | + throw new Error('TextEncoder is not available in this environment'); |
| 19 | + } |
| 20 | +}; |
| 21 | + |
| 22 | +const toUint8Array = (value: ArrayBuffer | ArrayBufferView): Uint8Array => { |
| 23 | + // TypedArray/DataView instances expose a shared buffer; slice the relevant window into a standalone Uint8Array. |
| 24 | + if (ArrayBuffer.isView(value)) { |
| 25 | + return new Uint8Array(value.buffer, value.byteOffset, value.byteLength); |
| 26 | + } |
| 27 | + |
| 28 | + return new Uint8Array(value); |
| 29 | +}; |
| 30 | + |
| 31 | +const normalizeInput = (input: SupportedInput): Uint8Array => { |
| 32 | + // Accommodate all portable input shapes while keeping the helper tree-shakeable and browser-friendly. |
| 33 | + if (typeof input === 'string') { |
| 34 | + return encodeString(input); |
| 35 | + } |
| 36 | + |
| 37 | + if (input instanceof Uint8Array) { |
| 38 | + return input; |
| 39 | + } |
| 40 | + |
| 41 | + if (typeof ArrayBuffer !== 'undefined') { |
| 42 | + if (input instanceof ArrayBuffer) { |
| 43 | + return toUint8Array(input); |
| 44 | + } |
| 45 | + |
| 46 | + if (ArrayBuffer.isView(input)) { |
| 47 | + return toUint8Array(input); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + throw new TypeError( |
| 52 | + 'Input must be provided as a string, Uint8Array, ArrayBuffer or ArrayBufferView' |
| 53 | + ); |
| 54 | +}; |
| 55 | + |
| 56 | +/** |
| 57 | + * Generate a CIDv0 IPFS identifier for the provided content. |
| 58 | + */ |
| 59 | +export const getIpfsId = async (input: SupportedInput): Promise<IpfsCidV0> => { |
| 60 | + const normalizedInput = normalizeInput(input); |
| 61 | + const hashOf = Hash.of as unknown as ( |
| 62 | + value: string | Uint8Array |
| 63 | + ) => Promise<string>; |
| 64 | + const cid = await hashOf(normalizedInput); |
| 65 | + |
| 66 | + if (!cid.startsWith('Qm')) { |
| 67 | + throw new Error('Generated IPFS CID is not CIDv0'); |
| 68 | + } |
| 69 | + |
| 70 | + return cid as IpfsCidV0; |
| 71 | +}; |
0 commit comments