Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto-eval getContext #1213

Merged
merged 2 commits into from
Dec 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion packages/snap-toolbox/src/getContext/getContext.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import { getContext } from './getContext';

describe('getContext', () => {
beforeEach(() => (document.body.innerHTML = ''));
beforeAll(() => {
// used to test global variable assignment in evaluation
const globalScriptTag = document.createElement('script');
globalScriptTag.innerHTML = 'const globalVar = "constant";';

document.head.append(globalScriptTag);
});

beforeEach(() => {
document.body.innerHTML = '';
});

it('expects an array of strings as the first parameter', () => {
const scriptTag = document.createElement('script');
Expand Down Expand Up @@ -261,4 +271,18 @@ describe('getContext', () => {
getContext(['error'], scriptTag);
}).toThrow();
});

it('does not throw an error when variables exist already, but are not in evaluation list', () => {
const scriptTag = document.createElement('script');
scriptTag.setAttribute('type', 'searchspring/recommend');
scriptTag.setAttribute('id', 'searchspring-recommend');
scriptTag.innerHTML = `
siteId = 'abc123';
globalVar = 'snap';
`;

expect(() => {
getContext(['error'], scriptTag);
}).not.toThrow();
});
});
15 changes: 13 additions & 2 deletions packages/snap-toolbox/src/getContext/getContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,23 @@ export function getContext(evaluate: string[] = [], script?: HTMLScriptElement |
});

const scriptVariables: ContextVariables = {};
const scriptInnerHTML = scriptElem.innerHTML;

// attempt to grab inner HTML variables
const scriptInnerVars = scriptInnerHTML.match(/([a-zA-Z_$][a-zA-Z_$0-9]*)\s?=/g)?.map((match) => match.replace(/[\s=]/g, ''));

const combinedVars = evaluate.concat(scriptInnerVars || []);

// de-dupe vars
const evaluateVars = combinedVars.filter((item, index) => {
return combinedVars.indexOf(item) === index;
});

// evaluate text and put into variables
evaluate?.forEach((name) => {
const fn = new Function(`
var ${evaluate.join(', ')};
${scriptElem.innerHTML}
var ${evaluateVars.join(', ')};
${scriptInnerHTML}
return ${name};
`);

Expand Down
Loading