@defjs/core 0.0.0-test-001 → 0.0.0-test-002

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
@@ -20,7 +20,7 @@ export declare const minLength: (min: number) => ValidatorFn;
20
20
  export declare const maxLength: (max: number) => ValidatorFn;
21
21
  export declare const min: (min: number) => ValidatorFn;
22
22
  export declare const max: (max: number) => ValidatorFn;
23
- export declare const pattern: (pattern: string | RegExp) => ValidatorFn;
23
+ export declare const pattern: (pattern: RegExp) => ValidatorFn;
24
24
  declare const FIELD: unique symbol;
25
25
  declare enum FieldType {
26
26
  Json = 1,
@@ -28,7 +28,8 @@ declare enum FieldType {
28
28
  Param = 3,
29
29
  Header = 4,
30
30
  Form = 5,
31
- Body = 6
31
+ Body = 6,
32
+ UrlForm = 7
32
33
  }
33
34
  export interface FieldMetadata<T = undefined> {
34
35
  alias: Map<FieldType, string | undefined>;
@@ -41,6 +42,7 @@ export type Field<T = undefined> = (() => T) & {
41
42
  withQuery(alias?: string): Field<T>;
42
43
  withParam(alias?: string): Field<T>;
43
44
  withHeader(alias?: string): Field<T>;
45
+ withUrlForm(alias?: string): Field<T>;
44
46
  withBody(): Field<T>;
45
47
  withValidators(...fn: ValidatorFn<T>[]): Field<T>;
46
48
  withAsyncValidators(...fn: AsyncValidatorFn<T>[]): Field<T>;
@@ -53,25 +55,13 @@ export declare function validatorField(validators: ValidatorFn<any>[], value: un
53
55
  export declare function asyncValidatorField(asyncValidator: AsyncValidatorFn<any>[], value: unknown): Promise<void>;
54
56
  export declare function isField(value: unknown): value is Field;
55
57
  export declare function isFieldGroup(value: unknown): value is Record<PropertyKey, Field>;
56
- declare const HTTP_RESPONSE: unique symbol;
57
58
  export type HttpResponseBody = string | ArrayBuffer | Blob | object | null;
58
- export type HttpResponse<R> = ({
59
- readonly ok: true;
60
- readonly error: null;
61
- } | {
62
- readonly ok: false;
63
- readonly error: Error;
64
- }) & {
59
+ export type HttpResponse<R> = {
65
60
  readonly url: string;
66
61
  readonly status: number;
67
62
  readonly statusText: string;
68
63
  readonly headers: Headers;
69
64
  readonly body: R | null;
70
- readonly [HTTP_RESPONSE]: unknown;
71
- };
72
- export declare function isHttpResponse<R>(value: unknown): value is HttpResponse<R>;
73
- export declare function isHttpResponseError<R>(value: unknown): value is HttpResponse<R> & {
74
- ok: false;
75
65
  };
76
66
  export type MakeResponseOptions<R> = {
77
67
  status?: number;
@@ -79,9 +69,7 @@ export type MakeResponseOptions<R> = {
79
69
  url?: string;
80
70
  headers?: Headers;
81
71
  body?: R | null;
82
- error?: Error;
83
72
  };
84
- export declare function makeResponse<R>(options: MakeResponseOptions<R>): HttpResponse<R>;
85
73
  export type InterceptorFn = (req: HttpRequest, next: HttpHandler) => Promise<HttpResponse<unknown>>;
86
74
  export type BasicCredential = {
87
75
  username: string;
@@ -107,13 +95,12 @@ export interface HttpProgressEvent {
107
95
  readonly total: number;
108
96
  }
109
97
  export type HttpProgressFn = (event: HttpProgressEvent) => void;
110
- export type TransformRequestFn<Input = unknown> = (input: Input, request: HttpRequest) => HttpRequest["body"];
111
98
  export type TransformResponseFn<Output = unknown> = (response: HttpResponse<unknown>) => Output;
112
99
  export interface HttpRequest {
113
100
  host?: string;
114
101
  method: string;
115
102
  endpoint: string;
116
- body?: Blob | ArrayBuffer | FormData | object | string | number | boolean | null;
103
+ body?: Blob | ArrayBuffer | FormData | URLSearchParams | object | string | number | boolean | null;
117
104
  headers?: Headers;
118
105
  queryParams?: URLSearchParams;
119
106
  /** default:json */
@@ -126,10 +113,8 @@ export interface HttpRequest {
126
113
  downloadProgress?: HttpProgressFn;
127
114
  /**
128
115
  * default:body
129
- *
130
- * @todo Implement streaming response
131
116
  */
132
- observe?: "body" | "stream" | "response";
117
+ observe?: "body" | "response";
133
118
  abort?: AbortSignal;
134
119
  }
135
120
  export type RequestInputValue<T> = T extends Field<infer V> ? V : T extends {
@@ -137,29 +122,16 @@ export type RequestInputValue<T> = T extends Field<infer V> ? V : T extends {
137
122
  } ? {
138
123
  [K in keyof T]: RequestInputValue<T[K]>;
139
124
  } : never;
140
- export type RequestOptions<Output = unknown, Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined> = {
141
- method: string;
142
- endpoint: string;
143
- input?: Input;
144
- interceptors?: InterceptorFn[];
145
- responseType?: HttpResponseType;
146
- context?: HttpContext;
147
- observe?: "body" | "response";
148
- withCredentials?: boolean;
149
- validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
150
- transformRequest?: TransformRequestFn;
151
- transformResponse?: TransformResponseFn<Output>;
152
- };
153
125
  export type DoRequestOptions = {
154
126
  abort?: AbortSignal;
155
127
  handler?: HttpHandler;
156
128
  client?: Client;
157
129
  timeout?: number;
158
130
  };
159
- export type DoRequestFn<Input = unknown, Output = unknown> = Input extends undefined ? (options?: DoRequestOptions) => Promise<Output> : (input: RequestInputValue<Input>, options?: DoRequestOptions) => Promise<Output>;
160
- export type UseRequestFn<Output = unknown, Input = unknown> = () => {
161
- doRequest: DoRequestFn<Input, Output>;
162
- inputValue: Input extends Field<infer V> ? V : Input extends {
131
+ export type ObserveType<Observe, Output> = Observe extends "body" ? Output : Observe extends "response" ? HttpResponse<Output> : never;
132
+ export type UseRequestFn<Input, Output, Observe> = {
133
+ doRequest: Input extends undefined ? (options?: DoRequestOptions) => Promise<ObserveType<Observe, Output>> : (input: RequestInputValue<Input>, options?: DoRequestOptions) => Promise<ObserveType<Observe, Output>>;
134
+ getInitValue: () => Input extends Field<infer V> ? V : Input extends {
163
135
  [K in keyof Input]: Field<any>;
164
136
  } ? {
165
137
  [K in keyof Input]: RequestInputValue<Input[K]>;
@@ -167,112 +139,22 @@ export type UseRequestFn<Output = unknown, Input = unknown> = () => {
167
139
  setUploadProgress: (fn: HttpProgressFn) => void;
168
140
  setDownloadProgress: (fn: HttpProgressFn) => void;
169
141
  };
170
- /** Observe: Body */
171
- export declare function defineRequest<Output = unknown, Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
172
- method: string;
173
- endpoint: string;
174
- input?: Input;
175
- interceptors?: InterceptorFn[];
176
- responseType?: "json";
177
- observe?: "body";
178
- context?: HttpContext;
179
- withCredentials?: boolean;
180
- validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
181
- transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
182
- transformResponse?: TransformResponseFn<Output>;
183
- }): UseRequestFn<Output, Input>;
184
- export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
185
- method: string;
186
- endpoint: string;
187
- input?: Input;
188
- interceptors?: InterceptorFn[];
189
- responseType: "text";
190
- observe?: "body";
191
- context?: HttpContext;
192
- withCredentials?: boolean;
193
- validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
194
- transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
195
- transformResponse?: TransformResponseFn;
196
- }): UseRequestFn<string, Input>;
197
- export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
198
- method: string;
199
- endpoint: string;
200
- input?: Input;
201
- interceptors?: InterceptorFn[];
202
- responseType: "blob";
203
- observe?: "body";
204
- context?: HttpContext;
205
- withCredentials?: boolean;
206
- validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
207
- transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
208
- transformResponse?: TransformResponseFn;
209
- }): UseRequestFn<Blob, Input>;
210
- export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
211
- method: string;
212
- endpoint: string;
213
- input?: Input;
214
- interceptors?: InterceptorFn[];
215
- responseType: "arraybuffer";
216
- observe?: "body";
217
- context?: HttpContext;
218
- withCredentials?: boolean;
219
- validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
220
- transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
221
- transformResponse?: TransformResponseFn;
222
- }): UseRequestFn<ArrayBuffer, Input>;
223
- /** Observe: Response */
224
- export declare function defineRequest<Output = unknown, Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
225
- method: string;
226
- endpoint: string;
227
- input?: Input;
228
- interceptors?: InterceptorFn[];
229
- responseType?: "json";
230
- observe: "response";
231
- context?: HttpContext;
232
- withCredentials?: boolean;
233
- validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
234
- transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
235
- transformResponse?: TransformResponseFn<Output>;
236
- }): UseRequestFn<HttpResponse<Output>, Input>;
237
- export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
238
- method: string;
239
- endpoint: string;
240
- input?: Input;
241
- interceptors?: InterceptorFn[];
242
- responseType?: "text";
243
- observe: "response";
244
- context?: HttpContext;
245
- withCredentials?: boolean;
246
- validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
247
- transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
248
- transformResponse?: TransformResponseFn;
249
- }): UseRequestFn<HttpResponse<string>, Input>;
250
- export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
251
- method: string;
252
- endpoint: string;
253
- input?: Input;
254
- interceptors?: InterceptorFn[];
255
- responseType: "blob";
256
- observe: "response";
257
- context?: HttpContext;
258
- withCredentials?: boolean;
259
- validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
260
- transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
261
- transformResponse?: TransformResponseFn;
262
- }): UseRequestFn<HttpResponse<Blob>, Input>;
263
- export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
264
- method: string;
265
- endpoint: string;
266
- input?: Input;
267
- interceptors?: InterceptorFn[];
268
- responseType?: "arraybuffer";
269
- observe: "response";
270
- context?: HttpContext;
271
- withCredentials?: boolean;
272
- validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
273
- transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
274
- transformResponse?: TransformResponseFn;
275
- }): UseRequestFn<HttpResponse<ArrayBuffer>, Input>;
142
+ export interface DefineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined, Output = unknown, Observe extends "body" | "response" = "body"> {
143
+ (): UseRequestFn<Input, Output, Observe>;
144
+ withField<I extends Field<any> | Record<PropertyKey, Field<any>>>(value: I): DefineRequest<I, Output, Observe>;
145
+ withInterceptors(value: InterceptorFn[]): DefineRequest<Input, Output, Observe>;
146
+ withContext(value: HttpContext): DefineRequest<Input, Output, Observe>;
147
+ withCredentials(value: boolean): DefineRequest<Input, Output, Observe>;
148
+ withValidators(value: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[]): DefineRequest<Input, Output, Observe>;
149
+ withTransformResponse<O>(fn: TransformResponseFn<O>): DefineRequest<Input, O, Observe>;
150
+ withObserve(value: "body"): DefineRequest<Input, Output, "body">;
151
+ withObserve(value: "response"): DefineRequest<Input, Output, "response">;
152
+ withResponseType(value: "json"): DefineRequest<Input, Output, Observe>;
153
+ withResponseType(value: "text"): DefineRequest<Input, string, Observe>;
154
+ withResponseType(value: "blob"): DefineRequest<Input, Blob, Observe>;
155
+ withResponseType(value: "arraybuffer"): DefineRequest<Input, ArrayBuffer, Observe>;
156
+ }
157
+ export declare function defineRequest<Output>(method: string, endpoint: string): DefineRequest<undefined, Output>;
276
158
  export type HttpHandler = (req: HttpRequest) => Promise<HttpResponse<unknown>>;
