awslambdanodejs

package
v1.168.0-devpreview Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 9, 2022 License: Apache-2.0 Imports: 15 Imported by: 0

README

Amazon Lambda Node.js Library

This library provides constructs for Node.js Lambda functions.

Node.js Function

The NodejsFunction construct creates a Lambda function with automatic transpiling and bundling of TypeScript or Javascript code. This results in smaller Lambda packages that contain only the code and dependencies needed to run the function.

It uses esbuild under the hood.

Reference project architecture

The NodejsFunction allows you to define your CDK and runtime dependencies in a single package.json and to collocate your runtime code with your infrastructure code:

.
├── lib
│   ├── my-construct.api.ts # Lambda handler for API
│   ├── my-construct.auth.ts # Lambda handler for Auth
│   └── my-construct.ts # CDK construct with two Lambda functions
├── package-lock.json # single lock file
├── package.json # CDK and runtime dependencies defined in a single package.json
└── tsconfig.json

By default, the construct will use the name of the defining file and the construct's id to look up the entry file. In my-construct.ts above we have:

// automatic entry look up
apiHandler := lambda.NewNodejsFunction(this, jsii.String("api"))
authHandler := lambda.NewNodejsFunction(this, jsii.String("auth"))

Alternatively, an entry file and handler can be specified:

lambda.NewNodejsFunction(this, jsii.String("MyFunction"), &nodejsFunctionProps{
	entry: jsii.String("/path/to/my/file.ts"),
	 // accepts .js, .jsx, .ts, .tsx and .mjs files
	handler: jsii.String("myExportedFunc"),
})

For monorepos, the reference architecture becomes:

.
├── packages
│   ├── cool-package
│   │   ├── lib
│   │   │   ├── cool-construct.api.ts
│   │   │   ├── cool-construct.auth.ts
│   │   │   └── cool-construct.ts
│   │   ├── package.json # CDK and runtime dependencies for cool-package
│   │   └── tsconfig.json
│   └── super-package
│       ├── lib
│       │   ├── super-construct.handler.ts
│       │   └── super-construct.ts
│       ├── package.json # CDK and runtime dependencies for super-package
│       └── tsconfig.json
├── package-lock.json # single lock file
├── package.json # root dependencies
└── tsconfig.json

Customizing the underlying Lambda function

All properties of lambda.Function can be used to customize the underlying lambda.Function.

See also the AWS Lambda construct library.

The NodejsFunction construct automatically reuses existing connections when working with the AWS SDK for JavaScript. Set the awsSdkConnectionReuse prop to false to disable it.

Lock file

The NodejsFunction requires a dependencies lock file (yarn.lock, pnpm-lock.yaml or package-lock.json). When bundling in a Docker container, the path containing this lock file is used as the source (/asset-input) for the volume mounted in the container.

By default, the construct will try to automatically determine your project lock file. Alternatively, you can specify the depsLockFilePath prop manually. In this case you need to ensure that this path includes entry and any module/dependencies used by your function. Otherwise bundling will fail.

Local bundling

If esbuild is available it will be used to bundle your code in your environment. Otherwise, bundling will happen in a Lambda compatible Docker container with the Docker platform based on the target architecture of the Lambda function.

For macOS the recommended approach is to install esbuild as Docker volume performance is really poor.

esbuild can be installed with:

$ npm install --save-dev esbuild@0

OR

$ yarn add --dev esbuild@0

If you're using a monorepo layout, the esbuild dependency needs to be installed in the "root" package.json file, not in the workspace. From the reference architecture described above, the esbuild dev dependency needs to be in ./package.json, not packages/cool-package/package.json or packages/super-package/package.json.

To force bundling in a Docker container even if esbuild is available in your environment, set bundling.forceDockerBundling to true. This is useful if your function relies on node modules that should be installed (nodeModules prop, see below) in a Lambda compatible environment. This is usually the case with modules using native dependencies.

Working with modules

Externals

By default, all node modules are bundled except for aws-sdk. This can be configured by specifying bundling.externalModules:

lambda.NewNodejsFunction(this, jsii.String("my-handler"), &nodejsFunctionProps{
	bundling: &bundlingOptions{
		externalModules: []*string{
			jsii.String("aws-sdk"),
			jsii.String("cool-module"),
		},
	},
})
Install modules

By default, all node modules referenced in your Lambda code will be bundled by esbuild. Use the nodeModules prop under bundling to specify a list of modules that should not be bundled but instead included in the node_modules folder of the Lambda package. This is useful when working with native dependencies or when esbuild fails to bundle a module.

lambda.NewNodejsFunction(this, jsii.String("my-handler"), &nodejsFunctionProps{
	bundling: &bundlingOptions{
		nodeModules: []*string{
			jsii.String("native-module"),
			jsii.String("other-module"),
		},
	},
})

The modules listed in nodeModules must be present in the package.json's dependencies or installed. The same version will be used for installation. The lock file (yarn.lock, pnpm-lock.yaml or package-lock.json) will be used along with the right installer (yarn, pnpm or npm).

When working with nodeModules using native dependencies, you might want to force bundling in a Docker container even if esbuild is available in your environment. This can be done by setting bundling.forceDockerBundling to true.

Configuring esbuild

The NodejsFunction construct exposes esbuild options via properties under bundling:

lambda.NewNodejsFunction(this, jsii.String("my-handler"), &nodejsFunctionProps{
	bundling: &bundlingOptions{
		minify: jsii.Boolean(true),
		 // minify code, defaults to false
		sourceMap: jsii.Boolean(true),
		 // include source map, defaults to false
		sourceMapMode: lambda.sourceMapMode_INLINE,
		 // defaults to SourceMapMode.DEFAULT
		sourcesContent: jsii.Boolean(false),
		 // do not include original source into source map, defaults to true
		target: jsii.String("es2020"),
		 // target environment for the generated JavaScript code
		loader: map[string]*string{
			 // Use the 'dataurl' loader for '.png' files
			".png": jsii.String("dataurl"),
		},
		define: map[string]*string{
			 // Replace strings during build time
			"process.env.API_KEY": JSON.stringify(jsii.String("xxx-xxxx-xxx")),
			"process.env.PRODUCTION": JSON.stringify(jsii.Boolean(true)),
			"process.env.NUMBER": JSON.stringify(jsii.Number(123)),
		},
		logLevel: lambda.logLevel_SILENT,
		 // defaults to LogLevel.WARNING
		keepNames: jsii.Boolean(true),
		 // defaults to false
		tsconfig: jsii.String("custom-tsconfig.json"),
		 // use custom-tsconfig.json instead of default,
		metafile: jsii.Boolean(true),
		 // include meta file, defaults to false
		banner: jsii.String("/* comments */"),
		 // requires esbuild >= 0.9.0, defaults to none
		footer: jsii.String("/* comments */"),
		 // requires esbuild >= 0.9.0, defaults to none
		charset: lambda.charset_UTF8,
		 // do not escape non-ASCII characters, defaults to Charset.ASCII
		format: lambda.outputFormat_ESM,
		 // ECMAScript module output format, defaults to OutputFormat.CJS (OutputFormat.ESM requires Node.js 14.x)
		mainFields: []*string{
			jsii.String("module"),
			jsii.String("main"),
		},
		 // prefer ECMAScript versions of dependencies
		inject: []*string{
			jsii.String("./my-shim.js"),
			jsii.String("./other-shim.js"),
		},
		 // allows to automatically replace a global variable with an import from another file
		esbuildArgs: map[string]interface{}{
			 // Pass additional arguments to esbuild
			"--log-limit": jsii.String("0"),
			"--splitting": jsii.Boolean(true),
		},
	},
})

Command hooks

It is possible to run additional commands by specifying the commandHooks prop:

