vector-framework 1.1.1 → 1.2.0

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.
Files changed (98) hide show
  1. package/README.md +87 -635
  2. package/dist/auth/protected.d.ts.map +1 -1
  3. package/dist/auth/protected.js.map +1 -1
  4. package/dist/cache/manager.d.ts.map +1 -1
  5. package/dist/cache/manager.js +2 -7
  6. package/dist/cache/manager.js.map +1 -1
  7. package/dist/cli/index.js +17 -62
  8. package/dist/cli/index.js.map +1 -1
  9. package/dist/cli/option-resolution.d.ts +4 -0
  10. package/dist/cli/option-resolution.d.ts.map +1 -0
  11. package/dist/cli/option-resolution.js +28 -0
  12. package/dist/cli/option-resolution.js.map +1 -0
  13. package/dist/cli.js +2721 -617
  14. package/dist/constants/index.d.ts +3 -0
  15. package/dist/constants/index.d.ts.map +1 -1
  16. package/dist/constants/index.js +6 -0
  17. package/dist/constants/index.js.map +1 -1
  18. package/dist/core/config-loader.d.ts.map +1 -1
  19. package/dist/core/config-loader.js +2 -0
  20. package/dist/core/config-loader.js.map +1 -1
  21. package/dist/core/router.d.ts +41 -17
  22. package/dist/core/router.d.ts.map +1 -1
  23. package/dist/core/router.js +432 -153
  24. package/dist/core/router.js.map +1 -1
  25. package/dist/core/server.d.ts +14 -1
  26. package/dist/core/server.d.ts.map +1 -1
  27. package/dist/core/server.js +250 -30
  28. package/dist/core/server.js.map +1 -1
  29. package/dist/core/vector.d.ts +4 -3
  30. package/dist/core/vector.d.ts.map +1 -1
  31. package/dist/core/vector.js +21 -12
  32. package/dist/core/vector.js.map +1 -1
  33. package/dist/dev/route-generator.d.ts.map +1 -1
  34. package/dist/dev/route-generator.js.map +1 -1
  35. package/dist/dev/route-scanner.d.ts.map +1 -1
  36. package/dist/dev/route-scanner.js +1 -5
  37. package/dist/dev/route-scanner.js.map +1 -1
  38. package/dist/http.d.ts +14 -14
  39. package/dist/http.d.ts.map +1 -1
  40. package/dist/http.js +34 -41
  41. package/dist/http.js.map +1 -1
  42. package/dist/index.js +1314 -8
  43. package/dist/index.mjs +1314 -8
  44. package/dist/middleware/manager.d.ts.map +1 -1
  45. package/dist/middleware/manager.js +4 -0
  46. package/dist/middleware/manager.js.map +1 -1
  47. package/dist/openapi/docs-ui.d.ts +2 -0
  48. package/dist/openapi/docs-ui.d.ts.map +1 -0
  49. package/dist/openapi/docs-ui.js +1313 -0
  50. package/dist/openapi/docs-ui.js.map +1 -0
  51. package/dist/openapi/generator.d.ts +12 -0
  52. package/dist/openapi/generator.d.ts.map +1 -0
  53. package/dist/openapi/generator.js +273 -0
  54. package/dist/openapi/generator.js.map +1 -0
  55. package/dist/types/index.d.ts +70 -11
  56. package/dist/types/index.d.ts.map +1 -1
  57. package/dist/types/standard-schema.d.ts +118 -0
  58. package/dist/types/standard-schema.d.ts.map +1 -0
  59. package/dist/types/standard-schema.js +2 -0
  60. package/dist/types/standard-schema.js.map +1 -0
  61. package/dist/utils/cors.d.ts +13 -0
  62. package/dist/utils/cors.d.ts.map +1 -0
  63. package/dist/utils/cors.js +89 -0
  64. package/dist/utils/cors.js.map +1 -0
  65. package/dist/utils/path.d.ts +6 -0
  66. package/dist/utils/path.d.ts.map +1 -1
  67. package/dist/utils/path.js +5 -0
  68. package/dist/utils/path.js.map +1 -1
  69. package/dist/utils/schema-validation.d.ts +31 -0
  70. package/dist/utils/schema-validation.d.ts.map +1 -0
  71. package/dist/utils/schema-validation.js +77 -0
  72. package/dist/utils/schema-validation.js.map +1 -0
  73. package/dist/utils/validation.d.ts.map +1 -1
  74. package/dist/utils/validation.js +1 -0
  75. package/dist/utils/validation.js.map +1 -1
  76. package/package.json +13 -12
  77. package/src/auth/protected.ts +3 -13
  78. package/src/cache/manager.ts +4 -18
  79. package/src/cli/index.ts +19 -75
  80. package/src/cli/option-resolution.ts +40 -0
  81. package/src/constants/index.ts +7 -0
  82. package/src/core/config-loader.ts +3 -3
  83. package/src/core/router.ts +502 -156
  84. package/src/core/server.ts +327 -32
  85. package/src/core/vector.ts +49 -29
  86. package/src/dev/route-generator.ts +1 -3
  87. package/src/dev/route-scanner.ts +2 -9
  88. package/src/http.ts +85 -125
  89. package/src/middleware/manager.ts +4 -0
  90. package/src/openapi/assets/tailwindcdn.js +83 -0
  91. package/src/openapi/docs-ui.ts +1317 -0
  92. package/src/openapi/generator.ts +359 -0
  93. package/src/types/index.ts +104 -17
  94. package/src/types/standard-schema.ts +147 -0
  95. package/src/utils/cors.ts +101 -0
  96. package/src/utils/path.ts +6 -0
  97. package/src/utils/schema-validation.ts +123 -0
  98. package/src/utils/validation.ts +1 -0
