TypeScript/tests/webTestServer.ts

1014 lines
38 KiB
TypeScript
Raw Normal View History

/// <reference types="node" />
2018-04-24 06:52:16 +02:00
// tslint:disable:no-null-keyword
2014-07-13 01:04:16 +02:00
import minimist = require("minimist");
2014-07-13 01:04:16 +02:00
import http = require("http");
import fs = require("fs");
import path = require("path");
import url = require("url");
2017-10-20 02:48:13 +02:00
import URL = url.URL;
2014-07-13 01:04:16 +02:00
import child_process = require("child_process");
import os = require("os");
2017-10-20 02:48:13 +02:00
import crypto = require("crypto");
2018-04-24 06:52:16 +02:00
import { Readable, Writable } from "stream";
import { isBuffer, isString, isObject } from "util";
import { install, getErrorSource } from "source-map-support";
install();
2014-07-13 01:04:16 +02:00
2017-10-20 02:48:13 +02:00
const port = 8888; // harness.ts and webTestResults.html depend on this exact port number.
2018-04-24 06:52:16 +02:00
const baseUrl = new URL(`http://localhost:${port}/`);
2017-10-20 02:48:13 +02:00
const rootDir = path.dirname(__dirname);
const useCaseSensitiveFileNames = isFileSystemCaseSensitive();
const defaultBrowser = os.platform() === "win32" ? "edge" : "chrome";
let browser: "edge" | "chrome" | "none" = defaultBrowser;
2017-10-20 02:48:13 +02:00
let grep: string | undefined;
let verbose = false;
2014-07-13 01:04:16 +02:00
2018-05-09 21:57:48 +02:00
interface FileBasedTest {
file: string;
2018-05-09 21:57:48 +02:00
configurations?: FileBasedTestConfiguration[];
}
2018-05-09 21:57:48 +02:00
interface FileBasedTestConfiguration {
[setting: string]: string;
}
2018-04-24 06:52:16 +02:00
function isFileSystemCaseSensitive(): boolean {
// win32\win64 are case insensitive platforms
const platform = os.platform();
if (platform === "win32" || <string>platform === "win64") {
return false;
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
// If this file exists under a different case, we must be case-insensitve.
return !fs.existsSync(swapCase(__filename));
2014-07-13 01:04:16 +02:00
}
2018-04-24 06:52:16 +02:00
function swapCase(s: string): string {
return s.replace(/\w/g, (ch) => {
const up = ch.toUpperCase();
return ch === up ? ch.toLowerCase() : up;
});
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function hasLeadingSeparator(pathname: string) {
const ch = pathname.charAt(0);
return ch === "/" || ch === "\\";
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function ensureLeadingSeparator(pathname: string) {
return hasLeadingSeparator(pathname) ? pathname : "/" + pathname;
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function trimLeadingSeparator(pathname: string) {
return hasLeadingSeparator(pathname) ? pathname.slice(1) : pathname;
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function normalizeSlashes(path: string) {
return path.replace(/\\+/g, "/");
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function hasTrailingSeparator(pathname: string) {
const ch = pathname.charAt(pathname.length - 1);
return ch === "/" || ch === "\\";
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
function toServerPath(url: url.URL | string) {
if (typeof url === "string") url = new URL(url, baseUrl);
const pathname = decodeURIComponent(url.pathname);
return path.join(rootDir, pathname);
2014-07-13 01:04:16 +02:00
}
2018-04-24 06:52:16 +02:00
function toClientPath(pathname: string) {
pathname = normalizeSlashes(pathname);
pathname = trimLeadingSeparator(pathname);
2014-07-13 01:04:16 +02:00
2018-04-24 06:52:16 +02:00
const serverPath = path.resolve(rootDir, pathname);
if (serverPath.slice(0, rootDir.length) !== rootDir) {
return undefined;
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
let clientPath = serverPath.slice(rootDir.length);
clientPath = ensureLeadingSeparator(clientPath);
clientPath = normalizeSlashes(clientPath);
return clientPath;
}
2017-10-20 02:48:13 +02:00
function flatMap<T, U>(array: T[], selector: (value: T) => U | U[]) {
let result: U[] = [];
for (const item of array) {
const mapped = selector(item);
if (Array.isArray(mapped)) {
result = result.concat(mapped);
}
else {
result.push(mapped);
}
}
return result;
}
2018-04-24 06:52:16 +02:00
declare module "http" {
interface IncomingHttpHeaders {
"if-match"?: string;
"if-none-match"?: string;
"if-modified-since"?: string;
"if-unmodified-since"?: string;
"accept-charset"?: string;
"accept-encoding"?: string;
"range"?: string;
2017-10-20 02:48:13 +02:00
}
2016-07-27 16:26:28 +02:00
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function getQuality<T extends { quality?: number }>(value: T) {
return value.quality === undefined ? 1 : value.quality;
2014-07-13 01:04:16 +02:00
}
2018-04-24 06:52:16 +02:00
function bestMatch<T, TPattern extends { quality?: number }>(value: T, patterns: TPattern[], isMatch: (value: T, pattern: TPattern) => boolean) {
let match: TPattern | undefined;
for (const pattern of patterns) {
if (!isMatch(value, pattern)) continue;
if (match === undefined || getQuality(pattern) > getQuality(match)) {
match = pattern;
2017-10-20 02:48:13 +02:00
}
}
2018-04-24 06:52:16 +02:00
return match;
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
const mediaTypeParser = /^([^\/]+)\/([^\/;]+)(?:;(.*))?$/;
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
interface MediaType {
type: string;
subtype: string;
parameters: Record<string, string>;
charset?: string;
quality?: number;
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function parseMediaType(mediaType: string): MediaType {
const match = mediaTypeParser.exec(mediaType);
if (!match) throw new Error("Invalid media type");
const type = match[1].trim();
const subtype = match[2].trim();
if (type === "*" && subtype !== "*") throw new Error("Invalid media type");
const parameters: Record<string, string> = {};
let charset: string | undefined;
let quality: number | undefined;
if (match[3]) {
for (const parameter of match[3].split(";")) {
const pair = parameter.split("=");
const name = pair[0].trim();
const value = pair[1].trim();
parameters[name] = value;
if (name === "charset") charset = value;
if (name === "q") quality = +value;
}
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
return { type, subtype, parameters, charset, quality };
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function parseMediaTypes(value: string) {
const mediaTypes: MediaType[] = [];
for (const mediaRange of value.split(",")) {
mediaTypes.push(parseMediaType(mediaRange));
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
return mediaTypes;
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function matchesMediaType(mediaType: MediaType, mediaTypePattern: MediaType) {
if (mediaTypePattern.type === "*") return true;
if (mediaTypePattern.type === mediaType.type) {
if (mediaTypePattern.subtype === "*") return true;
if (mediaTypePattern.subtype === mediaType.subtype) return true;
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
return false;
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
interface StringWithQuality {
value: string;
quality?: number;
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
const stringWithQualityParser = /^([^;]+)(;\s*q\s*=\s*([^\s]+)\s*)?$/;
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function parseStringWithQuality(value: string) {
const match = stringWithQualityParser.exec(value);
if (!match) throw new Error("Invalid header value");
return { value: match[1].trim(), quality: match[2] ? +match[2] : undefined };
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function parseStringsWithQuality(value: string) {
const charsets: StringWithQuality[] = [];
for (const charset of value.split(",")) {
charsets.push(parseStringWithQuality(charset));
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
return charsets;
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function matchesCharSet(charset: string, charsetPattern: StringWithQuality) {
return charsetPattern.value === "*" || charsetPattern.value === charset;
2014-07-13 01:04:16 +02:00
}
2018-04-24 06:52:16 +02:00
function computeETag(stats: fs.Stats) {
return JSON.stringify(crypto
.createHash("sha1")
.update(JSON.stringify({
dev: stats.dev,
ino: stats.ino,
mtime: stats.mtimeMs,
size: stats.size
}))
.digest("base64"));
}
2016-04-09 01:53:52 +02:00
2018-04-24 06:52:16 +02:00
function tryParseETags(value: string | undefined): "*" | string[] | undefined {
if (!value) return undefined;
if (value === "*") return value;
const etags: string[] = [];
for (const etag of value.split(",")) {
etags.push(etag.trim());
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
return etags;
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function matchesETag(etag: string | undefined, condition: "*" | string[] | undefined) {
if (!condition) return true;
if (!etag) return false;
return condition === "*" || condition.indexOf(etag) >= 0;
}
2016-04-09 01:53:52 +02:00
2018-04-24 06:52:16 +02:00
function tryParseDate(value: string | undefined) {
return value ? new Date(value) : undefined;
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
interface ByteRange {
start: number;
end: number;
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
const byteRangeParser = /^\s*(\d+)\s*-\s*(\d+)\s*$/;
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function tryParseByteRange(value: string, contentLength: number): ByteRange | undefined {
const match = byteRangeParser.exec(value);
const firstBytePos = match && match[1] ? +match[1] : undefined;
const lastBytePos = match && match[2] ? +match[2] : undefined;
if (firstBytePos !== undefined && lastBytePos !== undefined) {
if (lastBytePos < firstBytePos) return undefined;
return { start: firstBytePos, end: lastBytePos + 1 };
2016-04-09 01:53:52 +02:00
}
2018-04-24 06:52:16 +02:00
if (firstBytePos !== undefined) return { start: firstBytePos, end: contentLength };
if (lastBytePos !== undefined) return { start: contentLength - lastBytePos, end: contentLength };
return undefined;
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function tryParseByteRanges(value: string, contentLength: number): ByteRange[] | undefined {
if (!value.startsWith("bytes=")) return;
const ranges: ByteRange[] = [];
for (const range of value.slice(6).split(",")) {
const byteRange = tryParseByteRange(range, contentLength);
if (byteRange === undefined) return undefined;
if (byteRange.start >= contentLength) continue;
ranges.push(byteRange);
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
return ranges;
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function once<T extends (...args: any[]) => void>(callback: T): T;
function once(callback: (...args: any[]) => void) {
let called = false;
return (...args: any[]) => {
if (called) return;
called = true;
callback(...args);
};
2016-04-09 01:53:52 +02:00
}
2018-04-24 06:52:16 +02:00
function mkdirp(dirname: string, callback: (err: NodeJS.ErrnoException | null) => void) {
fs.mkdir(dirname, err => {
if (err && err.code === "EEXIST") err = null;
if (err && err.code === "ENOENT") {
const parentdir = path.dirname(dirname);
if (!parentdir || parentdir === dirname) return callback(err);
return mkdirp(parentdir, err => {
if (err) return callback(err);
return fs.mkdir(dirname, callback);
});
}
return callback(err);
});
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function getAccessibleFileSystemEntries(pathname: string) {
try {
const entries = fs.readdirSync(pathname).sort();
2017-10-20 02:48:13 +02:00
const files: string[] = [];
2018-04-24 06:52:16 +02:00
const directories: string[] = [];
for (const entry of entries) {
// This is necessary because on some file system node fails to exclude
// "." and "..". See https://github.com/nodejs/node/issues/4002
if (entry === "." || entry === "..") {
continue;
}
const name = path.join(pathname, entry);
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
let stat: fs.Stats;
try {
stat = fs.statSync(name);
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
catch (e) {
continue;
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
if (stat.isFile()) {
files.push(entry);
}
else if (stat.isDirectory()) {
directories.push(entry);
}
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
return { files, directories };
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
catch (e) {
return { files: [], directories: [] };
2017-10-20 02:48:13 +02:00
}
2016-04-09 01:53:52 +02:00
}
2018-04-24 06:52:16 +02:00
function guessMediaType(pathname: string) {
switch (path.extname(pathname).toLowerCase()) {
case ".html": return "text/html; charset=utf-8";
case ".css": return "text/css; charset=utf-8";
case ".js": return "application/javascript; charset=utf-8";
case ".mjs": return "application/javascript; charset=utf-8";
case ".jsx": return "text/jsx; charset=utf-8";
case ".ts": return "text/plain; charset=utf-8";
case ".tsx": return "text/plain; charset=utf-8";
case ".json": return "text/plain; charset=utf-8";
case ".map": return "application/json; charset=utf-8";
default: return "application/octet-stream";
}
}
function readContent(req: http.ServerRequest, callback: (err: NodeJS.ErrnoException | null, content: string | null) => void) {
const chunks: Buffer[] = [];
const done = once((err: NodeJS.ErrnoException | null) => {
if (err) return callback(err, /*content*/ null);
let content: string | null = null;
try {
content = Buffer.concat(chunks).toString("utf8");
}
catch (e) {
err = e;
}
return callback(err, content);
});
req.on("data", chunk => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf8")));
req.on("error", err => done(err));
req.on("end", () => done(/*err*/ null));
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function saveToFile(file: string, readable: Readable, callback: (err: NodeJS.ErrnoException | null) => void) {
callback = once(callback);
const writable = fs.createWriteStream(file, { autoClose: true });
writable.on("error", err => callback(err));
readable.on("end", () => callback(/*err*/ null));
readable.pipe(writable, { end: true });
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function sendContent(res: http.ServerResponse, statusCode: number, content: string | Buffer, contentType: string): void;
function sendContent(res: http.ServerResponse, statusCode: number, content: Readable, contentType: string, contentLength: number): void;
function sendContent(res: http.ServerResponse, statusCode: number, content: string | Buffer | Readable, contentType: string, contentLength?: number) {
res.statusCode = statusCode;
res.setHeader("Content-Type", contentType);
if (isString(content)) {
res.setHeader("Content-Length", Buffer.byteLength(content, "utf8"));
res.end(content, "utf8");
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
else if (isBuffer(content)) {
res.setHeader("Content-Length", content.byteLength);
res.end(content);
}
else {
if (contentLength !== undefined) res.setHeader("Content-Length", contentLength);
content.on("error", e => sendInternalServerError(res, e));
content.pipe(res, { end: true });
2016-04-09 01:53:52 +02:00
}
}
2018-04-24 06:52:16 +02:00
function sendJson(res: http.ServerResponse, statusCode: number, value: any) {
try {
sendContent(res, statusCode, JSON.stringify(value), "application/json; charset=utf-8");
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
catch (e) {
sendInternalServerError(res, e);
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function sendCreated(res: http.ServerResponse, location?: string, etag?: string) {
res.statusCode = 201;
if (location) res.setHeader("Location", location);
if (etag) res.setHeader("ETag", etag);
res.end();
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function sendNoContent(res: http.ServerResponse) {
res.statusCode = 204;
res.end();
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function sendFound(res: http.ServerResponse, location: string) {
res.statusCode = 302;
res.setHeader("Location", location);
res.end();
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function sendNotModified(res: http.ServerResponse) {
res.statusCode = 304;
res.end();
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function sendBadRequest(res: http.ServerResponse) {
res.statusCode = 400;
res.end();
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function sendNotFound(res: http.ServerResponse) {
res.statusCode = 404;
res.end();
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function sendMethodNotAllowed(res: http.ServerResponse, allowedMethods: string[]) {
res.statusCode = 405;
res.setHeader("Allow", allowedMethods);
res.end();
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function sendNotAcceptable(res: http.ServerResponse) {
res.statusCode = 406;
res.end();
2014-07-13 01:04:16 +02:00
}
2018-04-24 06:52:16 +02:00
function sendPreconditionFailed(res: http.ServerResponse) {
res.statusCode = 412;
res.end();
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function sendUnsupportedMediaType(res: http.ServerResponse) {
res.statusCode = 415;
res.end();
2014-07-13 01:04:16 +02:00
}
2018-04-24 06:52:16 +02:00
function sendRangeNotSatisfiable(res: http.ServerResponse) {
res.statusCode = 416;
res.end();
2017-10-20 02:48:13 +02:00
}
2014-07-13 01:04:16 +02:00
2018-04-24 06:52:16 +02:00
function sendInternalServerError(res: http.ServerResponse, error: Error) {
console.error(error);
return sendContent(res, /*statusCode*/ 500, error.stack, "text/plain; charset=utf8");
2014-07-13 01:04:16 +02:00
}
2018-04-24 06:52:16 +02:00
function sendNotImplemented(res: http.ServerResponse) {
res.statusCode = 501;
res.end();
[Transforms] Merge master 08/09 (#10263) * Improve error message * Remove `SupportedExpressionWithTypeArguments` type; just check that the expression of each `ExpressionWithTypeArguments` is an `EntityNameExpression`. * Fix bug * Fix #10083 - allowSyntheticDefaultImports alters getExternalModuleMember (#10096) * Use recursion, and fix error for undefined node * Rename function * Fix lint error * Narrowing type parameter intersects w/narrowed types This makes sure that a union type that includes a type parameter is still usable as the actual type that the type guard narrows to. * Don't allow ".d.ts" extension in an import either. * Add a helper function `getOrUpdateProperty` to prevent unprotected access to Maps. * Limit type guards as assertions to incomplete types in loops * Accept new baselines * Fix linting error * Allow JS multiple declarations of ctor properties When a property is declared in the constructor and on the prototype of an ES6 class, the property's symbol is discarded in favour of the method's symbol. That because the usual use for this pattern is to bind an instance function: `this.m = this.m.bind(this)`. In this case the type you want really is the method's type. * Use {} type facts for unconstrained type params Previously it was using TypeFacts.All. But the constraint of an unconstrained type parameter is actually {}. * Fix newline lint * Test that declares conflicting method first * [Release-2.0] Fix 9662: Visual Studio 2015 with TS2.0 gives incorrect @types path resolution errors (#9867) * Change the shape of the shim layer to support getAutomaticTypeDirectives * Change the key for looking up automatic type-directives * Update baselines from change look-up name of type-directives * Add @currentDirectory into the test * Update baselines * Fix linting error * Address PR: fix spelling mistake * Instead of return path of the type directive names just return type directive names * Remove unused reference files: these tests produce erros so they will not produce these files (#9233) * Add string-literal completion test for jsdoc * Support other (new) literal types in jsdoc * Don't allow properties inherited from Object to be automatically included in TSX attributes * Add new test baseline and delete else in binder The extra `else` caused a ton of test failures! * Fix lint * Port PR #10016 to Master (#10100) * Treat namespaceExportDeclaration as declaration * Update baselines * wip - add tests * Add tests * Show "export namespace" for quick-info * Fix more lint * Try using runtests-parallel for CI (#9970) * Try using runtests-parallel for CI * Put worker count setting into .travis.yml * Reduce worker count to 4 - 8 wasnt much different from 4-6 but had contention issues causing timeouts * Fix lssl task (#9967) * Surface noErrorTruncation option * Stricter check for discriminant properties in type guards * Add tests * Emit more efficient/concise "empty" ES6 ctor When there are property assignments in a the class body of an inheriting class, tsc current emit the following compilation: ```ts class Foo extends Bar { public foo = 1; } ``` ```js class Foo extends Bar { constructor(…args) { super(…args); this.foo = 1; } } ``` This introduces an unneeded local variable and might force a reification of the `arguments` object (or otherwise reify the arguments into an array). This is particularly bad when that output is fed into another transpiler like Babel. In Babel, you get something like this today: ```js var Foo = (function (_Bar) { _inherits(Foo, _Bar); function Foo() { _classCallCheck(this, Foo); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _Bar.call.apply(_Bar, [this].concat(args)); this.foo = 1; } return Foo; })(Bar); ``` This causes a lot of needless work/allocations and some very strange code (`.call.apply` o_0). Admittedly, this is not strictly tsc’s problem; it could have done a deeper analysis of the code and optimized out the extra dance. However, tsc could also have emitted this simpler, more concise and semantically equivalent code in the first place: ```js class Foo extends Bar { constructor() { super(…arguments); this.foo = 1; } } ``` Which compiles into the following in Babel: ```js var Foo = (function (_Bar) { _inherits(Foo, _Bar); function Foo() { _classCallCheck(this, Foo); _Bar.apply(this, arguments); this.foo = 1; } return Foo; })(Bar); ``` Which is well-optimized (today) in most engines and much less confusing to read. As far as I can tell, the proposed compilation has exactly the same semantics as before. Fixes #10175 * Fix instanceof operator narrowing issues * Accept new baselines * Add regression test * Improve naming and documentation from PR * Update comment * Add more tests * Accept new baselines * Reduce worker count to 3 (#10210) Since we saw a starvation issue on one of @sandersn's PRs. * Speed up fourslash tests * Duh * Make baselines faster by not writing out unneeded files * Fix non-strict-compliant test * Fix 10076: Fix Tuple Destructing with "this" (#10208) * Call checkExpression eventhough there is no appropriate type from destructuring of array * Add tests and baselines * use transpileModule * Remove use strict * Improve instanceof for structurally identical types * Introduce isTypeInstanceOf function * Add test * Accept new baselines * Fix loop over array to use for-of instead of for-in * Use correct this in tuple type parameter constraints Instantiate this in tuple types used as type parameter constraints * Add explanatory comment to resolveTupleTypeMembers * Ignore null, undefined, void when checking for discriminant property * Add regression test * Delay tuple type constraint resolution Create a new tuple that stores the this-type. * Always use thisType when generating tuple id * Optimize format of type list id strings used in maps * wip - fix error * Make ReadonlyArray iterable. * Allow OSX to fail while we investigate (#10255) The random test timeouts are an issue. * Fix error from using merging master * avoid using the global name * Fix single-quote lint * Update baselines * Fix linting * Optimize performance of maps * Update API sample * Fix processDiagnosticMessages script * Have travis take shallow clones of the repo (#10275) Just cloning TS on travis takes 23 seconds on linux (68 seconds on mac), hopefully having it do a shallow clone will help. We don't rely on any tagging/artifacts from the travis servers which clone depth could impact, so this shouldn't impact anything other than build speed. * Add folds to travis log (#10269) * Optimize filterType to only call getUnionType if necessary * Add shorthand types declaration for travis-fold (#10293) * Optimize getTypeWithFacts * Filter out nullable and primitive types in isDiscriminantProperty * Fix typo * Add regression tests * Optimize core filter function to only allocate when necessary * Address CR comments + more optimizations * Faster path for creating union types from filterType * Allow an @types direcotry to have a package.json which specifies `"typings": null` to disclude it from automatically included typings. * Lint * Collect timing information for commands running on travis (#10308) * Simplifies performance API * Use 'MapLike' instead of 'Map' in 'preferConstRule.ts'. * narrow from 'any' in most situations instanceof and user-defined typeguards narrow from 'any' unless the narrowed-to type is exactly 'Object' or 'Function'. This is a breaking change. * Update instanceof conformance tests * accept new baselines * add tests * accept new baselines * Use lowercase names for type reference directives * Use proper response codes in web tests * Treat ambient shorthand declarations as explicit uses of the `any` type * Rename 'find' functions * Parallel linting (#10313) * A perilous thing, a parallel lint * Use work queue rather than scheduling work * Dont read files for lint on main thread * Fix style * Fix the style fix (#10344) * Aligned mark names with values used by ts-perf. * Use an enum in checkClassForDuplicateDeclarations to aid readability * Rename to Accessor * Migrated more MapLikes to Maps * Add ES2015 Date constructor signature that accepts another Date (#10353) * Parameters with no assignments implicitly considered const * Add tests * Migrate additional MapLikes to Maps. * Fix 10625: JSX Not validating when index signature is present (#10352) * Check for type of property declaration before using index signature * Add tests and baselines * fix linting error * Adding more comments * Clean up/move some Map helper functions. * Revert some formatting changes. * Improve ReadonlyArray<T>.concat to match Array<T> The Array-based signature was incorrect and also out-of-date. * Fix link to blog * Remove old assertion about when we're allowed to use fileExists * Set isNewIdentifierLocation to true for JavaScript files * Update error message for conflicting type definitions Fixes #10370 * Explain why we lower-case type reference directives * Correctly merge bindThisPropertyAssignment Also simply it considerably after noticing that it's *only* called for Javascript files, so there was a lot of dead code for TS cases that never happened. * Fix comment * Property handle imcomplete control flow types in nested loops * Update due to CR suggestion * Add regression test * Assign and instantiate contextual this type if not present * Fix 10289: correctly generate tsconfig.json with --lib (#10355) * Separate generate tsconfig into its own function and implement init with --lib # Conflicts: # src/compiler/tsc.ts * Add tests and baselines; Update function name Add unittests and baselines Add unittests and baselines for generating tsconfig Move unittest into harness folder Update harness tsconfig.json USe correct function name * Use new MapLike interstead. Update unittest # Conflicts: # src/compiler/commandLineParser.ts * Update JakeFile * Add tests for incorrect cases * Address PR : remove explicity write node_modules * JSDoc supports null, undefined and never types * Update baselines in jsDocParsing unit tests * Restored comments to explain spreading 'arguments' into calls to 'super'. * Added test. * Use the non-nullable type of the contextual type for object completions. * Return non-JsDocComment children ... to make syntactic classification work * Add more tests for `export = foo.bar`. * Output test baselines to tests/baselines/local instead of root * Move supportedTypescriptExtensionsWithDtsFirst next to supportedTypeScriptExtensions and rename * Fix comment * Fix RWC Runner (#10420) * Use /// <reference types * Don't report an errors if it comes from lib.d.ts * Treat special property access symbol differently ... when retriving documentation * Fix tests * Update shim version to be 2.1 (#10424) * Check return code paths on getters (#10102) * Check return paths on getters * Remove TODO comment * Remove extraneous arguments from harness's runBaseline (#10419) * Remove extraneous arguments from runBaseline * Address comments from @yuit * Remove needless call to basename * Refactor baseliners out of compiler runner (#10440) * CR feedback * fix broken tests * Pass in baselineOpts into types baselines so that RWC baselines can be written to internal folder (#10443) * Add error message Add error message when trying to relate primitives to the boxed/apparent backing types. * fix linting error * follow advise * remove extra code * Add more test for 10426 * fix some errors * routine update of dom libs * Add test for jsdoc syntactic classification for function declaration * Simplify implementation * Tolerate certain errors in tsconfig.json * Add test for configFile error tolerance * Use TS parser to tolerate more errors in tsconfig.json * Implement tuple types as type references to synthesized generic types * Add comments + minor changes * Accept new baselines * Add .types extension * Properly guard for undefined in getTypeReferenceArity * Add jsdoc nullable union test case to fourslash * Fix class/interface merging issue + lint error * Allow "typings" in a package.json to be missing its extension (but also allow it to have an extension) * Contextually type this in getDeclFromSig, not checkThisExpr * Update parser comment with es7 grammar (#10459) * Use ES7 term of ExponentiationExpression * Update timeout for mac OS * Address PR: add space * allowSyntheticDefaultImports resolves to modules instead of variables Fixes #10429 by improving the fix in #10096 * Rename getContextuallyTypedThisParameter to getContextualThisParameter * Fix 10472: Invalid emitted code for await expression (#10483) * Properly emit await expression with yield expression * Add tests and update baselines * Move parsing await expression into parse unary-expression * Update incorrect comment * change error message * Fix broken build from merging with master * Fix linting error
2016-08-27 00:51:10 +02:00
}
2018-04-24 06:52:16 +02:00
function shouldIgnoreCache(url: URL) {
switch (url.pathname) {
case "/built/local/bundle.js":
case "/built/local/bundle.js.map":
return true;
default:
return false;
}
2014-07-13 01:04:16 +02:00
}
2018-04-24 06:52:16 +02:00
function isAcceptable(req: http.ServerRequest, contentType: string) {
const mediaType = parseMediaType(contentType);
return isAcceptableMediaType(req, mediaType)
&& isAcceptableCharSet(req, mediaType)
&& isAcceptableEncoding(req);
2017-10-20 02:48:13 +02:00
}
2014-07-13 01:04:16 +02:00
2018-04-24 06:52:16 +02:00
function isAcceptableMediaType(req: http.ServerRequest, mediaType: MediaType) {
if (!req.headers.accept) return true;
const acceptedMediaType = bestMatch(mediaType, parseMediaTypes(req.headers.accept), matchesMediaType);
return acceptedMediaType ? getQuality(acceptedMediaType) > 0 : false;
2017-10-20 02:48:13 +02:00
}
2014-07-13 01:04:16 +02:00
2018-04-24 06:52:16 +02:00
function isAcceptableCharSet(req: http.ServerRequest, mediaType: MediaType) {
if (!req.headers["accept-charset"]) return true;
const acceptedCharSet = bestMatch(mediaType.charset || "utf-8", parseStringsWithQuality(req.headers["accept-charset"]), matchesCharSet);
return acceptedCharSet ? getQuality(acceptedCharSet) > 0 : false;
2017-10-20 02:48:13 +02:00
}
2014-07-13 01:04:16 +02:00
2018-04-24 06:52:16 +02:00
function isAcceptableEncoding(req: http.ServerRequest) {
if (!req.headers["accept-encoding"]) return true;
const acceptedEncoding = bestMatch(/*value*/ undefined, parseStringsWithQuality(req.headers["accept-encoding"]), (_, pattern) => pattern.value === "*" || pattern.value === "identity");
return acceptedEncoding ? getQuality(acceptedEncoding) > 0 : true;
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
function shouldSendNotModified(req: http.ServerRequest, stats: fs.Stats, etag: string) {
const ifNoneMatch = tryParseETags(req.headers["if-none-match"]);
if (ifNoneMatch) return matchesETag(etag, ifNoneMatch);
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
const ifModifiedSince = tryParseDate(req.headers["if-modified-since"]);
if (ifModifiedSince) return stats.mtime.getTime() <= ifModifiedSince.getTime();
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
return false;
2014-07-13 01:04:16 +02:00
}
2018-04-24 06:52:16 +02:00
function shouldSendPreconditionFailed(req: http.ServerRequest, stats: fs.Stats, etag: string) {
const ifMatch = tryParseETags(req.headers["if-match"]);
if (ifMatch && !matchesETag(etag, ifMatch)) return true;
2014-07-13 01:04:16 +02:00
2018-04-24 06:52:16 +02:00
const ifUnmodifiedSince = tryParseDate(req.headers["if-unmodified-since"]);
if (ifUnmodifiedSince && stats.mtime.getTime() > ifUnmodifiedSince.getTime()) return true;
return false;
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
function handleGetRequest(req: http.ServerRequest, res: http.ServerResponse) {
const url = new URL(req.url, baseUrl);
if (url.pathname === "/") {
url.pathname = "/tests/webTestResults.html";
return sendFound(res, url.toString());
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
const file = toServerPath(url);
fs.stat(file, (err, stats) => {
try {
if (err) {
if (err.code === "ENOENT") return sendNotFound(res);
return sendInternalServerError(res, err);
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
if (stats && stats.isFile()) {
const contentType = guessMediaType(file);
if (!isAcceptable(req, contentType)) return sendNotAcceptable(res);
const etag = computeETag(stats);
if (shouldSendNotModified(req, stats, etag)) return sendNotModified(res);
if (shouldSendPreconditionFailed(req, stats, etag)) return sendPreconditionFailed(res);
if (shouldIgnoreCache(url)) res.setHeader("Cache-Control", "no-store");
res.setHeader("Last-Modified", stats.mtime.toUTCString());
res.setHeader("ETag", etag);
res.setHeader("Content-Type", contentType);
res.setHeader("Accept-Ranges", "bytes");
const ranges = req.headers.range && tryParseByteRanges(req.headers.range, stats.size);
if (ranges && ranges.length === 0) return sendRangeNotSatisfiable(res);
let start: number | undefined;
let end: number | undefined;
if (ranges && ranges.length === 1) {
start = ranges[0].start;
end = ranges[0].end;
if (start >= stats.size || end > stats.size) return sendRangeNotSatisfiable(res);
res.statusCode = 206;
res.setHeader("Content-Length", end - start);
res.setHeader("Content-Range", `bytes ${start}-${end - 1}/${stats.size}`);
}
else {
res.statusCode = 200;
res.setHeader("Content-Length", stats.size);
}
if (req.method === "HEAD") return res.end();
const readable = fs.createReadStream(file, { start, end, autoClose: true });
readable.on("error", err => sendInternalServerError(res, err));
readable.pipe(res, { end: true });
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
else {
if (req.headers["if-match"] === "*") return sendPreconditionFailed(res);
return sendNotFound(res);
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
}
catch (e) {
return sendInternalServerError(res, e);
}
});
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function handlePutRequest(req: http.ServerRequest, res: http.ServerResponse) {
if (req.headers["content-encoding"]) return sendUnsupportedMediaType(res);
if (req.headers["content-range"]) return sendNotImplemented(res);
const file = toServerPath(req.url);
fs.stat(file, (err, stats) => {
try {
if (err && err.code !== "ENOENT") return sendInternalServerError(res, err);
if (stats && !stats.isFile()) return sendMethodNotAllowed(res, []);
return mkdirp(path.dirname(file), err => {
if (err) return sendInternalServerError(res, err);
try {
const writable = fs.createWriteStream(file, { autoClose: true });
writable.on("error", err => sendInternalServerError(res, err));
writable.on("finish", () => {
if (stats) return sendNoContent(res);
fs.stat(file, (err, stats) => {
if (err) return sendInternalServerError(res, err);
return sendCreated(res, toClientPath(file), computeETag(stats));
});
});
req.pipe(writable, { end: true });
return;
}
catch (e) {
return sendInternalServerError(res, e);
}
});
}
catch (e) {
return sendInternalServerError(res, e);
}
});
}
function handleDeleteRequest(req: http.ServerRequest, res: http.ServerResponse) {
const file = toServerPath(req.url);
fs.stat(file, (err, stats) => {
try {
if (err && err.code !== "ENOENT") return sendInternalServerError(res, err);
if (!stats) return sendNotFound(res);
if (stats.isFile()) return fs.unlink(file, handleResult);
if (stats.isDirectory()) return fs.rmdir(file, handleResult);
return sendNotFound(res);
function handleResult(err: NodeJS.ErrnoException) {
if (err && err.code !== "ENOENT") return sendInternalServerError(res, err);
if (err) return sendNotFound(res);
return sendNoContent(res);
2014-07-13 01:04:16 +02:00
}
}
2018-04-24 06:52:16 +02:00
catch (e) {
return sendInternalServerError(res, e);
}
});
2014-07-13 01:04:16 +02:00
}
2018-04-24 06:52:16 +02:00
function handleOptionsRequest(req: http.ServerRequest, res: http.ServerResponse) {
res.setHeader("X-Case-Sensitivity", useCaseSensitiveFileNames ? "CS" : "CI");
return sendNoContent(res);
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
function handleApiResolve(req: http.ServerRequest, res: http.ServerResponse) {
readContent(req, (err, content) => {
try {
if (err) return sendInternalServerError(res, err);
if (!content) return sendBadRequest(res);
const serverPath = toServerPath(content);
const clientPath = toClientPath(serverPath);
if (clientPath === undefined) return sendBadRequest(res);
return sendContent(res, /*statusCode*/ 200, clientPath, /*contentType*/ "text/plain;charset=utf-8");
}
catch (e) {
return sendInternalServerError(res, e);
}
});
2017-10-20 02:48:13 +02:00
}
function handleApiEnumerateTestFiles(req: http.ServerRequest, res: http.ServerResponse) {
readContent(req, (err, content) => {
try {
if (err) return sendInternalServerError(res, err);
if (!content) return sendBadRequest(res);
2018-05-09 21:57:48 +02:00
const tests: (string | FileBasedTest)[] = enumerateTestFiles(content);
return sendJson(res, /*statusCode*/ 200, tests);
}
catch (e) {
return sendInternalServerError(res, e);
}
});
}
function enumerateTestFiles(runner: string) {
switch (runner) {
case "conformance":
case "compiler":
return listFiles(`tests/cases/${runner}`, /*serverDirname*/ undefined, /\.tsx?$/, { recursive: true }).map(parseCompilerTestConfigurations);
case "fourslash":
return listFiles(`tests/cases/fourslash`, /*serverDirname*/ undefined, /\.ts/i, { recursive: false });
case "fourslash-shims":
return listFiles(`tests/cases/fourslash/shims`, /*serverDirname*/ undefined, /\.ts/i, { recursive: false });
case "fourslash-shims-pp":
return listFiles(`tests/cases/fourslash/shims-pp`, /*serverDirname*/ undefined, /\.ts/i, { recursive: false });
case "fourslash-server":
return listFiles(`tests/cases/fourslash/server`, /*serverDirname*/ undefined, /\.ts/i, { recursive: false });
default:
throw new Error(`Runner '${runner}' not supported in browser tests.`);
}
}
// Regex for parsing options in the format "@Alpha: Value of any sort"
const optionRegex = /^[\/]{2}\s*@(\w+)\s*:\s*([^\r\n]*)/gm; // multiple matches on multiple lines
2018-05-09 21:57:48 +02:00
function extractCompilerSettings(content: string): Record<string, string> {
const opts: Record<string, string> = {};
let match: RegExpExecArray;
while ((match = optionRegex.exec(content)) !== null) {
opts[match[1]] = match[2].trim();
}
return opts;
}
2018-05-09 21:57:48 +02:00
function splitVaryBySettingValue(text: string): string[] | undefined {
if (!text) return undefined;
const entries = text.split(/,/).map(s => s.trim().toLowerCase()).filter(s => s.length > 0);
return entries && entries.length > 1 ? entries : undefined;
}
2018-05-09 21:57:48 +02:00
function computeFileBasedTestConfigurationVariations(configurations: FileBasedTestConfiguration[], variationState: FileBasedTestConfiguration, varyByEntries: [string, string[]][], offset: number) {
if (offset >= varyByEntries.length) {
// make a copy of the current variation state
configurations.push({ ...variationState });
return;
}
2018-05-09 21:57:48 +02:00
const [varyBy, entries] = varyByEntries[offset];
for (const entry of entries) {
// set or overwrite the variation
variationState[varyBy] = entry;
computeFileBasedTestConfigurationVariations(configurations, variationState, varyByEntries, offset + 1);
}
}
function getFileBasedTestConfigurations(settings: Record<string, string>, varyBy: string[]): FileBasedTestConfiguration[] | undefined {
let varyByEntries: [string, string[]][] | undefined;
for (const varyByKey of varyBy) {
if (Object.prototype.hasOwnProperty.call(settings, varyByKey)) {
const entries = splitVaryBySettingValue(settings[varyByKey]);
if (entries) {
if (!varyByEntries) varyByEntries = [];
varyByEntries.push([varyByKey, entries]);
}
}
}
2018-05-09 21:57:48 +02:00
if (!varyByEntries) return undefined;
const configurations: FileBasedTestConfiguration[] = [];
computeFileBasedTestConfigurationVariations(configurations, {}, varyByEntries, 0);
return configurations;
}
2018-05-09 21:57:48 +02:00
function parseCompilerTestConfigurations(file: string): FileBasedTest {
const content = fs.readFileSync(path.join(rootDir, file), "utf8");
const settings = extractCompilerSettings(content);
const configurations = getFileBasedTestConfigurations(settings, ["module", "target"]);
return { file, configurations };
}
2018-04-24 06:52:16 +02:00
function handleApiListFiles(req: http.ServerRequest, res: http.ServerResponse) {
readContent(req, (err, content) => {
try {
if (err) return sendInternalServerError(res, err);
if (!content) return sendBadRequest(res);
const serverPath = toServerPath(content);
const files = listFiles(content, serverPath, /*spec*/ undefined, { recursive: true });
2018-04-24 06:52:16 +02:00
return sendJson(res, /*statusCode*/ 200, files);
}
catch (e) {
return sendInternalServerError(res, e);
}
});
2017-10-20 02:48:13 +02:00
}
function listFiles(clientDirname: string, serverDirname: string = path.resolve(rootDir, clientDirname), spec?: RegExp, options: { recursive?: boolean } = {}): string[] {
const files: string[] = [];
visit(serverDirname, clientDirname, files);
return files;
function visit(dirname: string, relative: string, results: string[]) {
const { files, directories } = getAccessibleFileSystemEntries(dirname);
for (const file of files) {
if (!spec || file.match(spec)) {
results.push(path.join(relative, file));
}
}
for (const directory of directories) {
if (options.recursive) {
visit(path.join(dirname, directory), path.join(relative, directory), results);
}
}
}
}
2018-04-24 06:52:16 +02:00
function handleApiDirectoryExists(req: http.ServerRequest, res: http.ServerResponse) {
readContent(req, (err, content) => {
try {
if (err) return sendInternalServerError(res, err);
if (!content) return sendBadRequest(res);
const serverPath = toServerPath(content);
fs.stat(serverPath, (err, stats) => {
try {
if (err && err.code !== "ENOENT") return sendInternalServerError(res, err);
return sendJson(res, /*statusCode*/ 200, !!stats && stats.isDirectory());
}
catch (e) {
return sendInternalServerError(res, e);
}
});
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
catch (e) {
return sendInternalServerError(res, e);
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
});
}
function handleApiGetAccessibleFileSystemEntries(req: http.ServerRequest, res: http.ServerResponse) {
readContent(req, (err, content) => {
try {
if (err) return sendInternalServerError(res, err);
if (!content) return sendBadRequest(res);
const serverPath = toServerPath(content);
return sendJson(res, /*statusCode*/ 200, getAccessibleFileSystemEntries(serverPath));
2017-10-20 02:48:13 +02:00
}
2018-04-24 06:52:16 +02:00
catch (e) {
return sendInternalServerError(res, e);
}
});
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function handlePostRequest(req: http.ServerRequest, res: http.ServerResponse) {
// API responses should not be cached
res.setHeader("Cache-Control", "no-cache");
switch (new URL(req.url, baseUrl).pathname) {
case "/api/resolve": return handleApiResolve(req, res);
case "/api/listFiles": return handleApiListFiles(req, res);
case "/api/enumerateTestFiles": return handleApiEnumerateTestFiles(req, res);
2018-04-24 06:52:16 +02:00
case "/api/directoryExists": return handleApiDirectoryExists(req, res);
case "/api/getAccessibleFileSystemEntries": return handleApiGetAccessibleFileSystemEntries(req, res);
default: return sendMethodNotAllowed(res, ["HEAD", "GET", "PUT", "DELETE", "OPTIONS"]);
2014-07-13 01:04:16 +02:00
}
2018-04-24 06:52:16 +02:00
}
2017-10-20 02:48:13 +02:00
2018-04-24 06:52:16 +02:00
function handleRequest(req: http.ServerRequest, res: http.ServerResponse) {
try {
switch (req.method) {
case "HEAD":
case "GET": return handleGetRequest(req, res);
case "PUT": return handlePutRequest(req, res);
case "POST": return handlePostRequest(req, res);
case "DELETE": return handleDeleteRequest(req, res);
case "OPTIONS": return handleOptionsRequest(req, res);
default: return sendMethodNotAllowed(res, ["HEAD", "GET", "PUT", "POST", "DELETE"]);
}
}
catch (e) {
return sendInternalServerError(res, e);
}
2017-10-20 02:48:13 +02:00
}
function startServer() {
console.log(`Static file server running at\n => http://localhost:${port}/\nCTRL + C to shutdown`);
2018-04-24 06:52:16 +02:00
return http.createServer(handleRequest).listen(port);
2016-07-27 16:26:28 +02:00
}
2017-10-20 02:48:13 +02:00
const REG_COLUMN_PADDING = 4;
function queryRegistryValue(keyPath: string, callback: (error: Error | null, value: string) => void) {
const args = ["query", keyPath];
child_process.execFile("reg", ["query", keyPath, "/ve"], { encoding: "utf8" }, (error, stdout) => {
if (error) return callback(error, null);
const valueLine = stdout.replace(/^\r\n.+?\r\n|\r\n\r\n$/g, "");
if (!valueLine) {
return callback(new Error("Unable to retrieve value."), null);
}
const valueNameColumnOffset = REG_COLUMN_PADDING;
if (valueLine.lastIndexOf("(Default)", valueNameColumnOffset) !== valueNameColumnOffset) {
return callback(new Error("Unable to retrieve value."), null);
}
const dataTypeColumnOffset = valueNameColumnOffset + "(Default)".length + REG_COLUMN_PADDING;
if (valueLine.lastIndexOf("REG_SZ", dataTypeColumnOffset) !== dataTypeColumnOffset) {
return callback(new Error("Unable to retrieve value."), null);
}
const valueColumnOffset = dataTypeColumnOffset + "REG_SZ".length + REG_COLUMN_PADDING;
const value = valueLine.slice(valueColumnOffset);
return callback(null, value);
});
}
interface Browser {
description: string;
command: string;
}
function createBrowserFromPath(path: string): Browser {
return { description: path, command: path };
}
function getChromePath(callback: (error: Error | null, browser: Browser | string | null) => void) {
switch (os.platform()) {
case "win32":
return queryRegistryValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe", (error, value) => {
if (error) return callback(null, "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe");
return callback(null, createBrowserFromPath(value));
});
case "darwin": return callback(null, "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome");
case "linux": return callback(null, "/opt/google/chrome/chrome");
default: return callback(new Error(`Chrome location is unknown for platform '${os.platform()}'`), null);
}
}
function getEdgePath(callback: (error: Error | null, browser: Browser | null) => void) {
switch (os.platform()) {
case "win32": return callback(null, { description: "Microsoft Edge", command: "cmd /c start microsoft-edge:%1" });
default: return callback(new Error(`Edge location is unknown for platform '${os.platform()}'`), null);
}
}
function getBrowserPath(callback: (error: Error | null, browser: Browser | null) => void) {
switch (browser) {
case "chrome": return getChromePath(afterGetBrowserPath);
case "edge": return getEdgePath(afterGetBrowserPath);
default: return callback(new Error(`Browser location is unknown for '${browser}'`), null);
}
function afterGetBrowserPath(error: Error | null, browser: Browser | string | null) {
if (error) return callback(error, null);
if (typeof browser === "object") return callback(null, browser);
return fs.stat(browser, (error, stats) => {
if (!error && stats.isFile()) {
return callback(null, createBrowserFromPath(browser));
}
if (browser === "chrome") return callback(null, createBrowserFromPath("chrome"));
return callback(new Error(`Browser location is unknown for '${browser}'`), null);
});
}
}
2018-04-24 06:52:16 +02:00
function startClient(server: http.Server) {
2017-10-20 02:48:13 +02:00
let browserPath: string;
if (browser === "none") {
return;
}
getBrowserPath((error, browser) => {
if (error) return console.error(error);
console.log(`Using browser: ${browser.description}`);
const queryString = grep ? `?grep=${grep}` : "";
const args = [`http://localhost:${port}/tests/webTestResults.html${queryString}`];
if (browser.command.indexOf("%") === -1) {
child_process.spawn(browser.command, args);
2017-10-20 02:48:13 +02:00
}
else {
const command = browser.command.replace(/%(\d+)/g, (_, offset) => args[+offset - 1]);
child_process.exec(command);
2017-10-20 02:48:13 +02:00
}
});
2018-04-24 06:52:16 +02:00
}
function printHelp() {
console.log("Runs an http server on port 8888, looking for tests folder in the current directory\n");
console.log("Syntax: node webTestServer.js [browser] [tests] [--verbose]\n");
console.log("Options:");
console.log(" <browser> The browser to launch. One of 'edge', 'chrome', or 'none' (default 'edge' on Windows, otherwise `chrome`).");
2018-04-24 06:52:16 +02:00
console.log(" <tests> A regular expression to pass to Mocha.");
console.log(" --verbose Enables verbose logging.");
}
function parseCommandLine(args: string[]) {
const parsed = minimist(args, { boolean: ["help", "verbose"] });
if (parsed.help) {
printHelp();
return false;
}
if (parsed.verbose) {
verbose = true;
}
const [parsedBrowser = defaultBrowser, parsedGrep, ...unrecognized] = parsed._;
if (parsedBrowser !== "edge" && parsedBrowser !== "chrome" && parsedBrowser !== "none") {
console.log(`Unrecognized browser '${parsedBrowser}', expected 'edge', 'chrome', or 'none'.`);
return false;
2018-04-24 06:52:16 +02:00
}
if (unrecognized.length > 0) {
console.log(`Unrecognized argument: ${unrecognized[0]}`);
2018-04-24 06:52:16 +02:00
return false;
}
browser = parsedBrowser;
grep = parsedGrep;
2018-04-24 06:52:16 +02:00
return true;
}
function log(msg: string) {
if (verbose) {
console.log(msg);
}
2014-07-13 01:04:16 +02:00
}
2017-10-20 02:48:13 +02:00
function main() {
if (parseCommandLine(process.argv.slice(2))) {
2018-04-24 06:52:16 +02:00
startClient(startServer());
2017-10-20 02:48:13 +02:00
}
}
2014-07-13 01:04:16 +02:00
2018-04-24 06:52:16 +02:00
main();
// tslint:enable:no-null-keyword