// This example only available in TypeScript
// Run additional props via `commandHooks`
new lambda.NodejsFunction(this, 'my-handler-with-commands', {
  bundling: {
    commandHooks: {
      beforeBundling(inputDir: string, outputDir: string): string[] {
        return [
          `echo hello > ${inputDir}/a.txt`,
          `cp ${inputDir}/a.txt ${outputDir}`,
        ];
      },
      afterBundling(inputDir: string, outputDir: string): string[] {
        return [`cp ${inputDir}/b.txt ${outputDir}/txt`];
      },
      beforeInstall() {
        return [];
      },
      // ...
    },
    // ...
  },
});

The following hooks are available:

  • beforeBundling: runs before all bundling commands
  • beforeInstall: runs before node modules installation
  • afterBundling: runs after all bundling commands

They all receive the directory containing the lock file (inputDir) and the directory where the bundled asset will be output (outputDir). They must return an array of commands to run. Commands are chained with &&.

The commands will run in the environment in which bundling occurs: inside the container for Docker bundling or on the host OS for local bundling.

Pre Compilation with TSC

In some cases, esbuild may not yet support some newer features of the typescript language, such as, emitDecoratorMetadata. In such cases, it is possible to run pre-compilation using tsc by setting the preCompilation flag.

lambda.NewNodejsFunction(this, jsii.String("my-handler"), &nodejsFunctionProps{
	bundling: &bundlingOptions{
		preCompilation: jsii.Boolean(true),
	},
})

Note: A tsconfig.json file is required

Customizing Docker bundling

Use bundling.environment to define environments variables when esbuild runs:

lambda.NewNodejsFunction(this, jsii.String("my-handler"), &nodejsFunctionProps{
	bundling: &bundlingOptions{
		environment: map[string]*string{
			"NODE_ENV": jsii.String("production"),
		},
	},
})

Use bundling.buildArgs to pass build arguments when building the Docker bundling image:

lambda.NewNodejsFunction(this, jsii.String("my-handler"), &nodejsFunctionProps{
	bundling: &bundlingOptions{
		buildArgs: map[string]*string{
			"HTTPS_PROXY": jsii.String("https://127.0.0.1:3001"),
		},
	},
})

Use bundling.dockerImage to use a custom Docker bundling image:

lambda.NewNodejsFunction(this, jsii.String("my-handler"), &nodejsFunctionProps{
	bundling: &bundlingOptions{
		dockerImage: awscdk.DockerImage.fromBuild(jsii.String("/path/to/Dockerfile")),
	},
})

This image should have esbuild installed globally. If you plan to use nodeModules it should also have npm, yarn or pnpm depending on the lock file you're using.

Use the default image provided by @aws-cdk/aws-lambda-nodejs as a source of inspiration.

Asset hash

By default the asset hash will be calculated based on the bundled output (AssetHashType.OUTPUT).

Use the assetHash prop to pass a custom hash:

lambda.NewNodejsFunction(this, jsii.String("my-handler"), &nodejsFunctionProps{
	bundling: &bundlingOptions{
		assetHash: jsii.String("my-custom-hash"),
	},
})

If you chose to customize the hash, you will need to make sure it is updated every time the asset changes, or otherwise it is possible that some deployments will not be invalidated.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewNodejsFunction_Override

func NewNodejsFunction_Override(n NodejsFunction, scope awscdk.Construct, id *string, props *NodejsFunctionProps)

Experimental.

func NodejsFunction_ClassifyVersionProperty

func NodejsFunction_ClassifyVersionProperty(propertyName *string, locked *bool)

Record whether specific properties in the `AWS::Lambda::Function` resource should also be associated to the Version resource.

See 'currentVersion' section in the module README for more details. Experimental.

func NodejsFunction_FromFunctionArn

func NodejsFunction_FromFunctionArn(scope constructs.Construct, id *string, functionArn *string) awslambda.IFunction

Import a lambda function into the CDK using its ARN. Experimental.

func NodejsFunction_FromFunctionAttributes

func NodejsFunction_FromFunctionAttributes(scope constructs.Construct, id *string, attrs *awslambda.FunctionAttributes) awslambda.IFunction

Creates a Lambda function object which represents a function not defined within this stack. Experimental.

func NodejsFunction_FromFunctionName

func NodejsFunction_FromFunctionName(scope constructs.Construct, id *string, functionName *string) awslambda.IFunction

Import a lambda function into the CDK using its name. Experimental.

func NodejsFunction_IsConstruct

func NodejsFunction_IsConstruct(x interface{}) *bool

Return whether the given object is a Construct. Experimental.

func NodejsFunction_IsResource

func NodejsFunction_IsResource(construct awscdk.IConstruct) *bool

Check whether the given construct is a Resource. Experimental.

func NodejsFunction_MetricAll

func NodejsFunction_MetricAll(metricName *string, props *awscloudwatch.MetricOptions) awscloudwatch.Metric

Return the given named metric for this Lambda. Experimental.

func NodejsFunction_MetricAllConcurrentExecutions

func NodejsFunction_MetricAllConcurrentExecutions(props *awscloudwatch.MetricOptions) awscloudwatch.Metric

Metric for the number of concurrent executions across all Lambdas. Experimental.

func NodejsFunction_MetricAllDuration

func NodejsFunction_MetricAllDuration(props *awscloudwatch.MetricOptions) awscloudwatch.Metric

Metric for the Duration executing all Lambdas. Experimental.

func NodejsFunction_MetricAllErrors

func NodejsFunction_MetricAllErrors(props *awscloudwatch.MetricOptions) awscloudwatch.Metric

Metric for the number of Errors executing all Lambdas. Experimental.

func NodejsFunction_MetricAllInvocations

func NodejsFunction_MetricAllInvocations(props *awscloudwatch.MetricOptions) awscloudwatch.Metric

Metric for the number of invocations of all Lambdas. Experimental.

func NodejsFunction_MetricAllThrottles

func NodejsFunction_MetricAllThrottles(props *awscloudwatch.MetricOptions) awscloudwatch.Metric

Metric for the number of throttled invocations of all Lambdas. Experimental.

func NodejsFunction_MetricAllUnreservedConcurrentExecutions

func NodejsFunction_MetricAllUnreservedConcurrentExecutions(props *awscloudwatch.MetricOptions) awscloudwatch.Metric

Metric for the number of unreserved concurrent executions across all Lambdas. Experimental.

Types

type BundlingOptions

