From bfe41e359e271d9c85943f1b50b94b8976155e74 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Sun, 23 Oct 2016 22:25:16 +0100 Subject: [PATCH 01/17] Started refactor breaking apart modules made noImplicitAny --- .gitignore | 4 +- index.js | 3 + package.json | 2 +- src/constants.ts | 3 + index.ts => src/index.ts | 209 ++++-------------- src/interfaces.ts | 150 +++++++++++++ resolver.ts => src/resolver.ts | 7 +- tsconfig.json => src/tsconfig.json | 9 +- {typings => src/typings}/arrify/arrify.d.ts | 0 {typings => src/typings}/colors/colors.d.ts | 0 .../typings}/loaderUtils/loaderUtils.d.ts | 0 {typings => src/typings}/node/node.d.ts | 0 .../typings}/objectAssign/objectAssign.d.ts | 0 src/utils.ts | 49 ++++ test/comparison-tests/node/app.ts | 2 +- .../node/expectedOutput-2.0/bundle.js | 2 +- .../expectedOutput-2.0/bundle.transpiled.js | 2 +- .../expectedOutput-2.0/output.transpiled.txt | 4 +- .../node/expectedOutput-2.0/output.txt | 6 +- 19 files changed, 268 insertions(+), 184 deletions(-) create mode 100644 index.js create mode 100644 src/constants.ts rename index.ts => src/index.ts (77%) create mode 100644 src/interfaces.ts rename resolver.ts => src/resolver.ts (93%) rename tsconfig.json => src/tsconfig.json (51%) rename {typings => src/typings}/arrify/arrify.d.ts (100%) rename {typings => src/typings}/colors/colors.d.ts (100%) rename {typings => src/typings}/loaderUtils/loaderUtils.d.ts (100%) rename {typings => src/typings}/node/node.d.ts (100%) rename {typings => src/typings}/objectAssign/objectAssign.d.ts (100%) create mode 100644 src/utils.ts diff --git a/.gitignore b/.gitignore index a213b918c..189374f07 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ /*.js +!index.js +/src/*.js /*.d.ts /*.log *.js.map @@ -8,4 +10,4 @@ npm-debug.log /test/execution-tests/**/typings !/test/**/expectedOutput-*/** /node_modules -!build.js \ No newline at end of file +!build.js diff --git a/index.js b/index.js new file mode 100644 index 000000000..b6e436d0e --- /dev/null +++ b/index.js @@ -0,0 +1,3 @@ +var loader = require('./src'); + +module.exports = loader; \ No newline at end of file diff --git a/package.json b/package.json index 91b19e425..51eeb5ddd 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "description": "TypeScript loader for webpack", "main": "index.js", "scripts": { - "build": "tsc", + "build": "tsc --project \"./src\"", "comparison-tests": "npm link ./test/comparison-tests/testLib && node test/comparison-tests/run-tests.js", "execution-tests": "node test/execution-tests/run-tests.js", "test": "node test/run-tests.js", diff --git a/src/constants.ts b/src/constants.ts new file mode 100644 index 000000000..194187109 --- /dev/null +++ b/src/constants.ts @@ -0,0 +1,3 @@ +import os = require('os'); + +export var EOL = os.EOL; diff --git a/index.ts b/src/index.ts similarity index 77% rename from index.ts rename to src/index.ts index c6b676235..7f7daf5cc 100644 --- a/index.ts +++ b/src/index.ts @@ -1,16 +1,13 @@ -/// -/// -/// -/// -/// import typescript = require('typescript'); import path = require('path'); import fs = require('fs'); -import os = require('os'); import loaderUtils = require('loader-utils'); import objectAssign = require('object-assign'); import arrify = require('arrify'); import makeResolver = require('./resolver'); +import interfaces = require('./interfaces'); +import constants = require('./constants'); +import utils = require('./utils'); var Console = require('console').Console; var semver = require('semver') require('colors'); @@ -18,134 +15,16 @@ require('colors'); const stderrConsole = new Console(process.stderr); const stdoutConsole = new Console(process.stdout); -var pushArray = function(arr, toPush) { - Array.prototype.splice.apply(arr, [0, 0].concat(toPush)); -} - -function hasOwnProperty(obj, property) { - return Object.prototype.hasOwnProperty.call(obj, property) -} - enum LogLevel { INFO = 1, WARN = 2, ERROR = 3 } -interface LoaderOptions { - silent: boolean; - logLevel: string; - logInfoToStdOut: boolean; - instance: string; - compiler: string; - configFileName: string; - transpileOnly: boolean; - ignoreDiagnostics: number[]; - compilerOptions: typescript.CompilerOptions; -} - -interface TSFile { - text: string; - version: number; -} - -interface TSFiles { - [fileName: string]: TSFile; -} - -interface DependencyGraph { - [index: string]: string[] -} - -interface ReverseDependencyGraph { - [index: string]: { - [index: string]: boolean - } -} - -interface TSInstance { - compiler: typeof typescript; - compilerOptions: typescript.CompilerOptions; - loaderOptions: LoaderOptions; - files: TSFiles; - languageService?: typescript.LanguageService; - version?: number; - dependencyGraph: DependencyGraph; - reverseDependencyGraph: ReverseDependencyGraph; - modifiedFiles?: TSFiles; - filesWithErrors?: TSFiles; -} - -interface TSInstances { - [name: string]: TSInstance; -} - -interface WebpackError { - module?: any; - file?: string; - message: string; - rawMessage: string; - location?: {line: number, character: number}; - loaderSource: string; -} - -interface ResolvedModule { - resolvedFileName: string; - resolvedModule?: ResolvedModule; - isExternalLibraryImport?: boolean; -} - -interface TSCompatibleCompiler { - // typescript@next 1.7+ - readConfigFile(fileName: string, readFile: (path: string) => string): { - config?: any; - error?: typescript.Diagnostic; - }; - // typescript@latest 1.6.2 - readConfigFile(fileName: string): { - config?: any; - error?: typescript.Diagnostic; - }; - // typescript@next 1.8+ - parseJsonConfigFileContent?(json: any, host: typescript.ParseConfigHost, basePath: string): typescript.ParsedCommandLine; - // typescript@latest 1.6.2 - parseConfigFile?(json: any, host: typescript.ParseConfigHost, basePath: string): typescript.ParsedCommandLine; -} - -var instances = {}; -var webpackInstances = []; +var instances = {}; +var webpackInstances: any = []; let scriptRegex = /\.tsx?$/i; -// Take TypeScript errors, parse them and format to webpack errors -// Optionally adds a file name -function formatErrors(diagnostics: typescript.Diagnostic[], instance: TSInstance, merge?: any): WebpackError[] { - return diagnostics - .filter(diagnostic => instance.loaderOptions.ignoreDiagnostics.indexOf(diagnostic.code) == -1) - .map(diagnostic => { - var errorCategory = instance.compiler.DiagnosticCategory[diagnostic.category].toLowerCase(); - var errorCategoryAndCode = errorCategory + ' TS' + diagnostic.code + ': '; - - var messageText = errorCategoryAndCode + instance.compiler.flattenDiagnosticMessageText(diagnostic.messageText, os.EOL); - if (diagnostic.file) { - var lineChar = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); - return { - message: `${'('.white}${(lineChar.line+1).toString().cyan},${(lineChar.character+1).toString().cyan}): ${messageText.red}`, - rawMessage: messageText, - location: {line: lineChar.line+1, character: lineChar.character+1}, - loaderSource: 'ts-loader' - }; - } - else { - return { - message:`${messageText.red}`, - rawMessage: messageText, - loaderSource: 'ts-loader' - }; - } - }) - .map(error => objectAssign(error, merge)); -} - // The tsconfig.json is found using the same method as `tsc`, starting in the current directory // and continuing up the parent directory chain. function findConfigFile(compiler: typeof typescript, searchPath: string, configFileName: string): string { @@ -168,7 +47,7 @@ function findConfigFile(compiler: typeof typescript, searchPath: string, configF // along with definition files and options. This function either creates an instance // or returns the existing one. Multiple instances are possible by using the // `instance` property. -function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { instance?: TSInstance, error?: WebpackError } { +function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loader: any): { instance?: interfaces.TSInstance, error?: interfaces.WebpackError } { function log(...messages: string[]): void { logToConsole(loaderOptions.logInfoToStdOut ? stdoutConsole : stderrConsole, messages); } @@ -197,7 +76,7 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { } } - if (hasOwnProperty(instances, loaderOptions.instance)) { + if (utils.hasOwnProperty(instances, loaderOptions.instance)) { return { instance: instances[loaderOptions.instance] }; } @@ -230,8 +109,8 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { logWarning(`${motd}. This version may or may not be compatible with ts-loader.`.yellow); } - var files = {}; - var instance: TSInstance = instances[loaderOptions.instance] = { + var files: interfaces.TSFiles = {}; + var instance: interfaces.TSInstance = instances[loaderOptions.instance] = { compiler, compilerOptions: null, loaderOptions, @@ -249,7 +128,7 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { }; // Load any available tsconfig.json file - var filesToLoad = []; + var filesToLoad: string[] = []; var configFilePath = findConfigFile(compiler, path.dirname(loader.resourcePath), loaderOptions.configFileName); var configFile: { config?: any; @@ -261,13 +140,13 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { // HACK: relies on the fact that passing an extra argument won't break // the old API that has a single parameter - configFile = (compiler).readConfigFile( + configFile = (compiler).readConfigFile( configFilePath, compiler.sys.readFile ); if (configFile.error) { - var configFileError = formatErrors([configFile.error], instance, {file: configFilePath })[0]; + var configFileError = utils.formatErrors([configFile.error], instance, {file: configFilePath })[0]; return { error: configFileError } } } @@ -296,16 +175,16 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { scriptRegex = /\.tsx?$|\.jsx?$/i; } - var configParseResult; + var configParseResult: typescript.ParsedCommandLine; if (typeof (compiler).parseJsonConfigFileContent === 'function') { // parseConfigFile was renamed between 1.6.2 and 1.7 - configParseResult = (compiler).parseJsonConfigFileContent( + configParseResult = (compiler).parseJsonConfigFileContent( configFile.config, compiler.sys, path.dirname(configFilePath || '') ); } else { - configParseResult = (compiler).parseConfigFile( + configParseResult = (compiler).parseConfigFile( configFile.config, compiler.sys, path.dirname(configFilePath || '') @@ -313,9 +192,9 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { } if (configParseResult.errors.length) { - pushArray( + utils.pushArray( loader._module.errors, - formatErrors(configParseResult.errors, instance, { file: configFilePath })); + utils.formatErrors(configParseResult.errors, instance, { file: configFilePath })); return { error: { file: configFilePath, @@ -343,9 +222,9 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { var program = compiler.createProgram([], compilerOptions), diagnostics = program.getOptionsDiagnostics(); - pushArray( + utils.pushArray( loader._module.errors, - formatErrors(diagnostics, instance, {file: configFilePath || 'tsconfig.json'})); + utils.formatErrors(diagnostics, instance, {file: configFilePath || 'tsconfig.json'})); return { instance: instances[loaderOptions.instance] = { compiler, compilerOptions, loaderOptions, files, dependencyGraph: {}, reverseDependencyGraph: {} }}; } @@ -373,12 +252,12 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { let newLine = compilerOptions.newLine === 0 /* CarriageReturnLineFeed */ ? '\r\n' : compilerOptions.newLine === 1 /* LineFeed */ ? '\n' : - os.EOL; + constants.EOL; // make a (sync) resolver that follows webpack's rules let resolver = makeResolver(loader.options); - var readFile = function(fileName) { + var readFile = function(fileName: string) { fileName = path.normalize(fileName); try { return fs.readFileSync(fileName, {encoding: 'utf8'}) @@ -397,11 +276,11 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { var servicesHost = { getProjectVersion: () => instance.version+'', getScriptFileNames: () => Object.keys(files).filter(filePath => scriptRegex.test(filePath)), - getScriptVersion: fileName => { + getScriptVersion: (fileName: string) => { fileName = path.normalize(fileName); return files[fileName] && files[fileName].version.toString(); }, - getScriptSnapshot: fileName => { + getScriptSnapshot: (fileName: string) => { // This is called any time TypeScript needs a file's text // We either load from memory or from disk fileName = path.normalize(fileName); @@ -429,11 +308,11 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { getCurrentDirectory: () => process.cwd(), getCompilationSettings: () => compilerOptions, - getDefaultLibFileName: options => compiler.getDefaultLibFilePath(options), + getDefaultLibFileName: (options: typescript.CompilerOptions) => compiler.getDefaultLibFilePath(options), getNewLine: () => newLine, log: log, resolveModuleNames: (moduleNames: string[], containingFile: string) => { - let resolvedModules: ResolvedModule[] = []; + let resolvedModules: interfaces.ResolvedModule[] = []; for (let moduleName of moduleNames) { let resolvedFileName: string; @@ -480,7 +359,7 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { var getCompilerOptionDiagnostics = true; var checkAllFilesForErrors = true; - loader._compiler.plugin("after-compile", (compilation, callback) => { + loader._compiler.plugin("after-compile", (compilation: interfaces.WebpackCompilation, callback: () => void) => { // Don't add errors for child compilations if (compilation.compiler.isChild()) { callback(); @@ -493,7 +372,7 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { // compilation-to-compilation, and since not every module always runs through // the loader, we need to detect and remove any pre-existing errors. - function removeTSLoaderErrors(errors: WebpackError[]) { + function removeTSLoaderErrors(errors: interfaces.WebpackError[]) { let index = -1, length = errors.length; while (++index < length) { if (errors[index].loaderSource == 'ts-loader') { @@ -525,19 +404,19 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { // handle compiler option errors after the first compile if (getCompilerOptionDiagnostics) { getCompilerOptionDiagnostics = false; - pushArray( + utils.pushArray( compilation.errors, - formatErrors(languageService.getCompilerOptionsDiagnostics(), instance, {file: configFilePath || 'tsconfig.json'})); + utils.formatErrors(languageService.getCompilerOptionsDiagnostics(), instance, {file: configFilePath || 'tsconfig.json'})); } // build map of all modules based on normalized filename // this is used for quick-lookup when trying to find modules // based on filepath - let modules = {}; + let modules: { [modulePath:string]: interfaces.WebpackModule[]} = {}; compilation.modules.forEach(module => { if (module.resource) { let modulePath = path.normalize(module.resource); - if (hasOwnProperty(modules, modulePath)) { + if (utils.hasOwnProperty(modules, modulePath)) { let existingModules = modules[modulePath]; if (existingModules.indexOf(module) == -1) { existingModules.push(module); @@ -550,9 +429,9 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { }) // gather all errors from TypeScript and output them to webpack - let filesWithErrors: TSFiles = {} + let filesWithErrors: interfaces.TSFiles = {} // calculate array of files to check - let filesToCheckForErrors: TSFiles = null + let filesToCheckForErrors: interfaces.TSFiles = null if (checkAllFilesForErrors) { // check all files on initial run filesToCheckForErrors = instance.files @@ -585,7 +464,7 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { } // if we have access to a webpack module, use that - if (hasOwnProperty(modules, filePath)) { + if (utils.hasOwnProperty(modules, filePath)) { let associatedModules = modules[filePath]; associatedModules.forEach(module => { @@ -593,14 +472,14 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { removeTSLoaderErrors(module.errors); // append errors - let formattedErrors = formatErrors(errors, instance, { module }); - pushArray(module.errors, formattedErrors); - pushArray(compilation.errors, formattedErrors); + let formattedErrors = utils.formatErrors(errors, instance, { module }); + utils.pushArray(module.errors, formattedErrors); + utils.pushArray(compilation.errors, formattedErrors); }) } // otherwise it's a more generic error else { - pushArray(compilation.errors, formatErrors(errors, instance, {file: filePath})); + utils.pushArray(compilation.errors, utils.formatErrors(errors, instance, {file: filePath})); } }); @@ -626,7 +505,7 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { }); // manually update changed files - loader._compiler.plugin("watch-run", (watching, cb) => { + loader._compiler.plugin("watch-run", (watching: interfaces.WebpackWatching, cb: () => void) => { var mtimes = watching.compiler.watchFileSystem.watcher.mtimes; if (null === instance.modifiedFiles) { instance.modifiedFiles = {} @@ -650,15 +529,15 @@ function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { return { instance }; } -function loader(contents) { +function loader(contents: string) { this.cacheable && this.cacheable(); var callback = this.async(); var filePath = path.normalize(this.resourcePath); - var queryOptions = loaderUtils.parseQuery(this.query); + var queryOptions = loaderUtils.parseQuery(this.query); var configFileOptions = this.options.ts || {}; - var options = objectAssign({}, { + var options = objectAssign({}, { silent: false, logLevel: 'INFO', logInfoToStdOut: false, @@ -688,7 +567,7 @@ function loader(contents) { // Update file contents var file = instance.files[filePath] if (!file) { - file = instance.files[filePath] = { version: 0 }; + file = instance.files[filePath] = { version: 0 }; } if (file.text !== contents) { @@ -715,7 +594,7 @@ function loader(contents) { ({ outputText, sourceMapText, diagnostics } = transpileResult); - pushArray(this._module.errors, formatErrors(diagnostics, instance, {module: this._module})); + utils.pushArray(this._module.errors, utils.formatErrors(diagnostics, instance, {module: this._module})); } else { let langService = instance.languageService; diff --git a/src/interfaces.ts b/src/interfaces.ts new file mode 100644 index 000000000..f3106a2b3 --- /dev/null +++ b/src/interfaces.ts @@ -0,0 +1,150 @@ +import typescript = require('typescript'); + +export interface WebpackError { + module?: any; + file?: string; + message: string; + rawMessage: string; + location?: { line: number, character: number }; + loaderSource: string; +} + +export interface WebpackCompilation { + compiler: WebpackCompiler; + errors: WebpackError[]; + modules: WebpackModule[]; + assets: { + [index: string]: { + size: () => number; + source: () => string; + } + }; +} + +export interface WebpackCompiler { + isChild(): boolean; + context: string; // a guess + watchFileSystem: WebpackNodeWatchFileSystem; +} + +export interface WebpackModule { + resource: string; + errors: WebpackError[]; +} + +export interface WebpackNodeWatchFileSystem { + watcher: { + mtimes: number; // a guess + } +} + +export interface WebpackWatching { + compiler: WebpackCompiler; // a guess +} + +export interface Resolve { + /** Replace modules by other modules or paths. */ + alias?: { [key: string]: string; }; + /** + * The directory (absolute path) that contains your modules. + * May also be an array of directories. + * This setting should be used to add individual directories to the search path. */ + root?: string | string[]; + /** + * An array of directory names to be resolved to the current directory as well as its ancestors, and searched for modules. + * This functions similarly to how node finds “node_modules” directories. + * For example, if the value is ["mydir"], webpack will look in “./mydir”, “../mydir”, “../../mydir”, etc. + */ + modulesDirectories?: string[]; + /** + * A directory (or array of directories absolute paths), + * in which webpack should look for modules that weren’t found in resolve.root or resolve.modulesDirectories. + */ + fallback?: string | string[]; + /** + * An array of extensions that should be used to resolve modules. + * For example, in order to discover CoffeeScript files, your array should contain the string ".coffee". + */ + extensions?: string[]; + /** Check these fields in the package.json for suitable files. */ + packageMains?: (string | string[])[]; + /** Check this field in the package.json for an object. Key-value-pairs are threaded as aliasing according to this spec */ + packageAlias?: (string | string[])[]; + /** + * Enable aggressive but unsafe caching for the resolving of a part of your files. + * Changes to cached paths may cause failure (in rare cases). An array of RegExps, only a RegExp or true (all files) is expected. + * If the resolved path matches, it’ll be cached. + */ + unsafeCache?: RegExp | RegExp[] | boolean; +} + +export interface TSInstance { + compiler: typeof typescript; + compilerOptions: typescript.CompilerOptions; + loaderOptions: LoaderOptions; + files: TSFiles; + languageService?: typescript.LanguageService; + version?: number; + dependencyGraph: DependencyGraph; + reverseDependencyGraph: ReverseDependencyGraph; + modifiedFiles?: TSFiles; + filesWithErrors?: TSFiles; +} + +export interface TSInstances { + [name: string]: TSInstance; +} + +interface DependencyGraph { + [index: string]: string[] +} + +interface ReverseDependencyGraph { + [index: string]: { + [index: string]: boolean + } +} + +export interface LoaderOptions { + silent: boolean; + logLevel: string; + logInfoToStdOut: boolean; + instance: string; + compiler: string; + configFileName: string; + transpileOnly: boolean; + ignoreDiagnostics: number[]; + compilerOptions: typescript.CompilerOptions; +} + +export interface TSFile { + text: string; + version: number; +} + +export interface TSFiles { + [fileName: string]: TSFile; +} + +export interface ResolvedModule { + resolvedFileName: string; + resolvedModule?: ResolvedModule; + isExternalLibraryImport?: boolean; +} + +export interface TSCompatibleCompiler { + // typescript@next 1.7+ + readConfigFile(fileName: string, readFile: (path: string) => string): { + config?: any; + error?: typescript.Diagnostic; + }; + // typescript@latest 1.6.2 + readConfigFile(fileName: string): { + config?: any; + error?: typescript.Diagnostic; + }; + // typescript@next 1.8+ + parseJsonConfigFileContent?(json: any, host: typescript.ParseConfigHost, basePath: string): typescript.ParsedCommandLine; + // typescript@latest 1.6.2 + parseConfigFile?(json: any, host: typescript.ParseConfigHost, basePath: string): typescript.ParsedCommandLine; +} diff --git a/resolver.ts b/src/resolver.ts similarity index 93% rename from resolver.ts rename to src/resolver.ts index 1f66ec317..656055296 100644 --- a/resolver.ts +++ b/src/resolver.ts @@ -1,8 +1,7 @@ // This file serves as a hacky workaround for the lack of "resolveSync" support in webpack. // We make our own resolver using a sync file system but using the same plugins & options // that webpack does. - -/// +import interfaces = require('./interfaces'); var Resolver = require("enhanced-resolve/lib/Resolver"); var SyncNodeJsInputFileSystem = require("enhanced-resolve/lib/SyncNodeJsInputFileSystem"); @@ -19,7 +18,7 @@ var DirectoryDescriptionFileFieldAliasPlugin = require("enhanced-resolve/lib/Dir var FileAppendPlugin = require("enhanced-resolve/lib/FileAppendPlugin"); var ResultSymlinkPlugin = require("enhanced-resolve/lib/ResultSymlinkPlugin"); -function makeRootPlugin(name, root) { +function makeRootPlugin(name: string, root: string | string[]) { if(typeof root === "string") return new ModulesInRootPlugin(name, root); else if(Array.isArray(root)) { @@ -32,7 +31,7 @@ function makeRootPlugin(name, root) { return function() {}; } -function makeResolver(options) { +function makeResolver(options: { resolve: interfaces.Resolve }) { let fileSystem = new CachedInputFileSystem(new SyncNodeJsInputFileSystem(), 60000); let resolver = new Resolver(fileSystem); diff --git a/tsconfig.json b/src/tsconfig.json similarity index 51% rename from tsconfig.json rename to src/tsconfig.json index 35f96a537..9fe417fe7 100644 --- a/tsconfig.json +++ b/src/tsconfig.json @@ -1,9 +1,8 @@ { "compilerOptions": { + "noImplicitAny": true, + "suppressImplicitAnyIndexErrors": true, "module": "commonjs", "moduleResolution": "node" - }, - "files": [ - "index.ts" - ] -} + } +} \ No newline at end of file diff --git a/typings/arrify/arrify.d.ts b/src/typings/arrify/arrify.d.ts similarity index 100% rename from typings/arrify/arrify.d.ts rename to src/typings/arrify/arrify.d.ts diff --git a/typings/colors/colors.d.ts b/src/typings/colors/colors.d.ts similarity index 100% rename from typings/colors/colors.d.ts rename to src/typings/colors/colors.d.ts diff --git a/typings/loaderUtils/loaderUtils.d.ts b/src/typings/loaderUtils/loaderUtils.d.ts similarity index 100% rename from typings/loaderUtils/loaderUtils.d.ts rename to src/typings/loaderUtils/loaderUtils.d.ts diff --git a/typings/node/node.d.ts b/src/typings/node/node.d.ts similarity index 100% rename from typings/node/node.d.ts rename to src/typings/node/node.d.ts diff --git a/typings/objectAssign/objectAssign.d.ts b/src/typings/objectAssign/objectAssign.d.ts similarity index 100% rename from typings/objectAssign/objectAssign.d.ts rename to src/typings/objectAssign/objectAssign.d.ts diff --git a/src/utils.ts b/src/utils.ts new file mode 100644 index 000000000..30d7aa5b3 --- /dev/null +++ b/src/utils.ts @@ -0,0 +1,49 @@ +import typescript = require('typescript'); +import objectAssign = require('object-assign'); +import constants = require('./constants'); +import interfaces = require('./interfaces'); + +export function pushArray(arr: T[], toPush: any) { + Array.prototype.splice.apply(arr, [0, 0].concat(toPush)); +} + +export function hasOwnProperty(obj: T, property: string) { + return Object.prototype.hasOwnProperty.call(obj, property) +} + +/** + * Take TypeScript errors, parse them and format to webpack errors + * Optionally adds a file name + */ +export function formatErrors( + diagnostics: typescript.Diagnostic[], + instance: interfaces.TSInstance, + merge?: any): interfaces.WebpackError[] { + + return diagnostics + .filter(diagnostic => instance.loaderOptions.ignoreDiagnostics.indexOf(diagnostic.code) == -1) + .map(diagnostic => { + var errorCategory = instance.compiler.DiagnosticCategory[diagnostic.category].toLowerCase(); + var errorCategoryAndCode = errorCategory + ' TS' + diagnostic.code + ': '; + + var messageText = errorCategoryAndCode + instance.compiler.flattenDiagnosticMessageText(diagnostic.messageText, constants.EOL); + if (diagnostic.file) { + var lineChar = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); + return { + message: `${'('.white}${(lineChar.line+1).toString().cyan},${(lineChar.character+1).toString().cyan}): ${messageText.red}`, + rawMessage: messageText, + location: {line: lineChar.line+1, character: lineChar.character+1}, + loaderSource: 'ts-loader' + }; + } + else { + return { + message:`${messageText.red}`, + rawMessage: messageText, + loaderSource: 'ts-loader' + }; + } + }) + .map(error => objectAssign(error, merge)); +} + diff --git a/test/comparison-tests/node/app.ts b/test/comparison-tests/node/app.ts index a3fa3509c..08e21d426 100644 --- a/test/comparison-tests/node/app.ts +++ b/test/comparison-tests/node/app.ts @@ -1 +1 @@ -/// \ No newline at end of file +/// \ No newline at end of file diff --git a/test/comparison-tests/node/expectedOutput-2.0/bundle.js b/test/comparison-tests/node/expectedOutput-2.0/bundle.js index 19d798610..a3d17262f 100644 --- a/test/comparison-tests/node/expectedOutput-2.0/bundle.js +++ b/test/comparison-tests/node/expectedOutput-2.0/bundle.js @@ -44,7 +44,7 @@ /* 0 */ /***/ function(module, exports) { - /// + /// /***/ } diff --git a/test/comparison-tests/node/expectedOutput-2.0/bundle.transpiled.js b/test/comparison-tests/node/expectedOutput-2.0/bundle.transpiled.js index c38f39d99..df06de007 100644 --- a/test/comparison-tests/node/expectedOutput-2.0/bundle.transpiled.js +++ b/test/comparison-tests/node/expectedOutput-2.0/bundle.transpiled.js @@ -44,7 +44,7 @@ /* 0 */ /***/ function(module, exports) { - "use strict";/// + "use strict";/// /***/ } diff --git a/test/comparison-tests/node/expectedOutput-2.0/output.transpiled.txt b/test/comparison-tests/node/expectedOutput-2.0/output.transpiled.txt index 2db3f5850..f412fc3dc 100644 --- a/test/comparison-tests/node/expectedOutput-2.0/output.transpiled.txt +++ b/test/comparison-tests/node/expectedOutput-2.0/output.transpiled.txt @@ -1,4 +1,4 @@ Asset Size Chunks Chunk Names bundle.js 1.46 kB 0 [emitted] main -chunk {0} bundle.js (main) 68 bytes [rendered] - [0] ./.test/node/app.ts 68 bytes {0} [built] \ No newline at end of file +chunk {0} bundle.js (main) 72 bytes [rendered] + [0] ./.test/node/app.ts 72 bytes {0} [built] \ No newline at end of file diff --git a/test/comparison-tests/node/expectedOutput-2.0/output.txt b/test/comparison-tests/node/expectedOutput-2.0/output.txt index 3d487cb03..2ee0a5e06 100644 --- a/test/comparison-tests/node/expectedOutput-2.0/output.txt +++ b/test/comparison-tests/node/expectedOutput-2.0/output.txt @@ -1,4 +1,4 @@ Asset Size Chunks Chunk Names -bundle.js 1.44 kB 0 [emitted] main -chunk {0} bundle.js (main) 55 bytes [rendered] - [0] ./.test/node/app.ts 55 bytes {0} [built] \ No newline at end of file +bundle.js 1.45 kB 0 [emitted] main +chunk {0} bundle.js (main) 59 bytes [rendered] + [0] ./.test/node/app.ts 59 bytes {0} [built] \ No newline at end of file From 334e14b2835be9761bf12299c2bd5840038a9b24 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Mon, 24 Oct 2016 19:20:32 +0100 Subject: [PATCH 02/17] moved logger into separate module --- src/index.ts | 70 ++++++++++++++------------------------------------- src/logger.ts | 56 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 51 deletions(-) create mode 100644 src/logger.ts diff --git a/src/index.ts b/src/index.ts index 7f7daf5cc..27f165223 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,25 +8,18 @@ import makeResolver = require('./resolver'); import interfaces = require('./interfaces'); import constants = require('./constants'); import utils = require('./utils'); -var Console = require('console').Console; +import getLogger = require('./logger'); var semver = require('semver') require('colors'); -const stderrConsole = new Console(process.stderr); -const stdoutConsole = new Console(process.stdout); - -enum LogLevel { - INFO = 1, - WARN = 2, - ERROR = 3 -} - var instances = {}; var webpackInstances: any = []; let scriptRegex = /\.tsx?$/i; -// The tsconfig.json is found using the same method as `tsc`, starting in the current directory -// and continuing up the parent directory chain. +/** + * The tsconfig.json is found using the same method as `tsc`, starting in the current directory + * and continuing up the parent directory chain. + */ function findConfigFile(compiler: typeof typescript, searchPath: string, configFileName: string): string { while (true) { var fileName = path.join(searchPath, configFileName); @@ -42,40 +35,14 @@ function findConfigFile(compiler: typeof typescript, searchPath: string, configF return undefined; } -// The loader is executed once for each file seen by webpack. However, we need to keep -// a persistent instance of TypeScript that contains all of the files in the program -// along with definition files and options. This function either creates an instance -// or returns the existing one. Multiple instances are possible by using the -// `instance` property. +/** + * The loader is executed once for each file seen by webpack. However, we need to keep + * a persistent instance of TypeScript that contains all of the files in the program + * along with definition files and options. This function either creates an instance + * or returns the existing one. Multiple instances are possible by using the + * `instance` property. + */ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loader: any): { instance?: interfaces.TSInstance, error?: interfaces.WebpackError } { - function log(...messages: string[]): void { - logToConsole(loaderOptions.logInfoToStdOut ? stdoutConsole : stderrConsole, messages); - } - - function logToConsole(logConsole:any, messages: string[]): void { - if (!loaderOptions.silent) { - console.log.apply(logConsole, messages); - } - } - - function logInfo(...messages: string[]): void { - if (LogLevel[loaderOptions.logLevel] <= LogLevel.INFO) { - logToConsole(loaderOptions.logInfoToStdOut ? stdoutConsole : stderrConsole, messages); - } - } - - function logError(...messages: string[]): void { - if (LogLevel[loaderOptions.logLevel] <= LogLevel.ERROR) { - logToConsole(stderrConsole, messages); - } - } - - function logWarning(...messages: string[]): void { - if (LogLevel[loaderOptions.logLevel] <= LogLevel.WARN) { - logToConsole(stderrConsole, messages); - } - } - if (utils.hasOwnProperty(instances, loaderOptions.instance)) { return { instance: instances[loaderOptions.instance] }; } @@ -94,6 +61,7 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade } }; } + const log = getLogger(loaderOptions); var motd = `ts-loader: Using ${loaderOptions.compiler}@${compiler.version}`, compilerCompatible = false; if (loaderOptions.compiler == 'typescript') { @@ -102,11 +70,11 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade compilerCompatible = true; } else { - logError(`${motd}. This version is incompatible with ts-loader. Please upgrade to the latest version of TypeScript.`.red); + log.logError(`${motd}. This version is incompatible with ts-loader. Please upgrade to the latest version of TypeScript.`.red); } } else { - logWarning(`${motd}. This version may or may not be compatible with ts-loader.`.yellow); + log.logWarning(`${motd}. This version may or may not be compatible with ts-loader.`.yellow); } var files: interfaces.TSFiles = {}; @@ -135,8 +103,8 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade error?: typescript.Diagnostic; }; if (configFilePath) { - if (compilerCompatible) logInfo(`${motd} and ${configFilePath}`.green) - else logInfo(`ts-loader: Using config file at ${configFilePath}`.green) + if (compilerCompatible) log.logInfo(`${motd} and ${configFilePath}`.green) + else log.logInfo(`ts-loader: Using config file at ${configFilePath}`.green) // HACK: relies on the fact that passing an extra argument won't break // the old API that has a single parameter @@ -151,7 +119,7 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade } } else { - if (compilerCompatible) logInfo(motd.green) + if (compilerCompatible) log.logInfo(motd.green) configFile = { config: { @@ -310,7 +278,7 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade getCompilationSettings: () => compilerOptions, getDefaultLibFileName: (options: typescript.CompilerOptions) => compiler.getDefaultLibFilePath(options), getNewLine: () => newLine, - log: log, + log: log.log, resolveModuleNames: (moduleNames: string[], containingFile: string) => { let resolvedModules: interfaces.ResolvedModule[] = []; diff --git a/src/logger.ts b/src/logger.ts new file mode 100644 index 000000000..15572743c --- /dev/null +++ b/src/logger.ts @@ -0,0 +1,56 @@ +import interfaces = require('./interfaces'); +var Console = require('console').Console; + +const stderrConsole = new Console(process.stderr); +const stdoutConsole = new Console(process.stdout); + +enum LogLevel { + INFO = 1, + WARN = 2, + ERROR = 3 +} + +interface Logger { + (whereToLog: any, messages: string[]): void +} + +function makeLogger(loaderOptions: interfaces.LoaderOptions) { + return loaderOptions.silent + ? (whereToLog: any, messages: string[]) => {} + : (whereToLog: any, messages: string[]) => console.log.apply(whereToLog, messages); +} + +function makeExternalLogger(loaderOptions: interfaces.LoaderOptions, logger: Logger) { + const output = loaderOptions.logInfoToStdOut ? stdoutConsole : stderrConsole; + return (...messages: string[]) => logger(output, messages); +} + +function makeLogInfo(loaderOptions: interfaces.LoaderOptions, logger: Logger) { + return LogLevel[loaderOptions.logLevel] <= LogLevel.INFO + ? (...messages: string[]) => logger(loaderOptions.logInfoToStdOut ? stdoutConsole : stderrConsole, messages) + : (...messages: string[]) => {} +} + +function makeLogError(loaderOptions: interfaces.LoaderOptions, logger: Logger) { + return LogLevel[loaderOptions.logLevel] <= LogLevel.ERROR + ? (...messages: string[]) => logger(stderrConsole, messages) + : (...messages: string[]) => {} +} + +function makeLogWarning(loaderOptions: interfaces.LoaderOptions, logger: Logger) { + return LogLevel[loaderOptions.logLevel] <= LogLevel.WARN + ? (...messages: string[]) => logger(stderrConsole, messages) + : (...messages: string[]) => {} +} + +function getLogger(loaderOptions: interfaces.LoaderOptions) { + const logger = makeLogger(loaderOptions); + return { + log: makeExternalLogger(loaderOptions, logger), + logInfo: makeLogInfo(loaderOptions, logger), + logWarning: makeLogWarning(loaderOptions, logger), + logError: makeLogError(loaderOptions, logger) + } +} + +export = getLogger; \ No newline at end of file From 58c330a6d1c214731c2e9838aa5d54d9bb0365a7 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Mon, 24 Oct 2016 19:20:55 +0100 Subject: [PATCH 03/17] updated node definition --- src/typings/node/node.d.ts | 3445 +++++++++++++++++++++++++++++++----- 1 file changed, 2955 insertions(+), 490 deletions(-) diff --git a/src/typings/node/node.d.ts b/src/typings/node/node.d.ts index 321725c19..19c2609d0 100644 --- a/src/typings/node/node.d.ts +++ b/src/typings/node/node.d.ts @@ -1,21 +1,38 @@ -// Type definitions for Node.js v0.10.1 +// Type definitions for Node.js v6.x // Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript , DefinitelyTyped -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: Microsoft TypeScript , DefinitelyTyped +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************************ * * -* Node.js v0.10.1 API * +* Node.js v6.x API * * * ************************************************/ +interface Error { + stack?: string; +} + +interface ErrorConstructor { + captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + stackTraceLimit: number; +} + +// compat for TypeScript 1.8 +// if you use with --target es3 or --target es5 and use below definitions, +// use the lib.es6.d.ts that is bundled with TypeScript 1.8. +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } + /************************************************ * * * GLOBAL * * * ************************************************/ declare var process: NodeJS.Process; -declare var global: any; +declare var global: NodeJS.Global; declare var __filename: string; declare var __dirname: string; @@ -27,23 +44,30 @@ declare function clearInterval(intervalId: NodeJS.Timer): void; declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; declare function clearImmediate(immediateId: any): void; -declare var require: { +interface NodeRequireFunction { (id: string): any; - resolve(id:string): string; +} + +interface NodeRequire extends NodeRequireFunction { + resolve(id: string): string; cache: any; extensions: any; main: any; -}; +} + +declare var require: NodeRequire; -declare var module: { +interface NodeModule { exports: any; - require(id: string): any; + require: NodeRequireFunction; id: string; filename: string; loaded: boolean; parent: any; children: any[]; -}; +} + +declare var module: NodeModule; // Same as module.exports declare var exports: any; @@ -60,16 +84,146 @@ declare var SlowBuffer: { // Buffer class -interface Buffer extends NodeBuffer {} +type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "binary" | "hex"; +interface Buffer extends NodeBuffer { } + +/** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + */ declare var Buffer: { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ new (str: string, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ new (size: number): Buffer; - new (size: Uint8Array): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + new (array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + new (arrayBuffer: ArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ new (array: any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + new (buffer: Buffer): Buffer; prototype: Buffer; - isBuffer(obj: any): boolean; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafeSlow(size: number): Buffer; }; /************************************************ @@ -77,31 +231,38 @@ declare var Buffer: { * GLOBAL INTERFACES * * * ************************************************/ -declare module NodeJS { +declare namespace NodeJS { export interface ErrnoException extends Error { - errno?: any; + errno?: string; code?: string; path?: string; syscall?: string; + stack?: string; } - export interface EventEmitter { - addListener(event: string, listener: Function): EventEmitter; - on(event: string, listener: Function): EventEmitter; - once(event: string, listener: Function): EventEmitter; - removeListener(event: string, listener: Function): EventEmitter; - removeAllListeners(event?: string): EventEmitter; - setMaxListeners(n: number): void; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; + export class EventEmitter { + addListener(event: string | symbol, listener: Function): this; + on(event: string | symbol, listener: Function): this; + once(event: string | symbol, listener: Function): this; + removeListener(event: string | symbol, listener: Function): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + listenerCount(type: string | symbol): number; + // Added in Node 6... + prependListener(event: string | symbol, listener: Function): this; + prependOnceListener(event: string | symbol, listener: Function): this; + eventNames(): (string | symbol)[]; } export interface ReadableStream extends EventEmitter { readable: boolean; - read(size?: number): any; + read(size?: number): string | Buffer; setEncoding(encoding: string): void; - pause(): void; - resume(): void; + pause(): ReadableStream; + resume(): ReadableStream; pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: T): void; unshift(chunk: string): void; @@ -111,8 +272,7 @@ declare module NodeJS { export interface WritableStream extends EventEmitter { writable: boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; + write(buffer: Buffer | string, cb?: Function): boolean; write(str: string, encoding?: string, cb?: Function): boolean; end(): void; end(buffer: Buffer, cb?: Function): void; @@ -120,19 +280,59 @@ declare module NodeJS { end(str: string, encoding?: string, cb?: Function): void; } - export interface ReadWriteStream extends ReadableStream, WritableStream {} + export interface ReadWriteStream extends ReadableStream, WritableStream { + pause(): ReadWriteStream; + resume(): ReadWriteStream; + } + + export interface Events extends EventEmitter { } + + export interface Domain extends Events { + run(fn: Function): void; + add(emitter: Events): void; + remove(emitter: Events): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; + + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + } + + export interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + } + + export interface ProcessVersions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } export interface Process extends EventEmitter { stdout: WritableStream; stderr: WritableStream; stdin: ReadableStream; argv: string[]; + argv0: string; + execArgv: string[]; execPath: string; abort(): void; chdir(directory: string): void; cwd(): string; env: any; exit(code?: number): void; + exitCode: number; getgid(): number; setgid(id: number): void; setgid(id: string): void; @@ -140,15 +340,7 @@ declare module NodeJS { setuid(id: number): void; setuid(id: string): void; version: string; - versions: { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - openssl: string; - }; + versions: ProcessVersions; config: { target_defaults: { cflags: any[]; @@ -175,39 +367,118 @@ declare module NodeJS { visibility: string; }; }; - kill(pid: number, signal?: string): void; + kill(pid: number, signal?: string | number): void; pid: number; title: string; arch: string; platform: string; - memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; }; - nextTick(callback: Function): void; + memoryUsage(): MemoryUsage; + nextTick(callback: Function, ...args: any[]): void; umask(mask?: number): number; uptime(): number; - hrtime(time?:number[]): number[]; + hrtime(time?: number[]): number[]; + domain: Domain; // Worker send?(message: any, sendHandle?: any): void; + disconnect(): void; + connected: boolean; + } + + export interface Global { + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + GLOBAL: Global; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: Function; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: any) => void; + clearInterval: (intervalId: NodeJS.Timer) => void; + clearTimeout: (timeoutId: NodeJS.Timer) => void; + console: typeof console; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + process: Process; + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; } export interface Timer { - ref() : void; - unref() : void; + ref(): void; + unref(): void; } } +interface IterableIterator { } + /** * @deprecated */ -interface NodeBuffer { - [index: number]: number; +interface NodeBuffer extends Uint8Array { write(string: string, offset?: number, length?: number, encoding?: string): number; toString(encoding?: string, start?: number, end?: number): string; - toJSON(): any; - length: number; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; slice(start?: number, end?: number): Buffer; - readUInt8(offset: number, noAsset?: boolean): number; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; readUInt16LE(offset: number, noAssert?: boolean): number; readUInt16BE(offset: number, noAssert?: boolean): number; readUInt32LE(offset: number, noAssert?: boolean): number; @@ -221,21 +492,30 @@ interface NodeBuffer { readFloatBE(offset: number, noAssert?: boolean): number; readDoubleLE(offset: number, noAssert?: boolean): number; readDoubleBE(offset: number, noAssert?: boolean): number; - writeUInt8(value: number, offset: number, noAssert?: boolean): void; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): void; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): void; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): void; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): void; - writeInt8(value: number, offset: number, noAssert?: boolean): void; - writeInt16LE(value: number, offset: number, noAssert?: boolean): void; - writeInt16BE(value: number, offset: number, noAssert?: boolean): void; - writeInt32LE(value: number, offset: number, noAssert?: boolean): void; - writeInt32BE(value: number, offset: number, noAssert?: boolean): void; - writeFloatLE(value: number, offset: number, noAssert?: boolean): void; - writeFloatBE(value: number, offset: number, noAssert?: boolean): void; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): void; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): void; - fill(value: any, offset?: number, end?: number): void; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + keys(): IterableIterator; + values(): IterableIterator; } /************************************************ @@ -245,55 +525,83 @@ interface NodeBuffer { ************************************************/ declare module "buffer" { export var INSPECT_MAX_BYTES: number; + var BuffType: typeof Buffer; + var SlowBuffType: typeof SlowBuffer; + export { BuffType as Buffer, SlowBuffType as SlowBuffer }; } declare module "querystring" { - export function stringify(obj: any, sep?: string, eq?: string): string; - export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; - export function escape(): any; - export function unescape(): any; + export interface StringifyOptions { + encodeURIComponent?: Function; + } + + export interface ParseOptions { + maxKeys?: number; + decodeURIComponent?: Function; + } + + export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; + export function escape(str: string): string; + export function unescape(str: string): string; } declare module "events" { - export class EventEmitter implements NodeJS.EventEmitter { - static listenerCount(emitter: EventEmitter, event: string): number; - - addListener(event: string, listener: Function): EventEmitter; - on(event: string, listener: Function): EventEmitter; - once(event: string, listener: Function): EventEmitter; - removeListener(event: string, listener: Function): EventEmitter; - removeAllListeners(event?: string): EventEmitter; - setMaxListeners(n: number): void; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - } + export class EventEmitter extends NodeJS.EventEmitter { + static EventEmitter: EventEmitter; + static listenerCount(emitter: EventEmitter, event: string | symbol): number; // deprecated + static defaultMaxListeners: number; + + addListener(event: string | symbol, listener: Function): this; + on(event: string | symbol, listener: Function): this; + once(event: string | symbol, listener: Function): this; + prependListener(event: string | symbol, listener: Function): this; + prependOnceListener(event: string | symbol, listener: Function): this; + removeListener(event: string | symbol, listener: Function): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + eventNames(): (string | symbol)[]; + listenerCount(type: string | symbol): number; + } } declare module "http" { - import events = require("events"); - import net = require("net"); - import stream = require("stream"); + import * as events from "events"; + import * as net from "net"; + import * as stream from "stream"; - export interface Server extends events.EventEmitter { - listen(port: number, hostname?: string, backlog?: number, callback?: Function): Server; - listen(path: string, callback?: Function): Server; - listen(handle: any, listeningListener?: Function): Server; - close(cb?: any): Server; - address(): { port: number; family: string; address: string; }; + export interface RequestOptions { + protocol?: string; + host?: string; + hostname?: string; + family?: number; + port?: number; + localAddress?: string; + socketPath?: string; + method?: string; + path?: string; + headers?: { [key: string]: any }; + auth?: string; + agent?: Agent | boolean; + } + + export interface Server extends net.Server { + setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; + timeout: number; + listening: boolean; } - export interface ServerRequest extends events.EventEmitter, stream.Readable { - method: string; - url: string; - headers: any; - trailers: string; - httpVersion: string; - setEncoding(encoding?: string): void; - pause(): void; - resume(): void; + /** + * @deprecated Use IncomingMessage + */ + export interface ServerRequest extends IncomingMessage { connection: net.Socket; } - export interface ServerResponse extends events.EventEmitter, stream.Writable { + export interface ServerResponse extends stream.Writable { // Extended base methods write(buffer: Buffer): boolean; write(buffer: Buffer, cb?: Function): boolean; @@ -305,12 +613,16 @@ declare module "http" { writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; writeHead(statusCode: number, headers?: any): void; statusCode: number; - setHeader(name: string, value: string): void; + statusMessage: string; + headersSent: boolean; + setHeader(name: string, value: string | string[]): void; + setTimeout(msecs: number, callback: Function): ServerResponse; sendDate: boolean; getHeader(name: string): string; removeHeader(name: string): void; write(chunk: any, encoding?: string): any; addTrailers(headers: any): void; + finished: boolean; // Extended base methods end(): void; @@ -319,7 +631,7 @@ declare module "http" { end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; } - export interface ClientRequest extends events.EventEmitter, stream.Writable { + export interface ClientRequest extends stream.Writable { // Extended base methods write(buffer: Buffer): boolean; write(buffer: Buffer, cb?: Function): boolean; @@ -333,6 +645,11 @@ declare module "http" { setNoDelay(noDelay?: boolean): void; setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + setHeader(name: string, value: string | string[]): void; + getHeader(name: string): string; + removeHeader(name: string): void; + addTrailers(headers: any): void; + // Extended base methods end(): void; end(buffer: Buffer, cb?: Function): void; @@ -340,70 +657,356 @@ declare module "http" { end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; } - export interface ClientResponse extends events.EventEmitter, stream.Readable { - statusCode: number; + export interface IncomingMessage extends stream.Readable { httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + connection: net.Socket; headers: any; + rawHeaders: string[]; trailers: any; - setEncoding(encoding?: string): void; - pause(): void; - resume(): void; + rawTrailers: any; + setTimeout(msecs: number, callback: Function): NodeJS.Timer; + /** + * Only valid for request obtained from http.Server. + */ + method?: string; + /** + * Only valid for request obtained from http.Server. + */ + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: net.Socket; + destroy(error?: Error): void; + } + /** + * @deprecated Use IncomingMessage + */ + export interface ClientResponse extends IncomingMessage { } + + export interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + } + + export class Agent { + maxSockets: number; + sockets: any; + requests: any; + + constructor(opts?: AgentOptions); + + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; } - export interface Agent { maxSockets: number; sockets: any; requests: any; } + + export var METHODS: string[]; export var STATUS_CODES: { [errorCode: number]: string; [errorCode: string]: string; }; - export function createServer(requestListener?: (request: ServerRequest, response: ServerResponse) =>void ): Server; + export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; export function createClient(port?: number, host?: string): any; - export function request(options: any, callback?: Function): ClientRequest; - export function get(options: any, callback?: Function): ClientRequest; + export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; export var globalAgent: Agent; } declare module "cluster" { - import child = require("child_process"); - import events = require("events"); + import * as child from "child_process"; + import * as events from "events"; + import * as net from "net"; + // interfaces export interface ClusterSettings { + execArgv?: string[]; // default: process.execArgv exec?: string; args?: string[]; silent?: boolean; + stdio?: any[]; + uid?: number; + gid?: number; + } + + export interface ClusterSetupMasterSettings { + exec?: string; // default: process.argv[1] + args?: string[]; // default: process.argv.slice(2) + silent?: boolean; // default: false + stdio?: any[]; + } + + export interface Address { + address: string; + port: number; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" } export class Worker extends events.EventEmitter { id: string; process: child.ChildProcess; suicide: boolean; - send(message: any, sendHandle?: any): void; + send(message: any, sendHandle?: any): boolean; kill(signal?: string): void; destroy(signal?: string): void; disconnect(): void; + isConnected(): boolean; + isDead(): boolean; + exitedAfterDisconnect: boolean; + + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: Function): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (code: number, signal: string) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + + emit(event: string, listener: Function): boolean + emit(event: "disconnect", listener: () => void): boolean + emit(event: "error", listener: (code: number, signal: string) => void): boolean + emit(event: "exit", listener: (code: number, signal: string) => void): boolean + emit(event: "listening", listener: (address: Address) => void): boolean + emit(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): boolean + emit(event: "online", listener: () => void): boolean + + on(event: string, listener: Function): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (code: number, signal: string) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (code: number, signal: string) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (code: number, signal: string) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; } - export var settings: ClusterSettings; + export interface Cluster extends events.EventEmitter { + Worker: Worker; + disconnect(callback?: Function): void; + fork(env?: any): Worker; + isMaster: boolean; + isWorker: boolean; + // TODO: cluster.schedulingPolicy + settings: ClusterSettings; + setupMaster(settings?: ClusterSetupMasterSettings): void; + worker: Worker; + workers: { + [index: string]: Worker + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: Function): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: any) => void): this; + + emit(event: string, listener: Function): boolean; + emit(event: "disconnect", listener: (worker: Worker) => void): boolean; + emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; + emit(event: "fork", listener: (worker: Worker) => void): boolean; + emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; + emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; + emit(event: "online", listener: (worker: Worker) => void): boolean; + emit(event: "setup", listener: (settings: any) => void): boolean; + + on(event: string, listener: Function): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: any) => void): this; + + once(event: string, listener: Function): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: any) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: any) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: any) => void): this; + + } + + export function disconnect(callback?: Function): void; + export function fork(env?: any): Worker; export var isMaster: boolean; export var isWorker: boolean; - export function setupMaster(settings?: ClusterSettings): void; - export function fork(env?: any): Worker; - export function disconnect(callback?: Function): void; + // TODO: cluster.schedulingPolicy + export var settings: ClusterSettings; + export function setupMaster(settings?: ClusterSetupMasterSettings): void; export var worker: Worker; - export var workers: Worker[]; - - // Event emitter - export function addListener(event: string, listener: Function): void; - export function on(event: string, listener: Function): any; - export function once(event: string, listener: Function): void; - export function removeListener(event: string, listener: Function): void; - export function removeAllListeners(event?: string): void; - export function setMaxListeners(n: number): void; + export var workers: { + [index: string]: Worker + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + export function addListener(event: string, listener: Function): Cluster; + export function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function addListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function emit(event: string, listener: Function): boolean; + export function emit(event: "disconnect", listener: (worker: Worker) => void): boolean; + export function emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; + export function emit(event: "fork", listener: (worker: Worker) => void): boolean; + export function emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; + export function emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; + export function emit(event: "online", listener: (worker: Worker) => void): boolean; + export function emit(event: "setup", listener: (settings: any) => void): boolean; + + export function on(event: string, listener: Function): Cluster; + export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function on(event: "fork", listener: (worker: Worker) => void): Cluster; + export function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function on(event: "online", listener: (worker: Worker) => void): Cluster; + export function on(event: "setup", listener: (settings: any) => void): Cluster; + + export function once(event: string, listener: Function): Cluster; + export function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function once(event: "fork", listener: (worker: Worker) => void): Cluster; + export function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function once(event: "online", listener: (worker: Worker) => void): Cluster; + export function once(event: "setup", listener: (settings: any) => void): Cluster; + + export function removeListener(event: string, listener: Function): Cluster; + export function removeAllListeners(event?: string): Cluster; + export function setMaxListeners(n: number): Cluster; + export function getMaxListeners(): number; export function listeners(event: string): Function[]; - export function emit(event: string, ...args: any[]): boolean; + export function listenerCount(type: string): number; + + export function prependListener(event: string, listener: Function): Cluster; + export function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function prependOnceListener(event: string, listener: Function): Cluster; + export function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function eventNames(): string[]; } declare module "zlib" { - import stream = require("stream"); + import * as stream from "stream"; export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } export interface Gzip extends stream.Transform { } @@ -422,13 +1025,20 @@ declare module "zlib" { export function createInflateRaw(options?: ZlibOptions): InflateRaw; export function createUnzip(options?: ZlibOptions): Unzip; - export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; - export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflate(buf: Buffer, callback: (error: Error, result: any) => void): void; + export function deflateSync(buf: Buffer, options?: ZlibOptions): any; + export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) => void): void; + export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any; + export function gzip(buf: Buffer, callback: (error: Error, result: any) => void): void; + export function gzipSync(buf: Buffer, options?: ZlibOptions): any; + export function gunzip(buf: Buffer, callback: (error: Error, result: any) => void): void; + export function gunzipSync(buf: Buffer, options?: ZlibOptions): any; + export function inflate(buf: Buffer, callback: (error: Error, result: any) => void): void; + export function inflateSync(buf: Buffer, options?: ZlibOptions): any; + export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) => void): void; + export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any; + export function unzip(buf: Buffer, callback: (error: Error, result: any) => void): void; + export function unzipSync(buf: Buffer, options?: ZlibOptions): any; // Constants export var Z_NO_FLUSH: number; @@ -465,25 +1075,168 @@ declare module "zlib" { } declare module "os" { - export function tmpdir(): string; + export interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + + export interface NetworkInterfaceInfo { + address: string; + netmask: string; + family: string; + mac: string; + internal: boolean; + } + export function hostname(): string; - export function type(): string; - export function platform(): string; - export function arch(): string; - export function release(): string; - export function uptime(): number; export function loadavg(): number[]; - export function totalmem(): number; + export function uptime(): number; export function freemem(): number; - export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[]; - export function networkInterfaces(): any; + export function totalmem(): number; + export function cpus(): CpuInfo[]; + export function type(): string; + export function release(): string; + export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; + export function homedir(): string; + export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string } + export var constants: { + UV_UDP_REUSEADDR: number, + errno: { + SIGHUP: number; + SIGINT: number; + SIGQUIT: number; + SIGILL: number; + SIGTRAP: number; + SIGABRT: number; + SIGIOT: number; + SIGBUS: number; + SIGFPE: number; + SIGKILL: number; + SIGUSR1: number; + SIGSEGV: number; + SIGUSR2: number; + SIGPIPE: number; + SIGALRM: number; + SIGTERM: number; + SIGCHLD: number; + SIGSTKFLT: number; + SIGCONT: number; + SIGSTOP: number; + SIGTSTP: number; + SIGTTIN: number; + SIGTTOU: number; + SIGURG: number; + SIGXCPU: number; + SIGXFSZ: number; + SIGVTALRM: number; + SIGPROF: number; + SIGWINCH: number; + SIGIO: number; + SIGPOLL: number; + SIGPWR: number; + SIGSYS: number; + SIGUNUSED: number; + }, + signals: { + E2BIG: number; + EACCES: number; + EADDRINUSE: number; + EADDRNOTAVAIL: number; + EAFNOSUPPORT: number; + EAGAIN: number; + EALREADY: number; + EBADF: number; + EBADMSG: number; + EBUSY: number; + ECANCELED: number; + ECHILD: number; + ECONNABORTED: number; + ECONNREFUSED: number; + ECONNRESET: number; + EDEADLK: number; + EDESTADDRREQ: number; + EDOM: number; + EDQUOT: number; + EEXIST: number; + EFAULT: number; + EFBIG: number; + EHOSTUNREACH: number; + EIDRM: number; + EILSEQ: number; + EINPROGRESS: number; + EINTR: number; + EINVAL: number; + EIO: number; + EISCONN: number; + EISDIR: number; + ELOOP: number; + EMFILE: number; + EMLINK: number; + EMSGSIZE: number; + EMULTIHOP: number; + ENAMETOOLONG: number; + ENETDOWN: number; + ENETRESET: number; + ENETUNREACH: number; + ENFILE: number; + ENOBUFS: number; + ENODATA: number; + ENODEV: number; + ENOENT: number; + ENOEXEC: number; + ENOLCK: number; + ENOLINK: number; + ENOMEM: number; + ENOMSG: number; + ENOPROTOOPT: number; + ENOSPC: number; + ENOSR: number; + ENOSTR: number; + ENOSYS: number; + ENOTCONN: number; + ENOTDIR: number; + ENOTEMPTY: number; + ENOTSOCK: number; + ENOTSUP: number; + ENOTTY: number; + ENXIO: number; + EOPNOTSUPP: number; + EOVERFLOW: number; + EPERM: number; + EPIPE: number; + EPROTO: number; + EPROTONOSUPPORT: number; + EPROTOTYPE: number; + ERANGE: number; + EROFS: number; + ESPIPE: number; + ESRCH: number; + ESTALE: number; + ETIME: number; + ETIMEDOUT: number; + ETXTBSY: number; + EWOULDBLOCK: number; + EXDEV: number; + }, + }; + export function arch(): string; + export function platform(): string; + export function tmpdir(): string; export var EOL: string; + export function endianness(): "BE" | "LE"; } declare module "https" { - import tls = require("tls"); - import events = require("events"); - import http = require("http"); + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; export interface ServerOptions { pfx?: any; @@ -497,18 +1250,10 @@ declare module "https" { requestCert?: boolean; rejectUnauthorized?: boolean; NPNProtocols?: any; - SNICallback?: (servername: string) => any; + SNICallback?: (servername: string, cb: (err: Error, ctx: tls.SecureContext) => any) => any; } - export interface RequestOptions { - host?: string; - hostname?: string; - port?: number; - path?: string; - method?: string; - headers?: any; - auth?: string; - agent?: any; + export interface RequestOptions extends http.RequestOptions { pfx?: any; key?: any; passphrase?: string; @@ -516,20 +1261,30 @@ declare module "https" { ca?: any; ciphers?: string; rejectUnauthorized?: boolean; + secureProtocol?: string; } - export interface Agent { - maxSockets: number; - sockets: any; - requests: any; + export interface Agent extends http.Agent { } + + export interface AgentOptions extends http.AgentOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: string; + rejectUnauthorized?: boolean; + secureProtocol?: string; + maxCachedSessions?: number; } + export var Agent: { - new (options?: RequestOptions): Agent; + new (options?: AgentOptions): Agent; }; export interface Server extends tls.Server { } export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: http.ClientResponse) =>void ): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: http.ClientResponse) =>void ): http.ClientRequest; + export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; export var globalAgent: Agent; } @@ -540,15 +1295,15 @@ declare module "punycode" { export function toASCII(domain: string): string; export var ucs2: ucs2; interface ucs2 { - decode(string: string): string; + decode(string: string): number[]; encode(codePoints: number[]): string; } export var version: any; } declare module "repl" { - import stream = require("stream"); - import events = require("events"); + import * as stream from "stream"; + import * as readline from "readline"; export interface ReplOptions { prompt?: string; @@ -560,115 +1315,278 @@ declare module "repl" { useGlobal?: boolean; ignoreUndefined?: boolean; writer?: Function; + completer?: Function; + replMode?: any; + breakEvalOnSigint?: any; } - export function start(options: ReplOptions): events.EventEmitter; + + export interface REPLServer extends readline.ReadLine { + defineCommand(keyword: string, cmd: Function | { help: string, action: Function }): void; + displayPrompt(preserveCursor?: boolean): void + } + + export function start(options: ReplOptions): REPLServer; } declare module "readline" { - import events = require("events"); - import stream = require("stream"); + import * as events from "events"; + import * as stream from "stream"; + + export interface Key { + sequence?: string; + name?: string; + ctrl?: boolean; + meta?: boolean; + shift?: boolean; + } export interface ReadLine extends events.EventEmitter { - setPrompt(prompt: string, length: number): void; + setPrompt(prompt: string): void; prompt(preserveCursor?: boolean): void; - question(query: string, callback: Function): void; - pause(): void; - resume(): void; + question(query: string, callback: (answer: string) => void): void; + pause(): ReadLine; + resume(): ReadLine; close(): void; - write(data: any, key?: any): void; + write(data: string | Buffer, key?: Key): void; } + + export interface Completer { + (line: string): CompleterResult; + (line: string, callback: (err: any, result: CompleterResult) => void): any; + } + + export interface CompleterResult { + completions: string[]; + line: string; + } + export interface ReadLineOptions { input: NodeJS.ReadableStream; - output: NodeJS.WritableStream; - completer?: Function; + output?: NodeJS.WritableStream; + completer?: Completer; terminal?: boolean; + historySize?: number; } + + export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): ReadLine; export function createInterface(options: ReadLineOptions): ReadLine; + + export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; + export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; + export function clearLine(stream: NodeJS.WritableStream, dir: number): void; + export function clearScreenDown(stream: NodeJS.WritableStream): void; } declare module "vm" { export interface Context { } - export interface Script { - runInThisContext(): void; - runInNewContext(sandbox?: Context): void; - } - export function runInThisContext(code: string, filename?: string): void; - export function runInNewContext(code: string, sandbox?: Context, filename?: string): void; - export function runInContext(code: string, context: Context, filename?: string): void; - export function createContext(initSandbox?: Context): Context; - export function createScript(code: string, filename?: string): Script; + export interface ScriptOptions { + filename?: string; + lineOffset?: number; + columnOffset?: number; + displayErrors?: boolean; + timeout?: number; + cachedData?: Buffer; + produceCachedData?: boolean; + } + export interface RunningScriptOptions { + filename?: string; + lineOffset?: number; + columnOffset?: number; + displayErrors?: boolean; + timeout?: number; + } + export class Script { + constructor(code: string, options?: ScriptOptions); + runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; + runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; + runInThisContext(options?: RunningScriptOptions): any; + } + export function createContext(sandbox?: Context): Context; + export function isContext(sandbox: Context): boolean; + export function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions): any; + export function runInDebugContext(code: string): any; + export function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions): any; + export function runInThisContext(code: string, options?: RunningScriptOptions): any; } declare module "child_process" { - import events = require("events"); - import stream = require("stream"); + import * as events from "events"; + import * as stream from "stream"; export interface ChildProcess extends events.EventEmitter { - stdin: stream.Writable; + stdin: stream.Writable; stdout: stream.Readable; stderr: stream.Readable; + stdio: [stream.Writable, stream.Readable, stream.Readable]; pid: number; kill(signal?: string): void; - send(message: any, sendHandle: any): void; + send(message: any, sendHandle?: any): boolean; + connected: boolean; disconnect(): void; + unref(): void; + ref(): void; } - export function spawn(command: string, args?: string[], options?: { + export interface SpawnOptions { cwd?: string; - stdio?: any; - custom?: any; env?: any; + stdio?: any; detached?: boolean; - }): ChildProcess; - export function exec(command: string, options: { + uid?: number; + gid?: number; + shell?: boolean | string; + } + export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + + export interface ExecOptions { cwd?: string; - stdio?: any; - customFds?: any; env?: any; - encoding?: string; + shell?: string; timeout?: number; maxBuffer?: number; killSignal?: string; - }, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function exec(command: string, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, - callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], - callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], options?: { + uid?: number; + gid?: number; + } + export interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + export interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: string; // specify `null`. + } + export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, options: ExecOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + // usage. child_process.exec("tsc", {encoding: null as string}, (err, stdout, stderr) => {}); + export function exec(command: string, options: ExecOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + + export interface ExecFileOptions { cwd?: string; + env?: any; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + } + export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: string; // specify `null`. + } + export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + // usage. child_process.execFile("file.sh", {encoding: null as string}, (err, stdout, stderr) => {}); + export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + // usage. child_process.execFile("file.sh", ["foo"], {encoding: null as string}, (err, stdout, stderr) => {}); + export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + + export interface ForkOptions { + cwd?: string; + env?: any; + execPath?: string; + execArgv?: string[]; + silent?: boolean; + uid?: number; + gid?: number; + } + export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; + + export interface SpawnSyncOptions { + cwd?: string; + input?: string | Buffer; stdio?: any; - customFds?: any; env?: any; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; encoding?: string; + shell?: boolean | string; + } + export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + export interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding: string; // specify `null`. + } + export interface SpawnSyncReturns { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number; + signal: string; + error: Error; + } + export function spawnSync(command: string): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns; + + export interface ExecSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + shell?: string; + uid?: number; + gid?: number; timeout?: number; - maxBuffer?: string; killSignal?: string; - }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function fork(modulePath: string, args?: string[], options?: { + maxBuffer?: number; + encoding?: string; + } + export interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + export interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding: string; // specify `null`. + } + export function execSync(command: string): Buffer; + export function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; + export function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; + export function execSync(command: string, options?: ExecSyncOptions): Buffer; + + export interface ExecFileSyncOptions { cwd?: string; + input?: string | Buffer; + stdio?: any; env?: any; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; encoding?: string; - }): ChildProcess; + } + export interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + export interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding: string; // specify `null`. + } + export function execFileSync(command: string): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; + export function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithStringEncoding): string; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer; } declare module "url" { export interface Url { - href: string; - protocol: string; - auth: string; - hostname: string; - port: string; - host: string; - pathname: string; - search: string; - query: any; // string | Object - slashes: boolean; - hash?: string; - path?: string; - } - - export interface UrlOptions { + href?: string; protocol?: string; auth?: string; hostname?: string; @@ -676,33 +1594,67 @@ declare module "url" { host?: string; pathname?: string; search?: string; - query?: any; + query?: string | any; + slashes?: boolean; hash?: string; path?: string; } - export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; - export function format(url: UrlOptions): string; + export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; + export function format(url: Url): string; export function resolve(from: string, to: string): string; } declare module "dns" { - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; - export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; + export interface MxRecord { + exchange: string, + priority: number + } + + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; + export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: MxRecord[]) => void): string[]; + export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; + export function setServers(servers: string[]): void; + + //Error codes + export var NODATA: string; + export var FORMERR: string; + export var SERVFAIL: string; + export var NOTFOUND: string; + export var NOTIMP: string; + export var REFUSED: string; + export var BADQUERY: string; + export var BADNAME: string; + export var BADFAMILY: string; + export var BADRESP: string; + export var CONNREFUSED: string; + export var TIMEOUT: string; + export var EOF: string; + export var FILE: string; + export var NOMEM: string; + export var DESTRUCTION: string; + export var BADSTR: string; + export var BADFLAGS: string; + export var NONAME: string; + export var BADHINTS: string; + export var NOTINITIALIZED: string; + export var LOADIPHLPAPI: string; + export var ADDRGETNETWORKPARAMS: string; + export var CANCELLED: string; } declare module "net" { - import stream = require("stream"); + import * as stream from "stream"; + import * as events from "events"; export interface Socket extends stream.Duplex { // Extended base methods @@ -718,8 +1670,8 @@ declare module "net" { setEncoding(encoding?: string): void; write(data: any, encoding?: string, callback?: Function): void; destroy(): void; - pause(): void; - resume(): void; + pause(): Socket; + resume(): Socket; setTimeout(timeout: number, callback?: Function): void; setNoDelay(noDelay?: boolean): void; setKeepAlive(enable?: boolean, initialDelay?: number): void; @@ -728,7 +1680,10 @@ declare module "net" { ref(): void; remoteAddress: string; + remoteFamily: string; remotePort: number; + localAddress: string; + localPort: number; bytesRead: number; bytesWritten: number; @@ -738,27 +1693,158 @@ declare module "net" { end(str: string, cb?: Function): void; end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; + + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: (had_error: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + addListener(event: "timeout", listener: () => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close", had_error: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "timeout"): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: (had_error: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + on(event: "timeout", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: (had_error: boolean) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: (had_error: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; } export var Socket: { new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; }; - export interface Server extends Socket { - listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; + export interface ListenOptions { + port?: number; + host?: string; + backlog?: number; + path?: string; + exclusive?: boolean; + } + + export interface Server extends events.EventEmitter { + listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): Server; + listen(port: number, hostname?: string, listeningListener?: Function): Server; + listen(port: number, backlog?: number, listeningListener?: Function): Server; + listen(port: number, listeningListener?: Function): Server; + listen(path: string, backlog?: number, listeningListener?: Function): Server; listen(path: string, listeningListener?: Function): Server; + listen(handle: any, backlog?: number, listeningListener?: Function): Server; listen(handle: any, listeningListener?: Function): Server; + listen(options: ListenOptions, listeningListener?: Function): Server; close(callback?: Function): Server; address(): { port: number; family: string; address: string; }; + getConnections(cb: (error: Error, count: number) => void): void; + ref(): Server; + unref(): Server; maxConnections: number; connections: number; + + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; } - export function createServer(connectionListener?: (socket: Socket) =>void ): Server; - export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server; - export function connect(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createServer(connectionListener?: (socket: Socket) => void): Server; + export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server; + export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; export function connect(port: number, host?: string, connectionListener?: Function): Socket; export function connect(path: string, connectionListener?: Function): Socket; - export function createConnection(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createConnection(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; export function createConnection(path: string, connectionListener?: Function): Socket; export function isIP(input: string): number; @@ -767,12 +1853,12 @@ declare module "net" { } declare module "dgram" { - import events = require("events"); + import * as events from "events"; interface RemoteInfo { address: string; + family: string; port: number; - size: number; } interface AddressInfo { @@ -781,24 +1867,84 @@ declare module "dgram" { port: number; } - export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + interface BindOptions { + port: number; + address?: string; + exclusive?: boolean; + } - interface Socket extends events.EventEmitter { - send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - bind(port: number, address?: string, callback?: () => void): void; - close(): void; + interface SocketOptions { + type: "udp4" | "udp6"; + reuseAddr?: boolean; + } + + export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + + export interface Socket extends events.EventEmitter { + send(msg: Buffer | String | any[], port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + send(msg: Buffer | String | any[], offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + bind(port?: number, address?: string, callback?: () => void): void; + bind(options: BindOptions, callback?: Function): void; + close(callback?: any): void; address(): AddressInfo; setBroadcast(flag: boolean): void; + setTTL(ttl: number): void; setMulticastTTL(ttl: number): void; setMulticastLoopback(flag: boolean): void; addMembership(multicastAddress: string, multicastInterface?: string): void; dropMembership(multicastAddress: string, multicastInterface?: string): void; + ref(): void; + unref(): void; + + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + **/ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: string, rinfo: AddressInfo): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; } } declare module "fs" { - import stream = require("stream"); - import events = require("events"); + import * as stream from "stream"; + import * as events from "events"; interface Stats { isFile(): boolean; @@ -821,82 +1967,241 @@ declare module "fs" { atime: Date; mtime: Date; ctime: Date; + birthtime: Date; } interface FSWatcher extends events.EventEmitter { close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: Function): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (code: number, signal: string) => void): this; + + on(event: string, listener: Function): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (code: number, signal: string) => void): this; + + once(event: string, listener: Function): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (code: number, signal: string) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (code: number, signal: string) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; } export interface ReadStream extends stream.Readable { close(): void; + destroy(): void; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: Function): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; } + export interface WriteStream extends stream.Writable { close(): void; + bytesWritten: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: Function): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; } + /** + * Asynchronous rename. + * @param oldPath + * @param newPath + * @param callback No arguments other than a possible exception are given to the completion callback. + */ export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /** + * Synchronous rename + * @param oldPath + * @param newPath + */ export function renameSync(oldPath: string, newPath: string): void; - export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncateSync(path: string, len?: number): void; + export function truncate(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncate(path: string | Buffer, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncateSync(path: string | Buffer, len?: number): void; export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function ftruncateSync(fd: number, len?: number): void; - export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chownSync(path: string, uid: number, gid: number): void; + export function chown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chownSync(path: string | Buffer, uid: number, gid: number): void; export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function fchownSync(fd: number, uid: number, gid: number): void; - export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchownSync(path: string, uid: number, gid: number): void; - export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmodSync(path: string, mode: number): void; - export function chmodSync(path: string, mode: string): void; + export function lchown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchownSync(path: string | Buffer, uid: number, gid: number): void; + export function chmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmodSync(path: string | Buffer, mode: number): void; + export function chmodSync(path: string | Buffer, mode: string): void; export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; export function fchmodSync(fd: number, mode: number): void; export function fchmodSync(fd: number, mode: string): void; - export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmodSync(path: string, mode: number): void; - export function lchmodSync(path: string, mode: string): void; - export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function lchmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmodSync(path: string | Buffer, mode: number): void; + export function lchmodSync(path: string | Buffer, mode: string): void; + export function stat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function lstat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function statSync(path: string): Stats; - export function lstatSync(path: string): Stats; + export function statSync(path: string | Buffer): Stats; + export function lstatSync(path: string | Buffer): Stats; export function fstatSync(fd: number): Stats; - export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function linkSync(srcpath: string, dstpath: string): void; - export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; - export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; - export function readlinkSync(path: string): string; - export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; - export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void; - export function realpathSync(path: string, cache?: {[path: string]: string}): string; - export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function unlinkSync(path: string): void; - export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function rmdirSync(path: string): void; - export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function mkdirSync(path: string, mode?: number): void; - export function mkdirSync(path: string, mode?: string): void; - export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; - export function readdirSync(path: string): string[]; + export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function linkSync(srcpath: string | Buffer, dstpath: string | Buffer): void; + export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function symlinkSync(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): void; + export function readlink(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; + export function readlinkSync(path: string | Buffer): string; + export function realpath(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpathSync(path: string | Buffer, cache?: { [path: string]: string }): string; + /* + * Asynchronous unlink - deletes the file specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function unlink(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous unlink - deletes the file specified in {path} + * + * @param path + */ + export function unlinkSync(path: string | Buffer): void; + /* + * Asynchronous rmdir - removes the directory specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function rmdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous rmdir - removes the directory specified in {path} + * + * @param path + */ + export function rmdirSync(path: string | Buffer): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdir(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdir(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdirSync(path: string | Buffer, mode?: number): void; + /* + * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdirSync(path: string | Buffer, mode?: string): void; + /* + * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * @param prefix + * @param callback The created folder path is passed as a string to the callback's second parameter. + */ + export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; + /* + * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * @param prefix + * @returns Returns the created folder path. + */ + export function mkdtempSync(prefix: string): string; + export function readdir(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; + export function readdirSync(path: string | Buffer): string[]; export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function closeSync(fd: number): void; - export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function openSync(path: string, flags: string, mode?: number): number; - export function openSync(path: string, flags: string, mode?: string): number; - export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimesSync(path: string, atime: number, mtime: number): void; - export function utimesSync(path: string, atime: Date, mtime: Date): void; + export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + export function openSync(path: string | Buffer, flags: string | number, mode?: number): number; + export function utimes(path: string | Buffer, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimesSync(path: string | Buffer, atime: number, mtime: number): void; + export function utimesSync(path: string | Buffer, atime: Date, mtime: Date): void; export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; export function futimesSync(fd: number, atime: number, mtime: number): void; @@ -904,15 +2209,65 @@ declare module "fs" { export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function fsyncSync(fd: number): void; export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; - export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + export function write(fd: number, buffer: Buffer, offset: number, length: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function write(fd: number, data: any, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function write(fd: number, data: any, offset: number, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number; + export function writeSync(fd: number, data: any, position?: number, enconding?: string): number; export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param encoding + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void ): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param encoding + */ export function readFileSync(filename: string, encoding: string): string; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. + */ export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. + */ export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; @@ -928,95 +2283,607 @@ declare module "fs" { export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; - export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; - export function exists(path: string, callback?: (exists: boolean) => void): void; - export function existsSync(path: string): boolean; - export function createReadStream(path: string, options?: { + export function watch(filename: string, encoding: string, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; + export function watch(filename: string, options: { persistent?: boolean; recursive?: boolean; encoding?: string }, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; + export function exists(path: string | Buffer, callback?: (exists: boolean) => void): void; + export function existsSync(path: string | Buffer): boolean; + + export namespace constants { + // File Access Constants + + /** Constant for fs.access(). File is visible to the calling process. */ + export const F_OK: number; + + /** Constant for fs.access(). File can be read by the calling process. */ + export const R_OK: number; + + /** Constant for fs.access(). File can be written by the calling process. */ + export const W_OK: number; + + /** Constant for fs.access(). File can be executed by the calling process. */ + export const X_OK: number; + + // File Open Constants + + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + export const O_RDONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + export const O_WRONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + export const O_RDWR: number; + + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + export const O_CREAT: number; + + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + export const O_EXCL: number; + + /** Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one). */ + export const O_NOCTTY: number; + + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + export const O_TRUNC: number; + + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + export const O_APPEND: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + export const O_DIRECTORY: number; + + /** Constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only. */ + export const O_NOATIME: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + export const O_NOFOLLOW: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + export const O_SYNC: number; + + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + export const O_SYMLINK: number; + + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + export const O_DIRECT: number; + + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + export const O_NONBLOCK: number; + + // File Type Constants + + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + export const S_IFMT: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + export const S_IFREG: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + export const S_IFDIR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + export const S_IFCHR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + export const S_IFBLK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + export const S_IFIFO: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + export const S_IFLNK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + export const S_IFSOCK: number; + + // File Mode Constants + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + export const S_IRWXU: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + export const S_IRUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + export const S_IWUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + export const S_IXUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + export const S_IRWXG: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + export const S_IRGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + export const S_IWGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + export const S_IXGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + export const S_IRWXO: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + export const S_IROTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + export const S_IWOTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + export const S_IXOTH: number; + } + + /** Tests a user's permissions for the file specified by path. */ + export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; + export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; + /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ + export function accessSync(path: string | Buffer, mode?: number): void; + export function createReadStream(path: string | Buffer, options?: { flags?: string; encoding?: string; - fd?: string; + fd?: number; mode?: number; - bufferSize?: number; + autoClose?: boolean; + start?: number; + end?: number; }): ReadStream; - export function createReadStream(path: string, options?: { + export function createWriteStream(path: string | Buffer, options?: { flags?: string; encoding?: string; - fd?: string; - mode?: string; - bufferSize?: number; - }): ReadStream; - export function createWriteStream(path: string, options?: { - flags?: string; - encoding?: string; - string?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; }): WriteStream; + export function fdatasync(fd: number, callback: Function): void; + export function fdatasyncSync(fd: number): void; } declare module "path" { + + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + export interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ export function normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths string paths to join. + */ export function join(...paths: any[]): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths string paths to join. + */ + export function join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ export function resolve(...pathSegments: any[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + export function isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @param from + * @param to + */ export function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ export function dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ export function basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ export function extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ export var sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + export var delimiter: string; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + export function parse(pathString: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + export function format(pathObject: ParsedPath): string; + + export module posix { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } + + export module win32 { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } } declare module "string_decoder" { export interface NodeStringDecoder { write(buffer: Buffer): string; - detectIncompleteChar(buffer: Buffer): number; + end(buffer?: Buffer): string; } export var StringDecoder: { - new (encoding: string): NodeStringDecoder; + new (encoding?: string): NodeStringDecoder; }; } declare module "tls" { - import crypto = require("crypto"); - import net = require("net"); - import stream = require("stream"); + import * as crypto from "crypto"; + import * as net from "net"; + import * as stream from "stream"; var CLIENT_RENEG_LIMIT: number; var CLIENT_RENEG_WINDOW: number; + export interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + + export interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + } + + export class TLSSocket extends stream.Duplex { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket:net.Socket, options?: { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext, + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean, + /** + * An optional net.Server instance. + */ + server?: net.Server, + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean, + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. Defaults to false. + */ + rejectUnauthorized?: boolean, + /** + * An array of strings or a Buffer naming possible NPN protocols. + * (Protocols should be ordered by their priority.) + */ + NPNProtocols?: string[] | Buffer, + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) When the server + * receives both NPN and ALPN extensions from the client, ALPN takes + * precedence over NPN and the server does not send an NPN extension + * to the client. + */ + ALPNProtocols?: string[] | Buffer, + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: Function, + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer, + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean + }); + /** + * Returns the bound address, the address family name and port of the underlying socket as reported by + * the operating system. + * @returns {any} - An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. + */ + address(): { port: number; family: string; address: string }; + /** + * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. + */ + authorized: boolean; + /** + * The reason why the peer's certificate has not been verified. + * This property becomes available only when tlsSocket.authorized === false. + */ + authorizationError: Error; + /** + * Static boolean value, always true. + * May be used to distinguish TLS sockets from regular ones. + */ + encrypted: boolean; + /** + * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. + * @returns {CipherNameAndProtocol} - Returns an object representing the cipher name + * and the SSL/TLS protocol version of the current connection. + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the peer's certificate. + * The returned object has some properties corresponding to the field of the certificate. + * If detailed argument is true the full chain with issuer property will be returned, + * if false only the top certificate without issuer property. + * If the peer does not provide a certificate, it returns null or an empty object. + * @param {boolean} detailed - If true; the full chain with issuer property will be returned. + * @returns {any} - An object representing the peer's certificate. + */ + getPeerCertificate(detailed?: boolean): { + subject: Certificate; + issuerInfo: Certificate; + issuer: Certificate; + raw: any; + valid_from: string; + valid_to: string; + fingerprint: string; + serialNumber: string; + }; + /** + * Could be used to speed up handshake establishment when reconnecting to the server. + * @returns {any} - ASN.1 encoded TLS session or undefined if none was negotiated. + */ + getSession(): any; + /** + * NOTE: Works only with client TLS sockets. + * Useful only for debugging, for session reuse provide session option to tls.connect(). + * @returns {any} - TLS session ticket or undefined if none was negotiated. + */ + getTLSTicket(): any; + /** + * The string representation of the local IP address. + */ + localAddress: string; + /** + * The numeric representation of the local port. + */ + localPort: string; + /** + * The string representation of the remote IP address. + * For example, '74.125.127.100' or '2001:4860:a005::68'. + */ + remoteAddress: string; + /** + * The string representation of the remote IP family. 'IPv4' or 'IPv6'. + */ + remoteFamily: string; + /** + * The numeric representation of the remote port. For example, 443. + */ + remotePort: number; + /** + * Initiate TLS renegotiation process. + * + * NOTE: Can be used to request peer's certificate after the secure connection has been established. + * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. + * @param {TlsOptions} options - The options may contain the following fields: rejectUnauthorized, + * requestCert (See tls.createServer() for details). + * @param {Function} callback - callback(err) will be executed with null as err, once the renegotiation + * is successfully completed. + */ + renegotiate(options: TlsOptions, callback: (err: Error) => any): any; + /** + * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by + * the TLS layer until the entire fragment is received and its integrity is verified; + * large fragments can span multiple roundtrips, and their processing can be delayed due to packet + * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, + * which may decrease overall server throughput. + * @param {number} size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns {boolean} - Returns true on success, false otherwise. + */ + setMaxSendFragment(size: number): boolean; + + /** + * events.EventEmitter + * 1. OCSPResponse + * 2. secureConnect + **/ + addListener(event: string, listener: Function): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + + on(event: string, listener: Function): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + } + export interface TlsOptions { - pfx?: any; //string or buffer - key?: any; //string or buffer + host?: string; + port?: number; + pfx?: string | Buffer[]; + key?: string | string[] | Buffer | any[]; passphrase?: string; - cert?: any; - ca?: any; //string or buffer - crl?: any; //string or string array + cert?: string | string[] | Buffer | Buffer[]; + ca?: string | string[] | Buffer | Buffer[]; + crl?: string | string[]; ciphers?: string; - honorCipherOrder?: any; + honorCipherOrder?: boolean; requestCert?: boolean; rejectUnauthorized?: boolean; - NPNProtocols?: any; //array or Buffer; - SNICallback?: (servername: string) => any; + NPNProtocols?: string[] | Buffer; + SNICallback?: (servername: string, cb: (err: Error, ctx: SecureContext) => any) => any; + ecdhCurve?: string; + dhparam?: string | Buffer; + handshakeTimeout?: number; + ALPNProtocols?: string[] | Buffer; + sessionTimeout?: number; + ticketKeys?: any; + sessionIdContext?: string; + secureProtocol?: string; } export interface ConnectionOptions { host?: string; port?: number; socket?: net.Socket; - pfx?: any; //string | Buffer - key?: any; //string | Buffer + pfx?: string | Buffer + key?: string | string[] | Buffer | Buffer[]; passphrase?: string; - cert?: any; //string | Buffer - ca?: any; //Array of string | Buffer + cert?: string | string[] | Buffer | Buffer[]; + ca?: string | Buffer | (string | Buffer)[]; rejectUnauthorized?: boolean; - NPNProtocols?: any; //Array of string | Buffer + NPNProtocols?: (string | Buffer)[]; servername?: string; + path?: string; + ALPNProtocols?: (string | Buffer)[]; + checkServerIdentity?: (servername: string, cert: string | Buffer | (string | Buffer)[]) => any; + secureProtocol?: string; + secureContext?: Object; + session?: Buffer; + minDHSize?: number; } export interface Server extends net.Server { - // Extended base methods - listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; - listen(path: string, listeningListener?: Function): Server; - listen(handle: any, listeningListener?: Function): Server; - - listen(port: number, host?: string, callback?: Function): Server; close(): Server; address(): { port: number; family: string; address: string; }; addContext(hostName: string, credentials: { @@ -1026,6 +2893,56 @@ declare module "tls" { }): void; maxConnections: number; connections: number; + + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + **/ + addListener(event: string, listener: Function): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + addListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: Function): boolean; + emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + + on(event: string, listener: Function): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + once(event: string, listener: Function): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependOnceListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; } export interface ClearTextStream extends stream.Duplex { @@ -1050,186 +2967,412 @@ declare module "tls" { cleartext: any; } - export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server; - export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream; - export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; - export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; + export interface SecureContextOptions { + pfx?: string | Buffer; + key?: string | Buffer; + passphrase?: string; + cert?: string | Buffer; + ca?: string | Buffer; + crl?: string | string[] + ciphers?: string; + honorCipherOrder?: boolean; + } + + export interface SecureContext { + context: any; + } + + export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) => void): Server; + export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): ClearTextStream; + export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; + export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + export function createSecureContext(details: SecureContextOptions): SecureContext; } declare module "crypto" { + export interface Certificate { + exportChallenge(spkac: string | Buffer): Buffer; + exportPublicKey(spkac: string | Buffer): Buffer; + verifySpkac(spkac: Buffer): boolean; + } + export var Certificate: { + new (): Certificate; + (): Certificate; + } + + export var fips: boolean; + export interface CredentialDetails { pfx: string; key: string; passphrase: string; cert: string; - ca: any; //string | string array - crl: any; //string | string array + ca: string | string[]; + crl: string | string[]; ciphers: string; } export interface Credentials { context?: any; } export function createCredentials(details: CredentialDetails): Credentials; export function createHash(algorithm: string): Hash; - export function createHmac(algorithm: string, key: string): Hmac; - export function createHmac(algorithm: string, key: Buffer): Hmac; - interface Hash { - update(data: any, input_encoding?: string): Hash; - digest(encoding: 'buffer'): Buffer; - digest(encoding: string): any; + export function createHmac(algorithm: string, key: string | Buffer): Hmac; + + type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; + type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; + type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; + type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + + export interface Hash extends NodeJS.ReadWriteStream { + update(data: string | Buffer): Hash; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hash; digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; } - interface Hmac { - update(data: any, input_encoding?: string): Hmac; - digest(encoding: 'buffer'): Buffer; - digest(encoding: string): any; + export interface Hmac extends NodeJS.ReadWriteStream { + update(data: string | Buffer): Hmac; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hmac; digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; } export function createCipher(algorithm: string, password: any): Cipher; export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; - interface Cipher { + export interface Cipher extends NodeJS.ReadWriteStream { update(data: Buffer): Buffer; - update(data: string, input_encoding?: string, output_encoding?: string): string; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; final(): Buffer; final(output_encoding: string): string; - setAutoPadding(auto_padding: boolean): void; + setAutoPadding(auto_padding?: boolean): void; + getAuthTag(): Buffer; + setAAD(buffer: Buffer): void; } export function createDecipher(algorithm: string, password: any): Decipher; export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; - interface Decipher { + export interface Decipher extends NodeJS.ReadWriteStream { update(data: Buffer): Buffer; - update(data: string, input_encoding?: string, output_encoding?: string): string; + update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; + update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; final(): Buffer; final(output_encoding: string): string; - setAutoPadding(auto_padding: boolean): void; + setAutoPadding(auto_padding?: boolean): void; + setAuthTag(tag: Buffer): void; + setAAD(buffer: Buffer): void; } export function createSign(algorithm: string): Signer; - interface Signer { - update(data: any): void; - sign(private_key: string, output_format: string): string; + export interface Signer extends NodeJS.WritableStream { + update(data: string | Buffer): Signer; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Signer; + sign(private_key: string | { key: string; passphrase: string }): Buffer; + sign(private_key: string | { key: string; passphrase: string }, output_format: HexBase64Latin1Encoding): string; } export function createVerify(algorith: string): Verify; - interface Verify { - update(data: any): void; - verify(object: string, signature: string, signature_format?: string): boolean; - } - export function createDiffieHellman(prime_length: number): DiffieHellman; - export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; - interface DiffieHellman { - generateKeys(encoding?: string): string; - computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; - getPrime(encoding?: string): string; - getGenerator(encoding: string): string; - getPublicKey(encoding?: string): string; - getPrivateKey(encoding?: string): string; - setPublicKey(public_key: string, encoding?: string): void; - setPrivateKey(public_key: string, encoding?: string): void; + export interface Verify extends NodeJS.WritableStream { + update(data: string | Buffer): Verify; + update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Verify; + verify(object: string, signature: Buffer): boolean; + verify(object: string, signature: string, signature_format: HexBase64Latin1Encoding): boolean; + } + export function createDiffieHellman(prime_length: number, generator?: number): DiffieHellman; + export function createDiffieHellman(prime: Buffer): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Buffer): DiffieHellman; + export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; + export interface DiffieHellman { + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: Buffer): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrime(): Buffer; + getPrime(encoding: HexBase64Latin1Encoding): string; + getGenerator(): Buffer; + getGenerator(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + setPublicKey(public_key: Buffer): void; + setPublicKey(public_key: string, encoding: string): void; + setPrivateKey(private_key: Buffer): void; + setPrivateKey(private_key: string, encoding: string): void; + verifyError: number; } export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer; + export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer; export function randomBytes(size: number): Buffer; - export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; + export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; export function pseudoRandomBytes(size: number): Buffer; - export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; + export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; + export interface RsaPublicKey { + key: string; + padding?: number; + } + export interface RsaPrivateKey { + key: string; + passphrase?: string, + padding?: number; + } + export function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer + export function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer + export function privateEncrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer + export function publicDecrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer + export function getCiphers(): string[]; + export function getCurves(): string[]; + export function getHashes(): string[]; + export interface ECDH { + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding): string; + generateKeys(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; + computeSecret(other_public_key: Buffer): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding): string; + getPublicKey(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; + setPrivateKey(private_key: Buffer): void; + setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; + } + export function createECDH(curve_name: string): ECDH; + export function timingSafeEqual(a: Buffer, b: Buffer): boolean; + export var DEFAULT_ENCODING: string; } declare module "stream" { - import events = require("events"); + import * as events from "events"; - export interface Stream extends events.EventEmitter { + class internal extends events.EventEmitter { pipe(destination: T, options?: { end?: boolean; }): T; } + namespace internal { - export interface ReadableOptions { - highWaterMark?: number; - encoding?: string; - objectMode?: boolean; - } + export class Stream extends internal { } - export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { - readable: boolean; - constructor(opts?: ReadableOptions); - _read(size: number): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - } + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?: (size?: number) => any; + } - export interface WritableOptions { - highWaterMark?: number; - decodeStrings?: boolean; - } + export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { + readable: boolean; + constructor(opts?: ReadableOptions); + protected _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): Readable; + resume(): Readable; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. readable + * 5. error + **/ + addListener(event: string, listener: Function): this; + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + + removeListener(event: string, listener: Function): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + } - export class Writable extends events.EventEmitter implements NodeJS.WritableStream { - writable: boolean; - constructor(opts?: WritableOptions); - _write(data: Buffer, encoding: string, callback: Function): void; - _write(data: string, encoding: string, callback: Function): void; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; + writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; + } - export interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean; - } + export class Writable extends events.EventEmitter implements NodeJS.WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + protected _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + **/ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "drain", chunk: Buffer | string): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + + removeListener(event: string, listener: Function): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + } - // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements NodeJS.ReadWriteStream { - writable: boolean; - constructor(opts?: DuplexOptions); - _write(data: Buffer, encoding: string, callback: Function): void; - _write(data: string, encoding: string, callback: Function): void; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - } + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writableObjectMode?: boolean; + } - export interface TransformOptions extends ReadableOptions, WritableOptions {} + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements NodeJS.ReadWriteStream { + // Readable + pause(): Duplex; + resume(): Duplex; + // Writeable + writable: boolean; + constructor(opts?: DuplexOptions); + protected _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } - // Note: Transform lacks the _read and _write methods of Readable/Writable. - export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { - readable: boolean; - writable: boolean; - constructor(opts?: TransformOptions); - _transform(chunk: Buffer, encoding: string, callback: Function): void; - _transform(chunk: string, encoding: string, callback: Function): void; - _flush(callback: Function): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: string): void; - unshift(chunk: Buffer): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; + export interface TransformOptions extends DuplexOptions { + transform?: (chunk: string | Buffer, encoding: string, callback: Function) => any; + flush?: (callback: Function) => any; + } + + // Note: Transform lacks the _read and _write methods of Readable/Writable. + export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { + readable: boolean; + writable: boolean; + constructor(opts?: TransformOptions); + protected _transform(chunk: any, encoding: string, callback: Function): void; + protected _flush(callback: Function): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): Transform; + resume(): Transform; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export class PassThrough extends Transform { } } - export class PassThrough extends Transform {} + export = internal; } declare module "util" { @@ -1253,11 +3396,24 @@ declare module "util" { export function isDate(object: any): boolean; export function isError(object: any): boolean; export function inherits(constructor: any, superConstructor: any): void; + export function debuglog(key: string): (msg: string, ...param: any[]) => void; + export function isBoolean(object: any): boolean; + export function isBuffer(object: any): boolean; + export function isFunction(object: any): boolean; + export function isNull(object: any): boolean; + export function isNullOrUndefined(object: any): boolean; + export function isNumber(object: any): boolean; + export function isObject(object: any): boolean; + export function isPrimitive(object: any): boolean; + export function isString(object: any): boolean; + export function isSymbol(object: any): boolean; + export function isUndefined(object: any): boolean; + export function deprecate(fn: Function, message: string): Function; } declare module "assert" { - function internal (value: any, message?: string): void; - module internal { + function internal(value: any, message?: string): void; + namespace internal { export class AssertionError implements Error { name: string; message: string; @@ -1266,11 +3422,13 @@ declare module "assert" { operator: string; generatedMessage: boolean; - constructor(options?: {message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function}); + constructor(options?: { + message?: string; actual?: any; expected?: any; + operator?: string; stackStartFunction?: Function + }); } - export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; + export function fail(actual: any, expected: any, message: string, operator: string): void; export function ok(value: any, message?: string): void; export function equal(actual: any, expected: any, message?: string): void; export function notEqual(actual: any, expected: any, message?: string): void; @@ -1278,6 +3436,8 @@ declare module "assert" { export function notDeepEqual(acutal: any, expected: any, message?: string): void; export function strictEqual(actual: any, expected: any, message?: string): void; export function notStrictEqual(actual: any, expected: any, message?: string): void; + export function deepStrictEqual(actual: any, expected: any, message?: string): void; + export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; export var throws: { (block: Function, message?: string): void; (block: Function, error: Function, message?: string): void; @@ -1299,36 +3459,341 @@ declare module "assert" { } declare module "tty" { - import net = require("net"); + import * as net from "net"; export function isatty(fd: number): boolean; export interface ReadStream extends net.Socket { isRaw: boolean; setRawMode(mode: boolean): void; + isTTY: boolean; } export interface WriteStream extends net.Socket { columns: number; rows: number; + isTTY: boolean; } } declare module "domain" { - import events = require("events"); + import * as events from "events"; - export class Domain extends events.EventEmitter { + export class Domain extends events.EventEmitter implements NodeJS.Domain { run(fn: Function): void; add(emitter: events.EventEmitter): void; remove(emitter: events.EventEmitter): void; bind(cb: (err: Error, data: any) => any): any; intercept(cb: (data: any) => any): any; dispose(): void; - - addListener(event: string, listener: Function): Domain; - on(event: string, listener: Function): Domain; - once(event: string, listener: Function): Domain; - removeListener(event: string, listener: Function): Domain; - removeAllListeners(event?: string): Domain; + members: any[]; + enter(): void; + exit(): void; } export function create(): Domain; } + +declare module "constants" { + export var E2BIG: number; + export var EACCES: number; + export var EADDRINUSE: number; + export var EADDRNOTAVAIL: number; + export var EAFNOSUPPORT: number; + export var EAGAIN: number; + export var EALREADY: number; + export var EBADF: number; + export var EBADMSG: number; + export var EBUSY: number; + export var ECANCELED: number; + export var ECHILD: number; + export var ECONNABORTED: number; + export var ECONNREFUSED: number; + export var ECONNRESET: number; + export var EDEADLK: number; + export var EDESTADDRREQ: number; + export var EDOM: number; + export var EEXIST: number; + export var EFAULT: number; + export var EFBIG: number; + export var EHOSTUNREACH: number; + export var EIDRM: number; + export var EILSEQ: number; + export var EINPROGRESS: number; + export var EINTR: number; + export var EINVAL: number; + export var EIO: number; + export var EISCONN: number; + export var EISDIR: number; + export var ELOOP: number; + export var EMFILE: number; + export var EMLINK: number; + export var EMSGSIZE: number; + export var ENAMETOOLONG: number; + export var ENETDOWN: number; + export var ENETRESET: number; + export var ENETUNREACH: number; + export var ENFILE: number; + export var ENOBUFS: number; + export var ENODATA: number; + export var ENODEV: number; + export var ENOENT: number; + export var ENOEXEC: number; + export var ENOLCK: number; + export var ENOLINK: number; + export var ENOMEM: number; + export var ENOMSG: number; + export var ENOPROTOOPT: number; + export var ENOSPC: number; + export var ENOSR: number; + export var ENOSTR: number; + export var ENOSYS: number; + export var ENOTCONN: number; + export var ENOTDIR: number; + export var ENOTEMPTY: number; + export var ENOTSOCK: number; + export var ENOTSUP: number; + export var ENOTTY: number; + export var ENXIO: number; + export var EOPNOTSUPP: number; + export var EOVERFLOW: number; + export var EPERM: number; + export var EPIPE: number; + export var EPROTO: number; + export var EPROTONOSUPPORT: number; + export var EPROTOTYPE: number; + export var ERANGE: number; + export var EROFS: number; + export var ESPIPE: number; + export var ESRCH: number; + export var ETIME: number; + export var ETIMEDOUT: number; + export var ETXTBSY: number; + export var EWOULDBLOCK: number; + export var EXDEV: number; + export var WSAEINTR: number; + export var WSAEBADF: number; + export var WSAEACCES: number; + export var WSAEFAULT: number; + export var WSAEINVAL: number; + export var WSAEMFILE: number; + export var WSAEWOULDBLOCK: number; + export var WSAEINPROGRESS: number; + export var WSAEALREADY: number; + export var WSAENOTSOCK: number; + export var WSAEDESTADDRREQ: number; + export var WSAEMSGSIZE: number; + export var WSAEPROTOTYPE: number; + export var WSAENOPROTOOPT: number; + export var WSAEPROTONOSUPPORT: number; + export var WSAESOCKTNOSUPPORT: number; + export var WSAEOPNOTSUPP: number; + export var WSAEPFNOSUPPORT: number; + export var WSAEAFNOSUPPORT: number; + export var WSAEADDRINUSE: number; + export var WSAEADDRNOTAVAIL: number; + export var WSAENETDOWN: number; + export var WSAENETUNREACH: number; + export var WSAENETRESET: number; + export var WSAECONNABORTED: number; + export var WSAECONNRESET: number; + export var WSAENOBUFS: number; + export var WSAEISCONN: number; + export var WSAENOTCONN: number; + export var WSAESHUTDOWN: number; + export var WSAETOOMANYREFS: number; + export var WSAETIMEDOUT: number; + export var WSAECONNREFUSED: number; + export var WSAELOOP: number; + export var WSAENAMETOOLONG: number; + export var WSAEHOSTDOWN: number; + export var WSAEHOSTUNREACH: number; + export var WSAENOTEMPTY: number; + export var WSAEPROCLIM: number; + export var WSAEUSERS: number; + export var WSAEDQUOT: number; + export var WSAESTALE: number; + export var WSAEREMOTE: number; + export var WSASYSNOTREADY: number; + export var WSAVERNOTSUPPORTED: number; + export var WSANOTINITIALISED: number; + export var WSAEDISCON: number; + export var WSAENOMORE: number; + export var WSAECANCELLED: number; + export var WSAEINVALIDPROCTABLE: number; + export var WSAEINVALIDPROVIDER: number; + export var WSAEPROVIDERFAILEDINIT: number; + export var WSASYSCALLFAILURE: number; + export var WSASERVICE_NOT_FOUND: number; + export var WSATYPE_NOT_FOUND: number; + export var WSA_E_NO_MORE: number; + export var WSA_E_CANCELLED: number; + export var WSAEREFUSED: number; + export var SIGHUP: number; + export var SIGINT: number; + export var SIGILL: number; + export var SIGABRT: number; + export var SIGFPE: number; + export var SIGKILL: number; + export var SIGSEGV: number; + export var SIGTERM: number; + export var SIGBREAK: number; + export var SIGWINCH: number; + export var SSL_OP_ALL: number; + export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; + export var SSL_OP_CISCO_ANYCONNECT: number; + export var SSL_OP_COOKIE_EXCHANGE: number; + export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + export var SSL_OP_EPHEMERAL_RSA: number; + export var SSL_OP_LEGACY_SERVER_CONNECT: number; + export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; + export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + export var SSL_OP_NETSCAPE_CA_DN_BUG: number; + export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NO_COMPRESSION: number; + export var SSL_OP_NO_QUERY_MTU: number; + export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + export var SSL_OP_NO_SSLv2: number; + export var SSL_OP_NO_SSLv3: number; + export var SSL_OP_NO_TICKET: number; + export var SSL_OP_NO_TLSv1: number; + export var SSL_OP_NO_TLSv1_1: number; + export var SSL_OP_NO_TLSv1_2: number; + export var SSL_OP_PKCS1_CHECK_1: number; + export var SSL_OP_PKCS1_CHECK_2: number; + export var SSL_OP_SINGLE_DH_USE: number; + export var SSL_OP_SINGLE_ECDH_USE: number; + export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; + export var SSL_OP_TLS_D5_BUG: number; + export var SSL_OP_TLS_ROLLBACK_BUG: number; + export var ENGINE_METHOD_DSA: number; + export var ENGINE_METHOD_DH: number; + export var ENGINE_METHOD_RAND: number; + export var ENGINE_METHOD_ECDH: number; + export var ENGINE_METHOD_ECDSA: number; + export var ENGINE_METHOD_CIPHERS: number; + export var ENGINE_METHOD_DIGESTS: number; + export var ENGINE_METHOD_STORE: number; + export var ENGINE_METHOD_PKEY_METHS: number; + export var ENGINE_METHOD_PKEY_ASN1_METHS: number; + export var ENGINE_METHOD_ALL: number; + export var ENGINE_METHOD_NONE: number; + export var DH_CHECK_P_NOT_SAFE_PRIME: number; + export var DH_CHECK_P_NOT_PRIME: number; + export var DH_UNABLE_TO_CHECK_GENERATOR: number; + export var DH_NOT_SUITABLE_GENERATOR: number; + export var NPN_ENABLED: number; + export var RSA_PKCS1_PADDING: number; + export var RSA_SSLV23_PADDING: number; + export var RSA_NO_PADDING: number; + export var RSA_PKCS1_OAEP_PADDING: number; + export var RSA_X931_PADDING: number; + export var RSA_PKCS1_PSS_PADDING: number; + export var POINT_CONVERSION_COMPRESSED: number; + export var POINT_CONVERSION_UNCOMPRESSED: number; + export var POINT_CONVERSION_HYBRID: number; + export var O_RDONLY: number; + export var O_WRONLY: number; + export var O_RDWR: number; + export var S_IFMT: number; + export var S_IFREG: number; + export var S_IFDIR: number; + export var S_IFCHR: number; + export var S_IFBLK: number; + export var S_IFIFO: number; + export var S_IFSOCK: number; + export var S_IRWXU: number; + export var S_IRUSR: number; + export var S_IWUSR: number; + export var S_IXUSR: number; + export var S_IRWXG: number; + export var S_IRGRP: number; + export var S_IWGRP: number; + export var S_IXGRP: number; + export var S_IRWXO: number; + export var S_IROTH: number; + export var S_IWOTH: number; + export var S_IXOTH: number; + export var S_IFLNK: number; + export var O_CREAT: number; + export var O_EXCL: number; + export var O_NOCTTY: number; + export var O_DIRECTORY: number; + export var O_NOATIME: number; + export var O_NOFOLLOW: number; + export var O_SYNC: number; + export var O_SYMLINK: number; + export var O_DIRECT: number; + export var O_NONBLOCK: number; + export var O_TRUNC: number; + export var O_APPEND: number; + export var F_OK: number; + export var R_OK: number; + export var W_OK: number; + export var X_OK: number; + export var UV_UDP_REUSEADDR: number; + export var SIGQUIT: number; + export var SIGTRAP: number; + export var SIGIOT: number; + export var SIGBUS: number; + export var SIGUSR1: number; + export var SIGUSR2: number; + export var SIGPIPE: number; + export var SIGALRM: number; + export var SIGCHLD: number; + export var SIGSTKFLT: number; + export var SIGCONT: number; + export var SIGSTOP: number; + export var SIGTSTP: number; + export var SIGTTIN: number; + export var SIGTTOU: number; + export var SIGURG: number; + export var SIGXCPU: number; + export var SIGXFSZ: number; + export var SIGVTALRM: number; + export var SIGPROF: number; + export var SIGIO: number; + export var SIGPOLL: number; + export var SIGPWR: number; + export var SIGSYS: number; + export var SIGUNUSED: number; + export var defaultCoreCipherList: string; + export var defaultCipherList: string; + export var ENGINE_METHOD_RSA: number; + export var ALPN_ENABLED: number; +} + +declare module "process" { + export = process; +} + +declare module "v8" { + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + export function getHeapStatistics(): { total_heap_size: number, total_heap_size_executable: number, total_physical_size: number, total_avaialble_size: number, used_heap_size: number, heap_size_limit: number }; + export function getHeapSpaceStatistics(): HeapSpaceInfo[]; + export function setFlagsFromString(flags: string): void; +} + +declare module "timers" { + export function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + export function clearTimeout(timeoutId: NodeJS.Timer): void; + export function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + export function clearInterval(intervalId: NodeJS.Timer): void; + export function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; + export function clearImmediate(immediateId: any): void; +} + +declare module "console" { + export = console; +} \ No newline at end of file From 8baf265d73cbe5d1c137fcda865c96a178351228 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Mon, 24 Oct 2016 20:41:16 +0100 Subject: [PATCH 04/17] added tslint with standard defaults & made code compliant --- package.json | 1 + src/index.ts | 265 ++++++++++++++++++++++------------------------ src/interfaces.ts | 6 ++ src/logger.ts | 8 +- src/tslint.json | 24 +++++ src/utils.ts | 34 ++++-- 6 files changed, 186 insertions(+), 152 deletions(-) create mode 100644 src/tslint.json diff --git a/package.json b/package.json index 51eeb5ddd..1787fdaf2 100644 --- a/package.json +++ b/package.json @@ -59,6 +59,7 @@ "mocha": "^3.1.0", "phantomjs-prebuilt": "^2.1.2", "rimraf": "^2.4.2", + "tslint": "^3.15.1", "typescript": "^2.0.3", "typings": "^1.4.0", "webpack": "^1.11.0" diff --git a/src/index.ts b/src/index.ts index 27f165223..6efa3f8a9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -9,11 +9,11 @@ import interfaces = require('./interfaces'); import constants = require('./constants'); import utils = require('./utils'); import getLogger = require('./logger'); -var semver = require('semver') +const semver = require('semver'); require('colors'); -var instances = {}; -var webpackInstances: any = []; +let instances = {}; +let webpackInstances: any = []; let scriptRegex = /\.tsx?$/i; /** @@ -22,11 +22,11 @@ let scriptRegex = /\.tsx?$/i; */ function findConfigFile(compiler: typeof typescript, searchPath: string, configFileName: string): string { while (true) { - var fileName = path.join(searchPath, configFileName); + const fileName = path.join(searchPath, configFileName); if (compiler.sys.fileExists(fileName)) { return fileName; } - var parentPath = path.dirname(searchPath); + const parentPath = path.dirname(searchPath); if (parentPath === searchPath) { break; } @@ -47,38 +47,36 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade return { instance: instances[loaderOptions.instance] }; } + let compiler: typeof typescript; try { - var compiler: typeof typescript = require(loaderOptions.compiler); - } - catch (e) { - let message = loaderOptions.compiler == 'typescript' + compiler = require(loaderOptions.compiler); + } catch (e) { + let message = loaderOptions.compiler === 'typescript' ? 'Could not load TypeScript. Try installing with `npm install typescript`. If TypeScript is installed globally, try using `npm link typescript`.' - : `Could not load TypeScript compiler with NPM package name \`${loaderOptions.compiler}\`. Are you sure it is correctly installed?` + : `Could not load TypeScript compiler with NPM package name \`${loaderOptions.compiler}\`. Are you sure it is correctly installed?`; return { error: { message: message.red, rawMessage: message, - loaderSource: 'ts-loader' + loaderSource: 'ts-loader', } }; } const log = getLogger(loaderOptions); - var motd = `ts-loader: Using ${loaderOptions.compiler}@${compiler.version}`, - compilerCompatible = false; - if (loaderOptions.compiler == 'typescript') { + const motd = `ts-loader: Using ${loaderOptions.compiler}@${compiler.version}`; + let compilerCompatible = false; + if (loaderOptions.compiler === 'typescript') { if (compiler.version && semver.gte(compiler.version, '1.6.2-0')) { // don't log yet in this case, if a tsconfig.json exists we want to combine the message compilerCompatible = true; - } - else { + } else { log.logError(`${motd}. This version is incompatible with ts-loader. Please upgrade to the latest version of TypeScript.`.red); } - } - else { + } else { log.logWarning(`${motd}. This version may or may not be compatible with ts-loader.`.yellow); } - var files: interfaces.TSFiles = {}; - var instance: interfaces.TSInstance = instances[loaderOptions.instance] = { + const files: interfaces.TSFiles = {}; + const instance: interfaces.TSInstance = instances[loaderOptions.instance] = { compiler, compilerOptions: null, loaderOptions, @@ -87,46 +85,48 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade version: 0, dependencyGraph: {}, reverseDependencyGraph: {}, - modifiedFiles: null + modifiedFiles: null, }; - var compilerOptions: typescript.CompilerOptions = { + const compilerOptions: typescript.CompilerOptions = { skipDefaultLibCheck: true, - suppressOutputPathCheck: true // This is why: https://github.com/Microsoft/TypeScript/issues/7363 + suppressOutputPathCheck: true, // This is why: https://github.com/Microsoft/TypeScript/issues/7363 }; // Load any available tsconfig.json file - var filesToLoad: string[] = []; - var configFilePath = findConfigFile(compiler, path.dirname(loader.resourcePath), loaderOptions.configFileName); - var configFile: { + let filesToLoad: string[] = []; + const configFilePath = findConfigFile(compiler, path.dirname(loader.resourcePath), loaderOptions.configFileName); + let configFile: { config?: any; error?: typescript.Diagnostic; }; if (configFilePath) { - if (compilerCompatible) log.logInfo(`${motd} and ${configFilePath}`.green) - else log.logInfo(`ts-loader: Using config file at ${configFilePath}`.green) + if (compilerCompatible) { + log.logInfo(`${motd} and ${configFilePath}`.green); + } else { + log.logInfo(`ts-loader: Using config file at ${configFilePath}`.green); + } // HACK: relies on the fact that passing an extra argument won't break // the old API that has a single parameter - configFile = (compiler).readConfigFile( + configFile = ( compiler).readConfigFile( configFilePath, compiler.sys.readFile ); if (configFile.error) { - var configFileError = utils.formatErrors([configFile.error], instance, {file: configFilePath })[0]; - return { error: configFileError } + const configFileError = utils.formatErrors([configFile.error], instance, {file: configFilePath })[0]; + return { error: configFileError }; } - } - else { - if (compilerCompatible) log.logInfo(motd.green) + } else { + if (compilerCompatible) { log.logInfo(motd.green); } configFile = { config: { compilerOptions: {}, - files: [] - } - } + files: [], + }, + }; } configFile.config.compilerOptions = objectAssign({}, @@ -143,16 +143,16 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade scriptRegex = /\.tsx?$|\.jsx?$/i; } - var configParseResult: typescript.ParsedCommandLine; - if (typeof (compiler).parseJsonConfigFileContent === 'function') { + let configParseResult: typescript.ParsedCommandLine; + if (typeof ( compiler).parseJsonConfigFileContent === 'function') { // parseConfigFile was renamed between 1.6.2 and 1.7 - configParseResult = (compiler).parseJsonConfigFileContent( + configParseResult = ( compiler).parseJsonConfigFileContent( configFile.config, compiler.sys, path.dirname(configFilePath || '') ); } else { - configParseResult = (compiler).parseConfigFile( + configParseResult = ( compiler).parseConfigFile( configFile.config, compiler.sys, path.dirname(configFilePath || '') @@ -168,7 +168,7 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade file: configFilePath, message: 'error while parsing tsconfig.json'.red, rawMessage: 'error while parsing tsconfig.json', - loaderSource: 'ts-loader' + loaderSource: 'ts-loader', }}; } @@ -177,18 +177,17 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade // if `module` is not specified and not using ES6 target, default to CJS module output if (compilerOptions.module == null && compilerOptions.target !== 2 /* ES6 */) { - compilerOptions.module = 1 /* CommonJS */ - } - // special handling for TS 1.6 and target: es6 - else if (compilerCompatible && semver.lt(compiler.version, '1.7.3-0') && compilerOptions.target == 2 /* ES6 */) { + compilerOptions.module = 1; /* CommonJS */ + } else if (compilerCompatible && semver.lt(compiler.version, '1.7.3-0') && compilerOptions.target === 2 /* ES6 */) { + // special handling for TS 1.6 and target: es6 compilerOptions.module = 0 /* None */; } if (loaderOptions.transpileOnly) { // quick return for transpiling // we do need to check for any issues with TS options though - var program = compiler.createProgram([], compilerOptions), - diagnostics = program.getOptionsDiagnostics(); + const program = compiler.createProgram([], compilerOptions); + const diagnostics = program.getOptionsDiagnostics(); utils.pushArray( loader._module.errors, @@ -204,16 +203,15 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade filePath = path.normalize(fp); files[filePath] = { text: fs.readFileSync(filePath, 'utf-8'), - version: 0 + version: 0, }; }); - } - catch (exc) { + } catch (exc) { let filePathError = `A file specified in tsconfig.json could not be found: ${ filePath }`; return { error: { message: filePathError.red, rawMessage: filePathError, - loaderSource: 'ts-loader' + loaderSource: 'ts-loader', }}; } @@ -225,24 +223,14 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade // make a (sync) resolver that follows webpack's rules let resolver = makeResolver(loader.options); - var readFile = function(fileName: string) { - fileName = path.normalize(fileName); - try { - return fs.readFileSync(fileName, {encoding: 'utf8'}) - } - catch (e) { - return; - } - } - - var moduleResolutionHost = { - fileExists: (fileName: string) => readFile(fileName) !== undefined, - readFile: (fileName: string) => readFile(fileName) + const moduleResolutionHost = { + fileExists: (fileName: string) => utils.readFile(fileName) !== undefined, + readFile: (fileName: string) => utils.readFile(fileName), }; // Create the TypeScript language service - var servicesHost = { - getProjectVersion: () => instance.version+'', + const servicesHost = { + getProjectVersion: () => instance.version + '', getScriptFileNames: () => Object.keys(files).filter(filePath => scriptRegex.test(filePath)), getScriptVersion: (fileName: string) => { fileName = path.normalize(fileName); @@ -252,13 +240,13 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade // This is called any time TypeScript needs a file's text // We either load from memory or from disk fileName = path.normalize(fileName); - var file = files[fileName]; + let file = files[fileName]; if (!file) { - let text = readFile(fileName); + let text = utils.readFile(fileName); if (text == null) return; - file = files[fileName] = { version: 0, text } + file = files[fileName] = { version: 0, text }; } return compiler.ScriptSnapshot.fromString(file.text); @@ -267,12 +255,12 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade * getDirectories is also required for full import and type reference completions. * Without it defined, certain completions will not be provided */ - getDirectories: typescript.sys ? (typescript.sys).getDirectories : undefined, + getDirectories: typescript.sys ? ( typescript.sys).getDirectories : undefined, /** * For @types expansion, these two functions are needed. */ - directoryExists: typescript.sys ? (typescript.sys).directoryExists : undefined, + directoryExists: typescript.sys ? ( typescript.sys).directoryExists : undefined, getCurrentDirectory: () => process.cwd(), getCompilationSettings: () => compilerOptions, @@ -287,18 +275,18 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade let resolutionResult: any; try { - resolvedFileName = resolver.resolveSync(path.normalize(path.dirname(containingFile)), moduleName) + resolvedFileName = resolver.resolveSync(path.normalize(path.dirname(containingFile)), moduleName); if (!resolvedFileName.match(scriptRegex)) resolvedFileName = null; else resolutionResult = { resolvedFileName }; } - catch (e) { resolvedFileName = null } + catch (e) { resolvedFileName = null; } let tsResolution = compiler.resolveModuleName(moduleName, containingFile, compilerOptions, moduleResolutionHost); if (tsResolution.resolvedModule) { if (resolvedFileName) { - if (resolvedFileName == tsResolution.resolvedModule.resolvedFileName) { + if (resolvedFileName === tsResolution.resolvedModule.resolvedFileName) { resolutionResult.isExternalLibraryImport = tsResolution.resolvedModule.isExternalLibraryImport; } } @@ -312,20 +300,20 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade instance.dependencyGraph[path.normalize(containingFile)] = importedFiles; importedFiles.forEach(importedFileName => { if (!instance.reverseDependencyGraph[importedFileName]) { - instance.reverseDependencyGraph[importedFileName] = {} + instance.reverseDependencyGraph[importedFileName] = {}; } - instance.reverseDependencyGraph[importedFileName][path.normalize(containingFile)] = true - }) + instance.reverseDependencyGraph[importedFileName][path.normalize(containingFile)] = true; + }); return resolvedModules; - } + }, }; - var languageService = instance.languageService = compiler.createLanguageService(servicesHost, compiler.createDocumentRegistry()); + const languageService = instance.languageService = compiler.createLanguageService(servicesHost, compiler.createDocumentRegistry()); - var getCompilerOptionDiagnostics = true; - var checkAllFilesForErrors = true; + let getCompilerOptionDiagnostics = true; + let checkAllFilesForErrors = true; loader._compiler.plugin("after-compile", (compilation: interfaces.WebpackCompilation, callback: () => void) => { // Don't add errors for child compilations @@ -343,7 +331,7 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade function removeTSLoaderErrors(errors: interfaces.WebpackError[]) { let index = -1, length = errors.length; while (++index < length) { - if (errors[index].loaderSource == 'ts-loader') { + if (errors[index].loaderSource === 'ts-loader') { errors.splice(index--, 1); length--; } @@ -354,17 +342,17 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade * Recursive collect all possible dependats of passed file */ function collectAllDependants(fileName: string, collected: any = {}): string[] { - let result = {} - result[fileName] = true - collected[fileName] = true + let result = {}; + result[fileName] = true; + collected[fileName] = true; if (instance.reverseDependencyGraph[fileName]) { Object.keys(instance.reverseDependencyGraph[fileName]).forEach(dependantFileName => { if (!collected[dependantFileName]) { - collectAllDependants(dependantFileName, collected).forEach(fName => result[fName] = true) + collectAllDependants(dependantFileName, collected).forEach(fName => result[fName] = true); } - }) + }); } - return Object.keys(result) + return Object.keys(result); } removeTSLoaderErrors(compilation.errors); @@ -380,13 +368,13 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade // build map of all modules based on normalized filename // this is used for quick-lookup when trying to find modules // based on filepath - let modules: { [modulePath:string]: interfaces.WebpackModule[]} = {}; + let modules: { [modulePath: string]: interfaces.WebpackModule[]} = {}; compilation.modules.forEach(module => { if (module.resource) { let modulePath = path.normalize(module.resource); if (utils.hasOwnProperty(modules, modulePath)) { let existingModules = modules[modulePath]; - if (existingModules.indexOf(module) == -1) { + if (existingModules.indexOf(module) === -1) { existingModules.push(module); } } @@ -394,30 +382,30 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade modules[modulePath] = [module]; } } - }) + }); // gather all errors from TypeScript and output them to webpack - let filesWithErrors: interfaces.TSFiles = {} + let filesWithErrors: interfaces.TSFiles = {}; // calculate array of files to check - let filesToCheckForErrors: interfaces.TSFiles = null + let filesToCheckForErrors: interfaces.TSFiles = null; if (checkAllFilesForErrors) { // check all files on initial run - filesToCheckForErrors = instance.files - checkAllFilesForErrors = false + filesToCheckForErrors = instance.files; + checkAllFilesForErrors = false; } else { - filesToCheckForErrors = {} + filesToCheckForErrors = {}; // check all modified files, and all dependants Object.keys(instance.modifiedFiles).forEach(modifiedFileName => { collectAllDependants(modifiedFileName).forEach(fName => { - filesToCheckForErrors[fName] = instance.files[fName] - }) - }) + filesToCheckForErrors[fName] = instance.files[fName]; + }); + }); } // re-check files with errors from previous build if (instance.filesWithErrors) { Object.keys(instance.filesWithErrors).forEach(fileWithErrorName => filesToCheckForErrors[fileWithErrorName] = instance.filesWithErrors[fileWithErrorName] - ) + ); } Object.keys(filesToCheckForErrors) @@ -426,9 +414,9 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade let errors = languageService.getSyntacticDiagnostics(filePath).concat(languageService.getSemanticDiagnostics(filePath)); if (errors.length > 0) { if (null === filesWithErrors) { - filesWithErrors = {} + filesWithErrors = {}; } - filesWithErrors[filePath] = instance.files[filePath] + filesWithErrors[filePath] = instance.files[filePath]; } // if we have access to a webpack module, use that @@ -443,7 +431,7 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade let formattedErrors = utils.formatErrors(errors, instance, { module }); utils.pushArray(module.errors, formattedErrors); utils.pushArray(compilation.errors, formattedErrors); - }) + }); } // otherwise it's a more generic error else { @@ -462,7 +450,7 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade let assetPath = path.relative(compilation.compiler.context, declarationFile.name); compilation.assets[assetPath] = { source: () => declarationFile.text, - size: () => declarationFile.text.length + size: () => declarationFile.text.length, }; } }); @@ -474,38 +462,38 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade // manually update changed files loader._compiler.plugin("watch-run", (watching: interfaces.WebpackWatching, cb: () => void) => { - var mtimes = watching.compiler.watchFileSystem.watcher.mtimes; + const mtimes = watching.compiler.watchFileSystem.watcher.mtimes; if (null === instance.modifiedFiles) { - instance.modifiedFiles = {} + instance.modifiedFiles = {}; } Object.keys(mtimes) .filter(filePath => !!filePath.match(/\.tsx?$|\.jsx?$/)) .forEach(filePath => { filePath = path.normalize(filePath); - var file = instance.files[filePath]; + const file = instance.files[filePath]; if (file) { - file.text = readFile(filePath) || ''; + file.text = utils.readFile(filePath) || ''; file.version++; instance.version++; instance.modifiedFiles[filePath] = file; } }); - cb() - }) + cb(); + }); return { instance }; } function loader(contents: string) { this.cacheable && this.cacheable(); - var callback = this.async(); - var filePath = path.normalize(this.resourcePath); + const callback = this.async(); + const filePath = path.normalize(this.resourcePath); - var queryOptions = loaderUtils.parseQuery(this.query); - var configFileOptions = this.options.ts || {}; + const queryOptions = loaderUtils.parseQuery(this.query); + const configFileOptions = this.options.ts || {}; - var options = objectAssign({}, { + const options = objectAssign({}, { silent: false, logLevel: 'INFO', logInfoToStdOut: false, @@ -513,29 +501,29 @@ function loader(contents: string) { compiler: 'typescript', configFileName: 'tsconfig.json', transpileOnly: false, - compilerOptions: {} + compilerOptions: {}, }, configFileOptions, queryOptions); options.ignoreDiagnostics = arrify(options.ignoreDiagnostics).map(Number); options.logLevel = options.logLevel.toUpperCase(); // differentiate the TypeScript instance based on the webpack instance - var webpackIndex = webpackInstances.indexOf(this._compiler); - if (webpackIndex == -1) { - webpackIndex = webpackInstances.push(this._compiler)-1; + let webpackIndex = webpackInstances.indexOf(this._compiler); + if (webpackIndex === -1) { + webpackIndex = webpackInstances.push(this._compiler) - 1; } options.instance = webpackIndex + '_' + options.instance; - var { instance, error } = ensureTypeScriptInstance(options, this); + const { instance, error } = ensureTypeScriptInstance(options, this); if (error) { - callback(error) + callback(error); return; } // Update file contents - var file = instance.files[filePath] + let file = instance.files[filePath]; if (!file) { - file = instance.files[filePath] = { version: 0 }; + file = instance.files[filePath] = { version: 0 }; } if (file.text !== contents) { @@ -546,18 +534,18 @@ function loader(contents: string) { // push this file to modified files hash. if (!instance.modifiedFiles) { - instance.modifiedFiles = {} + instance.modifiedFiles = {}; } instance.modifiedFiles[filePath] = file; - var outputText: string, sourceMapText: string, diagnostics: typescript.Diagnostic[] = []; + let outputText: string, sourceMapText: string, diagnostics: typescript.Diagnostic[] = []; if (options.transpileOnly) { - var fileName = path.basename(filePath); - var transpileResult = instance.compiler.transpileModule(contents, { + const fileName = path.basename(filePath); + const transpileResult = instance.compiler.transpileModule(contents, { compilerOptions: instance.compilerOptions, reportDiagnostics: true, - fileName + fileName, }); ({ outputText, sourceMapText, diagnostics } = transpileResult); @@ -568,7 +556,7 @@ function loader(contents: string) { let langService = instance.languageService; // Emit Javascript - var output = langService.getEmitOutput(filePath); + const output = langService.getEmitOutput(filePath); // Make this file dependent on *all* definition files in the program this.clearDependencies(); @@ -580,24 +568,25 @@ function loader(contents: string) { // Additionally make this file dependent on all imported files let additionalDependencies = instance.dependencyGraph[filePath]; if (additionalDependencies) { - additionalDependencies.forEach(this.addDependency.bind(this)) + additionalDependencies.forEach(this.addDependency.bind(this)); } this._module.meta.tsLoaderDefinitionFileVersions = allDefinitionFiles .concat(additionalDependencies) - .map(filePath => filePath+'@'+(instance.files[filePath] || {version: '?'}).version); + .map(filePath => filePath + '@' + (instance.files[filePath] || {version: '?'}).version); - var outputFile = output.outputFiles.filter(file => !!file.name.match(/\.js(x?)$/)).pop(); - if (outputFile) { outputText = outputFile.text } + const outputFile = output.outputFiles.filter(file => !!file.name.match(/\.js(x?)$/)).pop(); + if (outputFile) { outputText = outputFile.text; } - var sourceMapFile = output.outputFiles.filter(file => !!file.name.match(/\.js(x?)\.map$/)).pop(); - if (sourceMapFile) { sourceMapText = sourceMapFile.text } + const sourceMapFile = output.outputFiles.filter(file => !!file.name.match(/\.js(x?)\.map$/)).pop(); + if (sourceMapFile) { sourceMapText = sourceMapFile.text; } } if (outputText == null) throw new Error(`Typescript emitted no output for ${filePath}`); + let sourceMap: { sources: any[], file: string; sourcesContent: string[] }; if (sourceMapText) { - var sourceMap = JSON.parse(sourceMapText); + sourceMap = JSON.parse(sourceMapText); sourceMap.sources = [loaderUtils.getRemainingRequest(this)]; sourceMap.file = filePath; sourceMap.sourcesContent = [contents]; @@ -609,7 +598,7 @@ function loader(contents: string) { // treated as new this._module.meta.tsLoaderFileVersion = file.version; - callback(null, outputText, sourceMap) + callback(null, outputText, sourceMap); } export = loader; diff --git a/src/interfaces.ts b/src/interfaces.ts index f3106a2b3..c777bc4ca 100644 --- a/src/interfaces.ts +++ b/src/interfaces.ts @@ -9,6 +9,9 @@ export interface WebpackError { loaderSource: string; } +/** + * webpack/lib/Compilation.js + */ export interface WebpackCompilation { compiler: WebpackCompiler; errors: WebpackError[]; @@ -21,6 +24,9 @@ export interface WebpackCompilation { }; } +/** + * webpack/lib/Compiler.js + */ export interface WebpackCompiler { isChild(): boolean; context: string; // a guess diff --git a/src/logger.ts b/src/logger.ts index 15572743c..c8325126b 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -14,6 +14,8 @@ interface Logger { (whereToLog: any, messages: string[]): void } +const doNothingLogger = (...messages: string[]) => {}; + function makeLogger(loaderOptions: interfaces.LoaderOptions) { return loaderOptions.silent ? (whereToLog: any, messages: string[]) => {} @@ -28,19 +30,19 @@ function makeExternalLogger(loaderOptions: interfaces.LoaderOptions, logger: Log function makeLogInfo(loaderOptions: interfaces.LoaderOptions, logger: Logger) { return LogLevel[loaderOptions.logLevel] <= LogLevel.INFO ? (...messages: string[]) => logger(loaderOptions.logInfoToStdOut ? stdoutConsole : stderrConsole, messages) - : (...messages: string[]) => {} + : doNothingLogger } function makeLogError(loaderOptions: interfaces.LoaderOptions, logger: Logger) { return LogLevel[loaderOptions.logLevel] <= LogLevel.ERROR ? (...messages: string[]) => logger(stderrConsole, messages) - : (...messages: string[]) => {} + : doNothingLogger } function makeLogWarning(loaderOptions: interfaces.LoaderOptions, logger: Logger) { return LogLevel[loaderOptions.logLevel] <= LogLevel.WARN ? (...messages: string[]) => logger(stderrConsole, messages) - : (...messages: string[]) => {} + : doNothingLogger } function getLogger(loaderOptions: interfaces.LoaderOptions) { diff --git a/src/tslint.json b/src/tslint.json new file mode 100644 index 000000000..63c51d145 --- /dev/null +++ b/src/tslint.json @@ -0,0 +1,24 @@ +{ + "extends": "tslint:latest", + "rules": { + "max-line-length": [false, 140], + "object-literal-sort-keys": false, + "member-ordering": [true, + "public-before-private", + "static-before-instance", + "variables-before-functions" + ], + "no-unused-variable": false, + "no-var-requires": false, + "quotemark": [ + "single" + ], + "no-trailing-comma": true, + "variable-name": [true, + "ban-keywords", + "check-format", + "allow-leading-underscore", + "allow-pascal-case" + ] + } +} diff --git a/src/utils.ts b/src/utils.ts index 30d7aa5b3..a456c0019 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,4 +1,6 @@ import typescript = require('typescript'); +import path = require('path'); +import fs = require('fs'); import objectAssign = require('object-assign'); import constants = require('./constants'); import interfaces = require('./interfaces'); @@ -8,7 +10,7 @@ export function pushArray(arr: T[], toPush: any) { } export function hasOwnProperty(obj: T, property: string) { - return Object.prototype.hasOwnProperty.call(obj, property) + return Object.prototype.hasOwnProperty.call(obj, property); } /** @@ -17,33 +19,43 @@ export function hasOwnProperty(obj: T, property: string) { */ export function formatErrors( diagnostics: typescript.Diagnostic[], - instance: interfaces.TSInstance, + instance: interfaces.TSInstance, merge?: any): interfaces.WebpackError[] { return diagnostics - .filter(diagnostic => instance.loaderOptions.ignoreDiagnostics.indexOf(diagnostic.code) == -1) + .filter(diagnostic => instance.loaderOptions.ignoreDiagnostics.indexOf(diagnostic.code) === -1) .map(diagnostic => { - var errorCategory = instance.compiler.DiagnosticCategory[diagnostic.category].toLowerCase(); - var errorCategoryAndCode = errorCategory + ' TS' + diagnostic.code + ': '; + const errorCategory = instance.compiler.DiagnosticCategory[diagnostic.category].toLowerCase(); + const errorCategoryAndCode = errorCategory + ' TS' + diagnostic.code + ': '; - var messageText = errorCategoryAndCode + instance.compiler.flattenDiagnosticMessageText(diagnostic.messageText, constants.EOL); + const messageText = errorCategoryAndCode + instance.compiler.flattenDiagnosticMessageText(diagnostic.messageText, constants.EOL); if (diagnostic.file) { - var lineChar = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); + const lineChar = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); return { - message: `${'('.white}${(lineChar.line+1).toString().cyan},${(lineChar.character+1).toString().cyan}): ${messageText.red}`, + message: `${'('.white}${(lineChar.line + 1).toString().cyan},${(lineChar.character + 1).toString().cyan}): ${messageText.red}`, rawMessage: messageText, - location: {line: lineChar.line+1, character: lineChar.character+1}, + location: {line: lineChar.line + 1, character: lineChar.character + 1}, loaderSource: 'ts-loader' }; } else { return { - message:`${messageText.red}`, + message: `${messageText.red}`, rawMessage: messageText, loaderSource: 'ts-loader' }; } }) - .map(error => objectAssign(error, merge)); + .map(error => objectAssign(error, merge)); } +export function readFile(fileName: string) { + fileName = path.normalize(fileName); + try { + return fs.readFileSync(fileName, {encoding: 'utf8'}); + } catch (e) { + return; + } +} + + From b48e2b3fe84d9a7fa5af0c9a9b8f8c3d0b03d71c Mon Sep 17 00:00:00 2001 From: John Reilly Date: Mon, 24 Oct 2016 20:47:55 +0100 Subject: [PATCH 05/17] revert node type definition --- src/typings/node/node.d.ts | 3445 +++++------------------------------- 1 file changed, 490 insertions(+), 2955 deletions(-) diff --git a/src/typings/node/node.d.ts b/src/typings/node/node.d.ts index 19c2609d0..321725c19 100644 --- a/src/typings/node/node.d.ts +++ b/src/typings/node/node.d.ts @@ -1,38 +1,21 @@ -// Type definitions for Node.js v6.x +// Type definitions for Node.js v0.10.1 // Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript , DefinitelyTyped -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Definitions by: Microsoft TypeScript , DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped /************************************************ * * -* Node.js v6.x API * +* Node.js v0.10.1 API * * * ************************************************/ -interface Error { - stack?: string; -} - -interface ErrorConstructor { - captureStackTrace(targetObject: Object, constructorOpt?: Function): void; - stackTraceLimit: number; -} - -// compat for TypeScript 1.8 -// if you use with --target es3 or --target es5 and use below definitions, -// use the lib.es6.d.ts that is bundled with TypeScript 1.8. -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } - /************************************************ * * * GLOBAL * * * ************************************************/ declare var process: NodeJS.Process; -declare var global: NodeJS.Global; +declare var global: any; declare var __filename: string; declare var __dirname: string; @@ -44,30 +27,23 @@ declare function clearInterval(intervalId: NodeJS.Timer): void; declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; declare function clearImmediate(immediateId: any): void; -interface NodeRequireFunction { +declare var require: { (id: string): any; -} - -interface NodeRequire extends NodeRequireFunction { - resolve(id: string): string; + resolve(id:string): string; cache: any; extensions: any; main: any; -} - -declare var require: NodeRequire; +}; -interface NodeModule { +declare var module: { exports: any; - require: NodeRequireFunction; + require(id: string): any; id: string; filename: string; loaded: boolean; parent: any; children: any[]; -} - -declare var module: NodeModule; +}; // Same as module.exports declare var exports: any; @@ -84,146 +60,16 @@ declare var SlowBuffer: { // Buffer class -type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "binary" | "hex"; -interface Buffer extends NodeBuffer { } - -/** - * Raw data is stored in instances of the Buffer class. - * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. - * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - */ +interface Buffer extends NodeBuffer {} declare var Buffer: { - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - */ new (str: string, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - */ new (size: number): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - new (array: Uint8Array): Buffer; - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - */ - new (arrayBuffer: ArrayBuffer): Buffer; - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ + new (size: Uint8Array): Buffer; new (array: any[]): Buffer; - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - */ - new (buffer: Buffer): Buffer; prototype: Buffer; - /** - * Allocates a new Buffer using an {array} of octets. - * - * @param array - */ - from(array: any[]): Buffer; - /** - * When passed a reference to the .buffer property of a TypedArray instance, - * the newly created Buffer will share the same allocated memory as the TypedArray. - * The optional {byteOffset} and {length} arguments specify a memory range - * within the {arrayBuffer} that will be shared by the Buffer. - * - * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length - */ - from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer - */ - from(buffer: Buffer): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - * - * @param str - */ - from(str: string, encoding?: string): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - isBuffer(obj: any): obj is Buffer; - /** - * Returns true if {encoding} is a valid encoding argument. - * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - * - * @param encoding string to test. - */ - isEncoding(encoding: string): boolean; - /** - * Gives the actual byte length of a string. encoding defaults to 'utf8'. - * This is not the same as String.prototype.length since that returns the number of characters in a string. - * - * @param string string to test. - * @param encoding encoding used to evaluate (defaults to 'utf8') - */ + isBuffer(obj: any): boolean; byteLength(string: string, encoding?: string): number; - /** - * Returns a buffer which is the result of concatenating all the buffers in the list together. - * - * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. - * If the list has exactly one item, then the first item of the list is returned. - * If the list has more than one item, then a new Buffer is created. - * - * @param list An array of Buffer objects to concatenate - * @param totalLength Total length of the buffers when concatenated. - * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. - */ concat(list: Buffer[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - compare(buf1: Buffer, buf2: Buffer): number; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @param fill if specified, buffer will be initialized by calling buf.fill(fill). - * If parameter is omitted, buffer will be filled with zeros. - * @param encoding encoding used for call to buf.fill while initalizing - */ - alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - allocUnsafe(size: number): Buffer; - /** - * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - allocUnsafeSlow(size: number): Buffer; }; /************************************************ @@ -231,38 +77,31 @@ declare var Buffer: { * GLOBAL INTERFACES * * * ************************************************/ -declare namespace NodeJS { +declare module NodeJS { export interface ErrnoException extends Error { - errno?: string; + errno?: any; code?: string; path?: string; syscall?: string; - stack?: string; } - export class EventEmitter { - addListener(event: string | symbol, listener: Function): this; - on(event: string | symbol, listener: Function): this; - once(event: string | symbol, listener: Function): this; - removeListener(event: string | symbol, listener: Function): this; - removeAllListeners(event?: string | symbol): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string | symbol): Function[]; - emit(event: string | symbol, ...args: any[]): boolean; - listenerCount(type: string | symbol): number; - // Added in Node 6... - prependListener(event: string | symbol, listener: Function): this; - prependOnceListener(event: string | symbol, listener: Function): this; - eventNames(): (string | symbol)[]; + export interface EventEmitter { + addListener(event: string, listener: Function): EventEmitter; + on(event: string, listener: Function): EventEmitter; + once(event: string, listener: Function): EventEmitter; + removeListener(event: string, listener: Function): EventEmitter; + removeAllListeners(event?: string): EventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; } export interface ReadableStream extends EventEmitter { readable: boolean; - read(size?: number): string | Buffer; + read(size?: number): any; setEncoding(encoding: string): void; - pause(): ReadableStream; - resume(): ReadableStream; + pause(): void; + resume(): void; pipe(destination: T, options?: { end?: boolean; }): T; unpipe(destination?: T): void; unshift(chunk: string): void; @@ -272,7 +111,8 @@ declare namespace NodeJS { export interface WritableStream extends EventEmitter { writable: boolean; - write(buffer: Buffer | string, cb?: Function): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; write(str: string, encoding?: string, cb?: Function): boolean; end(): void; end(buffer: Buffer, cb?: Function): void; @@ -280,59 +120,19 @@ declare namespace NodeJS { end(str: string, encoding?: string, cb?: Function): void; } - export interface ReadWriteStream extends ReadableStream, WritableStream { - pause(): ReadWriteStream; - resume(): ReadWriteStream; - } - - export interface Events extends EventEmitter { } - - export interface Domain extends Events { - run(fn: Function): void; - add(emitter: Events): void; - remove(emitter: Events): void; - bind(cb: (err: Error, data: any) => any): any; - intercept(cb: (data: any) => any): any; - dispose(): void; - - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; - } - - export interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - } - - export interface ProcessVersions { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - modules: string; - openssl: string; - } + export interface ReadWriteStream extends ReadableStream, WritableStream {} export interface Process extends EventEmitter { stdout: WritableStream; stderr: WritableStream; stdin: ReadableStream; argv: string[]; - argv0: string; - execArgv: string[]; execPath: string; abort(): void; chdir(directory: string): void; cwd(): string; env: any; exit(code?: number): void; - exitCode: number; getgid(): number; setgid(id: number): void; setgid(id: string): void; @@ -340,7 +140,15 @@ declare namespace NodeJS { setuid(id: number): void; setuid(id: string): void; version: string; - versions: ProcessVersions; + versions: { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + openssl: string; + }; config: { target_defaults: { cflags: any[]; @@ -367,118 +175,39 @@ declare namespace NodeJS { visibility: string; }; }; - kill(pid: number, signal?: string | number): void; + kill(pid: number, signal?: string): void; pid: number; title: string; arch: string; platform: string; - memoryUsage(): MemoryUsage; - nextTick(callback: Function, ...args: any[]): void; + memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; }; + nextTick(callback: Function): void; umask(mask?: number): number; uptime(): number; - hrtime(time?: number[]): number[]; - domain: Domain; + hrtime(time?:number[]): number[]; // Worker send?(message: any, sendHandle?: any): void; - disconnect(): void; - connected: boolean; - } - - export interface Global { - Array: typeof Array; - ArrayBuffer: typeof ArrayBuffer; - Boolean: typeof Boolean; - Buffer: typeof Buffer; - DataView: typeof DataView; - Date: typeof Date; - Error: typeof Error; - EvalError: typeof EvalError; - Float32Array: typeof Float32Array; - Float64Array: typeof Float64Array; - Function: typeof Function; - GLOBAL: Global; - Infinity: typeof Infinity; - Int16Array: typeof Int16Array; - Int32Array: typeof Int32Array; - Int8Array: typeof Int8Array; - Intl: typeof Intl; - JSON: typeof JSON; - Map: MapConstructor; - Math: typeof Math; - NaN: typeof NaN; - Number: typeof Number; - Object: typeof Object; - Promise: Function; - RangeError: typeof RangeError; - ReferenceError: typeof ReferenceError; - RegExp: typeof RegExp; - Set: SetConstructor; - String: typeof String; - Symbol: Function; - SyntaxError: typeof SyntaxError; - TypeError: typeof TypeError; - URIError: typeof URIError; - Uint16Array: typeof Uint16Array; - Uint32Array: typeof Uint32Array; - Uint8Array: typeof Uint8Array; - Uint8ClampedArray: Function; - WeakMap: WeakMapConstructor; - WeakSet: WeakSetConstructor; - clearImmediate: (immediateId: any) => void; - clearInterval: (intervalId: NodeJS.Timer) => void; - clearTimeout: (timeoutId: NodeJS.Timer) => void; - console: typeof console; - decodeURI: typeof decodeURI; - decodeURIComponent: typeof decodeURIComponent; - encodeURI: typeof encodeURI; - encodeURIComponent: typeof encodeURIComponent; - escape: (str: string) => string; - eval: typeof eval; - global: Global; - isFinite: typeof isFinite; - isNaN: typeof isNaN; - parseFloat: typeof parseFloat; - parseInt: typeof parseInt; - process: Process; - root: Global; - setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; - setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; - setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; - undefined: typeof undefined; - unescape: (str: string) => string; - gc: () => void; - v8debug?: any; } export interface Timer { - ref(): void; - unref(): void; + ref() : void; + unref() : void; } } -interface IterableIterator { } - /** * @deprecated */ -interface NodeBuffer extends Uint8Array { +interface NodeBuffer { + [index: number]: number; write(string: string, offset?: number, length?: number, encoding?: string): number; toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + toJSON(): any; + length: number; copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; + readUInt8(offset: number, noAsset?: boolean): number; readUInt16LE(offset: number, noAssert?: boolean): number; readUInt16BE(offset: number, noAssert?: boolean): number; readUInt32LE(offset: number, noAssert?: boolean): number; @@ -492,30 +221,21 @@ interface NodeBuffer extends Uint8Array { readFloatBE(offset: number, noAssert?: boolean): number; readDoubleLE(offset: number, noAssert?: boolean): number; readDoubleBE(offset: number, noAssert?: boolean): number; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - entries(): IterableIterator<[number, number]>; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - keys(): IterableIterator; - values(): IterableIterator; + writeUInt8(value: number, offset: number, noAssert?: boolean): void; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): void; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): void; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): void; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): void; + writeInt8(value: number, offset: number, noAssert?: boolean): void; + writeInt16LE(value: number, offset: number, noAssert?: boolean): void; + writeInt16BE(value: number, offset: number, noAssert?: boolean): void; + writeInt32LE(value: number, offset: number, noAssert?: boolean): void; + writeInt32BE(value: number, offset: number, noAssert?: boolean): void; + writeFloatLE(value: number, offset: number, noAssert?: boolean): void; + writeFloatBE(value: number, offset: number, noAssert?: boolean): void; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): void; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): void; + fill(value: any, offset?: number, end?: number): void; } /************************************************ @@ -525,83 +245,55 @@ interface NodeBuffer extends Uint8Array { ************************************************/ declare module "buffer" { export var INSPECT_MAX_BYTES: number; - var BuffType: typeof Buffer; - var SlowBuffType: typeof SlowBuffer; - export { BuffType as Buffer, SlowBuffType as SlowBuffer }; } declare module "querystring" { - export interface StringifyOptions { - encodeURIComponent?: Function; - } - - export interface ParseOptions { - maxKeys?: number; - decodeURIComponent?: Function; - } - - export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any; - export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; - export function escape(str: string): string; - export function unescape(str: string): string; + export function stringify(obj: any, sep?: string, eq?: string): string; + export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; + export function escape(): any; + export function unescape(): any; } declare module "events" { - export class EventEmitter extends NodeJS.EventEmitter { - static EventEmitter: EventEmitter; - static listenerCount(emitter: EventEmitter, event: string | symbol): number; // deprecated - static defaultMaxListeners: number; - - addListener(event: string | symbol, listener: Function): this; - on(event: string | symbol, listener: Function): this; - once(event: string | symbol, listener: Function): this; - prependListener(event: string | symbol, listener: Function): this; - prependOnceListener(event: string | symbol, listener: Function): this; - removeListener(event: string | symbol, listener: Function): this; - removeAllListeners(event?: string | symbol): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string | symbol): Function[]; - emit(event: string | symbol, ...args: any[]): boolean; - eventNames(): (string | symbol)[]; - listenerCount(type: string | symbol): number; - } + export class EventEmitter implements NodeJS.EventEmitter { + static listenerCount(emitter: EventEmitter, event: string): number; + + addListener(event: string, listener: Function): EventEmitter; + on(event: string, listener: Function): EventEmitter; + once(event: string, listener: Function): EventEmitter; + removeListener(event: string, listener: Function): EventEmitter; + removeAllListeners(event?: string): EventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } } declare module "http" { - import * as events from "events"; - import * as net from "net"; - import * as stream from "stream"; - - export interface RequestOptions { - protocol?: string; - host?: string; - hostname?: string; - family?: number; - port?: number; - localAddress?: string; - socketPath?: string; - method?: string; - path?: string; - headers?: { [key: string]: any }; - auth?: string; - agent?: Agent | boolean; - } + import events = require("events"); + import net = require("net"); + import stream = require("stream"); - export interface Server extends net.Server { - setTimeout(msecs: number, callback: Function): void; + export interface Server extends events.EventEmitter { + listen(port: number, hostname?: string, backlog?: number, callback?: Function): Server; + listen(path: string, callback?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + close(cb?: any): Server; + address(): { port: number; family: string; address: string; }; maxHeadersCount: number; - timeout: number; - listening: boolean; } - /** - * @deprecated Use IncomingMessage - */ - export interface ServerRequest extends IncomingMessage { + export interface ServerRequest extends events.EventEmitter, stream.Readable { + method: string; + url: string; + headers: any; + trailers: string; + httpVersion: string; + setEncoding(encoding?: string): void; + pause(): void; + resume(): void; connection: net.Socket; } - export interface ServerResponse extends stream.Writable { + export interface ServerResponse extends events.EventEmitter, stream.Writable { // Extended base methods write(buffer: Buffer): boolean; write(buffer: Buffer, cb?: Function): boolean; @@ -613,16 +305,12 @@ declare module "http" { writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; writeHead(statusCode: number, headers?: any): void; statusCode: number; - statusMessage: string; - headersSent: boolean; - setHeader(name: string, value: string | string[]): void; - setTimeout(msecs: number, callback: Function): ServerResponse; + setHeader(name: string, value: string): void; sendDate: boolean; getHeader(name: string): string; removeHeader(name: string): void; write(chunk: any, encoding?: string): any; addTrailers(headers: any): void; - finished: boolean; // Extended base methods end(): void; @@ -631,7 +319,7 @@ declare module "http" { end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; } - export interface ClientRequest extends stream.Writable { + export interface ClientRequest extends events.EventEmitter, stream.Writable { // Extended base methods write(buffer: Buffer): boolean; write(buffer: Buffer, cb?: Function): boolean; @@ -645,11 +333,6 @@ declare module "http" { setNoDelay(noDelay?: boolean): void; setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - setHeader(name: string, value: string | string[]): void; - getHeader(name: string): string; - removeHeader(name: string): void; - addTrailers(headers: any): void; - // Extended base methods end(): void; end(buffer: Buffer, cb?: Function): void; @@ -657,356 +340,70 @@ declare module "http" { end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; } - export interface IncomingMessage extends stream.Readable { + export interface ClientResponse extends events.EventEmitter, stream.Readable { + statusCode: number; httpVersion: string; - httpVersionMajor: number; - httpVersionMinor: number; - connection: net.Socket; headers: any; - rawHeaders: string[]; trailers: any; - rawTrailers: any; - setTimeout(msecs: number, callback: Function): NodeJS.Timer; - /** - * Only valid for request obtained from http.Server. - */ - method?: string; - /** - * Only valid for request obtained from http.Server. - */ - url?: string; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusCode?: number; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusMessage?: string; - socket: net.Socket; - destroy(error?: Error): void; - } - /** - * @deprecated Use IncomingMessage - */ - export interface ClientResponse extends IncomingMessage { } - - export interface AgentOptions { - /** - * Keep sockets around in a pool to be used by other requests in the future. Default = false - */ - keepAlive?: boolean; - /** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - */ - keepAliveMsecs?: number; - /** - * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity - */ - maxSockets?: number; - /** - * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. - */ - maxFreeSockets?: number; - } - - export class Agent { - maxSockets: number; - sockets: any; - requests: any; - - constructor(opts?: AgentOptions); - - /** - * Destroy any sockets that are currently in use by the agent. - * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, - * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, - * sockets may hang open for quite a long time before the server terminates them. - */ - destroy(): void; + setEncoding(encoding?: string): void; + pause(): void; + resume(): void; } - - export var METHODS: string[]; + export interface Agent { maxSockets: number; sockets: any; requests: any; } export var STATUS_CODES: { [errorCode: number]: string; [errorCode: string]: string; }; - export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; + export function createServer(requestListener?: (request: ServerRequest, response: ServerResponse) =>void ): Server; export function createClient(port?: number, host?: string): any; - export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; + export function request(options: any, callback?: Function): ClientRequest; + export function get(options: any, callback?: Function): ClientRequest; export var globalAgent: Agent; } declare module "cluster" { - import * as child from "child_process"; - import * as events from "events"; - import * as net from "net"; + import child = require("child_process"); + import events = require("events"); - // interfaces export interface ClusterSettings { - execArgv?: string[]; // default: process.execArgv exec?: string; args?: string[]; silent?: boolean; - stdio?: any[]; - uid?: number; - gid?: number; - } - - export interface ClusterSetupMasterSettings { - exec?: string; // default: process.argv[1] - args?: string[]; // default: process.argv.slice(2) - silent?: boolean; // default: false - stdio?: any[]; - } - - export interface Address { - address: string; - port: number; - addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" } export class Worker extends events.EventEmitter { id: string; process: child.ChildProcess; suicide: boolean; - send(message: any, sendHandle?: any): boolean; + send(message: any, sendHandle?: any): void; kill(signal?: string): void; destroy(signal?: string): void; disconnect(): void; - isConnected(): boolean; - isDead(): boolean; - exitedAfterDisconnect: boolean; - - /** - * events.EventEmitter - * 1. disconnect - * 2. error - * 3. exit - * 4. listening - * 5. message - * 6. online - */ - addListener(event: string, listener: Function): this; - addListener(event: "disconnect", listener: () => void): this; - addListener(event: "error", listener: (code: number, signal: string) => void): this; - addListener(event: "exit", listener: (code: number, signal: string) => void): this; - addListener(event: "listening", listener: (address: Address) => void): this; - addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - addListener(event: "online", listener: () => void): this; - - emit(event: string, listener: Function): boolean - emit(event: "disconnect", listener: () => void): boolean - emit(event: "error", listener: (code: number, signal: string) => void): boolean - emit(event: "exit", listener: (code: number, signal: string) => void): boolean - emit(event: "listening", listener: (address: Address) => void): boolean - emit(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): boolean - emit(event: "online", listener: () => void): boolean - - on(event: string, listener: Function): this; - on(event: "disconnect", listener: () => void): this; - on(event: "error", listener: (code: number, signal: string) => void): this; - on(event: "exit", listener: (code: number, signal: string) => void): this; - on(event: "listening", listener: (address: Address) => void): this; - on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - on(event: "online", listener: () => void): this; - - once(event: string, listener: Function): this; - once(event: "disconnect", listener: () => void): this; - once(event: "error", listener: (code: number, signal: string) => void): this; - once(event: "exit", listener: (code: number, signal: string) => void): this; - once(event: "listening", listener: (address: Address) => void): this; - once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - once(event: "online", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "disconnect", listener: () => void): this; - prependListener(event: "error", listener: (code: number, signal: string) => void): this; - prependListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependListener(event: "listening", listener: (address: Address) => void): this; - prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependListener(event: "online", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "disconnect", listener: () => void): this; - prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; - prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependOnceListener(event: "listening", listener: (address: Address) => void): this; - prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependOnceListener(event: "online", listener: () => void): this; - } - - export interface Cluster extends events.EventEmitter { - Worker: Worker; - disconnect(callback?: Function): void; - fork(env?: any): Worker; - isMaster: boolean; - isWorker: boolean; - // TODO: cluster.schedulingPolicy - settings: ClusterSettings; - setupMaster(settings?: ClusterSetupMasterSettings): void; - worker: Worker; - workers: { - [index: string]: Worker - }; - - /** - * events.EventEmitter - * 1. disconnect - * 2. exit - * 3. fork - * 4. listening - * 5. message - * 6. online - * 7. setup - */ - addListener(event: string, listener: Function): this; - addListener(event: "disconnect", listener: (worker: Worker) => void): this; - addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - addListener(event: "fork", listener: (worker: Worker) => void): this; - addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - addListener(event: "online", listener: (worker: Worker) => void): this; - addListener(event: "setup", listener: (settings: any) => void): this; - - emit(event: string, listener: Function): boolean; - emit(event: "disconnect", listener: (worker: Worker) => void): boolean; - emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; - emit(event: "fork", listener: (worker: Worker) => void): boolean; - emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; - emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; - emit(event: "online", listener: (worker: Worker) => void): boolean; - emit(event: "setup", listener: (settings: any) => void): boolean; - - on(event: string, listener: Function): this; - on(event: "disconnect", listener: (worker: Worker) => void): this; - on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - on(event: "fork", listener: (worker: Worker) => void): this; - on(event: "listening", listener: (worker: Worker, address: Address) => void): this; - on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - on(event: "online", listener: (worker: Worker) => void): this; - on(event: "setup", listener: (settings: any) => void): this; - - once(event: string, listener: Function): this; - once(event: "disconnect", listener: (worker: Worker) => void): this; - once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - once(event: "fork", listener: (worker: Worker) => void): this; - once(event: "listening", listener: (worker: Worker, address: Address) => void): this; - once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - once(event: "online", listener: (worker: Worker) => void): this; - once(event: "setup", listener: (settings: any) => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "disconnect", listener: (worker: Worker) => void): this; - prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - prependListener(event: "fork", listener: (worker: Worker) => void): this; - prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependListener(event: "online", listener: (worker: Worker) => void): this; - prependListener(event: "setup", listener: (settings: any) => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; - prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; - prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependOnceListener(event: "online", listener: (worker: Worker) => void): this; - prependOnceListener(event: "setup", listener: (settings: any) => void): this; - } - export function disconnect(callback?: Function): void; - export function fork(env?: any): Worker; + export var settings: ClusterSettings; export var isMaster: boolean; export var isWorker: boolean; - // TODO: cluster.schedulingPolicy - export var settings: ClusterSettings; - export function setupMaster(settings?: ClusterSetupMasterSettings): void; + export function setupMaster(settings?: ClusterSettings): void; + export function fork(env?: any): Worker; + export function disconnect(callback?: Function): void; export var worker: Worker; - export var workers: { - [index: string]: Worker - }; - - /** - * events.EventEmitter - * 1. disconnect - * 2. exit - * 3. fork - * 4. listening - * 5. message - * 6. online - * 7. setup - */ - export function addListener(event: string, listener: Function): Cluster; - export function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; - export function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - export function addListener(event: "online", listener: (worker: Worker) => void): Cluster; - export function addListener(event: "setup", listener: (settings: any) => void): Cluster; - - export function emit(event: string, listener: Function): boolean; - export function emit(event: "disconnect", listener: (worker: Worker) => void): boolean; - export function emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; - export function emit(event: "fork", listener: (worker: Worker) => void): boolean; - export function emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; - export function emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; - export function emit(event: "online", listener: (worker: Worker) => void): boolean; - export function emit(event: "setup", listener: (settings: any) => void): boolean; - - export function on(event: string, listener: Function): Cluster; - export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function on(event: "fork", listener: (worker: Worker) => void): Cluster; - export function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - export function on(event: "online", listener: (worker: Worker) => void): Cluster; - export function on(event: "setup", listener: (settings: any) => void): Cluster; - - export function once(event: string, listener: Function): Cluster; - export function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function once(event: "fork", listener: (worker: Worker) => void): Cluster; - export function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - export function once(event: "online", listener: (worker: Worker) => void): Cluster; - export function once(event: "setup", listener: (settings: any) => void): Cluster; - - export function removeListener(event: string, listener: Function): Cluster; - export function removeAllListeners(event?: string): Cluster; - export function setMaxListeners(n: number): Cluster; - export function getMaxListeners(): number; + export var workers: Worker[]; + + // Event emitter + export function addListener(event: string, listener: Function): void; + export function on(event: string, listener: Function): any; + export function once(event: string, listener: Function): void; + export function removeListener(event: string, listener: Function): void; + export function removeAllListeners(event?: string): void; + export function setMaxListeners(n: number): void; export function listeners(event: string): Function[]; - export function listenerCount(type: string): number; - - export function prependListener(event: string, listener: Function): Cluster; - export function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; - export function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - export function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; - export function prependListener(event: "setup", listener: (settings: any) => void): Cluster; - - export function prependOnceListener(event: string, listener: Function): Cluster; - export function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - export function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - export function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; - export function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - export function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - export function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; - export function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; - - export function eventNames(): string[]; + export function emit(event: string, ...args: any[]): boolean; } declare module "zlib" { - import * as stream from "stream"; + import stream = require("stream"); export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } export interface Gzip extends stream.Transform { } @@ -1025,20 +422,13 @@ declare module "zlib" { export function createInflateRaw(options?: ZlibOptions): InflateRaw; export function createUnzip(options?: ZlibOptions): Unzip; - export function deflate(buf: Buffer, callback: (error: Error, result: any) => void): void; - export function deflateSync(buf: Buffer, options?: ZlibOptions): any; - export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) => void): void; - export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any; - export function gzip(buf: Buffer, callback: (error: Error, result: any) => void): void; - export function gzipSync(buf: Buffer, options?: ZlibOptions): any; - export function gunzip(buf: Buffer, callback: (error: Error, result: any) => void): void; - export function gunzipSync(buf: Buffer, options?: ZlibOptions): any; - export function inflate(buf: Buffer, callback: (error: Error, result: any) => void): void; - export function inflateSync(buf: Buffer, options?: ZlibOptions): any; - export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) => void): void; - export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any; - export function unzip(buf: Buffer, callback: (error: Error, result: any) => void): void; - export function unzipSync(buf: Buffer, options?: ZlibOptions): any; + export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; // Constants export var Z_NO_FLUSH: number; @@ -1075,168 +465,25 @@ declare module "zlib" { } declare module "os" { - export interface CpuInfo { - model: string; - speed: number; - times: { - user: number; - nice: number; - sys: number; - idle: number; - irq: number; - }; - } - - export interface NetworkInterfaceInfo { - address: string; - netmask: string; - family: string; - mac: string; - internal: boolean; - } - + export function tmpdir(): string; export function hostname(): string; - export function loadavg(): number[]; - export function uptime(): number; - export function freemem(): number; - export function totalmem(): number; - export function cpus(): CpuInfo[]; export function type(): string; - export function release(): string; - export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; - export function homedir(): string; - export function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string } - export var constants: { - UV_UDP_REUSEADDR: number, - errno: { - SIGHUP: number; - SIGINT: number; - SIGQUIT: number; - SIGILL: number; - SIGTRAP: number; - SIGABRT: number; - SIGIOT: number; - SIGBUS: number; - SIGFPE: number; - SIGKILL: number; - SIGUSR1: number; - SIGSEGV: number; - SIGUSR2: number; - SIGPIPE: number; - SIGALRM: number; - SIGTERM: number; - SIGCHLD: number; - SIGSTKFLT: number; - SIGCONT: number; - SIGSTOP: number; - SIGTSTP: number; - SIGTTIN: number; - SIGTTOU: number; - SIGURG: number; - SIGXCPU: number; - SIGXFSZ: number; - SIGVTALRM: number; - SIGPROF: number; - SIGWINCH: number; - SIGIO: number; - SIGPOLL: number; - SIGPWR: number; - SIGSYS: number; - SIGUNUSED: number; - }, - signals: { - E2BIG: number; - EACCES: number; - EADDRINUSE: number; - EADDRNOTAVAIL: number; - EAFNOSUPPORT: number; - EAGAIN: number; - EALREADY: number; - EBADF: number; - EBADMSG: number; - EBUSY: number; - ECANCELED: number; - ECHILD: number; - ECONNABORTED: number; - ECONNREFUSED: number; - ECONNRESET: number; - EDEADLK: number; - EDESTADDRREQ: number; - EDOM: number; - EDQUOT: number; - EEXIST: number; - EFAULT: number; - EFBIG: number; - EHOSTUNREACH: number; - EIDRM: number; - EILSEQ: number; - EINPROGRESS: number; - EINTR: number; - EINVAL: number; - EIO: number; - EISCONN: number; - EISDIR: number; - ELOOP: number; - EMFILE: number; - EMLINK: number; - EMSGSIZE: number; - EMULTIHOP: number; - ENAMETOOLONG: number; - ENETDOWN: number; - ENETRESET: number; - ENETUNREACH: number; - ENFILE: number; - ENOBUFS: number; - ENODATA: number; - ENODEV: number; - ENOENT: number; - ENOEXEC: number; - ENOLCK: number; - ENOLINK: number; - ENOMEM: number; - ENOMSG: number; - ENOPROTOOPT: number; - ENOSPC: number; - ENOSR: number; - ENOSTR: number; - ENOSYS: number; - ENOTCONN: number; - ENOTDIR: number; - ENOTEMPTY: number; - ENOTSOCK: number; - ENOTSUP: number; - ENOTTY: number; - ENXIO: number; - EOPNOTSUPP: number; - EOVERFLOW: number; - EPERM: number; - EPIPE: number; - EPROTO: number; - EPROTONOSUPPORT: number; - EPROTOTYPE: number; - ERANGE: number; - EROFS: number; - ESPIPE: number; - ESRCH: number; - ESTALE: number; - ETIME: number; - ETIMEDOUT: number; - ETXTBSY: number; - EWOULDBLOCK: number; - EXDEV: number; - }, - }; - export function arch(): string; export function platform(): string; - export function tmpdir(): string; + export function arch(): string; + export function release(): string; + export function uptime(): number; + export function loadavg(): number[]; + export function totalmem(): number; + export function freemem(): number; + export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[]; + export function networkInterfaces(): any; export var EOL: string; - export function endianness(): "BE" | "LE"; } declare module "https" { - import * as tls from "tls"; - import * as events from "events"; - import * as http from "http"; + import tls = require("tls"); + import events = require("events"); + import http = require("http"); export interface ServerOptions { pfx?: any; @@ -1250,10 +497,18 @@ declare module "https" { requestCert?: boolean; rejectUnauthorized?: boolean; NPNProtocols?: any; - SNICallback?: (servername: string, cb: (err: Error, ctx: tls.SecureContext) => any) => any; + SNICallback?: (servername: string) => any; } - export interface RequestOptions extends http.RequestOptions { + export interface RequestOptions { + host?: string; + hostname?: string; + port?: number; + path?: string; + method?: string; + headers?: any; + auth?: string; + agent?: any; pfx?: any; key?: any; passphrase?: string; @@ -1261,30 +516,20 @@ declare module "https" { ca?: any; ciphers?: string; rejectUnauthorized?: boolean; - secureProtocol?: string; } - export interface Agent extends http.Agent { } - - export interface AgentOptions extends http.AgentOptions { - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any; - ciphers?: string; - rejectUnauthorized?: boolean; - secureProtocol?: string; - maxCachedSessions?: number; + export interface Agent { + maxSockets: number; + sockets: any; + requests: any; } - export var Agent: { - new (options?: AgentOptions): Agent; + new (options?: RequestOptions): Agent; }; export interface Server extends tls.Server { } export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export function request(options: RequestOptions, callback?: (res: http.ClientResponse) =>void ): http.ClientRequest; + export function get(options: RequestOptions, callback?: (res: http.ClientResponse) =>void ): http.ClientRequest; export var globalAgent: Agent; } @@ -1295,15 +540,15 @@ declare module "punycode" { export function toASCII(domain: string): string; export var ucs2: ucs2; interface ucs2 { - decode(string: string): number[]; + decode(string: string): string; encode(codePoints: number[]): string; } export var version: any; } declare module "repl" { - import * as stream from "stream"; - import * as readline from "readline"; + import stream = require("stream"); + import events = require("events"); export interface ReplOptions { prompt?: string; @@ -1315,278 +560,115 @@ declare module "repl" { useGlobal?: boolean; ignoreUndefined?: boolean; writer?: Function; - completer?: Function; - replMode?: any; - breakEvalOnSigint?: any; } - - export interface REPLServer extends readline.ReadLine { - defineCommand(keyword: string, cmd: Function | { help: string, action: Function }): void; - displayPrompt(preserveCursor?: boolean): void - } - - export function start(options: ReplOptions): REPLServer; + export function start(options: ReplOptions): events.EventEmitter; } declare module "readline" { - import * as events from "events"; - import * as stream from "stream"; - - export interface Key { - sequence?: string; - name?: string; - ctrl?: boolean; - meta?: boolean; - shift?: boolean; - } + import events = require("events"); + import stream = require("stream"); export interface ReadLine extends events.EventEmitter { - setPrompt(prompt: string): void; + setPrompt(prompt: string, length: number): void; prompt(preserveCursor?: boolean): void; - question(query: string, callback: (answer: string) => void): void; - pause(): ReadLine; - resume(): ReadLine; + question(query: string, callback: Function): void; + pause(): void; + resume(): void; close(): void; - write(data: string | Buffer, key?: Key): void; + write(data: any, key?: any): void; } - - export interface Completer { - (line: string): CompleterResult; - (line: string, callback: (err: any, result: CompleterResult) => void): any; - } - - export interface CompleterResult { - completions: string[]; - line: string; - } - export interface ReadLineOptions { input: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - completer?: Completer; + output: NodeJS.WritableStream; + completer?: Function; terminal?: boolean; - historySize?: number; } - - export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): ReadLine; export function createInterface(options: ReadLineOptions): ReadLine; - - export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; - export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; - export function clearLine(stream: NodeJS.WritableStream, dir: number): void; - export function clearScreenDown(stream: NodeJS.WritableStream): void; } declare module "vm" { export interface Context { } - export interface ScriptOptions { - filename?: string; - lineOffset?: number; - columnOffset?: number; - displayErrors?: boolean; - timeout?: number; - cachedData?: Buffer; - produceCachedData?: boolean; - } - export interface RunningScriptOptions { - filename?: string; - lineOffset?: number; - columnOffset?: number; - displayErrors?: boolean; - timeout?: number; - } - export class Script { - constructor(code: string, options?: ScriptOptions); - runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; - runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; - runInThisContext(options?: RunningScriptOptions): any; - } - export function createContext(sandbox?: Context): Context; - export function isContext(sandbox: Context): boolean; - export function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions): any; - export function runInDebugContext(code: string): any; - export function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions): any; - export function runInThisContext(code: string, options?: RunningScriptOptions): any; + export interface Script { + runInThisContext(): void; + runInNewContext(sandbox?: Context): void; + } + export function runInThisContext(code: string, filename?: string): void; + export function runInNewContext(code: string, sandbox?: Context, filename?: string): void; + export function runInContext(code: string, context: Context, filename?: string): void; + export function createContext(initSandbox?: Context): Context; + export function createScript(code: string, filename?: string): Script; } declare module "child_process" { - import * as events from "events"; - import * as stream from "stream"; + import events = require("events"); + import stream = require("stream"); export interface ChildProcess extends events.EventEmitter { - stdin: stream.Writable; + stdin: stream.Writable; stdout: stream.Readable; stderr: stream.Readable; - stdio: [stream.Writable, stream.Readable, stream.Readable]; pid: number; kill(signal?: string): void; - send(message: any, sendHandle?: any): boolean; - connected: boolean; + send(message: any, sendHandle: any): void; disconnect(): void; - unref(): void; - ref(): void; } - export interface SpawnOptions { + export function spawn(command: string, args?: string[], options?: { cwd?: string; - env?: any; stdio?: any; - detached?: boolean; - uid?: number; - gid?: number; - shell?: boolean | string; - } - export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; - - export interface ExecOptions { - cwd?: string; + custom?: any; env?: any; - shell?: string; - timeout?: number; - maxBuffer?: number; - killSignal?: string; - uid?: number; - gid?: number; - } - export interface ExecOptionsWithStringEncoding extends ExecOptions { - encoding: BufferEncoding; - } - export interface ExecOptionsWithBufferEncoding extends ExecOptions { - encoding: string; // specify `null`. - } - export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function exec(command: string, options: ExecOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - // usage. child_process.exec("tsc", {encoding: null as string}, (err, stdout, stderr) => {}); - export function exec(command: string, options: ExecOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - - export interface ExecFileOptions { + detached?: boolean; + }): ChildProcess; + export function exec(command: string, options: { cwd?: string; + stdio?: any; + customFds?: any; env?: any; + encoding?: string; timeout?: number; maxBuffer?: number; killSignal?: string; - uid?: number; - gid?: number; - } - export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { - encoding: BufferEncoding; - } - export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { - encoding: string; // specify `null`. - } - export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - // usage. child_process.execFile("file.sh", {encoding: null as string}, (err, stdout, stderr) => {}); - export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - // usage. child_process.execFile("file.sh", ["foo"], {encoding: null as string}, (err, stdout, stderr) => {}); - export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - - export interface ForkOptions { + }, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function exec(command: string, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function execFile(file: string, + callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function execFile(file: string, args?: string[], + callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function execFile(file: string, args?: string[], options?: { cwd?: string; - env?: any; - execPath?: string; - execArgv?: string[]; - silent?: boolean; - uid?: number; - gid?: number; - } - export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; - - export interface SpawnSyncOptions { - cwd?: string; - input?: string | Buffer; stdio?: any; + customFds?: any; env?: any; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; encoding?: string; - shell?: boolean | string; - } - export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { - encoding: BufferEncoding; - } - export interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { - encoding: string; // specify `null`. - } - export interface SpawnSyncReturns { - pid: number; - output: string[]; - stdout: T; - stderr: T; - status: number; - signal: string; - error: Error; - } - export function spawnSync(command: string): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns; - - export interface ExecSyncOptions { - cwd?: string; - input?: string | Buffer; - stdio?: any; - env?: any; - shell?: string; - uid?: number; - gid?: number; timeout?: number; + maxBuffer?: string; killSignal?: string; - maxBuffer?: number; - encoding?: string; - } - export interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { - encoding: BufferEncoding; - } - export interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { - encoding: string; // specify `null`. - } - export function execSync(command: string): Buffer; - export function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; - export function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; - export function execSync(command: string, options?: ExecSyncOptions): Buffer; - - export interface ExecFileSyncOptions { + }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function fork(modulePath: string, args?: string[], options?: { cwd?: string; - input?: string | Buffer; - stdio?: any; env?: any; - uid?: number; - gid?: number; - timeout?: number; - killSignal?: string; - maxBuffer?: number; encoding?: string; - } - export interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { - encoding: BufferEncoding; - } - export interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { - encoding: string; // specify `null`. - } - export function execFileSync(command: string): Buffer; - export function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; - export function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; - export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithStringEncoding): string; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; - export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer; + }): ChildProcess; } declare module "url" { export interface Url { - href?: string; + href: string; + protocol: string; + auth: string; + hostname: string; + port: string; + host: string; + pathname: string; + search: string; + query: any; // string | Object + slashes: boolean; + hash?: string; + path?: string; + } + + export interface UrlOptions { protocol?: string; auth?: string; hostname?: string; @@ -1594,67 +676,33 @@ declare module "url" { host?: string; pathname?: string; search?: string; - query?: string | any; - slashes?: boolean; + query?: any; hash?: string; path?: string; } - export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; - export function format(url: Url): string; + export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; + export function format(url: UrlOptions): string; export function resolve(from: string, to: string): string; } declare module "dns" { - export interface MxRecord { - exchange: string, - priority: number - } - - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; - export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: MxRecord[]) => void): string[]; - export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; - export function setServers(servers: string[]): void; - - //Error codes - export var NODATA: string; - export var FORMERR: string; - export var SERVFAIL: string; - export var NOTFOUND: string; - export var NOTIMP: string; - export var REFUSED: string; - export var BADQUERY: string; - export var BADNAME: string; - export var BADFAMILY: string; - export var BADRESP: string; - export var CONNREFUSED: string; - export var TIMEOUT: string; - export var EOF: string; - export var FILE: string; - export var NOMEM: string; - export var DESTRUCTION: string; - export var BADSTR: string; - export var BADFLAGS: string; - export var NONAME: string; - export var BADHINTS: string; - export var NOTINITIALIZED: string; - export var LOADIPHLPAPI: string; - export var ADDRGETNETWORKPARAMS: string; - export var CANCELLED: string; + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; + export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; } declare module "net" { - import * as stream from "stream"; - import * as events from "events"; + import stream = require("stream"); export interface Socket extends stream.Duplex { // Extended base methods @@ -1670,8 +718,8 @@ declare module "net" { setEncoding(encoding?: string): void; write(data: any, encoding?: string, callback?: Function): void; destroy(): void; - pause(): Socket; - resume(): Socket; + pause(): void; + resume(): void; setTimeout(timeout: number, callback?: Function): void; setNoDelay(noDelay?: boolean): void; setKeepAlive(enable?: boolean, initialDelay?: number): void; @@ -1680,10 +728,7 @@ declare module "net" { ref(): void; remoteAddress: string; - remoteFamily: string; remotePort: number; - localAddress: string; - localPort: number; bytesRead: number; bytesWritten: number; @@ -1693,158 +738,27 @@ declare module "net" { end(str: string, cb?: Function): void; end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; - - /** - * events.EventEmitter - * 1. close - * 2. connect - * 3. data - * 4. drain - * 5. end - * 6. error - * 7. lookup - * 8. timeout - */ - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: (had_error: boolean) => void): this; - addListener(event: "connect", listener: () => void): this; - addListener(event: "data", listener: (data: Buffer) => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - addListener(event: "timeout", listener: () => void): this; - - emit(event: string, ...args: any[]): boolean; - emit(event: "close", had_error: boolean): boolean; - emit(event: "connect"): boolean; - emit(event: "data", data: Buffer): boolean; - emit(event: "drain"): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; - emit(event: "timeout"): boolean; - - on(event: string, listener: Function): this; - on(event: "close", listener: (had_error: boolean) => void): this; - on(event: "connect", listener: () => void): this; - on(event: "data", listener: (data: Buffer) => void): this; - on(event: "drain", listener: () => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - on(event: "timeout", listener: () => void): this; - - once(event: string, listener: Function): this; - once(event: "close", listener: (had_error: boolean) => void): this; - once(event: "connect", listener: () => void): this; - once(event: "data", listener: (data: Buffer) => void): this; - once(event: "drain", listener: () => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - once(event: "timeout", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: (had_error: boolean) => void): this; - prependListener(event: "connect", listener: () => void): this; - prependListener(event: "data", listener: (data: Buffer) => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - prependListener(event: "timeout", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; - prependOnceListener(event: "connect", listener: () => void): this; - prependOnceListener(event: "data", listener: (data: Buffer) => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; } export var Socket: { new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; }; - export interface ListenOptions { - port?: number; - host?: string; - backlog?: number; - path?: string; - exclusive?: boolean; - } - - export interface Server extends events.EventEmitter { - listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): Server; - listen(port: number, hostname?: string, listeningListener?: Function): Server; - listen(port: number, backlog?: number, listeningListener?: Function): Server; - listen(port: number, listeningListener?: Function): Server; - listen(path: string, backlog?: number, listeningListener?: Function): Server; + export interface Server extends Socket { + listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; listen(path: string, listeningListener?: Function): Server; - listen(handle: any, backlog?: number, listeningListener?: Function): Server; listen(handle: any, listeningListener?: Function): Server; - listen(options: ListenOptions, listeningListener?: Function): Server; close(callback?: Function): Server; address(): { port: number; family: string; address: string; }; - getConnections(cb: (error: Error, count: number) => void): void; - ref(): Server; - unref(): Server; maxConnections: number; connections: number; - - /** - * events.EventEmitter - * 1. close - * 2. connection - * 3. error - * 4. listening - */ - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "connection", listener: (socket: Socket) => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - - emit(event: string, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "connection", socket: Socket): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - - on(event: string, listener: Function): this; - on(event: "close", listener: () => void): this; - on(event: "connection", listener: (socket: Socket) => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - - once(event: string, listener: Function): this; - once(event: "close", listener: () => void): this; - once(event: "connection", listener: (socket: Socket) => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "connection", listener: (socket: Socket) => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; } - export function createServer(connectionListener?: (socket: Socket) => void): Server; - export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server; - export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createServer(connectionListener?: (socket: Socket) =>void ): Server; + export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server; + export function connect(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; export function connect(port: number, host?: string, connectionListener?: Function): Socket; export function connect(path: string, connectionListener?: Function): Socket; - export function createConnection(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createConnection(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; export function createConnection(path: string, connectionListener?: Function): Socket; export function isIP(input: string): number; @@ -1853,12 +767,12 @@ declare module "net" { } declare module "dgram" { - import * as events from "events"; + import events = require("events"); interface RemoteInfo { address: string; - family: string; port: number; + size: number; } interface AddressInfo { @@ -1867,84 +781,24 @@ declare module "dgram" { port: number; } - interface BindOptions { - port: number; - address?: string; - exclusive?: boolean; - } - - interface SocketOptions { - type: "udp4" | "udp6"; - reuseAddr?: boolean; - } - export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - export function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - - export interface Socket extends events.EventEmitter { - send(msg: Buffer | String | any[], port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - send(msg: Buffer | String | any[], offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; - bind(port?: number, address?: string, callback?: () => void): void; - bind(options: BindOptions, callback?: Function): void; - close(callback?: any): void; + + interface Socket extends events.EventEmitter { + send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + bind(port: number, address?: string, callback?: () => void): void; + close(): void; address(): AddressInfo; setBroadcast(flag: boolean): void; - setTTL(ttl: number): void; setMulticastTTL(ttl: number): void; setMulticastLoopback(flag: boolean): void; addMembership(multicastAddress: string, multicastInterface?: string): void; dropMembership(multicastAddress: string, multicastInterface?: string): void; - ref(): void; - unref(): void; - - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - **/ - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - addListener(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; - - emit(event: string, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - emit(event: "message", msg: string, rinfo: AddressInfo): boolean; - - on(event: string, listener: Function): this; - on(event: "close", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - on(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; - - once(event: string, listener: Function): this; - once(event: "close", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - once(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - prependListener(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; - prependOnceListener(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; } } declare module "fs" { - import * as stream from "stream"; - import * as events from "events"; + import stream = require("stream"); + import events = require("events"); interface Stats { isFile(): boolean; @@ -1967,241 +821,82 @@ declare module "fs" { atime: Date; mtime: Date; ctime: Date; - birthtime: Date; } interface FSWatcher extends events.EventEmitter { close(): void; - - /** - * events.EventEmitter - * 1. change - * 2. error - */ - addListener(event: string, listener: Function): this; - addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - addListener(event: "error", listener: (code: number, signal: string) => void): this; - - on(event: string, listener: Function): this; - on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - on(event: "error", listener: (code: number, signal: string) => void): this; - - once(event: string, listener: Function): this; - once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - once(event: "error", listener: (code: number, signal: string) => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependListener(event: "error", listener: (code: number, signal: string) => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; } export interface ReadStream extends stream.Readable { close(): void; - destroy(): void; - - /** - * events.EventEmitter - * 1. open - * 2. close - */ - addListener(event: string, listener: Function): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "close", listener: () => void): this; - - on(event: string, listener: Function): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "close", listener: () => void): this; - - once(event: string, listener: Function): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "close", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "close", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; } - export interface WriteStream extends stream.Writable { close(): void; - bytesWritten: number; - path: string | Buffer; - - /** - * events.EventEmitter - * 1. open - * 2. close - */ - addListener(event: string, listener: Function): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "close", listener: () => void): this; - - on(event: string, listener: Function): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "close", listener: () => void): this; - - once(event: string, listener: Function): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "close", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "close", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; } - /** - * Asynchronous rename. - * @param oldPath - * @param newPath - * @param callback No arguments other than a possible exception are given to the completion callback. - */ export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - /** - * Synchronous rename - * @param oldPath - * @param newPath - */ export function renameSync(oldPath: string, newPath: string): void; - export function truncate(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncate(path: string | Buffer, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncateSync(path: string | Buffer, len?: number): void; + export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncateSync(path: string, len?: number): void; export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function ftruncateSync(fd: number, len?: number): void; - export function chown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chownSync(path: string | Buffer, uid: number, gid: number): void; + export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chownSync(path: string, uid: number, gid: number): void; export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function fchownSync(fd: number, uid: number, gid: number): void; - export function lchown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchownSync(path: string | Buffer, uid: number, gid: number): void; - export function chmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmodSync(path: string | Buffer, mode: number): void; - export function chmodSync(path: string | Buffer, mode: string): void; + export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchownSync(path: string, uid: number, gid: number): void; + export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmodSync(path: string, mode: number): void; + export function chmodSync(path: string, mode: string): void; export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; export function fchmodSync(fd: number, mode: number): void; export function fchmodSync(fd: number, mode: string): void; - export function lchmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmodSync(path: string | Buffer, mode: number): void; - export function lchmodSync(path: string | Buffer, mode: string): void; - export function stat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function lstat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmodSync(path: string, mode: number): void; + export function lchmodSync(path: string, mode: string): void; + export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function statSync(path: string | Buffer): Stats; - export function lstatSync(path: string | Buffer): Stats; + export function statSync(path: string): Stats; + export function lstatSync(path: string): Stats; export function fstatSync(fd: number): Stats; - export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function linkSync(srcpath: string | Buffer, dstpath: string | Buffer): void; - export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function symlinkSync(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): void; - export function readlink(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; - export function readlinkSync(path: string | Buffer): string; - export function realpath(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; - export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; - export function realpathSync(path: string | Buffer, cache?: { [path: string]: string }): string; - /* - * Asynchronous unlink - deletes the file specified in {path} - * - * @param path - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function unlink(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Synchronous unlink - deletes the file specified in {path} - * - * @param path - */ - export function unlinkSync(path: string | Buffer): void; - /* - * Asynchronous rmdir - removes the directory specified in {path} - * - * @param path - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function rmdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Synchronous rmdir - removes the directory specified in {path} - * - * @param path - */ - export function rmdirSync(path: string | Buffer): void; - /* - * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function mkdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function mkdir(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function mkdir(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - /* - * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function mkdirSync(path: string | Buffer, mode?: number): void; - /* - * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. - */ - export function mkdirSync(path: string | Buffer, mode?: string): void; - /* - * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * - * @param prefix - * @param callback The created folder path is passed as a string to the callback's second parameter. - */ - export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; - /* - * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * - * @param prefix - * @returns Returns the created folder path. - */ - export function mkdtempSync(prefix: string): string; - export function readdir(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; - export function readdirSync(path: string | Buffer): string[]; + export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function linkSync(srcpath: string, dstpath: string): void; + export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; + export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; + export function readlinkSync(path: string): string; + export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void; + export function realpathSync(path: string, cache?: {[path: string]: string}): string; + export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function unlinkSync(path: string): void; + export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function rmdirSync(path: string): void; + export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function mkdirSync(path: string, mode?: number): void; + export function mkdirSync(path: string, mode?: string): void; + export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; + export function readdirSync(path: string): string[]; export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function closeSync(fd: number): void; - export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; - export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; - export function openSync(path: string | Buffer, flags: string | number, mode?: number): number; - export function utimes(path: string | Buffer, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimesSync(path: string | Buffer, atime: number, mtime: number): void; - export function utimesSync(path: string | Buffer, atime: Date, mtime: Date): void; + export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function openSync(path: string, flags: string, mode?: number): number; + export function openSync(path: string, flags: string, mode?: string): number; + export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimesSync(path: string, atime: number, mtime: number): void; + export function utimesSync(path: string, atime: Date, mtime: Date): void; export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; export function futimesSync(fd: number, atime: number, mtime: number): void; @@ -2209,65 +904,15 @@ declare module "fs" { export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function fsyncSync(fd: number): void; export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; - export function write(fd: number, buffer: Buffer, offset: number, length: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; - export function write(fd: number, data: any, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function write(fd: number, data: any, offset: number, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number; - export function writeSync(fd: number, data: any, position?: number, enconding?: string): number; + export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; - /* - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param encoding - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. - */ export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; - /* - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. - */ export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; - /* - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. - */ export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - /* - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. - */ - export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - /* - * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param encoding - */ + export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void ): void; export function readFileSync(filename: string, encoding: string): string; - /* - * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. - */ export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; - /* - * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. - */ export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; @@ -2283,607 +928,95 @@ declare module "fs" { export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; - export function watch(filename: string, encoding: string, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; - export function watch(filename: string, options: { persistent?: boolean; recursive?: boolean; encoding?: string }, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; - export function exists(path: string | Buffer, callback?: (exists: boolean) => void): void; - export function existsSync(path: string | Buffer): boolean; - - export namespace constants { - // File Access Constants - - /** Constant for fs.access(). File is visible to the calling process. */ - export const F_OK: number; - - /** Constant for fs.access(). File can be read by the calling process. */ - export const R_OK: number; - - /** Constant for fs.access(). File can be written by the calling process. */ - export const W_OK: number; - - /** Constant for fs.access(). File can be executed by the calling process. */ - export const X_OK: number; - - // File Open Constants - - /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ - export const O_RDONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ - export const O_WRONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ - export const O_RDWR: number; - - /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ - export const O_CREAT: number; - - /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ - export const O_EXCL: number; - - /** Constant for fs.open(). Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one). */ - export const O_NOCTTY: number; - - /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ - export const O_TRUNC: number; - - /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ - export const O_APPEND: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ - export const O_DIRECTORY: number; - - /** Constant for fs.open(). Flag indicating reading accesses to the file system will no longer result in an update to the atime information associated with the file. This flag is available on Linux operating systems only. */ - export const O_NOATIME: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ - export const O_NOFOLLOW: number; - - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ - export const O_SYNC: number; - - /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ - export const O_SYMLINK: number; - - /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ - export const O_DIRECT: number; - - /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ - export const O_NONBLOCK: number; - - // File Type Constants - - /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ - export const S_IFMT: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ - export const S_IFREG: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ - export const S_IFDIR: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ - export const S_IFCHR: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ - export const S_IFBLK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ - export const S_IFIFO: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ - export const S_IFLNK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ - export const S_IFSOCK: number; - - // File Mode Constants - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ - export const S_IRWXU: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ - export const S_IRUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ - export const S_IWUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ - export const S_IXUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ - export const S_IRWXG: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ - export const S_IRGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ - export const S_IWGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ - export const S_IXGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ - export const S_IRWXO: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ - export const S_IROTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ - export const S_IWOTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ - export const S_IXOTH: number; - } - - /** Tests a user's permissions for the file specified by path. */ - export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; - export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; - /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ - export function accessSync(path: string | Buffer, mode?: number): void; - export function createReadStream(path: string | Buffer, options?: { + export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; + export function exists(path: string, callback?: (exists: boolean) => void): void; + export function existsSync(path: string): boolean; + export function createReadStream(path: string, options?: { flags?: string; encoding?: string; - fd?: number; + fd?: string; mode?: number; - autoClose?: boolean; - start?: number; - end?: number; + bufferSize?: number; }): ReadStream; - export function createWriteStream(path: string | Buffer, options?: { + export function createReadStream(path: string, options?: { flags?: string; encoding?: string; - fd?: number; - mode?: number; - autoClose?: boolean; - start?: number; + fd?: string; + mode?: string; + bufferSize?: number; + }): ReadStream; + export function createWriteStream(path: string, options?: { + flags?: string; + encoding?: string; + string?: string; }): WriteStream; - export function fdatasync(fd: number, callback: Function): void; - export function fdatasyncSync(fd: number): void; } declare module "path" { - - /** - * A parsed path object generated by path.parse() or consumed by path.format(). - */ - export interface ParsedPath { - /** - * The root of the path such as '/' or 'c:\' - */ - root: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base: string; - /** - * The file extension (if any) such as '.html' - */ - ext: string; - /** - * The file name without extension (if any) such as 'index' - */ - name: string; - } - - /** - * Normalize a string path, reducing '..' and '.' parts. - * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. - * - * @param p string path to normalize. - */ export function normalize(p: string): string; - /** - * Join all arguments together and normalize the resulting path. - * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. - * - * @param paths string paths to join. - */ export function join(...paths: any[]): string; - /** - * Join all arguments together and normalize the resulting path. - * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. - * - * @param paths string paths to join. - */ - export function join(...paths: string[]): string; - /** - * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. - * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. - * - * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. - * - * @param pathSegments string paths to join. Non-string arguments are ignored. - */ export function resolve(...pathSegments: any[]): string; - /** - * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. - * - * @param path path to test. - */ - export function isAbsolute(path: string): boolean; - /** - * Solve the relative path from {from} to {to}. - * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - * - * @param from - * @param to - */ export function relative(from: string, to: string): string; - /** - * Return the directory name of a path. Similar to the Unix dirname command. - * - * @param p the path to evaluate. - */ export function dirname(p: string): string; - /** - * Return the last portion of a path. Similar to the Unix basename command. - * Often used to extract the file name from a fully qualified path. - * - * @param p the path to evaluate. - * @param ext optionally, an extension to remove from the result. - */ export function basename(p: string, ext?: string): string; - /** - * Return the extension of the path, from the last '.' to end of string in the last portion of the path. - * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string - * - * @param p the path to evaluate. - */ export function extname(p: string): string; - /** - * The platform-specific file separator. '\\' or '/'. - */ export var sep: string; - /** - * The platform-specific file delimiter. ';' or ':'. - */ - export var delimiter: string; - /** - * Returns an object from a path string - the opposite of format(). - * - * @param pathString path to evaluate. - */ - export function parse(pathString: string): ParsedPath; - /** - * Returns a path string from an object - the opposite of parse(). - * - * @param pathString path to evaluate. - */ - export function format(pathObject: ParsedPath): string; - - export module posix { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; - export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; - } - - export module win32 { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; - export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; - } } declare module "string_decoder" { export interface NodeStringDecoder { write(buffer: Buffer): string; - end(buffer?: Buffer): string; + detectIncompleteChar(buffer: Buffer): number; } export var StringDecoder: { - new (encoding?: string): NodeStringDecoder; + new (encoding: string): NodeStringDecoder; }; } declare module "tls" { - import * as crypto from "crypto"; - import * as net from "net"; - import * as stream from "stream"; + import crypto = require("crypto"); + import net = require("net"); + import stream = require("stream"); var CLIENT_RENEG_LIMIT: number; var CLIENT_RENEG_WINDOW: number; - export interface Certificate { - /** - * Country code. - */ - C: string; - /** - * Street. - */ - ST: string; - /** - * Locality. - */ - L: string; - /** - * Organization. - */ - O: string; - /** - * Organizational unit. - */ - OU: string; - /** - * Common name. - */ - CN: string; - } - - export interface CipherNameAndProtocol { - /** - * The cipher name. - */ - name: string; - /** - * SSL/TLS protocol version. - */ - version: string; - } - - export class TLSSocket extends stream.Duplex { - /** - * Construct a new tls.TLSSocket object from an existing TCP socket. - */ - constructor(socket:net.Socket, options?: { - /** - * An optional TLS context object from tls.createSecureContext() - */ - secureContext?: SecureContext, - /** - * If true the TLS socket will be instantiated in server-mode. - * Defaults to false. - */ - isServer?: boolean, - /** - * An optional net.Server instance. - */ - server?: net.Server, - /** - * If true the server will request a certificate from clients that - * connect and attempt to verify that certificate. Defaults to - * false. - */ - requestCert?: boolean, - /** - * If true the server will reject any connection which is not - * authorized with the list of supplied CAs. This option only has an - * effect if requestCert is true. Defaults to false. - */ - rejectUnauthorized?: boolean, - /** - * An array of strings or a Buffer naming possible NPN protocols. - * (Protocols should be ordered by their priority.) - */ - NPNProtocols?: string[] | Buffer, - /** - * An array of strings or a Buffer naming possible ALPN protocols. - * (Protocols should be ordered by their priority.) When the server - * receives both NPN and ALPN extensions from the client, ALPN takes - * precedence over NPN and the server does not send an NPN extension - * to the client. - */ - ALPNProtocols?: string[] | Buffer, - /** - * SNICallback(servername, cb) A function that will be - * called if the client supports SNI TLS extension. Two arguments - * will be passed when called: servername and cb. SNICallback should - * invoke cb(null, ctx), where ctx is a SecureContext instance. - * (tls.createSecureContext(...) can be used to get a proper - * SecureContext.) If SNICallback wasn't provided the default callback - * with high-level API will be used (see below). - */ - SNICallback?: Function, - /** - * An optional Buffer instance containing a TLS session. - */ - session?: Buffer, - /** - * If true, specifies that the OCSP status request extension will be - * added to the client hello and an 'OCSPResponse' event will be - * emitted on the socket before establishing a secure communication - */ - requestOCSP?: boolean - }); - /** - * Returns the bound address, the address family name and port of the underlying socket as reported by - * the operating system. - * @returns {any} - An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. - */ - address(): { port: number; family: string; address: string }; - /** - * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. - */ - authorized: boolean; - /** - * The reason why the peer's certificate has not been verified. - * This property becomes available only when tlsSocket.authorized === false. - */ - authorizationError: Error; - /** - * Static boolean value, always true. - * May be used to distinguish TLS sockets from regular ones. - */ - encrypted: boolean; - /** - * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. - * @returns {CipherNameAndProtocol} - Returns an object representing the cipher name - * and the SSL/TLS protocol version of the current connection. - */ - getCipher(): CipherNameAndProtocol; - /** - * Returns an object representing the peer's certificate. - * The returned object has some properties corresponding to the field of the certificate. - * If detailed argument is true the full chain with issuer property will be returned, - * if false only the top certificate without issuer property. - * If the peer does not provide a certificate, it returns null or an empty object. - * @param {boolean} detailed - If true; the full chain with issuer property will be returned. - * @returns {any} - An object representing the peer's certificate. - */ - getPeerCertificate(detailed?: boolean): { - subject: Certificate; - issuerInfo: Certificate; - issuer: Certificate; - raw: any; - valid_from: string; - valid_to: string; - fingerprint: string; - serialNumber: string; - }; - /** - * Could be used to speed up handshake establishment when reconnecting to the server. - * @returns {any} - ASN.1 encoded TLS session or undefined if none was negotiated. - */ - getSession(): any; - /** - * NOTE: Works only with client TLS sockets. - * Useful only for debugging, for session reuse provide session option to tls.connect(). - * @returns {any} - TLS session ticket or undefined if none was negotiated. - */ - getTLSTicket(): any; - /** - * The string representation of the local IP address. - */ - localAddress: string; - /** - * The numeric representation of the local port. - */ - localPort: string; - /** - * The string representation of the remote IP address. - * For example, '74.125.127.100' or '2001:4860:a005::68'. - */ - remoteAddress: string; - /** - * The string representation of the remote IP family. 'IPv4' or 'IPv6'. - */ - remoteFamily: string; - /** - * The numeric representation of the remote port. For example, 443. - */ - remotePort: number; - /** - * Initiate TLS renegotiation process. - * - * NOTE: Can be used to request peer's certificate after the secure connection has been established. - * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. - * @param {TlsOptions} options - The options may contain the following fields: rejectUnauthorized, - * requestCert (See tls.createServer() for details). - * @param {Function} callback - callback(err) will be executed with null as err, once the renegotiation - * is successfully completed. - */ - renegotiate(options: TlsOptions, callback: (err: Error) => any): any; - /** - * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by - * the TLS layer until the entire fragment is received and its integrity is verified; - * large fragments can span multiple roundtrips, and their processing can be delayed due to packet - * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, - * which may decrease overall server throughput. - * @param {number} size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * @returns {boolean} - Returns true on success, false otherwise. - */ - setMaxSendFragment(size: number): boolean; - - /** - * events.EventEmitter - * 1. OCSPResponse - * 2. secureConnect - **/ - addListener(event: string, listener: Function): this; - addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - addListener(event: "secureConnect", listener: () => void): this; - - emit(event: string, ...args: any[]): boolean; - emit(event: "OCSPResponse", response: Buffer): boolean; - emit(event: "secureConnect"): boolean; - - on(event: string, listener: Function): this; - on(event: "OCSPResponse", listener: (response: Buffer) => void): this; - on(event: "secureConnect", listener: () => void): this; - - once(event: string, listener: Function): this; - once(event: "OCSPResponse", listener: (response: Buffer) => void): this; - once(event: "secureConnect", listener: () => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - prependListener(event: "secureConnect", listener: () => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - prependOnceListener(event: "secureConnect", listener: () => void): this; - } - export interface TlsOptions { - host?: string; - port?: number; - pfx?: string | Buffer[]; - key?: string | string[] | Buffer | any[]; + pfx?: any; //string or buffer + key?: any; //string or buffer passphrase?: string; - cert?: string | string[] | Buffer | Buffer[]; - ca?: string | string[] | Buffer | Buffer[]; - crl?: string | string[]; + cert?: any; + ca?: any; //string or buffer + crl?: any; //string or string array ciphers?: string; - honorCipherOrder?: boolean; + honorCipherOrder?: any; requestCert?: boolean; rejectUnauthorized?: boolean; - NPNProtocols?: string[] | Buffer; - SNICallback?: (servername: string, cb: (err: Error, ctx: SecureContext) => any) => any; - ecdhCurve?: string; - dhparam?: string | Buffer; - handshakeTimeout?: number; - ALPNProtocols?: string[] | Buffer; - sessionTimeout?: number; - ticketKeys?: any; - sessionIdContext?: string; - secureProtocol?: string; + NPNProtocols?: any; //array or Buffer; + SNICallback?: (servername: string) => any; } export interface ConnectionOptions { host?: string; port?: number; socket?: net.Socket; - pfx?: string | Buffer - key?: string | string[] | Buffer | Buffer[]; + pfx?: any; //string | Buffer + key?: any; //string | Buffer passphrase?: string; - cert?: string | string[] | Buffer | Buffer[]; - ca?: string | Buffer | (string | Buffer)[]; + cert?: any; //string | Buffer + ca?: any; //Array of string | Buffer rejectUnauthorized?: boolean; - NPNProtocols?: (string | Buffer)[]; + NPNProtocols?: any; //Array of string | Buffer servername?: string; - path?: string; - ALPNProtocols?: (string | Buffer)[]; - checkServerIdentity?: (servername: string, cert: string | Buffer | (string | Buffer)[]) => any; - secureProtocol?: string; - secureContext?: Object; - session?: Buffer; - minDHSize?: number; } export interface Server extends net.Server { + // Extended base methods + listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; + listen(path: string, listeningListener?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + + listen(port: number, host?: string, callback?: Function): Server; close(): Server; address(): { port: number; family: string; address: string; }; addContext(hostName: string, credentials: { @@ -2893,56 +1026,6 @@ declare module "tls" { }): void; maxConnections: number; connections: number; - - /** - * events.EventEmitter - * 1. tlsClientError - * 2. newSession - * 3. OCSPRequest - * 4. resumeSession - * 5. secureConnection - **/ - addListener(event: string, listener: Function): this; - addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - addListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - - emit(event: string, ...args: any[]): boolean; - emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; - emit(event: "newSession", sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void): boolean; - emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: Function): boolean; - emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; - emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; - - on(event: string, listener: Function): this; - on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - - once(event: string, listener: Function): this; - once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; - prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; - prependOnceListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; - prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; } export interface ClearTextStream extends stream.Duplex { @@ -2967,412 +1050,186 @@ declare module "tls" { cleartext: any; } - export interface SecureContextOptions { - pfx?: string | Buffer; - key?: string | Buffer; - passphrase?: string; - cert?: string | Buffer; - ca?: string | Buffer; - crl?: string | string[] - ciphers?: string; - honorCipherOrder?: boolean; - } - - export interface SecureContext { - context: any; - } - - export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) => void): Server; - export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): ClearTextStream; - export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; - export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; + export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server; + export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream; + export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; + export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; - export function createSecureContext(details: SecureContextOptions): SecureContext; } declare module "crypto" { - export interface Certificate { - exportChallenge(spkac: string | Buffer): Buffer; - exportPublicKey(spkac: string | Buffer): Buffer; - verifySpkac(spkac: Buffer): boolean; - } - export var Certificate: { - new (): Certificate; - (): Certificate; - } - - export var fips: boolean; - export interface CredentialDetails { pfx: string; key: string; passphrase: string; cert: string; - ca: string | string[]; - crl: string | string[]; + ca: any; //string | string array + crl: any; //string | string array ciphers: string; } export interface Credentials { context?: any; } export function createCredentials(details: CredentialDetails): Credentials; export function createHash(algorithm: string): Hash; - export function createHmac(algorithm: string, key: string | Buffer): Hmac; - - type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; - type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; - type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; - type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; - type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; - - export interface Hash extends NodeJS.ReadWriteStream { - update(data: string | Buffer): Hash; - update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hash; + export function createHmac(algorithm: string, key: string): Hmac; + export function createHmac(algorithm: string, key: Buffer): Hmac; + interface Hash { + update(data: any, input_encoding?: string): Hash; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): any; digest(): Buffer; - digest(encoding: HexBase64Latin1Encoding): string; } - export interface Hmac extends NodeJS.ReadWriteStream { - update(data: string | Buffer): Hmac; - update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Hmac; + interface Hmac { + update(data: any, input_encoding?: string): Hmac; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): any; digest(): Buffer; - digest(encoding: HexBase64Latin1Encoding): string; } export function createCipher(algorithm: string, password: any): Cipher; export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; - export interface Cipher extends NodeJS.ReadWriteStream { + interface Cipher { update(data: Buffer): Buffer; - update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; - update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; + update(data: string, input_encoding?: string, output_encoding?: string): string; final(): Buffer; final(output_encoding: string): string; - setAutoPadding(auto_padding?: boolean): void; - getAuthTag(): Buffer; - setAAD(buffer: Buffer): void; + setAutoPadding(auto_padding: boolean): void; } export function createDecipher(algorithm: string, password: any): Decipher; export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; - export interface Decipher extends NodeJS.ReadWriteStream { + interface Decipher { update(data: Buffer): Buffer; - update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; - update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; + update(data: string, input_encoding?: string, output_encoding?: string): string; final(): Buffer; final(output_encoding: string): string; - setAutoPadding(auto_padding?: boolean): void; - setAuthTag(tag: Buffer): void; - setAAD(buffer: Buffer): void; + setAutoPadding(auto_padding: boolean): void; } export function createSign(algorithm: string): Signer; - export interface Signer extends NodeJS.WritableStream { - update(data: string | Buffer): Signer; - update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Signer; - sign(private_key: string | { key: string; passphrase: string }): Buffer; - sign(private_key: string | { key: string; passphrase: string }, output_format: HexBase64Latin1Encoding): string; + interface Signer { + update(data: any): void; + sign(private_key: string, output_format: string): string; } export function createVerify(algorith: string): Verify; - export interface Verify extends NodeJS.WritableStream { - update(data: string | Buffer): Verify; - update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Verify; - verify(object: string, signature: Buffer): boolean; - verify(object: string, signature: string, signature_format: HexBase64Latin1Encoding): boolean; - } - export function createDiffieHellman(prime_length: number, generator?: number): DiffieHellman; - export function createDiffieHellman(prime: Buffer): DiffieHellman; - export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; - export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Buffer): DiffieHellman; - export function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; - export interface DiffieHellman { - generateKeys(): Buffer; - generateKeys(encoding: HexBase64Latin1Encoding): string; - computeSecret(other_public_key: Buffer): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; - getPrime(): Buffer; - getPrime(encoding: HexBase64Latin1Encoding): string; - getGenerator(): Buffer; - getGenerator(encoding: HexBase64Latin1Encoding): string; - getPublicKey(): Buffer; - getPublicKey(encoding: HexBase64Latin1Encoding): string; - getPrivateKey(): Buffer; - getPrivateKey(encoding: HexBase64Latin1Encoding): string; - setPublicKey(public_key: Buffer): void; - setPublicKey(public_key: string, encoding: string): void; - setPrivateKey(private_key: Buffer): void; - setPrivateKey(private_key: string, encoding: string): void; - verifyError: number; + interface Verify { + update(data: any): void; + verify(object: string, signature: string, signature_format?: string): boolean; + } + export function createDiffieHellman(prime_length: number): DiffieHellman; + export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; + interface DiffieHellman { + generateKeys(encoding?: string): string; + computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; + getPrime(encoding?: string): string; + getGenerator(encoding: string): string; + getPublicKey(encoding?: string): string; + getPrivateKey(encoding?: string): string; + setPublicKey(public_key: string, encoding?: string): void; + setPrivateKey(public_key: string, encoding?: string): void; } export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer; + export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer; export function randomBytes(size: number): Buffer; - export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; + export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; export function pseudoRandomBytes(size: number): Buffer; - export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; - export interface RsaPublicKey { - key: string; - padding?: number; - } - export interface RsaPrivateKey { - key: string; - passphrase?: string, - padding?: number; - } - export function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer - export function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer - export function privateEncrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer - export function publicDecrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer - export function getCiphers(): string[]; - export function getCurves(): string[]; - export function getHashes(): string[]; - export interface ECDH { - generateKeys(): Buffer; - generateKeys(encoding: HexBase64Latin1Encoding): string; - generateKeys(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; - computeSecret(other_public_key: Buffer): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; - getPrivateKey(): Buffer; - getPrivateKey(encoding: HexBase64Latin1Encoding): string; - getPublicKey(): Buffer; - getPublicKey(encoding: HexBase64Latin1Encoding): string; - getPublicKey(encoding: HexBase64Latin1Encoding, format: ECDHKeyFormat): string; - setPrivateKey(private_key: Buffer): void; - setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; - } - export function createECDH(curve_name: string): ECDH; - export function timingSafeEqual(a: Buffer, b: Buffer): boolean; - export var DEFAULT_ENCODING: string; + export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; } declare module "stream" { - import * as events from "events"; + import events = require("events"); - class internal extends events.EventEmitter { + export interface Stream extends events.EventEmitter { pipe(destination: T, options?: { end?: boolean; }): T; } - namespace internal { - - export class Stream extends internal { } - - export interface ReadableOptions { - highWaterMark?: number; - encoding?: string; - objectMode?: boolean; - read?: (size?: number) => any; - } - export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { - readable: boolean; - constructor(opts?: ReadableOptions); - protected _read(size: number): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): Readable; - resume(): Readable; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. data - * 3. end - * 4. readable - * 5. error - **/ - addListener(event: string, listener: Function): this; - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - - emit(event: string, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "data", chunk: Buffer | string): boolean; - emit(event: "end"): boolean; - emit(event: "readable"): boolean; - emit(event: "error", err: Error): boolean; - - on(event: string, listener: Function): this; - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "end", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - - once(event: string, listener: Function): this; - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "end", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - - removeListener(event: string, listener: Function): this; - removeListener(event: "close", listener: () => void): this; - removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; - removeListener(event: "end", listener: () => void): this; - removeListener(event: "readable", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - } + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + } - export interface WritableOptions { - highWaterMark?: number; - decodeStrings?: boolean; - objectMode?: boolean; - write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; - } + export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { + readable: boolean; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + } - export class Writable extends events.EventEmitter implements NodeJS.WritableStream { - writable: boolean; - constructor(opts?: WritableOptions); - protected _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. drain - * 3. error - * 4. finish - * 5. pipe - * 6. unpipe - **/ - addListener(event: string, listener: Function): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "pipe", listener: (src: Readable) => void): this; - addListener(event: "unpipe", listener: (src: Readable) => void): this; - - emit(event: string, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "drain", chunk: Buffer | string): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "pipe", src: Readable): boolean; - emit(event: "unpipe", src: Readable): boolean; - - on(event: string, listener: Function): this; - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "pipe", listener: (src: Readable) => void): this; - on(event: "unpipe", listener: (src: Readable) => void): this; - - once(event: string, listener: Function): this; - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "pipe", listener: (src: Readable) => void): this; - once(event: "unpipe", listener: (src: Readable) => void): this; - - prependListener(event: string, listener: Function): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "pipe", listener: (src: Readable) => void): this; - prependListener(event: "unpipe", listener: (src: Readable) => void): this; - - prependOnceListener(event: string, listener: Function): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; - - removeListener(event: string, listener: Function): this; - removeListener(event: "close", listener: () => void): this; - removeListener(event: "drain", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - removeListener(event: "finish", listener: () => void): this; - removeListener(event: "pipe", listener: (src: Readable) => void): this; - removeListener(event: "unpipe", listener: (src: Readable) => void): this; - } + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + } - export interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean; - readableObjectMode?: boolean; - writableObjectMode?: boolean; - } + export class Writable extends events.EventEmitter implements NodeJS.WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + _write(data: Buffer, encoding: string, callback: Function): void; + _write(data: string, encoding: string, callback: Function): void; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } - // Note: Duplex extends both Readable and Writable. - export class Duplex extends Readable implements NodeJS.ReadWriteStream { - // Readable - pause(): Duplex; - resume(): Duplex; - // Writeable - writable: boolean; - constructor(opts?: DuplexOptions); - protected _write(chunk: any, encoding: string, callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + } - export interface TransformOptions extends DuplexOptions { - transform?: (chunk: string | Buffer, encoding: string, callback: Function) => any; - flush?: (callback: Function) => any; - } + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements NodeJS.ReadWriteStream { + writable: boolean; + constructor(opts?: DuplexOptions); + _write(data: Buffer, encoding: string, callback: Function): void; + _write(data: string, encoding: string, callback: Function): void; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } - // Note: Transform lacks the _read and _write methods of Readable/Writable. - export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { - readable: boolean; - writable: boolean; - constructor(opts?: TransformOptions); - protected _transform(chunk: any, encoding: string, callback: Function): void; - protected _flush(callback: Function): void; - read(size?: number): any; - setEncoding(encoding: string): void; - pause(): Transform; - resume(): Transform; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: T): void; - unshift(chunk: any): void; - wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; - push(chunk: any, encoding?: string): boolean; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; - end(): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; - } + export interface TransformOptions extends ReadableOptions, WritableOptions {} - export class PassThrough extends Transform { } + // Note: Transform lacks the _read and _write methods of Readable/Writable. + export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { + readable: boolean; + writable: boolean; + constructor(opts?: TransformOptions); + _transform(chunk: Buffer, encoding: string, callback: Function): void; + _transform(chunk: string, encoding: string, callback: Function): void; + _flush(callback: Function): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; } - export = internal; + export class PassThrough extends Transform {} } declare module "util" { @@ -3396,24 +1253,11 @@ declare module "util" { export function isDate(object: any): boolean; export function isError(object: any): boolean; export function inherits(constructor: any, superConstructor: any): void; - export function debuglog(key: string): (msg: string, ...param: any[]) => void; - export function isBoolean(object: any): boolean; - export function isBuffer(object: any): boolean; - export function isFunction(object: any): boolean; - export function isNull(object: any): boolean; - export function isNullOrUndefined(object: any): boolean; - export function isNumber(object: any): boolean; - export function isObject(object: any): boolean; - export function isPrimitive(object: any): boolean; - export function isString(object: any): boolean; - export function isSymbol(object: any): boolean; - export function isUndefined(object: any): boolean; - export function deprecate(fn: Function, message: string): Function; } declare module "assert" { - function internal(value: any, message?: string): void; - namespace internal { + function internal (value: any, message?: string): void; + module internal { export class AssertionError implements Error { name: string; message: string; @@ -3422,13 +1266,11 @@ declare module "assert" { operator: string; generatedMessage: boolean; - constructor(options?: { - message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function - }); + constructor(options?: {message?: string; actual?: any; expected?: any; + operator?: string; stackStartFunction?: Function}); } - export function fail(actual: any, expected: any, message: string, operator: string): void; + export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; export function ok(value: any, message?: string): void; export function equal(actual: any, expected: any, message?: string): void; export function notEqual(actual: any, expected: any, message?: string): void; @@ -3436,8 +1278,6 @@ declare module "assert" { export function notDeepEqual(acutal: any, expected: any, message?: string): void; export function strictEqual(actual: any, expected: any, message?: string): void; export function notStrictEqual(actual: any, expected: any, message?: string): void; - export function deepStrictEqual(actual: any, expected: any, message?: string): void; - export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; export var throws: { (block: Function, message?: string): void; (block: Function, error: Function, message?: string): void; @@ -3459,341 +1299,36 @@ declare module "assert" { } declare module "tty" { - import * as net from "net"; + import net = require("net"); export function isatty(fd: number): boolean; export interface ReadStream extends net.Socket { isRaw: boolean; setRawMode(mode: boolean): void; - isTTY: boolean; } export interface WriteStream extends net.Socket { columns: number; rows: number; - isTTY: boolean; } } declare module "domain" { - import * as events from "events"; + import events = require("events"); - export class Domain extends events.EventEmitter implements NodeJS.Domain { + export class Domain extends events.EventEmitter { run(fn: Function): void; add(emitter: events.EventEmitter): void; remove(emitter: events.EventEmitter): void; bind(cb: (err: Error, data: any) => any): any; intercept(cb: (data: any) => any): any; dispose(): void; - members: any[]; - enter(): void; - exit(): void; - } - - export function create(): Domain; -} - -declare module "constants" { - export var E2BIG: number; - export var EACCES: number; - export var EADDRINUSE: number; - export var EADDRNOTAVAIL: number; - export var EAFNOSUPPORT: number; - export var EAGAIN: number; - export var EALREADY: number; - export var EBADF: number; - export var EBADMSG: number; - export var EBUSY: number; - export var ECANCELED: number; - export var ECHILD: number; - export var ECONNABORTED: number; - export var ECONNREFUSED: number; - export var ECONNRESET: number; - export var EDEADLK: number; - export var EDESTADDRREQ: number; - export var EDOM: number; - export var EEXIST: number; - export var EFAULT: number; - export var EFBIG: number; - export var EHOSTUNREACH: number; - export var EIDRM: number; - export var EILSEQ: number; - export var EINPROGRESS: number; - export var EINTR: number; - export var EINVAL: number; - export var EIO: number; - export var EISCONN: number; - export var EISDIR: number; - export var ELOOP: number; - export var EMFILE: number; - export var EMLINK: number; - export var EMSGSIZE: number; - export var ENAMETOOLONG: number; - export var ENETDOWN: number; - export var ENETRESET: number; - export var ENETUNREACH: number; - export var ENFILE: number; - export var ENOBUFS: number; - export var ENODATA: number; - export var ENODEV: number; - export var ENOENT: number; - export var ENOEXEC: number; - export var ENOLCK: number; - export var ENOLINK: number; - export var ENOMEM: number; - export var ENOMSG: number; - export var ENOPROTOOPT: number; - export var ENOSPC: number; - export var ENOSR: number; - export var ENOSTR: number; - export var ENOSYS: number; - export var ENOTCONN: number; - export var ENOTDIR: number; - export var ENOTEMPTY: number; - export var ENOTSOCK: number; - export var ENOTSUP: number; - export var ENOTTY: number; - export var ENXIO: number; - export var EOPNOTSUPP: number; - export var EOVERFLOW: number; - export var EPERM: number; - export var EPIPE: number; - export var EPROTO: number; - export var EPROTONOSUPPORT: number; - export var EPROTOTYPE: number; - export var ERANGE: number; - export var EROFS: number; - export var ESPIPE: number; - export var ESRCH: number; - export var ETIME: number; - export var ETIMEDOUT: number; - export var ETXTBSY: number; - export var EWOULDBLOCK: number; - export var EXDEV: number; - export var WSAEINTR: number; - export var WSAEBADF: number; - export var WSAEACCES: number; - export var WSAEFAULT: number; - export var WSAEINVAL: number; - export var WSAEMFILE: number; - export var WSAEWOULDBLOCK: number; - export var WSAEINPROGRESS: number; - export var WSAEALREADY: number; - export var WSAENOTSOCK: number; - export var WSAEDESTADDRREQ: number; - export var WSAEMSGSIZE: number; - export var WSAEPROTOTYPE: number; - export var WSAENOPROTOOPT: number; - export var WSAEPROTONOSUPPORT: number; - export var WSAESOCKTNOSUPPORT: number; - export var WSAEOPNOTSUPP: number; - export var WSAEPFNOSUPPORT: number; - export var WSAEAFNOSUPPORT: number; - export var WSAEADDRINUSE: number; - export var WSAEADDRNOTAVAIL: number; - export var WSAENETDOWN: number; - export var WSAENETUNREACH: number; - export var WSAENETRESET: number; - export var WSAECONNABORTED: number; - export var WSAECONNRESET: number; - export var WSAENOBUFS: number; - export var WSAEISCONN: number; - export var WSAENOTCONN: number; - export var WSAESHUTDOWN: number; - export var WSAETOOMANYREFS: number; - export var WSAETIMEDOUT: number; - export var WSAECONNREFUSED: number; - export var WSAELOOP: number; - export var WSAENAMETOOLONG: number; - export var WSAEHOSTDOWN: number; - export var WSAEHOSTUNREACH: number; - export var WSAENOTEMPTY: number; - export var WSAEPROCLIM: number; - export var WSAEUSERS: number; - export var WSAEDQUOT: number; - export var WSAESTALE: number; - export var WSAEREMOTE: number; - export var WSASYSNOTREADY: number; - export var WSAVERNOTSUPPORTED: number; - export var WSANOTINITIALISED: number; - export var WSAEDISCON: number; - export var WSAENOMORE: number; - export var WSAECANCELLED: number; - export var WSAEINVALIDPROCTABLE: number; - export var WSAEINVALIDPROVIDER: number; - export var WSAEPROVIDERFAILEDINIT: number; - export var WSASYSCALLFAILURE: number; - export var WSASERVICE_NOT_FOUND: number; - export var WSATYPE_NOT_FOUND: number; - export var WSA_E_NO_MORE: number; - export var WSA_E_CANCELLED: number; - export var WSAEREFUSED: number; - export var SIGHUP: number; - export var SIGINT: number; - export var SIGILL: number; - export var SIGABRT: number; - export var SIGFPE: number; - export var SIGKILL: number; - export var SIGSEGV: number; - export var SIGTERM: number; - export var SIGBREAK: number; - export var SIGWINCH: number; - export var SSL_OP_ALL: number; - export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; - export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; - export var SSL_OP_CISCO_ANYCONNECT: number; - export var SSL_OP_COOKIE_EXCHANGE: number; - export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; - export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; - export var SSL_OP_EPHEMERAL_RSA: number; - export var SSL_OP_LEGACY_SERVER_CONNECT: number; - export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; - export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; - export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; - export var SSL_OP_NETSCAPE_CA_DN_BUG: number; - export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; - export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; - export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; - export var SSL_OP_NO_COMPRESSION: number; - export var SSL_OP_NO_QUERY_MTU: number; - export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; - export var SSL_OP_NO_SSLv2: number; - export var SSL_OP_NO_SSLv3: number; - export var SSL_OP_NO_TICKET: number; - export var SSL_OP_NO_TLSv1: number; - export var SSL_OP_NO_TLSv1_1: number; - export var SSL_OP_NO_TLSv1_2: number; - export var SSL_OP_PKCS1_CHECK_1: number; - export var SSL_OP_PKCS1_CHECK_2: number; - export var SSL_OP_SINGLE_DH_USE: number; - export var SSL_OP_SINGLE_ECDH_USE: number; - export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; - export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; - export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; - export var SSL_OP_TLS_D5_BUG: number; - export var SSL_OP_TLS_ROLLBACK_BUG: number; - export var ENGINE_METHOD_DSA: number; - export var ENGINE_METHOD_DH: number; - export var ENGINE_METHOD_RAND: number; - export var ENGINE_METHOD_ECDH: number; - export var ENGINE_METHOD_ECDSA: number; - export var ENGINE_METHOD_CIPHERS: number; - export var ENGINE_METHOD_DIGESTS: number; - export var ENGINE_METHOD_STORE: number; - export var ENGINE_METHOD_PKEY_METHS: number; - export var ENGINE_METHOD_PKEY_ASN1_METHS: number; - export var ENGINE_METHOD_ALL: number; - export var ENGINE_METHOD_NONE: number; - export var DH_CHECK_P_NOT_SAFE_PRIME: number; - export var DH_CHECK_P_NOT_PRIME: number; - export var DH_UNABLE_TO_CHECK_GENERATOR: number; - export var DH_NOT_SUITABLE_GENERATOR: number; - export var NPN_ENABLED: number; - export var RSA_PKCS1_PADDING: number; - export var RSA_SSLV23_PADDING: number; - export var RSA_NO_PADDING: number; - export var RSA_PKCS1_OAEP_PADDING: number; - export var RSA_X931_PADDING: number; - export var RSA_PKCS1_PSS_PADDING: number; - export var POINT_CONVERSION_COMPRESSED: number; - export var POINT_CONVERSION_UNCOMPRESSED: number; - export var POINT_CONVERSION_HYBRID: number; - export var O_RDONLY: number; - export var O_WRONLY: number; - export var O_RDWR: number; - export var S_IFMT: number; - export var S_IFREG: number; - export var S_IFDIR: number; - export var S_IFCHR: number; - export var S_IFBLK: number; - export var S_IFIFO: number; - export var S_IFSOCK: number; - export var S_IRWXU: number; - export var S_IRUSR: number; - export var S_IWUSR: number; - export var S_IXUSR: number; - export var S_IRWXG: number; - export var S_IRGRP: number; - export var S_IWGRP: number; - export var S_IXGRP: number; - export var S_IRWXO: number; - export var S_IROTH: number; - export var S_IWOTH: number; - export var S_IXOTH: number; - export var S_IFLNK: number; - export var O_CREAT: number; - export var O_EXCL: number; - export var O_NOCTTY: number; - export var O_DIRECTORY: number; - export var O_NOATIME: number; - export var O_NOFOLLOW: number; - export var O_SYNC: number; - export var O_SYMLINK: number; - export var O_DIRECT: number; - export var O_NONBLOCK: number; - export var O_TRUNC: number; - export var O_APPEND: number; - export var F_OK: number; - export var R_OK: number; - export var W_OK: number; - export var X_OK: number; - export var UV_UDP_REUSEADDR: number; - export var SIGQUIT: number; - export var SIGTRAP: number; - export var SIGIOT: number; - export var SIGBUS: number; - export var SIGUSR1: number; - export var SIGUSR2: number; - export var SIGPIPE: number; - export var SIGALRM: number; - export var SIGCHLD: number; - export var SIGSTKFLT: number; - export var SIGCONT: number; - export var SIGSTOP: number; - export var SIGTSTP: number; - export var SIGTTIN: number; - export var SIGTTOU: number; - export var SIGURG: number; - export var SIGXCPU: number; - export var SIGXFSZ: number; - export var SIGVTALRM: number; - export var SIGPROF: number; - export var SIGIO: number; - export var SIGPOLL: number; - export var SIGPWR: number; - export var SIGSYS: number; - export var SIGUNUSED: number; - export var defaultCoreCipherList: string; - export var defaultCipherList: string; - export var ENGINE_METHOD_RSA: number; - export var ALPN_ENABLED: number; -} - -declare module "process" { - export = process; -} -declare module "v8" { - interface HeapSpaceInfo { - space_name: string; - space_size: number; - space_used_size: number; - space_available_size: number; - physical_space_size: number; + addListener(event: string, listener: Function): Domain; + on(event: string, listener: Function): Domain; + once(event: string, listener: Function): Domain; + removeListener(event: string, listener: Function): Domain; + removeAllListeners(event?: string): Domain; } - export function getHeapStatistics(): { total_heap_size: number, total_heap_size_executable: number, total_physical_size: number, total_avaialble_size: number, used_heap_size: number, heap_size_limit: number }; - export function getHeapSpaceStatistics(): HeapSpaceInfo[]; - export function setFlagsFromString(flags: string): void; -} -declare module "timers" { - export function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; - export function clearTimeout(timeoutId: NodeJS.Timer): void; - export function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; - export function clearInterval(intervalId: NodeJS.Timer): void; - export function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; - export function clearImmediate(immediateId: any): void; + export function create(): Domain; } - -declare module "console" { - export = console; -} \ No newline at end of file From 5f814334b4519671e2221062dc34b776918d1251 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Mon, 24 Oct 2016 21:32:11 +0100 Subject: [PATCH 06/17] embrace the triple equals --- src/index.ts | 10 ++++++---- src/tslint.json | 3 +++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/index.ts b/src/index.ts index 6efa3f8a9..4a6105afa 100644 --- a/src/index.ts +++ b/src/index.ts @@ -176,7 +176,7 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade filesToLoad = configParseResult.fileNames; // if `module` is not specified and not using ES6 target, default to CJS module output - if (compilerOptions.module == null && compilerOptions.target !== 2 /* ES6 */) { + if ((!compilerOptions.module) && compilerOptions.target !== 2 /* ES6 */) { compilerOptions.module = 1; /* CommonJS */ } else if (compilerCompatible && semver.lt(compiler.version, '1.7.3-0') && compilerOptions.target === 2 /* ES6 */) { // special handling for TS 1.6 and target: es6 @@ -244,7 +244,7 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade if (!file) { let text = utils.readFile(fileName); - if (text == null) return; + if (!text) { return; } file = files[fileName] = { version: 0, text }; } @@ -296,7 +296,7 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade resolvedModules.push(resolutionResult); } - let importedFiles = resolvedModules.filter(m => m != null).map(m => m.resolvedFileName); + let importedFiles = resolvedModules.filter(m => m).map(m => m.resolvedFileName); instance.dependencyGraph[path.normalize(containingFile)] = importedFiles; importedFiles.forEach(importedFileName => { if (!instance.reverseDependencyGraph[importedFileName]) { @@ -582,7 +582,9 @@ function loader(contents: string) { if (sourceMapFile) { sourceMapText = sourceMapFile.text; } } - if (outputText == null) throw new Error(`Typescript emitted no output for ${filePath}`); + if (outputText === null || outputText === undefined) { + throw new Error(`Typescript emitted no output for ${filePath}`); + } let sourceMap: { sources: any[], file: string; sourcesContent: string[] }; if (sourceMapText) { diff --git a/src/tslint.json b/src/tslint.json index 63c51d145..7e468b8a9 100644 --- a/src/tslint.json +++ b/src/tslint.json @@ -14,6 +14,9 @@ "single" ], "no-trailing-comma": true, + "triple-equals": [ + true + ], "variable-name": [true, "ban-keywords", "check-format", From f850b7cdb4b787799a38fd5b853a6fb071d2f66e Mon Sep 17 00:00:00 2001 From: John Reilly Date: Mon, 24 Oct 2016 22:04:08 +0100 Subject: [PATCH 07/17] make changes back compatible --- src/constants.ts | 4 +++- src/index.ts | 10 ++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/constants.ts b/src/constants.ts index 194187109..4b81de541 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -1,3 +1,5 @@ import os = require('os'); -export var EOL = os.EOL; +export const EOL = os.EOL; +export const CarriageReturnLineFeed = '\r\n'; +export const LineFeed = '\n'; diff --git a/src/index.ts b/src/index.ts index 4a6105afa..668099a11 100644 --- a/src/index.ts +++ b/src/index.ts @@ -216,8 +216,8 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade } let newLine = - compilerOptions.newLine === 0 /* CarriageReturnLineFeed */ ? '\r\n' : - compilerOptions.newLine === 1 /* LineFeed */ ? '\n' : + compilerOptions.newLine === 0 /* CarriageReturnLineFeed */ ? constants.CarriageReturnLineFeed : + compilerOptions.newLine === 1 /* LineFeed */ ? constants.LineFeed : constants.EOL; // make a (sync) resolver that follows webpack's rules @@ -230,7 +230,7 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade // Create the TypeScript language service const servicesHost = { - getProjectVersion: () => instance.version + '', + getProjectVersion: () => `${instance.version}`, getScriptFileNames: () => Object.keys(files).filter(filePath => scriptRegex.test(filePath)), getScriptVersion: (fileName: string) => { fileName = path.normalize(fileName); @@ -296,7 +296,9 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade resolvedModules.push(resolutionResult); } - let importedFiles = resolvedModules.filter(m => m).map(m => m.resolvedFileName); + let importedFiles = resolvedModules + .filter(m => m !== null && m !== undefined) + .map(m => m.resolvedFileName); instance.dependencyGraph[path.normalize(containingFile)] = importedFiles; importedFiles.forEach(importedFileName => { if (!instance.reverseDependencyGraph[importedFileName]) { From 5d2fa67a6a197e82a98115322530049fead1bbde Mon Sep 17 00:00:00 2001 From: John Reilly Date: Mon, 24 Oct 2016 22:06:26 +0100 Subject: [PATCH 08/17] make changes compatible with TS 1.6/1.7/1.8 --- src/index.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/index.ts b/src/index.ts index 668099a11..95c4a1862 100644 --- a/src/index.ts +++ b/src/index.ts @@ -296,7 +296,7 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade resolvedModules.push(resolutionResult); } - let importedFiles = resolvedModules + const importedFiles = resolvedModules .filter(m => m !== null && m !== undefined) .map(m => m.resolvedFileName); instance.dependencyGraph[path.normalize(containingFile)] = importedFiles; @@ -307,7 +307,6 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade instance.reverseDependencyGraph[importedFileName][path.normalize(containingFile)] = true; }); - return resolvedModules; }, }; From 79e8c7039a26c7ba5d7471f2915d1a46735509c4 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Mon, 24 Oct 2016 22:33:04 +0100 Subject: [PATCH 09/17] drop prepublish move node version back to 4.0, add 5 and 6 to travis as well make ts-loader compile prior to global installation of typescript build now reports typescript version --- .travis.yml | 3 +++ appveyor.yml | 4 ++-- package.json | 5 ++--- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 1dacf8ecf..68ba36706 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,12 @@ language: node_js node_js: + - "4.0" + - "5.0" - "6.0" sudo: false install: - npm install + - npm run build - npm install $TYPESCRIPT env: - TYPESCRIPT=typescript@1.6.2 diff --git a/appveyor.yml b/appveyor.yml index 2736ac3e3..18b352788 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,5 +1,5 @@ environment: - nodejs_version: "6.0" + nodejs_version: "4.0" matrix: - TYPESCRIPT: typescript@1.6.2 - TYPESCRIPT: typescript@1.7.5 @@ -9,10 +9,10 @@ environment: install: - ps: Install-Product node $env:nodejs_version - npm install + - npm run build - npm install %TYPESCRIPT% test_script: - node --version - npm --version - - npm run build - npm test build: off diff --git a/package.json b/package.json index 1787fdaf2..9769cacd5 100644 --- a/package.json +++ b/package.json @@ -4,11 +4,10 @@ "description": "TypeScript loader for webpack", "main": "index.js", "scripts": { - "build": "tsc --project \"./src\"", + "build": "tsc --version && tsc --project \"./src\"", "comparison-tests": "npm link ./test/comparison-tests/testLib && node test/comparison-tests/run-tests.js", "execution-tests": "node test/execution-tests/run-tests.js", - "test": "node test/run-tests.js", - "prepublish": "npm run build" + "test": "node test/run-tests.js" }, "repository": { "type": "git", From 1e30623600c83e27273914cab55f07ecfc093553 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Mon, 24 Oct 2016 22:49:28 +0100 Subject: [PATCH 10/17] tslint no longer a dependency --- package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/package.json b/package.json index 9769cacd5..f446c3328 100644 --- a/package.json +++ b/package.json @@ -58,7 +58,6 @@ "mocha": "^3.1.0", "phantomjs-prebuilt": "^2.1.2", "rimraf": "^2.4.2", - "tslint": "^3.15.1", "typescript": "^2.0.3", "typings": "^1.4.0", "webpack": "^1.11.0" From d3f18308ab4fe113bf92e6a4e29dd47b3b53e283 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Tue, 25 Oct 2016 14:10:03 +0100 Subject: [PATCH 11/17] Update appveyor.yml --- appveyor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index 18b352788..a91901261 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,5 +1,5 @@ environment: - nodejs_version: "4.0" + nodejs_version: "6.0" matrix: - TYPESCRIPT: typescript@1.6.2 - TYPESCRIPT: typescript@1.7.5 From 94fb7dbccc0922837ae28e8715fd037126135669 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Tue, 25 Oct 2016 14:35:08 +0100 Subject: [PATCH 12/17] Update .travis.yml --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 68ba36706..899e5cddb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,6 +5,7 @@ node_js: - "6.0" sudo: false install: + - npm install npm -g - npm install - npm run build - npm install $TYPESCRIPT From d782e93c8e2a1e030e39495857938027ad596055 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Tue, 25 Oct 2016 21:15:40 +0100 Subject: [PATCH 13/17] ensure that when using ts 2 features the tests still run using a *different* version of ts remove "files": [] occurrences in tsconfig.jsons of test pack to cater for change in compiler behaviour in ts 2.1: https://github.com/Microsoft/TypeScript/pull/11743 --- test/comparison-tests/babel-issue81/tsconfig.json | 3 +-- test/comparison-tests/dependencyErrors/tsconfig.json | 3 +-- test/comparison-tests/errors/tsconfig.json | 3 +-- test/comparison-tests/ignoreDiagnostics/tsconfig.json | 3 +-- test/comparison-tests/importsWatch/tsconfig.json | 3 +-- test/comparison-tests/node/tsconfig.json | 3 +-- test/comparison-tests/nolib/tsconfig.json | 3 +-- test/comparison-tests/npmLink/tsconfig.json | 3 +-- test/comparison-tests/replacement/tsconfig.json | 3 +-- test/comparison-tests/simpleDependency/tsconfig.json | 3 +-- test/comparison-tests/sourceMaps/tsconfig.json | 3 +-- test/comparison-tests/typeSystemWatch/tsconfig.json | 4 +++- test/execution-tests/simpleDependency/tsconfig.json | 3 +-- 13 files changed, 15 insertions(+), 25 deletions(-) diff --git a/test/comparison-tests/babel-issue81/tsconfig.json b/test/comparison-tests/babel-issue81/tsconfig.json index 15262ce6e..c82ccfa51 100644 --- a/test/comparison-tests/babel-issue81/tsconfig.json +++ b/test/comparison-tests/babel-issue81/tsconfig.json @@ -3,6 +3,5 @@ "target": "es6", "sourceMap": true, "experimentalDecorators": true - }, - "files": [] + } } \ No newline at end of file diff --git a/test/comparison-tests/dependencyErrors/tsconfig.json b/test/comparison-tests/dependencyErrors/tsconfig.json index fc16344c1..0efa0a638 100644 --- a/test/comparison-tests/dependencyErrors/tsconfig.json +++ b/test/comparison-tests/dependencyErrors/tsconfig.json @@ -1,5 +1,4 @@ { "compilerOptions": { - }, - "files": [] + } } \ No newline at end of file diff --git a/test/comparison-tests/errors/tsconfig.json b/test/comparison-tests/errors/tsconfig.json index fc16344c1..0efa0a638 100644 --- a/test/comparison-tests/errors/tsconfig.json +++ b/test/comparison-tests/errors/tsconfig.json @@ -1,5 +1,4 @@ { "compilerOptions": { - }, - "files": [] + } } \ No newline at end of file diff --git a/test/comparison-tests/ignoreDiagnostics/tsconfig.json b/test/comparison-tests/ignoreDiagnostics/tsconfig.json index fc16344c1..0efa0a638 100644 --- a/test/comparison-tests/ignoreDiagnostics/tsconfig.json +++ b/test/comparison-tests/ignoreDiagnostics/tsconfig.json @@ -1,5 +1,4 @@ { "compilerOptions": { - }, - "files": [] + } } \ No newline at end of file diff --git a/test/comparison-tests/importsWatch/tsconfig.json b/test/comparison-tests/importsWatch/tsconfig.json index fc16344c1..0efa0a638 100644 --- a/test/comparison-tests/importsWatch/tsconfig.json +++ b/test/comparison-tests/importsWatch/tsconfig.json @@ -1,5 +1,4 @@ { "compilerOptions": { - }, - "files": [] + } } \ No newline at end of file diff --git a/test/comparison-tests/node/tsconfig.json b/test/comparison-tests/node/tsconfig.json index fc16344c1..0efa0a638 100644 --- a/test/comparison-tests/node/tsconfig.json +++ b/test/comparison-tests/node/tsconfig.json @@ -1,5 +1,4 @@ { "compilerOptions": { - }, - "files": [] + } } \ No newline at end of file diff --git a/test/comparison-tests/nolib/tsconfig.json b/test/comparison-tests/nolib/tsconfig.json index ac89b38f8..db841f124 100644 --- a/test/comparison-tests/nolib/tsconfig.json +++ b/test/comparison-tests/nolib/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { "noLib": true - }, - "files": [] + } } \ No newline at end of file diff --git a/test/comparison-tests/npmLink/tsconfig.json b/test/comparison-tests/npmLink/tsconfig.json index fa51fe925..f28c8052c 100644 --- a/test/comparison-tests/npmLink/tsconfig.json +++ b/test/comparison-tests/npmLink/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { "module": "commonjs" - }, - "files": [] + } } \ No newline at end of file diff --git a/test/comparison-tests/replacement/tsconfig.json b/test/comparison-tests/replacement/tsconfig.json index fc16344c1..0efa0a638 100644 --- a/test/comparison-tests/replacement/tsconfig.json +++ b/test/comparison-tests/replacement/tsconfig.json @@ -1,5 +1,4 @@ { "compilerOptions": { - }, - "files": [] + } } \ No newline at end of file diff --git a/test/comparison-tests/simpleDependency/tsconfig.json b/test/comparison-tests/simpleDependency/tsconfig.json index fc16344c1..0efa0a638 100644 --- a/test/comparison-tests/simpleDependency/tsconfig.json +++ b/test/comparison-tests/simpleDependency/tsconfig.json @@ -1,5 +1,4 @@ { "compilerOptions": { - }, - "files": [] + } } \ No newline at end of file diff --git a/test/comparison-tests/sourceMaps/tsconfig.json b/test/comparison-tests/sourceMaps/tsconfig.json index 96c4e44fd..40470b346 100644 --- a/test/comparison-tests/sourceMaps/tsconfig.json +++ b/test/comparison-tests/sourceMaps/tsconfig.json @@ -1,6 +1,5 @@ { "compilerOptions": { "sourceMap": true - }, - "files": [] + } } \ No newline at end of file diff --git a/test/comparison-tests/typeSystemWatch/tsconfig.json b/test/comparison-tests/typeSystemWatch/tsconfig.json index fc16344c1..e2edf650a 100644 --- a/test/comparison-tests/typeSystemWatch/tsconfig.json +++ b/test/comparison-tests/typeSystemWatch/tsconfig.json @@ -1,5 +1,7 @@ { "compilerOptions": { }, - "files": [] + "files": [ + "app.ts" + ] } \ No newline at end of file diff --git a/test/execution-tests/simpleDependency/tsconfig.json b/test/execution-tests/simpleDependency/tsconfig.json index fc16344c1..0efa0a638 100644 --- a/test/execution-tests/simpleDependency/tsconfig.json +++ b/test/execution-tests/simpleDependency/tsconfig.json @@ -1,5 +1,4 @@ { "compilerOptions": { - }, - "files": [] + } } \ No newline at end of file From 79e02a1ed811076e8a8d96031b7c6cd67cb036e8 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Tue, 25 Oct 2016 21:47:07 +0100 Subject: [PATCH 14/17] change output of loader to dist folder --- .gitignore | 1 + .npmignore | 1 + index.js | 2 +- src/tsconfig.json | 3 ++- 4 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 189374f07..884610dd2 100644 --- a/.gitignore +++ b/.gitignore @@ -10,4 +10,5 @@ npm-debug.log /test/execution-tests/**/typings !/test/**/expectedOutput-*/** /node_modules +/dist !build.js diff --git a/.npmignore b/.npmignore index 534661f31..d40cd89f4 100644 --- a/.npmignore +++ b/.npmignore @@ -1,4 +1,5 @@ *.ts test .* +src typings \ No newline at end of file diff --git a/index.js b/index.js index b6e436d0e..8a47bdc5c 100644 --- a/index.js +++ b/index.js @@ -1,3 +1,3 @@ -var loader = require('./src'); +var loader = require('./dist'); module.exports = loader; \ No newline at end of file diff --git a/src/tsconfig.json b/src/tsconfig.json index 9fe417fe7..91402039e 100644 --- a/src/tsconfig.json +++ b/src/tsconfig.json @@ -3,6 +3,7 @@ "noImplicitAny": true, "suppressImplicitAnyIndexErrors": true, "module": "commonjs", - "moduleResolution": "node" + "moduleResolution": "node", + "outDir": "../dist" } } \ No newline at end of file From 86bef3e4652525f9be0e3d07bf137b6c3e8552cd Mon Sep 17 00:00:00 2001 From: John Reilly Date: Tue, 25 Oct 2016 23:26:02 +0100 Subject: [PATCH 15/17] Split out watch-run and after-compile into distinct modules --- src/after-compile.ts | 164 +++++++++++++++++++++++++ src/index.ts | 282 ++----------------------------------------- src/logger.ts | 29 +++-- src/servicesHost.ts | 118 ++++++++++++++++++ src/watch-run.ts | 34 ++++++ 5 files changed, 346 insertions(+), 281 deletions(-) create mode 100644 src/after-compile.ts create mode 100644 src/servicesHost.ts create mode 100644 src/watch-run.ts diff --git a/src/after-compile.ts b/src/after-compile.ts new file mode 100644 index 000000000..ad8198691 --- /dev/null +++ b/src/after-compile.ts @@ -0,0 +1,164 @@ +import typescript = require('typescript'); +import interfaces = require('./interfaces'); +import path = require('path'); +import utils = require('./utils'); + +function makeAfterCompile( + instance: interfaces.TSInstance, + compiler: typeof typescript, + servicesHost: typescript.LanguageServiceHost, + configFilePath: string +) { + const languageService = instance.languageService = compiler.createLanguageService(servicesHost, compiler.createDocumentRegistry()); + + let getCompilerOptionDiagnostics = true; + let checkAllFilesForErrors = true; + + return (compilation: interfaces.WebpackCompilation, callback: () => void) => { + // Don't add errors for child compilations + if (compilation.compiler.isChild()) { + callback(); + return; + } + + removeTSLoaderErrors(compilation.errors); + + // handle compiler option errors after the first compile + if (getCompilerOptionDiagnostics) { + getCompilerOptionDiagnostics = false; + utils.pushArray( + compilation.errors, + utils.formatErrors(languageService.getCompilerOptionsDiagnostics(), instance, { file: configFilePath || 'tsconfig.json' })); + } + + // build map of all modules based on normalized filename + // this is used for quick-lookup when trying to find modules + // based on filepath + let modules: { [modulePath: string]: interfaces.WebpackModule[] } = {}; + compilation.modules.forEach(module => { + if (module.resource) { + let modulePath = path.normalize(module.resource); + if (utils.hasOwnProperty(modules, modulePath)) { + let existingModules = modules[modulePath]; + if (existingModules.indexOf(module) === -1) { + existingModules.push(module); + } + } + else { + modules[modulePath] = [module]; + } + } + }); + + // gather all errors from TypeScript and output them to webpack + let filesWithErrors: interfaces.TSFiles = {}; + // calculate array of files to check + let filesToCheckForErrors: interfaces.TSFiles = null; + if (checkAllFilesForErrors) { + // check all files on initial run + filesToCheckForErrors = instance.files; + checkAllFilesForErrors = false; + } else { + filesToCheckForErrors = {}; + // check all modified files, and all dependants + Object.keys(instance.modifiedFiles).forEach(modifiedFileName => { + collectAllDependants(instance, modifiedFileName).forEach(fName => { + filesToCheckForErrors[fName] = instance.files[fName]; + }); + }); + } + // re-check files with errors from previous build + if (instance.filesWithErrors) { + Object.keys(instance.filesWithErrors).forEach(fileWithErrorName => + filesToCheckForErrors[fileWithErrorName] = instance.filesWithErrors[fileWithErrorName] + ); + } + + Object.keys(filesToCheckForErrors) + .filter(filePath => !!filePath.match(/(\.d)?\.ts(x?)$/)) + .forEach(filePath => { + let errors = languageService.getSyntacticDiagnostics(filePath).concat(languageService.getSemanticDiagnostics(filePath)); + if (errors.length > 0) { + if (null === filesWithErrors) { + filesWithErrors = {}; + } + filesWithErrors[filePath] = instance.files[filePath]; + } + + // if we have access to a webpack module, use that + if (utils.hasOwnProperty(modules, filePath)) { + let associatedModules = modules[filePath]; + + associatedModules.forEach(module => { + // remove any existing errors + removeTSLoaderErrors(module.errors); + + // append errors + let formattedErrors = utils.formatErrors(errors, instance, { module }); + utils.pushArray(module.errors, formattedErrors); + utils.pushArray(compilation.errors, formattedErrors); + }); + } + // otherwise it's a more generic error + else { + utils.pushArray(compilation.errors, utils.formatErrors(errors, instance, { file: filePath })); + } + }); + + + // gather all declaration files from TypeScript and output them to webpack + Object.keys(filesToCheckForErrors) + .filter(filePath => !!filePath.match(/\.ts(x?)$/)) + .forEach(filePath => { + let output = languageService.getEmitOutput(filePath); + let declarationFile = output.outputFiles.filter(filePath => !!filePath.name.match(/\.d.ts$/)).pop(); + if (declarationFile) { + let assetPath = path.relative(compilation.compiler.context, declarationFile.name); + compilation.assets[assetPath] = { + source: () => declarationFile.text, + size: () => declarationFile.text.length, + }; + } + }); + + instance.filesWithErrors = filesWithErrors; + instance.modifiedFiles = null; + callback(); + } +} + +/** + * handle all other errors. The basic approach here to get accurate error + * reporting is to start with a "blank slate" each compilation and gather + * all errors from all files. Since webpack tracks errors in a module from + * compilation-to-compilation, and since not every module always runs through + * the loader, we need to detect and remove any pre-existing errors. + */ +function removeTSLoaderErrors(errors: interfaces.WebpackError[]) { + let index = -1, length = errors.length; + while (++index < length) { + if (errors[index].loaderSource === 'ts-loader') { + errors.splice(index--, 1); + length--; + } + } +} + +/** + * Recursively collect all possible dependants of passed file + */ +function collectAllDependants(instance: interfaces.TSInstance, fileName: string, collected: any = {}): string[] { + let result = {}; + result[fileName] = true; + collected[fileName] = true; + if (instance.reverseDependencyGraph[fileName]) { + Object.keys(instance.reverseDependencyGraph[fileName]).forEach(dependantFileName => { + if (!collected[dependantFileName]) { + collectAllDependants(instance, dependantFileName, collected).forEach(fName => result[fName] = true); + } + }); + } + return Object.keys(result); +} + +export = makeAfterCompile; \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 95c4a1862..1bc13c9c7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,13 +4,16 @@ import fs = require('fs'); import loaderUtils = require('loader-utils'); import objectAssign = require('object-assign'); import arrify = require('arrify'); -import makeResolver = require('./resolver'); +const semver = require('semver'); +require('colors'); + +import afterCompile = require('./after-compile'); import interfaces = require('./interfaces'); import constants = require('./constants'); import utils = require('./utils'); -import getLogger = require('./logger'); -const semver = require('semver'); -require('colors'); +import logger = require('./logger'); +import makeServicesHost = require('./servicesHost'); +import watchRun = require('./watch-run'); let instances = {}; let webpackInstances: any = []; @@ -61,7 +64,7 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade } }; } - const log = getLogger(loaderOptions); + const log = logger.makeLogger(loaderOptions); const motd = `ts-loader: Using ${loaderOptions.compiler}@${compiler.version}`; let compilerCompatible = false; if (loaderOptions.compiler === 'typescript') { @@ -215,273 +218,10 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade }}; } - let newLine = - compilerOptions.newLine === 0 /* CarriageReturnLineFeed */ ? constants.CarriageReturnLineFeed : - compilerOptions.newLine === 1 /* LineFeed */ ? constants.LineFeed : - constants.EOL; - - // make a (sync) resolver that follows webpack's rules - let resolver = makeResolver(loader.options); - - const moduleResolutionHost = { - fileExists: (fileName: string) => utils.readFile(fileName) !== undefined, - readFile: (fileName: string) => utils.readFile(fileName), - }; - - // Create the TypeScript language service - const servicesHost = { - getProjectVersion: () => `${instance.version}`, - getScriptFileNames: () => Object.keys(files).filter(filePath => scriptRegex.test(filePath)), - getScriptVersion: (fileName: string) => { - fileName = path.normalize(fileName); - return files[fileName] && files[fileName].version.toString(); - }, - getScriptSnapshot: (fileName: string) => { - // This is called any time TypeScript needs a file's text - // We either load from memory or from disk - fileName = path.normalize(fileName); - let file = files[fileName]; - - if (!file) { - let text = utils.readFile(fileName); - if (!text) { return; } - - file = files[fileName] = { version: 0, text }; - } - - return compiler.ScriptSnapshot.fromString(file.text); - }, - /** - * getDirectories is also required for full import and type reference completions. - * Without it defined, certain completions will not be provided - */ - getDirectories: typescript.sys ? ( typescript.sys).getDirectories : undefined, - - /** - * For @types expansion, these two functions are needed. - */ - directoryExists: typescript.sys ? ( typescript.sys).directoryExists : undefined, - getCurrentDirectory: () => process.cwd(), - - getCompilationSettings: () => compilerOptions, - getDefaultLibFileName: (options: typescript.CompilerOptions) => compiler.getDefaultLibFilePath(options), - getNewLine: () => newLine, - log: log.log, - resolveModuleNames: (moduleNames: string[], containingFile: string) => { - let resolvedModules: interfaces.ResolvedModule[] = []; - - for (let moduleName of moduleNames) { - let resolvedFileName: string; - let resolutionResult: any; - - try { - resolvedFileName = resolver.resolveSync(path.normalize(path.dirname(containingFile)), moduleName); - - if (!resolvedFileName.match(scriptRegex)) resolvedFileName = null; - else resolutionResult = { resolvedFileName }; - } - catch (e) { resolvedFileName = null; } - - let tsResolution = compiler.resolveModuleName(moduleName, containingFile, compilerOptions, moduleResolutionHost); - - if (tsResolution.resolvedModule) { - if (resolvedFileName) { - if (resolvedFileName === tsResolution.resolvedModule.resolvedFileName) { - resolutionResult.isExternalLibraryImport = tsResolution.resolvedModule.isExternalLibraryImport; - } - } - else resolutionResult = tsResolution.resolvedModule; - } - - resolvedModules.push(resolutionResult); - } - - const importedFiles = resolvedModules - .filter(m => m !== null && m !== undefined) - .map(m => m.resolvedFileName); - instance.dependencyGraph[path.normalize(containingFile)] = importedFiles; - importedFiles.forEach(importedFileName => { - if (!instance.reverseDependencyGraph[importedFileName]) { - instance.reverseDependencyGraph[importedFileName] = {}; - } - instance.reverseDependencyGraph[importedFileName][path.normalize(containingFile)] = true; - }); - - return resolvedModules; - }, - }; - - const languageService = instance.languageService = compiler.createLanguageService(servicesHost, compiler.createDocumentRegistry()); - - let getCompilerOptionDiagnostics = true; - let checkAllFilesForErrors = true; - - loader._compiler.plugin("after-compile", (compilation: interfaces.WebpackCompilation, callback: () => void) => { - // Don't add errors for child compilations - if (compilation.compiler.isChild()) { - callback(); - return; - } - - // handle all other errors. The basic approach here to get accurate error - // reporting is to start with a "blank slate" each compilation and gather - // all errors from all files. Since webpack tracks errors in a module from - // compilation-to-compilation, and since not every module always runs through - // the loader, we need to detect and remove any pre-existing errors. - - function removeTSLoaderErrors(errors: interfaces.WebpackError[]) { - let index = -1, length = errors.length; - while (++index < length) { - if (errors[index].loaderSource === 'ts-loader') { - errors.splice(index--, 1); - length--; - } - } - } - - /** - * Recursive collect all possible dependats of passed file - */ - function collectAllDependants(fileName: string, collected: any = {}): string[] { - let result = {}; - result[fileName] = true; - collected[fileName] = true; - if (instance.reverseDependencyGraph[fileName]) { - Object.keys(instance.reverseDependencyGraph[fileName]).forEach(dependantFileName => { - if (!collected[dependantFileName]) { - collectAllDependants(dependantFileName, collected).forEach(fName => result[fName] = true); - } - }); - } - return Object.keys(result); - } - - removeTSLoaderErrors(compilation.errors); - - // handle compiler option errors after the first compile - if (getCompilerOptionDiagnostics) { - getCompilerOptionDiagnostics = false; - utils.pushArray( - compilation.errors, - utils.formatErrors(languageService.getCompilerOptionsDiagnostics(), instance, {file: configFilePath || 'tsconfig.json'})); - } - - // build map of all modules based on normalized filename - // this is used for quick-lookup when trying to find modules - // based on filepath - let modules: { [modulePath: string]: interfaces.WebpackModule[]} = {}; - compilation.modules.forEach(module => { - if (module.resource) { - let modulePath = path.normalize(module.resource); - if (utils.hasOwnProperty(modules, modulePath)) { - let existingModules = modules[modulePath]; - if (existingModules.indexOf(module) === -1) { - existingModules.push(module); - } - } - else { - modules[modulePath] = [module]; - } - } - }); - - // gather all errors from TypeScript and output them to webpack - let filesWithErrors: interfaces.TSFiles = {}; - // calculate array of files to check - let filesToCheckForErrors: interfaces.TSFiles = null; - if (checkAllFilesForErrors) { - // check all files on initial run - filesToCheckForErrors = instance.files; - checkAllFilesForErrors = false; - } else { - filesToCheckForErrors = {}; - // check all modified files, and all dependants - Object.keys(instance.modifiedFiles).forEach(modifiedFileName => { - collectAllDependants(modifiedFileName).forEach(fName => { - filesToCheckForErrors[fName] = instance.files[fName]; - }); - }); - } - // re-check files with errors from previous build - if (instance.filesWithErrors) { - Object.keys(instance.filesWithErrors).forEach(fileWithErrorName => - filesToCheckForErrors[fileWithErrorName] = instance.filesWithErrors[fileWithErrorName] - ); - } - - Object.keys(filesToCheckForErrors) - .filter(filePath => !!filePath.match(/(\.d)?\.ts(x?)$/)) - .forEach(filePath => { - let errors = languageService.getSyntacticDiagnostics(filePath).concat(languageService.getSemanticDiagnostics(filePath)); - if (errors.length > 0) { - if (null === filesWithErrors) { - filesWithErrors = {}; - } - filesWithErrors[filePath] = instance.files[filePath]; - } - - // if we have access to a webpack module, use that - if (utils.hasOwnProperty(modules, filePath)) { - let associatedModules = modules[filePath]; - - associatedModules.forEach(module => { - // remove any existing errors - removeTSLoaderErrors(module.errors); - - // append errors - let formattedErrors = utils.formatErrors(errors, instance, { module }); - utils.pushArray(module.errors, formattedErrors); - utils.pushArray(compilation.errors, formattedErrors); - }); - } - // otherwise it's a more generic error - else { - utils.pushArray(compilation.errors, utils.formatErrors(errors, instance, {file: filePath})); - } - }); - - - // gather all declaration files from TypeScript and output them to webpack - Object.keys(filesToCheckForErrors) - .filter(filePath => !!filePath.match(/\.ts(x?)$/)) - .forEach(filePath => { - let output = languageService.getEmitOutput(filePath); - let declarationFile = output.outputFiles.filter(filePath => !!filePath.name.match(/\.d.ts$/)).pop(); - if (declarationFile) { - let assetPath = path.relative(compilation.compiler.context, declarationFile.name); - compilation.assets[assetPath] = { - source: () => declarationFile.text, - size: () => declarationFile.text.length, - }; - } - }); - - instance.filesWithErrors = filesWithErrors; - instance.modifiedFiles = null; - callback(); - }); - - // manually update changed files - loader._compiler.plugin("watch-run", (watching: interfaces.WebpackWatching, cb: () => void) => { - const mtimes = watching.compiler.watchFileSystem.watcher.mtimes; - if (null === instance.modifiedFiles) { - instance.modifiedFiles = {}; - } + const servicesHost = makeServicesHost(files, scriptRegex, log, loader, compilerOptions, instance, compiler, configFilePath); - Object.keys(mtimes) - .filter(filePath => !!filePath.match(/\.tsx?$|\.jsx?$/)) - .forEach(filePath => { - filePath = path.normalize(filePath); - const file = instance.files[filePath]; - if (file) { - file.text = utils.readFile(filePath) || ''; - file.version++; - instance.version++; - instance.modifiedFiles[filePath] = file; - } - }); - cb(); - }); + loader._compiler.plugin("after-compile", afterCompile(instance, compiler, servicesHost, configFilePath)); + loader._compiler.plugin("watch-run", watchRun(instance)); return { instance }; } diff --git a/src/logger.ts b/src/logger.ts index c8325126b..b5a1d1f31 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -10,43 +10,54 @@ enum LogLevel { ERROR = 3 } -interface Logger { +interface InternalLoggerFunc { (whereToLog: any, messages: string[]): void } const doNothingLogger = (...messages: string[]) => {}; -function makeLogger(loaderOptions: interfaces.LoaderOptions) { +function makeLoggerFunc(loaderOptions: interfaces.LoaderOptions) { return loaderOptions.silent ? (whereToLog: any, messages: string[]) => {} : (whereToLog: any, messages: string[]) => console.log.apply(whereToLog, messages); } -function makeExternalLogger(loaderOptions: interfaces.LoaderOptions, logger: Logger) { +function makeExternalLogger(loaderOptions: interfaces.LoaderOptions, logger: InternalLoggerFunc) { const output = loaderOptions.logInfoToStdOut ? stdoutConsole : stderrConsole; return (...messages: string[]) => logger(output, messages); } -function makeLogInfo(loaderOptions: interfaces.LoaderOptions, logger: Logger) { +function makeLogInfo(loaderOptions: interfaces.LoaderOptions, logger: InternalLoggerFunc) { return LogLevel[loaderOptions.logLevel] <= LogLevel.INFO ? (...messages: string[]) => logger(loaderOptions.logInfoToStdOut ? stdoutConsole : stderrConsole, messages) : doNothingLogger } -function makeLogError(loaderOptions: interfaces.LoaderOptions, logger: Logger) { +function makeLogError(loaderOptions: interfaces.LoaderOptions, logger: InternalLoggerFunc) { return LogLevel[loaderOptions.logLevel] <= LogLevel.ERROR ? (...messages: string[]) => logger(stderrConsole, messages) : doNothingLogger } -function makeLogWarning(loaderOptions: interfaces.LoaderOptions, logger: Logger) { +function makeLogWarning(loaderOptions: interfaces.LoaderOptions, logger: InternalLoggerFunc) { return LogLevel[loaderOptions.logLevel] <= LogLevel.WARN ? (...messages: string[]) => logger(stderrConsole, messages) : doNothingLogger } -function getLogger(loaderOptions: interfaces.LoaderOptions) { - const logger = makeLogger(loaderOptions); +interface LoggerFunc { + (...messages: string[]): void +} + +export interface Logger { + log: LoggerFunc; + logInfo: LoggerFunc; + logWarning: LoggerFunc; + logError: LoggerFunc; +} + +export function makeLogger(loaderOptions: interfaces.LoaderOptions): Logger { + const logger = makeLoggerFunc(loaderOptions); return { log: makeExternalLogger(loaderOptions, logger), logInfo: makeLogInfo(loaderOptions, logger), @@ -54,5 +65,3 @@ function getLogger(loaderOptions: interfaces.LoaderOptions) { logError: makeLogError(loaderOptions, logger) } } - -export = getLogger; \ No newline at end of file diff --git a/src/servicesHost.ts b/src/servicesHost.ts new file mode 100644 index 000000000..d91854570 --- /dev/null +++ b/src/servicesHost.ts @@ -0,0 +1,118 @@ +import typescript = require('typescript'); +import constants = require('./constants'); +import interfaces = require('./interfaces'); +import logger = require('./logger'); +import path = require('path'); +import makeResolver = require('./resolver'); +import utils = require('./utils'); + +/** + * Create the TypeScript language service + */ +function makeServicesHost( + files: interfaces.TSFiles, + scriptRegex: RegExp, + log: logger.Logger, + loader: any, //TODO: not any + compilerOptions: typescript.CompilerOptions, + instance: interfaces.TSInstance, + compiler: typeof typescript, + configFilePath: string +) { + const newLine = + compilerOptions.newLine === 0 /* CarriageReturnLineFeed */ ? constants.CarriageReturnLineFeed : + compilerOptions.newLine === 1 /* LineFeed */ ? constants.LineFeed : + constants.EOL; + + // make a (sync) resolver that follows webpack's rules + const resolver = makeResolver(loader.options); + + const moduleResolutionHost = { + fileExists: (fileName: string) => utils.readFile(fileName) !== undefined, + readFile: (fileName: string) => utils.readFile(fileName), + }; + + return { + getProjectVersion: () => `${instance.version}`, + getScriptFileNames: () => Object.keys(files).filter(filePath => scriptRegex.test(filePath)), + getScriptVersion: (fileName: string) => { + fileName = path.normalize(fileName); + return files[fileName] && files[fileName].version.toString(); + }, + getScriptSnapshot: (fileName: string) => { + // This is called any time TypeScript needs a file's text + // We either load from memory or from disk + fileName = path.normalize(fileName); + let file = files[fileName]; + + if (!file) { + let text = utils.readFile(fileName); + if (!text) { return; } + + file = files[fileName] = { version: 0, text }; + } + + return compiler.ScriptSnapshot.fromString(file.text); + }, + /** + * getDirectories is also required for full import and type reference completions. + * Without it defined, certain completions will not be provided + */ + getDirectories: typescript.sys ? (typescript.sys).getDirectories : undefined, + + /** + * For @types expansion, these two functions are needed. + */ + directoryExists: typescript.sys ? (typescript.sys).directoryExists : undefined, + getCurrentDirectory: () => process.cwd(), + + getCompilationSettings: () => compilerOptions, + getDefaultLibFileName: (options: typescript.CompilerOptions) => compiler.getDefaultLibFilePath(options), + getNewLine: () => newLine, + log: log.log, + resolveModuleNames: (moduleNames: string[], containingFile: string) => { + let resolvedModules: interfaces.ResolvedModule[] = []; + + for (let moduleName of moduleNames) { + let resolvedFileName: string; + let resolutionResult: any; + + try { + resolvedFileName = resolver.resolveSync(path.normalize(path.dirname(containingFile)), moduleName); + + if (!resolvedFileName.match(scriptRegex)) resolvedFileName = null; + else resolutionResult = { resolvedFileName }; + } + catch (e) { resolvedFileName = null; } + + let tsResolution = compiler.resolveModuleName(moduleName, containingFile, compilerOptions, moduleResolutionHost); + + if (tsResolution.resolvedModule) { + if (resolvedFileName) { + if (resolvedFileName === tsResolution.resolvedModule.resolvedFileName) { + resolutionResult.isExternalLibraryImport = tsResolution.resolvedModule.isExternalLibraryImport; + } + } + else resolutionResult = tsResolution.resolvedModule; + } + + resolvedModules.push(resolutionResult); + } + + const importedFiles = resolvedModules + .filter(m => m !== null && m !== undefined) + .map(m => m.resolvedFileName); + instance.dependencyGraph[path.normalize(containingFile)] = importedFiles; + importedFiles.forEach(importedFileName => { + if (!instance.reverseDependencyGraph[importedFileName]) { + instance.reverseDependencyGraph[importedFileName] = {}; + } + instance.reverseDependencyGraph[importedFileName][path.normalize(containingFile)] = true; + }); + + return resolvedModules; + }, + }; +} + +export = makeServicesHost; \ No newline at end of file diff --git a/src/watch-run.ts b/src/watch-run.ts new file mode 100644 index 000000000..35d828c5c --- /dev/null +++ b/src/watch-run.ts @@ -0,0 +1,34 @@ +import path = require('path'); +import utils = require('./utils'); +import interfaces = require('./interfaces'); + +/** + * Make function which will manually update changed files + */ +function makeWatchRun( + instance: interfaces.TSInstance +) { + + return (watching: interfaces.WebpackWatching, cb: () => void) => { + const mtimes = watching.compiler.watchFileSystem.watcher.mtimes; + if (null === instance.modifiedFiles) { + instance.modifiedFiles = {}; + } + + Object.keys(mtimes) + .filter(filePath => !!filePath.match(/\.tsx?$|\.jsx?$/)) + .forEach(filePath => { + filePath = path.normalize(filePath); + const file = instance.files[filePath]; + if (file) { + file.text = utils.readFile(filePath) || ''; + file.version++; + instance.version++; + instance.modifiedFiles[filePath] = file; + } + }); + cb(); + }; +} + +export = makeWatchRun; \ No newline at end of file From 53b5782ca017359a0978734fe502ef3702a059bf Mon Sep 17 00:00:00 2001 From: John Reilly Date: Tue, 25 Oct 2016 23:31:30 +0100 Subject: [PATCH 16/17] fix up --- test/execution-tests/simpleDependency/tsconfig.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/execution-tests/simpleDependency/tsconfig.json b/test/execution-tests/simpleDependency/tsconfig.json index 0efa0a638..fc16344c1 100644 --- a/test/execution-tests/simpleDependency/tsconfig.json +++ b/test/execution-tests/simpleDependency/tsconfig.json @@ -1,4 +1,5 @@ { "compilerOptions": { - } + }, + "files": [] } \ No newline at end of file From a03486e18761d89d996009635b021b4becf46588 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Wed, 26 Oct 2016 00:24:32 +0100 Subject: [PATCH 17/17] split get config file out --- src/config.ts | 92 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/index.ts | 74 +++++++---------------------------------- 2 files changed, 104 insertions(+), 62 deletions(-) create mode 100644 src/config.ts diff --git a/src/config.ts b/src/config.ts new file mode 100644 index 000000000..d18282cde --- /dev/null +++ b/src/config.ts @@ -0,0 +1,92 @@ +import objectAssign = require('object-assign'); +import typescript = require('typescript'); +import path = require('path'); + +import interfaces = require('./interfaces'); +import logger = require('./logger'); +import utils = require('./utils'); + +interface ConfigFile { + config?: any; + error?: typescript.Diagnostic; +} + +function getConfigFile( + compiler: typeof typescript, + loader: any, + loaderOptions: interfaces.LoaderOptions, + compilerCompatible: boolean, + log: logger.Logger, + compilerDetailsLogMessage: string, + instance: interfaces.TSInstance +) { + const configFilePath = findConfigFile(compiler, path.dirname(loader.resourcePath), loaderOptions.configFileName); + let configFileError: interfaces.WebpackError; + let configFile: ConfigFile; + + if (configFilePath) { + if (compilerCompatible) { + log.logInfo(`${compilerDetailsLogMessage} and ${configFilePath}`.green); + } else { + log.logInfo(`ts-loader: Using config file at ${configFilePath}`.green); + } + + // HACK: relies on the fact that passing an extra argument won't break + // the old API that has a single parameter + configFile = (compiler).readConfigFile( + configFilePath, + compiler.sys.readFile + ); + + if (configFile.error) { + configFileError = utils.formatErrors([configFile.error], instance, { file: configFilePath })[0]; + } + } else { + if (compilerCompatible) { log.logInfo(compilerDetailsLogMessage.green); } + + configFile = { + config: { + compilerOptions: {}, + files: [], + }, + }; + } + + if (!configFileError) { + configFile.config.compilerOptions = objectAssign({}, + configFile.config.compilerOptions, + loaderOptions.compilerOptions); + + // do any necessary config massaging + if (loaderOptions.transpileOnly) { + configFile.config.compilerOptions.isolatedModules = true; + } + } + + return { + configFilePath, + configFile, + configFileError + }; +} + +/** + * The tsconfig.json is found using the same method as `tsc`, starting in the current directory + * and continuing up the parent directory chain. + */ +function findConfigFile(compiler: typeof typescript, searchPath: string, configFileName: string): string { + while (true) { + const fileName = path.join(searchPath, configFileName); + if (compiler.sys.fileExists(fileName)) { + return fileName; + } + const parentPath = path.dirname(searchPath); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + } + return undefined; +} + +export = getConfigFile; \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 1bc13c9c7..dd8e83346 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,6 +8,7 @@ const semver = require('semver'); require('colors'); import afterCompile = require('./after-compile'); +import getConfigFile = require('./config'); import interfaces = require('./interfaces'); import constants = require('./constants'); import utils = require('./utils'); @@ -19,25 +20,6 @@ let instances = {}; let webpackInstances: any = []; let scriptRegex = /\.tsx?$/i; -/** - * The tsconfig.json is found using the same method as `tsc`, starting in the current directory - * and continuing up the parent directory chain. - */ -function findConfigFile(compiler: typeof typescript, searchPath: string, configFileName: string): string { - while (true) { - const fileName = path.join(searchPath, configFileName); - if (compiler.sys.fileExists(fileName)) { - return fileName; - } - const parentPath = path.dirname(searchPath); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; - } - return undefined; -} - /** * The loader is executed once for each file seen by webpack. However, we need to keep * a persistent instance of TypeScript that contains all of the files in the program @@ -65,17 +47,17 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade } const log = logger.makeLogger(loaderOptions); - const motd = `ts-loader: Using ${loaderOptions.compiler}@${compiler.version}`; + const compilerDetailsLogMessage = `ts-loader: Using ${loaderOptions.compiler}@${compiler.version}`; let compilerCompatible = false; if (loaderOptions.compiler === 'typescript') { if (compiler.version && semver.gte(compiler.version, '1.6.2-0')) { // don't log yet in this case, if a tsconfig.json exists we want to combine the message compilerCompatible = true; } else { - log.logError(`${motd}. This version is incompatible with ts-loader. Please upgrade to the latest version of TypeScript.`.red); + log.logError(`${compilerDetailsLogMessage}. This version is incompatible with ts-loader. Please upgrade to the latest version of TypeScript.`.red); } } else { - log.logWarning(`${motd}. This version may or may not be compatible with ts-loader.`.yellow); + log.logWarning(`${compilerDetailsLogMessage}. This version may or may not be compatible with ts-loader.`.yellow); } const files: interfaces.TSFiles = {}; @@ -98,47 +80,15 @@ function ensureTypeScriptInstance(loaderOptions: interfaces.LoaderOptions, loade // Load any available tsconfig.json file let filesToLoad: string[] = []; - const configFilePath = findConfigFile(compiler, path.dirname(loader.resourcePath), loaderOptions.configFileName); - let configFile: { - config?: any; - error?: typescript.Diagnostic; - }; - if (configFilePath) { - if (compilerCompatible) { - log.logInfo(`${motd} and ${configFilePath}`.green); - } else { - log.logInfo(`ts-loader: Using config file at ${configFilePath}`.green); - } - - // HACK: relies on the fact that passing an extra argument won't break - // the old API that has a single parameter - configFile = ( compiler).readConfigFile( - configFilePath, - compiler.sys.readFile - ); - if (configFile.error) { - const configFileError = utils.formatErrors([configFile.error], instance, {file: configFilePath })[0]; - return { error: configFileError }; - } - } else { - if (compilerCompatible) { log.logInfo(motd.green); } - - configFile = { - config: { - compilerOptions: {}, - files: [], - }, - }; - } - - configFile.config.compilerOptions = objectAssign({}, - configFile.config.compilerOptions, - loaderOptions.compilerOptions); - - // do any necessary config massaging - if (loaderOptions.transpileOnly) { - configFile.config.compilerOptions.isolatedModules = true; + const { + configFilePath, + configFile, + configFileError + } = getConfigFile(compiler, loader, loaderOptions, compilerCompatible, log, compilerDetailsLogMessage, instance); + + if (configFileError) { + return { error: configFileError }; } // if allowJs is set then we should accept js(x) files