@defjs/core 0.2.0 → 0.3.0

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/index.d.ts CHANGED
@@ -63,6 +63,17 @@ export declare function field<T>(defaultValue: T): Field<T>;
63
63
  export declare function doValid<T>(validators: (ValidatorFn<T> | AsyncValidatorFn<T>)[], value: T): Promise<void>;
64
64
  export declare function isField(value: unknown): value is Field;
65
65
  export declare function isFieldGroup(value: unknown): value is Record<PropertyKey, Field>;
66
+ export declare const ERR_ABORTED: Error;
67
+ export declare const ERR_TIMEOUT: Error;
68
+ export declare const ERR_NETWORK: Error;
69
+ export declare const ERR_NOT_FOUND_HANDLER: Error;
70
+ export declare const ERR_OBSERVE: Error;
71
+ export declare const ERR_NOT_SET_ALIAS: Error;
72
+ export declare const ERR_UNSUPPORTED_FIELD_TYPE: Error;
73
+ export declare const ERR_INVALID_CLIENT: Error;
74
+ export declare const ERR_NOT_FOUND_GLOBAL_CLIENT: Error;
75
+ export declare const ERR_INVALID_HTTP_CONTEXT_TOKEN: Error;
76
+ export declare const ERR_UNKNOWN: Error;
66
77
  export type HttpResponseBody = string | ArrayBuffer | Blob | object | null;