type BundlingOptions struct {
	// Specify a custom hash for this asset.
	//
	// For consistency, this custom hash will
	// be SHA256 hashed and encoded as hex. The resulting hash will be the asset
	// hash.
	//
	// NOTE: the hash is used in order to identify a specific revision of the asset, and
	// used for optimizing and caching deployment activities related to this asset such as
	// packaging, uploading to Amazon S3, etc. If you chose to customize the hash, you will
	// need to make sure it is updated every time the asset changes, or otherwise it is
	// possible that some deployments will not be invalidated.
	// Experimental.
	AssetHash *string `field:"optional" json:"assetHash" yaml:"assetHash"`
	// Use this to insert an arbitrary string at the beginning of generated JavaScript files.
	//
	// This is similar to footer which inserts at the end instead of the beginning.
	//
	// This is commonly used to insert comments:.
	// Experimental.
	Banner *string `field:"optional" json:"banner" yaml:"banner"`
	// Build arguments to pass when building the bundling image.
	// Experimental.
	BuildArgs *map[string]*string `field:"optional" json:"buildArgs" yaml:"buildArgs"`
	// The charset to use for esbuild's output.
	//
	// By default esbuild's output is ASCII-only. Any non-ASCII characters are escaped
	// using backslash escape sequences. Using escape sequences makes the generated output
	// slightly bigger, and also makes it harder to read. If you would like for esbuild to print
	// the original characters without using escape sequences, use `Charset.UTF8`.
	// See: https://esbuild.github.io/api/#charset
	//
	// Experimental.
	Charset Charset `field:"optional" json:"charset" yaml:"charset"`
	// Command hooks.
	// Experimental.
	CommandHooks ICommandHooks `field:"optional" json:"commandHooks" yaml:"commandHooks"`
	// Replace global identifiers with constant expressions.
	//
	// For example, `{ 'process.env.DEBUG': 'true' }`.
	//
	// Another example, `{ 'process.env.API_KEY': JSON.stringify('xxx-xxxx-xxx') }`.
	// Experimental.
	Define *map[string]*string `field:"optional" json:"define" yaml:"define"`
	// A custom bundling Docker image.
	//
	// This image should have esbuild installed globally. If you plan to use `nodeModules`
	// it should also have `npm` or `yarn` depending on the lock file you're using.
	//
	// See https://github.com/aws/aws-cdk/blob/master/packages/%40aws-cdk/aws-lambda-nodejs/lib/Dockerfile
	// for the default image provided by @aws-cdk/aws-lambda-nodejs.
	// Experimental.
	DockerImage awscdk.DockerImage `field:"optional" json:"dockerImage" yaml:"dockerImage"`
	// Environment variables defined when bundling runs.
	// Experimental.
	Environment *map[string]*string `field:"optional" json:"environment" yaml:"environment"`
	// Build arguments to pass into esbuild.
	//
	// For example, to add the [--log-limit](https://esbuild.github.io/api/#log-limit) flag:
	//
	// “`text
	// new NodejsFunction(scope, id, {
	//    ...
	//    bundling: {
	//      esbuildArgs: {
	//        "--log-limit": "0",
	//      }
	//    }
	// });
	// “`.
	// Experimental.
	EsbuildArgs *map[string]interface{} `field:"optional" json:"esbuildArgs" yaml:"esbuildArgs"`
	// The version of esbuild to use when running in a Docker container.
	// Experimental.
	EsbuildVersion *string `field:"optional" json:"esbuildVersion" yaml:"esbuildVersion"`
	// A list of modules that should be considered as externals (already available in the runtime).
	// Experimental.
	ExternalModules *[]*string `field:"optional" json:"externalModules" yaml:"externalModules"`
	// Use this to insert an arbitrary string at the end of generated JavaScript files.
	//
	// This is similar to banner which inserts at the beginning instead of the end.
	//
	// This is commonly used to insert comments.
	// Experimental.
	Footer *string `field:"optional" json:"footer" yaml:"footer"`
	// Force bundling in a Docker container even if local bundling is possible.
	//
	// This is useful if your function relies on node modules
	// that should be installed (`nodeModules`) in a Lambda compatible
	// environment.
	// Experimental.
	ForceDockerBundling *bool `field:"optional" json:"forceDockerBundling" yaml:"forceDockerBundling"`
	// Output format for the generated JavaScript files.
	// Experimental.
	Format OutputFormat `field:"optional" json:"format" yaml:"format"`
	// This option allows you to automatically replace a global variable with an import from another file.
	// See: https://esbuild.github.io/api/#inject
	//
	// Experimental.
	Inject *[]*string `field:"optional" json:"inject" yaml:"inject"`
	// Whether to preserve the original `name` values even in minified code.
	//
	// In JavaScript the `name` property on functions and classes defaults to a
	// nearby identifier in the source code.
	//
	// However, minification renames symbols to reduce code size and bundling
	// sometimes need to rename symbols to avoid collisions. That changes value of
	// the `name` property for many of these cases. This is usually fine because
	// the `name` property is normally only used for debugging. However, some
	// frameworks rely on the `name` property for registration and binding purposes.
	// If this is the case, you can enable this option to preserve the original
	// `name` values even in minified code.
	// Experimental.
	KeepNames *bool `field:"optional" json:"keepNames" yaml:"keepNames"`
	// Use loaders to change how a given input file is interpreted.
	//
	// Configuring a loader for a given file type lets you load that file type with
	// an `import` statement or a `require` call.
	// See: https://esbuild.github.io/api/#loader
	//
	// For example, `{ '.png': 'dataurl' }`.
	//
	// Experimental.
	Loader *map[string]*string `field:"optional" json:"loader" yaml:"loader"`
	// Log level for esbuild.
	//
	// This is also propagated to the package manager and
	// applies to its specific install command.
	// Experimental.
	LogLevel LogLevel `field:"optional" json:"logLevel" yaml:"logLevel"`
	// How to determine the entry point for modules.
	//
	// Try ['module', 'main'] to default to ES module versions.
	// Experimental.
	MainFields *[]*string `field:"optional" json:"mainFields" yaml:"mainFields"`
	// This option tells esbuild to write out a JSON file relative to output directory with metadata about the build.
	//
	// The metadata in this JSON file follows this schema (specified using TypeScript syntax):
	//
	// “`text
	// {
	//    outputs: {
	//      [path: string]: {
	//        bytes: number
	//        inputs: {
	//          [path: string]: { bytesInOutput: number }
	//        }
	//        imports: { path: string }[]
	//        exports: string[]
	//      }
	//    }
	// }
	// “`
	// This data can then be analyzed by other tools. For example,
	// bundle buddy can consume esbuild's metadata format and generates a treemap visualization
	// of the modules in your bundle and how much space each one takes up.
	// See: https://esbuild.github.io/api/#metafile
	//
	// Experimental.
	Metafile *bool `field:"optional" json:"metafile" yaml:"metafile"`
	// Whether to minify files when bundling.
	// Experimental.
	Minify *bool `field:"optional" json:"minify" yaml:"minify"`
	// A list of modules that should be installed instead of bundled.
	//
	// Modules are
	// installed in a Lambda compatible environment only when bundling runs in
	// Docker.
	// Experimental.
	NodeModules *[]*string `field:"optional" json:"nodeModules" yaml:"nodeModules"`
	// Run compilation using tsc before running file through bundling step.
	//
	// This usually is not required unless you are using new experimental features that
	// are only supported by typescript's `tsc` compiler.
	// One example of such feature is `emitDecoratorMetadata`.
	// Experimental.
	PreCompilation *bool `field:"optional" json:"preCompilation" yaml:"preCompilation"`
	// Whether to include source maps when bundling.
	// Experimental.
	SourceMap *bool `field:"optional" json:"sourceMap" yaml:"sourceMap"`
	// Source map mode to be used when bundling.
	// See: https://esbuild.github.io/api/#sourcemap
	//
	// Experimental.
	SourceMapMode SourceMapMode `field:"optional" json:"sourceMapMode" yaml:"sourceMapMode"`
	// Whether to include original source code in source maps when bundling.
	// See: https://esbuild.github.io/api/#sources-content
	//
	// Experimental.
	SourcesContent *bool `field:"optional" json:"sourcesContent" yaml:"sourcesContent"`
	// Target environment for the generated JavaScript code.
	// See: https://esbuild.github.io/api/#target
	//
	// Experimental.
	Target *string `field:"optional" json:"target" yaml:"target"`
	// Normally the esbuild automatically discovers `tsconfig.json` files and reads their contents during a build.
	//
	// However, you can also configure a custom `tsconfig.json` file to use instead.
	//
	// This is similar to entry path, you need to provide path to your custom `tsconfig.json`.
	//
	// This can be useful if you need to do multiple builds of the same code with different settings.
	//
	// For example, `{ 'tsconfig': 'path/custom.tsconfig.json' }`.
	// Experimental.
	Tsconfig *string `field:"optional" json:"tsconfig" yaml:"tsconfig"`
}

Bundling options.

Example:

lambda.NewNodejsFunction(this, jsii.String("my-handler"), &nodejsFunctionProps{
	bundling: &bundlingOptions{
		dockerImage: awscdk.DockerImage.fromBuild(jsii.String("/path/to/Dockerfile")),
	},
})

Experimental.

type Charset

type Charset string

Charset for esbuild's output.

Example:

