Skip to content

@rpallas/outcrop-runtime ​

Lambda runtime helpers for services built with @rpallas/outcrop: structured logging, config and secret resolution through the platform SSM contract, EventBridge envelopes and thin handler wrappers for HTTP, SQS and EventBridge.

The package is CDK-free and depends only on Powertools for AWS Lambda and the AWS SDK v3 clients it wraps.

sh
npm install @rpallas/outcrop-runtime

Environment ​

The platform constructs inject PLATFORM_PROJECT, PLATFORM_SERVICE, PLATFORM_ENV, PLATFORM_PREVIEW_ID, PLATFORM_SSM_ROOT, PLATFORM_FUNCTION and LOG_LEVEL.

ts
import { platformEnv, requireEnv } from "@rpallas/outcrop-runtime";

const env = platformEnv(); // throws if PLATFORM_SERVICE / PLATFORM_ENV are missing
env.service; // "orders"
env.isPreview; // true inside a preview stack
const table = requireEnv("TABLE_NAME");

Logger ​

createLogger() returns a Powertools Logger whose service name and persistent keys (env, previewId, functionName) come from the platform environment. getLogger() is a lazy module singleton.

ts
import { getLogger } from "@rpallas/outcrop-runtime";

const logger = getLogger();
logger.info("order created", { orderId });

Parameters ​

Cached (5 minutes by default) reads of the SSM contract written by @rpallas/outcrop-account.

ts
import { getParameter, platformParams } from "@rpallas/outcrop-runtime";

const params = platformParams();
const accountId = await params.account.id();
const busName = await params.env().eventBusName(); // env defaults to PLATFORM_ENV
const topic = await params.env("prod").alertTopicArn("critical");
const flag = await params.config("feature-flags");
const apiUrl = await params.service("billing", "api-url");

const raw = await getParameter("/my/own/parameter", { maxAge: 60, decrypt: true });

PlatformParameterPaths (also exported) builds the same paths without reading them.

Secrets ​

ts
import { getSecret, getSecretJson, getConfig } from "@rpallas/outcrop-runtime";

// A full ARN is read directly; a short name is resolved via /platform/secrets/{name}/arn.
const apiKey = await getSecret("third-party-api-key");
const db = await getSecretJson("database", { parse: DbCredentials.parse }); // e.g. a zod schema
const region = await getConfig("primary-region"); // /platform/config/primary-region

Events ​

Events are published to EventBridge with detail-type = eventName, source = PLATFORM_SERVICE and a { eventName, eventBody } envelope as detail. The bus comes from EVENT_BUS_NAME unless busName is passed.

ts
import { publishEvent, publishEvents, parseEnvelope } from "@rpallas/outcrop-runtime";

await publishEvent("OrderCreated", { orderId, total });
await publishEvents(items.map((item) => ({ eventName: "ItemShipped", eventBody: item })));

// Bodies larger than 200 KB can be offloaded to S3; consumers use resolveEnvelope().
await publishEvent("ReportGenerated", report, { offload: { bucket: process.env.EVENTS_BUCKET } });

parseEnvelope / parseSqsEnvelope validate inline envelopes synchronously; resolveEnvelope / resolveSqsEnvelope also download offloaded bodies.

HTTP handler ​

ts
import {
  withHttpHandler,
  json,
  parseJsonBody,
  pathParam,
  notFound,
} from "@rpallas/outcrop-runtime";

export const handler = withHttpHandler(async (event) => {
  const id = pathParam(event, "id");
  const body = parseJsonBody(event, UpdateOrder.parse); // 400 on invalid JSON or schema failure
  const order = await orders.update(id, body);
  if (!order) throw notFound("Order not found", { id });
  return json(200, order);
});

HttpErrors become { error, details } JSON responses with their status code; anything else is logged with its stack and returned as a 500. Every response carries an x-correlation-id header (taken from the request header, the API Gateway request id or the Lambda request id).

SQS handler ​

ts
import { withSqsHandler, parseSqsEnvelope } from "@rpallas/outcrop-runtime";

export const handler = withSqsHandler(
  async (record) => {
    const { eventName, eventBody } = parseSqsEnvelope(record);
    await process(eventName, eventBody);
  },
  { concurrency: 5 },
);

Failed records are logged and returned as batchItemFailures; enable ReportBatchItemFailures on the event source mapping.

EventBridge handler ​

ts
import { withEventHandler } from "@rpallas/outcrop-runtime";

export const handler = withEventHandler<OrderCreated>(
  async ({ eventName, eventBody }) => {
    await fulfil(eventBody);
  },
  { parse: OrderCreated.parse },
);

Generic wrapper ​

withHandler(fn, { logger?, logEvent?, onError? }) is the building block used by the wrappers above: it attaches the Lambda context (including cold start) to the logger, logs the event (debug, or info when POWERTOOLS_LOGGER_LOG_EVENT=true), adds a per-invocation correlationId key, logs and rethrows errors and resets the temporary keys afterwards.

Telemetry layer ​

@rpallas/outcrop-runtime/layer exports TELEMETRY_LAYER_DIR, TELEMETRY_REQUIRE_PATH and TELEMETRY_NODE_OPTIONS for building an opt-in Lambda layer that writes JSON log lines straight to the Lambda Telemetry API file descriptor. See layer/README.md for the mechanism.

ts
import { TELEMETRY_LAYER_DIR, TELEMETRY_NODE_OPTIONS } from "@rpallas/outcrop-runtime/layer";

