test(language-service): Improve integration test (#28168)

The current integration test for language service involves piping the
results of one process to another using Unix pipes.
This makes the test hard to debug, and hard to configure.

This commit refactors the integration test to use regular Jasmine
scaffolding.

More importantly, it tests the way the language service will actually
be installed by end users. Users would not have to add
`@angular/language-service` to the plugins section in tsconfig.json
Instead, all they need to do is install the *extension* from
the VS Code Marketplace and Angular Language Service will be loaded
as a global plugin.

PR Close #28168
This commit is contained in:
Keen Yee Liau 2018-12-17 23:44:26 -08:00 committed by Alex Rickabaugh
parent 5a582a8afd
commit f8ad4d1e99
25 changed files with 608 additions and 1718 deletions

View File

@ -1 +1,3 @@
*.js
*.js
tsserver.log
ti-*.log

View File

@ -1,260 +0,0 @@
[
{
"type": "response",
"command": "configure",
"success": true
},
{
"type": "response",
"command": "compilerOptionsForInferredProjects",
"success": true,
"body": true
},
{
"type": "response",
"command": "completions",
"success": true,
"body": [
{
"name": "anchor",
"kind": "method",
"kindModifiers": "",
"sortText": "anchor"
},
{
"name": "big",
"kind": "method",
"kindModifiers": "",
"sortText": "big"
},
{
"name": "blink",
"kind": "method",
"kindModifiers": "",
"sortText": "blink"
},
{
"name": "bold",
"kind": "method",
"kindModifiers": "",
"sortText": "bold"
},
{
"name": "charAt",
"kind": "method",
"kindModifiers": "",
"sortText": "charAt"
},
{
"name": "charCodeAt",
"kind": "method",
"kindModifiers": "",
"sortText": "charCodeAt"
},
{
"name": "codePointAt",
"kind": "method",
"kindModifiers": "",
"sortText": "codePointAt"
},
{
"name": "concat",
"kind": "method",
"kindModifiers": "",
"sortText": "concat"
},
{
"name": "endsWith",
"kind": "method",
"kindModifiers": "",
"sortText": "endsWith"
},
{
"name": "fixed",
"kind": "method",
"kindModifiers": "",
"sortText": "fixed"
},
{
"name": "fontcolor",
"kind": "method",
"kindModifiers": "",
"sortText": "fontcolor"
},
{
"name": "fontsize",
"kind": "method",
"kindModifiers": "",
"sortText": "fontsize"
},
{
"name": "includes",
"kind": "method",
"kindModifiers": "",
"sortText": "includes"
},
{
"name": "indexOf",
"kind": "method",
"kindModifiers": "",
"sortText": "indexOf"
},
{
"name": "italics",
"kind": "method",
"kindModifiers": "",
"sortText": "italics"
},
{
"name": "lastIndexOf",
"kind": "method",
"kindModifiers": "",
"sortText": "lastIndexOf"
},
{
"name": "length",
"kind": "property",
"kindModifiers": "",
"sortText": "length"
},
{
"name": "link",
"kind": "method",
"kindModifiers": "",
"sortText": "link"
},
{
"name": "localeCompare",
"kind": "method",
"kindModifiers": "",
"sortText": "localeCompare"
},
{
"name": "match",
"kind": "method",
"kindModifiers": "",
"sortText": "match"
},
{
"name": "normalize",
"kind": "method",
"kindModifiers": "",
"sortText": "normalize"
},
{
"name": "repeat",
"kind": "method",
"kindModifiers": "",
"sortText": "repeat"
},
{
"name": "replace",
"kind": "method",
"kindModifiers": "",
"sortText": "replace"
},
{
"name": "search",
"kind": "method",
"kindModifiers": "",
"sortText": "search"
},
{
"name": "slice",
"kind": "method",
"kindModifiers": "",
"sortText": "slice"
},
{
"name": "small",
"kind": "method",
"kindModifiers": "",
"sortText": "small"
},
{
"name": "split",
"kind": "method",
"kindModifiers": "",
"sortText": "split"
},
{
"name": "startsWith",
"kind": "method",
"kindModifiers": "",
"sortText": "startsWith"
},
{
"name": "strike",
"kind": "method",
"kindModifiers": "",
"sortText": "strike"
},
{
"name": "sub",
"kind": "method",
"kindModifiers": "",
"sortText": "sub"
},
{
"name": "substr",
"kind": "method",
"kindModifiers": "",
"sortText": "substr"
},
{
"name": "substring",
"kind": "method",
"kindModifiers": "",
"sortText": "substring"
},
{
"name": "sup",
"kind": "method",
"kindModifiers": "",
"sortText": "sup"
},
{
"name": "toLocaleLowerCase",
"kind": "method",
"kindModifiers": "",
"sortText": "toLocaleLowerCase"
},
{
"name": "toLocaleUpperCase",
"kind": "method",
"kindModifiers": "",
"sortText": "toLocaleUpperCase"
},
{
"name": "toLowerCase",
"kind": "method",
"kindModifiers": "",
"sortText": "toLowerCase"
},
{
"name": "toString",
"kind": "method",
"kindModifiers": "",
"sortText": "toString"
},
{
"name": "toUpperCase",
"kind": "method",
"kindModifiers": "",
"sortText": "toUpperCase"
},
{
"name": "trim",
"kind": "method",
"kindModifiers": "",
"sortText": "trim"
},
{
"name": "valueOf",
"kind": "method",
"kindModifiers": "",
"sortText": "valueOf"
}
]
}
]

View File

@ -1,68 +0,0 @@
[
{
"seq": 0,
"type": "request",
"command": "configure",
"arguments": {
"hostInfo": "vscode"
}
},
{
"seq": 1,
"type": "request",
"command": "compilerOptionsForInferredProjects",
"arguments": {
"options": {
"module": "CommonJS",
"target": "ES6",
"allowSyntheticDefaultImports": true,
"allowNonTsExtensions": true,
"allowJs": true,
"jsx": "Preserve"
}
}
},
{
"seq": 4,
"type": "request",
"command": "open",
"arguments": {
"file": "$$PWD$$/project/app/app.component.ts",
"fileContent": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'my-app',\n template: `<h1>Hello {{name}}</h1>`,\n})\nexport class AppComponent { name = 'Angular'; }\n"
}
},
{
"seq": 7,
"type": "request",
"command": "geterr",
"arguments": {
"delay": 0,
"files": [
"$$PWD$$/project/app/app.component.ts"
]
}
},
{
"seq": 12,
"type": "request",
"command": "change",
"arguments": {
"file": "$$PWD$$/project/app/app.component.ts",
"line": 5,
"offset": 30,
"endLine": 5,
"endOffset": 30,
"insertString": "."
}
},
{
"seq": 13,
"type": "request",
"command": "completions",
"arguments": {
"file": "$$PWD$$/project/app/app.component.ts",
"line": 5,
"offset": 31
}
}
]

