biketrack-app/node_modules/@ethersphere/bee-js/dist/mjs/utils/data.browser.js

108 lines
2.8 KiB
JavaScript

var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function (resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { isNodeReadable, isReadableStream } from "./stream.js";
/**
* Validates input and converts to Uint8Array
*
* @param data any string, ArrayBuffer or Uint8Array
*/
export function prepareData(data) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof data === 'string') return new Blob([data], {
type: 'text/plain'
});
if (data instanceof Uint8Array || data instanceof ArrayBuffer) {
return new Blob([data], {
type: 'application/octet-stream'
});
}
if (data instanceof Blob) {
return data;
} // Currently it is not possible to stream requests from browsers
// there are already first experiments on this field (Chromium)
// but till it is fully implemented across browsers-land we have to
// buffer the data before sending the requests.
if (isNodeReadable(data)) {
return new Promise(resolve => {
const buffers = [];
data.on('data', d => {
buffers.push(d);
});
data.on('end', () => {
resolve(new Blob(buffers, {
type: 'application/octet-stream'
}));
});
});
}
if (isReadableStream(data)) {
return new Promise(resolve => __awaiter(this, void 0, void 0, function* () {
const reader = data.getReader();
const buffers = [];
let done, value;
do {
;
({
done,
value
} = yield reader.read());
if (!done) {
buffers.push(value);
}
} while (!done);
resolve(new Blob(buffers, {
type: 'application/octet-stream'
}));
}));
}
throw new TypeError('unknown data type');
});
}
export function prepareWebsocketData(data) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof data === 'string') return new TextEncoder().encode(data);
if (data instanceof ArrayBuffer) return new Uint8Array(data);
if (data instanceof Blob) return new Uint8Array(yield new Response(data).arrayBuffer());
throw new TypeError('unknown websocket data type');
});
}