UNPKG

one

Version:

One is a React framework for web, iOS, and Android apps.

433 lines (430 loc) • 14.7 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var index_native_exports = {}; __export(index_native_exports, { installFetch: () => installFetch }); module.exports = __toCommonJS(index_native_exports); var import_BlobManager = __toESM(require("react-native/Libraries/Blob/BlobManager"), 1); var import_react_native = require("react-native"); var import_react_native_nitro_modules = require("react-native-nitro-modules"); function _class_call_check(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _create_class(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _define_property(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true }); } else obj[key] = value; return obj; } var hybrid; var BlobManager = import_BlobManager.default; function native() { hybrid !== null && hybrid !== void 0 ? hybrid : hybrid = import_react_native_nitro_modules.NitroModules.createHybridObject("OneFetch"); return hybrid; } var lastId = 0; function bufferOf(view) { var { buffer, byteOffset, byteLength } = view; if (!(buffer instanceof ArrayBuffer)) { throw new TypeError("fetch: a body backed by a SharedArrayBuffer is not supported"); } return buffer.slice(byteOffset, byteOffset + byteLength); } function blobRef(blob) { var data = Reflect.get(blob, "data"); if (typeof data !== "object" || data === null || !("blobId" in data) || typeof data.blobId !== "string" || !("offset" in data) || typeof data.offset !== "number") { throw new TypeError("fetch: the Blob body is not a React Native blob"); } return { blobId: data.blobId, offset: data.offset, size: blob.size }; } function formParts(form) { var entries = Reflect.get(form, "_parts"); if (!Array.isArray(entries)) { throw new TypeError("fetch: the FormData body is not a React Native FormData"); } return entries.map(function(entry) { var [name, value] = entry; if (typeof name !== "string") throw new TypeError("fetch: a FormData name must be a string"); if (value instanceof Blob) { var filename = Reflect.get(value, "name"); return { name, blob: blobRef(value), filename: typeof filename === "string" ? filename : "blob", type: value.type || "application/octet-stream" }; } if (typeof value === "object" && value !== null && "uri" in value) { if (typeof value.uri !== "string") throw new TypeError("fetch: a FormData uri must be a string"); var filename1 = "name" in value && typeof value.name === "string" ? value.name : void 0; var type = "type" in value && typeof value.type === "string" ? value.type : void 0; return { name, uri: value.uri, filename: filename1, type }; } return { name, value: String(value) }; }); } function encode(body) { if (typeof body === "string") { return { native: { body: bufferOf(new TextEncoder().encode(body)) }, type: "text/plain;charset=UTF-8" }; } if (body instanceof URLSearchParams) { return { native: { body: bufferOf(new TextEncoder().encode(body.toString())) }, type: "application/x-www-form-urlencoded;charset=UTF-8" }; } if (body instanceof ArrayBuffer) return { native: { body: body.slice(0) } }; if (ArrayBuffer.isView(body)) return { native: { body: bufferOf(body) } }; if (body instanceof Blob) { return { native: { blob: blobRef(body) }, type: body.type || void 0 }; } if (body instanceof FormData) { var boundary = `----OneFormBoundary${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`; return { native: { form: formParts(body), boundary }, type: `multipart/form-data; boundary=${boundary}`, forceType: true }; } throw new TypeError("fetch: body must be a string, URLSearchParams, ArrayBuffer, typed array, Blob or FormData"); } function hasBody(method, status) { return method !== "HEAD" && status !== 204 && status !== 205 && status !== 304; } function concat(chunks) { var length = 0; var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = void 0; try { for (var _iterator = chunks[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var chunk = _step.value; length += chunk.byteLength; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return != null) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } var bytes = new Uint8Array(length); var offset = 0; var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = void 0; try { for (var _iterator1 = chunks[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true) { var chunk1 = _step1.value; bytes.set(chunk1, offset); offset += chunk1.byteLength; } } catch (err) { _didIteratorError1 = true; _iteratorError1 = err; } finally { try { if (!_iteratorNormalCompletion1 && _iterator1.return != null) { _iterator1.return(); } } finally { if (_didIteratorError1) { throw _iteratorError1; } } } return bytes; } var StreamingResponse = /* @__PURE__ */ (function() { "use strict"; function StreamingResponse2(head, body) { _class_call_check(this, StreamingResponse2); _define_property(this, "type", "default"); _define_property(this, "ok", void 0); _define_property(this, "status", void 0); _define_property(this, "statusText", void 0); _define_property(this, "url", void 0); _define_property(this, "redirected", void 0); _define_property(this, "headers", void 0); _define_property(this, "body", void 0); this.status = head.status; this.ok = head.status >= 200 && head.status < 300; this.statusText = head.statusText; this.url = head.url; this.redirected = head.redirected; this.headers = head.headers; this.body = body; } _create_class(StreamingResponse2, [ { key: "bodyUsed", get: function get() { var _ref; var _this_body; return (_ref = (_this_body = this.body) === null || _this_body === void 0 ? void 0 : _this_body.locked) !== null && _ref !== void 0 ? _ref : false; } }, { key: "bytes", value: async function bytes() { if (!this.body) return new Uint8Array(0); if (this.body.locked) throw new TypeError("Already read"); var reader = this.body.getReader(); var chunks = []; for (;;) { var { done, value } = await reader.read(); if (done) return concat(chunks); chunks.push(value); } } }, { key: "arrayBuffer", value: async function arrayBuffer() { return bufferOf(await this.bytes()); } }, { key: "text", value: async function text() { return new TextDecoder().decode(await this.bytes()); } }, { key: "json", value: async function json() { return JSON.parse(await this.text()); } }, { key: "blob", value: (async function blob() { var _this_headers_get; var bytes = await this.bytes(); var blobId = native().storeBlob(bufferOf(bytes)); return BlobManager.createFromOptions({ blobId, offset: 0, size: bytes.byteLength, type: (_this_headers_get = this.headers.get("content-type")) !== null && _this_headers_get !== void 0 ? _this_headers_get : "", lastModified: Date.now() }); }) }, { key: "formData", value: (async function formData() { var form = new FormData(); new URLSearchParams(await this.text()).forEach(function(value, name) { form.append(name, value); }); return form; }) }, { key: "clone", value: function clone() { if (this.bodyUsed) throw new TypeError("Already read"); var head = { ...this, headers: new Headers(this.headers) }; if (!this.body) return new StreamingResponse2(head, null); var [mine, theirs] = this.body.tee(); Reflect.set(this, "body", mine); return new StreamingResponse2(head, theirs); } } ]); return StreamingResponse2; })(); function abortReason(signal) { var _signal_reason; return (_signal_reason = signal.reason) !== null && _signal_reason !== void 0 ? _signal_reason : Object.assign(new Error("Aborted"), { name: "AbortError" }); } async function fetch(input) { var init = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; var _init_signal, _ref, _init_method, _init_headers, _init_credentials, _init_body; var request = input instanceof Request ? input : void 0; var signal = (_init_signal = init.signal) !== null && _init_signal !== void 0 ? _init_signal : request === null || request === void 0 ? void 0 : request.signal; if (signal === null || signal === void 0 ? void 0 : signal.aborted) throw abortReason(signal); var url = request ? request.url : String(input); var method = ((_ref = (_init_method = init.method) !== null && _init_method !== void 0 ? _init_method : request === null || request === void 0 ? void 0 : request.method) !== null && _ref !== void 0 ? _ref : "GET").toUpperCase(); var headers = new Headers((_init_headers = init.headers) !== null && _init_headers !== void 0 ? _init_headers : request === null || request === void 0 ? void 0 : request.headers); var credentials = (_init_credentials = init.credentials) !== null && _init_credentials !== void 0 ? _init_credentials : request === null || request === void 0 ? void 0 : request.credentials; var body = (_init_body = init.body) !== null && _init_body !== void 0 ? _init_body : request ? Reflect.get(request, "_bodyInit") : void 0; var nativeBody = {}; if (body != null) { if (method === "GET" || method === "HEAD") { throw new TypeError(`fetch: a ${method} request cannot have a body`); } var encoded = encode(body); nativeBody = encoded.native; if (encoded.type && (encoded.forceType || !headers.has("content-type"))) { headers.set("content-type", encoded.type); } } var list = []; headers.forEach(function(value, name) { list.push({ name, value }); }); return new Promise(function(resolve, reject) { var id = ++lastId; var controller; var response; var settled = false; var settle = function settle2() { settled = true; signal === null || signal === void 0 ? void 0 : signal.removeEventListener("abort", onAbort); }; var fail = function fail2(error) { settle(); if (response) controller === null || controller === void 0 ? void 0 : controller.error(error); else reject(error); }; var onAbort = function onAbort2() { if (settled || !signal) return; native().cancel(id); fail(abortReason(signal)); }; signal === null || signal === void 0 ? void 0 : signal.addEventListener("abort", onAbort); native().start(id, { url, method, headers: list, ...nativeBody, omitCredentials: credentials === "omit" }, function(head) { if (settled) return; var responseHeaders = new Headers(); var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = void 0; try { for (var _iterator = head.headers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var { name, value } = _step.value; responseHeaders.append(name, value); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return != null) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } var stream = hasBody(method, head.status) ? new ReadableStream({ start(streamController) { controller = streamController; }, cancel() { if (settled) return; settle(); native().cancel(id); } }) : null; response = new StreamingResponse({ ...head, headers: responseHeaders }, stream); resolve(response); }, function(chunk) { if (!settled) controller === null || controller === void 0 ? void 0 : controller.enqueue(new Uint8Array(chunk)); }, function() { if (settled) return; settle(); controller === null || controller === void 0 ? void 0 : controller.close(); }, function(message) { if (!settled) fail(new TypeError(`Network request failed: ${message}`)); }); }); } function installFetch() { if (!import_react_native_nitro_modules.NitroModules.hasHybridObject("OneFetch")) return; if (typeof globalThis.Headers !== "function" || typeof globalThis.Request !== "function" || typeof globalThis.Response !== "function") { throw new Error("fetch: react native's Headers, Request and Response must be installed before One's fetch"); } Object.setPrototypeOf(StreamingResponse.prototype, globalThis.Response.prototype); if (import_react_native.Platform.OS === "ios") import_react_native.NativeModules.OneFetchBlobStore.install(); Object.defineProperty(globalThis, "fetch", { value: fetch, writable: true, configurable: true, enumerable: true }); } //# sourceMappingURL=index.native.js.map