View File

@ -1,45 +0,0 @@
[
{
"seq": 0,
"type": "request",
"command": "configure",
"arguments": {
"hostInfo": "vscode"
}
},
{
"seq": 1,
"type": "request",
"command": "compilerOptionsForInferredProjects",
"arguments": {
"options": {
"module": "CommonJS",
"target": "ES6",
"allowSyntheticDefaultImports": true,
"allowNonTsExtensions": true,
"allowJs": true,
"jsx": "Preserve"
}
}
},
{
"seq": 2,
"type": "request",
"command": "open",
"arguments": {
"file": "$$PWD$$/app/app.module.ts",
"fileContent": ""
}
},
{
"seq": 3,
"type": "request",
"command": "geterr",
"arguments": {
"delay": 0,
"files": [
"$$PWD$$/app/app.module.ts"
]
}
}
]

View File

@ -0,0 +1,22 @@
/**
* @fileOverview
* This file serves as the entry point for generating goldens file for the
* language service integration test. It expects each golden file that needs
* to be generated to be passed in as command line arguments.
* For example, to generate golden file for the 'configure' request, run
* `yarn golden configure.json`.
* To generate multiple golden files, run
* `yarn golden configure.json completionInfo.json`.
*
* This is different from just running `yarn jasmine test.js` because this
* allows passing in arbitrary arguments.
*/
import Jasmine = require('jasmine');
function main() {
const jasmine = new Jasmine({});
jasmine.execute(['test.js']);
}
main()

View File

@ -1,13 +1,8 @@
[
{
"type": "response",
"command": "configure",
"success": true
},
{
{
"seq": 0,
"type": "response",
"command": "compilerOptionsForInferredProjects",
"request_seq": 1,
"success": true,
"body": true
}
]
}

View File

