UNPKG

@serverless-stack/nextjs-lambda

Version:

Provides handlers that can be used in CloudFront Lambda@Edge to deploy next.js applications to the edge

2 lines (1 loc) 16.1 kB
"use strict";var e=require("stream"),t=require("zlib"),r=require("http"),o=require("./manifest.json");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=n(e),i=n(t),a=n(r),c=n(o);const u={"accept-encoding":!0,"content-length":!0,"if-modified-since":!0,"if-none-match":!0,"if-range":!0,"if-unmodified-since":!0,"transfer-encoding":!0,via:!0},l={202:"Accepted",502:"Bad Gateway",400:"Bad Request",409:"Conflict",100:"Continue",201:"Created",417:"Expectation Failed",424:"Failed Dependency",403:"Forbidden",504:"Gateway Timeout",410:"Gone",505:"HTTP Version Not Supported",418:"I'm a teapot",419:"Insufficient Space on Resource",507:"Insufficient Storage",500:"Server Error",411:"Length Required",423:"Locked",420:"Method Failure",405:"Method Not Allowed",301:"Moved Permanently",302:"Moved Temporarily",207:"Multi-Status",300:"Multiple Choices",511:"Network Authentication Required",204:"No Content",203:"Non Authoritative Information",406:"Not Acceptable",404:"Not Found",501:"Not Implemented",304:"Not Modified",200:"OK",206:"Partial Content",402:"Payment Required",308:"Permanent Redirect",412:"Precondition Failed",428:"Precondition Required",102:"Processing",407:"Proxy Authentication Required",431:"Request Header Fields Too Large",408:"Request Timeout",413:"Request Entity Too Large",414:"Request-URI Too Long",416:"Requested Range Not Satisfiable",205:"Reset Content",303:"See Other",503:"Service Unavailable",101:"Switching Protocols",307:"Temporary Redirect",429:"Too Many Requests",401:"Unauthorized",422:"Unprocessable Entity",415:"Unsupported Media Type",305:"Use Proxy"},d={enableHTTPCompression:!1},E=(e,{enableHTTPCompression:t,rewrittenUri:r}=d)=>{const{request:o,response:n={headers:{}}}=e,c={headers:{}},E=new s.default.Readable,_=Object.assign(E,a.default.IncomingMessage.prototype);_.url=r||o.uri,_.method=o.method,_.rawHeaders=[],_.headers={},_.connection={},o.querystring&&(_.url=_.url+"?"+o.querystring);const f=o.headers||{};for(const e of Object.keys(f)){const t=f[e];t.forEach((e=>{_.rawHeaders.push(e.key),_.rawHeaders.push(e.value)})),_.headers[e]=t[0].value}_.getHeader=e=>_.headers[e.toLowerCase()],_.getHeaders=()=>_.headers,o.body&&o.body.data&&_.push(o.body.data,o.body.encoding?"base64":void 0),_.push(null);const p=new s.default;p.finished=!1,Object.defineProperty(p,"statusCode",{get:()=>c.status,set(e){c.status=e,c.statusDescription=l[e]}}),p.headers={};const T={};p.writeHead=(e,t)=>(c.status=e,c.statusDescription=l[e],t&&(p.headers=Object.assign(p.headers,t)),p),p.write=e=>{c.body||(c.body=Buffer.from("")),c.body=Buffer.concat([c.body,Buffer.isBuffer(e)?e:Buffer.from(e)])};let h=t&&(e=>{let t=!1;const r=e["accept-encoding"];if(r)for(let e=0;e<r.length;e++){const{value:o}=r[e];-1!==o.split(",").map((e=>e.split(";")[0].trim())).indexOf("gzip")&&(t=!0)}return t})(f);const b=new Promise((e=>{p.end=t=>{!0!==p.finished&&(p.finished=!0,t&&p.write(t),p.statusCode||(p.statusCode=200),c.body&&(c.bodyEncoding="base64",c.body=h?i.default.gzipSync(c.body).toString("base64"):Buffer.from(c.body).toString("base64")),c.headers=((e,t,r)=>{const o={};return Object.entries(r).forEach((([e,t])=>{o[e.toLowerCase()]=t})),Object.entries(e).forEach((([e,r])=>{const n=e.toLowerCase();e=t[n]||e,u[n]||(o[n]=[],r instanceof Array?r.forEach((t=>{o[n].push({key:e,value:t.toString()})})):o[n].push({key:e,value:r.toString()}))})),o})(p.headers,T,n.headers),h&&(c.headers["content-encoding"]=[{key:"Content-Encoding",value:"gzip"}]),e(c))}}));return p.setHeader=(e,t)=>{p.headers[e.toLowerCase()]=t,T[e.toLowerCase()]=e},p.removeHeader=e=>{delete p.headers[e.toLowerCase()]},p.getHeader=e=>p.headers[e.toLowerCase()],p.getHeaders=()=>p.headers,p.hasHeader=e=>!!p.getHeader(e),{req:_,res:p,responsePromise:b}};E.SPECIAL_NODE_HEADERS=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];var _=E;var f=(()=>{var e={343:(e,t,r)=>{r.r(t),r.d(t,{Observable:()=>S,combineLatest:()=>m,default:()=>y,merge:()=>I,zip:()=>R});const o=()=>"function"==typeof Symbol,n=e=>o()&&Boolean(Symbol[e]),s=e=>n(e)?Symbol[e]:"@@"+e;o()&&!n("observable")&&(Symbol.observable=Symbol("observable"));const i=s("iterator"),a=s("observable"),c=s("species");function u(e,t){let r=e[t];if(null!=r){if("function"!=typeof r)throw new TypeError(r+" is not a function");return r}}function l(e){let t=e.constructor;return void 0!==t&&(t=t[c],null===t&&(t=void 0)),void 0!==t?t:S}function d(e){d.log?d.log(e):setTimeout((()=>{throw e}))}function E(e){Promise.resolve().then((()=>{try{e()}catch(e){d(e)}}))}function _(e){let t=e._cleanup;if(void 0!==t&&(e._cleanup=void 0,t))try{if("function"==typeof t)t();else{let e=u(t,"unsubscribe");e&&e.call(t)}}catch(e){d(e)}}function f(e){e._observer=void 0,e._queue=void 0,e._state="closed"}function p(e,t,r){e._state="running";let o=e._observer;try{let n=u(o,t);switch(t){case"next":n&&n.call(o,r);break;case"error":if(f(e),!n)throw r;n.call(o,r);break;case"complete":f(e),n&&n.call(o)}}catch(e){d(e)}"closed"===e._state?_(e):"running"===e._state&&(e._state="ready")}function T(e,t,r){if("closed"!==e._state){if("buffering"!==e._state)return"ready"!==e._state?(e._state="buffering",e._queue=[{type:t,value:r}],void E((()=>function(e){let t=e._queue;if(t){e._queue=void 0,e._state="ready";for(let r=0;r<t.length&&(p(e,t[r].type,t[r].value),"closed"!==e._state);++r);}}(e)))):void p(e,t,r);e._queue.push({type:t,value:r})}}class h{constructor(e,t){this._cleanup=void 0,this._observer=e,this._queue=void 0,this._state="initializing";let r=new b(this);try{this._cleanup=t.call(void 0,r)}catch(e){r.error(e)}"initializing"===this._state&&(this._state="ready")}get closed(){return"closed"===this._state}unsubscribe(){"closed"!==this._state&&(f(this),_(this))}}class b{constructor(e){this._subscription=e}get closed(){return"closed"===this._subscription._state}next(e){T(this._subscription,"next",e)}error(e){T(this._subscription,"error",e)}complete(){T(this._subscription,"complete")}}class S{constructor(e){if(!(this instanceof S))throw new TypeError("Observable cannot be called as a function");if("function"!=typeof e)throw new TypeError("Observable initializer must be a function");this._subscriber=e}subscribe(e){return"object"==typeof e&&null!==e||(e={next:e,error:arguments[1],complete:arguments[2]}),new h(e,this._subscriber)}forEach(e){return new Promise(((t,r)=>{if("function"!=typeof e)return void r(new TypeError(e+" is not a function"));function o(){n.unsubscribe(),t()}let n=this.subscribe({next(t){try{e(t,o)}catch(e){r(e),n.unsubscribe()}},error:r,complete:t})}))}map(e){if("function"!=typeof e)throw new TypeError(e+" is not a function");return new(l(this))((t=>this.subscribe({next(r){try{r=e(r)}catch(e){return t.error(e)}t.next(r)},error(e){t.error(e)},complete(){t.complete()}})))}filter(e){if("function"!=typeof e)throw new TypeError(e+" is not a function");return new(l(this))((t=>this.subscribe({next(r){try{if(!e(r))return}catch(e){return t.error(e)}t.next(r)},error(e){t.error(e)},complete(){t.complete()}})))}reduce(e){if("function"!=typeof e)throw new TypeError(e+" is not a function");let t=l(this),r=arguments.length>1,o=!1,n=arguments[1];return new t((t=>this.subscribe({next(s){let i=!o;if(o=!0,!i||r)try{n=e(n,s)}catch(e){return t.error(e)}else n=s},error(e){t.error(e)},complete(){if(!o&&!r)return t.error(new TypeError("Cannot reduce an empty sequence"));t.next(n),t.complete()}})))}concat(...e){let t=l(this);return new t((r=>{let o,n=0;return function s(i){o=i.subscribe({next(e){r.next(e)},error(e){r.error(e)},complete(){n===e.length?(o=void 0,r.complete()):s(t.from(e[n++]))}})}(this),()=>{o&&(o.unsubscribe(),o=void 0)}}))}flatMap(e){if("function"!=typeof e)throw new TypeError(e+" is not a function");let t=l(this);return new t((r=>{let o=[],n=this.subscribe({next(n){if(e)try{n=e(n)}catch(e){return r.error(e)}let i=t.from(n).subscribe({next(e){r.next(e)},error(e){r.error(e)},complete(){let e=o.indexOf(i);e>=0&&o.splice(e,1),s()}});o.push(i)},error(e){r.error(e)},complete(){s()}});function s(){n.closed&&0===o.length&&r.complete()}return()=>{o.forEach((e=>e.unsubscribe())),n.unsubscribe()}}))}[a](){return this}static from(e){let t="function"==typeof this?this:S;if(null==e)throw new TypeError(e+" is not an object");let r=u(e,a);if(r){let o=r.call(e);if(Object(o)!==o)throw new TypeError(o+" is not an object");return function(e){return e instanceof S}(o)&&o.constructor===t?o:new t((e=>o.subscribe(e)))}if(n("iterator")&&(r=u(e,i),r))return new t((t=>{E((()=>{if(!t.closed){for(let o of r.call(e))if(t.next(o),t.closed)return;t.complete()}}))}));if(Array.isArray(e))return new t((t=>{E((()=>{if(!t.closed){for(let r=0;r<e.length;++r)if(t.next(e[r]),t.closed)return;t.complete()}}))}));throw new TypeError(e+" is not observable")}static of(...e){return new("function"==typeof this?this:S)((t=>{E((()=>{if(!t.closed){for(let r=0;r<e.length;++r)if(t.next(e[r]),t.closed)return;t.complete()}}))}))}static get[c](){return this}}function I(...e){return new S((t=>{if(0===e.length)return S.from([]);let r=e.length,o=e.map((e=>S.from(e).subscribe({next(e){t.next(e)},error(e){t.error(e)},complete(){0==--r&&t.complete()}})));return()=>o.forEach((e=>e.unsubscribe()))}))}function m(...e){return new S((t=>{if(0===e.length)return S.from([]);let r=e.length,o=new Set,n=!1,s=e.map((()=>{})),i=e.map(((i,a)=>S.from(i).subscribe({next(r){if(s[a]=r,!n){if(o.add(a),o.size!==e.length)return;o=null,n=!0}t.next(Array.from(s))},error(e){t.error(e)},complete(){0==--r&&t.complete()}})));return()=>i.forEach((e=>e.unsubscribe()))}))}function R(...e){return new S((t=>{if(0===e.length)return S.from([]);let r=e.map((()=>[]));function o(){return r.some(((e,t)=>0===e.length&&n[t].closed))}let n=e.map(((e,n)=>S.from(e).subscribe({next(e){r[n].push(e),r.every((e=>e.length>0))&&(t.next(r.map((e=>e.shift()))),o()&&t.complete())},error(e){t.error(e)},complete(){o()&&t.complete()}})));return()=>n.forEach((e=>e.unsubscribe()))}))}o()&&Object.defineProperty(S,Symbol("extensions"),{value:{symbol:a,hostReportError:d},configurable:!0});const y=S}},t={};function r(o){if(t[o])return t[o].exports;var n=t[o]={exports:{}},s=!0;try{e[o](n,n.exports,r),s=!1}finally{s&&delete t[o]}return n.exports}return r.d=(e,t)=>{for(var o in t)r.o(t,o)&&!r.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.ab=__dirname+"/",r(343)})(),p="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function T(e){var t={exports:{}};return e(t,t.exports),t.exports}T((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.SERVER_DIRECTORY=t.PAGES_MANIFEST=t.SERVER_PROPS_ID=t.CLIENT_STATIC_FILES_RUNTIME_WEBPACK=t.PERMANENT_REDIRECT_STATUS=t.SERVER_FILES_MANIFEST=t.STATIC_PROPS_ID=t.BUILD_MANIFEST=t.BLOCKED_PAGES=t.STATIC_STATUS_PAGES=t.PRERENDER_MANIFEST=t.DEV_CLIENT_PAGES_MANIFEST=t.OPTIMIZED_FONT_PROVIDERS=t.TEMPORARY_REDIRECT_STATUS=t.SERVERLESS_DIRECTORY=t.EXPORT_MARKER=t.GOOGLE_FONT_PROVIDER=t.PHASE_PRODUCTION_BUILD=t.CLIENT_STATIC_FILES_RUNTIME_MAIN=t.BUILD_ID_FILE=t.CONFIG_FILE=t.CLIENT_STATIC_FILES_RUNTIME=t.PHASE_PRODUCTION_SERVER=t.EXPORT_DETAIL=t.IMAGES_MANIFEST=t.CLIENT_STATIC_FILES_RUNTIME_AMP=t.CLIENT_PUBLIC_FILES_PATH=t.CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL=t.STRING_LITERAL_DROP_BUNDLE=t.TRACE_OUTPUT_VERSION=t.CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH=t.FONT_MANIFEST=t.REACT_LOADABLE_MANIFEST=t.ROUTES_MANIFEST=t.CLIENT_STATIC_FILES_PATH=t.BODY_RENDER_TARGET=t.PHASE_EXPORT=t.PHASE_DEVELOPMENT_SERVER=void 0;t.PHASE_EXPORT="phase-export";t.PHASE_PRODUCTION_BUILD="phase-production-build";t.PHASE_PRODUCTION_SERVER="phase-production-server";t.PHASE_DEVELOPMENT_SERVER="phase-development-server";t.PAGES_MANIFEST="pages-manifest.json";t.BUILD_MANIFEST="build-manifest.json";t.EXPORT_MARKER="export-marker.json";t.EXPORT_DETAIL="export-detail.json";t.PRERENDER_MANIFEST="prerender-manifest.json";t.ROUTES_MANIFEST="routes-manifest.json";t.IMAGES_MANIFEST="images-manifest.json";t.SERVER_FILES_MANIFEST="required-server-files.json";t.DEV_CLIENT_PAGES_MANIFEST="_devPagesManifest.json";t.REACT_LOADABLE_MANIFEST="react-loadable-manifest.json";t.FONT_MANIFEST="font-manifest.json";t.SERVER_DIRECTORY="server";t.SERVERLESS_DIRECTORY="serverless";t.CONFIG_FILE="next.config.js";t.BUILD_ID_FILE="BUILD_ID";t.BLOCKED_PAGES=["/_document","/_app","/_error"];t.CLIENT_PUBLIC_FILES_PATH="public";t.CLIENT_STATIC_FILES_PATH="static";t.CLIENT_STATIC_FILES_RUNTIME="runtime";t.BODY_RENDER_TARGET="__NEXT_BODY_RENDER_TARGET__";t.STRING_LITERAL_DROP_BUNDLE="__NEXT_DROP_CLIENT_FILE__";t.CLIENT_STATIC_FILES_RUNTIME_MAIN="main";t.CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH="react-refresh";t.CLIENT_STATIC_FILES_RUNTIME_AMP="amp";t.CLIENT_STATIC_FILES_RUNTIME_WEBPACK="webpack";const r=Symbol("polyfills");t.CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL=r;t.TEMPORARY_REDIRECT_STATUS=307;t.PERMANENT_REDIRECT_STATUS=308;t.STATIC_PROPS_ID="__N_SSG";t.SERVER_PROPS_ID="__N_SSP";const o="https://fonts.googleapis.com/css";t.GOOGLE_FONT_PROVIDER=o;const n=[{url:o,preconnect:"https://fonts.gstatic.com"},{url:"https://use.typekit.net",preconnect:"https://use.typekit.net"}];t.OPTIMIZED_FONT_PROVIDERS=n;t.STATIC_STATUS_PAGES=["/500"];t.TRACE_OUTPUT_VERSION=1}));var h,b=async function(e){const t=[];return await function(e){return S.default.prototype.concat.call(...e)}(e).forEach((e=>{t.push(e)})),t.join("")},S=(h=f)&&h.__esModule?h:{default:h};exports.commonjsGlobal=p,exports.createCommonjsModule=T,exports.getAugmentedNamespace=function(e){if(e.__esModule)return e;var t=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(e).forEach((function(r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})})),t},exports.handler=async e=>{!function(){try{const e="{{ _SST_NEXTJS_SITE_ENVIRONMENT_ }}";process.env={...process.env,...e}}catch(e){console.log("Failed to set SST NextjsSite environment."),console.log(e)}}(),await Promise.all(e.Records.map((async e=>{const t=JSON.parse(e.body),r=c.default,{req:o,res:n}=_({request:t.cloudFrontEventRequest},{enableHTTPCompression:r.enableHTTPCompression}),s=require(`./${t.pagePath}`),{renderOpts:i,html:a}=await(async(e,t,r,o)=>{const{renderOpts:n,html:s}=await e.renderReqToHTML(t,r,o);let i;try{i="string"==typeof s?s:s?await b([s]):""}catch(o){console.log("Falling back to using page's rendering function for html"),i=await e.renderReqToHTML(t,r)}return{html:i,renderOpts:n}})(s,o,n,"passthrough");await(async e=>{const{S3Client:t}=await Promise.resolve().then((function(){return require("./S3Client-c84c8da4.js")})),r=new t({region:e.region,maxAttempts:3}),o=e.basePath?`${e.basePath.replace(/^\//,"")}/`:"",n=e.uri.replace(/^\/$/,"index").replace(/^\//,"").replace(/\.(json|html)$/,"").replace(/^_next\/data\/[^\/]*\//,""),s=`_next/data/${e.buildId}/${n}.json`,i=`static-pages/${e.buildId}/${n}.html`,a=e.revalidate?void 0:"public, max-age=0, s-maxage=2678400, must-revalidate",c=e.revalidate?new Date((new Date).getTime()+1e3*e.revalidate):void 0,u={Bucket:e.bucketName,Key:`${o}${s}`,Body:JSON.stringify(e.pageData),ContentType:"application/json",CacheControl:a,Expires:c},l={Bucket:e.bucketName,Key:`${o}${i}`,Body:e.html,ContentType:"text/html",CacheControl:a,Expires:c},{PutObjectCommand:d}=await Promise.resolve().then((function(){return require("./PutObjectCommand-2c2eb70c.js")}));return await Promise.all([r.send(new d(u)),r.send(new d(l))]),{cacheControl:a,expires:c}})({html:a,uri:t.cloudFrontEventRequest.uri,basePath:t.basePath,bucketName:t.bucketName,buildId:r.buildId,pageData:i.pageData,region:t.region,revalidate:i.revalidate})})))};