277
159
  export interface FetchConfig {
278
160
  /** A string indicating how the request will interact with the browser's cache to set request's cache. */
@@ -309,7 +191,7 @@ export type Client = {} & {
309
191
  };
310
192
  export declare function isClient(value: unknown): value is Client;
311
193
  export declare function createClient(options: ClientOptions): Client;
312
- export declare function cloneClient(client: Client, options: ClientOptions): Client;
194
+ export declare function cloneClient(client: Client, options: Partial<ClientOptions>): Client;
313
195
  export declare function getGlobalClient(): Client;
314
196
  export declare function setGlobalClient(client: Client): void;
315
197
  export declare function restGlobalClient(): void;
@@ -318,13 +200,28 @@ export declare const ERR_ABORTED: Error;
318
200
  export declare const ERR_TIMEOUT: Error;
319
201
  export declare const ERR_NETWORK: Error;
320
202
  export declare const ERR_NOT_FOUND_HANDLER: Error;
321
- export declare const ERR_TRANSFORM_RESPONSE: Error;
322
- export declare const ERR_STREAMING_NOT_IMPLEMENTED: Error;
323
203
  export declare const ERR_OBSERVE: Error;
324
204
  export declare const ERR_NOT_SET_ALIAS: Error;
325
205
  export declare const ERR_UNSUPPORTED_FIELD_TYPE: Error;
326
206
  export declare const ERR_INVALID_CLIENT: Error;
327
207
  export declare const ERR_NOT_FOUND_GLOBAL_CLIENT: Error;
328
208
  export declare const ERR_INVALID_HTTP_CONTEXT_TOKEN: Error;
209
+ export declare const ERR_UNKNOWN: Error;
210
+ export declare class HttpErrorResponse extends Error {
211
+ readonly status: number;
212
+ readonly statusText: string;
213
+ readonly url: string | null;
214
+ readonly headers: Headers;
215
+ readonly ok: boolean;
216
+ readonly body: unknown;
217
+ constructor(init: {
218
+ error?: Error | string | unknown;
219
+ status?: number;
220
+ statusText?: string;
221
+ url?: string;
222
+ headers?: Headers;
223
+ body?: unknown;
224
+ });
225
+ }
329
226
 
330
227
  export {};
@@ -0,0 +1 @@
1
+ var $=new Error("ERR_ABORTED"),K=new Error("ERR_TIMEOUT"),Ht=new Error("ERR_NETWORK"),y=new Error("ERR_NOT_FOUND_HANDLER"),W=new Error("ERR_OBSERVE"),h=new Error("ERR_NOT_SET_ALIAS"),X=new Error("ERR_UNSUPPORTED_FIELD_TYPE"),J=new Error("ERR_INVALID_CLIENT"),Q=new Error("ERR_NOT_FOUND_GLOBAL_CLIENT"),V=new Error("ERR_INVALID_HTTP_CONTEXT_TOKEN"),it=new Error("ERR_UNKNOWN");class _ extends Error{status;statusText;url;headers;ok;body;constructor(t){const n=t.status??0,r=t.statusText??"",o=n>=200&&n<300,s=t.headers??new Headers,c=t.url??null,i=t.body??null;let R;if(o)R=`Http failure during parsing for ${t.url||"(unknown url)"}`;else R=`Http failure response for ${t.url||"(unknown url)"}: ${t.status} ${t.statusText}`;super(R,{cause:t.error});super.name="HttpErrorResponse",this.statusText=r,this.url=c,this.headers=s,this.status=n,this.ok=o,this.body=i}}function Y(t){return Object.defineProperty(t,v,{value:t}),t}function j(t){return typeof t==="function"&&v in t}function Z(){const t=new Map;return{set(n,r){if(!j(n))throw V;return t.set(n,r),this},get(n){if(!j(n))throw V;if(!t.has(n))t.set(n,n());return t.get(n)},del(n){return t.delete(n),this},has(n){return t.has(n)},keys(){return t.keys()}}}var v=Symbol("HttpContextToken");function pt(t){const n={alias:new Map,validators:[],asyncValidator:[]},r=()=>t;return Object.defineProperty(r,G,{value:n}),r.withJson=(o)=>{return n.alias.set(1,o),r},r.withForm=(o)=>{return n.alias.set(5,o),r},r.withQuery=(o)=>{return n.alias.set(2,o),r},r.withParam=(o)=>{return n.alias.set(3,o),r},r.withHeader=(o)=>{return n.alias.set(4,o),r},r.withUrlForm=(o)=>{return n.alias.set(7,o),r},r.withBody=()=>{return n.alias.set(6,void 0),r},r.withValidators=(...o)=>{return n.validators=o,r},r.withAsyncValidators=(...o)=>{return n.asyncValidator=o,r},r}function S(t){return t[G]}function Rt(t,n){for(let r of t){const o=r(n);if(o)throw o}}async function ft(t,n){for(let r of t){const o=await r(n);if(o)throw o}}function O(t){return!!t&&typeof t==="function"&&G in t}function B(t){return!!t&&typeof t==="object"&&Object.entries(t).every(([,n])=>O(n))}var G=Symbol("field");var kt=void 0;var tt=()=>kt;function nt(t){return t.reduceRight((n,r)=>{return(o,s)=>r(o,(c)=>n(c,s))},(n,r)=>r(n))}function D(t){const n=t.status??0,r=t.statusText??"",o=t.url??"",s=t.headers??new Headers,c=t.body??null;return{status:n,statusText:r,url:o,headers:s,body:c}}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 xt(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 mt(t){if(O(t))return t();if(B(t)){const n={};for(let[r,o]of Object.entries(t))n[r]=o();return n}return}function Nt(t,n){let r=!1,o,s=[],c="json",i,R="body",e=!1,E=[],w;const T=()=>{let x,m,f;return{doRequest:async(...C)=>{let F,p;switch(C.length){case 1:{p=C[0];break}case 2:{F=C[0],p=C[1];break}}if(r&&!F)throw new Error("Because the request has input, the first argument must be the input value");if(E.length>0)for(let M of E)M(F);const k=p?.timeout||0;if(p?.abort)f=p.abort;else if(k>0)f=AbortSignal.timeout(k);const U=L(p?.client)?p.client:d(),l=z(U),u={host:l?.host,method:t,endpoint:n,queryParams:new URLSearchParams,headers:new Headers,body:void 0,withCredentials:e,responseType:c,context:i||Z(),observe:R,uploadProgress:x,downloadProgress:m,timeout:k,abort:f},q=p?.handler||l?.handler||tt();if(!q)throw y;if(r)await Ct(u,o,F);let I=await nt([...s])(u,q);if(typeof w==="function")try{I=D({...I,body:w(I)})}catch(M){throw new _({error:M})}switch(u.observe){case"body":return I.body;case"response":return I;default:throw W}},getInitValue:()=>mt(o),setUploadProgress:(C)=>{x=C},setDownloadProgress:(C)=>{m=C}}};return T.withField=(x)=>{return o=x,r=!0,T},T.withInterceptors=(x)=>{return s=x,T},T.withContext=(x)=>{return i=x,T},T.withCredentials=(x)=>{return e=x,T},T.withValidators=(x)=>{return E=x,console.log(E),T},T.withTransformResponse=(x)=>{return w=x,T},T.withObserve=(x)=>{return R=x,T},T.withResponseType=(x)=>{return c=x,T},T}function rt(t,n){return t.replace(/:([^\/]+)/g,(r,o)=>{return n.get(o)??"undefined"})}async function Ct(t,n,r){async function o(e,E){for(let w of e){const T=await w(E);if(T)return T}return}function s(e){return typeof e==="object"&&e!==null}function c(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 i(e,E,w){if(Array.isArray(w))for(let T of w)e.append(E,c(T));else e.set(E,c(w));return e}function R(e,E,w){if(Array.isArray(w))for(let T of w)R(e,E,c(T));return e.set(E,c(w)),e}if(O(n)){let e,E,w,T=void 0;const x=r??n(),m=S(n),f=await o([...m.validators,...m.asyncValidator],x);if(f)throw f;for(let[N,H]of m.alias)switch(N){case 2:{if(!H)throw h;E=i(new URLSearchParams,H,x);break}case 3:{if(!H)throw h;e=R(new Map,H,x);break}case 4:{if(!H)throw h;w=i(new Headers,H,x);break}case 5:{if(!H)throw h;T=i(new FormData,H,x);break}case 7:{if(!H)throw h;T=i(new URLSearchParams,H,x);break}case 1:case 6:T=x;break}if(e)t.endpoint=rt(t.endpoint,e);t.queryParams=E,t.headers=w,t.body=T;return}if(B(n)&&s(r)){let e=new Map,E=new URLSearchParams,w=new Headers,T=new URLSearchParams,x=new FormData;const m={};let f=void 0,N;for(let[H,A]of Object.entries(n)){const g=S(A);for(let[C,F]of g.alias){const p=F||H,k=r[H]||A(),U=await o([...g.validators,...g.asyncValidator],k);if(U)throw U;switch(C){case 1:{Object.defineProperty(m,p,{value:k,writable:!0,enumerable:!0}),N=1;break}case 2:E=i(E,p,k);break;case 3:e=R(e,p,k);break;case 4:w=i(w,p,k);break;case 5:{x=i(x,p,k),N=5;break}case 7:{T=i(T,p,k),N=7;break}case 6:{f=k,N=6;break}}}}switch(t.endpoint=rt(t.endpoint,e),t.queryParams=E,t.headers=w,N){case 6:t.body=f;break;case 5:t.body=x;break;case 7:t.body=T;break;case 1:t.body=m;break}return}throw X}function et(t){const n=t.get("Content-Length");if(!n)return 0;const r=Number(n);if(isNaN(r))return 0;return r}function Tt(t){return t.get("Content-Type")||""}function ct(t){const{request:n,content:r,contentType:o}=t,s=n.responseType;if(!s)return null;switch(s){case"json":{const c=new TextDecoder().decode(r);if(c==="")return null;return console.log(c),JSON.parse(c)}case"text":return new TextDecoder().decode(r);case"blob":return new Blob([r],{type:o});case"arraybuffer":return r.buffer;default:return null}}function st(t,n){const r=new Uint8Array(n);let o=0;for(let s of t)r.set(s,o),o+=s.length;return r}function _t(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 c=xt(t.body);if(c)r.set("Content-Type",c)}if(!r.has("Accept"))r.set("Accept","application/json, text/plain, */*");const o=t.withCredentials?"include":void 0,s=t.context?.get(Et)||{};return new Request(n,{...s,headers:r,method:t.method,body:ot(t.body),signal:t.abort,credentials:o})}async function b(t){const n=t.downloadProgress,r=_t(t);let o;try{o=await(globalThis||window).fetch(r)}catch(x){if(x instanceof DOMException)switch(!0){case(x.name==="AbortError"||x.code===x.ABORT_ERR):throw new _({error:$});case(x.name==="TimeoutError"||x.code===x.TIMEOUT_ERR):throw new _({error:K})}throw new _({error:x})}const{ok:s,headers:c,status:i,statusText:R,url:e}=o,E=et(c),w=Tt(c);let T=null;if(o.body){const x=[],m=o.body.getReader();let f=0;while(!0){const{done:H,value:A}=await m.read();if(H)break;x.push(A),f+=A.length,n?.({lengthComputable:E>0,loaded:f,total:E})}const N=st(x,f);try{T=ct({request:t,content:N,contentType:w})}catch(H){throw new _({error:H,status:i,statusText:R,headers:c,url:e})}}if(!s)throw new _({status:i,statusText:R,headers:c,url:e,body:T});return D({url:e,status:i,statusText:R,headers:c,body:T})}var Et=Y(()=>({}));function L(t){return typeof t==="object"&&t!==null&&P in t}function z(t){if(!L(t))throw J;return t[P]}function wt(t){const n={host:t.host,interceptors:t.interceptors??[],handler:t.handler||b};return{[P]:n}}function ht(t,n){const o={...z(t),...n};return{[P]:o}}function d(){if(!a)throw Q;return a}function At(t){a=t}function Ft(){a=void 0}function It(t){a=wt(t)}var P=Symbol("Client"),a;function Ot(t,n){let r=n?.encode;if(!r){const o=(globalThis||window).btoa;if(typeof o!=="function")throw new Error("BasicAuthInterceptor is not supported in this environment");r=(s)=>o(`${s.username}:${s.password}`)}return(o,s)=>{const c=o.headers||new Headers;return c.set("Authorization",`Basic ${r(t())}`),o.headers=c,s(o)}}var at=(t)=>{if(!t)return new Error("required");return null},gt=(t)=>{if(typeof t!=="boolean"||!t)return new Error("requiredTrue");return null},Ut=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length<t)return new Error(`minLength ${t}`);return null}},Vt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length>t)return new Error(`maxLength ${t}`);return null}},Bt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n<t)return new Error(`minLength ${t}`);return null}},Dt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n>t)return new Error(`maxLength ${t}`);return null}},Lt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(!t.test(n))return new Error("pattern");return null}};export{Rt as validatorField,At as setGlobalClient,Ft as restGlobalClient,gt as requiredTrue,at as required,Lt as pattern,Ut as minLength,Bt as min,Vt as maxLength,Dt as max,Y as makeHttpContextToken,Z as makeHttpContext,j as isHttpContextToken,B as isFieldGroup,O as isField,L as isClient,d as getGlobalClient,pt as field,b as fetchHandler,Nt as defineRequest,It as createGlobalClient,wt as createClient,ht as cloneClient,Ot as basicAuthInterceptor,ft as asyncValidatorField,_ as HttpErrorResponse,Et as FETCH_CONFIG_KEY,X as ERR_UNSUPPORTED_FIELD_TYPE,it as ERR_UNKNOWN,K as ERR_TIMEOUT,W as ERR_OBSERVE,h as ERR_NOT_SET_ALIAS,y as ERR_NOT_FOUND_HANDLER,Q as ERR_NOT_FOUND_GLOBAL_CLIENT,Ht as ERR_NETWORK,V as ERR_INVALID_HTTP_CONTEXT_TOKEN,J as ERR_INVALID_CLIENT,$ as ERR_ABORTED};
package/index.js CHANGED
@@ -1,20 +1,46 @@
1
1
  // src/error.ts
