Skip to content

Commit 3710aa2

Browse files
tdaneckergpotter2
andauthored
Add support for loading ECMAScript modules (#222) (#230)
* Add support for loading ECMAScript modules (#222) Loading ECMAScript modules is incompatible with the watch mode, though, as we can't invalidate the import cache. * Add doc regarding --esm --------- Co-authored-by: gpotter2 <10530980+gpotter2@users.noreply.github.com>
1 parent 618782e commit 3710aa2

File tree

5 files changed

+79
-21
lines changed

5 files changed

+79
-21
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ Executes a lambda given the `options` object, which is a dictionary where the ke
6464
| `lambdaHandler`|optional handler name, default to `handler`|
6565
| `region`|optional, AWS region, default to `us-east-1`|| `callbackWaitsForEmptyEventLoop`|optional, default to `false`. Setting it to True will wait for an empty loop before returning.|
6666
| `timeoutMs`|optional, timeout, default to 3000 ms|
67+
| `esm`|boolean, marks that the script is an ECMAScript module (use import), default false|
6768
| `environment`|optional, extra environment variables for the lambda|
6869
| `envfile`|optional, load an environment file before booting|
6970
| `envdestroy`|optional, destroy added environment on closing, default to false|
@@ -137,6 +138,7 @@ lambdaLocal.execute({
137138
* `-e, --event-path <event path>` (required --watch is not in use) Specify event data file name.
138139
* `-h, --handler <handler name>` (optional) Lambda function handler name. Default is "handler".
139140
* `-t, --timeout <timeout>` (optional) Seconds until lambda function timeout. Default is 3 seconds.
141+
* `--esm` (optional) Load lambda function as ECMAScript module.
140142
* `-r, --region <aws region>` (optional) Sets the AWS region, defaults to us-east-1.
141143
* `-P, --profile-path <aws profile name>` (optional) Read the specified AWS credentials file.
142144
* `-p, --profile <aws profile name>` (optional) Use with **-P**: Read the AWS profile of the file.

src/cli.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ import utils = require('./lib/utils');
2121
.option('-e, --event-path <path>', '(required if --watch is not in use) Event data file name.')
2222
.option('-h, --handler <handler name>',
2323
'(optional) Lambda function handler name. Default is \'handler\'.')
24+
.option('--esm',
25+
'(optional) Load lambda function as ECMAScript module.')
2426
.option('-t, --timeout <timeout seconds>',
2527
'(optional) Seconds until lambda function timeout. Default is 3 seconds.')
2628
.option('-r, --region <aws region>',
@@ -50,6 +52,7 @@ import utils = require('./lib/utils');
5052
var eventPath = program.eventPath,
5153
lambdaPath = program.lambdaPath,
5254
lambdaHandler = program.handler,
55+
esm = program.esm,
5356
profilePath = program.profilePath,
5457
profileName = program.profile,
5558
region = program.region,
@@ -129,6 +132,17 @@ import utils = require('./lib/utils');
129132
_close_inspector = function(){inspector.close();}
130133
}
131134
}
135+
136+
if (esm) {
137+
if (utils.get_node_major_version() < 12) {
138+
console.log("Loading ESCMAScript modules not available on NodeJS < 12.0.0.");
139+
process.exit(1);
140+
}
141+
if (program.watch) {
142+
console.log("Watch mode not supported for ECMAScript lambda modules.");
143+
process.exit(1);
144+
}
145+
}
132146
var event = function(){
133147
if(program.watch) return null;
134148
return require(utils.getAbsolutePath(eventPath));
@@ -140,6 +154,7 @@ import utils = require('./lib/utils');
140154
event: event,
141155
lambdaPath: lambdaPath,
142156
lambdaHandler: lambdaHandler,
157+
esm: esm,
143158
profilePath: profilePath,
144159
profileName: profileName,
145160
region: region,

src/lambdalocal.ts

Lines changed: 32 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ function _executeSync(opts) {
122122
lambdaFunc = opts.lambdaFunc,
123123
lambdaPath = opts.lambdaPath,
124124
lambdaHandler = opts.lambdaHandler || 'handler',
125+
esm = opts.esm,
125126
profilePath = opts.profilePath,
126127
profileName = opts.profileName || process.env['AWS_PROFILE'] || process.env['AWS_DEFAULT_PROFILE'],
127128
region = opts.region,
@@ -246,30 +247,40 @@ function _executeSync(opts) {
246247

247248
var ctx = context.generate_context();
248249

249-
try {
250-
// load lambda function
251-
if (!(lambdaFunc)){
252-
// delete this function from the require.cache to ensure every dependency is refreshed
253-
delete require.cache[require.resolve(lambdaPath)];
254-
lambdaFunc = require(lambdaPath);
255-
}
256-
257-
//load event
258-
if (event instanceof Function){
259-
event = event();
260-
}
250+
const executeLambdaFunc = lambdaFunc => {
251+
try {
252+
//load event
253+
if (event instanceof Function){
254+
event = event();
255+
}
261256

262-
//start timeout
263-
context._init_timeout();
257+
//start timeout
258+
context._init_timeout();
264259

265-
// execute lambda function
266-
var result = lambdaFunc[lambdaHandler](event, ctx, ctx.done);
267-
if (result) {
268-
if (result.then) {
269-
result.then(ctx.succeed, ctx.fail);
270-
} else {
271-
ctx.succeed(null);
260+
// execute lambda function
261+
var result = lambdaFunc[lambdaHandler](event, ctx, ctx.done);
262+
if (result) {
263+
if (result.then) {
264+
result.then(ctx.succeed, ctx.fail);
265+
} else {
266+
ctx.succeed(null);
267+
}
272268
}
269+
} catch(err){
270+
ctx.fail(err);
271+
}
272+
}
273+
274+
try {
275+
if (lambdaFunc) {
276+
executeLambdaFunc(lambdaFunc);
277+
} else if (esm) {
278+
// use eval to avoid typescript transpilation of dynamic import ()
279+
eval("import(lambdaPath)").then(executeLambdaFunc, err => ctx.fail(err));
280+
} else {
281+
// delete this function from the require.cache to ensure every dependency is refreshed
282+
delete require.cache[require.resolve(lambdaPath)];
283+
executeLambdaFunc(require(lambdaPath));
273284
}
274285
} catch(err){
275286
ctx.fail(err);

test/functs/test-func-esm.mjs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export async function handler(event, context) {
2+
return {"result": event.key, "context": context}
3+
}

test/test.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -482,6 +482,25 @@ describe("- Testing lambdalocal.js", function () {
482482
});
483483
});
484484
}
485+
if (get_node_major_version() >= 12) {
486+
describe('* Loading ECMAScript module', function () {
487+
it('should load ECMAScript lambda module successfully', function () {
488+
var lambdalocal = require(lambdalocal_path);
489+
lambdalocal.setLogger(winston);
490+
return lambdalocal.execute({
491+
event: require(path.join(__dirname, "./events/test-event.js")),
492+
lambdaPath: path.join(__dirname, "./functs/test-func-esm.mjs"),
493+
lambdaHandler: functionName,
494+
esm: true,
495+
callbackWaitsForEmptyEventLoop: false,
496+
timeoutMs: timeoutMs,
497+
verboseLevel: 1
498+
}).then(function (data) {
499+
assert.equal(data.result, "testvar")
500+
})
501+
})
502+
})
503+
}
485504
});
486505
describe("- Testing cli.js", function () {
487506
var spawnSync = require('child_process').spawnSync;
@@ -570,6 +589,14 @@ describe("- Testing cli.js", function () {
570589
assert.equal(r.status, 1);
571590
console.log(r.output);
572591
});
592+
593+
it("should fail: esm with unsupported watch mode", function () {
594+
var command = get_shell("node ../build/cli.js -l ./functs/test-func-esm.mjs --esm --watch");
595+
var r = spawnSync(command[0], command[1]);
596+
process_outputs(r);
597+
assert.equal(r.status, 1);
598+
console.log(r.output);
599+
})
573600
});
574601

575602
describe("* Environment test run", function () {

0 commit comments

Comments
 (0)