@ -0,0 +1,266 @@
{
"seq": 0,
"type": "response",
"command": "completionInfo",
"request_seq": 5,
"success": true,
"body": {
"isGlobalCompletion": false,
"isMemberCompletion": false,
"isNewIdentifierLocation": false,
"entries": [
{
"name": "anchor",
"kind": "method",
"kindModifiers": "",
"sortText": "anchor"
},
{
"name": "big",
"kind": "method",
"kindModifiers": "",
"sortText": "big"
},
{
"name": "blink",
"kind": "method",
"kindModifiers": "",
"sortText": "blink"
},
{
"name": "bold",
"kind": "method",
"kindModifiers": "",
"sortText": "bold"
},
{
"name": "charAt",
"kind": "method",
"kindModifiers": "",
"sortText": "charAt"
},
{
"name": "charCodeAt",
"kind": "method",
"kindModifiers": "",
"sortText": "charCodeAt"
},
{
"name": "codePointAt",
"kind": "method",
"kindModifiers": "",
"sortText": "codePointAt"
},
{
"name": "concat",
"kind": "method",
"kindModifiers": "",
"sortText": "concat"
},
{
"name": "endsWith",
"kind": "method",
"kindModifiers": "",
"sortText": "endsWith"
},
{
"name": "fixed",
"kind": "method",
"kindModifiers": "",
"sortText": "fixed"
},
{
"name": "fontcolor",
"kind": "method",
"kindModifiers": "",
"sortText": "fontcolor"
},
{
"name": "fontsize",
"kind": "method",
"kindModifiers": "",
"sortText": "fontsize"
},
{
"name": "includes",
"kind": "method",
"kindModifiers": "",
"sortText": "includes"
},
{
"name": "indexOf",
"kind": "method",
"kindModifiers": "",
"sortText": "indexOf"
},
{
"name": "italics",
"kind": "method",
"kindModifiers": "",
"sortText": "italics"
},
{
"name": "lastIndexOf",
"kind": "method",
"kindModifiers": "",
"sortText": "lastIndexOf"
},
{
"name": "length",
"kind": "property",
"kindModifiers": "",
"sortText": "length"
},
{
"name": "link",
"kind": "method",
"kindModifiers": "",
"sortText": "link"
},
{
"name": "localeCompare",
"kind": "method",
"kindModifiers": "",
"sortText": "localeCompare"
},
{
"name": "match",
"kind": "method",
"kindModifiers": "",
"sortText": "match"
},
{
"name": "normalize",
"kind": "method",
"kindModifiers": "",
"sortText": "normalize"
},
{
"name": "repeat",
"kind": "method",
"kindModifiers": "",
"sortText": "repeat"
},
{
"name": "replace",
"kind": "method",
"kindModifiers": "",
"sortText": "replace"
},
{
"name": "search",
"kind": "method",
"kindModifiers": "",
"sortText": "search"
},
{
"name": "slice",
"kind": "method",
"kindModifiers": "",
"sortText": "slice"
},
{
"name": "small",
"kind": "method",
"kindModifiers": "",
"sortText": "small"
},
{
"name": "split",
"kind": "method",
"kindModifiers": "",
"sortText": "split"
},
{
"name": "startsWith",
"kind": "method",
"kindModifiers": "",
"sortText": "startsWith"
},
{
"name": "strike",
"kind": "method",
"kindModifiers": "",
"sortText": "strike"
},
{
"name": "sub",
"kind": "method",
"kindModifiers": "",
"sortText": "sub"
},
{
"name": "substr",
"kind": "method",
"kindModifiers": "",
"sortText": "substr"
},
{
"name": "substring",
"kind": "method",
"kindModifiers": "",
"sortText": "substring"
},
{
"name": "sup",
"kind": "method",
"kindModifiers": "",
"sortText": "sup"
},
{
"name": "toLocaleLowerCase",
"kind": "method",
"kindModifiers": "",
"sortText": "toLocaleLowerCase"
},
{
"name": "toLocaleUpperCase",
"kind": "method",
"kindModifiers": "",
"sortText": "toLocaleUpperCase"
},
{
"name": "toLowerCase",
"kind": "method",
"kindModifiers": "",
"sortText": "toLowerCase"
},
{
"name": "toString",
"kind": "method",
"kindModifiers": "",
"sortText": "toString"
},
{
"name": "toUpperCase",
"kind": "method",
"kindModifiers": "",
"sortText": "toUpperCase"
},
{
"name": "trim",
"kind": "method",
"kindModifiers": "",
"sortText": "trim"
},
{
"name": "trimLeft",
"kind": "method",
"kindModifiers": "",
"sortText": "trimLeft"
},
{
"name": "trimRight",
"kind": "method",
"kindModifiers": "",
"sortText": "trimRight"
},
{
"name": "valueOf",
"kind": "method",
"kindModifiers": "",
"sortText": "valueOf"
}
]
}
}

