truxie 0.1.1 → 0.1.3
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 +1 -1
- package/dist/chunk-CD6QSDG5.js +2 -0
- package/dist/chunk-RDP32XIU.js +1 -0
- package/dist/index.d.ts +187 -12
- package/dist/index.js +3 -3
- package/dist/testing.js +1 -1
- package/dist/{types-G2NQp5Jb.d.ts → types-BHt3a4dp.d.ts} +11 -1
- package/dist/ws.d.ts +7 -5
- package/dist/ws.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-42ZAPMNO.js +0 -1
- package/dist/chunk-RXJTN5BJ.js +0 -1
package/README.md
CHANGED
|
@@ -99,7 +99,7 @@ Dynamic modules (`forRoot` / `forRootAsync` / `forFeature`) come from `Configura
|
|
|
99
99
|
- **CQRS** (`truxie/cqrs`) — `CommandBus`, `QueryBus`, `EventBus`, `AggregateRoot`, `@CommandHandler`, `@QueryHandler`, `@EventsHandler`.
|
|
100
100
|
- **WebSockets** (`truxie/ws`) — `@WebSocketGateway`, `@SubscribeMessage`, adapter-agnostic peers.
|
|
101
101
|
- **Testing** (`truxie/testing`) — `Test.createTestingModule(...)` with `overrideProvider`, running the same lifecycle the application runs.
|
|
102
|
-
- **Introspection** — `app.getRoutes()`, `@ApiDoc`, `describeRouteInput`, consumed by `@truxie/openapi` and `@truxie/mcp`.
|
|
102
|
+
- **Introspection** — `app.getRoutes()`, `@ApiDoc`, `describeRouteInput`, consumed by `@truxie/openapi` and `@truxie/mcp`. A handler that validates by hand documents its input with `@ApiDoc({request: {query, body, params}})`; a schema a param decorator records still wins, and `routeInputDrift(route)` reports keys the handler reads that the documentation misses, and the reverse.
|
|
103
103
|
|
|
104
104
|
```ts
|
|
105
105
|
const testingModule = await Test.createTestingModule(UserModule)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {i as i$1}from'./chunk-RDP32XIU.js';import {d,h,a as a$1,i,j as j$1,k as k$1,b,n,o,e}from'./chunk-TSJZVSHP.js';import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';var $=new WeakSet;function S(i){return $.has(i)?false:($.add(i),true)}a(S,"claimDestroy");var k=class extends Error{static{a(this,"MissingProviderError");}},F=class i$1{static{a(this,"Container");}registrations=new Map;parent=null;children=[];register(...e){for(let t of e)this.registerOne(t);}registerOne(e){let t=e&&typeof e=="object"&&"forwardRef"in e?d(e):e;if(typeof t=="function"){let a=h(t)?.scope??a$1.SINGLETON;this.registrations.set(t,{provider:t,scope:a,resolved:false});return}let n=t.provide,o=a$1.SINGLETON,s=t;if("useClass"in t){let r=t.useClass,a=r&&typeof r=="object"&&"forwardRef"in r?d(r):r,f=h(a);o=t.scope??f?.scope??a$1.SINGLETON,s={...t,useClass:a};}else if("useExisting"in t){let r=t.useExisting,a=r&&typeof r=="object"&&"forwardRef"in r?d(r):r;s={...t,useExisting:a};}else "useFactory"in t&&(o=t.scope??a$1.SINGLETON);this.registrations.set(n,{provider:s,scope:o,resolved:false});}async resolve(e){return this.resolveInternal(e,J)}async resolveInternal(e,t){let n=d(e),o=n!==e?n:e,s=this.findOwner(o);if(!s)throw new k(`No provider found for ${P(o)}`);let r=s.registrations.get(o),a=r.scope===a$1.SINGLETON?s:this,f=r.scope===a$1.SINGLETON||r.scope===a$1.REQUEST&&a.parent!==null;if(f&&r.resolved)return r.instance;if(t.has(o))throw new Error(`Circular dependency detected for ${P(o)}`);if(f&&r.inFlight)return r.inFlight;let m=new Set(t).add(o),l=a.createInstance(r,m).then(h=>(f&&(r.instance=h,r.resolved=true),r.inFlight=void 0,h),h=>{throw r.inFlight=void 0,h});return f&&(r.inFlight=l),l}has(e){return this.registrations.has(e)||(this.parent?.has(e)??false)}hasRequestScoped(){for(let[,e]of this.registrations)if(e.scope===a$1.REQUEST)return true;return this.parent?.hasRequestScoped()??false}findOwner(e){return this.registrations.has(e)?this:this.parent?.findOwner(e)??null}createChild(){let e=new i$1;e.parent=this;for(let[t,n]of this.registrations)n.scope===a$1.REQUEST&&e.registrations.set(t,{provider:n.provider,scope:a$1.REQUEST,instance:void 0,resolved:false});return this.children.push(e),e}async dispose(){for(let e of [...this.children])await e.dispose();this.children=[];for(let[,e]of this.registrations){if(!e.resolved)continue;let t=e.instance;if(!t||typeof t!="object")continue;let n=t;typeof n.onModuleDestroy=="function"&&S(t)&&await n.onModuleDestroy();}if(this.registrations.clear(),this.parent){let e=this.parent.children.indexOf(this);e!==-1&&this.parent.children.splice(e,1),this.parent=null;}}async createInstance(e,t){let{provider:n}=e;if(typeof n=="function")return this.instantiateClass(n,t);if("useValue"in n)return n.useValue;if("useClass"in n)return this.instantiateClass(n.useClass,t);if("useFactory"in n){let o=n,s=[];if(o.inject)for(let r of o.inject)s.push(await this.resolveInternal(r,t));return o.useFactory(...s)}if("useExisting"in n)return this.resolveInternal(n.useExisting,t);throw new Error("Unknown provider type")}async instantiateClass(e,t){let n=Reflect.getMetadata("design:paramtypes",e)??[],o=i(e),s=j$1(e),r=k$1(e),a=s.size>0?Math.max(...s.keys())+1:0,f=Math.max(n.length,a,o.length),m=[];for(let l=0;l<f;l++){let h=s.get(l)??o[l]??n[l];try{m.push(await this.resolveInternal(h,t));}catch(g){if(g instanceof k&&r.has(l)){m.push(void 0);continue}let M=g instanceof Error?g.message:String(g);throw new Error(`Cannot resolve parameter at index ${l} (${P(h)}) of ${e.name}: ${M}`,{cause:g})}}return new e(...m)}},J=new Set;function P(i){return typeof i=="string"?i:typeof i=="symbol"||i instanceof b?i.toString():typeof i=="function"?i.name:String(i)}a(P,"tokenToString");function _(i,e){let t=[];for(let s=e;typeof s=="function"&&s!==Function.prototype;s=Object.getPrototypeOf(s)){let r=Reflect.getOwnMetadata(i,s);r!==void 0&&r.length>0&&t.push(r);}let n=new Set,o=[];for(let s of t.reverse())for(let r of s)n.has(r)||(n.add(r),o.push(r));return o}a(_,"inheritedClassMetadata");var L=Symbol.for("truxie:controller:path"),v=Symbol.for("truxie:controller:guards"),j=Symbol.for("truxie:route:metadata"),U=Symbol.for("truxie:method:route"),E=Symbol.for("truxie:method:guards"),N=Symbol.for("truxie:method:noguard");function ye(i){return e=>{Reflect.defineMetadata(L,i,e);}}a(ye,"Controller");function x(i){return (e="")=>(t,n,o)=>{let s=o!==void 0,r=String(s?n:n?.name??n),a=s?o?.value:t;if(typeof a=="function"&&(a[U]={method:i,path:e,methodName:r}),s){let f=Reflect.getOwnMetadata(j,t.constructor)??[];return f.push({method:i,path:e,methodName:r}),Reflect.defineMetadata(j,f,t.constructor),o}return t}}a(x,"createMethodDecorator");var we=x("GET"),Ee=x("POST"),xe=x("PUT"),Me=x("DELETE"),be=x("PATCH");function Te(...i){return (e,t,n)=>{if(t==null){let o=Reflect.getOwnMetadata(v,e)??[];Reflect.defineMetadata(v,[...o,...i],e);return}if(n!==void 0){if(n?.value){let o=n.value[E]??[];n.value[E]=[...o,...i];}return n}if(typeof e=="function"){let o=e[E]??[];e[E]=[...o,...i];}if(typeof e=="function"&&t?.kind==="class"){let o=Reflect.getOwnMetadata(v,e)??[];Reflect.defineMetadata(v,[...o,...i],e);}return e}}a(Te,"RouteGuards");function Re(){return (i,e,t)=>t!==void 0?(t?.value&&(t.value[N]=true),t):(typeof i=="function"&&(i[N]=true),i)}a(Re,"NoGuard");function V(i){return Reflect.getOwnMetadata(L,i)}a(V,"getControllerPath");function Se(i){return Reflect.getOwnMetadata(v,i)??[]}a(Se,"getControllerGuards");function Q(i){let e=new Map,t=i.prototype;for(;t&&t!==Object.prototype;){for(let n of Object.getOwnPropertyNames(t)){if(n==="constructor"||e.has(n))continue;let o=Object.getOwnPropertyDescriptor(t,n);!o||typeof o.value!="function"||e.set(n,o.value);}t=Object.getPrototypeOf(t);}return e}a(Q,"methodsOf");function X(i,e){return Q(i).get(e)}a(X,"methodOf");function Oe(i){let e=[],t=new Set;for(let[n,o]of Q(i)){let s=o[U];!s||t.has(n)||(t.add(n),e.push(s));}if(e.length>0)return e;for(let n=i;n&&n!==Function.prototype;n=Object.getPrototypeOf(n)){let o=Reflect.getOwnMetadata(j,n)??[];for(let s of o)t.has(s.methodName)||(t.add(s.methodName),e.push(s));}return e}a(Oe,"getRouteMetadata");function Pe(i,e){let t=X(i,e),n=t!==void 0&&t[N]===true,o=t!==void 0&&t[E]||[];return n?o:[...Z(i),...o]}a(Pe,"getMethodGuards");function Z(i){return _(v,i)}a(Z,"controllerGuardsOf");var z=class{static{a(this,"ModuleRegistry");}resolved=new Map;sortedModules=[];scan(e){this.resolveModule(e),this.sortedModules=this.topologicalSort(),this.validateExports();}registerAll(e){let t=new Set;for(let n of this.sortedModules)if(n.global)for(let o of n.providers)t.add(o);t.size>0&&e.register(...t);for(let n of this.sortedModules){e.register(...n.providers);for(let o of n.metadata.imports??[]){let s=this.getModuleType(o),r=this.resolved.get(s);if(r)for(let a of r.exports){let f=this.findProvider(r,a)??this.findReExportedProvider(r,a);f&&e.register(f);}}}}getAllProviders(){let e=[];for(let t of this.sortedModules)e.push(...t.providers);return e}getAllControllers(){let e=new Set,t=[];for(let n of this.sortedModules){for(let o of n.controllers)e.has(o)||(e.add(o),t.push(o));for(let o of n.metadata.providers??[])typeof o=="function"&&V(o)!==void 0&&!e.has(o)&&(e.add(o),t.push(o));}return t}getAllGateways(){let e=new Set,t=[];for(let n of this.sortedModules)for(let o of n.providers)typeof o=="function"&&i$1(o)!==void 0&&!e.has(o)&&(e.add(o),t.push(o));return t}async callLifecycleHooks(e,t,n){for(let o of this.sortedModules)for(let s of o.providers){let r=typeof s=="function"?s:s.provide;if(e.has(r))try{let a=await e.resolve(r);if(a&&typeof a=="object"&&typeof a[t]=="function"){if(t==="onModuleDestroy"&&!S(a))continue;await a[t](n);}}catch{}}}resolveModule(e){let t=d(e),n$1=typeof t=="object"&&"module"in t,o$1=n$1?t.module:t,s=this.resolved.get(o$1);if(s)return n$1&&this.mergeDynamicModule(s,e),s;let r=n(o$1)??{},a=n$1?e:{},f=[...r.controllers??[],...a.controllers??[]],m=[...r.providers??[],...a.providers??[]],l=[...r.exports??[],...a.exports??[]],h=m.map(u=>u&&typeof u=="object"&&"forwardRef"in u?d(u):u),g=l.map(u=>u&&typeof u=="object"&&"forwardRef"in u?d(u):u),M={imports:[...r.imports??[],...a.imports??[]],controllers:f,providers:h,exports:g},D={type:o$1,metadata:M,controllers:f,providers:[...f,...h],exports:new Set(g),global:n$1?e.global??o(o$1):o(o$1)};this.resolved.set(o$1,D);for(let u of M.imports??[])this.resolveModule(u);return D}mergeDynamicModule(e,t){if(t.controllers&&t.controllers.length>0&&(e.controllers.push(...t.controllers),e.providers.push(...t.controllers),e.metadata.controllers=[...e.metadata.controllers??[],...t.controllers]),t.providers&&t.providers.length>0){let n=t.providers.map(o=>o&&typeof o=="object"&&"forwardRef"in o?d(o):o);e.providers.push(...n),e.metadata.providers=[...e.metadata.providers??[],...n];}if(t.exports&&t.exports.length>0){let n=t.exports.map(o=>o&&typeof o=="object"&&"forwardRef"in o?d(o):o);for(let o of n)e.exports.add(o);e.metadata.exports=[...e.metadata.exports??[],...n];}if(t.imports&&t.imports.length>0){e.metadata.imports=[...e.metadata.imports??[],...t.imports];for(let n of t.imports)this.resolveModule(n);}t.global===true&&(e.global=true);}getVisibleTokens(e){let t=new Set;for(let n of e.providers)t.add(this.getProviderToken(n));for(let n of e.metadata.imports??[]){let o=this.getModuleType(n),s=this.resolved.get(o);if(s)for(let r of s.exports)t.add(r);}for(let n of this.sortedModules)if(n.global)for(let o of n.providers)t.add(this.getProviderToken(o));return t}validateExports(){for(let e of this.sortedModules){let t=new Set(e.providers.map(o=>this.getProviderToken(o))),n=this.collectImportedExports(e);for(let o of e.exports)if(!t.has(o)&&!n.has(o)){let s=typeof o=="function"?o.name:String(o);throw new Error(`${e.type.name} exports ${s} but it is not in its providers and is not re-exported from an imported module`)}}}validateVisibility(e=[]){let t=new Set(e),n=[];for(let o of this.sortedModules){let s=this.getVisibleTokens(o);for(let r of o.providers){let a=typeof r=="function"?r.name:q(r.provide);for(let f of K(r))!s.has(f)&&!t.has(f)&&n.push(`${o.type.name}: ${a} depends on ${q(f)}, but it is not provided in this module and not exported by any imported module`);}}if(n.length>0)throw new Error(n.join(`
|
|
2
|
+
`))}getProviderToken(e){return typeof e=="function"?e:e.provide}collectImportedExports(e){let t=new Set;for(let n of e.metadata.imports??[]){let o=this.getModuleType(n),s=this.resolved.get(o);if(s)for(let r of s.exports)t.add(r);}return t}findProvider(e,t){return e.providers.find(n=>typeof n=="function"?n===t:n.provide===t)}findReExportedProvider(e,t){for(let n of e.metadata.imports??[]){let o=this.getModuleType(n),s=this.resolved.get(o);if(!s||!s.exports.has(t))continue;let r=this.findProvider(s,t);if(r)return r;let a=this.findReExportedProvider(s,t);if(a)return a}}getModuleType(e){let t=d(e);return typeof t=="object"&&"module"in t?t.module:t}topologicalSort(){let e=new Set,t=new Set,n=[],o=a(s=>{if(e.has(s))return;if(t.has(s))throw new Error(`Circular module dependency detected: ${s.name}`);t.add(s);let r=this.resolved.get(s);if(r){for(let a of r.metadata.imports??[])o(this.getModuleType(a));t.delete(s),e.add(s),n.push(r);}},"visit");for(let[s]of this.resolved)o(s);return n}};function q(i){return typeof i=="function"?i.name:String(i)}a(q,"tokenName");function W(i$1){let e=i(i$1),t=j$1(i$1),n=k$1(i$1),o=Math.max(e.length,...[...t.keys()].map(r=>r+1),0),s=[];for(let r=0;r<o;r++){if(n.has(r))continue;let a=t.get(r)??e[r];a!==void 0&&s.push(a);}return s}a(W,"classDependencies");function K(i){return typeof i=="function"?W(i):"useClass"in i?W(d(i.useClass)):"useFactory"in i?(i.inject??[]).map(e=>d(e)):"useExisting"in i?[d(i.useExisting)]:[]}a(K,"providerDependencies");function ee(i,e,t,n){var o=arguments.length,s=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(i,e,t,n);else for(var a=i.length-1;a>=0;a--)(r=i[a])&&(s=(o<3?r(s):o>3?r(e,t,s):r(e,t))||s);return o>3&&s&&Object.defineProperty(e,t,s),s}a(ee,"_ts_decorate");function Y(i,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(i,e)}a(Y,"_ts_metadata");var y=class{static{a(this,"EventEmitter2");}handlers=new Map;pending=new Map;onError;constructor(){this.onError=te;}setOptions(e){e.onError&&(this.onError=e.onError);}subscribe(e,t,n){let o=this.handlers.get(e)??[];o.push({instance:n?.instance??{},methodName:n?.methodName??"anonymous",handler:t}),this.handlers.set(e,o);}registerHandler(e,t,n){let o=t[n].bind(t);this.subscribe(e,o,{instance:t,methodName:n});}async emit(e){let t=this.handlers.get(e.type);if(!t||t.length===0)return;let n=this.executeHandlers(t,e);this.pending.set(n,e.type);try{await n;}finally{this.pending.delete(n);}}emitAsync(e){let t=this.handlers.get(e.type);if(!t||t.length===0)return Promise.resolve([]);let n=this.executeHandlers(t,e).then(o=>(this.pending.delete(n),o),()=>(this.pending.delete(n),[]));return this.pending.set(n,e.type),n}async waitForAllDone(...e){for(;;){let t=this.getPending(e);if(t.length===0)break;await Promise.allSettled(t);}}getPending(e){if(e.length===0)return [...this.pending.keys()];let t=[];for(let[n,o]of this.pending)e.includes(o)&&t.push(n);return t}hasHandlers(e){let t=this.handlers.get(e);return t!==void 0&&t.length>0}handlerCount(e){return this.handlers.get(e)?.length??0}clear(){this.handlers.clear();}async executeHandlers(e,t){return (await Promise.allSettled(e.map(async o=>{let s=Date.now();try{return {value:await o.handler(t),durationMs:Date.now()-s}}catch(r){return {err:r,durationMs:Date.now()-s,threw:true}}}))).map((o,s)=>{let r=e[s],a=`${r.instance.constructor?.name??"Unknown"}.${r.methodName}`;if(o.status==="fulfilled"&&!("threw"in o.value))return {name:a,status:"success",value:o.value.value,durationMs:o.value.durationMs};let f=o.status==="fulfilled"?o.value.err:o.reason,m=f instanceof Error?f.message:typeof f=="string"?f:String(f),l=o.status==="fulfilled"?o.value.durationMs:0;return this.onError(f,t.type,a),{name:a,status:"failed",error:m,durationMs:l}})}};y=ee([e(),Y("design:type",Function),Y("design:paramtypes",[])],y);function te(i,e,t){console.error(`[EventEmitter2] Handler "${t}" failed for event "${e}":`,i);}a(te,"defaultErrorHandler");var C=Symbol.for("truxie:on-event");function Ve(i){return (e,t,n)=>{let o=Reflect.getOwnMetadata(C,e.constructor)??[];o.push({eventType:i,methodName:String(t)}),Reflect.defineMetadata(C,o,e.constructor);}}a(Ve,"OnEvent");function B(i){return Reflect.getOwnMetadata(C,i)??[]}a(B,"getOnEventMetadata");async function Be(i,e){let t=await i.resolve(y);for(let n of e){let o=oe(n);if(!o)continue;let s=B(o);if(s.length===0)continue;let r=typeof n=="function"?n:n.provide,a;try{a=await i.resolve(r);}catch{continue}for(let f of s)typeof a[f.methodName]=="function"&&t.registerHandler(f.eventType,a,f.methodName);}}a(Be,"scanEventHandlers");function oe(i){return typeof i=="function"?h(i)?i:null:"useClass"in i?i.useClass:null}a(oe,"getProviderClass");export{S as a,F as b,_ as c,ye as d,we as e,Ee as f,xe as g,Me as h,be as i,Te as j,Re as k,V as l,Se as m,Oe as n,Pe as o,z as p,y as q,Ve as r,Be as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';var l=Symbol.for("truxie:ws:gateway"),f=Symbol.for("truxie:ws:message"),d=Symbol.for("truxie:ws:params"),x=Symbol.for("truxie:ws:guards"),g=Symbol.for("truxie:ws:server");function w(e){return n=>{let o=typeof e=="string"?{path:e}:e??{},a={path:o.path??"/",namespace:o.namespace??"/",target:n};Reflect.defineMetadata(l,a,n);}}a(w,"WebSocketGateway");function p(e){return (n,o,a)=>{let s=n.constructor,r=Reflect.getOwnMetadata(f,s)??[];Reflect.defineMetadata(f,[...r,{event:e,methodName:String(o)}],s);}}a(p,"SubscribeMessage");function M(){return (e,n)=>{let o=e.constructor,a=Reflect.getOwnMetadata(g,o)??[];Reflect.defineMetadata(g,[...a,String(n)],o);}}a(M,"WebSocketServer");function i(e,n){return (o,a,s)=>{if(a===void 0)return;let r=o[a];if(typeof r!="function")return;let c=r[d]??[];r[d]=[...c,{type:e,index:s,extractor:n}];}}a(i,"buildWsParamDecorator");var b=a(()=>i("message-body"),"MessageBody"),R=a(()=>i("connected-socket"),"ConnectedSocket"),W=a(()=>i("ws-auth"),"WsAuth");function y(e){return ()=>i("custom",e)}a(y,"createWsParamDecorator");function A(...e){return n=>{let o=Reflect.getOwnMetadata(x,n)??[];Reflect.defineMetadata(x,[...o,...e],n);}}a(A,"WsGuards");function h(e){return Reflect.getOwnMetadata(l,e)}a(h,"getGatewayMetadata");function k(e){return Reflect.getOwnMetadata(f,e)??[]}a(k,"getMessageHandlers");function _(e){return e[d]??[]}a(_,"getWsParams");function E(e){return Reflect.getOwnMetadata(x,e)??[]}a(E,"getWsGuards");function G(e){return Reflect.getOwnMetadata(g,e)??[]}a(G,"getWsServerProperties");function D(e,n,o,a){if(e.length===0)return [];let s=Math.max(...e.map(c=>c.index)),r=new Array(s+1).fill(void 0);for(let{type:c,index:u,extractor:S}of e)switch(c){case "message-body":r[u]=a;break;case "connected-socket":r[u]=n;break;case "ws-auth":r[u]=n.context.auth;break;case "custom":r[u]=S?S(n,o):void 0;break}return r}a(D,"resolveWsArgs");export{w as a,p as b,M as c,b as d,R as e,W as f,y as g,A as h,h as i,k as j,_ as k,E as l,G as m,D as n};
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { C as Container, E as EventBusOptions, a as EventEmitter2 } from './even
|
|
|
2
2
|
export { D as DomainEvent, b as EventHandler } from './event-bus-CaQGBKG0.js';
|
|
3
3
|
import { T as Token, F as ForwardRef, I as InjectableOptions, a as Type, M as ModuleMetadata, D as DynamicModule, P as Provider, b as ModuleAsyncOptions, c as InjectionToken } from './types-BonRQLDb.js';
|
|
4
4
|
export { C as ClassProvider, E as ExistingProvider, d as FactoryProvider, e as ModuleOptionsFactory, S as Scope, V as ValueProvider } from './types-BonRQLDb.js';
|
|
5
|
-
import { W as WsPeer, a as WsMessage } from './types-
|
|
5
|
+
import { W as WsPeer, a as WsMessage } from './types-BHt3a4dp.js';
|
|
6
6
|
|
|
7
7
|
declare function Injectable(options?: InjectableOptions): ClassDecorator;
|
|
8
8
|
/**
|
|
@@ -92,11 +92,14 @@ declare class ModuleRegistry {
|
|
|
92
92
|
*/
|
|
93
93
|
private validateExports;
|
|
94
94
|
/**
|
|
95
|
-
* Validate that
|
|
96
|
-
*
|
|
95
|
+
* Validate that every dependency of every provider (class `@Inject(...)`, parameter `@Inject(token)`,
|
|
96
|
+
* `useClass`, `useFactory.inject`, `useExisting`) is visible to the module that declares it: its own
|
|
97
|
+
* providers, the exports of the modules it imports, a global module, or `alwaysVisible` — tokens the
|
|
98
|
+
* application registers itself outside every module (EventEmitter2, DiscoveryService).
|
|
99
|
+
* `@Optional()` parameters are skipped. Throws once, listing every violation.
|
|
97
100
|
* Call after scan() for strict visibility enforcement.
|
|
98
101
|
*/
|
|
99
|
-
validateVisibility(): void;
|
|
102
|
+
validateVisibility(alwaysVisible?: Iterable<Token>): void;
|
|
100
103
|
private getProviderToken;
|
|
101
104
|
private collectImportedExports;
|
|
102
105
|
/**
|
|
@@ -417,7 +420,10 @@ interface CreatePipelineOptions extends PipelineOptions {
|
|
|
417
420
|
declare function createPipeline(container: Container, globalOptions: PipelineOptions, localOptions: CreatePipelineOptions): (ctx: ExecutionContext) => Promise<unknown>;
|
|
418
421
|
|
|
419
422
|
declare function UseInterceptors(...interceptors: InterceptorRef[]): any;
|
|
420
|
-
/**
|
|
423
|
+
/**
|
|
424
|
+
* Class-level interceptors set via @UseInterceptors, including those declared
|
|
425
|
+
* on a base controller — routes are inherited, so their interceptors must be.
|
|
426
|
+
*/
|
|
421
427
|
declare function getInterceptorsMetadata(target: Function): InterceptorRef[];
|
|
422
428
|
/** Method-level interceptors set via @UseInterceptors on a specific method. */
|
|
423
429
|
declare function getMethodInterceptors(target: Function, methodName: string): InterceptorRef[];
|
|
@@ -528,7 +534,10 @@ declare class UnitOfWorkInterceptor implements Interceptor {
|
|
|
528
534
|
* }
|
|
529
535
|
*/
|
|
530
536
|
declare function UseMiddleware(...middlewares: MiddlewareRef[]): any;
|
|
531
|
-
/**
|
|
537
|
+
/**
|
|
538
|
+
* Class-level middlewares set via @UseMiddleware, including those declared on
|
|
539
|
+
* a base controller — routes are inherited, so their middleware must be too.
|
|
540
|
+
*/
|
|
532
541
|
declare function getMiddlewaresMetadata(target: Function): MiddlewareRef[];
|
|
533
542
|
/** Method-level middlewares set via @UseMiddleware on a specific method. */
|
|
534
543
|
declare function getMethodMiddlewares(target: Function, methodName: string): MiddlewareRef[];
|
|
@@ -640,6 +649,31 @@ declare class RequestAbortedError extends AppError {
|
|
|
640
649
|
constructor(message?: string);
|
|
641
650
|
}
|
|
642
651
|
|
|
652
|
+
/**
|
|
653
|
+
* Reduce an arbitrary thrown value to a `{ status, message }` pair that is
|
|
654
|
+
* safe to hand to an HTTP client.
|
|
655
|
+
*
|
|
656
|
+
* The adapters are the de-facto default error handler: core ships no global
|
|
657
|
+
* exception filter, and `handleError` rethrows when no registered filter
|
|
658
|
+
* matches. Copying `err.message` straight into the response body therefore
|
|
659
|
+
* published whatever a driver happened to put there — `E11000 duplicate key
|
|
660
|
+
* error collection: acme_prod.users index: email_1`, `connect ECONNREFUSED
|
|
661
|
+
* 10.0.4.12:5432`, absolute paths out of MODULE_NOT_FOUND — to any caller who
|
|
662
|
+
* could provoke a 500.
|
|
663
|
+
*
|
|
664
|
+
* An `AppError` message is written for the caller, so it passes through
|
|
665
|
+
* unchanged. Anything else collapses to a constant; log the original
|
|
666
|
+
* server-side if you want it.
|
|
667
|
+
*
|
|
668
|
+
* Detection is duck-typed rather than `instanceof AppError` on purpose: a dual
|
|
669
|
+
* CJS/ESM resolution can hand a consumer two copies of the class, and an
|
|
670
|
+
* identity check would then silently start masking real application messages.
|
|
671
|
+
*/
|
|
672
|
+
declare function clientSafeError(err: unknown): {
|
|
673
|
+
status: number;
|
|
674
|
+
message: string;
|
|
675
|
+
};
|
|
676
|
+
|
|
643
677
|
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
|
644
678
|
interface RouteMetadata {
|
|
645
679
|
method: HttpMethod;
|
|
@@ -901,6 +935,22 @@ interface ApiResponseDoc {
|
|
|
901
935
|
schema?: unknown;
|
|
902
936
|
description?: string;
|
|
903
937
|
example?: unknown;
|
|
938
|
+
/**
|
|
939
|
+
* The media type the body is served as. Defaults to `application/json`.
|
|
940
|
+
*
|
|
941
|
+
* `schema` still applies to a non-JSON body — `{type: 'string'}` is an honest
|
|
942
|
+
* description of a CSV export or an HTML page, and it is what an OpenAPI UI
|
|
943
|
+
* needs to stop offering to pretty-print one as JSON.
|
|
944
|
+
*/
|
|
945
|
+
contentType?: string;
|
|
946
|
+
/** Response headers worth knowing about — a `Location`, a rate-limit budget, a `Content-Disposition`. */
|
|
947
|
+
headers?: Record<string, ApiHeaderDoc>;
|
|
948
|
+
}
|
|
949
|
+
/** One documented response header. */
|
|
950
|
+
interface ApiHeaderDoc {
|
|
951
|
+
description?: string;
|
|
952
|
+
/** Zod or JSON Schema, converted like any other response schema. Defaults to a string. */
|
|
953
|
+
schema?: unknown;
|
|
904
954
|
}
|
|
905
955
|
/**
|
|
906
956
|
* A failure this endpoint is known to produce.
|
|
@@ -915,7 +965,43 @@ interface ApiErrorDoc {
|
|
|
915
965
|
when: string;
|
|
916
966
|
/** What the caller should do instead. "read the existing user; do not retry" */
|
|
917
967
|
then?: string;
|
|
968
|
+
/** The JSON body of the error, when it carries more than a status — a list of field errors, a retry hint. */
|
|
969
|
+
schema?: unknown;
|
|
970
|
+
example?: unknown;
|
|
918
971
|
}
|
|
972
|
+
/**
|
|
973
|
+
* The input of a handler that validates by hand.
|
|
974
|
+
*
|
|
975
|
+
* The schema a param decorator records is always the better source, because it
|
|
976
|
+
* is the one that actually runs: a handler built on `ZodValidatedQuery(schema)`
|
|
977
|
+
* cannot accept what its schema refuses. But plenty of handlers read
|
|
978
|
+
* `@Query('from')` and `@Query('to')` and check them in code, and for those the
|
|
979
|
+
* only thing the route table knows is WHICH keys are read — not their types,
|
|
980
|
+
* not which are required, not what they mean. This is where that is written
|
|
981
|
+
* down.
|
|
982
|
+
*
|
|
983
|
+
* It is a second source of truth, and second sources drift. `routeInputDrift()`
|
|
984
|
+
* compares it against the keys the handler actually plucks, so a test can fail
|
|
985
|
+
* the day the two disagree instead of a reader finding out from a 400.
|
|
986
|
+
*/
|
|
987
|
+
interface ApiRequestDoc {
|
|
988
|
+
/** Schema (Zod or JSON Schema) of the path params. */
|
|
989
|
+
params?: unknown;
|
|
990
|
+
/** Schema of the query object. */
|
|
991
|
+
query?: unknown;
|
|
992
|
+
/** Schema of the body. */
|
|
993
|
+
body?: unknown;
|
|
994
|
+
/** Body media type(s). Default `'application/json'`. */
|
|
995
|
+
contentType?: string | string[];
|
|
996
|
+
/** Whether a body is required. Default true when `body` is given. */
|
|
997
|
+
bodyRequired?: boolean;
|
|
998
|
+
}
|
|
999
|
+
/**
|
|
1000
|
+
* One way of satisfying a route's authentication: scheme name → scopes, all of
|
|
1001
|
+
* them required together. A list of these is a list of ALTERNATIVES — the
|
|
1002
|
+
* shape of an OpenAPI `security` block.
|
|
1003
|
+
*/
|
|
1004
|
+
type ApiSecurityRequirement = Record<string, string[]>;
|
|
919
1005
|
/** A worked example of calling the endpoint. */
|
|
920
1006
|
interface ApiExampleDoc {
|
|
921
1007
|
summary?: string;
|
|
@@ -948,6 +1034,21 @@ interface ApiDocOptions {
|
|
|
948
1034
|
errors?: ApiErrorDoc[];
|
|
949
1035
|
/** Worked examples. One realistic example beats a schema for getting a first call right. */
|
|
950
1036
|
examples?: ApiExampleDoc[];
|
|
1037
|
+
/**
|
|
1038
|
+
* The input, for a handler that validates by hand. Ignored for any part a
|
|
1039
|
+
* param decorator already recorded a schema for — see `ApiRequestDoc`.
|
|
1040
|
+
*/
|
|
1041
|
+
request?: ApiRequestDoc;
|
|
1042
|
+
/**
|
|
1043
|
+
* How a caller authenticates, overriding whatever the renderer derived from
|
|
1044
|
+
* the guards. `[]` means explicitly public.
|
|
1045
|
+
*
|
|
1046
|
+
* For the routes guards cannot describe: a webhook authenticated by a
|
|
1047
|
+
* signature in a header, a callback whose token lives in the path. Without
|
|
1048
|
+
* this they either inherit a bearer requirement nobody can meet or say
|
|
1049
|
+
* nothing at all, and both mislead.
|
|
1050
|
+
*/
|
|
1051
|
+
security?: ApiSecurityRequirement[];
|
|
951
1052
|
/**
|
|
952
1053
|
* Endpoints this one relates to — where an identifier it takes comes from,
|
|
953
1054
|
* what usually follows it. Written as `"GET /api/users"`.
|
|
@@ -976,10 +1077,12 @@ interface ApiDocOptions {
|
|
|
976
1077
|
* an endpoint is reachable by an agent — otherwise documenting a route would
|
|
977
1078
|
* quietly publish it, which is exactly the default worth avoiding.
|
|
978
1079
|
*
|
|
979
|
-
*
|
|
980
|
-
*
|
|
981
|
-
*
|
|
982
|
-
*
|
|
1080
|
+
* Per-parameter types belong in the schema the handler validates with, and a
|
|
1081
|
+
* route built on a schema-carrying decorator needs nothing more. `request`
|
|
1082
|
+
* exists for the handler that validates by hand — it is a second source of
|
|
1083
|
+
* truth, so it loses to a recorded schema wherever both exist, and
|
|
1084
|
+
* `routeInputDrift()` is there to catch it drifting from the keys the handler
|
|
1085
|
+
* actually reads.
|
|
983
1086
|
*
|
|
984
1087
|
* @example
|
|
985
1088
|
* ```ts
|
|
@@ -1013,11 +1116,39 @@ declare function apiResponses(doc: ApiDocOptions | null | undefined): ApiRespons
|
|
|
1013
1116
|
|
|
1014
1117
|
/** A JSON Schema fragment. Passed through, never validated. */
|
|
1015
1118
|
type JsonSchemaObject = Record<string, unknown>;
|
|
1119
|
+
/**
|
|
1120
|
+
* Which side of a schema to describe.
|
|
1121
|
+
*
|
|
1122
|
+
* A schema is two contracts, not one: `z.number().default(1)` may be omitted
|
|
1123
|
+
* by the CALLER but is always present in what the server sends back, and a
|
|
1124
|
+
* transform accepts one shape and produces another. A request is described
|
|
1125
|
+
* from the input side, a response from the output side — describe a response
|
|
1126
|
+
* from the input side and every defaulted field reads as optional to a client
|
|
1127
|
+
* that will in fact always receive it.
|
|
1128
|
+
*/
|
|
1129
|
+
interface ToJsonSchemaOptions {
|
|
1130
|
+
io?: 'input' | 'output';
|
|
1131
|
+
}
|
|
1132
|
+
/**
|
|
1133
|
+
* Schema → JSON Schema. `zodToJsonSchema` from `@truxie/zod` is one.
|
|
1134
|
+
*
|
|
1135
|
+
* The second argument is optional so a one-argument converter written before
|
|
1136
|
+
* it existed still fits; such a converter just describes both sides the same
|
|
1137
|
+
* way, which is what everything did before.
|
|
1138
|
+
*/
|
|
1139
|
+
type ToJsonSchema = (schema: unknown, options?: ToJsonSchemaOptions) => JsonSchemaObject | null;
|
|
1016
1140
|
/** What a handler accepts, recovered from the decorators that already validate it. */
|
|
1017
1141
|
interface RouteInput {
|
|
1018
1142
|
params?: JsonSchemaObject;
|
|
1019
1143
|
query?: JsonSchemaObject;
|
|
1020
1144
|
body?: JsonSchemaObject;
|
|
1145
|
+
/**
|
|
1146
|
+
* The body's media types, when `@ApiDoc({request: {contentType}})` declared
|
|
1147
|
+
* them. Absent means the renderer's default, `application/json`.
|
|
1148
|
+
*/
|
|
1149
|
+
bodyContentTypes?: string[];
|
|
1150
|
+
/** Whether the body may be omitted, when `@ApiDoc({request: {bodyRequired}})` said so. */
|
|
1151
|
+
bodyRequired?: boolean;
|
|
1021
1152
|
}
|
|
1022
1153
|
interface DescribeRouteInputOptions {
|
|
1023
1154
|
/**
|
|
@@ -1025,7 +1156,7 @@ interface DescribeRouteInputOptions {
|
|
|
1025
1156
|
* `zodToJsonSchema` from `@truxie/zod`. Without it only the shapes that can
|
|
1026
1157
|
* be recovered from decorator KEYS are reported.
|
|
1027
1158
|
*/
|
|
1028
|
-
toJsonSchema?:
|
|
1159
|
+
toJsonSchema?: ToJsonSchema;
|
|
1029
1160
|
/** Hand-written override, when the handler validates by hand. */
|
|
1030
1161
|
bodySchema?: JsonSchemaObject;
|
|
1031
1162
|
/** Hand-written override. */
|
|
@@ -1038,8 +1169,52 @@ interface DescribeRouteInputOptions {
|
|
|
1038
1169
|
* catalog, a route dump — and all of them should read the SAME thing, which is
|
|
1039
1170
|
* the schema the handler already validates with. Where nothing was recorded it
|
|
1040
1171
|
* reports "an object" rather than inventing a shape.
|
|
1172
|
+
*
|
|
1173
|
+
* Per part, the first of these that exists wins:
|
|
1174
|
+
*
|
|
1175
|
+
* 1. an explicit override passed in `options` — the caller knows best;
|
|
1176
|
+
* 2. the schema a param decorator recorded — it is the one that actually
|
|
1177
|
+
* VALIDATES, so it cannot be wrong about what the handler accepts, while
|
|
1178
|
+
* anything written beside it can;
|
|
1179
|
+
* 3. `@ApiDoc({request})` — prose-adjacent documentation for a handler that
|
|
1180
|
+
* validates by hand, trusted only where nothing better exists;
|
|
1181
|
+
* 4. the keys `@Query('k')` / `@Body('k')` pluck — names without types;
|
|
1182
|
+
* 5. for a body, "an object of undeclared shape".
|
|
1041
1183
|
*/
|
|
1042
1184
|
declare function describeRouteInput(route: CompiledRoute, options?: DescribeRouteInputOptions): RouteInput;
|
|
1185
|
+
/**
|
|
1186
|
+
* Whether a value is already JSON Schema rather than a validator's schema that
|
|
1187
|
+
* needs converting. A Zod schema is an object too, so it is ruled out by its
|
|
1188
|
+
* internals before the keyword check.
|
|
1189
|
+
*/
|
|
1190
|
+
declare function isJsonSchemaObject(value: unknown): value is JsonSchemaObject;
|
|
1191
|
+
/** Keys one side knows about and the other does not. Both empty means no drift. */
|
|
1192
|
+
interface KeyDrift {
|
|
1193
|
+
/** Read by the handler, missing from `@ApiDoc({request})`. A caller cannot know to send them. */
|
|
1194
|
+
undocumented: string[];
|
|
1195
|
+
/** Documented, never read. A caller sends them and they are silently ignored. */
|
|
1196
|
+
unread: string[];
|
|
1197
|
+
}
|
|
1198
|
+
interface RouteInputDrift {
|
|
1199
|
+
query: KeyDrift;
|
|
1200
|
+
body: KeyDrift;
|
|
1201
|
+
}
|
|
1202
|
+
/**
|
|
1203
|
+
* Compare the keys `@ApiDoc({request})` documents with the keys the handler
|
|
1204
|
+
* actually plucks via `@Query('k')` / `@Body('k')`.
|
|
1205
|
+
*
|
|
1206
|
+
* `request` is a second source of truth, and a second source of truth drifts:
|
|
1207
|
+
* a handler gains a `?currency=` filter, nobody touches the decorator above it,
|
|
1208
|
+
* and the published spec quietly stops describing the endpoint. This is the
|
|
1209
|
+
* check a test runs to make that a failure instead of a surprise.
|
|
1210
|
+
*
|
|
1211
|
+
* Deliberately silent where it cannot know. A handler that takes the whole
|
|
1212
|
+
* `@Query()` object (or a schema-carrying decorator for that part) may read any
|
|
1213
|
+
* key at all, so nothing is reported for that part rather than a guess; the
|
|
1214
|
+
* same when nothing was documented, or the documented schema could not be
|
|
1215
|
+
* converted into something with properties.
|
|
1216
|
+
*/
|
|
1217
|
+
declare function routeInputDrift(route: CompiledRoute, options?: Pick<DescribeRouteInputOptions, 'toJsonSchema'>): RouteInputDrift;
|
|
1043
1218
|
|
|
1044
1219
|
/** Set by the application from `ApplicationOptions.trustProxy`. */
|
|
1045
1220
|
declare const TRUST_PROXY_KEY = "__trustProxy";
|
|
@@ -1274,4 +1449,4 @@ declare class TruxieFactory {
|
|
|
1274
1449
|
static create(rootModule: Type | DynamicModule, options?: ApplicationOptions): Promise<TruxieApplication>;
|
|
1275
1450
|
}
|
|
1276
1451
|
|
|
1277
|
-
export { ApiDoc, type ApiDocOptions, type ApiErrorDoc, type ApiExampleDoc, type ApiResponseDoc, AppError, type ApplicationOptions, Auth, type AuthExtractorFn, BaseExecutionContext, Body, Catch, type CompiledRoute, ConfigurableModuleBuilder, type ConfigurableModuleBuilderResult, type ConfigurableModuleClass, ConflictError, Container, Controller, ControllerRouter, Cookie, type CreatePipelineOptions, type CustomParamOptions, DefaultValuePipe, Delete, type DescribeRouteInputOptions, DiscoveryService, DynamicModule, EventBusOptions, EventEmitter2, type ExceptionFilter, type ExecutionContext, type ExtraOptions, type FeatureConfig, type FilterRef, ForbiddenError, FormData, type FormDataPart, ForwardRef, Get, Global, type GuardClass, type GuardInstance, type GuardRef, type HandlerFn, Headers, type HttpDispatchResult, type HttpMethod, type ICanActivateGuard, type IUseCase, Inject, Injectable, InjectableOptions, InjectionToken, type Interceptor, type InterceptorRef, Ip, type JsonSchemaObject, type Middleware, type MiddlewareRef, Module, ModuleAsyncOptions, ModuleMetadata, ModuleRegistry, NoGuard, NotFoundError, type OnApplicationBootstrap, type OnApplicationShutdown, OnEvent, type OnModuleDestroy, type OnModuleInit, Optional, Param, type ParamPipe, type ParamPipeRef, ParseIdPipe, ParseIntPipe, Patch, type PipeRef, type PipeTransform, type PipelineOptions, Post, Provider, Put, Query, REDIRECT_BRAND, REMOTE_ADDRESS_KEY, RawBody, type RedirectResult, RequestAbortedError, RouteGuards, type RouteInput, type RouteMatch, type RouteMetadata, type RouteParamMetadata, type RouteParamType, TRUST_PROXY_KEY, Token, TruxieApplication, TruxieFactory, Type, UOW_INSTANCE_KEY, UOW_SESSION_KEY, UnauthorizedError, type UnitOfWork, type UnitOfWorkFactory, UnitOfWorkInterceptor, UseFilters, UseInterceptors, UseMiddleware, UsePipes, UserAgent, ValidationError, type WsHooks, type WsHooksAdapters, apiResponses, applyJsonBody, clientIp, contributeApiDoc, createAsyncOptionsProviders, createParamDecorator, createPipeline, defineAuth, describeRouteInput, forwardRef, getApiDoc, getControllerGuards, getControllerPath, getEffectiveInterceptors, getEffectiveMiddlewares, getInterceptorsMetadata, getMethodGuards, getMethodInterceptors, getMethodMiddlewares, getMiddlewaresMetadata, getModuleMetadata, getRequestHeaders, getRouteMetadata, getRouteParams, isGlobalModule, isRedirect, isServerless, redirect, resolveForwardRef, resolveParamArgs };
|
|
1452
|
+
export { ApiDoc, type ApiDocOptions, type ApiErrorDoc, type ApiExampleDoc, type ApiHeaderDoc, type ApiRequestDoc, type ApiResponseDoc, type ApiSecurityRequirement, AppError, type ApplicationOptions, Auth, type AuthExtractorFn, BaseExecutionContext, Body, Catch, type CompiledRoute, ConfigurableModuleBuilder, type ConfigurableModuleBuilderResult, type ConfigurableModuleClass, ConflictError, Container, Controller, ControllerRouter, Cookie, type CreatePipelineOptions, type CustomParamOptions, DefaultValuePipe, Delete, type DescribeRouteInputOptions, DiscoveryService, DynamicModule, EventBusOptions, EventEmitter2, type ExceptionFilter, type ExecutionContext, type ExtraOptions, type FeatureConfig, type FilterRef, ForbiddenError, FormData, type FormDataPart, ForwardRef, Get, Global, type GuardClass, type GuardInstance, type GuardRef, type HandlerFn, Headers, type HttpDispatchResult, type HttpMethod, type ICanActivateGuard, type IUseCase, Inject, Injectable, InjectableOptions, InjectionToken, type Interceptor, type InterceptorRef, Ip, type JsonSchemaObject, type KeyDrift, type Middleware, type MiddlewareRef, Module, ModuleAsyncOptions, ModuleMetadata, ModuleRegistry, NoGuard, NotFoundError, type OnApplicationBootstrap, type OnApplicationShutdown, OnEvent, type OnModuleDestroy, type OnModuleInit, Optional, Param, type ParamPipe, type ParamPipeRef, ParseIdPipe, ParseIntPipe, Patch, type PipeRef, type PipeTransform, type PipelineOptions, Post, Provider, Put, Query, REDIRECT_BRAND, REMOTE_ADDRESS_KEY, RawBody, type RedirectResult, RequestAbortedError, RouteGuards, type RouteInput, type RouteInputDrift, type RouteMatch, type RouteMetadata, type RouteParamMetadata, type RouteParamType, TRUST_PROXY_KEY, type ToJsonSchema, type ToJsonSchemaOptions, Token, TruxieApplication, TruxieFactory, Type, UOW_INSTANCE_KEY, UOW_SESSION_KEY, UnauthorizedError, type UnitOfWork, type UnitOfWorkFactory, UnitOfWorkInterceptor, UseFilters, UseInterceptors, UseMiddleware, UsePipes, UserAgent, ValidationError, type WsHooks, type WsHooksAdapters, apiResponses, applyJsonBody, clientIp, clientSafeError, contributeApiDoc, createAsyncOptionsProviders, createParamDecorator, createPipeline, defineAuth, describeRouteInput, forwardRef, getApiDoc, getControllerGuards, getControllerPath, getEffectiveInterceptors, getEffectiveMiddlewares, getInterceptorsMetadata, getMethodGuards, getMethodInterceptors, getMethodMiddlewares, getMiddlewaresMetadata, getModuleMetadata, getRequestHeaders, getRouteMetadata, getRouteParams, isGlobalModule, isJsonSchemaObject, isRedirect, isServerless, redirect, resolveForwardRef, resolveParamArgs, routeInputDrift };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {k,m as m$1,n,b as b$2,o,p,r}from'./chunk-RXJTN5BJ.js';export{b as Container,c as Controller,g as Delete,p as EventEmitter2,d as Get,o as ModuleRegistry,j as NoGuard,q as OnEvent,h as Patch,e as Post,f as Put,i as RouteGuards,l as getControllerGuards,k as getControllerPath,n as getMethodGuards,m as getRouteMetadata}from'./chunk-RXJTN5BJ.js';import {n as n$1,i,j as j$1,k as k$1,m as m$2}from'./chunk-42ZAPMNO.js';import {b as b$1,p as p$1,i as i$1,j as j$2}from'./chunk-TSJZVSHP.js';export{p as DiscoveryService,m as Global,f as Inject,e as Injectable,b as InjectionToken,l as Module,g as Optional,a as Scope,c as forwardRef,n as getModuleMetadata,o as isGlobalModule,d as resolveForwardRef}from'./chunk-TSJZVSHP.js';import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';function re(t,e){if("useFactory"in e&&e.useFactory){let r=e.useFactory;return [{provide:t,useFactory:r,inject:e.inject??[]}]}if("useClass"in e&&e.useClass){let r=e.useClass;return [{provide:t,useFactory:a(async o=>o.createModuleOptions(),"useFactory"),inject:[r]},r]}if("useExisting"in e&&e.useExisting){let r=e.useExisting;return [{provide:t,useFactory:a(async o=>o.createModuleOptions(),"useFactory"),inject:[r]}]}throw new Error("ModuleAsyncOptions must specify one of: useFactory, useClass, or useExisting")}a(re,"createAsyncOptionsProviders");var U=class{static{a(this,"ConfigurableModuleBuilder");}description;featureDescription;onForRoot;onForFeature;constructor(e="MODULE_OPTIONS"){this.description=e,this.featureDescription=e+"_FEATURE";}setTokenDescription(e){return this.description=e,this}transformDynamicModule(e){return this.onForRoot=e,this}transformFeatureModule(e){return this.onForFeature=e,this}build(){let e=new b$1(this.description),r=new b$1(this.featureDescription),o=this.onForRoot,s=this.onForFeature;return {ConfigurableModuleClass:class{static{a(this,"ConfigurableModuleClassImpl");}static forRoot(c,l={}){let u={module:this,global:l.global??false,providers:[{provide:e,useValue:c}],exports:[e]};return o&&(u=o(u,c)),u}static forRootAsync(c){let l=re(e,c),u={module:this,imports:c.imports??[],providers:l,exports:[e]};return o&&(u=o(u)),u}static forFeature(c,l={}){let u={module:this,global:l.global??false,providers:[{provide:r,useValue:c}],exports:[r]};return s&&(u=s(u,c)),u}},MODULE_OPTIONS_TOKEN:e,MODULE_FEATURE_TOKEN:r}}};var $=class{static{a(this,"BaseExecutionContext");}nativeRequest;handler;container;query;params;body;bodyParseError;rawBody;formData;auth;data=new Map;metadata=new Map;abortController;constructor(e,r,o,s={},a={},i){this.nativeRequest=e,this.handler=r,this.container=o,this.query=s,this.params=a,this.abortController=i??new AbortController;}getNativeRequest(){return this.nativeRequest}getHandler(){return this.handler}setHandler(e){this.handler=e;}getBody(){return this.body}setBody(e){this.body=e;}getRawBody(){return this.rawBody}setRawBody(e){this.rawBody=e;}getBodyParseError(){return this.bodyParseError}setBodyParseError(e){this.bodyParseError=e;}getFormData(){return this.formData}setFormData(e){this.formData=e;}getQuery(){return this.query}getParams(){return this.params}getAuth(){return this.auth}setAuth(e){this.auth=e;}getMetadata(e){return this.metadata.get(e)}setMetadata(e,r){this.metadata.set(e,r);}getData(e){return this.data.get(e)}setData(e,r){this.data.set(e,r);}getContainer(){return this.container}setContainer(e){this.container=e;}getSignal(){return this.abortController.signal}abort(e){this.abortController.abort(e);}};function Xe(t,e,r=""){if(e!=="")try{t.setBody(JSON.parse(e));}catch(o){It(e,r)&&t.setBodyParseError(o instanceof Error?o:new Error(String(o)));}}a(Xe,"applyJsonBody");function It(t,e){if(e.toLowerCase().includes("json"))return true;let r=t.trimStart().charAt(0);return r==="{"||r==="["}a(It,"looksLikeJson");var oe=Symbol.for("truxie:filters"),Ze=Symbol.for("truxie:catch");function et(...t){return (e,r,o)=>{let s=r?e.constructor:e,a=Reflect.getOwnMetadata(oe,s)??[];Reflect.defineMetadata(oe,[...a,...t],s);}}a(et,"UseFilters");function tt(...t){return e=>{Reflect.defineMetadata(Ze,t,e);}}a(tt,"Catch");function ne(t){return Reflect.getOwnMetadata(oe,t)??[]}a(ne,"getFiltersMetadata");function se(t){return Reflect.getOwnMetadata(Ze,t)??[]}a(se,"getCatchMetadata");var h=class extends Error{static{a(this,"AppError");}statusCode;status;isOperational;constructor(e,r){super(e),this.statusCode=r,this.status=r>=400&&r<500?"fail":"error",this.isOperational=true,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace(this,this.constructor);}},G=class extends h{static{a(this,"NotFoundError");}constructor(e="Resource not found"){super(e,404);}},m=class extends h{static{a(this,"ValidationError");}errors;constructor(e="Validation failed",r){super(e,400),this.errors=r;}},q=class extends h{static{a(this,"UnauthorizedError");}constructor(e="Not authorized"){super(e,401);}},R=class extends h{static{a(this,"ForbiddenError");}constructor(e="Access forbidden"){super(e,403);}},j=class extends h{static{a(this,"ConflictError");}constructor(e="Resource conflict"){super(e,409);}},M=class extends h{static{a(this,"RequestAbortedError");}constructor(e="Request aborted by client"){super(e,499);}};function S(t,e,r){return async o=>{let s=[...e.middlewares??[],...r.middlewares??[]],a$1=[...e.guards??[],...r.guards??[]],i=[...e.interceptors??[],...r.interceptors??[]],c=[...e.pipes??[],...r.pipes??[]],l=[...e.filters??[],...r.filters??[]],u=await I(t,l);try{w(o);let d=await I(t,s);return await St(o,d,async()=>{w(o);let f=await I(t,a$1);for(let A of f)if(w(o),!await A.canActivate(o))throw new R("Access denied by guard");w(o);let y=await I(t,c);for(let A of y)w(o),await A.transform(o);w(o);let p=await I(t,i),Me=a(async()=>(w(o),r.handler(o)),"handlerCall");return p.length===0?Me():p.reduceRight((A,be)=>async()=>(w(o),be.intercept(o,A)),Me)()})}catch(d){return _t(d,o,u)}}}a(S,"createPipeline");async function St(t,e,r){return e.length===0?r():e.reduceRight((s,a)=>()=>a.use(t,s),r)()}a(St,"runMiddlewareChain");function w(t){if(t.getSignal().aborted)throw new M}a(w,"checkAborted");async function _t(t,e,r){for(let o of r){let s=se(o.constructor);if(s.length===0||t instanceof Error&&s.some(i=>t instanceof i))return o.catch(t,e)}throw t}a(_t,"handleError");async function I(t,e){let r=[];for(let o of e){if(typeof o!="function"){r.push(o);continue}let s=o;if(t.has(s)){r.push(await t.resolve(s));continue}if(Nt(s))throw new Error(`${s.name} declares constructor dependencies but is not registered as a provider, so they cannot be injected. Add it to a module's \`providers\`, or read what it needs off the ExecutionContext instead (\`ctx.getContainer().resolve(...)\`).`);r.push(new s);}return r}a(I,"resolveRefs");function Nt(t){return i$1(t).length>0||j$2(t).size>0?true:(Reflect.getMetadata?.("design:paramtypes",t)??[]).length>0}a(Nt,"declaresDependencies");var ie=Symbol.for("truxie:interceptors"),ae=Symbol.for("truxie:method:interceptors");function rt(...t){return (e,r,o)=>{if(r!==void 0){let a=o?.value??e,i=a[ae]??[];return a[ae]=[...i,...t],o}let s=Reflect.getOwnMetadata(ie,e)??[];Reflect.defineMetadata(ie,[...s,...t],e);}}a(rt,"UseInterceptors");function ce(t){return Reflect.getOwnMetadata(ie,t)??[]}a(ce,"getInterceptorsMetadata");function ue(t,e){let o=t.prototype?.[e];return typeof o=="function"&&o[ae]||[]}a(ue,"getMethodInterceptors");function z(t,e){return [...ce(t),...ue(t,e)]}a(z,"getEffectiveInterceptors");var de="uow:session",le="uow:instance",W=class{static{a(this,"UnitOfWorkInterceptor");}factory;constructor(e){this.factory=e;}async intercept(e,r){let o=this.factory();await o.start(),e.setData(de,o.getContext()),e.setData(le,o);try{let s=await r();return await o.commit(),s}catch(s){throw await o.rollback(),s}}};var fe=Symbol.for("truxie:middlewares"),pe=Symbol.for("truxie:method:middlewares");function ot(...t){return (e,r,o)=>{if(r!==void 0){let a=o?.value??e,i=a[pe]??[];return a[pe]=[...i,...t],o}let s=Reflect.getOwnMetadata(fe,e)??[];Reflect.defineMetadata(fe,[...s,...t],e);}}a(ot,"UseMiddleware");function he(t){return Reflect.getOwnMetadata(fe,t)??[]}a(he,"getMiddlewaresMetadata");function me(t,e){let o=t.prototype?.[e];return typeof o=="function"&&o[pe]||[]}a(me,"getMethodMiddlewares");function H(t,e){return [...he(t),...me(t,e)]}a(H,"getEffectiveMiddlewares");var ge=Symbol.for("truxie:pipes");function nt(...t){return (e,r,o)=>{let s=r?e.constructor:e,a=Reflect.getOwnMetadata(ge,s)??[];Reflect.defineMetadata(ge,[...a,...t],s);}}a(nt,"UsePipes");function ye(t){return Reflect.getOwnMetadata(ge,t)??[]}a(ye,"getPipesMetadata");var Tt=/^[0-9a-fA-F]{24}$/,Y=class{static{a(this,"ParseIdPipe");}paramName;constructor(e="id"){this.paramName=e;}transform(e){let o=e.getParams()[this.paramName];if(!o||!Tt.test(o))throw new m(`Invalid ${this.paramName}: must be a valid ObjectId`)}};var L=class{static{a(this,"ParseIntPipe");}transform(e){let r=Number(e);if(!Number.isInteger(r)||e===""||e===null||e===void 0)throw new m(`Expected an integer, received: ${JSON.stringify(e)}`);return r}};function st(t){return {transform(e){return e??t}}}a(st,"DefaultValuePipe");var K=class{static{a(this,"DomainEvent");}payload;timestamp;constructor(e){this.payload=e,this.timestamp=Date.now();}};var x=class{static{a(this,"ControllerRouter");}routes=[];globalPrefix;constructor(e=""){this.globalPrefix=e;}register(...e){for(let r of e){let o=k(r)??"",s=m$1(r);for(let a of s){let i=it(`${this.globalPrefix}/${o}/${a.path}`);kt(i,r.name,a.methodName),this.checkDuplicate(i,a.method,r.name,a.methodName);let{pattern:c,paramNames:l}=at(i),u=n(r,a.methodName),d=z(r,a.methodName),f=H(r,a.methodName);this.routes.push({method:a.method,pattern:c,paramNames:l,controllerClass:r,methodName:a.methodName,guardClasses:u,interceptorRefs:d,middlewareRefs:f,pipeRefs:ye(r),filterRefs:ne(r),rawPath:i});}}this.routes.sort((r,o)=>ct(r.rawPath)-ct(o.rawPath));}checkDuplicate(e,r,o,s){let{pattern:a}=at(e),i=this.routes.find(c=>c.method===r&&c.pattern.source===a.source);if(i){let c=i.rawPath===e?e:`${i.rawPath} / ${e}`;throw new Error(`Duplicate route: ${r} ${c}
|
|
2
|
-
Already registered by: ${
|
|
3
|
-
Conflicting with: ${o}.${s}`)}}match(e,r){let o=e.toUpperCase(),s=it(r);for(let a of this.routes){if(a.method!==o)continue;let i=a.pattern.exec(s);if(!i)continue;let c={};for(let l=0;l<a.paramNames.length;l++)c[a.paramNames[l]]=i[l+1]??"";return {route:a,params:c}}return null}getRoutes(){return this.routes}};function it(t){return "/"+t.replace(/\/+/g,"/").replace(/^\/|\/$/g,"")}a(it,"normalizePath");function at(t){let e=[],r=t.split("/").map(o=>o.startsWith(":")?(e.push(o.slice(1)),"([^/]+)"):Ot(o)).join("/");return {pattern:new RegExp(`^${r}$`),paramNames:e}}a(at,"compilePath");function Ot(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(Ot,"escapeRegex");function ct(t){return t.split("/").filter(Boolean).reduce((e,r)=>e+(r.startsWith(":")?1:0),0)}a(ct,"routePriority");function kt(t,e,r){let o=`Invalid path "${t}" on ${e}.${r}:`;if(!t.startsWith("/"))throw new Error(`${o} must start with /`);let s=t.split("/").filter((i,c)=>c>0),a=new Set;for(let i of s){if(i==="")throw new Error(`${o} contains empty segment (double slash)`);if(i.startsWith(":")){let c=i.slice(1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c))throw new Error(`${o} invalid param name ":${c}" \u2014 must be a valid identifier`);if(a.has(c))throw new Error(`${o} duplicate param name ":${c}"`);a.add(c);}}}a(kt,"validatePath");var _="__trustProxy",we="__remoteAddress";function ut(t){return b(t.getNativeRequest())}a(ut,"getRequestHeaders");function b(t){let e=t?.node?.req?.headers;if(e&&typeof e=="object")return e;let r=t?.headers;return r&&typeof r.entries=="function"?Object.fromEntries(r.entries()):r&&typeof r=="object"?r:{}}a(b,"headersOf");function V(t){let e=Ft(t);if(t.getData(_)!==true)return e;let r=b(t.getNativeRequest()),o=r["cf-connecting-ip"];if(o)return String(o).trim();let s=r["x-forwarded-for"];if(s){let i=String(s).split(",")[0]?.trim();if(i)return i}let a=r["x-real-ip"];return a?String(a).trim():e}a(V,"clientIp");function Ft(t){let e=t.getData(we);if(e)return e;let r=t.getNativeRequest();return r?.node?.req?.socket?.remoteAddress??r?.socket?.remoteAddress??""}a(Ft,"directAddress");var E=Symbol.for("truxie:route:params");function Bt(t){return t==null?false:typeof t=="function"||typeof t=="object"&&typeof t.transform=="function"}a(Bt,"isParamPipeRef");function J(t,e){return Bt(t)?{key:void 0,pipes:[t,...e??[]]}:{key:t,pipes:e??[]}}a(J,"resolveArgs");function g(t,e,r=[]){return (o,s,a)=>{if(s===void 0)return;let i=o[s];if(typeof i!="function")return;let c=i[E]??[];i[E]=[...c,{index:a,type:t,key:e,pipes:r.length>0?r:void 0}];}}a(g,"buildBuiltinDecorator");function Ut(t){return typeof t=="function"?new t:t}a(Ut,"resolveParamPipe");function dt(t,...e){let{key:r,pipes:o}=J(t,e);return g("query",r,o)}a(dt,"Query");function lt(t,...e){let{key:r,pipes:o}=J(t,e);return g("param",r,o)}a(lt,"Param");function ft(t,...e){let{key:r,pipes:o}=J(t,e);return g("body",r,o)}a(ft,"Body");var pt=a(()=>g("rawBody"),"RawBody"),ht=a(()=>g("formData"),"FormData"),mt=a(()=>g("ip"),"Ip"),gt=a(()=>g("userAgent"),"UserAgent"),yt=a(t=>g("cookie",t),"Cookie");function wt(t,...e){let{key:r,pipes:o}=J(t,e);return g("headers",r,o)}a(wt,"Headers");function xe(t){return ()=>(e,r,o)=>{if(r===void 0)return;let s=e[r];if(typeof s!="function")return;let a=s[E]??[];s[E]=[...a,{index:o,type:"auth",extractor:t}];}}a(xe,"defineAuth");var xt=xe();function Et(t,e){return ()=>(r,o,s)=>{if(o===void 0)return;let a=r[o];if(typeof a!="function")return;let i=a[E]??[];a[E]=[...i,{index:s,type:"custom",extractor:t,schema:e?.schema,source:e?.source}];}}a(Et,"createParamDecorator");function P(t,e){let r=t.prototype[e];if(typeof r!="function")return null;let o=r[E];return o&&o.length>0?o:null}a(P,"getRouteParams");async function Q(t,e){let r=Math.max(...t.map(s=>s.index)),o=new Array(r+1).fill(void 0);for(let{index:s,type:a,key:i,pipes:c,extractor:l}of t){let u;switch(a){case "query":{let d=e.getQuery();u=i!==void 0?d[i]:d;break}case "param":{let d=e.getParams();u=i!==void 0?d[i]:d;break}case "body":{let d=e.getBodyParseError();if(d)throw new m(`Malformed JSON body: ${d.message}`);let f=e.getBody()??{};u=i!==void 0?f[i]:f;break}case "rawBody":{u=e.getRawBody();break}case "formData":{u=e.getFormData();break}case "headers":{let d=b(e.getNativeRequest());u=i!==void 0?d[i.toLowerCase()]:d;break}case "cookie":{let f=b(e.getNativeRequest()).cookie??"";if(i&&f){let y=f.split(";").map(p=>p.trim()).find(p=>p.startsWith(i+"="));u=y?decodeURIComponent(y.slice(i.length+1)):void 0;}else u=void 0;break}case "ip":{u=V(e);break}case "userAgent":{u=b(e.getNativeRequest())["user-agent"]??"";break}case "auth":{u=l?await l(e):e.getAuth();break}case "custom":{u=l?await l(e):void 0;break}}if(c&&c.length>0)for(let d of c)u=await Ut(d).transform(u);o[s]=u;}return o}a(Q,"resolveParamArgs");var X=Symbol.for("truxie:api:doc");function Rt(t){return (e,r,o)=>o!==void 0?(typeof o.value=="function"&&Ee(o.value,t,"override"),o):(typeof e=="function"&&Ee(e,t,"override"),e)}a(Rt,"ApiDoc");function Mt(t,e){Ee(t,e,"fill");}a(Mt,"contributeApiDoc");function Ee(t,e,r){let o=t,s=Gt(o[X])?o[X]:{},a=$t(e),i=r==="override"?{...s,...a}:{...a,...s},c=r==="override"?{...s.extensions,...a.extensions}:{...a.extensions,...s.extensions};Object.keys(c).length>0&&(i.extensions=c),o[X]=i;}a(Ee,"writeApiDoc");function $t(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}a($t,"defined");function Gt(t){return typeof t=="object"&&t!==null}a(Gt,"isRecord");function bt(t,e){let r=t.prototype?.[e];if(typeof r!="function")return null;let o=r[X];return qt(o)?o:null}a(bt,"getApiDoc");function Pt(t){return t?.returns?(Array.isArray(t.returns)?t.returns:[t.returns]).map(r=>({...r,status:r.status??200})):[]}a(Pt,"apiResponses");function qt(t){return typeof t=="object"&&t!==null&&typeof t.summary=="string"}a(qt,"isApiDoc");function vt(t,e={}){let r=P(t.controllerClass,t.methodName)??[],o={},s=Re(r,"param",e.toJsonSchema)??zt(t.paramNames);s&&(o.params=s);let a=e.querySchema??Re(r,"query",e.toJsonSchema)??At(r,"query");if(a&&(o.query=a),t.method!=="GET"){let i=e.bodySchema??Re(r,"body",e.toJsonSchema)??At(r,"body")??jt(r);i&&(o.body=i);}return o}a(vt,"describeRouteInput");function Re(t,e,r){if(r)for(let o of t){if(o.schema===void 0||(o.source??o.type)!==e)continue;let s=r(o.schema);if(s)return s}}a(Re,"schemaFor");function At(t,e){let r=t.filter(s=>s.type===e&&typeof s.key=="string").map(s=>s.key);if(r.length===0)return;let o={};for(let s of r)o[s]={};return {type:"object",properties:o}}a(At,"keyedSchema");function jt(t){return t.some(r=>r.type==="body"||r.source==="body")?{type:"object",description:"Shape not declared by the handler."}:void 0}a(jt,"looseBody");function zt(t){if(t.length===0)return;let e={};for(let r of t)e[r]={type:"string"};return {type:"object",properties:e,required:[...t]}}a(zt,"pathParamsSchema");var Ct="__redirect";function Dt(t,e=302){return {__redirect:true,url:t,statusCode:e}}a(Dt,"redirect");function Z(t){return t!==null&&typeof t=="object"&&t.__redirect===true}a(Z,"isRedirect");function ee(){return !!(process.env.VERCEL||process.env.AWS_LAMBDA_FUNCTION_NAME||process.env.LAMBDA_TASK_ROOT||process.env.FUNCTIONS_WORKER_RUNTIME||process.env.K_SERVICE||process.env.NETLIFY)}a(ee,"isServerless");var N=class{static{a(this,"TruxieApplication");}container;registry;initialized=false;rootModule;options;eventEmitter;prefix="";trustProxy;router;gateways=new Map;wsInitialized=false;constructor(e,r={}){this.rootModule=e,this.options=r,this.trustProxy=r.trustProxy??ee(),this.container=new b$2,this.registry=new o;}async init(){if(this.initialized)return;this.eventEmitter=new p,this.options.eventBus&&this.eventEmitter.setOptions(this.options.eventBus),this.container.register({provide:p,useValue:this.eventEmitter});let e=new p$1;this.container.register({provide:p$1,useValue:e}),this.registry.scan(this.rootModule),this.options.strictModuleBoundaries&&this.registry.validateVisibility(),this.registry.registerAll(this.container);let r$1=this.registry.getAllProviders();e._init(this.container,r$1),await this.registry.callLifecycleHooks(this.container,"onModuleInit"),await r(this.container,r$1),await this.registry.callLifecycleHooks(this.container,"onApplicationBootstrap"),this.router=new x(this.prefix),this.router.register(...this.registry.getAllControllers()),this.initialized=true;}setGlobalPrefix(e){return this.prefix=e,this.initialized&&(this.router=new x(this.prefix),this.router.register(...this.registry.getAllControllers())),this}getGlobalPrefix(){return this.prefix}async resolve(e){return this.ensureInitialized(),this.container.resolve(e)}has(e){return this.container.has(e)}getContainer(){return this.container}matchRoute(e,r){return this.ensureInitialized(),this.router.match(e,r)??null}getRoutes(){return this.ensureInitialized(),this.router.getRoutes()}async handleRequest(e,r){this.ensureInitialized();let{container:o,dispose:s}=this.createRequestContext();try{let a$1=await o.resolve(e.controllerClass),i=a$1[e.methodName];if(typeof i!="function")throw new Error(`${e.controllerClass.name}.${e.methodName} is not a method on the resolved controller.`);let c=i.bind(a$1),l=P(e.controllerClass,e.methodName);r.setData("__controllerClass",e.controllerClass),r.setData("__methodName",e.methodName),r.setData(_,this.trustProxy),r.setHandler?.(i),r.setContainer?.(o);let d=await S(o,this.getGlobalOptions(),{middlewares:e.middlewareRefs,guards:e.guardClasses,interceptors:e.interceptorRefs,pipes:e.pipeRefs,filters:e.filterRefs,handler:a(async f=>l?c(...await Q(l,f)):c(f),"handler")})(r);if(Z(d)){let f=d;return {value:d,isRedirect:!0,redirectUrl:f.url,redirectStatus:f.statusCode}}return {value:d,isRedirect:!1}}finally{await s();}}hasGateways(){return this.ensureInitialized(),this.registry.getAllGateways().length>0}async createWebSocketHooks(e){this.ensureInitialized(),await this.initGateways();let r=this;return {async open(o){let a="/"+(e.getUrl(o).split("?")[0]??"/").replace(/^\/+|\/+$/g,""),i=r.matchGatewayPath(a);if(!i)return;let c=o.context;c&&(c._gatewayPath=i);let l=r.gateways.get(i),u=e.adaptPeer(o);for(let d of l.serverProps)l.instance[d]={peers:e.getPeers(o)??new Set};if(l.hasConnection)try{await l.instance.handleConnection(u);}catch(d){console.error(`[WS] ${l.className}.handleConnection error:`,d);}},async message(o,s){let i=o.context?._gatewayPath;if(!i)return;let c=r.gateways.get(i);if(!c)return;let l=e.adaptPeer(o),u=e.adaptMessage(s),d;try{d=u.json();}catch{return}if(!d.event||typeof d.event!="string")return;let f=c.messageHandlers.get(d.event);if(f)try{let y=n$1(f.paramMeta,l,u,d.data),p=await f.method(...y);p!=null&&l.send(p);}catch(y){console.error(`[WS] ${c.className}.${d.event} error:`,y);}},async close(o,s){let i=o.context?._gatewayPath;if(!i)return;let c=r.gateways.get(i);if(!c?.hasDisconnect)return;let l=e.adaptPeer(o);try{await c.instance.handleDisconnect(l,s);}catch(u){console.error(`[WS] ${c.className}.handleDisconnect error:`,u);}},async error(o,s){let a=o?.id??"unknown";console.error(`[WS] Peer ${String(a)} error:`,s);}}}getControllers(){return this.ensureInitialized(),this.registry.getAllControllers()}getGateways(){return this.ensureInitialized(),this.registry.getAllGateways()}getProviders(){return this.ensureInitialized(),this.registry.getAllProviders()}getEventEmitter(){return this.ensureInitialized(),this.eventEmitter}getRouter(){return this.ensureInitialized(),this.router}createHandler(e){return this.ensureInitialized(),S(this.container,this.getGlobalOptions(),e)}async shutdown(){this.initialized&&(await this.registry.callLifecycleHooks(this.container,"onModuleDestroy"),await this.registry.callLifecycleHooks(this.container,"onApplicationShutdown"),this.eventEmitter.clear(),await this.container.dispose(),this.initialized=false);}createRequestContext(){if(!this.container.hasRequestScoped())return {container:this.container,dispose:a(async()=>{},"dispose")};let e=this.container.createChild();return {container:e,dispose:a(()=>e.dispose(),"dispose")}}matchGatewayPath(e){if(this.gateways.has(e))return e;for(let r of this.gateways.keys())if(e.endsWith(r))return r;if(this.gateways.has("/"))return "/"}async initGateways(){if(!this.wsInitialized){for(let e of this.registry.getAllGateways()){let r=i(e);if(!r)continue;let o=await this.container.resolve(e),s=new Map;for(let a of j$1(e)){let i=o[a.methodName];typeof i=="function"&&s.set(a.event,{method:i.bind(o),paramMeta:k$1(e.prototype[a.methodName])});}if(this.gateways.set(r.path,{instance:o,className:e.name,messageHandlers:s,hasConnection:typeof o.handleConnection=="function",hasDisconnect:typeof o.handleDisconnect=="function",serverProps:m$2(e)}),typeof o.afterInit=="function")try{await o.afterInit();}catch{}}this.wsInitialized=true;}}getGlobalOptions(){return {middlewares:this.options.globalMiddlewares,guards:this.options.globalGuards,interceptors:this.options.globalInterceptors,pipes:this.options.globalPipes,filters:this.options.globalFilters}}ensureInitialized(){if(!this.initialized)throw new Error("TruxieApplication not initialized. Call TruxieFactory.create() or app.init().")}},te=class{static{a(this,"TruxieFactory");}static async create(e,r){let o=new N(e,r);return await o.init(),o}};export{Rt as ApiDoc,h as AppError,xt as Auth,$ as BaseExecutionContext,ft as Body,tt as Catch,U as ConfigurableModuleBuilder,j as ConflictError,x as ControllerRouter,yt as Cookie,st as DefaultValuePipe,K as DomainEvent,R as ForbiddenError,ht as FormData,wt as Headers,mt as Ip,G as NotFoundError,lt as Param,Y as ParseIdPipe,L as ParseIntPipe,dt as Query,Ct as REDIRECT_BRAND,we as REMOTE_ADDRESS_KEY,pt as RawBody,M as RequestAbortedError,_ as TRUST_PROXY_KEY,N as TruxieApplication,te as TruxieFactory,le as UOW_INSTANCE_KEY,de as UOW_SESSION_KEY,q as UnauthorizedError,W as UnitOfWorkInterceptor,et as UseFilters,rt as UseInterceptors,ot as UseMiddleware,nt as UsePipes,gt as UserAgent,m as ValidationError,Pt as apiResponses,Xe as applyJsonBody,V as clientIp,Mt as contributeApiDoc,re as createAsyncOptionsProviders,Et as createParamDecorator,S as createPipeline,xe as defineAuth,vt as describeRouteInput,bt as getApiDoc,z as getEffectiveInterceptors,H as getEffectiveMiddlewares,ce as getInterceptorsMetadata,ue as getMethodInterceptors,me as getMethodMiddlewares,he as getMiddlewaresMetadata,ut as getRequestHeaders,P as getRouteParams,Z as isRedirect,ee as isServerless,Dt as redirect,Q as resolveParamArgs};
|
|
1
|
+
import {l,n,o,b as b$2,p,q,s,c}from'./chunk-CD6QSDG5.js';export{b as Container,d as Controller,h as Delete,q as EventEmitter2,e as Get,p as ModuleRegistry,k as NoGuard,r as OnEvent,i as Patch,f as Post,g as Put,j as RouteGuards,m as getControllerGuards,l as getControllerPath,o as getMethodGuards,n as getRouteMetadata}from'./chunk-CD6QSDG5.js';import {n as n$1,i,j as j$1,k,l as l$1,m as m$1}from'./chunk-RDP32XIU.js';import {b as b$1,p as p$1,i as i$1,j as j$2}from'./chunk-TSJZVSHP.js';export{p as DiscoveryService,m as Global,f as Inject,e as Injectable,b as InjectionToken,l as Module,g as Optional,a as Scope,c as forwardRef,n as getModuleMetadata,o as isGlobalModule,d as resolveForwardRef}from'./chunk-TSJZVSHP.js';import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';function se(t,e){if("useFactory"in e&&e.useFactory){let r=e.useFactory;return [{provide:t,useFactory:r,inject:e.inject??[]}]}if("useClass"in e&&e.useClass){let r=e.useClass;return [{provide:t,useFactory:a(async o=>o.createModuleOptions(),"useFactory"),inject:[r]},r]}if("useExisting"in e&&e.useExisting){let r=e.useExisting;return [{provide:t,useFactory:a(async o=>o.createModuleOptions(),"useFactory"),inject:[r]}]}throw new Error("ModuleAsyncOptions must specify one of: useFactory, useClass, or useExisting")}a(se,"createAsyncOptionsProviders");var j=class{static{a(this,"ConfigurableModuleBuilder");}description;featureDescription;onForRoot;onForFeature;constructor(e="MODULE_OPTIONS"){this.description=e,this.featureDescription=e+"_FEATURE";}setTokenDescription(e){return this.description=e,this}transformDynamicModule(e){return this.onForRoot=e,this}transformFeatureModule(e){return this.onForFeature=e,this}build(){let e=new b$1(this.description),r=new b$1(this.featureDescription),o=this.onForRoot,s=this.onForFeature;return {ConfigurableModuleClass:class{static{a(this,"ConfigurableModuleClassImpl");}static forRoot(c,d={}){let u={module:this,global:d.global??false,providers:[{provide:e,useValue:c}],exports:[e]};return o&&(u=o(u,c)),u}static forRootAsync(c){let d=se(e,c),u={module:this,imports:c.imports??[],providers:d,exports:[e]};return o&&(u=o(u)),u}static forFeature(c,d={}){let u={module:this,global:d.global??false,providers:[{provide:r,useValue:c}],exports:[r]};return s&&(u=s(u,c)),u}},MODULE_OPTIONS_TOKEN:e,MODULE_FEATURE_TOKEN:r}}};var U=class{static{a(this,"BaseExecutionContext");}nativeRequest;handler;container;query;params;body;bodyParseError;rawBody;formData;auth;data=new Map;metadata=new Map;abortController;constructor(e,r,o,s={},i={},a){this.nativeRequest=e,this.handler=r,this.container=o,this.query=s,this.params=i,this.abortController=a??new AbortController;}getNativeRequest(){return this.nativeRequest}getHandler(){return this.handler}setHandler(e){this.handler=e;}getBody(){return this.body}setBody(e){this.body=e;}getRawBody(){return this.rawBody}setRawBody(e){this.rawBody=e;}getBodyParseError(){return this.bodyParseError}setBodyParseError(e){this.bodyParseError=e;}getFormData(){return this.formData}setFormData(e){this.formData=e;}getQuery(){return this.query}getParams(){return this.params}getAuth(){return this.auth}setAuth(e){this.auth=e;}getMetadata(e){return this.metadata.get(e)}setMetadata(e,r){this.metadata.set(e,r);}getData(e){return this.data.get(e)}setData(e,r){this.data.set(e,r);}getContainer(){return this.container}setContainer(e){this.container=e;}getSignal(){return this.abortController.signal}abort(e){this.abortController.abort(e);}};function nt(t,e,r=""){if(e!=="")try{t.setBody(JSON.parse(e));}catch(o){$t(e,r)&&t.setBodyParseError(o instanceof Error?o:new Error(String(o)));}}a(nt,"applyJsonBody");function $t(t,e){if(e.toLowerCase().includes("json"))return true;let r=t.trimStart().charAt(0);return r==="{"||r==="["}a($t,"looksLikeJson");var ie=Symbol.for("truxie:filters"),st=Symbol.for("truxie:catch");function it(...t){return (e,r,o)=>{let s=r?e.constructor:e,i=Reflect.getOwnMetadata(ie,s)??[];Reflect.defineMetadata(ie,[...i,...t],s);}}a(it,"UseFilters");function at(...t){return e=>{Reflect.defineMetadata(st,t,e);}}a(at,"Catch");function ae(t){return c(ie,t)}a(ae,"getFiltersMetadata");function ce(t){return Reflect.getOwnMetadata(st,t)??[]}a(ce,"getCatchMetadata");var m=class extends Error{static{a(this,"AppError");}statusCode;status;isOperational;constructor(e,r){super(e),this.statusCode=r,this.status=r>=400&&r<500?"fail":"error",this.isOperational=true,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace(this,this.constructor);}},G=class extends m{static{a(this,"NotFoundError");}constructor(e="Resource not found"){super(e,404);}},y=class extends m{static{a(this,"ValidationError");}errors;constructor(e="Validation failed",r){super(e,400),this.errors=r;}},z=class extends m{static{a(this,"UnauthorizedError");}constructor(e="Not authorized"){super(e,401);}},C=class extends m{static{a(this,"ForbiddenError");}constructor(e="Access forbidden"){super(e,403);}},W=class extends m{static{a(this,"ConflictError");}constructor(e="Resource conflict"){super(e,409);}},v=class extends m{static{a(this,"RequestAbortedError");}constructor(e="Request aborted by client"){super(e,499);}};function _(t,e,r){return async o=>{let s=[...e.middlewares??[],...r.middlewares??[]],i=[...e.guards??[],...r.guards??[]],a$1=[...e.interceptors??[],...r.interceptors??[]],c=[...e.pipes??[],...r.pipes??[]],d=[...e.filters??[],...r.filters??[]],u=await E(t,d);try{x(o);let f=await E(t,s);return await Bt(o,f,async()=>{x(o);let l=await E(t,i);for(let S of l)if(x(o),!await S.canActivate(o))throw new C("Access denied by guard");x(o);let p=await E(t,c);for(let S of p)x(o),await S.transform(o);x(o);let h=await E(t,a$1),ve=a(async()=>(x(o),r.handler(o)),"handlerCall");return h.length===0?ve():h.reduceRight((S,De)=>async()=>(x(o),De.intercept(o,S)),ve)()})}catch(f){return jt(f,o,u)}}}a(_,"createPipeline");async function Bt(t,e,r){return e.length===0?r():e.reduceRight((s,i)=>()=>i.use(t,s),r)()}a(Bt,"runMiddlewareChain");function x(t){if(t.getSignal().aborted)throw new v}a(x,"checkAborted");async function jt(t,e,r){for(let o of r){let s=ce(o.constructor);if(s.length===0||t instanceof Error&&s.some(a=>t instanceof a))return o.catch(t,e)}throw t}a(jt,"handleError");async function E(t,e){let r=[];for(let o of e){if(typeof o!="function"){r.push(o);continue}let s=o;if(t.has(s)){r.push(await t.resolve(s));continue}if(Ut(s))throw new Error(`${s.name} declares constructor dependencies but is not registered as a provider, so they cannot be injected. Add it to a module's \`providers\`, or read what it needs off the ExecutionContext instead (\`ctx.getContainer().resolve(...)\`).`);r.push(new s);}return r}a(E,"resolveRefs");function Ut(t){return i$1(t).length>0||j$2(t).size>0?true:(Reflect.getMetadata?.("design:paramtypes",t)??[]).length>0}a(Ut,"declaresDependencies");var ue=Symbol.for("truxie:interceptors"),de=Symbol.for("truxie:method:interceptors");function ct(...t){return (e,r,o)=>{if(r!==void 0){let i=o?.value??e,a=i[de]??[];return i[de]=[...a,...t],o}let s=Reflect.getOwnMetadata(ue,e)??[];Reflect.defineMetadata(ue,[...s,...t],e);}}a(ct,"UseInterceptors");function fe(t){return c(ue,t)}a(fe,"getInterceptorsMetadata");function le(t,e){let o=t.prototype?.[e];return typeof o=="function"&&o[de]||[]}a(le,"getMethodInterceptors");function H(t,e){return [...fe(t),...le(t,e)]}a(H,"getEffectiveInterceptors");var pe="uow:session",he="uow:instance",K=class{static{a(this,"UnitOfWorkInterceptor");}factory;constructor(e){this.factory=e;}async intercept(e,r){let o=this.factory();await o.start(),e.setData(pe,o.getContext()),e.setData(he,o);try{let s=await r();return await o.commit(),s}catch(s){throw await o.rollback(),s}}};var me=Symbol.for("truxie:middlewares"),ye=Symbol.for("truxie:method:middlewares");function ut(...t){return (e,r,o)=>{if(r!==void 0){let i=o?.value??e,a=i[ye]??[];return i[ye]=[...a,...t],o}let s=Reflect.getOwnMetadata(me,e)??[];Reflect.defineMetadata(me,[...s,...t],e);}}a(ut,"UseMiddleware");function ge(t){return c(me,t)}a(ge,"getMiddlewaresMetadata");function we(t,e){let o=t.prototype?.[e];return typeof o=="function"&&o[ye]||[]}a(we,"getMethodMiddlewares");function Y(t,e){return [...ge(t),...we(t,e)]}a(Y,"getEffectiveMiddlewares");var xe=Symbol.for("truxie:pipes");function dt(...t){return (e,r,o)=>{let s=r?e.constructor:e,i=Reflect.getOwnMetadata(xe,s)??[];Reflect.defineMetadata(xe,[...i,...t],s);}}a(dt,"UsePipes");function Ee(t){return c(xe,t)}a(Ee,"getPipesMetadata");var Gt=/^[0-9a-fA-F]{24}$/,L=class{static{a(this,"ParseIdPipe");}paramName;constructor(e="id"){this.paramName=e;}transform(e){let o=e.getParams()[this.paramName];if(!o||!Gt.test(o))throw new y(`Invalid ${this.paramName}: must be a valid ObjectId`)}};var V=class{static{a(this,"ParseIntPipe");}transform(e){let r=Number(e);if(!Number.isInteger(r)||e===""||e===null||e===void 0)throw new y(`Expected an integer, received: ${JSON.stringify(e)}`);return r}};function ft(t){return {transform(e){return e??t}}}a(ft,"DefaultValuePipe");var J=class{static{a(this,"DomainEvent");}payload;timestamp;constructor(e){this.payload=e,this.timestamp=Date.now();}};function lt(t){let e=t,r=typeof e?.statusCode=="number"&&e.statusCode>=400&&e.statusCode<=599?e.statusCode:500,s=(e?.isOperational===true||r>=400&&r<500)&&typeof e?.message=="string"&&e.message.length>0?e.message:"Internal server error";return {status:r,message:s}}a(lt,"clientSafeError");var R=class{static{a(this,"ControllerRouter");}routes=[];globalPrefix;constructor(e=""){this.globalPrefix=e;}register(...e){for(let r of e){let o$1=l(r)??"",s=n(r);for(let i of s){let a=pt(`${this.globalPrefix}/${o$1}/${i.path}`);Wt(a,r.name,i.methodName),this.checkDuplicate(a,i.method,r.name,i.methodName);let{pattern:c,paramNames:d}=ht(a),u=o(r,i.methodName),f=H(r,i.methodName),l=Y(r,i.methodName);this.routes.push({method:i.method,pattern:c,paramNames:d,controllerClass:r,methodName:i.methodName,guardClasses:u,interceptorRefs:f,middlewareRefs:l,pipeRefs:Ee(r),filterRefs:ae(r),rawPath:a});}}this.routes.sort((r,o)=>mt(r.rawPath)-mt(o.rawPath));}checkDuplicate(e,r,o,s){let{pattern:i}=ht(e),a=this.routes.find(c=>c.method===r&&c.pattern.source===i.source);if(a){let c=a.rawPath===e?e:`${a.rawPath} / ${e}`;throw new Error(`Duplicate route: ${r} ${c}
|
|
2
|
+
Already registered by: ${a.controllerClass.name}.${a.methodName}
|
|
3
|
+
Conflicting with: ${o}.${s}`)}}match(e,r){let o=e.toUpperCase(),s=pt(r);for(let i of this.routes){if(i.method!==o)continue;let a=i.pattern.exec(s);if(!a)continue;let c={};for(let d=0;d<i.paramNames.length;d++)c[i.paramNames[d]]=a[d+1]??"";return {route:i,params:c}}return null}getRoutes(){return this.routes}};function pt(t){return "/"+t.replace(/\/+/g,"/").replace(/^\/|\/$/g,"")}a(pt,"normalizePath");function ht(t){let e=[],r=t.split("/").map(o=>o.startsWith(":")?(e.push(o.slice(1)),"([^/]+)"):zt(o)).join("/");return {pattern:new RegExp(`^${r}$`),paramNames:e}}a(ht,"compilePath");function zt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(zt,"escapeRegex");function mt(t){return t.split("/").filter(Boolean).reduce((e,r)=>e+(r.startsWith(":")?1:0),0)}a(mt,"routePriority");function Wt(t,e,r){let o=`Invalid path "${t}" on ${e}.${r}:`;if(!t.startsWith("/"))throw new Error(`${o} must start with /`);let s=t.split("/").filter((a,c)=>c>0),i=new Set;for(let a of s){if(a==="")throw new Error(`${o} contains empty segment (double slash)`);if(a.startsWith(":")){let c=a.slice(1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c))throw new Error(`${o} invalid param name ":${c}" \u2014 must be a valid identifier`);if(i.has(c))throw new Error(`${o} duplicate param name ":${c}"`);i.add(c);}}}a(Wt,"validatePath");var N="__trustProxy",Re="__remoteAddress";function yt(t){return D(t.getNativeRequest())}a(yt,"getRequestHeaders");function D(t){let e=t?.node?.req?.headers;if(e&&typeof e=="object")return e;let r=t?.headers;return r&&typeof r.entries=="function"?Object.fromEntries(r.entries()):r&&typeof r=="object"?r:{}}a(D,"headersOf");function Q(t){let e=Ht(t);if(t.getData(N)!==true)return e;let r=D(t.getNativeRequest()),o=r["cf-connecting-ip"];if(o)return String(o).trim();let s=r["x-forwarded-for"];if(s){let a=String(s).split(",")[0]?.trim();if(a)return a}let i=r["x-real-ip"];return i?String(i).trim():e}a(Q,"clientIp");function Ht(t){let e=t.getData(Re);if(e)return e;let r=t.getNativeRequest();return r?.node?.req?.socket?.remoteAddress??r?.socket?.remoteAddress??""}a(Ht,"directAddress");var b=Symbol.for("truxie:route:params");function Kt(t){return t==null?false:typeof t=="function"||typeof t=="object"&&typeof t.transform=="function"}a(Kt,"isParamPipeRef");function X(t,e){return Kt(t)?{key:void 0,pipes:[t,...e??[]]}:{key:t,pipes:e??[]}}a(X,"resolveArgs");function g(t,e,r=[]){return (o,s,i)=>{if(s===void 0)return;let a=o[s];if(typeof a!="function")return;let c=a[b]??[];a[b]=[...c,{index:i,type:t,key:e,pipes:r.length>0?r:void 0}];}}a(g,"buildBuiltinDecorator");function Yt(t){return typeof t=="function"?new t:t}a(Yt,"resolveParamPipe");function gt(t,...e){let{key:r,pipes:o}=X(t,e);return g("query",r,o)}a(gt,"Query");function wt(t,...e){let{key:r,pipes:o}=X(t,e);return g("param",r,o)}a(wt,"Param");function xt(t,...e){let{key:r,pipes:o}=X(t,e);return g("body",r,o)}a(xt,"Body");var Et=a(()=>g("rawBody"),"RawBody"),Rt=a(()=>g("formData"),"FormData"),bt=a(()=>g("ip"),"Ip"),Mt=a(()=>g("userAgent"),"UserAgent"),At=a(t=>g("cookie",t),"Cookie");function Pt(t,...e){let{key:r,pipes:o}=X(t,e);return g("headers",r,o)}a(Pt,"Headers");function be(t){return ()=>(e,r,o)=>{if(r===void 0)return;let s=e[r];if(typeof s!="function")return;let i=s[b]??[];s[b]=[...i,{index:o,type:"auth",extractor:t}];}}a(be,"defineAuth");var Ct=be();function vt(t,e){return ()=>(r,o,s)=>{if(o===void 0)return;let i=r[o];if(typeof i!="function")return;let a=i[b]??[];i[b]=[...a,{index:s,type:"custom",extractor:t,schema:e?.schema,source:e?.source}];}}a(vt,"createParamDecorator");function M(t,e){let r=t.prototype[e];if(typeof r!="function")return null;let o=r[b];return o&&o.length>0?o:null}a(M,"getRouteParams");async function Z(t,e){let r=Math.max(...t.map(s=>s.index)),o=new Array(r+1).fill(void 0);for(let{index:s,type:i,key:a,pipes:c,extractor:d}of t){let u;switch(i){case "query":{let f=e.getQuery();u=a!==void 0?f[a]:f;break}case "param":{let f=e.getParams();u=a!==void 0?f[a]:f;break}case "body":{let f=e.getBodyParseError();if(f)throw new y(`Malformed JSON body: ${f.message}`);let l=e.getBody()??{};u=a!==void 0?l[a]:l;break}case "rawBody":{u=e.getRawBody();break}case "formData":{u=e.getFormData();break}case "headers":{let f=D(e.getNativeRequest());u=a!==void 0?f[a.toLowerCase()]:f;break}case "cookie":{let l=D(e.getNativeRequest()).cookie??"";if(a&&l){let p=l.split(";").map(h=>h.trim()).find(h=>h.startsWith(a+"="));u=p?decodeURIComponent(p.slice(a.length+1)):void 0;}else u=void 0;break}case "ip":{u=Q(e);break}case "userAgent":{u=D(e.getNativeRequest())["user-agent"]??"";break}case "auth":{u=d?await d(e):e.getAuth();break}case "custom":{u=d?await d(e):void 0;break}}if(c&&c.length>0)for(let f of c)u=await Yt(f).transform(u);o[s]=u;}return o}a(Z,"resolveParamArgs");var ee=Symbol.for("truxie:api:doc");function Dt(t){return (e,r,o)=>o!==void 0?(typeof o.value=="function"&&Ae(o.value,t,"override"),o):(typeof e=="function"&&Ae(e,t,"override"),e)}a(Dt,"ApiDoc");function St(t,e){Ae(t,e,"fill");}a(St,"contributeApiDoc");function Ae(t,e,r){let o=t,s=Lt(o[ee])?o[ee]:{},i=Me(e),a=r==="override"?{...s,...i}:{...i,...s},c=r==="override"?{...s.extensions,...i.extensions}:{...i.extensions,...s.extensions};if(Object.keys(c).length>0&&(a.extensions=c),s.request||i.request){let d=Me(s.request??{}),u=Me(i.request??{});a.request=r==="override"?{...d,...u}:{...u,...d};}o[ee]=a;}a(Ae,"writeApiDoc");function Me(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}a(Me,"defined");function Lt(t){return typeof t=="object"&&t!==null}a(Lt,"isRecord");function T(t,e){let r=t.prototype?.[e];if(typeof r!="function")return null;let o=r[ee];return Vt(o)?o:null}a(T,"getApiDoc");function It(t){return t?.returns?(Array.isArray(t.returns)?t.returns:[t.returns]).map(r=>({...r,status:r.status??200})):[]}a(It,"apiResponses");function Vt(t){return typeof t=="object"&&t!==null&&typeof t.summary=="string"}a(Vt,"isApiDoc");function Tt(t,e={}){let r=M(t.controllerClass,t.methodName)??[],o=T(t.controllerClass,t.methodName)?.request,s=e.toJsonSchema,i={},a=Pe(r,"param",s)??te(o?.params,s)??Xt(t.paramNames);a&&(i.params=a);let c=e.querySchema??Pe(r,"query",s)??te(o?.query,s)??_t(r,"query");if(c&&(i.query=c),t.method!=="GET"){let d=e.bodySchema??Pe(r,"body",s)??te(o?.body,s)??_t(r,"body")??Qt(r);d&&Object.assign(i,{body:d},Jt(o));}return i}a(Tt,"describeRouteInput");function Jt(t){let e={},r=t?.contentType===void 0?[]:[t.contentType].flat();return r.length>0&&(e.bodyContentTypes=r),t?.bodyRequired!==void 0&&(e.bodyRequired=t.bodyRequired),e}a(Jt,"bodyMedia");function Pe(t,e,r){if(r)for(let o of t){if(o.schema===void 0||(o.source??o.type)!==e)continue;let s=r(o.schema,{io:"input"});if(s)return s}}a(Pe,"schemaFor");function te(t,e){if(t!==void 0)return Ce(t)?t:e?.(t,{io:"input"})??void 0}a(te,"documentedSchema");function _t(t,e){let r=kt(t,e);if(r.length===0)return;let o={};for(let s of r)o[s]={};return {type:"object",properties:o}}a(_t,"keyedSchema");function Qt(t){return t.some(r=>r.type==="body"||r.source==="body")?{type:"object",description:"Shape not declared by the handler."}:void 0}a(Qt,"looseBody");function Xt(t){if(t.length===0)return;let e={};for(let r of t)e[r]={type:"string"};return {type:"object",properties:e,required:[...t]}}a(Xt,"pathParamsSchema");function Ce(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e._def=="object"||typeof e._zod=="object"?false:"type"in e||"properties"in e||"$ref"in e||"anyOf"in e||"allOf"in e||"oneOf"in e}a(Ce,"isJsonSchemaObject");function Ot(t,e={}){let r=M(t.controllerClass,t.methodName)??[],o=T(t.controllerClass,t.methodName)?.request;return {query:Nt(r,"query",o?.query,e.toJsonSchema),body:Nt(r,"body",o?.body,e.toJsonSchema)}}a(Ot,"routeInputDrift");function Nt(t,e,r,o){let s={undocumented:[],unread:[]};if(r===void 0||Zt(t,e))return s;let i=er(te(r,o));if(!i)return s;let a=new Set(kt(t,e)),c=new Set(i);return {undocumented:[...a].filter(d=>!c.has(d)),unread:i.filter(d=>!a.has(d))}}a(Nt,"partDrift");function kt(t,e){let r=t.filter(o=>o.type===e&&typeof o.key=="string").map(o=>o.key);return [...new Set(r)]}a(kt,"readKeys");function Zt(t,e){return t.some(r=>r.type===e&&r.key===void 0||r.type==="custom"&&r.source===e?true:e==="body"&&(r.type==="rawBody"||r.type==="formData"))}a(Zt,"readsWholeObject");function er(t){let r=tr(t)?.properties;return typeof r!="object"||r===null?null:Object.keys(r)}a(er,"propertyNames");function tr(t){let e=t?.$ref;if(typeof e!="string")return t;let r=/^#\/(\$defs|definitions)\/([^/]+)$/.exec(e);return r?t?.[r[1]]?.[rr(r[2])]??t:t}a(tr,"resolveRootRef");function rr(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}a(rr,"decodePointer");var Ft="__redirect";function qt(t,e=302){return {__redirect:true,url:t,statusCode:e}}a(qt,"redirect");function re(t){return t!==null&&typeof t=="object"&&t.__redirect===true}a(re,"isRedirect");function oe(){return !!(process.env.VERCEL||process.env.AWS_LAMBDA_FUNCTION_NAME||process.env.LAMBDA_TASK_ROOT||process.env.FUNCTIONS_WORKER_RUNTIME||process.env.K_SERVICE||process.env.NETLIFY)}a(oe,"isServerless");var O=class{static{a(this,"TruxieApplication");}container;registry;initialized=false;rootModule;options;eventEmitter;prefix="";trustProxy;router;gateways=new Map;wsInitialized=false;constructor(e,r={}){this.rootModule=e,this.options=r,this.trustProxy=r.trustProxy??oe(),this.container=new b$2,this.registry=new p;}async init(){if(this.initialized)return;this.eventEmitter=new q,this.options.eventBus&&this.eventEmitter.setOptions(this.options.eventBus),this.container.register({provide:q,useValue:this.eventEmitter});let e=new p$1;this.container.register({provide:p$1,useValue:e}),this.registry.scan(this.rootModule),this.options.strictModuleBoundaries&&this.registry.validateVisibility([q,p$1]),this.registry.registerAll(this.container);let r=this.registry.getAllProviders();e._init(this.container,r),await this.registry.callLifecycleHooks(this.container,"onModuleInit"),await s(this.container,r),await this.registry.callLifecycleHooks(this.container,"onApplicationBootstrap"),this.router=new R(this.prefix),this.router.register(...this.registry.getAllControllers()),this.initialized=true;}setGlobalPrefix(e){return this.prefix=e,this.initialized&&(this.router=new R(this.prefix),this.router.register(...this.registry.getAllControllers())),this}getGlobalPrefix(){return this.prefix}async resolve(e){return this.ensureInitialized(),this.container.resolve(e)}has(e){return this.container.has(e)}getContainer(){return this.container}matchRoute(e,r){return this.ensureInitialized(),this.router.match(e,r)??null}getRoutes(){return this.ensureInitialized(),this.router.getRoutes()}async handleRequest(e,r){this.ensureInitialized();let{container:o,dispose:s}=this.createRequestContext();try{let i=await o.resolve(e.controllerClass),a$1=i[e.methodName];if(typeof a$1!="function")throw new Error(`${e.controllerClass.name}.${e.methodName} is not a method on the resolved controller.`);let c=a$1.bind(i),d=M(e.controllerClass,e.methodName);r.setData("__controllerClass",e.controllerClass),r.setData("__methodName",e.methodName),r.setData(N,this.trustProxy),r.setHandler?.(a$1),r.setContainer?.(o);let f=await _(o,this.getGlobalOptions(),{middlewares:e.middlewareRefs,guards:e.guardClasses,interceptors:e.interceptorRefs,pipes:e.pipeRefs,filters:e.filterRefs,handler:a(async l=>d?c(...await Z(d,l)):c(l),"handler")})(r);if(re(f)){let l=f;return {value:f,isRedirect:!0,redirectUrl:l.url,redirectStatus:l.statusCode}}return {value:f,isRedirect:!1}}finally{await s();}}hasGateways(){return this.ensureInitialized(),this.registry.getAllGateways().length>0}async createWebSocketHooks(e){this.ensureInitialized(),await this.initGateways();let r=this;return {async open(o){let i="/"+(e.getUrl(o).split("?")[0]??"/").replace(/^\/+|\/+$/g,""),a=r.matchGatewayPath(i);if(!a)return;let c=r.gateways.get(a),d=e.adaptPeer(o);for(let f of c.guards){let l=false;try{l=await f.canActivate(d);}catch(p){console.error(`[WS] ${c.className} guard error:`,p);}if(!l){d.close(1008,"Unauthorized");return}}let u=o.context;u&&(u._gatewayPath=a);for(let f of c.serverProps)c.instance[f]={peers:e.getPeers(o)??new Set};if(c.hasConnection)try{await c.instance.handleConnection(d);}catch(f){console.error(`[WS] ${c.className}.handleConnection error:`,f);}},async message(o,s){let a=o.context?._gatewayPath;if(!a)return;let c=r.gateways.get(a);if(!c)return;let d=e.adaptPeer(o),u=e.adaptMessage(s),f;try{f=u.json();}catch{return}if(!f.event||typeof f.event!="string")return;let l=c.messageHandlers.get(f.event);if(l)try{let p=n$1(l.paramMeta,d,u,f.data),h=await l.method(...p);h!=null&&d.send(h);}catch(p){console.error(`[WS] ${c.className}.${f.event} error:`,p);}},async close(o,s){let a=o.context?._gatewayPath;if(!a)return;let c=r.gateways.get(a);if(!c?.hasDisconnect)return;let d=e.adaptPeer(o);try{await c.instance.handleDisconnect(d,s);}catch(u){console.error(`[WS] ${c.className}.handleDisconnect error:`,u);}},async error(o,s){let i=o?.id??"unknown";console.error(`[WS] Peer ${String(i)} error:`,s);}}}getControllers(){return this.ensureInitialized(),this.registry.getAllControllers()}getGateways(){return this.ensureInitialized(),this.registry.getAllGateways()}getProviders(){return this.ensureInitialized(),this.registry.getAllProviders()}getEventEmitter(){return this.ensureInitialized(),this.eventEmitter}getRouter(){return this.ensureInitialized(),this.router}createHandler(e){return this.ensureInitialized(),_(this.container,this.getGlobalOptions(),e)}async shutdown(){this.initialized&&(await this.registry.callLifecycleHooks(this.container,"onModuleDestroy"),await this.registry.callLifecycleHooks(this.container,"onApplicationShutdown"),this.eventEmitter.clear(),await this.container.dispose(),this.initialized=false);}createRequestContext(){if(!this.container.hasRequestScoped())return {container:this.container,dispose:a(async()=>{},"dispose")};let e=this.container.createChild();return {container:e,dispose:a(()=>e.dispose(),"dispose")}}matchGatewayPath(e){if(this.gateways.has(e))return e;if(this.prefix){let r="/"+this.prefix.replace(/^\/+|\/+$/g,"");if(r!=="/"&&e.startsWith(r+"/")){let o=e.slice(r.length);if(this.gateways.has(o))return o}}}async initGateways(){if(!this.wsInitialized){for(let e of this.registry.getAllGateways()){let r=i(e);if(!r)continue;let o=await this.container.resolve(e),s=new Map;for(let a of j$1(e)){let c=o[a.methodName];typeof c=="function"&&s.set(a.event,{method:c.bind(o),paramMeta:k(e.prototype[a.methodName])});}let i$1=await E(this.container,l$1(e));if(this.gateways.set(r.path,{instance:o,className:e.name,messageHandlers:s,hasConnection:typeof o.handleConnection=="function",hasDisconnect:typeof o.handleDisconnect=="function",serverProps:m$1(e),guards:i$1}),typeof o.afterInit=="function")try{await o.afterInit();}catch{}}this.wsInitialized=true;}}getGlobalOptions(){return {middlewares:this.options.globalMiddlewares,guards:this.options.globalGuards,interceptors:this.options.globalInterceptors,pipes:this.options.globalPipes,filters:this.options.globalFilters}}ensureInitialized(){if(!this.initialized)throw new Error("TruxieApplication not initialized. Call TruxieFactory.create() or app.init().")}},ne=class{static{a(this,"TruxieFactory");}static async create(e,r){let o=new O(e,r);return await o.init(),o}};export{Dt as ApiDoc,m as AppError,Ct as Auth,U as BaseExecutionContext,xt as Body,at as Catch,j as ConfigurableModuleBuilder,W as ConflictError,R as ControllerRouter,At as Cookie,ft as DefaultValuePipe,J as DomainEvent,C as ForbiddenError,Rt as FormData,Pt as Headers,bt as Ip,G as NotFoundError,wt as Param,L as ParseIdPipe,V as ParseIntPipe,gt as Query,Ft as REDIRECT_BRAND,Re as REMOTE_ADDRESS_KEY,Et as RawBody,v as RequestAbortedError,N as TRUST_PROXY_KEY,O as TruxieApplication,ne as TruxieFactory,he as UOW_INSTANCE_KEY,pe as UOW_SESSION_KEY,z as UnauthorizedError,K as UnitOfWorkInterceptor,it as UseFilters,ct as UseInterceptors,ut as UseMiddleware,dt as UsePipes,Mt as UserAgent,y as ValidationError,It as apiResponses,nt as applyJsonBody,Q as clientIp,lt as clientSafeError,St as contributeApiDoc,se as createAsyncOptionsProviders,vt as createParamDecorator,_ as createPipeline,be as defineAuth,Tt as describeRouteInput,T as getApiDoc,H as getEffectiveInterceptors,Y as getEffectiveMiddlewares,fe as getInterceptorsMetadata,le as getMethodInterceptors,we as getMethodMiddlewares,ge as getMiddlewaresMetadata,yt as getRequestHeaders,M as getRouteParams,Ce as isJsonSchemaObject,re as isRedirect,oe as isServerless,qt as redirect,Z as resolveParamArgs,Ot as routeInputDrift};
|
package/dist/testing.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b,p as p$
|
|
1
|
+
import {b,q,p as p$2,s,a as a$1}from'./chunk-CD6QSDG5.js';import'./chunk-RDP32XIU.js';import {p as p$1,d}from'./chunk-TSJZVSHP.js';import {a}from'./chunk-EI7MMDWY.js';var h=class{static{a(this,"TestBuilder");}metadata;overrides=new Map;constructor(e){this.metadata=e;}overrideProvider(e){return {useValue:a(s=>(this.overrides.set(e,{provide:e,useValue:s}),this),"useValue"),useClass:a(s=>(this.overrides.set(e,{provide:e,useClass:s}),this),"useClass"),useFactory:a((s,n)=>(this.overrides.set(e,{provide:e,useFactory:s,inject:n??[]}),this),"useFactory")}}async compile(){let e=new b,s$1=new q;e.register({provide:q,useValue:s$1});let n=new p$1;e.register({provide:p$1,useValue:n});let i=this.metadata,o=[];if(g(i)){let t=(i.providers??[]).map(a=>a&&typeof a=="object"&&"forwardRef"in a?d(a):a);if(e.register(...t),o=t,i.imports&&i.imports.length>0){let a$1=new p$2,w={module:class{static{a(this,"TempTestModule");}},imports:i.imports,providers:t,exports:i.exports??[]};a$1.scan(w),a$1.registerAll(e),o=a$1.getAllProviders();}}else {let t=new p$2;t.scan(i),t.registerAll(e),o=t.getAllProviders();}for(let[,t]of this.overrides)e.register(t);return n._init(e,o),await this.callHook(e,o,"onModuleInit"),await s(e,o),await this.callHook(e,o,"onApplicationBootstrap"),{resolve:a(t=>e.resolve(t),"resolve"),has:a(t=>e.has(t),"has"),getContainer:a(()=>e,"getContainer"),getEventEmitter:a(()=>s$1,"getEventEmitter"),shutdown:a(async()=>{await this.callHook(e,o,"onModuleDestroy"),await this.callHook(e,o,"onApplicationShutdown"),s$1.clear(),await e.dispose();},"shutdown")}}async callHook(e,s,n){for(let i of s){let o=typeof i=="function"?i:i.provide;if(e.has(o))try{let t=await e.resolve(o);if(t&&typeof t=="object"&&typeof t[n]=="function"){if(n==="onModuleDestroy"&&!a$1(t))continue;await t[n]();}}catch{}}}};function g(l){return !(typeof l=="function"||l&&typeof l=="object"&&"module"in l)}a(g,"isModuleMetadata");var p=class{static{a(this,"Test");}static createTestingModule(e){return new h(e)}};export{p as Test};
|
|
@@ -27,6 +27,16 @@ interface WsPeer {
|
|
|
27
27
|
/** Subscribed topics */
|
|
28
28
|
readonly topics: Set<string>;
|
|
29
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* A guard applied to a `@WebSocketGateway` with `@WsGuards`.
|
|
32
|
+
*
|
|
33
|
+
* It runs once, during the connection phase, before any `@SubscribeMessage`
|
|
34
|
+
* handler on that gateway can be reached. Return `false` — or throw — to
|
|
35
|
+
* refuse the peer; the connection is closed with 1008 (policy violation).
|
|
36
|
+
*/
|
|
37
|
+
interface WsGuard {
|
|
38
|
+
canActivate(peer: WsPeer): boolean | Promise<boolean>;
|
|
39
|
+
}
|
|
30
40
|
/** Represents a received WebSocket message. Framework-agnostic. */
|
|
31
41
|
interface WsMessage {
|
|
32
42
|
/** Raw data */
|
|
@@ -115,4 +125,4 @@ interface OnGatewayInit {
|
|
|
115
125
|
afterInit(): void | Promise<void>;
|
|
116
126
|
}
|
|
117
127
|
|
|
118
|
-
export type { GatewayOptions as G, MessageHandlerEntry as M, OnGatewayConnection as O, WsPeer as W, WsMessage as a,
|
|
128
|
+
export type { GatewayOptions as G, MessageHandlerEntry as M, OnGatewayConnection as O, WsPeer as W, WsMessage as a, WsGuard as b, GatewayMetadata as c, WsParamType as d, OnGatewayDisconnect as e, OnGatewayInit as f, WsCloseDetails as g };
|
package/dist/ws.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import { G as GatewayOptions, W as WsPeer, a as WsMessage,
|
|
2
|
-
export { O as OnGatewayConnection,
|
|
1
|
+
import { G as GatewayOptions, b as WsGuard, W as WsPeer, a as WsMessage, c as GatewayMetadata, M as MessageHandlerEntry, d as WsParamType } from './types-BHt3a4dp.js';
|
|
2
|
+
export { O as OnGatewayConnection, e as OnGatewayDisconnect, f as OnGatewayInit, g as WsCloseDetails } from './types-BHt3a4dp.js';
|
|
3
3
|
|
|
4
|
+
/** Constructor of a gateway guard, as accepted by `@WsGuards`. */
|
|
5
|
+
type WsGuardClass = new (...args: any[]) => WsGuard;
|
|
4
6
|
/**
|
|
5
7
|
* Marks a class as a WebSocket gateway.
|
|
6
8
|
* Add to module's `providers: []` — auto-discovered like controllers.
|
|
@@ -123,15 +125,15 @@ declare function createWsParamDecorator<T = unknown>(extractor: (peer: WsPeer, m
|
|
|
123
125
|
* class PrivateGateway { ... }
|
|
124
126
|
* ```
|
|
125
127
|
*/
|
|
126
|
-
declare function WsGuards(...guards:
|
|
128
|
+
declare function WsGuards(...guards: WsGuardClass[]): ClassDecorator;
|
|
127
129
|
declare function getGatewayMetadata(target: Function): GatewayMetadata | undefined;
|
|
128
130
|
declare function getMessageHandlers(target: Function): MessageHandlerEntry[];
|
|
129
131
|
declare function getWsParams(fn: Function): WsParamType[];
|
|
130
|
-
declare function getWsGuards(target: Function):
|
|
132
|
+
declare function getWsGuards(target: Function): WsGuardClass[];
|
|
131
133
|
declare function getWsServerProperties(target: Function): string[];
|
|
132
134
|
/**
|
|
133
135
|
* Resolve parameter values for a @SubscribeMessage handler.
|
|
134
136
|
*/
|
|
135
137
|
declare function resolveWsArgs(paramMeta: WsParamType[], peer: WsPeer, message?: WsMessage, messageData?: unknown): unknown[];
|
|
136
138
|
|
|
137
|
-
export { ConnectedSocket, GatewayMetadata, GatewayOptions, MessageBody, MessageHandlerEntry, SubscribeMessage, WebSocketGateway, WebSocketServer, WsAuth, WsGuards, WsMessage, WsParamType, WsPeer, createWsParamDecorator, getGatewayMetadata, getMessageHandlers, getWsGuards, getWsParams, getWsServerProperties, resolveWsArgs };
|
|
139
|
+
export { ConnectedSocket, GatewayMetadata, GatewayOptions, MessageBody, MessageHandlerEntry, SubscribeMessage, WebSocketGateway, WebSocketServer, WsAuth, WsGuard, type WsGuardClass, WsGuards, WsMessage, WsParamType, WsPeer, createWsParamDecorator, getGatewayMetadata, getMessageHandlers, getWsGuards, getWsParams, getWsServerProperties, resolveWsArgs };
|
package/dist/ws.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{e as ConnectedSocket,d as MessageBody,b as SubscribeMessage,a as WebSocketGateway,c as WebSocketServer,f as WsAuth,h as WsGuards,g as createWsParamDecorator,i as getGatewayMetadata,j as getMessageHandlers,l as getWsGuards,k as getWsParams,m as getWsServerProperties,n as resolveWsArgs}from'./chunk-
|
|
1
|
+
export{e as ConnectedSocket,d as MessageBody,b as SubscribeMessage,a as WebSocketGateway,c as WebSocketServer,f as WsAuth,h as WsGuards,g as createWsParamDecorator,i as getGatewayMetadata,j as getMessageHandlers,l as getWsGuards,k as getWsParams,m as getWsServerProperties,n as resolveWsArgs}from'./chunk-RDP32XIU.js';import'./chunk-EI7MMDWY.js';
|
package/package.json
CHANGED
package/dist/chunk-42ZAPMNO.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';var S=Symbol.for("truxie:ws:gateway"),f=Symbol.for("truxie:ws:message"),d=Symbol.for("truxie:ws:params"),l=Symbol.for("truxie:ws:guards"),x=Symbol.for("truxie:ws:server");function p(e){return n=>{let r=typeof e=="string"?{path:e}:e??{},a={path:r.path??"/",namespace:r.namespace??"/",target:n};Reflect.defineMetadata(S,a,n);}}a(p,"WebSocketGateway");function w(e){return (n,r,a)=>{let s=n.constructor,o=Reflect.getOwnMetadata(f,s)??[];Reflect.defineMetadata(f,[...o,{event:e,methodName:String(r)}],s);}}a(w,"SubscribeMessage");function b(){return (e,n)=>{let r=e.constructor,a=Reflect.getOwnMetadata(x,r)??[];Reflect.defineMetadata(x,[...a,String(n)],r);}}a(b,"WebSocketServer");function i(e,n){return (r,a,s)=>{if(a===void 0)return;let o=r[a];if(typeof o!="function")return;let c=o[d]??[];o[d]=[...c,{type:e,index:s,extractor:n}];}}a(i,"buildWsParamDecorator");var M=a(()=>i("message-body"),"MessageBody"),W=a(()=>i("connected-socket"),"ConnectedSocket"),R=a(()=>i("ws-auth"),"WsAuth");function y(e){return ()=>i("custom",e)}a(y,"createWsParamDecorator");function A(...e){return n=>{Reflect.defineMetadata(l,e,n);}}a(A,"WsGuards");function h(e){return Reflect.getOwnMetadata(S,e)}a(h,"getGatewayMetadata");function k(e){return Reflect.getOwnMetadata(f,e)??[]}a(k,"getMessageHandlers");function _(e){return e[d]??[]}a(_,"getWsParams");function E(e){return Reflect.getOwnMetadata(l,e)??[]}a(E,"getWsGuards");function G(e){return Reflect.getOwnMetadata(x,e)??[]}a(G,"getWsServerProperties");function D(e,n,r,a){if(e.length===0)return [];let s=Math.max(...e.map(c=>c.index)),o=new Array(s+1).fill(void 0);for(let{type:c,index:u,extractor:g}of e)switch(c){case "message-body":o[u]=a;break;case "connected-socket":o[u]=n;break;case "ws-auth":o[u]=n.context.auth;break;case "custom":o[u]=g?g(n,r):void 0;break}return o}a(D,"resolveWsArgs");export{p as a,w as b,b as c,M as d,W as e,R as f,y as g,A as h,h as i,k as j,_ as k,E as l,G as m,D as n};
|
package/dist/chunk-RXJTN5BJ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {i as i$1}from'./chunk-42ZAPMNO.js';import {d,h,a as a$1,i,j as j$1,k as k$1,b,n,o,e}from'./chunk-TSJZVSHP.js';import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';var $=new WeakSet;function M(i){return $.has(i)?false:($.add(i),true)}a(M,"claimDestroy");var F=class extends Error{static{a(this,"MissingProviderError");}},_=class i$1{static{a(this,"Container");}registrations=new Map;parent=null;children=[];register(...e){for(let t of e)this.registerOne(t);}registerOne(e){let t=e&&typeof e=="object"&&"forwardRef"in e?d(e):e;if(typeof t=="function"){let a=h(t)?.scope??a$1.SINGLETON;this.registrations.set(t,{provider:t,scope:a,resolved:false});return}let r=t.provide,o=a$1.SINGLETON,n=t;if("useClass"in t){let s=t.useClass,a=s&&typeof s=="object"&&"forwardRef"in s?d(s):s,f=h(a);o=t.scope??f?.scope??a$1.SINGLETON,n={...t,useClass:a};}else if("useExisting"in t){let s=t.useExisting,a=s&&typeof s=="object"&&"forwardRef"in s?d(s):s;n={...t,useExisting:a};}else "useFactory"in t&&(o=t.scope??a$1.SINGLETON);this.registrations.set(r,{provider:n,scope:o,resolved:false});}async resolve(e){return this.resolveInternal(e,W)}async resolveInternal(e,t){let r=d(e),o=r!==e?r:e,n=this.findOwner(o);if(!n)throw new F(`No provider found for ${S(o)}`);let s=n.registrations.get(o),a=s.scope===a$1.SINGLETON?n:this,f=s.scope===a$1.SINGLETON||s.scope===a$1.REQUEST&&a.parent!==null;if(f&&s.resolved)return s.instance;if(t.has(o))throw new Error(`Circular dependency detected for ${S(o)}`);if(f&&s.inFlight)return s.inFlight;let m=new Set(t).add(o),d$1=a.createInstance(s,m).then(h=>(f&&(s.instance=h,s.resolved=true),s.inFlight=void 0,h),h=>{throw s.inFlight=void 0,h});return f&&(s.inFlight=d$1),d$1}has(e){return this.registrations.has(e)||(this.parent?.has(e)??false)}hasRequestScoped(){for(let[,e]of this.registrations)if(e.scope===a$1.REQUEST)return true;return this.parent?.hasRequestScoped()??false}findOwner(e){return this.registrations.has(e)?this:this.parent?.findOwner(e)??null}createChild(){let e=new i$1;e.parent=this;for(let[t,r]of this.registrations)r.scope===a$1.REQUEST&&e.registrations.set(t,{provider:r.provider,scope:a$1.REQUEST,instance:void 0,resolved:false});return this.children.push(e),e}async dispose(){for(let e of [...this.children])await e.dispose();this.children=[];for(let[,e]of this.registrations){if(!e.resolved)continue;let t=e.instance;if(!t||typeof t!="object")continue;let r=t;typeof r.onModuleDestroy=="function"&&M(t)&&await r.onModuleDestroy();}if(this.registrations.clear(),this.parent){let e=this.parent.children.indexOf(this);e!==-1&&this.parent.children.splice(e,1),this.parent=null;}}async createInstance(e,t){let{provider:r}=e;if(typeof r=="function")return this.instantiateClass(r,t);if("useValue"in r)return r.useValue;if("useClass"in r)return this.instantiateClass(r.useClass,t);if("useFactory"in r){let o=r,n=[];if(o.inject)for(let s of o.inject)n.push(await this.resolveInternal(s,t));return o.useFactory(...n)}if("useExisting"in r)return this.resolveInternal(r.useExisting,t);throw new Error("Unknown provider type")}async instantiateClass(e,t){let r=Reflect.getMetadata("design:paramtypes",e)??[],o=i(e),n=j$1(e),s=k$1(e),a=n.size>0?Math.max(...n.keys())+1:0,f=Math.max(r.length,a,o.length),m=[];for(let d=0;d<f;d++){let h=n.get(d)??o[d]??r[d];try{m.push(await this.resolveInternal(h,t));}catch(g){if(g instanceof F&&s.has(d)){m.push(void 0);continue}let x=g instanceof Error?g.message:String(g);throw new Error(`Cannot resolve parameter at index ${d} (${S(h)}) of ${e.name}: ${x}`,{cause:g})}}return new e(...m)}},W=new Set;function S(i){return typeof i=="string"?i:typeof i=="symbol"||i instanceof b?i.toString():typeof i=="function"?i.name:String(i)}a(S,"tokenToString");var L=Symbol.for("truxie:controller:path"),T=Symbol.for("truxie:controller:guards"),O=Symbol.for("truxie:route:metadata"),U=Symbol.for("truxie:method:route"),w=Symbol.for("truxie:method:guards"),P=Symbol.for("truxie:method:noguard");function de(i){return e=>{Reflect.defineMetadata(L,i,e);}}a(de,"Controller");function E(i){return (e="")=>(t,r,o)=>{let n=o!==void 0,s=String(n?r:r?.name??r),a=n?o?.value:t;if(typeof a=="function"&&(a[U]={method:i,path:e,methodName:s}),n){let f=Reflect.getOwnMetadata(O,t.constructor)??[];return f.push({method:i,path:e,methodName:s}),Reflect.defineMetadata(O,f,t.constructor),o}return t}}a(E,"createMethodDecorator");var le=E("GET"),ue=E("POST"),pe=E("PUT"),he=E("DELETE"),me=E("PATCH");function ge(...i){return (e,t,r)=>{if(t==null){Reflect.defineMetadata(T,i,e);return}if(r!==void 0){if(r?.value){let o=r.value[w]??[];r.value[w]=[...o,...i];}return r}if(typeof e=="function"){let o=e[w]??[];e[w]=[...o,...i];}return typeof e=="function"&&t?.kind==="class"&&Reflect.defineMetadata(T,i,e),e}}a(ge,"RouteGuards");function ve(){return (i,e,t)=>t!==void 0?(t?.value&&(t.value[P]=true),t):(typeof i=="function"&&(i[P]=true),i)}a(ve,"NoGuard");function k(i){return Reflect.getOwnMetadata(L,i)}a(k,"getControllerPath");function ye(i){return Reflect.getOwnMetadata(T,i)??[]}a(ye,"getControllerGuards");function V(i){let e=new Map,t=i.prototype;for(;t&&t!==Object.prototype;){for(let r of Object.getOwnPropertyNames(t)){if(r==="constructor"||e.has(r))continue;let o=Object.getOwnPropertyDescriptor(t,r);!o||typeof o.value!="function"||e.set(r,o.value);}t=Object.getPrototypeOf(t);}return e}a(V,"methodsOf");function Y(i,e){return V(i).get(e)}a(Y,"methodOf");function we(i){let e=[],t=new Set;for(let[r,o]of V(i)){let n=o[U];!n||t.has(r)||(t.add(r),e.push(n));}if(e.length>0)return e;for(let r=i;r&&r!==Function.prototype;r=Object.getPrototypeOf(r)){let o=Reflect.getOwnMetadata(O,r)??[];for(let n of o)t.has(n.methodName)||(t.add(n.methodName),e.push(n));}return e}a(we,"getRouteMetadata");function Ee(i,e){let t=Y(i,e),r=t!==void 0&&t[P]===true,o=t!==void 0&&t[w]||[];return r?o:[...B(i),...o]}a(Ee,"getMethodGuards");function B(i){for(let e=i;e&&e!==Function.prototype;e=Object.getPrototypeOf(e)){let t=Reflect.getOwnMetadata(T,e);if(t)return t}return []}a(B,"controllerGuardsOf");var Q=class{static{a(this,"ModuleRegistry");}resolved=new Map;sortedModules=[];scan(e){this.resolveModule(e),this.sortedModules=this.topologicalSort(),this.validateExports();}registerAll(e){let t=new Set;for(let r of this.sortedModules)if(r.global)for(let o of r.providers)t.add(o);t.size>0&&e.register(...t);for(let r of this.sortedModules){e.register(...r.providers);for(let o of r.metadata.imports??[]){let n=this.getModuleType(o),s=this.resolved.get(n);if(s)for(let a of s.exports){let f=this.findProvider(s,a)??this.findReExportedProvider(s,a);f&&e.register(f);}}}}getAllProviders(){let e=[];for(let t of this.sortedModules)e.push(...t.providers);return e}getAllControllers(){let e=new Set,t=[];for(let r of this.sortedModules){for(let o of r.controllers)e.has(o)||(e.add(o),t.push(o));for(let o of r.metadata.providers??[])typeof o=="function"&&k(o)!==void 0&&!e.has(o)&&(e.add(o),t.push(o));}return t}getAllGateways(){let e=new Set,t=[];for(let r of this.sortedModules)for(let o of r.providers)typeof o=="function"&&i$1(o)!==void 0&&!e.has(o)&&(e.add(o),t.push(o));return t}async callLifecycleHooks(e,t,r){for(let o of this.sortedModules)for(let n of o.providers){let s=typeof n=="function"?n:n.provide;if(e.has(s))try{let a=await e.resolve(s);if(a&&typeof a=="object"&&typeof a[t]=="function"){if(t==="onModuleDestroy"&&!M(a))continue;await a[t](r);}}catch{}}}resolveModule(e){let t=d(e),r=typeof t=="object"&&"module"in t,o$1=r?t.module:t,n$1=this.resolved.get(o$1);if(n$1)return r&&this.mergeDynamicModule(n$1,e),n$1;let s=n(o$1)??{},a=r?e:{},f=[...s.controllers??[],...a.controllers??[]],m=[...s.providers??[],...a.providers??[]],d$1=[...s.exports??[],...a.exports??[]],h=m.map(l=>l&&typeof l=="object"&&"forwardRef"in l?d(l):l),g=d$1.map(l=>l&&typeof l=="object"&&"forwardRef"in l?d(l):l),x={imports:[...s.imports??[],...a.imports??[]],controllers:f,providers:h,exports:g},N={type:o$1,metadata:x,controllers:f,providers:[...f,...h],exports:new Set(g),global:r?e.global??o(o$1):o(o$1)};this.resolved.set(o$1,N);for(let l of x.imports??[])this.resolveModule(l);return N}mergeDynamicModule(e,t){if(t.controllers&&t.controllers.length>0&&(e.controllers.push(...t.controllers),e.providers.push(...t.controllers),e.metadata.controllers=[...e.metadata.controllers??[],...t.controllers]),t.providers&&t.providers.length>0){let r=t.providers.map(o=>o&&typeof o=="object"&&"forwardRef"in o?d(o):o);e.providers.push(...r),e.metadata.providers=[...e.metadata.providers??[],...r];}if(t.exports&&t.exports.length>0){let r=t.exports.map(o=>o&&typeof o=="object"&&"forwardRef"in o?d(o):o);for(let o of r)e.exports.add(o);e.metadata.exports=[...e.metadata.exports??[],...r];}if(t.imports&&t.imports.length>0){e.metadata.imports=[...e.metadata.imports??[],...t.imports];for(let r of t.imports)this.resolveModule(r);}t.global===true&&(e.global=true);}getVisibleTokens(e){let t=new Set;for(let r of e.providers)t.add(this.getProviderToken(r));for(let r of e.metadata.imports??[]){let o=this.getModuleType(r),n=this.resolved.get(o);if(n)for(let s of n.exports)t.add(s);}for(let r of this.sortedModules)if(r.global)for(let o of r.providers)t.add(this.getProviderToken(o));return t}validateExports(){for(let e of this.sortedModules){let t=new Set(e.providers.map(o=>this.getProviderToken(o))),r=this.collectImportedExports(e);for(let o of e.exports)if(!t.has(o)&&!r.has(o)){let n=typeof o=="function"?o.name:String(o);throw new Error(`${e.type.name} exports ${n} but it is not in its providers and is not re-exported from an imported module`)}}}validateVisibility(){for(let e of this.sortedModules){let t=this.getVisibleTokens(e);for(let r of e.providers){if(typeof r!="function")continue;let o=i(r);for(let n of o)if(!t.has(n)){let s=typeof n=="function"?n.name:String(n);throw new Error(`${e.type.name}: ${r.name} depends on ${s}, but it is not provided in this module and not exported by any imported module`)}}}}getProviderToken(e){return typeof e=="function"?e:e.provide}collectImportedExports(e){let t=new Set;for(let r of e.metadata.imports??[]){let o=this.getModuleType(r),n=this.resolved.get(o);if(n)for(let s of n.exports)t.add(s);}return t}findProvider(e,t){return e.providers.find(r=>typeof r=="function"?r===t:r.provide===t)}findReExportedProvider(e,t){for(let r of e.metadata.imports??[]){let o=this.getModuleType(r),n=this.resolved.get(o);if(!n||!n.exports.has(t))continue;let s=this.findProvider(n,t);if(s)return s;let a=this.findReExportedProvider(n,t);if(a)return a}}getModuleType(e){let t=d(e);return typeof t=="object"&&"module"in t?t.module:t}topologicalSort(){let e=new Set,t=new Set,r=[],o=a(n=>{if(e.has(n))return;if(t.has(n))throw new Error(`Circular module dependency detected: ${n.name}`);t.add(n);let s=this.resolved.get(n);if(s){for(let a of s.metadata.imports??[])o(this.getModuleType(a));t.delete(n),e.add(n),r.push(s);}},"visit");for(let[n]of this.resolved)o(n);return r}};function J(i,e,t,r){var o=arguments.length,n=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(i,e,t,r);else for(var a=i.length-1;a>=0;a--)(s=i[a])&&(n=(o<3?s(n):o>3?s(e,t,n):s(e,t))||n);return o>3&&n&&Object.defineProperty(e,t,n),n}a(J,"_ts_decorate");function z(i,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(i,e)}a(z,"_ts_metadata");var v=class{static{a(this,"EventEmitter2");}handlers=new Map;pending=new Map;onError;constructor(){this.onError=X;}setOptions(e){e.onError&&(this.onError=e.onError);}subscribe(e,t,r){let o=this.handlers.get(e)??[];o.push({instance:r?.instance??{},methodName:r?.methodName??"anonymous",handler:t}),this.handlers.set(e,o);}registerHandler(e,t,r){let o=t[r].bind(t);this.subscribe(e,o,{instance:t,methodName:r});}async emit(e){let t=this.handlers.get(e.type);if(!t||t.length===0)return;let r=this.executeHandlers(t,e);this.pending.set(r,e.type);try{await r;}finally{this.pending.delete(r);}}emitAsync(e){let t=this.handlers.get(e.type);if(!t||t.length===0)return Promise.resolve([]);let r=this.executeHandlers(t,e).then(o=>(this.pending.delete(r),o),()=>(this.pending.delete(r),[]));return this.pending.set(r,e.type),r}async waitForAllDone(...e){for(;;){let t=this.getPending(e);if(t.length===0)break;await Promise.allSettled(t);}}getPending(e){if(e.length===0)return [...this.pending.keys()];let t=[];for(let[r,o]of this.pending)e.includes(o)&&t.push(r);return t}hasHandlers(e){let t=this.handlers.get(e);return t!==void 0&&t.length>0}handlerCount(e){return this.handlers.get(e)?.length??0}clear(){this.handlers.clear();}async executeHandlers(e,t){return (await Promise.allSettled(e.map(async o=>{let n=Date.now();try{return {value:await o.handler(t),durationMs:Date.now()-n}}catch(s){return {err:s,durationMs:Date.now()-n,threw:true}}}))).map((o,n)=>{let s=e[n],a=`${s.instance.constructor?.name??"Unknown"}.${s.methodName}`;if(o.status==="fulfilled"&&!("threw"in o.value))return {name:a,status:"success",value:o.value.value,durationMs:o.value.durationMs};let f=o.status==="fulfilled"?o.value.err:o.reason,m=f instanceof Error?f.message:typeof f=="string"?f:String(f),d=o.status==="fulfilled"?o.value.durationMs:0;return this.onError(f,t.type,a),{name:a,status:"failed",error:m,durationMs:d}})}};v=J([e(),z("design:type",Function),z("design:paramtypes",[])],v);function X(i,e,t){console.error(`[EventEmitter2] Handler "${t}" failed for event "${e}":`,i);}a(X,"defaultErrorHandler");var j=Symbol.for("truxie:on-event");function Ae(i){return (e,t,r)=>{let o=Reflect.getOwnMetadata(j,e.constructor)??[];o.push({eventType:i,methodName:String(t)}),Reflect.defineMetadata(j,o,e.constructor);}}a(Ae,"OnEvent");function q(i){return Reflect.getOwnMetadata(j,i)??[]}a(q,"getOnEventMetadata");async function Ue(i,e){let t=await i.resolve(v);for(let r of e){let o=Z(r);if(!o)continue;let n=q(o);if(n.length===0)continue;let s=typeof r=="function"?r:r.provide,a;try{a=await i.resolve(s);}catch{continue}for(let f of n)typeof a[f.methodName]=="function"&&t.registerHandler(f.eventType,a,f.methodName);}}a(Ue,"scanEventHandlers");function Z(i){return typeof i=="function"?h(i)?i:null:"useClass"in i?i.useClass:null}a(Z,"getProviderClass");export{M as a,_ as b,de as c,le as d,ue as e,pe as f,he as g,me as h,ge as i,ve as j,k,ye as l,we as m,Ee as n,Q as o,v as p,Ae as q,Ue as r};
|