Skip to content

Commit

Permalink
Merge pull request #34 from patricklx/patch-4
Browse files Browse the repository at this point in the history
fix gts ts imports issue
  • Loading branch information
ef4 authored Apr 12, 2024
2 parents 5fceb59 + 7a9dcaa commit cd3ce26
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 54 deletions.
18 changes: 17 additions & 1 deletion __tests__/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,7 @@ describe('htmlbars-inline-precompile', function () {
);

expect(transformed).toEqualCode(`
define(["@ember/template-compilation", "@ember/template-factory"], function (_templateCompilation, _templateFactory) {
define(["@ember/template-factory"], function (_templateFactory) {
"use strict";
var compiled = (0, _templateFactory.createTemplateFactory)(
Expand Down Expand Up @@ -1845,6 +1845,15 @@ describe('htmlbars-inline-precompile', function () {
});

it('interoperates correctly with @babel/plugin-transform-typescript when handling locals with wire target', function () {
let imports: string[] = [];
let otherPlugin: babel.PluginObj = {
name: 'other',
visitor: {
ImportDeclaration(path) {
imports.push(path.node.source.value);
},
},
};
plugins = [
[
HTMLBarsInlinePrecompile,
Expand All @@ -1853,6 +1862,7 @@ describe('htmlbars-inline-precompile', function () {
targetFormat: 'wire',
},
],
otherPlugin,
TransformTypescript,
];

Expand All @@ -1863,6 +1873,12 @@ describe('htmlbars-inline-precompile', function () {
`
);

expect(imports.length).toEqual(4);
expect(imports[0]).toEqual('somewhere');
expect(imports[1]).toEqual('@ember/template-factory');
expect(imports[2]).toEqual('@ember/component');
expect(imports[3]).toEqual('@ember/component/template-only');

expect(normalizeWireFormat(transformed)).toEqualCode(`
import HelloWorld from 'somewhere';
import { createTemplateFactory } from "@ember/template-factory";
Expand Down
73 changes: 20 additions & 53 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,6 @@ interface State<EnvSpecificOptions> {
lastInsertedPath: NodePath<t.Statement> | undefined;
filename: string;
recursionGuard: Set<unknown>;
originalImportedNames: Map<string, [string, string]>;
}

export function makePlugin<EnvSpecificOptions>(loadOptions: (opts: EnvSpecificOptions) => Options) {
Expand All @@ -156,26 +155,7 @@ export function makePlugin<EnvSpecificOptions>(loadOptions: (opts: EnvSpecificOp
): Babel.PluginObj<State<EnvSpecificOptions>> {
let t = babel.types;

return {
pre(this: State<EnvSpecificOptions>, file) {
// Remember the available set of imported names very early here in <pre>
// so that when other plugins (particularly
// @babel/plugin-transform-typescript) drop "unused" imports in their
// own Program.enter we still know about them. If we want to use them
// from inside a template, they weren't really unused and we can ensure
// they continue to exist.
this.originalImportedNames = new Map();
for (let statement of file.ast.program.body) {
if (statement.type === 'ImportDeclaration') {
for (let specifier of statement.specifiers) {
this.originalImportedNames.set(specifier.local.name, [
statement.source.value,
importedName(specifier),
]);
}
}
}
},
const plugin = {
visitor: {
Program: {
enter(path: NodePath<t.Program>, state: State<EnvSpecificOptions>) {
Expand Down Expand Up @@ -335,6 +315,15 @@ export function makePlugin<EnvSpecificOptions>(loadOptions: (opts: EnvSpecificOp
},
},
};

return {
pre(this: State<EnvSpecificOptions>, file) {
// run our processing in pre so that imports for gts
// are kept for other plugins.
babel.traverse(file.ast, plugin.visitor, file.scope, this);
},
visitor: {},
};
} as (babel: typeof Babel) => Babel.PluginObj<unknown>;
}

Expand Down Expand Up @@ -513,7 +502,6 @@ function insertCompiledTemplate<EnvSpecificOptions>(
configFile: false,
}) as t.File;

ensureImportedNames(target, scopeLocals, state.util, state.originalImportedNames);
remapIdentifiers(precompileResultAST, babel, scopeLocals);

let templateExpression = (precompileResultAST.program.body[0] as t.VariableDeclaration)
Expand Down Expand Up @@ -548,6 +536,7 @@ function insertCompiledTemplate<EnvSpecificOptions>(
);
}
target.replaceWith(expression);
target.scope.crawl();
}

function insertTransformedTemplate<EnvSpecificOptions>(
Expand All @@ -572,15 +561,16 @@ function insertTransformedTemplate<EnvSpecificOptions>(
);
let ast = preprocess(template, { ...options, mode: 'codemod' });
let transformed = print(ast, { entityEncoding: 'raw' });
let needsScopeCrawl = false;
if (target.isCallExpression()) {
(target.get('arguments.0') as NodePath<t.Node>).replaceWith(t.stringLiteral(transformed));
if (!scopeLocals.isEmpty()) {
if (!formatOptions.enableScope) {
maybePruneImport(state.util, target.get('callee'));
target.set('callee', precompileTemplate(state.util, target));
}
ensureImportedNames(target, scopeLocals, state.util, state.originalImportedNames);
updateScope(babel, target, scopeLocals);
needsScopeCrawl = true;
}

if (formatOptions.rfc931Support === 'polyfilled') {
Expand All @@ -590,7 +580,7 @@ function insertTransformedTemplate<EnvSpecificOptions>(
removeEvalAndScope(target);
target.node.arguments = target.node.arguments.slice(0, 2);
state.recursionGuard.add(target.node);
target.replaceWith(
target = target.replaceWith(
t.callExpression(state.util.import(target, '@ember/component', 'setComponentTemplate'), [
target.node,
backingClass?.node ??
Expand All @@ -604,7 +594,11 @@ function insertTransformedTemplate<EnvSpecificOptions>(
[]
),
])
);
)[0];
needsScopeCrawl = true;
}
if (needsScopeCrawl) {
target.scope.crawl();
}
} else {
if (!scopeLocals.isEmpty()) {
Expand All @@ -614,8 +608,8 @@ function insertTransformedTemplate<EnvSpecificOptions>(
let newCall = target.replaceWith(
t.callExpression(precompileTemplate(state.util, target), [t.stringLiteral(transformed)])
)[0];
ensureImportedNames(newCall, scopeLocals, state.util, state.originalImportedNames);
updateScope(babel, newCall, scopeLocals);
newCall.scope.crawl();
} else {
(target.get('quasi').get('quasis.0') as NodePath<t.TemplateElement>).replaceWith(
t.templateElement({ raw: transformed })
Expand Down Expand Up @@ -752,31 +746,4 @@ function name(node: t.StringLiteral | t.Identifier) {
}
}

function ensureImportedNames(
target: NodePath<t.Node>,
scopeLocals: ScopeLocals,
util: ImportUtil,
originalImportedNames: Map<string, [string, string]>
) {
for (let [nameInTemplate, identifier] of scopeLocals.entries()) {
if (!target.scope.getBinding(identifier)) {
let available = originalImportedNames.get(identifier);
if (available) {
let newIdent = util.import(target, available[0], available[1], identifier);
scopeLocals.add(nameInTemplate, newIdent.name);
}
}
}
}

function importedName(node: t.ImportDeclaration['specifiers'][number]): string {
if (node.type === 'ImportDefaultSpecifier') {
return 'default';
} else if (node.type === 'ImportNamespaceSpecifier') {
return '*';
} else {
return name(node.imported);
}
}

export default makePlugin<Options>((options) => options);

0 comments on commit cd3ce26

Please sign in to comment.