@defjs/core 0.3.0 → 0.3.2

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
@@ -134,10 +134,10 @@ export interface HttpRequest {
134
134
  downloadProgress?: HttpProgressFn;
135
135
  abort?: AbortSignal;
136
136
  }
137
- export type RequestInputValue<T> = T extends Field<infer V> ? V : T extends {
137
+ export type RequestInputValue<T> = T extends {
138
138
  [K in keyof T]: Field<any>;
139
139
  } ? {
140
- [K in keyof T]: RequestInputValue<T[K]>;
140
+ [K in keyof T]: T[K] extends Field<infer V> ? V : never;
141
141
  } : never;
142
142
  export type UseRequestOptions = {
143
143
  abort?: AbortSignal;
@@ -148,21 +148,17 @@ export type UseRequestOptions = {
148
148
  export type UseRequestFn<Input, Output> = {
149
149
  doRequest: undefined extends RequestInputValue<Input> ? (input?: RequestInputValue<Input>) => Promise<HttpResponse<Output>> : (input: RequestInputValue<Input>) => Promise<HttpResponse<Output>>;
150
150
  cancel: () => void;
151
- getInitValue: () => Input extends Field<infer V> ? V : Input extends {
152
- [K in keyof Input]: Field<any>;
153
- } ? {
154
- [K in keyof Input]: RequestInputValue<Input[K]>;
155
- } : undefined;
151
+ getInitValue: () => RequestInputValue<Input>;
156
152
  setUploadProgress: (fn: HttpProgressFn) => void;
157
153
  setDownloadProgress: (fn: HttpProgressFn) => void;
158
154
  };
159
- export interface DefineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined, Output = unknown> {
155
+ export interface DefineRequest<Input extends Record<PropertyKey, Field<any>> | undefined = undefined, Output = unknown> {
160
156
  (options?: UseRequestOptions): UseRequestFn<Input, Output>;
161
- withField<I extends Field<any> | Record<PropertyKey, Field<any>>>(value: I): DefineRequest<I, Output>;
157
+ withField<I extends Record<PropertyKey, Field<any>>>(value: I): DefineRequest<I, Output>;
162
158
  withInterceptors(value: InterceptorFn[]): DefineRequest<Input, Output>;
163
159
  withContext(value: HttpContext): DefineRequest<Input, Output>;
164
160
  withCredentials(value: boolean): DefineRequest<Input, Output>;
165
- withValidators(value: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[]): DefineRequest<Input, Output>;
161
+ withValidators(...fn: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[]): DefineRequest<Input, Output>;
166
162
  withTransformResponse<O>(fn: TransformResponseFn<O>): DefineRequest<Input, O>;
167
163
  withResponseType(value: "json"): DefineRequest<Input, Output>;
168
164
  withResponseType(value: "text"): DefineRequest<Input, string>;
package/index.js CHANGED
@@ -1,51 +1,15 @@
1
- // src/handler/util.ts
2
- function __getContentLength(headers) {
3
- const value = headers.get("Content-Length");
4
- if (!value) {
5
- return 0;
6
- }
7
- const num = Number(value);
8
- if (isNaN(num)) {
9
- return 0;
10
- }
11
- return num;
12
- }
13
- function __getContentType(headers) {
14
- return headers.get("Content-Type") || "";
15
- }
16
- function __parseBody(params) {
17
- const { request, content, contentType } = params;
18
- const responseType = request.responseType;
19
- switch (responseType) {
20
- case "json": {
21
- const text = new TextDecoder().decode(content);
22
- if (text === "") {
23
- return null;
24
- }
25
- return JSON.parse(text);
26
- }
27
- case "text":
28
- return new TextDecoder().decode(content);
29
- case "blob": {
30
- return new Blob([content], { type: contentType });
31
- }
32
- case "arraybuffer":
33
- return content.buffer;
34
- default:
35
- return null;
36
- }
37
- }
38
- function __concatChunks(chunks, totalLength) {
39
- const chunksAll = new Uint8Array(totalLength);
40
- let position = 0;
41
- for (const chunk of chunks) {
42
- chunksAll.set(chunk, position);
43
- position += chunk.length;
44
- }
45
- return chunksAll;
46
- }
47
-
48
1
  // src/response.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");
49
13
  function __makeResponse(options) {
50
14
  const status = options?.status ?? 0;
51
15
  const ok = status >= 200 && status < 300;
@@ -70,19 +34,9 @@ function __makeResponse(options) {
70
34
  error
71
35
  };
72
36
  }
73
- var ERR_ABORTED = new Error("ERR_ABORTED");
74
- var ERR_TIMEOUT = new Error("ERR_TIMEOUT");
75
- var ERR_NETWORK = new Error("ERR_NETWORK");
76
- var ERR_NOT_FOUND_HANDLER = new Error("ERR_NOT_FOUND_HANDLER");
77
- var ERR_OBSERVE = new Error("ERR_OBSERVE");
78
- var ERR_NOT_SET_ALIAS = new Error("ERR_NOT_SET_ALIAS");
79
- var ERR_UNSUPPORTED_FIELD_TYPE = new Error("ERR_UNSUPPORTED_FIELD_TYPE");
80
- var ERR_INVALID_CLIENT = new Error("ERR_INVALID_CLIENT");
81
- var ERR_NOT_FOUND_GLOBAL_CLIENT = new Error("ERR_NOT_FOUND_GLOBAL_CLIENT");
82
- var ERR_INVALID_HTTP_CONTEXT_TOKEN = new Error("ERR_INVALID_HTTP_CONTEXT_TOKEN");
83
- var ERR_UNKNOWN = new Error("ERR_UNKNOWN");
84
37
 
85
38
  // src/context.ts
39
+ var HTTP_CONTEXT_TOKEN = Symbol("HttpContextToken");
86
40
  function makeHttpContextToken(defaultValue) {
87
41
  Object.defineProperty(defaultValue, HTTP_CONTEXT_TOKEN, { value: defaultValue });
88
42
  return defaultValue;
@@ -90,6 +44,7 @@ function makeHttpContextToken(defaultValue) {
90
44
  function isHttpContextToken(value) {
91
45
  return typeof value === "function" && HTTP_CONTEXT_TOKEN in value;
92
46
  }
47
+ var HTTP_CONTEXT = Symbol("HttpContext");
93
48
  function isHttpContext(value) {
94
49
  return typeof value === "object" && value !== null && HTTP_CONTEXT in value;
95
50
  }
@@ -144,10 +99,9 @@ function makeHttpContext(entries) {
144
99
  [HTTP_CONTEXT]: ctx
145
100
  };
146
101
  }
147
- var HTTP_CONTEXT_TOKEN = Symbol("HttpContextToken");
148
- var HTTP_CONTEXT = Symbol("HttpContext");
149
102
 
150
103
  // src/field.ts
104
+ var FIELD = Symbol("field");
151
105
  function field(defaultValue) {
152
106
  const meta = {
153
107
  required: typeof defaultValue !== "undefined",
@@ -209,7 +163,6 @@ function isField(value) {
209
163
  function isFieldGroup(value) {
210
164
  return !!value && typeof value === "object" && Object.entries(value).every(([, v]) => isField(v));
211
165
  }
212
- var FIELD = Symbol("field");
213
166
 
214
167
  // src/handler/handler.ts
215
168
  var globalHttpHandler = undefined;
@@ -243,15 +196,12 @@ function __serializeBody(body) {
243
196
  function __detectContentTypeHeader(body) {
244
197
  switch (true) {
245
198
  case body instanceof FormData:
246
- return "multipart/form-data";
199
+ case body instanceof URLSearchParams:
200
+ return null;
247
201
  case body instanceof ArrayBuffer:
248
202
  return "application/octet-stream";
249
- case body instanceof Blob: {
203
+ case body instanceof Blob:
250
204
  return body.type || "application/octet-stream";
251
- }
252
- case body instanceof URLSearchParams: {
253
- return "application/x-www-form-urlencoded;charset=UTF-8";
254
- }
255
205
  case typeof body === "string":
256
206
  return "text/plain";
257
207
  case (typeof body === "object" && body !== null):
@@ -263,13 +213,10 @@ function __detectContentTypeHeader(body) {
263
213
  }
264
214
  }
265
215
  function __buildFieldDefaultValue(input) {
266
- if (isField(input)) {
267
- return input();
268
- }
269
216
  if (isFieldGroup(input)) {
270
217
  const obj = {};
271
- for (const [key, field3] of Object.entries(input)) {
272
- obj[key] = field3();
218
+ for (const [key, field2] of Object.entries(input)) {
219
+ obj[key] = field2();
273
220
  }
274
221
  return obj;
275
222
  }
@@ -279,10 +226,10 @@ function defineRequest(...args) {
279
226
  let method;
280
227
  let endpoint;
281
228
  let requiredInput = false;
282
- let field3;
229
+ let field2;
283
230
  let interceptors = [];
284
231
  let responseType = "json";
285
- let context2;
232
+ let context;
286
233
  let withCredentials = false;
287
234
  let validators = [];
288
235
  let transformResponse;
@@ -302,10 +249,10 @@ function defineRequest(...args) {
302
249
  }
303
250
  const fn = (options) => {
304
251
  const timeout = options?.timeout || 0;
305
- const client2 = options?.client || getGlobalClient();
306
- const clientOptions = getClientConfig(client2);
307
- const handler2 = options?.handler || clientOptions?.handler || getGlobalHttpHandler();
308
- if (!handler2) {
252
+ const client = options?.client || getGlobalClient();
253
+ const clientOptions = getClientConfig(client);
254
+ const handler = options?.handler || clientOptions?.handler || getGlobalHttpHandler();
255
+ if (!handler) {
309
256
  throw ERR_NOT_FOUND_HANDLER;
310
257
  }
311
258
  let uploadProgress;
@@ -324,7 +271,7 @@ function defineRequest(...args) {
324
271
  const cancel = () => {
325
272
  abortController?.abort();
326
273
  };
327
- const getInitValue = () => __buildFieldDefaultValue(field3);
274
+ const getInitValue = () => __buildFieldDefaultValue(field2);
328
275
  const setUploadProgress = (fn2) => {
329
276
  uploadProgress = fn2;
330
277
  };
@@ -354,17 +301,17 @@ function defineRequest(...args) {
354
301
  body: undefined,
355
302
  withCredentials,
356
303
  responseType,
357
- context: context2 || makeHttpContext(),
304
+ context: context || makeHttpContext(),
358
305
  uploadProgress,
359
306
  downloadProgress,
360
307
  timeout,
361
308
  abort: AbortSignal.any(abortSignal)
362
309
  };
363
- if (requiredInput && field3) {
364
- await __fillRequestFromField(req, field3, input);
310
+ if (requiredInput && field2) {
311
+ await __fillRequestFromField(req, field2, input);
365
312
  }
366
313
  const chain = makeInterceptorChain([...clientOptions.interceptors, ...interceptors]);
367
- let res = await chain(req, handler2);
314
+ let res = await chain(req, handler);
368
315
  if (typeof transformResponse === "function") {
369
316
  res = __makeResponse({
370
317
  ...res,
@@ -385,7 +332,7 @@ function defineRequest(...args) {
385
332
  };
386
333
  };
387
334
  fn.withField = (value) => {
388
- field3 = value;
335
+ field2 = value;
389
336
  requiredInput = true;
390
337
  return fn;
391
338
  };
@@ -394,15 +341,15 @@ function defineRequest(...args) {
394
341
  return fn;
395
342
  };
396
343
  fn.withContext = (value) => {
397
- context2 = value;
344
+ context = value;
398
345
  return fn;
399
346
  };
400
347
  fn.withCredentials = (value) => {
401
348
  withCredentials = value;
402
349
  return fn;
403
350
  };
404
- fn.withValidators = (value) => {
405
- validators = value;
351
+ fn.withValidators = (...fns) => {
352
+ validators = fns;
406
353
  return fn;
407
354
  };
408
355
  fn.withTransformResponse = (value) => {
@@ -535,11 +482,11 @@ async function __fillRequestFromField(request, fieldOrFieldGroup, input) {
535
482
  const json = {};
536
483
  let body = undefined;
537
484
  let lastBodyField;
538
- for (const [propertyKey, field3] of Object.entries(fieldOrFieldGroup)) {
539
- const meta = __getFieldMetadata(field3);
485
+ for (const [propertyKey, field2] of Object.entries(fieldOrFieldGroup)) {
486
+ const meta = __getFieldMetadata(field2);
540
487
  for (const [type, aliasName] of meta.alias) {
541
488
  const valueKey = aliasName || propertyKey;
542
- const value = getValidValue(input[propertyKey], field3());
489
+ const value = getValidValue(input[propertyKey], field2());
543
490
  await doValid([...meta.validators, ...meta.asyncValidator], value);
544
491
  switch (type) {
545
492
  case 0 /* Json */: {
@@ -600,15 +547,62 @@ async function __fillRequestFromField(request, fieldOrFieldGroup, input) {
600
547
  throw ERR_UNSUPPORTED_FIELD_TYPE;
601
548
  }
602
549
 
550
+ // src/handler/util.ts
551
+ function __getContentLength(headers) {
552
+ const value = headers.get("Content-Length");
553
+ if (!value) {
554
+ return 0;
555
+ }
556
+ const num = Number(value);
557
+ if (isNaN(num)) {
558
+ return 0;
559
+ }
560
+ return num;
561
+ }
562
+ function __getContentType(headers) {
563
+ return headers.get("Content-Type") || "";
564
+ }
565
+ function __parseBody(params) {
566
+ const { request, content, contentType } = params;
567
+ const responseType = request.responseType;
568
+ switch (responseType) {
569
+ case "json": {
570
+ const text = new TextDecoder().decode(content);
571
+ if (text === "") {
572
+ return null;
573
+ }
574
+ return JSON.parse(text);
575
+ }
576
+ case "text":
577
+ return new TextDecoder().decode(content);
578
+ case "blob": {
579
+ return new Blob([content], { type: contentType });
580
+ }
581
+ case "arraybuffer":
582
+ return content.buffer;
583
+ default:
584
+ return null;
585
+ }
586
+ }
587
+ function __concatChunks(chunks, totalLength) {
588
+ const chunksAll = new Uint8Array(totalLength);
589
+ let position = 0;
590
+ for (const chunk of chunks) {
591
+ chunksAll.set(chunk, position);
592
+ position += chunk.length;
593
+ }
594
+ return chunksAll;
595
+ }
596
+
603
597
  // src/handler/fetch/fetch.ts
604
- function __createRequest(request2) {
605
- const url = new URL(request2.endpoint, request2.host);
606
- if (request2.queryParams) {
607
- url.search = request2.queryParams.toString();
598
+ function __createRequest(request) {
599
+ const url = new URL(request.endpoint, request.host);
600
+ if (request.queryParams) {
601
+ url.search = request.queryParams.toString();
608
602
  }
609
- const headers = request2.headers ?? new Headers;
603
+ const headers = request.headers ?? new Headers;
610
604
  if (!headers.has("Content-Type")) {
611
- const detectedType = __detectContentTypeHeader(request2.body);
605
+ const detectedType = __detectContentTypeHeader(request.body);
612
606
  if (detectedType) {
613
607
  headers.set("Content-Type", detectedType);
614
608
  }
@@ -616,22 +610,22 @@ function __createRequest(request2) {
616
610
  if (!headers.has("Accept")) {
617
611
  headers.set("Accept", "application/json, text/plain, */*");
618
612
  }
619
- const credentials = request2.withCredentials ? "include" : undefined;
613
+ const credentials = request.withCredentials ? "include" : undefined;
620
614
  return new Request(url, {
621
615
  headers,
622
- method: request2.method,
623
- body: __serializeBody(request2.body),
624
- signal: request2.abort,
616
+ method: request.method,
617
+ body: __serializeBody(request.body),
618
+ signal: request.abort,
625
619
  credentials
626
620
  });
627
621
  }
628
622
  async function fetchHandler(httpRequest) {
629
623
  const downloadProgress = httpRequest.downloadProgress;
630
- const request2 = __createRequest(httpRequest);
624
+ const request = __createRequest(httpRequest);
631
625
  const abortSignal = httpRequest.abort;
632
- let response4;
626
+ let response;
633
627
  try {
634
- response4 = await globalThis.fetch(request2);
628
+ response = await globalThis.fetch(request);
635
629
  } catch (error) {
636
630
  if (abortSignal?.aborted && abortSignal.reason instanceof Error) {
637
631
  switch (true) {
@@ -643,13 +637,13 @@ async function fetchHandler(httpRequest) {
643
637
  }
644
638
  return __makeResponse({ error });
645
639
  }
646
- const { headers, status, statusText, url } = response4;
640
+ const { headers, status, statusText, url } = response;
647
641
  const contentLength = __getContentLength(headers);
648
642
  const contentType = __getContentType(headers);
649
643
  let body = null;
650
- if (response4.body) {
644
+ if (response.body) {
651
645
  const chunks = [];
652
- const reader = response4.body.getReader();
646
+ const reader = response.body.getReader();
653
647
  let receivedLength = 0;
654
648
  while (true) {
655
649
  const { done, value } = await reader.read();
@@ -690,14 +684,16 @@ async function fetchHandler(httpRequest) {
690
684
  });
691
685
  }
692
686
  // src/client.ts
687
+ var CLIENT = Symbol("Client");
688
+ var globalClient;
693
689
  function isClient(value) {
694
690
  return typeof value === "object" && value !== null && CLIENT in value;
695
691
  }
696
- function getClientConfig(client2) {
697
- if (!isClient(client2)) {
692
+ function getClientConfig(client) {
693
+ if (!isClient(client)) {
698
694
  throw ERR_INVALID_CLIENT;
699
695
  }
700
- return client2[CLIENT];
696
+ return client[CLIENT];
701
697
  }
702
698
  function createClient(options) {
703
699
  const conf = {
@@ -709,8 +705,8 @@ function createClient(options) {
709
705
  [CLIENT]: conf
710
706
  };
711
707
  }
712
- function cloneClient(client2, options) {
713
- const preConf = getClientConfig(client2);
708
+ function cloneClient(client, options) {
709
+ const preConf = getClientConfig(client);
714
710
  const conf = {
715
711
  ...preConf,
716
712
  ...options
@@ -725,8 +721,8 @@ function getGlobalClient() {
725
721
  }
726
722
  return globalClient;
727
723
  }
728
- function setGlobalClient(client2) {
729
- globalClient = client2;
724
+ function setGlobalClient(client) {
725
+ globalClient = client;
730
726
  }
731
727
  function restGlobalClient() {
732
728
  globalClient = undefined;
@@ -734,8 +730,6 @@ function restGlobalClient() {
734
730
  function createGlobalClient(options) {
735
731
  globalClient = createClient(options);
736
732
  }
737
- var CLIENT = Symbol("Client");
738
- var globalClient;
739
733
  // src/interceptor/authorization/basic_auth_interceptor.ts
740
734
  function basicAuthInterceptor(fn, options) {
741
735
  let encode = options?.encode;
package/index.min.js CHANGED
@@ -1 +1 @@
1
- function d(t){const n=t.get("Content-Length");if(!n)return 0;const r=Number(n);if(isNaN(r))return 0;return r}function a(t){return t.get("Content-Type")||""}function q(t){const{request:n,content:r,contentType:o}=t;switch(n.responseType){case"json":{const H=new TextDecoder().decode(r);if(H==="")return null;return JSON.parse(H)}case"text":return new TextDecoder().decode(r);case"blob":return new Blob([r],{type:o});case"arraybuffer":return r.buffer;default:return null}}function l(t,n){const r=new Uint8Array(n);let o=0;for(let T of t)r.set(T,o),o+=T.length;return r}function N(t){const n=t?.status??0,r=n>=200&&n<300,o=t?.statusText??"",T=t?.url??"",H=t?.headers??new Headers,f=t?.body??null;let R=t?.error;if(!R&&!r){let e=`Http failure response for ${T||"(unknown url)"}: ${n}`;if(o)e+=` - ${o}`;R=new Error(e)}return{status:n,statusText:o,url:T,headers:H,body:f,error:R}}var y=new Error("ERR_ABORTED"),K=new Error("ERR_TIMEOUT"),Ht=new Error("ERR_NETWORK"),X=new Error("ERR_NOT_FOUND_HANDLER"),Et=new Error("ERR_OBSERVE"),A=new Error("ERR_NOT_SET_ALIAS"),W=new Error("ERR_UNSUPPORTED_FIELD_TYPE"),J=new Error("ERR_INVALID_CLIENT"),j=new Error("ERR_NOT_FOUND_GLOBAL_CLIENT"),P=new Error("ERR_INVALID_HTTP_CONTEXT_TOKEN"),pt=new Error("ERR_UNKNOWN");function wt(t){return Object.defineProperty(t,v,{value:t}),t}function V(t){return typeof t==="function"&&v in t}function Rt(t){return typeof t==="object"&&t!==null&&Q in t}function Y(t){const n=new Map;switch(!0){case Array.isArray(t):{for(let[r,o]of t)if(V(r))n.set(r,o);break}case Rt(t):{for(let[r,o]of t[Q])n.set(r,o);break}}return{set(r,o){if(!V(r))throw P;return n.set(r,o),this},get(r){if(!V(r))throw P;if(!n.has(r))n.set(r,r());return n.get(r)},del(r){return n.delete(r),this},has(r){return n.has(r)},keys(){return n.keys()},get length(){return Array.from(n.keys()).length},[Q]:n}}var v=Symbol("HttpContextToken"),Q=Symbol("HttpContext");function it(t){const n={required:typeof t!=="undefined",alias:new Map,validators:[],asyncValidator:[]},r=()=>t;return Object.defineProperty(r,Z,{value:n}),r.withJson=(o)=>{return n.alias.set(0,o),r},r.withForm=(o)=>{return n.alias.set(4,o),r},r.withQuery=(o)=>{return n.alias.set(1,o),r},r.withParam=(o)=>{return n.alias.set(2,o),r},r.withHeader=(o)=>{return n.alias.set(3,o),r},r.withUrlForm=(o)=>{return n.alias.set(6,o),r},r.withBody=()=>{return n.alias.set(5,void 0),r},r.withValidators=(...o)=>{return n.validators=o,r},r.withAsyncValidators=(...o)=>{return n.asyncValidator=o,r},r}function G(t){return t[Z]}async function M(t,n){await Promise.all(t.map((r)=>r(n)))}function D(t){return!!t&&typeof t==="function"&&Z in t}function $(t){return!!t&&typeof t==="object"&&Object.entries(t).every(([,n])=>D(n))}var Z=Symbol("field");var ft=void 0;var tt=()=>ft;function nt(t){return t.reduceRight((n,r)=>{return(o,T)=>r(o,(H)=>n(H,T))},(n,r)=>r(n))}function ot(t){switch(!0){case t instanceof FormData:case t instanceof Blob:case t instanceof ArrayBuffer:case t instanceof URLSearchParams:case typeof t==="string":return t;case typeof t==="object":case typeof t==="boolean":case typeof t==="number":case Array.isArray(t):return JSON.stringify(t);default:return null}}function et(t){switch(!0){case t instanceof FormData:return"multipart/form-data";case t instanceof ArrayBuffer:return"application/octet-stream";case t instanceof Blob:return t.type||"application/octet-stream";case t instanceof URLSearchParams:return"application/x-www-form-urlencoded;charset=UTF-8";case typeof t==="string":return"text/plain";case(typeof t==="object"&&t!==null):case typeof t==="number":case typeof t==="boolean":return"application/json";default:return null}}function kt(t){if(D(t))return t();if($(t)){const n={};for(let[r,o]of Object.entries(t))n[r]=o();return n}return}function Ct(...t){let n,r,o=!1,T,H=[],f="json",R,e=!1,p=[],w;switch(t.length){case 1:{n="GET",r=t[0];break}case 2:{n=t[0],r=t[1];break}default:throw new Error("Invalid arguments")}const c=(x)=>{const i=x?.timeout||0,k=x?.client||S(),E=z(k),C=x?.handler||E?.handler||tt();if(!C)throw X;let m,I,B;const _=[];if(x?.abort)_.push(x.abort);else B=new AbortController,_.push(B.signal);if(i>0)_.push(AbortSignal.timeout(i));return{doRequest:async(...F)=>{try{let U;if(o&&F.length===1)U=F[0];if(o&&!U)throw new Error("Because the request has input, the argument must be the input value");if(p.length>0)for(let ct of p)ct(U);const b={host:E?.host,method:n,endpoint:r,queryParams:new URLSearchParams,headers:new Headers,body:void 0,withCredentials:e,responseType:f,context:R||Y(),uploadProgress:m,downloadProgress:I,timeout:i,abort:AbortSignal.any(_)};if(o&&T)await st(b,T,U);let h=await nt([...E.interceptors,...H])(b,C);if(typeof w==="function")h=N({...h,body:w(h)});return h}catch(U){return N({error:U})}},cancel:()=>{B?.abort()},getInitValue:()=>kt(T),setUploadProgress:(F)=>{m=F},setDownloadProgress:(F)=>{I=F}}};return c.withField=(x)=>{return T=x,o=!0,c},c.withInterceptors=(x)=>{return H=x,c},c.withContext=(x)=>{return R=x,c},c.withCredentials=(x)=>{return e=x,c},c.withValidators=(x)=>{return p=x,c},c.withTransformResponse=(x)=>{return w=x,c},c.withResponseType=(x)=>{return f=x,c},c}function rt(t,n){return t.replace(/:([^\/]+)/g,(r,o)=>{return n.get(o)??"undefined"})}async function st(t,n,r){function o(e){return typeof e==="object"&&e!==null}function T(e){switch(!0){case Array.isArray(e):case(typeof e==="object"&&e!==null):return JSON.stringify(e);case(typeof e==="object"&&e===null):case typeof e==="boolean":case typeof e==="number":case typeof e==="string":return String(e);default:throw new Error("Unsupported value type")}}function H(e,p,w){if(Array.isArray(w))for(let c of w)e.append(p,T(c));else e.set(p,T(w));return e}function f(e,p,w){if(Array.isArray(w))for(let c of w)f(e,p,T(c));return e.set(p,T(w)),e}function R(e,p){switch(!0){case typeof e==="undefined":return p;case(typeof e==="object"&&e===null):return e;default:return e}}if(D(n)){let e,p,w,c=void 0;const x=R(r,n()),i=G(n);await M([...i.validators,...i.asyncValidator],x);for(let[k,E]of i.alias)switch(k){case 1:{if(!E)throw A;p=H(new URLSearchParams,E,x);break}case 2:{if(!E)throw A;e=f(new Map,E,x);break}case 3:{if(!E)throw A;w=H(new Headers,E,x);break}case 4:{if(!E)throw A;c=H(new FormData,E,x);break}case 6:{if(!E)throw A;c=H(new URLSearchParams,E,x);break}case 0:case 5:c=x;break}if(e)t.endpoint=rt(t.endpoint,e);t.queryParams=p,t.headers=w,t.body=c;return}if($(n)&&o(r)){let e=new Map,p=new URLSearchParams,w=new Headers,c=new URLSearchParams,x=new FormData;const i={};let k=void 0,E;for(let[C,m]of Object.entries(n)){const I=G(m);for(let[B,_]of I.alias){const O=_||C,s=R(r[C],m());switch(await M([...I.validators,...I.asyncValidator],s),B){case 0:{Object.defineProperty(i,O,{value:s,writable:!0,enumerable:!0}),E=0;break}case 1:p=H(p,O,s);break;case 2:e=f(e,O,s);break;case 3:w=H(w,O,s);break;case 4:{x=H(x,O,s),E=4;break}case 6:{c=H(c,O,s),E=6;break}case 5:{k=s,E=5;break}}}}switch(t.endpoint=rt(t.endpoint,e),t.queryParams=p,t.headers=w,E){case 5:t.body=k;break;case 4:t.body=x;break;case 6:t.body=c;break;case 0:t.body=i;break}return}throw W}function Nt(t){const n=new URL(t.endpoint,t.host);if(t.queryParams)n.search=t.queryParams.toString();const r=t.headers??new Headers;if(!r.has("Content-Type")){const T=et(t.body);if(T)r.set("Content-Type",T)}if(!r.has("Accept"))r.set("Accept","application/json, text/plain, */*");const o=t.withCredentials?"include":void 0;return new Request(n,{headers:r,method:t.method,body:ot(t.body),signal:t.abort,credentials:o})}async function u(t){const n=t.downloadProgress,r=Nt(t),o=t.abort;let T;try{T=await globalThis.fetch(r)}catch(x){if(o?.aborted&&o.reason instanceof Error)switch(!0){case o.reason.name==="AbortError":return N({error:y});case o.reason.name==="TimeoutError":return N({error:K})}return N({error:x})}const{headers:H,status:f,statusText:R,url:e}=T,p=d(H),w=a(H);let c=null;if(T.body){const x=[],i=T.body.getReader();let k=0;while(!0){const{done:C,value:m}=await i.read();if(C)break;x.push(m),k+=m.length,n?.({lengthComputable:p>0,loaded:k,total:p})}const E=l(x,k);try{c=q({request:t,content:E,contentType:w})}catch(C){return N({error:C,status:f,statusText:R,headers:H,url:e})}}return N({status:f,statusText:R,headers:H,url:e,body:c})}function xt(t){return typeof t==="object"&&t!==null&&g in t}function z(t){if(!xt(t))throw J;return t[g]}function Tt(t){const n={host:t.host,interceptors:t.interceptors??[],handler:t.handler||u};return{[g]:n}}function mt(t,n){const o={...z(t),...n};return{[g]:o}}function S(){if(!L)throw j;return L}function Ot(t){L=t}function At(){L=void 0}function It(t){L=Tt(t)}var g=Symbol("Client"),L;function _t(t,n){let r=n?.encode;if(!r){const o=globalThis.btoa;if(typeof o!=="function")throw new Error("BasicAuthInterceptor is not supported in this environment");r=(T)=>o(`${T.username}:${T.password}`)}return(o,T)=>{const H=o.headers||new Headers;return H.set("Authorization",`Basic ${r(t())}`),o.headers=H,T(o)}}var Ft=(t)=>{if(!t)return new Error("required");return null},Ut=(t)=>{if(typeof t!=="boolean"||!t)return new Error("requiredTrue");return null},Bt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length<t)return new Error(`minLength ${t}`);return null}},Dt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length>t)return new Error(`maxLength ${t}`);return null}},Lt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n<t)return new Error(`minLength ${t}`);return null}},ht=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n>t)return new Error(`maxLength ${t}`);return null}},Pt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(!t.test(n))return new Error("pattern");return null}};export{Ot as setGlobalClient,At as restGlobalClient,Ut as requiredTrue,Ft as required,Pt as pattern,Bt as minLength,Lt as min,Dt as maxLength,ht as max,wt as makeHttpContextToken,Y as makeHttpContext,V as isHttpContextToken,$ as isFieldGroup,D as isField,xt as isClient,S as getGlobalClient,it as field,u as fetchHandler,M as doValid,Ct as defineRequest,It as createGlobalClient,Tt as createClient,mt as cloneClient,_t as basicAuthInterceptor,W as ERR_UNSUPPORTED_FIELD_TYPE,pt as ERR_UNKNOWN,K as ERR_TIMEOUT,Et as ERR_OBSERVE,A as ERR_NOT_SET_ALIAS,X as ERR_NOT_FOUND_HANDLER,j as ERR_NOT_FOUND_GLOBAL_CLIENT,Ht as ERR_NETWORK,P as ERR_INVALID_HTTP_CONTEXT_TOKEN,J as ERR_INVALID_CLIENT,y as ERR_ABORTED};
1
+ var K=new Error("ERR_ABORTED"),X=new Error("ERR_TIMEOUT"),Ht=new Error("ERR_NETWORK"),y=new Error("ERR_NOT_FOUND_HANDLER"),Et=new Error("ERR_OBSERVE"),A=new Error("ERR_NOT_SET_ALIAS"),W=new Error("ERR_UNSUPPORTED_FIELD_TYPE"),J=new Error("ERR_INVALID_CLIENT"),j=new Error("ERR_NOT_FOUND_GLOBAL_CLIENT"),L=new Error("ERR_INVALID_HTTP_CONTEXT_TOKEN"),pt=new Error("ERR_UNKNOWN");function N(t){let n=t?.status??0,r=n>=200&&n<300,o=t?.statusText??"",T=t?.url??"",H=t?.headers??new Headers,f=t?.body??null,i=t?.error;if(!i&&!r){let e=`Http failure response for ${T||"(unknown url)"}: ${n}`;if(o)e+=` - ${o}`;i=new Error(e)}return{status:n,statusText:o,url:T,headers:H,body:f,error:i}}var d=Symbol("HttpContextToken");function wt(t){return Object.defineProperty(t,d,{value:t}),t}function P(t){return typeof t==="function"&&d in t}var Q=Symbol("HttpContext");function it(t){return typeof t==="object"&&t!==null&&Q in t}function Y(t){let n=new Map;switch(!0){case Array.isArray(t):{for(let[r,o]of t)if(P(r))n.set(r,o);break}case it(t):{for(let[r,o]of t[Q])n.set(r,o);break}}return{set(r,o){if(!P(r))throw L;return n.set(r,o),this},get(r){if(!P(r))throw L;if(!n.has(r))n.set(r,r());return n.get(r)},del(r){return n.delete(r),this},has(r){return n.has(r)},keys(){return n.keys()},get length(){return Array.from(n.keys()).length},[Q]:n}}var Z=Symbol("field");function Rt(t){let n={required:typeof t!=="undefined",alias:new Map,validators:[],asyncValidator:[]},r=()=>t;return Object.defineProperty(r,Z,{value:n}),r.withJson=(o)=>{return n.alias.set(0,o),r},r.withForm=(o)=>{return n.alias.set(4,o),r},r.withQuery=(o)=>{return n.alias.set(1,o),r},r.withParam=(o)=>{return n.alias.set(2,o),r},r.withHeader=(o)=>{return n.alias.set(3,o),r},r.withUrlForm=(o)=>{return n.alias.set(6,o),r},r.withBody=()=>{return n.alias.set(5,void 0),r},r.withValidators=(...o)=>{return n.validators=o,r},r.withAsyncValidators=(...o)=>{return n.asyncValidator=o,r},r}function G(t){return t[Z]}async function V(t,n){await Promise.all(t.map((r)=>r(n)))}function M(t){return!!t&&typeof t==="function"&&Z in t}function g(t){return!!t&&typeof t==="object"&&Object.entries(t).every(([,n])=>M(n))}var ft=void 0;var a=()=>ft;function q(t){return t.reduceRight((n,r)=>{return(o,T)=>r(o,(H)=>n(H,T))},(n,r)=>r(n))}function v(t){switch(!0){case t instanceof FormData:case t instanceof Blob:case t instanceof ArrayBuffer:case t instanceof URLSearchParams:case typeof t==="string":return t;case typeof t==="object":case typeof t==="boolean":case typeof t==="number":case Array.isArray(t):return JSON.stringify(t);default:return null}}function tt(t){switch(!0){case t instanceof FormData:case t instanceof URLSearchParams:return null;case t instanceof ArrayBuffer:return"application/octet-stream";case t instanceof Blob:return t.type||"application/octet-stream";case typeof t==="string":return"text/plain";case(typeof t==="object"&&t!==null):case typeof t==="number":case typeof t==="boolean":return"application/json";default:return null}}function kt(t){if(g(t)){let n={};for(let[r,o]of Object.entries(t))n[r]=o();return n}return}function st(...t){let n,r,o=!1,T,H=[],f="json",i,e=!1,p=[],w;switch(t.length){case 1:{n="GET",r=t[0];break}case 2:{n=t[0],r=t[1];break}default:throw new Error("Invalid arguments")}let c=(x)=>{let R=x?.timeout||0,k=x?.client||S(),E=z(k),s=x?.handler||E?.handler||a();if(!s)throw y;let m,I,h,_=[];if(x?.abort)_.push(x.abort);else h=new AbortController,_.push(h.signal);if(R>0)_.push(AbortSignal.timeout(R));return{doRequest:async(...F)=>{try{let U;if(o&&F.length===1)U=F[0];if(o&&!U)throw new Error("Because the request has input, the argument must be the input value");if(p.length>0)for(let ct of p)ct(U);let b={host:E?.host,method:n,endpoint:r,queryParams:new URLSearchParams,headers:new Headers,body:void 0,withCredentials:e,responseType:f,context:i||Y(),uploadProgress:m,downloadProgress:I,timeout:R,abort:AbortSignal.any(_)};if(o&&T)await Ct(b,T,U);let D=await q([...E.interceptors,...H])(b,s);if(typeof w==="function")D=N({...D,body:w(D)});return D}catch(U){return N({error:U})}},cancel:()=>{h?.abort()},getInitValue:()=>kt(T),setUploadProgress:(F)=>{m=F},setDownloadProgress:(F)=>{I=F}}};return c.withField=(x)=>{return T=x,o=!0,c},c.withInterceptors=(x)=>{return H=x,c},c.withContext=(x)=>{return i=x,c},c.withCredentials=(x)=>{return e=x,c},c.withValidators=(...x)=>{return p=x,c},c.withTransformResponse=(x)=>{return w=x,c},c.withResponseType=(x)=>{return f=x,c},c}function l(t,n){return t.replace(/:([^\/]+)/g,(r,o)=>{return n.get(o)??"undefined"})}async function Ct(t,n,r){function o(e){return typeof e==="object"&&e!==null}function T(e){switch(!0){case Array.isArray(e):case(typeof e==="object"&&e!==null):return JSON.stringify(e);case(typeof e==="object"&&e===null):case typeof e==="boolean":case typeof e==="number":case typeof e==="string":return String(e);default:throw new Error("Unsupported value type")}}function H(e,p,w){if(Array.isArray(w))for(let c of w)e.append(p,T(c));else e.set(p,T(w));return e}function f(e,p,w){if(Array.isArray(w))for(let c of w)f(e,p,T(c));return e.set(p,T(w)),e}function i(e,p){switch(!0){case typeof e==="undefined":return p;case(typeof e==="object"&&e===null):return e;default:return e}}if(M(n)){let e,p,w,c=void 0,x=i(r,n()),R=G(n);await V([...R.validators,...R.asyncValidator],x);for(let[k,E]of R.alias)switch(k){case 1:{if(!E)throw A;p=H(new URLSearchParams,E,x);break}case 2:{if(!E)throw A;e=f(new Map,E,x);break}case 3:{if(!E)throw A;w=H(new Headers,E,x);break}case 4:{if(!E)throw A;c=H(new FormData,E,x);break}case 6:{if(!E)throw A;c=H(new URLSearchParams,E,x);break}case 0:case 5:c=x;break}if(e)t.endpoint=l(t.endpoint,e);t.queryParams=p,t.headers=w,t.body=c;return}if(g(n)&&o(r)){let e=new Map,p=new URLSearchParams,w=new Headers,c=new URLSearchParams,x=new FormData,R={},k=void 0,E;for(let[s,m]of Object.entries(n)){let I=G(m);for(let[h,_]of I.alias){let O=_||s,C=i(r[s],m());switch(await V([...I.validators,...I.asyncValidator],C),h){case 0:{Object.defineProperty(R,O,{value:C,writable:!0,enumerable:!0}),E=0;break}case 1:p=H(p,O,C);break;case 2:e=f(e,O,C);break;case 3:w=H(w,O,C);break;case 4:{x=H(x,O,C),E=4;break}case 6:{c=H(c,O,C),E=6;break}case 5:{k=C,E=5;break}}}}switch(t.endpoint=l(t.endpoint,e),t.queryParams=p,t.headers=w,E){case 5:t.body=k;break;case 4:t.body=x;break;case 6:t.body=c;break;case 0:t.body=R;break}return}throw W}function nt(t){let n=t.get("Content-Length");if(!n)return 0;let r=Number(n);if(isNaN(r))return 0;return r}function rt(t){return t.get("Content-Type")||""}function ot(t){let{request:n,content:r,contentType:o}=t;switch(n.responseType){case"json":{let H=new TextDecoder().decode(r);if(H==="")return null;return JSON.parse(H)}case"text":return new TextDecoder().decode(r);case"blob":return new Blob([r],{type:o});case"arraybuffer":return r.buffer;default:return null}}function et(t,n){let r=new Uint8Array(n),o=0;for(let T of t)r.set(T,o),o+=T.length;return r}function Nt(t){let n=new URL(t.endpoint,t.host);if(t.queryParams)n.search=t.queryParams.toString();let r=t.headers??new Headers;if(!r.has("Content-Type")){let T=tt(t.body);if(T)r.set("Content-Type",T)}if(!r.has("Accept"))r.set("Accept","application/json, text/plain, */*");let o=t.withCredentials?"include":void 0;return new Request(n,{headers:r,method:t.method,body:v(t.body),signal:t.abort,credentials:o})}async function u(t){let n=t.downloadProgress,r=Nt(t),o=t.abort,T;try{T=await globalThis.fetch(r)}catch(x){if(o?.aborted&&o.reason instanceof Error)switch(!0){case o.reason.name==="AbortError":return N({error:K});case o.reason.name==="TimeoutError":return N({error:X})}return N({error:x})}let{headers:H,status:f,statusText:i,url:e}=T,p=nt(H),w=rt(H),c=null;if(T.body){let x=[],R=T.body.getReader(),k=0;while(!0){let{done:s,value:m}=await R.read();if(s)break;x.push(m),k+=m.length,n?.({lengthComputable:p>0,loaded:k,total:p})}let E=et(x,k);try{c=ot({request:t,content:E,contentType:w})}catch(s){return N({error:s,status:f,statusText:i,headers:H,url:e})}}return N({status:f,statusText:i,headers:H,url:e,body:c})}var $=Symbol("Client"),B;function xt(t){return typeof t==="object"&&t!==null&&$ in t}function z(t){if(!xt(t))throw J;return t[$]}function Tt(t){let n={host:t.host,interceptors:t.interceptors??[],handler:t.handler||u};return{[$]:n}}function mt(t,n){let o={...z(t),...n};return{[$]:o}}function S(){if(!B)throw j;return B}function Ot(t){B=t}function At(){B=void 0}function It(t){B=Tt(t)}function _t(t,n){let r=n?.encode;if(!r){let o=globalThis.btoa;if(typeof o!=="function")throw new Error("BasicAuthInterceptor is not supported in this environment");r=(T)=>o(`${T.username}:${T.password}`)}return(o,T)=>{let H=o.headers||new Headers;return H.set("Authorization",`Basic ${r(t())}`),o.headers=H,T(o)}}var Ft=(t)=>{if(!t)return new Error("required");return null},Ut=(t)=>{if(typeof t!=="boolean"||!t)return new Error("requiredTrue");return null},ht=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length<t)return new Error(`minLength ${t}`);return null}},Bt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length>t)return new Error(`maxLength ${t}`);return null}},Dt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n<t)return new Error(`minLength ${t}`);return null}},Lt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n>t)return new Error(`maxLength ${t}`);return null}},Pt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(!t.test(n))return new Error("pattern");return null}};export{Ot as setGlobalClient,At as restGlobalClient,Ut as requiredTrue,Ft as required,Pt as pattern,ht as minLength,Dt as min,Bt as maxLength,Lt as max,wt as makeHttpContextToken,Y as makeHttpContext,P as isHttpContextToken,g as isFieldGroup,M as isField,xt as isClient,S as getGlobalClient,Rt as field,u as fetchHandler,V as doValid,st as defineRequest,It as createGlobalClient,Tt as createClient,mt as cloneClient,_t as basicAuthInterceptor,W as ERR_UNSUPPORTED_FIELD_TYPE,pt as ERR_UNKNOWN,X as ERR_TIMEOUT,Et as ERR_OBSERVE,A as ERR_NOT_SET_ALIAS,y as ERR_NOT_FOUND_HANDLER,j as ERR_NOT_FOUND_GLOBAL_CLIENT,Ht as ERR_NETWORK,L as ERR_INVALID_HTTP_CONTEXT_TOKEN,J as ERR_INVALID_CLIENT,K as ERR_ABORTED};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defjs/core",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "type": "module",
5
5
  "module": "index.js",
6
6
  "typings": "index.d.ts",