vue-use-async 1.13.9 → 1.13.10

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.js CHANGED
@@ -1 +1 @@
1
- import{computed as e,isRef as t,onBeforeUnmount as r,ref as s,unref as n,watch as o}from"vue";const i={log(e){},warn(e){},info(e){},error(e){},debug(e){}},a=new Map;async function u(e){const{id:t,xhr:r}=e||{};let s,n,o="string"!=typeof e.duration&&e.duration||200;if("max"===e.duration&&(o=36e5),!a.get(t)&&r?(s=r(),a.set(t,s),s.then(e=>(i.log(`[Log] add cache: ${t}`),clearTimeout(n),n=window.setTimeout(()=>{a.delete(t),i.log(`[Log] delete cache: ${t}`),clearTimeout(n)},o),e),()=>{a.delete(t),i.log(`[Log] delete cache: ${t}`)})):t&&(s=a.get(t)),s)return s;throw Error("Call to undefined cache")}function l(){return a.size}function h(){return Array.from(a.keys())}function c(e){e?a.delete(e):a.forEach((e,t,r)=>{r.delete(t)}),i.log("[Log] cache cleared")}function d(e,t,r){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var r=t.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class v{constructor(){d(this,"resolve",void 0),d(this,"reject",void 0),d(this,"promise",void 0),d(this,"done",!1),this.resolve=()=>{throw Error("Can t resolve")},this.reject=()=>{throw Error("Can t reject")},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t}),this.promise.finally(()=>{this.done=!0})}}const p="10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+e/4).toString(16));function f(e,t,r){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var r=t.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class m{constructor(e){f(this,"value",void 0),f(this,"uuid",void 0),this.uuid=p,this.value=e}}function y(t,r,s=e=>e){const n=void 0===t.value?r:t.value;return t.value=void 0===n?n:new m(s?.(n)),o(()=>t.value,e=>{void 0===e||e instanceof m||(t.value=new m(s?.(e)))}),e({get:()=>{let e;return e=t.value instanceof m?t.value.value:t.value,void 0===e?r:e},set:e=>{t.value=new m(e)}})}const g=(t,...[r,i])=>{const a=i??s(!0),u=s(),l=s(),h=s(null),c=[],d=[],v=[],f=s(null),y=e(()=>"function"==typeof r?r():n(r)),g=s(),b=e(()=>"function"==typeof a?a():n(a)),_=e=>{if(!b.value)return null;u.value&&f.value?.abortXhr?.(),d.forEach(e=>e(y.value)),u.value=!0,h.value=null;const r=t,s=t;return f.value=Array.isArray(e)?s(...e):r(e),f.value.catch(e=>{h.value=e||null,c.forEach(e=>e(h.value,y.value))}),f.value.then(e=>{l.value=e,v.forEach(t=>t(e,y.value))}),f.value.finally(()=>{u.value=!1}),f.value},E=e(()=>f.value);return o(()=>b.value,e=>{!u.value&&e&&_(y.value)},{immediate:!1}),o(()=>h.value,e=>{if(e)throw e}),o(()=>y.value,e=>{const t=JSON.stringify(e);!u.value&&(void 0===e&&void 0===g.value||b.value&&t!==JSON.stringify(g.value))&&_(e),g.value=void 0===t?void 0:JSON.parse(t)},{immediate:b.value,deep:!0}),{isPending:u,data:e({get:()=>l.value,set:e=>{e instanceof m&&e.uuid===p||console.warn('"useAsync" update a readonly field is not allowed'),l.value=e}}),error:h,reload:()=>_(y.value),onError:e=>{c.push(e)},onStart:e=>{d.push(e)},onEnd:e=>{v.push(e)},promise:E}};function b(t){const r=s(),n=s(),o=s(),i=[],a=[],u=s(null);return{mutate:(e,...s)=>{r.value=!0,o.value=null;const l=t;return u.value=l(e,...s),u.value.catch(t=>{o.value=t||null,i.forEach(t=>t(o.value,s.length?[e,...s]:e)),o.value=t}),u.value.then(t=>{n.value=t,a.forEach(t=>t(n.value,s.length?[e,...s]:e))}),u.value.finally(()=>{r.value=!1}),u.value},onError:e=>i.push(e),onEnd:e=>a.push(e),isPending:r,error:o,data:n,promise:e(()=>u.value)}}function _(){return function(e){return b(e)}}function E(e,t,r){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var r=t.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class R{static parseResult(e){let t=e.response;try{const r=e.getResponseHeader("Content-Type");r?.toLowerCase().includes("json")&&(t=JSON.parse(e.response))}catch(r){t=e.response}return t}static extractQueryParams(e){let t=e;const r={},s=t.search(/#/);s>-1&&(t=t.substring(0,s));const n=t.indexOf("?"),o=(!0).toString(),i=(!1).toString();return n>-1&&t.split("?")[1].split("&").reduce((e,t)=>{const r=e,[s,n=""]=t.split("="),[,a]=/^(?:"?([^"]+)"?)$/.exec(n)||[];if(a===o||a===i)return r[s]=a===o,r;const u=Number(a);return r[s]=""===a||Number.isNaN(u)?a:u,r},r),r}static onBeforeSend(e){R.onBeforeSendList.push(e)}constructor(e,t){E(this,"onError",()=>{}),E(this,"onStart",()=>{}),E(this,"onAbort",()=>{}),E(this,"onProgress",()=>{}),E(this,"onEnd",()=>{}),E(this,"token",null),E(this,"url",""),E(this,"params",{}),E(this,"sendAs","json"),E(this,"timeout",1e4),E(this,"port",80),E(this,"responseType","text"),E(this,"isPending",!1),E(this,"_eventsReady",void 0),E(this,"_oXHR",void 0),E(this,"_onEnd",()=>{}),E(this,"_onError",()=>{}),E(this,"_deferred",void 0),E(this,"_isXhrResolved",void 0),E(this,"_isXhrRejected",void 0),E(this,"_eventReady",void 0),this._eventsReady=!1,this._constructor(e||{},t)}static new(e){return new R(e)}_getUrl(e={}){const t=R.onBeforeSendList.reduce((e,t)=>t(e||{}),e);return R.stringifyUrl(this.url,t)}removeEvents(){const e=()=>{this._oXHR.removeEventListener("load",this._onEnd,!1),this._oXHR.removeEventListener("error",this._onError,!1),this._oXHR.removeEventListener("timeout",this._onError,!1),this._oXHR.removeEventListener("loadstart",this.onStart,!1),this._oXHR.removeEventListener("abort",this.onAbort,!1),this._oXHR.upload.removeEventListener("progress",this.onProgress,!1),this._oXHR.removeEventListener("progress",this.onProgress,!1)};this._deferred.promise.then(e,e)}post(e){this._constructor(e);const{url:t,params:r}=R.injectParamsInUrl(this.url,this.params);return this.url=t,this.params=r,this._oXHR.open("POST",this._getUrl(),!0),this._send(),this._deferred.promise}put(e){this._constructor(e);const{url:t,params:r}=R.injectParamsInUrl(this.url,this.params);return this.url=t,this.params=r,this._oXHR.open("PUT",this._getUrl(),!0),this._send(),this._deferred.promise}get(e){this._constructor(e||{});const{url:t,params:r}=R.injectParamsInUrl(this.url,this.params);this.url=t,this.params=r,this._oXHR.open("GET",this._getUrl("multipart"===this.sendAs?{}:this.params),!0),this._send();const s=this._deferred.promise;return s.abortXhr=this.abort.bind(this),s}delete(e){this._constructor(e);const{url:t,params:r}=R.injectParamsInUrl(this.url,this.params);return this.url=t,this.params=r,this._oXHR.open("DELETE",this._getUrl(this.params),!0),this._send(),this._deferred.promise}abort(){return this._isXhrResolved&&!this._isXhrRejected||(this._oXHR.abort(null,this),this._isXhrRejected=!0,this._deferred.reject({message:`Xhr aborted: ${this.url}`,name:"HTTP-ABORTED"})),this._deferred.promise}static stringifyUrl(e,t={}){let r=e,s=t;({url:r,params:s}=R.injectParamsInUrl(r,s));let n=r.includes("?")?"&":"?",o="";return s&&!Array.isArray(s)&&"object"==typeof s?Object.getOwnPropertyNames(s).filter(e=>void 0!==s[e]).forEach(e=>{o+=`${n}${e}=${encodeURIComponent(JSON.stringify(s[e]))}`,n="&"}):s&&(o=n+encodeURIComponent(JSON.stringify(s))),r=r.replace(/\/:[^/]*/gi,""),r+o}static getFormData(e){const t=new FormData;let r;return Object.keys(e).forEach(s=>{if(e[s]instanceof FileList)for(let r=0;r<e[s].length;r+=1)t.append(s,e[s][r]);else e[s]instanceof File?t.append(s,e[s]):(r=e[s],"object"!=typeof r&&!Array.isArray(r)||null===r||(r=JSON.stringify(r)),t.append(s,r))}),t}resolve(e){return this._deferred.resolve(e),this._deferred.promise}reject(e){return this._deferred.reject(e),this._deferred.promise}static _stringifyForPathParam(e,t,r){let s=r[t];switch(typeof r[t]){case"boolean":case"string":case"bigint":case"number":s=String(s);break;default:s=null===s?"null":encodeURIComponent(JSON.stringify(s))}return e.replace(`:${t}`,s)}static injectParamsInUrl(e,t={},r="GET"){if(Array.isArray(t)||0===Object.keys(t).length)return{url:e,params:t};let s=t,n=e;if("GET"===r){n=decodeURIComponent(e);const r=R.extractQueryParams(n),o=n.search(/\?|#/);o>-1&&(n=n.substring(0,o)),s=Object.getOwnPropertyNames(t).reduce((e,r)=>({...e,[r]:t[r]}),{...r}),Object.keys(s).forEach(e=>{void 0!==r[e]&&(r[e]=s[e],delete s[e])});const i=Object.keys(r);if(i.length){let e="?";i.forEach(t=>{if(!0===r[t]||!1===r[t])n+=`${e}${t}=${r[t]}`;else if(null===r[t])n+=`${e}${t}=${r[t]}`;else{const s=Number(r[t]),o=Number.isNaN(s)?encodeURIComponent(`"${r[t]}"`):s;n+=`${e}${t}=${o}`}e="&"})}}return(n.match(/:[a-z0-9]+/gi)||[]).forEach(e=>{let t=e;t=t.substring(1),void 0!==s[t]&&(n=R._stringifyForPathParam(n,t,s),delete s[t])}),{url:n,params:s}}_setEvents(e){this._eventsReady||(this._eventReady=!0,e.addEventListener("load",this._onEnd,!1),e.addEventListener("error",this._onError,!1),e.addEventListener("timeout",this._onError,!1),e.addEventListener("loadstart",this.onStart,!1),e.addEventListener("abort",this.onAbort,!1),e.upload.addEventListener("progress",this.onProgress,!1),e.addEventListener("progress",this.onProgress,!1))}_send(){let e;this.isPending=!0,"multipart"===this.sendAs?e=R.getFormData(this.params):"json"===this.sendAs&&(this._oXHR.setRequestHeader("content-type","application/json; charset=utf-8"),e=JSON.stringify(this.params)),this.token&&this._oXHR.setRequestHeader("Authorization",`Bearer ${this.token}`),this._oXHR.send(e,this)}_constructor(e,t){e&&"object"==typeof e?(this.sendAs=e.sendAs||this.sendAs,this.url=e.url||this.url,this.port=e.port||this.port,this.params=e.params||this.params,this.timeout=e.timeout||this.timeout,this.responseType=e.responseType||this.responseType,this.onProgress=(e.onProgress||this.onProgress).bind(this),this.onStart=(e.onStart||this.onStart).bind(this),this.onAbort=(e.onAbort||this.onAbort).bind(this),this.onEnd=(e.onEnd||this.onEnd).bind(this),this.onError=(e.onError||this.onError).bind(this),this.token=e.token||this.token):e&&"string"==typeof e&&(this.url=e,this.params=t||this.params),80!==this.port&&(this.url=`${window.location.protocol}//${window.location.hostname}:${this.port}${this.url}`),this._deferred=new v,this._deferred.promise.finally(()=>{this.isPending=!1}),this._oXHR=new XMLHttpRequest,this._oXHR.timeout=this.timeout,this._oXHR.responseType=this.responseType,this._isXhrResolved=!1,this._isXhrRejected=!1,this._onError=e=>{this.onError(e),this.removeEvents(),this._deferred.reject(e)},this._onEnd=async e=>{const t=R.parseResult(this._oXHR);if(this._oXHR.status>=400){let e=await(this._oXHR.response.text?.())||this._oXHR.response;try{e=JSON.parse(e)}catch(e){}return this._isXhrRejected=!0,this._onError(e),this._deferred.reject(e)}return this.onEnd(t,e),this._isXhrResolved=!0,this.removeEvents(),this.resolve(t)},this._setEvents(this._oXHR)}}E(R,"onBeforeSendList",[]);const w=()=>{},j=e=>n(e);function P(i){const{onError:a,onStart:l,onEnd:h,context:c,legacy:d,token:v=null}=i||{onError:()=>{},onStart:()=>{},onEnd:()=>{},context:null,legacy:!1,token:null},f=s([]),y=[],b=(t,r,s)=>{let o=s;const i=e(()=>{const e={},t=n(r||{});return o||(o=t.params||{}),e.params=n(o),v&&(e.token=j(v)),e.url=n(t.url),e}),a=new R,u=n(i.value.params)||{};let l;switch(t){case"post":default:l=a.post.bind(a);break;case"put":l=a.put.bind(a);break;case"delete":l=a.delete.bind(a)}return{...g(async()=>l({...i.value,params:u})),xhr:a}};return d||r(()=>{f.value.forEach(e=>{e.isPending&&e.abort()}),y.forEach(e=>e())}),{get:function(r,i,d){let g=i;const b=new R,_=(a||w).bind(c),E=(l||w).bind(c),P=(h||w).bind(c),X=[_],S=[E],H=[P],A=s(null);f.value.push(b);const L=s(),O=s();let T="",$=0;const U=e(()=>{const e={},s=n(r);let o;"string"==typeof s?o=s:(o=n(s.url),g||(g=s.params||{}),$=s.cacheDuration,void 0!==s.enabled&&(e.enabled=s.enabled),void 0===e.enabled&&(e.enabled=d),e.params=n(g),e.cacheDuration=$),v&&(e.token=j(v));let i=n(e.params||g||{});return"function"==typeof i&&(i=i()),e.params={...i,...t(g)?g.value||{}:g},T="function"==typeof o?o(e.params):n(o),e.url=T,e}),N=()=>{const e=void 0!==U.value.enabled?U.value.enabled:d;return void 0===e||(t(e)?n(e):"function"==typeof e?e():!0===e)},k=s(),x=()=>{if(!N())return;L.value&&b.abort();const e="object"==typeof U.value.params?U.value.params:{};S.forEach(t=>t(e,b)),L.value=!0,A.value=null;const t=decodeURIComponent(R.stringifyUrl(String(T),e));k.value=u({id:t,xhr:b.get.bind(b,U.value),duration:$}),k.value.catch(e=>{X.forEach(t=>t(e,b)),A.value=e}),k.value.then(e=>{O.value=e}),k.value.finally(()=>{(()=>{const e=f.value.indexOf(b);e>-1&&f.value.splice(e,1)})(),L.value=!1,H.forEach(t=>t(O.value,e,b))})};return y.push(o(()=>U.value,x,{immediate:N(),deep:!0})),y.push(o(()=>A.value,e=>{if(e)throw e})),{isPending:e(()=>L.value),data:e({get:()=>O.value,set:e=>{e instanceof m&&e.uuid===p||console.warn('"useXhr" update a readonly field is not allowed'),O.value=e}}),onError:e=>X.push(e),onStart:e=>S.push(e),onEnd:e=>H.push(e),error:A,abort:()=>k.value?.abortXhr(),promise:e(async()=>k.value||new Promise(()=>{})),reload:x,xhr:b}},post:(e,t)=>b("post",e,t),put:(e,t)=>b("put",e,t),delete:(e,t)=>b("delete",e,t)}}function X(t,n=400){const i=s(!1);let a,u=0;return o(()=>t.value,e=>{if(e&&(u=Date.now(),i.value=e),!1===e&&u>0){const t=Date.now()-u;clearTimeout(a),t>n?i.value=e:a=setTimeout(()=>{i.value=e},n-t)}},{immediate:!0}),r(()=>{clearTimeout(a)}),e(()=>i.value)}export{v as Deferred,R as Xhr,u as cache,h as cacheIds,l as cacheSize,c as clearCache,g as useAsync,b as useMutation,_ as useMutationWithError,y as useResult,X as useSpinner,P as useXhr};
1
+ import{computed as e,isRef as t,onBeforeUnmount as r,ref as s,unref as n,watch as o}from"vue";const i={log(e){},warn(e){},info(e){},error(e){},debug(e){}},a=new Map;async function u(e){const{id:t,xhr:r}=e||{};let s,n,o="string"!=typeof e.duration&&e.duration||200;if("max"===e.duration&&(o=36e5),!a.get(t)&&r?(s=r(),a.set(t,s),s.then(e=>(i.log(`[Log] add cache: ${t}`),clearTimeout(n),n=window.setTimeout(()=>{a.delete(t),i.log(`[Log] delete cache: ${t}`),clearTimeout(n)},o),e),()=>{a.delete(t),i.log(`[Log] delete cache: ${t}`)})):t&&(s=a.get(t)),s)return s;throw Error("Call to undefined cache")}function l(){return a.size}function h(){return Array.from(a.keys())}function c(e){e?a.delete(e):a.forEach((e,t,r)=>{r.delete(t)}),i.log("[Log] cache cleared")}function d(e,t,r){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var r=t.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class v{constructor(){d(this,"resolve",void 0),d(this,"reject",void 0),d(this,"promise",void 0),d(this,"done",!1),this.resolve=()=>{throw Error("Can t resolve")},this.reject=()=>{throw Error("Can t reject")},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t}),this.promise.finally(()=>{this.done=!0})}}const p="10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(+e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+e/4).toString(16));function f(e,t,r){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var r=t.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class m{constructor(e){f(this,"value",void 0),f(this,"uuid",void 0),this.uuid=p,this.value=e}}function y(t,r,s=e=>e){const n=void 0===t.value?r:t.value;return t.value=void 0===n?n:new m(s?.(n)),o(()=>t.value,e=>{void 0===e||e instanceof m||(t.value=new m(s?.(e)))}),e({get:()=>{let e;return e=t.value instanceof m?t.value.value:t.value,void 0===e?r:e},set:e=>{t.value=new m(e)}})}const g=(t,...[r,i])=>{const a=i??s(!0),u=s(),l=s(),h=s(null),c=[],d=[],v=[],f=s(null),y=e(()=>"function"==typeof r?r():n(r)),g=s(),b=e(()=>"function"==typeof a?a():n(a)),_=e=>{if(!b.value)return null;u.value&&f.value?.abortXhr?.(),d.forEach(e=>e(y.value)),u.value=!0,h.value=null;const r=t;return f.value=Array.isArray(e)?r(...e):r(e),f.value.catch(e=>{h.value=e||null,c.forEach(e=>e(h.value,y.value))}),f.value.then(e=>{l.value=e,v.forEach(t=>t(e,y.value))}),f.value.finally(()=>{u.value=!1}),f.value},E=e(()=>f.value);return o(()=>b.value,e=>{!u.value&&e&&_(y.value)},{immediate:!1}),o(()=>h.value,e=>{if(e)throw e}),o(()=>y.value,e=>{const t=JSON.stringify(e);!u.value&&(void 0===e&&void 0===g.value||b.value&&t!==JSON.stringify(g.value))&&_(e),g.value=void 0===t?void 0:JSON.parse(t)},{immediate:b.value,deep:!0}),{isPending:u,data:e({get:()=>l.value,set:e=>{e instanceof m&&e.uuid===p||console.warn('"useAsync" update a readonly field is not allowed'),l.value=e}}),error:h,reload:()=>_(y.value),onError:e=>{c.push(e)},onStart:e=>{d.push(e)},onEnd:e=>{v.push(e)},promise:E}};function b(t){const r=s(),n=s(),o=s(),i=[],a=[],u=s(null);return{mutate:(e,...s)=>{r.value=!0,o.value=null;const l=t;return u.value=l(e,...s),u.value.catch(t=>{o.value=t||null,i.forEach(t=>t(o.value,s.length?[e,...s]:e)),o.value=t}),u.value.then(t=>{n.value=t,a.forEach(t=>t(n.value,s.length?[e,...s]:e))}),u.value.finally(()=>{r.value=!1}),u.value},onError:e=>i.push(e),onEnd:e=>a.push(e),isPending:r,error:o,data:n,promise:e(()=>u.value)}}function _(){return function(e){return b(e)}}function E(e,t,r){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var r=t.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class R{static parseResult(e){let t=e.response;try{const r=e.getResponseHeader("Content-Type");r?.toLowerCase().includes("json")&&(t=JSON.parse(e.response))}catch(r){t=e.response}return t}static extractQueryParams(e){let t=e;const r={},s=t.search(/#/);s>-1&&(t=t.substring(0,s));const n=t.indexOf("?"),o=(!0).toString(),i=(!1).toString();return n>-1&&t.split("?")[1].split("&").reduce((e,t)=>{const r=e,[s,n=""]=t.split("="),[,a]=/^(?:"?([^"]+)"?)$/.exec(n)||[];if(a===o||a===i)return r[s]=a===o,r;const u=Number(a);return r[s]=""===a||Number.isNaN(u)?a:u,r},r),r}static onBeforeSend(e){R.onBeforeSendList.push(e)}constructor(e,t){E(this,"onError",()=>{}),E(this,"onStart",()=>{}),E(this,"onAbort",()=>{}),E(this,"onProgress",()=>{}),E(this,"onEnd",()=>{}),E(this,"token",null),E(this,"url",""),E(this,"params",{}),E(this,"sendAs","json"),E(this,"timeout",1e4),E(this,"port",80),E(this,"responseType","text"),E(this,"isPending",!1),E(this,"_eventsReady",void 0),E(this,"_oXHR",void 0),E(this,"_onEnd",()=>{}),E(this,"_onError",()=>{}),E(this,"_deferred",void 0),E(this,"_isXhrResolved",void 0),E(this,"_isXhrRejected",void 0),E(this,"_eventReady",void 0),this._eventsReady=!1,this._constructor(e||{},t)}static new(e){return new R(e)}_getUrl(e={}){const t=R.onBeforeSendList.reduce((e,t)=>t(e||{}),e);return R.stringifyUrl(this.url,t)}removeEvents(){const e=()=>{this._oXHR.removeEventListener("load",this._onEnd,!1),this._oXHR.removeEventListener("error",this._onError,!1),this._oXHR.removeEventListener("timeout",this._onError,!1),this._oXHR.removeEventListener("loadstart",this.onStart,!1),this._oXHR.removeEventListener("abort",this.onAbort,!1),this._oXHR.upload.removeEventListener("progress",this.onProgress,!1),this._oXHR.removeEventListener("progress",this.onProgress,!1)};this._deferred.promise.then(e,e)}post(e){this._constructor(e);const{url:t,params:r}=R.injectParamsInUrl(this.url,this.params);return this.url=t,this.params=r,this._oXHR.open("POST",this._getUrl(),!0),this._send(),this._deferred.promise}put(e){this._constructor(e);const{url:t,params:r}=R.injectParamsInUrl(this.url,this.params);return this.url=t,this.params=r,this._oXHR.open("PUT",this._getUrl(),!0),this._send(),this._deferred.promise}get(e){this._constructor(e||{});const{url:t,params:r}=R.injectParamsInUrl(this.url,this.params);this.url=t,this.params=r,this._oXHR.open("GET",this._getUrl("multipart"===this.sendAs?{}:this.params),!0),this._send();const s=this._deferred.promise;return s.abortXhr=this.abort.bind(this),s}delete(e){this._constructor(e);const{url:t,params:r}=R.injectParamsInUrl(this.url,this.params);return this.url=t,this.params=r,this._oXHR.open("DELETE",this._getUrl(this.params),!0),this._send(),this._deferred.promise}abort(){return this._isXhrResolved&&!this._isXhrRejected||(this._oXHR.abort(null,this),this._isXhrRejected=!0,this._deferred.reject({message:`Xhr aborted: ${this.url}`,name:"HTTP-ABORTED"})),this._deferred.promise}static stringifyUrl(e,t={}){let r=e,s=t;({url:r,params:s}=R.injectParamsInUrl(r,s));let n=r.includes("?")?"&":"?",o="";return s&&!Array.isArray(s)&&"object"==typeof s?Object.getOwnPropertyNames(s).filter(e=>void 0!==s[e]).forEach(e=>{o+=`${n}${e}=${encodeURIComponent(JSON.stringify(s[e]))}`,n="&"}):s&&(o=n+encodeURIComponent(JSON.stringify(s))),r=r.replace(/\/:[^/]*/gi,""),r+o}static getFormData(e){const t=new FormData;let r;return Object.keys(e).forEach(s=>{if(e[s]instanceof FileList)for(let r=0;r<e[s].length;r+=1)t.append(s,e[s][r]);else e[s]instanceof File?t.append(s,e[s]):(r=e[s],"object"!=typeof r&&!Array.isArray(r)||null===r||(r=JSON.stringify(r)),t.append(s,r))}),t}resolve(e){return this._deferred.resolve(e),this._deferred.promise}reject(e){return this._deferred.reject(e),this._deferred.promise}static _stringifyForPathParam(e,t,r){let s=r[t];switch(typeof r[t]){case"boolean":case"string":case"bigint":case"number":s=String(s);break;default:s=null===s?"null":encodeURIComponent(JSON.stringify(s))}return e.replace(`:${t}`,s)}static injectParamsInUrl(e,t={},r="GET"){if(Array.isArray(t)||0===Object.keys(t).length)return{url:e,params:t};let s=t,n=e;if("GET"===r){n=decodeURIComponent(e);const r=R.extractQueryParams(n),o=n.search(/\?|#/);o>-1&&(n=n.substring(0,o)),s=Object.getOwnPropertyNames(t).reduce((e,r)=>({...e,[r]:t[r]}),{...r}),Object.keys(s).forEach(e=>{void 0!==r[e]&&(r[e]=s[e],delete s[e])});const i=Object.keys(r);if(i.length){let e="?";i.forEach(t=>{if(!0===r[t]||!1===r[t])n+=`${e}${t}=${r[t]}`;else if(null===r[t])n+=`${e}${t}=${r[t]}`;else{const s=Number(r[t]),o=Number.isNaN(s)?encodeURIComponent(`"${r[t]}"`):s;n+=`${e}${t}=${o}`}e="&"})}}return(n.match(/:[a-z0-9]+/gi)||[]).forEach(e=>{let t=e;t=t.substring(1),void 0!==s[t]&&(n=R._stringifyForPathParam(n,t,s),delete s[t])}),{url:n,params:s}}_setEvents(e){this._eventsReady||(this._eventReady=!0,e.addEventListener("load",this._onEnd,!1),e.addEventListener("error",this._onError,!1),e.addEventListener("timeout",this._onError,!1),e.addEventListener("loadstart",this.onStart,!1),e.addEventListener("abort",this.onAbort,!1),e.upload.addEventListener("progress",this.onProgress,!1),e.addEventListener("progress",this.onProgress,!1))}_send(){let e;this.isPending=!0,"multipart"===this.sendAs?e=R.getFormData(this.params):"json"===this.sendAs&&(this._oXHR.setRequestHeader("content-type","application/json; charset=utf-8"),e=JSON.stringify(this.params)),this.token&&this._oXHR.setRequestHeader("Authorization",`Bearer ${this.token}`),this._oXHR.send(e,this)}_constructor(e,t){e&&"object"==typeof e?(this.sendAs=e.sendAs||this.sendAs,this.url=e.url||this.url,this.port=e.port||this.port,this.params=e.params||this.params,this.timeout=e.timeout||this.timeout,this.responseType=e.responseType||this.responseType,this.onProgress=(e.onProgress||this.onProgress).bind(this),this.onStart=(e.onStart||this.onStart).bind(this),this.onAbort=(e.onAbort||this.onAbort).bind(this),this.onEnd=(e.onEnd||this.onEnd).bind(this),this.onError=(e.onError||this.onError).bind(this),this.token=e.token||this.token):e&&"string"==typeof e&&(this.url=e,this.params=t||this.params),80!==this.port&&(this.url=`${window.location.protocol}//${window.location.hostname}:${this.port}${this.url}`),this._deferred=new v,this._deferred.promise.finally(()=>{this.isPending=!1}),this._oXHR=new XMLHttpRequest,this._oXHR.timeout=this.timeout,this._oXHR.responseType=this.responseType,this._isXhrResolved=!1,this._isXhrRejected=!1,this._onError=e=>{this.onError(e),this.removeEvents(),this._deferred.reject(e)},this._onEnd=async e=>{const t=R.parseResult(this._oXHR);if(this._oXHR.status>=400){let e=await(this._oXHR.response.text?.())||this._oXHR.response;try{e=JSON.parse(e)}catch(e){}return this._isXhrRejected=!0,this._onError(e),this._deferred.reject(e)}return this.onEnd(t,e),this._isXhrResolved=!0,this.removeEvents(),this.resolve(t)},this._setEvents(this._oXHR)}}E(R,"onBeforeSendList",[]);const w=()=>{},j=e=>n(e);function P(i){const{onError:a,onStart:l,onEnd:h,context:c,legacy:d,token:v=null}=i||{onError:()=>{},onStart:()=>{},onEnd:()=>{},context:null,legacy:!1,token:null},f=s([]),y=[],b=(t,r,s)=>{let o=s;const i=e(()=>{const e={},t=n(r||{});return o||(o=t.params||{}),e.params=n(o),v&&(e.token=j(v)),e.url=n(t.url),e}),a=new R,u=n(i.value.params)||{};let l;switch(t){case"post":default:l=a.post.bind(a);break;case"put":l=a.put.bind(a);break;case"delete":l=a.delete.bind(a)}return{...g(async()=>l({...i.value,params:u})),xhr:a}};return d||r(()=>{f.value.forEach(e=>{e.isPending&&e.abort()}),y.forEach(e=>e())}),{get:function(r,i,d){let g=i;const b=new R,_=(a||w).bind(c),E=(l||w).bind(c),P=(h||w).bind(c),X=[_],S=[E],H=[P],A=s(null);f.value.push(b);const L=s(),O=s();let T="",$=0;const U=e(()=>{const e={},s=n(r);let o;"string"==typeof s?o=s:(o=n(s.url),g||(g=s.params||{}),$=s.cacheDuration,void 0!==s.enabled&&(e.enabled=s.enabled),void 0===e.enabled&&(e.enabled=d),e.params=n(g),e.cacheDuration=$),v&&(e.token=j(v));let i=n(e.params||g||{});return"function"==typeof i&&(i=i()),e.params={...i,...t(g)?g.value||{}:g},T="function"==typeof o?o(e.params):n(o),e.url=T,e}),N=()=>{const e=void 0!==U.value.enabled?U.value.enabled:d;return void 0===e||(t(e)?n(e):"function"==typeof e?e():!0===e)},k=s(),x=()=>{if(!N())return;L.value&&b.abort();const e="object"==typeof U.value.params?U.value.params:{};S.forEach(t=>t(e,b)),L.value=!0,A.value=null;const t=decodeURIComponent(R.stringifyUrl(String(T),e));k.value=u({id:t,xhr:b.get.bind(b,U.value),duration:$}),k.value.catch(e=>{X.forEach(t=>t(e,b)),A.value=e}),k.value.then(e=>{O.value=e}),k.value.finally(()=>{(()=>{const e=f.value.indexOf(b);e>-1&&f.value.splice(e,1)})(),L.value=!1,H.forEach(t=>t(O.value,e,b))})};return y.push(o(()=>U.value,x,{immediate:N(),deep:!0})),y.push(o(()=>A.value,e=>{if(e)throw e})),{isPending:e(()=>L.value),data:e({get:()=>O.value,set:e=>{e instanceof m&&e.uuid===p||console.warn('"useXhr" update a readonly field is not allowed'),O.value=e}}),onError:e=>X.push(e),onStart:e=>S.push(e),onEnd:e=>H.push(e),error:A,abort:()=>k.value?.abortXhr(),promise:e(async()=>k.value||new Promise(()=>{})),reload:x,xhr:b}},post:(e,t)=>b("post",e,t),put:(e,t)=>b("put",e,t),delete:(e,t)=>b("delete",e,t)}}function X(t,n=400){const i=s(!1);let a,u=0;return o(()=>t.value,e=>{if(e&&(u=Date.now(),i.value=e),!1===e&&u>0){const t=Date.now()-u;clearTimeout(a),t>n?i.value=e:a=setTimeout(()=>{i.value=e},n-t)}},{immediate:!0}),r(()=>{clearTimeout(a)}),e(()=>i.value)}export{v as Deferred,R as Xhr,u as cache,h as cacheIds,l as cacheSize,c as clearCache,g as useAsync,b as useMutation,_ as useMutationWithError,y as useResult,X as useSpinner,P as useXhr};
@@ -1,16 +1,21 @@
1
- import type { ComputedRef, Ref, UnwrapRef } from 'vue';
1
+ import type { ComputedRef, Ref } from 'vue';
2
2
  import type { RequiredParams, TypeAllowed, UnwrappedPromiseType } from '.';
3
3
  type OnErrorCb<T> = (e: null | Error, params: T) => unknown;
4
4
  type OnStartCb<T> = (params: T) => unknown;
5
5
  type OnEndCb<T, Z> = (res: T, params: Z) => unknown;
6
- declare const useAsync: <T, Z extends TypeAllowed, A extends TypeAllowed[], F extends ((...args: A) => Promise<T>) | ((args: Z) => Promise<T>), P extends RequiredParams<Parameters<F>[0], A>>(func: ((...args: A) => Promise<T>) | ((args: Z) => Promise<T>), ...[params, enabledArg]: undefined extends P ? [params?: P, enabled?: Ref<boolean> | (() => boolean)] : [params: P, enabled?: Ref<boolean> | (() => boolean)]) => {
6
+ type AsyncFunc = (...args: any[]) => Promise<unknown>;
7
+ type Enabled = Ref<boolean> | (() => boolean);
8
+ type AsyncParams<F extends AsyncFunc> = Parameters<F> extends TypeAllowed[] ? RequiredParams<Parameters<F>[0], Parameters<F>> : never;
9
+ type AsyncArgs<F extends AsyncFunc, P> = Parameters<F> extends [] ? [params?: undefined, enabled?: Enabled] : [] extends Parameters<F> ? [params?: P, enabled?: Enabled] : [params: P, enabled?: Enabled];
10
+ type UnwrapParams<P> = P extends () => infer PP ? PP : (P extends Ref<infer PP> ? PP : P);
11
+ declare const useAsync: <F extends AsyncFunc, P extends AsyncParams<F> = AsyncParams<F>>(func: F, ...[params, enabledArg]: AsyncArgs<F, P>) => {
7
12
  isPending: Ref<undefined | boolean>;
8
13
  data: ComputedRef<undefined | null | UnwrappedPromiseType<F>>;
9
14
  error: Ref<null | Error>;
10
- reload: () => null | Promise<T>;
11
- onError: (cb: OnErrorCb<P extends () => infer PP ? PP : (P extends ComputedRef<unknown> ? UnwrapRef<P> : P)>) => void;
12
- onStart: (cb: OnStartCb<P extends () => infer PP ? PP : (P extends ComputedRef<unknown> ? UnwrapRef<P> : P)>) => void;
13
- onEnd: (cb: OnEndCb<UnwrappedPromiseType<F>, P extends () => infer PP ? PP : (P extends ComputedRef<unknown> ? UnwrapRef<P> : P)>) => unknown;
14
- promise: ComputedRef<null | Promise<T>>;
15
+ reload: () => null | Promise<UnwrappedPromiseType<F>>;
16
+ onError: (cb: OnErrorCb<UnwrapParams<P>>) => void;
17
+ onStart: (cb: OnStartCb<UnwrapParams<P>>) => void;
18
+ onEnd: (cb: OnEndCb<UnwrappedPromiseType<F>, UnwrapParams<P>>) => unknown;
19
+ promise: ComputedRef<null | Promise<UnwrappedPromiseType<F>>>;
15
20
  };
16
21
  export default useAsync;
package/dist/useXhr.d.ts CHANGED
@@ -23,9 +23,9 @@ export default function <T, Z extends TypeAllowed, A extends TypeAllowed[], F ex
23
23
  data: ComputedRef<TT | null | undefined>;
24
24
  error: Ref<null | Error>;
25
25
  reload: () => Promise<TT> | null;
26
- onError: (cb: (e: null | Error, params: Ref<[] | TypeAllowed, [] | TypeAllowed> | [] | TypeAllowed) => unknown) => void;
27
- onStart: (cb: (params: Ref<[] | TypeAllowed, [] | TypeAllowed> | [] | TypeAllowed) => unknown) => void;
28
- onEnd: (cb: (res: TT, params: Ref<[] | TypeAllowed, [] | TypeAllowed> | [] | TypeAllowed) => unknown) => unknown;
26
+ onError: (cb: (e: null | Error, params: [] | undefined) => unknown) => void;
27
+ onStart: (cb: (params: [] | undefined) => unknown) => void;
28
+ onEnd: (cb: (res: TT, params: [] | undefined) => unknown) => unknown;
29
29
  promise: ComputedRef<Promise<TT> | null>;
30
30
  xhr: Xhr<TT>;
31
31
  };
@@ -34,9 +34,9 @@ export default function <T, Z extends TypeAllowed, A extends TypeAllowed[], F ex
34
34
  data: ComputedRef<TT | null | undefined>;
35
35
  error: Ref<null | Error>;
36
36
  reload: () => Promise<TT> | null;
37
- onError: (cb: (e: null | Error, params: Ref<[] | TypeAllowed, [] | TypeAllowed> | [] | TypeAllowed) => unknown) => void;
38
- onStart: (cb: (params: Ref<[] | TypeAllowed, [] | TypeAllowed> | [] | TypeAllowed) => unknown) => void;
39
- onEnd: (cb: (res: TT, params: Ref<[] | TypeAllowed, [] | TypeAllowed> | [] | TypeAllowed) => unknown) => unknown;
37
+ onError: (cb: (e: null | Error, params: [] | undefined) => unknown) => void;
38
+ onStart: (cb: (params: [] | undefined) => unknown) => void;
39
+ onEnd: (cb: (res: TT, params: [] | undefined) => unknown) => unknown;
40
40
  promise: ComputedRef<Promise<TT> | null>;
41
41
  xhr: Xhr<TT>;
42
42
  };
@@ -45,9 +45,9 @@ export default function <T, Z extends TypeAllowed, A extends TypeAllowed[], F ex
45
45
  data: ComputedRef<TT | null | undefined>;
46
46
  error: Ref<null | Error>;
47
47
  reload: () => Promise<TT> | null;
48
- onError: (cb: (e: null | Error, params: Ref<[] | TypeAllowed, [] | TypeAllowed> | [] | TypeAllowed) => unknown) => void;
49
- onStart: (cb: (params: Ref<[] | TypeAllowed, [] | TypeAllowed> | [] | TypeAllowed) => unknown) => void;
50
- onEnd: (cb: (res: TT, params: Ref<[] | TypeAllowed, [] | TypeAllowed> | [] | TypeAllowed) => unknown) => unknown;
48
+ onError: (cb: (e: null | Error, params: [] | undefined) => unknown) => void;
49
+ onStart: (cb: (params: [] | undefined) => unknown) => void;
50
+ onEnd: (cb: (res: TT, params: [] | undefined) => unknown) => unknown;
51
51
  promise: ComputedRef<Promise<TT> | null>;
52
52
  xhr: Xhr<TT>;
53
53
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vue-use-async",
3
- "version": "1.13.9",
3
+ "version": "1.13.10",
4
4
  "description": "Xhr and async helpers",
5
5
  "repository": {
6
6
  "type": "git",
@@ -28,41 +28,41 @@
28
28
  },
29
29
  "dependencies": {
30
30
  "@eslint/config-helpers": "^0.7.0",
31
- "@jest/globals": "^30.4.1",
31
+ "@jest/globals": "^30.5.2",
32
32
  "prune": "^0.0.2"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@babel/plugin-transform-class-properties": "^8.0.1",
36
- "@babel/preset-env": "^8.0.2",
36
+ "@babel/preset-env": "^8.0.6",
37
37
  "@babel/preset-typescript": "^8.0.1",
38
- "@eslint/compat": "^2.1.0",
39
- "@eslint/eslintrc": "^3.3.6",
38
+ "@eslint/compat": "^2.1.1",
39
+ "@eslint/eslintrc": "^3.3.7",
40
40
  "@eslint/js": "^9.39.5",
41
41
  "@stylistic/eslint-plugin": "^5.10.0",
42
- "@tcy/eslint-rules": "^1.7.0",
42
+ "@tcy/eslint-rules": "^1.10.0",
43
43
  "@types/jest": "^30.0.0",
44
- "@types/node": "^26.2.0",
45
- "@typescript-eslint/eslint-plugin": "^8.67.0",
46
- "@typescript-eslint/parser": "^8.67.0",
44
+ "@types/node": "^26.6.3",
45
+ "@typescript-eslint/eslint-plugin": "^8.70.1",
46
+ "@typescript-eslint/parser": "^8.70.1",
47
47
  "babel-loader": "^10.1.1",
48
48
  "babel-plugin-module-resolver": "^5.0.3",
49
49
  "eslint": "^9.39.2",
50
50
  "eslint-config-airbnb-extended": "^3.2.0",
51
51
  "eslint-import-resolver-typescript": "^4.4.5",
52
52
  "eslint-plugin-import-x": "^4.17.1",
53
- "eslint-plugin-jest": "^29.16.1",
54
- "eslint-plugin-n": "^18.3.0",
53
+ "eslint-plugin-jest": "^29.16.6",
54
+ "eslint-plugin-n": "^18.4.0",
55
55
  "husky": "^9.1.7",
56
- "jest": "^30.4.2",
57
- "jest-environment-jsdom": "^30.4.1",
58
- "lint-staged": "^17.3.0",
56
+ "jest": "^30.5.2",
57
+ "jest-environment-jsdom": "^30.5.2",
58
+ "lint-staged": "^17.6.0",
59
59
  "rimraf": "^6.1.3",
60
60
  "ts-node": "^10.9.2",
61
61
  "typescript": "^6.0.3",
62
- "typescript-eslint": "^8.67.0",
62
+ "typescript-eslint": "^8.70.1",
63
63
  "typescript7": "npm:typescript@^7.0.2",
64
- "webpack": "^5.109.2",
65
- "webpack-cli": "^7.2.2"
64
+ "webpack": "^5.111.1",
65
+ "webpack-cli": "^7.2.3"
66
66
  },
67
67
  "peerDependencies": {
68
68
  "vue": "*"