lambda.NewNodejsFunction(this, jsii.String("my-handler"), &nodejsFunctionProps{
	bundling: &bundlingOptions{
		minify: jsii.Boolean(true),
		 // minify code, defaults to false
		sourceMap: jsii.Boolean(true),
		 // include source map, defaults to false
		sourceMapMode: lambda.sourceMapMode_INLINE,
		 // defaults to SourceMapMode.DEFAULT
		sourcesContent: jsii.Boolean(false),
		 // do not include original source into source map, defaults to true
		target: jsii.String("es2020"),
		 // target environment for the generated JavaScript code
		loader: map[string]*string{
			 // Use the 'dataurl' loader for '.png' files
			".png": jsii.String("dataurl"),
		},
		define: map[string]*string{
			 // Replace strings during build time
			"process.env.API_KEY": JSON.stringify(jsii.String("xxx-xxxx-xxx")),
			"process.env.PRODUCTION": JSON.stringify(jsii.Boolean(true)),
			"process.env.NUMBER": JSON.stringify(jsii.Number(123)),
		},
		logLevel: lambda.logLevel_SILENT,
		 // defaults to LogLevel.WARNING
		keepNames: jsii.Boolean(true),
		 // defaults to false
		tsconfig: jsii.String("custom-tsconfig.json"),
		 // use custom-tsconfig.json instead of default,
		metafile: jsii.Boolean(true),
		 // include meta file, defaults to false
		banner: jsii.String("/* comments */"),
		 // requires esbuild >= 0.9.0, defaults to none
		footer: jsii.String("/* comments */"),
		 // requires esbuild >= 0.9.0, defaults to none
		charset: lambda.charset_UTF8,
		 // do not escape non-ASCII characters, defaults to Charset.ASCII
		format: lambda.outputFormat_ESM,
		 // ECMAScript module output format, defaults to OutputFormat.CJS (OutputFormat.ESM requires Node.js 14.x)
		mainFields: []*string{
			jsii.String("module"),
			jsii.String("main"),
		},
		 // prefer ECMAScript versions of dependencies
		inject: []*string{
			jsii.String("./my-shim.js"),
			jsii.String("./other-shim.js"),
		},
		 // allows to automatically replace a global variable with an import from another file
		esbuildArgs: map[string]interface{}{
			 // Pass additional arguments to esbuild
			"--log-limit": jsii.String("0"),
			"--splitting": jsii.Boolean(true),
		},
	},
})

Experimental.

const (
	// ASCII.
	//
	// Any non-ASCII characters are escaped using backslash escape sequences.
	// Experimental.
	Charset_ASCII Charset = "ASCII"
	// UTF-8.
	//
	// Keep original characters without using escape sequences.
	// Experimental.
	Charset_UTF8 Charset = "UTF8"
)

type ICommandHooks

type ICommandHooks interface {
	// Returns commands to run after bundling.
	//
	// Commands are chained with `&&`.
	// Experimental.
	AfterBundling(inputDir *string, outputDir *string) *[]*string
	// Returns commands to run before bundling.
	//
	// Commands are chained with `&&`.
	// Experimental.
	BeforeBundling(inputDir *string, outputDir *string) *[]*string
	// Returns commands to run before installing node modules.
	//
	// This hook only runs when node modules are installed.
	//
	// Commands are chained with `&&`.
	// Experimental.
	BeforeInstall(inputDir *string, outputDir *string) *[]*string
}

Command hooks.

These commands will run in the environment in which bundling occurs: inside the container for Docker bundling or on the host OS for local bundling.

Commands are chained with `&&`.

The following example (specified in TypeScript) copies a file from the input directory to the output directory to include it in the bundled asset:

```text

afterBundling(inputDir: string, outputDir: string): string[]{
   return [`cp ${inputDir}/my-binary.node ${outputDir}`];
}

```. Experimental.

type LogLevel

type LogLevel string

Log levels for esbuild and package managers' install commands.

Example:

lambda.NewNodejsFunction(this, jsii.String("my-handler"), &nodejsFunctionProps{
	bundling: &bundlingOptions{
		minify: jsii.Boolean(true),
		 // minify code, defaults to false
		sourceMap: jsii.Boolean(true),
		 // include source map, defaults to false
		sourceMapMode: lambda.sourceMapMode_INLINE,
		 // defaults to SourceMapMode.DEFAULT
		sourcesContent: jsii.Boolean(false),
		 // do not include original source into source map, defaults to true
		target: jsii.String("es2020"),
		 // target environment for the generated JavaScript code
		loader: map[string]*string{
			 // Use the 'dataurl' loader for '.png' files
			".png": jsii.String("dataurl"),
		},
		define: map[string]*string{
			 // Replace strings during build time
			"process.env.API_KEY": JSON.stringify(jsii.String("xxx-xxxx-xxx")),
			"process.env.PRODUCTION": JSON.stringify(jsii.Boolean(true)),
			"process.env.NUMBER": JSON.stringify(jsii.Number(123)),
		},
		logLevel: lambda.logLevel_SILENT,
		 // defaults to LogLevel.WARNING
		keepNames: jsii.Boolean(true),
		 // defaults to false
		tsconfig: jsii.String("custom-tsconfig.json"),
		 // use custom-tsconfig.json instead of default,
		metafile: jsii.Boolean(true),
		 // include meta file, defaults to false
		banner: jsii.String("/* comments */"),
		 // requires esbuild >= 0.9.0, defaults to none
		footer: jsii.String("/* comments */"),
		 // requires esbuild >= 0.9.0, defaults to none
		charset: lambda.charset_UTF8,
		 // do not escape non-ASCII characters, defaults to Charset.ASCII
		format: lambda.outputFormat_ESM,
		 // ECMAScript module output format, defaults to OutputFormat.CJS (OutputFormat.ESM requires Node.js 14.x)
		mainFields: []*string{
			jsii.String("module"),
			jsii.String("main"),
		},
		 // prefer ECMAScript versions of dependencies
		inject: []*string{
			jsii.String("./my-shim.js"),
			jsii.String("./other-shim.js"),
		},
		 // allows to automatically replace a global variable with an import from another file
		esbuildArgs: map[string]interface{}{
			 // Pass additional arguments to esbuild
			"--log-limit": jsii.String("0"),
			"--splitting": jsii.Boolean(true),
		},
	},
})

Experimental.

const (
	// Show everything.
	// Experimental.
	LogLevel_INFO LogLevel = "INFO"
	// Show warnings and errors.
	// Experimental.
	LogLevel_WARNING LogLevel = "WARNING"
	// Show errors only.
	// Experimental.
	LogLevel_ERROR LogLevel = "ERROR"
	// Show nothing.
	// Experimental.
	LogLevel_SILENT LogLevel = "SILENT"
)

type NodejsFunction