const layer = new lambda.LayerVersion(this, "Telemetry", {
  code: lambda.Code.fromAsset(TELEMETRY_LAYER_DIR),
});
fn.addLayers(layer);
fn.addEnvironment("NODE_OPTIONS", TELEMETRY_NODE_OPTIONS);
fn.addEnvironment("PLATFORM_TELEMETRY_FD", "1");

Classes ​

HttpError ​

Defined in: http.ts:4

An error that maps directly to an HTTP response.

Extends ​

  • Error

Constructors ​

Constructor ​
ts
new HttpError(
   statusCode, 
   message, 
   details?
): HttpError;

Defined in: http.ts:5

Parameters ​
ParameterType
statusCodenumber
messagestring
details?unknown
Returns ​

HttpError

Overrides ​
ts
Error.constructor

Properties ​

PropertyModifierTypeDefined in
details?readonlyunknownhttp.ts:8
statusCodereadonlynumberhttp.ts:6

PlatformParameterPaths ​

Defined in: paths.ts:19

Builds the well-known SSM parameter paths of the platform contract. Written by @rpallas/outcrop-account, read by the @rpallas/outcrop constructs at synth time and by this package at runtime.

This is a CDK-free mirror of PlatformParameterPaths in @rpallas/outcrop.

Constructors ​

Constructor ​
ts
new PlatformParameterPaths(rootPrefix?): PlatformParameterPaths;

Defined in: paths.ts:22

Parameters ​
ParameterTypeDefault value
rootPrefixstring"/platform"
Returns ​

PlatformParameterPaths

Properties ​

PropertyModifierTypeDefined in
accountreadonlyobjectpaths.ts:30
account.accessLogsBucketNamepublic() => stringpaths.ts:48
account.cloudTrailBucketNamepublic() => stringpaths.ts:47
account.deployRoleArnpublic(repo) => stringpaths.ts:43
account.idpublic() => stringpaths.ts:31
account.kmsKeyArnpublic() => stringpaths.ts:33
account.kmsKeyIdpublic() => stringpaths.ts:34
account.logRetentionDayspublic() => stringpaths.ts:46
account.namepublic() => stringpaths.ts:32
account.oidcProviderArnpublic() => stringpaths.ts:42
account.readonlyRoleArnpublic(repo) => stringpaths.ts:44
account.vpcAvailabilityZonespublic() => stringpaths.ts:40
account.vpcCidrpublic() => stringpaths.ts:36
account.vpcIdpublic() => stringpaths.ts:35
account.vpcIsolatedSubnetIdspublic() => stringpaths.ts:39
account.vpcLambdaSecurityGroupIdpublic() => stringpaths.ts:41
account.vpcPrivateSubnetIdspublic() => stringpaths.ts:37
account.vpcPublicSubnetIdspublic() => stringpaths.ts:38
rootreadonlystringpaths.ts:20

Methods ​

config() ​
ts
config(key): string;

Defined in: paths.ts:66

Shared plain configuration value.

Parameters ​
ParameterType
keystring
Returns ​

string

env() ​
ts
readonly env(env): EnvironmentParameterPaths;

Defined in: paths.ts:51

Parameters ​
ParameterType
envstring
Returns ​

EnvironmentParameterPaths

secretArn() ​
ts
secretArn(name): string;

Defined in: paths.ts:71

ARN of a shared Secrets Manager secret.

Parameters ​
ParameterType
namestring
Returns ​

string

service() ​
ts
service(service, key): string;

Defined in: paths.ts:76

Values a service publishes about itself, e.g. /platform/services/orders/api-url.

Parameters ​
ParameterType
servicestring
keystring
Returns ​

string

Interfaces ​

CreateLoggerOptions ​

Defined in: logger.ts:7

Properties ​

PropertyTypeDescriptionDefined in
logLevel?LogLevelLog level; defaults to LOG_LEVEL / POWERTOOLS_LOG_LEVEL, then info.logger.ts:11
persistentKeys?Record<string, unknown>Additional keys added to every log record.logger.ts:13
sampleRateValue?numberDebug sampling rate between 0 and 1.logger.ts:15
serviceName?stringService name; defaults to POWERTOOLS_SERVICE_NAME, then PLATFORM_SERVICE.logger.ts:9

EnvironmentParameterPaths ​

Defined in: paths.ts:81

Methods ​

alertTopicArn() ​
ts
alertTopicArn(severity): string;

Defined in: paths.ts:88

Parameters ​
ParameterType
severity"critical" | "high" | "medium" | "low"
Returns ​

string

certRegionalArn() ​
ts
certRegionalArn(): string;

Defined in: paths.ts:86

Returns ​

string

certUsEast1Arn() ​
ts
certUsEast1Arn(): string;

Defined in: paths.ts:87

Returns ​

string

dnsZoneId() ​
ts
dnsZoneId(): string;

Defined in: paths.ts:84

Returns ​

string

dnsZoneName() ​
ts
dnsZoneName(): string;

Defined in: paths.ts:85

Returns ​

string

domain() ​
ts
domain(): string;

Defined in: paths.ts:83

Returns ​

string

eventBusArn() ​
ts
eventBusArn(): string;

Defined in: paths.ts:90

Returns ​

string

eventBusName() ​
ts
eventBusName(): string;

Defined in: paths.ts:89

Returns ​

string