67
78
  export type HttpResponse<R> = {
68
79
  readonly url: string;
@@ -70,6 +81,7 @@ export type HttpResponse<R> = {
70
81
  readonly statusText: string;
71
82
  readonly headers: Headers;
72
83
  readonly body: R | null;
84
+ readonly error?: Error | string | unknown;
73
85
  };
74
86
  export type MakeResponseOptions<R> = {
75
87
  status?: number;
@@ -77,6 +89,7 @@ export type MakeResponseOptions<R> = {
77
89
  url?: string;
78
90
  headers?: Headers;
79
91
  body?: R | null;
92
+ error?: Error | string | unknown;
80
93
  };
81
94
  export type InterceptorFn = (req: HttpRequest, next: HttpHandler) => Promise<HttpResponse<unknown>>;
82
95
  export type BasicCredential = {
@@ -181,31 +194,5 @@ export declare function getGlobalClient(): Client;
181
194
  export declare function setGlobalClient(client: Client): void;
182
195
  export declare function restGlobalClient(): void;
183
196
  export declare function createGlobalClient(options: ClientOptions): void;
184
- export declare const ERR_ABORTED: Error;
185
- export declare const ERR_TIMEOUT: Error;
186
- export declare const ERR_NETWORK: Error;
187
- export declare const ERR_NOT_FOUND_HANDLER: Error;
188
- export declare const ERR_OBSERVE: Error;
189
- export declare const ERR_NOT_SET_ALIAS: Error;
190
- export declare const ERR_UNSUPPORTED_FIELD_TYPE: Error;
191
- export declare const ERR_INVALID_CLIENT: Error;
192
- export declare const ERR_NOT_FOUND_GLOBAL_CLIENT: Error;
193
- export declare const ERR_INVALID_HTTP_CONTEXT_TOKEN: Error;
194
- export declare const ERR_UNKNOWN: Error;
195
- export declare class HttpErrorResponse extends Error {
196
- readonly status: number;
197
- readonly statusText: string;
198
- readonly url: string;
199
- readonly headers: Headers;
200
- readonly body: unknown;
201
- constructor(init?: {
202
- error?: Error | string | unknown;
203
- status?: number;
204
- statusText?: string;
205
- url?: string;
206
- headers?: Headers;
207
- body?: unknown;
208
- });
209
- }
210
197
 
211
198
  export {};
package/index.js CHANGED
@@ -1,48 +1,3 @@
1
- // src/error.ts
2
- var ERR_ABORTED = new Error("ERR_ABORTED");
3
- var ERR_TIMEOUT = new Error("ERR_TIMEOUT");
4
- var ERR_NETWORK = new Error("ERR_NETWORK");
5
- var ERR_NOT_FOUND_HANDLER = new Error("ERR_NOT_FOUND_HANDLER");
6
- var ERR_OBSERVE = new Error("ERR_OBSERVE");
7
- var ERR_NOT_SET_ALIAS = new Error("ERR_NOT_SET_ALIAS");
8
- var ERR_UNSUPPORTED_FIELD_TYPE = new Error("ERR_UNSUPPORTED_FIELD_TYPE");
9
- var ERR_INVALID_CLIENT = new Error("ERR_INVALID_CLIENT");
10
- var ERR_NOT_FOUND_GLOBAL_CLIENT = new Error("ERR_NOT_FOUND_GLOBAL_CLIENT");
11
- var ERR_INVALID_HTTP_CONTEXT_TOKEN = new Error("ERR_INVALID_HTTP_CONTEXT_TOKEN");
12
- var ERR_UNKNOWN = new Error("ERR_UNKNOWN");
13
-
14
- class HttpErrorResponse extends Error {
15
- status;
16
- statusText;
17
- url;
18
- headers;
19
- body;
20
- constructor(init) {
21
- const status = init?.status ?? 0;
22
- const statusText = init?.statusText ?? "";
23
- const ok = status >= 200 && status < 300;
24
- const headers = init?.headers ?? new Headers;
25
- const url = init?.url ?? "";
26
- const body = init?.body ?? null;
27
- let message;
28
- if (ok) {
29
- message = `Http failure during parsing for ${url}`;
30
- } else {
31
- message = `Http failure response for ${url || "(unknown url)"}: ${status}`;
32
- if (statusText) {
33
- message += ` - ${statusText}`;
34
- }
35
- }
36
- super(message, { cause: init?.error });
37
- super.name = "HttpErrorResponse";
38
- this.statusText = statusText;
39
- this.url = url;
40
- this.headers = headers;
41
- this.status = status;
42
- this.body = body;
43
- }
44
- }
45
-
46
1
  // src/handler/util.ts
47
2
  function __getContentLength(headers) {
48
3
  const value = headers.get("Content-Length");
@@ -90,6 +45,43 @@ function __concatChunks(chunks, totalLength) {
90
45
  return chunksAll;
91
46
  }
92
47
 
48
+ // src/response.ts
49
+ function __makeResponse(options) {
50
+ const status = options?.status ?? 0;
51
+ const ok = status >= 200 && status < 300;
52
+ const statusText = options?.statusText ?? "";
53
+ const url = options?.url ?? "";
54
+ const headers = options?.headers ?? new Headers;
55
+ const body = options?.body ?? null;
56
+ let error = options?.error;
57
+ if (!error && !ok) {
58
+ let message = `Http failure response for ${url || "(unknown url)"}: ${status}`;
59
+ if (statusText) {
60
+ message += ` - ${statusText}`;
61
+ }
62
+ error = new Error(message);
63
+ }
64
+ return {
65
+ status,
66
+ statusText,
67
+ url,
68
+ headers,
69
+ body,
70
+ error
71
+ };
72
+ }
73
+ var ERR_ABORTED = new Error("ERR_ABORTED");
74
+ var ERR_TIMEOUT = new Error("ERR_TIMEOUT");
75
+ var ERR_NETWORK = new Error("ERR_NETWORK");
76
+ var ERR_NOT_FOUND_HANDLER = new Error("ERR_NOT_FOUND_HANDLER");
77
+ var ERR_OBSERVE = new Error("ERR_OBSERVE");
78
+ var ERR_NOT_SET_ALIAS = new Error("ERR_NOT_SET_ALIAS");
79
+ var ERR_UNSUPPORTED_FIELD_TYPE = new Error("ERR_UNSUPPORTED_FIELD_TYPE");
80
+ var ERR_INVALID_CLIENT = new Error("ERR_INVALID_CLIENT");
81
+ var ERR_NOT_FOUND_GLOBAL_CLIENT = new Error("ERR_NOT_FOUND_GLOBAL_CLIENT");
82
+ var ERR_INVALID_HTTP_CONTEXT_TOKEN = new Error("ERR_INVALID_HTTP_CONTEXT_TOKEN");
83
+ var ERR_UNKNOWN = new Error("ERR_UNKNOWN");
84
+
93
85
  // src/context.ts
94
86
  function makeHttpContextToken(defaultValue) {
95
87
  Object.defineProperty(defaultValue, HTTP_CONTEXT_TOKEN, { value: defaultValue });
@@ -230,22 +222,6 @@ function makeInterceptorChain(interceptors) {
230
222
  }, (req, fn) => fn(req));
231
223
  }
232
224
 
233
- // src/response.ts
234
- function __makeResponse(options) {
235
- const status = options?.status ?? 0;
236
- const statusText = options?.statusText ?? "";
237
- const url = options?.url ?? "";
238
- const headers = options?.headers ?? new Headers;
239
- const body = options?.body ?? null;
240
- return {
241
- status,
242
- statusText,
243
- url,
244
- headers,
245
- body
246
- };
247
- }
248
-
249
225
  // src/request.ts
250
226
  function __serializeBody(body) {
251
227
  switch (true) {
@@ -356,49 +332,49 @@ function defineRequest(...args) {
356
332
  downloadProgress = fn2;
357
333
  };
358
334
  const doRequest = async (...args2) => {
359
- let input;
360
- if (requiredInput && args2.length === 1) {
361
- input = args2[0];
362
- }
363
- if (requiredInput && !input) {
364
- throw new Error(`Because the request has input, the argument must be the input value`);
365
- }
366
- if (validators.length > 0) {
367
- for (const fn2 of validators) {
368
- fn2(input);
335
+ try {
336
+ let input;
337
+ if (requiredInput && args2.length === 1) {
338
+ input = args2[0];
369
339
  }
370
- }
371
- const req = {
372
- host: clientOptions?.host,
373
- method,
374
- endpoint,
375
- queryParams: new URLSearchParams,
376
- headers: new Headers,
377
- body: undefined,
378
- withCredentials,
379
- responseType,
380
- context: context2 || makeHttpContext(),
381
- uploadProgress,
382
- downloadProgress,
383
- timeout,
384
- abort: AbortSignal.any(abortSignal)
385
- };
386
- if (requiredInput && field3) {
387
- await __fillRequestFromField(req, field3, input);
388
- }
389
- const chain = makeInterceptorChain([...clientOptions.interceptors, ...interceptors]);
390
- let res = await chain(req, handler2);
391
- if (typeof transformResponse === "function") {
392
- try {
340
+ if (requiredInput && !input) {
341
+ throw new Error(`Because the request has input, the argument must be the input value`);
342
+ }
343
+ if (validators.length > 0) {
344
+ for (const fn2 of validators) {
345
+ fn2(input);
346
+ }
347
+ }
348
+ const req = {
349
+ host: clientOptions?.host,
350
+ method,
351
+ endpoint,
352
+ queryParams: new URLSearchParams,
353
+ headers: new Headers,
354
+ body: undefined,
355
+ withCredentials,
356
+ responseType,
357
+ context: context2 || makeHttpContext(),
358
+ uploadProgress,
359
+ downloadProgress,
360
+ timeout,
361
+ abort: AbortSignal.any(abortSignal)
362
+ };
363
+ if (requiredInput && field3) {
364
+ await __fillRequestFromField(req, field3, input);
365
+ }
366
+ const chain = makeInterceptorChain([...clientOptions.interceptors, ...interceptors]);
367
+ let res = await chain(req, handler2);
368
+ if (typeof transformResponse === "function") {
393
369
  res = __makeResponse({
394
370
  ...res,
395
371
  body: transformResponse(res)
396
372
  });
397
- } catch (error3) {
398
- throw new HttpErrorResponse({ error: error3 });
399
373
  }
374
+ return res;
375
+ } catch (error) {
376
+ return __makeResponse({ error });
400
377
  }
401
- return res;
402
378
  };
403
379
  return {
404
380
  doRequest,
@@ -653,27 +629,27 @@ async function fetchHandler(httpRequest) {
653
629
  const downloadProgress = httpRequest.downloadProgress;
654
630
  const request2 = __createRequest(httpRequest);
655
631
  const abortSignal = httpRequest.abort;
656
- let response3;
632
+ let response4;
657
633
  try {
658
- response3 = await globalThis.fetch(request2);
659
- } catch (error4) {
634
+ response4 = await globalThis.fetch(request2);
635
+ } catch (error) {
660
636
  if (abortSignal?.aborted && abortSignal.reason instanceof Error) {
661
637
  switch (true) {
662
638
  case abortSignal.reason.name === "AbortError":
663
- throw new HttpErrorResponse({ error: ERR_ABORTED });
639
+ return __makeResponse({ error: ERR_ABORTED });
664
640
  case abortSignal.reason.name === "TimeoutError":
665
- throw new HttpErrorResponse({ error: ERR_TIMEOUT });
641
+ return __makeResponse({ error: ERR_TIMEOUT });
666
642
  }
667
643
  }
668
- throw new HttpErrorResponse({ error: error4 });
644
+ return __makeResponse({ error });
669
645
  }
670
- const { ok, headers, status, statusText, url } = response3;
646
+ const { headers, status, statusText, url } = response4;
671
647
  const contentLength = __getContentLength(headers);
672
648
  const contentType = __getContentType(headers);
673
649
  let body = null;
674
- if (response3.body) {
650
+ if (response4.body) {
675
651
  const chunks = [];
676
- const reader = response3.body.getReader();
652
+ const reader = response4.body.getReader();
677
653
  let receivedLength = 0;
678
654
  while (true) {
679
655
  const { done, value } = await reader.read();
@@ -695,9 +671,9 @@ async function fetchHandler(httpRequest) {
695
671
  content: chunksAll,
696
672
  contentType
697
673
  });
698
- } catch (error4) {
699
- throw new HttpErrorResponse({
700
- error: error4,
674
+ } catch (error) {
675
+ return __makeResponse({
676
+ error,
701
677
  status,
702
678
  statusText,
703
679
  headers,
@@ -705,20 +681,11 @@ async function fetchHandler(httpRequest) {
705
681
  });
706
682
  }
707
683
  }
708
- if (!ok) {
709
- throw new HttpErrorResponse({
710
- status,
711
- statusText,
712
- headers,
713
- url,
714
- body
715
- });
716
- }
717
684
  return __makeResponse({
718
- url,
719
685
  status,
720
686
  statusText,
721
687
  headers,
688
+ url,
722
689
  body
723
690
  });
724
691
  }
@@ -879,7 +846,6 @@ export {
879
846
  createClient,
880
847
  cloneClient,
881
848
  basicAuthInterceptor,
882
- HttpErrorResponse,
883
849
  ERR_UNSUPPORTED_FIELD_TYPE,
884
850
  ERR_UNKNOWN,
885
851
  ERR_TIMEOUT,
package/index.min.js CHANGED
@@ -1 +1 @@
1
- var K=new Error("ERR_ABORTED"),X=new Error("ERR_TIMEOUT"),Ht=new Error("ERR_NETWORK"),W=new Error("ERR_NOT_FOUND_HANDLER"),pt=new Error("ERR_OBSERVE"),A=new Error("ERR_NOT_SET_ALIAS"),J=new Error("ERR_UNSUPPORTED_FIELD_TYPE"),j=new Error("ERR_INVALID_CLIENT"),Q=new Error("ERR_NOT_FOUND_GLOBAL_CLIENT"),y=new Error("ERR_INVALID_HTTP_CONTEXT_TOKEN"),Et=new Error("ERR_UNKNOWN");class f extends Error{status;statusText;url;headers;body;constructor(t){const n=t?.status??0,r=t?.statusText??"",o=n>=200&&n<300,T=t?.headers??new Headers,s=t?.url??"",i=t?.body??null;let R;if(o)R=`Http failure during parsing for ${s}`;else if(R=`Http failure response for ${s||"(unknown url)"}: ${n}`,r)R+=` - ${r}`;super(R,{cause:t?.error});super.name="HttpErrorResponse",this.statusText=r,this.url=s,this.headers=T,this.status=n,this.body=i}}function q(t){const n=t.get("Content-Length");if(!n)return 0;const r=Number(n);if(isNaN(r))return 0;return r}function l(t){return t.get("Content-Type")||""}function v(t){const{request:n,content:r,contentType:o}=t;switch(n.responseType){case"json":{const s=new TextDecoder().decode(r);if(s==="")return null;return JSON.parse(s)}case"text":return new TextDecoder().decode(r);case"blob":return new Blob([r],{type:o});case"arraybuffer":return r.buffer;default:return null}}function tt(t,n){const r=new Uint8Array(n);let o=0;for(let T of t)r.set(T,o),o+=T.length;return r}function wt(t){return Object.defineProperty(t,nt,{value:t}),t}function P(t){return typeof t==="function"&&nt in t}function it(t){return typeof t==="object"&&t!==null&&Y in t}function Z(t){const n=new Map;switch(!0){case Array.isArray(t):{for(let[r,o]of t)if(P(r))n.set(r,o);break}case it(t):{for(let[r,o]of t[Y])n.set(r,o);break}}return{set(r,o){if(!P(r))throw y;return n.set(r,o),this},get(r){if(!P(r))throw y;if(!n.has(r))n.set(r,r());return n.get(r)},del(r){return n.delete(r),this},has(r){return n.has(r)},keys(){return n.keys()},get length(){return Array.from(n.keys()).length},[Y]:n}}var nt=Symbol("HttpContextToken"),Y=Symbol("HttpContext");function Rt(t){const n={required:typeof t!=="undefined",alias:new Map,validators:[],asyncValidator:[]},r=()=>t;return Object.defineProperty(r,a,{value:n}),r.withJson=(o)=>{return n.alias.set(0,o),r},r.withForm=(o)=>{return n.alias.set(4,o),r},r.withQuery=(o)=>{return n.alias.set(1,o),r},r.withParam=(o)=>{return n.alias.set(2,o),r},r.withHeader=(o)=>{return n.alias.set(3,o),r},r.withUrlForm=(o)=>{return n.alias.set(6,o),r},r.withBody=()=>{return n.alias.set(5,void 0),r},r.withValidators=(...o)=>{return n.validators=o,r},r.withAsyncValidators=(...o)=>{return n.asyncValidator=o,r},r}function G(t){return t[a]}async function g(t,n){await Promise.all(t.map((r)=>r(n)))}function U(t){return!!t&&typeof t==="function"&&a in t}function V(t){return!!t&&typeof t==="object"&&Object.entries(t).every(([,n])=>U(n))}var a=Symbol("field");var ft=void 0;var rt=()=>ft;function ot(t){return t.reduceRight((n,r)=>{return(o,T)=>r(o,(s)=>n(s,T))},(n,r)=>r(n))}function M(t){const n=t?.status??0,r=t?.statusText??"",o=t?.url??"",T=t?.headers??new Headers,s=t?.body??null;return{status:n,statusText:r,url:o,headers:T,body:s}}function xt(t){switch(!0){case t instanceof FormData:case t instanceof Blob:case t instanceof ArrayBuffer:case t instanceof URLSearchParams:case typeof t==="string":return t;case typeof t==="object":case typeof t==="boolean":case typeof t==="number":case Array.isArray(t):return JSON.stringify(t);default:return null}}function Tt(t){switch(!0){case t instanceof FormData:return"multipart/form-data";case t instanceof ArrayBuffer:return"application/octet-stream";case t instanceof Blob:return t.type||"application/octet-stream";case t instanceof URLSearchParams:return"application/x-www-form-urlencoded;charset=UTF-8";case typeof t==="string":return"text/plain";case(typeof t==="object"&&t!==null):case typeof t==="number":case typeof t==="boolean":return"application/json";default:return null}}function kt(t){if(U(t))return t();if(V(t)){const n={};for(let[r,o]of Object.entries(t))n[r]=o();return n}return}function mt(...t){let n,r,o=!1,T,s=[],i="json",R,e=!1,p=[],E;switch(t.length){case 1:{n="GET",r=t[0];break}case 2:{n=t[0],r=t[1];break}default:throw new Error("Invalid arguments")}const c=(x)=>{const w=x?.timeout||0,N=x?.client||z(),H=d(N),_=x?.handler||H?.handler||rt();if(!_)throw W;let k,m,F;const h=[];if(x?.abort)h.push(x.abort);else F=new AbortController,h.push(F.signal);if(w>0)h.push(AbortSignal.timeout(w));return{doRequest:async(...I)=>{let D;if(o&&I.length===1)D=I[0];if(o&&!D)throw new Error("Because the request has input, the argument must be the input value");if(p.length>0)for(let u of p)u(D);const b={host:H?.host,method:n,endpoint:r,queryParams:new URLSearchParams,headers:new Headers,body:void 0,withCredentials:e,responseType:i,context:R||Z(),uploadProgress:k,downloadProgress:m,timeout:w,abort:AbortSignal.any(h)};if(o&&T)await Ct(b,T,D);let L=await ot([...H.interceptors,...s])(b,_);if(typeof E==="function")try{L=M({...L,body:E(L)})}catch(u){throw new f({error:u})}return L},cancel:()=>{F?.abort()},getInitValue:()=>kt(T),setUploadProgress:(I)=>{k=I},setDownloadProgress:(I)=>{m=I}}};return c.withField=(x)=>{return T=x,o=!0,c},c.withInterceptors=(x)=>{return s=x,c},c.withContext=(x)=>{return R=x,c},c.withCredentials=(x)=>{return e=x,c},c.withValidators=(x)=>{return p=x,c},c.withTransformResponse=(x)=>{return E=x,c},c.withResponseType=(x)=>{return i=x,c},c}function et(t,n){return t.replace(/:([^\/]+)/g,(r,o)=>{return n.get(o)??"undefined"})}async function Ct(t,n,r){function o(e){return typeof e==="object"&&e!==null}function T(e){switch(!0){case Array.isArray(e):case(typeof e==="object"&&e!==null):return JSON.stringify(e);case(typeof e==="object"&&e===null):case typeof e==="boolean":case typeof e==="number":case typeof e==="string":return String(e);default:throw new Error("Unsupported value type")}}function s(e,p,E){if(Array.isArray(E))for(let c of E)e.append(p,T(c));else e.set(p,T(E));return e}function i(e,p,E){if(Array.isArray(E))for(let c of E)i(e,p,T(c));return e.set(p,T(E)),e}function R(e,p){switch(!0){case typeof e==="undefined":return p;case(typeof e==="object"&&e===null):return e;default:return e}}if(U(n)){let e,p,E,c=void 0;const x=R(r,n()),w=G(n);await g([...w.validators,...w.asyncValidator],x);for(let[N,H]of w.alias)switch(N){case 1:{if(!H)throw A;p=s(new URLSearchParams,H,x);break}case 2:{if(!H)throw A;e=i(new Map,H,x);break}case 3:{if(!H)throw A;E=s(new Headers,H,x);break}case 4:{if(!H)throw A;c=s(new FormData,H,x);break}case 6:{if(!H)throw A;c=s(new URLSearchParams,H,x);break}case 0:case 5:c=x;break}if(e)t.endpoint=et(t.endpoint,e);t.queryParams=p,t.headers=E,t.body=c;return}if(V(n)&&o(r)){let e=new Map,p=new URLSearchParams,E=new Headers,c=new URLSearchParams,x=new FormData;const w={};let N=void 0,H;for(let[_,k]of Object.entries(n)){const m=G(k);for(let[F,h]of m.alias){const O=h||_,C=R(r[_],k());switch(await g([...m.validators,...m.asyncValidator],C),F){case 0:{Object.defineProperty(w,O,{value:C,writable:!0,enumerable:!0}),H=0;break}case 1:p=s(p,O,C);break;case 2:e=i(e,O,C);break;case 3:E=s(E,O,C);break;case 4:{x=s(x,O,C),H=4;break}case 6:{c=s(c,O,C),H=6;break}case 5:{N=C,H=5;break}}}}switch(t.endpoint=et(t.endpoint,e),t.queryParams=p,t.headers=E,H){case 5:t.body=N;break;case 4:t.body=x;break;case 6:t.body=c;break;case 0:t.body=w;break}return}throw J}function Nt(t){const n=new URL(t.endpoint,t.host);if(t.queryParams)n.search=t.queryParams.toString();const r=t.headers??new Headers;if(!r.has("Content-Type")){const T=Tt(t.body);if(T)r.set("Content-Type",T)}if(!r.has("Accept"))r.set("Accept","application/json, text/plain, */*");const o=t.withCredentials?"include":void 0;return new Request(n,{headers:r,method:t.method,body:xt(t.body),signal:t.abort,credentials:o})}async function S(t){const n=t.downloadProgress,r=Nt(t),o=t.abort;let T;try{T=await globalThis.fetch(r)}catch(w){if(o?.aborted&&o.reason instanceof Error)switch(!0){case o.reason.name==="AbortError":throw new f({error:K});case o.reason.name==="TimeoutError":throw new f({error:X})}throw new f({error:w})}const{ok:s,headers:i,status:R,statusText:e,url:p}=T,E=q(i),c=l(i);let x=null;if(T.body){const w=[],N=T.body.getReader();let H=0;while(!0){const{done:k,value:m}=await N.read();if(k)break;w.push(m),H+=m.length,n?.({lengthComputable:E>0,loaded:H,total:E})}const _=tt(w,H);try{x=v({request:t,content:_,contentType:c})}catch(k){throw new f({error:k,status:R,statusText:e,headers:i,url:p})}}if(!s)throw new f({status:R,statusText:e,headers:i,url:p,body:x});return M({url:p,status:R,statusText:e,headers:i,body:x})}function ct(t){return typeof t==="object"&&t!==null&&$ in t}function d(t){if(!ct(t))throw j;return t[$]}function st(t){const n={host:t.host,interceptors:t.interceptors??[],handler:t.handler||S};return{[$]:n}}function _t(t,n){const o={...d(t),...n};return{[$]:o}}function z(){if(!B)throw Q;return B}function Ot(t){B=t}function At(){B=void 0}function ht(t){B=st(t)}var $=Symbol("Client"),B;function It(t,n){let r=n?.encode;if(!r){const o=globalThis.btoa;if(typeof o!=="function")throw new Error("BasicAuthInterceptor is not supported in this environment");r=(T)=>o(`${T.username}:${T.password}`)}return(o,T)=>{const s=o.headers||new Headers;return s.set("Authorization",`Basic ${r(t())}`),o.headers=s,T(o)}}var Ft=(t)=>{if(!t)return new Error("required");return null},Ut=(t)=>{if(typeof t!=="boolean"||!t)return new Error("requiredTrue");return null},Bt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length<t)return new Error(`minLength ${t}`);return null}},Dt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length>t)return new Error(`maxLength ${t}`);return null}},Lt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n<t)return new Error(`minLength ${t}`);return null}},yt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n>t)return new Error(`maxLength ${t}`);return null}},Pt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(!t.test(n))return new Error("pattern");return null}};export{Ot as setGlobalClient,At as restGlobalClient,Ut as requiredTrue,Ft as required,Pt as pattern,Bt as minLength,Lt as min,Dt as maxLength,yt as max,wt as makeHttpContextToken,Z as makeHttpContext,P as isHttpContextToken,V as isFieldGroup,U as isField,ct as isClient,z as getGlobalClient,Rt as field,S as fetchHandler,g as doValid,mt as defineRequest,ht as createGlobalClient,st as createClient,_t as cloneClient,It as basicAuthInterceptor,f as HttpErrorResponse,J as ERR_UNSUPPORTED_FIELD_TYPE,Et as ERR_UNKNOWN,X as ERR_TIMEOUT,pt as ERR_OBSERVE,A as ERR_NOT_SET_ALIAS,W as ERR_NOT_FOUND_HANDLER,Q as ERR_NOT_FOUND_GLOBAL_CLIENT,Ht as ERR_NETWORK,y as ERR_INVALID_HTTP_CONTEXT_TOKEN,j as ERR_INVALID_CLIENT,K as ERR_ABORTED};
1
+ function d(t){const n=t.get("Content-Length");if(!n)return 0;const r=Number(n);if(isNaN(r))return 0;return r}function a(t){return t.get("Content-Type")||""}function q(t){const{request:n,content:r,contentType:o}=t;switch(n.responseType){case"json":{const H=new TextDecoder().decode(r);if(H==="")return null;return JSON.parse(H)}case"text":return new TextDecoder().decode(r);case"blob":return new Blob([r],{type:o});case"arraybuffer":return r.buffer;default:return null}}function l(t,n){const r=new Uint8Array(n);let o=0;for(let T of t)r.set(T,o),o+=T.length;return r}function N(t){const n=t?.status??0,r=n>=200&&n<300,o=t?.statusText??"",T=t?.url??"",H=t?.headers??new Headers,f=t?.body??null;let R=t?.error;if(!R&&!r){let e=`Http failure response for ${T||"(unknown url)"}: ${n}`;if(o)e+=` - ${o}`;R=new Error(e)}return{status:n,statusText:o,url:T,headers:H,body:f,error:R}}var y=new Error("ERR_ABORTED"),K=new Error("ERR_TIMEOUT"),Ht=new Error("ERR_NETWORK"),X=new Error("ERR_NOT_FOUND_HANDLER"),Et=new Error("ERR_OBSERVE"),A=new Error("ERR_NOT_SET_ALIAS"),W=new Error("ERR_UNSUPPORTED_FIELD_TYPE"),J=new Error("ERR_INVALID_CLIENT"),j=new Error("ERR_NOT_FOUND_GLOBAL_CLIENT"),P=new Error("ERR_INVALID_HTTP_CONTEXT_TOKEN"),pt=new Error("ERR_UNKNOWN");function wt(t){return Object.defineProperty(t,v,{value:t}),t}function V(t){return typeof t==="function"&&v in t}function Rt(t){return typeof t==="object"&&t!==null&&Q in t}function Y(t){const n=new Map;switch(!0){case Array.isArray(t):{for(let[r,o]of t)if(V(r))n.set(r,o);break}case Rt(t):{for(let[r,o]of t[Q])n.set(r,o);break}}return{set(r,o){if(!V(r))throw P;return n.set(r,o),this},get(r){if(!V(r))throw P;if(!n.has(r))n.set(r,r());return n.get(r)},del(r){return n.delete(r),this},has(r){return n.has(r)},keys(){return n.keys()},get length(){return Array.from(n.keys()).length},[Q]:n}}var v=Symbol("HttpContextToken"),Q=Symbol("HttpContext");function it(t){const n={required:typeof t!=="undefined",alias:new Map,validators:[],asyncValidator:[]},r=()=>t;return Object.defineProperty(r,Z,{value:n}),r.withJson=(o)=>{return n.alias.set(0,o),r},r.withForm=(o)=>{return n.alias.set(4,o),r},r.withQuery=(o)=>{return n.alias.set(1,o),r},r.withParam=(o)=>{return n.alias.set(2,o),r},r.withHeader=(o)=>{return n.alias.set(3,o),r},r.withUrlForm=(o)=>{return n.alias.set(6,o),r},r.withBody=()=>{return n.alias.set(5,void 0),r},r.withValidators=(...o)=>{return n.validators=o,r},r.withAsyncValidators=(...o)=>{return n.asyncValidator=o,r},r}function G(t){return t[Z]}async function M(t,n){await Promise.all(t.map((r)=>r(n)))}function D(t){return!!t&&typeof t==="function"&&Z in t}function $(t){return!!t&&typeof t==="object"&&Object.entries(t).every(([,n])=>D(n))}var Z=Symbol("field");var ft=void 0;var tt=()=>ft;function nt(t){return t.reduceRight((n,r)=>{return(o,T)=>r(o,(H)=>n(H,T))},(n,r)=>r(n))}function ot(t){switch(!0){case t instanceof FormData:case t instanceof Blob:case t instanceof ArrayBuffer:case t instanceof URLSearchParams:case typeof t==="string":return t;case typeof t==="object":case typeof t==="boolean":case typeof t==="number":case Array.isArray(t):return JSON.stringify(t);default:return null}}function et(t){switch(!0){case t instanceof FormData:return"multipart/form-data";case t instanceof ArrayBuffer:return"application/octet-stream";case t instanceof Blob:return t.type||"application/octet-stream";case t instanceof URLSearchParams:return"application/x-www-form-urlencoded;charset=UTF-8";case typeof t==="string":return"text/plain";case(typeof t==="object"&&t!==null):case typeof t==="number":case typeof t==="boolean":return"application/json";default:return null}}function kt(t){if(D(t))return t();if($(t)){const n={};for(let[r,o]of Object.entries(t))n[r]=o();return n}return}function Ct(...t){let n,r,o=!1,T,H=[],f="json",R,e=!1,p=[],w;switch(t.length){case 1:{n="GET",r=t[0];break}case 2:{n=t[0],r=t[1];break}default:throw new Error("Invalid arguments")}const c=(x)=>{const i=x?.timeout||0,k=x?.client||S(),E=z(k),C=x?.handler||E?.handler||tt();if(!C)throw X;let m,I,B;const _=[];if(x?.abort)_.push(x.abort);else B=new AbortController,_.push(B.signal);if(i>0)_.push(AbortSignal.timeout(i));return{doRequest:async(...F)=>{try{let U;if(o&&F.length===1)U=F[0];if(o&&!U)throw new Error("Because the request has input, the argument must be the input value");if(p.length>0)for(let ct of p)ct(U);const b={host:E?.host,method:n,endpoint:r,queryParams:new URLSearchParams,headers:new Headers,body:void 0,withCredentials:e,responseType:f,context:R||Y(),uploadProgress:m,downloadProgress:I,timeout:i,abort:AbortSignal.any(_)};if(o&&T)await st(b,T,U);let h=await nt([...E.interceptors,...H])(b,C);if(typeof w==="function")h=N({...h,body:w(h)});return h}catch(U){return N({error:U})}},cancel:()=>{B?.abort()},getInitValue:()=>kt(T),setUploadProgress:(F)=>{m=F},setDownloadProgress:(F)=>{I=F}}};return c.withField=(x)=>{return T=x,o=!0,c},c.withInterceptors=(x)=>{return H=x,c},c.withContext=(x)=>{return R=x,c},c.withCredentials=(x)=>{return e=x,c},c.withValidators=(x)=>{return p=x,c},c.withTransformResponse=(x)=>{return w=x,c},c.withResponseType=(x)=>{return f=x,c},c}function rt(t,n){return t.replace(/:([^\/]+)/g,(r,o)=>{return n.get(o)??"undefined"})}async function st(t,n,r){function o(e){return typeof e==="object"&&e!==null}function T(e){switch(!0){case Array.isArray(e):case(typeof e==="object"&&e!==null):return JSON.stringify(e);case(typeof e==="object"&&e===null):case typeof e==="boolean":case typeof e==="number":case typeof e==="string":return String(e);default:throw new Error("Unsupported value type")}}function H(e,p,w){if(Array.isArray(w))for(let c of w)e.append(p,T(c));else e.set(p,T(w));return e}function f(e,p,w){if(Array.isArray(w))for(let c of w)f(e,p,T(c));return e.set(p,T(w)),e}function R(e,p){switch(!0){case typeof e==="undefined":return p;case(typeof e==="object"&&e===null):return e;default:return e}}if(D(n)){let e,p,w,c=void 0;const x=R(r,n()),i=G(n);await M([...i.validators,...i.asyncValidator],x);for(let[k,E]of i.alias)switch(k){case 1:{if(!E)throw A;p=H(new URLSearchParams,E,x);break}case 2:{if(!E)throw A;e=f(new Map,E,x);break}case 3:{if(!E)throw A;w=H(new Headers,E,x);break}case 4:{if(!E)throw A;c=H(new FormData,E,x);break}case 6:{if(!E)throw A;c=H(new URLSearchParams,E,x);break}case 0:case 5:c=x;break}if(e)t.endpoint=rt(t.endpoint,e);t.queryParams=p,t.headers=w,t.body=c;return}if($(n)&&o(r)){let e=new Map,p=new URLSearchParams,w=new Headers,c=new URLSearchParams,x=new FormData;const i={};let k=void 0,E;for(let[C,m]of Object.entries(n)){const I=G(m);for(let[B,_]of I.alias){const O=_||C,s=R(r[C],m());switch(await M([...I.validators,...I.asyncValidator],s),B){case 0:{Object.defineProperty(i,O,{value:s,writable:!0,enumerable:!0}),E=0;break}case 1:p=H(p,O,s);break;case 2:e=f(e,O,s);break;case 3:w=H(w,O,s);break;case 4:{x=H(x,O,s),E=4;break}case 6:{c=H(c,O,s),E=6;break}case 5:{k=s,E=5;break}}}}switch(t.endpoint=rt(t.endpoint,e),t.queryParams=p,t.headers=w,E){case 5:t.body=k;break;case 4:t.body=x;break;case 6:t.body=c;break;case 0:t.body=i;break}return}throw W}function Nt(t){const n=new URL(t.endpoint,t.host);if(t.queryParams)n.search=t.queryParams.toString();const r=t.headers??new Headers;if(!r.has("Content-Type")){const T=et(t.body);if(T)r.set("Content-Type",T)}if(!r.has("Accept"))r.set("Accept","application/json, text/plain, */*");const o=t.withCredentials?"include":void 0;return new Request(n,{headers:r,method:t.method,body:ot(t.body),signal:t.abort,credentials:o})}async function u(t){const n=t.downloadProgress,r=Nt(t),o=t.abort;let T;try{T=await globalThis.fetch(r)}catch(x){if(o?.aborted&&o.reason instanceof Error)switch(!0){case o.reason.name==="AbortError":return N({error:y});case o.reason.name==="TimeoutError":return N({error:K})}return N({error:x})}const{headers:H,status:f,statusText:R,url:e}=T,p=d(H),w=a(H);let c=null;if(T.body){const x=[],i=T.body.getReader();let k=0;while(!0){const{done:C,value:m}=await i.read();if(C)break;x.push(m),k+=m.length,n?.({lengthComputable:p>0,loaded:k,total:p})}const E=l(x,k);try{c=q({request:t,content:E,contentType:w})}catch(C){return N({error:C,status:f,statusText:R,headers:H,url:e})}}return N({status:f,statusText:R,headers:H,url:e,body:c})}function xt(t){return typeof t==="object"&&t!==null&&g in t}function z(t){if(!xt(t))throw J;return t[g]}function Tt(t){const n={host:t.host,interceptors:t.interceptors??[],handler:t.handler||u};return{[g]:n}}function mt(t,n){const o={...z(t),...n};return{[g]:o}}function S(){if(!L)throw j;return L}function Ot(t){L=t}function At(){L=void 0}function It(t){L=Tt(t)}var g=Symbol("Client"),L;function _t(t,n){let r=n?.encode;if(!r){const o=globalThis.btoa;if(typeof o!=="function")throw new Error("BasicAuthInterceptor is not supported in this environment");r=(T)=>o(`${T.username}:${T.password}`)}return(o,T)=>{const H=o.headers||new Headers;return H.set("Authorization",`Basic ${r(t())}`),o.headers=H,T(o)}}var Ft=(t)=>{if(!t)return new Error("required");return null},Ut=(t)=>{if(typeof t!=="boolean"||!t)return new Error("requiredTrue");return null},Bt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length<t)return new Error(`minLength ${t}`);return null}},Dt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length>t)return new Error(`maxLength ${t}`);return null}},Lt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n<t)return new Error(`minLength ${t}`);return null}},ht=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n>t)return new Error(`maxLength ${t}`);return null}},Pt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(!t.test(n))return new Error("pattern");return null}};export{Ot as setGlobalClient,At as restGlobalClient,Ut as requiredTrue,Ft as required,Pt as pattern,Bt as minLength,Lt as min,Dt as maxLength,ht as max,wt as makeHttpContextToken,Y as makeHttpContext,V as isHttpContextToken,$ as isFieldGroup,D as isField,xt as isClient,S as getGlobalClient,it as field,u as fetchHandler,M as doValid,Ct as defineRequest,It as createGlobalClient,Tt as createClient,mt as cloneClient,_t as basicAuthInterceptor,W as ERR_UNSUPPORTED_FIELD_TYPE,pt as ERR_UNKNOWN,K as ERR_TIMEOUT,Et as ERR_OBSERVE,A as ERR_NOT_SET_ALIAS,X as ERR_NOT_FOUND_HANDLER,j as ERR_NOT_FOUND_GLOBAL_CLIENT,Ht as ERR_NETWORK,P as ERR_INVALID_HTTP_CONTEXT_TOKEN,J as ERR_INVALID_CLIENT,y as ERR_ABORTED};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defjs/core",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "module": "index.js",
6
6
  "typings": "index.d.ts",