type NodejsFunction interface {
	awslambda.Function
	// The architecture of this Lambda Function (this is an optional attribute and defaults to X86_64).
	// Experimental.
	Architecture() awslambda.Architecture
	// Whether the addPermission() call adds any permissions.
	//
	// True for new Lambdas, false for version $LATEST and imported Lambdas
	// from different accounts.
	// Experimental.
	CanCreatePermissions() *bool
	// Access the Connections object.
	//
	// Will fail if not a VPC-enabled Lambda Function.
	// Experimental.
	Connections() awsec2.Connections
	// Returns a `lambda.Version` which represents the current version of this Lambda function. A new version will be created every time the function's configuration changes.
	//
	// You can specify options for this version using the `currentVersionOptions`
	// prop when initializing the `lambda.Function`.
	// Experimental.
	CurrentVersion() awslambda.Version
	// The DLQ (as queue) associated with this Lambda Function (this is an optional attribute).
	// Experimental.
	DeadLetterQueue() awssqs.IQueue
	// The DLQ (as topic) associated with this Lambda Function (this is an optional attribute).
	// Experimental.
	DeadLetterTopic() awssns.ITopic
	// The environment this resource belongs to.
	//
	// For resources that are created and managed by the CDK
	// (generally, those created by creating new class instances like Role, Bucket, etc.),
	// this is always the same as the environment of the stack they belong to;
	// however, for imported resources
	// (those obtained from static methods like fromRoleArn, fromBucketName, etc.),
	// that might be different than the stack they were imported into.
	// Experimental.
	Env() *awscdk.ResourceEnvironment
	// ARN of this function.
	// Experimental.
	FunctionArn() *string
	// Name of this function.
	// Experimental.
	FunctionName() *string
	// The principal this Lambda Function is running as.
	// Experimental.
	GrantPrincipal() awsiam.IPrincipal
	// Whether or not this Lambda function was bound to a VPC.
	//
	// If this is is `false`, trying to access the `connections` object will fail.
	// Experimental.
	IsBoundToVpc() *bool
	// The `$LATEST` version of this function.
	//
	// Note that this is reference to a non-specific AWS Lambda version, which
	// means the function this version refers to can return different results in
	// different invocations.
	//
	// To obtain a reference to an explicit version which references the current
	// function configuration, use `lambdaFunction.currentVersion` instead.
	// Experimental.
	LatestVersion() awslambda.IVersion
	// The LogGroup where the Lambda function's logs are made available.
	//
	// If either `logRetention` is set or this property is called, a CloudFormation custom resource is added to the stack that
	// pre-creates the log group as part of the stack deployment, if it already doesn't exist, and sets the correct log retention
	// period (never expire, by default).
	//
	// Further, if the log group already exists and the `logRetention` is not set, the custom resource will reset the log retention
	// to never expire even if it was configured with a different value.
	// Experimental.
	LogGroup() awslogs.ILogGroup
	// The construct tree node associated with this construct.
	// Experimental.
	Node() awscdk.ConstructNode
	// The construct node where permissions are attached.
	// Experimental.
	PermissionsNode() awscdk.ConstructNode
	// Returns a string-encoded token that resolves to the physical name that should be passed to the CloudFormation resource.
	//
	// This value will resolve to one of the following:
	// - a concrete value (e.g. `"my-awesome-bucket"`)
	// - `undefined`, when a name should be generated by CloudFormation
	// - a concrete name generated automatically during synthesis, in
	//    cross-environment scenarios.
	// Experimental.
	PhysicalName() *string
	// The ARN(s) to put into the resource field of the generated IAM policy for grantInvoke().
	// Experimental.
	ResourceArnsForGrantInvoke() *[]*string
	// Execution role associated with this function.
	// Experimental.
	Role() awsiam.IRole
	// The runtime configured for this lambda.
	// Experimental.
	Runtime() awslambda.Runtime
	// The stack in which this resource is defined.
	// Experimental.
	Stack() awscdk.Stack
	// The timeout configured for this lambda.
	// Experimental.
	Timeout() awscdk.Duration
	// Defines an alias for this function.
	//
	// The alias will automatically be updated to point to the latest version of
	// the function as it is being updated during a deployment.
	//
	// “`ts
	// declare const fn: lambda.Function;
	//
	// fn.addAlias('Live');
	//
	// // Is equivalent to
	//
	// new lambda.Alias(this, 'AliasLive', {
	//    aliasName: 'Live',
	//    version: fn.currentVersion,
	// });.
	// Experimental.
	AddAlias(aliasName *string, options *awslambda.AliasOptions) awslambda.Alias
	// Adds an environment variable to this Lambda function.
	//
	// If this is a ref to a Lambda function, this operation results in a no-op.
	// Experimental.
	AddEnvironment(key *string, value *string, options *awslambda.EnvironmentOptions) awslambda.Function
	// Adds an event source to this function.
	//
	// Event sources are implemented in the @aws-cdk/aws-lambda-event-sources module.
	//
	// The following example adds an SQS Queue as an event source:
	// “`
	// import { SqsEventSource } from '@aws-cdk/aws-lambda-event-sources';
	// myFunction.addEventSource(new SqsEventSource(myQueue));
	// “`.
	// Experimental.
	AddEventSource(source awslambda.IEventSource)
	// Adds an event source that maps to this AWS Lambda function.
	// Experimental.
	AddEventSourceMapping(id *string, options *awslambda.EventSourceMappingOptions) awslambda.EventSourceMapping
	// Adds a url to this lambda function.
	// Experimental.
	AddFunctionUrl(options *awslambda.FunctionUrlOptions) awslambda.FunctionUrl
	// Adds one or more Lambda Layers to this Lambda function.
	// Experimental.
	AddLayers(layers ...awslambda.ILayerVersion)
	// Adds a permission to the Lambda resource policy.
	// See: Permission for details.
	//
	// Experimental.
	AddPermission(id *string, permission *awslambda.Permission)
	// Adds a statement to the IAM role assumed by the instance.
	// Experimental.
	AddToRolePolicy(statement awsiam.PolicyStatement)
	// Add a new version for this Lambda.
	//
	// If you want to deploy through CloudFormation and use aliases, you need to
	// add a new version (with a new name) to your Lambda every time you want to
	// deploy an update. An alias can then refer to the newly created Version.
	//
	// All versions should have distinct names, and you should not delete versions
	// as long as your Alias needs to refer to them.
	//
	// Returns: A new Version object.
	// Deprecated: This method will create an AWS::Lambda::Version resource which
	// snapshots the AWS Lambda function *at the time of its creation* and it
	// won't get updated when the function changes. Instead, use
	// `this.currentVersion` to obtain a reference to a version resource that gets
	// automatically recreated when the function configuration (or code) changes.
	AddVersion(name *string, codeSha256 *string, description *string, provisionedExecutions *float64, asyncInvokeConfig *awslambda.EventInvokeConfigOptions) awslambda.Version
	// Apply the given removal policy to this resource.
	//
	// The Removal Policy controls what happens to this resource when it stops
	// being managed by CloudFormation, either because you've removed it from the
	// CDK application or because you've made a change that requires the resource
	// to be replaced.
	//
	// The resource can be deleted (`RemovalPolicy.DESTROY`), or left in your AWS
	// account for data recovery and cleanup later (`RemovalPolicy.RETAIN`).
	// Experimental.
	ApplyRemovalPolicy(policy awscdk.RemovalPolicy)
	// Configures options for asynchronous invocation.
	// Experimental.
	ConfigureAsyncInvoke(options *awslambda.EventInvokeConfigOptions)
	// A warning will be added to functions under the following conditions: - permissions that include `lambda:InvokeFunction` are added to the unqualified function.
	//
	// - function.currentVersion is invoked before or after the permission is created.
	//
	// This applies only to permissions on Lambda functions, not versions or aliases.
	// This function is overridden as a noOp for QualifiedFunctionBase.
	// Experimental.
	ConsiderWarningOnInvokeFunctionPermissions(scope awscdk.Construct, action *string)
	// Experimental.
	GeneratePhysicalName() *string
	// Returns an environment-sensitive token that should be used for the resource's "ARN" attribute (e.g. `bucket.bucketArn`).
	//
	// Normally, this token will resolve to `arnAttr`, but if the resource is
	// referenced across environments, `arnComponents` will be used to synthesize
	// a concrete ARN with the resource's physical name. Make sure to reference
	// `this.physicalName` in `arnComponents`.
	// Experimental.
	GetResourceArnAttribute(arnAttr *string, arnComponents *awscdk.ArnComponents) *string
	// Returns an environment-sensitive token that should be used for the resource's "name" attribute (e.g. `bucket.bucketName`).
	//
	// Normally, this token will resolve to `nameAttr`, but if the resource is
	// referenced across environments, it will be resolved to `this.physicalName`,
	// which will be a concrete name.
	// Experimental.
	GetResourceNameAttribute(nameAttr *string) *string
	// Grant the given identity permissions to invoke this Lambda.
	// Experimental.
	GrantInvoke(grantee awsiam.IGrantable) awsiam.Grant
	// Grant the given identity permissions to invoke this Lambda Function URL.
	// Experimental.
	GrantInvokeUrl(grantee awsiam.IGrantable) awsiam.Grant
	// Return the given named metric for this Function.
	// Experimental.
	Metric(metricName *string, props *awscloudwatch.MetricOptions) awscloudwatch.Metric
	// How long execution of this Lambda takes.
	//
	// Average over 5 minutes.
	// Experimental.
	MetricDuration(props *awscloudwatch.MetricOptions) awscloudwatch.Metric
	// How many invocations of this Lambda fail.
	//
	// Sum over 5 minutes.
	// Experimental.
	MetricErrors(props *awscloudwatch.MetricOptions) awscloudwatch.Metric
	// How often this Lambda is invoked.
	//
	// Sum over 5 minutes.
	// Experimental.
	MetricInvocations(props *awscloudwatch.MetricOptions) awscloudwatch.Metric
	// How often this Lambda is throttled.
	//
	// Sum over 5 minutes.
	// Experimental.
	MetricThrottles(props *awscloudwatch.MetricOptions) awscloudwatch.Metric
	// Perform final modifications before synthesis.
	//
	// This method can be implemented by derived constructs in order to perform
	// final changes before synthesis. prepare() will be called after child
	// constructs have been prepared.
	//
	// This is an advanced framework feature. Only use this if you
	// understand the implications.
	// Experimental.
	OnPrepare()
	// Allows this construct to emit artifacts into the cloud assembly during synthesis.
	//
	// This method is usually implemented by framework-level constructs such as `Stack` and `Asset`
	// as they participate in synthesizing the cloud assembly.
	// Experimental.
	OnSynthesize(session constructs.ISynthesisSession)
	// Validate the current construct.
	//
	// This method can be implemented by derived constructs in order to perform
	// validation logic. It is called on all constructs before synthesis.
	//
	// Returns: An array of validation error messages, or an empty array if the construct is valid.
	// Experimental.
	OnValidate() *[]*string
	// Perform final modifications before synthesis.
	//
	// This method can be implemented by derived constructs in order to perform
	// final changes before synthesis. prepare() will be called after child
	// constructs have been prepared.
	//
	// This is an advanced framework feature. Only use this if you
	// understand the implications.
	// Experimental.
	Prepare()
	// Allows this construct to emit artifacts into the cloud assembly during synthesis.
	//
	// This method is usually implemented by framework-level constructs such as `Stack` and `Asset`
	// as they participate in synthesizing the cloud assembly.
	// Experimental.
	Synthesize(session awscdk.ISynthesisSession)
	// Returns a string representation of this construct.
	// Experimental.
	ToString() *string
	// Validate the current construct.
	//
	// This method can be implemented by derived constructs in order to perform
	// validation logic. It is called on all constructs before synthesis.
	//
	// Returns: An array of validation error messages, or an empty array if the construct is valid.
	// Experimental.
	Validate() *[]*string
	// Experimental.
	WarnInvokeFunctionPermissions(scope awscdk.Construct)
}