View File

@ -0,0 +1,7 @@
{
"seq": 0,
"type": "response",
"command": "configure",
"request_seq": 0,
"success": true
}

View File

@ -0,0 +1,32 @@
import { writeFileSync } from 'fs';
const goldens: string[] = process.argv.slice(2);
export const goldenMatcher: jasmine.CustomMatcherFactories = {
toMatchGolden(util: jasmine.MatchersUtil): jasmine.CustomMatcher {
return {
compare(actual: {command: string}, golden: string): jasmine.CustomMatcherResult {
const expected = require(`./goldens/${golden}`);
const pass = util.equals(actual, expected);
if (!pass && goldens.indexOf(golden) >= 0) {
console.error(`Writing golden file ${golden}`);
writeFileSync(`./goldens/${golden}`, JSON.stringify(actual, null, 2));
return { pass : true };
}
return {
pass,
message: `Expected response for '${actual.command}' to match golden file ${golden}.\n` +
`To generate new golden file, run "yarn golden ${golden}".`,
};
}
};
},
};
declare global {
namespace jasmine {
interface Matchers<T> {
toMatchGolden(golden: string): void
}
}
}

View File

@ -4,23 +4,16 @@
"license": "MIT",
"description": "Angular Language Service plugin integration test",
"dependencies": {
"@angular/animations": "file:../../dist/packages-dist/animations",
"@angular/common": "file:../../dist/packages-dist/common",
"@angular/compiler": "file:../../dist/packages-dist/compiler",
"@angular/compiler-cli": "file:../../dist/packages-dist/compiler-cli",
"@angular/core": "file:../../dist/packages-dist/core",
"@angular/language-service": "file:../../dist/packages-dist/language-service",
"@angular/platform-browser": "file:../../dist/packages-dist/platform-browser",
"@angular/platform-server": "file:../../dist/packages-dist/platform-server",
"@types/minimist": "^1.2.0",
"@types/node": "^7.0.5",
"minimist": "^1.2.0",
"rxjs": "file:../../node_modules/rxjs",
"typescript": "file:../../node_modules/typescript",
"zone.js": "file:../../node_modules/zone.js"
"@types/node": "file:../../node_modules/@types/node",
"jasmine": "file:../../node_modules/jasmine",
"typescript": "file:../../node_modules/typescript"
},
"scripts": {
"postinstall": "scripts/install.sh",
"test": "tsc -p tools && scripts/test.sh"
"build": "tsc -p tsconfig.json",
"cleanup": "rm -rf ti-*.log tsserver.log",
"golden": "node generate.js",
"test": "yarn cleanup && yarn build && jasmine test.js"
}
}

View File

@ -8,9 +8,6 @@
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"plugins": [
{ "name": "@angular/language-service" }
]
"suppressImplicitAnyIndexErrors": true
}
}

View File

@ -1,2 +0,0 @@
TYPESCRIPTS=2.3
FIXTURES="smokeTest getCompletions"

View File

@ -1,16 +0,0 @@
#!/usr/bin/env bash
set -ex -o pipefail
cd `dirname $0`
cd ..
source scripts/env.sh
# Setup TypeScripts
for TYPESCRIPT in ${TYPESCRIPTS[@]}
do
(
cd typescripts/$TYPESCRIPT
yarn
)
done

View File

@ -1,30 +0,0 @@
#!/usr/bin/env bash
set -ex -o pipefail
cd `dirname $0`
cd ..
source scripts/env.sh
HOST="node tools/typescript_host.js"
VALIDATE="node tools/typescript_validator.js"
# Ensure the languages service can load correctly in node before typescript loads it.
# This verifies its dependencies and emits any exceptions, both of which are only
# emitted to the typescript logs (not the validated output).
node tools/load_test.js
for TYPESCRIPT in ${TYPESCRIPTS[@]}
do
SERVER="node typescripts/$TYPESCRIPT/node_modules/typescript/lib/tsserver.js"
for FIXTURE_BASE in ${FIXTURES[@]}
do
FIXTURE=fixtures/$FIXTURE_BASE.json
EXPECTED=fixtures/$FIXTURE_BASE-expected-$TYPESCRIPT.json
if [[ ${UPDATE_GOLDEN} == true ]]; then
$HOST --file $FIXTURE --pwd $(pwd) | $SERVER | $VALIDATE --golden > $EXPECTED
else
$HOST --file $FIXTURE --pwd $(pwd) | $SERVER | $VALIDATE --expect $EXPECTED
fi
done
done

