Skip to content

Commit

Permalink
fix: emit closure requires in global scope
Browse files Browse the repository at this point in the history
  • Loading branch information
pjoe committed Nov 29, 2022
1 parent 9086bf9 commit cc4e345
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
11 changes: 11 additions & 0 deletions sdk/nodejs/runtime/closure/serializeClosure.ts
Expand Up @@ -151,6 +151,7 @@ function serializeJavaScriptText(

let environmentText = "";
let functionText = "";
const emittedRequires = new Set<string>();

const outerFunctionName = emitFunctionAndGetName(outerClosure.func);

Expand Down Expand Up @@ -202,6 +203,16 @@ function serializeJavaScriptText(

const parameters = [...Array(functionInfo.paramCount)].map((_, index) => `__${index}`).join(", ");

for (const [keyEntry, { entry: valEntry }] of functionInfo.capturedValues) {
if (valEntry.module !== undefined) {
if(!emittedRequires.has(keyEntry.json)) {
emittedRequires.add(keyEntry.json);
functionText += `const ${keyEntry.json} = require("${valEntry.module}");\n`;
}
delete capturedValues[keyEntry.json];
}
}

functionText += "\n" +
"function " + varName + "(" + parameters + ") {\n" +
" return (function() {\n" +
Expand Down
12 changes: 8 additions & 4 deletions sdk/nodejs/tests/runtime/tsClosureCases.ts
Expand Up @@ -859,10 +859,11 @@ return () => { let x = eval("undefined + null + NaN + Infinity + __filename"); r
title: "Capture built in module by ref",
func: () => os,
expectText: `exports.handler = __f0;
const os = require("os");
function __f0() {
return (function() {
with({ os: require("os") }) {
with({ }) {
return () => os;
Expand All @@ -886,10 +887,11 @@ return () => os;
return { v };
},
expectText: `exports.handler = __f0;
const os = require("os");
function __f0(__0, __1, __2) {
return (function() {
with({ os: require("os") }) {
with({ }) {
return (a, b, c) => {
const v = os;
Expand All @@ -915,10 +917,11 @@ return (a, b, c) => {
title: "Capture module through indirect function references",
func: func,
expectText: `exports.handler = __f0;
const os = require("os");
function __f1() {
return (function() {
with({ os: require("os") }) {
with({ }) {
return () => os;
Expand Down Expand Up @@ -6645,10 +6648,11 @@ return function (thisArg, _arguments, P, generator) {
}
}).apply(undefined, undefined).apply(this, arguments);
}
const mockpackage_1 = require("mockpackage");
function __f1() {
return (function() {
with({ mockpackage_1: require("mockpackage") }) {
with({ }) {
return () => mockpackage_1.z.object({
message: mockpackage_1.z.string(),
Expand Down

0 comments on commit cc4e345

Please sign in to comment.