@huggingface/blob
Version:
Utilities to convert URLs and files to Blobs, internally used by Hugging Face libs
89 lines (84 loc) • 2.79 kB
JavaScript
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
// src/utils/WebBlob.ts
var WebBlob = class extends Blob {
constructor(url, start, end, contentType, full, customFetch) {
super([]);
__publicField(this, "url");
__publicField(this, "start");
__publicField(this, "end");
__publicField(this, "contentType");
__publicField(this, "full");
__publicField(this, "fetch");
this.url = url;
this.start = start;
this.end = end;
this.contentType = contentType;
this.full = full;
this.fetch = customFetch;
}
static async create(url, opts) {
var _a, _b;
const customFetch = (_a = opts == null ? void 0 : opts.fetch) != null ? _a : fetch;
const response = await customFetch(url, { method: "HEAD" });
const size = Number(response.headers.get("content-length"));
const contentType = response.headers.get("content-type") || "";
const supportRange = response.headers.get("accept-ranges") === "bytes";
if (!supportRange || size < ((_b = opts == null ? void 0 : opts.cacheBelow) != null ? _b : 1e6)) {
return await (await customFetch(url)).blob();
}
return new WebBlob(url, 0, size, contentType, true, customFetch);
}
get size() {
return this.end - this.start;
}
get type() {
return this.contentType;
}
slice(start = 0, end = this.size) {
if (start < 0 || end < 0) {
new TypeError("Unsupported negative start/end on FileBlob.slice");
}
const slice = new WebBlob(
this.url,
this.start + start,
Math.min(this.start + end, this.end),
this.contentType,
start === 0 && end === this.size ? this.full : false,
this.fetch
);
return slice;
}
async arrayBuffer() {
const result = await this.fetchRange();
return result.arrayBuffer();
}
async text() {
const result = await this.fetchRange();
return result.text();
}
stream() {
const stream = new TransformStream();
this.fetchRange().then((response) => {
var _a;
return (_a = response.body) == null ? void 0 : _a.pipeThrough(stream);
}).catch((error) => stream.writable.abort(error.message));
return stream.readable;
}
fetchRange() {
const fetch2 = this.fetch;
if (this.full) {
return fetch2(this.url);
}
return fetch2(this.url, {
headers: {
Range: `bytes=${this.start}-${this.end - 1}`
}
});
}
};
exports.WebBlob = WebBlob;