elysia 1.4.30 → 1.4.31

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/dist/compose.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Cookie } from "./index.mjs";
2
- import { Value, TransformDecodeError } from "@sinclair/typebox/value";
2
+ import { TransformDecodeError } from "@sinclair/typebox/value";
3
3
  import {
4
4
  Kind,
5
5
  TypeBoxError
@@ -10,6 +10,7 @@ import {
10
10
  parseQueryFromURL,
11
11
  parseQueryStandardSchema
12
12
  } from "./parse-query.mjs";
13
+ import { parseFormData } from "./form-data.mjs";
13
14
  import {
14
15
  ELYSIA_REQUEST_ID,
15
16
  getLoosePath,
@@ -21,6 +22,7 @@ import {
21
22
  isNotEmpty,
22
23
  encodePath,
23
24
  mergeCookie,
25
+ safeAssign,
24
26
  getResponseLength
25
27
  } from "./utils.mjs";
26
28
  import { isBun } from "./universal/utils.mjs";
@@ -33,6 +35,8 @@ import {
33
35
  } from "./error.mjs";
34
36
  import { ELYSIA_TRACE } from "./trace.mjs";
35
37
  import {
38
+ applySchemaDefaults,
39
+ cloneSchemaInput,
36
40
  getSchemaProperties,
37
41
  getSchemaValidator,
38
42
  hasElysiaMeta,
@@ -255,7 +259,7 @@ return function(){return a}`
255
259
  inference.server && (fnLiteral += `Object.defineProperty(c,'server',{get:function(){return getServer()}})
256
260
  `), validator.createBody?.(), validator.createQuery?.(), validator.createHeaders?.(), validator.createParams?.(), validator.createCookie?.(), validator.createResponse?.();
257
261
  const hasValidation = !!validator.body || !!validator.headers || !!validator.params || !!validator.query || !!validator.cookie || !!validator.response, hasQuery = inference.query || !!validator.query, requestNoBody = hooks.parse?.length === 1 && // @ts-expect-error
258
- hooks.parse[0].fn === "none", hasBody = method !== "" && method !== "GET" && method !== "HEAD" && (inference.body || !!validator.body || !!hooks.parse?.length) && !requestNoBody, defaultHeaders = app.setHeaders, hasDefaultHeaders = defaultHeaders && !!Object.keys(defaultHeaders).length, hasHeaders = inference.headers || !!validator.headers || adapter.preferWebstandardHeaders !== !0 && inference.body, hasCookie = inference.cookie || !!validator.cookie, cookieMeta = validator.cookie?.config ? mergeCookie(validator?.cookie?.config, app.config.cookie) : app.config.cookie;
262
+ hooks.parse[0].fn === "none", hasBody = method !== "" && method !== "GET" && method !== "HEAD" && (inference.body || !!validator.body || !!hooks.parse?.length) && !requestNoBody, defaultHeaders = app.setHeaders, hasDefaultHeaders = defaultHeaders && !!Object.keys(defaultHeaders).length, hasHeaders = inference.headers || !!validator.headers || adapter.preferWebstandardHeaders !== !0 && inference.body, hasCookie = inference.cookie || !!validator.cookie, defaultCookie = hooks.config?.cookie ? mergeCookie(app.config.cookie ?? {}, hooks.config.cookie) : app.config.cookie, cookieMeta = validator.cookie?.config ? mergeCookie(validator?.cookie?.config, defaultCookie) : defaultCookie;
259
263
  let _encodeCookie = "";
260
264
  const encodeCookie = () => {
261
265
  if (_encodeCookie) return _encodeCookie;
@@ -327,7 +331,7 @@ c.cookie=await parseCookie(c.set,c.request.headers.get('cookie'),${options})
327
331
  hasArrayProperty ? "," + JSON.stringify(arrayProperties) : hasObjectProperty ? ",undefined" : ""}${//
328
332
  hasObjectProperty ? "," + JSON.stringify(objectProperties) : ""})}`;
329
333
  }
330
- const isAsyncHandler = typeof handler == "function" && isAsync(handler), saveResponse = hasTrace || hooks.afterResponse?.length ? "c.response=c.responseValue= " : "", responseKeys = Object.keys(validator.response ?? {}), hasMultipleResponses = responseKeys.length > 1, hasSingle200 = responseKeys.length === 0 || responseKeys.length === 1 && responseKeys[0] === "200", maybeAsync = hasCookie || hasBody || isAsyncHandler || !!hooks.parse?.length || !!hooks.afterHandle?.some(isAsync) || !!hooks.beforeHandle?.some(isAsync) || !!hooks.transform?.some(isAsync) || !!hooks.mapResponse?.some(isAsync) || validator.body?.provider === "standard" || validator.headers?.provider === "standard" || validator.query?.provider === "standard" || validator.params?.provider === "standard" || validator.cookie?.provider === "standard" || Object.values(validator.response ?? {}).find(
334
+ const isAsyncHandler = typeof handler == "function" && isAsync(handler), saveResponse = hasTrace || hooks.afterResponse?.length ? "c.response=c.responseValue= " : "", responseKeys = Object.keys(validator.response ?? {}), hasMultipleResponses = responseKeys.length > 1, hasSingle200 = responseKeys.length === 0 || responseKeys.length === 1 && responseKeys[0] === "200", isAsyncBeforeHandle = (hook) => isAsync(hook) || hook.fn.toString().includes("[native code]"), maybeAsync = hasCookie || hasBody || isAsyncHandler || !!hooks.parse?.length || !!hooks.afterHandle?.some(isAsync) || !!hooks.beforeHandle?.some(isAsyncBeforeHandle) || !!hooks.transform?.some(isAsync) || !!hooks.mapResponse?.some(isAsync) || validator.body?.provider === "standard" || validator.headers?.provider === "standard" || validator.query?.provider === "standard" || validator.params?.provider === "standard" || validator.cookie?.provider === "standard" || Object.values(validator.response ?? {}).find(
331
335
  (x) => x.provider === "standard"
332
336
  ), maybeStream = (typeof handler == "function" ? isGenerator(handler) : !1) || !!hooks.beforeHandle?.some(isGenerator) || !!hooks.afterHandle?.some(isGenerator) || !!hooks.transform?.some(isGenerator), hasSet = inference.cookie || inference.set || hasHeaders || hasTrace || hasMultipleResponses || !hasSingle200 || isHandleFn && hasDefaultHeaders || maybeStream;
333
337
  let _afterResponse;
@@ -364,7 +368,7 @@ ${prefix}e.afterResponse[${i}](c)
364
368
  `;
365
369
  return after ? `const _res=${response}` + after + "return _res" : `return ${response}`;
366
370
  }, mapResponseContext = adapter.mapResponseContext ? `,${adapter.mapResponseContext}` : "";
367
- (hasTrace || inference.route) && (fnLiteral += `c.route=\`${path}\`
371
+ (hasTrace || inference.route) && (fnLiteral += `c.route=${JSON.stringify(path)}
368
372
  `), (hasTrace || hooks.afterResponse?.length) && (fnLiteral += `let afterHandlerStreamListener
369
373
  `);
370
374
  const parseReporter = report("parse", {
@@ -536,7 +540,7 @@ transformed.url=c.url
536
540
  transformed.redirect=c.redirect
537
541
  transformed.set=c.set
538
542
  transformed.error=c.error
539
- c=transformed}` : fnLiteral += "if(transformed instanceof ElysiaCustomStatusResponse){" + mapResponse("transformed") + `}else Object.assign(c,transformed)
543
+ c=transformed}` : fnLiteral += "if(transformed instanceof ElysiaCustomStatusResponse){" + mapResponse("transformed") + `}else safeAssign(c,transformed)
540
544
  `, endUnit();
541
545
  }
542
546
  }
@@ -545,24 +549,15 @@ c=transformed}` : fnLiteral += "if(transformed instanceof ElysiaCustomStatusResp
545
549
  const fileUnions = [];
546
550
  if (validator) {
547
551
  if (validator.headers) {
548
- if (validator.headers.hasDefault)
549
- for (const [key, value] of Object.entries(
550
- Value.Default(
551
- // @ts-ignore
552
- validator.headers.schema,
553
- {}
554
- )
555
- )) {
556
- const parsed = typeof value == "object" || typeof value == "string" ? JSON.stringify(value) : value;
557
- parsed !== void 0 && (fnLiteral += `c.headers[${JSON.stringify(key)}]??=${parsed}
558
- `);
559
- }
560
- fnLiteral += composeCleaner({
552
+ const cleanHeaders = composeCleaner({
561
553
  name: "c.headers",
562
554
  schema: validator.headers,
563
555
  type: "headers",
564
556
  normalize
565
- }), validator.headers.isOptional && (fnLiteral += "if(isNotEmpty(c.headers)){"), validator.headers?.provider === "standard" ? fnLiteral += `let vah=validator.headers.Validate(c.headers)
557
+ });
558
+ cleanHeaders && validator.headers.hasDefault && (fnLiteral += `c.headers=cloneSchemaInput(c.headers)
559
+ `), fnLiteral += cleanHeaders, validator.headers.hasDefault && (fnLiteral += `c.headers=applySchemaDefaults(validator.headers,c.headers,true)
560
+ `), validator.headers.isOptional && (fnLiteral += "if(isNotEmpty(c.headers)){"), validator.headers?.provider === "standard" ? fnLiteral += `let vah=validator.headers.Validate(c.headers)
566
561
  if(vah instanceof Promise)vah=await vah
567
562
  if(vah.issues){` + validation.validate("headers", void 0, "vah.issues") + `}else{c.headers=vah.value}
568
563
  ` : validator.headers?.schema?.noValidate !== !0 && (fnLiteral += "if(validator.headers.Check(c.headers) === false){" + validation.validate("headers") + "}"), validator.headers.hasTransform && (fnLiteral += coerceTransformDecodeError(
@@ -572,48 +567,25 @@ if(vah.issues){` + validation.validate("headers", void 0, "vah.issues") + `}else
572
567
  allowUnsafeValidationDetails
573
568
  )), validator.headers.isOptional && (fnLiteral += "}");