A Node.js Lambda function bundled using esbuild.

Example:

lambda.NewNodejsFunction(this, jsii.String("my-handler"), &nodejsFunctionProps{
	bundling: &bundlingOptions{
		dockerImage: awscdk.DockerImage.fromBuild(jsii.String("/path/to/Dockerfile")),
	},
})

Experimental.

func NewNodejsFunction

func NewNodejsFunction(scope awscdk.Construct, id *string, props *NodejsFunctionProps) NodejsFunction

Experimental.

type NodejsFunctionProps

type NodejsFunctionProps struct {
	// The maximum age of a request that Lambda sends to a function for processing.
	//
	// Minimum: 60 seconds
	// Maximum: 6 hours.
	// Experimental.
	MaxEventAge awscdk.Duration `field:"optional" json:"maxEventAge" yaml:"maxEventAge"`
	// The destination for failed invocations.
	// Experimental.
	OnFailure awslambda.IDestination `field:"optional" json:"onFailure" yaml:"onFailure"`
	// The destination for successful invocations.
	// Experimental.
	OnSuccess awslambda.IDestination `field:"optional" json:"onSuccess" yaml:"onSuccess"`
	// The maximum number of times to retry when the function returns an error.
	//
	// Minimum: 0
	// Maximum: 2.
	// Experimental.
	RetryAttempts *float64 `field:"optional" json:"retryAttempts" yaml:"retryAttempts"`
	// Whether to allow the Lambda to send all network traffic.
	//
	// If set to false, you must individually add traffic rules to allow the
	// Lambda to connect to network targets.
	// Experimental.
	AllowAllOutbound *bool `field:"optional" json:"allowAllOutbound" yaml:"allowAllOutbound"`
	// Lambda Functions in a public subnet can NOT access the internet.
	//
	// Use this property to acknowledge this limitation and still place the function in a public subnet.
	// See: https://stackoverflow.com/questions/52992085/why-cant-an-aws-lambda-function-inside-a-public-subnet-in-a-vpc-connect-to-the/52994841#52994841
	//
	// Experimental.
	AllowPublicSubnet *bool `field:"optional" json:"allowPublicSubnet" yaml:"allowPublicSubnet"`
	// The system architectures compatible with this lambda function.
	// Experimental.
	Architecture awslambda.Architecture `field:"optional" json:"architecture" yaml:"architecture"`
	// DEPRECATED.
	// Deprecated: use `architecture`.
	Architectures *[]awslambda.Architecture `field:"optional" json:"architectures" yaml:"architectures"`
	// Code signing config associated with this function.
	// Experimental.
	CodeSigningConfig awslambda.ICodeSigningConfig `field:"optional" json:"codeSigningConfig" yaml:"codeSigningConfig"`
	// Options for the `lambda.Version` resource automatically created by the `fn.currentVersion` method.
	// Experimental.
	CurrentVersionOptions *awslambda.VersionOptions `field:"optional" json:"currentVersionOptions" yaml:"currentVersionOptions"`
	// The SQS queue to use if DLQ is enabled.
	//
	// If SNS topic is desired, specify `deadLetterTopic` property instead.
	// Experimental.
	DeadLetterQueue awssqs.IQueue `field:"optional" json:"deadLetterQueue" yaml:"deadLetterQueue"`
	// Enabled DLQ.
	//
	// If `deadLetterQueue` is undefined,
	// an SQS queue with default options will be defined for your Function.
	// Experimental.
	DeadLetterQueueEnabled *bool `field:"optional" json:"deadLetterQueueEnabled" yaml:"deadLetterQueueEnabled"`
	// The SNS topic to use as a DLQ.
	//
	// Note that if `deadLetterQueueEnabled` is set to `true`, an SQS queue will be created
	// rather than an SNS topic. Using an SNS topic as a DLQ requires this property to be set explicitly.
	// Experimental.
	DeadLetterTopic awssns.ITopic `field:"optional" json:"deadLetterTopic" yaml:"deadLetterTopic"`
	// A description of the function.
	// Experimental.
	Description *string `field:"optional" json:"description" yaml:"description"`
	// Key-value pairs that Lambda caches and makes available for your Lambda functions.
	//
	// Use environment variables to apply configuration changes, such
	// as test and production environment configurations, without changing your
	// Lambda function source code.
	// Experimental.
	Environment *map[string]*string `field:"optional" json:"environment" yaml:"environment"`
	// The AWS KMS key that's used to encrypt your function's environment variables.
	// Experimental.
	EnvironmentEncryption awskms.IKey `field:"optional" json:"environmentEncryption" yaml:"environmentEncryption"`
	// The size of the function’s /tmp directory in MiB.
	// Experimental.
	EphemeralStorageSize awscdk.Size `field:"optional" json:"ephemeralStorageSize" yaml:"ephemeralStorageSize"`
	// Event sources for this function.
	//
	// You can also add event sources using `addEventSource`.
	// Experimental.
	Events *[]awslambda.IEventSource `field:"optional" json:"events" yaml:"events"`
	// The filesystem configuration for the lambda function.
	// Experimental.
	Filesystem awslambda.FileSystem `field:"optional" json:"filesystem" yaml:"filesystem"`
	// A name for the function.
	// Experimental.
	FunctionName *string `field:"optional" json:"functionName" yaml:"functionName"`
	// Initial policy statements to add to the created Lambda Role.
	//
	// You can call `addToRolePolicy` to the created lambda to add statements post creation.
	// Experimental.
	InitialPolicy *[]awsiam.PolicyStatement `field:"optional" json:"initialPolicy" yaml:"initialPolicy"`
	// Specify the version of CloudWatch Lambda insights to use for monitoring.
	// See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Lambda-Insights-Getting-Started-docker.html
	//
	// Experimental.
	InsightsVersion awslambda.LambdaInsightsVersion `field:"optional" json:"insightsVersion" yaml:"insightsVersion"`
	// A list of layers to add to the function's execution environment.
	//
	// You can configure your Lambda function to pull in
	// additional code during initialization in the form of layers. Layers are packages of libraries or other dependencies
	// that can be used by multiple functions.
	// Experimental.
	Layers *[]awslambda.ILayerVersion `field:"optional" json:"layers" yaml:"layers"`
	// The number of days log events are kept in CloudWatch Logs.
	//
	// When updating
	// this property, unsetting it doesn't remove the log retention policy. To
	// remove the retention policy, set the value to `INFINITE`.
	// Experimental.
	LogRetention awslogs.RetentionDays `field:"optional" json:"logRetention" yaml:"logRetention"`
	// When log retention is specified, a custom resource attempts to create the CloudWatch log group.
	//
	// These options control the retry policy when interacting with CloudWatch APIs.
	// Experimental.
	LogRetentionRetryOptions *awslambda.LogRetentionRetryOptions `field:"optional" json:"logRetentionRetryOptions" yaml:"logRetentionRetryOptions"`
	// The IAM role for the Lambda function associated with the custom resource that sets the retention policy.
	// Experimental.
	LogRetentionRole awsiam.IRole `field:"optional" json:"logRetentionRole" yaml:"logRetentionRole"`
	// The amount of memory, in MB, that is allocated to your Lambda function.
	//
	// Lambda uses this value to proportionally allocate the amount of CPU
	// power. For more information, see Resource Model in the AWS Lambda
	// Developer Guide.
	// Experimental.
	MemorySize *float64 `field:"optional" json:"memorySize" yaml:"memorySize"`
	// Enable profiling.
	// See: https://docs.aws.amazon.com/codeguru/latest/profiler-ug/setting-up-lambda.html
	//
	// Experimental.
	Profiling *bool `field:"optional" json:"profiling" yaml:"profiling"`
	// Profiling Group.
	// See: https://docs.aws.amazon.com/codeguru/latest/profiler-ug/setting-up-lambda.html
	//
	// Experimental.
	ProfilingGroup awscodeguruprofiler.IProfilingGroup `field:"optional" json:"profilingGroup" yaml:"profilingGroup"`
	// The maximum of concurrent executions you want to reserve for the function.
	// See: https://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html
	//
	// Experimental.
	ReservedConcurrentExecutions *float64 `field:"optional" json:"reservedConcurrentExecutions" yaml:"reservedConcurrentExecutions"`
	// Lambda execution role.
	//
	// This is the role that will be assumed by the function upon execution.
	// It controls the permissions that the function will have. The Role must
	// be assumable by the 'lambda.amazonaws.com' service principal.
	//
	// The default Role automatically has permissions granted for Lambda execution. If you
	// provide a Role, you must add the relevant AWS managed policies yourself.
	//
	// The relevant managed policies are "service-role/AWSLambdaBasicExecutionRole" and
	// "service-role/AWSLambdaVPCAccessExecutionRole".
	// Experimental.
	Role awsiam.IRole `field:"optional" json:"role" yaml:"role"`
	// What security group to associate with the Lambda's network interfaces. This property is being deprecated, consider using securityGroups instead.
	//
	// Only used if 'vpc' is supplied.
	//
	// Use securityGroups property instead.
	// Function constructor will throw an error if both are specified.
	// Deprecated: - This property is deprecated, use securityGroups instead.
	SecurityGroup awsec2.ISecurityGroup `field:"optional" json:"securityGroup" yaml:"securityGroup"`
	// The list of security groups to associate with the Lambda's network interfaces.
	//
	// Only used if 'vpc' is supplied.
	// Experimental.
	SecurityGroups *[]awsec2.ISecurityGroup `field:"optional" json:"securityGroups" yaml:"securityGroups"`
	// The function execution time (in seconds) after which Lambda terminates the function.
	//
	// Because the execution time affects cost, set this value
	// based on the function's expected execution time.
	// Experimental.
	Timeout awscdk.Duration `field:"optional" json:"timeout" yaml:"timeout"`
	// Enable AWS X-Ray Tracing for Lambda Function.
	// Experimental.
	Tracing awslambda.Tracing `field:"optional" json:"tracing" yaml:"tracing"`
	// VPC network to place Lambda network interfaces.
	//
	// Specify this if the Lambda function needs to access resources in a VPC.
	// Experimental.
	Vpc awsec2.IVpc `field:"optional" json:"vpc" yaml:"vpc"`
	// Where to place the network interfaces within the VPC.
	//
	// Only used if 'vpc' is supplied. Note: internet access for Lambdas
	// requires a NAT gateway, so picking Public subnets is not allowed.
	// Experimental.
	VpcSubnets *awsec2.SubnetSelection `field:"optional" json:"vpcSubnets" yaml:"vpcSubnets"`
	// Whether to automatically reuse TCP connections when working with the AWS SDK for JavaScript.
	//
	// This sets the `AWS_NODEJS_CONNECTION_REUSE_ENABLED` environment variable
	// to `1`.
	// See: https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/node-reusing-connections.html
	//
	// Experimental.
	AwsSdkConnectionReuse *bool `field:"optional" json:"awsSdkConnectionReuse" yaml:"awsSdkConnectionReuse"`
	// Bundling options.
	// Experimental.
	Bundling *BundlingOptions `field:"optional" json:"bundling" yaml:"bundling"`
	// The path to the dependencies lock file (`yarn.lock` or `package-lock.json`).
	//
	// This will be used as the source for the volume mounted in the Docker
	// container.
	//
	// Modules specified in `nodeModules` will be installed using the right
	// installer (`npm` or `yarn`) along with this lock file.
	// Experimental.
	DepsLockFilePath *string `field:"optional" json:"depsLockFilePath" yaml:"depsLockFilePath"`
	// Path to the entry file (JavaScript or TypeScript).
	// Experimental.
	Entry *string `field:"optional" json:"entry" yaml:"entry"`
	// The name of the exported handler in the entry file.
	// Experimental.
	Handler *string `field:"optional" json:"handler" yaml:"handler"`
	// The path to the directory containing project config files (`package.json` or `tsconfig.json`).
	// Experimental.
	ProjectRoot *string `field:"optional" json:"projectRoot" yaml:"projectRoot"`
	// The runtime environment.
	//
	// Only runtimes of the Node.js family are
	// supported.
	// Experimental.
	Runtime awslambda.Runtime `field:"optional" json:"runtime" yaml:"runtime"`
}

