@ahoo-wang/fetcher-react 2.6.15 → 2.6.18

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.
package/dist/index.umd.js CHANGED
@@ -1,18 +1,2 @@
1
- (function(C,d){typeof exports=="object"&&typeof module<"u"?d(exports,require("react"),require("@ahoo-wang/fetcher")):typeof define=="function"&&define.amd?define(["exports","react","@ahoo-wang/fetcher"],d):(C=typeof globalThis<"u"?globalThis:C||self,d(C.FetcherReact={},C.React,C.Fetcher))})(this,(function(C,d,j){"use strict";function ie(){const e=d.useRef(!1),t=d.useCallback(()=>e.current,[]);return d.useEffect(()=>(e.current=!0,()=>{e.current=!1}),[]),t}function Y(e){const t=d.useRef(e);return t.current=e,t}var Ae=(e=>(e.IDLE="idle",e.LOADING="loading",e.SUCCESS="success",e.ERROR="error",e))(Ae||{});function ye(e){const[t,r]=d.useState(e?.initialStatus??"idle"),[a,i]=d.useState(void 0),[u,f]=d.useState(void 0),E=ie(),w=Y(e),b=d.useCallback(()=>{E()&&(r("loading"),f(void 0))},[E]),M=d.useCallback(async g=>{if(E()){i(g),r("success"),f(void 0);try{await w.current?.onSuccess?.(g)}catch(O){console.warn("PromiseState onSuccess callback error:",O)}}},[E,w]),_=d.useCallback(async g=>{if(E()){f(g),r("error"),i(void 0);try{await w.current?.onError?.(g)}catch(O){console.warn("PromiseState onError callback error:",O)}}},[E,w]),A=d.useCallback(()=>{E()&&(r("idle"),f(void 0),i(void 0))},[E]);return d.useMemo(()=>({status:t,loading:t==="loading",result:a,error:u,setLoading:b,setSuccess:M,setError:_,setIdle:A}),[t,a,u,b,M,_,A])}function Ee(){const e=d.useRef(0),t=d.useCallback(()=>++e.current,[]),r=d.useCallback(()=>e.current,[]),a=d.useCallback(f=>f===e.current,[]),i=d.useCallback(()=>{e.current++},[]),u=d.useCallback(()=>{e.current=0},[]);return d.useMemo(()=>({generate:t,current:r,isLatest:a,invalidate:i,reset:u}),[t,r,a,i,u])}function Z(e){const t=ye(e),r=ie(),a=Ee(),i=d.useCallback(async f=>{if(!r())throw new Error("Component is unmounted");const E=a.generate();t.setLoading();try{const b=await(typeof f=="function"?f():f);return r()&&a.isLatest(E)&&await t.setSuccess(b),b}catch(w){if(r()&&a.isLatest(E)&&await t.setError(w),e?.propagateError)throw w;return w}},[t,r,a,e]),u=d.useCallback(()=>{r()&&t.setIdle()},[t,r]);return d.useMemo(()=>({loading:t.loading,result:t.result,error:t.error,execute:i,reset:u,status:t.status}),[t.loading,t.result,t.error,i,u,t.status])}function at(e){const t=d.useCallback(u=>e.addListener(u),[e]),r=d.useCallback(()=>e.get(),[e]),a=d.useSyncExternalStore(t,r,r),i=d.useCallback(u=>e.set(u),[e]);return[a,i]}function ot(e){const{fetcher:t=j.fetcherRegistrar.default}=e||{},r=ye(e),[a,i]=d.useState(void 0),u=ie(),f=d.useRef(),E=Ee(),w=Y(e),b=j.getFetcher(t),M=d.useCallback(async _=>{f.current&&f.current.abort(),f.current=_.abortController??new AbortController,_.abortController=f.current;const A=E.generate();r.setLoading();try{const g=await b.exchange(_,w.current);u()&&E.isLatest(A)&&i(g);const O=await g.extractResult();u()&&E.isLatest(A)&&await r.setSuccess(O)}catch(g){if(g instanceof Error&&g.name==="AbortError"){u()&&r.setIdle();return}u()&&E.isLatest(A)&&await r.setError(g)}finally{f.current===_.abortController&&(f.current=void 0)}},[b,u,w,r,E]);return d.useEffect(()=>()=>{f.current?.abort(),f.current=void 0},[]),d.useMemo(()=>({...r,exchange:a,execute:M}),[r,a,M])}let st=class{constructor(){this.buffer=""}transform(t,r){try{this.buffer+=t;const a=this.buffer.split(`
2
- `);this.buffer=a.pop()||"";for(const i of a)r.enqueue(i)}catch(a){r.error(a)}}flush(t){try{this.buffer&&t.enqueue(this.buffer)}catch(r){t.error(r)}}};class it extends TransformStream{constructor(){super(new st)}}const re=class{};re.ID="id",re.RETRY="retry",re.EVENT="event",re.DATA="data";let ue=re;function ut(e,t,r){switch(e){case ue.EVENT:r.event=t;break;case ue.DATA:r.data.push(t);break;case ue.ID:r.id=t;break;case ue.RETRY:{const a=parseInt(t,10);isNaN(a)||(r.retry=a);break}}}const K="message";let ct=class{constructor(){this.currentEvent={event:K,id:void 0,retry:void 0,data:[]}}transform(t,r){const a=this.currentEvent;try{if(t.trim()===""){a.data.length>0&&(r.enqueue({event:a.event||K,data:a.data.join(`
3
- `),id:a.id||"",retry:a.retry}),a.event=K,a.data=[]);return}if(t.startsWith(":"))return;const i=t.indexOf(":");let u,f;i===-1?(u=t.toLowerCase(),f=""):(u=t.substring(0,i).toLowerCase(),f=t.substring(i+1),f.startsWith(" ")&&(f=f.substring(1))),u=u.trim(),f=f.trim(),ut(u,f,a)}catch(i){r.error(i instanceof Error?i:new Error(String(i))),a.event=K,a.id=void 0,a.retry=void 0,a.data=[]}}flush(t){const r=this.currentEvent;try{r.data.length>0&&t.enqueue({event:r.event||K,data:r.data.join(`
4
- `),id:r.id||"",retry:r.retry})}catch(a){t.error(a instanceof Error?a:new Error(String(a)))}finally{r.event=K,r.id=void 0,r.retry=void 0,r.data=[]}}},ft=class extends TransformStream{constructor(){super(new ct)}};class ne extends j.FetcherError{constructor(t,r,a){super(r,a),this.response=t,this.name="EventStreamConvertError",Object.setPrototypeOf(this,ne.prototype)}}function lt(e){if(!e.body)throw new ne(e,"Response body is null");return e.body.pipeThrough(new TextDecoderStream("utf-8")).pipeThrough(new it).pipeThrough(new ft)}class dt{transform(t,r){const a=JSON.parse(t.data);r.enqueue({data:a,event:t.event,id:t.id,retry:t.retry})}}class ht extends TransformStream{constructor(){super(new dt)}}function pt(e){return e.pipeThrough(new ht)}const ce=e=>e.requiredResponse.requiredJsonEventStream(),Pe="contentType";Object.prototype.hasOwnProperty.call(Response.prototype,Pe)||Object.defineProperty(Response.prototype,Pe,{get(){return this.headers.get(j.CONTENT_TYPE_HEADER)},configurable:!0});const ke="isEventStream";Object.prototype.hasOwnProperty.call(Response.prototype,ke)||Object.defineProperty(Response.prototype,ke,{get(){const e=this.contentType;return e?e.includes(j.ContentTypeValues.TEXT_EVENT_STREAM):!1},configurable:!0}),Object.prototype.hasOwnProperty.call(Response.prototype,"eventStream")||(Response.prototype.eventStream=function(){return this.isEventStream?lt(this):null}),Object.prototype.hasOwnProperty.call(Response.prototype,"requiredEventStream")||(Response.prototype.requiredEventStream=function(){const e=this.eventStream();if(!e)throw new ne(this,`Event stream is not available. Response content-type: [${this.contentType}]`);return e}),Object.prototype.hasOwnProperty.call(Response.prototype,"jsonEventStream")||(Response.prototype.jsonEventStream=function(){const e=this.eventStream();return e?pt(e):null}),Object.prototype.hasOwnProperty.call(Response.prototype,"requiredJsonEventStream")||(Response.prototype.requiredJsonEventStream=function(){const e=this.jsonEventStream();if(!e)throw new ne(this,`Event stream is not available. Response content-type: [${this.contentType}]`);return e});class yt{constructor(t){this.stream=t,this._locked=!0,this.reader=t.getReader()}get locked(){return this._locked}releaseLock(){if(!this._locked)return!1;this._locked=!1;try{return this.reader.releaseLock(),!0}catch(t){return console.debug("Failed to release reader lock:",t),!1}}[Symbol.asyncIterator](){return this}async next(){try{const{done:t,value:r}=await this.reader.read();return t?(this.releaseLock(),{done:!0,value:void 0}):{done:!1,value:r}}catch(t){throw this.releaseLock(),t}}async return(){try{await this.reader.cancel()}catch(t){console.debug("Failed to cancel stream reader:",t)}finally{this.releaseLock()}return{done:!0,value:void 0}}async throw(t){return console.debug("Throwing error:",t),this.releaseLock(),{done:!0,value:void 0}}}typeof ReadableStream.prototype[Symbol.asyncIterator]=="function"||(ReadableStream.prototype[Symbol.asyncIterator]=function(){return new yt(this)});var Ce=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ie={};/*! *****************************************************************************
5
- Copyright (C) Microsoft. All rights reserved.
6
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
7
- this file except in compliance with the License. You may obtain a copy of the
8
- License at http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
11
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
12
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
13
- MERCHANTABLITY OR NON-INFRINGEMENT.
14
-
15
- See the Apache Version 2.0 License for specific language governing permissions
16
- and limitations under the License.
17
- ***************************************************************************** */var Le;function Et(){if(Le)return Ie;Le=1;var e;return(function(t){(function(r){var a=typeof globalThis=="object"?globalThis:typeof Ce=="object"?Ce:typeof self=="object"?self:typeof this=="object"?this:w(),i=u(t);typeof a.Reflect<"u"&&(i=u(a.Reflect,i)),r(i,a),typeof a.Reflect>"u"&&(a.Reflect=t);function u(b,M){return function(_,A){Object.defineProperty(b,_,{configurable:!0,writable:!0,value:A}),M&&M(_,A)}}function f(){try{return Function("return this;")()}catch{}}function E(){try{return(0,eval)("(function() { return this; })()")}catch{}}function w(){return f()||E()}})(function(r,a){var i=Object.prototype.hasOwnProperty,u=typeof Symbol=="function",f=u&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",E=u&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",w=typeof Object.create=="function",b={__proto__:[]}instanceof Array,M=!w&&!b,_={create:w?function(){return Me(Object.create(null))}:b?function(){return Me({__proto__:null})}:function(){return Me({})},has:M?function(n,o){return i.call(n,o)}:function(n,o){return o in n},get:M?function(n,o){return i.call(n,o)?n[o]:void 0}:function(n,o){return n[o]}},A=Object.getPrototypeOf(Function),g=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:yr(),O=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Er(),z=typeof WeakMap=="function"?WeakMap:vr(),U=u?Symbol.for("@reflect-metadata:registry"):void 0,he=dr(),Ue=hr(he);function Bt(n,o,s,c){if(S(s)){if(!Je(n))throw new TypeError;if(!ze(o))throw new TypeError;return ar(n,o)}else{if(!Je(n))throw new TypeError;if(!I(o))throw new TypeError;if(!I(c)&&!S(c)&&!te(c))throw new TypeError;return te(c)&&(c=void 0),s=F(s),or(n,o,s,c)}}r("decorate",Bt);function Xt(n,o){function s(c,v){if(!I(c))throw new TypeError;if(!S(v)&&!fr(v))throw new TypeError;Fe(n,o,c,v)}return s}r("metadata",Xt);function Jt(n,o,s,c){if(!I(s))throw new TypeError;return S(c)||(c=F(c)),Fe(n,o,s,c)}r("defineMetadata",Jt);function zt(n,o,s){if(!I(o))throw new TypeError;return S(s)||(s=F(s)),$e(n,o,s)}r("hasMetadata",zt);function Zt(n,o,s){if(!I(o))throw new TypeError;return S(s)||(s=F(s)),ge(n,o,s)}r("hasOwnMetadata",Zt);function Kt(n,o,s){if(!I(o))throw new TypeError;return S(s)||(s=F(s)),We(n,o,s)}r("getMetadata",Kt);function er(n,o,s){if(!I(o))throw new TypeError;return S(s)||(s=F(s)),Qe(n,o,s)}r("getOwnMetadata",er);function tr(n,o){if(!I(n))throw new TypeError;return S(o)||(o=F(o)),Ve(n,o)}r("getMetadataKeys",tr);function rr(n,o){if(!I(n))throw new TypeError;return S(o)||(o=F(o)),Ye(n,o)}r("getOwnMetadataKeys",rr);function nr(n,o,s){if(!I(o))throw new TypeError;if(S(s)||(s=F(s)),!I(o))throw new TypeError;S(s)||(s=F(s));var c=se(o,s,!1);return S(c)?!1:c.OrdinaryDeleteMetadata(n,o,s)}r("deleteMetadata",nr);function ar(n,o){for(var s=n.length-1;s>=0;--s){var c=n[s],v=c(o);if(!S(v)&&!te(v)){if(!ze(v))throw new TypeError;o=v}}return o}function or(n,o,s,c){for(var v=n.length-1;v>=0;--v){var P=n[v],L=P(o,s,c);if(!S(L)&&!te(L)){if(!I(L))throw new TypeError;c=L}}return c}function $e(n,o,s){var c=ge(n,o,s);if(c)return!0;var v=Oe(o);return te(v)?!1:$e(n,v,s)}function ge(n,o,s){var c=se(o,s,!1);return S(c)?!1:Xe(c.OrdinaryHasOwnMetadata(n,o,s))}function We(n,o,s){var c=ge(n,o,s);if(c)return Qe(n,o,s);var v=Oe(o);if(!te(v))return We(n,v,s)}function Qe(n,o,s){var c=se(o,s,!1);if(!S(c))return c.OrdinaryGetOwnMetadata(n,o,s)}function Fe(n,o,s,c){var v=se(s,c,!0);v.OrdinaryDefineOwnMetadata(n,o,s,c)}function Ve(n,o){var s=Ye(n,o),c=Oe(n);if(c===null)return s;var v=Ve(c,o);if(v.length<=0)return s;if(s.length<=0)return v;for(var P=new O,L=[],m=0,l=s;m<l.length;m++){var h=l[m],p=P.has(h);p||(P.add(h),L.push(h))}for(var y=0,T=v;y<T.length;y++){var h=T[y],p=P.has(h);p||(P.add(h),L.push(h))}return L}function Ye(n,o){var s=se(n,o,!1);return s?s.OrdinaryOwnMetadataKeys(n,o):[]}function Be(n){if(n===null)return 1;switch(typeof n){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return n===null?1:6;default:return 6}}function S(n){return n===void 0}function te(n){return n===null}function sr(n){return typeof n=="symbol"}function I(n){return typeof n=="object"?n!==null:typeof n=="function"}function ir(n,o){switch(Be(n)){case 0:return n;case 1:return n;case 2:return n;case 3:return n;case 4:return n;case 5:return n}var s="string",c=Ze(n,f);if(c!==void 0){var v=c.call(n,s);if(I(v))throw new TypeError;return v}return ur(n)}function ur(n,o){var s,c,v;{var P=n.toString;if(pe(P)){var c=P.call(n);if(!I(c))return c}var s=n.valueOf;if(pe(s)){var c=s.call(n);if(!I(c))return c}}throw new TypeError}function Xe(n){return!!n}function cr(n){return""+n}function F(n){var o=ir(n);return sr(o)?o:cr(o)}function Je(n){return Array.isArray?Array.isArray(n):n instanceof Object?n instanceof Array:Object.prototype.toString.call(n)==="[object Array]"}function pe(n){return typeof n=="function"}function ze(n){return typeof n=="function"}function fr(n){switch(Be(n)){case 3:return!0;case 4:return!0;default:return!1}}function Re(n,o){return n===o||n!==n&&o!==o}function Ze(n,o){var s=n[o];if(s!=null){if(!pe(s))throw new TypeError;return s}}function Ke(n){var o=Ze(n,E);if(!pe(o))throw new TypeError;var s=o.call(n);if(!I(s))throw new TypeError;return s}function et(n){return n.value}function tt(n){var o=n.next();return o.done?!1:o}function rt(n){var o=n.return;o&&o.call(n)}function Oe(n){var o=Object.getPrototypeOf(n);if(typeof n!="function"||n===A||o!==A)return o;var s=n.prototype,c=s&&Object.getPrototypeOf(s);if(c==null||c===Object.prototype)return o;var v=c.constructor;return typeof v!="function"||v===n?o:v}function lr(){var n;!S(U)&&typeof a.Reflect<"u"&&!(U in a.Reflect)&&typeof a.Reflect.defineMetadata=="function"&&(n=pr(a.Reflect));var o,s,c,v=new z,P={registerProvider:L,getProvider:l,setProvider:p};return P;function L(y){if(!Object.isExtensible(P))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case n===y:break;case S(o):o=y;break;case o===y:break;case S(s):s=y;break;case s===y:break;default:c===void 0&&(c=new O),c.add(y);break}}function m(y,T){if(!S(o)){if(o.isProviderFor(y,T))return o;if(!S(s)){if(s.isProviderFor(y,T))return o;if(!S(c))for(var R=Ke(c);;){var k=tt(R);if(!k)return;var W=et(k);if(W.isProviderFor(y,T))return rt(R),W}}}if(!S(n)&&n.isProviderFor(y,T))return n}function l(y,T){var R=v.get(y),k;return S(R)||(k=R.get(T)),S(k)&&(k=m(y,T),S(k)||(S(R)&&(R=new g,v.set(y,R)),R.set(T,k))),k}function h(y){if(S(y))throw new TypeError;return o===y||s===y||!S(c)&&c.has(y)}function p(y,T,R){if(!h(R))throw new Error("Metadata provider not registered.");var k=l(y,T);if(k!==R){if(!S(k))return!1;var W=v.get(y);S(W)&&(W=new g,v.set(y,W)),W.set(T,R)}return!0}}function dr(){var n;return!S(U)&&I(a.Reflect)&&Object.isExtensible(a.Reflect)&&(n=a.Reflect[U]),S(n)&&(n=lr()),!S(U)&&I(a.Reflect)&&Object.isExtensible(a.Reflect)&&Object.defineProperty(a.Reflect,U,{enumerable:!1,configurable:!1,writable:!1,value:n}),n}function hr(n){var o=new z,s={isProviderFor:function(h,p){var y=o.get(h);return S(y)?!1:y.has(p)},OrdinaryDefineOwnMetadata:L,OrdinaryHasOwnMetadata:v,OrdinaryGetOwnMetadata:P,OrdinaryOwnMetadataKeys:m,OrdinaryDeleteMetadata:l};return he.registerProvider(s),s;function c(h,p,y){var T=o.get(h),R=!1;if(S(T)){if(!y)return;T=new g,o.set(h,T),R=!0}var k=T.get(p);if(S(k)){if(!y)return;if(k=new g,T.set(p,k),!n.setProvider(h,p,s))throw T.delete(p),R&&o.delete(h),new Error("Wrong provider for target.")}return k}function v(h,p,y){var T=c(p,y,!1);return S(T)?!1:Xe(T.has(h))}function P(h,p,y){var T=c(p,y,!1);if(!S(T))return T.get(h)}function L(h,p,y,T){var R=c(y,T,!0);R.set(h,p)}function m(h,p){var y=[],T=c(h,p,!1);if(S(T))return y;for(var R=T.keys(),k=Ke(R),W=0;;){var nt=tt(k);if(!nt)return y.length=W,y;var Sr=et(nt);try{y[W]=Sr}catch(mr){try{rt(k)}finally{throw mr}}W++}}function l(h,p,y){var T=c(p,y,!1);if(S(T)||!T.delete(h))return!1;if(T.size===0){var R=o.get(p);S(R)||(R.delete(y),R.size===0&&o.delete(R))}return!0}}function pr(n){var o=n.defineMetadata,s=n.hasOwnMetadata,c=n.getOwnMetadata,v=n.getOwnMetadataKeys,P=n.deleteMetadata,L=new z,m={isProviderFor:function(l,h){var p=L.get(l);return!S(p)&&p.has(h)?!0:v(l,h).length?(S(p)&&(p=new O,L.set(l,p)),p.add(h),!0):!1},OrdinaryDefineOwnMetadata:o,OrdinaryHasOwnMetadata:s,OrdinaryGetOwnMetadata:c,OrdinaryOwnMetadataKeys:v,OrdinaryDeleteMetadata:P};return m}function se(n,o,s){var c=he.getProvider(n,o);if(!S(c))return c;if(s){if(he.setProvider(n,o,Ue))return Ue;throw new Error("Illegal state.")}}function yr(){var n={},o=[],s=(function(){function m(l,h,p){this._index=0,this._keys=l,this._values=h,this._selector=p}return m.prototype["@@iterator"]=function(){return this},m.prototype[E]=function(){return this},m.prototype.next=function(){var l=this._index;if(l>=0&&l<this._keys.length){var h=this._selector(this._keys[l],this._values[l]);return l+1>=this._keys.length?(this._index=-1,this._keys=o,this._values=o):this._index++,{value:h,done:!1}}return{value:void 0,done:!0}},m.prototype.throw=function(l){throw this._index>=0&&(this._index=-1,this._keys=o,this._values=o),l},m.prototype.return=function(l){return this._index>=0&&(this._index=-1,this._keys=o,this._values=o),{value:l,done:!0}},m})(),c=(function(){function m(){this._keys=[],this._values=[],this._cacheKey=n,this._cacheIndex=-2}return Object.defineProperty(m.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),m.prototype.has=function(l){return this._find(l,!1)>=0},m.prototype.get=function(l){var h=this._find(l,!1);return h>=0?this._values[h]:void 0},m.prototype.set=function(l,h){var p=this._find(l,!0);return this._values[p]=h,this},m.prototype.delete=function(l){var h=this._find(l,!1);if(h>=0){for(var p=this._keys.length,y=h+1;y<p;y++)this._keys[y-1]=this._keys[y],this._values[y-1]=this._values[y];return this._keys.length--,this._values.length--,Re(l,this._cacheKey)&&(this._cacheKey=n,this._cacheIndex=-2),!0}return!1},m.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=n,this._cacheIndex=-2},m.prototype.keys=function(){return new s(this._keys,this._values,v)},m.prototype.values=function(){return new s(this._keys,this._values,P)},m.prototype.entries=function(){return new s(this._keys,this._values,L)},m.prototype["@@iterator"]=function(){return this.entries()},m.prototype[E]=function(){return this.entries()},m.prototype._find=function(l,h){if(!Re(this._cacheKey,l)){this._cacheIndex=-1;for(var p=0;p<this._keys.length;p++)if(Re(this._keys[p],l)){this._cacheIndex=p;break}}return this._cacheIndex<0&&h&&(this._cacheIndex=this._keys.length,this._keys.push(l),this._values.push(void 0)),this._cacheIndex},m})();return c;function v(m,l){return m}function P(m,l){return l}function L(m,l){return[m,l]}}function Er(){var n=(function(){function o(){this._map=new g}return Object.defineProperty(o.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),o.prototype.has=function(s){return this._map.has(s)},o.prototype.add=function(s){return this._map.set(s,s),this},o.prototype.delete=function(s){return this._map.delete(s)},o.prototype.clear=function(){this._map.clear()},o.prototype.keys=function(){return this._map.keys()},o.prototype.values=function(){return this._map.keys()},o.prototype.entries=function(){return this._map.entries()},o.prototype["@@iterator"]=function(){return this.keys()},o.prototype[E]=function(){return this.keys()},o})();return n}function vr(){var n=16,o=_.create(),s=c();return(function(){function l(){this._key=c()}return l.prototype.has=function(h){var p=v(h,!1);return p!==void 0?_.has(p,this._key):!1},l.prototype.get=function(h){var p=v(h,!1);return p!==void 0?_.get(p,this._key):void 0},l.prototype.set=function(h,p){var y=v(h,!0);return y[this._key]=p,this},l.prototype.delete=function(h){var p=v(h,!1);return p!==void 0?delete p[this._key]:!1},l.prototype.clear=function(){this._key=c()},l})();function c(){var l;do l="@@WeakMap@@"+m();while(_.has(o,l));return o[l]=!0,l}function v(l,h){if(!i.call(l,s)){if(!h)return;Object.defineProperty(l,s,{value:_.create()})}return l[s]}function P(l,h){for(var p=0;p<h;++p)l[p]=Math.random()*255|0;return l}function L(l){if(typeof Uint8Array=="function"){var h=new Uint8Array(l);return typeof crypto<"u"?crypto.getRandomValues(h):typeof msCrypto<"u"?msCrypto.getRandomValues(h):P(h,l),h}return P(new Array(l),l)}function m(){var l=L(n);l[6]=l[6]&79|64,l[8]=l[8]&191|128;for(var h="",p=0;p<n;++p){var y=l[p];(p===4||p===6||p===8)&&(h+="-"),y<16&&(h+="0"),h+=y.toString(16).toLowerCase()}return h}}function Me(n){return n.__=void 0,delete n.__,n}})})(e||(e={})),Ie}Et();const Ne=Symbol("endpoint:metadata");function ve(e,t,r={}){return function(a,i){const u={method:e,path:t,...r};Reflect.defineMetadata(Ne,u,a,i)}}function q(e="",t={}){return ve(j.HttpMethod.POST,e,t)}var Se=(e=>(e.EXCHANGE="Exchange",e.RESULT="Result",e))(Se||{});const vt="__decorator_target__",St="__decorator_metadata__";let mt=class{constructor(t,r){this.target=t,this.metadata=r}async execute(t){const r=this.metadata.fetcher,a=this.metadata.resolveExchangeInit(t);a.attributes?.set(vt,this.target),a.attributes?.set(St,this.metadata);const i=this.metadata.resolveResultExtractor(),u=this.metadata.resolveEndpointReturnType(),f=await r.exchange(a.request,{resultExtractor:i,attributes:a.attributes});return u===Se.EXCHANGE?f:await f.extractResult()}};const ae=new WeakMap;function Tt(e){if(typeof e!="function")throw new TypeError("Expected a function");if(ae.has(e))return ae.get(e);try{const t=e.toString().trim(),r=_t(t);if(!bt(r)){const i=[];return ae.set(e,i),i}const a=gt(r);return ae.set(e,a),a}catch{const t=[];return ae.set(e,t),t}}function wt(e,t,r,a){if(a)return a;try{const i=e[t];if(i&&typeof i=="function"){const u=Tt(i);if(r<u.length)return u[r]}}catch{}}function bt(e){return e!=null&&e.trim()!==""}function _t(e){if(e.startsWith("(")){const a=je(e,0);return a===-1?"":e.substring(1,a)}const t=e.indexOf("(");if(t===-1)return"";const r=je(e,t);return r===-1?"":e.substring(t+1,r)}function je(e,t){let r=1;for(let a=t+1;a<e.length;a++){const i=e[a];if(i==="(")r++;else if(i===")"&&(r--,r===0))return a}return-1}function gt(e){return e.split(",").map(Rt).filter(Ot).map(Mt)}function Rt(e){return e.trim()}function Ot(e){return e.length>0}function Mt(e){let t=At(e);return t=Pt(t),t.trim()}function At(e){const t=e.indexOf("=");return t!==-1?e.substring(0,t):e}function Pt(e){const t=e.indexOf(":");return t!==-1?e.substring(0,t):e}var J=(e=>(e.PATH="path",e.QUERY="query",e.HEADER="header",e.BODY="body",e.REQUEST="request",e.ATTRIBUTE="attribute",e))(J||{});const me=Symbol("parameter:metadata");function Te(e,t=""){return function(r,a,i){const u=wt(r,a,i,t),f=Reflect.getMetadata(me,r,a)||new Map,E={type:e,name:u,index:i};f.set(i,E),Reflect.defineMetadata(me,f,r,a)}}function H(){return Te("body")}function xe(){return Te("request")}function D(e=""){return Te("attribute",e)}let De=class{constructor(t,r,a,i){this.name=t,this.api=r,this.endpoint=a,this.parameters=i}get fetcher(){return j.getFetcher(this.endpoint.fetcher??this.api.fetcher)}resolvePath(t){const r=this.endpoint.basePath||this.api.basePath||"",a=t||this.endpoint.path||"";return j.combineURLs(r,a)}resolveTimeout(){return this.endpoint.timeout||this.api.timeout}resolveResultExtractor(){return this.endpoint.resultExtractor||this.api.resultExtractor||j.JsonResultExtractor}resolveAttributes(){const t=j.mergeRecordToMap(this.api.attributes);return j.mergeRecordToMap(this.endpoint.attributes,t)}resolveEndpointReturnType(){return this.endpoint.returnType||this.api.returnType||Se.RESULT}resolveExchangeInit(t){const r={},a={},i={...this.api.headers,...this.endpoint.headers};let u,f,E,w={};const b=this.resolveAttributes();t.forEach((O,z)=>{if(O instanceof AbortSignal){f=O;return}if(O instanceof AbortController){E=O;return}const U=this.parameters.get(z);if(U)switch(U.type){case J.PATH:this.processPathParam(U,O,r);break;case J.QUERY:this.processQueryParam(U,O,a);break;case J.HEADER:this.processHeaderParam(U,O,i);break;case J.BODY:u=O;break;case J.REQUEST:w=this.processRequestParam(O);break;case J.ATTRIBUTE:this.processAttributeParam(U,O,b);break}});const M={path:r,query:a},_={method:this.endpoint.method,urlParams:M,headers:i,body:u,timeout:this.resolveTimeout(),signal:f,abortController:E},A=j.mergeRequest(_,w),g=w.path;return A.url=this.resolvePath(g),{request:A,attributes:b}}processHttpParam(t,r,a){if(r==null)return;if(typeof r=="object"){Object.entries(r).forEach(([u,f])=>{a[u]=f});return}const i=t.name||`param${t.index}`;a[i]=r}processPathParam(t,r,a){this.processHttpParam(t,r,a)}processQueryParam(t,r,a){this.processHttpParam(t,r,a)}processHeaderParam(t,r,a){this.processHttpParam(t,r,a)}processRequestParam(t){if(!t)return{};const r=t;return{...r,headers:r.headers||{},urlParams:r.urlParams||{path:{},query:{}}}}processAttributeParam(t,r,a){if(typeof r=="object"||r instanceof Map){j.mergeRecordToMap(r,a);return}t.name&&r!==void 0&&a.set(t.name,r)}};const kt=Symbol("api:metadata");function Ct(e,t,r){const a=e.prototype[t];if(t==="constructor"||typeof a!="function")return;const i=Reflect.getMetadata(Ne,e.prototype,t);if(!i)return;const u=Reflect.getMetadata(me,e.prototype,t)||new Map,f=new De(t,r,i,u);e.prototype[t]=async function(...E){return await It(this,f).execute(E)}}function It(e,t){let r=e.requestExecutors;r||(r=new Map,e.requestExecutors=r);let a=r.get(t.name);if(a)return a;const i=e.apiMetadata,u={...t.api,...i};return a=new mt(e,new De(t.name,u,t.endpoint,t.parameters)),r.set(t.name,a),a}function we(e="",t={}){return function(r){const a={basePath:e,...t};return Reflect.defineMetadata(kt,a,r),Object.getOwnPropertyNames(r.prototype).forEach(i=>{Ct(r,i,a)}),r}}let Lt=class extends Error{constructor(){super("Implementation will be generated automatically."),this.name="AutoGenerated"}};const G=(...e)=>new Lt;var Nt=Object.defineProperty,jt=Object.getOwnPropertyDescriptor,be=(e,t,r,a)=>{for(var i=a>1?void 0:a?jt(t,r):t,u=e.length-1,f;u>=0;u--)(f=e[u])&&(i=(a?f(t,r,i):f(i))||i);return a&&i&&Nt(t,r,i),i},fe=(e,t)=>(r,a)=>t(r,a,e);let le=class{constructor(e){this.apiMetadata=e}send(e,t){throw G(e,t)}sendAndWaitStream(e,t){throw G(e,t)}};be([ve(),fe(0,xe()),fe(1,D())],le.prototype,"send",1),be([ve(void 0,void 0,{headers:{Accept:j.ContentTypeValues.TEXT_EVENT_STREAM},resultExtractor:ce}),fe(0,xe()),fe(1,D())],le.prototype,"sendAndWaitStream",1),le=be([we()],le);var Ge=(e=>(e.AND="AND",e.OR="OR",e.NOR="NOR",e.ID="ID",e.IDS="IDS",e.AGGREGATE_ID="AGGREGATE_ID",e.AGGREGATE_IDS="AGGREGATE_IDS",e.TENANT_ID="TENANT_ID",e.OWNER_ID="OWNER_ID",e.DELETED="DELETED",e.ALL="ALL",e.EQ="EQ",e.NE="NE",e.GT="GT",e.LT="LT",e.GTE="GTE",e.LTE="LTE",e.CONTAINS="CONTAINS",e.IN="IN",e.NOT_IN="NOT_IN",e.BETWEEN="BETWEEN",e.ALL_IN="ALL_IN",e.STARTS_WITH="STARTS_WITH",e.ENDS_WITH="ENDS_WITH",e.ELEM_MATCH="ELEM_MATCH",e.NULL="NULL",e.NOT_NULL="NOT_NULL",e.TRUE="TRUE",e.FALSE="FALSE",e.EXISTS="EXISTS",e.TODAY="TODAY",e.BEFORE_TODAY="BEFORE_TODAY",e.TOMORROW="TOMORROW",e.THIS_WEEK="THIS_WEEK",e.NEXT_WEEK="NEXT_WEEK",e.LAST_WEEK="LAST_WEEK",e.THIS_MONTH="THIS_MONTH",e.LAST_MONTH="LAST_MONTH",e.RECENT_DAYS="RECENT_DAYS",e.EARLIER_DAYS="EARLIER_DAYS",e.RAW="RAW",e))(Ge||{});function _e(){return{operator:Ge.ALL}}const qe={index:1,size:10};function xt({condition:e=_e(),projection:t,sort:r}={}){return{condition:e,projection:t,sort:r}}function Dt({condition:e=_e(),projection:t,sort:r,limit:a=qe.size}={}){return{condition:e,projection:t,sort:r,limit:a}}function Gt({condition:e=_e(),projection:t,sort:r,pagination:a=qe}={}){return{condition:e,projection:t,sort:r,pagination:a}}const B=class{};B.EVENT_STREAM_RESOURCE_NAME="event",B.COUNT=`${B.EVENT_STREAM_RESOURCE_NAME}/count`,B.LIST=`${B.EVENT_STREAM_RESOURCE_NAME}/list`,B.PAGED=`${B.EVENT_STREAM_RESOURCE_NAME}/paged`;let de=B;var qt=Object.defineProperty,Ht=Object.getOwnPropertyDescriptor,oe=(e,t,r,a)=>{for(var i=a>1?void 0:a?Ht(t,r):t,u=e.length-1,f;u>=0;u--)(f=e[u])&&(i=(a?f(t,r,i):f(i))||i);return a&&i&&qt(t,r,i),i},X=(e,t)=>(r,a)=>t(r,a,e);let ee=class{constructor(e){this.apiMetadata=e}count(e,t){throw G(e,t)}list(e,t){throw G(e,t)}listStream(e,t){throw G(e,t)}paged(e,t){throw G(e,t)}};oe([q(de.COUNT),X(0,H()),X(1,D())],ee.prototype,"count",1),oe([q(de.LIST),X(0,H()),X(1,D())],ee.prototype,"list",1),oe([q(de.LIST,{headers:{Accept:j.ContentTypeValues.TEXT_EVENT_STREAM},resultExtractor:ce}),X(0,H()),X(1,D())],ee.prototype,"listStream",1),oe([q(de.PAGED),X(0,H()),X(1,D())],ee.prototype,"paged",1),ee=oe([we()],ee);const x=class{};x.SNAPSHOT_RESOURCE_NAME="snapshot",x.COUNT=`${x.SNAPSHOT_RESOURCE_NAME}/count`,x.LIST=`${x.SNAPSHOT_RESOURCE_NAME}/list`,x.LIST_STATE=`${x.LIST}/state`,x.PAGED=`${x.SNAPSHOT_RESOURCE_NAME}/paged`,x.PAGED_STATE=`${x.PAGED}/state`,x.SINGLE=`${x.SNAPSHOT_RESOURCE_NAME}/single`,x.SINGLE_STATE=`${x.SINGLE}/state`;let V=x;var Ut=Object.defineProperty,$t=Object.getOwnPropertyDescriptor,Q=(e,t,r,a)=>{for(var i=a>1?void 0:a?$t(t,r):t,u=e.length-1,f;u>=0;u--)(f=e[u])&&(i=(a?f(t,r,i):f(i))||i);return a&&i&&Ut(t,r,i),i},N=(e,t)=>(r,a)=>t(r,a,e);let $=class{constructor(e){this.apiMetadata=e}count(e,t){throw G(e,t)}list(e,t){throw G(e,t)}listStream(e,t){throw G(e,t)}listState(e,t){throw G(e,t)}listStateStream(e,t){throw G(e,t)}paged(e,t){throw G(e,t)}pagedState(e,t){throw G(e,t)}single(e,t){throw G(e,t)}singleState(e,t){throw G(e,t)}};Q([q(V.COUNT),N(0,H()),N(1,D())],$.prototype,"count",1),Q([q(V.LIST),N(0,H()),N(1,D())],$.prototype,"list",1),Q([q(V.LIST,{headers:{Accept:j.ContentTypeValues.TEXT_EVENT_STREAM},resultExtractor:ce}),N(0,H()),N(1,D())],$.prototype,"listStream",1),Q([q(V.LIST_STATE),N(0,H()),N(1,D())],$.prototype,"listState",1),Q([q(V.LIST_STATE,{headers:{Accept:j.ContentTypeValues.TEXT_EVENT_STREAM},resultExtractor:ce}),N(0,H()),N(1,D())],$.prototype,"listStateStream",1),Q([q(V.PAGED),N(0,H()),N(1,D())],$.prototype,"paged",1),Q([q(V.PAGED_STATE),N(0,H()),N(1,D())],$.prototype,"pagedState",1),Q([q(V.SINGLE),N(0,H()),N(1,D())],$.prototype,"single",1),Q([q(V.SINGLE_STATE),N(0,H()),N(1,D())],$.prototype,"singleState",1),$=Q([we()],$);function Wt(e){const{initialQuery:t}=e,r=Z(e),[a,i]=d.useState(t.condition),[u,f]=d.useState(t.pagination),[E,w]=d.useState(t.projection),[b,M]=d.useState(t.sort),_=Y(e),A=d.useCallback(async()=>{const z=Gt({condition:a,pagination:u,projection:E,sort:b});return _.current.query(z,_.current.attributes)},[a,E,u,b,_]),g=d.useCallback(()=>r.execute(A),[r,A]),{autoExecute:O}=e;return d.useEffect(()=>{O&&g()},[O,g]),d.useMemo(()=>({...r,execute:g,setCondition:i,setProjection:w,setPagination:f,setSort:M}),[r,g,i,w,f,M])}function Qt(e){const{initialQuery:t}=e,r=Z(e),[a,i]=d.useState(t.condition),[u,f]=d.useState(t.projection),[E,w]=d.useState(t.sort),b=Y(e),M=d.useCallback(async()=>{const g=xt({condition:a,projection:u,sort:E});return b.current.query(g,b.current.attributes)},[a,u,E,b]),_=d.useCallback(()=>r.execute(M),[r,M]),{autoExecute:A}=e;return d.useEffect(()=>{A&&_()},[A,_]),d.useMemo(()=>({...r,execute:_,setCondition:i,setProjection:f,setSort:w}),[r,_,i,f,w])}function Ft(e){const{initialCondition:t}=e,r=Z(e),[a,i]=d.useState(t),u=Y(e),f=d.useCallback(async()=>u.current.count(a,u.current.attributes),[a,u]),E=d.useCallback(()=>r.execute(f),[r,f]),{autoExecute:w}=e;return d.useEffect(()=>{w&&E()},[w,E]),d.useMemo(()=>({...r,execute:E,setCondition:i}),[r,E,i])}function He(e){const{initialQuery:t}=e,[r,a]=d.useState(t.condition),[i,u]=d.useState(t.projection),[f,E]=d.useState(t.sort),[w,b]=d.useState(t.limit),M=d.useCallback(()=>Dt({condition:r,projection:i,sort:f,limit:w}),[r,i,f,w]);return d.useMemo(()=>({condition:r,projection:i,sort:f,limit:w,setCondition:a,setProjection:u,setSort:E,setLimit:b,buildQuery:M}),[r,i,f,w,a,u,E,b,M])}function Vt(e){const t=Z(e),r=He({initialQuery:e.initialQuery}),a=Y(e),i=d.useCallback(async()=>{const E=r.buildQuery();return a.current.list(E,a.current.attributes)},[r,a]),u=d.useCallback(()=>t.execute(i),[t,i]),{autoExecute:f}=e;return d.useEffect(()=>{f&&u()},[f,u]),d.useMemo(()=>({...t,execute:u,setCondition:r.setCondition,setProjection:r.setProjection,setSort:r.setSort,setLimit:r.setLimit}),[t,u,r.setCondition,r.setProjection,r.setSort,r.setLimit])}function Yt(e){const t=Z(e),r=He({initialQuery:e.initialQuery}),a=Y(e),i=d.useCallback(async()=>{const E=r.buildQuery();return a.current.listStream(E,a.current.attributes)},[r,a]),u=d.useCallback(()=>t.execute(i),[t,i]),{autoExecute:f}=e;return d.useEffect(()=>{f&&u()},[f,u]),d.useMemo(()=>({...t,execute:u,setCondition:r.setCondition,setProjection:r.setProjection,setSort:r.setSort,setLimit:r.setLimit}),[t,u,r.setCondition,r.setProjection,r.setSort,r.setLimit])}C.PromiseStatus=Ae,C.useCountQuery=Ft,C.useExecutePromise=Z,C.useFetcher=ot,C.useKeyStorage=at,C.useLatest=Y,C.useListQuery=Vt,C.useListStreamQuery=Yt,C.useMounted=ie,C.usePagedQuery=Wt,C.usePromiseState=ye,C.useRequestId=Ee,C.useSingleQuery=Qt,Object.defineProperty(C,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(s,t){typeof exports=="object"&&typeof module<"u"?t(exports,require("react"),require("@ahoo-wang/fetcher")):typeof define=="function"&&define.amd?define(["exports","react","@ahoo-wang/fetcher"],t):(s=typeof globalThis<"u"?globalThis:s||self,t(s.FetcherReact={},s.React,s.Fetcher))})(this,(function(s,t,R){"use strict";function S(){const e=t.useRef(!1),c=t.useCallback(()=>e.current,[]);return t.useEffect(()=>(e.current=!0,()=>{e.current=!1}),[]),c}function h(e){const c=t.useRef(e);return c.current=e,c}var w=(e=>(e.IDLE="idle",e.LOADING="loading",e.SUCCESS="success",e.ERROR="error",e))(w||{});function k(e){const[c,r]=t.useState(e?.initialStatus??"idle"),[o,i]=t.useState(void 0),[n,u]=t.useState(void 0),a=S(),d=h(e),l=t.useCallback(()=>{a()&&(r("loading"),u(void 0))},[a]),b=t.useCallback(async f=>{if(a()){i(f),r("success"),u(void 0);try{await d.current?.onSuccess?.(f)}catch(E){console.warn("PromiseState onSuccess callback error:",E)}}},[a,d]),y=t.useCallback(async f=>{if(a()){u(f),r("error"),i(void 0);try{await d.current?.onError?.(f)}catch(E){console.warn("PromiseState onError callback error:",E)}}},[a,d]),C=t.useCallback(()=>{a()&&(r("idle"),u(void 0),i(void 0))},[a]);return t.useMemo(()=>({status:c,loading:c==="loading",result:o,error:n,setLoading:l,setSuccess:b,setError:y,setIdle:C}),[c,o,n,l,b,y,C])}function L(){const e=t.useRef(0),c=t.useCallback(()=>++e.current,[]),r=t.useCallback(()=>e.current,[]),o=t.useCallback(u=>u===e.current,[]),i=t.useCallback(()=>{e.current++},[]),n=t.useCallback(()=>{e.current=0},[]);return t.useMemo(()=>({generate:c,current:r,isLatest:o,invalidate:i,reset:n}),[c,r,o,i,n])}function Q(e){const{loading:c,result:r,error:o,status:i,setLoading:n,setSuccess:u,setError:a,setIdle:d}=k(e),l=S(),b=L(),y=e?.propagateError,C=t.useCallback(async E=>{if(!l())throw new Error("Component is unmounted");const v=b.generate();n();try{const I=await(typeof E=="function"?E():E);return l()&&b.isLatest(v)&&await u(I),I}catch(m){if(l()&&b.isLatest(v)&&await a(m),y)throw m;return m}},[n,u,a,l,b,y]),f=t.useCallback(()=>{l()&&d()},[d,l]);return t.useMemo(()=>({loading:c,result:r,error:o,execute:C,reset:f,status:i}),[c,r,o,C,f,i])}function M(e){const c=t.useCallback(n=>e.addListener(n),[e]),r=t.useCallback(()=>e.get(),[e]),o=t.useSyncExternalStore(c,r,r),i=t.useCallback(n=>e.set(n),[e]);return[o,i]}function F(e){const{fetcher:c=R.fetcherRegistrar.default}=e||{},r=k(e),[o,i]=t.useState(void 0),n=S(),u=t.useRef(),a=L(),d=h(e),l=R.getFetcher(c),b=t.useCallback(async y=>{u.current&&u.current.abort(),u.current=y.abortController??new AbortController,y.abortController=u.current;const C=a.generate();r.setLoading();try{const f=await l.exchange(y,d.current);n()&&a.isLatest(C)&&i(f);const E=await f.extractResult();n()&&a.isLatest(C)&&await r.setSuccess(E)}catch(f){if(f instanceof Error&&f.name==="AbortError"){n()&&r.setIdle();return}n()&&a.isLatest(C)&&await r.setError(f)}finally{u.current===y.abortController&&(u.current=void 0)}},[l,n,d,r,a]);return t.useEffect(()=>()=>{u.current?.abort(),u.current=void 0},[]),t.useMemo(()=>({...r,exchange:o,execute:b}),[r,o,b])}function g(e){const{initialQuery:c}=e,r=Q(e),o=h(c),i=h(e),n=t.useCallback(async()=>i.current.execute(o.current,i.current.attributes),[o,i]),u=t.useCallback(()=>o.current,[o]),a=t.useCallback(y=>{o.current=y},[o]),{execute:d}=r,l=t.useCallback(()=>d(n),[d,n]),{autoExecute:b}=e;return t.useEffect(()=>{b&&l()},[b,l]),t.useMemo(()=>({...r,execute:l,getQuery:u,setQuery:a}),[r,l,u,a])}function q(e){return g(e)}function P(e){return g(e)}function O(e){return g(e)}function x(e){return g(e)}function A(e){return g(e)}s.PromiseStatus=w,s.useCountQuery=O,s.useExecutePromise=Q,s.useFetcher=F,s.useKeyStorage=M,s.useLatest=h,s.useListQuery=x,s.useListStreamQuery=A,s.useMounted=S,s.usePagedQuery=q,s.usePromiseState=k,s.useQuery=g,s.useRequestId=L,s.useSingleQuery=P,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})}));
18
2
  //# sourceMappingURL=index.umd.js.map