lambda: Cannot create ES Module function w/Code.fromInline
- Dominant language
- TypeScript
- Stars
- 12.9k
- Forks
- 4.6k
- Avg merge
- 2d 3h
- Merged PRs (30d)
- 83
Description
### Describe the bug
Lambda Node Runtimes support loading ESM code since the `nodejs14.x` runtime.
If there is a single file in the zip, it needs to have the `.mjs` extension to be loaded as an ES module. Other option is providing a `package.json` file with `"type": "module"` in it.
Currently, there is no way to tell CDK to set the file extension when `lambda.Code.fromInline` is used:
### Expected Behavior
Not getting `Runtime.UserCodeSyntaxError` from the lambda invocation.
### Current Behavior
Error on lambda invoke:
```
{
"errorType": "Runtime.UserCodeSyntaxError",
"errorMessage": "SyntaxError: Cannot use import statement outside a module",
"trace": [
"Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module",
" at _loadUserApp (file:///var/runtime/index.mjs:1084:17)",
" at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1119:21)",
" at async start (file:///var/runtime/index.mjs:1282:23)",
" at async file:///var/runtime/index.mjs:1288:1"
]
}
```
only because the file name in the deployment package is `index.js`.
### Reproduction Steps
```
new lambda.Function(this, "Verso-Cacher", {
functionName: "esm",
code: lambda.Code.fromInline("import { DynamoDBClient } from '@aws-sdk/client-dynamodb'",
handler: "index.handler",
memorySize: 2048,
timeout: Duration.seconds(60),
runtime: new lambda.Runtime("nodejs18.x", lambda.RuntimeFamily.NODEJS, {
supportsInlineCode: true,
}),
});
```
Deploy and invoke the function.
This function handler doesn't do anything useful, other than importing from the SDK as an ES Module. It will deploy successfully and invocations will fail.
### Possible Solution
Add a new argument in `lambda.Code.fromInline` that specifies the filename, `index.mjs` would fix it for the example.
### Additional Information/Context
_No response_
### CDK CLI Version
any
### Framework Version
_No response_
### Node.js Version
14,16,18
### OS
any
### Language
TypeScript
### Language Version
_No response_
### Other information
_No response_
Contributor guide
Research direction
Start at the lambda.Code.fromInline entry point and trace how inline code is packaged and named for Node.js Lambda runtimes. Check the surrounding tests, then verify that ESM inline code can be deployed and invoked successfully while existing inline-code behavior remains unchanged.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- aws, node.js, typescript
- Domain
- cloud
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 55/100