klaim 1.12.43 → 1.12.44

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/deno.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@antharuu/klaim",
3
- "version": "1.12.43",
3
+ "version": "1.12.44",
4
4
  "description": "Klaim is a lightweight TypeScript library designed to manage APIs and record requests, optimized for an optimal user experience.",
5
5
  "repository": {
6
6
  "type": "git",
package/dist/klaim.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});function e(e){return e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(`-`,``).replace(`_`,``)).replace(/(^\w)/,e=>e.toLowerCase())}function t(e){return e.trim().replace(/^\/|\/$/g,``)}var n={limit:5,duration:10},r=new Map;function i(e,t){let n=Date.now(),i=t.duration*1e3,a=r.get(e);a||(a={timestamps:[]},r.set(e,a));let o=a.timestamps.filter(e=>n-e<i);return o.length>=t.limit?!1:(o.push(n),a.timestamps=o,!0)}function a(e,t){let n=r.get(e);if(!n||n.timestamps.length<t.limit)return 0;let i=Date.now(),a=t.duration*1e3,o=[...n.timestamps].sort((e,t)=>e-t)[0]+a-i;return Math.max(0,o)}var o=class extends Error{constructor(e){super(e),this.name=`KlaimError`}},s=class extends o{retryAfterMs;constructor(e,t){super(e),this.name=`RateLimitError`,this.retryAfterMs=t}},c=class extends o{constructor(e){super(e),this.name=`TimeoutError`}},l=class extends o{attempts;cause;constructor(e,t,n){super(e),this.name=`RetryExhaustedError`,this.attempts=t,this.cause=n}},u=class extends o{argument;constructor(e){super(`Argument ${e} is missing`),this.name=`MissingArgumentError`,this.argument=e}},d=class extends o{constructor(e){super(`Invalid path: ${e}`),this.name=`InvalidPathError`}},f={duration:5,message:`Request timed out`};async function p(e,t){let{duration:n,message:r}=t;return Promise.race([e,new Promise((e,t)=>{let i=setTimeout(()=>{clearTimeout(i),t(new c(r))},n*1e3)})])}var m={page:1,pageParam:`page`,limit:10,limitParam:`limit`},h=class{type;name;url;headers;parent;method;arguments=new Set;schema;pagination;callbacks={before:null,after:null,call:null};cache=!1;retry=!1;rate=!1;timeout=!1;constructor(n,r,i,a={}){this.type=n,this.name=e(r),this.url=t(i),this.headers=a||{}}before(e){return this.callbacks.before=e,this}after(e){return this.callbacks.after=e,this}onCall(e){return this.callbacks.call=e,this}withCache(e=20){return this.cache=e,this}withRetry(e=2){return this.retry=e,this}withPagination(e={}){return this.pagination={...m,...e},this}withRate(e={}){return this.rate={...n,...e},this}withTimeout(e=f.duration,t=f.message){return this.timeout={duration:e,message:t},this}},g=1e3,_=class e{static _instance;cache;maxSize;constructor(e=g){this.cache=new Map,this.maxSize=e}static get i(){return e._instance||=new e,e._instance}set(e,t,n=0){if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=this.maxSize){let e=this.cache.keys().next().value;e!==void 0&&this.cache.delete(e)}let r=n>0?Date.now()+n:1/0;this.cache.set(e,{data:t,expiry:r})}has(e){let t=this.cache.get(e);return t?Date.now()>t.expiry?(this.cache.delete(e),!1):!0:!1}get(e){if(this.has(e)){let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t.data}return null}clear(){this.cache.clear()}get size(){return this.cache.size}};function v(e){let t=16777619,n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,t)>>>0;let r=(n>>>0).toString(16).padStart(8,`0`),i=0;for(;r.length<32;)n^=r.charCodeAt(i%r.length),n=Math.imul(n,t)>>>0,r+=(n>>>0).toString(16).padStart(8,`0`),i++;return r.substring(0,32)}async function y(e,t,n){let r=v(`${e.toString()}${JSON.stringify(t)}`);if(_.i.has(r))return _.i.get(r);let i=await(await fetch(e,t)).json();return _.i.set(r,i,n),i}var b=class{static _callbacks=new Map;static subscribe(e,t){this._callbacks.set(e,t)}static run(e){let t=this._callbacks.get(e);t&&t()}static unsubscribe(e){this._callbacks.delete(e)}static unsubscribeAll(){this._callbacks.clear()}},x={};function S(e,t){return async(...n)=>{if(t.pagination){let[r=0,i={},a={}]=n;return C(e,t,r,i,a)}let[r={},i={}]=n;return C(e,t,void 0,r,i)}}async function C(e,t,n,r={},i={}){let a=e.split(`.`),o;for(let e=0;e<a.length;e++){let t=a[e];if(o=k.i.getApi(t),o)break}if(!t||!o||t.type!==`route`||o.type!==`api`)throw new d(`${e}.${t.name}`);let s=E(`${o.url}/${t.url}`,t,r);if(t.pagination&&n!==void 0){let{pageParam:e=`page`,limit:r=10,limitParam:i=`limit`}=t.pagination,a=new URLSearchParams;a.append(e,String(n)),a.append(i,String(r));let o=s.includes(`?`)?`&`:`?`;s=`${s}${o}${a.toString()}`}let c={};i&&t.method!==`GET`&&(c.body=JSON.stringify(i)),c.headers={"Content-Type":`application/json`,...o.headers,...t.headers},c.method=t.method;let{beforeRoute:l,beforeApi:u,beforeUrl:f,beforeConfig:p}=D({route:t,api:o,url:s,config:c});s=f,c=p,k.updateElement(u),k.updateElement(l);let m=await T(o,t,s,c);t.schema&&(m=await t.schema.validate(m));let{afterRoute:h,afterApi:g,afterData:_}=O({route:t,api:o,response:m,data:m});return k.updateElement(g),k.updateElement(h),b.run(`${o.name}.${t.name}`),_}async function w(e,t,n,r){return e?await y(t,n,r.cache||void 0):await(await fetch(t,n)).json()}async function T(e,t,n,r){let o=e.cache||t.cache,c=t.retry||e.retry||0,u=t.timeout||e.timeout;if(t.rate){let n=`ROUTE:${e.name}:${t.name}`;if(!i(n,t.rate)){let r=a(n,t.rate);throw new s(`Rate limit exceeded for ${e.name}.${t.name}. Try again in ${Math.ceil(r/1e3)} seconds.`,r)}}else if(e.rate){let t=`API:${e.name}`;if(!i(t,e.rate)){let n=a(t,e.rate);throw new s(`Rate limit exceeded for ${e.name} API. Try again in ${Math.ceil(n/1e3)} seconds.`,n)}}let d,f=!1,m=0;for(;m<=c&&!f;)try{t.callbacks?.call?t.callbacks.call({}):e.callbacks?.call&&e.callbacks.call({});let i=w(!!o,n,r,e);d=u?await p(i,u):await i,f=!0}catch(e){if(m++,m>c){if(c===0&&e instanceof Error)throw e;let t=e instanceof Error?e:void 0;throw new l(`Failed to fetch ${n} after ${c+1} attempts`,m,t)}let t=200*2**(m-1)+Math.random()*100;await new Promise(e=>setTimeout(e,t))}return d}function E(e,t,n){let r=e;return t.arguments.forEach(e=>{let t=n[e];if(t===void 0)throw new u(e);r=r.replace(`[${e}]`,encodeURIComponent(String(t)))}),r}function D({route:e,api:t,url:n,config:r}){let i=e.callbacks.before?.({route:e,api:t,url:n,config:r});return{beforeRoute:i?.route||e,beforeApi:i?.api||t,beforeUrl:i?.url||n,beforeConfig:i?.config||r}}function O({route:e,api:t,response:n,data:r}){let i=e.callbacks.after?.({route:e,api:t,response:n,data:r});return{afterRoute:i?.route||e,afterApi:i?.api||t,afterResponse:i?.response||n,afterData:i?.data||r}}var k=class e{static _instance;_elements=new Map;_currentParent=null;constructor(){}static get i(){return e._instance||=new e,e._instance}registerElement(e){let t=this._currentParent;t&&(e.parent=this.getFullPath(t));let n=this.getElementKey(e);if(this._elements.set(n,e),e.type===`api`||e.type===`group`){let n=x;if(t){let e=this.getFullPath(t).split(`.`);for(let t of e)n[t]||(n[t]={}),n=n[t]}n[e.name]||(n[e.name]={})}}getCurrentParent(){return this._currentParent}setCurrentParent(e){let t=this._elements.get(e);if(!t||t.type!==`api`&&t.type!==`group`)throw Error(`Element ${e} not found or not a valid parent type`);this._currentParent=t}clearCurrentParent(){this._currentParent=null}registerRoute(e){if(!this._currentParent)throw Error(`No current parent set, use Route only inside Api or Group create callback`);e.parent=this.getFullPath(this._currentParent);let t=this.getElementKey(e);this._elements.set(t,e),this.addToKlaimRoute(e)}addToKlaimRoute(e){if(!e.parent)return;let t=x,n=e.parent.split(`.`);for(let e of n)t[e]||(t[e]={}),t=t[e];t[e.name]=S(e.parent,e)}getElementKey(e){return e?e.parent?`${e.parent}.${e.name}`:e.name:``}getFullPath(e){if(!e)return``;if(!e.parent)return e.name;let t=[e.name],n=e;for(;n.parent;){let e=this._elements.get(n.parent);if(!e)break;t.unshift(e.name),n=e}return t.join(`.`)}getRoute(e,t){return this._elements.get(`${e}.${t}`)}getChildren(e){let t=[];return this._elements.forEach(n=>{n.parent===e&&t.push(n)}),t}static updateElement(t){return e.i._elements.get(e.i.getElementKey(t))||t}getApi(e){let t=this._elements.get(e);if(!t){for(let[t,n]of this._elements.entries())if(n.type===`api`&&t.endsWith(`.${e}`))return n;return}return t.type===`api`?t:this.findApi(t)}findApi(e){if(!e||!e.parent)return;let t=e.parent.split(`.`);for(let e=t.length;e>=0;e--){let n=t.slice(0,e).join(`.`),r=this._elements.get(n);if(r?.type===`api`)return r}}reset(){this._elements.clear(),this._currentParent=null;for(let e of Object.keys(x))delete x[e]}},A=class t extends h{static create(n,r,i,a={}){let o=e(n),s=new t(o,r,a),c=k.i.getCurrentParent();k.i.registerElement(s);let l=c?k.i.getFullPath(c):``,u=l?`${l}.${o}`:o;return k.i.setCurrentParent(u),i(),c?k.i.setCurrentParent(k.i.getFullPath(c)):k.i.clearCurrentParent(),s}constructor(e,t,n={}){super(`api`,e,t,n)}},j=class t extends h{static create(n,r){let i=e(n),a=k.i.getCurrentParent(),o=a?k.i.getFullPath(a):``,s=o?`${o}.${i}`:i,c=new t(i,``);k.i.registerElement(c);let l=k.i.getCurrentParent();return k.i.setCurrentParent(s),r(),l?k.i.setCurrentParent(k.i.getFullPath(l)):k.i.clearCurrentParent(),c}constructor(e,t,n={}){super(`group`,e,t,n)}withCache(e=20){return super.withCache(e),k.i.getChildren(k.i.getFullPath(this)).forEach(t=>{t.cache||=e}),this}withRetry(e=2){return super.withRetry(e),k.i.getChildren(k.i.getFullPath(this)).forEach(t=>{t.retry||=e}),this}withTimeout(e=f.duration,t=f.message){return super.withTimeout(e,t),k.i.getChildren(k.i.getFullPath(this)).forEach(n=>{n.timeout||={duration:e,message:t}}),this}before(e){return super.before(e),k.i.getChildren(k.i.getFullPath(this)).forEach(t=>{t.callbacks.before||(t.callbacks.before=e)}),this}after(e){return super.after(e),k.i.getChildren(k.i.getFullPath(this)).forEach(t=>{t.callbacks.after||(t.callbacks.after=e)}),this}onCall(e){return super.onCall(e),k.i.getChildren(k.i.getFullPath(this)).forEach(t=>{t.callbacks.call||(t.callbacks.call=e)}),this}},M=function(e){return e.GET=`GET`,e.POST=`POST`,e.PUT=`PUT`,e.DELETE=`DELETE`,e.PATCH=`PATCH`,e.OPTIONS=`OPTIONS`,e}({}),N=class e extends h{constructor(e,t,n={},r=M.GET){super(`route`,e,t,n),this.method=r,this.detectArguments()}static createRoute(t,n,r={},i){let a=new e(t,n,r,i);return k.i.registerRoute(a),a}static get(e,t,n={}){return this.createRoute(e,t,n,M.GET)}static post(e,t,n={}){return this.createRoute(e,t,n,M.POST)}static put(e,t,n={}){return this.createRoute(e,t,n,M.PUT)}static delete(e,t,n={}){return this.createRoute(e,t,n,M.DELETE)}static patch(e,t,n={}){return this.createRoute(e,t,n,M.PATCH)}static options(e,t,n={}){return this.createRoute(e,t,n,M.OPTIONS)}detectArguments(){let e=this.url.match(/\[([^\]]+)]/g);e&&e.forEach(e=>{let t=e.slice(1,-1);this.arguments.add(t)})}validate(e){return this.schema=e,this}};exports.Api=A,exports.Cache=_,exports.Group=j,exports.Hook=b,exports.InvalidPathError=d,exports.Klaim=x,exports.KlaimError=o,exports.MissingArgumentError=u,exports.RateLimitError=s,exports.Registry=k,exports.RetryExhaustedError=l,exports.Route=N,exports.TimeoutError=c;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});function e(e){return e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(`-`,``).replace(`_`,``)).replace(/(^\w)/,e=>e.toLowerCase())}function t(e){return e.trim().replace(/^\/|\/$/g,``)}var n={limit:5,duration:10},r=new Map;function i(e,t){let n=Date.now(),i=t.duration*1e3,a=r.get(e);a||(a={timestamps:[]},r.set(e,a));let o=a.timestamps.filter(e=>n-e<i);return o.length>=t.limit?!1:(o.push(n),a.timestamps=o,!0)}function a(e,t){let n=r.get(e);if(!n||n.timestamps.length<t.limit)return 0;let i=Date.now(),a=t.duration*1e3,o=[...n.timestamps].sort((e,t)=>e-t)[0]+a-i;return Math.max(0,o)}var o=class extends Error{constructor(e){super(e),this.name=`KlaimError`}},s=class extends o{retryAfterMs;constructor(e,t){super(e),this.name=`RateLimitError`,this.retryAfterMs=t}},c=class extends o{constructor(e){super(e),this.name=`TimeoutError`}},l=class extends o{attempts;cause;constructor(e,t,n){super(e),this.name=`RetryExhaustedError`,this.attempts=t,this.cause=n}},u=class extends o{argument;constructor(e){super(`Argument ${e} is missing`),this.name=`MissingArgumentError`,this.argument=e}},d=class extends o{constructor(e){super(`Invalid path: ${e}`),this.name=`InvalidPathError`}},f={duration:5,message:`Request timed out`};async function p(e,t){let{duration:n,message:r}=t;return Promise.race([e,new Promise((e,t)=>{let i=setTimeout(()=>{clearTimeout(i),t(new c(r))},n*1e3)})])}var m={page:1,pageParam:`page`,limit:10,limitParam:`limit`},h=class{type;name;url;headers;parent;method;arguments=new Set;schema;pagination;callbacks={before:null,after:null,call:null};cache=!1;retry=!1;rate=!1;timeout=!1;constructor(n,r,i,a={}){this.type=n,this.name=e(r),this.url=t(i),this.headers=a||{}}before(e){return this.callbacks.before=e,this}after(e){return this.callbacks.after=e,this}onCall(e){return this.callbacks.call=e,this}withCache(e=20){return this.cache=e,this}withRetry(e=2){return this.retry=e,this}withPagination(e={}){return this.pagination={...m,...e},this}withRate(e={}){return this.rate={...n,...e},this}withTimeout(e=f.duration,t=f.message){return this.timeout={duration:e,message:t},this}},g=1e3,_=class e{static _instance;cache;maxSize;constructor(e=g){this.cache=new Map,this.maxSize=e}static get i(){return e._instance||=new e,e._instance}set(e,t,n=0){if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=this.maxSize){let e=this.cache.keys().next().value;e!==void 0&&this.cache.delete(e)}let r=n>0?Date.now()+n:1/0;this.cache.set(e,{data:t,expiry:r})}has(e){let t=this.cache.get(e);return t?Date.now()>t.expiry?(this.cache.delete(e),!1):!0:!1}get(e){if(this.has(e)){let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t.data}return null}clear(){this.cache.clear()}get size(){return this.cache.size}};function v(e){let t=16777619,n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,t)>>>0;let r=(n>>>0).toString(16).padStart(8,`0`),i=0;for(;r.length<32;)n^=r.charCodeAt(i%r.length),n=Math.imul(n,t)>>>0,r+=(n>>>0).toString(16).padStart(8,`0`),i++;return r.substring(0,32)}async function y(e,t,n){let r=v(`${e.toString()}${JSON.stringify(t)}`);if(_.i.has(r))return _.i.get(r);let i=await(await fetch(e,t)).json();return _.i.set(r,i,n),i}var b=class{static _callbacks=new Map;static subscribe(e,t){this._callbacks.set(e,t)}static run(e){let t=this._callbacks.get(e);t&&t()}static unsubscribe(e){this._callbacks.delete(e)}static unsubscribeAll(){this._callbacks.clear()}},x={};function S(e,t){return async(...n)=>{if(t.pagination){let[r=0,i={},a={}]=n;return C(e,t,r,i,a)}let[r={},i={}]=n;return C(e,t,void 0,r,i)}}async function C(e,t,n,r={},i={}){let a=e.split(`.`),o;for(let e=0;e<a.length;e++){let t=a[e];if(o=k.i.getApi(t),o)break}if(!t||!o||t.type!==`route`||o.type!==`api`)throw new d(`${e}.${t.name}`);let s=E(`${o.url}/${t.url}`,t,r);if(t.pagination&&n!==void 0){let{pageParam:e=`page`,limit:r=10,limitParam:i=`limit`}=t.pagination,a=new URLSearchParams;a.append(e,String(n)),a.append(i,String(r));let o=s.includes(`?`)?`&`:`?`;s=`${s}${o}${a.toString()}`}let c={};i&&t.method!==`GET`&&(c.body=JSON.stringify(i)),c.headers={"Content-Type":`application/json`,...o.headers,...t.headers},c.method=t.method;let{beforeRoute:l,beforeApi:u,beforeUrl:f,beforeConfig:p}=D({route:t,api:o,url:s,config:c});s=f,c=p,k.updateElement(u),k.updateElement(l);let m=await T(o,t,s,c);t.schema&&(m=await t.schema.validate(m));let{afterRoute:h,afterApi:g,afterData:_}=O({route:t,api:o,response:m,data:m});return k.updateElement(g),k.updateElement(h),b.run(`${o.name}.${t.name}`),_}async function w(e,t,n,r){return e?await y(t,n,r.cache||void 0):await(await fetch(t,n)).json()}async function T(e,t,n,r){let o=e.cache||t.cache,c=t.retry||e.retry||0,u=t.timeout||e.timeout;if(t.rate){let n=`ROUTE:${e.name}:${t.name}`;if(!i(n,t.rate)){let r=a(n,t.rate);throw new s(`Rate limit exceeded for ${e.name}.${t.name}. Try again in ${Math.ceil(r/1e3)} seconds.`,r)}}else if(e.rate){let t=`API:${e.name}`;if(!i(t,e.rate)){let n=a(t,e.rate);throw new s(`Rate limit exceeded for ${e.name} API. Try again in ${Math.ceil(n/1e3)} seconds.`,n)}}let d,f=!1,m=0;for(;m<=c&&!f;)try{t.callbacks?.call?t.callbacks.call({}):e.callbacks?.call&&e.callbacks.call({});let i=w(!!o,n,r,e);d=u?await p(i,u):await i,f=!0}catch(e){if(m++,m>c){if(c===0&&e instanceof Error)throw e;let t=e instanceof Error?e:void 0;throw new l(`Failed to fetch ${n} after ${c+1} attempts`,m,t)}let t=200*2**(m-1)+Math.random()*100;await new Promise(e=>setTimeout(e,t))}return d}function E(e,t,n){let r=e;return t.arguments.forEach(e=>{let t=n[e];if(t===void 0)throw new u(e);r=r.replace(`[${e}]`,encodeURIComponent(String(t)))}),r}function D({route:e,api:t,url:n,config:r}){let i=e.callbacks.before?.({route:e,api:t,url:n,config:r});return{beforeRoute:i?.route||e,beforeApi:i?.api||t,beforeUrl:i?.url||n,beforeConfig:i?.config||r}}function O({route:e,api:t,response:n,data:r}){let i=e.callbacks.after?.({route:e,api:t,response:n,data:r});return{afterRoute:i?.route||e,afterApi:i?.api||t,afterResponse:i?.response||n,afterData:i?.data||r}}var k=class e{static _instance;_elements=new Map;_currentParent=null;constructor(){}static get i(){return e._instance||=new e,e._instance}registerElement(e){let t=this._currentParent;t&&(e.parent=this.getFullPath(t));let n=this.getElementKey(e);if(this._elements.set(n,e),e.type===`api`||e.type===`group`){let n=x;if(t){let e=this.getFullPath(t).split(`.`);for(let t of e)n[t]||(n[t]={}),n=n[t]}n[e.name]||(n[e.name]={})}}getCurrentParent(){return this._currentParent}setCurrentParent(e){let t=this._elements.get(e);if(!t||t.type!==`api`&&t.type!==`group`)throw Error(`Element ${e} not found or not a valid parent type`);this._currentParent=t}clearCurrentParent(){this._currentParent=null}registerRoute(e){if(!this._currentParent)throw Error(`No current parent set, use Route only inside Api or Group create callback`);e.parent=this.getFullPath(this._currentParent);let t=this.getElementKey(e);this._elements.set(t,e),this.addToKlaimRoute(e)}addToKlaimRoute(e){if(!e.parent)return;let t=x,n=e.parent.split(`.`);for(let e of n)t[e]||(t[e]={}),t=t[e];t[e.name]=S(e.parent,e)}getElementKey(e){return e?e.parent?`${e.parent}.${e.name}`:e.name:``}getFullPath(e){if(!e)return``;if(!e.parent)return e.name;let t=[e.name],n=e;for(;n.parent;){let e=this._elements.get(n.parent);if(!e)break;t.unshift(e.name),n=e}return t.join(`.`)}getRoute(e,t){return this._elements.get(`${e}.${t}`)}getChildren(e){let t=[];return this._elements.forEach(n=>{n.parent===e&&t.push(n)}),t}static updateElement(t){return e.i._elements.get(e.i.getElementKey(t))||t}getApi(e){let t=this._elements.get(e);if(!t){for(let[t,n]of this._elements.entries())if(n.type===`api`&&t.endsWith(`.${e}`))return n;return}return t.type===`api`?t:this.findApi(t)}findApi(e){if(!e||!e.parent)return;let t=e.parent.split(`.`);for(let e=t.length;e>=0;e--){let n=t.slice(0,e).join(`.`),r=this._elements.get(n);if(r?.type===`api`)return r}}reset(){this._elements.clear(),this._currentParent=null;for(let e of Object.keys(x))delete x[e]}},A=class t extends h{static create(n,r,i,a={}){let o=e(n),s=new t(o,r,a),c=k.i.getCurrentParent();k.i.registerElement(s);let l=c?k.i.getFullPath(c):``,u=l?`${l}.${o}`:o;return k.i.setCurrentParent(u),i(),c?k.i.setCurrentParent(k.i.getFullPath(c)):k.i.clearCurrentParent(),s}constructor(e,t,n={}){super(`api`,e,t,n)}},j=class t extends h{static create(n,r){let i=e(n),a=k.i.getCurrentParent(),o=a?k.i.getFullPath(a):``,s=o?`${o}.${i}`:i,c=new t(i,``);k.i.registerElement(c);let l=k.i.getCurrentParent();return k.i.setCurrentParent(s),r(),l?k.i.setCurrentParent(k.i.getFullPath(l)):k.i.clearCurrentParent(),c}constructor(e,t,n={}){super(`group`,e,t,n)}withCache(e=20){return super.withCache(e),k.i.getChildren(k.i.getFullPath(this)).forEach(t=>{t.cache||=e}),this}withRetry(e=2){return super.withRetry(e),k.i.getChildren(k.i.getFullPath(this)).forEach(t=>{t.retry||=e}),this}withTimeout(e=f.duration,t=f.message){return super.withTimeout(e,t),k.i.getChildren(k.i.getFullPath(this)).forEach(n=>{n.timeout||={duration:e,message:t}}),this}before(e){return super.before(e),k.i.getChildren(k.i.getFullPath(this)).forEach(t=>{t.callbacks.before||(t.callbacks.before=e)}),this}after(e){return super.after(e),k.i.getChildren(k.i.getFullPath(this)).forEach(t=>{t.callbacks.after||(t.callbacks.after=e)}),this}onCall(e){return super.onCall(e),k.i.getChildren(k.i.getFullPath(this)).forEach(t=>{t.callbacks.call||(t.callbacks.call=e)}),this}},M=class e extends h{constructor(e,t,n={},r=`GET`){super(`route`,e,t,n),this.method=r,this.detectArguments()}static createRoute(t,n,r={},i){let a=new e(t,n,r,i);return k.i.registerRoute(a),a}static get(e,t,n={}){return this.createRoute(e,t,n,`GET`)}static post(e,t,n={}){return this.createRoute(e,t,n,`POST`)}static put(e,t,n={}){return this.createRoute(e,t,n,`PUT`)}static delete(e,t,n={}){return this.createRoute(e,t,n,`DELETE`)}static patch(e,t,n={}){return this.createRoute(e,t,n,`PATCH`)}static options(e,t,n={}){return this.createRoute(e,t,n,`OPTIONS`)}detectArguments(){let e=this.url.match(/\[([^\]]+)]/g);e&&e.forEach(e=>{let t=e.slice(1,-1);this.arguments.add(t)})}validate(e){return this.schema=e,this}};exports.Api=A,exports.Cache=_,exports.Group=j,exports.Hook=b,exports.InvalidPathError=d,exports.Klaim=x,exports.KlaimError=o,exports.MissingArgumentError=u,exports.RateLimitError=s,exports.Registry=k,exports.RetryExhaustedError=l,exports.Route=M,exports.TimeoutError=c;
package/dist/klaim.es.js CHANGED
@@ -465,10 +465,8 @@ var k = class e {
465
465
  t.callbacks.call || (t.callbacks.call = e);
466
466
  }), this;
