@chainpay/component
Version:
A React-based payment component library that supports multiple payment channels and internationalization.
1,532 lines • 193 kB
JavaScript
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);
import { jsxs, Fragment, jsx } from "react/jsx-runtime";
import { createContext, useContext, useCallback, useState, useRef, useEffect, useMemo } from "react";
import { createRoot } from "react-dom/client";
import { unstableSetRender, message, Spin, Image, Select, Button, Steps, QRCode, ConfigProvider, theme, Modal } from "antd";
unstableSetRender(function(node, container) {
container._reactRoot || (container._reactRoot = createRoot(container));
var root = container._reactRoot;
root.render(node);
return function() {
return new Promise(function(resolve) {
setTimeout(function() {
root.unmount();
resolve();
}, 0);
});
};
});
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
function warn() {
if (console && console.warn) {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (isString$1(args[0])) args[0] = `react-i18next:: ${args[0]}`;
console.warn(...args);
}
}
const alreadyWarned = {};
function warnOnce() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
if (isString$1(args[0]) && alreadyWarned[args[0]]) return;
if (isString$1(args[0])) alreadyWarned[args[0]] = /* @__PURE__ */ new Date();
warn(...args);
}
const loadedClb = (i18n, cb) => () => {
if (i18n.isInitialized) {
cb();
} else {
const initialized = () => {
setTimeout(() => {
i18n.off("initialized", initialized);
}, 0);
cb();
};
i18n.on("initialized", initialized);
}
};
const loadNamespaces = (i18n, ns, cb) => {
i18n.loadNamespaces(ns, loadedClb(i18n, cb));
};
const loadLanguages = (i18n, lng, ns, cb) => {
if (isString$1(ns)) ns = [ns];
ns.forEach((n) => {
if (i18n.options.ns.indexOf(n) < 0) i18n.options.ns.push(n);
});
i18n.loadLanguages(lng, loadedClb(i18n, cb));
};
const oldI18nextHasLoadedNamespace = function(ns, i18n) {
let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
const lng = i18n.languages[0];
const fallbackLng = i18n.options ? i18n.options.fallbackLng : false;
const lastLng = i18n.languages[i18n.languages.length - 1];
if (lng.toLowerCase() === "cimode") return true;
const loadNotPending = (l, n) => {
const loadState = i18n.services.backendConnector.state[`${l}|${n}`];
return loadState === -1 || loadState === 2;
};
if (options.bindI18n && options.bindI18n.indexOf("languageChanging") > -1 && i18n.services.backendConnector.backend && i18n.isLanguageChangingTo && !loadNotPending(i18n.isLanguageChangingTo, ns)) return false;
if (i18n.hasResourceBundle(lng, ns)) return true;
if (!i18n.services.backendConnector.backend || i18n.options.resources && !i18n.options.partialBundledLanguages) return true;
if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
return false;
};
const hasLoadedNamespace = function(ns, i18n) {
let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
if (!i18n.languages || !i18n.languages.length) {
warnOnce("i18n.languages were undefined or empty", i18n.languages);
return true;
}
const isNewerI18next = i18n.options.ignoreJSONStructure !== void 0;
if (!isNewerI18next) {
return oldI18nextHasLoadedNamespace(ns, i18n, options);
}
return i18n.hasLoadedNamespace(ns, {
lng: options.lng,
precheck: (i18nInstance2, loadNotPending) => {
if (options.bindI18n && options.bindI18n.indexOf("languageChanging") > -1 && i18nInstance2.services.backendConnector.backend && i18nInstance2.isLanguageChangingTo && !loadNotPending(i18nInstance2.isLanguageChangingTo, ns)) return false;
}
});
};
const isString$1 = (obj) => typeof obj === "string";
const isObject = (obj) => typeof obj === "object" && obj !== null;
const matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;
const htmlEntities = {
"&": "&",
"&": "&",
"<": "<",
"<": "<",
">": ">",
">": ">",
"'": "'",
"'": "'",
""": '"',
""": '"',
" ": " ",
" ": " ",
"©": "©",
"©": "©",
"®": "®",
"®": "®",
"…": "…",
"…": "…",
"/": "/",
"/": "/"
};
const unescapeHtmlEntity = (m) => htmlEntities[m];
const unescape = (text) => text.replace(matchHtmlEntity, unescapeHtmlEntity);
let defaultOptions = {
bindI18n: "languageChanged",
bindI18nStore: "",
transEmptyNodeValue: "",
transSupportBasicHtmlNodes: true,
transWrapTextNodes: "",
transKeepBasicHtmlNodesFor: ["br", "strong", "i", "p"],
useSuspense: true,
unescape
};
const setDefaults = function() {
let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
defaultOptions = {
...defaultOptions,
...options
};
};
const getDefaults = () => defaultOptions;
let i18nInstance;
const setI18n = (instance2) => {
i18nInstance = instance2;
};
const getI18n = () => i18nInstance;
const initReactI18next = {
type: "3rdParty",
init(instance2) {
setDefaults(instance2.options.react);
setI18n(instance2);
}
};
const I18nContext = createContext();
class ReportNamespaces {
constructor() {
__publicField(this, "getUsedNamespaces", () => Object.keys(this.usedNamespaces));
this.usedNamespaces = {};
}
addUsedNamespaces(namespaces) {
namespaces.forEach((ns) => {
if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true;
});
}
}
const usePrevious = (value, ignore) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value, ignore]);
return ref.current;
};
const alwaysNewT = (i18n, language, namespace, keyPrefix) => i18n.getFixedT(language, namespace, keyPrefix);
const useMemoizedT = (i18n, language, namespace, keyPrefix) => useCallback(alwaysNewT(i18n, language, namespace, keyPrefix), [i18n, language, namespace, keyPrefix]);
const useTranslation = function(ns) {
let props = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
const {
i18n: i18nFromProps
} = props;
const {
i18n: i18nFromContext,
defaultNS: defaultNSFromContext
} = useContext(I18nContext) || {};
const i18n = i18nFromProps || i18nFromContext || getI18n();
if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();
if (!i18n) {
warnOnce("You will need to pass in an i18next instance by using initReactI18next");
const notReadyT = (k, optsOrDefaultValue) => {
if (isString$1(optsOrDefaultValue)) return optsOrDefaultValue;
if (isObject(optsOrDefaultValue) && isString$1(optsOrDefaultValue.defaultValue)) return optsOrDefaultValue.defaultValue;
return Array.isArray(k) ? k[k.length - 1] : k;
};
const retNotReady = [notReadyT, {}, false];
retNotReady.t = notReadyT;
retNotReady.i18n = {};
retNotReady.ready = false;
return retNotReady;
}
if (i18n.options.react && i18n.options.react.wait !== void 0) warnOnce("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");
const i18nOptions = {
...getDefaults(),
...i18n.options.react,
...props
};
const {
useSuspense,
keyPrefix
} = i18nOptions;
let namespaces = defaultNSFromContext || i18n.options && i18n.options.defaultNS;
namespaces = isString$1(namespaces) ? [namespaces] : namespaces || ["translation"];
if (i18n.reportNamespaces.addUsedNamespaces) i18n.reportNamespaces.addUsedNamespaces(namespaces);
const ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every((n) => hasLoadedNamespace(n, i18n, i18nOptions));
const memoGetT = useMemoizedT(i18n, props.lng || null, i18nOptions.nsMode === "fallback" ? namespaces : namespaces[0], keyPrefix);
const getT = () => memoGetT;
const getNewT = () => alwaysNewT(i18n, props.lng || null, i18nOptions.nsMode === "fallback" ? namespaces : namespaces[0], keyPrefix);
const [t, setT] = useState(getT);
let joinedNS = namespaces.join();
if (props.lng) joinedNS = `${props.lng}${joinedNS}`;
const previousJoinedNS = usePrevious(joinedNS);
const isMounted = useRef(true);
useEffect(() => {
const {
bindI18n,
bindI18nStore
} = i18nOptions;
isMounted.current = true;
if (!ready && !useSuspense) {
if (props.lng) {
loadLanguages(i18n, props.lng, namespaces, () => {
if (isMounted.current) setT(getNewT);
});
} else {
loadNamespaces(i18n, namespaces, () => {
if (isMounted.current) setT(getNewT);
});
}
}
if (ready && previousJoinedNS && previousJoinedNS !== joinedNS && isMounted.current) {
setT(getNewT);
}
const boundReset = () => {
if (isMounted.current) setT(getNewT);
};
if (bindI18n && i18n) i18n.on(bindI18n, boundReset);
if (bindI18nStore && i18n) i18n.store.on(bindI18nStore, boundReset);
return () => {
isMounted.current = false;
if (bindI18n && i18n) bindI18n.split(" ").forEach((e) => i18n.off(e, boundReset));
if (bindI18nStore && i18n) bindI18nStore.split(" ").forEach((e) => i18n.store.off(e, boundReset));
};
}, [i18n, joinedNS]);
useEffect(() => {
if (isMounted.current && ready) {
setT(getT);
}
}, [i18n, keyPrefix, ready]);
const ret = [t, i18n, ready];
ret.t = t;
ret.i18n = i18n;
ret.ready = ready;
if (ready) return ret;
if (!ready && !useSuspense) return ret;
throw new Promise((resolve) => {
if (props.lng) {
loadLanguages(i18n, props.lng, namespaces, () => resolve());
} else {
loadNamespaces(i18n, namespaces, () => resolve());
}
});
};
var createUpdateEffect = function(hook) {
return function(effect, deps) {
var isMounted = useRef(false);
hook(function() {
return function() {
isMounted.current = false;
};
}, []);
hook(function() {
if (!isMounted.current) {
isMounted.current = true;
} else {
return effect();
}
}, deps);
};
};
var __assign = function() {
__assign = Object.assign || function __assign2(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __awaiter(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());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
}, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["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 (g && (g = 0, op[0] && (_ = 0)), _) 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 };
}
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r2, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r2 = i.next()).done) ar.push(r2.value);
} catch (error) {
e = { error };
} finally {
try {
if (r2 && !r2.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message2) {
var e = new Error(message2);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var isFunction = function(value) {
return typeof value === "function";
};
var isDev = process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test";
function useMemoizedFn(fn) {
if (isDev) {
if (!isFunction(fn)) {
console.error("useMemoizedFn expected parameter is a function, got ".concat(typeof fn));
}
}
var fnRef = useRef(fn);
fnRef.current = useMemo(function() {
return fn;
}, [fn]);
var memoizedFn = useRef();
if (!memoizedFn.current) {
memoizedFn.current = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return fnRef.current.apply(this, args);
};
}
return memoizedFn.current;
}
const useUpdateEffect = createUpdateEffect(useEffect);
var useAutoRunPlugin = function(fetchInstance, _a) {
var manual = _a.manual, _b = _a.ready, ready = _b === void 0 ? true : _b, _c = _a.defaultParams, defaultParams = _c === void 0 ? [] : _c, _d = _a.refreshDeps, refreshDeps = _d === void 0 ? [] : _d, refreshDepsAction = _a.refreshDepsAction;
var hasAutoRun = useRef(false);
hasAutoRun.current = false;
useUpdateEffect(function() {
if (!manual && ready) {
hasAutoRun.current = true;
fetchInstance.run.apply(fetchInstance, __spreadArray([], __read(defaultParams), false));
}
}, [ready]);
useUpdateEffect(function() {
if (hasAutoRun.current) {
return;
}
if (!manual) {
hasAutoRun.current = true;
if (refreshDepsAction) {
refreshDepsAction();
} else {
fetchInstance.refresh();
}
}
}, __spreadArray([], __read(refreshDeps), false));
return {
onBefore: function() {
if (!ready) {
return {
stopNow: true
};
}
}
};
};
useAutoRunPlugin.onInit = function(_a) {
var _b = _a.ready, ready = _b === void 0 ? true : _b, manual = _a.manual;
return {
loading: !manual && ready
};
};
function depsAreSame(oldDeps, deps) {
if (oldDeps === deps) return true;
for (var i = 0; i < oldDeps.length; i++) {
if (!Object.is(oldDeps[i], deps[i])) return false;
}
return true;
}
function useCreation(factory, deps) {
var current = useRef({
deps,
obj: void 0,
initialized: false
}).current;
if (current.initialized === false || !depsAreSame(current.deps, deps)) {
current.deps = deps;
current.obj = factory();
current.initialized = true;
}
return current.obj;
}
function useLatest(value) {
var ref = useRef(value);
ref.current = value;
return ref;
}
var useUnmount = function(fn) {
if (isDev) {
if (!isFunction(fn)) {
console.error("useUnmount expected parameter is a function, got ".concat(typeof fn));
}
}
var fnRef = useLatest(fn);
useEffect(function() {
return function() {
fnRef.current();
};
}, []);
};
var cache = /* @__PURE__ */ new Map();
var setCache = function(key, cacheTime, cachedData) {
var currentCache = cache.get(key);
if (currentCache === null || currentCache === void 0 ? void 0 : currentCache.timer) {
clearTimeout(currentCache.timer);
}
var timer = void 0;
if (cacheTime > -1) {
timer = setTimeout(function() {
cache.delete(key);
}, cacheTime);
}
cache.set(key, __assign(__assign({}, cachedData), {
timer
}));
};
var getCache = function(key) {
return cache.get(key);
};
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);
});
};
var listeners$2 = {};
var trigger = function(key, data) {
if (listeners$2[key]) {
listeners$2[key].forEach(function(item) {
return item(data);
});
}
};
var subscribe$2 = function(key, listener) {
if (!listeners$2[key]) {
listeners$2[key] = [];
}
listeners$2[key].push(listener);
return function unsubscribe() {
var index = listeners$2[key].indexOf(listener);
listeners$2[key].splice(index, 1);
};
};
var useCachePlugin = function(fetchInstance, _a) {
var cacheKey = _a.cacheKey, _b = _a.cacheTime, cacheTime = _b === void 0 ? 5 * 60 * 1e3 : _b, _c = _a.staleTime, staleTime = _c === void 0 ? 0 : _c, customSetCache = _a.setCache, customGetCache = _a.getCache;
var unSubscribeRef = useRef();
var currentPromiseRef = useRef();
var _setCache = function(key, cachedData) {
if (customSetCache) {
customSetCache(cachedData);
} else {
setCache(key, cacheTime, cachedData);
}
trigger(key, cachedData.data);
};
var _getCache = function(key, params) {
if (params === void 0) {
params = [];
}
if (customGetCache) {
return customGetCache(params);
}
return getCache(key);
};
useCreation(function() {
if (!cacheKey) {
return;
}
var cacheData = _getCache(cacheKey);
if (cacheData && Object.hasOwnProperty.call(cacheData, "data")) {
fetchInstance.state.data = cacheData.data;
fetchInstance.state.params = cacheData.params;
if (staleTime === -1 || (/* @__PURE__ */ new Date()).getTime() - cacheData.time <= staleTime) {
fetchInstance.state.loading = false;
}
}
unSubscribeRef.current = subscribe$2(cacheKey, function(data) {
fetchInstance.setState({
data
});
});
}, []);
useUnmount(function() {
var _a2;
(_a2 = unSubscribeRef.current) === null || _a2 === void 0 ? void 0 : _a2.call(unSubscribeRef);
});
if (!cacheKey) {
return {};
}
return {
onBefore: function(params) {
var cacheData = _getCache(cacheKey, params);
if (!cacheData || !Object.hasOwnProperty.call(cacheData, "data")) {
return {};
}
if (staleTime === -1 || (/* @__PURE__ */ new Date()).getTime() - cacheData.time <= staleTime) {
return {
loading: false,
data: cacheData === null || cacheData === void 0 ? void 0 : cacheData.data,
error: void 0,
returnNow: true
};
} else {
return {
data: cacheData === null || cacheData === void 0 ? void 0 : cacheData.data,
error: void 0
};
}
},
onRequest: function(service, args) {
var servicePromise = getCachePromise(cacheKey);
if (servicePromise && servicePromise !== currentPromiseRef.current) {
return {
servicePromise
};
}
servicePromise = service.apply(void 0, __spreadArray([], __read(args), false));
currentPromiseRef.current = servicePromise;
setCachePromise(cacheKey, servicePromise);
return {
servicePromise
};
},
onSuccess: function(data, params) {
var _a2;
if (cacheKey) {
(_a2 = unSubscribeRef.current) === null || _a2 === void 0 ? void 0 : _a2.call(unSubscribeRef);
_setCache(cacheKey, {
data,
params,
time: (/* @__PURE__ */ new Date()).getTime()
});
unSubscribeRef.current = subscribe$2(cacheKey, function(d) {
fetchInstance.setState({
data: d
});
});
}
},
onMutate: function(data) {
var _a2;
if (cacheKey) {
(_a2 = unSubscribeRef.current) === null || _a2 === void 0 ? void 0 : _a2.call(unSubscribeRef);
_setCache(cacheKey, {
data,
params: fetchInstance.state.params,
time: (/* @__PURE__ */ new Date()).getTime()
});
unSubscribeRef.current = subscribe$2(cacheKey, function(d) {
fetchInstance.setState({
data: d
});
});
}
}
};
};
var isObject_1;
var hasRequiredIsObject;
function requireIsObject() {
if (hasRequiredIsObject) return isObject_1;
hasRequiredIsObject = 1;
function isObject2(value) {
var type = typeof value;
return value != null && (type == "object" || type == "function");
}
isObject_1 = isObject2;
return isObject_1;
}
var _freeGlobal;
var hasRequired_freeGlobal;
function require_freeGlobal() {
if (hasRequired_freeGlobal) return _freeGlobal;
hasRequired_freeGlobal = 1;
var freeGlobal = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
_freeGlobal = freeGlobal;
return _freeGlobal;
}
var _root;
var hasRequired_root;
function require_root() {
if (hasRequired_root) return _root;
hasRequired_root = 1;
var freeGlobal = require_freeGlobal();
var freeSelf = typeof self == "object" && self && self.Object === Object && self;
var root = freeGlobal || freeSelf || Function("return this")();
_root = root;
return _root;
}
var now_1;
var hasRequiredNow;
function requireNow() {
if (hasRequiredNow) return now_1;
hasRequiredNow = 1;
var root = require_root();
var now = function() {
return root.Date.now();
};
now_1 = now;
return now_1;
}
var _trimmedEndIndex;
var hasRequired_trimmedEndIndex;
function require_trimmedEndIndex() {
if (hasRequired_trimmedEndIndex) return _trimmedEndIndex;
hasRequired_trimmedEndIndex = 1;
var reWhitespace = /\s/;
function trimmedEndIndex(string) {
var index = string.length;
while (index-- && reWhitespace.test(string.charAt(index))) {
}
return index;
}
_trimmedEndIndex = trimmedEndIndex;
return _trimmedEndIndex;
}
var _baseTrim;
var hasRequired_baseTrim;
function require_baseTrim() {
if (hasRequired_baseTrim) return _baseTrim;
hasRequired_baseTrim = 1;
var trimmedEndIndex = require_trimmedEndIndex();
var reTrimStart = /^\s+/;
function baseTrim(string) {
return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, "") : string;
}
_baseTrim = baseTrim;
return _baseTrim;
}
var _Symbol;
var hasRequired_Symbol;
function require_Symbol() {
if (hasRequired_Symbol) return _Symbol;
hasRequired_Symbol = 1;
var root = require_root();
var Symbol2 = root.Symbol;
_Symbol = Symbol2;
return _Symbol;
}
var _getRawTag;
var hasRequired_getRawTag;
function require_getRawTag() {
if (hasRequired_getRawTag) return _getRawTag;
hasRequired_getRawTag = 1;
var Symbol2 = require_Symbol();
var objectProto = Object.prototype;
var hasOwnProperty = objectProto.hasOwnProperty;
var nativeObjectToString = objectProto.toString;
var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0;
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
try {
value[symToStringTag] = void 0;
var unmasked = true;
} catch (e) {
}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
_getRawTag = getRawTag;
return _getRawTag;
}
var _objectToString;
var hasRequired_objectToString;
function require_objectToString() {
if (hasRequired_objectToString) return _objectToString;
hasRequired_objectToString = 1;
var objectProto = Object.prototype;
var nativeObjectToString = objectProto.toString;
function objectToString(value) {
return nativeObjectToString.call(value);
}
_objectToString = objectToString;
return _objectToString;
}
var _baseGetTag;
var hasRequired_baseGetTag;
function require_baseGetTag() {
if (hasRequired_baseGetTag) return _baseGetTag;
hasRequired_baseGetTag = 1;
var Symbol2 = require_Symbol(), getRawTag = require_getRawTag(), objectToString = require_objectToString();
var nullTag = "[object Null]", undefinedTag = "[object Undefined]";
var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0;
function baseGetTag(value) {
if (value == null) {
return value === void 0 ? undefinedTag : nullTag;
}
return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
}
_baseGetTag = baseGetTag;
return _baseGetTag;
}
var isObjectLike_1;
var hasRequiredIsObjectLike;
function requireIsObjectLike() {
if (hasRequiredIsObjectLike) return isObjectLike_1;
hasRequiredIsObjectLike = 1;
function isObjectLike(value) {
return value != null && typeof value == "object";
}
isObjectLike_1 = isObjectLike;
return isObjectLike_1;
}
var isSymbol_1;
var hasRequiredIsSymbol;
function requireIsSymbol() {
if (hasRequiredIsSymbol) return isSymbol_1;
hasRequiredIsSymbol = 1;
var baseGetTag = require_baseGetTag(), isObjectLike = requireIsObjectLike();
var symbolTag = "[object Symbol]";
function isSymbol(value) {
return typeof value == "symbol" || isObjectLike(value) && baseGetTag(value) == symbolTag;
}
isSymbol_1 = isSymbol;
return isSymbol_1;
}
var toNumber_1;
var hasRequiredToNumber;
function requireToNumber() {
if (hasRequiredToNumber) return toNumber_1;
hasRequiredToNumber = 1;
var baseTrim = require_baseTrim(), isObject2 = requireIsObject(), isSymbol = requireIsSymbol();
var NAN = 0 / 0;
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
var reIsBinary = /^0b[01]+$/i;
var reIsOctal = /^0o[0-7]+$/i;
var freeParseInt = parseInt;
function toNumber(value) {
if (typeof value == "number") {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject2(value)) {
var other = typeof value.valueOf == "function" ? value.valueOf() : value;
value = isObject2(other) ? other + "" : other;
}
if (typeof value != "string") {
return value === 0 ? value : +value;
}
value = baseTrim(value);
var isBinary = reIsBinary.test(value);
return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}
toNumber_1 = toNumber;
return toNumber_1;
}
var debounce_1;
var hasRequiredDebounce;
function requireDebounce() {
if (hasRequiredDebounce) return debounce_1;
hasRequiredDebounce = 1;
var isObject2 = requireIsObject(), now = requireNow(), toNumber = requireToNumber();
var FUNC_ERROR_TEXT = "Expected a function";
var nativeMax = Math.max, nativeMin = Math.min;
function debounce2(func, wait, options) {
var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
if (typeof func != "function") {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber(wait) || 0;
if (isObject2(options)) {
leading = !!options.leading;
maxing = "maxWait" in options;
maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
trailing = "trailing" in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs, thisArg = lastThis;
lastArgs = lastThis = void 0;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
lastInvokeTime = time;
timerId = setTimeout(timerExpired, wait);
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall;
return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
}
function timerExpired() {
var time = now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
timerId = setTimeout(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) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = void 0;
}
function flush() {
return timerId === void 0 ? result : trailingEdge(now());
}
function debounced() {
var time = now(), isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === void 0) {
return leadingEdge(lastCallTime);
}
if (maxing) {
clearTimeout(timerId);
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === void 0) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
debounce_1 = debounce2;
return debounce_1;
}
var debounceExports = requireDebounce();
const debounce = /* @__PURE__ */ getDefaultExportFromCjs(debounceExports);
var useDebouncePlugin = function(fetchInstance, _a) {
var debounceWait = _a.debounceWait, debounceLeading = _a.debounceLeading, debounceTrailing = _a.debounceTrailing, debounceMaxWait = _a.debounceMaxWait;
var debouncedRef = useRef();
var options = useMemo(function() {
var ret = {};
if (debounceLeading !== void 0) {
ret.leading = debounceLeading;
}
if (debounceTrailing !== void 0) {
ret.trailing = debounceTrailing;
}
if (debounceMaxWait !== void 0) {
ret.maxWait = debounceMaxWait;
}
return ret;
}, [debounceLeading, debounceTrailing, debounceMaxWait]);
useEffect(function() {
if (debounceWait) {
var _originRunAsync_1 = fetchInstance.runAsync.bind(fetchInstance);
debouncedRef.current = debounce(function(callback) {
callback();
}, debounceWait, options);
fetchInstance.runAsync = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new Promise(function(resolve, reject) {
var _a2;
(_a2 = debouncedRef.current) === null || _a2 === void 0 ? void 0 : _a2.call(debouncedRef, function() {
_originRunAsync_1.apply(void 0, __spreadArray([], __read(args), false)).then(resolve).catch(reject);
});
});
};
return function() {
var _a2;
(_a2 = debouncedRef.current) === null || _a2 === void 0 ? void 0 : _a2.cancel();
fetchInstance.runAsync = _originRunAsync_1;
};
}
}, [debounceWait, options]);
if (!debounceWait) {
return {};
}
return {
onCancel: function() {
var _a2;
(_a2 = debouncedRef.current) === null || _a2 === void 0 ? void 0 : _a2.cancel();
}
};
};
var useLoadingDelayPlugin = function(fetchInstance, _a) {
var loadingDelay = _a.loadingDelay, ready = _a.ready;
var timerRef = useRef();
if (!loadingDelay) {
return {};
}
var cancelTimeout = function() {
if (timerRef.current) {
clearTimeout(timerRef.current);
}
};
return {
onBefore: function() {
cancelTimeout();
if (ready !== false) {
timerRef.current = setTimeout(function() {
fetchInstance.setState({
loading: true
});
}, loadingDelay);
}
return {
loading: false
};
},
onFinally: function() {
cancelTimeout();
},
onCancel: function() {
cancelTimeout();
}
};
};
var isBrowser = !!(typeof window !== "undefined" && window.document && window.document.createElement);
function isDocumentVisible() {
if (isBrowser) {
return document.visibilityState !== "hidden";
}
return true;
}
var listeners$1 = [];
function subscribe$1(listener) {
listeners$1.push(listener);
return function unsubscribe() {
var index = listeners$1.indexOf(listener);
listeners$1.splice(index, 1);
};
}
if (isBrowser) {
var revalidate$1 = function() {
if (!isDocumentVisible()) return;
for (var i = 0; i < listeners$1.length; i++) {
var listener = listeners$1[i];
listener();
}
};
window.addEventListener("visibilitychange", revalidate$1, false);
}
var usePollingPlugin = function(fetchInstance, _a) {
var pollingInterval = _a.pollingInterval, _b = _a.pollingWhenHidden, pollingWhenHidden = _b === void 0 ? true : _b, _c = _a.pollingErrorRetryCount, pollingErrorRetryCount = _c === void 0 ? -1 : _c;
var timerRef = useRef();
var unsubscribeRef = useRef();
var countRef = useRef(0);
var stopPolling = function() {
var _a2;
if (timerRef.current) {
clearTimeout(timerRef.current);
}
(_a2 = unsubscribeRef.current) === null || _a2 === void 0 ? void 0 : _a2.call(unsubscribeRef);
};
useUpdateEffect(function() {
if (!pollingInterval) {
stopPolling();
}
}, [pollingInterval]);
if (!pollingInterval) {
return {};
}
return {
onBefore: function() {
stopPolling();
},
onError: function() {
countRef.current += 1;
},
onSuccess: function() {
countRef.current = 0;
},
onFinally: function() {
if (pollingErrorRetryCount === -1 || // When an error occurs, the request is not repeated after pollingErrorRetryCount retries
pollingErrorRetryCount !== -1 && countRef.current <= pollingErrorRetryCount) {
timerRef.current = setTimeout(function() {
if (!pollingWhenHidden && !isDocumentVisible()) {
unsubscribeRef.current = subscribe$1(function() {
fetchInstance.refresh();
});
} else {
fetchInstance.refresh();
}
}, pollingInterval);
} else {
countRef.current = 0;
}
},
onCancel: function() {
stopPolling();
}
};
};
function limit(fn, timespan) {
var pending = false;
return function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (pending) return;
pending = true;
fn.apply(void 0, __spreadArray([], __read(args), false));
setTimeout(function() {
pending = false;
}, timespan);
};
}
function isOnline() {
if (isBrowser && typeof navigator.onLine !== "undefined") {
return navigator.onLine;
}
return true;
}
var listeners = [];
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
var index = listeners.indexOf(listener);
if (index > -1) {
listeners.splice(index, 1);
}
};
}
if (isBrowser) {
var revalidate = function() {
if (!isDocumentVisible() || !isOnline()) return;
for (var i = 0; i < listeners.length; i++) {
var listener = listeners[i];
listener();
}
};
window.addEventListener("visibilitychange", revalidate, false);
window.addEventListener("focus", revalidate, false);
}
var useRefreshOnWindowFocusPlugin = function(fetchInstance, _a) {
var refreshOnWindowFocus = _a.refreshOnWindowFocus, _b = _a.focusTimespan, focusTimespan = _b === void 0 ? 5e3 : _b;
var unsubscribeRef = useRef();
var stopSubscribe = function() {
var _a2;
(_a2 = unsubscribeRef.current) === null || _a2 === void 0 ? void 0 : _a2.call(unsubscribeRef);
};
useEffect(function() {
if (refreshOnWindowFocus) {
var limitRefresh_1 = limit(fetchInstance.refresh.bind(fetchInstance), focusTimespan);
unsubscribeRef.current = subscribe(function() {
limitRefresh_1();
});
}
return function() {
stopSubscribe();
};
}, [refreshOnWindowFocus, focusTimespan]);
useUnmount(function() {
stopSubscribe();
});
return {};
};
var useRetryPlugin = function(fetchInstance, _a) {
var retryInterval = _a.retryInterval, retryCount = _a.retryCount;
var timerRef = useRef();
var countRef = useRef(0);
var triggerByRetry = useRef(false);
if (!retryCount) {
return {};
}
return {
onBefore: function() {
if (!triggerByRetry.current) {
countRef.current = 0;
}
triggerByRetry.current = false;
if (timerRef.current) {
clearTimeout(timerRef.current);
}
},
onSuccess: function() {
countRef.current = 0;
},
onError: function() {
countRef.current += 1;
if (retryCount === -1 || countRef.current <= retryCount) {
var timeout = retryInterval !== null && retryInterval !== void 0 ? retryInterval : Math.min(1e3 * Math.pow(2, countRef.current), 3e4);
timerRef.current = setTimeout(function() {
triggerByRetry.current = true;
fetchInstance.refresh();
}, timeout);
} else {
countRef.current = 0;
}
},
onCancel: function() {
countRef.current = 0;
if (timerRef.current) {
clearTimeout(timerRef.current);
}
}
};
};
var throttle_1;
var hasRequiredThrottle;
function requireThrottle() {
if (hasRequiredThrottle) return throttle_1;
hasRequiredThrottle = 1;
var debounce2 = requireDebounce(), isObject2 = requireIsObject();
var FUNC_ERROR_TEXT = "Expected a function";
function throttle2(func, wait, options) {
var leading = true, trailing = true;
if (typeof func != "function") {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (isObject2(options)) {
leading = "leading" in options ? !!options.leading : leading;
trailing = "trailing" in options ? !!options.trailing : trailing;
}
return debounce2(func, wait, {
"leading": leading,
"maxWait": wait,
"trailing": trailing
});
}
throttle_1 = throttle2;
return throttle_1;
}
var throttleExports = requireThrottle();
const throttle = /* @__PURE__ */ getDefaultExportFromCjs(throttleExports);
var useThrottlePlugin = function(fetchInstance, _a) {
var throttleWait = _a.throttleWait, throttleLeading = _a.throttleLeading, throttleTrailing = _a.throttleTrailing;
var throttledRef = useRef();
var options = {};
if (throttleLeading !== void 0) {
options.leading = throttleLeading;
}
if (throttleTrailing !== void 0) {
options.trailing = throttleTrailing;
}
useEffect(function() {
if (throttleWait) {
var _originRunAsync_1 = fetchInstance.runAsync.bind(fetchInstance);
throttledRef.current = throttle(function(callback) {
callback();
}, throttleWait, options);
fetchInstance.runAsync = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return new Promise(function(resolve, reject) {
var _a2;
(_a2 = throttledRef.current) === null || _a2 === void 0 ? void 0 : _a2.call(throttledRef, function() {
_originRunAsync_1.apply(void 0, __spreadArray([], __read(args), false)).then(resolve).catch(reject);
});
});
};
return function() {
var _a2;
fetchInstance.runAsync = _originRunAsync_1;
(_a2 = throttledRef.current) === null || _a2 === void 0 ? void 0 : _a2.cancel();
};
}
}, [throttleWait, throttleLeading, throttleTrailing]);
if (!throttleWait) {
return {};
}
return {
onCancel: function() {
var _a2;
(_a2 = throttledRef.current) === null || _a2 === void 0 ? void 0 : _a2.cancel();
}
};
};
var useMount = function(fn) {
if (isDev) {
if (!isFunction(fn)) {
console.error('useMount: parameter `fn` expected to be a function, but got "'.concat(typeof fn, '".'));
}
}
useEffect(function() {
fn === null || fn === void 0 ? void 0 : fn();
}, []);
};
var useUpdate = function() {
var _a = __read(useState({}), 2), setState = _a[1];
return useCallback(function() {
return setState({});
}, []);
};
var Fetch = (
/** @class */
function() {
function Fetch2(serviceRef, options, subscribe2, initState) {
if (initState === void 0) {
initState = {};
}
this.serviceRef = serviceRef;
this.options = options;
this.subscribe = subscribe2;
this.initState = initState;
this.count = 0;
this.state = {
loading: false,
params: void 0,
data: void 0,
error: void 0
};
this.state = __assign(__assign(__assign({}, this.state), {
loading: !options.manual
}), initState);
}
Fetch2.prototype.setState = function(s) {
if (s === void 0) {
s = {};
}
this.state = __assign(__assign({}, this.state), s);
this.subscribe();
};
Fetch2.prototype.runPluginHandler = function(event) {
var rest = [];
for (var _i = 1; _i < arguments.length; _i++) {
rest[_i - 1] = arguments[_i];
}
var r2 = this.pluginImpls.map(function(i) {
var _a;
return (_a = i[event]) === null || _a === void 0 ? void 0 : _a.call.apply(_a, __spreadArray([i], __read(rest), false));
}).filter(Boolean);
return Object.assign.apply(Object, __spreadArray([{}], __read(r2), false));
};
Fetch2.prototype.runAsync = function() {
var params = [];
for (var _i = 0; _i < arguments.length; _i++) {
params[_i] = arguments[_i];
}
return __awaiter(this, void 0, void 0, function() {
var currentCount, _a, _b, stopNow, _c, returnNow, state, servicePromise, res, error_1;
var _d;
var _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
return __generator(this, function(_q) {
switch (_q.label) {
case 0:
this.count += 1;
currentCount = this.count;
_a = this.runPluginHandler("onBefore", params), _b = _a.stopNow, stopNow = _b === void 0 ? false : _b, _c = _a.returnNow, returnNow = _c === void 0 ? false : _c, state = __rest(_a, ["stopNow", "returnNow"]);
if (stopNow) {
return [2, new Promise(function() {
})];
}
this.setState(__assign({
loading: true,
params
}, state));
if (returnNow) {
return [2, Promise.resolve(state.data)];
}
(_f = (_e = this.options).onBefore) === null || _f === void 0 ? void 0 : _f.call(_e, params);
_q.label = 1;
case 1:
_q.trys.push([1, 3, , 4]);
servicePromise = this.runPluginHandler("onRequest", this.serviceRef.current, params).servicePromise;
if (!servicePromise) {
servicePromise = (_d = this.serviceRef).current.apply(_d, __spreadArray([], __read(params), false));
}
return [4, servicePromise];
case 2:
res = _q.sent();
if (currentCount !== this.count) {
return [2, new Promise(function() {
})];
}
this.setState({
data: res,
error: void 0,
loading: false
});
(_h = (_g = this.options).onSuccess) === null || _h === void 0 ? void 0 : _h.call(_g, res, params);
this.runPluginHandler("onSuccess", res, params);
(_k = (_j = this.options).onFinally) === null || _k === void 0 ? void 0 : _k.call(_j, params, res, void 0);
if (currentCount === this.count) {
this.runPluginHandler("onFinally", params, res, void 0);
}
return [2, res];
case 3:
error_1 = _q.sent();
if (currentCount !== this.count) {
return [2, new Promise(function() {
})];
}
this.setState({
error: error_1,
loading: false
});
(_m = (_l = this.options).onError) === null || _m === void 0 ? void 0 : _m.call(_l, error_1, params);
this.runPluginHandler("onError", error_1, params);
(_p = (_o = this.options).onFinally) === null || _p === void 0 ? void 0 : _p.call(_o, params, void 0, error_1);
if (currentCount === this.count) {
this.runPluginHandler("onFinally", params, void 0, error_1);
}
throw error_1;
case 4:
return [
2
/*return*/
];
}
});
});
};
Fetch2.prototype.run = function() {
var _this = this;
var params = [];
for (var _i = 0; _i < arguments.length; _i++) {
params[_i] = arguments[_i];
}
this.runAsync.apply(this, __spreadArray([], __read(params), false)).catch(function(error) {
if (!_this.options.onError) {
console.error(error);
}
});
};
Fetch2.prototype.cancel = function() {
this.count += 1;
this.setState({
loading: false
});
this.runPluginHandler("onCancel");
};
Fetch2.prototype.refresh = function() {
this.run.apply(this, __spreadArray([], __read(this.state.params || []), false));
};
Fetch2.prototype.refreshAsync = function() {
return this.runAsync.apply(this, __spreadArray([], __read(this.state.params || []), false));
};
Fetch2.prototype.mutate = function(data) {
var targetData = isFunction(data) ? data(this.state.data) : data;
this.runPluginHandler("onMutate", targetData);
this.setState({
data: targetData
});
};
return Fetch2;
}()
);
function useRequestImplement(service, options, plugins) {
if (options === void 0) {
options = {};
}
if (plugins === void 0) {
plugins = [];
}
var _a = options.manual, manual = _a === void 0 ? false : _a, _b = options.ready, ready = _b === void 0 ? true : _b, rest = __rest(options, ["manual", "ready"]);
if (isDev) {
if (options.defaultParams && !Array.isArray(options.defaultParams)) {
console.warn("expected defaultParams is array, got ".concat(typeof options.defaultParams));
}
}
var fetchOptions = __assign({
manual,
ready
}, rest);
var serviceRef = useLatest(service);
var update = useUpdate();
var fetchInstance = useCreation(function() {
var initState = plugins.map(function(p) {
var _a2;
return (_a2 = p === null || p === void 0 ? void 0 : p.onInit) === null || _a2 === void 0 ? void 0 : _a2.call(p, fetchOptions);
}).filter(Boolean);
return new Fetch(serviceRef, fetchOptions, update, Object.assign.apply(Object, __spreadArray([{}], __read(initState), false)));
}, []);
fetchInstance.options = fetchOptions;
fetchIns