@bitblit/ratchet-epsilon-common 4.0.210-alpha → 4.0.219-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/lib/index.mjs.map +1 -1
- package/package.json +18 -17
package/lib/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../src/epsilon-build-properties.ts","../src/epsilon-constants.ts","../src/http/error/unauthorized-error.ts","../src/http/error/bad-request-error.ts","../src/http/event-util.ts","../src/http/response-util.ts","../src/http/error/request-timeout-error.ts","../src/util/context-util.ts","../src/util/aws-util.ts","../src/http/web-v2-handler.ts","../src/inter-api/inter-api-util.ts","../src/lambda-event-handler/inter-api-epsilon-lambda-event-handler.ts","../src/lambda-event-handler/generic-sns-epsilon-lambda-event-handler.ts","../src/util/cron-util.ts","../src/lambda-event-handler/cron-epsilon-lambda-event-handler.ts","../src/lambda-event-handler/s3-epsilon-lambda-event-handler.ts","../src/lambda-event-handler/dynamo-epsilon-lambda-event-handler.ts","../src/epsilon-logging-extension-processor.ts","../src/epsilon-global-handler.ts","../src/inter-api-manager.ts","../src/local-server-cert.ts","../src/http/error/not-found-error.ts","../src/http/error/forbidden-error.ts","../src/http/error/not-implemented.ts","../src/http/error/misconfigured-error.ts","../src/built-in/http/built-in-handlers.ts","../src/http/auth/local-web-token-manipulator.ts","../src/built-in/background/echo-processor.ts","../src/built-in/background/no-op-processor.ts","../src/built-in/background/sample-delay-processor.ts","../src/built-in/background/log-and-enqueue-echo-processor.ts","../src/background/background-process-handling.ts","../src/background/background-execution-event-type.ts","../src/config/http/null-returned-object-handling.ts","../src/built-in/http/apollo/epsilon-apollo-cors-method.ts","../src/background/background-http-adapter-handler.ts","../src/background/background-validator.ts","../src/background/manager/abstract-background-manager.ts","../src/background/background-handler.ts","../src/built-in/http/built-in-filters.ts","../src/built-in/http/built-in-auth-filters.ts","../src/built-in/http/log-level-manipulation-filter.ts","../src/http/route/router-util.ts","../src/built-in/http/run-handler-as-filter.ts","../src/http/web-handler.ts","../src/util/epsilon-config-parser.ts","../src/built-in/background/sample-input-validated-processor.ts","../src/built-in/http/built-in-authorizers.ts","../src/built-in/http/apollo/apollo-util.ts","../src/built-in/http/apollo-filter.ts","../src/built-in/background/log-message-background-error-processor.ts","../src/background/manager/single-thread-local-background-manager.ts","../src/sample/sample-server-static-files.ts","../src/sample/sample-server-components.ts","../src/local-server.ts","../src/local-container-server.ts","../src/background/background-dynamo-log-table-handler.ts","../src/background/epsilon-background-process-error.ts","../src/background/s3-background-transaction-logger.ts","../src/background/manager/aws-sqs-sns-background-manager.ts","../src/build/ratchet-epsilon-common-info.ts","../src/built-in/built-in-trace-id-generators.ts","../src/built-in/background/retry-processor.ts","../src/built-in/daemon/daemon-handler.ts","../src/cli/run-background-process-from-command-line.ts","../src/sample/test-error-server.ts","../src/cli/ratchet-cli-handler.ts","../src/http/auth/api-gateway-adapter-authentication-handler.ts","../src/http/auth/auth0-web-token-manipulator.ts","../src/http/auth/google-web-token-manipulator.ts","../src/http/auth/jwt-ratchet-local-web-token-manipulator.ts","../src/http/error/bad-gateway.ts","../src/http/error/conflict-error.ts","../src/http/error/gateway-timeout.ts","../src/http/error/method-not-allowed-error.ts","../src/http/error/service-unavailable.ts","../src/http/error/too-many-requests-error.ts","../src/open-api-util/open-api-doc-modifier.ts","../src/open-api-util/yaml-combiner.ts"],"sourcesContent":["import { StringRatchet } from '@bitblit/ratchet-common';\nexport class EpsilonBuildProperties {\n constructor() { }\n static get buildVersion() {\n return 'LOCAL-SNAPSHOT';\n }\n static get buildHash() {\n return 'LOCAL-HASH';\n }\n static get buildBranch() {\n return 'LOCAL-BRANCH';\n }\n static get buildTag() {\n return 'LOCAL-TAG';\n }\n static get buildBranchOrTag() {\n return StringRatchet.trimToNull(EpsilonBuildProperties.buildBranch)\n ? 'BRANCH:' + EpsilonBuildProperties.buildBranch\n : 'TAG:' + EpsilonBuildProperties.buildTag;\n }\n static get buildTime() {\n return 'LOCAL-TIME';\n }\n}\n//# sourceMappingURL=epsilon-build-properties.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { EsmRatchet } from '@bitblit/ratchet-common';\nexport class EpsilonConstants {\n static EPSILON_FINDER_DYNAMIC_IMPORT_PATH_ENV_NAME = 'EPSILON_FINDER_DYNAMIC_IMPORT_PATH';\n static EPSILON_FINDER_FUNCTION_NAME_ENV_NAME = 'EPSILON_FINDER_FUNCTION_NAME';\n static DEFAULT_EPSILON_FINDER_DYNAMIC_IMPORT_PATH = 'epsilon-global-handler-provider.js';\n static DEFAULT_EPSILON_FINDER_FUNCTION_NAME = 'findEpsilonGlobalHandler';\n static AUTH_HEADER_PREFIX = 'Bearer ';\n static AUTH_HEADER_NAME = 'Authorization';\n static BACKGROUND_SQS_TYPE_FIELD = 'BACKGROUND_TYPE';\n static BACKGROUND_SNS_START_MARKER = 'BACKGROUND_START_MARKER';\n static BACKGROUND_SNS_IMMEDIATE_RUN_FLAG = 'BACKGROUND_IMMEDIATE_RUN_FLAG';\n static INTER_API_SNS_EVENT = 'EPSILON_INTER_API_EVENT';\n static load(filePath, className) {\n Logger.info('Searching for %s : %s : %s', filePath, className, EsmRatchet.fetchDirName(import.meta.url));\n let rval = null;\n const val = require(filePath);\n if (val) {\n Logger.debug('Found %s - pulling object : %j : %s', filePath, Object.keys(val), className);\n rval = val[className];\n }\n return rval;\n }\n static async findDynamicImportEpsilonGlobalHandlerProvider() {\n const importPath = process.env[EpsilonConstants.EPSILON_FINDER_DYNAMIC_IMPORT_PATH_ENV_NAME] ||\n EpsilonConstants.DEFAULT_EPSILON_FINDER_DYNAMIC_IMPORT_PATH;\n const fnName = process.env[EpsilonConstants.EPSILON_FINDER_FUNCTION_NAME_ENV_NAME] || EpsilonConstants.DEFAULT_EPSILON_FINDER_FUNCTION_NAME;\n Logger.debug('Using epsilon finder dynamic import path : %s / %s', importPath, fnName);\n let provider = null;\n try {\n provider = this.load(importPath, fnName);\n }\n catch (err) {\n Logger.error('Error loading provider : %s / %s : %s', importPath, fnName, err, err);\n }\n let rval = null;\n if (provider) {\n Logger.debug('Type2 is : %s', typeof provider);\n Logger.info('Got3 : %s : %s', provider, typeof provider);\n rval = provider();\n Logger.info('Rval3 is %s', rval);\n }\n return rval;\n }\n constructor() { }\n}\n//# sourceMappingURL=epsilon-constants.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class UnauthorizedError extends RestfulApiHttpError {\n static HTTP_CODE = 401;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(UnauthorizedError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=unauthorized-error.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class BadRequestError extends RestfulApiHttpError {\n static HTTP_CODE = 400;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(BadRequestError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=bad-request-error.js.map","import { UnauthorizedError } from './error/unauthorized-error.js';\nimport { BadRequestError } from './error/bad-request-error.js';\nimport { Logger } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { MapRatchet } from '@bitblit/ratchet-common';\nimport { LoggerLevelName } from '@bitblit/ratchet-common';\nimport { EnumRatchet } from '@bitblit/ratchet-common';\nimport { Base64Ratchet } from '@bitblit/ratchet-common';\nimport jwt from 'jsonwebtoken';\nimport { EpsilonConstants } from '../epsilon-constants.js';\nexport class EventUtil {\n constructor() { }\n static extractStage(event) {\n if (!event.path.startsWith('/')) {\n throw new BadRequestError('Path should start with / but does not : ' + event.path);\n }\n const idx = event.path.indexOf('/', 1);\n if (idx == -1) {\n throw new BadRequestError('No second / found in the path : ' + event.path);\n }\n return event.path.substring(1, idx);\n }\n static extractHostHeader(event) {\n return MapRatchet.extractValueFromMapIgnoreCase(event.headers, 'Host');\n }\n static extractProtocol(event) {\n return MapRatchet.extractValueFromMapIgnoreCase(event.headers, 'X-Forwarded-Proto');\n }\n static extractApiGatewayStage(event) {\n const rc = EventUtil.extractRequestContext(event);\n return rc ? rc.stage : null;\n }\n static extractRequestContext(event) {\n return event.requestContext;\n }\n static extractAuthorizer(event) {\n const rc = EventUtil.extractRequestContext(event);\n return rc ? rc.authorizer : null;\n }\n static ipAddressChain(event) {\n const headerVal = event && event.headers ? MapRatchet.extractValueFromMapIgnoreCase(event.headers, 'X-Forwarded-For') : null;\n let headerList = headerVal ? String(headerVal).split(',') : [];\n headerList = headerList.map((s) => s.trim());\n return headerList;\n }\n static ipAddress(event) {\n const list = EventUtil.ipAddressChain(event);\n return list && list.length > 0 ? list[0] : null;\n }\n static extractFullPath(event, overrideProtocol = null) {\n const protocol = overrideProtocol || EventUtil.extractProtocol(event) || 'https';\n return protocol + '://' + event.requestContext['domainName'] + event.requestContext.path;\n }\n static extractFullPrefix(event, overrideProtocol = null) {\n const protocol = overrideProtocol || EventUtil.extractProtocol(event) || 'https';\n const prefix = event.requestContext.path.substring(0, event.requestContext.path.indexOf('/', 1));\n return protocol + '://' + event.requestContext['domainName'] + prefix;\n }\n static jsonBodyToObject(event) {\n let rval = null;\n if (event.body) {\n const contentType = MapRatchet.extractValueFromMapIgnoreCase(event.headers, 'Content-Type') || 'application/octet-stream';\n rval = event.body;\n if (event.isBase64Encoded) {\n rval = Buffer.from(rval, 'base64');\n }\n if (contentType.startsWith('application/json')) {\n rval = JSON.parse(rval.toString('ascii'));\n }\n }\n return rval;\n }\n static calcLogLevelViaEventOrEnvParam(curLevel, event, rConfig) {\n let rval = curLevel;\n if (rConfig?.envParamLogLevelName && process.env[rConfig.envParamLogLevelName]) {\n rval = EnumRatchet.keyToEnum(LoggerLevelName, process.env[rConfig.envParamLogLevelName]);\n Logger.silly('Found env log level : %s', rval);\n }\n if (rConfig &&\n rConfig.queryParamLogLevelName &&\n event &&\n event.queryStringParameters &&\n event.queryStringParameters[rConfig.queryParamLogLevelName]) {\n rval = EnumRatchet.keyToEnum(LoggerLevelName, event.queryStringParameters[rConfig.queryParamLogLevelName]);\n Logger.silly('Found query log level : %s', rval);\n }\n return rval;\n }\n static fixStillEncodedQueryParams(event) {\n if (event?.queryStringParameters) {\n const newParams = {};\n Object.keys(event.queryStringParameters).forEach((k) => {\n const val = event.queryStringParameters[k];\n if (k.toLowerCase().startsWith('amp;')) {\n newParams[k.substring(4)] = val;\n }\n else {\n newParams[k] = val;\n }\n });\n event.queryStringParameters = newParams;\n }\n if (event?.multiValueQueryStringParameters) {\n const newParams = {};\n Object.keys(event.multiValueQueryStringParameters).forEach((k) => {\n const val = event.multiValueQueryStringParameters[k];\n if (k.toLowerCase().startsWith('amp;')) {\n newParams[k.substring(4)] = val;\n }\n else {\n newParams[k] = val;\n }\n });\n event.multiValueQueryStringParameters = newParams;\n }\n }\n static applyTokenToEventForTesting(event, jwtToken) {\n const jwtFullData = jwt.decode(jwtToken, { complete: true });\n if (!jwtFullData['payload']) {\n throw new Error('No payload found in passed token');\n }\n const jwtData = jwtFullData['payload'];\n event.headers = event.headers || {};\n event.headers[EpsilonConstants.AUTH_HEADER_NAME.toLowerCase()] = 'Bearer ' + jwtToken;\n event.requestContext = event.requestContext || {};\n const newAuth = Object.assign({}, event.requestContext.authorizer);\n newAuth.userData = jwtData;\n newAuth.userDataJSON = jwtData ? JSON.stringify(jwtData) : null;\n newAuth.srcData = jwtToken;\n event.requestContext.authorizer = newAuth;\n }\n static extractBasicAuthenticationToken(event, throwErrorOnMissingBad = false) {\n let rval = null;\n if (!!event && !!event.headers) {\n const headerVal = EventUtil.extractAuthorizationHeaderCaseInsensitive(event);\n if (!!headerVal && headerVal.startsWith('Basic ')) {\n const parsed = Base64Ratchet.base64StringToString(headerVal.substring(6));\n const sp = parsed.split(':');\n Logger.silly('Parsed to %j', sp);\n if (!!sp && sp.length === 2) {\n rval = {\n username: sp[0],\n password: sp[1],\n };\n }\n }\n }\n if (!rval && throwErrorOnMissingBad) {\n throw new UnauthorizedError('Could not find valid basic authentication header');\n }\n return rval;\n }\n static eventIsAGraphQLIntrospection(event) {\n let rval = false;\n if (!!event) {\n if (!!event.httpMethod && 'post' === event.httpMethod.toLowerCase()) {\n if (!!event.path && event.path.endsWith('/graphql')) {\n const body = EventUtil.jsonBodyToObject(event);\n rval = !!body && !!body['operationName'] && body['operationName'] === 'IntrospectionQuery';\n }\n }\n }\n return rval;\n }\n static extractAuthorizationHeaderCaseInsensitive(evt) {\n return MapRatchet.caseInsensitiveAccess(evt?.headers || {}, EpsilonConstants.AUTH_HEADER_NAME);\n }\n static extractBearerTokenFromEvent(evt) {\n let rval = null;\n const authHeader = StringRatchet.trimToEmpty(EventUtil.extractAuthorizationHeaderCaseInsensitive(evt));\n if (authHeader.toLowerCase().startsWith('bearer ')) {\n rval = authHeader.substring(7);\n }\n return rval;\n }\n static hostIsLocal(host) {\n let rval = false;\n if (StringRatchet.trimToNull(host)) {\n host = host.includes(':') ? host.substring(0, host.indexOf(':')) : host;\n host = host.toLowerCase();\n if (host === 'localhost' || host === '127.0.0.1') {\n rval = true;\n }\n }\n return rval;\n }\n static hostIsLocalOrNotRoutableIP4(host) {\n let rval = false;\n if (StringRatchet.trimToNull(host)) {\n host = host.includes(':') ? host.substring(0, host.indexOf(':')) : host;\n host = host.toLowerCase();\n if (host === 'localhost' ||\n host === '127.0.0.1' ||\n host.startsWith('192.168.') ||\n host.startsWith('10.') ||\n host.startsWith('172.16.')) {\n rval = true;\n }\n }\n return rval;\n }\n}\n//# sourceMappingURL=event-util.js.map","import { Logger, MapRatchet } from '@bitblit/ratchet-common';\nimport zlib from 'zlib';\nexport class ResponseUtil {\n constructor() { }\n static errorResponse(err) {\n const body = {\n errors: err.errors,\n httpStatusCode: err.httpStatusCode,\n requestId: err.requestId,\n };\n if (err.detailErrorCode) {\n body['detailErrorCode'] = err.detailErrorCode;\n }\n if (err.endUserErrors && err.endUserErrors.length > 0) {\n body['endUserErrors'] = err.endUserErrors;\n }\n if (err.details) {\n body['details'] = err.details;\n }\n if (err.wrappedError) {\n body['wrappedError'] = err.wrappedError.name + ' : ' + err.wrappedError.message;\n }\n const errorResponse = {\n statusCode: err.httpStatusCode,\n isBase64Encoded: false,\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n };\n return errorResponse;\n }\n static redirect(target, code = 301, queryParams = null) {\n if (code !== 301 && code !== 302 && code !== 307) {\n throw new Error('Code must be 301 or 302 or 307 for a redirect');\n }\n let redirectTarget = target;\n if (queryParams) {\n const keys = Object.keys(queryParams);\n if (keys.length > 0) {\n Logger.silly('Applying params to input target : %j', queryParams);\n redirectTarget += redirectTarget.indexOf('?') === -1 ? '?' : '&';\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n redirectTarget += k + '=' + encodeURIComponent(queryParams[k]);\n if (i < keys.length - 1) {\n redirectTarget += '&';\n }\n }\n }\n }\n return {\n statusCode: code,\n body: '{\"redirect-target\":\"' + redirectTarget + '}',\n headers: {\n 'Content-Type': 'application/json',\n Location: redirectTarget,\n },\n };\n }\n static coerceToProxyResult(input) {\n let rval = null;\n if (input != null) {\n if (typeof input === 'object') {\n if (input.statusCode && input.body !== undefined) {\n rval = Object.assign({}, input);\n if (typeof input.body === 'string') {\n }\n else if (Buffer.isBuffer(input.body)) {\n rval.body = input.body.toString('base64');\n rval.headers = input.headers || {};\n rval.headers['Content-Type'] = input.body.contentType;\n rval.isBase64Encoded = true;\n }\n }\n else {\n const headers = input.headers || {};\n headers['Content-Type'] = 'application/json';\n rval = ResponseUtil.coerceToProxyResult({\n statusCode: 200,\n body: JSON.stringify(input),\n headers: headers,\n isBase64Encoded: false,\n });\n }\n }\n else if (typeof input === 'string' || Buffer.isBuffer(input)) {\n rval = ResponseUtil.coerceToProxyResult({ statusCode: 200, body: input });\n }\n else {\n const headers = input.headers || {};\n headers['Content-Type'] = 'application/json';\n rval = ResponseUtil.coerceToProxyResult({\n statusCode: 200,\n body: JSON.stringify(input),\n headers: headers,\n isBase64Encoded: false,\n });\n }\n }\n return rval;\n }\n static async applyGzipIfPossible(encodingHeader, proxyResult) {\n const rval = proxyResult;\n if (encodingHeader && encodingHeader.toLowerCase().indexOf('gzip') > -1) {\n const bigEnough = proxyResult.body.length > 1400;\n let contentType = MapRatchet.extractValueFromMapIgnoreCase(proxyResult.headers, 'content-type') || '';\n contentType = contentType.toLowerCase();\n const exemptContent = contentType === 'application/pdf' || contentType === 'application/zip' || contentType.startsWith('image/');\n if (bigEnough && !exemptContent) {\n const asBuffer = proxyResult.isBase64Encoded ? Buffer.from(proxyResult.body, 'base64') : Buffer.from(proxyResult.body);\n const zipped = await this.gzip(asBuffer);\n Logger.debug('Comp from %s to %d bytes', asBuffer.length, zipped.length);\n const zipped64 = zipped.toString('base64');\n rval.body = zipped64;\n rval.isBase64Encoded = true;\n rval.headers = rval.headers || {};\n rval.headers['Content-Encoding'] = 'gzip';\n }\n else {\n Logger.silly('Not gzipping, too small or exempt content');\n }\n }\n else {\n Logger.silly('Not gzipping, not an accepted encoding');\n }\n return rval;\n }\n static gzip(input) {\n const promise = new Promise(function (resolve, reject) {\n zlib.gzip(input, function (error, result) {\n if (!error)\n resolve(result);\n else\n reject(error);\n });\n });\n return promise;\n }\n}\n//# sourceMappingURL=response-util.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class RequestTimeoutError extends RestfulApiHttpError {\n static HTTP_CODE = 500;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(RequestTimeoutError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=request-timeout-error.js.map","import { StringRatchet } from '@bitblit/ratchet-common';\nimport { ErrorRatchet } from '@bitblit/ratchet-common';\nimport { NumberRatchet } from '@bitblit/ratchet-common';\nexport class ContextUtil {\n static CURRENT_EPSILON_REFERENCE;\n static CURRENT_CONTEXT;\n static CURRENT_EVENT;\n static CURRENT_LOG_VARS = {};\n static CURRENT_PROCESS_LABEL;\n static CURRENT_OVERRIDE_TRACE_ID;\n static CURRENT_OVERRIDE_TRACE_DEPTH;\n constructor() { }\n static initContext(epsilon, evt, ctx, processLabel) {\n ContextUtil.CURRENT_EPSILON_REFERENCE = epsilon;\n ContextUtil.CURRENT_CONTEXT = ctx;\n ContextUtil.CURRENT_EVENT = evt;\n ContextUtil.CURRENT_LOG_VARS = {};\n ContextUtil.CURRENT_PROCESS_LABEL = processLabel;\n }\n static clearContext() {\n ContextUtil.CURRENT_EPSILON_REFERENCE = null;\n ContextUtil.CURRENT_CONTEXT = null;\n ContextUtil.CURRENT_EVENT = null;\n ContextUtil.CURRENT_LOG_VARS = {};\n ContextUtil.CURRENT_PROCESS_LABEL = null;\n ContextUtil.CURRENT_OVERRIDE_TRACE_ID = null;\n ContextUtil.CURRENT_OVERRIDE_TRACE_DEPTH = null;\n }\n static setOverrideTrace(traceId, traceDepth) {\n ContextUtil.CURRENT_OVERRIDE_TRACE_ID = traceId || ContextUtil.CURRENT_OVERRIDE_TRACE_ID;\n ContextUtil.CURRENT_OVERRIDE_TRACE_DEPTH = traceDepth || ContextUtil.CURRENT_OVERRIDE_TRACE_DEPTH;\n }\n static setOverrideTraceFromInternalBackgroundEntry(entry) {\n ContextUtil.setOverrideTrace(entry.traceId, entry.traceDepth);\n }\n static setOverrideTraceFromInterApiEntry(interApiEntry) {\n ContextUtil.setOverrideTrace(interApiEntry.traceId, interApiEntry.traceDepth);\n }\n static addHeadersToRecord(input, depthOffset = 0) {\n if (input) {\n input[ContextUtil.traceHeaderName()] = ContextUtil.currentTraceId();\n input[ContextUtil.traceDepthHeaderName()] = StringRatchet.safeString(ContextUtil.currentTraceDepth() + depthOffset);\n }\n else {\n ErrorRatchet.throwFormattedErr('Cannot add headers to null/undefined input');\n }\n }\n static addTraceToProxyResult(pr) {\n pr.headers = pr.headers || {};\n ContextUtil.addHeadersToRecord(pr.headers);\n }\n static addTraceToHttpRequestInit(ri) {\n ri.headers = ri.headers || {};\n ContextUtil.addHeadersToRecord(ri.headers, 1);\n }\n static setProcessLabel(processLabel) {\n ContextUtil.CURRENT_PROCESS_LABEL = processLabel;\n }\n static currentRequestId() {\n const ctx = ContextUtil.CURRENT_CONTEXT;\n return ctx ? ctx.awsRequestId : null;\n }\n static defaultedCurrentRequestId(defaultValueIfMissing = StringRatchet.createType4Guid()) {\n return ContextUtil.currentRequestId() ?? defaultValueIfMissing;\n }\n static remainingTimeMS() {\n const ctx = ContextUtil.CURRENT_CONTEXT;\n return ctx ? ctx.getRemainingTimeInMillis() : null;\n }\n static currentProcessLabel() {\n return ContextUtil.CURRENT_PROCESS_LABEL || 'unset';\n }\n static traceHeaderName() {\n const headerName = ContextUtil?.CURRENT_EPSILON_REFERENCE?.config?.loggerConfig?.traceHeaderName || 'X-TRACE-ID';\n return headerName;\n }\n static traceDepthHeaderName() {\n const headerName = ContextUtil?.CURRENT_EPSILON_REFERENCE?.config?.loggerConfig?.traceDepthHeaderName || 'X-TRACE-DEPTH';\n return headerName;\n }\n static currentTraceId() {\n const traceFn = ContextUtil?.CURRENT_EPSILON_REFERENCE?.config?.loggerConfig?.traceIdGenerator || ContextUtil.defaultedCurrentRequestId;\n const traceId = ContextUtil.CURRENT_OVERRIDE_TRACE_ID ||\n ContextUtil.CURRENT_EVENT?.headers?.[ContextUtil.traceHeaderName()] ||\n traceFn(ContextUtil.CURRENT_EVENT, ContextUtil.CURRENT_CONTEXT);\n return traceId;\n }\n static currentTraceDepth() {\n const caller = ContextUtil.CURRENT_OVERRIDE_TRACE_DEPTH ||\n NumberRatchet.safeNumber(ContextUtil.CURRENT_EVENT?.headers?.[ContextUtil.traceDepthHeaderName()]) ||\n 1;\n return caller;\n }\n static addLogVariable(name, val) {\n ContextUtil.CURRENT_LOG_VARS[name] = val;\n }\n static fetchLogVariable(name) {\n return ContextUtil.CURRENT_LOG_VARS?.[name];\n }\n static fetchLogVariables() {\n return Object.assign({}, ContextUtil.CURRENT_LOG_VARS || {});\n }\n}\n//# sourceMappingURL=context-util.js.map","export class AwsUtil {\n static apiGatewayV2ToApiGatewayV1(srcEvt) {\n const rval = {\n requestContext: AwsUtil.apiGatewayV2RequestContextToApiGatewayV1RequestContext(srcEvt.requestContext),\n httpMethod: srcEvt.requestContext.http.method,\n path: srcEvt.requestContext.http.path,\n queryStringParameters: srcEvt.queryStringParameters,\n headers: srcEvt.headers,\n body: srcEvt.body,\n isBase64Encoded: srcEvt.isBase64Encoded,\n multiValueHeaders: null,\n multiValueQueryStringParameters: null,\n pathParameters: srcEvt.pathParameters,\n stageVariables: srcEvt.stageVariables,\n resource: null,\n };\n return rval;\n }\n static apiGatewayV2RequestContextToApiGatewayV1RequestContext(srcEvt) {\n const rval = {\n accountId: srcEvt.accountId,\n apiId: srcEvt.apiId,\n authorizer: null,\n domainName: srcEvt.domainName,\n domainPrefix: srcEvt.domainPrefix,\n requestId: srcEvt.requestId,\n routeKey: srcEvt.routeKey,\n stage: srcEvt.stage,\n requestTime: srcEvt.time,\n requestTimeEpoch: srcEvt.timeEpoch,\n protocol: srcEvt.http.protocol,\n httpMethod: srcEvt.http.method,\n identity: null,\n path: srcEvt.http.path,\n resourceId: null,\n resourcePath: null,\n };\n return rval;\n }\n static findInMap(toFind, map) {\n let rval = null;\n map.forEach((val, key) => {\n if (AwsUtil.matchExact(key, toFind)) {\n rval = val;\n }\n });\n return rval;\n }\n static matchExact(r, str) {\n const match = str.match(r);\n return match != null && str == match[0];\n }\n static resolvePotentialFunctionToResult(src, def) {\n let rval = def;\n if (src) {\n if (typeof src === 'function') {\n rval = src();\n }\n else {\n rval = src;\n }\n }\n return rval;\n }\n}\n//# sourceMappingURL=aws-util.js.map","import { AwsUtil } from '../util/aws-util.js';\nimport { LambdaEventDetector } from '@bitblit/ratchet-aws';\nexport class WebV2Handler {\n webHandler;\n constructor(webHandler) {\n this.webHandler = webHandler;\n }\n extractLabel(evt, context) {\n let rval = this.webHandler.extractLabel(AwsUtil.apiGatewayV2ToApiGatewayV1(evt), context);\n rval = rval.replace('WEB:', 'WEB2:');\n return rval;\n }\n handlesEvent(evt) {\n return LambdaEventDetector.isValidApiGatewayV2WithRequestContextEvent(evt);\n }\n async processEvent(evt, context) {\n const conv = AwsUtil.apiGatewayV2ToApiGatewayV1(evt);\n const asExtended = Object.assign({}, { parsedBody: null, authorization: null, convertedFromV2Event: true }, conv);\n const rval = await this.webHandler.openApiLambdaHandler(asExtended, context);\n return rval;\n }\n}\n//# sourceMappingURL=web-v2-handler.js.map","import { LambdaEventDetector } from '@bitblit/ratchet-aws';\nimport { EpsilonConstants } from '../epsilon-constants.js';\nimport { RequireRatchet } from '@bitblit/ratchet-common';\nimport { Logger } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { ContextUtil } from '../util/context-util.js';\nexport class InterApiUtil {\n static isInterApiSnsEvent(event) {\n return !!InterApiUtil.extractEntryFromEvent(event);\n }\n static extractEntryFromEvent(evt) {\n let rval = null;\n if (!!evt) {\n if (LambdaEventDetector.isSingleSnsEvent(evt)) {\n const cast = evt;\n const msg = cast.Records[0].Sns.Message;\n if (!!StringRatchet.trimToNull(msg)) {\n const parsed = JSON.parse(msg);\n if (!!parsed && parsed['type'] === EpsilonConstants.INTER_API_SNS_EVENT) {\n rval = parsed['interApiEvent'];\n }\n }\n }\n }\n return rval;\n }\n static async processInterApiEvent(evt, cfg, mgr) {\n let rval = [];\n RequireRatchet.notNullOrUndefined(evt, 'InterApiEntry');\n RequireRatchet.notNullOrUndefined(mgr, 'BackgroundManager');\n const interApiEntry = InterApiUtil.extractEntryFromEvent(evt);\n ContextUtil.setOverrideTraceFromInterApiEntry(interApiEntry);\n Logger.info('Processing inter-api event : %j', evt);\n const backgroundEntries = [];\n cfg.processMappings.forEach((map) => {\n if (!map.disabled && interApiEntry.source.match(map.sourceRegex) && interApiEntry.type.match(map.typeRegex)) {\n map.backgroundProcessTypes.forEach((taskName) => {\n const entry = mgr.createEntry(taskName, interApiEntry.data);\n backgroundEntries.push(entry);\n });\n }\n });\n if (backgroundEntries.length > 0) {\n Logger.info('Adding %d entries to queue', backgroundEntries.length);\n rval = await mgr.addEntriesToQueue(backgroundEntries, true);\n }\n else {\n Logger.info('No entries mapped for this event');\n }\n return rval;\n }\n static addTraceToInterApiEntry(ent) {\n if (ent) {\n ent.traceId = ent.traceId || ContextUtil.currentTraceId();\n ent.traceDepth = ent.traceDepth || ContextUtil.currentTraceDepth() + 1;\n }\n return ent;\n }\n}\n//# sourceMappingURL=inter-api-util.js.map","import { InterApiUtil } from '../inter-api/inter-api-util.js';\nexport class InterApiEpsilonLambdaEventHandler {\n _epsilon;\n constructor(_epsilon) {\n this._epsilon = _epsilon;\n }\n extractLabel(evt, context) {\n const ent = InterApiUtil.extractEntryFromEvent(evt);\n return 'InterApi:' + ent.source + ':' + ent.type;\n }\n handlesEvent(evt) {\n return this._epsilon.config.interApiConfig && InterApiUtil.isInterApiSnsEvent(evt);\n }\n async processEvent(evt, context) {\n const tmp = await InterApiUtil.processInterApiEvent(evt, this._epsilon.config.interApiConfig, this._epsilon.backgroundManager);\n const rval = {\n statusCode: 200,\n body: JSON.stringify(tmp),\n isBase64Encoded: false,\n };\n return rval;\n }\n}\n//# sourceMappingURL=inter-api-epsilon-lambda-event-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { AwsUtil } from '../util/aws-util.js';\nimport { LambdaEventDetector } from '@bitblit/ratchet-aws';\nexport class GenericSnsEpsilonLambdaEventHandler {\n _epsilon;\n constructor(_epsilon) {\n this._epsilon = _epsilon;\n }\n extractLabel(evt, context) {\n return 'SNSEvt:' + evt.Records[0].EventSource;\n }\n handlesEvent(evt) {\n return LambdaEventDetector.isValidSnsEvent(evt);\n }\n async processEvent(evt, context) {\n let rval = null;\n if (this._epsilon.config && this._epsilon.config.sns && evt && evt.Records.length > 0) {\n const finder = evt.Records[0].Sns.TopicArn;\n const handler = AwsUtil.findInMap(finder, this._epsilon.config.sns.handlers);\n if (handler) {\n rval = await handler(evt);\n }\n else {\n Logger.info('Found no SNS handler for : %s', finder);\n }\n }\n return rval;\n }\n}\n//# sourceMappingURL=generic-sns-epsilon-lambda-event-handler.js.map","import { RequireRatchet } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { ErrorRatchet } from '@bitblit/ratchet-common';\nimport { DateTime } from 'luxon';\nexport class CronUtil {\n static everyNMinuteFilter(n) {\n return CronUtil.everyNElementFilter(n, 60);\n }\n static everyNDaysOfYearFilter(n) {\n return CronUtil.everyNElementFilter(n, 365);\n }\n static everyNElementFilter(n, m) {\n RequireRatchet.notNullOrUndefined(n);\n RequireRatchet.notNullOrUndefined(m);\n const half = Math.floor(m / 2);\n if (!n || n < 2 || n > half || m % n !== 0) {\n ErrorRatchet.throwFormattedErr('Invalid config - this function only makes sense for 2 < N < %d and %d evenly divisible by N', half, m);\n throw new Error('Invalid config - this function only makes sense for 2 < N < 31 and 60 evenly divisible by N');\n }\n const rval = [];\n for (let i = 0; i < 60; i += n) {\n rval.push(i);\n }\n return rval;\n }\n static numberMatchesFilter(num, filter) {\n return !filter || filter.length === 0 || filter.includes(num);\n }\n static eventMatchesEntry(event, entry, cfg, testTimeEpochMS = new Date().getTime()) {\n let rval = false;\n if (!!event && !!entry && !!cfg.timezone) {\n if (!!event.resources && event.resources.length > 0) {\n const eventSourceName = event.resources[0];\n const targetTZ = StringRatchet.trimToNull(entry.overrideTimezone) || cfg.timezone;\n const nowInTZ = DateTime.fromMillis(testTimeEpochMS).setZone(targetTZ);\n rval = !entry.eventFilter || entry.eventFilter.test(eventSourceName);\n rval = rval && CronUtil.numberMatchesFilter(nowInTZ.minute, entry.minuteFilter);\n rval = rval && CronUtil.numberMatchesFilter(nowInTZ.hour, entry.hourFilter);\n rval = rval && CronUtil.numberMatchesFilter(nowInTZ.weekday, entry.dayOfWeekFilter);\n rval = rval && CronUtil.numberMatchesFilter(nowInTZ.day, entry.dayOfMonthFilter);\n rval = rval && CronUtil.numberMatchesFilter(nowInTZ.month, entry.monthOfYearFilter);\n rval = rval && (!entry.contextMatchFilter || entry.contextMatchFilter.test(StringRatchet.trimToEmpty(cfg.context)));\n rval = rval && (!entry.contextNoMatchFilter || !entry.contextNoMatchFilter.test(StringRatchet.trimToEmpty(cfg.context)));\n }\n }\n return rval;\n }\n static cronEntryName(entry, idx = null) {\n RequireRatchet.notNullOrUndefined(entry);\n let rval = null;\n if (!!entry) {\n rval = entry.name;\n rval = rval || entry['backgroundTaskType'];\n if (!rval && !!entry['directHandler']) {\n if (!!idx) {\n rval = 'Direct Entry ' + idx;\n }\n else {\n rval = 'Direct Entry (No idx specified)';\n }\n }\n }\n else {\n rval = 'ERROR: no entry passed';\n }\n return rval;\n }\n}\n//# sourceMappingURL=cron-util.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { AwsUtil } from '../util/aws-util.js';\nimport { CronUtil } from '../util/cron-util.js';\nimport { LambdaEventDetector } from '@bitblit/ratchet-aws';\nexport class CronEpsilonLambdaEventHandler {\n _epsilon;\n constructor(_epsilon) {\n this._epsilon = _epsilon;\n }\n extractLabel(evt, context) {\n return 'CronEvt:' + evt.source;\n }\n handlesEvent(evt) {\n return LambdaEventDetector.isValidCronEvent(evt);\n }\n async processEvent(evt, context) {\n let rval = null;\n Logger.debug('Epsilon: CRON: %j', evt);\n if (!this._epsilon.config.cron) {\n Logger.debug('Skipping - CRON disabled');\n rval = {\n statusCode: 200,\n body: JSON.stringify({ message: 'CRON skipped - disabled' }),\n isBase64Encoded: false,\n };\n }\n else {\n const output = await CronEpsilonLambdaEventHandler.processCronEvent(evt, this._epsilon.config.cron, this._epsilon.backgroundManager, this._epsilon.backgroundHandler);\n rval = {\n statusCode: 200,\n body: JSON.stringify({ message: 'CRON complete' }),\n isBase64Encoded: false,\n };\n }\n return rval;\n }\n static async processCronEvent(evt, cronConfig, backgroundManager, background) {\n let rval = false;\n if (cronConfig && evt && evt.resources[0]) {\n if (!!cronConfig.entries) {\n if (!!background) {\n const toEnqueue = [];\n for (let i = 0; i < cronConfig.entries.length; i++) {\n const smCronEntry = cronConfig.entries[i];\n if (CronUtil.eventMatchesEntry(evt, smCronEntry, cronConfig)) {\n Logger.info('CRON Firing : %s', CronUtil.cronEntryName(smCronEntry));\n const backgroundEntry = {\n type: smCronEntry.backgroundTaskType,\n data: AwsUtil.resolvePotentialFunctionToResult(smCronEntry.data, {}),\n };\n Logger.silly('Resolved entry : %j', backgroundEntry);\n if (smCronEntry.fireImmediate) {\n await backgroundManager.fireImmediateProcessRequest(backgroundEntry);\n rval = true;\n }\n else {\n toEnqueue.push(backgroundEntry);\n }\n }\n }\n if (toEnqueue.length > 0) {\n await backgroundManager.addEntriesToQueue(toEnqueue, true);\n rval = true;\n }\n }\n else {\n Logger.warn('Cron defines background tasks, but no background manager provided');\n }\n }\n }\n return rval;\n }\n}\n//# sourceMappingURL=cron-epsilon-lambda-event-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { AwsUtil } from '../util/aws-util.js';\nimport { LambdaEventDetector } from '@bitblit/ratchet-aws';\nexport class S3EpsilonLambdaEventHandler {\n _epsilon;\n constructor(_epsilon) {\n this._epsilon = _epsilon;\n }\n extractLabel(evt, context) {\n return 'S3Evt:' + evt.Records[0].eventSource;\n }\n handlesEvent(evt) {\n return LambdaEventDetector.isValidS3Event(evt);\n }\n async processEvent(evt, context) {\n let rval = null;\n if (this._epsilon.config && this._epsilon.config.s3 && evt && evt.Records.length > 0) {\n const finder = evt.Records[0].s3.bucket.name + '/' + evt.Records[0].s3.object.key;\n const isRemoveEvent = evt.Records[0].eventName && evt.Records[0].eventName.startsWith('ObjectRemoved');\n if (isRemoveEvent) {\n const handler = AwsUtil.findInMap(finder, this._epsilon.config.s3.removeHandlers);\n if (handler) {\n rval = await handler(evt);\n }\n else {\n Logger.info('Found no s3 create handler for : %s', finder);\n }\n }\n else {\n const handler = AwsUtil.findInMap(finder, this._epsilon.config.s3.createHandlers);\n if (handler) {\n rval = await handler(evt);\n }\n else {\n Logger.info('Found no s3 remove handler for : %s', finder);\n }\n }\n }\n return rval;\n }\n}\n//# sourceMappingURL=s3-epsilon-lambda-event-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { AwsUtil } from '../util/aws-util.js';\nimport { LambdaEventDetector } from '@bitblit/ratchet-aws';\nexport class DynamoEpsilonLambdaEventHandler {\n _epsilon;\n constructor(_epsilon) {\n this._epsilon = _epsilon;\n }\n extractLabel(evt, context) {\n return 'DDBEvt:' + evt.Records[0].eventName + ':' + evt.Records[0].eventSource;\n }\n handlesEvent(evt) {\n return LambdaEventDetector.isValidDynamoDBEvent(evt);\n }\n async processEvent(evt, context) {\n let rval = null;\n if (this._epsilon.config && this._epsilon.config.dynamoDb && evt && evt.Records && evt.Records.length > 0) {\n const finder = evt.Records[0].eventSourceARN;\n const handler = AwsUtil.findInMap(finder, this._epsilon.config.dynamoDb.handlers);\n if (handler) {\n rval = await handler(evt);\n }\n else {\n Logger.info('Found no Dynamo handler for : %s', finder);\n }\n }\n return rval;\n }\n async processUncaughtError(event, context, err) {\n Logger.error('Error slipped out to outer edge (Dynamo). Logging and rethrowing : %s', err, err);\n throw err;\n }\n}\n//# sourceMappingURL=dynamo-epsilon-lambda-event-handler.js.map","import { ContextUtil } from './util/context-util.js';\nexport class EpsilonLoggingExtensionProcessor {\n process(msg) {\n msg.params = Object.assign({}, msg.params || {}, ContextUtil.fetchLogVariables());\n msg.params['tester'] = Date.now();\n msg.params['awsRequestId'] = ContextUtil.currentRequestId();\n msg.params['traceId'] = ContextUtil.currentTraceId();\n msg.params['traceDepth'] = ContextUtil.currentTraceDepth();\n msg.params['procLabel'] = ContextUtil.currentProcessLabel();\n return msg;\n }\n label() {\n return 'EpsilonLoggingExtensionProcessor';\n }\n}\n//# sourceMappingURL=epsilon-logging-extension-processor.js.map","import { ErrorRatchet, Logger, LoggerLevelName, LoggerOutputFunction, LogMessageFormatType, PromiseRatchet, TimeoutToken, RestfulApiHttpError } from '@bitblit/ratchet-common';\nimport { EventUtil } from './http/event-util.js';\nimport { ResponseUtil } from './http/response-util.js';\nimport { RequestTimeoutError } from './http/error/request-timeout-error.js';\nimport { ContextUtil } from './util/context-util.js';\nimport { WebV2Handler } from './http/web-v2-handler.js';\nimport { InterApiEpsilonLambdaEventHandler } from './lambda-event-handler/inter-api-epsilon-lambda-event-handler.js';\nimport { GenericSnsEpsilonLambdaEventHandler } from './lambda-event-handler/generic-sns-epsilon-lambda-event-handler.js';\nimport { CronEpsilonLambdaEventHandler } from './lambda-event-handler/cron-epsilon-lambda-event-handler.js';\nimport { S3EpsilonLambdaEventHandler } from './lambda-event-handler/s3-epsilon-lambda-event-handler.js';\nimport { DynamoEpsilonLambdaEventHandler } from './lambda-event-handler/dynamo-epsilon-lambda-event-handler.js';\nimport { EpsilonLoggingExtensionProcessor } from './epsilon-logging-extension-processor.js';\nexport class EpsilonGlobalHandler {\n _epsilon;\n static LOGGER_CONFIGURED = false;\n static GLOBAL_INSTANCE_PROVIDER;\n static set globalInstanceProvider(input) {\n EpsilonGlobalHandler.GLOBAL_INSTANCE_PROVIDER = input;\n }\n static get globalInstanceProvider() {\n return EpsilonGlobalHandler.GLOBAL_INSTANCE_PROVIDER;\n }\n handlers = null;\n constructor(_epsilon) {\n this._epsilon = _epsilon;\n if (!EpsilonGlobalHandler.LOGGER_CONFIGURED) {\n EpsilonGlobalHandler.configureDefaultLogger();\n Logger.info('EpsilonLoggingConfiguration:Default logger configured');\n }\n else {\n Logger.info('EpsilonLoggingConfiguration:Skipping default logger config - already configured');\n }\n this.handlers = [\n this._epsilon.webHandler,\n new WebV2Handler(this._epsilon.webHandler),\n this._epsilon.backgroundHandler,\n new InterApiEpsilonLambdaEventHandler(this._epsilon),\n new GenericSnsEpsilonLambdaEventHandler(this._epsilon),\n new CronEpsilonLambdaEventHandler(this._epsilon),\n new S3EpsilonLambdaEventHandler(this._epsilon),\n new DynamoEpsilonLambdaEventHandler(this._epsilon),\n ];\n }\n static configureDefaultLogger(overrides) {\n const output = overrides ? Object.assign({}, overrides) : {};\n output.initialLevel = output.initialLevel ?? LoggerLevelName.info;\n output.formatType = output.formatType ?? LogMessageFormatType.StructuredJson;\n output.globalVars = output.globalVars ?? {};\n output.outputFunction = output.outputFunction ?? LoggerOutputFunction.StdOut;\n output.ringBufferSize = output.ringBufferSize ?? 0;\n const src = output.preProcessors || [];\n output.preProcessors = src.concat([new EpsilonLoggingExtensionProcessor()]);\n const pre = Logger.getOptions();\n Logger.changeDefaultOptions(output, true);\n const post = Logger.getOptions();\n EpsilonGlobalHandler.LOGGER_CONFIGURED = true;\n Logger.info('EpsilonLoggingConfiguration: Updated');\n Logger.dumpOptionsIntoLog();\n }\n get epsilon() {\n return this._epsilon;\n }\n async processSingleBackgroundByParts(type, data, overrideTraceId, overrideTraceDepth) {\n return this.processSingleBackgroundEntry(this._epsilon.backgroundManager.createEntry(type, data), overrideTraceId, overrideTraceDepth);\n }\n async processSingleBackgroundEntry(e, overrideTraceId, overrideTraceDepth) {\n let rval = false;\n if (e?.type) {\n const internal = this._epsilon.backgroundManager.wrapEntryForInternal(e, overrideTraceId, overrideTraceDepth);\n rval = await this._epsilon.backgroundHandler.processSingleBackgroundEntry(internal);\n Logger.info('Direct processed request %j to %s', e, rval);\n }\n else {\n Logger.error('Cannot process null/unnamed background entry');\n }\n return rval;\n }\n async lambdaHandler(event, context) {\n let rval = null;\n try {\n if (this.epsilon.config.disableLastResortTimeout || !context || !context.getRemainingTimeInMillis()) {\n rval = await this.innerLambdaHandler(event, context);\n }\n else {\n const tmp = await PromiseRatchet.timeout(this.innerLambdaHandler(event, context), 'EpsilonLastResortTimeout', context.getRemainingTimeInMillis() - 1000);\n if (TimeoutToken.isTimeoutToken(tmp)) {\n tmp.writeToLog();\n rval = ResponseUtil.errorResponse(RestfulApiHttpError.wrapError(new RequestTimeoutError('Timed out')));\n }\n else {\n rval = tmp;\n }\n }\n }\n finally {\n ContextUtil.clearContext();\n }\n return rval;\n }\n async innerLambdaHandler(event, context) {\n ContextUtil.initContext(this._epsilon, event, context, 'TBD');\n let rval = null;\n let errorHandler = EpsilonGlobalHandler.defaultProcessUncaughtError;\n try {\n if (!this._epsilon) {\n Logger.error('Config not found, abandoning');\n return false;\n }\n const logLevel = EventUtil.calcLogLevelViaEventOrEnvParam(Logger.getLevel(), event, this._epsilon.config.loggerConfig);\n Logger.setLevel(logLevel);\n if (this._epsilon.config.loggerConfig &&\n this._epsilon.config.loggerConfig.queryParamTracePrefixName &&\n event.queryStringParameters &&\n event.queryStringParameters[this._epsilon.config.loggerConfig.queryParamTracePrefixName]) {\n Logger.info('Setting trace prefix to %s', event.queryStringParameters[this._epsilon.config.loggerConfig.queryParamTracePrefixName]);\n Logger.updateTracePrefix(event.queryStringParameters[this._epsilon.config.loggerConfig.queryParamTracePrefixName]);\n }\n let found = false;\n for (let i = 0; i < this.handlers.length && !found; i++) {\n const handler = this.handlers[i];\n if (handler.handlesEvent(event)) {\n found = true;\n errorHandler = handler.processUncaughtError || errorHandler;\n const label = handler.extractLabel(event, context);\n ContextUtil.setProcessLabel(label);\n Logger.logByLevel(this._epsilon?.config?.loggerConfig?.epsilonStartEndMessageLogLevel || LoggerLevelName.info, 'EvtStart: %s', label);\n rval = await handler.processEvent(event, context);\n Logger.logByLevel(this._epsilon?.config?.loggerConfig?.epsilonStartEndMessageLogLevel || LoggerLevelName.info, 'EvtEnd: %s', label);\n Logger.silly('EvtEnd:Value: %s Value: %j', label, rval);\n }\n }\n }\n catch (err) {\n rval = await errorHandler(event, context, err);\n }\n return rval;\n }\n static async defaultProcessUncaughtError(event, context, err) {\n Logger.error('Error slipped out to outer edge (Default). Logging and returning log : %s', err, err);\n const rval = {\n statusCode: 500,\n body: JSON.stringify({ error: ErrorRatchet.safeStringifyErr(err) }),\n isBase64Encoded: false,\n };\n return rval;\n }\n}\n//# sourceMappingURL=epsilon-global-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { EpsilonConstants } from './epsilon-constants.js';\nimport { InterApiUtil } from './inter-api/inter-api-util.js';\nimport { PublishCommand } from '@aws-sdk/client-sns';\nexport class InterApiManager {\n _aws;\n _sns;\n constructor(_aws, _sns) {\n this._aws = _aws;\n this._sns = _sns;\n }\n get config() {\n return this._aws;\n }\n get sns() {\n return this._sns;\n }\n createEntry(type, data) {\n const rval = {\n source: this._aws.source,\n type: type,\n data: data,\n };\n return rval;\n }\n async fireInterApiEventByParts(type, data) {\n const entry = this.createEntry(type, data);\n const rval = await this.fireInterApiEvent(entry);\n return rval;\n }\n async fireInterApiEvent(entry) {\n let rval = null;\n if (this.config.localMode) {\n Logger.info('Fire inter-api event ignored because running locally (was %j)', entry);\n rval = 'INTER-API-IGNORED';\n }\n else {\n try {\n Logger.info('Firing inter-api event (remote) : %j ', entry);\n const toWrite = {\n type: EpsilonConstants.INTER_API_SNS_EVENT,\n interApiEvent: InterApiUtil.addTraceToInterApiEntry(entry),\n };\n const msg = JSON.stringify(toWrite);\n const snsId = await this.writeMessageToSnsTopic(msg);\n Logger.debug('Inter-api Wrote message : %s to SNS : %s', rval, msg, snsId);\n }\n catch (err) {\n Logger.error('Failed to fireImmediateProcessRequest : %s', err, err);\n }\n }\n return rval;\n }\n async writeMessageToSnsTopic(message) {\n let rval = null;\n const params = {\n Message: message,\n TopicArn: this._aws.snsArn,\n };\n Logger.debug('Writing message to SNS topic : j', params);\n const result = await this.sns.send(new PublishCommand(params));\n rval = result.MessageId;\n return rval;\n }\n}\n//# sourceMappingURL=inter-api-manager.js.map","export class LocalServerCert {\n static CLIENT_CSR = '-----BEGIN CERTIFICATE REQUEST-----\\n' +\n 'MIICwjCCAaoCAQAwfTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAk5WMRIwEAYDVQQH\\n' +\n 'DAlMYXMgVmVnYXMxDjAMBgNVBAoMBVBsdW1hMRkwFwYDVQQDDBB3d3cuaGV5cGx1\\n' +\n 'bWEuY29tMSIwIAYJKoZIhvcNAQkBFhNjd2Vpc3NAaGV5cGx1bWEuY29tMIIBIjAN\\n' +\n 'BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Gh1SD1VciosMgh3MHF7IyKgNTu2\\n' +\n 'DjGMo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n6Kubmi3tGhzS7BN4TEO9/SSE2gIQTk9zwAMuf+mZJQcG0Qz1iftVp5nnM\\n' +\n 'zi205vBLLq2Pmk7wbhTIBO8J190Dli1/fuvk/cmJrA60Ys8v3y4e820CgYEA2gfV\\n' +\n 'Q3eHRxk3wl4On71mMovY7lMx6+S8K8hBGo26A5FIu6N6v2jxKnQ5YphwFgjtkxgs\\n' +\n 'LspAXmxRwFMapZP3d/nFeBhlOzNly7tqIdDOeNqEcUzEx7pwGXpWGZEHOYs1fvU+\\n' +\n 'gU/1N8q9DBvr0B+XGeYR3NNdljajo6pwWZ6ed5sCgYAGmkz5ZPLU0yVBR8rsRaJh\\n' +\n 'yWFdT2EEhgIDTQXDBImxqblahYw3hIR1Ij1B8g+NI9jj0P1BMC6X7sliDEcreFB5\\n' +\n 'QHVdx0T5UFFE6XmH2ue7Q5IWp6cL1ShsRyXHRoE9okb0BI8c3S9haXDBCj44ndAN\\n' +\n 'VUXrDlykevFXC/k7fHBTdQKBgHjIshpoEycOD1e753oS4JTL6GdO6271DlFq5LYj\\n' +\n 'IZNsXtCkJhH3vvJ35Hp8XEu4snQ0hfV90d79PuS+pRppOETct8pqKVp8hL4ymv8U\\n' +\n 'v+0vkQN7NeA3pnZW0W/kag400nP8xJ26f+xiggw9Q4vOlFSioe6loUjgCBNZDlh3\\n' +\n 'iO5VAoGASXkcv39B9/8FuWQ7rwhXHEubxOOwZZzSBU1wtLj2qHyPGoeU9ZpsmdrL\\n' +\n 'XS9w1Jy0e49qmbBjzTqAEBw2nn/JVMFHyI/s//JVF7Q9GfBZAF5XF6mJ24yzTKgF\\n' +\n 'kSoO5T+7s8NXi0eAIBe4CkWCBX7kWEZtu46GuVhsrC3oEazuLOs=\\n' +\n '-----END RSA PRIVATE KEY-----\\n';\n}\n//# sourceMappingURL=local-server-cert.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class NotFoundError extends RestfulApiHttpError {\n static HTTP_CODE = 404;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(NotFoundError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=not-found-error.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class ForbiddenError extends RestfulApiHttpError {\n static HTTP_CODE = 403;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(ForbiddenError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=forbidden-error.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class NotImplemented extends RestfulApiHttpError {\n static HTTP_CODE = 501;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(NotImplemented.HTTP_CODE);\n }\n}\n//# sourceMappingURL=not-implemented.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class MisconfiguredError extends RestfulApiHttpError {\n static HTTP_CODE = 500;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(MisconfiguredError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=misconfigured-error.js.map","import { Logger, NumberRatchet, StringRatchet, RestfulApiHttpError } from '@bitblit/ratchet-common';\nimport { BadRequestError } from '../../http/error/bad-request-error.js';\nimport { UnauthorizedError } from '../../http/error/unauthorized-error.js';\nimport { NotFoundError } from '../../http/error/not-found-error.js';\nimport { ForbiddenError } from '../../http/error/forbidden-error.js';\nimport { NotImplemented } from '../../http/error/not-implemented.js';\nimport { MisconfiguredError } from '../../http/error/misconfigured-error.js';\nexport class BuiltInHandlers {\n static async expectedHandledByFilter(evt, flag) {\n throw new MisconfiguredError().withFormattedErrorMessage('Should not happen - it was expected that route %s would be handled by a filter', evt.path);\n }\n static async handleNotImplemented(evt, flag) {\n Logger.info('A request was made to %s with body %j - not yet implemented', evt.path, evt.body);\n const rval = {\n time: new Date().toLocaleString(),\n path: evt.path,\n message: 'NOT IMPLEMENTED YET',\n };\n return rval;\n }\n static async sample(evt, flag, context) {\n const rval = {\n time: new Date().toLocaleString(),\n evt: evt,\n pad: StringRatchet.createRandomHexString(2000),\n flag: flag,\n };\n if (context) {\n rval['context'] = context;\n }\n const errNumber = NumberRatchet.safeNumber(evt.queryStringParameters['error']);\n if (errNumber) {\n switch (errNumber) {\n case -1:\n throw new Error('Test random failure');\n case 400:\n throw new BadRequestError('Bad request error');\n case 401:\n throw new UnauthorizedError('Unauthorized error');\n case 403:\n throw new ForbiddenError('Forbidden error');\n case 404:\n throw new NotFoundError('Not Found error');\n case 501:\n throw new NotImplemented('Not Implemented');\n default:\n throw new RestfulApiHttpError()\n .withFormattedErrorMessage('Default error - %s', errNumber)\n .withHttpStatusCode(500)\n .withDetails({ src: errNumber })\n .withEndUserErrors(['msg1', 'msg2']);\n }\n }\n let test = StringRatchet.trimToNull(evt.queryStringParameters['test']);\n if (test) {\n test = test.toLowerCase();\n if (test === 'null') {\n return null;\n }\n }\n return rval;\n }\n static async defaultErrorProcessor(event, err, cfg) {\n Logger.warn('Unhandled error (in promise catch) : %s \\nStack was: %s\\nEvt was: %j\\nConfig was: %j', err.message, err.stack, event, cfg);\n }\n}\n//# sourceMappingURL=built-in-handlers.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { UnauthorizedError } from '../error/unauthorized-error.js';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { RequireRatchet } from '@bitblit/ratchet-common';\nimport { JwtRatchet } from '@bitblit/ratchet-common';\nimport { ExpiredJwtHandling } from '@bitblit/ratchet-common';\nexport class LocalWebTokenManipulator {\n encryptionKeys;\n issuer;\n _ratchet;\n constructor(encryptionKeys, issuer) {\n this.encryptionKeys = encryptionKeys;\n this.issuer = issuer;\n RequireRatchet.notNullOrUndefined(encryptionKeys, 'encryptionKeys');\n RequireRatchet.noNullOrUndefinedValuesInArray(encryptionKeys, encryptionKeys.length);\n this._ratchet = new JwtRatchet(Promise.resolve(encryptionKeys));\n }\n withExtraDecryptionKeys(keys) {\n RequireRatchet.notNullOrUndefined(keys, 'keys');\n RequireRatchet.noNullOrUndefinedValuesInArray(keys, keys.length);\n this._ratchet = new JwtRatchet(this._ratchet.encryptionKeyPromise, Promise.resolve(keys), this._ratchet.jtiGenerator, this._ratchet.decryptOnlyKeyUseLogLevel, this._ratchet.parseFailureLogLevel);\n return this;\n }\n withParseFailureLogLevel(logLevel) {\n this._ratchet = new JwtRatchet(this._ratchet.encryptionKeyPromise, this._ratchet.decryptKeysPromise, this._ratchet.jtiGenerator, this._ratchet.decryptOnlyKeyUseLogLevel, logLevel);\n return this;\n }\n withOldKeyUseLogLevel(logLevel) {\n this._ratchet = new JwtRatchet(this._ratchet.encryptionKeyPromise, this._ratchet.decryptKeysPromise, this._ratchet.jtiGenerator, logLevel, this._ratchet.parseFailureLogLevel);\n return this;\n }\n get jwtRatchet() {\n return this._ratchet;\n }\n get selectRandomEncryptionKey() {\n return this._ratchet.selectRandomEncryptionKey();\n }\n createRefreshedJWTString(tokenString, expirationSeconds, allowExpired) {\n return this._ratchet.refreshJWTString(tokenString, allowExpired || false, expirationSeconds);\n }\n async parseAndValidateJWTStringAsync(tokenString) {\n const payload = await this._ratchet.decodeToken(tokenString, ExpiredJwtHandling.ADD_FLAG);\n if (JwtRatchet.hasExpiredFlag(payload)) {\n throw new UnauthorizedError('Failing JWT token read/validate - token expired on ' + payload.exp);\n }\n else {\n return payload;\n }\n }\n async createJWTStringAsync(principal, userObject, roles = ['USER'], expirationSeconds = 3600, proxyUser = null) {\n Logger.info('Creating JWT token for %s that expires in %s', principal, expirationSeconds);\n const now = new Date().getTime();\n const expires = now + expirationSeconds * 1000;\n const tokenData = {\n exp: expires,\n iss: this.issuer,\n sub: principal,\n iat: now,\n user: userObject,\n proxy: proxyUser,\n roles: roles,\n };\n const token = await this._ratchet.createTokenString(tokenData, expirationSeconds);\n return token;\n }\n async extractTokenFromAuthorizationHeader(header) {\n let tokenString = StringRatchet.trimToEmpty(header);\n if (tokenString.toLowerCase().startsWith('bearer ')) {\n tokenString = tokenString.substring(7);\n }\n const validated = !!tokenString ? await this.parseAndValidateJWTStringAsync(tokenString) : null;\n return validated;\n }\n}\n//# sourceMappingURL=local-web-token-manipulator.js.map","import { ErrorRatchet } from '@bitblit/ratchet-common';\nimport { Logger } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nexport class EchoProcessor {\n static TYPE_NAME = 'EpsilonEcho';\n get typeName() {\n return EchoProcessor.TYPE_NAME;\n }\n async handleEvent(data, mgr) {\n Logger.info('Echo processing : %j', data);\n if (data && StringRatchet.trimToNull(data['error'])) {\n ErrorRatchet.throwFormattedErr('Forced error : %s', data['error']);\n }\n }\n}\n//# sourceMappingURL=echo-processor.js.map","import { Logger } from '@bitblit/ratchet-common';\nexport class NoOpProcessor {\n get typeName() {\n return 'EpsilonNoOp';\n }\n async handleEvent(data, mgr) {\n Logger.silly('Hit the no-op proc');\n }\n}\n//# sourceMappingURL=no-op-processor.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { PromiseRatchet } from '@bitblit/ratchet-common';\nexport class SampleDelayProcessor {\n get typeName() {\n return 'EpsilonSampleDelay';\n }\n async handleEvent(data, mgr) {\n const delayMS = Math.floor(Math.random() * 5000);\n Logger.info('Running sample processor for %d', delayMS);\n await PromiseRatchet.wait(delayMS);\n Logger.info('Sample processor complete');\n }\n}\n//# sourceMappingURL=sample-delay-processor.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { EchoProcessor } from './echo-processor.js';\nexport class LogAndEnqueueEchoProcessor {\n get typeName() {\n return 'EpsilonLogAndEnqueueEcho';\n }\n async handleEvent(data, cfg) {\n Logger.info('LogAndEnqueueEchoProcessor : %j', data);\n await cfg.fireImmediateProcessRequestByParts(EchoProcessor.TYPE_NAME, { upstream: data });\n Logger.info('Completed : LogAndEnqueueEchoProcessor');\n }\n}\n//# sourceMappingURL=log-and-enqueue-echo-processor.js.map","export var BackgroundProcessHandling;\n(function (BackgroundProcessHandling) {\n BackgroundProcessHandling[\"Queued\"] = \"Queued\";\n BackgroundProcessHandling[\"Immediate\"] = \"Immediate\";\n})(BackgroundProcessHandling || (BackgroundProcessHandling = {}));\n//# sourceMappingURL=background-process-handling.js.map","export var BackgroundExecutionEventType;\n(function (BackgroundExecutionEventType) {\n BackgroundExecutionEventType[\"ProcessStarting\"] = \"ProcessStarting\";\n BackgroundExecutionEventType[\"DataValidationError\"] = \"DataValidationError\";\n BackgroundExecutionEventType[\"ExecutionSuccessfullyComplete\"] = \"ExecutionSuccessfullyComplete\";\n BackgroundExecutionEventType[\"ExecutionFailedError\"] = \"ExecutionRuntimeError\";\n BackgroundExecutionEventType[\"NoMatchProcessorName\"] = \"NoMatchProcessorName\";\n})(BackgroundExecutionEventType || (BackgroundExecutionEventType = {}));\n//# sourceMappingURL=background-execution-event-type.js.map","export var NullReturnedObjectHandling;\n(function (NullReturnedObjectHandling) {\n NullReturnedObjectHandling[\"Error\"] = \"Error\";\n NullReturnedObjectHandling[\"ConvertToEmptyString\"] = \"ConvertToEmptyString\";\n NullReturnedObjectHandling[\"Return404NotFoundResponse\"] = \"Return404NotFoundResponse\";\n})(NullReturnedObjectHandling || (NullReturnedObjectHandling = {}));\n//# sourceMappingURL=null-returned-object-handling.js.map","export var EpsilonApolloCorsMethod;\n(function (EpsilonApolloCorsMethod) {\n EpsilonApolloCorsMethod[\"None\"] = \"None\";\n EpsilonApolloCorsMethod[\"All\"] = \"All\";\n EpsilonApolloCorsMethod[\"Reflective\"] = \"Reflective\";\n})(EpsilonApolloCorsMethod || (EpsilonApolloCorsMethod = {}));\n//# sourceMappingURL=epsilon-apollo-cors-method.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { PromiseRatchet } from '@bitblit/ratchet-common';\nimport { BackgroundProcessHandling } from './background-process-handling.js';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { BooleanRatchet } from '@bitblit/ratchet-common';\nimport { BadRequestError } from '../http/error/bad-request-error.js';\nimport { NotFoundError } from '../http/error/not-found-error.js';\nimport { StopWatch } from '@bitblit/ratchet-common';\nexport class BackgroundHttpAdapterHandler {\n backgroundConfig;\n modelValidator;\n backgroundManager;\n maxWaitInMsForBackgroundJobToStart;\n constructor(backgroundConfig, modelValidator, backgroundManager, maxWaitInMsForBackgroundJobToStart = 10_000) {\n this.backgroundConfig = backgroundConfig;\n this.modelValidator = modelValidator;\n this.backgroundManager = backgroundManager;\n this.maxWaitInMsForBackgroundJobToStart = maxWaitInMsForBackgroundJobToStart;\n }\n get httpMetaEndpoint() {\n return this.backgroundConfig.httpMetaEndpoint;\n }\n get httpSubmissionPath() {\n return this.backgroundConfig.httpSubmissionPath;\n }\n get httpStatusPath() {\n return this.backgroundConfig.httpStatusEndpoint;\n }\n get implyTypeFromPathSuffix() {\n return this.backgroundConfig.implyTypeFromPathSuffix;\n }\n async handleBackgroundStatusRequest(evt, context) {\n Logger.info('handleBackgroundStatusRequest called');\n if (!this.backgroundConfig.transactionLogger) {\n throw new BadRequestError('Process logging not enabled');\n }\n else {\n const guid = StringRatchet.trimToNull(evt.pathParameters['guid']) || StringRatchet.trimToNull(evt.queryStringParameters['guid']);\n if (guid) {\n const sw = new StopWatch();\n let log = null;\n while (!log && sw.elapsedMS() < this.maxWaitInMsForBackgroundJobToStart) {\n log = await this.backgroundConfig.transactionLogger.readTransactionLog(guid);\n if (!log) {\n Logger.debug('No log found yet, waiting 500 ms and retrying (%s of %d waited so far)', sw.dump(), this.maxWaitInMsForBackgroundJobToStart);\n await PromiseRatchet.wait(500);\n }\n }\n if (!log) {\n throw new NotFoundError().withFormattedErrorMessage('No background result found for guid %s', guid);\n }\n return log;\n }\n else {\n throw new BadRequestError('No guid specified');\n }\n }\n }\n async handleBackgroundMetaRequest(evt, context) {\n Logger.info('handleBackgroundMetaRequest called');\n const currentCount = await this.backgroundManager.fetchApproximateNumberOfQueueEntries();\n const valid = this.backgroundConfig.processors.map((b) => b.typeName).filter((a) => !!a);\n valid.sort((a, b) => a.localeCompare(b));\n const rval = {\n currentQueueLength: currentCount,\n validTypes: valid,\n backgroundManagerName: this.backgroundManager.backgroundManagerName,\n };\n return rval;\n }\n async handleBackgroundSubmission(evt, context) {\n Logger.info('handleBackgroundSubmission : %j (mgr:%s)', evt.parsedBody, this.backgroundManager.backgroundManagerName);\n let rval = null;\n const startIdx = evt.path.indexOf(this.httpSubmissionPath) + this.httpSubmissionPath.length;\n let pathSuppliedBackgroundType = this.backgroundConfig.implyTypeFromPathSuffix\n ? evt.path.substring(startIdx).split('-').join('').toLowerCase()\n : '';\n if (pathSuppliedBackgroundType.includes('?')) {\n pathSuppliedBackgroundType = pathSuppliedBackgroundType.substring(0, pathSuppliedBackgroundType.indexOf('?'));\n }\n if (pathSuppliedBackgroundType.includes('#')) {\n pathSuppliedBackgroundType = pathSuppliedBackgroundType.substring(0, pathSuppliedBackgroundType.indexOf('#'));\n }\n const entry = evt.parsedBody || {};\n if (StringRatchet.trimToNull(pathSuppliedBackgroundType)) {\n if (StringRatchet.trimToNull(entry?.type) && entry.type.toLocaleLowerCase() !== pathSuppliedBackgroundType.toLocaleLowerCase()) {\n throw new BadRequestError('Background submission has type but does not match path supplied type');\n }\n else {\n entry.type = pathSuppliedBackgroundType;\n }\n }\n else {\n if (!StringRatchet.trimToNull(entry?.type)) {\n throw new BadRequestError('Background submission missing type and not configured in pathed mode');\n }\n }\n const foundProc = this.backgroundConfig.processors.find((s) => s.typeName.toLowerCase() === entry.type.toLowerCase());\n const immediate = BooleanRatchet.parseBool(evt.queryStringParameters['immediate']);\n const startProcessor = BooleanRatchet.parseBool(evt.queryStringParameters['startProcessor']);\n if (foundProc) {\n if (StringRatchet.trimToNull(foundProc.dataSchemaName)) {\n const errors = this.modelValidator.validate(foundProc.dataSchemaName, entry.data, false, false);\n if (errors.length > 0) {\n throw new BadRequestError().withErrors(errors);\n }\n }\n let result = null;\n if (immediate) {\n result = await this.backgroundManager.fireImmediateProcessRequest(entry);\n }\n else {\n result = await this.backgroundManager.addEntryToQueue(entry, startProcessor);\n }\n rval = {\n processHandling: immediate ? BackgroundProcessHandling.Immediate : BackgroundProcessHandling.Queued,\n startProcessorRequested: startProcessor,\n success: true,\n resultId: result,\n error: null,\n };\n }\n else {\n throw new BadRequestError().withFormattedErrorMessage('Could not find target background processor : %s', entry.type);\n }\n return rval;\n }\n}\n//# sourceMappingURL=background-http-adapter-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { ErrorRatchet } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nexport class BackgroundValidator {\n cfg;\n modelValidator;\n constructor(cfg, modelValidator) {\n this.cfg = cfg;\n this.modelValidator = modelValidator;\n }\n findProcessor(typeName) {\n const rval = this.cfg.processors.find((s) => s.typeName === typeName);\n return rval;\n }\n validType(type) {\n return !!this.findProcessor(type);\n }\n validateEntry(entry) {\n const rval = [];\n if (!entry) {\n rval.push('Entry is null');\n }\n else if (!StringRatchet.trimToNull(entry.type)) {\n rval.push('Entry type is null or empty');\n const proc = this.findProcessor(entry.type);\n if (!proc) {\n rval.push('Entry type is invalid');\n }\n }\n return rval;\n }\n validateEntryAndThrowException(entry) {\n const errors = this.validateEntry(entry);\n if (errors.length > 0) {\n Logger.warn('Invalid entry %j : errors : %j', entry, errors);\n ErrorRatchet.throwFormattedErr('Invalid entry %j : errors : %j', entry, errors);\n }\n }\n static validateAndMapProcessors(processorInput, modelValidator) {\n const rval = new Map();\n processorInput.forEach((p, idx) => {\n if (!p) {\n ErrorRatchet.throwFormattedErr('Null processor provided at index %d', idx);\n }\n if (!StringRatchet.trimToNull(p.typeName)) {\n ErrorRatchet.throwFormattedErr('Processor at index %d defines no name', idx);\n }\n if (rval.has(p.typeName)) {\n ErrorRatchet.throwFormattedErr('More than one processor defined for type %s', p.typeName);\n }\n rval.set(p.typeName, p);\n });\n return rval;\n }\n static validateAwsConfig(cfg) {\n const rval = [];\n if (!cfg) {\n rval.push('Null config');\n }\n else {\n if (!cfg.notificationArn) {\n rval.push('AWS config missing notificationArn');\n }\n if (!cfg.queueUrl) {\n rval.push('AWS config missing queueUrl');\n }\n if ((cfg.sendNotificationOnBackgroundError || cfg.sendNotificationOnBackgroundValidationFailure) &&\n !cfg.backgroundProcessFailureSnsArn) {\n rval.push('At least one send notification flag set to true but no sns arn set');\n }\n }\n return rval;\n }\n static validateConfig(cfg) {\n const rval = [];\n if (!cfg) {\n rval.push('Null config');\n }\n else {\n if (!cfg.processors || cfg.processors.length === 0) {\n rval.push('No processes specified');\n }\n }\n return rval;\n }\n}\n//# sourceMappingURL=background-validator.js.map","import { ErrorRatchet } from '@bitblit/ratchet-common';\nimport { Logger } from '@bitblit/ratchet-common';\nimport { RequireRatchet } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { DateTime } from 'luxon';\nimport { ContextUtil } from '../../util/context-util.js';\nexport class AbstractBackgroundManager {\n createEntry(type, data) {\n const rval = {\n type: type,\n data: data,\n };\n return rval;\n }\n wrapEntryForInternal(entry, overrideTraceId, overrideTraceDepth) {\n const rval = Object.assign({}, entry, {\n createdEpochMS: new Date().getTime(),\n guid: AbstractBackgroundManager.generateBackgroundGuid(),\n traceId: overrideTraceId || ContextUtil.currentTraceId(),\n traceDepth: overrideTraceDepth || ContextUtil.currentTraceDepth() + 1,\n });\n return rval;\n }\n async addEntryToQueueByParts(type, data, fireStartMessage) {\n let rval = null;\n const entry = this.createEntry(type, data);\n if (entry) {\n rval = await this.addEntryToQueue(entry, fireStartMessage);\n }\n return rval;\n }\n async addEntriesToQueue(entries, fireStartMessage) {\n const rval = [];\n for (let i = 0; i < entries.length; i++) {\n try {\n const tmp = await this.addEntryToQueue(entries[i], false);\n rval.push(tmp);\n }\n catch (err) {\n Logger.error('Error processing %j : %s', entries[i], err);\n rval.push(err['message']);\n }\n if (fireStartMessage) {\n const fireResult = await this.fireStartProcessingRequest();\n Logger.silly('FireResult : %s', fireResult);\n }\n }\n return rval;\n }\n async fireImmediateProcessRequestByParts(type, data) {\n let rval = null;\n const entry = this.createEntry(type, data);\n if (entry) {\n rval = await this.fireImmediateProcessRequest(entry);\n }\n return rval;\n }\n static generateBackgroundGuid(targetEpochMS = new Date().getTime()) {\n const dt = DateTime.fromMillis(targetEpochMS);\n return dt.toFormat('yyyy-MM-dd-HH-mm-ss-') + StringRatchet.createType4Guid();\n }\n static backgroundGuidToPath(prefix, guid) {\n let path = StringRatchet.trimToEmpty(prefix);\n if (path.length && !path.endsWith('/')) {\n path += '/';\n }\n path += guid.substring(0, 4) + '/' + guid.substring(5, 7) + '/' + guid.substring(8, 10) + '/';\n path += guid + '.json';\n return path;\n }\n static pathToBackgroundGuid(prefix, path) {\n RequireRatchet.notNullOrUndefined(path, 'path');\n let start = 0;\n if (!path.endsWith('.json')) {\n ErrorRatchet.throwFormattedErr('Cannot extract guid, does not end with .json : %s : %s', path, prefix);\n }\n if (StringRatchet.trimToNull(prefix)) {\n if (!path.startsWith(prefix)) {\n ErrorRatchet.throwFormattedErr('Cannot extract guid, does not start with prefix : %s : %s', path, prefix);\n }\n start = prefix.length;\n if (!prefix.endsWith('/')) {\n start++;\n }\n }\n start += 11;\n return path.substring(start, path.length - 5);\n }\n}\n//# sourceMappingURL=abstract-background-manager.js.map","import { ErrorRatchet } from '@bitblit/ratchet-common';\nimport { Logger } from '@bitblit/ratchet-common';\nimport { LambdaEventDetector } from '@bitblit/ratchet-aws';\nimport { EpsilonConstants } from '../epsilon-constants.js';\nimport { BackgroundValidator } from './background-validator.js';\nimport { BackgroundExecutionEventType } from './background-execution-event-type.js';\nimport { ContextUtil } from '../util/context-util.js';\nimport { AbstractBackgroundManager } from './manager/abstract-background-manager.js';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { StopWatch } from '@bitblit/ratchet-common';\nexport class BackgroundHandler {\n cfg;\n mgr;\n modelValidator;\n processors;\n validator;\n constructor(cfg, mgr, modelValidator) {\n this.cfg = cfg;\n this.mgr = mgr;\n this.modelValidator = modelValidator;\n const cfgErrors = BackgroundValidator.validateConfig(cfg);\n if (cfgErrors.length > 0) {\n ErrorRatchet.throwFormattedErr('Invalid background config : %j', cfgErrors);\n }\n Logger.silly('Starting Background processor, %d processors', cfg.processors.length);\n this.validator = new BackgroundValidator(cfg, modelValidator);\n this.processors = BackgroundValidator.validateAndMapProcessors(cfg.processors, modelValidator);\n if (mgr?.immediateProcessQueue && mgr.immediateProcessQueue()) {\n Logger.info('Attaching to immediate processing queue');\n mgr.immediateProcessQueue().subscribe(async (evt) => {\n Logger.debug('Processing local background entry : %j', evt);\n const rval = await this.processSingleBackgroundEntry(evt);\n Logger.info('Processor returned %s', rval);\n });\n }\n }\n extractLabel(evt, context) {\n let rval = null;\n if (this.isBackgroundStartSnsEvent(evt)) {\n rval = 'BG:START-EVT';\n }\n else if (this.isBackgroundImmediateFireEvent(evt)) {\n const pEvt = this.parseImmediateFireBackgroundEntry(evt);\n rval = 'BG:' + pEvt.type + ':' + pEvt.guid;\n }\n else {\n rval = 'BG:UNKNOWN';\n }\n return rval;\n }\n handlesEvent(evt) {\n return LambdaEventDetector.isValidSnsEvent(evt) && this.isBackgroundSNSEvent(evt);\n }\n isBackgroundSNSEvent(event) {\n return this.isBackgroundStartSnsEvent(event) || this.isBackgroundImmediateFireEvent(event);\n }\n isBackgroundStartSnsEvent(event) {\n let rval = false;\n if (event) {\n if (LambdaEventDetector.isSingleSnsEvent(event)) {\n const cast = event;\n rval = cast.Records[0].Sns.Message === EpsilonConstants.BACKGROUND_SNS_START_MARKER;\n }\n }\n return rval;\n }\n isBackgroundImmediateFireEvent(event) {\n let rval = false;\n if (!!event) {\n if (LambdaEventDetector.isSingleSnsEvent(event)) {\n const cast = event;\n const msg = cast.Records[0].Sns.Message;\n if (!!StringRatchet.trimToNull(msg)) {\n const parsed = JSON.parse(msg);\n rval = !!parsed && parsed['type'] === EpsilonConstants.BACKGROUND_SNS_IMMEDIATE_RUN_FLAG;\n }\n }\n }\n return rval;\n }\n parseImmediateFireBackgroundEntry(event) {\n let rval = null;\n try {\n if (!!event) {\n if (LambdaEventDetector.isSingleSnsEvent(event)) {\n const cast = event;\n const msg = cast.Records[0].Sns.Message;\n if (!!StringRatchet.trimToNull(msg)) {\n const parsed = JSON.parse(msg);\n if (!!parsed && parsed['type'] === EpsilonConstants.BACKGROUND_SNS_IMMEDIATE_RUN_FLAG) {\n rval = parsed['backgroundEntry'];\n }\n }\n }\n }\n }\n catch (err) {\n Logger.error('Could not parse %j as an immediate run event : %s', event, err, err);\n }\n return rval;\n }\n async processEvent(event, context) {\n let procd = null;\n if (!this.isBackgroundStartSnsEvent(event)) {\n const backgroundEntry = this.parseImmediateFireBackgroundEntry(event);\n if (!!backgroundEntry) {\n Logger.silly('Processing immediate fire event : %j', backgroundEntry);\n const result = await this.processSingleBackgroundEntry(backgroundEntry);\n procd = 1;\n }\n else {\n Logger.warn('Tried to process non-background start / immediate event : %j returning false', event);\n }\n }\n else {\n Logger.info('Reading task from background queue');\n procd = await this.takeAndProcessSingleBackgroundQueueEntry();\n if (procd > 0) {\n Logger.info('Processed %d elements from background queue, refiring', procd);\n const refire = await this.mgr.fireStartProcessingRequest();\n Logger.info('Refire returned %s', refire);\n }\n else {\n Logger.info('No items processed - stopping');\n }\n }\n const rval = {\n statusCode: 200,\n body: StringRatchet.safeString(procd),\n isBase64Encoded: false,\n };\n return rval;\n }\n async takeAndProcessSingleBackgroundQueueEntry() {\n let rval = null;\n const entries = await this.mgr.takeEntryFromBackgroundQueue();\n Logger.info('Found %d entries - processing', entries.length);\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i];\n const result = await this.processSingleBackgroundEntry(e);\n rval += result ? 1 : 0;\n }\n Logger.debug('Returning %d', rval);\n return rval;\n }\n async safeWriteToLogger(entry) {\n if (this.cfg.transactionLogger) {\n try {\n await this.cfg.transactionLogger.logTransaction(entry);\n }\n catch (err) {\n Logger.error('Failed to write to transaction logger : %j : %s', entry, err, err);\n }\n }\n else {\n Logger.silly('Skipping - no logger defined');\n }\n }\n async conditionallyStartTransactionLog(e) {\n if (!StringRatchet.trimToNull(e.guid)) {\n Logger.warn('No guid found - creating');\n e.guid = AbstractBackgroundManager.generateBackgroundGuid();\n const log = {\n request: e,\n running: true,\n };\n await this.safeWriteToLogger(log);\n }\n Logger.debug('Starting transaction log');\n }\n async conditionallyCompleteTransactionLog(e, result, error, runtimeMS) {\n Logger.debug('Completing transaction log');\n const log = {\n request: e,\n result: result,\n error: error ? ErrorRatchet.safeStringifyErr(error) : null,\n running: false,\n runtimeMS: runtimeMS,\n };\n await this.safeWriteToLogger(log);\n }\n async conditionallyRunErrorProcessor(e, error) {\n try {\n if (this.cfg.errorProcessor) {\n Logger.info('Running error processor');\n await this.cfg.errorProcessor.handleError(e, error);\n }\n }\n catch (err) {\n Logger.error('Background : BAD - Failed to run error processor : %s', err, err);\n }\n }\n async fireListenerEvent(event) {\n const listeners = this.cfg.executionListeners || [];\n for (const listener of listeners) {\n try {\n await listener.onEvent(event);\n }\n catch (err) {\n Logger.error('Failure triggering handler %s : %s', StringRatchet.trimToNull(listener?.label) || 'No-name', err);\n }\n }\n }\n async processSingleBackgroundEntry(e) {\n ContextUtil.setOverrideTraceFromInternalBackgroundEntry(e);\n Logger.info('Background Process Start: %j', e);\n const sw = new StopWatch();\n await this.conditionallyStartTransactionLog(e);\n let rval = false;\n try {\n await this.fireListenerEvent({\n type: BackgroundExecutionEventType.ProcessStarting,\n processorType: e.type,\n data: e.data,\n guid: e.guid,\n });\n const processorInput = this.processors.get(e.type);\n if (!processorInput) {\n ErrorRatchet.throwFormattedErr('Found no processor for background entry : %j (returning false)', e);\n await this.fireListenerEvent({\n type: BackgroundExecutionEventType.NoMatchProcessorName,\n processorType: e.type,\n data: e.data,\n guid: e.guid,\n });\n }\n let dataValidationErrors = [];\n if (StringRatchet.trimToNull(processorInput.dataSchemaName)) {\n dataValidationErrors = this.modelValidator.validate(processorInput.dataSchemaName, e.data, false, false);\n }\n if (dataValidationErrors.length > 0) {\n await this.fireListenerEvent({\n type: BackgroundExecutionEventType.DataValidationError,\n processorType: e.type,\n data: e.data,\n errors: dataValidationErrors,\n guid: e.guid,\n });\n ErrorRatchet.throwFormattedErr('Not processing, data failed validation; entry was %j : errors : %j', e, dataValidationErrors);\n }\n else {\n let result = await processorInput.handleEvent(e.data, this.mgr);\n result = result || 'SUCCESSFUL COMPLETION : NO RESULT RETURNED';\n await this.conditionallyCompleteTransactionLog(e, result, null, sw.elapsedMS());\n await this.fireListenerEvent({\n type: BackgroundExecutionEventType.ExecutionSuccessfullyComplete,\n processorType: e.type,\n data: result,\n guid: e.guid,\n });\n rval = true;\n }\n }\n catch (err) {\n Logger.error('Background Process Error: %j : %s', e, err, err);\n await this.conditionallyRunErrorProcessor(e, err);\n await this.conditionallyCompleteTransactionLog(e, null, err, sw.elapsedMS());\n await this.fireListenerEvent({\n type: BackgroundExecutionEventType.ExecutionFailedError,\n processorType: e.type,\n data: e.data,\n errors: [ErrorRatchet.safeStringifyErr(err)],\n guid: e.guid,\n });\n }\n Logger.info('Background Process Stop: %j : %s', e, sw.dump());\n return rval;\n }\n getConfig() {\n const rval = Object.assign({}, this.cfg);\n return rval;\n }\n}\n//# sourceMappingURL=background-handler.js.map","import { Logger, MapRatchet, StringRatchet, RestfulApiHttpError } from '@bitblit/ratchet-common';\nimport { EventUtil } from '../../http/event-util.js';\nimport { BadRequestError } from '../../http/error/bad-request-error.js';\nimport { ResponseUtil } from '../../http/response-util.js';\nimport { MisconfiguredError } from '../../http/error/misconfigured-error.js';\nexport class BuiltInFilters {\n static MAXIMUM_LAMBDA_BODY_SIZE_BYTES = 1024 * 1024 * 5 - 1024 * 100;\n static async combineFilters(fCtx, filters) {\n let cont = true;\n if (filters && filters.length > 0) {\n for (let i = 0; i < filters.length && cont; i++) {\n cont = await filters[i](fCtx);\n }\n }\n return cont;\n }\n static async applyGzipIfPossible(fCtx) {\n if (fCtx.event?.headers && fCtx.result) {\n const encodingHeader = fCtx.event && fCtx.event.headers ? MapRatchet.extractValueFromMapIgnoreCase(fCtx.event.headers, 'accept-encoding') : null;\n fCtx.result = await ResponseUtil.applyGzipIfPossible(encodingHeader, fCtx.result);\n }\n return true;\n }\n static async addConstantHeaders(fCtx, headers) {\n if (headers && fCtx.result) {\n fCtx.result.headers = Object.assign({}, headers, fCtx.result.headers);\n }\n else {\n Logger.warn('Could not add headers - either result or headers were missing');\n }\n return true;\n }\n static async addAWSRequestIdHeader(fCtx, headerName = 'X-REQUEST-ID') {\n if (fCtx.result && StringRatchet.trimToNull(headerName) && headerName.startsWith('X-')) {\n fCtx.result.headers = fCtx.result.headers || {};\n fCtx.result.headers[headerName] = fCtx.context?.awsRequestId || 'Request-Id-Missing';\n }\n else {\n Logger.warn('Could not add request id header - either result or context were missing or name was invalid');\n }\n return true;\n }\n static async addAllowEverythingCORSHeaders(fCtx) {\n return BuiltInFilters.addConstantHeaders(fCtx, {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': '*',\n 'Access-Control-Allow-Headers': '*',\n });\n }\n static async addAllowReflectionCORSHeaders(fCtx) {\n return BuiltInFilters.addConstantHeaders(fCtx, {\n 'Access-Control-Allow-Origin': MapRatchet.caseInsensitiveAccess(fCtx.event.headers, 'Origin') || '*',\n 'Access-Control-Allow-Methods': MapRatchet.caseInsensitiveAccess(fCtx.event.headers, 'Access-Control-Request-Method') || '*',\n 'Access-Control-Allow-Headers': MapRatchet.caseInsensitiveAccess(fCtx.event.headers, 'Access-Control-Request-Headers') || '*',\n });\n }\n static async uriDecodeQueryParams(fCtx) {\n if (fCtx?.event?.queryStringParameters) {\n Object.keys(fCtx.event.queryStringParameters).forEach((k) => {\n const val = fCtx.event.queryStringParameters[k];\n if (val) {\n fCtx.event.queryStringParameters[k] = decodeURIComponent(val);\n }\n });\n }\n if (fCtx?.event?.multiValueQueryStringParameters) {\n Object.keys(fCtx.event.multiValueQueryStringParameters).forEach((k) => {\n const val = fCtx.event.multiValueQueryStringParameters[k];\n if (val && val.length) {\n const cleaned = val.map((v) => decodeURIComponent(v));\n fCtx.event.multiValueQueryStringParameters[k] = cleaned;\n }\n });\n }\n return true;\n }\n static async fixStillEncodedQueryParams(fCtx) {\n EventUtil.fixStillEncodedQueryParams(fCtx.event);\n return true;\n }\n static async disallowStringNullAsPathParameter(fCtx) {\n if (fCtx?.event?.pathParameters) {\n Object.keys(fCtx.event.pathParameters).forEach((k) => {\n if ('null' === StringRatchet.trimToEmpty(fCtx.event.pathParameters[k]).toLowerCase()) {\n throw new BadRequestError().withFormattedErrorMessage('Path parameter %s was string -null-', k);\n }\n });\n }\n return true;\n }\n static async disallowStringNullAsQueryStringParameter(fCtx) {\n if (fCtx?.event?.queryStringParameters) {\n Object.keys(fCtx.event.queryStringParameters).forEach((k) => {\n if ('null' === StringRatchet.trimToEmpty(fCtx.event.queryStringParameters[k]).toLowerCase()) {\n throw new BadRequestError().withFormattedErrorMessage('Query parameter %s was string -null-', k);\n }\n });\n }\n return true;\n }\n static async ensureEventMaps(fCtx) {\n fCtx.event.queryStringParameters = fCtx.event.queryStringParameters || {};\n fCtx.event.headers = fCtx.event.headers || {};\n fCtx.event.pathParameters = fCtx.event.pathParameters || {};\n return true;\n }\n static async parseJsonBodyToObject(fCtx) {\n if (fCtx.event?.body) {\n try {\n fCtx.event.parsedBody = EventUtil.jsonBodyToObject(fCtx.event);\n }\n catch (err) {\n throw new RestfulApiHttpError('Supplied body was not parsable as valid JSON').withHttpStatusCode(400);\n }\n }\n return true;\n }\n static async checkMaximumLambdaBodySize(fCtx) {\n if (fCtx.result?.body && fCtx.result.body.length > BuiltInFilters.MAXIMUM_LAMBDA_BODY_SIZE_BYTES) {\n const delta = fCtx.result.body.length - BuiltInFilters.MAXIMUM_LAMBDA_BODY_SIZE_BYTES;\n throw new RestfulApiHttpError('Response size is ' + fCtx.result.body.length + ' bytes, which is ' + delta + ' bytes too large for this handler').withHttpStatusCode(500);\n }\n return true;\n }\n static async validateInboundBody(fCtx) {\n if (fCtx?.event?.parsedBody && fCtx.routeAndParse) {\n if (fCtx.routeAndParse.mapping.validation) {\n if (!fCtx.modelValidator) {\n throw new MisconfiguredError('Requested body validation but supplied no validator');\n }\n const errors = fCtx.modelValidator.validate(fCtx.routeAndParse.mapping.validation.modelName, fCtx.event.parsedBody, fCtx.routeAndParse.mapping.validation.emptyAllowed, fCtx.routeAndParse.mapping.validation.extraPropertiesAllowed);\n if (errors.length > 0) {\n Logger.info('Found errors while validating %s object %j', fCtx.routeAndParse.mapping.validation.modelName, errors);\n const newError = new BadRequestError(...errors);\n throw newError;\n }\n }\n }\n else {\n Logger.debug('No validation since no route specified or no parsed body');\n }\n return true;\n }\n static async validateInboundQueryParams(fCtx) {\n return true;\n }\n static async validateInboundPathParams(fCtx) {\n return true;\n }\n static async validateOutboundResponse(fCtx) {\n if (fCtx?.rawResult) {\n if (fCtx.routeAndParse.mapping.outboundValidation) {\n Logger.debug('Applying outbound check to %j', fCtx.rawResult);\n const errors = fCtx.modelValidator.validate(fCtx.routeAndParse.mapping.outboundValidation.modelName, fCtx.rawResult, fCtx.routeAndParse.mapping.outboundValidation.emptyAllowed, fCtx.routeAndParse.mapping.outboundValidation.extraPropertiesAllowed);\n if (errors.length > 0) {\n Logger.error('Found outbound errors while validating %s object %j', fCtx.routeAndParse.mapping.outboundValidation.modelName, errors);\n errors.unshift('Server sent object invalid according to spec');\n throw new RestfulApiHttpError().withErrors(errors).withHttpStatusCode(500).withDetails(fCtx.rawResult);\n }\n }\n else {\n Logger.debug('Applied no outbound validation because none set');\n }\n }\n else {\n Logger.debug('No validation since no outbound body or disabled');\n }\n return true;\n }\n static async autoRespondToOptionsRequestWithCors(fCtx) {\n if (StringRatchet.trimToEmpty(fCtx?.event?.httpMethod).toLowerCase() === 'options') {\n fCtx.result = {\n statusCode: 200,\n body: '{\"cors\":true, \"m\":2}',\n };\n await BuiltInFilters.addAllowReflectionCORSHeaders(fCtx);\n return false;\n }\n else {\n return true;\n }\n }\n static async autoRespond(fCtx, inBody) {\n const body = inBody || {\n message: 'Not Implemented',\n };\n fCtx.result = {\n statusCode: 200,\n body: JSON.stringify(body),\n };\n return false;\n }\n static async secureOutboundServerErrorForProduction(fCtx, errorMessage, errCode) {\n if (fCtx?.result?.statusCode) {\n if (errCode === null || fCtx.result.statusCode === errCode) {\n Logger.warn('Securing outbound error info (was : %j)', fCtx.result.body);\n fCtx.rawResult = new RestfulApiHttpError(errorMessage).withHttpStatusCode(fCtx.result.statusCode);\n const oldResult = fCtx.result;\n fCtx.result = ResponseUtil.errorResponse(fCtx.rawResult);\n fCtx.result.headers = Object.assign({}, oldResult.headers || {}, fCtx.result.headers || {});\n }\n }\n return true;\n }\n}\n//# sourceMappingURL=built-in-filters.js.map","import { StringRatchet } from '@bitblit/ratchet-common';\nimport { UnauthorizedError } from '../../http/error/unauthorized-error.js';\nimport { MisconfiguredError } from '../../http/error/misconfigured-error.js';\nimport { ForbiddenError } from '../../http/error/forbidden-error.js';\nimport { EventUtil } from '../../http/event-util.js';\nexport class BuiltInAuthFilters {\n static async requireAllRolesInCommonJwt(fCtx, requiredRoleAllOf) {\n if (!requiredRoleAllOf || requiredRoleAllOf.length === 0) {\n throw new MisconfiguredError('You must require at least 1 role');\n }\n if (!fCtx.event?.authorization?.auth) {\n throw new UnauthorizedError('May not proceed, not authenticated');\n }\n else {\n const asJwt = fCtx.event.authorization.auth;\n if (!asJwt.roles || asJwt.roles.length === 0) {\n throw new UnauthorizedError('Required role not found');\n }\n else {\n requiredRoleAllOf.forEach((r) => {\n if (!asJwt.roles.includes(r)) {\n throw new UnauthorizedError('Required role not found');\n }\n });\n }\n }\n return true;\n }\n static async requireAnyRoleInCommonJwt(fCtx, requiredRoleOneOf) {\n if (!requiredRoleOneOf || requiredRoleOneOf.length === 0) {\n throw new MisconfiguredError('You must require at least 1 role');\n }\n if (!fCtx.event?.authorization?.auth) {\n throw new UnauthorizedError('May not proceed, not authenticated');\n }\n else {\n const asJwt = fCtx.event.authorization.auth;\n if (!asJwt.roles || asJwt.roles.length === 0) {\n throw new UnauthorizedError('Required role not found');\n }\n else {\n let found = false;\n requiredRoleOneOf.forEach((r) => {\n if (!found && asJwt.roles.includes(r)) {\n found = true;\n }\n });\n if (!found) {\n throw new UnauthorizedError('Required role not found');\n }\n }\n }\n return true;\n }\n static async parseAuthorizationHeader(fCtx, webTokenManipulators) {\n if (!fCtx?.event || !webTokenManipulators || (Array.isArray(webTokenManipulators) && !webTokenManipulators.length)) {\n throw new MisconfiguredError('Cannot continue - missing event or encryption');\n }\n else {\n const tokenString = EventUtil.extractBearerTokenFromEvent(fCtx?.event);\n if (!Array.isArray(webTokenManipulators)) {\n webTokenManipulators = [webTokenManipulators];\n }\n for (let i = 0; i < webTokenManipulators.length && !fCtx?.event?.authorization?.auth; i++) {\n const manipulator = webTokenManipulators[i];\n try {\n const token = await manipulator.extractTokenFromAuthorizationHeader(tokenString);\n fCtx.event.authorization = {\n raw: tokenString,\n auth: token,\n error: null,\n };\n }\n catch (err) {\n fCtx.event.authorization = {\n raw: tokenString,\n auth: null,\n error: err['message'],\n };\n }\n }\n }\n return true;\n }\n static async applyOpenApiAuthorization(fCtx) {\n if (StringRatchet.trimToNull(fCtx?.routeAndParse?.mapping?.authorizerName)) {\n const authorizer = fCtx?.authenticators?.get(fCtx.routeAndParse.mapping.authorizerName);\n if (authorizer) {\n if (fCtx?.event?.authorization?.auth) {\n const allowed = await authorizer(fCtx.event.authorization, fCtx.event, fCtx.routeAndParse.mapping);\n if (!allowed) {\n throw new ForbiddenError('You lack privileges to see this endpoint');\n }\n }\n else {\n throw new UnauthorizedError('You need to supply credentials for this endpoint');\n }\n }\n else {\n throw new MisconfiguredError().withFormattedErrorMessage('Authorizer %s requested but not found', fCtx.routeAndParse.mapping.authorizerName);\n }\n }\n else {\n }\n return true;\n }\n}\n//# sourceMappingURL=built-in-auth-filters.js.map","import { Logger } from '@bitblit/ratchet-common';\nexport class LogLevelManipulationFilter {\n static LOG_LEVEL_BEFORE_CHANGE = null;\n static async setLogLevelForTransaction(fCtx) {\n LogLevelManipulationFilter.LOG_LEVEL_BEFORE_CHANGE = Logger.getLevel();\n return true;\n }\n static async clearLogLevelForTransaction(fCtx) {\n if (LogLevelManipulationFilter.LOG_LEVEL_BEFORE_CHANGE) {\n Logger.setLevel(LogLevelManipulationFilter.LOG_LEVEL_BEFORE_CHANGE);\n LogLevelManipulationFilter.LOG_LEVEL_BEFORE_CHANGE = null;\n Logger.updateTracePrefix(null);\n }\n return true;\n }\n}\n//# sourceMappingURL=log-level-manipulation-filter.js.map","import { MisconfiguredError } from '../error/misconfigured-error.js';\nimport { Logger } from '@bitblit/ratchet-common';\nimport { BooleanRatchet } from '@bitblit/ratchet-common';\nimport { NullReturnedObjectHandling } from '../../config/http/null-returned-object-handling.js';\nimport { BuiltInFilters } from '../../built-in/http/built-in-filters.js';\nimport { BuiltInHandlers } from '../../built-in/http/built-in-handlers.js';\nimport { BuiltInAuthFilters } from '../../built-in/http/built-in-auth-filters.js';\nimport { LogLevelManipulationFilter } from '../../built-in/http/log-level-manipulation-filter.js';\nexport class RouterUtil {\n constructor() { }\n static defaultAuthenticationHeaderParsingEpsilonPreFilters(webTokenManipulator) {\n return [\n (fCtx) => BuiltInAuthFilters.parseAuthorizationHeader(fCtx, webTokenManipulator),\n (fCtx) => BuiltInAuthFilters.applyOpenApiAuthorization(fCtx),\n ].concat(RouterUtil.defaultEpsilonPreFilters());\n }\n static defaultEpsilonPreFilters() {\n return [\n (fCtx) => BuiltInFilters.autoRespondToOptionsRequestWithCors(fCtx),\n (fCtx) => BuiltInFilters.ensureEventMaps(fCtx),\n (fCtx) => LogLevelManipulationFilter.setLogLevelForTransaction(fCtx),\n (fCtx) => BuiltInFilters.parseJsonBodyToObject(fCtx),\n (fCtx) => BuiltInFilters.fixStillEncodedQueryParams(fCtx),\n (fCtx) => BuiltInFilters.uriDecodeQueryParams(fCtx),\n (fCtx) => BuiltInFilters.disallowStringNullAsPathParameter(fCtx),\n (fCtx) => BuiltInFilters.disallowStringNullAsQueryStringParameter(fCtx),\n (fCtx) => BuiltInFilters.validateInboundBody(fCtx),\n (fCtx) => BuiltInFilters.validateInboundQueryParams(fCtx),\n (fCtx) => BuiltInFilters.validateInboundQueryParams(fCtx),\n ];\n }\n static defaultEpsilonPostFilters() {\n return [\n (fCtx) => BuiltInFilters.validateOutboundResponse(fCtx),\n (fCtx) => BuiltInFilters.addAWSRequestIdHeader(fCtx),\n (fCtx) => BuiltInFilters.addAllowReflectionCORSHeaders(fCtx),\n (fCtx) => BuiltInFilters.applyGzipIfPossible(fCtx),\n (fCtx) => BuiltInFilters.checkMaximumLambdaBodySize(fCtx),\n (fCtx) => LogLevelManipulationFilter.clearLogLevelForTransaction(fCtx),\n ];\n }\n static defaultEpsilonErrorFilters() {\n return [\n (fCtx) => BuiltInFilters.addAWSRequestIdHeader(fCtx),\n (fCtx) => BuiltInFilters.addAllowReflectionCORSHeaders(fCtx),\n (fCtx) => LogLevelManipulationFilter.clearLogLevelForTransaction(fCtx),\n ];\n }\n static defaultHttpMetaProcessingConfigWithAuthenticationHeaderParsing(webTokenManipulator) {\n const defaults = {\n configName: 'EpsilonDefaultHttpMetaProcessingConfig',\n timeoutMS: 30_000,\n overrideAuthorizerName: null,\n preFilters: RouterUtil.defaultAuthenticationHeaderParsingEpsilonPreFilters(webTokenManipulator),\n postFilters: RouterUtil.defaultEpsilonPostFilters(),\n errorFilters: RouterUtil.defaultEpsilonErrorFilters(),\n nullReturnedObjectHandling: NullReturnedObjectHandling.Return404NotFoundResponse,\n };\n return defaults;\n }\n static defaultHttpMetaProcessingConfig() {\n const defaults = {\n configName: 'EpsilonDefaultHttpMetaProcessingConfig',\n timeoutMS: 30_000,\n overrideAuthorizerName: null,\n preFilters: RouterUtil.defaultEpsilonPreFilters(),\n postFilters: RouterUtil.defaultEpsilonPostFilters(),\n errorFilters: RouterUtil.defaultEpsilonErrorFilters(),\n nullReturnedObjectHandling: NullReturnedObjectHandling.Return404NotFoundResponse,\n };\n return defaults;\n }\n static assignDefaultsOnHttpConfig(cfg) {\n const defaults = {\n handlers: new Map(),\n authorizers: new Map(),\n defaultMetaHandling: this.defaultHttpMetaProcessingConfig(),\n staticContentRoutes: {},\n prefixesToStripBeforeRouteMatch: [],\n filterHandledRouteMatches: ['options .*'],\n };\n const rval = Object.assign({}, defaults, cfg || {});\n return rval;\n }\n static findApplicableMeta(httpConfig, method, path) {\n let rval = null;\n if (httpConfig?.overrideMetaHandling) {\n for (let i = 0; i < httpConfig.overrideMetaHandling.length && !rval; i++) {\n const test = httpConfig.overrideMetaHandling[i];\n if (!test.methods ||\n test.methods.length === 0 ||\n test.methods.map((s) => s.toLocaleLowerCase()).includes(method.toLocaleLowerCase())) {\n const matches = !!path.match(test.pathRegex);\n if ((matches && !test.invertPathMatching) || (!matches && test.invertPathMatching)) {\n rval = test.config;\n }\n }\n }\n }\n if (!rval) {\n rval = httpConfig.defaultMetaHandling || RouterUtil.defaultHttpMetaProcessingConfig();\n }\n return rval;\n }\n static openApiYamlToRouterConfig(httpConfig, openApiDoc, modelValidator, backgroundHttpAdapterHandler) {\n if (!openApiDoc || !httpConfig) {\n throw new MisconfiguredError('Cannot configure, missing either yaml or cfg');\n }\n const rval = {\n routes: [],\n openApiModelValidator: modelValidator,\n config: RouterUtil.assignDefaultsOnHttpConfig(httpConfig),\n };\n if (openApiDoc?.components?.securitySchemes) {\n Object.keys(openApiDoc.components.securitySchemes).forEach((sk) => {\n if (!rval.config.authorizers || !rval.config.authorizers.get(sk)) {\n throw new MisconfiguredError().withFormattedErrorMessage('Doc requires authorizer %s but not found in map', sk);\n }\n });\n }\n const missingPaths = [];\n const filterHandledPathMatches = httpConfig.filterHandledRouteMatches || [];\n if (openApiDoc?.paths) {\n Object.keys(openApiDoc.paths).forEach((path) => {\n Object.keys(openApiDoc.paths[path]).forEach((method) => {\n const convertedPath = RouterUtil.openApiPathToRouteParserPath(path);\n const finder = method + ' ' + path;\n const applicableMeta = RouterUtil.findApplicableMeta(httpConfig, method, path);\n const entry = openApiDoc.paths[path][method];\n const isBackgroundEndpoint = path.startsWith(backgroundHttpAdapterHandler.httpSubmissionPath);\n const isBackgroundMetaEndpoint = path === backgroundHttpAdapterHandler.httpMetaEndpoint;\n const isBackgroundStatusEndpoint = path === backgroundHttpAdapterHandler.httpStatusPath;\n if (isBackgroundEndpoint) {\n rval.config.handlers.set(finder, (evt, ctx) => backgroundHttpAdapterHandler.handleBackgroundSubmission(evt, ctx));\n }\n if (isBackgroundMetaEndpoint) {\n rval.config.handlers.set(finder, (evt, ctx) => backgroundHttpAdapterHandler.handleBackgroundMetaRequest(evt, ctx));\n }\n if (isBackgroundStatusEndpoint) {\n rval.config.handlers.set(finder, (evt, ctx) => backgroundHttpAdapterHandler.handleBackgroundStatusRequest(evt, ctx));\n }\n if (!rval.config.handlers || !rval.config.handlers.get(finder)) {\n const match = filterHandledPathMatches.find((reg) => finder.match(reg));\n if (match) {\n Logger.debug('Adding filter-handled handler for %s', finder);\n rval.config.handlers.set(finder, (evt) => BuiltInHandlers.expectedHandledByFilter(evt));\n }\n else {\n missingPaths.push(finder);\n }\n }\n if (entry && entry['security'] && entry['security'].length > 1) {\n throw new MisconfiguredError('Epsilon does not currently support multiple security (path was ' + finder + ')');\n }\n const authorizerName = entry['security'] && entry['security'].length == 1 ? Object.keys(entry['security'][0])[0] : null;\n const newRoute = {\n path: convertedPath,\n method: method,\n function: rval.config.handlers.get(finder),\n authorizerName: applicableMeta.overrideAuthorizerName || authorizerName,\n metaProcessingConfig: applicableMeta,\n validation: null,\n outboundValidation: null,\n };\n if (entry['requestBody'] &&\n entry['requestBody']['content'] &&\n entry['requestBody']['content']['application/json'] &&\n entry['requestBody']['content']['application/json']['schema']) {\n const schema = entry['requestBody']['content'];\n Logger.silly('Applying schema %j to %s', schema, finder);\n const modelName = this.findAndValidateModelName(method, path, schema, rval.config.overrideModelValidator || rval.openApiModelValidator);\n const required = BooleanRatchet.parseBool(entry['requestBody']['required']);\n const validation = {\n extraPropertiesAllowed: true,\n emptyAllowed: !required,\n modelName: modelName,\n };\n newRoute.validation = validation;\n }\n if (entry['responses'] &&\n entry['responses']['200'] &&\n entry['responses']['200']['content'] &&\n entry['responses']['200']['content']['application/json'] &&\n entry['responses']['200']['content']['application/json']['schema']) {\n const schema = entry['responses']['200']['content'];\n Logger.silly('Applying schema %j to %s', schema, finder);\n const modelName = this.findAndValidateModelName(method, path, schema, rval.config.overrideModelValidator || rval.openApiModelValidator);\n const validation = {\n extraPropertiesAllowed: false,\n emptyAllowed: false,\n modelName: modelName,\n };\n newRoute.outboundValidation = validation;\n }\n rval.routes.push(newRoute);\n });\n });\n }\n if (missingPaths.length > 0) {\n throw new MisconfiguredError().withFormattedErrorMessage('Missing expected handlers : %j', missingPaths);\n }\n return rval;\n }\n static findAndValidateModelName(method, path, schema, modelValidator) {\n let rval = undefined;\n const schemaPath = schema['application/json']['schema']['$ref'];\n const inlinePath = schema['application/json']['schema']['type'];\n if (schemaPath) {\n rval = schemaPath.substring(schemaPath.lastIndexOf('/') + 1);\n if (!modelValidator.fetchModel(rval)) {\n throw new MisconfiguredError(`Path ${method} ${path} refers to schema ${rval} but its not in the schema section`);\n }\n }\n else if (inlinePath) {\n rval = `${method}-${path}-requestBodyModel`;\n const model = schema['application/json']['schema'];\n modelValidator.addModel(rval, model);\n }\n return rval;\n }\n static openApiPathToRouteParserPath(input) {\n let rval = input;\n if (rval) {\n let sIdx = rval.indexOf('{');\n while (sIdx > -1) {\n const eIdx = rval.indexOf('}');\n rval = rval.substring(0, sIdx) + ':' + rval.substring(sIdx + 1, eIdx) + rval.substring(eIdx + 1);\n sIdx = rval.indexOf('{');\n }\n }\n return rval;\n }\n}\n//# sourceMappingURL=router-util.js.map","import { Logger, PromiseRatchet, TimeoutToken, RestfulApiHttpError } from '@bitblit/ratchet-common';\nimport { RequestTimeoutError } from '../../http/error/request-timeout-error.js';\nimport { ResponseUtil } from '../../http/response-util.js';\nimport { NotFoundError } from '../../http/error/not-found-error.js';\nimport { NullReturnedObjectHandling } from '../../config/http/null-returned-object-handling.js';\nexport class RunHandlerAsFilter {\n static async runHandler(fCtx, rm) {\n const handler = RunHandlerAsFilter.findHandler(rm, fCtx.event, fCtx.context);\n Logger.debug('Processing event with epsilon: %j', fCtx.event);\n let tmp = await handler;\n if (TimeoutToken.isTimeoutToken(tmp)) {\n tmp.writeToLog();\n throw new RequestTimeoutError('Timed out');\n }\n Logger.debug('Initial return value : %j', tmp);\n tmp = RunHandlerAsFilter.applyNullReturnedObjectHandling(tmp, rm.mapping.metaProcessingConfig.nullReturnedObjectHandling);\n fCtx.rawResult = tmp;\n fCtx.result = ResponseUtil.coerceToProxyResult(tmp);\n return true;\n }\n static applyNullReturnedObjectHandling(result, handling) {\n let rval = result;\n if (result === null || result === undefined) {\n if (handling === NullReturnedObjectHandling.Error) {\n Logger.error('Null object returned and Error specified, throwing 500');\n throw new RestfulApiHttpError('Null object').withHttpStatusCode(500);\n }\n else if (handling === NullReturnedObjectHandling.Return404NotFoundResponse) {\n throw new NotFoundError('Resource not found');\n }\n else if (handling === NullReturnedObjectHandling.ConvertToEmptyString) {\n Logger.warn('Null object returned from handler and convert not specified, converting to empty string');\n rval = '';\n }\n else {\n throw new RestfulApiHttpError('Cant happen - failed enum check').withHttpStatusCode(500);\n }\n }\n return rval;\n }\n static async findHandler(rm, event, context, add404OnMissing = true) {\n let rval = null;\n if (rm) {\n event.pathParameters = Object.assign({}, event.pathParameters, rm.parsed);\n rval = PromiseRatchet.timeout(rm.mapping.function(event, context), 'Timed out after ' + rm.mapping.metaProcessingConfig.timeoutMS + ' ms. Request was ' + JSON.stringify(event), rm.mapping.metaProcessingConfig.timeoutMS);\n }\n else if (add404OnMissing) {\n throw new NotFoundError('No such endpoint');\n }\n return rval;\n }\n static addRunHandlerAsFilterToList(filters, rm) {\n if (filters) {\n filters.push((fCtx) => RunHandlerAsFilter.runHandler(fCtx, rm));\n }\n }\n}\n//# sourceMappingURL=run-handler-as-filter.js.map","import { Logger, RequireRatchet, StringRatchet, RestfulApiHttpError } from '@bitblit/ratchet-common';\nimport Route from 'route-parser';\nimport { ResponseUtil } from './response-util.js';\nimport { BuiltInFilters } from '../built-in/http/built-in-filters.js';\nimport { RunHandlerAsFilter } from '../built-in/http/run-handler-as-filter.js';\nimport { ContextUtil } from '../util/context-util.js';\nimport { LambdaEventDetector } from '@bitblit/ratchet-aws';\nexport class WebHandler {\n routerConfig;\n static MAXIMUM_LAMBDA_BODY_SIZE_BYTES = 1024 * 1024 * 5 - 1024 * 100;\n constructor(routerConfig) {\n this.routerConfig = routerConfig;\n RequireRatchet.notNullOrUndefined(routerConfig);\n }\n get router() {\n return this.routerConfig;\n }\n extractLabel(evt, context) {\n return 'WEB:' + StringRatchet.trimToEmpty(evt.httpMethod).toUpperCase() + ':' + evt.path;\n }\n handlesEvent(evt) {\n return LambdaEventDetector.isValidApiGatewayEvent(evt);\n }\n async processEvent(event, context) {\n if (!this.routerConfig) {\n throw new Error('Router config not found');\n }\n const asExtended = Object.assign({}, { parsedBody: null, authorization: null, convertedFromV2Event: false }, event);\n const rval = await this.openApiLambdaHandler(asExtended, context);\n ContextUtil.addTraceToProxyResult(rval);\n Logger.updateTracePrefix(null);\n return rval;\n }\n async openApiLambdaHandler(evt, context) {\n const rm = this.findBestMatchingRoute(evt);\n const procConfig = rm?.mapping?.metaProcessingConfig\n ? rm.mapping.metaProcessingConfig\n : this.routerConfig.config.defaultMetaHandling;\n const fCtx = {\n event: evt,\n context: context,\n result: null,\n rawResult: null,\n routeAndParse: rm,\n modelValidator: this.routerConfig.config.overrideModelValidator || this.routerConfig.openApiModelValidator,\n authenticators: this.routerConfig.config.authorizers,\n };\n try {\n let filterChain = Object.assign([], procConfig.preFilters || []);\n RunHandlerAsFilter.addRunHandlerAsFilterToList(filterChain, rm);\n filterChain = filterChain.concat(procConfig.postFilters || []);\n await BuiltInFilters.combineFilters(fCtx, filterChain);\n }\n catch (err) {\n const wrapper = RestfulApiHttpError.wrapError(err);\n fCtx.result = ResponseUtil.errorResponse(wrapper);\n try {\n await BuiltInFilters.combineFilters(fCtx, procConfig.errorFilters);\n }\n catch (convErr) {\n Logger.error('REALLY BAD - FAILED WHILE PROCESSING ERROR FILTERS : %s', convErr);\n }\n }\n return fCtx.result;\n }\n findBestMatchingRoute(event) {\n let rval = null;\n const cleanPath = this.cleanPath(event);\n const methodLower = event.httpMethod.toLowerCase();\n const matchRoutes = this.routerConfig.routes\n .map((r) => {\n let rval = null;\n if (r.method && r.method.toLowerCase() === methodLower) {\n const routeParser = new Route(r.path);\n const parsed = routeParser.match(cleanPath);\n if (parsed !== false) {\n rval = {\n mapping: r,\n route: routeParser,\n parsed: parsed,\n };\n }\n }\n return rval;\n })\n .filter((r) => r != null);\n matchRoutes.sort((a, b) => {\n return Object.keys(a.parsed).length - Object.keys(b.parsed).length;\n });\n rval = matchRoutes && matchRoutes.length > 0 ? matchRoutes[0] : null;\n if (!rval) {\n Logger.debug('Failed to find handler for %s (cleaned path was %s, strip prefixes were %j)', event.path, cleanPath, this.routerConfig.config.prefixesToStripBeforeRouteMatch);\n }\n return rval;\n }\n cleanPath(event) {\n let rval = event.path;\n while (rval.startsWith('/')) {\n rval = rval.substring(1);\n }\n if (this.routerConfig.config.prefixesToStripBeforeRouteMatch) {\n this.routerConfig.config.prefixesToStripBeforeRouteMatch.forEach((prefix) => {\n if (rval.toLowerCase().startsWith(prefix.toLowerCase() + '/')) {\n rval = rval.substring(prefix.length);\n }\n });\n }\n while (rval.startsWith('/')) {\n rval = rval.substring(1);\n }\n rval = '/' + rval;\n return rval;\n }\n}\n//# sourceMappingURL=web-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { ErrorRatchet } from '@bitblit/ratchet-common';\nimport yaml from 'js-yaml';\nimport { ModelValidator } from '@bitblit/ratchet-misc';\nimport { BackgroundHttpAdapterHandler } from '../background/background-http-adapter-handler.js';\nimport { BackgroundHandler } from '../background/background-handler.js';\nimport { RouterUtil } from '../http/route/router-util.js';\nimport { WebHandler } from '../http/web-handler.js';\nimport { MisconfiguredError } from '../http/error/misconfigured-error.js';\nimport { EpsilonGlobalHandler } from '../epsilon-global-handler.js';\nexport class EpsilonConfigParser {\n constructor() { }\n static epsilonConfigToEpsilonGlobalHandler(config, backgroundManager) {\n return new EpsilonGlobalHandler(EpsilonConfigParser.epsilonConfigToEpsilonInstance(config, backgroundManager));\n }\n static epsilonConfigToEpsilonInstance(config, backgroundManager) {\n this.validateGlobalConfig(config);\n const label = config?.label || 'NO EPSILON CONFIG LABEL SET';\n Logger.info('Creating epsilon : %s : BM : %j', label, backgroundManager);\n const parsed = EpsilonConfigParser.parseOpenApiDocument(config.openApiYamlString);\n const modelValidator = EpsilonConfigParser.openApiDocToValidator(parsed);\n const backgroundHttpAdapter = new BackgroundHttpAdapterHandler(config.backgroundConfig, modelValidator, backgroundManager);\n const backgroundHandler = config.backgroundConfig\n ? new BackgroundHandler(config.backgroundConfig, backgroundManager, modelValidator)\n : null;\n const epsilonRouter = config.httpConfig\n ? RouterUtil.openApiYamlToRouterConfig(config.httpConfig, parsed, modelValidator, backgroundHttpAdapter)\n : null;\n const webHandler = epsilonRouter ? new WebHandler(epsilonRouter) : null;\n const inst = {\n config: config,\n parsedOpenApiDoc: parsed,\n modelValidator: modelValidator,\n webHandler: webHandler,\n backgroundHandler: backgroundHandler,\n backgroundManager: backgroundManager,\n };\n return inst;\n }\n static parseOpenApiDocument(yamlString) {\n if (!yamlString) {\n throw new MisconfiguredError('Cannot configure, missing either yaml or cfg');\n }\n const doc = yaml.load(yamlString);\n return doc;\n }\n static openApiDocToValidator(doc) {\n let rval = null;\n if (doc?.components?.schemas) {\n rval = ModelValidator.createFromParsedObject(doc.components.schemas);\n }\n return rval;\n }\n static validateGlobalConfig(config) {\n if (!config) {\n ErrorRatchet.throwFormattedErr('Config may not be null');\n }\n if (!config.openApiYamlString) {\n ErrorRatchet.throwFormattedErr('Config must define an open api document');\n }\n if (!!config.cron && !config.cron.timezone) {\n ErrorRatchet.throwFormattedErr('Cron is defined, but timezone is not set');\n }\n }\n}\n//# sourceMappingURL=epsilon-config-parser.js.map","import { Logger } from '@bitblit/ratchet-common';\nexport class SampleInputValidatedProcessor {\n get typeName() {\n return 'EpsilonSampleInputValidated';\n }\n async handleEvent(data, mgr) {\n Logger.info('Running SampleInputValidatedProcessor, data was : %j', data);\n }\n get dataSchemaName() {\n return 'BackgroundSampleInputValidatedProcessorData';\n }\n}\n//# sourceMappingURL=sample-input-validated-processor.js.map","import { Logger } from '@bitblit/ratchet-common';\nexport class BuiltInAuthorizers {\n static async simpleNoAuthenticationLogAccess(authorizationContext, evt) {\n Logger.debug('Auth requested for %s : %j', evt.path, authorizationContext?.auth);\n return true;\n }\n static async simpleLoggedInAuth(authorizationContext, evt) {\n const rval = !!authorizationContext?.auth;\n Logger.silly('SimpleLoggedInAuth returning %s for %s', rval, evt.path);\n return rval;\n }\n static async simpleRoleRouteAuth(authorizationContext, event, route, requiredRoleOneOf = null, requiredRoleAllOf = null) {\n let rval = true;\n const token = authorizationContext?.auth;\n if (token) {\n if (requiredRoleOneOf) {\n requiredRoleOneOf.forEach((r) => {\n rval = rval || token.roles.indexOf(r) > -1;\n });\n if (!rval) {\n Logger.warn('Request to %s failed to find at least one of %j', route.path, requiredRoleOneOf);\n }\n }\n if (rval && requiredRoleAllOf) {\n requiredRoleAllOf.forEach((r) => {\n rval = rval && token.roles.indexOf(r) > -1;\n });\n if (!rval) {\n Logger.warn('Request to %s failed to find all of %j', route.path, requiredRoleAllOf);\n }\n }\n }\n else {\n Logger.warn('Cannot authenticate - no parsed auth found');\n rval = false;\n }\n return rval;\n }\n}\n//# sourceMappingURL=built-in-authorizers.js.map","import { EventUtil } from '../../../http/event-util.js';\nimport { ExpiredJwtHandling, Logger, MapRatchet } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { UnauthorizedError } from '../../../http/error/unauthorized-error.js';\nexport class ApolloUtil {\n constructor() { }\n static async emptyContext() {\n return {};\n }\n static async defaultEpsilonApolloContext(args, jwt) {\n const authTokenSt = EventUtil.extractBearerTokenFromEvent(args.lambdaEvent);\n let token = null;\n if (StringRatchet.trimToNull(authTokenSt) && jwt) {\n Logger.info('Got : %s', authTokenSt);\n token = await jwt.decodeToken(authTokenSt, ExpiredJwtHandling.RETURN_NULL);\n }\n const rval = {\n user: token,\n bearerTokenString: authTokenSt,\n headers: args.lambdaEvent.headers,\n functionName: args.lambdaContext.functionName,\n lambdaEvent: args.lambdaEvent,\n lambdaContext: args.lambdaContext,\n };\n return rval;\n }\n static async nonRouteableOnlyEpsilonApolloContext(args, jwt) {\n const hostName = StringRatchet.trimToNull(MapRatchet.extractValueFromMapIgnoreCase(args.lambdaEvent.headers, 'host'));\n const hostIsLocalOrNotRoutableIP4 = EventUtil.hostIsLocalOrNotRoutableIP4(hostName);\n if (!hostIsLocalOrNotRoutableIP4) {\n throw new UnauthorizedError('May only run local / non-routeable : ' + hostName);\n }\n return ApolloUtil.defaultEpsilonApolloContext(args, jwt);\n }\n}\n//# sourceMappingURL=apollo-util.js.map","import { Base64Ratchet, Logger, PromiseRatchet, RequireRatchet, StringRatchet, TimeoutToken, RestfulApiHttpError } from '@bitblit/ratchet-common';\nimport { RequestTimeoutError } from '../../http/error/request-timeout-error.js';\nimport { HeaderMap } from '@apollo/server';\nimport { ContextUtil } from '../../util/context-util.js';\nimport { ApolloUtil } from './apollo/apollo-util.js';\nimport { EpsilonApolloCorsMethod } from './apollo/epsilon-apollo-cors-method.js';\nimport { BuiltInFilters } from './built-in-filters.js';\nexport class ApolloFilter {\n static async handlePathWithApollo(fCtx, apolloPathRegex, apolloServer, options) {\n let rval = false;\n if (fCtx.event?.path && apolloPathRegex && apolloPathRegex.test(fCtx.event.path)) {\n fCtx.result = await ApolloFilter.processApolloRequest(fCtx.event, fCtx.context, apolloServer, options);\n if (options?.corsMethod) {\n switch (options.corsMethod) {\n case EpsilonApolloCorsMethod.All:\n await BuiltInFilters.addAllowEverythingCORSHeaders(fCtx);\n break;\n case EpsilonApolloCorsMethod.Reflective:\n await BuiltInFilters.addAllowReflectionCORSHeaders(fCtx);\n break;\n default:\n }\n }\n }\n else {\n rval = true;\n }\n return rval;\n }\n static async processApolloRequest(event, context, apolloServer, options) {\n Logger.silly('Processing event with apollo: %j', event);\n let rval = null;\n RequireRatchet.notNullOrUndefined(apolloServer, 'apolloServer');\n apolloServer.assertStarted('Cannot process with apollo - instance not started');\n const headerMap = new HeaderMap();\n for (const headersKey in event.headers) {\n headerMap.set(headersKey, event.headers[headersKey]);\n }\n const eventMethod = StringRatchet.trimToEmpty(event.httpMethod).toUpperCase();\n let body = null;\n if (StringRatchet.trimToNull(event.body)) {\n const bodyString = event.isBase64Encoded ? Base64Ratchet.base64StringToString(event.body) : event.body;\n body = JSON.parse(bodyString);\n }\n const aRequest = {\n method: eventMethod,\n headers: headerMap,\n search: eventMethod === 'GET' && event?.queryStringParameters\n ? Object.keys(event.queryStringParameters)\n .map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(event.queryStringParameters[k]))\n .join('&')\n : null,\n body: body,\n };\n const timeoutMS = options?.timeoutMS ?? context.getRemainingTimeInMillis() - 500;\n const contextFn = options?.context ?? ApolloUtil.emptyContext;\n const apolloPromise = apolloServer.executeHTTPGraphQLRequest({\n httpGraphQLRequest: aRequest,\n context: () => contextFn({ lambdaContext: context, lambdaEvent: event }),\n });\n let result = null;\n if (timeoutMS) {\n result = await PromiseRatchet.timeout(apolloPromise, 'Apollo timed out after ' + timeoutMS + ' ms.', timeoutMS);\n }\n else {\n Logger.warn('No timeout set even after defaulting for Apollo');\n result = await apolloPromise;\n }\n if (TimeoutToken.isTimeoutToken(result)) {\n result.writeToLog();\n throw new RequestTimeoutError('Timed out');\n }\n const httpGraphQLResponse = result;\n const outHeaders = {};\n for (const [headersKey, headersValue] of httpGraphQLResponse.headers.entries()) {\n outHeaders[headersKey] = headersValue;\n }\n if (httpGraphQLResponse.body.kind === 'chunked') {\n throw new RestfulApiHttpError('Apollo returned chunked result').withHttpStatusCode(500).withRequestId(ContextUtil.currentRequestId());\n }\n const bodyAsString = StringRatchet.trimToEmpty(httpGraphQLResponse?.body?.string);\n rval = {\n body: Base64Ratchet.generateBase64VersionOfString(bodyAsString),\n headers: outHeaders,\n multiValueHeaders: {},\n isBase64Encoded: true,\n statusCode: httpGraphQLResponse.status || 200,\n };\n if (eventMethod === 'GET' && rval.headers['content-type'] !== 'text/html' && bodyAsString.indexOf('<!DOCTYPE html>') >= 0) {\n Logger.info('Forcing content type to html for the sandbox page');\n rval.headers = rval.headers || {};\n rval.headers['content-type'] = 'text/html';\n }\n return rval;\n }\n static addApolloFilterToList(filters, apolloPathRegex, apolloServer, options) {\n if (filters) {\n filters.push((fCtx) => ApolloFilter.handlePathWithApollo(fCtx, apolloPathRegex, apolloServer, options));\n }\n }\n}\n//# sourceMappingURL=apollo-filter.js.map","import { Logger } from '@bitblit/ratchet-common';\nexport class LogMessageBackgroundErrorProcessor {\n async handleError(submission, error) {\n Logger.error('-------- ERROR PROCESSED : %j : %s----', submission, error);\n }\n}\n//# sourceMappingURL=log-message-background-error-processor.js.map","import { Subject } from 'rxjs';\nimport { Logger } from '@bitblit/ratchet-common';\nimport { AbstractBackgroundManager } from './abstract-background-manager.js';\nexport class SingleThreadLocalBackgroundManager extends AbstractBackgroundManager {\n _localBus = new Subject();\n get backgroundManagerName() {\n return 'SingleThreadLocalBackgroundManager';\n }\n constructor() {\n super();\n }\n immediateProcessQueue() {\n return this._localBus;\n }\n async addEntryToQueue(entry, fireStartMessage) {\n const wrapped = this.wrapEntryForInternal(entry);\n const rval = wrapped.guid;\n Logger.info('Add entry to queue (local) : %j : Start : %s', entry, fireStartMessage);\n this._localBus.next(wrapped);\n return rval;\n }\n async fireImmediateProcessRequest(entry) {\n let rval = null;\n const wrapped = this.wrapEntryForInternal(entry);\n rval = wrapped.guid;\n Logger.info('Fire immediately (local) : %j ', entry);\n this._localBus.next(wrapped);\n return rval;\n }\n async fireStartProcessingRequest() {\n let rval = null;\n Logger.info('Fire start processing request (local, ignored)');\n rval = 'NO-OP';\n return rval;\n }\n async fetchApproximateNumberOfQueueEntries() {\n let rval = null;\n rval = 0;\n return rval;\n }\n async takeEntryFromBackgroundQueue() {\n Logger.info('Called takeEntryFromBackgroundQueue on SingleThreadedLocal - returning empty');\n return [];\n }\n}\n//# sourceMappingURL=single-thread-local-background-manager.js.map","export class SampleServerStaticFiles {\n constructor() { }\n static SAMPLE_OPEN_API_DOC = 'openapi: 3.0.0\\n' +\n 'info:\\n' +\n ' version: v0\\n' +\n ' title: SampleAPI\\n' +\n 'tags:\\n' +\n ' - name: CORS\\n' +\n ' description: These endpoints are here to support CORS\\n' +\n ' - name: Public\\n' +\n ' description: These endpoints can be called without setting the authorization header\\n' +\n ' - name: Secure\\n' +\n ' description: Authentication and authorization of the API\\n' +\n 'paths:\\n' +\n ' /:\\n' +\n ' get:\\n' +\n ' description: Redirects to the /meta/server endpoint\\n' +\n ' tags:\\n' +\n ' - Meta\\n' +\n ' - Public\\n' +\n ' responses:\\n' +\n \" '301':\\n\" +\n ' description: Redirects to the /meta/server endpoint\\n' +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Standard CORS header response\\n' +\n ' /meta/server:\\n' +\n ' get:\\n' +\n ' description: >\\n' +\n ' Returns information about the current build and time. Can be used to\\n' +\n ' test error-handling code by passing a specific http error code in the\\n' +\n ' error query parameter. Can also be used to process specific named tests\\n' +\n ' by passing those names to the test parameter.\\n' +\n ' tags:\\n' +\n ' - Public\\n' +\n ' parameters:\\n' +\n ' - name: error\\n' +\n ' in: query\\n' +\n ' description: >-\\n' +\n ' If set, throw a specific error for testing (valid are\\n' +\n ' 500,400,403,404)\\n' +\n ' required: false\\n' +\n ' schema:\\n' +\n ' type: number\\n' +\n ' - name: test\\n' +\n ' in: query\\n' +\n ' description: Run a specific named test (currently none are publicly available)\\n' +\n ' required: false\\n' +\n ' schema:\\n' +\n ' type: string\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n \" '400':\\n\" +\n ' description: Simulated bad request\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n \" '403':\\n\" +\n ' description: Simulated unauthorized\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n \" '404':\\n\" +\n ' description: Simulated not found\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n \" '500':\\n\" +\n ' description: Simulated internal server error\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Standard CORS header response\\n' +\n ' /meta/user:\\n' +\n ' get:\\n' +\n ' description: >\\n' +\n ' When logged in, returns the contents of the JWT token as the server\\n' +\n ' parses it. This should match what you get when you process the token\\n' +\n ' returned from the \"POST /access-token\" endpoint through a standard JWT\\n' +\n ' token processor.\\n' +\n ' tags:\\n' +\n ' - Meta\\n' +\n ' security:\\n' +\n ' - SampleAuthorizer: []\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/AccessTokenContents'\\n\" +\n \" '401':\\n\" +\n ' description: Unauthorized\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n \" '401':\\n\" +\n ' description: Unauthorized\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n ' /meta/item/{itemId}:\\n' +\n ' get:\\n' +\n ' description: >\\n' +\n ' Example of a path param\\n' +\n ' parameters:\\n' +\n ' - name: itemId\\n' +\n ' in: path\\n' +\n ' description: A sample item id\\n' +\n ' required: true\\n' +\n ' schema:\\n' +\n ' type: string\\n' +\n ' tags:\\n' +\n ' - Meta\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/Empty'\\n\" +\n \" '401':\\n\" +\n ' description: Unauthorized\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' parameters:\\n' +\n ' - name: itemId\\n' +\n ' in: path\\n' +\n ' description: A sample item id\\n' +\n ' required: true\\n' +\n ' schema:\\n' +\n ' type: string\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n \" '401':\\n\" +\n ' description: Unauthorized\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n '\\n' +\n ' /meta/sample-item:\\n' +\n ' get:\\n' +\n ' description: >\\n' +\n ' Example of an object returned\\n' +\n ' parameters:\\n' +\n ' - name: num\\n' +\n ' in: path\\n' +\n ' description: Number to return in the number value\\n' +\n ' required: false\\n' +\n ' schema:\\n' +\n ' type: number\\n' +\n ' tags:\\n' +\n ' - Meta\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' content:\\n' +\n \" 'application/json':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/BackgroundSampleInputValidatedProcessorData'\\n\" +\n ' post:\\n' +\n ' description: >\\n' +\n ' Example of an object posted\\n' +\n ' requestBody:\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/BackgroundSampleInputValidatedProcessorData'\\n\" +\n ' description: Request to refresh the access token or change active user\\n' +\n ' required: true\\n' +\n ' tags:\\n' +\n ' - Meta\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' content:\\n' +\n \" 'application/json':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/BackgroundSampleInputValidatedProcessorData'\\n\" +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n '\\n' +\n ' /secure/access-token:\\n' +\n ' post:\\n' +\n ' tags:\\n' +\n ' - Secure\\n' +\n ' - Public\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/AccessTokenResponse'\\n\" +\n \" '400':\\n\" +\n ' description: Invalid request\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n \" '403':\\n\" +\n ' description: Invalid credentials\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n ' requestBody:\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/AccessTokenRequest'\\n\" +\n ' description: Request to refresh the access token or change active user\\n' +\n ' required: true\\n' +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Standard CORS header response\\n' +\n ' /multi/fixed:\\n' +\n ' get:\\n' +\n ' description: Tests path matching from most specific to least (this is most)\\n' +\n ' tags:\\n' +\n ' - Public\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Standard CORS header response\\n' +\n ' /multi/{v}:\\n' +\n ' get:\\n' +\n ' description: Tests path matching from most specific to least (this is least)\\n' +\n ' tags:\\n' +\n ' - Public\\n' +\n ' parameters:\\n' +\n ' - name: v\\n' +\n ' in: path\\n' +\n ' description: A variable\\n' +\n ' required: true\\n' +\n ' schema:\\n' +\n ' type: string\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' parameters:\\n' +\n ' - name: v\\n' +\n ' in: path\\n' +\n ' description: A variable\\n' +\n ' required: true\\n' +\n ' schema:\\n' +\n ' type: string\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Standard CORS header response\\n' +\n '\\n' +\n ' /err/{code}:\\n' +\n ' get:\\n' +\n ' description: Tests path matching from most specific to least (this is least)\\n' +\n ' tags:\\n' +\n ' - Public\\n' +\n ' parameters:\\n' +\n ' - name: code\\n' +\n ' in: path\\n' +\n ' description: Error code\\n' +\n ' required: true\\n' +\n ' schema:\\n' +\n ' type: number\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' parameters:\\n' +\n ' - name: code\\n' +\n ' in: path\\n' +\n ' description: A variable\\n' +\n ' required: true\\n' +\n ' schema:\\n' +\n ' type: number\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Standard CORS header response\\n' +\n '\\n' +\n ' /background:\\n' +\n ' post:\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/BackgroundQueueResponse'\\n\" +\n \" '400':\\n\" +\n ' description: Invalid request\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n \" '403':\\n\" +\n ' description: Invalid credentials\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n ' requestBody:\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/Empty'\\n\" +\n ' description: Content to echo\\n' +\n ' required: true\\n' +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Standard CORS header response\\n' +\n '\\n' +\n ' /background/meta:\\n' +\n ' get:\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/BackgroundMetaResponse'\\n\" +\n \" '400':\\n\" +\n ' description: Invalid request\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n \" '403':\\n\" +\n ' description: Invalid credentials\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Standard CORS header response\\n' +\n '\\n' +\n 'x-amazon-apigateway-binary-media-types:\\n' +\n \" - '*/*'\\n\" +\n 'x-amazon-apigateway-gateway-responses:\\n' +\n ' UNAUTHORIZED:\\n' +\n ' statusCode: 401\\n' +\n ' responseParameters:\\n' +\n ' gatewayresponse.header.Access-Control-Allow-Origin: \"\\'*\\'\"\\n' +\n ' responseTemplates:\\n' +\n ' application/json: \\'{\"errors\":[\"Unauthorized\"], \"httpStatusCode\": 401}\\'\\n' +\n ' MISSING_AUTHENTICATION_TOKEN:\\n' +\n ' statusCode: 404\\n' +\n ' responseParameters:\\n' +\n ' gatewayresponse.header.Access-Control-Allow-Origin: \"\\'*\\'\"\\n' +\n ' responseTemplates:\\n' +\n ' application/json: \\'{\"errors\":[\"No such endpoint\"], \"httpStatusCode\": 404}\\'\\n' +\n ' INTEGRATION_TIMEOUT:\\n' +\n ' statusCode: 504\\n' +\n ' responseParameters:\\n' +\n ' gatewayresponse.header.Access-Control-Allow-Origin: \"\\'*\\'\"\\n' +\n ' responseTemplates:\\n' +\n ' application/json: \\'{\"errors\":[\"Timeout\"], \"httpStatusCode\": 504}\\'\\n' +\n ' DEFAULT_5XX:\\n' +\n ' statusCode: 500\\n' +\n ' responseParameters:\\n' +\n ' gatewayresponse.header.Access-Control-Allow-Origin: \"\\'*\\'\"\\n' +\n ' responseTemplates:\\n' +\n ' application/json: \\'{\"errors\":[\"Internal Server Error\"], \"httpStatusCode\": 500}\\'\\n' +\n '\\n' +\n 'servers:\\n' +\n \" - url: 'https://api.sample.com/dev'\\n\" +\n 'components:\\n' +\n ' securitySchemes:\\n' +\n ' SampleAuthorizer:\\n' +\n ' type: apiKey\\n' +\n ' name: Authorization\\n' +\n ' in: header\\n' +\n ' schemas:\\n' +\n ' Empty:\\n' +\n ' type: object\\n' +\n ' title: Empty Schema\\n' +\n '\\n' +\n ' AccessTokenRequest:\\n' +\n ' type: object\\n' +\n ' title: Access Token Request\\n' +\n ' required:\\n' +\n ' - email\\n' +\n ' - password\\n' +\n ' - scope\\n' +\n ' properties:\\n' +\n ' email:\\n' +\n ' type: string\\n' +\n ' description: Email address of the account to authenticate\\n' +\n ' format: email\\n' +\n ' minLength: 7\\n' +\n ' password:\\n' +\n ' type: string\\n' +\n ' description: Password of the account to authenticate\\n' +\n ' minLength: 6\\n' +\n ' scope:\\n' +\n ' type: string\\n' +\n ' enum:\\n' +\n ' - OWNER\\n' +\n ' - ADVERTISER\\n' +\n ' - GLOBAL\\n' +\n ' - RUN_AS_OWNER\\n' +\n ' - RUN_AS_ADVERTISER\\n' +\n ' description: |\\n' +\n ' What style of account to authenticate:\\n' +\n ' * `OWNER` - A device owner account\\n' +\n ' * `ADVERTISER` - A advertising account\\n' +\n ' * `GLOBAL` - Used by Adomni customer service\\n' +\n ' * `RUN_AS_OWNER` - Used by Adomni customer service\\n' +\n ' * `RUN_AS_ADVERTISER` - Used by Adomni customer service\\n' +\n ' default: OWNER\\n' +\n ' runAs:\\n' +\n ' type: string\\n' +\n ' description: Used by Adomni customer service\\n' +\n ' format: email\\n' +\n ' expirationSeconds:\\n' +\n ' type: number\\n' +\n ' minimum: 10\\n' +\n ' maximum: 3600\\n' +\n ' default: 3600\\n' +\n ' AccessTokenResponse:\\n' +\n ' type: object\\n' +\n ' title: Access Token Response\\n' +\n ' required:\\n' +\n ' - token\\n' +\n ' - expires\\n' +\n ' properties:\\n' +\n ' token:\\n' +\n ' type: string\\n' +\n ' description: A JWT access token for the API\\n' +\n ' expires:\\n' +\n ' type: number\\n' +\n ' format: int64\\n' +\n \" description: 'The time this token will expire, expressed in epoch ms'\\n\" +\n ' AccessTokenContents:\\n' +\n ' type: object\\n' +\n ' title: Access Token Contents\\n' +\n ' description: The contents of the JWT token\\n' +\n ' required:\\n' +\n ' - exp\\n' +\n ' - iss\\n' +\n ' - sub\\n' +\n ' - iat\\n' +\n ' - user\\n' +\n ' properties:\\n' +\n ' exp:\\n' +\n ' type: number\\n' +\n ' description: >-\\n' +\n ' Expiration claim - The time this token will expire, expressed in\\n' +\n ' epoch ms\\n' +\n ' iss:\\n' +\n ' type: string\\n' +\n ' description: Issuer claim - Who created the token\\n' +\n ' sub:\\n' +\n ' type: string\\n' +\n ' description: Subject claim - The target of the token (typically user email)\\n' +\n ' iat:\\n' +\n ' type: number\\n' +\n ' description: >-\\n' +\n ' Issued at claim - The time this token was created, expressed in\\n' +\n ' epoch ms\\n' +\n ' user:\\n' +\n ' type: object\\n' +\n ' description: Object describing the user authenticated by this token\\n' +\n ' ApiErrorResponse:\\n' +\n ' type: object\\n' +\n ' title: API Error Response\\n' +\n ' required:\\n' +\n ' - errors\\n' +\n ' - httpStatusCode\\n' +\n ' properties:\\n' +\n ' errors:\\n' +\n ' type: array\\n' +\n ' items:\\n' +\n ' type: string\\n' +\n ' description: List of the errors that occurred\\n' +\n ' httpStatusCode:\\n' +\n ' type: number\\n' +\n ' description: Http status code of this error\\n' +\n ' detailCode:\\n' +\n ' type: number\\n' +\n ' description: Adomni detail status code for this error\\n' +\n ' BackgroundQueueResponse:\\n' +\n ' type: object\\n' +\n ' title: Background Queue Response\\n' +\n ' description: When any of the background endpoints are hit, this is what will be returned\\n' +\n ' required:\\n' +\n ' - resultId\\n' +\n ' - success\\n' +\n ' properties:\\n' +\n ' processHandling:\\n' +\n ' type: string\\n' +\n \" enum: ['Queued', 'Immediate']\\n\" +\n ' success:\\n' +\n ' type: boolean\\n' +\n ' resultId:\\n' +\n ' type: string\\n' +\n ' BackgroundMetaResponse:\\n' +\n ' type: object\\n' +\n ' title: Background Meta Response\\n' +\n ' description: If\\n' +\n ' properties:\\n' +\n ' validTypes:\\n' +\n ' type: array\\n' +\n ' items:\\n' +\n ' type: string\\n' +\n ' currentQueueLength:\\n' +\n ' type: number\\n' +\n '\\n' +\n ' BackgroundSampleInputValidatedProcessorData:\\n' +\n ' type: object\\n' +\n ' title: BackgroundSampleInputValidatedProcessorData\\n' +\n ' description: This is used for testing the background validator\\n' +\n ' required:\\n' +\n ' - nameParam\\n' +\n ' - numberParam\\n' +\n ' properties:\\n' +\n ' nameParam:\\n' +\n ' type: string\\n' +\n ' description: A sample name parameter\\n' +\n ' minimum: 0\\n' +\n ' maximum: 10\\n' +\n ' numberParam:\\n' +\n ' type: number\\n' +\n ' description: A sample number parameter\\n';\n static SAMPLE_SERVER_GRAPHQL = 'schema {\\n' +\n ' query: RootQueryType\\n' +\n '}\\n' +\n '\\n' +\n 'type RootQueryType {\\n' +\n ' serverMeta: ServerMeta\\n' +\n ' forceTimeout: ForceTimeout\\n' +\n '}\\n' +\n '\\n' +\n 'type ServerMeta {\\n' +\n ' version: String\\n' +\n ' serverTime: String\\n' +\n ' status: String\\n' +\n '}\\n' +\n '\\n' +\n 'type ForceTimeout {\\n' +\n ' placeholder: String\\n' +\n '}\\n';\n}\n//# sourceMappingURL=sample-server-static-files.js.map","import { BooleanRatchet, ErrorRatchet, Logger, LoggerLevelName, NumberRatchet, PromiseRatchet, StringRatchet, } from '@bitblit/ratchet-common';\nimport { ApolloServer } from '@apollo/server';\nimport { gql } from 'graphql-tag';\nimport { ApolloServerPluginLandingPageLocalDefault } from '@apollo/server/plugin/landingPage/default';\nimport { EpsilonGlobalHandler } from '../epsilon-global-handler.js';\nimport { BuiltInHandlers } from '../built-in/http/built-in-handlers.js';\nimport { LocalWebTokenManipulator } from '../http/auth/local-web-token-manipulator.js';\nimport { EchoProcessor } from '../built-in/background/echo-processor.js';\nimport { NoOpProcessor } from '../built-in/background/no-op-processor.js';\nimport { SampleDelayProcessor } from '../built-in/background/sample-delay-processor.js';\nimport { LogAndEnqueueEchoProcessor } from '../built-in/background/log-and-enqueue-echo-processor.js';\nimport { EpsilonConfigParser } from '../util/epsilon-config-parser.js';\nimport { RouterUtil } from '../http/route/router-util.js';\nimport { SampleInputValidatedProcessor } from '../built-in/background/sample-input-validated-processor.js';\nimport { BuiltInAuthorizers } from '../built-in/http/built-in-authorizers.js';\nimport { ApolloFilter } from '../built-in/http/apollo-filter.js';\nimport { BuiltInFilters } from '../built-in/http/built-in-filters.js';\nimport { LogMessageBackgroundErrorProcessor } from '../built-in/background/log-message-background-error-processor.js';\nimport { SingleThreadLocalBackgroundManager } from '../background/manager/single-thread-local-background-manager.js';\nimport { SampleServerStaticFiles } from './sample-server-static-files.js';\nimport { ApolloUtil } from '../built-in/http/apollo/apollo-util.js';\nimport { EpsilonApolloCorsMethod } from '../built-in/http/apollo/epsilon-apollo-cors-method.js';\nexport class SampleServerComponents {\n constructor() { }\n static async createSampleApollo() {\n const gqlString = SampleServerStaticFiles.SAMPLE_SERVER_GRAPHQL;\n Logger.silly('Creating apollo from : %s', gqlString);\n const typeDefs = gql(gqlString);\n const resolvers = {\n RootQueryType: {\n serverMeta: async (root) => {\n return { version: 'A1', serverTime: new Date().toISOString() };\n },\n forceTimeout: async (root) => {\n await PromiseRatchet.wait(1000 * 60 * 30);\n return { placeholder: 'A1' };\n },\n },\n };\n const server = new ApolloServer({\n introspection: true,\n typeDefs,\n resolvers,\n plugins: [\n ApolloServerPluginLandingPageLocalDefault({ footer: false }),\n ],\n });\n await server.start();\n return server;\n }\n static async createSampleEpsilonConfig(label) {\n const yamlString = SampleServerStaticFiles.SAMPLE_OPEN_API_DOC;\n const authorizers = new Map();\n authorizers.set('SampleAuthorizer', (token, evt) => BuiltInAuthorizers.simpleLoggedInAuth(token, evt));\n authorizers.set('LogAuthorizer', (token, evt) => BuiltInAuthorizers.simpleNoAuthenticationLogAccess(token, evt));\n const handlers = new Map();\n handlers.set('get /', (event, context) => BuiltInHandlers.sample(event, null, context));\n handlers.set('get /meta/server', (event) => BuiltInHandlers.sample(event));\n handlers.set('get /meta/user', (event) => BuiltInHandlers.sample(event));\n handlers.set('get /meta/item/{itemId}', (event) => BuiltInHandlers.sample(event));\n handlers.set('post /secure/access-token', (event) => BuiltInHandlers.sample(event));\n handlers.set('get /multi/fixed', (event) => BuiltInHandlers.sample(event, 'fixed'));\n handlers.set('get /multi/{v}', (event) => BuiltInHandlers.sample(event, 'variable'));\n handlers.set('get /err/{code}', (event) => {\n const err = ErrorRatchet.fErr('Fake Err : %j', event);\n err['statusCode'] = NumberRatchet.safeNumber(event.pathParameters['code']);\n throw err;\n });\n handlers.set('get /meta/sample-item', async (event) => {\n const numberToUse = NumberRatchet.safeNumber(event.queryStringParameters['num']) || 5;\n const rval = {\n numberParam: numberToUse,\n nameParam: 'Test-String',\n };\n return rval;\n });\n handlers.set('post /meta/sample-item', async (event) => {\n const parsed = event.parsedBody;\n const forceFail = BooleanRatchet.parseBool(StringRatchet.trimToNull(event.queryStringParameters['forceFail'])) === true;\n if (forceFail) {\n parsed['numberParam'] = 'test';\n }\n return parsed;\n });\n const tokenManipulator = new LocalWebTokenManipulator(['abcd1234'], 'sample.erigir.com')\n .withParseFailureLogLevel(LoggerLevelName.debug)\n .withExtraDecryptionKeys(['abcdefabcdef'])\n .withOldKeyUseLogLevel(LoggerLevelName.info);\n const meta = RouterUtil.defaultHttpMetaProcessingConfigWithAuthenticationHeaderParsing(tokenManipulator);\n meta.timeoutMS = 10_000;\n ApolloFilter.addApolloFilterToList(meta.preFilters, new RegExp('.*graphql.*'), await SampleServerComponents.createSampleApollo(), {\n context: (arg) => ApolloUtil.defaultEpsilonApolloContext(arg, tokenManipulator.jwtRatchet),\n timeoutMS: 5_000,\n corsMethod: EpsilonApolloCorsMethod.All,\n });\n meta.errorFilters.push((fCtx) => BuiltInFilters.secureOutboundServerErrorForProduction(fCtx, 'Clean Internal Server Error', 500));\n const preFiltersAllowingNull = Object.assign({}, meta);\n preFiltersAllowingNull.preFilters = Object.assign([], preFiltersAllowingNull.preFilters);\n preFiltersAllowingNull.preFilters.splice(8, 1);\n const cfg = {\n defaultMetaHandling: meta,\n handlers: handlers,\n authorizers: authorizers,\n overrideMetaHandling: [\n {\n pathRegex: '/background',\n methods: null,\n config: Object.assign({}, meta, { overrideAuthorizerName: 'LogAuthorizer' }),\n },\n {\n pathRegex: '/meta/server',\n methods: ['GET'],\n config: preFiltersAllowingNull,\n },\n ],\n prefixesToStripBeforeRouteMatch: ['v0'],\n filterHandledRouteMatches: ['options .*'],\n };\n const background = {\n httpMetaEndpoint: '/background/meta',\n httpSubmissionPath: '/background',\n implyTypeFromPathSuffix: false,\n processors: [\n new EchoProcessor(),\n new NoOpProcessor(),\n new SampleDelayProcessor(),\n new SampleInputValidatedProcessor(),\n new LogAndEnqueueEchoProcessor(),\n ],\n errorProcessor: new LogMessageBackgroundErrorProcessor(),\n };\n const epsilonConfig = {\n label: label,\n openApiYamlString: yamlString,\n httpConfig: cfg,\n backgroundConfig: background,\n };\n return epsilonConfig;\n }\n static async createSampleEpsilonGlobalHandler(label) {\n const epsilonConfig = await SampleServerComponents.createSampleEpsilonConfig(label);\n const backgroundManager = new SingleThreadLocalBackgroundManager();\n const epsilonInstance = EpsilonConfigParser.epsilonConfigToEpsilonInstance(epsilonConfig, backgroundManager);\n const rval = new EpsilonGlobalHandler(epsilonInstance);\n return rval;\n }\n static async createSampleBatchOnlyEpsilonGlobalHandler(label) {\n const epsilonConfig = await SampleServerComponents.createSampleEpsilonConfig(label);\n epsilonConfig.httpConfig.handlers = new Map();\n const byPassCfg = Object.assign({}, epsilonConfig.httpConfig.defaultMetaHandling);\n byPassCfg.preFilters = byPassCfg.preFilters.concat([\n (fCtx) => BuiltInFilters.autoRespond(fCtx, { message: 'Background Processing Only' }),\n ]);\n epsilonConfig.httpConfig.overrideMetaHandling = [\n {\n pathRegex: '.*background.*',\n invertPathMatching: true,\n config: byPassCfg,\n },\n ];\n epsilonConfig.httpConfig.filterHandledRouteMatches = ['.*'];\n const backgroundManager = new SingleThreadLocalBackgroundManager();\n const epsilonInstance = EpsilonConfigParser.epsilonConfigToEpsilonInstance(epsilonConfig, backgroundManager);\n const rval = new EpsilonGlobalHandler(epsilonInstance);\n return rval;\n }\n}\n//# sourceMappingURL=sample-server-components.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport http from 'http';\nimport https from 'https';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { DateTime } from 'luxon';\nimport qs from 'querystring';\nimport { EventUtil } from './http/event-util.js';\nimport { LoggerLevelName } from '@bitblit/ratchet-common';\nimport { LocalServerCert } from './local-server-cert.js';\nimport { SampleServerComponents } from './sample/sample-server-components.js';\nimport { LocalWebTokenManipulator } from './http/auth/local-web-token-manipulator.js';\nexport class LocalServer {\n globalHandler;\n port;\n server;\n aborted = false;\n constructor(globalHandler, port = 8888, https = false) {\n this.globalHandler = globalHandler;\n this.port = port;\n }\n async runServer() {\n return new Promise((res, rej) => {\n try {\n Logger.info('Starting Epsilon server on port %d', this.port);\n if (https) {\n const options = {\n key: LocalServerCert.CLIENT_KEY_PEM,\n cert: LocalServerCert.CLIENT_CERT_PEM,\n };\n Logger.info('Starting https server - THIS SERVER IS NOT SECURE! The KEYS are in the code! Testing Server Only - Use at your own risk!');\n this.server = https.createServer(options, this.requestHandler.bind(this)).listen(this.port);\n }\n else {\n this.server = http.createServer(this.requestHandler.bind(this)).listen(this.port);\n }\n Logger.info('Epsilon server is listening');\n process.on('SIGINT', () => {\n Logger.info('Caught SIGINT - shutting down test server...');\n this.aborted = true;\n res(true);\n });\n }\n catch (err) {\n Logger.error('Local server failed : %s', err, err);\n rej(err);\n }\n });\n }\n async requestHandler(request, response) {\n const context = {\n awsRequestId: 'LOCAL-' + StringRatchet.createType4Guid(),\n getRemainingTimeInMillis() {\n return 300000;\n },\n };\n const evt = await LocalServer.messageToApiGatewayEvent(request, context);\n const logEventLevel = EventUtil.eventIsAGraphQLIntrospection(evt) ? LoggerLevelName.silly : LoggerLevelName.info;\n if (evt.path == '/epsilon-poison-pill') {\n this.aborted = true;\n return true;\n }\n else {\n const result = await this.globalHandler.lambdaHandler(evt, context);\n const written = await LocalServer.writeProxyResultToServerResponse(result, response);\n return written;\n }\n }\n static async bodyAsBase64String(request) {\n return new Promise((res, rej) => {\n const body = [];\n request.on('data', (chunk) => {\n body.push(chunk);\n });\n request.on('end', () => {\n const rval = Buffer.concat(body).toString('base64');\n res(rval);\n });\n });\n }\n static async messageToApiGatewayEvent(request, context) {\n const bodyString = await LocalServer.bodyAsBase64String(request);\n const stageIdx = request.url.indexOf('/', 1);\n const stage = request.url.substring(1, stageIdx);\n const path = request.url.substring(stageIdx + 1);\n const reqTime = new Date().getTime();\n const formattedTime = DateTime.utc().toFormat('dd/MMM/yyyy:hh:mm:ss ZZ');\n const queryIdx = request.url.indexOf('?');\n const queryStringParams = queryIdx > -1 ? qs.parse(request.url.substring(queryIdx + 1)) : {};\n const headers = Object.assign({}, request.headers);\n headers['X-Forwarded-Proto'] = 'http';\n const rval = {\n body: bodyString,\n multiValueHeaders: {},\n multiValueQueryStringParameters: {},\n resource: '/{proxy+}',\n path: request.url,\n httpMethod: request.method.toLowerCase(),\n isBase64Encoded: true,\n queryStringParameters: queryStringParams,\n pathParameters: {\n proxy: path,\n },\n stageVariables: {\n baz: 'qux',\n },\n headers: headers,\n requestContext: {\n accountId: '123456789012',\n resourceId: '123456',\n stage: stage,\n requestId: context.awsRequestId,\n requestTime: formattedTime,\n requestTimeEpoch: reqTime,\n identity: null,\n path: request.url,\n domainName: request.headers['host'],\n resourcePath: '/{proxy+}',\n httpMethod: request.method.toLowerCase(),\n apiId: '1234567890',\n protocol: 'HTTP/1.1',\n },\n };\n return rval;\n }\n static async writeProxyResultToServerResponse(proxyResult, response) {\n const isGraphQLSchemaResponse = !!proxyResult && !!proxyResult.body && proxyResult.body.indexOf('{\"data\":{\"__schema\"') > -1;\n if (!isGraphQLSchemaResponse) {\n Logger.debug('Result: %j', proxyResult);\n }\n response.statusCode = proxyResult.statusCode;\n if (proxyResult.headers) {\n Object.keys(proxyResult.headers).forEach((hk) => {\n response.setHeader(hk, String(proxyResult.headers[hk]));\n });\n }\n if (proxyResult.multiValueHeaders) {\n Object.keys(proxyResult.multiValueHeaders).forEach((hk) => {\n response.setHeader(hk, proxyResult.multiValueHeaders[hk].join(','));\n });\n }\n const toWrite = proxyResult.isBase64Encoded ? Buffer.from(proxyResult.body, 'base64') : Buffer.from(proxyResult.body);\n response.end(toWrite);\n return !!proxyResult.body;\n }\n static async runSampleBatchOnlyServerFromCliArgs(args) {\n Logger.setLevel(LoggerLevelName.debug);\n const handler = await SampleServerComponents.createSampleBatchOnlyEpsilonGlobalHandler('SampleBatchOnlyLocalServer-' + Date.now());\n const testServer = new LocalServer(handler);\n const res = await testServer.runServer();\n Logger.info('Res was : %s', res);\n }\n static async runSampleLocalServerFromCliArgs(args) {\n Logger.setLevel(LoggerLevelName.debug);\n const localTokenHandler = new LocalWebTokenManipulator(['abcd1234'], 'sample-server');\n const token = await localTokenHandler.createJWTStringAsync('asdf', {}, ['USER'], 3600);\n Logger.info('Use token: %s', token);\n const handler = await SampleServerComponents.createSampleEpsilonGlobalHandler('SampleLocalServer-' + Date.now());\n const testServer = new LocalServer(handler, 8888, true);\n const res = await testServer.runServer();\n Logger.info('Res was : %s', res);\n }\n}\n//# sourceMappingURL=local-server.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { LoggerLevelName } from '@bitblit/ratchet-common';\nimport http from 'http';\nimport { EventUtil } from './http/event-util.js';\nimport fetch from 'cross-fetch';\nimport { LocalServer } from './local-server.js';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nexport class LocalContainerServer {\n port;\n server;\n aborted = false;\n constructor(port = 8889) {\n this.port = port;\n }\n async runServer() {\n return new Promise((res, rej) => {\n try {\n Logger.info('Starting Epsilon server on port %d', this.port);\n this.server = http.createServer(this.requestHandler.bind(this)).listen(this.port);\n Logger.info('Epsilon server is listening');\n process.on('SIGINT', () => {\n Logger.info('Caught SIGINT - shutting down test server...');\n this.aborted = true;\n res(true);\n });\n }\n catch (err) {\n Logger.error('Local server failed : %s', err, err);\n rej(err);\n }\n });\n }\n async requestHandler(request, response) {\n const context = {\n awsRequestId: 'LOCAL-' + StringRatchet.createType4Guid(),\n getRemainingTimeInMillis() {\n return 300000;\n },\n };\n const evt = await LocalServer.messageToApiGatewayEvent(request, context);\n const logEventLevel = EventUtil.eventIsAGraphQLIntrospection(evt) ? LoggerLevelName.silly : LoggerLevelName.info;\n Logger.logByLevel(logEventLevel, 'Processing event: %j', evt);\n if (evt.path == '/epsilon-poison-pill') {\n this.aborted = true;\n return true;\n }\n else {\n const url = 'http://localhost:8080/2015-03-31/functions/function/invocations';\n try {\n const postResp = await fetch(url, { method: 'POST', body: JSON.stringify(evt) });\n const respBody = await postResp.json();\n const result = respBody;\n const written = await LocalServer.writeProxyResultToServerResponse(result, response);\n return written;\n }\n catch (err) {\n Logger.error('Failed: %s', err);\n return '{\"bad\":true}';\n }\n }\n }\n static async runFromCliArgs(args) {\n try {\n Logger.setLevel(LoggerLevelName.debug);\n Logger.debug('Running local container server : %j', process?.argv);\n const testServer = new LocalContainerServer();\n await testServer.runServer();\n Logger.info('Got res server');\n process.exit(0);\n }\n catch (err) {\n Logger.error('Error : %s', err);\n process.exit(1);\n }\n }\n}\n//# sourceMappingURL=local-container-server.js.map","import { BackgroundExecutionEventType } from './background-execution-event-type.js';\nimport { ContextUtil } from '../util/context-util.js';\nexport class BackgroundDynamoLogTableHandler {\n dynamo;\n tableName;\n env;\n backgroundQueueName;\n constructor(dynamo, tableName, env, backgroundQueueName) {\n this.dynamo = dynamo;\n this.tableName = tableName;\n this.env = env;\n this.backgroundQueueName = backgroundQueueName;\n }\n async onEvent(event) {\n const entry = {\n env: this.env,\n backgroundQueueName: this.backgroundQueueName,\n requestId: ContextUtil.currentRequestId(),\n guid: event.guid,\n processTypeName: event.processorType,\n state: event.type.toString(),\n timestampEpochMs: new Date().getTime(),\n };\n if (event.type == BackgroundExecutionEventType.DataValidationError) {\n const errors = event?.errors?.length ? event.errors : ['No-Error'];\n entry.errors = errors;\n }\n else if (event.type == BackgroundExecutionEventType.ProcessStarting) {\n entry.params = event.data;\n }\n else if (event.type == BackgroundExecutionEventType.ExecutionFailedError) {\n const errors = event?.errors?.length ? event.errors : ['No-Error'];\n entry.errors = errors;\n }\n await this.dynamo.simplePut(this.tableName, entry);\n }\n}\n//# sourceMappingURL=background-dynamo-log-table-handler.js.map","import util from 'util';\nexport class EpsilonBackgroundProcessError extends Error {\n static EPSILON_BACKGROUND_PROCESS_ERROR_FLAG_KEY = '__epsilonBackgroundProcessErrorFlag';\n _errors;\n _detailErrorCode;\n _details;\n _requestId;\n _wrappedError;\n constructor(...errors) {\n super(EpsilonBackgroundProcessError.combineErrorStringsWithDefault(errors));\n Object.setPrototypeOf(this, EpsilonBackgroundProcessError.prototype);\n this._errors = errors;\n this[EpsilonBackgroundProcessError.EPSILON_BACKGROUND_PROCESS_ERROR_FLAG_KEY] = true;\n }\n static combineErrorStringsWithDefault(errors, defMessage = 'Internal Server Error') {\n return errors && errors.length > 0 ? errors.join(',') : defMessage;\n }\n setFormattedErrorMessage(format, ...input) {\n const msg = util.format(format, ...input);\n this.errors = [msg];\n }\n withFormattedErrorMessage(format, ...input) {\n this.setFormattedErrorMessage(format, ...input);\n return this;\n }\n withErrors(errors) {\n this.errors = errors;\n return this;\n }\n withDetailErrorCode(detailErrorCode) {\n this._detailErrorCode = detailErrorCode;\n return this;\n }\n withDetails(details) {\n this._details = details;\n return this;\n }\n withRequestId(requestId) {\n this._requestId = requestId;\n return this;\n }\n withWrappedError(err) {\n this._wrappedError = err;\n return this;\n }\n isWrappedError() {\n return !!this._wrappedError;\n }\n static wrapError(err) {\n let rval = null;\n if (EpsilonBackgroundProcessError.objectIsEpsilonBackgroundProcessError(err)) {\n rval = err;\n }\n else {\n rval = new EpsilonBackgroundProcessError(err.message).withWrappedError(err);\n }\n return rval;\n }\n static objectIsEpsilonBackgroundProcessError(obj) {\n return obj && obj[EpsilonBackgroundProcessError.EPSILON_BACKGROUND_PROCESS_ERROR_FLAG_KEY] === true;\n }\n set errors(value) {\n this._errors = value || ['Internal Server Error'];\n this.message = EpsilonBackgroundProcessError.combineErrorStringsWithDefault(this._errors);\n }\n get errors() {\n return this._errors;\n }\n set detailErrorCode(value) {\n this._detailErrorCode = value;\n }\n get detailErrorCode() {\n return this._detailErrorCode;\n }\n set details(value) {\n this._details = value;\n }\n get details() {\n return this._details;\n }\n set requestId(value) {\n this._requestId = value || 'MISSING';\n }\n get requestId() {\n return this._requestId;\n }\n set wrappedError(value) {\n this._wrappedError = value;\n }\n get wrappedError() {\n return this._wrappedError;\n }\n}\n//# sourceMappingURL=epsilon-background-process-error.js.map","import { S3CacheRatchet } from '@bitblit/ratchet-aws';\nimport { AbstractBackgroundManager } from './manager/abstract-background-manager.js';\nimport { ErrorRatchet } from '@bitblit/ratchet-common';\nimport { Logger } from '@bitblit/ratchet-common';\nexport class S3BackgroundTransactionLogger {\n cfg;\n s3TransactionLogCacheRatchet;\n constructor(cfg) {\n this.cfg = cfg;\n const err = S3BackgroundTransactionLogger.validateConfig(cfg);\n if (err.length) {\n ErrorRatchet.throwFormattedErr('Invalid S3BackgroundTransactionLogger config : %j', err);\n }\n this.s3TransactionLogCacheRatchet = new S3CacheRatchet(this.cfg.s3, this.cfg.bucket);\n }\n async logTransaction(txLog) {\n if (txLog) {\n if (txLog.request?.guid) {\n await this.s3TransactionLogCacheRatchet.writeObjectToCacheFile(AbstractBackgroundManager.backgroundGuidToPath(this.cfg.prefix, txLog.request.guid), txLog);\n }\n else {\n Logger.warn('Could not write transaction record - no guid defined : %j', txLog);\n }\n }\n else {\n Logger.silly('Skipping write of null log');\n }\n }\n async readTransactionLog(txGuid) {\n const path = AbstractBackgroundManager.backgroundGuidToPath(this.cfg.prefix, txGuid);\n const log = await this.s3TransactionLogCacheRatchet.fetchCacheFileAsObject(path);\n return log;\n }\n static validateConfig(cfg) {\n const rval = [];\n if (cfg) {\n if (!cfg.s3) {\n rval.push('You must supply an S3 object');\n }\n if (!cfg.bucket) {\n rval.push('You must supply a bucket');\n }\n if (!cfg.timeToLiveDays) {\n rval.push('You must supply a timeToLiveDays');\n }\n }\n else {\n rval.push('No config defined');\n }\n return rval;\n }\n}\n//# sourceMappingURL=s3-background-transaction-logger.js.map","import { ErrorRatchet } from '@bitblit/ratchet-common';\nimport { Logger } from '@bitblit/ratchet-common';\nimport { NumberRatchet } from '@bitblit/ratchet-common';\nimport { DeleteMessageCommand, GetQueueAttributesCommand, ReceiveMessageCommand, SendMessageCommand, } from '@aws-sdk/client-sqs';\nimport { EpsilonConstants } from '../../epsilon-constants.js';\nimport { AbstractBackgroundManager } from './abstract-background-manager.js';\nimport { BackgroundValidator } from '../background-validator.js';\nimport { PublishCommand } from '@aws-sdk/client-sns';\nexport class AwsSqsSnsBackgroundManager extends AbstractBackgroundManager {\n _awsConfig;\n _sqs;\n _sns;\n constructor(_awsConfig, _sqs, _sns) {\n super();\n this._awsConfig = _awsConfig;\n this._sqs = _sqs;\n this._sns = _sns;\n const cfgErrors = BackgroundValidator.validateAwsConfig(_awsConfig);\n if (cfgErrors.length) {\n ErrorRatchet.throwFormattedErr('Cannot start - invalid AWS config : %j', cfgErrors);\n }\n }\n get backgroundManagerName() {\n return 'AwsSqsSnsBackgroundManager';\n }\n get awsConfig() {\n return this._awsConfig;\n }\n get sqs() {\n return this._sqs;\n }\n get sns() {\n return this._sns;\n }\n async addEntryToQueue(entry, fireStartMessage) {\n try {\n const wrapped = this.wrapEntryForInternal(entry);\n const rval = wrapped.guid;\n const params = {\n DelaySeconds: 0,\n MessageBody: JSON.stringify(wrapped),\n MessageGroupId: entry.type,\n QueueUrl: this.awsConfig.queueUrl,\n };\n Logger.info('Add entry to queue (remote) : %j : Start : %s', params, fireStartMessage);\n const result = await this.sqs.send(new SendMessageCommand(params));\n if (fireStartMessage) {\n const fireResult = await this.fireStartProcessingRequest();\n Logger.silly('FireResult : %s', fireResult);\n }\n Logger.info('Background process %s using message id %s', rval, result.MessageId);\n return rval;\n }\n catch (error) {\n Logger.error('Error inserting background entry into SQS queue : %j', error);\n throw new Error('Error inserting background entry into SQS queue : ' + error['code'] + ' : ' + error['name']);\n }\n }\n async fireImmediateProcessRequest(entry) {\n let rval = null;\n const wrapped = this.wrapEntryForInternal(entry);\n rval = wrapped.guid;\n try {\n Logger.info('Fire immediately (remote) : %j ', entry);\n const toWrite = {\n type: EpsilonConstants.BACKGROUND_SNS_IMMEDIATE_RUN_FLAG,\n backgroundEntry: wrapped,\n };\n const msg = JSON.stringify(toWrite);\n const snsId = await this.writeMessageToSnsTopic(msg);\n Logger.debug('Background guid %s Wrote message : %s to SNS : %s', rval, msg, snsId);\n }\n catch (err) {\n Logger.error('Failed to fireImmediateProcessRequest : %s', err, err);\n }\n return rval;\n }\n async fireStartProcessingRequest() {\n let rval = null;\n try {\n Logger.info('Fire start processing request (remote)');\n rval = await this.writeMessageToSnsTopic(EpsilonConstants.BACKGROUND_SNS_START_MARKER);\n }\n catch (err) {\n Logger.error('Failed to fireStartProcessingRequest : %s', err, err);\n }\n return rval;\n }\n async fetchApproximateNumberOfQueueEntries() {\n let rval = null;\n const all = await this.fetchCurrentQueueAttributes();\n rval = NumberRatchet.safeNumber(all.Attributes['ApproximateNumberOfMessages']);\n return rval;\n }\n async fetchCurrentQueueAttributes() {\n let rval = null;\n const req = {\n AttributeNames: ['All'],\n QueueUrl: this.awsConfig.queueUrl,\n };\n rval = await this.sqs.send(new GetQueueAttributesCommand(req));\n return rval;\n }\n async writeMessageToSnsTopic(message) {\n let rval = null;\n const params = {\n Message: message,\n TopicArn: this.awsConfig.notificationArn,\n };\n Logger.debug('Writing message to SNS topic : j', params);\n const result = await this.sns.send(new PublishCommand(params));\n rval = result.MessageId;\n return rval;\n }\n async takeEntryFromBackgroundQueue() {\n const rval = [];\n const params = {\n MaxNumberOfMessages: 1,\n QueueUrl: this.awsConfig.queueUrl,\n VisibilityTimeout: 300,\n WaitTimeSeconds: 0,\n };\n const message = await this.sqs.send(new ReceiveMessageCommand(params));\n if (message && message.Messages && message.Messages.length > 0) {\n for (let i = 0; i < message.Messages.length; i++) {\n const m = message.Messages[i];\n try {\n const parsedBody = JSON.parse(m.Body);\n if (!parsedBody.type) {\n Logger.warn('Dropping invalid background entry : %j', parsedBody);\n }\n else {\n rval.push(parsedBody);\n }\n Logger.debug('Removing message from queue');\n const delParams = {\n QueueUrl: this.awsConfig.queueUrl,\n ReceiptHandle: m.ReceiptHandle,\n };\n const delResult = await this.sqs.send(new DeleteMessageCommand(delParams));\n Logger.silly('Delete result : %j', delResult);\n }\n catch (err) {\n Logger.warn('Error parsing message, dropping : %j', m);\n }\n }\n }\n else {\n Logger.debug('No messages found (likely end of recursion)');\n }\n return rval;\n }\n}\n//# sourceMappingURL=aws-sqs-sns-background-manager.js.map","export class RatchetEpsilonCommonInfo {\n constructor() { }\n static buildInformation() {\n const val = {\n version: 'LOCAL-SNAPSHOT',\n hash: 'LOCAL-HASH',\n branch: 'LOCAL-BRANCH',\n tag: 'LOCAL-TAG',\n timeBuiltISO: 'LOCAL-TIME-ISO',\n notes: 'LOCAL-NOTES',\n };\n return val;\n }\n}\n//# sourceMappingURL=ratchet-epsilon-common-info.js.map","import { StringRatchet } from '@bitblit/ratchet-common';\nimport { ContextUtil } from '../util/context-util.js';\nexport class BuiltInTraceIdGenerators {\n static fullAwsRequestId() {\n return ContextUtil.defaultedCurrentRequestId();\n }\n static shortAwsRequestId() {\n let rval = BuiltInTraceIdGenerators.fullAwsRequestId();\n if (rval.length > 10) {\n let idx = rval.lastIndexOf('-');\n idx = idx === -1 ? rval.length - 10 : idx;\n rval = rval.substring(idx);\n }\n return rval;\n }\n static fixedLengthHex(length = 10) {\n return StringRatchet.createRandomHexString(length);\n }\n}\n//# sourceMappingURL=built-in-trace-id-generators.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { PromiseRatchet } from '@bitblit/ratchet-common';\nimport { DurationRatchet } from '@bitblit/ratchet-common';\nimport { NumberRatchet } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nexport class RetryProcessor {\n delegate;\n opts;\n static RETRY_FIELD_NAME = '___RetryProcessorTryNumber';\n constructor(delegate, opts) {\n this.delegate = delegate;\n this.opts = opts;\n }\n get typeName() {\n return StringRatchet.trimToEmpty(this.opts?.typePrefix) + this.delegate.typeName + StringRatchet.trimToEmpty(this.opts?.typeSuffix);\n }\n async handleEvent(data, mgr) {\n const tryNumber = data && data[RetryProcessor.RETRY_FIELD_NAME] ? NumberRatchet.safeNumber(data[RetryProcessor.RETRY_FIELD_NAME]) : 1;\n const dataCopy = data ? Object.assign({}, data) : null;\n delete dataCopy[RetryProcessor.RETRY_FIELD_NAME];\n Logger.info('RetryProcessor : %s : Try %d of %d', this.delegate.typeName, tryNumber, this.opts.retryCount);\n try {\n await this.delegate.handleEvent(dataCopy, mgr);\n }\n catch (err) {\n Logger.error('Failed to process : %s', err, err);\n if (tryNumber < this.opts.retryCount) {\n const waitTimeMS = tryNumber * this.opts.baseDelayMS;\n Logger.info('Firing automatic retry after a wait of %s', DurationRatchet.formatMsDuration(waitTimeMS));\n await PromiseRatchet.wait(waitTimeMS);\n const wrapped = dataCopy || {};\n wrapped[RetryProcessor.RETRY_FIELD_NAME] = tryNumber + 1;\n await mgr.fireImmediateProcessRequestByParts(this.typeName, wrapped);\n }\n else {\n Logger.error('That was the last try - giving up');\n }\n }\n }\n}\n//# sourceMappingURL=retry-processor.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { NotFoundError } from '../../http/error/not-found-error.js';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nexport class DaemonHandler {\n daemon;\n inConfig;\n static ALLOW_EVERYTHING_AUTHORIZER = async (evt, proc) => {\n return true;\n };\n config;\n constructor(daemon, inConfig) {\n this.daemon = daemon;\n this.inConfig = inConfig;\n this.config = inConfig || {};\n this.config.authorizer = this.config.authorizer || DaemonHandler.ALLOW_EVERYTHING_AUTHORIZER;\n this.config.groupSelector = this.config.groupSelector || ((evt) => Promise.resolve(daemon.defaultGroup));\n this.config.fetchDaemonStatusByPublicTokenPathParameter =\n StringRatchet.trimToNull(this.config.fetchDaemonStatusByPublicTokenPathParameter) || 'publicToken';\n this.config.fetchDaemonStatusPathParameter = StringRatchet.trimToNull(this.config.fetchDaemonStatusPathParameter) || 'key';\n }\n async fetchDaemonStatusByPublicToken(evt) {\n const publicToken = evt.pathParameters[this.config.fetchDaemonStatusByPublicTokenPathParameter];\n Logger.info('Fetching daemon status for token: %s', publicToken);\n let rval = await this.daemon.statFromPublicToken(publicToken);\n const canRead = rval ? await this.config.authorizer(evt, rval) : false;\n rval = canRead ? rval : null;\n if (rval === null) {\n throw new NotFoundError('No such token : ' + publicToken);\n }\n return rval;\n }\n async fetchDaemonStatus(evt) {\n const daemonKey = evt.pathParameters[this.config.fetchDaemonStatusPathParameter];\n Logger.info('Fetching daemon status for : %s', daemonKey);\n let rval = await this.daemon.stat(daemonKey);\n const canRead = rval ? await this.config.authorizer(evt, rval) : false;\n rval = canRead ? rval : null;\n if (rval === null) {\n throw new NotFoundError('No such key : ' + daemonKey);\n }\n return rval;\n }\n async listDaemonStatus(evt) {\n const group = await this.config.groupSelector(evt);\n const keys = await this.daemon.list(group);\n const allowed = [];\n for (let i = 0; i < keys.length; i++) {\n const canRead = await this.config.authorizer(evt, keys[i]);\n if (canRead) {\n allowed.push(keys[i]);\n }\n }\n const rval = {\n results: allowed,\n nextToken: null,\n };\n return rval;\n }\n}\n//# sourceMappingURL=daemon-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { BooleanRatchet } from '@bitblit/ratchet-common';\nexport class RunBackgroundProcessFromCommandLine {\n static async runFromCliArgs(args) {\n if (args.length > 1) {\n const procName = args[0];\n const dryRun = args.length > 1 && BooleanRatchet.parseBool(args[1]);\n const data = args.length > 2 ? JSON.parse(args[2]) : null;\n const meta = args.length > 3 ? JSON.parse(args[3]) : null;\n const epsilon = null;\n if (dryRun) {\n Logger.info('Dry-Run, would have sent : %s %j %j', procName, data, meta);\n }\n else {\n await epsilon.processSingleBackgroundByParts(procName, data, meta);\n }\n }\n else {\n console.log('Usage : run-background-process {processName} {dryRun true/false} {dataJson} {metaJson}');\n }\n }\n}\n//# sourceMappingURL=run-background-process-from-command-line.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport net from 'net';\nexport class TestErrorServer {\n port;\n server;\n aborted = false;\n constructor(port = 9999) {\n this.port = port;\n }\n async runServer() {\n Logger.info('Starting Test Error net server on port %d', this.port);\n return new Promise((res, rej) => {\n const server = new net.Server({});\n server.listen(this.port, () => {\n Logger.info('Server listening for connection requests on socket localhost: %s', this.port);\n });\n server.on('connection', async (socket) => {\n Logger.info('X: A new connection has been established.');\n socket.write('Hello, client.');\n socket.on('data', (chunk) => {\n Logger.info('Data received from client: %s', chunk);\n });\n socket.on('end', () => {\n Logger.info('Closing connection with the client');\n });\n socket.on('error', (err) => {\n Logger.info('Error: %s', err);\n });\n });\n });\n }\n async requestHandler(request, response) {\n Logger.info('Got request %d - closing socket', request);\n request.setTimeout(100);\n response.end('x');\n }\n static async runFromCliArgs(args) {\n Logger.info('test-error-server requested (cli is %s) - starting', process?.argv);\n const testServer = new TestErrorServer();\n await testServer.runServer();\n Logger.info('Got res server');\n process.exit(0);\n }\n}\n//# sourceMappingURL=test-error-server.js.map","import { AbstractRatchetCliHandler } from '@bitblit/ratchet-node-only';\nimport { RunBackgroundProcessFromCommandLine } from './run-background-process-from-command-line.js';\nimport { TestErrorServer } from '../sample/test-error-server.js';\nimport { LocalContainerServer } from '../local-container-server.js';\nimport { RatchetEpsilonCommonInfo } from '../build/ratchet-epsilon-common-info.js';\nimport { LocalServer } from '../local-server.js';\nexport class RatchetCliHandler extends AbstractRatchetCliHandler {\n fetchHandlerMap() {\n return {\n 'run-background-process': RunBackgroundProcessFromCommandLine.runFromCliArgs,\n 'run-test-error-server': TestErrorServer.runFromCliArgs,\n 'run-local-container-server': LocalContainerServer.runFromCliArgs,\n 'run-sample-local-server': LocalServer.runSampleLocalServerFromCliArgs,\n 'run-sample-local-batch-server': LocalServer.runSampleLocalServerFromCliArgs,\n };\n }\n fetchVersionInfo() {\n return RatchetEpsilonCommonInfo.buildInformation();\n }\n}\n//# sourceMappingURL=ratchet-cli-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { LocalWebTokenManipulator } from './local-web-token-manipulator.js';\nimport { EpsilonConstants } from '../../epsilon-constants.js';\nexport class ApiGatewayAdapterAuthenticationHandler {\n webTokenManipulator;\n constructor(issuer, encryptionKeys) {\n this.webTokenManipulator = new LocalWebTokenManipulator([encryptionKeys], issuer);\n }\n lambdaHandler(event, context, callback) {\n Logger.info('Got event : %j', event);\n const srcString = ApiGatewayAdapterAuthenticationHandler.extractTokenStringFromAuthorizerEvent(event);\n if (srcString) {\n const methodArn = event.methodArn;\n this.webTokenManipulator\n .parseAndValidateJWTStringAsync(srcString)\n .then((parsed) => {\n if (parsed) {\n callback(null, this.createPolicy(methodArn, srcString, parsed));\n }\n else {\n Logger.info('Invalid bearer token');\n callback(new Error('Unauthorized'));\n }\n })\n .catch((err) => {\n Logger.error('Exception parsing token : %s', err);\n callback(new Error('Unauthorized'));\n });\n }\n else {\n Logger.info('Token not supplied');\n callback(new Error('Unauthorized'));\n }\n }\n createPolicy(methodArn, srcString, userOb) {\n const tmp = methodArn.split(':');\n const apiGatewayArnTmp = tmp[5].split('/');\n const awsAccountId = tmp[4];\n const region = tmp[3];\n const stage = apiGatewayArnTmp[1];\n const restApiId = apiGatewayArnTmp[0];\n const response = {\n principalId: 'user',\n policyDocument: {\n Version: '2012-10-17',\n Statement: [\n {\n Action: 'execute-api:Invoke',\n Effect: 'Allow',\n Resource: ['arn:aws:execute-api:' + region + ':' + awsAccountId + ':' + restApiId + '/' + stage + '/*/*'],\n },\n ],\n },\n context: {\n userJSON: JSON.stringify(userOb),\n srcData: srcString,\n },\n };\n return response;\n }\n static extractTokenStringFromAuthorizerEvent(event) {\n Logger.silly('Extracting token from event : %j', event);\n let rval = null;\n if (event && event.authorizationToken) {\n const token = event.authorizationToken;\n if (token && token.startsWith(EpsilonConstants.AUTH_HEADER_PREFIX)) {\n rval = token.substring(EpsilonConstants.AUTH_HEADER_PREFIX.length);\n }\n }\n return rval;\n }\n}\n//# sourceMappingURL=api-gateway-adapter-authentication-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport jwt from 'jsonwebtoken';\nimport jwks from 'jwks-rsa';\nexport class Auth0WebTokenManipulator {\n clientId;\n jwksUri;\n issuer;\n jwksClient;\n constructor(clientId, jwksUri, issuer) {\n this.clientId = clientId;\n this.jwksUri = jwksUri;\n this.issuer = issuer;\n }\n async extractTokenFromAuthorizationHeader(authHeader) {\n let tokenString = StringRatchet.trimToEmpty(authHeader);\n if (tokenString.toLowerCase().startsWith('bearer ')) {\n tokenString = tokenString.substring(7);\n }\n const validated = tokenString ? await this.parseAndValidateAuth0Token(tokenString, false) : null;\n return validated;\n }\n async parseAndValidateAuth0Token(auth0Token, allowExpired = false) {\n Logger.debug('Validating Auth0 token : %s', StringRatchet.obscure(auth0Token, 4));\n const fullToken = jwt.decode(auth0Token, { complete: true });\n const kid = fullToken?.header?.kid;\n const nowEpochSeconds = Math.floor(new Date().getTime() / 1000);\n const pubKey = await this.fetchSigningKey(kid);\n const validated = jwt.verify(auth0Token, pubKey, {\n audience: this.clientId,\n issuer: this.issuer,\n ignoreExpiration: allowExpired,\n clockTimestamp: nowEpochSeconds,\n });\n return validated;\n }\n async fetchSigningKey(kid) {\n const jClient = await this.fetchJwksClient();\n return new Promise((res, rej) => {\n jClient.getSigningKey(kid, (err, key) => {\n if (err) {\n rej(err);\n }\n else {\n res(key.publicKey || key.rsaPublicKey);\n }\n });\n });\n }\n async fetchJwksClient() {\n if (!this.jwksClient) {\n this.jwksClient = jwks({\n cache: true,\n cacheMaxEntries: 5,\n cacheMaxAge: 1000 * 60 * 60 * 10,\n jwksUri: this.jwksUri,\n });\n }\n return this.jwksClient;\n }\n}\n//# sourceMappingURL=auth0-web-token-manipulator.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport jwt from 'jsonwebtoken';\nimport jwks from 'jwks-rsa';\nimport fetch from 'cross-fetch';\nexport class GoogleWebTokenManipulator {\n clientId;\n static GOOGLE_DISCOVERY_DOCUMENT = 'https://accounts.google.com/.well-known/openid-configuration';\n cacheGoogleDiscoveryDocument;\n jwksClient;\n constructor(clientId) {\n this.clientId = clientId;\n }\n async extractTokenFromAuthorizationHeader(authHeader) {\n let tokenString = StringRatchet.trimToEmpty(authHeader);\n if (tokenString.toLowerCase().startsWith('bearer ')) {\n tokenString = tokenString.substring(7);\n }\n const validated = !!tokenString ? await this.parseAndValidateGoogleToken(tokenString, false) : null;\n return validated;\n }\n async parseAndValidateGoogleToken(googleToken, allowExpired = false) {\n Logger.debug('Auth : %s', StringRatchet.obscure(googleToken, 4));\n const fullToken = jwt.decode(googleToken, { complete: true });\n const kid = fullToken.header.kid;\n const nowEpochSeconds = Math.floor(new Date().getTime() / 1000);\n const pubKey = await this.fetchSigningKey(kid);\n const validated = jwt.verify(googleToken, pubKey, {\n audience: this.clientId,\n issuer: ['https://accounts.google.com', 'accounts.google.com'],\n ignoreExpiration: allowExpired,\n clockTimestamp: nowEpochSeconds,\n });\n return validated;\n }\n async fetchSigningKey(kid) {\n const jClient = await this.fetchJwksClient();\n return new Promise((res, rej) => {\n jClient.getSigningKey(kid, (err, key) => {\n if (err) {\n rej(err);\n }\n else {\n res(key.publicKey || key.rsaPublicKey);\n }\n });\n });\n }\n async fetchJwksClient() {\n if (!this.jwksClient) {\n const discDoc = await this.fetchGoogleDiscoveryDocument();\n const client = jwks({\n cache: true,\n cacheMaxEntries: 5,\n cacheMaxAge: 1000 * 60 * 60 * 10,\n jwksUri: discDoc.jwks_uri,\n });\n this.jwksClient = client;\n }\n return this.jwksClient;\n }\n async fetchGoogleDiscoveryDocument() {\n if (!this.cacheGoogleDiscoveryDocument) {\n const resp = await fetch(GoogleWebTokenManipulator.GOOGLE_DISCOVERY_DOCUMENT);\n const doc = await resp.json();\n this.cacheGoogleDiscoveryDocument = doc;\n }\n return this.cacheGoogleDiscoveryDocument;\n }\n}\n//# sourceMappingURL=google-web-token-manipulator.js.map","import { StringRatchet } from '@bitblit/ratchet-common';\nimport { RequireRatchet } from '@bitblit/ratchet-common';\nimport { ExpiredJwtHandling } from '@bitblit/ratchet-common';\nexport class JwtRatchetLocalWebTokenManipulator {\n _jwtRatchet;\n _issuer;\n constructor(_jwtRatchet, _issuer) {\n this._jwtRatchet = _jwtRatchet;\n this._issuer = _issuer;\n RequireRatchet.notNullOrUndefined(_jwtRatchet, '_jwtRatchet');\n RequireRatchet.notNullOrUndefined(StringRatchet.trimToNull(_issuer), '_issuer');\n }\n get jwtRatchet() {\n return this._jwtRatchet;\n }\n get issuer() {\n return this._issuer;\n }\n async extractTokenFromAuthorizationHeader(header) {\n let tokenString = StringRatchet.trimToEmpty(header);\n if (tokenString.toLowerCase().startsWith('bearer ')) {\n tokenString = tokenString.substring(7);\n }\n const validated = !!tokenString ? await this.jwtRatchet.decodeToken(tokenString, ExpiredJwtHandling.THROW_EXCEPTION) : null;\n return validated;\n }\n}\n//# sourceMappingURL=jwt-ratchet-local-web-token-manipulator.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class BadGateway extends RestfulApiHttpError {\n static HTTP_CODE = 502;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(BadGateway.HTTP_CODE);\n }\n}\n//# sourceMappingURL=bad-gateway.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class ConflictError extends RestfulApiHttpError {\n static HTTP_CODE = 409;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(ConflictError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=conflict-error.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class GatewayTimeout extends RestfulApiHttpError {\n static HTTP_CODE = 504;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(GatewayTimeout.HTTP_CODE);\n }\n}\n//# sourceMappingURL=gateway-timeout.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class MethodNotAllowedError extends RestfulApiHttpError {\n static HTTP_CODE = 405;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(MethodNotAllowedError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=method-not-allowed-error.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class ServiceUnavailable extends RestfulApiHttpError {\n static HTTP_CODE = 503;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(ServiceUnavailable.HTTP_CODE);\n }\n}\n//# sourceMappingURL=service-unavailable.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class TooManyRequestsError extends RestfulApiHttpError {\n static HTTP_CODE = 429;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(TooManyRequestsError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=too-many-requests-error.js.map","import yaml from 'js-yaml';\nimport { Logger } from '@bitblit/ratchet-common';\nexport class OpenApiDocModifier {\n options;\n constructor(options) {\n this.options = options;\n }\n modifyOpenApiDoc(yamlString) {\n let rval;\n if (!!yamlString && !!this.options) {\n try {\n const openApi = yaml.load(yamlString);\n const removeTags = this.options.removeTags ? this.options.removeTags.map((t) => t.toLowerCase()) : [];\n if (this.options.newServerPath) {\n openApi['servers'] = [{ url: this.options.newServerPath }];\n }\n if (!!this.options.removeTags && openApi['tags']) {\n if (openApi['tags']) {\n openApi['tags'] = openApi.tags.filter((f) => {\n const n = !!f && !!f['name'] ? f['name'].toLowerCase() : '';\n const i = removeTags.indexOf(n);\n return i === -1;\n });\n }\n }\n if (openApi['paths']) {\n let newPaths = {};\n Object.keys(openApi['paths']).forEach((p) => {\n const path = openApi['paths'][p];\n Object.keys(path).forEach((verb) => {\n const entry = path[verb];\n entry.tags = !!entry.tags ? entry.tags.filter((t) => removeTags.lastIndexOf(t.toLowerCase()) == -1) : entry.tags;\n const matcher = verb.toLowerCase() + ' ' + p.toLowerCase();\n if (this.matchNone(matcher, this.options.removeEndpoints)) {\n newPaths[p] = newPaths[p] || {};\n newPaths[p][verb] = entry;\n }\n });\n });\n if (this.options.sortEndpoints) {\n const keys = Object.keys(newPaths).sort();\n const newPaths2 = {};\n keys.forEach((k) => {\n newPaths2[k] = newPaths[k];\n });\n newPaths = newPaths2;\n }\n openApi['paths'] = newPaths;\n }\n let remSchemas = this.options.removeSchemas || [];\n remSchemas = remSchemas.map((s) => s.toLowerCase());\n if (openApi['components'] && openApi['components']['schemas']) {\n const keys = Object.keys(openApi['components']['schemas']).sort();\n const newComp = {};\n keys.forEach((k) => {\n if (remSchemas.indexOf(k.toLowerCase()) === -1) {\n newComp[k] = openApi['components']['schemas'][k];\n }\n });\n openApi['components']['schemas'] = newComp;\n }\n rval = yaml.dump(openApi);\n }\n catch (err) {\n Logger.error('Error processing yaml: %s', err, err);\n }\n }\n return rval;\n }\n matchNone(input, regex) {\n let rval = true;\n if (!!input && !!regex) {\n regex.forEach((r) => {\n rval = rval && !r.test(input);\n });\n }\n return rval;\n }\n}\n//# sourceMappingURL=open-api-doc-modifier.js.map","import fs from 'fs';\nimport { RequireRatchet } from '@bitblit/ratchet-common';\nimport yaml from 'js-yaml';\nimport { Logger } from '@bitblit/ratchet-common';\nexport class YamlCombiner {\n static combine(files, inRootPath = []) {\n RequireRatchet.notNullOrUndefined(files, 'Files argument');\n RequireRatchet.true(files.length > 0, 'Files argument larger than 0');\n RequireRatchet.notNullOrUndefined(inRootPath, 'Root path argument');\n Logger.info('Processing %d files into output', files.length);\n let allElements = {};\n for (let i = 0; i < files.length; i++) {\n const fileContents = fs.readFileSync(files[i]).toString();\n const openApi = yaml.load(fileContents);\n allElements = Object.assign(allElements, openApi);\n }\n const rootPath = Object.assign([], inRootPath);\n while (rootPath.length > 0) {\n const next = {};\n next[rootPath[rootPath.length - 1]] = allElements;\n rootPath.splice(rootPath.length - 1, 1);\n allElements = next;\n }\n const rval = yaml.dump(allElements);\n return rval;\n }\n}\n//# sourceMappingURL=yaml-combiner.js.map"],"names":["EpsilonBuildProperties","constructor","buildVersion","buildHash","buildBranch","buildTag","buildBranchOrTag","StringRatchet","trimToNull","buildTime","EpsilonConstants","static","filePath","className","Logger","info","EsmRatchet","fetchDirName","url","rval","val","require","debug","Object","keys","importPath","process","env","EPSILON_FINDER_DYNAMIC_IMPORT_PATH_ENV_NAME","DEFAULT_EPSILON_FINDER_DYNAMIC_IMPORT_PATH","fnName","EPSILON_FINDER_FUNCTION_NAME_ENV_NAME","DEFAULT_EPSILON_FINDER_FUNCTION_NAME","provider","this","load","err","error","UnauthorizedError","RestfulApiHttpError","errors","super","withHttpStatusCode","HTTP_CODE","BadRequestError","EventUtil","event","path","startsWith","idx","indexOf","substring","MapRatchet","extractValueFromMapIgnoreCase","headers","rc","extractRequestContext","stage","requestContext","authorizer","headerVal","headerList","String","split","map","s","trim","list","ipAddressChain","length","overrideProtocol","extractProtocol","protocol","prefix","body","contentType","isBase64Encoded","Buffer","from","JSON","parse","toString","curLevel","rConfig","envParamLogLevelName","EnumRatchet","keyToEnum","LoggerLevelName","silly","queryParamLogLevelName","queryStringParameters","newParams","forEach","k","toLowerCase","multiValueQueryStringParameters","jwtToken","jwtFullData","jwt","decode","complete","Error","jwtData","AUTH_HEADER_NAME","newAuth","assign","userData","userDataJSON","stringify","srcData","throwErrorOnMissingBad","extractAuthorizationHeaderCaseInsensitive","sp","Base64Ratchet","base64StringToString","username","password","httpMethod","endsWith","jsonBodyToObject","evt","caseInsensitiveAccess","authHeader","trimToEmpty","host","includes","ResponseUtil","httpStatusCode","requestId","detailErrorCode","endUserErrors","details","wrappedError","name","message","statusCode","target","code","queryParams","redirectTarget","i","encodeURIComponent","Location","input","undefined","isBuffer","coerceToProxyResult","encodingHeader","proxyResult","bigEnough","exemptContent","asBuffer","zipped","gzip","zipped64","Promise","resolve","reject","zlib","result","RequestTimeoutError","ContextUtil","epsilon","ctx","processLabel","CURRENT_EPSILON_REFERENCE","CURRENT_CONTEXT","CURRENT_EVENT","CURRENT_LOG_VARS","CURRENT_PROCESS_LABEL","CURRENT_OVERRIDE_TRACE_ID","CURRENT_OVERRIDE_TRACE_DEPTH","traceId","traceDepth","entry","setOverrideTrace","interApiEntry","depthOffset","traceHeaderName","currentTraceId","traceDepthHeaderName","safeString","currentTraceDepth","ErrorRatchet","throwFormattedErr","pr","addHeadersToRecord","ri","awsRequestId","defaultValueIfMissing","createType4Guid","currentRequestId","getRemainingTimeInMillis","config","loggerConfig","traceFn","traceIdGenerator","defaultedCurrentRequestId","NumberRatchet","safeNumber","AwsUtil","srcEvt","apiGatewayV2RequestContextToApiGatewayV1RequestContext","http","method","multiValueHeaders","pathParameters","stageVariables","resource","accountId","apiId","domainName","domainPrefix","routeKey","requestTime","time","requestTimeEpoch","timeEpoch","identity","resourceId","resourcePath","toFind","key","matchExact","r","str","match","src","def","WebV2Handler","webHandler","extractLabel","context","apiGatewayV2ToApiGatewayV1","replace","handlesEvent","LambdaEventDetector","isValidApiGatewayV2WithRequestContextEvent","async","conv","asExtended","parsedBody","authorization","convertedFromV2Event","openApiLambdaHandler","InterApiUtil","extractEntryFromEvent","isSingleSnsEvent","msg","Records","Sns","Message","parsed","INTER_API_SNS_EVENT","cfg","mgr","RequireRatchet","notNullOrUndefined","setOverrideTraceFromInterApiEntry","backgroundEntries","processMappings","disabled","source","sourceRegex","type","typeRegex","backgroundProcessTypes","taskName","createEntry","data","push","addEntriesToQueue","ent","InterApiEpsilonLambdaEventHandler","_epsilon","interApiConfig","isInterApiSnsEvent","tmp","processInterApiEvent","backgroundManager","GenericSnsEpsilonLambdaEventHandler","EventSource","isValidSnsEvent","sns","finder","TopicArn","handler","findInMap","handlers","CronUtil","n","everyNElementFilter","m","half","Math","floor","num","filter","testTimeEpochMS","Date","getTime","timezone","resources","eventSourceName","targetTZ","overrideTimezone","nowInTZ","DateTime","fromMillis","setZone","eventFilter","test","numberMatchesFilter","minute","minuteFilter","hour","hourFilter","weekday","dayOfWeekFilter","day","dayOfMonthFilter","month","monthOfYearFilter","contextMatchFilter","contextNoMatchFilter","CronEpsilonLambdaEventHandler","isValidCronEvent","cron","processCronEvent","backgroundHandler","cronConfig","background","entries","toEnqueue","smCronEntry","eventMatchesEntry","cronEntryName","backgroundEntry","backgroundTaskType","resolvePotentialFunctionToResult","fireImmediate","fireImmediateProcessRequest","warn","S3EpsilonLambdaEventHandler","eventSource","isValidS3Event","s3","bucket","object","eventName","removeHandlers","createHandlers","DynamoEpsilonLambdaEventHandler","isValidDynamoDBEvent","dynamoDb","eventSourceARN","EpsilonLoggingExtensionProcessor","params","fetchLogVariables","now","currentProcessLabel","label","EpsilonGlobalHandler","globalInstanceProvider","GLOBAL_INSTANCE_PROVIDER","LOGGER_CONFIGURED","configureDefaultLogger","overrides","output","initialLevel","formatType","LogMessageFormatType","StructuredJson","globalVars","outputFunction","LoggerOutputFunction","StdOut","ringBufferSize","preProcessors","concat","getOptions","changeDefaultOptions","dumpOptionsIntoLog","overrideTraceId","overrideTraceDepth","processSingleBackgroundEntry","e","internal","wrapEntryForInternal","disableLastResortTimeout","PromiseRatchet","timeout","innerLambdaHandler","TimeoutToken","isTimeoutToken","writeToLog","errorResponse","wrapError","clearContext","initContext","errorHandler","defaultProcessUncaughtError","logLevel","calcLogLevelViaEventOrEnvParam","getLevel","setLevel","queryParamTracePrefixName","updateTracePrefix","found","processUncaughtError","setProcessLabel","logByLevel","epsilonStartEndMessageLogLevel","processEvent","safeStringifyErr","InterApiManager","_aws","_sns","fireInterApiEvent","localMode","toWrite","interApiEvent","addTraceToInterApiEntry","snsId","writeMessageToSnsTopic","snsArn","send","PublishCommand","MessageId","LocalServerCert","NotFoundError","ForbiddenError","NotImplemented","MisconfiguredError","BuiltInHandlers","flag","withFormattedErrorMessage","toLocaleString","pad","createRandomHexString","errNumber","withDetails","withEndUserErrors","stack","LocalWebTokenManipulator","encryptionKeys","issuer","_ratchet","noNullOrUndefinedValuesInArray","JwtRatchet","withExtraDecryptionKeys","encryptionKeyPromise","jtiGenerator","decryptOnlyKeyUseLogLevel","parseFailureLogLevel","withParseFailureLogLevel","decryptKeysPromise","withOldKeyUseLogLevel","jwtRatchet","selectRandomEncryptionKey","createRefreshedJWTString","tokenString","expirationSeconds","allowExpired","refreshJWTString","payload","decodeToken","ExpiredJwtHandling","ADD_FLAG","hasExpiredFlag","exp","principal","userObject","roles","proxyUser","tokenData","iss","sub","iat","user","proxy","createTokenString","header","parseAndValidateJWTStringAsync","EchoProcessor","typeName","TYPE_NAME","NoOpProcessor","SampleDelayProcessor","delayMS","random","wait","LogAndEnqueueEchoProcessor","fireImmediateProcessRequestByParts","upstream","BackgroundProcessHandling","BackgroundExecutionEventType","NullReturnedObjectHandling","EpsilonApolloCorsMethod","BackgroundHttpAdapterHandler","backgroundConfig","modelValidator","maxWaitInMsForBackgroundJobToStart","httpMetaEndpoint","httpSubmissionPath","httpStatusPath","httpStatusEndpoint","implyTypeFromPathSuffix","transactionLogger","guid","sw","StopWatch","log","elapsedMS","readTransactionLog","dump","currentCount","fetchApproximateNumberOfQueueEntries","valid","processors","b","a","sort","localeCompare","currentQueueLength","validTypes","backgroundManagerName","startIdx","pathSuppliedBackgroundType","join","toLocaleLowerCase","foundProc","find","immediate","BooleanRatchet","parseBool","startProcessor","dataSchemaName","validate","withErrors","addEntryToQueue","processHandling","Immediate","Queued","startProcessorRequested","success","resultId","BackgroundValidator","findProcessor","validType","validateEntry","validateEntryAndThrowException","processorInput","Map","p","has","set","notificationArn","queueUrl","sendNotificationOnBackgroundError","sendNotificationOnBackgroundValidationFailure","backgroundProcessFailureSnsArn","AbstractBackgroundManager","createdEpochMS","generateBackgroundGuid","fireStartMessage","fireResult","fireStartProcessingRequest","targetEpochMS","toFormat","start","BackgroundHandler","validator","cfgErrors","validateConfig","validateAndMapProcessors","immediateProcessQueue","subscribe","isBackgroundStartSnsEvent","isBackgroundImmediateFireEvent","pEvt","parseImmediateFireBackgroundEntry","isBackgroundSNSEvent","BACKGROUND_SNS_START_MARKER","BACKGROUND_SNS_IMMEDIATE_RUN_FLAG","procd","takeAndProcessSingleBackgroundQueueEntry","refire","takeEntryFromBackgroundQueue","logTransaction","request","running","safeWriteToLogger","runtimeMS","errorProcessor","handleError","listeners","executionListeners","listener","onEvent","setOverrideTraceFromInternalBackgroundEntry","conditionallyStartTransactionLog","fireListenerEvent","ProcessStarting","processorType","get","NoMatchProcessorName","dataValidationErrors","DataValidationError","handleEvent","conditionallyCompleteTransactionLog","ExecutionSuccessfullyComplete","conditionallyRunErrorProcessor","ExecutionFailedError","getConfig","BuiltInFilters","fCtx","filters","cont","applyGzipIfPossible","headerName","addConstantHeaders","decodeURIComponent","cleaned","v","fixStillEncodedQueryParams","MAXIMUM_LAMBDA_BODY_SIZE_BYTES","delta","routeAndParse","mapping","validation","modelName","emptyAllowed","extraPropertiesAllowed","rawResult","outboundValidation","unshift","addAllowReflectionCORSHeaders","inBody","errorMessage","errCode","oldResult","BuiltInAuthFilters","requiredRoleAllOf","auth","asJwt","requiredRoleOneOf","webTokenManipulators","Array","isArray","extractBearerTokenFromEvent","manipulator","token","extractTokenFromAuthorizationHeader","raw","authorizerName","authenticators","LogLevelManipulationFilter","LOG_LEVEL_BEFORE_CHANGE","RouterUtil","webTokenManipulator","parseAuthorizationHeader","applyOpenApiAuthorization","defaultEpsilonPreFilters","autoRespondToOptionsRequestWithCors","ensureEventMaps","setLogLevelForTransaction","parseJsonBodyToObject","uriDecodeQueryParams","disallowStringNullAsPathParameter","disallowStringNullAsQueryStringParameter","validateInboundBody","validateInboundQueryParams","validateOutboundResponse","addAWSRequestIdHeader","checkMaximumLambdaBodySize","clearLogLevelForTransaction","configName","timeoutMS","overrideAuthorizerName","preFilters","defaultAuthenticationHeaderParsingEpsilonPreFilters","postFilters","defaultEpsilonPostFilters","errorFilters","defaultEpsilonErrorFilters","nullReturnedObjectHandling","Return404NotFoundResponse","defaults","authorizers","defaultMetaHandling","defaultHttpMetaProcessingConfig","staticContentRoutes","prefixesToStripBeforeRouteMatch","filterHandledRouteMatches","httpConfig","overrideMetaHandling","methods","matches","pathRegex","invertPathMatching","openApiDoc","backgroundHttpAdapterHandler","routes","openApiModelValidator","assignDefaultsOnHttpConfig","components","securitySchemes","sk","missingPaths","filterHandledPathMatches","paths","convertedPath","openApiPathToRouteParserPath","applicableMeta","findApplicableMeta","isBackgroundEndpoint","isBackgroundMetaEndpoint","isBackgroundStatusEndpoint","handleBackgroundSubmission","handleBackgroundMetaRequest","handleBackgroundStatusRequest","reg","expectedHandledByFilter","newRoute","function","metaProcessingConfig","schema","findAndValidateModelName","overrideModelValidator","schemaPath","inlinePath","lastIndexOf","fetchModel","model","addModel","sIdx","eIdx","RunHandlerAsFilter","rm","findHandler","applyNullReturnedObjectHandling","handling","ConvertToEmptyString","add404OnMissing","runHandler","WebHandler","routerConfig","router","toUpperCase","isValidApiGatewayEvent","addTraceToProxyResult","findBestMatchingRoute","procConfig","filterChain","addRunHandlerAsFilterToList","combineFilters","wrapper","convErr","cleanPath","methodLower","matchRoutes","routeParser","Route","route","EpsilonConfigParser","epsilonConfigToEpsilonInstance","validateGlobalConfig","parseOpenApiDocument","openApiYamlString","openApiDocToValidator","backgroundHttpAdapter","epsilonRouter","openApiYamlToRouterConfig","parsedOpenApiDoc","yamlString","yaml","doc","schemas","ModelValidator","createFromParsedObject","SampleInputValidatedProcessor","BuiltInAuthorizers","authorizationContext","ApolloUtil","args","authTokenSt","lambdaEvent","RETURN_NULL","bearerTokenString","functionName","lambdaContext","hostName","hostIsLocalOrNotRoutableIP4","defaultEpsilonApolloContext","ApolloFilter","apolloPathRegex","apolloServer","options","processApolloRequest","corsMethod","All","addAllowEverythingCORSHeaders","Reflective","assertStarted","headerMap","HeaderMap","headersKey","eventMethod","bodyString","aRequest","search","contextFn","emptyContext","apolloPromise","executeHTTPGraphQLRequest","httpGraphQLRequest","httpGraphQLResponse","outHeaders","headersValue","kind","withRequestId","bodyAsString","string","generateBase64VersionOfString","status","handlePathWithApollo","LogMessageBackgroundErrorProcessor","submission","SingleThreadLocalBackgroundManager","_localBus","Subject","wrapped","next","SampleServerStaticFiles","SampleServerComponents","gqlString","SAMPLE_SERVER_GRAPHQL","typeDefs","gql","server","ApolloServer","introspection","resolvers","RootQueryType","serverMeta","root","version","serverTime","toISOString","forceTimeout","placeholder","plugins","ApolloServerPluginLandingPageLocalDefault","footer","SAMPLE_OPEN_API_DOC","simpleLoggedInAuth","simpleNoAuthenticationLogAccess","sample","fErr","numberParam","nameParam","tokenManipulator","meta","defaultHttpMetaProcessingConfigWithAuthenticationHeaderParsing","addApolloFilterToList","RegExp","createSampleApollo","arg","secureOutboundServerErrorForProduction","preFiltersAllowingNull","splice","epsilonConfig","createSampleEpsilonConfig","epsilonInstance","byPassCfg","autoRespond","LocalServer","globalHandler","port","aborted","https","res","rej","CLIENT_KEY_PEM","cert","CLIENT_CERT_PEM","createServer","requestHandler","bind","listen","on","response","messageToApiGatewayEvent","eventIsAGraphQLIntrospection","lambdaHandler","writeProxyResultToServerResponse","chunk","bodyAsBase64String","stageIdx","reqTime","formattedTime","utc","queryIdx","queryStringParams","qs","baz","hk","setHeader","end","createSampleBatchOnlyEpsilonGlobalHandler","testServer","runServer","localTokenHandler","createJWTStringAsync","createSampleEpsilonGlobalHandler","LocalContainerServer","logEventLevel","postResp","fetch","json","argv","exit","BackgroundDynamoLogTableHandler","dynamo","tableName","backgroundQueueName","processTypeName","state","timestampEpochMs","simplePut","EpsilonBackgroundProcessError","_errors","_detailErrorCode","_details","_requestId","_wrappedError","combineErrorStringsWithDefault","setPrototypeOf","prototype","EPSILON_BACKGROUND_PROCESS_ERROR_FLAG_KEY","defMessage","setFormattedErrorMessage","format","util","withDetailErrorCode","withWrappedError","isWrappedError","objectIsEpsilonBackgroundProcessError","obj","value","S3BackgroundTransactionLogger","s3TransactionLogCacheRatchet","S3CacheRatchet","txLog","writeObjectToCacheFile","backgroundGuidToPath","txGuid","fetchCacheFileAsObject","timeToLiveDays","AwsSqsSnsBackgroundManager","_awsConfig","_sqs","validateAwsConfig","awsConfig","sqs","DelaySeconds","MessageBody","MessageGroupId","QueueUrl","SendMessageCommand","all","fetchCurrentQueueAttributes","Attributes","req","AttributeNames","GetQueueAttributesCommand","MaxNumberOfMessages","VisibilityTimeout","WaitTimeSeconds","ReceiveMessageCommand","Messages","Body","delParams","ReceiptHandle","delResult","DeleteMessageCommand","RatchetEpsilonCommonInfo","hash","branch","tag","timeBuiltISO","notes","BuiltInTraceIdGenerators","fullAwsRequestId","RetryProcessor","delegate","opts","typePrefix","typeSuffix","tryNumber","RETRY_FIELD_NAME","dataCopy","retryCount","waitTimeMS","baseDelayMS","DurationRatchet","formatMsDuration","DaemonHandler","daemon","inConfig","proc","ALLOW_EVERYTHING_AUTHORIZER","groupSelector","defaultGroup","fetchDaemonStatusByPublicTokenPathParameter","fetchDaemonStatusPathParameter","publicToken","statFromPublicToken","daemonKey","stat","group","allowed","results","nextToken","RunBackgroundProcessFromCommandLine","procName","dryRun","processSingleBackgroundByParts","console","TestErrorServer","net","Server","socket","write","setTimeout","RatchetCliHandler","AbstractRatchetCliHandler","fetchHandlerMap","runFromCliArgs","runSampleLocalServerFromCliArgs","fetchVersionInfo","buildInformation","ApiGatewayAdapterAuthenticationHandler","callback","srcString","extractTokenStringFromAuthorizerEvent","methodArn","then","createPolicy","catch","userOb","apiGatewayArnTmp","awsAccountId","region","principalId","policyDocument","Version","Statement","Action","Effect","Resource","userJSON","authorizationToken","AUTH_HEADER_PREFIX","Auth0WebTokenManipulator","clientId","jwksUri","jwksClient","parseAndValidateAuth0Token","auth0Token","obscure","fullToken","kid","nowEpochSeconds","pubKey","fetchSigningKey","verify","audience","ignoreExpiration","clockTimestamp","jClient","fetchJwksClient","getSigningKey","publicKey","rsaPublicKey","jwks","cache","cacheMaxEntries","cacheMaxAge","GoogleWebTokenManipulator","cacheGoogleDiscoveryDocument","parseAndValidateGoogleToken","googleToken","discDoc","fetchGoogleDiscoveryDocument","client","jwks_uri","resp","GOOGLE_DISCOVERY_DOCUMENT","JwtRatchetLocalWebTokenManipulator","_jwtRatchet","_issuer","THROW_EXCEPTION","BadGateway","ConflictError","GatewayTimeout","MethodNotAllowedError","ServiceUnavailable","TooManyRequestsError","OpenApiDocModifier","modifyOpenApiDoc","openApi","removeTags","t","newServerPath","tags","f","newPaths","verb","matcher","matchNone","removeEndpoints","sortEndpoints","newPaths2","remSchemas","removeSchemas","newComp","regex","YamlCombiner","files","inRootPath","true","allElements","fileContents","fs","readFileSync","rootPath"],"mappings":"g1CACO,MAAMA,EACTC,cAAiB,CACNC,0BACP,MAAO,gBACV,CACUC,uBACP,MAAO,YACV,CACUC,yBACP,MAAO,cACV,CACUC,sBACP,MAAO,WACV,CACUC,8BACP,OAAOC,EAAcC,WAAWR,EAAuBI,aACjD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B,EAAU,CAAA,EAChB/kC,EAAKoE,SAASC,KACmC,IAAzCwgC,EAAWnjC,QAAQ2C,EAAEC,iBACrBygC,EAAQ1gC,GAAK2/B,EAAoB,WAAW,QAAE3/B,GACjD,IAEL2/B,EAAoB,WAAW,QAAIe,CACtC,CACDplC,EAAOqvB,EAAKrQ,KAAKqlB,EACpB,CACD,MAAOpjC,GACHtB,EAAOuB,MAAM,4BAA6BD,EAAKA,EAClD,CAEL,OAAOjB,CACV,CACD8kC,UAAUl9B,EAAOy9B,GACb,IAAIrlC,GAAO,EAMX,OALM4H,GAAWy9B,GACbA,EAAM5gC,SAASoI,IACX7M,EAAOA,IAAS6M,EAAEuF,KAAKxK,EAAM,IAG9B5H,CACV,ECzEE,MAAMslC,GACT9lC,eAAe+lC,EAAOC,EAAa,IAC/B32B,EAAeC,mBAAmBy2B,EAAO,kBACzC12B,EAAe42B,KAAKF,EAAMriC,OAAS,EAAG,gCACtC2L,EAAeC,mBAAmB02B,EAAY,sBAC9C7lC,EAAOC,KAAK,kCAAmC2lC,EAAMriC,QACrD,IAAIwiC,EAAc,CAAA,EAClB,IAAK,IAAIj+B,EAAI,EAAGA,EAAI89B,EAAMriC,OAAQuE,IAAK,CACnC,MAAMk+B,EAAeC,EAAGC,aAAaN,EAAM99B,IAAI3D,WACzCugC,EAAUhV,EAAKruB,KAAK2kC,GAC1BD,EAActlC,OAAOkF,OAAOogC,EAAarB,EAC5C,CACD,MAAMyB,EAAW1lC,OAAOkF,OAAO,GAAIkgC,GACnC,KAAOM,EAAS5iC,OAAS,GAAG,CACxB,MAAM4vB,EAAO,CAAA,EACbA,EAAKgT,EAASA,EAAS5iC,OAAS,IAAMwiC,EACtCI,EAAS1Q,OAAO0Q,EAAS5iC,OAAS,EAAG,GACrCwiC,EAAc5S,CACjB,CAED,OADazD,EAAKrQ,KAAK0mB,EAE1B"}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../src/epsilon-build-properties.ts","../src/epsilon-constants.ts","../src/http/error/unauthorized-error.ts","../src/http/error/bad-request-error.ts","../src/http/event-util.ts","../src/http/response-util.ts","../src/http/error/request-timeout-error.ts","../src/util/context-util.ts","../src/util/aws-util.ts","../src/http/web-v2-handler.ts","../src/inter-api/inter-api-util.ts","../src/lambda-event-handler/inter-api-epsilon-lambda-event-handler.ts","../src/lambda-event-handler/generic-sns-epsilon-lambda-event-handler.ts","../src/util/cron-util.ts","../src/lambda-event-handler/cron-epsilon-lambda-event-handler.ts","../src/lambda-event-handler/s3-epsilon-lambda-event-handler.ts","../src/lambda-event-handler/dynamo-epsilon-lambda-event-handler.ts","../src/epsilon-logging-extension-processor.ts","../src/epsilon-global-handler.ts","../src/inter-api-manager.ts","../src/local-server-cert.ts","../src/http/error/not-found-error.ts","../src/http/error/forbidden-error.ts","../src/http/error/not-implemented.ts","../src/http/error/misconfigured-error.ts","../src/built-in/http/built-in-handlers.ts","../src/http/auth/local-web-token-manipulator.ts","../src/built-in/background/echo-processor.ts","../src/built-in/background/no-op-processor.ts","../src/built-in/background/sample-delay-processor.ts","../src/built-in/background/log-and-enqueue-echo-processor.ts","../src/background/background-process-handling.ts","../src/background/background-execution-event-type.ts","../src/config/http/null-returned-object-handling.ts","../src/built-in/http/apollo/epsilon-apollo-cors-method.ts","../src/background/background-http-adapter-handler.ts","../src/background/background-validator.ts","../src/background/manager/abstract-background-manager.ts","../src/background/background-handler.ts","../src/built-in/http/built-in-filters.ts","../src/built-in/http/built-in-auth-filters.ts","../src/built-in/http/log-level-manipulation-filter.ts","../src/http/route/router-util.ts","../src/built-in/http/run-handler-as-filter.ts","../src/http/web-handler.ts","../src/util/epsilon-config-parser.ts","../src/built-in/background/sample-input-validated-processor.ts","../src/built-in/http/built-in-authorizers.ts","../src/built-in/http/apollo/apollo-util.ts","../src/built-in/http/apollo-filter.ts","../src/built-in/background/log-message-background-error-processor.ts","../src/background/manager/single-thread-local-background-manager.ts","../src/sample/sample-server-static-files.ts","../src/sample/sample-server-components.ts","../src/local-server.ts","../src/local-container-server.ts","../src/background/background-dynamo-log-table-handler.ts","../src/background/epsilon-background-process-error.ts","../src/background/s3-background-transaction-logger.ts","../src/background/manager/aws-sqs-sns-background-manager.ts","../src/build/ratchet-epsilon-common-info.ts","../src/built-in/built-in-trace-id-generators.ts","../src/built-in/background/retry-processor.ts","../src/built-in/daemon/daemon-handler.ts","../src/cli/run-background-process-from-command-line.ts","../src/sample/test-error-server.ts","../src/cli/ratchet-cli-handler.ts","../src/http/auth/api-gateway-adapter-authentication-handler.ts","../src/http/auth/auth0-web-token-manipulator.ts","../src/http/auth/google-web-token-manipulator.ts","../src/http/auth/jwt-ratchet-local-web-token-manipulator.ts","../src/http/error/bad-gateway.ts","../src/http/error/conflict-error.ts","../src/http/error/gateway-timeout.ts","../src/http/error/method-not-allowed-error.ts","../src/http/error/service-unavailable.ts","../src/http/error/too-many-requests-error.ts","../src/open-api-util/open-api-doc-modifier.ts","../src/open-api-util/yaml-combiner.ts"],"sourcesContent":["import { StringRatchet } from '@bitblit/ratchet-common';\nexport class EpsilonBuildProperties {\n constructor() { }\n static get buildVersion() {\n return 'LOCAL-SNAPSHOT';\n }\n static get buildHash() {\n return 'LOCAL-HASH';\n }\n static get buildBranch() {\n return 'LOCAL-BRANCH';\n }\n static get buildTag() {\n return 'LOCAL-TAG';\n }\n static get buildBranchOrTag() {\n return StringRatchet.trimToNull(EpsilonBuildProperties.buildBranch)\n ? 'BRANCH:' + EpsilonBuildProperties.buildBranch\n : 'TAG:' + EpsilonBuildProperties.buildTag;\n }\n static get buildTime() {\n return 'LOCAL-TIME';\n }\n}\n//# sourceMappingURL=epsilon-build-properties.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { EsmRatchet } from '@bitblit/ratchet-common';\nexport class EpsilonConstants {\n static EPSILON_FINDER_DYNAMIC_IMPORT_PATH_ENV_NAME = 'EPSILON_FINDER_DYNAMIC_IMPORT_PATH';\n static EPSILON_FINDER_FUNCTION_NAME_ENV_NAME = 'EPSILON_FINDER_FUNCTION_NAME';\n static DEFAULT_EPSILON_FINDER_DYNAMIC_IMPORT_PATH = 'epsilon-global-handler-provider.js';\n static DEFAULT_EPSILON_FINDER_FUNCTION_NAME = 'findEpsilonGlobalHandler';\n static AUTH_HEADER_PREFIX = 'Bearer ';\n static AUTH_HEADER_NAME = 'Authorization';\n static BACKGROUND_SQS_TYPE_FIELD = 'BACKGROUND_TYPE';\n static BACKGROUND_SNS_START_MARKER = 'BACKGROUND_START_MARKER';\n static BACKGROUND_SNS_IMMEDIATE_RUN_FLAG = 'BACKGROUND_IMMEDIATE_RUN_FLAG';\n static INTER_API_SNS_EVENT = 'EPSILON_INTER_API_EVENT';\n static load(filePath, className) {\n Logger.info('Searching for %s : %s : %s', filePath, className, EsmRatchet.fetchDirName(import.meta.url));\n let rval = null;\n const val = require(filePath);\n if (val) {\n Logger.debug('Found %s - pulling object : %j : %s', filePath, Object.keys(val), className);\n rval = val[className];\n }\n return rval;\n }\n static async findDynamicImportEpsilonGlobalHandlerProvider() {\n const importPath = process.env[EpsilonConstants.EPSILON_FINDER_DYNAMIC_IMPORT_PATH_ENV_NAME] ||\n EpsilonConstants.DEFAULT_EPSILON_FINDER_DYNAMIC_IMPORT_PATH;\n const fnName = process.env[EpsilonConstants.EPSILON_FINDER_FUNCTION_NAME_ENV_NAME] || EpsilonConstants.DEFAULT_EPSILON_FINDER_FUNCTION_NAME;\n Logger.debug('Using epsilon finder dynamic import path : %s / %s', importPath, fnName);\n let provider = null;\n try {\n provider = this.load(importPath, fnName);\n }\n catch (err) {\n Logger.error('Error loading provider : %s / %s : %s', importPath, fnName, err, err);\n }\n let rval = null;\n if (provider) {\n Logger.debug('Type2 is : %s', typeof provider);\n Logger.info('Got3 : %s : %s', provider, typeof provider);\n rval = provider();\n Logger.info('Rval3 is %s', rval);\n }\n return rval;\n }\n constructor() { }\n}\n//# sourceMappingURL=epsilon-constants.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class UnauthorizedError extends RestfulApiHttpError {\n static HTTP_CODE = 401;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(UnauthorizedError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=unauthorized-error.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class BadRequestError extends RestfulApiHttpError {\n static HTTP_CODE = 400;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(BadRequestError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=bad-request-error.js.map","import { UnauthorizedError } from './error/unauthorized-error.js';\nimport { BadRequestError } from './error/bad-request-error.js';\nimport { Logger } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { MapRatchet } from '@bitblit/ratchet-common';\nimport { LoggerLevelName } from '@bitblit/ratchet-common';\nimport { EnumRatchet } from '@bitblit/ratchet-common';\nimport { Base64Ratchet } from '@bitblit/ratchet-common';\nimport jwt from 'jsonwebtoken';\nimport { EpsilonConstants } from '../epsilon-constants.js';\nexport class EventUtil {\n constructor() { }\n static extractStage(event) {\n if (!event.path.startsWith('/')) {\n throw new BadRequestError('Path should start with / but does not : ' + event.path);\n }\n const idx = event.path.indexOf('/', 1);\n if (idx == -1) {\n throw new BadRequestError('No second / found in the path : ' + event.path);\n }\n return event.path.substring(1, idx);\n }\n static extractHostHeader(event) {\n return MapRatchet.extractValueFromMapIgnoreCase(event.headers, 'Host');\n }\n static extractProtocol(event) {\n return MapRatchet.extractValueFromMapIgnoreCase(event.headers, 'X-Forwarded-Proto');\n }\n static extractApiGatewayStage(event) {\n const rc = EventUtil.extractRequestContext(event);\n return rc ? rc.stage : null;\n }\n static extractRequestContext(event) {\n return event.requestContext;\n }\n static extractAuthorizer(event) {\n const rc = EventUtil.extractRequestContext(event);\n return rc ? rc.authorizer : null;\n }\n static ipAddressChain(event) {\n const headerVal = event && event.headers ? MapRatchet.extractValueFromMapIgnoreCase(event.headers, 'X-Forwarded-For') : null;\n let headerList = headerVal ? String(headerVal).split(',') : [];\n headerList = headerList.map((s) => s.trim());\n return headerList;\n }\n static ipAddress(event) {\n const list = EventUtil.ipAddressChain(event);\n return list && list.length > 0 ? list[0] : null;\n }\n static extractFullPath(event, overrideProtocol = null) {\n const protocol = overrideProtocol || EventUtil.extractProtocol(event) || 'https';\n return protocol + '://' + event.requestContext['domainName'] + event.requestContext.path;\n }\n static extractFullPrefix(event, overrideProtocol = null) {\n const protocol = overrideProtocol || EventUtil.extractProtocol(event) || 'https';\n const prefix = event.requestContext.path.substring(0, event.requestContext.path.indexOf('/', 1));\n return protocol + '://' + event.requestContext['domainName'] + prefix;\n }\n static jsonBodyToObject(event) {\n let rval = null;\n if (event.body) {\n const contentType = MapRatchet.extractValueFromMapIgnoreCase(event.headers, 'Content-Type') || 'application/octet-stream';\n rval = event.body;\n if (event.isBase64Encoded) {\n rval = Buffer.from(rval, 'base64');\n }\n if (contentType.startsWith('application/json')) {\n rval = JSON.parse(rval.toString('ascii'));\n }\n }\n return rval;\n }\n static calcLogLevelViaEventOrEnvParam(curLevel, event, rConfig) {\n let rval = curLevel;\n if (rConfig?.envParamLogLevelName && process.env[rConfig.envParamLogLevelName]) {\n rval = EnumRatchet.keyToEnum(LoggerLevelName, process.env[rConfig.envParamLogLevelName]);\n Logger.silly('Found env log level : %s', rval);\n }\n if (rConfig &&\n rConfig.queryParamLogLevelName &&\n event &&\n event.queryStringParameters &&\n event.queryStringParameters[rConfig.queryParamLogLevelName]) {\n rval = EnumRatchet.keyToEnum(LoggerLevelName, event.queryStringParameters[rConfig.queryParamLogLevelName]);\n Logger.silly('Found query log level : %s', rval);\n }\n return rval;\n }\n static fixStillEncodedQueryParams(event) {\n if (event?.queryStringParameters) {\n const newParams = {};\n Object.keys(event.queryStringParameters).forEach((k) => {\n const val = event.queryStringParameters[k];\n if (k.toLowerCase().startsWith('amp;')) {\n newParams[k.substring(4)] = val;\n }\n else {\n newParams[k] = val;\n }\n });\n event.queryStringParameters = newParams;\n }\n if (event?.multiValueQueryStringParameters) {\n const newParams = {};\n Object.keys(event.multiValueQueryStringParameters).forEach((k) => {\n const val = event.multiValueQueryStringParameters[k];\n if (k.toLowerCase().startsWith('amp;')) {\n newParams[k.substring(4)] = val;\n }\n else {\n newParams[k] = val;\n }\n });\n event.multiValueQueryStringParameters = newParams;\n }\n }\n static applyTokenToEventForTesting(event, jwtToken) {\n const jwtFullData = jwt.decode(jwtToken, { complete: true });\n if (!jwtFullData['payload']) {\n throw new Error('No payload found in passed token');\n }\n const jwtData = jwtFullData['payload'];\n event.headers = event.headers || {};\n event.headers[EpsilonConstants.AUTH_HEADER_NAME.toLowerCase()] = 'Bearer ' + jwtToken;\n event.requestContext = event.requestContext || {};\n const newAuth = Object.assign({}, event.requestContext.authorizer);\n newAuth.userData = jwtData;\n newAuth.userDataJSON = jwtData ? JSON.stringify(jwtData) : null;\n newAuth.srcData = jwtToken;\n event.requestContext.authorizer = newAuth;\n }\n static extractBasicAuthenticationToken(event, throwErrorOnMissingBad = false) {\n let rval = null;\n if (!!event && !!event.headers) {\n const headerVal = EventUtil.extractAuthorizationHeaderCaseInsensitive(event);\n if (!!headerVal && headerVal.startsWith('Basic ')) {\n const parsed = Base64Ratchet.base64StringToString(headerVal.substring(6));\n const sp = parsed.split(':');\n Logger.silly('Parsed to %j', sp);\n if (!!sp && sp.length === 2) {\n rval = {\n username: sp[0],\n password: sp[1],\n };\n }\n }\n }\n if (!rval && throwErrorOnMissingBad) {\n throw new UnauthorizedError('Could not find valid basic authentication header');\n }\n return rval;\n }\n static eventIsAGraphQLIntrospection(event) {\n let rval = false;\n if (!!event) {\n if (!!event.httpMethod && 'post' === event.httpMethod.toLowerCase()) {\n if (!!event.path && event.path.endsWith('/graphql')) {\n const body = EventUtil.jsonBodyToObject(event);\n rval = !!body && !!body['operationName'] && body['operationName'] === 'IntrospectionQuery';\n }\n }\n }\n return rval;\n }\n static extractAuthorizationHeaderCaseInsensitive(evt) {\n return MapRatchet.caseInsensitiveAccess(evt?.headers || {}, EpsilonConstants.AUTH_HEADER_NAME);\n }\n static extractBearerTokenFromEvent(evt) {\n let rval = null;\n const authHeader = StringRatchet.trimToEmpty(EventUtil.extractAuthorizationHeaderCaseInsensitive(evt));\n if (authHeader.toLowerCase().startsWith('bearer ')) {\n rval = authHeader.substring(7);\n }\n return rval;\n }\n static hostIsLocal(host) {\n let rval = false;\n if (StringRatchet.trimToNull(host)) {\n host = host.includes(':') ? host.substring(0, host.indexOf(':')) : host;\n host = host.toLowerCase();\n if (host === 'localhost' || host === '127.0.0.1') {\n rval = true;\n }\n }\n return rval;\n }\n static hostIsLocalOrNotRoutableIP4(host) {\n let rval = false;\n if (StringRatchet.trimToNull(host)) {\n host = host.includes(':') ? host.substring(0, host.indexOf(':')) : host;\n host = host.toLowerCase();\n if (host === 'localhost' ||\n host === '127.0.0.1' ||\n host.startsWith('192.168.') ||\n host.startsWith('10.') ||\n host.startsWith('172.16.')) {\n rval = true;\n }\n }\n return rval;\n }\n}\n//# sourceMappingURL=event-util.js.map","import { Logger, MapRatchet } from '@bitblit/ratchet-common';\nimport zlib from 'zlib';\nexport class ResponseUtil {\n constructor() { }\n static errorResponse(err) {\n const body = {\n errors: err.errors,\n httpStatusCode: err.httpStatusCode,\n requestId: err.requestId,\n };\n if (err.detailErrorCode) {\n body['detailErrorCode'] = err.detailErrorCode;\n }\n if (err.endUserErrors && err.endUserErrors.length > 0) {\n body['endUserErrors'] = err.endUserErrors;\n }\n if (err.details) {\n body['details'] = err.details;\n }\n if (err.wrappedError) {\n body['wrappedError'] = err.wrappedError.name + ' : ' + err.wrappedError.message;\n }\n const errorResponse = {\n statusCode: err.httpStatusCode,\n isBase64Encoded: false,\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n };\n return errorResponse;\n }\n static redirect(target, code = 301, queryParams = null) {\n if (code !== 301 && code !== 302 && code !== 307) {\n throw new Error('Code must be 301 or 302 or 307 for a redirect');\n }\n let redirectTarget = target;\n if (queryParams) {\n const keys = Object.keys(queryParams);\n if (keys.length > 0) {\n Logger.silly('Applying params to input target : %j', queryParams);\n redirectTarget += redirectTarget.indexOf('?') === -1 ? '?' : '&';\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n redirectTarget += k + '=' + encodeURIComponent(queryParams[k]);\n if (i < keys.length - 1) {\n redirectTarget += '&';\n }\n }\n }\n }\n return {\n statusCode: code,\n body: '{\"redirect-target\":\"' + redirectTarget + '}',\n headers: {\n 'Content-Type': 'application/json',\n Location: redirectTarget,\n },\n };\n }\n static coerceToProxyResult(input) {\n let rval = null;\n if (input != null) {\n if (typeof input === 'object') {\n if (input.statusCode && input.body !== undefined) {\n rval = Object.assign({}, input);\n if (typeof input.body === 'string') {\n }\n else if (Buffer.isBuffer(input.body)) {\n rval.body = input.body.toString('base64');\n rval.headers = input.headers || {};\n rval.headers['Content-Type'] = input.body.contentType;\n rval.isBase64Encoded = true;\n }\n }\n else {\n const headers = input.headers || {};\n headers['Content-Type'] = 'application/json';\n rval = ResponseUtil.coerceToProxyResult({\n statusCode: 200,\n body: JSON.stringify(input),\n headers: headers,\n isBase64Encoded: false,\n });\n }\n }\n else if (typeof input === 'string' || Buffer.isBuffer(input)) {\n rval = ResponseUtil.coerceToProxyResult({ statusCode: 200, body: input });\n }\n else {\n const headers = input.headers || {};\n headers['Content-Type'] = 'application/json';\n rval = ResponseUtil.coerceToProxyResult({\n statusCode: 200,\n body: JSON.stringify(input),\n headers: headers,\n isBase64Encoded: false,\n });\n }\n }\n return rval;\n }\n static async applyGzipIfPossible(encodingHeader, proxyResult) {\n const rval = proxyResult;\n if (encodingHeader && encodingHeader.toLowerCase().indexOf('gzip') > -1) {\n const bigEnough = proxyResult.body.length > 1400;\n let contentType = MapRatchet.extractValueFromMapIgnoreCase(proxyResult.headers, 'content-type') || '';\n contentType = contentType.toLowerCase();\n const exemptContent = contentType === 'application/pdf' || contentType === 'application/zip' || contentType.startsWith('image/');\n if (bigEnough && !exemptContent) {\n const asBuffer = proxyResult.isBase64Encoded ? Buffer.from(proxyResult.body, 'base64') : Buffer.from(proxyResult.body);\n const zipped = await this.gzip(asBuffer);\n Logger.debug('Comp from %s to %d bytes', asBuffer.length, zipped.length);\n const zipped64 = zipped.toString('base64');\n rval.body = zipped64;\n rval.isBase64Encoded = true;\n rval.headers = rval.headers || {};\n rval.headers['Content-Encoding'] = 'gzip';\n }\n else {\n Logger.silly('Not gzipping, too small or exempt content');\n }\n }\n else {\n Logger.silly('Not gzipping, not an accepted encoding');\n }\n return rval;\n }\n static gzip(input) {\n const promise = new Promise(function (resolve, reject) {\n zlib.gzip(input, function (error, result) {\n if (!error)\n resolve(result);\n else\n reject(error);\n });\n });\n return promise;\n }\n}\n//# sourceMappingURL=response-util.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class RequestTimeoutError extends RestfulApiHttpError {\n static HTTP_CODE = 500;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(RequestTimeoutError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=request-timeout-error.js.map","import { StringRatchet } from '@bitblit/ratchet-common';\nimport { ErrorRatchet } from '@bitblit/ratchet-common';\nimport { NumberRatchet } from '@bitblit/ratchet-common';\nexport class ContextUtil {\n static CURRENT_EPSILON_REFERENCE;\n static CURRENT_CONTEXT;\n static CURRENT_EVENT;\n static CURRENT_LOG_VARS = {};\n static CURRENT_PROCESS_LABEL;\n static CURRENT_OVERRIDE_TRACE_ID;\n static CURRENT_OVERRIDE_TRACE_DEPTH;\n constructor() { }\n static initContext(epsilon, evt, ctx, processLabel) {\n ContextUtil.CURRENT_EPSILON_REFERENCE = epsilon;\n ContextUtil.CURRENT_CONTEXT = ctx;\n ContextUtil.CURRENT_EVENT = evt;\n ContextUtil.CURRENT_LOG_VARS = {};\n ContextUtil.CURRENT_PROCESS_LABEL = processLabel;\n }\n static clearContext() {\n ContextUtil.CURRENT_EPSILON_REFERENCE = null;\n ContextUtil.CURRENT_CONTEXT = null;\n ContextUtil.CURRENT_EVENT = null;\n ContextUtil.CURRENT_LOG_VARS = {};\n ContextUtil.CURRENT_PROCESS_LABEL = null;\n ContextUtil.CURRENT_OVERRIDE_TRACE_ID = null;\n ContextUtil.CURRENT_OVERRIDE_TRACE_DEPTH = null;\n }\n static setOverrideTrace(traceId, traceDepth) {\n ContextUtil.CURRENT_OVERRIDE_TRACE_ID = traceId || ContextUtil.CURRENT_OVERRIDE_TRACE_ID;\n ContextUtil.CURRENT_OVERRIDE_TRACE_DEPTH = traceDepth || ContextUtil.CURRENT_OVERRIDE_TRACE_DEPTH;\n }\n static setOverrideTraceFromInternalBackgroundEntry(entry) {\n ContextUtil.setOverrideTrace(entry.traceId, entry.traceDepth);\n }\n static setOverrideTraceFromInterApiEntry(interApiEntry) {\n ContextUtil.setOverrideTrace(interApiEntry.traceId, interApiEntry.traceDepth);\n }\n static addHeadersToRecord(input, depthOffset = 0) {\n if (input) {\n input[ContextUtil.traceHeaderName()] = ContextUtil.currentTraceId();\n input[ContextUtil.traceDepthHeaderName()] = StringRatchet.safeString(ContextUtil.currentTraceDepth() + depthOffset);\n }\n else {\n ErrorRatchet.throwFormattedErr('Cannot add headers to null/undefined input');\n }\n }\n static addTraceToProxyResult(pr) {\n pr.headers = pr.headers || {};\n ContextUtil.addHeadersToRecord(pr.headers);\n }\n static addTraceToHttpRequestInit(ri) {\n ri.headers = ri.headers || {};\n ContextUtil.addHeadersToRecord(ri.headers, 1);\n }\n static setProcessLabel(processLabel) {\n ContextUtil.CURRENT_PROCESS_LABEL = processLabel;\n }\n static currentRequestId() {\n const ctx = ContextUtil.CURRENT_CONTEXT;\n return ctx ? ctx.awsRequestId : null;\n }\n static defaultedCurrentRequestId(defaultValueIfMissing = StringRatchet.createType4Guid()) {\n return ContextUtil.currentRequestId() ?? defaultValueIfMissing;\n }\n static remainingTimeMS() {\n const ctx = ContextUtil.CURRENT_CONTEXT;\n return ctx ? ctx.getRemainingTimeInMillis() : null;\n }\n static currentProcessLabel() {\n return ContextUtil.CURRENT_PROCESS_LABEL || 'unset';\n }\n static traceHeaderName() {\n const headerName = ContextUtil?.CURRENT_EPSILON_REFERENCE?.config?.loggerConfig?.traceHeaderName || 'X-TRACE-ID';\n return headerName;\n }\n static traceDepthHeaderName() {\n const headerName = ContextUtil?.CURRENT_EPSILON_REFERENCE?.config?.loggerConfig?.traceDepthHeaderName || 'X-TRACE-DEPTH';\n return headerName;\n }\n static currentTraceId() {\n const traceFn = ContextUtil?.CURRENT_EPSILON_REFERENCE?.config?.loggerConfig?.traceIdGenerator || ContextUtil.defaultedCurrentRequestId;\n const traceId = ContextUtil.CURRENT_OVERRIDE_TRACE_ID ||\n ContextUtil.CURRENT_EVENT?.headers?.[ContextUtil.traceHeaderName()] ||\n traceFn(ContextUtil.CURRENT_EVENT, ContextUtil.CURRENT_CONTEXT);\n return traceId;\n }\n static currentTraceDepth() {\n const caller = ContextUtil.CURRENT_OVERRIDE_TRACE_DEPTH ||\n NumberRatchet.safeNumber(ContextUtil.CURRENT_EVENT?.headers?.[ContextUtil.traceDepthHeaderName()]) ||\n 1;\n return caller;\n }\n static addLogVariable(name, val) {\n ContextUtil.CURRENT_LOG_VARS[name] = val;\n }\n static fetchLogVariable(name) {\n return ContextUtil.CURRENT_LOG_VARS?.[name];\n }\n static fetchLogVariables() {\n return Object.assign({}, ContextUtil.CURRENT_LOG_VARS || {});\n }\n}\n//# sourceMappingURL=context-util.js.map","export class AwsUtil {\n static apiGatewayV2ToApiGatewayV1(srcEvt) {\n const rval = {\n requestContext: AwsUtil.apiGatewayV2RequestContextToApiGatewayV1RequestContext(srcEvt.requestContext),\n httpMethod: srcEvt.requestContext.http.method,\n path: srcEvt.requestContext.http.path,\n queryStringParameters: srcEvt.queryStringParameters,\n headers: srcEvt.headers,\n body: srcEvt.body,\n isBase64Encoded: srcEvt.isBase64Encoded,\n multiValueHeaders: null,\n multiValueQueryStringParameters: null,\n pathParameters: srcEvt.pathParameters,\n stageVariables: srcEvt.stageVariables,\n resource: null,\n };\n return rval;\n }\n static apiGatewayV2RequestContextToApiGatewayV1RequestContext(srcEvt) {\n const rval = {\n accountId: srcEvt.accountId,\n apiId: srcEvt.apiId,\n authorizer: null,\n domainName: srcEvt.domainName,\n domainPrefix: srcEvt.domainPrefix,\n requestId: srcEvt.requestId,\n routeKey: srcEvt.routeKey,\n stage: srcEvt.stage,\n requestTime: srcEvt.time,\n requestTimeEpoch: srcEvt.timeEpoch,\n protocol: srcEvt.http.protocol,\n httpMethod: srcEvt.http.method,\n identity: null,\n path: srcEvt.http.path,\n resourceId: null,\n resourcePath: null,\n };\n return rval;\n }\n static findInMap(toFind, map) {\n let rval = null;\n map.forEach((val, key) => {\n if (AwsUtil.matchExact(key, toFind)) {\n rval = val;\n }\n });\n return rval;\n }\n static matchExact(r, str) {\n const match = str.match(r);\n return match != null && str == match[0];\n }\n static resolvePotentialFunctionToResult(src, def) {\n let rval = def;\n if (src) {\n if (typeof src === 'function') {\n rval = src();\n }\n else {\n rval = src;\n }\n }\n return rval;\n }\n}\n//# sourceMappingURL=aws-util.js.map","import { AwsUtil } from '../util/aws-util.js';\nimport { LambdaEventDetector } from '@bitblit/ratchet-aws';\nexport class WebV2Handler {\n webHandler;\n constructor(webHandler) {\n this.webHandler = webHandler;\n }\n extractLabel(evt, context) {\n let rval = this.webHandler.extractLabel(AwsUtil.apiGatewayV2ToApiGatewayV1(evt), context);\n rval = rval.replace('WEB:', 'WEB2:');\n return rval;\n }\n handlesEvent(evt) {\n return LambdaEventDetector.isValidApiGatewayV2WithRequestContextEvent(evt);\n }\n async processEvent(evt, context) {\n const conv = AwsUtil.apiGatewayV2ToApiGatewayV1(evt);\n const asExtended = Object.assign({}, { parsedBody: null, authorization: null, convertedFromV2Event: true }, conv);\n const rval = await this.webHandler.openApiLambdaHandler(asExtended, context);\n return rval;\n }\n}\n//# sourceMappingURL=web-v2-handler.js.map","import { LambdaEventDetector } from '@bitblit/ratchet-aws';\nimport { EpsilonConstants } from '../epsilon-constants.js';\nimport { RequireRatchet } from '@bitblit/ratchet-common';\nimport { Logger } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { ContextUtil } from '../util/context-util.js';\nexport class InterApiUtil {\n static isInterApiSnsEvent(event) {\n return !!InterApiUtil.extractEntryFromEvent(event);\n }\n static extractEntryFromEvent(evt) {\n let rval = null;\n if (!!evt) {\n if (LambdaEventDetector.isSingleSnsEvent(evt)) {\n const cast = evt;\n const msg = cast.Records[0].Sns.Message;\n if (!!StringRatchet.trimToNull(msg)) {\n const parsed = JSON.parse(msg);\n if (!!parsed && parsed['type'] === EpsilonConstants.INTER_API_SNS_EVENT) {\n rval = parsed['interApiEvent'];\n }\n }\n }\n }\n return rval;\n }\n static async processInterApiEvent(evt, cfg, mgr) {\n let rval = [];\n RequireRatchet.notNullOrUndefined(evt, 'InterApiEntry');\n RequireRatchet.notNullOrUndefined(mgr, 'BackgroundManager');\n const interApiEntry = InterApiUtil.extractEntryFromEvent(evt);\n ContextUtil.setOverrideTraceFromInterApiEntry(interApiEntry);\n Logger.info('Processing inter-api event : %j', evt);\n const backgroundEntries = [];\n cfg.processMappings.forEach((map) => {\n if (!map.disabled && interApiEntry.source.match(map.sourceRegex) && interApiEntry.type.match(map.typeRegex)) {\n map.backgroundProcessTypes.forEach((taskName) => {\n const entry = mgr.createEntry(taskName, interApiEntry.data);\n backgroundEntries.push(entry);\n });\n }\n });\n if (backgroundEntries.length > 0) {\n Logger.info('Adding %d entries to queue', backgroundEntries.length);\n rval = await mgr.addEntriesToQueue(backgroundEntries, true);\n }\n else {\n Logger.info('No entries mapped for this event');\n }\n return rval;\n }\n static addTraceToInterApiEntry(ent) {\n if (ent) {\n ent.traceId = ent.traceId || ContextUtil.currentTraceId();\n ent.traceDepth = ent.traceDepth || ContextUtil.currentTraceDepth() + 1;\n }\n return ent;\n }\n}\n//# sourceMappingURL=inter-api-util.js.map","import { InterApiUtil } from '../inter-api/inter-api-util.js';\nexport class InterApiEpsilonLambdaEventHandler {\n _epsilon;\n constructor(_epsilon) {\n this._epsilon = _epsilon;\n }\n extractLabel(evt, context) {\n const ent = InterApiUtil.extractEntryFromEvent(evt);\n return 'InterApi:' + ent.source + ':' + ent.type;\n }\n handlesEvent(evt) {\n return this._epsilon.config.interApiConfig && InterApiUtil.isInterApiSnsEvent(evt);\n }\n async processEvent(evt, context) {\n const tmp = await InterApiUtil.processInterApiEvent(evt, this._epsilon.config.interApiConfig, this._epsilon.backgroundManager);\n const rval = {\n statusCode: 200,\n body: JSON.stringify(tmp),\n isBase64Encoded: false,\n };\n return rval;\n }\n}\n//# sourceMappingURL=inter-api-epsilon-lambda-event-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { AwsUtil } from '../util/aws-util.js';\nimport { LambdaEventDetector } from '@bitblit/ratchet-aws';\nexport class GenericSnsEpsilonLambdaEventHandler {\n _epsilon;\n constructor(_epsilon) {\n this._epsilon = _epsilon;\n }\n extractLabel(evt, context) {\n return 'SNSEvt:' + evt.Records[0].EventSource;\n }\n handlesEvent(evt) {\n return LambdaEventDetector.isValidSnsEvent(evt);\n }\n async processEvent(evt, context) {\n let rval = null;\n if (this._epsilon.config && this._epsilon.config.sns && evt && evt.Records.length > 0) {\n const finder = evt.Records[0].Sns.TopicArn;\n const handler = AwsUtil.findInMap(finder, this._epsilon.config.sns.handlers);\n if (handler) {\n rval = await handler(evt);\n }\n else {\n Logger.info('Found no SNS handler for : %s', finder);\n }\n }\n return rval;\n }\n}\n//# sourceMappingURL=generic-sns-epsilon-lambda-event-handler.js.map","import { RequireRatchet } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { ErrorRatchet } from '@bitblit/ratchet-common';\nimport { DateTime } from 'luxon';\nexport class CronUtil {\n static everyNMinuteFilter(n) {\n return CronUtil.everyNElementFilter(n, 60);\n }\n static everyNDaysOfYearFilter(n) {\n return CronUtil.everyNElementFilter(n, 365);\n }\n static everyNElementFilter(n, m) {\n RequireRatchet.notNullOrUndefined(n);\n RequireRatchet.notNullOrUndefined(m);\n const half = Math.floor(m / 2);\n if (!n || n < 2 || n > half || m % n !== 0) {\n ErrorRatchet.throwFormattedErr('Invalid config - this function only makes sense for 2 < N < %d and %d evenly divisible by N', half, m);\n throw new Error('Invalid config - this function only makes sense for 2 < N < 31 and 60 evenly divisible by N');\n }\n const rval = [];\n for (let i = 0; i < 60; i += n) {\n rval.push(i);\n }\n return rval;\n }\n static numberMatchesFilter(num, filter) {\n return !filter || filter.length === 0 || filter.includes(num);\n }\n static eventMatchesEntry(event, entry, cfg, testTimeEpochMS = new Date().getTime()) {\n let rval = false;\n if (!!event && !!entry && !!cfg.timezone) {\n if (!!event.resources && event.resources.length > 0) {\n const eventSourceName = event.resources[0];\n const targetTZ = StringRatchet.trimToNull(entry.overrideTimezone) || cfg.timezone;\n const nowInTZ = DateTime.fromMillis(testTimeEpochMS).setZone(targetTZ);\n rval = !entry.eventFilter || entry.eventFilter.test(eventSourceName);\n rval = rval && CronUtil.numberMatchesFilter(nowInTZ.minute, entry.minuteFilter);\n rval = rval && CronUtil.numberMatchesFilter(nowInTZ.hour, entry.hourFilter);\n rval = rval && CronUtil.numberMatchesFilter(nowInTZ.weekday, entry.dayOfWeekFilter);\n rval = rval && CronUtil.numberMatchesFilter(nowInTZ.day, entry.dayOfMonthFilter);\n rval = rval && CronUtil.numberMatchesFilter(nowInTZ.month, entry.monthOfYearFilter);\n rval = rval && (!entry.contextMatchFilter || entry.contextMatchFilter.test(StringRatchet.trimToEmpty(cfg.context)));\n rval = rval && (!entry.contextNoMatchFilter || !entry.contextNoMatchFilter.test(StringRatchet.trimToEmpty(cfg.context)));\n }\n }\n return rval;\n }\n static cronEntryName(entry, idx = null) {\n RequireRatchet.notNullOrUndefined(entry);\n let rval = null;\n if (!!entry) {\n rval = entry.name;\n rval = rval || entry['backgroundTaskType'];\n if (!rval && !!entry['directHandler']) {\n if (!!idx) {\n rval = 'Direct Entry ' + idx;\n }\n else {\n rval = 'Direct Entry (No idx specified)';\n }\n }\n }\n else {\n rval = 'ERROR: no entry passed';\n }\n return rval;\n }\n}\n//# sourceMappingURL=cron-util.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { AwsUtil } from '../util/aws-util.js';\nimport { CronUtil } from '../util/cron-util.js';\nimport { LambdaEventDetector } from '@bitblit/ratchet-aws';\nexport class CronEpsilonLambdaEventHandler {\n _epsilon;\n constructor(_epsilon) {\n this._epsilon = _epsilon;\n }\n extractLabel(evt, context) {\n return 'CronEvt:' + evt.source;\n }\n handlesEvent(evt) {\n return LambdaEventDetector.isValidCronEvent(evt);\n }\n async processEvent(evt, context) {\n let rval = null;\n Logger.debug('Epsilon: CRON: %j', evt);\n if (!this._epsilon.config.cron) {\n Logger.debug('Skipping - CRON disabled');\n rval = {\n statusCode: 200,\n body: JSON.stringify({ message: 'CRON skipped - disabled' }),\n isBase64Encoded: false,\n };\n }\n else {\n const output = await CronEpsilonLambdaEventHandler.processCronEvent(evt, this._epsilon.config.cron, this._epsilon.backgroundManager, this._epsilon.backgroundHandler);\n rval = {\n statusCode: 200,\n body: JSON.stringify({ message: 'CRON complete' }),\n isBase64Encoded: false,\n };\n }\n return rval;\n }\n static async processCronEvent(evt, cronConfig, backgroundManager, background) {\n let rval = false;\n if (cronConfig && evt && evt.resources[0]) {\n if (!!cronConfig.entries) {\n if (!!background) {\n const toEnqueue = [];\n for (let i = 0; i < cronConfig.entries.length; i++) {\n const smCronEntry = cronConfig.entries[i];\n if (CronUtil.eventMatchesEntry(evt, smCronEntry, cronConfig)) {\n Logger.info('CRON Firing : %s', CronUtil.cronEntryName(smCronEntry));\n const backgroundEntry = {\n type: smCronEntry.backgroundTaskType,\n data: AwsUtil.resolvePotentialFunctionToResult(smCronEntry.data, {}),\n };\n Logger.silly('Resolved entry : %j', backgroundEntry);\n if (smCronEntry.fireImmediate) {\n await backgroundManager.fireImmediateProcessRequest(backgroundEntry);\n rval = true;\n }\n else {\n toEnqueue.push(backgroundEntry);\n }\n }\n }\n if (toEnqueue.length > 0) {\n await backgroundManager.addEntriesToQueue(toEnqueue, true);\n rval = true;\n }\n }\n else {\n Logger.warn('Cron defines background tasks, but no background manager provided');\n }\n }\n }\n return rval;\n }\n}\n//# sourceMappingURL=cron-epsilon-lambda-event-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { AwsUtil } from '../util/aws-util.js';\nimport { LambdaEventDetector } from '@bitblit/ratchet-aws';\nexport class S3EpsilonLambdaEventHandler {\n _epsilon;\n constructor(_epsilon) {\n this._epsilon = _epsilon;\n }\n extractLabel(evt, context) {\n return 'S3Evt:' + evt.Records[0].eventSource;\n }\n handlesEvent(evt) {\n return LambdaEventDetector.isValidS3Event(evt);\n }\n async processEvent(evt, context) {\n let rval = null;\n if (this._epsilon.config && this._epsilon.config.s3 && evt && evt.Records.length > 0) {\n const finder = evt.Records[0].s3.bucket.name + '/' + evt.Records[0].s3.object.key;\n const isRemoveEvent = evt.Records[0].eventName && evt.Records[0].eventName.startsWith('ObjectRemoved');\n if (isRemoveEvent) {\n const handler = AwsUtil.findInMap(finder, this._epsilon.config.s3.removeHandlers);\n if (handler) {\n rval = await handler(evt);\n }\n else {\n Logger.info('Found no s3 create handler for : %s', finder);\n }\n }\n else {\n const handler = AwsUtil.findInMap(finder, this._epsilon.config.s3.createHandlers);\n if (handler) {\n rval = await handler(evt);\n }\n else {\n Logger.info('Found no s3 remove handler for : %s', finder);\n }\n }\n }\n return rval;\n }\n}\n//# sourceMappingURL=s3-epsilon-lambda-event-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { AwsUtil } from '../util/aws-util.js';\nimport { LambdaEventDetector } from '@bitblit/ratchet-aws';\nexport class DynamoEpsilonLambdaEventHandler {\n _epsilon;\n constructor(_epsilon) {\n this._epsilon = _epsilon;\n }\n extractLabel(evt, context) {\n return 'DDBEvt:' + evt.Records[0].eventName + ':' + evt.Records[0].eventSource;\n }\n handlesEvent(evt) {\n return LambdaEventDetector.isValidDynamoDBEvent(evt);\n }\n async processEvent(evt, context) {\n let rval = null;\n if (this._epsilon.config && this._epsilon.config.dynamoDb && evt && evt.Records && evt.Records.length > 0) {\n const finder = evt.Records[0].eventSourceARN;\n const handler = AwsUtil.findInMap(finder, this._epsilon.config.dynamoDb.handlers);\n if (handler) {\n rval = await handler(evt);\n }\n else {\n Logger.info('Found no Dynamo handler for : %s', finder);\n }\n }\n return rval;\n }\n async processUncaughtError(event, context, err) {\n Logger.error('Error slipped out to outer edge (Dynamo). Logging and rethrowing : %s', err, err);\n throw err;\n }\n}\n//# sourceMappingURL=dynamo-epsilon-lambda-event-handler.js.map","import { ContextUtil } from './util/context-util.js';\nexport class EpsilonLoggingExtensionProcessor {\n process(msg) {\n msg.params = Object.assign({}, msg.params || {}, ContextUtil.fetchLogVariables());\n msg.params['tester'] = Date.now();\n msg.params['awsRequestId'] = ContextUtil.currentRequestId();\n msg.params['traceId'] = ContextUtil.currentTraceId();\n msg.params['traceDepth'] = ContextUtil.currentTraceDepth();\n msg.params['procLabel'] = ContextUtil.currentProcessLabel();\n return msg;\n }\n label() {\n return 'EpsilonLoggingExtensionProcessor';\n }\n}\n//# sourceMappingURL=epsilon-logging-extension-processor.js.map","import { ErrorRatchet, Logger, LoggerLevelName, LoggerOutputFunction, LogMessageFormatType, PromiseRatchet, TimeoutToken, RestfulApiHttpError } from '@bitblit/ratchet-common';\nimport { EventUtil } from './http/event-util.js';\nimport { ResponseUtil } from './http/response-util.js';\nimport { RequestTimeoutError } from './http/error/request-timeout-error.js';\nimport { ContextUtil } from './util/context-util.js';\nimport { WebV2Handler } from './http/web-v2-handler.js';\nimport { InterApiEpsilonLambdaEventHandler } from './lambda-event-handler/inter-api-epsilon-lambda-event-handler.js';\nimport { GenericSnsEpsilonLambdaEventHandler } from './lambda-event-handler/generic-sns-epsilon-lambda-event-handler.js';\nimport { CronEpsilonLambdaEventHandler } from './lambda-event-handler/cron-epsilon-lambda-event-handler.js';\nimport { S3EpsilonLambdaEventHandler } from './lambda-event-handler/s3-epsilon-lambda-event-handler.js';\nimport { DynamoEpsilonLambdaEventHandler } from './lambda-event-handler/dynamo-epsilon-lambda-event-handler.js';\nimport { EpsilonLoggingExtensionProcessor } from './epsilon-logging-extension-processor.js';\nexport class EpsilonGlobalHandler {\n _epsilon;\n static LOGGER_CONFIGURED = false;\n static GLOBAL_INSTANCE_PROVIDER;\n static set globalInstanceProvider(input) {\n EpsilonGlobalHandler.GLOBAL_INSTANCE_PROVIDER = input;\n }\n static get globalInstanceProvider() {\n return EpsilonGlobalHandler.GLOBAL_INSTANCE_PROVIDER;\n }\n handlers = null;\n constructor(_epsilon) {\n this._epsilon = _epsilon;\n if (!EpsilonGlobalHandler.LOGGER_CONFIGURED) {\n EpsilonGlobalHandler.configureDefaultLogger();\n Logger.info('EpsilonLoggingConfiguration:Default logger configured');\n }\n else {\n Logger.info('EpsilonLoggingConfiguration:Skipping default logger config - already configured');\n }\n this.handlers = [\n this._epsilon.webHandler,\n new WebV2Handler(this._epsilon.webHandler),\n this._epsilon.backgroundHandler,\n new InterApiEpsilonLambdaEventHandler(this._epsilon),\n new GenericSnsEpsilonLambdaEventHandler(this._epsilon),\n new CronEpsilonLambdaEventHandler(this._epsilon),\n new S3EpsilonLambdaEventHandler(this._epsilon),\n new DynamoEpsilonLambdaEventHandler(this._epsilon),\n ];\n }\n static configureDefaultLogger(overrides) {\n const output = overrides ? Object.assign({}, overrides) : {};\n output.initialLevel = output.initialLevel ?? LoggerLevelName.info;\n output.formatType = output.formatType ?? LogMessageFormatType.StructuredJson;\n output.globalVars = output.globalVars ?? {};\n output.outputFunction = output.outputFunction ?? LoggerOutputFunction.StdOut;\n output.ringBufferSize = output.ringBufferSize ?? 0;\n const src = output.preProcessors || [];\n output.preProcessors = src.concat([new EpsilonLoggingExtensionProcessor()]);\n const pre = Logger.getOptions();\n Logger.changeDefaultOptions(output, true);\n const post = Logger.getOptions();\n EpsilonGlobalHandler.LOGGER_CONFIGURED = true;\n Logger.info('EpsilonLoggingConfiguration: Updated');\n Logger.dumpOptionsIntoLog();\n }\n get epsilon() {\n return this._epsilon;\n }\n async processSingleBackgroundByParts(type, data, overrideTraceId, overrideTraceDepth) {\n return this.processSingleBackgroundEntry(this._epsilon.backgroundManager.createEntry(type, data), overrideTraceId, overrideTraceDepth);\n }\n async processSingleBackgroundEntry(e, overrideTraceId, overrideTraceDepth) {\n let rval = false;\n if (e?.type) {\n const internal = this._epsilon.backgroundManager.wrapEntryForInternal(e, overrideTraceId, overrideTraceDepth);\n rval = await this._epsilon.backgroundHandler.processSingleBackgroundEntry(internal);\n Logger.info('Direct processed request %j to %s', e, rval);\n }\n else {\n Logger.error('Cannot process null/unnamed background entry');\n }\n return rval;\n }\n async lambdaHandler(event, context) {\n let rval = null;\n try {\n if (this.epsilon.config.disableLastResortTimeout || !context || !context.getRemainingTimeInMillis()) {\n rval = await this.innerLambdaHandler(event, context);\n }\n else {\n const tmp = await PromiseRatchet.timeout(this.innerLambdaHandler(event, context), 'EpsilonLastResortTimeout', context.getRemainingTimeInMillis() - 1000);\n if (TimeoutToken.isTimeoutToken(tmp)) {\n tmp.writeToLog();\n rval = ResponseUtil.errorResponse(RestfulApiHttpError.wrapError(new RequestTimeoutError('Timed out')));\n }\n else {\n rval = tmp;\n }\n }\n }\n finally {\n ContextUtil.clearContext();\n }\n return rval;\n }\n async innerLambdaHandler(event, context) {\n ContextUtil.initContext(this._epsilon, event, context, 'TBD');\n let rval = null;\n let errorHandler = EpsilonGlobalHandler.defaultProcessUncaughtError;\n try {\n if (!this._epsilon) {\n Logger.error('Config not found, abandoning');\n return false;\n }\n const logLevel = EventUtil.calcLogLevelViaEventOrEnvParam(Logger.getLevel(), event, this._epsilon.config.loggerConfig);\n Logger.setLevel(logLevel);\n if (this._epsilon.config.loggerConfig &&\n this._epsilon.config.loggerConfig.queryParamTracePrefixName &&\n event.queryStringParameters &&\n event.queryStringParameters[this._epsilon.config.loggerConfig.queryParamTracePrefixName]) {\n Logger.info('Setting trace prefix to %s', event.queryStringParameters[this._epsilon.config.loggerConfig.queryParamTracePrefixName]);\n Logger.updateTracePrefix(event.queryStringParameters[this._epsilon.config.loggerConfig.queryParamTracePrefixName]);\n }\n let found = false;\n for (let i = 0; i < this.handlers.length && !found; i++) {\n const handler = this.handlers[i];\n if (handler.handlesEvent(event)) {\n found = true;\n errorHandler = handler.processUncaughtError || errorHandler;\n const label = handler.extractLabel(event, context);\n ContextUtil.setProcessLabel(label);\n Logger.logByLevel(this._epsilon?.config?.loggerConfig?.epsilonStartEndMessageLogLevel || LoggerLevelName.info, 'EvtStart: %s', label);\n rval = await handler.processEvent(event, context);\n Logger.logByLevel(this._epsilon?.config?.loggerConfig?.epsilonStartEndMessageLogLevel || LoggerLevelName.info, 'EvtEnd: %s', label);\n Logger.silly('EvtEnd:Value: %s Value: %j', label, rval);\n }\n }\n }\n catch (err) {\n rval = await errorHandler(event, context, err);\n }\n return rval;\n }\n static async defaultProcessUncaughtError(event, context, err) {\n Logger.error('Error slipped out to outer edge (Default). Logging and returning log : %s', err, err);\n const rval = {\n statusCode: 500,\n body: JSON.stringify({ error: ErrorRatchet.safeStringifyErr(err) }),\n isBase64Encoded: false,\n };\n return rval;\n }\n}\n//# sourceMappingURL=epsilon-global-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { EpsilonConstants } from './epsilon-constants.js';\nimport { InterApiUtil } from './inter-api/inter-api-util.js';\nimport { PublishCommand } from '@aws-sdk/client-sns';\nexport class InterApiManager {\n _aws;\n _sns;\n constructor(_aws, _sns) {\n this._aws = _aws;\n this._sns = _sns;\n }\n get config() {\n return this._aws;\n }\n get sns() {\n return this._sns;\n }\n createEntry(type, data) {\n const rval = {\n source: this._aws.source,\n type: type,\n data: data,\n };\n return rval;\n }\n async fireInterApiEventByParts(type, data) {\n const entry = this.createEntry(type, data);\n const rval = await this.fireInterApiEvent(entry);\n return rval;\n }\n async fireInterApiEvent(entry) {\n let rval = null;\n if (this.config.localMode) {\n Logger.info('Fire inter-api event ignored because running locally (was %j)', entry);\n rval = 'INTER-API-IGNORED';\n }\n else {\n try {\n Logger.info('Firing inter-api event (remote) : %j ', entry);\n const toWrite = {\n type: EpsilonConstants.INTER_API_SNS_EVENT,\n interApiEvent: InterApiUtil.addTraceToInterApiEntry(entry),\n };\n const msg = JSON.stringify(toWrite);\n const snsId = await this.writeMessageToSnsTopic(msg);\n Logger.debug('Inter-api Wrote message : %s to SNS : %s', rval, msg, snsId);\n }\n catch (err) {\n Logger.error('Failed to fireImmediateProcessRequest : %s', err, err);\n }\n }\n return rval;\n }\n async writeMessageToSnsTopic(message) {\n let rval = null;\n const params = {\n Message: message,\n TopicArn: this._aws.snsArn,\n };\n Logger.debug('Writing message to SNS topic : j', params);\n const result = await this.sns.send(new PublishCommand(params));\n rval = result.MessageId;\n return rval;\n }\n}\n//# sourceMappingURL=inter-api-manager.js.map","export class LocalServerCert {\n static CLIENT_CSR = '-----BEGIN CERTIFICATE REQUEST-----\\n' +\n 'MIICwjCCAaoCAQAwfTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAk5WMRIwEAYDVQQH\\n' +\n 'DAlMYXMgVmVnYXMxDjAMBgNVBAoMBVBsdW1hMRkwFwYDVQQDDBB3d3cuaGV5cGx1\\n' +\n 'bWEuY29tMSIwIAYJKoZIhvcNAQkBFhNjd2Vpc3NAaGV5cGx1bWEuY29tMIIBIjAN\\n' +\n 'BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Gh1SD1VciosMgh3MHF7IyKgNTu2\\n' +\n 'DjGMoORJV4VNKzrjp7UOdKnD3so0Xx3A6bUTYAL8Vtc+EG+8LZjUpBIOwuKzzbVo\\n' +\n 't16+yt3YXBxzTZPU9g7sFsXx42RoNispIFq0enRtJrq/zq8izZxUZdGn9XD2DidL\\n' +\n 'AedtRGjb8cmRuP6wmMRPBOZjct4ZjsSiTyhPa6kpt8V7Pa7vm0HGxcHiDAGp6zoy\\n' +\n 'GHfBdsqeBdGbkGT1ZPfs9kpbtXPm82Sckd0p3oY3fJn0rZqpT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ZEHOYs1fvU+\\n' +\n 'gU/1N8q9DBvr0B+XGeYR3NNdljajo6pwWZ6ed5sCgYAGmkz5ZPLU0yVBR8rsRaJh\\n' +\n 'yWFdT2EEhgIDTQXDBImxqblahYw3hIR1Ij1B8g+NI9jj0P1BMC6X7sliDEcreFB5\\n' +\n 'QHVdx0T5UFFE6XmH2ue7Q5IWp6cL1ShsRyXHRoE9okb0BI8c3S9haXDBCj44ndAN\\n' +\n 'VUXrDlykevFXC/k7fHBTdQKBgHjIshpoEycOD1e753oS4JTL6GdO6271DlFq5LYj\\n' +\n 'IZNsXtCkJhH3vvJ35Hp8XEu4snQ0hfV90d79PuS+pRppOETct8pqKVp8hL4ymv8U\\n' +\n 'v+0vkQN7NeA3pnZW0W/kag400nP8xJ26f+xiggw9Q4vOlFSioe6loUjgCBNZDlh3\\n' +\n 'iO5VAoGASXkcv39B9/8FuWQ7rwhXHEubxOOwZZzSBU1wtLj2qHyPGoeU9ZpsmdrL\\n' +\n 'XS9w1Jy0e49qmbBjzTqAEBw2nn/JVMFHyI/s//JVF7Q9GfBZAF5XF6mJ24yzTKgF\\n' +\n 'kSoO5T+7s8NXi0eAIBe4CkWCBX7kWEZtu46GuVhsrC3oEazuLOs=\\n' +\n '-----END RSA PRIVATE KEY-----\\n';\n}\n//# sourceMappingURL=local-server-cert.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class NotFoundError extends RestfulApiHttpError {\n static HTTP_CODE = 404;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(NotFoundError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=not-found-error.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class ForbiddenError extends RestfulApiHttpError {\n static HTTP_CODE = 403;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(ForbiddenError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=forbidden-error.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class NotImplemented extends RestfulApiHttpError {\n static HTTP_CODE = 501;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(NotImplemented.HTTP_CODE);\n }\n}\n//# sourceMappingURL=not-implemented.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class MisconfiguredError extends RestfulApiHttpError {\n static HTTP_CODE = 500;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(MisconfiguredError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=misconfigured-error.js.map","import { Logger, NumberRatchet, StringRatchet, RestfulApiHttpError } from '@bitblit/ratchet-common';\nimport { BadRequestError } from '../../http/error/bad-request-error.js';\nimport { UnauthorizedError } from '../../http/error/unauthorized-error.js';\nimport { NotFoundError } from '../../http/error/not-found-error.js';\nimport { ForbiddenError } from '../../http/error/forbidden-error.js';\nimport { NotImplemented } from '../../http/error/not-implemented.js';\nimport { MisconfiguredError } from '../../http/error/misconfigured-error.js';\nexport class BuiltInHandlers {\n static async expectedHandledByFilter(evt, flag) {\n throw new MisconfiguredError().withFormattedErrorMessage('Should not happen - it was expected that route %s would be handled by a filter', evt.path);\n }\n static async handleNotImplemented(evt, flag) {\n Logger.info('A request was made to %s with body %j - not yet implemented', evt.path, evt.body);\n const rval = {\n time: new Date().toLocaleString(),\n path: evt.path,\n message: 'NOT IMPLEMENTED YET',\n };\n return rval;\n }\n static async sample(evt, flag, context) {\n const rval = {\n time: new Date().toLocaleString(),\n evt: evt,\n pad: StringRatchet.createRandomHexString(2000),\n flag: flag,\n };\n if (context) {\n rval['context'] = context;\n }\n const errNumber = NumberRatchet.safeNumber(evt.queryStringParameters['error']);\n if (errNumber) {\n switch (errNumber) {\n case -1:\n throw new Error('Test random failure');\n case 400:\n throw new BadRequestError('Bad request error');\n case 401:\n throw new UnauthorizedError('Unauthorized error');\n case 403:\n throw new ForbiddenError('Forbidden error');\n case 404:\n throw new NotFoundError('Not Found error');\n case 501:\n throw new NotImplemented('Not Implemented');\n default:\n throw new RestfulApiHttpError()\n .withFormattedErrorMessage('Default error - %s', errNumber)\n .withHttpStatusCode(500)\n .withDetails({ src: errNumber })\n .withEndUserErrors(['msg1', 'msg2']);\n }\n }\n let test = StringRatchet.trimToNull(evt.queryStringParameters['test']);\n if (test) {\n test = test.toLowerCase();\n if (test === 'null') {\n return null;\n }\n }\n return rval;\n }\n static async defaultErrorProcessor(event, err, cfg) {\n Logger.warn('Unhandled error (in promise catch) : %s \\nStack was: %s\\nEvt was: %j\\nConfig was: %j', err.message, err.stack, event, cfg);\n }\n}\n//# sourceMappingURL=built-in-handlers.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { UnauthorizedError } from '../error/unauthorized-error.js';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { RequireRatchet } from '@bitblit/ratchet-common';\nimport { JwtRatchet } from '@bitblit/ratchet-common';\nimport { ExpiredJwtHandling } from '@bitblit/ratchet-common';\nexport class LocalWebTokenManipulator {\n encryptionKeys;\n issuer;\n _ratchet;\n constructor(encryptionKeys, issuer) {\n this.encryptionKeys = encryptionKeys;\n this.issuer = issuer;\n RequireRatchet.notNullOrUndefined(encryptionKeys, 'encryptionKeys');\n RequireRatchet.noNullOrUndefinedValuesInArray(encryptionKeys, encryptionKeys.length);\n this._ratchet = new JwtRatchet(Promise.resolve(encryptionKeys));\n }\n withExtraDecryptionKeys(keys) {\n RequireRatchet.notNullOrUndefined(keys, 'keys');\n RequireRatchet.noNullOrUndefinedValuesInArray(keys, keys.length);\n this._ratchet = new JwtRatchet(this._ratchet.encryptionKeyPromise, Promise.resolve(keys), this._ratchet.jtiGenerator, this._ratchet.decryptOnlyKeyUseLogLevel, this._ratchet.parseFailureLogLevel);\n return this;\n }\n withParseFailureLogLevel(logLevel) {\n this._ratchet = new JwtRatchet(this._ratchet.encryptionKeyPromise, this._ratchet.decryptKeysPromise, this._ratchet.jtiGenerator, this._ratchet.decryptOnlyKeyUseLogLevel, logLevel);\n return this;\n }\n withOldKeyUseLogLevel(logLevel) {\n this._ratchet = new JwtRatchet(this._ratchet.encryptionKeyPromise, this._ratchet.decryptKeysPromise, this._ratchet.jtiGenerator, logLevel, this._ratchet.parseFailureLogLevel);\n return this;\n }\n get jwtRatchet() {\n return this._ratchet;\n }\n get selectRandomEncryptionKey() {\n return this._ratchet.selectRandomEncryptionKey();\n }\n createRefreshedJWTString(tokenString, expirationSeconds, allowExpired) {\n return this._ratchet.refreshJWTString(tokenString, allowExpired || false, expirationSeconds);\n }\n async parseAndValidateJWTStringAsync(tokenString) {\n const payload = await this._ratchet.decodeToken(tokenString, ExpiredJwtHandling.ADD_FLAG);\n if (JwtRatchet.hasExpiredFlag(payload)) {\n throw new UnauthorizedError('Failing JWT token read/validate - token expired on ' + payload.exp);\n }\n else {\n return payload;\n }\n }\n async createJWTStringAsync(principal, userObject, roles = ['USER'], expirationSeconds = 3600, proxyUser = null) {\n Logger.info('Creating JWT token for %s that expires in %s', principal, expirationSeconds);\n const now = new Date().getTime();\n const expires = now + expirationSeconds * 1000;\n const tokenData = {\n exp: expires,\n iss: this.issuer,\n sub: principal,\n iat: now,\n user: userObject,\n proxy: proxyUser,\n roles: roles,\n };\n const token = await this._ratchet.createTokenString(tokenData, expirationSeconds);\n return token;\n }\n async extractTokenFromAuthorizationHeader(header) {\n let tokenString = StringRatchet.trimToEmpty(header);\n if (tokenString.toLowerCase().startsWith('bearer ')) {\n tokenString = tokenString.substring(7);\n }\n const validated = !!tokenString ? await this.parseAndValidateJWTStringAsync(tokenString) : null;\n return validated;\n }\n}\n//# sourceMappingURL=local-web-token-manipulator.js.map","import { ErrorRatchet } from '@bitblit/ratchet-common';\nimport { Logger } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nexport class EchoProcessor {\n static TYPE_NAME = 'EpsilonEcho';\n get typeName() {\n return EchoProcessor.TYPE_NAME;\n }\n async handleEvent(data, mgr) {\n Logger.info('Echo processing : %j', data);\n if (data && StringRatchet.trimToNull(data['error'])) {\n ErrorRatchet.throwFormattedErr('Forced error : %s', data['error']);\n }\n }\n}\n//# sourceMappingURL=echo-processor.js.map","import { Logger } from '@bitblit/ratchet-common';\nexport class NoOpProcessor {\n get typeName() {\n return 'EpsilonNoOp';\n }\n async handleEvent(data, mgr) {\n Logger.silly('Hit the no-op proc');\n }\n}\n//# sourceMappingURL=no-op-processor.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { PromiseRatchet } from '@bitblit/ratchet-common';\nexport class SampleDelayProcessor {\n get typeName() {\n return 'EpsilonSampleDelay';\n }\n async handleEvent(data, mgr) {\n const delayMS = Math.floor(Math.random() * 5000);\n Logger.info('Running sample processor for %d', delayMS);\n await PromiseRatchet.wait(delayMS);\n Logger.info('Sample processor complete');\n }\n}\n//# sourceMappingURL=sample-delay-processor.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { EchoProcessor } from './echo-processor.js';\nexport class LogAndEnqueueEchoProcessor {\n get typeName() {\n return 'EpsilonLogAndEnqueueEcho';\n }\n async handleEvent(data, cfg) {\n Logger.info('LogAndEnqueueEchoProcessor : %j', data);\n await cfg.fireImmediateProcessRequestByParts(EchoProcessor.TYPE_NAME, { upstream: data });\n Logger.info('Completed : LogAndEnqueueEchoProcessor');\n }\n}\n//# sourceMappingURL=log-and-enqueue-echo-processor.js.map","export var BackgroundProcessHandling;\n(function (BackgroundProcessHandling) {\n BackgroundProcessHandling[\"Queued\"] = \"Queued\";\n BackgroundProcessHandling[\"Immediate\"] = \"Immediate\";\n})(BackgroundProcessHandling || (BackgroundProcessHandling = {}));\n//# sourceMappingURL=background-process-handling.js.map","export var BackgroundExecutionEventType;\n(function (BackgroundExecutionEventType) {\n BackgroundExecutionEventType[\"ProcessStarting\"] = \"ProcessStarting\";\n BackgroundExecutionEventType[\"DataValidationError\"] = \"DataValidationError\";\n BackgroundExecutionEventType[\"ExecutionSuccessfullyComplete\"] = \"ExecutionSuccessfullyComplete\";\n BackgroundExecutionEventType[\"ExecutionFailedError\"] = \"ExecutionRuntimeError\";\n BackgroundExecutionEventType[\"NoMatchProcessorName\"] = \"NoMatchProcessorName\";\n})(BackgroundExecutionEventType || (BackgroundExecutionEventType = {}));\n//# sourceMappingURL=background-execution-event-type.js.map","export var NullReturnedObjectHandling;\n(function (NullReturnedObjectHandling) {\n NullReturnedObjectHandling[\"Error\"] = \"Error\";\n NullReturnedObjectHandling[\"ConvertToEmptyString\"] = \"ConvertToEmptyString\";\n NullReturnedObjectHandling[\"Return404NotFoundResponse\"] = \"Return404NotFoundResponse\";\n})(NullReturnedObjectHandling || (NullReturnedObjectHandling = {}));\n//# sourceMappingURL=null-returned-object-handling.js.map","export var EpsilonApolloCorsMethod;\n(function (EpsilonApolloCorsMethod) {\n EpsilonApolloCorsMethod[\"None\"] = \"None\";\n EpsilonApolloCorsMethod[\"All\"] = \"All\";\n EpsilonApolloCorsMethod[\"Reflective\"] = \"Reflective\";\n})(EpsilonApolloCorsMethod || (EpsilonApolloCorsMethod = {}));\n//# sourceMappingURL=epsilon-apollo-cors-method.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { PromiseRatchet } from '@bitblit/ratchet-common';\nimport { BackgroundProcessHandling } from './background-process-handling.js';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { BooleanRatchet } from '@bitblit/ratchet-common';\nimport { BadRequestError } from '../http/error/bad-request-error.js';\nimport { NotFoundError } from '../http/error/not-found-error.js';\nimport { StopWatch } from '@bitblit/ratchet-common';\nexport class BackgroundHttpAdapterHandler {\n backgroundConfig;\n modelValidator;\n backgroundManager;\n maxWaitInMsForBackgroundJobToStart;\n constructor(backgroundConfig, modelValidator, backgroundManager, maxWaitInMsForBackgroundJobToStart = 10_000) {\n this.backgroundConfig = backgroundConfig;\n this.modelValidator = modelValidator;\n this.backgroundManager = backgroundManager;\n this.maxWaitInMsForBackgroundJobToStart = maxWaitInMsForBackgroundJobToStart;\n }\n get httpMetaEndpoint() {\n return this.backgroundConfig.httpMetaEndpoint;\n }\n get httpSubmissionPath() {\n return this.backgroundConfig.httpSubmissionPath;\n }\n get httpStatusPath() {\n return this.backgroundConfig.httpStatusEndpoint;\n }\n get implyTypeFromPathSuffix() {\n return this.backgroundConfig.implyTypeFromPathSuffix;\n }\n async handleBackgroundStatusRequest(evt, context) {\n Logger.info('handleBackgroundStatusRequest called');\n if (!this.backgroundConfig.transactionLogger) {\n throw new BadRequestError('Process logging not enabled');\n }\n else {\n const guid = StringRatchet.trimToNull(evt.pathParameters['guid']) || StringRatchet.trimToNull(evt.queryStringParameters['guid']);\n if (guid) {\n const sw = new StopWatch();\n let log = null;\n while (!log && sw.elapsedMS() < this.maxWaitInMsForBackgroundJobToStart) {\n log = await this.backgroundConfig.transactionLogger.readTransactionLog(guid);\n if (!log) {\n Logger.debug('No log found yet, waiting 500 ms and retrying (%s of %d waited so far)', sw.dump(), this.maxWaitInMsForBackgroundJobToStart);\n await PromiseRatchet.wait(500);\n }\n }\n if (!log) {\n throw new NotFoundError().withFormattedErrorMessage('No background result found for guid %s', guid);\n }\n return log;\n }\n else {\n throw new BadRequestError('No guid specified');\n }\n }\n }\n async handleBackgroundMetaRequest(evt, context) {\n Logger.info('handleBackgroundMetaRequest called');\n const currentCount = await this.backgroundManager.fetchApproximateNumberOfQueueEntries();\n const valid = this.backgroundConfig.processors.map((b) => b.typeName).filter((a) => !!a);\n valid.sort((a, b) => a.localeCompare(b));\n const rval = {\n currentQueueLength: currentCount,\n validTypes: valid,\n backgroundManagerName: this.backgroundManager.backgroundManagerName,\n };\n return rval;\n }\n async handleBackgroundSubmission(evt, context) {\n Logger.info('handleBackgroundSubmission : %j (mgr:%s)', evt.parsedBody, this.backgroundManager.backgroundManagerName);\n let rval = null;\n const startIdx = evt.path.indexOf(this.httpSubmissionPath) + this.httpSubmissionPath.length;\n let pathSuppliedBackgroundType = this.backgroundConfig.implyTypeFromPathSuffix\n ? evt.path.substring(startIdx).split('-').join('').toLowerCase()\n : '';\n if (pathSuppliedBackgroundType.includes('?')) {\n pathSuppliedBackgroundType = pathSuppliedBackgroundType.substring(0, pathSuppliedBackgroundType.indexOf('?'));\n }\n if (pathSuppliedBackgroundType.includes('#')) {\n pathSuppliedBackgroundType = pathSuppliedBackgroundType.substring(0, pathSuppliedBackgroundType.indexOf('#'));\n }\n const entry = evt.parsedBody || {};\n if (StringRatchet.trimToNull(pathSuppliedBackgroundType)) {\n if (StringRatchet.trimToNull(entry?.type) && entry.type.toLocaleLowerCase() !== pathSuppliedBackgroundType.toLocaleLowerCase()) {\n throw new BadRequestError('Background submission has type but does not match path supplied type');\n }\n else {\n entry.type = pathSuppliedBackgroundType;\n }\n }\n else {\n if (!StringRatchet.trimToNull(entry?.type)) {\n throw new BadRequestError('Background submission missing type and not configured in pathed mode');\n }\n }\n const foundProc = this.backgroundConfig.processors.find((s) => s.typeName.toLowerCase() === entry.type.toLowerCase());\n const immediate = BooleanRatchet.parseBool(evt.queryStringParameters['immediate']);\n const startProcessor = BooleanRatchet.parseBool(evt.queryStringParameters['startProcessor']);\n if (foundProc) {\n if (StringRatchet.trimToNull(foundProc.dataSchemaName)) {\n const errors = this.modelValidator.validate(foundProc.dataSchemaName, entry.data, false, false);\n if (errors.length > 0) {\n throw new BadRequestError().withErrors(errors);\n }\n }\n let result = null;\n if (immediate) {\n result = await this.backgroundManager.fireImmediateProcessRequest(entry);\n }\n else {\n result = await this.backgroundManager.addEntryToQueue(entry, startProcessor);\n }\n rval = {\n processHandling: immediate ? BackgroundProcessHandling.Immediate : BackgroundProcessHandling.Queued,\n startProcessorRequested: startProcessor,\n success: true,\n resultId: result,\n error: null,\n };\n }\n else {\n throw new BadRequestError().withFormattedErrorMessage('Could not find target background processor : %s', entry.type);\n }\n return rval;\n }\n}\n//# sourceMappingURL=background-http-adapter-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { ErrorRatchet } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nexport class BackgroundValidator {\n cfg;\n modelValidator;\n constructor(cfg, modelValidator) {\n this.cfg = cfg;\n this.modelValidator = modelValidator;\n }\n findProcessor(typeName) {\n const rval = this.cfg.processors.find((s) => s.typeName === typeName);\n return rval;\n }\n validType(type) {\n return !!this.findProcessor(type);\n }\n validateEntry(entry) {\n const rval = [];\n if (!entry) {\n rval.push('Entry is null');\n }\n else if (!StringRatchet.trimToNull(entry.type)) {\n rval.push('Entry type is null or empty');\n const proc = this.findProcessor(entry.type);\n if (!proc) {\n rval.push('Entry type is invalid');\n }\n }\n return rval;\n }\n validateEntryAndThrowException(entry) {\n const errors = this.validateEntry(entry);\n if (errors.length > 0) {\n Logger.warn('Invalid entry %j : errors : %j', entry, errors);\n ErrorRatchet.throwFormattedErr('Invalid entry %j : errors : %j', entry, errors);\n }\n }\n static validateAndMapProcessors(processorInput, modelValidator) {\n const rval = new Map();\n processorInput.forEach((p, idx) => {\n if (!p) {\n ErrorRatchet.throwFormattedErr('Null processor provided at index %d', idx);\n }\n if (!StringRatchet.trimToNull(p.typeName)) {\n ErrorRatchet.throwFormattedErr('Processor at index %d defines no name', idx);\n }\n if (rval.has(p.typeName)) {\n ErrorRatchet.throwFormattedErr('More than one processor defined for type %s', p.typeName);\n }\n rval.set(p.typeName, p);\n });\n return rval;\n }\n static validateAwsConfig(cfg) {\n const rval = [];\n if (!cfg) {\n rval.push('Null config');\n }\n else {\n if (!cfg.notificationArn) {\n rval.push('AWS config missing notificationArn');\n }\n if (!cfg.queueUrl) {\n rval.push('AWS config missing queueUrl');\n }\n if ((cfg.sendNotificationOnBackgroundError || cfg.sendNotificationOnBackgroundValidationFailure) &&\n !cfg.backgroundProcessFailureSnsArn) {\n rval.push('At least one send notification flag set to true but no sns arn set');\n }\n }\n return rval;\n }\n static validateConfig(cfg) {\n const rval = [];\n if (!cfg) {\n rval.push('Null config');\n }\n else {\n if (!cfg.processors || cfg.processors.length === 0) {\n rval.push('No processes specified');\n }\n }\n return rval;\n }\n}\n//# sourceMappingURL=background-validator.js.map","import { ErrorRatchet } from '@bitblit/ratchet-common';\nimport { Logger } from '@bitblit/ratchet-common';\nimport { RequireRatchet } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { DateTime } from 'luxon';\nimport { ContextUtil } from '../../util/context-util.js';\nexport class AbstractBackgroundManager {\n createEntry(type, data) {\n const rval = {\n type: type,\n data: data,\n };\n return rval;\n }\n wrapEntryForInternal(entry, overrideTraceId, overrideTraceDepth) {\n const rval = Object.assign({}, entry, {\n createdEpochMS: new Date().getTime(),\n guid: AbstractBackgroundManager.generateBackgroundGuid(),\n traceId: overrideTraceId || ContextUtil.currentTraceId(),\n traceDepth: overrideTraceDepth || ContextUtil.currentTraceDepth() + 1,\n });\n return rval;\n }\n async addEntryToQueueByParts(type, data, fireStartMessage) {\n let rval = null;\n const entry = this.createEntry(type, data);\n if (entry) {\n rval = await this.addEntryToQueue(entry, fireStartMessage);\n }\n return rval;\n }\n async addEntriesToQueue(entries, fireStartMessage) {\n const rval = [];\n for (let i = 0; i < entries.length; i++) {\n try {\n const tmp = await this.addEntryToQueue(entries[i], false);\n rval.push(tmp);\n }\n catch (err) {\n Logger.error('Error processing %j : %s', entries[i], err);\n rval.push(err['message']);\n }\n if (fireStartMessage) {\n const fireResult = await this.fireStartProcessingRequest();\n Logger.silly('FireResult : %s', fireResult);\n }\n }\n return rval;\n }\n async fireImmediateProcessRequestByParts(type, data) {\n let rval = null;\n const entry = this.createEntry(type, data);\n if (entry) {\n rval = await this.fireImmediateProcessRequest(entry);\n }\n return rval;\n }\n static generateBackgroundGuid(targetEpochMS = new Date().getTime()) {\n const dt = DateTime.fromMillis(targetEpochMS);\n return dt.toFormat('yyyy-MM-dd-HH-mm-ss-') + StringRatchet.createType4Guid();\n }\n static backgroundGuidToPath(prefix, guid) {\n let path = StringRatchet.trimToEmpty(prefix);\n if (path.length && !path.endsWith('/')) {\n path += '/';\n }\n path += guid.substring(0, 4) + '/' + guid.substring(5, 7) + '/' + guid.substring(8, 10) + '/';\n path += guid + '.json';\n return path;\n }\n static pathToBackgroundGuid(prefix, path) {\n RequireRatchet.notNullOrUndefined(path, 'path');\n let start = 0;\n if (!path.endsWith('.json')) {\n ErrorRatchet.throwFormattedErr('Cannot extract guid, does not end with .json : %s : %s', path, prefix);\n }\n if (StringRatchet.trimToNull(prefix)) {\n if (!path.startsWith(prefix)) {\n ErrorRatchet.throwFormattedErr('Cannot extract guid, does not start with prefix : %s : %s', path, prefix);\n }\n start = prefix.length;\n if (!prefix.endsWith('/')) {\n start++;\n }\n }\n start += 11;\n return path.substring(start, path.length - 5);\n }\n}\n//# sourceMappingURL=abstract-background-manager.js.map","import { ErrorRatchet } from '@bitblit/ratchet-common';\nimport { Logger } from '@bitblit/ratchet-common';\nimport { LambdaEventDetector } from '@bitblit/ratchet-aws';\nimport { EpsilonConstants } from '../epsilon-constants.js';\nimport { BackgroundValidator } from './background-validator.js';\nimport { BackgroundExecutionEventType } from './background-execution-event-type.js';\nimport { ContextUtil } from '../util/context-util.js';\nimport { AbstractBackgroundManager } from './manager/abstract-background-manager.js';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { StopWatch } from '@bitblit/ratchet-common';\nexport class BackgroundHandler {\n cfg;\n mgr;\n modelValidator;\n processors;\n validator;\n constructor(cfg, mgr, modelValidator) {\n this.cfg = cfg;\n this.mgr = mgr;\n this.modelValidator = modelValidator;\n const cfgErrors = BackgroundValidator.validateConfig(cfg);\n if (cfgErrors.length > 0) {\n ErrorRatchet.throwFormattedErr('Invalid background config : %j', cfgErrors);\n }\n Logger.silly('Starting Background processor, %d processors', cfg.processors.length);\n this.validator = new BackgroundValidator(cfg, modelValidator);\n this.processors = BackgroundValidator.validateAndMapProcessors(cfg.processors, modelValidator);\n if (mgr?.immediateProcessQueue && mgr.immediateProcessQueue()) {\n Logger.info('Attaching to immediate processing queue');\n mgr.immediateProcessQueue().subscribe(async (evt) => {\n Logger.debug('Processing local background entry : %j', evt);\n const rval = await this.processSingleBackgroundEntry(evt);\n Logger.info('Processor returned %s', rval);\n });\n }\n }\n extractLabel(evt, context) {\n let rval = null;\n if (this.isBackgroundStartSnsEvent(evt)) {\n rval = 'BG:START-EVT';\n }\n else if (this.isBackgroundImmediateFireEvent(evt)) {\n const pEvt = this.parseImmediateFireBackgroundEntry(evt);\n rval = 'BG:' + pEvt.type + ':' + pEvt.guid;\n }\n else {\n rval = 'BG:UNKNOWN';\n }\n return rval;\n }\n handlesEvent(evt) {\n return LambdaEventDetector.isValidSnsEvent(evt) && this.isBackgroundSNSEvent(evt);\n }\n isBackgroundSNSEvent(event) {\n return this.isBackgroundStartSnsEvent(event) || this.isBackgroundImmediateFireEvent(event);\n }\n isBackgroundStartSnsEvent(event) {\n let rval = false;\n if (event) {\n if (LambdaEventDetector.isSingleSnsEvent(event)) {\n const cast = event;\n rval = cast.Records[0].Sns.Message === EpsilonConstants.BACKGROUND_SNS_START_MARKER;\n }\n }\n return rval;\n }\n isBackgroundImmediateFireEvent(event) {\n let rval = false;\n if (!!event) {\n if (LambdaEventDetector.isSingleSnsEvent(event)) {\n const cast = event;\n const msg = cast.Records[0].Sns.Message;\n if (!!StringRatchet.trimToNull(msg)) {\n const parsed = JSON.parse(msg);\n rval = !!parsed && parsed['type'] === EpsilonConstants.BACKGROUND_SNS_IMMEDIATE_RUN_FLAG;\n }\n }\n }\n return rval;\n }\n parseImmediateFireBackgroundEntry(event) {\n let rval = null;\n try {\n if (!!event) {\n if (LambdaEventDetector.isSingleSnsEvent(event)) {\n const cast = event;\n const msg = cast.Records[0].Sns.Message;\n if (!!StringRatchet.trimToNull(msg)) {\n const parsed = JSON.parse(msg);\n if (!!parsed && parsed['type'] === EpsilonConstants.BACKGROUND_SNS_IMMEDIATE_RUN_FLAG) {\n rval = parsed['backgroundEntry'];\n }\n }\n }\n }\n }\n catch (err) {\n Logger.error('Could not parse %j as an immediate run event : %s', event, err, err);\n }\n return rval;\n }\n async processEvent(event, context) {\n let procd = null;\n if (!this.isBackgroundStartSnsEvent(event)) {\n const backgroundEntry = this.parseImmediateFireBackgroundEntry(event);\n if (!!backgroundEntry) {\n Logger.silly('Processing immediate fire event : %j', backgroundEntry);\n const result = await this.processSingleBackgroundEntry(backgroundEntry);\n procd = 1;\n }\n else {\n Logger.warn('Tried to process non-background start / immediate event : %j returning false', event);\n }\n }\n else {\n Logger.info('Reading task from background queue');\n procd = await this.takeAndProcessSingleBackgroundQueueEntry();\n if (procd > 0) {\n Logger.info('Processed %d elements from background queue, refiring', procd);\n const refire = await this.mgr.fireStartProcessingRequest();\n Logger.info('Refire returned %s', refire);\n }\n else {\n Logger.info('No items processed - stopping');\n }\n }\n const rval = {\n statusCode: 200,\n body: StringRatchet.safeString(procd),\n isBase64Encoded: false,\n };\n return rval;\n }\n async takeAndProcessSingleBackgroundQueueEntry() {\n let rval = null;\n const entries = await this.mgr.takeEntryFromBackgroundQueue();\n Logger.info('Found %d entries - processing', entries.length);\n for (let i = 0; i < entries.length; i++) {\n const e = entries[i];\n const result = await this.processSingleBackgroundEntry(e);\n rval += result ? 1 : 0;\n }\n Logger.debug('Returning %d', rval);\n return rval;\n }\n async safeWriteToLogger(entry) {\n if (this.cfg.transactionLogger) {\n try {\n await this.cfg.transactionLogger.logTransaction(entry);\n }\n catch (err) {\n Logger.error('Failed to write to transaction logger : %j : %s', entry, err, err);\n }\n }\n else {\n Logger.silly('Skipping - no logger defined');\n }\n }\n async conditionallyStartTransactionLog(e) {\n if (!StringRatchet.trimToNull(e.guid)) {\n Logger.warn('No guid found - creating');\n e.guid = AbstractBackgroundManager.generateBackgroundGuid();\n const log = {\n request: e,\n running: true,\n };\n await this.safeWriteToLogger(log);\n }\n Logger.debug('Starting transaction log');\n }\n async conditionallyCompleteTransactionLog(e, result, error, runtimeMS) {\n Logger.debug('Completing transaction log');\n const log = {\n request: e,\n result: result,\n error: error ? ErrorRatchet.safeStringifyErr(error) : null,\n running: false,\n runtimeMS: runtimeMS,\n };\n await this.safeWriteToLogger(log);\n }\n async conditionallyRunErrorProcessor(e, error) {\n try {\n if (this.cfg.errorProcessor) {\n Logger.info('Running error processor');\n await this.cfg.errorProcessor.handleError(e, error);\n }\n }\n catch (err) {\n Logger.error('Background : BAD - Failed to run error processor : %s', err, err);\n }\n }\n async fireListenerEvent(event) {\n const listeners = this.cfg.executionListeners || [];\n for (const listener of listeners) {\n try {\n await listener.onEvent(event);\n }\n catch (err) {\n Logger.error('Failure triggering handler %s : %s', StringRatchet.trimToNull(listener?.label) || 'No-name', err);\n }\n }\n }\n async processSingleBackgroundEntry(e) {\n ContextUtil.setOverrideTraceFromInternalBackgroundEntry(e);\n Logger.info('Background Process Start: %j', e);\n const sw = new StopWatch();\n await this.conditionallyStartTransactionLog(e);\n let rval = false;\n try {\n await this.fireListenerEvent({\n type: BackgroundExecutionEventType.ProcessStarting,\n processorType: e.type,\n data: e.data,\n guid: e.guid,\n });\n const processorInput = this.processors.get(e.type);\n if (!processorInput) {\n ErrorRatchet.throwFormattedErr('Found no processor for background entry : %j (returning false)', e);\n await this.fireListenerEvent({\n type: BackgroundExecutionEventType.NoMatchProcessorName,\n processorType: e.type,\n data: e.data,\n guid: e.guid,\n });\n }\n let dataValidationErrors = [];\n if (StringRatchet.trimToNull(processorInput.dataSchemaName)) {\n dataValidationErrors = this.modelValidator.validate(processorInput.dataSchemaName, e.data, false, false);\n }\n if (dataValidationErrors.length > 0) {\n await this.fireListenerEvent({\n type: BackgroundExecutionEventType.DataValidationError,\n processorType: e.type,\n data: e.data,\n errors: dataValidationErrors,\n guid: e.guid,\n });\n ErrorRatchet.throwFormattedErr('Not processing, data failed validation; entry was %j : errors : %j', e, dataValidationErrors);\n }\n else {\n let result = await processorInput.handleEvent(e.data, this.mgr);\n result = result || 'SUCCESSFUL COMPLETION : NO RESULT RETURNED';\n await this.conditionallyCompleteTransactionLog(e, result, null, sw.elapsedMS());\n await this.fireListenerEvent({\n type: BackgroundExecutionEventType.ExecutionSuccessfullyComplete,\n processorType: e.type,\n data: result,\n guid: e.guid,\n });\n rval = true;\n }\n }\n catch (err) {\n Logger.error('Background Process Error: %j : %s', e, err, err);\n await this.conditionallyRunErrorProcessor(e, err);\n await this.conditionallyCompleteTransactionLog(e, null, err, sw.elapsedMS());\n await this.fireListenerEvent({\n type: BackgroundExecutionEventType.ExecutionFailedError,\n processorType: e.type,\n data: e.data,\n errors: [ErrorRatchet.safeStringifyErr(err)],\n guid: e.guid,\n });\n }\n Logger.info('Background Process Stop: %j : %s', e, sw.dump());\n return rval;\n }\n getConfig() {\n const rval = Object.assign({}, this.cfg);\n return rval;\n }\n}\n//# sourceMappingURL=background-handler.js.map","import { Logger, MapRatchet, StringRatchet, RestfulApiHttpError } from '@bitblit/ratchet-common';\nimport { EventUtil } from '../../http/event-util.js';\nimport { BadRequestError } from '../../http/error/bad-request-error.js';\nimport { ResponseUtil } from '../../http/response-util.js';\nimport { MisconfiguredError } from '../../http/error/misconfigured-error.js';\nexport class BuiltInFilters {\n static MAXIMUM_LAMBDA_BODY_SIZE_BYTES = 1024 * 1024 * 5 - 1024 * 100;\n static async combineFilters(fCtx, filters) {\n let cont = true;\n if (filters && filters.length > 0) {\n for (let i = 0; i < filters.length && cont; i++) {\n cont = await filters[i](fCtx);\n }\n }\n return cont;\n }\n static async applyGzipIfPossible(fCtx) {\n if (fCtx.event?.headers && fCtx.result) {\n const encodingHeader = fCtx.event && fCtx.event.headers ? MapRatchet.extractValueFromMapIgnoreCase(fCtx.event.headers, 'accept-encoding') : null;\n fCtx.result = await ResponseUtil.applyGzipIfPossible(encodingHeader, fCtx.result);\n }\n return true;\n }\n static async addConstantHeaders(fCtx, headers) {\n if (headers && fCtx.result) {\n fCtx.result.headers = Object.assign({}, headers, fCtx.result.headers);\n }\n else {\n Logger.warn('Could not add headers - either result or headers were missing');\n }\n return true;\n }\n static async addAWSRequestIdHeader(fCtx, headerName = 'X-REQUEST-ID') {\n if (fCtx.result && StringRatchet.trimToNull(headerName) && headerName.startsWith('X-')) {\n fCtx.result.headers = fCtx.result.headers || {};\n fCtx.result.headers[headerName] = fCtx.context?.awsRequestId || 'Request-Id-Missing';\n }\n else {\n Logger.warn('Could not add request id header - either result or context were missing or name was invalid');\n }\n return true;\n }\n static async addAllowEverythingCORSHeaders(fCtx) {\n return BuiltInFilters.addConstantHeaders(fCtx, {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': '*',\n 'Access-Control-Allow-Headers': '*',\n });\n }\n static async addAllowReflectionCORSHeaders(fCtx) {\n return BuiltInFilters.addConstantHeaders(fCtx, {\n 'Access-Control-Allow-Origin': MapRatchet.caseInsensitiveAccess(fCtx.event.headers, 'Origin') || '*',\n 'Access-Control-Allow-Methods': MapRatchet.caseInsensitiveAccess(fCtx.event.headers, 'Access-Control-Request-Method') || '*',\n 'Access-Control-Allow-Headers': MapRatchet.caseInsensitiveAccess(fCtx.event.headers, 'Access-Control-Request-Headers') || '*',\n });\n }\n static async uriDecodeQueryParams(fCtx) {\n if (fCtx?.event?.queryStringParameters) {\n Object.keys(fCtx.event.queryStringParameters).forEach((k) => {\n const val = fCtx.event.queryStringParameters[k];\n if (val) {\n fCtx.event.queryStringParameters[k] = decodeURIComponent(val);\n }\n });\n }\n if (fCtx?.event?.multiValueQueryStringParameters) {\n Object.keys(fCtx.event.multiValueQueryStringParameters).forEach((k) => {\n const val = fCtx.event.multiValueQueryStringParameters[k];\n if (val && val.length) {\n const cleaned = val.map((v) => decodeURIComponent(v));\n fCtx.event.multiValueQueryStringParameters[k] = cleaned;\n }\n });\n }\n return true;\n }\n static async fixStillEncodedQueryParams(fCtx) {\n EventUtil.fixStillEncodedQueryParams(fCtx.event);\n return true;\n }\n static async disallowStringNullAsPathParameter(fCtx) {\n if (fCtx?.event?.pathParameters) {\n Object.keys(fCtx.event.pathParameters).forEach((k) => {\n if ('null' === StringRatchet.trimToEmpty(fCtx.event.pathParameters[k]).toLowerCase()) {\n throw new BadRequestError().withFormattedErrorMessage('Path parameter %s was string -null-', k);\n }\n });\n }\n return true;\n }\n static async disallowStringNullAsQueryStringParameter(fCtx) {\n if (fCtx?.event?.queryStringParameters) {\n Object.keys(fCtx.event.queryStringParameters).forEach((k) => {\n if ('null' === StringRatchet.trimToEmpty(fCtx.event.queryStringParameters[k]).toLowerCase()) {\n throw new BadRequestError().withFormattedErrorMessage('Query parameter %s was string -null-', k);\n }\n });\n }\n return true;\n }\n static async ensureEventMaps(fCtx) {\n fCtx.event.queryStringParameters = fCtx.event.queryStringParameters || {};\n fCtx.event.headers = fCtx.event.headers || {};\n fCtx.event.pathParameters = fCtx.event.pathParameters || {};\n return true;\n }\n static async parseJsonBodyToObject(fCtx) {\n if (fCtx.event?.body) {\n try {\n fCtx.event.parsedBody = EventUtil.jsonBodyToObject(fCtx.event);\n }\n catch (err) {\n throw new RestfulApiHttpError('Supplied body was not parsable as valid JSON').withHttpStatusCode(400);\n }\n }\n return true;\n }\n static async checkMaximumLambdaBodySize(fCtx) {\n if (fCtx.result?.body && fCtx.result.body.length > BuiltInFilters.MAXIMUM_LAMBDA_BODY_SIZE_BYTES) {\n const delta = fCtx.result.body.length - BuiltInFilters.MAXIMUM_LAMBDA_BODY_SIZE_BYTES;\n throw new RestfulApiHttpError('Response size is ' + fCtx.result.body.length + ' bytes, which is ' + delta + ' bytes too large for this handler').withHttpStatusCode(500);\n }\n return true;\n }\n static async validateInboundBody(fCtx) {\n if (fCtx?.event?.parsedBody && fCtx.routeAndParse) {\n if (fCtx.routeAndParse.mapping.validation) {\n if (!fCtx.modelValidator) {\n throw new MisconfiguredError('Requested body validation but supplied no validator');\n }\n const errors = fCtx.modelValidator.validate(fCtx.routeAndParse.mapping.validation.modelName, fCtx.event.parsedBody, fCtx.routeAndParse.mapping.validation.emptyAllowed, fCtx.routeAndParse.mapping.validation.extraPropertiesAllowed);\n if (errors.length > 0) {\n Logger.info('Found errors while validating %s object %j', fCtx.routeAndParse.mapping.validation.modelName, errors);\n const newError = new BadRequestError(...errors);\n throw newError;\n }\n }\n }\n else {\n Logger.debug('No validation since no route specified or no parsed body');\n }\n return true;\n }\n static async validateInboundQueryParams(fCtx) {\n return true;\n }\n static async validateInboundPathParams(fCtx) {\n return true;\n }\n static async validateOutboundResponse(fCtx) {\n if (fCtx?.rawResult) {\n if (fCtx.routeAndParse.mapping.outboundValidation) {\n Logger.debug('Applying outbound check to %j', fCtx.rawResult);\n const errors = fCtx.modelValidator.validate(fCtx.routeAndParse.mapping.outboundValidation.modelName, fCtx.rawResult, fCtx.routeAndParse.mapping.outboundValidation.emptyAllowed, fCtx.routeAndParse.mapping.outboundValidation.extraPropertiesAllowed);\n if (errors.length > 0) {\n Logger.error('Found outbound errors while validating %s object %j', fCtx.routeAndParse.mapping.outboundValidation.modelName, errors);\n errors.unshift('Server sent object invalid according to spec');\n throw new RestfulApiHttpError().withErrors(errors).withHttpStatusCode(500).withDetails(fCtx.rawResult);\n }\n }\n else {\n Logger.debug('Applied no outbound validation because none set');\n }\n }\n else {\n Logger.debug('No validation since no outbound body or disabled');\n }\n return true;\n }\n static async autoRespondToOptionsRequestWithCors(fCtx) {\n if (StringRatchet.trimToEmpty(fCtx?.event?.httpMethod).toLowerCase() === 'options') {\n fCtx.result = {\n statusCode: 200,\n body: '{\"cors\":true, \"m\":2}',\n };\n await BuiltInFilters.addAllowReflectionCORSHeaders(fCtx);\n return false;\n }\n else {\n return true;\n }\n }\n static async autoRespond(fCtx, inBody) {\n const body = inBody || {\n message: 'Not Implemented',\n };\n fCtx.result = {\n statusCode: 200,\n body: JSON.stringify(body),\n };\n return false;\n }\n static async secureOutboundServerErrorForProduction(fCtx, errorMessage, errCode) {\n if (fCtx?.result?.statusCode) {\n if (errCode === null || fCtx.result.statusCode === errCode) {\n Logger.warn('Securing outbound error info (was : %j)', fCtx.result.body);\n fCtx.rawResult = new RestfulApiHttpError(errorMessage).withHttpStatusCode(fCtx.result.statusCode);\n const oldResult = fCtx.result;\n fCtx.result = ResponseUtil.errorResponse(fCtx.rawResult);\n fCtx.result.headers = Object.assign({}, oldResult.headers || {}, fCtx.result.headers || {});\n }\n }\n return true;\n }\n}\n//# sourceMappingURL=built-in-filters.js.map","import { StringRatchet } from '@bitblit/ratchet-common';\nimport { UnauthorizedError } from '../../http/error/unauthorized-error.js';\nimport { MisconfiguredError } from '../../http/error/misconfigured-error.js';\nimport { ForbiddenError } from '../../http/error/forbidden-error.js';\nimport { EventUtil } from '../../http/event-util.js';\nexport class BuiltInAuthFilters {\n static async requireAllRolesInCommonJwt(fCtx, requiredRoleAllOf) {\n if (!requiredRoleAllOf || requiredRoleAllOf.length === 0) {\n throw new MisconfiguredError('You must require at least 1 role');\n }\n if (!fCtx.event?.authorization?.auth) {\n throw new UnauthorizedError('May not proceed, not authenticated');\n }\n else {\n const asJwt = fCtx.event.authorization.auth;\n if (!asJwt.roles || asJwt.roles.length === 0) {\n throw new UnauthorizedError('Required role not found');\n }\n else {\n requiredRoleAllOf.forEach((r) => {\n if (!asJwt.roles.includes(r)) {\n throw new UnauthorizedError('Required role not found');\n }\n });\n }\n }\n return true;\n }\n static async requireAnyRoleInCommonJwt(fCtx, requiredRoleOneOf) {\n if (!requiredRoleOneOf || requiredRoleOneOf.length === 0) {\n throw new MisconfiguredError('You must require at least 1 role');\n }\n if (!fCtx.event?.authorization?.auth) {\n throw new UnauthorizedError('May not proceed, not authenticated');\n }\n else {\n const asJwt = fCtx.event.authorization.auth;\n if (!asJwt.roles || asJwt.roles.length === 0) {\n throw new UnauthorizedError('Required role not found');\n }\n else {\n let found = false;\n requiredRoleOneOf.forEach((r) => {\n if (!found && asJwt.roles.includes(r)) {\n found = true;\n }\n });\n if (!found) {\n throw new UnauthorizedError('Required role not found');\n }\n }\n }\n return true;\n }\n static async parseAuthorizationHeader(fCtx, webTokenManipulators) {\n if (!fCtx?.event || !webTokenManipulators || (Array.isArray(webTokenManipulators) && !webTokenManipulators.length)) {\n throw new MisconfiguredError('Cannot continue - missing event or encryption');\n }\n else {\n const tokenString = EventUtil.extractBearerTokenFromEvent(fCtx?.event);\n if (!Array.isArray(webTokenManipulators)) {\n webTokenManipulators = [webTokenManipulators];\n }\n for (let i = 0; i < webTokenManipulators.length && !fCtx?.event?.authorization?.auth; i++) {\n const manipulator = webTokenManipulators[i];\n try {\n const token = await manipulator.extractTokenFromAuthorizationHeader(tokenString);\n fCtx.event.authorization = {\n raw: tokenString,\n auth: token,\n error: null,\n };\n }\n catch (err) {\n fCtx.event.authorization = {\n raw: tokenString,\n auth: null,\n error: err['message'],\n };\n }\n }\n }\n return true;\n }\n static async applyOpenApiAuthorization(fCtx) {\n if (StringRatchet.trimToNull(fCtx?.routeAndParse?.mapping?.authorizerName)) {\n const authorizer = fCtx?.authenticators?.get(fCtx.routeAndParse.mapping.authorizerName);\n if (authorizer) {\n if (fCtx?.event?.authorization?.auth) {\n const allowed = await authorizer(fCtx.event.authorization, fCtx.event, fCtx.routeAndParse.mapping);\n if (!allowed) {\n throw new ForbiddenError('You lack privileges to see this endpoint');\n }\n }\n else {\n throw new UnauthorizedError('You need to supply credentials for this endpoint');\n }\n }\n else {\n throw new MisconfiguredError().withFormattedErrorMessage('Authorizer %s requested but not found', fCtx.routeAndParse.mapping.authorizerName);\n }\n }\n else {\n }\n return true;\n }\n}\n//# sourceMappingURL=built-in-auth-filters.js.map","import { Logger } from '@bitblit/ratchet-common';\nexport class LogLevelManipulationFilter {\n static LOG_LEVEL_BEFORE_CHANGE = null;\n static async setLogLevelForTransaction(fCtx) {\n LogLevelManipulationFilter.LOG_LEVEL_BEFORE_CHANGE = Logger.getLevel();\n return true;\n }\n static async clearLogLevelForTransaction(fCtx) {\n if (LogLevelManipulationFilter.LOG_LEVEL_BEFORE_CHANGE) {\n Logger.setLevel(LogLevelManipulationFilter.LOG_LEVEL_BEFORE_CHANGE);\n LogLevelManipulationFilter.LOG_LEVEL_BEFORE_CHANGE = null;\n Logger.updateTracePrefix(null);\n }\n return true;\n }\n}\n//# sourceMappingURL=log-level-manipulation-filter.js.map","import { MisconfiguredError } from '../error/misconfigured-error.js';\nimport { Logger } from '@bitblit/ratchet-common';\nimport { BooleanRatchet } from '@bitblit/ratchet-common';\nimport { NullReturnedObjectHandling } from '../../config/http/null-returned-object-handling.js';\nimport { BuiltInFilters } from '../../built-in/http/built-in-filters.js';\nimport { BuiltInHandlers } from '../../built-in/http/built-in-handlers.js';\nimport { BuiltInAuthFilters } from '../../built-in/http/built-in-auth-filters.js';\nimport { LogLevelManipulationFilter } from '../../built-in/http/log-level-manipulation-filter.js';\nexport class RouterUtil {\n constructor() { }\n static defaultAuthenticationHeaderParsingEpsilonPreFilters(webTokenManipulator) {\n return [\n (fCtx) => BuiltInAuthFilters.parseAuthorizationHeader(fCtx, webTokenManipulator),\n (fCtx) => BuiltInAuthFilters.applyOpenApiAuthorization(fCtx),\n ].concat(RouterUtil.defaultEpsilonPreFilters());\n }\n static defaultEpsilonPreFilters() {\n return [\n (fCtx) => BuiltInFilters.autoRespondToOptionsRequestWithCors(fCtx),\n (fCtx) => BuiltInFilters.ensureEventMaps(fCtx),\n (fCtx) => LogLevelManipulationFilter.setLogLevelForTransaction(fCtx),\n (fCtx) => BuiltInFilters.parseJsonBodyToObject(fCtx),\n (fCtx) => BuiltInFilters.fixStillEncodedQueryParams(fCtx),\n (fCtx) => BuiltInFilters.uriDecodeQueryParams(fCtx),\n (fCtx) => BuiltInFilters.disallowStringNullAsPathParameter(fCtx),\n (fCtx) => BuiltInFilters.disallowStringNullAsQueryStringParameter(fCtx),\n (fCtx) => BuiltInFilters.validateInboundBody(fCtx),\n (fCtx) => BuiltInFilters.validateInboundQueryParams(fCtx),\n (fCtx) => BuiltInFilters.validateInboundQueryParams(fCtx),\n ];\n }\n static defaultEpsilonPostFilters() {\n return [\n (fCtx) => BuiltInFilters.validateOutboundResponse(fCtx),\n (fCtx) => BuiltInFilters.addAWSRequestIdHeader(fCtx),\n (fCtx) => BuiltInFilters.addAllowReflectionCORSHeaders(fCtx),\n (fCtx) => BuiltInFilters.applyGzipIfPossible(fCtx),\n (fCtx) => BuiltInFilters.checkMaximumLambdaBodySize(fCtx),\n (fCtx) => LogLevelManipulationFilter.clearLogLevelForTransaction(fCtx),\n ];\n }\n static defaultEpsilonErrorFilters() {\n return [\n (fCtx) => BuiltInFilters.addAWSRequestIdHeader(fCtx),\n (fCtx) => BuiltInFilters.addAllowReflectionCORSHeaders(fCtx),\n (fCtx) => LogLevelManipulationFilter.clearLogLevelForTransaction(fCtx),\n ];\n }\n static defaultHttpMetaProcessingConfigWithAuthenticationHeaderParsing(webTokenManipulator) {\n const defaults = {\n configName: 'EpsilonDefaultHttpMetaProcessingConfig',\n timeoutMS: 30_000,\n overrideAuthorizerName: null,\n preFilters: RouterUtil.defaultAuthenticationHeaderParsingEpsilonPreFilters(webTokenManipulator),\n postFilters: RouterUtil.defaultEpsilonPostFilters(),\n errorFilters: RouterUtil.defaultEpsilonErrorFilters(),\n nullReturnedObjectHandling: NullReturnedObjectHandling.Return404NotFoundResponse,\n };\n return defaults;\n }\n static defaultHttpMetaProcessingConfig() {\n const defaults = {\n configName: 'EpsilonDefaultHttpMetaProcessingConfig',\n timeoutMS: 30_000,\n overrideAuthorizerName: null,\n preFilters: RouterUtil.defaultEpsilonPreFilters(),\n postFilters: RouterUtil.defaultEpsilonPostFilters(),\n errorFilters: RouterUtil.defaultEpsilonErrorFilters(),\n nullReturnedObjectHandling: NullReturnedObjectHandling.Return404NotFoundResponse,\n };\n return defaults;\n }\n static assignDefaultsOnHttpConfig(cfg) {\n const defaults = {\n handlers: new Map(),\n authorizers: new Map(),\n defaultMetaHandling: this.defaultHttpMetaProcessingConfig(),\n staticContentRoutes: {},\n prefixesToStripBeforeRouteMatch: [],\n filterHandledRouteMatches: ['options .*'],\n };\n const rval = Object.assign({}, defaults, cfg || {});\n return rval;\n }\n static findApplicableMeta(httpConfig, method, path) {\n let rval = null;\n if (httpConfig?.overrideMetaHandling) {\n for (let i = 0; i < httpConfig.overrideMetaHandling.length && !rval; i++) {\n const test = httpConfig.overrideMetaHandling[i];\n if (!test.methods ||\n test.methods.length === 0 ||\n test.methods.map((s) => s.toLocaleLowerCase()).includes(method.toLocaleLowerCase())) {\n const matches = !!path.match(test.pathRegex);\n if ((matches && !test.invertPathMatching) || (!matches && test.invertPathMatching)) {\n rval = test.config;\n }\n }\n }\n }\n if (!rval) {\n rval = httpConfig.defaultMetaHandling || RouterUtil.defaultHttpMetaProcessingConfig();\n }\n return rval;\n }\n static openApiYamlToRouterConfig(httpConfig, openApiDoc, modelValidator, backgroundHttpAdapterHandler) {\n if (!openApiDoc || !httpConfig) {\n throw new MisconfiguredError('Cannot configure, missing either yaml or cfg');\n }\n const rval = {\n routes: [],\n openApiModelValidator: modelValidator,\n config: RouterUtil.assignDefaultsOnHttpConfig(httpConfig),\n };\n if (openApiDoc?.components?.securitySchemes) {\n Object.keys(openApiDoc.components.securitySchemes).forEach((sk) => {\n if (!rval.config.authorizers || !rval.config.authorizers.get(sk)) {\n throw new MisconfiguredError().withFormattedErrorMessage('Doc requires authorizer %s but not found in map', sk);\n }\n });\n }\n const missingPaths = [];\n const filterHandledPathMatches = httpConfig.filterHandledRouteMatches || [];\n if (openApiDoc?.paths) {\n Object.keys(openApiDoc.paths).forEach((path) => {\n Object.keys(openApiDoc.paths[path]).forEach((method) => {\n const convertedPath = RouterUtil.openApiPathToRouteParserPath(path);\n const finder = method + ' ' + path;\n const applicableMeta = RouterUtil.findApplicableMeta(httpConfig, method, path);\n const entry = openApiDoc.paths[path][method];\n const isBackgroundEndpoint = path.startsWith(backgroundHttpAdapterHandler.httpSubmissionPath);\n const isBackgroundMetaEndpoint = path === backgroundHttpAdapterHandler.httpMetaEndpoint;\n const isBackgroundStatusEndpoint = path === backgroundHttpAdapterHandler.httpStatusPath;\n if (isBackgroundEndpoint) {\n rval.config.handlers.set(finder, (evt, ctx) => backgroundHttpAdapterHandler.handleBackgroundSubmission(evt, ctx));\n }\n if (isBackgroundMetaEndpoint) {\n rval.config.handlers.set(finder, (evt, ctx) => backgroundHttpAdapterHandler.handleBackgroundMetaRequest(evt, ctx));\n }\n if (isBackgroundStatusEndpoint) {\n rval.config.handlers.set(finder, (evt, ctx) => backgroundHttpAdapterHandler.handleBackgroundStatusRequest(evt, ctx));\n }\n if (!rval.config.handlers || !rval.config.handlers.get(finder)) {\n const match = filterHandledPathMatches.find((reg) => finder.match(reg));\n if (match) {\n Logger.debug('Adding filter-handled handler for %s', finder);\n rval.config.handlers.set(finder, (evt) => BuiltInHandlers.expectedHandledByFilter(evt));\n }\n else {\n missingPaths.push(finder);\n }\n }\n if (entry && entry['security'] && entry['security'].length > 1) {\n throw new MisconfiguredError('Epsilon does not currently support multiple security (path was ' + finder + ')');\n }\n const authorizerName = entry['security'] && entry['security'].length == 1 ? Object.keys(entry['security'][0])[0] : null;\n const newRoute = {\n path: convertedPath,\n method: method,\n function: rval.config.handlers.get(finder),\n authorizerName: applicableMeta.overrideAuthorizerName || authorizerName,\n metaProcessingConfig: applicableMeta,\n validation: null,\n outboundValidation: null,\n };\n if (entry['requestBody'] &&\n entry['requestBody']['content'] &&\n entry['requestBody']['content']['application/json'] &&\n entry['requestBody']['content']['application/json']['schema']) {\n const schema = entry['requestBody']['content'];\n Logger.silly('Applying schema %j to %s', schema, finder);\n const modelName = this.findAndValidateModelName(method, path, schema, rval.config.overrideModelValidator || rval.openApiModelValidator);\n const required = BooleanRatchet.parseBool(entry['requestBody']['required']);\n const validation = {\n extraPropertiesAllowed: true,\n emptyAllowed: !required,\n modelName: modelName,\n };\n newRoute.validation = validation;\n }\n if (entry['responses'] &&\n entry['responses']['200'] &&\n entry['responses']['200']['content'] &&\n entry['responses']['200']['content']['application/json'] &&\n entry['responses']['200']['content']['application/json']['schema']) {\n const schema = entry['responses']['200']['content'];\n Logger.silly('Applying schema %j to %s', schema, finder);\n const modelName = this.findAndValidateModelName(method, path, schema, rval.config.overrideModelValidator || rval.openApiModelValidator);\n const validation = {\n extraPropertiesAllowed: false,\n emptyAllowed: false,\n modelName: modelName,\n };\n newRoute.outboundValidation = validation;\n }\n rval.routes.push(newRoute);\n });\n });\n }\n if (missingPaths.length > 0) {\n throw new MisconfiguredError().withFormattedErrorMessage('Missing expected handlers : %j', missingPaths);\n }\n return rval;\n }\n static findAndValidateModelName(method, path, schema, modelValidator) {\n let rval = undefined;\n const schemaPath = schema['application/json']['schema']['$ref'];\n const inlinePath = schema['application/json']['schema']['type'];\n if (schemaPath) {\n rval = schemaPath.substring(schemaPath.lastIndexOf('/') + 1);\n if (!modelValidator.fetchModel(rval)) {\n throw new MisconfiguredError(`Path ${method} ${path} refers to schema ${rval} but its not in the schema section`);\n }\n }\n else if (inlinePath) {\n rval = `${method}-${path}-requestBodyModel`;\n const model = schema['application/json']['schema'];\n modelValidator.addModel(rval, model);\n }\n return rval;\n }\n static openApiPathToRouteParserPath(input) {\n let rval = input;\n if (rval) {\n let sIdx = rval.indexOf('{');\n while (sIdx > -1) {\n const eIdx = rval.indexOf('}');\n rval = rval.substring(0, sIdx) + ':' + rval.substring(sIdx + 1, eIdx) + rval.substring(eIdx + 1);\n sIdx = rval.indexOf('{');\n }\n }\n return rval;\n }\n}\n//# sourceMappingURL=router-util.js.map","import { Logger, PromiseRatchet, TimeoutToken, RestfulApiHttpError } from '@bitblit/ratchet-common';\nimport { RequestTimeoutError } from '../../http/error/request-timeout-error.js';\nimport { ResponseUtil } from '../../http/response-util.js';\nimport { NotFoundError } from '../../http/error/not-found-error.js';\nimport { NullReturnedObjectHandling } from '../../config/http/null-returned-object-handling.js';\nexport class RunHandlerAsFilter {\n static async runHandler(fCtx, rm) {\n const handler = RunHandlerAsFilter.findHandler(rm, fCtx.event, fCtx.context);\n Logger.debug('Processing event with epsilon: %j', fCtx.event);\n let tmp = await handler;\n if (TimeoutToken.isTimeoutToken(tmp)) {\n tmp.writeToLog();\n throw new RequestTimeoutError('Timed out');\n }\n Logger.debug('Initial return value : %j', tmp);\n tmp = RunHandlerAsFilter.applyNullReturnedObjectHandling(tmp, rm.mapping.metaProcessingConfig.nullReturnedObjectHandling);\n fCtx.rawResult = tmp;\n fCtx.result = ResponseUtil.coerceToProxyResult(tmp);\n return true;\n }\n static applyNullReturnedObjectHandling(result, handling) {\n let rval = result;\n if (result === null || result === undefined) {\n if (handling === NullReturnedObjectHandling.Error) {\n Logger.error('Null object returned and Error specified, throwing 500');\n throw new RestfulApiHttpError('Null object').withHttpStatusCode(500);\n }\n else if (handling === NullReturnedObjectHandling.Return404NotFoundResponse) {\n throw new NotFoundError('Resource not found');\n }\n else if (handling === NullReturnedObjectHandling.ConvertToEmptyString) {\n Logger.warn('Null object returned from handler and convert not specified, converting to empty string');\n rval = '';\n }\n else {\n throw new RestfulApiHttpError('Cant happen - failed enum check').withHttpStatusCode(500);\n }\n }\n return rval;\n }\n static async findHandler(rm, event, context, add404OnMissing = true) {\n let rval = null;\n if (rm) {\n event.pathParameters = Object.assign({}, event.pathParameters, rm.parsed);\n rval = PromiseRatchet.timeout(rm.mapping.function(event, context), 'Timed out after ' + rm.mapping.metaProcessingConfig.timeoutMS + ' ms. Request was ' + JSON.stringify(event), rm.mapping.metaProcessingConfig.timeoutMS);\n }\n else if (add404OnMissing) {\n throw new NotFoundError('No such endpoint');\n }\n return rval;\n }\n static addRunHandlerAsFilterToList(filters, rm) {\n if (filters) {\n filters.push((fCtx) => RunHandlerAsFilter.runHandler(fCtx, rm));\n }\n }\n}\n//# sourceMappingURL=run-handler-as-filter.js.map","import { Logger, RequireRatchet, StringRatchet, RestfulApiHttpError } from '@bitblit/ratchet-common';\nimport Route from 'route-parser';\nimport { ResponseUtil } from './response-util.js';\nimport { BuiltInFilters } from '../built-in/http/built-in-filters.js';\nimport { RunHandlerAsFilter } from '../built-in/http/run-handler-as-filter.js';\nimport { ContextUtil } from '../util/context-util.js';\nimport { LambdaEventDetector } from '@bitblit/ratchet-aws';\nexport class WebHandler {\n routerConfig;\n static MAXIMUM_LAMBDA_BODY_SIZE_BYTES = 1024 * 1024 * 5 - 1024 * 100;\n constructor(routerConfig) {\n this.routerConfig = routerConfig;\n RequireRatchet.notNullOrUndefined(routerConfig);\n }\n get router() {\n return this.routerConfig;\n }\n extractLabel(evt, context) {\n return 'WEB:' + StringRatchet.trimToEmpty(evt.httpMethod).toUpperCase() + ':' + evt.path;\n }\n handlesEvent(evt) {\n return LambdaEventDetector.isValidApiGatewayEvent(evt);\n }\n async processEvent(event, context) {\n if (!this.routerConfig) {\n throw new Error('Router config not found');\n }\n const asExtended = Object.assign({}, { parsedBody: null, authorization: null, convertedFromV2Event: false }, event);\n const rval = await this.openApiLambdaHandler(asExtended, context);\n ContextUtil.addTraceToProxyResult(rval);\n Logger.updateTracePrefix(null);\n return rval;\n }\n async openApiLambdaHandler(evt, context) {\n const rm = this.findBestMatchingRoute(evt);\n const procConfig = rm?.mapping?.metaProcessingConfig\n ? rm.mapping.metaProcessingConfig\n : this.routerConfig.config.defaultMetaHandling;\n const fCtx = {\n event: evt,\n context: context,\n result: null,\n rawResult: null,\n routeAndParse: rm,\n modelValidator: this.routerConfig.config.overrideModelValidator || this.routerConfig.openApiModelValidator,\n authenticators: this.routerConfig.config.authorizers,\n };\n try {\n let filterChain = Object.assign([], procConfig.preFilters || []);\n RunHandlerAsFilter.addRunHandlerAsFilterToList(filterChain, rm);\n filterChain = filterChain.concat(procConfig.postFilters || []);\n await BuiltInFilters.combineFilters(fCtx, filterChain);\n }\n catch (err) {\n const wrapper = RestfulApiHttpError.wrapError(err);\n fCtx.result = ResponseUtil.errorResponse(wrapper);\n try {\n await BuiltInFilters.combineFilters(fCtx, procConfig.errorFilters);\n }\n catch (convErr) {\n Logger.error('REALLY BAD - FAILED WHILE PROCESSING ERROR FILTERS : %s', convErr);\n }\n }\n return fCtx.result;\n }\n findBestMatchingRoute(event) {\n let rval = null;\n const cleanPath = this.cleanPath(event);\n const methodLower = event.httpMethod.toLowerCase();\n const matchRoutes = this.routerConfig.routes\n .map((r) => {\n let rval = null;\n if (r.method && r.method.toLowerCase() === methodLower) {\n const routeParser = new Route(r.path);\n const parsed = routeParser.match(cleanPath);\n if (parsed !== false) {\n rval = {\n mapping: r,\n route: routeParser,\n parsed: parsed,\n };\n }\n }\n return rval;\n })\n .filter((r) => r != null);\n matchRoutes.sort((a, b) => {\n return Object.keys(a.parsed).length - Object.keys(b.parsed).length;\n });\n rval = matchRoutes && matchRoutes.length > 0 ? matchRoutes[0] : null;\n if (!rval) {\n Logger.debug('Failed to find handler for %s (cleaned path was %s, strip prefixes were %j)', event.path, cleanPath, this.routerConfig.config.prefixesToStripBeforeRouteMatch);\n }\n return rval;\n }\n cleanPath(event) {\n let rval = event.path;\n while (rval.startsWith('/')) {\n rval = rval.substring(1);\n }\n if (this.routerConfig.config.prefixesToStripBeforeRouteMatch) {\n this.routerConfig.config.prefixesToStripBeforeRouteMatch.forEach((prefix) => {\n if (rval.toLowerCase().startsWith(prefix.toLowerCase() + '/')) {\n rval = rval.substring(prefix.length);\n }\n });\n }\n while (rval.startsWith('/')) {\n rval = rval.substring(1);\n }\n rval = '/' + rval;\n return rval;\n }\n}\n//# sourceMappingURL=web-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { ErrorRatchet } from '@bitblit/ratchet-common';\nimport yaml from 'js-yaml';\nimport { ModelValidator } from '@bitblit/ratchet-misc';\nimport { BackgroundHttpAdapterHandler } from '../background/background-http-adapter-handler.js';\nimport { BackgroundHandler } from '../background/background-handler.js';\nimport { RouterUtil } from '../http/route/router-util.js';\nimport { WebHandler } from '../http/web-handler.js';\nimport { MisconfiguredError } from '../http/error/misconfigured-error.js';\nimport { EpsilonGlobalHandler } from '../epsilon-global-handler.js';\nexport class EpsilonConfigParser {\n constructor() { }\n static epsilonConfigToEpsilonGlobalHandler(config, backgroundManager) {\n return new EpsilonGlobalHandler(EpsilonConfigParser.epsilonConfigToEpsilonInstance(config, backgroundManager));\n }\n static epsilonConfigToEpsilonInstance(config, backgroundManager) {\n this.validateGlobalConfig(config);\n const label = config?.label || 'NO EPSILON CONFIG LABEL SET';\n Logger.info('Creating epsilon : %s : BM : %j', label, backgroundManager);\n const parsed = EpsilonConfigParser.parseOpenApiDocument(config.openApiYamlString);\n const modelValidator = EpsilonConfigParser.openApiDocToValidator(parsed);\n const backgroundHttpAdapter = new BackgroundHttpAdapterHandler(config.backgroundConfig, modelValidator, backgroundManager);\n const backgroundHandler = config.backgroundConfig\n ? new BackgroundHandler(config.backgroundConfig, backgroundManager, modelValidator)\n : null;\n const epsilonRouter = config.httpConfig\n ? RouterUtil.openApiYamlToRouterConfig(config.httpConfig, parsed, modelValidator, backgroundHttpAdapter)\n : null;\n const webHandler = epsilonRouter ? new WebHandler(epsilonRouter) : null;\n const inst = {\n config: config,\n parsedOpenApiDoc: parsed,\n modelValidator: modelValidator,\n webHandler: webHandler,\n backgroundHandler: backgroundHandler,\n backgroundManager: backgroundManager,\n };\n return inst;\n }\n static parseOpenApiDocument(yamlString) {\n if (!yamlString) {\n throw new MisconfiguredError('Cannot configure, missing either yaml or cfg');\n }\n const doc = yaml.load(yamlString);\n return doc;\n }\n static openApiDocToValidator(doc) {\n let rval = null;\n if (doc?.components?.schemas) {\n rval = ModelValidator.createFromParsedObject(doc.components.schemas);\n }\n return rval;\n }\n static validateGlobalConfig(config) {\n if (!config) {\n ErrorRatchet.throwFormattedErr('Config may not be null');\n }\n if (!config.openApiYamlString) {\n ErrorRatchet.throwFormattedErr('Config must define an open api document');\n }\n if (!!config.cron && !config.cron.timezone) {\n ErrorRatchet.throwFormattedErr('Cron is defined, but timezone is not set');\n }\n }\n}\n//# sourceMappingURL=epsilon-config-parser.js.map","import { Logger } from '@bitblit/ratchet-common';\nexport class SampleInputValidatedProcessor {\n get typeName() {\n return 'EpsilonSampleInputValidated';\n }\n async handleEvent(data, mgr) {\n Logger.info('Running SampleInputValidatedProcessor, data was : %j', data);\n }\n get dataSchemaName() {\n return 'BackgroundSampleInputValidatedProcessorData';\n }\n}\n//# sourceMappingURL=sample-input-validated-processor.js.map","import { Logger } from '@bitblit/ratchet-common';\nexport class BuiltInAuthorizers {\n static async simpleNoAuthenticationLogAccess(authorizationContext, evt) {\n Logger.debug('Auth requested for %s : %j', evt.path, authorizationContext?.auth);\n return true;\n }\n static async simpleLoggedInAuth(authorizationContext, evt) {\n const rval = !!authorizationContext?.auth;\n Logger.silly('SimpleLoggedInAuth returning %s for %s', rval, evt.path);\n return rval;\n }\n static async simpleRoleRouteAuth(authorizationContext, event, route, requiredRoleOneOf = null, requiredRoleAllOf = null) {\n let rval = true;\n const token = authorizationContext?.auth;\n if (token) {\n if (requiredRoleOneOf) {\n requiredRoleOneOf.forEach((r) => {\n rval = rval || token.roles.indexOf(r) > -1;\n });\n if (!rval) {\n Logger.warn('Request to %s failed to find at least one of %j', route.path, requiredRoleOneOf);\n }\n }\n if (rval && requiredRoleAllOf) {\n requiredRoleAllOf.forEach((r) => {\n rval = rval && token.roles.indexOf(r) > -1;\n });\n if (!rval) {\n Logger.warn('Request to %s failed to find all of %j', route.path, requiredRoleAllOf);\n }\n }\n }\n else {\n Logger.warn('Cannot authenticate - no parsed auth found');\n rval = false;\n }\n return rval;\n }\n}\n//# sourceMappingURL=built-in-authorizers.js.map","import { EventUtil } from '../../../http/event-util.js';\nimport { ExpiredJwtHandling, Logger, MapRatchet } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { UnauthorizedError } from '../../../http/error/unauthorized-error.js';\nexport class ApolloUtil {\n constructor() { }\n static async emptyContext() {\n return {};\n }\n static async defaultEpsilonApolloContext(args, jwt) {\n const authTokenSt = EventUtil.extractBearerTokenFromEvent(args.lambdaEvent);\n let token = null;\n if (StringRatchet.trimToNull(authTokenSt) && jwt) {\n Logger.info('Got : %s', authTokenSt);\n token = await jwt.decodeToken(authTokenSt, ExpiredJwtHandling.RETURN_NULL);\n }\n const rval = {\n user: token,\n bearerTokenString: authTokenSt,\n headers: args.lambdaEvent.headers,\n functionName: args.lambdaContext.functionName,\n lambdaEvent: args.lambdaEvent,\n lambdaContext: args.lambdaContext,\n };\n return rval;\n }\n static async nonRouteableOnlyEpsilonApolloContext(args, jwt) {\n const hostName = StringRatchet.trimToNull(MapRatchet.extractValueFromMapIgnoreCase(args.lambdaEvent.headers, 'host'));\n const hostIsLocalOrNotRoutableIP4 = EventUtil.hostIsLocalOrNotRoutableIP4(hostName);\n if (!hostIsLocalOrNotRoutableIP4) {\n throw new UnauthorizedError('May only run local / non-routeable : ' + hostName);\n }\n return ApolloUtil.defaultEpsilonApolloContext(args, jwt);\n }\n}\n//# sourceMappingURL=apollo-util.js.map","import { Base64Ratchet, Logger, PromiseRatchet, RequireRatchet, StringRatchet, TimeoutToken, RestfulApiHttpError } from '@bitblit/ratchet-common';\nimport { RequestTimeoutError } from '../../http/error/request-timeout-error.js';\nimport { HeaderMap } from '@apollo/server';\nimport { ContextUtil } from '../../util/context-util.js';\nimport { ApolloUtil } from './apollo/apollo-util.js';\nimport { EpsilonApolloCorsMethod } from './apollo/epsilon-apollo-cors-method.js';\nimport { BuiltInFilters } from './built-in-filters.js';\nexport class ApolloFilter {\n static async handlePathWithApollo(fCtx, apolloPathRegex, apolloServer, options) {\n let rval = false;\n if (fCtx.event?.path && apolloPathRegex && apolloPathRegex.test(fCtx.event.path)) {\n fCtx.result = await ApolloFilter.processApolloRequest(fCtx.event, fCtx.context, apolloServer, options);\n if (options?.corsMethod) {\n switch (options.corsMethod) {\n case EpsilonApolloCorsMethod.All:\n await BuiltInFilters.addAllowEverythingCORSHeaders(fCtx);\n break;\n case EpsilonApolloCorsMethod.Reflective:\n await BuiltInFilters.addAllowReflectionCORSHeaders(fCtx);\n break;\n default:\n }\n }\n }\n else {\n rval = true;\n }\n return rval;\n }\n static async processApolloRequest(event, context, apolloServer, options) {\n Logger.silly('Processing event with apollo: %j', event);\n let rval = null;\n RequireRatchet.notNullOrUndefined(apolloServer, 'apolloServer');\n apolloServer.assertStarted('Cannot process with apollo - instance not started');\n const headerMap = new HeaderMap();\n for (const headersKey in event.headers) {\n headerMap.set(headersKey, event.headers[headersKey]);\n }\n const eventMethod = StringRatchet.trimToEmpty(event.httpMethod).toUpperCase();\n let body = null;\n if (StringRatchet.trimToNull(event.body)) {\n const bodyString = event.isBase64Encoded ? Base64Ratchet.base64StringToString(event.body) : event.body;\n body = JSON.parse(bodyString);\n }\n const aRequest = {\n method: eventMethod,\n headers: headerMap,\n search: eventMethod === 'GET' && event?.queryStringParameters\n ? Object.keys(event.queryStringParameters)\n .map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(event.queryStringParameters[k]))\n .join('&')\n : null,\n body: body,\n };\n const timeoutMS = options?.timeoutMS ?? context.getRemainingTimeInMillis() - 500;\n const contextFn = options?.context ?? ApolloUtil.emptyContext;\n const apolloPromise = apolloServer.executeHTTPGraphQLRequest({\n httpGraphQLRequest: aRequest,\n context: () => contextFn({ lambdaContext: context, lambdaEvent: event }),\n });\n let result = null;\n if (timeoutMS) {\n result = await PromiseRatchet.timeout(apolloPromise, 'Apollo timed out after ' + timeoutMS + ' ms.', timeoutMS);\n }\n else {\n Logger.warn('No timeout set even after defaulting for Apollo');\n result = await apolloPromise;\n }\n if (TimeoutToken.isTimeoutToken(result)) {\n result.writeToLog();\n throw new RequestTimeoutError('Timed out');\n }\n const httpGraphQLResponse = result;\n const outHeaders = {};\n for (const [headersKey, headersValue] of httpGraphQLResponse.headers.entries()) {\n outHeaders[headersKey] = headersValue;\n }\n if (httpGraphQLResponse.body.kind === 'chunked') {\n throw new RestfulApiHttpError('Apollo returned chunked result').withHttpStatusCode(500).withRequestId(ContextUtil.currentRequestId());\n }\n const bodyAsString = StringRatchet.trimToEmpty(httpGraphQLResponse?.body?.string);\n rval = {\n body: Base64Ratchet.generateBase64VersionOfString(bodyAsString),\n headers: outHeaders,\n multiValueHeaders: {},\n isBase64Encoded: true,\n statusCode: httpGraphQLResponse.status || 200,\n };\n if (eventMethod === 'GET' && rval.headers['content-type'] !== 'text/html' && bodyAsString.indexOf('<!DOCTYPE html>') >= 0) {\n Logger.info('Forcing content type to html for the sandbox page');\n rval.headers = rval.headers || {};\n rval.headers['content-type'] = 'text/html';\n }\n return rval;\n }\n static addApolloFilterToList(filters, apolloPathRegex, apolloServer, options) {\n if (filters) {\n filters.push((fCtx) => ApolloFilter.handlePathWithApollo(fCtx, apolloPathRegex, apolloServer, options));\n }\n }\n}\n//# sourceMappingURL=apollo-filter.js.map","import { Logger } from '@bitblit/ratchet-common';\nexport class LogMessageBackgroundErrorProcessor {\n async handleError(submission, error) {\n Logger.error('-------- ERROR PROCESSED : %j : %s----', submission, error);\n }\n}\n//# sourceMappingURL=log-message-background-error-processor.js.map","import { Subject } from 'rxjs';\nimport { Logger } from '@bitblit/ratchet-common';\nimport { AbstractBackgroundManager } from './abstract-background-manager.js';\nexport class SingleThreadLocalBackgroundManager extends AbstractBackgroundManager {\n _localBus = new Subject();\n get backgroundManagerName() {\n return 'SingleThreadLocalBackgroundManager';\n }\n constructor() {\n super();\n }\n immediateProcessQueue() {\n return this._localBus;\n }\n async addEntryToQueue(entry, fireStartMessage) {\n const wrapped = this.wrapEntryForInternal(entry);\n const rval = wrapped.guid;\n Logger.info('Add entry to queue (local) : %j : Start : %s', entry, fireStartMessage);\n this._localBus.next(wrapped);\n return rval;\n }\n async fireImmediateProcessRequest(entry) {\n let rval = null;\n const wrapped = this.wrapEntryForInternal(entry);\n rval = wrapped.guid;\n Logger.info('Fire immediately (local) : %j ', entry);\n this._localBus.next(wrapped);\n return rval;\n }\n async fireStartProcessingRequest() {\n let rval = null;\n Logger.info('Fire start processing request (local, ignored)');\n rval = 'NO-OP';\n return rval;\n }\n async fetchApproximateNumberOfQueueEntries() {\n let rval = null;\n rval = 0;\n return rval;\n }\n async takeEntryFromBackgroundQueue() {\n Logger.info('Called takeEntryFromBackgroundQueue on SingleThreadedLocal - returning empty');\n return [];\n }\n}\n//# sourceMappingURL=single-thread-local-background-manager.js.map","export class SampleServerStaticFiles {\n constructor() { }\n static SAMPLE_OPEN_API_DOC = 'openapi: 3.0.0\\n' +\n 'info:\\n' +\n ' version: v0\\n' +\n ' title: SampleAPI\\n' +\n 'tags:\\n' +\n ' - name: CORS\\n' +\n ' description: These endpoints are here to support CORS\\n' +\n ' - name: Public\\n' +\n ' description: These endpoints can be called without setting the authorization header\\n' +\n ' - name: Secure\\n' +\n ' description: Authentication and authorization of the API\\n' +\n 'paths:\\n' +\n ' /:\\n' +\n ' get:\\n' +\n ' description: Redirects to the /meta/server endpoint\\n' +\n ' tags:\\n' +\n ' - Meta\\n' +\n ' - Public\\n' +\n ' responses:\\n' +\n \" '301':\\n\" +\n ' description: Redirects to the /meta/server endpoint\\n' +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Standard CORS header response\\n' +\n ' /meta/server:\\n' +\n ' get:\\n' +\n ' description: >\\n' +\n ' Returns information about the current build and time. Can be used to\\n' +\n ' test error-handling code by passing a specific http error code in the\\n' +\n ' error query parameter. Can also be used to process specific named tests\\n' +\n ' by passing those names to the test parameter.\\n' +\n ' tags:\\n' +\n ' - Public\\n' +\n ' parameters:\\n' +\n ' - name: error\\n' +\n ' in: query\\n' +\n ' description: >-\\n' +\n ' If set, throw a specific error for testing (valid are\\n' +\n ' 500,400,403,404)\\n' +\n ' required: false\\n' +\n ' schema:\\n' +\n ' type: number\\n' +\n ' - name: test\\n' +\n ' in: query\\n' +\n ' description: Run a specific named test (currently none are publicly available)\\n' +\n ' required: false\\n' +\n ' schema:\\n' +\n ' type: string\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n \" '400':\\n\" +\n ' description: Simulated bad request\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n \" '403':\\n\" +\n ' description: Simulated unauthorized\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n \" '404':\\n\" +\n ' description: Simulated not found\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n \" '500':\\n\" +\n ' description: Simulated internal server error\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Standard CORS header response\\n' +\n ' /meta/user:\\n' +\n ' get:\\n' +\n ' description: >\\n' +\n ' When logged in, returns the contents of the JWT token as the server\\n' +\n ' parses it. This should match what you get when you process the token\\n' +\n ' returned from the \"POST /access-token\" endpoint through a standard JWT\\n' +\n ' token processor.\\n' +\n ' tags:\\n' +\n ' - Meta\\n' +\n ' security:\\n' +\n ' - SampleAuthorizer: []\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/AccessTokenContents'\\n\" +\n \" '401':\\n\" +\n ' description: Unauthorized\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n \" '401':\\n\" +\n ' description: Unauthorized\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n ' /meta/item/{itemId}:\\n' +\n ' get:\\n' +\n ' description: >\\n' +\n ' Example of a path param\\n' +\n ' parameters:\\n' +\n ' - name: itemId\\n' +\n ' in: path\\n' +\n ' description: A sample item id\\n' +\n ' required: true\\n' +\n ' schema:\\n' +\n ' type: string\\n' +\n ' tags:\\n' +\n ' - Meta\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/Empty'\\n\" +\n \" '401':\\n\" +\n ' description: Unauthorized\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' parameters:\\n' +\n ' - name: itemId\\n' +\n ' in: path\\n' +\n ' description: A sample item id\\n' +\n ' required: true\\n' +\n ' schema:\\n' +\n ' type: string\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n \" '401':\\n\" +\n ' description: Unauthorized\\n' +\n ' content:\\n' +\n \" '*/*':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n '\\n' +\n ' /meta/sample-item:\\n' +\n ' get:\\n' +\n ' description: >\\n' +\n ' Example of an object returned\\n' +\n ' parameters:\\n' +\n ' - name: num\\n' +\n ' in: path\\n' +\n ' description: Number to return in the number value\\n' +\n ' required: false\\n' +\n ' schema:\\n' +\n ' type: number\\n' +\n ' tags:\\n' +\n ' - Meta\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' content:\\n' +\n \" 'application/json':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/BackgroundSampleInputValidatedProcessorData'\\n\" +\n ' post:\\n' +\n ' description: >\\n' +\n ' Example of an object posted\\n' +\n ' requestBody:\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/BackgroundSampleInputValidatedProcessorData'\\n\" +\n ' description: Request to refresh the access token or change active user\\n' +\n ' required: true\\n' +\n ' tags:\\n' +\n ' - Meta\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' content:\\n' +\n \" 'application/json':\\n\" +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/BackgroundSampleInputValidatedProcessorData'\\n\" +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n '\\n' +\n ' /secure/access-token:\\n' +\n ' post:\\n' +\n ' tags:\\n' +\n ' - Secure\\n' +\n ' - Public\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/AccessTokenResponse'\\n\" +\n \" '400':\\n\" +\n ' description: Invalid request\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n \" '403':\\n\" +\n ' description: Invalid credentials\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n ' requestBody:\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/AccessTokenRequest'\\n\" +\n ' description: Request to refresh the access token or change active user\\n' +\n ' required: true\\n' +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Standard CORS header response\\n' +\n ' /multi/fixed:\\n' +\n ' get:\\n' +\n ' description: Tests path matching from most specific to least (this is most)\\n' +\n ' tags:\\n' +\n ' - Public\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Standard CORS header response\\n' +\n ' /multi/{v}:\\n' +\n ' get:\\n' +\n ' description: Tests path matching from most specific to least (this is least)\\n' +\n ' tags:\\n' +\n ' - Public\\n' +\n ' parameters:\\n' +\n ' - name: v\\n' +\n ' in: path\\n' +\n ' description: A variable\\n' +\n ' required: true\\n' +\n ' schema:\\n' +\n ' type: string\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' parameters:\\n' +\n ' - name: v\\n' +\n ' in: path\\n' +\n ' description: A variable\\n' +\n ' required: true\\n' +\n ' schema:\\n' +\n ' type: string\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Standard CORS header response\\n' +\n '\\n' +\n ' /err/{code}:\\n' +\n ' get:\\n' +\n ' description: Tests path matching from most specific to least (this is least)\\n' +\n ' tags:\\n' +\n ' - Public\\n' +\n ' parameters:\\n' +\n ' - name: code\\n' +\n ' in: path\\n' +\n ' description: Error code\\n' +\n ' required: true\\n' +\n ' schema:\\n' +\n ' type: number\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' parameters:\\n' +\n ' - name: code\\n' +\n ' in: path\\n' +\n ' description: A variable\\n' +\n ' required: true\\n' +\n ' schema:\\n' +\n ' type: number\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Standard CORS header response\\n' +\n '\\n' +\n ' /background:\\n' +\n ' post:\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/BackgroundQueueResponse'\\n\" +\n \" '400':\\n\" +\n ' description: Invalid request\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n \" '403':\\n\" +\n ' description: Invalid credentials\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n ' requestBody:\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/Empty'\\n\" +\n ' description: Content to echo\\n' +\n ' required: true\\n' +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Standard CORS header response\\n' +\n '\\n' +\n ' /background/meta:\\n' +\n ' get:\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Success\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/BackgroundMetaResponse'\\n\" +\n \" '400':\\n\" +\n ' description: Invalid request\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n \" '403':\\n\" +\n ' description: Invalid credentials\\n' +\n ' content:\\n' +\n ' application/json:\\n' +\n ' schema:\\n' +\n \" $ref: '#/components/schemas/ApiErrorResponse'\\n\" +\n ' options:\\n' +\n ' tags:\\n' +\n ' - CORS\\n' +\n ' responses:\\n' +\n \" '200':\\n\" +\n ' description: Standard CORS header response\\n' +\n '\\n' +\n 'x-amazon-apigateway-binary-media-types:\\n' +\n \" - '*/*'\\n\" +\n 'x-amazon-apigateway-gateway-responses:\\n' +\n ' UNAUTHORIZED:\\n' +\n ' statusCode: 401\\n' +\n ' responseParameters:\\n' +\n ' gatewayresponse.header.Access-Control-Allow-Origin: \"\\'*\\'\"\\n' +\n ' responseTemplates:\\n' +\n ' application/json: \\'{\"errors\":[\"Unauthorized\"], \"httpStatusCode\": 401}\\'\\n' +\n ' MISSING_AUTHENTICATION_TOKEN:\\n' +\n ' statusCode: 404\\n' +\n ' responseParameters:\\n' +\n ' gatewayresponse.header.Access-Control-Allow-Origin: \"\\'*\\'\"\\n' +\n ' responseTemplates:\\n' +\n ' application/json: \\'{\"errors\":[\"No such endpoint\"], \"httpStatusCode\": 404}\\'\\n' +\n ' INTEGRATION_TIMEOUT:\\n' +\n ' statusCode: 504\\n' +\n ' responseParameters:\\n' +\n ' gatewayresponse.header.Access-Control-Allow-Origin: \"\\'*\\'\"\\n' +\n ' responseTemplates:\\n' +\n ' application/json: \\'{\"errors\":[\"Timeout\"], \"httpStatusCode\": 504}\\'\\n' +\n ' DEFAULT_5XX:\\n' +\n ' statusCode: 500\\n' +\n ' responseParameters:\\n' +\n ' gatewayresponse.header.Access-Control-Allow-Origin: \"\\'*\\'\"\\n' +\n ' responseTemplates:\\n' +\n ' application/json: \\'{\"errors\":[\"Internal Server Error\"], \"httpStatusCode\": 500}\\'\\n' +\n '\\n' +\n 'servers:\\n' +\n \" - url: 'https://api.sample.com/dev'\\n\" +\n 'components:\\n' +\n ' securitySchemes:\\n' +\n ' SampleAuthorizer:\\n' +\n ' type: apiKey\\n' +\n ' name: Authorization\\n' +\n ' in: header\\n' +\n ' schemas:\\n' +\n ' Empty:\\n' +\n ' type: object\\n' +\n ' title: Empty Schema\\n' +\n '\\n' +\n ' AccessTokenRequest:\\n' +\n ' type: object\\n' +\n ' title: Access Token Request\\n' +\n ' required:\\n' +\n ' - email\\n' +\n ' - password\\n' +\n ' - scope\\n' +\n ' properties:\\n' +\n ' email:\\n' +\n ' type: string\\n' +\n ' description: Email address of the account to authenticate\\n' +\n ' format: email\\n' +\n ' minLength: 7\\n' +\n ' password:\\n' +\n ' type: string\\n' +\n ' description: Password of the account to authenticate\\n' +\n ' minLength: 6\\n' +\n ' scope:\\n' +\n ' type: string\\n' +\n ' enum:\\n' +\n ' - OWNER\\n' +\n ' - ADVERTISER\\n' +\n ' - GLOBAL\\n' +\n ' - RUN_AS_OWNER\\n' +\n ' - RUN_AS_ADVERTISER\\n' +\n ' description: |\\n' +\n ' What style of account to authenticate:\\n' +\n ' * `OWNER` - A device owner account\\n' +\n ' * `ADVERTISER` - A advertising account\\n' +\n ' * `GLOBAL` - Used by Adomni customer service\\n' +\n ' * `RUN_AS_OWNER` - Used by Adomni customer service\\n' +\n ' * `RUN_AS_ADVERTISER` - Used by Adomni customer service\\n' +\n ' default: OWNER\\n' +\n ' runAs:\\n' +\n ' type: string\\n' +\n ' description: Used by Adomni customer service\\n' +\n ' format: email\\n' +\n ' expirationSeconds:\\n' +\n ' type: number\\n' +\n ' minimum: 10\\n' +\n ' maximum: 3600\\n' +\n ' default: 3600\\n' +\n ' AccessTokenResponse:\\n' +\n ' type: object\\n' +\n ' title: Access Token Response\\n' +\n ' required:\\n' +\n ' - token\\n' +\n ' - expires\\n' +\n ' properties:\\n' +\n ' token:\\n' +\n ' type: string\\n' +\n ' description: A JWT access token for the API\\n' +\n ' expires:\\n' +\n ' type: number\\n' +\n ' format: int64\\n' +\n \" description: 'The time this token will expire, expressed in epoch ms'\\n\" +\n ' AccessTokenContents:\\n' +\n ' type: object\\n' +\n ' title: Access Token Contents\\n' +\n ' description: The contents of the JWT token\\n' +\n ' required:\\n' +\n ' - exp\\n' +\n ' - iss\\n' +\n ' - sub\\n' +\n ' - iat\\n' +\n ' - user\\n' +\n ' properties:\\n' +\n ' exp:\\n' +\n ' type: number\\n' +\n ' description: >-\\n' +\n ' Expiration claim - The time this token will expire, expressed in\\n' +\n ' epoch ms\\n' +\n ' iss:\\n' +\n ' type: string\\n' +\n ' description: Issuer claim - Who created the token\\n' +\n ' sub:\\n' +\n ' type: string\\n' +\n ' description: Subject claim - The target of the token (typically user email)\\n' +\n ' iat:\\n' +\n ' type: number\\n' +\n ' description: >-\\n' +\n ' Issued at claim - The time this token was created, expressed in\\n' +\n ' epoch ms\\n' +\n ' user:\\n' +\n ' type: object\\n' +\n ' description: Object describing the user authenticated by this token\\n' +\n ' ApiErrorResponse:\\n' +\n ' type: object\\n' +\n ' title: API Error Response\\n' +\n ' required:\\n' +\n ' - errors\\n' +\n ' - httpStatusCode\\n' +\n ' properties:\\n' +\n ' errors:\\n' +\n ' type: array\\n' +\n ' items:\\n' +\n ' type: string\\n' +\n ' description: List of the errors that occurred\\n' +\n ' httpStatusCode:\\n' +\n ' type: number\\n' +\n ' description: Http status code of this error\\n' +\n ' detailCode:\\n' +\n ' type: number\\n' +\n ' description: Adomni detail status code for this error\\n' +\n ' BackgroundQueueResponse:\\n' +\n ' type: object\\n' +\n ' title: Background Queue Response\\n' +\n ' description: When any of the background endpoints are hit, this is what will be returned\\n' +\n ' required:\\n' +\n ' - resultId\\n' +\n ' - success\\n' +\n ' properties:\\n' +\n ' processHandling:\\n' +\n ' type: string\\n' +\n \" enum: ['Queued', 'Immediate']\\n\" +\n ' success:\\n' +\n ' type: boolean\\n' +\n ' resultId:\\n' +\n ' type: string\\n' +\n ' BackgroundMetaResponse:\\n' +\n ' type: object\\n' +\n ' title: Background Meta Response\\n' +\n ' description: If\\n' +\n ' properties:\\n' +\n ' validTypes:\\n' +\n ' type: array\\n' +\n ' items:\\n' +\n ' type: string\\n' +\n ' currentQueueLength:\\n' +\n ' type: number\\n' +\n '\\n' +\n ' BackgroundSampleInputValidatedProcessorData:\\n' +\n ' type: object\\n' +\n ' title: BackgroundSampleInputValidatedProcessorData\\n' +\n ' description: This is used for testing the background validator\\n' +\n ' required:\\n' +\n ' - nameParam\\n' +\n ' - numberParam\\n' +\n ' properties:\\n' +\n ' nameParam:\\n' +\n ' type: string\\n' +\n ' description: A sample name parameter\\n' +\n ' minimum: 0\\n' +\n ' maximum: 10\\n' +\n ' numberParam:\\n' +\n ' type: number\\n' +\n ' description: A sample number parameter\\n';\n static SAMPLE_SERVER_GRAPHQL = 'schema {\\n' +\n ' query: RootQueryType\\n' +\n '}\\n' +\n '\\n' +\n 'type RootQueryType {\\n' +\n ' serverMeta: ServerMeta\\n' +\n ' forceTimeout: ForceTimeout\\n' +\n '}\\n' +\n '\\n' +\n 'type ServerMeta {\\n' +\n ' version: String\\n' +\n ' serverTime: String\\n' +\n ' status: String\\n' +\n '}\\n' +\n '\\n' +\n 'type ForceTimeout {\\n' +\n ' placeholder: String\\n' +\n '}\\n';\n}\n//# sourceMappingURL=sample-server-static-files.js.map","import { BooleanRatchet, ErrorRatchet, Logger, LoggerLevelName, NumberRatchet, PromiseRatchet, StringRatchet, } from '@bitblit/ratchet-common';\nimport { ApolloServer } from '@apollo/server';\nimport { gql } from 'graphql-tag';\nimport { ApolloServerPluginLandingPageLocalDefault } from '@apollo/server/plugin/landingPage/default';\nimport { EpsilonGlobalHandler } from '../epsilon-global-handler.js';\nimport { BuiltInHandlers } from '../built-in/http/built-in-handlers.js';\nimport { LocalWebTokenManipulator } from '../http/auth/local-web-token-manipulator.js';\nimport { EchoProcessor } from '../built-in/background/echo-processor.js';\nimport { NoOpProcessor } from '../built-in/background/no-op-processor.js';\nimport { SampleDelayProcessor } from '../built-in/background/sample-delay-processor.js';\nimport { LogAndEnqueueEchoProcessor } from '../built-in/background/log-and-enqueue-echo-processor.js';\nimport { EpsilonConfigParser } from '../util/epsilon-config-parser.js';\nimport { RouterUtil } from '../http/route/router-util.js';\nimport { SampleInputValidatedProcessor } from '../built-in/background/sample-input-validated-processor.js';\nimport { BuiltInAuthorizers } from '../built-in/http/built-in-authorizers.js';\nimport { ApolloFilter } from '../built-in/http/apollo-filter.js';\nimport { BuiltInFilters } from '../built-in/http/built-in-filters.js';\nimport { LogMessageBackgroundErrorProcessor } from '../built-in/background/log-message-background-error-processor.js';\nimport { SingleThreadLocalBackgroundManager } from '../background/manager/single-thread-local-background-manager.js';\nimport { SampleServerStaticFiles } from './sample-server-static-files.js';\nimport { ApolloUtil } from '../built-in/http/apollo/apollo-util.js';\nimport { EpsilonApolloCorsMethod } from '../built-in/http/apollo/epsilon-apollo-cors-method.js';\nexport class SampleServerComponents {\n constructor() { }\n static async createSampleApollo() {\n const gqlString = SampleServerStaticFiles.SAMPLE_SERVER_GRAPHQL;\n Logger.silly('Creating apollo from : %s', gqlString);\n const typeDefs = gql(gqlString);\n const resolvers = {\n RootQueryType: {\n serverMeta: async (root) => {\n return { version: 'A1', serverTime: new Date().toISOString() };\n },\n forceTimeout: async (root) => {\n await PromiseRatchet.wait(1000 * 60 * 30);\n return { placeholder: 'A1' };\n },\n },\n };\n const server = new ApolloServer({\n introspection: true,\n typeDefs,\n resolvers,\n plugins: [\n ApolloServerPluginLandingPageLocalDefault({ footer: false }),\n ],\n });\n await server.start();\n return server;\n }\n static async createSampleEpsilonConfig(label) {\n const yamlString = SampleServerStaticFiles.SAMPLE_OPEN_API_DOC;\n const authorizers = new Map();\n authorizers.set('SampleAuthorizer', (token, evt) => BuiltInAuthorizers.simpleLoggedInAuth(token, evt));\n authorizers.set('LogAuthorizer', (token, evt) => BuiltInAuthorizers.simpleNoAuthenticationLogAccess(token, evt));\n const handlers = new Map();\n handlers.set('get /', (event, context) => BuiltInHandlers.sample(event, null, context));\n handlers.set('get /meta/server', (event) => BuiltInHandlers.sample(event));\n handlers.set('get /meta/user', (event) => BuiltInHandlers.sample(event));\n handlers.set('get /meta/item/{itemId}', (event) => BuiltInHandlers.sample(event));\n handlers.set('post /secure/access-token', (event) => BuiltInHandlers.sample(event));\n handlers.set('get /multi/fixed', (event) => BuiltInHandlers.sample(event, 'fixed'));\n handlers.set('get /multi/{v}', (event) => BuiltInHandlers.sample(event, 'variable'));\n handlers.set('get /err/{code}', (event) => {\n const err = ErrorRatchet.fErr('Fake Err : %j', event);\n err['statusCode'] = NumberRatchet.safeNumber(event.pathParameters['code']);\n throw err;\n });\n handlers.set('get /meta/sample-item', async (event) => {\n const numberToUse = NumberRatchet.safeNumber(event.queryStringParameters['num']) || 5;\n const rval = {\n numberParam: numberToUse,\n nameParam: 'Test-String',\n };\n return rval;\n });\n handlers.set('post /meta/sample-item', async (event) => {\n const parsed = event.parsedBody;\n const forceFail = BooleanRatchet.parseBool(StringRatchet.trimToNull(event.queryStringParameters['forceFail'])) === true;\n if (forceFail) {\n parsed['numberParam'] = 'test';\n }\n return parsed;\n });\n const tokenManipulator = new LocalWebTokenManipulator(['abcd1234'], 'sample.erigir.com')\n .withParseFailureLogLevel(LoggerLevelName.debug)\n .withExtraDecryptionKeys(['abcdefabcdef'])\n .withOldKeyUseLogLevel(LoggerLevelName.info);\n const meta = RouterUtil.defaultHttpMetaProcessingConfigWithAuthenticationHeaderParsing(tokenManipulator);\n meta.timeoutMS = 10_000;\n ApolloFilter.addApolloFilterToList(meta.preFilters, new RegExp('.*graphql.*'), await SampleServerComponents.createSampleApollo(), {\n context: (arg) => ApolloUtil.defaultEpsilonApolloContext(arg, tokenManipulator.jwtRatchet),\n timeoutMS: 5_000,\n corsMethod: EpsilonApolloCorsMethod.All,\n });\n meta.errorFilters.push((fCtx) => BuiltInFilters.secureOutboundServerErrorForProduction(fCtx, 'Clean Internal Server Error', 500));\n const preFiltersAllowingNull = Object.assign({}, meta);\n preFiltersAllowingNull.preFilters = Object.assign([], preFiltersAllowingNull.preFilters);\n preFiltersAllowingNull.preFilters.splice(8, 1);\n const cfg = {\n defaultMetaHandling: meta,\n handlers: handlers,\n authorizers: authorizers,\n overrideMetaHandling: [\n {\n pathRegex: '/background',\n methods: null,\n config: Object.assign({}, meta, { overrideAuthorizerName: 'LogAuthorizer' }),\n },\n {\n pathRegex: '/meta/server',\n methods: ['GET'],\n config: preFiltersAllowingNull,\n },\n ],\n prefixesToStripBeforeRouteMatch: ['v0'],\n filterHandledRouteMatches: ['options .*'],\n };\n const background = {\n httpMetaEndpoint: '/background/meta',\n httpSubmissionPath: '/background',\n implyTypeFromPathSuffix: false,\n processors: [\n new EchoProcessor(),\n new NoOpProcessor(),\n new SampleDelayProcessor(),\n new SampleInputValidatedProcessor(),\n new LogAndEnqueueEchoProcessor(),\n ],\n errorProcessor: new LogMessageBackgroundErrorProcessor(),\n };\n const epsilonConfig = {\n label: label,\n openApiYamlString: yamlString,\n httpConfig: cfg,\n backgroundConfig: background,\n };\n return epsilonConfig;\n }\n static async createSampleEpsilonGlobalHandler(label) {\n const epsilonConfig = await SampleServerComponents.createSampleEpsilonConfig(label);\n const backgroundManager = new SingleThreadLocalBackgroundManager();\n const epsilonInstance = EpsilonConfigParser.epsilonConfigToEpsilonInstance(epsilonConfig, backgroundManager);\n const rval = new EpsilonGlobalHandler(epsilonInstance);\n return rval;\n }\n static async createSampleBatchOnlyEpsilonGlobalHandler(label) {\n const epsilonConfig = await SampleServerComponents.createSampleEpsilonConfig(label);\n epsilonConfig.httpConfig.handlers = new Map();\n const byPassCfg = Object.assign({}, epsilonConfig.httpConfig.defaultMetaHandling);\n byPassCfg.preFilters = byPassCfg.preFilters.concat([\n (fCtx) => BuiltInFilters.autoRespond(fCtx, { message: 'Background Processing Only' }),\n ]);\n epsilonConfig.httpConfig.overrideMetaHandling = [\n {\n pathRegex: '.*background.*',\n invertPathMatching: true,\n config: byPassCfg,\n },\n ];\n epsilonConfig.httpConfig.filterHandledRouteMatches = ['.*'];\n const backgroundManager = new SingleThreadLocalBackgroundManager();\n const epsilonInstance = EpsilonConfigParser.epsilonConfigToEpsilonInstance(epsilonConfig, backgroundManager);\n const rval = new EpsilonGlobalHandler(epsilonInstance);\n return rval;\n }\n}\n//# sourceMappingURL=sample-server-components.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport http from 'http';\nimport https from 'https';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport { DateTime } from 'luxon';\nimport qs from 'querystring';\nimport { EventUtil } from './http/event-util.js';\nimport { LoggerLevelName } from '@bitblit/ratchet-common';\nimport { LocalServerCert } from './local-server-cert.js';\nimport { SampleServerComponents } from './sample/sample-server-components.js';\nimport { LocalWebTokenManipulator } from './http/auth/local-web-token-manipulator.js';\nexport class LocalServer {\n globalHandler;\n port;\n server;\n aborted = false;\n constructor(globalHandler, port = 8888, https = false) {\n this.globalHandler = globalHandler;\n this.port = port;\n }\n async runServer() {\n return new Promise((res, rej) => {\n try {\n Logger.info('Starting Epsilon server on port %d', this.port);\n if (https) {\n const options = {\n key: LocalServerCert.CLIENT_KEY_PEM,\n cert: LocalServerCert.CLIENT_CERT_PEM,\n };\n Logger.info('Starting https server - THIS SERVER IS NOT SECURE! The KEYS are in the code! Testing Server Only - Use at your own risk!');\n this.server = https.createServer(options, this.requestHandler.bind(this)).listen(this.port);\n }\n else {\n this.server = http.createServer(this.requestHandler.bind(this)).listen(this.port);\n }\n Logger.info('Epsilon server is listening');\n process.on('SIGINT', () => {\n Logger.info('Caught SIGINT - shutting down test server...');\n this.aborted = true;\n res(true);\n });\n }\n catch (err) {\n Logger.error('Local server failed : %s', err, err);\n rej(err);\n }\n });\n }\n async requestHandler(request, response) {\n const context = {\n awsRequestId: 'LOCAL-' + StringRatchet.createType4Guid(),\n getRemainingTimeInMillis() {\n return 300000;\n },\n };\n const evt = await LocalServer.messageToApiGatewayEvent(request, context);\n const logEventLevel = EventUtil.eventIsAGraphQLIntrospection(evt) ? LoggerLevelName.silly : LoggerLevelName.info;\n if (evt.path == '/epsilon-poison-pill') {\n this.aborted = true;\n return true;\n }\n else {\n const result = await this.globalHandler.lambdaHandler(evt, context);\n const written = await LocalServer.writeProxyResultToServerResponse(result, response);\n return written;\n }\n }\n static async bodyAsBase64String(request) {\n return new Promise((res, rej) => {\n const body = [];\n request.on('data', (chunk) => {\n body.push(chunk);\n });\n request.on('end', () => {\n const rval = Buffer.concat(body).toString('base64');\n res(rval);\n });\n });\n }\n static async messageToApiGatewayEvent(request, context) {\n const bodyString = await LocalServer.bodyAsBase64String(request);\n const stageIdx = request.url.indexOf('/', 1);\n const stage = request.url.substring(1, stageIdx);\n const path = request.url.substring(stageIdx + 1);\n const reqTime = new Date().getTime();\n const formattedTime = DateTime.utc().toFormat('dd/MMM/yyyy:hh:mm:ss ZZ');\n const queryIdx = request.url.indexOf('?');\n const queryStringParams = queryIdx > -1 ? qs.parse(request.url.substring(queryIdx + 1)) : {};\n const headers = Object.assign({}, request.headers);\n headers['X-Forwarded-Proto'] = 'http';\n const rval = {\n body: bodyString,\n multiValueHeaders: {},\n multiValueQueryStringParameters: {},\n resource: '/{proxy+}',\n path: request.url,\n httpMethod: request.method.toLowerCase(),\n isBase64Encoded: true,\n queryStringParameters: queryStringParams,\n pathParameters: {\n proxy: path,\n },\n stageVariables: {\n baz: 'qux',\n },\n headers: headers,\n requestContext: {\n accountId: '123456789012',\n resourceId: '123456',\n stage: stage,\n requestId: context.awsRequestId,\n requestTime: formattedTime,\n requestTimeEpoch: reqTime,\n identity: null,\n path: request.url,\n domainName: request.headers['host'],\n resourcePath: '/{proxy+}',\n httpMethod: request.method.toLowerCase(),\n apiId: '1234567890',\n protocol: 'HTTP/1.1',\n },\n };\n return rval;\n }\n static async writeProxyResultToServerResponse(proxyResult, response) {\n const isGraphQLSchemaResponse = !!proxyResult && !!proxyResult.body && proxyResult.body.indexOf('{\"data\":{\"__schema\"') > -1;\n if (!isGraphQLSchemaResponse) {\n Logger.debug('Result: %j', proxyResult);\n }\n response.statusCode = proxyResult.statusCode;\n if (proxyResult.headers) {\n Object.keys(proxyResult.headers).forEach((hk) => {\n response.setHeader(hk, String(proxyResult.headers[hk]));\n });\n }\n if (proxyResult.multiValueHeaders) {\n Object.keys(proxyResult.multiValueHeaders).forEach((hk) => {\n response.setHeader(hk, proxyResult.multiValueHeaders[hk].join(','));\n });\n }\n const toWrite = proxyResult.isBase64Encoded ? Buffer.from(proxyResult.body, 'base64') : Buffer.from(proxyResult.body);\n response.end(toWrite);\n return !!proxyResult.body;\n }\n static async runSampleBatchOnlyServerFromCliArgs(args) {\n Logger.setLevel(LoggerLevelName.debug);\n const handler = await SampleServerComponents.createSampleBatchOnlyEpsilonGlobalHandler('SampleBatchOnlyLocalServer-' + Date.now());\n const testServer = new LocalServer(handler);\n const res = await testServer.runServer();\n Logger.info('Res was : %s', res);\n }\n static async runSampleLocalServerFromCliArgs(args) {\n Logger.setLevel(LoggerLevelName.debug);\n const localTokenHandler = new LocalWebTokenManipulator(['abcd1234'], 'sample-server');\n const token = await localTokenHandler.createJWTStringAsync('asdf', {}, ['USER'], 3600);\n Logger.info('Use token: %s', token);\n const handler = await SampleServerComponents.createSampleEpsilonGlobalHandler('SampleLocalServer-' + Date.now());\n const testServer = new LocalServer(handler, 8888, true);\n const res = await testServer.runServer();\n Logger.info('Res was : %s', res);\n }\n}\n//# sourceMappingURL=local-server.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { LoggerLevelName } from '@bitblit/ratchet-common';\nimport http from 'http';\nimport { EventUtil } from './http/event-util.js';\nimport fetch from 'cross-fetch';\nimport { LocalServer } from './local-server.js';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nexport class LocalContainerServer {\n port;\n server;\n aborted = false;\n constructor(port = 8889) {\n this.port = port;\n }\n async runServer() {\n return new Promise((res, rej) => {\n try {\n Logger.info('Starting Epsilon server on port %d', this.port);\n this.server = http.createServer(this.requestHandler.bind(this)).listen(this.port);\n Logger.info('Epsilon server is listening');\n process.on('SIGINT', () => {\n Logger.info('Caught SIGINT - shutting down test server...');\n this.aborted = true;\n res(true);\n });\n }\n catch (err) {\n Logger.error('Local server failed : %s', err, err);\n rej(err);\n }\n });\n }\n async requestHandler(request, response) {\n const context = {\n awsRequestId: 'LOCAL-' + StringRatchet.createType4Guid(),\n getRemainingTimeInMillis() {\n return 300000;\n },\n };\n const evt = await LocalServer.messageToApiGatewayEvent(request, context);\n const logEventLevel = EventUtil.eventIsAGraphQLIntrospection(evt) ? LoggerLevelName.silly : LoggerLevelName.info;\n Logger.logByLevel(logEventLevel, 'Processing event: %j', evt);\n if (evt.path == '/epsilon-poison-pill') {\n this.aborted = true;\n return true;\n }\n else {\n const url = 'http://localhost:8080/2015-03-31/functions/function/invocations';\n try {\n const postResp = await fetch(url, { method: 'POST', body: JSON.stringify(evt) });\n const respBody = await postResp.json();\n const result = respBody;\n const written = await LocalServer.writeProxyResultToServerResponse(result, response);\n return written;\n }\n catch (err) {\n Logger.error('Failed: %s', err);\n return '{\"bad\":true}';\n }\n }\n }\n static async runFromCliArgs(args) {\n try {\n Logger.setLevel(LoggerLevelName.debug);\n Logger.debug('Running local container server : %j', process?.argv);\n const testServer = new LocalContainerServer();\n await testServer.runServer();\n Logger.info('Got res server');\n process.exit(0);\n }\n catch (err) {\n Logger.error('Error : %s', err);\n process.exit(1);\n }\n }\n}\n//# sourceMappingURL=local-container-server.js.map","import { BackgroundExecutionEventType } from './background-execution-event-type.js';\nimport { ContextUtil } from '../util/context-util.js';\nexport class BackgroundDynamoLogTableHandler {\n dynamo;\n tableName;\n env;\n backgroundQueueName;\n constructor(dynamo, tableName, env, backgroundQueueName) {\n this.dynamo = dynamo;\n this.tableName = tableName;\n this.env = env;\n this.backgroundQueueName = backgroundQueueName;\n }\n async onEvent(event) {\n const entry = {\n env: this.env,\n backgroundQueueName: this.backgroundQueueName,\n requestId: ContextUtil.currentRequestId(),\n guid: event.guid,\n processTypeName: event.processorType,\n state: event.type.toString(),\n timestampEpochMs: new Date().getTime(),\n };\n if (event.type == BackgroundExecutionEventType.DataValidationError) {\n const errors = event?.errors?.length ? event.errors : ['No-Error'];\n entry.errors = errors;\n }\n else if (event.type == BackgroundExecutionEventType.ProcessStarting) {\n entry.params = event.data;\n }\n else if (event.type == BackgroundExecutionEventType.ExecutionFailedError) {\n const errors = event?.errors?.length ? event.errors : ['No-Error'];\n entry.errors = errors;\n }\n await this.dynamo.simplePut(this.tableName, entry);\n }\n}\n//# sourceMappingURL=background-dynamo-log-table-handler.js.map","import util from 'util';\nexport class EpsilonBackgroundProcessError extends Error {\n static EPSILON_BACKGROUND_PROCESS_ERROR_FLAG_KEY = '__epsilonBackgroundProcessErrorFlag';\n _errors;\n _detailErrorCode;\n _details;\n _requestId;\n _wrappedError;\n constructor(...errors) {\n super(EpsilonBackgroundProcessError.combineErrorStringsWithDefault(errors));\n Object.setPrototypeOf(this, EpsilonBackgroundProcessError.prototype);\n this._errors = errors;\n this[EpsilonBackgroundProcessError.EPSILON_BACKGROUND_PROCESS_ERROR_FLAG_KEY] = true;\n }\n static combineErrorStringsWithDefault(errors, defMessage = 'Internal Server Error') {\n return errors && errors.length > 0 ? errors.join(',') : defMessage;\n }\n setFormattedErrorMessage(format, ...input) {\n const msg = util.format(format, ...input);\n this.errors = [msg];\n }\n withFormattedErrorMessage(format, ...input) {\n this.setFormattedErrorMessage(format, ...input);\n return this;\n }\n withErrors(errors) {\n this.errors = errors;\n return this;\n }\n withDetailErrorCode(detailErrorCode) {\n this._detailErrorCode = detailErrorCode;\n return this;\n }\n withDetails(details) {\n this._details = details;\n return this;\n }\n withRequestId(requestId) {\n this._requestId = requestId;\n return this;\n }\n withWrappedError(err) {\n this._wrappedError = err;\n return this;\n }\n isWrappedError() {\n return !!this._wrappedError;\n }\n static wrapError(err) {\n let rval = null;\n if (EpsilonBackgroundProcessError.objectIsEpsilonBackgroundProcessError(err)) {\n rval = err;\n }\n else {\n rval = new EpsilonBackgroundProcessError(err.message).withWrappedError(err);\n }\n return rval;\n }\n static objectIsEpsilonBackgroundProcessError(obj) {\n return obj && obj[EpsilonBackgroundProcessError.EPSILON_BACKGROUND_PROCESS_ERROR_FLAG_KEY] === true;\n }\n set errors(value) {\n this._errors = value || ['Internal Server Error'];\n this.message = EpsilonBackgroundProcessError.combineErrorStringsWithDefault(this._errors);\n }\n get errors() {\n return this._errors;\n }\n set detailErrorCode(value) {\n this._detailErrorCode = value;\n }\n get detailErrorCode() {\n return this._detailErrorCode;\n }\n set details(value) {\n this._details = value;\n }\n get details() {\n return this._details;\n }\n set requestId(value) {\n this._requestId = value || 'MISSING';\n }\n get requestId() {\n return this._requestId;\n }\n set wrappedError(value) {\n this._wrappedError = value;\n }\n get wrappedError() {\n return this._wrappedError;\n }\n}\n//# sourceMappingURL=epsilon-background-process-error.js.map","import { S3CacheRatchet } from '@bitblit/ratchet-aws';\nimport { AbstractBackgroundManager } from './manager/abstract-background-manager.js';\nimport { ErrorRatchet } from '@bitblit/ratchet-common';\nimport { Logger } from '@bitblit/ratchet-common';\nexport class S3BackgroundTransactionLogger {\n cfg;\n s3TransactionLogCacheRatchet;\n constructor(cfg) {\n this.cfg = cfg;\n const err = S3BackgroundTransactionLogger.validateConfig(cfg);\n if (err.length) {\n ErrorRatchet.throwFormattedErr('Invalid S3BackgroundTransactionLogger config : %j', err);\n }\n this.s3TransactionLogCacheRatchet = new S3CacheRatchet(this.cfg.s3, this.cfg.bucket);\n }\n async logTransaction(txLog) {\n if (txLog) {\n if (txLog.request?.guid) {\n await this.s3TransactionLogCacheRatchet.writeObjectToCacheFile(AbstractBackgroundManager.backgroundGuidToPath(this.cfg.prefix, txLog.request.guid), txLog);\n }\n else {\n Logger.warn('Could not write transaction record - no guid defined : %j', txLog);\n }\n }\n else {\n Logger.silly('Skipping write of null log');\n }\n }\n async readTransactionLog(txGuid) {\n const path = AbstractBackgroundManager.backgroundGuidToPath(this.cfg.prefix, txGuid);\n const log = await this.s3TransactionLogCacheRatchet.fetchCacheFileAsObject(path);\n return log;\n }\n static validateConfig(cfg) {\n const rval = [];\n if (cfg) {\n if (!cfg.s3) {\n rval.push('You must supply an S3 object');\n }\n if (!cfg.bucket) {\n rval.push('You must supply a bucket');\n }\n if (!cfg.timeToLiveDays) {\n rval.push('You must supply a timeToLiveDays');\n }\n }\n else {\n rval.push('No config defined');\n }\n return rval;\n }\n}\n//# sourceMappingURL=s3-background-transaction-logger.js.map","import { ErrorRatchet } from '@bitblit/ratchet-common';\nimport { Logger } from '@bitblit/ratchet-common';\nimport { NumberRatchet } from '@bitblit/ratchet-common';\nimport { DeleteMessageCommand, GetQueueAttributesCommand, ReceiveMessageCommand, SendMessageCommand, } from '@aws-sdk/client-sqs';\nimport { EpsilonConstants } from '../../epsilon-constants.js';\nimport { AbstractBackgroundManager } from './abstract-background-manager.js';\nimport { BackgroundValidator } from '../background-validator.js';\nimport { PublishCommand } from '@aws-sdk/client-sns';\nexport class AwsSqsSnsBackgroundManager extends AbstractBackgroundManager {\n _awsConfig;\n _sqs;\n _sns;\n constructor(_awsConfig, _sqs, _sns) {\n super();\n this._awsConfig = _awsConfig;\n this._sqs = _sqs;\n this._sns = _sns;\n const cfgErrors = BackgroundValidator.validateAwsConfig(_awsConfig);\n if (cfgErrors.length) {\n ErrorRatchet.throwFormattedErr('Cannot start - invalid AWS config : %j', cfgErrors);\n }\n }\n get backgroundManagerName() {\n return 'AwsSqsSnsBackgroundManager';\n }\n get awsConfig() {\n return this._awsConfig;\n }\n get sqs() {\n return this._sqs;\n }\n get sns() {\n return this._sns;\n }\n async addEntryToQueue(entry, fireStartMessage) {\n try {\n const wrapped = this.wrapEntryForInternal(entry);\n const rval = wrapped.guid;\n const params = {\n DelaySeconds: 0,\n MessageBody: JSON.stringify(wrapped),\n MessageGroupId: entry.type,\n QueueUrl: this.awsConfig.queueUrl,\n };\n Logger.info('Add entry to queue (remote) : %j : Start : %s', params, fireStartMessage);\n const result = await this.sqs.send(new SendMessageCommand(params));\n if (fireStartMessage) {\n const fireResult = await this.fireStartProcessingRequest();\n Logger.silly('FireResult : %s', fireResult);\n }\n Logger.info('Background process %s using message id %s', rval, result.MessageId);\n return rval;\n }\n catch (error) {\n Logger.error('Error inserting background entry into SQS queue : %j', error);\n throw new Error('Error inserting background entry into SQS queue : ' + error['code'] + ' : ' + error['name']);\n }\n }\n async fireImmediateProcessRequest(entry) {\n let rval = null;\n const wrapped = this.wrapEntryForInternal(entry);\n rval = wrapped.guid;\n try {\n Logger.info('Fire immediately (remote) : %j ', entry);\n const toWrite = {\n type: EpsilonConstants.BACKGROUND_SNS_IMMEDIATE_RUN_FLAG,\n backgroundEntry: wrapped,\n };\n const msg = JSON.stringify(toWrite);\n const snsId = await this.writeMessageToSnsTopic(msg);\n Logger.debug('Background guid %s Wrote message : %s to SNS : %s', rval, msg, snsId);\n }\n catch (err) {\n Logger.error('Failed to fireImmediateProcessRequest : %s', err, err);\n }\n return rval;\n }\n async fireStartProcessingRequest() {\n let rval = null;\n try {\n Logger.info('Fire start processing request (remote)');\n rval = await this.writeMessageToSnsTopic(EpsilonConstants.BACKGROUND_SNS_START_MARKER);\n }\n catch (err) {\n Logger.error('Failed to fireStartProcessingRequest : %s', err, err);\n }\n return rval;\n }\n async fetchApproximateNumberOfQueueEntries() {\n let rval = null;\n const all = await this.fetchCurrentQueueAttributes();\n rval = NumberRatchet.safeNumber(all.Attributes['ApproximateNumberOfMessages']);\n return rval;\n }\n async fetchCurrentQueueAttributes() {\n let rval = null;\n const req = {\n AttributeNames: ['All'],\n QueueUrl: this.awsConfig.queueUrl,\n };\n rval = await this.sqs.send(new GetQueueAttributesCommand(req));\n return rval;\n }\n async writeMessageToSnsTopic(message) {\n let rval = null;\n const params = {\n Message: message,\n TopicArn: this.awsConfig.notificationArn,\n };\n Logger.debug('Writing message to SNS topic : j', params);\n const result = await this.sns.send(new PublishCommand(params));\n rval = result.MessageId;\n return rval;\n }\n async takeEntryFromBackgroundQueue() {\n const rval = [];\n const params = {\n MaxNumberOfMessages: 1,\n QueueUrl: this.awsConfig.queueUrl,\n VisibilityTimeout: 300,\n WaitTimeSeconds: 0,\n };\n const message = await this.sqs.send(new ReceiveMessageCommand(params));\n if (message && message.Messages && message.Messages.length > 0) {\n for (let i = 0; i < message.Messages.length; i++) {\n const m = message.Messages[i];\n try {\n const parsedBody = JSON.parse(m.Body);\n if (!parsedBody.type) {\n Logger.warn('Dropping invalid background entry : %j', parsedBody);\n }\n else {\n rval.push(parsedBody);\n }\n Logger.debug('Removing message from queue');\n const delParams = {\n QueueUrl: this.awsConfig.queueUrl,\n ReceiptHandle: m.ReceiptHandle,\n };\n const delResult = await this.sqs.send(new DeleteMessageCommand(delParams));\n Logger.silly('Delete result : %j', delResult);\n }\n catch (err) {\n Logger.warn('Error parsing message, dropping : %j', m);\n }\n }\n }\n else {\n Logger.debug('No messages found (likely end of recursion)');\n }\n return rval;\n }\n}\n//# sourceMappingURL=aws-sqs-sns-background-manager.js.map","export class RatchetEpsilonCommonInfo {\n constructor() { }\n static buildInformation() {\n const val = {\n version: 'LOCAL-SNAPSHOT',\n hash: 'LOCAL-HASH',\n branch: 'LOCAL-BRANCH',\n tag: 'LOCAL-TAG',\n timeBuiltISO: 'LOCAL-TIME-ISO',\n notes: 'LOCAL-NOTES',\n };\n return val;\n }\n}\n//# sourceMappingURL=ratchet-epsilon-common-info.js.map","import { StringRatchet } from '@bitblit/ratchet-common';\nimport { ContextUtil } from '../util/context-util.js';\nexport class BuiltInTraceIdGenerators {\n static fullAwsRequestId() {\n return ContextUtil.defaultedCurrentRequestId();\n }\n static shortAwsRequestId() {\n let rval = BuiltInTraceIdGenerators.fullAwsRequestId();\n if (rval.length > 10) {\n let idx = rval.lastIndexOf('-');\n idx = idx === -1 ? rval.length - 10 : idx;\n rval = rval.substring(idx);\n }\n return rval;\n }\n static fixedLengthHex(length = 10) {\n return StringRatchet.createRandomHexString(length);\n }\n}\n//# sourceMappingURL=built-in-trace-id-generators.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { PromiseRatchet } from '@bitblit/ratchet-common';\nimport { DurationRatchet } from '@bitblit/ratchet-common';\nimport { NumberRatchet } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nexport class RetryProcessor {\n delegate;\n opts;\n static RETRY_FIELD_NAME = '___RetryProcessorTryNumber';\n constructor(delegate, opts) {\n this.delegate = delegate;\n this.opts = opts;\n }\n get typeName() {\n return StringRatchet.trimToEmpty(this.opts?.typePrefix) + this.delegate.typeName + StringRatchet.trimToEmpty(this.opts?.typeSuffix);\n }\n async handleEvent(data, mgr) {\n const tryNumber = data && data[RetryProcessor.RETRY_FIELD_NAME] ? NumberRatchet.safeNumber(data[RetryProcessor.RETRY_FIELD_NAME]) : 1;\n const dataCopy = data ? Object.assign({}, data) : null;\n delete dataCopy[RetryProcessor.RETRY_FIELD_NAME];\n Logger.info('RetryProcessor : %s : Try %d of %d', this.delegate.typeName, tryNumber, this.opts.retryCount);\n try {\n await this.delegate.handleEvent(dataCopy, mgr);\n }\n catch (err) {\n Logger.error('Failed to process : %s', err, err);\n if (tryNumber < this.opts.retryCount) {\n const waitTimeMS = tryNumber * this.opts.baseDelayMS;\n Logger.info('Firing automatic retry after a wait of %s', DurationRatchet.formatMsDuration(waitTimeMS));\n await PromiseRatchet.wait(waitTimeMS);\n const wrapped = dataCopy || {};\n wrapped[RetryProcessor.RETRY_FIELD_NAME] = tryNumber + 1;\n await mgr.fireImmediateProcessRequestByParts(this.typeName, wrapped);\n }\n else {\n Logger.error('That was the last try - giving up');\n }\n }\n }\n}\n//# sourceMappingURL=retry-processor.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { NotFoundError } from '../../http/error/not-found-error.js';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nexport class DaemonHandler {\n daemon;\n inConfig;\n static ALLOW_EVERYTHING_AUTHORIZER = async (evt, proc) => {\n return true;\n };\n config;\n constructor(daemon, inConfig) {\n this.daemon = daemon;\n this.inConfig = inConfig;\n this.config = inConfig || {};\n this.config.authorizer = this.config.authorizer || DaemonHandler.ALLOW_EVERYTHING_AUTHORIZER;\n this.config.groupSelector = this.config.groupSelector || ((evt) => Promise.resolve(daemon.defaultGroup));\n this.config.fetchDaemonStatusByPublicTokenPathParameter =\n StringRatchet.trimToNull(this.config.fetchDaemonStatusByPublicTokenPathParameter) || 'publicToken';\n this.config.fetchDaemonStatusPathParameter = StringRatchet.trimToNull(this.config.fetchDaemonStatusPathParameter) || 'key';\n }\n async fetchDaemonStatusByPublicToken(evt) {\n const publicToken = evt.pathParameters[this.config.fetchDaemonStatusByPublicTokenPathParameter];\n Logger.info('Fetching daemon status for token: %s', publicToken);\n let rval = await this.daemon.statFromPublicToken(publicToken);\n const canRead = rval ? await this.config.authorizer(evt, rval) : false;\n rval = canRead ? rval : null;\n if (rval === null) {\n throw new NotFoundError('No such token : ' + publicToken);\n }\n return rval;\n }\n async fetchDaemonStatus(evt) {\n const daemonKey = evt.pathParameters[this.config.fetchDaemonStatusPathParameter];\n Logger.info('Fetching daemon status for : %s', daemonKey);\n let rval = await this.daemon.stat(daemonKey);\n const canRead = rval ? await this.config.authorizer(evt, rval) : false;\n rval = canRead ? rval : null;\n if (rval === null) {\n throw new NotFoundError('No such key : ' + daemonKey);\n }\n return rval;\n }\n async listDaemonStatus(evt) {\n const group = await this.config.groupSelector(evt);\n const keys = await this.daemon.list(group);\n const allowed = [];\n for (let i = 0; i < keys.length; i++) {\n const canRead = await this.config.authorizer(evt, keys[i]);\n if (canRead) {\n allowed.push(keys[i]);\n }\n }\n const rval = {\n results: allowed,\n nextToken: null,\n };\n return rval;\n }\n}\n//# sourceMappingURL=daemon-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { BooleanRatchet } from '@bitblit/ratchet-common';\nexport class RunBackgroundProcessFromCommandLine {\n static async runFromCliArgs(args) {\n if (args.length > 1) {\n const procName = args[0];\n const dryRun = args.length > 1 && BooleanRatchet.parseBool(args[1]);\n const data = args.length > 2 ? JSON.parse(args[2]) : null;\n const meta = args.length > 3 ? JSON.parse(args[3]) : null;\n const epsilon = null;\n if (dryRun) {\n Logger.info('Dry-Run, would have sent : %s %j %j', procName, data, meta);\n }\n else {\n await epsilon.processSingleBackgroundByParts(procName, data, meta);\n }\n }\n else {\n console.log('Usage : run-background-process {processName} {dryRun true/false} {dataJson} {metaJson}');\n }\n }\n}\n//# sourceMappingURL=run-background-process-from-command-line.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport net from 'net';\nexport class TestErrorServer {\n port;\n server;\n aborted = false;\n constructor(port = 9999) {\n this.port = port;\n }\n async runServer() {\n Logger.info('Starting Test Error net server on port %d', this.port);\n return new Promise((res, rej) => {\n const server = new net.Server({});\n server.listen(this.port, () => {\n Logger.info('Server listening for connection requests on socket localhost: %s', this.port);\n });\n server.on('connection', async (socket) => {\n Logger.info('X: A new connection has been established.');\n socket.write('Hello, client.');\n socket.on('data', (chunk) => {\n Logger.info('Data received from client: %s', chunk);\n });\n socket.on('end', () => {\n Logger.info('Closing connection with the client');\n });\n socket.on('error', (err) => {\n Logger.info('Error: %s', err);\n });\n });\n });\n }\n async requestHandler(request, response) {\n Logger.info('Got request %d - closing socket', request);\n request.setTimeout(100);\n response.end('x');\n }\n static async runFromCliArgs(args) {\n Logger.info('test-error-server requested (cli is %s) - starting', process?.argv);\n const testServer = new TestErrorServer();\n await testServer.runServer();\n Logger.info('Got res server');\n process.exit(0);\n }\n}\n//# sourceMappingURL=test-error-server.js.map","import { AbstractRatchetCliHandler } from '@bitblit/ratchet-node-only';\nimport { RunBackgroundProcessFromCommandLine } from './run-background-process-from-command-line.js';\nimport { TestErrorServer } from '../sample/test-error-server.js';\nimport { LocalContainerServer } from '../local-container-server.js';\nimport { RatchetEpsilonCommonInfo } from '../build/ratchet-epsilon-common-info.js';\nimport { LocalServer } from '../local-server.js';\nexport class RatchetCliHandler extends AbstractRatchetCliHandler {\n fetchHandlerMap() {\n return {\n 'run-background-process': RunBackgroundProcessFromCommandLine.runFromCliArgs,\n 'run-test-error-server': TestErrorServer.runFromCliArgs,\n 'run-local-container-server': LocalContainerServer.runFromCliArgs,\n 'run-sample-local-server': LocalServer.runSampleLocalServerFromCliArgs,\n 'run-sample-local-batch-server': LocalServer.runSampleLocalServerFromCliArgs,\n };\n }\n fetchVersionInfo() {\n return RatchetEpsilonCommonInfo.buildInformation();\n }\n}\n//# sourceMappingURL=ratchet-cli-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { LocalWebTokenManipulator } from './local-web-token-manipulator.js';\nimport { EpsilonConstants } from '../../epsilon-constants.js';\nexport class ApiGatewayAdapterAuthenticationHandler {\n webTokenManipulator;\n constructor(issuer, encryptionKeys) {\n this.webTokenManipulator = new LocalWebTokenManipulator([encryptionKeys], issuer);\n }\n lambdaHandler(event, context, callback) {\n Logger.info('Got event : %j', event);\n const srcString = ApiGatewayAdapterAuthenticationHandler.extractTokenStringFromAuthorizerEvent(event);\n if (srcString) {\n const methodArn = event.methodArn;\n this.webTokenManipulator\n .parseAndValidateJWTStringAsync(srcString)\n .then((parsed) => {\n if (parsed) {\n callback(null, this.createPolicy(methodArn, srcString, parsed));\n }\n else {\n Logger.info('Invalid bearer token');\n callback(new Error('Unauthorized'));\n }\n })\n .catch((err) => {\n Logger.error('Exception parsing token : %s', err);\n callback(new Error('Unauthorized'));\n });\n }\n else {\n Logger.info('Token not supplied');\n callback(new Error('Unauthorized'));\n }\n }\n createPolicy(methodArn, srcString, userOb) {\n const tmp = methodArn.split(':');\n const apiGatewayArnTmp = tmp[5].split('/');\n const awsAccountId = tmp[4];\n const region = tmp[3];\n const stage = apiGatewayArnTmp[1];\n const restApiId = apiGatewayArnTmp[0];\n const response = {\n principalId: 'user',\n policyDocument: {\n Version: '2012-10-17',\n Statement: [\n {\n Action: 'execute-api:Invoke',\n Effect: 'Allow',\n Resource: ['arn:aws:execute-api:' + region + ':' + awsAccountId + ':' + restApiId + '/' + stage + '/*/*'],\n },\n ],\n },\n context: {\n userJSON: JSON.stringify(userOb),\n srcData: srcString,\n },\n };\n return response;\n }\n static extractTokenStringFromAuthorizerEvent(event) {\n Logger.silly('Extracting token from event : %j', event);\n let rval = null;\n if (event && event.authorizationToken) {\n const token = event.authorizationToken;\n if (token && token.startsWith(EpsilonConstants.AUTH_HEADER_PREFIX)) {\n rval = token.substring(EpsilonConstants.AUTH_HEADER_PREFIX.length);\n }\n }\n return rval;\n }\n}\n//# sourceMappingURL=api-gateway-adapter-authentication-handler.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport jwt from 'jsonwebtoken';\nimport jwks from 'jwks-rsa';\nexport class Auth0WebTokenManipulator {\n clientId;\n jwksUri;\n issuer;\n jwksClient;\n constructor(clientId, jwksUri, issuer) {\n this.clientId = clientId;\n this.jwksUri = jwksUri;\n this.issuer = issuer;\n }\n async extractTokenFromAuthorizationHeader(authHeader) {\n let tokenString = StringRatchet.trimToEmpty(authHeader);\n if (tokenString.toLowerCase().startsWith('bearer ')) {\n tokenString = tokenString.substring(7);\n }\n const validated = tokenString ? await this.parseAndValidateAuth0Token(tokenString, false) : null;\n return validated;\n }\n async parseAndValidateAuth0Token(auth0Token, allowExpired = false) {\n Logger.debug('Validating Auth0 token : %s', StringRatchet.obscure(auth0Token, 4));\n const fullToken = jwt.decode(auth0Token, { complete: true });\n const kid = fullToken?.header?.kid;\n const nowEpochSeconds = Math.floor(new Date().getTime() / 1000);\n const pubKey = await this.fetchSigningKey(kid);\n const validated = jwt.verify(auth0Token, pubKey, {\n audience: this.clientId,\n issuer: this.issuer,\n ignoreExpiration: allowExpired,\n clockTimestamp: nowEpochSeconds,\n });\n return validated;\n }\n async fetchSigningKey(kid) {\n const jClient = await this.fetchJwksClient();\n return new Promise((res, rej) => {\n jClient.getSigningKey(kid, (err, key) => {\n if (err) {\n rej(err);\n }\n else {\n res(key.publicKey || key.rsaPublicKey);\n }\n });\n });\n }\n async fetchJwksClient() {\n if (!this.jwksClient) {\n this.jwksClient = jwks({\n cache: true,\n cacheMaxEntries: 5,\n cacheMaxAge: 1000 * 60 * 60 * 10,\n jwksUri: this.jwksUri,\n });\n }\n return this.jwksClient;\n }\n}\n//# sourceMappingURL=auth0-web-token-manipulator.js.map","import { Logger } from '@bitblit/ratchet-common';\nimport { StringRatchet } from '@bitblit/ratchet-common';\nimport jwt from 'jsonwebtoken';\nimport jwks from 'jwks-rsa';\nimport fetch from 'cross-fetch';\nexport class GoogleWebTokenManipulator {\n clientId;\n static GOOGLE_DISCOVERY_DOCUMENT = 'https://accounts.google.com/.well-known/openid-configuration';\n cacheGoogleDiscoveryDocument;\n jwksClient;\n constructor(clientId) {\n this.clientId = clientId;\n }\n async extractTokenFromAuthorizationHeader(authHeader) {\n let tokenString = StringRatchet.trimToEmpty(authHeader);\n if (tokenString.toLowerCase().startsWith('bearer ')) {\n tokenString = tokenString.substring(7);\n }\n const validated = !!tokenString ? await this.parseAndValidateGoogleToken(tokenString, false) : null;\n return validated;\n }\n async parseAndValidateGoogleToken(googleToken, allowExpired = false) {\n Logger.debug('Auth : %s', StringRatchet.obscure(googleToken, 4));\n const fullToken = jwt.decode(googleToken, { complete: true });\n const kid = fullToken.header.kid;\n const nowEpochSeconds = Math.floor(new Date().getTime() / 1000);\n const pubKey = await this.fetchSigningKey(kid);\n const validated = jwt.verify(googleToken, pubKey, {\n audience: this.clientId,\n issuer: ['https://accounts.google.com', 'accounts.google.com'],\n ignoreExpiration: allowExpired,\n clockTimestamp: nowEpochSeconds,\n });\n return validated;\n }\n async fetchSigningKey(kid) {\n const jClient = await this.fetchJwksClient();\n return new Promise((res, rej) => {\n jClient.getSigningKey(kid, (err, key) => {\n if (err) {\n rej(err);\n }\n else {\n res(key.publicKey || key.rsaPublicKey);\n }\n });\n });\n }\n async fetchJwksClient() {\n if (!this.jwksClient) {\n const discDoc = await this.fetchGoogleDiscoveryDocument();\n const client = jwks({\n cache: true,\n cacheMaxEntries: 5,\n cacheMaxAge: 1000 * 60 * 60 * 10,\n jwksUri: discDoc.jwks_uri,\n });\n this.jwksClient = client;\n }\n return this.jwksClient;\n }\n async fetchGoogleDiscoveryDocument() {\n if (!this.cacheGoogleDiscoveryDocument) {\n const resp = await fetch(GoogleWebTokenManipulator.GOOGLE_DISCOVERY_DOCUMENT);\n const doc = await resp.json();\n this.cacheGoogleDiscoveryDocument = doc;\n }\n return this.cacheGoogleDiscoveryDocument;\n }\n}\n//# sourceMappingURL=google-web-token-manipulator.js.map","import { StringRatchet } from '@bitblit/ratchet-common';\nimport { RequireRatchet } from '@bitblit/ratchet-common';\nimport { ExpiredJwtHandling } from '@bitblit/ratchet-common';\nexport class JwtRatchetLocalWebTokenManipulator {\n _jwtRatchet;\n _issuer;\n constructor(_jwtRatchet, _issuer) {\n this._jwtRatchet = _jwtRatchet;\n this._issuer = _issuer;\n RequireRatchet.notNullOrUndefined(_jwtRatchet, '_jwtRatchet');\n RequireRatchet.notNullOrUndefined(StringRatchet.trimToNull(_issuer), '_issuer');\n }\n get jwtRatchet() {\n return this._jwtRatchet;\n }\n get issuer() {\n return this._issuer;\n }\n async extractTokenFromAuthorizationHeader(header) {\n let tokenString = StringRatchet.trimToEmpty(header);\n if (tokenString.toLowerCase().startsWith('bearer ')) {\n tokenString = tokenString.substring(7);\n }\n const validated = !!tokenString ? await this.jwtRatchet.decodeToken(tokenString, ExpiredJwtHandling.THROW_EXCEPTION) : null;\n return validated;\n }\n}\n//# sourceMappingURL=jwt-ratchet-local-web-token-manipulator.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class BadGateway extends RestfulApiHttpError {\n static HTTP_CODE = 502;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(BadGateway.HTTP_CODE);\n }\n}\n//# sourceMappingURL=bad-gateway.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class ConflictError extends RestfulApiHttpError {\n static HTTP_CODE = 409;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(ConflictError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=conflict-error.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class GatewayTimeout extends RestfulApiHttpError {\n static HTTP_CODE = 504;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(GatewayTimeout.HTTP_CODE);\n }\n}\n//# sourceMappingURL=gateway-timeout.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class MethodNotAllowedError extends RestfulApiHttpError {\n static HTTP_CODE = 405;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(MethodNotAllowedError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=method-not-allowed-error.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class ServiceUnavailable extends RestfulApiHttpError {\n static HTTP_CODE = 503;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(ServiceUnavailable.HTTP_CODE);\n }\n}\n//# sourceMappingURL=service-unavailable.js.map","import { RestfulApiHttpError } from '@bitblit/ratchet-common';\nexport class TooManyRequestsError extends RestfulApiHttpError {\n static HTTP_CODE = 429;\n constructor(...errors) {\n super(...errors);\n this.withHttpStatusCode(TooManyRequestsError.HTTP_CODE);\n }\n}\n//# sourceMappingURL=too-many-requests-error.js.map","import yaml from 'js-yaml';\nimport { Logger } from '@bitblit/ratchet-common';\nexport class OpenApiDocModifier {\n options;\n constructor(options) {\n this.options = options;\n }\n modifyOpenApiDoc(yamlString) {\n let rval;\n if (!!yamlString && !!this.options) {\n try {\n const openApi = yaml.load(yamlString);\n const removeTags = this.options.removeTags ? this.options.removeTags.map((t) => t.toLowerCase()) : [];\n if (this.options.newServerPath) {\n openApi['servers'] = [{ url: this.options.newServerPath }];\n }\n if (!!this.options.removeTags && openApi['tags']) {\n if (openApi['tags']) {\n openApi['tags'] = openApi.tags.filter((f) => {\n const n = !!f && !!f['name'] ? f['name'].toLowerCase() : '';\n const i = removeTags.indexOf(n);\n return i === -1;\n });\n }\n }\n if (openApi['paths']) {\n let newPaths = {};\n Object.keys(openApi['paths']).forEach((p) => {\n const path = openApi['paths'][p];\n Object.keys(path).forEach((verb) => {\n const entry = path[verb];\n entry.tags = !!entry.tags ? entry.tags.filter((t) => removeTags.lastIndexOf(t.toLowerCase()) == -1) : entry.tags;\n const matcher = verb.toLowerCase() + ' ' + p.toLowerCase();\n if (this.matchNone(matcher, this.options.removeEndpoints)) {\n newPaths[p] = newPaths[p] || {};\n newPaths[p][verb] = entry;\n }\n });\n });\n if (this.options.sortEndpoints) {\n const keys = Object.keys(newPaths).sort();\n const newPaths2 = {};\n keys.forEach((k) => {\n newPaths2[k] = newPaths[k];\n });\n newPaths = newPaths2;\n }\n openApi['paths'] = newPaths;\n }\n let remSchemas = this.options.removeSchemas || [];\n remSchemas = remSchemas.map((s) => s.toLowerCase());\n if (openApi['components'] && openApi['components']['schemas']) {\n const keys = Object.keys(openApi['components']['schemas']).sort();\n const newComp = {};\n keys.forEach((k) => {\n if (remSchemas.indexOf(k.toLowerCase()) === -1) {\n newComp[k] = openApi['components']['schemas'][k];\n }\n });\n openApi['components']['schemas'] = newComp;\n }\n rval = yaml.dump(openApi);\n }\n catch (err) {\n Logger.error('Error processing yaml: %s', err, err);\n }\n }\n return rval;\n }\n matchNone(input, regex) {\n let rval = true;\n if (!!input && !!regex) {\n regex.forEach((r) => {\n rval = rval && !r.test(input);\n });\n }\n return rval;\n }\n}\n//# sourceMappingURL=open-api-doc-modifier.js.map","import fs from 'fs';\nimport { RequireRatchet } from '@bitblit/ratchet-common';\nimport yaml from 'js-yaml';\nimport { Logger } from '@bitblit/ratchet-common';\nexport class YamlCombiner {\n static combine(files, inRootPath = []) {\n RequireRatchet.notNullOrUndefined(files, 'Files argument');\n RequireRatchet.true(files.length > 0, 'Files argument larger than 0');\n RequireRatchet.notNullOrUndefined(inRootPath, 'Root path argument');\n Logger.info('Processing %d files into output', files.length);\n let allElements = {};\n for (let i = 0; i < files.length; i++) {\n const fileContents = fs.readFileSync(files[i]).toString();\n const openApi = yaml.load(fileContents);\n allElements = Object.assign(allElements, openApi);\n }\n const rootPath = Object.assign([], inRootPath);\n while (rootPath.length > 0) {\n const next = {};\n next[rootPath[rootPath.length - 1]] = allElements;\n rootPath.splice(rootPath.length - 1, 1);\n allElements = next;\n }\n const rval = yaml.dump(allElements);\n return rval;\n }\n}\n//# sourceMappingURL=yaml-combiner.js.map"],"names":["EpsilonBuildProperties","constructor","buildVersion","buildHash","buildBranch","buildTag","buildBranchOrTag","StringRatchet","trimToNull","buildTime","EpsilonConstants","static","load","filePath","className","Logger","info","EsmRatchet","fetchDirName","url","rval","val","require","debug","Object","keys","findDynamicImportEpsilonGlobalHandlerProvider","importPath","process","env","EPSILON_FINDER_DYNAMIC_IMPORT_PATH_ENV_NAME","DEFAULT_EPSILON_FINDER_DYNAMIC_IMPORT_PATH","fnName","EPSILON_FINDER_FUNCTION_NAME_ENV_NAME","DEFAULT_EPSILON_FINDER_FUNCTION_NAME","provider","this","err","error","UnauthorizedError","RestfulApiHttpError","errors","super","withHttpStatusCode","HTTP_CODE","BadRequestError","EventUtil","extractStage","event","path","startsWith","idx","indexOf","substring","extractHostHeader","MapRatchet","extractValueFromMapIgnoreCase","headers","extractProtocol","extractApiGatewayStage","rc","extractRequestContext","stage","requestContext","extractAuthorizer","authorizer","ipAddressChain","headerVal","headerList","String","split","map","s","trim","ipAddress","list","length","extractFullPath","overrideProtocol","extractFullPrefix","protocol","prefix","jsonBodyToObject","body","contentType","isBase64Encoded","Buffer","from","JSON","parse","toString","calcLogLevelViaEventOrEnvParam","curLevel","rConfig","envParamLogLevelName","EnumRatchet","keyToEnum","LoggerLevelName","silly","queryParamLogLevelName","queryStringParameters","fixStillEncodedQueryParams","newParams","forEach","k","toLowerCase","multiValueQueryStringParameters","applyTokenToEventForTesting","jwtToken","jwtFullData","jwt","decode","complete","Error","jwtData","AUTH_HEADER_NAME","newAuth","assign","userData","userDataJSON","stringify","srcData","extractBasicAuthenticationToken","throwErrorOnMissingBad","extractAuthorizationHeaderCaseInsensitive","sp","Base64Ratchet","base64StringToString","username","password","eventIsAGraphQLIntrospection","httpMethod","endsWith","evt","caseInsensitiveAccess","extractBearerTokenFromEvent","authHeader","trimToEmpty","hostIsLocal","host","includes","hostIsLocalOrNotRoutableIP4","ResponseUtil","errorResponse","httpStatusCode","requestId","detailErrorCode","endUserErrors","details","wrappedError","name","message","statusCode","redirect","target","code","queryParams","redirectTarget","i","encodeURIComponent","Location","coerceToProxyResult","input","undefined","isBuffer","applyGzipIfPossible","encodingHeader","proxyResult","bigEnough","exemptContent","asBuffer","zipped","gzip","zipped64","Promise","resolve","reject","zlib","result","RequestTimeoutError","ContextUtil","initContext","epsilon","ctx","processLabel","CURRENT_EPSILON_REFERENCE","CURRENT_CONTEXT","CURRENT_EVENT","CURRENT_LOG_VARS","CURRENT_PROCESS_LABEL","clearContext","CURRENT_OVERRIDE_TRACE_ID","CURRENT_OVERRIDE_TRACE_DEPTH","setOverrideTrace","traceId","traceDepth","setOverrideTraceFromInternalBackgroundEntry","entry","setOverrideTraceFromInterApiEntry","interApiEntry","addHeadersToRecord","depthOffset","traceHeaderName","currentTraceId","traceDepthHeaderName","safeString","currentTraceDepth","ErrorRatchet","throwFormattedErr","addTraceToProxyResult","pr","addTraceToHttpRequestInit","ri","setProcessLabel","currentRequestId","awsRequestId","defaultedCurrentRequestId","defaultValueIfMissing","createType4Guid","remainingTimeMS","getRemainingTimeInMillis","currentProcessLabel","config","loggerConfig","traceFn","traceIdGenerator","NumberRatchet","safeNumber","addLogVariable","fetchLogVariable","fetchLogVariables","AwsUtil","apiGatewayV2ToApiGatewayV1","srcEvt","apiGatewayV2RequestContextToApiGatewayV1RequestContext","http","method","multiValueHeaders","pathParameters","stageVariables","resource","accountId","apiId","domainName","domainPrefix","routeKey","requestTime","time","requestTimeEpoch","timeEpoch","identity","resourceId","resourcePath","findInMap","toFind","key","matchExact","r","str","match","resolvePotentialFunctionToResult","src","def","WebV2Handler","webHandler","extractLabel","context","replace","handlesEvent","LambdaEventDetector","isValidApiGatewayV2WithRequestContextEvent","processEvent","conv","asExtended","parsedBody","authorization","convertedFromV2Event","openApiLambdaHandler","InterApiUtil","isInterApiSnsEvent","extractEntryFromEvent","isSingleSnsEvent","msg","Records","Sns","Message","parsed","INTER_API_SNS_EVENT","processInterApiEvent","cfg","mgr","RequireRatchet","notNullOrUndefined","backgroundEntries","processMappings","disabled","source","sourceRegex","type","typeRegex","backgroundProcessTypes","taskName","createEntry","data","push","addEntriesToQueue","addTraceToInterApiEntry","ent","InterApiEpsilonLambdaEventHandler","_epsilon","interApiConfig","tmp","backgroundManager","GenericSnsEpsilonLambdaEventHandler","EventSource","isValidSnsEvent","sns","finder","TopicArn","handler","handlers","CronUtil","everyNMinuteFilter","n","everyNElementFilter","everyNDaysOfYearFilter","m","half","Math","floor","numberMatchesFilter","num","filter","eventMatchesEntry","testTimeEpochMS","Date","getTime","timezone","resources","eventSourceName","targetTZ","overrideTimezone","nowInTZ","DateTime","fromMillis","setZone","eventFilter","test","minute","minuteFilter","hour","hourFilter","weekday","dayOfWeekFilter","day","dayOfMonthFilter","month","monthOfYearFilter","contextMatchFilter","contextNoMatchFilter","cronEntryName","CronEpsilonLambdaEventHandler","isValidCronEvent","cron","processCronEvent","backgroundHandler","cronConfig","background","entries","toEnqueue","smCronEntry","backgroundEntry","backgroundTaskType","fireImmediate","fireImmediateProcessRequest","warn","S3EpsilonLambdaEventHandler","eventSource","isValidS3Event","s3","bucket","object","eventName","removeHandlers","createHandlers","DynamoEpsilonLambdaEventHandler","isValidDynamoDBEvent","dynamoDb","eventSourceARN","processUncaughtError","EpsilonLoggingExtensionProcessor","params","now","label","EpsilonGlobalHandler","globalInstanceProvider","GLOBAL_INSTANCE_PROVIDER","LOGGER_CONFIGURED","configureDefaultLogger","overrides","output","initialLevel","formatType","LogMessageFormatType","StructuredJson","globalVars","outputFunction","LoggerOutputFunction","StdOut","ringBufferSize","preProcessors","concat","getOptions","changeDefaultOptions","dumpOptionsIntoLog","processSingleBackgroundByParts","overrideTraceId","overrideTraceDepth","processSingleBackgroundEntry","e","internal","wrapEntryForInternal","lambdaHandler","disableLastResortTimeout","PromiseRatchet","timeout","innerLambdaHandler","TimeoutToken","isTimeoutToken","writeToLog","wrapError","errorHandler","defaultProcessUncaughtError","logLevel","getLevel","setLevel","queryParamTracePrefixName","updateTracePrefix","found","logByLevel","epsilonStartEndMessageLogLevel","safeStringifyErr","InterApiManager","_aws","_sns","fireInterApiEventByParts","fireInterApiEvent","localMode","toWrite","interApiEvent","snsId","writeMessageToSnsTopic","snsArn","send","PublishCommand","MessageId","LocalServerCert","NotFoundError","ForbiddenError","NotImplemented","MisconfiguredError","BuiltInHandlers","expectedHandledByFilter","flag","withFormattedErrorMessage","handleNotImplemented","toLocaleString","sample","pad","createRandomHexString","errNumber","withDetails","withEndUserErrors","defaultErrorProcessor","stack","LocalWebTokenManipulator","encryptionKeys","issuer","_ratchet","noNullOrUndefinedValuesInArray","JwtRatchet","withExtraDecryptionKeys","encryptionKeyPromise","jtiGenerator","decryptOnlyKeyUseLogLevel","parseFailureLogLevel","withParseFailureLogLevel","decryptKeysPromise","withOldKeyUseLogLevel","jwtRatchet","selectRandomEncryptionKey","createRefreshedJWTString","tokenString","expirationSeconds","allowExpired","refreshJWTString","parseAndValidateJWTStringAsync","payload","decodeToken","ExpiredJwtHandling","ADD_FLAG","hasExpiredFlag","exp","createJWTStringAsync","principal","userObject","roles","proxyUser","tokenData","iss","sub","iat","user","proxy","createTokenString","extractTokenFromAuthorizationHeader","header","EchoProcessor","typeName","TYPE_NAME","handleEvent","NoOpProcessor","SampleDelayProcessor","delayMS","random","wait","LogAndEnqueueEchoProcessor","fireImmediateProcessRequestByParts","upstream","BackgroundProcessHandling","BackgroundExecutionEventType","NullReturnedObjectHandling","EpsilonApolloCorsMethod","BackgroundHttpAdapterHandler","backgroundConfig","modelValidator","maxWaitInMsForBackgroundJobToStart","httpMetaEndpoint","httpSubmissionPath","httpStatusPath","httpStatusEndpoint","implyTypeFromPathSuffix","handleBackgroundStatusRequest","transactionLogger","guid","sw","StopWatch","log","elapsedMS","readTransactionLog","dump","handleBackgroundMetaRequest","currentCount","fetchApproximateNumberOfQueueEntries","valid","processors","b","a","sort","localeCompare","currentQueueLength","validTypes","backgroundManagerName","handleBackgroundSubmission","startIdx","pathSuppliedBackgroundType","join","toLocaleLowerCase","foundProc","find","immediate","BooleanRatchet","parseBool","startProcessor","dataSchemaName","validate","withErrors","addEntryToQueue","processHandling","Immediate","Queued","startProcessorRequested","success","resultId","BackgroundValidator","findProcessor","validType","validateEntry","validateEntryAndThrowException","validateAndMapProcessors","processorInput","Map","p","has","set","validateAwsConfig","notificationArn","queueUrl","sendNotificationOnBackgroundError","sendNotificationOnBackgroundValidationFailure","backgroundProcessFailureSnsArn","validateConfig","AbstractBackgroundManager","createdEpochMS","generateBackgroundGuid","addEntryToQueueByParts","fireStartMessage","fireResult","fireStartProcessingRequest","targetEpochMS","toFormat","backgroundGuidToPath","pathToBackgroundGuid","start","BackgroundHandler","validator","cfgErrors","immediateProcessQueue","subscribe","async","isBackgroundStartSnsEvent","isBackgroundImmediateFireEvent","pEvt","parseImmediateFireBackgroundEntry","isBackgroundSNSEvent","BACKGROUND_SNS_START_MARKER","BACKGROUND_SNS_IMMEDIATE_RUN_FLAG","procd","takeAndProcessSingleBackgroundQueueEntry","refire","takeEntryFromBackgroundQueue","safeWriteToLogger","logTransaction","conditionallyStartTransactionLog","request","running","conditionallyCompleteTransactionLog","runtimeMS","conditionallyRunErrorProcessor","errorProcessor","handleError","fireListenerEvent","listeners","executionListeners","listener","onEvent","ProcessStarting","processorType","get","NoMatchProcessorName","dataValidationErrors","DataValidationError","ExecutionSuccessfullyComplete","ExecutionFailedError","getConfig","BuiltInFilters","combineFilters","fCtx","filters","cont","addConstantHeaders","addAWSRequestIdHeader","headerName","addAllowEverythingCORSHeaders","addAllowReflectionCORSHeaders","uriDecodeQueryParams","decodeURIComponent","cleaned","v","disallowStringNullAsPathParameter","disallowStringNullAsQueryStringParameter","ensureEventMaps","parseJsonBodyToObject","checkMaximumLambdaBodySize","MAXIMUM_LAMBDA_BODY_SIZE_BYTES","delta","validateInboundBody","routeAndParse","mapping","validation","modelName","emptyAllowed","extraPropertiesAllowed","validateInboundQueryParams","validateInboundPathParams","validateOutboundResponse","rawResult","outboundValidation","unshift","autoRespondToOptionsRequestWithCors","autoRespond","inBody","secureOutboundServerErrorForProduction","errorMessage","errCode","oldResult","BuiltInAuthFilters","requireAllRolesInCommonJwt","requiredRoleAllOf","auth","asJwt","requireAnyRoleInCommonJwt","requiredRoleOneOf","parseAuthorizationHeader","webTokenManipulators","Array","isArray","manipulator","token","raw","applyOpenApiAuthorization","authorizerName","authenticators","LogLevelManipulationFilter","setLogLevelForTransaction","LOG_LEVEL_BEFORE_CHANGE","clearLogLevelForTransaction","RouterUtil","defaultAuthenticationHeaderParsingEpsilonPreFilters","webTokenManipulator","defaultEpsilonPreFilters","defaultEpsilonPostFilters","defaultEpsilonErrorFilters","defaultHttpMetaProcessingConfigWithAuthenticationHeaderParsing","configName","timeoutMS","overrideAuthorizerName","preFilters","postFilters","errorFilters","nullReturnedObjectHandling","Return404NotFoundResponse","defaultHttpMetaProcessingConfig","assignDefaultsOnHttpConfig","defaults","authorizers","defaultMetaHandling","staticContentRoutes","prefixesToStripBeforeRouteMatch","filterHandledRouteMatches","findApplicableMeta","httpConfig","overrideMetaHandling","methods","matches","pathRegex","invertPathMatching","openApiYamlToRouterConfig","openApiDoc","backgroundHttpAdapterHandler","routes","openApiModelValidator","components","securitySchemes","sk","missingPaths","filterHandledPathMatches","paths","convertedPath","openApiPathToRouteParserPath","applicableMeta","isBackgroundEndpoint","isBackgroundMetaEndpoint","isBackgroundStatusEndpoint","reg","newRoute","function","metaProcessingConfig","schema","findAndValidateModelName","overrideModelValidator","schemaPath","inlinePath","lastIndexOf","fetchModel","model","addModel","sIdx","eIdx","RunHandlerAsFilter","runHandler","rm","findHandler","applyNullReturnedObjectHandling","handling","ConvertToEmptyString","add404OnMissing","addRunHandlerAsFilterToList","WebHandler","routerConfig","router","toUpperCase","isValidApiGatewayEvent","findBestMatchingRoute","procConfig","filterChain","wrapper","convErr","cleanPath","methodLower","matchRoutes","routeParser","Route","route","EpsilonConfigParser","epsilonConfigToEpsilonGlobalHandler","epsilonConfigToEpsilonInstance","validateGlobalConfig","parseOpenApiDocument","openApiYamlString","openApiDocToValidator","backgroundHttpAdapter","epsilonRouter","parsedOpenApiDoc","yamlString","yaml","doc","schemas","ModelValidator","createFromParsedObject","SampleInputValidatedProcessor","BuiltInAuthorizers","simpleNoAuthenticationLogAccess","authorizationContext","simpleLoggedInAuth","simpleRoleRouteAuth","ApolloUtil","emptyContext","defaultEpsilonApolloContext","args","authTokenSt","lambdaEvent","RETURN_NULL","bearerTokenString","functionName","lambdaContext","nonRouteableOnlyEpsilonApolloContext","hostName","ApolloFilter","handlePathWithApollo","apolloPathRegex","apolloServer","options","processApolloRequest","corsMethod","All","Reflective","assertStarted","headerMap","HeaderMap","headersKey","eventMethod","bodyString","aRequest","search","contextFn","apolloPromise","executeHTTPGraphQLRequest","httpGraphQLRequest","httpGraphQLResponse","outHeaders","headersValue","kind","withRequestId","bodyAsString","string","generateBase64VersionOfString","status","addApolloFilterToList","LogMessageBackgroundErrorProcessor","submission","SingleThreadLocalBackgroundManager","_localBus","Subject","wrapped","next","SampleServerStaticFiles","SampleServerComponents","createSampleApollo","gqlString","SAMPLE_SERVER_GRAPHQL","typeDefs","gql","server","ApolloServer","introspection","resolvers","RootQueryType","serverMeta","root","version","serverTime","toISOString","forceTimeout","placeholder","plugins","ApolloServerPluginLandingPageLocalDefault","footer","createSampleEpsilonConfig","SAMPLE_OPEN_API_DOC","fErr","numberParam","nameParam","tokenManipulator","meta","RegExp","arg","preFiltersAllowingNull","splice","createSampleEpsilonGlobalHandler","epsilonConfig","epsilonInstance","createSampleBatchOnlyEpsilonGlobalHandler","byPassCfg","LocalServer","globalHandler","port","aborted","https","runServer","res","rej","CLIENT_KEY_PEM","cert","CLIENT_CERT_PEM","createServer","requestHandler","bind","listen","on","response","messageToApiGatewayEvent","writeProxyResultToServerResponse","bodyAsBase64String","chunk","stageIdx","reqTime","formattedTime","utc","queryIdx","queryStringParams","qs","baz","hk","setHeader","end","runSampleBatchOnlyServerFromCliArgs","testServer","runSampleLocalServerFromCliArgs","localTokenHandler","LocalContainerServer","logEventLevel","postResp","fetch","json","runFromCliArgs","argv","exit","BackgroundDynamoLogTableHandler","dynamo","tableName","backgroundQueueName","processTypeName","state","timestampEpochMs","simplePut","EpsilonBackgroundProcessError","_errors","_detailErrorCode","_details","_requestId","_wrappedError","combineErrorStringsWithDefault","setPrototypeOf","prototype","EPSILON_BACKGROUND_PROCESS_ERROR_FLAG_KEY","defMessage","setFormattedErrorMessage","format","util","withDetailErrorCode","withWrappedError","isWrappedError","objectIsEpsilonBackgroundProcessError","obj","value","S3BackgroundTransactionLogger","s3TransactionLogCacheRatchet","S3CacheRatchet","txLog","writeObjectToCacheFile","txGuid","fetchCacheFileAsObject","timeToLiveDays","AwsSqsSnsBackgroundManager","_awsConfig","_sqs","awsConfig","sqs","DelaySeconds","MessageBody","MessageGroupId","QueueUrl","SendMessageCommand","all","fetchCurrentQueueAttributes","Attributes","req","AttributeNames","GetQueueAttributesCommand","MaxNumberOfMessages","VisibilityTimeout","WaitTimeSeconds","ReceiveMessageCommand","Messages","Body","delParams","ReceiptHandle","delResult","DeleteMessageCommand","RatchetEpsilonCommonInfo","buildInformation","hash","branch","tag","timeBuiltISO","notes","BuiltInTraceIdGenerators","fullAwsRequestId","shortAwsRequestId","fixedLengthHex","RetryProcessor","delegate","opts","typePrefix","typeSuffix","tryNumber","RETRY_FIELD_NAME","dataCopy","retryCount","waitTimeMS","baseDelayMS","DurationRatchet","formatMsDuration","DaemonHandler","daemon","inConfig","proc","ALLOW_EVERYTHING_AUTHORIZER","groupSelector","defaultGroup","fetchDaemonStatusByPublicTokenPathParameter","fetchDaemonStatusPathParameter","fetchDaemonStatusByPublicToken","publicToken","statFromPublicToken","fetchDaemonStatus","daemonKey","stat","listDaemonStatus","group","allowed","results","nextToken","RunBackgroundProcessFromCommandLine","procName","dryRun","console","TestErrorServer","net","Server","socket","write","setTimeout","RatchetCliHandler","AbstractRatchetCliHandler","fetchHandlerMap","fetchVersionInfo","ApiGatewayAdapterAuthenticationHandler","callback","srcString","extractTokenStringFromAuthorizerEvent","methodArn","then","createPolicy","catch","userOb","apiGatewayArnTmp","awsAccountId","region","principalId","policyDocument","Version","Statement","Action","Effect","Resource","userJSON","authorizationToken","AUTH_HEADER_PREFIX","Auth0WebTokenManipulator","clientId","jwksUri","jwksClient","parseAndValidateAuth0Token","auth0Token","obscure","fullToken","kid","nowEpochSeconds","pubKey","fetchSigningKey","verify","audience","ignoreExpiration","clockTimestamp","jClient","fetchJwksClient","getSigningKey","publicKey","rsaPublicKey","jwks","cache","cacheMaxEntries","cacheMaxAge","GoogleWebTokenManipulator","cacheGoogleDiscoveryDocument","parseAndValidateGoogleToken","googleToken","discDoc","fetchGoogleDiscoveryDocument","client","jwks_uri","resp","GOOGLE_DISCOVERY_DOCUMENT","JwtRatchetLocalWebTokenManipulator","_jwtRatchet","_issuer","THROW_EXCEPTION","BadGateway","ConflictError","GatewayTimeout","MethodNotAllowedError","ServiceUnavailable","TooManyRequestsError","OpenApiDocModifier","modifyOpenApiDoc","openApi","removeTags","t","newServerPath","tags","f","newPaths","verb","matcher","matchNone","removeEndpoints","sortEndpoints","newPaths2","remSchemas","removeSchemas","newComp","regex","YamlCombiner","combine","files","inRootPath","true","allElements","fileContents","f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