Skip to content

Support standalone template files in @glint/cli #35

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

Merged
merged 4 commits into from
Dec 12, 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
58 changes: 47 additions & 11 deletions packages/cli/__tests__/check.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ describe('single-pass typechecking', () => {

test('passes a valid project', async () => {
let code = stripIndent`
import '@glint/template/glimmerx';
import Component, { hbs } from '@glimmerx/component';

interface ApplicationArgs {
Expand Down Expand Up @@ -42,7 +41,6 @@ describe('single-pass typechecking', () => {

test('reports diagnostics for a template syntax error', async () => {
let code = stripIndent`
import '@glint/template/glimmerx';
import Component, { hbs } from '@glimmerx/component';

interface ApplicationArgs {
Expand All @@ -66,20 +64,19 @@ describe('single-pass typechecking', () => {
expect(checkResult.exitCode).toBe(1);
expect(checkResult.stdout).toEqual('');
expect(stripAnsi(checkResult.stderr)).toMatchInlineSnapshot(`
"index.ts:11:28 - error TS0: [glint] Parse error on line 2:
"index.ts:10:28 - error TS0: [glint] Parse error on line 2:
...e to app v{{@version}. The current t
-----------------------^
Expecting 'CLOSE_RAW_BLOCK', 'CLOSE', 'CLOSE_UNESCAPED', 'OPEN_SEXPR', 'CLOSE_SEXPR', 'ID', 'OPEN_BLOCK_PARAMS', 'STRING', 'NUMBER', 'BOOLEAN', 'UNDEFINED', 'NULL', 'DATA', 'SEP', got 'INVALID'

11 public static template = hbs\`
10 public static template = hbs\`
~~~
"
`);
});

test('reports diagnostics for a template type error', async () => {
test('reports diagnostics for an inline template type error', async () => {
let code = stripIndent`
import '@glint/template/glimmerx';
import Component, { hbs } from '@glimmerx/component';

interface ApplicationArgs {
Expand All @@ -103,22 +100,61 @@ describe('single-pass typechecking', () => {
expect(checkResult.exitCode).toBe(1);
expect(checkResult.stdout).toEqual('');
expect(stripAnsi(checkResult.stderr)).toMatchInlineSnapshot(`
"index.ts:13:32 - error TS2551: Property 'startupTimee' does not exist on type 'Application'. Did you mean 'startupTime'?
"index.ts:12:32 - error TS2551: Property 'startupTimee' does not exist on type 'Application'. Did you mean 'startupTime'?

13 The current time is {{this.startupTimee}}.
12 The current time is {{this.startupTimee}}.
~~~~~~~~~~~~

index.ts:9:11
9 private startupTime = new Date().toISOString();
index.ts:8:11
8 private startupTime = new Date().toISOString();
~~~~~~~~~~~
'startupTime' is declared here.
"
`);
});

test('reports diagnostics for a companion template type error', async () => {
project.write('.glintrc', 'environment: ember-loose\n');

let script = stripIndent`
import Component from '@ember/component';

export interface MyComponentArgs {
message: string;
}

export default class MyComponent extends Component<MyComponentArgs> {
target = 'World!';
}
`;

let template = stripIndent`
{{@message}}, {{this.targett}}
`;

project.write('my-component.ts', script);
project.write('my-component.hbs', template);

let checkResult = await project.check({ reject: false });

expect(checkResult.exitCode).toBe(1);
expect(checkResult.stdout).toEqual('');
expect(stripAnsi(checkResult.stderr)).toMatchInlineSnapshot(`
"my-component.hbs:1:22 - error TS2551: Property 'targett' does not exist on type 'MyComponent'. Did you mean 'target'?

1 {{@message}}, {{this.targett}}
~~~~~~~

my-component.ts:8:3
8 target = 'World!';
~~~~~~
'target' is declared here.
"
`);
});

test('honors .glintrc configuration', async () => {
let code = stripIndent`
import '@glint/template/glimmerx';
import Component, { hbs } from '@glimmerx/component';

export default class Application extends Component {
Expand Down
4 changes: 4 additions & 0 deletions packages/cli/__tests__/utils/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ export default class Project {
return fs.readFileSync(this.filePath(fileName), 'utf-8');
}

public remove(fileName: string): void {
fs.unlinkSync(this.filePath(fileName));
}

public async destroy(): Promise<void> {
fs.rmdirSync(this.rootDir, { recursive: true });
}
Expand Down
76 changes: 64 additions & 12 deletions packages/cli/__tests__/watch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ describe('watched typechecking', () => {

test('passes a valid project', async () => {
let code = stripIndent`
import '@glint/template/glimmerx';
import Component, { hbs } from '@glimmerx/component';

interface ApplicationArgs {
Expand Down Expand Up @@ -45,7 +44,6 @@ describe('watched typechecking', () => {

test('reports diagnostics for a template syntax error', async () => {
let code = stripIndent`
import '@glint/template/glimmerx';
import Component, { hbs } from '@glimmerx/component';

interface ApplicationArgs {
Expand All @@ -70,23 +68,25 @@ describe('watched typechecking', () => {
await watch.terminate();

let stripped = stripAnsi(output);
let error = stripped.slice(stripped.indexOf('index.ts'), stripped.lastIndexOf(`~~~${os.EOL}`) + 3);
let error = stripped.slice(
stripped.indexOf('index.ts'),
stripped.lastIndexOf(`~~~${os.EOL}`) + 3
);

expect(output).toMatch('Found 1 error.');
expect(error.replace(/\r/g, '')).toMatchInlineSnapshot(`
"index.ts:11:28 - error TS0: [glint] Parse error on line 2:
"index.ts:10:28 - error TS0: [glint] Parse error on line 2:
...e to app v{{@version}. The current t
-----------------------^
Expecting 'CLOSE_RAW_BLOCK', 'CLOSE', 'CLOSE_UNESCAPED', 'OPEN_SEXPR', 'CLOSE_SEXPR', 'ID', 'OPEN_BLOCK_PARAMS', 'STRING', 'NUMBER', 'BOOLEAN', 'UNDEFINED', 'NULL', 'DATA', 'SEP', got 'INVALID'

11 public static template = hbs\`
10 public static template = hbs\`
~~~"
`);
});

test('reports diagnostics for a template type error', async () => {
let code = stripIndent`
import '@glint/template/glimmerx';
import Component, { hbs } from '@glimmerx/component';

interface ApplicationArgs {
Expand All @@ -111,24 +111,26 @@ describe('watched typechecking', () => {
await watch.terminate();

let stripped = stripAnsi(output);
let error = stripped.slice(stripped.indexOf('index.ts'), stripped.lastIndexOf(`~~~${os.EOL}`) + 3);
let error = stripped.slice(
stripped.indexOf('index.ts'),
stripped.lastIndexOf(`~~~${os.EOL}`) + 3
);

expect(output).toMatch('Found 1 error.');
expect(error.replace(/\r/g, '')).toMatchInlineSnapshot(`
"index.ts:13:32 - error TS2551: Property 'startupTimee' does not exist on type 'Application'. Did you mean 'startupTime'?
"index.ts:12:32 - error TS2551: Property 'startupTimee' does not exist on type 'Application'. Did you mean 'startupTime'?

13 The current time is {{this.startupTimee}}.
12 The current time is {{this.startupTimee}}.
~~~~~~~~~~~~

index.ts:9:11
9 private startupTime = new Date().toISOString();
index.ts:8:11
8 private startupTime = new Date().toISOString();
~~~~~~~~~~~"
`);
});

test('reports on errors introduced and cleared during the watch', async () => {
let code = stripIndent`
import '@glint/template/glimmerx';
import Component, { hbs } from '@glimmerx/component';

interface ApplicationArgs {
Expand Down Expand Up @@ -164,4 +166,54 @@ describe('watched typechecking', () => {

await watch.terminate();
});

test('reports on errors introduced and cleared in a companion template', async () => {
project.write('.glintrc', 'environment: ember-loose\n');
project.write('index.ts', 'import "@glint/environment-ember-loose/types";');

let script = stripIndent`
import Component from '@ember/component';

export interface MyComponentArgs {
message: string;
}

export default class MyComponent extends Component<MyComponentArgs> {
target = 'World!';
}
`;

let template = stripIndent`
{{@message}}, {{this.target}}
`;

project.write('my-component.ts', script);

let watch = project.watch({ reject: true });

let output = await watch.awaitOutput('Watching for file changes.');
expect(output).toMatch('Found 0 errors.');

project.write('my-component.hbs', template.replace('target', 'tarrget'));

output = await watch.awaitOutput('Watching for file changes.');
expect(output).toMatch('Found 1 error.');

project.write('my-component.hbs', template);

output = await watch.awaitOutput('Watching for file changes.');
expect(output).toMatch('Found 0 errors.');

project.write('my-component.hbs', template.replace('@message', '@messagee'));

output = await watch.awaitOutput('Watching for file changes.');
expect(output).toMatch('Found 1 error.');

project.remove('my-component.hbs');

output = await watch.awaitOutput('Watching for file changes.');
expect(output).toMatch('Found 0 errors.');

await watch.terminate();
});
});
1 change: 0 additions & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
"dependencies": {
"@glint/config": "^0.2.1",
"@glint/transform": "^0.2.1",
"debug": "^4.1.1",
"resolve": "^1.17.0",
"yargs": "^15.3.1"
},
Expand Down
4 changes: 1 addition & 3 deletions packages/cli/src/perform-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@ function createCompilerHost(
transformManager: TransformManager
): ts.CompilerHost {
let host = ts.createCompilerHost(options);
host.readFile = function (filename) {
return transformManager.readFile(filename);
};
host.readFile = transformManager.readFile;
return host;
}

Expand Down
5 changes: 2 additions & 3 deletions packages/cli/src/perform-watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,8 @@ function sysForWatchCompilerHost(
): typeof ts.sys {
return {
...ts.sys,
readFile(path, encoding) {
return transformManager.readFile(path, encoding);
},
watchFile: transformManager.watchFile,
readFile: transformManager.readFile,
};
}

Expand Down
62 changes: 51 additions & 11 deletions packages/cli/src/transform-manager.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { TransformedModule, rewriteModule, rewriteDiagnostic } from '@glint/transform';
import type ts from 'typescript';
import { GlintConfig } from '@glint/config';
import { assert } from '@glint/transform/lib/util';

export default class TransformManager {
private transformedModules = new Map<string, TransformedModule>();
Expand All @@ -19,36 +20,75 @@ export default class TransformManager {
}

public formatDiagnostic(diagnostic: ts.Diagnostic): string {
let file = diagnostic.file;
let transformedModule = file && this.transformedModules.get(file.fileName);
if (diagnostic.code && file && transformedModule) {
diagnostic = rewriteDiagnostic(this.ts, diagnostic, transformedModule);
}
let transformedDiagnostic = rewriteDiagnostic(this.ts, diagnostic, (fileName) =>
this.transformedModules.get(fileName)
);

return this.ts.formatDiagnosticsWithColorAndContext([diagnostic], this.formatDiagnosticHost);
return this.ts.formatDiagnosticsWithColorAndContext(
[transformedDiagnostic],
this.formatDiagnosticHost
);
}

public readFile(filename: string, encoding?: string): string | undefined {
public watchFile = (
path: string,
callback: ts.FileWatcherCallback,
pollingInterval?: number,
options?: ts.WatchOptions
): ts.FileWatcher => {
const { watchFile } = this.ts.sys;
assert(watchFile);

let rootWatcher = watchFile(path, callback, pollingInterval, options);
let templatePaths = this.glintConfig.environment.getPossibleTemplatePaths(path);

if (this.glintConfig.includesFile(path) && templatePaths.length) {
let templateWatchers = templatePaths.map((candidate) =>
watchFile(candidate, (_, event) => callback(path, event), pollingInterval, options)
);

return {
close() {
rootWatcher.close();
templateWatchers.forEach((watcher) => watcher.close());
},
};
}

return rootWatcher;
};

public readFile = (filename: string, encoding?: string): string | undefined => {
let contents = this.ts.sys.readFile(filename, encoding);
let config = this.glintConfig;

if (
contents &&
filename.endsWith('.ts') &&
!filename.endsWith('.d.ts') &&
config.includesFile(filename) &&
config.environment.moduleMayHaveTagImports(contents)
config.includesFile(filename)
) {
let mayHaveTaggedTemplates = contents && config.environment.moduleMayHaveTagImports(contents);
let templateCandidates = config.environment.getPossibleTemplatePaths(filename);
let templatePath = templateCandidates.find((candidate) => this.ts.sys.fileExists(candidate));
if (!mayHaveTaggedTemplates && !templatePath) {
return contents;
}

let script = { filename, contents };
let transformedModule = rewriteModule({ script }, config.environment);
let template = templatePath
? { filename: templatePath, contents: this.ts.sys.readFile(templatePath) ?? '' }
: undefined;

let transformedModule = rewriteModule({ script, template }, config.environment);
if (transformedModule) {
this.transformedModules.set(filename, transformedModule);
return transformedModule.transformedContents;
}
}

return contents;
}
};

private readonly formatDiagnosticHost: ts.FormatDiagnosticsHost = {
getCanonicalFileName: (name) => name,
Expand Down
Loading