@cleverbrush/server 4.4.3 → 4.5.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.
- package/README.md +13 -1
- package/dist/CacheTag.d.ts +1 -17
- package/dist/Endpoint.d.ts +1 -1
- package/dist/cacheKey.d.ts +17 -0
- package/dist/chunk-L2OPVEOF.js +2 -0
- package/dist/chunk-L2OPVEOF.js.map +1 -0
- package/dist/contract.d.ts +1 -0
- package/dist/contract.js +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/middlewares/ResponseCache.d.ts +2 -2
- package/package.json +4 -4
- package/dist/chunk-PLSVKHPB.js +0 -2
- package/dist/chunk-PLSVKHPB.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as xe,b as Ae,c as Me,d as Be,e as de,f as Ee,g as ke,h as _e,i as je,j as He,k as qe,l as Ne,m as Oe,n as Fe,o as De}from"./chunk-PLSVKHPB.js";var C=class{static ok(e,t){return new P(e,200,t)}static created(e,t,r){let n={...r};return t&&(n.location=t),new P(e,201,n)}static accepted(e,t){return new P(e,202,t)}static noContent(){return new z}static badRequest(e,t){return new P(e,400,t)}static unauthorized(e,t){return new P(e,401,t)}static forbidden(e,t){return new P(e,403,t)}static notFound(e,t){return new P(e,404,t)}static conflict(e,t){return new P(e,409,t)}static redirect(e,t=!1){return new I(e,t)}static json(e,t=200,r){return new P(e,t,r)}static file(e,t,r="application/octet-stream"){return new N(e,t,r)}static content(e,t,r=200){return new O(e,t,r)}static stream(e,t,r){return new F(e,t,r)}static raw(e){return new q(e)}static status(e,t){return new D(e,t)}},q=class extends C{handler;constructor(e){super(),this.handler=e}async executeAsync(e,t,r){await this.handler(e,t)}},P=class extends C{body;status;headers;constructor(e,t=200,r){super(),this.body=e,this.status=t,this.headers=r??{}}async executeAsync(e,t,r){for(let[n,o]of Object.entries(this.headers))t.setHeader(n,o);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))}},N=class extends C{content;fileName;contentType;constructor(e,t,r="application/octet-stream"){super(),this.content=e,this.fileName=t,this.contentType=r}async executeAsync(e,t,r){let n=this.fileName,o=n.replace(/[^\x20-\x7E]/g,"_"),i=o===n?`attachment; filename="${n}"`:`attachment; filename="${o}"; filename*=UTF-8''${encodeURIComponent(n)}`;t.writeHead(200,{"content-type":this.contentType,"content-disposition":i,"content-length":String(this.content.byteLength)}),t.end(this.content)}},O=class extends C{body;contentType;status;constructor(e,t,r=200){super(),this.body=e,this.contentType=t,this.status=r}async executeAsync(e,t,r){t.writeHead(this.status,{"content-type":this.contentType}),t.end(this.body)}},F=class extends C{readable;contentType;fileName;constructor(e,t,r){super(),this.readable=e,this.contentType=t,this.fileName=r}async executeAsync(e,t,r){let n={"content-type":this.contentType};this.fileName&&(n["content-disposition"]=`attachment; filename="${this.fileName}"`),t.writeHead(200,n),await new Promise((o,i)=>{this.readable.on("error",i),t.on("error",i),this.readable.on("end",o),this.readable.pipe(t,{end:!0})})}},D=class extends C{status;headers;constructor(e,t){super(),this.status=e,this.headers=t??{}}async executeAsync(e,t,r){t.writeHead(this.status,this.headers),t.end()}},I=class extends C{url;permanent;constructor(e,t=!1){super(),this.url=e,this.permanent=t}async executeAsync(e,t,r){t.writeHead(this.permanent?301:302,{location:this.url}),t.end()}},z=class extends C{async executeAsync(e,t,r){t.writeHead(204),t.end()}};function x(s){return JSON.parse(s,(e,t)=>{if(!(e==="__proto__"||e==="constructor"))return t})}function A(s,e=64){K(s,0,e)}function K(s,e,t){if(!(s===null||typeof s!="object")){if(e>=t)throw new Error(`JSON nesting depth exceeds maximum of ${t}`);if(Array.isArray(s))for(let r of s)K(r,e+1,t);else for(let r of Object.values(s))K(r,e+1,t)}}var ce={mimeType:"application/json",serialize(s){return JSON.stringify(s)},deserialize(s){let e=x(s);return A(e),e}},le={mimeType:"application/x-www-form-urlencoded",serialize(s){let e=new URLSearchParams;if(s&&typeof s=="object"){for(let[t,r]of Object.entries(s))if(r!=null)if(Array.isArray(r))for(let n of r)e.append(t,String(n));else e.append(t,String(r))}return e.toString()},deserialize(s){let e={},t=new URLSearchParams(s);for(let[r,n]of t){if(Ie(r))continue;let o=e[r];o===void 0?e[r]=n:Array.isArray(o)?o.push(n):e[r]=[o,n]}return e}};function Ie(s){return s==="__proto__"||s==="constructor"||s==="prototype"}function ze(s){return s.split(",").map(e=>{let t=e.trim(),[r,...n]=t.split(";").map(i=>i.trim()),o=1;for(let i of n){let[d,c]=i.split("=");d?.trim()==="q"&&c&&(o=parseFloat(c),Number.isNaN(o)&&(o=1))}return{mimeType:r.toLowerCase(),quality:o}}).sort((e,t)=>t.quality-e.quality)}var j=class{#e=new Map;constructor(){this.register(ce),this.register(le)}register(e){this.#e.set(e.mimeType.toLowerCase(),e)}selectResponseHandler(e){if(!e)return this.#e.get("application/json")??null;let t=ze(e);for(let{mimeType:r}of t){if(r==="*/*")return this.#e.get("application/json")??null;let n=this.#e.get(r);if(n)return n}return null}selectRequestHandler(e){if(!e)return null;let t=e.split(";")[0].trim().toLowerCase();return this.#e.get(t)??null}};var Je={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",409:"Conflict",415:"Unsupported Media Type",422:"Unprocessable Content",500:"Internal Server Error",503:"Service Unavailable"};function S(s,e,t,r){return{type:`https://httpstatuses.com/${s}`,status:s,title:e??Je[s]??"Error",...t!==void 0?{detail:t}:{},...r}}function X(s){return S(400,"Bad Request","One or more validation errors occurred.",{errors:s})}function v(s){return JSON.stringify(s)}var w="application/problem+json";var T=class extends Error{status;title;detail;extensions;constructor(e,t,r,n){super(r??t??`HTTP ${e}`),this.name="HttpError",this.status=e,this.title=t??`HTTP ${e}`,this.detail=r,this.extensions=n}toProblemDetails(){return S(this.status,this.title,this.detail,this.extensions)}},Y=class extends T{constructor(e){super(404,"Not Found",e),this.name="NotFoundError"}},Z=class extends T{constructor(e){super(400,"Bad Request",e),this.name="BadRequestError"}},Q=class extends T{constructor(e){super(401,"Unauthorized",e),this.name="UnauthorizedError"}},ee=class extends T{constructor(e){super(403,"Forbidden",e),this.name="ForbiddenError"}},te=class extends T{constructor(e){super(409,"Conflict",e),this.name="ConflictError"}};function Ue(s){return["POST","PUT","DELETE","PATCH"].includes(s.toUpperCase())}var Le=6e4;function We(s={}){let{ttl:e=864e5,headerName:t="x-idempotency-key",skip:r=i=>!Ue(i.method)}=s,n=new Map,o=setInterval(()=>{let i=Date.now();for(let[d,c]of n)c.expiresAt<=i&&n.delete(d)},Le);return o.unref&&o.unref(),async(i,d)=>{if(r(i))return d();let c=i.headers[t]??i.headers[t.toLowerCase()];if(!c||typeof c!="string"||c.length===0)return d();let a=n.get(c);if(a)if(a.expiresAt<=Date.now())n.delete(c);else{let u=i.response;u.writeHead(a.status,a.headers),u.end(a.body),i.responded=!0;return}let f=i.response.writeHead.bind(i.response),m=i.response.end.bind(i.response),p=200,g={},h=[];if(i.response.writeHead=function(u,...l){return p=u,l.length>0&&(g=l[0]),f(u,...l)},i.response.end=function(u,...l){return u&&h.push(Buffer.isBuffer(u)?u:Buffer.from(u)),m(u,...l)},await d(),p>=200&&p<500){let u=Buffer.concat(h);n.set(c,{status:p,headers:g,body:u,expiresAt:Date.now()+e})}}}function $e(s){return["POST","PUT","DELETE","PATCH"].includes(s.toUpperCase())}function ue(s,e){return s.map(t=>{let r=[];for(let[n,o]of Object.entries(t.properties).sort(([i],[d])=>i.localeCompare(d))){let i=o.getValue(e);i.success&&i.value!==void 0&&r.push(`${n}=${String(i.value)}`)}return r.length>0?`${t.name}:${r.join(",")}`:t.name})}function Ve(s={}){let{ttlByTag:e={},defaultTtl:t=6e4}=s,r=new Map;return async(n,o)=>{let d=n.items.get("__endpoint_meta")?.cacheTags??[];if(d.length===0)return o();if($e(n.method)){if(await o(),n.response.statusCode>=200&&n.response.statusCode<300){let c=n.items.get("__raw_body"),a={params:n.pathParams??{},body:c,query:n.queryParams??{},headers:n.headers??{}},f=ue(d,a);for(let m of d){for(let[p]of r)(f.includes(p)||f.some(g=>p.startsWith(m.name)))&&r.delete(p);for(let[p]of r)p.startsWith(m.name)&&r.delete(p)}}return}if(n.method==="GET"){let c={params:n.pathParams??{},body:void 0,query:n.queryParams??{},headers:n.headers??{}},a=ue(d,c);for(let u of a){let l=r.get(u);if(l&&l.expiresAt>Date.now()){let y=n.response;y.writeHead(l.status,l.headers),y.end(l.body),n.responded=!0;return}l&&r.delete(u)}let f=n.response.writeHead.bind(n.response),m=n.response.end.bind(n.response),p=200,g={},h=[];if(n.response.writeHead=function(u,...l){return p=u,l.length>0&&(g=l[0]),f(u,...l)},n.response.end=function(u,...l){return u&&h.push(Buffer.isBuffer(u)?u:Buffer.from(u)),m(u,...l)},await o(),p>=200&&p<300){let u=Buffer.concat(h),l=d.reduce((y,b)=>{let R=e[b.name]!==void 0?e[b.name]:t;return R>y?R:y},0);if(l>0)for(let y of a)r.set(y,{status:p,headers:g,body:u,expiresAt:Date.now()+l})}return}return o()}}import{URL as Ge}from"url";import{any as re,boolean as Ke,func as pe,object as Xe,promise as he,record as ne,string as M}from"@cleverbrush/schema";var Ye=Xe({method:M(),url:M(),pathParams:ne(M(),M()),queryParams:ne(M(),M()),headers:ne(M(),M()),items:re(),body:pe().hasReturnType(he(re())),json:pe().hasReturnType(he(re())),responded:Ke()}),H=5*1024*1024,E=class{request;response;url;method;headers;items=new Map;maxBodySize;#e={};_queryParams;#t;#r=null;#n=!1;#s=void 0;#i=!1;responded=!1;principal=void 0;constructor(e,t,r){this.request=e,this.response=t,this.method=(e.method??"GET").toUpperCase(),this.maxBodySize=r??H;let n=e.url??"/";this.url=new Ge(n,`http://${e.headers.host??"localhost"}`);let o={};for(let[i,d]of Object.entries(e.headers))typeof d=="string"?o[i]=d:Array.isArray(d)&&(o[i]=d.join(", "));this.headers=o}get pathParams(){return this.#e}set pathParams(e){this.#e=e}get queryParams(){if(this._queryParams)return this._queryParams;let e={};for(let[t,r]of this.url.searchParams)e[t]=r;return e}get services(){return this.#t}set services(e){this.#t=e}async body(){return this.#n?this.#r:(this.#r=await new Promise((e,t)=>{let r=[],n=0;this.request.on("data",o=>{if(n+=o.length,n>this.maxBodySize){this.request.destroy(),t(new T(413,"Payload Too Large"));return}r.push(o)}),this.request.on("end",()=>e(Buffer.concat(r))),this.request.on("error",t)}),this.#n=!0,this.#r)}async json(){if(this.#i)return this.#s;let t=(await this.body()).toString("utf-8");return t.length>0&&(this.#s=x(t),A(this.#s)),this.#i=!0,this.#s}};import*as G from"http";import*as Te from"https";import{AuthorizationService as nt,PolicyBuilder as st,Principal as W,parseCookies as ot,requireRole as it}from"@cleverbrush/auth";import{ServiceCollection as at}from"@cleverbrush/di";import{Busboy as dt}from"@fastify/busboy";import{WebSocketServer as ct}from"ws";var k=class{#e=[];add(e){this.#e.push(e)}async execute(e,t){let r=0,n=async()=>{if(r<this.#e.length){let o=this.#e[r++];await o(e,n)}else await t()};await n()}};function fe(s){return s.bodySchema!=null}async function me(s,e,t,r){let n=[],o={};if(o.context=t,s.authRoles!==null&&t.principal!==void 0&&(o.principal=t.principal),e&&Object.keys(e).length>0&&(o.params=e),s.bodySchema){let i=await s.bodySchema.validateAsync(r,{doNotStopOnFirstError:!0});if(i.valid)o.body=i.object;else{let d=typeof i.getInvalidProperties=="function"?i.getInvalidProperties:null,c=!1;if(d)for(let a of d()){let f=a.descriptor.toJsonPointer();for(let m of a.errors)n.push({pointer:`/body${f}`,detail:m}),c=!0}if(!c)for(let a of i.errors??[])n.push({pointer:"/body",detail:a.message})}}if(s.querySchema){let i=s.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,c={};for(let[a,f]of Object.entries(d)){let m=t.queryParams[a],p=await f.validateAsync(m,{doNotStopOnFirstError:!0});if(p.valid)c[a]=p.object;else for(let g of p.errors??[])n.push({pointer:`/query/${a}`,detail:g.message})}o.query=c}if(s.headerSchema){let i=s.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,c={};for(let[a,f]of Object.entries(d)){let m=t.headers[a.toLowerCase()],p=await f.validateAsync(m,{doNotStopOnFirstError:!0});if(p.valid)c[a]=p.object;else for(let g of p.errors??[])n.push({pointer:`/headers/${a}`,detail:g.message})}o.headers=c}if(n.length>0)return{valid:!1,problemDetails:X(n)};if(s.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,c]of Object.entries(s.serviceSchemas))i[d]=t.services.get(c);return{valid:!0,args:[o,i]}}return{valid:!0,args:[o]}}function _(s){let e=decodeURI(s);return e.length>1&&e.endsWith("/")?e.slice(0,-1):e}function se(s){return typeof s!="string"&&typeof s.validate=="function"}function ge(s){let e=0,t=!1;for(let r of s)for(let n of r)n==="/"?(t&&e++,t=!1):t=!0;return e+(t?1:0)}function Ze(s,e){if(!se(e)){let o=_(e),i=o==="/"?s||"/":s+o;return{isStatic:!0,literalSegments:ge([i]),dynamicSegments:0}}let{literals:t,segments:r}=e.introspect().templateDefinition,n=[s+(t[0]??""),...t.slice(1)];return{isStatic:r.length===0,literalSegments:ge(n),dynamicSegments:r.length}}function Qe(s,e){return s.isStatic!==e.isStatic?s.isStatic?1:-1:s.literalSegments!==e.literalSegments?s.literalSegments-e.literalSegments:e.dynamicSegments-s.dynamicSegments}function et(s,e){if(!se(e)){let n=_(e);return n==="/"?s||"/":s+n}let{literals:t,segments:r}=e.introspect().templateDefinition;return r.length>0?null:s+(t[0]??"")}function ye(s,e,t){let r=_(s);return{basePath:r,routePath:e,specificity:Ze(r,e),exactPath:et(r,e),registration:t}}function Re(){return{exactRoutes:new Map,dynamicRoutes:[]}}function Se(s,e){if(e.exactPath!==null){s.exactRoutes.has(e.exactPath)||s.exactRoutes.set(e.exactPath,e);return}s.dynamicRoutes.push(e)}var J=class{#e=new Map;#t=Re();#r=!0;addRoute(e){let{method:t,basePath:r,pathTemplate:n}=e.endpoint,o=t.toUpperCase(),i=ye(r,n,e),d=this.#e.get(o);d||(d=Re(),this.#e.set(o,d)),Se(d,i),this.#r=!1}finalize(){if(!this.#r){for(let e of this.#e.values())this.#s(e.dynamicRoutes);this.#s(this.#t.dynamicRoutes),this.#r=!0}}match(e,t){let r;try{r=_(t)}catch{return{match:null,methodNotAllowed:!1,badRequest:!0}}let n=e.toUpperCase();this.finalize();let o=this.#e.get(n);if(o){let d=this.#n(o,r);if(d)return{match:d,methodNotAllowed:!1}}let i=[];for(let[d,c]of this.#e)d!==n&&this.#n(c,r)&&i.push(d);return i.length>0?{match:null,methodNotAllowed:!0,allowedMethods:i}:{match:null,methodNotAllowed:!1}}#n(e,t){let r=e.exactRoutes.get(t);if(r){let n=this.#i(r,t);if(n)return n}for(let n of e.dynamicRoutes){let o=this.#i(n,t);if(o)return o}return null}#s(e){e.sort((t,r)=>Qe(r.specificity,t.specificity))}#i(e,t){let{basePath:r,routePath:n}=e;if(r&&!t.startsWith(r))return null;let o=r?t.slice(r.length):t;if(se(n)){let c=n.validate(o);return c.valid?{registration:e.registration,parsedPath:c.object}:null}let i=_(n);return(o.length===0?"/":o)===i?{registration:e.registration,parsedPath:null}:null}addSubscriptionRoute(e){let{basePath:t,pathTemplate:r}=e.endpoint;Se(this.#t,ye(t,r,e)),this.#r=!1}matchSubscription(e){let t;try{t=_(e)}catch{return null}return this.finalize(),this.#n(this.#t,t)}};import{Readable as tt,Writable as rt}from"stream";var U=class extends tt{method;url;headers;__cleverbrushBatchSubrequest;socket=null;#e;#t=!1;constructor(e){super(),this.method=e.method,this.url=e.url;let t={};for(let[r,n]of Object.entries(e.headers??{}))t[r.toLowerCase()]=n;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))}},L=class extends rt{statusCode=200;headersSent=!1;#e=[];#t={};#r=200;_write(e,t,r){this.#e.push(Buffer.isBuffer(e)?e:Buffer.from(e)),r()}writeHead(e,t){if(this.#r=e,this.statusCode=e,t!=null&&typeof t=="object"&&!Array.isArray(t))for(let[r,n]of Object.entries(t))this.#t[r.toLowerCase()]=Array.isArray(n)?n.join(", "):String(n);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()]}end(e,...t){if(e!=null&&typeof e!="function"){let r=Buffer.isBuffer(e)||e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),"utf-8");this.#e.push(r),super.end(...t)}else typeof e=="function"?super.end(e):super.end(...t);return this}toResult(){return{status:this.#r,headers:{...this.#t},body:Buffer.concat(this.#e).toString("utf-8")}}};function be(s){return{type:"message",data:s}}function ve(s,e){return{type:"tracked",id:s,data:e}}function we(){return{type:"pong"}}function B(s,e){return{type:"error",code:s,message:e}}function Pe(s){let e;try{e=x(s),A(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}async function lt(s,e){let t=e.maxFileCount??10,r=e.maxFileSize??10*1024*1024,n=e.allowedMimeTypes;return new Promise((o,i)=>{let d={},c={},a=[],f=0,m=dt({headers:s.headers,limits:{fileSize:r,files:t}});m.on("field",(p,g)=>{d[p]=g}),m.on("file",(p,g,h,u,l)=>{if(f>=t){a.push({filename:h,mimeType:l,reason:`Exceeded max file count (${t})`}),g.resume();return}if(n&&!n.some(R=>R.endsWith("/*")?l.startsWith(R.slice(0,-1)):l===R)){a.push({filename:h,mimeType:l,reason:`MIME type "${l}" not allowed (allowed: ${n.join(", ")})`}),g.resume();return}f++;let y=[];g.on("data",b=>{y.push(b)}),g.on("end",()=>{let b=Buffer.concat(y);c[p]={filename:h,mimeType:l,buffer:b,size:b.length}}),g.on("error",i)}),m.on("error",i),m.on("finish",()=>o({fields:d,files:c,rejectedFiles:a})),s.pipe(m)})}var $=class{#e=new at;#t=[];#r=[];#n=[];#s=[];#i=new j;#a;#d=null;#o=null;#c=!1;#l=null;constructor(e={}){this.#a=e}services(e){return e(this.#e),this}use(e){return this.#s.push(e),this}contentType(e){return this.#i.register(e),this}useAuthentication(e){return this.#d=e,this}useAuthorization(e){return this.#o=e??{},this}withHealthcheck(){return this.#c=!0,this}useBatching(e={}){return this.#l=e,this}handle(e,t,r){return this.#t.push({endpoint:e.introspect(),handler:t,middlewares:r?.middlewares}),this}handleAll(e){for(let t of e._entries)this.#t.push({endpoint:t.endpoint.introspect(),handler:t.handler,middlewares:t.middlewares});for(let t of e._subscriptions)this.#r.push({endpoint:t.endpoint.introspect(),handler:t.handler,middlewares:t.middlewares});return this}getRegistrations(){return[...this.#t]}getSubscriptionRegistrations(){return[...this.#r]}webhook(e){return this.#n.push(e),this}getWebhooks(){return[...this.#n]}getAuthenticationConfig(){return this.#d}async listen(e,t){let r=new J;for(let f of this.#t)r.addRoute(f);for(let f of this.#r)r.addSubscriptionRoute(f);r.finalize();let n=this.#e.buildServiceProvider({validateScopes:!1}),o=[];if(this.#d&&o.push(ft(this.#d)),this.#o!==null){let f=new Map;if(this.#o.policies)for(let[p,g]of Object.entries(this.#o.policies)){let h=new st;g(h),f.set(p,h.build(p))}let m=new nt(f);o.push(mt(m,this.#d))}let i=[...o,...this.#s],d=new V(r,n,this.#i,i,this.#c,this.#r.length>0,this.#l,this.#a.maxBodySize),c=e??this.#a.port??3e3,a=t??this.#a.host??"0.0.0.0";return await d.start(c,a,this.#a),d}},ut=1024,V=class{#e;#t;#r;#n;#s;#i;#a;#d;#o=null;#c=null;#l=new Set;constructor(e,t,r,n,o=!1,i=!1,d=null,c=H){this.#e=e,this.#t=t,this.#r=r,this.#n=n,this.#s=o,this.#i=i,this.#a=d,this.#d=c}async start(e,t,r){let n=(o,i)=>{this.#u(o,i).catch(d=>{i.headersSent||(i.writeHead(500,{"content-type":w}),i.end(v(S(500))))})};r.https?this.#o=Te.createServer({key:r.https.key,cert:r.https.cert},n):this.#o=G.createServer(n),await new Promise(o=>{this.#o.listen(e,t,o)}),this.#i&&(this.#c=new ct({noServer:!0,maxPayload:this.#d}),this.#o.on("upgrade",(o,i,d)=>{let c=new URL(o.url??"/",`http://${o.headers.host??"localhost"}`).pathname,a=this.#e.matchSubscription(c);if(!a){i.write(`HTTP/1.1 404 Not Found\r
|
|
1
|
+
import{a as Z,b as xe,c as Ae,d as Me,e as le,f as Be,g as Ee,h as ke,i as He,j as je,k as _e,l as qe,m as Ne,n as Oe,o as Fe}from"./chunk-L2OPVEOF.js";var C=class{static ok(e,t){return new P(e,200,t)}static created(e,t,r){let n={...r};return t&&(n.location=t),new P(e,201,n)}static accepted(e,t){return new P(e,202,t)}static noContent(){return new L}static badRequest(e,t){return new P(e,400,t)}static unauthorized(e,t){return new P(e,401,t)}static forbidden(e,t){return new P(e,403,t)}static notFound(e,t){return new P(e,404,t)}static conflict(e,t){return new P(e,409,t)}static redirect(e,t=!1){return new U(e,t)}static json(e,t=200,r){return new P(e,t,r)}static file(e,t,r="application/octet-stream"){return new D(e,t,r)}static content(e,t,r=200){return new I(e,t,r)}static stream(e,t,r){return new z(e,t,r)}static raw(e){return new F(e)}static status(e,t){return new J(e,t)}},F=class extends C{handler;constructor(e){super(),this.handler=e}async executeAsync(e,t,r){await this.handler(e,t)}},P=class extends C{body;status;headers;constructor(e,t=200,r){super(),this.body=e,this.status=t,this.headers=r??{}}async executeAsync(e,t,r){for(let[n,i]of Object.entries(this.headers))t.setHeader(n,i);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))}},D=class extends C{content;fileName;contentType;constructor(e,t,r="application/octet-stream"){super(),this.content=e,this.fileName=t,this.contentType=r}async executeAsync(e,t,r){let n=this.fileName,i=n.replace(/[^\x20-\x7E]/g,"_"),o=i===n?`attachment; filename="${n}"`:`attachment; filename="${i}"; filename*=UTF-8''${encodeURIComponent(n)}`;t.writeHead(200,{"content-type":this.contentType,"content-disposition":o,"content-length":String(this.content.byteLength)}),t.end(this.content)}},I=class extends C{body;contentType;status;constructor(e,t,r=200){super(),this.body=e,this.contentType=t,this.status=r}async executeAsync(e,t,r){t.writeHead(this.status,{"content-type":this.contentType}),t.end(this.body)}},z=class extends C{readable;contentType;fileName;constructor(e,t,r){super(),this.readable=e,this.contentType=t,this.fileName=r}async executeAsync(e,t,r){let n={"content-type":this.contentType};this.fileName&&(n["content-disposition"]=`attachment; filename="${this.fileName}"`),t.writeHead(200,n),await new Promise((i,o)=>{this.readable.on("error",o),t.on("error",o),this.readable.on("end",i),this.readable.pipe(t,{end:!0})})}},J=class extends C{status;headers;constructor(e,t){super(),this.status=e,this.headers=t??{}}async executeAsync(e,t,r){t.writeHead(this.status,this.headers),t.end()}},U=class extends C{url;permanent;constructor(e,t=!1){super(),this.url=e,this.permanent=t}async executeAsync(e,t,r){t.writeHead(this.permanent?301:302,{location:this.url}),t.end()}},L=class extends C{async executeAsync(e,t,r){t.writeHead(204),t.end()}};function A(s){return JSON.parse(s,(e,t)=>{if(!(e==="__proto__"||e==="constructor"))return t})}function M(s,e=64){Q(s,0,e)}function Q(s,e,t){if(!(s===null||typeof s!="object")){if(e>=t)throw new Error(`JSON nesting depth exceeds maximum of ${t}`);if(Array.isArray(s))for(let r of s)Q(r,e+1,t);else for(let r of Object.values(s))Q(r,e+1,t)}}var ue={mimeType:"application/json",serialize(s){return JSON.stringify(s)},deserialize(s){let e=A(s);return M(e),e}},pe={mimeType:"application/x-www-form-urlencoded",serialize(s){let e=new URLSearchParams;if(s&&typeof s=="object"){for(let[t,r]of Object.entries(s))if(r!=null)if(Array.isArray(r))for(let n of r)e.append(t,String(n));else e.append(t,String(r))}return e.toString()},deserialize(s){let e={},t=new URLSearchParams(s);for(let[r,n]of t){if(De(r))continue;let i=e[r];i===void 0?e[r]=n:Array.isArray(i)?i.push(n):e[r]=[i,n]}return e}};function De(s){return s==="__proto__"||s==="constructor"||s==="prototype"}function Ie(s){return s.split(",").map(e=>{let t=e.trim(),[r,...n]=t.split(";").map(o=>o.trim()),i=1;for(let o of n){let[d,c]=o.split("=");d?.trim()==="q"&&c&&(i=parseFloat(c),Number.isNaN(i)&&(i=1))}return{mimeType:r.toLowerCase(),quality:i}}).sort((e,t)=>t.quality-e.quality)}var q=class{#e=new Map;constructor(){this.register(ue),this.register(pe)}register(e){this.#e.set(e.mimeType.toLowerCase(),e)}selectResponseHandler(e){if(!e)return this.#e.get("application/json")??null;let t=Ie(e);for(let{mimeType:r}of t){if(r==="*/*")return this.#e.get("application/json")??null;let n=this.#e.get(r);if(n)return n}return null}selectRequestHandler(e){if(!e)return null;let t=e.split(";")[0].trim().toLowerCase();return this.#e.get(t)??null}};var ze={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",409:"Conflict",415:"Unsupported Media Type",422:"Unprocessable Content",500:"Internal Server Error",503:"Service Unavailable"};function b(s,e,t,r){return{type:`https://httpstatuses.com/${s}`,status:s,title:e??ze[s]??"Error",...t!==void 0?{detail:t}:{},...r}}function ee(s){return b(400,"Bad Request","One or more validation errors occurred.",{errors:s})}function v(s){return JSON.stringify(s)}var w="application/problem+json";var T=class extends Error{status;title;detail;extensions;constructor(e,t,r,n){super(r??t??`HTTP ${e}`),this.name="HttpError",this.status=e,this.title=t??`HTTP ${e}`,this.detail=r,this.extensions=n}toProblemDetails(){return b(this.status,this.title,this.detail,this.extensions)}},te=class extends T{constructor(e){super(404,"Not Found",e),this.name="NotFoundError"}},re=class extends T{constructor(e){super(400,"Bad Request",e),this.name="BadRequestError"}},ne=class extends T{constructor(e){super(401,"Unauthorized",e),this.name="UnauthorizedError"}},se=class extends T{constructor(e){super(403,"Forbidden",e),this.name="ForbiddenError"}},oe=class extends T{constructor(e){super(409,"Conflict",e),this.name="ConflictError"}};function Je(s){return["POST","PUT","DELETE","PATCH"].includes(s.toUpperCase())}var Ue=6e4;function Le(s={}){let{ttl:e=864e5,headerName:t="x-idempotency-key",skip:r=o=>!Je(o.method)}=s,n=new Map,i=setInterval(()=>{let o=Date.now();for(let[d,c]of n)c.expiresAt<=o&&n.delete(d)},Ue);return i.unref&&i.unref(),async(o,d)=>{if(r(o))return d();let c=o.headers[t]??o.headers[t.toLowerCase()];if(!c||typeof c!="string"||c.length===0)return d();let a=n.get(c);if(a)if(a.expiresAt<=Date.now())n.delete(c);else{let f=o.response;f.writeHead(a.status,a.headers),f.end(a.body),o.responded=!0;return}let p=o.response.writeHead.bind(o.response),l=o.response.end.bind(o.response),h=200,m={},u=[];if(o.response.writeHead=function(f,...g){return h=f,g.length>0&&(m=g[0]),p(f,...g)},o.response.end=function(f,...g){return f&&u.push(Buffer.isBuffer(f)?f:Buffer.from(f)),l(f,...g)},await d(),h>=200&&h<500){let f=Buffer.concat(u);n.set(c,{status:h,headers:m,body:f,expiresAt:Date.now()+e})}}}function We(s){return["POST","PUT","DELETE","PATCH"].includes(s.toUpperCase())}function $e(s={}){let{ttlByTag:e={},defaultTtl:t=6e4}=s,r=new Map,n=new Map,i=o=>o.every(([d,c])=>n.get(d)===c);return async(o,d)=>{let a=o.items.get("__endpoint_meta")?.cacheTags??[];if(a.length===0)return d();if(We(o.method)){let p=a.map(l=>l.name);if(await d(),o.response.statusCode>=200&&o.response.statusCode<300){for(let[l,h]of n)p.some(m=>l.startsWith(m))&&n.set(l,h+1);for(let[l,h]of r)i(h.generations)||r.delete(l)}return}if(o.method==="GET"){let p={params:o.pathParams??{},body:void 0,query:o.queryParams??{},headers:o.headers??{}},l=a.map(y=>Z(y,p)),h=a.map(({name:y})=>(n.has(y)||n.set(y,0),[y,n.get(y)]));for(let y of l){let R=r.get(y);if(R&&R.expiresAt>Date.now()&&i(R.generations)){let x=o.response;x.writeHead(R.status,R.headers),x.end(R.body),o.responded=!0;return}R&&r.delete(y)}let m=o.response.writeHead.bind(o.response),u=o.response.end.bind(o.response),f=200,g={},S=[];if(o.response.writeHead=function(y,...R){return f=y,R.length>0&&(g=R[0]),m(y,...R)},o.response.end=function(y,...R){return y&&S.push(Buffer.isBuffer(y)?y:Buffer.from(y)),u(y,...R)},await d(),f>=200&&f<300&&i(h)){let y=Buffer.concat(S),R=a.reduce((x,_)=>{let O=e[_.name]!==void 0?e[_.name]:t;return O>x?O:x},0);if(R>0)for(let x of l)r.set(x,{status:f,headers:g,body:y,expiresAt:Date.now()+R,generations:h})}return}return d()}}import{URL as Ve}from"url";import{any as ie,boolean as Ge,func as he,object as Xe,promise as fe,record as ae,string as B}from"@cleverbrush/schema";var Ye=Xe({method:B(),url:B(),pathParams:ae(B(),B()),queryParams:ae(B(),B()),headers:ae(B(),B()),items:ie(),body:he().hasReturnType(fe(ie())),json:he().hasReturnType(fe(ie())),responded:Ge()}),N=5*1024*1024,k=class{request;response;url;method;headers;items=new Map;maxBodySize;#e={};_queryParams;#t;#r=null;#n=!1;#s=void 0;#i=!1;responded=!1;principal=void 0;constructor(e,t,r){this.request=e,this.response=t,this.method=(e.method??"GET").toUpperCase(),this.maxBodySize=r??N;let n=e.url??"/";this.url=new Ve(n,`http://${e.headers.host??"localhost"}`);let i={};for(let[o,d]of Object.entries(e.headers))typeof d=="string"?i[o]=d:Array.isArray(d)&&(i[o]=d.join(", "));this.headers=i}get pathParams(){return this.#e}set pathParams(e){this.#e=e}get queryParams(){if(this._queryParams)return this._queryParams;let e={};for(let[t,r]of this.url.searchParams)e[t]=r;return e}get services(){return this.#t}set services(e){this.#t=e}async body(){return this.#n?this.#r:(this.#r=await new Promise((e,t)=>{let r=[],n=0;this.request.on("data",i=>{if(n+=i.length,n>this.maxBodySize){this.request.destroy(),t(new T(413,"Payload Too Large"));return}r.push(i)}),this.request.on("end",()=>e(Buffer.concat(r))),this.request.on("error",t)}),this.#n=!0,this.#r)}async json(){if(this.#i)return this.#s;let t=(await this.body()).toString("utf-8");return t.length>0&&(this.#s=A(t),M(this.#s)),this.#i=!0,this.#s}};import*as K from"http";import*as Ce from"https";import{AuthorizationService as rt,PolicyBuilder as nt,Principal as G,parseCookies as st,requireRole as ot}from"@cleverbrush/auth";import{ServiceCollection as it}from"@cleverbrush/di";import{Busboy as at}from"@fastify/busboy";import{WebSocketServer as dt}from"ws";var H=class{#e=[];add(e){this.#e.push(e)}async execute(e,t){let r=0,n=async()=>{if(r<this.#e.length){let i=this.#e[r++];await i(e,n)}else await t()};await n()}};function me(s){return s.bodySchema!=null}async function ge(s,e,t,r){let n=[],i={};if(i.context=t,s.authRoles!==null&&t.principal!==void 0&&(i.principal=t.principal),e&&Object.keys(e).length>0&&(i.params=e),s.bodySchema){let o=await s.bodySchema.validateAsync(r,{doNotStopOnFirstError:!0});if(o.valid)i.body=o.object;else{let d=typeof o.getInvalidProperties=="function"?o.getInvalidProperties:null,c=!1;if(d)for(let a of d()){let p=a.descriptor.toJsonPointer();for(let l of a.errors)n.push({pointer:`/body${p}`,detail:l}),c=!0}if(!c)for(let a of o.errors??[])n.push({pointer:"/body",detail:a.message})}}if(s.querySchema){let o=s.querySchema.introspect();if(o.type!=="object"||!o.properties)throw new Error("Endpoint query schema must be an object schema whose properties map to query parameter names.");let d=o.properties,c={};for(let[a,p]of Object.entries(d)){let l=t.queryParams[a],h=await p.validateAsync(l,{doNotStopOnFirstError:!0});if(h.valid)c[a]=h.object;else for(let m of h.errors??[])n.push({pointer:`/query/${a}`,detail:m.message})}i.query=c}if(s.headerSchema){let o=s.headerSchema.introspect();if(o.type!=="object"||!o.properties)throw new Error("Endpoint headers schema must be an object schema whose properties map to header names.");let d=o.properties,c={};for(let[a,p]of Object.entries(d)){let l=t.headers[a.toLowerCase()],h=await p.validateAsync(l,{doNotStopOnFirstError:!0});if(h.valid)c[a]=h.object;else for(let m of h.errors??[])n.push({pointer:`/headers/${a}`,detail:m.message})}i.headers=c}if(n.length>0)return{valid:!1,problemDetails:ee(n)};if(s.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 o={};for(let[d,c]of Object.entries(s.serviceSchemas))o[d]=t.services.get(c);return{valid:!0,args:[i,o]}}return{valid:!0,args:[i]}}function j(s){let e=decodeURI(s);return e.length>1&&e.endsWith("/")?e.slice(0,-1):e}function de(s){return typeof s!="string"&&typeof s.validate=="function"}function ye(s){let e=0,t=!1;for(let r of s)for(let n of r)n==="/"?(t&&e++,t=!1):t=!0;return e+(t?1:0)}function Ke(s,e){if(!de(e)){let i=j(e),o=i==="/"?s||"/":s+i;return{isStatic:!0,literalSegments:ye([o]),dynamicSegments:0}}let{literals:t,segments:r}=e.introspect().templateDefinition,n=[s+(t[0]??""),...t.slice(1)];return{isStatic:r.length===0,literalSegments:ye(n),dynamicSegments:r.length}}function Ze(s,e){return s.isStatic!==e.isStatic?s.isStatic?1:-1:s.literalSegments!==e.literalSegments?s.literalSegments-e.literalSegments:e.dynamicSegments-s.dynamicSegments}function Qe(s,e){if(!de(e)){let n=j(e);return n==="/"?s||"/":s+n}let{literals:t,segments:r}=e.introspect().templateDefinition;return r.length>0?null:s+(t[0]??"")}function Re(s,e,t){let r=j(s);return{basePath:r,routePath:e,specificity:Ke(r,e),exactPath:Qe(r,e),registration:t}}function Se(){return{exactRoutes:new Map,dynamicRoutes:[]}}function be(s,e){if(e.exactPath!==null){s.exactRoutes.has(e.exactPath)||s.exactRoutes.set(e.exactPath,e);return}s.dynamicRoutes.push(e)}var W=class{#e=new Map;#t=Se();#r=!0;addRoute(e){let{method:t,basePath:r,pathTemplate:n}=e.endpoint,i=t.toUpperCase(),o=Re(r,n,e),d=this.#e.get(i);d||(d=Se(),this.#e.set(i,d)),be(d,o),this.#r=!1}finalize(){if(!this.#r){for(let e of this.#e.values())this.#s(e.dynamicRoutes);this.#s(this.#t.dynamicRoutes),this.#r=!0}}match(e,t){let r;try{r=j(t)}catch{return{match:null,methodNotAllowed:!1,badRequest:!0}}let n=e.toUpperCase();this.finalize();let i=this.#e.get(n);if(i){let d=this.#n(i,r);if(d)return{match:d,methodNotAllowed:!1}}let o=[];for(let[d,c]of this.#e)d!==n&&this.#n(c,r)&&o.push(d);return o.length>0?{match:null,methodNotAllowed:!0,allowedMethods:o}:{match:null,methodNotAllowed:!1}}#n(e,t){let r=e.exactRoutes.get(t);if(r){let n=this.#i(r,t);if(n)return n}for(let n of e.dynamicRoutes){let i=this.#i(n,t);if(i)return i}return null}#s(e){e.sort((t,r)=>Ze(r.specificity,t.specificity))}#i(e,t){let{basePath:r,routePath:n}=e;if(r&&!t.startsWith(r))return null;let i=r?t.slice(r.length):t;if(de(n)){let c=n.validate(i);return c.valid?{registration:e.registration,parsedPath:c.object}:null}let o=j(n);return(i.length===0?"/":i)===o?{registration:e.registration,parsedPath:null}:null}addSubscriptionRoute(e){let{basePath:t,pathTemplate:r}=e.endpoint;be(this.#t,Re(t,r,e)),this.#r=!1}matchSubscription(e){let t;try{t=j(e)}catch{return null}return this.finalize(),this.#n(this.#t,t)}};import{Readable as et,Writable as tt}from"stream";var $=class extends et{method;url;headers;__cleverbrushBatchSubrequest;socket=null;#e;#t=!1;constructor(e){super(),this.method=e.method,this.url=e.url;let t={};for(let[r,n]of Object.entries(e.headers??{}))t[r.toLowerCase()]=n;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))}},V=class extends tt{statusCode=200;headersSent=!1;#e=[];#t={};#r=200;_write(e,t,r){this.#e.push(Buffer.isBuffer(e)?e:Buffer.from(e)),r()}writeHead(e,t){if(this.#r=e,this.statusCode=e,t!=null&&typeof t=="object"&&!Array.isArray(t))for(let[r,n]of Object.entries(t))this.#t[r.toLowerCase()]=Array.isArray(n)?n.join(", "):String(n);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()]}end(e,...t){if(e!=null&&typeof e!="function"){let r=Buffer.isBuffer(e)||e instanceof Uint8Array?Buffer.from(e):Buffer.from(String(e),"utf-8");this.#e.push(r),super.end(...t)}else typeof e=="function"?super.end(e):super.end(...t);return this}toResult(){return{status:this.#r,headers:{...this.#t},body:Buffer.concat(this.#e).toString("utf-8")}}};function ve(s){return{type:"message",data:s}}function we(s,e){return{type:"tracked",id:s,data:e}}function Pe(){return{type:"pong"}}function E(s,e){return{type:"error",code:s,message:e}}function Te(s){let e;try{e=A(s),M(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}async function ct(s,e){let t=e.maxFileCount??10,r=e.maxFileSize??10*1024*1024,n=e.allowedMimeTypes;return new Promise((i,o)=>{let d={},c={},a=[],p=0,l=at({headers:s.headers,limits:{fileSize:r,files:t}});l.on("field",(h,m)=>{d[h]=m}),l.on("file",(h,m,u,f,g)=>{if(p>=t){a.push({filename:u,mimeType:g,reason:`Exceeded max file count (${t})`}),m.resume();return}if(n&&!n.some(R=>R.endsWith("/*")?g.startsWith(R.slice(0,-1)):g===R)){a.push({filename:u,mimeType:g,reason:`MIME type "${g}" not allowed (allowed: ${n.join(", ")})`}),m.resume();return}p++;let S=[];m.on("data",y=>{S.push(y)}),m.on("end",()=>{let y=Buffer.concat(S);c[h]={filename:u,mimeType:g,buffer:y,size:y.length}}),m.on("error",o)}),l.on("error",o),l.on("finish",()=>i({fields:d,files:c,rejectedFiles:a})),s.pipe(l)})}var X=class{#e=new it;#t=[];#r=[];#n=[];#s=[];#i=new q;#a;#d=null;#o=null;#c=!1;#l=null;constructor(e={}){this.#a=e}services(e){return e(this.#e),this}use(e){return this.#s.push(e),this}contentType(e){return this.#i.register(e),this}useAuthentication(e){return this.#d=e,this}useAuthorization(e){return this.#o=e??{},this}withHealthcheck(){return this.#c=!0,this}useBatching(e={}){return this.#l=e,this}handle(e,t,r){return this.#t.push({endpoint:e.introspect(),handler:t,middlewares:r?.middlewares}),this}handleAll(e){for(let t of e._entries)this.#t.push({endpoint:t.endpoint.introspect(),handler:t.handler,middlewares:t.middlewares});for(let t of e._subscriptions)this.#r.push({endpoint:t.endpoint.introspect(),handler:t.handler,middlewares:t.middlewares});return this}getRegistrations(){return[...this.#t]}getSubscriptionRegistrations(){return[...this.#r]}webhook(e){return this.#n.push(e),this}getWebhooks(){return[...this.#n]}getAuthenticationConfig(){return this.#d}async listen(e,t){let r=new W;for(let p of this.#t)r.addRoute(p);for(let p of this.#r)r.addSubscriptionRoute(p);r.finalize();let n=this.#e.buildServiceProvider({validateScopes:!1}),i=[];if(this.#d&&i.push(ht(this.#d)),this.#o!==null){let p=new Map;if(this.#o.policies)for(let[h,m]of Object.entries(this.#o.policies)){let u=new nt;m(u),p.set(h,u.build(h))}let l=new rt(p);i.push(ft(l,this.#d))}let o=[...i,...this.#s],d=new Y(r,n,this.#i,o,this.#c,this.#r.length>0,this.#l,this.#a.maxBodySize),c=e??this.#a.port??3e3,a=t??this.#a.host??"0.0.0.0";return await d.start(c,a,this.#a),d}},lt=1024,Y=class{#e;#t;#r;#n;#s;#i;#a;#d;#o=null;#c=null;#l=new Set;constructor(e,t,r,n,i=!1,o=!1,d=null,c=N){this.#e=e,this.#t=t,this.#r=r,this.#n=n,this.#s=i,this.#i=o,this.#a=d,this.#d=c}async start(e,t,r){let n=(i,o)=>{this.#u(i,o).catch(d=>{o.headersSent||(o.writeHead(500,{"content-type":w}),o.end(v(b(500))))})};r.https?this.#o=Ce.createServer({key:r.https.key,cert:r.https.cert},n):this.#o=K.createServer(n),await new Promise(i=>{this.#o.listen(e,t,i)}),this.#i&&(this.#c=new dt({noServer:!0,maxPayload:this.#d}),this.#o.on("upgrade",(i,o,d)=>{let c=new URL(i.url??"/",`http://${i.headers.host??"localhost"}`).pathname,a=this.#e.matchSubscription(c);if(!a){o.write(`HTTP/1.1 404 Not Found\r
|
|
2
2
|
\r
|
|
3
|
-
`),
|
|
3
|
+
`),o.destroy();return}this.#c.handleUpgrade(i,o,d,p=>{this.#f(p,i,a.registration,a.parsedPath)})}))}async close(){for(let e of this.#l)e.close(1001,"Server shutting down");this.#l.clear(),this.#c&&(await new Promise((e,t)=>{this.#c.close(r=>{r?t(r):e()})}),this.#c=null),this.#o&&(await new Promise((e,t)=>{this.#o.close(r=>{r?t(r):e()})}),this.#o=null)}get address(){let e=this.#o?.address();return!e||typeof e=="string"?null:{port:e.port,host:e.address}}async#u(e,t){let r=this.#t.createScope();try{let n=new k(e,t,this.#d),i=n.url.pathname,o=n.method,d=e.__cleverbrushBatchSubrequest;if(d&&n.items.set("__batch_subrequest",d),this.#s&&o==="GET"&&i==="/health"){t.writeHead(200),t.end();return}if(this.#a!==null&&o==="POST"&&i===(this.#a.path??"/__batch")){n.services=r.serviceProvider;let m=new H;for(let u of this.#n)m.add(u);await m.execute(n,async()=>{n.responded||(await this.#p(e,t),n.responded=!0)});return}let c=this.#e.match(o,i);if(!c.match){if(c.badRequest){let u=b(400);t.writeHead(400,{"content-type":w}),t.end(v(u));return}if(c.methodNotAllowed){let u=b(405,"Method Not Allowed");t.writeHead(405,{"content-type":w,allow:c.allowedMethods.join(", ")}),t.end(v(u));return}let m=b(404);t.writeHead(404,{"content-type":w}),t.end(v(m));return}let{registration:a,parsedPath:p}=c.match,l=a.endpoint;if(p){let m={};ce(p,"",m),n.pathParams=m}n.services=r.serviceProvider,n.items.set("__endpoint_meta",l);let h=new H;for(let m of this.#n)h.add(m);if(a.middlewares)for(let m of a.middlewares)h.add(m);await h.execute(n,async()=>{if(n.responded)return;let m,u,f;if(me(l)){let y=e.headers["content-type"]??"";if(l.fileUpload&&y.startsWith("multipart/form-data"))try{let R=await ct(e,l.fileUpload);m=R.fields,u=R.files,f=R.rejectedFiles}catch{let R=b(400,"Malformed multipart request");t.writeHead(400,{"content-type":w}),t.end(v(R)),n.responded=!0;return}else if(l.fileUpload){let R=b(400,"File upload endpoint requires multipart/form-data content type");t.writeHead(400,{"content-type":w}),t.end(v(R)),n.responded=!0;return}else{let R=this.#r.selectRequestHandler(y);if(R){let _=(await n.body()).toString("utf-8");if(_.length>0)try{m=R.deserialize(_)}catch{let O=b(400,"Malformed request body");t.writeHead(400,{"content-type":w}),t.end(v(O)),n.responded=!0;return}}else if(y){let x=b(415);t.writeHead(415,{"content-type":w}),t.end(v(x)),n.responded=!0;return}}}let g=await ge(l,p,n,m);if(!g.valid){t.writeHead(400,{"content-type":w}),t.end(v(g.problemDetails)),n.responded=!0;return}if(u&&g.args.length>0){let y=g.args[0];y.files=u,f&&f.length>0&&(y.rejectedFiles=f)}let S=a.handler(...g.args);S instanceof Promise&&(S=await S),!n.responded&&(await this.#h(e,t,S),n.responded=!0)})}catch(n){if(t.headersSent)return;if(n instanceof T){let i=n.toProblemDetails();t.writeHead(i.status,{"content-type":w}),t.end(v(i))}else{console.error("[server] Unhandled error:",n);let i=b(500);t.writeHead(500,{"content-type":w}),t.end(v(i))}}finally{try{await r.asyncDispose()}catch{}}}async#p(e,t){let r=this.#a,n=r.maxSize??20,i=r.parallel??!0,o;try{let a=await pt(e,this.#d),p=A(a.toString("utf-8"));if(M(p),o=p,!Array.isArray(o?.requests))throw new Error("requests must be an array")}catch(a){if(a instanceof T&&a.status===413){let l=b(413,"Payload Too Large");t.writeHead(413,{"content-type":w}),t.end(v(l));return}let p=b(400,"Invalid batch request body");t.writeHead(400,{"content-type":w}),t.end(v(p));return}if(o.requests.length>n){let a=b(400,`Batch size ${o.requests.length} exceeds maximum of ${n}`);t.writeHead(400,{"content-type":w}),t.end(v(a));return}let d=async(a,p)=>{let l=new $({method:(a.method??"GET").toUpperCase(),url:a.url,headers:a.headers??{},body:a.body});l.__cleverbrushBatchSubrequest={index:p,size:o.requests.length,path:r.path??"/__batch"};let h=new V;return await this.#u(l,h),h.toResult()},c;if(i)c=await Promise.all(o.requests.map(d));else{c=[];for(let a=0;a<o.requests.length;a++)c.push(await d(o.requests[a],a))}t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({responses:c}))}async#h(e,t,r){r instanceof C?await r.executeAsync(e,t,this.#r):r==null?(t.writeHead(204),t.end()):await new P(r,200).executeAsync(e,t,this.#r)}#f(e,t,r,n){this.#l.add(e);let i=this.#t.createScope(),o=new AbortController,d=r.endpoint,c=new K.ServerResponse(t),a=new k(t,c);if(n){let l={};ce(n,"",l),a.pathParams=l}a.services=i.serviceProvider,a.items.set("__endpoint_meta",d);let p=new H;for(let l of this.#n)p.add(l);if(r.middlewares)for(let l of r.middlewares)p.add(l);p.execute(a,async()=>{if(a.responded){e.close(1008,"Unauthorized");return}this.#m(e,a,d,r.handler,n,i,o)}).catch(()=>{e.close(1011,"Internal Server Error")}),e.on("close",()=>{this.#l.delete(e),o.abort(),i.asyncDispose().catch(()=>{})}),e.on("error",()=>{this.#l.delete(e),o.abort(),i.asyncDispose().catch(()=>{})})}#m(e,t,r,n,i,o,d){let c=[],a=null,p=!1,l={[Symbol.asyncIterator](){return{next(){return c.length>0?Promise.resolve({value:c.shift(),done:!1}):p?Promise.resolve({value:void 0,done:!0}):new Promise(u=>{a=()=>{a=null,c.length>0?u({value:c.shift(),done:!1}):u({value:void 0,done:!0})}})},return(){return p=!0,Promise.resolve({value:void 0,done:!0})}}}};e.on("message",u=>{let f=typeof u=="string"?u:u.toString("utf-8"),g=Te(f);if(!g){e.send(JSON.stringify(E(400,"Invalid frame format")));return}if(g.type==="ping"){e.send(JSON.stringify(Pe()));return}if(c.length>=lt){e.send(JSON.stringify(E(429,"Message queue full \u2014 slow down or reconnect"))),e.close(1008,"Message queue overflow");return}if(r.incomingSchema){let S=r.incomingSchema.validate(g.data);if(!S.valid){let y=(S.errors??[]).map(R=>R.message).join("; ");e.send(JSON.stringify(E(422,`Validation failed: ${y}`)));return}c.push(S.object)}else c.push(g.data);a&&a()}),e.on("close",()=>{p=!0,a&&a()});let h={context:t,signal:d.signal};if(i&&Object.keys(i).length>0&&(h.params=i),r.querySchema){let u={};for(let[g,S]of t.url.searchParams.entries())u[g]=S;let f=r.querySchema.validate(u);if(!f.valid){let g=(f.errors??[]).map(S=>S.message).join("; ");e.close(1002,`Query validation failed: ${g}`);return}h.query=f.object}if(r.headerSchema){let u=r.headerSchema.validate(t.headers);if(!u.valid){let f=(u.errors??[]).map(g=>g.message).join("; ");e.close(1002,`Header validation failed: ${f}`);return}h.headers=u.object}t.principal!==void 0&&(h.principal=t.principal),r.incomingSchema,h.incoming=l;let m=[h];if(r.serviceSchemas){let u={};for(let[f,g]of Object.entries(r.serviceSchemas))u[f]=o.serviceProvider.get(g);m.push(u)}(async()=>{try{let u=n(...m);for await(let f of u){if(e.readyState!==e.OPEN)break;let g;if(le(f)){let S=r.outgoingSchema?r.outgoingSchema.validate(f.data):{valid:!0,object:f.data};if(!S.valid){e.send(JSON.stringify(E(500,"Outgoing validation failed")));continue}g=JSON.stringify(we(f.id,S.object))}else{let S=r.outgoingSchema?r.outgoingSchema.validate(f):{valid:!0,object:f};if(!S.valid){e.send(JSON.stringify(E(500,"Outgoing validation failed")));continue}g=JSON.stringify(ve(S.object))}e.send(g)}}catch(u){e.readyState===e.OPEN&&(u instanceof Error&&console.error("[server] Subscription handler error:",u),e.send(JSON.stringify(E(500,"Internal error"))),e.close(1011,"Handler error"))}})()}};function ut(s){return new X(s)}function pt(s,e=N){return new Promise((t,r)=>{let n=[],i=0;s.on("data",o=>{if(i+=o.length,i>e){s.destroy(),r(new T(413,"Payload Too Large"));return}n.push(o)}),s.on("end",()=>t(Buffer.concat(n))),s.on("error",r)})}function ce(s,e,t){for(let[r,n]of Object.entries(s)){let i=e?`${e}.${r}`:r;n!==null&&typeof n=="object"&&!Array.isArray(n)?ce(n,i,t):t[i]=String(n)}}function ht(s){let e=new Map;for(let r of s.schemes)e.set(r.name,r);let t;return s.trySchemes==="all"?t=s.schemes:t=(s.trySchemes&&s.trySchemes.length>0?s.trySchemes:[s.defaultScheme]).map(n=>e.get(n)).filter(n=>n!==void 0),async(r,n)=>{if(r.items.get("__endpoint_meta")?.authRoles===null){r.principal=G.anonymous(),await n();return}let o={headers:r.headers,cookies:st(r.headers.cookie??""),items:r.items};r.principal=G.anonymous();for(let d of t){let c=await d.authenticate(o);if(c.succeeded){r.principal=c.principal;break}}await n()}}function ft(s,e){let t={};if(e){for(let r of e.schemes)if(r.challenge){let n=r.challenge();t[n.headerName.toLowerCase()]=n.headerValue}}return async(r,n)=>{let i=r.items.get("__endpoint_meta");if(!i||i.authRoles===null){await n();return}let o=r.principal;if(!o||!(o instanceof G)||!o.isAuthenticated){let d=b(401,"Unauthorized"),c={"content-type":w,...t};r.response.writeHead(401,c),r.response.end(v(d)),r.responded=!0;return}if(i.authRoles.length>0&&!(await s.authorize(o,[ot(...i.authRoles)])).allowed){let c=b(403,"Forbidden");r.response.writeHead(403,{"content-type":w}),r.response.end(v(c)),r.responded=!0;return}o instanceof G&&(r.principal=o.value),await n()}}function mt(s,e){return{name:s,...e}}export{C as ActionResult,re as BadRequestError,oe as ConflictError,q as ContentNegotiator,I as ContentResult,N as DEFAULT_MAX_BODY_SIZE,ke as EndpointBuilder,D as FileResult,se as ForbiddenError,T as HttpError,Ye as IRequestContext,P as JsonResult,L as NoContentResult,te as NotFoundError,F as RawResult,U as RedirectResult,k as RequestContext,Y as Server,X as ServerBuilder,J as StatusCodeResult,z as StreamResult,Be as SubscriptionBuilder,ne as UnauthorizedError,$e as cacheResponse,Z as computeCacheKey,xe as createCacheTagTree,He as createEndpoints,b as createProblemDetails,ut as createServer,ee as createValidationProblemDetails,qe as defineApi,mt as defineWebhook,je as endpoint,pe as formUrlEncodedContentTypeHandler,Le as idempotency,ue as jsonContentTypeHandler,Ee as mapHandlers,Ne as mergeContracts,Fe as omitGroups,Oe as pickGroups,_e as route,Ae as serializeTag,Me as tracked};
|
|
4
4
|
//# sourceMappingURL=index.js.map
|