name() ​
ts
name(): string;

Defined in: paths.ts:82

Returns ​

string

root() ​
ts
root(): string;

Defined in: paths.ts:91

Returns ​

string


EventToPublish ​

Defined in: events.ts:63

Type Parameters ​

Type ParameterDefault type
Tunknown

Properties ​

PropertyTypeDefined in
eventBodyTevents.ts:65
eventNamestringevents.ts:64

GetConfigOptions ​

Defined in: secrets.ts:116

Properties ​

PropertyTypeDescriptionDefined in
client?SSMClientCustom SSM client, mainly for tests.secrets.ts:122
maxAge?numberMaximum age of the cached value in seconds (default 300).secrets.ts:118
rootPrefix?stringSSM root prefix; defaults to PLATFORM_SSM_ROOT or /platform.secrets.ts:120

GetParameterOptions ​

Defined in: params.ts:13

Extended by ​

Properties ​

PropertyTypeDescriptionDefined in
client?SSMClientCustom SSM client, mainly for tests.params.ts:21
decrypt?booleanDecrypt SecureString parameters (default false).params.ts:17
forceFetch?booleanBypass the cache for this call.params.ts:19
maxAge?numberMaximum age of the cached value in seconds (default 300).params.ts:15

GetParametersOptions ​

Defined in: params.ts:24

Extends ​

Properties ​

PropertyTypeDescriptionInherited fromDefined in
client?SSMClientCustom SSM client, mainly for tests.GetParameterOptions.clientparams.ts:21
decrypt?booleanDecrypt SecureString parameters (default false).GetParameterOptions.decryptparams.ts:17
forceFetch?booleanBypass the cache for this call.GetParameterOptions.forceFetchparams.ts:19
maxAge?numberMaximum age of the cached value in seconds (default 300).GetParameterOptions.maxAgeparams.ts:15
recursive?booleanFetch parameters below the prefix recursively (default true).-params.ts:26

GetSecretJsonOptions ​

Defined in: secrets.ts:27

Extends ​

Type Parameters ​

Type Parameter
T

Properties ​

PropertyTypeDescriptionInherited fromDefined in
client?SecretsManagerClientCustom Secrets Manager client, mainly for tests.GetSecretOptions.clientsecrets.ts:20
forceFetch?booleanBypass the cache for this call.GetSecretOptions.forceFetchsecrets.ts:18
maxAge?numberMaximum age of the cached value in seconds (default 300).GetSecretOptions.maxAgesecrets.ts:16
parse?(value) => TValidates / narrows the parsed JSON, e.g. schema.parse from zod.-secrets.ts:29
rootPrefix?stringSSM root prefix used to resolve secret names; defaults to PLATFORM_SSM_ROOT or /platform.GetSecretOptions.rootPrefixsecrets.ts:24
ssmClient?SSMClientCustom SSM client used to resolve /{root}/secrets/{name}/arn, mainly for tests.GetSecretOptions.ssmClientsecrets.ts:22

GetSecretOptions ​

Defined in: secrets.ts:14

Extended by ​

Properties ​

PropertyTypeDescriptionDefined in
client?SecretsManagerClientCustom Secrets Manager client, mainly for tests.secrets.ts:20
forceFetch?booleanBypass the cache for this call.secrets.ts:18
maxAge?numberMaximum age of the cached value in seconds (default 300).secrets.ts:16
rootPrefix?stringSSM root prefix used to resolve secret names; defaults to PLATFORM_SSM_ROOT or /platform.secrets.ts:24
ssmClient?SSMClientCustom SSM client used to resolve /{root}/secrets/{name}/arn, mainly for tests.secrets.ts:22

OffloadedPointer ​

Defined in: events.ts:12

Location of an event body that was too large for EventBridge and was stored in S3.

Properties ​

PropertyTypeDefined in
bucketstringevents.ts:13
keystringevents.ts:14

OffloadOptions ​

Defined in: events.ts:33

Properties ​

PropertyTypeDescriptionDefined in
bucketstringBucket that receives large event bodies.events.ts:35
client?S3ClientCustom S3 client, mainly for tests.events.ts:39
keyPrefix?stringKey prefix inside the bucket (default events).events.ts:41
thresholdBytes?numberDetail size (in bytes) above which the body is offloaded (default 200 000).events.ts:37

PlatformAccountParams ​

Defined in: params.ts:106

Methods ​

accessLogsBucketName() ​
ts
accessLogsBucketName(): Promise<string>;

Defined in: params.ts:113

Returns ​

Promise<string>

cloudTrailBucketName() ​
ts
cloudTrailBucketName(): Promise<string>;

Defined in: params.ts:114

Returns ​

Promise<string>

deployRoleArn() ​
ts
deployRoleArn(repo): Promise<string>;

Defined in: params.ts:116

Parameters ​
ParameterType
repostring
Returns ​

Promise<string>

id() ​
ts
id(): Promise<string>;

Defined in: params.ts:107

Returns ​

Promise<string>

kmsKeyArn() ​
ts
kmsKeyArn(): Promise<string>;

Defined in: params.ts:109

Returns ​

Promise<string>

kmsKeyId() ​
ts
kmsKeyId(): Promise<string>;

Defined in: params.ts:110

Returns ​

Promise<string>

logRetentionDays() ​
ts
logRetentionDays(): Promise<string>;

Defined in: params.ts:112

Returns ​

Promise<string>