2
- function __withErrorCause(err, cause) {
3
- err.cause = cause;
4
- return err;
5
- }
6
2
  var ERR_ABORTED = new Error("ERR_ABORTED");
7
3
  var ERR_TIMEOUT = new Error("ERR_TIMEOUT");
8
4
  var ERR_NETWORK = new Error("ERR_NETWORK");
9
5
  var ERR_NOT_FOUND_HANDLER = new Error("ERR_NOT_FOUND_HANDLER");
10
- var ERR_TRANSFORM_RESPONSE = new Error("ERR_TRANSFORM_RESPONSE");
11
- var ERR_STREAMING_NOT_IMPLEMENTED = new Error("ERR_STREAMING_NOT_IMPLEMENTED");
12
6
  var ERR_OBSERVE = new Error("ERR_OBSERVE");
13
7
  var ERR_NOT_SET_ALIAS = new Error("ERR_NOT_SET_ALIAS");
14
8
  var ERR_UNSUPPORTED_FIELD_TYPE = new Error("ERR_UNSUPPORTED_FIELD_TYPE");
15
9
  var ERR_INVALID_CLIENT = new Error("ERR_INVALID_CLIENT");
16
10
  var ERR_NOT_FOUND_GLOBAL_CLIENT = new Error("ERR_NOT_FOUND_GLOBAL_CLIENT");
