agent-claw: automated task changes

This commit is contained in:
daniel
2026-05-06 18:55:16 -05:00
parent 38905bb1e9
commit 732b00fb66
8494 changed files with 2018127 additions and 4 deletions

View File

@@ -0,0 +1,13 @@
{
"targets": {
"java": {
"package": "software.amazon.awscdk.services.lambda.nodejs"
},
"dotnet": {
"namespace": "Amazon.CDK.AWS.Lambda.Nodejs"
},
"python": {
"module": "aws_cdk.aws_lambda_nodejs"
}
}
}

View File

@@ -0,0 +1,454 @@
# 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](https://esbuild.github.io/) 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:
```plaintext
.
├── 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:
```ts
// automatic entry look up
const apiHandler = new nodejs.NodejsFunction(this, 'api');
const authHandler = new nodejs.NodejsFunction(this, 'auth');
```
Alternatively, an entry file and handler can be specified:
```ts
new nodejs.NodejsFunction(this, 'MyFunction', {
entry: '/path/to/my/file.ts', // accepts .js, .jsx, .cjs, .mjs, .ts, .tsx, .cts and .mts files
handler: 'myExportedFunc', // defaults to 'handler'
});
```
The handler value will be automatically prefixed with the bundled output file name, `index.`,
unless the handler value contains a `.` character, in which case the handler value is used as-is to
allow for values needed by some Lambda extensions.
For monorepos, the reference architecture becomes:
```plaintext
.
├── 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](https://github.com/aws/aws-cdk/tree/main/packages/aws-cdk-lib/aws-lambda).
The `NodejsFunction` construct automatically [reuses existing connections](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/node-reusing-connections.html)
when working with the AWS SDK v2 for JavaScript. Set the `awsSdkConnectionReuse` prop to `false` to disable it.
The AWS SDK v3 for JavaScript does not include the environment variable set by `awsSdkConnectionReuse`. See [this guide](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-reusing-connections.html) for information about reusing connections. Therefore, for runtimes >= Node 18, which include SDK v3, the prop defaults to `false`, and must be explicitly set to `true` in order for the environment variable to be set.
## Runtime
When the `@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion` feature flag is enabled, the `NODEJS_LATEST` runtime
will be used by default. This runtime will be updated to use the latest Node.js version currently available in lambda.
Since this runtime can change from version to version, you should ensure that all of your dependencies are included
during packaging and avoid relying on depdendencies being globally installed. See [externals](#externals) for details.
**When using `NODEJS_LATEST` runtime make sure that all of your dependencies are included during bundling, or as layers.
Usage of globally installed packages in the lambda environment may cause your function to break in future versions. If
you need to rely on packages pre-installed in the lambda environment, you must explicitly set your runtime.**
This can be set via `lambda.Runtime`:
```ts
import { Runtime } from 'aws-cdk-lib/aws-lambda';
new nodejs.NodejsFunction(this, 'my-function', {
runtime: Runtime.NODEJS_LATEST,
});
```
With the `@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion` disabled, the runtime will default to `NODEJ_16_X`.
## Lock file
The `NodejsFunction` requires a dependencies lock file (`yarn.lock`, `pnpm-lock.yaml`, `bun.lockb`,
`bun.lock` 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](https://gallery.ecr.aws/sam/build-nodejs22.x)
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:
```console
$ npm install --save-dev esbuild@0
```
OR
```console
$ 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](#reference-project-architecture), 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](#install-modules)) in a Lambda
compatible environment. This is usually the case with modules using native dependencies.
## Working with modules
### Externals
When the `NODEJS_LATEST` runtime is used, no modules are excluded from bundling by default. This is because the runtime
will change as new NodeJs versions become available in lambda, which may change what packages are vended as part of the
environment.
When passing a runtime that is known to include a version of the aws sdk, it will be excluded by default. For example, when
passing `NODEJS_16_X`, `aws-sdk` is excluded. When passing `NODEJS_18_X`, all `@aws-sdk/*` packages are excluded.
> [!WARNING]
> The NodeJS runtime of Node 16 will be deprecated by Lambda on June 12, 2024. Lambda runtimes Node 18 and higher include SDKv3 and not SDKv2. Updating your Lambda runtime from <=Node 16 to any newer version will require bundling the SDK with your handler code, or updating all SDK calls in your handler code to use SDKv3 (which is not a trivial update). Please account for this added complexity and update as soon as possible.
This can be configured by specifying `bundling.externalModules`:
```ts
new nodejs.NodejsFunction(this, 'my-handler', {
bundling: {
externalModules: [
'@aws-sdk/*', // Use the AWS SDK for JS v3 available in the Lambda runtime
'cool-module', // 'cool-module' is already available in a Layer
],
},
});
```
Includes AWS SDK in the bundle asset by setting `bundleAwsSDK` to `true`. This will exclude SDK from the external module and would not be resolved to Lambda provided SDK.
```ts
new nodejs.NodejsFunction(this, 'my-handler', {
bundling: {
bundleAwsSDK: true,
},
});
```
### 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.
```ts
new nodejs.NodejsFunction(this, 'my-handler', {
bundling: {
nodeModules: ['native-module', '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`, `bun.lockb`, `bun.lock` or `package-lock.json`) will be used along with the right installer (`yarn`,
`pnpm`, `bun` 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](https://esbuild.github.io/api/#build-api)
via properties under `bundling`:
```ts
new nodejs.NodejsFunction(this, 'my-handler', {
bundling: {
minify: true, // minify code, defaults to false
sourceMap: true, // include source map, defaults to false
sourceMapMode: nodejs.SourceMapMode.INLINE, // defaults to SourceMapMode.DEFAULT
sourcesContent: false, // do not include original source into source map, defaults to true
target: 'es2020', // target environment for the generated JavaScript code
loader: { // Use the 'dataurl' loader for '.png' files
'.png': 'dataurl',
},
define: { // Replace strings during build time
'process.env.API_KEY': JSON.stringify('xxx-xxxx-xxx'),
'process.env.PRODUCTION': JSON.stringify(true),
'process.env.NUMBER': JSON.stringify(123),
},
logLevel: nodejs.LogLevel.ERROR, // defaults to LogLevel.WARNING
keepNames: true, // defaults to false
tsconfig: 'custom-tsconfig.json', // use custom-tsconfig.json instead of default,
metafile: true, // include meta file, defaults to false
banner: '/* comments */', // requires esbuild >= 0.9.0, defaults to none
footer: '/* comments */', // requires esbuild >= 0.9.0, defaults to none
charset: nodejs.Charset.UTF8, // do not escape non-ASCII characters, defaults to Charset.ASCII
format: nodejs.OutputFormat.ESM, // ECMAScript module output format, defaults to OutputFormat.CJS (OutputFormat.ESM requires Node.js >= 14)
mainFields: ['module', 'main'], // prefer ECMAScript versions of dependencies
inject: ['./my-shim.js', './other-shim.js'], // allows to automatically replace a global variable with an import from another file
esbuildArgs: { // Pass additional arguments to esbuild
"--log-limit": "0",
"--splitting": true,
},
},
});
```
## Command hooks
It is possible to run additional commands by specifying the `commandHooks` prop:
```text
// This example only available in TypeScript
// Run additional props via `commandHooks`
new nodejs.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`](https://www.typescriptlang.org/tsconfig#emitDecoratorMetadata).
In such cases, it is possible to run pre-compilation using `tsc` by setting the `preCompilation` flag.
```ts
new nodejs.NodejsFunction(this, 'my-handler', {
bundling: {
preCompilation: true,
},
});
```
Note: A [`tsconfig.json` file](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) is required
## Customizing Docker bundling
Use `bundling.environment` to define environments variables when `esbuild` runs:
```ts
new nodejs.NodejsFunction(this, 'my-handler', {
bundling: {
environment: {
NODE_ENV: 'production',
},
},
});
```
Use `bundling.buildArgs` to pass build arguments when building the Docker bundling image:
```ts
new nodejs.NodejsFunction(this, 'my-handler', {
bundling: {
buildArgs: {
HTTPS_PROXY: 'https://127.0.0.1:3001',
},
}
});
```
Use `bundling.dockerImage` to use a custom Docker bundling image:
```ts
new nodejs.NodejsFunction(this, 'my-handler', {
bundling: {
dockerImage: DockerImage.fromBuild('/path/to/Dockerfile'),
},
});
```
This image should have `esbuild` installed **globally**. If you plan to use `nodeModules` it
should also have `npm`, `yarn`, `bun` or `pnpm` depending on the lock file you're using.
Use the [default image provided by `aws-cdk-lib/aws-lambda-nodejs`](https://github.com/aws/aws-cdk/blob/main/packages/aws-cdk-lib/aws-lambda-nodejs/lib/Dockerfile)
as a source of inspiration.
You can set additional Docker options to configure the build environment:
```ts
new nodejs.NodejsFunction(this, 'my-handler', {
bundling: {
network: 'host',
securityOpt: 'no-new-privileges',
user: 'user:group',
volumesFrom: ['777f7dc92da7'],
volumes: [{ hostPath: '/host-path', containerPath: '/container-path' }],
},
});
```
## 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:
```ts
new nodejs.NodejsFunction(this, 'my-handler', {
bundling: {
assetHash: '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.
## Docker based bundling in complex Docker configurations
By default the input and output of Docker based bundling is handled via bind mounts.
In situtations where this does not work, like Docker-in-Docker setups or when using a remote Docker socket, you can configure an alternative, but slower, variant that also works in these situations.
```ts
new nodejs.NodejsFunction(this, 'my-handler', {
bundling: {
bundlingFileAccess: BundlingFileAccess.VOLUME_COPY,
},
});
```
## Running a custom build script as part of cdk synthesis
If you need more control over bundling -- or the build process in general -- then we include the ability to invoke your own build script. For example, if you have the following `build.mjs` file:
```
import * as path from 'path';
import { fileURLToPath } from 'url';
import esbuild from "esbuild";
import { cache } from "esbuild-plugin-cache";
import time from "esbuild-plugin-time";
const __filename = fileURLToPath(import.meta.url); // get the resolved path to the file
const __dirname = path.dirname(__filename); // get the name of the directory
await esbuild
.build({
entryPoints: [path.join(__dirname, 'handler', 'index.ts')],
outfile: path.join(__dirname, 'build-output', 'index.js'),
external: ['@aws-sdk/*', 'aws-sdk'],
format: 'cjs',
platform: 'node',
target: 'node18',
bundle: true,
minify: true,
plugins: [time(), cache({ directory: ".cache" })],
})
.catch((error) => {
console.log(error);
process.exit(1)
});
```
then you could use `build.mjs` in a cdk construct as follows:
```
export class ExampleStack extends Stack {
public constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const pathToBuildFile = path.join(__dirname, 'build.mjs');
// assuming the `handler` property is specified as 'index.handler' (as in this example), then
// this 'build-output' directory must contain an index.js file with an exported `handler` function.
const pathToOutputFile = path.join(__dirname, 'build-output');
const handler = 'index.handler';
const commandThatIsRanDuringCdkSynth = ['node', pathToBuildFile];
const code = lambda.Code.fromCustomCommand(
pathToOutputFile,
commandThatIsRanDuringCdkSynth,
);
new nodejs.NodejsFunction(this, 'NodejsFunctionBuild', {
code,
handler,
});
}
}
```
where the `build-output` would be a directory that contains an `index.js` file with an exported `handler` function.

View File

@@ -0,0 +1 @@
export * from './lib';

View File

@@ -0,0 +1 @@
"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p)&&__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});var _noFold;exports.NodejsFunction=void 0,Object.defineProperty(exports,_noFold="NodejsFunction",{enumerable:!0,configurable:!0,get:()=>{var value=require("./lib").NodejsFunction;return Object.defineProperty(exports,_noFold="NodejsFunction",{enumerable:!0,configurable:!0,value}),value}}),exports.OutputFormat=void 0,Object.defineProperty(exports,_noFold="OutputFormat",{enumerable:!0,configurable:!0,get:()=>{var value=require("./lib").OutputFormat;return Object.defineProperty(exports,_noFold="OutputFormat",{enumerable:!0,configurable:!0,value}),value}}),exports.LogLevel=void 0,Object.defineProperty(exports,_noFold="LogLevel",{enumerable:!0,configurable:!0,get:()=>{var value=require("./lib").LogLevel;return Object.defineProperty(exports,_noFold="LogLevel",{enumerable:!0,configurable:!0,value}),value}}),exports.SourceMapMode=void 0,Object.defineProperty(exports,_noFold="SourceMapMode",{enumerable:!0,configurable:!0,get:()=>{var value=require("./lib").SourceMapMode;return Object.defineProperty(exports,_noFold="SourceMapMode",{enumerable:!0,configurable:!0,value}),value}}),exports.Charset=void 0,Object.defineProperty(exports,_noFold="Charset",{enumerable:!0,configurable:!0,get:()=>{var value=require("./lib").Charset;return Object.defineProperty(exports,_noFold="Charset",{enumerable:!0,configurable:!0,value}),value}});

View File

@@ -0,0 +1,54 @@
# The correct AWS SAM build image based on the runtime of the function will be
# passed as build arg. The default allows to do `docker build .` when testing.
ARG IMAGE=public.ecr.aws/sam/build-nodejs24.x
FROM $IMAGE
# Install yarn
RUN npm install --global yarn@1.22.5
# Install pnpm
RUN npm install --global pnpm@7.33.7
# Install bun
RUN npm install --global bun@1.2.23
# Install typescript
RUN npm install --global typescript
# Install esbuild
# (unsafe-perm because esbuild has a postinstall script)
# pin the minor version to 0.21 to prevent breaking change
ARG ESBUILD_VERSION=0.21
RUN npm install --global --unsafe-perm=true esbuild@$ESBUILD_VERSION
# Ensure all users can write to npm cache
RUN mkdir /tmp/npm-cache && \
chmod -R 777 /tmp/npm-cache && \
npm config --global set cache /tmp/npm-cache
# Ensure all users can write to yarn cache
RUN mkdir /tmp/yarn-cache && \
chmod -R 777 /tmp/yarn-cache && \
yarn config set cache-folder /tmp/yarn-cache
# Ensure all users can write to pnpm cache
RUN mkdir /tmp/pnpm-cache && \
chmod -R 777 /tmp/pnpm-cache && \
pnpm config --global set store-dir /tmp/pnpm-cache
# Disable npm update notifications
RUN npm config --global set update-notifier false
# create non root user and change allow execute command for non root user
RUN /sbin/useradd -u 1000 user && chmod 711 /
# Ensure all users can write to bun cache
RUN mkdir /tmp/bun-cache && \
chmod -R 777 /tmp/bun-cache && \
echo -e "[install.cache]\ndir = \"/tmp/bun-cache\"\ndisable = true" >> /home/user/.bunfig.toml
# Setting a non-root user to run default command,
# This will be overridden later when the Docker container is running, using either the local OS user or props.user.
USER nobody
CMD [ "esbuild" ]

View File

@@ -0,0 +1,97 @@
import type { IConstruct } from 'constructs';
import type { BundlingOptions } from './types';
import type { Architecture, AssetCode } from '../../aws-lambda';
import { Runtime } from '../../aws-lambda';
import * as cdk from '../../core';
/**
* Bundling properties
*/
export interface BundlingProps extends BundlingOptions {
/**
* Path to lock file
*/
readonly depsLockFilePath: string;
/**
* Entry file
*/
readonly entry: string;
/**
* The runtime of the lambda function
*/
readonly runtime: Runtime;
/**
* The system architecture of the lambda function
*/
readonly architecture: Architecture;
/**
* Path to project root
*/
readonly projectRoot: string;
/**
* Run compilation using `tsc` before bundling
*/
readonly preCompilation?: boolean;
/**
* Which option to use to copy the source files to the docker container and output files back
* @default - BundlingFileAccess.BIND_MOUNT
*/
readonly bundlingFileAccess?: cdk.BundlingFileAccess;
}
/**
* Bundling with esbuild
*/
export declare class Bundling implements cdk.BundlingOptions {
private readonly props;
/**
* esbuild bundled Lambda asset code
*/
static bundle(scope: IConstruct, options: BundlingProps): AssetCode;
static clearEsbuildInstallationCache(): void;
static clearTscInstallationCache(): void;
private static esbuildInstallation?;
private static tscInstallation?;
readonly image: cdk.DockerImage;
readonly entrypoint?: string[];
readonly command: string[];
readonly volumes?: cdk.DockerVolume[];
readonly volumesFrom?: string[];
readonly environment?: {
[key: string]: string;
};
readonly workingDirectory: string;
readonly user?: string;
readonly securityOpt?: string;
readonly network?: string;
readonly local?: cdk.ILocalBundling;
readonly bundlingFileAccess?: cdk.BundlingFileAccess;
private readonly projectRoot;
private readonly relativeEntryPath;
private readonly relativeTsconfigPath?;
private readonly relativeDepsLockFilePath;
private readonly externals;
private readonly packageManager;
constructor(scope: IConstruct, props: BundlingProps);
/**
* Builds the raw esbuild CLI arguments as an array of strings.
* No shell quoting — callers apply their own formatting.
*/
private buildEsbuildArgs;
private createBundlingCommand;
/**
* Produces shell-command steps for file operations in Docker bundling.
*/
private dockerFileOps;
/**
* Produces callback+spawn steps for file operations in local bundling.
*/
private localFileOps;
private getLocalBundlingProvider;
/**
* Creates the sequence of bundling steps.
*
* This is the single source of truth for the bundling pipeline, used by both
* Docker bundling (rendered to a shell command) and local bundling (executed directly).
*/
private createBundlingSteps;
private executeBundlingSteps;
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,120 @@
import type { Construct } from 'constructs';
import type { BundlingOptions } from './types';
import * as lambda from '../../aws-lambda';
/**
* Properties for a NodejsFunction
*/
export interface NodejsFunctionProps extends lambda.FunctionOptions {
/**
* Path to the entry file (JavaScript or TypeScript).
*
* If this is a relative path, it will be evaluated with respect to the
* JavaScript/TypeScript source file that instantiates the `NodejsFunction`
* construct. If the current project is not a Node project, relative paths are
* not reliable and absolute paths should be used.
*
* This file should be located underneath the `projectRoot` directory (by default,
* the directory containing the package manager's lock file).
*
* If omitted, the entry file will be derived from the TypeScript/JavaScript file
* that instantiates the `NodejsFunction` construct, and the construct identifier
* of the `NodejsFunction` construct, in the following way:
*
* ```
* <filename>.<construct-id>.(ts|js)
*
* // Example, if stack.ts contains the following:
* new NodejsFunction(this, 'my-handler', { ... });
*
* // Then the implicit entry point(s) will be
* stack.my-handler.ts
* stack.my-handler.js
* ```
*
* Again: if the current project is not a Node project this is not reliable,
* and instead explicit, absolute paths should be used.
*
* @default - (Realible in Node projects only) derived from the defining file's name and construct ID as described in the documentation.
*/
readonly entry?: string;
/**
* The name of the exported handler in the entry file.
*
* * If the `code` property is supplied, then you must include the `handler` property. The handler should be the name of the file
* that contains the exported handler and the function that should be called when the AWS Lambda is invoked. For example, if
* you had a file called `myLambda.js` and the function to be invoked was `myHandler`, then you should input `handler` property as `myLambda.myHandler`.
*
* * If the `code` property is not supplied and the handler input does not contain a `.`, then the handler is prefixed with `index.` (index period). Otherwise,
* the handler property is not modified.
*
* @default handler
*/
readonly handler?: string;
/**
* The runtime environment. Only runtimes of the Node.js family are
* supported.
*
* @default `Runtime.NODEJS_LATEST` if the `@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion` feature flag is enabled, otherwise `Runtime.NODEJS_16_X`
*/
readonly runtime?: lambda.Runtime;
/**
* The `AWS_NODEJS_CONNECTION_REUSE_ENABLED` environment variable does not exist in the AWS SDK for JavaScript v3.
*
* This prop will be deprecated when the Lambda Node16 runtime is deprecated on June 12, 2024.
* See https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html#runtime-support-policy
*
* Info for Node 16 runtimes / SDK v2 users:
*
* Whether to automatically reuse TCP connections when working with the AWS
* SDK for JavaScript v2.
*
* This sets the `AWS_NODEJS_CONNECTION_REUSE_ENABLED` environment variable
* to `1`.
*
* @see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-reusing-connections.html
*
* @default - false (obsolete) for runtimes >= Node 18, true for runtimes <= Node 16.
*/
readonly awsSdkConnectionReuse?: boolean;
/**
* The path to the dependencies lock file (`yarn.lock`, `pnpm-lock.yaml`, `bun.lockb`, `bun.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 (`yarn`, `pnpm`, `bun` or `npm`) along with this lock file.
*
* @default - the path is found by walking up parent directories searching for
* a `yarn.lock`, `pnpm-lock.yaml`, `bun.lockb`, `bun.lock` or `package-lock.json` file
*/
readonly depsLockFilePath?: string;
/**
* Bundling options
*
* @default - use default bundling options: no minify, no sourcemap, all
* modules are bundled.
*/
readonly bundling?: BundlingOptions;
/**
* The path to the directory containing project config files (`package.json` or `tsconfig.json`)
*
* @default - the directory containing the `depsLockFilePath`
*/
readonly projectRoot?: string;
/**
* The code that will be deployed to the Lambda Handler. If included, then properties related to
* bundling of the code are ignored.
*
* * If the `code` field is specified, then you must include the `handler` property.
*
* @default - the code is bundled by esbuild
*/
readonly code?: lambda.Code;
}
/**
* A Node.js Lambda function bundled using esbuild
*/
export declare class NodejsFunction extends lambda.Function {
constructor(scope: Construct, id: string, props?: NodejsFunctionProps);
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export * from './function';
export * from './types';

View File

@@ -0,0 +1 @@
"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p)&&__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});var _noFold;exports.NodejsFunction=void 0,Object.defineProperty(exports,_noFold="NodejsFunction",{enumerable:!0,configurable:!0,get:()=>{var value=require("./function").NodejsFunction;return Object.defineProperty(exports,_noFold="NodejsFunction",{enumerable:!0,configurable:!0,value}),value}}),exports.OutputFormat=void 0,Object.defineProperty(exports,_noFold="OutputFormat",{enumerable:!0,configurable:!0,get:()=>{var value=require("./types").OutputFormat;return Object.defineProperty(exports,_noFold="OutputFormat",{enumerable:!0,configurable:!0,value}),value}}),exports.LogLevel=void 0,Object.defineProperty(exports,_noFold="LogLevel",{enumerable:!0,configurable:!0,get:()=>{var value=require("./types").LogLevel;return Object.defineProperty(exports,_noFold="LogLevel",{enumerable:!0,configurable:!0,value}),value}}),exports.SourceMapMode=void 0,Object.defineProperty(exports,_noFold="SourceMapMode",{enumerable:!0,configurable:!0,get:()=>{var value=require("./types").SourceMapMode;return Object.defineProperty(exports,_noFold="SourceMapMode",{enumerable:!0,configurable:!0,value}),value}}),exports.Charset=void 0,Object.defineProperty(exports,_noFold="Charset",{enumerable:!0,configurable:!0,get:()=>{var value=require("./types").Charset;return Object.defineProperty(exports,_noFold="Charset",{enumerable:!0,configurable:!0,value}),value}});

View File

@@ -0,0 +1,8 @@
/**
* Package installation
*/
export declare abstract class PackageInstallation {
static detect(module: string): PackageInstallation | undefined;
abstract readonly isWorkspacePackage: boolean;
abstract readonly version: string;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PackageInstallation=void 0;var child_process_1=()=>{var tmp=require("child_process");return child_process_1=()=>tmp,tmp},util_1=()=>{var tmp=require("./util");return util_1=()=>tmp,tmp};class PackageInstallation{static detect(module2){try{const version=(0,util_1().tryGetModuleVersionFromRequire)(module2);if(version)return{isWorkspacePackage:!0,version};const proc=(0,child_process_1().spawnSync)(module2,["--version"]);return proc.status===0&&!proc.error?{isWorkspacePackage:!1,version:proc.stdout.toString().trim()}:void 0}catch{return}}}exports.PackageInstallation=PackageInstallation;

View File

@@ -0,0 +1,34 @@
import { LogLevel } from './types';
interface PackageManagerProps {
readonly lockFile: string;
readonly installCommand: string[];
readonly runCommand: string[];
readonly argsSeparator?: string;
}
export declare enum LockFile {
NPM = "package-lock.json",
YARN = "yarn.lock",
BUN = "bun.lockb",
BUN_LOCK = "bun.lock",
PNPM = "pnpm-lock.yaml"
}
/**
* A node package manager
*/
export declare class PackageManager {
/**
* Use a lock file path to determine the package manager to use. Optionally, specify a log level to
* control its verbosity.
* @param lockFilePath Path of the lock file
* @param logLevel optional log level @default LogLevel.INFO
* @returns the right PackageManager for that lock file
*/
static fromLockFile(lockFilePath: string, logLevel?: LogLevel): PackageManager;
readonly lockFile: string;
readonly installCommand: string[];
readonly runCommand: string[];
readonly argsSeparator?: string;
constructor(props: PackageManagerProps);
runBinCommand(bin: string): string[];
}
export {};

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PackageManager=exports.LockFile=void 0;var os=()=>{var tmp=require("os");return os=()=>tmp,tmp},path=()=>{var tmp=require("path");return path=()=>tmp,tmp},types_1=()=>{var tmp=require("./types");return types_1=()=>tmp,tmp},LockFile;(function(LockFile2){LockFile2.NPM="package-lock.json",LockFile2.YARN="yarn.lock",LockFile2.BUN="bun.lockb",LockFile2.BUN_LOCK="bun.lock",LockFile2.PNPM="pnpm-lock.yaml"})(LockFile||(exports.LockFile=LockFile={}));class PackageManager{static fromLockFile(lockFilePath,logLevel){const lockFile=path().basename(lockFilePath);switch(lockFile){case LockFile.YARN:return new PackageManager({lockFile:LockFile.YARN,installCommand:logLevel&&logLevel!==types_1().LogLevel.INFO?["yarn","install","--no-immutable","--silent"]:["yarn","install","--no-immutable"],runCommand:["yarn","run"]});case LockFile.PNPM:return new PackageManager({lockFile:LockFile.PNPM,installCommand:logLevel&&logLevel!==types_1().LogLevel.INFO?["pnpm","install","--reporter","silent","--config.node-linker=hoisted","--config.package-import-method=clone-or-copy","--no-prefer-frozen-lockfile"]:["pnpm","install","--config.node-linker=hoisted","--config.package-import-method=clone-or-copy","--no-prefer-frozen-lockfile"],runCommand:["pnpm","exec"],argsSeparator:"--"});case LockFile.BUN:case LockFile.BUN_LOCK:return new PackageManager({lockFile,installCommand:logLevel&&logLevel!==types_1().LogLevel.INFO?["bun","install","--backend","copyfile","--silent"]:["bun","install","--backend","copyfile"],runCommand:["bun","run"]});default:return new PackageManager({lockFile:LockFile.NPM,installCommand:logLevel?["npm","ci","--loglevel",logLevel]:["npm","ci"],runCommand:["npx","--no-install"]})}}lockFile;installCommand;runCommand;argsSeparator;constructor(props){this.lockFile=props.lockFile,this.installCommand=props.installCommand,this.runCommand=props.runCommand,this.argsSeparator=props.argsSeparator}runBinCommand(bin){const[runCommand,...runArgs]=this.runCommand;return[os().platform()==="win32"?`${runCommand}.cmd`:runCommand,...runArgs,...this.argsSeparator?[this.argsSeparator]:[],bin]}}exports.PackageManager=PackageManager;

View File

@@ -0,0 +1,410 @@
import type { BundlingFileAccess, DockerImage, DockerRunOptions } from '../../core';
/**
* Bundling options
*/
export interface BundlingOptions extends DockerRunOptions {
/**
* Whether to minify files when bundling.
*
* @default false
*/
readonly minify?: boolean;
/**
* Whether to include source maps when bundling.
*
* @default false
*/
readonly sourceMap?: boolean;
/**
* Source map mode to be used when bundling.
* @see https://esbuild.github.io/api/#sourcemap
*
* @default SourceMapMode.DEFAULT
*/
readonly sourceMapMode?: SourceMapMode;
/**
* Whether to include original source code in source maps when bundling.
*
* @see https://esbuild.github.io/api/#sources-content
*
* @default true
*/
readonly sourcesContent?: boolean;
/**
* Target environment for the generated JavaScript code.
*
* @see https://esbuild.github.io/api/#target
*
* @default - the node version of the runtime
*/
readonly target?: string;
/**
* 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.
*
* For example, `{ '.png': 'dataurl' }`.
*
* @see https://esbuild.github.io/api/#loader
*
* @default - use esbuild default loaders
*/
readonly loader?: {
[ext: string]: string;
};
/**
* Log level for esbuild. This is also propagated to the package manager and
* applies to its specific install command.
*
* @default LogLevel.WARNING
*/
readonly logLevel?: LogLevel;
/**
* 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.
*
* @default false
*/
readonly keepNames?: boolean;
/**
* 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' }`.
*
* @default - automatically discovered by `esbuild`
*/
readonly tsconfig?: string;
/**
* 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
* @default false
*/
readonly metafile?: boolean;
/**
* 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:
*
* @default - no comments are passed
*/
readonly banner?: string;
/**
* 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
*
* @default - no comments are passed
*/
readonly footer?: string;
/**
* 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
* @default Charset.ASCII
*/
readonly charset?: Charset;
/**
* Replace global identifiers with constant expressions.
*
* For example, `{ 'process.env.DEBUG': 'true' }`.
*
* Another example, `{ 'process.env.API_KEY': JSON.stringify('xxx-xxxx-xxx') }`.
*
* @default - no replacements are made
*/
readonly define?: {
[key: string]: string;
};
/**
* A list of modules that should be considered as externals (already available
* in the runtime).
*
* @default - no replacements are made
*/
readonly externalModules?: string[];
/**
* Includes AWS SDK in the bundle asset.
*
* @default - false
* if `true` the `aws-sdk` will be included in the asset bundle and not be
* resolved to the Lambda provided sdk.
*/
readonly bundleAwsSDK?: boolean;
/**
* 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.
*
* @default - all modules are bundled
*/
readonly nodeModules?: string[];
/**
* The version of esbuild to use when running in a Docker container.
*
* @default - latest v0
*/
readonly esbuildVersion?: string;
/**
* 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",
* }
* }
* });
* ```
*
* @default - no additional esbuild arguments are passed
*/
readonly esbuildArgs?: {
[key: string]: string | boolean;
};
/**
* Build arguments to pass when building the bundling image.
*
* @default - no build arguments are passed
*/
readonly buildArgs?: {
[key: string]: string;
};
/**
* 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.
*
* @default false
*/
readonly forceDockerBundling?: boolean;
/**
* 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`.
*
* @default false
*/
readonly preCompilation?: boolean;
/**
* A custom bundling Docker image.
*
* This image should have esbuild installed globally. If you plan to use `nodeModules`
* it should also have `npm`, `yarn`, `bun` or `pnpm` depending on the lock file you're using.
*
* See https://github.com/aws/aws-cdk/blob/main/packages/aws-cdk-lib/aws-lambda-nodejs/lib/Dockerfile
* for the default image provided by aws-cdk-lib/aws-lambda-nodejs.
*
* @default - use the Docker image provided by aws-cdk-lib/aws-lambda-nodejs
*/
readonly dockerImage?: DockerImage;
/**
* Command hooks
*
* @default - do not run additional commands
*/
readonly commandHooks?: ICommandHooks;
/**
* 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.
*
* @default - asset hash is calculated based on the bundled output
*/
readonly assetHash?: string;
/**
* Output format for the generated JavaScript files
*
* @default OutputFormat.CJS
*/
readonly format?: OutputFormat;
/**
* How to determine the entry point for modules.
* Try ['module', 'main'] to default to ES module versions.
*
* @default []
*/
readonly mainFields?: string[];
/**
* This option allows you to automatically replace a global variable with an
* import from another file.
*
* @see https://esbuild.github.io/api/#inject
* @default - no code is injected
*/
readonly inject?: string[];
/**
* Which option to use to copy the source files to the docker container and output files back
* @default - BundlingFileAccess.BIND_MOUNT
*/
readonly bundlingFileAccess?: BundlingFileAccess;
}
/**
* Output format for the generated JavaScript files
*/
export declare enum OutputFormat {
/**
* CommonJS
*/
CJS = "cjs",
/**
* ECMAScript module
*
* Requires a running environment that supports `import` and `export` syntax.
*/
ESM = "esm"
}
/**
* 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}`];
* }
* ```
*/
export interface ICommandHooks {
/**
* Returns commands to run before bundling.
*
* Commands are chained with `&&`.
*/
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 `&&`.
*/
beforeInstall(inputDir: string, outputDir: string): string[];
/**
* Returns commands to run after bundling.
*
* Commands are chained with `&&`.
*/
afterBundling(inputDir: string, outputDir: string): string[];
}
/**
* Log levels for esbuild and package managers' install commands.
*/
export declare enum LogLevel {
/** Show everything */
VERBOSE = "verbose",
/** Show everything from info and some additional messages for debugging */
DEBUG = "debug",
/** Show warnings, errors, and an output file summary */
INFO = "info",
/** Show warnings and errors */
WARNING = "warning",
/** Show errors only */
ERROR = "error",
/** Show nothing */
SILENT = "silent"
}
/**
* SourceMap mode for esbuild
* @see https://esbuild.github.io/api/#sourcemap
*/
export declare enum SourceMapMode {
/**
* 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
*/
DEFAULT = "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
*/
EXTERNAL = "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
*/
INLINE = "inline",
/**
* Both sourceMap mode - If you want to have the effect of both inline and external simultaneously
*/
BOTH = "both"
}
/**
* Charset for esbuild's output
*/
export declare enum Charset {
/**
* ASCII
*
* Any non-ASCII characters are escaped using backslash escape sequences
*/
ASCII = "ascii",
/**
* UTF-8
*
* Keep original characters without using escape sequences
*/
UTF8 = "utf8"
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Charset=exports.SourceMapMode=exports.LogLevel=exports.OutputFormat=void 0;var OutputFormat;(function(OutputFormat2){OutputFormat2.CJS="cjs",OutputFormat2.ESM="esm"})(OutputFormat||(exports.OutputFormat=OutputFormat={}));var LogLevel;(function(LogLevel2){LogLevel2.VERBOSE="verbose",LogLevel2.DEBUG="debug",LogLevel2.INFO="info",LogLevel2.WARNING="warning",LogLevel2.ERROR="error",LogLevel2.SILENT="silent"})(LogLevel||(exports.LogLevel=LogLevel={}));var SourceMapMode;(function(SourceMapMode2){SourceMapMode2.DEFAULT="default",SourceMapMode2.EXTERNAL="external",SourceMapMode2.INLINE="inline",SourceMapMode2.BOTH="both"})(SourceMapMode||(exports.SourceMapMode=SourceMapMode={}));var Charset;(function(Charset2){Charset2.ASCII="ascii",Charset2.UTF8="utf8"})(Charset||(exports.Charset=Charset={}));

View File

@@ -0,0 +1,64 @@
import type { SpawnSyncOptions } from 'child_process';
import { Runtime } from '../../aws-lambda';
export interface CallSite {
getThis(): any;
getTypeName(): string;
getFunctionName(): string;
getMethodName(): string;
getFileName(): string;
getLineNumber(): number;
getColumnNumber(): number;
getFunction(): Function;
getEvalOrigin(): string;
isNative(): boolean;
isToplevel(): boolean;
isEval(): boolean;
isConstructor(): boolean;
}
/**
* Get callsites from the V8 stack trace API
*
* https://github.com/sindresorhus/callsites
*/
export declare function callsites(): CallSite[];
/**
* Find a file by walking up parent directories
*/
export declare function findUp(name: string, directory?: string): string | undefined;
/**
* Find the lowest of multiple files by walking up parent directories. If
* multiple files exist at the same level, they will all be returned.
*/
export declare function findUpMultiple(names: string[], directory?: string): string[];
/**
* Spawn sync with error handling
*/
export declare function exec(cmd: string, args: string[], options?: SpawnSyncOptions): import("child_process").SpawnSyncReturns<string | Buffer<ArrayBufferLike>>;
/**
* Returns a module version by requiring its package.json file
*/
export declare function tryGetModuleVersionFromRequire(mod: string): string | undefined;
/**
* Gets module version from package.json content
*/
export declare function tryGetModuleVersionFromPkg(mod: string, pkgJson: {
[key: string]: any;
}, pkgPath: string): string | undefined;
/**
* Extract versions for a list of modules.
*
* First lookup the version in the package.json and then fallback to requiring
* the module's package.json. The fallback is needed for transitive dependencies.
*/
export declare function extractDependencies(pkgPath: string, modules: string[]): {
[key: string]: string;
};
export declare function getTsconfigCompilerOptions(tsconfigPath: string): string;
/**
* Returns tsconfig compiler options as an array of CLI arguments for direct spawn.
*/
export declare function getTsconfigCompilerOptionsArray(tsconfigPath: string): string[];
/**
* Detect if a given Node.js runtime uses SDKv2
*/
export declare function isSdkV2Runtime(runtime: Runtime): boolean;

View File

@@ -0,0 +1,6 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.callsites=callsites,exports.findUp=findUp,exports.findUpMultiple=findUpMultiple,exports.exec=exec,exports.tryGetModuleVersionFromRequire=tryGetModuleVersionFromRequire,exports.tryGetModuleVersionFromPkg=tryGetModuleVersionFromPkg,exports.extractDependencies=extractDependencies,exports.getTsconfigCompilerOptions=getTsconfigCompilerOptions,exports.getTsconfigCompilerOptionsArray=getTsconfigCompilerOptionsArray,exports.isSdkV2Runtime=isSdkV2Runtime;var child_process_1=()=>{var tmp=require("child_process");return child_process_1=()=>tmp,tmp},fs=()=>{var tmp=require("fs");return fs=()=>tmp,tmp},path=()=>{var tmp=require("path");return path=()=>tmp,tmp},aws_lambda_1=()=>{var tmp=require("../../aws-lambda");return aws_lambda_1=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},literal_string_1=()=>{var tmp=require("../../core/lib/private/literal-string");return literal_string_1=()=>tmp,tmp};function callsites(){const _prepareStackTrace=Error.prepareStackTrace;Error.prepareStackTrace=(_,stack2)=>stack2;const stack=new Error().stack?.slice(1);return Error.prepareStackTrace=_prepareStackTrace,stack}function findUp(name,directory=process.cwd()){return findUpMultiple([name],directory)[0]}function findUpMultiple(names,directory=process.cwd()){const absoluteDirectory=path().resolve(directory),files=[];for(const name of names){const file=path().join(directory,name);fs().existsSync(file)&&files.push(file)}if(files.length>0)return files;const{root}=path().parse(absoluteDirectory);return absoluteDirectory===root?[]:findUpMultiple(names,path().dirname(absoluteDirectory))}function exec(cmd,args,options){const proc=(0,child_process_1().spawnSync)(cmd,args,options);if(proc.error)throw proc.error;if(proc.status!==0)throw proc.stdout||proc.stderr?new(core_1()).UnscopedValidationError((0,literal_string_1().lit)`ProcessExitedWithNonZeroStatus`,`[Status ${proc.status}] stdout: ${proc.stdout?.toString().trim()}
stderr: ${proc.stderr?.toString().trim()}`):new(core_1()).UnscopedValidationError((0,literal_string_1().lit)`CommandExitedWithNonZeroStatus`,`${cmd} ${args.join(" ")} ${options?.cwd?`run in directory ${options.cwd}`:""} exited with status ${proc.status}`);return proc}function tryGetModuleVersionFromRequire(mod){try{return require(`${mod}/package.json`).version}catch{return}}function tryGetModuleVersionFromPkg(mod,pkgJson,pkgPath){const dependencies={...pkgJson.dependencies??{},...pkgJson.devDependencies??{},...pkgJson.peerDependencies??{}};if(!dependencies[mod])return;const fileMatch=dependencies[mod].match(/file:(.+)/);return fileMatch&&!path().isAbsolute(fileMatch[1])?`file:${path().join(path().dirname(pkgPath),fileMatch[1])}`:dependencies[mod]}function extractDependencies(pkgPath,modules){const dependencies={},pkgJson=require(pkgPath);for(const mod of modules){const version=tryGetModuleVersionFromPkg(mod,pkgJson,pkgPath)??tryGetModuleVersionFromRequire(mod);if(!version)throw new(core_1()).UnscopedValidationError((0,literal_string_1().lit)`CannotExtractModuleVersion`,`Cannot extract version for module '${mod}'. Check that it's referenced in your package.json or installed.`);dependencies[mod]=version}return dependencies}function getTsconfigCompilerOptions(tsconfigPath){const compilerOptions=extractTsConfig(tsconfigPath),excludedCompilerOptions=["composite","charset","noEmit","tsBuildInfoFile"],options={...compilerOptions,incremental:!1,rootDir:"./",outDir:"./"};let compilerOptionsString="";return Object.keys(options).sort().forEach(key=>{if(excludedCompilerOptions.includes(key))return;const value=options[key],option="--"+key,type=typeof value;if(type==="boolean")value?compilerOptionsString+=option+" ":compilerOptionsString+=option+" false ";else if(type==="string")compilerOptionsString+=option+" "+value+" ";else if(type==="object")Array.isArray(value)&&(compilerOptionsString+=option+" "+value.join(",")+" ");else throw new(core_1()).UnscopedValidationError((0,literal_string_1().lit)`UnsupportedCompilerOption`,`Missing support for compilerOption: [${key}]: { ${type}, ${value}}
`)}),compilerOptionsString.trim()}function getTsconfigCompilerOptionsArray(tsconfigPath){const compilerOptions=extractTsConfig(tsconfigPath),excludedCompilerOptions=["composite","charset","noEmit","tsBuildInfoFile"],options={...compilerOptions,incremental:!1,rootDir:"./",outDir:"./"},args=[];return Object.keys(options).sort().forEach(key=>{if(excludedCompilerOptions.includes(key))return;const value=options[key],option="--"+key,type=typeof value;if(type==="boolean")args.push(option),value||args.push("false");else if(type==="string")args.push(option,value);else if(type==="object")Array.isArray(value)&&args.push(option,value.join(","));else throw new(core_1()).UnscopedValidationError((0,literal_string_1().lit)`UnsupportedCompilerOption`,`Missing support for compilerOption: [${key}]: { ${type}, ${value}}
`)}),args}function extractTsConfig(tsconfigPath,previousCompilerOptions){const{extends:extendedConfig,compilerOptions}=require(tsconfigPath),updatedCompilerOptions={...compilerOptions,...previousCompilerOptions??{}};return extendedConfig?extractTsConfig(path().resolve(tsconfigPath.replace(/[^\/]+$/,""),extendedConfig),updatedCompilerOptions):updatedCompilerOptions}function isSdkV2Runtime(runtime){return[aws_lambda_1().Runtime.NODEJS,aws_lambda_1().Runtime.NODEJS_4_3,aws_lambda_1().Runtime.NODEJS_6_10,aws_lambda_1().Runtime.NODEJS_8_10,aws_lambda_1().Runtime.NODEJS_10_X,aws_lambda_1().Runtime.NODEJS_12_X,aws_lambda_1().Runtime.NODEJS_14_X,aws_lambda_1().Runtime.NODEJS_16_X].some(r=>r.family===runtime.family&&r.name===runtime.name)}