name() ​
ts
name(): Promise<string>;

Defined in: params.ts:108

Returns ​

Promise<string>

oidcProviderArn() ​
ts
oidcProviderArn(): Promise<string>;

Defined in: params.ts:115

Returns ​

Promise<string>

readonlyRoleArn() ​
ts
readonlyRoleArn(repo): Promise<string>;

Defined in: params.ts:117

Parameters ​
ParameterType
repostring
Returns ​

Promise<string>

vpcId() ​
ts
vpcId(): Promise<string>;

Defined in: params.ts:111

Returns ​

Promise<string>


PlatformEnv ​

Defined in: env.ts:5

Platform environment variables injected into every Lambda function by the @rpallas/outcrop constructs.

Properties ​

PropertyTypeDescriptionDefined in
envstringDeployment environment such as dev, staging, prod (PLATFORM_ENV).env.ts:11
functionName?stringLogical function name within the service (PLATFORM_FUNCTION).env.ts:17
isPreviewbooleanTrue when previewId is set.env.ts:21
logLevelPlatformLogLevelLog level (LOG_LEVEL, default info).env.ts:19
previewId?stringPreview identifier when running inside a preview stack (PLATFORM_PREVIEW_ID).env.ts:13
projectstringProject name (PLATFORM_PROJECT, defaults to the service name).env.ts:7
servicestringService name (PLATFORM_SERVICE).env.ts:9
ssmRootstringSSM root prefix of the platform contract (PLATFORM_SSM_ROOT, default /platform).env.ts:15

PlatformEnvironmentParams ​

Defined in: params.ts:120

Methods ​

alertTopicArn() ​
ts
alertTopicArn(severity): Promise<string>;

Defined in: params.ts:127

Parameters ​
ParameterType
severity"critical" | "high" | "medium" | "low"
Returns ​

Promise<string>

certRegionalArn() ​
ts
certRegionalArn(): Promise<string>;

Defined in: params.ts:125

Returns ​

Promise<string>

certUsEast1Arn() ​
ts
certUsEast1Arn(): Promise<string>;

Defined in: params.ts:126

Returns ​

Promise<string>

dnsZoneId() ​
ts
dnsZoneId(): Promise<string>;

Defined in: params.ts:123

Returns ​

Promise<string>

dnsZoneName() ​
ts
dnsZoneName(): Promise<string>;

Defined in: params.ts:124

Returns ​

Promise<string>

domain() ​
ts
domain(): Promise<string>;

Defined in: params.ts:122

Returns ​

Promise<string>

eventBusArn() ​
ts
eventBusArn(): Promise<string>;

Defined in: params.ts:129

Returns ​

Promise<string>

eventBusName() ​
ts
eventBusName(): Promise<string>;

Defined in: params.ts:128

Returns ​

Promise<string>

name() ​
ts
name(): Promise<string>;

Defined in: params.ts:121

Returns ​

Promise<string>


PlatformEvent ​

Defined in: events.ts:21

Envelope stored in the EventBridge detail field. eventBody is undefined while the body lives in S3 (see OffloadedPointer).

Type Parameters ​

Type ParameterDefault type
Tunknown

Properties ​

PropertyTypeDefined in
eventBodyTevents.ts:23
eventNamestringevents.ts:22
offloaded?OffloadedPointerevents.ts:24

PlatformParams ​

Defined in: params.ts:132

Properties ​

PropertyTypeDescriptionDefined in
accountPlatformAccountParamsAccount-level contract values.params.ts:138
pathsPlatformParameterPathsPath builder used by the getters.params.ts:134

Methods ​

config() ​
ts
config(key): Promise<string>;

Defined in: params.ts:142

Shared plain configuration value /{root}/config/{key}.

Parameters ​
ParameterType
keystring
Returns ​

Promise<string>

env() ​
ts
env(envName?): PlatformEnvironmentParams;

Defined in: params.ts:140

Environment-level contract values; envName defaults to PLATFORM_ENV.

Parameters ​
ParameterType
envName?string
Returns ​

PlatformEnvironmentParams

get() ​
ts
get(path, options?): Promise<string>;

Defined in: params.ts:136

Reads an arbitrary parameter path.

Parameters ​
ParameterType
pathstring
options?GetParameterOptions
Returns ​

Promise<string>

secretArn() ​
ts
secretArn(name): Promise<string>;

Defined in: params.ts:144

ARN of the shared secret /{root}/secrets/{name}/arn.

Parameters ​
ParameterType
namestring
Returns ​

Promise<string>

service() ​
ts
service(service, key): Promise<string>;

Defined in: params.ts:146

Value published by another service /{root}/services/{service}/{key}.

Parameters ​
ParameterType
servicestring
keystring
Returns ​

Promise<string>


PlatformParamsOptions ​

Defined in: params.ts:95

Properties ​

PropertyTypeDescriptionDefined in
client?SSMClientCustom SSM client, mainly for tests.params.ts:103
env?stringEnvironment name used by env(); defaults to PLATFORM_ENV.params.ts:99
maxAge?numberCache duration in seconds for every read (default 300).params.ts:101
rootPrefix?stringSSM root prefix; defaults to PLATFORM_SSM_ROOT or /platform.params.ts:97

PublishEventOptions ​

Defined in: events.ts:44

Properties ​

