@acrool/react-fetcher 0.0.7-alpha.2 → 0.0.7-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -542,548 +542,269 @@ function D(e2, t2) {
542
542
  };
543
543
  return !w(e2, r2);
544
544
  }
545
- class FetcherException extends Error {
546
- constructor(response) {
547
- super(response.message);
548
- __publicField(this, "code");
549
- __publicField(this, "args");
550
- __publicField(this, "path");
551
- this.response = response;
552
- this.code = response.code;
553
- this.args = response.args;
554
- this.path = response.path;
555
- this.name = this.constructor.name;
556
- Object.setPrototypeOf(this, FetcherException.prototype);
545
+ function bind(fn, thisArg) {
546
+ return function wrap() {
547
+ return fn.apply(thisArg, arguments);
548
+ };
549
+ }
550
+ const { toString } = Object.prototype;
551
+ const { getPrototypeOf } = Object;
552
+ const { iterator, toStringTag } = Symbol;
553
+ const kindOf = /* @__PURE__ */ ((cache) => (thing) => {
554
+ const str = toString.call(thing);
555
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
556
+ })(/* @__PURE__ */ Object.create(null));
557
+ const kindOfTest = (type) => {
558
+ type = type.toLowerCase();
559
+ return (thing) => kindOf(thing) === type;
560
+ };
561
+ const typeOfTest = (type) => (thing) => typeof thing === type;
562
+ const { isArray } = Array;
563
+ const isUndefined = typeOfTest("undefined");
564
+ function isBuffer(val) {
565
+ return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
566
+ }
567
+ const isArrayBuffer = kindOfTest("ArrayBuffer");
568
+ function isArrayBufferView(val) {
569
+ let result;
570
+ if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
571
+ result = ArrayBuffer.isView(val);
572
+ } else {
573
+ result = val && val.buffer && isArrayBuffer(val.buffer);
557
574
  }
575
+ return result;
558
576
  }
559
- const AuthStateContext = createContext({
560
- lastUpdateTimestamp: 0,
561
- isAuth: false,
562
- getTokens: () => {
563
- u.warning("AuthStateContext", "getTokens not yet ready");
564
- return null;
565
- },
566
- updateTokens: () => u.warning("AuthStateContext", "updateTokens not yet ready"),
567
- forceLogout: () => u.warning("AuthStateContext", "forceLogout not yet ready"),
568
- refreshTokens: async () => {
569
- u.warning("AuthStateContext", "refreshToken not yet ready");
570
- return void 0;
577
+ const isString = typeOfTest("string");
578
+ const isFunction = typeOfTest("function");
579
+ const isNumber = typeOfTest("number");
580
+ const isObject = (thing) => thing !== null && typeof thing === "object";
581
+ const isBoolean = (thing) => thing === true || thing === false;
582
+ const isPlainObject = (val) => {
583
+ if (kindOf(val) !== "object") {
584
+ return false;
571
585
  }
572
- });
573
- const useAuthState = () => useContext(AuthStateContext);
574
- const AuthStateProvider = ({
575
- children,
576
- onGetTokens,
577
- onSetTokens,
578
- onRefreshTokens,
579
- onForceLogout,
580
- isDebug = false
581
- }) => {
582
- const [lastUpdateTimestamp, setLastUpdateTimestamp] = useState(0);
583
- const [isAuth, setIsAuth] = useState(() => {
584
- return D(onGetTokens());
585
- });
586
- const updateTokens = (tokensOrUpdater) => {
587
- let nextTokens;
588
- if (typeof tokensOrUpdater === "function") {
589
- nextTokens = tokensOrUpdater(onGetTokens());
590
- } else {
591
- nextTokens = tokensOrUpdater;
592
- }
593
- onSetTokens(nextTokens);
594
- setIsAuth(D(nextTokens));
595
- setLastUpdateTimestamp(Date.now());
596
- };
597
- const handleOnForceLogout = () => {
598
- updateTokens(null);
599
- if (onForceLogout) {
600
- onForceLogout();
601
- }
602
- };
603
- const handleOnRefreshTokens = async () => {
604
- var _a;
605
- const refreshToken = (_a = onGetTokens()) == null ? void 0 : _a.refreshToken;
606
- if (!refreshToken || !onRefreshTokens) {
607
- if (isDebug) u.danger("[AuthStateProvider] handleOnRefreshTokens", "refreshToken|onRefreshTokens empty");
608
- throw new FetcherException({ message: "refreshToken|onRefreshTokens empty", code: "REFRESH_TOKEN_EMPTY" });
609
- }
610
- try {
611
- const authTokens = await onRefreshTokens(refreshToken);
612
- if (w(authTokens)) {
613
- if (isDebug) u.danger("[AuthStateProvider] handleOnRefreshTokens", "new refresh token fail");
614
- throw new FetcherException({ message: "new refresh token fail", code: "NEW_REFRESH_TOKEN_EMPTY" });
615
- }
616
- updateTokens(authTokens);
617
- return;
618
- } catch (err) {
619
- handleOnForceLogout();
620
- throw new FetcherException({ message: "refresh token fail", code: "REFRESH_TOKEN_CATCH" });
621
- }
622
- };
623
- return /* @__PURE__ */ jsxRuntimeExports.jsx(AuthStateContext.Provider, { value: {
624
- lastUpdateTimestamp,
625
- isAuth,
626
- getTokens: onGetTokens,
627
- updateTokens,
628
- refreshTokens: handleOnRefreshTokens,
629
- forceLogout: handleOnForceLogout
630
- }, children });
586
+ const prototype2 = getPrototypeOf(val);
587
+ return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(toStringTag in val) && !(iterator in val);
631
588
  };
632
- class AxiosCancelException extends Error {
633
- constructor(response) {
634
- super(response.message);
635
- __publicField(this, "code");
636
- __publicField(this, "devInfo");
637
- __publicField(this, "args");
638
- __publicField(this, "path");
639
- this.response = response;
640
- this.code = response.code;
641
- this.args = response.args;
642
- this.path = response.path;
643
- this.initName();
589
+ const isDate = kindOfTest("Date");
590
+ const isFile = kindOfTest("File");
591
+ const isBlob = kindOfTest("Blob");
592
+ const isFileList = kindOfTest("FileList");
593
+ const isStream = (val) => isObject(val) && isFunction(val.pipe);
594
+ const isFormData = (thing) => {
595
+ let kind;
596
+ return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
597
+ kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]"));
598
+ };
599
+ const isURLSearchParams = kindOfTest("URLSearchParams");
600
+ const [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest);
601
+ const trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
602
+ function forEach(obj, fn, { allOwnKeys = false } = {}) {
603
+ if (obj === null || typeof obj === "undefined") {
604
+ return;
644
605
  }
645
- initName() {
646
- this.name = this.constructor.name;
606
+ let i2;
607
+ let l2;
608
+ if (typeof obj !== "object") {
609
+ obj = [obj];
647
610
  }
648
- getInfo() {
649
- return {
650
- message: this.response.message,
651
- code: this.response.code,
652
- args: this.response.args,
653
- path: this.response.path
654
- };
611
+ if (isArray(obj)) {
612
+ for (i2 = 0, l2 = obj.length; i2 < l2; i2++) {
613
+ fn.call(null, obj[i2], i2, obj);
614
+ }
615
+ } else {
616
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
617
+ const len = keys.length;
618
+ let key;
619
+ for (i2 = 0; i2 < len; i2++) {
620
+ key = keys[i2];
621
+ fn.call(null, obj[key], key, obj);
622
+ }
655
623
  }
656
624
  }
657
- const getGraphQLResponseFormatError = (axiosError) => {
658
- var _a, _b, _c;
659
- const responseData = (_a = axiosError == null ? void 0 : axiosError.response) == null ? void 0 : _a.data;
660
- if ((_b = responseData.errors) == null ? void 0 : _b[0]) {
661
- return (_c = responseData.errors) == null ? void 0 : _c[0];
662
- }
663
- if (axiosError == null ? void 0 : axiosError.isAxiosError) {
664
- return {
665
- message: axiosError.message,
666
- code: axiosError.code
667
- };
625
+ function findKey(obj, key) {
626
+ key = key.toLowerCase();
627
+ const keys = Object.keys(obj);
628
+ let i2 = keys.length;
629
+ let _key;
630
+ while (i2-- > 0) {
631
+ _key = keys[i2];
632
+ if (key === _key.toLowerCase()) {
633
+ return _key;
634
+ }
668
635
  }
669
- return {
670
- message: "Axios error",
671
- code: "ERR_SYS_BAD_RESPONSE"
636
+ return null;
637
+ }
638
+ const _global = (() => {
639
+ if (typeof globalThis !== "undefined") return globalThis;
640
+ return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
641
+ })();
642
+ const isContextDefined = (context) => !isUndefined(context) && context !== _global;
643
+ function merge() {
644
+ const { caseless } = isContextDefined(this) && this || {};
645
+ const result = {};
646
+ const assignValue = (val, key) => {
647
+ const targetKey = caseless && findKey(result, key) || key;
648
+ if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
649
+ result[targetKey] = merge(result[targetKey], val);
650
+ } else if (isPlainObject(val)) {
651
+ result[targetKey] = merge({}, val);
652
+ } else if (isArray(val)) {
653
+ result[targetKey] = val.slice();
654
+ } else {
655
+ result[targetKey] = val;
656
+ }
672
657
  };
673
- };
674
- const getRestFulResponseFormatError = (axiosError) => {
675
- var _a;
676
- const responseData = (_a = axiosError == null ? void 0 : axiosError.response) == null ? void 0 : _a.data;
677
- if (responseData) {
678
- return responseData;
658
+ for (let i2 = 0, l2 = arguments.length; i2 < l2; i2++) {
659
+ arguments[i2] && forEach(arguments[i2], assignValue);
679
660
  }
680
- if (axiosError == null ? void 0 : axiosError.isAxiosError) {
681
- return {
682
- message: axiosError.message,
683
- code: axiosError.code
684
- };
661
+ return result;
662
+ }
663
+ const extend = (a2, b, thisArg, { allOwnKeys } = {}) => {
664
+ forEach(b, (val, key) => {
665
+ if (thisArg && isFunction(val)) {
666
+ a2[key] = bind(val, thisArg);
667
+ } else {
668
+ a2[key] = val;
669
+ }
670
+ }, { allOwnKeys });
671
+ return a2;
672
+ };
673
+ const stripBOM = (content) => {
674
+ if (content.charCodeAt(0) === 65279) {
675
+ content = content.slice(1);
685
676
  }
686
- return {
687
- message: "Axios error",
688
- code: "ERR_SYS_BAD_RESPONSE"
689
- };
677
+ return content;
690
678
  };
691
- let isTokenRefreshing = false;
692
- let pendingRequestQueues = [];
693
- const AxiosClientContext = createContext(null);
694
- const FetcherProvider = ({
695
- children,
696
- axiosInstance,
697
- locale = "en-US",
698
- getResponseFormatError = getRestFulResponseFormatError,
699
- onResponseError,
700
- checkIsRefreshTokenRequest,
701
- checkIsErrorResponse,
702
- authorizationPrefix = "Bearer",
703
- isDebug = false
704
- }) => {
705
- const {
706
- getTokens,
707
- updateTokens,
708
- refreshTokens,
709
- forceLogout
710
- } = useAuthState();
711
- useLayoutEffect(() => {
712
- const interceptorReq = axiosInstance.interceptors.request.use(interceptorsRequest);
713
- const interceptorRes = axiosInstance.interceptors.response.use(interceptorsResponseSuccess, interceptorsResponseError);
714
- return () => {
715
- axiosInstance.interceptors.request.eject(interceptorReq);
716
- axiosInstance.interceptors.response.eject(interceptorRes);
717
- };
718
- }, [getTokens, refreshTokens, updateTokens, forceLogout]);
719
- const runPendingRequest = (isSuccess) => {
720
- if (isDebug) u.warning("[FetcherProvider] runPendingRequest", { isSuccess });
721
- isTokenRefreshing = false;
722
- for (const cb of pendingRequestQueues) {
723
- cb(isSuccess);
724
- }
725
- pendingRequestQueues = [];
726
- };
727
- const pushPendingRequestQueues = (resolve, reject) => {
728
- return (originConfig) => {
729
- if (isDebug) u.info("[FetcherProvider] Request add pending queue", { originConfig });
730
- pendingRequestQueues.push((isTokenRefreshOK) => {
731
- if (isTokenRefreshOK) {
732
- originConfig.pendingRequest = true;
733
- resolve(axiosInstance(originConfig));
734
- } else {
735
- reject(new FetcherException({
736
- message: "Please login before continuing",
737
- code: "UNAUTHORIZED",
738
- path: "AxiosClientProvider.pushPendingRequestQueues"
739
- }));
740
- }
741
- });
742
- };
743
- };
744
- const interceptorsRequest = (originConfig) => {
745
- return new Promise((resolve, reject) => {
746
- var _a, _b;
747
- originConfig.headers["Accept-Language"] = locale;
748
- const accessTokens = (_a = getTokens()) == null ? void 0 : _a.accessToken;
749
- const forceGuest = (_b = originConfig.fetchOptions) == null ? void 0 : _b.forceGuest;
750
- if (!forceGuest && accessTokens) {
751
- originConfig.headers["Authorization"] = [authorizationPrefix, accessTokens].filter((str) => str).join(" ");
752
- }
753
- const isRefreshTokenAPI = originConfig && checkIsRefreshTokenRequest ? checkIsRefreshTokenRequest(originConfig) : false;
754
- if (!isRefreshTokenAPI && isTokenRefreshing) {
755
- pushPendingRequestQueues(resolve, reject)(originConfig);
756
- reject(new AxiosCancelException({
757
- message: "Token refreshing, so request save queues not send",
758
- code: "REFRESHING_TOKEN"
759
- }));
760
- return;
679
+ const inherits = (constructor, superConstructor, props, descriptors2) => {
680
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
681
+ constructor.prototype.constructor = constructor;
682
+ Object.defineProperty(constructor, "super", {
683
+ value: superConstructor.prototype
684
+ });
685
+ props && Object.assign(constructor.prototype, props);
686
+ };
687
+ const toFlatObject = (sourceObj, destObj, filter2, propFilter) => {
688
+ let props;
689
+ let i2;
690
+ let prop;
691
+ const merged = {};
692
+ destObj = destObj || {};
693
+ if (sourceObj == null) return destObj;
694
+ do {
695
+ props = Object.getOwnPropertyNames(sourceObj);
696
+ i2 = props.length;
697
+ while (i2-- > 0) {
698
+ prop = props[i2];
699
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
700
+ destObj[prop] = sourceObj[prop];
701
+ merged[prop] = true;
761
702
  }
762
- resolve(originConfig);
763
- });
764
- };
765
- const interceptorsResponseSuccess = (response) => {
766
- if (isDebug) u.info("[FetcherProvider] interceptorsResponseSuccess", { response });
767
- if (checkIsErrorResponse && checkIsErrorResponse(response)) {
768
- const axiosError = new Error("Business logic error");
769
- axiosError.response = response;
770
- axiosError.config = response.config;
771
- axiosError.status = response.status;
772
- axiosError.isAxiosError = true;
773
- return Promise.reject(axiosError);
774
703
  }
775
- return response;
704
+ sourceObj = filter2 !== false && getPrototypeOf(sourceObj);
705
+ } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype);
706
+ return destObj;
707
+ };
708
+ const endsWith = (str, searchString, position) => {
709
+ str = String(str);
710
+ if (position === void 0 || position > str.length) {
711
+ position = str.length;
712
+ }
713
+ position -= searchString.length;
714
+ const lastIndex = str.indexOf(searchString, position);
715
+ return lastIndex !== -1 && lastIndex === position;
716
+ };
717
+ const toArray = (thing) => {
718
+ if (!thing) return null;
719
+ if (isArray(thing)) return thing;
720
+ let i2 = thing.length;
721
+ if (!isNumber(i2)) return null;
722
+ const arr = new Array(i2);
723
+ while (i2-- > 0) {
724
+ arr[i2] = thing[i2];
725
+ }
726
+ return arr;
727
+ };
728
+ const isTypedArray = /* @__PURE__ */ ((TypedArray) => {
729
+ return (thing) => {
730
+ return TypedArray && thing instanceof TypedArray;
776
731
  };
777
- const interceptorsResponseError = (axiosError) => {
778
- if (isDebug) u.danger("[FetcherProvider] interceptorsResponseError", { axiosError });
779
- const response = axiosError.response;
780
- const originalConfig = axiosError.config;
781
- const status = axiosError.status;
782
- const responseFirstError = getResponseFormatError(axiosError);
783
- if (isDebug) u.warning("[FetcherProvider] interceptorsResponseError(2)", { status, responseFirstError });
784
- if (onResponseError && originalConfig.ignoreErrorCallback !== true) {
785
- onResponseError(responseFirstError);
732
+ })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
733
+ const forEachEntry = (obj, fn) => {
734
+ const generator = obj && obj[iterator];
735
+ const _iterator = generator.call(obj);
736
+ let result;
737
+ while ((result = _iterator.next()) && !result.done) {
738
+ const pair = result.value;
739
+ fn.call(obj, pair[0], pair[1]);
740
+ }
741
+ };
742
+ const matchAll = (regExp, str) => {
743
+ let matches;
744
+ const arr = [];
745
+ while ((matches = regExp.exec(str)) !== null) {
746
+ arr.push(matches);
747
+ }
748
+ return arr;
749
+ };
750
+ const isHTMLForm = kindOfTest("HTMLFormElement");
751
+ const toCamelCase = (str) => {
752
+ return str.toLowerCase().replace(
753
+ /[-_\s]([a-z\d])(\w*)/g,
754
+ function replacer(m, p1, p2) {
755
+ return p1.toUpperCase() + p2;
786
756
  }
787
- const isRefresh = originalConfig && checkIsRefreshTokenRequest ? checkIsRefreshTokenRequest(originalConfig) : false;
788
- if (response && originalConfig) {
789
- if (status === 401 || responseFirstError.code === "UNAUTHENTICATED") {
790
- const tokens = getTokens();
791
- if (isDebug) u.warning("[FetcherProvider] enter refresh token flow", { refreshToken: tokens == null ? void 0 : tokens.refreshToken });
792
- if (w(tokens == null ? void 0 : tokens.refreshToken) || isRefresh || originalConfig.pendingRequest) {
793
- isTokenRefreshing = false;
794
- if (isDebug) u.warning("[FetcherProvider] no refreshToken/refreshAPI|pendingRequest fail, force logout");
795
- forceLogout();
796
- return Promise.reject(new FetcherException(responseFirstError));
797
- }
798
- if (!isTokenRefreshing) {
799
- isTokenRefreshing = true;
800
- if (isDebug) u.warning("[FetcherProvider] refreshTokens");
801
- refreshTokens().then(() => {
802
- if (isDebug) u.info("[FetcherProvider] refreshTokens success");
803
- runPendingRequest(true);
804
- }).catch(() => {
805
- if (isDebug) u.danger("[FetcherProvider] refreshTokens fail");
806
- runPendingRequest(false);
807
- });
808
- }
809
- return new Promise((resolve, reject) => {
810
- pushPendingRequestQueues(resolve, reject)(originalConfig);
811
- });
812
- }
757
+ );
758
+ };
759
+ const hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
760
+ const isRegExp = kindOfTest("RegExp");
761
+ const reduceDescriptors = (obj, reducer) => {
762
+ const descriptors2 = Object.getOwnPropertyDescriptors(obj);
763
+ const reducedDescriptors = {};
764
+ forEach(descriptors2, (descriptor, name) => {
765
+ let ret;
766
+ if ((ret = reducer(descriptor, name, obj)) !== false) {
767
+ reducedDescriptors[name] = ret || descriptor;
813
768
  }
814
- return Promise.reject(new FetcherException(responseFirstError));
815
- };
816
- return /* @__PURE__ */ jsxRuntimeExports.jsx(
817
- AxiosClientContext.Provider,
818
- {
819
- value: axiosInstance,
820
- children
769
+ });
770
+ Object.defineProperties(obj, reducedDescriptors);
771
+ };
772
+ const freezeMethods = (obj) => {
773
+ reduceDescriptors(obj, (descriptor, name) => {
774
+ if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) {
775
+ return false;
821
776
  }
822
- );
777
+ const value = obj[name];
778
+ if (!isFunction(value)) return;
779
+ descriptor.enumerable = false;
780
+ if ("writable" in descriptor) {
781
+ descriptor.writable = false;
782
+ return;
783
+ }
784
+ if (!descriptor.set) {
785
+ descriptor.set = () => {
786
+ throw Error("Can not rewrite read-only method '" + name + "'");
787
+ };
788
+ }
789
+ });
823
790
  };
824
- function bind(fn, thisArg) {
825
- return function wrap() {
826
- return fn.apply(thisArg, arguments);
791
+ const toObjectSet = (arrayOrString, delimiter) => {
792
+ const obj = {};
793
+ const define = (arr) => {
794
+ arr.forEach((value) => {
795
+ obj[value] = true;
796
+ });
827
797
  };
828
- }
829
- const { toString } = Object.prototype;
830
- const { getPrototypeOf } = Object;
831
- const { iterator, toStringTag } = Symbol;
832
- const kindOf = /* @__PURE__ */ ((cache) => (thing) => {
833
- const str = toString.call(thing);
834
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
835
- })(/* @__PURE__ */ Object.create(null));
836
- const kindOfTest = (type) => {
837
- type = type.toLowerCase();
838
- return (thing) => kindOf(thing) === type;
798
+ isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
799
+ return obj;
839
800
  };
840
- const typeOfTest = (type) => (thing) => typeof thing === type;
841
- const { isArray } = Array;
842
- const isUndefined = typeOfTest("undefined");
843
- function isBuffer(val) {
844
- return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
845
- }
846
- const isArrayBuffer = kindOfTest("ArrayBuffer");
847
- function isArrayBufferView(val) {
848
- let result;
849
- if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
850
- result = ArrayBuffer.isView(val);
851
- } else {
852
- result = val && val.buffer && isArrayBuffer(val.buffer);
853
- }
854
- return result;
855
- }
856
- const isString = typeOfTest("string");
857
- const isFunction = typeOfTest("function");
858
- const isNumber = typeOfTest("number");
859
- const isObject = (thing) => thing !== null && typeof thing === "object";
860
- const isBoolean = (thing) => thing === true || thing === false;
861
- const isPlainObject = (val) => {
862
- if (kindOf(val) !== "object") {
863
- return false;
864
- }
865
- const prototype2 = getPrototypeOf(val);
866
- return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(toStringTag in val) && !(iterator in val);
867
- };
868
- const isDate = kindOfTest("Date");
869
- const isFile = kindOfTest("File");
870
- const isBlob = kindOfTest("Blob");
871
- const isFileList = kindOfTest("FileList");
872
- const isStream = (val) => isObject(val) && isFunction(val.pipe);
873
- const isFormData = (thing) => {
874
- let kind;
875
- return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
876
- kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]"));
877
- };
878
- const isURLSearchParams = kindOfTest("URLSearchParams");
879
- const [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest);
880
- const trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
881
- function forEach(obj, fn, { allOwnKeys = false } = {}) {
882
- if (obj === null || typeof obj === "undefined") {
883
- return;
884
- }
885
- let i2;
886
- let l2;
887
- if (typeof obj !== "object") {
888
- obj = [obj];
889
- }
890
- if (isArray(obj)) {
891
- for (i2 = 0, l2 = obj.length; i2 < l2; i2++) {
892
- fn.call(null, obj[i2], i2, obj);
893
- }
894
- } else {
895
- const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
896
- const len = keys.length;
897
- let key;
898
- for (i2 = 0; i2 < len; i2++) {
899
- key = keys[i2];
900
- fn.call(null, obj[key], key, obj);
901
- }
902
- }
903
- }
904
- function findKey(obj, key) {
905
- key = key.toLowerCase();
906
- const keys = Object.keys(obj);
907
- let i2 = keys.length;
908
- let _key;
909
- while (i2-- > 0) {
910
- _key = keys[i2];
911
- if (key === _key.toLowerCase()) {
912
- return _key;
913
- }
914
- }
915
- return null;
916
- }
917
- const _global = (() => {
918
- if (typeof globalThis !== "undefined") return globalThis;
919
- return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
920
- })();
921
- const isContextDefined = (context) => !isUndefined(context) && context !== _global;
922
- function merge() {
923
- const { caseless } = isContextDefined(this) && this || {};
924
- const result = {};
925
- const assignValue = (val, key) => {
926
- const targetKey = caseless && findKey(result, key) || key;
927
- if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
928
- result[targetKey] = merge(result[targetKey], val);
929
- } else if (isPlainObject(val)) {
930
- result[targetKey] = merge({}, val);
931
- } else if (isArray(val)) {
932
- result[targetKey] = val.slice();
933
- } else {
934
- result[targetKey] = val;
935
- }
936
- };
937
- for (let i2 = 0, l2 = arguments.length; i2 < l2; i2++) {
938
- arguments[i2] && forEach(arguments[i2], assignValue);
939
- }
940
- return result;
941
- }
942
- const extend = (a2, b, thisArg, { allOwnKeys } = {}) => {
943
- forEach(b, (val, key) => {
944
- if (thisArg && isFunction(val)) {
945
- a2[key] = bind(val, thisArg);
946
- } else {
947
- a2[key] = val;
948
- }
949
- }, { allOwnKeys });
950
- return a2;
951
- };
952
- const stripBOM = (content) => {
953
- if (content.charCodeAt(0) === 65279) {
954
- content = content.slice(1);
955
- }
956
- return content;
957
- };
958
- const inherits = (constructor, superConstructor, props, descriptors2) => {
959
- constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
960
- constructor.prototype.constructor = constructor;
961
- Object.defineProperty(constructor, "super", {
962
- value: superConstructor.prototype
963
- });
964
- props && Object.assign(constructor.prototype, props);
965
- };
966
- const toFlatObject = (sourceObj, destObj, filter2, propFilter) => {
967
- let props;
968
- let i2;
969
- let prop;
970
- const merged = {};
971
- destObj = destObj || {};
972
- if (sourceObj == null) return destObj;
973
- do {
974
- props = Object.getOwnPropertyNames(sourceObj);
975
- i2 = props.length;
976
- while (i2-- > 0) {
977
- prop = props[i2];
978
- if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
979
- destObj[prop] = sourceObj[prop];
980
- merged[prop] = true;
981
- }
982
- }
983
- sourceObj = filter2 !== false && getPrototypeOf(sourceObj);
984
- } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype);
985
- return destObj;
986
- };
987
- const endsWith = (str, searchString, position) => {
988
- str = String(str);
989
- if (position === void 0 || position > str.length) {
990
- position = str.length;
991
- }
992
- position -= searchString.length;
993
- const lastIndex = str.indexOf(searchString, position);
994
- return lastIndex !== -1 && lastIndex === position;
995
- };
996
- const toArray = (thing) => {
997
- if (!thing) return null;
998
- if (isArray(thing)) return thing;
999
- let i2 = thing.length;
1000
- if (!isNumber(i2)) return null;
1001
- const arr = new Array(i2);
1002
- while (i2-- > 0) {
1003
- arr[i2] = thing[i2];
1004
- }
1005
- return arr;
1006
- };
1007
- const isTypedArray = /* @__PURE__ */ ((TypedArray) => {
1008
- return (thing) => {
1009
- return TypedArray && thing instanceof TypedArray;
1010
- };
1011
- })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
1012
- const forEachEntry = (obj, fn) => {
1013
- const generator = obj && obj[iterator];
1014
- const _iterator = generator.call(obj);
1015
- let result;
1016
- while ((result = _iterator.next()) && !result.done) {
1017
- const pair = result.value;
1018
- fn.call(obj, pair[0], pair[1]);
1019
- }
1020
- };
1021
- const matchAll = (regExp, str) => {
1022
- let matches;
1023
- const arr = [];
1024
- while ((matches = regExp.exec(str)) !== null) {
1025
- arr.push(matches);
1026
- }
1027
- return arr;
1028
- };
1029
- const isHTMLForm = kindOfTest("HTMLFormElement");
1030
- const toCamelCase = (str) => {
1031
- return str.toLowerCase().replace(
1032
- /[-_\s]([a-z\d])(\w*)/g,
1033
- function replacer(m, p1, p2) {
1034
- return p1.toUpperCase() + p2;
1035
- }
1036
- );
1037
- };
1038
- const hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
1039
- const isRegExp = kindOfTest("RegExp");
1040
- const reduceDescriptors = (obj, reducer) => {
1041
- const descriptors2 = Object.getOwnPropertyDescriptors(obj);
1042
- const reducedDescriptors = {};
1043
- forEach(descriptors2, (descriptor, name) => {
1044
- let ret;
1045
- if ((ret = reducer(descriptor, name, obj)) !== false) {
1046
- reducedDescriptors[name] = ret || descriptor;
1047
- }
1048
- });
1049
- Object.defineProperties(obj, reducedDescriptors);
1050
- };
1051
- const freezeMethods = (obj) => {
1052
- reduceDescriptors(obj, (descriptor, name) => {
1053
- if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) {
1054
- return false;
1055
- }
1056
- const value = obj[name];
1057
- if (!isFunction(value)) return;
1058
- descriptor.enumerable = false;
1059
- if ("writable" in descriptor) {
1060
- descriptor.writable = false;
1061
- return;
1062
- }
1063
- if (!descriptor.set) {
1064
- descriptor.set = () => {
1065
- throw Error("Can not rewrite read-only method '" + name + "'");
1066
- };
1067
- }
1068
- });
1069
- };
1070
- const toObjectSet = (arrayOrString, delimiter) => {
1071
- const obj = {};
1072
- const define = (arr) => {
1073
- arr.forEach((value) => {
1074
- obj[value] = true;
1075
- });
1076
- };
1077
- isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
1078
- return obj;
1079
- };
1080
- const noop = () => {
1081
- };
1082
- const toFiniteNumber = (value, defaultValue) => {
1083
- return value != null && Number.isFinite(value = +value) ? value : defaultValue;
1084
- };
1085
- function isSpecCompliantForm(thing) {
1086
- return !!(thing && isFunction(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]);
801
+ const noop = () => {
802
+ };
803
+ const toFiniteNumber = (value, defaultValue) => {
804
+ return value != null && Number.isFinite(value = +value) ? value : defaultValue;
805
+ };
806
+ function isSpecCompliantForm(thing) {
807
+ return !!(thing && isFunction(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]);
1087
808
  }
1088
809
  const toJSONObject = (obj) => {
1089
810
  const stack = new Array(10);
@@ -1307,6 +1028,9 @@ function toFormData$1(obj, formData, options) {
1307
1028
  if (utils$1.isDate(value)) {
1308
1029
  return value.toISOString();
1309
1030
  }
1031
+ if (utils$1.isBoolean(value)) {
1032
+ return value.toString();
1033
+ }
1310
1034
  if (!useBlob && utils$1.isBlob(value)) {
1311
1035
  throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");
1312
1036
  }
@@ -2610,7 +2334,7 @@ const fetchAdapter = isFetchSupported && (async (config) => {
2610
2334
  duplex: "half",
2611
2335
  credentials: isCredentialsSupported ? withCredentials : void 0
2612
2336
  });
2613
- let response = await fetch(request);
2337
+ let response = await fetch(request, fetchOptions);
2614
2338
  const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
2615
2339
  if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
2616
2340
  const options = {};
@@ -2751,7 +2475,7 @@ function dispatchRequest(config) {
2751
2475
  return Promise.reject(reason);
2752
2476
  });
2753
2477
  }
2754
- const VERSION$1 = "1.9.0";
2478
+ const VERSION$1 = "1.10.0";
2755
2479
  const validators$1 = {};
2756
2480
  ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i2) => {
2757
2481
  validators$1[type] = function validator2(thing) {
@@ -3203,6 +2927,291 @@ const {
3203
2927
  getAdapter,
3204
2928
  mergeConfig
3205
2929
  } = axios;
2930
+ class FetcherException extends Error {
2931
+ constructor(response) {
2932
+ super(response.message);
2933
+ __publicField(this, "code");
2934
+ __publicField(this, "args");
2935
+ __publicField(this, "path");
2936
+ this.response = response;
2937
+ this.code = response.code;
2938
+ this.args = response.args;
2939
+ this.path = response.path;
2940
+ this.name = this.constructor.name;
2941
+ Object.setPrototypeOf(this, FetcherException.prototype);
2942
+ }
2943
+ }
2944
+ const AuthStateContext = createContext({
2945
+ lastUpdateTimestamp: 0,
2946
+ isAuth: false,
2947
+ getTokens: () => {
2948
+ u.warning("AuthStateContext", "getTokens not yet ready");
2949
+ return null;
2950
+ },
2951
+ updateTokens: () => u.warning("AuthStateContext", "updateTokens not yet ready"),
2952
+ forceLogout: () => u.warning("AuthStateContext", "forceLogout not yet ready"),
2953
+ refreshTokens: async () => {
2954
+ u.warning("AuthStateContext", "refreshToken not yet ready");
2955
+ return void 0;
2956
+ }
2957
+ });
2958
+ const useAuthState = () => useContext(AuthStateContext);
2959
+ const AuthStateProvider = ({
2960
+ children,
2961
+ onGetTokens,
2962
+ onSetTokens,
2963
+ onRefreshTokens,
2964
+ onForceLogout,
2965
+ isDebug = false
2966
+ }) => {
2967
+ const [lastUpdateTimestamp, setLastUpdateTimestamp] = useState(0);
2968
+ const [isAuth, setIsAuth] = useState(() => {
2969
+ return D(onGetTokens());
2970
+ });
2971
+ const updateTokens = (tokensOrUpdater) => {
2972
+ let nextTokens;
2973
+ if (typeof tokensOrUpdater === "function") {
2974
+ nextTokens = tokensOrUpdater(onGetTokens());
2975
+ } else {
2976
+ nextTokens = tokensOrUpdater;
2977
+ }
2978
+ onSetTokens(nextTokens);
2979
+ setIsAuth(D(nextTokens));
2980
+ setLastUpdateTimestamp(Date.now());
2981
+ };
2982
+ const handleOnForceLogout = () => {
2983
+ updateTokens(null);
2984
+ if (onForceLogout) {
2985
+ onForceLogout();
2986
+ }
2987
+ };
2988
+ const handleOnRefreshTokens = async () => {
2989
+ var _a;
2990
+ const refreshToken = (_a = onGetTokens()) == null ? void 0 : _a.refreshToken;
2991
+ if (!refreshToken || !onRefreshTokens) {
2992
+ if (isDebug) u.danger("[AuthStateProvider] handleOnRefreshTokens", "refreshToken|onRefreshTokens empty");
2993
+ throw new FetcherException({ message: "refreshToken|onRefreshTokens empty", code: "REFRESH_TOKEN_EMPTY" });
2994
+ }
2995
+ try {
2996
+ const authTokens = await onRefreshTokens(refreshToken);
2997
+ if (w(authTokens)) {
2998
+ if (isDebug) u.danger("[AuthStateProvider] handleOnRefreshTokens", "new refresh token fail");
2999
+ throw new FetcherException({ message: "new refresh token fail", code: "NEW_REFRESH_TOKEN_EMPTY" });
3000
+ }
3001
+ updateTokens(authTokens);
3002
+ return;
3003
+ } catch (err) {
3004
+ handleOnForceLogout();
3005
+ throw new FetcherException({ message: "refresh token fail", code: "REFRESH_TOKEN_CATCH" });
3006
+ }
3007
+ };
3008
+ return /* @__PURE__ */ jsxRuntimeExports.jsx(AuthStateContext.Provider, { value: {
3009
+ lastUpdateTimestamp,
3010
+ isAuth,
3011
+ getTokens: onGetTokens,
3012
+ updateTokens,
3013
+ refreshTokens: handleOnRefreshTokens,
3014
+ forceLogout: handleOnForceLogout
3015
+ }, children });
3016
+ };
3017
+ class AxiosCancelException extends Error {
3018
+ constructor(response) {
3019
+ super(response.message);
3020
+ __publicField(this, "code");
3021
+ __publicField(this, "devInfo");
3022
+ __publicField(this, "args");
3023
+ __publicField(this, "path");
3024
+ this.response = response;
3025
+ this.code = response.code;
3026
+ this.args = response.args;
3027
+ this.path = response.path;
3028
+ this.initName();
3029
+ }
3030
+ initName() {
3031
+ this.name = this.constructor.name;
3032
+ }
3033
+ getInfo() {
3034
+ return {
3035
+ message: this.response.message,
3036
+ code: this.response.code,
3037
+ args: this.response.args,
3038
+ path: this.response.path
3039
+ };
3040
+ }
3041
+ }
3042
+ const getGraphQLResponseFormatError = (axiosError) => {
3043
+ var _a, _b, _c;
3044
+ const responseData = (_a = axiosError == null ? void 0 : axiosError.response) == null ? void 0 : _a.data;
3045
+ if ((_b = responseData.errors) == null ? void 0 : _b[0]) {
3046
+ return (_c = responseData.errors) == null ? void 0 : _c[0];
3047
+ }
3048
+ if (axiosError == null ? void 0 : axiosError.isAxiosError) {
3049
+ return {
3050
+ message: axiosError.message,
3051
+ code: axiosError.code
3052
+ };
3053
+ }
3054
+ return {
3055
+ message: "Axios error",
3056
+ code: "ERR_SYS_BAD_RESPONSE"
3057
+ };
3058
+ };
3059
+ const getRestFulResponseFormatError = (axiosError) => {
3060
+ var _a;
3061
+ const responseData = (_a = axiosError == null ? void 0 : axiosError.response) == null ? void 0 : _a.data;
3062
+ if (responseData) {
3063
+ return responseData;
3064
+ }
3065
+ if (axiosError == null ? void 0 : axiosError.isAxiosError) {
3066
+ return {
3067
+ message: axiosError.message,
3068
+ code: axiosError.code
3069
+ };
3070
+ }
3071
+ return {
3072
+ message: "Axios error",
3073
+ code: "ERR_SYS_BAD_RESPONSE"
3074
+ };
3075
+ };
3076
+ let isTokenRefreshing = false;
3077
+ let pendingRequestQueues = [];
3078
+ const AxiosClientContext = createContext(null);
3079
+ const FetcherProvider = ({
3080
+ children,
3081
+ axiosInstance,
3082
+ locale = "en-US",
3083
+ getResponseFormatError = getRestFulResponseFormatError,
3084
+ onResponseError,
3085
+ checkIsRefreshTokenRequest,
3086
+ checkIsErrorResponse,
3087
+ checkErrorIs401,
3088
+ authorizationPrefix = "Bearer",
3089
+ isDebug = false
3090
+ }) => {
3091
+ const {
3092
+ getTokens,
3093
+ updateTokens,
3094
+ refreshTokens,
3095
+ forceLogout
3096
+ } = useAuthState();
3097
+ useLayoutEffect(() => {
3098
+ const interceptorReq = axiosInstance.interceptors.request.use(interceptorsRequest);
3099
+ const interceptorRes = axiosInstance.interceptors.response.use(interceptorsResponseSuccess, interceptorsResponseError);
3100
+ return () => {
3101
+ axiosInstance.interceptors.request.eject(interceptorReq);
3102
+ axiosInstance.interceptors.response.eject(interceptorRes);
3103
+ };
3104
+ }, [getTokens, refreshTokens, updateTokens, forceLogout]);
3105
+ const runPendingRequest = (isSuccess) => {
3106
+ if (isDebug) u.warning("[FetcherProvider] runPendingRequest", { isSuccess });
3107
+ isTokenRefreshing = false;
3108
+ for (const cb of pendingRequestQueues) {
3109
+ cb(isSuccess);
3110
+ }
3111
+ pendingRequestQueues = [];
3112
+ };
3113
+ const pushPendingRequestQueues = (resolve, reject) => {
3114
+ return (originConfig) => {
3115
+ if (isDebug) u.info("[FetcherProvider] Request add pending queue", { originConfig });
3116
+ pendingRequestQueues.push((isTokenRefreshOK) => {
3117
+ if (isTokenRefreshOK) {
3118
+ originConfig.pendingRequest = true;
3119
+ resolve(axiosInstance(originConfig));
3120
+ } else {
3121
+ reject(new FetcherException({
3122
+ message: "Please login before continuing",
3123
+ code: "UNAUTHORIZED",
3124
+ path: "AxiosClientProvider.pushPendingRequestQueues"
3125
+ }));
3126
+ }
3127
+ });
3128
+ };
3129
+ };
3130
+ const interceptorsRequest = (originConfig) => {
3131
+ return new Promise((resolve, reject) => {
3132
+ var _a, _b;
3133
+ originConfig.headers["Accept-Language"] = locale;
3134
+ const accessTokens = (_a = getTokens()) == null ? void 0 : _a.accessToken;
3135
+ const forceGuest = (_b = originConfig.fetchOptions) == null ? void 0 : _b.forceGuest;
3136
+ if (!forceGuest && accessTokens) {
3137
+ originConfig.headers["Authorization"] = [authorizationPrefix, accessTokens].filter((str) => str).join(" ");
3138
+ }
3139
+ const isRefreshTokenAPI = originConfig && checkIsRefreshTokenRequest ? checkIsRefreshTokenRequest(originConfig) : false;
3140
+ if (!isRefreshTokenAPI && isTokenRefreshing) {
3141
+ pushPendingRequestQueues(resolve, reject)(originConfig);
3142
+ reject(new AxiosCancelException({
3143
+ message: "Token refreshing, so request save queues not send",
3144
+ code: "REFRESHING_TOKEN"
3145
+ }));
3146
+ return;
3147
+ }
3148
+ resolve(originConfig);
3149
+ });
3150
+ };
3151
+ const interceptorsResponseSuccess = (response) => {
3152
+ if (isDebug) u.info("[FetcherProvider] interceptorsResponseSuccess", { response });
3153
+ if (checkIsErrorResponse && checkIsErrorResponse(response)) {
3154
+ return interceptorsResponseError(new AxiosError(
3155
+ response.data.message,
3156
+ "ERR_BAD_RESPONSE",
3157
+ response.config,
3158
+ response.request,
3159
+ response
3160
+ ));
3161
+ }
3162
+ return response;
3163
+ };
3164
+ const handleOnResponseError = (responseFirstError) => {
3165
+ if (onResponseError) {
3166
+ onResponseError(responseFirstError);
3167
+ }
3168
+ };
3169
+ const interceptorsResponseError = (axiosError) => {
3170
+ if (isDebug) u.danger("[FetcherProvider] interceptorsResponseError", { axiosError });
3171
+ const response = axiosError.response;
3172
+ const originalConfig = axiosError.config;
3173
+ const status = axiosError.status;
3174
+ const responseFirstError = getResponseFormatError(axiosError);
3175
+ if (isDebug) u.warning("[FetcherProvider] interceptorsResponseError(2)", { status, responseFirstError });
3176
+ const isRefresh = originalConfig && checkIsRefreshTokenRequest ? checkIsRefreshTokenRequest(originalConfig) : false;
3177
+ if (response && originalConfig) {
3178
+ if (status === 401 || checkErrorIs401 && checkErrorIs401(responseFirstError)) {
3179
+ const tokens = getTokens();
3180
+ if (isDebug) u.warning("[FetcherProvider] enter refresh token flow", { refreshToken: tokens == null ? void 0 : tokens.refreshToken });
3181
+ if (w(tokens == null ? void 0 : tokens.refreshToken) || isRefresh || originalConfig.pendingRequest) {
3182
+ isTokenRefreshing = false;
3183
+ if (isDebug) u.warning("[FetcherProvider] no refreshToken/refreshAPI|pendingRequest fail, force logout");
3184
+ forceLogout();
3185
+ if (originalConfig.ignoreErrorCallback !== true) handleOnResponseError(responseFirstError);
3186
+ return Promise.reject(new FetcherException(responseFirstError));
3187
+ }
3188
+ if (!isTokenRefreshing) {
3189
+ isTokenRefreshing = true;
3190
+ if (isDebug) u.warning("[FetcherProvider] refreshTokens");
3191
+ refreshTokens().then(() => {
3192
+ if (isDebug) u.info("[FetcherProvider] refreshTokens success");
3193
+ runPendingRequest(true);
3194
+ }).catch(() => {
3195
+ if (isDebug) u.danger("[FetcherProvider] refreshTokens fail");
3196
+ runPendingRequest(false);
3197
+ });
3198
+ }
3199
+ return new Promise((resolve, reject) => {
3200
+ pushPendingRequestQueues(resolve, reject)(originalConfig);
3201
+ });
3202
+ }
3203
+ }
3204
+ if (originalConfig.ignoreErrorCallback !== true) handleOnResponseError(responseFirstError);
3205
+ return Promise.reject(new FetcherException(responseFirstError));
3206
+ };
3207
+ return /* @__PURE__ */ jsxRuntimeExports.jsx(
3208
+ AxiosClientContext.Provider,
3209
+ {
3210
+ value: axiosInstance,
3211
+ children
3212
+ }
3213
+ );
3214
+ };
3206
3215
  const createAxiosInstance = (config) => {
3207
3216
  return axios.create({
3208
3217
  timeout: 2 * 60 * 1e3,