Skip to content

Commit

Permalink
fix: expose global functions when they are wrapped with try/catch (#236)
Browse files Browse the repository at this point in the history
  • Loading branch information
slawekkolodziej committed Aug 29, 2022
1 parent aff8eef commit 8b20c66
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
9 changes: 5 additions & 4 deletions src/lib/web-worker/worker-exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,13 @@ export const run = (env: WebWorkerEnvironment, scriptContent: string, scriptUrl?

scriptContent =
`with(this){${
scriptContent.replace(/\bthis\b/g, '(thi$(this)?window:this)').replace(/\/\/# so/g, '//Xso')
}\n;function thi$(t){return t===this}};${
(webWorkerCtx.$config$.globalFns || [])
.filter((globalFnName) => /[a-zA-Z_$][0-9a-zA-Z_$]*/.test(globalFnName))
.map((g) => `(typeof ${g}=='function'&&(window.${g}=${g}))`)
.join(';') +
scriptContent.replace(/\bthis\b/g, '(thi$(this)?window:this)').replace(/\/\/# so/g, '//Xso')
}\n;function thi$(t){return t===this}}` + (scriptUrl ? '\n//# sourceURL=' + scriptUrl : '');
.map((g) => `(typeof ${g}=='function'&&(this.${g}=${g}))`)
.join(';')
};` + (scriptUrl ? '\n//# sourceURL=' + scriptUrl : '');

if (!env.$isSameOrigin$) {
scriptContent = scriptContent.replace(/.postMessage\(/g, `.postMessage('${env.$winId$}',`);
Expand Down
27 changes: 25 additions & 2 deletions tests/unit/worker-exec.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,39 @@ test('Class this', ({ env, win }) => {

test('manually define global functions', ({ env, win, config }) => {
config.globalFns = ['abc', 'xyz'];
const s = `
const s1 = `
function abc() {
return true;
}
function xyz() {
return true;
}
`;
const s2 = `
window.result = window.abc() && window.xyz();
`;
run(env, s);
run(env, s1);
run(env, s2);
assert.is(win.result, true);
});

test('manually define global functions in try/catch', ({ env, win, config }) => {
config.globalFns = ['abc', 'xyz'];
const s1 = `
try {
function abc() {
return true;
}
function xyz() {
return true;
}
} catch(err) {}
`;
const s2 = `
window.result = window.abc() && window.xyz();
`;
run(env, s1);
run(env, s2);
assert.is(win.result, true);
});

Expand Down

1 comment on commit 8b20c66

@vercel
Copy link

@vercel vercel bot commented on 8b20c66 Aug 29, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.