PropertyTypeDescriptionDefined in
busName?stringEvent bus name; defaults to EVENT_BUS_NAME.events.ts:46
client?EventBridgeClientCustom EventBridge client, mainly for tests.events.ts:50
offload?OffloadOptionsStore large bodies in S3 and publish a pointer instead.events.ts:56
resources?string[]ARNs the event relates to.events.ts:52
source?stringEvent source; defaults to PLATFORM_SERVICE.events.ts:48
time?DateEvent time; defaults to now.events.ts:54

PublishEventResult ​

Defined in: events.ts:59

Properties ​

PropertyTypeDefined in
eventId?stringevents.ts:60

ResolveEnvelopeOptions ​

Defined in: events.ts:299

Type Parameters ​

Type Parameter
T

Properties ​

PropertyTypeDescriptionDefined in
parse?(body) => TValidates / narrows the body, e.g. schema.parse from zod.events.ts:303
s3Client?S3ClientCustom S3 client used to download offloaded bodies, mainly for tests.events.ts:301

WithEventHandlerOptions ​

Defined in: handler.ts:220

Type Parameters ​

Type Parameter
T

Properties ​

PropertyTypeDescriptionDefined in
logEvent?booleanLog the incoming event at info level.handler.ts:224
logger?LoggerLogger to use; defaults to getLogger.handler.ts:222
parse?(body) => TValidates / narrows the event body, e.g. schema.parse from zod.handler.ts:226
s3Client?S3ClientCustom S3 client used to download offloaded bodies.handler.ts:228

WithHandlerOptions ​

Defined in: handler.ts:21

Type Parameters ​

Type Parameter
TEvent
TResult

Properties ​

PropertyTypeDescriptionDefined in
logEvent?booleanLog the incoming event at info level (default: honour POWERTOOLS_LOGGER_LOG_EVENT).handler.ts:25
logger?LoggerLogger to use; defaults to getLogger.handler.ts:23
onError?(error, event, context) => TResult | Promise<TResult>Called instead of rethrowing when the handler fails.handler.ts:27

WithSqsHandlerOptions ​

Defined in: handler.ts:159

Properties ​

PropertyTypeDescriptionDefined in
concurrency?numberMaximum number of records processed concurrently (default 1 = sequential).handler.ts:165
logEvent?booleanLog the incoming event at info level.handler.ts:163
logger?LoggerLogger to use; defaults to getLogger.handler.ts:161

Type Aliases ​

AlertSeverity ​

ts
type AlertSeverity = typeof ALERT_SEVERITIES[number];

Defined in: paths.ts:7

Alert severity. Each severity maps to one SNS topic per environment so that routing (pager, chat channel, email digest) is an account-level decision.


HttpHandler ​

ts
type HttpHandler = LambdaHandler<APIGatewayProxyEventV2, APIGatewayProxyStructuredResultV2>;

Defined in: handler.ts:103


HttpHeaders ​

ts
type HttpHeaders = Record<string, string>;

Defined in: http.ts:32


LambdaHandler ​

ts
type LambdaHandler<TEvent, TResult> = (event, context) => Promise<TResult>;

Defined in: handler.ts:17

Type Parameters ​

Type Parameter
TEvent
TResult

Parameters ​

ParameterType
eventTEvent
contextContext

Returns ​

Promise<TResult>


PlatformEventHandler ​

ts
type PlatformEventHandler<T> = (envelope, event, context) => Promise<void>;

Defined in: handler.ts:214

Type Parameters ​

Type Parameter
T

Parameters ​

ParameterType
envelopePlatformEvent<T>
eventEventBridgeEvent<string, unknown>
contextContext

Returns ​

Promise<void>


PlatformLogLevel ​

ts
type PlatformLogLevel = "debug" | "info" | "warn" | "error";

Defined in: env.ts:24


SqsRecordHandler ​

ts
type SqsRecordHandler = (record, context) => Promise<void>;

Defined in: handler.ts:157

Parameters ​

ParameterType
recordSQSRecord
contextContext

Returns ​

Promise<void>


WithHttpHandlerOptions ​

ts
type WithHttpHandlerOptions = WithHandlerOptions<APIGatewayProxyEventV2, APIGatewayProxyStructuredResultV2>;

Defined in: handler.ts:105

Variables ​

ALERT_SEVERITIES ​

ts
const ALERT_SEVERITIES: readonly ["critical", "high", "medium", "low"];

Defined in: paths.ts:1


CORRELATION_ID_HEADER ​

ts
const CORRELATION_ID_HEADER: "x-correlation-id" = "x-correlation-id";

Defined in: handler.ts:19


DEFAULT_OFFLOAD_THRESHOLD_BYTES ​

ts
const DEFAULT_OFFLOAD_THRESHOLD_BYTES: 200000 = 200_000;

Defined in: events.ts:28

Default maximum detail size before the body is offloaded to S3 (EventBridge allows 256 KiB per entry).


DEFAULT_PARAMETER_MAX_AGE ​

ts
const DEFAULT_PARAMETER_MAX_AGE: 300 = 300;

Defined in: params.ts:11

Default cache duration for parameters, in seconds.


DEFAULT_SECRET_MAX_AGE ​

ts
const DEFAULT_SECRET_MAX_AGE: 300 = 300;

Defined in: secrets.ts:12

Default cache duration for secrets, in seconds.


DEFAULT_SSM_ROOT ​

ts
const DEFAULT_SSM_ROOT: "/platform" = "/platform";

Defined in: env.ts:28