17
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
+ ok;
20
+ body;
21
+ constructor(init) {
22
+ const status = init.status ?? 0;
23
+ const statusText = init.statusText ?? "";
24
+ const ok = status >= 200 && status < 300;
25
+ const headers = init.headers ?? new Headers;
26
+ const url = init.url ?? null;
27
+ const body = init.body ?? null;
28
+ let message;
29
+ if (ok) {
30
+ message = `Http failure during parsing for ${init.url || "(unknown url)"}`;
31
+ } else {
32
+ message = `Http failure response for ${init.url || "(unknown url)"}: ${init.status} ${init.statusText}`;
33
+ }
34
+ super(message, { cause: init.error });
35
+ super.name = "HttpErrorResponse";
36
+ this.statusText = statusText;
37
+ this.url = url;
38
+ this.headers = headers;
39
+ this.status = status;
40
+ this.ok = ok;
41
+ this.body = body;
42
+ }
43
+ }
18
44
 
19
45
  // src/context.ts
20
46
  function makeHttpContextToken(defaultValue) {
@@ -88,6 +114,10 @@ function field(defaultValue) {
88
114
  meta.alias.set(4 /* Header */, alias);
89
115
  return getter;
90
116
  };
117
+ getter.withUrlForm = (alias) => {
118
+ meta.alias.set(7 /* UrlForm */, alias);
119
+ return getter;
120
+ };
91
121
  getter.withBody = () => {
92
122
  meta.alias.set(6 /* Body */, undefined);
93
123
  return getter;
@@ -141,44 +171,20 @@ function makeInterceptorChain(interceptors) {
141
171
  }
142
172
 
143
173
  // src/response.ts
144
- function isHttpResponse(value) {
145
- return typeof value === "object" && value !== null && HTTP_RESPONSE in value;
146
- }
147
- function isHttpResponseError(value) {
148
- return isHttpResponse(value) && !value.ok;
149
- }
150
- function makeResponse(options) {
174
+ function __makeResponse(options) {
151
175
  const status = options.status ?? 0;
152
176
  const statusText = options.statusText ?? "";
153
- const ok = status >= 200 && status < 300;
154
177
  const url = options.url ?? "";
155
178
  const headers = options.headers ?? new Headers;
156
179
  const body = options.body ?? null;
157
- if (!ok || options.error) {
158
- const error2 = options.error || new Error(`Http failure response for ${options.url}: ${status} ${statusText}`);
159
- return {
160
- ok: false,
161
- error: error2,
162
- status,
163
- statusText,
164
- url,
165
- headers,
166
- body,
167
- [HTTP_RESPONSE]: null
168
- };
169
- }
170
180
  return {
171
- ok: true,
172
- error: null,
173
181
  status,
174
182
  statusText,
175
183
  url,
176
184
  headers,
177
- body,
178
- [HTTP_RESPONSE]: null
185
+ body
179
186
  };
180
187
  }
181
- var HTTP_RESPONSE = Symbol("HTTP_RESPONSE");
182
188
 
183
189
  // src/request.ts
184
190
  function __serializeBody(body) {
@@ -186,6 +192,7 @@ function __serializeBody(body) {
186
192
  case body instanceof FormData:
187
193
  case body instanceof Blob:
188
194
  case body instanceof ArrayBuffer:
195
+ case body instanceof URLSearchParams:
189
196
  case typeof body === "string":
190
197
  return body;
191
198
  case typeof body === "object":
@@ -219,7 +226,7 @@ function __detectContentTypeHeader(body) {
219
226
  return null;
220
227
  }
221
228
  }
222
- function __buildFieldValue(input) {
229
+ function __buildFieldDefaultValue(input) {
223
230
  if (isField(input)) {
224
231
  return input();
225
232
  }
@@ -232,21 +239,26 @@ function __buildFieldValue(input) {
232
239
  }
233
240
  return;
234
241
  }
235
- function defineRequest(options) {
236
- const requestOptions = {
237
- ...options
238
- };
239
- const requiredInput = !!requestOptions.input;
240
- return () => {
242
+ function defineRequest(method, endpoint) {
243
+ let requiredInput = false;
244
+ let field3;
245
+ let interceptors = [];
246
+ let responseType = "json";
247
+ let context2;
248
+ let observe = "body";
249
+ let withCredentials = false;
250
+ let validators = [];
251
+ let transformResponse;
252
+ const fn = () => {
241
253
  let uploadProgress;
242
254
  let downloadProgress;
243
- let abortController;
244
255
  let abortSignal;
245
- const setUploadProgress = (fn) => {
246
- uploadProgress = fn;
256
+ const getInitValue = () => __buildFieldDefaultValue(field3);
257
+ const setUploadProgress = (fn2) => {
258
+ uploadProgress = fn2;
247
259
  };
248
- const setDownloadProgress = (fn) => {
249
- downloadProgress = fn;
260
+ const setDownloadProgress = (fn2) => {
261
+ downloadProgress = fn2;
250
262
  };
251
263
  const doRequest = async (...args) => {
252
264
  let input;
@@ -265,28 +277,30 @@ function defineRequest(options) {
265
277
  if (requiredInput && !input) {
266
278
  throw new Error(`Because the request has input, the first argument must be the input value`);
267
279
  }
280
+ if (validators.length > 0) {
281
+ for (const fn2 of validators) {
282
+ fn2(input);
283
+ }
284
+ }
268
285
  const timeout = doRequestOptions?.timeout || 0;
269
286
  if (doRequestOptions?.abort) {
270
287
  abortSignal = doRequestOptions.abort;
271
288
  } else if (timeout > 0) {
272
289
  abortSignal = AbortSignal.timeout(timeout);
273
- } else {
274
- abortController = new AbortController;
275
- abortSignal = abortController.signal;
276
290
  }
277
291
  const client2 = isClient(doRequestOptions?.client) ? doRequestOptions.client : getGlobalClient();
278
292
  const clientOptions = getClientConfig(client2);
279
293
  const req = {
280
294
  host: clientOptions?.host,
281
- method: requestOptions.method,
282
- endpoint: requestOptions.endpoint,
295
+ method,
296
+ endpoint,
283
297
  queryParams: new URLSearchParams,
284
298
  headers: new Headers,
285
299
  body: undefined,
286
- withCredentials: requestOptions.withCredentials,
287
- responseType: requestOptions.responseType ?? "json",
288
- context: requestOptions.context || makeHttpContext(),
289
- observe: requestOptions.observe ?? "body",
300
+ withCredentials,
301
+ responseType,
302
+ context: context2 || makeHttpContext(),
303
+ observe,
290
304
  uploadProgress,
291
305
  downloadProgress,
292
306
  timeout,
@@ -297,47 +311,23 @@ function defineRequest(options) {
297
311
  throw ERR_NOT_FOUND_HANDLER;
298
312
  }
299
313
  if (requiredInput) {
300
- await __fillRequestFromField(req, requestOptions.input, input);
301
- }
302
- if (typeof requestOptions.transformRequest === "function") {
303
- req.body = requestOptions.transformRequest(input, req);
304
- }
305
- const chain = makeInterceptorChain([...clientOptions?.interceptors || [], ...requestOptions?.interceptors || []]);
306
- let res;
307
- try {
308
- res = await chain(req, handler2);
309
- } catch (error3) {
310
- if (error3 instanceof DOMException) {
311
- switch (true) {
312
- case (error3.name === "AbortError" || error3.code === error3.ABORT_ERR):
313
- throw ERR_ABORTED;
314
- case (error3.name === "TimeoutError" || error3.code === error3.TIMEOUT_ERR):
315
- throw ERR_TIMEOUT;
316
- }
317
- }
318
- throw makeResponse({
319
- error: __withErrorCause(ERR_NETWORK, error3)
320
- });
314
+ await __fillRequestFromField(req, field3, input);
321
315
  }
322
- if (typeof requestOptions.transformResponse === "function") {
316
+ const chain = makeInterceptorChain([...interceptors]);
317
+ let res = await chain(req, handler2);
318
+ if (typeof transformResponse === "function") {
323
319
  try {
324
- res = makeResponse({
320
+ res = __makeResponse({
325
321
  ...res,
326
- body: requestOptions.transformResponse(res),
327
- error: undefined
322
+ body: transformResponse(res)
328
323
  });
329
324
  } catch (error3) {
330
- throw makeResponse({
331
- ...res,
332
- error: __withErrorCause(ERR_TRANSFORM_RESPONSE, error3)
333
- });
325
+ throw new HttpErrorResponse({ error: error3 });
334
326
  }
335
327
  }
336
328
  switch (req.observe) {
337
329
  case "body":
338
330
  return res.body;
339
- case "stream":
340
- throw ERR_STREAMING_NOT_IMPLEMENTED;
341
331
  case "response":
342
332
  return res;
343
333
  default:
@@ -346,11 +336,46 @@ function defineRequest(options) {
346
336
  };
347
337
  return {
348
338
  doRequest,
349
- inputValue: __buildFieldValue(requestOptions.input),
339
+ getInitValue,
350
340
  setUploadProgress,
351
341
  setDownloadProgress
352
342
  };
353
343
  };
344
+ fn.withField = (value) => {
345
+ field3 = value;
346
+ requiredInput = true;
347
+ return fn;
348
+ };
349
+ fn.withInterceptors = (value) => {
350
+ interceptors = value;
351
+ return fn;
352
+ };
353
+ fn.withContext = (value) => {
354
+ context2 = value;
355
+ return fn;
356
+ };
357
+ fn.withCredentials = (value) => {
358
+ withCredentials = value;
359
+ return fn;
360
+ };
361
+ fn.withValidators = (value) => {
362
+ validators = value;
363
+ console.log(validators);
364
+ return fn;
365
+ };
366
+ fn.withTransformResponse = (value) => {
367
+ transformResponse = value;
368
+ return fn;
369
+ };
370
+ fn.withObserve = (value) => {
371
+ observe = value;
372
+ return fn;
373
+ };
374
+ fn.withResponseType = (value) => {
375
+ responseType = value;
376
+ return fn;
377
+ };
378
+ return fn;
354
379
  }
355
380
  function __fillUrl(endpoint, params) {
356
381
  return endpoint.replace(/:([^\/]+)/g, (_, p1) => {
@@ -370,24 +395,37 @@ async function __fillRequestFromField(request, fieldOrFieldGroup, input) {
370
395
  function inputIsObject(input2) {
371
396
  return typeof input2 === "object" && input2 !== null;
372
397
  }
398
+ function serializeToString(value) {
399
+ switch (true) {
400
+ case Array.isArray(value):
401
+ case (typeof value === "object" && value !== null):
402
+ return JSON.stringify(value);
403
+ case (typeof value === "object" && value === null):
404
+ case typeof value === "boolean":
405
+ case typeof value === "number":
406
+ case typeof value === "string":
407
+ return String(value);
408
+ default:
409
+ throw new Error("Unsupported value type");
410
+ }
411
+ }
373
412
  function appendValue(sp, key, value) {
374
413
  if (Array.isArray(value)) {
375
414
  for (const v of value) {
376
- sp.append(key, String(v));
415
+ sp.append(key, serializeToString(v));
377
416
  }
378
417
  } else {
379
- sp.set(key, String(value));
418
+ sp.set(key, serializeToString(value));
380
419
  }
381
420
  return sp;
382
421
  }
383
422
  function setValue(sp, key, value) {
384
423
  if (Array.isArray(value)) {
385
424
  for (const v of value) {
386
- sp.set(key, String(v));
425
+ setValue(sp, key, serializeToString(v));
387
426
  }
388
- } else {
389
- sp.set(key, String(value));
390
427
  }
428
+ sp.set(key, serializeToString(value));
391
429
  return sp;
392
430
  }
393
431
  if (isField(fieldOrFieldGroup)) {
@@ -431,6 +469,13 @@ async function __fillRequestFromField(request, fieldOrFieldGroup, input) {
431
469
  body = appendValue(new FormData, aliasName, fieldValue);
432
470
  break;
433
471
  }
472
+ case 7 /* UrlForm */: {
473
+ if (!aliasName) {
474
+ throw ERR_NOT_SET_ALIAS;
475
+ }
476
+ body = appendValue(new URLSearchParams, aliasName, fieldValue);
477
+ break;
478
+ }
434
479
  case 1 /* Json */:
435
480
  case 6 /* Body */:
436
481
  body = fieldValue;
@@ -449,9 +494,11 @@ async function __fillRequestFromField(request, fieldOrFieldGroup, input) {
449
494
  let params = new Map;
450
495
  let queryParams = new URLSearchParams;
451
496
  let headers = new Headers;
497
+ let urlForm = new URLSearchParams;
452
498
  let formData = new FormData;
453
499
  const json = {};
454
500
  let body = undefined;
501
+ let lastBodyField;
455
502
  for (const [propertyKey, field3] of Object.entries(fieldOrFieldGroup)) {
456
503
  const meta = __getFieldMetadata(field3);
457
504
  for (const [type, aliasName] of meta.alias) {
@@ -462,13 +509,15 @@ async function __fillRequestFromField(request, fieldOrFieldGroup, input) {
462
509
  throw err;
463
510
  }
464
511
  switch (type) {
465
- case 1 /* Json */:
512
+ case 1 /* Json */: {
466
513
  Object.defineProperty(json, valueKey, {
467
514
  value,
468
515
  writable: true,
469
516
  enumerable: true
470
517
  });
518
+ lastBodyField = 1 /* Json */;
471
519
  break;
520
+ }
472
521
  case 2 /* Query */:
473
522
  queryParams = appendValue(queryParams, valueKey, value);
474
523
  break;
@@ -478,24 +527,40 @@ async function __fillRequestFromField(request, fieldOrFieldGroup, input) {
478
527
  case 4 /* Header */:
479
528
  headers = appendValue(headers, valueKey, value);
480
529
  break;
481
- case 5 /* Form */:
530
+ case 5 /* Form */: {
482
531
  formData = appendValue(formData, valueKey, value);
532
+ lastBodyField = 5 /* Form */;
483
533
  break;
484
- case 6 /* Body */:
534
+ }
535
+ case 7 /* UrlForm */: {
536
+ urlForm = appendValue(urlForm, valueKey, value);
537
+ lastBodyField = 7 /* UrlForm */;
538
+ break;
539
+ }
540
+ case 6 /* Body */: {
485
541
  body = value;
542
+ lastBodyField = 6 /* Body */;
486
543
  break;
544
+ }
487
545
  }
488
546
  }
489
547
  }
490
548
  request.endpoint = __fillUrl(request.endpoint, params);
491
549
  request.queryParams = queryParams;
492
550
  request.headers = headers;
493
- if (body) {
494
- request.body = body;
495
- } else if (Array.from(formData.keys()).length > 0) {
496
- request.body = formData;
497
- } else if (Object.keys(json).length) {
498
- request.body = json;
551
+ switch (lastBodyField) {
552
+ case 6 /* Body */:
553
+ request.body = body;
554
+ break;
555
+ case 5 /* Form */:
556
+ request.body = formData;
557
+ break;
558
+ case 7 /* UrlForm */:
559
+ request.body = urlForm;
560
+ break;
561
+ case 1 /* Json */:
562
+ request.body = json;
563
+ break;
499
564
  }
500
565
  return;
501
566
  }
@@ -503,7 +568,7 @@ async function __fillRequestFromField(request, fieldOrFieldGroup, input) {
503
568
  }
504
569
 
505
570
  // src/handler/util.ts
506
- function getContentLength(headers) {
571
+ function __getContentLength(headers) {
507
572
  const value = headers.get("Content-Length");
508
573
  if (!value) {
509
574
  return 0;
@@ -514,10 +579,10 @@ function getContentLength(headers) {
514
579
  }
515
580
  return num;
516
581
  }
517
- function getContentType(headers) {
582
+ function __getContentType(headers) {
518
583
  return headers.get("Content-Type") || "";
519
584
  }
520
- function parseBody(params) {
585
+ function __parseBody(params) {
521
586
  const { request, content, contentType } = params;
522
587
  const responseType = request.responseType;
523
588
  if (!responseType) {
@@ -529,6 +594,7 @@ function parseBody(params) {
529
594
  if (text === "") {
530
595
  return null;
531
596
  }
597
+ console.log(text);
532
598
  return JSON.parse(text);
533
599
  }
534
600
  case "text":
@@ -542,7 +608,7 @@ function parseBody(params) {
542
608
  return null;
543
609
  }
544
610
  }
545
- function concatChunks(chunks, totalLength) {
611
+ function __concatChunks(chunks, totalLength) {
546
612
  const chunksAll = new Uint8Array(totalLength);
547
613
  let position = 0;
548
614
  for (const chunk of chunks) {
@@ -582,10 +648,23 @@ function __createRequest(request2) {
582
648
  async function fetchHandler(httpRequest) {
583
649
  const downloadProgress = httpRequest.downloadProgress;
584
650
  const request2 = __createRequest(httpRequest);
585
- const response3 = await (globalThis || window).fetch(request2);
586
- const { headers, status, statusText, url } = response3;
587
- const contentLength = getContentLength(headers);
588
- const contentType = getContentType(headers);
651
+ let response3;
652
+ try {
653
+ response3 = await (globalThis || window).fetch(request2);
654
+ } catch (error4) {
655
+ if (error4 instanceof DOMException) {
656
+ switch (true) {
657
+ case (error4.name === "AbortError" || error4.code === error4.ABORT_ERR):
658
+ throw new HttpErrorResponse({ error: ERR_ABORTED });
659
+ case (error4.name === "TimeoutError" || error4.code === error4.TIMEOUT_ERR):
660
+ throw new HttpErrorResponse({ error: ERR_TIMEOUT });
661
+ }
662
+ }
663
+ throw new HttpErrorResponse({ error: error4 });
664
+ }
665
+ const { ok, headers, status, statusText, url } = response3;
666
+ const contentLength = __getContentLength(headers);
667
+ const contentType = __getContentType(headers);
589
668
  let body = null;
590
669
  if (response3.body) {
591
670
  const chunks = [];
@@ -604,14 +683,33 @@ async function fetchHandler(httpRequest) {
604
683
  total: contentLength
605
684
  });
606
685
  }
607
- const chunksAll = concatChunks(chunks, receivedLength);
608
- body = parseBody({
609
- request: httpRequest,
610
- content: chunksAll,
611
- contentType
686
+ const chunksAll = __concatChunks(chunks, receivedLength);
687
+ try {
688
+ body = __parseBody({
689
+ request: httpRequest,
690
+ content: chunksAll,
691
+ contentType
692
+ });
693
+ } catch (error4) {
694
+ throw new HttpErrorResponse({
695
+ error: error4,
696
+ status,
697
+ statusText,
698
+ headers,
699
+ url
700
+ });
701
+ }
702
+ }
703
+ if (!ok) {
704
+ throw new HttpErrorResponse({
705
+ status,
706
+ statusText,
707
+ headers,
708
+ url,
709
+ body
612
710
  });
613
711
  }
614
- return makeResponse({
712
+ return __makeResponse({
615
713
  url,
616
714
  status,
617
715
  statusText,
@@ -746,9 +844,6 @@ var pattern = (pattern2) => {
746
844
  if (typeof value !== "string") {
747
845
  return new Error("invalid string");
748
846
  }
749
- if (typeof pattern2 === "string") {
750
- pattern2 = new RegExp(pattern2);
751
- }
752
847
  if (!pattern2.test(value)) {
753
848
  return new Error("pattern");
754
849
  }
@@ -766,11 +861,8 @@ export {
766
861
  min,
767
862
  maxLength,
768
863
  max,
769
- makeResponse,
770
864
  makeHttpContextToken,
771
865
  makeHttpContext,
772
- isHttpResponseError,
773
- isHttpResponse,
774
866
  isHttpContextToken,
775
867
  isFieldGroup,
776
868
  isField,
@@ -784,11 +876,11 @@ export {
784
876
  cloneClient,
785
877
  basicAuthInterceptor,
786
878
  asyncValidatorField,
879
+ HttpErrorResponse,
787
880
  FETCH_CONFIG_KEY,
788
881
  ERR_UNSUPPORTED_FIELD_TYPE,
789
- ERR_TRANSFORM_RESPONSE,
882
+ ERR_UNKNOWN,
790
883
  ERR_TIMEOUT,
791
- ERR_STREAMING_NOT_IMPLEMENTED,
792
884
  ERR_OBSERVE,
793
885
  ERR_NOT_SET_ALIAS,
794
886
  ERR_NOT_FOUND_HANDLER,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defjs/core",
3
- "version": "0.0.0-test-001",
3
+ "version": "0.0.0-test-002",
4
4
  "type": "module",
5
5
  "module": "index.js",
6
6
  "typings": "index.d.ts",
package/index.min.js DELETED
@@ -1 +0,0 @@
1
- function U(t,n){return t.cause=n,t}var l=new Error("ERR_ABORTED"),h=new Error("ERR_TIMEOUT"),L=new Error("ERR_NETWORK"),P=new Error("ERR_NOT_FOUND_HANDLER"),D=new Error("ERR_TRANSFORM_RESPONSE"),M=new Error("ERR_STREAMING_NOT_IMPLEMENTED"),d=new Error("ERR_OBSERVE"),m=new Error("ERR_NOT_SET_ALIAS"),O=new Error("ERR_UNSUPPORTED_FIELD_TYPE"),g=new Error("ERR_INVALID_CLIENT"),S=new Error("ERR_NOT_FOUND_GLOBAL_CLIENT"),u=new Error("ERR_INVALID_HTTP_CONTEXT_TOKEN");function X(t){return Object.defineProperty(t,z,{value:t}),t}function $(t){return typeof t==="function"&&z in t}function J(){const t=new Map;return{set(n,r){if(!$(n))throw u;return t.set(n,r),this},get(n){if(!$(n))throw u;if(!t.has(n))t.set(n,n());return t.get(n)},del(n){return t.delete(n),this},has(n){return t.has(n)},keys(){return t.keys()}}}var z=Symbol("HttpContextToken");function it(t){const n={alias:new Map,validators:[],asyncValidator:[]},r=()=>t;return Object.defineProperty(r,K,{value:n}),r.withJson=(o)=>{return n.alias.set(1,o),r},r.withForm=(o)=>{return n.alias.set(5,o),r},r.withQuery=(o)=>{return n.alias.set(2,o),r},r.withParam=(o)=>{return n.alias.set(3,o),r},r.withHeader=(o)=>{return n.alias.set(4,o),r},r.withBody=()=>{return n.alias.set(6,void 0),r},r.withValidators=(...o)=>{return n.validators=o,r},r.withAsyncValidators=(...o)=>{return n.asyncValidator=o,r},r}function Q(t){return t[K]}function pt(t,n){for(let r of t){const o=r(n);if(o)throw o}}async function ct(t,n){for(let r of t){const o=await r(n);if(o)throw o}}function A(t){return!!t&&typeof t==="function"&&K in t}function y(t){return!!t&&typeof t==="object"&&Object.entries(t).every(([,n])=>A(n))}var K=Symbol("field");var ft=void 0;var G=()=>ft;function b(t){return t.reduceRight((n,r)=>{return(o,T)=>r(o,(x)=>n(x,T))},(n,r)=>r(n))}function v(t){return typeof t==="object"&&t!==null&&j in t}function Rt(t){return v(t)&&!t.ok}function _(t){const n=t.status??0,r=t.statusText??"",o=n>=200&&n<300,T=t.url??"",x=t.headers??new Headers,a=t.body??null;if(!o||t.error)return{ok:!1,error:t.error||new Error(`Http failure response for ${t.url}: ${n} ${r}`),status:n,statusText:r,url:T,headers:x,body:a,[j]:null};return{ok:!0,error:null,status:n,statusText:r,url:T,headers:x,body:a,[j]:null}}var j=Symbol("HTTP_RESPONSE");function tt(t){switch(!0){case t instanceof FormData:case t instanceof Blob:case t instanceof ArrayBuffer: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 nt(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 Ht(t){if(A(t))return t();if(y(t)){const n={};for(let[r,o]of Object.entries(t))n[r]=o();return n}return}function wt(t){const n={...t},r=!!n.input;return()=>{let o,T,x,a;const E=(e)=>{o=e},i=(e)=>{T=e};return{doRequest:async(...e)=>{let c,f;switch(e.length){case 1:{f=e[0];break}case 2:{c=e[0],f=e[1];break}}if(r&&!c)throw new Error("Because the request has input, the first argument must be the input value");const w=f?.timeout||0;if(f?.abort)a=f.abort;else if(w>0)a=AbortSignal.timeout(w);else x=new AbortController,a=x.signal;const F=B(f?.client)?f.client:Y(),R=W(F),k={host:R?.host,method:n.method,endpoint:n.endpoint,queryParams:new URLSearchParams,headers:new Headers,body:void 0,withCredentials:n.withCredentials,responseType:n.responseType??"json",context:n.context||J(),observe:n.observe??"body",uploadProgress:o,downloadProgress:T,timeout:w,abort:a},I=f?.handler||R?.handler||G();if(!I)throw P;if(r)await st(k,n.input,c);if(typeof n.transformRequest==="function")k.body=n.transformRequest(c,k);const N=b([...R?.interceptors||[],...n?.interceptors||[]]);let H;try{H=await N(k,I)}catch(s){if(s instanceof DOMException)switch(!0){case(s.name==="AbortError"||s.code===s.ABORT_ERR):throw l;case(s.name==="TimeoutError"||s.code===s.TIMEOUT_ERR):throw h}throw _({error:U(L,s)})}if(typeof n.transformResponse==="function")try{H=_({...H,body:n.transformResponse(H),error:void 0})}catch(s){throw _({...H,error:U(D,s)})}switch(k.observe){case"body":return H.body;case"stream":throw M;case"response":return H;default:throw d}},inputValue:Ht(n.input),setUploadProgress:E,setDownloadProgress:i}}}function q(t,n){return t.replace(/:([^\/]+)/g,(r,o)=>{return n.get(o)??"undefined"})}async function st(t,n,r){async function o(E,i){for(let p of E){const e=await p(i);if(e)return e}return}function T(E){return typeof E==="object"&&E!==null}function x(E,i,p){if(Array.isArray(p))for(let e of p)E.append(i,String(e));else E.set(i,String(p));return E}function a(E,i,p){if(Array.isArray(p))for(let e of p)E.set(i,String(e));else E.set(i,String(p));return E}if(A(n)){let E,i,p,e=void 0;const c=r??n(),f=Q(n),w=await o([...f.validators,...f.asyncValidator],c);if(w)throw w;for(let[F,R]of f.alias)switch(F){case 2:{if(!R)throw m;i=x(new URLSearchParams,R,c);break}case 3:{if(!R)throw m;E=a(new Map,R,c);break}case 4:{if(!R)throw m;p=x(new Headers,R,c);break}case 5:{if(!R)throw m;e=x(new FormData,R,c);break}case 1:case 6:e=c;break}if(E)t.endpoint=q(t.endpoint,E);t.queryParams=i,t.headers=p,t.body=e;return}if(y(n)&&T(r)){let E=new Map,i=new URLSearchParams,p=new Headers,e=new FormData;const c={};let f=void 0;for(let[w,F]of Object.entries(n)){const R=Q(F);for(let[k,I]of R.alias){const N=I||w,H=r[w]||F(),s=await o([...R.validators,...R.asyncValidator],H);if(s)throw s;switch(k){case 1:Object.defineProperty(c,N,{value:H,writable:!0,enumerable:!0});break;case 2:i=x(i,N,H);break;case 3:E=a(E,N,H);break;case 4:p=x(p,N,H);break;case 5:e=x(e,N,H);break;case 6:f=H;break}}}if(t.endpoint=q(t.endpoint,E),t.queryParams=i,t.headers=p,f)t.body=f;else if(Array.from(e.keys()).length>0)t.body=e;else if(Object.keys(c).length)t.body=c;return}throw O}function rt(t){const n=t.get("Content-Length");if(!n)return 0;const r=Number(n);if(isNaN(r))return 0;return r}function ot(t){return t.get("Content-Type")||""}function et(t){const{request:n,content:r,contentType:o}=t,T=n.responseType;if(!T)return null;switch(T){case"json":{const x=new TextDecoder().decode(r);if(x==="")return null;return JSON.parse(x)}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 at(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 x=nt(t.body);if(x)r.set("Content-Type",x)}if(!r.has("Accept"))r.set("Accept","application/json, text/plain, */*");const o=t.withCredentials?"include":void 0,T=t.context?.get(xt)||{};return new Request(n,{...T,headers:r,method:t.method,body:tt(t.body),signal:t.abort,credentials:o})}async function Z(t){const n=t.downloadProgress,r=at(t),o=await(globalThis||window).fetch(r),{headers:T,status:x,statusText:a,url:E}=o,i=rt(T),p=ot(T);let e=null;if(o.body){const c=[],f=o.body.getReader();let w=0;while(!0){const{done:R,value:k}=await f.read();if(R)break;c.push(k),w+=k.length,n?.({lengthComputable:i>0,loaded:w,total:i})}const F=Tt(c,w);e=et({request:t,content:F,contentType:p})}return _({url:E,status:x,statusText:a,headers:T,body:e})}var xt=X(()=>({}));function B(t){return typeof t==="object"&&t!==null&&V in t}function W(t){if(!B(t))throw g;return t[V]}function Et(t){const n={host:t.host,interceptors:t.interceptors??[],handler:t.handler||Z};return{[V]:n}}function kt(t,n){const o={...W(t),...n};return{[V]:o}}function Y(){if(!C)throw S;return C}function Ft(t){C=t}function Nt(){C=void 0}function _t(t){C=Et(t)}var V=Symbol("Client"),C;function mt(t,n){let r=n?.encode;if(!r){const o=(globalThis||window).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 x=o.headers||new Headers;return x.set("Authorization",`Basic ${r(t())}`),o.headers=x,T(o)}}var At=(t)=>{if(!t)return new Error("required");return null},Ct=(t)=>{if(typeof t!=="boolean"||!t)return new Error("requiredTrue");return null},It=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length<t)return new Error(`minLength ${t}`);return null}},ut=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length>t)return new Error(`maxLength ${t}`);return null}},yt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n<t)return new Error(`minLength ${t}`);return null}},Bt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n>t)return new Error(`maxLength ${t}`);return null}},Vt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(typeof t==="string")t=new RegExp(t);if(!t.test(n))return new Error("pattern");return null}};export{pt as validatorField,Ft as setGlobalClient,Nt as restGlobalClient,Ct as requiredTrue,At as required,Vt as pattern,It as minLength,yt as min,ut as maxLength,Bt as max,_ as makeResponse,X as makeHttpContextToken,J as makeHttpContext,Rt as isHttpResponseError,v as isHttpResponse,$ as isHttpContextToken,y as isFieldGroup,A as isField,B as isClient,Y as getGlobalClient,it as field,Z as fetchHandler,wt as defineRequest,_t as createGlobalClient,Et as createClient,kt as cloneClient,mt as basicAuthInterceptor,ct as asyncValidatorField,xt as FETCH_CONFIG_KEY,O as ERR_UNSUPPORTED_FIELD_TYPE,D as ERR_TRANSFORM_RESPONSE,h as ERR_TIMEOUT,M as ERR_STREAMING_NOT_IMPLEMENTED,d as ERR_OBSERVE,m as ERR_NOT_SET_ALIAS,P as ERR_NOT_FOUND_HANDLER,S as ERR_NOT_FOUND_GLOBAL_CLIENT,L as ERR_NETWORK,u as ERR_INVALID_HTTP_CONTEXT_TOKEN,g as ERR_INVALID_CLIENT,l as ERR_ABORTED};