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

Transform exported functions correctly #225

Merged
merged 4 commits into from
Dec 3, 2020
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
5 changes: 5 additions & 0 deletions .changeset/tasty-donkeys-wait.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

Transform exported functions correctly
144 changes: 10 additions & 134 deletions packages/kit/src/api/dev/loader.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { URL } from 'url';
import { resolve, relative } from 'path';
import * as meriyah from 'meriyah';
import MagicString from 'magic-string';
import { extract_names } from 'periscopic';
import { walk } from 'estree-walker';
import { transform } from './transform';

// This function makes it possible to load modules from the 'server'
// snowpack server, for the sake of SSR
Expand Down Expand Up @@ -47,7 +44,6 @@ export default function loader(snowpack, config) {
});

async function load(url, url_stack) {
// TODO: meriyah (JS parser) doesn't support `import.meta.hot = ...` used in HMR setup code.
if (url.endsWith('.css.proxy.js')) {
return null;
}
Expand Down Expand Up @@ -75,133 +71,7 @@ export default function loader(snowpack, config) {
}

async function initialize_module(url, data, url_stack) {
const code = new MagicString(data);
const ast = meriyah.parseModule(data, {
ranges: true,
next: true
});

const imports = [];

const export_from_identifiers = new Map();
let uid = 1;

ast.body.forEach((node) => {
if (node.type === 'ImportDeclaration') {
imports.push(node);
code.remove(node.start, node.end);
}

if (node.type === 'ExportAllDeclaration') {
if (!export_from_identifiers.has(node.source)) {
export_from_identifiers.set(node.source, `__import${uid++}`);
}

code.overwrite(
node.start,
node.end,
`Object.assign(exports, ${export_from_identifiers.get(node.source)})`
);
imports.push(node);
}

if (node.type === 'ExportDefaultDeclaration') {
code.overwrite(node.start, node.declaration.start, 'exports.default = ');
}

if (node.type === 'ExportNamedDeclaration') {
if (node.source) {
imports.push(node);

if (!export_from_identifiers.has(node.source)) {
export_from_identifiers.set(node.source, `__import${uid++}`);
}
}

if (node.specifiers && node.specifiers.length > 0) {
code.remove(node.start, node.specifiers[0].start);

node.specifiers.forEach((specifier) => {
const lhs = `exports.${specifier.exported.name}`;
const rhs = node.source
? `${export_from_identifiers.get(node.source)}.${specifier.local.name}`
: specifier.local.name;

code.overwrite(specifier.start, specifier.end, `${lhs} = ${rhs}`);
});

code.remove(node.specifiers[node.specifiers.length - 1].end, node.end);
} else {
// `export const foo = ...` or `export function foo() {...}`
if (node.declaration.type === 'VariableDeclaration') {
code.remove(node.start, node.declaration.start);

const names = [];
node.declaration.declarations.forEach((declarator) => {
names.push(...extract_names(declarator.id));
});

code.appendLeft(node.end, names.map((name) => ` exports.${name} = ${name};`).join(''));
} else {
code.overwrite(
node.start,
node.declaration.start,
`exports.${node.declaration.id.name} = `
);
}
}
}
});

// replace import.meta and import(dynamic)
if (/import\s*\.\s*meta/.test(data) || /import\s*\(/.test(data)) {
walk(ast.body, {
enter(node) {
if (node.type === 'MetaProperty' && node.meta.name === 'import') {
code.overwrite(node.start, node.end, '__importmeta__');
} else if (node.type === 'ImportExpression') {
code.overwrite(node.start, node.start + 6, '__import__');
}
}
});
}

const deps = [];
imports.forEach((node) => {
const promise = get_module(url, node.source.value, url_stack);

if (node.type === 'ExportAllDeclaration' || node.type === 'ExportNamedDeclaration') {
// `export * from './other.js'` or `export { foo } from './other.js'`
deps.push({
name: export_from_identifiers.get(node.source),
promise
});
} else if (node.specifiers.length === 0) {
// bare import
deps.push({
name: null,
promise
});
} else if (node.specifiers[0].type === 'ImportNamespaceSpecifier') {
deps.push({
name: node.specifiers[0].local.name,
promise
});
} else {
deps.push(
...node.specifiers.map((specifier) => ({
name: specifier.local.name,
promise: promise.then(
(exports) => exports[specifier.imported ? specifier.imported.name : 'default']
)
}))
);
}
});

deps.sort((a, b) => (!!a.name !== !!b.name ? (a.name ? -1 : 1) : 0));

code.append(`\n//# sourceURL=${url}`);
const { code, deps } = transform(data);

const fn = new Function(
'exports',
Expand All @@ -210,9 +80,15 @@ export default function loader(snowpack, config) {
'__import__',
'__importmeta__',
...deps.map((d) => d.name).filter(Boolean),
code.toString()
`${code}\n//# sourceURL=${url}`
);
const values = await Promise.all(deps.map((d) => d.promise));

const promises = deps.map(async (dep) => {
const mod = await get_module(url, dep.source, url_stack);
return dep.prop ? mod[dep.prop] : mod;
});

const values = await Promise.all(promises);

const exports = {};

Expand Down
137 changes: 137 additions & 0 deletions packages/kit/src/api/dev/transform.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import * as meriyah from 'meriyah';
import MagicString from 'magic-string';
import { extract_names } from 'periscopic';
import { walk } from 'estree-walker';

export function transform(data) {
const code = new MagicString(data);
const ast = meriyah.parseModule(data, {
ranges: true,
next: true
});

const imports = [];

const export_from_identifiers = new Map();
let uid = 1;

ast.body.forEach((node) => {
if (node.type === 'ImportDeclaration') {
imports.push(node);
code.remove(node.start, node.end);
}

if (node.type === 'ExportAllDeclaration') {
if (!export_from_identifiers.has(node.source)) {
export_from_identifiers.set(node.source, `__import${uid++}`);
}

code.overwrite(
node.start,
node.end,
`Object.assign(exports, ${export_from_identifiers.get(node.source)})`
);
imports.push(node);
}

if (node.type === 'ExportDefaultDeclaration') {
code.overwrite(node.start, node.declaration.start, 'exports.default = ');
}

if (node.type === 'ExportNamedDeclaration') {
if (node.source) {
imports.push(node);

if (!export_from_identifiers.has(node.source)) {
export_from_identifiers.set(node.source, `__import${uid++}`);
}
}

if (node.specifiers && node.specifiers.length > 0) {
code.remove(node.start, node.specifiers[0].start);

node.specifiers.forEach((specifier) => {
const lhs = `exports.${specifier.exported.name}`;
const rhs = node.source
? `${export_from_identifiers.get(node.source)}.${specifier.local.name}`
: specifier.local.name;

code.overwrite(specifier.start, specifier.end, `${lhs} = ${rhs}`);
});

code.remove(node.specifiers[node.specifiers.length - 1].end, node.end);
} else {
// `export const foo = ...` or `export function foo() {...}`
code.remove(node.start, node.declaration.start);

let suffix;

if (node.declaration.type === 'VariableDeclaration') {
const names = [];
node.declaration.declarations.forEach((declarator) => {
names.push(...extract_names(declarator.id));
});

suffix = names.map((name) => ` exports.${name} = ${name};`).join('');
} else {
const { name } = node.declaration.id;
suffix = ` exports.${name} = ${name};`;
}

code.appendLeft(node.end, suffix);
}
}
});

// replace import.meta and import(dynamic)
if (/import\s*\.\s*meta/.test(data) || /import\s*\(/.test(data)) {
walk(ast.body, {
enter(node) {
if (node.type === 'MetaProperty' && node.meta.name === 'import') {
code.overwrite(node.start, node.end, '__importmeta__');
} else if (node.type === 'ImportExpression') {
code.overwrite(node.start, node.start + 6, '__import__');
}
}
});
}

const deps = [];
imports.forEach((node) => {
const source = node.source.value;

if (node.type === 'ExportAllDeclaration' || node.type === 'ExportNamedDeclaration') {
// `export * from './other.js'` or `export { foo } from './other.js'`
deps.push({
name: export_from_identifiers.get(node.source),
prop: null,
source
});
} else if (node.specifiers.length === 0) {
// bare import
deps.push({
name: null,
prop: null,
source
});
} else if (node.specifiers[0].type === 'ImportNamespaceSpecifier') {
deps.push({
name: node.specifiers[0].local.name,
prop: null,
source
});
} else {
deps.push(
...node.specifiers.map((specifier) => ({
name: specifier.local.name,
prop: specifier.imported ? specifier.imported.name : 'default',
source
}))
);
}
});

deps.sort((a, b) => (!!a.name !== !!b.name ? (a.name ? -1 : 1) : 0));

return { code: code.toString(), deps };
}
58 changes: 58 additions & 0 deletions packages/kit/src/api/dev/transform.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { test } from 'uvu';
import * as assert from 'uvu/assert';
import { transform } from './transform';

function compare(a, b) {
assert.equal(
a.replace(/^\t+/gm, '').trim(),
b.replace(/^\t+/gm, '').trim()
);
}

test('extracts imports', () => {
const { code, deps } = transform(`
import './empty.js';
import foo from './foo.js';
import { bar } from './bar.js';
import * as baz from './baz.js';

console.log(foo, bar, baz);
`);

compare(code, `
console.log(foo, bar, baz);
`);

assert.equal(deps, [
{ name: 'foo', prop: 'default', source: './foo.js' },
{ name: 'bar', prop: 'bar', source: './bar.js' },
{ name: 'baz', prop: null, source: './baz.js' },
{ name: null, prop: null, source: './empty.js' }
]);
});

test('transforms exported functions safely', () => {
const { code, deps } = transform(`
export function foo() {
console.log('foo');
}

export function bar() {
foo();
}
`);

compare(code, `
function foo() {
console.log('foo');
} exports.foo = foo;

function bar() {
foo();
} exports.bar = bar;
`);

assert.equal(deps, []);
});

test.run();