Properties for a NodejsFunction.

Example:

lambda.NewNodejsFunction(this, jsii.String("my-handler"), &nodejsFunctionProps{
	bundling: &bundlingOptions{
		minify: jsii.Boolean(true),
		 // minify code, defaults to false
		sourceMap: jsii.Boolean(true),
		 // include source map, defaults to false
		sourceMapMode: lambda.sourceMapMode_INLINE,
		 // defaults to SourceMapMode.DEFAULT
		sourcesContent: jsii.Boolean(false),
		 // do not include original source into source map, defaults to true
		target: jsii.String("es2020"),
		 // target environment for the generated JavaScript code
		loader: map[string]*string{
			 // Use the 'dataurl' loader for '.png' files
			".png": jsii.String("dataurl"),
		},
		define: map[string]*string{
			 // Replace strings during build time
			"process.env.API_KEY": JSON.stringify(jsii.String("xxx-xxxx-xxx")),
			"process.env.PRODUCTION": JSON.stringify(jsii.Boolean(true)),
			"process.env.NUMBER": JSON.stringify(jsii.Number(123)),
		},
		logLevel: lambda.logLevel_SILENT,
		 // defaults to LogLevel.WARNING
		keepNames: jsii.Boolean(true),
		 // defaults to false
		tsconfig: jsii.String("custom-tsconfig.json"),
		 // use custom-tsconfig.json instead of default,
		metafile: jsii.Boolean(true),
		 // include meta file, defaults to false
		banner: jsii.String("/* comments */"),
		 // requires esbuild >= 0.9.0, defaults to none
		footer: jsii.String("/* comments */"),
		 // requires esbuild >= 0.9.0, defaults to none
		charset: lambda.charset_UTF8,
		 // do not escape non-ASCII characters, defaults to Charset.ASCII
		format: lambda.outputFormat_ESM,
		 // ECMAScript module output format, defaults to OutputFormat.CJS (OutputFormat.ESM requires Node.js 14.x)
		mainFields: []*string{
			jsii.String("module"),
			jsii.String("main"),
		},
		 // prefer ECMAScript versions of dependencies
		inject: []*string{
			jsii.String("./my-shim.js"),
			jsii.String("./other-shim.js"),
		},
		 // allows to automatically replace a global variable with an import from another file
		esbuildArgs: map[string]interface{}{
			 // Pass additional arguments to esbuild
			"--log-limit": jsii.String("0"),
			"--splitting": jsii.Boolean(true),
		},
	},
})