574
569
  }
575
- if (validator.params) {
576
- if (validator.params.hasDefault)
577
- for (const [key, value] of Object.entries(
578
- Value.Default(
579
- // @ts-ignore
580
- validator.params.schema,
581
- {}
582
- )
583
- )) {
584
- const parsed = typeof value == "object" || typeof value == "string" ? JSON.stringify(value) : value;
585
- parsed !== void 0 && (fnLiteral += `c.params[${JSON.stringify(key)}]??=${parsed}
586
- `);
587
- }
588
- validator.params.provider === "standard" ? fnLiteral += `let vap=validator.params.Validate(c.params)
570
+ if (validator.params && (validator.params.hasDefault && (fnLiteral += `c.params=applySchemaDefaults(validator.params,c.params,true)
571
+ `), validator.params.provider === "standard" ? fnLiteral += `let vap=validator.params.Validate(c.params)
589
572
  if(vap instanceof Promise)vap=await vap
590
573
  if(vap.issues){` + validation.validate("params", void 0, "vap.issues") + `}else{c.params=vap.value}
591
574
  ` : validator.params?.schema?.noValidate !== !0 && (fnLiteral += "if(validator.params.Check(c.params)===false){" + validation.validate("params") + "}"), validator.params.hasTransform && (fnLiteral += coerceTransformDecodeError(
592
- `c.params=validator.params.Decode(c.params)
575
+ `c.params=validator.params.Decode(c.params)
593
576
  `,
594
- "params",
595
- allowUnsafeValidationDetails
596
- ));
597
- }
598
- if (validator.query) {
599
- if (Kind in validator.query?.schema && validator.query.hasDefault)
600
- for (const [key, value] of Object.entries(
601
- Value.Default(
602
- // @ts-ignore
603
- validator.query.schema,
604
- {}
605
- )
606
- )) {
607
- const parsed = typeof value == "object" || typeof value == "string" ? JSON.stringify(value) : value;
608
- parsed !== void 0 && (fnLiteral += `if(c.query[${JSON.stringify(key)}]===undefined)c.query[${JSON.stringify(key)}]=${parsed}
609
- `);
610
- }
611
- fnLiteral += composeCleaner({
577
+ "params",
578
+ allowUnsafeValidationDetails
579
+ ))), validator.query) {
580
+ const cleanQuery = composeCleaner({
612
581
  name: "c.query",
613
582
  schema: validator.query,
614
583
  type: "query",
615
584
  normalize
616
- }), validator.query.isOptional && (fnLiteral += "if(isNotEmpty(c.query)){"), validator.query.provider === "standard" ? fnLiteral += `let vaq=validator.query.Validate(c.query)
585
+ });
586
+ cleanQuery && validator.query.hasDefault && (fnLiteral += `c.query=cloneSchemaInput(c.query)
587
+ `), fnLiteral += cleanQuery, Kind in validator.query?.schema && validator.query.hasDefault && (fnLiteral += `c.query=applySchemaDefaults(validator.query,c.query)
588
+ `), validator.query.isOptional && (fnLiteral += "if(isNotEmpty(c.query)){"), validator.query.provider === "standard" ? fnLiteral += `let vaq=validator.query.Validate(c.query)
617
589
  if(vaq instanceof Promise)vaq=await vaq
618
590
  if(vaq.issues){` + validation.validate("query", void 0, "vaq.issues") + `}else{c.query=vaq.value}
619
591
  ` : validator.query?.schema?.noValidate !== !0 && (fnLiteral += "if(validator.query.Check(c.query)===false){" + validation.validate("query") + "}"), validator.query.hasTransform && (fnLiteral += coerceTransformDecodeError(
@@ -629,32 +601,23 @@ if(vaq.issues){` + validation.validate("query", void 0, "vaq.issues") + `}else{c
629
601
  )), validator.query.isOptional && (fnLiteral += "}");
630
602
  }
631
603
  if (hasBody && validator.body) {
632
- (validator.body.hasTransform || validator.body.isOptional) && (fnLiteral += `const isNotEmptyObject=c.body&&(typeof c.body==="object"&&(isNotEmpty(c.body)||c.body instanceof ArrayBuffer))
604
+ (validator.body.hasTransform || validator.body.isOptional) && (fnLiteral += `let isNotEmptyObject
633
605
  `);
634
606
  const hasUnion = isUnion(validator.body.schema);
635
607
  let hasNonUnionFileWithDefault = !1;
636
608
  if (validator.body.hasDefault) {
637
- let value = Value.Default(
638
- validator.body.schema,
639
- validator.body.schema.type === "object" || unwrapImportSchema(validator.body.schema)[Kind] === "Object" ? {} : void 0
640
- );
641
609
  const schema = unwrapImportSchema(validator.body.schema);
642
- if (!hasUnion && value && typeof value == "object" && (hasType("File", schema) || hasType("Files", schema))) {
643
- hasNonUnionFileWithDefault = !0;
644
- for (const [k, v] of Object.entries(value))
645
- (v === "File" || v === "Files") && delete value[k];
646
- isNotEmpty(value) || (value = void 0);
647
- }
648
- const parsed = typeof value == "object" || typeof value == "string" ? JSON.stringify(value) : value;
649
- value != null && (Array.isArray(value) ? fnLiteral += `if(!c.body)c.body=${parsed}
650
- ` : typeof value == "object" ? fnLiteral += `c.body=Object.assign(${parsed},c.body)
651
- ` : fnLiteral += `c.body=${parsed}
652
- `), fnLiteral += composeCleaner({
610
+ !hasUnion && (hasType("File", schema) || hasType("Files", schema)) && (hasNonUnionFileWithDefault = !0);
611
+ const cleanBody = composeCleaner({
653
612
  name: "c.body",
654
613
  schema: validator.body,
655
614
  type: "body",
656
615
  normalize
657
- }), validator.body.provider === "standard" ? fnLiteral += `let vab=validator.body.Validate(c.body)
616
+ });
617
+ cleanBody && (fnLiteral += `c.body=cloneSchemaInput(c.body)
618
+ `), fnLiteral += cleanBody, fnLiteral += `c.body=applySchemaDefaults(validator.body,c.body)
619
+ `, (validator.body.hasTransform || validator.body.isOptional) && (fnLiteral += `isNotEmptyObject=c.body&&(typeof c.body==="object"&&(isNotEmpty(c.body)||c.body instanceof ArrayBuffer))
620
+ `), validator.body.provider === "standard" ? fnLiteral += `let vab=validator.body.Validate(c.body)
658
621
  if(vab instanceof Promise)vab=await vab
659
622
  if(vab.issues){` + validation.validate("body", void 0, "vab.issues") + `}else{c.body=vab.value}
660
623
  ` : validator.body?.schema?.noValidate !== !0 && (validator.body.isOptional ? fnLiteral += "if(isNotEmptyObject&&validator.body.Check(c.body)===false){" + validation.validate("body") + "}" : fnLiteral += "if(validator.body.Check(c.body)===false){" + validation.validate("body") + "}");
@@ -664,7 +627,8 @@ if(vab.issues){` + validation.validate("body", void 0, "vab.issues") + `}else{c.
664
627
  schema: validator.body,
665
628
  type: "body",
666
629
  normalize
667
- }), validator.body.provider === "standard" ? fnLiteral += `let vab=validator.body.Validate(c.body)
630
+ }), (validator.body.hasTransform || validator.body.isOptional) && (fnLiteral += `isNotEmptyObject=c.body&&(typeof c.body==="object"&&(isNotEmpty(c.body)||c.body instanceof ArrayBuffer))
631
+ `), validator.body.provider === "standard" ? fnLiteral += `let vab=validator.body.Validate(c.body)
668
632
  if(vab instanceof Promise)vab=await vab
669
633
  if(vab.issues){` + validation.validate("body", void 0, "vab.issues") + `}else{c.body=vab.value}
670
634
  ` : validator.body?.schema?.noValidate !== !0 && (validator.body.isOptional ? fnLiteral += "if(isNotEmptyObject&&validator.body.Check(c.body)===false){" + validation.validate("body") + "}" : fnLiteral += "if(validator.body.Check(c.body)===false){" + validation.validate("body") + "}");
@@ -700,7 +664,7 @@ if(vab.issues){` + validation.validate("body", void 0, "vab.issues") + `}else{c.
700
664
  let validateFile = "", validatorLength = 0;
701
665
  for (let i2 = 0; i2 < iterator2.length; i2++) {
702
666
  const [k, v] = iterator2[i2];
703
- !v.extension || v[Kind] !== "File" && v[Kind] !== "Files" || (validatorLength && (validateFile += ","), validateFile += `fileType(c.body.${k},${JSON.stringify(v.extension)},'body.${k}')`, validatorLength++);
667
+ !v.extension || v[Kind] !== "File" && v[Kind] !== "Files" || (validatorLength && (validateFile += ","), validateFile += `fileType(c.body[${JSON.stringify(k)}],${JSON.stringify(v.extension)},${JSON.stringify("body." + k)})`, validatorLength++);
704
668
  }
705
669
  validateFile && (validatorLength === 1 ? validator2 += `await ${validateFile}
706
670
  ` : validatorLength > 1 && (validator2 += `await Promise.all([${validateFile}])
@@ -722,7 +686,7 @@ if(vab.issues){` + validation.validate("body", void 0, "vab.issues") + `}else{c.
722
686
  let i = 0;
723
687
  if (bodyProperties)
724
688
  for (const [k, v] of Object.entries(bodyProperties))
725
- !v.extension || v[Kind] !== "File" && v[Kind] !== "Files" || (i && (validateFile += ","), validateFile += `fileType(c.body.${k},${JSON.stringify(v.extension)},'body.${k}')`, i++);
689
+ !v.extension || v[Kind] !== "File" && v[Kind] !== "Files" || (i && (validateFile += ","), validateFile += `fileType(c.body[${JSON.stringify(k)}],${JSON.stringify(v.extension)},${JSON.stringify("body." + k)})`, i++);
726
690
  i && (fnLiteral += `
727
691
  `), i === 1 ? fnLiteral += `await ${validateFile}
728
692
  ` : i > 1 && (fnLiteral += `await Promise.all([${validateFile}])
@@ -731,7 +695,7 @@ if(vab.issues){` + validation.validate("body", void 0, "vab.issues") + `}else{c.
731
695
  }
732
696
  validator.cookie && (validator.cookie.config = mergeCookie(
733
697
  validator.cookie.config,
734
- app.config.cookie ?? {}
698
+ defaultCookie ?? {}
735
699
  ), fnLiteral += `let cookieValue={}
736
700
  for(const [key,value] of Object.entries(c.cookie))cookieValue[key]=value.value
737
701
  `, validator.cookie.isOptional && (fnLiteral += "if(isNotEmpty(c.cookie)){"), validator.cookie.provider === "standard" ? (fnLiteral += `let vac=validator.cookie.Validate(cookieValue)
@@ -751,11 +715,11 @@ if(vac.issues){` + validation.validate("cookie", void 0, "vac.issues") + `}else{
751
715
  let hasResolve = !1;
752
716
  if (hooks.beforeHandle?.length)
753
717
  for (let i = 0; i < hooks.beforeHandle.length; i++) {
754
- const beforeHandle = hooks.beforeHandle[i], endUnit = reporter.resolveChild(beforeHandle.fn.name), returning = hasReturn(beforeHandle);
718
+ const beforeHandle = hooks.beforeHandle[i], asyncBeforeHandle = isAsyncBeforeHandle(beforeHandle), endUnit = reporter.resolveChild(beforeHandle.fn.name);
755
719
  if (beforeHandle.subType === "resolve" || beforeHandle.subType === "mapResolve")
756
720
  hasResolve || (hasResolve = !0, fnLiteral += `
757
721
  let resolved
758
- `), fnLiteral += isAsync(beforeHandle) ? `resolved=await e.beforeHandle[${i}](c);
722
+ `), fnLiteral += asyncBeforeHandle ? `resolved=await e.beforeHandle[${i}](c);
759
723
  ` : `resolved=e.beforeHandle[${i}](c);
760
724
  `, beforeHandle.subType === "mapResolve" ? fnLiteral += "if(resolved instanceof ElysiaCustomStatusResponse){" + mapResponse("resolved") + `}else{resolved.request=c.request
761
725
  resolved.store=c.store
@@ -765,14 +729,10 @@ resolved.url=c.url
765
729
  resolved.redirect=c.redirect
766
730
  resolved.set=c.set
767
731
  resolved.error=c.error
768
- c=resolved}` : fnLiteral += "if(resolved instanceof ElysiaCustomStatusResponse){" + mapResponse("resolved") + `}else Object.assign(c, resolved)
769
- `, endUnit();
770
- else if (!returning)
771
- fnLiteral += isAsync(beforeHandle) ? `await e.beforeHandle[${i}](c)
772
- ` : `e.beforeHandle[${i}](c)
732
+ c=resolved}` : fnLiteral += "if(resolved instanceof ElysiaCustomStatusResponse){" + mapResponse("resolved") + `}else safeAssign(c,resolved)
773
733
  `, endUnit();
774
734
  else {
775
- if (fnLiteral += isAsync(beforeHandle) ? `be=await e.beforeHandle[${i}](c)
735
+ if (fnLiteral += asyncBeforeHandle ? `be=await e.beforeHandle[${i}](c)
776
736
  ` : `be=e.beforeHandle[${i}](c)
777
737
  `, endUnit("be"), fnLiteral += "if(be!==undefined){", reporter.resolve(), hooks.afterHandle?.length || hasTrace) {
778
738
  report("handle", {
@@ -783,11 +743,11 @@ c=resolved}` : fnLiteral += "if(resolved instanceof ElysiaCustomStatusResponse){
783
743
  });
784
744
  if (hooks.afterHandle?.length)
785
745
  for (let i2 = 0; i2 < hooks.afterHandle.length; i2++) {
786
- const hook = hooks.afterHandle[i2], returning2 = hasReturn(hook), endUnit2 = reporter2.resolveChild(
746
+ const hook = hooks.afterHandle[i2], returning = hasReturn(hook), endUnit2 = reporter2.resolveChild(
787
747
  hook.fn.name
788
748
  );
789
749
  fnLiteral += `c.response=c.responseValue=be
790
- `, returning2 ? (fnLiteral += isAsync(hook.fn) ? `af=await e.afterHandle[${i2}](c)
750
+ `, returning ? (fnLiteral += isAsync(hook.fn) ? `af=await e.afterHandle[${i2}](c)
791
751
  ` : `af=e.afterHandle[${i2}](c)
792
752
  `, fnLiteral += `if(af!==undefined) c.response=c.responseValue=be=af
793
753
  `) : fnLiteral += isAsync(hook.fn) ? `await e.afterHandle[${i2}](c, be)
@@ -975,7 +935,7 @@ if(mep!==undefined)er=mep
975
935
  }
976
936
  errorReporter.resolve(), fnLiteral += "return handleError(c,error,true)", !maybeAsync && hooks.error?.length && (fnLiteral += "})()"), fnLiteral += "}";
977
937
  const adapterVariables = adapter.inject ? Object.keys(adapter.inject).join(",") + "," : "";
978
- let init = "const {handler,handleError,hooks:e, " + allocateIf("validator,", hasValidation) + "mapResponse,mapCompactResponse,mapEarlyResponse,isNotEmpty,utils:{" + allocateIf("parseQuery,", hasBody) + allocateIf("parseQueryFromURL,", hasQuery) + "},error:{" + allocateIf("ValidationError,", hasValidation) + allocateIf("ParseError", hasBody) + "},fileType,schema,definitions,tee,ERROR_CODE," + allocateIf("parseCookie,", hasCookie) + allocateIf("signCookie,", hasCookie) + allocateIf("decodeURIComponent,", hasQuery) + "ElysiaCustomStatusResponse," + allocateIf("ELYSIA_TRACE,", hasTrace) + allocateIf("ELYSIA_REQUEST_ID,", hasTrace) + allocateIf("parser,", hooks.parse?.length) + allocateIf("getServer,", inference.server) + allocateIf("fileUnions,", fileUnions.length) + adapterVariables + allocateIf("TypeBoxError", hasValidation) + `}=hooks
938
+ let init = "const {handler,handleError,hooks:e, " + allocateIf("validator,", hasValidation) + "mapResponse,mapCompactResponse,mapEarlyResponse,isNotEmpty,safeAssign,applySchemaDefaults,cloneSchemaInput,utils:{" + allocateIf("parseQuery,", hasBody) + allocateIf("parseQueryFromURL,", hasQuery) + allocateIf("parseFormData,", hasBody) + "},error:{" + allocateIf("ValidationError,", hasValidation) + allocateIf("ParseError", hasBody) + "},fileType,schema,definitions,tee,ERROR_CODE," + allocateIf("parseCookie,", hasCookie) + allocateIf("signCookie,", hasCookie) + allocateIf("decodeURIComponent,", hasQuery) + "ElysiaCustomStatusResponse," + allocateIf("ELYSIA_TRACE,", hasTrace) + allocateIf("ELYSIA_REQUEST_ID,", hasTrace) + allocateIf("parser,", hooks.parse?.length) + allocateIf("getServer,", inference.server) + allocateIf("fileUnions,", fileUnions.length) + adapterVariables + allocateIf("TypeBoxError", hasValidation) + `}=hooks
979
939
  const trace=e.trace
980
940
  return ${maybeAsync ? "async " : ""}function handle(c){`;
981
941
  hooks.beforeHandle?.length && (init += `let be
@@ -999,8 +959,12 @@ c.defs=definitions
999
959
  mapCompactResponse: adapterHandler.mapCompactResponse,
1000
960
  mapEarlyResponse: adapterHandler.mapEarlyResponse,
1001
961
  isNotEmpty,
962
+ safeAssign,
963
+ applySchemaDefaults,
964
+ cloneSchemaInput,
1002
965
  utils: {
1003
966
  parseQuery: hasBody ? parseQuery : void 0,
967
+ parseFormData: hasBody ? parseFormData : void 0,
1004
968
  parseQueryFromURL: hasQuery ? validator.query?.provider === "standard" ? parseQueryStandardSchema : parseQueryFromURL : void 0
1005
969
  },
1006
970
  error: {
@@ -1140,9 +1104,9 @@ return route.store.compile()(c)
1140
1104
  `;
1141
1105
  let switchMap = "";
1142
1106
  for (const [path, methods] of Object.entries(router.static)) {
1143
- switchMap += `case'${path}':`, app.config.strictPath !== !0 && (switchMap += `case'${getLoosePath(path)}':`);
1107
+ switchMap += `case${JSON.stringify(path)}:`, app.config.strictPath !== !0 && (switchMap += `case${JSON.stringify(getLoosePath(path))}:`);
1144
1108
  const encoded = encodePath(path);
1145
- path !== encoded && (switchMap += `case'${encoded}':`), switchMap += "switch(r.method){", ("GET" in methods || "WS" in methods) && (switchMap += "case 'GET':", "WS" in methods && (switchMap += `if(r.headers.get('upgrade')==='websocket')return ht[${methods.WS}].composed(c)
1109
+ path !== encoded && (switchMap += `case${JSON.stringify(encoded)}:`), switchMap += "switch(r.method){", ("GET" in methods || "WS" in methods) && (switchMap += "case 'GET':", "WS" in methods && (switchMap += `if(r.headers.get('upgrade')==='websocket')return ht[${methods.WS}].composed(c)
1146
1110
  `, "GET" in methods || ("ALL" in methods ? switchMap += `return ht[${methods.ALL}].composed(c)
1147
1111
  ` : switchMap += `break map
1148
1112
  `)), "GET" in methods && (switchMap += `return ht[${methods.GET}].composed(c)
@@ -1151,7 +1115,7 @@ return new Response(null,{status:_ht.status,statusText:_ht.statusText,headers:_h
1151
1115
  }))
1152
1116
  `);
1153
1117
  for (const [method, index] of Object.entries(methods))
1154
- method === "ALL" || method === "GET" || method === "WS" || (switchMap += `case '${method}':return ht[${index}].composed(c)
1118
+ method === "ALL" || method === "GET" || method === "WS" || (switchMap += `case ${JSON.stringify(method)}:return ht[${index}].composed(c)
1155
1119
  `);
1156
1120
  "ALL" in methods ? switchMap += `default:return ht[${methods.ALL}].composed(c)
1157
1121
  ` : switchMap += `default:break map
@@ -19,75 +19,7 @@ __export(dynamic_handle_exports, {
19
19
  createDynamicHandler: () => createDynamicHandler
20
20
  });
21
21
  module.exports = __toCommonJS(dynamic_handle_exports);
22
- var import_value = require("@sinclair/typebox/value"), import_cookies = require('./cookies.js'), import_error = require('./error.js'), import_parse_query = require('./parse-query.js'), import_schema = require('./schema.js'), import_utils = require('./utils.js');
23
- const ARRAY_INDEX_REGEX = /^(.+)\[(\d+)\]$/, DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), isDangerousKey = (key) => {
24
- if (DANGEROUS_KEYS.has(key)) return !0;
25
- const match = key.match(ARRAY_INDEX_REGEX);
26
- return match ? DANGEROUS_KEYS.has(match[1]) : !1;
27
- }, parseArrayKey = (key) => {
28
- const match = key.match(ARRAY_INDEX_REGEX);
29
- return match ? {
30
- name: match[1],
31
- index: parseInt(match[2], 10)
32
- } : null;
33
- }, parseObjectString = (entry) => {
34
- if (!(typeof entry != "string" || entry.charCodeAt(0) !== 123))
35
- try {
36
- const parsed = JSON.parse(entry);
37
- if (parsed && typeof parsed == "object" && !Array.isArray(parsed))
38
- return parsed;
39
- } catch {
40
- return;
41
- }
42
- }, setNestedValue = (obj, path, value) => {
43
- const keys = path.split("."), lastKey = keys.pop();
44
- if (isDangerousKey(lastKey) || keys.some(isDangerousKey)) return;
45
- let current = obj;
46
- for (const key of keys) {
47
- const arrayInfo2 = parseArrayKey(key);
48
- if (arrayInfo2) {
49
- Array.isArray(current[arrayInfo2.name]) || (current[arrayInfo2.name] = []);
50
- const existing = current[arrayInfo2.name][arrayInfo2.index], isFile = typeof File < "u" && existing instanceof File;
51
- (!existing || typeof existing != "object" || Array.isArray(existing) || isFile) && (current[arrayInfo2.name][arrayInfo2.index] = parseObjectString(existing) ?? {}), current = current[arrayInfo2.name][arrayInfo2.index];
52
- } else
53
- (!current[key] || typeof current[key] != "object") && (current[key] = {}), current = current[key];
54
- }
55
- const arrayInfo = parseArrayKey(lastKey);
56
- arrayInfo ? (Array.isArray(current[arrayInfo.name]) || (current[arrayInfo.name] = []), current[arrayInfo.name][arrayInfo.index] = value) : current[lastKey] = value;
57
- }, normalizeFormValue = (value) => {
58
- if (value.length === 1) {
59
- const stringValue2 = value[0];
60
- if (typeof stringValue2 == "string" && (stringValue2.charCodeAt(0) === 123 || stringValue2.charCodeAt(0) === 91))
61
- try {
62
- const parsed2 = JSON.parse(stringValue2);
63
- if (parsed2 && typeof parsed2 == "object")
64
- return parsed2;
65
- } catch {
66
- }
67
- return value[0];
68
- }
69
- const stringValue = value.find(
70
- (entry) => typeof entry == "string"
71
- );
72
- if (!stringValue || typeof File > "u") return value;
73
- const files = value.filter((entry) => entry instanceof File);
74
- if (!files.length || stringValue.charCodeAt(0) !== 123) return value;
75
- let parsed;
76
- try {
77
- parsed = JSON.parse(stringValue);
78
- } catch {
79
- return value;
80
- }
81
- return typeof parsed != "object" || parsed === null ? value : (!("file" in parsed) && files.length === 1 ? parsed.file = files[0] : !("files" in parsed) && files.length > 1 && (parsed.files = files), parsed);
82
- }, injectDefaultValues = (typeChecker, obj) => {
83
- let schema = typeChecker.schema;
84
- if (!schema) return;
85
- schema.$defs?.[schema.$ref] && (schema = schema.$defs[schema.$ref]);
86
- const properties = (0, import_schema.getSchemaProperties)(schema);
87
- if (properties)
88
- for (const [key, keySchema] of Object.entries(properties))
89
- obj[key] ??= keySchema.default;
90
- };
22
+ var import_value = require("@sinclair/typebox/value"), import_cookies = require('./cookies.js'), import_error = require('./error.js'), import_parse_query = require('./parse-query.js'), import_form_data = require('./form-data.js'), import_schema = require('./schema.js'), import_utils = require('./utils.js');
91
23
  async function validateStandardSchema(type, validator, value) {
92
24
  const result = await validator.Validate(value);
93
25
  if (result.issues)
@@ -135,10 +67,10 @@ const createDynamicHandler = (app) => {
135
67
  if (!handler)
136
68
  throw context.query = qi === -1 ? {} : (0, import_parse_query.parseQuery)(url.substring(qi + 1)), new import_error.NotFoundError();
137
69
  const { handle, validator, content, route } = handler.store;
138
- if (hooks = handler.store.hooks, hooks.config?.mount)
139
- return await hooks.config.mount(request);
70
+ hooks = handler.store.hooks;
71
+ const isMount = !!hooks.config?.mount;
140
72
  let body;
141
- if (request.method !== "GET" && request.method !== "HEAD")
73
+ if (!isMount && request.method !== "GET" && request.method !== "HEAD")
142
74
  if (content)
143
75
  switch (content) {
144
76
  case "application/json":
@@ -154,17 +86,7 @@ const createDynamicHandler = (app) => {
154
86
  body = await request.arrayBuffer();
155
87
  break;
156
88
  case "multipart/form-data": {
157
- body = {};
158
- const form = await request.formData(), grouped = /* @__PURE__ */ new Map();
159
- form.forEach((v, k) => {
160
- const list = grouped.get(k);
161
- list ? list.push(v) : grouped.set(k, [v]);
162
- });
163
- for (const [key, value] of grouped) {
164
- if (body[key]) continue;
165
- const finalValue = normalizeFormValue(value);
166
- key.includes(".") || key.includes("[") ? setNestedValue(body, key, finalValue) : body[key] = finalValue;
167
- }
89
+ body = (0, import_form_data.parseFormData)(await request.formData());
168
90
  break;
169
91
  }
170
92
  }
@@ -197,17 +119,9 @@ const createDynamicHandler = (app) => {
197
119
  break;
198
120
  case "formdata":
199
121
  case "multipart/form-data": {
200
- body = {};
201
- const form = await request.formData(), grouped = /* @__PURE__ */ new Map();
202
- form.forEach((v, k) => {
203
- const list = grouped.get(k);
204
- list ? list.push(v) : grouped.set(k, [v]);
205
- });
206
- for (const [key, value] of grouped) {
207
- if (body[key]) continue;
208
- const finalValue = normalizeFormValue(value);
209
- key.includes(".") || key.includes("[") ? setNestedValue(body, key, finalValue) : body[key] = finalValue;
210
- }
122
+ body = (0, import_form_data.parseFormData)(
123
+ await request.formData()
124
+ );
211
125
  break;
212
126
  }
213
127
  default: {
@@ -248,17 +162,9 @@ const createDynamicHandler = (app) => {
248
162
  body = await request.arrayBuffer();
249
163
  break;
250
164
  case "multipart/form-data": {
251
- body = {};
252
- const form = await request.formData(), grouped = /* @__PURE__ */ new Map();
253
- form.forEach((v, k) => {
254
- const list = grouped.get(k);
255
- list ? list.push(v) : grouped.set(k, [v]);
256
- });
257
- for (const [key, value] of grouped) {
258
- if (body[key]) continue;
259
- const finalValue = normalizeFormValue(value);
260
- key.includes(".") || key.includes("[") ? setNestedValue(body, key, finalValue) : body[key] = finalValue;
261
- }
165
+ body = (0, import_form_data.parseFormData)(
166
+ await request.formData()
167
+ );
262
168
  break;
263
169
  }
264
170
  }
@@ -267,29 +173,29 @@ const createDynamicHandler = (app) => {
267
173
  context.route = route, context.body = body, context.params = handler?.params || void 0, context.query = qi === -1 ? {} : (0, import_parse_query.parseQuery)(url.substring(qi + 1)), context.headers = {};
268
174
  for (const [key, value] of request.headers.entries())
269
175
  context.headers[key] = value;
270
- const cookieMeta = {
271
- domain: app.config.cookie?.domain ?? // @ts-expect-error
176
+ const cookieValidator = validator?.createCookie?.(), defaultCookie = hooks.config?.cookie ? (0, import_utils.mergeCookie)(app.config.cookie ?? {}, hooks.config.cookie) : app.config.cookie, cookieMeta = {
177
+ domain: defaultCookie?.domain ?? // @ts-expect-error
272
178
  validator?.cookie?.config.domain,
273
- expires: app.config.cookie?.expires ?? // @ts-expect-error
179
+ expires: defaultCookie?.expires ?? // @ts-expect-error
274
180
  validator?.cookie?.config.expires,
275
- httpOnly: app.config.cookie?.httpOnly ?? // @ts-expect-error
181
+ httpOnly: defaultCookie?.httpOnly ?? // @ts-expect-error
276
182
  validator?.cookie?.config.httpOnly,
277
- maxAge: app.config.cookie?.maxAge ?? // @ts-expect-error
183
+ maxAge: defaultCookie?.maxAge ?? // @ts-expect-error
278
184
  validator?.cookie?.config.maxAge,
279
185
  // @ts-expect-error
280
- path: app.config.cookie?.path ?? validator?.cookie?.config.path,
281
- priority: app.config.cookie?.priority ?? // @ts-expect-error
186
+ path: defaultCookie?.path ?? validator?.cookie?.config.path,
187
+ priority: defaultCookie?.priority ?? // @ts-expect-error
282
188
  validator?.cookie?.config.priority,
283
- partitioned: app.config.cookie?.partitioned ?? // @ts-expect-error
189
+ partitioned: defaultCookie?.partitioned ?? // @ts-expect-error
284
190
  validator?.cookie?.config.partitioned,
285
- sameSite: app.config.cookie?.sameSite ?? // @ts-expect-error
191
+ sameSite: defaultCookie?.sameSite ?? // @ts-expect-error
286
192
  validator?.cookie?.config.sameSite,
287
- secure: app.config.cookie?.secure ?? // @ts-expect-error
193
+ secure: defaultCookie?.secure ?? // @ts-expect-error
288
194
  validator?.cookie?.config.secure,
289
- secrets: app.config.cookie?.secrets ?? // @ts-expect-error
195
+ secrets: defaultCookie?.secrets ?? // @ts-expect-error
290
196
  validator?.cookie?.config.secrets,
291
197
  // @ts-expect-error
292
- sign: app.config.cookie?.sign ?? validator?.cookie?.config.sign
198
+ sign: defaultCookie?.sign ?? validator?.cookie?.config.sign
293
199
  }, cookieHeaderValue = request.headers.get("cookie");
294
200
  context.cookie = await (0, import_cookies.parseCookie)(
295
201
  context.set,
@@ -297,11 +203,23 @@ const createDynamicHandler = (app) => {
297
203
  cookieMeta
298
204
  );
299
205
  const headerValidator = validator?.createHeaders?.();
300
- headerValidator && injectDefaultValues(headerValidator, context.headers);
206
+ headerValidator?.hasDefault && (context.headers = (0, import_schema.applySchemaDefaults)(
207
+ headerValidator,
208
+ context.headers,
209
+ !0
210
+ ));
301
211
  const paramsValidator = validator?.createParams?.();
302
- paramsValidator && injectDefaultValues(paramsValidator, context.params);
212
+ paramsValidator?.hasDefault && (context.params = (0, import_schema.applySchemaDefaults)(
213
+ paramsValidator,
214
+ context.params,
215
+ !0
216
+ ));
303
217
  const queryValidator = validator?.createQuery?.();
304
- if (queryValidator && injectDefaultValues(queryValidator, context.query), hooks.transform)
218
+ if (queryValidator?.hasDefault && (context.query = (0, import_schema.applySchemaDefaults)(
219
+ queryValidator,
220
+ context.query,
221
+ !0
222
+ )), hooks.transform)
305
223
  for (let i = 0; i < hooks.transform.length; i++) {
306
224
  const hook = hooks.transform[i];
307
225
  let response2 = hook.fn(context);
@@ -310,7 +228,7 @@ const createDynamicHandler = (app) => {
310
228
  if (result)
311
229
  return context.response = result;
312
230
  }
313
- hook.subType === "derive" && Object.assign(context, response2);
231
+ hook.subType === "derive" && (0, import_utils.safeAssign)(context, response2);
314
232
  }
315
233
  if (validator) {
316
234
  if (headerValidator) {
@@ -370,32 +288,34 @@ const createDynamicHandler = (app) => {
370
288
  );
371
289
  validator.query?.Decode && (context.query = validator.query.Decode(context.query));
372
290
  }
373
- if (validator.createCookie?.()) {
291
+ if (cookieValidator) {
374
292
  let cookieValue = {};
375
293
  for (const [key, value] of Object.entries(context.cookie))
376
294
  cookieValue[key] = value.value;
377
- if (validator.cookie.provider === "standard") {
295
+ if (cookieValidator.provider === "standard") {
378
296
  cookieValue = await validateStandardSchema(
379
297
  "cookie",
380
- validator.cookie,
298
+ cookieValidator,
381
299
  cookieValue
382
300
  );
383
301
  for (const key of Object.keys(cookieValue))
384
302
  context.cookie[key].value = cookieValue[key];
385
303
  } else {
386
- if (validator.cookie.Check(cookieValue) === !1)
304
+ if (cookieValidator.Check(cookieValue) === !1)
387
305
  throw new import_error.ValidationError(
388
306
  "cookie",
389
- validator.cookie,
307
+ cookieValidator,
390
308
  cookieValue
391
309
  );
392
- validator.cookie?.Decode && (cookieValue = validator.cookie.Decode(
393
- cookieValue
394
- ));
310
+ if (cookieValidator.Decode) {
311
+ cookieValue = cookieValidator.Decode(cookieValue);
312
+ for (const key of Object.keys(cookieValue))
313
+ context.cookie[key].value = cookieValue[key];
314
+ }
395
315
  }
396
316
  }
397
317
  const bodyValidator = validator.createBody?.();
398
- if (bodyValidator?.provider === "standard")
318
+ if (bodyValidator?.hasDefault && (body = (0, import_schema.applySchemaDefaults)(bodyValidator, body), context.body = body), bodyValidator?.provider === "standard")
399
319
  context.body = await validateStandardSchema(
400
320
  "body",
401
321
  bodyValidator,
@@ -420,7 +340,7 @@ const createDynamicHandler = (app) => {
420
340
  return context.response = result;
421
341
  }
422
342
  if (hook.subType === "resolve") {
423
- Object.assign(context, response2);
343
+ (0, import_utils.safeAssign)(context, response2);
424
344
  continue;
425
345
  }
426
346
  if (response2 !== void 0) {
@@ -536,7 +456,9 @@ const createDynamicHandler = (app) => {
536
456
  secret
537
457
  );
538
458
  } else {
539
- const properties = (0, import_schema.getSchemaProperties)(validator?.cookie?.schema);
459
+ const properties = (0, import_schema.getSchemaProperties)(
460
+ validator?.cookie?.schema
461
+ );
540
462
  if (secret)
541
463
  for (const name of cookieMeta.sign)
542
464
  !properties || !(name in properties) || context.set.cookie[name]?.value && (context.set.cookie[name].value = await (0, import_utils.signCookie)(