UNPKG

ym-userequest

Version:
1,372 lines (1,371 loc) 58.4 kB
"use strict"; function _array_like_to_array(arr, len) { if (len == null || len > arr.length) len = arr.length; for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i]; return arr2; } function _array_without_holes(arr) { if (Array.isArray(arr)) return _array_like_to_array(arr); } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _async_to_generator(fn) { return function() { var self = this, args = arguments; return new Promise(function(resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _define_property(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _iterable_to_array(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _non_iterable_spread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _object_spread(target) { for(var i = 1; i < arguments.length; i++){ var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === "function") { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function(key) { _define_property(target, key, source[key]); }); } return target; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function(sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _object_spread_props(target, source) { source = source != null ? source : {}; if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function(key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _object_without_properties(source, excluded) { if (source == null) return {}; var target = _object_without_properties_loose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for(i = 0; i < sourceSymbolKeys.length; i++){ key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _object_without_properties_loose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for(i = 0; i < sourceKeys.length; i++){ key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _to_consumable_array(arr) { return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread(); } function _type_of(obj) { "@swc/helpers - typeof"; return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; } function _unsupported_iterable_to_array(o, minLen) { if (!o) return; if (typeof o === "string") return _array_like_to_array(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen); } function _ts_generator(thisArg, body) { var f, y, t, g, _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function(v) { return step([ n, v ]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while(_)try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [ op[0] & 2, t.value ]; switch(op[0]){ case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [ 0 ]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [ 6, e ]; y = 0; } finally{ f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var _window; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = function(target, all) { for(var name in all)__defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = function(to, from, except, desc) { if (from && (typeof from === "undefined" ? "undefined" : _type_of(from)) === "object" || typeof from === "function") { var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined; try { var _loop = function() { var key = _step.value; if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: function() { return from[key]; }, enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); }; for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop(); } catch (err) { _didIteratorError = true; _iteratorError = err; } finally{ try { if (!_iteratorNormalCompletion && _iterator.return != null) { _iterator.return(); } } finally{ if (_didIteratorError) { throw _iteratorError; } } } } return to; }; var __toCommonJS = function(mod) { return __copyProps(__defProp({}, "__esModule", { value: true }), mod); }; // lib/index.ts var lib_exports = {}; __export(lib_exports, { TypeChecker: function() { return TypeChecker; }, clearCache: function() { return clearCache; }, debounce: function() { return debounce_default; }, definePlugins: function() { return definePlugins; }, getCache: function() { return getCache; }, getRequest: function() { return getRequest; }, setCache: function() { return setCache; }, throttle: function() { return throttle_default; }, trigger: function() { return trigger; }, useRequest: function() { return useRequest; }, useRequestConfig: function() { return useRequestConfig; }, wrappedPromise: function() { return wrappedPromise; } }); module.exports = __toCommonJS(lib_exports); // lib/requestMap.ts var requestInstances = /* @__PURE__ */ new Map(); function setRequest(id, requestInstance) { requestInstances.set(id, requestInstance); } function getRequest(id) { return requestInstances.get(id); } function removeRequest(id) { return requestInstances.delete(id); } // lib/utils/index.ts var import_vue = require("vue"); function useDelay(fn, delay) { if (delay) { return setTimeout(function() { fn(); }, delay); } else { fn(); } } var isNonZeroFalsy = function(value) { return !TypeChecker.isNumber(value) && !value; }; var unrefParms = function(value) { var _value = (0, import_vue.unref)(value); return TypeChecker.isArray(_value) ? _value : [ _value ]; }; var TYPE_MAP = { null: "null", undefined: "undefined", object: "object", array: "array", string: "string", number: "number", boolean: "boolean", function: "function", regexp: "regexp", date: "date", error: "error", symbol: "symbol", bigint: "bigint" }; var getType = function(o) { var _s_match; var s = Object.prototype.toString.call(o); return (_s_match = s.match(/\[object (.*?)\]/)) === null || _s_match === void 0 ? void 0 : _s_match[1].toLowerCase(); }; var createTypeChecker = function(expectedType) { return function(v) { return getType(v) === expectedType; }; }; var isNull = createTypeChecker(TYPE_MAP.null); var isUndefined = createTypeChecker(TYPE_MAP.undefined); var isObject = createTypeChecker(TYPE_MAP.object); var isArray = createTypeChecker(TYPE_MAP.array); var isString = createTypeChecker(TYPE_MAP.string); var isNumber = createTypeChecker(TYPE_MAP.number); var isBoolean = createTypeChecker(TYPE_MAP.boolean); var isFunction = createTypeChecker(TYPE_MAP.function); var isRegExp = createTypeChecker(TYPE_MAP.regexp); var isDate = createTypeChecker(TYPE_MAP.date); var isError = createTypeChecker(TYPE_MAP.error); var isSymbol = createTypeChecker(TYPE_MAP.symbol); var isBigInt = createTypeChecker(TYPE_MAP.bigint); var isPromise = function(v) { return Boolean(v && typeof v.then === "function"); }; var isEmpty = function(v) { if (isNull(v) || isUndefined(v)) return true; if (isString(v) || isArray(v)) return v.length === 0; if (isObject(v)) return Object.keys(v).length === 0; if (isNumber(v)) return isNaN(v); return false; }; var TypeChecker = { isNull: isNull, isUndefined: isUndefined, isObject: isObject, isArray: isArray, isString: isString, isNumber: isNumber, isBoolean: isBoolean, isFunction: isFunction, isRegExp: isRegExp, isDate: isDate, isError: isError, isSymbol: isSymbol, isBigInt: isBigInt, isPromise: isPromise, isEmpty: isEmpty }; function limit(fn, timespan) { var pending = false; return function() { for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){ args[_key] = arguments[_key]; } if (pending) return; pending = true; fn.apply(void 0, _to_consumable_array(args)); setTimeout(function() { pending = false; }, timespan); }; } function wrappedPromise(service, call) { return /*#__PURE__*/ _async_to_generator(function() { var _len, args, _key, result; var _arguments = arguments; return _ts_generator(this, function(_state) { switch(_state.label){ case 0: for(_len = _arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){ args[_key] = _arguments[_key]; } return [ 4, service.apply(void 0, _to_consumable_array(args)) ]; case 1: result = _state.sent(); return [ 2, call(result, args) ]; } }); }); } // lib/utils/debounce.ts function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime; var lastInvokeTime = 0; var leading = false; var maxing = false; var trailing = true; var useRAF = !wait && wait !== 0 && window && typeof window.requestAnimationFrame === "function"; if (typeof func !== "function") { throw new TypeError("Expected a function"); } wait = +wait || 0; if (options && TypeChecker.isObject(options)) { leading = !!options.leading; maxing = "maxWait" in options; maxWait = maxing ? Math.max(+options.maxWait || 0, wait) : maxWait; trailing = "trailing" in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs; var thisArg = lastThis; lastArgs = lastThis = void 0; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function startTimer(pendingFunc, wait2) { if (useRAF) { window.cancelAnimationFrame(timerId); return window.requestAnimationFrame(pendingFunc); } return setTimeout(pendingFunc, wait2); } function cancelTimer(id) { if (useRAF) { return window.cancelAnimationFrame(id); } clearTimeout(id); } function leadingEdge(time) { lastInvokeTime = time; timerId = startTimer(timerExpired, wait); return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime; var timeSinceLastInvoke = time - lastInvokeTime; var timeWaiting = wait - timeSinceLastCall; return maxing ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime; var timeSinceLastInvoke = time - lastInvokeTime; return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; } function timerExpired() { var time = Date.now(); if (shouldInvoke(time)) { return trailingEdge(time); } timerId = startTimer(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = void 0; if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = void 0; return result; } function cancel() { if (timerId !== void 0) { cancelTimer(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = void 0; } function flush() { return timerId === void 0 ? result : trailingEdge(Date.now()); } function pending() { return timerId !== void 0; } function debounced() { for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){ args[_key] = arguments[_key]; } var time = Date.now(); var isInvoking = shouldInvoke(time); lastArgs = args; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === void 0) { return leadingEdge(lastCallTime); } if (maxing) { timerId = startTimer(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === void 0) { timerId = startTimer(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; debounced.pending = pending; return debounced; } var debounce_default = debounce; // lib/utils/throttle.ts function throttle(func, wait, options) { var leading = true; var trailing = true; if (typeof func !== "function") { throw new TypeError("Expected a function"); } if (options && TypeChecker.isObject(options)) { leading = "leading" in options ? !!options.leading : leading; trailing = "trailing" in options ? !!options.trailing : trailing; } return debounce_default(func, wait, { leading: leading, trailing: trailing, maxWait: wait }); } var throttle_default = throttle; // lib/utils/cache.ts var cache = /* @__PURE__ */ new Map(); var setCache = function(key, value, cacheTime) { var currentCache = cache.get(key); if (currentCache === null || currentCache === void 0 ? void 0 : currentCache.timer) { clearTimeout(currentCache.time); } var timer; if (cacheTime > -1) { timer = setTimeout(function() { cache.delete(key); }, cacheTime); } cache.set(key, _object_spread_props(_object_spread({}, value), { timer: timer })); }; var getCache = function(key) { return cache.get(key); }; var clearCache = function(key) { if (key) { var cachedKeys = Array.isArray(key) ? key : [ key ]; cachedKeys.forEach(function(cachedKey) { return cache.delete(cachedKey); }); } else { cache.clear(); } }; // lib/utils/cacheSubscribe.ts var listeners = {}; var trigger = function(key, data) { if (listeners[key]) { listeners[key].forEach(function(item) { return item(data); }); } }; var subscribe = function(key, listener) { if (!listeners[key]) { listeners[key] = []; } listeners[key].push(listener); return function() { var index = listeners[key].indexOf(listener); listeners[key].splice(index, 1); }; }; // lib/usePlugins.ts var import_vue3 = require("vue"); // lib/createInstance.ts var import_vue2 = require("vue"); function createInstance(service, options) { var _functionContext, _functionContext1; var defaultData = options.defaultData, defaultParams = options.defaultParams, onBefore = options.onBefore, onRequest = options.onRequest, onSuccess = options.onSuccess, onError = options.onError, onFinally = options.onFinally, onCancel = options.onCancel, onCache = options.onCache; var data = (0, import_vue2.isRef)(defaultData) ? defaultData : (0, import_vue2.ref)(defaultData); var loading = (0, import_vue2.ref)(false); var params = (0, import_vue2.ref)(defaultParams); var pollingCount = (0, import_vue2.ref)(0); var error = (0, import_vue2.shallowRef)(); var status = (0, import_vue2.ref)(); var plugins = (0, import_vue2.ref)([]); var count = (0, import_vue2.ref)(0); var callPlugin = function(type) { for(var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){ args[_key - 1] = arguments[_key]; } var _Object; var res = plugins.value.map(function(i) { var _i_type; var _i_type1; return (_i_type1 = i[type]) === null || _i_type1 === void 0 ? void 0 : (_i_type = _i_type1).call.apply(_i_type, [ i ].concat(_to_consumable_array(args))); }); return (_Object = Object).assign.apply(_Object, [ {} ].concat(_to_consumable_array(res))); }; var functionContext = {}; var resolveTick; var tickPromise = new Promise(function(resolve) { resolveTick = resolve; }); var isCurrentRequest = function(requestCount) { return requestCount === count.value; }; var resetTickPromise = function() { tickPromise = new Promise(function(resolve) { resolveTick = resolve; }); }; var handleRequestSuccess = /*#__PURE__*/ function() { var _ref = _async_to_generator(function(currentCount, res, args) { var result; return _ts_generator(this, function(_state) { switch(_state.label){ case 0: if (!isCurrentRequest(currentCount)) { return [ 2 ]; } error.value = void 0; return [ 4, onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(res, args) ]; case 1: result = _state.sent(); data.value = result !== void 0 ? result : res; callPlugin("onSuccess", data.value, args); return [ 2, data.value ]; } }); }); return function handleRequestSuccess(currentCount, res, args) { return _ref.apply(this, arguments); }; }(); var handleRequestError = function(currentCount, err, args) { if (!isCurrentRequest(currentCount)) { return; } error.value = err; callPlugin("onError", err, args); onError === null || onError === void 0 ? void 0 : onError(err, args); throw err; }; var handleRequestFinally = function(currentCount, args) { loading.value = false; status.value = "settled"; resolveTick({ params: params.value, data: data.value }); if (!isCurrentRequest(currentCount)) { return; } callPlugin("onFinally", args); onFinally === null || onFinally === void 0 ? void 0 : onFinally(); }; var makeRequest = /*#__PURE__*/ function() { var _ref = _async_to_generator(function(currentCount, args) { var _callPlugin, _callPlugin_returnNow, returnNow, returnData, returnType, servicePromise, res, err; return _ts_generator(this, function(_state) { switch(_state.label){ case 0: _callPlugin = callPlugin("onBefore", args), _callPlugin_returnNow = _callPlugin.returnNow, returnNow = _callPlugin_returnNow === void 0 ? false : _callPlugin_returnNow, returnData = _callPlugin.returnData, returnType = _callPlugin.returnType; if (returnData !== void 0) { data.value = returnData; if (returnType === "cache") { onCache === null || onCache === void 0 ? void 0 : onCache(returnData); } } if (returnNow) { loading.value = false; status.value = "settled"; return [ 2, Promise.resolve(returnData) ]; } onBefore === null || onBefore === void 0 ? void 0 : onBefore(args); servicePromise = callPlugin("onInit", service).servicePromise; if (!servicePromise) { servicePromise = service.apply(void 0, _to_consumable_array(params.value)); } _state.label = 1; case 1: _state.trys.push([ 1, 4, 5, 6 ]); return [ 4, servicePromise ]; case 2: res = _state.sent(); onRequest === null || onRequest === void 0 ? void 0 : onRequest({ params: args, response: res, error: void 0, abort: !isCurrentRequest(currentCount) }); return [ 4, handleRequestSuccess(currentCount, res, args) ]; case 3: return [ 2, _state.sent() ]; case 4: err = _state.sent(); onRequest === null || onRequest === void 0 ? void 0 : onRequest({ params: args, response: void 0, error: err, abort: !isCurrentRequest(currentCount) }); return [ 2, handleRequestError(currentCount, err, args) ]; case 5: handleRequestFinally(currentCount, args); return [ 7 ]; case 6: return [ 2 ]; } }); }); return function makeRequest(currentCount, args) { return _ref.apply(this, arguments); }; }(); functionContext.runAsync = /*#__PURE__*/ _async_to_generator(function() { var _len, args, _key, currentCount; var _arguments = arguments; return _ts_generator(this, function(_state) { for(_len = _arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){ args[_key] = _arguments[_key]; } loading.value = true; if (args === null || args === void 0 ? void 0 : args.length) { params.value = args; } status.value = "pending"; count.value++; currentCount = count.value; resetTickPromise(); return [ 2, makeRequest(currentCount, args) ]; }); }); functionContext.run = function() { for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){ args[_key] = arguments[_key]; } var _functionContext; (_functionContext = functionContext).runAsync.apply(_functionContext, _to_consumable_array(args)).catch(function(err) { !onError && console.error(err); }); }; functionContext.cancel = function() { count.value--; loading.value = false; callPlugin("onCancel"); onCancel === null || onCancel === void 0 ? void 0 : onCancel(); }; functionContext.refresh = function() { return (_functionContext = functionContext).run.apply(_functionContext, _to_consumable_array(params.value)); }; functionContext.refreshAsync = function() { return (_functionContext1 = functionContext).runAsync.apply(_functionContext1, _to_consumable_array(params.value)); }; functionContext.mutate = function(v) { data.value = (v === null || v === void 0 ? void 0 : v.constructor) === Function ? v(data.value) : v; callPlugin("onMutate", data.value); }; var requestTick = /*#__PURE__*/ function() { var _ref = _async_to_generator(function(callback) { var res; return _ts_generator(this, function(_state) { switch(_state.label){ case 0: if (!(status.value === "pending")) return [ 3, 2 ]; return [ 4, tickPromise ]; case 1: res = _state.sent(); callback === null || callback === void 0 ? void 0 : callback(res); return [ 2, res ]; case 2: callback === null || callback === void 0 ? void 0 : callback(); return [ 2 ]; } }); }); return function requestTick(callback) { return _ref.apply(this, arguments); }; }(); return { status: status, data: data, params: params, pollingCount: pollingCount, loading: loading, error: error, plugins: plugins, requestTick: requestTick, functionContext: functionContext }; } var createInstance_default = createInstance; // lib/usePlugins.ts function usePlugins(service) { var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, plugins = arguments.length > 2 ? arguments[2] : void 0; var id = options.id, _options_manual = options.manual, manual = _options_manual === void 0 ? false : _options_manual, _options_defaultParams = options.defaultParams, defaultParams = _options_defaultParams === void 0 ? [] : _options_defaultParams, rest = _object_without_properties(options, [ "id", "manual", "defaultParams" ]); var _defaultParams = unrefParms(defaultParams); var fetchOptions = _object_spread({ manual: manual, defaultParams: _defaultParams }, rest); var instance = createInstance_default(service, fetchOptions); instance.plugins.value = plugins.map(function(p) { return p(instance, fetchOptions); }); if (!manual) { var _instance_functionContext; (_instance_functionContext = instance.functionContext).run.apply(_instance_functionContext, _to_consumable_array(_defaultParams)); } (0, import_vue3.onUnmounted)(function() { instance.functionContext.cancel(); id && removeRequest(id); }); return _object_spread({ status: instance.status, loading: instance.loading, data: instance.data, error: instance.error, params: instance.params, pollingCount: instance.pollingCount, requestTick: instance.requestTick }, instance.functionContext); } var usePlugins_default = usePlugins; // lib/plugins/useLoadingDelayPlugin.ts var import_vue4 = require("vue"); var useLoadingDelayPlugin = function(instance, param) { var loadingDelay = param.loadingDelay; var timerRef = (0, import_vue4.ref)(); return { onBefore: function onBefore() { if (loadingDelay) { instance.loading.value = false; timerRef.value = useDelay(function() { instance.loading.value = true; }, loadingDelay); } }, onCancel: function onCancel() { clearTimeout(timerRef.value); }, onFinally: function onFinally() { clearTimeout(timerRef.value); } }; }; var useLoadingDelayPlugin_default = useLoadingDelayPlugin; // lib/plugins/usePollingPlugin.ts var import_vue5 = require("vue"); var usePollingPlugin = function(instance, param) { var pollingInterval = param.pollingInterval, _param_pollingErrorRetryCount = param.pollingErrorRetryCount, pollingErrorRetryCount = _param_pollingErrorRetryCount === void 0 ? -1 : _param_pollingErrorRetryCount; var timerRef = (0, import_vue5.ref)(); var countRef = (0, import_vue5.ref)(0); var pollingIntervalRef = (0, import_vue5.computed)(function() { return (0, import_vue5.unref)(pollingInterval); }); var polling = function(callback) { var timerId; var canPolling = !isNonZeroFalsy(pollingIntervalRef.value) && pollingIntervalRef.value >= 0; if (!canPolling) { return; } if (pollingErrorRetryCount === -1 || pollingErrorRetryCount !== -1 && countRef.value <= pollingErrorRetryCount) { instance.pollingCount.value++; timerId = useDelay(callback, pollingIntervalRef.value); } else { countRef.value = 0; } return function() { return timerId && clearTimeout(timerId); }; }; (0, import_vue5.watch)(pollingIntervalRef, function() { if (timerRef.value) { timerRef.value(); timerRef.value = polling(function() { return instance.functionContext.refresh(); }); } }); return { onBefore: function onBefore() { var _timerRef_value; (_timerRef_value = timerRef.value) === null || _timerRef_value === void 0 ? void 0 : _timerRef_value.call(timerRef); }, onCancel: function onCancel() { var _timerRef_value; (_timerRef_value = timerRef.value) === null || _timerRef_value === void 0 ? void 0 : _timerRef_value.call(timerRef); instance.pollingCount.value = 0; }, onSuccess: function onSuccess() { countRef.value = 0; }, onError: function onError() { countRef.value++; }, onFinally: function onFinally() { timerRef.value = polling(function() { return instance.functionContext.refresh(); }); } }; }; var usePollingPlugin_default = usePollingPlugin; // lib/plugins/useReadyPlugin.ts var import_vue6 = require("vue"); var useReadyPlugin = function(instance, param) { var _param_ready = param.ready, ready = _param_ready === void 0 ? true : _param_ready; return { onBefore: function onBefore() { var _ready = TypeChecker.isFunction(ready) ? ready() : ready; if (!(0, import_vue6.unref)(_ready)) { instance.loading.value = false; return { returnNow: true }; } } }; }; var useReadyPlugin_default = useReadyPlugin; // lib/plugins/useRefreshDepsPlugin.ts var import_vue7 = require("vue"); var useRefreshDepsPlugin = function(instance, param) { var _param_refreshDeps = param.refreshDeps, refreshDeps = _param_refreshDeps === void 0 ? null : _param_refreshDeps, _param_refreshDepsParams = param.refreshDepsParams, refreshDepsParams = _param_refreshDepsParams === void 0 ? null : _param_refreshDepsParams; if (refreshDeps) { (0, import_vue7.watch)(refreshDeps, /*#__PURE__*/ function() { var _ref = _async_to_generator(function(oldValue, newValue) { var res, _instance_functionContext, _instance_functionContext1; return _ts_generator(this, function(_state) { switch(_state.label){ case 0: if (!refreshDepsParams) return [ 3, 4 ]; if (!isFunction(refreshDepsParams)) return [ 3, 2 ]; return [ 4, refreshDepsParams(oldValue, newValue) ]; case 1: res = _state.sent(); if (res) { ; (_instance_functionContext = instance.functionContext).run.apply(_instance_functionContext, _to_consumable_array(unrefParms(res))); } return [ 3, 3 ]; case 2: (_instance_functionContext1 = instance.functionContext).run.apply(_instance_functionContext1, _to_consumable_array(unrefParms(refreshDepsParams))); _state.label = 3; case 3: return [ 3, 5 ]; case 4: instance.functionContext.refresh(); _state.label = 5; case 5: return [ 2 ]; } }); }); return function(oldValue, newValue) { return _ref.apply(this, arguments); }; }(), { deep: true }); } return {}; }; var useRefreshDepsPlugin_default = useRefreshDepsPlugin; // lib/plugins/useDebouncePlugin.ts var import_vue8 = require("vue"); var useDebouncePlugin = function(instance, param) { var debounceWait = param.debounceWait, debounceOptions = param.debounceOptions; var debouncedRef = (0, import_vue8.ref)(); (0, import_vue8.watchEffect)(function(onCleanup) { if (!debounceWait) return; var debounceWaitUnref = (0, import_vue8.unref)(debounceWait); var debounceOptionsUnref = (0, import_vue8.unref)(debounceOptions); var originRunAsync = instance.functionContext.runAsync; debouncedRef.value = debounce_default(function(callback) { return callback(); }, debounceWaitUnref, debounceOptionsUnref); instance.functionContext.runAsync = function() { for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){ args[_key] = arguments[_key]; } return new Promise(function(resolve, reject) { debouncedRef.value(function() { originRunAsync.apply(void 0, _to_consumable_array(args)).then(resolve).catch(reject); }); }); }; onCleanup(function() { var _debouncedRef_value; (_debouncedRef_value = debouncedRef.value) === null || _debouncedRef_value === void 0 ? void 0 : _debouncedRef_value.cancel(); instance.functionContext.runAsync = originRunAsync; }); }); return { onCancel: function onCancel() { var _debouncedRef_value; (_debouncedRef_value = debouncedRef.value) === null || _debouncedRef_value === void 0 ? void 0 : _debouncedRef_value.cancel(); } }; }; var useDebouncePlugin_default = useDebouncePlugin; // lib/plugins/useThrottlePlugin.ts var import_vue9 = require("vue"); var useThrottlePlugin = function(instance, param) { var throttleWait = param.throttleWait, throttleOptions = param.throttleOptions; var throttleRef = (0, import_vue9.ref)(); (0, import_vue9.watchEffect)(function(onCleanup) { if (!throttleWait) return; var throttleWaitUnref = (0, import_vue9.unref)(throttleWait); var throttleOptionsUnref = (0, import_vue9.unref)(throttleOptions); var originRunAsync = instance.functionContext.runAsync; throttleRef.value = throttle_default(function(callback) { return callback(); }, throttleWaitUnref, throttleOptionsUnref); instance.functionContext.runAsync = function() { for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){ args[_key] = arguments[_key]; } return new Promise(function(resolve, reject) { throttleRef.value(function() { originRunAsync.apply(void 0, _to_consumable_array(args)).then(resolve).catch(reject); }); }); }; onCleanup(function() { var _throttleRef_value; (_throttleRef_value = throttleRef.value) === null || _throttleRef_value === void 0 ? void 0 : _throttleRef_value.cancel(); instance.functionContext.runAsync = originRunAsync; }); }); return { onCancel: function onCancel() { var _throttleRef_value; (_throttleRef_value = throttleRef.value) === null || _throttleRef_value === void 0 ? void 0 : _throttleRef_value.cancel(); } }; }; var useThrottlePlugin_default = useThrottlePlugin; // lib/plugins/useCachePlugin.ts var import_vue10 = require("vue"); // lib/utils/cachePromise.ts var cachePromise = /* @__PURE__ */ new Map(); var getCachePromise = function(cacheKey) { return cachePromise.get(cacheKey); }; var setCachePromise = function(cacheKey, promise) { cachePromise.set(cacheKey, promise); promise.then(function(res) { cachePromise.delete(cacheKey); return res; }).catch(function() { cachePromise.delete(cacheKey); }); }; // lib/plugins/useCachePlugin.ts var useCachePlugin = function(instance, param) { var customCacheKey = param.cacheKey, _param_cacheTime = param.cacheTime, cacheTime = _param_cacheTime === void 0 ? 5 * 60 * 1e3 : _param_cacheTime, _param_staleTime = param.staleTime, staleTime = _param_staleTime === void 0 ? 0 : _param_staleTime, customGetCache = param.getCache, customSetCache = param.setCache, onCache = param.onCache; if (!customCacheKey) { return {}; } var unSubscribe = function() {}; var currentPromise; var currentCacheKey; var cacheKey = isFunction(customCacheKey) ? customCacheKey : function() { return customCacheKey; }; var _setCache = function(key, cacheData, time) { if (customSetCache) { customSetCache(key, cacheData); } else { setCache(key, cacheData, time); } trigger(key, cacheData.data); }; var _getCache = function(key) { if (customGetCache) { return customGetCache(key); } else { return getCache(key); } }; var initialCacheKey = cacheKey(); var cache2 = _getCache(initialCacheKey); if (cache2 && Reflect.has(cache2, "data")) { instance.data.value = cache2.data; instance.params.value = cache2.params; } var setUnSubscribe = function(params) { var newCacheKey = cacheKey(params); if (newCacheKey !== currentCacheKey) { unSubscribe(); currentCacheKey = newCacheKey; unSubscribe = subscribe(currentCacheKey, function(data) { instance.data.value = data; onCache === null || onCache === void 0 ? void 0 : onCache(data); }); } }; setUnSubscribe(); (0, import_vue10.onBeforeUnmount)(function() { unSubscribe(); }); var updateCache = function(data, params) { var _cacheKey = cacheKey(params); if (_cacheKey) { unSubscribe(); _setCache(_cacheKey, { data: data, params: params, time: /* @__PURE__ */ new Date().getTime() }, cacheTime); setUnSubscribe(params); } }; return { onBefore: function onBefore(params) { var _cacheKey = cacheKey(params); var cache3 = _getCache(_cacheKey); if (!cache3 || !Reflect.has(cache3, "data")) { return {}; } if (staleTime === -1 || /* @__PURE__ */ new Date().getTime() - cache3.time <= staleTime) { return { returnNow: true, returnData: cache3.data, returnType: "cache" }; } else { return { returnData: cache3.data, returnType: "cache" }; } }, onInit: function onInit(service) { var params = instance.params.value; var _cacheKey = cacheKey(params); var servicePromise = getCachePromise(_cacheKey); if (servicePromise && servicePromise !== currentPromise) { return { servicePromise: servicePromise }; } servicePromise = service.apply(void 0, _to_consumable_array(params)); currentPromise = servicePromise; setCachePromise(_cacheKey, servicePromise); return { servicePromise: servicePromise }; }, onSuccess: function onSuccess(data, params) { updateCache(data, params); }, onMutate: function onMutate(data) { var params = instance.params.value; updateCache(data, params); } }; }; var useCachePlugin_default = useCachePlugin; // lib/plugins/useRetryPlugin.ts var import_vue11 = require("vue"); var useRetryPlugin = function(instance, param) { var retryCount = param.retryCount, retryInterval = param.retryInterval; var timerRef = (0, import_vue11.ref)(); var countRef = (0, import_vue11.ref)(0); var triggerByRetry = (0, import_vue11.ref)(false); if (!retryCount) { return {}; } return { onBefore: function onBefore() { if (!triggerByRetry.value) { countRef.value = 0; } triggerByRetry.value = false; if (timerRef.value) { clearTimeout(timerRef.value); } }, onSuccess: function onSuccess() { countRef.value = 0; }, onError: function onError() { countRef.value += 1; if (retryCount === -1 || countRef.value <= retryCount) { var timeout = retryInterval !== null && retryInterval !== void 0 ? retryInterval : Math.min(1e3 * Math.pow(2, countRef.value), 3e4); timerRef.value = setTimeout(function() { triggerByRetry.value = true; instance.functionContext.refresh(); }, timeout); } else { countRef.value = 0; } }, onCancel: function onCancel() { countRef.value = 0; if (timerRef.value) { clearTimeout(timerRef.value); } } }; }; var useRetryPlugin_default = useRetryPlugin; // lib/plugins/useWindowVisibilityChangePlugin.ts var import_vue12 = require("vue"); // lib/utils/subscribeVisivilityChange.ts var refreshListeners = []; var cancelListeners = []; function refreshSubscribe(listener) { refreshListeners.push(listener); return function unsubscribe() { var index = refreshListeners.indexOf(listener); if (index > -1) { refreshListeners.splice(index, 1); } }; } function cancelSubscribe(listener) { cancelListeners.push(listener); return function unsubscribe() { var index = cancelListeners.indexOf(listener); if (index > -1) { cancelListeners.splice(index, 1); } }; } if ((_window = window) === null || _window === void 0 ? void 0 : _window.document) { var revalidate = function() { if (document.visibilityState === "visible") { for(var i = 0; i < refreshListeners.length; i++){ var listener = refreshListeners[i]; listener();