@cleverbrush/server 5.0.0 → 5.1.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.
@@ -205,4 +205,5 @@ export declare function pickGroups<T extends ApiContract, K extends keyof T>(con
205
205
  * ```
206
206
  */
207
207
  export declare function omitGroups<T extends ApiContract, K extends keyof T>(contract: T, ...groups: K[]): Readonly<Omit<T, K>>;
208
+ export { type EndpointParams, endpointPath, matchEndpointPath } from './EndpointPath.js';
208
209
  export { file, type UploadConfiguration, type UploadContract, type UploadFiles, type UploadSchema } from './upload.js';
package/dist/contract.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a,d as b,f as c,h as d,j as e,k as f,l as g,m as h,n as i,o as j,p as k,q as l}from"./chunk-UZECVBRI.js";export{e as EndpointBuilder,c as SubscriptionBuilder,a as computeCacheKey,f as createEndpoints,i as defineApi,g as endpoint,d as file,j as mergeContracts,l as omitGroups,k as pickGroups,h as route,b as tracked};
1
+ import{a,d as b,f as c,h as d,j as e,k as f,l as g,m as h,n as i,o as j,q as k,r as l,s as m,t as n}from"./chunk-YCSREVQU.js";export{e as EndpointBuilder,c as SubscriptionBuilder,a as computeCacheKey,f as createEndpoints,k as defineApi,g as endpoint,i as endpointPath,d as file,j as matchEndpointPath,l as mergeContracts,n as omitGroups,m as pickGroups,h as route,b as tracked};
2
2
  //# sourceMappingURL=contract.js.map
package/dist/index.d.ts CHANGED
@@ -5,6 +5,7 @@ export type { ServerCorsOptions } from './Cors.js';
5
5
  export { type ApiContract, type ApiGroup, defineApi, type MergedContracts, mergeContracts, omitGroups, pickGroups } from './contract.js';
6
6
  export { type ActionContext, type AllowedResponseReturn, type CallbackDefinition, createEndpoints, EndpointBuilder, type EndpointMetadata, type EndpointMetadataDescriptors, endpoint, type Handler, type HandlerEntry, type HandlerMap, type HandlerMapping, type LinkDefinition, mapHandlers, type PropertyRefTree, type ResponsesOf, type ScopedEndpointFactory } from './Endpoint.js';
7
7
  export type { EndpointIdempotencyLimits, EndpointOptions, IdempotencyScope } from './EndpointOptions.js';
8
+ export { type EndpointParams, endpointPath, matchEndpointPath } from './EndpointPath.js';
8
9
  export { ErrorMap, type ErrorResponse, type ErrorResponsesOf, errorMap, withErrors } from './ErrorMap.js';
9
10
  export { BadRequestError, ConflictError, ForbiddenError, HttpError, NotFoundError, UnauthorizedError } from './HttpError.js';
10
11
  export { ApiImplementation, type ImplementationDefaults, type ImplementationGroupOptions, type ImplementationHandlerEntry, type ImplementationHandlers, ImplementationModule, type ImplementationOperationOptions, ImplementationScope, implement } from './Implementation.js';
@@ -18,3 +19,4 @@ export { SubscriptionBuilder, type SubscriptionContext, type SubscriptionHandler
18
19
  export type { ContentTypeHandler, EndpointRegistration, FilePart, Middleware, RejectedFile, ServerBatchingOptions, ServerOptions, SubscriptionRegistration, UploadOptions } from './types.js';
19
20
  export { file, type UploadConfiguration, type UploadContract, type UploadFiles, type UploadSchema } from './upload.js';
20
21
  export { defineWebhook, type WebhookDefinition } from './Webhook.js';
22
+ export { type RequestSignalContext, type RequestSignalOptions, withRequestSignal } from './withRequestSignal.js';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as we,b as ot,c as st,d as it,e as Ne,f as at,g as qe,h as dt,i as Re,j as ct,k as lt,l as ut,m as pt,n as ft,o as ht,p as yt,q as mt}from"./chunk-UZECVBRI.js";var j=class{static ok(e,t){return new k(e,200,t)}static created(e,t,n){let s={...n};return t&&(s.location=t),new k(e,201,s)}static accepted(e,t){return new k(e,202,t)}static noContent(){return new U}static badRequest(e,t){return new k(e,400,t)}static unauthorized(e,t){return new k(e,401,t)}static forbidden(e,t){return new k(e,403,t)}static notFound(e,t){return new k(e,404,t)}static conflict(e,t){return new k(e,409,t)}static redirect(e,t=!1){return new ne(e,t)}static json(e,t=200,n){return new k(e,t,n)}static file(e,t,n="application/octet-stream"){return new Z(e,t,n)}static content(e,t,n=200){return new ee(e,t,n)}static stream(e,t,n){return new te(e,t,n)}static raw(e){return new Y(e)}static status(e,t){return new G(e,t)}},Y=class extends j{handler;constructor(e){super(),this.handler=e}async executeAsync(e,t,n){await this.handler(e,t)}},k=class extends j{body;status;headers;constructor(e,t=200,n){super(),this.body=e,this.status=t,this.headers=n??{}}async executeAsync(e,t,n){for(let[s,r]of Object.entries(this.headers))t.setHeader(s,r);if(this.body===null||this.body===void 0){t.writeHead(this.status),t.end();return}t.writeHead(this.status,{"content-type":"application/json"}),t.end(JSON.stringify(this.body))}},Z=class extends j{content;fileName;contentType;constructor(e,t,n="application/octet-stream"){super(),this.content=e,this.fileName=t,this.contentType=n}async executeAsync(e,t,n){let s=this.fileName,r=s.replace(/[^\x20-\x7E]/g,"_"),i=r===s?`attachment; filename="${s}"`:`attachment; filename="${r}"; filename*=UTF-8''${encodeURIComponent(s)}`;t.writeHead(200,{"content-type":this.contentType,"content-disposition":i,"content-length":String(this.content.byteLength)}),t.end(this.content)}},ee=class extends j{body;contentType;status;constructor(e,t,n=200){super(),this.body=e,this.contentType=t,this.status=n}async executeAsync(e,t,n){t.writeHead(this.status,{"content-type":this.contentType}),t.end(this.body)}},te=class extends j{readable;contentType;fileName;constructor(e,t,n){super(),this.readable=e,this.contentType=t,this.fileName=n}async executeAsync(e,t,n){let s={"content-type":this.contentType};this.fileName&&(s["content-disposition"]=`attachment; filename="${this.fileName}"`),t.writeHead(200,s),await new Promise((r,i)=>{this.readable.on("error",i),t.on("error",i),this.readable.on("end",r),this.readable.pipe(t,{end:!0})})}},G=class extends j{status;headers;constructor(e,t){super(),this.status=e,this.headers=t??{}}async executeAsync(e,t,n){t.writeHead(this.status,this.headers),t.end()}},ne=class extends j{url;permanent;constructor(e,t=!1){super(),this.url=e,this.permanent=t}async executeAsync(e,t,n){t.writeHead(this.permanent?301:302,{location:this.url}),t.end()}},U=class extends j{async executeAsync(e,t,n){t.writeHead(204),t.end()}};function N(o){return JSON.parse(o,(e,t)=>{if(!(e==="__proto__"||e==="constructor"))return t})}function q(o,e=64){be(o,0,e)}function be(o,e,t){if(!(o===null||typeof o!="object")){if(e>=t)throw new Error(`JSON nesting depth exceeds maximum of ${t}`);if(Array.isArray(o))for(let n of o)be(n,e+1,t);else for(let n of Object.values(o))be(n,e+1,t)}}var _e={mimeType:"application/json",serialize(o){return JSON.stringify(o)},deserialize(o){let e=N(o);return q(e),e}},Fe={mimeType:"application/x-www-form-urlencoded",serialize(o){let e=new URLSearchParams;if(o&&typeof o=="object"){for(let[t,n]of Object.entries(o))if(n!=null)if(Array.isArray(n))for(let s of n)e.append(t,String(s));else e.append(t,String(n))}return e.toString()},deserialize(o){let e={},t=new URLSearchParams(o);for(let[n,s]of t){if(gt(n))continue;let r=e[n];r===void 0?e[n]=s:Array.isArray(r)?r.push(s):e[n]=[r,s]}return e}};function gt(o){return o==="__proto__"||o==="constructor"||o==="prototype"}function wt(o){return o.split(",").map(e=>{let t=e.trim(),[n,...s]=t.split(";").map(i=>i.trim()),r=1;for(let i of s){let[d,a]=i.split("=");d?.trim()==="q"&&a&&(r=parseFloat(a),Number.isNaN(r)&&(r=1))}return{mimeType:n.toLowerCase(),quality:r}}).sort((e,t)=>t.quality-e.quality)}var W=class{#e=new Map;constructor(){this.register(_e),this.register(Fe)}register(e){this.#e.set(e.mimeType.toLowerCase(),e)}selectResponseHandler(e){if(!e)return this.#e.get("application/json")??null;let t=wt(e);for(let{mimeType:n}of t){if(n==="*/*")return this.#e.get("application/json")??null;let s=this.#e.get(n);if(s)return s}return null}selectRequestHandler(e){if(!e)return null;let t=e.split(";")[0].trim().toLowerCase();return this.#e.get(t)??null}};var re=class o{#e;constructor(e=[]){this.#e=[...e]}on(e,t){return new o([...this.#e,{matches:n=>n instanceof e,translate:t}])}async translate(e){let t=this.#e.find(s=>s.matches(e));if(!t)throw e;let n=await t.translate(e);if(!(n instanceof k)&&!(n instanceof U)&&!(n instanceof G))throw new TypeError("Error translators must return an explicit JSON or bodyless status result");return n}};function Rt(){return new re}function Se(o,e,t){return ve(o),(async(...n)=>{try{return await t(...n)}catch(s){return e.translate(s)}})}function ve(o){let e=o.introspect().responsesSchemas;if(!e||Object.keys(e).length===0)throw new TypeError("Error policies require explicit endpoint responses")}var bt={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",409:"Conflict",413:"Payload Too Large",415:"Unsupported Media Type",422:"Unprocessable Content",500:"Internal Server Error",503:"Service Unavailable"};function E(o,e,t,n){return{type:`https://httpstatuses.com/${o}`,status:o,title:e??bt[o]??"Error",...t!==void 0?{detail:t}:{},...n}}function xe(o){return E(400,"Bad Request","One or more validation errors occurred.",{errors:o})}function T(o){return JSON.stringify(o)}var P="application/problem+json";var S=class extends Error{status;title;detail;extensions;constructor(e,t,n,s){super(n??t??`HTTP ${e}`),this.name="HttpError",this.status=e,this.title=t??`HTTP ${e}`,this.detail=n,this.extensions=s}toProblemDetails(){return E(this.status,this.title,this.detail,this.extensions)}},Ee=class extends S{constructor(e){super(404,"Not Found",e),this.name="NotFoundError"}},Ce=class extends S{constructor(e){super(400,"Bad Request",e),this.name="BadRequestError"}},Oe=class extends S{constructor(e){super(401,"Unauthorized",e),this.name="UnauthorizedError"}},Te=class extends S{constructor(e){super(403,"Forbidden",e),this.name="ForbiddenError"}},Pe=class extends S{constructor(e){super(409,"Conflict",e),this.name="ConflictError"}};var oe=Symbol("implementationEntries"),J=class{#e;constructor(e){this.#e=Object.freeze(e.map(t=>Object.freeze({...t,middlewares:t.middlewares?[...t.middlewares]:void 0})))}[oe](){return this.#e}},se=class o{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=Object.freeze({...t}),this.#n=Object.freeze({...n})}get endpoints(){return this.#n}pick(...e){let t={},n={},s=new Set;for(let r of e){if(!Object.hasOwn(this.#t,r))throw new TypeError(`Unknown operation ${this.#e}.${r}`);if(s.has(r))throw new TypeError(`Duplicate operation ${this.#e}.${r}`);s.add(r),Object.defineProperty(t,r,{value:this.#t[r],enumerable:!0}),Object.defineProperty(n,r,{value:this.#n[r],enumerable:!0})}return new o(this.#e,t,n)}withHandlers(e){for(let n of Object.keys(e))if(!Object.hasOwn(this.#n,n))throw new TypeError(`Unknown handler ${this.#e}.${n}`);let t=[];for(let n of Object.keys(this.#n)){let s=this.#n[n],r=Object.hasOwn(e,n)?e[n]:void 0,i=typeof r=="function"?r:r?.handler;if(typeof i!="function")throw new TypeError(`Missing handler ${this.#e}.${n}`);let d=typeof r=="function"?void 0:r?.errors;if(d&&qe(s))throw new TypeError("HTTP error policies cannot wrap subscription handlers");t.push({group:this.#e,name:n,source:this.#t[n],endpoint:s,handler:d?Se(s,d,i):i,handlerErrorsMapped:!!d,errors:d,prepare:typeof r=="function"?void 0:r?.prepare,idempotency:typeof r=="function"?void 0:r?.idempotency,middlewares:typeof r=="function"?void 0:r?.middlewares})}return new J(t)}},ie=class o extends J{#e;constructor(e,t=[]){super(t),this.#e=Object.freeze(Object.fromEntries(Object.entries(e).map(([n,s])=>[n,Object.freeze({...s})])))}group(e,t){if(!Object.hasOwn(this.#e,e))throw new TypeError(`Unknown contract group ${e}`);let n=this.#e[e],s=t??{};for(let i of Object.keys(s.operations??{}))if(!Object.hasOwn(n,i))throw new TypeError(`Unknown operation ${e}.${i}`);let r=Object.fromEntries(Object.entries(n).map(([i,d])=>[i,St(d,s,s.operations?.[i]??{})]));return new se(e,n,r)}use(...e){let t=[...this[oe]()],n=new Map;for(let s of t)n.has(s.group)||n.set(s.group,new Set),n.get(s.group).add(s.name);for(let s of e){if(!(s instanceof J))throw new TypeError("Expected an implementation module");for(let r of s[oe]()){if(!Object.hasOwn(this.#e,r.group)||!Object.hasOwn(this.#e[r.group],r.name)||this.#e[r.group][r.name]!==r.source)throw new TypeError(`Incompatible source endpoint ${r.group}.${r.name}`);if(n.get(r.group)?.has(r.name))throw new TypeError(`Duplicate implementation ${r.group}.${r.name}`);n.has(r.group)||n.set(r.group,new Set),n.get(r.group).add(r.name),t.push(r)}}return new o(this.#e,t)}complete(){let e=Object.create(null),t=Object.create(null);for(let s of this[oe]())e[s.group]??=Object.create(null),t[s.group]??=Object.create(null),e[s.group][s.name]=s.endpoint,t[s.group][s.name]={handler:s.handler,handlerErrorsMapped:s.handlerErrorsMapped,prepare:s.prepare,idempotency:s.idempotency,errors:s.errors,middlewares:s.middlewares?[...s.middlewares]:void 0};let n=[];for(let[s,r]of Object.entries(this.#e))for(let i of Object.keys(r))Object.hasOwn(e[s]??{},i)||n.push(`${s}.${i}`);if(n.length)throw new TypeError(`Missing implementations: ${n.join(", ")}`);return Re(e,t)}};function St(o,e,t){let n=o;(e.inject||t.inject)&&(n=n.inject({...o.introspect().serviceSchemas,...e.inject,...t.inject}));let s=t.authorize??e.authorize;s&&(n=n.authorize(s));let r=t.tags??e.tags;return r&&(n=n.tags(...r)),t.summary!==void 0&&(n=n.summary(t.summary)),t.description!==void 0&&(n=n.description(t.description)),t.operationId!==void 0&&(n=n.operationId(t.operationId)),t.deprecated&&(n=n.deprecated()),n}function vt(o){return new ie(o)}import{createHash as xt}from"crypto";async function ae(o,e,t){let{write:n,writeHead:s,end:r}=o,i=[],d=0,a=!1,c={},l=(p,u)=>{if(p==null||typeof p=="function"||d>t)return;let h=typeof p=="string"?Buffer.from(p,typeof u=="string"?u:"utf8"):Buffer.from(p);d+=h.length,d>t?i.length=0:i.push(h)};o.writeHead=function(p,...u){let h=typeof u[0]=="string"?u[1]:u[0];if(Array.isArray(h)){let m={};for(let g=0;g<h.length;g+=2){let w=h[g].toLowerCase(),O=m[w];m[w]=O===void 0?h[g+1]:[...Array.isArray(O)?O:[String(O)],h[g+1]]}c={...c,...m}}else if(h)for(let[m,g]of Object.entries(h))c[m.toLowerCase()]=g;let f=Reflect.apply(s,this,[p,...u]);return c={...c,...this.getHeaders?.()},f},o.write=function(p,...u){return l(p,u[0]),Reflect.apply(n,this,[p,...u])},o.end=function(p,...u){l(p,u[0]);let h=Reflect.apply(r,this,[p,...u]);return a=!0,c={...c,...this.getHeaders?.()},h};try{return await e(),!a||d>t?void 0:{status:o.statusCode,headers:c,body:Buffer.concat(i)}}finally{o.write=n,o.writeHead=s,o.end=r}}function de(o){if(typeof o?.scope!="function")throw new TypeError("idempotency requires an explicit scope");let{scope:e,ttl:t=864e5,headerName:n="x-idempotency-key",skip:s=a=>!["POST","PUT","DELETE","PATCH"].includes(a.method),maxEntries:r=1e3,maxResponseBytes:i=65536}=o;for(let[a,c]of Object.entries({ttl:t,maxEntries:r,maxResponseBytes:i}))if(!Number.isSafeInteger(c)||c<=0)throw new TypeError(a+" must be a positive safe integer");let d=new Map;return async(a,c)=>{let l=a.headers[n.toLowerCase()]??a.headers[n];if(s(a)||!l)return c();if(l.length>256)throw new S(400,"Idempotency key is too long");let p=e(a);if(p===void 0)return c();if(typeof p!="string")throw new TypeError("Idempotency scope must be a string");let u=xt("sha256").update(JSON.stringify([p,a.method,a.url?.href??"/",l])).digest("hex"),h=Date.now();for(let[y,v]of d)v.expiresAt<=h&&d.delete(y);let f=d.get(u);if(f){let y=await f.result;if(!y)throw new S(409,"The previous response cannot be replayed; verify the operation outcome");a.response.writeHead(y.status,y.headers),a.response.end(y.body),a.responded=!0;return}if(d.size>=r)throw new S(503,"Idempotency capacity reached");let m,g,w=new Promise((y,v)=>{m=y,g=v});w.catch(()=>{});let O={result:w,expiresAt:1/0};d.set(u,O);try{let y=await ae(a.response,c,i);O.expiresAt=Date.now()+t,m(y)}catch(y){throw d.delete(u),g(y),y}}}function Et(o){return["POST","PUT","DELETE","PATCH"].includes(o.toUpperCase())}function Ct(o={}){let{defaultTtl:e=6e4,maxEntries:t=1e3,maxResponseBytes:n=65536}=o,s={...o.ttlByTag};for(let[a,c]of Object.entries({maxEntries:t,maxResponseBytes:n}))if(!Number.isSafeInteger(c)||c<=0)throw new TypeError(a+" must be a positive safe integer");for(let a of[e,...Object.values(s)])if(!Number.isFinite(a)||a<0)throw new TypeError("Cache TTL must be finite and non-negative");let r=new Map,i=new Map,d=a=>a.every(([c,l])=>i.get(c)===l);return async(a,c)=>{let p=a.items.get("__endpoint_meta")?.cacheTags??[];if(p.length===0)return c();if(Et(a.method)){let u=p.map(h=>h.name);if(await c(),a.response.statusCode>=200&&a.response.statusCode<300){for(let[h,f]of i)u.some(m=>h.startsWith(m))&&i.set(h,f+1);for(let[h,f]of r)d(f.generations)||r.delete(h)}return}if(a.method==="GET"){for(let[y,v]of r)v.expiresAt<=Date.now()&&r.delete(y);let u={params:a.pathParams??{},body:void 0,query:a.queryParams??{},headers:a.headers??{}},h=p.map(y=>we(y,u)),f=p.map(({name:y})=>(i.has(y)||i.set(y,0),[y,i.get(y)]));for(let y of h){let v=r.get(y);if(v&&v.expiresAt>Date.now()&&d(v.generations)){let M=a.response;M.writeHead(v.status,v.headers),M.end(v.body),a.responded=!0;return}v&&r.delete(y)}let m=await ae(a.response,c,n);if(!m)return;let{status:g,headers:w,body:O}=m;if(Object.keys(w).some(y=>y.toLowerCase()==="set-cookie")||/\b(?:private|no-store)\b/i.test(String(w["cache-control"]??"")))return;if(g>=200&&g<300&&d(f)){let y=p.reduce((v,M)=>{let B=s[M.name]!==void 0?s[M.name]:e;return B>v?B:v},0);if(y>0)for(let v of h)!r.has(v)&&r.size>=t&&r.delete(r.keys().next().value),r.set(v,{status:g,headers:w,body:O,expiresAt:Date.now()+y,generations:f})}return}return c()}}import{URL as Ot}from"url";import{any as ce,boolean as Tt,func as De,object as Pt,promise as ze,record as ke,string as _}from"@cleverbrush/schema";var kt=Pt({method:_(),url:ce().hasType(),pathParams:ke(_(),_()),queryParams:ke(_(),_()),headers:ke(_(),_()),items:ce(),body:De().hasReturnType(ze(ce())),json:De().hasReturnType(ze(ce())),responded:Tt()}),V=5*1024*1024,$=class{request;response;url;method;headers;items=new Map;maxBodySize;#e={};_queryParams;#t;#n;#r=void 0;#o=!1;responded=!1;principal=void 0;constructor(e,t,n){this.request=e,this.response=t,this.method=(e.method??"GET").toUpperCase(),this.maxBodySize=n??V;let s=e.url??"/";this.url=new Ot(s,`http://${e.headers.host??"localhost"}`);let r=Object.create(null);for(let[i,d]of Object.entries(e.headers))typeof d=="string"?r[i]=d:Array.isArray(d)&&(r[i]=d.join(", "));this.headers=r}get pathParams(){return this.#e}set pathParams(e){this.#e=e}get queryParams(){if(this._queryParams)return this._queryParams;let e=Object.create(null);for(let[t,n]of this.url.searchParams)e[t]=n;return e}get services(){return this.#t}set services(e){this.#t=e}async body(){return this.#n?this.#n:(this.#n=new Promise((e,t)=>{let n=[],s=0,r=!1,i=()=>{this.request.off("data",l),this.request.off("end",p),this.request.off("error",d),this.request.off("aborted",a),this.request.off("close",c)},d=u=>{r||(r=!0,i(),n.length=0,t(u))},a=()=>d(new S(400,"Request body interrupted")),c=()=>{this.request.readableEnded||a()},l=u=>{if(!r){if(s+=u.length,s>this.maxBodySize){d(new S(413,"Payload Too Large")),this.request.destroy();return}n.push(u)}},p=()=>{r||(r=!0,i(),e(Buffer.concat(n)))};if(this.request.destroyed||this.request.readableEnded){a();return}this.request.on("data",l),this.request.on("end",p),this.request.on("error",d),this.request.on("aborted",a),this.request.on("close",c)}),this.#n)}async json(){if(this.#o)return this.#r;let t=(await this.body()).toString("utf-8");return t.length>0&&(this.#r=N(t),q(this.#r)),this.#o=!0,this.#r}};import*as ge from"http";import*as tt from"https";import{AuthorizationService as Ft,PolicyBuilder as Dt,Principal as he,parseCookies as zt,requireRole as Gt}from"@cleverbrush/auth";import{ServiceCollection as Ut}from"@cleverbrush/di";import{WebSocketServer as Jt}from"ws";var Mt=/[^!#$%&'*+\-.^_`|~\da-zA-Z]/,Ge=new Set(["access-control-allow-origin","access-control-allow-credentials","access-control-allow-methods","access-control-allow-headers","access-control-expose-headers","access-control-max-age"]);function Ue(o){if(typeof o!="string")return!1;if(o==="null")return!0;try{let e=new URL(o).origin;return e!=="null"&&e===o}catch{return!1}}function Ae(o){return typeof o=="string"&&o.length>0&&!Mt.test(o)}function Me(o,e){if(o===void 0)return[];if(!Array.isArray(o)||o.some(t=>!Ae(t)||t==="*"))throw new TypeError(`CORS ${e} must contain explicit HTTP tokens`);return[...new Set(o.map(t=>t.toLowerCase()))]}function At(o,e){let t=new Map;for(let n of[...o,...e])if(n!==void 0)for(let s of String(n).split(",")){let r=s.trim();if(r==="*")return"*";r&&!t.has(r.toLowerCase())&&t.set(r.toLowerCase(),r)}return[...t.values()].join(", ")}function jt(o,e,t){let n=o.writeHead;o.writeHead=function(s,...r){let i=typeof r[0]=="string"||r.length>1?1:0,d=r[i],a=[this.getHeader("vary")],c=(l,p)=>{let u=l.toLowerCase();return u==="vary"&&a.push(p),u!=="vary"&&!Ge.has(u)};if(Array.isArray(d)){let l=[];for(let p=0;p<d.length;p+=2)c(d[p],d[p+1])&&l.push(d[p],d[p+1]);r[i]=l}else d!==void 0&&(r[i]=Object.fromEntries(Object.entries(d).filter(([l,p])=>c(l,p))));for(let l of Ge)this.removeHeader(l);for(let[l,p]of Object.entries(e))this.setHeader(l,p);return this.setHeader("vary",At(a,t)),n.call(this,s,...r)}}function H(o,e,t){return o.writeHead(e,{"content-type":P,...t?{allow:t.join(", ")}:{}}),o.end(T(E(e))),!0}var le=class{#e;#t;#n;#r;#o;#s;constructor(e){let t=e?.origin;if(t==="*")this.#e="*";else if(typeof t=="function")this.#e=t;else{let s=typeof t=="string"?[t]:t;if(!Array.isArray(s)||s.some(r=>!Ue(r)))throw new TypeError("CORS origin must be a serialized origin, list, wildcard or predicate");this.#e=new Set(s)}if(e.credentials!==void 0&&typeof e.credentials!="boolean")throw new TypeError("CORS credentials must be a boolean");if(this.#o=e.credentials??!1,this.#o&&this.#e==="*")throw new TypeError("CORS credentials require explicit origins or a predicate");if(this.#s=e.maxAgeSeconds===void 0?0:e.maxAgeSeconds,!Number.isSafeInteger(this.#s)||this.#s<0)throw new TypeError("CORS maxAgeSeconds must be a non-negative safe integer");let n=Me(e.methods,"methods");e.methods!==void 0&&(this.#t=new Set(n.map(s=>s.toUpperCase()))),this.#n=new Set(Me(e.allowedHeaders,"allowedHeaders")),this.#r=Me(e.exposedHeaders,"exposedHeaders").join(", ")}async handle(e,t,n){let s=e.headers.origin,r=e.method?.toUpperCase()==="OPTIONS"&&s!==void 0&&e.headers["access-control-request-method"]!==void 0,i={};if(jt(t,i,r?["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]:["Origin"]),s===void 0)return!1;if(!Ue(s))return H(t,403);let d;try{if(d=this.#e==="*"||(typeof this.#e=="function"?await this.#e(s):this.#e.has(s)),typeof d!="boolean")return H(t,500)}catch{return H(t,500)}if(!d)return H(t,403);if(r){let a=e.headers["access-control-request-method"],c=e.headers["access-control-request-headers"];if(!Ae(a)||a==="*"||c!==void 0&&typeof c!="string")return H(t,400);let l=c===void 0?[]:c.split(",").map(h=>h.trim().toLowerCase());if(l.some(h=>!Ae(h)||h==="*"))return H(t,400);let p;try{p=new URL(e.url??"/",`http://${e.headers.host??"localhost"}`).pathname}catch{return H(t,400)}let u=n(a.toUpperCase(),p);if(u.status!==200)return H(t,u.status,u.allowedMethods);if(this.#t&&!this.#t.has(a.toUpperCase())||l.some(h=>!this.#n.has(h)))return H(t,403);i["access-control-allow-methods"]=a,l.length&&(i["access-control-allow-headers"]=[...new Set(l)].join(", ")),i["access-control-max-age"]=String(this.#s)}else this.#r&&(i["access-control-expose-headers"]=this.#r);return i["access-control-allow-origin"]=this.#e==="*"?"*":s,this.#o&&(i["access-control-allow-credentials"]="true"),r?(t.writeHead(204),t.end(),!0):!1}};var K=class{#e=[];add(e){this.#e.push(e)}async execute(e,t){let n=0,s=async()=>{if(n<this.#e.length){let r=this.#e[n++];await r(e,s)}else await t()};await s()}};import{Busboy as Ht}from"@fastify/busboy";function A(o,e,t){let n=t===void 0?"/files":`/files/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`;return new S(o,o===413?"Payload Too Large":"Bad Request",e,{errors:[{pointer:n,detail:e}]})}async function Je(o,e,t){let n=e.maxFileCount??10,s=e.maxFieldCount??100,r=e.schema?.introspect().properties,i=Object.create(null),d=Object.create(null),a=[],c=new Set;if(Number(o.headers["content-length"])>t)throw o.resume(),A(413,"Multipart request exceeds maxBodySize");await new Promise((u,h)=>{let f=!1,m=0,g=new Map,w=Ht({headers:o.headers,limits:{fileSize:e.maxFileSize??10*1024*1024,files:n,fieldSize:e.maxFieldSize??1024*1024,fields:s,parts:e.maxPartCount??n+s}}),O=()=>{o.unpipe(w),o.off("data",v),o.off("aborted",M),o.off("error",b),o.off("close",B);for(let[R,C]of g)C.length=0,R.destroy();g.clear()},y=R=>{if(!f){f=!0,O();for(let C of Object.keys(d))delete d[C];w.destroy(),o.resume(),h(R instanceof S?R:A(400,"Malformed multipart request"))}},v=R=>{m+=R.length,m>t&&y(A(413,"Multipart request exceeds maxBodySize"))},M=()=>y(A(400,"Multipart request interrupted")),B=()=>{o.complete||M()},b=R=>y(R),x=R=>Buffer.byteLength(R)>(e.maxFieldNameSize??100)?(y(A(413,"Multipart field name is too long",R)),!1):!0;w.on("field",(R,C,D,Be)=>{if(!(f||!x(R))){if(D||Be){y(A(413,"Multipart field exceeds its size limit",R));return}if(Object.hasOwn(i,R)||c.has(R)||r&&Object.hasOwn(r,R)){y(A(400,"Duplicate or incorrectly encoded multipart field",R));return}i[R]=C}}),w.on("file",(R,C,D,Be,z)=>{let Q=[];if(g.set(C,Q),C.on("error",b),C.on("limit",()=>y(A(413,"File exceeds maxFileSize",R))),f||!x(R)){C.resume();return}let Ie=r&&Object.hasOwn(r,R)?r[R]:void 0,nt=Ie?.introspect().type==="array";if(r&&!Ie||Object.hasOwn(i,R)||c.has(R)&&!nt){y(A(400,"Unknown or duplicate file field",R));return}if(c.add(R),!(!e.allowedMimeTypes||e.allowedMimeTypes.some(I=>I.endsWith("/*")?z.startsWith(I.slice(0,-1)):z===I))){if(r){y(A(400,`MIME type "${z}" is not allowed`,R));return}a.push({fieldName:R,filename:D,mimeType:z,reason:`MIME type "${z}" is not allowed`}),C.on("end",()=>g.delete(C)),C.resume();return}let X=d[R]??[];d[R]=X;let rt=X.length;X.push(void 0),C.on("data",I=>{f||Q.push(I)}),C.on("end",()=>{if(g.delete(C),f)return;if(C.truncated){y(A(413,"File was truncated",R));return}let I=Buffer.concat(Q);Q.length=0,X[rt]={filename:D,mimeType:z,buffer:I,size:I.length}})}),w.on("filesLimit",()=>y(A(413,"Exceeded maxFileCount"))),w.on("fieldsLimit",()=>y(A(413,"Exceeded maxFieldCount"))),w.on("partsLimit",()=>y(A(413,"Exceeded maxPartCount"))),w.on("error",b),w.on("finish",()=>{f||(f=!0,O(),u())}),o.on("data",v),o.once("aborted",M),o.once("error",b),o.once("close",B),o.pipe(w)});let p=Object.create(null);for(let[u,h]of Object.entries(d))p[u]=r?.[u]?.introspect().type==="array"?h:h[0];if(e.schema){for(let[h,f]of Object.entries(r)){let m=f.introspect();m.type==="array"&&m.isRequired&&!Object.hasOwn(p,h)&&(p[h]=[])}let u=await e.schema.validateAsync(p,{doNotStopOnFirstError:!0});if(!u.valid){let h=u.getInvalidProperties().flatMap(f=>f.errors.map(m=>({pointer:`/files${f.descriptor.toJsonPointer()}`,detail:m})));throw new S(400,"Bad Request","Upload contract validation failed",{errors:h.length?h:u.errors?.map(f=>({pointer:"/files",detail:f.message}))})}return{fields:i,files:Object.fromEntries(Object.entries(u.object).filter(([,h])=>h!==void 0)),rejectedFiles:a}}return{fields:i,files:p,rejectedFiles:a}}function $e(o){return o.bodySchema!=null}async function Ke(o,e,t,n){let s=[],r={};if(r.context=t,o.authRoles!==null&&t.principal!==void 0&&(r.principal=t.principal),e&&Object.keys(e).length>0&&(r.params=e),o.bodySchema){let i=await o.bodySchema.validateAsync(n,{doNotStopOnFirstError:!0});if(i.valid)r.body=i.object;else{let d=typeof i.getInvalidProperties=="function"?i.getInvalidProperties:null,a=!1;if(d)for(let c of d()){let l=c.descriptor.toJsonPointer();for(let p of c.errors)s.push({pointer:`/body${l}`,detail:p}),a=!0}if(!a)for(let c of i.errors??[])s.push({pointer:"/body",detail:c.message})}}if(o.querySchema){let i=o.querySchema.introspect();if(i.type!=="object"||!i.properties)throw new Error("Endpoint query schema must be an object schema whose properties map to query parameter names.");let d=i.properties,a={};for(let[c,l]of Object.entries(d)){let p=t.queryParams[c],u=await l.validateAsync(p,{doNotStopOnFirstError:!0});if(u.valid)a[c]=u.object;else for(let h of u.errors??[])s.push({pointer:`/query/${c.replace(/~/g,"~0").replace(/\//g,"~1")}`,detail:h.message})}r.query=a}if(o.headerSchema){let i=o.headerSchema.introspect();if(i.type!=="object"||!i.properties)throw new Error("Endpoint headers schema must be an object schema whose properties map to header names.");let d=i.properties,a={};for(let[c,l]of Object.entries(d)){let p=t.headers[c.toLowerCase()],u=await l.validateAsync(p,{doNotStopOnFirstError:!0});if(u.valid)a[c]=u.object;else for(let h of u.errors??[])s.push({pointer:`/headers/${c.replace(/~/g,"~0").replace(/\//g,"~1")}`,detail:h.message})}r.headers=a}if(s.length>0)return{valid:!1,problemDetails:xe(s)};if(o.serviceSchemas){if(!t.services)throw new Error("Endpoint declares .inject() dependencies but no service provider is available. Register services via createServer().services() before handling this endpoint.");let i={};for(let[d,a]of Object.entries(o.serviceSchemas))i[d]=t.services.get(a);return{valid:!0,args:[r,i]}}return{valid:!0,args:[r]}}function L(o){let e=decodeURI(o);return e.length>1&&e.endsWith("/")?e.slice(0,-1):e}function je(o){return typeof o!="string"&&typeof o.validate=="function"}function Le(o){let e=0,t=!1;for(let n of o)for(let s of n)s==="/"?(t&&e++,t=!1):t=!0;return e+(t?1:0)}function Bt(o,e){if(!je(e)){let r=L(e),i=r==="/"?o||"/":o+r;return{isStatic:!0,literalSegments:Le([i]),dynamicSegments:0}}let{literals:t,segments:n}=e.introspect().templateDefinition,s=[o+(t[0]??""),...t.slice(1)];return{isStatic:n.length===0,literalSegments:Le(s),dynamicSegments:n.length}}function It(o,e){return o.isStatic!==e.isStatic?o.isStatic?1:-1:o.literalSegments!==e.literalSegments?o.literalSegments-e.literalSegments:e.dynamicSegments-o.dynamicSegments}function Nt(o,e){if(!je(e)){let s=L(e);return s==="/"?o||"/":o+s}let{literals:t,segments:n}=e.introspect().templateDefinition;return n.length>0?null:o+(t[0]??"")}function We(o,e,t){let n=L(o);return{basePath:n,routePath:e,specificity:Bt(n,e),exactPath:Nt(n,e),registration:t}}function Ve(){return{exactRoutes:new Map,dynamicRoutes:[]}}function Qe(o,e){if(e.exactPath!==null){o.exactRoutes.has(e.exactPath)||o.exactRoutes.set(e.exactPath,e);return}o.dynamicRoutes.push(e)}var ue=class{#e=new Map;#t=Ve();#n=!0;addRoute(e){let{method:t,basePath:n,pathTemplate:s}=e.endpoint,r=t.toUpperCase(),i=We(n,s,e),d=this.#e.get(r);d||(d=Ve(),this.#e.set(r,d)),Qe(d,i),this.#n=!1}finalize(){if(!this.#n){for(let e of this.#e.values())this.#o(e.dynamicRoutes);this.#o(this.#t.dynamicRoutes),this.#n=!0}}match(e,t){let n;try{n=L(t)}catch{return{match:null,methodNotAllowed:!1,badRequest:!0}}let s=e.toUpperCase();this.finalize();let r=this.#e.get(s);if(r){let d=this.#r(r,n);if(d)return{match:d,methodNotAllowed:!1}}let i=[];for(let[d,a]of this.#e)d!==s&&this.#r(a,n)&&i.push(d);return i.length>0?{match:null,methodNotAllowed:!0,allowedMethods:i}:{match:null,methodNotAllowed:!1}}#r(e,t){let n=e.exactRoutes.get(t);if(n){let s=this.#s(n,t);if(s)return s}for(let s of e.dynamicRoutes){let r=this.#s(s,t);if(r)return r}return null}#o(e){e.sort((t,n)=>It(n.specificity,t.specificity))}#s(e,t){let{basePath:n,routePath:s}=e;if(n&&!t.startsWith(n))return null;let r=n?t.slice(n.length):t;if(je(s)){let a=s.validate(r);return a.valid?{registration:e.registration,parsedPath:a.object}:null}let i=L(s);return(r.length===0?"/":r)===i?{registration:e.registration,parsedPath:null}:null}addSubscriptionRoute(e){let{basePath:t,pathTemplate:n}=e.endpoint;Qe(this.#t,We(t,n,e)),this.#n=!1}matchSubscription(e){let t;try{t=L(e)}catch{return null}return this.finalize(),this.#r(this.#t,t)}};import{Readable as qt,Writable as _t}from"stream";var pe=class extends qt{method;url;headers;__cleverbrushBatchSubrequest;socket=null;#e;#t=!1;constructor(e){super(),this.method=e.method,this.url=e.url;let t={};for(let[n,s]of Object.entries(e.headers??{}))t[n.toLowerCase()]=s;this.headers={host:"localhost",...t},this.#e=e.body!=null&&e.body.length>0?Buffer.from(e.body,"utf-8"):Buffer.alloc(0)}_read(){this.#t||(this.#t=!0,this.#e.length>0&&this.push(this.#e),this.push(null))}},fe=class extends _t{statusCode=200;headersSent=!1;#e=[];#t={};_write(e,t,n){this.#e.push(Buffer.isBuffer(e)?e:Buffer.from(e)),n()}writeHead(e,t){if(this.statusCode=e,t!=null&&typeof t=="object"&&!Array.isArray(t))for(let[n,s]of Object.entries(t))this.#t[n.toLowerCase()]=Array.isArray(s)?s.join(", "):String(s);return this.headersSent=!0,this}setHeader(e,t){return this.#t[e.toLowerCase()]=Array.isArray(t)?t.join(", "):String(t),this}getHeader(e){return this.#t[e.toLowerCase()]}getHeaders(){return{...this.#t}}end(e,...t){if(e!=null&&typeof e!="function"){let n=Buffer.isBuffer(e)||e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),"utf-8");this.#e.push(n),super.end(...t)}else typeof e=="function"?super.end(e):super.end(...t);return this}toResult(){return{status:this.statusCode,headers:{...this.#t},body:Buffer.concat(this.#e).toString("utf-8")}}};function Xe(o){return{type:"message",data:o}}function Ye(o,e){return{type:"tracked",id:o,data:e}}function Ze(){return{type:"pong"}}function F(o,e){return{type:"error",code:o,message:e}}function et(o){let e;try{e=N(o),q(e)}catch{return null}if(typeof e!="object"||e===null)return null;let t=e;return t.type==="ping"?{type:"ping"}:t.type==="message"&&"data"in t?{type:"message",data:t.data}:null}var ye=class{#e=new Ut;#t=[];#n=[];#r=[];#o=[];#s=new W;#d;#c=null;#i=null;#l=!1;#u=null;#a;constructor(e={}){this.#d=e}services(e){return e(this.#e),this}use(e){return this.#o.push(e),this}useCors(e){if(e===void 0)throw new TypeError("CORS requires an explicit origin policy");return this.#a=e,this}contentType(e){return this.#s.register(e),this}useAuthentication(e){return this.#c=e,this}useAuthorization(e){return this.#i=e??{},this}withHealthcheck(){return this.#l=!0,this}useBatching(e={}){return this.#u=e,this}handle(e,t,n){return this.#t.push({endpoint:e.introspect(),handler:t,middlewares:n?.middlewares,prepare:n?.prepare,idempotency:n?.idempotency,errors:n?.errors}),this}handleAll(e){for(let t of e._entries)this.#t.push({endpoint:t.endpoint.introspect(),handler:t.handler,middlewares:t.middlewares,handlerErrorsMapped:t.handlerErrorsMapped,prepare:t.prepare,idempotency:t.idempotency,errors:t.errors});for(let t of e._subscriptions)this.#n.push({endpoint:t.endpoint.introspect(),handler:t.handler,middlewares:t.middlewares});return this}getRegistrations(){return[...this.#t]}getSubscriptionRegistrations(){return[...this.#n]}webhook(e){return this.#r.push(e),this}getWebhooks(){return[...this.#r]}getAuthenticationConfig(){return this.#c}async listen(e,t){let n=new ue;for(let l of this.#t){if(l.endpoint.idempotent&&typeof l.idempotency?.scope!="function")throw new TypeError("Idempotent endpoints require an explicit scope policy");if(l.idempotency&&!l.endpoint.idempotent)throw new TypeError("An idempotency policy requires an idempotent contract");l.errors&&ve({introspect:()=>l.endpoint}),l.idempotency&&de({...l.idempotency,scope:()=>{}}),n.addRoute(l)}for(let l of this.#n)n.addSubscriptionRoute(l);n.finalize();let s=this.#e.buildServiceProvider({validateScopes:!1}),r=[];if(this.#c&&r.push(Wt(this.#c)),this.#i!==null){let l=new Map;if(this.#i.policies)for(let[u,h]of Object.entries(this.#i.policies)){let f=new Dt;h(f),l.set(u,f.build(u))}let p=new Ft(l);r.push(Vt(p,this.#c))}let i=[...r,...this.#o],d=new me(n,s,this.#s,i,this.#l,this.#n.length>0,this.#u,this.#d.maxBodySize,this.#a),a=e??this.#d.port??3e3,c=t??this.#d.host??"0.0.0.0";return await d.start(a,c,this.#d),d}},$t=1024,me=class{#e;#t=new Map;#n=new WeakMap;#r;#o;#s;#d;#c;#i;#l;#u;#a=null;#p=null;#f=new Set;constructor(e,t,n,s,r=!1,i=!1,d=null,a=V,c){this.#e=e,this.#r=t,this.#o=n,this.#s=s,this.#d=r,this.#c=i,this.#i=d,this.#l=a,this.#u=c===void 0?void 0:new le(c)}async start(e,t,n){let s=(r,i)=>{this.#h(r,i).catch(d=>{i.headersSent||(i.writeHead(500,{"content-type":P}),i.end(T(E(500))))})};n.https?this.#a=tt.createServer({key:n.https.key,cert:n.https.cert},s):this.#a=ge.createServer(s),await new Promise(r=>{this.#a.listen(e,t,r)}),this.#c&&(this.#p=new Jt({noServer:!0,maxPayload:this.#l}),this.#a.on("upgrade",(r,i,d)=>{let a=new URL(r.url??"/",`http://${r.headers.host??"localhost"}`).pathname,c=this.#e.matchSubscription(a);if(!c){i.write(`HTTP/1.1 404 Not Found\r
1
+ import{a as we,b as st,c as it,d as at,e as qe,f as dt,g as Ne,h as ct,i as Re,j as lt,k as ut,l as pt,m as ft,n as ht,o as yt,p as _e,q as mt,r as gt,s as wt,t as Rt}from"./chunk-YCSREVQU.js";var j=class{static ok(e,t){return new k(e,200,t)}static created(e,t,n){let s={...n};return t&&(s.location=t),new k(e,201,s)}static accepted(e,t){return new k(e,202,t)}static noContent(){return new U}static badRequest(e,t){return new k(e,400,t)}static unauthorized(e,t){return new k(e,401,t)}static forbidden(e,t){return new k(e,403,t)}static notFound(e,t){return new k(e,404,t)}static conflict(e,t){return new k(e,409,t)}static redirect(e,t=!1){return new ne(e,t)}static json(e,t=200,n){return new k(e,t,n)}static file(e,t,n="application/octet-stream"){return new Z(e,t,n)}static content(e,t,n=200){return new ee(e,t,n)}static stream(e,t,n){return new te(e,t,n)}static raw(e){return new Y(e)}static status(e,t){return new G(e,t)}},Y=class extends j{handler;constructor(e){super(),this.handler=e}async executeAsync(e,t,n){await this.handler(e,t)}},k=class extends j{body;status;headers;constructor(e,t=200,n){super(),this.body=e,this.status=t,this.headers=n??{}}async executeAsync(e,t,n){for(let[s,r]of Object.entries(this.headers))t.setHeader(s,r);if(this.body===null||this.body===void 0){t.writeHead(this.status),t.end();return}t.writeHead(this.status,{"content-type":"application/json"}),t.end(JSON.stringify(this.body))}},Z=class extends j{content;fileName;contentType;constructor(e,t,n="application/octet-stream"){super(),this.content=e,this.fileName=t,this.contentType=n}async executeAsync(e,t,n){let s=this.fileName,r=s.replace(/[^\x20-\x7E]/g,"_"),i=r===s?`attachment; filename="${s}"`:`attachment; filename="${r}"; filename*=UTF-8''${encodeURIComponent(s)}`;t.writeHead(200,{"content-type":this.contentType,"content-disposition":i,"content-length":String(this.content.byteLength)}),t.end(this.content)}},ee=class extends j{body;contentType;status;constructor(e,t,n=200){super(),this.body=e,this.contentType=t,this.status=n}async executeAsync(e,t,n){t.writeHead(this.status,{"content-type":this.contentType}),t.end(this.body)}},te=class extends j{readable;contentType;fileName;constructor(e,t,n){super(),this.readable=e,this.contentType=t,this.fileName=n}async executeAsync(e,t,n){let s={"content-type":this.contentType};this.fileName&&(s["content-disposition"]=`attachment; filename="${this.fileName}"`),t.writeHead(200,s),await new Promise((r,i)=>{this.readable.on("error",i),t.on("error",i),this.readable.on("end",r),this.readable.pipe(t,{end:!0})})}},G=class extends j{status;headers;constructor(e,t){super(),this.status=e,this.headers=t??{}}async executeAsync(e,t,n){t.writeHead(this.status,this.headers),t.end()}},ne=class extends j{url;permanent;constructor(e,t=!1){super(),this.url=e,this.permanent=t}async executeAsync(e,t,n){t.writeHead(this.permanent?301:302,{location:this.url}),t.end()}},U=class extends j{async executeAsync(e,t,n){t.writeHead(204),t.end()}};function q(o){return JSON.parse(o,(e,t)=>{if(!(e==="__proto__"||e==="constructor"))return t})}function N(o,e=64){be(o,0,e)}function be(o,e,t){if(!(o===null||typeof o!="object")){if(e>=t)throw new Error(`JSON nesting depth exceeds maximum of ${t}`);if(Array.isArray(o))for(let n of o)be(n,e+1,t);else for(let n of Object.values(o))be(n,e+1,t)}}var Fe={mimeType:"application/json",serialize(o){return JSON.stringify(o)},deserialize(o){let e=q(o);return N(e),e}},De={mimeType:"application/x-www-form-urlencoded",serialize(o){let e=new URLSearchParams;if(o&&typeof o=="object"){for(let[t,n]of Object.entries(o))if(n!=null)if(Array.isArray(n))for(let s of n)e.append(t,String(s));else e.append(t,String(n))}return e.toString()},deserialize(o){let e={},t=new URLSearchParams(o);for(let[n,s]of t){if(bt(n))continue;let r=e[n];r===void 0?e[n]=s:Array.isArray(r)?r.push(s):e[n]=[r,s]}return e}};function bt(o){return o==="__proto__"||o==="constructor"||o==="prototype"}function St(o){return o.split(",").map(e=>{let t=e.trim(),[n,...s]=t.split(";").map(i=>i.trim()),r=1;for(let i of s){let[a,c]=i.split("=");a?.trim()==="q"&&c&&(r=parseFloat(c),Number.isNaN(r)&&(r=1))}return{mimeType:n.toLowerCase(),quality:r}}).sort((e,t)=>t.quality-e.quality)}var W=class{#e=new Map;constructor(){this.register(Fe),this.register(De)}register(e){this.#e.set(e.mimeType.toLowerCase(),e)}selectResponseHandler(e){if(!e)return this.#e.get("application/json")??null;let t=St(e);for(let{mimeType:n}of t){if(n==="*/*")return this.#e.get("application/json")??null;let s=this.#e.get(n);if(s)return s}return null}selectRequestHandler(e){if(!e)return null;let t=e.split(";")[0].trim().toLowerCase();return this.#e.get(t)??null}};var re=class o{#e;constructor(e=[]){this.#e=[...e]}on(e,t){return new o([...this.#e,{matches:n=>n instanceof e,translate:t}])}async translate(e){let t=this.#e.find(s=>s.matches(e));if(!t)throw e;let n=await t.translate(e);if(!(n instanceof k)&&!(n instanceof U)&&!(n instanceof G))throw new TypeError("Error translators must return an explicit JSON or bodyless status result");return n}};function vt(){return new re}function Se(o,e,t){return ve(o),(async(...n)=>{try{return await t(...n)}catch(s){return e.translate(s)}})}function ve(o){let e=o.introspect().responsesSchemas;if(!e||Object.keys(e).length===0)throw new TypeError("Error policies require explicit endpoint responses")}var xt={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",409:"Conflict",413:"Payload Too Large",415:"Unsupported Media Type",422:"Unprocessable Content",500:"Internal Server Error",503:"Service Unavailable"};function E(o,e,t,n){return{type:`https://httpstatuses.com/${o}`,status:o,title:e??xt[o]??"Error",...t!==void 0?{detail:t}:{},...n}}function xe(o){return E(400,"Bad Request","One or more validation errors occurred.",{errors:o})}function T(o){return JSON.stringify(o)}var P="application/problem+json";var S=class extends Error{status;title;detail;extensions;constructor(e,t,n,s){super(n??t??`HTTP ${e}`),this.name="HttpError",this.status=e,this.title=t??`HTTP ${e}`,this.detail=n,this.extensions=s}toProblemDetails(){return E(this.status,this.title,this.detail,this.extensions)}},Ee=class extends S{constructor(e){super(404,"Not Found",e),this.name="NotFoundError"}},Ce=class extends S{constructor(e){super(400,"Bad Request",e),this.name="BadRequestError"}},Oe=class extends S{constructor(e){super(401,"Unauthorized",e),this.name="UnauthorizedError"}},Te=class extends S{constructor(e){super(403,"Forbidden",e),this.name="ForbiddenError"}},Pe=class extends S{constructor(e){super(409,"Conflict",e),this.name="ConflictError"}};var oe=Symbol("implementationEntries"),J=class{#e;constructor(e){this.#e=Object.freeze(e.map(t=>Object.freeze({...t,middlewares:t.middlewares?[...t.middlewares]:void 0})))}[oe](){return this.#e}},se=class o{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=Object.freeze({...t}),this.#n=Object.freeze({...n})}get endpoints(){return this.#n}pick(...e){let t={},n={},s=new Set;for(let r of e){if(!Object.hasOwn(this.#t,r))throw new TypeError(`Unknown operation ${this.#e}.${r}`);if(s.has(r))throw new TypeError(`Duplicate operation ${this.#e}.${r}`);s.add(r),Object.defineProperty(t,r,{value:this.#t[r],enumerable:!0}),Object.defineProperty(n,r,{value:this.#n[r],enumerable:!0})}return new o(this.#e,t,n)}withHandlers(e){for(let n of Object.keys(e))if(!Object.hasOwn(this.#n,n))throw new TypeError(`Unknown handler ${this.#e}.${n}`);let t=[];for(let n of Object.keys(this.#n)){let s=this.#n[n],r=Object.hasOwn(e,n)?e[n]:void 0,i=typeof r=="function"?r:r?.handler;if(typeof i!="function")throw new TypeError(`Missing handler ${this.#e}.${n}`);let a=typeof r=="function"?void 0:r?.errors;if(a&&Ne(s))throw new TypeError("HTTP error policies cannot wrap subscription handlers");t.push({group:this.#e,name:n,source:this.#t[n],endpoint:s,handler:a?Se(s,a,i):i,handlerErrorsMapped:!!a,errors:a,prepare:typeof r=="function"?void 0:r?.prepare,idempotency:typeof r=="function"?void 0:r?.idempotency,middlewares:typeof r=="function"?void 0:r?.middlewares})}return new J(t)}},ie=class o extends J{#e;constructor(e,t=[]){super(t),this.#e=Object.freeze(Object.fromEntries(Object.entries(e).map(([n,s])=>[n,Object.freeze({...s})])))}group(e,t){if(!Object.hasOwn(this.#e,e))throw new TypeError(`Unknown contract group ${e}`);let n=this.#e[e],s=t??{};for(let i of Object.keys(s.operations??{}))if(!Object.hasOwn(n,i))throw new TypeError(`Unknown operation ${e}.${i}`);let r=Object.fromEntries(Object.entries(n).map(([i,a])=>[i,Et(a,s,s.operations?.[i]??{})]));return new se(e,n,r)}use(...e){let t=[...this[oe]()],n=new Map;for(let s of t)n.has(s.group)||n.set(s.group,new Set),n.get(s.group).add(s.name);for(let s of e){if(!(s instanceof J))throw new TypeError("Expected an implementation module");for(let r of s[oe]()){if(!Object.hasOwn(this.#e,r.group)||!Object.hasOwn(this.#e[r.group],r.name)||this.#e[r.group][r.name]!==r.source)throw new TypeError(`Incompatible source endpoint ${r.group}.${r.name}`);if(n.get(r.group)?.has(r.name))throw new TypeError(`Duplicate implementation ${r.group}.${r.name}`);n.has(r.group)||n.set(r.group,new Set),n.get(r.group).add(r.name),t.push(r)}}return new o(this.#e,t)}complete(){let e=Object.create(null),t=Object.create(null);for(let s of this[oe]())e[s.group]??=Object.create(null),t[s.group]??=Object.create(null),e[s.group][s.name]=s.endpoint,t[s.group][s.name]={handler:s.handler,handlerErrorsMapped:s.handlerErrorsMapped,prepare:s.prepare,idempotency:s.idempotency,errors:s.errors,middlewares:s.middlewares?[...s.middlewares]:void 0};let n=[];for(let[s,r]of Object.entries(this.#e))for(let i of Object.keys(r))Object.hasOwn(e[s]??{},i)||n.push(`${s}.${i}`);if(n.length)throw new TypeError(`Missing implementations: ${n.join(", ")}`);return Re(e,t)}};function Et(o,e,t){let n=o;(e.inject||t.inject)&&(n=n.inject({...o.introspect().serviceSchemas,...e.inject,...t.inject}));let s=t.authorize??e.authorize;s&&(n=n.authorize(s));let r=t.tags??e.tags;return r&&(n=n.tags(...r)),t.summary!==void 0&&(n=n.summary(t.summary)),t.description!==void 0&&(n=n.description(t.description)),t.operationId!==void 0&&(n=n.operationId(t.operationId)),t.deprecated&&(n=n.deprecated()),n}function Ct(o){return new ie(o)}import{createHash as Ot}from"crypto";async function ae(o,e,t){let{write:n,writeHead:s,end:r}=o,i=[],a=0,c=!1,d={},l=(p,u)=>{if(p==null||typeof p=="function"||a>t)return;let h=typeof p=="string"?Buffer.from(p,typeof u=="string"?u:"utf8"):Buffer.from(p);a+=h.length,a>t?i.length=0:i.push(h)};o.writeHead=function(p,...u){let h=typeof u[0]=="string"?u[1]:u[0];if(Array.isArray(h)){let m={};for(let g=0;g<h.length;g+=2){let w=h[g].toLowerCase(),O=m[w];m[w]=O===void 0?h[g+1]:[...Array.isArray(O)?O:[String(O)],h[g+1]]}d={...d,...m}}else if(h)for(let[m,g]of Object.entries(h))d[m.toLowerCase()]=g;let f=Reflect.apply(s,this,[p,...u]);return d={...d,...this.getHeaders?.()},f},o.write=function(p,...u){return l(p,u[0]),Reflect.apply(n,this,[p,...u])},o.end=function(p,...u){l(p,u[0]);let h=Reflect.apply(r,this,[p,...u]);return c=!0,d={...d,...this.getHeaders?.()},h};try{return await e(),!c||a>t?void 0:{status:o.statusCode,headers:d,body:Buffer.concat(i)}}finally{o.write=n,o.writeHead=s,o.end=r}}function de(o){if(typeof o?.scope!="function")throw new TypeError("idempotency requires an explicit scope");let{scope:e,ttl:t=864e5,headerName:n="x-idempotency-key",skip:s=c=>!["POST","PUT","DELETE","PATCH"].includes(c.method),maxEntries:r=1e3,maxResponseBytes:i=65536}=o;for(let[c,d]of Object.entries({ttl:t,maxEntries:r,maxResponseBytes:i}))if(!Number.isSafeInteger(d)||d<=0)throw new TypeError(c+" must be a positive safe integer");let a=new Map;return async(c,d)=>{let l=c.headers[n.toLowerCase()]??c.headers[n];if(s(c)||!l)return d();if(l.length>256)throw new S(400,"Idempotency key is too long");let p=e(c);if(p===void 0)return d();if(typeof p!="string")throw new TypeError("Idempotency scope must be a string");let u=Ot("sha256").update(JSON.stringify([p,c.method,c.url?.href??"/",l])).digest("hex"),h=Date.now();for(let[y,v]of a)v.expiresAt<=h&&a.delete(y);let f=a.get(u);if(f){let y=await f.result;if(!y)throw new S(409,"The previous response cannot be replayed; verify the operation outcome");c.response.writeHead(y.status,y.headers),c.response.end(y.body),c.responded=!0;return}if(a.size>=r)throw new S(503,"Idempotency capacity reached");let m,g,w=new Promise((y,v)=>{m=y,g=v});w.catch(()=>{});let O={result:w,expiresAt:1/0};a.set(u,O);try{let y=await ae(c.response,d,i);O.expiresAt=Date.now()+t,m(y)}catch(y){throw a.delete(u),g(y),y}}}function Tt(o){return["POST","PUT","DELETE","PATCH"].includes(o.toUpperCase())}function Pt(o={}){let{defaultTtl:e=6e4,maxEntries:t=1e3,maxResponseBytes:n=65536}=o,s={...o.ttlByTag};for(let[c,d]of Object.entries({maxEntries:t,maxResponseBytes:n}))if(!Number.isSafeInteger(d)||d<=0)throw new TypeError(c+" must be a positive safe integer");for(let c of[e,...Object.values(s)])if(!Number.isFinite(c)||c<0)throw new TypeError("Cache TTL must be finite and non-negative");let r=new Map,i=new Map,a=c=>c.every(([d,l])=>i.get(d)===l);return async(c,d)=>{let p=c.items.get("__endpoint_meta")?.cacheTags??[];if(p.length===0)return d();if(Tt(c.method)){let u=p.map(h=>h.name);if(await d(),c.response.statusCode>=200&&c.response.statusCode<300){for(let[h,f]of i)u.some(m=>h.startsWith(m))&&i.set(h,f+1);for(let[h,f]of r)a(f.generations)||r.delete(h)}return}if(c.method==="GET"){for(let[y,v]of r)v.expiresAt<=Date.now()&&r.delete(y);let u={params:c.pathParams??{},body:void 0,query:c.queryParams??{},headers:c.headers??{}},h=p.map(y=>we(y,u)),f=p.map(({name:y})=>(i.has(y)||i.set(y,0),[y,i.get(y)]));for(let y of h){let v=r.get(y);if(v&&v.expiresAt>Date.now()&&a(v.generations)){let M=c.response;M.writeHead(v.status,v.headers),M.end(v.body),c.responded=!0;return}v&&r.delete(y)}let m=await ae(c.response,d,n);if(!m)return;let{status:g,headers:w,body:O}=m;if(Object.keys(w).some(y=>y.toLowerCase()==="set-cookie")||/\b(?:private|no-store)\b/i.test(String(w["cache-control"]??"")))return;if(g>=200&&g<300&&a(f)){let y=p.reduce((v,M)=>{let B=s[M.name]!==void 0?s[M.name]:e;return B>v?B:v},0);if(y>0)for(let v of h)!r.has(v)&&r.size>=t&&r.delete(r.keys().next().value),r.set(v,{status:g,headers:w,body:O,expiresAt:Date.now()+y,generations:f})}return}return d()}}import{URL as kt}from"url";import{any as ce,boolean as Mt,func as ze,object as At,promise as Ge,record as ke,string as _}from"@cleverbrush/schema";var jt=At({method:_(),url:ce().hasType(),pathParams:ke(_(),_()),queryParams:ke(_(),_()),headers:ke(_(),_()),items:ce(),body:ze().hasReturnType(Ge(ce())),json:ze().hasReturnType(Ge(ce())),responded:Mt()}),V=5*1024*1024,L=class{request;response;url;method;headers;items=new Map;maxBodySize;#e={};_queryParams;#t;#n;#r=void 0;#o=!1;responded=!1;principal=void 0;constructor(e,t,n){this.request=e,this.response=t,this.method=(e.method??"GET").toUpperCase(),this.maxBodySize=n??V;let s=e.url??"/";this.url=new kt(s,`http://${e.headers.host??"localhost"}`);let r=Object.create(null);for(let[i,a]of Object.entries(e.headers))typeof a=="string"?r[i]=a:Array.isArray(a)&&(r[i]=a.join(", "));this.headers=r}get pathParams(){return this.#e}set pathParams(e){this.#e=e}get queryParams(){if(this._queryParams)return this._queryParams;let e=Object.create(null);for(let[t,n]of this.url.searchParams)e[t]=n;return e}get services(){return this.#t}set services(e){this.#t=e}async body(){return this.#n?this.#n:(this.#n=new Promise((e,t)=>{let n=[],s=0,r=!1,i=()=>{this.request.off("data",l),this.request.off("end",p),this.request.off("error",a),this.request.off("aborted",c),this.request.off("close",d)},a=u=>{r||(r=!0,i(),n.length=0,t(u))},c=()=>a(new S(400,"Request body interrupted")),d=()=>{this.request.readableEnded||c()},l=u=>{if(!r){if(s+=u.length,s>this.maxBodySize){a(new S(413,"Payload Too Large")),this.request.destroy();return}n.push(u)}},p=()=>{r||(r=!0,i(),e(Buffer.concat(n)))};if(this.request.destroyed||this.request.readableEnded){c();return}this.request.on("data",l),this.request.on("end",p),this.request.on("error",a),this.request.on("aborted",c),this.request.on("close",d)}),this.#n)}async json(){if(this.#o)return this.#r;let t=(await this.body()).toString("utf-8");return t.length>0&&(this.#r=q(t),N(this.#r)),this.#o=!0,this.#r}};import*as ge from"http";import*as nt from"https";import{AuthorizationService as Gt,PolicyBuilder as Ut,Principal as he,parseCookies as Jt,requireRole as Lt}from"@cleverbrush/auth";import{ServiceCollection as $t}from"@cleverbrush/di";import{WebSocketServer as Kt}from"ws";var Ht=/[^!#$%&'*+\-.^_`|~\da-zA-Z]/,Ue=new Set(["access-control-allow-origin","access-control-allow-credentials","access-control-allow-methods","access-control-allow-headers","access-control-expose-headers","access-control-max-age"]);function Je(o){if(typeof o!="string")return!1;if(o==="null")return!0;try{let e=new URL(o).origin;return e!=="null"&&e===o}catch{return!1}}function Ae(o){return typeof o=="string"&&o.length>0&&!Ht.test(o)}function Me(o,e){if(o===void 0)return[];if(!Array.isArray(o)||o.some(t=>!Ae(t)||t==="*"))throw new TypeError(`CORS ${e} must contain explicit HTTP tokens`);return[...new Set(o.map(t=>t.toLowerCase()))]}function Bt(o,e){let t=new Map;for(let n of[...o,...e])if(n!==void 0)for(let s of String(n).split(",")){let r=s.trim();if(r==="*")return"*";r&&!t.has(r.toLowerCase())&&t.set(r.toLowerCase(),r)}return[...t.values()].join(", ")}function It(o,e,t){let n=o.writeHead;o.writeHead=function(s,...r){let i=typeof r[0]=="string"||r.length>1?1:0,a=r[i],c=[this.getHeader("vary")],d=(l,p)=>{let u=l.toLowerCase();return u==="vary"&&c.push(p),u!=="vary"&&!Ue.has(u)};if(Array.isArray(a)){let l=[];for(let p=0;p<a.length;p+=2)d(a[p],a[p+1])&&l.push(a[p],a[p+1]);r[i]=l}else a!==void 0&&(r[i]=Object.fromEntries(Object.entries(a).filter(([l,p])=>d(l,p))));for(let l of Ue)this.removeHeader(l);for(let[l,p]of Object.entries(e))this.setHeader(l,p);return this.setHeader("vary",Bt(c,t)),n.call(this,s,...r)}}function H(o,e,t){return o.writeHead(e,{"content-type":P,...t?{allow:t.join(", ")}:{}}),o.end(T(E(e))),!0}var le=class{#e;#t;#n;#r;#o;#s;constructor(e){let t=e?.origin;if(t==="*")this.#e="*";else if(typeof t=="function")this.#e=t;else{let s=typeof t=="string"?[t]:t;if(!Array.isArray(s)||s.some(r=>!Je(r)))throw new TypeError("CORS origin must be a serialized origin, list, wildcard or predicate");this.#e=new Set(s)}if(e.credentials!==void 0&&typeof e.credentials!="boolean")throw new TypeError("CORS credentials must be a boolean");if(this.#o=e.credentials??!1,this.#o&&this.#e==="*")throw new TypeError("CORS credentials require explicit origins or a predicate");if(this.#s=e.maxAgeSeconds===void 0?0:e.maxAgeSeconds,!Number.isSafeInteger(this.#s)||this.#s<0)throw new TypeError("CORS maxAgeSeconds must be a non-negative safe integer");let n=Me(e.methods,"methods");e.methods!==void 0&&(this.#t=new Set(n.map(s=>s.toUpperCase()))),this.#n=new Set(Me(e.allowedHeaders,"allowedHeaders")),this.#r=Me(e.exposedHeaders,"exposedHeaders").join(", ")}async handle(e,t,n){let s=e.headers.origin,r=e.method?.toUpperCase()==="OPTIONS"&&s!==void 0&&e.headers["access-control-request-method"]!==void 0,i={};if(It(t,i,r?["Origin","Access-Control-Request-Method","Access-Control-Request-Headers"]:["Origin"]),s===void 0)return!1;if(!Je(s))return H(t,403);let a;try{if(a=this.#e==="*"||(typeof this.#e=="function"?await this.#e(s):this.#e.has(s)),typeof a!="boolean")return H(t,500)}catch{return H(t,500)}if(!a)return H(t,403);if(r){let c=e.headers["access-control-request-method"],d=e.headers["access-control-request-headers"];if(!Ae(c)||c==="*"||d!==void 0&&typeof d!="string")return H(t,400);let l=d===void 0?[]:d.split(",").map(h=>h.trim().toLowerCase());if(l.some(h=>!Ae(h)||h==="*"))return H(t,400);let p;try{p=new URL(e.url??"/",`http://${e.headers.host??"localhost"}`).pathname}catch{return H(t,400)}let u=n(c.toUpperCase(),p);if(u.status!==200)return H(t,u.status,u.allowedMethods);if(this.#t&&!this.#t.has(c.toUpperCase())||l.some(h=>!this.#n.has(h)))return H(t,403);i["access-control-allow-methods"]=c,l.length&&(i["access-control-allow-headers"]=[...new Set(l)].join(", ")),i["access-control-max-age"]=String(this.#s)}else this.#r&&(i["access-control-expose-headers"]=this.#r);return i["access-control-allow-origin"]=this.#e==="*"?"*":s,this.#o&&(i["access-control-allow-credentials"]="true"),r?(t.writeHead(204),t.end(),!0):!1}};var $=class{#e=[];add(e){this.#e.push(e)}async execute(e,t){let n=0,s=async()=>{if(n<this.#e.length){let r=this.#e[n++];await r(e,s)}else await t()};await s()}};import{Busboy as qt}from"@fastify/busboy";function A(o,e,t){let n=t===void 0?"/files":`/files/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`;return new S(o,o===413?"Payload Too Large":"Bad Request",e,{errors:[{pointer:n,detail:e}]})}async function Le(o,e,t){let n=e.maxFileCount??10,s=e.maxFieldCount??100,r=e.schema?.introspect().properties,i=Object.create(null),a=Object.create(null),c=[],d=new Set;if(Number(o.headers["content-length"])>t)throw o.resume(),A(413,"Multipart request exceeds maxBodySize");await new Promise((u,h)=>{let f=!1,m=0,g=new Map,w=qt({headers:o.headers,limits:{fileSize:e.maxFileSize??10*1024*1024,files:n,fieldSize:e.maxFieldSize??1024*1024,fields:s,parts:e.maxPartCount??n+s}}),O=()=>{o.unpipe(w),o.off("data",v),o.off("aborted",M),o.off("error",b),o.off("close",B);for(let[R,C]of g)C.length=0,R.destroy();g.clear()},y=R=>{if(!f){f=!0,O();for(let C of Object.keys(a))delete a[C];w.destroy(),o.resume(),h(R instanceof S?R:A(400,"Malformed multipart request"))}},v=R=>{m+=R.length,m>t&&y(A(413,"Multipart request exceeds maxBodySize"))},M=()=>y(A(400,"Multipart request interrupted")),B=()=>{o.complete||M()},b=R=>y(R),x=R=>Buffer.byteLength(R)>(e.maxFieldNameSize??100)?(y(A(413,"Multipart field name is too long",R)),!1):!0;w.on("field",(R,C,D,Be)=>{if(!(f||!x(R))){if(D||Be){y(A(413,"Multipart field exceeds its size limit",R));return}if(Object.hasOwn(i,R)||d.has(R)||r&&Object.hasOwn(r,R)){y(A(400,"Duplicate or incorrectly encoded multipart field",R));return}i[R]=C}}),w.on("file",(R,C,D,Be,z)=>{let Q=[];if(g.set(C,Q),C.on("error",b),C.on("limit",()=>y(A(413,"File exceeds maxFileSize",R))),f||!x(R)){C.resume();return}let Ie=r&&Object.hasOwn(r,R)?r[R]:void 0,rt=Ie?.introspect().type==="array";if(r&&!Ie||Object.hasOwn(i,R)||d.has(R)&&!rt){y(A(400,"Unknown or duplicate file field",R));return}if(d.add(R),!(!e.allowedMimeTypes||e.allowedMimeTypes.some(I=>I.endsWith("/*")?z.startsWith(I.slice(0,-1)):z===I))){if(r){y(A(400,`MIME type "${z}" is not allowed`,R));return}c.push({fieldName:R,filename:D,mimeType:z,reason:`MIME type "${z}" is not allowed`}),C.on("end",()=>g.delete(C)),C.resume();return}let X=a[R]??[];a[R]=X;let ot=X.length;X.push(void 0),C.on("data",I=>{f||Q.push(I)}),C.on("end",()=>{if(g.delete(C),f)return;if(C.truncated){y(A(413,"File was truncated",R));return}let I=Buffer.concat(Q);Q.length=0,X[ot]={filename:D,mimeType:z,buffer:I,size:I.length}})}),w.on("filesLimit",()=>y(A(413,"Exceeded maxFileCount"))),w.on("fieldsLimit",()=>y(A(413,"Exceeded maxFieldCount"))),w.on("partsLimit",()=>y(A(413,"Exceeded maxPartCount"))),w.on("error",b),w.on("finish",()=>{f||(f=!0,O(),u())}),o.on("data",v),o.once("aborted",M),o.once("error",b),o.once("close",B),o.pipe(w)});let p=Object.create(null);for(let[u,h]of Object.entries(a))p[u]=r?.[u]?.introspect().type==="array"?h:h[0];if(e.schema){for(let[h,f]of Object.entries(r)){let m=f.introspect();m.type==="array"&&m.isRequired&&!Object.hasOwn(p,h)&&(p[h]=[])}let u=await e.schema.validateAsync(p,{doNotStopOnFirstError:!0});if(!u.valid){let h=u.getInvalidProperties().flatMap(f=>f.errors.map(m=>({pointer:`/files${f.descriptor.toJsonPointer()}`,detail:m})));throw new S(400,"Bad Request","Upload contract validation failed",{errors:h.length?h:u.errors?.map(f=>({pointer:"/files",detail:f.message}))})}return{fields:i,files:Object.fromEntries(Object.entries(u.object).filter(([,h])=>h!==void 0)),rejectedFiles:c}}return{fields:i,files:p,rejectedFiles:c}}function $e(o){return o.bodySchema!=null}async function Ke(o,e,t,n){let s=[],r={};if(r.context=t,o.authRoles!==null&&t.principal!==void 0&&(r.principal=t.principal),e&&Object.keys(e).length>0&&(r.params=e),o.bodySchema){let i=await o.bodySchema.validateAsync(n,{doNotStopOnFirstError:!0});if(i.valid)r.body=i.object;else{let a=typeof i.getInvalidProperties=="function"?i.getInvalidProperties:null,c=!1;if(a)for(let d of a()){let l=d.descriptor.toJsonPointer();for(let p of d.errors)s.push({pointer:`/body${l}`,detail:p}),c=!0}if(!c)for(let d of i.errors??[])s.push({pointer:"/body",detail:d.message})}}if(o.querySchema){let i=o.querySchema.introspect();if(i.type!=="object"||!i.properties)throw new Error("Endpoint query schema must be an object schema whose properties map to query parameter names.");let a=i.properties,c={};for(let[d,l]of Object.entries(a)){let p=t.queryParams[d],u=await l.validateAsync(p,{doNotStopOnFirstError:!0});if(u.valid)c[d]=u.object;else for(let h of u.errors??[])s.push({pointer:`/query/${d.replace(/~/g,"~0").replace(/\//g,"~1")}`,detail:h.message})}r.query=c}if(o.headerSchema){let i=o.headerSchema.introspect();if(i.type!=="object"||!i.properties)throw new Error("Endpoint headers schema must be an object schema whose properties map to header names.");let a=i.properties,c={};for(let[d,l]of Object.entries(a)){let p=t.headers[d.toLowerCase()],u=await l.validateAsync(p,{doNotStopOnFirstError:!0});if(u.valid)c[d]=u.object;else for(let h of u.errors??[])s.push({pointer:`/headers/${d.replace(/~/g,"~0").replace(/\//g,"~1")}`,detail:h.message})}r.headers=c}if(s.length>0)return{valid:!1,problemDetails:xe(s)};if(o.serviceSchemas){if(!t.services)throw new Error("Endpoint declares .inject() dependencies but no service provider is available. Register services via createServer().services() before handling this endpoint.");let i={};for(let[a,c]of Object.entries(o.serviceSchemas))i[a]=t.services.get(c);return{valid:!0,args:[r,i]}}return{valid:!0,args:[r]}}function K(o){let e=decodeURI(o);return e.length>1&&e.endsWith("/")?e.slice(0,-1):e}function je(o){return typeof o!="string"&&typeof o.validate=="function"}function We(o){let e=0,t=!1;for(let n of o)for(let s of n)s==="/"?(t&&e++,t=!1):t=!0;return e+(t?1:0)}function Nt(o,e){if(!je(e)){let r=K(e),i=r==="/"?o||"/":o+r;return{isStatic:!0,literalSegments:We([i]),dynamicSegments:0}}let{literals:t,segments:n}=e.introspect().templateDefinition,s=[o+(t[0]??""),...t.slice(1)];return{isStatic:n.length===0,literalSegments:We(s),dynamicSegments:n.length}}function _t(o,e){return o.isStatic!==e.isStatic?o.isStatic?1:-1:o.literalSegments!==e.literalSegments?o.literalSegments-e.literalSegments:e.dynamicSegments-o.dynamicSegments}function Ft(o,e){if(!je(e)){let s=K(e);return s==="/"?o||"/":o+s}let{literals:t,segments:n}=e.introspect().templateDefinition;return n.length>0?null:o+(t[0]??"")}function Ve(o,e,t){let n=K(o);return{basePath:n,routePath:e,specificity:Nt(n,e),exactPath:Ft(n,e),registration:t}}function Qe(){return{exactRoutes:new Map,dynamicRoutes:[]}}function Xe(o,e){if(e.exactPath!==null){o.exactRoutes.has(e.exactPath)||o.exactRoutes.set(e.exactPath,e);return}o.dynamicRoutes.push(e)}var ue=class{#e=new Map;#t=Qe();#n=!0;addRoute(e){let{method:t,basePath:n,pathTemplate:s}=e.endpoint,r=t.toUpperCase(),i=Ve(n,s,e),a=this.#e.get(r);a||(a=Qe(),this.#e.set(r,a)),Xe(a,i),this.#n=!1}finalize(){if(!this.#n){for(let e of this.#e.values())this.#o(e.dynamicRoutes);this.#o(this.#t.dynamicRoutes),this.#n=!0}}match(e,t){let n;try{n=K(t)}catch{return{match:null,methodNotAllowed:!1,badRequest:!0}}let s=e.toUpperCase();this.finalize();let r=this.#e.get(s);if(r){let a=this.#r(r,n,t);if(a)return{match:a,methodNotAllowed:!1}}let i=[];for(let[a,c]of this.#e)a!==s&&this.#r(c,n,t)&&i.push(a);return i.length>0?{match:null,methodNotAllowed:!0,allowedMethods:i}:{match:null,methodNotAllowed:!1}}#r(e,t,n){let s=e.exactRoutes.get(t);if(s){let r=this.#s(s,t,n);if(r)return r}for(let r of e.dynamicRoutes){let i=this.#s(r,t,n);if(i)return i}return null}#o(e){e.sort((t,n)=>_t(n.specificity,t.specificity))}#s(e,t,n){let{basePath:s,routePath:r}=e;if(s&&!t.startsWith(s))return null;let i=s?t.slice(s.length):t;if(je(r)){let d=_e({basePath:s,pathTemplate:r},n);return d!==void 0?{registration:e.registration,parsedPath:d}:null}let a=K(r);return(i.length===0?"/":i)===a?{registration:e.registration,parsedPath:null}:null}addSubscriptionRoute(e){let{basePath:t,pathTemplate:n}=e.endpoint;Xe(this.#t,Ve(t,n,e)),this.#n=!1}matchSubscription(e){let t;try{t=K(e)}catch{return null}return this.finalize(),this.#r(this.#t,t,e)}};import{Readable as Dt,Writable as zt}from"stream";var pe=class extends Dt{method;url;headers;__cleverbrushBatchSubrequest;socket=null;#e;#t=!1;constructor(e){super(),this.method=e.method,this.url=e.url;let t={};for(let[n,s]of Object.entries(e.headers??{}))t[n.toLowerCase()]=s;this.headers={host:"localhost",...t},this.#e=e.body!=null&&e.body.length>0?Buffer.from(e.body,"utf-8"):Buffer.alloc(0)}_read(){this.#t||(this.#t=!0,this.#e.length>0&&this.push(this.#e),this.push(null))}},fe=class extends zt{statusCode=200;headersSent=!1;#e=[];#t={};_write(e,t,n){this.#e.push(Buffer.isBuffer(e)?e:Buffer.from(e)),n()}writeHead(e,t){if(this.statusCode=e,t!=null&&typeof t=="object"&&!Array.isArray(t))for(let[n,s]of Object.entries(t))this.#t[n.toLowerCase()]=Array.isArray(s)?s.join(", "):String(s);return this.headersSent=!0,this}setHeader(e,t){return this.#t[e.toLowerCase()]=Array.isArray(t)?t.join(", "):String(t),this}getHeader(e){return this.#t[e.toLowerCase()]}getHeaders(){return{...this.#t}}end(e,...t){if(e!=null&&typeof e!="function"){let n=Buffer.isBuffer(e)||e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),"utf-8");this.#e.push(n),super.end(...t)}else typeof e=="function"?super.end(e):super.end(...t);return this}toResult(){return{status:this.statusCode,headers:{...this.#t},body:Buffer.concat(this.#e).toString("utf-8")}}};function Ye(o){return{type:"message",data:o}}function Ze(o,e){return{type:"tracked",id:o,data:e}}function et(){return{type:"pong"}}function F(o,e){return{type:"error",code:o,message:e}}function tt(o){let e;try{e=q(o),N(e)}catch{return null}if(typeof e!="object"||e===null)return null;let t=e;return t.type==="ping"?{type:"ping"}:t.type==="message"&&"data"in t?{type:"message",data:t.data}:null}var ye=class{#e=new $t;#t=[];#n=[];#r=[];#o=[];#s=new W;#d;#c=null;#i=null;#l=!1;#u=null;#a;constructor(e={}){this.#d=e}services(e){return e(this.#e),this}use(e){return this.#o.push(e),this}useCors(e){if(e===void 0)throw new TypeError("CORS requires an explicit origin policy");return this.#a=e,this}contentType(e){return this.#s.register(e),this}useAuthentication(e){return this.#c=e,this}useAuthorization(e){return this.#i=e??{},this}withHealthcheck(){return this.#l=!0,this}useBatching(e={}){return this.#u=e,this}handle(e,t,n){return this.#t.push({endpoint:e.introspect(),handler:t,middlewares:n?.middlewares,prepare:n?.prepare,idempotency:n?.idempotency,errors:n?.errors}),this}handleAll(e){for(let t of e._entries)this.#t.push({endpoint:t.endpoint.introspect(),handler:t.handler,middlewares:t.middlewares,handlerErrorsMapped:t.handlerErrorsMapped,prepare:t.prepare,idempotency:t.idempotency,errors:t.errors});for(let t of e._subscriptions)this.#n.push({endpoint:t.endpoint.introspect(),handler:t.handler,middlewares:t.middlewares});return this}getRegistrations(){return[...this.#t]}getSubscriptionRegistrations(){return[...this.#n]}webhook(e){return this.#r.push(e),this}getWebhooks(){return[...this.#r]}getAuthenticationConfig(){return this.#c}async listen(e,t){let n=new ue;for(let l of this.#t){if(l.endpoint.idempotent&&typeof l.idempotency?.scope!="function")throw new TypeError("Idempotent endpoints require an explicit scope policy");if(l.idempotency&&!l.endpoint.idempotent)throw new TypeError("An idempotency policy requires an idempotent contract");l.errors&&ve({introspect:()=>l.endpoint}),l.idempotency&&de({...l.idempotency,scope:()=>{}}),n.addRoute(l)}for(let l of this.#n)n.addSubscriptionRoute(l);n.finalize();let s=this.#e.buildServiceProvider({validateScopes:!1}),r=[];if(this.#c&&r.push(Xt(this.#c)),this.#i!==null){let l=new Map;if(this.#i.policies)for(let[u,h]of Object.entries(this.#i.policies)){let f=new Ut;h(f),l.set(u,f.build(u))}let p=new Gt(l);r.push(Yt(p,this.#c))}let i=[...r,...this.#o],a=new me(n,s,this.#s,i,this.#l,this.#n.length>0,this.#u,this.#d.maxBodySize,this.#a),c=e??this.#d.port??3e3,d=t??this.#d.host??"0.0.0.0";return await a.start(c,d,this.#d),a}},Wt=1024,me=class{#e;#t=new Map;#n=new WeakMap;#r;#o;#s;#d;#c;#i;#l;#u;#a=null;#p=null;#f=new Set;constructor(e,t,n,s,r=!1,i=!1,a=null,c=V,d){this.#e=e,this.#r=t,this.#o=n,this.#s=s,this.#d=r,this.#c=i,this.#i=a,this.#l=c,this.#u=d===void 0?void 0:new le(d)}async start(e,t,n){let s=(r,i)=>{this.#h(r,i).catch(a=>{i.headersSent||(i.writeHead(500,{"content-type":P}),i.end(T(E(500))))})};n.https?this.#a=nt.createServer({key:n.https.key,cert:n.https.cert},s):this.#a=ge.createServer(s),await new Promise(r=>{this.#a.listen(e,t,r)}),this.#c&&(this.#p=new Kt({noServer:!0,maxPayload:this.#l}),this.#a.on("upgrade",(r,i,a)=>{let c=new URL(r.url??"/",`http://${r.headers.host??"localhost"}`).pathname,d=this.#e.matchSubscription(c);if(!d){i.write(`HTTP/1.1 404 Not Found\r
2
2
  \r
3
- `),i.destroy();return}this.#p.handleUpgrade(r,i,d,l=>{this.#w(l,r,c.registration,c.parsedPath)})}))}async close(){for(let e of this.#f)e.close(1001,"Server shutting down");this.#f.clear(),this.#p&&(await new Promise((e,t)=>{this.#p.close(n=>{n?t(n):e()})}),this.#p=null),this.#a&&(await new Promise((e,t)=>{this.#a.close(n=>{n?t(n):e()})}),this.#a=null)}get address(){let e=this.#a?.address();return!e||typeof e=="string"?null:{port:e.port,host:e.address}}async#h(e,t,n=!0){if(n&&this.#u&&await this.#u.handle(e,t,(r,i)=>this.#y(r,i)))return;let s=this.#r.createScope();try{let r=new $(e,t,this.#l),i=r.url.pathname,d=r.method,a=e.__cleverbrushBatchSubrequest;if(a&&r.items.set("__batch_subrequest",a),this.#d&&d==="GET"&&i==="/health"){t.writeHead(200),t.end();return}if(this.#i!==null&&d==="POST"&&i===(this.#i.path??"/__batch")){r.services=s.serviceProvider;let f=new K;for(let m of this.#s)f.add(m);await f.execute(r,async()=>{r.responded||(await this.#m(e,t),r.responded=!0)});return}let c=this.#e.match(d,i);if(!c.match){if(c.badRequest){let m=E(400);t.writeHead(400,{"content-type":P}),t.end(T(m));return}if(c.methodNotAllowed){let m=E(405,"Method Not Allowed");t.writeHead(405,{"content-type":P,allow:c.allowedMethods.join(", ")}),t.end(T(m));return}let f=E(404);t.writeHead(404,{"content-type":P}),t.end(T(f));return}let{registration:l,parsedPath:p}=c.match,u=l.endpoint;if(p){let f={};He(p,"",f),r.pathParams=f}r.services=s.serviceProvider,r.items.set("__endpoint_meta",u);let h=new K;for(let f of this.#s)h.add(f);if(l.middlewares)for(let f of l.middlewares)h.add(f);await h.execute(r,async()=>{if(r.responded)return;let f,m,g;if($e(u)||u.fileUpload){let b=e.headers["content-type"]??"";if(u.fileUpload&&b.startsWith("multipart/form-data"))try{let x=await Je(e,u.fileUpload,this.#l);if(u.fileUpload.schema&&!u.bodySchema&&Object.keys(x.fields).length)throw new S(400,"Bad Request","This upload endpoint does not declare text fields",{errors:Object.keys(x.fields).map(R=>({pointer:`/body/${R.replace(/~/g,"~0").replace(/\//g,"~1")}`,detail:"Unexpected multipart text field"}))});f=x.fields,m=x.files,g=x.rejectedFiles}catch(x){if(x instanceof S)throw x;let R=E(400,"Malformed multipart request");t.writeHead(400,{"content-type":P}),t.end(T(R)),r.responded=!0;return}else if(u.fileUpload){let x=E(400,"File upload endpoint requires multipart/form-data content type");t.writeHead(400,{"content-type":P}),t.end(T(x)),r.responded=!0;return}else{let x=this.#o.selectRequestHandler(b);if(x){let C=(await r.body()).toString("utf-8");if(C.length>0)try{f=x.deserialize(C)}catch{let D=E(400,"Malformed request body");t.writeHead(400,{"content-type":P}),t.end(T(D)),r.responded=!0;return}}else if(b){let R=E(415);t.writeHead(415,{"content-type":P}),t.end(T(R)),r.responded=!0;return}}}let w=await Ke(u,p,r,f);if(!w.valid){t.writeHead(400,{"content-type":P}),t.end(T(w.problemDetails)),r.responded=!0;return}if(m&&w.args.length>0){let b=w.args[0];b.files=m,g&&g.length>0&&(b.rejectedFiles=g)}let O=w.args,y=async b=>{r.responded||(await this.#g(e,t,b),r.responded=!0)},v=async b=>{if(!l.errors)throw b;return l.errors.translate(b)},M=r.headers["x-idempotency-key"];if(u.idempotent&&M!==void 0&&(M.length===0||M.length>256))throw new S(400,"Idempotency key must contain 1 to 256 characters");try{if(l.prepare&&(O[0]=await l.prepare(...O)),l.idempotency&&M!==void 0){let b=await l.idempotency.scope(...O);if(typeof b!="string"&&!(Array.isArray(b)&&b.length>0&&b.every(x=>typeof x=="string"||typeof x=="number"&&Number.isFinite(x))))throw new TypeError("Idempotency scope must be a string or identity components");this.#n.set(r,JSON.stringify(b))}}catch(b){await y(await v(b));return}let B=async()=>{let b;try{b=await l.handler(...O)}catch(x){if(l.handlerErrorsMapped)throw x;b=await v(x)}await y(b)};if(l.idempotency){let b=this.#t.get(l);b||(b=de({...l.idempotency,scope:x=>this.#n.get(x)}),this.#t.set(l,b)),await b(r,B)}else await B()})}catch(r){if(t.headersSent)return;if(r instanceof S){let i=r.toProblemDetails();t.writeHead(i.status,{"content-type":P}),t.end(T(i))}else{console.error("[server] Unhandled error:",r);let i=E(500);t.writeHead(500,{"content-type":P}),t.end(T(i))}}finally{try{await s.asyncDispose()}catch{}}}#y(e,t){let n=[];if(this.#d&&t==="/health"&&n.push("GET"),this.#i&&t===(this.#i.path??"/__batch")&&n.push("POST"),n.includes(e))return{status:200};let s=this.#e.match(e,t);if(s.badRequest)return{status:400};if(s.match)return{status:200};let r=[...new Set([...n,...s.allowedMethods??[]])];return r.length?{status:405,allowedMethods:r}:{status:404}}async#m(e,t){let n=this.#i,s=n.maxSize??20,r=n.parallel??!0,i;try{let c=await Lt(e,this.#l),l=N(c.toString("utf-8"));if(q(l),i=l,!Array.isArray(i?.requests))throw new Error("requests must be an array")}catch(c){if(c instanceof S&&c.status===413){let p=E(413,"Payload Too Large");t.writeHead(413,{"content-type":P}),t.end(T(p));return}let l=E(400,"Invalid batch request body");t.writeHead(400,{"content-type":P}),t.end(T(l));return}if(i.requests.length>s){let c=E(400,`Batch size ${i.requests.length} exceeds maximum of ${s}`);t.writeHead(400,{"content-type":P}),t.end(T(c));return}let d=async(c,l)=>{let p=new pe({method:(c.method??"GET").toUpperCase(),url:c.url,headers:{host:e.headers.host??"localhost",...c.headers},body:c.body});p.__cleverbrushBatchSubrequest={index:l,size:i.requests.length,path:n.path??"/__batch"};let u=new fe;return await this.#h(p,u,!1),u.toResult()},a;if(r)a=await Promise.all(i.requests.map(d));else{a=[];for(let c=0;c<i.requests.length;c++)a.push(await d(i.requests[c],c))}t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({responses:a}))}async#g(e,t,n){n instanceof j?await n.executeAsync(e,t,this.#o):n==null?(t.writeHead(204),t.end()):await new k(n,200).executeAsync(e,t,this.#o)}#w(e,t,n,s){this.#f.add(e);let r=this.#r.createScope(),i=new AbortController,d=n.endpoint,a=new ge.ServerResponse(t),c=new $(t,a);if(s){let p={};He(s,"",p),c.pathParams=p}c.services=r.serviceProvider,c.items.set("__endpoint_meta",d);let l=new K;for(let p of this.#s)l.add(p);if(n.middlewares)for(let p of n.middlewares)l.add(p);l.execute(c,async()=>{if(c.responded){e.close(1008,"Unauthorized");return}this.#R(e,c,d,n.handler,s,r,i)}).then(()=>{c.responded&&e.close(1008,"Unauthorized")}).catch(()=>{e.close(1011,"Internal Server Error")}),e.on("close",()=>{this.#f.delete(e),i.abort(),r.asyncDispose().catch(()=>{})}),e.on("error",()=>{this.#f.delete(e),i.abort(),r.asyncDispose().catch(()=>{})})}#R(e,t,n,s,r,i,d){let a=[],c=null,l=!1,p={[Symbol.asyncIterator](){return{next(){return a.length>0?Promise.resolve({value:a.shift(),done:!1}):l?Promise.resolve({value:void 0,done:!0}):new Promise(f=>{c=()=>{c=null,a.length>0?f({value:a.shift(),done:!1}):f({value:void 0,done:!0})}})},return(){return l=!0,Promise.resolve({value:void 0,done:!0})}}}};e.on("message",f=>{let m=typeof f=="string"?f:f.toString("utf-8"),g=et(m);if(!g){e.send(JSON.stringify(F(400,"Invalid frame format")));return}if(g.type==="ping"){e.send(JSON.stringify(Ze()));return}if(a.length>=$t){e.send(JSON.stringify(F(429,"Message queue full \u2014 slow down or reconnect"))),e.close(1008,"Message queue overflow");return}if(n.incomingSchema){let w=n.incomingSchema.validate(g.data);if(!w.valid){let O=(w.errors??[]).map(y=>y.message).join("; ");e.send(JSON.stringify(F(422,`Validation failed: ${O}`)));return}a.push(w.object)}else a.push(g.data);c&&c()}),e.on("close",()=>{l=!0,c&&c()});let u={context:t,signal:d.signal};if(r&&Object.keys(r).length>0&&(u.params=r),n.querySchema){let f={};for(let[g,w]of t.url.searchParams.entries())f[g]=w;let m=n.querySchema.validate(f);if(!m.valid){let g=(m.errors??[]).map(w=>w.message).join("; ");e.close(1002,`Query validation failed: ${g}`);return}u.query=m.object}if(n.headerSchema){let f=n.headerSchema.validate(t.headers);if(!f.valid){let m=(f.errors??[]).map(g=>g.message).join("; ");e.close(1002,`Header validation failed: ${m}`);return}u.headers=f.object}t.principal!==void 0&&(u.principal=t.principal),n.incomingSchema,u.incoming=p;let h=[u];if(n.serviceSchemas){let f={};for(let[m,g]of Object.entries(n.serviceSchemas))f[m]=i.serviceProvider.get(g);h.push(f)}(async()=>{try{let f=s(...h);for await(let m of f){if(e.readyState!==e.OPEN)break;let g;if(Ne(m)){let w=n.outgoingSchema?n.outgoingSchema.validate(m.data):{valid:!0,object:m.data};if(!w.valid){e.send(JSON.stringify(F(500,"Outgoing validation failed")));continue}g=JSON.stringify(Ye(m.id,w.object))}else{let w=n.outgoingSchema?n.outgoingSchema.validate(m):{valid:!0,object:m};if(!w.valid){e.send(JSON.stringify(F(500,"Outgoing validation failed")));continue}g=JSON.stringify(Xe(w.object))}e.send(g)}}catch(f){e.readyState===e.OPEN&&(f instanceof Error&&console.error("[server] Subscription handler error:",f),e.send(JSON.stringify(F(500,"Internal error"))),e.close(1011,"Handler error"))}})()}};function Kt(o){return new ye(o)}function Lt(o,e=V){return new Promise((t,n)=>{let s=[],r=0;o.on("data",i=>{if(r+=i.length,r>e){o.destroy(),n(new S(413,"Payload Too Large"));return}s.push(i)}),o.on("end",()=>t(Buffer.concat(s))),o.on("error",n)})}function He(o,e,t){for(let[n,s]of Object.entries(o)){let r=e?`${e}.${n}`:n;s!==null&&typeof s=="object"&&!Array.isArray(s)?He(s,r,t):t[r]=String(s)}}function Wt(o){let e=new Map;for(let n of o.schemes)e.set(n.name,n);let t;return o.trySchemes==="all"?t=o.schemes:t=(o.trySchemes&&o.trySchemes.length>0?o.trySchemes:[o.defaultScheme]).map(s=>e.get(s)).filter(s=>s!==void 0),async(n,s)=>{if(n.items.get("__endpoint_meta")?.authRoles===null){n.principal=he.anonymous(),await s();return}let i={headers:n.headers,cookies:zt(n.headers.cookie??""),items:n.items};n.principal=he.anonymous();for(let d of t){let a=await d.authenticate(i);if(a.succeeded){n.principal=a.principal;break}}await s()}}function Vt(o,e){let t={};if(e){for(let n of e.schemes)if(n.challenge){let s=n.challenge();t[s.headerName.toLowerCase()]=s.headerValue}}return async(n,s)=>{let r=n.items.get("__endpoint_meta");if(!r||r.authRoles===null){await s();return}let i=n.principal;if(!i||!(i instanceof he)||!i.isAuthenticated){let d=E(401,"Unauthorized"),a={"content-type":P,...t};n.response.writeHead(401,a),n.response.end(T(d)),n.responded=!0;return}if(r.authRoles.length>0&&!(await o.authorize(i,[Gt(...r.authRoles)])).allowed){let a=E(403,"Forbidden");n.response.writeHead(403,{"content-type":P}),n.response.end(T(a)),n.responded=!0;return}i instanceof he&&(n.principal=i.value),await s()}}function Qt(o,e){return{name:o,...e}}export{j as ActionResult,ie as ApiImplementation,Ce as BadRequestError,Pe as ConflictError,W as ContentNegotiator,ee as ContentResult,V as DEFAULT_MAX_BODY_SIZE,ct as EndpointBuilder,re as ErrorMap,Z as FileResult,Te as ForbiddenError,S as HttpError,kt as IRequestContext,J as ImplementationModule,se as ImplementationScope,k as JsonResult,U as NoContentResult,Ee as NotFoundError,Y as RawResult,ne as RedirectResult,$ as RequestContext,me as Server,ye as ServerBuilder,G as StatusCodeResult,te as StreamResult,at as SubscriptionBuilder,Oe as UnauthorizedError,Ct as cacheResponse,we as computeCacheKey,ot as createCacheTagTree,lt as createEndpoints,E as createProblemDetails,Kt as createServer,xe as createValidationProblemDetails,ft as defineApi,Qt as defineWebhook,ut as endpoint,Rt as errorMap,dt as file,Fe as formUrlEncodedContentTypeHandler,de as idempotency,vt as implement,_e as jsonContentTypeHandler,Re as mapHandlers,ht as mergeContracts,mt as omitGroups,yt as pickGroups,pt as route,st as serializeTag,it as tracked,Se as withErrors};
3
+ `),i.destroy();return}this.#p.handleUpgrade(r,i,a,l=>{this.#w(l,r,d.registration,d.parsedPath)})}))}async close(){for(let e of this.#f)e.close(1001,"Server shutting down");this.#f.clear(),this.#p&&(await new Promise((e,t)=>{this.#p.close(n=>{n?t(n):e()})}),this.#p=null),this.#a&&(await new Promise((e,t)=>{this.#a.close(n=>{n?t(n):e()})}),this.#a=null)}get address(){let e=this.#a?.address();return!e||typeof e=="string"?null:{port:e.port,host:e.address}}async#h(e,t,n=!0){if(n&&this.#u&&await this.#u.handle(e,t,(r,i)=>this.#y(r,i)))return;let s=this.#r.createScope();try{let r=new L(e,t,this.#l),i=r.url.pathname,a=r.method,c=e.__cleverbrushBatchSubrequest;if(c&&r.items.set("__batch_subrequest",c),this.#d&&a==="GET"&&i==="/health"){t.writeHead(200),t.end();return}if(this.#i!==null&&a==="POST"&&i===(this.#i.path??"/__batch")){r.services=s.serviceProvider;let f=new $;for(let m of this.#s)f.add(m);await f.execute(r,async()=>{r.responded||(await this.#m(e,t),r.responded=!0)});return}let d=this.#e.match(a,i);if(!d.match){if(d.badRequest){let m=E(400);t.writeHead(400,{"content-type":P}),t.end(T(m));return}if(d.methodNotAllowed){let m=E(405,"Method Not Allowed");t.writeHead(405,{"content-type":P,allow:d.allowedMethods.join(", ")}),t.end(T(m));return}let f=E(404);t.writeHead(404,{"content-type":P}),t.end(T(f));return}let{registration:l,parsedPath:p}=d.match,u=l.endpoint;if(p){let f={};He(p,"",f),r.pathParams=f}r.services=s.serviceProvider,r.items.set("__endpoint_meta",u);let h=new $;for(let f of this.#s)h.add(f);if(l.middlewares)for(let f of l.middlewares)h.add(f);await h.execute(r,async()=>{if(r.responded)return;let f,m,g;if($e(u)||u.fileUpload){let b=e.headers["content-type"]??"";if(u.fileUpload&&b.startsWith("multipart/form-data"))try{let x=await Le(e,u.fileUpload,this.#l);if(u.fileUpload.schema&&!u.bodySchema&&Object.keys(x.fields).length)throw new S(400,"Bad Request","This upload endpoint does not declare text fields",{errors:Object.keys(x.fields).map(R=>({pointer:`/body/${R.replace(/~/g,"~0").replace(/\//g,"~1")}`,detail:"Unexpected multipart text field"}))});f=x.fields,m=x.files,g=x.rejectedFiles}catch(x){if(x instanceof S)throw x;let R=E(400,"Malformed multipart request");t.writeHead(400,{"content-type":P}),t.end(T(R)),r.responded=!0;return}else if(u.fileUpload){let x=E(400,"File upload endpoint requires multipart/form-data content type");t.writeHead(400,{"content-type":P}),t.end(T(x)),r.responded=!0;return}else{let x=this.#o.selectRequestHandler(b);if(x){let C=(await r.body()).toString("utf-8");if(C.length>0)try{f=x.deserialize(C)}catch{let D=E(400,"Malformed request body");t.writeHead(400,{"content-type":P}),t.end(T(D)),r.responded=!0;return}}else if(b){let R=E(415);t.writeHead(415,{"content-type":P}),t.end(T(R)),r.responded=!0;return}}}let w=await Ke(u,p,r,f);if(!w.valid){t.writeHead(400,{"content-type":P}),t.end(T(w.problemDetails)),r.responded=!0;return}if(m&&w.args.length>0){let b=w.args[0];b.files=m,g&&g.length>0&&(b.rejectedFiles=g)}let O=w.args,y=async b=>{r.responded||(await this.#g(e,t,b),r.responded=!0)},v=async b=>{if(!l.errors)throw b;return l.errors.translate(b)},M=r.headers["x-idempotency-key"];if(u.idempotent&&M!==void 0&&(M.length===0||M.length>256))throw new S(400,"Idempotency key must contain 1 to 256 characters");try{if(l.prepare&&(O[0]=await l.prepare(...O)),l.idempotency&&M!==void 0){let b=await l.idempotency.scope(...O);if(typeof b!="string"&&!(Array.isArray(b)&&b.length>0&&b.every(x=>typeof x=="string"||typeof x=="number"&&Number.isFinite(x))))throw new TypeError("Idempotency scope must be a string or identity components");this.#n.set(r,JSON.stringify(b))}}catch(b){await y(await v(b));return}let B=async()=>{let b;try{b=await l.handler(...O)}catch(x){if(l.handlerErrorsMapped)throw x;b=await v(x)}await y(b)};if(l.idempotency){let b=this.#t.get(l);b||(b=de({...l.idempotency,scope:x=>this.#n.get(x)}),this.#t.set(l,b)),await b(r,B)}else await B()})}catch(r){if(t.headersSent)return;if(r instanceof S){let i=r.toProblemDetails();t.writeHead(i.status,{"content-type":P}),t.end(T(i))}else{console.error("[server] Unhandled error:",r);let i=E(500);t.writeHead(500,{"content-type":P}),t.end(T(i))}}finally{try{await s.asyncDispose()}catch{}}}#y(e,t){let n=[];if(this.#d&&t==="/health"&&n.push("GET"),this.#i&&t===(this.#i.path??"/__batch")&&n.push("POST"),n.includes(e))return{status:200};let s=this.#e.match(e,t);if(s.badRequest)return{status:400};if(s.match)return{status:200};let r=[...new Set([...n,...s.allowedMethods??[]])];return r.length?{status:405,allowedMethods:r}:{status:404}}async#m(e,t){let n=this.#i,s=n.maxSize??20,r=n.parallel??!0,i;try{let d=await Qt(e,this.#l),l=q(d.toString("utf-8"));if(N(l),i=l,!Array.isArray(i?.requests))throw new Error("requests must be an array")}catch(d){if(d instanceof S&&d.status===413){let p=E(413,"Payload Too Large");t.writeHead(413,{"content-type":P}),t.end(T(p));return}let l=E(400,"Invalid batch request body");t.writeHead(400,{"content-type":P}),t.end(T(l));return}if(i.requests.length>s){let d=E(400,`Batch size ${i.requests.length} exceeds maximum of ${s}`);t.writeHead(400,{"content-type":P}),t.end(T(d));return}let a=async(d,l)=>{let p=new pe({method:(d.method??"GET").toUpperCase(),url:d.url,headers:{host:e.headers.host??"localhost",...d.headers},body:d.body});p.__cleverbrushBatchSubrequest={index:l,size:i.requests.length,path:n.path??"/__batch"};let u=new fe;return await this.#h(p,u,!1),u.toResult()},c;if(r)c=await Promise.all(i.requests.map(a));else{c=[];for(let d=0;d<i.requests.length;d++)c.push(await a(i.requests[d],d))}t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({responses:c}))}async#g(e,t,n){n instanceof j?await n.executeAsync(e,t,this.#o):n==null?(t.writeHead(204),t.end()):await new k(n,200).executeAsync(e,t,this.#o)}#w(e,t,n,s){this.#f.add(e);let r=this.#r.createScope(),i=new AbortController,a=n.endpoint,c=new ge.ServerResponse(t),d=new L(t,c);if(s){let p={};He(s,"",p),d.pathParams=p}d.services=r.serviceProvider,d.items.set("__endpoint_meta",a);let l=new $;for(let p of this.#s)l.add(p);if(n.middlewares)for(let p of n.middlewares)l.add(p);l.execute(d,async()=>{if(d.responded){e.close(1008,"Unauthorized");return}this.#R(e,d,a,n.handler,s,r,i)}).then(()=>{d.responded&&e.close(1008,"Unauthorized")}).catch(()=>{e.close(1011,"Internal Server Error")}),e.on("close",()=>{this.#f.delete(e),i.abort(),r.asyncDispose().catch(()=>{})}),e.on("error",()=>{this.#f.delete(e),i.abort(),r.asyncDispose().catch(()=>{})})}#R(e,t,n,s,r,i,a){let c=[],d=null,l=!1,p={[Symbol.asyncIterator](){return{next(){return c.length>0?Promise.resolve({value:c.shift(),done:!1}):l?Promise.resolve({value:void 0,done:!0}):new Promise(f=>{d=()=>{d=null,c.length>0?f({value:c.shift(),done:!1}):f({value:void 0,done:!0})}})},return(){return l=!0,Promise.resolve({value:void 0,done:!0})}}}};e.on("message",f=>{let m=typeof f=="string"?f:f.toString("utf-8"),g=tt(m);if(!g){e.send(JSON.stringify(F(400,"Invalid frame format")));return}if(g.type==="ping"){e.send(JSON.stringify(et()));return}if(c.length>=Wt){e.send(JSON.stringify(F(429,"Message queue full \u2014 slow down or reconnect"))),e.close(1008,"Message queue overflow");return}if(n.incomingSchema){let w=n.incomingSchema.validate(g.data);if(!w.valid){let O=(w.errors??[]).map(y=>y.message).join("; ");e.send(JSON.stringify(F(422,`Validation failed: ${O}`)));return}c.push(w.object)}else c.push(g.data);d&&d()}),e.on("close",()=>{l=!0,d&&d()});let u={context:t,signal:a.signal};if(r&&Object.keys(r).length>0&&(u.params=r),n.querySchema){let f={};for(let[g,w]of t.url.searchParams.entries())f[g]=w;let m=n.querySchema.validate(f);if(!m.valid){let g=(m.errors??[]).map(w=>w.message).join("; ");e.close(1002,`Query validation failed: ${g}`);return}u.query=m.object}if(n.headerSchema){let f=n.headerSchema.validate(t.headers);if(!f.valid){let m=(f.errors??[]).map(g=>g.message).join("; ");e.close(1002,`Header validation failed: ${m}`);return}u.headers=f.object}t.principal!==void 0&&(u.principal=t.principal),n.incomingSchema,u.incoming=p;let h=[u];if(n.serviceSchemas){let f={};for(let[m,g]of Object.entries(n.serviceSchemas))f[m]=i.serviceProvider.get(g);h.push(f)}(async()=>{try{let f=s(...h);for await(let m of f){if(e.readyState!==e.OPEN)break;let g;if(qe(m)){let w=n.outgoingSchema?n.outgoingSchema.validate(m.data):{valid:!0,object:m.data};if(!w.valid){e.send(JSON.stringify(F(500,"Outgoing validation failed")));continue}g=JSON.stringify(Ze(m.id,w.object))}else{let w=n.outgoingSchema?n.outgoingSchema.validate(m):{valid:!0,object:m};if(!w.valid){e.send(JSON.stringify(F(500,"Outgoing validation failed")));continue}g=JSON.stringify(Ye(w.object))}e.send(g)}}catch(f){e.readyState===e.OPEN&&(f instanceof Error&&console.error("[server] Subscription handler error:",f),e.send(JSON.stringify(F(500,"Internal error"))),e.close(1011,"Handler error"))}})()}};function Vt(o){return new ye(o)}function Qt(o,e=V){return new Promise((t,n)=>{let s=[],r=0;o.on("data",i=>{if(r+=i.length,r>e){o.destroy(),n(new S(413,"Payload Too Large"));return}s.push(i)}),o.on("end",()=>t(Buffer.concat(s))),o.on("error",n)})}function He(o,e,t){for(let[n,s]of Object.entries(o)){let r=e?`${e}.${n}`:n;s!==null&&typeof s=="object"&&!Array.isArray(s)?He(s,r,t):t[r]=String(s)}}function Xt(o){let e=new Map;for(let n of o.schemes)e.set(n.name,n);let t;return o.trySchemes==="all"?t=o.schemes:t=(o.trySchemes&&o.trySchemes.length>0?o.trySchemes:[o.defaultScheme]).map(s=>e.get(s)).filter(s=>s!==void 0),async(n,s)=>{if(n.items.get("__endpoint_meta")?.authRoles===null){n.principal=he.anonymous(),await s();return}let i={headers:n.headers,cookies:Jt(n.headers.cookie??""),items:n.items};n.principal=he.anonymous();for(let a of t){let c=await a.authenticate(i);if(c.succeeded){n.principal=c.principal;break}}await s()}}function Yt(o,e){let t={};if(e){for(let n of e.schemes)if(n.challenge){let s=n.challenge();t[s.headerName.toLowerCase()]=s.headerValue}}return async(n,s)=>{let r=n.items.get("__endpoint_meta");if(!r||r.authRoles===null){await s();return}let i=n.principal;if(!i||!(i instanceof he)||!i.isAuthenticated){let a=E(401,"Unauthorized"),c={"content-type":P,...t};n.response.writeHead(401,c),n.response.end(T(a)),n.responded=!0;return}if(r.authRoles.length>0&&!(await o.authorize(i,[Lt(...r.authRoles)])).allowed){let c=E(403,"Forbidden");n.response.writeHead(403,{"content-type":P}),n.response.end(T(c)),n.responded=!0;return}i instanceof he&&(n.principal=i.value),await s()}}function Zt(o,e){return{name:o,...e}}async function en(o,e,t){if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<=0||t.timeoutMs>2147483647)throw new RangeError("timeoutMs must be a positive timer-safe integer.");let n=new AbortController,s=()=>n.abort(new DOMException("Request disconnected.","AbortError")),r=()=>{o.response.writableFinished||s()},i=()=>n.abort(t.signal.reason),a=setTimeout(()=>n.abort(new DOMException("Request deadline exceeded.","TimeoutError")),t.timeoutMs);o.request.once("aborted",s),o.response.once("close",r),t.signal?.addEventListener("abort",i,{once:!0});try{return(o.request.aborted||o.response.destroyed)&&r(),o.request.aborted&&s(),t.signal?.aborted&&i(),n.signal.throwIfAborted(),await e(n.signal)}finally{clearTimeout(a),o.request.off("aborted",s),o.response.off("close",r),t.signal?.removeEventListener("abort",i)}}export{j as ActionResult,ie as ApiImplementation,Ce as BadRequestError,Pe as ConflictError,W as ContentNegotiator,ee as ContentResult,V as DEFAULT_MAX_BODY_SIZE,lt as EndpointBuilder,re as ErrorMap,Z as FileResult,Te as ForbiddenError,S as HttpError,jt as IRequestContext,J as ImplementationModule,se as ImplementationScope,k as JsonResult,U as NoContentResult,Ee as NotFoundError,Y as RawResult,ne as RedirectResult,L as RequestContext,me as Server,ye as ServerBuilder,G as StatusCodeResult,te as StreamResult,dt as SubscriptionBuilder,Oe as UnauthorizedError,Pt as cacheResponse,we as computeCacheKey,st as createCacheTagTree,ut as createEndpoints,E as createProblemDetails,Vt as createServer,xe as createValidationProblemDetails,mt as defineApi,Zt as defineWebhook,pt as endpoint,ht as endpointPath,vt as errorMap,ct as file,De as formUrlEncodedContentTypeHandler,de as idempotency,Ct as implement,Fe as jsonContentTypeHandler,Re as mapHandlers,yt as matchEndpointPath,gt as mergeContracts,Rt as omitGroups,wt as pickGroups,ft as route,it as serializeTag,at as tracked,Se as withErrors,en as withRequestSignal};
4
4
  //# sourceMappingURL=index.js.map