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

Amend shapeshifter to allow use of dynamic import #171

Merged
merged 1 commit into from
Aug 4, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 14 additions & 2 deletions packages/eval/shapeshifter.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export const wrappedAsync = true;

export default (_code) => {
const { code, addReturn } = wrapAsync(_code);
const ast = parseScriptWithLocation(code);
const ast = parseScriptWithLocation(disguiseImports(code));
const artificialNodes = [];
const parents = [];
const shifted = replace(ast.tree, {
Expand Down Expand Up @@ -128,10 +128,22 @@ export default (_code) => {
if (wrappedAsync) {
addReturn(shifted);
}
const generated = codegen(shifted);
const generated = undisguiseImports(codegen(shifted));
return generated;
};

// renames all import statements to "_mport" as Shift doesn't support dynamic import.
// there shouldn't be any side-effects from this as this change does not affect
// the syntax & will be undone by the equivalent replace in "undisguiseImports".
function disguiseImports(code) {
return code.replaceAll('import', '_mport'); // Must be the same length!
}

// Rename the renamed import statements back to "import"
function undisguiseImports(code) {
return code.replaceAll('_mport', 'import');
}

function wrapAsync(code) {
// wrap code in async to make await work on top level => this will create 1 line offset to locations
// this is why line offset is -1 in getLocationObject calls below
Expand Down
6 changes: 6 additions & 0 deletions packages/eval/test/shapeshifter.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,10 @@ describe('shapeshifter', () => {
it('Should shift simple double quote string', () => {
assert.equal(shapeshifter('"c3"'), '(async()=>{return mini("c3").withMiniLocation([1,0,15],[1,4,19])})()');
});
it('Should handle dynamic imports', () => {
assert.equal(
shapeshifter('const { default: foo } = await import(\'https://bar.com/foo.js\');"c3"'),
'(async()=>{const{default:foo}=await import("https://bar.com/foo.js");return mini("c3").withMiniLocation([1,64,79],[1,68,83])})()',
);
});
});