View File

@ -1,8 +0,0 @@
#!/usr/bin/env bash
set -ex -o pipefail
cd `dirname $0`
cd ..
UPDATE_GOLDEN=true scripts/test.sh

View File

@ -0,0 +1,104 @@
import { fork, ChildProcess } from 'child_process';
import { join } from 'path';
import { Client } from './tsclient';
import { goldenMatcher } from './matcher';
describe('Angular Language Service', () => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; /* 10 seconds */
const PWD = process.env.PWD!;
const SERVER_PATH = "./node_modules/typescript/lib/tsserver.js";
let server: ChildProcess;
let client: Client;
beforeEach(() => {
jasmine.addMatchers(goldenMatcher);
server = fork(SERVER_PATH, [
'--globalPlugins', '@angular/language-service',
'--logVerbosity', 'verbose',
'--logFile', join(PWD, 'tsserver.log'),
], {
stdio: ['pipe', 'pipe', 'inherit', 'ipc'],
});
client = new Client(server);
client.listen();
});
afterEach(async () => {
client.sendRequest('exit', {});
// Give server process some time to flush all messages
await new Promise((resolve) => setTimeout(resolve, 1000));
});
it('should be launched as tsserver plugin', async () => {
let response = await client.sendRequest('configure', {
hostInfo: 'vscode',
});
expect(response).toMatchGolden('configure.json');
response = await client.sendRequest('compilerOptionsForInferredProjects', {
"options": {
module: "CommonJS",
target: "ES6",
allowSyntheticDefaultImports: true,
allowNonTsExtensions: true,
allowJs: true,
jsx: "Preserve"
}
});
expect(response).toMatchGolden('compilerOptionsForInferredProjects.json');
// Server does not send response to open request
// https://github.com/Microsoft/TypeScript/blob/master/lib/protocol.d.ts#L1055
client.sendRequest('open', {
file: `${PWD}/project/app/app.module.ts`,
fileContent: ""
});
// Server does not send response to geterr request
// https://github.com/Microsoft/TypeScript/blob/master/lib/protocol.d.ts#L1770
client.sendRequest('geterr', {
delay: 0,
files: [`${PWD}/project/app/app.module.ts`]
});
});
it('should perform completions', async () => {
await client.sendRequest('configure', {
hostInfo: 'vscode',
});
await client.sendRequest('compilerOptionsForInferredProjects', {
"options": {
module: "CommonJS",
target: "ES6",
allowSyntheticDefaultImports: true,
allowNonTsExtensions: true,
allowJs: true,
jsx: "Preserve"
}
});
client.sendRequest('open', {
file: `${PWD}/project/app/app.component.ts`,
fileContent: "import { Component } from '@angular/core';\n\n@Component({\n selector: 'my-app',\n template: `<h1>Hello {{name}}</h1>`,\n})\nexport class AppComponent { name = 'Angular'; }\n"
});
client.sendRequest('geterr', {
delay: 0,
files: [`${PWD}/project/app/app.component.ts`]
});
client.sendRequest('change', {
file: `${PWD}/project/app/app.component.ts`,
line: 5,
offset: 30,
endLine: 5,
endOffset: 30,
insertString: '.',
});
const response = await client.sendRequest('completionInfo', {
file: `${PWD}/project/app/app.component.ts`,
line: 5,
offset: 31,
});
expect(response).toMatchGolden('completionInfo.json');
});
});

View File

@ -1,35 +0,0 @@
const ts = require('typescript');
const Module = require('module');
const existingRequire = Module.prototype.require;
const recordedRequires: string[] = [];
function recordingRequire(path: string) {
recordedRequires.push(path);
return existingRequire.call(this, path);
}
Module.prototype.require = recordingRequire;
try {
const lsf = require('@angular/language-service');
const ls = lsf({typescript: ts});
// Assert that the only module that should have been required are '@angular/language-service', 'fs', and 'path'
const allowedLoads = new Set(["@angular/language-service", "fs", "path"]);
const invalidModules = recordedRequires.filter(m => !allowedLoads.has(m));
if (invalidModules.length > 0) {
console.error(`FAILED: Loading the language service required: ${invalidModules.join(', ')}`);
process.exit(1);
}
} catch (e) {
console.error(`FAILED: Loading the language service caused the following exception: ${e.stack || e}`);
process.exit(1);
}
console.log('SUCCESS: Loading passed')
process.exit(0);

