balda 0.0.46 → 0.0.47

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/lib/index.cjs CHANGED
@@ -1081,7 +1081,7 @@ export const storage = new Storage(
1081
1081
  defaultProvider: "local",
1082
1082
  },
1083
1083
  );
1084
- `}[e]||""}};P([C({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],_e,"storageType"),P([C({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],_e,"outputPath");var Ho=[Me,Qe,Ce,je,he,Re,Oe,Q,ne,qe,Ee,ot,K,ke,_e,Ue,Ae,Te],Mt=class o{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static loggerPath="src/logger.ts";static logger=M.child({scope:"CommandRegistry"});static setLogger(e){o.logger=e.child({scope:"CommandRegistry"}),k.logger=e.child({scope:"Command"});}static async loadLogger(e){let t=e||o.loggerPath;try{let r=await import(S.join(H.getCwd(),t));r.logger&&o.setLogger(r.logger);}catch{o.logger.debug(`Could not load logger from ${t}, using default logger`);}}constructor(){this.commands=new Map,this.builtInCommands=new Set;}static getInstance(){return new o}static setCommandsPattern(e){this.commandsPattern=e;}getLogger(){return o.logger}setLogger(e){o.logger=e.child({scope:"CommandRegistry"}),k.logger=e.child({scope:"Command"});}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}getBuiltInCommands(){return Array.from(this.commands.values()).filter(e=>this.builtInCommands.has(e.commandName))}getUserDefinedCommands(){return Array.from(this.commands.values()).filter(e=>!this.builtInCommands.has(e.commandName))}isBuiltInCommand(e){return this.builtInCommands.has(e)}async loadCommands(e){o.logger.info(`Loading commands from ${e}`);let t=await y.glob(e,{cwd:H.getCwd()});if(t.some(r=>r.endsWith(".ts")))try{let{register:r}=await import('module');r("ts-node/esm",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));}catch{o.logger.error("Failed to register ts-node/esm, you need to install it in your project in order to use typescript in the cli\ntry running: `npm install -D ts-node`"),process.exit(1);}for(let r of t){let s=await import(r).then(i=>i.default?i.default:i).catch(i=>(o.logger.error(`Error loading command ${r}: ${i}`),null));s&&this.commands.set(s.commandName,s);}for(let r of Ho)this.commands.set(r.commandName,r),this.builtInCommands.add(r.commandName);}},Pe=Mt.getInstance();function br(o,e){let t={...Ne,...e?.defaultTtl!==void 0&&{defaultTtl:e.defaultTtl},...e?.compressionThreshold!==void 0&&{compressionThreshold:e.compressionThreshold},...e?.keyPrefix!==void 0&&{keyPrefix:e.keyPrefix},...e?.enableStats!==void 0&&{enableStats:e.enableStats},...e?.lockTimeout!==void 0&&{lockTimeout:e.lockTimeout},...e?.lockBehavior!==void 0&&{lockBehavior:e.lockBehavior}};return ar(o,t),async(r,s,i)=>{await i();}}var it=class{store=new Map;sets=new Map;locks=new Map;async get(e){let t=this.store.get(e);return t?Date.now()>t.expiresAt?(this.store.delete(e),null):t.value:null}async set(e,t,r){this.store.set(e,{value:t,expiresAt:Date.now()+r*1e3});}async del(e){return this.store.delete(e)||this.sets.delete(e)}async delMany(e){let t=0;for(let r of e)(this.store.delete(r)||this.sets.delete(r))&&t++;return t}async addToSet(e,t,r){let s=this.sets.get(e);(!s||Date.now()>s.expiresAt)&&(s={members:new Set,expiresAt:r?Date.now()+r*1e3:Number.MAX_SAFE_INTEGER},this.sets.set(e,s));for(let i of t)s.members.add(i);r&&(s.expiresAt=Date.now()+r*1e3);}async getSetMembers(e){let t=this.sets.get(e);return t?Date.now()>t.expiresAt?(this.sets.delete(e),[]):Array.from(t.members):[]}async acquireLock(e,t){let r=this.locks.get(e);return r&&Date.now()<r?false:(this.locks.set(e,Date.now()+t),true)}async releaseLock(e){this.locks.delete(e);}async*scan(e){let t=No(e),r=[];for(let s of this.store.keys())if(t.test(s)){let i=this.store.get(s);Date.now()<=i.expiresAt&&(r.push(s),r.length>=100&&(yield [...r],r.length=0));}r.length>0&&(yield r);}async disconnect(){this.store.clear(),this.sets.clear(),this.locks.clear();}};function No(o){let e=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp("^"+e+"$")}var nt=class{redis=null;options;constructor(e={}){this.options=e;}async getClient(){if(this.redis)return this.redis;let e;try{let{default:t}=await import('ioredis');e=t;}catch{throw new Error("ioredis is required for RedisCacheProvider. Install it with: npm install ioredis")}return this.options.url?this.redis=new e(this.options.url):this.redis=new e({host:this.options.host??"localhost",port:this.options.port??6379,password:this.options.password,db:this.options.db??0,keyPrefix:this.options.keyPrefix}),this.redis}async get(e){return (await this.getClient()).get(e)}async set(e,t,r){await(await this.getClient()).set(e,t,"EX",r);}async del(e){return await(await this.getClient()).del(e)>0}async delMany(e){return e.length===0?0:(await this.getClient()).del(...e)}async addToSet(e,t,r){if(t.length===0)return;let i=(await this.getClient()).pipeline();i.sadd(e,...t),r&&i.expire(e,r),await i.exec();}async getSetMembers(e){return (await this.getClient()).smembers(e)}async acquireLock(e,t){return await(await this.getClient()).set(e,"1","PX",t,"NX")==="OK"}async releaseLock(e){await(await this.getClient()).del(e);}async*scan(e){let t=await this.getClient(),r=this.options.keyPrefix||"",s=r+e,i="0";do{let[n,a]=await t.scan(i,"MATCH",s,"COUNT",100);i=n,a.length>0&&(yield r?a.map(c=>c.startsWith(r)?c.slice(r.length):c):a);}while(i!=="0")}async disconnect(){this.redis&&(await this.redis.quit(),this.redis=null);}};G();var ze=class{get(e){switch(E.type){case "node":case "bun":case "deno":return process.env[e];default:throw new Error(`Unsupported runtime: ${E.type}`)}}getEnvironment(){switch(E.type){case "node":case "deno":case "bun":return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>t!==void 0))}}};var Fo=new ze,N=o=>{let e=Fo.get("NODE_ENV")!=="production";return {code:o.name||"INTERNAL_ERROR",message:o.message,...e&&{stack:o.stack,cause:o.cause}}};var Ge=class extends R{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`);}};var z=class extends R{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`);}};var se=class{schemaOptions;apolloOptions;isEnabled;constructor(e){let t=this.initializeConfiguration(e);this.schemaOptions=t.schemaOptions,this.apolloOptions=t.apolloOptions,this.isEnabled=t.isEnabled;}getSchemaOptions(){return this.schemaOptions}getApolloOptions(){return this.apolloOptions}addTypeDef(e){if(typeof e=="function"){this.addTypeDef(e());return}if(Array.isArray(e)){this.addTypeDefArray(e);return}this.ensureTypeDefsArray(),this.schemaOptions.typeDefs.push(e);}addResolver(e,t){if(typeof e=="string"&&t){this.addResolverByType(e,t);return}this.addFullResolver(e);}initializeConfiguration(e){return e?this.createEnabledConfiguration(e):this.createDisabledConfiguration()}createDisabledConfiguration(){return {schemaOptions:{typeDefs:"",resolvers:{}},apolloOptions:{},isEnabled:false}}createEnabledConfiguration(e){return {schemaOptions:this.resolveSchemaOptions(e.schema),apolloOptions:this.resolveApolloOptions(e.apolloOptions),isEnabled:true}}resolveSchemaOptions(e){return e!==void 0?e:{typeDefs:"",resolvers:{}}}resolveApolloOptions(e){return e!==void 0?e:{}}addResolverByType(e,t){if(this.ensureResolversInitialized(),Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers.push({[e]:t});return}this.mergeResolverIntoObject(e,t);}ensureResolversInitialized(){!this.schemaOptions.resolvers&&(this.schemaOptions.resolvers={});}mergeResolverIntoObject(e,t){let r=this.schemaOptions.resolvers,s=r[e];if(s&&typeof s=="object"){r[e]={...s,...t};return}r[e]=t;}addFullResolver(e){if(this.ensureResolversInitialized(),Array.isArray(e)){this.addResolverArray(e);return}if(typeof e=="object"&&e!==null){this.addResolverObject(e);return}this.schemaOptions.resolvers=e;}addResolverArray(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,...e];return}this.schemaOptions.resolvers=[this.schemaOptions.resolvers,...e];}addResolverObject(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,e];return}this.schemaOptions.resolvers={...this.schemaOptions.resolvers,...e};}addTypeDefArray(e){for(let t of e)this.addTypeDef(t);}ensureTypeDefsArray(){if(Array.isArray(this.schemaOptions.typeDefs))return;if(this.schemaOptions.typeDefs!==void 0){this.schemaOptions.typeDefs=[this.schemaOptions.typeDefs];return}this.schemaOptions.typeDefs=[];}};var fe=async(o,e,t,r)=>{let s=o.length;if(s===0){let a=await e(t,r);return a&&r.send(a),r}let i=0,n=async()=>{if(i>=s){let d=await e(t,r);return d&&r.send(d),r}let a=i++,c=o[a];await c(t,r,n);};return await n(),r},Io=new Set(["post","put","patch"]),ae=o=>o?Io.has(o.toLowerCase()):true,qt=async(o,e,t,r,s)=>{try{let{HeaderMap:i}=await import('@apollo/server'),n=new i;e.headers.forEach((u,f)=>{n.set(f,u);});let c=(e.headers.get("content-type")??"").includes("application/json"),d="";if(t!=="GET"){let u=await e.text();d=c&&u?JSON.parse(u):u;}let p={method:t.toUpperCase(),headers:n,body:d,search:r?`?${r}`:""},l=await o.executeHTTPGraphQLRequest({httpGraphQLRequest:p,context:async()=>s}),h={};for(let[u,f]of l.headers)h[u]=f;if(l.body.kind==="complete")return new globalThis.Response(l.body.string,{status:l.status??200,headers:h});let m=new ReadableStream({async start(u){if(l.body.kind==="chunked")for await(let f of l.body.asyncIterator)u.enqueue(new TextEncoder().encode(f));u.close();}});return new globalThis.Response(m,{status:l.status??200,headers:h})}catch{return new globalThis.Response(JSON.stringify({errors:[{message:"Internal server error"}]}),{status:500,headers:{"Content-Type":"application/json"}})}},fs=async(o,e,t,r,s,i,n)=>{try{let{HeaderMap:a}=await import('@apollo/server'),c=new a;for(let[f,g]of Object.entries(e))g!==void 0&&c.set(f,Array.isArray(g)?g.join(", "):g);let l=(c.get("content-type")??"").includes("application/json")&&r?JSON.parse(r):r,h={method:t?.toUpperCase()??"POST",headers:c,body:l,search:s?`?${s}`:""},m=await o.executeHTTPGraphQLRequest({httpGraphQLRequest:h,context:async()=>i}),u=m.status??200;m.body.kind==="complete"?await n(m.headers,u,m.body.string):await n(m.headers,u,m.body.asyncIterator);}catch{await n(new Map([["Content-Type","application/json"]]),500,JSON.stringify({errors:[{message:"Internal server error"}]}));}},ge=o=>{let e=null,t=false,r=async()=>{for(;t;)await new Promise(i=>setTimeout(i,10));},s=async()=>{try{let{ApolloServer:i}=await import('@apollo/server'),{makeExecutableSchema:n}=await import('@graphql-tools/schema'),a=o.getSchemaOptions(),c=o.getApolloOptions(),d=n({typeDefs:a.typeDefs,resolvers:a.resolvers}),p=new i({schema:d,...c});return await p.start(),{server:p,url:"/graphql"}}catch(i){throw i instanceof Error&&(i.message.includes("Cannot find module")||i.message.includes("Cannot find package"))?new Error("GraphQL is enabled but '@apollo/server' is not installed. Install it with: npm install @apollo/server @graphql-tools/schema graphql"):i}};return async()=>{if(!o.isEnabled)return null;if(e!==null)return e;if(t)return await r(),e;t=true;try{return e=s(),await e}catch(c){throw e=null,c}finally{t=false;}}};var oe=class o{static fromRequest(e){let t=Object.assign(new o,{url:e.url,method:e.method,headers:e.headers,signal:e.signal,referrer:e.referrer,referrerPolicy:e.referrerPolicy,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,integrity:e.integrity,keepalive:e.keepalive});return t.#t=e,t}toWebApi(){if(this.#t)return this.#t;let e=this.method==="POST"||this.method==="PUT"||this.method==="PATCH";if(this.#s&&e){let t=stream.Readable.toWeb(this.#s);return this.#t=new globalThis.Request(this.url,{method:this.method,body:t,headers:this.headers,signal:this.signal,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive}),this.#t}return new globalThis.Request(this.url,{method:this.method,...e&&this.body?{body:this.body,duplex:"half"}:{},headers:this.headers,signal:this.signal,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive})}static toJSONSchemaWithPrefix(e){return $.isZodSchema(e)?{jsonSchema:$.toJSONSchema(e),prefix:"zod_schema"}:F.isTypeBoxSchema(e)?{jsonSchema:e,prefix:"typebox_schema"}:typeof e=="object"&&e!==null?{jsonSchema:e,prefix:"json_schema"}:{jsonSchema:{type:typeof e},prefix:`primitive_${JSON.stringify(e)}`}}static getOrCompileSchema(e){let{jsonSchema:t,prefix:r}=this.toJSONSchemaWithPrefix(e);return A.storeJsonSchema(t,r),A.getOrCompileValidator(t,r)}static compileAndValidate(e,t,r){let s=this.getOrCompileSchema(e);return Rt(s,t,r)}#t;#s;url="";method="GET";headers=new Headers;signal;referrer;referrerPolicy;mode;credentials;cache;redirect;integrity;keepalive;body=void 0;bodyUsed=false;ctx={};file=e=>this.files.find(t=>t.formName===e)??null;cookies={};cookie=e=>this.cookies[e];timeout;session=void 0;saveSession=async()=>{};destroySession=async()=>{};ip;files=[];params={};#e;#r;#i=false;get query(){if(this.#i)return this.#e;if(!this.#r||this.#r==="")this.#e={};else if(this.#r.length<50&&!this.#r.includes("&")){let e=this.#r.indexOf("=");if(e===-1)this.#e={[this.#r]:""};else {let t=this.#r.slice(0,e),r=decodeURIComponent(this.#r.slice(e+1));this.#e={[t]:r};}}else this.#e=Object.fromEntries(new URLSearchParams(this.#r));return this.#i=true,this.#e}set query(e){this.#e=e,this.#i=true;}setQueryString(e){this.#r=e,this.#i=false,this.#e=void 0;}#o;get id(){return this.#o||(this.#o=ee.randomUUID()),this.#o}set id(e){this.#o=e;}validate(e,t=false){return o.compileAndValidate(e,this.body||{},t)}validateQuery(e,t=false){return o.compileAndValidate(e,this.query||{},t)}validateAll(e,t=false){return o.compileAndValidate(e,{...this.body??{},...this.query??{}},t)}setNodeRequest(e){this.#s=e;}};G();var wr=class{file(e,t){switch(E.type){case "bun":case "node":return st__default.default.readFileSync(e,t);case "deno":return Deno.readFileSync(e);default:throw new Error("Unsupported runtime")}}},Et=new wr;var gs=new Map([[".html","text/html"],[".htm","text/html"],[".css","text/css"],[".js","application/javascript"],[".mjs","application/javascript"],[".cjs","application/javascript"],[".ts","application/typescript"],[".jsx","text/jsx"],[".tsx","text/tsx"],[".json","application/json"],[".xml","application/xml"],[".yaml","application/yaml"],[".yml","application/yaml"],[".csv","text/csv"],[".txt","text/plain"],[".md","text/markdown"],[".markdown","text/markdown"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".gif","image/gif"],[".svg","image/svg+xml"],[".ico","image/x-icon"],[".webp","image/webp"],[".avif","image/avif"],[".bmp","image/bmp"],[".tiff","image/tiff"],[".tif","image/tiff"],[".heic","image/heic"],[".heif","image/heif"],[".mp4","video/mp4"],[".webm","video/webm"],[".avi","video/x-msvideo"],[".mov","video/quicktime"],[".mkv","video/x-matroska"],[".wmv","video/x-ms-wmv"],[".flv","video/x-flv"],[".m4v","video/x-m4v"],[".mpeg","video/mpeg"],[".mpg","video/mpeg"],[".3gp","video/3gpp"],[".mp3","audio/mpeg"],[".wav","audio/wav"],[".ogg","audio/ogg"],[".flac","audio/flac"],[".aac","audio/aac"],[".m4a","audio/mp4"],[".wma","audio/x-ms-wma"],[".opus","audio/opus"],[".mid","audio/midi"],[".midi","audio/midi"],[".woff","font/woff"],[".woff2","font/woff2"],[".ttf","font/ttf"],[".otf","font/otf"],[".eot","application/vnd.ms-fontobject"],[".pdf","application/pdf"],[".doc","application/msword"],[".docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],[".xls","application/vnd.ms-excel"],[".xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],[".ppt","application/vnd.ms-powerpoint"],[".pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],[".odt","application/vnd.oasis.opendocument.text"],[".ods","application/vnd.oasis.opendocument.spreadsheet"],[".odp","application/vnd.oasis.opendocument.presentation"],[".rtf","application/rtf"],[".epub","application/epub+zip"],[".zip","application/zip"],[".tar","application/x-tar"],[".gz","application/gzip"],[".gzip","application/gzip"],[".bz2","application/x-bzip2"],[".xz","application/x-xz"],[".rar","application/vnd.rar"],[".7z","application/x-7z-compressed"],[".wasm","application/wasm"],[".map","application/json"],[".webmanifest","application/manifest+json"],[".ics","text/calendar"],[".vcf","text/vcard"],[".sql","application/sql"],[".sh","application/x-sh"],[".bat","application/x-msdos-program"],[".exe","application/x-msdownload"],[".dll","application/x-msdownload"],[".bin","application/octet-stream"],[".iso","application/x-iso9660-image"],[".dmg","application/x-apple-diskimage"],[".apk","application/vnd.android.package-archive"],[".jar","application/java-archive"],[".swf","application/x-shockwave-flash"]]);var Sr=(o,e)=>{let{source:t,path:r}=o,s=r;return s.startsWith("/")||(s="/"+s),s!=="/"&&s.endsWith("/")&&(s=s.slice(0,-1)),_.addOrUpdate("GET",`${s}/*`,[],async(i,n)=>Uo(i,n,t),{},{service:"StaticFiles",...e}),async(i,n,a)=>a()};async function Uo(o,e,t){if(o.method!=="GET"&&o.method!=="HEAD")return e.status(405).json({...N(new Ge(o.url,o.method))});let r=o.params["*"]||"",s=S.join(t,r),i=S.resolve(H.getCwd(),s),n=S.resolve(H.getCwd(),t);if(!i.startsWith(n))return e.notFound({...N(new z(o.url,o.method))});try{if(!(await y.stat(i)).isFile)return e.notFound({...N(new z(o.url,o.method))})}catch(d){if(d.code==="ENOENT")return e.notFound({...N(new z(o.url,o.method))});throw d}let a=xr(S.extName(i));e.setHeader("Content-Type",a);let c=Et.file(i);e.raw(c);}function xr(o){return gs.get(o)||"application/octet-stream"}var D=class{static toWebResponse(e){let t=e.getBody();return e.headers["Content-Type"]?.toLowerCase()==="application/json"?typeof t=="string"?new globalThis.Response(t,{status:e.responseStatus,headers:e.headers}):globalThis.Response.json(t,{status:e.responseStatus,headers:e.headers}):new globalThis.Response(t,{status:e.responseStatus,headers:e.headers})}responseStatus;headers;body;#t;#s;#e;constructor(e=200){this.responseStatus=e,this.headers={};}setRouteResponseSchemas(e){this.#s=e,this.#e=A.getOrCreateResponseSerializers(e)??void 0;}setHeader(e,t){return this.headers[e]=t,this}status(e){return this.responseStatus=e,this}send(e){if(e==null)return this.text("");if(typeof e=="string")return this.text(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return this.raw(e);if(typeof Buffer<"u"&&e instanceof Buffer)return this.download(new Uint8Array(e));if(e instanceof ArrayBuffer||e instanceof Uint8Array)return this.download(new Uint8Array(e));if(typeof e=="object"&&e!==null)try{return this.json(e)}catch{return this.text(String(e))}if(typeof e=="symbol")return this.text(e.toString());this.body=e;}raw(e){this.body=e;}text(e){this.body=e,this.headers["Content-Type"]="text/plain";}json(e,t){if(this.body=e,this.headers["Content-Type"]="application/json",!t&&this.#e){let s=this.#e.get(this.responseStatus);if(s){this.#t=s;return}}let r=t??this.#s?.[this.responseStatus];if(r){let{jsonSchema:s,prefix:i}=this.getJsonSchemaWithPrefix(r);this.#t=A.getOrCreateSerializer(s,i)??void 0;}}html(e){this.body=e,this.headers["Content-Type"]="text/html";}xml(e){this.body=e,this.headers["Content-Type"]="application/xml";}download(e){this.body=e,this.headers["Content-Type"]="application/octet-stream";}file(e,t){let r=S.extName(e),s=xr(r);this.body=Et.file(e,t),this.headers["Content-Type"]=s;}ok(e){this.status(200).send(e);}created(e){this.status(201).send(e);}accepted(e){this.status(202).send(e);}noContent(){this.responseStatus=204,this.body="";}partialContent(e){this.status(206).send(e);}multipleChoices(e){this.status(300).setHeader("Location",e);}redirect(e){this.status(302).setHeader("Location",e);}movedPermanently(e){this.status(301).setHeader("Location",e);}found(e){this.status(302).setHeader("Location",e);}seeOther(e){this.status(303).setHeader("Location",e);}notModified(){this.responseStatus=304,this.body="";}temporaryRedirect(e){this.status(307).setHeader("Location",e);}permanentRedirect(e){this.status(308).setHeader("Location",e);}badRequest(e){this.status(400).send(e);}unauthorized(e){this.status(401).send(e);}forbidden(e){this.status(403).send(e);}notFound(e){this.status(404).send(e);}methodNotAllowed(e){this.status(405).send(e);}notAcceptable(e){this.status(406).send(e);}conflict(e){this.status(409).send(e);}gone(e){this.status(410).send(e);}payloadTooLarge(e){this.status(413).send(e);}unsupportedMediaType(e){this.status(415).send(e);}unprocessableEntity(e){this.status(422).send(e);}tooManyRequests(e){this.status(429).send(e);}internalServerError(e){this.status(500).send(e);}notImplemented(e){this.status(501).send(e);}badGateway(e){this.status(502).send(e);}serviceUnavailable(e){this.status(503).send(e);}gatewayTimeout(e){this.status(504).send(e);}httpVersionNotSupported(e){this.status(505).send(e);}stream(e,t){if(this.headers["Content-Type"]="text/event-stream",this.headers["Cache-Control"]="no-cache",this.headers.Connection="keep-alive",t?.customHeaders)for(let r in t.customHeaders)this.headers[r]=t.customHeaders[r];if(e instanceof ReadableStream){this.body=e;return}this.body=new ReadableStream({async start(r){for await(let s of e)r.enqueue(new TextEncoder().encode(s));r.close();}});}getBody(){if(this.#t&&typeof this.body=="object"&&this.body!==null)try{this.body=this.#t(this.body),this.#t=void 0;}catch(e){M.error({error:e,statusCode:this.responseStatus,contentType:this.headers["Content-Type"]},"Fast-json-stringify serialization failed, falling back to JSON.stringify"),this.#t=void 0;}return this.body}getJsonSchemaWithPrefix(e){return $.isZodSchema(e)?{jsonSchema:$.toJSONSchema(e),prefix:"fast_stringify_zod"}:F.isTypeBoxSchema(e)?{jsonSchema:e,prefix:"fast_stringify_typebox"}:typeof e=="object"&&e!==null?{jsonSchema:e,prefix:"fast_stringify_json"}:{jsonSchema:{type:typeof e},prefix:`fast_stringify_primitive_${JSON.stringify(e)}`}}};var de=class{constructor(e){this.response=e;}body(){let e=this.response.getBody();if(typeof e=="string"&&this.response.headers["Content-Type"]?.includes("json"))try{return JSON.parse(e)}catch{return e}return e}statusCode(){return this.response.responseStatus}headers(){return this.response.headers}assertStatus(e){if(this.response.responseStatus!==e)throw new Error(`Expected status ${e}, but got ${this.response.responseStatus}`);return this}assertHeader(e,t){if(this.response.headers[e]!==t)throw new Error(`Expected header ${e} to be ${t}, but got ${this.response.headers[e]}`);return this}assertHeaderExists(e){if(!(e in this.response.headers))throw new Error(`Expected header ${e} to exist, but it was not found`);return this}assertHeaderNotExists(e){if(e in this.response.headers)throw new Error(`Expected header ${e} to not exist, but it was found with value: ${this.response.headers[e]}`);return this}assertBodySubset(e){return this.assertSubset(this.body(),e,"body"),this}assertBodyDeepEqual(e){return this.assertDeepEqual(this.body(),e,"body"),this}assertBodyNotSubset(e){return this.assertNotSubset(this.body(),e,"body"),this}assertBodyNotDeepEqual(e){return this.assertNotDeepEqual(this.body(),e,"body"),this}assertCustom(e){return e(this.response),this}assertSubset(e,t,r){for(let s in t){let i=r===""?s:`${r}.${s}`,n=e[s],a=t[s];if(!(s in e))throw new Error(`Expected ${r} to have key ${s}, but it was not found`);if(this.isObject(a)&&this.isObject(n))this.assertSubset(n,a,i);else if(Array.isArray(a)&&Array.isArray(n))this.assertArraySubset(n,a,i);else if(n!==a)throw new Error(`Expected ${i} to be ${a}, but got ${n}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let s=Object.keys(e),i=Object.keys(t);if(s.length!==i.length)throw new Error(`Expected ${r} to have ${i.length} keys, but got ${s.length}`);for(let n of i){let a=r==="body"?n:`${r}.${n}`;this.assertDeepEqual(e[n],t[n],a);}}else if(Array.isArray(e)&&Array.isArray(t))this.assertArrayDeepEqual(e,t,r);else if(e!==t)throw new Error(`Expected ${r} to be ${t}, but got ${e}`)}assertNotSubset(e,t,r){try{throw this.assertSubset(e,t,r),new Error(`Expected ${r} to NOT contain the subset, but it does`)}catch(s){if(s instanceof Error&&s.message.includes("Expected"))return;throw s}}assertNotDeepEqual(e,t,r){try{throw this.assertDeepEqual(e,t,r),new Error(`Expected ${r} to NOT be deeply equal, but it is`)}catch(s){if(s instanceof Error&&s.message.includes("Expected"))return;throw s}}assertArraySubset(e,t,r){if(t.length>e.length)throw new Error(`Expected ${r} to have at least ${t.length} elements, but got ${e.length}`);for(let s=0;s<t.length;s++){let i=`${r}[${s}]`,n=e[s],a=t[s];if(this.isObject(a)&&this.isObject(n))this.assertSubset(n,a,i);else if(Array.isArray(a)&&Array.isArray(n))this.assertArraySubset(n,a,i);else if(n!==a)throw new Error(`Expected ${i} to be ${a}, but got ${n}`)}}assertArrayDeepEqual(e,t,r){if(e.length!==t.length)throw new Error(`Expected ${r} to have ${t.length} elements, but got ${e.length}`);for(let s=0;s<t.length;s++){let i=`${r}[${s}]`;this.assertDeepEqual(e[s],t[s],i);}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var At=class{server;logger=M.child({scope:"MockServer"});ensureGraphQLHandler;constructor(e){this.server=e,this.ensureGraphQLHandler=ge(this.server.graphql);}async request(e,t,r={}){let{headers:s={},query:i={},cookies:n={},ip:a}=r;this.validateOptions(r);let c=this.server.graphql.isEnabled,d=t.startsWith("/graphql");if(c&&d)return this.handleGraphQLRequest(e,t,r);let p=_.find(e.toUpperCase(),t);if(!p){let g=new D(404);return g.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new de(g)}let l,h="application/json";if(r.body!==void 0&&(typeof r.body=="object"&&!(r.body instanceof Uint8Array)&&!(r.body instanceof ArrayBuffer)?l=JSON.stringify(r.body):l=r.body),r.formData){let g=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;h=`multipart/form-data; boundary=${g}`,l=await this.formDataToMultipart(r.formData,g);}r.urlencoded&&(h="application/x-www-form-urlencoded",l=new URLSearchParams(r.urlencoded).toString());let m=new URL(`http://${this.server.host}:${this.server.port}${t}`);m.search=new URLSearchParams(i).toString();let u=new globalThis.Request(m.toString(),{method:e.toUpperCase(),body:ae(e)?l:void 0,headers:{"content-type":h,...s}}),f=oe.fromRequest(u);f.query={...Object.fromEntries(m.searchParams.entries()),...i},f.params=p.params,f.cookies=n,f.ip=a;try{let g=await fe(p.middleware,p.handler,f,new D);return new de(g)}catch(g){this.logger.error({error:g},`Error processing mock request ${e} ${t}:`);let v=new D(500);return v.json({error:"Internal server error",message:g instanceof Error?g.message:String(g)}),new de(v)}}async get(e,t){return this.request("GET",e,t)}async post(e,t){return this.request("POST",e,t)}async put(e,t){return this.request("PUT",e,t)}async patch(e,t){return this.request("PATCH",e,t)}async delete(e,t){return this.request("DELETE",e,t)}async formDataToMultipart(e,t){let r=new TextEncoder,s=[];for(let[c,d]of e.entries()){s.push(r.encode(`--${t}\r
1084
+ `}[e]||""}};P([C({description:"Storage provider type (s3, azure, local)",type:"string",aliases:["t"],name:"type",required:true})],_e,"storageType"),P([C({description:"Output directory for storage setup",type:"string",aliases:["o"],name:"output",required:false,defaultValue:"src/storage/"})],_e,"outputPath");var Ho=[Me,Qe,Ce,je,he,Re,Oe,Q,ne,qe,Ee,ot,K,ke,_e,Ue,Ae,Te],Mt=class o{commands;builtInCommands;static commandsPattern="src/commands/**/*.{ts,js}";static loggerPath="src/logger.ts";static logger=M.child({scope:"CommandRegistry"});static setLogger(e){o.logger=e.child({scope:"CommandRegistry"}),k.logger=e.child({scope:"Command"});}static async loadLogger(e){let t=e||o.loggerPath;try{let r=await import(S.join(H.getCwd(),t));r.logger&&o.setLogger(r.logger);}catch{o.logger.debug(`Could not load logger from ${t}, using default logger`);}}constructor(){this.commands=new Map,this.builtInCommands=new Set;}static getInstance(){return new o}static setCommandsPattern(e){this.commandsPattern=e;}getLogger(){return o.logger}setLogger(e){o.logger=e.child({scope:"CommandRegistry"}),k.logger=e.child({scope:"Command"});}getCommand(e){return this.commands.get(e)??null}getCommands(){return Array.from(this.commands.values())}getBuiltInCommands(){return Array.from(this.commands.values()).filter(e=>this.builtInCommands.has(e.commandName))}getUserDefinedCommands(){return Array.from(this.commands.values()).filter(e=>!this.builtInCommands.has(e.commandName))}isBuiltInCommand(e){return this.builtInCommands.has(e)}async loadCommands(e){o.logger.info(`Loading commands from ${e}`);let t=await y.glob(e,{cwd:H.getCwd()});if(t.some(r=>r.endsWith(".ts")))try{let{register:r}=await import('module');r("ts-node/esm",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));}catch{o.logger.error("Failed to register ts-node/esm, you need to install it in your project in order to use typescript in the cli\ntry running: `npm install -D ts-node`"),process.exit(1);}for(let r of t){let s=await import(r).then(i=>i.default?i.default:i).catch(i=>(o.logger.error(`Error loading command ${r}: ${i}`),null));s&&this.commands.set(s.commandName,s);}for(let r of Ho)this.commands.set(r.commandName,r),this.builtInCommands.add(r.commandName);}},Pe=Mt.getInstance();function br(o,e){let t={...Ne,...e?.defaultTtl!==void 0&&{defaultTtl:e.defaultTtl},...e?.compressionThreshold!==void 0&&{compressionThreshold:e.compressionThreshold},...e?.keyPrefix!==void 0&&{keyPrefix:e.keyPrefix},...e?.enableStats!==void 0&&{enableStats:e.enableStats},...e?.lockTimeout!==void 0&&{lockTimeout:e.lockTimeout},...e?.lockBehavior!==void 0&&{lockBehavior:e.lockBehavior}};return ar(o,t),async(r,s,i)=>{await i();}}var it=class{store=new Map;sets=new Map;locks=new Map;async get(e){let t=this.store.get(e);return t?Date.now()>t.expiresAt?(this.store.delete(e),null):t.value:null}async set(e,t,r){this.store.set(e,{value:t,expiresAt:Date.now()+r*1e3});}async del(e){return this.store.delete(e)||this.sets.delete(e)}async delMany(e){let t=0;for(let r of e)(this.store.delete(r)||this.sets.delete(r))&&t++;return t}async addToSet(e,t,r){let s=this.sets.get(e);(!s||Date.now()>s.expiresAt)&&(s={members:new Set,expiresAt:r?Date.now()+r*1e3:Number.MAX_SAFE_INTEGER},this.sets.set(e,s));for(let i of t)s.members.add(i);r&&(s.expiresAt=Date.now()+r*1e3);}async getSetMembers(e){let t=this.sets.get(e);return t?Date.now()>t.expiresAt?(this.sets.delete(e),[]):Array.from(t.members):[]}async acquireLock(e,t){let r=this.locks.get(e);return r&&Date.now()<r?false:(this.locks.set(e,Date.now()+t),true)}async releaseLock(e){this.locks.delete(e);}async*scan(e){let t=No(e),r=[];for(let s of this.store.keys())if(t.test(s)){let i=this.store.get(s);Date.now()<=i.expiresAt&&(r.push(s),r.length>=100&&(yield [...r],r.length=0));}r.length>0&&(yield r);}async disconnect(){this.store.clear(),this.sets.clear(),this.locks.clear();}};function No(o){let e=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp("^"+e+"$")}var nt=class{redis=null;options;constructor(e={}){this.options=e;}async getClient(){if(this.redis)return this.redis;let e;try{let{default:t}=await import('ioredis');e=t;}catch{throw new Error("ioredis is required for RedisCacheProvider. Install it with: npm install ioredis")}return this.options.url?this.redis=new e(this.options.url):this.redis=new e({host:this.options.host??"localhost",port:this.options.port??6379,password:this.options.password,db:this.options.db??0,keyPrefix:this.options.keyPrefix}),this.redis}async get(e){return (await this.getClient()).get(e)}async set(e,t,r){await(await this.getClient()).set(e,t,"EX",r);}async del(e){return await(await this.getClient()).del(e)>0}async delMany(e){return e.length===0?0:(await this.getClient()).del(...e)}async addToSet(e,t,r){if(t.length===0)return;let i=(await this.getClient()).pipeline();i.sadd(e,...t),r&&i.expire(e,r),await i.exec();}async getSetMembers(e){return (await this.getClient()).smembers(e)}async acquireLock(e,t){return await(await this.getClient()).set(e,"1","PX",t,"NX")==="OK"}async releaseLock(e){await(await this.getClient()).del(e);}async*scan(e){let t=await this.getClient(),r=this.options.keyPrefix||"",s=r+e,i="0";do{let[n,a]=await t.scan(i,"MATCH",s,"COUNT",100);i=n,a.length>0&&(yield r?a.map(c=>c.startsWith(r)?c.slice(r.length):c):a);}while(i!=="0")}async disconnect(){this.redis&&(await this.redis.quit(),this.redis=null);}};G();var ze=class{get(e){switch(E.type){case "node":case "bun":case "deno":return process.env[e];default:throw new Error(`Unsupported runtime: ${E.type}`)}}getEnvironment(){switch(E.type){case "node":case "deno":case "bun":return Object.fromEntries(Object.entries(process.env).filter(([e,t])=>t!==void 0))}}};var Fo=new ze,N=o=>{let e=Fo.get("NODE_ENV")!=="production";return {code:o.name||"INTERNAL_ERROR",message:o.message,...e&&{stack:o.stack,cause:o.cause}}};var Ge=class extends R{constructor(e,t){super(`METHOD_NOT_ALLOWED: Cannot ${t} ${e}`);}};var z=class extends R{constructor(e,t){super(`ROUTE_NOT_FOUND: Cannot ${t} ${e}`);}};var se=class{schemaOptions;apolloOptions;isEnabled;constructor(e){let t=this.initializeConfiguration(e);this.schemaOptions=t.schemaOptions,this.apolloOptions=t.apolloOptions,this.isEnabled=t.isEnabled;}getSchemaOptions(){return this.schemaOptions}getApolloOptions(){return this.apolloOptions}addTypeDef(e){if(typeof e=="function"){this.addTypeDef(e());return}if(Array.isArray(e)){this.addTypeDefArray(e);return}this.ensureTypeDefsArray(),this.schemaOptions.typeDefs.push(e);}addResolver(e,t){if(typeof e=="string"&&t){this.addResolverByType(e,t);return}this.addFullResolver(e);}initializeConfiguration(e){return e?this.createEnabledConfiguration(e):this.createDisabledConfiguration()}createDisabledConfiguration(){return {schemaOptions:{typeDefs:"",resolvers:{}},apolloOptions:{},isEnabled:false}}createEnabledConfiguration(e){return {schemaOptions:this.resolveSchemaOptions(e.schema),apolloOptions:this.resolveApolloOptions(e.apolloOptions),isEnabled:true}}resolveSchemaOptions(e){return e!==void 0?e:{typeDefs:"",resolvers:{}}}resolveApolloOptions(e){return e!==void 0?e:{}}addResolverByType(e,t){if(this.ensureResolversInitialized(),Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers.push({[e]:t});return}this.mergeResolverIntoObject(e,t);}ensureResolversInitialized(){!this.schemaOptions.resolvers&&(this.schemaOptions.resolvers={});}mergeResolverIntoObject(e,t){let r=this.schemaOptions.resolvers,s=r[e];if(s&&typeof s=="object"){r[e]={...s,...t};return}r[e]=t;}addFullResolver(e){if(this.ensureResolversInitialized(),Array.isArray(e)){this.addResolverArray(e);return}if(typeof e=="object"&&e!==null){this.addResolverObject(e);return}this.schemaOptions.resolvers=e;}addResolverArray(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,...e];return}this.schemaOptions.resolvers=[this.schemaOptions.resolvers,...e];}addResolverObject(e){if(Array.isArray(this.schemaOptions.resolvers)){this.schemaOptions.resolvers=[...this.schemaOptions.resolvers,e];return}this.schemaOptions.resolvers={...this.schemaOptions.resolvers,...e};}addTypeDefArray(e){for(let t of e)this.addTypeDef(t);}ensureTypeDefsArray(){if(Array.isArray(this.schemaOptions.typeDefs))return;if(this.schemaOptions.typeDefs!==void 0){this.schemaOptions.typeDefs=[this.schemaOptions.typeDefs];return}this.schemaOptions.typeDefs=[];}};var fe=async(o,e,t,r)=>{let s=o.length;if(s===0){let a=await e(t,r);return a&&r.send(a),r}let i=0,n=async()=>{if(i>=s){let d=await e(t,r);return d&&r.send(d),r}let a=i++,c=o[a];await c(t,r,n);};return await n(),r},Io=new Set(["post","put","patch"]),ae=o=>o?Io.has(o.toLowerCase()):true,qt=async(o,e,t,r,s)=>{try{let{HeaderMap:i}=await import('@apollo/server'),n=new i;e.headers.forEach((u,f)=>{n.set(f,u);});let c=(e.headers.get("content-type")??"").includes("application/json"),d="";if(t!=="GET"){let u=await e.text();d=c&&u?JSON.parse(u):u;}let p={method:t.toUpperCase(),headers:n,body:d,search:r?`?${r}`:""},l=await o.executeHTTPGraphQLRequest({httpGraphQLRequest:p,context:async()=>s}),h={};for(let[u,f]of l.headers)h[u]=f;if(l.body.kind==="complete")return new globalThis.Response(l.body.string,{status:l.status??200,headers:h});let m=new ReadableStream({async start(u){if(l.body.kind==="chunked")for await(let f of l.body.asyncIterator)u.enqueue(new TextEncoder().encode(f));u.close();}});return new globalThis.Response(m,{status:l.status??200,headers:h})}catch{return new globalThis.Response(JSON.stringify({errors:[{message:"Internal server error"}]}),{status:500,headers:{"Content-Type":"application/json"}})}},fs=async(o,e,t,r,s,i,n)=>{try{let{HeaderMap:a}=await import('@apollo/server'),c=new a;for(let[f,g]of Object.entries(e))g!==void 0&&c.set(f,Array.isArray(g)?g.join(", "):g);let l=(c.get("content-type")??"").includes("application/json")&&r?JSON.parse(r):r,h={method:t?.toUpperCase()??"POST",headers:c,body:l,search:s?`?${s}`:""},m=await o.executeHTTPGraphQLRequest({httpGraphQLRequest:h,context:async()=>i}),u=m.status??200;m.body.kind==="complete"?await n(m.headers,u,m.body.string):await n(m.headers,u,m.body.asyncIterator);}catch{await n(new Map([["Content-Type","application/json"]]),500,JSON.stringify({errors:[{message:"Internal server error"}]}));}},ge=o=>{let e=null,t=false,r=async()=>{for(;t;)await new Promise(i=>setTimeout(i,10));},s=async()=>{try{let{ApolloServer:i}=await import('@apollo/server'),{makeExecutableSchema:n}=await import('@graphql-tools/schema'),a=o.getSchemaOptions(),c=o.getApolloOptions(),d=n({typeDefs:a.typeDefs,resolvers:a.resolvers}),p=new i({schema:d,...c});return await p.start(),{server:p,url:"/graphql"}}catch(i){throw i instanceof Error&&(i.message.includes("Cannot find module")||i.message.includes("Cannot find package"))?new Error("GraphQL is enabled but '@apollo/server' is not installed. Install it with: npm install @apollo/server @graphql-tools/schema graphql"):i}};return async()=>{if(!o.isEnabled)return null;if(e!==null)return e;if(t)return await r(),e;t=true;try{return e=s(),await e}catch(c){throw e=null,c}finally{t=false;}}};var oe=class o{static fromRequest(e){let t=Object.assign(new o,{url:e.url,method:e.method,headers:e.headers,signal:e.signal,referrer:e.referrer,referrerPolicy:e.referrerPolicy,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,integrity:e.integrity,keepalive:e.keepalive});return t.#t=e,t}toWebApi(){if(this.#t)return this.#t;let e=this.method==="POST"||this.method==="PUT"||this.method==="PATCH";if(this.#s&&e){let t=stream.Readable.toWeb(this.#s);return this.#t=new globalThis.Request(this.url,{method:this.method,body:t,headers:this.headers,signal:this.signal,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive,duplex:"half"}),this.#t}return new globalThis.Request(this.url,{method:this.method,...e&&this.body?{body:this.body,duplex:"half"}:{},headers:this.headers,signal:this.signal,referrer:this.referrer,referrerPolicy:this.referrerPolicy,mode:this.mode,credentials:this.credentials,cache:this.cache,redirect:this.redirect,integrity:this.integrity,keepalive:this.keepalive})}static toJSONSchemaWithPrefix(e){return $.isZodSchema(e)?{jsonSchema:$.toJSONSchema(e),prefix:"zod_schema"}:F.isTypeBoxSchema(e)?{jsonSchema:e,prefix:"typebox_schema"}:typeof e=="object"&&e!==null?{jsonSchema:e,prefix:"json_schema"}:{jsonSchema:{type:typeof e},prefix:`primitive_${JSON.stringify(e)}`}}static getOrCompileSchema(e){let{jsonSchema:t,prefix:r}=this.toJSONSchemaWithPrefix(e);return A.storeJsonSchema(t,r),A.getOrCompileValidator(t,r)}static compileAndValidate(e,t,r){let s=this.getOrCompileSchema(e);return Rt(s,t,r)}#t;#s;url="";method="GET";headers=new Headers;signal;referrer;referrerPolicy;mode;credentials;cache;redirect;integrity;keepalive;body=void 0;bodyUsed=false;ctx={};file=e=>this.files.find(t=>t.formName===e)??null;cookies={};cookie=e=>this.cookies[e];timeout;session=void 0;saveSession=async()=>{};destroySession=async()=>{};ip;files=[];params={};#e;#r;#i=false;get query(){if(this.#i)return this.#e;if(!this.#r||this.#r==="")this.#e={};else if(this.#r.length<50&&!this.#r.includes("&")){let e=this.#r.indexOf("=");if(e===-1)this.#e={[this.#r]:""};else {let t=this.#r.slice(0,e),r=decodeURIComponent(this.#r.slice(e+1));this.#e={[t]:r};}}else this.#e=Object.fromEntries(new URLSearchParams(this.#r));return this.#i=true,this.#e}set query(e){this.#e=e,this.#i=true;}setQueryString(e){this.#r=e,this.#i=false,this.#e=void 0;}#o;get id(){return this.#o||(this.#o=ee.randomUUID()),this.#o}set id(e){this.#o=e;}validate(e,t=false){return o.compileAndValidate(e,this.body||{},t)}validateQuery(e,t=false){return o.compileAndValidate(e,this.query||{},t)}validateAll(e,t=false){return o.compileAndValidate(e,{...this.body??{},...this.query??{}},t)}setNodeRequest(e){this.#s=e;}};G();var wr=class{file(e,t){switch(E.type){case "bun":case "node":return st__default.default.readFileSync(e,t);case "deno":return Deno.readFileSync(e);default:throw new Error("Unsupported runtime")}}},Et=new wr;var gs=new Map([[".html","text/html"],[".htm","text/html"],[".css","text/css"],[".js","application/javascript"],[".mjs","application/javascript"],[".cjs","application/javascript"],[".ts","application/typescript"],[".jsx","text/jsx"],[".tsx","text/tsx"],[".json","application/json"],[".xml","application/xml"],[".yaml","application/yaml"],[".yml","application/yaml"],[".csv","text/csv"],[".txt","text/plain"],[".md","text/markdown"],[".markdown","text/markdown"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".gif","image/gif"],[".svg","image/svg+xml"],[".ico","image/x-icon"],[".webp","image/webp"],[".avif","image/avif"],[".bmp","image/bmp"],[".tiff","image/tiff"],[".tif","image/tiff"],[".heic","image/heic"],[".heif","image/heif"],[".mp4","video/mp4"],[".webm","video/webm"],[".avi","video/x-msvideo"],[".mov","video/quicktime"],[".mkv","video/x-matroska"],[".wmv","video/x-ms-wmv"],[".flv","video/x-flv"],[".m4v","video/x-m4v"],[".mpeg","video/mpeg"],[".mpg","video/mpeg"],[".3gp","video/3gpp"],[".mp3","audio/mpeg"],[".wav","audio/wav"],[".ogg","audio/ogg"],[".flac","audio/flac"],[".aac","audio/aac"],[".m4a","audio/mp4"],[".wma","audio/x-ms-wma"],[".opus","audio/opus"],[".mid","audio/midi"],[".midi","audio/midi"],[".woff","font/woff"],[".woff2","font/woff2"],[".ttf","font/ttf"],[".otf","font/otf"],[".eot","application/vnd.ms-fontobject"],[".pdf","application/pdf"],[".doc","application/msword"],[".docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],[".xls","application/vnd.ms-excel"],[".xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],[".ppt","application/vnd.ms-powerpoint"],[".pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"],[".odt","application/vnd.oasis.opendocument.text"],[".ods","application/vnd.oasis.opendocument.spreadsheet"],[".odp","application/vnd.oasis.opendocument.presentation"],[".rtf","application/rtf"],[".epub","application/epub+zip"],[".zip","application/zip"],[".tar","application/x-tar"],[".gz","application/gzip"],[".gzip","application/gzip"],[".bz2","application/x-bzip2"],[".xz","application/x-xz"],[".rar","application/vnd.rar"],[".7z","application/x-7z-compressed"],[".wasm","application/wasm"],[".map","application/json"],[".webmanifest","application/manifest+json"],[".ics","text/calendar"],[".vcf","text/vcard"],[".sql","application/sql"],[".sh","application/x-sh"],[".bat","application/x-msdos-program"],[".exe","application/x-msdownload"],[".dll","application/x-msdownload"],[".bin","application/octet-stream"],[".iso","application/x-iso9660-image"],[".dmg","application/x-apple-diskimage"],[".apk","application/vnd.android.package-archive"],[".jar","application/java-archive"],[".swf","application/x-shockwave-flash"]]);var Sr=(o,e)=>{let{source:t,path:r}=o,s=r;return s.startsWith("/")||(s="/"+s),s!=="/"&&s.endsWith("/")&&(s=s.slice(0,-1)),_.addOrUpdate("GET",`${s}/*`,[],async(i,n)=>Uo(i,n,t),{},{service:"StaticFiles",...e}),async(i,n,a)=>a()};async function Uo(o,e,t){if(o.method!=="GET"&&o.method!=="HEAD")return e.status(405).json({...N(new Ge(o.url,o.method))});let r=o.params["*"]||"",s=S.join(t,r),i=S.resolve(H.getCwd(),s),n=S.resolve(H.getCwd(),t);if(!i.startsWith(n))return e.notFound({...N(new z(o.url,o.method))});try{if(!(await y.stat(i)).isFile)return e.notFound({...N(new z(o.url,o.method))})}catch(d){if(d.code==="ENOENT")return e.notFound({...N(new z(o.url,o.method))});throw d}let a=xr(S.extName(i));e.setHeader("Content-Type",a);let c=Et.file(i);e.raw(c);}function xr(o){return gs.get(o)||"application/octet-stream"}var D=class{static toWebResponse(e){let t=e.getBody();return e.headers["Content-Type"]?.toLowerCase()==="application/json"?typeof t=="string"?new globalThis.Response(t,{status:e.responseStatus,headers:e.headers}):globalThis.Response.json(t,{status:e.responseStatus,headers:e.headers}):new globalThis.Response(t,{status:e.responseStatus,headers:e.headers})}responseStatus;headers;body;#t;#s;#e;constructor(e=200){this.responseStatus=e,this.headers={};}setRouteResponseSchemas(e){this.#s=e,this.#e=A.getOrCreateResponseSerializers(e)??void 0;}setHeader(e,t){return this.headers[e]=t,this}status(e){return this.responseStatus=e,this}send(e){if(e==null)return this.text("");if(typeof e=="string")return this.text(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return this.raw(e);if(typeof Buffer<"u"&&e instanceof Buffer)return this.download(new Uint8Array(e));if(e instanceof ArrayBuffer||e instanceof Uint8Array)return this.download(new Uint8Array(e));if(typeof e=="object"&&e!==null)try{return this.json(e)}catch{return this.text(String(e))}if(typeof e=="symbol")return this.text(e.toString());this.body=e;}raw(e){this.body=e;}text(e){this.body=e,this.headers["Content-Type"]="text/plain";}json(e,t){if(this.body=e,this.headers["Content-Type"]="application/json",!t&&this.#e){let s=this.#e.get(this.responseStatus);if(s){this.#t=s;return}}let r=t??this.#s?.[this.responseStatus];if(r){let{jsonSchema:s,prefix:i}=this.getJsonSchemaWithPrefix(r);this.#t=A.getOrCreateSerializer(s,i)??void 0;}}html(e){this.body=e,this.headers["Content-Type"]="text/html";}xml(e){this.body=e,this.headers["Content-Type"]="application/xml";}download(e){this.body=e,this.headers["Content-Type"]="application/octet-stream";}file(e,t){let r=S.extName(e),s=xr(r);this.body=Et.file(e,t),this.headers["Content-Type"]=s;}ok(e){this.status(200).send(e);}created(e){this.status(201).send(e);}accepted(e){this.status(202).send(e);}noContent(){this.responseStatus=204,this.body="";}partialContent(e){this.status(206).send(e);}multipleChoices(e){this.status(300).setHeader("Location",e);}redirect(e){this.status(302).setHeader("Location",e);}movedPermanently(e){this.status(301).setHeader("Location",e);}found(e){this.status(302).setHeader("Location",e);}seeOther(e){this.status(303).setHeader("Location",e);}notModified(){this.responseStatus=304,this.body="";}temporaryRedirect(e){this.status(307).setHeader("Location",e);}permanentRedirect(e){this.status(308).setHeader("Location",e);}badRequest(e){this.status(400).send(e);}unauthorized(e){this.status(401).send(e);}forbidden(e){this.status(403).send(e);}notFound(e){this.status(404).send(e);}methodNotAllowed(e){this.status(405).send(e);}notAcceptable(e){this.status(406).send(e);}conflict(e){this.status(409).send(e);}gone(e){this.status(410).send(e);}payloadTooLarge(e){this.status(413).send(e);}unsupportedMediaType(e){this.status(415).send(e);}unprocessableEntity(e){this.status(422).send(e);}tooManyRequests(e){this.status(429).send(e);}internalServerError(e){this.status(500).send(e);}notImplemented(e){this.status(501).send(e);}badGateway(e){this.status(502).send(e);}serviceUnavailable(e){this.status(503).send(e);}gatewayTimeout(e){this.status(504).send(e);}httpVersionNotSupported(e){this.status(505).send(e);}stream(e,t){if(this.headers["Content-Type"]="text/event-stream",this.headers["Cache-Control"]="no-cache",this.headers.Connection="keep-alive",t?.customHeaders)for(let r in t.customHeaders)this.headers[r]=t.customHeaders[r];if(e instanceof ReadableStream){this.body=e;return}this.body=new ReadableStream({async start(r){for await(let s of e)r.enqueue(new TextEncoder().encode(s));r.close();}});}getBody(){if(this.#t&&typeof this.body=="object"&&this.body!==null)try{this.body=this.#t(this.body),this.#t=void 0;}catch(e){M.error({error:e,statusCode:this.responseStatus,contentType:this.headers["Content-Type"]},"Fast-json-stringify serialization failed, falling back to JSON.stringify"),this.#t=void 0;}return this.body}getJsonSchemaWithPrefix(e){return $.isZodSchema(e)?{jsonSchema:$.toJSONSchema(e),prefix:"fast_stringify_zod"}:F.isTypeBoxSchema(e)?{jsonSchema:e,prefix:"fast_stringify_typebox"}:typeof e=="object"&&e!==null?{jsonSchema:e,prefix:"fast_stringify_json"}:{jsonSchema:{type:typeof e},prefix:`fast_stringify_primitive_${JSON.stringify(e)}`}}};var de=class{constructor(e){this.response=e;}body(){let e=this.response.getBody();if(typeof e=="string"&&this.response.headers["Content-Type"]?.includes("json"))try{return JSON.parse(e)}catch{return e}return e}statusCode(){return this.response.responseStatus}headers(){return this.response.headers}assertStatus(e){if(this.response.responseStatus!==e)throw new Error(`Expected status ${e}, but got ${this.response.responseStatus}`);return this}assertHeader(e,t){if(this.response.headers[e]!==t)throw new Error(`Expected header ${e} to be ${t}, but got ${this.response.headers[e]}`);return this}assertHeaderExists(e){if(!(e in this.response.headers))throw new Error(`Expected header ${e} to exist, but it was not found`);return this}assertHeaderNotExists(e){if(e in this.response.headers)throw new Error(`Expected header ${e} to not exist, but it was found with value: ${this.response.headers[e]}`);return this}assertBodySubset(e){return this.assertSubset(this.body(),e,"body"),this}assertBodyDeepEqual(e){return this.assertDeepEqual(this.body(),e,"body"),this}assertBodyNotSubset(e){return this.assertNotSubset(this.body(),e,"body"),this}assertBodyNotDeepEqual(e){return this.assertNotDeepEqual(this.body(),e,"body"),this}assertCustom(e){return e(this.response),this}assertSubset(e,t,r){for(let s in t){let i=r===""?s:`${r}.${s}`,n=e[s],a=t[s];if(!(s in e))throw new Error(`Expected ${r} to have key ${s}, but it was not found`);if(this.isObject(a)&&this.isObject(n))this.assertSubset(n,a,i);else if(Array.isArray(a)&&Array.isArray(n))this.assertArraySubset(n,a,i);else if(n!==a)throw new Error(`Expected ${i} to be ${a}, but got ${n}`)}}assertDeepEqual(e,t,r){if(this.isObject(e)&&this.isObject(t)){let s=Object.keys(e),i=Object.keys(t);if(s.length!==i.length)throw new Error(`Expected ${r} to have ${i.length} keys, but got ${s.length}`);for(let n of i){let a=r==="body"?n:`${r}.${n}`;this.assertDeepEqual(e[n],t[n],a);}}else if(Array.isArray(e)&&Array.isArray(t))this.assertArrayDeepEqual(e,t,r);else if(e!==t)throw new Error(`Expected ${r} to be ${t}, but got ${e}`)}assertNotSubset(e,t,r){try{throw this.assertSubset(e,t,r),new Error(`Expected ${r} to NOT contain the subset, but it does`)}catch(s){if(s instanceof Error&&s.message.includes("Expected"))return;throw s}}assertNotDeepEqual(e,t,r){try{throw this.assertDeepEqual(e,t,r),new Error(`Expected ${r} to NOT be deeply equal, but it is`)}catch(s){if(s instanceof Error&&s.message.includes("Expected"))return;throw s}}assertArraySubset(e,t,r){if(t.length>e.length)throw new Error(`Expected ${r} to have at least ${t.length} elements, but got ${e.length}`);for(let s=0;s<t.length;s++){let i=`${r}[${s}]`,n=e[s],a=t[s];if(this.isObject(a)&&this.isObject(n))this.assertSubset(n,a,i);else if(Array.isArray(a)&&Array.isArray(n))this.assertArraySubset(n,a,i);else if(n!==a)throw new Error(`Expected ${i} to be ${a}, but got ${n}`)}}assertArrayDeepEqual(e,t,r){if(e.length!==t.length)throw new Error(`Expected ${r} to have ${t.length} elements, but got ${e.length}`);for(let s=0;s<t.length;s++){let i=`${r}[${s}]`;this.assertDeepEqual(e[s],t[s],i);}}isObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}};var At=class{server;logger=M.child({scope:"MockServer"});ensureGraphQLHandler;constructor(e){this.server=e,this.ensureGraphQLHandler=ge(this.server.graphql);}async request(e,t,r={}){let{headers:s={},query:i={},cookies:n={},ip:a}=r;this.validateOptions(r);let c=this.server.graphql.isEnabled,d=t.startsWith("/graphql");if(c&&d)return this.handleGraphQLRequest(e,t,r);let p=_.find(e.toUpperCase(),t);if(!p){let g=new D(404);return g.json({caller:"MockServer",error:"Route not found",path:t,method:e}),new de(g)}let l,h="application/json";if(r.body!==void 0&&(typeof r.body=="object"&&!(r.body instanceof Uint8Array)&&!(r.body instanceof ArrayBuffer)?l=JSON.stringify(r.body):l=r.body),r.formData){let g=`----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;h=`multipart/form-data; boundary=${g}`,l=await this.formDataToMultipart(r.formData,g);}r.urlencoded&&(h="application/x-www-form-urlencoded",l=new URLSearchParams(r.urlencoded).toString());let m=new URL(`http://${this.server.host}:${this.server.port}${t}`);m.search=new URLSearchParams(i).toString();let u=new globalThis.Request(m.toString(),{method:e.toUpperCase(),body:ae(e)?l:void 0,headers:{"content-type":h,...s}}),f=oe.fromRequest(u);f.query={...Object.fromEntries(m.searchParams.entries()),...i},f.params=p.params,f.cookies=n,f.ip=a;try{let g=await fe(p.middleware,p.handler,f,new D);return new de(g)}catch(g){this.logger.error({error:g},`Error processing mock request ${e} ${t}:`);let v=new D(500);return v.json({error:"Internal server error",message:g instanceof Error?g.message:String(g)}),new de(v)}}async get(e,t){return this.request("GET",e,t)}async post(e,t){return this.request("POST",e,t)}async put(e,t){return this.request("PUT",e,t)}async patch(e,t){return this.request("PATCH",e,t)}async delete(e,t){return this.request("DELETE",e,t)}async formDataToMultipart(e,t){let r=new TextEncoder,s=[];for(let[c,d]of e.entries()){s.push(r.encode(`--${t}\r
1085
1085
  `));let p=`Content-Disposition: form-data; name="${c}"`,l="";if(d instanceof File&&(p+=`; filename="${d.name}"`,l=`Content-Type: ${d.type||"application/octet-stream"}\r
1086
1086
  `),s.push(r.encode(`${p}\r
1087
1087
  ${l}\r