diff --git a/packages/core/src/adapter/node.ts b/packages/core/src/adapter/node.ts index c50a210..46dd0ec 100644 --- a/packages/core/src/adapter/node.ts +++ b/packages/core/src/adapter/node.ts @@ -3,6 +3,7 @@ import { basename } from 'node:path' import FileType from 'file-type' import { FileResponse } from '../index.js' import { readFile } from 'node:fs/promises' +import { Binary } from 'cosmokit' export { lookup } from 'node:dns/promises' @@ -10,9 +11,12 @@ export async function loadFile(url: string): Promise { if (url.startsWith('file://')) { const data = await readFile(fileURLToPath(url)) const result = await FileType.fromBuffer(data) - // https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer#answer-31394257 - const buffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) - return { mime: result?.mime, filename: basename(url), data: buffer } + return { + type: result?.mime!, + mime: result?.mime, + filename: basename(url), + data: Binary.fromSource(data), + } } } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 91374f1..7af0a86 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -122,6 +122,8 @@ export interface FileConfig { } export interface FileResponse { + type: string + /** @deprecated use `type` instead */ mime?: string filename: string data: ArrayBuffer @@ -384,20 +386,20 @@ export class HTTP extends Service { if (result) return result const capture = /^data:([\w/-]+);base64,(.*)$/.exec(url) if (capture) { - const [, mime, base64] = capture + const [, type, base64] = capture let name = 'file' - const ext = mime && mimedb[mime]?.extensions?.[0] + const ext = type && mimedb[type]?.extensions?.[0] if (ext) name += `.${ext}` - return { mime, data: Binary.fromBase64(base64), filename: name } + return { type, mime: type, data: Binary.fromBase64(base64), filename: name } } const { headers, data, url: responseUrl } = await this(url, { method: 'GET', responseType: 'arraybuffer', timeout: +options.timeout! || undefined, }) - const mime = headers.get('content-type') ?? undefined + const type = headers.get('content-type')! const [, name] = responseUrl.match(/.+\/([^/?]*)(?=\?)?/)! - return { mime, filename: name, data } + return { type, mime: type, filename: name, data } } async isLocal(url: string) {