Merge branch 'master' into typeToStringViaTypeNode

This commit is contained in:
Arthur Ozga
2017-04-19 10:48:38 -07:00
5422 changed files with 43795 additions and 37845 deletions
+26 -3
View File
@@ -1,13 +1,14 @@
AbubakerB <abubaker_bashir@hotmail.com> # Abubaker Bashir
Alexander <alexander@kuvaev.me># Alexander Kuvaev
Aluan Haddad <aluanh@gmail.com>
Adam Freidin <adam.freidin@gmail.com> Adam Freidin <afreidin@adobe.com>
Adi Dahiya <adahiya@palantir.com> Adi Dahiya <adi.dahiya14@gmail.com>
Ahmad Farid <ahfarid@microsoft.com> ahmad-farid <ahfarid@microsoft.com>
Alexander Rusakov <a_s_rusakov@mail.ru>
Alex Eagle <alexeagle@google.com>
Anatoly Ressin <anatoly.ressin@icloud.com>
Anders Hejlsberg <andersh@microsoft.com> unknown <andersh@AndersX1.NOE.Nokia.com> unknown <andersh@andersh-yoga.redmond.corp.microsoft.com>
Anders Hejlsberg <andersh@microsoft.com> unknown <andersh@AndersX1.NOE.Nokia.com> unknown <andersh@andersh-yoga.redmond.corp.microsoft.com> Anders Hejlsberg <Anders Hejlsberg>
about-code <about-code@users.noreply.github.com> # Andreas Martin
Andrej Baran <andrej.baran@gmail.com>
Andrew Ochsner <andrew.ochsner@wipro.com>
@@ -24,6 +25,7 @@ Basarat Ali Syed <basaratali@gmail.com> Basarat Syed <basaratali@gmail.com> basa
Bill Ticehurst <billti@hotmail.com> Bill Ticehurst <billti@microsoft.com>
Ben Duffield <jebavarde@gmail.com>
Ben Mosher <me@benmosher.com>
Benjamin Bock <bb@users.noreply.github.com>
Blake Embrey <hello@blakeembrey.com>
Bowden Kelly <wilkelly@microsoft.com>
Brett Mayen <bmayen@midnightsnacks.net>
@@ -49,6 +51,7 @@ Dirk Holtwick <dirk.holtwick@gmail.com>
Dom Chen <domchen@users.noreply.github.com>
Doug Ilijev <dilijev@users.noreply.github.com>
Erik Edrosa <erik.edrosa@gmail.com>
Erik McClenney <erikmcc@google.com>
erictsangx <erictsangx@gmail.com> # Eric Tsang
Ethan Rubio <ethanrubio@users.noreply.github.com>
Evan Martin <martine@danga.com>
@@ -68,13 +71,18 @@ Guillaume Salles <guillaume.salles@me.com>
Guy Bedford <guybedford@gmail.com> guybedford <guybedford@gmail.com>
Harald Niesche <harald@niesche.de>
Homa Wong <homawong@gmail.com>
Hendrik Liebau <mail@hendrik-liebau.de>
Iain Monro <iain.monro@softwire.com>
IgorNovozhilov <maildrakon@gmail.com> # Igor Novozhilov
Ingvar Stepanyan <me@rreverser.com>
impinball <impinball@gmail.com> # Isiah Meadows
Iwata Hidetaka <iwata0303@gmail.com>
Ivo Gabe de Wolff <ivogabe@ivogabe.nl>
Jakub Młokosiewicz <hckr@users.noreply.github.com>
James Whitney <james@whitney.io>
James Henry <james@henry.sc>
Jason Freeman <jfreeman@microsoft.com> Jason Freeman <JsonFreeman@users.noreply.github.com>
Jason Jarrett <jason@elegantcode.com>
Jason Killian <jkillian@palantir.com>
Jason Ramsay <jasonra@microsoft.com> jramsay <jramsay@users.noreply.github.com>
Jed Mao <jed.hunsaker@gmail.com>
@@ -89,6 +97,7 @@ Jonathan Toland <toland@dnalot.com>
Jesse Schalken <me@jesseschalken.com>
Joel Day <joelday@gmail.com>
Josh Abernathy <joshaber@gmail.com> joshaber <joshaber@gmail.com>
Josh Goldberg <joshuakgoldberg@outlook.com>
Josh Kalderimis <josh.kalderimis@gmail.com>
Josh Soref <jsoref@users.noreply.github.com>
Juan Luis Boya García <ntrrgc@gmail.com>
@@ -107,20 +116,26 @@ Keith Mashinter <kmashint@yahoo.com> kmashint <kmashint@yahoo.com>
Ken Howard <ken@simplicatedweb.com>
Kevin Lang <klang2012@gmail.com>
kimamula <kenji.imamula@gmail.com> # Kenji Imamula
Kitson Kelly <me@kitsonkelly.com>
Klaus Meinhardt <klaus.meinhardt1@gmail.com>
Kyle Kelley <rgbkrk@gmail.com>
Lorant Pinter <lorant.pinter@prezi.com>
Lucien Greathouse <me@lpghatguy.com>
Lukas Elmer <lukas.elmer@gmail.com> Lukas Elmer <lukas.elmer@renuo.ch>
Magnus Hiie <magnus.hiie@gmail.com>
Martin Vseticka <vseticka.martin@gmail.com> Martin Všeticka <vseticka.martin@gmail.com> MartyIX <vseticka.martin@gmail.com>
gcnew <gcnew@abv.bg> # Marin Marinov
vvakame <vvakame+dev@gmail.com> # Masahiro Wakame
Matt McCutchen <rmccutch@mit.edu>
Matt McCutchen <rmccutch@mit.edu> Matt McCutchen <matt@mattmccutchen.net>
Matt Bierner <matb@microsoft.com>
MANISH-GIRI <manish.giri.me@gmail.com> # Manish Giri
Max Deepfield <maxdeepfield@absolutefreakout.com>
Micah Zoltu <micah@zoltu.net>
Michael <maykelchiche@gmail.com>
Mike Busyrev <busyrev@gmail.com>
Mine Starks <minestarks@users.noreply.github.com> Mine Starks <mineyalc@microsoft.com>
Mohamed Hegazy <mhegazy@microsoft.com>
ncoley <nrcoley@gmail.com> # Natalie Coley
Nathan Shively-Sanders <nathansa@microsoft.com>
Nathan Yee <ny.nathan.yee@gmail.com>
Nima Zahedi <nima.zahedee@gmail.com>
@@ -143,12 +158,14 @@ Rado Kirov <radokirov@google.com>
Ron Buckton <rbuckton@microsoft.com> Ron Buckton <ron.buckton@microsoft.com> rbuckton <rbuckton@chronicles.org>
Rostislav Galimsky <rostgal@gmail.com>
Richard Knoll <riknoll@users.noreply.github.com> Richard Knoll <riknoll@microsoft.com>
Richard Karmazín <richard@karmazin.cz>
Rowan Wyborn <rwyborn@internode.on.net>
Ryan Cavanaugh <RyanCavanaugh@users.noreply.github.com> Ryan Cavanaugh <ryan.cavanaugh@microsoft.com> Ryan Cavanaugh <ryanca@microsoft.com>
Ryohei Ikegami <iofg2100@gmail.com>
Sarangan Rajamanickam <sarajama@microsoft.com>
Sébastien Arod <sebastien.arod@gmail.com>
Sergey Shandar <sergey-shandar@users.noreply.github.com>
chico <chi187@gmail.com> # Sergey Rubanov
Sheetal Nandi <shkamat@microsoft.com>
Shengping Zhong <zhongsp@users.noreply.github.com>
shyyko.serhiy@gmail.com <shyyko.serhiy@gmail.com> # Shyyko Serhiy
@@ -156,6 +173,7 @@ Sam El-Husseini <samelh@microsoft.com>
Simon Hürlimann <simon.huerlimann@cyt.ch>
Slawomir Sadziak <slsadzia@microsoft.com>
Solal Pirelli <solal.pirelli@gmail.com>
Soo Jae Hwang <misoguy1985@gmail.com>
Stan Thomas <stmsdn@norvil.net>
Stanislav Sysoev <d4rkr00t@gmail.com>
Steve Lucco <steveluc@users.noreply.github.com> steveluc <steveluc@microsoft.com>
@@ -173,6 +191,7 @@ Torben Fitschen <torben.fitschen@mayflower.de>
TruongSinh Tran-Nguyen <i@truongsinh.pro>
vilicvane <i@vilic.info> # Vilic Vane
Vladimir Matveev <vladima@microsoft.com> vladima <vladima@microsoft.com> v2m <desco.by@gmail.com>
Vadi Taslim <vadz77@hotmail.com>
Wesley Wigham <t-weswig@microsoft.com> Wesley Wigham <wwigham@gmail.com>
York Yao <plantain-00@users.noreply.github.com> york yao <yaoao12306@outlook.com> yaoyao <yaoyao12306@163.com>
Yuichi Nukiyama <oscar.wilde84@hotmail.co.jp> YuichiNukiyama <oscar.wilde84@hotmail.co.jp>
@@ -199,6 +218,7 @@ Aliaksandr Radzivanovich <aradzivanovich@gmail.com>
BuildTools <FranklinWhale@users.noreply.github.com> # Franklin Tse
ChogyDan <danielhollocher@gmail.com> # Daniel Hollocher
Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com> Daniel Rosenwasser <drosen@microsoft.com>
DLehenbauer <DLehenbauer@users.noreply.github.com> # Daniel Lehenbauer
David Kmenta <david.kmenta@lmc.eu>
E020873 <nicolas.henry-partner@arcelormittal.com> # Nicolas Henry
Elisée Maurer <elisee@sparklinlabs.com>
@@ -225,4 +245,7 @@ Viktor Zozulyak <zozulyakviktor@gmail.com>
rix <rix@rixs-MacBook-Pro.local> # Richard Sentino
rohitverma007 <rohitverma@live.ca> # Rohit Verma
rdosanjh <me@rajdeep.io> # Raj Dosanjh
gdh1995 <gdh1995@qq.com> # Dahan Gong
gdh1995 <gdh1995@qq.com> # Dahan Gong
cedvdb <cedvandenbosch@gmail.com> # @cedvdb
kpreisser <kpreisser@users.noreply.github.com> # K. Preißer
e-cloud <saintscott119@gmail.com> # @e-cloud
+1 -1
View File
@@ -18,12 +18,12 @@ branches:
- master
- release-2.1
- release-2.2
- release-2.3
install:
- npm uninstall typescript
- npm uninstall tslint
- npm install
- npm update
cache:
directories:
+23
View File
@@ -10,6 +10,7 @@ TypeScript is authored by:
* Alexander Rusakov
* Ali Sabzevari
* Aliaksandr Radzivanovich
* Aluan Haddad
* Anatoly Ressin
* Anders Hejlsberg
* Andreas Martin
@@ -29,6 +30,7 @@ TypeScript is authored by:
* Basarat Ali Syed
* Ben Duffield
* Ben Mosher
* Benjamin Bock
* Bill Ticehurst
* Blake Embrey
* @bootstraponline
@@ -36,6 +38,7 @@ TypeScript is authored by:
* Brett Mayen
* Bryan Forbes
* Caitlin Potter
* @cedvdb
* Charly POLY
* Chris Bubernak
* Christophe Vidal
@@ -49,6 +52,7 @@ TypeScript is authored by:
* Dan Corder
* Dan Quirk
* Daniel Hollocher
* Daniel Lehenbauer
* Daniel Rosenwasser
* David Kmenta
* David Li
@@ -60,10 +64,12 @@ TypeScript is authored by:
* Dirk Holtwick
* Dom Chen
* Doug Ilijev
* @e-cloud
* Elisée Maurer
* Emilio García-Pumarino
* Eric Tsang
* Erik Edrosa
* Erik McClenney
* Ethan Resnick
* Ethan Rubio
* Evan Martin
@@ -84,15 +90,20 @@ TypeScript is authored by:
* Guillaume Salles
* Guy Bedford
* Harald Niesche
* Hendrik Liebau
* Herrington Darkholme
* Homa Wong
* Iain Monro
* Igor Novozhilov
* Ingvar Stepanyan
* Isiah Meadows
* Ivo Gabe de Wolff
* Iwata Hidetaka
* Jakub Młokosiewicz
* James Henry
* James Whitney
* Jason Freeman
* Jason Jarrett
* Jason Killian
* Jason Ramsay
* JBerger
@@ -110,29 +121,34 @@ TypeScript is authored by:
* Jonathan Turner
* Jonathon Smith
* Josh Abernathy
* Josh Goldberg
* Josh Kalderimis
* Josh Soref
* Juan Luis Boya García
* Julian Williams
* Justin Bay
* Justin Johansson
* K. Preißer
* Kagami Sascha Rosylight
* Kanchalai Tanglertsampan
* Keith Mashinter
* Ken Howard
* Kenji Imamula
* Kevin Lang
* Kitson Kelly
* Klaus Meinhardt
* Kyle Kelley
* Kārlis Gaņģis
* Lorant Pinter
* Lucien Greathouse
* Lukas Elmer
* Magnus Hiie
* Manish Giri
* Marin Marinov
* Marius Schulz
* Martin Vseticka
* Masahiro Wakame
* Matt Bierner
* Matt McCutchen
* Mattias Buelens
* Mattias Buelens
@@ -140,8 +156,11 @@ TypeScript is authored by:
* Micah Zoltu
* Michael
* Michael Bromley
* Mike Busyrev
* Mine Starks
* Mohamed Hegazy
* Myles Megyesi
* Natalie Coley
* Nathan Shively-Sanders
* Nathan Yee
* Nicolas Henry
@@ -167,6 +186,7 @@ TypeScript is authored by:
* Punya Biswal
* Rado Kirov
* Raj Dosanjh
* Richard Karmazín
* Richard Knoll
* Richard Sentino
* Robert Coie
@@ -178,6 +198,7 @@ TypeScript is authored by:
* Ryohei Ikegami
* Sam El-Husseini
* Sarangan Rajamanickam
* Sergey Rubanov
* Sergey Shandar
* Sheetal Nandi
* Shengping Zhong
@@ -185,6 +206,7 @@ TypeScript is authored by:
* Simon Hürlimann
* Slawomir Sadziak
* Solal Pirelli
* Soo Jae Hwang
* Stan Thomas
* Stanislav Sysoev
* Steve Lucco
@@ -204,6 +226,7 @@ TypeScript is authored by:
* Tomas Grubliauskas
* Torben Fitschen
* TruongSinh Tran-Nguyen
* Vadi Taslim
* Vidar Tonaas Fauske
* Viktor Zozulyak
* Vilic Vane
+39 -35
View File
@@ -41,6 +41,7 @@ const cmdLineOptions = minimist(process.argv.slice(2), {
boolean: ["debug", "inspect", "light", "colors", "lint", "soft"],
string: ["browser", "tests", "host", "reporter", "stackTraceLimit"],
alias: {
b: "browser",
d: "debug",
t: "tests",
test: "tests",
@@ -162,7 +163,10 @@ const librarySourceMap = [
// JavaScript + all host library
{ target: "lib.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(hostsLibrarySources) },
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") }
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") },
{ target: "lib.es2016.full.d.ts", sources: ["header.d.ts", "es2016.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") },
{ target: "lib.es2017.full.d.ts", sources: ["header.d.ts", "es2017.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") },
{ target: "lib.esnext.full.d.ts", sources: ["header.d.ts", "esnext.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") },
].concat(es2015LibrarySourceMap, es2016LibrarySourceMap, es2017LibrarySourceMap, esnextLibrarySourceMap);
const libraryTargets = librarySourceMap.map(function(f) {
@@ -175,7 +179,7 @@ for (const i in libraryTargets) {
const sources = [copyright].concat(entry.sources.map(function(s) {
return path.join(libraryDirectory, s);
}));
gulp.task(target, false, [], function() {
gulp.task(target, /*help*/ false, [], function() {
return gulp.src(sources)
.pipe(newer(target))
.pipe(concat(target, { newLine: "\n\n" }))
@@ -275,7 +279,7 @@ function getCompilerSettings(base: tsc.Settings, useBuiltCompiler?: boolean): ts
return copy;
}
gulp.task(configureNightlyJs, false, [], () => {
gulp.task(configureNightlyJs, /*help*/ false, [], () => {
const settings: tsc.Settings = {
declaration: false,
removeComments: true,
@@ -304,7 +308,7 @@ const importDefinitelyTypedTestsDirectory = path.join(scriptsDirectory, "importD
const importDefinitelyTypedTestsJs = path.join(importDefinitelyTypedTestsDirectory, "importDefinitelyTypedTests.js");
const importDefinitelyTypedTestsTs = path.join(importDefinitelyTypedTestsDirectory, "importDefinitelyTypedTests.ts");
gulp.task(importDefinitelyTypedTestsJs, false, [], () => {
gulp.task(importDefinitelyTypedTestsJs, /*help*/ false, [], () => {
const settings: tsc.Settings = getCompilerSettings({
declaration: false,
removeComments: true,
@@ -335,7 +339,7 @@ const generatedDiagnosticMessagesJSON = path.join(compilerDirectory, "diagnostic
const builtGeneratedDiagnosticMessagesJSON = path.join(builtLocalDirectory, "diagnosticMessages.generated.json");
// processDiagnosticMessages script
gulp.task(processDiagnosticMessagesJs, false, [], () => {
gulp.task(processDiagnosticMessagesJs, /*help*/ false, [], () => {
const settings: tsc.Settings = getCompilerSettings({
target: "es5",
declaration: false,
@@ -383,8 +387,8 @@ function prependCopyright(outputCopyright: boolean = !useDebugMode) {
return insert.prepend(outputCopyright ? (copyrightContent || (copyrightContent = fs.readFileSync(copyright).toString())) : "");
}
gulp.task(builtLocalCompiler, false, [servicesFile], () => {
const localCompilerProject = tsc.createProject("src/compiler/tsconfig.json", getCompilerSettings({}, /*useBuiltCompiler*/true));
gulp.task(builtLocalCompiler, /*help*/ false, [servicesFile], () => {
const localCompilerProject = tsc.createProject("src/compiler/tsconfig.json", getCompilerSettings({}, /*useBuiltCompiler*/ true));
return localCompilerProject.src()
.pipe(newer(builtLocalCompiler))
.pipe(sourcemaps.init())
@@ -394,15 +398,15 @@ gulp.task(builtLocalCompiler, false, [servicesFile], () => {
.pipe(gulp.dest("src/compiler"));
});
gulp.task(servicesFile, false, ["lib", "generate-diagnostics"], () => {
const servicesProject = tsc.createProject("src/services/tsconfig.json", getCompilerSettings({ removeComments: false }, /*useBuiltCompiler*/false));
gulp.task(servicesFile, /*help*/ false, ["lib", "generate-diagnostics"], () => {
const servicesProject = tsc.createProject("src/services/tsconfig.json", getCompilerSettings({ removeComments: false }, /*useBuiltCompiler*/ false));
const {js, dts} = servicesProject.src()
.pipe(newer(servicesFile))
.pipe(sourcemaps.init())
.pipe(servicesProject());
const completedJs = js.pipe(prependCopyright())
.pipe(sourcemaps.write("."));
const completedDts = dts.pipe(prependCopyright(/*outputCopyright*/true))
const completedDts = dts.pipe(prependCopyright(/*outputCopyright*/ true))
.pipe(insert.transform((contents, file) => {
file.path = standaloneDefinitionsFile;
return contents.replace(/^(\s*)(export )?const enum (\S+) {(\s*)$/gm, "$1$2enum $3 {$4");
@@ -428,8 +432,8 @@ gulp.task(servicesFile, false, ["lib", "generate-diagnostics"], () => {
// cancellationToken.js
const cancellationTokenJs = path.join(builtLocalDirectory, "cancellationToken.js");
gulp.task(cancellationTokenJs, false, [servicesFile], () => {
const cancellationTokenProject = tsc.createProject("src/server/cancellationToken/tsconfig.json", getCompilerSettings({}, /*useBuiltCompiler*/true));
gulp.task(cancellationTokenJs, /*help*/ false, [servicesFile], () => {
const cancellationTokenProject = tsc.createProject("src/server/cancellationToken/tsconfig.json", getCompilerSettings({}, /*useBuiltCompiler*/ true));
return cancellationTokenProject.src()
.pipe(newer(cancellationTokenJs))
.pipe(sourcemaps.init())
@@ -441,8 +445,8 @@ gulp.task(cancellationTokenJs, false, [servicesFile], () => {
// typingsInstallerFile.js
const typingsInstallerJs = path.join(builtLocalDirectory, "typingsInstaller.js");
gulp.task(typingsInstallerJs, false, [servicesFile], () => {
const cancellationTokenProject = tsc.createProject("src/server/typingsInstaller/tsconfig.json", getCompilerSettings({}, /*useBuiltCompiler*/true));
gulp.task(typingsInstallerJs, /*help*/ false, [servicesFile], () => {
const cancellationTokenProject = tsc.createProject("src/server/typingsInstaller/tsconfig.json", getCompilerSettings({}, /*useBuiltCompiler*/ true));
return cancellationTokenProject.src()
.pipe(newer(typingsInstallerJs))
.pipe(sourcemaps.init())
@@ -454,8 +458,8 @@ gulp.task(typingsInstallerJs, false, [servicesFile], () => {
const serverFile = path.join(builtLocalDirectory, "tsserver.js");
gulp.task(serverFile, false, [servicesFile, typingsInstallerJs, cancellationTokenJs], () => {
const serverProject = tsc.createProject("src/server/tsconfig.json", getCompilerSettings({}, /*useBuiltCompiler*/true));
gulp.task(serverFile, /*help*/ false, [servicesFile, typingsInstallerJs, cancellationTokenJs], () => {
const serverProject = tsc.createProject("src/server/tsconfig.json", getCompilerSettings({}, /*useBuiltCompiler*/ true));
return serverProject.src()
.pipe(newer(serverFile))
.pipe(sourcemaps.init())
@@ -468,7 +472,7 @@ gulp.task(serverFile, false, [servicesFile, typingsInstallerJs, cancellationToke
const tsserverLibraryFile = path.join(builtLocalDirectory, "tsserverlibrary.js");
const tsserverLibraryDefinitionFile = path.join(builtLocalDirectory, "tsserverlibrary.d.ts");
gulp.task(tsserverLibraryFile, false, [servicesFile], (done) => {
gulp.task(tsserverLibraryFile, /*help*/ false, [servicesFile], (done) => {
const serverLibraryProject = tsc.createProject("src/server/tsconfig.library.json", getCompilerSettings({}, /*useBuiltCompiler*/ true));
const {js, dts}: { js: NodeJS.ReadableStream, dts: NodeJS.ReadableStream } = serverLibraryProject.src()
.pipe(sourcemaps.init())
@@ -479,7 +483,7 @@ gulp.task(tsserverLibraryFile, false, [servicesFile], (done) => {
js.pipe(prependCopyright())
.pipe(sourcemaps.write("."))
.pipe(gulp.dest("src/server")),
dts.pipe(prependCopyright(/*outputCopyright*/true))
dts.pipe(prependCopyright(/*outputCopyright*/ true))
.pipe(insert.transform((content) => {
return content + "\r\nexport = ts;\r\nexport as namespace ts;";
}))
@@ -497,7 +501,7 @@ const word2mdTs = path.join(scriptsDirectory, "word2md.ts");
const specWord = path.join(docDirectory, "TypeScript Language Specification.docx");
const specMd = path.join(docDirectory, "spec.md");
gulp.task(word2mdJs, false, [], () => {
gulp.task(word2mdJs, /*help*/ false, [], () => {
const settings: tsc.Settings = getCompilerSettings({
outFile: word2mdJs
}, /*useBuiltCompiler*/ false);
@@ -509,7 +513,7 @@ gulp.task(word2mdJs, false, [], () => {
.pipe(gulp.dest("."));
});
gulp.task(specMd, false, [word2mdJs], (done) => {
gulp.task(specMd, /*help*/ false, [word2mdJs], (done) => {
const specWordFullPath = path.resolve(specWord);
const specMDFullPath = path.resolve(specMd);
const cmd = "cscript //nologo " + word2mdJs + " \"" + specWordFullPath + "\" " + "\"" + specMDFullPath + "\"";
@@ -525,10 +529,10 @@ gulp.task("clean", "Cleans the compiler output, declare files, and tests", [], (
return del([builtDirectory]);
});
gulp.task("useDebugMode", false, [], (done) => { useDebugMode = true; done(); });
gulp.task("dontUseDebugMode", false, [], (done) => { useDebugMode = false; done(); });
gulp.task("useDebugMode", /*help*/ false, [], (done) => { useDebugMode = true; done(); });
gulp.task("dontUseDebugMode", /*help*/ false, [], (done) => { useDebugMode = false; done(); });
gulp.task("VerifyLKG", false, [], () => {
gulp.task("VerifyLKG", /*help*/ false, [], () => {
const expectedFiles = [builtLocalCompiler, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile, typingsInstallerJs, cancellationTokenJs].concat(libraryTargets);
const missingFiles = expectedFiles.filter(function(f) {
return !fs.existsSync(f);
@@ -541,7 +545,7 @@ gulp.task("VerifyLKG", false, [], () => {
return gulp.src(expectedFiles).pipe(gulp.dest(LKGDirectory));
});
gulp.task("LKGInternal", false, ["lib", "local"]);
gulp.task("LKGInternal", /*help*/ false, ["lib", "local"]);
gulp.task("LKG", "Makes a new LKG out of the built js files", ["clean", "dontUseDebugMode"], () => {
return runSequence("LKGInternal", "VerifyLKG");
@@ -550,8 +554,8 @@ gulp.task("LKG", "Makes a new LKG out of the built js files", ["clean", "dontUse
// Task to build the tests infrastructure using the built compiler
const run = path.join(builtLocalDirectory, "run.js");
gulp.task(run, false, [servicesFile], () => {
const testProject = tsc.createProject("src/harness/tsconfig.json", getCompilerSettings({}, /*useBuiltCompiler*/true));
gulp.task(run, /*help*/ false, [servicesFile], () => {
const testProject = tsc.createProject("src/harness/tsconfig.json", getCompilerSettings({}, /*useBuiltCompiler*/ true));
return testProject.src()
.pipe(newer(run))
.pipe(sourcemaps.init())
@@ -724,7 +728,7 @@ gulp.task("runtests",
const nodeServerOutFile = "tests/webTestServer.js";
const nodeServerInFile = "tests/webTestServer.ts";
gulp.task(nodeServerOutFile, false, [servicesFile], () => {
gulp.task(nodeServerOutFile, /*help*/ false, [servicesFile], () => {
const settings: tsc.Settings = getCompilerSettings({ module: "commonjs" }, /*useBuiltCompiler*/ true);
return gulp.src(nodeServerInFile)
.pipe(newer(nodeServerOutFile))
@@ -757,7 +761,7 @@ gulp.task("browserify", "Runs browserify on run.js to produce a file suitable fo
browserify(intoStream(file.contents), { debug: true })
.bundle((err, res) => {
// assumes file.contents is a Buffer
const maps = JSON.parse(convertMap.fromSource(res.toString(), /*largeSource*/true).toJSON());
const maps = JSON.parse(convertMap.fromSource(res.toString(), /*largeSource*/ true).toJSON());
delete maps.sourceRoot;
maps.sources = maps.sources.map(s => path.resolve(s === "_stream_0.js" ? "built/local/_stream_0.js" : s));
// Strip browserify's inline comments away (could probably just let sorcery do this, but then we couldn't fix the paths)
@@ -775,7 +779,7 @@ gulp.task("browserify", "Runs browserify on run.js to produce a file suitable fo
});
const finalMap = chain.apply();
file.sourceMap = finalMap;
next(undefined, file);
next(/*err*/ undefined, file);
});
}))
.pipe(sourcemaps.write(".", { includeContent: false }))
@@ -889,7 +893,7 @@ gulp.task("baseline-accept-test262", "Makes the most recent test262 test results
// Webhost
const webhostPath = "tests/webhost/webtsc.ts";
const webhostJsPath = "tests/webhost/webtsc.js";
gulp.task(webhostJsPath, false, [servicesFile], () => {
gulp.task(webhostJsPath, /*help*/ false, [servicesFile], () => {
const settings: tsc.Settings = getCompilerSettings({
outFile: webhostJsPath
}, /*useBuiltCompiler*/ true);
@@ -909,7 +913,7 @@ gulp.task("webhost", "Builds the tsc web host", [webhostJsPath], () => {
// Perf compiler
const perftscPath = "tests/perftsc.ts";
const perftscJsPath = "built/local/perftsc.js";
gulp.task(perftscJsPath, false, [servicesFile], () => {
gulp.task(perftscJsPath, /*help*/ false, [servicesFile], () => {
const settings: tsc.Settings = getCompilerSettings({
outFile: perftscJsPath
}, /*useBuiltCompiler*/ true);
@@ -927,10 +931,10 @@ gulp.task("perftsc", "Builds augmented version of the compiler for perf tests",
// Instrumented compiler
const loggedIOpath = path.join(harnessDirectory, "loggedIO.ts");
const loggedIOJsPath = path.join(builtLocalDirectory, "loggedIO.js");
gulp.task(loggedIOJsPath, false, [], (done) => {
gulp.task(loggedIOJsPath, /*help*/ false, [], (done) => {
const temp = path.join(builtLocalDirectory, "temp");
mkdirP(temp, (err) => {
if (err) { console.error(err); done(err); process.exit(1); };
if (err) { console.error(err); done(err); process.exit(1); }
exec(host, [LKGCompiler, "--types --outdir", temp, loggedIOpath], () => {
fs.renameSync(path.join(temp, "/harness/loggedIO.js"), loggedIOJsPath);
del(temp).then(() => done(), done);
@@ -940,7 +944,7 @@ gulp.task(loggedIOJsPath, false, [], (done) => {
const instrumenterPath = path.join(harnessDirectory, "instrumenter.ts");
const instrumenterJsPath = path.join(builtLocalDirectory, "instrumenter.js");
gulp.task(instrumenterJsPath, false, [servicesFile], () => {
gulp.task(instrumenterJsPath, /*help*/ false, [servicesFile], () => {
const settings: tsc.Settings = getCompilerSettings({
outFile: instrumenterJsPath
}, /*useBuiltCompiler*/ true);
@@ -1024,7 +1028,7 @@ gulp.task("lint", "Runs tslint on the compiler sources. Optional arguments are:
const fileMatcher = cmdLineOptions["files"];
const files = fileMatcher
? `src/**/${fileMatcher}`
: "Gulpfile.ts 'src/**/*.ts' --exclude src/lib/es5.d.ts --exclude 'src/lib/*.generated.d.ts'";
: "Gulpfile.ts 'scripts/tslint/*.ts' 'src/**/*.ts' --exclude src/lib/es5.d.ts --exclude 'src/lib/*.generated.d.ts'";
const cmd = `node node_modules/tslint/bin/tslint ${files} --format stylish`;
console.log("Linting: " + cmd);
child_process.execSync(cmd, { stdio: [0, 1, 2] });
+6 -3
View File
@@ -205,7 +205,10 @@ var librarySourceMap = [
// JavaScript + all host library
{ target: "lib.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(hostsLibrarySources) },
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") }
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts") },
{ target: "lib.es2016.full.d.ts", sources: ["header.d.ts", "es2016.d.ts"].concat(hostsLibrarySources, "dom.iterable.d.ts") },
{ target: "lib.es2017.full.d.ts", sources: ["header.d.ts", "es2017.d.ts"].concat(hostsLibrarySources, "dom.iterable.d.ts") },
{ target: "lib.esnext.full.d.ts", sources: ["header.d.ts", "esnext.d.ts"].concat(hostsLibrarySources, "dom.iterable.d.ts") },
].concat(es2015LibrarySourceMap, es2016LibrarySourceMap, es2017LibrarySourceMap, esnextLibrarySourceMap);
var libraryTargets = librarySourceMap.map(function (f) {
@@ -946,7 +949,7 @@ task("generate-code-coverage", ["tests", builtLocalDirectory], function () {
// Browser tests
var nodeServerOutFile = "tests/webTestServer.js";
var nodeServerInFile = "tests/webTestServer.ts";
compileFile(nodeServerOutFile, [nodeServerInFile], [builtLocalDirectory, tscFile], [], /*useBuiltCompiler:*/ true, { noOutFile: true });
compileFile(nodeServerOutFile, [nodeServerInFile], [builtLocalDirectory, tscFile], [], /*useBuiltCompiler:*/ true, { noOutFile: true, lib: "es6" });
desc("Runs browserify on run.js to produce a file suitable for running tests in the browser");
task("browserify", ["tests", builtLocalDirectory, nodeServerOutFile], function() {
@@ -1197,7 +1200,7 @@ task("lint", ["build-rules"], () => {
const fileMatcher = process.env.f || process.env.file || process.env.files;
const files = fileMatcher
? `src/**/${fileMatcher}`
: "Gulpfile.ts 'src/**/*.ts' --exclude src/lib/es5.d.ts --exclude 'src/lib/*.generated.d.ts'";
: "Gulpfile.ts 'scripts/tslint/*.ts' 'src/**/*.ts' --exclude src/lib/es5.d.ts --exclude 'src/lib/*.generated.d.ts'";
const cmd = `node node_modules/tslint/bin/tslint ${files} --format stylish`;
console.log("Linting: " + cmd);
jake.exec([cmd], { interactive: true }, () => {
+1 -1
View File
@@ -1,6 +1,6 @@
[![Build Status](https://travis-ci.org/Microsoft/TypeScript.svg?branch=master)](https://travis-ci.org/Microsoft/TypeScript)
[![npm version](https://badge.fury.io/js/typescript.svg)](https://www.npmjs.com/package/typescript)
[![Downloads](https://img.shields.io/npm/dm/TypeScript.svg)](https://www.npmjs.com/package/typescript)
[![Downloads](https://img.shields.io/npm/dm/typescript.svg)](https://www.npmjs.com/package/typescript)
# TypeScript
+78 -46
View File
@@ -2,62 +2,94 @@ import * as Lint from "tslint/lib";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING_FACTORY(name: string, currently?: string): string {
const current = currently ? ` (currently '${currently}')` : "";
return `Tag boolean argument as '${name}'${current}`;
}
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
// Cheat to get type checker
const program = ts.createProgram([sourceFile.fileName], Lint.createCompilerOptions());
const checker = program.getTypeChecker();
return this.applyWithFunction(program.getSourceFile(sourceFile.fileName), ctx => walk(ctx, checker));
return this.applyWithFunction(sourceFile, ctx => walk(ctx));
}
}
function walk(ctx: Lint.WalkContext<void>, checker: ts.TypeChecker): void {
ts.forEachChild(ctx.sourceFile, recur);
function recur(node: ts.Node): void {
function walk(ctx: Lint.WalkContext<void>): void {
const { sourceFile } = ctx;
ts.forEachChild(sourceFile, function recur(node: ts.Node): void {
if (node.kind === ts.SyntaxKind.CallExpression) {
checkCall(node as ts.CallExpression);
}
ts.forEachChild(node, recur);
}
});
function checkCall(node: ts.CallExpression): void {
if (!node.arguments || !node.arguments.some(arg => arg.kind === ts.SyntaxKind.TrueKeyword || arg.kind === ts.SyntaxKind.FalseKeyword)) {
return;
}
const targetCallSignature = checker.getResolvedSignature(node);
if (!targetCallSignature) {
return;
}
const targetParameters = targetCallSignature.getParameters();
for (let index = 0; index < targetParameters.length; index++) {
const param = targetParameters[index];
const arg = node.arguments[index];
if (!(arg && param)) {
continue;
}
const argType = checker.getContextualType(arg);
if (argType && (argType.getFlags() & ts.TypeFlags.Boolean)) {
if (arg.kind !== ts.SyntaxKind.TrueKeyword && arg.kind !== ts.SyntaxKind.FalseKeyword) {
continue;
}
let triviaContent: string | undefined;
const ranges = ts.getLeadingCommentRanges(arg.getFullText(), 0);
if (ranges && ranges.length === 1 && ranges[0].kind === ts.SyntaxKind.MultiLineCommentTrivia) {
triviaContent = arg.getFullText().slice(ranges[0].pos + 2, ranges[0].end - 2); // +/-2 to remove /**/
}
const paramName = param.getName();
if (triviaContent !== paramName && triviaContent !== paramName + ":") {
ctx.addFailureAtNode(arg, Rule.FAILURE_STRING_FACTORY(param.getName(), triviaContent));
}
if (!shouldIgnoreCalledExpression(node.expression)) {
for (const arg of node.arguments) {
checkArg(arg);
}
}
}
}
/** Skip certain function/method names whose parameter names are not informative. */
function shouldIgnoreCalledExpression(expression: ts.Expression): boolean {
if (expression.kind === ts.SyntaxKind.PropertyAccessExpression) {
const methodName = (expression as ts.PropertyAccessExpression).name.text;
if (methodName.indexOf("set") === 0) {
return true;
}
switch (methodName) {
case "apply":
case "assert":
case "call":
case "equal":
case "fail":
case "isTrue":
case "output":
case "stringify":
return true;
}
}
else if (expression.kind === ts.SyntaxKind.Identifier) {
const functionName = (expression as ts.Identifier).text;
if (functionName.indexOf("set") === 0) {
return true;
}
switch (functionName) {
case "assert":
case "contains":
case "createAnonymousType":
case "createImportSpecifier":
case "createProperty":
case "createSignature":
case "resolveName":
return true;
}
}
return false;
}
function checkArg(arg: ts.Expression): void {
if (!isTrivia(arg)) {
return;
}
const ranges = ts.getTrailingCommentRanges(sourceFile.text, arg.pos) || ts.getLeadingCommentRanges(sourceFile.text, arg.pos);
if (ranges === undefined || ranges.length !== 1 || ranges[0].kind !== ts.SyntaxKind.MultiLineCommentTrivia) {
ctx.addFailureAtNode(arg, "Tag boolean argument with parameter name");
return;
}
const range = ranges[0];
const argStart = arg.getStart(sourceFile);
if (range.end + 1 !== argStart && sourceFile.text.slice(range.end, argStart).indexOf("\n") === -1) {
ctx.addFailureAtNode(arg, "There should be 1 space between an argument and its comment.");
}
}
function isTrivia(arg: ts.Expression): boolean {
switch (arg.kind) {
case ts.SyntaxKind.TrueKeyword:
case ts.SyntaxKind.FalseKeyword:
case ts.SyntaxKind.NullKeyword:
return true;
case ts.SyntaxKind.Identifier:
return (arg as ts.Identifier).originalKeywordKind === ts.SyntaxKind.UndefinedKeyword;
default:
return false;
}
}
}
+57 -38
View File
@@ -259,7 +259,7 @@ namespace ts {
case SyntaxKind.ExportAssignment:
return (<ExportAssignment>node).isExportEquals ? "export=" : "default";
case SyntaxKind.BinaryExpression:
switch (getSpecialPropertyAssignmentKind(node)) {
switch (getSpecialPropertyAssignmentKind(node as BinaryExpression)) {
case SpecialPropertyAssignmentKind.ModuleExports:
// module.exports = ...
return "export=";
@@ -418,7 +418,7 @@ namespace ts {
return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
}
else {
return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
}
else {
@@ -447,13 +447,13 @@ namespace ts {
(symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0) |
(symbolFlags & SymbolFlags.Type ? SymbolFlags.ExportType : 0) |
(symbolFlags & SymbolFlags.Namespace ? SymbolFlags.ExportNamespace : 0);
const local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes);
const local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
node.localSymbol = local;
return local;
}
else {
return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes);
return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
}
}
@@ -703,6 +703,7 @@ namespace ts {
function isNarrowableReference(expr: Expression): boolean {
return expr.kind === SyntaxKind.Identifier ||
expr.kind === SyntaxKind.ThisKeyword ||
expr.kind === SyntaxKind.SuperKeyword ||
expr.kind === SyntaxKind.PropertyAccessExpression && isNarrowableReference((<PropertyAccessExpression>expr).expression);
}
@@ -1413,6 +1414,7 @@ namespace ts {
if (isObjectLiteralOrClassExpressionMethod(node)) {
return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals | ContainerFlags.IsFunctionLike | ContainerFlags.IsObjectLiteralOrClassExpressionMethod;
}
// falls through
case SyntaxKind.Constructor:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.MethodSignature:
@@ -1544,7 +1546,7 @@ namespace ts {
function declareSourceFileMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) {
return isExternalModule(file)
? declareModuleMember(node, symbolFlags, symbolExcludes)
: declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes);
: declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
function hasExportDeclarations(node: ModuleDeclaration | SourceFile): boolean {
@@ -1714,13 +1716,13 @@ namespace ts {
declareModuleMember(node, symbolFlags, symbolExcludes);
break;
}
// fall through.
// falls through
default:
if (!blockScopeContainer.locals) {
blockScopeContainer.locals = createMap<Symbol>();
addToContainerChain(blockScopeContainer);
}
declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes);
declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
}
}
@@ -1854,7 +1856,7 @@ namespace ts {
}
function checkStrictModeNumericLiteral(node: NumericLiteral) {
if (inStrictMode && node.isOctalLiteral) {
if (inStrictMode && node.numericLiteralFlags & NumericLiteralFlags.Octal) {
file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
}
}
@@ -1910,7 +1912,9 @@ namespace ts {
// Here the current node is "foo", which is a container, but the scope of "MyType" should
// not be inside "foo". Therefore we always bind @typedef before bind the parent node,
// and skip binding this tag later when binding all the other jsdoc tags.
bindJSDocTypedefTagIfAny(node);
if (isInJavaScriptFile(node)) {
bindJSDocTypedefTagIfAny(node);
}
// First we bind declaration nodes to a symbol if possible. We'll both create a symbol
// and then potentially add the symbol to an appropriate symbol table. Possible
@@ -2006,6 +2010,7 @@ namespace ts {
bindBlockScopedDeclaration(<Declaration>parentNode, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
break;
}
// falls through
case SyntaxKind.ThisKeyword:
if (currentFlow && (isExpression(node) || parent.kind === SyntaxKind.ShorthandPropertyAssignment)) {
node.flowNode = currentFlow;
@@ -2017,30 +2022,28 @@ namespace ts {
}
break;
case SyntaxKind.BinaryExpression:
if (isInJavaScriptFile(node)) {
const specialKind = getSpecialPropertyAssignmentKind(node);
switch (specialKind) {
case SpecialPropertyAssignmentKind.ExportsProperty:
bindExportsPropertyAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.ModuleExports:
bindModuleExportsAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.PrototypeProperty:
bindPrototypePropertyAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.ThisProperty:
bindThisPropertyAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.Property:
bindStaticPropertyAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.None:
// Nothing to do
break;
default:
Debug.fail("Unknown special property assignment kind");
}
const specialKind = getSpecialPropertyAssignmentKind(node as BinaryExpression);
switch (specialKind) {
case SpecialPropertyAssignmentKind.ExportsProperty:
bindExportsPropertyAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.ModuleExports:
bindModuleExportsAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.PrototypeProperty:
bindPrototypePropertyAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.ThisProperty:
bindThisPropertyAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.Property:
bindStaticPropertyAssignment(<BinaryExpression>node);
break;
case SpecialPropertyAssignmentKind.None:
// Nothing to do
break;
default:
Debug.fail("Unknown special property assignment kind");
}
return checkStrictModeBinaryExpression(<BinaryExpression>node);
case SyntaxKind.CatchClause:
@@ -2183,7 +2186,7 @@ namespace ts {
if (!isFunctionLike(node.parent)) {
return;
}
// Fall through
// falls through
case SyntaxKind.ModuleBlock:
return updateStrictModeStatementList((<Block | ModuleBlock>node).statements);
}
@@ -2297,7 +2300,7 @@ namespace ts {
function isNameOfExportsOrModuleExportsAliasDeclaration(node: Node) {
if (node.kind === SyntaxKind.Identifier) {
const symbol = container.locals.get((<Identifier>node).text);
const symbol = lookupSymbolForName((<Identifier>node).text);
if (symbol && symbol.valueDeclaration && symbol.valueDeclaration.kind === SyntaxKind.VariableDeclaration) {
const declaration = symbol.valueDeclaration as VariableDeclaration;
if (declaration.initializer) {
@@ -2332,7 +2335,7 @@ namespace ts {
function bindThisPropertyAssignment(node: BinaryExpression) {
Debug.assert(isInJavaScriptFile(node));
const container = getThisContainer(node, /*includeArrowFunctions*/false);
const container = getThisContainer(node, /*includeArrowFunctions*/ false);
switch (container.kind) {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
@@ -2399,8 +2402,12 @@ namespace ts {
}
}
function lookupSymbolForName(name: string) {
return (container.symbol && container.symbol.exports && container.symbol.exports.get(name)) || (container.locals && container.locals.get(name));
}
function bindPropertyAssignment(functionName: string, propertyAccessExpression: PropertyAccessExpression, isPrototypeProperty: boolean) {
let targetSymbol = container.locals.get(functionName);
let targetSymbol = lookupSymbolForName(functionName);
if (targetSymbol && isDeclarationOfFunctionOrClassExpression(targetSymbol)) {
targetSymbol = (targetSymbol.valueDeclaration as VariableDeclaration).initializer.symbol;
@@ -2422,7 +2429,7 @@ namespace ts {
function bindCallExpression(node: CallExpression) {
// We're only inspecting call expressions to detect CommonJS modules, so we can skip
// this check if we've already seen the module indicator
if (!file.commonJsModuleIndicator && isRequireCall(node, /*checkArgumentIsStringLiteral*/false)) {
if (!file.commonJsModuleIndicator && isRequireCall(node, /*checkArgumentIsStringLiteral*/ false)) {
setCommonJsModuleIndicator(node);
}
}
@@ -3329,6 +3336,18 @@ namespace ts {
transformFlags |= TransformFlags.AssertES2015;
break;
case SyntaxKind.StringLiteral:
if ((<StringLiteral>node).hasExtendedUnicodeEscape) {
transformFlags |= TransformFlags.AssertES2015;
}
break;
case SyntaxKind.NumericLiteral:
if ((<NumericLiteral>node).numericLiteralFlags & NumericLiteralFlags.BinaryOrOctalSpecifier) {
transformFlags |= TransformFlags.AssertES2015;
}
break;
case SyntaxKind.ForOfStatement:
// This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
if ((<ForOfStatement>node).awaitModifier) {
+742 -603
View File
File diff suppressed because it is too large Load Diff
+34 -24
View File
@@ -153,6 +153,12 @@ namespace ts {
category: Diagnostics.Basic_Options,
description: Diagnostics.Allow_javascript_files_to_be_compiled
},
{
name: "checkJs",
type: "boolean",
category: Diagnostics.Basic_Options,
description: Diagnostics.Report_errors_in_js_files
},
{
name: "jsx",
type: createMapFromTemplate({
@@ -854,9 +860,9 @@ namespace ts {
}
/**
* Read tsconfig.json file
* @param fileName The path to the config file
*/
* Read tsconfig.json file
* @param fileName The path to the config file
*/
export function readConfigFile(fileName: string, readFile: (path: string) => string): { config?: any; error?: Diagnostic } {
let text = "";
try {
@@ -869,10 +875,10 @@ namespace ts {
}
/**
* Parse the text of the tsconfig.json file
* @param fileName The path to the config file
* @param jsonText The text of the config file
*/
* Parse the text of the tsconfig.json file
* @param fileName The path to the config file
* @param jsonText The text of the config file
*/
export function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments = true): { config?: any; error?: Diagnostic } {
try {
const jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText;
@@ -889,7 +895,7 @@ namespace ts {
* @param fileNames array of filenames to be generated into tsconfig.json
*/
/* @internal */
export function generateTSConfig(options: CompilerOptions, fileNames: string[]): string {
export function generateTSConfig(options: CompilerOptions, fileNames: string[], newLine: string): string {
const compilerOptions = extend(options, defaultInitCompilerOptions);
const configurations: { compilerOptions: MapLike<CompilerOptionsValue>; files?: string[] } = {
compilerOptions: serializeCompilerOptions(compilerOptions)
@@ -1001,7 +1007,7 @@ namespace ts {
let seenKnownKeys = 0;
const nameColumn: string[] = [];
const descriptionColumn: string[] = [];
const knownKesyCount = getOwnKeys(configurations.compilerOptions).length;
const knownKeysCount = getOwnKeys(configurations.compilerOptions).length;
for (const category in categorizedOptions) {
if (nameColumn.length !== 0) {
nameColumn.push("");
@@ -1012,7 +1018,7 @@ namespace ts {
for (const option of categorizedOptions[category]) {
let optionName;
if (hasProperty(configurations.compilerOptions, option.name)) {
optionName = `"${option.name}": ${JSON.stringify(configurations.compilerOptions[option.name])}${(seenKnownKeys += 1) === knownKesyCount ? "" : ","}`;
optionName = `"${option.name}": ${JSON.stringify(configurations.compilerOptions[option.name])}${(seenKnownKeys += 1) === knownKeysCount ? "" : ","}`;
}
else {
optionName = `// "${option.name}": ${JSON.stringify(getDefaultValueForOption(option))},`;
@@ -1047,7 +1053,7 @@ namespace ts {
}
result.push(`}`);
return result.join(sys.newLine);
return result.join(newLine);
}
}
@@ -1077,12 +1083,12 @@ namespace ts {
}
/**
* Parse the contents of a config file (tsconfig.json).
* @param json The contents of the config file to parse
* @param host Instance of ParseConfigHost used to enumerate files in folder.
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
* Parse the contents of a config file (tsconfig.json).
* @param json The contents of the config file to parse
* @param host Instance of ParseConfigHost used to enumerate files in folder.
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: JsFileExtensionInfo[] = []): ParsedCommandLine {
const errors: Diagnostic[] = [];
basePath = normalizeSlashes(basePath);
@@ -1105,10 +1111,11 @@ namespace ts {
const jsonOptions = json["typeAcquisition"] || json["typingOptions"];
const typeAcquisition: TypeAcquisition = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
let baseCompileOnSave: boolean;
if (json["extends"]) {
let [include, exclude, files, baseOptions]: [string[], string[], string[], CompilerOptions] = [undefined, undefined, undefined, {}];
if (typeof json["extends"] === "string") {
[include, exclude, files, baseOptions] = (tryExtendsName(json["extends"]) || [include, exclude, files, baseOptions]);
[include, exclude, files, baseCompileOnSave, baseOptions] = (tryExtendsName(json["extends"]) || [include, exclude, files, baseCompileOnSave, baseOptions]);
}
else {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
@@ -1129,7 +1136,10 @@ namespace ts {
options.configFilePath = configFileName;
const { fileNames, wildcardDirectories } = getFileNames(errors);
const compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
let compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
if (baseCompileOnSave && json[compileOnSaveCommandLineOption.name] === undefined) {
compileOnSave = baseCompileOnSave;
}
return {
options,
@@ -1141,7 +1151,7 @@ namespace ts {
compileOnSave
};
function tryExtendsName(extendedConfig: string): [string[], string[], string[], CompilerOptions] {
function tryExtendsName(extendedConfig: string): [string[], string[], string[], boolean, CompilerOptions] {
// If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future)
if (!(isRootedDiskPath(extendedConfig) || startsWith(normalizeSlashes(extendedConfig), "./") || startsWith(normalizeSlashes(extendedConfig), "../"))) {
errors.push(createCompilerDiagnostic(Diagnostics.A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not, extendedConfig));
@@ -1164,14 +1174,14 @@ namespace ts {
const relativeDifference = convertToRelativePath(extendedDirname, basePath, getCanonicalFileName);
const updatePath: (path: string) => string = path => isRootedDiskPath(path) ? path : combinePaths(relativeDifference, path);
// Merge configs (copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios)
const result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, /*existingOptions*/undefined, getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath]));
const result = parseJsonConfigFileContent(extendedResult.config, host, extendedDirname, /*existingOptions*/ undefined, getBaseFileName(extendedConfigPath), resolutionStack.concat([resolvedPath]));
errors.push(...result.errors);
const [include, exclude, files] = map(["include", "exclude", "files"], key => {
if (!json[key] && extendedResult.config[key]) {
return map(extendedResult.config[key], updatePath);
}
});
return [include, exclude, files, result.options];
return [include, exclude, files, result.compileOnSave, result.options];
}
function getFileNames(errors: Diagnostic[]): ExpandResult {
@@ -1239,7 +1249,7 @@ namespace ts {
}
}
export function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean {
export function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean | undefined {
if (!hasProperty(jsonOption, compileOnSaveCommandLineOption.name)) {
return false;
}
@@ -1574,7 +1584,7 @@ namespace ts {
delete wildcardDirectories[key];
}
}
};
}
}
return wildcardDirectories;
+1 -1
View File
@@ -411,7 +411,7 @@ namespace ts {
* Determine if the given comment is a triple-slash
*
* @return true if the comment is a triple-slash comment else false
**/
*/
function isTripleSlashComment(commentPos: number, commentEnd: number) {
// Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
// so that we don't end up computing comment string and doing match for all // comments
+32 -7
View File
@@ -30,7 +30,7 @@ namespace ts {
/** Create a MapLike with good performance. */
function createDictionaryObject<T>(): MapLike<T> {
const map = Object.create(null); // tslint:disable-line:no-null-keyword
const map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword
// Using 'delete' on an object causes V8 to put the object in dictionary mode.
// This disables creation of hidden classes, which are expensive when an object is
@@ -224,6 +224,25 @@ namespace ts {
}
return undefined;
}
/**
* Iterates through the parent chain of a node and performs the callback on each parent until the callback
* returns a truthy value, then returns that value.
* If no such value is found, it applies the callback until the parent pointer is undefined or the callback returns "quit"
* At that point findAncestor returns undefined.
*/
export function findAncestor(node: Node, callback: (element: Node) => boolean | "quit"): Node {
while (node) {
const result = callback(node);
if (result === "quit") {
return undefined;
}
else if (result) {
return node;
}
node = node.parent;
}
return undefined;
}
export function zipWith<T, U>(arrayA: T[], arrayB: U[], callback: (a: T, b: U, index: number) => void): void {
Debug.assert(arrayA.length === arrayB.length);
@@ -887,10 +906,12 @@ namespace ts {
}
/** Shims `Array.from`. */
export function arrayFrom<T>(iterator: Iterator<T>): T[] {
const result: T[] = [];
export function arrayFrom<T, U>(iterator: Iterator<T>, map: (t: T) => U): U[];
export function arrayFrom<T>(iterator: Iterator<T>): T[];
export function arrayFrom(iterator: Iterator<any>, map?: (t: any) => any): any[] {
const result: any[] = [];
for (let { value, done } = iterator.next(); !done; { value, done } = iterator.next()) {
result.push(value);
result.push(map ? map(value) : value);
}
return result;
}
@@ -943,7 +964,7 @@ namespace ts {
export function assign<T1 extends MapLike<{}>>(t: T1, ...args: any[]): any;
export function assign<T1 extends MapLike<{}>>(t: T1, ...args: any[]) {
for (const arg of args) {
for (const p of getOwnKeys(arg)) {
for (const p in arg) if (hasProperty(arg, p)) {
t[p] = arg[p];
}
}
@@ -1358,7 +1379,7 @@ namespace ts {
/**
* Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files")
*/
*/
export function getRootLength(path: string): number {
if (path.charCodeAt(0) === CharacterCodes.slash) {
if (path.charCodeAt(1) !== CharacterCodes.slash) return 1;
@@ -1455,7 +1476,7 @@ namespace ts {
return /^\.\.?($|[\\/])/.test(moduleName);
}
export function getEmitScriptTarget(compilerOptions: CompilerOptions | PrinterOptions) {
export function getEmitScriptTarget(compilerOptions: CompilerOptions) {
return compilerOptions.target || ScriptTarget.ES3;
}
@@ -2360,4 +2381,8 @@ namespace ts {
return Extension.Jsx;
}
}
export function isCheckJsEnabledForFile(sourceFile: SourceFile, compilerOptions: CompilerOptions) {
return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
}
}
+1 -1
View File
@@ -590,7 +590,7 @@ namespace ts {
currentIdentifiers = node.identifiers;
isCurrentFileExternalModule = isExternalModule(node);
enclosingDeclaration = node;
emitDetachedComments(currentText, currentLineMap, writer, writeCommentRange, node, newLine, true /* remove comments */);
emitDetachedComments(currentText, currentLineMap, writer, writeCommentRange, node, newLine, /*removeComents*/ true);
emitLines(node.statements);
}
+51 -1
View File
@@ -175,7 +175,7 @@
"category": "Error",
"code": 1057
},
"Type used as operand to 'await' or the return type of an async function must either be a valid promise or must not contain a callable 'then' member.": {
"The return type of an async function must either be a valid promise or must not contain a callable 'then' member.": {
"category": "Error",
"code": 1058
},
@@ -867,6 +867,18 @@
"category": "Error",
"code": 1319
},
"Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member.": {
"category": "Error",
"code": 1320
},
"Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member.": {
"category": "Error",
"code": 1321
},
"Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member.": {
"category": "Error",
"code": 1322
},
"Duplicate identifier '{0}'.": {
"category": "Error",
"code": 2300
@@ -1827,6 +1839,10 @@
"category": "Error",
"code": 2549
},
"Generic type instantiation is excessively deep and possibly infinite.": {
"category": "Error",
"code": 2550
},
"JSX element attributes type '{0}' may not be a union type.": {
"category": "Error",
"code": 2600
@@ -2095,6 +2111,14 @@
"category": "Error",
"code": 2707
},
"Cannot use namespace '{0}' as a value.": {
"category": "Error",
"code": 2708
},
"Cannot use namespace '{0}' as a type.": {
"category": "Error",
"code": 2709
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
@@ -3173,6 +3197,10 @@
"category": "Message",
"code": 6181
},
"Scoped package detected, looking in '{0}'": {
"category": "Message",
"code": "6182"
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
@@ -3480,6 +3508,24 @@
"category": "Message",
"code": 90017
},
"Disable checking for this file.": {
"category": "Message",
"code": 90018
},
"Ignore this error message.": {
"category": "Message",
"code": 90019
},
"Initialize property '{0}' in the constructor.": {
"category": "Message",
"code": 90020
},
"Initialize static property '{0}'.": {
"category": "Message",
"code": 90021
},
"Octal literal types must use ES2015 syntax. Use the syntax '{0}'.": {
"category": "Error",
"code": 8017
@@ -3487,5 +3533,9 @@
"Octal literals are not allowed in enums members initializer. Use the syntax '{0}'.": {
"category": "Error",
"code": 8018
},
"Report errors in .js files.": {
"category": "Message",
"code": 8019
}
}
+75 -33
View File
@@ -204,7 +204,6 @@ namespace ts {
} = handlers;
const newLine = getNewLineCharacter(printerOptions);
const languageVersion = getEmitScriptTarget(printerOptions);
const comments = createCommentWriter(printerOptions, onEmitSourceMapOfPosition);
const {
emitNodeWithComments,
@@ -276,6 +275,8 @@ namespace ts {
function writeBundle(bundle: Bundle, output: EmitTextWriter) {
const previousWriter = writer;
setWriter(output);
emitShebangIfNeeded(bundle);
emitPrologueDirectivesIfNeeded(bundle);
emitHelpersIndirect(bundle);
for (const sourceFile of bundle.sourceFiles) {
print(EmitHint.SourceFile, sourceFile, sourceFile);
@@ -287,6 +288,8 @@ namespace ts {
function writeFile(sourceFile: SourceFile, output: EmitTextWriter) {
const previousWriter = writer;
setWriter(output);
emitShebangIfNeeded(sourceFile);
emitPrologueDirectivesIfNeeded(sourceFile);
print(EmitHint.SourceFile, sourceFile, sourceFile);
reset();
writer = previousWriter;
@@ -739,15 +742,6 @@ namespace ts {
return node && substituteNode && substituteNode(hint, node) || node;
}
function emitBodyIndirect(node: Node, elements: NodeArray<Node>, emitCallback: (node: Node) => void): void {
if (emitBodyWithDetachedComments) {
emitBodyWithDetachedComments(node, elements, emitCallback);
}
else {
emitCallback(node);
}
}
function emitHelpersIndirect(node: Node) {
if (onEmitHelpers) {
onEmitHelpers(node, writeLines);
@@ -1091,7 +1085,7 @@ namespace ts {
}
const preferNewLine = node.multiLine ? ListFormat.PreferNewLine : ListFormat.None;
const allowTrailingComma = languageVersion >= ScriptTarget.ES5 ? ListFormat.AllowTrailingComma : ListFormat.None;
const allowTrailingComma = currentSourceFile.languageVersion >= ScriptTarget.ES5 ? ListFormat.AllowTrailingComma : ListFormat.None;
emitList(node, properties, ListFormat.ObjectLiteralExpressionProperties | allowTrailingComma | preferNewLine);
if (indentedFlag) {
@@ -1125,11 +1119,11 @@ namespace ts {
// 1..toString is a valid property access, emit a dot after the literal
// Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
function needsDotDotForPropertyAccess(expression: Expression) {
if (expression.kind === SyntaxKind.NumericLiteral) {
expression = skipPartiallyEmittedExpressions(expression);
if (isNumericLiteral(expression)) {
// check if numeric literal is a decimal literal that was originally written with a dot
const text = getLiteralTextOfNode(<LiteralExpression>expression);
return getNumericLiteralFlags(text, /*hint*/ NumericLiteralFlags.All) === NumericLiteralFlags.None
&& !(<LiteralExpression>expression).isOctalLiteral
return !expression.numericLiteralFlags
&& text.indexOf(tokenToString(SyntaxKind.DotToken)) < 0;
}
else if (isPropertyAccessExpression(expression) || isElementAccessExpression(expression)) {
@@ -1665,7 +1659,12 @@ namespace ts {
? emitBlockFunctionBodyOnSingleLine
: emitBlockFunctionBodyWorker;
emitBodyIndirect(body, body.statements, emitBlockFunctionBody);
if (emitBodyWithDetachedComments) {
emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody);
}
else {
emitBlockFunctionBody(body);
}
decreaseIndent();
writeToken(SyntaxKind.CloseBraceToken, body.statements.end, body);
@@ -2074,16 +2073,27 @@ namespace ts {
function emitSourceFile(node: SourceFile) {
writeLine();
emitShebang();
emitBodyIndirect(node, node.statements, emitSourceFileWorker);
const statements = node.statements;
if (emitBodyWithDetachedComments) {
// Emit detached comment if there are no prologue directives or if the first node is synthesized.
// The synthesized node will have no leading comment so some comments may be missed.
const shouldEmitDetachedComment = statements.length === 0 ||
!isPrologueDirective(statements[0]) ||
nodeIsSynthesized(statements[0]);
if (shouldEmitDetachedComment) {
emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
return;
}
}
emitSourceFileWorker(node);
}
function emitSourceFileWorker(node: SourceFile) {
const statements = node.statements;
const statementOffset = emitPrologueDirectives(statements);
pushNameGenerationScope();
emitHelpersIndirect(node);
emitList(node, statements, ListFormat.MultiLine, statementOffset);
const index = findIndex(statements, statement => !isPrologueDirective(statement));
emitList(node, statements, ListFormat.MultiLine, index === -1 ? statements.length : index);
popNameGenerationScope();
}
@@ -2097,13 +2107,20 @@ namespace ts {
* Emits any prologue directives at the start of a Statement list, returning the
* number of prologue directives written to the output.
*/
function emitPrologueDirectives(statements: Node[], startWithNewLine?: boolean): number {
function emitPrologueDirectives(statements: Node[], startWithNewLine?: boolean, seenPrologueDirectives?: Map<String>): number {
for (let i = 0; i < statements.length; i++) {
if (isPrologueDirective(statements[i])) {
if (startWithNewLine || i > 0) {
writeLine();
const statement = statements[i];
if (isPrologueDirective(statement)) {
const shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
if (shouldEmitPrologueDirective) {
if (startWithNewLine || i > 0) {
writeLine();
}
emit(statement);
if (seenPrologueDirectives) {
seenPrologueDirectives.set(statement.expression.text, statement.expression.text);
}
}
emit(statements[i]);
}
else {
// return index of the first non prologue directive
@@ -2114,18 +2131,43 @@ namespace ts {
return statements.length;
}
function emitPrologueDirectivesIfNeeded(sourceFileOrBundle: Bundle | SourceFile) {
if (isSourceFile(sourceFileOrBundle)) {
setSourceFile(sourceFileOrBundle as SourceFile);
emitPrologueDirectives((sourceFileOrBundle as SourceFile).statements);
}
else {
const seenPrologueDirectives = createMap<String>();
for (const sourceFile of (sourceFileOrBundle as Bundle).sourceFiles) {
setSourceFile(sourceFile);
emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives);
}
}
}
function emitShebangIfNeeded(sourceFileOrBundle: Bundle | SourceFile) {
if (isSourceFile(sourceFileOrBundle)) {
const shebang = getShebang(sourceFileOrBundle.text);
if (shebang) {
write(shebang);
writeLine();
return true;
}
}
else {
for (const sourceFile of sourceFileOrBundle.sourceFiles) {
// Emit only the first encountered shebang
if (emitShebangIfNeeded(sourceFile)) {
break;
}
}
}
}
//
// Helpers
//
function emitShebang() {
const shebang = getShebang(currentSourceFile.text);
if (shebang) {
write(shebang);
writeLine();
}
}
function emitModifiers(node: Node, modifiers: NodeArray<Modifier>) {
if (modifiers && modifiers.length) {
emitList(node, modifiers, ListFormat.Modifiers);
@@ -2597,7 +2639,7 @@ namespace ts {
}
}
return getLiteralText(node, currentSourceFile, languageVersion);
return getLiteralText(node, currentSourceFile);
}
/**
+28 -9
View File
@@ -113,6 +113,7 @@ namespace ts {
export function createNumericLiteral(value: string): NumericLiteral {
const node = <NumericLiteral>createSynthesizedNode(SyntaxKind.NumericLiteral);
node.text = value;
node.numericLiteralFlags = 0;
return node;
}
@@ -3084,7 +3085,18 @@ namespace ts {
* @param ensureUseStrict: boolean determining whether the function need to add prologue-directives
* @param visitor: Optional callback used to visit any custom prologue directives.
*/
export function addPrologueDirectives(target: Statement[], source: Statement[], ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult<Node>): number {
export function addPrologue(target: Statement[], source: Statement[], ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult<Node>): number {
const offset = addStandardPrologue(target, source, ensureUseStrict);
return addCustomPrologue(target, source, offset, visitor);
}
/**
* Add just the standard (string-expression) prologue-directives into target statement-array.
* The function needs to be called during each transformation step.
* This function needs to be called whenever we transform the statement
* list of a source file, namespace, or function-like body.
*/
export function addStandardPrologue(target: Statement[], source: Statement[], ensureUseStrict?: boolean): number {
Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
let foundUseStrict = false;
let statementOffset = 0;
@@ -3092,7 +3104,7 @@ namespace ts {
while (statementOffset < numStatements) {
const statement = source[statementOffset];
if (isPrologueDirective(statement)) {
if (isUseStrictPrologue(statement as ExpressionStatement)) {
if (isUseStrictPrologue(statement)) {
foundUseStrict = true;
}
target.push(statement);
@@ -3105,6 +3117,17 @@ namespace ts {
if (ensureUseStrict && !foundUseStrict) {
target.push(startOnNewLine(createStatement(createLiteral("use strict"))));
}
return statementOffset;
}
/**
* Add just the custom prologue-directives into target statement-array.
* The function needs to be called during each transformation step.
* This function needs to be called whenever we transform the statement
* list of a source file, namespace, or function-like body.
*/
export function addCustomPrologue(target: Statement[], source: Statement[], statementOffset: number, visitor?: (node: Node) => VisitResult<Node>): number {
const numStatements = source.length;
while (statementOffset < numStatements) {
const statement = source[statementOffset];
if (getEmitFlags(statement) & EmitFlags.CustomPrologue) {
@@ -3392,17 +3415,14 @@ namespace ts {
*/
export function parenthesizeForAccess(expression: Expression): LeftHandSideExpression {
// isLeftHandSideExpression is almost the correct criterion for when it is not necessary
// to parenthesize the expression before a dot. The known exceptions are:
// to parenthesize the expression before a dot. The known exception is:
//
// NewExpression:
// new C.x -> not the same as (new C).x
// NumericLiteral
// 1.x -> not the same as (1).x
//
const emittedExpression = skipPartiallyEmittedExpressions(expression);
if (isLeftHandSideExpression(emittedExpression)
&& (emittedExpression.kind !== SyntaxKind.NewExpression || (<NewExpression>emittedExpression).arguments)
&& emittedExpression.kind !== SyntaxKind.NumericLiteral) {
&& (emittedExpression.kind !== SyntaxKind.NewExpression || (<NewExpression>emittedExpression).arguments)) {
return <LeftHandSideExpression>expression;
}
@@ -3518,8 +3538,7 @@ namespace ts {
}
export function parenthesizeConciseBody(body: ConciseBody): ConciseBody {
const emittedBody = skipPartiallyEmittedExpressions(body);
if (emittedBody.kind === SyntaxKind.ObjectLiteralExpression) {
if (!isBlock(body) && getLeftmostExpression(body).kind === SyntaxKind.ObjectLiteralExpression) {
return setTextRange(createParen(<Expression>body), body);
}
+27 -12
View File
@@ -249,13 +249,13 @@ namespace ts {
}
/**
* Given a set of options, returns the set of type directive names
* that should be included for this program automatically.
* This list could either come from the config file,
* or from enumerating the types root + initial secondary types lookup location.
* More type directives might appear in the program later as a result of loading actual source files;
* this list is only the set of defaults that are implicitly included.
*/
* Given a set of options, returns the set of type directive names
* that should be included for this program automatically.
* This list could either come from the config file,
* or from enumerating the types root + initial secondary types lookup location.
* More type directives might appear in the program later as a result of loading actual source files;
* this list is only the set of defaults that are implicitly included.
*/
export function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[] {
// Use explicit type list from tsconfig.json
if (options.types) {
@@ -378,7 +378,7 @@ namespace ts {
directoryPathMap.set(parent, result);
current = parent;
if (current == commonPrefix) {
if (current === commonPrefix) {
break;
}
}
@@ -656,7 +656,7 @@ namespace ts {
// A path mapping may have a ".ts" extension; in contrast to an import, which should omit it.
const tsExtension = tryGetExtensionFromPath(candidate);
if (tsExtension !== undefined) {
const path = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/false, state);
const path = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state);
return path && { path, extension: tsExtension };
}
@@ -694,7 +694,7 @@ namespace ts {
return { resolvedModule: undefined, failedLookupLocations };
function tryResolve(extensions: Extensions): SearchResult<{ resolved: Resolved, isExternalLibraryImport: boolean }> {
const loader: ResolutionKindSpecificLoader = (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) => nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/true);
const loader: ResolutionKindSpecificLoader = (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) => nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true);
const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state);
if (resolved) {
return toSearchResult({ resolved, isExternalLibraryImport: false });
@@ -710,7 +710,7 @@ namespace ts {
}
else {
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
const resolved = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/true);
const resolved = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
return resolved && toSearchResult({ resolved, isExternalLibraryImport: false });
}
}
@@ -954,10 +954,25 @@ namespace ts {
}
nodeModulesAtTypesExists = false;
}
return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, moduleName, nodeModulesAtTypes, nodeModulesAtTypesExists, failedLookupLocations, state);
return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes, nodeModulesAtTypesExists, failedLookupLocations, state);
}
}
/** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
function mangleScopedPackage(moduleName: string, state: ModuleResolutionState): string {
if (startsWith(moduleName, "@")) {
const replaceSlash = moduleName.replace(ts.directorySeparator, "__");
if (replaceSlash !== moduleName) {
const mangled = replaceSlash.slice(1); // Take off the "@"
if (state.traceEnabled) {
trace(state.host, Diagnostics.Scoped_package_detected_looking_in_0, mangled);
}
return mangled;
}
}
return moduleName;
}
function tryFindNonRelativeModuleNameInCache(cache: PerModuleNameCache | undefined, moduleName: string, containingDirectory: string, traceEnabled: boolean, host: ModuleResolutionHost): SearchResult<Resolved> {
const result = cache && cache.get(containingDirectory);
if (result) {
+39 -22
View File
@@ -57,7 +57,7 @@ namespace ts {
// The visitXXX functions could be written as local functions that close over the cbNode and cbNodeArray
// callback parameters, but that causes a closure allocation for each invocation with noticeable effects
// on performance.
const visitNodes: (cb: (node: Node | Node[]) => T, nodes: Node[]) => T = cbNodeArray ? visitNodeArray : visitEachNode;
const visitNodes: (cb: ((node: Node) => T) | ((node: Node[]) => T), nodes: Node[]) => T = cbNodeArray ? visitNodeArray : visitEachNode;
const cbNodes = cbNodeArray || cbNode;
switch (node.kind) {
case SyntaxKind.QualifiedName:
@@ -458,6 +458,7 @@ namespace ts {
return Parser.parseIsolatedEntityName(text, languageVersion);
}
// See also `isExternalOrCommonJsModule` in utilities.ts
export function isExternalModule(file: SourceFile): boolean {
return file.externalModuleIndicator !== undefined;
}
@@ -1267,6 +1268,7 @@ namespace ts {
function nextTokenIsClassOrFunctionOrAsync(): boolean {
nextToken();
return token() === SyntaxKind.ClassKeyword || token() === SyntaxKind.FunctionKeyword ||
(token() === SyntaxKind.AbstractKeyword && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
(token() === SyntaxKind.AsyncKeyword && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
}
@@ -1844,7 +1846,7 @@ namespace ts {
case ParsingContext.JSDocTupleTypes: return Diagnostics.Type_expected;
case ParsingContext.JSDocRecordMembers: return Diagnostics.Property_assignment_expected;
}
};
}
// Parses a comma-delimited list of elements
function parseDelimitedList<T extends Node>(kind: ParsingContext, parseElement: () => T, considerSemicolonAsDelimiter?: boolean): NodeArray<T> {
@@ -2030,32 +2032,27 @@ namespace ts {
node.isUnterminated = true;
}
const tokenPos = scanner.getTokenPos();
nextToken();
finishNode(node);
// Octal literals are not allowed in strict mode or ES5
// Note that theoretically the following condition would hold true literals like 009,
// which is not octal.But because of how the scanner separates the tokens, we would
// never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
// We also do not need to check for negatives because any prefix operator would be part of a
// parent unary expression.
if (node.kind === SyntaxKind.NumericLiteral
&& sourceText.charCodeAt(tokenPos) === CharacterCodes._0
&& isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) {
node.isOctalLiteral = true;
if (node.kind === SyntaxKind.NumericLiteral) {
(<NumericLiteral>node).numericLiteralFlags = scanner.getNumericLiteralFlags();
}
nextToken();
finishNode(node);
return node;
}
// TYPES
function parseTypeReference(): TypeReferenceNode {
const typeName = parseEntityName(/*allowReservedWords*/ false, Diagnostics.Type_expected);
const node = <TypeReferenceNode>createNode(SyntaxKind.TypeReference, typeName.pos);
node.typeName = typeName;
const node = <TypeReferenceNode>createNode(SyntaxKind.TypeReference);
node.typeName = parseEntityName(/*allowReservedWords*/ false, Diagnostics.Type_expected);
if (!scanner.hasPrecedingLineBreak() && token() === SyntaxKind.LessThanToken) {
node.typeArguments = parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken);
}
@@ -2134,7 +2131,7 @@ namespace ts {
function parseParameter(): ParameterDeclaration {
const node = <ParameterDeclaration>createNode(SyntaxKind.Parameter);
if (token() === SyntaxKind.ThisKeyword) {
node.name = createIdentifier(/*isIdentifier*/true, undefined);
node.name = createIdentifier(/*isIdentifier*/ true);
node.type = parseParameterType();
return finishNode(node);
}
@@ -3043,7 +3040,7 @@ namespace ts {
// If we have an arrow, then try to parse the body. Even if not, try to parse if we
// have an opening brace, just in case we're in an error state.
const lastToken = token();
arrowFunction.equalsGreaterThanToken = parseExpectedToken(SyntaxKind.EqualsGreaterThanToken, /*reportAtCurrentPosition*/false, Diagnostics._0_expected, "=>");
arrowFunction.equalsGreaterThanToken = parseExpectedToken(SyntaxKind.EqualsGreaterThanToken, /*reportAtCurrentPosition*/ false, Diagnostics._0_expected, "=>");
arrowFunction.body = (lastToken === SyntaxKind.EqualsGreaterThanToken || lastToken === SyntaxKind.OpenBraceToken)
? parseArrowFunctionExpressionBody(isAsync)
: parseIdentifier();
@@ -3576,6 +3573,7 @@ namespace ts {
if (isAwaitExpression()) {
return parseAwaitExpression();
}
// falls through
default:
return parseIncrementExpression();
}
@@ -3609,8 +3607,8 @@ namespace ts {
if (sourceFile.languageVariant !== LanguageVariant.JSX) {
return false;
}
// We are in JSX context and the token is part of JSXElement.
// Fall through
// We are in JSX context and the token is part of JSXElement.
// falls through
default:
return true;
}
@@ -3812,7 +3810,7 @@ namespace ts {
// Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
// of one sort or another.
if (inExpressionContext && token() === SyntaxKind.LessThanToken) {
const invalidElement = tryParse(() => parseJsxElementOrSelfClosingElement(/*inExpressionContext*/true));
const invalidElement = tryParse(() => parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true));
if (invalidElement) {
parseErrorAtCurrentToken(Diagnostics.JSX_expressions_must_have_one_parent_element);
const badNode = <BinaryExpression>createNode(SyntaxKind.BinaryExpression, result.pos);
@@ -4661,6 +4659,11 @@ namespace ts {
return tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
}
function nextTokenIsClassKeywordOnSameLine() {
nextToken();
return token() === SyntaxKind.ClassKeyword && !scanner.hasPrecedingLineBreak();
}
function nextTokenIsFunctionKeywordOnSameLine() {
nextToken();
return token() === SyntaxKind.FunctionKeyword && !scanner.hasPrecedingLineBreak();
@@ -5817,11 +5820,12 @@ namespace ts {
}
function processReferenceComments(sourceFile: SourceFile): void {
const triviaScanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/false, LanguageVariant.Standard, sourceText);
const triviaScanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/ false, LanguageVariant.Standard, sourceText);
const referencedFiles: FileReference[] = [];
const typeReferenceDirectives: FileReference[] = [];
const amdDependencies: { path: string; name: string }[] = [];
let amdModuleName: string;
let checkJsDirective: CheckJsDirective = undefined;
// Keep scanning all the leading trivia in the file until we get to something that
// isn't trivia. Any single line comment will be analyzed to see if it is a
@@ -5883,6 +5887,16 @@ namespace ts {
amdDependencies.push(amdDependency);
}
}
const checkJsDirectiveRegEx = /^\/\/\/?\s*(@ts-check|@ts-nocheck)\s*$/gim;
const checkJsDirectiveMatchResult = checkJsDirectiveRegEx.exec(comment);
if (checkJsDirectiveMatchResult) {
checkJsDirective = {
enabled: compareStrings(checkJsDirectiveMatchResult[1], "@ts-check", /*ignoreCase*/ true) === Comparison.EqualTo,
end: range.end,
pos: range.pos
};
}
}
}
@@ -5890,6 +5904,7 @@ namespace ts {
sourceFile.typeReferenceDirectives = typeReferenceDirectives;
sourceFile.amdDependencies = amdDependencies;
sourceFile.moduleName = amdModuleName;
sourceFile.checkJsDirective = checkJsDirective;
}
function setExternalModuleIndicator(sourceFile: SourceFile) {
@@ -6516,7 +6531,7 @@ namespace ts {
function parseTagComments(indent: number) {
const comments: string[] = [];
let state = JSDocState.SawAsterisk;
let state = JSDocState.BeginningOfLine;
let margin: number | undefined;
function pushComment(text: string) {
if (!margin) {
@@ -6557,7 +6572,8 @@ namespace ts {
indent += scanner.getTokenText().length;
break;
}
// FALLTHROUGH otherwise to record the * as a comment
// record the * as a comment
// falls through
default:
state = JSDocState.SavingComments; // leading identifiers start recording as well
pushComment(scanner.getTokenText());
@@ -6783,6 +6799,7 @@ namespace ts {
break;
case SyntaxKind.Identifier:
canParseTag = false;
break;
case SyntaxKind.EndOfFileToken:
break;
}
+45 -13
View File
@@ -4,6 +4,7 @@
namespace ts {
const emptyArray: any[] = [];
const ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/;
export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName = "tsconfig.json"): string {
while (true) {
@@ -556,7 +557,7 @@ namespace ts {
// combine results of resolutions and predicted results
let j = 0;
for (let i = 0; i < result.length; i++) {
if (result[i] == predictedToResolveToAmbientModuleMarker) {
if (result[i] === predictedToResolveToAmbientModuleMarker) {
result[i] = undefined;
}
else {
@@ -911,17 +912,44 @@ namespace ts {
Debug.assert(!!sourceFile.bindDiagnostics);
const bindDiagnostics = sourceFile.bindDiagnostics;
// For JavaScript files, we don't want to report semantic errors.
// Instead, we'll report errors for using TypeScript-only constructs from within a
// JavaScript file when we get syntactic diagnostics for the file.
const checkDiagnostics = isSourceFileJavaScript(sourceFile) ? [] : typeChecker.getDiagnostics(sourceFile, cancellationToken);
// For JavaScript files, we don't want to report semantic errors unless explicitly requested.
const includeCheckDiagnostics = !isSourceFileJavaScript(sourceFile) || isCheckJsEnabledForFile(sourceFile, options);
const checkDiagnostics = includeCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : [];
const fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
return bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
const diagnostics = bindDiagnostics.concat(checkDiagnostics, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
return isSourceFileJavaScript(sourceFile)
? filter(diagnostics, shouldReportDiagnostic)
: diagnostics;
});
}
/**
* Skip errors if previous line start with '// @ts-ignore' comment, not counting non-empty non-comment lines
*/
function shouldReportDiagnostic(diagnostic: Diagnostic) {
const { file, start } = diagnostic;
if (file) {
const lineStarts = getLineStarts(file);
let { line } = computeLineAndCharacterOfPosition(lineStarts, start);
while (line > 0) {
const previousLineText = file.text.slice(lineStarts[line - 1], lineStarts[line]);
const result = ignoreDiagnosticCommentRegEx.exec(previousLineText);
if (!result) {
// non-empty line
return true;
}
if (result[3]) {
// @ts-ignore
return false;
}
line--;
}
}
return true;
}
function getJavaScriptSyntacticDiagnosticsForFile(sourceFile: SourceFile): Diagnostic[] {
return runWithCancellationToken(() => {
const diagnostics: Diagnostic[] = [];
@@ -941,8 +969,7 @@ namespace ts {
diagnostics.push(createDiagnosticForNode(node, Diagnostics._0_can_only_be_used_in_a_ts_file, "?"));
return;
}
// Pass through
// falls through
case SyntaxKind.MethodDeclaration:
case SyntaxKind.MethodSignature:
case SyntaxKind.Constructor:
@@ -1022,7 +1049,7 @@ namespace ts {
diagnostics.push(createDiagnosticForNodeArray(nodes, Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file));
return;
}
// pass through
// falls through
case SyntaxKind.VariableStatement:
// Check modifiers
if (nodes === (<ClassDeclaration | FunctionLikeDeclaration | VariableStatement>parent).modifiers) {
@@ -1070,7 +1097,8 @@ namespace ts {
if (isConstValid) {
continue;
}
// Fallthrough to report error
// to report error,
// falls through
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
@@ -1192,7 +1220,7 @@ namespace ts {
&& !file.isDeclarationFile) {
// synthesize 'import "tslib"' declaration
const externalHelpersModuleReference = createLiteral(externalHelpersModuleNameText);
const importDecl = createImportDeclaration(undefined, undefined, undefined);
const importDecl = createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined);
externalHelpersModuleReference.parent = importDecl;
importDecl.parent = file;
imports = [externalHelpersModuleReference];
@@ -1265,7 +1293,7 @@ namespace ts {
}
function collectRequireCalls(node: Node): void {
if (isRequireCall(node, /*checkArgumentIsStringLiteral*/true)) {
if (isRequireCall(node, /*checkArgumentIsStringLiteral*/ true)) {
(imports || (imports = [])).push(<StringLiteral>(<CallExpression>node).arguments[0]);
}
else {
@@ -1338,7 +1366,7 @@ namespace ts {
// If the file was previously found via a node_modules search, but is now being processed as a root file,
// then everything it sucks in may also be marked incorrectly, and needs to be checked again.
if (file && sourceFilesFoundSearchingNodeModules.get(file.path) && currentNodeModulesDepth == 0) {
if (file && sourceFilesFoundSearchingNodeModules.get(file.path) && currentNodeModulesDepth === 0) {
sourceFilesFoundSearchingNodeModules.set(file.path, false);
if (!options.noResolve) {
processReferencedFiles(file, isDefaultLib);
@@ -1722,6 +1750,10 @@ namespace ts {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "allowJs", "declaration"));
}
if (options.checkJs && !options.allowJs) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
}
if (options.emitDecoratorMetadata &&
!options.experimentalDecorators) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"));
+17 -3
View File
@@ -23,6 +23,8 @@ namespace ts {
isIdentifier(): boolean;
isReservedWord(): boolean;
isUnterminated(): boolean;
/* @internal */
getNumericLiteralFlags(): NumericLiteralFlags;
reScanGreaterToken(): SyntaxKind;
reScanSlashToken(): SyntaxKind;
reScanTemplateToken(): SyntaxKind;
@@ -306,6 +308,7 @@ namespace ts {
if (text.charCodeAt(pos) === CharacterCodes.lineFeed) {
pos++;
}
// falls through
case CharacterCodes.lineFeed:
result.push(lineStart);
lineStart = pos;
@@ -452,6 +455,7 @@ namespace ts {
if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) {
pos++;
}
// falls through
case CharacterCodes.lineFeed:
pos++;
if (stopAfterLineBreak) {
@@ -623,6 +627,7 @@ namespace ts {
if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) {
pos++;
}
// falls through
case CharacterCodes.lineFeed:
pos++;
if (trailing) {
@@ -733,11 +738,11 @@ namespace ts {
}
export function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined {
return reduceEachLeadingCommentRange(text, pos, appendCommentRange, undefined, undefined);
return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
}
export function getTrailingCommentRanges(text: string, pos: number): CommentRange[] | undefined {
return reduceEachTrailingCommentRange(text, pos, appendCommentRange, undefined, undefined);
return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
}
/** Optionally, get the shebang */
@@ -799,6 +804,7 @@ namespace ts {
let precedingLineBreak: boolean;
let hasExtendedUnicodeEscape: boolean;
let tokenIsUnterminated: boolean;
let numericLiteralFlags: NumericLiteralFlags;
setText(text, start, length);
@@ -814,6 +820,7 @@ namespace ts {
isIdentifier: () => token === SyntaxKind.Identifier || token > SyntaxKind.LastReservedWord,
isReservedWord: () => token >= SyntaxKind.FirstReservedWord && token <= SyntaxKind.LastReservedWord,
isUnterminated: () => tokenIsUnterminated,
getNumericLiteralFlags: () => numericLiteralFlags,
reScanGreaterToken,
reScanSlashToken,
reScanTemplateToken,
@@ -850,6 +857,7 @@ namespace ts {
let end = pos;
if (text.charCodeAt(pos) === CharacterCodes.E || text.charCodeAt(pos) === CharacterCodes.e) {
pos++;
numericLiteralFlags = NumericLiteralFlags.Scientific;
if (text.charCodeAt(pos) === CharacterCodes.plus || text.charCodeAt(pos) === CharacterCodes.minus) pos++;
if (isDigit(text.charCodeAt(pos))) {
pos++;
@@ -1067,7 +1075,7 @@ namespace ts {
if (pos < end && text.charCodeAt(pos) === CharacterCodes.lineFeed) {
pos++;
}
// fall through
// falls through
case CharacterCodes.lineFeed:
case CharacterCodes.lineSeparator:
case CharacterCodes.paragraphSeparator:
@@ -1221,6 +1229,7 @@ namespace ts {
hasExtendedUnicodeEscape = false;
precedingLineBreak = false;
tokenIsUnterminated = false;
numericLiteralFlags = 0;
while (true) {
tokenPos = pos;
if (pos >= end) {
@@ -1419,6 +1428,7 @@ namespace ts {
value = 0;
}
tokenValue = "" + value;
numericLiteralFlags = NumericLiteralFlags.HexSpecifier;
return token = SyntaxKind.NumericLiteral;
}
else if (pos + 2 < end && (text.charCodeAt(pos + 1) === CharacterCodes.B || text.charCodeAt(pos + 1) === CharacterCodes.b)) {
@@ -1429,6 +1439,7 @@ namespace ts {
value = 0;
}
tokenValue = "" + value;
numericLiteralFlags = NumericLiteralFlags.BinarySpecifier;
return token = SyntaxKind.NumericLiteral;
}
else if (pos + 2 < end && (text.charCodeAt(pos + 1) === CharacterCodes.O || text.charCodeAt(pos + 1) === CharacterCodes.o)) {
@@ -1439,16 +1450,19 @@ namespace ts {
value = 0;
}
tokenValue = "" + value;
numericLiteralFlags = NumericLiteralFlags.OctalSpecifier;
return token = SyntaxKind.NumericLiteral;
}
// Try to parse as an octal
if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
tokenValue = "" + scanOctalDigits();
numericLiteralFlags = NumericLiteralFlags.Octal;
return token = SyntaxKind.NumericLiteral;
}
// This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
// can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
// permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
// falls through
case CharacterCodes._1:
case CharacterCodes._2:
case CharacterCodes._3:
+7 -7
View File
@@ -54,10 +54,10 @@ namespace ts {
referenceCount: number;
}
declare var require: any;
declare var process: any;
declare var global: any;
declare var __filename: string;
declare const require: any;
declare const process: any;
declare const global: any;
declare const __filename: string;
export function getNodeMajorVersion() {
if (typeof process === "undefined") {
@@ -74,7 +74,7 @@ namespace ts {
return parseInt(version.substring(1, dot));
}
declare var ChakraHost: {
declare const ChakraHost: {
args: string[];
currentDirectory: string;
executingFile: string;
@@ -232,7 +232,7 @@ namespace ts {
try {
fd = _fs.openSync(fileName, "w");
_fs.writeSync(fd, data, undefined, "utf8");
_fs.writeSync(fd, data, /*position*/ undefined, "utf8");
}
finally {
if (fd !== undefined) {
@@ -368,7 +368,7 @@ namespace ts {
if (eventName === "rename") {
// When deleting a file, the passed baseFileName is null
callback(!relativeFileName ? relativeFileName : normalizePath(combinePaths(directoryName, relativeFileName)));
};
}
}
);
},
+3 -2
View File
@@ -490,7 +490,8 @@ namespace ts {
};
/** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
* `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`*/
* `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
*/
function createRestCall(context: TransformationContext, value: Expression, elements: BindingOrAssignmentElement[], computedTempVariables: Expression[], location: TextRange): Expression {
context.requestEmitHelper(restHelper);
const propertyNames: Expression[] = [];
@@ -517,7 +518,7 @@ namespace ts {
}
return createCall(
getHelperName("__rest"),
undefined,
/*typeArguments*/ undefined,
[
value,
setTextRange(
+51 -9
View File
@@ -315,7 +315,7 @@ namespace ts {
* Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
* @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
* @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
**/
*/
function enterSubtree(excludeFacts: HierarchyFacts, includeFacts: HierarchyFacts) {
const ancestorFacts = hierarchyFacts;
hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & HierarchyFacts.AncestorFactsMask;
@@ -328,7 +328,7 @@ namespace ts {
* @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
* @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
* @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
**/
*/
function exitSubtree(ancestorFacts: HierarchyFacts, excludeFacts: HierarchyFacts, includeFacts: HierarchyFacts) {
hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & HierarchyFacts.SubtreeFactsMask | ancestorFacts;
}
@@ -466,6 +466,12 @@ namespace ts {
case SyntaxKind.TemplateTail:
return visitTemplateLiteral(<LiteralExpression>node);
case SyntaxKind.StringLiteral:
return visitStringLiteral(<StringLiteral>node);
case SyntaxKind.NumericLiteral:
return visitNumericLiteral(<NumericLiteral>node);
case SyntaxKind.TaggedTemplateExpression:
return visitTaggedTemplateExpression(<TaggedTemplateExpression>node);
@@ -509,8 +515,9 @@ namespace ts {
const ancestorFacts = enterSubtree(HierarchyFacts.SourceFileExcludes, HierarchyFacts.SourceFileIncludes);
const statements: Statement[] = [];
startLexicalEnvironment();
const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ false, visitor);
let statementOffset = addStandardPrologue(statements, node.statements, /*ensureUseStrict*/ false);
addCaptureThisForNodeIfNeeded(statements, node);
statementOffset = addCustomPrologue(statements, node.statements, statementOffset, visitor);
addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset));
addRange(statements, endLexicalEnvironment());
exitSubtree(ancestorFacts, HierarchyFacts.None, HierarchyFacts.None);
@@ -918,13 +925,16 @@ namespace ts {
statementOffset = 0;
}
else if (constructor) {
// Otherwise, try to emit all potential prologue directives first.
statementOffset = addPrologueDirectives(statements, constructor.body.statements, /*ensureUseStrict*/ false, visitor);
statementOffset = addStandardPrologue(statements, constructor.body.statements, /*ensureUseStrict*/ false);
}
if (constructor) {
addDefaultValueAssignmentsIfNeeded(statements, constructor);
addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
if (!hasSynthesizedSuper) {
// If no super call has been synthesized, emit custom prologue directives.
statementOffset = addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
}
Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!");
}
@@ -1815,8 +1825,8 @@ namespace ts {
resumeLexicalEnvironment();
if (isBlock(body)) {
// ensureUseStrict is false because no new prologue-directive should be added.
// addPrologueDirectives will simply put already-existing directives at the beginning of the target statement-array
statementOffset = addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor);
// addStandardPrologue will put already-existing directives at the beginning of the target statement-array
statementOffset = addStandardPrologue(statements, body.statements, /*ensureUseStrict*/ false);
}
addCaptureThisForNodeIfNeeded(statements, node);
@@ -1829,6 +1839,9 @@ namespace ts {
}
if (isBlock(body)) {
// addCustomPrologue puts already-existing directives at the beginning of the target statement-array
statementOffset = addCustomPrologue(statements, body.statements, statementOffset, visitor);
statementsLocation = body.statements;
addRange(statements, visitNodes(body.statements, visitor, isStatement, statementOffset));
@@ -2869,7 +2882,12 @@ namespace ts {
!state.labeledNonLocalContinues;
const call = createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, map(parameters, p => <Identifier>p.name));
const callResult = isAsyncBlockContainingAwait ? createYield(createToken(SyntaxKind.AsteriskToken), call) : call;
const callResult = isAsyncBlockContainingAwait
? createYield(
createToken(SyntaxKind.AsteriskToken),
setEmitFlags(call, EmitFlags.Iterator)
)
: call;
if (isSimpleLoop) {
statements.push(createStatement(callResult));
copyOutParameters(state.loopOutParameters, CopyDirection.ToOriginal, statements);
@@ -3103,7 +3121,7 @@ namespace ts {
const ancestorFacts = enterSubtree(HierarchyFacts.BlockScopeExcludes, HierarchyFacts.BlockScopeIncludes);
let updated: CatchClause;
if (isBindingPattern(node.variableDeclaration.name)) {
const temp = createTempVariable(undefined);
const temp = createTempVariable(/*recordTempVariable*/ undefined);
const newVariableDeclaration = createVariableDeclaration(temp);
setTextRange(newVariableDeclaration, node.variableDeclaration);
const vars = flattenDestructuringBinding(
@@ -3414,6 +3432,30 @@ namespace ts {
return setTextRange(createLiteral(node.text), node);
}
/**
* Visits a string literal with an extended unicode escape.
*
* @param node A string literal.
*/
function visitStringLiteral(node: StringLiteral) {
if (node.hasExtendedUnicodeEscape) {
return setTextRange(createLiteral(node.text), node);
}
return node;
}
/**
* Visits a binary or octal (ES6) numeric literal.
*
* @param node A string literal.
*/
function visitNumericLiteral(node: NumericLiteral) {
if (node.numericLiteralFlags & NumericLiteralFlags.BinaryOrOctalSpecifier) {
return setTextRange(createNumericLiteral(node.text), node);
}
return node;
}
/**
* Visits a TaggedTemplateExpression node.
*
+1 -1
View File
@@ -222,7 +222,7 @@ namespace ts {
if (!isArrowFunction) {
const statements: Statement[] = [];
const statementOffset = addPrologueDirectives(statements, (<Block>node.body).statements, /*ensureUseStrict*/ false, visitor);
const statementOffset = addPrologue(statements, (<Block>node.body).statements, /*ensureUseStrict*/ false, visitor);
statements.push(
createReturn(
createAwaiterHelper(
+13 -5
View File
@@ -618,7 +618,7 @@ namespace ts {
function transformAsyncGeneratorFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody {
resumeLexicalEnvironment();
const statements: Statement[] = [];
const statementOffset = addPrologueDirectives(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
const statementOffset = addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
appendObjectRestAssignmentsIfNeeded(statements, node);
statements.push(
@@ -663,12 +663,19 @@ namespace ts {
function transformFunctionBody(node: ArrowFunction): ConciseBody;
function transformFunctionBody(node: FunctionLikeDeclaration): ConciseBody {
resumeLexicalEnvironment();
const leadingStatements = appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node);
let statementOffset = 0;
const statements: Statement[] = [];
const body = visitNode(node.body, visitor, isConciseBody);
if (isBlock(body)) {
statementOffset = addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
}
addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
const trailingStatements = endLexicalEnvironment();
if (some(leadingStatements) || some(trailingStatements)) {
if (statementOffset > 0 || some(statements) || some(trailingStatements)) {
const block = convertToFunctionBody(body, /*multiLine*/ true);
return updateBlock(block, setTextRange(createNodeArray(concatenate(concatenate(leadingStatements, block.statements), trailingStatements)), block.statements));
addRange(statements, block.statements.slice(statementOffset));
addRange(statements, trailingStatements);
return updateBlock(block, setTextRange(createNodeArray(statements), block.statements));
}
return body;
}
@@ -884,7 +891,8 @@ namespace ts {
function verb(n) { return function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]), next(); }); }; }
function next() { if (!c && q.length) resume((c = q.shift())[0], c[1]); }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(c[3], e); } }
function step(r) { r.done ? settle(c[2], r) : r.value[0] === "yield" ? settle(c[2], { value: r.value[1], done: false }) : Promise.resolve(r.value[1]).then(r.value[0] === "delegate" ? delegate : fulfill, reject); }
function step(r) { r.done ? settle(c[2], r) : Promise.resolve(r.value[1]).then(r.value[0] === "yield" ? _yield : r.value[0] === "delegate" ? delegate : fulfill, reject); }
function _yield(value) { settle(c[2], { value: value, done: false }); }
function delegate(r) { step(r.done ? r : { value: ["yield", r.value], done: false }); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
+6 -3
View File
@@ -587,7 +587,7 @@ namespace ts {
// Build the generator
resumeLexicalEnvironment();
const statementOffset = addPrologueDirectives(statements, body.statements, /*ensureUseStrict*/ false, visitor);
const statementOffset = addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
transformAndEmitStatements(body.statements, statementOffset);
@@ -939,7 +939,10 @@ namespace ts {
const resumeLabel = defineLabel();
const expression = visitNode(node.expression, visitor, isExpression);
if (node.asteriskToken) {
emitYieldStar(createValuesHelper(context, expression, /*location*/ node), /*location*/ node);
const iterator = (getEmitFlags(node.expression) & EmitFlags.Iterator) === 0
? createValuesHelper(context, expression, /*location*/ node)
: expression;
emitYieldStar(iterator, /*location*/ node);
}
else {
emitYield(expression, /*location*/ node);
@@ -1478,7 +1481,7 @@ namespace ts {
}
const initializer = node.initializer;
if (isVariableDeclarationList(initializer)) {
if (initializer && isVariableDeclarationList(initializer)) {
for (const variable of initializer.declarations) {
hoistVariableDeclaration(<Identifier>variable.name);
}
+1 -1
View File
@@ -24,7 +24,7 @@ namespace ts {
const externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions);
if (externalHelpersModuleName) {
const statements: Statement[] = [];
const statementOffset = addPrologueDirectives(statements, node.statements);
const statementOffset = addPrologue(statements, node.statements);
append(statements,
createImportDeclaration(
/*decorators*/ undefined,
+18 -13
View File
@@ -90,7 +90,7 @@ namespace ts {
const statements: Statement[] = [];
const ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && isExternalModule(currentSourceFile));
const statementOffset = addPrologueDirectives(statements, node.statements, ensureUseStrict, sourceElementVisitor);
const statementOffset = addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
if (shouldEmitUnderscoreUnderscoreESModule()) {
append(statements, createUnderscoreUnderscoreESModule());
@@ -359,15 +359,20 @@ namespace ts {
// Find the name of the module alias, if there is one
const importAliasName = getLocalNameForExternalImport(importNode, currentSourceFile);
if (includeNonAmdDependencies && importAliasName) {
// Set emitFlags on the name of the classDeclaration
// This is so that when printer will not substitute the identifier
setEmitFlags(importAliasName, EmitFlags.NoSubstitution);
aliasedModuleNames.push(externalModuleName);
importAliasNames.push(createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
}
else {
unaliasedModuleNames.push(externalModuleName);
// It is possible that externalModuleName is undefined if it is not string literal.
// This can happen in the invalid import syntax.
// E.g : "import * from alias from 'someLib';"
if (externalModuleName) {
if (includeNonAmdDependencies && importAliasName) {
// Set emitFlags on the name of the classDeclaration
// This is so that when printer will not substitute the identifier
setEmitFlags(importAliasName, EmitFlags.NoSubstitution);
aliasedModuleNames.push(externalModuleName);
importAliasNames.push(createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
}
else {
unaliasedModuleNames.push(externalModuleName);
}
}
}
@@ -383,7 +388,7 @@ namespace ts {
startLexicalEnvironment();
const statements: Statement[] = [];
const statementOffset = addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
const statementOffset = addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
if (shouldEmitUnderscoreUnderscoreESModule()) {
append(statements, createUnderscoreUnderscoreESModule());
@@ -1157,7 +1162,7 @@ namespace ts {
statement = createStatement(
createExportExpression(
createIdentifier("__esModule"),
createLiteral(true)
createLiteral(/*value*/ true)
)
);
}
@@ -1170,7 +1175,7 @@ namespace ts {
createIdentifier("exports"),
createLiteral("__esModule"),
createObjectLiteral([
createPropertyAssignment("value", createLiteral(true))
createPropertyAssignment("value", createLiteral(/*value*/ true))
])
]
)
+20 -14
View File
@@ -151,18 +151,20 @@ namespace ts {
for (let i = 0; i < externalImports.length; i++) {
const externalImport = externalImports[i];
const externalModuleName = getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions);
const text = externalModuleName.text;
const groupIndex = groupIndices.get(text);
if (groupIndex !== undefined) {
// deduplicate/group entries in dependency list by the dependency name
dependencyGroups[groupIndex].externalImports.push(externalImport);
}
else {
groupIndices.set(text, dependencyGroups.length);
dependencyGroups.push({
name: externalModuleName,
externalImports: [externalImport]
});
if (externalModuleName) {
const text = externalModuleName.text;
const groupIndex = groupIndices.get(text);
if (groupIndex !== undefined) {
// deduplicate/group entries in dependency list by the dependency name
dependencyGroups[groupIndex].externalImports.push(externalImport);
}
else {
groupIndices.set(text, dependencyGroups.length);
dependencyGroups.push({
name: externalModuleName,
externalImports: [externalImport]
});
}
}
}
@@ -226,7 +228,7 @@ namespace ts {
// Add any prologue directives.
const ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && isExternalModule(currentSourceFile));
const statementOffset = addPrologueDirectives(statements, node.statements, ensureUseStrict, sourceElementVisitor);
const statementOffset = addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
// var __moduleName = context_1 && context_1.id;
statements.push(
@@ -477,8 +479,8 @@ namespace ts {
// module is imported only for side-effects, no emit required
break;
}
// falls through
// fall-through
case SyntaxKind.ImportEqualsDeclaration:
Debug.assert(importVariableName !== undefined);
// save import into the local
@@ -1287,6 +1289,10 @@ namespace ts {
* @param node The node to visit.
*/
function visitForInitializer(node: ForInitializer): ForInitializer {
if (!node) {
return node;
}
if (shouldHoistForInitializer(node)) {
let expressions: Expression[];
for (const variable of node.declarations) {
+7 -4
View File
@@ -954,7 +954,7 @@ namespace ts {
if (ctor.body) {
const statements = ctor.body.statements;
// add prologue directives to the list (if any)
const index = addPrologueDirectives(result, statements, /*ensureUseStrict*/ false, visitor);
const index = addPrologue(result, statements, /*ensureUseStrict*/ false, visitor);
if (index === statements.length) {
// list contains nothing but prologue directives (or empty) - exit
return index;
@@ -1707,6 +1707,9 @@ namespace ts {
case SyntaxKind.StringKeyword:
return createIdentifier("String");
case SyntaxKind.ObjectKeyword:
return createIdentifier("Object");
case SyntaxKind.LiteralType:
switch ((<LiteralTypeNode>node).literal.kind) {
case SyntaxKind.StringLiteral:
@@ -2324,13 +2327,13 @@ namespace ts {
// code if the casted expression has a lower precedence than the rest of the
// expression.
//
// To preserve comments, we return a "PartiallyEmittedExpression" here which will
// preserve the position information of the original expression.
//
// Due to the auto-parenthesization rules used by the visitor and factory functions
// we can safely elide the parentheses here, as a new synthetic
// ParenthesizedExpression will be inserted if we remove parentheses too
// aggressively.
//
// To preserve comments, we return a "PartiallyEmittedExpression" here which will
// preserve the position information of the original expression.
return createPartiallyEmittedExpression(expression, node);
}
+5 -5
View File
@@ -30,7 +30,7 @@ namespace ts {
}
function reportEmittedFiles(files: string[]): void {
if (!files || files.length == 0) {
if (!files || files.length === 0) {
return;
}
@@ -282,7 +282,7 @@ namespace ts {
// When the configFileName is just "tsconfig.json", the watched directory should be
// the current directory; if there is a given "project" parameter, then the configFileName
// is an absolute file name.
directory == "" ? "." : directory,
directory === "" ? "." : directory,
watchedDirectoryChanged, /*recursive*/ true);
}
}
@@ -334,9 +334,9 @@ namespace ts {
// When the configFileName is just "tsconfig.json", the watched directory should be
// the current directory; if there is a given "project" parameter, then the configFileName
// is an absolute file name.
directory == "" ? "." : directory,
directory === "" ? "." : directory,
watchedDirectoryChanged, /*recursive*/ true);
};
}
}
return configParseResult;
}
@@ -739,7 +739,7 @@ namespace ts {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file), /* host */ undefined);
}
else {
sys.writeFile(file, generateTSConfig(options, fileNames));
sys.writeFile(file, generateTSConfig(options, fileNames, sys.newLine));
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Successfully_created_a_tsconfig_json_file), /* host */ undefined);
}
+44 -19
View File
@@ -819,7 +819,7 @@ namespace ts {
body?: FunctionBody;
}
/** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements.*/
/** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */
export interface SemicolonClassElement extends ClassElement {
kind: SyntaxKind.SemicolonClassElement;
parent?: ClassDeclaration | ClassExpression;
@@ -1313,8 +1313,6 @@ namespace ts {
text: string;
isUnterminated?: boolean;
hasExtendedUnicodeEscape?: boolean;
/* @internal */
isOctalLiteral?: boolean;
}
// The text property of a LiteralExpression stores the interpreted value of the literal in text form. For a StringLiteral,
@@ -1332,8 +1330,21 @@ namespace ts {
kind: SyntaxKind.NoSubstitutionTemplateLiteral;
}
/* @internal */
export const enum NumericLiteralFlags {
None = 0,
Scientific = 1 << 1, // e.g. `10e2`
Octal = 1 << 2, // e.g. `0777`
HexSpecifier = 1 << 3, // e.g. `0x00000000`
BinarySpecifier = 1 << 4, // e.g. `0b0110010000000000`
OctalSpecifier = 1 << 5, // e.g. `0o777`
BinaryOrOctalSpecifier = BinarySpecifier | OctalSpecifier,
}
export interface NumericLiteral extends LiteralExpression {
kind: SyntaxKind.NumericLiteral;
/* @internal */
numericLiteralFlags?: NumericLiteralFlags;
}
export interface TemplateHead extends LiteralLikeNode {
@@ -1386,11 +1397,11 @@ namespace ts {
}
/**
* This interface is a base interface for ObjectLiteralExpression and JSXAttributes to extend from. JSXAttributes is similar to
* ObjectLiteralExpression in that it contains array of properties; however, JSXAttributes' properties can only be
* JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type
* ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.)
**/
* This interface is a base interface for ObjectLiteralExpression and JSXAttributes to extend from. JSXAttributes is similar to
* ObjectLiteralExpression in that it contains array of properties; however, JSXAttributes' properties can only be
* JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type
* ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.)
*/
export interface ObjectLiteralExpressionBase<T extends ObjectLiteralElement> extends PrimaryExpression, Declaration {
properties: NodeArray<T>;
}
@@ -1402,7 +1413,7 @@ namespace ts {
multiLine?: boolean;
}
export type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression;
export type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression | ParenthesizedExpression;
export type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression;
export interface PropertyAccessExpression extends MemberExpression, Declaration {
@@ -1875,6 +1886,7 @@ namespace ts {
kind: SyntaxKind.ImportDeclaration;
parent?: SourceFile | ModuleBlock;
importClause?: ImportClause;
/** If this is not a StringLiteral it will be a grammar error. */
moduleSpecifier: Expression;
}
@@ -1908,6 +1920,7 @@ namespace ts {
kind: SyntaxKind.ExportDeclaration;
parent?: SourceFile | ModuleBlock;
exportClause?: NamedExports;
/** If this is not a StringLiteral it will be a grammar error. */
moduleSpecifier?: Expression;
}
@@ -1952,6 +1965,10 @@ namespace ts {
fileName: string;
}
export interface CheckJsDirective extends TextRange {
enabled: boolean;
}
export type CommentKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia;
export interface CommentRange extends TextRange {
@@ -2290,10 +2307,11 @@ namespace ts {
// Content of this field should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead
/* @internal */ resolvedModules: Map<ResolvedModuleFull>;
/* @internal */ resolvedTypeReferenceDirectiveNames: Map<ResolvedTypeReferenceDirective>;
/* @internal */ imports: LiteralExpression[];
/* @internal */ moduleAugmentations: LiteralExpression[];
/* @internal */ imports: StringLiteral[];
/* @internal */ moduleAugmentations: StringLiteral[];
/* @internal */ patternAmbientModules?: PatternAmbientModule[];
/* @internal */ ambientModuleNames: string[];
/* @internal */ checkJsDirective: CheckJsDirective | undefined;
}
export interface Bundle extends Node {
@@ -2314,9 +2332,9 @@ namespace ts {
readDirectory(rootDir: string, extensions: string[], excludes: string[], includes: string[]): string[];
/**
* Gets a value indicating whether the specified path exists and is a file.
* @param path The path to test.
*/
* Gets a value indicating whether the specified path exists and is a file.
* @param path The path to test.
*/
fileExists(path: string): boolean;
readFile(path: string): string;
@@ -2506,10 +2524,14 @@ namespace ts {
isUndefinedSymbol(symbol: Symbol): boolean;
isArgumentsSymbol(symbol: Symbol): boolean;
isUnknownSymbol(symbol: Symbol): boolean;
/* @internal */ getMergedSymbol(symbol: Symbol): Symbol;
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number;
isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean;
/** Follow all aliases to get the original symbol. */
getAliasedSymbol(symbol: Symbol): Symbol;
/** Follow a *single* alias to get the immediately aliased symbol. */
/* @internal */ getImmediateAliasedSymbol(symbol: Symbol): Symbol;
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
/** Unlike `getExportsOfModule`, this includes properties of an `export =` value. */
/* @internal */ getExportsAndPropertiesOfModule(moduleSymbol: Symbol): Symbol[];
@@ -2666,8 +2688,7 @@ namespace ts {
errorModuleName?: string; // If the symbol is not visible from module, module's name
}
/** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator
* metadata */
/** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
/* @internal */
export enum TypeReferenceSerializationKind {
Unknown, // The TypeReferenceNode could not be resolved. The type name
@@ -2828,6 +2849,7 @@ namespace ts {
/* @internal */
export interface SymbolLinks {
immediateTarget?: Symbol; // Immediate target of an alias. May be another alias. Do not access directly, use `checker.getImmediateAliasedSymbol` instead.
target?: Symbol; // Resolved (non-alias) target of an alias
type?: Type; // Type of value symbol
declaredType?: Type; // Type of class, interface, enum, type alias, or type parameter
@@ -2839,7 +2861,7 @@ namespace ts {
containingType?: UnionOrIntersectionType; // Containing union or intersection type for synthetic property
leftSpread?: Symbol; // Left source for synthetic spread property
rightSpread?: Symbol; // Right source for synthetic spread property
mappedTypeOrigin?: Symbol; // For a property on a mapped type, points back to the orignal 'T' from 'keyof T'.
syntheticOrigin?: Symbol; // For a property on a mapped or spread type, points back to the original property
isDiscriminantProperty?: boolean; // True if discriminant synthetic property
resolvedExports?: SymbolTable; // Resolved exports of module
exportsChecked?: boolean; // True if exports of external module have been checked
@@ -2867,6 +2889,7 @@ namespace ts {
/* @internal */
export interface TransientSymbol extends Symbol, SymbolLinks {
checkFlags: CheckFlags;
isRestParameter?: boolean;
}
export type SymbolTable = Map<Symbol>;
@@ -2896,7 +2919,7 @@ namespace ts {
ContextChecked = 0x00000400, // Contextual types have been assigned
AsyncMethodWithSuper = 0x00000800, // An async method that reads a value from a member of 'super'.
AsyncMethodWithSuperBinding = 0x00001000, // An async method that assigns a value to a member of 'super'.
CaptureArguments = 0x00002000, // Lexical 'arguments' used in body (for async functions)
CaptureArguments = 0x00002000, // Lexical 'arguments' used in body
EnumValuesComputed = 0x00004000, // Values for enum members have been computed, and any errors have been reported for them.
LexicalModuleMergesWithClass = 0x00008000, // Instantiated lexical module declaration is merged with a previous class declaration.
LoopWithCapturedBlockScopedBinding = 0x00010000, // Loop that contains block scoped variable captured in closure
@@ -2920,6 +2943,7 @@ namespace ts {
maybeTypePredicate?: boolean; // Cached check whether call expression might reference a type predicate
enumMemberValue?: number; // Constant value of enum member
isVisible?: boolean; // Is this node visible
containsArgumentsReference?: boolean; // Whether a function-like declaration contains an 'arguments' reference
hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context
jsxFlags?: JsxFlags; // flags for knowing what kind of element/attributes we're dealing with
resolvedJsxElementAttributesType?: Type; // resolved element attributes type of a JSX openinglike element
@@ -3357,6 +3381,7 @@ namespace ts {
alwaysStrict?: boolean; // Always combine with strict property
baseUrl?: string;
charset?: string;
checkJs?: boolean;
/* @internal */ configFilePath?: string;
declaration?: boolean;
declarationDir?: string;
@@ -3922,6 +3947,7 @@ namespace ts {
CustomPrologue = 1 << 19, // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed).
NoHoisting = 1 << 20, // Do not hoist this declaration in --module system
HasEndOfDeclarationMarker = 1 << 21, // Declaration has an associated NotEmittedStatement to mark the end of the declaration
Iterator = 1 << 22, // The expression to a `yield*` should be treated as an Iterator when down-leveling, not an Iterable.
}
export interface EmitHelper {
@@ -4184,7 +4210,6 @@ namespace ts {
}
export interface PrinterOptions {
target?: ScriptTarget;
removeComments?: boolean;
newLine?: NewLineKind;
/*@internal*/ sourceMap?: boolean;
+50 -97
View File
@@ -322,21 +322,11 @@ namespace ts {
return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
}
export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile, languageVersion: ScriptTarget) {
// Any template literal or string literal with an extended escape
// (e.g. "\u{0067}") will need to be downleveled as a escaped string literal.
if (languageVersion < ScriptTarget.ES2015 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) {
return getQuotedEscapedLiteralText('"', node.text, '"');
}
export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile) {
// If we don't need to downlevel and we can reach the original source text using
// the node's parent reference, then simply get the text as it was originally written.
if (!nodeIsSynthesized(node) && node.parent) {
const text = getSourceTextOfNodeFromSourceFile(sourceFile, node);
if (languageVersion < ScriptTarget.ES2015 && isBinaryOrOctalIntegerLiteral(node, text)) {
return node.text;
}
return text;
return getSourceTextOfNodeFromSourceFile(sourceFile, node);
}
// If we can't reach the original source text, use the canonical form if it's a number,
@@ -359,55 +349,6 @@ namespace ts {
Debug.fail(`Literal kind '${node.kind}' not accounted for.`);
}
export function isBinaryOrOctalIntegerLiteral(node: LiteralLikeNode, text: string) {
return node.kind === SyntaxKind.NumericLiteral
&& (getNumericLiteralFlags(text, /*hint*/ NumericLiteralFlags.BinaryOrOctal) & NumericLiteralFlags.BinaryOrOctal) !== 0;
}
export const enum NumericLiteralFlags {
None = 0,
Hexadecimal = 1 << 0,
Binary = 1 << 1,
Octal = 1 << 2,
Scientific = 1 << 3,
BinaryOrOctal = Binary | Octal,
BinaryOrOctalOrHexadecimal = BinaryOrOctal | Hexadecimal,
All = Hexadecimal | Binary | Octal | Scientific,
}
/**
* Scans a numeric literal string to determine the form of the number.
* @param text Numeric literal text
* @param hint If `Scientific` or `All` is specified, performs a more expensive check to scan for scientific notation.
*/
export function getNumericLiteralFlags(text: string, hint?: NumericLiteralFlags) {
if (text.length > 1) {
switch (text.charCodeAt(1)) {
case CharacterCodes.b:
case CharacterCodes.B:
return NumericLiteralFlags.Binary;
case CharacterCodes.o:
case CharacterCodes.O:
return NumericLiteralFlags.Octal;
case CharacterCodes.x:
case CharacterCodes.X:
return NumericLiteralFlags.Hexadecimal;
}
if (hint & NumericLiteralFlags.Scientific) {
for (let i = text.length - 1; i >= 0; i--) {
switch (text.charCodeAt(i)) {
case CharacterCodes.e:
case CharacterCodes.E:
return NumericLiteralFlags.Scientific;
}
}
}
}
return NumericLiteralFlags.None;
}
function getQuotedEscapedLiteralText(leftQuote: string, text: string, rightQuote: string) {
return leftQuote + escapeNonAsciiCharacters(escapeString(text)) + rightQuote;
}
@@ -438,9 +379,9 @@ namespace ts {
((<ModuleDeclaration>node).name.kind === SyntaxKind.StringLiteral || isGlobalScopeAugmentation(<ModuleDeclaration>node));
}
/** Given a symbol for a module, checks that it is either an untyped import or a shorthand ambient module. */
export function isUntypedOrShorthandAmbientModuleSymbol(moduleSymbol: Symbol): boolean {
return !moduleSymbol.declarations || isShorthandAmbientModule(moduleSymbol.valueDeclaration);
/** Given a symbol for a module, checks that it is a shorthand ambient module. */
export function isShorthandAmbientModuleSymbol(moduleSymbol: Symbol): boolean {
return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
}
function isShorthandAmbientModule(node: Node): boolean {
@@ -733,6 +674,7 @@ namespace ts {
// At this point, node is either a qualified name or an identifier
Debug.assert(node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName || node.kind === SyntaxKind.PropertyAccessExpression,
"'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
// falls through
case SyntaxKind.QualifiedName:
case SyntaxKind.PropertyAccessExpression:
case SyntaxKind.ThisKeyword:
@@ -842,6 +784,7 @@ namespace ts {
if (operand) {
traverse(operand);
}
return;
case SyntaxKind.EnumDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.ModuleDeclaration:
@@ -1059,7 +1002,7 @@ namespace ts {
if (!includeArrowFunctions) {
continue;
}
// Fall through
// falls through
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ModuleDeclaration:
@@ -1095,13 +1038,13 @@ namespace ts {
}
/**
* Given an super call/property node, returns the closest node where
* - a super call/property access is legal in the node and not legal in the parent node the node.
* i.e. super call is legal in constructor but not legal in the class body.
* - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
* - a super call/property is definitely illegal in the container (but might be legal in some subnode)
* i.e. super property access is illegal in function declaration but can be legal in the statement list
*/
* Given an super call/property node, returns the closest node where
* - a super call/property access is legal in the node and not legal in the parent node the node.
* i.e. super call is legal in constructor but not legal in the class body.
* - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
* - a super call/property is definitely illegal in the container (but might be legal in some subnode)
* i.e. super property access is illegal in function declaration but can be legal in the statement list
*/
export function getSuperContainer(node: Node, stopOnFunctions: boolean): Node {
while (true) {
node = node.parent;
@@ -1118,6 +1061,7 @@ namespace ts {
if (!stopOnFunctions) {
continue;
}
// falls through
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.PropertySignature:
case SyntaxKind.MethodDeclaration:
@@ -1317,7 +1261,7 @@ namespace ts {
if (node.parent.kind === SyntaxKind.TypeQuery || isJSXTagName(node)) {
return true;
}
// fall through
// falls through
case SyntaxKind.NumericLiteral:
case SyntaxKind.StringLiteral:
case SyntaxKind.ThisKeyword:
@@ -1404,17 +1348,24 @@ namespace ts {
/**
* Returns true if the node is a CallExpression to the identifier 'require' with
* exactly one argument.
* exactly one argument (of the form 'require("name")').
* This function does not test if the node is in a JavaScript file or not.
*/
export function isRequireCall(expression: Node, checkArgumentIsStringLiteral: boolean): expression is CallExpression {
// of the form 'require("name")'
const isRequire = expression.kind === SyntaxKind.CallExpression &&
(<CallExpression>expression).expression.kind === SyntaxKind.Identifier &&
(<Identifier>(<CallExpression>expression).expression).text === "require" &&
(<CallExpression>expression).arguments.length === 1;
*/
export function isRequireCall(callExpression: Node, checkArgumentIsStringLiteral: boolean): callExpression is CallExpression {
if (callExpression.kind !== SyntaxKind.CallExpression) {
return false;
}
const { expression, arguments: args } = callExpression as CallExpression;
return isRequire && (!checkArgumentIsStringLiteral || (<CallExpression>expression).arguments[0].kind === SyntaxKind.StringLiteral);
if (expression.kind !== SyntaxKind.Identifier || (expression as Identifier).text !== "require") {
return false;
}
if (args.length !== 1) {
return false;
}
const arg = args[0];
return !checkArgumentIsStringLiteral || arg.kind === SyntaxKind.StringLiteral || arg.kind === SyntaxKind.NoSubstitutionTemplateLiteral;
}
export function isSingleOrDoubleQuote(charCode: number) {
@@ -1450,13 +1401,10 @@ namespace ts {
/// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
/// assignments we treat as special in the binder
export function getSpecialPropertyAssignmentKind(expression: Node): SpecialPropertyAssignmentKind {
export function getSpecialPropertyAssignmentKind(expression: ts.BinaryExpression): SpecialPropertyAssignmentKind {
if (!isInJavaScriptFile(expression)) {
return SpecialPropertyAssignmentKind.None;
}
if (expression.kind !== SyntaxKind.BinaryExpression) {
return SpecialPropertyAssignmentKind.None;
}
const expr = <BinaryExpression>expression;
if (expr.operatorToken.kind !== SyntaxKind.EqualsToken || expr.left.kind !== SyntaxKind.PropertyAccessExpression) {
return SpecialPropertyAssignmentKind.None;
@@ -1591,7 +1539,7 @@ namespace ts {
return node && firstOrUndefined(getJSDocTags(node, kind));
}
function getJSDocs(node: Node): (JSDoc | JSDocTag)[] {
export function getJSDocs(node: Node): (JSDoc | JSDocTag)[] {
let cache: (JSDoc | JSDocTag)[] = node.jsDocCache;
if (!cache) {
getJSDocsWorker(node);
@@ -1995,7 +1943,7 @@ namespace ts {
if (node.asteriskToken) {
flags |= FunctionFlags.Generator;
}
// fall through
// falls through
case SyntaxKind.ArrowFunction:
if (hasModifier(node, ModifierFlags.Async)) {
flags |= FunctionFlags.Async;
@@ -2023,6 +1971,10 @@ namespace ts {
return false;
}
export function isNumericLiteral(node: Node): node is NumericLiteral {
return node.kind === SyntaxKind.NumericLiteral;
}
export function isStringOrNumericLiteral(node: Node): node is StringLiteral | NumericLiteral {
const kind = node.kind;
return kind === SyntaxKind.StringLiteral
@@ -3185,7 +3137,7 @@ namespace ts {
return isExportDefaultSymbol(symbol) ? symbol.valueDeclaration.localSymbol : undefined;
}
export function isExportDefaultSymbol(symbol: Symbol): boolean {
function isExportDefaultSymbol(symbol: Symbol): boolean {
return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, ModifierFlags.Default);
}
@@ -4255,12 +4207,13 @@ namespace ts {
export function getDefaultLibFileName(options: CompilerOptions): string {
switch (options.target) {
case ScriptTarget.ESNext:
return "lib.esnext.full.d.ts";
case ScriptTarget.ES2017:
return "lib.es2017.d.ts";
return "lib.es2017.full.d.ts";
case ScriptTarget.ES2016:
return "lib.es2016.d.ts";
return "lib.es2016.full.d.ts";
case ScriptTarget.ES2015:
return "lib.es6.d.ts";
return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
default:
return "lib.d.ts";
}
@@ -4480,7 +4433,7 @@ namespace ts {
newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
}
return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength:*/ newEndN - oldStartN);
return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
}
export function getTypeParameterOwner(d: Declaration): Declaration {
@@ -4552,9 +4505,9 @@ namespace ts {
}
/**
* Checks to see if the locale is in the appropriate format,
* and if it is, attempts to set the appropriate language.
*/
* Checks to see if the locale is in the appropriate format,
* and if it is, attempts to set the appropriate language.
*/
export function validateLocaleAndSetLanguage(
locale: string,
sys: { getExecutingFilePath(): string, resolvePath(path: string): string, fileExists(fileName: string): boolean, readFile(fileName: string): string },
@@ -4656,7 +4609,7 @@ namespace ts {
*/
export function getParseTreeNode<T extends Node>(node: Node, nodeTest?: (node: Node) => node is T): T;
export function getParseTreeNode(node: Node, nodeTest?: (node: Node) => boolean): Node {
if (node == undefined || isParseTreeNode(node)) {
if (node === undefined || isParseTreeNode(node)) {
return node;
}
+5 -3
View File
@@ -322,7 +322,7 @@ namespace ts {
nodesVisitor((<UnionOrIntersectionTypeNode>node).types, visitor, isTypeNode));
case SyntaxKind.ParenthesizedType:
Debug.fail("not implemented.");
throw Debug.fail("not implemented.");
case SyntaxKind.TypeOperator:
return updateTypeOperatorNode(<TypeOperatorNode>node, visitNode((<TypeOperatorNode>node).type, visitor, isTypeNode));
@@ -887,7 +887,7 @@ namespace ts {
return initial;
}
const reduceNodes: (nodes: NodeArray<Node>, f: (memo: T, node: Node | NodeArray<Node>) => T, initial: T) => T = cbNodeArray ? reduceNodeArray : reduceLeft;
const reduceNodes: (nodes: NodeArray<Node>, f: ((memo: T, node: Node) => T) | ((memo: T, node: NodeArray<Node>) => T), initial: T) => T = cbNodeArray ? reduceNodeArray : reduceLeft;
const cbNodes = cbNodeArray || cbNode;
const kind = node.kind;
@@ -1291,6 +1291,7 @@ namespace ts {
case SyntaxKind.JsxAttributes:
result = reduceNodes((<JsxAttributes>node).properties, cbNodes, result);
break;
case SyntaxKind.JsxClosingElement:
result = reduceNode((<JsxClosingElement>node).tagName, cbNode, result);
@@ -1312,7 +1313,7 @@ namespace ts {
// Clauses
case SyntaxKind.CaseClause:
result = reduceNode((<CaseClause>node).expression, cbNode, result);
// fall-through
// falls through
case SyntaxKind.DefaultClause:
result = reduceNodes((<CaseClause | DefaultClause>node).statements, cbNodes, result);
@@ -1346,6 +1347,7 @@ namespace ts {
case SyntaxKind.EnumMember:
result = reduceNode((<EnumMember>node).name, cbNode, result);
result = reduceNode((<EnumMember>node).initializer, cbNode, result);
break;
// Top-level nodes
case SyntaxKind.SourceFile:
+1 -1
View File
@@ -51,7 +51,7 @@ class CompilerBaselineRunner extends RunnerBase {
const path = ts.toPath(name, root, (fileName) => Harness.Compiler.getCanonicalFileName(fileName));
const pathStart = ts.toPath(Harness.IO.getCurrentDirectory(), "", (fileName) => Harness.Compiler.getCanonicalFileName(fileName));
return pathStart ? path.replace(pathStart, "/") : path;
};
}
public checkTestCodeOutput(fileName: string) {
describe("compiler tests for " + fileName, () => {
+175 -38
View File
@@ -549,10 +549,21 @@ namespace FourSlash {
Harness.IO.log("Unexpected error(s) found. Error list is:");
}
errors.forEach(function (error: ts.Diagnostic) {
Harness.IO.log(" minChar: " + error.start +
", limChar: " + (error.start + error.length) +
", message: " + ts.flattenDiagnosticMessageText(error.messageText, Harness.IO.newLine()) + "\n");
for (const { start, length, messageText } of errors) {
Harness.IO.log(" minChar: " + start +
", limChar: " + (start + length) +
", message: " + ts.flattenDiagnosticMessageText(messageText, Harness.IO.newLine()) + "\n");
}
}
public verifyNoErrors() {
ts.forEachKey(this.inputFiles, fileName => {
const errors = this.getDiagnostics(fileName);
if (errors.length) {
this.printErrorLog(/*expectErrors*/ false, errors);
const error = errors[0];
this.raiseError(`Found an error: ${error.file.fileName}@${error.start}: ${error.messageText}`);
}
});
}
@@ -858,7 +869,7 @@ namespace FourSlash {
}
}
public verifyCompletionEntryDetails(entryName: string, expectedText: string, expectedDocumentation?: string, kind?: string) {
public verifyCompletionEntryDetails(entryName: string, expectedText: string, expectedDocumentation?: string, kind?: string, tags?: ts.JSDocTagInfo[]) {
const details = this.getCompletionEntryDetails(entryName);
assert(details, "no completion entry available");
@@ -872,9 +883,78 @@ namespace FourSlash {
if (kind !== undefined) {
assert.equal(details.kind, kind, this.assertionMessageAtLastKnownMarker("completion entry kind"));
}
if (tags !== undefined) {
assert.equal(details.tags.length, tags.length, this.messageAtLastKnownMarker("QuickInfo tags"));
ts.zipWith(tags, details.tags, (expectedTag, actualTag) => {
assert.equal(expectedTag.name, actualTag.name);
assert.equal(expectedTag.text, actualTag.text, this.messageAtLastKnownMarker("QuickInfo tag " + actualTag.name));
});
}
}
public verifyReferencesAre(expectedReferences: Range[]) {
/** Use `getProgram` instead of accessing this directly. */
private _program: ts.Program;
/** Use `getChecker` instead of accessing this directly. */
private _checker: ts.TypeChecker;
private getProgram(): ts.Program {
return this._program || (this._program = this.languageService.getProgram());
}
private getChecker() {
return this._checker || (this._checker = this.getProgram().getTypeChecker());
}
private getSourceFile(): ts.SourceFile {
const { fileName } = this.activeFile;
const result = this.getProgram().getSourceFile(fileName);
if (!result) {
throw new Error(`Could not get source file ${fileName}`);
}
return result;
}
private getNode(): ts.Node {
return ts.getTouchingPropertyName(this.getSourceFile(), this.currentCaretPosition);
}
private goToAndGetNode(range: Range): ts.Node {
this.goToRangeStart(range);
const node = this.getNode();
this.verifyRange("touching property name", range, node);
return node;
}
private verifyRange(desc: string, expected: Range, actual: ts.Node) {
const actualStart = actual.getStart();
const actualEnd = actual.getEnd();
if (actualStart !== expected.start || actualEnd !== expected.end) {
this.raiseError(`${desc} should be ${expected.start}-${expected.end}, got ${actualStart}-${actualEnd}`);
}
}
private verifySymbol(symbol: ts.Symbol, declarationRanges: Range[]) {
const { declarations } = symbol;
if (declarations.length !== declarationRanges.length) {
this.raiseError(`Expected to get ${declarationRanges.length} declarations, got ${declarations.length}`);
}
ts.zipWith(declarations, declarationRanges, (decl, range) => {
this.verifyRange("symbol declaration", range, decl);
});
}
public verifySymbolAtLocation(startRange: Range, declarationRanges: Range[]): void {
const node = this.goToAndGetNode(startRange);
const symbol = this.getChecker().getSymbolAtLocation(node);
if (!symbol) {
this.raiseError("Could not get symbol at location");
}
this.verifySymbol(symbol, declarationRanges);
}
private verifyReferencesAre(expectedReferences: Range[]) {
const actualReferences = this.getReferencesAtCaret() || [];
if (actualReferences.length > expectedReferences.length) {
@@ -920,7 +1000,7 @@ namespace FourSlash {
for (const startRange of toArray(startRanges)) {
this.goToRangeStart(startRange);
const fullActual = this.findReferencesAtCaret().map<ReferenceJson>(({ definition, references }) => ({
const fullActual = ts.map<ts.ReferencedSymbol, ReferenceJson>(this.findReferencesAtCaret(), ({ definition, references }) => ({
definition: definition.displayParts.map(d => d.text).join(""),
ranges: references
}));
@@ -1083,7 +1163,9 @@ namespace FourSlash {
public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: { start: number; length: number; },
displayParts: ts.SymbolDisplayPart[],
documentation: ts.SymbolDisplayPart[]) {
documentation: ts.SymbolDisplayPart[],
tags: ts.JSDocTagInfo[]
) {
const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition);
assert.equal(actualQuickInfo.kind, kind, this.messageAtLastKnownMarker("QuickInfo kind"));
@@ -1091,11 +1173,39 @@ namespace FourSlash {
assert.equal(JSON.stringify(actualQuickInfo.textSpan), JSON.stringify(textSpan), this.messageAtLastKnownMarker("QuickInfo textSpan"));
assert.equal(TestState.getDisplayPartsJson(actualQuickInfo.displayParts), TestState.getDisplayPartsJson(displayParts), this.messageAtLastKnownMarker("QuickInfo displayParts"));
assert.equal(TestState.getDisplayPartsJson(actualQuickInfo.documentation), TestState.getDisplayPartsJson(documentation), this.messageAtLastKnownMarker("QuickInfo documentation"));
assert.equal(actualQuickInfo.tags.length, tags.length, this.messageAtLastKnownMarker("QuickInfo tags"));
ts.zipWith(tags, actualQuickInfo.tags, (expectedTag, actualTag) => {
assert.equal(expectedTag.name, actualTag.name);
assert.equal(expectedTag.text, actualTag.text, this.messageAtLastKnownMarker("QuickInfo tag " + actualTag.name));
});
}
public verifyRenameLocations(findInStrings: boolean, findInComments: boolean, ranges?: Range[]) {
const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition);
if (renameInfo.canRename) {
public verifyRangesAreRenameLocations(options?: Range[] | { findInStrings?: boolean, findInComments?: boolean, ranges?: Range[] }) {
const ranges = ts.isArray(options) ? options : options && options.ranges || this.getRanges();
this.verifyRenameLocations(ranges, { ranges, ...options });
}
public verifyRenameLocations(startRanges: Range | Range[], options: Range[] | { findInStrings?: boolean, findInComments?: boolean, ranges: Range[] }) {
let findInStrings: boolean, findInComments: boolean, ranges: Range[];
if (ts.isArray(options)) {
findInStrings = findInComments = false;
ranges = options;
}
else {
findInStrings = !!options.findInStrings;
findInComments = !!options.findInComments;
ranges = options.ranges;
}
for (const startRange of toArray(startRanges)) {
this.goToRangeStart(startRange);
const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition);
if (!renameInfo.canRename) {
this.raiseError("Expected rename to succeed, but it actually failed.");
break;
}
let references = this.languageService.findRenameLocations(
this.activeFile.fileName, this.currentCaretPosition, findInStrings, findInComments);
@@ -1117,13 +1227,10 @@ namespace FourSlash {
ts.zipWith(references, ranges, (reference, range) => {
if (reference.textSpan.start !== range.start || ts.textSpanEnd(reference.textSpan) !== range.end) {
this.raiseError("Rename location results do not match.\n\nExpected: " + stringify(ranges) + "\n\nActual:" + JSON.stringify(references));
this.raiseError("Rename location results do not match.\n\nExpected: " + stringify(ranges) + "\n\nActual:" + stringify(references));
}
});
}
else {
this.raiseError("Expected rename to succeed, but it actually failed.");
}
}
public verifyQuickInfoExists(negative: boolean) {
@@ -1184,6 +1291,16 @@ namespace FourSlash {
assert.equal(ts.displayPartsToString(actualDocComment), docComment, this.assertionMessageAtLastKnownMarker("current signature help doc comment"));
}
public verifyCurrentSignatureHelpTags(tags: ts.JSDocTagInfo[]) {
const actualTags = this.getActiveSignatureHelpItem().tags;
assert.equal(actualTags.length, tags.length, this.assertionMessageAtLastKnownMarker("signature help tags"));
ts.zipWith(tags, actualTags, (expectedTag, actualTag) => {
assert.equal(expectedTag.name, actualTag.name);
assert.equal(expectedTag.text, actualTag.text, this.assertionMessageAtLastKnownMarker("signature help tag " + actualTag.name));
});
}
public verifySignatureHelpCount(expected: number) {
const help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition);
const actual = help && help.items ? help.items.length : 0;
@@ -1669,7 +1786,7 @@ namespace FourSlash {
if (ch === "\r") {
this.currentCaretPosition--;
}
};
}
}
private applyEdits(fileName: string, edits: ts.TextChange[], isFormattingEdit = false): number {
@@ -2180,7 +2297,7 @@ namespace FourSlash {
/**
* Applies fixes for the errors in fileName and compares the results to
* expectedContents after all fixes have been applied.
*
* Note: applying one codefix may generate another (eg: remove duplicate implements
* may generate an extends -> interface conversion fix).
* @param expectedContents The contents of the file after the fixes are applied.
@@ -2250,13 +2367,13 @@ namespace FourSlash {
public verifyImportFixAtPosition(expectedTextArray: string[], errorCode?: number) {
const ranges = this.getRanges();
if (ranges.length == 0) {
if (ranges.length === 0) {
this.raiseError("At least one range should be specified in the testfile.");
}
const codeFixes = this.getCodeFixActions(this.activeFile.fileName, errorCode);
if (!codeFixes || codeFixes.length == 0) {
if (!codeFixes || codeFixes.length === 0) {
this.raiseError("No codefixes returned.");
}
@@ -2526,8 +2643,8 @@ namespace FourSlash {
}
}
public verifyRangesAreRenameLocations(findInStrings: boolean, findInComments: boolean) {
this.goToEachRange(() => this.verifyRenameLocations(findInStrings, findInComments));
public verifyRangesWithSameTextAreRenameLocations() {
this.rangesByText().forEach(ranges => this.verifyRangesAreRenameLocations(ranges));
}
public verifyRangesWithSameTextAreDocumentHighlights() {
@@ -2566,7 +2683,7 @@ namespace FourSlash {
ts.zipWith(expectedRangesInFile, spansInFile, (expectedRange, span) => {
if (span.textSpan.start !== expectedRange.start || ts.textSpanEnd(span.textSpan) !== expectedRange.end) {
this.raiseError(`verifyDocumentHighlights failed - span does not match, actual: ${JSON.stringify(span.textSpan)}, expected: ${expectedRange.start}--${expectedRange.end}`);
this.raiseError(`verifyDocumentHighlights failed - span does not match, actual: ${stringify(span.textSpan)}, expected: ${expectedRange.start}--${expectedRange.end}`);
}
});
}
@@ -2584,6 +2701,11 @@ namespace FourSlash {
}
}
public printAvailableCodeFixes() {
const codeFixes = this.getCodeFixActions(this.activeFile.fileName);
Harness.IO.log(stringify(codeFixes));
}
// Get the text of the entire line the caret is currently at
private getCurrentLineContent() {
const text = this.getFileContent(this.activeFile.fileName);
@@ -2616,7 +2738,7 @@ namespace FourSlash {
private assertItemInCompletionList(items: ts.CompletionEntry[], name: string, text?: string, documentation?: string, kind?: string, spanIndex?: number) {
for (const item of items) {
if (item.name === name) {
if (documentation != undefined || text !== undefined) {
if (documentation !== undefined || text !== undefined) {
const details = this.getCompletionEntryDetails(item.name);
if (documentation !== undefined) {
@@ -2867,9 +2989,8 @@ ${code}
}
}
}
// TODO: should be '==='?
}
else if (line == "" || lineLength === 0) {
else if (line === "" || lineLength === 0) {
// Previously blank lines between fourslash content caused it to be considered as 2 files,
// Remove this behavior since it just causes errors now
}
@@ -3161,7 +3282,7 @@ ${code}
}
// Add the remaining text
flush(undefined);
flush(/*lastSafeCharIndex*/ undefined);
if (openRanges.length > 0) {
const openRange = openRanges[0];
@@ -3465,8 +3586,8 @@ namespace FourSlashInterface {
this.state.verifyGetEmitOutputContentsForCurrentFile(expected);
}
public referencesAre(ranges: FourSlash.Range[]) {
this.state.verifyReferencesAre(ranges);
public symbolAtLocation(startRange: FourSlash.Range, ...declarationRanges: FourSlash.Range[]) {
this.state.verifySymbolAtLocation(startRange, declarationRanges);
}
public referencesOf(start: FourSlash.Range, references: FourSlash.Range[]) {
@@ -3509,6 +3630,10 @@ namespace FourSlashInterface {
this.state.verifyCurrentSignatureHelpDocComment(docComment);
}
public currentSignatureHelpTagsAre(tags: ts.JSDocTagInfo[]) {
this.state.verifyCurrentSignatureHelpTags(tags);
}
public signatureHelpCountIs(expected: number) {
this.state.verifySignatureHelpCount(expected);
}
@@ -3529,6 +3654,10 @@ namespace FourSlashInterface {
this.state.verifyCurrentSignatureHelpIs(expected);
}
public noErrors() {
this.state.verifyNoErrors();
}
public numberOfErrorsInCurrentFile(expected: number) {
this.state.verifyNumberOfErrorsInCurrentFile(expected);
}
@@ -3625,8 +3754,12 @@ namespace FourSlashInterface {
this.state.verifyRangesAreOccurrences(isWriteAccess);
}
public rangesAreRenameLocations(findInStrings = false, findInComments = false) {
this.state.verifyRangesAreRenameLocations(findInStrings, findInComments);
public rangesWithSameTextAreRenameLocations() {
this.state.verifyRangesWithSameTextAreRenameLocations();
}
public rangesAreRenameLocations(options?: FourSlash.Range[] | { findInStrings?: boolean, findInComments?: boolean, ranges?: FourSlash.Range[] }) {
this.state.verifyRangesAreRenameLocations(options);
}
public rangesAreDocumentHighlights(ranges?: FourSlash.Range[]) {
@@ -3637,8 +3770,8 @@ namespace FourSlashInterface {
this.state.verifyRangesWithSameTextAreDocumentHighlights();
}
public completionEntryDetailIs(entryName: string, text: string, documentation?: string, kind?: string) {
this.state.verifyCompletionEntryDetails(entryName, text, documentation, kind);
public completionEntryDetailIs(entryName: string, text: string, documentation?: string, kind?: string, tags?: ts.JSDocTagInfo[]) {
this.state.verifyCompletionEntryDetails(entryName, text, documentation, kind, tags);
}
/**
@@ -3663,13 +3796,13 @@ namespace FourSlashInterface {
this.state.verifyRenameInfoFailed(message);
}
public renameLocations(findInStrings: boolean, findInComments: boolean, ranges?: FourSlash.Range[]) {
this.state.verifyRenameLocations(findInStrings, findInComments, ranges);
public renameLocations(startRanges: FourSlash.Range | FourSlash.Range[], options: FourSlash.Range[] | { findInStrings?: boolean, findInComments?: boolean, ranges: FourSlash.Range[] }) {
this.state.verifyRenameLocations(startRanges, options);
}
public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: { start: number; length: number; },
displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[]) {
this.state.verifyQuickInfoDisplayParts(kind, kindModifiers, textSpan, displayParts, documentation);
displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[], tags: ts.JSDocTagInfo[]) {
this.state.verifyQuickInfoDisplayParts(kind, kindModifiers, textSpan, displayParts, documentation, tags);
}
public getSyntacticDiagnostics(expected: string) {
@@ -3753,11 +3886,11 @@ namespace FourSlashInterface {
}
public printCurrentFileStateWithWhitespace() {
this.state.printCurrentFileState(/*makeWhitespaceVisible*/true);
this.state.printCurrentFileState(/*makeWhitespaceVisible*/ true);
}
public printCurrentFileStateWithoutCaret() {
this.state.printCurrentFileState(/*makeWhitespaceVisible*/false, /*makeCaretVisible*/false);
this.state.printCurrentFileState(/*makeWhitespaceVisible*/ false, /*makeCaretVisible*/ false);
}
public printCurrentQuickInfo() {
@@ -3772,6 +3905,10 @@ namespace FourSlashInterface {
this.state.printCompletionListMembers();
}
public printAvailableCodeFixes() {
this.state.printAvailableCodeFixes();
}
public printBreakpointLocation(pos: number) {
this.state.printBreakpointLocation(pos);
}
+3 -3
View File
@@ -191,7 +191,7 @@ namespace Utils {
for (const childName in node) {
if (childName === "parent" || childName === "nextContainer" || childName === "modifiers" || childName === "externalModuleIndicator" ||
// for now ignore jsdoc comments
childName === "jsDocComment") {
childName === "jsDocComment" || childName === "checkJsDirective") {
continue;
}
const child = (<any>node)[childName];
@@ -1797,7 +1797,7 @@ namespace Harness {
if (currentFileContent === undefined) {
currentFileContent = "";
}
else {
else if (currentFileContent !== "") {
// End-of-line
currentFileContent = currentFileContent + "\n";
}
@@ -1933,7 +1933,7 @@ namespace Harness {
}
const parentDirectory = IO.directoryName(dirName);
if (parentDirectory != "") {
if (parentDirectory !== "") {
createDirectoryStructure(parentDirectory);
}
IO.createDirectory(dirName);
+16 -12
View File
@@ -169,9 +169,9 @@ namespace Harness.LanguageService {
}
/**
* @param line 0 based index
* @param col 0 based index
*/
* @param line 0 based index
* @param col 0 based index
*/
public positionToLineAndCharacter(fileName: string, position: number): ts.LineAndCharacter {
const script: ScriptInfo = this.getScriptInfo(fileName);
assert.isOk(script);
@@ -210,7 +210,7 @@ namespace Harness.LanguageService {
}
readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[] {
return ts.matchFiles(path, extensions, exclude, include,
/*useCaseSensitiveFileNames*/false,
/*useCaseSensitiveFileNames*/ false,
this.getCurrentDirectory(),
(p) => this.virtualFileSystem.getAccessibleFileSystemEntries(p));
}
@@ -795,7 +795,7 @@ namespace Harness.LanguageService {
function makeDefaultProxy(info: ts.server.PluginCreateInfo) {
// tslint:disable-next-line:no-null-keyword
const proxy = Object.create(null);
const proxy = Object.create(/*prototype*/ null);
const langSvc: any = info.languageService;
for (const k of Object.keys(langSvc)) {
proxy[k] = function () {
@@ -818,13 +818,17 @@ namespace Harness.LanguageService {
// This host is just a proxy for the clientHost, it uses the client
// host to answer server queries about files on disk
const serverHost = new SessionServerHost(clientHost);
const server = new ts.server.Session(serverHost,
ts.server.nullCancellationToken,
/*useOneInferredProject*/ false,
/*typingsInstaller*/ undefined,
Utils.byteLength,
process.hrtime, serverHost,
/*canUseEvents*/ true);
const opts: ts.server.SessionOptions = {
host: serverHost,
cancellationToken: ts.server.nullCancellationToken,
useSingleInferredProject: false,
typingsInstaller: undefined,
byteLength: Utils.byteLength,
hrtime: process.hrtime,
logger: serverHost,
canUseEvents: true
};
const server = new ts.server.Session(opts);
// Fake the connection between the client and the server
serverHost.writeMessage = client.onMessage.bind(client);
+1 -2
View File
@@ -111,8 +111,7 @@ class ProjectRunner extends RunnerBase {
else if (url.indexOf(diskProjectPath) === 0) {
// Replace the disk specific path into the project root path
url = url.substr(diskProjectPath.length);
// TODO: should be '!=='?
if (url.charCodeAt(0) != ts.CharacterCodes.slash) {
if (url.charCodeAt(0) !== ts.CharacterCodes.slash) {
url = "/" + url;
}
}
+5 -5
View File
@@ -50,11 +50,11 @@ namespace Harness.SourceMapRecorder {
return true;
}
if (sourceMapMappings.charAt(decodingIndex) == ",") {
if (sourceMapMappings.charAt(decodingIndex) === ",") {
return true;
}
if (sourceMapMappings.charAt(decodingIndex) == ";") {
if (sourceMapMappings.charAt(decodingIndex) === ";") {
return true;
}
@@ -117,7 +117,7 @@ namespace Harness.SourceMapRecorder {
}
while (decodingIndex < sourceMapMappings.length) {
if (sourceMapMappings.charAt(decodingIndex) == ";") {
if (sourceMapMappings.charAt(decodingIndex) === ";") {
// New line
decodeOfEncodedMapping.emittedLine++;
decodeOfEncodedMapping.emittedColumn = 1;
@@ -125,7 +125,7 @@ namespace Harness.SourceMapRecorder {
continue;
}
if (sourceMapMappings.charAt(decodingIndex) == ",") {
if (sourceMapMappings.charAt(decodingIndex) === ",") {
// Next entry is on same line - no action needed
decodingIndex++;
continue;
@@ -422,7 +422,7 @@ namespace Harness.SourceMapRecorder {
const jsFileText = getTextOfLine(currentJsLine, jsLineMap, jsFile.code);
if (prevEmittedCol < jsFileText.length) {
// There is remaining text on this line that will be part of next source span so write marker that continues
writeSourceMapMarker(undefined, spansOnSingleLine.length, /*endColumn*/ jsFileText.length, /*endContinues*/ true);
writeSourceMapMarker(/*currentSpan*/ undefined, spansOnSingleLine.length, /*endColumn*/ jsFileText.length, /*endContinues*/ true);
}
// Emit Source text
+3 -2
View File
@@ -1,4 +1,4 @@
{
{
"extends": "../tsconfig-base",
"compilerOptions": {
"removeComments": false,
@@ -81,6 +81,7 @@
"../services/codefixes/helpers.ts",
"../services/codefixes/importFixes.ts",
"../services/codefixes/unusedIdentifierFixes.ts",
"../services/codefixes/disableJsDiagnostics.ts",
"harness.ts",
"sourceMapRecorder.ts",
@@ -95,7 +96,7 @@
"rwcRunner.ts",
"test262Runner.ts",
"runner.ts",
"../server/protocol.d.ts",
"../server/protocol.ts",
"../server/session.ts",
"../server/client.ts",
"../server/editorServices.ts",
+11 -3
View File
@@ -64,8 +64,16 @@ namespace ts {
getLogFileName: (): string => undefined
};
const projectService = new server.ProjectService(serverHost, logger, { isCancellationRequested: () => false }, /*useOneInferredProject*/ false, /*typingsInstaller*/ undefined);
const rootScriptInfo = projectService.getOrCreateScriptInfo(rootFile, /* openedByClient */true, /*containingProject*/ undefined);
const svcOpts: server.ProjectServiceOptions = {
host: serverHost,
logger,
cancellationToken: { isCancellationRequested: () => false },
useSingleInferredProject: false,
typingsInstaller: undefined
};
const projectService = new server.ProjectService(svcOpts);
const rootScriptInfo = projectService.getOrCreateScriptInfo(rootFile, /* openedByClient */ true, /*containingProject*/ undefined);
const project = projectService.createInferredProjectWithRootFileIfNecessary(rootScriptInfo);
project.setCompilerOptions({ module: ts.ModuleKind.AMD } );
return {
@@ -203,4 +211,4 @@ namespace ts {
assert.isTrue(diags.length === 0);
});
});
}
}
+50 -13
View File
@@ -31,6 +31,20 @@ namespace ts.projectSystem {
}
}
function createSession(host: server.ServerHost, typingsInstaller?: server.ITypingsInstaller): server.Session {
const opts: server.SessionOptions = {
host,
cancellationToken: nullCancellationToken,
useSingleInferredProject: false,
typingsInstaller: typingsInstaller || server.nullTypingsInstaller,
byteLength: Utils.byteLength,
hrtime: process.hrtime,
logger: nullLogger,
canUseEvents: false
};
return new server.Session(opts);
}
describe("for configured projects", () => {
let moduleFile1: FileOrFolder;
let file1Consumer1: FileOrFolder;
@@ -113,7 +127,7 @@ namespace ts.projectSystem {
it("should contains only itself if a module file's shape didn't change, and all files referencing it if its shape changed", () => {
const host = createServerHost([moduleFile1, file1Consumer1, file1Consumer2, globalFile3, moduleFile2, configFile, libFile]);
const typingsInstaller = createTestTypingsInstaller(host);
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
const session = createSession(host, typingsInstaller);
openFilesForSession([moduleFile1, file1Consumer1], session);
@@ -138,7 +152,7 @@ namespace ts.projectSystem {
it("should be up-to-date with the reference map changes", () => {
const host = createServerHost([moduleFile1, file1Consumer1, file1Consumer2, globalFile3, moduleFile2, configFile, libFile]);
const typingsInstaller = createTestTypingsInstaller(host);
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
const session = createSession(host, typingsInstaller);
openFilesForSession([moduleFile1, file1Consumer1], session);
@@ -185,7 +199,7 @@ namespace ts.projectSystem {
it("should be up-to-date with changes made in non-open files", () => {
const host = createServerHost([moduleFile1, file1Consumer1, file1Consumer2, globalFile3, moduleFile2, configFile, libFile]);
const typingsInstaller = createTestTypingsInstaller(host);
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
const session = createSession(host, typingsInstaller);
openFilesForSession([moduleFile1], session);
@@ -203,7 +217,7 @@ namespace ts.projectSystem {
it("should be up-to-date with deleted files", () => {
const host = createServerHost([moduleFile1, file1Consumer1, file1Consumer2, globalFile3, moduleFile2, configFile, libFile]);
const typingsInstaller = createTestTypingsInstaller(host);
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
const session = createSession(host, typingsInstaller);
openFilesForSession([moduleFile1], session);
sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer2] }]);
@@ -218,7 +232,7 @@ namespace ts.projectSystem {
it("should be up-to-date with newly created files", () => {
const host = createServerHost([moduleFile1, file1Consumer1, file1Consumer2, globalFile3, moduleFile2, configFile, libFile]);
const typingsInstaller = createTestTypingsInstaller(host);
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
const session = createSession(host, typingsInstaller);
openFilesForSession([moduleFile1], session);
sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer2] }]);
@@ -255,7 +269,7 @@ namespace ts.projectSystem {
const host = createServerHost([moduleFile1, file1Consumer1, configFile, libFile]);
const typingsInstaller = createTestTypingsInstaller(host);
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
const session = createSession(host, typingsInstaller);
openFilesForSession([moduleFile1, file1Consumer1], session);
sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1] }]);
@@ -272,7 +286,7 @@ namespace ts.projectSystem {
it("should return all files if a global file changed shape", () => {
const host = createServerHost([moduleFile1, file1Consumer1, file1Consumer2, globalFile3, moduleFile2, configFile, libFile]);
const typingsInstaller = createTestTypingsInstaller(host);
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
const session = createSession(host, typingsInstaller);
openFilesForSession([globalFile3], session);
const changeGlobalFile3ShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
@@ -298,11 +312,34 @@ namespace ts.projectSystem {
const host = createServerHost([moduleFile1, file1Consumer1, file1Consumer2, configFile, libFile]);
const typingsInstaller = createTestTypingsInstaller(host);
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
const session = createSession(host, typingsInstaller);
openFilesForSession([moduleFile1], session);
sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, []);
});
it("should save when compileOnSave is enabled in base tsconfig.json", () => {
configFile = {
path: "/a/b/tsconfig.json",
content: `{
"extends": "/a/tsconfig.json"
}`
};
const configFile2: FileOrFolder = {
path: "/a/tsconfig.json",
content: `{
"compileOnSave": true
}`
};
const host = createServerHost([moduleFile1, file1Consumer1, file1Consumer2, configFile2, configFile, libFile]);
const typingsInstaller = createTestTypingsInstaller(host);
const session = createSession(host, typingsInstaller);
openFilesForSession([moduleFile1, file1Consumer1], session);
sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer2] }]);
});
it("should always return the file itself if '--isolatedModules' is specified", () => {
configFile = {
path: "/a/b/tsconfig.json",
@@ -316,7 +353,7 @@ namespace ts.projectSystem {
const host = createServerHost([moduleFile1, file1Consumer1, configFile, libFile]);
const typingsInstaller = createTestTypingsInstaller(host);
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
const session = createSession(host, typingsInstaller);
openFilesForSession([moduleFile1], session);
const file1ChangeShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
@@ -345,7 +382,7 @@ namespace ts.projectSystem {
const host = createServerHost([moduleFile1, file1Consumer1, configFile, libFile]);
const typingsInstaller = createTestTypingsInstaller(host);
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
const session = createSession(host, typingsInstaller);
openFilesForSession([moduleFile1], session);
const file1ChangeShapeRequest = makeSessionRequest<server.protocol.ChangeRequestArgs>(CommandNames.Change, {
@@ -367,7 +404,7 @@ namespace ts.projectSystem {
};
const host = createServerHost([moduleFile1, file1Consumer1, file1Consumer1Consumer1, globalFile3, configFile, libFile]);
const typingsInstaller = createTestTypingsInstaller(host);
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
const session = createSession(host, typingsInstaller);
openFilesForSession([moduleFile1, file1Consumer1], session);
sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer1Consumer1] }]);
@@ -400,7 +437,7 @@ namespace ts.projectSystem {
};
const host = createServerHost([file1, file2, configFile]);
const typingsInstaller = createTestTypingsInstaller(host);
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
const session = createSession(host, typingsInstaller);
openFilesForSession([file1, file2], session);
const file1AffectedListRequest = makeSessionRequest<server.protocol.FileRequestArgs>(CommandNames.CompileOnSaveAffectedFileList, { file: file1.path });
@@ -513,7 +550,7 @@ namespace ts.projectSystem {
};
const host = createServerHost([file1, file2, configFile, libFile], { newLine: "\r\n" });
const typingsInstaller = createTestTypingsInstaller(host);
const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false);
const session = createSession(host, typingsInstaller);
openFilesForSession([file1, file2], session);
const compileFileRequest = makeSessionRequest<server.protocol.CompileOnSaveEmitFileRequestArgs>(CommandNames.CompileOnSaveEmitFile, { file: file1.path, projectFileName: configFile.path });
+79 -78
View File
@@ -2,84 +2,84 @@
/// <reference path="..\virtualFileSystem.ts" />
namespace ts {
const testContents = createMapFromTemplate({
"/dev/tsconfig.json": `{
"extends": "./configs/base",
"files": [
"main.ts",
"supplemental.ts"
]
}`,
"/dev/tsconfig.nostrictnull.json": `{
"extends": "./tsconfig",
"compilerOptions": {
"strictNullChecks": false
}
}`,
"/dev/configs/base.json": `{
"compilerOptions": {
"allowJs": true,
"noImplicitAny": true,
"strictNullChecks": true
}
}`,
"/dev/configs/tests.json": `{
"compilerOptions": {
"preserveConstEnums": true,
"removeComments": false,
"sourceMap": true
},
"exclude": [
"../tests/baselines",
"../tests/scenarios"
],
"include": [
"../tests/**/*.ts"
]
}`,
"/dev/circular.json": `{
"extends": "./circular2",
"compilerOptions": {
"module": "amd"
}
}`,
"/dev/circular2.json": `{
"extends": "./circular",
"compilerOptions": {
"module": "commonjs"
}
}`,
"/dev/missing.json": `{
"extends": "./missing2",
"compilerOptions": {
"types": []
}
}`,
"/dev/failure.json": `{
"extends": "./failure2.json",
"compilerOptions": {
"typeRoots": []
}
}`,
"/dev/failure2.json": `{
"excludes": ["*.js"]
}`,
"/dev/configs/first.json": `{
"extends": "./base",
"compilerOptions": {
"module": "commonjs"
},
"files": ["../main.ts"]
}`,
"/dev/configs/second.json": `{
"extends": "./base",
"compilerOptions": {
"module": "amd"
},
"include": ["../supplemental.*"]
}`,
"/dev/extends.json": `{ "extends": 42 }`,
"/dev/extends2.json": `{ "extends": "configs/base" }`,
const testContentsJson = createMapFromTemplate({
"/dev/tsconfig.json": {
extends: "./configs/base",
files: [
"main.ts",
"supplemental.ts"
]
},
"/dev/tsconfig.nostrictnull.json": {
extends: "./tsconfig",
compilerOptions: {
strictNullChecks: false
}
},
"/dev/configs/base.json": {
compilerOptions: {
allowJs: true,
noImplicitAny: true,
strictNullChecks: true
}
},
"/dev/configs/tests.json": {
compilerOptions: {
"preserveConstEnums": true,
"removeComments": false,
"sourceMap": true
},
exclude: [
"../tests/baselines",
"../tests/scenarios"
],
include: [
"../tests/**/*.ts"
]
},
"/dev/circular.json": {
extends: "./circular2",
compilerOptions: {
module: "amd"
}
},
"/dev/circular2.json": {
extends: "./circular",
compilerOptions: {
module: "commonjs"
}
},
"/dev/missing.json": {
extends: "./missing2",
compilerOptions: {
"types": []
}
},
"/dev/failure.json": {
extends: "./failure2.json",
compilerOptions: {
typeRoots: []
}
},
"/dev/failure2.json": {
excludes: ["*.js"]
},
"/dev/configs/first.json": {
extends: "./base",
compilerOptions: {
module: "commonjs"
},
files: ["../main.ts"]
},
"/dev/configs/second.json": {
extends: "./base",
compilerOptions: {
module: "amd"
},
include: ["../supplemental.*"]
},
"/dev/extends.json": { extends: 42 },
"/dev/extends2.json": { extends: "configs/base" },
"/dev/main.ts": "",
"/dev/supplemental.ts": "",
"/dev/tests/unit/spec.ts": "",
@@ -87,6 +87,7 @@ namespace ts {
"/dev/tests/scenarios/first.json": "",
"/dev/tests/baselines/first/output.ts": ""
});
const testContents = mapEntries(testContentsJson, (k, v) => [k, typeof v === "string" ? v : JSON.stringify(v)]);
const caseInsensitiveBasePath = "c:/dev/";
const caseInsensitiveHost = new Utils.MockParseConfigHost(caseInsensitiveBasePath, /*useCaseSensitiveFileNames*/ false, mapEntries(testContents, (key, content) => [`c:${key}`, content]));
+1 -1
View File
@@ -22,7 +22,7 @@ namespace ts {
});
it("Converts simple code snippet correctly", () => {
runTest(`/// <reference path="file.ts" />
runTest(`/// <reference path="file.ts" />
var x: string = "string";
console.log(x);`);
});
+2 -13
View File
@@ -6,22 +6,11 @@ namespace ts {
function initTSConfigCorrectly(name: string, commandLinesArgs: string[]) {
describe(name, () => {
const commandLine = parseCommandLine(commandLinesArgs);
const initResult = generateTSConfig(commandLine.options, commandLine.fileNames);
const initResult = generateTSConfig(commandLine.options, commandLine.fileNames, "\n");
const outputFileName = `tsConfig/${name.replace(/[^a-z0-9\-. ]/ig, "")}/tsconfig.json`;
it(`Correct output for ${outputFileName}`, () => {
Harness.Baseline.runBaseline(outputFileName, () => {
if (initResult) {
// normalize line endings
return initResult.replace(new RegExp(sys.newLine, "g"), "\n");
}
else {
// This can happen if compiler recieve invalid compiler-options
/* tslint:disable:no-null-keyword */
return null;
/* tslint:enable:no-null-keyword */
}
});
Harness.Baseline.runBaseline(outputFileName, () => initResult);
});
});
}
+11 -11
View File
@@ -212,7 +212,7 @@ namespace ts {
fileNames: [],
wildcardDirectories: {},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, /*existingOptions*/ undefined, caseInsensitiveTsconfigPath);
assertParsed(actual, expected);
});
it("with missing files are excluded", () => {
@@ -231,7 +231,7 @@ namespace ts {
fileNames: [],
wildcardDirectories: {},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, /*existingOptions*/ undefined, caseInsensitiveTsconfigPath);
assertParsed(actual, expected);
});
it("with literal excludes", () => {
@@ -584,7 +584,7 @@ namespace ts {
"c:/dev": ts.WatchDirectoryFlags.Recursive
},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, /*existingOptions*/ undefined, caseInsensitiveTsconfigPath);
assertParsed(actual, expected);
});
it("always include literal files", () => {
@@ -728,7 +728,7 @@ namespace ts {
"c:/dev/js": ts.WatchDirectoryFlags.None
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, /*existingOptions*/ undefined, caseInsensitiveTsconfigPath);
assertParsed(actual, expected);
});
it("include .js files when allowJs=true", () => {
@@ -846,7 +846,7 @@ namespace ts {
fileNames: [],
wildcardDirectories: {}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, /*existingOptions*/ undefined, caseInsensitiveTsconfigPath);
assertParsed(actual, expected);
});
it("include files with .. in their name", () => {
@@ -1087,7 +1087,7 @@ namespace ts {
fileNames: [],
wildcardDirectories: {}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, /*existingOptions*/ undefined, caseInsensitiveTsconfigPath);
assertParsed(actual, expected);
});
it("in excludes", () => {
@@ -1108,7 +1108,7 @@ namespace ts {
fileNames: [],
wildcardDirectories: {}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, /*existingOptions*/ undefined, caseInsensitiveTsconfigPath);
assertParsed(actual, expected);
});
});
@@ -1129,7 +1129,7 @@ namespace ts {
fileNames: [],
wildcardDirectories: {}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, /*existingOptions*/ undefined, caseInsensitiveTsconfigPath);
assertParsed(actual, expected);
});
it("in excludes", () => {
@@ -1178,7 +1178,7 @@ namespace ts {
fileNames: [],
wildcardDirectories: {}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, /*existingOptions*/ undefined, caseInsensitiveTsconfigPath);
assertParsed(actual, expected);
});
@@ -1198,7 +1198,7 @@ namespace ts {
fileNames: [],
wildcardDirectories: {}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, /*existingOptions*/ undefined, caseInsensitiveTsconfigPath);
assertParsed(actual, expected);
});
@@ -1382,7 +1382,7 @@ namespace ts {
fileNames: [],
wildcardDirectories: {}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath, /*existingOptions*/ undefined, caseInsensitiveTsconfigPath);
assertParsed(actual, expected);
});
});
+5 -7
View File
@@ -144,18 +144,16 @@ namespace ts {
const resolution = nodeModuleNameResolver("b", containingFile.name, {}, createModuleResolutionHost(hasDirectoryExists, containingFile, packageJson, moduleFile, indexFile));
checkResolvedModule(resolution.resolvedModule, createResolvedModule(indexPath, /*isExternalLibraryImport*/true));
checkResolvedModule(resolution.resolvedModule, createResolvedModule(indexPath, /*isExternalLibraryImport*/ true));
}
}
it("module name as directory - handle invalid 'typings'", () => {
testTypingsIgnored(["a", "b"]);
testTypingsIgnored({ "a": "b" });
testTypingsIgnored(true);
/* tslint:disable no-null-keyword */
testTypingsIgnored(null);
/* tslint:enable no-null-keyword */
testTypingsIgnored(undefined);
testTypingsIgnored(/*typings*/ true);
testTypingsIgnored(/*typings*/ null); // tslint:disable-line no-null-keyword
testTypingsIgnored(/*typings*/ undefined);
});
it("module name as directory - load index.d.ts", () => {
test(/*hasDirectoryExists*/ false);
@@ -532,7 +530,7 @@ import b = require("./moduleB");
check("m1", main, m1);
check("m2", main, m2);
check("m3", main, m3Typings);
check("m4", main, m4, /*isExternalLibraryImport*/true);
check("m4", main, m4, /*isExternalLibraryImport*/ true);
function check(name: string, caller: File, expected: File, isExternalLibraryImport = false) {
const result = resolveModuleName(name, caller.name, options, host);
+5
View File
@@ -52,6 +52,9 @@ namespace ts {
printsCorrectly("default", {}, printer => printer.printFile(sourceFile));
printsCorrectly("removeComments", { removeComments: true }, printer => printer.printFile(sourceFile));
// github #14948
printsCorrectly("templateLiteral", {}, printer => printer.printFile(createSourceFile("source.ts", "let greeting = `Hi ${name}, how are you?`;", ScriptTarget.ES2017)));
});
describe("printBundle", () => {
@@ -77,6 +80,7 @@ namespace ts {
describe("printNode", () => {
const printsCorrectly = makePrintsCorrectly("printsNodeCorrectly");
const sourceFile = createSourceFile("source.ts", "", ScriptTarget.ES2015);
// tslint:disable boolean-trivia
const syntheticNode = createClassDeclaration(
undefined,
undefined,
@@ -94,6 +98,7 @@ namespace ts {
)
])
);
// tslint:enable boolean-trivia
printsCorrectly("class", {}, printer => printer.printNode(EmitHint.Unspecified, syntheticNode, sourceFile));
});
});
@@ -323,7 +323,7 @@ namespace ts {
const program_1 = newProgram(files, ["a.ts"], options);
checkResolvedModulesCache(program_1, "a.ts", createMapFromTemplate({ "b": createResolvedModule("b.ts") }));
checkResolvedModulesCache(program_1, "b.ts", undefined);
checkResolvedModulesCache(program_1, "b.ts", /*expectedContent*/ undefined);
const program_2 = updateProgram(program_1, ["a.ts"], options, files => {
files[0].text = files[0].text.updateProgram("var x = 2");
@@ -332,14 +332,14 @@ namespace ts {
// content of resolution cache should not change
checkResolvedModulesCache(program_1, "a.ts", createMapFromTemplate({ "b": createResolvedModule("b.ts") }));
checkResolvedModulesCache(program_1, "b.ts", undefined);
checkResolvedModulesCache(program_1, "b.ts", /*expectedContent*/ undefined);
// imports has changed - program is not reused
const program_3 = updateProgram(program_2, ["a.ts"], options, files => {
files[0].text = files[0].text.updateImportsAndExports("");
});
assert.isTrue(!program_2.structureIsReused);
checkResolvedModulesCache(program_3, "a.ts", undefined);
checkResolvedModulesCache(program_3, "a.ts", /*expectedContent*/ undefined);
const program_4 = updateProgram(program_3, ["a.ts"], options, files => {
const newImports = `import x from 'b'
@@ -360,7 +360,7 @@ namespace ts {
const program_1 = newProgram(files, ["/a.ts"], options);
checkResolvedTypeDirectivesCache(program_1, "/a.ts", createMapFromTemplate({ "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } }));
checkResolvedTypeDirectivesCache(program_1, "/types/typedefs/index.d.ts", undefined);
checkResolvedTypeDirectivesCache(program_1, "/types/typedefs/index.d.ts", /*expectedContent*/ undefined);
const program_2 = updateProgram(program_1, ["/a.ts"], options, files => {
files[0].text = files[0].text.updateProgram("var x = 2");
@@ -369,7 +369,7 @@ namespace ts {
// content of resolution cache should not change
checkResolvedTypeDirectivesCache(program_1, "/a.ts", createMapFromTemplate({ "typedefs": { resolvedFileName: "/types/typedefs/index.d.ts", primary: true } }));
checkResolvedTypeDirectivesCache(program_1, "/types/typedefs/index.d.ts", undefined);
checkResolvedTypeDirectivesCache(program_1, "/types/typedefs/index.d.ts", /*expectedContent*/ undefined);
// type reference directives has changed - program is not reused
const program_3 = updateProgram(program_2, ["/a.ts"], options, files => {
@@ -377,7 +377,7 @@ namespace ts {
});
assert.isTrue(!program_2.structureIsReused);
checkResolvedTypeDirectivesCache(program_3, "/a.ts", undefined);
checkResolvedTypeDirectivesCache(program_3, "/a.ts", /*expectedContent*/ undefined);
updateProgram(program_3, ["/a.ts"], options, files => {
const newReferences = `/// <reference types="typedefs"/>
@@ -34,7 +34,7 @@ describe("PreProcessFile:", function () {
describe("Test preProcessFiles,", function () {
it("Correctly return referenced files from triple slash", function () {
test("///<reference path = \"refFile1.ts\" />" + "\n" + "///<reference path =\"refFile2.ts\"/>" + "\n" + "///<reference path=\"refFile3.ts\" />" + "\n" + "///<reference path= \"..\\refFile4d.ts\" />",
/*readImportFile*/true,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [{ fileName: "refFile1.ts", pos: 0, end: 37 }, { fileName: "refFile2.ts", pos: 38, end: 73 },
@@ -48,7 +48,7 @@ describe("PreProcessFile:", function () {
it("Do not return reference path because of invalid triple-slash syntax", function () {
test("///<reference path\"refFile1.ts\" />" + "\n" + "///<reference path =\"refFile2.ts\">" + "\n" + "///<referencepath=\"refFile3.ts\" />" + "\n" + "///<reference pat= \"refFile4d.ts\" />",
/*readImportFile*/true,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: <ts.FileReference[]>[],
@@ -61,7 +61,7 @@ describe("PreProcessFile:", function () {
it("Correctly return imported files", function () {
test("import i1 = require(\"r1.ts\"); import i2 =require(\"r2.ts\"); import i3= require(\"r3.ts\"); import i4=require(\"r4.ts\"); import i5 = require (\"r5.ts\");",
/*readImportFile*/true,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: <ts.FileReference[]>[],
@@ -88,7 +88,7 @@ describe("PreProcessFile:", function () {
it("Do not return import path because of invalid import syntax", function () {
test("import i1 require(\"r1.ts\"); import = require(\"r2.ts\") import i3= require(\"r3.ts\"); import i5",
/*readImportFile*/true,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: <ts.FileReference[]>[],
@@ -101,7 +101,7 @@ describe("PreProcessFile:", function () {
it("Correctly return referenced files and import files", function () {
test("///<reference path=\"refFile1.ts\" />" + "\n" + "///<reference path =\"refFile2.ts\"/>" + "\n" + "import i1 = require(\"r1.ts\"); import i2 =require(\"r2.ts\");",
/*readImportFile*/true,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [{ fileName: "refFile1.ts", pos: 0, end: 35 }, { fileName: "refFile2.ts", pos: 36, end: 71 }],
@@ -114,7 +114,7 @@ describe("PreProcessFile:", function () {
it("Correctly return referenced files and import files even with some invalid syntax", function () {
test("///<reference path=\"refFile1.ts\" />" + "\n" + "///<reference path \"refFile2.ts\"/>" + "\n" + "import i1 = require(\"r1.ts\"); import = require(\"r2.ts\"); import i2 = require(\"r3.ts\");",
/*readImportFile*/true,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [{ fileName: "refFile1.ts", pos: 0, end: 35 }],
@@ -133,7 +133,7 @@ describe("PreProcessFile:", function () {
"import {a as A} from \"m5\";" + "\n" +
"import {a as A, b, c as C} from \"m6\";" + "\n" +
"import def , {a, b, c as C} from \"m7\";" + "\n",
/*readImportFile*/true,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
@@ -157,7 +157,7 @@ describe("PreProcessFile:", function () {
"export {a} from \"m2\";" + "\n" +
"export {a as A} from \"m3\";" + "\n" +
"export {a as A, b, c as C} from \"m4\";" + "\n",
/*readImportFile*/true,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
@@ -194,7 +194,7 @@ describe("PreProcessFile:", function () {
it("Correctly handles export import declarations", function () {
test("export import a = require(\"m1\");",
/*readImportFile*/true,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ false,
{
referencedFiles: [],
@@ -213,7 +213,7 @@ describe("PreProcessFile:", function () {
foo(require('m3'));
var z = { f: require('m4') }
`,
/*readImportFile*/true,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ true,
{
referencedFiles: [],
@@ -233,7 +233,7 @@ describe("PreProcessFile:", function () {
define(["mod1", "mod2"], (m1, m2) => {
});
`,
/*readImportFile*/true,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ true,
{
referencedFiles: [],
@@ -251,7 +251,7 @@ describe("PreProcessFile:", function () {
define("mod", ["mod1", "mod2"], (m1, m2) => {
});
`,
/*readImportFile*/true,
/*readImportFile*/ true,
/*detectJavaScriptImports*/ true,
{
referencedFiles: [],
+38 -6
View File
@@ -50,8 +50,22 @@ namespace ts.server {
let session: TestSession;
let lastSent: protocol.Message;
function createSession(): TestSession {
const opts: server.SessionOptions = {
host: mockHost,
cancellationToken: nullCancellationToken,
useSingleInferredProject: false,
typingsInstaller: undefined,
byteLength: Utils.byteLength,
hrtime: process.hrtime,
logger: mockLogger,
canUseEvents: true
};
return new TestSession(opts);
}
beforeEach(() => {
session = new TestSession(mockHost, nullCancellationToken, /*useOneInferredProject*/ false, /*typingsInstaller*/ undefined, Utils.byteLength, process.hrtime, mockLogger, /*canUseEvents*/ true);
session = createSession();
session.send = (msg: protocol.Message) => {
lastSent = msg;
};
@@ -318,7 +332,16 @@ namespace ts.server {
lastSent: protocol.Message;
customHandler = "testhandler";
constructor() {
super(mockHost, nullCancellationToken, /*useOneInferredProject*/ false, /*typingsInstaller*/ undefined, Utils.byteLength, process.hrtime, mockLogger, /*canUseEvents*/ true);
super({
host: mockHost,
cancellationToken: nullCancellationToken,
useSingleInferredProject: false,
typingsInstaller: undefined,
byteLength: Utils.byteLength,
hrtime: process.hrtime,
logger: mockLogger,
canUseEvents: true
});
this.addProtocolHandler(this.customHandler, () => {
return { response: undefined, responseRequired: true };
});
@@ -326,7 +349,7 @@ namespace ts.server {
send(msg: protocol.Message) {
this.lastSent = msg;
}
};
}
it("can override methods such as send", () => {
const session = new TestSession();
@@ -367,7 +390,7 @@ namespace ts.server {
assert(this.projectService);
expect(this.projectService).to.be.instanceOf(ProjectService);
}
};
}
new ServiceSession();
});
});
@@ -376,7 +399,16 @@ namespace ts.server {
class InProcSession extends Session {
private queue: protocol.Request[] = [];
constructor(private client: InProcClient) {
super(mockHost, nullCancellationToken, /*useOneInferredProject*/ false, /*typingsInstaller*/ undefined, Utils.byteLength, process.hrtime, mockLogger, /*canUseEvents*/ true);
super({
host: mockHost,
cancellationToken: nullCancellationToken,
useSingleInferredProject: false,
typingsInstaller: undefined,
byteLength: Utils.byteLength,
hrtime: process.hrtime,
logger: mockLogger,
canUseEvents: true
});
this.addProtocolHandler("echo", (req: protocol.Request) => ({
response: req.arguments,
responseRequired: true
@@ -462,7 +494,7 @@ namespace ts.server {
});
this.callbacks[this.seq] = callback;
}
};
}
it("can be constructed and respond to commands", (done) => {
const cli = new InProcClient();
+225 -50
View File
@@ -17,6 +17,16 @@ namespace ts.projectSystem {
})
};
const customSafeList = {
path: <Path>"/typeMapList.json",
content: JSON.stringify({
"quack": {
"match": "/duckquack-(\\d+)\\.min\\.js",
"types": ["duck-types"]
},
})
};
export interface PostExecAction {
readonly success: boolean;
readonly callback: TI.RequestCompletedAction;
@@ -174,13 +184,25 @@ namespace ts.projectSystem {
request.type = "request";
return this.executeCommand(<T>request);
}
};
}
export function createSession(host: server.ServerHost, typingsInstaller?: server.ITypingsInstaller, projectServiceEventHandler?: server.ProjectServiceEventHandler, cancellationToken?: server.ServerCancellationToken) {
export function createSession(host: server.ServerHost, typingsInstaller?: server.ITypingsInstaller, projectServiceEventHandler?: server.ProjectServiceEventHandler, cancellationToken?: server.ServerCancellationToken, throttleWaitMilliseconds?: number) {
if (typingsInstaller === undefined) {
typingsInstaller = new TestTypingsInstaller("/a/data/", /*throttleLimit*/5, host);
}
return new TestSession(host, cancellationToken || server.nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ projectServiceEventHandler !== undefined, projectServiceEventHandler);
const opts: server.SessionOptions = {
host,
cancellationToken: cancellationToken || server.nullCancellationToken,
useSingleInferredProject: false,
typingsInstaller,
byteLength: Utils.byteLength,
hrtime: process.hrtime,
logger: nullLogger,
canUseEvents: projectServiceEventHandler !== undefined,
eventHandler: projectServiceEventHandler,
throttleWaitMilliseconds
};
return new TestSession(opts);
}
export interface CreateProjectServiceParameters {
@@ -195,7 +217,9 @@ namespace ts.projectSystem {
export class TestProjectService extends server.ProjectService {
constructor(host: server.ServerHost, logger: server.Logger, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean,
typingsInstaller: server.ITypingsInstaller, eventHandler: server.ProjectServiceEventHandler) {
super(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler);
super({
host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler
});
}
checkNumberOfProjects(count: { inferredProjects?: number, configuredProjects?: number, externalProjects?: number }) {
@@ -310,7 +334,7 @@ namespace ts.projectSystem {
register(cb: (...args: any[]) => void, args: any[]) {
const timeoutId = this.nextId;
this.nextId++;
this.map[timeoutId] = cb.bind(undefined, ...args);
this.map[timeoutId] = cb.bind(/*this*/ undefined, ...args);
return timeoutId;
}
unregister(id: any) {
@@ -381,7 +405,7 @@ namespace ts.projectSystem {
fileExists(s: string) {
const path = this.toPath(s);
return this.fs.contains(path) && isFile(this.fs.get(path));
};
}
getFileSize(s: string) {
const path = this.toPath(s);
@@ -476,11 +500,11 @@ namespace ts.projectSystem {
// TOOD: record and invoke callbacks to simulate timer events
setTimeout(callback: TimeOutCallback, _time: number, ...args: any[]) {
return this.timeoutCallbacks.register(callback, args);
};
}
clearTimeout(timeoutId: any): void {
this.timeoutCallbacks.unregister(timeoutId);
};
}
checkTimeoutQueueLength(expected: number) {
const callbacksCount = this.timeoutCallbacks.count();
@@ -501,7 +525,7 @@ namespace ts.projectSystem {
clearImmediate(timeoutId: any): void {
this.immediateCallbacks.unregister(timeoutId);
};
}
createDirectory(directoryName: string): void {
this.createFileOrFolder({ path: directoryName });
@@ -547,6 +571,49 @@ namespace ts.projectSystem {
readonly getEnvironmentVariable = notImplemented;
}
/**
* Test server cancellation token used to mock host token cancellation requests.
* The cancelAfterRequest constructor param specifies how many isCancellationRequested() calls
* should be made before canceling the token. The id of the request to cancel should be set with
* setRequestToCancel();
*/
export class TestServerCancellationToken implements server.ServerCancellationToken {
private currentId = -1;
private requestToCancel = -1;
private isCancellationRequestedCount = 0;
constructor(private cancelAfterRequest = 0) {
}
setRequest(requestId: number) {
this.currentId = requestId;
}
setRequestToCancel(requestId: number) {
this.resetToken();
this.requestToCancel = requestId;
}
resetRequest(requestId: number) {
assert.equal(requestId, this.currentId, "unexpected request id in cancellation");
this.currentId = undefined;
}
isCancellationRequested() {
this.isCancellationRequestedCount++;
// If the request id is the request to cancel and isCancellationRequestedCount
// has been met then cancel the request. Ex: cancel the request if it is a
// nav bar request & isCancellationRequested() has already been called three times.
return this.requestToCancel === this.currentId && this.isCancellationRequestedCount >= this.cancelAfterRequest;
}
resetToken() {
this.currentId = -1;
this.isCancellationRequestedCount = 0;
this.requestToCancel = -1;
}
}
export function makeSessionRequest<T>(command: string, args: T) {
const newRequest: protocol.Request = {
seq: 0,
@@ -764,7 +831,7 @@ namespace ts.projectSystem {
path: "/c/app.ts",
content: "let x = 1"
};
const makeProject = (f: FileOrFolder) => ({ projectFileName: f.path + ".csproj", rootFiles: [toExternalFile(f.path)], options: {} });
const makeProject = (f: FileOrFolder) => ({ projectFileName: f.path + ".csproj", rootFiles: [toExternalFile(f.path)], options: {} });
const p1 = makeProject(f1);
const p2 = makeProject(f2);
const p3 = makeProject(f3);
@@ -1402,6 +1469,66 @@ namespace ts.projectSystem {
checkProjectActualFiles(projectService.inferredProjects[1], [file3.path]);
});
it("ignores files excluded by a custom safe type list", () => {
const file1 = {
path: "/a/b/f1.ts",
content: "export let x = 5"
};
const office = {
path: "/lib/duckquack-3.min.js",
content: "whoa do @@ not parse me ok thanks!!!"
};
const host = createServerHost([customSafeList, file1, office]);
const projectService = createProjectService(host);
projectService.loadSafeList(customSafeList.path);
try {
projectService.openExternalProject({ projectFileName: "project", options: {}, rootFiles: toExternalFiles([file1.path, office.path]) });
const proj = projectService.externalProjects[0];
assert.deepEqual(proj.getFileNames(/*excludeFilesFromExternalLibraries*/ true), [file1.path]);
assert.deepEqual(proj.getTypeAcquisition().include, ["duck-types"]);
} finally {
projectService.resetSafeList();
}
});
it("ignores files excluded by the default type list", () => {
const file1 = {
path: "/a/b/f1.ts",
content: "export let x = 5"
};
const minFile = {
path: "/c/moment.min.js",
content: "unspecified"
};
const kendoFile1 = {
path: "/q/lib/kendo/kendo.all.min.js",
content: "unspecified"
};
const kendoFile2 = {
path: "/q/lib/kendo/kendo.ui.min.js",
content: "unspecified"
};
const officeFile1 = {
path: "/scripts/Office/1/excel-15.debug.js",
content: "unspecified"
};
const officeFile2 = {
path: "/scripts/Office/1/powerpoint.js",
content: "unspecified"
};
const files = [file1, minFile, kendoFile1, kendoFile2, officeFile1, officeFile2];
const host = createServerHost(files);
const projectService = createProjectService(host);
try {
projectService.openExternalProject({ projectFileName: "project", options: {}, rootFiles: toExternalFiles(files.map(f => f.path)) });
const proj = projectService.externalProjects[0];
assert.deepEqual(proj.getFileNames(/*excludeFilesFromExternalLibraries*/ true), [file1.path]);
assert.deepEqual(proj.getTypeAcquisition().include, ["kendo-ui", "office"]);
} finally {
projectService.resetSafeList();
}
});
it("open file become a part of configured project if it is referenced from root file", () => {
const file1 = {
path: "/a/b/f1.ts",
@@ -1652,7 +1779,7 @@ namespace ts.projectSystem {
checkProjectActualFiles(projectService.inferredProjects[1], [file2.path]);
});
it ("loading files with correct priority", () => {
it("loading files with correct priority", () => {
const f1 = {
path: "/a/main.ts",
content: "let x = 1"
@@ -1677,14 +1804,14 @@ namespace ts.projectSystem {
});
projectService.openClientFile(f1.path);
projectService.checkNumberOfProjects({ configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [ f1.path ]);
checkProjectActualFiles(projectService.configuredProjects[0], [f1.path]);
projectService.closeClientFile(f1.path);
projectService.openClientFile(f2.path);
projectService.checkNumberOfProjects({ configuredProjects: 1, inferredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [ f1.path ]);
checkProjectActualFiles(projectService.inferredProjects[0], [ f2.path ]);
checkProjectActualFiles(projectService.configuredProjects[0], [f1.path]);
checkProjectActualFiles(projectService.inferredProjects[0], [f2.path]);
});
it("tsconfig script block support", () => {
@@ -1720,9 +1847,9 @@ namespace ts.projectSystem {
// Open HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/[{ fileName: file2.path, hasMixedContent: true, scriptKind: ScriptKind.JS, content: `var hello = "hello";` }],
/*changedFiles*/undefined,
/*closedFiles*/undefined);
/*openFiles*/ [{ fileName: file2.path, hasMixedContent: true, scriptKind: ScriptKind.JS, content: `var hello = "hello";` }],
/*changedFiles*/ undefined,
/*closedFiles*/ undefined);
// Now HTML file is included in the project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
@@ -1735,9 +1862,9 @@ namespace ts.projectSystem {
// Close HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/undefined,
/*changedFiles*/undefined,
/*closedFiles*/[file2.path]);
/*openFiles*/ undefined,
/*changedFiles*/ undefined,
/*closedFiles*/ [file2.path]);
// HTML file is still included in project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
@@ -1802,7 +1929,7 @@ namespace ts.projectSystem {
// #3. Ensure no errors when compiler options aren't specified
const config3 = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({ })
content: JSON.stringify({})
};
host = createServerHost([file1, file2, config3, libFile], { executingFilePath: combinePaths(getDirectoryPath(libFile.path), "tsc.js") });
@@ -2195,12 +2322,12 @@ namespace ts.projectSystem {
projectService.openClientFile(f1.path, "let x = 1;\nlet y = 2;");
projectService.checkNumberOfProjects({ externalProjects: 1 });
projectService.externalProjects[0].getLanguageService(/*ensureSynchronized*/false).getNavigationBarItems(f1.path);
projectService.externalProjects[0].getLanguageService(/*ensureSynchronized*/ false).getNavigationBarItems(f1.path);
projectService.closeClientFile(f1.path);
projectService.openClientFile(f1.path);
projectService.checkNumberOfProjects({ externalProjects: 1 });
const navbar = projectService.externalProjects[0].getLanguageService(/*ensureSynchronized*/false).getNavigationBarItems(f1.path);
const navbar = projectService.externalProjects[0].getLanguageService(/*ensureSynchronized*/ false).getNavigationBarItems(f1.path);
assert.equal(navbar[0].spans[0].length, f1.content.length);
});
});
@@ -3101,7 +3228,7 @@ namespace ts.projectSystem {
checkNumberOfInferredProjects(projectService, 1);
const configuredProject = projectService.configuredProjects[0];
assert.isTrue(configuredProject.getFileNames().length == 0);
assert.isTrue(configuredProject.getFileNames().length === 0);
const inferredProject = projectService.inferredProjects[0];
assert.isTrue(inferredProject.containsFile(<server.NormalizedPath>file1.path));
@@ -3338,13 +3465,13 @@ namespace ts.projectSystem {
assert.equal((<protocol.CompileOnSaveAffectedFileListSingleProject[]>response)[0].projectUsesOutFile, expectedUsesOutFile, "usesOutFile");
}
it ("projectUsesOutFile should not be returned if not set", () => {
it("projectUsesOutFile should not be returned if not set", () => {
test({}, /*expectedUsesOutFile*/ false);
});
it ("projectUsesOutFile should be true if outFile is set", () => {
it("projectUsesOutFile should be true if outFile is set", () => {
test({ outFile: "/a/out.js" }, /*expectedUsesOutFile*/ true);
});
it ("projectUsesOutFile should be true if out is set", () => {
it("projectUsesOutFile should be true if out is set", () => {
test({ out: "/a/out.js" }, /*expectedUsesOutFile*/ true);
});
});
@@ -3384,6 +3511,7 @@ namespace ts.projectSystem {
},
resetRequest: noop
};
const session = createSession(host, /*typingsInstaller*/ undefined, /*projectServiceEventHandler*/ undefined, cancellationToken);
expectedRequestId = session.getNextSeq();
@@ -3422,24 +3550,9 @@ namespace ts.projectSystem {
})
};
let requestToCancel = -1;
const cancellationToken: server.ServerCancellationToken = (function(){
let currentId: number;
return <server.ServerCancellationToken>{
setRequest(requestId) {
currentId = requestId;
},
resetRequest(requestId) {
assert.equal(requestId, currentId, "unexpected request id in cancellation");
currentId = undefined;
},
isCancellationRequested() {
return requestToCancel === currentId;
}
};
})();
const cancellationToken = new TestServerCancellationToken();
const host = createServerHost([f1, config]);
const session = createSession(host, /*typingsInstaller*/ undefined, () => {}, cancellationToken);
const session = createSession(host, /*typingsInstaller*/ undefined, () => { }, cancellationToken);
{
session.executeCommandSeq(<protocol.OpenRequest>{
command: "open",
@@ -3472,13 +3585,13 @@ namespace ts.projectSystem {
host.clearOutput();
// cancel previously issued Geterr
requestToCancel = getErrId;
cancellationToken.setRequestToCancel(getErrId);
host.runQueuedTimeoutCallbacks();
assert.equal(host.getOutput().length, 1, "expect 1 message");
verifyRequestCompleted(getErrId, 0);
requestToCancel = -1;
cancellationToken.resetToken();
}
{
const getErrId = session.getNextSeq();
@@ -3495,12 +3608,12 @@ namespace ts.projectSystem {
assert.equal(e1.event, "syntaxDiag");
host.clearOutput();
requestToCancel = getErrId;
cancellationToken.setRequestToCancel(getErrId);
host.runQueuedImmediateCallbacks();
assert.equal(host.getOutput().length, 1, "expect 1 message");
verifyRequestCompleted(getErrId, 0);
requestToCancel = -1;
cancellationToken.resetToken();
}
{
const getErrId = session.getNextSeq();
@@ -3523,7 +3636,7 @@ namespace ts.projectSystem {
assert.equal(e2.event, "semanticDiag");
verifyRequestCompleted(getErrId, 1);
requestToCancel = -1;
cancellationToken.resetToken();
}
{
const getErr1 = session.getNextSeq();
@@ -3558,6 +3671,68 @@ namespace ts.projectSystem {
return JSON.parse(server.extractMessage(host.getOutput()[n]));
}
});
it("Lower priority tasks are cancellable", () => {
const f1 = {
path: "/a/app.ts",
content: `{ let x = 1; } var foo = "foo"; var bar = "bar"; var fooBar = "fooBar";`
};
const config = {
path: "/a/tsconfig.json",
content: JSON.stringify({
compilerOptions: {}
})
};
const cancellationToken = new TestServerCancellationToken(/*cancelAfterRequest*/ 3);
const host = createServerHost([f1, config]);
const session = createSession(host, /*typingsInstaller*/ undefined, () => { }, cancellationToken, /*throttleWaitMilliseconds*/ 0);
{
session.executeCommandSeq(<protocol.OpenRequest>{
command: "open",
arguments: { file: f1.path }
});
// send navbar request (normal priority)
session.executeCommandSeq(<protocol.NavBarRequest>{
command: "navbar",
arguments: { file: f1.path }
});
// ensure the nav bar request can be canceled
verifyExecuteCommandSeqIsCancellable(<protocol.NavBarRequest>{
command: "navbar",
arguments: { file: f1.path }
});
// send outlining spans request (normal priority)
session.executeCommandSeq(<protocol.OutliningSpansRequest>{
command: "outliningSpans",
arguments: { file: f1.path }
});
// ensure the outlining spans request can be canceled
verifyExecuteCommandSeqIsCancellable(<protocol.OutliningSpansRequest>{
command: "outliningSpans",
arguments: { file: f1.path }
});
}
function verifyExecuteCommandSeqIsCancellable<T extends server.protocol.Request>(request: Partial<T>) {
// Set the next request to be cancellable
// The cancellation token will cancel the request the third time
// isCancellationRequested() is called.
cancellationToken.setRequestToCancel(session.getNextSeq());
let operationCanceledExceptionThrown = false;
try {
session.executeCommandSeq(request);
}
catch (e) {
assert(e instanceof OperationCanceledException);
operationCanceledExceptionThrown = true;
}
assert(operationCanceledExceptionThrown, "Operation Canceled Exception not thrown for request: " + JSON.stringify(request));
}
});
});
describe("occurence highlight on string", () => {
@@ -3659,4 +3834,4 @@ namespace ts.projectSystem {
assert.isUndefined(project.getCompilerOptions().maxNodeModuleJsDepth);
});
});
}
}
+51 -4
View File
@@ -381,12 +381,12 @@ namespace ts.projectSystem {
const p = projectService.externalProjects[0];
projectService.checkNumberOfProjects({ externalProjects: 1 });
checkProjectActualFiles(p, [file1.path, file2.path]);
checkProjectActualFiles(p, [file2.path]);
installer.checkPendingCommands(/*expectedCount*/ 0);
checkNumberOfProjects(projectService, { externalProjects: 1 });
checkProjectActualFiles(p, [file1.path, file2.path]);
checkProjectActualFiles(p, [file2.path]);
});
it("external project - with type acquisition, with only js, d.ts files", () => {
@@ -692,7 +692,54 @@ namespace ts.projectSystem {
checkProjectActualFiles(p, [app.path, jqueryDTS.path]);
});
it("configured projects discover from bower.josn", () => {
it("configured projects discover from bower_components", () => {
const app = {
path: "/app.js",
content: ""
};
const jsconfig = {
path: "/jsconfig.json",
content: JSON.stringify({})
};
const jquery = {
path: "/bower_components/jquery/index.js",
content: ""
};
const jqueryPackage = {
path: "/bower_components/jquery/package.json",
content: JSON.stringify({ name: "jquery" })
};
const jqueryDTS = {
path: "/tmp/node_modules/@types/jquery/index.d.ts",
content: ""
};
const host = createServerHost([app, jsconfig, jquery, jqueryPackage]);
const installer = new (class extends Installer {
constructor() {
super(host, { globalTypingsCacheLocation: "/tmp", typesRegistry: createTypesRegistry("jquery") });
}
installWorker(_requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jqueryDTS];
executeCommand(this, host, installedTypings, typingFiles, cb);
}
})();
const projectService = createProjectService(host, { useSingleInferredProject: true, typingsInstaller: installer });
projectService.openClientFile(app.path);
checkNumberOfProjects(projectService, { configuredProjects: 1 });
const p = projectService.configuredProjects[0];
checkProjectActualFiles(p, [app.path]);
checkWatchedFiles(host, [jsconfig.path, "/bower_components", "/node_modules"]);
installer.installAll(/*expectedCount*/ 1);
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(p, [app.path, jqueryDTS.path]);
});
it("configured projects discover from bower.json", () => {
const app = {
path: "/app.js",
content: ""
@@ -975,7 +1022,7 @@ namespace ts.projectSystem {
}
});
it("should use cached locaitons", () => {
it("should use cached locations", () => {
const f = {
path: "/a/b/app.js",
content: ""
+1 -1
View File
@@ -278,7 +278,7 @@ and grew 1cm per day`;
const insertString = testContent.substring(rsa[i], rsa[i] + las[i]);
svc.edit(ersa[i], elas[i], insertString);
checkText = editFlat(ersa[i], elas[i], insertString, checkText);
if (0 == (i % 4)) {
if (0 === (i % 4)) {
const snap = svc.getSnapshot();
const snapText = snap.getText(0, checkText.length);
assert.equal(checkText, snapText);
+1 -1
View File
@@ -98,7 +98,7 @@ namespace Utils {
useCaseSensitiveFileNames: boolean;
constructor(currentDirectory: string, useCaseSensitiveFileNames: boolean) {
super(undefined, "");
super(/*fileSystem*/ undefined, "");
this.fileSystem = this;
this.root = new VirtualDirectory(this, "");
this.currentDirectory = currentDirectory;
+207 -113
View File
@@ -78,8 +78,8 @@ interface ConstrainLongRange extends LongRange {
}
interface ConstrainVideoFacingModeParameters {
exact?: string | string[];
ideal?: string | string[];
exact?: VideoFacingModeEnum | VideoFacingModeEnum[];
ideal?: VideoFacingModeEnum | VideoFacingModeEnum[];
}
interface CustomEventInit extends EventInit {
@@ -308,7 +308,7 @@ interface MSAudioSendSignal {
}
interface MSConnectivity {
iceType?: string;
iceType?: MSIceType;
iceWarningFlags?: MSIceWarningFlags;
relayAddress?: MSRelayAddress;
}
@@ -318,11 +318,11 @@ interface MSCredentialFilter {
}
interface MSCredentialParameters {
type?: string;
type?: MSCredentialType;
}
interface MSCredentialSpec {
type?: string;
type?: MSCredentialType;
id?: string;
}
@@ -333,7 +333,7 @@ interface MSDelay {
interface MSDescription extends RTCStats {
connectivity?: MSConnectivity;
transport?: string;
transport?: RTCIceProtocol;
networkconnectivity?: MSNetworkConnectivityInfo;
localAddr?: MSIPAddressInfo;
remoteAddr?: MSIPAddressInfo;
@@ -457,11 +457,11 @@ interface MSTransportDiagnosticsStats extends RTCStats {
numConsentRespReceived?: number;
interfaces?: MSNetworkInterfaceType;
baseInterface?: MSNetworkInterfaceType;
protocol?: string;
protocol?: RTCIceProtocol;
localInterface?: MSNetworkInterfaceType;
localAddrType?: string;
remoteAddrType?: string;
iceRole?: string;
localAddrType?: MSIceAddrType;
remoteAddrType?: MSIceAddrType;
iceRole?: RTCIceRole;
rtpRtcpMux?: boolean;
allocationTimeInMs?: number;
msRtcEngineVersion?: string;
@@ -534,7 +534,7 @@ interface MediaEncryptedEventInit extends EventInit {
}
interface MediaKeyMessageEventInit extends EventInit {
messageType?: string;
messageType?: MediaKeyMessageType;
message?: ArrayBuffer;
}
@@ -542,8 +542,8 @@ interface MediaKeySystemConfiguration {
initDataTypes?: string[];
audioCapabilities?: MediaKeySystemMediaCapability[];
videoCapabilities?: MediaKeySystemMediaCapability[];
distinctiveIdentifier?: string;
persistentState?: string;
distinctiveIdentifier?: MediaKeysRequirement;
persistentState?: MediaKeysRequirement;
}
interface MediaKeySystemMediaCapability {
@@ -667,7 +667,7 @@ interface MutationObserverInit {
}
interface NotificationOptions {
dir?: string;
dir?: NotificationDirection;
lang?: string;
body?: string;
tag?: string;
@@ -766,8 +766,8 @@ interface PushSubscriptionOptionsInit {
interface RTCConfiguration {
iceServers?: RTCIceServer[];
iceTransportPolicy?: string;
bundlePolicy?: string;
iceTransportPolicy?: RTCIceTransportPolicy;
bundlePolicy?: RTCBundlePolicy;
peerIdentity?: string;
}
@@ -781,7 +781,7 @@ interface RTCDtlsFingerprint {
}
interface RTCDtlsParameters {
role?: string;
role?: RTCDtlsRole;
fingerprints?: RTCDtlsFingerprint[];
}
@@ -789,7 +789,7 @@ interface RTCIceCandidateAttributes extends RTCStats {
ipAddress?: string;
portNumber?: number;
transport?: string;
candidateType?: string;
candidateType?: RTCStatsIceCandidateType;
priority?: number;
addressSourceUrl?: string;
}
@@ -801,10 +801,10 @@ interface RTCIceCandidateDictionary {
foundation?: string;
priority?: number;
ip?: string;
protocol?: string;
protocol?: RTCIceProtocol;
port?: number;
type?: string;
tcpType?: string;
type?: RTCIceCandidateType;
tcpType?: RTCIceTcpCandidateType;
relatedAddress?: string;
relatedPort?: number;
msMTurnSessionId?: string;
@@ -825,7 +825,7 @@ interface RTCIceCandidatePairStats extends RTCStats {
transportId?: string;
localCandidateId?: string;
remoteCandidateId?: string;
state?: string;
state?: RTCStatsIceCandidatePairState;
priority?: number;
nominated?: boolean;
writable?: boolean;
@@ -838,7 +838,7 @@ interface RTCIceCandidatePairStats extends RTCStats {
}
interface RTCIceGatherOptions {
gatherPolicy?: string;
gatherPolicy?: RTCIceGatherPolicy;
iceservers?: RTCIceServer[];
portRange?: MSPortRange;
}
@@ -1003,7 +1003,7 @@ interface RTCRtpParameters {
headerExtensions?: RTCRtpHeaderExtensionParameters[];
encodings?: RTCRtpEncodingParameters[];
rtcp?: RTCRtcpParameters;
degradationPreference?: string;
degradationPreference?: RTCDegradationPreference;
}
interface RTCRtpRtxParameters {
@@ -1017,7 +1017,7 @@ interface RTCRtpUnhandled {
}
interface RTCSessionDescriptionInit {
type?: string;
type?: RTCSdpType;
sdp?: string;
}
@@ -1043,9 +1043,9 @@ interface RTCSsrcRange {
interface RTCStats {
timestamp?: number;
type?: string;
type?: RTCStatsType;
id?: string;
msType?: string;
msType?: MSStatsType;
}
interface RTCStatsReport {
@@ -1070,11 +1070,11 @@ interface RequestInit {
headers?: any;
body?: any;
referrer?: string;
referrerPolicy?: string;
mode?: string;
credentials?: string;
cache?: string;
redirect?: string;
referrerPolicy?: ReferrerPolicy;
mode?: RequestMode;
credentials?: RequestCredentials;
cache?: RequestCache;
redirect?: RequestRedirect;
integrity?: string;
keepalive?: boolean;
window?: any;
@@ -1087,9 +1087,9 @@ interface ResponseInit {
}
interface ScopedCredentialDescriptor {
type?: string;
type?: ScopedCredentialType;
id?: any;
transports?: string[];
transports?: Transport[];
}
interface ScopedCredentialOptions {
@@ -1100,7 +1100,7 @@ interface ScopedCredentialOptions {
}
interface ScopedCredentialParameters {
type?: string;
type?: ScopedCredentialType;
algorithm?: string | Algorithm;
}
@@ -1330,7 +1330,7 @@ interface AudioContextBase extends EventTarget {
readonly listener: AudioListener;
onstatechange: (this: AudioContext, ev: Event) => any;
readonly sampleRate: number;
readonly state: string;
readonly state: AudioContextState;
close(): Promise<void>;
createAnalyser(): AnalyserNode;
createBiquadFilter(): BiquadFilterNode;
@@ -1390,8 +1390,8 @@ declare var AudioListener: {
interface AudioNode extends EventTarget {
channelCount: number;
channelCountMode: string;
channelInterpretation: string;
channelCountMode: ChannelCountMode;
channelInterpretation: ChannelInterpretation;
readonly context: AudioContext;
readonly numberOfInputs: number;
readonly numberOfOutputs: number;
@@ -1494,7 +1494,7 @@ interface BiquadFilterNode extends AudioNode {
readonly detune: AudioParam;
readonly frequency: AudioParam;
readonly gain: AudioParam;
type: string;
type: BiquadFilterType;
getFrequencyResponse(frequencyHz: Float32Array, magResponse: Float32Array, phaseResponse: Float32Array): void;
}
@@ -2134,7 +2134,7 @@ interface CanvasRenderingContext2D extends Object, CanvasPathMethods {
lineJoin: string;
lineWidth: number;
miterLimit: number;
msFillRule: string;
msFillRule: CanvasFillRule;
shadowBlur: number;
shadowColor: string;
shadowOffsetX: number;
@@ -2147,7 +2147,7 @@ interface CanvasRenderingContext2D extends Object, CanvasPathMethods {
oImageSmoothingEnabled: boolean;
beginPath(): void;
clearRect(x: number, y: number, w: number, h: number): void;
clip(fillRule?: string): void;
clip(fillRule?: CanvasFillRule): void;
createImageData(imageDataOrSw: number | ImageData, sh?: number): ImageData;
createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient;
createPattern(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, repetition: string): CanvasPattern;
@@ -2156,12 +2156,12 @@ interface CanvasRenderingContext2D extends Object, CanvasPathMethods {
drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number): void;
drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, dstX: number, dstY: number, dstW: number, dstH: number): void;
drawImage(image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap, srcX: number, srcY: number, srcW: number, srcH: number, dstX: number, dstY: number, dstW: number, dstH: number): void;
fill(fillRule?: string): void;
fill(fillRule?: CanvasFillRule): void;
fillRect(x: number, y: number, w: number, h: number): void;
fillText(text: string, x: number, y: number, maxWidth?: number): void;
getImageData(sx: number, sy: number, sw: number, sh: number): ImageData;
getLineDash(): number[];
isPointInPath(x: number, y: number, fillRule?: string): boolean;
isPointInPath(x: number, y: number, fillRule?: CanvasFillRule): boolean;
measureText(text: string): TextMetrics;
putImageData(imagedata: ImageData, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void;
restore(): void;
@@ -2538,6 +2538,7 @@ interface DataTransfer {
clearData(format?: string): boolean;
getData(format: string): string;
setData(format: string, data: string): boolean;
setDragImage(image: Element, x: number, y: number): void;
}
declare var DataTransfer: {
@@ -2574,7 +2575,7 @@ declare var DataTransferItemList: {
interface DeferredPermissionRequest {
readonly id: number;
readonly type: string;
readonly type: MSWebViewPermissionType;
readonly uri: string;
allow(): void;
deny(): void;
@@ -3192,7 +3193,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
* Contains the title of the document.
*/
title: string;
readonly visibilityState: string;
readonly visibilityState: VisibilityState;
/**
* Sets or gets the color of the links that the user has visited.
*/
@@ -3207,7 +3208,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
* Gets or sets the version attribute specified in the declaration of an XML document.
*/
xmlVersion: string | null;
adoptNode(source: Node): Node;
adoptNode<T extends Node>(source: T): T;
captureEvents(): void;
caretRangeFromPoint(x: number, y: number): Range;
clear(): void;
@@ -3384,7 +3385,7 @@ interface Document extends Node, GlobalEventHandlers, NodeSelector, DocumentEven
* Gets a value indicating whether the object currently has focus.
*/
hasFocus(): boolean;
importNode(importedNode: Node, deep: boolean): Node;
importNode<T extends Node>(importedNode: T, deep: boolean): T;
msElementsFromPoint(x: number, y: number): NodeListOf<Element>;
msElementsFromRect(left: number, top: number, width: number, height: number): NodeListOf<Element>;
/**
@@ -3700,9 +3701,9 @@ declare var Event: {
}
interface EventTarget {
addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
addEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
dispatchEvent(evt: Event): boolean;
removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
}
declare var EventTarget: {
@@ -3781,7 +3782,7 @@ declare var FocusEvent: {
}
interface FocusNavigationEvent extends Event {
readonly navigationReason: string;
readonly navigationReason: NavigationReason;
readonly originHeight: number;
readonly originLeft: number;
readonly originTop: number;
@@ -3795,7 +3796,12 @@ declare var FocusNavigationEvent: {
}
interface FormData {
append(name: any, value: any, blobName?: string): void;
append(name: string, value: string | Blob, fileName?: string): void;
delete(name: string): void;
get(name: string): FormDataEntryValue | null;
getAll(name: string): FormDataEntryValue[];
has(name: string): boolean;
set(name: string, value: string | Blob, fileName?: string): void;
}
declare var FormData: {
@@ -6957,7 +6963,7 @@ declare var History: {
}
interface IDBCursor {
readonly direction: string;
readonly direction: IDBCursorDirection;
key: IDBKeyRange | IDBValidKey;
readonly primaryKey: any;
source: IDBObjectStore | IDBIndex;
@@ -7109,7 +7115,7 @@ interface IDBRequest extends EventTarget {
readonly error: DOMError;
onerror: (this: IDBRequest, ev: Event) => any;
onsuccess: (this: IDBRequest, ev: Event) => any;
readonly readyState: string;
readonly readyState: IDBRequestReadyState;
readonly result: any;
source: IDBObjectStore | IDBIndex | IDBCursor;
readonly transaction: IDBTransaction;
@@ -7131,7 +7137,7 @@ interface IDBTransactionEventMap {
interface IDBTransaction extends EventTarget {
readonly db: IDBDatabase;
readonly error: DOMError;
readonly mode: string;
readonly mode: IDBTransactionMode;
onabort: (this: IDBTransaction, ev: Event) => any;
oncomplete: (this: IDBTransaction, ev: Event) => any;
onerror: (this: IDBTransaction, ev: Event) => any;
@@ -7249,7 +7255,7 @@ declare var KeyboardEvent: {
interface ListeningStateChangedEvent extends Event {
readonly label: string;
readonly state: string;
readonly state: ListeningState;
}
declare var ListeningStateChangedEvent: {
@@ -7340,7 +7346,7 @@ declare var MSAppAsyncOperation: {
interface MSAssertion {
readonly id: string;
readonly type: string;
readonly type: MSCredentialType;
}
declare var MSAssertion: {
@@ -7372,7 +7378,7 @@ interface MSFIDOCredentialAssertion extends MSAssertion {
readonly algorithm: string | Algorithm;
readonly attestation: any;
readonly publicKey: string;
readonly transportHints: string[];
readonly transportHints: MSTransportType[];
}
declare var MSFIDOCredentialAssertion: {
@@ -7476,7 +7482,7 @@ interface MSHTMLWebViewElement extends HTMLElement {
goForward(): void;
invokeScriptAsync(scriptName: string, ...args: any[]): MSWebViewAsyncOperation;
navigate(uri: string): void;
navigateFocus(navigationReason: string, origin: FocusNavigationOrigin): void;
navigateFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void;
navigateToLocalStreamUri(source: string, streamResolver: any): void;
navigateToString(contents: string): void;
navigateWithHttpRequestMessage(requestMessage: any): void;
@@ -7731,7 +7737,7 @@ declare var MSWebViewSettings: {
interface MediaDeviceInfo {
readonly deviceId: string;
readonly groupId: string;
readonly kind: string;
readonly kind: MediaDeviceKind;
readonly label: string;
}
@@ -7798,7 +7804,7 @@ declare var MediaError: {
interface MediaKeyMessageEvent extends Event {
readonly message: ArrayBuffer;
readonly messageType: string;
readonly messageType: MediaKeyMessageType;
}
declare var MediaKeyMessageEvent: {
@@ -7826,7 +7832,7 @@ declare var MediaKeySession: {
interface MediaKeyStatusMap {
readonly size: number;
forEach(callback: ForEachCallback): void;
get(keyId: any): string;
get(keyId: any): MediaKeyStatus;
has(keyId: any): boolean;
}
@@ -7847,7 +7853,7 @@ declare var MediaKeySystemAccess: {
}
interface MediaKeys {
createSession(sessionType?: string): MediaKeySession;
createSession(sessionType?: MediaKeySessionType): MediaKeySession;
setServerCertificate(serverCertificate: any): Promise<void>;
}
@@ -7985,7 +7991,7 @@ interface MediaStreamTrack extends EventTarget {
onoverconstrained: (this: MediaStreamTrack, ev: MediaStreamErrorEvent) => any;
onunmute: (this: MediaStreamTrack, ev: Event) => any;
readonly readonly: boolean;
readonly readyState: string;
readonly readyState: MediaStreamTrackState;
readonly remote: boolean;
applyConstraints(constraints: MediaTrackConstraints): Promise<void>;
clone(): MediaStreamTrack;
@@ -8206,7 +8212,7 @@ declare var NavigationEventWithReferrer: {
interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorContentUtils, NavigatorStorageUtils, NavigatorGeolocation, MSNavigatorDoNotTrack, MSFileSaver, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorUserMedia {
readonly authentication: WebAuthentication;
readonly cookieEnabled: boolean;
gamepadInputEmulation: string;
gamepadInputEmulation: GamepadInputEmulationType;
readonly language: string;
readonly maxTouchPoints: number;
readonly mimeTypes: MimeTypeArray;
@@ -8253,15 +8259,15 @@ interface Node extends EventTarget {
contains(child: Node): boolean;
hasAttributes(): boolean;
hasChildNodes(): boolean;
insertBefore(newChild: Node, refChild: Node | null): Node;
insertBefore<T extends Node>(newChild: T, refChild: Node | null): T;
isDefaultNamespace(namespaceURI: string | null): boolean;
isEqualNode(arg: Node): boolean;
isSameNode(other: Node): boolean;
lookupNamespaceURI(prefix: string | null): string | null;
lookupPrefix(namespaceURI: string | null): string | null;
normalize(): void;
removeChild(oldChild: Node): Node;
replaceChild(newChild: Node, oldChild: Node): Node;
removeChild<T extends Node>(oldChild: T): T;
replaceChild<T extends Node>(newChild: Node, oldChild: T): T;
readonly ATTRIBUTE_NODE: number;
readonly CDATA_SECTION_NODE: number;
readonly COMMENT_NODE: number;
@@ -8363,14 +8369,14 @@ interface NotificationEventMap {
interface Notification extends EventTarget {
readonly body: string;
readonly dir: string;
readonly dir: NotificationDirection;
readonly icon: string;
readonly lang: string;
onclick: (this: Notification, ev: Event) => any;
onclose: (this: Notification, ev: Event) => any;
onerror: (this: Notification, ev: Event) => any;
onshow: (this: Notification, ev: Event) => any;
readonly permission: string;
readonly permission: NotificationPermission;
readonly tag: string;
readonly title: string;
close(): void;
@@ -8381,7 +8387,7 @@ interface Notification extends EventTarget {
declare var Notification: {
prototype: Notification;
new(title: string, options?: NotificationOptions): Notification;
requestPermission(callback?: NotificationPermissionCallback): Promise<string>;
requestPermission(callback?: NotificationPermissionCallback): Promise<NotificationPermission>;
}
interface OES_element_index_uint {
@@ -8471,7 +8477,7 @@ interface OscillatorNode extends AudioNode {
readonly detune: AudioParam;
readonly frequency: AudioParam;
onended: (this: OscillatorNode, ev: MediaStreamErrorEvent) => any;
type: string;
type: OscillatorType;
setPeriodicWave(periodicWave: PeriodicWave): void;
start(when?: number): void;
stop(when?: number): void;
@@ -8514,9 +8520,9 @@ interface PannerNode extends AudioNode {
coneInnerAngle: number;
coneOuterAngle: number;
coneOuterGain: number;
distanceModel: string;
distanceModel: DistanceModelType;
maxDistance: number;
panningModel: string;
panningModel: PanningModelType;
refDistance: number;
rolloffFactor: number;
setOrientation(x: number, y: number, z: number): void;
@@ -8567,7 +8573,7 @@ interface PaymentRequest extends EventTarget {
onshippingoptionchange: (this: PaymentRequest, ev: Event) => any;
readonly shippingAddress: PaymentAddress | null;
readonly shippingOption: string | null;
readonly shippingType: string | null;
readonly shippingType: PaymentShippingType | null;
abort(): Promise<void>;
show(): Promise<PaymentResponse>;
addEventListener<K extends keyof PaymentRequestEventMap>(type: K, listener: (this: PaymentRequest, ev: PaymentRequestEventMap[K]) => any, useCapture?: boolean): void;
@@ -8596,7 +8602,7 @@ interface PaymentResponse {
readonly payerPhone: string | null;
readonly shippingAddress: PaymentAddress | null;
readonly shippingOption: string | null;
complete(result?: string): Promise<void>;
complete(result?: PaymentComplete): Promise<void>;
toJSON(): any;
}
@@ -8724,7 +8730,7 @@ interface PerformanceNavigationTiming extends PerformanceEntry {
readonly requestStart: number;
readonly responseEnd: number;
readonly responseStart: number;
readonly type: string;
readonly type: NavigationType;
readonly unloadEventEnd: number;
readonly unloadEventStart: number;
}
@@ -8793,7 +8799,7 @@ declare var PeriodicWave: {
}
interface PermissionRequest extends DeferredPermissionRequest {
readonly state: string;
readonly state: MSWebViewPermissionState;
defer(): void;
}
@@ -8923,7 +8929,7 @@ declare var ProgressEvent: {
interface PushManager {
getSubscription(): Promise<PushSubscription>;
permissionState(options?: PushSubscriptionOptionsInit): Promise<string>;
permissionState(options?: PushSubscriptionOptionsInit): Promise<PushPermissionState>;
subscribe(options?: PushSubscriptionOptionsInit): Promise<PushSubscription>;
}
@@ -8935,7 +8941,7 @@ declare var PushManager: {
interface PushSubscription {
readonly endpoint: USVString;
readonly options: PushSubscriptionOptions;
getKey(name: string): ArrayBuffer | null;
getKey(name: PushEncryptionKeyName): ArrayBuffer | null;
toJSON(): any;
unsubscribe(): Promise<boolean>;
}
@@ -8972,7 +8978,7 @@ interface RTCDtlsTransportEventMap {
interface RTCDtlsTransport extends RTCStatsProvider {
ondtlsstatechange: ((this: RTCDtlsTransport, ev: RTCDtlsTransportStateChangedEvent) => any) | null;
onerror: ((this: RTCDtlsTransport, ev: Event) => any) | null;
readonly state: string;
readonly state: RTCDtlsTransportState;
readonly transport: RTCIceTransport;
getLocalParameters(): RTCDtlsParameters;
getRemoteCertificates(): ArrayBuffer[];
@@ -8989,7 +8995,7 @@ declare var RTCDtlsTransport: {
}
interface RTCDtlsTransportStateChangedEvent extends Event {
readonly state: string;
readonly state: RTCDtlsTransportState;
}
declare var RTCDtlsTransportStateChangedEvent: {
@@ -9045,7 +9051,7 @@ interface RTCIceGathererEventMap {
}
interface RTCIceGatherer extends RTCStatsProvider {
readonly component: string;
readonly component: RTCIceComponent;
onerror: ((this: RTCIceGatherer, ev: Event) => any) | null;
onlocalcandidate: ((this: RTCIceGatherer, ev: RTCIceGathererEvent) => any) | null;
createAssociatedGatherer(): RTCIceGatherer;
@@ -9075,19 +9081,19 @@ interface RTCIceTransportEventMap {
}
interface RTCIceTransport extends RTCStatsProvider {
readonly component: string;
readonly component: RTCIceComponent;
readonly iceGatherer: RTCIceGatherer | null;
oncandidatepairchange: ((this: RTCIceTransport, ev: RTCIceCandidatePairChangedEvent) => any) | null;
onicestatechange: ((this: RTCIceTransport, ev: RTCIceTransportStateChangedEvent) => any) | null;
readonly role: string;
readonly state: string;
readonly role: RTCIceRole;
readonly state: RTCIceTransportState;
addRemoteCandidate(remoteCandidate: RTCIceCandidateDictionary | RTCIceCandidateComplete): void;
createAssociatedTransport(): RTCIceTransport;
getNominatedCandidatePair(): RTCIceCandidatePair | null;
getRemoteCandidates(): RTCIceCandidateDictionary[];
getRemoteParameters(): RTCIceParameters | null;
setRemoteCandidates(remoteCandidates: RTCIceCandidateDictionary[]): void;
start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: string): void;
start(gatherer: RTCIceGatherer, remoteParameters: RTCIceParameters, role?: RTCIceRole): void;
stop(): void;
addEventListener<K extends keyof RTCIceTransportEventMap>(type: K, listener: (this: RTCIceTransport, ev: RTCIceTransportEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -9099,7 +9105,7 @@ declare var RTCIceTransport: {
}
interface RTCIceTransportStateChangedEvent extends Event {
readonly state: string;
readonly state: RTCIceTransportState;
}
declare var RTCIceTransportStateChangedEvent: {
@@ -9119,8 +9125,8 @@ interface RTCPeerConnectionEventMap {
interface RTCPeerConnection extends EventTarget {
readonly canTrickleIceCandidates: boolean | null;
readonly iceConnectionState: string;
readonly iceGatheringState: string;
readonly iceConnectionState: RTCIceConnectionState;
readonly iceGatheringState: RTCIceGatheringState;
readonly localDescription: RTCSessionDescription | null;
onaddstream: (this: RTCPeerConnection, ev: MediaStreamEvent) => any;
onicecandidate: (this: RTCPeerConnection, ev: RTCPeerConnectionIceEvent) => any;
@@ -9130,7 +9136,7 @@ interface RTCPeerConnection extends EventTarget {
onremovestream: (this: RTCPeerConnection, ev: MediaStreamEvent) => any;
onsignalingstatechange: (this: RTCPeerConnection, ev: Event) => any;
readonly remoteDescription: RTCSessionDescription | null;
readonly signalingState: string;
readonly signalingState: RTCSignalingState;
addIceCandidate(candidate: RTCIceCandidate, successCallback?: VoidFunction, failureCallback?: RTCPeerConnectionErrorCallback): Promise<void>;
addStream(stream: MediaStream): void;
close(): void;
@@ -9213,7 +9219,7 @@ declare var RTCRtpSender: {
interface RTCSessionDescription {
sdp: string | null;
type: string | null;
type: RTCSdpType | null;
toJSON(): any;
}
@@ -9272,7 +9278,7 @@ interface Range {
createContextualFragment(fragment: string): DocumentFragment;
deleteContents(): void;
detach(): void;
expand(Unit: string): boolean;
expand(Unit: ExpandGranularity): boolean;
extractContents(): DocumentFragment;
getBoundingClientRect(): ClientRect;
getClientRects(): ClientRectList;
@@ -9325,18 +9331,18 @@ declare var ReadableStreamReader: {
}
interface Request extends Object, Body {
readonly cache: string;
readonly credentials: string;
readonly destination: string;
readonly cache: RequestCache;
readonly credentials: RequestCredentials;
readonly destination: RequestDestination;
readonly headers: Headers;
readonly integrity: string;
readonly keepalive: boolean;
readonly method: string;
readonly mode: string;
readonly redirect: string;
readonly mode: RequestMode;
readonly redirect: RequestRedirect;
readonly referrer: string;
readonly referrerPolicy: string;
readonly type: string;
readonly referrerPolicy: ReferrerPolicy;
readonly type: RequestType;
readonly url: string;
clone(): Request;
}
@@ -9352,7 +9358,7 @@ interface Response extends Object, Body {
readonly ok: boolean;
readonly status: number;
readonly statusText: string;
readonly type: string;
readonly type: ResponseType;
readonly url: string;
clone(): Response;
}
@@ -11152,7 +11158,7 @@ declare var SVGZoomEvent: {
interface ScopedCredential {
readonly id: ArrayBuffer;
readonly type: string;
readonly type: ScopedCredentialType;
}
declare var ScopedCredential: {
@@ -11269,7 +11275,7 @@ interface ServiceWorkerEventMap extends AbstractWorkerEventMap {
interface ServiceWorker extends EventTarget, AbstractWorker {
onstatechange: (this: ServiceWorker, ev: Event) => any;
readonly scriptURL: USVString;
readonly state: string;
readonly state: ServiceWorkerState;
postMessage(message: any, transfer?: any[]): void;
addEventListener<K extends keyof ServiceWorkerEventMap>(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -11345,7 +11351,7 @@ interface SourceBuffer extends EventTarget {
appendWindowStart: number;
readonly audioTracks: AudioTrackList;
readonly buffered: TimeRanges;
mode: string;
mode: AppendMode;
timestampOffset: number;
readonly updating: boolean;
readonly videoTracks: VideoTrackList;
@@ -11581,7 +11587,7 @@ interface Text extends CharacterData {
declare var Text: {
prototype: Text;
new(): Text;
new(data?: string): Text;
}
interface TextEvent extends UIEvent {
@@ -11764,7 +11770,7 @@ interface TouchEvent extends UIEvent {
declare var TouchEvent: {
prototype: TouchEvent;
new(): TouchEvent;
new(type: string, touchEventInit?: TouchEventInit): TouchEvent;
}
interface TouchList {
@@ -11970,7 +11976,7 @@ declare var WEBGL_depth_texture: {
interface WaveShaperNode extends AudioNode {
curve: Float32Array | null;
oversample: string;
oversample: OverSampleType;
}
declare var WaveShaperNode: {
@@ -13231,6 +13237,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
readonly top: Window;
readonly window: Window;
URL: typeof URL;
URLSearchParams: typeof URLSearchParams;
Blob: typeof Blob;
customElements: CustomElementRegistry;
alert(message?: any): void;
@@ -13239,7 +13246,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
captureEvents(): void;
close(): void;
confirm(message?: string): boolean;
departFocus(navigationReason: string, origin: FocusNavigationOrigin): void;
departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void;
focus(): void;
getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration;
getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList;
@@ -13314,7 +13321,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly readyState: number;
readonly response: any;
readonly responseText: string;
responseType: string;
responseType: XMLHttpRequestResponseType;
readonly responseURL: string;
readonly responseXML: Document | null;
readonly status: number;
@@ -14171,6 +14178,21 @@ interface PromiseRejectionEventInit extends EventInit {
reason?: any;
}
interface EventListenerOptions {
capture?: boolean;
}
interface AddEventListenerOptions extends EventListenerOptions {
passive?: boolean;
once?: boolean;
}
interface TouchEventInit extends EventModifierInit {
touches?: Touch[];
targetTouches?: Touch[];
changedTouches?: Touch[];
}
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
@@ -14228,10 +14250,10 @@ interface NavigatorUserMediaErrorCallback {
(error: MediaStreamError): void;
}
interface ForEachCallback {
(keyId: any, status: string): void;
(keyId: any, status: MediaKeyStatus): void;
}
interface NotificationPermissionCallback {
(permission: string): void;
(permission: NotificationPermission): void;
}
interface IntersectionObserverCallback {
(entries: IntersectionObserverEntry[], observer: IntersectionObserver): void;
@@ -14838,7 +14860,7 @@ declare function cancelAnimationFrame(handle: number): void;
declare function captureEvents(): void;
declare function close(): void;
declare function confirm(message?: string): boolean;
declare function departFocus(navigationReason: string, origin: FocusNavigationOrigin): void;
declare function departFocus(navigationReason: NavigationReason, origin: FocusNavigationOrigin): void;
declare function focus(): void;
declare function getComputedStyle(elt: Element, pseudoElt?: string): CSSStyleDeclaration;
declare function getMatchedCSSRules(elt: Element, pseudoElt?: string): CSSRuleList;
@@ -14870,7 +14892,7 @@ declare function scrollTo(options?: ScrollToOptions): void;
declare function scrollBy(options?: ScrollToOptions): void;
declare function toString(): string;
declare function dispatchEvent(evt: Event): boolean;
declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
declare function clearInterval(handle: number): void;
declare function clearTimeout(handle: number): void;
declare function setInterval(handler: (...args: any[]) => void, timeout: number): number;
@@ -14939,4 +14961,76 @@ type ScrollLogicalPosition = "start" | "center" | "end" | "nearest";
type IDBValidKey = number | string | Date | IDBArrayKey;
type BufferSource = ArrayBuffer | ArrayBufferView;
type MouseWheelEvent = WheelEvent;
type ScrollRestoration = "auto" | "manual";
type ScrollRestoration = "auto" | "manual";
type FormDataEntryValue = string | File;
type AppendMode = "segments" | "sequence";
type AudioContextState = "suspended" | "running" | "closed";
type BiquadFilterType = "lowpass" | "highpass" | "bandpass" | "lowshelf" | "highshelf" | "peaking" | "notch" | "allpass";
type CanvasFillRule = "nonzero" | "evenodd";
type ChannelCountMode = "max" | "clamped-max" | "explicit";
type ChannelInterpretation = "speakers" | "discrete";
type DistanceModelType = "linear" | "inverse" | "exponential";
type ExpandGranularity = "character" | "word" | "sentence" | "textedit";
type GamepadInputEmulationType = "mouse" | "keyboard" | "gamepad";
type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique";
type IDBRequestReadyState = "pending" | "done";
type IDBTransactionMode = "readonly" | "readwrite" | "versionchange";
type ListeningState = "inactive" | "active" | "disambiguation";
type MSCredentialType = "FIDO_2_0";
type MSIceAddrType = "os" | "stun" | "turn" | "peer-derived";
type MSIceType = "failed" | "direct" | "relay";
type MSStatsType = "description" | "localclientevent" | "inbound-network" | "outbound-network" | "inbound-payload" | "outbound-payload" | "transportdiagnostics";
type MSTransportType = "Embedded" | "USB" | "NFC" | "BT";
type MSWebViewPermissionState = "unknown" | "defer" | "allow" | "deny";
type MSWebViewPermissionType = "geolocation" | "unlimitedIndexedDBQuota" | "media" | "pointerlock" | "webnotifications";
type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput";
type MediaKeyMessageType = "license-request" | "license-renewal" | "license-release" | "individualization-request";
type MediaKeySessionType = "temporary" | "persistent-license" | "persistent-release-message";
type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error";
type MediaKeysRequirement = "required" | "optional" | "not-allowed";
type MediaStreamTrackState = "live" | "ended";
type NavigationReason = "up" | "down" | "left" | "right";
type NavigationType = "navigate" | "reload" | "back_forward" | "prerender";
type NotificationDirection = "auto" | "ltr" | "rtl";
type NotificationPermission = "default" | "denied" | "granted";
type OscillatorType = "sine" | "square" | "sawtooth" | "triangle" | "custom";
type OverSampleType = "none" | "2x" | "4x";
type PanningModelType = "equalpower";
type PaymentComplete = "success" | "fail" | "";
type PaymentShippingType = "shipping" | "delivery" | "pickup";
type PushEncryptionKeyName = "p256dh" | "auth";
type PushPermissionState = "granted" | "denied" | "prompt";
type RTCBundlePolicy = "balanced" | "max-compat" | "max-bundle";
type RTCDegradationPreference = "maintain-framerate" | "maintain-resolution" | "balanced";
type RTCDtlsRole = "auto" | "client" | "server";
type RTCDtlsTransportState = "new" | "connecting" | "connected" | "closed";
type RTCIceCandidateType = "host" | "srflx" | "prflx" | "relay";
type RTCIceComponent = "RTP" | "RTCP";
type RTCIceConnectionState = "new" | "checking" | "connected" | "completed" | "failed" | "disconnected" | "closed";
type RTCIceGatherPolicy = "all" | "nohost" | "relay";
type RTCIceGathererState = "new" | "gathering" | "complete";
type RTCIceGatheringState = "new" | "gathering" | "complete";
type RTCIceProtocol = "udp" | "tcp";
type RTCIceRole = "controlling" | "controlled";
type RTCIceTcpCandidateType = "active" | "passive" | "so";
type RTCIceTransportPolicy = "none" | "relay" | "all";
type RTCIceTransportState = "new" | "checking" | "connected" | "completed" | "disconnected" | "closed";
type RTCSdpType = "offer" | "pranswer" | "answer";
type RTCSignalingState = "stable" | "have-local-offer" | "have-remote-offer" | "have-local-pranswer" | "have-remote-pranswer" | "closed";
type RTCStatsIceCandidatePairState = "frozen" | "waiting" | "inprogress" | "failed" | "succeeded" | "cancelled";
type RTCStatsIceCandidateType = "host" | "serverreflexive" | "peerreflexive" | "relayed";
type RTCStatsType = "inboundrtp" | "outboundrtp" | "session" | "datachannel" | "track" | "transport" | "candidatepair" | "localcandidate" | "remotecandidate";
type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url";
type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache";
type RequestCredentials = "omit" | "same-origin" | "include";
type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker";
type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors";
type RequestRedirect = "follow" | "error" | "manual";
type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video";
type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect";
type ScopedCredentialType = "ScopedCred";
type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant";
type Transport = "usb" | "nfc" | "ble";
type VideoFacingModeEnum = "user" | "environment" | "left" | "right";
type VisibilityState = "hidden" | "visible" | "prerender" | "unloaded";
type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text";
+37 -20
View File
@@ -4,25 +4,42 @@ interface DOMTokenList {
[Symbol.iterator](): IterableIterator<string>;
}
interface FormData {
/**
* Returns an array of key, value pairs for every entry in the list
*/
entries(): IterableIterator<[string, string | File]>;
/**
* Returns a list of keys in the list
*/
keys(): IterableIterator<string>;
/**
* Returns a list of values in the list
*/
values(): IterableIterator<string | File>;
[Symbol.iterator](): IterableIterator<string | File>;
}
interface NodeList {
/**
* Returns an array of key, value pairs for every entry in the list
*/
* Returns an array of key, value pairs for every entry in the list
*/
entries(): IterableIterator<[number, Node]>;
/**
* Performs the specified action for each node in an list.
* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
* Performs the specified action for each node in an list.
* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: Node, index: number, listObj: NodeList) => void, thisArg?: any): void;
/**
* Returns an list of keys in the list
*/
* Returns an list of keys in the list
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the list
*/
* Returns an list of values in the list
*/
values(): IterableIterator<Node>;
@@ -32,23 +49,23 @@ interface NodeList {
interface NodeListOf<TNode extends Node> {
/**
* Returns an array of key, value pairs for every entry in the list
*/
* Returns an array of key, value pairs for every entry in the list
*/
entries(): IterableIterator<[number, TNode]>;
/**
* Performs the specified action for each node in an list.
* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
* Performs the specified action for each node in an list.
* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: TNode, index: number, listObj: NodeListOf<TNode>) => void, thisArg?: any): void;
/**
* Returns an list of keys in the list
*/
* Returns an list of keys in the list
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the list
*/
* Returns an list of values in the list
*/
values(): IterableIterator<TNode>;
[Symbol.iterator](): IterableIterator<TNode>;
+6 -6
View File
@@ -30,9 +30,9 @@ interface WeakMap<K extends object, V> {
}
interface WeakMapConstructor {
new (): WeakMap<any, any>;
new (): WeakMap<object, any>;
new <K extends object, V>(entries?: [K, V][]): WeakMap<K, V>;
readonly prototype: WeakMap<any, any>;
readonly prototype: WeakMap<object, any>;
}
declare var WeakMap: WeakMapConstructor;
@@ -58,15 +58,15 @@ interface ReadonlySet<T> {
readonly size: number;
}
interface WeakSet<T> {
interface WeakSet<T extends object> {
add(value: T): this;
delete(value: T): boolean;
has(value: T): boolean;
}
interface WeakSetConstructor {
new (): WeakSet<any>;
new <T>(values?: T[]): WeakSet<T>;
readonly prototype: WeakSet<any>;
new (): WeakSet<object>;
new <T extends object>(values?: T[]): WeakSet<T>;
readonly prototype: WeakSet<object>;
}
declare var WeakSet: WeakSetConstructor;
+287 -287
View File
@@ -2,75 +2,75 @@ declare type PropertyKey = string | number | symbol;
interface Array<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (this: undefined, value: T, index: number, obj: Array<T>) => boolean): T | undefined;
find(predicate: (this: undefined, value: T, index: number, obj: Array<T>) => boolean, thisArg: undefined): T | undefined;
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (this: void, value: T, index: number, obj: Array<T>) => boolean): T | undefined;
find(predicate: (this: void, value: T, index: number, obj: Array<T>) => boolean, thisArg: undefined): T | undefined;
find<Z>(predicate: (this: Z, value: T, index: number, obj: Array<T>) => boolean, thisArg: Z): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (this: undefined, value: T, index: number, obj: Array<T>) => boolean): number;
findIndex(predicate: (this: undefined, value: T, index: number, obj: Array<T>) => boolean, thisArg: undefined): number;
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (this: void, value: T, index: number, obj: Array<T>) => boolean): number;
findIndex(predicate: (this: void, value: T, index: number, obj: Array<T>) => boolean, thisArg: undefined): number;
findIndex<Z>(predicate: (this: Z, value: T, index: number, obj: Array<T>) => boolean, thisArg: Z): number;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: T, start?: number, end?: number): this;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
}
interface ArrayConstructor {
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(arrayLike: ArrayLike<T>, mapfn: (this: undefined, v: T, k: number) => U): Array<U>;
from<T, U>(arrayLike: ArrayLike<T>, mapfn: (this: undefined, v: T, k: number) => U, thisArg: undefined): Array<U>;
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(arrayLike: ArrayLike<T>, mapfn: (this: void, v: T, k: number) => U): Array<U>;
from<T, U>(arrayLike: ArrayLike<T>, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array<U>;
from<Z, T, U>(arrayLike: ArrayLike<T>, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array<U>;
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
*/
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
*/
from<T>(arrayLike: ArrayLike<T>): Array<T>;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of<T>(...items: T[]): Array<T>;
}
@@ -80,332 +80,332 @@ interface DateConstructor {
interface Function {
/**
* Returns the name of the function. Function names are read-only and can not be changed.
*/
* Returns the name of the function. Function names are read-only and can not be changed.
*/
readonly name: string;
}
interface Math {
/**
* Returns the number of leading zero bits in the 32-bit binary representation of a number.
* @param x A numeric expression.
*/
* Returns the number of leading zero bits in the 32-bit binary representation of a number.
* @param x A numeric expression.
*/
clz32(x: number): number;
/**
* Returns the result of 32-bit multiplication of two numbers.
* @param x First number
* @param y Second number
*/
* Returns the result of 32-bit multiplication of two numbers.
* @param x First number
* @param y Second number
*/
imul(x: number, y: number): number;
/**
* Returns the sign of the x, indicating whether x is positive, negative or zero.
* @param x The numeric expression to test
*/
* Returns the sign of the x, indicating whether x is positive, negative or zero.
* @param x The numeric expression to test
*/
sign(x: number): number;
/**
* Returns the base 10 logarithm of a number.
* @param x A numeric expression.
*/
* Returns the base 10 logarithm of a number.
* @param x A numeric expression.
*/
log10(x: number): number;
/**
* Returns the base 2 logarithm of a number.
* @param x A numeric expression.
*/
* Returns the base 2 logarithm of a number.
* @param x A numeric expression.
*/
log2(x: number): number;
/**
* Returns the natural logarithm of 1 + x.
* @param x A numeric expression.
*/
* Returns the natural logarithm of 1 + x.
* @param x A numeric expression.
*/
log1p(x: number): number;
/**
* Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of
* the natural logarithms).
* @param x A numeric expression.
*/
* Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of
* the natural logarithms).
* @param x A numeric expression.
*/
expm1(x: number): number;
/**
* Returns the hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
* Returns the hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
cosh(x: number): number;
/**
* Returns the hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
* Returns the hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
sinh(x: number): number;
/**
* Returns the hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
* Returns the hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
tanh(x: number): number;
/**
* Returns the inverse hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
* Returns the inverse hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
acosh(x: number): number;
/**
* Returns the inverse hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
* Returns the inverse hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
asinh(x: number): number;
/**
* Returns the inverse hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
* Returns the inverse hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
atanh(x: number): number;
/**
* Returns the square root of the sum of squares of its arguments.
* @param values Values to compute the square root for.
* If no arguments are passed, the result is +0.
* If there is only one argument, the result is the absolute value.
* If any argument is +Infinity or -Infinity, the result is +Infinity.
* If any argument is NaN, the result is NaN.
* If all arguments are either +0 or 0, the result is +0.
*/
* Returns the square root of the sum of squares of its arguments.
* @param values Values to compute the square root for.
* If no arguments are passed, the result is +0.
* If there is only one argument, the result is the absolute value.
* If any argument is +Infinity or -Infinity, the result is +Infinity.
* If any argument is NaN, the result is NaN.
* If all arguments are either +0 or 0, the result is +0.
*/
hypot(...values: number[] ): number;
/**
* Returns the integral part of the a numeric expression, x, removing any fractional digits.
* If x is already an integer, the result is x.
* @param x A numeric expression.
*/
* Returns the integral part of the a numeric expression, x, removing any fractional digits.
* If x is already an integer, the result is x.
* @param x A numeric expression.
*/
trunc(x: number): number;
/**
* Returns the nearest single precision float representation of a number.
* @param x A numeric expression.
*/
* Returns the nearest single precision float representation of a number.
* @param x A numeric expression.
*/
fround(x: number): number;
/**
* Returns an implementation-dependent approximation to the cube root of number.
* @param x A numeric expression.
*/
* Returns an implementation-dependent approximation to the cube root of number.
* @param x A numeric expression.
*/
cbrt(x: number): number;
}
interface NumberConstructor {
/**
* The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1
* that is representable as a Number value, which is approximately:
* 2.2204460492503130808472633361816 x 1016.
*/
* The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1
* that is representable as a Number value, which is approximately:
* 2.2204460492503130808472633361816 x 1016.
*/
readonly EPSILON: number;
/**
* Returns true if passed value is finite.
* Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
* Returns true if passed value is finite.
* Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
isFinite(number: number): boolean;
/**
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
isInteger(number: number): boolean;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
isNaN(number: number): boolean;
/**
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
isSafeInteger(number: number): boolean;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
* The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 1.
*/
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
* The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 1.
*/
readonly MAX_SAFE_INTEGER: number;
/**
* The value of the smallest integer n such that n and n 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 ((2^53 1)).
*/
* The value of the smallest integer n such that n and n 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 ((2^53 1)).
*/
readonly MIN_SAFE_INTEGER: number;
/**
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
*/
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
*/
parseFloat(string: string): number;
/**
* Converts A string to an integer.
* @param s A string to convert into a number.
* @param radix A value between 2 and 36 that specifies the base of the number in numString.
* If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.
* All other strings are considered decimal.
*/
* Converts A string to an integer.
* @param s A string to convert into a number.
* @param radix A value between 2 and 36 that specifies the base of the number in numString.
* If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.
* All other strings are considered decimal.
*/
parseInt(string: string, radix?: number): number;
}
interface Object {
/**
* Determines whether an object has a property with the specified name.
* @param v A property name.
*/
* Determines whether an object has a property with the specified name.
* @param v A property name.
*/
hasOwnProperty(v: PropertyKey): boolean;
/**
* Determines whether a specified property is enumerable.
* @param v A property name.
*/
* Determines whether a specified property is enumerable.
* @param v A property name.
*/
propertyIsEnumerable(v: PropertyKey): boolean;
}
interface ObjectConstructor {
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source The source object from which to copy properties.
*/
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source The source object from which to copy properties.
*/
assign<T, U>(target: T, source: U): T & U;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
*/
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
*/
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
* @param source3 The third source object from which to copy properties.
*/
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
* @param source3 The third source object from which to copy properties.
*/
assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param sources One or more source objects from which to copy properties
*/
assign(target: any, ...sources: any[]): any;
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param sources One or more source objects from which to copy properties
*/
assign(target: object, ...sources: any[]): any;
/**
* Returns an array of all symbol properties found directly on object o.
* @param o Object to retrieve the symbols from.
*/
* Returns an array of all symbol properties found directly on object o.
* @param o Object to retrieve the symbols from.
*/
getOwnPropertySymbols(o: any): symbol[];
/**
* Returns true if the values are the same value, false otherwise.
* @param value1 The first value.
* @param value2 The second value.
*/
* Returns true if the values are the same value, false otherwise.
* @param value1 The first value.
* @param value2 The second value.
*/
is(value1: any, value2: any): boolean;
/**
* Sets the prototype of a specified object o to object proto or null. Returns the object o.
* @param o The object to change its prototype.
* @param proto The value of the new prototype or null.
*/
* Sets the prototype of a specified object o to object proto or null. Returns the object o.
* @param o The object to change its prototype.
* @param proto The value of the new prototype or null.
*/
setPrototypeOf(o: any, proto: object | null): any;
/**
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not
* inherited from the object's prototype.
* @param o Object that contains the property.
* @param p Name of the property.
*/
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not
* inherited from the object's prototype.
* @param o Object that contains the property.
* @param p Name of the property.
*/
getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor;
/**
* Adds a property to an object, or modifies attributes of an existing property.
* @param o Object on which to add or modify the property. This can be a native JavaScript
* object (that is, a user-defined object or a built in object) or a DOM object.
* @param p The property name.
* @param attributes Descriptor for the property. It can be for a data property or an accessor
* property.
*/
* Adds a property to an object, or modifies attributes of an existing property.
* @param o Object on which to add or modify the property. This can be a native JavaScript
* object (that is, a user-defined object or a built in object) or a DOM object.
* @param p The property name.
* @param attributes Descriptor for the property. It can be for a data property or an accessor
* property.
*/
defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any;
}
interface ReadonlyArray<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (this: undefined, value: T, index: number, obj: ReadonlyArray<T>) => boolean): T | undefined;
find(predicate: (this: undefined, value: T, index: number, obj: ReadonlyArray<T>) => boolean, thisArg: undefined): T | undefined;
find<Z>(predicate: (this: Z, value: T, index: number, obj: ReadonlyArray<T>) => boolean, thisArg: Z): T | undefined;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray<T>) => boolean): T | undefined;
find(predicate: (this: void, value: T, index: number, obj: ReadonlyArray<T>) => boolean, thisArg: undefined): T | undefined;
find<Z>(predicate: (this: Z, value: T, index: number, obj: ReadonlyArray<T>) => boolean, thisArg: Z): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (this: undefined, value: T, index: number, obj: Array<T>) => boolean): number;
findIndex(predicate: (this: undefined, value: T, index: number, obj: Array<T>) => boolean, thisArg: undefined): number;
findIndex<Z>(predicate: (this: Z, value: T, index: number, obj: Array<T>) => boolean, thisArg: Z): number;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (this: void, value: T, index: number, obj: Array<T>) => boolean): number;
findIndex(predicate: (this: void, value: T, index: number, obj: Array<T>) => boolean, thisArg: undefined): number;
findIndex<Z>(predicate: (this: Z, value: T, index: number, obj: Array<T>) => boolean, thisArg: Z): number;
}
interface RegExp {
/**
* Returns a string indicating the flags of the regular expression in question. This field is read-only.
* The characters in this string are sequenced and concatenated in the following order:
*
* - "g" for global
* - "i" for ignoreCase
* - "m" for multiline
* - "u" for unicode
* - "y" for sticky
*
* If no flags are set, the value is the empty string.
*/
* Returns a string indicating the flags of the regular expression in question. This field is read-only.
* The characters in this string are sequenced and concatenated in the following order:
*
* - "g" for global
* - "i" for ignoreCase
* - "m" for multiline
* - "u" for unicode
* - "y" for sticky
*
* If no flags are set, the value is the empty string.
*/
readonly flags: string;
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
*/
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
*/
readonly sticky: boolean;
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
*/
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
*/
readonly unicode: boolean;
}
@@ -416,64 +416,64 @@ interface RegExpConstructor {
interface String {
/**
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
*/
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
*/
codePointAt(pos: number): number | undefined;
/**
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* greater than or equal to position; otherwise, returns false.
* @param searchString search string
* @param position If position is undefined, 0 is assumed, so as to search all of the String.
*/
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* greater than or equal to position; otherwise, returns false.
* @param searchString search string
* @param position If position is undefined, 0 is assumed, so as to search all of the String.
*/
includes(searchString: string, position?: number): boolean;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* endPosition length(this). Otherwise returns false.
*/
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* endPosition length(this). Otherwise returns false.
*/
endsWith(searchString: string, endPosition?: number): boolean;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form?: string): string;
/**
* Returns a String value that is made from count copies appended together. If count is 0,
* T is the empty String is returned.
* @param count number of copies to append
*/
* Returns a String value that is made from count copies appended together. If count is 0,
* T is the empty String is returned.
* @param count number of copies to append
*/
repeat(count: number): string;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* position. Otherwise returns false.
*/
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* position. Otherwise returns false.
*/
startsWith(searchString: string, position?: number): boolean;
/**
* Returns an <a> HTML anchor element and sets the name attribute to the text value
* @param name
*/
* Returns an <a> HTML anchor element and sets the name attribute to the text value
* @param name
*/
anchor(name: string): string;
/** Returns a <big> HTML element */
@@ -518,17 +518,17 @@ interface String {
interface StringConstructor {
/**
* Return the String value whose elements are, in order, the elements in the List elements.
* If length is 0, the empty string is returned.
*/
* Return the String value whose elements are, in order, the elements in the List elements.
* If length is 0, the empty string is returned.
*/
fromCodePoint(...codePoints: number[]): string;
/**
* String.raw is intended for use as a tag function of a Tagged Template String. When called
* as such the first argument will be a well formed template call site object and the rest
* parameter will contain the substitution values.
* @param template A well-formed template string call site representation.
* @param substitutions A set of substitution values.
*/
* String.raw is intended for use as a tag function of a Tagged Template String. When called
* as such the first argument will be a well formed template call site object and the rest
* parameter will contain the substitution values.
* @param template A well-formed template string call site representation.
* @param substitutions A set of substitution values.
*/
raw(template: TemplateStringsArray, ...substitutions: any[]): string;
}
+14 -14
View File
@@ -16,37 +16,37 @@ interface GeneratorFunction {
*/
readonly length: number;
/**
* Returns the name of the function.
*/
* Returns the name of the function.
*/
readonly name: string;
/**
* A reference to the prototype.
*/
* A reference to the prototype.
*/
readonly prototype: Generator;
}
interface GeneratorFunctionConstructor {
/**
* Creates a new Generator function.
* @param args A list of arguments the function accepts.
*/
* Creates a new Generator function.
* @param args A list of arguments the function accepts.
*/
new (...args: string[]): GeneratorFunction;
/**
* Creates a new Generator function.
* @param args A list of arguments the function accepts.
*/
* Creates a new Generator function.
* @param args A list of arguments the function accepts.
*/
(...args: string[]): GeneratorFunction;
/**
* The length of the arguments.
*/
readonly length: number;
/**
* Returns the name of the function.
*/
* Returns the name of the function.
*/
readonly name: string;
/**
* A reference to the prototype.
*/
* A reference to the prototype.
*/
readonly prototype: GeneratorFunction;
}
declare var GeneratorFunction: GeneratorFunctionConstructor;
+172 -172
View File
@@ -2,9 +2,9 @@
interface SymbolConstructor {
/**
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
readonly iterator: symbol;
}
@@ -32,36 +32,36 @@ interface Array<T> {
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, T]>;
/**
* Returns an list of keys in the array
*/
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
* Returns an list of values in the array
*/
values(): IterableIterator<T>;
}
interface ArrayConstructor {
/**
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(iterable: Iterable<T>, mapfn: (this: undefined, v: T, k: number) => U): Array<U>;
from<T, U>(iterable: Iterable<T>, mapfn: (this: undefined, v: T, k: number) => U, thisArg: undefined): Array<U>;
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(iterable: Iterable<T>, mapfn: (this: void, v: T, k: number) => U): Array<U>;
from<T, U>(iterable: Iterable<T>, mapfn: (this: void, v: T, k: number) => U, thisArg: undefined): Array<U>;
from<Z, T, U>(iterable: Iterable<T>, mapfn: (this: Z, v: T, k: number) => U, thisArg: Z): Array<U>;
/**
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
*/
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
*/
from<T>(iterable: Iterable<T>): Array<T>;
}
@@ -70,18 +70,18 @@ interface ReadonlyArray<T> {
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, T]>;
/**
* Returns an list of keys in the array
*/
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
* Returns an list of values in the array
*/
values(): IterableIterator<T>;
}
@@ -118,10 +118,10 @@ interface SetConstructor {
new <T>(iterable: Iterable<T>): Set<T>;
}
interface WeakSet<T> { }
interface WeakSet<T extends object> { }
interface WeakSetConstructor {
new <T>(iterable: Iterable<T>): WeakSet<T>;
new <T extends object>(iterable: Iterable<T>): WeakSet<T>;
}
interface Promise<T> { }
@@ -145,7 +145,7 @@ interface PromiseConstructor {
}
declare namespace Reflect {
function enumerate(target: any): IterableIterator<any>;
function enumerate(target: object): IterableIterator<any>;
}
interface String {
@@ -154,22 +154,22 @@ interface String {
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
@@ -177,35 +177,35 @@ interface Int8ArrayConstructor {
new (elements: Iterable<number>): Int8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number): Int8Array;
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Int8Array;
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number): Int8Array;
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int8Array;
from<Z>(arrayLike: Iterable<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int8Array;
from(arrayLike: Iterable<number>): Int8Array;
}
/**
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
@@ -213,37 +213,37 @@ interface Uint8ArrayConstructor {
new (elements: Iterable<number>): Uint8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number): Uint8Array;
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Uint8Array;
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number): Uint8Array;
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8Array;
from<Z>(arrayLike: Iterable<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8Array;
from(arrayLike: Iterable<number>): Uint8Array;
}
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
@@ -252,37 +252,37 @@ interface Uint8ClampedArrayConstructor {
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number): Uint8ClampedArray;
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray;
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number): Uint8ClampedArray;
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray;
from<Z>(arrayLike: Iterable<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8ClampedArray;
from(arrayLike: Iterable<number>): Uint8ClampedArray;
}
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
@@ -290,35 +290,35 @@ interface Int16ArrayConstructor {
new (elements: Iterable<number>): Int16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number): Int16Array;
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Int16Array;
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number): Int16Array;
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int16Array;
from<Z>(arrayLike: Iterable<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int16Array;
from(arrayLike: Iterable<number>): Int16Array;
}
/**
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
@@ -326,35 +326,35 @@ interface Uint16ArrayConstructor {
new (elements: Iterable<number>): Uint16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number): Uint16Array;
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Uint16Array;
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number): Uint16Array;
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint16Array;
from<Z>(arrayLike: Iterable<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint16Array;
from(arrayLike: Iterable<number>): Uint16Array;
}
/**
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
@@ -362,35 +362,35 @@ interface Int32ArrayConstructor {
new (elements: Iterable<number>): Int32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number): Int32Array;
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Int32Array;
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number): Int32Array;
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int32Array;
from<Z>(arrayLike: Iterable<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int32Array;
from(arrayLike: Iterable<number>): Int32Array;
}
/**
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
@@ -398,35 +398,35 @@ interface Uint32ArrayConstructor {
new (elements: Iterable<number>): Uint32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number): Uint32Array;
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Uint32Array;
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number): Uint32Array;
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint32Array;
from<Z>(arrayLike: Iterable<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint32Array;
from(arrayLike: Iterable<number>): Uint32Array;
}
/**
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
@@ -434,35 +434,35 @@ interface Float32ArrayConstructor {
new (elements: Iterable<number>): Float32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number): Float32Array;
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Float32Array;
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number): Float32Array;
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float32Array;
from<Z>(arrayLike: Iterable<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float32Array;
from(arrayLike: Iterable<number>): Float32Array;
}
/**
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
[Symbol.iterator](): IterableIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
@@ -470,13 +470,13 @@ interface Float64ArrayConstructor {
new (elements: Iterable<number>): Float64Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number): Float64Array;
from(arrayLike: Iterable<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Float64Array;
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number): Float64Array;
from(arrayLike: Iterable<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float64Array;
from<Z>(arrayLike: Iterable<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float64Array;
from(arrayLike: Iterable<number>): Float64Array;
+6 -6
View File
@@ -1,7 +1,7 @@
interface PromiseConstructor {
/**
* A reference to the prototype.
*/
* A reference to the prototype.
*/
readonly prototype: Promise<any>;
/**
@@ -187,10 +187,10 @@ interface PromiseConstructor {
reject<T>(reason: any): Promise<T>;
/**
* Creates a new resolved promise for the provided value.
* @param value A promise.
* @returns A promise whose internal state matches the provided promise.
*/
* Creates a new resolved promise for the provided value.
* @param value A promise.
* @returns A promise whose internal state matches the provided promise.
*/
resolve<T>(value: T | PromiseLike<T>): Promise<T>;
/**
+3 -3
View File
@@ -1,4 +1,4 @@
interface ProxyHandler<T> {
interface ProxyHandler<T extends object> {
getPrototypeOf? (target: T): object | null;
setPrototypeOf? (target: T, v: any): boolean;
isExtensible? (target: T): boolean;
@@ -16,7 +16,7 @@ interface ProxyHandler<T> {
}
interface ProxyConstructor {
revocable<T>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
new <T>(target: T, handler: ProxyHandler<T>): T;
revocable<T extends object>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
new <T extends object>(target: T, handler: ProxyHandler<T>): T;
}
declare var Proxy: ProxyConstructor;
+12 -12
View File
@@ -1,15 +1,15 @@
declare namespace Reflect {
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
function construct(target: Function, argumentsList: ArrayLike<any>, newTarget?: any): any;
function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;
function deleteProperty(target: any, propertyKey: PropertyKey): boolean;
function get(target: any, propertyKey: PropertyKey, receiver?: any): any;
function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor;
function getPrototypeOf(target: any): any;
function has(target: any, propertyKey: PropertyKey): boolean;
function isExtensible(target: any): boolean;
function ownKeys(target: any): Array<PropertyKey>;
function preventExtensions(target: any): boolean;
function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean;
function setPrototypeOf(target: any, proto: any): boolean;
}
function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;
function deleteProperty(target: object, propertyKey: PropertyKey): boolean;
function get(target: object, propertyKey: PropertyKey, receiver?: any): any;
function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor;
function getPrototypeOf(target: object): object;
function has(target: object, propertyKey: PropertyKey): boolean;
function isExtensible(target: object): boolean;
function ownKeys(target: object): Array<PropertyKey>;
function preventExtensions(target: object): boolean;
function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean;
function setPrototypeOf(target: object, proto: any): boolean;
}
+13 -13
View File
@@ -8,28 +8,28 @@ interface Symbol {
interface SymbolConstructor {
/**
* A reference to the prototype.
*/
* A reference to the prototype.
*/
readonly prototype: Symbol;
/**
* Returns a new unique Symbol value.
* @param description Description of the new Symbol object.
*/
* Returns a new unique Symbol value.
* @param description Description of the new Symbol object.
*/
(description?: string | number): symbol;
/**
* Returns a Symbol object from the global symbol registry matching the given key if found.
* Otherwise, returns a new symbol with this key.
* @param key key to search for.
*/
* Returns a Symbol object from the global symbol registry matching the given key if found.
* Otherwise, returns a new symbol with this key.
* @param key key to search for.
*/
for(key: string): symbol;
/**
* Returns a key from the global symbol registry matching the given Symbol if found.
* Otherwise, returns a undefined.
* @param sym Symbol to find the key for.
*/
* Returns a key from the global symbol registry matching the given Symbol if found.
* Otherwise, returns a undefined.
* @param sym Symbol to find the key for.
*/
keyFor(sym: symbol): string | undefined;
}
+113 -113
View File
@@ -2,63 +2,63 @@
interface SymbolConstructor {
/**
* A method that determines if a constructor object recognizes an object as one of the
* constructors instances. Called by the semantics of the instanceof operator.
*/
* A method that determines if a constructor object recognizes an object as one of the
* constructors instances. Called by the semantics of the instanceof operator.
*/
readonly hasInstance: symbol;
/**
* A Boolean value that if true indicates that an object should flatten to its array elements
* by Array.prototype.concat.
*/
* A Boolean value that if true indicates that an object should flatten to its array elements
* by Array.prototype.concat.
*/
readonly isConcatSpreadable: symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
*/
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
*/
readonly match: symbol;
/**
* A regular expression method that replaces matched substrings of a string. Called by the
* String.prototype.replace method.
*/
* A regular expression method that replaces matched substrings of a string. Called by the
* String.prototype.replace method.
*/
readonly replace: symbol;
/**
* A regular expression method that returns the index within a string that matches the
* regular expression. Called by the String.prototype.search method.
*/
* A regular expression method that returns the index within a string that matches the
* regular expression. Called by the String.prototype.search method.
*/
readonly search: symbol;
/**
* A function valued property that is the constructor function that is used to create
* derived objects.
*/
* A function valued property that is the constructor function that is used to create
* derived objects.
*/
readonly species: symbol;
/**
* A regular expression method that splits a string at the indices that match the regular
* expression. Called by the String.prototype.split method.
*/
* A regular expression method that splits a string at the indices that match the regular
* expression. Called by the String.prototype.split method.
*/
readonly split: symbol;
/**
* A method that converts an object to a corresponding primitive value.
* Called by the ToPrimitive abstract operation.
*/
* A method that converts an object to a corresponding primitive value.
* Called by the ToPrimitive abstract operation.
*/
readonly toPrimitive: symbol;
/**
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
readonly toStringTag: symbol;
/**
* An Object whose own property names are property names that are excluded from the 'with'
* environment bindings of the associated objects.
*/
* An Object whose own property names are property names that are excluded from the 'with'
* environment bindings of the associated objects.
*/
readonly unscopables: symbol;
}
@@ -118,7 +118,7 @@ interface Set<T> {
readonly [Symbol.toStringTag]: "Set";
}
interface WeakSet<T> {
interface WeakSet<T extends object> {
readonly [Symbol.toStringTag]: "WeakSet";
}
@@ -154,50 +154,50 @@ interface PromiseConstructor {
}
interface RegExp {
/**
* Matches a string with this regular expression, and returns an array containing the results of
* that search.
* @param string A string to search within.
*/
/**
* Matches a string with this regular expression, and returns an array containing the results of
* that search.
* @param string A string to search within.
*/
[Symbol.match](string: string): RegExpMatchArray | null;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replaceValue A String object or string literal containing the text to replace for every
* successful match of this regular expression.
*/
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replaceValue A String object or string literal containing the text to replace for every
* successful match of this regular expression.
*/
[Symbol.replace](string: string, replaceValue: string): string;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replacer A function that returns the replacement text.
*/
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replacer A function that returns the replacement text.
*/
[Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the position beginning first substring match in a regular expression search
* using this regular expression.
*
* @param string The string to search within.
*/
* Finds the position beginning first substring match in a regular expression search
* using this regular expression.
*
* @param string The string to search within.
*/
[Symbol.search](string: string): number;
/**
* Returns an array of substrings that were delimited by strings in the original input that
* match against this regular expression.
*
* If the regular expression contains capturing parentheses, then each time this
* regular expression matches, the results (including any undefined results) of the
* capturing parentheses are spliced.
*
* @param string string value to split
* @param limit if not undefined, the output array is truncated so that it contains no more
* than 'limit' elements.
*/
* Returns an array of substrings that were delimited by strings in the original input that
* match against this regular expression.
*
* If the regular expression contains capturing parentheses, then each time this
* regular expression matches, the results (including any undefined results) of the
* capturing parentheses are spliced.
*
* @param string string value to split
* @param limit if not undefined, the output array is truncated so that it contains no more
* than 'limit' elements.
*/
[Symbol.split](string: string, limit?: number): string[];
}
@@ -207,45 +207,45 @@ interface RegExpConstructor {
interface String {
/**
* Matches a string an object that supports being matched against, and returns an array containing the results of that search.
* @param matcher An object that supports being matched against.
*/
* Matches a string an object that supports being matched against, and returns an array containing the results of that search.
* @param matcher An object that supports being matched against.
*/
match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
*/
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
*/
replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replacer A function that returns the replacement text.
*/
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replacer A function that returns the replacement text.
*/
replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the first substring match in a regular expression search.
* @param searcher An object which supports searching within a string.
*/
* Finds the first substring match in a regular expression search.
* @param searcher An object which supports searching within a string.
*/
search(searcher: { [Symbol.search](string: string): number; }): number;
/**
* Split a string into substrings using the specified separator and return them as an array.
* @param splitter An object that can split a string.
* @param limit A value used to limit the number of elements returned in the array.
*/
* Split a string into substrings using the specified separator and return them as an array.
* @param splitter An object that can split a string.
* @param limit A value used to limit the number of elements returned in the array.
*/
split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[];
}
/**
* Represents a raw buffer of binary data, which is used to store data for the
* different typed arrays. ArrayBuffers cannot be read from or written to directly,
* but can be passed to a typed array or DataView Object to interpret the raw
* buffer as needed.
*/
* Represents a raw buffer of binary data, which is used to store data for the
* different typed arrays. ArrayBuffers cannot be read from or written to directly,
* but can be passed to a typed array or DataView Object to interpret the raw
* buffer as needed.
*/
interface ArrayBuffer {
readonly [Symbol.toStringTag]: "ArrayBuffer";
}
@@ -255,73 +255,73 @@ interface DataView {
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
readonly [Symbol.toStringTag]: "Int8Array";
}
/**
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
readonly [Symbol.toStringTag]: "UInt8Array";
}
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
readonly [Symbol.toStringTag]: "Uint8ClampedArray";
}
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
readonly [Symbol.toStringTag]: "Int16Array";
}
/**
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
readonly [Symbol.toStringTag]: "Uint16Array";
}
/**
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
readonly [Symbol.toStringTag]: "Int32Array";
}
/**
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
readonly [Symbol.toStringTag]: "Uint32Array";
}
/**
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
readonly [Symbol.toStringTag]: "Float32Array";
}
/**
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
readonly [Symbol.toStringTag]: "Float64Array";
}
+44 -44
View File
@@ -1,98 +1,98 @@
interface Array<T> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: T, fromIndex?: number): boolean;
}
interface ReadonlyArray<T> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: T, fromIndex?: number): boolean;
}
interface Int8Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint8Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint8ClampedArray {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Int16Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint16Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Int32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Float32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Float64Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
+12 -12
View File
@@ -1,25 +1,25 @@
interface ObjectConstructor {
/**
* Returns an array of values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
* Returns an array of values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
values<T>(o: { [s: string]: T }): T[];
/**
* Returns an array of values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
* Returns an array of values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
values(o: any): any[];
/**
* Returns an array of key/values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
* Returns an array of key/values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries<T>(o: { [s: string]: T }): [string, T][];
/**
* Returns an array of key/values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
* Returns an array of key/values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries(o: any): [string, any][];
}
+4 -4
View File
@@ -3,8 +3,8 @@
interface SharedArrayBuffer {
/**
* Read-only. The length of the ArrayBuffer (in bytes).
*/
* Read-only. The length of the ArrayBuffer (in bytes).
*/
readonly byteLength: number;
/*
@@ -12,8 +12,8 @@ interface SharedArrayBuffer {
*/
length: number;
/**
* Returns a section of an SharedArrayBuffer.
*/
* Returns a section of an SharedArrayBuffer.
*/
slice(begin: number, end?: number): SharedArrayBuffer;
readonly [Symbol.species]: SharedArrayBuffer;
readonly [Symbol.toStringTag]: "SharedArrayBuffer";
+20 -20
View File
@@ -1,27 +1,27 @@
interface String {
/**
* Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length.
* The padding is applied from the start (left) of the current string.
*
* @param maxLength The length of the resulting string once the current string has been padded.
* If this parameter is smaller than the current string's length, the current string will be returned as it is.
*
* @param fillString The string to pad the current string with.
* If this string is too long, it will be truncated and the left-most part will be applied.
* The default value for this parameter is " " (U+0020).
*/
* Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length.
* The padding is applied from the start (left) of the current string.
*
* @param maxLength The length of the resulting string once the current string has been padded.
* If this parameter is smaller than the current string's length, the current string will be returned as it is.
*
* @param fillString The string to pad the current string with.
* If this string is too long, it will be truncated and the left-most part will be applied.
* The default value for this parameter is " " (U+0020).
*/
padStart(maxLength: number, fillString?: string): string;
/**
* Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length.
* The padding is applied from the end (right) of the current string.
*
* @param maxLength The length of the resulting string once the current string has been padded.
* If this parameter is smaller than the current string's length, the current string will be returned as it is.
*
* @param fillString The string to pad the current string with.
* If this string is too long, it will be truncated and the left-most part will be applied.
* The default value for this parameter is " " (U+0020).
*/
* Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length.
* The padding is applied from the end (right) of the current string.
*
* @param maxLength The length of the resulting string once the current string has been padded.
* If this parameter is smaller than the current string's length, the current string will be returned as it is.
*
* @param fillString The string to pad the current string with.
* If this string is too long, it will be truncated and the left-most part will be applied.
* The default value for this parameter is " " (U+0020).
*/
padEnd(maxLength: number, fillString?: string): string;
}
+174 -174
View File
@@ -1017,48 +1017,48 @@ interface ReadonlyArray<T> {
* @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (this: undefined, value: T, index: number, array: ReadonlyArray<T>) => boolean): boolean;
every(callbackfn: (this: undefined, value: T, index: number, array: ReadonlyArray<T>) => boolean, thisArg: undefined): boolean;
every(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray<T>) => boolean): boolean;
every(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray<T>) => boolean, thisArg: undefined): boolean;
every<Z>(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray<T>) => boolean, thisArg: Z): boolean;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (this: undefined, value: T, index: number, array: ReadonlyArray<T>) => boolean): boolean;
some(callbackfn: (this: undefined, value: T, index: number, array: ReadonlyArray<T>) => boolean, thisArg: undefined): boolean;
some(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray<T>) => boolean): boolean;
some(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray<T>) => boolean, thisArg: undefined): boolean;
some<Z>(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray<T>) => boolean, thisArg: Z): boolean;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (this: undefined, value: T, index: number, array: ReadonlyArray<T>) => void): void;
forEach(callbackfn: (this: undefined, value: T, index: number, array: ReadonlyArray<T>) => void, thisArg: undefined): void;
forEach(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray<T>) => void): void;
forEach(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray<T>) => void, thisArg: undefined): void;
forEach<Z>(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray<T>) => void, thisArg: Z): void;
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(callbackfn: (this: undefined, value: T, index: number, array: ReadonlyArray<T>) => U): U[];
map<U>(callbackfn: (this: undefined, value: T, index: number, array: ReadonlyArray<T>) => U, thisArg: undefined): U[];
map<U>(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray<T>) => U): U[];
map<U>(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray<T>) => U, thisArg: undefined): U[];
map<Z, U>(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray<T>) => U, thisArg: Z): U[];
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
filter<S extends T>(callbackfn: (this: undefined, value: T, index: number, array: ReadonlyArray<T>) => value is S): S[];
filter<S extends T>(callbackfn: (this: undefined, value: T, index: number, array: ReadonlyArray<T>) => value is S, thisArg: undefined): S[];
filter<S extends T>(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray<T>) => value is S): S[];
filter<S extends T>(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray<T>) => value is S, thisArg: undefined): S[];
filter<Z, S extends T>(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray<T>) => value is S, thisArg: Z): S[];
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (this: undefined, value: T, index: number, array: ReadonlyArray<T>) => any): T[];
filter(callbackfn: (this: undefined, value: T, index: number, array: ReadonlyArray<T>) => any, thisArg: undefined): T[];
filter(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray<T>) => any): T[];
filter(callbackfn: (this: void, value: T, index: number, array: ReadonlyArray<T>) => any, thisArg: undefined): T[];
filter<Z>(callbackfn: (this: Z, value: T, index: number, array: ReadonlyArray<T>) => any, thisArg: Z): T[];
/**
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
@@ -1176,72 +1176,72 @@ interface Array<T> {
* @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (this: undefined, value: T, index: number, array: T[]) => boolean): boolean;
every(callbackfn: (this: undefined, value: T, index: number, array: T[]) => boolean, thisArg: undefined): boolean;
every(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): boolean;
every(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean, thisArg: undefined): boolean;
every<Z>(callbackfn: (this: Z, value: T, index: number, array: T[]) => boolean, thisArg: Z): boolean;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (this: undefined, value: T, index: number, array: T[]) => boolean): boolean;
some(callbackfn: (this: undefined, value: T, index: number, array: T[]) => boolean, thisArg: undefined): boolean;
some(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean): boolean;
some(callbackfn: (this: void, value: T, index: number, array: T[]) => boolean, thisArg: undefined): boolean;
some<Z>(callbackfn: (this: Z, value: T, index: number, array: T[]) => boolean, thisArg: Z): boolean;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (this: undefined, value: T, index: number, array: T[]) => void): void;
forEach(callbackfn: (this: undefined, value: T, index: number, array: T[]) => void, thisArg: undefined): void;
forEach(callbackfn: (this: void, value: T, index: number, array: T[]) => void): void;
forEach(callbackfn: (this: void, value: T, index: number, array: T[]) => void, thisArg: undefined): void;
forEach<Z>(callbackfn: (this: Z, value: T, index: number, array: T[]) => void, thisArg: Z): void;
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T, T, T], callbackfn: (this: undefined, value: T, index: number, array: T[]) => U): [U, U, U, U, U];
map<U>(this: [T, T, T, T, T], callbackfn: (this: undefined, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U, U, U, U];
map<U>(this: [T, T, T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U): [U, U, U, U, U];
map<U>(this: [T, T, T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U, U, U, U];
map<Z, U>(this: [T, T, T, T, T], callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): [U, U, U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T, T], callbackfn: (this: undefined, value: T, index: number, array: T[]) => U): [U, U, U, U];
map<U>(this: [T, T, T, T], callbackfn: (this: undefined, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U, U, U];
map<U>(this: [T, T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U): [U, U, U, U];
map<U>(this: [T, T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U, U, U];
map<Z, U>(this: [T, T, T, T], callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): [U, U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T, T], callbackfn: (this: undefined, value: T, index: number, array: T[]) => U): [U, U, U];
map<U>(this: [T, T, T], callbackfn: (this: undefined, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U, U];
map<U>(this: [T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U): [U, U, U];
map<U>(this: [T, T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U, U];
map<Z, U>(this: [T, T, T], callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): [U, U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(this: [T, T], callbackfn: (this: undefined, value: T, index: number, array: T[]) => U): [U, U];
map<U>(this: [T, T], callbackfn: (this: undefined, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U];
map<U>(this: [T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U): [U, U];
map<U>(this: [T, T], callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): [U, U];
map<Z, U>(this: [T, T], callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): [U, U];
/**
* Calls a defined callback function on each element of an array, and returns an array that contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
map<U>(callbackfn: (this: undefined, value: T, index: number, array: T[]) => U): U[];
map<U>(callbackfn: (this: undefined, value: T, index: number, array: T[]) => U, thisArg: undefined): U[];
map<U>(callbackfn: (this: void, value: T, index: number, array: T[]) => U): U[];
map<U>(callbackfn: (this: void, value: T, index: number, array: T[]) => U, thisArg: undefined): U[];
map<Z, U>(callbackfn: (this: Z, value: T, index: number, array: T[]) => U, thisArg: Z): U[];
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (this: undefined, value: T, index: number, array: T[]) => any): T[];
filter(callbackfn: (this: undefined, value: T, index: number, array: T[]) => any, thisArg: undefined): T[];
filter(callbackfn: (this: void, value: T, index: number, array: T[]) => any): T[];
filter(callbackfn: (this: void, value: T, index: number, array: T[]) => any, thisArg: undefined): T[];
filter<Z>(callbackfn: (this: Z, value: T, index: number, array: T[]) => any, thisArg: Z): T[];
/**
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
@@ -1587,8 +1587,8 @@ interface Int8Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (this: undefined, value: number, index: number, array: Int8Array) => boolean): boolean;
every(callbackfn: (this: undefined, value: number, index: number, array: Int8Array) => boolean, thisArg: undefined): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Int8Array) => boolean): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Int8Array) => boolean, thisArg: undefined): boolean;
every<Z>(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => boolean, thisArg: Z): boolean;
/**
@@ -1608,8 +1608,8 @@ interface Int8Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (this: undefined, value: number, index: number, array: Int8Array) => any): Int8Array;
filter(callbackfn: (this: undefined, value: number, index: number, array: Int8Array) => any, thisArg: undefined): Int8Array;
filter(callbackfn: (this: void, value: number, index: number, array: Int8Array) => any): Int8Array;
filter(callbackfn: (this: void, value: number, index: number, array: Int8Array) => any, thisArg: undefined): Int8Array;
filter<Z>(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => any, thisArg: Z): Int8Array;
/**
@@ -1621,8 +1621,8 @@ interface Int8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number | undefined;
/**
@@ -1634,8 +1634,8 @@ interface Int8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number;
/**
@@ -1645,8 +1645,8 @@ interface Int8Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (this: undefined, value: number, index: number, array: Int8Array) => void): void;
forEach(callbackfn: (this: undefined, value: number, index: number, array: Int8Array) => void, thisArg: undefined): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Int8Array) => void): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Int8Array) => void, thisArg: undefined): void;
forEach<Z>(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => void, thisArg: Z): void;
/**
@@ -1685,8 +1685,8 @@ interface Int8Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (this: undefined, value: number, index: number, array: Int8Array) => number): Int8Array;
map(callbackfn: (this: undefined, value: number, index: number, array: Int8Array) => number, thisArg: undefined): Int8Array;
map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number): Int8Array;
map(callbackfn: (this: void, value: number, index: number, array: Int8Array) => number, thisArg: undefined): Int8Array;
map<Z>(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => number, thisArg: Z): Int8Array;
/**
@@ -1771,8 +1771,8 @@ interface Int8Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (this: undefined, value: number, index: number, array: Int8Array) => boolean): boolean;
some(callbackfn: (this: undefined, value: number, index: number, array: Int8Array) => boolean, thisArg: undefined): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Int8Array) => boolean): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Int8Array) => boolean, thisArg: undefined): boolean;
some<Z>(callbackfn: (this: Z, value: number, index: number, array: Int8Array) => boolean, thisArg: Z): boolean;
/**
@@ -1825,8 +1825,8 @@ interface Int8ArrayConstructor {
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number): Int8Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Int8Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number): Int8Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int8Array;
from<Z>(arrayLike: ArrayLike<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int8Array;
from(arrayLike: ArrayLike<number>): Int8Array;
@@ -1878,8 +1878,8 @@ interface Uint8Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (this: undefined, value: number, index: number, array: Uint8Array) => boolean): boolean;
every(callbackfn: (this: undefined, value: number, index: number, array: Uint8Array) => boolean, thisArg: undefined): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => boolean): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => boolean, thisArg: undefined): boolean;
every<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => boolean, thisArg: Z): boolean;
/**
@@ -1899,8 +1899,8 @@ interface Uint8Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (this: undefined, value: number, index: number, array: Uint8Array) => any): Uint8Array;
filter(callbackfn: (this: undefined, value: number, index: number, array: Uint8Array) => any, thisArg: undefined): Uint8Array;
filter(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => any): Uint8Array;
filter(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => any, thisArg: undefined): Uint8Array;
filter<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => any, thisArg: Z): Uint8Array;
/**
@@ -1912,8 +1912,8 @@ interface Uint8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number | undefined;
/**
@@ -1925,8 +1925,8 @@ interface Uint8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number;
/**
@@ -1936,8 +1936,8 @@ interface Uint8Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (this: undefined, value: number, index: number, array: Uint8Array) => void): void;
forEach(callbackfn: (this: undefined, value: number, index: number, array: Uint8Array) => void, thisArg: undefined): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => void): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => void, thisArg: undefined): void;
forEach<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => void, thisArg: Z): void;
/**
@@ -1976,8 +1976,8 @@ interface Uint8Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (this: undefined, value: number, index: number, array: Uint8Array) => number): Uint8Array;
map(callbackfn: (this: undefined, value: number, index: number, array: Uint8Array) => number, thisArg: undefined): Uint8Array;
map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number): Uint8Array;
map(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => number, thisArg: undefined): Uint8Array;
map<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => number, thisArg: Z): Uint8Array;
/**
@@ -2062,8 +2062,8 @@ interface Uint8Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (this: undefined, value: number, index: number, array: Uint8Array) => boolean): boolean;
some(callbackfn: (this: undefined, value: number, index: number, array: Uint8Array) => boolean, thisArg: undefined): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => boolean): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Uint8Array) => boolean, thisArg: undefined): boolean;
some<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint8Array) => boolean, thisArg: Z): boolean;
/**
@@ -2117,8 +2117,8 @@ interface Uint8ArrayConstructor {
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number): Uint8Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Uint8Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number): Uint8Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8Array;
from<Z>(arrayLike: ArrayLike<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8Array;
from(arrayLike: ArrayLike<number>): Uint8Array;
@@ -2170,8 +2170,8 @@ interface Uint8ClampedArray {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (this: undefined, value: number, index: number, array: Uint8ClampedArray) => boolean): boolean;
every(callbackfn: (this: undefined, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: undefined): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => boolean): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: undefined): boolean;
every<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: Z): boolean;
/**
@@ -2191,8 +2191,8 @@ interface Uint8ClampedArray {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (this: undefined, value: number, index: number, array: Uint8ClampedArray) => any): Uint8ClampedArray;
filter(callbackfn: (this: undefined, value: number, index: number, array: Uint8ClampedArray) => any, thisArg: undefined): Uint8ClampedArray;
filter(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => any): Uint8ClampedArray;
filter(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => any, thisArg: undefined): Uint8ClampedArray;
filter<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => any, thisArg: Z): Uint8ClampedArray;
/**
@@ -2204,8 +2204,8 @@ interface Uint8ClampedArray {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number | undefined;
/**
@@ -2217,8 +2217,8 @@ interface Uint8ClampedArray {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number;
/**
@@ -2228,8 +2228,8 @@ interface Uint8ClampedArray {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (this: undefined, value: number, index: number, array: Uint8ClampedArray) => void): void;
forEach(callbackfn: (this: undefined, value: number, index: number, array: Uint8ClampedArray) => void, thisArg: undefined): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => void): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => void, thisArg: undefined): void;
forEach<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => void, thisArg: Z): void;
/**
@@ -2268,8 +2268,8 @@ interface Uint8ClampedArray {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (this: undefined, value: number, index: number, array: Uint8ClampedArray) => number): Uint8ClampedArray;
map(callbackfn: (this: undefined, value: number, index: number, array: Uint8ClampedArray) => number, thisArg: undefined): Uint8ClampedArray;
map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number): Uint8ClampedArray;
map(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => number, thisArg: undefined): Uint8ClampedArray;
map<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => number, thisArg: Z): Uint8ClampedArray;
/**
@@ -2354,8 +2354,8 @@ interface Uint8ClampedArray {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (this: undefined, value: number, index: number, array: Uint8ClampedArray) => boolean): boolean;
some(callbackfn: (this: undefined, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: undefined): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => boolean): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: undefined): boolean;
some<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg: Z): boolean;
/**
@@ -2409,8 +2409,8 @@ interface Uint8ClampedArrayConstructor {
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number): Uint8ClampedArray;
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number): Uint8ClampedArray;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint8ClampedArray;
from<Z>(arrayLike: ArrayLike<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint8ClampedArray;
from(arrayLike: ArrayLike<number>): Uint8ClampedArray;
@@ -2461,8 +2461,8 @@ interface Int16Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (this: undefined, value: number, index: number, array: Int16Array) => boolean): boolean;
every(callbackfn: (this: undefined, value: number, index: number, array: Int16Array) => boolean, thisArg: undefined): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Int16Array) => boolean): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Int16Array) => boolean, thisArg: undefined): boolean;
every<Z>(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => boolean, thisArg: Z): boolean;
/**
@@ -2482,8 +2482,8 @@ interface Int16Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (this: undefined, value: number, index: number, array: Int16Array) => any): Int16Array;
filter(callbackfn: (this: undefined, value: number, index: number, array: Int16Array) => any, thisArg: undefined): Int16Array;
filter(callbackfn: (this: void, value: number, index: number, array: Int16Array) => any): Int16Array;
filter(callbackfn: (this: void, value: number, index: number, array: Int16Array) => any, thisArg: undefined): Int16Array;
filter<Z>(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => any, thisArg: Z): Int16Array;
/**
@@ -2495,8 +2495,8 @@ interface Int16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number | undefined;
/**
@@ -2508,8 +2508,8 @@ interface Int16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number;
/**
@@ -2519,8 +2519,8 @@ interface Int16Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (this: undefined, value: number, index: number, array: Int16Array) => void): void;
forEach(callbackfn: (this: undefined, value: number, index: number, array: Int16Array) => void, thisArg: undefined): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Int16Array) => void): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Int16Array) => void, thisArg: undefined): void;
forEach<Z>(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => void, thisArg: Z): void;
/**
@@ -2559,8 +2559,8 @@ interface Int16Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (this: undefined, value: number, index: number, array: Int16Array) => number): Int16Array;
map(callbackfn: (this: undefined, value: number, index: number, array: Int16Array) => number, thisArg: undefined): Int16Array;
map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number): Int16Array;
map(callbackfn: (this: void, value: number, index: number, array: Int16Array) => number, thisArg: undefined): Int16Array;
map<Z>(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => number, thisArg: Z): Int16Array;
/**
@@ -2645,8 +2645,8 @@ interface Int16Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (this: undefined, value: number, index: number, array: Int16Array) => boolean): boolean;
some(callbackfn: (this: undefined, value: number, index: number, array: Int16Array) => boolean, thisArg: undefined): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Int16Array) => boolean): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Int16Array) => boolean, thisArg: undefined): boolean;
some<Z>(callbackfn: (this: Z, value: number, index: number, array: Int16Array) => boolean, thisArg: Z): boolean;
/**
@@ -2700,8 +2700,8 @@ interface Int16ArrayConstructor {
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number): Int16Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Int16Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number): Int16Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int16Array;
from<Z>(arrayLike: ArrayLike<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int16Array;
from(arrayLike: ArrayLike<number>): Int16Array;
@@ -2753,8 +2753,8 @@ interface Uint16Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (this: undefined, value: number, index: number, array: Uint16Array) => boolean): boolean;
every(callbackfn: (this: undefined, value: number, index: number, array: Uint16Array) => boolean, thisArg: undefined): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => boolean): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => boolean, thisArg: undefined): boolean;
every<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => boolean, thisArg: Z): boolean;
/**
@@ -2774,8 +2774,8 @@ interface Uint16Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (this: undefined, value: number, index: number, array: Uint16Array) => any): Uint16Array;
filter(callbackfn: (this: undefined, value: number, index: number, array: Uint16Array) => any, thisArg: undefined): Uint16Array;
filter(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => any): Uint16Array;
filter(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => any, thisArg: undefined): Uint16Array;
filter<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => any, thisArg: Z): Uint16Array;
/**
@@ -2787,8 +2787,8 @@ interface Uint16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number | undefined;
/**
@@ -2800,8 +2800,8 @@ interface Uint16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number;
/**
@@ -2811,8 +2811,8 @@ interface Uint16Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (this: undefined, value: number, index: number, array: Uint16Array) => void): void;
forEach(callbackfn: (this: undefined, value: number, index: number, array: Uint16Array) => void, thisArg: undefined): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => void): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => void, thisArg: undefined): void;
forEach<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => void, thisArg: Z): void;
/**
@@ -2851,8 +2851,8 @@ interface Uint16Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (this: undefined, value: number, index: number, array: Uint16Array) => number): Uint16Array;
map(callbackfn: (this: undefined, value: number, index: number, array: Uint16Array) => number, thisArg: undefined): Uint16Array;
map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number): Uint16Array;
map(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => number, thisArg: undefined): Uint16Array;
map<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => number, thisArg: Z): Uint16Array;
/**
@@ -2937,8 +2937,8 @@ interface Uint16Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (this: undefined, value: number, index: number, array: Uint16Array) => boolean): boolean;
some(callbackfn: (this: undefined, value: number, index: number, array: Uint16Array) => boolean, thisArg: undefined): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => boolean): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Uint16Array) => boolean, thisArg: undefined): boolean;
some<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint16Array) => boolean, thisArg: Z): boolean;
/**
@@ -2992,8 +2992,8 @@ interface Uint16ArrayConstructor {
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number): Uint16Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Uint16Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number): Uint16Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint16Array;
from<Z>(arrayLike: ArrayLike<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint16Array;
from(arrayLike: ArrayLike<number>): Uint16Array;
@@ -3044,8 +3044,8 @@ interface Int32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (this: undefined, value: number, index: number, array: Int32Array) => boolean): boolean;
every(callbackfn: (this: undefined, value: number, index: number, array: Int32Array) => boolean, thisArg: undefined): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Int32Array) => boolean): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Int32Array) => boolean, thisArg: undefined): boolean;
every<Z>(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => boolean, thisArg: Z): boolean;
/**
@@ -3065,8 +3065,8 @@ interface Int32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (this: undefined, value: number, index: number, array: Int32Array) => any): Int32Array;
filter(callbackfn: (this: undefined, value: number, index: number, array: Int32Array) => any, thisArg: undefined): Int32Array;
filter(callbackfn: (this: void, value: number, index: number, array: Int32Array) => any): Int32Array;
filter(callbackfn: (this: void, value: number, index: number, array: Int32Array) => any, thisArg: undefined): Int32Array;
filter<Z>(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => any, thisArg: Z): Int32Array;
/**
@@ -3078,8 +3078,8 @@ interface Int32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number | undefined;
/**
@@ -3091,8 +3091,8 @@ interface Int32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number;
/**
@@ -3102,8 +3102,8 @@ interface Int32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (this: undefined, value: number, index: number, array: Int32Array) => void): void;
forEach(callbackfn: (this: undefined, value: number, index: number, array: Int32Array) => void, thisArg: undefined): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Int32Array) => void): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Int32Array) => void, thisArg: undefined): void;
forEach<Z>(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => void, thisArg: Z): void;
/**
@@ -3142,8 +3142,8 @@ interface Int32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (this: undefined, value: number, index: number, array: Int32Array) => number): Int32Array;
map(callbackfn: (this: undefined, value: number, index: number, array: Int32Array) => number, thisArg: undefined): Int32Array;
map(callbackfn: (this: void, value: number, index: number, array: Int32Array) => number): Int32Array;
map(callbackfn: (this: void, value: number, index: number, array: Int32Array) => number, thisArg: undefined): Int32Array;
map<Z>(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => number, thisArg: Z): Int32Array;
/**
@@ -3228,8 +3228,8 @@ interface Int32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (this: undefined, value: number, index: number, array: Int32Array) => boolean): boolean;
some(callbackfn: (this: undefined, value: number, index: number, array: Int32Array) => boolean, thisArg: undefined): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Int32Array) => boolean): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Int32Array) => boolean, thisArg: undefined): boolean;
some<Z>(callbackfn: (this: Z, value: number, index: number, array: Int32Array) => boolean, thisArg: Z): boolean;
/**
@@ -3283,8 +3283,8 @@ interface Int32ArrayConstructor {
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number): Int32Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Int32Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number): Int32Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Int32Array;
from<Z>(arrayLike: ArrayLike<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Int32Array;
from(arrayLike: ArrayLike<number>): Int32Array;
@@ -3335,8 +3335,8 @@ interface Uint32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (this: undefined, value: number, index: number, array: Uint32Array) => boolean): boolean;
every(callbackfn: (this: undefined, value: number, index: number, array: Uint32Array) => boolean, thisArg: undefined): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => boolean): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => boolean, thisArg: undefined): boolean;
every<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => boolean, thisArg: Z): boolean;
/**
@@ -3356,8 +3356,8 @@ interface Uint32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (this: undefined, value: number, index: number, array: Uint32Array) => any): Uint32Array;
filter(callbackfn: (this: undefined, value: number, index: number, array: Uint32Array) => any, thisArg: undefined): Uint32Array;
filter(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => any): Uint32Array;
filter(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => any, thisArg: undefined): Uint32Array;
filter<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => any, thisArg: Z): Uint32Array;
/**
@@ -3369,8 +3369,8 @@ interface Uint32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number | undefined;
/**
@@ -3382,8 +3382,8 @@ interface Uint32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number;
/**
@@ -3393,8 +3393,8 @@ interface Uint32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (this: undefined, value: number, index: number, array: Uint32Array) => void): void;
forEach(callbackfn: (this: undefined, value: number, index: number, array: Uint32Array) => void, thisArg: undefined): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => void): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => void, thisArg: undefined): void;
forEach<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => void, thisArg: Z): void;
/**
@@ -3433,8 +3433,8 @@ interface Uint32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (this: undefined, value: number, index: number, array: Uint32Array) => number): Uint32Array;
map(callbackfn: (this: undefined, value: number, index: number, array: Uint32Array) => number, thisArg: undefined): Uint32Array;
map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number): Uint32Array;
map(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => number, thisArg: undefined): Uint32Array;
map<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => number, thisArg: Z): Uint32Array;
/**
@@ -3519,8 +3519,8 @@ interface Uint32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (this: undefined, value: number, index: number, array: Uint32Array) => boolean): boolean;
some(callbackfn: (this: undefined, value: number, index: number, array: Uint32Array) => boolean, thisArg: undefined): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => boolean): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Uint32Array) => boolean, thisArg: undefined): boolean;
some<Z>(callbackfn: (this: Z, value: number, index: number, array: Uint32Array) => boolean, thisArg: Z): boolean;
/**
@@ -3574,8 +3574,8 @@ interface Uint32ArrayConstructor {
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number): Uint32Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Uint32Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number): Uint32Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Uint32Array;
from<Z>(arrayLike: ArrayLike<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Uint32Array;
from(arrayLike: ArrayLike<number>): Uint32Array;
@@ -3626,8 +3626,8 @@ interface Float32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (this: undefined, value: number, index: number, array: Float32Array) => boolean): boolean;
every(callbackfn: (this: undefined, value: number, index: number, array: Float32Array) => boolean, thisArg: undefined): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Float32Array) => boolean): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Float32Array) => boolean, thisArg: undefined): boolean;
every<Z>(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => boolean, thisArg: Z): boolean;
/**
@@ -3647,8 +3647,8 @@ interface Float32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (this: undefined, value: number, index: number, array: Float32Array) => any): Float32Array;
filter(callbackfn: (this: undefined, value: number, index: number, array: Float32Array) => any, thisArg: undefined): Float32Array;
filter(callbackfn: (this: void, value: number, index: number, array: Float32Array) => any): Float32Array;
filter(callbackfn: (this: void, value: number, index: number, array: Float32Array) => any, thisArg: undefined): Float32Array;
filter<Z>(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => any, thisArg: Z): Float32Array;
/**
@@ -3660,8 +3660,8 @@ interface Float32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number | undefined;
/**
@@ -3673,8 +3673,8 @@ interface Float32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number;
/**
@@ -3684,8 +3684,8 @@ interface Float32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (this: undefined, value: number, index: number, array: Float32Array) => void): void;
forEach(callbackfn: (this: undefined, value: number, index: number, array: Float32Array) => void, thisArg: undefined): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Float32Array) => void): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Float32Array) => void, thisArg: undefined): void;
forEach<Z>(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => void, thisArg: Z): void;
/**
@@ -3724,8 +3724,8 @@ interface Float32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (this: undefined, value: number, index: number, array: Float32Array) => number): Float32Array;
map(callbackfn: (this: undefined, value: number, index: number, array: Float32Array) => number, thisArg: undefined): Float32Array;
map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number): Float32Array;
map(callbackfn: (this: void, value: number, index: number, array: Float32Array) => number, thisArg: undefined): Float32Array;
map<Z>(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => number, thisArg: Z): Float32Array;
/**
@@ -3810,8 +3810,8 @@ interface Float32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (this: undefined, value: number, index: number, array: Float32Array) => boolean): boolean;
some(callbackfn: (this: undefined, value: number, index: number, array: Float32Array) => boolean, thisArg: undefined): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Float32Array) => boolean): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Float32Array) => boolean, thisArg: undefined): boolean;
some<Z>(callbackfn: (this: Z, value: number, index: number, array: Float32Array) => boolean, thisArg: Z): boolean;
/**
@@ -3865,8 +3865,8 @@ interface Float32ArrayConstructor {
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number): Float32Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Float32Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number): Float32Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float32Array;
from<Z>(arrayLike: ArrayLike<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float32Array;
from(arrayLike: ArrayLike<number>): Float32Array;
@@ -3918,8 +3918,8 @@ interface Float64Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(callbackfn: (this: undefined, value: number, index: number, array: Float64Array) => boolean): boolean;
every(callbackfn: (this: undefined, value: number, index: number, array: Float64Array) => boolean, thisArg: undefined): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Float64Array) => boolean): boolean;
every(callbackfn: (this: void, value: number, index: number, array: Float64Array) => boolean, thisArg: undefined): boolean;
every<Z>(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => boolean, thisArg: Z): boolean;
/**
@@ -3939,8 +3939,8 @@ interface Float64Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (this: undefined, value: number, index: number, array: Float64Array) => any): Float64Array;
filter(callbackfn: (this: undefined, value: number, index: number, array: Float64Array) => any, thisArg: undefined): Float64Array;
filter(callbackfn: (this: void, value: number, index: number, array: Float64Array) => any): Float64Array;
filter(callbackfn: (this: void, value: number, index: number, array: Float64Array) => any, thisArg: undefined): Float64Array;
filter<Z>(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => any, thisArg: Z): Float64Array;
/**
@@ -3952,8 +3952,8 @@ interface Float64Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number | undefined;
find(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number | undefined;
find<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number | undefined;
/**
@@ -3965,8 +3965,8 @@ interface Float64Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: undefined, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean): number;
findIndex(predicate: (this: void, value: number, index: number, obj: Array<number>) => boolean, thisArg: undefined): number;
findIndex<Z>(predicate: (this: Z, value: number, index: number, obj: Array<number>) => boolean, thisArg: Z): number;
/**
@@ -3976,8 +3976,8 @@ interface Float64Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (this: undefined, value: number, index: number, array: Float64Array) => void): void;
forEach(callbackfn: (this: undefined, value: number, index: number, array: Float64Array) => void, thisArg: undefined): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Float64Array) => void): void;
forEach(callbackfn: (this: void, value: number, index: number, array: Float64Array) => void, thisArg: undefined): void;
forEach<Z>(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => void, thisArg: Z): void;
/**
@@ -4016,8 +4016,8 @@ interface Float64Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (this: undefined, value: number, index: number, array: Float64Array) => number): Float64Array;
map(callbackfn: (this: undefined, value: number, index: number, array: Float64Array) => number, thisArg: undefined): Float64Array;
map(callbackfn: (this: void, value: number, index: number, array: Float64Array) => number): Float64Array;
map(callbackfn: (this: void, value: number, index: number, array: Float64Array) => number, thisArg: undefined): Float64Array;
map<Z>(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => number, thisArg: Z): Float64Array;
/**
@@ -4102,8 +4102,8 @@ interface Float64Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(callbackfn: (this: undefined, value: number, index: number, array: Float64Array) => boolean): boolean;
some(callbackfn: (this: undefined, value: number, index: number, array: Float64Array) => boolean, thisArg: undefined): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Float64Array) => boolean): boolean;
some(callbackfn: (this: void, value: number, index: number, array: Float64Array) => boolean, thisArg: undefined): boolean;
some<Z>(callbackfn: (this: Z, value: number, index: number, array: Float64Array) => boolean, thisArg: Z): boolean;
/**
@@ -4157,8 +4157,8 @@ interface Float64ArrayConstructor {
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number): Float64Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: undefined, v: number, k: number) => number, thisArg: undefined): Float64Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number): Float64Array;
from(arrayLike: ArrayLike<number>, mapfn: (this: void, v: number, k: number) => number, thisArg: undefined): Float64Array;
from<Z>(arrayLike: ArrayLike<number>, mapfn: (this: Z, v: number, k: number) => number, thisArg: Z): Float64Array;
from(arrayLike: ArrayLike<number>): Float64Array;
+3 -3
View File
@@ -99,9 +99,9 @@ interface TextStreamReader extends TextStreamBase {
declare var WScript: {
/**
* Outputs text to either a message box (under WScript.exe) or the command console window followed by
* a newline (under CScript.exe).
*/
* Outputs text to either a message box (under WScript.exe) or the command console window followed by
* a newline (under CScript.exe).
*/
Echo(s: any): void;
/**
+127 -34
View File
@@ -54,13 +54,17 @@ interface MessageEventInit extends EventInit {
}
interface NotificationOptions {
dir?: string;
dir?: NotificationDirection;
lang?: string;
body?: string;
tag?: string;
icon?: string;
}
interface ObjectURLOptions {
oneTimeOnly?: boolean;
}
interface PushSubscriptionOptionsInit {
userVisibleOnly?: boolean;
applicationServerKey?: any;
@@ -71,11 +75,11 @@ interface RequestInit {
headers?: any;
body?: any;
referrer?: string;
referrerPolicy?: string;
mode?: string;
credentials?: string;
cache?: string;
redirect?: string;
referrerPolicy?: ReferrerPolicy;
mode?: RequestMode;
credentials?: RequestCredentials;
cache?: RequestCache;
redirect?: RequestRedirect;
integrity?: string;
keepalive?: boolean;
window?: any;
@@ -89,7 +93,7 @@ interface ResponseInit {
interface ClientQueryOptions {
includeUncontrolled?: boolean;
type?: string;
type?: ClientType;
}
interface ExtendableEventInit extends EventInit {
@@ -399,9 +403,9 @@ declare var Event: {
}
interface EventTarget {
addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
addEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
dispatchEvent(evt: Event): boolean;
removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
}
declare var EventTarget: {
@@ -461,7 +465,7 @@ declare var Headers: {
}
interface IDBCursor {
readonly direction: string;
readonly direction: IDBCursorDirection;
key: IDBKeyRange | IDBValidKey;
readonly primaryKey: any;
source: IDBObjectStore | IDBIndex;
@@ -613,7 +617,7 @@ interface IDBRequest extends EventTarget {
readonly error: DOMError;
onerror: (this: IDBRequest, ev: Event) => any;
onsuccess: (this: IDBRequest, ev: Event) => any;
readonly readyState: string;
readonly readyState: IDBRequestReadyState;
readonly result: any;
source: IDBObjectStore | IDBIndex | IDBCursor;
readonly transaction: IDBTransaction;
@@ -635,7 +639,7 @@ interface IDBTransactionEventMap {
interface IDBTransaction extends EventTarget {
readonly db: IDBDatabase;
readonly error: DOMError;
readonly mode: string;
readonly mode: IDBTransactionMode;
onabort: (this: IDBTransaction, ev: Event) => any;
oncomplete: (this: IDBTransaction, ev: Event) => any;
onerror: (this: IDBTransaction, ev: Event) => any;
@@ -728,14 +732,14 @@ interface NotificationEventMap {
interface Notification extends EventTarget {
readonly body: string;
readonly dir: string;
readonly dir: NotificationDirection;
readonly icon: string;
readonly lang: string;
onclick: (this: Notification, ev: Event) => any;
onclose: (this: Notification, ev: Event) => any;
onerror: (this: Notification, ev: Event) => any;
onshow: (this: Notification, ev: Event) => any;
readonly permission: string;
readonly permission: NotificationPermission;
readonly tag: string;
readonly title: string;
close(): void;
@@ -746,7 +750,7 @@ interface Notification extends EventTarget {
declare var Notification: {
prototype: Notification;
new(title: string, options?: NotificationOptions): Notification;
requestPermission(callback?: NotificationPermissionCallback): Promise<string>;
requestPermission(callback?: NotificationPermissionCallback): Promise<NotificationPermission>;
}
interface Performance {
@@ -863,7 +867,7 @@ declare var ProgressEvent: {
interface PushManager {
getSubscription(): Promise<PushSubscription>;
permissionState(options?: PushSubscriptionOptionsInit): Promise<string>;
permissionState(options?: PushSubscriptionOptionsInit): Promise<PushPermissionState>;
subscribe(options?: PushSubscriptionOptionsInit): Promise<PushSubscription>;
}
@@ -875,7 +879,7 @@ declare var PushManager: {
interface PushSubscription {
readonly endpoint: USVString;
readonly options: PushSubscriptionOptions;
getKey(name: string): ArrayBuffer | null;
getKey(name: PushEncryptionKeyName): ArrayBuffer | null;
toJSON(): any;
unsubscribe(): Promise<boolean>;
}
@@ -918,18 +922,18 @@ declare var ReadableStreamReader: {
}
interface Request extends Object, Body {
readonly cache: string;
readonly credentials: string;
readonly destination: string;
readonly cache: RequestCache;
readonly credentials: RequestCredentials;
readonly destination: RequestDestination;
readonly headers: Headers;
readonly integrity: string;
readonly keepalive: boolean;
readonly method: string;
readonly mode: string;
readonly redirect: string;
readonly mode: RequestMode;
readonly redirect: RequestRedirect;
readonly referrer: string;
readonly referrerPolicy: string;
readonly type: string;
readonly referrerPolicy: ReferrerPolicy;
readonly type: RequestType;
readonly url: string;
clone(): Request;
}
@@ -945,7 +949,7 @@ interface Response extends Object, Body {
readonly ok: boolean;
readonly status: number;
readonly statusText: string;
readonly type: string;
readonly type: ResponseType;
readonly url: string;
clone(): Response;
}
@@ -962,7 +966,7 @@ interface ServiceWorkerEventMap extends AbstractWorkerEventMap {
interface ServiceWorker extends EventTarget, AbstractWorker {
onstatechange: (this: ServiceWorker, ev: Event) => any;
readonly scriptURL: USVString;
readonly state: string;
readonly state: ServiceWorkerState;
postMessage(message: any, transfer?: any[]): void;
addEventListener<K extends keyof ServiceWorkerEventMap>(type: K, listener: (this: ServiceWorker, ev: ServiceWorkerEventMap[K]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@@ -1008,6 +1012,29 @@ declare var SyncManager: {
new(): SyncManager;
}
interface URL {
hash: string;
host: string;
hostname: string;
href: string;
readonly origin: string;
password: string;
pathname: string;
port: string;
protocol: string;
search: string;
username: string;
readonly searchParams: URLSearchParams;
toString(): string;
}
declare var URL: {
prototype: URL;
new(url: string, base?: string): URL;
createObjectURL(object: any, options?: ObjectURLOptions): string;
revokeObjectURL(url: string): void;
}
interface WebSocketEventMap {
"close": CloseEvent;
"error": Event;
@@ -1071,7 +1098,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly readyState: number;
readonly response: any;
readonly responseText: string;
responseType: string;
responseType: XMLHttpRequestResponseType;
readonly responseURL: string;
readonly responseXML: any;
readonly status: number;
@@ -1222,7 +1249,7 @@ interface XMLHttpRequestEventTarget {
}
interface Client {
readonly frameType: string;
readonly frameType: FrameType;
readonly id: string;
readonly url: USVString;
postMessage(message: any, transfer?: any[]): void;
@@ -1385,7 +1412,7 @@ declare var SyncEvent: {
interface WindowClient extends Client {
readonly focused: boolean;
readonly visibilityState: string;
readonly visibilityState: VisibilityState;
focus(): Promise<WindowClient>;
navigate(url: USVString): Promise<WindowClient>;
}
@@ -1484,6 +1511,41 @@ interface ImageBitmap {
close(): void;
}
interface URLSearchParams {
/**
* Appends a specified key/value pair as a new search parameter.
*/
append(name: string, value: string): void;
/**
* Deletes the given search parameter, and its associated value, from the list of all search parameters.
*/
delete(name: string): void;
/**
* Returns the first value associated to the given search parameter.
*/
get(name: string): string | null;
/**
* Returns all the values association with a given search parameter.
*/
getAll(name: string): string[];
/**
* Returns a Boolean indicating if such a search parameter exists.
*/
has(name: string): boolean;
/**
* Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.
*/
set(name: string, value: string): void;
}
declare var URLSearchParams: {
prototype: URLSearchParams;
/**
* Constructor returning a URLSearchParams object.
*/
new (init?: string | URLSearchParams): URLSearchParams;
}
interface BlobPropertyBag {
type?: string;
endings?: string;
@@ -1678,6 +1740,15 @@ interface JsonWebKey {
k?: string;
}
interface EventListenerOptions {
capture?: boolean;
}
interface AddEventListenerOptions extends EventListenerOptions {
passive?: boolean;
once?: boolean;
}
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
@@ -1699,10 +1770,10 @@ interface FunctionStringCallback {
(data: string): void;
}
interface ForEachCallback {
(keyId: any, status: string): void;
(keyId: any, status: MediaKeyStatus): void;
}
interface NotificationPermissionCallback {
(permission: string): void;
(permission: NotificationPermission): void;
}
declare var onmessage: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any;
declare function close(): void;
@@ -1717,7 +1788,7 @@ declare function msWriteProfilerMark(profilerMarkName: string): void;
declare function createImageBitmap(image: ImageBitmap | ImageData | Blob, options?: ImageBitmapOptions): Promise<ImageBitmap>;
declare function createImageBitmap(image: ImageBitmap | ImageData | Blob, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise<ImageBitmap>;
declare function dispatchEvent(evt: Event): boolean;
declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
declare var indexedDB: IDBFactory;
declare var msIndexedDB: IDBFactory;
declare var navigator: WorkerNavigator;
@@ -1736,7 +1807,7 @@ declare function btoa(rawString: string): string;
declare var console: Console;
declare function fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
declare function dispatchEvent(evt: Event): boolean;
declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
declare function addEventListener<K extends keyof DedicatedWorkerGlobalScopeEventMap>(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
type AlgorithmIdentifier = string | Algorithm;
@@ -1745,4 +1816,26 @@ type IDBKeyPath = string;
type RequestInfo = Request | string;
type USVString = string;
type IDBValidKey = number | string | Date | IDBArrayKey;
type BufferSource = ArrayBuffer | ArrayBufferView;
type BufferSource = ArrayBuffer | ArrayBufferView;
type FormDataEntryValue = string | File;
type IDBCursorDirection = "next" | "nextunique" | "prev" | "prevunique";
type IDBRequestReadyState = "pending" | "done";
type IDBTransactionMode = "readonly" | "readwrite" | "versionchange";
type MediaKeyStatus = "usable" | "expired" | "output-downscaled" | "output-not-allowed" | "status-pending" | "internal-error";
type NotificationDirection = "auto" | "ltr" | "rtl";
type NotificationPermission = "default" | "denied" | "granted";
type PushEncryptionKeyName = "p256dh" | "auth";
type PushPermissionState = "granted" | "denied" | "prompt";
type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | "origin-only" | "origin-when-cross-origin" | "unsafe-url";
type RequestCache = "default" | "no-store" | "reload" | "no-cache" | "force-cache";
type RequestCredentials = "omit" | "same-origin" | "include";
type RequestDestination = "" | "document" | "sharedworker" | "subresource" | "unknown" | "worker";
type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors";
type RequestRedirect = "follow" | "error" | "manual";
type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | "track" | "video";
type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect";
type ServiceWorkerState = "installing" | "installed" | "activating" | "activated" | "redundant";
type VisibilityState = "hidden" | "visible" | "prerender" | "unloaded";
type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text";
type ClientType = "window" | "worker" | "sharedworker" | "all";
type FrameType = "auxiliary" | "top-level" | "nested" | "none";
+1 -1
View File
@@ -191,7 +191,7 @@ namespace ts.server {
const l = lf.scriptInfo.fileName;
const r = rf.scriptInfo.fileName;
return (l < r ? -1 : (l > r ? 1 : 0));
};
}
static addToReferenceList(array: ModuleBuilderFileInfo[], fileInfo: ModuleBuilderFileInfo) {
if (array.length === 0) {
+2 -1
View File
@@ -178,7 +178,8 @@ namespace ts.server {
kindModifiers: response.body.kindModifiers,
textSpan: ts.createTextSpanFromBounds(start, end),
displayParts: [{ kind: "text", text: response.body.displayString }],
documentation: [{ kind: "text", text: response.body.documentation }]
documentation: [{ kind: "text", text: response.body.documentation }],
tags: response.body.tags
};
}
+208 -33
View File
@@ -35,6 +35,10 @@ namespace ts.server {
(event: ProjectServiceEvent): void;
}
export interface SafeList {
[name: string]: { match: RegExp, exclude?: Array<Array<string | number>>, types?: string[] };
}
function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions: CommandLineOption[]): Map<Map<number>> {
const map: Map<Map<number>> = createMap<Map<number>>();
for (const option of commandLineOptions) {
@@ -57,6 +61,55 @@ namespace ts.server {
"smart": IndentStyle.Smart
});
/**
* How to understand this block:
* * The 'match' property is a regexp that matches a filename.
* * If 'match' is successful, then:
* * All files from 'exclude' are removed from the project. See below.
* * All 'types' are included in ATA
* * What the heck is 'exclude' ?
* * An array of an array of strings and numbers
* * Each array is:
* * An array of strings and numbers
* * The strings are literals
* * The numbers refer to capture group indices from the 'match' regexp
* * Remember that '1' is the first group
* * These are concatenated together to form a new regexp
* * Filenames matching these regexps are excluded from the project
* This default value is tested in tsserverProjectSystem.ts; add tests there
* if you are changing this so that you can be sure your regexp works!
*/
const defaultTypeSafeList: SafeList = {
"jquery": {
// jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js")
"match": /jquery(-(\.?\d+)+)?(\.intellisense)?(\.min)?\.js$/i,
"types": ["jquery"]
},
"WinJS": {
// e.g. c:/temp/UWApp1/lib/winjs-4.0.1/js/base.js
"match": /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i, // If the winjs/base.js file is found..
"exclude": [["^", 1, "/.*"]], // ..then exclude all files under the winjs folder
"types": ["winjs"] // And fetch the @types package for WinJS
},
"Kendo": {
// e.g. /Kendo3/wwwroot/lib/kendo/kendo.all.min.js
"match": /^(.*\/kendo)\/kendo\.all\.min\.js$/i,
"exclude": [["^", 1, "/.*"]],
"types": ["kendo-ui"]
},
"Office Nuget": {
// e.g. /scripts/Office/1/excel-15.debug.js
"match": /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i, // Office NuGet package is installed under a "1/office" folder
"exclude": [["^", 1, "/.*"]], // Exclude that whole folder if the file indicated above is found in it
"types": ["office"] // @types package to fetch instead
},
"Minified files": {
// e.g. /whatever/blah.min.js
"match": /^(.+\.min\.js)$/i,
"exclude": [["^", 1, "$"]]
}
};
export function convertFormatOptions(protocolOptions: protocol.FormatCodeSettings): FormatCodeSettings {
if (typeof protocolOptions.indentStyle === "string") {
protocolOptions.indentStyle = indentStyle.get(protocolOptions.indentStyle.toLowerCase());
@@ -179,12 +232,12 @@ namespace ts.server {
class DirectoryWatchers {
/**
* a path to directory watcher map that detects added tsconfig files
**/
*/
private readonly directoryWatchersForTsconfig: Map<FileWatcher> = createMap<FileWatcher>();
/**
* count of how many projects are using the directory watcher.
* If the number becomes 0 for a watcher, then we should close it.
**/
*/
private readonly directoryWatchersRefCount: Map<number> = createMap<number>();
constructor(private readonly projectService: ProjectService) {
@@ -204,7 +257,7 @@ namespace ts.server {
startWatchingContainingDirectoriesForFile(fileName: string, project: InferredProject, callback: (fileName: string) => void) {
let currentPath = getDirectoryPath(fileName);
let parentPath = getDirectoryPath(currentPath);
while (currentPath != parentPath) {
while (currentPath !== parentPath) {
if (!this.directoryWatchersForTsconfig.has(currentPath)) {
this.projectService.logger.info(`Add watcher for: ${currentPath}`);
this.directoryWatchersForTsconfig.set(currentPath, this.projectService.host.watchDirectory(currentPath, callback));
@@ -220,6 +273,18 @@ namespace ts.server {
}
}
export interface ProjectServiceOptions {
host: ServerHost;
logger: Logger;
cancellationToken: HostCancellationToken;
useSingleInferredProject: boolean;
typingsInstaller: ITypingsInstaller;
eventHandler?: ProjectServiceEventHandler;
throttleWaitMilliseconds?: number;
globalPlugins?: string[];
pluginProbeLocations?: string[];
}
export class ProjectService {
public readonly typingsCache: TypingsCache;
@@ -241,11 +306,11 @@ namespace ts.server {
readonly externalProjects: ExternalProject[] = [];
/**
* projects built from openFileRoots
**/
*/
readonly inferredProjects: InferredProject[] = [];
/**
* projects specified by a tsconfig.json file
**/
*/
readonly configuredProjects: ConfiguredProject[] = [];
/**
* list of open files
@@ -259,6 +324,7 @@ namespace ts.server {
private readonly throttledOperations: ThrottledOperations;
private readonly hostConfiguration: HostConfiguration;
private static safelist: SafeList = defaultTypeSafeList;
private changedFiles: ScriptInfo[];
@@ -266,32 +332,45 @@ namespace ts.server {
public lastDeletedFile: ScriptInfo;
constructor(public readonly host: ServerHost,
public readonly logger: Logger,
public readonly cancellationToken: HostCancellationToken,
public readonly useSingleInferredProject: boolean,
readonly typingsInstaller: ITypingsInstaller = nullTypingsInstaller,
private readonly eventHandler?: ProjectServiceEventHandler) {
public readonly host: ServerHost;
public readonly logger: Logger;
public readonly cancellationToken: HostCancellationToken;
public readonly useSingleInferredProject: boolean;
public readonly typingsInstaller: ITypingsInstaller;
public readonly throttleWaitMilliseconds?: number;
private readonly eventHandler?: ProjectServiceEventHandler;
Debug.assert(!!host.createHash, "'ServerHost.createHash' is required for ProjectService");
public readonly globalPlugins: ReadonlyArray<string>;
public readonly pluginProbeLocations: ReadonlyArray<string>;
this.toCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
constructor(opts: ProjectServiceOptions) {
this.host = opts.host;
this.logger = opts.logger;
this.cancellationToken = opts.cancellationToken;
this.useSingleInferredProject = opts.useSingleInferredProject;
this.typingsInstaller = opts.typingsInstaller || nullTypingsInstaller;
this.throttleWaitMilliseconds = opts.throttleWaitMilliseconds;
this.eventHandler = opts.eventHandler;
this.globalPlugins = opts.globalPlugins || emptyArray;
this.pluginProbeLocations = opts.pluginProbeLocations || emptyArray;
Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService");
this.toCanonicalFileName = createGetCanonicalFileName(this.host.useCaseSensitiveFileNames);
this.directoryWatchers = new DirectoryWatchers(this);
this.throttledOperations = new ThrottledOperations(host);
this.throttledOperations = new ThrottledOperations(this.host);
this.typingsInstaller.attach(this);
this.typingsCache = new TypingsCache(this.typingsInstaller);
// ts.disableIncrementalParsing = true;
this.hostConfiguration = {
formatCodeOptions: getDefaultFormatCodeSettings(this.host),
hostInfo: "Unknown host",
extraFileExtensions: []
};
this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory());
this.documentRegistry = createDocumentRegistry(this.host.useCaseSensitiveFileNames, this.host.getCurrentDirectory());
}
/* @internal */
@@ -539,7 +618,7 @@ namespace ts.server {
*/
private onConfigFileAddedForInferredProject(fileName: string) {
// TODO: check directory separators
if (getBaseFileName(fileName) != "tsconfig.json") {
if (getBaseFileName(fileName) !== "tsconfig.json") {
this.logger.info(`${fileName} is not tsconfig.json`);
return;
}
@@ -613,18 +692,23 @@ namespace ts.server {
// when creation inferred project for some file has added other open files into this project (i.e. as referenced files)
// we definitely don't want to delete the project that was just created
for (const f of this.openFiles) {
if (f.containingProjects.length === 0) {
if (f.containingProjects.length === 0 || !inferredProject.containsScriptInfo(f)) {
// this is orphaned file that we have not processed yet - skip it
continue;
}
const defaultProject = f.getDefaultProject();
if (isRootFileInInferredProject(info) && defaultProject !== inferredProject && inferredProject.containsScriptInfo(f)) {
// open file used to be root in inferred project,
// this inferred project is different from the one we've just created for current file
// and new inferred project references this open file.
// We should delete old inferred project and attach open file to the new one
this.removeProject(defaultProject);
f.attachToProject(inferredProject);
for (const fContainingProject of f.containingProjects) {
if (fContainingProject.projectKind === ProjectKind.Inferred &&
fContainingProject.isRoot(f) &&
fContainingProject !== inferredProject) {
// open file used to be root in inferred project,
// this inferred project is different from the one we've just created for current file
// and new inferred project references this open file.
// We should delete old inferred project and attach open file to the new one
this.removeProject(fContainingProject);
f.attachToProject(inferredProject);
}
}
}
}
@@ -636,9 +720,9 @@ namespace ts.server {
}
/**
* Remove this file from the set of open, non-configured files.
* @param info The file that has been closed or newly configured
*/
* Remove this file from the set of open, non-configured files.
* @param info The file that has been closed or newly configured
*/
private closeOpenFile(info: ScriptInfo): void {
// Closing file should trigger re-reading the file content from disk. This is
// because the user may chose to discard the buffer content before saving
@@ -830,7 +914,7 @@ namespace ts.server {
getDirectoryPath(configFilename),
/*existingOptions*/ {},
configFilename,
/*resolutionStack*/ [],
/*resolutionStack*/[],
this.hostConfiguration.extraFileExtensions);
if (parsedCommandLine.errors.length) {
@@ -949,7 +1033,7 @@ namespace ts.server {
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
if (this.host.fileExists(rootFilename)) {
const info = this.getOrCreateScriptInfoForNormalizedPath(toNormalizedPath(rootFilename), /*openedByClient*/ clientFileName == rootFilename, /*fileContent*/ undefined, scriptKind, hasMixedContent);
const info = this.getOrCreateScriptInfoForNormalizedPath(toNormalizedPath(rootFilename), /*openedByClient*/ clientFileName === rootFilename, /*fileContent*/ undefined, scriptKind, hasMixedContent);
project.addRoot(info);
}
else {
@@ -1061,7 +1145,7 @@ namespace ts.server {
const { success, projectOptions, configFileErrors } = this.convertConfigFileContentToProjectOptions(project.getConfigFilePath());
if (!success) {
// reset project settings to default
this.updateNonInferredProject(project, [], fileNamePropertyReader, {}, {}, /*compileOnSave*/false, configFileErrors);
this.updateNonInferredProject(project, [], fileNamePropertyReader, {}, {}, /*compileOnSave*/ false, configFileErrors);
return configFileErrors;
}
@@ -1398,6 +1482,94 @@ namespace ts.server {
this.refreshInferredProjects();
}
/** Makes a filename safe to insert in a RegExp */
private static filenameEscapeRegexp = /[-\/\\^$*+?.()|[\]{}]/g;
private static escapeFilenameForRegex(filename: string) {
return filename.replace(this.filenameEscapeRegexp, "\\$&");
}
resetSafeList(): void {
ProjectService.safelist = defaultTypeSafeList;
}
loadSafeList(fileName: string): void {
const raw: SafeList = JSON.parse(this.host.readFile(fileName, "utf-8"));
// Parse the regexps
for (const k of Object.keys(raw)) {
raw[k].match = new RegExp(raw[k].match as {} as string, "i");
}
// raw is now fixed and ready
ProjectService.safelist = raw;
}
applySafeList(proj: protocol.ExternalProject): void {
const { rootFiles, typeAcquisition } = proj;
const types = (typeAcquisition && typeAcquisition.include) || [];
const excludeRules: string[] = [];
const normalizedNames = rootFiles.map(f => normalizeSlashes(f.fileName));
for (const name of Object.keys(ProjectService.safelist)) {
const rule = ProjectService.safelist[name];
for (const root of normalizedNames) {
if (rule.match.test(root)) {
this.logger.info(`Excluding files based on rule ${name}`);
// If the file matches, collect its types packages and exclude rules
if (rule.types) {
for (const type of rule.types) {
if (types.indexOf(type) < 0) {
types.push(type);
}
}
}
if (rule.exclude) {
for (const exclude of rule.exclude) {
const processedRule = root.replace(rule.match, (...groups: Array<string>) => {
return exclude.map(groupNumberOrString => {
// RegExp group numbers are 1-based, but the first element in groups
// is actually the original string, so it all works out in the end.
if (typeof groupNumberOrString === "number") {
if (typeof groups[groupNumberOrString] !== "string") {
// Specification was wrong - exclude nothing!
this.logger.info(`Incorrect RegExp specification in safelist rule ${name} - not enough groups`);
// * can't appear in a filename; escape it because it's feeding into a RegExp
return "\\*";
}
return ProjectService.escapeFilenameForRegex(groups[groupNumberOrString]);
}
return groupNumberOrString;
}).join("");
});
if (excludeRules.indexOf(processedRule) === -1) {
excludeRules.push(processedRule);
}
}
}
else {
// If not rules listed, add the default rule to exclude the matched file
const escaped = ProjectService.escapeFilenameForRegex(root);
if (excludeRules.indexOf(escaped) < 0) {
excludeRules.push(escaped);
}
}
}
}
// Copy back this field into the project if needed
if (types.length > 0) {
proj.typeAcquisition = proj.typeAcquisition || {};
proj.typeAcquisition.include = types;
}
}
const excludeRegexes = excludeRules.map(e => new RegExp(e, "i"));
proj.rootFiles = proj.rootFiles.filter((_file, index) => !excludeRegexes.some(re => re.test(normalizedNames[index])));
}
openExternalProject(proj: protocol.ExternalProject, suppressRefreshOfInferredProjects = false): void {
// typingOptions has been deprecated and is only supported for backward compatibility
// purposes. It should be removed in future releases - use typeAcquisition instead.
@@ -1405,6 +1577,9 @@ namespace ts.server {
const typeAcquisition = convertEnableAutoDiscoveryToEnable(proj.typingOptions);
proj.typeAcquisition = typeAcquisition;
}
this.applySafeList(proj);
let tsConfigFiles: NormalizedPath[];
const rootFiles: protocol.ExternalFile[] = [];
for (const file of proj.rootFiles) {
+1
View File
@@ -16,6 +16,7 @@ namespace ts.server {
readonly realpath?: (path: string) => string;
constructor(private readonly host: ServerHost, private readonly project: Project, private readonly cancellationToken: HostCancellationToken) {
this.cancellationToken = new ThrottledCancellationToken(cancellationToken, project.projectService.throttleWaitMilliseconds);
this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames);
if (host.trace) {
+36 -16
View File
@@ -643,7 +643,7 @@ namespace ts.server {
// check if requested version is the same that we have reported last time
if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) {
// if current structure version is the same - return info without any changes
if (this.projectStructureVersion == this.lastReportedVersion && !updatedFileNames) {
if (this.projectStructureVersion === this.lastReportedVersion && !updatedFileNames) {
return { info, projectErrors: this.projectErrors };
}
// compute and return the difference
@@ -843,7 +843,7 @@ namespace ts.server {
/** Used for configured projects which may have multiple open roots */
openRefCount = 0;
constructor(private configFileName: NormalizedPath,
constructor(configFileName: NormalizedPath,
projectService: ProjectService,
documentRegistry: ts.DocumentRegistry,
hasExplicitListOfFiles: boolean,
@@ -863,28 +863,48 @@ namespace ts.server {
enablePlugins() {
const host = this.projectService.host;
const options = this.getCompilerOptions();
const log = (message: string) => {
this.projectService.logger.info(message);
};
if (!(options.plugins && options.plugins.length)) {
this.projectService.logger.info("No plugins exist");
// No plugins
return;
}
if (!host.require) {
this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded");
return;
}
for (const pluginConfigEntry of options.plugins) {
const searchPath = getDirectoryPath(this.configFileName);
const resolvedModule = <PluginModuleFactory>Project.resolveModule(pluginConfigEntry.name, searchPath, host, log);
if (resolvedModule) {
this.enableProxy(resolvedModule, pluginConfigEntry);
// Search our peer node_modules, then any globally-specified probe paths
// ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/
const searchPaths = [combinePaths(host.getExecutingFilePath(), "../../.."), ...this.projectService.pluginProbeLocations];
// Enable tsconfig-specified plugins
if (options.plugins) {
for (const pluginConfigEntry of options.plugins) {
this.enablePlugin(pluginConfigEntry, searchPaths);
}
}
if (this.projectService.globalPlugins) {
// Enable global plugins with synthetic configuration entries
for (const globalPluginName of this.projectService.globalPlugins) {
// Skip already-locally-loaded plugins
if (options.plugins && options.plugins.some(p => p.name === globalPluginName)) continue;
// Provide global: true so plugins can detect why they can't find their config
this.enablePlugin({ name: globalPluginName, global: true } as PluginImport, searchPaths);
}
}
}
private enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]) {
const log = (message: string) => {
this.projectService.logger.info(message);
};
for (const searchPath of searchPaths) {
const resolvedModule = <PluginModuleFactory>Project.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log);
if (resolvedModule) {
this.enableProxy(resolvedModule, pluginConfigEntry);
return;
}
}
this.projectService.logger.info(`Couldn't find ${pluginConfigEntry.name} anywhere in paths: ${searchPaths.join(",")}`);
}
private enableProxy(pluginModuleFactory: PluginModuleFactory, configEntry: PluginImport) {
+480 -465
View File
File diff suppressed because it is too large Load Diff
+19 -3
View File
@@ -261,10 +261,26 @@ namespace ts.server {
}
getDefaultProject() {
if (this.containingProjects.length === 0) {
return Errors.ThrowNoProject();
switch (this.containingProjects.length) {
case 0:
return Errors.ThrowNoProject();
case 1:
return this.containingProjects[0];
default:
// if this file belongs to multiple projects, the first configured project should be
// the default project; if no configured projects, the first external project should
// be the default project; otherwise the first inferred project should be the default.
let firstExternalProject;
for (const project of this.containingProjects) {
if (project.projectKind === ProjectKind.Configured) {
return project;
}
else if (project.projectKind === ProjectKind.External && !firstExternalProject) {
firstExternalProject = project;
}
}
return firstExternalProject || this.containingProjects[0];
}
return this.containingProjects[0];
}
registerFileUpdate(): void {
+2 -2
View File
@@ -79,7 +79,7 @@ namespace ts.server {
const lm = LineIndex.linesFromText(insertedText);
const lines = lm.lines;
if (lines.length > 1) {
if (lines[lines.length - 1] == "") {
if (lines[lines.length - 1] === "") {
lines.length--;
}
}
@@ -570,7 +570,7 @@ namespace ts.server {
}
if (this.checkEdits) {
const updatedText = this.getText(0, this.root.charCount());
Debug.assert(checkText == updatedText, "buffer edit mismatch");
Debug.assert(checkText === updatedText, "buffer edit mismatch");
}
return walker.lineIndex;
}
+59 -37
View File
@@ -1,10 +1,22 @@
/// <reference types="node" />
/// <reference path="shared.ts" />
/// <reference path="session.ts" />
// used in fs.writeSync
/* tslint:disable:no-null-keyword */
namespace ts.server {
interface IOSessionOptions {
host: ServerHost;
cancellationToken: ServerCancellationToken;
canUseEvents: boolean;
installerEventPort: number;
useSingleInferredProject: boolean;
disableAutomaticTypingAcquisition: boolean;
globalTypingsCacheLocation: string;
logger: Logger;
typingSafeListLocation: string;
telemetryEnabled: boolean;
globalPlugins: string[];
pluginProbeLocations: string[];
}
const net: {
connect(options: { port: number }, onConnect?: () => void): NodeSocket
@@ -196,7 +208,8 @@ namespace ts.server {
}
if (this.fd >= 0) {
const buf = new Buffer(s);
fs.writeSync(this.fd, buf, 0, buf.length, null);
// tslint:disable-next-line no-null-keyword
fs.writeSync(this.fd, buf, 0, buf.length, /*position*/ null);
}
if (this.traceToConsole) {
console.warn(s);
@@ -219,6 +232,7 @@ namespace ts.server {
host: ServerHost,
eventPort: number,
readonly globalTypingsCacheLocation: string,
readonly typingSafeListLocation: string,
private newLine: string) {
this.throttledOperations = new ThrottledOperations(host);
if (eventPort) {
@@ -260,6 +274,9 @@ namespace ts.server {
if (this.logger.loggingEnabled() && this.logger.getLogFileName()) {
args.push(Arguments.LogFile, combinePaths(getDirectoryPath(normalizeSlashes(this.logger.getLogFileName())), `ti-${process.pid}.log`));
}
if (this.typingSafeListLocation) {
args.push(Arguments.TypingSafeListLocation, this.typingSafeListLocation);
}
const execArgv: string[] = [];
{
for (const arg of process.execArgv) {
@@ -363,40 +380,34 @@ namespace ts.server {
}
this.projectService.updateTypingsForProject(response);
if (response.kind == ActionSet && this.socket) {
if (response.kind === ActionSet && this.socket) {
this.sendEvent(0, "setTypings", response);
}
}
}
class IOSession extends Session {
constructor(
host: ServerHost,
cancellationToken: ServerCancellationToken,
installerEventPort: number,
canUseEvents: boolean,
useSingleInferredProject: boolean,
disableAutomaticTypingAcquisition: boolean,
globalTypingsCacheLocation: string,
telemetryEnabled: boolean,
logger: server.Logger) {
const typingsInstaller = disableAutomaticTypingAcquisition
? undefined
: new NodeTypingsInstaller(telemetryEnabled, logger, host, installerEventPort, globalTypingsCacheLocation, host.newLine);
constructor(options: IOSessionOptions) {
const { host, installerEventPort, globalTypingsCacheLocation, typingSafeListLocation, canUseEvents } = options;
const typingsInstaller = disableAutomaticTypingAcquisition
? undefined
: new NodeTypingsInstaller(telemetryEnabled, logger, host, installerEventPort, globalTypingsCacheLocation, typingSafeListLocation, host.newLine);
super(
host,
cancellationToken,
useSingleInferredProject,
typingsInstaller || nullTypingsInstaller,
Buffer.byteLength,
process.hrtime,
logger,
canUseEvents);
super({
host,
cancellationToken,
useSingleInferredProject,
typingsInstaller: typingsInstaller || nullTypingsInstaller,
byteLength: Buffer.byteLength,
hrtime: process.hrtime,
logger,
canUseEvents,
globalPlugins: options.globalPlugins,
pluginProbeLocations: options.pluginProbeLocations});
if (telemetryEnabled && typingsInstaller) {
typingsInstaller.setTelemetrySender(this);
}
if (telemetryEnabled && typingsInstaller) {
typingsInstaller.setTelemetrySender(this);
}
}
exit() {
@@ -697,7 +708,7 @@ namespace ts.server {
}
sys.require = (initialDir: string, moduleName: string): RequireResult => {
const result = nodeModuleNameResolverWorker(moduleName, initialDir + "/program.ts", { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, sys, undefined, /*jsOnly*/ true);
const result = nodeModuleNameResolverWorker(moduleName, initialDir + "/program.ts", { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, sys, /*cache*/ undefined, /*jsOnly*/ true);
try {
return { module: require(result.resolvedModule.resolvedFileName), error: undefined };
}
@@ -713,7 +724,7 @@ namespace ts.server {
}
catch (e) {
cancellationToken = nullCancellationToken;
};
}
let eventPort: number;
{
@@ -729,20 +740,31 @@ namespace ts.server {
validateLocaleAndSetLanguage(localeStr, sys);
}
const typingSafeListLocation = findArgument("--typingSafeListLocation");
const globalPlugins = (findArgument("--globalPlugins") || "").split(",");
const pluginProbeLocations = (findArgument("--pluginProbeLocations") || "").split(",");
const useSingleInferredProject = hasArgument("--useSingleInferredProject");
const disableAutomaticTypingAcquisition = hasArgument("--disableAutomaticTypingAcquisition");
const telemetryEnabled = hasArgument(Arguments.EnableTelemetry);
const ioSession = new IOSession(
sys,
const options: IOSessionOptions = {
host: sys,
cancellationToken,
eventPort,
/*canUseEvents*/ eventPort === undefined,
installerEventPort: eventPort,
canUseEvents: eventPort === undefined,
useSingleInferredProject,
disableAutomaticTypingAcquisition,
getGlobalTypingsCacheLocation(),
globalTypingsCacheLocation: getGlobalTypingsCacheLocation(),
typingSafeListLocation,
telemetryEnabled,
logger);
logger,
globalPlugins,
pluginProbeLocations
};
const ioSession = new IOSession(options);
process.on("uncaughtException", function (err: Error) {
ioSession.logError(err, "unknown");
});
+86 -38
View File
@@ -31,7 +31,8 @@ namespace ts.server {
}
else {
// For configured projects, require that skipLibCheck be set also
return project.getCompilerOptions().skipLibCheck && project.isJsOnlyProject();
const options = project.getCompilerOptions();
return options.skipLibCheck && !options.checkJs && project.isJsOnlyProject();
}
}
@@ -48,7 +49,7 @@ namespace ts.server {
if (a.file < b.file) {
return -1;
}
else if (a.file == b.file) {
else if (a.file === b.file) {
const n = compareNumber(a.start.line, b.start.line);
if (n === 0) {
return compareNumber(a.start.offset, b.start.offset);
@@ -218,7 +219,7 @@ namespace ts.server {
getCurrentRequestId(): number;
sendRequestCompletedEvent(requestId: number): void;
getServerHost(): ServerHost;
isCancellationRequested(): boolean;
isCancellationRequested(): boolean;
executeWithRequestId(requestId: number, action: () => void): void;
logError(error: Error, message: string): void;
}
@@ -299,7 +300,7 @@ namespace ts.server {
}
}
private setTimerHandle(timerHandle: any) {;
private setTimerHandle(timerHandle: any) {
if (this.timerHandle !== undefined) {
this.operationHost.getServerHost().clearTimeout(this.timerHandle);
}
@@ -318,6 +319,22 @@ namespace ts.server {
}
}
export interface SessionOptions {
host: ServerHost;
cancellationToken: ServerCancellationToken;
useSingleInferredProject: boolean;
typingsInstaller: ITypingsInstaller;
byteLength: (buf: string, encoding?: string) => number;
hrtime: (start?: number[]) => number[];
logger: Logger;
canUseEvents: boolean;
eventHandler?: ProjectServiceEventHandler;
throttleWaitMilliseconds?: number;
globalPlugins?: string[];
pluginProbeLocations?: string[];
}
export class Session implements EventSender {
private readonly gcTimer: GcTimer;
protected projectService: ProjectService;
@@ -326,21 +343,29 @@ namespace ts.server {
private currentRequestId: number;
private errorCheck: MultistepOperation;
private eventHander: ProjectServiceEventHandler;
private eventHandler: ProjectServiceEventHandler;
constructor(
private host: ServerHost,
private readonly cancellationToken: ServerCancellationToken,
useSingleInferredProject: boolean,
protected readonly typingsInstaller: ITypingsInstaller,
private byteLength: (buf: string, encoding?: string) => number,
private hrtime: (start?: number[]) => number[],
protected logger: Logger,
protected readonly canUseEvents: boolean,
eventHandler?: ProjectServiceEventHandler) {
private host: ServerHost;
private readonly cancellationToken: ServerCancellationToken;
protected readonly typingsInstaller: ITypingsInstaller;
private byteLength: (buf: string, encoding?: string) => number;
private hrtime: (start?: number[]) => number[];
protected logger: Logger;
private canUseEvents: boolean;
this.eventHander = canUseEvents
? eventHandler || (event => this.defaultEventHandler(event))
constructor(opts: SessionOptions) {
this.host = opts.host;
this.cancellationToken = opts.cancellationToken;
this.typingsInstaller = opts.typingsInstaller;
this.byteLength = opts.byteLength;
this.hrtime = opts.hrtime;
this.logger = opts.logger;
this.canUseEvents = opts.canUseEvents;
const { throttleWaitMilliseconds } = opts;
this.eventHandler = this.canUseEvents
? opts.eventHandler || (event => this.defaultEventHandler(event))
: undefined;
const multistepOperationHost: MultistepOperationHost = {
@@ -349,11 +374,22 @@ namespace ts.server {
getServerHost: () => this.host,
logError: (err, cmd) => this.logError(err, cmd),
sendRequestCompletedEvent: requestId => this.sendRequestCompletedEvent(requestId),
isCancellationRequested: () => cancellationToken.isCancellationRequested()
isCancellationRequested: () => this.cancellationToken.isCancellationRequested()
};
this.errorCheck = new MultistepOperation(multistepOperationHost);
this.projectService = new ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, this.eventHander);
this.gcTimer = new GcTimer(host, /*delay*/ 7000, logger);
const settings: ProjectServiceOptions = {
host: this.host,
logger: this.logger,
cancellationToken: this.cancellationToken,
useSingleInferredProject: opts.useSingleInferredProject,
typingsInstaller: this.typingsInstaller,
throttleWaitMilliseconds,
eventHandler: this.eventHandler,
globalPlugins: opts.globalPlugins,
pluginProbeLocations: opts.pluginProbeLocations
};
this.projectService = new ProjectService(settings);
this.gcTimer = new GcTimer(this.host, /*delay*/ 7000, this.logger);
}
private sendRequestCompletedEvent(requestId: number): void {
@@ -756,6 +792,17 @@ namespace ts.server {
return projects;
}
private getDefaultProject(args: protocol.FileRequestArgs) {
if (args.projectFileName) {
const project = this.getProject(args.projectFileName);
if (project) {
return project;
}
}
const info = this.projectService.getScriptInfo(args.file);
return info.getDefaultProject();
}
private getRenameLocations(args: protocol.RenameRequestArgs, simplifiedResult: boolean): protocol.RenameResponseBody | RenameLocation[] {
const file = toNormalizedPath(args.file);
const info = this.projectService.getScriptInfoForNormalizedPath(file);
@@ -763,7 +810,7 @@ namespace ts.server {
const projects = this.getProjects(args);
if (simplifiedResult) {
const defaultProject = projects[0];
const defaultProject = this.getDefaultProject(args);
// The rename info should be the same for every project
const renameInfo = defaultProject.getLanguageService().getRenameInfo(file, position);
if (!renameInfo) {
@@ -862,7 +909,7 @@ namespace ts.server {
const file = toNormalizedPath(args.file);
const projects = this.getProjects(args);
const defaultProject = projects[0];
const defaultProject = this.getDefaultProject(args);
const scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file);
const position = this.getPosition(args, scriptInfo);
if (simplifiedResult) {
@@ -913,9 +960,8 @@ namespace ts.server {
return combineProjectOutput(
projects,
project => project.getLanguageService().findReferences(file, position),
undefined,
// TODO: fixme
undefined
/*comparer*/ undefined,
/*areEqual (TODO: fixme)*/ undefined
);
}
@@ -935,8 +981,8 @@ namespace ts.server {
*/
private openClientFile(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind) {
const { configFileName, configFileErrors } = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind);
if (this.eventHander) {
this.eventHander({
if (this.eventHandler) {
this.eventHandler({
eventName: "configFileDiag",
data: { triggerFile: fileName, configFileName, diagnostics: configFileErrors || [] }
});
@@ -1018,6 +1064,7 @@ namespace ts.server {
if (simplifiedResult) {
const displayString = ts.displayPartsToString(quickInfo.displayParts);
const docString = ts.displayPartsToString(quickInfo.documentation);
return {
kind: quickInfo.kind,
kindModifiers: quickInfo.kindModifiers,
@@ -1025,6 +1072,7 @@ namespace ts.server {
end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)),
displayString: displayString,
documentation: docString,
tags: quickInfo.tags || []
};
}
else {
@@ -1080,7 +1128,7 @@ namespace ts.server {
// getFormattingEditsAfterKeystroke either empty or pertaining
// only to the previous line. If all this is true, then
// add edits necessary to properly indent the current line.
if ((args.key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) {
if ((args.key === "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) {
const lineInfo = scriptInfo.getLineInfo(args.line);
if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) {
const lineText = lineInfo.leaf.text;
@@ -1089,10 +1137,10 @@ namespace ts.server {
let hasIndent = 0;
let i: number, len: number;
for (i = 0, len = lineText.length; i < len; i++) {
if (lineText.charAt(i) == " ") {
if (lineText.charAt(i) === " ") {
hasIndent++;
}
else if (lineText.charAt(i) == "\t") {
else if (lineText.charAt(i) === "\t") {
hasIndent += formatOptions.tabSize;
}
else {
@@ -1495,7 +1543,7 @@ namespace ts.server {
const normalizedFileName = toNormalizedPath(fileName);
const project = this.projectService.getDefaultProjectForFile(normalizedFileName, /*refreshInferredProjects*/ true);
for (const fileNameInProject of fileNamesInProject) {
if (this.getCanonicalFileName(fileNameInProject) == this.getCanonicalFileName(fileName))
if (this.getCanonicalFileName(fileNameInProject) === this.getCanonicalFileName(fileName))
highPriorityFiles.push(fileNameInProject);
else {
const info = this.projectService.getScriptInfo(fileNameInProject);
@@ -1516,7 +1564,7 @@ namespace ts.server {
const checkList = fileNamesInProject.map(fileName => ({ fileName, project }));
// Project level error analysis runs on background files too, therefore
// doesn't require the file to be opened
this.updateErrorCheck(next, checkList, this.changeSeq, (n) => n == this.changeSeq, delay, 200, /*requireOpen*/ false);
this.updateErrorCheck(next, checkList, this.changeSeq, (n) => n === this.changeSeq, delay, 200, /*requireOpen*/ false);
}
}
@@ -1540,17 +1588,17 @@ namespace ts.server {
[CommandNames.OpenExternalProject]: (request: protocol.OpenExternalProjectRequest) => {
this.projectService.openExternalProject(request.arguments, /*suppressRefreshOfInferredProjects*/ false);
// TODO: report errors
return this.requiredResponse(true);
return this.requiredResponse(/*response*/ true);
},
[CommandNames.OpenExternalProjects]: (request: protocol.OpenExternalProjectsRequest) => {
this.projectService.openExternalProjects(request.arguments.projects);
// TODO: report errors
return this.requiredResponse(true);
return this.requiredResponse(/*response*/ true);
},
[CommandNames.CloseExternalProject]: (request: protocol.CloseExternalProjectRequest) => {
this.projectService.closeExternalProject(request.arguments.projectFileName);
// TODO: report errors
return this.requiredResponse(true);
return this.requiredResponse(/*response*/ true);
},
[CommandNames.SynchronizeProjectList]: (request: protocol.SynchronizeProjectListRequest) => {
const result = this.projectService.synchronizeProjectList(request.arguments.knownProjects);
@@ -1574,7 +1622,7 @@ namespace ts.server {
this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles);
this.changeSeq++;
// TODO: report errors
return this.requiredResponse(true);
return this.requiredResponse(/*response*/ true);
},
[CommandNames.Exit]: () => {
this.exit();
@@ -1685,7 +1733,7 @@ namespace ts.server {
},
[CommandNames.Cleanup]: () => {
this.cleanup();
return this.requiredResponse(true);
return this.requiredResponse(/*response*/ true);
},
[CommandNames.SemanticDiagnosticsSync]: (request: protocol.SemanticDiagnosticsSyncRequest) => {
return this.requiredResponse(this.getSemanticDiagnosticsSync(request.arguments));
@@ -1759,7 +1807,7 @@ namespace ts.server {
},
[CommandNames.CompilerOptionsForInferredProjects]: (request: protocol.SetCompilerOptionsForInferredProjectsRequest) => {
this.setCompilerOptionsForInferredProjects(request.arguments);
return this.requiredResponse(true);
return this.requiredResponse(/*response*/ true);
},
[CommandNames.ProjectInfo]: (request: protocol.ProjectInfoRequest) => {
return this.requiredResponse(this.getProjectInfo(request.arguments));
+1
View File
@@ -11,6 +11,7 @@ namespace ts.server {
export const GlobalCacheLocation = "--globalTypingsCacheLocation";
export const LogFile = "--logFile";
export const EnableTelemetry = "--enableTelemetry";
export const TypingSafeListLocation = "--typingSafeListLocation";
}
export function hasArgument(argumentName: string) {
+1 -1
View File
@@ -61,7 +61,7 @@ namespace ts.server {
function compilerOptionsChanged(opt1: CompilerOptions, opt2: CompilerOptions): boolean {
// TODO: add more relevant properties
return opt1.allowJs != opt2.allowJs;
return opt1.allowJs !== opt2.allowJs;
}
function unresolvedImportsChanged(imports1: SortedReadonlyArray<string>, imports2: SortedReadonlyArray<string>): boolean {
@@ -31,7 +31,7 @@ namespace ts.server.typingsInstaller {
}
function getNPMLocation(processName: string) {
if (path.basename(processName).indexOf("node") == 0) {
if (path.basename(processName).indexOf("node") === 0) {
return `"${path.join(path.dirname(process.argv[0]), "npm")}"`;
}
else {
@@ -76,11 +76,11 @@ namespace ts.server.typingsInstaller {
private delayedInitializationError: InitializationFailedResponse;
constructor(globalTypingsCacheLocation: string, throttleLimit: number, log: Log) {
constructor(globalTypingsCacheLocation: string, typingSafeListLocation: string, throttleLimit: number, log: Log) {
super(
sys,
globalTypingsCacheLocation,
toPath("typingSafeList.json", __dirname, createGetCanonicalFileName(sys.useCaseSensitiveFileNames)),
typingSafeListLocation ? toPath(typingSafeListLocation, "", createGetCanonicalFileName(sys.useCaseSensitiveFileNames)) : toPath("typingSafeList.json", __dirname, createGetCanonicalFileName(sys.useCaseSensitiveFileNames)),
throttleLimit,
log);
if (this.log.isEnabled()) {
@@ -164,6 +164,7 @@ namespace ts.server.typingsInstaller {
const logFilePath = findArgument(server.Arguments.LogFile);
const globalTypingsCacheLocation = findArgument(server.Arguments.GlobalCacheLocation);
const typingSafeListLocation = findArgument(server.Arguments.TypingSafeListLocation);
const log = new FileLog(logFilePath);
if (log.isEnabled()) {
@@ -177,6 +178,6 @@ namespace ts.server.typingsInstaller {
}
process.exit(0);
});
const installer = new NodeTypingsInstaller(globalTypingsCacheLocation, /*throttleLimit*/5, log);
const installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, /*throttleLimit*/5, log);
installer.listen();
}
+3 -3
View File
@@ -166,11 +166,11 @@ namespace ts.server {
export interface ProjectOptions {
/**
* true if config file explicitly listed files
**/
*/
configHasFilesProperty?: boolean;
/**
* these fields can be present in the project file
**/
*/
files?: string[];
wildcardDirectories?: Map<WatchDirectoryFlags>;
compilerOptions?: CompilerOptions;
@@ -219,7 +219,7 @@ namespace ts.server {
}
public scheduleCollect() {
if (!this.host.gc || this.timerId != undefined) {
if (!this.host.gc || this.timerId !== undefined) {
// no global.gc or collection was already scheduled - skip this request
return;
}
+6 -3
View File
@@ -97,7 +97,7 @@ namespace ts.BreakpointResolver {
if (isFunctionBlock(node)) {
return spanInFunctionBlock(<Block>node);
}
// Fall through
// falls through
case SyntaxKind.ModuleBlock:
return spanInBlock(<Block>node);
@@ -186,6 +186,7 @@ namespace ts.BreakpointResolver {
if (getModuleInstanceState(node) !== ModuleInstanceState.Instantiated) {
return undefined;
}
// falls through
case SyntaxKind.ClassDeclaration:
case SyntaxKind.EnumDeclaration:
@@ -264,7 +265,7 @@ namespace ts.BreakpointResolver {
// a or ...c or d: x from
// [a, b, ...c] or { a, b } or { d: x } from destructuring pattern
if ((node.kind === SyntaxKind.Identifier ||
node.kind == SyntaxKind.SpreadElement ||
node.kind === SyntaxKind.SpreadElement ||
node.kind === SyntaxKind.PropertyAssignment ||
node.kind === SyntaxKind.ShorthandPropertyAssignment) &&
isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
@@ -473,6 +474,7 @@ namespace ts.BreakpointResolver {
if (getModuleInstanceState(block.parent) !== ModuleInstanceState.Instantiated) {
return undefined;
}
// falls through
// Set on parent if on same line otherwise on first statement
case SyntaxKind.WhileStatement:
@@ -582,6 +584,7 @@ namespace ts.BreakpointResolver {
if (getModuleInstanceState(node.parent.parent) !== ModuleInstanceState.Instantiated) {
return undefined;
}
// falls through
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ClassDeclaration:
@@ -593,7 +596,7 @@ namespace ts.BreakpointResolver {
// Span on close brace token
return textSpan(node);
}
// fall through
// falls through
case SyntaxKind.CatchClause:
return spanInNode(lastOrUndefined((<Block>node.parent).statements));
+1 -1
View File
@@ -160,7 +160,7 @@ namespace ts {
case EndOfLineState.InTemplateMiddleOrTail:
text = "}\n" + text;
offset = 2;
// fallthrough
// falls through
case EndOfLineState.InTemplateSubstitutionPosition:
templateStack.push(SyntaxKind.TemplateHead);
break;
@@ -0,0 +1,70 @@
/* @internal */
namespace ts.codefix {
registerCodeFix({
errorCodes: getApplicableDiagnosticCodes(),
getCodeActions: getDisableJsDiagnosticsCodeActions
});
function getApplicableDiagnosticCodes(): number[] {
const allDiagnostcs = <MapLike<DiagnosticMessage>>Diagnostics;
return Object.keys(allDiagnostcs)
.filter(d => allDiagnostcs[d] && allDiagnostcs[d].category === DiagnosticCategory.Error)
.map(d => allDiagnostcs[d].code);
}
function getIgnoreCommentLocationForLocation(sourceFile: SourceFile, position: number, newLineCharacter: string) {
const { line } = getLineAndCharacterOfPosition(sourceFile, position);
const lineStartPosition = getStartPositionOfLine(line, sourceFile);
const startPosition = getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition);
// First try to see if we can put the '// @ts-ignore' on the previous line.
// We need to make sure that we are not in the middle of a string literal or a comment.
// We also want to check if the previous line holds a comment for a node on the next line
// if so, we do not want to separate the node from its comment if we can.
if (!isInComment(sourceFile, startPosition) && !isInString(sourceFile, startPosition) && !isInTemplateString(sourceFile, startPosition)) {
const token = getTouchingToken(sourceFile, startPosition);
const tokenLeadingCommnets = getLeadingCommentRangesOfNode(token, sourceFile);
if (!tokenLeadingCommnets || !tokenLeadingCommnets.length || tokenLeadingCommnets[0].pos >= startPosition) {
return {
span: { start: startPosition, length: 0 },
newText: `// @ts-ignore${newLineCharacter}`
};
}
}
// If all fails, add an extra new line immediatlly before the error span.
return {
span: { start: position, length: 0 },
newText: `${position === startPosition ? "" : newLineCharacter}// @ts-ignore${newLineCharacter}`
};
}
function getDisableJsDiagnosticsCodeActions(context: CodeFixContext): CodeAction[] | undefined {
const { sourceFile, program, newLineCharacter, span } = context;
if (!isInJavaScriptFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) {
return undefined;
}
return [{
description: getLocaleSpecificMessage(Diagnostics.Ignore_this_error_message),
changes: [{
fileName: sourceFile.fileName,
textChanges: [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)]
}]
},
{
description: getLocaleSpecificMessage(Diagnostics.Disable_checking_for_this_file),
changes: [{
fileName: sourceFile.fileName,
textChanges: [{
span: {
start: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.pos : 0,
length: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.end - sourceFile.checkJsDirective.pos : 0
},
newText: `// @ts-nocheck${newLineCharacter}`
}]
}]
}];
}
}
+99 -46
View File
@@ -14,72 +14,125 @@ namespace ts.codefix {
// ^^^^^^^
const token = getTokenAtPosition(sourceFile, start);
if (token.kind != SyntaxKind.Identifier) {
if (token.kind !== SyntaxKind.Identifier) {
return undefined;
}
const classDeclaration = getContainingClass(token);
if (!classDeclaration) {
if (!isPropertyAccessExpression(token.parent) || token.parent.expression.kind !== SyntaxKind.ThisKeyword) {
return undefined;
}
if (!(token.parent && token.parent.kind === SyntaxKind.PropertyAccessExpression)) {
const classMemberDeclaration = getThisContainer(token, /*includeArrowFunctions*/ false);
if (!isClassElement(classMemberDeclaration)) {
return undefined;
}
if ((token.parent as PropertyAccessExpression).expression.kind !== SyntaxKind.ThisKeyword) {
const classDeclaration = <ClassLikeDeclaration>classMemberDeclaration.parent;
if (!classDeclaration || !isClassLike(classDeclaration)) {
return undefined;
}
let typeNode: TypeNode;
const isStatic = hasModifier(classMemberDeclaration, ModifierFlags.Static);
if (token.parent.parent.kind === SyntaxKind.BinaryExpression) {
const binaryExpression = token.parent.parent as BinaryExpression;
return isInJavaScriptFile(sourceFile) ? getActionsForAddMissingMemberInJavaScriptFile() : getActionsForAddMissingMemberInTypeScriptFile();
const checker = context.program.getTypeChecker();
const widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(binaryExpression.right)));
typeNode = checker.typeToTypeNode(widenedType, classDeclaration) || typeNode;
function getActionsForAddMissingMemberInJavaScriptFile(): CodeAction[] | undefined {
const memberName = token.getText();
if (isStatic) {
if (classDeclaration.kind === SyntaxKind.ClassExpression) {
return undefined;
}
const className = classDeclaration.name.getText();
return [{
description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Initialize_static_property_0), [memberName]),
changes: [{
fileName: sourceFile.fileName,
textChanges: [{
span: { start: classDeclaration.getEnd(), length: 0 },
newText: `${context.newLineCharacter}${className}.${memberName} = undefined;${context.newLineCharacter}`
}]
}]
}];
}
else {
const classConstructor = getFirstConstructorWithBody(classDeclaration);
if (!classConstructor) {
return undefined;
}
return [{
description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Initialize_property_0_in_the_constructor), [memberName]),
changes: [{
fileName: sourceFile.fileName,
textChanges: [{
span: { start: classConstructor.body.getEnd() - 1, length: 0 },
newText: `this.${memberName} = undefined;${context.newLineCharacter}`
}]
}]
}];
}
}
typeNode = typeNode ? typeNode : createKeywordTypeNode(SyntaxKind.AnyKeyword);
function getActionsForAddMissingMemberInTypeScriptFile(): CodeAction[] | undefined {
let typeNode: TypeNode;
const openBrace = getOpenBraceOfClassLike(classDeclaration, sourceFile);
if (token.parent.parent.kind === SyntaxKind.BinaryExpression) {
const binaryExpression = token.parent.parent as BinaryExpression;
const property = createProperty(
/*decorators*/undefined,
/*modifiers*/ undefined,
token.getText(sourceFile),
/*questionToken*/ undefined,
typeNode,
/*initializer*/ undefined);
const propertyChangeTracker = textChanges.ChangeTracker.fromCodeFixContext(context);
propertyChangeTracker.insertNodeAfter(sourceFile, openBrace, property, { suffix: context.newLineCharacter });
const checker = context.program.getTypeChecker();
const widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(binaryExpression.right)));
typeNode = checker.typeToTypeNode(widenedType, classDeclaration);
}
const stringTypeNode = createKeywordTypeNode(SyntaxKind.StringKeyword);
const indexingParameter = createParameter(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*dotDotDotToken*/ undefined,
"x",
/*questionToken*/ undefined,
stringTypeNode,
/*initializer*/ undefined);
const indexSignature = createIndexSignatureDeclaration(
/*decorators*/undefined,
/*modifiers*/ undefined,
[indexingParameter],
typeNode);
typeNode = typeNode || createKeywordTypeNode(SyntaxKind.AnyKeyword);
const indexSignatureChangeTracker = textChanges.ChangeTracker.fromCodeFixContext(context);
indexSignatureChangeTracker.insertNodeAfter(sourceFile, openBrace, indexSignature, { suffix: context.newLineCharacter });
const openBrace = getOpenBraceOfClassLike(classDeclaration, sourceFile);
return [{
description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Add_declaration_for_missing_property_0), [token.getText()]),
changes: propertyChangeTracker.getChanges()
},
{
description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Add_index_signature_for_missing_property_0), [token.getText()]),
changes: indexSignatureChangeTracker.getChanges()
}];
const property = createProperty(
/*decorators*/undefined,
/*modifiers*/ isStatic ? [createToken(SyntaxKind.StaticKeyword)] : undefined,
token.getText(sourceFile),
/*questionToken*/ undefined,
typeNode,
/*initializer*/ undefined);
const propertyChangeTracker = textChanges.ChangeTracker.fromCodeFixContext(context);
propertyChangeTracker.insertNodeAfter(sourceFile, openBrace, property, { suffix: context.newLineCharacter });
const actions = [{
description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Add_declaration_for_missing_property_0), [token.getText()]),
changes: propertyChangeTracker.getChanges()
}];
if (!isStatic) {
const stringTypeNode = createKeywordTypeNode(SyntaxKind.StringKeyword);
const indexingParameter = createParameter(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*dotDotDotToken*/ undefined,
"x",
/*questionToken*/ undefined,
stringTypeNode,
/*initializer*/ undefined);
const indexSignature = createIndexSignatureDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
[indexingParameter],
typeNode);
const indexSignatureChangeTracker = textChanges.ChangeTracker.fromCodeFixContext(context);
indexSignatureChangeTracker.insertNodeAfter(sourceFile, openBrace, indexSignature, { suffix: context.newLineCharacter });
actions.push({
description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Add_index_signature_for_missing_property_0), [token.getText()]),
changes: indexSignatureChangeTracker.getChanges()
});
}
return actions;
}
}
}
@@ -18,7 +18,7 @@ namespace ts.codefix {
// figure out if the `this` access is actually inside the supercall
// i.e. super(this.a), since in that case we won't suggest a fix
if (superCall.expression && superCall.expression.kind == SyntaxKind.CallExpression) {
if (superCall.expression && superCall.expression.kind === SyntaxKind.CallExpression) {
const arguments = (<CallExpression>superCall.expression).arguments;
for (let i = 0; i < arguments.length; i++) {
if ((<PropertyAccessExpression>arguments[i]).expression === token) {
+1
View File
@@ -7,4 +7,5 @@
/// <reference path="fixForgottenThisPropertyAccess.ts" />
/// <reference path='unusedIdentifierFixes.ts' />
/// <reference path='importFixes.ts' />
/// <reference path='disableJsDiagnostics.ts' />
/// <reference path='helpers.ts' />
+4 -4
View File
@@ -146,7 +146,7 @@ namespace ts.codefix {
/** This is *a* signature with the maximal number of arguments,
* such that if there is a "maximal" signature without rest arguments,
* this is one of them.
*/
*/
let maxArgsSignature = signatures[0];
let minArgumentCount = signatures[0].minArgumentCount;
let someSigHasRestParameter = false;
@@ -194,7 +194,7 @@ namespace ts.codefix {
modifiers,
name,
optional,
/*typeParameters*/undefined,
/*typeParameters*/ undefined,
parameters,
/*returnType*/ undefined);
}
@@ -217,9 +217,9 @@ namespace ts.codefix {
[createThrow(
createNew(
createIdentifier("Error"),
/*typeArguments*/undefined,
/*typeArguments*/ undefined,
[createLiteral("Method not implemented.")]))],
/*multiline*/true);
/*multiline*/ true);
}
function createVisibilityModifier(flags: ModifierFlags) {
+4 -3
View File
@@ -42,12 +42,13 @@ namespace ts.codefix {
switch (this.compareModuleSpecifiers(existingAction.moduleSpecifier, newAction.moduleSpecifier)) {
case ModuleSpecifierComparison.Better:
// the new one is not worth considering if it is a new improt.
// the new one is not worth considering if it is a new import.
// However if it is instead a insertion into existing import, the user might want to use
// the module specifier even it is worse by our standards. So keep it.
if (newAction.kind === "NewImport") {
return;
}
// falls through
case ModuleSpecifierComparison.Equal:
// the current one is safe. But it is still possible that the new one is worse
// than another existing one. For example, you may have new imports from "./foo/bar"
@@ -542,12 +543,12 @@ namespace ts.codefix {
}
function getRelativePathIfInDirectory(path: string, directoryPath: string) {
const relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false);
const relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
return isRootedDiskPath(relativePath) || startsWith(relativePath, "..") ? undefined : relativePath;
}
function getRelativePath(path: string, directoryPath: string) {
const relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false);
const relativePath = getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
return moduleHasNonRelativeName(relativePath) ? "./" + relativePath : relativePath;
}
}
@@ -58,6 +58,8 @@ namespace ts.codefix {
return deleteNodeInList(token.parent);
}
}
// TODO: #14885
// falls through
case SyntaxKind.TypeParameter:
const typeParameters = (<DeclarationWithTypeParameters>token.parent.parent).typeParameters;
@@ -116,7 +118,7 @@ namespace ts.codefix {
const nextToken = getTokenAtPosition(sourceFile, importClause.name.end);
if (nextToken && nextToken.kind === SyntaxKind.CommaToken) {
// shift first non-whitespace position after comma to the start position of the node
return deleteRange({ pos: start, end: skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/true) });
return deleteRange({ pos: start, end: skipTrivia(sourceFile.text, nextToken.end, /*stopAfterLineBreaks*/ false, /*stopAtComments*/ true) });
}
else {
return deleteNode(importClause.name);
@@ -125,7 +127,7 @@ namespace ts.codefix {
case SyntaxKind.NamespaceImport:
const namespaceImport = <NamespaceImport>token.parent;
if (namespaceImport.name == token && !(<ImportClause>namespaceImport.parent).name) {
if (namespaceImport.name === token && !(<ImportClause>namespaceImport.parent).name) {
const importDecl = getAncestor(namespaceImport, SyntaxKind.ImportDeclaration);
return deleteNode(importDecl);
}
+10 -8
View File
@@ -173,7 +173,7 @@ namespace ts.Completions {
// a['/*completion position*/']
return getStringLiteralCompletionEntriesFromElementAccess(node.parent, typeChecker, compilerOptions.target, log);
}
else if (node.parent.kind === SyntaxKind.ImportDeclaration || isExpressionOfExternalModuleImportEqualsDeclaration(node) || isRequireCall(node.parent, false)) {
else if (node.parent.kind === SyntaxKind.ImportDeclaration || isExpressionOfExternalModuleImportEqualsDeclaration(node) || isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) {
// Get all known external module names or complete a path to a module
// i.e. import * as ns from "/*completion position*/";
// import x = require("/*completion position*/");
@@ -211,7 +211,7 @@ namespace ts.Completions {
const type = typeChecker.getContextualType((<ObjectLiteralExpression>element.parent));
const entries: CompletionEntry[] = [];
if (type) {
getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/false, typeChecker, target, log);
getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false, typeChecker, target, log);
if (entries.length) {
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries };
}
@@ -239,7 +239,7 @@ namespace ts.Completions {
const type = typeChecker.getTypeAtLocation(node.expression);
const entries: CompletionEntry[] = [];
if (type) {
getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/false, typeChecker, target, log);
getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false, typeChecker, target, log);
if (entries.length) {
return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries };
}
@@ -293,13 +293,14 @@ namespace ts.Completions {
const symbol = forEach(symbols, s => getCompletionEntryDisplayNameForSymbol(typeChecker, s, compilerOptions.target, /*performCharacterChecks*/ false, location) === entryName ? s : undefined);
if (symbol) {
const { displayParts, documentation, symbolKind } = SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, SemanticMeaning.All);
const { displayParts, documentation, symbolKind, tags } = SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, location, location, SemanticMeaning.All);
return {
name: entryName,
kindModifiers: SymbolDisplay.getSymbolModifiers(symbol),
kind: symbolKind,
displayParts,
documentation
documentation,
tags
};
}
}
@@ -312,7 +313,8 @@ namespace ts.Completions {
kind: ScriptElementKind.keyword,
kindModifiers: ScriptElementKindModifier.none,
displayParts: [displayPart(entryName, SymbolDisplayPartKind.keyword)],
documentation: undefined
documentation: undefined,
tags: undefined
};
}
@@ -485,7 +487,7 @@ namespace ts.Completions {
// It has a left-hand side, so we're not in an opening JSX tag.
break;
}
// fall through
// falls through
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.JsxElement:
@@ -1309,7 +1311,7 @@ namespace ts.Completions {
}
function isEqualityOperatorKind(kind: SyntaxKind) {
return kind == SyntaxKind.EqualsEqualsToken ||
return kind === SyntaxKind.EqualsEqualsToken ||
kind === SyntaxKind.ExclamationEqualsToken ||
kind === SyntaxKind.EqualsEqualsEqualsToken ||
kind === SyntaxKind.ExclamationEqualsEqualsToken;
+12 -24
View File
@@ -17,34 +17,22 @@ namespace ts.DocumentHighlights {
}
function getSemanticDocumentHighlights(node: Node, typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFilesToSearch: SourceFile[]): DocumentHighlights[] {
const context = new FindAllReferences.DefaultFindReferencesContext(typeChecker, cancellationToken);
const referencedSymbols = FindAllReferences.getReferencedSymbolsForNode(context, node, sourceFilesToSearch);
return referencedSymbols && convertReferencedSymbols(referencedSymbols);
const referenceEntries = FindAllReferences.getReferenceEntriesForNode(node, sourceFilesToSearch, typeChecker, cancellationToken);
return referenceEntries && convertReferencedSymbols(referenceEntries);
}
function convertReferencedSymbols(referencedSymbols: ReferencedSymbol[]): DocumentHighlights[] {
const fileNameToDocumentHighlights = createMap<DocumentHighlights>();
const result: DocumentHighlights[] = [];
for (const referencedSymbol of referencedSymbols) {
for (const referenceEntry of referencedSymbol.references) {
const fileName = referenceEntry.fileName;
let documentHighlights = fileNameToDocumentHighlights.get(fileName);
if (!documentHighlights) {
documentHighlights = { fileName, highlightSpans: [] };
fileNameToDocumentHighlights.set(fileName, documentHighlights);
result.push(documentHighlights);
}
documentHighlights.highlightSpans.push({
textSpan: referenceEntry.textSpan,
kind: referenceEntry.isWriteAccess ? HighlightSpanKind.writtenReference : HighlightSpanKind.reference,
isInString: referenceEntry.isInString
});
function convertReferencedSymbols(referenceEntries: FindAllReferences.Entry[]): DocumentHighlights[] {
const fileNameToDocumentHighlights = createMap<HighlightSpan[]>();
for (const entry of referenceEntries) {
const { fileName, span } = FindAllReferences.toHighlightSpan(entry);
let highlightSpans = fileNameToDocumentHighlights.get(fileName);
if (!highlightSpans) {
fileNameToDocumentHighlights.set(fileName, highlightSpans = []);
}
highlightSpans.push(span);
}
return result;
return arrayFrom(fileNameToDocumentHighlights.entries(), ([fileName, highlightSpans ]) => ({ fileName, highlightSpans }));
}
function getSyntacticDocumentHighlights(node: Node, sourceFile: SourceFile): DocumentHighlights[] {
@@ -245,7 +233,7 @@ namespace ts.DocumentHighlights {
if (statement.kind === SyntaxKind.ContinueStatement) {
continue;
}
// Fall through.
// falls through
case SyntaxKind.ForStatement:
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
+47 -47
View File
@@ -1,34 +1,34 @@
namespace ts {
/**
* The document registry represents a store of SourceFile objects that can be shared between
* multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST)
* of files in the context.
* SourceFile objects account for most of the memory usage by the language service. Sharing
* the same DocumentRegistry instance between different instances of LanguageService allow
* for more efficient memory utilization since all projects will share at least the library
* file (lib.d.ts).
*
* A more advanced use of the document registry is to serialize sourceFile objects to disk
* and re-hydrate them when needed.
*
* To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it
* to all subsequent createLanguageService calls.
*/
* The document registry represents a store of SourceFile objects that can be shared between
* multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST)
* of files in the context.
* SourceFile objects account for most of the memory usage by the language service. Sharing
* the same DocumentRegistry instance between different instances of LanguageService allow
* for more efficient memory utilization since all projects will share at least the library
* file (lib.d.ts).
*
* A more advanced use of the document registry is to serialize sourceFile objects to disk
* and re-hydrate them when needed.
*
* To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it
* to all subsequent createLanguageService calls.
*/
export interface DocumentRegistry {
/**
* Request a stored SourceFile with a given fileName and compilationSettings.
* The first call to acquire will call createLanguageServiceSourceFile to generate
* the SourceFile if was not found in the registry.
*
* @param fileName The name of the file requested
* @param compilationSettings Some compilation settings like target affects the
* shape of a the resulting SourceFile. This allows the DocumentRegistry to store
* multiple copies of the same file for different compilation settings.
* @parm scriptSnapshot Text of the file. Only used if the file was not found
* in the registry and a new one was created.
* @parm version Current version of the file. Only used if the file was not found
* in the registry and a new one was created.
*/
* Request a stored SourceFile with a given fileName and compilationSettings.
* The first call to acquire will call createLanguageServiceSourceFile to generate
* the SourceFile if was not found in the registry.
*
* @param fileName The name of the file requested
* @param compilationSettings Some compilation settings like target affects the
* shape of a the resulting SourceFile. This allows the DocumentRegistry to store
* multiple copies of the same file for different compilation settings.
* @parm scriptSnapshot Text of the file. Only used if the file was not found
* in the registry and a new one was created.
* @parm version Current version of the file. Only used if the file was not found
* in the registry and a new one was created.
*/
acquireDocument(
fileName: string,
compilationSettings: CompilerOptions,
@@ -46,17 +46,17 @@ namespace ts {
scriptKind?: ScriptKind): SourceFile;
/**
* Request an updated version of an already existing SourceFile with a given fileName
* and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile
* to get an updated SourceFile.
*
* @param fileName The name of the file requested
* @param compilationSettings Some compilation settings like target affects the
* shape of a the resulting SourceFile. This allows the DocumentRegistry to store
* multiple copies of the same file for different compilation settings.
* @param scriptSnapshot Text of the file.
* @param version Current version of the file.
*/
* Request an updated version of an already existing SourceFile with a given fileName
* and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile
* to get an updated SourceFile.
*
* @param fileName The name of the file requested
* @param compilationSettings Some compilation settings like target affects the
* shape of a the resulting SourceFile. This allows the DocumentRegistry to store
* multiple copies of the same file for different compilation settings.
* @param scriptSnapshot Text of the file.
* @param version Current version of the file.
*/
updateDocument(
fileName: string,
compilationSettings: CompilerOptions,
@@ -75,14 +75,14 @@ namespace ts {
getKeyForCompilationSettings(settings: CompilerOptions): DocumentRegistryBucketKey;
/**
* Informs the DocumentRegistry that a file is not needed any longer.
*
* Note: It is not allowed to call release on a SourceFile that was not acquired from
* this registry originally.
*
* @param fileName The name of the file to be released
* @param compilationSettings The compilation settings used to acquire the file
*/
* Informs the DocumentRegistry that a file is not needed any longer.
*
* Note: It is not allowed to call release on a SourceFile that was not acquired from
* this registry originally.
*
* @param fileName The name of the file to be released
* @param compilationSettings The compilation settings used to acquire the file
*/
releaseDocument(fileName: string, compilationSettings: CompilerOptions): void;
releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void;
@@ -214,7 +214,7 @@ namespace ts {
}
function releaseDocumentWithKey(path: Path, key: DocumentRegistryBucketKey): void {
const bucket = getBucketForCompilationSettings(key, /*createIfMissing*/false);
const bucket = getBucketForCompilationSettings(key, /*createIfMissing*/ false);
Debug.assert(bucket !== undefined);
const entry = bucket.get(path);

Some files were not shown because too many files have changed in this diff Show More