'use strict'; const ofetch = require('ofetch'); const cookieEs = require('cookie-es'); const destr = require('destr'); const defu = require('defu'); function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; } const destr__default = /*#__PURE__*/_interopDefaultCompat(destr); var __defProp$1 = Object.defineProperty; var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$1 = (obj, key, value) => { __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; class InterceptorManager { constructor() { __publicField$1(this, "handlers"); this.handlers = []; } /** * Add a new interceptor to the stack * * @param { (value: V) => T | Promise } onFulfilled The function to handle `then` for a `Promise` * @param { (error: any) => any } onRejected The function to handle `reject` for a `Promise` * * @return { number } An ID used to remove interceptor later */ use(onFulfilled, onRejected, options) { this.handlers.push({ onFulfilled, onRejected, synchronous: options ? options.synchronous : false, runWhen: options ? options.runWhen : void 0 }); return this.handlers.length - 1; } /** * Remove an interceptor from the stack * * @param { number } id The ID that was returned by `use` * * @returns { void } */ eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } } /** * Clear all interceptors from the stack * * @returns { void } */ clear() { if (this.handlers) { this.handlers = []; } } /** * Iterate over all the registered interceptors * * This method is particularly useful for skipping over any * interceptors that may have become `null` calling `eject`. * * @param { (fn: (handler: FetchInterceptorOptions) => void) } fn The function to call for each interceptor * * @returns { void } */ forEach(fn) { this.handlers.forEach((handler) => { if (handler !== null) { fn(handler); } }); } } const isBrowser = typeof window === "object"; function getCookies() { if (isBrowser) { return cookieEs.parse(document.cookie); } return {}; } function getCookie(key) { const cookies = getCookies(); const value = cookies[key] ? decodeURIComponent(cookies[key]) : void 0; return destr__default(value); } function isStreamable(body) { return typeof File !== "undefined" && body instanceof Blob || typeof File !== "undefined" && body instanceof File; } 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; }; var __accessCheck = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet = (obj, member, getter) => { __accessCheck(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet = (obj, member, value, setter) => { __accessCheck(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateMethod = (obj, member, method) => { __accessCheck(obj, member, "access private method"); return method; }; var _$fetch, _configDefaults, _createMethods, createMethods_fn, _dispatchRequest, dispatchRequest_fn, _uploadProgress, uploadProgress_fn, _downloadProgress, downloadProgress_fn, _addXSRFHeader, addXSRFHeader_fn; class FetchInstance { constructor(config = {}) { __privateAdd(this, _createMethods); __privateAdd(this, _dispatchRequest); __privateAdd(this, _uploadProgress); __privateAdd(this, _downloadProgress); __privateAdd(this, _addXSRFHeader); __privateAdd(this, _$fetch, void 0); __privateAdd(this, _configDefaults, void 0); __publicField(this, "interceptors"); __privateSet(this, _configDefaults, { xsrfCookieName: "XSRF-TOKEN", xsrfHeaderName: "X-XSRF-TOKEN", ...config }); this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() }; __privateSet(this, _$fetch, ofetch.$fetch); __privateMethod(this, _createMethods, createMethods_fn).call(this); } async native(request, config) { return typeof request === "string" ? this.request(request, { ...config, native: true }) : this.request({ ...request, native: true }); } async raw(request, config) { return typeof request === "string" ? this.request(request, { ...config, raw: true }) : this.request({ ...request, raw: true }); } async request(request, config) { if (typeof request === "string") { config = config || {}; config.url = request; } else { config = request; } config = defu.defu(config, __privateGet(this, _configDefaults)); config.method = config.method ? config.method.toUpperCase() : "GET"; if (/^https?/.test(config.url)) { delete config.baseURL; } const requestInterceptorChain = []; let synchronousRequestInterceptors = true; this.interceptors.request.forEach((interceptor) => { if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) { return; } synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; requestInterceptorChain.unshift(interceptor.onFulfilled, interceptor.onRejected); }); const responseInterceptorChain = []; this.interceptors.response.forEach((interceptor) => { responseInterceptorChain.push(interceptor.onFulfilled, interceptor.onRejected); }); let promise; let i = 0; let len; if (!synchronousRequestInterceptors) { const chain = [__privateMethod(this, _dispatchRequest, dispatchRequest_fn).bind(this), void 0]; chain.unshift.apply(chain, requestInterceptorChain); chain.push.apply(chain, responseInterceptorChain); len = chain.length; promise = Promise.resolve(config); while (i < len) { promise = promise.then(chain[i++], chain[i++]); } return promise; } len = requestInterceptorChain.length; let newConfig = config; i = 0; while (i < len) { const onFulfilled = requestInterceptorChain[i++]; const onRejected = requestInterceptorChain[i++]; try { newConfig = await onFulfilled?.(newConfig); } catch (error) { onRejected?.call(this, error); break; } } try { promise = __privateMethod(this, _dispatchRequest, dispatchRequest_fn).call(this, newConfig); } catch (error) { return Promise.reject(error); } i = 0; len = responseInterceptorChain.length; while (i < len) { promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); } return promise; } getFetch() { return __privateGet(this, _$fetch); } getDefaults() { return __privateGet(this, _configDefaults); } getBaseURL() { return __privateGet(this, _configDefaults).baseURL; } setBaseURL(baseURL) { __privateGet(this, _configDefaults).baseURL = baseURL; } setHeader(name, value) { __privateGet(this, _configDefaults).headers = __privateGet(this, _configDefaults)?.headers ? { ...__privateGet(this, _configDefaults).headers } : {}; if (!value) { delete __privateGet(this, _configDefaults).headers[name]; } else { __privateGet(this, _configDefaults).headers[name] = value; } } setToken(token, type) { const value = !token ? null : (type ? type + " " : "") + token; this.setHeader("Authorization", value); } onRequest(fn) { return this.interceptors.request.use((config) => fn(config) || config); } onResponse(fn) { return this.interceptors.response.use((response) => fn(response) || response); } onRequestError(fn) { return this.interceptors.request.use(void 0, (error) => fn(error) || Promise.reject(error)); } onResponseError(fn) { return this.interceptors.response.use(void 0, (error) => fn(error) || Promise.reject(error)); } create(options) { return createInstance({ ...this.getDefaults(), ...options }); } } _$fetch = new WeakMap(); _configDefaults = new WeakMap(); _createMethods = new WeakSet(); createMethods_fn = function() { for (const method of ["get", "head", "delete", "post", "put", "patch", "options"]) { Object.assign(this, { ["$" + method]: (request, config) => { return typeof request === "string" ? this.request(request, { ...config, method }) : this.request({ ...request, method }); }, [method]: (request, config) => { return typeof request === "string" ? this.raw(request, { ...config, method }) : this.raw({ ...request, method }); } }); } }; _dispatchRequest = new WeakSet(); dispatchRequest_fn = async function(config) { const controller = new AbortController(); const timeoutSignal = config.timeout ? setTimeout(() => controller.abort(), config.timeout) : void 0; const $ofetch = this.getFetch(); let response; config = config.timeout ? { ...config, signal: controller.signal } : config; config = __privateMethod(this, _addXSRFHeader, addXSRFHeader_fn).call(this, config); config.headers = removeDuplicateHeaders(config.headers); config.method = config.method ? config.method.toUpperCase() : "GET"; if (config.params) { config.params = serializeQuery(config.params); } if (config.query) { config.query = serializeQuery(config.query); } if (isStreamable(config.body) && typeof config.onUploadProgress === "function") { config = __privateMethod(this, _uploadProgress, uploadProgress_fn).call(this, config); } if (config.native) { delete config.native; response = fetch(config.url, { ...config }); if ((await response).body && typeof config.onDownloadProgress === "function" && typeof ReadableStream !== "undefined") { response = __privateMethod(this, _downloadProgress, downloadProgress_fn).call(this, await response, config); } } else if (config.raw) { delete config.raw; response = $ofetch.raw(config.url, { ...config }); } else { response = $ofetch(config.url, { ...config }); } if (config.timeout) { clearTimeout(timeoutSignal); } return response; }; _uploadProgress = new WeakSet(); uploadProgress_fn = function(config) { if (typeof Blob !== "undefined" && config.body instanceof Blob || typeof File !== "undefined" && config.body instanceof File) { let bytesUploaded = 0; const totalBytes = config.body.size; const trackProgress = new TransformStream({ start: () => { config.onUploadProgress?.({ total: totalBytes, loaded: 0 }); }, transform: (chunk, controller) => { controller.enqueue(chunk); bytesUploaded += chunk.byteLength; config.onUploadProgress?.({ total: totalBytes, loaded: bytesUploaded }); }, flush: () => { config.onUploadProgress?.({ total: totalBytes, loaded: totalBytes }); } }); config.body = config.body.stream().pipeThrough(trackProgress); config.duplex = "half"; } return config; }; _downloadProgress = new WeakSet(); downloadProgress_fn = async function(response, config) { const reader = response.body?.getReader(); let bytesUploaded = 0; const contentLength = response.headers.get("content-length"); const contentEncoding = response.headers.get("content-encoding"); const isCompressed = contentEncoding && !/^identity$/i.test(contentEncoding); const total = contentLength && !isCompressed ? parseInt(contentLength, 10) : void 0; const stream = new ReadableStream({ start(controller) { config.onDownloadProgress?.({ lengthComputable: typeof total !== "undefined", loaded: bytesUploaded, total }); (async function read() { const { done, value } = await reader.read(); if (done) { config.onDownloadProgress?.({ lengthComputable: typeof total !== "undefined", loaded: bytesUploaded, total }); controller.close(); return; } if (value) { bytesUploaded += value.length; config.onDownloadProgress?.({ lengthComputable: typeof total !== "undefined", loaded: bytesUploaded, total }); } controller.enqueue(value); read(); })(); } }); return new Response(stream, response); }; _addXSRFHeader = new WeakSet(); addXSRFHeader_fn = function(config) { const cookie = getCookie(config.xsrfCookieName); const cookies = getCookies(); if (config.credentials === "include" && config.xsrfCookieName && cookies[config.xsrfCookieName]) { config.headers[config.xsrfHeaderName] = decodeURIComponent(cookie); } return config; }; function serializeQuery(params) { const clean = [null, void 0, ""]; if (params) { Object.keys(params).forEach((key) => { if (clean.includes(params[key]) || Array.isArray(params[key]) && !params[key].length) { delete params[key]; } }); const queries = Object.fromEntries(Object.entries(params).map(([key, value]) => { if (Array.isArray(value)) { const uniqueArray = [...new Set(value)]; return [`${key}[]`, uniqueArray]; } return [key, value]; })); return queries; } return {}; } function removeDuplicateHeaders(headers) { const result = {}; const keys = Object.keys(headers); for (let i = keys.length - 1; i >= 0; i--) { const key = keys[i]; const lowerKey = key.toLowerCase(); if (!(lowerKey in result)) { result[lowerKey] = headers[key]; } } return result; } function createInstance(config) { return new FetchInstance(config); } const $fetch = createInstance; exports.$fetch = $fetch; exports.FetchInstance = FetchInstance; exports.createInstance = createInstance;