467
467
  }
468
- }, M = /* @__PURE__ */ function(e) {
469
- return e.GET = "GET", e.POST = "POST", e.PUT = "PUT", e.DELETE = "DELETE", e.PATCH = "PATCH", e.OPTIONS = "OPTIONS", e;
470
- }({}), N = class e extends h {
471
- constructor(e, t, n = {}, r = M.GET) {
468
+ }, M = class e extends h {
469
+ constructor(e, t, n = {}, r = "GET") {
472
470
  super("route", e, t, n), this.method = r, this.detectArguments();
473
471
  }
474
472
  static createRoute(t, n, r = {}, i) {
@@ -476,22 +474,22 @@ var k = class e {
476
474
  return k.i.registerRoute(a), a;
477
475
  }
478
476
  static get(e, t, n = {}) {
479
- return this.createRoute(e, t, n, M.GET);
477
+ return this.createRoute(e, t, n, "GET");
480
478
  }
481
479
  static post(e, t, n = {}) {
482
- return this.createRoute(e, t, n, M.POST);
480
+ return this.createRoute(e, t, n, "POST");
483
481
  }
484
482
  static put(e, t, n = {}) {
485
- return this.createRoute(e, t, n, M.PUT);
483
+ return this.createRoute(e, t, n, "PUT");
486
484
  }
487
485
  static delete(e, t, n = {}) {
488
- return this.createRoute(e, t, n, M.DELETE);
486
+ return this.createRoute(e, t, n, "DELETE");
489
487
  }
490
488
  static patch(e, t, n = {}) {
491
- return this.createRoute(e, t, n, M.PATCH);
489
+ return this.createRoute(e, t, n, "PATCH");
492
490
  }
493
491
  static options(e, t, n = {}) {
494
- return this.createRoute(e, t, n, M.OPTIONS);
492
+ return this.createRoute(e, t, n, "OPTIONS");
495
493
  }
496
494
  detectArguments() {
497
495
  let e = this.url.match(/\[([^\]]+)]/g);
@@ -505,4 +503,4 @@ var k = class e {
505
503
  }
506
504
  };
507
505
  //#endregion
508
- export { A as Api, _ as Cache, j as Group, b as Hook, d as InvalidPathError, x as Klaim, o as KlaimError, u as MissingArgumentError, s as RateLimitError, k as Registry, l as RetryExhaustedError, N as Route, c as TimeoutError };
506
+ export { A as Api, _ as Cache, j as Group, b as Hook, d as InvalidPathError, x as Klaim, o as KlaimError, u as MissingArgumentError, s as RateLimitError, k as Registry, l as RetryExhaustedError, M as Route, c as TimeoutError };
package/dist/klaim.umd.js CHANGED
@@ -1 +1 @@
1
- (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.klaim={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e){return e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(`-`,``).replace(`_`,``)).replace(/(^\w)/,e=>e.toLowerCase())}function n(e){return e.trim().replace(/^\/|\/$/g,``)}var r={limit:5,duration:10},i=new Map;function a(e,t){let n=Date.now(),r=t.duration*1e3,a=i.get(e);a||(a={timestamps:[]},i.set(e,a));let o=a.timestamps.filter(e=>n-e<r);return o.length>=t.limit?!1:(o.push(n),a.timestamps=o,!0)}function o(e,t){let n=i.get(e);if(!n||n.timestamps.length<t.limit)return 0;let r=Date.now(),a=t.duration*1e3,o=[...n.timestamps].sort((e,t)=>e-t)[0]+a-r;return Math.max(0,o)}var s=class extends Error{constructor(e){super(e),this.name=`KlaimError`}},c=class extends s{retryAfterMs;constructor(e,t){super(e),this.name=`RateLimitError`,this.retryAfterMs=t}},l=class extends s{constructor(e){super(e),this.name=`TimeoutError`}},u=class extends s{attempts;cause;constructor(e,t,n){super(e),this.name=`RetryExhaustedError`,this.attempts=t,this.cause=n}},d=class extends s{argument;constructor(e){super(`Argument ${e} is missing`),this.name=`MissingArgumentError`,this.argument=e}},f=class extends s{constructor(e){super(`Invalid path: ${e}`),this.name=`InvalidPathError`}},p={duration:5,message:`Request timed out`};async function m(e,t){let{duration:n,message:r}=t;return Promise.race([e,new Promise((e,t)=>{let i=setTimeout(()=>{clearTimeout(i),t(new l(r))},n*1e3)})])}var h={page:1,pageParam:`page`,limit:10,limitParam:`limit`},g=class{type;name;url;headers;parent;method;arguments=new Set;schema;pagination;callbacks={before:null,after:null,call:null};cache=!1;retry=!1;rate=!1;timeout=!1;constructor(e,r,i,a={}){this.type=e,this.name=t(r),this.url=n(i),this.headers=a||{}}before(e){return this.callbacks.before=e,this}after(e){return this.callbacks.after=e,this}onCall(e){return this.callbacks.call=e,this}withCache(e=20){return this.cache=e,this}withRetry(e=2){return this.retry=e,this}withPagination(e={}){return this.pagination={...h,...e},this}withRate(e={}){return this.rate={...r,...e},this}withTimeout(e=p.duration,t=p.message){return this.timeout={duration:e,message:t},this}},_=1e3,v=class e{static _instance;cache;maxSize;constructor(e=_){this.cache=new Map,this.maxSize=e}static get i(){return e._instance||=new e,e._instance}set(e,t,n=0){if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=this.maxSize){let e=this.cache.keys().next().value;e!==void 0&&this.cache.delete(e)}let r=n>0?Date.now()+n:1/0;this.cache.set(e,{data:t,expiry:r})}has(e){let t=this.cache.get(e);return t?Date.now()>t.expiry?(this.cache.delete(e),!1):!0:!1}get(e){if(this.has(e)){let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t.data}return null}clear(){this.cache.clear()}get size(){return this.cache.size}};function y(e){let t=16777619,n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,t)>>>0;let r=(n>>>0).toString(16).padStart(8,`0`),i=0;for(;r.length<32;)n^=r.charCodeAt(i%r.length),n=Math.imul(n,t)>>>0,r+=(n>>>0).toString(16).padStart(8,`0`),i++;return r.substring(0,32)}async function b(e,t,n){let r=y(`${e.toString()}${JSON.stringify(t)}`);if(v.i.has(r))return v.i.get(r);let i=await(await fetch(e,t)).json();return v.i.set(r,i,n),i}var x=class{static _callbacks=new Map;static subscribe(e,t){this._callbacks.set(e,t)}static run(e){let t=this._callbacks.get(e);t&&t()}static unsubscribe(e){this._callbacks.delete(e)}static unsubscribeAll(){this._callbacks.clear()}},S={};function C(e,t){return async(...n)=>{if(t.pagination){let[r=0,i={},a={}]=n;return w(e,t,r,i,a)}let[r={},i={}]=n;return w(e,t,void 0,r,i)}}async function w(e,t,n,r={},i={}){let a=e.split(`.`),o;for(let e=0;e<a.length;e++){let t=a[e];if(o=A.i.getApi(t),o)break}if(!t||!o||t.type!==`route`||o.type!==`api`)throw new f(`${e}.${t.name}`);let s=D(`${o.url}/${t.url}`,t,r);if(t.pagination&&n!==void 0){let{pageParam:e=`page`,limit:r=10,limitParam:i=`limit`}=t.pagination,a=new URLSearchParams;a.append(e,String(n)),a.append(i,String(r));let o=s.includes(`?`)?`&`:`?`;s=`${s}${o}${a.toString()}`}let c={};i&&t.method!==`GET`&&(c.body=JSON.stringify(i)),c.headers={"Content-Type":`application/json`,...o.headers,...t.headers},c.method=t.method;let{beforeRoute:l,beforeApi:u,beforeUrl:d,beforeConfig:p}=O({route:t,api:o,url:s,config:c});s=d,c=p,A.updateElement(u),A.updateElement(l);let m=await E(o,t,s,c);t.schema&&(m=await t.schema.validate(m));let{afterRoute:h,afterApi:g,afterData:_}=k({route:t,api:o,response:m,data:m});return A.updateElement(g),A.updateElement(h),x.run(`${o.name}.${t.name}`),_}async function T(e,t,n,r){return e?await b(t,n,r.cache||void 0):await(await fetch(t,n)).json()}async function E(e,t,n,r){let i=e.cache||t.cache,s=t.retry||e.retry||0,l=t.timeout||e.timeout;if(t.rate){let n=`ROUTE:${e.name}:${t.name}`;if(!a(n,t.rate)){let r=o(n,t.rate);throw new c(`Rate limit exceeded for ${e.name}.${t.name}. Try again in ${Math.ceil(r/1e3)} seconds.`,r)}}else if(e.rate){let t=`API:${e.name}`;if(!a(t,e.rate)){let n=o(t,e.rate);throw new c(`Rate limit exceeded for ${e.name} API. Try again in ${Math.ceil(n/1e3)} seconds.`,n)}}let d,f=!1,p=0;for(;p<=s&&!f;)try{t.callbacks?.call?t.callbacks.call({}):e.callbacks?.call&&e.callbacks.call({});let a=T(!!i,n,r,e);d=l?await m(a,l):await a,f=!0}catch(e){if(p++,p>s){if(s===0&&e instanceof Error)throw e;let t=e instanceof Error?e:void 0;throw new u(`Failed to fetch ${n} after ${s+1} attempts`,p,t)}let t=200*2**(p-1)+Math.random()*100;await new Promise(e=>setTimeout(e,t))}return d}function D(e,t,n){let r=e;return t.arguments.forEach(e=>{let t=n[e];if(t===void 0)throw new d(e);r=r.replace(`[${e}]`,encodeURIComponent(String(t)))}),r}function O({route:e,api:t,url:n,config:r}){let i=e.callbacks.before?.({route:e,api:t,url:n,config:r});return{beforeRoute:i?.route||e,beforeApi:i?.api||t,beforeUrl:i?.url||n,beforeConfig:i?.config||r}}function k({route:e,api:t,response:n,data:r}){let i=e.callbacks.after?.({route:e,api:t,response:n,data:r});return{afterRoute:i?.route||e,afterApi:i?.api||t,afterResponse:i?.response||n,afterData:i?.data||r}}var A=class e{static _instance;_elements=new Map;_currentParent=null;constructor(){}static get i(){return e._instance||=new e,e._instance}registerElement(e){let t=this._currentParent;t&&(e.parent=this.getFullPath(t));let n=this.getElementKey(e);if(this._elements.set(n,e),e.type===`api`||e.type===`group`){let n=S;if(t){let e=this.getFullPath(t).split(`.`);for(let t of e)n[t]||(n[t]={}),n=n[t]}n[e.name]||(n[e.name]={})}}getCurrentParent(){return this._currentParent}setCurrentParent(e){let t=this._elements.get(e);if(!t||t.type!==`api`&&t.type!==`group`)throw Error(`Element ${e} not found or not a valid parent type`);this._currentParent=t}clearCurrentParent(){this._currentParent=null}registerRoute(e){if(!this._currentParent)throw Error(`No current parent set, use Route only inside Api or Group create callback`);e.parent=this.getFullPath(this._currentParent);let t=this.getElementKey(e);this._elements.set(t,e),this.addToKlaimRoute(e)}addToKlaimRoute(e){if(!e.parent)return;let t=S,n=e.parent.split(`.`);for(let e of n)t[e]||(t[e]={}),t=t[e];t[e.name]=C(e.parent,e)}getElementKey(e){return e?e.parent?`${e.parent}.${e.name}`:e.name:``}getFullPath(e){if(!e)return``;if(!e.parent)return e.name;let t=[e.name],n=e;for(;n.parent;){let e=this._elements.get(n.parent);if(!e)break;t.unshift(e.name),n=e}return t.join(`.`)}getRoute(e,t){return this._elements.get(`${e}.${t}`)}getChildren(e){let t=[];return this._elements.forEach(n=>{n.parent===e&&t.push(n)}),t}static updateElement(t){return e.i._elements.get(e.i.getElementKey(t))||t}getApi(e){let t=this._elements.get(e);if(!t){for(let[t,n]of this._elements.entries())if(n.type===`api`&&t.endsWith(`.${e}`))return n;return}return t.type===`api`?t:this.findApi(t)}findApi(e){if(!e||!e.parent)return;let t=e.parent.split(`.`);for(let e=t.length;e>=0;e--){let n=t.slice(0,e).join(`.`),r=this._elements.get(n);if(r?.type===`api`)return r}}reset(){this._elements.clear(),this._currentParent=null;for(let e of Object.keys(S))delete S[e]}},j=class e extends g{static create(n,r,i,a={}){let o=t(n),s=new e(o,r,a),c=A.i.getCurrentParent();A.i.registerElement(s);let l=c?A.i.getFullPath(c):``,u=l?`${l}.${o}`:o;return A.i.setCurrentParent(u),i(),c?A.i.setCurrentParent(A.i.getFullPath(c)):A.i.clearCurrentParent(),s}constructor(e,t,n={}){super(`api`,e,t,n)}},M=class e extends g{static create(n,r){let i=t(n),a=A.i.getCurrentParent(),o=a?A.i.getFullPath(a):``,s=o?`${o}.${i}`:i,c=new e(i,``);A.i.registerElement(c);let l=A.i.getCurrentParent();return A.i.setCurrentParent(s),r(),l?A.i.setCurrentParent(A.i.getFullPath(l)):A.i.clearCurrentParent(),c}constructor(e,t,n={}){super(`group`,e,t,n)}withCache(e=20){return super.withCache(e),A.i.getChildren(A.i.getFullPath(this)).forEach(t=>{t.cache||=e}),this}withRetry(e=2){return super.withRetry(e),A.i.getChildren(A.i.getFullPath(this)).forEach(t=>{t.retry||=e}),this}withTimeout(e=p.duration,t=p.message){return super.withTimeout(e,t),A.i.getChildren(A.i.getFullPath(this)).forEach(n=>{n.timeout||={duration:e,message:t}}),this}before(e){return super.before(e),A.i.getChildren(A.i.getFullPath(this)).forEach(t=>{t.callbacks.before||(t.callbacks.before=e)}),this}after(e){return super.after(e),A.i.getChildren(A.i.getFullPath(this)).forEach(t=>{t.callbacks.after||(t.callbacks.after=e)}),this}onCall(e){return super.onCall(e),A.i.getChildren(A.i.getFullPath(this)).forEach(t=>{t.callbacks.call||(t.callbacks.call=e)}),this}},N=function(e){return e.GET=`GET`,e.POST=`POST`,e.PUT=`PUT`,e.DELETE=`DELETE`,e.PATCH=`PATCH`,e.OPTIONS=`OPTIONS`,e}({}),P=class e extends g{constructor(e,t,n={},r=N.GET){super(`route`,e,t,n),this.method=r,this.detectArguments()}static createRoute(t,n,r={},i){let a=new e(t,n,r,i);return A.i.registerRoute(a),a}static get(e,t,n={}){return this.createRoute(e,t,n,N.GET)}static post(e,t,n={}){return this.createRoute(e,t,n,N.POST)}static put(e,t,n={}){return this.createRoute(e,t,n,N.PUT)}static delete(e,t,n={}){return this.createRoute(e,t,n,N.DELETE)}static patch(e,t,n={}){return this.createRoute(e,t,n,N.PATCH)}static options(e,t,n={}){return this.createRoute(e,t,n,N.OPTIONS)}detectArguments(){let e=this.url.match(/\[([^\]]+)]/g);e&&e.forEach(e=>{let t=e.slice(1,-1);this.arguments.add(t)})}validate(e){return this.schema=e,this}};e.Api=j,e.Cache=v,e.Group=M,e.Hook=x,e.InvalidPathError=f,e.Klaim=S,e.KlaimError=s,e.MissingArgumentError=d,e.RateLimitError=c,e.Registry=A,e.RetryExhaustedError=u,e.Route=P,e.TimeoutError=l});
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.klaim={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e){return e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(`-`,``).replace(`_`,``)).replace(/(^\w)/,e=>e.toLowerCase())}function n(e){return e.trim().replace(/^\/|\/$/g,``)}var r={limit:5,duration:10},i=new Map;function a(e,t){let n=Date.now(),r=t.duration*1e3,a=i.get(e);a||(a={timestamps:[]},i.set(e,a));let o=a.timestamps.filter(e=>n-e<r);return o.length>=t.limit?!1:(o.push(n),a.timestamps=o,!0)}function o(e,t){let n=i.get(e);if(!n||n.timestamps.length<t.limit)return 0;let r=Date.now(),a=t.duration*1e3,o=[...n.timestamps].sort((e,t)=>e-t)[0]+a-r;return Math.max(0,o)}var s=class extends Error{constructor(e){super(e),this.name=`KlaimError`}},c=class extends s{retryAfterMs;constructor(e,t){super(e),this.name=`RateLimitError`,this.retryAfterMs=t}},l=class extends s{constructor(e){super(e),this.name=`TimeoutError`}},u=class extends s{attempts;cause;constructor(e,t,n){super(e),this.name=`RetryExhaustedError`,this.attempts=t,this.cause=n}},d=class extends s{argument;constructor(e){super(`Argument ${e} is missing`),this.name=`MissingArgumentError`,this.argument=e}},f=class extends s{constructor(e){super(`Invalid path: ${e}`),this.name=`InvalidPathError`}},p={duration:5,message:`Request timed out`};async function m(e,t){let{duration:n,message:r}=t;return Promise.race([e,new Promise((e,t)=>{let i=setTimeout(()=>{clearTimeout(i),t(new l(r))},n*1e3)})])}var h={page:1,pageParam:`page`,limit:10,limitParam:`limit`},g=class{type;name;url;headers;parent;method;arguments=new Set;schema;pagination;callbacks={before:null,after:null,call:null};cache=!1;retry=!1;rate=!1;timeout=!1;constructor(e,r,i,a={}){this.type=e,this.name=t(r),this.url=n(i),this.headers=a||{}}before(e){return this.callbacks.before=e,this}after(e){return this.callbacks.after=e,this}onCall(e){return this.callbacks.call=e,this}withCache(e=20){return this.cache=e,this}withRetry(e=2){return this.retry=e,this}withPagination(e={}){return this.pagination={...h,...e},this}withRate(e={}){return this.rate={...r,...e},this}withTimeout(e=p.duration,t=p.message){return this.timeout={duration:e,message:t},this}},_=1e3,v=class e{static _instance;cache;maxSize;constructor(e=_){this.cache=new Map,this.maxSize=e}static get i(){return e._instance||=new e,e._instance}set(e,t,n=0){if(this.cache.has(e)&&this.cache.delete(e),this.cache.size>=this.maxSize){let e=this.cache.keys().next().value;e!==void 0&&this.cache.delete(e)}let r=n>0?Date.now()+n:1/0;this.cache.set(e,{data:t,expiry:r})}has(e){let t=this.cache.get(e);return t?Date.now()>t.expiry?(this.cache.delete(e),!1):!0:!1}get(e){if(this.has(e)){let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t.data}return null}clear(){this.cache.clear()}get size(){return this.cache.size}};function y(e){let t=16777619,n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,t)>>>0;let r=(n>>>0).toString(16).padStart(8,`0`),i=0;for(;r.length<32;)n^=r.charCodeAt(i%r.length),n=Math.imul(n,t)>>>0,r+=(n>>>0).toString(16).padStart(8,`0`),i++;return r.substring(0,32)}async function b(e,t,n){let r=y(`${e.toString()}${JSON.stringify(t)}`);if(v.i.has(r))return v.i.get(r);let i=await(await fetch(e,t)).json();return v.i.set(r,i,n),i}var x=class{static _callbacks=new Map;static subscribe(e,t){this._callbacks.set(e,t)}static run(e){let t=this._callbacks.get(e);t&&t()}static unsubscribe(e){this._callbacks.delete(e)}static unsubscribeAll(){this._callbacks.clear()}},S={};function C(e,t){return async(...n)=>{if(t.pagination){let[r=0,i={},a={}]=n;return w(e,t,r,i,a)}let[r={},i={}]=n;return w(e,t,void 0,r,i)}}async function w(e,t,n,r={},i={}){let a=e.split(`.`),o;for(let e=0;e<a.length;e++){let t=a[e];if(o=A.i.getApi(t),o)break}if(!t||!o||t.type!==`route`||o.type!==`api`)throw new f(`${e}.${t.name}`);let s=D(`${o.url}/${t.url}`,t,r);if(t.pagination&&n!==void 0){let{pageParam:e=`page`,limit:r=10,limitParam:i=`limit`}=t.pagination,a=new URLSearchParams;a.append(e,String(n)),a.append(i,String(r));let o=s.includes(`?`)?`&`:`?`;s=`${s}${o}${a.toString()}`}let c={};i&&t.method!==`GET`&&(c.body=JSON.stringify(i)),c.headers={"Content-Type":`application/json`,...o.headers,...t.headers},c.method=t.method;let{beforeRoute:l,beforeApi:u,beforeUrl:d,beforeConfig:p}=O({route:t,api:o,url:s,config:c});s=d,c=p,A.updateElement(u),A.updateElement(l);let m=await E(o,t,s,c);t.schema&&(m=await t.schema.validate(m));let{afterRoute:h,afterApi:g,afterData:_}=k({route:t,api:o,response:m,data:m});return A.updateElement(g),A.updateElement(h),x.run(`${o.name}.${t.name}`),_}async function T(e,t,n,r){return e?await b(t,n,r.cache||void 0):await(await fetch(t,n)).json()}async function E(e,t,n,r){let i=e.cache||t.cache,s=t.retry||e.retry||0,l=t.timeout||e.timeout;if(t.rate){let n=`ROUTE:${e.name}:${t.name}`;if(!a(n,t.rate)){let r=o(n,t.rate);throw new c(`Rate limit exceeded for ${e.name}.${t.name}. Try again in ${Math.ceil(r/1e3)} seconds.`,r)}}else if(e.rate){let t=`API:${e.name}`;if(!a(t,e.rate)){let n=o(t,e.rate);throw new c(`Rate limit exceeded for ${e.name} API. Try again in ${Math.ceil(n/1e3)} seconds.`,n)}}let d,f=!1,p=0;for(;p<=s&&!f;)try{t.callbacks?.call?t.callbacks.call({}):e.callbacks?.call&&e.callbacks.call({});let a=T(!!i,n,r,e);d=l?await m(a,l):await a,f=!0}catch(e){if(p++,p>s){if(s===0&&e instanceof Error)throw e;let t=e instanceof Error?e:void 0;throw new u(`Failed to fetch ${n} after ${s+1} attempts`,p,t)}let t=200*2**(p-1)+Math.random()*100;await new Promise(e=>setTimeout(e,t))}return d}function D(e,t,n){let r=e;return t.arguments.forEach(e=>{let t=n[e];if(t===void 0)throw new d(e);r=r.replace(`[${e}]`,encodeURIComponent(String(t)))}),r}function O({route:e,api:t,url:n,config:r}){let i=e.callbacks.before?.({route:e,api:t,url:n,config:r});return{beforeRoute:i?.route||e,beforeApi:i?.api||t,beforeUrl:i?.url||n,beforeConfig:i?.config||r}}function k({route:e,api:t,response:n,data:r}){let i=e.callbacks.after?.({route:e,api:t,response:n,data:r});return{afterRoute:i?.route||e,afterApi:i?.api||t,afterResponse:i?.response||n,afterData:i?.data||r}}var A=class e{static _instance;_elements=new Map;_currentParent=null;constructor(){}static get i(){return e._instance||=new e,e._instance}registerElement(e){let t=this._currentParent;t&&(e.parent=this.getFullPath(t));let n=this.getElementKey(e);if(this._elements.set(n,e),e.type===`api`||e.type===`group`){let n=S;if(t){let e=this.getFullPath(t).split(`.`);for(let t of e)n[t]||(n[t]={}),n=n[t]}n[e.name]||(n[e.name]={})}}getCurrentParent(){return this._currentParent}setCurrentParent(e){let t=this._elements.get(e);if(!t||t.type!==`api`&&t.type!==`group`)throw Error(`Element ${e} not found or not a valid parent type`);this._currentParent=t}clearCurrentParent(){this._currentParent=null}registerRoute(e){if(!this._currentParent)throw Error(`No current parent set, use Route only inside Api or Group create callback`);e.parent=this.getFullPath(this._currentParent);let t=this.getElementKey(e);this._elements.set(t,e),this.addToKlaimRoute(e)}addToKlaimRoute(e){if(!e.parent)return;let t=S,n=e.parent.split(`.`);for(let e of n)t[e]||(t[e]={}),t=t[e];t[e.name]=C(e.parent,e)}getElementKey(e){return e?e.parent?`${e.parent}.${e.name}`:e.name:``}getFullPath(e){if(!e)return``;if(!e.parent)return e.name;let t=[e.name],n=e;for(;n.parent;){let e=this._elements.get(n.parent);if(!e)break;t.unshift(e.name),n=e}return t.join(`.`)}getRoute(e,t){return this._elements.get(`${e}.${t}`)}getChildren(e){let t=[];return this._elements.forEach(n=>{n.parent===e&&t.push(n)}),t}static updateElement(t){return e.i._elements.get(e.i.getElementKey(t))||t}getApi(e){let t=this._elements.get(e);if(!t){for(let[t,n]of this._elements.entries())if(n.type===`api`&&t.endsWith(`.${e}`))return n;return}return t.type===`api`?t:this.findApi(t)}findApi(e){if(!e||!e.parent)return;let t=e.parent.split(`.`);for(let e=t.length;e>=0;e--){let n=t.slice(0,e).join(`.`),r=this._elements.get(n);if(r?.type===`api`)return r}}reset(){this._elements.clear(),this._currentParent=null;for(let e of Object.keys(S))delete S[e]}},j=class e extends g{static create(n,r,i,a={}){let o=t(n),s=new e(o,r,a),c=A.i.getCurrentParent();A.i.registerElement(s);let l=c?A.i.getFullPath(c):``,u=l?`${l}.${o}`:o;return A.i.setCurrentParent(u),i(),c?A.i.setCurrentParent(A.i.getFullPath(c)):A.i.clearCurrentParent(),s}constructor(e,t,n={}){super(`api`,e,t,n)}},M=class e extends g{static create(n,r){let i=t(n),a=A.i.getCurrentParent(),o=a?A.i.getFullPath(a):``,s=o?`${o}.${i}`:i,c=new e(i,``);A.i.registerElement(c);let l=A.i.getCurrentParent();return A.i.setCurrentParent(s),r(),l?A.i.setCurrentParent(A.i.getFullPath(l)):A.i.clearCurrentParent(),c}constructor(e,t,n={}){super(`group`,e,t,n)}withCache(e=20){return super.withCache(e),A.i.getChildren(A.i.getFullPath(this)).forEach(t=>{t.cache||=e}),this}withRetry(e=2){return super.withRetry(e),A.i.getChildren(A.i.getFullPath(this)).forEach(t=>{t.retry||=e}),this}withTimeout(e=p.duration,t=p.message){return super.withTimeout(e,t),A.i.getChildren(A.i.getFullPath(this)).forEach(n=>{n.timeout||={duration:e,message:t}}),this}before(e){return super.before(e),A.i.getChildren(A.i.getFullPath(this)).forEach(t=>{t.callbacks.before||(t.callbacks.before=e)}),this}after(e){return super.after(e),A.i.getChildren(A.i.getFullPath(this)).forEach(t=>{t.callbacks.after||(t.callbacks.after=e)}),this}onCall(e){return super.onCall(e),A.i.getChildren(A.i.getFullPath(this)).forEach(t=>{t.callbacks.call||(t.callbacks.call=e)}),this}},N=class e extends g{constructor(e,t,n={},r=`GET`){super(`route`,e,t,n),this.method=r,this.detectArguments()}static createRoute(t,n,r={},i){let a=new e(t,n,r,i);return A.i.registerRoute(a),a}static get(e,t,n={}){return this.createRoute(e,t,n,`GET`)}static post(e,t,n={}){return this.createRoute(e,t,n,`POST`)}static put(e,t,n={}){return this.createRoute(e,t,n,`PUT`)}static delete(e,t,n={}){return this.createRoute(e,t,n,`DELETE`)}static patch(e,t,n={}){return this.createRoute(e,t,n,`PATCH`)}static options(e,t,n={}){return this.createRoute(e,t,n,`OPTIONS`)}detectArguments(){let e=this.url.match(/\[([^\]]+)]/g);e&&e.forEach(e=>{let t=e.slice(1,-1);this.arguments.add(t)})}validate(e){return this.schema=e,this}};e.Api=j,e.Cache=v,e.Group=M,e.Hook=x,e.InvalidPathError=f,e.Klaim=S,e.KlaimError=s,e.MissingArgumentError=d,e.RateLimitError=c,e.Registry=A,e.RetryExhaustedError=u,e.Route=N,e.TimeoutError=l});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "klaim",
3
- "version": "1.12.43",
3
+ "version": "1.12.44",
4
4
  "author": "antharuu",
5
5
  "repository": {
6
6
  "type": "git",
@@ -12,7 +12,7 @@
12
12
  "@eslint/js": "10.0.1",
13
13
  "@stylistic/eslint-plugin": "5.10.0",
14
14
  "@types/bun": "^1.3.14",
15
- "@types/node": "^25.7.0",
15
+ "@types/node": "^25.8.0",
16
16
  "@vitest/coverage-v8": "^4.1.6",
17
17
  "@vitest/ui": "^4.1.6",
18
18
  "dotenv-cli": "^11.0.0",
@@ -23,7 +23,7 @@
23
23
  "release-it": "^19.2.4",
24
24
  "typescript": "6.0.3",
25
25
  "typescript-eslint": "8.59.3",
26
- "vite": "^8.0.12",
26
+ "vite": "^8.0.13",
27
27
  "vite-plugin-dts": "^4.5.4",
28
28
  "vitest": "^4.1.6",
29
29
  "yup": "^1.7.1"