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

78 lines
2.3 KiB
JavaScript
Raw Normal View History

2022-07-11 10:27:11 +02:00
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 BlobPolyfill from 'fetch-blob';
import { isNodeReadable, isReadableStream, readableWebToNode } from "./stream.js";
/**
* Prepare data for valid input for node-fetch.
*
* node-fetch is not using WHATWG ReadableStream but NodeJS Readable so we need to convert in case of ReadableStream,
* but the typings are set to use ReadableStream so hence why type conversion here.
*
* @param data any string, ArrayBuffer, Uint8Array or Readable
*/
export function prepareData(data) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof data === 'string') return new BlobPolyfill([data], {
type: 'text/plain'
});
if (data instanceof Uint8Array || data instanceof ArrayBuffer) {
return new BlobPolyfill([data], {
type: 'application/octet-stream'
});
}
if (data instanceof BlobPolyfill || isNodeReadable(data)) return data;
if (isReadableStream(data)) {
return readableWebToNode(data);
}
throw new TypeError('unknown data type');
});
}
function isBufferArray(buffer) {
return Array.isArray(buffer) && buffer.length > 0 && buffer.every(data => data instanceof Buffer);
}
export function prepareWebsocketData(data) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof data === 'string') return new TextEncoder().encode(data);
if (data instanceof Buffer) return new Uint8Array(data);
if (data instanceof ArrayBuffer) return new Uint8Array(data);
if (isBufferArray(data)) return new Uint8Array(Buffer.concat(data));
throw new TypeError('unknown websocket data type');
});
}