Experimental.

type OutputFormat

type OutputFormat string

Output format for the generated JavaScript files.

Example:

lambda.NewNodejsFunction(this, jsii.String("my-handler"), &nodejsFunctionProps{
	bundling: &bundlingOptions{
		minify: jsii.Boolean(true),
		 // minify code, defaults to false
		sourceMap: jsii.Boolean(true),
		 // include source map, defaults to false
		sourceMapMode: lambda.sourceMapMode_INLINE,
		 // defaults to SourceMapMode.DEFAULT
		sourcesContent: jsii.Boolean(false),
		 // do not include original source into source map, defaults to true
		target: jsii.String("es2020"),
		 // target environment for the generated JavaScript code
		loader: map[string]*string{
			 // Use the 'dataurl' loader for '.png' files
			".png": jsii.String("dataurl"),
		},
		define: map[string]*string{
			 // Replace strings during build time
			"process.env.API_KEY": JSON.stringify(jsii.String("xxx-xxxx-xxx")),
			"process.env.PRODUCTION": JSON.stringify(jsii.Boolean(true)),
			"process.env.NUMBER": JSON.stringify(jsii.Number(123)),
		},
		logLevel: lambda.logLevel_SILENT,
		 // defaults to LogLevel.WARNING
		keepNames: jsii.Boolean(true),
		 // defaults to false
		tsconfig: jsii.String("custom-tsconfig.json"),
		 // use custom-tsconfig.json instead of default,
		metafile: jsii.Boolean(true),
		 // include meta file, defaults to false
		banner: jsii.String("/* comments */"),
		 // requires esbuild >= 0.9.0, defaults to none
		footer: jsii.String("/* comments */"),
		 // requires esbuild >= 0.9.0, defaults to none
		charset: lambda.charset_UTF8,
		 // do not escape non-ASCII characters, defaults to Charset.ASCII
		format: lambda.outputFormat_ESM,
		 // ECMAScript module output format, defaults to OutputFormat.CJS (OutputFormat.ESM requires Node.js 14.x)
		mainFields: []*string{
			jsii.String("module"),
			jsii.String("main"),
		},
		 // prefer ECMAScript versions of dependencies
		inject: []*string{
			jsii.String("./my-shim.js"),
			jsii.String("./other-shim.js"),
		},
		 // allows to automatically replace a global variable with an import from another file
		esbuildArgs: map[string]interface{}{
			 // Pass additional arguments to esbuild
			"--log-limit": jsii.String("0"),
			"--splitting": jsii.Boolean(true),
		},
	},
})

Experimental.

const (
	// CommonJS.
	// Experimental.
	OutputFormat_CJS OutputFormat = "CJS"
	// ECMAScript module.
	//
	// Requires a running environment that supports `import` and `export` syntax.
	// Experimental.
	OutputFormat_ESM OutputFormat = "ESM"
)

type SourceMapMode

type SourceMapMode string

SourceMap mode for esbuild.

Example:

lambda.NewNodejsFunction(this, jsii.String("my-handler"), &nodejsFunctionProps{
	bundling: &bundlingOptions{
		minify: jsii.Boolean(true),
		 // minify code, defaults to false
		sourceMap: jsii.Boolean(true),
		 // include source map, defaults to false
		sourceMapMode: lambda.sourceMapMode_INLINE,
		 // defaults to SourceMapMode.DEFAULT
		sourcesContent: jsii.Boolean(false),
		 // do not include original source into source map, defaults to true
		target: jsii.String("es2020"),
		 // target environment for the generated JavaScript code
		loader: map[string]*string{
			 // Use the 'dataurl' loader for '.png' files
			".png": jsii.String("dataurl"),
		},
		define: map[string]*string{
			 // Replace strings during build time
			"process.env.API_KEY": JSON.stringify(jsii.String("xxx-xxxx-xxx")),
			"process.env.PRODUCTION": JSON.stringify(jsii.Boolean(true)),
			"process.env.NUMBER": JSON.stringify(jsii.Number(123)),
		},
		logLevel: lambda.logLevel_SILENT,
		 // defaults to LogLevel.WARNING
		keepNames: jsii.Boolean(true),
		 // defaults to false
		tsconfig: jsii.String("custom-tsconfig.json"),
		 // use custom-tsconfig.json instead of default,
		metafile: jsii.Boolean(true),
		 // include meta file, defaults to false
		banner: jsii.String("/* comments */"),
		 // requires esbuild >= 0.9.0, defaults to none
		footer: jsii.String("/* comments */"),
		 // requires esbuild >= 0.9.0, defaults to none
		charset: lambda.charset_UTF8,
		 // do not escape non-ASCII characters, defaults to Charset.ASCII
		format: lambda.outputFormat_ESM,
		 // ECMAScript module output format, defaults to OutputFormat.CJS (OutputFormat.ESM requires Node.js 14.x)
		mainFields: []*string{
			jsii.String("module"),
			jsii.String("main"),
		},
		 // prefer ECMAScript versions of dependencies
		inject: []*string{
			jsii.String("./my-shim.js"),
			jsii.String("./other-shim.js"),
		},
		 // allows to automatically replace a global variable with an import from another file
		esbuildArgs: map[string]interface{}{
			 // Pass additional arguments to esbuild
			"--log-limit": jsii.String("0"),
			"--splitting": jsii.Boolean(true),
		},
	},
})

See: https://esbuild.github.io/api/#sourcemap

Experimental.

const (
	// Default sourceMap mode - will generate a .js.map file alongside any generated .js file and add a special //# sourceMappingURL= comment to the bottom of the .js file pointing to the .js.map file.
	// Experimental.
	SourceMapMode_DEFAULT SourceMapMode = "DEFAULT"
	// External sourceMap mode - If you want to omit the special //# sourceMappingURL= comment from the generated .js file but you still want to generate the .js.map files.
	// Experimental.
	SourceMapMode_EXTERNAL SourceMapMode = "EXTERNAL"
	// Inline sourceMap mode - If you want to insert the entire source map into the .js file instead of generating a separate .js.map file.
	// Experimental.
	SourceMapMode_INLINE SourceMapMode = "INLINE"
	// Both sourceMap mode - If you want to have the effect of both inline and external simultaneously.
	// Experimental.
	SourceMapMode_BOTH SourceMapMode = "BOTH"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL