UNPKG

zod-sockets

Version:

Socket.IO solution with I/O validation and the ability to generate AsyncAPI specification and a contract for consumers

17 lines (14 loc) 23.4 kB
import{z as Fe}from"zod";var q=(e,t)=>{try{return typeof e.parse(t)}catch{return}},H=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,He=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),C=e=>e.charAt(0).toLowerCase()+e.slice(1),l=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,o=>`/${o}`).split("/")).map(He).join(""),Ne=e=>e instanceof Error?e:new Error(String(e)),ce=e=>e instanceof Fe.ZodError?e.issues.map(({path:t,message:o})=>(t.length?[t.join("/")]:[]).concat(o).join(": ")).join("; "):e.message;var Y=e=>({join:async t=>e.join(t),leave:async t=>typeof t=="string"?e.leave(t):Promise.all(t.map(o=>e.leave(o))).then(()=>{})});import _e from"node:assert/strict";var J=({sockets:e,...t})=>e.map(o=>({id:o.id,handshake:o.handshake,rooms:Array.from(o.rooms),getData:()=>o.data||{},emit:v({subject:o,...t}),...Y(o)}));function v({subject:e,emission:t,timeout:o}){return async(n,...r)=>{let i="id"in e;_e(n in t,new Error(`Unsupported event ${n}`));let{schema:a,ack:s}=t[n],d=a.parse(r);if(!s)return e.emit(String(n),...d)||!0;let y=await e.timeout(o).emitWithAck(String(n),...d);return(i?s:s.array()).parse(y)}}var de=({subject:e,...t})=>o=>({getClients:async()=>J({sockets:await e.in(o).fetchSockets(),...t}),broadcast:v({...t,subject:e.to(o)})});var Ae={onConnection:({client:{id:e,getData:t},logger:o})=>o.debug("Client connected",{...t(),id:e}),onDisconnect:({client:{id:e,getData:t},logger:o})=>o.debug("Client disconnected",{...t(),id:e}),onAnyIncoming:({event:e,client:{id:t,getData:o},logger:n})=>n.debug(`${e} from ${t}`,o()),onAnyOutgoing:({event:e,logger:t,payload:o})=>t.debug(`Sending ${e}`,o),onStartup:({logger:e})=>e.debug("Ready"),onError:({logger:e,event:t,error:o})=>e.error(t?`${t} handling error`:"Error",o)};var Q="/",$=e=>{let t=e.trim();return t.startsWith("/")?t:`/${t}`};import{hex as G,italic as Be}from"ansis";import{T as Ve,always as X,cond as We,gt as pe}from"ramda";var qe=Be("for River".padEnd(20)),Ye="Proudly supports non-binary community.".padStart(77),Je=` ,, MMM"""AMV \u1FEF7MM .M"""bgd \u1FEF7MM mm M\u2019 AMV MM ,MI "Y MM MM \u1FEF AMV ,pW"Wq. ,M""bMM \u1FEFMMb. ,pW"Wq. ,p6"bo MM ,MP\u2019 .gP"Ya mmMMmm ,pP"Ybd AMV 6W\u2019 \u1FEFWb ,AP MM \u1FEFYMMNq. 6W\u2019 \u1FEFWb 6M\u2019 OO MM ;Y ,M\u2019 Yb MM 8I \u1FEF" AMV , 8M M8 8MI MM . \u1FEFMM 8M M8 8M MM;Mm 8M"""""" MM \u1FEFYMMMa. AMV ,M YA. ,A9 \u1FEFMb MM Mb dM YA. ,A9 YM. , MM \u1FEFMb. YM. , MM L. I8 AMVmmmmMM \u1FEFYbmd9\u2019 \u1FEFWbmd"MML. P"Ybmmd" \u1FEFYbmd9\u2019 YMbmd\u2019 .JMML. YA. \u1FEFMbmmd\u2019 \u1FEFMbmo M9mmmP\u2019 ${qe}${Ye} `,Qe=We([[pe(4),X(G("#FCF434"))],[pe(5),X(G("#FFF"))],[pe(8),X(G("#9C59D1"))],[Ve,X(G("#2C2C2C"))]]),Ee=()=>Je.split(` `).map((e,t)=>Qe(t)(e)).join(` `);var Ge=async({io:e,actions:t,target:o,config:{namespaces:n,timeout:r,startupLogo:i=!0},logger:a=console})=>{for(let s in n){let d=e.of($(s)),{emission:y,hooks:N,metadata:g}=n[s],{onConnection:k,onDisconnect:T,onAnyIncoming:Z,onAnyOutgoing:h,onStartup:P,onError:S}={...Ae,...N},x={emission:y,timeout:r},j={logger:a,withRooms:de({subject:e,metadata:g,...x}),all:{getClients:async()=>J({sockets:await d.fetchSockets(),metadata:g,...x}),getRooms:()=>Array.from(d.adapter.rooms.keys()),broadcast:v({subject:e,...x})}};d.on("connection",async f=>{let u=v({subject:f,...x}),A=v({subject:f.broadcast,...x}),z={emit:u,broadcast:A,id:f.id,handshake:f.handshake,getRequest:()=>f.request,isConnected:()=>f.connected,getRooms:()=>Array.from(f.rooms),getData:()=>f.data||{},setData:b=>{g.parse(b),f.data=b},...Y(f)},E={...j,client:z,withRooms:de({subject:f,metadata:g,...x})};await k(E),f.onAny((b,...U)=>Z({event:b,payload:U,...E})),f.onAnyOutgoing((b,...U)=>h({event:b,payload:U,...E}));for(let b of t)if(b.getNamespace()===s){let U=b.getEvent();f.on(U,async(...Ze)=>{try{return await b.execute({params:Ze,...E})}catch(Le){return S({...E,event:U,payload:Ze,error:Ne(Le)})}})}f.on("disconnect",()=>T(E))}),await P(j)}return(i?console.log:()=>{})(Ee()),a.debug("Running","v2.2.0 (ESM)"),a.info("Listening",o.address()),e.attach(o)};import{z as Xe}from"zod";var ee=class e{timeout;startupLogo;security;namespaces;constructor({timeout:t=2e3,startupLogo:o=!0,namespaces:n={},security:r=[]}={}){this.timeout=t,this.startupLogo=o,this.namespaces=n,this.security=r}addNamespace({path:t=Q,emission:o={},metadata:n=Xe.object({}),hooks:r={},examples:i={},security:a=[]}){let{namespaces:s,...d}=this,y={emission:o,examples:i,hooks:r,metadata:n,security:a};return new e({...d,namespaces:{...s,[t]:y}})}},et=({startupLogo:e,timeout:t,security:o,emission:n,examples:r,hooks:i,metadata:a}={})=>new ee({startupLogo:e,timeout:t,security:o}).addNamespace({emission:n,examples:r,metadata:a,hooks:i});import{init as tt,last as ot}from"ramda";import{z as B}from"zod";var te=class extends Error{name="IOSchemaError"},L=class extends te{constructor(o){super(ce(o));this.originalError=o}name="InputValidationError"},_=class extends te{constructor(o){super(ce(o));this.originalError=o}name="OutputValidationError"};var oe=class{},ne=class extends oe{#t;#r;#o;#e;#n;#i;constructor(t){super(),this.#t=t.event,this.#r=t.ns||Q,this.#o=t.input,this.#e="output"in t?t.output:void 0,this.#n=[],this.#i=t.handler}getEvent(){return this.#t}getNamespace(){return this.#r}getSchema(t){return t==="input"?this.#o:this.#e}#s(t){let o=this.#e?tt(t):t;try{return this.#o.parse(o)}catch(n){throw n instanceof B.ZodError?new L(n):n}}#a(t){if(this.#e)try{return B.function(this.#e,B.void()).parse(ot(t),{path:[Math.max(0,t.length-1)]})}catch(o){throw o instanceof B.ZodError?new L(o):o}}#c(t){if(this.#e)try{return this.#e.parse(t)}catch(o){throw o instanceof B.ZodError?new _(o):o}}async execute({params:t,logger:o,...n}){let r=this.#s(t);o.debug(`${this.#t}: parsed input (${this.#e?"excl.":"no"} ack)`,r);let i=this.#a(t),a=await this.#i({input:r,logger:o,...n}),s=this.#c(a);i&&s&&(o.debug(`${this.#t}: parsed output`,s),i(...s))}example(t,o){return this.#n.push({variant:t,payload:o}),this}getExamples(t){return this.#n.filter(o=>o.variant===t).map(({payload:o})=>o)}};var me=class{constructor(t){this.config=t}build(t){return new ne(t)}};import je from"typescript";import{range as ze}from"ramda";import Oe from"typescript";import{z as O}from"zod";var p=Oe.factory,V=[p.createModifier(Oe.SyntaxKind.ExportKeyword)],ue=(e,t,o=3)=>{if(!t)return O.function(e,O.void());let n=O.function(t,O.void()),r=e._def.rest;if(!r||o<=0)return O.function(O.tuple([...e.items,n]),O.void());let i=ze(0,o).map(a=>{let s=[...e.items].concat(ze(1,a+1).map(d=>r.describe(`${r.description||"rest"}${d}`))).concat(n);return O.function(O.tuple(s),O.void())});return O.union(i)};import m from"typescript";import{z as ie}from"zod";var D=(e,{onEach:t,rules:o,onMissing:n,ctx:r={}})=>{let i=o[e._def.typeName],s=i?i(e,{...r,next:y=>D(y,{ctx:r,onEach:t,rules:o,onMissing:n})}):n(e,r),d=t&&t(e,{prev:s,...r});return d?{...s,...d}:s};import I from"typescript";var{factory:re}=I,F=(e,t)=>{I.addSyntheticLeadingComment(e,I.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},le=(e,t,o)=>{let n=re.createTypeAliasDeclaration(void 0,re.createIdentifier(t),void 0,e);return o&&F(n,o),n},ke=(e,t)=>{let o=I.createSourceFile("print.ts","",I.ScriptTarget.Latest,!1,I.ScriptKind.TS);return I.createPrinter(t).printNode(I.EmitHint.Unspecified,e,o)},nt=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ce=e=>nt.test(e)?re.createIdentifier(e):re.createStringLiteral(e);var{factory:c}=m,rt={[m.SyntaxKind.AnyKeyword]:"",[m.SyntaxKind.BigIntKeyword]:BigInt(0),[m.SyntaxKind.BooleanKeyword]:!1,[m.SyntaxKind.NumberKeyword]:0,[m.SyntaxKind.ObjectKeyword]:{},[m.SyntaxKind.StringKeyword]:"",[m.SyntaxKind.UndefinedKeyword]:void 0,[m.SyntaxKind.UnknownKeyword]:void 0},it=({value:e})=>c.createLiteralTypeNode(typeof e=="number"?c.createNumericLiteral(e):typeof e=="boolean"?e?c.createTrue():c.createFalse():c.createStringLiteral(e)),st=({shape:e},{direction:t,next:o,optionalPropStyle:{withQuestionMark:n}})=>{let r=Object.entries(e).map(([i,a])=>{let s=t==="out"&&H(a)?a instanceof ie.ZodOptional:a.isOptional(),d=c.createPropertySignature(void 0,Ce(i),s&&n?c.createToken(m.SyntaxKind.QuestionToken):void 0,o(a));return a.description&&F(d,a.description),d});return c.createTypeLiteralNode(r)},at=({element:e},{next:t})=>c.createArrayTypeNode(t(e)),ct=({options:e})=>c.createUnionTypeNode(e.map(t=>c.createLiteralTypeNode(c.createStringLiteral(t)))),Me=(e,{next:t})=>c.createUnionTypeNode(e.options.map(t)),dt=(e,t)=>t instanceof ie.ZodDate?new Date:rt?.[e.kind],pt=(e,{next:t,direction:o})=>{let n=e.innerType(),r=t(n),i=e._def.effect;if(o==="out"&&i.type==="transform"){let a=q(e,dt(r,n)),s={number:m.SyntaxKind.NumberKeyword,bigint:m.SyntaxKind.BigIntKeyword,boolean:m.SyntaxKind.BooleanKeyword,string:m.SyntaxKind.StringKeyword,undefined:m.SyntaxKind.UndefinedKeyword,object:m.SyntaxKind.ObjectKeyword};return c.createKeywordTypeNode(a&&s[a]||m.SyntaxKind.AnyKeyword)}return r},mt=e=>c.createUnionTypeNode(Object.values(e.enum).map(t=>c.createLiteralTypeNode(typeof t=="number"?c.createNumericLiteral(t):c.createStringLiteral(t)))),ut=(e,{next:t,optionalPropStyle:{withUndefined:o}})=>{let n=t(e.unwrap());return o?c.createUnionTypeNode([n,c.createKeywordTypeNode(m.SyntaxKind.UndefinedKeyword)]):n},lt=(e,{next:t})=>c.createUnionTypeNode([t(e.unwrap()),c.createLiteralTypeNode(c.createNull())]),yt=({items:e,_def:{rest:t}},{next:o})=>c.createTupleTypeNode(e.map(o).concat(t===null?[]:c.createRestTypeNode(o(t)))),ft=({keySchema:e,valueSchema:t},{next:o})=>c.createExpressionWithTypeArguments(c.createIdentifier("Record"),[e,t].map(o)),gt=(e,{next:t})=>c.createIntersectionTypeNode([e._def.left,e._def.right].map(t)),xt=(e,{next:t})=>t(e._def.innerType),R=e=>()=>c.createKeywordTypeNode(e),bt=(e,{next:t})=>t(e.unwrap()),ht=(e,{next:t})=>t(e._def.innerType),St=(e,{next:t})=>t(e._def.innerType),Tt=(e,{next:t,direction:o})=>t(e._def[o]),Zt=()=>c.createLiteralTypeNode(c.createNull()),Nt=()=>c.createTypeReferenceNode(c.createIdentifier("Date")),At=(e,{makeAlias:t,next:o})=>t(e,()=>o(e.schema)),Et=(e,{next:t})=>{let o=e.parameters().items.map((r,i)=>c.createParameterDeclaration(void 0,void 0,c.createIdentifier(r.description?C(l(r.description)):`${r instanceof ie.ZodFunction?"cb":"p"}${i+1}`),void 0,t(r))),{rest:n}=e.parameters()._def;return n&&o.push(c.createParameterDeclaration(void 0,c.createToken(m.SyntaxKind.DotDotDotToken),c.createIdentifier(n.description?C(l(n.description)):"rest"),void 0,t(ie.array(n)))),c.createFunctionTypeNode(void 0,o,t(e.returnType()))},zt={ZodString:R(m.SyntaxKind.StringKeyword),ZodNumber:R(m.SyntaxKind.NumberKeyword),ZodBigInt:R(m.SyntaxKind.BigIntKeyword),ZodBoolean:R(m.SyntaxKind.BooleanKeyword),ZodAny:R(m.SyntaxKind.AnyKeyword),ZodVoid:R(m.SyntaxKind.VoidKeyword),ZodUnknown:R(m.SyntaxKind.UnknownKeyword),ZodDate:Nt,ZodNull:Zt,ZodArray:at,ZodTuple:yt,ZodRecord:ft,ZodObject:st,ZodLiteral:it,ZodIntersection:gt,ZodUnion:Me,ZodDefault:xt,ZodEnum:ct,ZodNativeEnum:mt,ZodEffects:pt,ZodOptional:ut,ZodNullable:lt,ZodDiscriminatedUnion:Me,ZodBranded:bt,ZodCatch:St,ZodPipeline:Tt,ZodLazy:At,ZodReadonly:ht,ZodFunction:Et},ye=(e,t)=>D(e,{rules:zt,onMissing:()=>c.createKeywordTypeNode(m.SyntaxKind.AnyKeyword),ctx:t});var Ot="root",De=["emission","actions"],fe=class{program=[];aliases={};ids={path:p.createIdentifier("path"),socket:p.createIdentifier("Socket"),socketBase:p.createIdentifier("SocketBase"),ioClient:p.createStringLiteral("socket.io-client"),emission:p.createIdentifier(l(De[0])),actions:p.createIdentifier(l(De[1]))};registry={};makeAlias(t,o,n){let r=this.aliases[t].get(o)?.name?.text;if(!r){r=`Type${this.aliases[t].size+1}`;let i=p.createLiteralTypeNode(p.createNull());this.aliases[t].set(o,le(i,r)),this.aliases[t].set(o,le(n(),r))}return p.createTypeReferenceNode(r)}constructor({config:{namespaces:t},actions:o,optionalPropStyle:n={withQuestionMark:!0,withUndefined:!0},maxOverloads:r=3}){this.program.push(p.createImportDeclaration(void 0,p.createImportClause(!0,void 0,p.createNamedImports([p.createImportSpecifier(!1,this.ids.socket,this.ids.socketBase)])),this.ids.ioClient));for(let[i,{emission:a}]of Object.entries(t)){this.aliases[i]=new Map,this.registry[i]={emission:[],actions:[]};let s={makeAlias:this.makeAlias.bind(this,i),optionalPropStyle:n};for(let[d,{schema:y,ack:N}]of Object.entries(a)){let g=ye(ue(y,N,r),{direction:"out",...s});this.registry[i].emission.push({event:d,node:g})}for(let d of o)if(d.getNamespace()===i){let y=d.getEvent(),N=d.getSchema("input"),g=d.getSchema("output"),k=ye(ue(N,g,r),{direction:"in",...s});this.registry[i].actions.push({event:y,node:k})}}for(let i in this.registry){let a=l(i)||l(Ot),s=p.createVariableStatement(V,p.createVariableDeclarationList([p.createVariableDeclaration(this.ids.path,void 0,void 0,p.createStringLiteral($(i)))],je.NodeFlags.Const));F(s,`@desc The actual path of the ${a} namespace`);let d=Object.entries(this.registry[i]).map(([N,g])=>p.createInterfaceDeclaration(V,l(N),void 0,void 0,g.map(({event:k,node:T})=>p.createPropertySignature(void 0,k,void 0,T)))),y=p.createTypeAliasDeclaration(V,this.ids.socket,void 0,p.createTypeReferenceNode(this.ids.socketBase,[p.createTypeReferenceNode(this.ids.emission),p.createTypeReferenceNode(this.ids.actions)]));F(y,`@example const socket: ${a}.${this.ids.socket.text} = io(${a}.${this.ids.path.text})`),this.program.push(p.createModuleDeclaration(V,p.createIdentifier(a),p.createModuleBlock([s,...this.aliases[i].values(),...d,y]),je.NodeFlags.Namespace))}}print(t){return this.program.map((o,n)=>ke(o,n<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(` `)}};import{z as K}from"zod";import kt from"yaml";var se=class{document;constructor(t){this.document={asyncapi:"3.0.0",...t,servers:{},channels:{},components:{}}}addServer(t,o){return this.document.servers={...this.document.servers,[t]:o},this}addChannel(t,o){return this.document.channels={...this.document.channels,[t]:o},this}addOperation(t,o){return this.document.operations={...this.document.operations,[t]:o},this}addSecurityScheme(t,o){return this.document.components={...this.document.components,securitySchemes:{...this.document.components?.securitySchemes,[t]:o}},this}getSpec(){return this.document}getSpecAsJson(t,o){return JSON.stringify(this.document,t,o)}getSpecAsYaml(){return kt.stringify(this.document)}};import ge from"node:assert/strict";import{concat as Ct,type as Mt,fromPairs as Ie,map as Ke,mergeDeepWith as jt,toLower as Dt,union as It,xprod as we}from"ramda";import{z as M}from"zod";function w(e){return"$ref"in e}var wt={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},vt=({_def:{innerType:e,defaultValue:t}},{next:o})=>({...o(e),default:t()}),Rt=({_def:{innerType:e}},{next:t})=>t(e),ve=()=>({format:"any"}),Kt=({options:e},{next:t})=>({oneOf:e.map(t)}),Pt=({options:e,discriminator:t},{next:o})=>({discriminator:t,oneOf:Array.from(e.values()).map(o)}),Ut=e=>{let[t,o]=e.filter(r=>!w(r)&&r.type==="object"&&Object.keys(r).every(i=>["type","properties","required","examples"].includes(i)));ge(t&&o,"Can not flatten objects");let n={type:"object"};return(t.properties||o.properties)&&(n.properties=jt((r,i)=>Array.isArray(r)&&Array.isArray(i)?Ct(r,i):r===i?i:ge.fail("Can not flatten properties"),t.properties||{},o.properties||{})),(t.required||o.required)&&(n.required=It(t.required||[],o.required||[])),n},$t=({_def:{left:e,right:t}},{next:o})=>{let n=[e,t].map(o);try{return Ut(n)}catch{}return{allOf:n}},Lt=(e,{next:t})=>t(e.unwrap()),Ft=(e,{next:t})=>t(e._def.innerType),Ht=(e,{next:t})=>{let o=t(e.unwrap());return w(o)||(o.type=Ue(o)),o},Pe=e=>{let t=Dt(Mt(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Re=e=>({type:Pe(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),_t=({value:e})=>({type:Pe(e),const:e}),Bt=(e,{direction:t,next:o})=>{let n=Object.keys(e.shape),r=s=>t==="out"&&H(s)?s instanceof M.ZodOptional:s.isOptional(),i=n.filter(s=>!r(e.shape[s])),a={type:"object"};return n.length&&(a.properties=ae(e,o)),i.length&&(a.required=i),a},Vt=()=>({type:"null"}),Wt=()=>({type:"boolean"}),qt=()=>({type:"integer",format:"bigint"}),Yt=e=>e.every(t=>t instanceof M.ZodLiteral),Jt=({keySchema:e,valueSchema:t},{next:o})=>{if(e instanceof M.ZodEnum||e instanceof M.ZodNativeEnum){let n=Object.values(e.enum),r={type:"object"};return n.length&&(r.properties=ae(M.object(Ie(we(n,[t]))),o),r.required=n),r}if(e instanceof M.ZodLiteral)return{type:"object",properties:ae(M.object({[e.value]:t}),o),required:[e.value]};if(e instanceof M.ZodUnion&&Yt(e.options)){let n=Ke(i=>`${i.value}`,e.options),r=Ie(we(n,[t]));return{type:"object",properties:ae(M.object(r),o),required:n}}return{type:"object",additionalProperties:o(t)}},Qt=({_def:e,element:t},{next:o})=>{let n={type:"array",items:o(t)};return e.minLength&&(n.minItems=e.minLength.value),e.maxLength&&(n.maxItems=e.maxLength.value),n},Gt=({items:e,_def:{rest:t}},{next:o})=>({type:"array",items:e.length?e.map(o):void 0,additionalItems:t===null?!1:o(t)}),Xt=({isEmail:e,isURL:t,minLength:o,maxLength:n,isUUID:r,isCUID:i,isCUID2:a,isULID:s,isIP:d,isEmoji:y,isDatetime:N,_def:{checks:g}})=>{let k=g.find(S=>S.kind==="regex"),T=g.find(S=>S.kind==="datetime"),Z=k?k.regex:T?T.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,h={type:"string"},P={"date-time":N,email:e,url:t,uuid:r,cuid:i,cuid2:a,ulid:s,ip:d,emoji:y};for(let S in P)if(P[S]){h.format=S;break}return o!==null&&(h.minLength=o),n!==null&&(h.maxLength=n),Z&&(h.pattern=Z.source),h},eo=e=>{let t=e._def.checks.find(({kind:d})=>d==="min"),o=e.minValue===null?e.isInt?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:e.minValue,n=t?t.inclusive:!0,r=e._def.checks.find(({kind:d})=>d==="max"),i=e.maxValue===null?e.isInt?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:e.maxValue,a=r?r.inclusive:!0,s={type:e.isInt?"integer":"number",format:e.isInt?"int64":"double"};return n?s.minimum=o:s.exclusiveMinimum=o,a?s.maximum=i:s.exclusiveMaximum=i,s},ae=({shape:e},t)=>Ke(t,e),to=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return e.format==="date"?new Date:wt?.[t]},Ue=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},oo=(e,{direction:t,next:o})=>{let n=o(e.innerType()),{effect:r}=e._def;if(t==="out"&&r.type==="transform"&&!w(n)){let i=q(e,to(n));return i&&["number","string","boolean"].includes(i)?{type:i}:o(M.any())}if(t==="in"&&r.type==="preprocess"&&!w(n)){let{type:i,...a}=n;return{...a,format:`${a.format||i} (preprocessed)`}}return n},no=(e,{direction:t,next:o})=>o(e._def[t]),ro=(e,{next:t})=>t(e.unwrap()),io=()=>({format:"date"}),xe={ZodString:Xt,ZodNumber:eo,ZodBigInt:qt,ZodBoolean:Wt,ZodNull:Vt,ZodArray:Qt,ZodTuple:Gt,ZodRecord:Jt,ZodObject:Bt,ZodLiteral:_t,ZodIntersection:$t,ZodUnion:Kt,ZodAny:ve,ZodDefault:vt,ZodEnum:Re,ZodNativeEnum:Re,ZodEffects:oo,ZodOptional:Lt,ZodNullable:Ht,ZodDiscriminatedUnion:Pt,ZodBranded:ro,ZodCatch:Rt,ZodPipeline:no,ZodReadonly:Ft,ZodDate:io,ZodUnknown:ve},be=(e,{direction:t,prev:o})=>{if(w(o))return{};let{description:n}=e,r=o.type!==void 0,i=t==="out"&&H(e),a=r&&!i&&e.isNullable(),s={};return n&&(s.description=n),a&&(s.type=Ue(o)),s},he=e=>ge.fail(`Zod type ${e.constructor.name} is unsupported.`),so=(e,t)=>{if(w(e)||!t)return e;if(e.type==="array"&&e.items&&Array.isArray(e.items))for(let o of t)for(let n=0;n<o.length;n++){let r=e.items[n];r&&!w(r)&&(r.examples=[...r.examples||[],o[n]])}return e},W=({event:e,schema:t,examples:o,direction:n,isAck:r})=>({name:r?void 0:e,title:r?`Acknowledgement for ${e}`:e,payload:so(D(t,{ctx:{direction:n},onMissing:he,onEach:be,rules:xe}),o),examples:o&&o.length?o.map(i=>({payload:i})):void 0}),Se=({direction:e,channelId:t,messageId:o,ackId:n,event:r,ns:i,securityIds:a})=>({action:e==="out"?"send":"receive",channel:{$ref:`#/channels/${t}`},messages:[{$ref:`#/channels/${t}/messages/${o}`}],title:r,summary:`${e==="out"?"Outgoing":"Incoming"} event ${r}`,description:`The message ${e==="out"?"produced":"consumed"} by the application within the ${i} namespace`,security:a&&a.length?a.map(s=>({$ref:`#/components/securitySchemes/${s}`})):void 0,reply:n?{address:{location:"$message.payload#",description:"Last argument: acknowledgement handler"},channel:{$ref:`#/channels/${t}`},messages:[{$ref:`#/channels/${t}/messages/${n}`}]}:void 0});var $e=(e,t)=>t&&(Array.isArray(t)?t:[t]).map(o=>o[e]).filter(o=>!!o),Te=class extends se{#t(){let t={onEach:be,onMissing:he,rules:xe,ctx:{direction:"in"}};return{bindingVersion:"0.1.0",method:"GET",headers:D(K.object({connection:K.literal("Upgrade").optional(),upgrade:K.literal("websocket").optional()}),t),query:{...D(K.object({EIO:K.literal("4").describe("The version of the protocol"),transport:K.enum(["polling","websocket"]).describe("The name of the transport"),sid:K.string().optional().describe("The session identifier")}),t),externalDocs:{description:"Engine.IO Protocol",url:"https://socket.io/docs/v4/engine-io-protocol/"}}}}constructor({actions:t,config:{namespaces:o,security:n},title:r,version:i,documentId:a,description:s,contact:d,license:y,servers:N={}}){super({info:{title:r,version:i,contact:d,license:y,description:s},id:a,defaultContentType:"text/plain"});let g=[];for(let[T,Z]of Object.entries(n)){let h=C(l(`server security ${T}`));this.addSecurityScheme(h,Z),g.push(h)}for(let T in N){let Z=new URL(N[T].url);this.addServer(T,{description:N[T].description,host:Z.host,pathname:Z.pathname,protocol:Z.protocol.slice(0,-1),security:g.length?g.map(h=>({$ref:`#/components/securitySchemes/${h}`})):void 0}),this.document.id||(this.document.id=`urn:${Z.host.split(".").concat(Z.pathname.slice(1).split("/")).join(":")}`)}let k=this.#t();for(let[T,{emission:Z,examples:h,security:P}]of Object.entries(o)){let S=$(T),x=l(S)||"Root",j={},f=[];for(let[u,A]of Object.entries(P)){let z=C(l(`${x} security ${u}`));this.addSecurityScheme(z,A),f.push(z)}for(let[u,{schema:A,ack:z}]of Object.entries(Z)){let E=C(l(`${x} outgoing ${u}`)),b=C(l(`${x} ack for outgoing ${u}`));j[E]=W({event:u,schema:A,direction:"out",examples:$e("payload",h[u])}),z&&(j[b]=W({event:u,schema:z,examples:$e("ack",h[u]),direction:"in",isAck:!0})),this.addOperation(l(`${x} send operation ${u}`),Se({direction:"out",event:u,channelId:x,messageId:E,ackId:z&&b,ns:S}))}for(let u of t)if(u.getNamespace()===S){let A=u.getEvent(),z=C(l(`${x} incoming ${A}`)),E=C(l(`${x} ack for incoming ${A}`)),b=u.getSchema("output");j[z]=W({event:A,schema:u.getSchema("input"),examples:u.getExamples("input"),direction:"in"}),b&&(j[E]=W({event:A,schema:b,examples:u.getExamples("output"),direction:"out",isAck:!0})),this.addOperation(l(`${x} recv operation ${A}`),Se({direction:"in",channelId:x,messageId:z,event:A,ns:S,ackId:b&&E,securityIds:f}))}this.addChannel(x,{address:S,title:`Namespace ${S}`,bindings:{ws:k},messages:j})}}};export{oe as AbstractAction,me as ActionsFactory,ee as Config,Te as Documentation,L as InputValidationError,fe as Integration,_ as OutputValidationError,Ge as attachSockets,et as createSimpleConfig};