elysia 1.4.17 → 1.4.18

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/bun/index.js CHANGED
@@ -37,7 +37,7 @@ const error404={clone:()=>new Response(error404Message,{status:404})}
37
37
  if(d.unions[${ui}][${i}].Check(tmp))return tmp
38
38
  `}if(cleanThenCheck)v+=cleanThenCheck;return v+=`return ${instruction.removeUnknownUnionType?"undefined":property}`,v+"})()"},mirror=(schema,property,instruction)=>{if(!schema)return"";let isRoot=property==="v"&&!instruction.unions.length;if(Kind3 in schema&&schema[Kind3]==="Import"&&schema.$ref in schema.$defs)return mirror(schema.$defs[schema.$ref],property,{...instruction,definitions:Object.assign(instruction.definitions,schema.$defs)});if(isRoot&&schema.type!=="object"&&schema.type!=="array"&&!schema.anyOf)return`return ${sanitize("v",instruction.sanitize?.length,schema)}`;if(instruction.recursion>=instruction.recursionLimit)return property;let v="";if(schema.$id&&Hint in schema)instruction.definitions[schema.$id]=schema;switch(schema.type){case"object":if(schema[Kind3]==="Record"){v=handleRecord(schema,property,instruction);break}if(schema=mergeObjectIntersection(schema),v+="{",schema.additionalProperties)v+=`...${property},`;let keys=Object.keys(schema.properties);for(let i2=0;i2<keys.length;i2++){let key=keys[i2],isOptional=!schema.required||schema.required&&!schema.required.includes(key)||Array.isArray(schema.properties[key].anyOf),name=joinProperty(property,key,instruction.parentIsOptional);if(isOptional){let index=instruction.array;if(property.startsWith("ar")){let dotIndex=name.indexOf("."),refName;if(dotIndex>=0)refName=name.slice(dotIndex);else refName=name.slice(property.length);if(refName.startsWith("?."))if(refName.charAt(2)==="[")refName=refName.slice(2);else refName=refName.slice(1);let array=instruction.optionalsInArray;if(array[index])array[index].push(refName);else array[index]=[refName]}else instruction.optionals.push(name)}let child=schema.properties[key];if(i2!==0)v+=",";v+=`${encodeProperty(key)}:${isOptional?`${name}===undefined?undefined:`:""}${mirror(child,name,{...instruction,recursion:instruction.recursion+1,parentIsOptional:isOptional})}`}v+="}";break;case"array":if(schema.items.type!=="object"&&schema.items.type!=="array"){if(Array.isArray(schema.items)){v=handleTuple(schema.items,property,instruction);break}else if(isRoot&&!Array.isArray(schema.items.anyOf))return"return v";else if(Kind3 in schema.items&&schema.items.$ref&&(schema.items[Kind3]==="Ref"||schema.items[Kind3]==="This"))v=mirror(deepClone(instruction.definitions[schema.items.$ref]),property,{...instruction,parentIsOptional:!0,recursion:instruction.recursion+1});else if(!Array.isArray(schema.items.anyOf)){v=property;break}}let i=instruction.array;instruction.array++;let reference=property;if(isRoot)v=`const ar${i}v=new Array(${property}.length);`;else reference=`ar${i}s`,v=`((${reference})=>{const ar${i}v=new Array(${reference}.length);`;v+=`for(let i=0;i<${reference}.length;i++){const ar${i}p=${reference}[i];ar${i}v[i]=${mirror(schema.items,`ar${i}p`,instruction)}`;let optionals=instruction.optionalsInArray[i+1];if(optionals)for(let oi=0;oi<optionals.length;oi++){let target=`ar${i}v[i]${optionals[oi]}`;v+=`;if(${target}===undefined)delete ${target}`}if(v+="}",!isRoot)v+=`return ar${i}v})(${property})`;break;default:if(schema.$ref&&schema.$ref in instruction.definitions)return mirror(instruction.definitions[schema.$ref],property,instruction);if(Array.isArray(schema.anyOf)){v=handleUnion(schema.anyOf,property,instruction);break}v=sanitize(property,instruction.sanitize?.length,schema);break}if(!isRoot)return v;if(schema.type==="array")v=`${v}const x=ar0v;`;else v=`const x=${v}
39
39
  `;for(let i=0;i<instruction.optionals.length;i++){let key=instruction.optionals[i],prop=key.slice(1);if(v+=`if(${key}===undefined`,instruction.unionKeys[key])v+=`||x${prop}===undefined`;let shouldQuestion=prop.charCodeAt(0)!==63&&schema.type!=="array";v+=`)delete x${shouldQuestion?prop.charCodeAt(0)===91?"?.":"?":""}${prop}
40
- `}return`${v}return x`},createMirror=(schema,{TypeCompiler:TypeCompiler22,modules,definitions,sanitize:sanitize2,recursionLimit=8,removeUnknownUnionType=!1}={})=>{let unions=[];if(typeof sanitize2==="function")sanitize2=[sanitize2];let f=mirror(schema,"v",{optionals:[],optionalsInArray:[],array:0,parentIsOptional:!1,unions,unionKeys:{},TypeCompiler:TypeCompiler22,modules,definitions:definitions??modules?.$defs??{},sanitize:sanitize2,recursion:0,recursionLimit,removeUnknownUnionType});if(!unions.length&&!sanitize2?.length)return Function("v",f);let hof;if(sanitize2?.length){hof={};for(let i=0;i<sanitize2.length;i++)hof[`h${i}`]=sanitize2[i]}return Function("d",`return function mirror(v){${f}}`)({unions,...hof})};var isOptional=(schema)=>{if(!schema)return!1;if(schema?.[Kind4]==="Import"&&schema.References)return schema.References().some(isOptional);if(schema.schema)schema=schema.schema;return!!schema&&OptionalKind in schema},hasAdditionalProperties=(_schema)=>{if(!_schema)return!1;let schema=_schema?.schema??_schema;if(schema[Kind4]==="Import"&&_schema.References)return _schema.References().some(hasAdditionalProperties);if(schema.anyOf)return schema.anyOf.some(hasAdditionalProperties);if(schema.someOf)return schema.someOf.some(hasAdditionalProperties);if(schema.allOf)return schema.allOf.some(hasAdditionalProperties);if(schema.not)return schema.not.some(hasAdditionalProperties);if(schema.type==="object"){let properties=schema.properties;if("additionalProperties"in schema)return schema.additionalProperties;if("patternProperties"in schema)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasAdditionalProperties(property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasAdditionalProperties(property.anyOf[i]))return!0}return property.additionalProperties}return!1}if(schema.type==="array"&&schema.items&&!Array.isArray(schema.items))return hasAdditionalProperties(schema.items);return!1},hasType=(type,schema)=>{if(!schema)return!1;if(Kind4 in schema&&schema[Kind4]===type)return!0;if(schema.type==="object"){let properties=schema.properties;if(!properties)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasType(type,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasType(type,property.anyOf[i]))return!0}if(Kind4 in property&&property[Kind4]===type)return!0}return!1}return!!schema.properties&&Kind4 in schema.properties&&schema.properties[Kind4]===type},hasElysiaMeta=(meta,_schema)=>{if(!_schema)return!1;let schema=_schema?.schema??_schema;if(schema.elysiaMeta===meta)return!0;if(schema[Kind4]==="Import"&&_schema.References)return _schema.References().some((schema2)=>hasElysiaMeta(meta,schema2));if(schema.anyOf)return schema.anyOf.some((schema2)=>hasElysiaMeta(meta,schema2));if(schema.someOf)return schema.someOf.some((schema2)=>hasElysiaMeta(meta,schema2));if(schema.allOf)return schema.allOf.some((schema2)=>hasElysiaMeta(meta,schema2));if(schema.not)return schema.not.some((schema2)=>hasElysiaMeta(meta,schema2));if(schema.type==="object"){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasElysiaMeta(meta,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasElysiaMeta(meta,property.anyOf[i]))return!0}return schema.elysiaMeta===meta}return!1}if(schema.type==="array"&&schema.items&&!Array.isArray(schema.items))return hasElysiaMeta(meta,schema.items);return!1},hasProperty=(expectedProperty,_schema)=>{if(!_schema)return;let schema=_schema.schema??_schema;if(schema[Kind4]==="Import"&&_schema.References)return _schema.References().some((schema2)=>hasProperty(expectedProperty,schema2));if(schema.type==="object"){let properties=schema.properties;if(!properties)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(expectedProperty in property)return!0;if(property.type==="object"){if(hasProperty(expectedProperty,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasProperty(expectedProperty,property.anyOf[i]))return!0}}return!1}return expectedProperty in schema},hasRef=(schema)=>{if(!schema)return!1;if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasRef(schema.oneOf[i]))return!0}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)if(hasRef(schema.anyOf[i]))return!0}if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasRef(schema.oneOf[i]))return!0}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)if(hasRef(schema.allOf[i]))return!0}if(schema.not&&hasRef(schema.not))return!0;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(hasRef(property))return!0;if(property.type==="array"&&property.items&&hasRef(property.items))return!0}}if(schema.type==="array"&&schema.items&&hasRef(schema.items))return!0;return schema[Kind4]==="Ref"&&"$ref"in schema},hasTransform=(schema)=>{if(!schema)return!1;if(schema.$ref&&schema.$defs&&schema.$ref in schema.$defs&&hasTransform(schema.$defs[schema.$ref]))return!0;if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasTransform(schema.oneOf[i]))return!0}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)if(hasTransform(schema.anyOf[i]))return!0}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)if(hasTransform(schema.allOf[i]))return!0}if(schema.not&&hasTransform(schema.not))return!0;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(hasTransform(property))return!0;if(property.type==="array"&&property.items&&hasTransform(property.items))return!0}}if(schema.type==="array"&&schema.items&&hasTransform(schema.items))return!0;return TransformKind in schema},replaceSchemaType=(schema,options,_config={})=>{let config=_config;if(config.root=!0,!Array.isArray(options))return options.original=schema,_replaceSchemaType(schema,options,config);for(let option of options)option.original=schema,schema=_replaceSchemaType(schema,option,config);return schema},_replaceSchemaType=(schema,options,config)=>{if(!schema)return schema;let root=config.root;if(options.onlyFirst&&schema.type===options.onlyFirst)return options.to(schema)??schema;if(options.untilObjectFound&&!root&&schema.type==="object")return schema;let fromSymbol=options.from[Kind4];if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)schema.oneOf[i]=_replaceSchemaType(schema.oneOf[i],options,config);return schema}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)schema.anyOf[i]=_replaceSchemaType(schema.anyOf[i],options,config);return schema}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)schema.allOf[i]=_replaceSchemaType(schema.allOf[i],options,config);return schema}if(schema.not)return _replaceSchemaType(schema.not,options,config);let isRoot=root&&!!options.excludeRoot;if(schema[Kind4]===fromSymbol){let{anyOf,oneOf,allOf,not,properties:properties2,items,...rest}=schema,to=options.to(rest);if(!to)return schema;let transform,composeProperties=(schema2)=>{let v=_composeProperties(schema2);if(v.$id)delete v.$id;return v},_composeProperties=(v)=>{if(properties2&&v.type==="object"){let newProperties={};for(let[key,value2]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value2,options,{...config,root:!1});return{...rest,...v,properties:newProperties}}if(items&&v.type==="array")return{...rest,...v,items:_replaceSchemaType(items,options,{...config,root:!1})};let value={...rest,...v};if(delete value.required,properties2&&v.type==="string"&&v.format==="ObjectString"&&v.default==="{}")transform=t.ObjectString(properties2,rest),value.properties=properties2;else if(items&&v.type==="string"&&v.format==="ArrayString"&&v.default==="[]")transform=t.ArrayString(items,rest),value.items=items;return value};if(isRoot){if(properties2){let newProperties={};for(let[key,value]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value,options,{...config,root:!1});return{...rest,properties:newProperties}}else if(items?.map)return{...rest,items:items.map((v)=>_replaceSchemaType(v,options,{...config,root:!1}))};return rest}if(to.anyOf)for(let i=0;i<to.anyOf.length;i++)to.anyOf[i]=composeProperties(to.anyOf[i]);else if(to.oneOf)for(let i=0;i<to.oneOf.length;i++)to.oneOf[i]=composeProperties(to.oneOf[i]);else if(to.allOf)for(let i=0;i<to.allOf.length;i++)to.allOf[i]=composeProperties(to.allOf[i]);else if(to.not)to.not=composeProperties(to.not);if(transform)to[TransformKind]=transform[TransformKind];if(to.anyOf||to.oneOf||to.allOf||to.not)return to;if(properties2){let newProperties={};for(let[key,value]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value,options,{...config,root:!1});return{...rest,...to,properties:newProperties}}else if(items?.map)return{...rest,...to,items:items.map((v)=>_replaceSchemaType(v,options,{...config,root:!1}))};return{...rest,...to}}let properties=schema?.properties;if(properties&&root&&options.rootOnly!==!0)for(let[key,value]of Object.entries(properties))switch(value[Kind4]){case fromSymbol:let{anyOf,oneOf,allOf,not,type,...rest}=value,to=options.to(rest);if(!to)return schema;if(to.anyOf)for(let i=0;i<to.anyOf.length;i++)to.anyOf[i]={...rest,...to.anyOf[i]};else if(to.oneOf)for(let i=0;i<to.oneOf.length;i++)to.oneOf[i]={...rest,...to.oneOf[i]};else if(to.allOf)for(let i=0;i<to.allOf.length;i++)to.allOf[i]={...rest,...to.allOf[i]};else if(to.not)to.not={...rest,...to.not};properties[key]={...rest,..._replaceSchemaType(rest,options,{...config,root:!1})};break;case"Object":case"Union":properties[key]=_replaceSchemaType(value,options,{...config,root:!1});break;default:if(Array.isArray(value.items))for(let i=0;i<value.items.length;i++)value.items[i]=_replaceSchemaType(value.items[i],options,{...config,root:!1});else if(value.anyOf||value.oneOf||value.allOf||value.not)properties[key]=_replaceSchemaType(value,options,{...config,root:!1});else if(value.type==="array")value.items=_replaceSchemaType(value.items,options,{...config,root:!1});break}if(schema.type==="array"&&schema.items)if(Array.isArray(schema.items))schema.items=schema.items.map((item)=>_replaceSchemaType(item,options,{...config,root:!1}));else schema.items=_replaceSchemaType(schema.items,options,{...config,root:!1});return schema},createCleaner=(schema)=>(value)=>{if(typeof value==="object")try{return Value3.Clean(schema,value)}catch{}return value},getSchemaValidator=(s,{models={},dynamic=!1,modules,normalize=!1,additionalProperties=!1,forceAdditionalProperties=!1,coerce=!1,additionalCoerce=[],validators,sanitize:sanitize2}={})=>{if(validators=validators?.filter((x)=>x),!s){if(!validators?.length)return;s=validators[0],validators=validators.slice(1)}let doesHaveRef=void 0,replaceSchema=(schema2)=>{if(coerce)return replaceSchemaType(schema2,[{from:t.Number(),to:(options)=>t.Numeric(options),untilObjectFound:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),untilObjectFound:!0},...Array.isArray(additionalCoerce)?additionalCoerce:[additionalCoerce]]);return replaceSchemaType(schema2,additionalCoerce)},mapSchema=(s2)=>{if(s2&&typeof s2!=="string"&&"~standard"in s2)return s2;if(!s2)return;let schema2;if(typeof s2!=="string")schema2=s2;else if(schema2=modules&&s2 in modules.$defs?modules.Import(s2):models[s2],!schema2)return;if(Kind4 in schema2){if(schema2[Kind4]==="Import"){if(!hasRef(schema2.$defs[schema2.$ref])){if(schema2=schema2.$defs[schema2.$ref],coerce||additionalCoerce)schema2=replaceSchema(schema2)}}else if(hasRef(schema2)){let id=randomId();schema2=t.Module({...modules?.$defs,[id]:schema2}).Import(id)}else if(coerce||additionalCoerce)schema2=replaceSchema(schema2)}return schema2},schema=mapSchema(s),_validators=validators;if("~standard"in schema||validators?.length&&validators.some((x)=>x&&typeof x!=="string"&&("~standard"in x))){let typeboxSubValidator=(schema2)=>{let mirror2;if(normalize===!0||normalize==="exactMirror")try{mirror2=createMirror(schema2,{TypeCompiler:TypeCompiler4,sanitize:sanitize2?.(),modules})}catch{console.warn("Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues"),console.warn(schema2),mirror2=createCleaner(schema2)}let vali=getSchemaValidator(schema2,{models,modules,dynamic,normalize,additionalProperties:!0,forceAdditionalProperties:!0,coerce,additionalCoerce});return vali.Decode=mirror2,(v)=>{if(vali.Check(v))return{value:vali.Decode(v)};else return{issues:[...vali.Errors(v)]}}},mainCheck=schema["~standard"]?schema["~standard"].validate:typeboxSubValidator(schema),checkers=[];if(validators?.length)for(let validator2 of validators){if(!validator2)continue;if(typeof validator2==="string")continue;if(validator2?.["~standard"]){checkers.push(validator2["~standard"]);continue}if(Kind4 in validator2){checkers.push(typeboxSubValidator(validator2));continue}}async function Check(value){let v=mainCheck(value);if(v instanceof Promise)v=await v;if(v.issues)return v;let values=[];if(v&&typeof v==="object")values.push(v.value);for(let i=0;i<checkers.length;i++){if(v=checkers[i].validate(value),v instanceof Promise)v=await v;if(v.issues)return v;if(v&&typeof v==="object")values.push(v.value)}if(!values.length)return{value:v};if(values.length===1)return{value:values[0]};if(values.length===2)return{value:mergeDeep(values[0],values[1])};let newValue=mergeDeep(values[0],values[1]);for(let i=2;i<values.length;i++)newValue=mergeDeep(newValue,values[i]);return{value:newValue}}let validator={provider:"standard",schema,references:"",checkFunc:()=>{},code:"",Check,Errors:(value)=>Check(value)?.then?.((x)=>x?.issues),Code:()=>"",Decode:Check,Encode:(value)=>value,hasAdditionalProperties:!1,hasDefault:!1,isOptional:!1,hasTransform:!1,hasRef:!1};return validator.parse=(v)=>{try{return validator.Decode(validator.Clean?.(v)??v)}catch(error){throw[...validator.Errors(v)].map(mapValueError)}},validator.safeParse=(v)=>{try{return{success:!0,data:validator.Decode(validator.Clean?.(v)??v),error:null}}catch(error){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},validator}else if(validators?.length){let hasAdditional=!1,validators2=_validators,{schema:mergedObjectSchema,notObjects}=mergeObjectSchemas([schema,...validators2.map(mapSchema)]);if(notObjects){if(schema=t.Intersect([...mergedObjectSchema?[mergedObjectSchema]:[],...notObjects.map((x)=>{let schema2=mapSchema(x);if(schema2.type==="object"&&"additionalProperties"in schema2){if(!hasAdditional&&schema2.additionalProperties===!1)hasAdditional=!0;delete schema2.additionalProperties}return schema2})]),schema.type==="object"&&hasAdditional)schema.additionalProperties=!1}}else if(schema.type==="object"&&(("additionalProperties"in schema)===!1||forceAdditionalProperties))schema.additionalProperties=additionalProperties;else schema=replaceSchemaType(schema,{onlyFirst:"object",from:t.Object({}),to({properties,...options}){if(!properties)return;if("additionalProperties"in schema)return;return t.Object(properties,{...options,additionalProperties:!1})}});if(dynamic)if(Kind4 in schema){let validator={provider:"typebox",schema,references:"",checkFunc:()=>{},code:"",Check:(value)=>Value3.Check(schema,value),Errors:(value)=>Value3.Errors(schema,value),Code:()=>"",Clean:createCleaner(schema),Decode:(value)=>Value3.Decode(schema,value),Encode:(value)=>Value3.Encode(schema,value),get hasAdditionalProperties(){if("~hasAdditionalProperties"in this)return this["~hasAdditionalProperties"];return this["~hasAdditionalProperties"]=hasAdditionalProperties(schema)},get hasDefault(){if("~hasDefault"in this)return this["~hasDefault"];return this["~hasDefault"]=hasProperty("default",schema)},get isOptional(){if("~isOptional"in this)return this["~isOptional"];return this["~isOptional"]=isOptional(schema)},get hasTransform(){if("~hasTransform"in this)return this["~hasTransform"];return this["~hasTransform"]=hasTransform(schema)},"~hasRef":doesHaveRef,get hasRef(){if("~hasRef"in this)return this["~hasRef"];return this["~hasRef"]=hasTransform(schema)}};if(schema.config){if(validator.config=schema.config,validator?.schema?.config)delete validator.schema.config}if(normalize&&schema.additionalProperties===!1)if(normalize===!0||normalize==="exactMirror")try{validator.Clean=createMirror(schema,{TypeCompiler:TypeCompiler4,sanitize:sanitize2?.(),modules})}catch{console.warn("Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues"),console.warn(schema),validator.Clean=createCleaner(schema)}else validator.Clean=createCleaner(schema);return validator.parse=(v)=>{try{return validator.Decode(validator.Clean?.(v)??v)}catch(error){throw[...validator.Errors(v)].map(mapValueError)}},validator.safeParse=(v)=>{try{return{success:!0,data:validator.Decode(validator.Clean?.(v)??v),error:null}}catch(error){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},validator}else{let validator={provider:"standard",schema,references:"",checkFunc:()=>{},code:"",Check:(v)=>schema["~standard"].validate(v),Errors(value){let response=schema["~standard"].validate(value);if(response instanceof Promise)throw Error("Async validation is not supported in non-dynamic schema");return response.issues},Code:()=>"",Decode(value){let response=schema["~standard"].validate(value);if(response instanceof Promise)throw Error("Async validation is not supported in non-dynamic schema");return response},Encode:(value)=>value,hasAdditionalProperties:!1,hasDefault:!1,isOptional:!1,hasTransform:!1,hasRef:!1};return validator.parse=(v)=>{try{return validator.Decode(validator.Clean?.(v)??v)}catch(error){throw[...validator.Errors(v)].map(mapValueError)}},validator.safeParse=(v)=>{try{return{success:!0,data:validator.Decode(validator.Clean?.(v)??v),error:null}}catch(error){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},validator}let compiled;if(Kind4 in schema){if(compiled=TypeCompiler4.Compile(schema,Object.values(models).filter((x)=>(Kind4 in x))),compiled.provider="typebox",schema.config){if(compiled.config=schema.config,compiled?.schema?.config)delete compiled.schema.config}if(normalize===!0||normalize==="exactMirror")try{compiled.Clean=createMirror(schema,{TypeCompiler:TypeCompiler4,sanitize:sanitize2?.(),modules})}catch(error){console.warn("Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues"),console.dir(schema,{depth:null}),compiled.Clean=createCleaner(schema)}else if(normalize==="typebox")compiled.Clean=createCleaner(schema)}else compiled={provider:"standard",schema,references:"",checkFunc(value){let response=schema["~standard"].validate(value);if(response instanceof Promise)throw Error("Async validation is not supported in non-dynamic schema");return response},code:"",Check:(v)=>schema["~standard"].validate(v),Errors(value){let response=schema["~standard"].validate(value);if(response instanceof Promise)throw Error("Async validation is not supported in non-dynamic schema");return response.issues},Code:()=>"",Decode(value){let response=schema["~standard"].validate(value);if(response instanceof Promise)throw Error("Async validation is not supported in non-dynamic schema");return response},Encode:(value)=>value,hasAdditionalProperties:!1,hasDefault:!1,isOptional:!1,hasTransform:!1,hasRef:!1};if(compiled.parse=(v)=>{try{return compiled.Decode(compiled.Clean?.(v)??v)}catch(error){throw[...compiled.Errors(v)].map(mapValueError)}},compiled.safeParse=(v)=>{try{return{success:!0,data:compiled.Decode(compiled.Clean?.(v)??v),error:null}}catch(error){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},Kind4 in schema)Object.assign(compiled,{get hasAdditionalProperties(){if("~hasAdditionalProperties"in this)return this["~hasAdditionalProperties"];return this["~hasAdditionalProperties"]=hasAdditionalProperties(compiled)},get hasDefault(){if("~hasDefault"in this)return this["~hasDefault"];return this["~hasDefault"]=hasProperty("default",compiled)},get isOptional(){if("~isOptional"in this)return this["~isOptional"];return this["~isOptional"]=isOptional(compiled)},get hasTransform(){if("~hasTransform"in this)return this["~hasTransform"];return this["~hasTransform"]=hasTransform(schema)},get hasRef(){if("~hasRef"in this)return this["~hasRef"];return this["~hasRef"]=hasRef(schema)},"~hasRef":doesHaveRef});return compiled},isUnion=(schema)=>schema[Kind4]==="Union"||!schema.schema&&!!schema.anyOf,mergeObjectSchemas=(schemas)=>{if(schemas.length===0)return{schema:void 0,notObjects:[]};if(schemas.length===1)return schemas[0].type==="object"?{schema:schemas[0],notObjects:[]}:{schema:void 0,notObjects:schemas};let newSchema,notObjects=[],additionalPropertiesIsTrue=!1,additionalPropertiesIsFalse=!1;for(let schema of schemas){if(schema.type!=="object"){notObjects.push(schema);continue}if("additionalProperties"in schema){if(schema.additionalProperties===!0)additionalPropertiesIsTrue=!0;else if(schema.additionalProperties===!1)additionalPropertiesIsFalse=!0}if(!newSchema){newSchema=schema;continue}newSchema={...newSchema,...schema,properties:{...newSchema.properties,...schema.properties},required:[...newSchema?.required??[],...schema.required??[]]}}if(newSchema){if(newSchema.required)newSchema.required=[...new Set(newSchema.required)];if(additionalPropertiesIsFalse)newSchema.additionalProperties=!1;else if(additionalPropertiesIsTrue)newSchema.additionalProperties=!0}return{schema:newSchema,notObjects}},getResponseSchemaValidator=(s,{models={},modules,dynamic=!1,normalize=!1,additionalProperties=!1,validators=[],sanitize:sanitize2})=>{if(validators=validators.filter((x)=>x),!s){if(!validators?.length)return;s=validators[0],validators=validators.slice(1)}let maybeSchemaOrRecord;if(typeof s!=="string")maybeSchemaOrRecord=s;else if(maybeSchemaOrRecord=modules&&s in modules.$defs?modules.Import(s):models[s],!maybeSchemaOrRecord)return;if(!maybeSchemaOrRecord)return;if(Kind4 in maybeSchemaOrRecord||"~standard"in maybeSchemaOrRecord)return{200:getSchemaValidator(maybeSchemaOrRecord,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[200]),sanitize:sanitize2})};let record={};return Object.keys(maybeSchemaOrRecord).forEach((status2)=>{if(isNaN(+status2))return;let maybeNameOrSchema=maybeSchemaOrRecord[+status2];if(typeof maybeNameOrSchema==="string"){if(maybeNameOrSchema in models){let schema=models[maybeNameOrSchema];if(!schema)return;record[+status2]=Kind4 in schema||"~standard"in schema?getSchemaValidator(schema,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[+status2]),sanitize:sanitize2}):schema}return}record[+status2]=Kind4 in maybeNameOrSchema||"~standard"in maybeNameOrSchema?getSchemaValidator(maybeNameOrSchema,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[+status2]),sanitize:sanitize2}):maybeNameOrSchema}),record},_stringToStructureCoercions,stringToStructureCoercions=()=>{if(!_stringToStructureCoercions)_stringToStructureCoercions=[{from:t.Object({}),to:()=>t.ObjectString({}),excludeRoot:!0},{from:t.Array(t.Any()),to:()=>t.ArrayString(t.Any())}];return _stringToStructureCoercions},_queryCoercions,queryCoercions=()=>{if(!_queryCoercions)_queryCoercions=[{from:t.Object({}),to:()=>t.ObjectString({}),excludeRoot:!0},{from:t.Array(t.Any()),to:()=>t.ArrayQuery(t.Any())}];return _queryCoercions},_coercePrimitiveRoot,coercePrimitiveRoot=()=>{if(!_coercePrimitiveRoot)_coercePrimitiveRoot=[{from:t.Number(),to:(options)=>t.Numeric(options),rootOnly:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),rootOnly:!0}];return _coercePrimitiveRoot},getCookieValidator=({validator,modules,defaultConfig={},config,dynamic,normalize=!1,models,validators,sanitize:sanitize2})=>{let cookieValidator=validator?.provider?validator:getSchemaValidator(validator,{modules,dynamic,models,normalize,additionalProperties:!0,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators,sanitize:sanitize2});if(cookieValidator)cookieValidator.config=mergeCookie(cookieValidator.config,config);else cookieValidator=getSchemaValidator(t.Cookie(t.Any()),{modules,dynamic,models,additionalProperties:!0,validators,sanitize:sanitize2}),cookieValidator.config=defaultConfig;return cookieValidator},unwrapImportSchema=(schema)=>schema&&schema[Kind4]==="Import"&&schema.$defs[schema.$ref][Kind4]==="Object"?schema.$defs[schema.$ref]:schema;var allocateIf=(value,condition)=>condition?value:"",overrideUnsafeQuote=(value)=>"`"+value.replace(/`/g,"\\`").replace(/\${/g,"$\\{")+"`",overrideUnsafeQuoteArrayValue=(value)=>value.replace(/`/g,"\\`").replace(/\${/g,"$\\{"),defaultParsers=["json","text","urlencoded","arrayBuffer","formdata","application/json","text/plain","application/x-www-form-urlencoded","application/octet-stream","multipart/form-data"],createReport=({context="c",trace=[],addFn})=>{if(!trace.length)return()=>{return{resolveChild(){return()=>{}},resolve(){}}};for(let i=0;i<trace.length;i++)addFn(`let report${i},reportChild${i},reportErr${i},reportErrChild${i};let trace${i}=${context}[ELYSIA_TRACE]?.[${i}]??trace[${i}](${context});
40
+ `}return`${v}return x`},createMirror=(schema,{TypeCompiler:TypeCompiler22,modules,definitions,sanitize:sanitize2,recursionLimit=8,removeUnknownUnionType=!1}={})=>{let unions=[];if(typeof sanitize2==="function")sanitize2=[sanitize2];let f=mirror(schema,"v",{optionals:[],optionalsInArray:[],array:0,parentIsOptional:!1,unions,unionKeys:{},TypeCompiler:TypeCompiler22,modules,definitions:definitions??modules?.$defs??{},sanitize:sanitize2,recursion:0,recursionLimit,removeUnknownUnionType});if(!unions.length&&!sanitize2?.length)return Function("v",f);let hof;if(sanitize2?.length){hof={};for(let i=0;i<sanitize2.length;i++)hof[`h${i}`]=sanitize2[i]}return Function("d",`return function mirror(v){${f}}`)({unions,...hof})};var isOptional=(schema)=>{if(!schema)return!1;if(schema?.[Kind4]==="Import"&&schema.References)return schema.References().some(isOptional);if(schema.schema)schema=schema.schema;return!!schema&&OptionalKind in schema},hasAdditionalProperties=(_schema)=>{if(!_schema)return!1;let schema=_schema?.schema??_schema;if(schema[Kind4]==="Import"&&_schema.References)return _schema.References().some(hasAdditionalProperties);if(schema.anyOf)return schema.anyOf.some(hasAdditionalProperties);if(schema.someOf)return schema.someOf.some(hasAdditionalProperties);if(schema.allOf)return schema.allOf.some(hasAdditionalProperties);if(schema.not)return schema.not.some(hasAdditionalProperties);if(schema.type==="object"){let properties=schema.properties;if("additionalProperties"in schema)return schema.additionalProperties;if("patternProperties"in schema)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasAdditionalProperties(property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasAdditionalProperties(property.anyOf[i]))return!0}return property.additionalProperties}return!1}if(schema.type==="array"&&schema.items&&!Array.isArray(schema.items))return hasAdditionalProperties(schema.items);return!1},hasType=(type,schema)=>{if(!schema)return!1;if(Kind4 in schema&&schema[Kind4]===type)return!0;if(schema.type==="object"){let properties=schema.properties;if(!properties)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasType(type,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasType(type,property.anyOf[i]))return!0}if(Kind4 in property&&property[Kind4]===type)return!0}return!1}return!!schema.properties&&Kind4 in schema.properties&&schema.properties[Kind4]===type},hasElysiaMeta=(meta,_schema)=>{if(!_schema)return!1;let schema=_schema?.schema??_schema;if(schema.elysiaMeta===meta)return!0;if(schema[Kind4]==="Import"&&_schema.References)return _schema.References().some((schema2)=>hasElysiaMeta(meta,schema2));if(schema.anyOf)return schema.anyOf.some((schema2)=>hasElysiaMeta(meta,schema2));if(schema.someOf)return schema.someOf.some((schema2)=>hasElysiaMeta(meta,schema2));if(schema.allOf)return schema.allOf.some((schema2)=>hasElysiaMeta(meta,schema2));if(schema.not)return schema.not.some((schema2)=>hasElysiaMeta(meta,schema2));if(schema.type==="object"){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(property.type==="object"){if(hasElysiaMeta(meta,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasElysiaMeta(meta,property.anyOf[i]))return!0}return schema.elysiaMeta===meta}return!1}if(schema.type==="array"&&schema.items&&!Array.isArray(schema.items))return hasElysiaMeta(meta,schema.items);return!1},hasProperty=(expectedProperty,_schema)=>{if(!_schema)return;let schema=_schema.schema??_schema;if(schema[Kind4]==="Import"&&_schema.References)return _schema.References().some((schema2)=>hasProperty(expectedProperty,schema2));if(schema.type==="object"){let properties=schema.properties;if(!properties)return!1;for(let key of Object.keys(properties)){let property=properties[key];if(expectedProperty in property)return!0;if(property.type==="object"){if(hasProperty(expectedProperty,property))return!0}else if(property.anyOf){for(let i=0;i<property.anyOf.length;i++)if(hasProperty(expectedProperty,property.anyOf[i]))return!0}}return!1}return expectedProperty in schema},hasRef=(schema)=>{if(!schema)return!1;if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasRef(schema.oneOf[i]))return!0}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)if(hasRef(schema.anyOf[i]))return!0}if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasRef(schema.oneOf[i]))return!0}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)if(hasRef(schema.allOf[i]))return!0}if(schema.not&&hasRef(schema.not))return!0;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(hasRef(property))return!0;if(property.type==="array"&&property.items&&hasRef(property.items))return!0}}if(schema.type==="array"&&schema.items&&hasRef(schema.items))return!0;return schema[Kind4]==="Ref"&&"$ref"in schema},hasTransform=(schema)=>{if(!schema)return!1;if(schema.$ref&&schema.$defs&&schema.$ref in schema.$defs&&hasTransform(schema.$defs[schema.$ref]))return!0;if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)if(hasTransform(schema.oneOf[i]))return!0}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)if(hasTransform(schema.anyOf[i]))return!0}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)if(hasTransform(schema.allOf[i]))return!0}if(schema.not&&hasTransform(schema.not))return!0;if(schema.type==="object"&&schema.properties){let properties=schema.properties;for(let key of Object.keys(properties)){let property=properties[key];if(hasTransform(property))return!0;if(property.type==="array"&&property.items&&hasTransform(property.items))return!0}}if(schema.type==="array"&&schema.items&&hasTransform(schema.items))return!0;return TransformKind in schema},replaceSchemaType=(schema,options,_config={})=>{let config=_config;if(config.root=!0,!Array.isArray(options))return options.original=schema,_replaceSchemaType(schema,options,config);for(let option of options)option.original=schema,schema=_replaceSchemaType(schema,option,config);return schema},_replaceSchemaType=(schema,options,config)=>{if(!schema)return schema;let root=config.root;if(options.onlyFirst&&schema.type===options.onlyFirst)return options.to(schema)??schema;if(options.untilObjectFound&&!root&&schema.type==="object")return schema;let fromSymbol=options.from[Kind4];if(schema.oneOf){for(let i=0;i<schema.oneOf.length;i++)schema.oneOf[i]=_replaceSchemaType(schema.oneOf[i],options,config);return schema}if(schema.anyOf){for(let i=0;i<schema.anyOf.length;i++)schema.anyOf[i]=_replaceSchemaType(schema.anyOf[i],options,config);return schema}if(schema.allOf){for(let i=0;i<schema.allOf.length;i++)schema.allOf[i]=_replaceSchemaType(schema.allOf[i],options,config);return schema}if(schema.not)return _replaceSchemaType(schema.not,options,config);let isRoot=root&&!!options.excludeRoot;if(schema[Kind4]===fromSymbol){let{anyOf,oneOf,allOf,not,properties:properties2,items,...rest}=schema,to=options.to(rest);if(!to)return schema;let transform,composeProperties=(schema2)=>{let v=_composeProperties(schema2);if(v.$id)delete v.$id;return v},_composeProperties=(v)=>{if(properties2&&v.type==="object"){let newProperties={};for(let[key,value2]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value2,options,{...config,root:!1});return{...rest,...v,properties:newProperties}}if(items&&v.type==="array")return{...rest,...v,items:_replaceSchemaType(items,options,{...config,root:!1})};let value={...rest,...v};if(delete value.required,properties2&&v.type==="string"&&v.format==="ObjectString"&&v.default==="{}")transform=t.ObjectString(properties2,rest),value.properties=properties2;else if(items&&v.type==="string"&&v.format==="ArrayString"&&v.default==="[]")transform=t.ArrayString(items,rest),value.items=items;return value};if(isRoot){if(properties2){let newProperties={};for(let[key,value]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value,options,{...config,root:!1});return{...rest,properties:newProperties}}else if(items?.map)return{...rest,items:items.map((v)=>_replaceSchemaType(v,options,{...config,root:!1}))};return rest}if(to.anyOf)for(let i=0;i<to.anyOf.length;i++)to.anyOf[i]=composeProperties(to.anyOf[i]);else if(to.oneOf)for(let i=0;i<to.oneOf.length;i++)to.oneOf[i]=composeProperties(to.oneOf[i]);else if(to.allOf)for(let i=0;i<to.allOf.length;i++)to.allOf[i]=composeProperties(to.allOf[i]);else if(to.not)to.not=composeProperties(to.not);if(transform)to[TransformKind]=transform[TransformKind];if(to.anyOf||to.oneOf||to.allOf||to.not)return to;if(properties2){let newProperties={};for(let[key,value]of Object.entries(properties2))newProperties[key]=_replaceSchemaType(value,options,{...config,root:!1});return{...rest,...to,properties:newProperties}}else if(items?.map)return{...rest,...to,items:items.map((v)=>_replaceSchemaType(v,options,{...config,root:!1}))};return{...rest,...to}}let properties=schema?.properties;if(properties&&root&&options.rootOnly!==!0)for(let[key,value]of Object.entries(properties))switch(value[Kind4]){case fromSymbol:let{anyOf,oneOf,allOf,not,type,...rest}=value,to=options.to(rest);if(!to)return schema;if(to.anyOf)for(let i=0;i<to.anyOf.length;i++)to.anyOf[i]={...rest,...to.anyOf[i]};else if(to.oneOf)for(let i=0;i<to.oneOf.length;i++)to.oneOf[i]={...rest,...to.oneOf[i]};else if(to.allOf)for(let i=0;i<to.allOf.length;i++)to.allOf[i]={...rest,...to.allOf[i]};else if(to.not)to.not={...rest,...to.not};properties[key]={...rest,..._replaceSchemaType(rest,options,{...config,root:!1})};break;case"Object":case"Union":properties[key]=_replaceSchemaType(value,options,{...config,root:!1});break;default:if(Array.isArray(value.items))for(let i=0;i<value.items.length;i++)value.items[i]=_replaceSchemaType(value.items[i],options,{...config,root:!1});else if(value.anyOf||value.oneOf||value.allOf||value.not)properties[key]=_replaceSchemaType(value,options,{...config,root:!1});else if(value.type==="array")value.items=_replaceSchemaType(value.items,options,{...config,root:!1});break}if(schema.type==="array"&&schema.items)if(Array.isArray(schema.items))schema.items=schema.items.map((item)=>_replaceSchemaType(item,options,{...config,root:!1}));else schema.items=_replaceSchemaType(schema.items,options,{...config,root:!1});return schema},createCleaner=(schema)=>(value)=>{if(typeof value==="object")try{return Value3.Clean(schema,value)}catch{}return value},getSchemaValidator=(s,{models={},dynamic=!1,modules,normalize=!1,additionalProperties=!1,forceAdditionalProperties=!1,coerce=!1,additionalCoerce=[],validators,sanitize:sanitize2}={})=>{if(validators=validators?.filter((x)=>x),!s){if(!validators?.length)return;s=validators[0],validators=validators.slice(1)}let doesHaveRef=void 0,replaceSchema=(schema2)=>{if(coerce)return replaceSchemaType(schema2,[{from:t.Number(),to:(options)=>t.Numeric(options),untilObjectFound:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),untilObjectFound:!0},...Array.isArray(additionalCoerce)?additionalCoerce:[additionalCoerce]]);return replaceSchemaType(schema2,additionalCoerce)},mapSchema=(s2)=>{if(s2&&typeof s2!=="string"&&"~standard"in s2)return s2;if(!s2)return;let schema2;if(typeof s2!=="string")schema2=s2;else if(schema2=modules&&s2 in modules.$defs?modules.Import(s2):models[s2],!schema2)return;if(Kind4 in schema2){if(schema2[Kind4]==="Import"){if(!hasRef(schema2.$defs[schema2.$ref])){if(schema2=schema2.$defs[schema2.$ref],coerce||additionalCoerce)schema2=replaceSchema(schema2)}}else if(hasRef(schema2)){let id=randomId();schema2=t.Module({...modules?.$defs,[id]:schema2}).Import(id)}else if(coerce||additionalCoerce)schema2=replaceSchema(schema2)}return schema2},schema=mapSchema(s),_validators=validators;if("~standard"in schema||validators?.length&&validators.some((x)=>x&&typeof x!=="string"&&("~standard"in x))){let typeboxSubValidator=(schema2)=>{let mirror2;if(normalize===!0||normalize==="exactMirror")try{mirror2=createMirror(schema2,{TypeCompiler:TypeCompiler4,sanitize:sanitize2?.(),modules})}catch{console.warn("Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues"),console.warn(schema2),mirror2=createCleaner(schema2)}let vali=getSchemaValidator(schema2,{models,modules,dynamic,normalize,additionalProperties:!0,forceAdditionalProperties:!0,coerce,additionalCoerce});return vali.Decode=mirror2,(v)=>{if(vali.Check(v))return{value:vali.Decode(v)};else return{issues:[...vali.Errors(v)]}}},mainCheck=schema["~standard"]?schema["~standard"].validate:typeboxSubValidator(schema),checkers=[];if(validators?.length)for(let validator2 of validators){if(!validator2)continue;if(typeof validator2==="string")continue;if(validator2?.["~standard"]){checkers.push(validator2["~standard"]);continue}if(Kind4 in validator2){checkers.push(typeboxSubValidator(validator2));continue}}async function Check(value){let v=mainCheck(value);if(v instanceof Promise)v=await v;if(v.issues)return v;let values=[];if(v&&typeof v==="object")values.push(v.value);for(let i=0;i<checkers.length;i++){if(v=checkers[i].validate(value),v instanceof Promise)v=await v;if(v.issues)return v;if(v&&typeof v==="object")values.push(v.value)}if(!values.length)return{value:v};if(values.length===1)return{value:values[0]};if(values.length===2)return{value:mergeDeep(values[0],values[1])};let newValue=mergeDeep(values[0],values[1]);for(let i=2;i<values.length;i++)newValue=mergeDeep(newValue,values[i]);return{value:newValue}}let validator={provider:"standard",schema,references:"",checkFunc:()=>{},code:"",Check,Errors:(value)=>Check(value)?.then?.((x)=>x?.issues),Code:()=>"",Decode:Check,Encode:(value)=>value,hasAdditionalProperties:!1,hasDefault:!1,isOptional:!1,hasTransform:!1,hasRef:!1};return validator.parse=(v)=>{try{return validator.Decode(validator.Clean?.(v)??v)}catch(error){throw[...validator.Errors(v)].map(mapValueError)}},validator.safeParse=(v)=>{try{return{success:!0,data:validator.Decode(validator.Clean?.(v)??v),error:null}}catch(error){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},validator}else if(validators?.length){let hasAdditional=!1,validators2=_validators,{schema:mergedObjectSchema,notObjects}=mergeObjectSchemas([schema,...validators2.map(mapSchema)]);if(notObjects){if(schema=t.Intersect([...mergedObjectSchema?[mergedObjectSchema]:[],...notObjects.map((x)=>{let schema2=mapSchema(x);if(schema2.type==="object"&&"additionalProperties"in schema2){if(!hasAdditional&&schema2.additionalProperties===!1)hasAdditional=!0;delete schema2.additionalProperties}return schema2})]),schema.type==="object"&&hasAdditional)schema.additionalProperties=!1}}else if(schema.type==="object"&&(("additionalProperties"in schema)===!1||forceAdditionalProperties))schema.additionalProperties=additionalProperties;else schema=replaceSchemaType(schema,{onlyFirst:"object",from:t.Object({}),to({properties,...options}){if(!properties)return;if("additionalProperties"in schema)return;return t.Object(properties,{...options,additionalProperties:!1})}});if(dynamic)if(Kind4 in schema){let validator={provider:"typebox",schema,references:"",checkFunc:()=>{},code:"",Check:(value)=>Value3.Check(schema,value),Errors:(value)=>Value3.Errors(schema,value),Code:()=>"",Clean:createCleaner(schema),Decode:(value)=>Value3.Decode(schema,value),Encode:(value)=>Value3.Encode(schema,value),get hasAdditionalProperties(){if("~hasAdditionalProperties"in this)return this["~hasAdditionalProperties"];return this["~hasAdditionalProperties"]=hasAdditionalProperties(schema)},get hasDefault(){if("~hasDefault"in this)return this["~hasDefault"];return this["~hasDefault"]=hasProperty("default",schema)},get isOptional(){if("~isOptional"in this)return this["~isOptional"];return this["~isOptional"]=isOptional(schema)},get hasTransform(){if("~hasTransform"in this)return this["~hasTransform"];return this["~hasTransform"]=hasTransform(schema)},"~hasRef":doesHaveRef,get hasRef(){if("~hasRef"in this)return this["~hasRef"];return this["~hasRef"]=hasTransform(schema)}};if(schema.config){if(validator.config=schema.config,validator?.schema?.config)delete validator.schema.config}if(normalize&&schema.additionalProperties===!1)if(normalize===!0||normalize==="exactMirror")try{validator.Clean=createMirror(schema,{TypeCompiler:TypeCompiler4,sanitize:sanitize2?.(),modules})}catch{console.warn("Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues"),console.warn(schema),validator.Clean=createCleaner(schema)}else validator.Clean=createCleaner(schema);return validator.parse=(v)=>{try{return validator.Decode(validator.Clean?.(v)??v)}catch(error){throw[...validator.Errors(v)].map(mapValueError)}},validator.safeParse=(v)=>{try{return{success:!0,data:validator.Decode(validator.Clean?.(v)??v),error:null}}catch(error){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},validator}else{let validator={provider:"standard",schema,references:"",checkFunc:()=>{},code:"",Check:(v)=>schema["~standard"].validate(v),Errors(value){let response=schema["~standard"].validate(value);if(response instanceof Promise)throw Error("Async validation is not supported in non-dynamic schema");return response.issues},Code:()=>"",Decode(value){let response=schema["~standard"].validate(value);if(response instanceof Promise)throw Error("Async validation is not supported in non-dynamic schema");return response},Encode:(value)=>value,hasAdditionalProperties:!1,hasDefault:!1,isOptional:!1,hasTransform:!1,hasRef:!1};return validator.parse=(v)=>{try{return validator.Decode(validator.Clean?.(v)??v)}catch(error){throw[...validator.Errors(v)].map(mapValueError)}},validator.safeParse=(v)=>{try{return{success:!0,data:validator.Decode(validator.Clean?.(v)??v),error:null}}catch(error){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},validator}let compiled;if(Kind4 in schema){if(compiled=TypeCompiler4.Compile(schema,Object.values(models).filter((x)=>(Kind4 in x))),compiled.provider="typebox",schema.config){if(compiled.config=schema.config,compiled?.schema?.config)delete compiled.schema.config}if(normalize===!0||normalize==="exactMirror")try{compiled.Clean=createMirror(schema,{TypeCompiler:TypeCompiler4,sanitize:sanitize2?.(),modules})}catch(error){console.warn("Failed to create exactMirror. Please report the following code to https://github.com/elysiajs/elysia/issues"),console.dir(schema,{depth:null}),compiled.Clean=createCleaner(schema)}else if(normalize==="typebox")compiled.Clean=createCleaner(schema)}else compiled={provider:"standard",schema,references:"",checkFunc(value){let response=schema["~standard"].validate(value);if(response instanceof Promise)throw Error("Async validation is not supported in non-dynamic schema");return response},code:"",Check:(v)=>schema["~standard"].validate(v),Errors(value){let response=schema["~standard"].validate(value);if(response instanceof Promise)throw Error("Async validation is not supported in non-dynamic schema");return response.issues},Code:()=>"",Decode(value){let response=schema["~standard"].validate(value);if(response instanceof Promise)throw Error("Async validation is not supported in non-dynamic schema");return response},Encode:(value)=>value,hasAdditionalProperties:!1,hasDefault:!1,isOptional:!1,hasTransform:!1,hasRef:!1};if(compiled.parse=(v)=>{try{return compiled.Decode(compiled.Clean?.(v)??v)}catch(error){throw[...compiled.Errors(v)].map(mapValueError)}},compiled.safeParse=(v)=>{try{return{success:!0,data:compiled.Decode(compiled.Clean?.(v)??v),error:null}}catch(error){let errors=[...compiled.Errors(v)].map(mapValueError);return{success:!1,data:null,error:errors[0]?.summary,errors}}},Kind4 in schema)Object.assign(compiled,{get hasAdditionalProperties(){if("~hasAdditionalProperties"in this)return this["~hasAdditionalProperties"];return this["~hasAdditionalProperties"]=hasAdditionalProperties(compiled)},get hasDefault(){if("~hasDefault"in this)return this["~hasDefault"];return this["~hasDefault"]=hasProperty("default",compiled)},get isOptional(){if("~isOptional"in this)return this["~isOptional"];return this["~isOptional"]=isOptional(compiled)},get hasTransform(){if("~hasTransform"in this)return this["~hasTransform"];return this["~hasTransform"]=hasTransform(schema)},get hasRef(){if("~hasRef"in this)return this["~hasRef"];return this["~hasRef"]=hasRef(schema)},"~hasRef":doesHaveRef});return compiled},isUnion=(schema)=>schema[Kind4]==="Union"||!schema.schema&&!!schema.anyOf,mergeObjectSchemas=(schemas)=>{if(schemas.length===0)return{schema:void 0,notObjects:[]};if(schemas.length===1)return schemas[0].type==="object"?{schema:schemas[0],notObjects:[]}:{schema:void 0,notObjects:schemas};let newSchema,notObjects=[],additionalPropertiesIsTrue=!1,additionalPropertiesIsFalse=!1;for(let schema of schemas){if(schema.type!=="object"){notObjects.push(schema);continue}if("additionalProperties"in schema){if(schema.additionalProperties===!0)additionalPropertiesIsTrue=!0;else if(schema.additionalProperties===!1)additionalPropertiesIsFalse=!0}if(!newSchema){newSchema=schema;continue}newSchema={...newSchema,...schema,properties:{...newSchema.properties,...schema.properties},required:[...newSchema?.required??[],...schema.required??[]]}}if(newSchema){if(newSchema.required)newSchema.required=[...new Set(newSchema.required)];if(additionalPropertiesIsFalse)newSchema.additionalProperties=!1;else if(additionalPropertiesIsTrue)newSchema.additionalProperties=!0}return{schema:newSchema,notObjects}},getResponseSchemaValidator=(s,{models={},modules,dynamic=!1,normalize=!1,additionalProperties=!1,validators=[],sanitize:sanitize2})=>{if(validators=validators.filter((x)=>x),!s){if(!validators?.length)return;s=validators[0],validators=validators.slice(1)}let maybeSchemaOrRecord;if(typeof s!=="string")maybeSchemaOrRecord=s;else if(maybeSchemaOrRecord=modules&&s in modules.$defs?modules.Import(s):models[s],!maybeSchemaOrRecord)return;if(!maybeSchemaOrRecord)return;if(Kind4 in maybeSchemaOrRecord||"~standard"in maybeSchemaOrRecord)return{200:getSchemaValidator(maybeSchemaOrRecord,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[200]),sanitize:sanitize2})};let record={};return Object.keys(maybeSchemaOrRecord).forEach((status2)=>{if(isNaN(+status2))return;let maybeNameOrSchema=maybeSchemaOrRecord[+status2];if(typeof maybeNameOrSchema==="string"){if(maybeNameOrSchema in models){let schema=models[maybeNameOrSchema];if(!schema)return;record[+status2]=Kind4 in schema||"~standard"in schema?getSchemaValidator(schema,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[+status2]),sanitize:sanitize2}):schema}return}record[+status2]=Kind4 in maybeNameOrSchema||"~standard"in maybeNameOrSchema?getSchemaValidator(maybeNameOrSchema,{modules,models,additionalProperties,dynamic,normalize,coerce:!1,additionalCoerce:[],validators:validators.map((x)=>x[+status2]),sanitize:sanitize2}):maybeNameOrSchema}),record},_stringToStructureCoercions,stringToStructureCoercions=()=>{if(!_stringToStructureCoercions)_stringToStructureCoercions=[{from:t.Object({}),to:()=>t.ObjectString({}),excludeRoot:!0},{from:t.Array(t.Any()),to:()=>t.ArrayString(t.Any())}];return _stringToStructureCoercions},_queryCoercions,queryCoercions=()=>{if(!_queryCoercions)_queryCoercions=[{from:t.Object({}),to:()=>t.ObjectString({}),excludeRoot:!0},{from:t.Array(t.Any()),to:()=>t.ArrayQuery(t.Any())}];return _queryCoercions},_coercePrimitiveRoot,coercePrimitiveRoot=()=>{if(!_coercePrimitiveRoot)_coercePrimitiveRoot=[{from:t.Number(),to:(options)=>t.Numeric(options),rootOnly:!0},{from:t.Boolean(),to:(options)=>t.BooleanString(options),rootOnly:!0}];return _coercePrimitiveRoot},getCookieValidator=({validator,modules,defaultConfig={},config,dynamic,normalize=!1,models,validators,sanitize:sanitize2})=>{let cookieValidator=validator?.provider?validator:getSchemaValidator(validator,{modules,dynamic,models,normalize,additionalProperties:!0,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators,sanitize:sanitize2});if(cookieValidator)cookieValidator.config=mergeCookie(cookieValidator.config,config);else cookieValidator=getSchemaValidator(t.Cookie(t.Any()),{modules,dynamic,models,additionalProperties:!0,validators,sanitize:sanitize2}),cookieValidator.config=defaultConfig;return cookieValidator},unwrapImportSchema=(schema)=>schema&&schema[Kind4]==="Import"&&schema.$defs[schema.$ref][Kind4]==="Object"?schema.$defs[schema.$ref]:schema;var allocateIf=(value,condition)=>condition?value:"",defaultParsers=["json","text","urlencoded","arrayBuffer","formdata","application/json","text/plain","application/x-www-form-urlencoded","application/octet-stream","multipart/form-data"],createReport=({context="c",trace=[],addFn})=>{if(!trace.length)return()=>{return{resolveChild(){return()=>{}},resolve(){}}};for(let i=0;i<trace.length;i++)addFn(`let report${i},reportChild${i},reportErr${i},reportErrChild${i};let trace${i}=${context}[ELYSIA_TRACE]?.[${i}]??trace[${i}](${context});
41
41
  `);return(event,{name,total=0,alias}={})=>{if(!name)name="anonymous";let reporter=event==="error"?"reportErr":"report";for(let i=0;i<trace.length;i++)if(addFn(`${alias?"const ":""}${alias??reporter}${i}=trace${i}.${event}({id,event:'${event}',name:'${name}',begin:performance.now(),total:${total}})
42
42
  `),alias)addFn(`${reporter}${i}=${alias}${i}
43
43
  `);return{resolve(){for(let i=0;i<trace.length;i++)addFn(`${alias??reporter}${i}.resolve()
@@ -67,10 +67,10 @@ throw error.error ?? new ValidationError('${type}',validator.${type},${value},${
67
67
  return function(){return a.clone()}`)(handler);return Function("a",`"use strict";
68
68
  return function(){return a}`)(handler)}if(isResponse){let response=handler;handler=()=>response.clone()}}let handle=isHandleFn?"handler(c)":"handler",hasTrace=!!hooks.trace?.length,fnLiteral="";if(inference=sucrose(Object.assign({handler},hooks),inference,app.config.sucrose),adapter.declare){let literal=adapter.declare(inference);if(literal)fnLiteral+=literal}if(inference.server)fnLiteral+=`Object.defineProperty(c,'server',{get:function(){return getServer()}})
69
69
  `;validator.createBody?.(),validator.createQuery?.(),validator.createHeaders?.(),validator.createParams?.(),validator.createCookie?.(),validator.createResponse?.();let hasValidation=!!validator.body||!!validator.headers||!!validator.params||!!validator.query||!!validator.cookie||!!validator.response,hasQuery=inference.query||!!validator.query,requestNoBody=hooks.parse?.length===1&&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,_encodeCookie="",encodeCookie=()=>{if(_encodeCookie)return _encodeCookie;if(cookieMeta?.sign){if(!cookieMeta.secrets)throw Error(`t.Cookie required secret which is not set in (${method}) ${path}.`);let secret=!cookieMeta.secrets?void 0:typeof cookieMeta.secrets==="string"?cookieMeta.secrets:cookieMeta.secrets[0];if(_encodeCookie+=`const _setCookie = c.set.cookie
70
- if(_setCookie){`,cookieMeta.sign===!0)_encodeCookie+=`for(const [key, cookie] of Object.entries(_setCookie)){c.set.cookie[key].value=await signCookie(cookie.value,${!secret?"undefined":overrideUnsafeQuote(secret)})}`;else{if(typeof cookieMeta.sign==="string")cookieMeta.sign=[cookieMeta.sign];for(let name of cookieMeta.sign)_encodeCookie+=`if(_setCookie[${overrideUnsafeQuote(name)}]?.value)c.set.cookie[${overrideUnsafeQuote(name)}].value=await signCookie(_setCookie[${overrideUnsafeQuote(name)}].value,${!secret?"undefined":overrideUnsafeQuote(secret)})
70
+ if(_setCookie){`,cookieMeta.sign===!0)_encodeCookie+=`for(const [key, cookie] of Object.entries(_setCookie)){c.set.cookie[key].value=await signCookie(cookie.value,${!secret?"undefined":JSON.stringify(secret)})}`;else{if(typeof cookieMeta.sign==="string")cookieMeta.sign=[cookieMeta.sign];for(let name of cookieMeta.sign)_encodeCookie+=`if(_setCookie[${JSON.stringify(name)}]?.value)c.set.cookie[${JSON.stringify(name)}].value=await signCookie(_setCookie[${JSON.stringify(name)}].value,${!secret?"undefined":JSON.stringify(secret)})
71
71
  `}_encodeCookie+=`}
72
72
  `}return _encodeCookie},normalize=app.config.normalize,encodeSchema=app.config.encodeSchema,allowUnsafeValidationDetails=app.config.allowUnsafeValidationDetails,validation=composeValidationFactory({normalize,validator,encodeSchema,isStaticResponse:handler instanceof Response,hasSanitize:!!app.config.sanitize,allowUnsafeValidationDetails});if(hasHeaders)fnLiteral+=adapter.headers;if(hasTrace)fnLiteral+=`const id=c[ELYSIA_REQUEST_ID]
73
- `;let report=createReport({trace:hooks.trace,addFn:(word)=>{fnLiteral+=word}});if(fnLiteral+="try{",hasCookie){let get=(name,defaultValue)=>{let value=cookieMeta?.[name]??defaultValue;if(value===void 0)return"";if(!value)return typeof defaultValue==="string"?`${name}:"${defaultValue}",`:`${name}:${defaultValue},`;if(typeof value==="string")return`${name}:${overrideUnsafeQuote(value)},`;if(value instanceof Date)return`${name}: new Date(${value.getTime()}),`;return`${name}:${value},`},options=cookieMeta?`{secrets:${cookieMeta.secrets!==void 0?typeof cookieMeta.secrets==="string"?overrideUnsafeQuote(cookieMeta.secrets):"["+cookieMeta.secrets.map(overrideUnsafeQuoteArrayValue).reduce((a,b)=>a+`'${b}',`,"")+"]":"undefined"},sign:${cookieMeta.sign===!0?!0:cookieMeta.sign!==void 0?typeof cookieMeta.sign==="string"?overrideUnsafeQuote(cookieMeta.sign):"["+cookieMeta.sign.map(overrideUnsafeQuoteArrayValue).reduce((a,b)=>a+`'${b}',`,"")+"]":"undefined"},`+get("domain")+get("expires")+get("httpOnly")+get("maxAge")+get("path","/")+get("priority")+get("sameSite")+get("secure")+"}":"undefined";if(hasHeaders)fnLiteral+=`
73
+ `;let report=createReport({trace:hooks.trace,addFn:(word)=>{fnLiteral+=word}});if(fnLiteral+="try{",hasCookie){let get=(name,defaultValue)=>{let value=cookieMeta?.[name]??defaultValue;if(value===void 0)return"";if(!value)return typeof defaultValue==="string"?`${name}:"${defaultValue}",`:`${name}:${defaultValue},`;if(typeof value==="string")return`${name}:${JSON.stringify(value)},`;if(value instanceof Date)return`${name}: new Date(${value.getTime()}),`;return`${name}:${value},`},options=cookieMeta?`{secrets:${cookieMeta.secrets!==void 0?typeof cookieMeta.secrets==="string"?JSON.stringify(cookieMeta.secrets):"["+cookieMeta.secrets.map((x)=>JSON.stringify(x)).join(",")+"]":"undefined"},sign:${cookieMeta.sign===!0?!0:cookieMeta.sign!==void 0?typeof cookieMeta.sign==="string"?JSON.stringify(cookieMeta.sign):"["+cookieMeta.sign.map((x)=>JSON.stringify(x)).join(",")+"]":"undefined"},`+get("domain")+get("expires")+get("httpOnly")+get("maxAge")+get("path","/")+get("priority")+get("sameSite")+get("secure")+"}":"undefined";if(hasHeaders)fnLiteral+=`
74
74
  c.cookie=await parseCookie(c.set,c.headers.cookie,${options})
75
75
  `;else fnLiteral+=`
76
76
  c.cookie=await parseCookie(c.set,c.request.headers.get('cookie'),${options})
@@ -360,5 +360,5 @@ for(const [k,v] of c.request.headers.entries())c.headers[k]=v
360
360
  `},listen(app){return(options,callback)=>{if(typeof Bun>"u")throw Error(".listen() is designed to run on Bun only. If you are running Elysia in other environment please use a dedicated plugin or export the handler via Elysia.fetch");if(app.compile(),typeof options==="string"){if(!isNumericString(options))throw Error("Port must be a numeric value");options=parseInt(options)}let createStaticRoute=(iterator,{withAsync=!1}={})=>{let staticRoutes={},ops=[];for(let[path,route]of Object.entries(iterator))if(path=encodeURI(path),supportPerMethodInlineHandler){if(!route)continue;for(let[method,value]of Object.entries(route)){if(!value||!(method in supportedMethods))continue;if(value instanceof Promise){if(withAsync){if(!staticRoutes[path])staticRoutes[path]={};ops.push(value.then((awaited)=>{if(awaited instanceof Response)staticRoutes[path][method]=awaited;if(isHTMLBundle(awaited))staticRoutes[path][method]=awaited}))}continue}if(!(value instanceof Response)&&!isHTMLBundle(value))continue;if(!staticRoutes[path])staticRoutes[path]={};staticRoutes[path][method]=value}}else{if(!route)continue;if(route instanceof Promise){if(withAsync){if(!staticRoutes[path])staticRoutes[path]={};ops.push(route.then((awaited)=>{if(awaited instanceof Response)staticRoutes[path]=awaited}))}continue}if(!(route instanceof Response))continue;staticRoutes[path]=route}if(withAsync)return Promise.all(ops).then(()=>staticRoutes);return staticRoutes},serve=typeof options==="object"?{development:!isProduction,reusePort:!0,idleTimeout:30,...app.config.serve||{},...options||{},routes:mergeRoutes(mergeRoutes(createStaticRoute(app.router.response),mapRoutes(app)),app.config.serve?.routes),websocket:{...app.config.websocket||{},...websocket||{},...options.websocket||{}},fetch:app.fetch}:{development:!isProduction,reusePort:!0,idleTimeout:30,...app.config.serve||{},routes:mergeRoutes(mergeRoutes(createStaticRoute(app.router.response),mapRoutes(app)),app.config.serve?.routes),websocket:{...app.config.websocket||{},...websocket||{}},port:options,fetch:app.fetch};if(app.server=Bun.serve(serve),app.event.start)for(let i=0;i<app.event.start.length;i++)app.event.start[i].fn(app);if(callback)callback(app.server);process.on("beforeExit",async()=>{if(app.server){if(await app.server.stop?.(),app.server=null,app.event.stop)for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(app)}}),app.promisedModules.then(async()=>{app.server?.reload({...serve,fetch:app.fetch,routes:mergeRoutes(mergeRoutes(await createStaticRoute(app.router.response,{withAsync:!0}),mapRoutes(app)),app.config.serve?.routes)}),Bun?.gc(!1)})}},async stop(app,closeActiveConnections){if(app.server){if(await app.server.stop(closeActiveConnections),app.server=null,app.event.stop?.length)for(let i=0;i<app.event.stop.length;i++)app.event.stop[i].fn(app)}else console.log("Elysia isn't running. Call `app.listen` to start the server.",Error().stack)},ws(app,path,options){let{parse:parse2,body,response,...rest}=options,messageValidator=getSchemaValidator(body,{modules:app.definitions.typebox,models:app.definitions.type,normalize:app.config.normalize}),validateMessage=messageValidator?messageValidator.provider==="standard"?(data)=>messageValidator.schema["~standard"].validate(data).issues:(data)=>messageValidator.Check(data)===!1:void 0,responseValidator=getSchemaValidator(response,{modules:app.definitions.typebox,models:app.definitions.type,normalize:app.config.normalize});app.route("WS",path,async(context)=>{let server=context.server??app.server,{set:set2,path:path2,qi,headers,query,params}=context;if(context.validator=responseValidator,options.upgrade){if(typeof options.upgrade==="function"){let temp=options.upgrade(context);if(temp instanceof Promise)await temp}else if(options.upgrade)Object.assign(set2.headers,options.upgrade)}if(set2.cookie&&isNotEmpty(set2.cookie)){let cookie=serializeCookie(set2.cookie);if(cookie)set2.headers["set-cookie"]=cookie}if(set2.headers["set-cookie"]&&Array.isArray(set2.headers["set-cookie"]))set2.headers=parseSetCookies(new Headers(set2.headers),set2.headers["set-cookie"]);let handleResponse3=createHandleWSResponse(responseValidator),parseMessage=createWSMessageParser(parse2),_id;if(typeof options.beforeHandle==="function"){let result=options.beforeHandle(context);if(result instanceof Promise)await result}let errorHandlers=[...options.error?Array.isArray(options.error)?options.error:[options.error]:[],...(app.event.error??[]).map((x)=>typeof x==="function"?x:x.fn)].filter((x)=>x),hasCustomErrorHandlers=errorHandlers.length>0,handleErrors=!hasCustomErrorHandlers?()=>{}:async(ws,error)=>{for(let handleError of errorHandlers){let response2=handleError(Object.assign(context,{error}));if(response2 instanceof Promise)response2=await response2;if(await handleResponse3(ws,response2),response2)break}};if(server?.upgrade(context.request,{headers:isNotEmpty(set2.headers)?set2.headers:void 0,data:{...context,get id(){if(_id)return _id;return _id=randomId()},validator:responseValidator,ping(ws,data){options.ping?.(ws,data)},pong(ws,data){options.pong?.(ws,data)},open:async(ws)=>{try{await handleResponse3(ws,options.open?.(new ElysiaWS(ws,context)))}catch(error){handleErrors(ws,error)}},message:async(ws,_message)=>{let message=await parseMessage(ws,_message);if(validateMessage&&validateMessage(message)){let validationError=new ValidationError("message",messageValidator,message);if(!hasCustomErrorHandlers)return void ws.send(validationError.message);return handleErrors(ws,validationError)}try{await handleResponse3(ws,options.message?.(new ElysiaWS(ws,context,message),message))}catch(error){handleErrors(ws,error)}},drain:async(ws)=>{try{await handleResponse3(ws,options.drain?.(new ElysiaWS(ws,context)))}catch(error){handleErrors(ws,error)}},close:async(ws,code,reason)=>{try{await handleResponse3(ws,options.close?.(new ElysiaWS(ws,context),code,reason))}catch(error){handleErrors(ws,error)}}}}))return;return status(400,"Expected a websocket connection")},{...rest,websocket:options})}};import{TransformDecodeError as TransformDecodeError2}from"@sinclair/typebox/value";var injectDefaultValues=(typeChecker,obj)=>{let schema=typeChecker.schema;if(!schema)return;if(schema.$defs?.[schema.$ref])schema=schema.$defs[schema.$ref];if(!schema?.properties)return;for(let[key,keySchema]of Object.entries(schema.properties))obj[key]??=keySchema.default},createDynamicHandler=(app)=>{let{mapResponse:mapResponse3,mapEarlyResponse:mapEarlyResponse3}=app["~adapter"].handler,defaultHeader=app.setHeaders;return async(request)=>{let url=request.url,s=url.indexOf("/",11),qi=url.indexOf("?",s+1),path=qi===-1?url.substring(s):url.substring(s,qi),set2={cookie:{},status:200,headers:defaultHeader?{...defaultHeader}:{}},context=Object.assign({},app.singleton.decorator,{set:set2,store:app.singleton.store,request,path,qi,error:status,status,redirect});try{if(app.event.request)for(let i=0;i<app.event.request.length;i++){let onRequest=app.event.request[i].fn,response2=onRequest(context);if(response2 instanceof Promise)response2=await response2;if(response2=mapEarlyResponse3(response2,set2),response2)return context.response=response2}let methodKey=request.method==="GET"&&request.headers.get("upgrade")?.toLowerCase()==="websocket"?"WS":request.method,handler=app.router.dynamic.find(request.method,path)??app.router.dynamic.find(methodKey,path)??app.router.dynamic.find("ALL",path);if(!handler)throw context.query=qi===-1?{}:parseQuery(url.substring(qi+1)),new NotFoundError;let{handle,hooks,validator,content,route}=handler.store,body;if(request.method!=="GET"&&request.method!=="HEAD")if(content)switch(content){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":{body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}}else{let contentType;if(request.body)contentType=request.headers.get("content-type");if(contentType){let index=contentType.indexOf(";");if(index!==-1)contentType=contentType.slice(0,index);if(context.contentType=contentType,hooks.parse)for(let i=0;i<hooks.parse.length;i++){let hook=hooks.parse[i].fn;if(typeof hook==="string")switch(hook){case"json":case"application/json":body=await request.json();break;case"text":case"text/plain":body=await request.text();break;case"urlencoded":case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"arrayBuffer":case"application/octet-stream":body=await request.arrayBuffer();break;case"formdata":case"multipart/form-data":{body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}default:{let parser=app["~parser"][hook];if(parser){let temp=parser(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}break}}else{let temp=hook(context,contentType);if(temp instanceof Promise)temp=await temp;if(temp){body=temp;break}}}if(delete context.contentType,body===void 0)switch(contentType){case"application/json":body=await request.json();break;case"text/plain":body=await request.text();break;case"application/x-www-form-urlencoded":body=parseQuery(await request.text());break;case"application/octet-stream":body=await request.arrayBuffer();break;case"multipart/form-data":{body={};let form2=await request.formData();for(let key of form2.keys()){if(body[key])continue;let value=form2.getAll(key);if(value.length===1)body[key]=value[0];else body[key]=value}break}}}}context.route=route,context.body=body,context.params=handler?.params||void 0,context.query=qi===-1?{}:parseQuery(url.substring(qi+1)),context.headers={};for(let[key,value]of request.headers.entries())context.headers[key]=value;let cookieMeta={domain:app.config.cookie?.domain??validator?.cookie?.config.domain,expires:app.config.cookie?.expires??validator?.cookie?.config.expires,httpOnly:app.config.cookie?.httpOnly??validator?.cookie?.config.httpOnly,maxAge:app.config.cookie?.maxAge??validator?.cookie?.config.maxAge,path:app.config.cookie?.path??validator?.cookie?.config.path,priority:app.config.cookie?.priority??validator?.cookie?.config.priority,partitioned:app.config.cookie?.partitioned??validator?.cookie?.config.partitioned,sameSite:app.config.cookie?.sameSite??validator?.cookie?.config.sameSite,secure:app.config.cookie?.secure??validator?.cookie?.config.secure,secrets:app.config.cookie?.secrets??validator?.cookie?.config.secrets,sign:app.config.cookie?.sign??validator?.cookie?.config.sign},cookieHeaderValue=request.headers.get("cookie");context.cookie=await parseCookie(context.set,cookieHeaderValue,cookieMeta);let headerValidator=validator?.createHeaders?.();if(headerValidator)injectDefaultValues(headerValidator,context.headers);let paramsValidator=validator?.createParams?.();if(paramsValidator)injectDefaultValues(paramsValidator,context.params);let queryValidator=validator?.createQuery?.();if(queryValidator)injectDefaultValues(queryValidator,context.query);if(hooks.transform)for(let i=0;i<hooks.transform.length;i++){let hook=hooks.transform[i],response2=hook.fn(context);if(response2 instanceof Promise)response2=await response2;if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}if(hook.subType==="derive")Object.assign(context,response2)}if(validator){if(headerValidator){let _header=structuredClone(context.headers);for(let[key,value]of request.headers)_header[key]=value;if(validator.headers.Check(_header)===!1)throw new ValidationError("header",validator.headers,_header)}else if(validator.headers?.Decode)context.headers=validator.headers.Decode(context.headers);if(paramsValidator?.Check(context.params)===!1)throw new ValidationError("params",validator.params,context.params);else if(validator.params?.Decode)context.params=validator.params.Decode(context.params);if(validator.query?.schema){let schema=validator.query.schema;if(schema.$defs?.[schema.$ref])schema=schema.$defs[schema.$ref];let properties=schema.properties;for(let property of Object.keys(properties)){let value=properties[property];if((value.type==="array"||value.items?.type==="string")&&typeof context.query[property]==="string"&&context.query[property])context.query[property]=context.query[property].split(",")}}if(queryValidator?.Check(context.query)===!1)throw new ValidationError("query",validator.query,context.query);else if(validator.query?.Decode)context.query=validator.query.Decode(context.query);if(validator.createCookie?.()){let cookieValue={};for(let[key,value]of Object.entries(context.cookie))cookieValue[key]=value.value;if(validator.cookie.Check(cookieValue)===!1)throw new ValidationError("cookie",validator.cookie,cookieValue);else if(validator.cookie?.Decode)cookieValue=validator.cookie.Decode(cookieValue)}if(validator.createBody?.()?.Check(body)===!1)throw new ValidationError("body",validator.body,body);else if(validator.body?.Decode)context.body=validator.body.Decode(body)}if(hooks.beforeHandle)for(let i=0;i<hooks.beforeHandle.length;i++){let hook=hooks.beforeHandle[i],response2=hook.fn(context);if(response2 instanceof Promise)response2=await response2;if(response2 instanceof ElysiaCustomStatusResponse){let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}if(hook.subType==="resolve"){Object.assign(context,response2);continue}if(response2!==void 0){if(context.response=response2,hooks.afterHandle)for(let i2=0;i2<hooks.afterHandle.length;i2++){let newResponse=hooks.afterHandle[i2].fn(context);if(newResponse instanceof Promise)newResponse=await newResponse;if(newResponse)response2=newResponse}let result=mapEarlyResponse3(response2,context.set);if(result)return context.response=result}}let response=typeof handle==="function"?handle(context):handle;if(response instanceof Promise)response=await response;if(!hooks.afterHandle?.length){let isCustomStatuResponse=response instanceof ElysiaCustomStatusResponse,status2=isCustomStatuResponse?response.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200;if(isCustomStatuResponse)set2.status=status2,response=response.response;let responseValidator=validator?.createResponse?.()?.[status2];if(responseValidator?.Check(response)===!1)if(responseValidator?.Clean){let temp=responseValidator.Clean(response);if(responseValidator?.Check(temp)===!1)throw new ValidationError("response",responseValidator,response);response=temp}else throw new ValidationError("response",responseValidator,response);if(responseValidator?.Encode)response=responseValidator.Encode(response);if(responseValidator?.Clean)response=responseValidator.Clean(response)}else{context.response=response;for(let i=0;i<hooks.afterHandle.length;i++){let response2=hooks.afterHandle[i].fn(context);if(response2 instanceof Promise)response2=await response2;let isCustomStatuResponse=response2 instanceof ElysiaCustomStatusResponse,status2=isCustomStatuResponse?response2.code:set2.status?typeof set2.status==="string"?StatusMap[set2.status]:set2.status:200;if(isCustomStatuResponse)set2.status=status2,response2=response2.response;let responseValidator=validator?.createResponse?.()?.[status2];if(responseValidator?.Check(response2)===!1)if(responseValidator?.Clean){let temp=responseValidator.Clean(response2);if(responseValidator?.Check(temp)===!1)throw new ValidationError("response",responseValidator,response2);response2=temp}else throw new ValidationError("response",responseValidator,response2);if(responseValidator?.Encode)context.response=response2=responseValidator.Encode(response2);if(responseValidator?.Clean)context.response=response2=responseValidator.Clean(response2);let result=mapEarlyResponse3(response2,context.set);if(result!==void 0)return context.response=result}}if(context.set.cookie&&cookieMeta?.sign){let secret=!cookieMeta.secrets?void 0:typeof cookieMeta.secrets==="string"?cookieMeta.secrets:cookieMeta.secrets[0];if(cookieMeta.sign===!0){if(secret)for(let[key,cookie]of Object.entries(context.set.cookie))context.set.cookie[key].value=await signCookie(cookie.value,secret)}else{let properties=validator?.cookie?.schema?.properties;if(secret)for(let name of cookieMeta.sign){if(!(name in properties))continue;if(context.set.cookie[name]?.value)context.set.cookie[name].value=await signCookie(context.set.cookie[name].value,secret)}}}return mapResponse3(context.response=response,context.set)}catch(error){let reportedError=error instanceof TransformDecodeError2&&error.error?error.error:error;return app.handleError(context,reportedError)}finally{if(app.event.afterResponse)setImmediate(async()=>{for(let afterResponse of app.event.afterResponse)await afterResponse.fn(context)})}}},createDynamicErrorHandler=(app)=>{let{mapResponse:mapResponse3}=app["~adapter"].handler;return async(context,error)=>{let errorContext=Object.assign(context,{error,code:error.code});if(errorContext.set=context.set,typeof error?.toResponse==="function"&&!(error instanceof ValidationError)&&!(error instanceof TransformDecodeError2))try{let raw=error.toResponse();if(typeof raw?.then==="function")raw=await raw;if(raw instanceof Response)context.set.status=raw.status;context.response=raw}catch(toResponseError){}if(!context.response&&app.event.error)for(let i=0;i<app.event.error.length;i++){let response=app.event.error[i].fn(errorContext);if(response instanceof Promise)response=await response;if(response!==void 0&&response!==null)return context.response=mapResponse3(response,context.set)}if(context.response){if(app.event.mapResponse)for(let i=0;i<app.event.mapResponse.length;i++){let response=app.event.mapResponse[i].fn(errorContext);if(response instanceof Promise)response=await response;if(response!==void 0&&response!==null)context.response=response}return mapResponse3(context.response,context.set)}return context.set.status=error.status??500,mapResponse3(typeof error.cause==="string"?error.cause:error.message,context.set)}};import{TypeSystemPolicy as TypeSystemPolicy2}from"@sinclair/typebox/system";class Elysia{config;server=null;dependencies={};"~Prefix"="";"~Singleton"=null;"~Definitions"=null;"~Metadata"=null;"~Ephemeral"=null;"~Volatile"=null;"~Routes"=null;singleton={decorator:{},store:{},derive:{},resolve:{}};get store(){return this.singleton.store}get decorator(){return this.singleton.decorator}definitions={typebox:t.Module({}),type:{},error:{}};extender={macro:{},higherOrderFunctions:[]};validator={global:null,scoped:null,local:null,getCandidate(){if(!this.global&&!this.scoped&&!this.local)return{body:void 0,headers:void 0,params:void 0,query:void 0,cookie:void 0,response:void 0};return mergeSchemaValidator(mergeSchemaValidator(this.global,this.scoped),this.local)}};standaloneValidator={global:null,scoped:null,local:null};event={};telemetry;router={"~http":void 0,get http(){if(!this["~http"])this["~http"]=new _({lazy:!0,onParam:import_fast_decode_uri_component4.default});return this["~http"]},"~dynamic":void 0,get dynamic(){if(!this["~dynamic"])this["~dynamic"]=new _({onParam:import_fast_decode_uri_component4.default});return this["~dynamic"]},static:{},response:{},history:[]};routeTree={};get routes(){return this.router.history}getGlobalRoutes(){return this.router.history}getGlobalDefinitions(){return this.definitions}inference={body:!1,cookie:!1,headers:!1,query:!1,set:!1,server:!1,path:!1,route:!1,url:!1};getServer(){return this.server}getParent(){return null}"~parser"={};_promisedModules;get promisedModules(){if(!this._promisedModules)this._promisedModules=new PromiseGroup(console.error,()=>{});return this._promisedModules}constructor(config={}){if(config.tags)if(!config.detail)config.detail={tags:config.tags};else config.detail.tags=config.tags;if(this.config={aot:env2.ELYSIA_AOT!=="false",nativeStaticResponse:!0,systemRouter:!0,encodeSchema:!0,normalize:!0,...config,prefix:config.prefix?config.prefix.charCodeAt(0)===47?config.prefix:`/${config.prefix}`:void 0,cookie:{path:"/",...config?.cookie},experimental:config?.experimental??{},seed:config?.seed===void 0?"":config?.seed},this["~adapter"]=config.adapter??(typeof Bun<"u"?BunAdapter:WebStandardAdapter),config?.analytic&&(config?.name||config?.seed!==void 0))this.telemetry={stack:Error().stack}}"~adapter";env(model,_env=env2){if(getSchemaValidator(model,{modules:this.definitions.typebox,dynamic:!0,additionalProperties:!0,coerce:!0,sanitize:()=>this.config.sanitize}).Check(_env)===!1){let error=new ValidationError("env",model,_env);throw Error(error.all.map((x)=>x.summary).join(`
361
361
  `))}return this}wrap(fn){return this.extender.higherOrderFunctions.push({checksum:checksum(JSON.stringify({name:this.config.name,seed:this.config.seed,content:fn.toString()})),fn}),this}get models(){let models={};for(let name of Object.keys(this.definitions.type))models[name]=getSchemaValidator(this.definitions.typebox.Import(name));return models.modules=this.definitions.typebox,models}add(method,path,handle,localHook,options){let skipPrefix=options?.skipPrefix??!1,allowMeta=options?.allowMeta??!1;localHook??={},this.applyMacro(localHook);let standaloneValidators=[];if(localHook.standaloneValidator)standaloneValidators=standaloneValidators.concat(localHook.standaloneValidator);if(this.standaloneValidator.local)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.local);if(this.standaloneValidator.scoped)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.scoped);if(this.standaloneValidator.global)standaloneValidators=standaloneValidators.concat(this.standaloneValidator.global);if(path!==""&&path.charCodeAt(0)!==47)path="/"+path;if(this.config.prefix&&!skipPrefix)path=this.config.prefix+path;if(localHook?.type)switch(localHook.type){case"text":localHook.type="text/plain";break;case"json":localHook.type="application/json";break;case"formdata":localHook.type="multipart/form-data";break;case"urlencoded":localHook.type="application/x-www-form-urlencoded";break;case"arrayBuffer":localHook.type="application/octet-stream";break;default:break}let instanceValidator=this.validator.getCandidate(),cloned={body:localHook?.body??instanceValidator?.body,headers:localHook?.headers??instanceValidator?.headers,params:localHook?.params??instanceValidator?.params,query:localHook?.query??instanceValidator?.query,cookie:localHook?.cookie??instanceValidator?.cookie,response:localHook?.response??instanceValidator?.response},shouldPrecompile=this.config.precompile===!0||typeof this.config.precompile==="object"&&this.config.precompile.compose===!0,createValidator=()=>{let models=this.definitions.type,dynamic=!this.config.aot,normalize=this.config.normalize,modules=this.definitions.typebox,sanitize2=()=>this.config.sanitize,cookieValidator=()=>{if(cloned.cookie||standaloneValidators.find((x)=>x.cookie))return getCookieValidator({modules,validator:cloned.cookie,defaultConfig:this.config.cookie,normalize,config:cloned.cookie?.config??{},dynamic,models,validators:standaloneValidators.map((x)=>x.cookie),sanitize:sanitize2})};return shouldPrecompile?{body:getSchemaValidator(cloned.body,{modules,dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot(),validators:standaloneValidators.map((x)=>x.body),sanitize:sanitize2}),headers:getSchemaValidator(cloned.headers,{modules,dynamic,models,additionalProperties:!0,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.headers),sanitize:sanitize2}),params:getSchemaValidator(cloned.params,{modules,dynamic,models,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.params),sanitize:sanitize2}),query:getSchemaValidator(cloned.query,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:queryCoercions(),validators:standaloneValidators.map((x)=>x.query),sanitize:sanitize2}),cookie:cookieValidator(),response:getResponseSchemaValidator(cloned.response,{modules,dynamic,models,normalize,validators:standaloneValidators.map((x)=>x.response),sanitize:sanitize2})}:{createBody(){if(this.body)return this.body;return this.body=getSchemaValidator(cloned.body,{modules,dynamic,models,normalize,additionalCoerce:coercePrimitiveRoot(),validators:standaloneValidators.map((x)=>x.body),sanitize:sanitize2})},createHeaders(){if(this.headers)return this.headers;return this.headers=getSchemaValidator(cloned.headers,{modules,dynamic,models,normalize,additionalProperties:!normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.headers),sanitize:sanitize2})},createParams(){if(this.params)return this.params;return this.params=getSchemaValidator(cloned.params,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:stringToStructureCoercions(),validators:standaloneValidators.map((x)=>x.params),sanitize:sanitize2})},createQuery(){if(this.query)return this.query;return this.query=getSchemaValidator(cloned.query,{modules,dynamic,models,normalize,coerce:!0,additionalCoerce:queryCoercions(),validators:standaloneValidators.map((x)=>x.query),sanitize:sanitize2})},createCookie(){if(this.cookie)return this.cookie;return this.cookie=cookieValidator()},createResponse(){if(this.response)return this.response;return this.response=getResponseSchemaValidator(cloned.response,{modules,dynamic,models,normalize,validators:standaloneValidators.map((x)=>x.response),sanitize:sanitize2})}}};if(instanceValidator.body||instanceValidator.cookie||instanceValidator.headers||instanceValidator.params||instanceValidator.query||instanceValidator.response)localHook=mergeHook(localHook,instanceValidator);if(localHook.tags)if(!localHook.detail)localHook.detail={tags:localHook.tags};else localHook.detail.tags=localHook.tags;if(isNotEmpty(this.config.detail))localHook.detail=mergeDeep(Object.assign({},this.config.detail),localHook.detail);let hooks=isNotEmpty(this.event)?mergeHook(this.event,localHookToLifeCycleStore(localHook)):{...lifeCycleToArray(localHookToLifeCycleStore(localHook))};if(standaloneValidators.length)Object.assign(hooks,{standaloneValidator:standaloneValidators});if(this.config.aot===!1){let validator=createValidator();this.router.dynamic.add(method,path,{validator,hooks,content:localHook?.type,handle,route:path});let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.dynamic.add(method,encoded,{validator,hooks,content:localHook?.type,handle,route:path});if(!this.config.strictPath){let loosePath=getLoosePath(path);this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle,route:path});let encoded2=encodePath(loosePath);if(loosePath!==encoded2)this.router.dynamic.add(method,loosePath,{validator,hooks,content:localHook?.type,handle,route:path})}this.router.history.push({method,path,composed:null,handler:handle,compile:void 0,hooks});return}let adapter=this["~adapter"].handler,nativeStaticHandler=typeof handle!=="function"?()=>{let context={redirect,request:this["~adapter"].isWebStandard?new Request(`http://ely.sia${path}`,{method}):void 0,server:null,set:{headers:Object.assign({},this.setHeaders)},status,store:this.store};try{this.event.request?.map((x)=>{if(typeof x.fn==="function")return x.fn(context);if(typeof x==="function")return x(context)})}catch(error){let res;if(context.error=error,this.event.error?.some((x)=>{if(typeof x.fn==="function")return res=x.fn(context);if(typeof x==="function")return res=x(context)}),res!==void 0)handle=res}let fn=adapter.createNativeStaticHandler?.(handle,hooks,context.set);return fn instanceof Promise?fn.then((fn2)=>{if(fn2)return fn2}):fn?.()}:void 0,useNativeStaticResponse=this.config.nativeStaticResponse===!0,addResponsePath=(path2)=>{if(!useNativeStaticResponse||!nativeStaticHandler)return;if(supportPerMethodInlineHandler)if(this.router.response[path2])this.router.response[path2][method]=nativeStaticHandler();else this.router.response[path2]={[method]:nativeStaticHandler()};else this.router.response[path2]=nativeStaticHandler()};addResponsePath(path);let compile2=()=>{let compiled=composeHandler({app:this,path,method,hooks,validator:createValidator(),handler:typeof handle!=="function"&&typeof adapter.createStaticHandler!=="function"?()=>handle:handle,allowMeta,inference:this.inference});if(this.router.history[index])this.router.history[index].composed=compiled;return compiled},oldIndex;if(`${method}_${path}`in this.routeTree)for(let i=0;i<this.router.history.length;i++){let route2=this.router.history[i];if(route2.path===path&&route2.method===method){oldIndex=i;break}}else this.routeTree[`${method}_${path}`]=this.router.history.length;let index=oldIndex??this.router.history.length,route=this.router.history,mainHandler=shouldPrecompile?compile2():(ctx)=>(route[index].composed=compile2())(ctx);if(oldIndex!==void 0)this.router.history[oldIndex]=Object.assign({method,path,composed:mainHandler,compile:compile2,handler:handle,hooks},standaloneValidators.length?{standaloneValidators}:void 0,localHook.webSocket?{websocket:localHook.websocket}:void 0);else this.router.history.push(Object.assign({method,path,composed:mainHandler,compile:compile2,handler:handle,hooks},localHook.webSocket?{websocket:localHook.websocket}:void 0));let handler={handler:shouldPrecompile?route[index].composed:void 0,compile(){return this.handler=compile2()}},staticRouter=this.router.static,isStaticPath=path.indexOf(":")===-1&&path.indexOf("*")===-1;if(method==="WS"){if(isStaticPath){if(path in staticRouter)staticRouter[path][method]=index;else staticRouter[path]={[method]:index};return}if(this.router.http.add("WS",path,handler),!this.config.strictPath)this.router.http.add("WS",getLoosePath(path),handler);let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.http.add("WS",encoded,handler);return}if(isStaticPath){if(path in staticRouter)staticRouter[path][method]=index;else staticRouter[path]={[method]:index};if(!this.config.strictPath)addResponsePath(getLoosePath(path))}else{if(this.router.http.add(method,path,handler),!this.config.strictPath){let loosePath=getLoosePath(path);addResponsePath(loosePath),this.router.http.add(method,loosePath,handler)}let encoded=encodePath(path,{dynamic:!0});if(path!==encoded)this.router.http.add(method,encoded,handler),addResponsePath(encoded)}}setHeaders;headers(header){if(!header)return this;if(!this.setHeaders)this.setHeaders={};return this.setHeaders=mergeDeep(this.setHeaders,header),this}onStart(handler){return this.on("start",handler),this}onRequest(handler){return this.on("request",handler),this}onParse(options,handler){if(!handler){if(typeof options==="string")return this.on("parse",this["~parser"][options]);return this.on("parse",options)}return this.on(options,"parse",handler)}parser(name,parser){return this["~parser"][name]=parser,this}onTransform(options,handler){if(!handler)return this.on("transform",options);return this.on(options,"transform",handler)}resolve(optionsOrResolve,resolve){if(!resolve)resolve=optionsOrResolve,optionsOrResolve={as:"local"};let hook={subType:"resolve",fn:resolve};return this.onBeforeHandle(optionsOrResolve,hook)}mapResolve(optionsOrResolve,mapper){if(!mapper)mapper=optionsOrResolve,optionsOrResolve={as:"local"};let hook={subType:"mapResolve",fn:mapper};return this.onBeforeHandle(optionsOrResolve,hook)}onBeforeHandle(options,handler){if(!handler)return this.on("beforeHandle",options);return this.on(options,"beforeHandle",handler)}onAfterHandle(options,handler){if(!handler)return this.on("afterHandle",options);return this.on(options,"afterHandle",handler)}mapResponse(options,handler){if(!handler)return this.on("mapResponse",options);return this.on(options,"mapResponse",handler)}onAfterResponse(options,handler){if(!handler)return this.on("afterResponse",options);return this.on(options,"afterResponse",handler)}trace(options,handler){if(!handler)handler=options,options={as:"local"};if(!Array.isArray(handler))handler=[handler];for(let fn of handler)this.on(options,"trace",createTracer(fn));return this}error(name,error){switch(typeof name){case"string":return error.prototype[ERROR_CODE]=name,this.definitions.error[name]=error,this;case"function":return this.definitions.error=name(this.definitions.error),this}for(let[code,error2]of Object.entries(name))error2.prototype[ERROR_CODE]=code,this.definitions.error[code]=error2;return this}onError(options,handler){if(!handler)return this.on("error",options);return this.on(options,"error",handler)}onStop(handler){return this.on("stop",handler),this}on(optionsOrType,typeOrHandlers,handlers){let type;switch(typeof optionsOrType){case"string":type=optionsOrType,handlers=typeOrHandlers;break;case"object":if(type=typeOrHandlers,!Array.isArray(typeOrHandlers)&&typeof typeOrHandlers==="object")handlers=typeOrHandlers;break}if(Array.isArray(handlers))handlers=fnToContainer(handlers);else if(typeof handlers==="function")handlers=[{fn:handlers}];else handlers=[handlers];let handles=handlers;for(let handle of handles)if(handle.scope=typeof optionsOrType==="string"?"local":optionsOrType?.as??"local",type==="resolve"||type==="derive")handle.subType=type;if(type!=="trace")this.inference=sucrose({[type]:handles.map((x)=>x.fn)},this.inference,this.config.sucrose);for(let handle of handles){let fn=asHookType(handle,"global",{skipIfHasType:!0});switch(type){case"start":this.event.start??=[],this.event.start.push(fn);break;case"request":this.event.request??=[],this.event.request.push(fn);break;case"parse":this.event.parse??=[],this.event.parse.push(fn);break;case"transform":this.event.transform??=[],this.event.transform.push(fn);break;case"derive":this.event.transform??=[],this.event.transform.push(fnToContainer(fn,"derive"));break;case"beforeHandle":this.event.beforeHandle??=[],this.event.beforeHandle.push(fn);break;case"resolve":this.event.beforeHandle??=[],this.event.beforeHandle.push(fnToContainer(fn,"resolve"));break;case"afterHandle":this.event.afterHandle??=[],this.event.afterHandle.push(fn);break;case"mapResponse":this.event.mapResponse??=[],this.event.mapResponse.push(fn);break;case"afterResponse":this.event.afterResponse??=[],this.event.afterResponse.push(fn);break;case"trace":this.event.trace??=[],this.event.trace.push(fn);break;case"error":this.event.error??=[],this.event.error.push(fn);break;case"stop":this.event.stop??=[],this.event.stop.push(fn);break}}return this}as(type){if(promoteEvent(this.event.parse,type),promoteEvent(this.event.transform,type),promoteEvent(this.event.beforeHandle,type),promoteEvent(this.event.afterHandle,type),promoteEvent(this.event.mapResponse,type),promoteEvent(this.event.afterResponse,type),promoteEvent(this.event.trace,type),promoteEvent(this.event.error,type),type==="scoped"){if(this.validator.scoped=mergeSchemaValidator(this.validator.scoped,this.validator.local),this.validator.local=null,this.standaloneValidator.local!==null)this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null}else if(type==="global"){if(this.validator.global=mergeSchemaValidator(this.validator.global,mergeSchemaValidator(this.validator.scoped,this.validator.local)),this.validator.scoped=null,this.validator.local=null,this.standaloneValidator.local!==null)this.standaloneValidator.scoped||=[],this.standaloneValidator.scoped.push(...this.standaloneValidator.local),this.standaloneValidator.local=null;if(this.standaloneValidator.scoped!==null)this.standaloneValidator.global||=[],this.standaloneValidator.global.push(...this.standaloneValidator.scoped),this.standaloneValidator.scoped=null}return this}group(prefix,schemaOrRun,run){let instance=new Elysia({...this.config,prefix:""});instance.singleton={...this.singleton},instance.definitions={...this.definitions},instance.getServer=()=>this.getServer(),instance.inference=cloneInference(this.inference),instance.extender={...this.extender},instance["~parser"]=this["~parser"],instance.standaloneValidator={local:[...this.standaloneValidator.local??[]],scoped:[...this.standaloneValidator.scoped??[]],global:[...this.standaloneValidator.global??[]]};let isSchema=typeof schemaOrRun==="object",sandbox=(isSchema?run:schemaOrRun)(instance);if(this.singleton=mergeDeep(this.singleton,instance.singleton),this.definitions=mergeDeep(this.definitions,instance.definitions),sandbox.event.request?.length)this.event.request=[...this.event.request||[],...sandbox.event.request||[]];if(sandbox.event.mapResponse?.length)this.event.mapResponse=[...this.event.mapResponse||[],...sandbox.event.mapResponse||[]];return this.model(sandbox.definitions.type),Object.values(instance.router.history).forEach(({method,path,handler,hooks})=>{if(path=(isSchema?"":this.config.prefix??"")+prefix+path,isSchema){let{body,headers,query,params,cookie,response,...hook}=schemaOrRun,localHook=hooks,hasStandaloneSchema=body||headers||query||params||cookie||response;this.add(method,path,handler,mergeHook(hook,{...localHook||{},error:!localHook.error?sandbox.event.error:Array.isArray(localHook.error)?[...localHook.error??[],...sandbox.event.error??[]]:[localHook.error,...sandbox.event.error??[]],standaloneValidator:!hasStandaloneSchema?localHook.standaloneValidator:[...localHook.standaloneValidator??[],{body,headers,query,params,cookie,response}]}),void 0)}else this.add(method,path,handler,mergeHook(hooks,{error:sandbox.event.error}),{skipPrefix:!0})}),this}guard(hook,run){if(!run){if(typeof hook==="object"){if(this.applyMacro(hook),hook.detail)if(this.config.detail)this.config.detail=mergeDeep(Object.assign({},this.config.detail),hook.detail);else this.config.detail=hook.detail;if(hook.tags)if(!this.config.detail)this.config.detail={tags:hook.tags};else this.config.detail.tags=hook.tags;let type=hook.as??"local";if(hook.schema==="standalone"){if(!this.standaloneValidator[type])this.standaloneValidator[type]=[];let response=!hook?.response?void 0:typeof hook.response==="string"||(Kind6 in hook.response)||("~standard"in hook.response)?{200:hook.response}:hook?.response;this.standaloneValidator[type].push({body:hook.body,headers:hook.headers,params:hook.params,query:hook.query,response,cookie:hook.cookie})}else this.validator[type]={body:hook.body??this.validator[type]?.body,headers:hook.headers??this.validator[type]?.headers,params:hook.params??this.validator[type]?.params,query:hook.query??this.validator[type]?.query,response:hook.response??this.validator[type]?.response,cookie:hook.cookie??this.validator[type]?.cookie};if(hook.parse)this.on({as:type},"parse",hook.parse);if(hook.transform)this.on({as:type},"transform",hook.transform);if(hook.derive)this.on({as:type},"derive",hook.derive);if(hook.beforeHandle)this.on({as:type},"beforeHandle",hook.beforeHandle);if(hook.resolve)this.on({as:type},"resolve",hook.resolve);if(hook.afterHandle)this.on({as:type},"afterHandle",hook.afterHandle);if(hook.mapResponse)this.on({as:type},"mapResponse",hook.mapResponse);if(hook.afterResponse)this.on({as:type},"afterResponse",hook.afterResponse);if(hook.error)this.on({as:type},"error",hook.error);return this}return this.guard({},hook)}let instance=new Elysia({...this.config,prefix:""});instance.singleton={...this.singleton},instance.definitions={...this.definitions},instance.inference=cloneInference(this.inference),instance.extender={...this.extender},instance.getServer=()=>this.getServer();let sandbox=run(instance);if(this.singleton=mergeDeep(this.singleton,instance.singleton),this.definitions=mergeDeep(this.definitions,instance.definitions),sandbox.getServer=()=>this.server,sandbox.event.request?.length)this.event.request=[...this.event.request||[],...sandbox.event.request||[]];if(sandbox.event.mapResponse?.length)this.event.mapResponse=[...this.event.mapResponse||[],...sandbox.event.mapResponse||[]];return this.model(sandbox.definitions.type),Object.values(instance.router.history).forEach(({method,path,handler,hooks:localHook})=>{let{body,headers,query,params,cookie,response,...guardHook}=hook,hasStandaloneSchema=body||headers||query||params||cookie||response;this.add(method,path,handler,mergeHook(guardHook,{...localHook||{},error:!localHook.error?sandbox.event.error:Array.isArray(localHook.error)?[...localHook.error??[],...sandbox.event.error??[]]:[localHook.error,...sandbox.event.error??[]],standaloneValidator:!hasStandaloneSchema?localHook.standaloneValidator:[...localHook.standaloneValidator??[],{body,headers,query,params,cookie,response}]}))}),this}use(plugin){if(!plugin)return this;if(Array.isArray(plugin)){let app=this;for(let p of plugin)app=app.use(p);return app}if(plugin instanceof Promise)return this.promisedModules.add(plugin.then((plugin2)=>{if(typeof plugin2==="function")return plugin2(this);if(plugin2 instanceof Elysia)return this._use(plugin2).compile();if(plugin2.constructor?.name==="Elysia")return this._use(plugin2).compile();if(typeof plugin2.default==="function")return plugin2.default(this);if(plugin2.default instanceof Elysia)return this._use(plugin2.default);if(plugin2.constructor?.name==="Elysia")return this._use(plugin2.default);if(plugin2.constructor?.name==="_Elysia")return this._use(plugin2.default);try{return this._use(plugin2.default)}catch(error){throw console.error('Invalid plugin type. Expected Elysia instance, function, or module with "default" as Elysia instance or function that returns Elysia instance.'),error}}).then((v)=>{if(v&&typeof v.compile==="function")v.compile();return v})),this;return this._use(plugin)}propagatePromiseModules(plugin){if(plugin.promisedModules.size<=0)return this;for(let promise of plugin.promisedModules.promises)this.promisedModules.add(promise.then((v)=>{if(!v)return;let t2=this._use(v);if(t2 instanceof Promise)return t2.then((v2)=>{if(v2)v2.compile();else v.compile()});return v.compile()}));return this}_use(plugin){if(typeof plugin==="function"){let instance=plugin(this);if(instance instanceof Promise)return this.promisedModules.add(instance.then((plugin2)=>{if(plugin2 instanceof Elysia){plugin2.getServer=()=>this.getServer(),plugin2.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin2.getGlobalDefinitions=()=>this.getGlobalDefinitions(),plugin2.model(this.definitions.type),plugin2.error(this.definitions.error);for(let{method,path,handler,hooks}of Object.values(plugin2.router.history))this.add(method,path,handler,hooks,void 0);if(plugin2===this)return;return this.propagatePromiseModules(plugin2),plugin2}if(typeof plugin2==="function")return plugin2(this);if(typeof plugin2.default==="function")return plugin2.default(this);return this._use(plugin2)}).then((v)=>{if(v&&typeof v.compile==="function")v.compile();return v})),this;return instance}this.propagatePromiseModules(plugin);let name=plugin.config.name,seed=plugin.config.seed;if(plugin.getParent=()=>this,plugin.getServer=()=>this.getServer(),plugin.getGlobalRoutes=()=>this.getGlobalRoutes(),plugin.getGlobalDefinitions=()=>this.getGlobalDefinitions(),plugin.standaloneValidator?.scoped)if(this.standaloneValidator.local)this.standaloneValidator.local=this.standaloneValidator.local.concat(plugin.standaloneValidator.scoped);else this.standaloneValidator.local=plugin.standaloneValidator.scoped;if(plugin.standaloneValidator?.global)if(this.standaloneValidator.global)this.standaloneValidator.global=this.standaloneValidator.global.concat(plugin.standaloneValidator.global);else this.standaloneValidator.global=plugin.standaloneValidator.global;if(isNotEmpty(plugin["~parser"]))this["~parser"]={...plugin["~parser"],...this["~parser"]};if(plugin.setHeaders)this.headers(plugin.setHeaders);if(name){if(!(name in this.dependencies))this.dependencies[name]=[];let current=seed!==void 0?checksum(name+JSON.stringify(seed)):0;if(!this.dependencies[name].some(({checksum:checksum2})=>current===checksum2))this.extender.macro={...this.extender.macro,...plugin.extender.macro},this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions)}else{if(isNotEmpty(plugin.extender.macro))this.extender.macro={...this.extender.macro,...plugin.extender.macro};if(plugin.extender.higherOrderFunctions.length)this.extender.higherOrderFunctions=this.extender.higherOrderFunctions.concat(plugin.extender.higherOrderFunctions)}if(plugin.extender.higherOrderFunctions.length){deduplicateChecksum(this.extender.higherOrderFunctions);let hofHashes=[];for(let i=0;i<this.extender.higherOrderFunctions.length;i++){let hof=this.extender.higherOrderFunctions[i];if(hof.checksum){if(hofHashes.includes(hof.checksum))this.extender.higherOrderFunctions.splice(i,1),i--;hofHashes.push(hof.checksum)}}hofHashes.length=0}if(this.inference=mergeInference(this.inference,plugin.inference),isNotEmpty(plugin.singleton.decorator))this.decorate(plugin.singleton.decorator);if(isNotEmpty(plugin.singleton.store))this.state(plugin.singleton.store);if(isNotEmpty(plugin.definitions.type))this.model(plugin.definitions.type);if(isNotEmpty(plugin.definitions.error))this.error(plugin.definitions.error);if(isNotEmpty(plugin.extender.macro))this.extender.macro={...this.extender.macro,...plugin.extender.macro};for(let{method,path,handler,hooks}of Object.values(plugin.router.history))this.add(method,path,handler,hooks);if(name){if(!(name in this.dependencies))this.dependencies[name]=[];let current=seed!==void 0?checksum(name+JSON.stringify(seed)):0;if(this.dependencies[name].some(({checksum:checksum2})=>current===checksum2))return this;if(this.dependencies[name].push(this.config?.analytic?{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies,stack:plugin.telemetry?.stack,routes:plugin.router.history,decorators:plugin.singleton,store:plugin.singleton.store,error:plugin.definitions.error,derive:plugin.event.transform?.filter((x)=>x?.subType==="derive").map((x)=>({fn:x.toString(),stack:Error().stack??""})),resolve:plugin.event.transform?.filter((x)=>x?.subType==="resolve").map((x)=>({fn:x.toString(),stack:Error().stack??""}))}:{name:plugin.config.name,seed:plugin.config.seed,checksum:current,dependencies:plugin.dependencies}),isNotEmpty(plugin.event))this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event),current)}else if(isNotEmpty(plugin.event))this.event=mergeLifeCycle(this.event,filterGlobalHook(plugin.event));if(plugin.validator.global)this.validator.global=mergeHook(this.validator.global,{...plugin.validator.global});if(plugin.validator.scoped)this.validator.local=mergeHook(this.validator.local,{...plugin.validator.scoped});return this}macro(macroOrName,macro){if(typeof macroOrName==="string"&&!macro)throw Error("Macro function is required");if(typeof macroOrName==="string")this.extender.macro[macroOrName]=macro;else this.extender.macro={...this.extender.macro,...macroOrName};return this}applyMacro(localHook,appliable=localHook,{iteration=0,applied={}}={}){if(iteration>=16)return;let macro=this.extender.macro;for(let[key,value]of Object.entries(appliable)){if(key in macro===!1)continue;let macroHook=typeof macro[key]==="function"?macro[key](value):macro[key];if(!macroHook||typeof macro[key]==="object"&&value===!1)return;let seed=checksum(key+JSON.stringify(macroHook.seed??value));if(seed in applied)continue;applied[seed]=!0;for(let[k2,value2]of Object.entries(macroHook)){if(k2==="seed")continue;if(k2 in emptySchema){insertStandaloneValidator(localHook,k2,value2),delete localHook[key];continue}if(k2==="introspect"){value2?.(localHook),delete localHook[key];continue}if(k2==="detail"){if(!localHook.detail)localHook.detail={};localHook.detail=mergeDeep(localHook.detail,value2,{mergeArray:!0}),delete localHook[key];continue}if(k2 in macro){this.applyMacro(localHook,{[k2]:value2},{applied,iteration:iteration+1}),delete localHook[key];continue}if((k2==="derive"||k2==="resolve")&&typeof value2==="function")value2={fn:value2,subType:k2};switch(typeof localHook[k2]){case"function":localHook[k2]=[localHook[k2],value2];break;case"object":if(Array.isArray(localHook[k2]))localHook[k2].push(value2);else localHook[k2]=[localHook[k2],value2];break;case"undefined":localHook[k2]=value2;break}delete localHook[key]}}}mount(path,handleOrConfig,config){if(path instanceof Elysia||typeof path==="function"||path.length===0||path==="/"){let run=typeof path==="function"?path:path instanceof Elysia?path.compile().fetch:handleOrConfig instanceof Elysia?handleOrConfig.compile().fetch:typeof handleOrConfig==="function"?handleOrConfig:(()=>{throw Error("Invalid handler")})(),handler2=({request,path:path2})=>run(new Request(replaceUrlPath(request.url,path2),{method:request.method,headers:request.headers,signal:request.signal,credentials:request.credentials,referrerPolicy:request.referrerPolicy,duplex:request.duplex,redirect:request.redirect,mode:request.mode,keepalive:request.keepalive,integrity:request.integrity,body:request.body}));return this.route("ALL","/*",handler2,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:run}}),this}let handle=handleOrConfig instanceof Elysia?handleOrConfig.compile().fetch:typeof handleOrConfig==="function"?handleOrConfig:(()=>{throw Error("Invalid handler")})(),length=path.length-(path.endsWith("*")?1:0),handler=({request,path:path2})=>handle(new Request(replaceUrlPath(request.url,path2.slice(length)||"/"),{method:request.method,headers:request.headers,signal:request.signal,credentials:request.credentials,referrerPolicy:request.referrerPolicy,duplex:request.duplex,redirect:request.redirect,mode:request.mode,keepalive:request.keepalive,integrity:request.integrity,body:request.body}));return this.route("ALL",path,handler,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:handle}}),this.route("ALL",path+(path.endsWith("/")?"*":"/*"),handler,{parse:"none",...config,detail:{...config?.detail,hide:!0},config:{mount:handle}}),this}get(path,handler,hook){return this.add("GET",path,handler,hook),this}post(path,handler,hook){return this.add("POST",path,handler,hook),this}put(path,handler,hook){return this.add("PUT",path,handler,hook),this}patch(path,handler,hook){return this.add("PATCH",path,handler,hook),this}delete(path,handler,hook){return this.add("DELETE",path,handler,hook),this}options(path,handler,hook){return this.add("OPTIONS",path,handler,hook),this}all(path,handler,hook){return this.add("ALL",path,handler,hook),this}head(path,handler,hook){return this.add("HEAD",path,handler,hook),this}connect(path,handler,hook){return this.add("CONNECT",path,handler,hook),this}route(method,path,handler,hook){return this.add(method.toUpperCase(),path,handler,hook,hook?.config),this}ws(path,options){if(this["~adapter"].ws)this["~adapter"].ws(this,path,options);else console.warn("Current adapter doesn't support WebSocket");return this}state(options,name,value){if(name===void 0)value=options,options={as:"append"},name="";else if(value===void 0){if(typeof options==="string")value=name,name=options,options={as:"append"};else if(typeof options==="object")value=name,name=""}let{as}=options;if(typeof name!=="string")return this;switch(typeof value){case"object":if(!value||!isNotEmpty(value))return this;if(name){if(name in this.singleton.store)this.singleton.store[name]=mergeDeep(this.singleton.store[name],value,{override:as==="override"});else this.singleton.store[name]=value;return this}if(value===null)return this;return this.singleton.store=mergeDeep(this.singleton.store,value,{override:as==="override"}),this;case"function":if(name){if(as==="override"||!(name in this.singleton.store))this.singleton.store[name]=value}else this.singleton.store=value(this.singleton.store);return this;default:if(as==="override"||!(name in this.singleton.store))this.singleton.store[name]=value;return this}}decorate(options,name,value){if(name===void 0)value=options,options={as:"append"},name="";else if(value===void 0){if(typeof options==="string")value=name,name=options,options={as:"append"};else if(typeof options==="object")value=name,name=""}let{as}=options;if(typeof name!=="string")return this;switch(typeof value){case"object":if(name){if(name in this.singleton.decorator)this.singleton.decorator[name]=mergeDeep(this.singleton.decorator[name],value,{override:as==="override"});else this.singleton.decorator[name]=value;return this}if(value===null)return this;return this.singleton.decorator=mergeDeep(this.singleton.decorator,value,{override:as==="override"}),this;case"function":if(name){if(as==="override"||!(name in this.singleton.decorator))this.singleton.decorator[name]=value}else this.singleton.decorator=value(this.singleton.decorator);return this;default:if(as==="override"||!(name in this.singleton.decorator))this.singleton.decorator[name]=value;return this}}derive(optionsOrTransform,transform){if(!transform)transform=optionsOrTransform,optionsOrTransform={as:"local"};let hook={subType:"derive",fn:transform};return this.onTransform(optionsOrTransform,hook)}model(name,model){let onlyTypebox=(a)=>{let res={};for(let key in a)if(!("~standard"in a[key]))res[key]=a[key];return res};switch(typeof name){case"object":let parsedTypebox={},kvs=Object.entries(name);if(!kvs.length)return this;for(let[key,value]of kvs){if(key in this.definitions.type)continue;if("~standard"in value)this.definitions.type[key]=value;else parsedTypebox[key]=this.definitions.type[key]=value,parsedTypebox[key].$id??=`#/components/schemas/${key}`}return this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...parsedTypebox}),this;case"function":let result=name(this.definitions.type);return this.definitions.type=result,this.definitions.typebox=t.Module(onlyTypebox(result)),this;case"string":if(!model)break;if(this.definitions.type[name]=model,"~standard"in model)return this;let newModel={...model,id:model.$id??`#/components/schemas/${name}`};return this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,...newModel}),this}if(!model)return this;if(this.definitions.type[name]=model,"~standard"in model)return this;return this.definitions.typebox=t.Module({...this.definitions.typebox.$defs,[name]:model}),this}Ref(key){return t.Ref(key)}mapDerive(optionsOrDerive,mapper){if(!mapper)mapper=optionsOrDerive,optionsOrDerive={as:"local"};let hook={subType:"mapDerive",fn:mapper};return this.onTransform(optionsOrDerive,hook)}affix(base,type,word){if(word==="")return this;let delimieter=["_","-"," "],capitalize=(word2)=>word2[0].toUpperCase()+word2.slice(1),joinKey=base==="prefix"?(prefix,word2)=>delimieter.includes(prefix.at(-1)??"")?prefix+word2:prefix+capitalize(word2):delimieter.includes(word.at(-1)??"")?(suffix,word2)=>word2+suffix:(suffix,word2)=>word2+capitalize(suffix),remap=(type2)=>{let store={};switch(type2){case"decorator":for(let key in this.singleton.decorator)store[joinKey(word,key)]=this.singleton.decorator[key];this.singleton.decorator=store;break;case"state":for(let key in this.singleton.store)store[joinKey(word,key)]=this.singleton.store[key];this.singleton.store=store;break;case"model":for(let key in this.definitions.type)store[joinKey(word,key)]=this.definitions.type[key];this.definitions.type=store;break;case"error":for(let key in this.definitions.error)store[joinKey(word,key)]=this.definitions.error[key];this.definitions.error=store;break}},types=Array.isArray(type)?type:[type];for(let type2 of types.some((x)=>x==="all")?["decorator","state","model","error"]:types)remap(type2);return this}prefix(type,word){return this.affix("prefix",type,word)}suffix(type,word){return this.affix("suffix",type,word)}compile(){if(this["~adapter"].beforeCompile?.(this),this["~adapter"].isWebStandard){if(this.fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this),typeof this.server?.reload==="function")this.server.reload({...this.server||{},fetch:this.fetch});return this}if(typeof this.server?.reload==="function")this.server.reload(this.server||{});return this._handle=composeGeneralHandler(this),this}handle=async(request)=>this.fetch(request);fetch=(request)=>{return(this.fetch=this.config.aot?composeGeneralHandler(this):createDynamicHandler(this))(request)};handleError=async(context,error)=>{return(this.handleError=this.config.aot?composeErrorHandler(this):createDynamicErrorHandler(this))(context,error)};listen=(options,callback)=>{return this["~adapter"].listen(this)(options,callback),this};stop=async(closeActiveConnections)=>{return await this["~adapter"].stop?.(this,closeActiveConnections),this};[Symbol.dispose]=()=>{if(this.server)this.stop()};get modules(){return this.promisedModules}}export{validationDetail,t,status,sse,serializeCookie,replaceUrlPath,replaceSchemaType,redirect,mergeObjectArray,mergeHook,mapValueError,getSchemaValidator,getResponseSchemaValidator,form,fileType,file,env2 as env,Elysia as default,deduplicateChecksum,cloneInference,checksum,ValidationError,TypeSystemPolicy2 as TypeSystemPolicy,StatusMap,ParseError,NotFoundError,InvertedStatusMap,InvalidFileType,InvalidCookieSignature,InternalServerError,ElysiaFile,ElysiaCustomStatusResponse,Elysia,ERROR_CODE,ELYSIA_TRACE,ELYSIA_REQUEST_ID,ELYSIA_FORM_DATA,Cookie};
362
362
 
363
- //# debugId=41BD3A74607152FA64756E2164756E21
363
+ //# debugId=21096E330B84A2AB64756E2164756E21
364
364
  //# sourceMappingURL=index.js.map