package/dist/index.mjs CHANGED
@@ -1,21 +1,1327 @@
1
- var j=(f="text/plain; charset=utf-8",i)=>(l,E={})=>{if(l===void 0||l instanceof Response)return l;let _=new Response(i?.(l)??l,E.url?void 0:E);return _.headers.set("content-type",f),_},Of=j("application/json; charset=utf-8",JSON.stringify);var Nf=j("text/plain; charset=utf-8",String),Df=j("text/html"),$f=j("image/jpeg"),Lf=j("image/png"),If=j("image/webp"),h=async(f)=>{f.content=f.body?await f.clone().json().catch(()=>f.clone().formData()).catch(()=>f.text()):void 0};var Y=(f={})=>{let{origin:i="*",credentials:l=!1,allowMethods:E="*",allowHeaders:_,exposeHeaders:A,maxAge:O}=f,N=(D)=>{let $=D?.headers.get("origin");return i===!0?$:i instanceof RegExp?i.test($)?$:void 0:Array.isArray(i)?i.includes($)?$:void 0:i instanceof Function?i($):i=="*"&&l?$:i},L=(D,$)=>{for(let[w,U]of Object.entries($))U&&D.headers.append(w,U);return D};return{corsify:(D,$)=>D?.headers?.get("access-control-allow-origin")||D.status==101?D:L(D.clone(),{"access-control-allow-origin":N($),"access-control-allow-credentials":l}),preflight:(D)=>{if(D.method=="OPTIONS"){let $=new Response(null,{status:204});return L($,{"access-control-allow-origin":N(D),"access-control-allow-methods":E?.join?.(",")??E,"access-control-expose-headers":A?.join?.(",")??A,"access-control-allow-headers":_?.join?.(",")??_??D.headers.get("access-control-request-headers"),"access-control-max-age":O,"access-control-allow-credentials":l})}}}};function g(f){return process.platform==="win32"?`file:///${f.replace(/\\/g,"/")}`:f}function d(f){return RegExp(`^${f.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>[\\s\\S]+))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}var C={OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,IM_USED:226,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},J={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},Q={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"};class V{protectedHandler=null;setProtectedHandler(f){this.protectedHandler=f}async authenticate(f){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let i=await this.protectedHandler(f);return f.authUser=i,i}catch(i){throw new Error(`Authentication failed: ${i instanceof Error?i.message:String(i)}`)}}isAuthenticated(f){return!!f.authUser}getUser(f){return f.authUser||null}}class K{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;inflight=new Map;setCacheHandler(f){this.cacheHandler=f}async get(f,i,l=J.CACHE_TTL){if(l<=0)return i();if(this.cacheHandler)return this.cacheHandler(f,i,l);return this.getFromMemoryCache(f,i,l)}async getFromMemoryCache(f,i,l){let E=Date.now(),_=this.memoryCache.get(f);if(this.isCacheValid(_,E))return _.value;if(this.inflight.has(f))return await this.inflight.get(f);let A=(async()=>{let O=await i();return this.setInMemoryCache(f,O,l),O})();this.inflight.set(f,A);try{return await A}finally{this.inflight.delete(f)}}isCacheValid(f,i){return f!==void 0&&f.expires>i}setInMemoryCache(f,i,l){let E=Date.now()+l*1000;this.memoryCache.set(f,{value:i,expires:E}),this.scheduleCleanup()}scheduleCleanup(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanupExpired()},60000)}cleanupExpired(){let f=Date.now();for(let[i,l]of this.memoryCache.entries())if(l.expires<=f)this.memoryCache.delete(i);if(this.memoryCache.size===0&&this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}clear(){if(this.memoryCache.clear(),this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}async set(f,i,l=J.CACHE_TTL){if(l<=0)return;if(this.cacheHandler){await this.cacheHandler(f,async()=>i,l);return}this.setInMemoryCache(f,i,l)}delete(f){return this.memoryCache.delete(f)}has(f){let i=this.memoryCache.get(f);if(!i)return!1;if(i.expires<=Date.now())return this.memoryCache.delete(f),!1;return!0}generateKey(f,i){let l=f._parsedUrl??new URL(f.url);return[f.method,l.pathname,l.search,i?.authUser?.id!=null?String(i.authUser.id):"anonymous"].join(":")}}var{promises:k}=(()=>({}));function S(f){if(typeof f!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(f))}function T(f,i){var l="",E=0,_=-1,A=0,O;for(var N=0;N<=f.length;++N){if(N<f.length)O=f.charCodeAt(N);else if(O===47)break;else O=47;if(O===47){if(_===N-1||A===1);else if(_!==N-1&&A===2){if(l.length<2||E!==2||l.charCodeAt(l.length-1)!==46||l.charCodeAt(l.length-2)!==46){if(l.length>2){var L=l.lastIndexOf("/");if(L!==l.length-1){if(L===-1)l="",E=0;else l=l.slice(0,L),E=l.length-1-l.lastIndexOf("/");_=N,A=0;continue}}else if(l.length===2||l.length===1){l="",E=0,_=N,A=0;continue}}if(i){if(l.length>0)l+="/..";else l="..";E=2}}else{if(l.length>0)l+="/"+f.slice(_+1,N);else l=f.slice(_+1,N);E=N-_-1}_=N,A=0}else if(O===46&&A!==-1)++A;else A=-1}return l}function q(f,i){var l=i.dir||i.root,E=i.base||(i.name||"")+(i.ext||"");if(!l)return E;if(l===i.root)return l+E;return l+f+E}function F(){var f="",i=!1,l;for(var E=arguments.length-1;E>=-1&&!i;E--){var _;if(E>=0)_=arguments[E];else{if(l===void 0)l=process.cwd();_=l}if(S(_),_.length===0)continue;f=_+"/"+f,i=_.charCodeAt(0)===47}if(f=T(f,!i),i)if(f.length>0)return"/"+f;else return"/";else if(f.length>0)return f;else return"."}function v(f){if(S(f),f.length===0)return".";var i=f.charCodeAt(0)===47,l=f.charCodeAt(f.length-1)===47;if(f=T(f,!i),f.length===0&&!i)f=".";if(f.length>0&&l)f+="/";if(i)return"/"+f;return f}function y(f){return S(f),f.length>0&&f.charCodeAt(0)===47}function Z(){if(arguments.length===0)return".";var f;for(var i=0;i<arguments.length;++i){var l=arguments[i];if(S(l),l.length>0)if(f===void 0)f=l;else f+="/"+l}if(f===void 0)return".";return v(f)}function G(f,i){if(S(f),S(i),f===i)return"";if(f=F(f),i=F(i),f===i)return"";var l=1;for(;l<f.length;++l)if(f.charCodeAt(l)!==47)break;var E=f.length,_=E-l,A=1;for(;A<i.length;++A)if(i.charCodeAt(A)!==47)break;var O=i.length,N=O-A,L=_<N?_:N,D=-1,$=0;for(;$<=L;++$){if($===L){if(N>L){if(i.charCodeAt(A+$)===47)return i.slice(A+$+1);else if($===0)return i.slice(A+$)}else if(_>L){if(f.charCodeAt(l+$)===47)D=$;else if($===0)D=0}break}var w=f.charCodeAt(l+$),U=i.charCodeAt(A+$);if(w!==U)break;else if(w===47)D=$}var R="";for($=l+D+1;$<=E;++$)if($===E||f.charCodeAt($)===47)if(R.length===0)R+="..";else R+="/..";if(R.length>0)return R+i.slice(A+D);else{if(A+=D,i.charCodeAt(A)===47)++A;return i.slice(A)}}function n(f){return f}function H(f){if(S(f),f.length===0)return".";var i=f.charCodeAt(0),l=i===47,E=-1,_=!0;for(var A=f.length-1;A>=1;--A)if(i=f.charCodeAt(A),i===47){if(!_){E=A;break}}else _=!1;if(E===-1)return l?"/":".";if(l&&E===1)return"//";return f.slice(0,E)}function s(f,i){if(i!==void 0&&typeof i!=="string")throw new TypeError('"ext" argument must be a string');S(f);var l=0,E=-1,_=!0,A;if(i!==void 0&&i.length>0&&i.length<=f.length){if(i.length===f.length&&i===f)return"";var O=i.length-1,N=-1;for(A=f.length-1;A>=0;--A){var L=f.charCodeAt(A);if(L===47){if(!_){l=A+1;break}}else{if(N===-1)_=!1,N=A+1;if(O>=0)if(L===i.charCodeAt(O)){if(--O===-1)E=A}else O=-1,E=N}}if(l===E)E=N;else if(E===-1)E=f.length;return f.slice(l,E)}else{for(A=f.length-1;A>=0;--A)if(f.charCodeAt(A)===47){if(!_){l=A+1;break}}else if(E===-1)_=!1,E=A+1;if(E===-1)return"";return f.slice(l,E)}}function p(f){S(f);var i=-1,l=0,E=-1,_=!0,A=0;for(var O=f.length-1;O>=0;--O){var N=f.charCodeAt(O);if(N===47){if(!_){l=O+1;break}continue}if(E===-1)_=!1,E=O+1;if(N===46){if(i===-1)i=O;else if(A!==1)A=1}else if(i!==-1)A=-1}if(i===-1||E===-1||A===0||A===1&&i===E-1&&i===l+1)return"";return f.slice(i,E)}function r(f){if(f===null||typeof f!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof f);return q("/",f)}function o(f){S(f);var i={root:"",dir:"",base:"",ext:"",name:""};if(f.length===0)return i;var l=f.charCodeAt(0),E=l===47,_;if(E)i.root="/",_=1;else _=0;var A=-1,O=0,N=-1,L=!0,D=f.length-1,$=0;for(;D>=_;--D){if(l=f.charCodeAt(D),l===47){if(!L){O=D+1;break}continue}if(N===-1)L=!1,N=D+1;if(l===46){if(A===-1)A=D;else if($!==1)$=1}else if(A!==-1)$=-1}if(A===-1||N===-1||$===0||$===1&&A===N-1&&A===O+1){if(N!==-1)if(O===0&&E)i.base=i.name=f.slice(1,N);else i.base=i.name=f.slice(O,N)}else{if(O===0&&E)i.name=f.slice(1,A),i.base=f.slice(1,N);else i.name=f.slice(O,A),i.base=f.slice(O,N);i.ext=f.slice(A,N)}if(O>0)i.dir=f.slice(0,O-1);else if(E)i.dir="/";return i}var X="/",t=":",Pf=((f)=>(f.posix=f,f))({resolve:F,normalize:v,isAbsolute:y,join:Z,relative:G,_makeLong:n,dirname:H,basename:s,extname:p,format:r,parse:o,sep:X,delimiter:t,win32:null,posix:null});class W{outputPath;constructor(f="./.vector/routes.generated.ts"){this.outputPath=f}async generate(f){let i=H(this.outputPath);await k.mkdir(i,{recursive:!0});let l=[],E=new Map;for(let N of f){if(!E.has(N.path))E.set(N.path,[]);E.get(N.path).push(N)}let _=0,A=[];for(let[N,L]of E){let D=G(H(this.outputPath),N).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),$=`route_${_++}`,w=L.filter((U)=>U.name!=="default").map((U)=>U.name);if(L.some((U)=>U.name==="default"))if(w.length>0)l.push(`import ${$}, { ${w.join(", ")} } from '${D}';`);else l.push(`import ${$} from '${D}';`);else if(w.length>0)l.push(`import { ${w.join(", ")} } from '${D}';`);for(let U of L){let R=U.name==="default"?$:U.name;A.push(` ${R},`)}}let O=`// This file is auto-generated. Do not edit manually.
1
+ var g={OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,IM_USED:226,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},S={PORT:3000,HOSTNAME:"localhost",ROUTES_DIR:"./routes",CACHE_TTL:0,CORS_MAX_AGE:86400},j={JSON:"application/json",TEXT:"text/plain",HTML:"text/html",FORM_URLENCODED:"application/x-www-form-urlencoded",MULTIPART:"multipart/form-data"};var L={NOT_FOUND:new Response(JSON.stringify({error:!0,message:"Not Found",statusCode:404}),{status:404,headers:{"content-type":"application/json"}})};class M{protectedHandler=null;setProtectedHandler(e){this.protectedHandler=e}async authenticate(e){if(!this.protectedHandler)throw new Error("Protected handler not configured. Use vector.protected() to set authentication handler.");try{let t=await this.protectedHandler(e);return e.authUser=t,t}catch(t){throw new Error(`Authentication failed: ${t instanceof Error?t.message:String(t)}`)}}isAuthenticated(e){return!!e.authUser}getUser(e){return e.authUser||null}}class P{cacheHandler=null;memoryCache=new Map;cleanupInterval=null;inflight=new Map;setCacheHandler(e){this.cacheHandler=e}async get(e,t,n=S.CACHE_TTL){if(n<=0)return t();if(this.cacheHandler)return this.cacheHandler(e,t,n);return this.getFromMemoryCache(e,t,n)}async getFromMemoryCache(e,t,n){let d=Date.now(),r=this.memoryCache.get(e);if(this.isCacheValid(r,d))return r.value;if(this.inflight.has(e))return await this.inflight.get(e);let a=(async()=>{let o=await t();return this.setInMemoryCache(e,o,n),o})();this.inflight.set(e,a);try{return await a}finally{this.inflight.delete(e)}}isCacheValid(e,t){return e!==void 0&&e.expires>t}setInMemoryCache(e,t,n){let d=Date.now()+n*1000;this.memoryCache.set(e,{value:t,expires:d}),this.scheduleCleanup()}scheduleCleanup(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanupExpired()},60000)}cleanupExpired(){let e=Date.now();for(let[t,n]of this.memoryCache.entries())if(n.expires<=e)this.memoryCache.delete(t);if(this.memoryCache.size===0&&this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}clear(){if(this.memoryCache.clear(),this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}async set(e,t,n=S.CACHE_TTL){if(n<=0)return;if(this.cacheHandler){await this.cacheHandler(e,async()=>t,n);return}this.setInMemoryCache(e,t,n)}delete(e){return this.memoryCache.delete(e)}has(e){let t=this.memoryCache.get(e);if(!t)return!1;if(t.expires<=Date.now())return this.memoryCache.delete(e),!1;return!0}generateKey(e,t){let n=e._parsedUrl??new URL(e.url),d=t?.authUser?.id!=null?String(t.authUser.id):"anonymous";return`${e.method}:${n.pathname}:${n.search}:${d}`}}var{promises:V}=(()=>({}));function y(e){if(typeof e!=="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function z(e,t){var n="",d=0,r=-1,a=0,o;for(var l=0;l<=e.length;++l){if(l<e.length)o=e.charCodeAt(l);else if(o===47)break;else o=47;if(o===47){if(r===l-1||a===1);else if(r!==l-1&&a===2){if(n.length<2||d!==2||n.charCodeAt(n.length-1)!==46||n.charCodeAt(n.length-2)!==46){if(n.length>2){var i=n.lastIndexOf("/");if(i!==n.length-1){if(i===-1)n="",d=0;else n=n.slice(0,i),d=n.length-1-n.lastIndexOf("/");r=l,a=0;continue}}else if(n.length===2||n.length===1){n="",d=0,r=l,a=0;continue}}if(t){if(n.length>0)n+="/..";else n="..";d=2}}else{if(n.length>0)n+="/"+e.slice(r+1,l);else n=e.slice(r+1,l);d=l-r-1}r=l,a=0}else if(o===46&&a!==-1)++a;else a=-1}return n}function se(e,t){var n=t.dir||t.root,d=t.base||(t.name||"")+(t.ext||"");if(!n)return d;if(n===t.root)return n+d;return n+e+d}function I(){var e="",t=!1,n;for(var d=arguments.length-1;d>=-1&&!t;d--){var r;if(d>=0)r=arguments[d];else{if(n===void 0)n=process.cwd();r=n}if(y(r),r.length===0)continue;e=r+"/"+e,t=r.charCodeAt(0)===47}if(e=z(e,!t),t)if(e.length>0)return"/"+e;else return"/";else if(e.length>0)return e;else return"."}function $(e){if(y(e),e.length===0)return".";var t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47;if(e=z(e,!t),e.length===0&&!t)e=".";if(e.length>0&&n)e+="/";if(t)return"/"+e;return e}function ce(e){return y(e),e.length>0&&e.charCodeAt(0)===47}function B(){if(arguments.length===0)return".";var e;for(var t=0;t<arguments.length;++t){var n=arguments[t];if(y(n),n.length>0)if(e===void 0)e=n;else e+="/"+n}if(e===void 0)return".";return $(e)}function k(e,t){if(y(e),y(t),e===t)return"";if(e=I(e),t=I(t),e===t)return"";var n=1;for(;n<e.length;++n)if(e.charCodeAt(n)!==47)break;var d=e.length,r=d-n,a=1;for(;a<t.length;++a)if(t.charCodeAt(a)!==47)break;var o=t.length,l=o-a,i=r<l?r:l,b=-1,s=0;for(;s<=i;++s){if(s===i){if(l>i){if(t.charCodeAt(a+s)===47)return t.slice(a+s+1);else if(s===0)return t.slice(a+s)}else if(r>i){if(e.charCodeAt(n+s)===47)b=s;else if(s===0)b=0}break}var u=e.charCodeAt(n+s),m=t.charCodeAt(a+s);if(u!==m)break;else if(u===47)b=s}var h="";for(s=n+b+1;s<=d;++s)if(s===d||e.charCodeAt(s)===47)if(h.length===0)h+="..";else h+="/..";if(h.length>0)return h+t.slice(a+b);else{if(a+=b,t.charCodeAt(a)===47)++a;return t.slice(a)}}function be(e){return e}function C(e){if(y(e),e.length===0)return".";var t=e.charCodeAt(0),n=t===47,d=-1,r=!0;for(var a=e.length-1;a>=1;--a)if(t=e.charCodeAt(a),t===47){if(!r){d=a;break}}else r=!1;if(d===-1)return n?"/":".";if(n&&d===1)return"//";return e.slice(0,d)}function ue(e,t){if(t!==void 0&&typeof t!=="string")throw new TypeError('"ext" argument must be a string');y(e);var n=0,d=-1,r=!0,a;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";var o=t.length-1,l=-1;for(a=e.length-1;a>=0;--a){var i=e.charCodeAt(a);if(i===47){if(!r){n=a+1;break}}else{if(l===-1)r=!1,l=a+1;if(o>=0)if(i===t.charCodeAt(o)){if(--o===-1)d=a}else o=-1,d=l}}if(n===d)d=l;else if(d===-1)d=e.length;return e.slice(n,d)}else{for(a=e.length-1;a>=0;--a)if(e.charCodeAt(a)===47){if(!r){n=a+1;break}}else if(d===-1)r=!1,d=a+1;if(d===-1)return"";return e.slice(n,d)}}function me(e){y(e);var t=-1,n=0,d=-1,r=!0,a=0;for(var o=e.length-1;o>=0;--o){var l=e.charCodeAt(o);if(l===47){if(!r){n=o+1;break}continue}if(d===-1)r=!1,d=o+1;if(l===46){if(t===-1)t=o;else if(a!==1)a=1}else if(t!==-1)a=-1}if(t===-1||d===-1||a===0||a===1&&t===d-1&&t===n+1)return"";return e.slice(t,d)}function fe(e){if(e===null||typeof e!=="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return se("/",e)}function pe(e){y(e);var t={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return t;var n=e.charCodeAt(0),d=n===47,r;if(d)t.root="/",r=1;else r=0;var a=-1,o=0,l=-1,i=!0,b=e.length-1,s=0;for(;b>=r;--b){if(n=e.charCodeAt(b),n===47){if(!i){o=b+1;break}continue}if(l===-1)i=!1,l=b+1;if(n===46){if(a===-1)a=b;else if(s!==1)s=1}else if(a!==-1)s=-1}if(a===-1||l===-1||s===0||s===1&&a===l-1&&a===o+1){if(l!==-1)if(o===0&&d)t.base=t.name=e.slice(1,l);else t.base=t.name=e.slice(o,l)}else{if(o===0&&d)t.name=e.slice(1,a),t.base=e.slice(1,l);else t.name=e.slice(o,a),t.base=e.slice(o,l);t.ext=e.slice(a,l)}if(o>0)t.dir=e.slice(0,o-1);else if(d)t.dir="/";return t}var O="/",he=":",Fe=((e)=>(e.posix=e,e))({resolve:I,normalize:$,isAbsolute:ce,join:B,relative:k,_makeLong:be,dirname:C,basename:ue,extname:me,format:fe,parse:pe,sep:O,delimiter:he,win32:null,posix:null});class _{outputPath;constructor(e="./.vector/routes.generated.ts"){this.outputPath=e}async generate(e){let t=C(this.outputPath);await V.mkdir(t,{recursive:!0});let n=[],d=new Map;for(let l of e){if(!d.has(l.path))d.set(l.path,[]);d.get(l.path).push(l)}let r=0,a=[];for(let[l,i]of d){let b=k(C(this.outputPath),l).replace(/\\/g,"/").replace(/\.(ts|js)$/,""),s=`route_${r++}`,u=i.filter((m)=>m.name!=="default").map((m)=>m.name);if(i.some((m)=>m.name==="default"))if(u.length>0)n.push(`import ${s}, { ${u.join(", ")} } from '${b}';`);else n.push(`import ${s} from '${b}';`);else if(u.length>0)n.push(`import { ${u.join(", ")} } from '${b}';`);for(let m of i){let h=m.name==="default"?s:m.name;a.push(` ${h},`)}}let o=`// This file is auto-generated. Do not edit manually.
2
2
  // Generated at: ${new Date().toISOString()}
3
3
 
4
- ${l.join(`
4
+ ${n.join(`
5
5
  `)}
6
6
 
7
7
  export const routes = [
8
- ${A.join(`
8
+ ${a.join(`
9
9
  `)}
10
10
  ];
11
11
 
12
12
  export default routes;
13
- `;await k.writeFile(this.outputPath,O,"utf-8")}async generateDynamic(f){let i=[];for(let l of f){let E=JSON.stringify({method:l.method,path:l.options.path,options:l.options});i.push(` await import('${l.path}').then(m => ({
14
- ...${E},
15
- handler: m.${l.name==="default"?"default":l.name}
13
+ `;await V.writeFile(this.outputPath,o,"utf-8")}async generateDynamic(e){let t=[];for(let n of e){let d=JSON.stringify({method:n.method,path:n.options.path,options:n.options});t.push(` await import('${n.path}').then(m => ({
14
+ ...${d},
15
+ handler: m.${n.name==="default"?"default":n.name}
16
16
  }))`)}return`export const loadRoutes = async () => {
17
17
  return Promise.all([
18
- ${i.join(`,
18
+ ${t.join(`,
19
19
  `)}
20
20
  ]);
21
- };`}}var{existsSync:e,promises:c}=(()=>({}));class z{routesDir;excludePatterns;static DEFAULT_EXCLUDE_PATTERNS=["*.test.ts","*.test.js","*.test.tsx","*.test.jsx","*.spec.ts","*.spec.js","*.spec.tsx","*.spec.jsx","*.tests.ts","*.tests.js","**/__tests__/**","*.interface.ts","*.type.ts","*.d.ts"];constructor(f="./routes",i){this.routesDir=F(process.cwd(),f),this.excludePatterns=i||z.DEFAULT_EXCLUDE_PATTERNS}async scan(){let f=[];if(!e(this.routesDir))return[];try{await this.scanDirectory(this.routesDir,f)}catch(i){if(i.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw i}return f}isExcluded(f){let i=G(this.routesDir,f);for(let l of this.excludePatterns){let E=l.replace(/\./g,"\\.").replace(/\*\*/g,"__GLOBSTAR__").replace(/\*/g,"[^/]*").replace(/__GLOBSTAR__/g,".*").replace(/\?/g,"."),_=new RegExp(`^${E}$`),A=i.split(X).pop()||"";if(_.test(i)||_.test(A))return!0}return!1}async scanDirectory(f,i,l=""){let E=await c.readdir(f);for(let _ of E){let A=Z(f,_);if((await c.stat(A)).isDirectory()){let N=l?`${l}/${_}`:_;await this.scanDirectory(A,i,N)}else if(_.endsWith(".ts")||_.endsWith(".js")){if(this.isExcluded(A))continue;let N=G(this.routesDir,A).replace(/\.(ts|js)$/,"").split(X).join("/");try{let D=await import(process.platform==="win32"?`file:///${A.replace(/\\/g,"/")}`:A);if(D.default&&typeof D.default==="function")i.push({name:"default",path:A,method:"GET",options:{method:"GET",path:`/${N}`,expose:!0}});for(let[$,w]of Object.entries(D)){if($==="default")continue;if(w&&typeof w==="object"&&"entry"in w&&"options"in w&&"handler"in w){let U=w;i.push({name:$,path:A,method:U.options.method,options:U.options})}else if(Array.isArray(w)&&w.length>=4){let[U,,,R]=w;i.push({name:$,path:A,method:U,options:{method:U,path:R,expose:!0}})}}}catch(L){console.error(`Failed to load route from ${A}:`,L)}}}}enableWatch(f){if(typeof Bun!=="undefined"&&Bun.env.NODE_ENV==="development")console.log(`Watching for route changes in ${this.routesDir}`),setInterval(async()=>{await f()},1000)}}class B{beforeHandlers=[];finallyHandlers=[];addBefore(...f){this.beforeHandlers.push(...f)}addFinally(...f){this.finallyHandlers.push(...f)}async executeBefore(f){let i=f;for(let l of this.beforeHandlers){let E=await l(i);if(E instanceof Response)return E;i=E}return i}async executeFinally(f,i){let l=f;for(let E of this.finallyHandlers)try{l=await E(l,i)}catch(_){console.error("After middleware error:",_)}return l}clone(){let f=new B;return f.beforeHandlers=[...this.beforeHandlers],f.finallyHandlers=[...this.finallyHandlers],f}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}class a{middlewareManager;authManager;cacheManager;routes=[];specificityCache=new Map;constructor(f,i,l){this.middlewareManager=f,this.authManager=i,this.cacheManager=l}getRouteSpecificity(f){let i=this.specificityCache.get(f);if(i!==void 0)return i;let l=1000,E=10,_=1,A=1e4,O=0,N=f.split("/").filter(Boolean);for(let L of N)if(this.isStaticSegment(L))O+=l;else if(this.isParamSegment(L))O+=E;else if(this.isWildcardSegment(L))O+=_;if(O+=f.length,this.isExactPath(f))O+=A;return this.specificityCache.set(f,O),O}isStaticSegment(f){return!f.startsWith(":")&&!f.includes("*")}isParamSegment(f){return f.startsWith(":")}isWildcardSegment(f){return f.includes("*")}isExactPath(f){return!f.includes(":")&&!f.includes("*")}sortRoutes(){this.routes.sort((f,i)=>{let l=this.extractPath(f),E=this.extractPath(i),_=this.getRouteSpecificity(l);return this.getRouteSpecificity(E)-_})}extractPath(f){return f[3]||""}route(f,i){let l=this.wrapHandler(f,i),E=[f.method.toUpperCase(),this.createRouteRegex(f.path),[l],f.path];return this.routes.push(E),this.sortRoutes(),E}createRouteRegex(f){return d(f)}prepareRequest(f,i){if(!f.context)f.context={};if(i?.params!==void 0)f.params=i.params;if(i?.route!==void 0)f.route=i.route;if(i?.metadata!==void 0)f.metadata=i.metadata;if(!f.query&&f.url){let l=f._parsedUrl??new URL(f.url),E={};for(let[_,A]of l.searchParams)if(_ in E)if(Array.isArray(E[_]))E[_].push(A);else E[_]=[E[_],A];else E[_]=A;f.query=E}if(!Object.getOwnPropertyDescriptor(f,"cookies"))Object.defineProperty(f,"cookies",{get(){let l=this.headers.get("cookie")??"",E={};if(l)for(let _ of l.split(";")){let A=_.indexOf("=");if(A>0)E[_.slice(0,A).trim()]=_.slice(A+1).trim()}return Object.defineProperty(this,"cookies",{value:E,writable:!0,configurable:!0,enumerable:!0}),E},configurable:!0,enumerable:!0})}wrapHandler(f,i){return async(l)=>{let E=l;this.prepareRequest(E,{metadata:f.metadata}),l=E;try{if(f.expose===!1)return b.forbidden("Forbidden");let _=await this.middlewareManager.executeBefore(l);if(_ instanceof Response)return _;if(l=_,f.auth)try{await this.authManager.authenticate(l)}catch(D){return b.unauthorized(D instanceof Error?D.message:"Authentication failed",f.responseContentType)}if(!f.rawRequest&&l.method!=="GET"&&l.method!=="HEAD")try{let D=l.headers.get("content-type");if(D?.includes("application/json"))l.content=await l.json();else if(D?.includes("application/x-www-form-urlencoded"))l.content=Object.fromEntries(await l.formData());else if(D?.includes("multipart/form-data"))l.content=await l.formData();else l.content=await l.text()}catch{l.content=null}let A,O=f.cache,N=async()=>{let D=await i(l);if(D instanceof Response)return{_isResponse:!0,body:await D.text(),status:D.status,headers:Object.fromEntries(D.headers.entries())};return D};if(O&&typeof O==="number"&&O>0){let D=this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,N,O)}else if(O&&typeof O==="object"&&O.ttl){let D=O.key||this.cacheManager.generateKey(l,{authUser:l.authUser});A=await this.cacheManager.get(D,N,O.ttl)}else A=await i(l);if(A&&typeof A==="object"&&A._isResponse===!0)A=new Response(A.body,{status:A.status,headers:A.headers});let L;if(f.rawResponse||A instanceof Response)L=A instanceof Response?A:new Response(A);else L=x(200,A,f.responseContentType);return L=await this.middlewareManager.executeFinally(L,l),L}catch(_){if(_ instanceof Response)return _;return console.error("Route handler error:",_),b.internalServerError(_ instanceof Error?_.message:String(_),f.responseContentType)}}}addRoute(f){this.routes.push(f),this.sortRoutes()}bulkAddRoutes(f){for(let i of f)this.routes.push(i);this.sortRoutes()}getRoutes(){return this.routes}async handle(f){let i;try{i=new URL(f.url)}catch{return b.badRequest("Malformed request URL")}f._parsedUrl=i;let l=i.pathname;for(let[E,_,A,O]of this.routes)if(f.method==="OPTIONS"||f.method===E){let N=l.match(_);if(N){let L=f;this.prepareRequest(L,{params:N.groups||{},route:O||l});for(let D of A){let $=await D(L);if($)return $}}}return b.notFound("Route not found")}clearRoutes(){this.routes=[],this.specificityCache.clear()}}class M{server=null;router;config;corsHandler;corsHeaders=null;constructor(f,i){if(this.router=f,this.config=i,i.cors){let l=this.normalizeCorsOptions(i.cors),{preflight:E,corsify:_}=Y(l);if(this.corsHandler={preflight:E,corsify:_},typeof l.origin==="string"){if(this.corsHeaders={"access-control-allow-origin":l.origin,"access-control-allow-methods":l.allowMethods,"access-control-allow-headers":l.allowHeaders,"access-control-expose-headers":l.exposeHeaders,"access-control-max-age":String(l.maxAge)},l.credentials)this.corsHeaders["access-control-allow-credentials"]="true"}}}normalizeCorsOptions(f){return{origin:f.origin||"*",credentials:f.credentials!==!1,allowHeaders:Array.isArray(f.allowHeaders)?f.allowHeaders.join(", "):f.allowHeaders||"Content-Type, Authorization",allowMethods:Array.isArray(f.allowMethods)?f.allowMethods.join(", "):f.allowMethods||"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:Array.isArray(f.exposeHeaders)?f.exposeHeaders.join(", "):f.exposeHeaders||"Authorization",maxAge:f.maxAge||86400}}async start(){let f=this.config.port||3000,i=this.config.hostname||"localhost",l=async(E)=>{try{if(this.corsHandler&&E.method==="OPTIONS")return this.corsHandler.preflight(E);let _=await this.router.handle(E);if(this.corsHeaders)for(let[A,O]of Object.entries(this.corsHeaders))_.headers.set(A,O);else if(this.corsHandler)_=this.corsHandler.corsify(_,E);return _}catch(_){return console.error("Server error:",_),new Response("Internal Server Error",{status:500})}};try{if(this.server=Bun.serve({port:f,hostname:i,reusePort:this.config.reusePort!==!1,fetch:l,idleTimeout:this.config.idleTimeout||60,error:(E)=>{return console.error("[ERROR] Server error:",E),new Response("Internal Server Error",{status:500})}}),!this.server||!this.server.port)throw new Error(`Failed to start server on ${i}:${f} - server object is invalid`);return this.server}catch(E){if(E.code==="EADDRINUSE"||E.message?.includes("address already in use"))E.message=`Port ${f} is already in use`,E.port=f;else if(E.code==="EACCES"||E.message?.includes("permission denied"))E.message=`Permission denied to bind to port ${f}`,E.port=f;else if(E.message?.includes("EADDRNOTAVAIL"))E.message=`Cannot bind to hostname ${i}`,E.hostname=i;throw E}}stop(){if(this.server)this.server.stop(),this.server=null,console.log("Server stopped")}getServer(){return this.server}getPort(){return this.server?.port||this.config.port||3000}getHostname(){return this.server?.hostname||this.config.hostname||"localhost"}getUrl(){let f=this.getPort();return`http://${this.getHostname()}:${f}`}}class P{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new B,this.authManager=new V,this.cacheManager=new K,this.router=new a(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!P.instance)P.instance=new P;return P.instance}setProtectedHandler(f){this._protectedHandler=f,this.authManager.setProtectedHandler(f)}getProtectedHandler(){return this._protectedHandler}setCacheHandler(f){this._cacheHandler=f,this.cacheManager.setCacheHandler(f)}getCacheHandler(){return this._cacheHandler}addRoute(f,i){return this.router.route(f,i)}async startServer(f){if(this.config={...this.config,...f},this.middlewareManager.clear(),this.config.autoDiscover!==!1)this.router.clearRoutes();if(f?.before)this.middlewareManager.addBefore(...f.before);if(f?.finally)this.middlewareManager.addFinally(...f.finally);if(this.config.autoDiscover!==!1)await this.discoverRoutes();return this.server=new M(this.router,this.config),await this.server.start()}async discoverRoutes(){let f=this.config.routesDir||"./routes",i=this.config.routeExcludePatterns;if(this.routeScanner=new z(f,i),!this.routeGenerator)this.routeGenerator=new W;try{let l=await this.routeScanner.scan();if(l.length>0){if(this.config.development)await this.routeGenerator.generate(l);for(let E of l)try{let A=await import(g(E.path)),O=E.name==="default"?A.default:A[E.name];if(O){if(this.isRouteDefinition(O)){let N=O;this.router.route(N.options,N.handler),this.logRouteLoaded(N.options)}else if(this.isRouteEntry(O))this.router.addRoute(O),this.logRouteLoaded(O);else if(typeof O==="function")this.router.route(E.options,O),this.logRouteLoaded(E.options)}}catch(_){console.error(`Failed to load route ${E.name} from ${E.path}:`,_)}this.router.sortRoutes()}}catch(l){if(l.code!=="ENOENT"&&l.code!=="ENOTDIR")console.error("Failed to discover routes:",l)}}async loadRoute(f){if(typeof f==="function"){let i=f();if(Array.isArray(i))this.router.addRoute(i)}else if(f&&typeof f==="object"){for(let[,i]of Object.entries(f))if(typeof i==="function"){let l=i();if(Array.isArray(l))this.router.addRoute(l)}}}isRouteEntry(f){return Array.isArray(f)&&f.length>=3}isRouteDefinition(f){return f&&typeof f==="object"&&"entry"in f&&"options"in f&&"handler"in f}logRouteLoaded(f){}stop(){if(this.server)this.server.stop(),this.server=null}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){P.instance=null}}var m=P.getInstance;var{preflight:qf,corsify:yf}=Y({origin:"*",credentials:!0,allowHeaders:"Content-Type, Authorization",allowMethods:"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:"Authorization",maxAge:86400});function ff(f,i){let l=_f(f,i);return{entry:[f.method.toUpperCase(),d(f.path),[l],f.path],options:f,handler:i}}function u(f,i=0){if(typeof f==="bigint")return!0;if(i>4||f===null||typeof f!=="object")return!1;for(let l of Object.values(f))if(u(l,i+1))return!0;return!1}function lf(f){let i=f??null;if(!u(i))return JSON.stringify(i);return JSON.stringify(i,(l,E)=>typeof E==="bigint"?E.toString():E)}var Ef={success:(f,i)=>x(C.OK,f,i),created:(f,i)=>x(C.CREATED,f,i)};function I(f,i,l){let E={error:!0,message:i,statusCode:f,timestamp:new Date().toISOString()};return x(f,E,l)}var b={badRequest:(f="Bad Request",i)=>I(C.BAD_REQUEST,f,i),unauthorized:(f="Unauthorized",i)=>I(C.UNAUTHORIZED,f,i),paymentRequired:(f="Payment Required",i)=>I(402,f,i),forbidden:(f="Forbidden",i)=>I(C.FORBIDDEN,f,i),notFound:(f="Not Found",i)=>I(C.NOT_FOUND,f,i),methodNotAllowed:(f="Method Not Allowed",i)=>I(405,f,i),notAcceptable:(f="Not Acceptable",i)=>I(406,f,i),requestTimeout:(f="Request Timeout",i)=>I(408,f,i),conflict:(f="Conflict",i)=>I(C.CONFLICT,f,i),gone:(f="Gone",i)=>I(410,f,i),lengthRequired:(f="Length Required",i)=>I(411,f,i),preconditionFailed:(f="Precondition Failed",i)=>I(412,f,i),payloadTooLarge:(f="Payload Too Large",i)=>I(413,f,i),uriTooLong:(f="URI Too Long",i)=>I(414,f,i),unsupportedMediaType:(f="Unsupported Media Type",i)=>I(415,f,i),rangeNotSatisfiable:(f="Range Not Satisfiable",i)=>I(416,f,i),expectationFailed:(f="Expectation Failed",i)=>I(417,f,i),imATeapot:(f="I'm a teapot",i)=>I(418,f,i),misdirectedRequest:(f="Misdirected Request",i)=>I(421,f,i),unprocessableEntity:(f="Unprocessable Entity",i)=>I(C.UNPROCESSABLE_ENTITY,f,i),locked:(f="Locked",i)=>I(423,f,i),failedDependency:(f="Failed Dependency",i)=>I(424,f,i),tooEarly:(f="Too Early",i)=>I(425,f,i),upgradeRequired:(f="Upgrade Required",i)=>I(426,f,i),preconditionRequired:(f="Precondition Required",i)=>I(428,f,i),tooManyRequests:(f="Too Many Requests",i)=>I(429,f,i),requestHeaderFieldsTooLarge:(f="Request Header Fields Too Large",i)=>I(431,f,i),unavailableForLegalReasons:(f="Unavailable For Legal Reasons",i)=>I(451,f,i),internalServerError:(f="Internal Server Error",i)=>I(C.INTERNAL_SERVER_ERROR,f,i),notImplemented:(f="Not Implemented",i)=>I(501,f,i),badGateway:(f="Bad Gateway",i)=>I(502,f,i),serviceUnavailable:(f="Service Unavailable",i)=>I(503,f,i),gatewayTimeout:(f="Gateway Timeout",i)=>I(504,f,i),httpVersionNotSupported:(f="HTTP Version Not Supported",i)=>I(505,f,i),variantAlsoNegotiates:(f="Variant Also Negotiates",i)=>I(506,f,i),insufficientStorage:(f="Insufficient Storage",i)=>I(507,f,i),loopDetected:(f="Loop Detected",i)=>I(508,f,i),notExtended:(f="Not Extended",i)=>I(510,f,i),networkAuthenticationRequired:(f="Network Authentication Required",i)=>I(511,f,i),invalidArgument:(f="Invalid Argument",i)=>I(C.UNPROCESSABLE_ENTITY,f,i),rateLimitExceeded:(f="Rate Limit Exceeded",i)=>I(429,f,i),maintenance:(f="Service Under Maintenance",i)=>I(503,f,i),custom:(f,i,l)=>I(f,i,l)};function x(f,i,l=Q.JSON){let E=l===Q.JSON?lf(i):i;return new Response(E,{status:f,headers:{"content-type":l}})}var Af=async(f,i)=>{let E=m().getProtectedHandler();if(!E)throw b.unauthorized("Authentication not configured",i);try{let _=await E(f);f.authUser=_}catch(_){throw b.unauthorized(_ instanceof Error?_.message:"Authentication failed",i)}};function _f(f,i){let{auth:l=!1,expose:E=!1,rawRequest:_=!1,rawResponse:A=!1,responseContentType:O=Q.JSON}=f;return async(N)=>{if(!E)return b.forbidden("Forbidden");try{if(l)await Af(N,O);if(!_)await h(N);let L=await i(N);return A?L:Ef.success(L,O)}catch(L){if(L instanceof Response)return L;return b.internalServerError(String(L),O)}}}export{ff as route,x as createResponse,b as APIError};
21
+ };`}}var{existsSync:ye,promises:G}=(()=>({}));class D{routesDir;excludePatterns;static DEFAULT_EXCLUDE_PATTERNS=["*.test.ts","*.test.js","*.test.tsx","*.test.jsx","*.spec.ts","*.spec.js","*.spec.tsx","*.spec.jsx","*.tests.ts","*.tests.js","**/__tests__/**","*.interface.ts","*.type.ts","*.d.ts"];constructor(e="./routes",t){this.routesDir=I(process.cwd(),e),this.excludePatterns=t||D.DEFAULT_EXCLUDE_PATTERNS}async scan(){let e=[];if(!ye(this.routesDir))return[];try{await this.scanDirectory(this.routesDir,e)}catch(t){if(t.code==="ENOENT")return console.warn(` ✗ Routes directory not accessible: ${this.routesDir}`),[];throw t}return e}isExcluded(e){let t=k(this.routesDir,e);for(let n of this.excludePatterns){let d=n.replace(/\./g,"\\.").replace(/\*\*/g,"__GLOBSTAR__").replace(/\*/g,"[^/]*").replace(/__GLOBSTAR__/g,".*").replace(/\?/g,"."),r=new RegExp(`^${d}$`),a=t.split(O).pop()||"";if(r.test(t)||r.test(a))return!0}return!1}async scanDirectory(e,t,n=""){let d=await G.readdir(e);for(let r of d){let a=B(e,r);if((await G.stat(a)).isDirectory()){let l=n?`${n}/${r}`:r;await this.scanDirectory(a,t,l)}else if(r.endsWith(".ts")||r.endsWith(".js")){if(this.isExcluded(a))continue;let l=k(this.routesDir,a).replace(/\.(ts|js)$/,"").split(O).join("/");try{let b=await import(process.platform==="win32"?`file:///${a.replace(/\\/g,"/")}`:a);if(b.default&&typeof b.default==="function")t.push({name:"default",path:a,method:"GET",options:{method:"GET",path:`/${l}`,expose:!0}});for(let[s,u]of Object.entries(b)){if(s==="default")continue;if(u&&typeof u==="object"&&"entry"in u&&"options"in u&&"handler"in u){let m=u;t.push({name:s,path:a,method:m.options.method,options:m.options})}else if(Array.isArray(u)&&u.length>=4){let[m,,,h]=u;t.push({name:s,path:a,method:m,options:{method:m,path:h,expose:!0}})}}}catch(i){console.error(`Failed to load route from ${a}:`,i)}}}}enableWatch(e){if(typeof Bun!=="undefined"&&Bun.env.NODE_ENV==="development")console.log(`Watching for route changes in ${this.routesDir}`),setInterval(async()=>{await e()},1000)}}class N{beforeHandlers=[];finallyHandlers=[];addBefore(...e){this.beforeHandlers.push(...e)}addFinally(...e){this.finallyHandlers.push(...e)}async executeBefore(e){if(this.beforeHandlers.length===0)return e;let t=e;for(let n of this.beforeHandlers){let d=await n(t);if(d instanceof Response)return d;t=d}return t}async executeFinally(e,t){if(this.finallyHandlers.length===0)return e;let n=e;for(let d of this.finallyHandlers)try{n=await d(n,t)}catch(r){console.error("After middleware error:",r)}return n}clone(){let e=new N;return e.beforeHandlers=[...this.beforeHandlers],e.finallyHandlers=[...this.finallyHandlers],e}clear(){this.beforeHandlers=[],this.finallyHandlers=[]}}function Q(e){return process.platform==="win32"?`file:///${e.replace(/\\/g,"/")}`:e}function H(e){return RegExp(`^${e.replace(/\/+(\/|$)/g,"$1").replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>[\\s\\S]+))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`)}function Y(e){let t=e?.["~standard"];return!!t&&typeof t==="object"&&typeof t.validate==="function"&&t.version===1}async function X(e,t){let n=await e["~standard"].validate(t),d=n?.issues;if(Array.isArray(d)&&d.length>0)return{success:!1,issues:d};return{success:!0,value:n?.value}}function W(e){if(Array.isArray(e))return e;if(e&&typeof e==="object"&&Array.isArray(e.issues))return e.issues;if(e&&typeof e==="object"&&e.cause&&Array.isArray(e.cause.issues))return e.cause.issues;return null}function ge(e){if(!Array.isArray(e))return[];let t=[];for(let n=0;n<e.length;n++){let d=e[n],r=d;if(d&&typeof d==="object"&&"key"in d)r=d.key;if(typeof r==="string"||typeof r==="number")t.push(r);else if(typeof r==="symbol")t.push(String(r));else if(r!==void 0&&r!==null)t.push(String(r))}return t}function R(e,t){let n=[];for(let d=0;d<e.length;d++){let r=e[d],a=r,o={message:typeof a?.message==="string"&&a.message.length>0?a.message:"Invalid value",path:ge(a?.path)};if(typeof a?.code==="string")o.code=a.code;if(t)o.raw=r;n.push(o)}return n}function T(e,t){return{error:!0,message:"Validation failed",statusCode:422,source:"validation",target:e,issues:t,timestamp:new Date().toISOString()}}class A{middlewareManager;authManager;cacheManager;routeBooleanDefaults={};developmentMode=void 0;routeDefinitions=[];routeTable=Object.create(null);routeMatchers=[];corsHeadersEntries=null;corsHandler=null;constructor(e,t,n){this.middlewareManager=e,this.authManager=t,this.cacheManager=n}setCorsHeaders(e){this.corsHeadersEntries=e}setCorsHandler(e){this.corsHandler=e}setRouteBooleanDefaults(e){this.routeBooleanDefaults={...e}}setDevelopmentMode(e){this.developmentMode=e}applyRouteBooleanDefaults(e){let t={...e},n=this.routeBooleanDefaults,d=["auth","expose","rawRequest","validate","rawResponse"];for(let r of d)if(t[r]===void 0&&n[r]!==void 0)t[r]=n[r];return t}route(e,t){let n=this.applyRouteBooleanDefaults(e),d=n.method.toUpperCase(),r=n.path,a=this.wrapHandler(n,t),o=this.getOrCreateMethodMap(r);o[d]=a,this.routeDefinitions.push({method:d,path:r,options:n})}addRoute(e){let[t,,n,d]=e;if(!d)return;let r=this.getOrCreateMethodMap(d);r[t.toUpperCase()]=n[0];let a=t.toUpperCase();this.routeDefinitions.push({method:a,path:d,options:{method:a,path:d,expose:!0}})}bulkAddRoutes(e){for(let t of e)this.addRoute(t)}addStaticRoute(e,t){let n=this.routeTable[e];if(n&&!(n instanceof Response))throw new Error(`Cannot register static route for path "${e}" because method routes already exist.`);this.routeTable[e]=t,this.removeRouteMatcher(e)}getRouteTable(){return this.routeTable}getRoutes(){let e=[];for(let t of this.routeMatchers){let n=this.routeTable[t.path];if(!n||n instanceof Response)continue;for(let[d,r]of Object.entries(n))e.push([d,t.regex,[r],t.path])}return e}getRouteDefinitions(){return[...this.routeDefinitions]}clearRoutes(){this.routeTable=Object.create(null),this.routeMatchers=[],this.routeDefinitions=[]}sortRoutes(){}async handle(e){let t;try{t=new URL(e.url)}catch{return x.badRequest("Malformed request URL")}e._parsedUrl=t;let n=t.pathname;for(let d of this.routeMatchers){let r=d.path,a=this.routeTable[r];if(!a)continue;if(a instanceof Response)continue;let o=a;if(e.method==="OPTIONS"||e.method in o){let l=n.match(d.regex);if(l){try{e.params=l.groups??{}}catch{}let i=o[e.method]??o.GET;if(i){let b=await i(e);if(b)return b}}}}return L.NOT_FOUND.clone()}prepareRequest(e,t){if(!e.context)e.context={};let n=!!e.params&&typeof e.params==="object"&&!Array.isArray(e.params)&&Object.keys(e.params).length===0;if(t?.params!==void 0&&(e.params===void 0||n))try{e.params=t.params}catch{}if(t?.route!==void 0)e.route=t.route;if(t?.metadata!==void 0)e.metadata=t.metadata;if(e.query==null&&e.url)try{Object.defineProperty(e,"query",{get(){let d=this._parsedUrl??new URL(this.url),r=A.parseQuery(d);return Object.defineProperty(this,"query",{value:r,writable:!0,configurable:!0,enumerable:!0}),r},set(d){Object.defineProperty(this,"query",{value:d,writable:!0,configurable:!0,enumerable:!0})},configurable:!0,enumerable:!0})}catch{let d=e._parsedUrl??new URL(e.url);try{e.query=A.parseQuery(d)}catch{}}if(!Object.getOwnPropertyDescriptor(e,"cookies"))Object.defineProperty(e,"cookies",{get(){let d=this.headers.get("cookie")??"",r={};if(d)for(let a of d.split(";")){let o=a.indexOf("=");if(o>0)r[a.slice(0,o).trim()]=a.slice(o+1).trim()}return Object.defineProperty(this,"cookies",{value:r,writable:!0,configurable:!0,enumerable:!0}),r},configurable:!0,enumerable:!0})}resolveFallbackParams(e,t){if(!t)return;let n=e.params;if(n&&typeof n==="object"&&!Array.isArray(n)&&Object.keys(n).length>0)return;let d;try{d=(e._parsedUrl??new URL(e.url)).pathname}catch{return}let r=d.match(t);if(!r?.groups)return;return r.groups}wrapHandler(e,t){let n=e.path,d=n.includes(":")?H(n):null;return async(r)=>{let a=r,o=this.resolveFallbackParams(r,d);this.prepareRequest(a,{params:o,route:n,metadata:e.metadata});try{if(e.expose===!1)return x.forbidden("Forbidden");let l=await this.middlewareManager.executeBefore(a);if(l instanceof Response)return l;let i=l;if(e.auth)try{await this.authManager.authenticate(i)}catch(f){return x.unauthorized(f instanceof Error?f.message:"Authentication failed",e.responseContentType)}if(!e.rawRequest&&i.method!=="GET"&&i.method!=="HEAD"){let f=null;try{let p=i.headers.get("content-type");if(p?.startsWith("application/json"))f=await i.json();else if(p?.startsWith("application/x-www-form-urlencoded"))f=Object.fromEntries(await i.formData());else if(p?.startsWith("multipart/form-data"))f=await i.formData();else f=await i.text()}catch{f=null}this.setContentAndBodyAlias(i,f)}let b=await this.validateInputSchema(i,e);if(b)return b;let s,u=e.cache;if(u&&typeof u==="number"&&u>0){let f=this.cacheManager.generateKey(i,{authUser:i.authUser});s=await this.cacheManager.get(f,async()=>{let p=await t(i);if(p instanceof Response)return{_isResponse:!0,body:await p.text(),status:p.status,headers:Object.fromEntries(p.headers.entries())};return p},u)}else if(u&&typeof u==="object"&&u.ttl){let f=u.key||this.cacheManager.generateKey(i,{authUser:i.authUser});s=await this.cacheManager.get(f,async()=>{let p=await t(i);if(p instanceof Response)return{_isResponse:!0,body:await p.text(),status:p.status,headers:Object.fromEntries(p.headers.entries())};return p},u.ttl)}else s=await t(i);if(s&&typeof s==="object"&&s._isResponse===!0)s=new Response(s.body,{status:s.status,headers:s.headers});let m;if(e.rawResponse||s instanceof Response)m=s instanceof Response?s:new Response(s);else m=E(200,s,e.responseContentType);m=await this.middlewareManager.executeFinally(m,i);let h=this.corsHeadersEntries;if(h)for(let[f,p]of h)m.headers.set(f,p);else{let f=this.corsHandler;if(f)m=f(m,i)}return m}catch(l){if(l instanceof Response)return l;return console.error("Route handler error:",l),x.internalServerError(l instanceof Error?l.message:String(l),e.responseContentType)}}}isDevelopmentMode(){if(this.developmentMode!==void 0)return this.developmentMode;return(typeof Bun!=="undefined"?Bun.env.NODE_ENV:"development")!=="production"}async buildInputValidationPayload(e,t){let n=e.content;if(t.rawRequest&&e.method!=="GET"&&e.method!=="HEAD")try{n=await e.clone().text()}catch{n=null}return{params:e.params??{},query:e.query??{},headers:Object.fromEntries(e.headers.entries()),cookies:e.cookies??{},body:n}}applyValidatedInput(e,t){if(e.validatedInput=t,!t||typeof t!=="object")return;let n=t;if("params"in n)try{e.params=n.params}catch{}if("query"in n)try{e.query=n.query}catch{}if("cookies"in n)try{e.cookies=n.cookies}catch{}if("body"in n)this.setContentAndBodyAlias(e,n.body)}setContentAndBodyAlias(e,t){try{e.content=t}catch{return}this.setBodyAlias(e,t)}setBodyAlias(e,t){try{e.body=t}catch{}}async validateInputSchema(e,t){let n=t.schema?.input;if(!n)return null;if(t.validate===!1)return null;if(!Y(n))return x.internalServerError("Invalid route schema configuration",t.responseContentType);let d=this.isDevelopmentMode(),r=await this.buildInputValidationPayload(e,t);try{let a=await X(n,r);if(a.success===!1){let o=R(a.issues,d);return E(422,T("input",o),t.responseContentType)}return this.applyValidatedInput(e,a.value),null}catch(a){let o=W(a);if(o){let l=R(o,d);return E(422,T("input",l),t.responseContentType)}return x.internalServerError(a instanceof Error?a.message:"Validation failed",t.responseContentType)}}getOrCreateMethodMap(e){let t=this.routeTable[e];if(t instanceof Response)throw new Error(`Cannot register method route for path "${e}" because a static route already exists.`);if(t)return t;let n=Object.create(null);return this.routeTable[e]=n,this.addRouteMatcher(e),n}addRouteMatcher(e){if(this.routeMatchers.some((t)=>t.path===e))return;this.routeMatchers.push({path:e,regex:H(e),specificity:this.routeSpecificityScore(e)}),this.routeMatchers.sort((t,n)=>{if(t.specificity!==n.specificity)return n.specificity-t.specificity;return t.path.localeCompare(n.path)})}removeRouteMatcher(e){this.routeMatchers=this.routeMatchers.filter((t)=>t.path!==e)}static parseQuery(e){let t={};for(let[n,d]of e.searchParams)if(n in t){let r=t[n];if(Array.isArray(r))r.push(d);else t[n]=[r,d]}else t[n]=d;return t}routeSpecificityScore(e){let a=e.split("/").filter(Boolean),o=0;for(let l of a)if(l.includes("*"))o+=1;else if(l.startsWith(":"))o+=10;else o+=1000;if(o+=e.length,!e.includes(":")&&!e.includes("*"))o+=1e4;return o}}var{existsSync:oe}=(()=>({}));function K(e,t){if(!e){if(typeof t.origin==="string"){if(t.origin==="*"&&t.credentials)return null;return t.origin}return null}if(typeof t.origin==="string"){if(t.origin==="*")return t.credentials?e:"*";return t.origin===e?e:null}if(Array.isArray(t.origin))return t.origin.includes(e)?e:null;if(typeof t.origin==="function")return t.origin(e)?e:null;return null}function Z(e){return typeof e.origin==="string"&&e.origin==="*"&&e.credentials||Array.isArray(e.origin)||typeof e.origin==="function"}function q(e,t,n){let d={};if(e){if(d["access-control-allow-origin"]=e,d["access-control-allow-methods"]=t.allowMethods,d["access-control-allow-headers"]=t.allowHeaders,d["access-control-expose-headers"]=t.exposeHeaders,d["access-control-max-age"]=String(t.maxAge),t.credentials)d["access-control-allow-credentials"]="true";if(n)d.vary="Origin"}return d}function xe(e,t){if(!e)return t;let n=e.split(",").map((r)=>r.trim()).filter(Boolean);if(!n.map((r)=>r.toLowerCase()).includes(t.toLowerCase()))n.push(t);return n.join(", ")}function ee(e){return{preflight(t){let n=t.headers.get("origin")??void 0,d=K(n,e),r=Boolean(n&&d&&Z(e));return new Response(null,{status:204,headers:q(d,e,r)})},corsify(t,n){let d=n.headers.get("origin")??void 0,r=K(d,e);if(!r)return t;let a=Boolean(d&&Z(e)),o=q(r,e,a);for(let[l,i]of Object.entries(o)){if(l==="vary"){t.headers.set("vary",xe(t.headers.get("vary"),i));continue}t.headers.set(l,i)}return t}}}function te(e,t,n){let d=JSON.stringify(e).replace(/<\/script/gi,"<\\/script"),r=JSON.stringify(t);return`<!DOCTYPE html>
22
+ <html lang="en">
23
+ <head>
24
+ <meta charset="UTF-8">
25
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
26
+ <title>Vector API Documentation</title>
27
+ <script>
28
+ if (localStorage.getItem('theme') === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
29
+ document.documentElement.classList.add('dark');
30
+ } else {
31
+ document.documentElement.classList.remove('dark');
32
+ }
33
+ </script>
34
+ <script src=${JSON.stringify(n)}></script>
35
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
36
+ <script>
37
+ tailwind.config = {
38
+ darkMode: 'class',
39
+ theme: {
40
+ extend: {
41
+ colors: {
42
+ brand: '#6366F1',
43
+ dark: { bg: '#0A0A0A', surface: '#111111', border: '#1F1F1F', text: '#EDEDED' },
44
+ light: { bg: '#FFFFFF', surface: '#F9F9F9', border: '#E5E5E5', text: '#111111' }
45
+ },
46
+ fontFamily: {
47
+ sans: ['Inter', 'sans-serif'],
48
+ mono: ['JetBrains Mono', 'monospace'],
49
+ }
50
+ }
51
+ }
52
+ };
53
+ </script>
54
+ <style>
55
+ :root {
56
+ --motion-fast: 180ms;
57
+ --motion-base: 280ms;
58
+ --motion-slow: 420ms;
59
+ --motion-ease: cubic-bezier(0.22, 1, 0.36, 1);
60
+ }
61
+ ::-webkit-scrollbar { width: 8px; height: 8px; }
62
+ ::-webkit-scrollbar-track { background: transparent; }
63
+ ::-webkit-scrollbar-thumb { background: #333; border-radius: 4px; }
64
+ body { transition: background-color 150ms ease, color 150ms ease; }
65
+ #sidebar-nav a,
66
+ #send-btn,
67
+ #copy-curl,
68
+ #add-header-btn,
69
+ #expand-body-btn,
70
+ #expand-response-btn,
71
+ #expand-close,
72
+ #expand-apply {
73
+ transition:
74
+ transform var(--motion-fast) var(--motion-ease),
75
+ opacity var(--motion-fast) var(--motion-ease),
76
+ border-color var(--motion-fast) var(--motion-ease),
77
+ background-color var(--motion-fast) var(--motion-ease),
78
+ color var(--motion-fast) var(--motion-ease);
79
+ will-change: transform, opacity;
80
+ }
81
+ #sidebar-nav a:hover,
82
+ #send-btn:hover,
83
+ #add-header-btn:hover,
84
+ #expand-body-btn:hover,
85
+ #expand-response-btn:hover {
86
+ transform: translateY(-1px);
87
+ }
88
+ #endpoint-card {
89
+ transition:
90
+ box-shadow var(--motion-base) var(--motion-ease),
91
+ transform var(--motion-base) var(--motion-ease),
92
+ opacity var(--motion-base) var(--motion-ease);
93
+ }
94
+ .enter-fade-up {
95
+ animation: enterFadeUp var(--motion-base) var(--motion-ease) both;
96
+ }
97
+ .enter-stagger {
98
+ animation: enterStagger var(--motion-base) var(--motion-ease) both;
99
+ animation-delay: var(--stagger-delay, 0ms);
100
+ }
101
+ @keyframes enterFadeUp {
102
+ from { opacity: 0; transform: translateY(8px); }
103
+ to { opacity: 1; transform: translateY(0); }
104
+ }
105
+ @keyframes enterStagger {
106
+ from { opacity: 0; transform: translateX(-6px); }
107
+ to { opacity: 1; transform: translateX(0); }
108
+ }
109
+ @media (prefers-reduced-motion: reduce) {
110
+ *, *::before, *::after {
111
+ animation: none !important;
112
+ transition: none !important;
113
+ }
114
+ }
115
+ .json-key { color: #0f766e; }
116
+ .json-string { color: #0369a1; }
117
+ .json-number { color: #7c3aed; }
118
+ .json-boolean { color: #b45309; }
119
+ .json-null { color: #be123c; }
120
+ .dark .json-key { color: #5eead4; }
121
+ .dark .json-string { color: #7dd3fc; }
122
+ .dark .json-number { color: #c4b5fd; }
123
+ .dark .json-boolean { color: #fcd34d; }
124
+ .dark .json-null { color: #fda4af; }
125
+ </style>
126
+ </head>
127
+ <body class="bg-light-bg text-light-text dark:bg-dark-bg dark:text-dark-text font-sans antialiased flex h-screen overflow-hidden">
128
+ <div id="mobile-backdrop" class="fixed inset-0 z-30 bg-black/40 opacity-0 pointer-events-none transition-opacity duration-300 md:hidden"></div>
129
+ <aside id="docs-sidebar" class="fixed inset-y-0 left-0 z-40 w-72 md:w-64 border-r border-light-border dark:border-dark-border bg-light-surface dark:bg-dark-surface flex flex-col flex-shrink-0 transition-transform duration-300 ease-out -translate-x-full md:translate-x-0 md:static md:z-auto transition-colors duration-150">
130
+ <div class="h-14 flex items-center px-5 border-b border-light-border dark:border-dark-border">
131
+ <svg class="w-5 h-5 text-brand" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
132
+ <polygon points="3 21 12 2 21 21 12 15 3 21"></polygon>
133
+ </svg>
134
+ <span class="ml-2.5 font-bold tracking-tight text-lg">Vector</span>
135
+ <button id="sidebar-close" class="ml-auto p-1.5 rounded-full border border-light-border dark:border-dark-border bg-light-bg/90 dark:bg-dark-bg/90 opacity-90 hover:opacity-100 transition md:hidden" aria-label="Close Menu" title="Close Menu">
136
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
137
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
138
+ </svg>
139
+ </button>
140
+ </div>
141
+ <div class="p-4">
142
+ <div class="relative">
143
+ <svg class="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 opacity-60" fill="none" stroke="currentColor" viewBox="0 0 24 24">
144
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
145
+ </svg>
146
+ <input
147
+ id="sidebar-search"
148
+ type="text"
149
+ placeholder="Search routes..."
150
+ class="w-full pl-9 pr-3 py-2 text-sm rounded-md border border-light-border dark:border-dark-border bg-light-bg dark:bg-dark-bg focus:outline-none focus:border-brand dark:focus:border-brand transition-colors"
151
+ />
152
+ </div>
153
+ </div>
154
+ <nav class="flex-1 overflow-y-auto px-3 py-2 space-y-6 text-sm" id="sidebar-nav"></nav>
155
+ </aside>
156
+
157
+ <main class="flex-1 flex flex-col min-w-0 relative">
158
+ <header class="h-14 flex items-center justify-between px-6 border-b border-light-border dark:border-dark-border lg:border-none lg:bg-transparent absolute top-0 w-full z-10 bg-light-bg/80 dark:bg-dark-bg/80 backdrop-blur-sm transition-colors duration-150">
159
+ <div class="md:hidden flex items-center gap-2">
160
+ <button id="sidebar-open" class="p-1.5 rounded-full border border-light-border dark:border-dark-border bg-light-bg/90 dark:bg-dark-bg/90 opacity-90 hover:opacity-100 transition" aria-label="Open Menu" title="Open Menu">
161
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
162
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path>
163
+ </svg>
164
+ </button>
165
+ <svg class="w-5 h-5 text-brand" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="3 21 12 2 21 21 12 15 3 21"></polygon></svg>
166
+ <span class="font-bold tracking-tight">Vector</span>
167
+ </div>
168
+ <div class="flex-1"></div>
169
+ <button id="theme-toggle" class="p-2 rounded-md hover:bg-black/5 dark:hover:bg-white/5 transition-colors" aria-label="Toggle Dark Mode">
170
+ <svg class="w-5 h-5 hidden dark:block text-dark-text" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"></path></svg>
171
+ <svg class="w-5 h-5 block dark:hidden text-light-text" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"></path></svg>
172
+ </button>
173
+ </header>
174
+
175
+ <div class="flex-1 overflow-y-auto pt-14 pb-24">
176
+ <div class="max-w-[860px] mx-auto px-6 py-12 lg:py-16">
177
+ <div class="mb-12">
178
+ <h1 class="text-4xl font-bold tracking-tight mb-4" id="tag-title">API</h1>
179
+ <p class="text-lg opacity-80 max-w-2xl leading-relaxed" id="tag-description">Interactive API documentation.</p>
180
+ </div>
181
+ <hr class="border-t border-light-border dark:border-dark-border mb-12">
182
+ <div class="mb-20" id="endpoint-card">
183
+ <div class="flex items-center gap-3 mb-4">
184
+ <span id="endpoint-method" class="px-2.5 py-0.5 rounded-full text-xs font-mono font-medium"></span>
185
+ <h2 class="text-xl font-semibold tracking-tight" id="endpoint-title">Operation</h2>
186
+ </div>
187
+ <p class="text-sm opacity-80 mb-8 font-mono" id="endpoint-path">/</p>
188
+ <div class="grid grid-cols-1 lg:grid-cols-12 gap-10">
189
+ <div class="lg:col-span-5 space-y-8" id="params-column"></div>
190
+ <div class="lg:col-span-7">
191
+ <div class="rounded-lg border border-light-border dark:border-[#1F1F1F] bg-light-bg dark:bg-[#111111] overflow-hidden group">
192
+ <div class="flex items-center justify-between px-4 py-2 border-b border-light-border dark:border-[#1F1F1F] bg-light-surface dark:bg-[#0A0A0A]">
193
+ <span class="text-xs font-mono text-light-text/70 dark:text-[#EDEDED]/70">cURL</span>
194
+ <button class="text-xs text-light-text/50 hover:text-light-text dark:text-[#EDEDED]/50 dark:hover:text-[#EDEDED] transition-colors" id="copy-curl">Copy</button>
195
+ </div>
196
+ <pre class="p-4 text-sm font-mono text-light-text dark:text-[#EDEDED] overflow-x-auto leading-relaxed"><code id="curl-code"></code></pre>
197
+ </div>
198
+ <div class="mt-4 p-4 rounded-lg border border-light-border dark:border-dark-border bg-light-surface dark:bg-dark-surface">
199
+ <div class="flex items-center justify-between mb-3">
200
+ <h4 class="text-sm font-medium">Try it out</h4>
201
+ <button id="send-btn" class="px-4 py-1.5 bg-teal-600 text-white text-sm font-semibold rounded hover:bg-teal-500 transition-colors">Submit</button>
202
+ </div>
203
+ <div class="space-y-4">
204
+ <div>
205
+ <div id="request-param-inputs" class="space-y-3"></div>
206
+ </div>
207
+
208
+ <div>
209
+ <div class="flex items-center justify-between mb-2">
210
+ <p class="text-xs font-semibold uppercase tracking-wider opacity-60">Headers</p>
211
+ <button id="add-header-btn" class="p-1.5 rounded-full border border-light-border dark:border-dark-border bg-light-bg/90 dark:bg-dark-bg/90 opacity-90 hover:opacity-100 hover:border-brand/60 transition-colors" aria-label="Add Header" title="Add Header">
212
+ <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
213
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 5v14m-7-7h14"></path>
214
+ </svg>
215
+ </button>
216
+ </div>
217
+ <div id="header-inputs" class="space-y-2"></div>
218
+ </div>
219
+
220
+ <div id="request-body-section">
221
+ <div class="flex items-center justify-between mb-2">
222
+ <p class="text-xs font-semibold uppercase tracking-wider opacity-60">Request Body</p>
223
+ </div>
224
+ <div class="relative h-40 rounded border border-light-border dark:border-dark-border bg-light-bg dark:bg-dark-bg overflow-hidden">
225
+ <pre id="body-highlight" class="absolute inset-0 m-0 p-3 pr-11 text-xs font-mono leading-5 overflow-auto whitespace-pre-wrap break-words pointer-events-none"></pre>
226
+ <textarea id="body-input" class="absolute inset-0 w-full h-full p-3 pr-11 text-xs font-mono leading-5 bg-transparent text-transparent caret-black dark:caret-white resize-none focus:outline-none overflow-auto placeholder:text-light-text/50 dark:placeholder:text-dark-text/40" placeholder='{"key":"value"}' spellcheck="false" autocapitalize="off" autocorrect="off"></textarea>
227
+ <button id="expand-body-btn" class="absolute bottom-2 right-2 p-1.5 rounded-full border border-light-border dark:border-dark-border bg-light-surface/95 dark:bg-dark-surface/95 opacity-90 hover:opacity-100 hover:border-brand/60 transition-colors" aria-label="Expand Request Body" title="Expand Request Body">
228
+ <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
229
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 9V4h5M20 15v5h-5M15 4h5v5M9 20H4v-5"></path>
230
+ </svg>
231
+ </button>
232
+ </div>
233
+ </div>
234
+
235
+ <div>
236
+ <div class="flex items-center justify-between mb-2">
237
+ <p class="text-xs font-semibold uppercase tracking-wider opacity-60">Response</p>
238
+ </div>
239
+ <div class="relative">
240
+ <pre id="result" class="p-3 pr-11 text-xs font-mono rounded border border-light-border dark:border-dark-border overflow-x-auto min-h-[140px]"></pre>
241
+ <button id="expand-response-btn" class="absolute bottom-2 right-2 p-1.5 rounded-full border border-light-border dark:border-dark-border bg-light-surface/95 dark:bg-dark-surface/95 opacity-90 hover:opacity-100 hover:border-brand/60 transition-colors" aria-label="Expand Response" title="Expand Response">
242
+ <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
243
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 9V4h5M20 15v5h-5M15 4h5v5M9 20H4v-5"></path>
244
+ </svg>
245
+ </button>
246
+ </div>
247
+ </div>
248
+ </div>
249
+ </div>
250
+ </div>
251
+ </div>
252
+ </div>
253
+ </div>
254
+ </div>
255
+ </main>
256
+
257
+ <div id="expand-modal" class="fixed inset-0 z-50 hidden items-center justify-center bg-black/60 p-4">
258
+ <div class="w-full max-w-5xl rounded-lg border border-light-border dark:border-dark-border bg-light-surface dark:bg-dark-surface p-4">
259
+ <div class="flex items-center justify-between mb-3">
260
+ <h3 id="expand-modal-title" class="text-sm font-semibold">Expanded View</h3>
261
+ <div class="flex items-center gap-2">
262
+ <button id="expand-apply" class="hidden text-sm px-3 py-1.5 rounded bg-teal-600 text-white font-semibold hover:bg-teal-500 transition-colors">Apply</button>
263
+ <button id="expand-close" class="p-1.5 rounded-full border border-light-border dark:border-dark-border bg-light-bg/90 dark:bg-dark-bg/90 opacity-90 hover:opacity-100 hover:border-brand/60 transition-colors" aria-label="Close Modal" title="Close Modal">
264
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
265
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
266
+ </svg>
267
+ </button>
268
+ </div>
269
+ </div>
270
+ <div id="expand-editor-shell" class="hidden relative w-full h-[70vh] rounded border border-light-border dark:border-dark-border bg-light-bg dark:bg-dark-bg overflow-hidden">
271
+ <pre id="expand-editor-highlight" class="absolute inset-0 m-0 p-3 text-sm font-mono leading-6 overflow-auto whitespace-pre-wrap break-words pointer-events-none"></pre>
272
+ <textarea id="expand-editor" class="absolute inset-0 w-full h-full p-3 text-sm font-mono leading-6 bg-transparent text-transparent caret-black dark:caret-white resize-none focus:outline-none overflow-auto" spellcheck="false" autocapitalize="off" autocorrect="off"></textarea>
273
+ </div>
274
+ <pre id="expand-viewer" class="hidden w-full h-[70vh] text-sm p-3 rounded border border-light-border dark:border-dark-border bg-light-bg dark:bg-dark-bg overflow-auto font-mono"></pre>
275
+ </div>
276
+ </div>
277
+
278
+ <script>
279
+ const spec = ${d};
280
+ const openapiPath = ${r};
281
+ const methodBadge = {
282
+ GET: "bg-green-100 text-green-700 dark:bg-green-500/10 dark:text-green-400",
283
+ POST: "bg-blue-100 text-blue-700 dark:bg-blue-500/10 dark:text-blue-400",
284
+ PUT: "bg-amber-100 text-amber-700 dark:bg-amber-500/10 dark:text-amber-400",
285
+ PATCH: "bg-amber-100 text-amber-700 dark:bg-amber-500/10 dark:text-amber-400",
286
+ DELETE: "bg-red-100 text-red-700 dark:bg-red-500/10 dark:text-red-400",
287
+ };
288
+
289
+ function getOperations() {
290
+ const httpMethods = new Set([
291
+ "get",
292
+ "post",
293
+ "put",
294
+ "patch",
295
+ "delete",
296
+ "head",
297
+ "options",
298
+ ]);
299
+
300
+ const humanizePath = (path) =>
301
+ path
302
+ .replace(/^\\/+/, "")
303
+ .replace(/[{}]/g, "")
304
+ .replace(/[\\/_]+/g, " ")
305
+ .trim() || "root";
306
+
307
+ const toTitleCase = (value) =>
308
+ value.replace(/\\w\\S*/g, (word) => word.charAt(0).toUpperCase() + word.slice(1));
309
+
310
+ const getDisplayName = (op, method, path) => {
311
+ if (typeof op.summary === "string" && op.summary.trim()) {
312
+ return op.summary.trim();
313
+ }
314
+
315
+ if (typeof op.operationId === "string" && op.operationId.trim()) {
316
+ const withoutPrefix = op.operationId.replace(
317
+ new RegExp("^" + method + "_+", "i"),
318
+ "",
319
+ );
320
+ const readable = withoutPrefix.replace(/_+/g, " ").trim();
321
+ if (readable) return toTitleCase(readable);
322
+ }
323
+
324
+ return toTitleCase(humanizePath(path));
325
+ };
326
+
327
+ const ops = [];
328
+ const paths = spec.paths || {};
329
+ for (const path of Object.keys(paths)) {
330
+ const methods = paths[path] || {};
331
+ for (const method of Object.keys(methods)) {
332
+ if (!httpMethods.has(method)) continue;
333
+ const op = methods[method];
334
+ ops.push({
335
+ path,
336
+ method: method.toUpperCase(),
337
+ operation: op,
338
+ tag: (op.tags && op.tags[0]) || "default",
339
+ name: getDisplayName(op, method, path),
340
+ });
341
+ }
342
+ }
343
+ return ops;
344
+ }
345
+
346
+ const operations = getOperations();
347
+ let selected = operations[0] || null;
348
+ const operationParamValues = new Map();
349
+ const operationBodyDrafts = new Map();
350
+ const requestHeaders = [{ key: "Authorization", value: "" }];
351
+ let expandModalMode = null;
352
+ let isMobileSidebarOpen = false;
353
+ let sidebarSearchQuery = "";
354
+
355
+ function setMobileSidebarOpen(open) {
356
+ const sidebar = document.getElementById("docs-sidebar");
357
+ const backdrop = document.getElementById("mobile-backdrop");
358
+ const openBtn = document.getElementById("sidebar-open");
359
+ if (!sidebar || !backdrop || !openBtn) return;
360
+
361
+ isMobileSidebarOpen = open;
362
+ sidebar.classList.toggle("-translate-x-full", !open);
363
+ backdrop.classList.toggle("opacity-0", !open);
364
+ backdrop.classList.toggle("pointer-events-none", !open);
365
+ openBtn.setAttribute("aria-expanded", open ? "true" : "false");
366
+ document.body.classList.toggle("overflow-hidden", open);
367
+ }
368
+
369
+ function getOperationKey(op) {
370
+ return op.method + " " + op.path;
371
+ }
372
+
373
+ function getOperationParameterGroups(op) {
374
+ const params =
375
+ op &&
376
+ op.operation &&
377
+ Array.isArray(op.operation.parameters)
378
+ ? op.operation.parameters
379
+ : [];
380
+
381
+ return {
382
+ all: params,
383
+ path: params.filter((p) => p.in === "path"),
384
+ query: params.filter((p) => p.in === "query"),
385
+ headers: params.filter((p) => p.in === "header"),
386
+ };
387
+ }
388
+
389
+ function getParameterValues(op) {
390
+ const key = getOperationKey(op);
391
+ if (!operationParamValues.has(key)) {
392
+ operationParamValues.set(key, {});
393
+ }
394
+ return operationParamValues.get(key);
395
+ }
396
+
397
+ function getBodyDraft(op) {
398
+ const key = getOperationKey(op);
399
+ return operationBodyDrafts.get(key);
400
+ }
401
+
402
+ function setBodyDraft(op, bodyValue) {
403
+ const key = getOperationKey(op);
404
+ operationBodyDrafts.set(key, bodyValue);
405
+ }
406
+
407
+ function resolvePath(pathTemplate, pathParams, values) {
408
+ let resolved = pathTemplate;
409
+ for (const param of pathParams) {
410
+ const rawValue = values[param.name];
411
+ if (rawValue === undefined || rawValue === null || rawValue === "") {
412
+ continue;
413
+ }
414
+ const placeholder = "{" + param.name + "}";
415
+ resolved = resolved
416
+ .split(placeholder)
417
+ .join(encodeURIComponent(String(rawValue)));
418
+ }
419
+ return resolved;
420
+ }
421
+
422
+ function buildRequestPath(op, pathParams, queryParams, values) {
423
+ const resolvedPath = resolvePath(op.path, pathParams, values);
424
+ const query = new URLSearchParams();
425
+
426
+ for (const param of queryParams) {
427
+ const rawValue = values[param.name];
428
+ if (rawValue === undefined || rawValue === null || rawValue === "") {
429
+ continue;
430
+ }
431
+ query.append(param.name, String(rawValue));
432
+ }
433
+
434
+ const queryString = query.toString();
435
+ return queryString ? resolvedPath + "?" + queryString : resolvedPath;
436
+ }
437
+
438
+ function schemaDefaultValue(schema) {
439
+ if (!schema || typeof schema !== "object") return null;
440
+ if (schema.default !== undefined) return schema.default;
441
+ if (schema.example !== undefined) return schema.example;
442
+ if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum[0];
443
+ if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
444
+ return schemaDefaultValue(schema.oneOf[0]);
445
+ }
446
+ if (Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
447
+ return schemaDefaultValue(schema.anyOf[0]);
448
+ }
449
+ if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
450
+ return schemaDefaultValue(schema.allOf[0]);
451
+ }
452
+
453
+ switch (schema.type) {
454
+ case "string":
455
+ return "";
456
+ case "number":
457
+ case "integer":
458
+ return 0;
459
+ case "boolean":
460
+ return false;
461
+ case "array":
462
+ return [];
463
+ case "object": {
464
+ const required = Array.isArray(schema.required) ? schema.required : [];
465
+ const properties = schema.properties && typeof schema.properties === "object"
466
+ ? schema.properties
467
+ : {};
468
+ const obj = {};
469
+ for (const fieldName of required) {
470
+ obj[fieldName] = schemaDefaultValue(properties[fieldName]);
471
+ }
472
+ return obj;
473
+ }
474
+ default:
475
+ return null;
476
+ }
477
+ }
478
+
479
+ function buildRequiredBodyPrefill(schema) {
480
+ if (!schema || typeof schema !== "object") return "";
481
+ const prefillValue = schemaDefaultValue(schema);
482
+ if (
483
+ prefillValue &&
484
+ typeof prefillValue === "object" &&
485
+ !Array.isArray(prefillValue) &&
486
+ Object.keys(prefillValue).length === 0
487
+ ) {
488
+ return "";
489
+ }
490
+ try {
491
+ return JSON.stringify(prefillValue, null, 2);
492
+ } catch {
493
+ return "";
494
+ }
495
+ }
496
+
497
+ function hasMeaningfulRequestBodySchema(schema) {
498
+ if (!schema || typeof schema !== "object") return false;
499
+ if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) return true;
500
+ if (Array.isArray(schema.anyOf) && schema.anyOf.length > 0) return true;
501
+ if (Array.isArray(schema.allOf) && schema.allOf.length > 0) return true;
502
+ if (schema.type && schema.type !== "object") return true;
503
+ if (schema.additionalProperties !== undefined) return true;
504
+ if (Array.isArray(schema.required) && schema.required.length > 0) return true;
505
+ if (schema.properties && typeof schema.properties === "object") {
506
+ return Object.keys(schema.properties).length > 0;
507
+ }
508
+ return false;
509
+ }
510
+
511
+ function renderSidebar() {
512
+ const nav = document.getElementById("sidebar-nav");
513
+ const groups = new Map();
514
+ const query = sidebarSearchQuery.trim().toLowerCase();
515
+ const visibleOps = query
516
+ ? operations.filter((op) => {
517
+ const haystack = [
518
+ op.name,
519
+ op.path,
520
+ op.method,
521
+ op.tag,
522
+ ]
523
+ .join(" ")
524
+ .toLowerCase();
525
+ return haystack.includes(query);
526
+ })
527
+ : operations;
528
+
529
+ for (const op of visibleOps) {
530
+ if (!groups.has(op.tag)) groups.set(op.tag, []);
531
+ groups.get(op.tag).push(op);
532
+ }
533
+ nav.innerHTML = "";
534
+ if (visibleOps.length === 0) {
535
+ nav.innerHTML =
536
+ '<p class="px-2 text-xs opacity-60">No routes match your search.</p>';
537
+ return;
538
+ }
539
+ for (const [tag, ops] of groups.entries()) {
540
+ const block = document.createElement("div");
541
+ block.innerHTML = '<h3 class="px-2 mb-2 font-semibold text-xs uppercase tracking-wider opacity-50"></h3><ul class="space-y-0.5"></ul>';
542
+ block.querySelector("h3").textContent = tag;
543
+ const list = block.querySelector("ul");
544
+ for (const op of ops) {
545
+ const li = document.createElement("li");
546
+ li.className = "enter-stagger";
547
+ li.style.setProperty("--stagger-delay", String(Math.min(list.children.length * 22, 180)) + "ms");
548
+ const a = document.createElement("a");
549
+ a.href = "#";
550
+ a.className = op === selected
551
+ ? "block px-2 py-1.5 rounded-md bg-black/5 dark:bg-white/5 text-brand font-medium transition-colors"
552
+ : "block px-2 py-1.5 rounded-md hover:bg-black/5 dark:hover:bg-white/5 transition-colors";
553
+
554
+ const row = document.createElement("span");
555
+ row.className = "flex items-center gap-2";
556
+
557
+ const method = document.createElement("span");
558
+ method.className = "px-1.5 py-0.5 rounded text-[10px] font-mono font-semibold " + (methodBadge[op.method] || "bg-zinc-100 text-zinc-700 dark:bg-zinc-500/10 dark:text-zinc-400");
559
+ method.textContent = op.method;
560
+
561
+ const name = document.createElement("span");
562
+ name.textContent = op.name;
563
+
564
+ row.appendChild(method);
565
+ row.appendChild(name);
566
+ a.appendChild(row);
567
+
568
+ a.onclick = (e) => {
569
+ e.preventDefault();
570
+ selected = op;
571
+ renderSidebar();
572
+ renderEndpoint();
573
+ if (window.innerWidth < 768) {
574
+ setMobileSidebarOpen(false);
575
+ }
576
+ };
577
+ li.appendChild(a);
578
+ list.appendChild(li);
579
+ }
580
+ nav.appendChild(block);
581
+ }
582
+ }
583
+
584
+ function renderParamSection(title, params) {
585
+ if (!params.length) return "";
586
+ let rows = "";
587
+ for (const p of params) {
588
+ const type = escapeHtml((p.schema && p.schema.type) || "unknown");
589
+ const name = escapeHtml(p.name || "");
590
+ rows += '<div class="py-2 flex justify-between border-b border-light-border/50 dark:border-dark-border/50"><div><code class="text-sm font-mono">' + name + '</code><span class="text-xs text-brand ml-2">' + (p.required ? "required" : "optional") + '</span></div><span class="text-xs font-mono opacity-60">' + type + '</span></div>';
591
+ }
592
+ return '<div><h3 class="text-sm font-semibold mb-3 flex items-center border-b border-light-border dark:border-dark-border pb-2">' + escapeHtml(title) + "</h3>" + rows + "</div>";
593
+ }
594
+
595
+ function getSchemaTypeLabel(schema) {
596
+ if (!schema || typeof schema !== "object") return "unknown";
597
+ if (Array.isArray(schema.type)) return schema.type.join(" | ");
598
+ if (schema.type) return String(schema.type);
599
+ if (schema.properties) return "object";
600
+ if (schema.items) return "array";
601
+ if (Array.isArray(schema.oneOf)) return "oneOf";
602
+ if (Array.isArray(schema.anyOf)) return "anyOf";
603
+ if (Array.isArray(schema.allOf)) return "allOf";
604
+ return "unknown";
605
+ }
606
+
607
+ function buildSchemaChildren(schema) {
608
+ if (!schema || typeof schema !== "object") return [];
609
+
610
+ const children = [];
611
+
612
+ if (schema.properties && typeof schema.properties === "object") {
613
+ const requiredSet = new Set(
614
+ Array.isArray(schema.required) ? schema.required : [],
615
+ );
616
+ for (const [name, childSchema] of Object.entries(schema.properties)) {
617
+ children.push({
618
+ name,
619
+ schema: childSchema || {},
620
+ required: requiredSet.has(name),
621
+ });
622
+ }
623
+ }
624
+
625
+ if (schema.items) {
626
+ children.push({
627
+ name: "items[]",
628
+ schema: schema.items,
629
+ required: true,
630
+ });
631
+ }
632
+
633
+ return children;
634
+ }
635
+
636
+ function renderSchemaFieldNode(field, depth) {
637
+ const schema = field.schema || {};
638
+ const name = escapeHtml(field.name || "field");
639
+ const requiredLabel = field.required ? "required" : "optional";
640
+ const type = escapeHtml(getSchemaTypeLabel(schema));
641
+ const children = buildSchemaChildren(schema);
642
+ const padding = depth * 14;
643
+
644
+ if (!children.length) {
645
+ return (
646
+ '<div class="py-2 border-b border-light-border/50 dark:border-dark-border/50" style="padding-left:' +
647
+ padding +
648
+ 'px"><div class="flex justify-between"><div><code class="text-sm font-mono">' +
649
+ name +
650
+ '</code><span class="text-xs text-brand ml-2">' +
651
+ requiredLabel +
652
+ '</span></div><span class="text-xs font-mono opacity-60">' +
653
+ type +
654
+ "</span></div></div>"
655
+ );
656
+ }
657
+
658
+ let nested = "";
659
+ for (const child of children) {
660
+ nested += renderSchemaFieldNode(child, depth + 1);
661
+ }
662
+
663
+ return (
664
+ '<details class="border-b border-light-border/50 dark:border-dark-border/50" open>' +
665
+ '<summary class="list-none cursor-pointer py-2 flex justify-between items-center" style="padding-left:' +
666
+ padding +
667
+ 'px"><div class="flex items-center gap-2"><span class="text-xs opacity-70">▾</span><code class="text-sm font-mono">' +
668
+ name +
669
+ '</code><span class="text-xs text-brand">' +
670
+ requiredLabel +
671
+ '</span></div><span class="text-xs font-mono opacity-60">' +
672
+ type +
673
+ "</span></summary>" +
674
+ '<div class="pb-1">' +
675
+ nested +
676
+ "</div></details>"
677
+ );
678
+ }
679
+
680
+ function renderRequestBodySchemaSection(schema) {
681
+ if (!schema || typeof schema !== "object") return "";
682
+ const rootChildren = buildSchemaChildren(schema);
683
+ if (!rootChildren.length) return "";
684
+
685
+ let rows = "";
686
+ for (const child of rootChildren) {
687
+ rows += renderSchemaFieldNode(child, 0);
688
+ }
689
+
690
+ return (
691
+ '<div><h3 class="text-sm font-semibold mb-3 flex items-center border-b border-light-border dark:border-dark-border pb-2">Request Body</h3>' +
692
+ rows +
693
+ "</div>"
694
+ );
695
+ }
696
+
697
+ function renderTryItParameterInputs(pathParams, queryParams) {
698
+ const container = document.getElementById("request-param-inputs");
699
+ if (!container || !selected) return;
700
+
701
+ const values = getParameterValues(selected);
702
+ container.innerHTML = "";
703
+
704
+ const sections = [
705
+ { title: "Path Values", params: pathParams },
706
+ { title: "Query Values", params: queryParams },
707
+ ];
708
+
709
+ for (const section of sections) {
710
+ if (!section.params.length) continue;
711
+
712
+ const group = document.createElement("div");
713
+ group.className = "space-y-2";
714
+
715
+ const title = document.createElement("p");
716
+ title.className = "text-xs font-semibold uppercase tracking-wider opacity-60";
717
+ title.textContent = section.title;
718
+ group.appendChild(title);
719
+
720
+ for (const param of section.params) {
721
+ const field = document.createElement("div");
722
+ field.className = "space-y-1";
723
+
724
+ const label = document.createElement("label");
725
+ label.className = "text-xs opacity-80 flex items-center gap-2";
726
+
727
+ const labelName = document.createElement("span");
728
+ labelName.className = "font-mono";
729
+ labelName.textContent = param.name;
730
+
731
+ const required = document.createElement("span");
732
+ required.className = "text-[10px] text-brand";
733
+ required.textContent = param.required ? "required" : "optional";
734
+
735
+ label.appendChild(labelName);
736
+ label.appendChild(required);
737
+
738
+ const input = document.createElement("input");
739
+ input.type = "text";
740
+ input.value = values[param.name] || "";
741
+ input.placeholder =
742
+ section.title === "Path Values" ? param.name : "optional";
743
+ input.className =
744
+ "w-full text-sm px-3 py-2 rounded border border-light-border dark:border-dark-border bg-light-bg dark:bg-dark-bg focus:outline-none focus:border-brand dark:focus:border-brand transition-colors font-mono";
745
+
746
+ input.addEventListener("input", () => {
747
+ values[param.name] = input.value;
748
+ updateRequestPreview();
749
+ });
750
+
751
+ field.appendChild(label);
752
+ field.appendChild(input);
753
+ group.appendChild(field);
754
+ }
755
+
756
+ container.appendChild(group);
757
+ }
758
+ }
759
+
760
+ function renderHeaderInputs() {
761
+ const container = document.getElementById("header-inputs");
762
+ if (!container) return;
763
+
764
+ container.innerHTML = "";
765
+ requestHeaders.forEach((entry, index) => {
766
+ const row = document.createElement("div");
767
+ row.className = "grid grid-cols-[1fr_1fr_auto] gap-2";
768
+
769
+ const keyInput = document.createElement("input");
770
+ keyInput.type = "text";
771
+ keyInput.value = entry.key || "";
772
+ keyInput.placeholder = "Header";
773
+ keyInput.className =
774
+ "w-full text-xs px-2.5 py-2 rounded border border-light-border dark:border-dark-border bg-light-bg dark:bg-dark-bg focus:outline-none focus:border-brand dark:focus:border-brand transition-colors font-mono";
775
+ keyInput.addEventListener("input", () => {
776
+ entry.key = keyInput.value;
777
+ updateRequestPreview();
778
+ });
779
+
780
+ const valueInput = document.createElement("input");
781
+ valueInput.type = "text";
782
+ valueInput.value = entry.value || "";
783
+ valueInput.placeholder =
784
+ String(entry.key || "").toLowerCase() === "authorization"
785
+ ? "Bearer token"
786
+ : "Value";
787
+ valueInput.className =
788
+ "w-full text-xs px-2.5 py-2 rounded border border-light-border dark:border-dark-border bg-light-bg dark:bg-dark-bg focus:outline-none focus:border-brand dark:focus:border-brand transition-colors font-mono";
789
+ valueInput.addEventListener("input", () => {
790
+ entry.value = valueInput.value;
791
+ updateRequestPreview();
792
+ });
793
+
794
+ const removeButton = document.createElement("button");
795
+ removeButton.type = "button";
796
+ removeButton.className =
797
+ "p-1.5 rounded-full border border-light-border dark:border-dark-border bg-light-bg/90 dark:bg-dark-bg/90 opacity-90 hover:opacity-100 hover:border-brand/60 transition-colors";
798
+ removeButton.setAttribute("aria-label", "Remove Header");
799
+ removeButton.setAttribute("title", "Remove Header");
800
+ removeButton.innerHTML =
801
+ '<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 12h12"></path></svg>';
802
+ removeButton.addEventListener("click", () => {
803
+ requestHeaders.splice(index, 1);
804
+ renderHeaderInputs();
805
+ updateRequestPreview();
806
+ });
807
+
808
+ row.appendChild(keyInput);
809
+ row.appendChild(valueInput);
810
+ row.appendChild(removeButton);
811
+ container.appendChild(row);
812
+ });
813
+ }
814
+
815
+ function hasHeaderName(headers, expectedName) {
816
+ const target = expectedName.toLowerCase();
817
+ return Object.keys(headers).some((key) => key.toLowerCase() === target);
818
+ }
819
+
820
+ function getRequestHeadersObject() {
821
+ const headers = {};
822
+ for (const entry of requestHeaders) {
823
+ const key = String(entry.key || "").trim();
824
+ const value = String(entry.value || "").trim();
825
+ if (!key || !value) continue;
826
+ headers[key] = value;
827
+ }
828
+ return headers;
829
+ }
830
+
831
+ function buildCurl(op, headers, body, requestPath) {
832
+ const url = window.location.origin + requestPath;
833
+ const lines = ['curl -X ' + op.method + ' "' + url + '"'];
834
+
835
+ for (const [name, value] of Object.entries(headers)) {
836
+ const safeName = String(name).replace(/"/g, '\\"');
837
+ const safeValue = String(value).replace(/"/g, '\\"');
838
+ lines.push(' -H "' + safeName + ": " + safeValue + '"');
839
+ }
840
+
841
+ if (body) {
842
+ lines.push(" -d '" + body.replace(/'/g, "'\\\\''") + "'");
843
+ }
844
+
845
+ return lines.join(" \\\\\\n");
846
+ }
847
+
848
+ function formatBodyJsonInput() {
849
+ const bodyInput = document.getElementById("body-input");
850
+ if (!bodyInput) return;
851
+ const current = bodyInput.value.trim();
852
+ if (!current) return;
853
+ try {
854
+ bodyInput.value = JSON.stringify(JSON.parse(current), null, 2);
855
+ } catch {}
856
+ }
857
+
858
+ function escapeHtml(value) {
859
+ return String(value)
860
+ .replace(/&/g, "&amp;")
861
+ .replace(/</g, "&lt;")
862
+ .replace(/>/g, "&gt;");
863
+ }
864
+
865
+ function toPrettyJson(value) {
866
+ const trimmed = (value || "").trim();
867
+ if (!trimmed) return null;
868
+ try {
869
+ return JSON.stringify(JSON.parse(trimmed), null, 2);
870
+ } catch {
871
+ return null;
872
+ }
873
+ }
874
+
875
+ function highlightJson(jsonText) {
876
+ const escaped = escapeHtml(jsonText);
877
+ return escaped.replace(
878
+ /("(\\\\u[a-zA-Z0-9]{4}|\\\\[^u]|[^\\\\"])*"(\\s*:)?|\\btrue\\b|\\bfalse\\b|\\bnull\\b|-?\\d+(?:\\.\\d+)?(?:[eE][+\\-]?\\d+)?)/g,
879
+ (match) => {
880
+ let cls = "json-number";
881
+ if (match.startsWith('"')) {
882
+ cls = match.endsWith(":") ? "json-key" : "json-string";
883
+ } else if (match === "true" || match === "false") {
884
+ cls = "json-boolean";
885
+ } else if (match === "null") {
886
+ cls = "json-null";
887
+ }
888
+ return '<span class="' + cls + '">' + match + "</span>";
889
+ },
890
+ );
891
+ }
892
+
893
+ function updateBodyJsonPresentation() {
894
+ const bodyInput = document.getElementById("body-input");
895
+ const highlight = document.getElementById("body-highlight");
896
+ const bodySection = document.getElementById("request-body-section");
897
+
898
+ if (!bodyInput || !highlight || !bodySection) return;
899
+ if (bodySection.classList.contains("hidden")) {
900
+ highlight.innerHTML = "";
901
+ return;
902
+ }
903
+
904
+ const raw = bodyInput.value || "";
905
+ if (!raw.trim()) {
906
+ const placeholder = bodyInput.getAttribute("placeholder") || "";
907
+ highlight.innerHTML = '<span class="opacity-40">' + escapeHtml(placeholder) + "</span>";
908
+ return;
909
+ }
910
+
911
+ const prettyJson = toPrettyJson(raw);
912
+ if (!prettyJson) {
913
+ highlight.innerHTML = escapeHtml(raw);
914
+ return;
915
+ }
916
+
917
+ highlight.innerHTML = highlightJson(raw);
918
+ }
919
+
920
+ function syncBodyEditorScroll() {
921
+ const bodyInput = document.getElementById("body-input");
922
+ const highlight = document.getElementById("body-highlight");
923
+ if (!bodyInput || !highlight) return;
924
+ highlight.scrollTop = bodyInput.scrollTop;
925
+ highlight.scrollLeft = bodyInput.scrollLeft;
926
+ }
927
+
928
+ function updateExpandEditorPresentation() {
929
+ const editor = document.getElementById("expand-editor");
930
+ const highlight = document.getElementById("expand-editor-highlight");
931
+ if (!editor || !highlight) return;
932
+ const raw = editor.value || "";
933
+ if (!raw.trim()) {
934
+ highlight.innerHTML = "";
935
+ return;
936
+ }
937
+ const prettyJson = toPrettyJson(raw);
938
+ highlight.innerHTML = prettyJson ? highlightJson(raw) : escapeHtml(raw);
939
+ }
940
+
941
+ function syncExpandEditorScroll() {
942
+ const editor = document.getElementById("expand-editor");
943
+ const highlight = document.getElementById("expand-editor-highlight");
944
+ if (!editor || !highlight) return;
945
+ highlight.scrollTop = editor.scrollTop;
946
+ highlight.scrollLeft = editor.scrollLeft;
947
+ }
948
+
949
+ function formatResponseText(responseText) {
950
+ const trimmed = (responseText || "").trim();
951
+ if (!trimmed) return { text: "(empty)", isJson: false };
952
+ try {
953
+ return {
954
+ text: JSON.stringify(JSON.parse(trimmed), null, 2),
955
+ isJson: true,
956
+ };
957
+ } catch {
958
+ return {
959
+ text: responseText,
960
+ isJson: false,
961
+ };
962
+ }
963
+ }
964
+
965
+ function setResponseContent(headerText, bodyText, isJson) {
966
+ const result = document.getElementById("result");
967
+ if (!result) return;
968
+ const fullText = String(headerText || "") + String(bodyText || "");
969
+ result.dataset.raw = fullText;
970
+ result.dataset.header = String(headerText || "");
971
+ result.dataset.body = String(bodyText || "");
972
+ result.dataset.isJson = isJson ? "true" : "false";
973
+ if (isJson) {
974
+ result.innerHTML = escapeHtml(String(headerText || "")) + highlightJson(String(bodyText || ""));
975
+ } else {
976
+ result.textContent = fullText;
977
+ }
978
+ }
979
+
980
+ function updateRequestPreview() {
981
+ if (!selected) return;
982
+
983
+ const { path, query } = getOperationParameterGroups(selected);
984
+ const values = getParameterValues(selected);
985
+ const requestPath = buildRequestPath(selected, path, query, values);
986
+ const bodyInput = document.getElementById("body-input");
987
+ const body = bodyInput ? bodyInput.value.trim() : "";
988
+ const headers = getRequestHeadersObject();
989
+ if (body && !hasHeaderName(headers, "Content-Type")) {
990
+ headers["Content-Type"] = "application/json";
991
+ }
992
+
993
+ document.getElementById("endpoint-path").textContent = requestPath;
994
+ document.getElementById("curl-code").textContent = buildCurl(
995
+ selected,
996
+ headers,
997
+ body,
998
+ requestPath,
999
+ );
1000
+ }
1001
+
1002
+ function renderEndpoint() {
1003
+ if (!selected) return;
1004
+ const endpointCard = document.getElementById("endpoint-card");
1005
+ if (endpointCard) {
1006
+ endpointCard.classList.remove("enter-fade-up");
1007
+ // Restart CSS animation for each operation switch
1008
+ void endpointCard.offsetWidth;
1009
+ endpointCard.classList.add("enter-fade-up");
1010
+ }
1011
+
1012
+ const op = selected.operation || {};
1013
+ const reqSchema = op.requestBody && op.requestBody.content && op.requestBody.content["application/json"] && op.requestBody.content["application/json"].schema;
1014
+ const requestBodySection = document.getElementById("request-body-section");
1015
+ const bodyInput = document.getElementById("body-input");
1016
+ const expandBodyBtn = document.getElementById("expand-body-btn");
1017
+ const supportsBody = hasMeaningfulRequestBodySchema(reqSchema);
1018
+
1019
+ if (requestBodySection) {
1020
+ requestBodySection.classList.toggle("hidden", !supportsBody);
1021
+ }
1022
+ if (supportsBody && bodyInput) {
1023
+ const existingDraft = getBodyDraft(selected);
1024
+ if (typeof existingDraft === "string") {
1025
+ bodyInput.value = existingDraft;
1026
+ } else {
1027
+ const prefill = buildRequiredBodyPrefill(reqSchema);
1028
+ bodyInput.value = prefill;
1029
+ setBodyDraft(selected, prefill);
1030
+ }
1031
+ } else if (!supportsBody && bodyInput) {
1032
+ bodyInput.value = "";
1033
+ }
1034
+ if (expandBodyBtn) {
1035
+ expandBodyBtn.disabled = !supportsBody;
1036
+ }
1037
+ setResponseContent("", "", false);
1038
+
1039
+ document.getElementById("tag-title").textContent = selected.tag;
1040
+ document.getElementById("tag-description").textContent = op.description || "Interactive API documentation.";
1041
+ const methodNode = document.getElementById("endpoint-method");
1042
+ methodNode.textContent = selected.method;
1043
+ methodNode.className = "px-2.5 py-0.5 rounded-full text-xs font-mono font-medium " + (methodBadge[selected.method] || "bg-zinc-100 text-zinc-700 dark:bg-zinc-500/10 dark:text-zinc-400");
1044
+ document.getElementById("endpoint-title").textContent = selected.name;
1045
+ document.getElementById("endpoint-path").textContent = selected.path;
1046
+
1047
+ const { all: params, query, path, headers } =
1048
+ getOperationParameterGroups(selected);
1049
+
1050
+ let html = "";
1051
+ html += renderParamSection("Path Parameters", path);
1052
+ html += renderParamSection("Query Parameters", query);
1053
+ html += renderParamSection("Header Parameters", headers);
1054
+
1055
+ html += renderRequestBodySchemaSection(reqSchema);
1056
+ document.getElementById("params-column").innerHTML = html || '<div class="text-sm opacity-70">No parameters</div>';
1057
+ renderTryItParameterInputs(path, query);
1058
+ renderHeaderInputs();
1059
+ updateRequestPreview();
1060
+ updateBodyJsonPresentation();
1061
+ syncBodyEditorScroll();
1062
+ }
1063
+
1064
+ document.getElementById("copy-curl").addEventListener("click", async () => {
1065
+ try { await navigator.clipboard.writeText(document.getElementById("curl-code").textContent || ""); } catch {}
1066
+ });
1067
+ document.getElementById("sidebar-search").addEventListener("input", (event) => {
1068
+ sidebarSearchQuery = event.currentTarget.value || "";
1069
+ renderSidebar();
1070
+ });
1071
+
1072
+ document.getElementById("send-btn").addEventListener("click", async () => {
1073
+ if (!selected) return;
1074
+ const { path, query } = getOperationParameterGroups(selected);
1075
+ const values = getParameterValues(selected);
1076
+ const missingPathParams = path.filter((param) => {
1077
+ if (param.required === false) return false;
1078
+ const value = values[param.name];
1079
+ return value === undefined || value === null || String(value).trim() === "";
1080
+ });
1081
+
1082
+ if (missingPathParams.length > 0) {
1083
+ setResponseContent(
1084
+ "",
1085
+ "Missing required path parameter(s): " +
1086
+ missingPathParams.map((param) => param.name).join(", "),
1087
+ false,
1088
+ );
1089
+ return;
1090
+ }
1091
+
1092
+ const requestPath = buildRequestPath(selected, path, query, values);
1093
+ formatBodyJsonInput();
1094
+ updateBodyJsonPresentation();
1095
+ const op = selected.operation || {};
1096
+ const reqSchema = op.requestBody && op.requestBody.content && op.requestBody.content["application/json"] && op.requestBody.content["application/json"].schema;
1097
+ const supportsBody = hasMeaningfulRequestBodySchema(reqSchema);
1098
+ const bodyInput = document.getElementById("body-input");
1099
+ const body =
1100
+ supportsBody && bodyInput ? bodyInput.value.trim() : "";
1101
+ const headers = getRequestHeadersObject();
1102
+ if (body && !hasHeaderName(headers, "Content-Type")) {
1103
+ headers["Content-Type"] = "application/json";
1104
+ }
1105
+
1106
+ try {
1107
+ const response = await fetch(requestPath, { method: selected.method, headers, body: body || undefined });
1108
+ const text = await response.text();
1109
+ const contentType = response.headers.get("content-type") || "unknown";
1110
+ const formattedResponse = formatResponseText(text);
1111
+ const headerText =
1112
+ "Status: " + response.status + " " + response.statusText + "\\n" +
1113
+ "Content-Type: " + contentType + "\\n\\n";
1114
+ setResponseContent(
1115
+ headerText,
1116
+ formattedResponse.text,
1117
+ formattedResponse.isJson,
1118
+ );
1119
+ } catch (error) {
1120
+ setResponseContent("", "Request failed: " + String(error), false);
1121
+ }
1122
+ });
1123
+
1124
+ function openExpandModal(mode) {
1125
+ const modal = document.getElementById("expand-modal");
1126
+ const title = document.getElementById("expand-modal-title");
1127
+ const editorShell = document.getElementById("expand-editor-shell");
1128
+ const editor = document.getElementById("expand-editor");
1129
+ const viewer = document.getElementById("expand-viewer");
1130
+ const apply = document.getElementById("expand-apply");
1131
+ const bodyInput = document.getElementById("body-input");
1132
+ const result = document.getElementById("result");
1133
+ if (!modal || !title || !editorShell || !editor || !viewer || !apply) return;
1134
+
1135
+ expandModalMode = mode;
1136
+ modal.classList.remove("hidden");
1137
+ modal.classList.add("flex");
1138
+
1139
+ if (mode === "body") {
1140
+ title.textContent = "Request Body";
1141
+ editorShell.classList.remove("hidden");
1142
+ viewer.classList.add("hidden");
1143
+ apply.classList.remove("hidden");
1144
+ editor.value = bodyInput ? bodyInput.value : "";
1145
+ updateExpandEditorPresentation();
1146
+ syncExpandEditorScroll();
1147
+ } else {
1148
+ title.textContent = "Response";
1149
+ viewer.classList.remove("hidden");
1150
+ editorShell.classList.add("hidden");
1151
+ apply.classList.add("hidden");
1152
+ const hasResponse = Boolean(result && result.dataset && result.dataset.raw);
1153
+ if (!hasResponse) {
1154
+ viewer.textContent = "(empty response yet)";
1155
+ return;
1156
+ }
1157
+
1158
+ const header = result.dataset.header || "";
1159
+ const body = result.dataset.body || "";
1160
+ const isJson = result.dataset.isJson === "true";
1161
+ if (isJson) {
1162
+ viewer.innerHTML = escapeHtml(header) + highlightJson(body);
1163
+ } else {
1164
+ viewer.textContent = result.dataset.raw || "(empty response yet)";
1165
+ }
1166
+ }
1167
+ }
1168
+
1169
+ function closeExpandModal() {
1170
+ const modal = document.getElementById("expand-modal");
1171
+ if (!modal) return;
1172
+ modal.classList.add("hidden");
1173
+ modal.classList.remove("flex");
1174
+ expandModalMode = null;
1175
+ }
1176
+
1177
+ document.getElementById("add-header-btn").addEventListener("click", () => {
1178
+ requestHeaders.push({ key: "", value: "" });
1179
+ renderHeaderInputs();
1180
+ updateRequestPreview();
1181
+ });
1182
+ document.getElementById("body-input").addEventListener("input", () => {
1183
+ if (selected) {
1184
+ setBodyDraft(selected, document.getElementById("body-input").value);
1185
+ }
1186
+ updateRequestPreview();
1187
+ updateBodyJsonPresentation();
1188
+ syncBodyEditorScroll();
1189
+ });
1190
+ document.getElementById("body-input").addEventListener("scroll", () => {
1191
+ syncBodyEditorScroll();
1192
+ });
1193
+ document.getElementById("body-input").addEventListener("keydown", (event) => {
1194
+ if (event.key !== "Tab") return;
1195
+ event.preventDefault();
1196
+ const input = event.currentTarget;
1197
+ const start = input.selectionStart;
1198
+ const end = input.selectionEnd;
1199
+ const value = input.value;
1200
+ const tab = " ";
1201
+ input.value = value.slice(0, start) + tab + value.slice(end);
1202
+ input.selectionStart = input.selectionEnd = start + tab.length;
1203
+ if (selected) {
1204
+ setBodyDraft(selected, input.value);
1205
+ }
1206
+ updateRequestPreview();
1207
+ updateBodyJsonPresentation();
1208
+ syncBodyEditorScroll();
1209
+ });
1210
+ document.getElementById("body-input").addEventListener("blur", () => {
1211
+ formatBodyJsonInput();
1212
+ if (selected) {
1213
+ setBodyDraft(selected, document.getElementById("body-input").value);
1214
+ }
1215
+ updateRequestPreview();
1216
+ updateBodyJsonPresentation();
1217
+ syncBodyEditorScroll();
1218
+ });
1219
+ document.getElementById("expand-editor").addEventListener("input", () => {
1220
+ updateExpandEditorPresentation();
1221
+ syncExpandEditorScroll();
1222
+ });
1223
+ document.getElementById("expand-editor").addEventListener("scroll", () => {
1224
+ syncExpandEditorScroll();
1225
+ });
1226
+ document.getElementById("expand-editor").addEventListener("keydown", (event) => {
1227
+ if (event.key !== "Tab") return;
1228
+ event.preventDefault();
1229
+ const editor = event.currentTarget;
1230
+ const start = editor.selectionStart;
1231
+ const end = editor.selectionEnd;
1232
+ const value = editor.value;
1233
+ const tab = " ";
1234
+ editor.value = value.slice(0, start) + tab + value.slice(end);
1235
+ editor.selectionStart = editor.selectionEnd = start + tab.length;
1236
+ updateExpandEditorPresentation();
1237
+ syncExpandEditorScroll();
1238
+ });
1239
+ document.getElementById("expand-editor").addEventListener("blur", () => {
1240
+ const editor = document.getElementById("expand-editor");
1241
+ const current = editor.value.trim();
1242
+ if (current) {
1243
+ try {
1244
+ editor.value = JSON.stringify(JSON.parse(current), null, 2);
1245
+ } catch {}
1246
+ }
1247
+ updateExpandEditorPresentation();
1248
+ syncExpandEditorScroll();
1249
+ });
1250
+ document.getElementById("expand-body-btn").addEventListener("click", () => {
1251
+ openExpandModal("body");
1252
+ });
1253
+ document.getElementById("expand-response-btn").addEventListener("click", () => {
1254
+ openExpandModal("response");
1255
+ });
1256
+ document.getElementById("expand-close").addEventListener("click", closeExpandModal);
1257
+ document.getElementById("expand-apply").addEventListener("click", () => {
1258
+ if (expandModalMode !== "body") {
1259
+ closeExpandModal();
1260
+ return;
1261
+ }
1262
+
1263
+ const editor = document.getElementById("expand-editor");
1264
+ const bodyInput = document.getElementById("body-input");
1265
+ if (editor && bodyInput) {
1266
+ bodyInput.value = editor.value;
1267
+ formatBodyJsonInput();
1268
+ if (selected) {
1269
+ setBodyDraft(selected, bodyInput.value);
1270
+ }
1271
+ updateRequestPreview();
1272
+ updateBodyJsonPresentation();
1273
+ syncBodyEditorScroll();
1274
+ }
1275
+ closeExpandModal();
1276
+ });
1277
+ document.getElementById("expand-modal").addEventListener("click", (event) => {
1278
+ if (event.target === event.currentTarget) {
1279
+ closeExpandModal();
1280
+ }
1281
+ });
1282
+ document.getElementById("sidebar-open").addEventListener("click", () => {
1283
+ setMobileSidebarOpen(true);
1284
+ });
1285
+ document.getElementById("sidebar-close").addEventListener("click", () => {
1286
+ setMobileSidebarOpen(false);
1287
+ });
1288
+ document.getElementById("mobile-backdrop").addEventListener("click", () => {
1289
+ setMobileSidebarOpen(false);
1290
+ });
1291
+ window.addEventListener("resize", () => {
1292
+ if (window.innerWidth >= 768 && isMobileSidebarOpen) {
1293
+ setMobileSidebarOpen(false);
1294
+ }
1295
+ });
1296
+ document.addEventListener("keydown", (event) => {
1297
+ if (event.key === "Escape") {
1298
+ if (isMobileSidebarOpen) {
1299
+ setMobileSidebarOpen(false);
1300
+ }
1301
+ closeExpandModal();
1302
+ }
1303
+ });
1304
+
1305
+ const themeToggleBtn = document.getElementById('theme-toggle');
1306
+ const htmlElement = document.documentElement;
1307
+ themeToggleBtn.addEventListener('click', () => {
1308
+ htmlElement.classList.toggle('dark');
1309
+ if (htmlElement.classList.contains('dark')) {
1310
+ localStorage.setItem('theme', 'dark');
1311
+ } else {
1312
+ localStorage.setItem('theme', 'light');
1313
+ }
1314
+ });
1315
+ window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
1316
+ if (!('theme' in localStorage)) {
1317
+ if (e.matches) htmlElement.classList.add('dark');
1318
+ else htmlElement.classList.remove('dark');
1319
+ }
1320
+ });
1321
+
1322
+ setMobileSidebarOpen(false);
1323
+ renderSidebar();
1324
+ renderEndpoint();
1325
+ </script>
1326
+ </body>
1327
+ </html>`}function de(e){let t=e?.["~standard"],n=t?.jsonSchema;return!!t&&typeof t==="object"&&t.version===1&&!!n&&typeof n.input==="function"&&typeof n.output==="function"}function re(e){let t=0,n=[];return{openapiPath:e.split("/").map((r)=>{let a=/^:([A-Za-z0-9_]+)\+$/.exec(r);if(a?.[1])return n.push(a[1]),`{${a[1]}}`;let o=/^:([A-Za-z0-9_]+)$/.exec(r);if(o?.[1])return n.push(o[1]),`{${o[1]}}`;if(r==="*"){t+=1;let l=t===1?"wildcard":`wildcard${t}`;return n.push(l),`{${l}}`}return r}).join("/"),pathParamNames:n}}function ve(e){return re(e).openapiPath}function ke(e,t){return`${e.toLowerCase()}_${t}`.replace(/[:{}]/g,"").replace(/[^A-Za-z0-9_]+/g,"_").replace(/^_+|_+$/g,"")||`${e.toLowerCase()}_operation`}function Ee(e){let t=e.split("/").filter(Boolean);for(let n of t)if(!n.startsWith(":")&&n!=="*")return n.toLowerCase();return"default"}function we(e){return re(e).pathParamNames}function Ie(e,t){let n=new Set((e.parameters||[]).filter((d)=>d.in==="path").map((d)=>String(d.name)));for(let d of we(t)){if(n.has(d))continue;(e.parameters||=[]).push({name:d,in:"path",required:!0,schema:{type:"string"}})}}function Be(e){let t=Number(e);if(!Number.isInteger(t))return!1;return t>=100&&t<200||t===204||t===205||t===304}function Ae(e){if(e==="204")return"No Content";if(e==="205")return"Reset Content";if(e==="304")return"Not Modified";let t=Number(e);if(Number.isInteger(t)&&t>=100&&t<200)return"Informational";return"OK"}function Le(e,t,n,d){if(!de(t))return null;try{return t["~standard"].jsonSchema.input({target:n})}catch(r){return d.push(`[OpenAPI] Failed input schema conversion for ${e}: ${r instanceof Error?r.message:String(r)}`),null}}function ne(e,t,n,d,r){if(!de(n))return null;try{return n["~standard"].jsonSchema.output({target:d})}catch(a){return r.push(`[OpenAPI] Failed output schema conversion for ${e} (${t}): ${a instanceof Error?a.message:String(a)}`),null}}function w(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function Ce(e,t){if(!w(t))return;if(t.type!=="object"||!w(t.properties)){e.requestBody={required:!0,content:{"application/json":{schema:t}}};return}let n=new Set(Array.isArray(t.required)?t.required:[]),d=t.properties,r=Array.isArray(e.parameters)?e.parameters:[],a=[{key:"params",in:"path"},{key:"query",in:"query"},{key:"headers",in:"header"},{key:"cookies",in:"cookie"}];for(let l of a){let i=d[l.key];if(!w(i))continue;if(i.type!=="object"||!w(i.properties))continue;let b=new Set(Array.isArray(i.required)?i.required:[]);for(let[s,u]of Object.entries(i.properties))r.push({name:s,in:l.in,required:l.in==="path"?!0:b.has(s),schema:w(u)?u:{}})}if(r.length>0){let l=new Map;for(let i of r)l.set(`${i.in}:${i.name}`,i);e.parameters=[...l.values()]}let o=d.body;if(o)e.requestBody={required:n.has("body"),content:{"application/json":{schema:w(o)?o:{}}}}}function Oe(e,t,n,d,r){let a=n.output;if(!a){e.responses={200:{description:"OK"}};return}let o={};if(typeof a==="object"&&a!==null&&"~standard"in a){let l=ne(t,"200",a,d,r);if(l)o["200"]={description:"OK",content:{"application/json":{schema:l}}};else o["200"]={description:"OK"}}else for(let[l,i]of Object.entries(a)){let b=String(l),s=ne(t,b,i,d,r),u=Ae(b);if(s&&!Be(b))o[b]={description:u,content:{"application/json":{schema:s}}};else o[b]={description:u}}if(Object.keys(o).length===0)o["200"]={description:"OK"};e.responses=o}function ae(e,t){let n=[],d={};for(let o of e){if(o.options.expose===!1)continue;if(!o.method||!o.path)continue;let l=o.method.toLowerCase();if(l==="options")continue;let i=ve(o.path),b={operationId:ke(l,i),tags:[o.options.schema?.tag||Ee(o.path)]},s=Le(o.path,o.options.schema?.input,t.target,n);if(s)Ce(b,s);Ie(b,o.path),Oe(b,o.path,o.options.schema||{},t.target,n),d[i]||={},d[i][l]=b}return{document:{openapi:t.target==="openapi-3.0"?"3.0.3":"3.1.0",info:{title:t.info?.title||"Vector API",version:t.info?.version||"1.0.0",...t.info?.description?{description:t.info.description}:{}},paths:d},warnings:n}}var U="/_vector/openapi/tailwindcdn.js",De=["../openapi/assets/tailwindcdn.js","../src/openapi/assets/tailwindcdn.js","../../src/openapi/assets/tailwindcdn.js"],Ne=["src/openapi/assets/tailwindcdn.js","openapi/assets/tailwindcdn.js","dist/openapi/assets/tailwindcdn.js"],Se="/* OpenAPI docs runtime asset missing: tailwind disabled */";function je(){for(let t of De)try{let n=new URL(t,import.meta.url);if(oe(n))return Bun.file(n)}catch{}let e=process.cwd();for(let t of Ne){let n=B(e,t);if(oe(n))return Bun.file(n)}return null}var le=je(),F="public, max-age=0, must-revalidate",ie="public, max-age=31536000, immutable";class J{server=null;router;config;openapiConfig;openapiDocCache=null;openapiDocsHtmlCache=null;openapiWarningsLogged=!1;openapiTailwindMissingLogged=!1;corsHandler=null;corsHeadersEntries=null;constructor(e,t){if(this.router=e,this.config=t,this.openapiConfig=this.normalizeOpenAPIConfig(t.openapi,t.development),t.cors){let n=this.normalizeCorsOptions(t.cors),{preflight:d,corsify:r}=ee(n);if(this.corsHandler={preflight:d,corsify:r},typeof n.origin==="string"&&(n.origin!=="*"||!n.credentials)){let o={"access-control-allow-origin":n.origin,"access-control-allow-methods":n.allowMethods,"access-control-allow-headers":n.allowHeaders,"access-control-expose-headers":n.exposeHeaders,"access-control-max-age":String(n.maxAge)};if(n.credentials)o["access-control-allow-credentials"]="true";this.corsHeadersEntries=Object.entries(o)}this.router.setCorsHeaders(this.corsHeadersEntries),this.router.setCorsHandler(this.corsHeadersEntries?null:this.corsHandler.corsify)}}normalizeOpenAPIConfig(e,t){let d=t!==!1&&!0;if(e===!1)return{enabled:!1,path:"/openapi.json",target:"openapi-3.0",docs:{enabled:!1,path:"/docs"}};if(e===!0)return{enabled:!0,path:"/openapi.json",target:"openapi-3.0",docs:{enabled:!1,path:"/docs"}};let r=e||{},a=r.docs,o=typeof a==="boolean"?{enabled:a,path:"/docs"}:{enabled:a?.enabled===!0,path:a?.path||"/docs"};return{enabled:r.enabled??d,path:r.path||"/openapi.json",target:r.target||"openapi-3.0",docs:o,info:r.info}}isDocsReservedPath(e){return e===this.openapiConfig.path||this.openapiConfig.docs.enabled&&e===this.openapiConfig.docs.path}getOpenAPIDocument(){if(this.openapiDocCache)return this.openapiDocCache;let e=this.router.getRouteDefinitions().filter((n)=>!this.isDocsReservedPath(n.path)),t=ae(e,{target:this.openapiConfig.target,info:this.openapiConfig.info});if(!this.openapiWarningsLogged&&t.warnings.length>0){for(let n of t.warnings)console.warn(n);this.openapiWarningsLogged=!0}return this.openapiDocCache=t.document,this.openapiDocCache}getOpenAPIDocsHtmlCacheEntry(){if(this.openapiDocsHtmlCache)return this.openapiDocsHtmlCache;let e=te(this.getOpenAPIDocument(),this.openapiConfig.path,U),t=Bun.gzipSync(e),n=`"${Bun.hash(e).toString(16)}"`;return this.openapiDocsHtmlCache={html:e,gzip:t,etag:n},this.openapiDocsHtmlCache}requestAcceptsGzip(e){let t=e.headers.get("accept-encoding");return Boolean(t&&/\bgzip\b/i.test(t))}validateReservedOpenAPIPaths(){if(!this.openapiConfig.enabled)return;let e=new Set([this.openapiConfig.path]);if(this.openapiConfig.docs.enabled)e.add(this.openapiConfig.docs.path),e.add(U);let t=this.router.getRouteDefinitions().filter((r)=>e.has(r.path)).map((r)=>`${r.method} ${r.path}`),n=Object.entries(this.router.getRouteTable()).filter(([r,a])=>e.has(r)&&a instanceof Response).map(([r])=>`STATIC ${r}`),d=[...t,...n];if(d.length>0)throw new Error(`OpenAPI reserved path conflict: ${d.join(", ")}. Change your route path(s) or reconfigure openapi.path/docs.path.`)}tryHandleOpenAPIRequest(e){if(!this.openapiConfig.enabled||e.method!=="GET")return null;let t=new URL(e.url).pathname;if(t===this.openapiConfig.path)return Response.json(this.getOpenAPIDocument());if(this.openapiConfig.docs.enabled&&t===this.openapiConfig.docs.path){let{html:n,gzip:d,etag:r}=this.getOpenAPIDocsHtmlCacheEntry();if(e.headers.get("if-none-match")===r)return new Response(null,{status:304,headers:{etag:r,"cache-control":F,vary:"accept-encoding"}});if(this.requestAcceptsGzip(e))return new Response(d,{status:200,headers:{"content-type":"text/html; charset=utf-8","content-encoding":"gzip",etag:r,"cache-control":F,vary:"accept-encoding"}});return new Response(n,{status:200,headers:{"content-type":"text/html; charset=utf-8",etag:r,"cache-control":F,vary:"accept-encoding"}})}if(this.openapiConfig.docs.enabled&&t===U){if(!le){if(!this.openapiTailwindMissingLogged)this.openapiTailwindMissingLogged=!0,console.warn('[OpenAPI] Missing docs runtime asset "tailwindcdn.js". Serving inline fallback script instead.');return new Response(Se,{status:200,headers:{"content-type":"application/javascript; charset=utf-8","cache-control":ie}})}return new Response(le,{status:200,headers:{"content-type":"application/javascript; charset=utf-8","cache-control":ie}})}return null}normalizeCorsOptions(e){return{origin:e.origin||"*",credentials:e.credentials!==!1,allowHeaders:Array.isArray(e.allowHeaders)?e.allowHeaders.join(", "):e.allowHeaders||"Content-Type, Authorization",allowMethods:Array.isArray(e.allowMethods)?e.allowMethods.join(", "):e.allowMethods||"GET, POST, PUT, PATCH, DELETE, OPTIONS",exposeHeaders:Array.isArray(e.exposeHeaders)?e.exposeHeaders.join(", "):e.exposeHeaders||"Authorization",maxAge:e.maxAge||86400}}applyCors(e,t){if(this.corsHeadersEntries){for(let[n,d]of this.corsHeadersEntries)e.headers.set(n,d);return e}if(this.corsHandler&&t)return this.corsHandler.corsify(e,t);return e}async start(){let e=this.config.port??3000,t=this.config.hostname||"localhost";this.validateReservedOpenAPIPaths();let n=async(d)=>{try{if(this.corsHandler&&d.method==="OPTIONS")return this.corsHandler.preflight(d);let r=this.tryHandleOpenAPIRequest(d);if(r)return this.applyCors(r,d);return this.applyCors(L.NOT_FOUND.clone(),d)}catch(r){return console.error("Server error:",r),this.applyCors(new Response("Internal Server Error",{status:500}),d)}};try{if(this.server=Bun.serve({port:e,hostname:t,reusePort:this.config.reusePort!==!1,routes:this.router.getRouteTable(),fetch:n,idleTimeout:this.config.idleTimeout||60,error:(d,r)=>{return console.error("[ERROR] Server error:",d),this.applyCors(new Response("Internal Server Error",{status:500}),r)}}),!this.server||!this.server.port)throw new Error(`Failed to start server on ${t}:${e} - server object is invalid`);return this.server}catch(d){if(d.code==="EADDRINUSE"||d.message?.includes("address already in use"))d.message=`Port ${e} is already in use`,d.port=e;else if(d.code==="EACCES"||d.message?.includes("permission denied"))d.message=`Permission denied to bind to port ${e}`,d.port=e;else if(d.message?.includes("EADDRNOTAVAIL"))d.message=`Cannot bind to hostname ${t}`,d.hostname=t;throw d}}stop(){if(this.server)this.server.stop(),this.server=null,this.openapiDocCache=null,this.openapiDocsHtmlCache=null,this.openapiWarningsLogged=!1,console.log("Server stopped")}getServer(){return this.server}getPort(){return this.server?.port??this.config.port??3000}getHostname(){return this.server?.hostname||this.config.hostname||"localhost"}getUrl(){let e=this.getPort();return`http://${this.getHostname()}:${e}`}}class v{static instance;router;server=null;middlewareManager;authManager;cacheManager;config={};routeScanner=null;routeGenerator=null;_protectedHandler=null;_cacheHandler=null;constructor(){this.middlewareManager=new N,this.authManager=new M,this.cacheManager=new P,this.router=new A(this.middlewareManager,this.authManager,this.cacheManager)}static getInstance(){if(!v.instance)v.instance=new v;return v.instance}setProtectedHandler(e){this._protectedHandler=e,this.authManager.setProtectedHandler(e)}getProtectedHandler(){return this._protectedHandler}setCacheHandler(e){this._cacheHandler=e,this.cacheManager.setCacheHandler(e)}getCacheHandler(){return this._cacheHandler}addRoute(e,t){this.router.route(e,t)}async startServer(e){this.config={...this.config,...e};let t={...this.config.defaults?.route};if(this.router.setRouteBooleanDefaults(t),this.router.setDevelopmentMode(this.config.development),this.middlewareManager.clear(),this.config.autoDiscover!==!1)this.router.clearRoutes();if(e?.before)this.middlewareManager.addBefore(...e.before);if(e?.finally)this.middlewareManager.addFinally(...e.finally);if(this.config.autoDiscover!==!1)await this.discoverRoutes();return this.server=new J(this.router,this.config),await this.server.start()}async discoverRoutes(){let e=this.config.routesDir||"./routes",t=this.config.routeExcludePatterns;if(this.routeScanner=new D(e,t),!this.routeGenerator)this.routeGenerator=new _;try{let n=await this.routeScanner.scan();if(n.length>0){if(this.config.development)await this.routeGenerator.generate(n);for(let d of n)try{let a=await import(Q(d.path)),o=d.name==="default"?a.default:a[d.name];if(o){if(this.isRouteDefinition(o))this.router.route(o.options,o.handler),this.logRouteLoaded(o.options);else if(this.isRouteEntry(o))this.router.addRoute(o),this.logRouteLoaded(o);else if(typeof o==="function")this.router.route(d.options,o),this.logRouteLoaded(d.options)}}catch(r){console.error(`Failed to load route ${d.name} from ${d.path}:`,r)}}}catch(n){if(n.code!=="ENOENT"&&n.code!=="ENOTDIR")console.error("Failed to discover routes:",n)}}async loadRoute(e){if(typeof e==="function"){let t=e();if(this.isRouteEntry(t))this.router.addRoute(t)}else if(e&&typeof e==="object"){for(let[,t]of Object.entries(e))if(typeof t==="function"){let n=t();if(this.isRouteEntry(n))this.router.addRoute(n)}}}isRouteEntry(e){if(!Array.isArray(e)||e.length<3)return!1;let[t,n,d,r]=e;return typeof t==="string"&&n instanceof RegExp&&Array.isArray(d)&&d.length>0&&d.every((a)=>typeof a==="function")&&(r===void 0||typeof r==="string")}isRouteDefinition(e){return e!==null&&typeof e==="object"&&"entry"in e&&"options"in e&&"handler"in e&&typeof e.handler==="function"}logRouteLoaded(e){}stop(){if(this.server)this.server.stop(),this.server=null}getServer(){return this.server}getRouter(){return this.router}getCacheManager(){return this.cacheManager}getAuthManager(){return this.authManager}static resetInstance(){v.instance=null}}var Me=v.getInstance;function Pe(e,t){return{entry:{method:e.method.toUpperCase(),path:e.path},options:e,handler:t}}function _e(e){let t=e??null;try{return JSON.stringify(t)}catch(n){if(n instanceof TypeError&&/\bbigint\b/i.test(n.message))return JSON.stringify(t,(d,r)=>typeof r==="bigint"?r.toString():r);throw n}}function c(e,t,n){let d={error:!0,message:t,statusCode:e,timestamp:new Date().toISOString()};return E(e,d,n)}var x={badRequest:(e="Bad Request",t)=>c(g.BAD_REQUEST,e,t),unauthorized:(e="Unauthorized",t)=>c(g.UNAUTHORIZED,e,t),paymentRequired:(e="Payment Required",t)=>c(402,e,t),forbidden:(e="Forbidden",t)=>c(g.FORBIDDEN,e,t),notFound:(e="Not Found",t)=>c(g.NOT_FOUND,e,t),methodNotAllowed:(e="Method Not Allowed",t)=>c(405,e,t),notAcceptable:(e="Not Acceptable",t)=>c(406,e,t),requestTimeout:(e="Request Timeout",t)=>c(408,e,t),conflict:(e="Conflict",t)=>c(g.CONFLICT,e,t),gone:(e="Gone",t)=>c(410,e,t),lengthRequired:(e="Length Required",t)=>c(411,e,t),preconditionFailed:(e="Precondition Failed",t)=>c(412,e,t),payloadTooLarge:(e="Payload Too Large",t)=>c(413,e,t),uriTooLong:(e="URI Too Long",t)=>c(414,e,t),unsupportedMediaType:(e="Unsupported Media Type",t)=>c(415,e,t),rangeNotSatisfiable:(e="Range Not Satisfiable",t)=>c(416,e,t),expectationFailed:(e="Expectation Failed",t)=>c(417,e,t),imATeapot:(e="I'm a teapot",t)=>c(418,e,t),misdirectedRequest:(e="Misdirected Request",t)=>c(421,e,t),unprocessableEntity:(e="Unprocessable Entity",t)=>c(g.UNPROCESSABLE_ENTITY,e,t),locked:(e="Locked",t)=>c(423,e,t),failedDependency:(e="Failed Dependency",t)=>c(424,e,t),tooEarly:(e="Too Early",t)=>c(425,e,t),upgradeRequired:(e="Upgrade Required",t)=>c(426,e,t),preconditionRequired:(e="Precondition Required",t)=>c(428,e,t),tooManyRequests:(e="Too Many Requests",t)=>c(429,e,t),requestHeaderFieldsTooLarge:(e="Request Header Fields Too Large",t)=>c(431,e,t),unavailableForLegalReasons:(e="Unavailable For Legal Reasons",t)=>c(451,e,t),internalServerError:(e="Internal Server Error",t)=>c(g.INTERNAL_SERVER_ERROR,e,t),notImplemented:(e="Not Implemented",t)=>c(501,e,t),badGateway:(e="Bad Gateway",t)=>c(502,e,t),serviceUnavailable:(e="Service Unavailable",t)=>c(503,e,t),gatewayTimeout:(e="Gateway Timeout",t)=>c(504,e,t),httpVersionNotSupported:(e="HTTP Version Not Supported",t)=>c(505,e,t),variantAlsoNegotiates:(e="Variant Also Negotiates",t)=>c(506,e,t),insufficientStorage:(e="Insufficient Storage",t)=>c(507,e,t),loopDetected:(e="Loop Detected",t)=>c(508,e,t),notExtended:(e="Not Extended",t)=>c(510,e,t),networkAuthenticationRequired:(e="Network Authentication Required",t)=>c(511,e,t),invalidArgument:(e="Invalid Argument",t)=>c(g.UNPROCESSABLE_ENTITY,e,t),rateLimitExceeded:(e="Rate Limit Exceeded",t)=>c(429,e,t),maintenance:(e="Service Under Maintenance",t)=>c(503,e,t),custom:(e,t,n)=>c(e,t,n)};function E(e,t,n=j.JSON){let d=n===j.JSON?_e(t):t;return new Response(d,{status:e,headers:{"content-type":n}})}export{Pe as route,E as createResponse,x as APIError};