UNPKG

serverless-aws-lambda

Version:

AWS Application Load Balancer and API Gateway - Lambda dev tool for Serverless. Allows Express synthax in handlers. Supports packaging, local invoking and offline ALB, APG, S3, SNS, SQS, DynamoDB Stream server mocking.

10 lines 96.8 kB
var w=(t,e)=>()=>(t&&(e=t(t=0)),e);var Er=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var X,wr,xr,B,Rr,kr,Ir,Pr,Nr,Tr,Lr,b,T=w(()=>{"use strict";X=!1,wr=t=>{X=t},xr=()=>X,B=(t,e)=>{X&&console.log(`\x1B[${t}m${e}\x1B[0m`)},Rr=t=>console.log(`\x1B[31m${t}\x1B[0m`),kr=t=>B("32",t),Ir=t=>B("33",t),Pr=t=>B("36",t),Nr=t=>B("90",t),Tr=t=>B("94",t),Lr=t=>X?console.log(t):void 0,b={GREEN:kr,YELLOW:Ir,CYAN:Pr,BR_BLUE:Tr,RED:Rr,GREY:Nr,setDebug:wr,getDebug:xr,info:Lr}});var Dr,Re,k,F=w(()=>{"use strict";T();Dr=["@invoke","@url"],Re=t=>b.YELLOW(`Invalid Request Headers or query string for ${t}`),k=class t{static handlers=[];static PORT=0;static ip="127.0.0.1";debug=!1;constructor(e){this.debug=e.debug}static parseNameFromUrl(e){let r=e.split("/"),n=Dr.includes(r[1])?r[2]:r[3];if(n=decodeURIComponent(n),n.includes(":function:")){let s=n.split(":function:");n=s[s.length-1]}if(n.includes(":")){let s=n.split(":");s.length==2&&(n=s[0])}return n}static getHandlerByName(e){if(!e)return;let r=t.parseNameFromUrl(e);return t.handlers.find(n=>n.name==r||n.outName==r)}static#e=(e,r)=>{let n=[],s=r.toString();return e.forEach(i=>{let a=i.some(({Key:o,Value:l})=>{if(o){let c=r[o.toLowerCase()];return l?c?c.includes(l.toLowerCase()):!1:(b.RED("alb conditions query must have 'Value' when 'Key' is specified"),!1)}else if(l)return s==l.toLowerCase()});n.push(a)}),n.every(i=>i===!0)};static findHandler=({method:e,path:r,kind:n,headers:s,query:i})=>{let a,o=n?.toLowerCase();if(t.handlers.find(c=>c.endpoints.filter(p=>n?p.kind==o:p).find(p=>{if(p.kind=="apg"){let m=p.paths.includes(r)&&(p.methods.includes("ANY")||p.methods.includes(e));if(m){let g=[m];p.headers&&g.push(p.headers.every(y=>y in s)),p.querystrings&&g.push(p.querystrings.every(y=>y in i));let h=g.every(y=>y===!0);return h?a={event:p,handler:c}:Re(c.name),h}}let d=p.paths.includes(r)&&(p.methods.includes("ANY")||p.methods.includes(e));if(d){let u=[d];if(p.query&&u.push(t.#e(p.query,i)),p.header){let g=p.header.every(h=>s[h.name.toLowerCase()]&&h.values.some(y=>s[h.name.toLowerCase()].find(v=>v==y)));u.push(g)}let m=u.every(g=>g===!0);return m?a={event:p,handler:c}:Re(c.name),m}})))return a;{let c=r.split("/").filter(Boolean).length;if(t.handlers.find(d=>d.endpoints.filter(u=>n?u.kind==o:u).find(u=>{let g=u.paths.find((h,y)=>{let v=r.match(u.pathsRegex[y]);return u.kind=="alb"||h.includes("+")||h=="/*"?v:v&&h.split("/").filter(Boolean).length==c})&&(u.methods.includes("ANY")||u.methods.includes(e));if(g){let h=[g];if(u.kind=="alb"){if(u.query&&h.push(t.#e(u.query,i)),u.header){let v=u.header.every(f=>s[f.name.toLowerCase()]&&f.values.some(S=>s[f.name.toLowerCase()].find(x=>x==S)));h.push(v)}}else u.headers&&h.push(u.headers.every(v=>v in s)),u.querystrings&&h.push(u.querystrings.every(v=>v in i));let y=h.every(v=>v===!0);return y?a={event:u,handler:d}:Re(d.name),y}})))return a}};addHandler(e){let r=t.handlers.findIndex(n=>n.name==e.name&&n.esOutputPath==e.esOutputPath);r==-1?(t.handlers.push(e),e.endpoints.length?e.endpoints.forEach(n=>{let s=n.kind=="alb"?"36":"35";n.paths.forEach(i=>{this.#t(n.methods.join(" "),i,s)})}):this.#t("ANY",`/@invoke/${e.name}`),e.url&&this.#t("ANY",`/@url/${e.name}`,"34")):t.handlers[r].runtime.startsWith("n")&&(t.handlers[r].clear(),t.handlers[r]=e)}#t(e,r,n="90"){let s=`${e} http://localhost:${t.PORT}${r}`;console.log(`\x1B[${n}m${s}\x1B[0m`)}}});import Or from"http";var jr,We,$e,Mr,Hr,Ue,ke,Ve,_e=w(()=>{"use strict";jr=t=>{switch(t.kind){case"sns":return"@sns/parsed/";case"sqs":return"@sqs";case"lambda":return`@invoke/${t.name}/`;default:break}},We=(t,e)=>{let r=jr(e);if(!r)return;let n={"Content-Type":e.kind=="sqs"?"application/x-www-form-urlencoded":"application/json"};return Or.request(`http://localhost:${t}/${r}`,{method:"POST",headers:n})},$e=({event:t,payload:e,requestId:r,lambdaName:n,success:s})=>{let i={version:"1.0",timestamp:"2023-02-25T13:25:04.688Z",requestContext:{requestId:r,functionArn:`arn:aws:lambda:eu-west-3:000000000000:function:${n}:$LATEST`,condition:s?"Success":"RetriesExhausted",approximateInvokeCount:1},requestPayload:t,responseContext:{statusCode:200,executedVersion:"$LATEST"},responsePayload:e};return s||(i.responseContext.functionError="Unhandled"),JSON.stringify(i)},Mr=({topicName:t,event:e,payload:r,requestId:n,success:s,lambdaName:i})=>{let a="";if(s)a=$e({event:e,payload:r,requestId:n,success:s,lambdaName:i});else if(typeof e=="string")a=e;else try{a=JSON.stringify(e)}catch(l){console.log(l)}let o={TopicArn:`arn:aws:sns:eu-west-3:000000000000:${t}`,Message:a,Action:"Publish",Version:"2010-03-31",MessageAttributes:{}};return s||(o.MessageAttributes={RequestID:{Type:"String",Value:n},ErrorCode:{Type:"String",Value:"200"},ErrorMessage:{Type:"String",Value:r.errorMessage}}),JSON.stringify(o)},Hr=({destination:t,event:e,payload:r,requestId:n,lambdaName:s,success:i})=>{let a=new URLSearchParams;a.append("QueueUrl",t.name),a.append("Action","SendMessage");let o=e;try{o=JSON.stringify(o)}catch{}return a.append("MessageBody",o),i||(a.append("MessageAttribute.1.Name","RequestID"),a.append("MessageAttribute.1.Value.StringValue",n),a.append("MessageAttribute.1.Value.DataType","String"),a.append("MessageAttribute.1.Name","ErrorCode"),a.append("MessageAttribute.1.Value.StringValue","200"),a.append("MessageAttribute.1.Value.DataType","Number"),a.append("MessageAttribute.1.Name","ErrorMessage"),a.append("MessageAttribute.1.Value.StringValue",r.errorMessage),a.append("MessageAttribute.1.Value.DataType","String")),a.toString()},Ue=({destination:t,event:e,payload:r,requestId:n,lambdaName:s,success:i})=>{switch(t.kind){case"sns":return Mr({topicName:t.name,event:e,payload:r,requestId:n,success:i,lambdaName:s});case"lambda":return $e({event:e,payload:r,requestId:n,lambdaName:s,success:i});case"sqs":return Hr({destination:t,event:e,payload:r,requestId:n,lambdaName:s,success:i});default:return""}},ke=({destination:t,LOCAL_PORT:e,event:r,payload:n,requestId:s,lambdaName:i})=>{try{let a=We(e,t);if(!a)return;a.end(Ue({destination:t,event:r,payload:n,requestId:s,lambdaName:i,success:!1}))}catch{}},Ve=({destination:t,LOCAL_PORT:e,event:r,payload:n,requestId:s,lambdaName:i})=>{try{let a=We(e,t);if(!a)return;a.end(Ue({destination:t,event:r,payload:n,requestId:s,lambdaName:i,success:!0}))}catch{}}});import{randomUUID as qr}from"crypto";var Fr,Wr,ze,G,Ce=w(()=>{"use strict";T();_e();Fr=1080*1e3,Wr=new Set(["async","ddb","kinesis","s3","sns","sqs"]),ze=t=>typeof t?.kind=="string"?Wr.has(t.kind)||t.async:!1,G=class t{name;outName;online;endpoints;runtime;s3;sns;sqs;ddb;kinesis;documentDb;url;timeout;memorySize;environment;handlerPath;handlerName;esEntryPoint;esOutputPath;entryPoint;onError;onSuccess;onFailure;invokeSub;invokeSuccessSub;invokeErrorSub;#e;runner;static ENABLE_TIMEOUT=!0;constructor({name:e,outName:r,online:n,endpoints:s,runtime:i,timeout:a,memorySize:o,environment:l,handlerPath:c,handlerName:p,esEntryPoint:d,esOutputPath:u,entryPoint:m,s3:g,sns:h,sqs:y,ddb:v,kinesis:f,url:S,documentDb:x,invokeSub:A,invokeSuccessSub:I,invokeErrorSub:P,onError:N,onSuccess:j,onFailure:q,runner:Z}){this.name=e,this.outName=r,this.online=n,this.endpoints=s,this.runtime=i,this.s3=g,this.sns=h,this.sqs=y,this.ddb=v,this.kinesis=f,this.url=S,this.documentDb=x,this.timeout=a,this.memorySize=o,this.environment=l,this.handlerPath=c,this.handlerName=p,this.esEntryPoint=d,this.esOutputPath=u,this.entryPoint=m,this.invokeSub=A,this.invokeSuccessSub=I,this.invokeErrorSub=P,this.onError=N,this.onSuccess=j,this.onFailure=q,this.runner=Z}handleErrorDestination(e,r,n,s){if(this.runner.onComplete(s),console.error(n),this.invokeErrorSub.forEach(i=>{try{i(e,n,r)}catch{}}),ze(r)){let i={LOCAL_PORT:this.environment.LOCAL_PORT,event:e,payload:n,requestId:s,lambdaName:this.outName};this.onError&&ke({...i,destination:this.onError}),this.onFailure&&ke({...i,destination:this.onFailure})}}handleSuccessDestination(e,r,n,s){this.runner.onComplete(s),this.onSuccess&&ze(r)&&Ve({destination:this.onSuccess,LOCAL_PORT:this.environment.LOCAL_PORT,event:e,payload:n,requestId:s,lambdaName:this.outName}),this.invokeSuccessSub.forEach(i=>{try{i(e,n,r)}catch{}})}async invoke(e,r,n,s){this.runner.isMounted||(b.BR_BLUE(`\u2744\uFE0F Cold start '${this.outName}'`),await this.runner.mount());let i=qr();this.invokeSub.forEach(o=>{try{let l=o(e,r);l&&typeof l.then!="function"&&(e=l)}catch{}});let a=this.#r(i,e,r);try{let o=await new Promise(async(l,c)=>{let p;t.ENABLE_TIMEOUT&&(p=setTimeout(()=>{s?.destroy(),this.runner.onComplete(i,!0),b.RED(`'${this.outName}' | ${i}: Request failed`),c({errorType:"Unhandled",errorMessage:`${new Date().toISOString()} ${i} Task timed out after ${this.timeout} seconds`})},this.timeout*1e3));try{let d=await this.runner.invoke({event:e,awsRequestId:i,info:r,clientContext:n,response:s});l(d)}catch(d){c(d)}finally{clearTimeout(p)}});return this.handleSuccessDestination(e,r,o,i),o}catch(o){throw this.handleErrorDestination(e,r,o,i),this.runner.unmount(!0),o}finally{this.#t(),t.#n(a,this.name)}}clear=()=>{clearTimeout(this.#e),this.runner.unmount()};#t=()=>{clearTimeout(this.#e),this.#e=setTimeout(()=>{this.runner.unmount(!0)},Fr)};#r=(e,r,n)=>{let s=r?.httpMethod??r?.method??"",i=r?.path??r?.rawPath??"";i&&(i=decodeURI(i));let a=`${s} ${i}`,o=new Date;b.CYAN(`${o.toLocaleDateString()} ${o.toLocaleTimeString()} requestId: ${e} | '${this.name}' ${a}`),b.GREY(this.entryPoint);let l="";return typeof n?.kind=="string"&&(l=` (${n.kind.toUpperCase()})`),b.YELLOW(`input payload${l}`),b.info(r),process.hrtime()};static#n=(e,r)=>{let n=process.hrtime(e),s=`${n[0]},${n[1]}s`,i=`\u231B\uFE0F '${r}' execution time: ${s}`;setTimeout(()=>{b.YELLOW(i)},400)}}});var Ke,Qe,Je,Be,ee=w(()=>{"use strict";Ke="<html><head><title>502 Bad Gateway</title></head><body><center><h1>502 Bad Gateway</h1></center></body></html>",Qe="<html><head><title>404 Not Found</title></head><body><center><h1>404 Not Found</h1></center></body></html>",Je="<html><head><title>400 Request Header Or Cookie Too Large</title></head><body><center><h1>400 Bad Request</h1></center><center>Request Header Or Cookie Too Large</center></body></html>",Be="<html><head><title>400 Bad Request</title></head><body><center><h1>400 Bad Request</h1></center></body></html>"});var Ge,D,_=w(()=>{"use strict";W();T();Ge="application/vnd.awslambda.http-integration-response",D=class t{buffer;_isHttpIntegrationResponse;_metaDelimiter;_endDelimiter;_ct;_isStreamResponse=!0;#e;static codec=new TextDecoder;static splitMessage=(e,r)=>{if(!e)return;let n=Array.from(e.values()),s=null;if(r)s=r;else for(let i=0;i<n.length;i++)if(n[i]===0&&[n[i+1],n[i+2],n[i+3],n[i+4],n[i+5],n[i+6],n[i+7]].every(l=>l===0)){s=i;break}if(s)return new Uint8Array(n.slice(0,s))};constructor(e){this._isHttpIntegrationResponse=!1,this._metaDelimiter=0,this._endDelimiter=0,this.#e=e}setHeader(e,r){this._isHttpIntegrationResponse=!this.buffer&&r==Ge&&(!this._ct||this._ct==Ge),this._ct=r}write(e,r){!this._isHttpIntegrationResponse&&!this._metaDelimiter&&(this._metaDelimiter=e.byteLength),this.#t(e)}end(e){this.buffer&&(this._endDelimiter=this.buffer.byteLength),e&&this.#t(e)}destroy(){}#t(e){this.buffer=typeof this.buffer>"u"?e:Buffer.concat([this.buffer,e])}getParsedResponse(){if(!this.#e)return;let e=this.#e.kind;if(e=="alb")return this.#r();if(e=="url")return this.#i();if(e=="apg")return this.#n()}#r(){let e=this._isHttpIntegrationResponse?t.splitMessage(this.buffer):this.buffer,r;return e&&(r=this.#s(e)),r}#n(){if(this._isHttpIntegrationResponse)return b.RED("awslambda.HttpResponseStream.from() is not supported with API Gateway"),{statusCode:500,headers:{"Content-Type":E.contentType.json},body:E.httpErrMsg};if(this.buffer)return this.#s(this.buffer)}#i(){let e=t.splitMessage(this.buffer,this._isHttpIntegrationResponse?void 0:this._metaDelimiter),r;return e&&(r=this.#s(e)),r}#s(e){let r=t.codec.decode(e);if(typeof r=="string")try{r=JSON.parse(r)}catch{}return r}}});import{randomUUID as $r}from"crypto";var Ur,Vr,te,Ze,$,re,ne,Xe,z,se,ie,ae,oe,et,Ye,_r,zr,tt,rt,C=w(()=>{"use strict";_();ee();Ur=["GET","HEAD","POST","PUT","DELETE","PATCH"],Vr=JSON.stringify({Message:null}),te=t=>{if(t)try{let e=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(e)}catch{return new Error("InvalidRequestContentException")}},Ze=(t,e)=>{if(!Ur.includes(e))return t.statusCode=403,t.setHeader("Content-Type","application/json"),t.end(Vr),!0},$=async(t,e)=>{let r;return t.on("data",s=>{r=typeof r>"u"?s:Buffer.concat([r,s])}),await new Promise(s=>{t.on("end",async()=>{s(r?r.toString(e?"base64":"utf-8"):void 0)})})},re=t=>{let e;try{e=JSON.parse(t)}catch(r){e&&e.length?e=r:e={}}return e},ne=t=>t instanceof D,Xe=t=>{let e,r=Buffer.from(t).toString();try{e=JSON.parse(r)}catch{e=r}return e},z=t=>{let e=$r();return t.setHeader("x-amzn-RequestId",e),e},se=t=>JSON.stringify({Type:"User",message:`Could not parse request body into json: Could not parse payload into json: ${t}: was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')`}),ie=JSON.stringify({Type:null,message:"Client context must be a valid Base64-encoded JSON object."}),ae=t=>JSON.stringify({Type:"User",message:`Function not found: arn:aws:lambda:region:000000000000:function:${t}`}),oe=t=>{t.writableFinished||(t.statusCode=502,t.headersSent||t.setHeader("Content-Type","application/json"),t.end("Internal Server Error"))},et=t=>t.byteLength==8&&Array.from(t.values()).every(e=>e===0),Ye=new Error(Je),_r={alb:65536,apg:10240,url:10240},zr=16376,tt=(t,e)=>{if(!t.host)throw new Error(Be);let r=0,n=_r[e],s=Object.entries(t);if(e=="alb"?s.forEach(i=>{let[a,o]=i;if(o=="x-mock-type")return;let l=a.length+o.length;if(l>zr)throw Ye;r=r+l}):s.forEach(i=>{let[a,o]=i;o!="x-mock-type"&&(r=r+a.length+o.length)}),r>n)throw Ye},rt=t=>t.charAt(0).toUpperCase()+t.slice(1)});var E,W=w(()=>{"use strict";C();E=class t{static apiId="";static accountId="";static port=3e3;static serve;static contentType={json:"application/json",text:"text/plain; charset=utf-8",octet:"application/octet-stream"};static keepAlive=["Connection","keep-alive"];static dummyHost="http://localhost:3003";static httpErrMsg='{"message":"Internal Server Error"}';static apigJsonParseErrMsg='{"message":"[Unknown error parsing request body]"}';static apigForbiddenErrMsg='{"message":"Forbidden"}';static amzMsgNull='{"message":null}';static apgTimeoutMsg='{"message": "Endpoint request timed out"}';static unavailable='{"message":"Service Unavailable"}';static timeoutRegex=/after.\d+.*seconds/;static apgRequestTimeout=30;static normalizeHeaderKey=e=>e.toLowerCase().split("-").map(rt).join("-");static getMultiValueHeaders=e=>{let r={},n=e.filter((i,a)=>a%2==0).map(i=>i.toLowerCase()),s=e.filter((i,a)=>a%2!==0);return n.forEach((i,a)=>{i!="x-mock-type"&&(r[i]?r[i].push(s[a]):r[i]=[s[a]])}),r};static getIsBase64Encoded=e=>{let r=e["content-type"];return e["content-encoding"]||!r?!0:!(r.startsWith("application/json")||r.startsWith("application/xml")||r.startsWith("application/javascript")||r.startsWith("text/"))};static knownHeaders=["accept","accept-encoding","user-agent","host","via","content-length"];static getApiGV1Headers(e,r){let{rawHeaders:n}=e,s,i={"X-Forwarded-For":e.socket.remoteAddress,"X-Forwarded-Proto":"http","X-Forwarded-Port":String(t.port)};for(let c=0;c<n.length;){let p=n[c],d=p.toLowerCase();if(["connection","x-mock-type"].includes(d)){c=c+2;continue}this.knownHeaders.includes(d)&&(p=this.normalizeHeaderKey(d));let u=n[c+1];i[p]=u,d=="x-api-key"&&(s=u),c=c+2}let a={};for(let c of Object.keys(i).sort((p,d)=>p.localeCompare(d)))a[c]=i[c];let o={"X-Forwarded-For":[e.socket.remoteAddress],"X-Forwarded-Proto":["http"],"X-Forwarded-Port":[String(t.port)]};for(let c=0;c<n.length;){let p=n[c],d=p.toLowerCase();if(["connection","x-mock-type"].includes(d)){c=c+2;continue}this.knownHeaders.includes(d)&&(p=this.normalizeHeaderKey(d));let u=n[c+1];o[p]?o[p].push(u):o[p]=[u],c=c+2}let l={};for(let c of Object.keys(o).sort((p,d)=>p.localeCompare(d)))l[c]=o[c];return{headers:a,multiValueHeaders:l,apiKey:s}}static getCustomHeaders(e,r){let{headers:n}=e;return delete n["x-mock-type"],delete n.connection,{"X-Forwarded-For":e.socket.remoteAddress,"X-Forwarded-Proto":"http","X-Forwarded-Port":String(t.port),...n}}static getPathParameters(e,r){let n=e.paths[0].split("/"),s=r.pathname.split("/"),i={};return n.forEach((a,o)=>{a.startsWith("{")&&a.endsWith("}")&&!a.endsWith("+}")&&(i[a.slice(1,-1)]=s[o])}),i}static normalizeSearchParams=(e,r)=>{let n={};Array.from(e.keys()).forEach(a=>{let o=e.getAll(a).map(c=>c.toLowerCase()),l=a.toLowerCase();o?n[l]?n[l].push(...o):n[l]=o:n[l]||(n[l]=void 0)});let s="",i=r.indexOf("?");return i!=-1&&(s=r.slice(i+1)),n.toString=()=>s,n};static getMultiValueQueryStringParameters=e=>{let r={};e.delete("x_mock_type");for(let n of Array.from(new Set(e.keys())))r[n]=e.getAll(n).map(encodeURI);return r};static isEndpointTimeoutError=e=>{if(!e)return;let r=e.match(this.timeoutRegex)?.[0];if(r){let n=r.split(" ")[1];if(!isNaN(n))return Number(n)>=t.apgRequestTimeout}}}});var ce,nt=w(()=>{"use strict";W();T();ee();ce=class t extends E{res;payload;mockEvent;constructor({res:e,req:r,body:n,mockEvent:s,multiValueHeaders:i,isBase64Encoded:a,lambdaName:o}){super(),this.res=e,this.mockEvent=s,this.payload=t.#t({req:r,mockEvent:s,multiValueHeaders:i,isBase64Encoded:a,body:n,lambdaName:o})}static#e=new Error;returnError=()=>this.res.writableFinished?!0:(this.res.shouldKeepAlive=!1,this.res.writeHead(502,[["Server","awselb/2.0"],["Date",new Date().toUTCString()],["Content-Type","text/html"],["Content-Length","110"],t.keepAlive]),this.res.end(Ke));sendResponse=e=>{let r=[["Server","awselb/2.0"],["Date",new Date().toUTCString()]],n=[],s=200,i;if(!e||typeof e.statusCode!="number")throw b.RED(`Valid ALB Lambda response must be an object which includes a valid 'statusCode' number. Received:`),console.log(e),t.#e;s=e.statusCode;let{statusDescription:a}=e;if(typeof a=="string"){let u=a.split(" ");if(isNaN(u[0]))b.RED("statusDescription must start with a statusCode number followed by a space + status description text"),b.YELLOW("example: '200 Found'");else{let m=u.slice(1).join(" ");m.length&&(i=m)}}this.mockEvent.multiValueHeaders?e.multiValueHeaders?Object.keys(e.multiValueHeaders).filter(m=>m!=="Server"&&m!=="Date").forEach(m=>{if(Array.isArray(e.multiValueHeaders[m]))n.push([m,e.multiValueHeaders[m]]);else throw b.RED(`multiValueHeaders (${m}) values must be an array`),b.YELLOW("example:"),b.GREEN(`'${m}': ['some/value']`),t.#e}):e.headers&&b.YELLOW("An ALB Lambda with 'multiValueHeaders enabled' must return 'multiValueHeaders' instead of 'headers'"):typeof e.headers=="object"&&!Array.isArray(e.headers)?Object.keys(e.headers).filter(m=>m!=="Server"&&m!=="Date").forEach(m=>{let g=typeof e.headers[m];if(g=="string")n.push([m,e.headers[m]]);else throw b.RED(`response headers (${m}) value must be typeof string. Received: '${g}'`),new Error}):e.multiValueHeaders&&b.YELLOW("Skipping 'multiValueHeaders' as it is not enabled for you target group in serverless.yml");let o=typeof e.body;if(o!="undefined"&&o!="string")throw b.RED(`response 'body' must be a string. Receievd ${o}`),t.#e;let l=e.body;if(l&&e.isBase64Encoded){let u=Buffer.from(l,"base64").toString();if(Buffer.from(u).toString("base64")!=l)throw b.RED("response body is not properly base64 encoded"),t.#e;l=u}let c=n.findIndex(u=>u[0].toLowerCase()=="content-type");c==-1?r.push(["Content-Type",t.contentType.octet]):(r.push(["Content-Type",n[c][1]]),n.splice(c,1));let p=n.findIndex(u=>u[0].toLowerCase()=="content-length"),d=l?String(Buffer.from(l).byteLength):"0";p!=-1&&n.splice(p,1),r.push(["Content-Length",d],t.keepAlive,...n),this.res.shouldKeepAlive=!1,i?this.res.writeHead(s,i,r):this.res.writeHead(s,r),this.res.end(l)};static#t({req:e,mockEvent:r,multiValueHeaders:n,isBase64Encoded:s,body:i,lambdaName:a}){let{method:o,headers:l,url:c}=e,p=new URL(c,t.dummyHost);p.searchParams.delete("x_mock_type");let d={requestContext:{elb:{targetGroupArn:`arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/${a}-tg/49e9d65c45c6791a`}},httpMethod:o,path:p.pathname,isBase64Encoded:i?s:!1,body:i??""};return r.multiValueHeaders?(d.multiValueHeaders={"x-forwarded-for":[String(e.socket.remoteAddress)],"x-forwarded-proto":["http"],"x-forwarded-port":[String(E.port)],...n},d.multiValueQueryStringParameters=E.getMultiValueQueryStringParameters(p.searchParams)):(d.headers={"x-forwarded-for":e.socket.remoteAddress,"x-forwarded-proto":"http","x-forwarded-port":String(E.port),...l},d.queryStringParameters=t.#r(c),d.headers["x-mock-type"]&&delete d.headers["x-mock-type"]),d}static#r(e){let r=e.indexOf("?");if(r==-1)return{};let n={};return e.slice(r+1).split("&").forEach(a=>{let[o,...l]=a.split("=");n[o]=l.join("=")}),delete n.x_mock_type,n}}});import{randomUUID as st}from"crypto";var K,Ie=w(()=>{"use strict";W();T();K=class t extends E{res;mockEvent;payload;constructor({res:e,req:r,body:n,mockEvent:s,multiValueHeaders:i,isBase64Encoded:a,lambdaName:o,parsedURL:l,requestId:c}){super(),this.res=e,this.mockEvent=s,this.payload=s.version==1?t.createApgV1Event({req:r,mockEvent:s,parsedURL:l,lambdaName:o,multiValueHeaders:i,isBase64Encoded:a,requestId:c,body:n}):t.createApgV2Event({req:r,mockEvent:s,parsedURL:l,requestId:c,isBase64Encoded:a,body:n})}static skipHeaders=["connection","content"];static createApgV2Event=({req:e,mockEvent:r,parsedURL:n,requestId:s,isBase64Encoded:i,body:a})=>{let{method:o,headers:l}=e,c=t.getPathParameters(r,n),p,d=r.methods.find(S=>S==o)??"ANY",u={},m="";for(let S of Array.from(new Set(n.searchParams.keys()))){let x=n.searchParams.getAll(S);m+=`&${x.map(A=>encodeURI(`${S}=${A}`)).join("&")}`,u[S]=x.join(",")}m&&(m=m.slice(1));let g=r.paths[0]=="/*"?"$default":`${d} ${n.pathname}`,h=new Date,y="127.0.0.1",v=l.host?.startsWith("localhost")?y:l.host?l.host.split(":")[0]:y,f={version:"2.0",routeKey:g,rawPath:n.pathname,rawQueryString:m,headers:t.getCustomHeaders(e,r),requestContext:{accountId:String(t.accountId),apiId:t.apiId,domainName:`localhost:${t.port}`,domainPrefix:"localhost",http:{method:o,path:n.pathname,protocol:"HTTP/1.1",sourceIp:v,userAgent:l["user-agent"]??""},requestId:s,routeKey:g,stage:"$default",time:h.toISOString(),timeEpoch:h.getTime()}};return a?(f.body=a,f.isBase64Encoded=i):f.isBase64Encoded=!1,Object.keys(u).length&&(f.queryStringParameters=u),Object.keys(c).length&&(f.pathParameters=c),l.cookie&&(f.cookies=l.cookie.split("; ")),p=f,p.headers["x-mock-type"]&&delete p.headers["x-mock-type"],p};static createApgV1Event=({req:e,mockEvent:r,parsedURL:n,lambdaName:s,isBase64Encoded:i,requestId:a,body:o})=>{let{method:l}=e,c={};r.proxy=="httpApi"&&(c.version="1.0");let p=r.paths[0];c.resource=p,c.path=n.pathname,c.httpMethod=l;let{headers:d,multiValueHeaders:u,apiKey:m}=t.getApiGV1Headers(e,r);c.headers=d,c.multiValueHeaders=u;let g=String(e.socket.remoteAddress),h=Object.fromEntries(n.searchParams);c.queryStringParameters=Object.keys(h).length?h:null;let y=t.getMultiValueQueryStringParameters(n.searchParams);c.multiValueQueryStringParameters=Object.keys(y).length?y:null;let v=new Date,f={accountId:String(t.accountId),apiId:t.apiId,domainName:`localhost:${t.port}`,domainPrefix:"localhost",extendedRequestId:"fake-id",httpMethod:l,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:g,user:null,userAgent:e.headers["user-agent"],userArn:null},path:n.pathname,protocol:"HTTP/1.1",requestId:a,requestTime:v.toISOString(),requestTimeEpoch:v.getTime(),resourceId:"exhmtv",resourcePath:p};r.proxy=="httpApi"?(f.identity.cognitoAmr=null,f.stage="$default"):(f.stage="dev",r.private&&(f.identity.apiKey=m,f.identity.apiKeyId="abcdefghjk")),c.requestContext=f;let S=t.getPathParameters(r,n);return c.pathParameters=Object.keys(S).length?S:null,c.stageVariables=null,c.body=o??null,c.isBase64Encoded=o?i:!1,c};returnError=e=>{if(this.res.writableFinished)return!0;let r=500,n=t.httpErrMsg;e&&t.isEndpointTimeoutError(e.errorMessage)&&(this.mockEvent.proxy=="httpApi"?(r=503,n=t.unavailable):(r=504,n=t.apgTimeoutMsg));let s=[["Date",new Date().toUTCString()],["Content-Type",t.contentType.json],["Content-Length",String(n.length)],t.keepAlive,["Apigw-Requestid","ETuSEj-PiGYEJdQ="]];return this.res.shouldKeepAlive=!1,this.res.writeHead(r,s),this.res.end(n)};#e=e=>{let r="",n=typeof e;if(n=="string"||n=="number"||n=="boolean")r=String(e);else if(e===null)r="";else throw new Error("");return r};sendV1Response=e=>{let r=[["Date",new Date().toUTCString()],["Apigw-Requestid",Buffer.from(st()).toString("base64").slice(0,16)],t.keepAlive],n=200;if(!e||isNaN(e.statusCode))throw b.RED(`Valid 'http' response payload must be an object which includes a valid 'statusCode'. Received:`),console.log(e),new Error;n=e.statusCode,e.headers&&typeof e.headers=="object"&&!Array.isArray(e.headers)&&Object.entries(e.headers).forEach(([c,p])=>{let d=t.normalizeHeaderKey(c),u=this.#e(p);r.push([d,u])}),e.multiValueHeaders&&typeof e.multiValueHeaders=="object"&&!Array.isArray(e.multiValueHeaders)&&Object.entries(e.multiValueHeaders).forEach(([c,p])=>{let d=t.normalizeHeaderKey(c);if(!Array.isArray(p))throw new Error;p.map(m=>this.#e(m)).forEach(m=>{r.push([d,m])})});let s=e.body;if(e.isBase64Encoded&&s){if(typeof s!="string")throw new Error;let c=Buffer.from(s,"base64").toString();if(Buffer.from(c).toString("base64")!=s)throw b.RED("response body is not properly base64 encoded"),new Error;s=c}r.findIndex(c=>c[0].toLowerCase()=="content-type")==-1&&r.push(["Content-Type",t.contentType.json]);let a=r.findIndex(c=>c[0].toLowerCase()=="content-length");a!=-1&&r.splice(a,1);let o=typeof s;o=="number"||o=="boolean"?s=String(s):s&&o!="string"&&b.YELLOW("API Gateway payload v1 return body must be typeof string, number or boolean ");let l=n==204?"0":s?String(Buffer.from(s).byteLength):"0";r.push(["Content-Length",l]),this.res.shouldKeepAlive=!1,this.res.writeHead(n,r),this.res.end(s)};sendV2Response=e=>{this.res.setHeader("Apigw-Requestid",Buffer.from(st()).toString("base64").slice(0,16)),this.res.setHeader("Date",new Date().toUTCString()),e?(typeof e.headers=="object"&&!Array.isArray(e.headers)&&Object.keys(e.headers).filter(s=>s!=="Apigw-Requestid"&&s!=="Date").forEach(s=>{this.res.setHeader(s,e.headers[s])}),e.statusCode?(this.res.statusCode=e.statusCode,e.cookies?.length&&this.res.setHeader("Set-Cookie",e.cookies)):this.res.statusCode=200):this.res.statusCode=200;let r="";if(!e)return this.res.end();if(typeof e=="object"&&typeof e.body=="string"&&(r=e.body,e.isBase64Encoded)){let n=Buffer.from(r,"base64").toString();if(Buffer.from(n).toString("base64")!=r)throw b.RED("response body is not properly base64 encoded"),new Error;r=n}typeof e=="string"?(this.res.setHeader("Content-Type",t.contentType.json),r=e):typeof e=="object"&&!e.statusCode&&(this.res.setHeader("Content-Type",t.contentType.json),r=JSON.stringify(e)),this.res.end(r)};sendResponse=e=>{if(!this.res.writableFinished)return this.mockEvent.version==1?this.sendV1Response(e):this.sendV2Response(e)}}});import{randomUUID as Cr}from"crypto";var Kr,Qr,Jr,it,at=w(()=>{"use strict";W();F();_();C();nt();Ie();Kr=(t,e)=>{if(t.get("x_mock_type")!==null)return t.get("x_mock_type");if(e["x-mock-type"])return Array.isArray(e["x-mock-type"])?e["x-mock-type"][0]:e["x-mock-type"]},Qr=t=>t.mockEvent.kind=="alb"?new ce(t):new K(t),Jr=(t,e,r)=>{if(e.private){if(!r.length)return console.log("\x1B[31mPrivate http endpoints require API Key to be defined in serverless.yml\x1B[0m"),!1}else return!0;for(let n=0;n<t.rawHeaders.length;n++)if(t.rawHeaders[n].toLowerCase()=="x-api-key"){let i=t.rawHeaders[n+1];if(r.includes(i))return!0}return!1},it=async(t,e,r,n)=>{let{url:s,method:i,headers:a,rawHeaders:o}=t,{searchParams:l}=r,c=Kr(l,a),p=E.getMultiValueHeaders(o),d=E.normalizeSearchParams(l,decodeURI(s)),u=k.findHandler({headers:p,query:d,method:i,path:decodeURIComponent(r.pathname),kind:c});if(!u)return;let{event:m,handler:g}=u;try{tt(a,m.kind)}catch(A){return e.statusCode=400,e.setHeader("Content-Type",E.contentType.text),e.end(A.message)}if(!Jr(t,m,n))return e.statusCode=403,e.setHeader("Content-Type",E.contentType.json),e.end(E.apigForbiddenErrMsg);m.async&&(e.statusCode=200,e.end());let h=Cr(),y=E.getIsBase64Encoded(a),v=await $(t,y),f=a["content-type"];if((!f||f=="application/json"||f=="application/json; charset=utf-8")&&m.kind=="apg"&&m.schema&&m.proxy=="http"){let A;try{A=JSON.parse(v)}catch{return e.statusCode=400,e.setHeader("Content-Type",E.contentType.json),e.end(E.apigJsonParseErrMsg)}if(!m.schema(A)){e.statusCode=400,e.setHeader("Content-Type",E.contentType.json);let P=m.schema.errors.map(N=>`instancePath '${N.instancePath}' ${N.message}`).join(", ");return e.end(JSON.stringify({message:`[${P}]`}))}}let x=Qr({req:t,res:e,body:v,isBase64Encoded:y,multiValueHeaders:p,mockEvent:m,lambdaName:g.outName,parsedURL:r,requestId:h});try{let A=await g.invoke(x.payload,m);A instanceof D&&(A=A.getParsedResponse()),x.sendResponse(A)}catch(A){return x.returnError(A)}return!0}});var le,ot=w(()=>{"use strict";le=class{err;constructor(e){this.err=new Error(`Local invoke of ${e} runtime is currently not supported by serverless-aws-lambda.`)}isMounted=!0;mount=()=>{};unmount=()=>{};invoke=async()=>{throw this.err};onComplete=()=>{}}});import{EventEmitter as Br}from"events";import{Worker as Gr}from"worker_threads";import Yr from"path";import{fileURLToPath as Zr}from"url";var Xr,pe,ct=w(()=>{"use strict";T();_();Xr=Zr(new URL(".",import.meta.url)),pe=class extends Br{_worker;isMounted=!1;_isLoading=!1;invoke;mount;unmount;name;outName;timeout;memorySize;environment;handlerPath;handlerName;esOutputPath;constructor({name:e,outName:r,timeout:n,memorySize:s,environment:i,handlerPath:a,handlerName:o,esOutputPath:l}){super(),this.name=e,this.outName=r,this.timeout=n,this.memorySize=s,this.environment=i,this.handlerPath=a,this.handlerName=o,this.esOutputPath=l,this.mount=async()=>{this._isLoading?(this.setMaxListeners(0),await new Promise((c,p)=>{this.once("loaded",d=>{d?c(void 0):p()})})):this.isMounted||(this._isLoading=!0,await this.importHandler())},this.unmount=()=>{this._worker?.terminate(),this.isMounted=!1,this._isLoading=!1},this.invoke=async({event:c,info:p,clientContext:d,response:u,awsRequestId:m})=>new Promise((g,h)=>{this._worker.postMessage({channel:"exec",data:{event:c,clientContext:d},awsRequestId:m});let y=u??new D(p);function v(f,S,x,A){switch(f){case"return":case"succeed":case"done":this.removeListener(m,v),g(S);break;case"fail":this.removeListener(m,v),h(S);break;case"stream":x=="write"?y.write(S,A):x=="ct"?y.setHeader("Content-Type",S):x=="timeout"?(this.removeListener(m,v),y.destroy(),h(S)):(this.removeListener(m,v),y.end(S),g(y instanceof D?y:void 0));break;default:this.removeListener(m,v),h(new Error("Unknown error"));break}}this.on(m,v)})}async importHandler(){await new Promise((e,r)=>{let n={name:this.name,env:this.environment,execArgv:["--enable-source-maps"],workerData:{name:this.name,timeout:this.timeout,memorySize:this.memorySize,esOutputPath:this.esOutputPath,handlerPath:this.handlerPath,handlerName:this.handlerName,debug:b.getDebug()}};this._worker=new Gr(Yr.resolve(Xr,"./lib/runtime/runners/node/index.js"),n),this._worker.setMaxListeners(0);let s=i=>{this.isMounted=!1,this._isLoading=!1,b.RED("Lambda execution fatal error"),console.error(i),this.emit("loaded",!1),r(i)};this._worker.on("message",i=>{let{channel:a,data:o,awsRequestId:l,type:c,encoding:p}=i;a=="import"?(this._worker.setMaxListeners(55),this.setMaxListeners(10),this._worker.removeListener("error",s),this.isMounted=!0,this._isLoading=!1,this.emit("loaded",!0),e(void 0)):a=="uncaught"?(this._worker.terminate(),this.isMounted=!1,this._isLoading=!1,b.RED(`${c} Uncaught exceptions`),console.error(o.error),o.solution&&(b.BR_BLUE("Solution:"),console.log(o.solution))):this.emit(l,a,o,c,p)}),this._worker.on("error",s),this._worker.postMessage({channel:"import"})})}onComplete=(e,r)=>{this._worker?.postMessage({channel:"complete",awsRequestId:e,timeout:r})}}});import{spawn as en}from"child_process";import Y from"path";import{watch as tn}from"fs";import{access as lt}from"fs/promises";import{fileURLToPath as rn}from"url";var nn,sn,de,pt=w(()=>{"use strict";nn=rn(new URL(".",import.meta.url)),sn=process.cwd(),de=class t{invoke;mount;unmount;name;outName;timeout;memorySize;environment;handlerPath;pyModulePath;handlerDir;handlerName;runtime;bin;python;isMounted=!1;watchers=[];filesTime=new Map;watcherListener;emitRebuild;static wrapper=nn.replace(`${Y.sep}dist`,"/src/lib/runtime/runners/python/index.py");static DELIMITER="__|response|__";static DELIMITEREND="__|responseEnd|__";static ERR_RESPONSE="__|error|__";static WATCH="__|watch|__";static WATCHEND="__|watchEnd|__";constructor({name:e,outName:r,timeout:n,memorySize:s,environment:i,handlerPath:a,handlerName:o,runtime:l},c){this.name=e,this.outName=r,this.timeout=n,this.memorySize=s,this.environment=i,this.handlerName=o,this.runtime=l,this.emitRebuild=c;let p=Y.resolve(a);this.handlerDir=Y.dirname(p),this.handlerPath=Y.basename(p,`.${this.handlerName}`),this.pyModulePath=`${this.handlerDir}/${this.handlerPath}`.replace(sn,"").replace(/\/|\\/g,".").slice(1),this.mount=async()=>{if(this.python)return;let d=`${this.handlerDir}/${this.handlerPath}.py`;try{await lt(d),this.load()}catch{console.error(`Can not find ${this.name}'s handler at: "${d}"`),process.exit(1)}},this.unmount=d=>{d&&(this.python?.kill(),this.python=void 0,this.isMounted=!1)},this.invoke=async({event:d,info:u,clientContext:m,awsRequestId:g})=>new Promise((h,y)=>{let v=JSON.stringify({event:d,awsRequestId:g,context:m??""}),f=x=>{let A=null,I=x.toString();try{let P=I.includes(t.WATCH);if(P&&this.setWatchFiles(I),I.includes(t.DELIMITER)){let N=I.split(t.DELIMITER),j=N[N.length-1].split(t.DELIMITEREND)[0];if(N.length>1){let q;P?q=N[0].split(t.WATCHEND)[1]:q=N.slice(0,-1).join(` `),q.trim()&&console.log(q)}j&&(A=JSON.parse(j)),this.python.stdout.removeListener("data",f),this.python.stderr.removeListener("data",S),h(A)}else if(I.trim()){let N;P?N=I.split(t.WATCHEND)[1]:N=I,N.trim()&&console.log(N)}}catch(P){console.log("err",P),y(P)}};this.python.stdout.on("data",f);let S=x=>{let A=x.toString();if(A.includes(t.ERR_RESPONSE))try{A=JSON.parse(A.split(t.ERR_RESPONSE)[1]),A.requestId=g}catch{}finally{this.python.stdout.removeListener("data",f),this.python.stderr.removeListener("data",S),y(A)}else console.log(A)};this.python.stderr.on("data",S),this.python.stdin.write(`${v} `)}),this.watcherListener=()=>{this.isMounted&&(this.unmount(!0),this.watchers.forEach(d=>d.close()),this.watchers=[],this.emitRebuild())}}setWatchFiles=async e=>{try{let r=e.split(t.WATCH),s=r[r.length-1].split(t.WATCHEND)[0],i=JSON.parse(s).map(a=>`${a.replace(/\./g,Y.sep)}.py`);for(let a of i)try{await lt(a),this.watchers.push(tn(a,{persistent:!1},this.watcherListener))}catch{}}catch(r){console.log(r)}};load=()=>{this.bin||(this.bin=process.platform==="win32"?"python":this.runtime.includes(".")?this.runtime.split(".")[0]:this.runtime),this.python=en(this.bin,[t.wrapper,this.pyModulePath,this.handlerName,String(this.timeout)],{env:this.environment}),this.python.pid||(console.error(`Can not find ${this.bin} in your PATH`),process.exit(1)),this.isMounted=!0};onComplete=e=>{}}});import{spawn as an}from"child_process";import me from"path";import{watch as on}from"fs";import{access as dt}from"fs/promises";import{fileURLToPath as cn}from"url";var ln,ue,mt=w(()=>{"use strict";ln=cn(new URL(".",import.meta.url)),ue=class t{invoke;mount;unmount;name;outName;timeout;memorySize;environment;handlerPath;modulePath;handlerDir;handlerName;runtime;bin;ruby;isMounted=!1;emitRebuild;watcherListener;watchers=[];static wrapper=ln.replace(`${me.sep}dist`,"/src/lib/runtime/runners/ruby/index.rb");static DELIMITER="__|response|__";static ERR_RESPONSE="__|error|__";static WATCH="__|watch|__";constructor({name:e,outName:r,timeout:n,memorySize:s,environment:i,handlerPath:a,handlerName:o,runtime:l},c){this.name=e,this.outName=r,this.timeout=n,this.memorySize=s,this.environment=i,this.handlerName=o,this.runtime=l,this.emitRebuild=c;let p=me.resolve(a);this.handlerDir=me.dirname(p),this.handlerPath=me.basename(p,`.${this.handlerName}`),this.modulePath=`${this.handlerDir}/${this.handlerPath}.rb`,this.mount=async()=>{if(!this.ruby)try{await dt(this.modulePath),this.load()}catch{console.error(`Can not find ${this.name}'s handler at: "${this.modulePath}"`),process.exit(1)}},this.unmount=d=>{d&&(this.ruby?.kill(),this.ruby=void 0,this.isMounted=!1)},this.invoke=async({event:d,info:u,clientContext:m,awsRequestId:g})=>new Promise((h,y)=>{let v=JSON.stringify({event:d,awsRequestId:g,context:m??""}),f=x=>{let A=null,I=x.toString();try{if(I.includes(t.WATCH))this.setWatchFiles(I);else if(I.includes(t.DELIMITER)){let P=I.split(t.DELIMITER),N=P[P.length-1];if(P.length>1){let j=P.slice(0,-1).join(` `);j.trim()&&console.log(j)}N&&(A=JSON.parse(N)),this.ruby.stdout.removeListener("data",f),this.ruby.stderr.removeListener("data",S),h(A)}else I.trim()&&console.log(I)}catch(P){y(P)}};this.ruby.stdout.on("data",f);let S=x=>{let A=x.toString();if(A.includes(t.ERR_RESPONSE))try{A=JSON.parse(A.split(t.ERR_RESPONSE)[1]),A.requestId=g}catch{}finally{this.ruby.stdout.removeListener("data",f),this.ruby.stderr.removeListener("data",S),y(A)}else console.log(A)};this.ruby.stderr.on("data",S),this.ruby.stdin.write(`${v} `)}),this.watcherListener=()=>{this.isMounted&&(this.unmount(!0),this.watchers.forEach(d=>d.close()),this.watchers=[],this.emitRebuild())}}setWatchFiles=async e=>{try{let r=e.split(t.WATCH),n=r[r.length-1],s=JSON.parse(n);s.push(this.modulePath);for(let i of s)try{await dt(i),this.watchers.push(on(i,{persistent:!1},this.watcherListener))}catch{}}catch(r){console.log(r)}};load=()=>{this.bin||(this.bin=process.platform==="win32"?"ruby.exe":"ruby"),this.ruby=an(this.bin,[t.wrapper,this.modulePath,this.handlerName,this.name,String(this.timeout)],{env:this.environment,shell:!0}),this.ruby.pid||(console.error(`Can not find ${this.bin} in your PATH`),process.exit(1)),this.isMounted=!0};onComplete=e=>{}}});var ut,ft,pn,dn,mn,fe,ht=w(()=>{"use strict";he();ut=(t,e,r)=>{switch(t){case"=":return e===r;case">":return e>r;case"<":return e<r;case">=":return e>=r;case"<=":return e<=r;default:return!1}},ft={exists:(t,e,r)=>{if(r===!0)return e in t&&!Pe(t[e]);if(r===!1)return!(e in t)},prefix:(t,e,r)=>{let n=typeof t[e]=="string"?t[e]:void 0;return n?n.startsWith(r):!1},suffix:(t,e,r)=>{let n=typeof t[e]=="string"?t[e]:void 0;return n?n.endsWith(r):!1},numeric:(t,e,r)=>{if(!(e in t))return!1;let n=[],[s,i]=r;if(n.push(ut(s,t[e],i)),r.length==4){let[,,a,o]=r;n.push(ut(a,t[e],o))}return n.every(a=>a===!0)},"anything-but":(t,e,r)=>{let n=typeof t[e]=="string"?t[e]:void 0;return n?!r.includes(n):!1},"equals-ignore-case":(t,e,r)=>typeof t?.[e]!="string"?!1:t[e].toLowerCase()==r.toLowerCase()},pn=(t,e,r)=>{if(r===null)return t[e]===null;let n=typeof r;if(n=="string")return t[e]==r;if(n=="object"&&!Array.isArray(r)){let s=[];for(let[i,a]of Object.entries(r))i in ft&&s.push(ft[i](t,e,a));return s.every(i=>i===!0)}return!1},dn=Array.isArray,mn=t=>t&&typeof t=="object"&&!Array.isArray(t),fe=(t,e)=>{let r=[];for(let[n,s]of Object.entries(t)){let i=[];dn(s)?(n=="$or"?i=s.map(a=>fe(a,e)):i=s.map(a=>pn(e,n,a)),r.push(i.some(a=>a===!0))):mn(e[n])&&fe(s,e[n])?r.push(!0):r.push(!1)}return r.every(n=>n===!0)}});import{randomUUID as un}from"crypto";var Q,Ne=w(()=>{"use strict";ht();Q=class{constructor(e,r){this.config=e;this.legacyDefinition=r}static SOURCES=[];UUID=un();LastModified=Date.now();LastProcessingResult="No records processed";State="Creating";StateTransitionReason="User action";filterRecords(e){let r=[],n=[];if(!Array.isArray(this.config.FilterCriteria?.Filters))return[e,[]];for(let s of e)this.config.FilterCriteria.Filters.map(o=>fe(JSON.parse(o.Pattern),s)).find(o=>o===!0)?r.push(s):n.push(s);return[r,n]}}});import"@aws-sdk/client-sqs";var O,Te=w(()=>{"use strict";O=class{static sqs;static async setSqsClient(e){try{let{SQSClient:r}=await import("@aws-sdk/client-sqs");this.sqs=new r(e)}catch{}}}});import{ReceiveMessageCommand as fn,DeleteMessageBatchCommand as hn,GetQueueAttributesCommand as yn,GetQueueUrlCommand as gn}from"@aws-sdk/client-sqs";var yt,gt,bn,vn,Sn,bt,An,En,wn,Le,ye,vt=w(()=>{"use strict";Ne();he();Te();F();yt=10,gt=0,bn=(t,e)=>O.sqs.send(new fn({QueueUrl:t,AttributeNames:["All"],MessageAttributeNames:["All"],MaxNumberOfMessages:e})),vn=t=>O.sqs.send(new gn({QueueName:t})),Sn=t=>O.sqs.send(new yn({QueueUrl:t,AttributeNames:["All"]})),bt=async(t,e)=>{for(let r of At(e,10)){if(!r.length)continue;let n=r.map((s,i)=>({Id:`id-${i+1}`,ReceiptHandle:s}));try{await O.sqs.send(new hn({QueueUrl:t,Entries:n}))}catch{}}},An=t=>{if(!t)return{};let e={};for(let[r,n]of Object.entries(t)){e[r]={};let{StringValue:s,BinaryValue:i,DataType:a}=n;a.startsWith("B")?e[r].binaryValue=i:e[r].stringValue=s,e[r].stringListValues=[],e[r].binaryListValues=[],e[r].dataType=a}return e},En=(t,e)=>{let{MessageId:r,Body:n,MD5OfBody:s,ReceiptHandle:i,Attributes:a,MessageAttributes:o,MD5OfMessageAttributes:l}=t,c={messageId:r,receiptHandle:i,body:n,attributes:a,messageAttributes:An(o)};return l&&(c.md5OfMessageAttributes=l),c.md5OfBody=s,c.eventSource="aws:sqs",c.eventSourceARN=e,c.awsRegion=e.split(":")[3],c},wn=(t,e)=>t.map(r=>En(r,e)),Le=class{constructor(e,r,n,s,i,a){this.MaximumBatchingWindowInSeconds=e;this.BatchSize=r;this.lambdaName=n;this.QueueUrl=s;this.ReportBatchItemFailures=i;this.legacyDefinition=a}available=!0;#e=[];#t=!1;#r(){setTimeout(async()=>{this.available=!1,this.#t||await this.#n()},this.MaximumBatchingWindowInSeconds*1e3)}async setRecord(e){this.#e.length||this.#r(),this.#e.push(e),(this.#e.length==this.BatchSize||!this.available)&&(this.available=!1,await this.#n())}async#n(){this.#t=!0;let e=this.#e.map(r=>r.receiptHandle);try{let n=await k.handlers.find(s=>s.name==this.lambdaName||s.outName==this.lambdaName).invoke({Records:this.#e},{kind:"sqs",event:this.legacyDefinition});this.ReportBatchItemFailures&&(e=St(this.#e,n)),await bt(this.QueueUrl,e)}catch{}}},ye=class extends Q{constructor(r,n){super(r,n);this.config=r;this.legacyDefinition=n;let s=this.config.EventSourceArn.split(":");this.QueueName=s[s.length-1],this.#r=this.config.FunctionResponseTypes?.[0]=="ReportBatchItemFailures"}#e=[];QueueName="";QueueUrl="";#t;#r;#n(){let r=this.#e.find(s=>s.available);if(r)return r;let n=new Le(this.config.MaximumBatchingWindowInSeconds,this.config.BatchSize,this.config.FunctionName,this.QueueUrl,this.#r,this.legacyDefinition);return this.#e.push(n),n}async#i(r){for(let n of r)await this.#n().setRecord(n)}async pool(){if(!O.sqs)return;let{QueueUrl:r}=await vn(this.QueueName);this.QueueUrl=r,await this.enable()}#s=1500;cleanBatchs(){for(let r=0;r<this.#e.length;r++)this.#e[r].available||this.#e.splice(r,1)}async#a(){let r=0,n=2e3,s=async()=>{try{let{Attributes:i}=await Sn(this.QueueUrl);if(!Number(i.ApproximateNumberOfMessages))r++,this.#s<=2e4&&(this.#s+=200),r==5&&(n=2e3);else{r=0,n=400;let o=this.#s;this.#s=350,o>=1600&&await this.#c(!0)}}catch{n=2e3}this.cleanBatchs(),this.#t=setTimeout(s,n)};await s()}#o;async#c(r){r&&clearTimeout(this.#o);let n=async()=>{if(!this.config.Enabled){this.State=="Disabling"&&(this.State="Disabled");return}try{let{Messages:s}=await bn(this.QueueUrl,this.config.BatchSize<=10?this.config.BatchSize:10);if(s){let i=wn(s,this.config.EventSourceArn),a=await this.#l(i);await this.#i(a)}}catch{}this.#o=setTimeout(n,this.#s)};await n()}async enable(){this.State="Enabling";try{await this.#a(),this.config.Enabled=!0,this.State="Enabled",await this.#c()}catch(r){console.error(r)}}disable(){this.config.Enabled=!1,clearTimeout(this.#t),this.State="Disabling"}async#l(r){let n=r.map(o=>{let l={...o};try{l.body=JSON.parse(l.body)}catch{}return l}),[s,i]=this.filterRecords(n);await bt(this.QueueUrl,i.map(o=>o.receiptHandle));let a=[];for(let o of s)a.push(...r.filter(l=>l.messageId==o.messageId));return a}}});var Et,xn,Rn,St,At,Pe,he=w(()=>{"use strict";T();Ne();vt();Et=async t=>{for(let e of t)for(let r of e.sqs){let n=r.arn;if(!n)if(r.name)n=`arn:aws:sqs:us-east-1:123456789012:${r.name}`;else continue;let s;if(Array.isArray(r.filterPatterns)){s=[];for(let a of r.filterPatterns)Pe(a)&&s.push({Pattern:JSON.stringify(a)});s.length||(s=void 0)}let i=new ye({BatchSize:typeof r.batchSize=="number"?r.batchSize:yt,Enabled:r.enabled,EventSourceArn:n,FunctionName:e.name,FunctionResponseTypes:r.functionResponseType,FilterCriteria:s?{Filters:s}:void 0,MaximumBatchingWindowInSeconds:typeof r.maximumBatchingWindow=="number"?r.maximumBatchingWindow:gt},r);if(Q.SOURCES.push(i),i.config.Enabled)try{await i.pool()}catch(a){b.RED(`Failed to start EventSourceMapping ${i.config.EventSourceArn} Please verify provided SQS Client Config validity.`),console.error(a)}}},xn=/(-|\w+)/g,Rn=t=>t.length<81&&t.replace(xn,"")=="",St=(t,e)=>{if(typeof e===void 0||e===null||typeof e=="object"&&(e.batchItemFailures===null||Array.isArray(e.batchItemFailures)&&!e.batchItemFailures.length))return t.map(n=>n.receiptHandle);let r=[];if(typeof e=="object"&&Array.isArray(e.batchItemFailures)){if(e.batchItemFailures.some(n=>!n.itemIdentifier||!Rn(n.itemIdentifier)||!t.find(s=>s.messageId==n.itemIdentifier)))throw new Error("ReportBatchItemFailures: complete failure.");return t.forEach(n=>{e.batchItemFailures.find(i=>i.itemIdentifier==n.messageId)||r.push(n.receiptHandle)}),r}},At=(t,e)=>{let r=[];for(let n=0;n<t.length;n+=e){let s=t.slice(n,n+e);r.push(s)}return r},Pe=t=>Object.prototype.toString.call(t)=="[object Object]"});import kn from"http";import{networkInterfaces as wt}from"os";import In from"inspector";import Pn from"serve-static";import{randomUUID as xt}from"crypto";var ge,Nn,Tn,be,Rt=w(()=>{"use strict";F();Ce();T();ee();W();at();ot();ct();pt();mt();he();wt&&(ge=Object.values(wt()).reduce((t,e)=>(t.push(...e),t),[])?.filter(t=>!t.internal&&t.family==="IPv4").find(Boolean)?.address);Nn=In?.url()!=null;Nn&&(console.warn("Lambdas timeout are disabled when a Debugger is attached"),G.ENABLE_TIMEOUT=!1);Tn={errors:[],warnings:[],outputFiles:[],metafile:{inputs:{},outputs:{}},mangleCache:{}},be=class t extends k{#e;runtimeConfig={};#t;customOfflineRequests=[];customBuildCallback;onReady;stop(e){this.#e.close(e)}#r=[];#n(e,r){for(let n of e)if(typeof n=="string"){let s=Buffer.from(xt(),"utf-8").toString("base64");this.#r.push(s),r[n]=s}else if(n&&typeof n=="object"&&!Array.isArray(n))if(typeof n.value=="string")this.#r.push(n.value);else for(let s of Object.values(n))Array.isArray(s)&&this.#n(s,r)}setApiKeys(e){if(!e)return;let r={};if(this.#n(e,r),Object.keys(r).length){console.log(` \x1B[90mREST API Gateway generated API Keys:\x1B[0m`);for(let[n,s]of Object.entries(r))console.log(`\x1B[35m${n}: \x1B[0m\x1B[36m${s}\x1B[0m`)}}constructor(e={debug:!1}){super(e),b.setDebug(e.debug),globalThis.sco=[],this.#e=kn.createServer({maxHeaderSize:105536},this.#s.bind(this)),this.#e.on("connection",n=>{n.on("close",()=>{let s=globalThis.sco.findIndex(i=>i==n);s!=-1&&globalThis.sco.splice(s,1)}),globalThis.sco.push(n)});let r=xt();E.accountId=Buffer.from(r).toString("hex").slice(0,16),E.apiId=Buffer.from(r).toString("ascii").slice(0,10),E.port=this.port}get port(){return k.PORT}set port(e){k.PORT=e,E.port=e}set serve(e){this.#t=Pn(e)}listen(e=0,r){if(isNaN(e))throw Error("port should be a number");this.#e.once("error",async n=>{n.code==="EADDRINUSE"?(b.RED(n.message),process.exit(1)):console.log(n)}),this.#e.listen(e,async()=>{let{port:n,address:s}=this.#e.address();this.port=n,ge&&(k.ip=ge),typeof r=="function"&&await r(n,ge);try{await this.onReady?.(n,k.ip),await Et(t.handlers)}catch(i){console.error(i)}process.send?.({port:n,ip:k.ip})})}#i(e,r){r=r.endsWith("/")?r:`${r}/`;let n=this.customOfflineRequests.find(s=>{let i=!1,a=!0;return typeof s.filter=="string"?(s.filter.endsWith("/")||(s.filter+="/"),i=s.filter==r):s.filter instanceof RegExp&&(i=s.filter.test(r)),typeof s.method=="string"&&s.method.toUpperCase()!="ANY"?a=s.method.toUpperCase()==e:Array.isArray(s.method)&&(s.method.findIndex(l=>l.toUpperCase()=="ANY")!==-1||(a=s.method.findIndex(l=>l.toUpperCase()==e)!==-1)),i&&a});if(n)return n.callback}async#s(e,r){let{url:n,method:s}=e,i=new URL(n,E.dummyHost),a=this.#i(s,i.pathname);if(a)try{await a(e,r)}catch{r.writableFinished||r.end("Internal Server Error")}else{e.on("error",c=>{console.error(c.stack)});let o=await it(e,r,i,this.#r),l=()=>{r.setHeader("Content-Type","text/html"),r.statusCode=404,r.end(Qe)};o||(this.#t?this.#t(e,r,l):l())}}fakeRebuildEmitter=async()=>{if(this.customBuildCallback)try{await this.customBuildCallback(Tn,!0)}catch(e){console.log(e)}console.log(`\x1B[32m${new Date().toLocaleString()} \u{1F504}\u2705 Rebuild\x1B[0m`),process.send?.({rebuild:!0})};async load(e){for(let r of e){let n=r.runtime.charAt(0);r.runner=n=="n"?new pe(r):n=="p"?new de(r,this.fakeRebuildEmitter):n=="r"?new ue(r,this.fakeRebuildEmitter):new le(r.runtime);let s=new G(r);this.addHandler(s)}}}});import Ln from"archiver";import{createReadStream as De,createWriteStream as Dn}from"fs";import{access as On,stat as jn}from"fs/promises";import L from"path";var kt,ve,It=w(()=>{"use strict";kt=process.cwd(),ve=class{serverless;defaultPreserveDir=!0;defaultFiles=[];defaultAssets=!1;format;sourcemap;outputs;outdir;constructor(e,r,n,s,i){if(this.serverless=e,this.format=r,this.sourcemap=n,this.outputs=s,this.outdir=L.resolve(i),this.serverless.service.package){typeof this.serverless.service.package.preserveDir=="boolean"&&(this.defaultPreserveDir=this.serverless.service.package.preserveDir),Array.isArray(this.serverless.service.package.files)&&(this.defaultFiles=this.serverless.service.package.files);let a=this.serverless.service.package.assets;this.isValidAssetsTyp