View File

@ -1,19 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": true,
"skipLibCheck": true,
"sourceMap": false,
"lib": ["es2015", "dom"],
"types": [
"node",
"minimist"
]
},
"files": [
"typescript_host.ts",
"typescript_validator.ts",
"load_test.ts"
]
}

View File

@ -1,77 +0,0 @@
import * as fs from 'fs';
import * as minimist from 'minimist';
const RE_PWD = /\$\$PWD\$\$/g;
let errorsDetected = false;
function reportError(arg: string): boolean {
console.error(`Unknown argument: ${arg}`);
errorsDetected = true;
return false;
}
function help() {
console.log('TypeScript Host')
console.log(`${process.argv[1]} --file <file-name> [--pwd <pwd>]`);
console.log(`
Send JSON message using the JSON RPC protocol to stdout.
`)
}
let args = minimist(process.argv.slice(2), { string: ['file', 'pwd'], unknown: reportError });
if (errorsDetected) {
help();
process.exit(2);
}
const file = args['file'];
if (!file) {
console.log('stdin form not supported yet.')
process.exit(1);
}
// Sender
const pending: string[] = [];
let writing = false;
function writeMessage(message: string) {
writing = true;
process.stdout.write(message + '\n', checkPending);
}
function checkPending() {
writing = false;
if (pending.length) {
writeMessage(pending.shift());
}
}
function send(message: string) {
if (writing) {
pending.push(message);
} else {
writeMessage(message);
}
}
try {
let content = fs.readFileSync(file, 'utf8');
if (args['pwd']) {
content = content.replace(RE_PWD, args['pwd']);
}
const json = JSON.parse(content);
if (Array.isArray(json)) {
for (const message of json) {
send(JSON.stringify(message));
}
} else {
throw Error('Expected an array for input messages.')
}
} catch(e) {
console.error(`Error: ${e.message}`);
process.exit(2);
}

View File

