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.
2 lines (1 loc) • 8.22 kB
JavaScript
import E from"events";var C=n=>{let e={...n};try{if(delete e.cookies,e.method=n.httpMethod,e.query={},n.multiValueQueryStringParameters)for(let[r,i]of Object.entries(n.multiValueQueryStringParameters)){let o=i.map(decodeURIComponent);o.length==1?e.query[r]=o[0]:e.query[r]=o}else if(n.queryStringParameters)for(let[r,i]of Object.entries(n.queryStringParameters))e.query[r]=decodeURIComponent(i);let s={};if(n.multiValueHeaders)for(let[r,i]of Object.entries(n.multiValueHeaders)){let o=i.map(decodeURIComponent);o.length==1?s[r]=o[0]:s[r]=o}else if(n.headers)for(let[r,i]of Object.entries(n.headers))s[r]=decodeURIComponent(i);e.headers=s,e.get=r=>e.headers[r.toLowerCase()],e.path=e.path??e.rawPath,e.requestContext&&(e.method||(e.method=e.requestContext?.http?.method),e.path||(e.path=e.requestContext?.http?.path));let t=e.path?decodeURIComponent(e.path):void 0;if(e.params=t?.split("/").filter(r=>r),e.protocol=e.headers["x-forwarded-proto"]??void 0,e.secure=e.protocol?e.protocol=="https":void 0,!e.isBase64Encoded&&e.headers["content-type"]=="application/json"){let r=JSON.parse(n.body);e.body=r}}catch(s){console.log(s)}return e};var g=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,v=function(e){return encodeURIComponent(e)};function S(n){return Object.prototype.toString.call(n)==="[object Date]"||n instanceof Date}var x={serialize:(n,e,s)=>{let t=s||{},r=t.encode||v;if(typeof r!="function")throw new TypeError("option encode is invalid");if(!g.test(n))throw new TypeError("argument name is invalid");let i=r(e);if(i&&!g.test(i))throw new TypeError("argument val is invalid");let o=n+"="+i;if(t.maxAge!=null){let l=t.maxAge-0;if(isNaN(l)||!isFinite(l))throw new TypeError("option maxAge is invalid");o+="; Max-Age="+Math.floor(l)}if(t.domain){if(!g.test(t.domain))throw new TypeError("option domain is invalid");o+="; Domain="+t.domain}if(t.path){if(!g.test(t.path))throw new TypeError("option path is invalid");o+="; Path="+t.path}if(t.expires){let l=t.expires;if(!S(l)||isNaN(l.valueOf()))throw new TypeError("option expires is invalid");o+="; Expires="+l.toUTCString()}if(t.httpOnly&&(o+="; HttpOnly"),t.secure&&(o+="; Secure"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():t.priority){case"low":o+="; Priority=Low";break;case"medium":o+="; Priority=Medium";break;case"high":o+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case!0:o+="; SameSite=Strict";break;case"lax":o+="; SameSite=Lax";break;case"strict":o+="; SameSite=Strict";break;case"none":o+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return o}};var j=n=>{if(n==0||n>8)return"Set-Cookie";{let e=["s","e","t","c","o","o","k","i","e"];return e[n]=e[n].toUpperCase(),[...e.slice(0,3),"-",...e.slice(3)].join("")}},m=class{locals;callbackWaitsForEmptyEventLoop;#n;#r;#i;functionVersion;functionName;memoryLimitInMB;logGroupName;logStreamName;clientContext;identity;invokedFunctionArn;awsRequestId;getRemainingTimeInMillis;callback;responseObject={cookies:[],isBase64Encoded:!1,statusCode:200,headers:{},body:""};#s;#e;constructor(e){this.locals=e.locals,this.callbackWaitsForEmptyEventLoop=e.context.callbackWaitsForEmptyEventLoop,this.#n=e.context.succeed,this.#r=e.context.fail,this.#i=e.context.done,this.functionVersion=e.context.functionVersion,this.functionName=e.context.functionName,this.memoryLimitInMB=e.context.memoryLimitInMB,this.logGroupName=e.context.logGroupName,this.logStreamName=e.context.logStreamName,this.clientContext=e.context.clientContext,this.identity=e.context.identity,this.invokedFunctionArn=e.context.invokedFunctionArn,this.awsRequestId=e.context.awsRequestId,this.awsRequestId=e.context.awsRequestId,this.getRemainingTimeInMillis=e.context.getRemainingTimeInMillis,this.callback=e.callback,this.#s=e.resolve,e.previousResponse&&(this.responseObject=e.previousResponse),e.req&&(this.#e=e.req)}succeed(e){this.#n(e)}done(e,s){this.#i(e,s)}fail(e){this.#r(e)}#t(){if(Object.keys(this.responseObject.headers).find(s=>s.toLowerCase()=="content-type")||(this.#e.requestContext?.elb?this.type("text/html; charset=utf-8"):this.type("application/json")),this.responseObject.cookies?.length?(this.#e.version=="1.0"&&(this.responseObject.multiValueHeaders={},this.responseObject.multiValueHeaders["Set-Cookie"]=[...this.responseObject.cookies],delete this.responseObject.cookies),this.#e.requestContext?.elb&&!this.#e.multiValueHeaders&&!this.#e.multiValueQueryStringParameters&&(this.responseObject.cookies.forEach((s,t)=>{this.#o(j(t),s)}),delete this.responseObject.cookies)):delete this.responseObject.cookies,this.#e.requestContext?.elb&&(this.#e.multiValueHeaders||this.#e.multiValueQueryStringParameters)){this.responseObject.multiValueHeaders={};for(let[s,t]of Object.entries(this.responseObject.headers))this.responseObject.multiValueHeaders[s]=[t];this.responseObject.cookies?.length&&(this.responseObject.multiValueHeaders["Set-Cookie"]=[...this.responseObject.cookies],delete this.responseObject.cookies),delete this.responseObject.headers}this.#s({...this.responseObject})}#a(e){return e instanceof Buffer?(this.responseObject.body=e.toString("base64"),this.responseObject.isBase64Encoded=!0):this.responseObject.body=e,this}cookie(e,s,t){return Array.isArray(this.responseObject.cookies)?this.responseObject.cookies.push(x.serialize(e,s,t)):this.responseObject.cookies=[x.serialize(e,s,t)],this}clearCookie(e,s){let t={expires:new Date(1),path:"/",...s};return this.cookie(e,"",t)}status(e){return this.responseObject.statusCode=e,this}sendStatus(e){this.status(e).#t()}type(e){return this.responseObject.headers["Content-Type"]=e,this}#o(e,s){this.responseObject.headers[e]=s}set(...e){let s=e[0];if(e.length===2){let i=e[1];var t=Array.isArray(i)?i.map(String):String(i);this.#o(s,t)}else for(var r in s)this.#o(r,s[r]);return this}setHeader=this.set;get(e){return this.responseObject.headers[e]}getHeader=this.get;json(e){this.type("application/json").#a(JSON.stringify(e)).#t()}send(e){this.#a(e).#t()}end(e){let s;Array.isArray(e)?s=[...e]:e&&typeof e=="object"?s={...e}:s=e,this.#s(s)}redirect(...e){let s=isNaN(e[0])?302:e[0],t=typeof e[0]=="string"?e[0]:typeof e[1]=="string"?e[1]:"/";this.status(s).location(t).#t()}location(e){let s=e;return e==="back"&&(s=this.#e.get("Referrer")||this.#e.get("Referer")||"/"),this.set("Location",encodeURI(s))}links(e){let s=this.get("Link")||"";return s&&(s+=", "),this.set("Link",s+Object.keys(e).map(function(t){return"<"+e[t]+'>; rel="'+t+'"'}).join(", "))}get cookies(){return this.responseObject.cookies}get headers(){return this.responseObject.headers}};var R=(n,e)=>{if(e){let s=n.findIndex(t=>t.length==4);if(s!=-1){let t=n[s];return n.splice(0,s),t}}else return n[0]?.length<4?n[0]:void 0},{IS_LOCAL:I}=process.env,q=process.env.NODE_ENV=="production",O=class extends Function{controllers=[];constructor(){return super(),new Proxy(this,{apply:(e,s,t)=>e._call(...t)})}async _call(...e){let s=[...this.controllers],t=C(e[0]),r=e[1],i=e[2],o=null,l=new E,b=a=>{if(!o){if(typeof a=="object"){o={...a};for(let c of Object.keys(o))Array.isArray(o[c])?o[c]=[...a[c]]:o[c]&&typeof o[c]=="object"&&(o[c]={...a[c]})}else o=a;l.emit("end")}},k=async(a,c,y,h)=>{try{s.shift();let p=R(s,a);p?await p(a,c,y,h):(I&&console.log(a),b({statusCode:500,body:"Internal Server Error"}))}catch(p){k(p,c,y,h)}},d=new m({context:r,resolve:b,req:t,locals:{},callback:i}),u,f=async a=>{u=a,s.shift();let c={...d.locals},y={...d.responseObject};d=new m({context:r,resolve:b,locals:c,req:t,previousResponse:y,callback:i});let h=R(s,u);if(h){try{h.length==4?await h(u,t,d,f):await h(t,d,f)}catch(p){await k(p,t,d,f)}!o&&!s.length&&d.status(404).send(`Cannot ${t.method} ${t.path}`)}else{let p,w=500;q?(p="Not Found",w=404):u?p=u.stack?u.stack:u:p="Cannot find route controller",d.status(w).send(`<pre>${p}</pre>`)}};return await new Promise(async a=>{l.once("end",a);let c=R(s);if(c)try{await c(t,d,f)}catch(y){await k(y,t,d,f),a(void 0)}else a(void 0)}),o??{statusCode:204}}handle(...e){return this.controllers.push(...e),this}use(...e){return this.controllers.push(...e),this}},L=()=>new O;export{L as Router};