PUT_EVENTS_BATCH_SIZE ​

ts
const PUT_EVENTS_BATCH_SIZE: 10 = 10;

Defined in: events.ts:31

Maximum number of entries in a single PutEvents call.


TELEMETRY_ENABLE_ENV ​

ts
const TELEMETRY_ENABLE_ENV: "PLATFORM_TELEMETRY_FD" = "PLATFORM_TELEMETRY_FD";

Defined in: layer.ts:16

Environment variable that opts a function into the telemetry shim.


TELEMETRY_LAYER_DIR ​

ts
const TELEMETRY_LAYER_DIR: string;

Defined in: layer.ts:7

Directory containing the Lambda layer content (nodejs/platform-telemetry.js). Point lambda.Code.fromAsset() at it when building the layer.


TELEMETRY_NODE_OPTIONS ​

ts
const TELEMETRY_NODE_OPTIONS: "--require /opt/nodejs/platform-telemetry.js";

Defined in: layer.ts:13

Value for NODE_OPTIONS that pre-loads the telemetry shim.


TELEMETRY_REQUIRE_PATH ​

ts
const TELEMETRY_REQUIRE_PATH: "/opt/nodejs/platform-telemetry.js" = "/opt/nodejs/platform-telemetry.js";

Defined in: layer.ts:10

Path of the telemetry shim once the layer is mounted at /opt.

Functions ​

badRequest() ​

ts
function badRequest(message?, details?): HttpError;

Defined in: http.ts:17

Parameters ​

ParameterTypeDefault value
messagestring"Bad Request"
details?unknownundefined

Returns ​

HttpError


conflict() ​

ts
function conflict(message?, details?): HttpError;

Defined in: http.ts:25

Parameters ​

ParameterTypeDefault value
messagestring"Conflict"
details?unknownundefined

Returns ​

HttpError


createLogger() ​

ts
function createLogger(options?): Logger;

Defined in: logger.ts:28

Creates a Powertools Logger pre-configured for the platform.

Persistent keys env, previewId and functionName are derived from the PLATFORM_* environment variables when they are available. Missing variables never cause an error so the logger keeps working in local scripts and tests.

Parameters ​

ParameterType
optionsCreateLoggerOptions

Returns ​

Logger


eventFromSqsRecord() ​

ts
function eventFromSqsRecord(record): EventBridgeEvent<string, unknown>;

Defined in: events.ts:284

Decodes the EventBridge event carried in an SQS record body.

Parameters ​

ParameterType
recordSQSRecord

Returns ​

EventBridgeEvent<string, unknown>


findHeader() ​

ts
function findHeader(headers, name): string | undefined;

Defined in: http.ts:124

Case-insensitive lookup in a headers map.

Parameters ​

ParameterType
headersRecord<string, string | undefined> | undefined
namestring

Returns ​

string | undefined


forbidden() ​

ts
function forbidden(message?, details?): HttpError;

Defined in: http.ts:21

Parameters ​

ParameterTypeDefault value
messagestring"Forbidden"
details?unknownundefined

Returns ​

HttpError


getConfig() ​

ts
function getConfig(key, options?): Promise<string>;

Defined in: secrets.ts:126

Reads the shared configuration value /{root}/config/{key}.

Parameters ​

ParameterType
keystring
optionsGetConfigOptions

Returns ​

Promise<string>


getLogger() ​

ts
function getLogger(): Logger;

Defined in: logger.ts:66

Returns the module-level logger, creating it on first use.

Returns ​

Logger


getParameter() ​

ts
function getParameter(name, options?): Promise<string>;

Defined in: params.ts:61

Reads a single SSM parameter, cached for maxAge seconds (default 300). Throws a descriptive error when the parameter does not exist.

Parameters ​

ParameterType
namestring
optionsGetParameterOptions

Returns ​

Promise<string>


getParameters() ​

ts
function getParameters(prefix, options?): Promise<Record<string, string>>;

Defined in: params.ts:79

Reads all parameters below prefix, keyed by the path relative to the prefix.

Parameters ​

ParameterType
prefixstring
optionsGetParametersOptions

Returns ​

Promise<Record<string, string>>


getSecret() ​

ts
function getSecret(nameOrArn, options?): Promise<string>;

Defined in: secrets.ts:73

Reads a secret string from Secrets Manager, cached for maxAge seconds (default 300).

nameOrArn may be a full ARN or the short name of a shared platform secret, in which case the ARN is looked up from SSM first.

Parameters ​

ParameterType
nameOrArnstring
optionsGetSecretOptions

Returns ​

Promise<string>


getSecretJson() ​

ts
function getSecretJson<T>(nameOrArn, options?): Promise<T>;

Defined in: secrets.ts:100

Reads a JSON secret and optionally validates it with parse.

Type Parameters ​

Type ParameterDefault type
Tunknown

Parameters ​

ParameterType
nameOrArnstring
optionsGetSecretJsonOptions<T>

Returns ​

Promise<T>

Example ​

ts
const creds = await getSecretJson("database", { parse: DbSchema.parse });

ts
function header(event, name): string | undefined;

Defined in: http.ts:119

Header value looked up case-insensitively, or undefined.

Parameters ​

ParameterType
eventAPIGatewayProxyEventV2
namestring

Returns ​

string | undefined


internalError() ​

ts
function internalError(message?, details?): HttpError;

Defined in: http.ts:29

Parameters ​