@ -1,164 +0,0 @@
import * as fs from 'fs';
import * as minimist from 'minimist';
let errorsDetected = false;
const start = Date.now();
function reportError(arg: string): boolean {
console.error(`Unknown argument: ${arg}`);
errorsDetected = true;
return false;
}
function help() {
console.log('TypeScript Validator')
console.log(`${process.argv[1]} [--expect <file-name> | --golden] [--pwd <dir>]`);
console.log(`
Validate that the emitted output produces the expect JSON.`)
}
let args = minimist(process.argv.slice(2), { string: ['expect', 'pwd'], boolean: ['golden'], unknown: reportError });
if (!args.golden && !args.expect) {
console.log('Expected -golden or -expect');
errorsDetected = true;
}
if (args.golden && args.expect) {
console.log('Expected -golded or -expect but not both');
errorsDetected = true;
}
if (errorsDetected) {
help();
process.exit(2);
}
var expected: any;
if (args.expect) {
expected = JSON.parse(fs.readFileSync(args.expect, 'utf8'));
}
// Reader
let pending = Buffer.alloc(0);
const prefix = 'Content-Length: ';
function tryReadMessage(cb: (message: any) => void) {
const firstLine = pending.indexOf(10);
if (firstLine >= 1) {
const line = pending.toString('utf8', 0, firstLine);
if (!line.startsWith(prefix)) {
throw Error(`Unexpected input: ${line}`);
}
const length = +line.substring(prefix.length, firstLine - 1);
const dataStart = firstLine + 2;
const messageText = pending.toString('utf8', dataStart, dataStart + length);
const message = JSON.parse(messageText);
pending = pending.slice(dataStart + length + 1);
cb(message);
tryReadMessage(cb);
}
}
function collect(cb: (error: any, messages: any[]) => void) {
const result: any[] = [];
function report(error: any, messages: any[]) {
cb(error, messages);
cb = () => {};
}
process.stdin.on('error', report);
process.stdin.on('data', (data: Buffer) => {
try {
pending = Buffer.concat([pending, data], pending.length + data.length);
tryReadMessage((message: any) => {
result.push(message);
});
} catch (e) {
report(e, []);
}
});
process.stdin.on('close', () => {
report(null, result);
});
}
function sanitize(messages: any[]): any[] {
return messages.filter((message: any) => {
return message && message.type == 'response';
}).map((message: any) => {
// Only preserve a fixed set of fields.
const result: any = {};
if (message.type != null) result.type = message.type;
if (message.command != null) result.command = message.command;
if (message.success != null) result.success = message.success;
if (message.body != null) result.body = message.body;
return result;
});
}
function isPrimitive(value: any): boolean {
return Object(value) !== value;
}
function expectPrimitive(received: any, expected: any) {
if (received !== expected) {
throw new Error(`Expected ${expected} but received ${received}`);
}
}
function expectArray(received: any, expected: any[]) {
if (!Array.isArray(received)) {
throw new Error(`Expected an array, received ${JSON.stringify(received)}`);
}
if (received.length != expected.length) {
throw new Error(`Expected an array length ${expected.length}, received ${JSON.stringify(received)}`);
}
for (let i = 0; i < expected.length; i++) {
expect(received[i], expected[i]);
}
}
function expectObject(received: any, expected: any) {
for (const name of Object.getOwnPropertyNames(expected)) {
if (!received.hasOwnProperty(name)) {
throw new Error(`Expected object an object containing a field ${name}, received ${JSON.stringify(expected)}`);
}
expect(received[name], expected[name]);
}
}
function expect(received: any, expected: any) {
if (isPrimitive(expected)) {
expectPrimitive(received, expected);
} else if (Array.isArray(expected)) {
expectArray(received, expected);
} else {
expectObject(received, expected);
}
}
collect((err: any, messages: any[]) => {
if (err) {
console.error(err.message);
process.exit(1);
}
if (args.golden) {
console.log(JSON.stringify(sanitize(messages), null, ' '));
} else {
try {
expect(sanitize(messages), expected);
console.log('PASSED:', Date.now() - start, 'ms');
process.exit(0);
} catch(e) {
console.log('FAILED:', e.message);
process.exit(1);
}
}
});

View File

@ -0,0 +1,70 @@
import { ChildProcess } from "child_process";
import { EventEmitter } from "events";
/**
* Provides a client for tsserver. Tsserver does not use standard JSON-RPC
* protocol thus the need for this custom client.
*/
export class Client {
private data: Buffer|undefined;
private id = 0;
private responseEmitter = new EventEmitter();
constructor(private readonly server: ChildProcess) {}
listen() {
this.server.stdout.on('data', (data: Buffer) => {
this.data = this.data ? Buffer.concat([this.data, data]) : data;
const CONTENT_LENGTH = 'Content-Length: '
const index = this.data.indexOf(CONTENT_LENGTH);
if (index < 0) {
return;
}
let start = index + CONTENT_LENGTH.length;
let end = this.data.indexOf('\r\n', start);
if (end < start) {
return;
}
const contentLengthStr = this.data.slice(start, end).toString();
const contentLength = Number(contentLengthStr);
if (isNaN(contentLength) || contentLength < 0) {
return;
}
start = end + 4;
end = start + contentLength;
if (end > this.data.length) {
return;
}
const content = this.data.slice(start, end).toString();
this.data = this.data.slice(end);
try {
const payload = JSON.parse(content);
if (payload.type === "event") {
return;
}
this.responseEmitter.emit('response', payload);
}
catch (error) {
this.responseEmitter.emit('error', error);
}
});
}
async send(type: string, command: string, params: {}) {
const request = {
seq: this.id++,
type,
command,
arguments: params
};
this.server.stdin.write(JSON.stringify(request) + '\r\n');
return new Promise((resolve, reject) => {
this.responseEmitter.once('response', resolve);
this.responseEmitter.once('error', reject);
});
}
async sendRequest(command: string, params: {}) {
return this.send('request', command, params);
}
}

View File

@ -1,13 +1,60 @@
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
/* Basic Options */
"target": "es2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
},
"include": ["*.ts"]
}

View File

@ -1,15 +0,0 @@
{
"name": "2.3",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"typescript": "2.3.0"
}
}

View File

@ -1,7 +0,0 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
typescript@2.3.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-2.3.0.tgz#2e63e09284392bc8158a2444c33e2093795c0418"

File diff suppressed because it is too large Load Diff