@bitblit/ratchet-epsilon-common 4.0.414-alpha → 4.0.415-alpha
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.mjs +1 -1
- package/package.json +9 -9
package/lib/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{StringRatchet as e,Logger as t,EsmRatchet as r,RestfulApiHttpError as n,MapRatchet as s,Base64Ratchet as o,EnumRatchet as a,LoggerLevelName as i,ErrorRatchet as c,NumberRatchet as l,RequireRatchet as u,LogMessageFormatType as d,LoggerOutputFunction as p,PromiseRatchet as h,TimeoutToken as g,JwtRatchet as m,StopWatch as f,BooleanRatchet as E,DurationRatchet as y}from"@bitblit/ratchet-common";import w from"jsonwebtoken";import S from"zlib";import{LambdaEventDetector as T,S3CacheRatchet as A}from"@bitblit/ratchet-aws";import{DateTime as R}from"luxon";import{PublishCommand as b}from"@aws-sdk/client-sns";import C from"http";import N from"cross-fetch";import v from"https";import{HeaderMap as P,ApolloServer as I}from"@apollo/server";import{gql as O}from"graphql-tag";import{ApolloServerPluginLandingPageLocalDefault as _}from"@apollo/server/plugin/landingPage/default";import L from"js-yaml";import{ModelValidator as M}from"@bitblit/ratchet-misc";import k from"route-parser";import{Subject as F}from"rxjs";import{CliRatchet as B,AbstractRatchetCliHandler as x}from"@bitblit/ratchet-node-only";import D from"util";import{SendMessageCommand as H,GetQueueAttributesCommand as j,ReceiveMessageCommand as q,DeleteMessageCommand as G}from"@aws-sdk/client-sqs";import U from"net";import V from"jwks-rsa";import Q from"fs";class z{constructor(){}static get buildVersion(){return"414"}static get buildHash(){return"311d546526302b7dd26ad47a98c28cad7b7c310c"}static get buildBranch(){return"alpha-2024-07-05-1"}static get buildTag(){return"alpha-2024-07-05-1"}static get buildBranchOrTag(){return e.trimToNull(z.buildBranch)?"BRANCH:"+z.buildBranch:"TAG:"+z.buildTag}static get buildTime(){return"LOCAL-TIME"}}class W{static EPSILON_FINDER_DYNAMIC_IMPORT_PATH_ENV_NAME="EPSILON_FINDER_DYNAMIC_IMPORT_PATH";static EPSILON_FINDER_FUNCTION_NAME_ENV_NAME="EPSILON_FINDER_FUNCTION_NAME";static DEFAULT_EPSILON_FINDER_DYNAMIC_IMPORT_PATH="epsilon-global-handler-provider.js";static DEFAULT_EPSILON_FINDER_FUNCTION_NAME="findEpsilonGlobalHandler";static AUTH_HEADER_PREFIX="Bearer ";static AUTH_HEADER_NAME="Authorization";static BACKGROUND_SQS_TYPE_FIELD="BACKGROUND_TYPE";static BACKGROUND_SNS_START_MARKER="BACKGROUND_START_MARKER";static BACKGROUND_SNS_IMMEDIATE_RUN_FLAG="BACKGROUND_IMMEDIATE_RUN_FLAG";static INTER_API_SNS_EVENT="EPSILON_INTER_API_EVENT";static load(e,n){t.info("Searching for %s : %s : %s",e,n,r.fetchDirName(import.meta.url));let s=null;const o=require(e);return o&&(t.debug("Found %s - pulling object : %j : %s",e,Object.keys(o),n),s=o[n]),s}static async findDynamicImportEpsilonGlobalHandlerProvider(){const e=process.env[W.EPSILON_FINDER_DYNAMIC_IMPORT_PATH_ENV_NAME]||W.DEFAULT_EPSILON_FINDER_DYNAMIC_IMPORT_PATH,r=process.env[W.EPSILON_FINDER_FUNCTION_NAME_ENV_NAME]||W.DEFAULT_EPSILON_FINDER_FUNCTION_NAME;t.debug("Using epsilon finder dynamic import path : %s / %s",e,r);let n=null;try{n=this.load(e,r)}catch(n){t.error("Error loading provider : %s / %s : %s",e,r,n,n)}let s=null;return n&&(t.debug("Type2 is : %s",typeof n),t.info("Got3 : %s : %s",n,typeof n),s=n(),t.info("Rval3 is %s",s)),s}constructor(){}}class Y extends n{static HTTP_CODE=401;constructor(...e){super(...e),Object.setPrototypeOf(this,Y.prototype),this.withHttpStatusCode(Y.HTTP_CODE)}}class K extends n{static HTTP_CODE=400;constructor(...e){super(...e),Object.setPrototypeOf(this,K.prototype),this.withHttpStatusCode(K.HTTP_CODE)}}class J{constructor(){}static extractStage(e){if(!e.path.startsWith("/"))throw new K("Path should start with / but does not : "+e.path);const t=e.path.indexOf("/",1);if(-1==t)throw new K("No second / found in the path : "+e.path);return e.path.substring(1,t)}static extractHostHeader(e){return s.extractValueFromMapIgnoreCase(e.headers,"Host")}static extractProtocol(e){return s.extractValueFromMapIgnoreCase(e.headers,"X-Forwarded-Proto")}static extractApiGatewayStage(e){const t=J.extractRequestContext(e);return t?t.stage:null}static extractRequestContext(e){return e.requestContext}static extractAuthorizer(e){const t=J.extractRequestContext(e);return t?t.authorizer:null}static ipAddressChain(e){const t=e&&e.headers?s.extractValueFromMapIgnoreCase(e.headers,"X-Forwarded-For"):null;let r=t?String(t).split(","):[];return r=r.map((e=>e.trim())),r}static ipAddress(e){const t=J.ipAddressChain(e);return t&&t.length>0?t[0]:null}static extractFullPath(e,t=null){return(t||J.extractProtocol(e)||"https")+"://"+e.requestContext.domainName+e.requestContext.path}static extractFullPrefix(e,t=null){const r=t||J.extractProtocol(e)||"https",n=e.requestContext.path.substring(0,e.requestContext.path.indexOf("/",1));return r+"://"+e.requestContext.domainName+n}static jsonBodyToObject(e){let t=null;if(e.body){const r=s.extractValueFromMapIgnoreCase(e.headers,"Content-Type")||"application/octet-stream";t=e.body,e.isBase64Encoded&&(t=o.base64StringToString(t)),r.startsWith("application/json")&&(t=JSON.parse(t.toString("ascii")))}return t}static calcLogLevelViaEventOrEnvParam(e,r,n){let s=e;return n?.envParamLogLevelName&&process.env[n.envParamLogLevelName]&&(s=a.keyToEnum(i,process.env[n.envParamLogLevelName]),t.silly("Found env log level : %s",s)),n&&n.queryParamLogLevelName&&r&&r.queryStringParameters&&r.queryStringParameters[n.queryParamLogLevelName]&&(s=a.keyToEnum(i,r.queryStringParameters[n.queryParamLogLevelName]),t.silly("Found query log level : %s",s)),s}static fixStillEncodedQueryParams(e){if(e?.queryStringParameters){const t={};Object.keys(e.queryStringParameters).forEach((r=>{const n=e.queryStringParameters[r];r.toLowerCase().startsWith("amp;")?t[r.substring(4)]=n:t[r]=n})),e.queryStringParameters=t}if(e?.multiValueQueryStringParameters){const t={};Object.keys(e.multiValueQueryStringParameters).forEach((r=>{const n=e.multiValueQueryStringParameters[r];r.toLowerCase().startsWith("amp;")?t[r.substring(4)]=n:t[r]=n})),e.multiValueQueryStringParameters=t}}static applyTokenToEventForTesting(e,t){const r=w.decode(t,{complete:!0});if(!r.payload)throw new Error("No payload found in passed token");const n=r.payload;e.headers=e.headers||{},e.headers[W.AUTH_HEADER_NAME.toLowerCase()]="Bearer "+t,e.requestContext=e.requestContext||{};const s=Object.assign({},e.requestContext.authorizer);s.userData=n,s.userDataJSON=n?JSON.stringify(n):null,s.srcData=t,e.requestContext.authorizer=s}static extractBasicAuthenticationToken(e,r=!1){let n=null;if(e&&e.headers){const r=J.extractAuthorizationHeaderCaseInsensitive(e);if(r&&r.startsWith("Basic ")){const e=o.base64StringToString(r.substring(6)).split(":");t.silly("Parsed to %j",e),e&&2===e.length&&(n={username:e[0],password:e[1]})}}if(!n&&r)throw new Y("Could not find valid basic authentication header");return n}static eventIsAGraphQLIntrospection(e){let r=!1;if(e&&e.httpMethod&&"post"===e.httpMethod.toLowerCase()&&e.path&&e.path.endsWith("/graphql"))try{const t=J.jsonBodyToObject(e);r=!!t&&!!t.operationName&&"IntrospectionQuery"===t.operationName}catch(n){t.error("Failed to parse body - treating as non-graphql : %s : %s",e?.body,n,n),r=!1}return r}static extractAuthorizationHeaderCaseInsensitive(e){return s.caseInsensitiveAccess(e?.headers||{},W.AUTH_HEADER_NAME)}static extractBearerTokenFromEvent(t){let r=null;const n=e.trimToEmpty(J.extractAuthorizationHeaderCaseInsensitive(t));return n.toLowerCase().startsWith("bearer ")&&(r=n.substring(7)),r}static hostIsLocal(t){let r=!1;return e.trimToNull(t)&&("localhost"!==(t=(t=t.includes(":")?t.substring(0,t.indexOf(":")):t).toLowerCase())&&"127.0.0.1"!==t||(r=!0)),r}static hostIsLocalOrNotRoutableIP4(t){let r=!1;return e.trimToNull(t)&&("localhost"===(t=(t=t.includes(":")?t.substring(0,t.indexOf(":")):t).toLowerCase())||"127.0.0.1"===t||t.startsWith("192.168.")||t.startsWith("10.")||t.startsWith("172.16."))&&(r=!0),r}}class X{constructor(){}static errorResponse(e){const t={errors:e.errors,httpStatusCode:e.httpStatusCode,requestId:e.requestId};e.detailErrorCode&&(t.detailErrorCode=e.detailErrorCode),e.endUserErrors&&e.endUserErrors.length>0&&(t.endUserErrors=e.endUserErrors),e.details&&(t.details=e.details),e.wrappedError&&(t.wrappedError=e.wrappedError.name+" : "+e.wrappedError.message);return{statusCode:e.httpStatusCode,isBase64Encoded:!1,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}}static redirect(e,r=301,n=null){if(301!==r&&302!==r&&307!==r)throw new Error("Code must be 301 or 302 or 307 for a redirect");let s=e;if(n){const e=Object.keys(n);if(e.length>0){t.silly("Applying params to input target : %j",n),s+=-1===s.indexOf("?")?"?":"&";for(let t=0;t<e.length;t++){const r=e[t];s+=r+"="+encodeURIComponent(n[r]),t<e.length-1&&(s+="&")}}}return{statusCode:r,body:'{"redirect-target":"'+s+"}",headers:{"Content-Type":"application/json",Location:s}}}static coerceToProxyResult(e){let t=null;if(null!=e)if("object"==typeof e)if(e.statusCode&&void 0!==e.body)t=Object.assign({},e),"string"==typeof e.body||Buffer.isBuffer(e.body)&&(t.body=e.body.toString("base64"),t.headers=e.headers||{},t.headers["Content-Type"]=e.body.contentType,t.isBase64Encoded=!0);else{const r=e.headers||{};r["Content-Type"]="application/json",t=X.coerceToProxyResult({statusCode:200,body:JSON.stringify(e),headers:r,isBase64Encoded:!1})}else if("string"==typeof e||Buffer.isBuffer(e))t=X.coerceToProxyResult({statusCode:200,body:e});else{const r=e.headers||{};r["Content-Type"]="application/json",t=X.coerceToProxyResult({statusCode:200,body:JSON.stringify(e),headers:r,isBase64Encoded:!1})}return t}static async applyGzipIfPossible(e,r){const n=r;if(e&&e.toLowerCase().indexOf("gzip")>-1){const e=r.body.length>1400;let o=s.extractValueFromMapIgnoreCase(r.headers,"content-type")||"";o=o.toLowerCase();const a="application/pdf"===o||"application/zip"===o||o.startsWith("image/");if(e&&!a){const e=r.isBase64Encoded?Buffer.from(r.body,"base64"):Buffer.from(r.body),s=await this.gzip(e);t.debug("Comp from %s to %d bytes",e.length,s.length);const o=s.toString("base64");n.body=o,n.isBase64Encoded=!0,n.headers=n.headers||{},n.headers["Content-Encoding"]="gzip"}else t.silly("Not gzipping, too small or exempt content")}else t.silly("Not gzipping, not an accepted encoding");return n}static gzip(e){return new Promise((function(t,r){S.gzip(e,(function(e,n){e?r(e):t(n)}))}))}}class Z extends n{static HTTP_CODE=500;constructor(...e){super(...e),Object.setPrototypeOf(this,Z.prototype),this.withHttpStatusCode(Z.HTTP_CODE)}}class ${static CURRENT_EPSILON_REFERENCE;static CURRENT_CONTEXT;static CURRENT_EVENT;static CURRENT_LOG_VARS={};static CURRENT_PROCESS_LABEL;static CURRENT_OVERRIDE_TRACE_ID;static CURRENT_OVERRIDE_TRACE_DEPTH;constructor(){}static initContext(e,t,r,n){$.CURRENT_EPSILON_REFERENCE=e,$.CURRENT_CONTEXT=r,$.CURRENT_EVENT=t,$.CURRENT_LOG_VARS={},$.CURRENT_PROCESS_LABEL=n}static clearContext(){$.CURRENT_EPSILON_REFERENCE=null,$.CURRENT_CONTEXT=null,$.CURRENT_EVENT=null,$.CURRENT_LOG_VARS={},$.CURRENT_PROCESS_LABEL=null,$.CURRENT_OVERRIDE_TRACE_ID=null,$.CURRENT_OVERRIDE_TRACE_DEPTH=null}static setOverrideTrace(e,t){$.CURRENT_OVERRIDE_TRACE_ID=e||$.CURRENT_OVERRIDE_TRACE_ID,$.CURRENT_OVERRIDE_TRACE_DEPTH=t||$.CURRENT_OVERRIDE_TRACE_DEPTH}static setOverrideTraceFromInternalBackgroundEntry(e){$.setOverrideTrace(e.traceId,e.traceDepth)}static setOverrideTraceFromInterApiEntry(e){$.setOverrideTrace(e.traceId,e.traceDepth)}static addHeadersToRecord(t,r=0){t?(t[$.traceHeaderName()]=$.currentTraceId(),t[$.traceDepthHeaderName()]=e.safeString($.currentTraceDepth()+r)):c.throwFormattedErr("Cannot add headers to null/undefined input")}static addTraceToProxyResult(e){e.headers=e.headers||{},$.addHeadersToRecord(e.headers)}static addTraceToHttpRequestInit(e){e.headers=e.headers||{},$.addHeadersToRecord(e.headers,1)}static setProcessLabel(e){$.CURRENT_PROCESS_LABEL=e}static currentRequestId(){const e=$.CURRENT_CONTEXT;return e?e.awsRequestId:null}static defaultedCurrentRequestId(t=e.createType4Guid()){return $.currentRequestId()??t}static remainingTimeMS(){const e=$.CURRENT_CONTEXT;return e?e.getRemainingTimeInMillis():null}static currentProcessLabel(){return $.CURRENT_PROCESS_LABEL||"unset"}static traceHeaderName(){return $?.CURRENT_EPSILON_REFERENCE?.config?.loggerConfig?.traceHeaderName||"X-TRACE-ID"}static traceDepthHeaderName(){return $?.CURRENT_EPSILON_REFERENCE?.config?.loggerConfig?.traceDepthHeaderName||"X-TRACE-DEPTH"}static currentTraceId(){const e=$?.CURRENT_EPSILON_REFERENCE?.config?.loggerConfig?.traceIdGenerator||$.defaultedCurrentRequestId;return $.CURRENT_OVERRIDE_TRACE_ID||$.CURRENT_EVENT?.headers?.[$.traceHeaderName()]||e($.CURRENT_EVENT,$.CURRENT_CONTEXT)}static currentTraceDepth(){return $.CURRENT_OVERRIDE_TRACE_DEPTH||l.safeNumber($.CURRENT_EVENT?.headers?.[$.traceDepthHeaderName()])||1}static addLogVariable(e,t){$.CURRENT_LOG_VARS[e]=t}static fetchLogVariable(e){return $.CURRENT_LOG_VARS?.[e]}static fetchLogVariables(){return Object.assign({},$.CURRENT_LOG_VARS||{})}}class ee{static apiGatewayV2ToApiGatewayV1(e){return{requestContext:ee.apiGatewayV2RequestContextToApiGatewayV1RequestContext(e.requestContext),httpMethod:e.requestContext.http.method,path:e.requestContext.http.path,queryStringParameters:e.queryStringParameters,headers:e.headers,body:e.body,isBase64Encoded:e.isBase64Encoded,multiValueHeaders:null,multiValueQueryStringParameters:null,pathParameters:e.pathParameters,stageVariables:e.stageVariables,resource:null}}static apiGatewayV2RequestContextToApiGatewayV1RequestContext(e){return{accountId:e.accountId,apiId:e.apiId,authorizer:null,domainName:e.domainName,domainPrefix:e.domainPrefix,requestId:e.requestId,routeKey:e.routeKey,stage:e.stage,requestTime:e.time,requestTimeEpoch:e.timeEpoch,protocol:e.http.protocol,httpMethod:e.http.method,identity:null,path:e.http.path,resourceId:null,resourcePath:null}}static findInMap(e,t){let r=null;return t.forEach(((t,n)=>{ee.matchExact(n,e)&&(r=t)})),r}static matchExact(e,t){const r=t.match(e);return null!=r&&t==r[0]}static resolvePotentialFunctionToResult(e,t){let r=t;return e&&(r="function"==typeof e?e():e),r}}class te{webHandler;constructor(e){this.webHandler=e}extractLabel(e,t){let r=this.webHandler.extractLabel(ee.apiGatewayV2ToApiGatewayV1(e),t);return r=r.replace("WEB:","WEB2:"),r}handlesEvent(e){return T.isValidApiGatewayV2WithRequestContextEvent(e)}async processEvent(e,t){const r=ee.apiGatewayV2ToApiGatewayV1(e),n=Object.assign({},{parsedBody:null,authorization:null,convertedFromV2Event:!0},r);return await this.webHandler.openApiLambdaHandler(n,t)}}class re{static isInterApiSnsEvent(e){return!!re.extractEntryFromEvent(e)}static extractEntryFromEvent(t){let r=null;if(t&&T.isSingleSnsEvent(t)){const n=t.Records[0].Sns.Message;if(e.trimToNull(n)){const e=JSON.parse(n);e&&e.type===W.INTER_API_SNS_EVENT&&(r=e.interApiEvent)}}return r}static async processInterApiEvent(e,r,n){let s=[];u.notNullOrUndefined(e,"InterApiEntry"),u.notNullOrUndefined(n,"BackgroundManager");const o=re.extractEntryFromEvent(e);$.setOverrideTraceFromInterApiEntry(o),t.info("Processing inter-api event : %j",e);const a=[];return r.processMappings.forEach((e=>{!e.disabled&&o.source.match(e.sourceRegex)&&o.type.match(e.typeRegex)&&e.backgroundProcessTypes.forEach((e=>{const t=n.createEntry(e,o.data);a.push(t)}))})),a.length>0?(t.info("Adding %d entries to queue",a.length),s=await n.addEntriesToQueue(a,!0)):t.info("No entries mapped for this event"),s}static addTraceToInterApiEntry(e){return e&&(e.traceId=e.traceId||$.currentTraceId(),e.traceDepth=e.traceDepth||$.currentTraceDepth()+1),e}}class ne{_epsilon;constructor(e){this._epsilon=e}extractLabel(e,t){const r=re.extractEntryFromEvent(e);return"InterApi:"+r.source+":"+r.type}handlesEvent(e){return this._epsilon.config.interApiConfig&&re.isInterApiSnsEvent(e)}async processEvent(e,t){const r=await re.processInterApiEvent(e,this._epsilon.config.interApiConfig,this._epsilon.backgroundManager);return{statusCode:200,body:JSON.stringify(r),isBase64Encoded:!1}}}class se extends Error{constructor(e){super(e??"No handlers found"),Object.setPrototypeOf(this,se.prototype)}}class oe{_epsilon;constructor(e){this._epsilon=e}extractLabel(e,t){return"SNSEvt:"+e.Records[0].EventSource}handlesEvent(e){return T.isValidSnsEvent(e)}async processEvent(e,r){let n=null;if(this._epsilon.config&&this._epsilon.config.sns&&e&&e.Records.length>0){const r=e.Records[0].Sns.TopicArn,s=ee.findInMap(r,this._epsilon.config.sns.handlers);if(!s)throw t.info("Found no SNS handler for : %s",r),new se;n=await s(e)}return n}}class ae{static everyNMinuteFilter(e){return ae.everyNElementFilter(e,60)}static everyNDaysOfYearFilter(e){return ae.everyNElementFilter(e,365)}static everyNElementFilter(e,t){u.notNullOrUndefined(e),u.notNullOrUndefined(t);const r=Math.floor(t/2);if(!e||e<2||e>r||t%e!=0)throw c.throwFormattedErr("Invalid config - this function only makes sense for 2 < N < %d and %d evenly divisible by N",r,t),new Error("Invalid config - this function only makes sense for 2 < N < 31 and 60 evenly divisible by N");const n=[];for(let t=0;t<60;t+=e)n.push(t);return n}static numberMatchesFilter(e,t){return!t||0===t.length||t.includes(e)}static eventMatchesEntry(t,r,n,s=(new Date).getTime()){let o=!1;if(t&&r&&n.timezone&&t.resources&&t.resources.length>0){const a=t.resources[0],i=e.trimToNull(r.overrideTimezone)||n.timezone,c=R.fromMillis(s).setZone(i);o=!r.eventFilter||r.eventFilter.test(a),o=o&&ae.numberMatchesFilter(c.minute,r.minuteFilter),o=o&&ae.numberMatchesFilter(c.hour,r.hourFilter),o=o&&ae.numberMatchesFilter(c.weekday,r.dayOfWeekFilter),o=o&&ae.numberMatchesFilter(c.day,r.dayOfMonthFilter),o=o&&ae.numberMatchesFilter(c.month,r.monthOfYearFilter),o=o&&(!r.contextMatchFilter||r.contextMatchFilter.test(e.trimToEmpty(n.context))),o=o&&(!r.contextNoMatchFilter||!r.contextNoMatchFilter.test(e.trimToEmpty(n.context)))}return o}static cronEntryName(e,t=null){u.notNullOrUndefined(e);let r=null;return e?(r=e.name,r=r||e.backgroundTaskType,!r&&e.directHandler&&(r=t?"Direct Entry "+t:"Direct Entry (No idx specified)")):r="ERROR: no entry passed",r}}class ie{_epsilon;constructor(e){this._epsilon=e}extractLabel(e,t){return"CronEvt:"+e.source}handlesEvent(e){return T.isValidCronEvent(e)}async processEvent(e,r){let n=null;return t.debug("Epsilon: CRON: %j",e),this._epsilon.config.cron?(await ie.processCronEvent(e,this._epsilon.config.cron,this._epsilon.backgroundManager,this._epsilon.backgroundHandler),n={statusCode:200,body:JSON.stringify({message:"CRON complete"}),isBase64Encoded:!1}):(t.debug("Skipping - CRON disabled"),n={statusCode:200,body:JSON.stringify({message:"CRON skipped - disabled"}),isBase64Encoded:!1}),n}static async processCronEvent(e,r,n,s){let o=!1;if(r&&e&&e.resources[0]&&r.entries)if(s){const s=[];for(let a=0;a<r.entries.length;a++){const i=r.entries[a];if(ae.eventMatchesEntry(e,i,r)){t.info("CRON Firing : %s",ae.cronEntryName(i));const e={type:i.backgroundTaskType,data:ee.resolvePotentialFunctionToResult(i.data,{})};t.silly("Resolved entry : %j",e),i.fireImmediate?(await n.fireImmediateProcessRequest(e),o=!0):s.push(e)}}s.length>0&&(await n.addEntriesToQueue(s,!0),o=!0)}else t.warn("Cron defines background tasks, but no background manager provided");return o}}class ce{_epsilon;constructor(e){this._epsilon=e}extractLabel(e,t){return"S3Evt:"+e.Records[0].eventSource}handlesEvent(e){return T.isValidS3Event(e)}async processEvent(e,r){let n=null;if(this._epsilon.config&&this._epsilon.config.s3&&e&&e.Records.length>0){const r=e.Records[0].s3.bucket.name+"/"+e.Records[0].s3.object.key;if(e.Records[0].eventName&&e.Records[0].eventName.startsWith("ObjectRemoved")){const s=ee.findInMap(r,this._epsilon.config.s3.removeHandlers);s?n=await s(e):t.info("Found no s3 create handler for : %s",r)}else{const s=ee.findInMap(r,this._epsilon.config.s3.createHandlers);s?n=await s(e):t.info("Found no s3 remove handler for : %s",r)}}return n}}class le{_epsilon;constructor(e){this._epsilon=e}extractLabel(e,t){return"DDBEvt:"+e.Records[0].eventName+":"+e.Records[0].eventSource}handlesEvent(e){return T.isValidDynamoDBEvent(e)}async processEvent(e,r){let n=null;if(this._epsilon.config&&this._epsilon.config.dynamoDb&&e&&e.Records&&e.Records.length>0){const r=e.Records[0].eventSourceARN,s=ee.findInMap(r,this._epsilon.config.dynamoDb.handlers);if(!s)throw t.info("Found no Dynamo handler for : %s",r),new se;n=await s(e)}return n}async processUncaughtError(e,r,n){throw t.error("Error slipped out to outer edge (Dynamo). Logging and rethrowing : %s",n,n),n}}class ue{process(e){return e.params=Object.assign({},e.params||{},$.fetchLogVariables()),e.params.tester=Date.now(),e.params.awsRequestId=$.currentRequestId(),e.params.traceId=$.currentTraceId(),e.params.traceDepth=$.currentTraceDepth(),e.params.procLabel=$.currentProcessLabel(),e}label(){return"EpsilonLoggingExtensionProcessor"}}class de{_epsilon;constructor(e){this._epsilon=e}extractLabel(e,t){return"SQSEvt:"+e.Records[0].eventSourceARN}handlesEvent(e){return T.isValidSqsEvent(e)}async processEvent(e,r){let n=null;if(this._epsilon.config&&this._epsilon.config.sqs&&e&&e.Records.length>0){const r=e.Records[0].eventSourceARN,s=ee.findInMap(r,this._epsilon.config.sqs.handlers);if(!s)throw t.info("Found no SQS handler for : %s",r),new se;n=await s(e)}return n}async processUncaughtError(e,r,n){throw t.error("Error slipped out to outer edge (SQS). Logging and rethrowing : %s",n,n),n}}class pe{_epsilon;static LOGGER_CONFIGURED=!1;static GLOBAL_INSTANCE_PROVIDER;static set globalInstanceProvider(e){pe.GLOBAL_INSTANCE_PROVIDER=e}static get globalInstanceProvider(){return pe.GLOBAL_INSTANCE_PROVIDER}handlers=null;constructor(e){this._epsilon=e,pe.LOGGER_CONFIGURED?t.info("EpsilonLoggingConfiguration:Skipping default logger config - already configured"):(pe.configureDefaultLogger(),t.info("EpsilonLoggingConfiguration:Default logger configured")),this.handlers=[this._epsilon.webHandler,new te(this._epsilon.webHandler),this._epsilon.backgroundHandler,new ne(this._epsilon),new oe(this._epsilon),new de(this._epsilon),new ie(this._epsilon),new ce(this._epsilon),new le(this._epsilon)]}static configureDefaultLogger(e){const r=e?Object.assign({},e):{};r.initialLevel=r.initialLevel??i.info,r.formatType=r.formatType??d.StructuredJson,r.globalVars=r.globalVars??{},r.outputFunction=r.outputFunction??p.StdOut,r.ringBufferSize=r.ringBufferSize??0;const n=r.preProcessors||[];r.preProcessors=n.concat([new ue]),t.getOptions(),t.changeDefaultOptions(r,!0),t.getOptions(),pe.LOGGER_CONFIGURED=!0,t.info("EpsilonLoggingConfiguration: Updated"),t.dumpOptionsIntoLog()}get epsilon(){return this._epsilon}async processSingleBackgroundByParts(e,t,r,n){return this.processSingleBackgroundEntry(this._epsilon.backgroundManager.createEntry(e,t),r,n)}async processSingleBackgroundEntry(e,r,n){let s=!1;if(e?.type){const o=await this._epsilon.backgroundManager.wrapEntryForInternal(e,r,n);s=await this._epsilon.backgroundHandler.processSingleBackgroundEntry(o),t.info("Direct processed request %j to %s",e,s)}else t.error("Cannot process null/unnamed background entry");return s}async lambdaHandler(e,t){let r=null;try{if(!this.epsilon.config.disableLastResortTimeout&&t&&t.getRemainingTimeInMillis()){const s=await h.timeout(this.innerLambdaHandler(e,t),"EpsilonLastResortTimeout",t.getRemainingTimeInMillis()-1e3);g.isTimeoutToken(s)?(s.writeToLog(),r=X.errorResponse(n.wrapError(new Z("Timed out")))):r=s}else r=await this.innerLambdaHandler(e,t)}finally{$.clearContext()}return r}async innerLambdaHandler(e,r){$.initContext(this._epsilon,e,r,"TBD");let n=null,s=pe.defaultProcessUncaughtError,o=!1;try{if(!this._epsilon)return t.error("Config not found, abandoning"),!1;const a=J.calcLogLevelViaEventOrEnvParam(t.getLevel(),e,this._epsilon.config.loggerConfig);t.setLevel(a),this._epsilon.config.loggerConfig&&this._epsilon.config.loggerConfig.queryParamTracePrefixName&&e.queryStringParameters&&e.queryStringParameters[this._epsilon.config.loggerConfig.queryParamTracePrefixName]&&(t.info("Setting trace prefix to %s",e.queryStringParameters[this._epsilon.config.loggerConfig.queryParamTracePrefixName]),t.updateTracePrefix(e.queryStringParameters[this._epsilon.config.loggerConfig.queryParamTracePrefixName]));let c=!1;for(let o=0;o<this.handlers.length&&!c;o++){const a=this.handlers[o];if(a.handlesEvent(e)){c=!0,s=a.processUncaughtError||s;const o=a.extractLabel(e,r);$.setProcessLabel(o),t.logByLevel(this._epsilon?.config?.loggerConfig?.epsilonStartEndMessageLogLevel||i.info,"EvtStart: %s",o);try{n=await a.processEvent(e,r)}catch(e){if(e instanceof se){c=!1;break}throw e}t.logByLevel(this._epsilon?.config?.loggerConfig?.epsilonStartEndMessageLogLevel||i.info,"EvtEnd: %s",o),t.silly("EvtEnd:Value: %s Value: %j",o,n)}}c||(o=!0)}catch(t){n=await s(e,r,t)}if(this.epsilon.config.throwErrorIfNoSuitableEventHandlers&&o)throw t.error("No matching handler found for event: %j",e),new Error("No matching handler found for event");return n}static async defaultProcessUncaughtError(e,r,n){t.error("Error slipped out to outer edge (Default). Logging and returning log : %s",n,n);return{statusCode:500,body:JSON.stringify({error:c.safeStringifyErr(n)}),isBase64Encoded:!1}}}class he{_aws;_sns;constructor(e,t){this._aws=e,this._sns=t}get config(){return this._aws}get sns(){return this._sns}createEntry(e,t){return{source:this._aws.source,type:e,data:t}}async fireInterApiEventByParts(e,t){const r=this.createEntry(e,t);return await this.fireInterApiEvent(r)}async fireInterApiEvent(e){let r=null;if(this.config.localMode)t.info("Fire inter-api event ignored because running locally (was %j)",e),r="INTER-API-IGNORED";else try{t.info("Firing inter-api event (remote) : %j ",e);const n={type:W.INTER_API_SNS_EVENT,interApiEvent:re.addTraceToInterApiEntry(e)},s=JSON.stringify(n),o=await this.writeMessageToSnsTopic(s);t.debug("Inter-api Wrote message : %s to SNS : %s",r,s,o)}catch(e){t.error("Failed to fireImmediateProcessRequest : %s",e,e)}return r}async writeMessageToSnsTopic(e){let r=null;const n={Message:e,TopicArn:this._aws.snsArn};t.debug("Writing message to SNS topic : j",n);return r=(await this.sns.send(new b(n))).MessageId,r}}class ge{static CLIENT_CSR="-----BEGIN CERTIFICATE REQUEST-----\nMIICwjCCAaoCAQAwfTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAk5WMRIwEAYDVQQH\nDAlMYXMgVmVnYXMxDjAMBgNVBAoMBVBsdW1hMRkwFwYDVQQDDBB3d3cuaGV5cGx1\nbWEuY29tMSIwIAYJKoZIhvcNAQkBFhNjd2Vpc3NAaGV5cGx1bWEuY29tMIIBIjAN\nBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Gh1SD1VciosMgh3MHF7IyKgNTu2\nDjGMoORJV4VNKzrjp7UOdKnD3so0Xx3A6bUTYAL8Vtc+EG+8LZjUpBIOwuKzzbVo\nt16+yt3YXBxzTZPU9g7sFsXx42RoNispIFq0enRtJrq/zq8izZxUZdGn9XD2DidL\nAedtRGjb8cmRuP6wmMRPBOZjct4ZjsSiTyhPa6kpt8V7Pa7vm0HGxcHiDAGp6zoy\nGHfBdsqeBdGbkGT1ZPfs9kpbtXPm82Sckd0p3oY3fJn0rZqpTAb8qcdGcnheYtqX\nFSjX7EoGsIXAK+oj25MvtfoZFMk4rjQ7FkHbgGk0iMHLN0kNjJzN0ysN/wIDAQAB\noAAwDQYJKoZIhvcNAQELBQADggEBAMbpCdoqmY9crolsh5y9YtYDLRIwisTjTjU1\nXzp1MurSzGIdHLokU+fdVWTIzn3uOu24yTQouTUUoYWHT4YgN4wELdDydfNxWvyl\nr34QV5B0FZbRV2sNz/3C1UX/Uor4af1Yv+QYlGHspgj+WIAEkNQ3xQIo9+I/miR+\n2VSlydtyGvmzipgv6CAwOsrQsIw7DkpVmnqIjgjPSXlGCgeKM9S1D/CwNwZnVA/e\nDF1SzDkJKl60/n+xZGYl/OtkH9vB8T6fHqk0iMxXuVUxI137fwEJwIQB5L6hFyJa\nL4hbjq7Cull4qOhXDby+fNJT9Ic7VCosJBXBHxHPsEnY2+TZAJo=\n-----END CERTIFICATE REQUEST-----\n";static CLIENT_CERT_PEM="-----BEGIN CERTIFICATE-----\nMIIDgTCCAmkCFDKASki0c6HD75dCdIZZ3vXq4eQeMA0GCSqGSIb3DQEBCwUAMH0x\nCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJOVjESMBAGA1UEBwwJTGFzIFZlZ2FzMQ4w\nDAYDVQQKDAVQbHVtYTEZMBcGA1UEAwwQd3d3LmhleXBsdW1hLmNvbTEiMCAGCSqG\nSIb3DQEJARYTY3dlaXNzQGhleXBsdW1hLmNvbTAeFw0yMzAxMjMxMDU2MDlaFw0y\nMzAyMjIxMDU2MDlaMH0xCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJOVjESMBAGA1UE\nBwwJTGFzIFZlZ2FzMQ4wDAYDVQQKDAVQbHVtYTEZMBcGA1UEAwwQd3d3LmhleXBs\ndW1hLmNvbTEiMCAGCSqGSIb3DQEJARYTY3dlaXNzQGhleXBsdW1hLmNvbTCCASIw\nDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANhodUg9VXIqLDIIdzBxeyMioDU7\ntg4xjKDkSVeFTSs646e1DnSpw97KNF8dwOm1E2AC/FbXPhBvvC2Y1KQSDsLis821\naLdevsrd2Fwcc02T1PYO7BbF8eNkaDYrKSBatHp0bSa6v86vIs2cVGXRp/Vw9g4n\nSwHnbURo2/HJkbj+sJjETwTmY3LeGY7Eok8oT2upKbfFez2u75tBxsXB4gwBqes6\nMhh3wXbKngXRm5Bk9WT37PZKW7Vz5vNknJHdKd6GN3yZ9K2aqUwG/KnHRnJ4XmLa\nlxUo1+xKBrCFwCvqI9uTL7X6GRTJOK40OxZB24BpNIjByzdJDYyczdMrDf8CAwEA\nATANBgkqhkiG9w0BAQsFAAOCAQEAWQG2tvWY+cyeeumD/7WKTBNaBjg4EAe+1mnZ\nKQsg0gGUL0kWsqCkg4xEqIojkKMjs62uS6ballEyWawygYd91OaJLFopNu+Dxk4N\n5GWKpriPr02vI6rMUZNtCmsooukEShr5ufFWb4WLnk4NXQlBCXTHbmIf7Z82UOMw\nONZdZyKLqlA0Z6SWYBp2gO32puww6dUU0DAKkIIx1SN8i8UKvowRAy13bugPtyau\nNknlE3J1+Gab1hHCMRdKFZPKy8nc7LWUNZhgKdY82IC/k5FSW32Wibfog1TwWRJR\nceTW4EN4P7ZmdHGMYkIplc7Qcx0mraY2HRqmjA33j3cNcY5UsQ==\n-----END CERTIFICATE-----\n";static CLIENT_KEY_PEM="-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEA2Gh1SD1VciosMgh3MHF7IyKgNTu2DjGMoORJV4VNKzrjp7UO\ndKnD3so0Xx3A6bUTYAL8Vtc+EG+8LZjUpBIOwuKzzbVot16+yt3YXBxzTZPU9g7s\nFsXx42RoNispIFq0enRtJrq/zq8izZxUZdGn9XD2DidLAedtRGjb8cmRuP6wmMRP\nBOZjct4ZjsSiTyhPa6kpt8V7Pa7vm0HGxcHiDAGp6zoyGHfBdsqeBdGbkGT1ZPfs\n9kpbtXPm82Sckd0p3oY3fJn0rZqpTAb8qcdGcnheYtqXFSjX7EoGsIXAK+oj25Mv\ntfoZFMk4rjQ7FkHbgGk0iMHLN0kNjJzN0ysN/wIDAQABAoIBAHzZ9yAQUqWk8w6C\nl9EZB4PDzE4p/uS9bXa9fhrCSz0vonv1FzvzXY/BdOmTTuMGlwEDd/XaBHKTJCvi\nSnvF90I0bKu3h4yTWtvLlbG+sD8HlQvInCifVuhr2zu1Nur1qb4kQXzgrRxfKmMZ\nWA/OH2qZGzwbK0kT7ZRUMuCR/EKPjYw9KP6pMF8nxXUjSm+g3YwgIB8kiPeDCV6C\n0/Ecpv5qMqcoYTg9f9KyBNmY3U5ZgbYrdwTDSMrrTwZKSHhTktdF0SEfYrVGLLEU\nvfQQlQmfcc5Z3+cz99BH1BeTNaCPtEaXjgvQYwkWlSxnY6QUE0p1qq9Jy0xaVEx9\n8LReuHECgYEA/hhJ6b2XV1WLtszFO8MRMzlyMuvBc3Ot0dsuJ7r1W3WOF5X7poSU\nxG0xe+n6Kubmi3tGhzS7BN4TEO9/SSE2gIQTk9zwAMuf+mZJQcG0Qz1iftVp5nnM\nzi205vBLLq2Pmk7wbhTIBO8J190Dli1/fuvk/cmJrA60Ys8v3y4e820CgYEA2gfV\nQ3eHRxk3wl4On71mMovY7lMx6+S8K8hBGo26A5FIu6N6v2jxKnQ5YphwFgjtkxgs\nLspAXmxRwFMapZP3d/nFeBhlOzNly7tqIdDOeNqEcUzEx7pwGXpWGZEHOYs1fvU+\ngU/1N8q9DBvr0B+XGeYR3NNdljajo6pwWZ6ed5sCgYAGmkz5ZPLU0yVBR8rsRaJh\nyWFdT2EEhgIDTQXDBImxqblahYw3hIR1Ij1B8g+NI9jj0P1BMC6X7sliDEcreFB5\nQHVdx0T5UFFE6XmH2ue7Q5IWp6cL1ShsRyXHRoE9okb0BI8c3S9haXDBCj44ndAN\nVUXrDlykevFXC/k7fHBTdQKBgHjIshpoEycOD1e753oS4JTL6GdO6271DlFq5LYj\nIZNsXtCkJhH3vvJ35Hp8XEu4snQ0hfV90d79PuS+pRppOETct8pqKVp8hL4ymv8U\nv+0vkQN7NeA3pnZW0W/kag400nP8xJ26f+xiggw9Q4vOlFSioe6loUjgCBNZDlh3\niO5VAoGASXkcv39B9/8FuWQ7rwhXHEubxOOwZZzSBU1wtLj2qHyPGoeU9ZpsmdrL\nXS9w1Jy0e49qmbBjzTqAEBw2nn/JVMFHyI/s//JVF7Q9GfBZAF5XF6mJ24yzTKgF\nkSoO5T+7s8NXi0eAIBe4CkWCBX7kWEZtu46GuVhsrC3oEazuLOs=\n-----END RSA PRIVATE KEY-----\n"}class me extends n{static HTTP_CODE=404;constructor(...e){super(...e),Object.setPrototypeOf(this,me.prototype),this.withHttpStatusCode(me.HTTP_CODE)}}class fe extends n{static HTTP_CODE=403;constructor(...e){super(...e),Object.setPrototypeOf(this,fe.prototype),this.withHttpStatusCode(fe.HTTP_CODE)}}class Ee extends n{static HTTP_CODE=501;constructor(...e){super(...e),Object.setPrototypeOf(this,Ee.prototype),this.withHttpStatusCode(Ee.HTTP_CODE)}}class ye extends n{static HTTP_CODE=500;constructor(...e){super(...e),Object.setPrototypeOf(this,ye.prototype),this.withHttpStatusCode(ye.HTTP_CODE)}}class we{static async expectedHandledByFilter(e,t){throw(new ye).withFormattedErrorMessage("Should not happen - it was expected that route %s would be handled by a filter",e.path)}static async handleNotImplemented(e,r){t.info("A request was made to %s with body %j - not yet implemented",e.path,e.body);return{time:(new Date).toLocaleString(),path:e.path,message:"NOT IMPLEMENTED YET"}}static async sample(t,r,s){const o={time:(new Date).toLocaleString(),evt:t,pad:e.createRandomHexString(2e3),flag:r};s&&(o.context=s);const a=l.safeNumber(t.queryStringParameters.error);if(a)switch(a){case-1:throw new Error("Test random failure");case 400:throw new K("Bad request error");case 401:throw new Y("Unauthorized error");case 403:throw new fe("Forbidden error");case 404:throw new me("Not Found error");case 501:throw new Ee("Not Implemented");default:throw(new n).withFormattedErrorMessage("Default error - %s",a).withHttpStatusCode(500).withDetails({src:a}).withEndUserErrors(["msg1","msg2"])}let i=e.trimToNull(t.queryStringParameters.test);return i&&(i=i.toLowerCase(),"null"===i)?null:o}static async defaultErrorProcessor(e,r,n){t.warn("Unhandled error (in promise catch) : %s \nStack was: %s\nEvt was: %j\nConfig was: %j",r.message,r.stack,e,n)}}class Se{encryptionKeys;issuer;_ratchet;constructor(e,t){this.encryptionKeys=e,this.issuer=t,u.notNullOrUndefined(e,"encryptionKeys"),u.noNullOrUndefinedValuesInArray(e,e.length);const r={encryptionKeyPromise:Promise.resolve(e)};this._ratchet=new m(r)}withExtraDecryptionKeys(e){u.notNullOrUndefined(e,"keys"),u.noNullOrUndefinedValuesInArray(e,e.length);const t=this._ratchet.copyConfig;return t.decryptKeysPromise=Promise.resolve(e),this._ratchet=new m(t),this}withParseFailureLogLevel(e){const t=this._ratchet.copyConfig;return t.parseFailureLogLevel=e,this._ratchet=new m(t),this}withOldKeyUseLogLevel(e){const t=this._ratchet.copyConfig;return t.decryptOnlyKeyUseLogLevel=e,this._ratchet=new m(t),this}get jwtRatchet(){return this._ratchet}get selectRandomEncryptionKey(){return this._ratchet.selectRandomEncryptionKey()}createRefreshedJWTString(e,t,r){return this._ratchet.refreshJWTString(e,r||!1,t)}async parseAndValidateJWTStringAsync(e){const t=await this._ratchet.decodeToken(e,2);if(m.hasExpiredFlag(t))throw new Y("Failing JWT token read/validate - token expired on "+t.exp);return t}async createJWTStringAsync(e,r,n=["USER"],s=3600,o=null){t.info("Creating JWT token for %s that expires in %s",e,s);const a=(new Date).getTime(),i={exp:a+1e3*s,iss:this.issuer,sub:e,iat:a,user:r,proxy:o,roles:n};return await this._ratchet.createTokenString(i,s)}async extractTokenFromAuthorizationHeader(t){let r=e.trimToEmpty(t);r.toLowerCase().startsWith("bearer ")&&(r=r.substring(7));return r?await this.parseAndValidateJWTStringAsync(r):null}}class Te{static TYPE_NAME="EpsilonEcho";get typeName(){return Te.TYPE_NAME}async handleEvent(r,n){t.info("Echo processing : %j",r),r&&e.trimToNull(r.error)&&c.throwFormattedErr("Forced error : %s",r.error)}}class Ae{get typeName(){return"EpsilonNoOp"}async handleEvent(e,r){t.silly("Hit the no-op proc")}}class Re{get typeName(){return"EpsilonSampleDelay"}async handleEvent(e,r){const n=Math.floor(5e3*Math.random());t.info("Running sample processor for %d",n),await h.wait(n),t.info("Sample processor complete")}}class be{get typeName(){return"EpsilonLogAndEnqueueEcho"}async handleEvent(e,r){t.info("LogAndEnqueueEchoProcessor : %j",e),await r.fireImmediateProcessRequestByParts(Te.TYPE_NAME,{upstream:e}),t.info("Completed : LogAndEnqueueEchoProcessor")}}const Ce={Queued:"Queued",Immediate:"Immediate"};class Ne{backgroundConfig;modelValidator;backgroundManager;maxWaitInMsForBackgroundJobToStart;constructor(e,t,r,n=1e4){this.backgroundConfig=e,this.modelValidator=t,this.backgroundManager=r,this.maxWaitInMsForBackgroundJobToStart=n}get httpMetaEndpoint(){return this.backgroundConfig.httpMetaEndpoint}get httpSubmissionPath(){return this.backgroundConfig.httpSubmissionPath}get httpStatusPath(){return this.backgroundConfig.httpStatusEndpoint}get implyTypeFromPathSuffix(){return this.backgroundConfig.implyTypeFromPathSuffix}async handleBackgroundStatusRequest(r,n){if(t.info("handleBackgroundStatusRequest called"),this.backgroundConfig.transactionLogger){const n=e.trimToNull(r.pathParameters.guid)||e.trimToNull(r.queryStringParameters.guid);if(n){const e=new f;let r=null;for(;!r&&e.elapsedMS()<this.maxWaitInMsForBackgroundJobToStart;)r=await this.backgroundConfig.transactionLogger.readTransactionLog(n),r||(t.debug("No log found yet, waiting 500 ms and retrying (%s of %d waited so far)",e.dump(),this.maxWaitInMsForBackgroundJobToStart),await h.wait(500));if(!r)throw(new me).withFormattedErrorMessage("No background result found for guid %s",n);return r}throw new K("No guid specified")}throw new K("Process logging not enabled")}async handleBackgroundMetaRequest(e,r){t.info("handleBackgroundMetaRequest called");const n=await this.backgroundManager.fetchApproximateNumberOfQueueEntries(),s=this.backgroundConfig.processors.map((e=>e.typeName)).filter((e=>!!e));s.sort(((e,t)=>e.localeCompare(t)));return{currentQueueLength:n,validTypes:s,backgroundManagerName:this.backgroundManager.backgroundManagerName}}async handleBackgroundSubmission(r,n){t.info("handleBackgroundSubmission : %j (mgr:%s)",r.parsedBody,this.backgroundManager.backgroundManagerName);let s=null;const o=r.path.indexOf(this.httpSubmissionPath)+this.httpSubmissionPath.length;let a=this.backgroundConfig.implyTypeFromPathSuffix?r.path.substring(o).split("-").join("").toLowerCase():"";a.includes("?")&&(a=a.substring(0,a.indexOf("?"))),a.includes("#")&&(a=a.substring(0,a.indexOf("#")));const i=r.parsedBody||{};if(e.trimToNull(a)){if(e.trimToNull(i?.type)&&i.type.toLocaleLowerCase()!==a.toLocaleLowerCase())throw new K("Background submission has type but does not match path supplied type");i.type=a}else if(!e.trimToNull(i?.type))throw new K("Background submission missing type and not configured in pathed mode");const c=this.backgroundConfig.processors.find((e=>e.typeName.toLowerCase()===i.type.toLowerCase())),l=E.parseBool(r.queryStringParameters.immediate),u=E.parseBool(r.queryStringParameters.startProcessor);if(!c)throw(new K).withFormattedErrorMessage("Could not find target background processor : %s",i.type);{if(e.trimToNull(c.dataSchemaName)){const e=this.modelValidator.validate(c.dataSchemaName,i.data,!1,!1);if(e.length>0)throw(new K).withErrors(e)}let t=null;t=l?await this.backgroundManager.fireImmediateProcessRequest(i):await this.backgroundManager.addEntryToQueue(i,u),s={processHandling:l?Ce.Immediate:Ce.Queued,startProcessorRequested:u,success:!0,resultId:t,error:null}}return s}}class ve{cfg;modelValidator;constructor(e,t){this.cfg=e,this.modelValidator=t}findProcessor(e){return this.cfg.processors.find((t=>t.typeName===e))}validType(e){return!!this.findProcessor(e)}validateEntry(t){const r=[];if(t){if(!e.trimToNull(t.type)){r.push("Entry type is null or empty");this.findProcessor(t.type)||r.push("Entry type is invalid")}}else r.push("Entry is null");return r}validateEntryAndThrowException(e){const r=this.validateEntry(e);r.length>0&&(t.warn("Invalid entry %j : errors : %j",e,r),c.throwFormattedErr("Invalid entry %j : errors : %j",e,r))}static validateAndMapProcessors(t,r){const n=new Map;return t.forEach(((t,r)=>{t||c.throwFormattedErr("Null processor provided at index %d",r),e.trimToNull(t.typeName)||c.throwFormattedErr("Processor at index %d defines no name",r),n.has(t.typeName)&&c.throwFormattedErr("More than one processor defined for type %s",t.typeName),n.set(t.typeName,t)})),n}static validateAwsConfig(e){const t=[];return e?(e.notificationArn||t.push("AWS config missing notificationArn"),e.queueUrl||t.push("AWS config missing queueUrl"),!e.sendNotificationOnBackgroundError&&!e.sendNotificationOnBackgroundValidationFailure||e.backgroundProcessFailureSnsArn||t.push("At least one send notification flag set to true but no sns arn set")):t.push("Null config"),t}static validateConfig(e){const t=[];return e?e.processors&&0!==e.processors.length||t.push("No processes specified"):t.push("Null config"),t}}const Pe={ProcessStarting:"ProcessStarting",DataValidationError:"DataValidationError",ExecutionSuccessfullyComplete:"ExecutionSuccessfullyComplete",ExecutionFailedError:"ExecutionRuntimeError",NoMatchProcessorName:"NoMatchProcessorName"};class Ie{createEntry(e,t){return{type:e,data:t}}async wrapEntryForInternal(e,t,r){return Object.assign({},e,{createdEpochMS:(new Date).getTime(),guid:Ie.generateBackgroundGuid(),traceId:t||$.currentTraceId(),traceDepth:r||$.currentTraceDepth()+1})}async addEntryToQueueByParts(e,t,r){let n=null;const s=this.createEntry(e,t);return s&&(n=await this.addEntryToQueue(s,r)),n}async addEntriesToQueue(e,r){const n=[];for(let s=0;s<e.length;s++){try{const t=await this.addEntryToQueue(e[s],!1);n.push(t)}catch(r){t.error("Error processing %j : %s",e[s],r),n.push(r.message)}if(r){const e=await this.fireStartProcessingRequest();t.silly("FireResult : %s",e)}}return n}async fireImmediateProcessRequestByParts(e,t){let r=null;const n=this.createEntry(e,t);return n&&(r=await this.fireImmediateProcessRequest(n)),r}static generateBackgroundGuid(t=(new Date).getTime()){return R.fromMillis(t).toFormat("yyyy-MM-dd-HH-mm-ss-")+e.createType4Guid()}static backgroundGuidToPath(t,r){let n=e.trimToEmpty(t);return n.length&&!n.endsWith("/")&&(n+="/"),n+=r.substring(0,4)+"/"+r.substring(5,7)+"/"+r.substring(8,10)+"/",n+=r+".json",n}static pathToBackgroundGuid(t,r){u.notNullOrUndefined(r,"path");let n=0;return r.endsWith(".json")||c.throwFormattedErr("Cannot extract guid, does not end with .json : %s : %s",r,t),e.trimToNull(t)&&(r.startsWith(t)||c.throwFormattedErr("Cannot extract guid, does not start with prefix : %s : %s",r,t),n=t.length,t.endsWith("/")||n++),n+=11,r.substring(n,r.length-5)}}class Oe{cfg;mgr;modelValidator;processors;validator;constructor(e,r,n){this.cfg=e,this.mgr=r,this.modelValidator=n;const s=ve.validateConfig(e);s.length>0&&c.throwFormattedErr("Invalid background config : %j",s),t.silly("Starting Background processor, %d processors",e.processors.length),this.validator=new ve(e,n),this.processors=ve.validateAndMapProcessors(e.processors,n),r?.immediateProcessQueue&&r.immediateProcessQueue()&&(t.info("Attaching to immediate processing queue"),r.immediateProcessQueue().subscribe((async e=>{t.debug("Processing local background entry : %j",e);const r=await this.processSingleBackgroundEntry(e);t.info("Processor returned %s",r)})))}extractLabel(e,t){let r=null;if(this.isBackgroundStartSnsEvent(e))r="BG:START-EVT";else if(this.isBackgroundImmediateFireEvent(e)){const t=this.parseImmediateFireBackgroundEntry(e);r="BG:"+t.type+":"+t.guid}else r="BG:UNKNOWN";return r}handlesEvent(e){return T.isValidSnsEvent(e)&&this.isBackgroundSNSEvent(e)}isBackgroundSNSEvent(e){return this.isBackgroundStartSnsEvent(e)||this.isBackgroundImmediateFireEvent(e)}isBackgroundStartSnsEvent(e){let t=!1;if(e&&T.isSingleSnsEvent(e)){t=e.Records[0].Sns.Message===W.BACKGROUND_SNS_START_MARKER}return t}isBackgroundImmediateFireEvent(t){let r=!1;if(t&&T.isSingleSnsEvent(t)){const n=t.Records[0].Sns.Message;if(e.trimToNull(n)){const e=JSON.parse(n);r=!!e&&e.type===W.BACKGROUND_SNS_IMMEDIATE_RUN_FLAG}}return r}parseImmediateFireBackgroundEntry(r){let n=null;try{if(r&&T.isSingleSnsEvent(r)){const t=r.Records[0].Sns.Message;if(e.trimToNull(t)){const e=JSON.parse(t);e&&e.type===W.BACKGROUND_SNS_IMMEDIATE_RUN_FLAG&&(n=e.backgroundEntry)}}}catch(e){t.error("Could not parse %j as an immediate run event : %s",r,e,e)}return n}async processEvent(r,n){let s=null;if(this.isBackgroundStartSnsEvent(r))if(t.info("Reading task from background queue"),s=await this.takeAndProcessSingleBackgroundQueueEntry(),s>0){t.info("Processed %d elements from background queue, refiring",s);const e=await this.mgr.fireStartProcessingRequest();t.info("Refire returned %s",e)}else t.info("No items processed - stopping");else{const e=this.parseImmediateFireBackgroundEntry(r);if(e){t.silly("Processing immediate fire event : %j",e);const r=await this.processSingleBackgroundEntry(e);t.silly("Result was : %s",r),s=1}else t.warn("Tried to process non-background start / immediate event : %j returning false",r)}return{statusCode:200,body:e.safeString(s),isBase64Encoded:!1}}async takeAndProcessSingleBackgroundQueueEntry(){let e=null;const r=await this.mgr.takeEntryFromBackgroundQueue();t.info("Found %d entries - processing",r.length);for(let t=0;t<r.length;t++){const n=r[t];e+=await this.processSingleBackgroundEntry(n)?1:0}return t.debug("Returning %d",e),e}async safeWriteToLogger(e){if(this.cfg.transactionLogger)try{await this.cfg.transactionLogger.logTransaction(e)}catch(r){t.error("Failed to write to transaction logger : %j : %s",e,r,r)}else t.silly("Skipping - no logger defined")}async conditionallyStartTransactionLog(r){if(!e.trimToNull(r.guid)){t.warn("No guid found - creating"),r.guid=Ie.generateBackgroundGuid();const e={request:r,running:!0};await this.safeWriteToLogger(e)}t.debug("Starting transaction log")}async conditionallyCompleteTransactionLog(e,r,n,s){t.debug("Completing transaction log");const o={request:e,result:r,error:n?c.safeStringifyErr(n):null,running:!1,runtimeMS:s};await this.safeWriteToLogger(o)}async conditionallyRunErrorProcessor(e,r){try{this.cfg.errorProcessor&&(t.info("Running error processor"),await this.cfg.errorProcessor.handleError(e,r))}catch(e){t.error("Background : BAD - Failed to run error processor : %s",e,e)}}async fireListenerEvent(r){const n=this.cfg.executionListeners||[];for(const s of n)try{await s.onEvent(r)}catch(r){t.error("Failure triggering handler %s : %s",e.trimToNull(s?.label)||"No-name",r)}}async processSingleBackgroundEntry(r){let n=r;$.setOverrideTraceFromInternalBackgroundEntry(n),t.info("Background Process Start: %j",n);const s=new f;await this.conditionallyStartTransactionLog(n),this?.mgr?.modifyPayloadPreProcess&&(t.silly("Firing payload pre-process"),n=await this.mgr.modifyPayloadPreProcess(n));let o=!1;try{await this.fireListenerEvent({type:Pe.ProcessStarting,processorType:n.type,data:n.data,guid:n.guid});const t=this.processors.get(n.type);t||(c.throwFormattedErr("Found no processor for background entry : %j (returning false)",n),await this.fireListenerEvent({type:Pe.NoMatchProcessorName,processorType:n.type,data:n.data,guid:n.guid}));let r=[];if(e.trimToNull(t.dataSchemaName)&&(r=this.modelValidator.validate(t.dataSchemaName,n.data,!1,!1)),r.length>0)await this.fireListenerEvent({type:Pe.DataValidationError,processorType:n.type,data:n.data,errors:r,guid:n.guid}),c.throwFormattedErr("Not processing, data failed validation; entry was %j : errors : %j",n,r);else{let e=await t.handleEvent(n.data,this.mgr);e=e||"SUCCESSFUL COMPLETION : NO RESULT RETURNED",await this.conditionallyCompleteTransactionLog(n,e,null,s.elapsedMS()),await this.fireListenerEvent({type:Pe.ExecutionSuccessfullyComplete,processorType:n.type,data:e,guid:n.guid}),o=!0}}catch(e){t.error("Background Process Error: %j : %s",n,e,e),await this.conditionallyRunErrorProcessor(n,e),await this.conditionallyCompleteTransactionLog(n,null,e,s.elapsedMS()),await this.fireListenerEvent({type:Pe.ExecutionFailedError,processorType:n.type,data:n.data,errors:[c.safeStringifyErr(e)],guid:n.guid})}return t.info("Background Process Stop: %j : %s",n,s.dump()),o}getConfig(){return Object.assign({},this.cfg)}}const _e={Error:"Error",ConvertToEmptyString:"ConvertToEmptyString",Return404NotFoundResponse:"Return404NotFoundResponse"};class Le{static MAXIMUM_LAMBDA_BODY_SIZE_BYTES=5140480;static async combineFilters(e,t){let r=!0;if(t&&t.length>0)for(let n=0;n<t.length&&r;n++)r=await t[n](e);return r}static async applyGzipIfPossible(e){if(e.event?.headers&&e.result){const t=e.event&&e.event.headers?s.extractValueFromMapIgnoreCase(e.event.headers,"accept-encoding"):null;e.result=await X.applyGzipIfPossible(t,e.result)}return!0}static async addConstantHeaders(e,r){return r&&e.result?e.result.headers=Object.assign({},r,e.result.headers):t.warn("Could not add headers - either result or headers were missing"),!0}static async addAWSRequestIdHeader(r,n="X-REQUEST-ID"){return r.result&&e.trimToNull(n)&&n.startsWith("X-")?(r.result.headers=r.result.headers||{},r.result.headers[n]=r.context?.awsRequestId||"Request-Id-Missing"):t.warn("Could not add request id header - either result or context were missing or name was invalid"),!0}static async addAllowEverythingCORSHeaders(e){return Le.addConstantHeaders(e,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"*","Access-Control-Allow-Headers":"*"})}static async addAllowReflectionCORSHeaders(e){return Le.addConstantHeaders(e,{"Access-Control-Allow-Origin":s.caseInsensitiveAccess(e.event.headers,"Origin")||"*","Access-Control-Allow-Methods":s.caseInsensitiveAccess(e.event.headers,"Access-Control-Request-Method")||"*","Access-Control-Allow-Headers":s.caseInsensitiveAccess(e.event.headers,"Access-Control-Request-Headers")||"*"})}static async uriDecodeQueryParams(e){return e?.event?.queryStringParameters&&Object.keys(e.event.queryStringParameters).forEach((t=>{const r=e.event.queryStringParameters[t];r&&(e.event.queryStringParameters[t]=Le.decodeUriComponentAndReplacePlus(r))})),e?.event?.multiValueQueryStringParameters&&Object.keys(e.event.multiValueQueryStringParameters).forEach((t=>{const r=e.event.multiValueQueryStringParameters[t];if(r&&r.length){const n=r.map((e=>Le.decodeUriComponentAndReplacePlus(e)));e.event.multiValueQueryStringParameters[t]=n}})),!0}static decodeUriComponentAndReplacePlus(e){return decodeURIComponent(e.replace(/\+/g," "))}static async fixStillEncodedQueryParams(e){return J.fixStillEncodedQueryParams(e.event),!0}static async disallowStringNullAsPathParameter(t){return t?.event?.pathParameters&&Object.keys(t.event.pathParameters).forEach((r=>{if("null"===e.trimToEmpty(t.event.pathParameters[r]).toLowerCase())throw(new K).withFormattedErrorMessage("Path parameter %s was string -null-",r)})),!0}static async disallowStringNullAsQueryStringParameter(t){return t?.event?.queryStringParameters&&Object.keys(t.event.queryStringParameters).forEach((r=>{if("null"===e.trimToEmpty(t.event.queryStringParameters[r]).toLowerCase())throw(new K).withFormattedErrorMessage("Query parameter %s was string -null-",r)})),!0}static async ensureEventMaps(e){return e.event.queryStringParameters=e.event.queryStringParameters||{},e.event.headers=e.event.headers||{},e.event.pathParameters=e.event.pathParameters||{},!0}static async parseJsonBodyToObject(e){if(e.event?.body)try{e.event.parsedBody=J.jsonBodyToObject(e.event)}catch(e){throw new n("Supplied body was not parsable as valid JSON").withHttpStatusCode(400)}return!0}static async checkMaximumLambdaBodySize(e){if(e.result?.body&&e.result.body.length>Le.MAXIMUM_LAMBDA_BODY_SIZE_BYTES){const t=e.result.body.length-Le.MAXIMUM_LAMBDA_BODY_SIZE_BYTES;throw new n("Response size is "+e.result.body.length+" bytes, which is "+t+" bytes too large for this handler").withHttpStatusCode(500)}return!0}static async validateInboundBody(e){if(e?.event?.parsedBody&&e.routeAndParse){if(e.routeAndParse.mapping.validation){if(!e.modelValidator)throw new ye("Requested body validation but supplied no validator");const r=e.modelValidator.validate(e.routeAndParse.mapping.validation.modelName,e.event.parsedBody,e.routeAndParse.mapping.validation.emptyAllowed,e.routeAndParse.mapping.validation.extraPropertiesAllowed);if(r.length>0){t.info("Found errors while validating %s object %j",e.routeAndParse.mapping.validation.modelName,r);throw new K(...r)}}}else t.debug("No validation since no route specified or no parsed body");return!0}static async validateInboundQueryParams(e){return!0}static async validateInboundPathParams(e){return!0}static async validateOutboundResponse(e){if(e?.rawResult)if(e.routeAndParse.mapping.outboundValidation){t.debug("Applying outbound check to %j",e.rawResult);const r=e.modelValidator.validate(e.routeAndParse.mapping.outboundValidation.modelName,e.rawResult,e.routeAndParse.mapping.outboundValidation.emptyAllowed,e.routeAndParse.mapping.outboundValidation.extraPropertiesAllowed);if(r.length>0)throw t.error("Found outbound errors while validating %s object %j",e.routeAndParse.mapping.outboundValidation.modelName,r),r.unshift("Server sent object invalid according to spec"),(new n).withErrors(r).withHttpStatusCode(500).withDetails(e.rawResult)}else t.debug("Applied no outbound validation because none set");else t.debug("No validation since no outbound body or disabled");return!0}static async autoRespondToOptionsRequestWithCors(t){return"options"!==e.trimToEmpty(t?.event?.httpMethod).toLowerCase()||(t.result={statusCode:200,body:'{"cors":true, "m":2}'},await Le.addAllowReflectionCORSHeaders(t),!1)}static async autoRespond(e,t){const r=t||{message:"Not Implemented"};return e.result={statusCode:200,body:JSON.stringify(r)},!1}static async secureOutboundServerErrorForProduction(e,r,s){if(e?.result?.statusCode&&(null===s||e.result.statusCode===s)){t.warn("Securing outbound error info (was : %j)",e.result.body),e.rawResult=new n(r).withHttpStatusCode(e.result.statusCode);const s=e.result;e.result=X.errorResponse(e.rawResult),e.result.headers=Object.assign({},s.headers||{},e.result.headers||{})}return!0}}class Me{static async requireAllRolesInCommonJwt(e,t){if(!t||0===t.length)throw new ye("You must require at least 1 role");if(!e.event?.authorization?.auth)throw new Y("May not proceed, not authenticated");{const r=e.event.authorization.auth;if(!r.roles||0===r.roles.length)throw new Y("Required role not found");t.forEach((e=>{if(!r.roles.includes(e))throw new Y("Required role not found")}))}return!0}static async requireAnyRoleInCommonJwt(e,t){if(!t||0===t.length)throw new ye("You must require at least 1 role");if(!e.event?.authorization?.auth)throw new Y("May not proceed, not authenticated");{const r=e.event.authorization.auth;if(!r.roles||0===r.roles.length)throw new Y("Required role not found");{let e=!1;if(t.forEach((t=>{!e&&r.roles.includes(t)&&(e=!0)})),!e)throw new Y("Required role not found")}}return!0}static async parseAuthorizationHeader(e,t){if(!e?.event||!t||Array.isArray(t)&&!t.length)throw new ye("Cannot continue - missing event or encryption");{const r=J.extractBearerTokenFromEvent(e?.event);Array.isArray(t)||(t=[t]);for(let n=0;n<t.length&&!e?.event?.authorization?.auth;n++){const s=t[n];try{const t=await s.extractTokenFromAuthorizationHeader(r);e.event.authorization={raw:r,auth:t,error:null}}catch(t){e.event.authorization={raw:r,auth:null,error:t.message}}}}return!0}static async applyOpenApiAuthorization(t){if(e.trimToNull(t?.routeAndParse?.mapping?.authorizerName)){const e=t?.authenticators?.get(t.routeAndParse.mapping.authorizerName);if(!e)throw(new ye).withFormattedErrorMessage("Authorizer %s requested but not found",t.routeAndParse.mapping.authorizerName);if(!t?.event?.authorization?.auth)throw new Y("You need to supply credentials for this endpoint");if(!await e(t.event.authorization,t.event,t.routeAndParse.mapping))throw new fe("You lack privileges to see this endpoint")}return!0}}class ke{static LOG_LEVEL_BEFORE_CHANGE=null;static async setLogLevelForTransaction(e){return ke.LOG_LEVEL_BEFORE_CHANGE=t.getLevel(),!0}static async clearLogLevelForTransaction(e){return ke.LOG_LEVEL_BEFORE_CHANGE&&(t.setLevel(ke.LOG_LEVEL_BEFORE_CHANGE),ke.LOG_LEVEL_BEFORE_CHANGE=null,t.updateTracePrefix(null)),!0}}class Fe{constructor(){}static defaultAuthenticationHeaderParsingEpsilonPreFilters(e){return[t=>Me.parseAuthorizationHeader(t,e),e=>Me.applyOpenApiAuthorization(e)].concat(Fe.defaultEpsilonPreFilters())}static defaultEpsilonPreFilters(){return[e=>Le.autoRespondToOptionsRequestWithCors(e),e=>Le.ensureEventMaps(e),e=>ke.setLogLevelForTransaction(e),e=>Le.parseJsonBodyToObject(e),e=>Le.fixStillEncodedQueryParams(e),e=>Le.uriDecodeQueryParams(e),e=>Le.disallowStringNullAsPathParameter(e),e=>Le.disallowStringNullAsQueryStringParameter(e),e=>Le.validateInboundBody(e),e=>Le.validateInboundQueryParams(e),e=>Le.validateInboundQueryParams(e)]}static defaultEpsilonPostFilters(){return[e=>Le.validateOutboundResponse(e),e=>Le.addAWSRequestIdHeader(e),e=>Le.addAllowReflectionCORSHeaders(e),e=>Le.applyGzipIfPossible(e),e=>Le.checkMaximumLambdaBodySize(e),e=>ke.clearLogLevelForTransaction(e)]}static defaultEpsilonErrorFilters(){return[e=>Le.addAWSRequestIdHeader(e),e=>Le.addAllowReflectionCORSHeaders(e),e=>ke.clearLogLevelForTransaction(e)]}static defaultHttpMetaProcessingConfigWithAuthenticationHeaderParsing(e){return{configName:"EpsilonDefaultHttpMetaProcessingConfig",timeoutMS:3e4,overrideAuthorizerName:null,preFilters:Fe.defaultAuthenticationHeaderParsingEpsilonPreFilters(e),postFilters:Fe.defaultEpsilonPostFilters(),errorFilters:Fe.defaultEpsilonErrorFilters(),nullReturnedObjectHandling:_e.Return404NotFoundResponse}}static defaultHttpMetaProcessingConfig(){return{configName:"EpsilonDefaultHttpMetaProcessingConfig",timeoutMS:3e4,overrideAuthorizerName:null,preFilters:Fe.defaultEpsilonPreFilters(),postFilters:Fe.defaultEpsilonPostFilters(),errorFilters:Fe.defaultEpsilonErrorFilters(),nullReturnedObjectHandling:_e.Return404NotFoundResponse}}static assignDefaultsOnHttpConfig(e){const t={handlers:new Map,authorizers:new Map,defaultMetaHandling:this.defaultHttpMetaProcessingConfig(),staticContentRoutes:{},prefixesToStripBeforeRouteMatch:[],filterHandledRouteMatches:["options .*"]};return Object.assign({},t,e||{})}static findApplicableMeta(e,t,r){let n=null;if(e?.overrideMetaHandling)for(let s=0;s<e.overrideMetaHandling.length&&!n;s++){const o=e.overrideMetaHandling[s];if(!o.methods||0===o.methods.length||o.methods.map((e=>e.toLocaleLowerCase())).includes(t.toLocaleLowerCase())){const e=!!r.match(o.pathRegex);(e&&!o.invertPathMatching||!e&&o.invertPathMatching)&&(n=o.config)}}return n||(n=e.defaultMetaHandling||Fe.defaultHttpMetaProcessingConfig()),n}static openApiYamlToRouterConfig(e,r,n,s){if(!r||!e)throw new ye("Cannot configure, missing either yaml or cfg");const o={routes:[],openApiModelValidator:n,config:Fe.assignDefaultsOnHttpConfig(e)};r?.components?.securitySchemes&&Object.keys(r.components.securitySchemes).forEach((e=>{if(!o.config.authorizers||!o.config.authorizers.get(e))throw(new ye).withFormattedErrorMessage("Doc requires authorizer %s but not found in map",e)}));const a=[],i=e.filterHandledRouteMatches||[];if(r?.paths&&Object.keys(r.paths).forEach((n=>{Object.keys(r.paths[n]).forEach((c=>{const l=Fe.openApiPathToRouteParserPath(n),u=c+" "+n,d=Fe.findApplicableMeta(e,c,n),p=r.paths[n][c],h=n.startsWith(s.httpSubmissionPath),g=n===s.httpMetaEndpoint,m=n===s.httpStatusPath;if(h&&o.config.handlers.set(u,((e,t)=>s.handleBackgroundSubmission(e,t))),g&&o.config.handlers.set(u,((e,t)=>s.handleBackgroundMetaRequest(e,t))),m&&o.config.handlers.set(u,((e,t)=>s.handleBackgroundStatusRequest(e,t))),!o.config.handlers||!o.config.handlers.get(u)){i.find((e=>u.match(e)))?(t.debug("Adding filter-handled handler for %s",u),o.config.handlers.set(u,(e=>we.expectedHandledByFilter(e)))):a.push(u)}if(p&&p.security&&p.security.length>1)throw new ye("Epsilon does not currently support multiple security (path was "+u+")");const f=p.security&&1==p.security.length?Object.keys(p.security[0])[0]:null,y={path:l,method:c,function:o.config.handlers.get(u),authorizerName:d.overrideAuthorizerName||f,metaProcessingConfig:d,validation:null,outboundValidation:null};if(p.requestBody&&p.requestBody.content&&p.requestBody.content["application/json"]&&p.requestBody.content["application/json"].schema){const e=p.requestBody.content;t.silly("Applying schema %j to %s",e,u);const r=this.findAndValidateModelName(c,n,e,o.config.overrideModelValidator||o.openApiModelValidator),s={extraPropertiesAllowed:!0,emptyAllowed:!E.parseBool(p.requestBody.required),modelName:r};y.validation=s}if(p.responses&&p.responses[200]&&p.responses[200].content&&p.responses[200].content["application/json"]&&p.responses[200].content["application/json"].schema){const e=p.responses[200].content;t.silly("Applying schema %j to %s",e,u);const r={extraPropertiesAllowed:!1,emptyAllowed:!1,modelName:this.findAndValidateModelName(c,n,e,o.config.overrideModelValidator||o.openApiModelValidator)};y.outboundValidation=r}o.routes.push(y)}))})),a.length>0)throw(new ye).withFormattedErrorMessage("Missing expected handlers : %j",a);return o}static findAndValidateModelName(e,t,r,n){let s;const o=r["application/json"].schema.$ref,a=r["application/json"].schema.type;if(o){if(s=o.substring(o.lastIndexOf("/")+1),!n.fetchModel(s))throw new ye(`Path ${e} ${t} refers to schema ${s} but its not in the schema section`)}else if(a){s=`${e}-${t}-requestBodyModel`;const o=r["application/json"].schema;n.addModel(s,o)}return s}static openApiPathToRouteParserPath(e){let t=e;if(t){let e=t.indexOf("{");for(;e>-1;){const r=t.indexOf("}");t=t.substring(0,e)+":"+t.substring(e+1,r)+t.substring(r+1),e=t.indexOf("{")}}return t}}class Be{static async runHandler(e,r){const n=Be.findHandler(r,e.event,e.context);t.debug("Processing event with epsilon: %j",Be.eventToStringForLog(e.event));let s=await n;if(g.isTimeoutToken(s))throw s.writeToLog(),new Z("Timed out");return t.debug("Initial return value : %j",s),s=Be.applyNullReturnedObjectHandling(s,r.mapping.metaProcessingConfig.nullReturnedObjectHandling),e.rawResult=s,e.result=X.coerceToProxyResult(s),!0}static applyNullReturnedObjectHandling(e,r){let s=e;if(null==e){if(r===_e.Error)throw t.error("Null object returned and Error specified, throwing 500"),new n("Null object").withHttpStatusCode(500);if(r===_e.Return404NotFoundResponse)throw new me("Resource not found");if(r!==_e.ConvertToEmptyString)throw new n("Cant happen - failed enum check").withHttpStatusCode(500);t.warn("Null object returned from handler and convert not specified, converting to empty string"),s=""}return s}static async findHandler(e,t,r,n=!0){let s=null;if(e)t.pathParameters=Object.assign({},t.pathParameters,e.parsed),s=h.timeout(e.mapping.function(t,r),"Timed out after "+e.mapping.metaProcessingConfig.timeoutMS+" ms. Request was "+Be.eventToStringForLog(t),e.mapping.metaProcessingConfig.timeoutMS);else if(n)throw new me("No such endpoint");return s}static addRunHandlerAsFilterToList(e,t){e&&e.push((e=>Be.runHandler(e,t)))}static eventToStringForLog(e){const t=structuredClone(e);return t?.authorization?.raw&&(t.authorization.raw=Be.redact(t.authorization.raw)),t?.headers?.authorization&&(t.headers.authorization=Be.redact(t.headers.authorization)),JSON.stringify(t)}static redact(t){return t?e.obscure(t,1,1):t}}class xe{routerConfig;static MAXIMUM_LAMBDA_BODY_SIZE_BYTES=5140480;constructor(e){this.routerConfig=e,u.notNullOrUndefined(e)}get router(){return this.routerConfig}extractLabel(t,r){return"WEB:"+e.trimToEmpty(t.httpMethod).toUpperCase()+":"+t.path}handlesEvent(e){return T.isValidApiGatewayEvent(e)}async processEvent(e,r){if(!this.routerConfig)throw new Error("Router config not found");const n=Object.assign({},{parsedBody:null,authorization:null,convertedFromV2Event:!1},e),s=await this.openApiLambdaHandler(n,r);return $.addTraceToProxyResult(s),t.updateTracePrefix(null),s}async openApiLambdaHandler(e,r){const s=this.findBestMatchingRoute(e),o=s?.mapping?.metaProcessingConfig?s.mapping.metaProcessingConfig:this.routerConfig.config.defaultMetaHandling,a={event:e,context:r,result:null,rawResult:null,routeAndParse:s,modelValidator:this.routerConfig.config.overrideModelValidator||this.routerConfig.openApiModelValidator,authenticators:this.routerConfig.config.authorizers};try{let e=Object.assign([],o.preFilters||[]);Be.addRunHandlerAsFilterToList(e,s),e=e.concat(o.postFilters||[]),await Le.combineFilters(a,e)}catch(e){const r=n.wrapError(e);a.result=X.errorResponse(r);try{await Le.combineFilters(a,o.errorFilters)}catch(e){t.error("REALLY BAD - FAILED WHILE PROCESSING ERROR FILTERS : %s",e)}}return a.result}findBestMatchingRoute(e){let r=null;const n=this.cleanPath(e),s=e.httpMethod.toLowerCase(),o=this.routerConfig.routes.map((e=>{let t=null;if(e.method&&e.method.toLowerCase()===s){const r=new k(e.path),s=r.match(n);!1!==s&&(t={mapping:e,route:r,parsed:s})}return t})).filter((e=>null!=e));return o.sort(((e,t)=>Object.keys(e.parsed).length-Object.keys(t.parsed).length)),r=o&&o.length>0?o[0]:null,r||t.debug("Failed to find handler for %s (cleaned path was %s, strip prefixes were %j)",e.path,n,this.routerConfig.config.prefixesToStripBeforeRouteMatch),r}cleanPath(e){let t=e.path;for(;t.startsWith("/");)t=t.substring(1);for(this.routerConfig.config.prefixesToStripBeforeRouteMatch&&this.routerConfig.config.prefixesToStripBeforeRouteMatch.forEach((e=>{t.toLowerCase().startsWith(e.toLowerCase()+"/")&&(t=t.substring(e.length))}));t.startsWith("/");)t=t.substring(1);return t="/"+t,t}}class De{constructor(){}static epsilonConfigToEpsilonGlobalHandler(e,t){return new pe(De.epsilonConfigToEpsilonInstance(e,t))}static epsilonConfigToEpsilonInstance(e,r){this.validateGlobalConfig(e);const n=e?.label||"NO EPSILON CONFIG LABEL SET";t.info("Creating epsilon : %s : BM : %j",n,r);const s=De.parseOpenApiDocument(e.openApiYamlString),o=De.openApiDocToValidator(s),a=new Ne(e.backgroundConfig,o,r),i=e.backgroundConfig?new Oe(e.backgroundConfig,r,o):null,c=e.httpConfig?Fe.openApiYamlToRouterConfig(e.httpConfig,s,o,a):null;return{config:e,parsedOpenApiDoc:s,modelValidator:o,webHandler:c?new xe(c):null,backgroundHandler:i,backgroundManager:r}}static parseOpenApiDocument(e){if(!e)throw new ye("Cannot configure, missing either yaml or cfg");return L.load(e)}static openApiDocToValidator(e){let t=null;return e?.components?.schemas&&(t=M.createFromParsedObject(e.components.schemas)),t}static validateGlobalConfig(e){e||c.throwFormattedErr("Config may not be null"),e.openApiYamlString||c.throwFormattedErr("Config must define an open api document"),e.cron&&!e.cron.timezone&&c.throwFormattedErr("Cron is defined, but timezone is not set")}}class He{get typeName(){return"EpsilonSampleInputValidated"}async handleEvent(e,r){t.info("Running SampleInputValidatedProcessor, data was : %j",e)}get dataSchemaName(){return"BackgroundSampleInputValidatedProcessorData"}}class je{static async simpleNoAuthenticationLogAccess(e,r){return t.debug("Auth requested for %s : %j",r.path,e?.auth),!0}static async simpleLoggedInAuth(e,r){const n=!!e?.auth;return t.silly("SimpleLoggedInAuth returning %s for %s",n,r.path),n}static async simpleRoleRouteAuth(e,r,n,s=null,o=null){let a=!0;const i=e?.auth;return i?(s&&(s.forEach((e=>{a=a||i.roles.indexOf(e)>-1})),a||t.warn("Request to %s failed to find at least one of %j",n.path,s)),a&&o&&(o.forEach((e=>{a=a&&i.roles.indexOf(e)>-1})),a||t.warn("Request to %s failed to find all of %j",n.path,o))):(t.warn("Cannot authenticate - no parsed auth found"),a=!1),a}}class qe{constructor(){}static async emptyContext(){return{}}static async defaultEpsilonApolloContext(r,n){const s=J.extractBearerTokenFromEvent(r.lambdaEvent);let o=null;e.trimToNull(s)&&n&&(t.info("Got : %s",s),o=await n.decodeToken(s,0));return{user:o,bearerTokenString:s,headers:r.lambdaEvent.headers,functionName:r.lambdaContext.functionName,lambdaEvent:r.lambdaEvent,lambdaContext:r.lambdaContext}}static async nonRouteableOnlyEpsilonApolloContext(t,r){const n=e.trimToNull(s.extractValueFromMapIgnoreCase(t.lambdaEvent.headers,"host"));if(!J.hostIsLocalOrNotRoutableIP4(n))throw new Y("May only run local / non-routeable : "+n);return qe.defaultEpsilonApolloContext(t,r)}}const Ge={None:"None",All:"All",Reflective:"Reflective"};class Ue{static async handlePathWithApollo(e,t,r,n){let s=!1;if(e.event?.path&&t&&t.test(e.event.path)){if(e.result=await Ue.processApolloRequest(e.event,e.context,r,n),n?.corsMethod)switch(n.corsMethod){case Ge.All:await Le.addAllowEverythingCORSHeaders(e);break;case Ge.Reflective:await Le.addAllowReflectionCORSHeaders(e)}}else s=!0;return s}static async processApolloRequest(r,s,a,i){t.silly("Processing event with apollo: %j",r);let c=null;u.notNullOrUndefined(a,"apolloServer"),a.assertStarted("Cannot process with apollo - instance not started");const l=new P;for(const e in r.headers)l.set(e,r.headers[e]);const d=e.trimToEmpty(r.httpMethod).toUpperCase();let p=null;if(e.trimToNull(r.body)){const e=r.isBase64Encoded?o.base64StringToString(r.body):r.body;p=JSON.parse(e)}const m={method:d,headers:l,search:"GET"===d&&r?.queryStringParameters?Object.keys(r.queryStringParameters).map((e=>encodeURIComponent(e)+"="+encodeURIComponent(r.queryStringParameters[e]))).join("&"):null,body:p},f=i?.timeoutMS??s.getRemainingTimeInMillis()-500,E=i?.context??qe.emptyContext,y=a.executeHTTPGraphQLRequest({httpGraphQLRequest:m,context:()=>E({lambdaContext:s,lambdaEvent:r})});let w=null;if(f?w=await h.timeout(y,"Apollo timed out after "+f+" ms.",f):(t.warn("No timeout set even after defaulting for Apollo"),w=await y),g.isTimeoutToken(w))throw w.writeToLog(),new Z("Timed out");const S=w,T={};for(const[e,t]of S.headers.entries())T[e]=t;if("chunked"===S.body.kind)throw new n("Apollo returned chunked result").withHttpStatusCode(500).withRequestId($.currentRequestId());const A=e.trimToEmpty(S?.body?.string);return c={body:o.generateBase64VersionOfString(A),headers:T,multiValueHeaders:{},isBase64Encoded:!0,statusCode:S.status||200},"GET"===d&&"text/html"!==c.headers["content-type"]&&A.indexOf("<!DOCTYPE html>")>=0&&(t.info("Forcing content type to html for the sandbox page"),c.headers=c.headers||{},c.headers["content-type"]="text/html"),i.debugOutputCallback&&await i.debugOutputCallback(c),c}static addApolloFilterToList(e,t,r,n){e&&e.push((e=>Ue.handlePathWithApollo(e,t,r,n)))}}class Ve{async handleError(e,r){t.error("-------- ERROR PROCESSED : %j : %s----",e,r)}}class Qe extends Ie{_localBus=new F;get backgroundManagerName(){return"SingleThreadLocalBackgroundManager"}constructor(){super()}immediateProcessQueue(){return this._localBus}async addEntryToQueue(e,r){const n=await this.wrapEntryForInternal(e),s=n.guid;return t.info("Add entry to queue (local) : %j : Start : %s",e,r),this._localBus.next(n),s}async fireImmediateProcessRequest(e){let r=null;const n=await this.wrapEntryForInternal(e);return r=n.guid,t.info("Fire immediately (local) : %j ",e),this._localBus.next(n),r}async fireStartProcessingRequest(){let e=null;return t.info("Fire start processing request (local, ignored)"),e="NO-OP","NO-OP"}async fetchApproximateNumberOfQueueEntries(){let e=null;return e=0,0}async takeEntryFromBackgroundQueue(){return t.info("Called takeEntryFromBackgroundQueue on SingleThreadedLocal - returning empty"),[]}}class ze{constructor(){}static SAMPLE_OPEN_API_DOC="openapi: 3.0.0\ninfo:\n version: v0\n title: SampleAPI\ntags:\n - name: CORS\n description: These endpoints are here to support CORS\n - name: Public\n description: These endpoints can be called without setting the authorization header\n - name: Secure\n description: Authentication and authorization of the API\npaths:\n /:\n get:\n description: Redirects to the /meta/server endpoint\n tags:\n - Meta\n - Public\n responses:\n '301':\n description: Redirects to the /meta/server endpoint\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Standard CORS header response\n /event:\n get:\n description: Tests URL parsing and returns event as JSON\n tags:\n - Meta\n - Public\n responses:\n '200':\n description: The parsed event, as JSON\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Standard CORS header response\n /meta/server:\n get:\n description: >\n Returns information about the current build and time. Can be used to\n test error-handling code by passing a specific http error code in the\n error query parameter. Can also be used to process specific named tests\n by passing those names to the test parameter.\n tags:\n - Public\n parameters:\n - name: error\n in: query\n description: >-\n If set, throw a specific error for testing (valid are\n 500,400,403,404)\n required: false\n schema:\n type: number\n - name: test\n in: query\n description: Run a specific named test (currently none are publicly available)\n required: false\n schema:\n type: string\n responses:\n '200':\n description: Success\n '400':\n description: Simulated bad request\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n '403':\n description: Simulated unauthorized\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n '404':\n description: Simulated not found\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n '500':\n description: Simulated internal server error\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Standard CORS header response\n /meta/user:\n get:\n description: >\n When logged in, returns the contents of the JWT token as the server\n parses it. This should match what you get when you process the token\n returned from the \"POST /access-token\" endpoint through a standard JWT\n token processor.\n tags:\n - Meta\n security:\n - SampleAuthorizer: []\n responses:\n '200':\n description: Success\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/AccessTokenContents'\n '401':\n description: Unauthorized\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Success\n '401':\n description: Unauthorized\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n /meta/item/{itemId}:\n get:\n description: >\n Example of a path param\n parameters:\n - name: itemId\n in: path\n description: A sample item id\n required: true\n schema:\n type: string\n tags:\n - Meta\n responses:\n '200':\n description: Success\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/Empty'\n '401':\n description: Unauthorized\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n options:\n tags:\n - CORS\n parameters:\n - name: itemId\n in: path\n description: A sample item id\n required: true\n schema:\n type: string\n responses:\n '200':\n description: Success\n '401':\n description: Unauthorized\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n\n /meta/sample-item:\n get:\n description: >\n Example of an object returned\n parameters:\n - name: num\n in: path\n description: Number to return in the number value\n required: false\n schema:\n type: number\n tags:\n - Meta\n responses:\n '200':\n description: Success\n content:\n 'application/json':\n schema:\n $ref: '#/components/schemas/BackgroundSampleInputValidatedProcessorData'\n post:\n description: >\n Example of an object posted\n requestBody:\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/BackgroundSampleInputValidatedProcessorData'\n description: Request to refresh the access token or change active user\n required: true\n tags:\n - Meta\n responses:\n '200':\n description: Success\n content:\n 'application/json':\n schema:\n $ref: '#/components/schemas/BackgroundSampleInputValidatedProcessorData'\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Success\n\n /secure/access-token:\n post:\n tags:\n - Secure\n - Public\n responses:\n '200':\n description: Success\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/AccessTokenResponse'\n '400':\n description: Invalid request\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n '403':\n description: Invalid credentials\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n requestBody:\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/AccessTokenRequest'\n description: Request to refresh the access token or change active user\n required: true\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Standard CORS header response\n /multi/fixed:\n get:\n description: Tests path matching from most specific to least (this is most)\n tags:\n - Public\n responses:\n '200':\n description: Success\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Standard CORS header response\n /multi/{v}:\n get:\n description: Tests path matching from most specific to least (this is least)\n tags:\n - Public\n parameters:\n - name: v\n in: path\n description: A variable\n required: true\n schema:\n type: string\n responses:\n '200':\n description: Success\n options:\n tags:\n - CORS\n parameters:\n - name: v\n in: path\n description: A variable\n required: true\n schema:\n type: string\n responses:\n '200':\n description: Standard CORS header response\n\n /err/{code}:\n get:\n description: Tests path matching from most specific to least (this is least)\n tags:\n - Public\n parameters:\n - name: code\n in: path\n description: Error code\n required: true\n schema:\n type: number\n responses:\n '200':\n description: Success\n options:\n tags:\n - CORS\n parameters:\n - name: code\n in: path\n description: A variable\n required: true\n schema:\n type: number\n responses:\n '200':\n description: Standard CORS header response\n\n /background:\n post:\n responses:\n '200':\n description: Success\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/BackgroundQueueResponse'\n '400':\n description: Invalid request\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n '403':\n description: Invalid credentials\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n requestBody:\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/Empty'\n description: Content to echo\n required: true\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Standard CORS header response\n\n /background/meta:\n get:\n responses:\n '200':\n description: Success\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/BackgroundMetaResponse'\n '400':\n description: Invalid request\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n '403':\n description: Invalid credentials\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Standard CORS header response\n\nx-amazon-apigateway-binary-media-types:\n - '*/*'\nx-amazon-apigateway-gateway-responses:\n UNAUTHORIZED:\n statusCode: 401\n responseParameters:\n gatewayresponse.header.Access-Control-Allow-Origin: \"'*'\"\n responseTemplates:\n application/json: '{\"errors\":[\"Unauthorized\"], \"httpStatusCode\": 401}'\n MISSING_AUTHENTICATION_TOKEN:\n statusCode: 404\n responseParameters:\n gatewayresponse.header.Access-Control-Allow-Origin: \"'*'\"\n responseTemplates:\n application/json: '{\"errors\":[\"No such endpoint\"], \"httpStatusCode\": 404}'\n INTEGRATION_TIMEOUT:\n statusCode: 504\n responseParameters:\n gatewayresponse.header.Access-Control-Allow-Origin: \"'*'\"\n responseTemplates:\n application/json: '{\"errors\":[\"Timeout\"], \"httpStatusCode\": 504}'\n DEFAULT_5XX:\n statusCode: 500\n responseParameters:\n gatewayresponse.header.Access-Control-Allow-Origin: \"'*'\"\n responseTemplates:\n application/json: '{\"errors\":[\"Internal Server Error\"], \"httpStatusCode\": 500}'\n\nservers:\n - url: 'https://api.sample.com/dev'\ncomponents:\n securitySchemes:\n SampleAuthorizer:\n type: apiKey\n name: Authorization\n in: header\n schemas:\n Empty:\n type: object\n title: Empty Schema\n\n AccessTokenRequest:\n type: object\n title: Access Token Request\n required:\n - email\n - password\n - scope\n properties:\n email:\n type: string\n description: Email address of the account to authenticate\n format: email\n minLength: 7\n password:\n type: string\n description: Password of the account to authenticate\n minLength: 6\n scope:\n type: string\n enum:\n - OWNER\n - ADVERTISER\n - GLOBAL\n - RUN_AS_OWNER\n - RUN_AS_ADVERTISER\n description: |\n What style of account to authenticate:\n * `OWNER` - A device owner account\n * `ADVERTISER` - A advertising account\n * `GLOBAL` - Used by Adomni customer service\n * `RUN_AS_OWNER` - Used by Adomni customer service\n * `RUN_AS_ADVERTISER` - Used by Adomni customer service\n default: OWNER\n runAs:\n type: string\n description: Used by Adomni customer service\n format: email\n expirationSeconds:\n type: number\n minimum: 10\n maximum: 3600\n default: 3600\n AccessTokenResponse:\n type: object\n title: Access Token Response\n required:\n - token\n - expires\n properties:\n token:\n type: string\n description: A JWT access token for the API\n expires:\n type: number\n format: int64\n description: 'The time this token will expire, expressed in epoch ms'\n AccessTokenContents:\n type: object\n title: Access Token Contents\n description: The contents of the JWT token\n required:\n - exp\n - iss\n - sub\n - iat\n - user\n properties:\n exp:\n type: number\n description: >-\n Expiration claim - The time this token will expire, expressed in\n epoch ms\n iss:\n type: string\n description: Issuer claim - Who created the token\n sub:\n type: string\n description: Subject claim - The target of the token (typically user email)\n iat:\n type: number\n description: >-\n Issued at claim - The time this token was created, expressed in\n epoch ms\n user:\n type: object\n description: Object describing the user authenticated by this token\n ApiErrorResponse:\n type: object\n title: API Error Response\n required:\n - errors\n - httpStatusCode\n properties:\n errors:\n type: array\n items:\n type: string\n description: List of the errors that occurred\n httpStatusCode:\n type: number\n description: Http status code of this error\n detailCode:\n type: number\n description: Adomni detail status code for this error\n BackgroundQueueResponse:\n type: object\n title: Background Queue Response\n description: When any of the background endpoints are hit, this is what will be returned\n required:\n - resultId\n - success\n properties:\n processHandling:\n type: string\n enum: ['Queued', 'Immediate']\n success:\n type: boolean\n resultId:\n type: string\n BackgroundMetaResponse:\n type: object\n title: Background Meta Response\n description: If\n properties:\n validTypes:\n type: array\n items:\n type: string\n currentQueueLength:\n type: number\n\n BackgroundSampleInputValidatedProcessorData:\n type: object\n title: BackgroundSampleInputValidatedProcessorData\n description: This is used for testing the background validator\n required:\n - nameParam\n - numberParam\n properties:\n nameParam:\n type: string\n description: A sample name parameter\n minimum: 0\n maximum: 10\n numberParam:\n type: number\n description: A sample number parameter\n";static SAMPLE_SERVER_GRAPHQL="schema {\n query: RootQueryType\n}\n\ntype RootQueryType {\n serverMeta: ServerMeta\n forceTimeout: ForceTimeout\n}\n\ntype ServerMeta {\n version: String\n serverTime: String\n status: String\n}\n\ntype ForceTimeout {\n placeholder: String\n}\n"}class We{constructor(){}static async createSampleApollo(){const e=ze.SAMPLE_SERVER_GRAPHQL;t.silly("Creating apollo from : %s",e);const r=O(e),n=new I({introspection:!0,typeDefs:r,resolvers:{RootQueryType:{serverMeta:async e=>({version:"A1",serverTime:(new Date).toISOString()}),forceTimeout:async e=>(await h.wait(18e5),{placeholder:"A1"})}},plugins:[_({footer:!1})]});return await n.start(),n}static async createSampleEpsilonConfig(t){const r=ze.SAMPLE_OPEN_API_DOC,n=new Map;n.set("SampleAuthorizer",((e,t)=>je.simpleLoggedInAuth(e,t))),n.set("LogAuthorizer",((e,t)=>je.simpleNoAuthenticationLogAccess(e,t)));const s=new Map;s.set("get /",((e,t)=>we.sample(e,null,t))),s.set("get /meta/server",(e=>we.sample(e))),s.set("get /meta/user",(e=>we.sample(e))),s.set("get /meta/item/{itemId}",(e=>we.sample(e))),s.set("post /secure/access-token",(e=>we.sample(e))),s.set("get /multi/fixed",(e=>we.sample(e,"fixed"))),s.set("get /multi/{v}",(e=>we.sample(e,"variable"))),s.set("get /event",(e=>Promise.resolve({statusCode:200,headers:{"Content-Type":"application/json"},body:JSON.stringify(e,null,2)}))),s.set("get /err/{code}",(e=>{const t=c.fErr("Fake Err : %j",e);throw t.statusCode=l.safeNumber(e.pathParameters.code),t})),s.set("get /meta/sample-item",(async e=>({numberParam:l.safeNumber(e.queryStringParameters.num)||5,nameParam:"Test-String"}))),s.set("post /meta/sample-item",(async t=>{const r=t.parsedBody;return!0===E.parseBool(e.trimToNull(t.queryStringParameters.forceFail))&&(r.numberParam="test"),r}));const o=new Se(["abcd1234"],"sample.erigir.com").withParseFailureLogLevel(i.debug).withExtraDecryptionKeys(["abcdefabcdef"]).withOldKeyUseLogLevel(i.info),a=Fe.defaultHttpMetaProcessingConfigWithAuthenticationHeaderParsing(o);a.timeoutMS=1e4,Ue.addApolloFilterToList(a.preFilters,new RegExp(".*graphql.*"),await We.createSampleApollo(),{context:e=>qe.defaultEpsilonApolloContext(e,o.jwtRatchet),timeoutMS:5e3,corsMethod:Ge.All}),a.errorFilters.push((e=>Le.secureOutboundServerErrorForProduction(e,"Clean Internal Server Error",500)));const u=Object.assign({},a);u.preFilters=Object.assign([],u.preFilters),u.preFilters.splice(8,1);return{label:t,openApiYamlString:r,httpConfig:{defaultMetaHandling:a,handlers:s,authorizers:n,overrideMetaHandling:[{pathRegex:"/background",methods:null,config:Object.assign({},a,{overrideAuthorizerName:"LogAuthorizer"})},{pathRegex:"/meta/server",methods:["GET"],config:u}],prefixesToStripBeforeRouteMatch:["v0"],filterHandledRouteMatches:["options .*"]},backgroundConfig:{httpMetaEndpoint:"/background/meta",httpSubmissionPath:"/background",implyTypeFromPathSuffix:!1,processors:[new Te,new Ae,new Re,new He,new be],errorProcessor:new Ve}}}static async createSampleEpsilonGlobalHandler(e){const t=await We.createSampleEpsilonConfig(e),r=new Qe,n=De.epsilonConfigToEpsilonInstance(t,r);return new pe(n)}static async createSampleBatchOnlyEpsilonGlobalHandler(e){const t=await We.createSampleEpsilonConfig(e);t.httpConfig.handlers=new Map;const r=Object.assign({},t.httpConfig.defaultMetaHandling);r.preFilters=r.preFilters.concat([e=>Le.autoRespond(e,{message:"Background Processing Only"})]),t.httpConfig.overrideMetaHandling=[{pathRegex:".*background.*",invertPathMatching:!0,config:r}],t.httpConfig.filterHandledRouteMatches=[".*"];const n=new Qe,s=De.epsilonConfigToEpsilonInstance(t,n);return new pe(s)}}class Ye{globalHandler;port;https;server;constructor(e,t=8888,r=!1){this.globalHandler=e,this.port=t,this.https=r}async runServer(){return new Promise(((e,r)=>{try{if(t.info("Starting Epsilon server on port %d",this.port),this.https){const e={key:ge.CLIENT_KEY_PEM,cert:ge.CLIENT_CERT_PEM};t.info("Starting https server - THIS SERVER IS NOT SECURE! The KEYS are in the code! Testing Server Only - Use at your own risk!"),this.server=v.createServer(e,this.requestHandler.bind(this)).listen(this.port)}else this.server=C.createServer(this.requestHandler.bind(this)).listen(this.port);t.info("Epsilon server is listening"),process.on("SIGINT",(()=>{t.info("Caught SIGINT - shutting down test server..."),this.server.close(),e(!0)}))}catch(e){t.error("Local server failed : %s",e,e),r(e)}}))}async requestHandler(t,r){const n={awsRequestId:"LOCAL-"+e.createType4Guid(),getRemainingTimeInMillis:()=>3e5},s=await Ye.messageToApiGatewayEvent(t,n),o=J.eventIsAGraphQLIntrospection(s)?i.silly:i.info;if("/epsilon-poison-pill"==s.path)return this.server.close(),!0;{const e=await this.globalHandler.lambdaHandler(s,n);return await Ye.writeProxyResultToServerResponse(e,r,o)}}static async bodyAsBase64String(e){return new Promise(((t,r)=>{const n=[];e.on("data",(e=>{n.push(e)})),e.on("end",(()=>{const e=Buffer.concat(n).toString("base64");t(e)}))}))}static async messageToApiGatewayEvent(e,t){const r=await Ye.bodyAsBase64String(e),n=e.url.indexOf("/",1),s=e.url.substring(1,n),o=e.url.substring(n+1),a=(new Date).getTime(),i=R.utc().toFormat("dd/MMM/yyyy:hh:mm:ss ZZ"),c=Ye.parseQueryParamsFromUrlString(o),l=Object.assign({},e.headers);l["X-Forwarded-Proto"]="http";return{body:r,multiValueHeaders:{},multiValueQueryStringParameters:{},resource:"/{proxy+}",path:e.url,httpMethod:e.method.toLowerCase(),isBase64Encoded:!0,queryStringParameters:c,pathParameters:{proxy:o},stageVariables:{baz:"qux"},headers:l,requestContext:{accountId:"123456789012",resourceId:"123456",stage:s,requestId:t.awsRequestId,requestTime:i,requestTimeEpoch:a,identity:{apiKeyId:null,clientCert:null,principalOrgId:null,apiKey:null,cognitoIdentityPoolId:null,accountId:null,cognitoIdentityId:null,caller:null,accessKey:null,sourceIp:"127.0.0.1",cognitoAuthenticationType:null,cognitoAuthenticationProvider:null,userArn:null,userAgent:"Custom User Agent String",user:null},path:e.url,domainName:e.headers.host,resourcePath:"/{proxy+}",httpMethod:e.method.toLowerCase(),apiId:"1234567890",protocol:"HTTP/1.1",authorizer:null}}}static async writeProxyResultToServerResponse(e,r,n){if(t.levelIsEnabled(n))if(e.isBase64Encoded){const r=structuredClone(e);r.body=o.base64StringToString(r.body),r.isBase64Encoded=!1,t.logByLevel(n,"Result (UB64): %j",r)}else t.logByLevel(n,"Result: %j",e);r.statusCode=e.statusCode,e.headers&&Object.keys(e.headers).forEach((t=>{r.setHeader(t,String(e.headers[t]))})),e.multiValueHeaders&&Object.keys(e.multiValueHeaders).forEach((t=>{r.setHeader(t,e.multiValueHeaders[t].join(","))}));const s=e.isBase64Encoded?Buffer.from(e.body,"base64"):Buffer.from(e.body);return r.end(s),!!e.body}static parseQueryParamsFromUrlString(e){const t={},r=e.split("?");if(r.length<2)return t;const n=r.slice(1).join("?").split("&");for(const e of n){const r=e.split("="),n=r[0],s=r.slice(1).join("=");t[n]=s}return t}static async runSampleBatchOnlyServerFromCliArgs(e){t.setLevel(i.debug);const r=await We.createSampleBatchOnlyEpsilonGlobalHandler("SampleBatchOnlyLocalServer-"+Date.now()),n=new Ye(r),s=await n.runServer();t.info("Res was : %s",s)}static async runSampleLocalServerFromCliArgs(e){t.setLevel(i.debug);const r=new Se(["abcd1234"],"sample-server"),n=await r.createJWTStringAsync("asdf",{},["USER"],3600);t.info("Use token: %s",n);const s=await We.createSampleEpsilonGlobalHandler("SampleLocalServer-"+Date.now()),o=new Ye(s,8888,!0),a=await o.runServer();t.info("Res was : %s",a)}}class Ke{port;containerUrl;server;aborted=!1;constructor(e=8889,t="http://localhost:9000/2015-03-31/functions/function/invocations"){this.port=e,this.containerUrl=t}async runServer(){return new Promise(((e,r)=>{try{t.info("Starting Epsilon container-wrapper server on port %d calling to %s",this.port,this.containerUrl),this.server=C.createServer(this.requestHandler.bind(this)).listen(this.port),t.info("Epsilon server is listening"),process.on("SIGINT",(()=>{t.info("Caught SIGINT - shutting down test server..."),this.aborted=!0,e(!0)}))}catch(e){t.error("Local server failed : %s",e,e),r(e)}}))}async requestHandler(r,n){const s={awsRequestId:"LOCAL-"+e.createType4Guid(),getRemainingTimeInMillis:()=>3e5},o=await Ye.messageToApiGatewayEvent(r,s),a=J.eventIsAGraphQLIntrospection(o)?i.silly:i.info;t.logByLevel(a,"Processing event: %j",o);if("/epsilon-poison-pill"==o.path)return this.aborted=!0,!0;try{const e=await N(this.containerUrl,{method:"POST",body:JSON.stringify(o)});n.statusCode=e.status,e.headers.forEach(((e,t)=>{n.setHeader(t,e)}));const t=await e.arrayBuffer();return n.end(new Uint8Array(t)),!0}catch(e){return t.error("Failed: %s : Body was %s Response was : %j",e,null,undefined,e),'{"bad":true}'}}static async runFromCliArgs(e){try{t.setLevel(i.debug),t.debug("Running local container server : %j",process?.argv);B.argsAfterCommand(["run-local-container-server"]);const e=new Ke;await e.runServer(),t.info("Got res server"),process.exit(0)}catch(e){t.error("Error : %s",e),process.exit(1)}}}class Je{dynamo;tableName;env;backgroundQueueName;constructor(e,t,r,n){this.dynamo=e,this.tableName=t,this.env=r,this.backgroundQueueName=n}async onEvent(e){const t={env:this.env,backgroundQueueName:this.backgroundQueueName,requestId:$.currentRequestId(),guid:e.guid,processTypeName:e.processorType,state:e.type.toString(),timestampEpochMs:(new Date).getTime()};if(e.type==Pe.DataValidationError){const r=e?.errors?.length?e.errors:["No-Error"];t.errors=r}else if(e.type==Pe.ProcessStarting)t.params=e.data;else if(e.type==Pe.ExecutionFailedError){const r=e?.errors?.length?e.errors:["No-Error"];t.errors=r}await this.dynamo.simplePut(this.tableName,t)}}class Xe extends Error{static EPSILON_BACKGROUND_PROCESS_ERROR_FLAG_KEY="__epsilonBackgroundProcessErrorFlag";_errors;_detailErrorCode;_details;_requestId;_wrappedError;constructor(...e){super(Xe.combineErrorStringsWithDefault(e)),Object.setPrototypeOf(this,Xe.prototype),this._errors=e,this[Xe.EPSILON_BACKGROUND_PROCESS_ERROR_FLAG_KEY]=!0}static combineErrorStringsWithDefault(e,t="Internal Server Error"){return e&&e.length>0?e.join(","):t}setFormattedErrorMessage(e,...t){const r=D.format(e,...t);this.errors=[r]}withFormattedErrorMessage(e,...t){return this.setFormattedErrorMessage(e,...t),this}withErrors(e){return this.errors=e,this}withDetailErrorCode(e){return this._detailErrorCode=e,this}withDetails(e){return this._details=e,this}withRequestId(e){return this._requestId=e,this}withWrappedError(e){return this._wrappedError=e,this}isWrappedError(){return!!this._wrappedError}static wrapError(e){let t=null;return t=Xe.objectIsEpsilonBackgroundProcessError(e)?e:new Xe(e.message).withWrappedError(e),t}static objectIsEpsilonBackgroundProcessError(e){return e&&!0===e[Xe.EPSILON_BACKGROUND_PROCESS_ERROR_FLAG_KEY]}set errors(e){this._errors=e||["Internal Server Error"],this.message=Xe.combineErrorStringsWithDefault(this._errors)}get errors(){return this._errors}set detailErrorCode(e){this._detailErrorCode=e}get detailErrorCode(){return this._detailErrorCode}set details(e){this._details=e}get details(){return this._details}set requestId(e){this._requestId=e||"MISSING"}get requestId(){return this._requestId}set wrappedError(e){this._wrappedError=e}get wrappedError(){return this._wrappedError}}class Ze{cfg;s3TransactionLogCacheRatchet;constructor(e){this.cfg=e;const t=Ze.validateConfig(e);t.length&&c.throwFormattedErr("Invalid S3BackgroundTransactionLogger config : %j",t),this.s3TransactionLogCacheRatchet=new A(this.cfg.s3,this.cfg.bucket)}async logTransaction(e){e?e.request?.guid?await this.s3TransactionLogCacheRatchet.writeObjectToCacheFile(Ie.backgroundGuidToPath(this.cfg.prefix,e.request.guid),e):t.warn("Could not write transaction record - no guid defined : %j",e):t.silly("Skipping write of null log")}async readTransactionLog(e){const t=Ie.backgroundGuidToPath(this.cfg.prefix,e);return await this.s3TransactionLogCacheRatchet.fetchCacheFileAsObject(t)}static validateConfig(e){const t=[];return e?(e.s3||t.push("You must supply an S3 object"),e.bucket||t.push("You must supply a bucket"),e.timeToLiveDays||t.push("You must supply a timeToLiveDays")):t.push("No config defined"),t}}class $e extends Ie{_awsConfig;_sqs;_sns;constructor(e,t,r){super(),this._awsConfig=e,this._sqs=t,this._sns=r;const n=ve.validateAwsConfig(e);n.length&&c.throwFormattedErr("Cannot start - invalid AWS config : %j",n)}get backgroundManagerName(){return"AwsSqsSnsBackgroundManager"}get awsConfig(){return this._awsConfig}get sqs(){return this._sqs}get sns(){return this._sns}async addEntryToQueue(e,r){try{const n=await this.wrapEntryForInternal(e),s=n.guid,o={DelaySeconds:0,MessageBody:JSON.stringify(n),MessageGroupId:e.type,QueueUrl:this.awsConfig.queueUrl};t.info("Add entry to queue (remote) : %j : Start : %s",o,r);const a=await this.sqs.send(new H(o));if(r){const e=await this.fireStartProcessingRequest();t.silly("FireResult : %s",e)}return t.info("Background process %s using message id %s",s,a.MessageId),s}catch(e){throw t.error("Error inserting background entry into SQS queue : %j",e),new Error("Error inserting background entry into SQS queue : "+e.code+" : "+e.name)}}async fireImmediateProcessRequest(e){try{const r=await this.wrapEntryForInternal(e),n=r.guid;t.info("Fire immediately (remote) : %j ",e);const s={type:W.BACKGROUND_SNS_IMMEDIATE_RUN_FLAG,backgroundEntry:r},o=JSON.stringify(s),a=await this.writeMessageToSnsTopic(o);return t.debug("Background guid %s Wrote message : %s to SNS : %s",n,o,a),n}catch(e){throw t.error("Failed to fireImmediateProcessRequest : %s",e,e),new Error("Failed to fireImmediateProcessRequest : : "+e.code+" : "+e.name)}}async fireStartProcessingRequest(){let e=null;try{t.info("Fire start processing request (remote)"),e=await this.writeMessageToSnsTopic(W.BACKGROUND_SNS_START_MARKER)}catch(e){t.error("Failed to fireStartProcessingRequest : %s",e,e)}return e}async fetchApproximateNumberOfQueueEntries(){let e=null;const t=await this.fetchCurrentQueueAttributes();return e=l.safeNumber(t.Attributes.ApproximateNumberOfMessages),e}async fetchCurrentQueueAttributes(){let e=null;const t={AttributeNames:["All"],QueueUrl:this.awsConfig.queueUrl};return e=await this.sqs.send(new j(t)),e}async writeMessageToSnsTopic(e){let r=null;const n={Message:e,TopicArn:this.awsConfig.notificationArn};t.debug("Writing message to SNS topic : j",n);return r=(await this.sns.send(new b(n))).MessageId,r}async takeEntryFromBackgroundQueue(){const e=[],r={MaxNumberOfMessages:1,QueueUrl:this.awsConfig.queueUrl,VisibilityTimeout:300,WaitTimeSeconds:0},n=await this.sqs.send(new q(r));if(n&&n.Messages&&n.Messages.length>0)for(let r=0;r<n.Messages.length;r++){const s=n.Messages[r];try{const r=JSON.parse(s.Body);r.type?e.push(r):t.warn("Dropping invalid background entry : %j",r),t.debug("Removing message from queue");const n={QueueUrl:this.awsConfig.queueUrl,ReceiptHandle:s.ReceiptHandle},o=await this.sqs.send(new G(n));t.silly("Delete result : %j",o)}catch(e){t.warn("Error parsing message, dropping : %j",s)}}else t.debug("No messages found (likely end of recursion)");return e}}class et extends $e{_s3;pathPrefix;static LARGE_MESSAGE_SIZE_THRESHOLD=25e4;static LARGE_MESSAGE_S3_PATH_META_KEY="S3_STORAGE_KEY";constructor(t,r,n,s,o=""){super(t,r,n),this._s3=s,this.pathPrefix=o,s||c.throwFormattedErr("Cannot start - no s3Client provided"),e.trimToNull(s.getDefaultBucket())||c.throwFormattedErr("Cannot start - no default bucket provided"),!o&&o.endsWith("/")&&c.throwFormattedErr("Path prefix may not end with /")}get backgroundManagerName(){return"AwsLargePayloadS3SqsSnsBackgroundManager"}get s3(){return this._s3}async wrapEntryForInternal(e,r,n){const s=await super.wrapEntryForInternal(e,r,n);if(Buffer.byteLength(JSON.stringify(s),"utf-8")>et.LARGE_MESSAGE_SIZE_THRESHOLD){t.info("Message payload is above LARGE_MESSAGE_SIZE_THRESHOLD. Uploading to s3."),s.meta=s.meta||{};const e=await this.writeMessageToS3(s.guid,s.data);s.meta[et.LARGE_MESSAGE_S3_PATH_META_KEY]=e,s.data=void 0}return s}async writeMessageToS3(t,r){let n=e.trimToNull(this.pathPrefix)?this.pathPrefix+"/":"";return n+=t+".json",await this.s3.writeObjectToCacheFile(n,r),n}async modify(e){if(e?.meta?.[et.LARGE_MESSAGE_S3_PATH_META_KEY]){t.silly("Restoring large data from %s",e.meta[et.LARGE_MESSAGE_S3_PATH_META_KEY]);const r=await this._s3.fetchCacheFileAsObject(e.meta[et.LARGE_MESSAGE_S3_PATH_META_KEY]);e.data=r,delete e.meta[et.LARGE_MESSAGE_S3_PATH_META_KEY]}return e}}class tt{constructor(){}static buildInformation(){return{version:"414",hash:"311d546526302b7dd26ad47a98c28cad7b7c310c",branch:"alpha-2024-07-05-1",tag:"alpha-2024-07-05-1",timeBuiltISO:"2024-07-05T16:31:46-0700",notes:"No notes"}}}class rt{static fullAwsRequestId(){return $.defaultedCurrentRequestId()}static shortAwsRequestId(){let e=rt.fullAwsRequestId();if(e.length>10){let t=e.lastIndexOf("-");t=-1===t?e.length-10:t,e=e.substring(t)}return e}static fixedLengthHex(t=10){return e.createRandomHexString(t)}}class nt{delegate;opts;static RETRY_FIELD_NAME="___RetryProcessorTryNumber";constructor(e,t){this.delegate=e,this.opts=t}get typeName(){return e.trimToEmpty(this.opts?.typePrefix)+this.delegate.typeName+e.trimToEmpty(this.opts?.typeSuffix)}async handleEvent(e,r){const n=e&&e[nt.RETRY_FIELD_NAME]?l.safeNumber(e[nt.RETRY_FIELD_NAME]):1,s=e?Object.assign({},e):null;delete s[nt.RETRY_FIELD_NAME],t.info("RetryProcessor : %s : Try %d of %d",this.delegate.typeName,n,this.opts.retryCount);try{await this.delegate.handleEvent(s,r)}catch(e){if(t.error("Failed to process : %s",e,e),n<this.opts.retryCount){const e=n*this.opts.baseDelayMS;t.info("Firing automatic retry after a wait of %s",y.formatMsDuration(e)),await h.wait(e);const o=s||{};o[nt.RETRY_FIELD_NAME]=n+1,await r.fireImmediateProcessRequestByParts(this.typeName,o)}else t.error("That was the last try - giving up")}}}class st{daemon;inConfig;static ALLOW_EVERYTHING_AUTHORIZER=async(e,t)=>!0;config;constructor(t,r){this.daemon=t,this.inConfig=r,this.config=r||{},this.config.authorizer=this.config.authorizer||st.ALLOW_EVERYTHING_AUTHORIZER,this.config.groupSelector=this.config.groupSelector||(e=>Promise.resolve(t.defaultGroup)),this.config.fetchDaemonStatusByPublicTokenPathParameter=e.trimToNull(this.config.fetchDaemonStatusByPublicTokenPathParameter)||"publicToken",this.config.fetchDaemonStatusPathParameter=e.trimToNull(this.config.fetchDaemonStatusPathParameter)||"key"}async fetchDaemonStatusByPublicToken(e){const r=e.pathParameters[this.config.fetchDaemonStatusByPublicTokenPathParameter];t.info("Fetching daemon status for token: %s",r);let n=await this.daemon.statFromPublicToken(r);if(n=!!n&&await this.config.authorizer(e,n)?n:null,null===n)throw new me("No such token : "+r);return n}async fetchDaemonStatus(e){const r=e.pathParameters[this.config.fetchDaemonStatusPathParameter];t.info("Fetching daemon status for : %s",r);let n=await this.daemon.stat(r);if(n=!!n&&await this.config.authorizer(e,n)?n:null,null===n)throw new me("No such key : "+r);return n}async listDaemonStatus(e){const t=await this.config.groupSelector(e),r=await this.daemon.list(t),n=[];for(let t=0;t<r.length;t++){await this.config.authorizer(e,r[t])&&n.push(r[t])}return{results:n,nextToken:null}}}class ot{static async runFromCliArgs(e){if(e.length>1){const r=e[0],n=e.length>1&&E.parseBool(e[1]),s=e.length>2?JSON.parse(e[2]):null,o=e.length>3?JSON.parse(e[3]):null,a=null;n?t.info("Dry-Run, would have sent : %s %j %j",r,s,o):await a.processSingleBackgroundByParts(r,s,o)}else console.log("Usage : run-background-process {processName} {dryRun true/false} {dataJson} {metaJson}")}}class at{port;server;aborted=!1;constructor(e=9999){this.port=e}async runServer(){return t.info("Starting Test Error net server on port %d",this.port),new Promise(((e,r)=>{const n=new U.Server({});n.listen(this.port,(()=>{t.info("Server listening for connection requests on socket localhost: %s",this.port)})),n.on("connection",(async e=>{t.info("X: A new connection has been established."),e.write("Hello, client."),e.on("data",(e=>{t.info("Data received from client: %s",e)})),e.on("end",(()=>{t.info("Closing connection with the client")})),e.on("error",(e=>{t.info("Error: %s",e)}))}))}))}async requestHandler(e,r){t.info("Got request %d - closing socket",e),e.setTimeout(100),r.end("x")}static async runFromCliArgs(e){t.info("test-error-server requested (cli is %s) - starting",process?.argv);const r=new at;await r.runServer(),t.info("Got res server"),process.exit(0)}}class it extends x{fetchHandlerMap(){return{"run-background-process":ot.runFromCliArgs,"run-test-error-server":at.runFromCliArgs,"run-local-container-server":Ke.runFromCliArgs,"run-sample-local-server":Ye.runSampleLocalServerFromCliArgs,"run-sample-local-batch-server":Ye.runSampleLocalServerFromCliArgs}}fetchVersionInfo(){return tt.buildInformation()}}class ct{webTokenManipulator;constructor(e,t){this.webTokenManipulator=new Se([t],e)}lambdaHandler(e,r,n){t.info("Got event : %j",e);const s=ct.extractTokenStringFromAuthorizerEvent(e);if(s){const r=e.methodArn;this.webTokenManipulator.parseAndValidateJWTStringAsync(s).then((e=>{e?n(null,this.createPolicy(r,s,e)):(t.info("Invalid bearer token"),n(new Error("Unauthorized")))})).catch((e=>{t.error("Exception parsing token : %s",e),n(new Error("Unauthorized"))}))}else t.info("Token not supplied"),n(new Error("Unauthorized"))}createPolicy(e,t,r){const n=e.split(":"),s=n[5].split("/"),o=n[4],a=n[3],i=s[1];return{principalId:"user",policyDocument:{Version:"2012-10-17",Statement:[{Action:"execute-api:Invoke",Effect:"Allow",Resource:["arn:aws:execute-api:"+a+":"+o+":"+s[0]+"/"+i+"/*/*"]}]},context:{userJSON:JSON.stringify(r),srcData:t}}}static extractTokenStringFromAuthorizerEvent(e){t.silly("Extracting token from event : %j",e);let r=null;if(e&&e.authorizationToken){const t=e.authorizationToken;t&&t.startsWith(W.AUTH_HEADER_PREFIX)&&(r=t.substring(W.AUTH_HEADER_PREFIX.length))}return r}}class lt{clientId;jwksUri;issuer;jwksClient;constructor(e,t,r){this.clientId=e,this.jwksUri=t,this.issuer=r}async extractTokenFromAuthorizationHeader(t){let r=e.trimToEmpty(t);r.toLowerCase().startsWith("bearer ")&&(r=r.substring(7));return r?await this.parseAndValidateAuth0Token(r,!1):null}async parseAndValidateAuth0Token(r,n=!1){t.debug("Validating Auth0 token : %s",e.obscure(r,4));const s=w.decode(r,{complete:!0}),o=s?.header?.kid,a=Math.floor((new Date).getTime()/1e3),i=await this.fetchSigningKey(o);return w.verify(r,i,{audience:this.clientId,issuer:this.issuer,ignoreExpiration:n,clockTimestamp:a})}async fetchSigningKey(e){const t=await this.fetchJwksClient();return new Promise(((r,n)=>{t.getSigningKey(e,((e,t)=>{e?n(e):r(t.publicKey||t.rsaPublicKey)}))}))}async fetchJwksClient(){return this.jwksClient||(this.jwksClient=V({cache:!0,cacheMaxEntries:5,cacheMaxAge:36e6,jwksUri:this.jwksUri})),this.jwksClient}}class ut{clientId;static GOOGLE_DISCOVERY_DOCUMENT="https://accounts.google.com/.well-known/openid-configuration";cacheGoogleDiscoveryDocument;jwksClient;constructor(e){this.clientId=e}async extractTokenFromAuthorizationHeader(t){let r=e.trimToEmpty(t);r.toLowerCase().startsWith("bearer ")&&(r=r.substring(7));return r?await this.parseAndValidateGoogleToken(r,!1):null}async parseAndValidateGoogleToken(r,n=!1){t.debug("Auth : %s",e.obscure(r,4));const s=w.decode(r,{complete:!0}).header.kid,o=Math.floor((new Date).getTime()/1e3),a=await this.fetchSigningKey(s);return w.verify(r,a,{audience:this.clientId,issuer:["https://accounts.google.com","accounts.google.com"],ignoreExpiration:n,clockTimestamp:o})}async fetchSigningKey(e){const t=await this.fetchJwksClient();return new Promise(((r,n)=>{t.getSigningKey(e,((e,t)=>{e?n(e):r(t.publicKey||t.rsaPublicKey)}))}))}async fetchJwksClient(){if(!this.jwksClient){const e=await this.fetchGoogleDiscoveryDocument(),t=V({cache:!0,cacheMaxEntries:5,cacheMaxAge:36e6,jwksUri:e.jwks_uri});this.jwksClient=t}return this.jwksClient}async fetchGoogleDiscoveryDocument(){if(!this.cacheGoogleDiscoveryDocument){const e=await N(ut.GOOGLE_DISCOVERY_DOCUMENT),t=await e.json();this.cacheGoogleDiscoveryDocument=t}return this.cacheGoogleDiscoveryDocument}}class dt{_jwtRatchet;_issuer;constructor(t,r){this._jwtRatchet=t,this._issuer=r,u.notNullOrUndefined(t,"_jwtRatchet"),u.notNullOrUndefined(e.trimToNull(r),"_issuer")}get jwtRatchet(){return this._jwtRatchet}get issuer(){return this._issuer}async extractTokenFromAuthorizationHeader(t){let r=e.trimToEmpty(t);r.toLowerCase().startsWith("bearer ")&&(r=r.substring(7));return r?await this.jwtRatchet.decodeToken(r,1):null}}class pt extends n{static HTTP_CODE=502;constructor(...e){super(...e),Object.setPrototypeOf(this,pt.prototype),this.withHttpStatusCode(pt.HTTP_CODE)}}class ht extends n{static HTTP_CODE=409;constructor(...e){super(...e),Object.setPrototypeOf(this,ht.prototype),this.withHttpStatusCode(ht.HTTP_CODE)}}class gt extends n{static HTTP_CODE=504;constructor(...e){super(...e),Object.setPrototypeOf(this,gt.prototype),this.withHttpStatusCode(gt.HTTP_CODE)}}class mt extends n{static HTTP_CODE=405;constructor(...e){super(...e),Object.setPrototypeOf(this,mt.prototype),this.withHttpStatusCode(mt.HTTP_CODE)}}class ft extends n{static HTTP_CODE=503;constructor(...e){super(...e),Object.setPrototypeOf(this,ft.prototype),this.withHttpStatusCode(ft.HTTP_CODE)}}class Et extends n{static HTTP_CODE=429;constructor(...e){super(...e),Object.setPrototypeOf(this,Et.prototype),this.withHttpStatusCode(Et.HTTP_CODE)}}class yt{options;constructor(e){this.options=e}modifyOpenApiDoc(e){let r;if(e&&this.options)try{const t=L.load(e),n=this.options.removeTags?this.options.removeTags.map((e=>e.toLowerCase())):[];if(this.options.newServerPath&&(t.servers=[{url:this.options.newServerPath}]),this.options.removeTags&&t.tags&&t.tags&&(t.tags=t.tags.filter((e=>{const t=e&&e.name?e.name.toLowerCase():"";return-1===n.indexOf(t)}))),t.paths){let e={};if(Object.keys(t.paths).forEach((r=>{const s=t.paths[r];Object.keys(s).forEach((t=>{const o=s[t];o.tags=o.tags?o.tags.filter((e=>-1==n.lastIndexOf(e.toLowerCase()))):o.tags;const a=t.toLowerCase()+" "+r.toLowerCase();this.matchNone(a,this.options.removeEndpoints)&&(e[r]=e[r]||{},e[r][t]=o)}))})),this.options.sortEndpoints){const t=Object.keys(e).sort(),r={};t.forEach((t=>{r[t]=e[t]})),e=r}t.paths=e}let s=this.options.removeSchemas||[];if(s=s.map((e=>e.toLowerCase())),t.components&&t.components.schemas){const e=Object.keys(t.components.schemas).sort(),r={};e.forEach((e=>{-1===s.indexOf(e.toLowerCase())&&(r[e]=t.components.schemas[e])})),t.components.schemas=r}r=L.dump(t)}catch(e){t.error("Error processing yaml: %s",e,e)}return r}matchNone(e,t){let r=!0;return e&&t&&t.forEach((t=>{r=r&&!t.test(e)})),r}}class wt{static combine(e,r=[]){u.notNullOrUndefined(e,"Files argument"),u.true(e.length>0,"Files argument larger than 0"),u.notNullOrUndefined(r,"Root path argument"),t.info("Processing %d files into output",e.length);let n={};for(let t=0;t<e.length;t++){const r=Q.readFileSync(e[t]).toString(),s=L.load(r);n=Object.assign(n,s)}const s=Object.assign([],r);for(;s.length>0;){const e={};e[s[s.length-1]]=n,s.splice(s.length-1,1),n=e}return L.dump(n)}}export{Ie as AbstractBackgroundManager,ct as ApiGatewayAdapterAuthenticationHandler,Ue as ApolloFilter,qe as ApolloUtil,lt as Auth0WebTokenManipulator,et as AwsLargePayloadS3SqsSnsBackgroundManager,$e as AwsSqsSnsBackgroundManager,ee as AwsUtil,Je as BackgroundDynamoLogTableHandler,Pe as BackgroundExecutionEventType,Oe as BackgroundHandler,Ne as BackgroundHttpAdapterHandler,Ce as BackgroundProcessHandling,ve as BackgroundValidator,pt as BadGateway,K as BadRequestError,Me as BuiltInAuthFilters,je as BuiltInAuthorizers,Le as BuiltInFilters,we as BuiltInHandlers,rt as BuiltInTraceIdGenerators,ht as ConflictError,$ as ContextUtil,ie as CronEpsilonLambdaEventHandler,ae as CronUtil,st as DaemonHandler,le as DynamoEpsilonLambdaEventHandler,Te as EchoProcessor,Ge as EpsilonApolloCorsMethod,Xe as EpsilonBackgroundProcessError,z as EpsilonBuildProperties,De as EpsilonConfigParser,W as EpsilonConstants,pe as EpsilonGlobalHandler,ue as EpsilonLoggingExtensionProcessor,J as EventUtil,fe as ForbiddenError,gt as GatewayTimeout,oe as GenericSnsEpsilonLambdaEventHandler,de as GenericSqsEpsilonLambdaEventHandler,ut as GoogleWebTokenManipulator,ne as InterApiEpsilonLambdaEventHandler,he as InterApiManager,re as InterApiUtil,dt as JwtRatchetLocalWebTokenManipulator,Ke as LocalContainerServer,Ye as LocalServer,ge as LocalServerCert,Se as LocalWebTokenManipulator,be as LogAndEnqueueEchoProcessor,ke as LogLevelManipulationFilter,Ve as LogMessageBackgroundErrorProcessor,mt as MethodNotAllowedError,ye as MisconfiguredError,se as NoHandlersFoundError,Ae as NoOpProcessor,me as NotFoundError,Ee as NotImplemented,_e as NullReturnedObjectHandling,yt as OpenApiDocModifier,it as RatchetCliHandler,tt as RatchetEpsilonCommonInfo,Z as RequestTimeoutError,X as ResponseUtil,nt as RetryProcessor,Fe as RouterUtil,ot as RunBackgroundProcessFromCommandLine,Be as RunHandlerAsFilter,Ze as S3BackgroundTransactionLogger,ce as S3EpsilonLambdaEventHandler,Re as SampleDelayProcessor,He as SampleInputValidatedProcessor,We as SampleServerComponents,ze as SampleServerStaticFiles,ft as ServiceUnavailable,Qe as SingleThreadLocalBackgroundManager,at as TestErrorServer,Et as TooManyRequestsError,Y as UnauthorizedError,xe as WebHandler,te as WebV2Handler,wt as YamlCombiner};
|
|
1
|
+
import{StringRatchet as e,Logger as t,EsmRatchet as r,RestfulApiHttpError as n,MapRatchet as s,Base64Ratchet as o,EnumRatchet as a,LoggerLevelName as i,ErrorRatchet as c,NumberRatchet as l,RequireRatchet as u,LogMessageFormatType as d,LoggerOutputFunction as p,PromiseRatchet as h,TimeoutToken as g,JwtRatchet as m,StopWatch as f,BooleanRatchet as E,DurationRatchet as y}from"@bitblit/ratchet-common";import w from"jsonwebtoken";import S from"zlib";import{LambdaEventDetector as T,S3CacheRatchet as A}from"@bitblit/ratchet-aws";import{DateTime as R}from"luxon";import{PublishCommand as b}from"@aws-sdk/client-sns";import C from"http";import N from"cross-fetch";import v from"https";import{HeaderMap as P,ApolloServer as I}from"@apollo/server";import{gql as O}from"graphql-tag";import{ApolloServerPluginLandingPageLocalDefault as _}from"@apollo/server/plugin/landingPage/default";import L from"js-yaml";import{ModelValidator as M}from"@bitblit/ratchet-misc";import k from"route-parser";import{Subject as F}from"rxjs";import{CliRatchet as B,AbstractRatchetCliHandler as x}from"@bitblit/ratchet-node-only";import D from"util";import{SendMessageCommand as H,GetQueueAttributesCommand as j,ReceiveMessageCommand as q,DeleteMessageCommand as G}from"@aws-sdk/client-sqs";import U from"net";import V from"jwks-rsa";import Q from"fs";class z{constructor(){}static get buildVersion(){return"415"}static get buildHash(){return"43b8898fca427e6952399e7dfd5c58cf8e8177c0"}static get buildBranch(){return"alpha-2024-07-12-1"}static get buildTag(){return"alpha-2024-07-12-1"}static get buildBranchOrTag(){return e.trimToNull(z.buildBranch)?"BRANCH:"+z.buildBranch:"TAG:"+z.buildTag}static get buildTime(){return"LOCAL-TIME"}}class W{static EPSILON_FINDER_DYNAMIC_IMPORT_PATH_ENV_NAME="EPSILON_FINDER_DYNAMIC_IMPORT_PATH";static EPSILON_FINDER_FUNCTION_NAME_ENV_NAME="EPSILON_FINDER_FUNCTION_NAME";static DEFAULT_EPSILON_FINDER_DYNAMIC_IMPORT_PATH="epsilon-global-handler-provider.js";static DEFAULT_EPSILON_FINDER_FUNCTION_NAME="findEpsilonGlobalHandler";static AUTH_HEADER_PREFIX="Bearer ";static AUTH_HEADER_NAME="Authorization";static BACKGROUND_SQS_TYPE_FIELD="BACKGROUND_TYPE";static BACKGROUND_SNS_START_MARKER="BACKGROUND_START_MARKER";static BACKGROUND_SNS_IMMEDIATE_RUN_FLAG="BACKGROUND_IMMEDIATE_RUN_FLAG";static INTER_API_SNS_EVENT="EPSILON_INTER_API_EVENT";static load(e,n){t.info("Searching for %s : %s : %s",e,n,r.fetchDirName(import.meta.url));let s=null;const o=require(e);return o&&(t.debug("Found %s - pulling object : %j : %s",e,Object.keys(o),n),s=o[n]),s}static async findDynamicImportEpsilonGlobalHandlerProvider(){const e=process.env[W.EPSILON_FINDER_DYNAMIC_IMPORT_PATH_ENV_NAME]||W.DEFAULT_EPSILON_FINDER_DYNAMIC_IMPORT_PATH,r=process.env[W.EPSILON_FINDER_FUNCTION_NAME_ENV_NAME]||W.DEFAULT_EPSILON_FINDER_FUNCTION_NAME;t.debug("Using epsilon finder dynamic import path : %s / %s",e,r);let n=null;try{n=this.load(e,r)}catch(n){t.error("Error loading provider : %s / %s : %s",e,r,n,n)}let s=null;return n&&(t.debug("Type2 is : %s",typeof n),t.info("Got3 : %s : %s",n,typeof n),s=n(),t.info("Rval3 is %s",s)),s}constructor(){}}class Y extends n{static HTTP_CODE=401;constructor(...e){super(...e),Object.setPrototypeOf(this,Y.prototype),this.withHttpStatusCode(Y.HTTP_CODE)}}class K extends n{static HTTP_CODE=400;constructor(...e){super(...e),Object.setPrototypeOf(this,K.prototype),this.withHttpStatusCode(K.HTTP_CODE)}}class J{constructor(){}static extractStage(e){if(!e.path.startsWith("/"))throw new K("Path should start with / but does not : "+e.path);const t=e.path.indexOf("/",1);if(-1==t)throw new K("No second / found in the path : "+e.path);return e.path.substring(1,t)}static extractHostHeader(e){return s.extractValueFromMapIgnoreCase(e.headers,"Host")}static extractProtocol(e){return s.extractValueFromMapIgnoreCase(e.headers,"X-Forwarded-Proto")}static extractApiGatewayStage(e){const t=J.extractRequestContext(e);return t?t.stage:null}static extractRequestContext(e){return e.requestContext}static extractAuthorizer(e){const t=J.extractRequestContext(e);return t?t.authorizer:null}static ipAddressChain(e){const t=e&&e.headers?s.extractValueFromMapIgnoreCase(e.headers,"X-Forwarded-For"):null;let r=t?String(t).split(","):[];return r=r.map((e=>e.trim())),r}static ipAddress(e){const t=J.ipAddressChain(e);return t&&t.length>0?t[0]:null}static extractFullPath(e,t=null){return(t||J.extractProtocol(e)||"https")+"://"+e.requestContext.domainName+e.requestContext.path}static extractFullPrefix(e,t=null){const r=t||J.extractProtocol(e)||"https",n=e.requestContext.path.substring(0,e.requestContext.path.indexOf("/",1));return r+"://"+e.requestContext.domainName+n}static jsonBodyToObject(e){let t=null;if(e.body){const r=s.extractValueFromMapIgnoreCase(e.headers,"Content-Type")||"application/octet-stream";t=e.body,e.isBase64Encoded&&(t=o.base64StringToString(t)),r.startsWith("application/json")&&(t=JSON.parse(t.toString("ascii")))}return t}static calcLogLevelViaEventOrEnvParam(e,r,n){let s=e;return n?.envParamLogLevelName&&process.env[n.envParamLogLevelName]&&(s=a.keyToEnum(i,process.env[n.envParamLogLevelName]),t.silly("Found env log level : %s",s)),n&&n.queryParamLogLevelName&&r&&r.queryStringParameters&&r.queryStringParameters[n.queryParamLogLevelName]&&(s=a.keyToEnum(i,r.queryStringParameters[n.queryParamLogLevelName]),t.silly("Found query log level : %s",s)),s}static fixStillEncodedQueryParams(e){if(e?.queryStringParameters){const t={};Object.keys(e.queryStringParameters).forEach((r=>{const n=e.queryStringParameters[r];r.toLowerCase().startsWith("amp;")?t[r.substring(4)]=n:t[r]=n})),e.queryStringParameters=t}if(e?.multiValueQueryStringParameters){const t={};Object.keys(e.multiValueQueryStringParameters).forEach((r=>{const n=e.multiValueQueryStringParameters[r];r.toLowerCase().startsWith("amp;")?t[r.substring(4)]=n:t[r]=n})),e.multiValueQueryStringParameters=t}}static applyTokenToEventForTesting(e,t){const r=w.decode(t,{complete:!0});if(!r.payload)throw new Error("No payload found in passed token");const n=r.payload;e.headers=e.headers||{},e.headers[W.AUTH_HEADER_NAME.toLowerCase()]="Bearer "+t,e.requestContext=e.requestContext||{};const s=Object.assign({},e.requestContext.authorizer);s.userData=n,s.userDataJSON=n?JSON.stringify(n):null,s.srcData=t,e.requestContext.authorizer=s}static extractBasicAuthenticationToken(e,r=!1){let n=null;if(e&&e.headers){const r=J.extractAuthorizationHeaderCaseInsensitive(e);if(r&&r.startsWith("Basic ")){const e=o.base64StringToString(r.substring(6)).split(":");t.silly("Parsed to %j",e),e&&2===e.length&&(n={username:e[0],password:e[1]})}}if(!n&&r)throw new Y("Could not find valid basic authentication header");return n}static eventIsAGraphQLIntrospection(e){let r=!1;if(e&&e.httpMethod&&"post"===e.httpMethod.toLowerCase()&&e.path&&e.path.endsWith("/graphql"))try{const t=J.jsonBodyToObject(e);r=!!t&&!!t.operationName&&"IntrospectionQuery"===t.operationName}catch(n){t.error("Failed to parse body - treating as non-graphql : %s : %s",e?.body,n,n),r=!1}return r}static extractAuthorizationHeaderCaseInsensitive(e){return s.caseInsensitiveAccess(e?.headers||{},W.AUTH_HEADER_NAME)}static extractBearerTokenFromEvent(t){let r=null;const n=e.trimToEmpty(J.extractAuthorizationHeaderCaseInsensitive(t));return n.toLowerCase().startsWith("bearer ")&&(r=n.substring(7)),r}static hostIsLocal(t){let r=!1;return e.trimToNull(t)&&("localhost"!==(t=(t=t.includes(":")?t.substring(0,t.indexOf(":")):t).toLowerCase())&&"127.0.0.1"!==t||(r=!0)),r}static hostIsLocalOrNotRoutableIP4(t){let r=!1;return e.trimToNull(t)&&("localhost"===(t=(t=t.includes(":")?t.substring(0,t.indexOf(":")):t).toLowerCase())||"127.0.0.1"===t||t.startsWith("192.168.")||t.startsWith("10.")||t.startsWith("172.16."))&&(r=!0),r}}class X{constructor(){}static errorResponse(e){const t={errors:e.errors,httpStatusCode:e.httpStatusCode,requestId:e.requestId};e.detailErrorCode&&(t.detailErrorCode=e.detailErrorCode),e.endUserErrors&&e.endUserErrors.length>0&&(t.endUserErrors=e.endUserErrors),e.details&&(t.details=e.details),e.wrappedError&&(t.wrappedError=e.wrappedError.name+" : "+e.wrappedError.message);return{statusCode:e.httpStatusCode,isBase64Encoded:!1,headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}}static redirect(e,r=301,n=null){if(301!==r&&302!==r&&307!==r)throw new Error("Code must be 301 or 302 or 307 for a redirect");let s=e;if(n){const e=Object.keys(n);if(e.length>0){t.silly("Applying params to input target : %j",n),s+=-1===s.indexOf("?")?"?":"&";for(let t=0;t<e.length;t++){const r=e[t];s+=r+"="+encodeURIComponent(n[r]),t<e.length-1&&(s+="&")}}}return{statusCode:r,body:'{"redirect-target":"'+s+"}",headers:{"Content-Type":"application/json",Location:s}}}static coerceToProxyResult(e){let t=null;if(null!=e)if("object"==typeof e)if(e.statusCode&&void 0!==e.body)t=Object.assign({},e),"string"==typeof e.body||Buffer.isBuffer(e.body)&&(t.body=e.body.toString("base64"),t.headers=e.headers||{},t.headers["Content-Type"]=e.body.contentType,t.isBase64Encoded=!0);else{const r=e.headers||{};r["Content-Type"]="application/json",t=X.coerceToProxyResult({statusCode:200,body:JSON.stringify(e),headers:r,isBase64Encoded:!1})}else if("string"==typeof e||Buffer.isBuffer(e))t=X.coerceToProxyResult({statusCode:200,body:e});else{const r=e.headers||{};r["Content-Type"]="application/json",t=X.coerceToProxyResult({statusCode:200,body:JSON.stringify(e),headers:r,isBase64Encoded:!1})}return t}static async applyGzipIfPossible(e,r){const n=r;if(e&&e.toLowerCase().indexOf("gzip")>-1){const e=r.body.length>1400;let o=s.extractValueFromMapIgnoreCase(r.headers,"content-type")||"";o=o.toLowerCase();const a="application/pdf"===o||"application/zip"===o||o.startsWith("image/");if(e&&!a){const e=r.isBase64Encoded?Buffer.from(r.body,"base64"):Buffer.from(r.body),s=await this.gzip(e);t.debug("Comp from %s to %d bytes",e.length,s.length);const o=s.toString("base64");n.body=o,n.isBase64Encoded=!0,n.headers=n.headers||{},n.headers["Content-Encoding"]="gzip"}else t.silly("Not gzipping, too small or exempt content")}else t.silly("Not gzipping, not an accepted encoding");return n}static gzip(e){return new Promise((function(t,r){S.gzip(e,(function(e,n){e?r(e):t(n)}))}))}}class Z extends n{static HTTP_CODE=500;constructor(...e){super(...e),Object.setPrototypeOf(this,Z.prototype),this.withHttpStatusCode(Z.HTTP_CODE)}}class ${static CURRENT_EPSILON_REFERENCE;static CURRENT_CONTEXT;static CURRENT_EVENT;static CURRENT_LOG_VARS={};static CURRENT_PROCESS_LABEL;static CURRENT_OVERRIDE_TRACE_ID;static CURRENT_OVERRIDE_TRACE_DEPTH;constructor(){}static initContext(e,t,r,n){$.CURRENT_EPSILON_REFERENCE=e,$.CURRENT_CONTEXT=r,$.CURRENT_EVENT=t,$.CURRENT_LOG_VARS={},$.CURRENT_PROCESS_LABEL=n}static clearContext(){$.CURRENT_EPSILON_REFERENCE=null,$.CURRENT_CONTEXT=null,$.CURRENT_EVENT=null,$.CURRENT_LOG_VARS={},$.CURRENT_PROCESS_LABEL=null,$.CURRENT_OVERRIDE_TRACE_ID=null,$.CURRENT_OVERRIDE_TRACE_DEPTH=null}static setOverrideTrace(e,t){$.CURRENT_OVERRIDE_TRACE_ID=e||$.CURRENT_OVERRIDE_TRACE_ID,$.CURRENT_OVERRIDE_TRACE_DEPTH=t||$.CURRENT_OVERRIDE_TRACE_DEPTH}static setOverrideTraceFromInternalBackgroundEntry(e){$.setOverrideTrace(e.traceId,e.traceDepth)}static setOverrideTraceFromInterApiEntry(e){$.setOverrideTrace(e.traceId,e.traceDepth)}static addHeadersToRecord(t,r=0){t?(t[$.traceHeaderName()]=$.currentTraceId(),t[$.traceDepthHeaderName()]=e.safeString($.currentTraceDepth()+r)):c.throwFormattedErr("Cannot add headers to null/undefined input")}static addTraceToProxyResult(e){e.headers=e.headers||{},$.addHeadersToRecord(e.headers)}static addTraceToHttpRequestInit(e){e.headers=e.headers||{},$.addHeadersToRecord(e.headers,1)}static setProcessLabel(e){$.CURRENT_PROCESS_LABEL=e}static currentRequestId(){const e=$.CURRENT_CONTEXT;return e?e.awsRequestId:null}static defaultedCurrentRequestId(t=e.createType4Guid()){return $.currentRequestId()??t}static remainingTimeMS(){const e=$.CURRENT_CONTEXT;return e?e.getRemainingTimeInMillis():null}static currentProcessLabel(){return $.CURRENT_PROCESS_LABEL||"unset"}static traceHeaderName(){return $?.CURRENT_EPSILON_REFERENCE?.config?.loggerConfig?.traceHeaderName||"X-TRACE-ID"}static traceDepthHeaderName(){return $?.CURRENT_EPSILON_REFERENCE?.config?.loggerConfig?.traceDepthHeaderName||"X-TRACE-DEPTH"}static currentTraceId(){const e=$?.CURRENT_EPSILON_REFERENCE?.config?.loggerConfig?.traceIdGenerator||$.defaultedCurrentRequestId;return $.CURRENT_OVERRIDE_TRACE_ID||$.CURRENT_EVENT?.headers?.[$.traceHeaderName()]||e($.CURRENT_EVENT,$.CURRENT_CONTEXT)}static currentTraceDepth(){return $.CURRENT_OVERRIDE_TRACE_DEPTH||l.safeNumber($.CURRENT_EVENT?.headers?.[$.traceDepthHeaderName()])||1}static addLogVariable(e,t){$.CURRENT_LOG_VARS[e]=t}static fetchLogVariable(e){return $.CURRENT_LOG_VARS?.[e]}static fetchLogVariables(){return Object.assign({},$.CURRENT_LOG_VARS||{})}}class ee{static apiGatewayV2ToApiGatewayV1(e){return{requestContext:ee.apiGatewayV2RequestContextToApiGatewayV1RequestContext(e.requestContext),httpMethod:e.requestContext.http.method,path:e.requestContext.http.path,queryStringParameters:e.queryStringParameters,headers:e.headers,body:e.body,isBase64Encoded:e.isBase64Encoded,multiValueHeaders:null,multiValueQueryStringParameters:null,pathParameters:e.pathParameters,stageVariables:e.stageVariables,resource:null}}static apiGatewayV2RequestContextToApiGatewayV1RequestContext(e){return{accountId:e.accountId,apiId:e.apiId,authorizer:null,domainName:e.domainName,domainPrefix:e.domainPrefix,requestId:e.requestId,routeKey:e.routeKey,stage:e.stage,requestTime:e.time,requestTimeEpoch:e.timeEpoch,protocol:e.http.protocol,httpMethod:e.http.method,identity:null,path:e.http.path,resourceId:null,resourcePath:null}}static findInMap(e,t){let r=null;return t.forEach(((t,n)=>{ee.matchExact(n,e)&&(r=t)})),r}static matchExact(e,t){const r=t.match(e);return null!=r&&t==r[0]}static resolvePotentialFunctionToResult(e,t){let r=t;return e&&(r="function"==typeof e?e():e),r}}class te{webHandler;constructor(e){this.webHandler=e}extractLabel(e,t){let r=this.webHandler.extractLabel(ee.apiGatewayV2ToApiGatewayV1(e),t);return r=r.replace("WEB:","WEB2:"),r}handlesEvent(e){return T.isValidApiGatewayV2WithRequestContextEvent(e)}async processEvent(e,t){const r=ee.apiGatewayV2ToApiGatewayV1(e),n=Object.assign({},{parsedBody:null,authorization:null,convertedFromV2Event:!0},r);return await this.webHandler.openApiLambdaHandler(n,t)}}class re{static isInterApiSnsEvent(e){return!!re.extractEntryFromEvent(e)}static extractEntryFromEvent(t){let r=null;if(t&&T.isSingleSnsEvent(t)){const n=t.Records[0].Sns.Message;if(e.trimToNull(n)){const e=JSON.parse(n);e&&e.type===W.INTER_API_SNS_EVENT&&(r=e.interApiEvent)}}return r}static async processInterApiEvent(e,r,n){let s=[];u.notNullOrUndefined(e,"InterApiEntry"),u.notNullOrUndefined(n,"BackgroundManager");const o=re.extractEntryFromEvent(e);$.setOverrideTraceFromInterApiEntry(o),t.info("Processing inter-api event : %j",e);const a=[];return r.processMappings.forEach((e=>{!e.disabled&&o.source.match(e.sourceRegex)&&o.type.match(e.typeRegex)&&e.backgroundProcessTypes.forEach((e=>{const t=n.createEntry(e,o.data);a.push(t)}))})),a.length>0?(t.info("Adding %d entries to queue",a.length),s=await n.addEntriesToQueue(a,!0)):t.info("No entries mapped for this event"),s}static addTraceToInterApiEntry(e){return e&&(e.traceId=e.traceId||$.currentTraceId(),e.traceDepth=e.traceDepth||$.currentTraceDepth()+1),e}}class ne{_epsilon;constructor(e){this._epsilon=e}extractLabel(e,t){const r=re.extractEntryFromEvent(e);return"InterApi:"+r.source+":"+r.type}handlesEvent(e){return this._epsilon.config.interApiConfig&&re.isInterApiSnsEvent(e)}async processEvent(e,t){const r=await re.processInterApiEvent(e,this._epsilon.config.interApiConfig,this._epsilon.backgroundManager);return{statusCode:200,body:JSON.stringify(r),isBase64Encoded:!1}}}class se extends Error{constructor(e){super(e??"No handlers found"),Object.setPrototypeOf(this,se.prototype)}}class oe{_epsilon;constructor(e){this._epsilon=e}extractLabel(e,t){return"SNSEvt:"+e.Records[0].EventSource}handlesEvent(e){return T.isValidSnsEvent(e)}async processEvent(e,r){let n=null;if(this._epsilon.config&&this._epsilon.config.sns&&e&&e.Records.length>0){const r=e.Records[0].Sns.TopicArn,s=ee.findInMap(r,this._epsilon.config.sns.handlers);if(!s)throw t.info("Found no SNS handler for : %s",r),new se;n=await s(e)}return n}}class ae{static everyNMinuteFilter(e){return ae.everyNElementFilter(e,60)}static everyNDaysOfYearFilter(e){return ae.everyNElementFilter(e,365)}static everyNElementFilter(e,t){u.notNullOrUndefined(e),u.notNullOrUndefined(t);const r=Math.floor(t/2);if(!e||e<2||e>r||t%e!=0)throw c.throwFormattedErr("Invalid config - this function only makes sense for 2 < N < %d and %d evenly divisible by N",r,t),new Error("Invalid config - this function only makes sense for 2 < N < 31 and 60 evenly divisible by N");const n=[];for(let t=0;t<60;t+=e)n.push(t);return n}static numberMatchesFilter(e,t){return!t||0===t.length||t.includes(e)}static eventMatchesEntry(t,r,n,s=(new Date).getTime()){let o=!1;if(t&&r&&n.timezone&&t.resources&&t.resources.length>0){const a=t.resources[0],i=e.trimToNull(r.overrideTimezone)||n.timezone,c=R.fromMillis(s).setZone(i);o=!r.eventFilter||r.eventFilter.test(a),o=o&&ae.numberMatchesFilter(c.minute,r.minuteFilter),o=o&&ae.numberMatchesFilter(c.hour,r.hourFilter),o=o&&ae.numberMatchesFilter(c.weekday,r.dayOfWeekFilter),o=o&&ae.numberMatchesFilter(c.day,r.dayOfMonthFilter),o=o&&ae.numberMatchesFilter(c.month,r.monthOfYearFilter),o=o&&(!r.contextMatchFilter||r.contextMatchFilter.test(e.trimToEmpty(n.context))),o=o&&(!r.contextNoMatchFilter||!r.contextNoMatchFilter.test(e.trimToEmpty(n.context)))}return o}static cronEntryName(e,t=null){u.notNullOrUndefined(e);let r=null;return e?(r=e.name,r=r||e.backgroundTaskType,!r&&e.directHandler&&(r=t?"Direct Entry "+t:"Direct Entry (No idx specified)")):r="ERROR: no entry passed",r}}class ie{_epsilon;constructor(e){this._epsilon=e}extractLabel(e,t){return"CronEvt:"+e.source}handlesEvent(e){return T.isValidCronEvent(e)}async processEvent(e,r){let n=null;return t.debug("Epsilon: CRON: %j",e),this._epsilon.config.cron?(await ie.processCronEvent(e,this._epsilon.config.cron,this._epsilon.backgroundManager,this._epsilon.backgroundHandler),n={statusCode:200,body:JSON.stringify({message:"CRON complete"}),isBase64Encoded:!1}):(t.debug("Skipping - CRON disabled"),n={statusCode:200,body:JSON.stringify({message:"CRON skipped - disabled"}),isBase64Encoded:!1}),n}static async processCronEvent(e,r,n,s){let o=!1;if(r&&e&&e.resources[0]&&r.entries)if(s){const s=[];for(let a=0;a<r.entries.length;a++){const i=r.entries[a];if(ae.eventMatchesEntry(e,i,r)){t.info("CRON Firing : %s",ae.cronEntryName(i));const e={type:i.backgroundTaskType,data:ee.resolvePotentialFunctionToResult(i.data,{})};t.silly("Resolved entry : %j",e),i.fireImmediate?(await n.fireImmediateProcessRequest(e),o=!0):s.push(e)}}s.length>0&&(await n.addEntriesToQueue(s,!0),o=!0)}else t.warn("Cron defines background tasks, but no background manager provided");return o}}class ce{_epsilon;constructor(e){this._epsilon=e}extractLabel(e,t){return"S3Evt:"+e.Records[0].eventSource}handlesEvent(e){return T.isValidS3Event(e)}async processEvent(e,r){let n=null;if(this._epsilon.config&&this._epsilon.config.s3&&e&&e.Records.length>0){const r=e.Records[0].s3.bucket.name+"/"+e.Records[0].s3.object.key;if(e.Records[0].eventName&&e.Records[0].eventName.startsWith("ObjectRemoved")){const s=ee.findInMap(r,this._epsilon.config.s3.removeHandlers);s?n=await s(e):t.info("Found no s3 create handler for : %s",r)}else{const s=ee.findInMap(r,this._epsilon.config.s3.createHandlers);s?n=await s(e):t.info("Found no s3 remove handler for : %s",r)}}return n}}class le{_epsilon;constructor(e){this._epsilon=e}extractLabel(e,t){return"DDBEvt:"+e.Records[0].eventName+":"+e.Records[0].eventSource}handlesEvent(e){return T.isValidDynamoDBEvent(e)}async processEvent(e,r){let n=null;if(this._epsilon.config&&this._epsilon.config.dynamoDb&&e&&e.Records&&e.Records.length>0){const r=e.Records[0].eventSourceARN,s=ee.findInMap(r,this._epsilon.config.dynamoDb.handlers);if(!s)throw t.info("Found no Dynamo handler for : %s",r),new se;n=await s(e)}return n}async processUncaughtError(e,r,n){throw t.error("Error slipped out to outer edge (Dynamo). Logging and rethrowing : %s",n,n),n}}class ue{process(e){return e.params=Object.assign({},e.params||{},$.fetchLogVariables()),e.params.tester=Date.now(),e.params.awsRequestId=$.currentRequestId(),e.params.traceId=$.currentTraceId(),e.params.traceDepth=$.currentTraceDepth(),e.params.procLabel=$.currentProcessLabel(),e}label(){return"EpsilonLoggingExtensionProcessor"}}class de{_epsilon;constructor(e){this._epsilon=e}extractLabel(e,t){return"SQSEvt:"+e.Records[0].eventSourceARN}handlesEvent(e){return T.isValidSqsEvent(e)}async processEvent(e,r){let n=null;if(this._epsilon.config&&this._epsilon.config.sqs&&e&&e.Records.length>0){const r=e.Records[0].eventSourceARN,s=ee.findInMap(r,this._epsilon.config.sqs.handlers);if(!s)throw t.info("Found no SQS handler for : %s",r),new se;n=await s(e)}return n}async processUncaughtError(e,r,n){throw t.error("Error slipped out to outer edge (SQS). Logging and rethrowing : %s",n,n),n}}class pe{_epsilon;static LOGGER_CONFIGURED=!1;static GLOBAL_INSTANCE_PROVIDER;static set globalInstanceProvider(e){pe.GLOBAL_INSTANCE_PROVIDER=e}static get globalInstanceProvider(){return pe.GLOBAL_INSTANCE_PROVIDER}handlers=null;constructor(e){this._epsilon=e,pe.LOGGER_CONFIGURED?t.info("EpsilonLoggingConfiguration:Skipping default logger config - already configured"):(pe.configureDefaultLogger(),t.info("EpsilonLoggingConfiguration:Default logger configured")),this.handlers=[this._epsilon.webHandler,new te(this._epsilon.webHandler),this._epsilon.backgroundHandler,new ne(this._epsilon),new oe(this._epsilon),new de(this._epsilon),new ie(this._epsilon),new ce(this._epsilon),new le(this._epsilon)]}static configureDefaultLogger(e){const r=e?Object.assign({},e):{};r.initialLevel=r.initialLevel??i.info,r.formatType=r.formatType??d.StructuredJson,r.globalVars=r.globalVars??{},r.outputFunction=r.outputFunction??p.StdOut,r.ringBufferSize=r.ringBufferSize??0;const n=r.preProcessors||[];r.preProcessors=n.concat([new ue]),t.getOptions(),t.changeDefaultOptions(r,!0),t.getOptions(),pe.LOGGER_CONFIGURED=!0,t.info("EpsilonLoggingConfiguration: Updated"),t.dumpOptionsIntoLog()}get epsilon(){return this._epsilon}async processSingleBackgroundByParts(e,t,r,n){return this.processSingleBackgroundEntry(this._epsilon.backgroundManager.createEntry(e,t),r,n)}async processSingleBackgroundEntry(e,r,n){let s=!1;if(e?.type){const o=await this._epsilon.backgroundManager.wrapEntryForInternal(e,r,n);s=await this._epsilon.backgroundHandler.processSingleBackgroundEntry(o),t.info("Direct processed request %j to %s",e,s)}else t.error("Cannot process null/unnamed background entry");return s}async lambdaHandler(e,t){let r=null;try{if(!this.epsilon.config.disableLastResortTimeout&&t&&t.getRemainingTimeInMillis()){const s=await h.timeout(this.innerLambdaHandler(e,t),"EpsilonLastResortTimeout",t.getRemainingTimeInMillis()-1e3);g.isTimeoutToken(s)?(s.writeToLog(),r=X.errorResponse(n.wrapError(new Z("Timed out")))):r=s}else r=await this.innerLambdaHandler(e,t)}finally{$.clearContext()}return r}async innerLambdaHandler(e,r){$.initContext(this._epsilon,e,r,"TBD");let n=null,s=pe.defaultProcessUncaughtError,o=!1;try{if(!this._epsilon)return t.error("Config not found, abandoning"),!1;const a=J.calcLogLevelViaEventOrEnvParam(t.getLevel(),e,this._epsilon.config.loggerConfig);t.setLevel(a),this._epsilon.config.loggerConfig&&this._epsilon.config.loggerConfig.queryParamTracePrefixName&&e.queryStringParameters&&e.queryStringParameters[this._epsilon.config.loggerConfig.queryParamTracePrefixName]&&(t.info("Setting trace prefix to %s",e.queryStringParameters[this._epsilon.config.loggerConfig.queryParamTracePrefixName]),t.updateTracePrefix(e.queryStringParameters[this._epsilon.config.loggerConfig.queryParamTracePrefixName]));let c=!1;for(let o=0;o<this.handlers.length&&!c;o++){const a=this.handlers[o];if(a.handlesEvent(e)){c=!0,s=a.processUncaughtError||s;const o=a.extractLabel(e,r);$.setProcessLabel(o),t.logByLevel(this._epsilon?.config?.loggerConfig?.epsilonStartEndMessageLogLevel||i.info,"EvtStart: %s",o);try{n=await a.processEvent(e,r)}catch(e){if(e instanceof se){c=!1;break}throw e}t.logByLevel(this._epsilon?.config?.loggerConfig?.epsilonStartEndMessageLogLevel||i.info,"EvtEnd: %s",o),t.silly("EvtEnd:Value: %s Value: %j",o,n)}}c||(o=!0)}catch(t){n=await s(e,r,t)}if(this.epsilon.config.throwErrorIfNoSuitableEventHandlers&&o)throw t.error("No matching handler found for event: %j",e),new Error("No matching handler found for event");return n}static async defaultProcessUncaughtError(e,r,n){t.error("Error slipped out to outer edge (Default). Logging and returning log : %s",n,n);return{statusCode:500,body:JSON.stringify({error:c.safeStringifyErr(n)}),isBase64Encoded:!1}}}class he{_aws;_sns;constructor(e,t){this._aws=e,this._sns=t}get config(){return this._aws}get sns(){return this._sns}createEntry(e,t){return{source:this._aws.source,type:e,data:t}}async fireInterApiEventByParts(e,t){const r=this.createEntry(e,t);return await this.fireInterApiEvent(r)}async fireInterApiEvent(e){let r=null;if(this.config.localMode)t.info("Fire inter-api event ignored because running locally (was %j)",e),r="INTER-API-IGNORED";else try{t.info("Firing inter-api event (remote) : %j ",e);const n={type:W.INTER_API_SNS_EVENT,interApiEvent:re.addTraceToInterApiEntry(e)},s=JSON.stringify(n),o=await this.writeMessageToSnsTopic(s);t.debug("Inter-api Wrote message : %s to SNS : %s",r,s,o)}catch(e){t.error("Failed to fireImmediateProcessRequest : %s",e,e)}return r}async writeMessageToSnsTopic(e){let r=null;const n={Message:e,TopicArn:this._aws.snsArn};t.debug("Writing message to SNS topic : j",n);return r=(await this.sns.send(new b(n))).MessageId,r}}class ge{static CLIENT_CSR="-----BEGIN CERTIFICATE REQUEST-----\nMIICwjCCAaoCAQAwfTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAk5WMRIwEAYDVQQH\nDAlMYXMgVmVnYXMxDjAMBgNVBAoMBVBsdW1hMRkwFwYDVQQDDBB3d3cuaGV5cGx1\nbWEuY29tMSIwIAYJKoZIhvcNAQkBFhNjd2Vpc3NAaGV5cGx1bWEuY29tMIIBIjAN\nBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Gh1SD1VciosMgh3MHF7IyKgNTu2\nDjGMoORJV4VNKzrjp7UOdKnD3so0Xx3A6bUTYAL8Vtc+EG+8LZjUpBIOwuKzzbVo\nt16+yt3YXBxzTZPU9g7sFsXx42RoNispIFq0enRtJrq/zq8izZxUZdGn9XD2DidL\nAedtRGjb8cmRuP6wmMRPBOZjct4ZjsSiTyhPa6kpt8V7Pa7vm0HGxcHiDAGp6zoy\nGHfBdsqeBdGbkGT1ZPfs9kpbtXPm82Sckd0p3oY3fJn0rZqpTAb8qcdGcnheYtqX\nFSjX7EoGsIXAK+oj25MvtfoZFMk4rjQ7FkHbgGk0iMHLN0kNjJzN0ysN/wIDAQAB\noAAwDQYJKoZIhvcNAQELBQADggEBAMbpCdoqmY9crolsh5y9YtYDLRIwisTjTjU1\nXzp1MurSzGIdHLokU+fdVWTIzn3uOu24yTQouTUUoYWHT4YgN4wELdDydfNxWvyl\nr34QV5B0FZbRV2sNz/3C1UX/Uor4af1Yv+QYlGHspgj+WIAEkNQ3xQIo9+I/miR+\n2VSlydtyGvmzipgv6CAwOsrQsIw7DkpVmnqIjgjPSXlGCgeKM9S1D/CwNwZnVA/e\nDF1SzDkJKl60/n+xZGYl/OtkH9vB8T6fHqk0iMxXuVUxI137fwEJwIQB5L6hFyJa\nL4hbjq7Cull4qOhXDby+fNJT9Ic7VCosJBXBHxHPsEnY2+TZAJo=\n-----END CERTIFICATE REQUEST-----\n";static CLIENT_CERT_PEM="-----BEGIN CERTIFICATE-----\nMIIDgTCCAmkCFDKASki0c6HD75dCdIZZ3vXq4eQeMA0GCSqGSIb3DQEBCwUAMH0x\nCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJOVjESMBAGA1UEBwwJTGFzIFZlZ2FzMQ4w\nDAYDVQQKDAVQbHVtYTEZMBcGA1UEAwwQd3d3LmhleXBsdW1hLmNvbTEiMCAGCSqG\nSIb3DQEJARYTY3dlaXNzQGhleXBsdW1hLmNvbTAeFw0yMzAxMjMxMDU2MDlaFw0y\nMzAyMjIxMDU2MDlaMH0xCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJOVjESMBAGA1UE\nBwwJTGFzIFZlZ2FzMQ4wDAYDVQQKDAVQbHVtYTEZMBcGA1UEAwwQd3d3LmhleXBs\ndW1hLmNvbTEiMCAGCSqGSIb3DQEJARYTY3dlaXNzQGhleXBsdW1hLmNvbTCCASIw\nDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANhodUg9VXIqLDIIdzBxeyMioDU7\ntg4xjKDkSVeFTSs646e1DnSpw97KNF8dwOm1E2AC/FbXPhBvvC2Y1KQSDsLis821\naLdevsrd2Fwcc02T1PYO7BbF8eNkaDYrKSBatHp0bSa6v86vIs2cVGXRp/Vw9g4n\nSwHnbURo2/HJkbj+sJjETwTmY3LeGY7Eok8oT2upKbfFez2u75tBxsXB4gwBqes6\nMhh3wXbKngXRm5Bk9WT37PZKW7Vz5vNknJHdKd6GN3yZ9K2aqUwG/KnHRnJ4XmLa\nlxUo1+xKBrCFwCvqI9uTL7X6GRTJOK40OxZB24BpNIjByzdJDYyczdMrDf8CAwEA\nATANBgkqhkiG9w0BAQsFAAOCAQEAWQG2tvWY+cyeeumD/7WKTBNaBjg4EAe+1mnZ\nKQsg0gGUL0kWsqCkg4xEqIojkKMjs62uS6ballEyWawygYd91OaJLFopNu+Dxk4N\n5GWKpriPr02vI6rMUZNtCmsooukEShr5ufFWb4WLnk4NXQlBCXTHbmIf7Z82UOMw\nONZdZyKLqlA0Z6SWYBp2gO32puww6dUU0DAKkIIx1SN8i8UKvowRAy13bugPtyau\nNknlE3J1+Gab1hHCMRdKFZPKy8nc7LWUNZhgKdY82IC/k5FSW32Wibfog1TwWRJR\nceTW4EN4P7ZmdHGMYkIplc7Qcx0mraY2HRqmjA33j3cNcY5UsQ==\n-----END CERTIFICATE-----\n";static CLIENT_KEY_PEM="-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEA2Gh1SD1VciosMgh3MHF7IyKgNTu2DjGMoORJV4VNKzrjp7UO\ndKnD3so0Xx3A6bUTYAL8Vtc+EG+8LZjUpBIOwuKzzbVot16+yt3YXBxzTZPU9g7s\nFsXx42RoNispIFq0enRtJrq/zq8izZxUZdGn9XD2DidLAedtRGjb8cmRuP6wmMRP\nBOZjct4ZjsSiTyhPa6kpt8V7Pa7vm0HGxcHiDAGp6zoyGHfBdsqeBdGbkGT1ZPfs\n9kpbtXPm82Sckd0p3oY3fJn0rZqpTAb8qcdGcnheYtqXFSjX7EoGsIXAK+oj25Mv\ntfoZFMk4rjQ7FkHbgGk0iMHLN0kNjJzN0ysN/wIDAQABAoIBAHzZ9yAQUqWk8w6C\nl9EZB4PDzE4p/uS9bXa9fhrCSz0vonv1FzvzXY/BdOmTTuMGlwEDd/XaBHKTJCvi\nSnvF90I0bKu3h4yTWtvLlbG+sD8HlQvInCifVuhr2zu1Nur1qb4kQXzgrRxfKmMZ\nWA/OH2qZGzwbK0kT7ZRUMuCR/EKPjYw9KP6pMF8nxXUjSm+g3YwgIB8kiPeDCV6C\n0/Ecpv5qMqcoYTg9f9KyBNmY3U5ZgbYrdwTDSMrrTwZKSHhTktdF0SEfYrVGLLEU\nvfQQlQmfcc5Z3+cz99BH1BeTNaCPtEaXjgvQYwkWlSxnY6QUE0p1qq9Jy0xaVEx9\n8LReuHECgYEA/hhJ6b2XV1WLtszFO8MRMzlyMuvBc3Ot0dsuJ7r1W3WOF5X7poSU\nxG0xe+n6Kubmi3tGhzS7BN4TEO9/SSE2gIQTk9zwAMuf+mZJQcG0Qz1iftVp5nnM\nzi205vBLLq2Pmk7wbhTIBO8J190Dli1/fuvk/cmJrA60Ys8v3y4e820CgYEA2gfV\nQ3eHRxk3wl4On71mMovY7lMx6+S8K8hBGo26A5FIu6N6v2jxKnQ5YphwFgjtkxgs\nLspAXmxRwFMapZP3d/nFeBhlOzNly7tqIdDOeNqEcUzEx7pwGXpWGZEHOYs1fvU+\ngU/1N8q9DBvr0B+XGeYR3NNdljajo6pwWZ6ed5sCgYAGmkz5ZPLU0yVBR8rsRaJh\nyWFdT2EEhgIDTQXDBImxqblahYw3hIR1Ij1B8g+NI9jj0P1BMC6X7sliDEcreFB5\nQHVdx0T5UFFE6XmH2ue7Q5IWp6cL1ShsRyXHRoE9okb0BI8c3S9haXDBCj44ndAN\nVUXrDlykevFXC/k7fHBTdQKBgHjIshpoEycOD1e753oS4JTL6GdO6271DlFq5LYj\nIZNsXtCkJhH3vvJ35Hp8XEu4snQ0hfV90d79PuS+pRppOETct8pqKVp8hL4ymv8U\nv+0vkQN7NeA3pnZW0W/kag400nP8xJ26f+xiggw9Q4vOlFSioe6loUjgCBNZDlh3\niO5VAoGASXkcv39B9/8FuWQ7rwhXHEubxOOwZZzSBU1wtLj2qHyPGoeU9ZpsmdrL\nXS9w1Jy0e49qmbBjzTqAEBw2nn/JVMFHyI/s//JVF7Q9GfBZAF5XF6mJ24yzTKgF\nkSoO5T+7s8NXi0eAIBe4CkWCBX7kWEZtu46GuVhsrC3oEazuLOs=\n-----END RSA PRIVATE KEY-----\n"}class me extends n{static HTTP_CODE=404;constructor(...e){super(...e),Object.setPrototypeOf(this,me.prototype),this.withHttpStatusCode(me.HTTP_CODE)}}class fe extends n{static HTTP_CODE=403;constructor(...e){super(...e),Object.setPrototypeOf(this,fe.prototype),this.withHttpStatusCode(fe.HTTP_CODE)}}class Ee extends n{static HTTP_CODE=501;constructor(...e){super(...e),Object.setPrototypeOf(this,Ee.prototype),this.withHttpStatusCode(Ee.HTTP_CODE)}}class ye extends n{static HTTP_CODE=500;constructor(...e){super(...e),Object.setPrototypeOf(this,ye.prototype),this.withHttpStatusCode(ye.HTTP_CODE)}}class we{static async expectedHandledByFilter(e,t){throw(new ye).withFormattedErrorMessage("Should not happen - it was expected that route %s would be handled by a filter",e.path)}static async handleNotImplemented(e,r){t.info("A request was made to %s with body %j - not yet implemented",e.path,e.body);return{time:(new Date).toLocaleString(),path:e.path,message:"NOT IMPLEMENTED YET"}}static async sample(t,r,s){const o={time:(new Date).toLocaleString(),evt:t,pad:e.createRandomHexString(2e3),flag:r};s&&(o.context=s);const a=l.safeNumber(t.queryStringParameters.error);if(a)switch(a){case-1:throw new Error("Test random failure");case 400:throw new K("Bad request error");case 401:throw new Y("Unauthorized error");case 403:throw new fe("Forbidden error");case 404:throw new me("Not Found error");case 501:throw new Ee("Not Implemented");default:throw(new n).withFormattedErrorMessage("Default error - %s",a).withHttpStatusCode(500).withDetails({src:a}).withEndUserErrors(["msg1","msg2"])}let i=e.trimToNull(t.queryStringParameters.test);return i&&(i=i.toLowerCase(),"null"===i)?null:o}static async defaultErrorProcessor(e,r,n){t.warn("Unhandled error (in promise catch) : %s \nStack was: %s\nEvt was: %j\nConfig was: %j",r.message,r.stack,e,n)}}class Se{encryptionKeys;issuer;_ratchet;constructor(e,t){this.encryptionKeys=e,this.issuer=t,u.notNullOrUndefined(e,"encryptionKeys"),u.noNullOrUndefinedValuesInArray(e,e.length);const r={encryptionKeyPromise:Promise.resolve(e)};this._ratchet=new m(r)}withExtraDecryptionKeys(e){u.notNullOrUndefined(e,"keys"),u.noNullOrUndefinedValuesInArray(e,e.length);const t=this._ratchet.copyConfig;return t.decryptKeysPromise=Promise.resolve(e),this._ratchet=new m(t),this}withParseFailureLogLevel(e){const t=this._ratchet.copyConfig;return t.parseFailureLogLevel=e,this._ratchet=new m(t),this}withOldKeyUseLogLevel(e){const t=this._ratchet.copyConfig;return t.decryptOnlyKeyUseLogLevel=e,this._ratchet=new m(t),this}get jwtRatchet(){return this._ratchet}get selectRandomEncryptionKey(){return this._ratchet.selectRandomEncryptionKey()}createRefreshedJWTString(e,t,r){return this._ratchet.refreshJWTString(e,r||!1,t)}async parseAndValidateJWTStringAsync(e){const t=await this._ratchet.decodeToken(e,2);if(m.hasExpiredFlag(t))throw new Y("Failing JWT token read/validate - token expired on "+t.exp);return t}async createJWTStringAsync(e,r,n=["USER"],s=3600,o=null){t.info("Creating JWT token for %s that expires in %s",e,s);const a=(new Date).getTime(),i={exp:a+1e3*s,iss:this.issuer,sub:e,iat:a,user:r,proxy:o,roles:n};return await this._ratchet.createTokenString(i,s)}async extractTokenFromAuthorizationHeader(t){let r=e.trimToEmpty(t);r.toLowerCase().startsWith("bearer ")&&(r=r.substring(7));return r?await this.parseAndValidateJWTStringAsync(r):null}}class Te{static TYPE_NAME="EpsilonEcho";get typeName(){return Te.TYPE_NAME}async handleEvent(r,n){t.info("Echo processing : %j",r),r&&e.trimToNull(r.error)&&c.throwFormattedErr("Forced error : %s",r.error)}}class Ae{get typeName(){return"EpsilonNoOp"}async handleEvent(e,r){t.silly("Hit the no-op proc")}}class Re{get typeName(){return"EpsilonSampleDelay"}async handleEvent(e,r){const n=Math.floor(5e3*Math.random());t.info("Running sample processor for %d",n),await h.wait(n),t.info("Sample processor complete")}}class be{get typeName(){return"EpsilonLogAndEnqueueEcho"}async handleEvent(e,r){t.info("LogAndEnqueueEchoProcessor : %j",e),await r.fireImmediateProcessRequestByParts(Te.TYPE_NAME,{upstream:e}),t.info("Completed : LogAndEnqueueEchoProcessor")}}const Ce={Queued:"Queued",Immediate:"Immediate"};class Ne{backgroundConfig;modelValidator;backgroundManager;maxWaitInMsForBackgroundJobToStart;constructor(e,t,r,n=1e4){this.backgroundConfig=e,this.modelValidator=t,this.backgroundManager=r,this.maxWaitInMsForBackgroundJobToStart=n}get httpMetaEndpoint(){return this.backgroundConfig.httpMetaEndpoint}get httpSubmissionPath(){return this.backgroundConfig.httpSubmissionPath}get httpStatusPath(){return this.backgroundConfig.httpStatusEndpoint}get implyTypeFromPathSuffix(){return this.backgroundConfig.implyTypeFromPathSuffix}async handleBackgroundStatusRequest(r,n){if(t.info("handleBackgroundStatusRequest called"),this.backgroundConfig.transactionLogger){const n=e.trimToNull(r.pathParameters.guid)||e.trimToNull(r.queryStringParameters.guid);if(n){const e=new f;let r=null;for(;!r&&e.elapsedMS()<this.maxWaitInMsForBackgroundJobToStart;)r=await this.backgroundConfig.transactionLogger.readTransactionLog(n),r||(t.debug("No log found yet, waiting 500 ms and retrying (%s of %d waited so far)",e.dump(),this.maxWaitInMsForBackgroundJobToStart),await h.wait(500));if(!r)throw(new me).withFormattedErrorMessage("No background result found for guid %s",n);return r}throw new K("No guid specified")}throw new K("Process logging not enabled")}async handleBackgroundMetaRequest(e,r){t.info("handleBackgroundMetaRequest called");const n=await this.backgroundManager.fetchApproximateNumberOfQueueEntries(),s=this.backgroundConfig.processors.map((e=>e.typeName)).filter((e=>!!e));s.sort(((e,t)=>e.localeCompare(t)));return{currentQueueLength:n,validTypes:s,backgroundManagerName:this.backgroundManager.backgroundManagerName}}async handleBackgroundSubmission(r,n){t.info("handleBackgroundSubmission : %j (mgr:%s)",r.parsedBody,this.backgroundManager.backgroundManagerName);let s=null;const o=r.path.indexOf(this.httpSubmissionPath)+this.httpSubmissionPath.length;let a=this.backgroundConfig.implyTypeFromPathSuffix?r.path.substring(o).split("-").join("").toLowerCase():"";a.includes("?")&&(a=a.substring(0,a.indexOf("?"))),a.includes("#")&&(a=a.substring(0,a.indexOf("#")));const i=r.parsedBody||{};if(e.trimToNull(a)){if(e.trimToNull(i?.type)&&i.type.toLocaleLowerCase()!==a.toLocaleLowerCase())throw new K("Background submission has type but does not match path supplied type");i.type=a}else if(!e.trimToNull(i?.type))throw new K("Background submission missing type and not configured in pathed mode");const c=this.backgroundConfig.processors.find((e=>e.typeName.toLowerCase()===i.type.toLowerCase())),l=E.parseBool(r.queryStringParameters.immediate),u=E.parseBool(r.queryStringParameters.startProcessor);if(!c)throw(new K).withFormattedErrorMessage("Could not find target background processor : %s",i.type);{if(e.trimToNull(c.dataSchemaName)){const e=this.modelValidator.validate(c.dataSchemaName,i.data,!1,!1);if(e.length>0)throw(new K).withErrors(e)}let t=null;t=l?await this.backgroundManager.fireImmediateProcessRequest(i):await this.backgroundManager.addEntryToQueue(i,u),s={processHandling:l?Ce.Immediate:Ce.Queued,startProcessorRequested:u,success:!0,resultId:t,error:null}}return s}}class ve{cfg;modelValidator;constructor(e,t){this.cfg=e,this.modelValidator=t}findProcessor(e){return this.cfg.processors.find((t=>t.typeName===e))}validType(e){return!!this.findProcessor(e)}validateEntry(t){const r=[];if(t){if(!e.trimToNull(t.type)){r.push("Entry type is null or empty");this.findProcessor(t.type)||r.push("Entry type is invalid")}}else r.push("Entry is null");return r}validateEntryAndThrowException(e){const r=this.validateEntry(e);r.length>0&&(t.warn("Invalid entry %j : errors : %j",e,r),c.throwFormattedErr("Invalid entry %j : errors : %j",e,r))}static validateAndMapProcessors(t,r){const n=new Map;return t.forEach(((t,r)=>{t||c.throwFormattedErr("Null processor provided at index %d",r),e.trimToNull(t.typeName)||c.throwFormattedErr("Processor at index %d defines no name",r),n.has(t.typeName)&&c.throwFormattedErr("More than one processor defined for type %s",t.typeName),n.set(t.typeName,t)})),n}static validateAwsConfig(e){const t=[];return e?(e.notificationArn||t.push("AWS config missing notificationArn"),e.queueUrl||t.push("AWS config missing queueUrl"),!e.sendNotificationOnBackgroundError&&!e.sendNotificationOnBackgroundValidationFailure||e.backgroundProcessFailureSnsArn||t.push("At least one send notification flag set to true but no sns arn set")):t.push("Null config"),t}static validateConfig(e){const t=[];return e?e.processors&&0!==e.processors.length||t.push("No processes specified"):t.push("Null config"),t}}const Pe={ProcessStarting:"ProcessStarting",DataValidationError:"DataValidationError",ExecutionSuccessfullyComplete:"ExecutionSuccessfullyComplete",ExecutionFailedError:"ExecutionRuntimeError",NoMatchProcessorName:"NoMatchProcessorName"};class Ie{createEntry(e,t){return{type:e,data:t}}async wrapEntryForInternal(e,t,r){return Object.assign({},e,{createdEpochMS:(new Date).getTime(),guid:Ie.generateBackgroundGuid(),traceId:t||$.currentTraceId(),traceDepth:r||$.currentTraceDepth()+1})}async addEntryToQueueByParts(e,t,r){let n=null;const s=this.createEntry(e,t);return s&&(n=await this.addEntryToQueue(s,r)),n}async addEntriesToQueue(e,r){const n=[];for(let s=0;s<e.length;s++){try{const t=await this.addEntryToQueue(e[s],!1);n.push(t)}catch(r){t.error("Error processing %j : %s",e[s],r),n.push(r.message)}if(r){const e=await this.fireStartProcessingRequest();t.silly("FireResult : %s",e)}}return n}async fireImmediateProcessRequestByParts(e,t){let r=null;const n=this.createEntry(e,t);return n&&(r=await this.fireImmediateProcessRequest(n)),r}static generateBackgroundGuid(t=(new Date).getTime()){return R.fromMillis(t).toFormat("yyyy-MM-dd-HH-mm-ss-")+e.createType4Guid()}static backgroundGuidToPath(t,r){let n=e.trimToEmpty(t);return n.length&&!n.endsWith("/")&&(n+="/"),n+=r.substring(0,4)+"/"+r.substring(5,7)+"/"+r.substring(8,10)+"/",n+=r+".json",n}static pathToBackgroundGuid(t,r){u.notNullOrUndefined(r,"path");let n=0;return r.endsWith(".json")||c.throwFormattedErr("Cannot extract guid, does not end with .json : %s : %s",r,t),e.trimToNull(t)&&(r.startsWith(t)||c.throwFormattedErr("Cannot extract guid, does not start with prefix : %s : %s",r,t),n=t.length,t.endsWith("/")||n++),n+=11,r.substring(n,r.length-5)}}class Oe{cfg;mgr;modelValidator;processors;validator;constructor(e,r,n){this.cfg=e,this.mgr=r,this.modelValidator=n;const s=ve.validateConfig(e);s.length>0&&c.throwFormattedErr("Invalid background config : %j",s),t.silly("Starting Background processor, %d processors",e.processors.length),this.validator=new ve(e,n),this.processors=ve.validateAndMapProcessors(e.processors,n),r?.immediateProcessQueue&&r.immediateProcessQueue()&&(t.info("Attaching to immediate processing queue"),r.immediateProcessQueue().subscribe((async e=>{t.debug("Processing local background entry : %j",e);const r=await this.processSingleBackgroundEntry(e);t.info("Processor returned %s",r)})))}extractLabel(e,t){let r=null;if(this.isBackgroundStartSnsEvent(e))r="BG:START-EVT";else if(this.isBackgroundImmediateFireEvent(e)){const t=this.parseImmediateFireBackgroundEntry(e);r="BG:"+t.type+":"+t.guid}else r="BG:UNKNOWN";return r}handlesEvent(e){return T.isValidSnsEvent(e)&&this.isBackgroundSNSEvent(e)}isBackgroundSNSEvent(e){return this.isBackgroundStartSnsEvent(e)||this.isBackgroundImmediateFireEvent(e)}isBackgroundStartSnsEvent(e){let t=!1;if(e&&T.isSingleSnsEvent(e)){t=e.Records[0].Sns.Message===W.BACKGROUND_SNS_START_MARKER}return t}isBackgroundImmediateFireEvent(t){let r=!1;if(t&&T.isSingleSnsEvent(t)){const n=t.Records[0].Sns.Message;if(e.trimToNull(n)){const e=JSON.parse(n);r=!!e&&e.type===W.BACKGROUND_SNS_IMMEDIATE_RUN_FLAG}}return r}parseImmediateFireBackgroundEntry(r){let n=null;try{if(r&&T.isSingleSnsEvent(r)){const t=r.Records[0].Sns.Message;if(e.trimToNull(t)){const e=JSON.parse(t);e&&e.type===W.BACKGROUND_SNS_IMMEDIATE_RUN_FLAG&&(n=e.backgroundEntry)}}}catch(e){t.error("Could not parse %j as an immediate run event : %s",r,e,e)}return n}async processEvent(r,n){let s=null;if(this.isBackgroundStartSnsEvent(r))if(t.info("Reading task from background queue"),s=await this.takeAndProcessSingleBackgroundQueueEntry(),s>0){t.info("Processed %d elements from background queue, refiring",s);const e=await this.mgr.fireStartProcessingRequest();t.info("Refire returned %s",e)}else t.info("No items processed - stopping");else{const e=this.parseImmediateFireBackgroundEntry(r);if(e){t.silly("Processing immediate fire event : %j",e);const r=await this.processSingleBackgroundEntry(e);t.silly("Result was : %s",r),s=1}else t.warn("Tried to process non-background start / immediate event : %j returning false",r)}return{statusCode:200,body:e.safeString(s),isBase64Encoded:!1}}async takeAndProcessSingleBackgroundQueueEntry(){let e=null;const r=await this.mgr.takeEntryFromBackgroundQueue();t.info("Found %d entries - processing",r.length);for(let t=0;t<r.length;t++){const n=r[t];e+=await this.processSingleBackgroundEntry(n)?1:0}return t.debug("Returning %d",e),e}async safeWriteToLogger(e){if(this.cfg.transactionLogger)try{await this.cfg.transactionLogger.logTransaction(e)}catch(r){t.error("Failed to write to transaction logger : %j : %s",e,r,r)}else t.silly("Skipping - no logger defined")}async conditionallyStartTransactionLog(r){if(!e.trimToNull(r.guid)){t.warn("No guid found - creating"),r.guid=Ie.generateBackgroundGuid();const e={request:r,running:!0};await this.safeWriteToLogger(e)}t.debug("Starting transaction log")}async conditionallyCompleteTransactionLog(e,r,n,s){t.debug("Completing transaction log");const o={request:e,result:r,error:n?c.safeStringifyErr(n):null,running:!1,runtimeMS:s};await this.safeWriteToLogger(o)}async conditionallyRunErrorProcessor(e,r){try{this.cfg.errorProcessor&&(t.info("Running error processor"),await this.cfg.errorProcessor.handleError(e,r))}catch(e){t.error("Background : BAD - Failed to run error processor : %s",e,e)}}async fireListenerEvent(r){const n=this.cfg.executionListeners||[];for(const s of n)try{await s.onEvent(r)}catch(r){t.error("Failure triggering handler %s : %s",e.trimToNull(s?.label)||"No-name",r)}}async processSingleBackgroundEntry(r){let n=r;$.setOverrideTraceFromInternalBackgroundEntry(n),t.info("Background Process Start: %j",n);const s=new f;await this.conditionallyStartTransactionLog(n),this?.mgr?.modifyPayloadPreProcess&&(t.silly("Firing payload pre-process"),n=await this.mgr.modifyPayloadPreProcess(n));let o=!1;try{await this.fireListenerEvent({type:Pe.ProcessStarting,processorType:n.type,data:n.data,guid:n.guid});const t=this.processors.get(n.type);t||(c.throwFormattedErr("Found no processor for background entry : %j (returning false)",n),await this.fireListenerEvent({type:Pe.NoMatchProcessorName,processorType:n.type,data:n.data,guid:n.guid}));let r=[];if(e.trimToNull(t.dataSchemaName)&&(r=this.modelValidator.validate(t.dataSchemaName,n.data,!1,!1)),r.length>0)await this.fireListenerEvent({type:Pe.DataValidationError,processorType:n.type,data:n.data,errors:r,guid:n.guid}),c.throwFormattedErr("Not processing, data failed validation; entry was %j : errors : %j",n,r);else{let e=await t.handleEvent(n.data,this.mgr);e=e||"SUCCESSFUL COMPLETION : NO RESULT RETURNED",await this.conditionallyCompleteTransactionLog(n,e,null,s.elapsedMS()),await this.fireListenerEvent({type:Pe.ExecutionSuccessfullyComplete,processorType:n.type,data:e,guid:n.guid}),o=!0}}catch(e){t.error("Background Process Error: %j : %s",n,e,e),await this.conditionallyRunErrorProcessor(n,e),await this.conditionallyCompleteTransactionLog(n,null,e,s.elapsedMS()),await this.fireListenerEvent({type:Pe.ExecutionFailedError,processorType:n.type,data:n.data,errors:[c.safeStringifyErr(e)],guid:n.guid})}return t.info("Background Process Stop: %j : %s",n,s.dump()),o}getConfig(){return Object.assign({},this.cfg)}}const _e={Error:"Error",ConvertToEmptyString:"ConvertToEmptyString",Return404NotFoundResponse:"Return404NotFoundResponse"};class Le{static MAXIMUM_LAMBDA_BODY_SIZE_BYTES=5140480;static async combineFilters(e,t){let r=!0;if(t&&t.length>0)for(let n=0;n<t.length&&r;n++)r=await t[n](e);return r}static async applyGzipIfPossible(e){if(e.event?.headers&&e.result){const t=e.event&&e.event.headers?s.extractValueFromMapIgnoreCase(e.event.headers,"accept-encoding"):null;e.result=await X.applyGzipIfPossible(t,e.result)}return!0}static async addConstantHeaders(e,r){return r&&e.result?e.result.headers=Object.assign({},r,e.result.headers):t.warn("Could not add headers - either result or headers were missing"),!0}static async addAWSRequestIdHeader(r,n="X-REQUEST-ID"){return r.result&&e.trimToNull(n)&&n.startsWith("X-")?(r.result.headers=r.result.headers||{},r.result.headers[n]=r.context?.awsRequestId||"Request-Id-Missing"):t.warn("Could not add request id header - either result or context were missing or name was invalid"),!0}static async addAllowEverythingCORSHeaders(e){return Le.addConstantHeaders(e,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"*","Access-Control-Allow-Headers":"*"})}static async addAllowReflectionCORSHeaders(e){return Le.addConstantHeaders(e,{"Access-Control-Allow-Origin":s.caseInsensitiveAccess(e.event.headers,"Origin")||"*","Access-Control-Allow-Methods":s.caseInsensitiveAccess(e.event.headers,"Access-Control-Request-Method")||"*","Access-Control-Allow-Headers":s.caseInsensitiveAccess(e.event.headers,"Access-Control-Request-Headers")||"*"})}static async uriDecodeQueryParams(e){return e?.event?.queryStringParameters&&Object.keys(e.event.queryStringParameters).forEach((t=>{const r=e.event.queryStringParameters[t];r&&(e.event.queryStringParameters[t]=Le.decodeUriComponentAndReplacePlus(r))})),e?.event?.multiValueQueryStringParameters&&Object.keys(e.event.multiValueQueryStringParameters).forEach((t=>{const r=e.event.multiValueQueryStringParameters[t];if(r&&r.length){const n=r.map((e=>Le.decodeUriComponentAndReplacePlus(e)));e.event.multiValueQueryStringParameters[t]=n}})),!0}static decodeUriComponentAndReplacePlus(e){return decodeURIComponent(e.replace(/\+/g," "))}static async fixStillEncodedQueryParams(e){return J.fixStillEncodedQueryParams(e.event),!0}static async disallowStringNullAsPathParameter(t){return t?.event?.pathParameters&&Object.keys(t.event.pathParameters).forEach((r=>{if("null"===e.trimToEmpty(t.event.pathParameters[r]).toLowerCase())throw(new K).withFormattedErrorMessage("Path parameter %s was string -null-",r)})),!0}static async disallowStringNullAsQueryStringParameter(t){return t?.event?.queryStringParameters&&Object.keys(t.event.queryStringParameters).forEach((r=>{if("null"===e.trimToEmpty(t.event.queryStringParameters[r]).toLowerCase())throw(new K).withFormattedErrorMessage("Query parameter %s was string -null-",r)})),!0}static async ensureEventMaps(e){return e.event.queryStringParameters=e.event.queryStringParameters||{},e.event.headers=e.event.headers||{},e.event.pathParameters=e.event.pathParameters||{},!0}static async parseJsonBodyToObject(e){if(e.event?.body)try{e.event.parsedBody=J.jsonBodyToObject(e.event)}catch(e){throw new n("Supplied body was not parsable as valid JSON").withHttpStatusCode(400)}return!0}static async checkMaximumLambdaBodySize(e){if(e.result?.body&&e.result.body.length>Le.MAXIMUM_LAMBDA_BODY_SIZE_BYTES){const t=e.result.body.length-Le.MAXIMUM_LAMBDA_BODY_SIZE_BYTES;throw new n("Response size is "+e.result.body.length+" bytes, which is "+t+" bytes too large for this handler").withHttpStatusCode(500)}return!0}static async validateInboundBody(e){if(e?.event?.parsedBody&&e.routeAndParse){if(e.routeAndParse.mapping.validation){if(!e.modelValidator)throw new ye("Requested body validation but supplied no validator");const r=e.modelValidator.validate(e.routeAndParse.mapping.validation.modelName,e.event.parsedBody,e.routeAndParse.mapping.validation.emptyAllowed,e.routeAndParse.mapping.validation.extraPropertiesAllowed);if(r.length>0){t.info("Found errors while validating %s object %j",e.routeAndParse.mapping.validation.modelName,r);throw new K(...r)}}}else t.debug("No validation since no route specified or no parsed body");return!0}static async validateInboundQueryParams(e){return!0}static async validateInboundPathParams(e){return!0}static async validateOutboundResponse(e){if(e?.rawResult)if(e.routeAndParse.mapping.outboundValidation){t.debug("Applying outbound check to %j",e.rawResult);const r=e.modelValidator.validate(e.routeAndParse.mapping.outboundValidation.modelName,e.rawResult,e.routeAndParse.mapping.outboundValidation.emptyAllowed,e.routeAndParse.mapping.outboundValidation.extraPropertiesAllowed);if(r.length>0)throw t.error("Found outbound errors while validating %s object %j",e.routeAndParse.mapping.outboundValidation.modelName,r),r.unshift("Server sent object invalid according to spec"),(new n).withErrors(r).withHttpStatusCode(500).withDetails(e.rawResult)}else t.debug("Applied no outbound validation because none set");else t.debug("No validation since no outbound body or disabled");return!0}static async autoRespondToOptionsRequestWithCors(t){return"options"!==e.trimToEmpty(t?.event?.httpMethod).toLowerCase()||(t.result={statusCode:200,body:'{"cors":true, "m":2}'},await Le.addAllowReflectionCORSHeaders(t),!1)}static async autoRespond(e,t){const r=t||{message:"Not Implemented"};return e.result={statusCode:200,body:JSON.stringify(r)},!1}static async secureOutboundServerErrorForProduction(e,r,s){if(e?.result?.statusCode&&(null===s||e.result.statusCode===s)){t.warn("Securing outbound error info (was : %j)",e.result.body),e.rawResult=new n(r).withHttpStatusCode(e.result.statusCode);const s=e.result;e.result=X.errorResponse(e.rawResult),e.result.headers=Object.assign({},s.headers||{},e.result.headers||{})}return!0}}class Me{static async requireAllRolesInCommonJwt(e,t){if(!t||0===t.length)throw new ye("You must require at least 1 role");if(!e.event?.authorization?.auth)throw new Y("May not proceed, not authenticated");{const r=e.event.authorization.auth;if(!r.roles||0===r.roles.length)throw new Y("Required role not found");t.forEach((e=>{if(!r.roles.includes(e))throw new Y("Required role not found")}))}return!0}static async requireAnyRoleInCommonJwt(e,t){if(!t||0===t.length)throw new ye("You must require at least 1 role");if(!e.event?.authorization?.auth)throw new Y("May not proceed, not authenticated");{const r=e.event.authorization.auth;if(!r.roles||0===r.roles.length)throw new Y("Required role not found");{let e=!1;if(t.forEach((t=>{!e&&r.roles.includes(t)&&(e=!0)})),!e)throw new Y("Required role not found")}}return!0}static async parseAuthorizationHeader(e,t){if(!e?.event||!t||Array.isArray(t)&&!t.length)throw new ye("Cannot continue - missing event or encryption");{const r=J.extractBearerTokenFromEvent(e?.event);Array.isArray(t)||(t=[t]);for(let n=0;n<t.length&&!e?.event?.authorization?.auth;n++){const s=t[n];try{const t=await s.extractTokenFromAuthorizationHeader(r);e.event.authorization={raw:r,auth:t,error:null}}catch(t){e.event.authorization={raw:r,auth:null,error:t.message}}}}return!0}static async applyOpenApiAuthorization(t){if(e.trimToNull(t?.routeAndParse?.mapping?.authorizerName)){const e=t?.authenticators?.get(t.routeAndParse.mapping.authorizerName);if(!e)throw(new ye).withFormattedErrorMessage("Authorizer %s requested but not found",t.routeAndParse.mapping.authorizerName);if(!t?.event?.authorization?.auth)throw new Y("You need to supply credentials for this endpoint");if(!await e(t.event.authorization,t.event,t.routeAndParse.mapping))throw new fe("You lack privileges to see this endpoint")}return!0}}class ke{static LOG_LEVEL_BEFORE_CHANGE=null;static async setLogLevelForTransaction(e){return ke.LOG_LEVEL_BEFORE_CHANGE=t.getLevel(),!0}static async clearLogLevelForTransaction(e){return ke.LOG_LEVEL_BEFORE_CHANGE&&(t.setLevel(ke.LOG_LEVEL_BEFORE_CHANGE),ke.LOG_LEVEL_BEFORE_CHANGE=null,t.updateTracePrefix(null)),!0}}class Fe{constructor(){}static defaultAuthenticationHeaderParsingEpsilonPreFilters(e){return[t=>Me.parseAuthorizationHeader(t,e),e=>Me.applyOpenApiAuthorization(e)].concat(Fe.defaultEpsilonPreFilters())}static defaultEpsilonPreFilters(){return[e=>Le.autoRespondToOptionsRequestWithCors(e),e=>Le.ensureEventMaps(e),e=>ke.setLogLevelForTransaction(e),e=>Le.parseJsonBodyToObject(e),e=>Le.fixStillEncodedQueryParams(e),e=>Le.uriDecodeQueryParams(e),e=>Le.disallowStringNullAsPathParameter(e),e=>Le.disallowStringNullAsQueryStringParameter(e),e=>Le.validateInboundBody(e),e=>Le.validateInboundQueryParams(e),e=>Le.validateInboundQueryParams(e)]}static defaultEpsilonPostFilters(){return[e=>Le.validateOutboundResponse(e),e=>Le.addAWSRequestIdHeader(e),e=>Le.addAllowReflectionCORSHeaders(e),e=>Le.applyGzipIfPossible(e),e=>Le.checkMaximumLambdaBodySize(e),e=>ke.clearLogLevelForTransaction(e)]}static defaultEpsilonErrorFilters(){return[e=>Le.addAWSRequestIdHeader(e),e=>Le.addAllowReflectionCORSHeaders(e),e=>ke.clearLogLevelForTransaction(e)]}static defaultHttpMetaProcessingConfigWithAuthenticationHeaderParsing(e){return{configName:"EpsilonDefaultHttpMetaProcessingConfig",timeoutMS:3e4,overrideAuthorizerName:null,preFilters:Fe.defaultAuthenticationHeaderParsingEpsilonPreFilters(e),postFilters:Fe.defaultEpsilonPostFilters(),errorFilters:Fe.defaultEpsilonErrorFilters(),nullReturnedObjectHandling:_e.Return404NotFoundResponse}}static defaultHttpMetaProcessingConfig(){return{configName:"EpsilonDefaultHttpMetaProcessingConfig",timeoutMS:3e4,overrideAuthorizerName:null,preFilters:Fe.defaultEpsilonPreFilters(),postFilters:Fe.defaultEpsilonPostFilters(),errorFilters:Fe.defaultEpsilonErrorFilters(),nullReturnedObjectHandling:_e.Return404NotFoundResponse}}static assignDefaultsOnHttpConfig(e){const t={handlers:new Map,authorizers:new Map,defaultMetaHandling:this.defaultHttpMetaProcessingConfig(),staticContentRoutes:{},prefixesToStripBeforeRouteMatch:[],filterHandledRouteMatches:["options .*"]};return Object.assign({},t,e||{})}static findApplicableMeta(e,t,r){let n=null;if(e?.overrideMetaHandling)for(let s=0;s<e.overrideMetaHandling.length&&!n;s++){const o=e.overrideMetaHandling[s];if(!o.methods||0===o.methods.length||o.methods.map((e=>e.toLocaleLowerCase())).includes(t.toLocaleLowerCase())){const e=!!r.match(o.pathRegex);(e&&!o.invertPathMatching||!e&&o.invertPathMatching)&&(n=o.config)}}return n||(n=e.defaultMetaHandling||Fe.defaultHttpMetaProcessingConfig()),n}static openApiYamlToRouterConfig(e,r,n,s){if(!r||!e)throw new ye("Cannot configure, missing either yaml or cfg");const o={routes:[],openApiModelValidator:n,config:Fe.assignDefaultsOnHttpConfig(e)};r?.components?.securitySchemes&&Object.keys(r.components.securitySchemes).forEach((e=>{if(!o.config.authorizers||!o.config.authorizers.get(e))throw(new ye).withFormattedErrorMessage("Doc requires authorizer %s but not found in map",e)}));const a=[],i=e.filterHandledRouteMatches||[];if(r?.paths&&Object.keys(r.paths).forEach((n=>{Object.keys(r.paths[n]).forEach((c=>{const l=Fe.openApiPathToRouteParserPath(n),u=c+" "+n,d=Fe.findApplicableMeta(e,c,n),p=r.paths[n][c],h=n.startsWith(s.httpSubmissionPath),g=n===s.httpMetaEndpoint,m=n===s.httpStatusPath;if(h&&o.config.handlers.set(u,((e,t)=>s.handleBackgroundSubmission(e,t))),g&&o.config.handlers.set(u,((e,t)=>s.handleBackgroundMetaRequest(e,t))),m&&o.config.handlers.set(u,((e,t)=>s.handleBackgroundStatusRequest(e,t))),!o.config.handlers||!o.config.handlers.get(u)){i.find((e=>u.match(e)))?(t.debug("Adding filter-handled handler for %s",u),o.config.handlers.set(u,(e=>we.expectedHandledByFilter(e)))):a.push(u)}if(p&&p.security&&p.security.length>1)throw new ye("Epsilon does not currently support multiple security (path was "+u+")");const f=p.security&&1==p.security.length?Object.keys(p.security[0])[0]:null,y={path:l,method:c,function:o.config.handlers.get(u),authorizerName:d.overrideAuthorizerName||f,metaProcessingConfig:d,validation:null,outboundValidation:null};if(p.requestBody&&p.requestBody.content&&p.requestBody.content["application/json"]&&p.requestBody.content["application/json"].schema){const e=p.requestBody.content;t.silly("Applying schema %j to %s",e,u);const r=this.findAndValidateModelName(c,n,e,o.config.overrideModelValidator||o.openApiModelValidator),s={extraPropertiesAllowed:!0,emptyAllowed:!E.parseBool(p.requestBody.required),modelName:r};y.validation=s}if(p.responses&&p.responses[200]&&p.responses[200].content&&p.responses[200].content["application/json"]&&p.responses[200].content["application/json"].schema){const e=p.responses[200].content;t.silly("Applying schema %j to %s",e,u);const r={extraPropertiesAllowed:!1,emptyAllowed:!1,modelName:this.findAndValidateModelName(c,n,e,o.config.overrideModelValidator||o.openApiModelValidator)};y.outboundValidation=r}o.routes.push(y)}))})),a.length>0)throw(new ye).withFormattedErrorMessage("Missing expected handlers : %j",a);return o}static findAndValidateModelName(e,t,r,n){let s;const o=r["application/json"].schema.$ref,a=r["application/json"].schema.type;if(o){if(s=o.substring(o.lastIndexOf("/")+1),!n.fetchModel(s))throw new ye(`Path ${e} ${t} refers to schema ${s} but its not in the schema section`)}else if(a){s=`${e}-${t}-requestBodyModel`;const o=r["application/json"].schema;n.addModel(s,o)}return s}static openApiPathToRouteParserPath(e){let t=e;if(t){let e=t.indexOf("{");for(;e>-1;){const r=t.indexOf("}");t=t.substring(0,e)+":"+t.substring(e+1,r)+t.substring(r+1),e=t.indexOf("{")}}return t}}class Be{static async runHandler(e,r){const n=Be.findHandler(r,e.event,e.context);t.debug("Processing event with epsilon: %j",Be.eventToStringForLog(e.event));let s=await n;if(g.isTimeoutToken(s))throw s.writeToLog(),new Z("Timed out");return t.debug("Initial return value : %j",s),s=Be.applyNullReturnedObjectHandling(s,r.mapping.metaProcessingConfig.nullReturnedObjectHandling),e.rawResult=s,e.result=X.coerceToProxyResult(s),!0}static applyNullReturnedObjectHandling(e,r){let s=e;if(null==e){if(r===_e.Error)throw t.error("Null object returned and Error specified, throwing 500"),new n("Null object").withHttpStatusCode(500);if(r===_e.Return404NotFoundResponse)throw new me("Resource not found");if(r!==_e.ConvertToEmptyString)throw new n("Cant happen - failed enum check").withHttpStatusCode(500);t.warn("Null object returned from handler and convert not specified, converting to empty string"),s=""}return s}static async findHandler(e,t,r,n=!0){let s=null;if(e)t.pathParameters=Object.assign({},t.pathParameters,e.parsed),s=h.timeout(e.mapping.function(t,r),"Timed out after "+e.mapping.metaProcessingConfig.timeoutMS+" ms. Request was "+Be.eventToStringForLog(t),e.mapping.metaProcessingConfig.timeoutMS);else if(n)throw new me("No such endpoint");return s}static addRunHandlerAsFilterToList(e,t){e&&e.push((e=>Be.runHandler(e,t)))}static eventToStringForLog(e){const t=structuredClone(e);return t?.authorization?.raw&&(t.authorization.raw=Be.redact(t.authorization.raw)),t?.headers?.authorization&&(t.headers.authorization=Be.redact(t.headers.authorization)),JSON.stringify(t)}static redact(t){return t?e.obscure(t,1,1):t}}class xe{routerConfig;static MAXIMUM_LAMBDA_BODY_SIZE_BYTES=5140480;constructor(e){this.routerConfig=e,u.notNullOrUndefined(e)}get router(){return this.routerConfig}extractLabel(t,r){return"WEB:"+e.trimToEmpty(t.httpMethod).toUpperCase()+":"+t.path}handlesEvent(e){return T.isValidApiGatewayEvent(e)}async processEvent(e,r){if(!this.routerConfig)throw new Error("Router config not found");const n=Object.assign({},{parsedBody:null,authorization:null,convertedFromV2Event:!1},e),s=await this.openApiLambdaHandler(n,r);return $.addTraceToProxyResult(s),t.updateTracePrefix(null),s}async openApiLambdaHandler(e,r){const s=this.findBestMatchingRoute(e),o=s?.mapping?.metaProcessingConfig?s.mapping.metaProcessingConfig:this.routerConfig.config.defaultMetaHandling,a={event:e,context:r,result:null,rawResult:null,routeAndParse:s,modelValidator:this.routerConfig.config.overrideModelValidator||this.routerConfig.openApiModelValidator,authenticators:this.routerConfig.config.authorizers};try{let e=Object.assign([],o.preFilters||[]);Be.addRunHandlerAsFilterToList(e,s),e=e.concat(o.postFilters||[]),await Le.combineFilters(a,e)}catch(e){const r=n.wrapError(e);a.result=X.errorResponse(r);try{await Le.combineFilters(a,o.errorFilters)}catch(e){t.error("REALLY BAD - FAILED WHILE PROCESSING ERROR FILTERS : %s",e)}}return a.result}findBestMatchingRoute(e){let r=null;const n=this.cleanPath(e),s=e.httpMethod.toLowerCase(),o=this.routerConfig.routes.map((e=>{let t=null;if(e.method&&e.method.toLowerCase()===s){const r=new k(e.path),s=r.match(n);!1!==s&&(t={mapping:e,route:r,parsed:s})}return t})).filter((e=>null!=e));return o.sort(((e,t)=>Object.keys(e.parsed).length-Object.keys(t.parsed).length)),r=o&&o.length>0?o[0]:null,r||t.debug("Failed to find handler for %s (cleaned path was %s, strip prefixes were %j)",e.path,n,this.routerConfig.config.prefixesToStripBeforeRouteMatch),r}cleanPath(e){let t=e.path;for(;t.startsWith("/");)t=t.substring(1);for(this.routerConfig.config.prefixesToStripBeforeRouteMatch&&this.routerConfig.config.prefixesToStripBeforeRouteMatch.forEach((e=>{t.toLowerCase().startsWith(e.toLowerCase()+"/")&&(t=t.substring(e.length))}));t.startsWith("/");)t=t.substring(1);return t="/"+t,t}}class De{constructor(){}static epsilonConfigToEpsilonGlobalHandler(e,t){return new pe(De.epsilonConfigToEpsilonInstance(e,t))}static epsilonConfigToEpsilonInstance(e,r){this.validateGlobalConfig(e);const n=e?.label||"NO EPSILON CONFIG LABEL SET";t.info("Creating epsilon : %s : BM : %j",n,r);const s=De.parseOpenApiDocument(e.openApiYamlString),o=De.openApiDocToValidator(s),a=new Ne(e.backgroundConfig,o,r),i=e.backgroundConfig?new Oe(e.backgroundConfig,r,o):null,c=e.httpConfig?Fe.openApiYamlToRouterConfig(e.httpConfig,s,o,a):null;return{config:e,parsedOpenApiDoc:s,modelValidator:o,webHandler:c?new xe(c):null,backgroundHandler:i,backgroundManager:r}}static parseOpenApiDocument(e){if(!e)throw new ye("Cannot configure, missing either yaml or cfg");return L.load(e)}static openApiDocToValidator(e){let t=null;return e?.components?.schemas&&(t=M.createFromParsedObject(e.components.schemas)),t}static validateGlobalConfig(e){e||c.throwFormattedErr("Config may not be null"),e.openApiYamlString||c.throwFormattedErr("Config must define an open api document"),e.cron&&!e.cron.timezone&&c.throwFormattedErr("Cron is defined, but timezone is not set")}}class He{get typeName(){return"EpsilonSampleInputValidated"}async handleEvent(e,r){t.info("Running SampleInputValidatedProcessor, data was : %j",e)}get dataSchemaName(){return"BackgroundSampleInputValidatedProcessorData"}}class je{static async simpleNoAuthenticationLogAccess(e,r){return t.debug("Auth requested for %s : %j",r.path,e?.auth),!0}static async simpleLoggedInAuth(e,r){const n=!!e?.auth;return t.silly("SimpleLoggedInAuth returning %s for %s",n,r.path),n}static async simpleRoleRouteAuth(e,r,n,s=null,o=null){let a=!0;const i=e?.auth;return i?(s&&(s.forEach((e=>{a=a||i.roles.indexOf(e)>-1})),a||t.warn("Request to %s failed to find at least one of %j",n.path,s)),a&&o&&(o.forEach((e=>{a=a&&i.roles.indexOf(e)>-1})),a||t.warn("Request to %s failed to find all of %j",n.path,o))):(t.warn("Cannot authenticate - no parsed auth found"),a=!1),a}}class qe{constructor(){}static async emptyContext(){return{}}static async defaultEpsilonApolloContext(r,n){const s=J.extractBearerTokenFromEvent(r.lambdaEvent);let o=null;e.trimToNull(s)&&n&&(t.info("Got : %s",s),o=await n.decodeToken(s,0));return{user:o,bearerTokenString:s,headers:r.lambdaEvent.headers,functionName:r.lambdaContext.functionName,lambdaEvent:r.lambdaEvent,lambdaContext:r.lambdaContext}}static async nonRouteableOnlyEpsilonApolloContext(t,r){const n=e.trimToNull(s.extractValueFromMapIgnoreCase(t.lambdaEvent.headers,"host"));if(!J.hostIsLocalOrNotRoutableIP4(n))throw new Y("May only run local / non-routeable : "+n);return qe.defaultEpsilonApolloContext(t,r)}}const Ge={None:"None",All:"All",Reflective:"Reflective"};class Ue{static async handlePathWithApollo(e,t,r,n){let s=!1;if(e.event?.path&&t&&t.test(e.event.path)){if(e.result=await Ue.processApolloRequest(e.event,e.context,r,n),n?.corsMethod)switch(n.corsMethod){case Ge.All:await Le.addAllowEverythingCORSHeaders(e);break;case Ge.Reflective:await Le.addAllowReflectionCORSHeaders(e)}}else s=!0;return s}static async processApolloRequest(r,s,a,i){t.silly("Processing event with apollo: %j",r);let c=null;u.notNullOrUndefined(a,"apolloServer"),a.assertStarted("Cannot process with apollo - instance not started");const l=new P;for(const e in r.headers)l.set(e,r.headers[e]);const d=e.trimToEmpty(r.httpMethod).toUpperCase();let p=null;if(e.trimToNull(r.body)){const e=r.isBase64Encoded?o.base64StringToString(r.body):r.body;p=JSON.parse(e)}const m={method:d,headers:l,search:"GET"===d&&r?.queryStringParameters?Object.keys(r.queryStringParameters).map((e=>encodeURIComponent(e)+"="+encodeURIComponent(r.queryStringParameters[e]))).join("&"):null,body:p},f=i?.timeoutMS??s.getRemainingTimeInMillis()-500,E=i?.context??qe.emptyContext,y=a.executeHTTPGraphQLRequest({httpGraphQLRequest:m,context:()=>E({lambdaContext:s,lambdaEvent:r})});let w=null;if(f?w=await h.timeout(y,"Apollo timed out after "+f+" ms.",f):(t.warn("No timeout set even after defaulting for Apollo"),w=await y),g.isTimeoutToken(w))throw w.writeToLog(),new Z("Timed out");const S=w,T={};for(const[e,t]of S.headers.entries())T[e]=t;if("chunked"===S.body.kind)throw new n("Apollo returned chunked result").withHttpStatusCode(500).withRequestId($.currentRequestId());const A=e.trimToEmpty(S?.body?.string);return c={body:o.generateBase64VersionOfString(A),headers:T,multiValueHeaders:{},isBase64Encoded:!0,statusCode:S.status||200},"GET"===d&&"text/html"!==c.headers["content-type"]&&A.indexOf("<!DOCTYPE html>")>=0&&(t.info("Forcing content type to html for the sandbox page"),c.headers=c.headers||{},c.headers["content-type"]="text/html"),i.debugOutputCallback&&await i.debugOutputCallback(c),c}static addApolloFilterToList(e,t,r,n){e&&e.push((e=>Ue.handlePathWithApollo(e,t,r,n)))}}class Ve{async handleError(e,r){t.error("-------- ERROR PROCESSED : %j : %s----",e,r)}}class Qe extends Ie{_localBus=new F;get backgroundManagerName(){return"SingleThreadLocalBackgroundManager"}constructor(){super()}immediateProcessQueue(){return this._localBus}async addEntryToQueue(e,r){const n=await this.wrapEntryForInternal(e),s=n.guid;return t.info("Add entry to queue (local) : %j : Start : %s",e,r),this._localBus.next(n),s}async fireImmediateProcessRequest(e){let r=null;const n=await this.wrapEntryForInternal(e);return r=n.guid,t.info("Fire immediately (local) : %j ",e),this._localBus.next(n),r}async fireStartProcessingRequest(){let e=null;return t.info("Fire start processing request (local, ignored)"),e="NO-OP","NO-OP"}async fetchApproximateNumberOfQueueEntries(){let e=null;return e=0,0}async takeEntryFromBackgroundQueue(){return t.info("Called takeEntryFromBackgroundQueue on SingleThreadedLocal - returning empty"),[]}}class ze{constructor(){}static SAMPLE_OPEN_API_DOC="openapi: 3.0.0\ninfo:\n version: v0\n title: SampleAPI\ntags:\n - name: CORS\n description: These endpoints are here to support CORS\n - name: Public\n description: These endpoints can be called without setting the authorization header\n - name: Secure\n description: Authentication and authorization of the API\npaths:\n /:\n get:\n description: Redirects to the /meta/server endpoint\n tags:\n - Meta\n - Public\n responses:\n '301':\n description: Redirects to the /meta/server endpoint\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Standard CORS header response\n /event:\n get:\n description: Tests URL parsing and returns event as JSON\n tags:\n - Meta\n - Public\n responses:\n '200':\n description: The parsed event, as JSON\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Standard CORS header response\n /meta/server:\n get:\n description: >\n Returns information about the current build and time. Can be used to\n test error-handling code by passing a specific http error code in the\n error query parameter. Can also be used to process specific named tests\n by passing those names to the test parameter.\n tags:\n - Public\n parameters:\n - name: error\n in: query\n description: >-\n If set, throw a specific error for testing (valid are\n 500,400,403,404)\n required: false\n schema:\n type: number\n - name: test\n in: query\n description: Run a specific named test (currently none are publicly available)\n required: false\n schema:\n type: string\n responses:\n '200':\n description: Success\n '400':\n description: Simulated bad request\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n '403':\n description: Simulated unauthorized\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n '404':\n description: Simulated not found\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n '500':\n description: Simulated internal server error\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Standard CORS header response\n /meta/user:\n get:\n description: >\n When logged in, returns the contents of the JWT token as the server\n parses it. This should match what you get when you process the token\n returned from the \"POST /access-token\" endpoint through a standard JWT\n token processor.\n tags:\n - Meta\n security:\n - SampleAuthorizer: []\n responses:\n '200':\n description: Success\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/AccessTokenContents'\n '401':\n description: Unauthorized\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Success\n '401':\n description: Unauthorized\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n /meta/item/{itemId}:\n get:\n description: >\n Example of a path param\n parameters:\n - name: itemId\n in: path\n description: A sample item id\n required: true\n schema:\n type: string\n tags:\n - Meta\n responses:\n '200':\n description: Success\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/Empty'\n '401':\n description: Unauthorized\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n options:\n tags:\n - CORS\n parameters:\n - name: itemId\n in: path\n description: A sample item id\n required: true\n schema:\n type: string\n responses:\n '200':\n description: Success\n '401':\n description: Unauthorized\n content:\n '*/*':\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n\n /meta/sample-item:\n get:\n description: >\n Example of an object returned\n parameters:\n - name: num\n in: path\n description: Number to return in the number value\n required: false\n schema:\n type: number\n tags:\n - Meta\n responses:\n '200':\n description: Success\n content:\n 'application/json':\n schema:\n $ref: '#/components/schemas/BackgroundSampleInputValidatedProcessorData'\n post:\n description: >\n Example of an object posted\n requestBody:\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/BackgroundSampleInputValidatedProcessorData'\n description: Request to refresh the access token or change active user\n required: true\n tags:\n - Meta\n responses:\n '200':\n description: Success\n content:\n 'application/json':\n schema:\n $ref: '#/components/schemas/BackgroundSampleInputValidatedProcessorData'\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Success\n\n /secure/access-token:\n post:\n tags:\n - Secure\n - Public\n responses:\n '200':\n description: Success\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/AccessTokenResponse'\n '400':\n description: Invalid request\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n '403':\n description: Invalid credentials\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n requestBody:\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/AccessTokenRequest'\n description: Request to refresh the access token or change active user\n required: true\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Standard CORS header response\n /multi/fixed:\n get:\n description: Tests path matching from most specific to least (this is most)\n tags:\n - Public\n responses:\n '200':\n description: Success\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Standard CORS header response\n /multi/{v}:\n get:\n description: Tests path matching from most specific to least (this is least)\n tags:\n - Public\n parameters:\n - name: v\n in: path\n description: A variable\n required: true\n schema:\n type: string\n responses:\n '200':\n description: Success\n options:\n tags:\n - CORS\n parameters:\n - name: v\n in: path\n description: A variable\n required: true\n schema:\n type: string\n responses:\n '200':\n description: Standard CORS header response\n\n /err/{code}:\n get:\n description: Tests path matching from most specific to least (this is least)\n tags:\n - Public\n parameters:\n - name: code\n in: path\n description: Error code\n required: true\n schema:\n type: number\n responses:\n '200':\n description: Success\n options:\n tags:\n - CORS\n parameters:\n - name: code\n in: path\n description: A variable\n required: true\n schema:\n type: number\n responses:\n '200':\n description: Standard CORS header response\n\n /background:\n post:\n responses:\n '200':\n description: Success\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/BackgroundQueueResponse'\n '400':\n description: Invalid request\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n '403':\n description: Invalid credentials\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n requestBody:\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/Empty'\n description: Content to echo\n required: true\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Standard CORS header response\n\n /background/meta:\n get:\n responses:\n '200':\n description: Success\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/BackgroundMetaResponse'\n '400':\n description: Invalid request\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n '403':\n description: Invalid credentials\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/ApiErrorResponse'\n options:\n tags:\n - CORS\n responses:\n '200':\n description: Standard CORS header response\n\nx-amazon-apigateway-binary-media-types:\n - '*/*'\nx-amazon-apigateway-gateway-responses:\n UNAUTHORIZED:\n statusCode: 401\n responseParameters:\n gatewayresponse.header.Access-Control-Allow-Origin: \"'*'\"\n responseTemplates:\n application/json: '{\"errors\":[\"Unauthorized\"], \"httpStatusCode\": 401}'\n MISSING_AUTHENTICATION_TOKEN:\n statusCode: 404\n responseParameters:\n gatewayresponse.header.Access-Control-Allow-Origin: \"'*'\"\n responseTemplates:\n application/json: '{\"errors\":[\"No such endpoint\"], \"httpStatusCode\": 404}'\n INTEGRATION_TIMEOUT:\n statusCode: 504\n responseParameters:\n gatewayresponse.header.Access-Control-Allow-Origin: \"'*'\"\n responseTemplates:\n application/json: '{\"errors\":[\"Timeout\"], \"httpStatusCode\": 504}'\n DEFAULT_5XX:\n statusCode: 500\n responseParameters:\n gatewayresponse.header.Access-Control-Allow-Origin: \"'*'\"\n responseTemplates:\n application/json: '{\"errors\":[\"Internal Server Error\"], \"httpStatusCode\": 500}'\n\nservers:\n - url: 'https://api.sample.com/dev'\ncomponents:\n securitySchemes:\n SampleAuthorizer:\n type: apiKey\n name: Authorization\n in: header\n schemas:\n Empty:\n type: object\n title: Empty Schema\n\n AccessTokenRequest:\n type: object\n title: Access Token Request\n required:\n - email\n - password\n - scope\n properties:\n email:\n type: string\n description: Email address of the account to authenticate\n format: email\n minLength: 7\n password:\n type: string\n description: Password of the account to authenticate\n minLength: 6\n scope:\n type: string\n enum:\n - OWNER\n - ADVERTISER\n - GLOBAL\n - RUN_AS_OWNER\n - RUN_AS_ADVERTISER\n description: |\n What style of account to authenticate:\n * `OWNER` - A device owner account\n * `ADVERTISER` - A advertising account\n * `GLOBAL` - Used by Adomni customer service\n * `RUN_AS_OWNER` - Used by Adomni customer service\n * `RUN_AS_ADVERTISER` - Used by Adomni customer service\n default: OWNER\n runAs:\n type: string\n description: Used by Adomni customer service\n format: email\n expirationSeconds:\n type: number\n minimum: 10\n maximum: 3600\n default: 3600\n AccessTokenResponse:\n type: object\n title: Access Token Response\n required:\n - token\n - expires\n properties:\n token:\n type: string\n description: A JWT access token for the API\n expires:\n type: number\n format: int64\n description: 'The time this token will expire, expressed in epoch ms'\n AccessTokenContents:\n type: object\n title: Access Token Contents\n description: The contents of the JWT token\n required:\n - exp\n - iss\n - sub\n - iat\n - user\n properties:\n exp:\n type: number\n description: >-\n Expiration claim - The time this token will expire, expressed in\n epoch ms\n iss:\n type: string\n description: Issuer claim - Who created the token\n sub:\n type: string\n description: Subject claim - The target of the token (typically user email)\n iat:\n type: number\n description: >-\n Issued at claim - The time this token was created, expressed in\n epoch ms\n user:\n type: object\n description: Object describing the user authenticated by this token\n ApiErrorResponse:\n type: object\n title: API Error Response\n required:\n - errors\n - httpStatusCode\n properties:\n errors:\n type: array\n items:\n type: string\n description: List of the errors that occurred\n httpStatusCode:\n type: number\n description: Http status code of this error\n detailCode:\n type: number\n description: Adomni detail status code for this error\n BackgroundQueueResponse:\n type: object\n title: Background Queue Response\n description: When any of the background endpoints are hit, this is what will be returned\n required:\n - resultId\n - success\n properties:\n processHandling:\n type: string\n enum: ['Queued', 'Immediate']\n success:\n type: boolean\n resultId:\n type: string\n BackgroundMetaResponse:\n type: object\n title: Background Meta Response\n description: If\n properties:\n validTypes:\n type: array\n items:\n type: string\n currentQueueLength:\n type: number\n\n BackgroundSampleInputValidatedProcessorData:\n type: object\n title: BackgroundSampleInputValidatedProcessorData\n description: This is used for testing the background validator\n required:\n - nameParam\n - numberParam\n properties:\n nameParam:\n type: string\n description: A sample name parameter\n minimum: 0\n maximum: 10\n numberParam:\n type: number\n description: A sample number parameter\n";static SAMPLE_SERVER_GRAPHQL="schema {\n query: RootQueryType\n}\n\ntype RootQueryType {\n serverMeta: ServerMeta\n forceTimeout: ForceTimeout\n}\n\ntype ServerMeta {\n version: String\n serverTime: String\n status: String\n}\n\ntype ForceTimeout {\n placeholder: String\n}\n"}class We{constructor(){}static async createSampleApollo(){const e=ze.SAMPLE_SERVER_GRAPHQL;t.silly("Creating apollo from : %s",e);const r=O(e),n=new I({introspection:!0,typeDefs:r,resolvers:{RootQueryType:{serverMeta:async e=>({version:"A1",serverTime:(new Date).toISOString()}),forceTimeout:async e=>(await h.wait(18e5),{placeholder:"A1"})}},plugins:[_({footer:!1})]});return await n.start(),n}static async createSampleEpsilonConfig(t){const r=ze.SAMPLE_OPEN_API_DOC,n=new Map;n.set("SampleAuthorizer",((e,t)=>je.simpleLoggedInAuth(e,t))),n.set("LogAuthorizer",((e,t)=>je.simpleNoAuthenticationLogAccess(e,t)));const s=new Map;s.set("get /",((e,t)=>we.sample(e,null,t))),s.set("get /meta/server",(e=>we.sample(e))),s.set("get /meta/user",(e=>we.sample(e))),s.set("get /meta/item/{itemId}",(e=>we.sample(e))),s.set("post /secure/access-token",(e=>we.sample(e))),s.set("get /multi/fixed",(e=>we.sample(e,"fixed"))),s.set("get /multi/{v}",(e=>we.sample(e,"variable"))),s.set("get /event",(e=>Promise.resolve({statusCode:200,headers:{"Content-Type":"application/json"},body:JSON.stringify(e,null,2)}))),s.set("get /err/{code}",(e=>{const t=c.fErr("Fake Err : %j",e);throw t.statusCode=l.safeNumber(e.pathParameters.code),t})),s.set("get /meta/sample-item",(async e=>({numberParam:l.safeNumber(e.queryStringParameters.num)||5,nameParam:"Test-String"}))),s.set("post /meta/sample-item",(async t=>{const r=t.parsedBody;return!0===E.parseBool(e.trimToNull(t.queryStringParameters.forceFail))&&(r.numberParam="test"),r}));const o=new Se(["abcd1234"],"sample.erigir.com").withParseFailureLogLevel(i.debug).withExtraDecryptionKeys(["abcdefabcdef"]).withOldKeyUseLogLevel(i.info),a=Fe.defaultHttpMetaProcessingConfigWithAuthenticationHeaderParsing(o);a.timeoutMS=1e4,Ue.addApolloFilterToList(a.preFilters,new RegExp(".*graphql.*"),await We.createSampleApollo(),{context:e=>qe.defaultEpsilonApolloContext(e,o.jwtRatchet),timeoutMS:5e3,corsMethod:Ge.All}),a.errorFilters.push((e=>Le.secureOutboundServerErrorForProduction(e,"Clean Internal Server Error",500)));const u=Object.assign({},a);u.preFilters=Object.assign([],u.preFilters),u.preFilters.splice(8,1);return{label:t,openApiYamlString:r,httpConfig:{defaultMetaHandling:a,handlers:s,authorizers:n,overrideMetaHandling:[{pathRegex:"/background",methods:null,config:Object.assign({},a,{overrideAuthorizerName:"LogAuthorizer"})},{pathRegex:"/meta/server",methods:["GET"],config:u}],prefixesToStripBeforeRouteMatch:["v0"],filterHandledRouteMatches:["options .*"]},backgroundConfig:{httpMetaEndpoint:"/background/meta",httpSubmissionPath:"/background",implyTypeFromPathSuffix:!1,processors:[new Te,new Ae,new Re,new He,new be],errorProcessor:new Ve}}}static async createSampleEpsilonGlobalHandler(e){const t=await We.createSampleEpsilonConfig(e),r=new Qe,n=De.epsilonConfigToEpsilonInstance(t,r);return new pe(n)}static async createSampleBatchOnlyEpsilonGlobalHandler(e){const t=await We.createSampleEpsilonConfig(e);t.httpConfig.handlers=new Map;const r=Object.assign({},t.httpConfig.defaultMetaHandling);r.preFilters=r.preFilters.concat([e=>Le.autoRespond(e,{message:"Background Processing Only"})]),t.httpConfig.overrideMetaHandling=[{pathRegex:".*background.*",invertPathMatching:!0,config:r}],t.httpConfig.filterHandledRouteMatches=[".*"];const n=new Qe,s=De.epsilonConfigToEpsilonInstance(t,n);return new pe(s)}}class Ye{globalHandler;port;https;server;constructor(e,t=8888,r=!1){this.globalHandler=e,this.port=t,this.https=r}async runServer(){return new Promise(((e,r)=>{try{if(t.info("Starting Epsilon server on port %d",this.port),this.https){const e={key:ge.CLIENT_KEY_PEM,cert:ge.CLIENT_CERT_PEM};t.info("Starting https server - THIS SERVER IS NOT SECURE! The KEYS are in the code! Testing Server Only - Use at your own risk!"),this.server=v.createServer(e,this.requestHandler.bind(this)).listen(this.port)}else this.server=C.createServer(this.requestHandler.bind(this)).listen(this.port);t.info("Epsilon server is listening"),process.on("SIGINT",(()=>{t.info("Caught SIGINT - shutting down test server..."),this.server.close(),e(!0)}))}catch(e){t.error("Local server failed : %s",e,e),r(e)}}))}async requestHandler(t,r){const n={awsRequestId:"LOCAL-"+e.createType4Guid(),getRemainingTimeInMillis:()=>3e5},s=await Ye.messageToApiGatewayEvent(t,n),o=J.eventIsAGraphQLIntrospection(s)?i.silly:i.info;if("/epsilon-poison-pill"==s.path)return this.server.close(),!0;{const e=await this.globalHandler.lambdaHandler(s,n);return await Ye.writeProxyResultToServerResponse(e,r,o)}}static async bodyAsBase64String(e){return new Promise(((t,r)=>{const n=[];e.on("data",(e=>{n.push(e)})),e.on("end",(()=>{const e=Buffer.concat(n).toString("base64");t(e)}))}))}static async messageToApiGatewayEvent(e,t){const r=await Ye.bodyAsBase64String(e),n=e.url.indexOf("/",1),s=e.url.substring(1,n),o=e.url.substring(n+1),a=(new Date).getTime(),i=R.utc().toFormat("dd/MMM/yyyy:hh:mm:ss ZZ"),c=Ye.parseQueryParamsFromUrlString(o),l=Object.assign({},e.headers);l["X-Forwarded-Proto"]="http";return{body:r,multiValueHeaders:{},multiValueQueryStringParameters:{},resource:"/{proxy+}",path:e.url,httpMethod:e.method.toLowerCase(),isBase64Encoded:!0,queryStringParameters:c,pathParameters:{proxy:o},stageVariables:{baz:"qux"},headers:l,requestContext:{accountId:"123456789012",resourceId:"123456",stage:s,requestId:t.awsRequestId,requestTime:i,requestTimeEpoch:a,identity:{apiKeyId:null,clientCert:null,principalOrgId:null,apiKey:null,cognitoIdentityPoolId:null,accountId:null,cognitoIdentityId:null,caller:null,accessKey:null,sourceIp:"127.0.0.1",cognitoAuthenticationType:null,cognitoAuthenticationProvider:null,userArn:null,userAgent:"Custom User Agent String",user:null},path:e.url,domainName:e.headers.host,resourcePath:"/{proxy+}",httpMethod:e.method.toLowerCase(),apiId:"1234567890",protocol:"HTTP/1.1",authorizer:null}}}static async writeProxyResultToServerResponse(e,r,n){if(t.levelIsEnabled(n))if(e.isBase64Encoded){const r=structuredClone(e);r.body=o.base64StringToString(r.body),r.isBase64Encoded=!1,t.logByLevel(n,"Result (UB64): %j",r)}else t.logByLevel(n,"Result: %j",e);r.statusCode=e.statusCode,e.headers&&Object.keys(e.headers).forEach((t=>{r.setHeader(t,String(e.headers[t]))})),e.multiValueHeaders&&Object.keys(e.multiValueHeaders).forEach((t=>{r.setHeader(t,e.multiValueHeaders[t].join(","))}));const s=e.isBase64Encoded?Buffer.from(e.body,"base64"):Buffer.from(e.body);return r.end(s),!!e.body}static parseQueryParamsFromUrlString(e){const t={},r=e.split("?");if(r.length<2)return t;const n=r.slice(1).join("?").split("&");for(const e of n){const r=e.split("="),n=r[0],s=r.slice(1).join("=");t[n]=s}return t}static async runSampleBatchOnlyServerFromCliArgs(e){t.setLevel(i.debug);const r=await We.createSampleBatchOnlyEpsilonGlobalHandler("SampleBatchOnlyLocalServer-"+Date.now()),n=new Ye(r),s=await n.runServer();t.info("Res was : %s",s)}static async runSampleLocalServerFromCliArgs(e){t.setLevel(i.debug);const r=new Se(["abcd1234"],"sample-server"),n=await r.createJWTStringAsync("asdf",{},["USER"],3600);t.info("Use token: %s",n);const s=await We.createSampleEpsilonGlobalHandler("SampleLocalServer-"+Date.now()),o=new Ye(s,8888,!0),a=await o.runServer();t.info("Res was : %s",a)}}class Ke{port;containerUrl;server;aborted=!1;constructor(e=8889,t="http://localhost:9000/2015-03-31/functions/function/invocations"){this.port=e,this.containerUrl=t}async runServer(){return new Promise(((e,r)=>{try{t.info("Starting Epsilon container-wrapper server on port %d calling to %s",this.port,this.containerUrl),this.server=C.createServer(this.requestHandler.bind(this)).listen(this.port),t.info("Epsilon server is listening"),process.on("SIGINT",(()=>{t.info("Caught SIGINT - shutting down test server..."),this.aborted=!0,e(!0)}))}catch(e){t.error("Local server failed : %s",e,e),r(e)}}))}async requestHandler(r,n){const s={awsRequestId:"LOCAL-"+e.createType4Guid(),getRemainingTimeInMillis:()=>3e5},o=await Ye.messageToApiGatewayEvent(r,s),a=J.eventIsAGraphQLIntrospection(o)?i.silly:i.info;t.logByLevel(a,"Processing event: %j",o);if("/epsilon-poison-pill"==o.path)return this.aborted=!0,!0;try{const e=await N(this.containerUrl,{method:"POST",body:JSON.stringify(o)});n.statusCode=e.status,e.headers.forEach(((e,t)=>{n.setHeader(t,e)}));const t=await e.arrayBuffer();return n.end(new Uint8Array(t)),!0}catch(e){return t.error("Failed: %s : Body was %s Response was : %j",e,null,undefined,e),'{"bad":true}'}}static async runFromCliArgs(e){try{t.setLevel(i.debug),t.debug("Running local container server : %j",process?.argv);B.argsAfterCommand(["run-local-container-server"]);const e=new Ke;await e.runServer(),t.info("Got res server"),process.exit(0)}catch(e){t.error("Error : %s",e),process.exit(1)}}}class Je{dynamo;tableName;env;backgroundQueueName;constructor(e,t,r,n){this.dynamo=e,this.tableName=t,this.env=r,this.backgroundQueueName=n}async onEvent(e){const t={env:this.env,backgroundQueueName:this.backgroundQueueName,requestId:$.currentRequestId(),guid:e.guid,processTypeName:e.processorType,state:e.type.toString(),timestampEpochMs:(new Date).getTime()};if(e.type==Pe.DataValidationError){const r=e?.errors?.length?e.errors:["No-Error"];t.errors=r}else if(e.type==Pe.ProcessStarting)t.params=e.data;else if(e.type==Pe.ExecutionFailedError){const r=e?.errors?.length?e.errors:["No-Error"];t.errors=r}await this.dynamo.simplePut(this.tableName,t)}}class Xe extends Error{static EPSILON_BACKGROUND_PROCESS_ERROR_FLAG_KEY="__epsilonBackgroundProcessErrorFlag";_errors;_detailErrorCode;_details;_requestId;_wrappedError;constructor(...e){super(Xe.combineErrorStringsWithDefault(e)),Object.setPrototypeOf(this,Xe.prototype),this._errors=e,this[Xe.EPSILON_BACKGROUND_PROCESS_ERROR_FLAG_KEY]=!0}static combineErrorStringsWithDefault(e,t="Internal Server Error"){return e&&e.length>0?e.join(","):t}setFormattedErrorMessage(e,...t){const r=D.format(e,...t);this.errors=[r]}withFormattedErrorMessage(e,...t){return this.setFormattedErrorMessage(e,...t),this}withErrors(e){return this.errors=e,this}withDetailErrorCode(e){return this._detailErrorCode=e,this}withDetails(e){return this._details=e,this}withRequestId(e){return this._requestId=e,this}withWrappedError(e){return this._wrappedError=e,this}isWrappedError(){return!!this._wrappedError}static wrapError(e){let t=null;return t=Xe.objectIsEpsilonBackgroundProcessError(e)?e:new Xe(e.message).withWrappedError(e),t}static objectIsEpsilonBackgroundProcessError(e){return e&&!0===e[Xe.EPSILON_BACKGROUND_PROCESS_ERROR_FLAG_KEY]}set errors(e){this._errors=e||["Internal Server Error"],this.message=Xe.combineErrorStringsWithDefault(this._errors)}get errors(){return this._errors}set detailErrorCode(e){this._detailErrorCode=e}get detailErrorCode(){return this._detailErrorCode}set details(e){this._details=e}get details(){return this._details}set requestId(e){this._requestId=e||"MISSING"}get requestId(){return this._requestId}set wrappedError(e){this._wrappedError=e}get wrappedError(){return this._wrappedError}}class Ze{cfg;s3TransactionLogCacheRatchet;constructor(e){this.cfg=e;const t=Ze.validateConfig(e);t.length&&c.throwFormattedErr("Invalid S3BackgroundTransactionLogger config : %j",t),this.s3TransactionLogCacheRatchet=new A(this.cfg.s3,this.cfg.bucket)}async logTransaction(e){e?e.request?.guid?await this.s3TransactionLogCacheRatchet.writeObjectToCacheFile(Ie.backgroundGuidToPath(this.cfg.prefix,e.request.guid),e):t.warn("Could not write transaction record - no guid defined : %j",e):t.silly("Skipping write of null log")}async readTransactionLog(e){const t=Ie.backgroundGuidToPath(this.cfg.prefix,e);return await this.s3TransactionLogCacheRatchet.fetchCacheFileAsObject(t)}static validateConfig(e){const t=[];return e?(e.s3||t.push("You must supply an S3 object"),e.bucket||t.push("You must supply a bucket"),e.timeToLiveDays||t.push("You must supply a timeToLiveDays")):t.push("No config defined"),t}}class $e extends Ie{_awsConfig;_sqs;_sns;constructor(e,t,r){super(),this._awsConfig=e,this._sqs=t,this._sns=r;const n=ve.validateAwsConfig(e);n.length&&c.throwFormattedErr("Cannot start - invalid AWS config : %j",n)}get backgroundManagerName(){return"AwsSqsSnsBackgroundManager"}get awsConfig(){return this._awsConfig}get sqs(){return this._sqs}get sns(){return this._sns}async addEntryToQueue(e,r){try{const n=await this.wrapEntryForInternal(e),s=n.guid,o={DelaySeconds:0,MessageBody:JSON.stringify(n),MessageGroupId:e.type,QueueUrl:this.awsConfig.queueUrl};t.info("Add entry to queue (remote) : %j : Start : %s",o,r);const a=await this.sqs.send(new H(o));if(r){const e=await this.fireStartProcessingRequest();t.silly("FireResult : %s",e)}return t.info("Background process %s using message id %s",s,a.MessageId),s}catch(e){throw t.error("Error inserting background entry into SQS queue : %j",e),new Error("Error inserting background entry into SQS queue : "+e.code+" : "+e.name)}}async fireImmediateProcessRequest(e){try{const r=await this.wrapEntryForInternal(e),n=r.guid;t.info("Fire immediately (remote) : %j ",e);const s={type:W.BACKGROUND_SNS_IMMEDIATE_RUN_FLAG,backgroundEntry:r},o=JSON.stringify(s),a=await this.writeMessageToSnsTopic(o);return t.debug("Background guid %s Wrote message : %s to SNS : %s",n,o,a),n}catch(e){throw t.error("Failed to fireImmediateProcessRequest : %s",e,e),new Error("Failed to fireImmediateProcessRequest : : "+e.code+" : "+e.name)}}async fireStartProcessingRequest(){let e=null;try{t.info("Fire start processing request (remote)"),e=await this.writeMessageToSnsTopic(W.BACKGROUND_SNS_START_MARKER)}catch(e){t.error("Failed to fireStartProcessingRequest : %s",e,e)}return e}async fetchApproximateNumberOfQueueEntries(){let e=null;const t=await this.fetchCurrentQueueAttributes();return e=l.safeNumber(t.Attributes.ApproximateNumberOfMessages),e}async fetchCurrentQueueAttributes(){let e=null;const t={AttributeNames:["All"],QueueUrl:this.awsConfig.queueUrl};return e=await this.sqs.send(new j(t)),e}async writeMessageToSnsTopic(e){let r=null;const n={Message:e,TopicArn:this.awsConfig.notificationArn};t.debug("Writing message to SNS topic : j",n);return r=(await this.sns.send(new b(n))).MessageId,r}async takeEntryFromBackgroundQueue(){const e=[],r={MaxNumberOfMessages:1,QueueUrl:this.awsConfig.queueUrl,VisibilityTimeout:300,WaitTimeSeconds:0},n=await this.sqs.send(new q(r));if(n&&n.Messages&&n.Messages.length>0)for(let r=0;r<n.Messages.length;r++){const s=n.Messages[r];try{const r=JSON.parse(s.Body);r.type?e.push(r):t.warn("Dropping invalid background entry : %j",r),t.debug("Removing message from queue");const n={QueueUrl:this.awsConfig.queueUrl,ReceiptHandle:s.ReceiptHandle},o=await this.sqs.send(new G(n));t.silly("Delete result : %j",o)}catch(e){t.warn("Error parsing message, dropping : %j",s)}}else t.debug("No messages found (likely end of recursion)");return e}}class et extends $e{_s3;pathPrefix;static LARGE_MESSAGE_SIZE_THRESHOLD=25e4;static LARGE_MESSAGE_S3_PATH_META_KEY="S3_STORAGE_KEY";constructor(t,r,n,s,o=""){super(t,r,n),this._s3=s,this.pathPrefix=o,s||c.throwFormattedErr("Cannot start - no s3Client provided"),e.trimToNull(s.getDefaultBucket())||c.throwFormattedErr("Cannot start - no default bucket provided"),!o&&o.endsWith("/")&&c.throwFormattedErr("Path prefix may not end with /")}get backgroundManagerName(){return"AwsLargePayloadS3SqsSnsBackgroundManager"}get s3(){return this._s3}async wrapEntryForInternal(e,r,n){const s=await super.wrapEntryForInternal(e,r,n);if(Buffer.byteLength(JSON.stringify(s),"utf-8")>et.LARGE_MESSAGE_SIZE_THRESHOLD){t.info("Message payload is above LARGE_MESSAGE_SIZE_THRESHOLD. Uploading to s3."),s.meta=s.meta||{};const e=await this.writeMessageToS3(s.guid,s.data);s.meta[et.LARGE_MESSAGE_S3_PATH_META_KEY]=e,s.data=void 0}return s}async writeMessageToS3(t,r){let n=e.trimToNull(this.pathPrefix)?this.pathPrefix+"/":"";return n+=t+".json",await this.s3.writeObjectToCacheFile(n,r),n}async modify(e){if(e?.meta?.[et.LARGE_MESSAGE_S3_PATH_META_KEY]){t.silly("Restoring large data from %s",e.meta[et.LARGE_MESSAGE_S3_PATH_META_KEY]);const r=await this._s3.fetchCacheFileAsObject(e.meta[et.LARGE_MESSAGE_S3_PATH_META_KEY]);e.data=r,delete e.meta[et.LARGE_MESSAGE_S3_PATH_META_KEY]}return e}}class tt{constructor(){}static buildInformation(){return{version:"415",hash:"43b8898fca427e6952399e7dfd5c58cf8e8177c0",branch:"alpha-2024-07-12-1",tag:"alpha-2024-07-12-1",timeBuiltISO:"2024-07-12T16:42:20-0700",notes:"No notes"}}}class rt{static fullAwsRequestId(){return $.defaultedCurrentRequestId()}static shortAwsRequestId(){let e=rt.fullAwsRequestId();if(e.length>10){let t=e.lastIndexOf("-");t=-1===t?e.length-10:t,e=e.substring(t)}return e}static fixedLengthHex(t=10){return e.createRandomHexString(t)}}class nt{delegate;opts;static RETRY_FIELD_NAME="___RetryProcessorTryNumber";constructor(e,t){this.delegate=e,this.opts=t}get typeName(){return e.trimToEmpty(this.opts?.typePrefix)+this.delegate.typeName+e.trimToEmpty(this.opts?.typeSuffix)}async handleEvent(e,r){const n=e&&e[nt.RETRY_FIELD_NAME]?l.safeNumber(e[nt.RETRY_FIELD_NAME]):1,s=e?Object.assign({},e):null;delete s[nt.RETRY_FIELD_NAME],t.info("RetryProcessor : %s : Try %d of %d",this.delegate.typeName,n,this.opts.retryCount);try{await this.delegate.handleEvent(s,r)}catch(e){if(t.error("Failed to process : %s",e,e),n<this.opts.retryCount){const e=n*this.opts.baseDelayMS;t.info("Firing automatic retry after a wait of %s",y.formatMsDuration(e)),await h.wait(e);const o=s||{};o[nt.RETRY_FIELD_NAME]=n+1,await r.fireImmediateProcessRequestByParts(this.typeName,o)}else t.error("That was the last try - giving up")}}}class st{daemon;inConfig;static ALLOW_EVERYTHING_AUTHORIZER=async(e,t)=>!0;config;constructor(t,r){this.daemon=t,this.inConfig=r,this.config=r||{},this.config.authorizer=this.config.authorizer||st.ALLOW_EVERYTHING_AUTHORIZER,this.config.groupSelector=this.config.groupSelector||(e=>Promise.resolve(t.defaultGroup)),this.config.fetchDaemonStatusByPublicTokenPathParameter=e.trimToNull(this.config.fetchDaemonStatusByPublicTokenPathParameter)||"publicToken",this.config.fetchDaemonStatusPathParameter=e.trimToNull(this.config.fetchDaemonStatusPathParameter)||"key"}async fetchDaemonStatusByPublicToken(e){const r=e.pathParameters[this.config.fetchDaemonStatusByPublicTokenPathParameter];t.info("Fetching daemon status for token: %s",r);let n=await this.daemon.statFromPublicToken(r);if(n=!!n&&await this.config.authorizer(e,n)?n:null,null===n)throw new me("No such token : "+r);return n}async fetchDaemonStatus(e){const r=e.pathParameters[this.config.fetchDaemonStatusPathParameter];t.info("Fetching daemon status for : %s",r);let n=await this.daemon.stat(r);if(n=!!n&&await this.config.authorizer(e,n)?n:null,null===n)throw new me("No such key : "+r);return n}async listDaemonStatus(e){const t=await this.config.groupSelector(e),r=await this.daemon.list(t),n=[];for(let t=0;t<r.length;t++){await this.config.authorizer(e,r[t])&&n.push(r[t])}return{results:n,nextToken:null}}}class ot{static async runFromCliArgs(e){if(e.length>1){const r=e[0],n=e.length>1&&E.parseBool(e[1]),s=e.length>2?JSON.parse(e[2]):null,o=e.length>3?JSON.parse(e[3]):null,a=null;n?t.info("Dry-Run, would have sent : %s %j %j",r,s,o):await a.processSingleBackgroundByParts(r,s,o)}else console.log("Usage : run-background-process {processName} {dryRun true/false} {dataJson} {metaJson}")}}class at{port;server;aborted=!1;constructor(e=9999){this.port=e}async runServer(){return t.info("Starting Test Error net server on port %d",this.port),new Promise(((e,r)=>{const n=new U.Server({});n.listen(this.port,(()=>{t.info("Server listening for connection requests on socket localhost: %s",this.port)})),n.on("connection",(async e=>{t.info("X: A new connection has been established."),e.write("Hello, client."),e.on("data",(e=>{t.info("Data received from client: %s",e)})),e.on("end",(()=>{t.info("Closing connection with the client")})),e.on("error",(e=>{t.info("Error: %s",e)}))}))}))}async requestHandler(e,r){t.info("Got request %d - closing socket",e),e.setTimeout(100),r.end("x")}static async runFromCliArgs(e){t.info("test-error-server requested (cli is %s) - starting",process?.argv);const r=new at;await r.runServer(),t.info("Got res server"),process.exit(0)}}class it extends x{fetchHandlerMap(){return{"run-background-process":ot.runFromCliArgs,"run-test-error-server":at.runFromCliArgs,"run-local-container-server":Ke.runFromCliArgs,"run-sample-local-server":Ye.runSampleLocalServerFromCliArgs,"run-sample-local-batch-server":Ye.runSampleLocalServerFromCliArgs}}fetchVersionInfo(){return tt.buildInformation()}}class ct{webTokenManipulator;constructor(e,t){this.webTokenManipulator=new Se([t],e)}lambdaHandler(e,r,n){t.info("Got event : %j",e);const s=ct.extractTokenStringFromAuthorizerEvent(e);if(s){const r=e.methodArn;this.webTokenManipulator.parseAndValidateJWTStringAsync(s).then((e=>{e?n(null,this.createPolicy(r,s,e)):(t.info("Invalid bearer token"),n(new Error("Unauthorized")))})).catch((e=>{t.error("Exception parsing token : %s",e),n(new Error("Unauthorized"))}))}else t.info("Token not supplied"),n(new Error("Unauthorized"))}createPolicy(e,t,r){const n=e.split(":"),s=n[5].split("/"),o=n[4],a=n[3],i=s[1];return{principalId:"user",policyDocument:{Version:"2012-10-17",Statement:[{Action:"execute-api:Invoke",Effect:"Allow",Resource:["arn:aws:execute-api:"+a+":"+o+":"+s[0]+"/"+i+"/*/*"]}]},context:{userJSON:JSON.stringify(r),srcData:t}}}static extractTokenStringFromAuthorizerEvent(e){t.silly("Extracting token from event : %j",e);let r=null;if(e&&e.authorizationToken){const t=e.authorizationToken;t&&t.startsWith(W.AUTH_HEADER_PREFIX)&&(r=t.substring(W.AUTH_HEADER_PREFIX.length))}return r}}class lt{clientId;jwksUri;issuer;jwksClient;constructor(e,t,r){this.clientId=e,this.jwksUri=t,this.issuer=r}async extractTokenFromAuthorizationHeader(t){let r=e.trimToEmpty(t);r.toLowerCase().startsWith("bearer ")&&(r=r.substring(7));return r?await this.parseAndValidateAuth0Token(r,!1):null}async parseAndValidateAuth0Token(r,n=!1){t.debug("Validating Auth0 token : %s",e.obscure(r,4));const s=w.decode(r,{complete:!0}),o=s?.header?.kid,a=Math.floor((new Date).getTime()/1e3),i=await this.fetchSigningKey(o);return w.verify(r,i,{audience:this.clientId,issuer:this.issuer,ignoreExpiration:n,clockTimestamp:a})}async fetchSigningKey(e){const t=await this.fetchJwksClient();return new Promise(((r,n)=>{t.getSigningKey(e,((e,t)=>{e?n(e):r(t.publicKey||t.rsaPublicKey)}))}))}async fetchJwksClient(){return this.jwksClient||(this.jwksClient=V({cache:!0,cacheMaxEntries:5,cacheMaxAge:36e6,jwksUri:this.jwksUri})),this.jwksClient}}class ut{clientId;static GOOGLE_DISCOVERY_DOCUMENT="https://accounts.google.com/.well-known/openid-configuration";cacheGoogleDiscoveryDocument;jwksClient;constructor(e){this.clientId=e}async extractTokenFromAuthorizationHeader(t){let r=e.trimToEmpty(t);r.toLowerCase().startsWith("bearer ")&&(r=r.substring(7));return r?await this.parseAndValidateGoogleToken(r,!1):null}async parseAndValidateGoogleToken(r,n=!1){t.debug("Auth : %s",e.obscure(r,4));const s=w.decode(r,{complete:!0}).header.kid,o=Math.floor((new Date).getTime()/1e3),a=await this.fetchSigningKey(s);return w.verify(r,a,{audience:this.clientId,issuer:["https://accounts.google.com","accounts.google.com"],ignoreExpiration:n,clockTimestamp:o})}async fetchSigningKey(e){const t=await this.fetchJwksClient();return new Promise(((r,n)=>{t.getSigningKey(e,((e,t)=>{e?n(e):r(t.publicKey||t.rsaPublicKey)}))}))}async fetchJwksClient(){if(!this.jwksClient){const e=await this.fetchGoogleDiscoveryDocument(),t=V({cache:!0,cacheMaxEntries:5,cacheMaxAge:36e6,jwksUri:e.jwks_uri});this.jwksClient=t}return this.jwksClient}async fetchGoogleDiscoveryDocument(){if(!this.cacheGoogleDiscoveryDocument){const e=await N(ut.GOOGLE_DISCOVERY_DOCUMENT),t=await e.json();this.cacheGoogleDiscoveryDocument=t}return this.cacheGoogleDiscoveryDocument}}class dt{_jwtRatchet;_issuer;constructor(t,r){this._jwtRatchet=t,this._issuer=r,u.notNullOrUndefined(t,"_jwtRatchet"),u.notNullOrUndefined(e.trimToNull(r),"_issuer")}get jwtRatchet(){return this._jwtRatchet}get issuer(){return this._issuer}async extractTokenFromAuthorizationHeader(t){let r=e.trimToEmpty(t);r.toLowerCase().startsWith("bearer ")&&(r=r.substring(7));return r?await this.jwtRatchet.decodeToken(r,1):null}}class pt extends n{static HTTP_CODE=502;constructor(...e){super(...e),Object.setPrototypeOf(this,pt.prototype),this.withHttpStatusCode(pt.HTTP_CODE)}}class ht extends n{static HTTP_CODE=409;constructor(...e){super(...e),Object.setPrototypeOf(this,ht.prototype),this.withHttpStatusCode(ht.HTTP_CODE)}}class gt extends n{static HTTP_CODE=504;constructor(...e){super(...e),Object.setPrototypeOf(this,gt.prototype),this.withHttpStatusCode(gt.HTTP_CODE)}}class mt extends n{static HTTP_CODE=405;constructor(...e){super(...e),Object.setPrototypeOf(this,mt.prototype),this.withHttpStatusCode(mt.HTTP_CODE)}}class ft extends n{static HTTP_CODE=503;constructor(...e){super(...e),Object.setPrototypeOf(this,ft.prototype),this.withHttpStatusCode(ft.HTTP_CODE)}}class Et extends n{static HTTP_CODE=429;constructor(...e){super(...e),Object.setPrototypeOf(this,Et.prototype),this.withHttpStatusCode(Et.HTTP_CODE)}}class yt{options;constructor(e){this.options=e}modifyOpenApiDoc(e){let r;if(e&&this.options)try{const t=L.load(e),n=this.options.removeTags?this.options.removeTags.map((e=>e.toLowerCase())):[];if(this.options.newServerPath&&(t.servers=[{url:this.options.newServerPath}]),this.options.removeTags&&t.tags&&t.tags&&(t.tags=t.tags.filter((e=>{const t=e&&e.name?e.name.toLowerCase():"";return-1===n.indexOf(t)}))),t.paths){let e={};if(Object.keys(t.paths).forEach((r=>{const s=t.paths[r];Object.keys(s).forEach((t=>{const o=s[t];o.tags=o.tags?o.tags.filter((e=>-1==n.lastIndexOf(e.toLowerCase()))):o.tags;const a=t.toLowerCase()+" "+r.toLowerCase();this.matchNone(a,this.options.removeEndpoints)&&(e[r]=e[r]||{},e[r][t]=o)}))})),this.options.sortEndpoints){const t=Object.keys(e).sort(),r={};t.forEach((t=>{r[t]=e[t]})),e=r}t.paths=e}let s=this.options.removeSchemas||[];if(s=s.map((e=>e.toLowerCase())),t.components&&t.components.schemas){const e=Object.keys(t.components.schemas).sort(),r={};e.forEach((e=>{-1===s.indexOf(e.toLowerCase())&&(r[e]=t.components.schemas[e])})),t.components.schemas=r}r=L.dump(t)}catch(e){t.error("Error processing yaml: %s",e,e)}return r}matchNone(e,t){let r=!0;return e&&t&&t.forEach((t=>{r=r&&!t.test(e)})),r}}class wt{static combine(e,r=[]){u.notNullOrUndefined(e,"Files argument"),u.true(e.length>0,"Files argument larger than 0"),u.notNullOrUndefined(r,"Root path argument"),t.info("Processing %d files into output",e.length);let n={};for(let t=0;t<e.length;t++){const r=Q.readFileSync(e[t]).toString(),s=L.load(r);n=Object.assign(n,s)}const s=Object.assign([],r);for(;s.length>0;){const e={};e[s[s.length-1]]=n,s.splice(s.length-1,1),n=e}return L.dump(n)}}export{Ie as AbstractBackgroundManager,ct as ApiGatewayAdapterAuthenticationHandler,Ue as ApolloFilter,qe as ApolloUtil,lt as Auth0WebTokenManipulator,et as AwsLargePayloadS3SqsSnsBackgroundManager,$e as AwsSqsSnsBackgroundManager,ee as AwsUtil,Je as BackgroundDynamoLogTableHandler,Pe as BackgroundExecutionEventType,Oe as BackgroundHandler,Ne as BackgroundHttpAdapterHandler,Ce as BackgroundProcessHandling,ve as BackgroundValidator,pt as BadGateway,K as BadRequestError,Me as BuiltInAuthFilters,je as BuiltInAuthorizers,Le as BuiltInFilters,we as BuiltInHandlers,rt as BuiltInTraceIdGenerators,ht as ConflictError,$ as ContextUtil,ie as CronEpsilonLambdaEventHandler,ae as CronUtil,st as DaemonHandler,le as DynamoEpsilonLambdaEventHandler,Te as EchoProcessor,Ge as EpsilonApolloCorsMethod,Xe as EpsilonBackgroundProcessError,z as EpsilonBuildProperties,De as EpsilonConfigParser,W as EpsilonConstants,pe as EpsilonGlobalHandler,ue as EpsilonLoggingExtensionProcessor,J as EventUtil,fe as ForbiddenError,gt as GatewayTimeout,oe as GenericSnsEpsilonLambdaEventHandler,de as GenericSqsEpsilonLambdaEventHandler,ut as GoogleWebTokenManipulator,ne as InterApiEpsilonLambdaEventHandler,he as InterApiManager,re as InterApiUtil,dt as JwtRatchetLocalWebTokenManipulator,Ke as LocalContainerServer,Ye as LocalServer,ge as LocalServerCert,Se as LocalWebTokenManipulator,be as LogAndEnqueueEchoProcessor,ke as LogLevelManipulationFilter,Ve as LogMessageBackgroundErrorProcessor,mt as MethodNotAllowedError,ye as MisconfiguredError,se as NoHandlersFoundError,Ae as NoOpProcessor,me as NotFoundError,Ee as NotImplemented,_e as NullReturnedObjectHandling,yt as OpenApiDocModifier,it as RatchetCliHandler,tt as RatchetEpsilonCommonInfo,Z as RequestTimeoutError,X as ResponseUtil,nt as RetryProcessor,Fe as RouterUtil,ot as RunBackgroundProcessFromCommandLine,Be as RunHandlerAsFilter,Ze as S3BackgroundTransactionLogger,ce as S3EpsilonLambdaEventHandler,Re as SampleDelayProcessor,He as SampleInputValidatedProcessor,We as SampleServerComponents,ze as SampleServerStaticFiles,ft as ServiceUnavailable,Qe as SingleThreadLocalBackgroundManager,at as TestErrorServer,Et as TooManyRequestsError,Y as UnauthorizedError,xe as WebHandler,te as WebV2Handler,wt as YamlCombiner};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bitblit/ratchet-epsilon-common",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.415-alpha",
|
|
4
4
|
"description": "Tiny adapter to simplify building API gateway Lambda APIS",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"bin": {
|
|
@@ -67,10 +67,10 @@
|
|
|
67
67
|
"@aws-sdk/client-sns": "3.600.0",
|
|
68
68
|
"@aws-sdk/client-sqs": "3.600.0",
|
|
69
69
|
"@aws-sdk/types": "3.598.0",
|
|
70
|
-
"@bitblit/ratchet-aws": "4.0.
|
|
71
|
-
"@bitblit/ratchet-common": "4.0.
|
|
72
|
-
"@bitblit/ratchet-misc": "4.0.
|
|
73
|
-
"@bitblit/ratchet-node-only": "4.0.
|
|
70
|
+
"@bitblit/ratchet-aws": "4.0.415-alpha",
|
|
71
|
+
"@bitblit/ratchet-common": "4.0.415-alpha",
|
|
72
|
+
"@bitblit/ratchet-misc": "4.0.415-alpha",
|
|
73
|
+
"@bitblit/ratchet-node-only": "4.0.415-alpha",
|
|
74
74
|
"@smithy/abort-controller": "3.1.0",
|
|
75
75
|
"@smithy/smithy-client": "3.1.4",
|
|
76
76
|
"@smithy/util-waiter": "3.1.0",
|
|
@@ -88,10 +88,10 @@
|
|
|
88
88
|
},
|
|
89
89
|
"peerDependencies": {
|
|
90
90
|
"@apollo/server": "^4.10.4",
|
|
91
|
-
"@bitblit/ratchet-aws": "4.0.
|
|
92
|
-
"@bitblit/ratchet-common": "4.0.
|
|
93
|
-
"@bitblit/ratchet-misc": "4.0.
|
|
94
|
-
"@bitblit/ratchet-node-only": "4.0.
|
|
91
|
+
"@bitblit/ratchet-aws": "4.0.415-alpha",
|
|
92
|
+
"@bitblit/ratchet-common": "4.0.415-alpha",
|
|
93
|
+
"@bitblit/ratchet-misc": "4.0.415-alpha",
|
|
94
|
+
"@bitblit/ratchet-node-only": "4.0.415-alpha",
|
|
95
95
|
"graphql": "^16.8.1"
|
|
96
96
|
},
|
|
97
97
|
"peerDependenciesMeta": {
|