ParameterTypeDefault value
messagestring"Internal Server Error"
details?unknownundefined

Returns ​

HttpError


isAlertSeverity() ​

ts
function isAlertSeverity(value): value is "critical" | "high" | "medium" | "low";

Defined in: paths.ts:9

Parameters ​

ParameterType
valuestring

Returns ​

value is "critical" | "high" | "medium" | "low"


isHttpError() ​

ts
function isHttpError(error): error is HttpError;

Defined in: http.ts:15

Parameters ​

ParameterType
errorunknown

Returns ​

error is HttpError


json() ​

ts
function json(
   statusCode, 
   body, 
   headers?
): APIGatewayProxyStructuredResultV2;

Defined in: http.ts:35

JSON response with content-type: application/json.

Parameters ​

ParameterType
statusCodenumber
bodyunknown
headersHttpHeaders

Returns ​

APIGatewayProxyStructuredResultV2


noContent() ​

ts
function noContent(headers?): APIGatewayProxyStructuredResultV2;

Defined in: http.ts:48

Empty 204 No Content response.

Parameters ​

ParameterType
headersHttpHeaders

Returns ​

APIGatewayProxyStructuredResultV2


notFound() ​

ts
function notFound(message?, details?): HttpError;

Defined in: http.ts:23

Parameters ​

ParameterTypeDefault value
messagestring"Not Found"
details?unknownundefined

Returns ​

HttpError


parseEnvelope() ​

ts
function parseEnvelope<T>(event, parse?): PlatformEvent<T>;

Defined in: events.ts:254

Extracts and validates the PlatformEvent envelope from an EventBridge event.

Throws when the detail is not an envelope. Offloaded envelopes (body stored in S3) cannot be parsed synchronously; use resolveEnvelope for those.

Type Parameters ​

Type ParameterDefault type
Tunknown

Parameters ​

ParameterType
eventEventBridgeEvent<string, unknown>
parse?(body) => T

Returns ​

PlatformEvent<T>


parseJsonBody() ​

ts
function parseJsonBody<T>(event, parse?): T;

Defined in: http.ts:72

Parses the JSON request body, optionally validating it with parse (e.g. schema.parse from zod). Throws a 400 HttpError when the body is missing, is not valid JSON, or parse rejects it.

Type Parameters ​

Type ParameterDefault type
Tunknown

Parameters ​

ParameterType
eventAPIGatewayProxyEventV2
parse?(value) => T

Returns ​

T


parseSqsEnvelope() ​

ts
function parseSqsEnvelope<T>(record, parse?): PlatformEvent<T>;

Defined in: events.ts:276

Parses the platform envelope from an SQS record that was delivered by an EventBridge rule (the SQS body is the EventBridge event JSON).

Type Parameters ​

Type ParameterDefault type
Tunknown

Parameters ​

ParameterType
recordSQSRecord
parse?(body) => T

Returns ​

PlatformEvent<T>


pathParam() ​

ts
function pathParam(event, name): string;

Defined in: http.ts:105

Path parameter value; throws a 400 HttpError when missing.

Parameters ​

ParameterType
eventAPIGatewayProxyEventV2
namestring

Returns ​

string


platformEnv() ​

ts
function platformEnv(env?): PlatformEnv;

Defined in: env.ts:64

Resolves the PlatformEnv from the process environment.

Throws when PLATFORM_SERVICE or PLATFORM_ENV are missing.

Parameters ​

ParameterTypeDefault value
envProcessEnvprocess.env

Returns ​

PlatformEnv


platformParams() ​

ts
function platformParams(options?): PlatformParams;

Defined in: params.ts:161

Typed accessors for the platform SSM contract.

Parameters ​

ParameterType
optionsPlatformParamsOptions

Returns ​

PlatformParams

Example ​

ts
const params = platformParams();
const busName = await params.env().eventBusName();

publishEvent() ​

ts
function publishEvent(
   eventName, 
   eventBody, 
   options?
): Promise<PublishEventResult>;

Defined in: events.ts:170

Publishes a single platform event to EventBridge.

The detail is a PlatformEvent envelope, detail-type is the event name and source is the publishing service.

Parameters ​

ParameterType
eventNamestring
eventBodyunknown
optionsPublishEventOptions

Returns ​

Promise<PublishEventResult>


publishEvents() ​

ts
function publishEvents<T>(events, options?): Promise<PublishEventResult[]>;

Defined in: events.ts:186

Publishes several events, in batches of 10 (the PutEvents limit). Results are returned in the same order as events.

Type Parameters ​

Type ParameterDefault type
Tunknown

Parameters ​

ParameterType
eventsEventToPublish<T>[]
optionsPublishEventOptions

Returns ​

Promise<PublishEventResult[]>


queryParam() ​

ts
function queryParam(event, name): string | undefined;

Defined in: http.ts:114

Query string parameter value, or undefined.

Parameters ​

ParameterType
eventAPIGatewayProxyEventV2
namestring

Returns ​

string | undefined


rawBody() ​

ts
function rawBody(event): string | undefined;

Defined in: http.ts:62

Raw request body, decoded when API Gateway base64-encoded it.

Parameters ​

ParameterType
eventAPIGatewayProxyEventV2

Returns ​

string | undefined


redirect() ​

ts
function redirect(
   location, 
   statusCode?, 
   headers?
): APIGatewayProxyStructuredResultV2;

Defined in: http.ts:53

Redirect response (302 Found by default).

