@defjs/core 0.0.0-test-000 → 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 +56 -148
- package/index.es.min.js +1 -0
- package/index.js +257 -137
- package/package.json +1 -1
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:
|
|
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,36 +55,21 @@ 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 status: number;
|
|
61
|
-
readonly statusText: string;
|
|
59
|
+
export type HttpResponse<R> = {
|
|
62
60
|
readonly url: string;
|
|
63
|
-
readonly headers: Headers;
|
|
64
|
-
readonly body: R | null;
|
|
65
|
-
} | {
|
|
66
|
-
readonly ok: false;
|
|
67
|
-
readonly error: Error;
|
|
68
61
|
readonly status: number;
|
|
69
62
|
readonly statusText: string;
|
|
70
|
-
readonly url: string;
|
|
71
63
|
readonly headers: Headers;
|
|
72
|
-
readonly body: null;
|
|
73
|
-
}) & {
|
|
74
|
-
readonly [HTTP_RESPONSE]: unknown;
|
|
64
|
+
readonly body: R | null;
|
|
75
65
|
};
|
|
76
|
-
export declare function isHttpResponse<R>(value: unknown): value is HttpResponse<R>;
|
|
77
66
|
export type MakeResponseOptions<R> = {
|
|
78
67
|
status?: number;
|
|
79
68
|
statusText?: string;
|
|
80
69
|
url?: string;
|
|
81
70
|
headers?: Headers;
|
|
82
71
|
body?: R | null;
|
|
83
|
-
error?: Error;
|
|
84
72
|
};
|
|
85
|
-
export declare function makeResponse<R>(options: MakeResponseOptions<R>): HttpResponse<R>;
|
|
86
73
|
export type InterceptorFn = (req: HttpRequest, next: HttpHandler) => Promise<HttpResponse<unknown>>;
|
|
87
74
|
export type BasicCredential = {
|
|
88
75
|
username: string;
|
|
@@ -108,13 +95,12 @@ export interface HttpProgressEvent {
|
|
|
108
95
|
readonly total: number;
|
|
109
96
|
}
|
|
110
97
|
export type HttpProgressFn = (event: HttpProgressEvent) => void;
|
|
111
|
-
export type TransformRequestFn<Input = unknown> = (input: Input, request: HttpRequest) => HttpRequest["body"];
|
|
112
98
|
export type TransformResponseFn<Output = unknown> = (response: HttpResponse<unknown>) => Output;
|
|
113
99
|
export interface HttpRequest {
|
|
114
100
|
host?: string;
|
|
115
101
|
method: string;
|
|
116
102
|
endpoint: string;
|
|
117
|
-
body?: Blob | ArrayBuffer | FormData | object | string | number | boolean | null;
|
|
103
|
+
body?: Blob | ArrayBuffer | FormData | URLSearchParams | object | string | number | boolean | null;
|
|
118
104
|
headers?: Headers;
|
|
119
105
|
queryParams?: URLSearchParams;
|
|
120
106
|
/** default:json */
|
|
@@ -127,10 +113,8 @@ export interface HttpRequest {
|
|
|
127
113
|
downloadProgress?: HttpProgressFn;
|
|
128
114
|
/**
|
|
129
115
|
* default:body
|
|
130
|
-
*
|
|
131
|
-
* @todo Implement streaming response
|
|
132
116
|
*/
|
|
133
|
-
observe?: "body" | "
|
|
117
|
+
observe?: "body" | "response";
|
|
134
118
|
abort?: AbortSignal;
|
|
135
119
|
}
|
|
136
120
|
export type RequestInputValue<T> = T extends Field<infer V> ? V : T extends {
|
|
@@ -138,29 +122,16 @@ export type RequestInputValue<T> = T extends Field<infer V> ? V : T extends {
|
|
|
138
122
|
} ? {
|
|
139
123
|
[K in keyof T]: RequestInputValue<T[K]>;
|
|
140
124
|
} : never;
|
|
141
|
-
export type RequestOptions<Output = unknown, Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined> = {
|
|
142
|
-
method: string;
|
|
143
|
-
endpoint: string;
|
|
144
|
-
input?: Input;
|
|
145
|
-
interceptors?: InterceptorFn[];
|
|
146
|
-
responseType?: HttpResponseType;
|
|
147
|
-
context?: HttpContext;
|
|
148
|
-
observe?: "body" | "response";
|
|
149
|
-
withCredentials?: boolean;
|
|
150
|
-
validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
|
|
151
|
-
transformRequest?: TransformRequestFn;
|
|
152
|
-
transformResponse?: TransformResponseFn<Output>;
|
|
153
|
-
};
|
|
154
125
|
export type DoRequestOptions = {
|
|
155
126
|
abort?: AbortSignal;
|
|
156
127
|
handler?: HttpHandler;
|
|
157
128
|
client?: Client;
|
|
158
129
|
timeout?: number;
|
|
159
130
|
};
|
|
160
|
-
export type
|
|
161
|
-
export type UseRequestFn<Output
|
|
162
|
-
doRequest:
|
|
163
|
-
|
|
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 {
|
|
164
135
|
[K in keyof Input]: Field<any>;
|
|
165
136
|
} ? {
|
|
166
137
|
[K in keyof Input]: RequestInputValue<Input[K]>;
|
|
@@ -168,112 +139,22 @@ export type UseRequestFn<Output = unknown, Input = unknown> = () => {
|
|
|
168
139
|
setUploadProgress: (fn: HttpProgressFn) => void;
|
|
169
140
|
setDownloadProgress: (fn: HttpProgressFn) => void;
|
|
170
141
|
};
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
endpoint: string;
|
|
188
|
-
input?: Input;
|
|
189
|
-
interceptors?: InterceptorFn[];
|
|
190
|
-
responseType: "text";
|
|
191
|
-
observe?: "body";
|
|
192
|
-
context?: HttpContext;
|
|
193
|
-
withCredentials?: boolean;
|
|
194
|
-
validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
|
|
195
|
-
transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
|
|
196
|
-
transformResponse?: TransformResponseFn;
|
|
197
|
-
}): UseRequestFn<string, Input>;
|
|
198
|
-
export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
|
|
199
|
-
method: string;
|
|
200
|
-
endpoint: string;
|
|
201
|
-
input?: Input;
|
|
202
|
-
interceptors?: InterceptorFn[];
|
|
203
|
-
responseType: "blob";
|
|
204
|
-
observe?: "body";
|
|
205
|
-
context?: HttpContext;
|
|
206
|
-
withCredentials?: boolean;
|
|
207
|
-
validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
|
|
208
|
-
transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
|
|
209
|
-
transformResponse?: TransformResponseFn;
|
|
210
|
-
}): UseRequestFn<Blob, Input>;
|
|
211
|
-
export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
|
|
212
|
-
method: string;
|
|
213
|
-
endpoint: string;
|
|
214
|
-
input?: Input;
|
|
215
|
-
interceptors?: InterceptorFn[];
|
|
216
|
-
responseType: "arraybuffer";
|
|
217
|
-
observe?: "body";
|
|
218
|
-
context?: HttpContext;
|
|
219
|
-
withCredentials?: boolean;
|
|
220
|
-
validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
|
|
221
|
-
transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
|
|
222
|
-
transformResponse?: TransformResponseFn;
|
|
223
|
-
}): UseRequestFn<ArrayBuffer, Input>;
|
|
224
|
-
/** Observe: Response */
|
|
225
|
-
export declare function defineRequest<Output = unknown, Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
|
|
226
|
-
method: string;
|
|
227
|
-
endpoint: string;
|
|
228
|
-
input?: Input;
|
|
229
|
-
interceptors?: InterceptorFn[];
|
|
230
|
-
responseType?: "json";
|
|
231
|
-
observe: "response";
|
|
232
|
-
context?: HttpContext;
|
|
233
|
-
withCredentials?: boolean;
|
|
234
|
-
validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
|
|
235
|
-
transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
|
|
236
|
-
transformResponse?: TransformResponseFn<Output>;
|
|
237
|
-
}): UseRequestFn<HttpResponse<Output>, Input>;
|
|
238
|
-
export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
|
|
239
|
-
method: string;
|
|
240
|
-
endpoint: string;
|
|
241
|
-
input?: Input;
|
|
242
|
-
interceptors?: InterceptorFn[];
|
|
243
|
-
responseType?: "text";
|
|
244
|
-
observe: "response";
|
|
245
|
-
context?: HttpContext;
|
|
246
|
-
withCredentials?: boolean;
|
|
247
|
-
validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
|
|
248
|
-
transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
|
|
249
|
-
transformResponse?: TransformResponseFn;
|
|
250
|
-
}): UseRequestFn<HttpResponse<string>, Input>;
|
|
251
|
-
export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
|
|
252
|
-
method: string;
|
|
253
|
-
endpoint: string;
|
|
254
|
-
input?: Input;
|
|
255
|
-
interceptors?: InterceptorFn[];
|
|
256
|
-
responseType: "blob";
|
|
257
|
-
observe: "response";
|
|
258
|
-
context?: HttpContext;
|
|
259
|
-
withCredentials?: boolean;
|
|
260
|
-
validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
|
|
261
|
-
transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
|
|
262
|
-
transformResponse?: TransformResponseFn;
|
|
263
|
-
}): UseRequestFn<HttpResponse<Blob>, Input>;
|
|
264
|
-
export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
|
|
265
|
-
method: string;
|
|
266
|
-
endpoint: string;
|
|
267
|
-
input?: Input;
|
|
268
|
-
interceptors?: InterceptorFn[];
|
|
269
|
-
responseType?: "arraybuffer";
|
|
270
|
-
observe: "response";
|
|
271
|
-
context?: HttpContext;
|
|
272
|
-
withCredentials?: boolean;
|
|
273
|
-
validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
|
|
274
|
-
transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
|
|
275
|
-
transformResponse?: TransformResponseFn;
|
|
276
|
-
}): 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>;
|
|
277
158
|
export type HttpHandler = (req: HttpRequest) => Promise<HttpResponse<unknown>>;
|
|
278
159
|
export interface FetchConfig {
|
|
279
160
|
/** A string indicating how the request will interact with the browser's cache to set request's cache. */
|
|
@@ -310,10 +191,37 @@ export type Client = {} & {
|
|
|
310
191
|
};
|
|
311
192
|
export declare function isClient(value: unknown): value is Client;
|
|
312
193
|
export declare function createClient(options: ClientOptions): Client;
|
|
313
|
-
export declare function cloneClient(client: Client, options: ClientOptions): Client;
|
|
194
|
+
export declare function cloneClient(client: Client, options: Partial<ClientOptions>): Client;
|
|
314
195
|
export declare function getGlobalClient(): Client;
|
|
315
196
|
export declare function setGlobalClient(client: Client): void;
|
|
316
197
|
export declare function restGlobalClient(): void;
|
|
317
198
|
export declare function createGlobalClient(options: ClientOptions): void;
|
|
199
|
+
export declare const ERR_ABORTED: Error;
|
|
200
|
+
export declare const ERR_TIMEOUT: Error;
|
|
201
|
+
export declare const ERR_NETWORK: Error;
|
|
202
|
+
export declare const ERR_NOT_FOUND_HANDLER: Error;
|
|
203
|
+
export declare const ERR_OBSERVE: Error;
|
|
204
|
+
export declare const ERR_NOT_SET_ALIAS: Error;
|
|
205
|
+
export declare const ERR_UNSUPPORTED_FIELD_TYPE: Error;
|
|
206
|
+
export declare const ERR_INVALID_CLIENT: Error;
|
|
207
|
+
export declare const ERR_NOT_FOUND_GLOBAL_CLIENT: Error;
|
|
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
|
+
}
|
|
318
226
|
|
|
319
227
|
export {};
|
package/index.es.min.js
ADDED
|
@@ -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,3 +1,47 @@
|
|
|
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
|
+
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
|
+
}
|
|
44
|
+
|
|
1
45
|
// src/context.ts
|
|
2
46
|
function makeHttpContextToken(defaultValue) {
|
|
3
47
|
Object.defineProperty(defaultValue, HTTP_CONTEXT_TOKEN, { value: defaultValue });
|
|
@@ -11,14 +55,14 @@ function makeHttpContext() {
|
|
|
11
55
|
return {
|
|
12
56
|
set(token, value) {
|
|
13
57
|
if (!isHttpContextToken(token)) {
|
|
14
|
-
throw
|
|
58
|
+
throw ERR_INVALID_HTTP_CONTEXT_TOKEN;
|
|
15
59
|
}
|
|
16
60
|
ctx.set(token, value);
|
|
17
61
|
return this;
|
|
18
62
|
},
|
|
19
63
|
get(token) {
|
|
20
64
|
if (!isHttpContextToken(token)) {
|
|
21
|
-
throw
|
|
65
|
+
throw ERR_INVALID_HTTP_CONTEXT_TOKEN;
|
|
22
66
|
}
|
|
23
67
|
if (!ctx.has(token)) {
|
|
24
68
|
ctx.set(token, token());
|
|
@@ -70,6 +114,10 @@ function field(defaultValue) {
|
|
|
70
114
|
meta.alias.set(4 /* Header */, alias);
|
|
71
115
|
return getter;
|
|
72
116
|
};
|
|
117
|
+
getter.withUrlForm = (alias) => {
|
|
118
|
+
meta.alias.set(7 /* UrlForm */, alias);
|
|
119
|
+
return getter;
|
|
120
|
+
};
|
|
73
121
|
getter.withBody = () => {
|
|
74
122
|
meta.alias.set(6 /* Body */, undefined);
|
|
75
123
|
return getter;
|
|
@@ -84,7 +132,7 @@ function field(defaultValue) {
|
|
|
84
132
|
};
|
|
85
133
|
return getter;
|
|
86
134
|
}
|
|
87
|
-
function
|
|
135
|
+
function __getFieldMetadata(field2) {
|
|
88
136
|
return field2[FIELD];
|
|
89
137
|
}
|
|
90
138
|
function validatorField(validators, value) {
|
|
@@ -123,47 +171,28 @@ function makeInterceptorChain(interceptors) {
|
|
|
123
171
|
}
|
|
124
172
|
|
|
125
173
|
// src/response.ts
|
|
126
|
-
function
|
|
127
|
-
return typeof value === "object" && value !== null && HTTP_RESPONSE in value;
|
|
128
|
-
}
|
|
129
|
-
function makeResponse(options) {
|
|
174
|
+
function __makeResponse(options) {
|
|
130
175
|
const status = options.status ?? 0;
|
|
131
176
|
const statusText = options.statusText ?? "";
|
|
132
|
-
const ok = status >= 200 && status < 300;
|
|
133
177
|
const url = options.url ?? "";
|
|
134
178
|
const headers = options.headers ?? new Headers;
|
|
135
179
|
const body = options.body ?? null;
|
|
136
|
-
if (!ok || options.error) {
|
|
137
|
-
const error = options.error || new Error(`Http failure response for ${options.url}: ${status} ${statusText}`);
|
|
138
|
-
return {
|
|
139
|
-
ok: false,
|
|
140
|
-
error,
|
|
141
|
-
status,
|
|
142
|
-
statusText,
|
|
143
|
-
url,
|
|
144
|
-
headers,
|
|
145
|
-
body: null,
|
|
146
|
-
[HTTP_RESPONSE]: null
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
180
|
return {
|
|
150
|
-
ok: true,
|
|
151
181
|
status,
|
|
152
182
|
statusText,
|
|
153
183
|
url,
|
|
154
184
|
headers,
|
|
155
|
-
body
|
|
156
|
-
[HTTP_RESPONSE]: null
|
|
185
|
+
body
|
|
157
186
|
};
|
|
158
187
|
}
|
|
159
|
-
var HTTP_RESPONSE = Symbol("HTTP_RESPONSE");
|
|
160
188
|
|
|
161
189
|
// src/request.ts
|
|
162
|
-
function
|
|
190
|
+
function __serializeBody(body) {
|
|
163
191
|
switch (true) {
|
|
164
192
|
case body instanceof FormData:
|
|
165
193
|
case body instanceof Blob:
|
|
166
194
|
case body instanceof ArrayBuffer:
|
|
195
|
+
case body instanceof URLSearchParams:
|
|
167
196
|
case typeof body === "string":
|
|
168
197
|
return body;
|
|
169
198
|
case typeof body === "object":
|
|
@@ -175,7 +204,7 @@ function serializeBody(body) {
|
|
|
175
204
|
return null;
|
|
176
205
|
}
|
|
177
206
|
}
|
|
178
|
-
function
|
|
207
|
+
function __detectContentTypeHeader(body) {
|
|
179
208
|
switch (true) {
|
|
180
209
|
case body instanceof FormData:
|
|
181
210
|
return "multipart/form-data";
|
|
@@ -197,7 +226,7 @@ function detectContentTypeHeader(body) {
|
|
|
197
226
|
return null;
|
|
198
227
|
}
|
|
199
228
|
}
|
|
200
|
-
function
|
|
229
|
+
function __buildFieldDefaultValue(input) {
|
|
201
230
|
if (isField(input)) {
|
|
202
231
|
return input();
|
|
203
232
|
}
|
|
@@ -210,21 +239,26 @@ function buildFieldValue(input) {
|
|
|
210
239
|
}
|
|
211
240
|
return;
|
|
212
241
|
}
|
|
213
|
-
function defineRequest(
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
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 = () => {
|
|
219
253
|
let uploadProgress;
|
|
220
254
|
let downloadProgress;
|
|
221
|
-
let abortController;
|
|
222
255
|
let abortSignal;
|
|
223
|
-
const
|
|
224
|
-
|
|
256
|
+
const getInitValue = () => __buildFieldDefaultValue(field3);
|
|
257
|
+
const setUploadProgress = (fn2) => {
|
|
258
|
+
uploadProgress = fn2;
|
|
225
259
|
};
|
|
226
|
-
const setDownloadProgress = (
|
|
227
|
-
downloadProgress =
|
|
260
|
+
const setDownloadProgress = (fn2) => {
|
|
261
|
+
downloadProgress = fn2;
|
|
228
262
|
};
|
|
229
263
|
const doRequest = async (...args) => {
|
|
230
264
|
let input;
|
|
@@ -241,99 +275,114 @@ function defineRequest(options) {
|
|
|
241
275
|
}
|
|
242
276
|
}
|
|
243
277
|
if (requiredInput && !input) {
|
|
244
|
-
throw new Error(
|
|
278
|
+
throw new Error(`Because the request has input, the first argument must be the input value`);
|
|
279
|
+
}
|
|
280
|
+
if (validators.length > 0) {
|
|
281
|
+
for (const fn2 of validators) {
|
|
282
|
+
fn2(input);
|
|
283
|
+
}
|
|
245
284
|
}
|
|
285
|
+
const timeout = doRequestOptions?.timeout || 0;
|
|
246
286
|
if (doRequestOptions?.abort) {
|
|
247
287
|
abortSignal = doRequestOptions.abort;
|
|
248
|
-
} else {
|
|
249
|
-
|
|
250
|
-
abortSignal = abortController.signal;
|
|
288
|
+
} else if (timeout > 0) {
|
|
289
|
+
abortSignal = AbortSignal.timeout(timeout);
|
|
251
290
|
}
|
|
252
291
|
const client2 = isClient(doRequestOptions?.client) ? doRequestOptions.client : getGlobalClient();
|
|
253
292
|
const clientOptions = getClientConfig(client2);
|
|
254
293
|
const req = {
|
|
255
294
|
host: clientOptions?.host,
|
|
256
|
-
method
|
|
257
|
-
endpoint
|
|
295
|
+
method,
|
|
296
|
+
endpoint,
|
|
258
297
|
queryParams: new URLSearchParams,
|
|
259
298
|
headers: new Headers,
|
|
260
299
|
body: undefined,
|
|
261
|
-
withCredentials
|
|
262
|
-
responseType
|
|
263
|
-
context:
|
|
264
|
-
observe
|
|
300
|
+
withCredentials,
|
|
301
|
+
responseType,
|
|
302
|
+
context: context2 || makeHttpContext(),
|
|
303
|
+
observe,
|
|
265
304
|
uploadProgress,
|
|
266
305
|
downloadProgress,
|
|
267
|
-
timeout
|
|
306
|
+
timeout,
|
|
268
307
|
abort: abortSignal
|
|
269
308
|
};
|
|
270
309
|
const handler2 = doRequestOptions?.handler || clientOptions?.handler || getGlobalHttpHandler();
|
|
271
310
|
if (!handler2) {
|
|
272
|
-
throw
|
|
311
|
+
throw ERR_NOT_FOUND_HANDLER;
|
|
273
312
|
}
|
|
274
313
|
if (requiredInput) {
|
|
275
|
-
await
|
|
276
|
-
}
|
|
277
|
-
if (typeof requestOptions.transformRequest === "function") {
|
|
278
|
-
req.body = requestOptions.transformRequest(input, req);
|
|
279
|
-
}
|
|
280
|
-
const chain = makeInterceptorChain([...clientOptions?.interceptors || [], ...requestOptions?.interceptors || []]);
|
|
281
|
-
if (typeof req.timeout === "number" && req.timeout > 0 && abortController) {
|
|
282
|
-
setTimeout(() => {
|
|
283
|
-
if (!req.abort?.aborted) {
|
|
284
|
-
abortController?.abort("timeout");
|
|
285
|
-
}
|
|
286
|
-
}, req.timeout);
|
|
314
|
+
await __fillRequestFromField(req, field3, input);
|
|
287
315
|
}
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
} catch (error) {
|
|
292
|
-
throw makeResponse({
|
|
293
|
-
error: error instanceof Error ? error : new Error("Transform response error", { cause: error })
|
|
294
|
-
});
|
|
295
|
-
}
|
|
296
|
-
if (typeof requestOptions.transformResponse === "function") {
|
|
316
|
+
const chain = makeInterceptorChain([...interceptors]);
|
|
317
|
+
let res = await chain(req, handler2);
|
|
318
|
+
if (typeof transformResponse === "function") {
|
|
297
319
|
try {
|
|
298
|
-
res =
|
|
299
|
-
...res,
|
|
300
|
-
body: requestOptions.transformResponse(res)
|
|
301
|
-
});
|
|
302
|
-
} catch (error) {
|
|
303
|
-
throw makeResponse({
|
|
320
|
+
res = __makeResponse({
|
|
304
321
|
...res,
|
|
305
|
-
|
|
322
|
+
body: transformResponse(res)
|
|
306
323
|
});
|
|
324
|
+
} catch (error3) {
|
|
325
|
+
throw new HttpErrorResponse({ error: error3 });
|
|
307
326
|
}
|
|
308
327
|
}
|
|
309
328
|
switch (req.observe) {
|
|
310
329
|
case "body":
|
|
311
330
|
return res.body;
|
|
312
|
-
case "stream":
|
|
313
|
-
throw new Error("streaming not implemented");
|
|
314
331
|
case "response":
|
|
315
332
|
return res;
|
|
316
333
|
default:
|
|
317
|
-
throw
|
|
334
|
+
throw ERR_OBSERVE;
|
|
318
335
|
}
|
|
319
336
|
};
|
|
320
337
|
return {
|
|
321
338
|
doRequest,
|
|
322
|
-
|
|
339
|
+
getInitValue,
|
|
323
340
|
setUploadProgress,
|
|
324
341
|
setDownloadProgress
|
|
325
342
|
};
|
|
326
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;
|
|
327
379
|
}
|
|
328
|
-
function
|
|
329
|
-
throw new Error("alias not set");
|
|
330
|
-
}
|
|
331
|
-
function fillUrl(endpoint, params) {
|
|
380
|
+
function __fillUrl(endpoint, params) {
|
|
332
381
|
return endpoint.replace(/:([^\/]+)/g, (_, p1) => {
|
|
333
382
|
return params.get(p1) ?? "undefined";
|
|
334
383
|
});
|
|
335
384
|
}
|
|
336
|
-
async function
|
|
385
|
+
async function __fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
337
386
|
async function doValid(validators, value) {
|
|
338
387
|
for (const validator of validators) {
|
|
339
388
|
const err = await validator(value);
|
|
@@ -346,24 +395,37 @@ async function fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
346
395
|
function inputIsObject(input2) {
|
|
347
396
|
return typeof input2 === "object" && input2 !== null;
|
|
348
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
|
+
}
|
|
349
412
|
function appendValue(sp, key, value) {
|
|
350
413
|
if (Array.isArray(value)) {
|
|
351
414
|
for (const v of value) {
|
|
352
|
-
sp.append(key,
|
|
415
|
+
sp.append(key, serializeToString(v));
|
|
353
416
|
}
|
|
354
417
|
} else {
|
|
355
|
-
sp.set(key,
|
|
418
|
+
sp.set(key, serializeToString(value));
|
|
356
419
|
}
|
|
357
420
|
return sp;
|
|
358
421
|
}
|
|
359
422
|
function setValue(sp, key, value) {
|
|
360
423
|
if (Array.isArray(value)) {
|
|
361
424
|
for (const v of value) {
|
|
362
|
-
sp
|
|
425
|
+
setValue(sp, key, serializeToString(v));
|
|
363
426
|
}
|
|
364
|
-
} else {
|
|
365
|
-
sp.set(key, String(value));
|
|
366
427
|
}
|
|
428
|
+
sp.set(key, serializeToString(value));
|
|
367
429
|
return sp;
|
|
368
430
|
}
|
|
369
431
|
if (isField(fieldOrFieldGroup)) {
|
|
@@ -372,7 +434,7 @@ async function fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
372
434
|
let headers;
|
|
373
435
|
let body = undefined;
|
|
374
436
|
const fieldValue = input ?? fieldOrFieldGroup();
|
|
375
|
-
const meta =
|
|
437
|
+
const meta = __getFieldMetadata(fieldOrFieldGroup);
|
|
376
438
|
const err = await doValid([...meta.validators, ...meta.asyncValidator], fieldValue);
|
|
377
439
|
if (err) {
|
|
378
440
|
throw err;
|
|
@@ -381,32 +443,39 @@ async function fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
381
443
|
switch (type) {
|
|
382
444
|
case 2 /* Query */: {
|
|
383
445
|
if (!aliasName) {
|
|
384
|
-
|
|
446
|
+
throw ERR_NOT_SET_ALIAS;
|
|
385
447
|
}
|
|
386
448
|
queryParams = appendValue(new URLSearchParams, aliasName, fieldValue);
|
|
387
449
|
break;
|
|
388
450
|
}
|
|
389
451
|
case 3 /* Param */: {
|
|
390
452
|
if (!aliasName) {
|
|
391
|
-
|
|
453
|
+
throw ERR_NOT_SET_ALIAS;
|
|
392
454
|
}
|
|
393
455
|
params = setValue(new Map, aliasName, fieldValue);
|
|
394
456
|
break;
|
|
395
457
|
}
|
|
396
458
|
case 4 /* Header */: {
|
|
397
459
|
if (!aliasName) {
|
|
398
|
-
|
|
460
|
+
throw ERR_NOT_SET_ALIAS;
|
|
399
461
|
}
|
|
400
462
|
headers = appendValue(new Headers, aliasName, fieldValue);
|
|
401
463
|
break;
|
|
402
464
|
}
|
|
403
465
|
case 5 /* Form */: {
|
|
404
466
|
if (!aliasName) {
|
|
405
|
-
|
|
467
|
+
throw ERR_NOT_SET_ALIAS;
|
|
406
468
|
}
|
|
407
469
|
body = appendValue(new FormData, aliasName, fieldValue);
|
|
408
470
|
break;
|
|
409
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
|
+
}
|
|
410
479
|
case 1 /* Json */:
|
|
411
480
|
case 6 /* Body */:
|
|
412
481
|
body = fieldValue;
|
|
@@ -414,7 +483,7 @@ async function fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
414
483
|
}
|
|
415
484
|
}
|
|
416
485
|
if (params) {
|
|
417
|
-
request.endpoint =
|
|
486
|
+
request.endpoint = __fillUrl(request.endpoint, params);
|
|
418
487
|
}
|
|
419
488
|
request.queryParams = queryParams;
|
|
420
489
|
request.headers = headers;
|
|
@@ -425,11 +494,13 @@ async function fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
425
494
|
let params = new Map;
|
|
426
495
|
let queryParams = new URLSearchParams;
|
|
427
496
|
let headers = new Headers;
|
|
497
|
+
let urlForm = new URLSearchParams;
|
|
428
498
|
let formData = new FormData;
|
|
429
499
|
const json = {};
|
|
430
500
|
let body = undefined;
|
|
501
|
+
let lastBodyField;
|
|
431
502
|
for (const [propertyKey, field3] of Object.entries(fieldOrFieldGroup)) {
|
|
432
|
-
const meta =
|
|
503
|
+
const meta = __getFieldMetadata(field3);
|
|
433
504
|
for (const [type, aliasName] of meta.alias) {
|
|
434
505
|
const valueKey = aliasName || propertyKey;
|
|
435
506
|
const value = input[propertyKey] || field3();
|
|
@@ -438,13 +509,15 @@ async function fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
438
509
|
throw err;
|
|
439
510
|
}
|
|
440
511
|
switch (type) {
|
|
441
|
-
case 1 /* Json */:
|
|
512
|
+
case 1 /* Json */: {
|
|
442
513
|
Object.defineProperty(json, valueKey, {
|
|
443
514
|
value,
|
|
444
515
|
writable: true,
|
|
445
516
|
enumerable: true
|
|
446
517
|
});
|
|
518
|
+
lastBodyField = 1 /* Json */;
|
|
447
519
|
break;
|
|
520
|
+
}
|
|
448
521
|
case 2 /* Query */:
|
|
449
522
|
queryParams = appendValue(queryParams, valueKey, value);
|
|
450
523
|
break;
|
|
@@ -454,32 +527,48 @@ async function fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
454
527
|
case 4 /* Header */:
|
|
455
528
|
headers = appendValue(headers, valueKey, value);
|
|
456
529
|
break;
|
|
457
|
-
case 5 /* Form */:
|
|
530
|
+
case 5 /* Form */: {
|
|
458
531
|
formData = appendValue(formData, valueKey, value);
|
|
532
|
+
lastBodyField = 5 /* Form */;
|
|
533
|
+
break;
|
|
534
|
+
}
|
|
535
|
+
case 7 /* UrlForm */: {
|
|
536
|
+
urlForm = appendValue(urlForm, valueKey, value);
|
|
537
|
+
lastBodyField = 7 /* UrlForm */;
|
|
459
538
|
break;
|
|
460
|
-
|
|
539
|
+
}
|
|
540
|
+
case 6 /* Body */: {
|
|
461
541
|
body = value;
|
|
542
|
+
lastBodyField = 6 /* Body */;
|
|
462
543
|
break;
|
|
544
|
+
}
|
|
463
545
|
}
|
|
464
546
|
}
|
|
465
547
|
}
|
|
466
|
-
request.endpoint =
|
|
548
|
+
request.endpoint = __fillUrl(request.endpoint, params);
|
|
467
549
|
request.queryParams = queryParams;
|
|
468
550
|
request.headers = headers;
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
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;
|
|
475
564
|
}
|
|
476
565
|
return;
|
|
477
566
|
}
|
|
478
|
-
throw
|
|
567
|
+
throw ERR_UNSUPPORTED_FIELD_TYPE;
|
|
479
568
|
}
|
|
480
569
|
|
|
481
570
|
// src/handler/util.ts
|
|
482
|
-
function
|
|
571
|
+
function __getContentLength(headers) {
|
|
483
572
|
const value = headers.get("Content-Length");
|
|
484
573
|
if (!value) {
|
|
485
574
|
return 0;
|
|
@@ -490,10 +579,10 @@ function getContentLength(headers) {
|
|
|
490
579
|
}
|
|
491
580
|
return num;
|
|
492
581
|
}
|
|
493
|
-
function
|
|
582
|
+
function __getContentType(headers) {
|
|
494
583
|
return headers.get("Content-Type") || "";
|
|
495
584
|
}
|
|
496
|
-
function
|
|
585
|
+
function __parseBody(params) {
|
|
497
586
|
const { request, content, contentType } = params;
|
|
498
587
|
const responseType = request.responseType;
|
|
499
588
|
if (!responseType) {
|
|
@@ -505,6 +594,7 @@ function parseBody(params) {
|
|
|
505
594
|
if (text === "") {
|
|
506
595
|
return null;
|
|
507
596
|
}
|
|
597
|
+
console.log(text);
|
|
508
598
|
return JSON.parse(text);
|
|
509
599
|
}
|
|
510
600
|
case "text":
|
|
@@ -518,7 +608,7 @@ function parseBody(params) {
|
|
|
518
608
|
return null;
|
|
519
609
|
}
|
|
520
610
|
}
|
|
521
|
-
function
|
|
611
|
+
function __concatChunks(chunks, totalLength) {
|
|
522
612
|
const chunksAll = new Uint8Array(totalLength);
|
|
523
613
|
let position = 0;
|
|
524
614
|
for (const chunk of chunks) {
|
|
@@ -529,14 +619,14 @@ function concatChunks(chunks, totalLength) {
|
|
|
529
619
|
}
|
|
530
620
|
|
|
531
621
|
// src/handler/fetch/fetch.ts
|
|
532
|
-
function
|
|
622
|
+
function __createRequest(request2) {
|
|
533
623
|
const url = new URL(request2.endpoint, request2.host);
|
|
534
624
|
if (request2.queryParams) {
|
|
535
625
|
url.search = request2.queryParams.toString();
|
|
536
626
|
}
|
|
537
627
|
const headers = request2.headers ?? new Headers;
|
|
538
628
|
if (!headers.has("Content-Type")) {
|
|
539
|
-
const detectedType =
|
|
629
|
+
const detectedType = __detectContentTypeHeader(request2.body);
|
|
540
630
|
if (detectedType) {
|
|
541
631
|
headers.set("Content-Type", detectedType);
|
|
542
632
|
}
|
|
@@ -550,23 +640,31 @@ function createRequest(request2) {
|
|
|
550
640
|
...fetchConfig,
|
|
551
641
|
headers,
|
|
552
642
|
method: request2.method,
|
|
553
|
-
body:
|
|
643
|
+
body: __serializeBody(request2.body),
|
|
554
644
|
signal: request2.abort,
|
|
555
645
|
credentials
|
|
556
646
|
});
|
|
557
647
|
}
|
|
558
648
|
async function fetchHandler(httpRequest) {
|
|
559
649
|
const downloadProgress = httpRequest.downloadProgress;
|
|
560
|
-
const request2 =
|
|
650
|
+
const request2 = __createRequest(httpRequest);
|
|
561
651
|
let response3;
|
|
562
652
|
try {
|
|
563
653
|
response3 = await (globalThis || window).fetch(request2);
|
|
564
|
-
} catch (
|
|
565
|
-
|
|
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 });
|
|
566
664
|
}
|
|
567
|
-
const { headers, status, statusText, url } = response3;
|
|
568
|
-
const contentLength =
|
|
569
|
-
const contentType =
|
|
665
|
+
const { ok, headers, status, statusText, url } = response3;
|
|
666
|
+
const contentLength = __getContentLength(headers);
|
|
667
|
+
const contentType = __getContentType(headers);
|
|
570
668
|
let body = null;
|
|
571
669
|
if (response3.body) {
|
|
572
670
|
const chunks = [];
|
|
@@ -585,18 +683,33 @@ async function fetchHandler(httpRequest) {
|
|
|
585
683
|
total: contentLength
|
|
586
684
|
});
|
|
587
685
|
}
|
|
588
|
-
const chunksAll =
|
|
686
|
+
const chunksAll = __concatChunks(chunks, receivedLength);
|
|
589
687
|
try {
|
|
590
|
-
body =
|
|
688
|
+
body = __parseBody({
|
|
591
689
|
request: httpRequest,
|
|
592
690
|
content: chunksAll,
|
|
593
691
|
contentType
|
|
594
692
|
});
|
|
595
|
-
} catch (
|
|
596
|
-
throw new
|
|
693
|
+
} catch (error4) {
|
|
694
|
+
throw new HttpErrorResponse({
|
|
695
|
+
error: error4,
|
|
696
|
+
status,
|
|
697
|
+
statusText,
|
|
698
|
+
headers,
|
|
699
|
+
url
|
|
700
|
+
});
|
|
597
701
|
}
|
|
598
702
|
}
|
|
599
|
-
|
|
703
|
+
if (!ok) {
|
|
704
|
+
throw new HttpErrorResponse({
|
|
705
|
+
status,
|
|
706
|
+
statusText,
|
|
707
|
+
headers,
|
|
708
|
+
url,
|
|
709
|
+
body
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
return __makeResponse({
|
|
600
713
|
url,
|
|
601
714
|
status,
|
|
602
715
|
statusText,
|
|
@@ -611,7 +724,7 @@ function isClient(value) {
|
|
|
611
724
|
}
|
|
612
725
|
function getClientConfig(client2) {
|
|
613
726
|
if (!isClient(client2)) {
|
|
614
|
-
throw
|
|
727
|
+
throw ERR_INVALID_CLIENT;
|
|
615
728
|
}
|
|
616
729
|
return client2[CLIENT];
|
|
617
730
|
}
|
|
@@ -637,7 +750,7 @@ function cloneClient(client2, options) {
|
|
|
637
750
|
}
|
|
638
751
|
function getGlobalClient() {
|
|
639
752
|
if (!globalClient) {
|
|
640
|
-
throw
|
|
753
|
+
throw ERR_NOT_FOUND_GLOBAL_CLIENT;
|
|
641
754
|
}
|
|
642
755
|
return globalClient;
|
|
643
756
|
}
|
|
@@ -731,9 +844,6 @@ var pattern = (pattern2) => {
|
|
|
731
844
|
if (typeof value !== "string") {
|
|
732
845
|
return new Error("invalid string");
|
|
733
846
|
}
|
|
734
|
-
if (typeof pattern2 === "string") {
|
|
735
|
-
pattern2 = new RegExp(pattern2);
|
|
736
|
-
}
|
|
737
847
|
if (!pattern2.test(value)) {
|
|
738
848
|
return new Error("pattern");
|
|
739
849
|
}
|
|
@@ -751,10 +861,8 @@ export {
|
|
|
751
861
|
min,
|
|
752
862
|
maxLength,
|
|
753
863
|
max,
|
|
754
|
-
makeResponse,
|
|
755
864
|
makeHttpContextToken,
|
|
756
865
|
makeHttpContext,
|
|
757
|
-
isHttpResponse,
|
|
758
866
|
isHttpContextToken,
|
|
759
867
|
isFieldGroup,
|
|
760
868
|
isField,
|
|
@@ -768,5 +876,17 @@ export {
|
|
|
768
876
|
cloneClient,
|
|
769
877
|
basicAuthInterceptor,
|
|
770
878
|
asyncValidatorField,
|
|
771
|
-
|
|
879
|
+
HttpErrorResponse,
|
|
880
|
+
FETCH_CONFIG_KEY,
|
|
881
|
+
ERR_UNSUPPORTED_FIELD_TYPE,
|
|
882
|
+
ERR_UNKNOWN,
|
|
883
|
+
ERR_TIMEOUT,
|
|
884
|
+
ERR_OBSERVE,
|
|
885
|
+
ERR_NOT_SET_ALIAS,
|
|
886
|
+
ERR_NOT_FOUND_HANDLER,
|
|
887
|
+
ERR_NOT_FOUND_GLOBAL_CLIENT,
|
|
888
|
+
ERR_NETWORK,
|
|
889
|
+
ERR_INVALID_HTTP_CONTEXT_TOKEN,
|
|
890
|
+
ERR_INVALID_CLIENT,
|
|
891
|
+
ERR_ABORTED
|
|
772
892
|
};
|