Parameters ​

ParameterTypeDefault value
locationstringundefined
statusCodenumber302
headersHttpHeaders{}

Returns ​

APIGatewayProxyStructuredResultV2


requireEnv() ​

ts
function requireEnv(name, env?): string;

Defined in: env.ts:34

Reads an environment variable and throws a descriptive error when it is missing or empty.

Parameters ​

ParameterTypeDefault value
namestringundefined
envProcessEnvprocess.env

Returns ​

string


resetLogger() ​

ts
function resetLogger(): void;

Defined in: logger.ts:72

Drops the module-level logger so the next getLogger call creates a fresh one.

Returns ​

void


resolveCorrelationId() ​

ts
function resolveCorrelationId(event, context): string;

Defined in: handler.ts:47

Picks the correlation id for an invocation: the x-correlation-id header, then the HTTP API request id, then the EventBridge event id, then the Lambda request id.

Parameters ​

ParameterType
eventunknown
contextContext

Returns ​

string


resolveEnvelope() ​

ts
function resolveEnvelope<T>(event, options?): Promise<PlatformEvent<T>>;

Defined in: events.ts:309

Like parseEnvelope but downloads the body from S3 when it was offloaded.

Type Parameters ​

Type ParameterDefault type
Tunknown

Parameters ​

ParameterType
eventEventBridgeEvent<string, unknown>
optionsResolveEnvelopeOptions<T>

Returns ​

Promise<PlatformEvent<T>>


resolveSecretArn() ​

ts
function resolveSecretArn(nameOrArn, options?): Promise<string>;

Defined in: secrets.ts:55

Resolves the Secrets Manager ARN for a shared platform secret name via the SSM contract path /{root}/secrets/{name}/arn. ARNs are returned unchanged.

Parameters ​

ParameterType
nameOrArnstring
optionsGetSecretOptions

Returns ​

Promise<string>


resolveSqsEnvelope() ​

ts
function resolveSqsEnvelope<T>(record, options?): Promise<PlatformEvent<T>>;

Defined in: events.ts:335

Like parseSqsEnvelope but downloads offloaded bodies from S3.

Type Parameters ​

Type ParameterDefault type
Tunknown

Parameters ​

ParameterType
recordSQSRecord
optionsResolveEnvelopeOptions<T>

Returns ​

Promise<PlatformEvent<T>>


tooManyRequests() ​

ts
function tooManyRequests(message?, details?): HttpError;

Defined in: http.ts:27

Parameters ​

ParameterTypeDefault value
messagestring"Too Many Requests"
details?unknownundefined

Returns ​

HttpError


tryPlatformEnv() ​

ts
function tryPlatformEnv(env?): PlatformEnv | undefined;

Defined in: env.ts:88

Like platformEnv but returns undefined instead of throwing when the required variables are not present. Useful for helpers that must keep working outside of a platform-managed Lambda (e.g. local scripts and tests).

Parameters ​

ParameterTypeDefault value
envProcessEnvprocess.env

Returns ​

PlatformEnv | undefined


unauthorized() ​

ts
function unauthorized(message?, details?): HttpError;

Defined in: http.ts:19

Parameters ​

ParameterTypeDefault value
messagestring"Unauthorized"
details?unknownundefined

Returns ​

HttpError


withEventHandler() ​

ts
function withEventHandler<T>(handler, options?): LambdaHandler<EventBridgeEvent<string, unknown>, void>;

Defined in: handler.ts:235

EventBridge handler wrapper: unwraps (and, when offloaded, downloads) the platform envelope before invoking handler. Adds eventName to the log keys.

Type Parameters ​

Type ParameterDefault type
Tunknown

Parameters ​

ParameterType
handlerPlatformEventHandler<T>
optionsWithEventHandlerOptions<T>

Returns ​

LambdaHandler<EventBridgeEvent<string, unknown>, void>


withHandler() ​

ts
function withHandler<TEvent, TResult>(handler, options?): LambdaHandler<TEvent, TResult>;

Defined in: handler.ts:72

Wraps a Lambda handler with logging boilerplate: Lambda context and cold start tracking, event logging, a per-invocation correlationId key, error logging and key cleanup.

Type Parameters ​

Type Parameter
TEvent
TResult

Parameters ​

ParameterType
handlerLambdaHandler<TEvent, TResult>
optionsWithHandlerOptions<TEvent, TResult>

Returns ​

LambdaHandler<TEvent, TResult>


withHttpHandler() ​

ts
function withHttpHandler(handler, options?): HttpHandler;

Defined in: handler.ts:123

HTTP API (payload v2) handler wrapper. HttpErrors become JSON error responses with their status code; anything else becomes a 500. Every response carries an x-correlation-id header.

Parameters ​

ParameterType
handlerHttpHandler
optionsWithHttpHandlerOptions

Returns ​

HttpHandler


withSqsHandler() ​

ts
function withSqsHandler(recordHandler, options?): LambdaHandler<SQSEvent, SQSBatchResponse>;

Defined in: handler.ts:173

SQS handler wrapper with partial batch responses: each record is handed to recordHandler; failures are logged and reported via batchItemFailures. Requires ReportBatchItemFailures on the event source mapping.

Parameters ​

ParameterType
recordHandlerSqsRecordHandler
optionsWithSqsHandlerOptions

Returns ​

LambdaHandler<SQSEvent, SQSBatchResponse>

Released under the MIT License.